From e5a381b3d37c173b17986a11c9431f495924cb8f Mon Sep 17 00:00:00 2001 From: Jeff Handley Date: Fri, 19 Dec 2025 16:30:29 -0800 Subject: [PATCH 1/6] Set branding to 10.1.2 --- eng/Versions.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/eng/Versions.props b/eng/Versions.props index 5c3ea3f8b74..9c7e29f64f9 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -2,7 +2,7 @@ 10 1 - 1 + 2 preview 1 $(MajorVersion).$(MinorVersion).$(PatchVersion) From 1f69937cfa493bef8dc7027342178cdd19bb0bee Mon Sep 17 00:00:00 2001 From: Jeff Handley Date: Thu, 18 Dec 2025 22:29:05 -0800 Subject: [PATCH 2/6] Overhaul project template builds and testing (#7113) * Remove project template snapshots * Overhaul project template builds and testing * Add back project template snapshots after testing overhaul * Remove project template snapshots * Overhaul project template builds and testing, approach 2 * Add back project template snapshots * Fix tools vs. tests package version imports * Use full package names for all template PackageVersion references * Improve MSBuild integration for getting project package versions * Fix build/clean properties for project template artifacts paths * Address PR feedback 1. Remove unused AllowExplicitReference property on PackageReference 2. Remove SetTargetFramework to avoid possible unintended side effects 3. Simplify how the replacement properties are passed in for template content Also tighten up the Snapshot test AddPackageReferenceScrubber helper to ensure it only replaces version strings so that bugs in the MSBuild replacement logic that produce unexpected replacement strings do not get matched. This ensures the Snapshot tests fail if the version replacement logic is broken. As part of that, the scrubber helpers were moved into the VerifyScrubbers.cs file. --- bench/Directory.Build.props | 2 - bench/Directory.Packages.props | 6 + eng/MSBuild/Packaging.targets | 20 +- eng/Tools/Directory.Packages.props | 6 + eng/build.proj | 8 +- eng/packages/General.props | 12 +- eng/packages/ProjectTemplates.props | 38 + eng/packages/{TestOnly.props => Tests.props} | 20 +- eng/packages/Tools.props | 8 + ...icrosoft.Extensions.AI.Abstractions.csproj | 2 +- .../Microsoft.Extensions.AI.OpenAI.csproj | 2 +- .../Microsoft.Extensions.AI.csproj | 2 +- ...sions.ServiceDiscovery.Abstractions.csproj | 2 +- ...crosoft.Extensions.ServiceDiscovery.csproj | 2 +- src/Packages/Directory.Build.props | 2 +- src/ProjectTemplates/.gitignore | 22 +- src/ProjectTemplates/Directory.Build.props | 10 + src/ProjectTemplates/Directory.Build.targets | 109 + src/ProjectTemplates/Directory.Packages.props | 6 + .../GenerateTemplateContent.csproj | 95 - src/ProjectTemplates/GeneratedContent.targets | 132 - ...icrosoft.Agents.AI.ProjectTemplates.csproj | 42 +- .../.template.config/dotnetcli.host.json | 0 .../.template.config/ide.host.json | 0 .../.template.config/ide/agent-framework.ico | Bin .../.template.config/template.json | 12 +- .../AIAgentWebApi-CSharp.csproj-in} | 16 +- .../AIAgentWebApi-CSharp}/Program.cs | 0 .../Properties/launchSettings.json | 4 +- .../AIAgentWebApi-CSharp}/README.md | 4 +- .../AIAgentWebApi-CSharp}/appsettings.json | 0 .../Microsoft.Extensions.AI.Templates.csproj | 79 +- .../package.json | 10 +- .../Directory.Build.targets.in | 21 - .../Directory.Build.props.in | 5 - .../Directory.Build.targets.in | 15 - .../src/ChatWithCustomData/NuGet.config.in | 25 - .../.template.config/dotnetcli.host.json | 0 .../.template.config/ide.host.json | 0 .../.template.config/ide/icon.ico | Bin .../.template.config/template.json | 40 +- .../AIChatWeb-CSharp.AppHost.csproj-in} | 14 +- .../AIChatWeb-CSharp.AppHost}/AppHost.cs | 2 +- .../Properties/launchSettings.json | 0 .../appsettings.Development.json | 0 .../appsettings.json | 0 ...IChatWeb-CSharp.ServiceDefaults.csproj-in} | 14 +- .../Extensions.cs | 0 .../AIChatWeb-CSharp.Web.csproj-in} | 48 +- .../Components/App.razor | 2 +- .../Components/Layout/LoadingSpinner.razor | 0 .../Layout/LoadingSpinner.razor.css | 0 .../Components/Layout/MainLayout.razor | 0 .../Components/Layout/MainLayout.razor.css | 0 .../Components/Layout/SurveyPrompt.razor | 0 .../Components/Layout/SurveyPrompt.razor.css | 0 .../Components/Pages/Chat/Chat.razor | 0 .../Components/Pages/Chat/Chat.razor.css | 0 .../Components/Pages/Chat/ChatCitation.razor | 0 .../Pages/Chat/ChatCitation.razor.css | 0 .../Components/Pages/Chat/ChatHeader.razor | 2 +- .../Pages/Chat/ChatHeader.razor.css | 0 .../Components/Pages/Chat/ChatInput.razor | 0 .../Components/Pages/Chat/ChatInput.razor.css | 0 .../Components/Pages/Chat/ChatInput.razor.js | 0 .../Pages/Chat/ChatMessageItem.razor | 0 .../Pages/Chat/ChatMessageItem.razor.css | 0 .../Pages/Chat/ChatMessageList.razor | 0 .../Pages/Chat/ChatMessageList.razor.css | 0 .../Pages/Chat/ChatMessageList.razor.js | 0 .../Pages/Chat/ChatSuggestions.razor | 0 .../Pages/Chat/ChatSuggestions.razor.css | 0 .../Components/Pages/Error.razor | 0 .../Components/Routes.razor | 0 .../Components/_Imports.razor | 8 +- .../OllamaResilienceHandlerExtensions.cs | 3 +- .../AIChatWeb-CSharp.Web}/Program.Aspire.cs | 6 +- .../AIChatWeb-CSharp.Web}/Program.cs | 6 +- .../Properties/launchSettings.json | 0 .../AIChatWeb-CSharp.Web}/README.md | 2 +- .../Services/IngestedChunk.cs | 4 +- .../Services/Ingestion/DataIngestor.cs | 2 +- .../Services/Ingestion/DocumentReader.cs | 2 +- .../Services/Ingestion/PdfPigReader.cs | 2 +- .../Services/SemanticSearch.cs | 4 +- .../appsettings.Development.json | 0 .../AIChatWeb-CSharp.Web}/appsettings.json | 0 .../Data/Example_Emergency_Survival_Kit.pdf | Bin .../wwwroot/Data/Example_GPS_Watch.md | 0 .../AIChatWeb-CSharp.Web}/wwwroot/app.css | 0 .../AIChatWeb-CSharp.Web}/wwwroot/app.js | 0 .../AIChatWeb-CSharp.Web}/wwwroot/favicon.ico | Bin .../wwwroot/lib/dompurify/README.md | 0 .../wwwroot/lib/dompurify/dist/purify.es.mjs | 0 .../wwwroot/lib/markdown_viewer/viewer.html | 0 .../wwwroot/lib/markdown_viewer/viewer.mjs | 0 .../wwwroot/lib/marked/README.md | 0 .../wwwroot/lib/marked/dist/marked.esm.js | 0 .../wwwroot/lib/pdf_viewer/viewer.html | 0 .../wwwroot/lib/pdf_viewer/viewer.mjs | 0 .../wwwroot/lib/pdfjs-dist/README.md | 0 .../lib/pdfjs-dist/dist/build/pdf.min.mjs | 0 .../pdfjs-dist/dist/build/pdf.worker.min.mjs | 0 .../dist/web/images/loading-icon.gif | Bin .../lib/pdfjs-dist/dist/web/pdf_viewer.css | 0 .../lib/pdfjs-dist/dist/web/pdf_viewer.mjs | 0 .../wwwroot/lib/tailwindcss/README.md | 0 .../lib/tailwindcss/dist/preflight.css | 0 .../AIChatWeb-CSharp/AIChatWeb-CSharp.sln} | 6 +- .../AIChatWeb-CSharp}/README.Aspire.md | 12 +- .../McpServer-CSharp/.mcp/server.json | 0 .../.template.config/dotnetcli.host.json | 0 .../.template.config/ide.host.json | 0 .../.template.config/ide/icon.ico | Bin .../.template.config/template.json | 0 .../McpServer-CSharp.csproj-in} | 4 +- .../McpServer-CSharp/Program.cs | 0 .../McpServer-CSharp/README.md | 0 .../Tools/RandomNumberTools.cs | 0 src/ProjectTemplates/README.md | 122 +- test/Directory.Build.props | 4 +- test/Directory.Build.targets | 4 - test/Directory.Packages.props | 6 + test/ProjectTemplates/.gitignore | 1 - .../TemplateExecutionTestBase.cs | 13 + .../TemplateExecutionTestClassFixtureBase.cs | 90 +- .../TemplateExecutionTestCollection.cs | 2 +- .../TemplateExecutionTestCollectionFixture.cs | 39 - .../TemplateExecutionTestConfiguration.cs | 7 +- .../Infrastructure/TemplateSandbox/README.md | 7 +- .../nuget.config} | 0 .../{ => projects}/Directory.Build.props | 0 .../{ => projects}/Directory.Build.targets | 0 .../nuget.config} | 0 .../TemplateSnapshotTestBase.cs | 53 + .../Infrastructure/TemplateTestUtilities.cs | 95 + .../Infrastructure/VerifyScrubbers.cs | 45 + .../Infrastructure/WellKnownPaths.cs | 30 +- .../AIAgentWebAPIExecutionTests.cs | 65 + .../AIAgentWebAPISnapshotTests.cs | 51 + ...ft.Agents.AI.ProjectTemplates.Tests.csproj | 6 - .../ProjectRootHelper.cs | 35 - .../Snapshots/README.md | 5 - .../aiagent-webapi/README.md | 129 - .../aiagent-webapi/Program.cs | 64 - .../Properties/launchSettings.json | 25 - .../Properties/launchSettings.json | 25 - .../aiagent-webapi/aiagent-webapi.csproj | 19 - .../aiagent-webapi/appsettings.json | 9 - .../aiagent-webapi/Program.cs | 0 .../Properties/launchSettings.json | 4 +- .../aiagent-webapi/README.md | 4 +- .../aiagent-webapi/aiagent-webapi.csproj | 14 +- .../aiagent-webapi/appsettings.json | 0 .../aiagent-webapi/Program.cs | 0 .../Properties/launchSettings.json | 4 +- .../aiagent-webapi/README.md | 4 +- .../aiagent-webapi/aiagent-webapi.csproj | 14 +- .../aiagent-webapi/appsettings.json | 0 .../aiagent-webapi/Program.cs | 0 .../Properties/launchSettings.json | 4 +- .../aiagent-webapi/README.md | 4 +- .../aiagent-webapi/aiagent-webapi.csproj | 16 +- .../aiagent-webapi/appsettings.json | 0 .../aiagent-webapi/Program.cs | 0 .../Properties/launchSettings.json | 4 +- .../aiagent-webapi/README.md | 8 +- .../aiagent-webapi/aiagent-webapi.csproj | 14 +- .../aiagent-webapi/appsettings.json | 0 .../aiagent-webapi/Program.cs | 0 .../Properties/launchSettings.json | 25 + .../aiagent-webapi/README.md | 4 +- .../aiagent-webapi/aiagent-webapi.csproj | 14 +- .../aiagent-webapi/appsettings.json | 0 .../WebApiAgentTemplateExecutionTests.cs | 123 - .../WebApiAgentTemplateSnapshotTests.cs | 139 - .../AIChatWebExecutionTests.cs | 214 +- .../AIChatWebSnapshotTests.cs | 132 +- .../McpServerExecutionTests.cs | 56 + .../McpServerSnapshotTests.cs | 101 +- ...osoft.Extensions.AI.Templates.Tests.csproj | 3 - .../ProjectRootHelper.cs | 35 - .../Data/Example_Emergency_Survival_Kit.pdf | Bin 153539 -> 0 bytes .../wwwroot/Data/Example_GPS_Watch.md | 193 - .../aichatweb/aichatweb.Web/wwwroot/app.css | 94 - .../aichatweb/aichatweb.Web/wwwroot/app.js | 24 - .../aichatweb.Web/wwwroot/favicon.ico | Bin 13126 -> 0 bytes .../wwwroot/lib/dompurify/README.md | 5 - .../wwwroot/lib/dompurify/dist/purify.es.mjs | 1338 --- .../wwwroot/lib/markdown_viewer/viewer.html | 32 - .../wwwroot/lib/markdown_viewer/viewer.mjs | 13 - .../wwwroot/lib/marked/README.md | 5 - .../wwwroot/lib/marked/dist/marked.esm.js | 2568 ----- .../wwwroot/lib/pdf_viewer/viewer.html | 31 - .../wwwroot/lib/pdf_viewer/viewer.mjs | 62 - .../wwwroot/lib/pdfjs-dist/README.md | 10 - .../lib/pdfjs-dist/dist/build/pdf.min.mjs | 21 - .../pdfjs-dist/dist/build/pdf.worker.min.mjs | 21 - .../dist/web/images/loading-icon.gif | Bin 2545 -> 0 bytes .../lib/pdfjs-dist/dist/web/pdf_viewer.css | 3274 ------- .../lib/pdfjs-dist/dist/web/pdf_viewer.mjs | 8435 ----------------- .../wwwroot/lib/tailwindcss/README.md | 7 - .../lib/tailwindcss/dist/preflight.css | 383 - .../Data/Example_Emergency_Survival_Kit.pdf | Bin 153539 -> 0 bytes .../wwwroot/Data/Example_GPS_Watch.md | 193 - .../aichatweb/wwwroot/app.css | 94 - .../aichatweb/wwwroot/app.js | 24 - .../aichatweb/wwwroot/favicon.ico | Bin 13126 -> 0 bytes .../aichatweb/wwwroot/lib/dompurify/README.md | 5 - .../wwwroot/lib/dompurify/dist/purify.es.mjs | 1338 --- .../wwwroot/lib/markdown_viewer/viewer.html | 32 - .../wwwroot/lib/markdown_viewer/viewer.mjs | 13 - .../aichatweb/wwwroot/lib/marked/README.md | 5 - .../wwwroot/lib/marked/dist/marked.esm.js | 2568 ----- .../wwwroot/lib/pdf_viewer/viewer.html | 31 - .../wwwroot/lib/pdf_viewer/viewer.mjs | 62 - .../wwwroot/lib/pdfjs-dist/README.md | 10 - .../lib/pdfjs-dist/dist/build/pdf.min.mjs | 21 - .../pdfjs-dist/dist/build/pdf.worker.min.mjs | 21 - .../dist/web/images/loading-icon.gif | Bin 2545 -> 0 bytes .../lib/pdfjs-dist/dist/web/pdf_viewer.css | 3274 ------- .../lib/pdfjs-dist/dist/web/pdf_viewer.mjs | 8435 ----------------- .../wwwroot/lib/tailwindcss/README.md | 7 - .../lib/tailwindcss/dist/preflight.css | 383 - .../Data/Example_Emergency_Survival_Kit.pdf | Bin 153539 -> 0 bytes .../wwwroot/Data/Example_GPS_Watch.md | 193 - .../aichatweb/aichatweb.Web/wwwroot/app.css | 94 - .../aichatweb/aichatweb.Web/wwwroot/app.js | 24 - .../aichatweb.Web/wwwroot/favicon.ico | Bin 13126 -> 0 bytes .../wwwroot/lib/dompurify/README.md | 5 - .../wwwroot/lib/dompurify/dist/purify.es.mjs | 1338 --- .../wwwroot/lib/markdown_viewer/viewer.html | 32 - .../wwwroot/lib/markdown_viewer/viewer.mjs | 13 - .../wwwroot/lib/marked/README.md | 5 - .../wwwroot/lib/marked/dist/marked.esm.js | 2568 ----- .../wwwroot/lib/pdf_viewer/viewer.html | 31 - .../wwwroot/lib/pdf_viewer/viewer.mjs | 62 - .../wwwroot/lib/pdfjs-dist/README.md | 10 - .../lib/pdfjs-dist/dist/build/pdf.min.mjs | 21 - .../pdfjs-dist/dist/build/pdf.worker.min.mjs | 21 - .../dist/web/images/loading-icon.gif | Bin 2545 -> 0 bytes .../lib/pdfjs-dist/dist/web/pdf_viewer.css | 3274 ------- .../lib/pdfjs-dist/dist/web/pdf_viewer.mjs | 8435 ----------------- .../wwwroot/lib/tailwindcss/README.md | 7 - .../lib/tailwindcss/dist/preflight.css | 383 - .../Data/Example_Emergency_Survival_Kit.pdf | Bin 153539 -> 0 bytes .../wwwroot/Data/Example_GPS_Watch.md | 193 - .../aichatweb/aichatweb.Web/wwwroot/app.css | 94 - .../aichatweb/aichatweb.Web/wwwroot/app.js | 24 - .../aichatweb.Web/wwwroot/favicon.ico | Bin 13126 -> 0 bytes .../wwwroot/lib/dompurify/README.md | 5 - .../wwwroot/lib/dompurify/dist/purify.es.mjs | 1338 --- .../wwwroot/lib/markdown_viewer/viewer.html | 32 - .../wwwroot/lib/markdown_viewer/viewer.mjs | 13 - .../wwwroot/lib/marked/README.md | 5 - .../wwwroot/lib/marked/dist/marked.esm.js | 2568 ----- .../wwwroot/lib/pdf_viewer/viewer.html | 31 - .../wwwroot/lib/pdf_viewer/viewer.mjs | 62 - .../wwwroot/lib/pdfjs-dist/README.md | 10 - .../lib/pdfjs-dist/dist/build/pdf.min.mjs | 21 - .../pdfjs-dist/dist/build/pdf.worker.min.mjs | 21 - .../dist/web/images/loading-icon.gif | Bin 2545 -> 0 bytes .../lib/pdfjs-dist/dist/web/pdf_viewer.css | 3274 ------- .../lib/pdfjs-dist/dist/web/pdf_viewer.mjs | 8435 ----------------- .../wwwroot/lib/tailwindcss/README.md | 7 - .../lib/tailwindcss/dist/preflight.css | 383 - .../aichatweb/Properties/launchSettings.json | 23 - .../Data/Example_Emergency_Survival_Kit.pdf | Bin 153539 -> 0 bytes .../wwwroot/Data/Example_GPS_Watch.md | 193 - .../aichatweb/wwwroot/app.css | 94 - .../aichatweb/wwwroot/app.js | 24 - .../aichatweb/wwwroot/favicon.ico | Bin 13126 -> 0 bytes .../aichatweb/wwwroot/lib/dompurify/README.md | 5 - .../wwwroot/lib/dompurify/dist/purify.es.mjs | 1338 --- .../wwwroot/lib/markdown_viewer/viewer.html | 32 - .../wwwroot/lib/markdown_viewer/viewer.mjs | 13 - .../aichatweb/wwwroot/lib/marked/README.md | 5 - .../wwwroot/lib/marked/dist/marked.esm.js | 2568 ----- .../wwwroot/lib/pdf_viewer/viewer.html | 31 - .../wwwroot/lib/pdf_viewer/viewer.mjs | 62 - .../wwwroot/lib/pdfjs-dist/README.md | 10 - .../lib/pdfjs-dist/dist/build/pdf.min.mjs | 21 - .../pdfjs-dist/dist/build/pdf.worker.min.mjs | 21 - .../dist/web/images/loading-icon.gif | Bin 2545 -> 0 bytes .../lib/pdfjs-dist/dist/web/pdf_viewer.css | 3274 ------- .../lib/pdfjs-dist/dist/web/pdf_viewer.mjs | 8435 ----------------- .../wwwroot/lib/tailwindcss/README.md | 7 - .../lib/tailwindcss/dist/preflight.css | 383 - .../aichatweb.A.verified}/aichatweb/README.md | 0 .../aichatweb/aichatweb.AppHost/AppHost.cs | 0 .../Properties/launchSettings.json | 12 +- .../aichatweb.AppHost.csproj | 4 +- .../appsettings.Development.json | 0 .../aichatweb.AppHost/appsettings.json | 0 .../aichatweb.ServiceDefaults/Extensions.cs | 0 .../aichatweb.ServiceDefaults.csproj | 14 +- .../aichatweb.Web/Components/App.razor | 0 .../Components/Layout/LoadingSpinner.razor | 0 .../Layout/LoadingSpinner.razor.css | 0 .../Components/Layout/MainLayout.razor | 0 .../Components/Layout/MainLayout.razor.css | 0 .../Components/Layout/SurveyPrompt.razor | 0 .../Components/Layout/SurveyPrompt.razor.css | 0 .../Components/Pages/Chat/Chat.razor | 0 .../Components/Pages/Chat/Chat.razor.css | 0 .../Components/Pages/Chat/ChatCitation.razor | 0 .../Pages/Chat/ChatCitation.razor.css | 0 .../Components/Pages/Chat/ChatHeader.razor | 0 .../Pages/Chat/ChatHeader.razor.css | 0 .../Components/Pages/Chat/ChatInput.razor | 0 .../Components/Pages/Chat/ChatInput.razor.css | 0 .../Components/Pages/Chat/ChatInput.razor.js | 0 .../Pages/Chat/ChatMessageItem.razor | 0 .../Pages/Chat/ChatMessageItem.razor.css | 0 .../Pages/Chat/ChatMessageList.razor | 0 .../Pages/Chat/ChatMessageList.razor.css | 0 .../Pages/Chat/ChatMessageList.razor.js | 0 .../Pages/Chat/ChatSuggestions.razor | 0 .../Pages/Chat/ChatSuggestions.razor.css | 0 .../Components/Pages/Error.razor | 0 .../aichatweb.Web/Components/Routes.razor | 0 .../aichatweb.Web/Components/_Imports.razor | 0 .../aichatweb/aichatweb.Web/Program.cs | 0 .../Properties/launchSettings.json | 4 +- .../aichatweb.Web/Services/IngestedChunk.cs | 0 .../Services/Ingestion/DataIngestor.cs | 0 .../Services/Ingestion/DocumentReader.cs | 0 .../aichatweb.Web/Services/SemanticSearch.cs | 0 .../aichatweb.Web/aichatweb.Web.csproj | 20 +- .../appsettings.Development.json | 0 .../aichatweb/aichatweb.Web/appsettings.json | 0 .../aichatweb/aichatweb.sln | 0 .../aichatweb/README.md | 0 .../aichatweb/aichatweb.AppHost/AppHost.cs | 0 .../Properties/launchSettings.json | 12 +- .../aichatweb.AppHost.csproj | 8 +- .../appsettings.Development.json | 0 .../aichatweb.AppHost/appsettings.json | 0 .../aichatweb.ServiceDefaults/Extensions.cs | 0 .../aichatweb.ServiceDefaults.csproj | 14 +- .../aichatweb.Web/Components/App.razor | 0 .../Components/Layout/LoadingSpinner.razor | 0 .../Layout/LoadingSpinner.razor.css | 0 .../Components/Layout/MainLayout.razor | 0 .../Components/Layout/MainLayout.razor.css | 0 .../Components/Layout/SurveyPrompt.razor | 0 .../Components/Layout/SurveyPrompt.razor.css | 0 .../Components/Pages/Chat/Chat.razor | 0 .../Components/Pages/Chat/Chat.razor.css | 0 .../Components/Pages/Chat/ChatCitation.razor | 0 .../Pages/Chat/ChatCitation.razor.css | 0 .../Components/Pages/Chat/ChatHeader.razor | 0 .../Pages/Chat/ChatHeader.razor.css | 0 .../Components/Pages/Chat/ChatInput.razor | 0 .../Components/Pages/Chat/ChatInput.razor.css | 0 .../Components/Pages/Chat/ChatInput.razor.js | 0 .../Pages/Chat/ChatMessageItem.razor | 0 .../Pages/Chat/ChatMessageItem.razor.css | 0 .../Pages/Chat/ChatMessageList.razor | 0 .../Pages/Chat/ChatMessageList.razor.css | 0 .../Pages/Chat/ChatMessageList.razor.js | 0 .../Pages/Chat/ChatSuggestions.razor | 0 .../Pages/Chat/ChatSuggestions.razor.css | 0 .../Components/Pages/Error.razor | 0 .../aichatweb.Web}/Components/Routes.razor | 0 .../aichatweb.Web/Components/_Imports.razor | 0 .../aichatweb/aichatweb.Web/Program.cs | 0 .../Properties/launchSettings.json | 4 +- .../aichatweb.Web/Services/IngestedChunk.cs | 0 .../Services/Ingestion/DataIngestor.cs | 0 .../Services/Ingestion/DocumentReader.cs | 0 .../aichatweb.Web/Services/SemanticSearch.cs | 0 .../aichatweb.Web/aichatweb.Web.csproj | 22 +- .../appsettings.Development.json | 0 .../aichatweb/aichatweb.Web}/appsettings.json | 0 .../aichatweb/aichatweb.sln | 0 .../aichatweb/Components/App.razor | 0 .../Components/Layout/LoadingSpinner.razor | 0 .../Layout/LoadingSpinner.razor.css | 0 .../Components/Layout/MainLayout.razor | 0 .../Components/Layout/MainLayout.razor.css | 0 .../Components/Layout/SurveyPrompt.razor | 0 .../Components/Layout/SurveyPrompt.razor.css | 0 .../Components/Pages/Chat/Chat.razor | 0 .../Components/Pages/Chat/Chat.razor.css | 0 .../Components/Pages/Chat/ChatCitation.razor | 0 .../Pages/Chat/ChatCitation.razor.css | 0 .../Components/Pages/Chat/ChatHeader.razor | 0 .../Pages/Chat/ChatHeader.razor.css | 0 .../Components/Pages/Chat/ChatInput.razor | 0 .../Components/Pages/Chat/ChatInput.razor.css | 0 .../Components/Pages/Chat/ChatInput.razor.js | 0 .../Pages/Chat/ChatMessageItem.razor | 0 .../Pages/Chat/ChatMessageItem.razor.css | 0 .../Pages/Chat/ChatMessageList.razor | 0 .../Pages/Chat/ChatMessageList.razor.css | 0 .../Pages/Chat/ChatMessageList.razor.js | 0 .../Pages/Chat/ChatSuggestions.razor | 0 .../Pages/Chat/ChatSuggestions.razor.css | 0 .../aichatweb}/Components/Pages/Error.razor | 0 .../aichatweb}/Components/Routes.razor | 0 .../aichatweb/Components/_Imports.razor | 0 .../aichatweb/Program.cs | 0 .../aichatweb}/Properties/launchSettings.json | 4 +- .../aichatweb/README.md | 0 .../aichatweb/Services/IngestedChunk.cs | 0 .../Services/Ingestion/DataIngestor.cs | 0 .../Services/Ingestion/DocumentReader.cs | 0 .../Services/Ingestion/PdfPigReader.cs | 0 .../aichatweb/Services/SemanticSearch.cs | 0 .../aichatweb/aichatweb.csproj | 18 +- .../aichatweb}/appsettings.Development.json | 0 .../aichatweb}/appsettings.json | 0 .../aichatweb/README.md | 0 .../aichatweb/aichatweb.AppHost/AppHost.cs | 0 .../Properties/launchSettings.json | 12 +- .../aichatweb.AppHost.csproj | 8 +- .../appsettings.Development.json | 0 .../aichatweb.AppHost/appsettings.json | 0 .../aichatweb.ServiceDefaults/Extensions.cs | 0 .../aichatweb.ServiceDefaults.csproj | 14 +- .../aichatweb.Web/Components/App.razor | 0 .../Components/Layout/LoadingSpinner.razor | 0 .../Layout/LoadingSpinner.razor.css | 0 .../Components/Layout/MainLayout.razor | 0 .../Components/Layout/MainLayout.razor.css | 0 .../Components/Layout/SurveyPrompt.razor | 0 .../Components/Layout/SurveyPrompt.razor.css | 0 .../Components/Pages/Chat/Chat.razor | 0 .../Components/Pages/Chat/Chat.razor.css | 0 .../Components/Pages/Chat/ChatCitation.razor | 0 .../Pages/Chat/ChatCitation.razor.css | 0 .../Components/Pages/Chat/ChatHeader.razor | 0 .../Pages/Chat/ChatHeader.razor.css | 0 .../Components/Pages/Chat/ChatInput.razor | 0 .../Components/Pages/Chat/ChatInput.razor.css | 0 .../Components/Pages/Chat/ChatInput.razor.js | 0 .../Pages/Chat/ChatMessageItem.razor | 0 .../Pages/Chat/ChatMessageItem.razor.css | 0 .../Pages/Chat/ChatMessageList.razor | 0 .../Pages/Chat/ChatMessageList.razor.css | 0 .../Pages/Chat/ChatMessageList.razor.js | 0 .../Pages/Chat/ChatSuggestions.razor | 0 .../Pages/Chat/ChatSuggestions.razor.css | 0 .../Components/Pages/Error.razor | 0 .../aichatweb.Web/Components/Routes.razor | 0 .../aichatweb.Web/Components/_Imports.razor | 0 .../OllamaResilienceHandlerExtensions.cs | 1 - .../aichatweb/aichatweb.Web/Program.cs | 0 .../Properties/launchSettings.json | 4 +- .../aichatweb.Web/Services/IngestedChunk.cs | 0 .../Services/Ingestion/DataIngestor.cs | 0 .../Services/Ingestion/DocumentReader.cs | 0 .../aichatweb.Web/Services/SemanticSearch.cs | 0 .../aichatweb.Web/aichatweb.Web.csproj | 22 +- .../appsettings.Development.json | 0 .../aichatweb/aichatweb.Web/appsettings.json | 0 .../aichatweb/aichatweb.sln | 0 .../aichatweb/Components/App.razor | 0 .../Components/Layout/LoadingSpinner.razor | 0 .../Layout/LoadingSpinner.razor.css | 0 .../Components/Layout/MainLayout.razor | 0 .../Components/Layout/MainLayout.razor.css | 0 .../Components/Layout/SurveyPrompt.razor | 0 .../Components/Layout/SurveyPrompt.razor.css | 0 .../Components/Pages/Chat/Chat.razor | 0 .../Components/Pages/Chat/Chat.razor.css | 0 .../Components/Pages/Chat/ChatCitation.razor | 0 .../Pages/Chat/ChatCitation.razor.css | 0 .../Components/Pages/Chat/ChatHeader.razor | 0 .../Pages/Chat/ChatHeader.razor.css | 0 .../Components/Pages/Chat/ChatInput.razor | 0 .../Components/Pages/Chat/ChatInput.razor.css | 0 .../Components/Pages/Chat/ChatInput.razor.js | 0 .../Pages/Chat/ChatMessageItem.razor | 0 .../Pages/Chat/ChatMessageItem.razor.css | 0 .../Pages/Chat/ChatMessageList.razor | 0 .../Pages/Chat/ChatMessageList.razor.css | 0 .../Pages/Chat/ChatMessageList.razor.js | 0 .../Pages/Chat/ChatSuggestions.razor | 0 .../Pages/Chat/ChatSuggestions.razor.css | 0 .../aichatweb/Components/Pages/Error.razor | 0 .../aichatweb/Components/Routes.razor | 0 .../aichatweb/Components/_Imports.razor | 0 .../aichatweb/Program.cs | 0 .../aichatweb/Properties/launchSettings.json | 23 + .../aichatweb/README.md | 0 .../aichatweb/Services/IngestedChunk.cs | 0 .../Services/Ingestion/DataIngestor.cs | 0 .../Services/Ingestion/DocumentReader.cs | 0 .../Services/Ingestion/PdfPigReader.cs | 0 .../aichatweb/Services/SemanticSearch.cs | 0 .../aichatweb/aichatweb.csproj | 22 +- .../aichatweb/appsettings.Development.json | 0 .../aichatweb/appsettings.json | 0 .../mcpserver/.mcp/server.json | 0 .../mcpserver/Program.cs | 0 .../mcpserver/README.md | 0 .../mcpserver/Tools/RandomNumberTools.cs | 0 .../mcpserver/mcpserver.csproj | 4 +- .../mcpserver/.mcp/server.json | 0 .../mcpserver/Program.cs | 0 .../mcpserver/README.md | 0 .../mcpserver/Tools/RandomNumberTools.cs | 0 .../mcpserver/mcpserver.csproj | 4 +- .../mcpserver/.mcp/server.json | 0 .../mcpserver/Program.cs | 0 .../mcpserver/README.md | 0 .../mcpserver/Tools/RandomNumberTools.cs | 0 .../mcpserver/mcpserver.csproj | 4 +- .../mcpserver/.mcp/server.json | 0 .../mcpserver/Program.cs | 0 .../mcpserver/README.md | 0 .../mcpserver/Tools/RandomNumberTools.cs | 0 .../mcpserver/mcpserver.csproj | 6 +- 515 files changed, 1270 insertions(+), 84406 deletions(-) create mode 100644 bench/Directory.Packages.props create mode 100644 eng/Tools/Directory.Packages.props create mode 100644 eng/packages/ProjectTemplates.props rename eng/packages/{TestOnly.props => Tests.props} (90%) create mode 100644 eng/packages/Tools.props create mode 100644 src/ProjectTemplates/Directory.Build.targets create mode 100644 src/ProjectTemplates/Directory.Packages.props delete mode 100644 src/ProjectTemplates/GenerateTemplateContent/GenerateTemplateContent.csproj delete mode 100644 src/ProjectTemplates/GeneratedContent.targets rename src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/{src/WebApiAgent/WebApiAgent-CSharp => templates/AIAgentWebApi-CSharp}/.template.config/dotnetcli.host.json (100%) rename src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/{src/WebApiAgent/WebApiAgent-CSharp => templates/AIAgentWebApi-CSharp}/.template.config/ide.host.json (100%) rename src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/{src/WebApiAgent/WebApiAgent-CSharp => templates/AIAgentWebApi-CSharp}/.template.config/ide/agent-framework.ico (100%) rename src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/{src/WebApiAgent/WebApiAgent-CSharp => templates/AIAgentWebApi-CSharp}/.template.config/template.json (95%) rename src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/{src/WebApiAgent/WebApiAgent-CSharp/WebApiAgent-CSharp.csproj.in => templates/AIAgentWebApi-CSharp/AIAgentWebApi-CSharp.csproj-in} (57%) rename src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/{src/WebApiAgent/WebApiAgent-CSharp => templates/AIAgentWebApi-CSharp}/Program.cs (100%) rename src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/{src/WebApiAgent/WebApiAgent-CSharp => templates/AIAgentWebApi-CSharp}/Properties/launchSettings.json (82%) rename src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/{src/WebApiAgent/WebApiAgent-CSharp => templates/AIAgentWebApi-CSharp}/README.md (99%) rename src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/{src/WebApiAgent/WebApiAgent-CSharp => templates/AIAgentWebApi-CSharp}/appsettings.json (100%) rename src/ProjectTemplates/{ => Microsoft.Extensions.AI.Templates}/package.json (71%) delete mode 100644 src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Directory.Build.targets.in delete mode 100644 src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/Directory.Build.props.in delete mode 100644 src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/Directory.Build.targets.in delete mode 100644 src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/NuGet.config.in rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData => templates/AIChatWeb-CSharp}/.template.config/dotnetcli.host.json (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData => templates/AIChatWeb-CSharp}/.template.config/ide.host.json (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData => templates/AIChatWeb-CSharp}/.template.config/ide/icon.ico (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData => templates/AIChatWeb-CSharp}/.template.config/template.json (93%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.AppHost/ChatWithCustomData-CSharp.AppHost.csproj.in => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.AppHost/AIChatWeb-CSharp.AppHost.csproj-in} (63%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.AppHost => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.AppHost}/AppHost.cs (96%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.AppHost => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.AppHost}/Properties/launchSettings.json (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.AppHost => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.AppHost}/appsettings.Development.json (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.AppHost => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.AppHost}/appsettings.json (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.ServiceDefaults/ChatWithCustomData-CSharp.ServiceDefaults.csproj.in => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.ServiceDefaults/AIChatWeb-CSharp.ServiceDefaults.csproj-in} (60%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.ServiceDefaults => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.ServiceDefaults}/Extensions.cs (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/ChatWithCustomData-CSharp.Web.csproj.in => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/AIChatWeb-CSharp.Web.csproj-in} (55%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/Components/App.razor (87%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/Components/Layout/LoadingSpinner.razor (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/Components/Layout/LoadingSpinner.razor.css (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/Components/Layout/MainLayout.razor (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/Components/Layout/MainLayout.razor.css (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/Components/Layout/SurveyPrompt.razor (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/Components/Layout/SurveyPrompt.razor.css (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/Components/Pages/Chat/Chat.razor (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/Components/Pages/Chat/Chat.razor.css (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/Components/Pages/Chat/ChatCitation.razor (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/Components/Pages/Chat/ChatCitation.razor.css (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/Components/Pages/Chat/ChatHeader.razor (90%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/Components/Pages/Chat/ChatHeader.razor.css (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/Components/Pages/Chat/ChatInput.razor (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/Components/Pages/Chat/ChatInput.razor.css (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/Components/Pages/Chat/ChatInput.razor.js (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/Components/Pages/Chat/ChatMessageItem.razor (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/Components/Pages/Chat/ChatMessageItem.razor.css (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/Components/Pages/Chat/ChatMessageList.razor (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/Components/Pages/Chat/ChatMessageList.razor.css (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/Components/Pages/Chat/ChatMessageList.razor.js (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/Components/Pages/Chat/ChatSuggestions.razor (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/Components/Pages/Chat/ChatSuggestions.razor.css (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/Components/Pages/Error.razor (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/Components/Routes.razor (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/Components/_Imports.razor (66%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/OllamaResilienceHandlerExtensions.cs (95%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/Program.Aspire.cs (94%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/Program.cs (97%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/Properties/launchSettings.json (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/README.md (98%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/Services/IngestedChunk.cs (90%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/Services/Ingestion/DataIngestor.cs (95%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/Services/Ingestion/DocumentReader.cs (96%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/Services/Ingestion/PdfPigReader.cs (95%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/Services/SemanticSearch.cs (90%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/appsettings.Development.json (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/appsettings.json (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/wwwroot/Data/Example_Emergency_Survival_Kit.pdf (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/wwwroot/Data/Example_GPS_Watch.md (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/wwwroot/app.css (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/wwwroot/app.js (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/wwwroot/favicon.ico (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/wwwroot/lib/dompurify/README.md (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/wwwroot/lib/dompurify/dist/purify.es.mjs (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/wwwroot/lib/markdown_viewer/viewer.html (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/wwwroot/lib/markdown_viewer/viewer.mjs (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/wwwroot/lib/marked/README.md (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/wwwroot/lib/marked/dist/marked.esm.js (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/wwwroot/lib/pdf_viewer/viewer.html (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/wwwroot/lib/pdf_viewer/viewer.mjs (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/wwwroot/lib/pdfjs-dist/README.md (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/wwwroot/lib/pdfjs-dist/dist/build/pdf.min.mjs (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/wwwroot/lib/pdfjs-dist/dist/build/pdf.worker.min.mjs (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/wwwroot/lib/pdfjs-dist/dist/web/images/loading-icon.gif (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.css (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.mjs (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/wwwroot/lib/tailwindcss/README.md (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.Web => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web}/wwwroot/lib/tailwindcss/dist/preflight.css (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData/ChatWithCustomData-CSharp.sln.in => templates/AIChatWeb-CSharp/AIChatWeb-CSharp.sln} (70%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/ChatWithCustomData => templates/AIChatWeb-CSharp}/README.Aspire.md (91%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/McpServer => templates}/McpServer-CSharp/.mcp/server.json (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/McpServer => templates}/McpServer-CSharp/.template.config/dotnetcli.host.json (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/McpServer => templates}/McpServer-CSharp/.template.config/ide.host.json (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/McpServer => templates}/McpServer-CSharp/.template.config/ide/icon.ico (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/McpServer => templates}/McpServer-CSharp/.template.config/template.json (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/McpServer/McpServer-CSharp/McpServer-CSharp.csproj.in => templates/McpServer-CSharp/McpServer-CSharp.csproj-in} (94%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/McpServer => templates}/McpServer-CSharp/Program.cs (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/McpServer => templates}/McpServer-CSharp/README.md (100%) rename src/ProjectTemplates/Microsoft.Extensions.AI.Templates/{src/McpServer => templates}/McpServer-CSharp/Tools/RandomNumberTools.cs (100%) create mode 100644 test/Directory.Packages.props delete mode 100644 test/ProjectTemplates/.gitignore delete mode 100644 test/ProjectTemplates/Infrastructure/TemplateExecutionTestCollectionFixture.cs rename test/ProjectTemplates/Infrastructure/TemplateSandbox/{nuget.template_install.config => install/nuget.config} (100%) rename test/ProjectTemplates/Infrastructure/TemplateSandbox/{ => projects}/Directory.Build.props (100%) rename test/ProjectTemplates/Infrastructure/TemplateSandbox/{ => projects}/Directory.Build.targets (100%) rename test/ProjectTemplates/Infrastructure/TemplateSandbox/{nuget.template_test.config => projects/nuget.config} (100%) create mode 100644 test/ProjectTemplates/Infrastructure/TemplateSnapshotTestBase.cs create mode 100644 test/ProjectTemplates/Infrastructure/TemplateTestUtilities.cs create mode 100644 test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/AIAgentWebAPIExecutionTests.cs create mode 100644 test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/AIAgentWebAPISnapshotTests.cs delete mode 100644 test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/ProjectRootHelper.cs delete mode 100644 test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/README.md delete mode 100644 test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.DefaultParameters.verified/aiagent-webapi/README.md delete mode 100644 test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.GitHubModels.verified/aiagent-webapi/Program.cs delete mode 100644 test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.Ollama.verified/aiagent-webapi/Properties/launchSettings.json delete mode 100644 test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.OpenAI.verified/aiagent-webapi/Properties/launchSettings.json delete mode 100644 test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.OpenAI.verified/aiagent-webapi/aiagent-webapi.csproj delete mode 100644 test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.OpenAI.verified/aiagent-webapi/appsettings.json rename test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/{aiagent-webapi.DefaultParameters.verified => aiagent-webapi/aiagent-webapi._defaults.verified}/aiagent-webapi/Program.cs (100%) rename test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/{aiagent-webapi.GitHubModels.verified => aiagent-webapi/aiagent-webapi._defaults.verified}/aiagent-webapi/Properties/launchSettings.json (82%) rename test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/{aiagent-webapi.GitHubModels.verified => aiagent-webapi/aiagent-webapi._defaults.verified}/aiagent-webapi/README.md (98%) rename test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/{aiagent-webapi.AzureOpenAI_ApiKey.verified => aiagent-webapi/aiagent-webapi._defaults.verified}/aiagent-webapi/aiagent-webapi.csproj (69%) rename test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/{aiagent-webapi.AzureOpenAI_ApiKey.verified => aiagent-webapi/aiagent-webapi._defaults.verified}/aiagent-webapi/appsettings.json (100%) rename test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/{aiagent-webapi.AzureOpenAI_ApiKey.verified => aiagent-webapi/aiagent-webapi.aoai_ID_F.verified}/aiagent-webapi/Program.cs (100%) rename test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/{aiagent-webapi.AzureOpenAI_ApiKey.verified => aiagent-webapi/aiagent-webapi.aoai_ID_F.verified}/aiagent-webapi/Properties/launchSettings.json (82%) rename test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/{aiagent-webapi.AzureOpenAI_ApiKey.verified => aiagent-webapi/aiagent-webapi.aoai_ID_F.verified}/aiagent-webapi/README.md (98%) rename test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/{aiagent-webapi.GitHubModels.verified => aiagent-webapi/aiagent-webapi.aoai_ID_F.verified}/aiagent-webapi/aiagent-webapi.csproj (69%) rename test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/{aiagent-webapi.AzureOpenAI_ManagedIdentity.verified => aiagent-webapi/aiagent-webapi.aoai_ID_F.verified}/aiagent-webapi/appsettings.json (100%) rename test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/{aiagent-webapi.AzureOpenAI_ManagedIdentity.verified => aiagent-webapi/aiagent-webapi.aoai_ID_T.verified}/aiagent-webapi/Program.cs (100%) rename test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/{aiagent-webapi.DefaultParameters.verified => aiagent-webapi/aiagent-webapi.aoai_ID_T.verified}/aiagent-webapi/Properties/launchSettings.json (82%) rename test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/{aiagent-webapi.AzureOpenAI_ManagedIdentity.verified => aiagent-webapi/aiagent-webapi.aoai_ID_T.verified}/aiagent-webapi/README.md (98%) rename test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/{aiagent-webapi.AzureOpenAI_ManagedIdentity.verified => aiagent-webapi/aiagent-webapi.aoai_ID_T.verified}/aiagent-webapi/aiagent-webapi.csproj (63%) rename test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/{aiagent-webapi.DefaultParameters.verified => aiagent-webapi/aiagent-webapi.aoai_ID_T.verified}/aiagent-webapi/appsettings.json (100%) rename test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/{aiagent-webapi.Ollama.verified => aiagent-webapi/aiagent-webapi.o.verified}/aiagent-webapi/Program.cs (100%) rename test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/{aiagent-webapi.AzureOpenAI_ManagedIdentity.verified => aiagent-webapi/aiagent-webapi.o.verified}/aiagent-webapi/Properties/launchSettings.json (82%) rename test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/{aiagent-webapi.Ollama.verified => aiagent-webapi/aiagent-webapi.o.verified}/aiagent-webapi/README.md (96%) rename test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/{aiagent-webapi.Ollama.verified => aiagent-webapi/aiagent-webapi.o.verified}/aiagent-webapi/aiagent-webapi.csproj (62%) rename test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/{aiagent-webapi.GitHubModels.verified => aiagent-webapi/aiagent-webapi.o.verified}/aiagent-webapi/appsettings.json (100%) rename test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/{aiagent-webapi.OpenAI.verified => aiagent-webapi/aiagent-webapi.oai.verified}/aiagent-webapi/Program.cs (100%) create mode 100644 test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.oai.verified/aiagent-webapi/Properties/launchSettings.json rename test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/{aiagent-webapi.OpenAI.verified => aiagent-webapi/aiagent-webapi.oai.verified}/aiagent-webapi/README.md (98%) rename test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/{aiagent-webapi.DefaultParameters.verified => aiagent-webapi/aiagent-webapi.oai.verified}/aiagent-webapi/aiagent-webapi.csproj (69%) rename test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/{aiagent-webapi.Ollama.verified => aiagent-webapi/aiagent-webapi.oai.verified}/aiagent-webapi/appsettings.json (100%) delete mode 100644 test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/WebApiAgentTemplateExecutionTests.cs delete mode 100644 test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/WebApiAgentTemplateSnapshotTests.cs create mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/McpServerExecutionTests.cs delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/ProjectRootHelper.cs delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/Data/Example_Emergency_Survival_Kit.pdf delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/Data/Example_GPS_Watch.md delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/app.css delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/app.js delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/favicon.ico delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/dompurify/README.md delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/dompurify/dist/purify.es.mjs delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/markdown_viewer/viewer.html delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/markdown_viewer/viewer.mjs delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/marked/README.md delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/marked/dist/marked.esm.js delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdf_viewer/viewer.html delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdf_viewer/viewer.mjs delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/README.md delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/build/pdf.min.mjs delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/build/pdf.worker.min.mjs delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/web/images/loading-icon.gif delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.css delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.mjs delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/tailwindcss/README.md delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/tailwindcss/dist/preflight.css delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/Data/Example_Emergency_Survival_Kit.pdf delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/Data/Example_GPS_Watch.md delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/app.css delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/app.js delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/favicon.ico delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/dompurify/README.md delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/dompurify/dist/purify.es.mjs delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/markdown_viewer/viewer.html delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/markdown_viewer/viewer.mjs delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/marked/README.md delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/marked/dist/marked.esm.js delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/pdf_viewer/viewer.html delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/pdf_viewer/viewer.mjs delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/pdfjs-dist/README.md delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/pdfjs-dist/dist/build/pdf.min.mjs delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/pdfjs-dist/dist/build/pdf.worker.min.mjs delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/pdfjs-dist/dist/web/images/loading-icon.gif delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.css delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.mjs delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/tailwindcss/README.md delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/tailwindcss/dist/preflight.css delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/Data/Example_Emergency_Survival_Kit.pdf delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/Data/Example_GPS_Watch.md delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/app.css delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/app.js delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/favicon.ico delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/dompurify/README.md delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/dompurify/dist/purify.es.mjs delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/markdown_viewer/viewer.html delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/markdown_viewer/viewer.mjs delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/marked/README.md delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/marked/dist/marked.esm.js delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdf_viewer/viewer.html delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdf_viewer/viewer.mjs delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/README.md delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/build/pdf.min.mjs delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/build/pdf.worker.min.mjs delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/web/images/loading-icon.gif delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.css delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.mjs delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/tailwindcss/README.md delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/tailwindcss/dist/preflight.css delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/Data/Example_Emergency_Survival_Kit.pdf delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/Data/Example_GPS_Watch.md delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/app.css delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/app.js delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/favicon.ico delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/dompurify/README.md delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/dompurify/dist/purify.es.mjs delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/markdown_viewer/viewer.html delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/markdown_viewer/viewer.mjs delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/marked/README.md delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/marked/dist/marked.esm.js delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdf_viewer/viewer.html delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdf_viewer/viewer.mjs delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/README.md delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/build/pdf.min.mjs delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/build/pdf.worker.min.mjs delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/web/images/loading-icon.gif delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.css delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.mjs delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/tailwindcss/README.md delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/tailwindcss/dist/preflight.css delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Properties/launchSettings.json delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/Data/Example_Emergency_Survival_Kit.pdf delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/Data/Example_GPS_Watch.md delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/app.css delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/app.js delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/favicon.ico delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/dompurify/README.md delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/dompurify/dist/purify.es.mjs delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/markdown_viewer/viewer.html delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/markdown_viewer/viewer.mjs delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/marked/README.md delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/marked/dist/marked.esm.js delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/pdf_viewer/viewer.html delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/pdf_viewer/viewer.mjs delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/pdfjs-dist/README.md delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/pdfjs-dist/dist/build/pdf.min.mjs delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/pdfjs-dist/dist/build/pdf.worker.min.mjs delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/pdfjs-dist/dist/web/images/loading-icon.gif delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.css delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.mjs delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/tailwindcss/README.md delete mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/tailwindcss/dist/preflight.css rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/README.md (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.AppHost/AppHost.cs (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.AppHost/Properties/launchSettings.json (84%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.AppHost/aichatweb.AppHost.csproj (84%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.AppHost/appsettings.Development.json (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.AppHost/appsettings.json (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.ServiceDefaults/Extensions.cs (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.ServiceDefaults/aichatweb.ServiceDefaults.csproj (79%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.Web/Components/App.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.Web/Components/Layout/LoadingSpinner.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.Web/Components/Layout/LoadingSpinner.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.Web/Components/Layout/MainLayout.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.Web/Components/Layout/MainLayout.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.Web/Components/Layout/SurveyPrompt.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.Web/Components/Layout/SurveyPrompt.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.Web/Components/Pages/Chat/Chat.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.Web/Components/Pages/Chat/Chat.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatCitation.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatCitation.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatHeader.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatHeader.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor.js (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageItem.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageItem.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor.js (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatSuggestions.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatSuggestions.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.Web/Components/Pages/Error.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.Web/Components/Routes.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.Web/Components/_Imports.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.Web/Program.cs (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.Web/Properties/launchSettings.json (80%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.Web/Services/IngestedChunk.cs (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.Web/Services/Ingestion/DataIngestor.cs (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.Web/Services/Ingestion/DocumentReader.cs (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.Web/Services/SemanticSearch.cs (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.Web/aichatweb.Web.csproj (74%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.Web/appsettings.Development.json (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.Web/appsettings.json (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A.verified}/aichatweb/aichatweb.sln (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A_aoai_aais.verified}/aichatweb/README.md (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A_aoai_aais.verified}/aichatweb/aichatweb.AppHost/AppHost.cs (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified => aichatweb/aichatweb.A_aoai_aais.verified}/aichatweb/aichatweb.AppHost/Properties/launchSettings.json (84%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A_aoai_aais.verified}/aichatweb/aichatweb.AppHost/aichatweb.AppHost.csproj (81%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified => aichatweb/aichatweb.A_aoai_aais.verified}/aichatweb/aichatweb.AppHost/appsettings.Development.json (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified => aichatweb/aichatweb.A_aoai_aais.verified}/aichatweb/aichatweb.AppHost/appsettings.json (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified => aichatweb/aichatweb.A_aoai_aais.verified}/aichatweb/aichatweb.ServiceDefaults/Extensions.cs (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A_aoai_aais.verified}/aichatweb/aichatweb.ServiceDefaults/aichatweb.ServiceDefaults.csproj (79%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified => aichatweb/aichatweb.A_aoai_aais.verified}/aichatweb/aichatweb.Web/Components/App.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Basic.verified/aichatweb => aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web}/Components/Layout/LoadingSpinner.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Basic.verified/aichatweb => aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web}/Components/Layout/LoadingSpinner.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Basic.verified/aichatweb => aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web}/Components/Layout/MainLayout.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Basic.verified/aichatweb => aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web}/Components/Layout/MainLayout.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Basic.verified/aichatweb => aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web}/Components/Layout/SurveyPrompt.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Basic.verified/aichatweb => aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web}/Components/Layout/SurveyPrompt.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Basic.verified/aichatweb => aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web}/Components/Pages/Chat/Chat.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Basic.verified/aichatweb => aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web}/Components/Pages/Chat/Chat.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Basic.verified/aichatweb => aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web}/Components/Pages/Chat/ChatCitation.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Basic.verified/aichatweb => aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web}/Components/Pages/Chat/ChatCitation.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified => aichatweb/aichatweb.A_aoai_aais.verified}/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatHeader.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Basic.verified/aichatweb => aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web}/Components/Pages/Chat/ChatHeader.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Basic.verified/aichatweb => aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web}/Components/Pages/Chat/ChatInput.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Basic.verified/aichatweb => aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web}/Components/Pages/Chat/ChatInput.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Basic.verified/aichatweb => aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web}/Components/Pages/Chat/ChatInput.razor.js (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Basic.verified/aichatweb => aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web}/Components/Pages/Chat/ChatMessageItem.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Basic.verified/aichatweb => aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web}/Components/Pages/Chat/ChatMessageItem.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Basic.verified/aichatweb => aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web}/Components/Pages/Chat/ChatMessageList.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Basic.verified/aichatweb => aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web}/Components/Pages/Chat/ChatMessageList.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Basic.verified/aichatweb => aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web}/Components/Pages/Chat/ChatMessageList.razor.js (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Basic.verified/aichatweb => aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web}/Components/Pages/Chat/ChatSuggestions.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Basic.verified/aichatweb => aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web}/Components/Pages/Chat/ChatSuggestions.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Basic.verified/aichatweb => aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web}/Components/Pages/Error.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Basic.verified/aichatweb => aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web}/Components/Routes.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified => aichatweb/aichatweb.A_aoai_aais.verified}/aichatweb/aichatweb.Web/Components/_Imports.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A_aoai_aais.verified}/aichatweb/aichatweb.Web/Program.cs (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Basic.verified/aichatweb => aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web}/Properties/launchSettings.json (80%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A_aoai_aais.verified}/aichatweb/aichatweb.Web/Services/IngestedChunk.cs (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified => aichatweb/aichatweb.A_aoai_aais.verified}/aichatweb/aichatweb.Web/Services/Ingestion/DataIngestor.cs (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified => aichatweb/aichatweb.A_aoai_aais.verified}/aichatweb/aichatweb.Web/Services/Ingestion/DocumentReader.cs (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified => aichatweb/aichatweb.A_aoai_aais.verified}/aichatweb/aichatweb.Web/Services/SemanticSearch.cs (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.AzureOpenAI_Qdrant_Aspire.verified => aichatweb/aichatweb.A_aoai_aais.verified}/aichatweb/aichatweb.Web/aichatweb.Web.csproj (74%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Basic.verified/aichatweb => aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web}/appsettings.Development.json (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Basic.verified/aichatweb => aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web}/appsettings.json (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified => aichatweb/aichatweb.A_aoai_aais.verified}/aichatweb/aichatweb.sln (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Basic.verified => aichatweb/aichatweb._defaults.verified}/aichatweb/Components/App.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web => aichatweb/aichatweb._defaults.verified/aichatweb}/Components/Layout/LoadingSpinner.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web => aichatweb/aichatweb._defaults.verified/aichatweb}/Components/Layout/LoadingSpinner.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web => aichatweb/aichatweb._defaults.verified/aichatweb}/Components/Layout/MainLayout.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web => aichatweb/aichatweb._defaults.verified/aichatweb}/Components/Layout/MainLayout.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web => aichatweb/aichatweb._defaults.verified/aichatweb}/Components/Layout/SurveyPrompt.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web => aichatweb/aichatweb._defaults.verified/aichatweb}/Components/Layout/SurveyPrompt.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web => aichatweb/aichatweb._defaults.verified/aichatweb}/Components/Pages/Chat/Chat.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web => aichatweb/aichatweb._defaults.verified/aichatweb}/Components/Pages/Chat/Chat.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web => aichatweb/aichatweb._defaults.verified/aichatweb}/Components/Pages/Chat/ChatCitation.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web => aichatweb/aichatweb._defaults.verified/aichatweb}/Components/Pages/Chat/ChatCitation.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Basic.verified => aichatweb/aichatweb._defaults.verified}/aichatweb/Components/Pages/Chat/ChatHeader.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web => aichatweb/aichatweb._defaults.verified/aichatweb}/Components/Pages/Chat/ChatHeader.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web => aichatweb/aichatweb._defaults.verified/aichatweb}/Components/Pages/Chat/ChatInput.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web => aichatweb/aichatweb._defaults.verified/aichatweb}/Components/Pages/Chat/ChatInput.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web => aichatweb/aichatweb._defaults.verified/aichatweb}/Components/Pages/Chat/ChatInput.razor.js (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web => aichatweb/aichatweb._defaults.verified/aichatweb}/Components/Pages/Chat/ChatMessageItem.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web => aichatweb/aichatweb._defaults.verified/aichatweb}/Components/Pages/Chat/ChatMessageItem.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web => aichatweb/aichatweb._defaults.verified/aichatweb}/Components/Pages/Chat/ChatMessageList.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web => aichatweb/aichatweb._defaults.verified/aichatweb}/Components/Pages/Chat/ChatMessageList.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web => aichatweb/aichatweb._defaults.verified/aichatweb}/Components/Pages/Chat/ChatMessageList.razor.js (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web => aichatweb/aichatweb._defaults.verified/aichatweb}/Components/Pages/Chat/ChatSuggestions.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web => aichatweb/aichatweb._defaults.verified/aichatweb}/Components/Pages/Chat/ChatSuggestions.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web => aichatweb/aichatweb._defaults.verified/aichatweb}/Components/Pages/Error.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web => aichatweb/aichatweb._defaults.verified/aichatweb}/Components/Routes.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Basic.verified => aichatweb/aichatweb._defaults.verified}/aichatweb/Components/_Imports.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Basic.verified => aichatweb/aichatweb._defaults.verified}/aichatweb/Program.cs (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web => aichatweb/aichatweb._defaults.verified/aichatweb}/Properties/launchSettings.json (80%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Basic.verified => aichatweb/aichatweb._defaults.verified}/aichatweb/README.md (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Basic.verified => aichatweb/aichatweb._defaults.verified}/aichatweb/Services/IngestedChunk.cs (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Basic.verified => aichatweb/aichatweb._defaults.verified}/aichatweb/Services/Ingestion/DataIngestor.cs (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Basic.verified => aichatweb/aichatweb._defaults.verified}/aichatweb/Services/Ingestion/DocumentReader.cs (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Basic.verified => aichatweb/aichatweb._defaults.verified}/aichatweb/Services/Ingestion/PdfPigReader.cs (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Basic.verified => aichatweb/aichatweb._defaults.verified}/aichatweb/Services/SemanticSearch.cs (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Basic.verified => aichatweb/aichatweb._defaults.verified}/aichatweb/aichatweb.csproj (67%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web => aichatweb/aichatweb._defaults.verified/aichatweb}/appsettings.Development.json (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web => aichatweb/aichatweb._defaults.verified/aichatweb}/appsettings.json (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/README.md (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.AppHost/AppHost.cs (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.AppHost/Properties/launchSettings.json (84%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.AppHost/aichatweb.AppHost.csproj (74%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.AppHost/appsettings.Development.json (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.AppHost/appsettings.json (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.ServiceDefaults/Extensions.cs (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.ServiceDefaults/aichatweb.ServiceDefaults.csproj (79%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.Web/Components/App.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.Web/Components/Layout/LoadingSpinner.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.Web/Components/Layout/LoadingSpinner.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.Web/Components/Layout/MainLayout.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.Web/Components/Layout/MainLayout.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.Web/Components/Layout/SurveyPrompt.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.Web/Components/Layout/SurveyPrompt.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.Web/Components/Pages/Chat/Chat.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.Web/Components/Pages/Chat/Chat.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatCitation.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatCitation.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatHeader.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatHeader.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor.js (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageItem.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageItem.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor.js (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatSuggestions.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatSuggestions.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.Web/Components/Pages/Error.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.Web/Components/Routes.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.Web/Components/_Imports.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.Web/OllamaResilienceHandlerExtensions.cs (99%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.Web/Program.cs (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.Web/Properties/launchSettings.json (80%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.Web/Services/IngestedChunk.cs (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.Web/Services/Ingestion/DataIngestor.cs (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.Web/Services/Ingestion/DocumentReader.cs (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.Web/Services/SemanticSearch.cs (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.Web/aichatweb.Web.csproj (66%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.Web/appsettings.Development.json (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.Web/appsettings.json (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.Ollama_Qdrant.verified => aichatweb/aichatweb.o_q.verified}/aichatweb/aichatweb.sln (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.OpenAI_AzureAISearch.verified => aichatweb/aichatweb.oai_aais.verified}/aichatweb/Components/App.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.OpenAI_AzureAISearch.verified => aichatweb/aichatweb.oai_aais.verified}/aichatweb/Components/Layout/LoadingSpinner.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.OpenAI_AzureAISearch.verified => aichatweb/aichatweb.oai_aais.verified}/aichatweb/Components/Layout/LoadingSpinner.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.OpenAI_AzureAISearch.verified => aichatweb/aichatweb.oai_aais.verified}/aichatweb/Components/Layout/MainLayout.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.OpenAI_AzureAISearch.verified => aichatweb/aichatweb.oai_aais.verified}/aichatweb/Components/Layout/MainLayout.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.OpenAI_AzureAISearch.verified => aichatweb/aichatweb.oai_aais.verified}/aichatweb/Components/Layout/SurveyPrompt.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.OpenAI_AzureAISearch.verified => aichatweb/aichatweb.oai_aais.verified}/aichatweb/Components/Layout/SurveyPrompt.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.OpenAI_AzureAISearch.verified => aichatweb/aichatweb.oai_aais.verified}/aichatweb/Components/Pages/Chat/Chat.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.OpenAI_AzureAISearch.verified => aichatweb/aichatweb.oai_aais.verified}/aichatweb/Components/Pages/Chat/Chat.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.OpenAI_AzureAISearch.verified => aichatweb/aichatweb.oai_aais.verified}/aichatweb/Components/Pages/Chat/ChatCitation.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.OpenAI_AzureAISearch.verified => aichatweb/aichatweb.oai_aais.verified}/aichatweb/Components/Pages/Chat/ChatCitation.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.OpenAI_AzureAISearch.verified => aichatweb/aichatweb.oai_aais.verified}/aichatweb/Components/Pages/Chat/ChatHeader.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.OpenAI_AzureAISearch.verified => aichatweb/aichatweb.oai_aais.verified}/aichatweb/Components/Pages/Chat/ChatHeader.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.OpenAI_AzureAISearch.verified => aichatweb/aichatweb.oai_aais.verified}/aichatweb/Components/Pages/Chat/ChatInput.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.OpenAI_AzureAISearch.verified => aichatweb/aichatweb.oai_aais.verified}/aichatweb/Components/Pages/Chat/ChatInput.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.OpenAI_AzureAISearch.verified => aichatweb/aichatweb.oai_aais.verified}/aichatweb/Components/Pages/Chat/ChatInput.razor.js (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.OpenAI_AzureAISearch.verified => aichatweb/aichatweb.oai_aais.verified}/aichatweb/Components/Pages/Chat/ChatMessageItem.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.OpenAI_AzureAISearch.verified => aichatweb/aichatweb.oai_aais.verified}/aichatweb/Components/Pages/Chat/ChatMessageItem.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.OpenAI_AzureAISearch.verified => aichatweb/aichatweb.oai_aais.verified}/aichatweb/Components/Pages/Chat/ChatMessageList.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.OpenAI_AzureAISearch.verified => aichatweb/aichatweb.oai_aais.verified}/aichatweb/Components/Pages/Chat/ChatMessageList.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.OpenAI_AzureAISearch.verified => aichatweb/aichatweb.oai_aais.verified}/aichatweb/Components/Pages/Chat/ChatMessageList.razor.js (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.OpenAI_AzureAISearch.verified => aichatweb/aichatweb.oai_aais.verified}/aichatweb/Components/Pages/Chat/ChatSuggestions.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.OpenAI_AzureAISearch.verified => aichatweb/aichatweb.oai_aais.verified}/aichatweb/Components/Pages/Chat/ChatSuggestions.razor.css (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.OpenAI_AzureAISearch.verified => aichatweb/aichatweb.oai_aais.verified}/aichatweb/Components/Pages/Error.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.OpenAI_AzureAISearch.verified => aichatweb/aichatweb.oai_aais.verified}/aichatweb/Components/Routes.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.OpenAI_AzureAISearch.verified => aichatweb/aichatweb.oai_aais.verified}/aichatweb/Components/_Imports.razor (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.OpenAI_AzureAISearch.verified => aichatweb/aichatweb.oai_aais.verified}/aichatweb/Program.cs (100%) create mode 100644 test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Properties/launchSettings.json rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.OpenAI_AzureAISearch.verified => aichatweb/aichatweb.oai_aais.verified}/aichatweb/README.md (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.OpenAI_AzureAISearch.verified => aichatweb/aichatweb.oai_aais.verified}/aichatweb/Services/IngestedChunk.cs (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.OpenAI_AzureAISearch.verified => aichatweb/aichatweb.oai_aais.verified}/aichatweb/Services/Ingestion/DataIngestor.cs (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.OpenAI_AzureAISearch.verified => aichatweb/aichatweb.oai_aais.verified}/aichatweb/Services/Ingestion/DocumentReader.cs (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.OpenAI_AzureAISearch.verified => aichatweb/aichatweb.oai_aais.verified}/aichatweb/Services/Ingestion/PdfPigReader.cs (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.OpenAI_AzureAISearch.verified => aichatweb/aichatweb.oai_aais.verified}/aichatweb/Services/SemanticSearch.cs (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.OpenAI_AzureAISearch.verified => aichatweb/aichatweb.oai_aais.verified}/aichatweb/aichatweb.csproj (64%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.OpenAI_AzureAISearch.verified => aichatweb/aichatweb.oai_aais.verified}/aichatweb/appsettings.Development.json (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{aichatweb.OpenAI_AzureAISearch.verified => aichatweb/aichatweb.oai_aais.verified}/aichatweb/appsettings.json (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{mcpserver.AotTrue.verified => mcpserver/mcpserver.AOT_T.verified}/mcpserver/.mcp/server.json (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{mcpserver.AotTrue.verified => mcpserver/mcpserver.AOT_T.verified}/mcpserver/Program.cs (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{mcpserver.AotTrue.verified => mcpserver/mcpserver.AOT_T.verified}/mcpserver/README.md (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{mcpserver.AotTrue.verified => mcpserver/mcpserver.AOT_T.verified}/mcpserver/Tools/RandomNumberTools.cs (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{mcpserver.AotTrue.verified => mcpserver/mcpserver.AOT_T.verified}/mcpserver/mcpserver.csproj (94%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{mcpserver.Basic.verified => mcpserver/mcpserver.SC_F.verified}/mcpserver/.mcp/server.json (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{mcpserver.Basic.verified => mcpserver/mcpserver.SC_F.verified}/mcpserver/Program.cs (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{mcpserver.SelfContainedFalse.verified => mcpserver/mcpserver.SC_F.verified}/mcpserver/README.md (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{mcpserver.Basic.verified => mcpserver/mcpserver.SC_F.verified}/mcpserver/Tools/RandomNumberTools.cs (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{mcpserver.SelfContainedFalse.verified => mcpserver/mcpserver.SC_F.verified}/mcpserver/mcpserver.csproj (91%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{mcpserver.SelfContainedFalse.verified => mcpserver/mcpserver._defaults.verified}/mcpserver/.mcp/server.json (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{mcpserver.SelfContainedFalse.verified => mcpserver/mcpserver._defaults.verified}/mcpserver/Program.cs (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{mcpserver.Basic.verified => mcpserver/mcpserver._defaults.verified}/mcpserver/README.md (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{mcpserver.SelfContainedFalse.verified => mcpserver/mcpserver._defaults.verified}/mcpserver/Tools/RandomNumberTools.cs (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{mcpserver.Basic.verified => mcpserver/mcpserver._defaults.verified}/mcpserver/mcpserver.csproj (93%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{mcpserver.net10.verified => mcpserver/mcpserver.net8.verified}/mcpserver/.mcp/server.json (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{mcpserver.net10.verified => mcpserver/mcpserver.net8.verified}/mcpserver/Program.cs (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{mcpserver.net10.verified => mcpserver/mcpserver.net8.verified}/mcpserver/README.md (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{mcpserver.net10.verified => mcpserver/mcpserver.net8.verified}/mcpserver/Tools/RandomNumberTools.cs (100%) rename test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/{mcpserver.net10.verified => mcpserver/mcpserver.net8.verified}/mcpserver/mcpserver.csproj (90%) diff --git a/bench/Directory.Build.props b/bench/Directory.Build.props index 7d847003d05..ba8eefefd02 100644 --- a/bench/Directory.Build.props +++ b/bench/Directory.Build.props @@ -1,6 +1,4 @@ - - false diff --git a/bench/Directory.Packages.props b/bench/Directory.Packages.props new file mode 100644 index 00000000000..010335bc108 --- /dev/null +++ b/bench/Directory.Packages.props @@ -0,0 +1,6 @@ + + + + + + diff --git a/eng/MSBuild/Packaging.targets b/eng/MSBuild/Packaging.targets index 0e1a385d685..3171136d95f 100644 --- a/eng/MSBuild/Packaging.targets +++ b/eng/MSBuild/Packaging.targets @@ -40,16 +40,16 @@ 9.10.0 - + - + @@ -102,14 +102,12 @@ - - + + - <_PackageVersionInfo Include="$(MSBuildProjectFullPath)"> - $(PackageVersion) - $(PackageId) - + diff --git a/eng/Tools/Directory.Packages.props b/eng/Tools/Directory.Packages.props new file mode 100644 index 00000000000..60fb4b1ad8e --- /dev/null +++ b/eng/Tools/Directory.Packages.props @@ -0,0 +1,6 @@ + + + + + + diff --git a/eng/build.proj b/eng/build.proj index 9626d7f0694..a5e895bd02b 100644 --- a/eng/build.proj +++ b/eng/build.proj @@ -1,8 +1,5 @@ - <_SnapshotsToExclude Include="$(MSBuildThisFileDirectory)..\test\**\Snapshots\**\*.*proj" /> - <_GeneratedContentToExclude Include="$(MSBuildThisFileDirectory)..\test\**\ExecutionTestSandbox\**\*.*proj" /> - <_ProjectsToBuild Include="$(MSBuildThisFileDirectory)..\src\**\*.csproj" /> @@ -11,7 +8,10 @@ <_ProjectsToBuild Include="$(MSBuildThisFileDirectory)..\src\Packages\Microsoft.Internal.Extensions.DotNetApiDocs.Transport\Microsoft.Internal.Extensions.DotNetApiDocs.Transport.proj" /> + + <_ProjectsToExclude Include="$(MSBuildThisFileDirectory)..\test\ProjectTemplates\**\Snapshots\**\*.csproj" /> + - + diff --git a/eng/packages/General.props b/eng/packages/General.props index 7565d36bac0..68e004a9275 100644 --- a/eng/packages/General.props +++ b/eng/packages/General.props @@ -9,26 +9,19 @@ + - - + - - - - - - - @@ -38,7 +31,6 @@ - diff --git a/eng/packages/ProjectTemplates.props b/eng/packages/ProjectTemplates.props new file mode 100644 index 00000000000..1abaa66643f --- /dev/null +++ b/eng/packages/ProjectTemplates.props @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/eng/packages/TestOnly.props b/eng/packages/Tests.props similarity index 90% rename from eng/packages/TestOnly.props rename to eng/packages/Tests.props index b1c041881b0..80d6fcda4fa 100644 --- a/eng/packages/TestOnly.props +++ b/eng/packages/Tests.props @@ -1,14 +1,14 @@ - - + + + - @@ -19,11 +19,12 @@ - + + - + @@ -32,6 +33,15 @@ + + + + + + diff --git a/eng/packages/Tools.props b/eng/packages/Tools.props new file mode 100644 index 00000000000..de396e59622 --- /dev/null +++ b/eng/packages/Tools.props @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/src/Libraries/Microsoft.Extensions.AI.Abstractions/Microsoft.Extensions.AI.Abstractions.csproj b/src/Libraries/Microsoft.Extensions.AI.Abstractions/Microsoft.Extensions.AI.Abstractions.csproj index 99340a1d2e9..72c354ccb97 100644 --- a/src/Libraries/Microsoft.Extensions.AI.Abstractions/Microsoft.Extensions.AI.Abstractions.csproj +++ b/src/Libraries/Microsoft.Extensions.AI.Abstractions/Microsoft.Extensions.AI.Abstractions.csproj @@ -17,7 +17,7 @@ $(TargetFrameworks);netstandard2.0 $(NoWarn);MEAI001 true - true + true diff --git a/src/Libraries/Microsoft.Extensions.AI.OpenAI/Microsoft.Extensions.AI.OpenAI.csproj b/src/Libraries/Microsoft.Extensions.AI.OpenAI/Microsoft.Extensions.AI.OpenAI.csproj index 3401a510e01..bf0841290e8 100644 --- a/src/Libraries/Microsoft.Extensions.AI.OpenAI/Microsoft.Extensions.AI.OpenAI.csproj +++ b/src/Libraries/Microsoft.Extensions.AI.OpenAI/Microsoft.Extensions.AI.OpenAI.csproj @@ -19,7 +19,7 @@ $(NoWarn);CA1063 $(NoWarn);OPENAI001;OPENAI002;MEAI001;SCME0001 true - true + true true diff --git a/src/Libraries/Microsoft.Extensions.AI/Microsoft.Extensions.AI.csproj b/src/Libraries/Microsoft.Extensions.AI/Microsoft.Extensions.AI.csproj index 380d9617c8e..c6daf35aa98 100644 --- a/src/Libraries/Microsoft.Extensions.AI/Microsoft.Extensions.AI.csproj +++ b/src/Libraries/Microsoft.Extensions.AI/Microsoft.Extensions.AI.csproj @@ -27,7 +27,7 @@ $(NoWarn);CA2007 true - true + true diff --git a/src/Libraries/Microsoft.Extensions.ServiceDiscovery.Abstractions/Microsoft.Extensions.ServiceDiscovery.Abstractions.csproj b/src/Libraries/Microsoft.Extensions.ServiceDiscovery.Abstractions/Microsoft.Extensions.ServiceDiscovery.Abstractions.csproj index b96d5ff7137..c39f5be1726 100644 --- a/src/Libraries/Microsoft.Extensions.ServiceDiscovery.Abstractions/Microsoft.Extensions.ServiceDiscovery.Abstractions.csproj +++ b/src/Libraries/Microsoft.Extensions.ServiceDiscovery.Abstractions/Microsoft.Extensions.ServiceDiscovery.Abstractions.csproj @@ -5,7 +5,7 @@ true Provides abstractions for service discovery. Interfaces defined in this package are implemented in Microsoft.Extensions.ServiceDiscovery and other service discovery packages. Open - true + true Microsoft.Extensions.ServiceDiscovery $(NoWarn);S1144;CA1002;S2365;SA1642;IDE0040;CA1307;EA0009;LA0003 diff --git a/src/Libraries/Microsoft.Extensions.ServiceDiscovery/Microsoft.Extensions.ServiceDiscovery.csproj b/src/Libraries/Microsoft.Extensions.ServiceDiscovery/Microsoft.Extensions.ServiceDiscovery.csproj index 51631d328c0..32b6485ef5a 100644 --- a/src/Libraries/Microsoft.Extensions.ServiceDiscovery/Microsoft.Extensions.ServiceDiscovery.csproj +++ b/src/Libraries/Microsoft.Extensions.ServiceDiscovery/Microsoft.Extensions.ServiceDiscovery.csproj @@ -5,7 +5,7 @@ true Provides extensions to HttpClient that enable service discovery based on configuration. Open - true + true $(NoWarn);CS8600;CS8602;CS8604;IDE0040;IDE0055;IDE0058;IDE1006;CA1307;CA1310;CA1849;CA2007;CA2213;SA1204;SA1128;SA1205;SA1405;SA1612;SA1623;SA1625;SA1642;S1144;S1449;S2302;S2692;S3872;S4457;EA0000;EA0009;EA0014;LA0001;LA0003;LA0008;VSTHRD200 enable diff --git a/src/Packages/Directory.Build.props b/src/Packages/Directory.Build.props index 94bdc485868..35ce59b0ef3 100644 --- a/src/Packages/Directory.Build.props +++ b/src/Packages/Directory.Build.props @@ -4,7 +4,7 @@ netstandard2.0 n/a true - true + true false diff --git a/src/ProjectTemplates/.gitignore b/src/ProjectTemplates/.gitignore index ee4a515c3d2..4cb6e4b8065 100644 --- a/src/ProjectTemplates/.gitignore +++ b/src/ProjectTemplates/.gitignore @@ -1,22 +1,8 @@ -# We're not tracking any package-lock.json files in source control here because -# we don't ship pre-generated NPM lockfiles in the templates. But we don't put -# them in the project template's .gitignore file because they should be tracked -# in source control when people actually create projects from the templates. -package-lock.json - -# Don't track files generated for debugging templates locally. -*/src/**/*.csproj -*/src/**/*.sln -*/src/**/NuGet.config -*/src/**/Directory.Build.targets -*/src/**/Directory.Build.props -*/src/**/ingestioncache.* - # The project templates include hard-coded launchSettings.json files -!*/src/ProjectTemplates/**/Properties/launchSettings.json +!**/templates/**/Properties/launchSettings.json # Templates include JS dependencies in dist folders. -!**/dist/* +!**/templates/**/dist/* -# Keep the package-lock.json file for updating template dependencies. -!package-lock.json +# Templates include solution files for Aspire configurations +!**/templates/**/*.sln diff --git a/src/ProjectTemplates/Directory.Build.props b/src/ProjectTemplates/Directory.Build.props index 2710579edee..5b7a0b022b8 100644 --- a/src/ProjectTemplates/Directory.Build.props +++ b/src/ProjectTemplates/Directory.Build.props @@ -7,4 +7,14 @@ false false + + + + + + diff --git a/src/ProjectTemplates/Directory.Build.targets b/src/ProjectTemplates/Directory.Build.targets new file mode 100644 index 00000000000..1e731a2e072 --- /dev/null +++ b/src/ProjectTemplates/Directory.Build.targets @@ -0,0 +1,109 @@ + + + + + + + + + + + + + + + + + + + + + + + %(_ResolvedTemplateContent.PackagePath) + + + + + + + + <_ResolvedTemplatePackageVersion Include="@(ProjectPackageVersion)" /> + + + <_ResolvedTemplatePackageVersion Remove="@(PackageVersion)" /> + <_ResolvedTemplatePackageVersion Include="@(PackageVersion)" /> + + + + + + <_GeneratedContentDir>$([System.IO.Path]::Combine($(ArtifactsDir), 'ProjectTemplates', $(PackageId), 'GeneratedContent')) + + + + <_TemplateContentFile Include="@(TemplateContent)"> + %(FileName)%(TemplateContent.Extension) + %(FileName)%(TemplateContent.ChangeExtension) + + $([System.IO.Path]::Combine("content", %(TemplateContent.RelativeDir))) + %(TemplateContent.PackagePath) + + + <_ResolvedTemplateContent Include="@(_TemplateContentFile)"> + $([System.IO.Path]::Combine($(_GeneratedContentDir), %(_TemplateContentFile.RelativeDir), %(_TemplateContentFile.OutputFileName))) + $([System.IO.Path]::Combine(%(_TemplateContentFile.PackagePathRoot), %(_TemplateContentFile.RecursiveDir), %(_TemplateContentFile.OutputFileName))) + + + + + diff --git a/src/ProjectTemplates/Directory.Packages.props b/src/ProjectTemplates/Directory.Packages.props new file mode 100644 index 00000000000..62b523710f3 --- /dev/null +++ b/src/ProjectTemplates/Directory.Packages.props @@ -0,0 +1,6 @@ + + + + + + diff --git a/src/ProjectTemplates/GenerateTemplateContent/GenerateTemplateContent.csproj b/src/ProjectTemplates/GenerateTemplateContent/GenerateTemplateContent.csproj deleted file mode 100644 index e8df485098b..00000000000 --- a/src/ProjectTemplates/GenerateTemplateContent/GenerateTemplateContent.csproj +++ /dev/null @@ -1,95 +0,0 @@ - - - - netstandard2.0 - true - - - <_GeneratedContentPropertiesHashFile>$(IntermediateOutputPath)$(MSBuildProjectName).content.g.cache - - - - - - - - - - - - - - - <_ResolvedPackageVersionVariableReference Include="@(_ResolvedPackageVersionInfo)"> - TemplatePackageVersion_$([System.String]::Copy('%(PackageId)').Replace('.', '')) - - - - - - $(GeneratedContentProperties); - - @(_ResolvedPackageVersionVariableReference->'%(VersionVariableName)=%(PackageVersion)') - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/ProjectTemplates/GeneratedContent.targets b/src/ProjectTemplates/GeneratedContent.targets deleted file mode 100644 index 97870dcc6b7..00000000000 --- a/src/ProjectTemplates/GeneratedContent.targets +++ /dev/null @@ -1,132 +0,0 @@ - - - - - <_LocalChatTemplateVariant>aspire - - <_WebApiAgentRoot>$(MSBuildThisFileDirectory)Microsoft.Agents.AI.ProjectTemplates\src\WebApiAgent\ - <_ChatWithCustomDataContentRoot>$(MSBuildThisFileDirectory)Microsoft.Extensions.AI.Templates\src\ChatWithCustomData\ - <_McpServerContentRoot>$(MSBuildThisFileDirectory)Microsoft.Extensions.AI.Templates\src\McpServer\ - - - - - - - - - - - - - - - - - 1.0.0-preview.251114.1 - 1.0.0-alpha.251114.1 - 13.0.0 - 13.0.0-preview.1.25560.3 - 1.1.0 - 1.17.1 - 11.7.0 - 13.0.0-beta.444 - 10.0.0 - 10.1.0 - 10.0.0 - 2.0.0 - 1.67.1 - 1.67.1-preview - 0.4.0-preview.3 - 5.4.11 - 1.14.0 - 0.1.12 - 10.0.0 - - - - - - $(GeneratedContentProperties); - - - ArtifactsShippingPackagesDir=$(ArtifactsShippingPackagesDir); - - - TemplatePackageVersion_MicrosoftAgentsAI=$(TemplatePackageVersion_MicrosoftAgentsAI); - TemplatePackageVersion_MicrosoftAgentsAIHostingOpenAI=$(TemplatePackageVersion_MicrosoftAgentsAIHostingOpenAI); - TemplatePackageVersion_Aspire=$(TemplatePackageVersion_Aspire); - TemplatePackageVersion_Aspire_Preview=$(TemplatePackageVersion_Aspire_Preview); - TemplatePackageVersion_AzureAIProjects=$(TemplatePackageVersion_AzureAIProjects); - TemplatePackageVersion_AzureIdentity=$(TemplatePackageVersion_AzureIdentity); - TemplatePackageVersion_AzureSearchDocuments=$(TemplatePackageVersion_AzureSearchDocuments); - TemplatePackageVersion_CommunityToolkitAspire=$(TemplatePackageVersion_CommunityToolkitAspire); - TemplatePackageVersion_MicrosoftExtensionsHosting=$(TemplatePackageVersion_MicrosoftExtensionsHosting); - TemplatePackageVersion_MicrosoftExtensionsHttpResilience=$(TemplatePackageVersion_MicrosoftExtensionsHttpResilience); - TemplatePackageVersion_MicrosoftExtensionsServiceDiscovery=$(TemplatePackageVersion_MicrosoftExtensionsServiceDiscovery); - TemplatePackageVersion_MicrosoftMLTokenizers=$(TemplatePackageVersion_MicrosoftMLTokenizers); - TemplatePackageVersion_MicrosoftSemanticKernel=$(TemplatePackageVersion_MicrosoftSemanticKernel); - TemplatePackageVersion_MicrosoftSemanticKernel_Preview=$(TemplatePackageVersion_MicrosoftSemanticKernel_Preview); - TemplatePackageVersion_ModelContextProtocol=$(TemplatePackageVersion_ModelContextProtocol); - TemplatePackageVersion_OllamaSharp=$(TemplatePackageVersion_OllamaSharp); - TemplatePackageVersion_OpenTelemetry=$(TemplatePackageVersion_OpenTelemetry); - TemplatePackageVersion_PdfPig=$(TemplatePackageVersion_PdfPig); - TemplatePackageVersion_SystemLinqAsyncEnumerable=$(TemplatePackageVersion_SystemLinqAsyncEnumerable); - - - LocalChatTemplateVariant=$(_LocalChatTemplateVariant); - - - - - - - - - - - - - - - - - - diff --git a/src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.csproj b/src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.csproj index f90597549a8..dc4f652791f 100644 --- a/src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.csproj +++ b/src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.csproj @@ -2,7 +2,7 @@ Template - $(NetCoreTargetFrameworks) + netstandard2.0 Project templates for Microsoft.Agents.AI. dotnet-new;templates;ai;agent @@ -30,32 +30,22 @@ - - - + - - - - - - + Include="templates\**" + Exclude="templates\**\*.csproj-in" + PackagePath="content" /> + + + + + diff --git a/src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/src/WebApiAgent/WebApiAgent-CSharp/.template.config/dotnetcli.host.json b/src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/templates/AIAgentWebApi-CSharp/.template.config/dotnetcli.host.json similarity index 100% rename from src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/src/WebApiAgent/WebApiAgent-CSharp/.template.config/dotnetcli.host.json rename to src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/templates/AIAgentWebApi-CSharp/.template.config/dotnetcli.host.json diff --git a/src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/src/WebApiAgent/WebApiAgent-CSharp/.template.config/ide.host.json b/src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/templates/AIAgentWebApi-CSharp/.template.config/ide.host.json similarity index 100% rename from src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/src/WebApiAgent/WebApiAgent-CSharp/.template.config/ide.host.json rename to src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/templates/AIAgentWebApi-CSharp/.template.config/ide.host.json diff --git a/src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/src/WebApiAgent/WebApiAgent-CSharp/.template.config/ide/agent-framework.ico b/src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/templates/AIAgentWebApi-CSharp/.template.config/ide/agent-framework.ico similarity index 100% rename from src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/src/WebApiAgent/WebApiAgent-CSharp/.template.config/ide/agent-framework.ico rename to src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/templates/AIAgentWebApi-CSharp/.template.config/ide/agent-framework.ico diff --git a/src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/src/WebApiAgent/WebApiAgent-CSharp/.template.config/template.json b/src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/templates/AIAgentWebApi-CSharp/.template.config/template.json similarity index 95% rename from src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/src/WebApiAgent/WebApiAgent-CSharp/.template.config/template.json rename to src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/templates/AIAgentWebApi-CSharp/.template.config/template.json index c4ef244e754..e61d1a68614 100644 --- a/src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/src/WebApiAgent/WebApiAgent-CSharp/.template.config/template.json +++ b/src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/templates/AIAgentWebApi-CSharp/.template.config/template.json @@ -2,12 +2,12 @@ "$schema": "http://json.schemastore.org/template", "author": "Microsoft", "classifications": [ "Common", "AI", "API", "Web", "Web API", "WebAPI", "Service" ], - "identity": "Microsoft.Agents.AI.ProjectTemplates.WebApiAgent.CSharp", + "identity": "Microsoft.Agents.AI.ProjectTemplates.AIAgentWebApi.CSharp", "name": "AI Agent Web API", "description": "A project template for creating an AI Agent Web API application.", "shortName": "aiagent-webapi", - "defaultName": "WebApiAgent", - "sourceName": "WebApiAgent-CSharp", + "defaultName": "AIAgentWebApi", + "sourceName": "AIAgentWebApi-CSharp", "preferNameDirectory": true, "tags": { "language": "C#", @@ -21,7 +21,7 @@ "path": "./README.md" }, { - "path": "./WebApiAgent-CSharp.csproj" + "path": "./AIAgentWebApi-CSharp.csproj" } ], "sources": [ @@ -170,7 +170,7 @@ "sourceVariableName": "httpPort", "fallbackVariableName": "httpPortGenerated" }, - "replaces": "5056", + "replaces": "9991", "onlyIf": [ { "after": "localhost:" @@ -197,7 +197,7 @@ "sourceVariableName": "httpsPort", "fallbackVariableName": "httpsPortGenerated" }, - "replaces": "7041", + "replaces": "9992", "onlyIf": [ { "after": "localhost:" diff --git a/src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/src/WebApiAgent/WebApiAgent-CSharp/WebApiAgent-CSharp.csproj.in b/src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/templates/AIAgentWebApi-CSharp/AIAgentWebApi-CSharp.csproj-in similarity index 57% rename from src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/src/WebApiAgent/WebApiAgent-CSharp/WebApiAgent-CSharp.csproj.in rename to src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/templates/AIAgentWebApi-CSharp/AIAgentWebApi-CSharp.csproj-in index a0363fb6848..a97b6ecd57b 100644 --- a/src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/src/WebApiAgent/WebApiAgent-CSharp/WebApiAgent-CSharp.csproj.in +++ b/src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/templates/AIAgentWebApi-CSharp/AIAgentWebApi-CSharp.csproj-in @@ -9,18 +9,18 @@ - + - - - - + + + + - + - + - + diff --git a/src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/src/WebApiAgent/WebApiAgent-CSharp/Program.cs b/src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/templates/AIAgentWebApi-CSharp/Program.cs similarity index 100% rename from src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/src/WebApiAgent/WebApiAgent-CSharp/Program.cs rename to src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/templates/AIAgentWebApi-CSharp/Program.cs diff --git a/src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/src/WebApiAgent/WebApiAgent-CSharp/Properties/launchSettings.json b/src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/templates/AIAgentWebApi-CSharp/Properties/launchSettings.json similarity index 82% rename from src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/src/WebApiAgent/WebApiAgent-CSharp/Properties/launchSettings.json rename to src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/templates/AIAgentWebApi-CSharp/Properties/launchSettings.json index 27165ad4a22..f089947ac3f 100644 --- a/src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/src/WebApiAgent/WebApiAgent-CSharp/Properties/launchSettings.json +++ b/src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/templates/AIAgentWebApi-CSharp/Properties/launchSettings.json @@ -6,7 +6,7 @@ "dotnetRunMessages": true, "launchBrowser": true, "launchUrl": "devui/", - "applicationUrl": "http://localhost:5056", + "applicationUrl": "http://localhost:9991", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } @@ -16,7 +16,7 @@ "dotnetRunMessages": true, "launchBrowser": true, "launchUrl": "devui/", - "applicationUrl": "https://localhost:7041;http://localhost:5056", + "applicationUrl": "https://localhost:9992;http://localhost:9991", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } diff --git a/src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/src/WebApiAgent/WebApiAgent-CSharp/README.md b/src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/templates/AIAgentWebApi-CSharp/README.md similarity index 99% rename from src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/src/WebApiAgent/WebApiAgent-CSharp/README.md rename to src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/templates/AIAgentWebApi-CSharp/README.md index a8811969839..eb0a525f12a 100644 --- a/src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/src/WebApiAgent/WebApiAgent-CSharp/README.md +++ b/src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/templates/AIAgentWebApi-CSharp/README.md @@ -158,8 +158,8 @@ dotnet run -lp https ``` The application will start and listen on: -- HTTP: `http://localhost:5056` -- HTTPS: `https://localhost:7041` +- HTTP: `http://localhost:9991` +- HTTPS: `https://localhost:9992` ### 3. Test the Application diff --git a/src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/src/WebApiAgent/WebApiAgent-CSharp/appsettings.json b/src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/templates/AIAgentWebApi-CSharp/appsettings.json similarity index 100% rename from src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/src/WebApiAgent/WebApiAgent-CSharp/appsettings.json rename to src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/templates/AIAgentWebApi-CSharp/appsettings.json diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/Microsoft.Extensions.AI.Templates.csproj b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/Microsoft.Extensions.AI.Templates.csproj index ab5ef554a3a..7571f225353 100644 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/Microsoft.Extensions.AI.Templates.csproj +++ b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/Microsoft.Extensions.AI.Templates.csproj @@ -1,8 +1,8 @@ - + Template - $(NetCoreTargetFrameworks) + netstandard2.0 Project templates for Microsoft.Extensions.AI. dotnet-new;templates;ai @@ -24,55 +24,42 @@ - - - - - + + + + + + + + - + + + Include="templates\AIChatWeb-CSharp\**\*" + Exclude="templates\AIChatWeb-CSharp\**\*.csproj-in" + PackagePath="content\AIChatWeb-CSharp" /> + + - - - - + Include="templates\McpServer-CSharp\**\*" + Exclude="templates\McpServer-CSharp\**\*.csproj-in" + PackagePath="content\McpServer-CSharp" /> + + + + diff --git a/src/ProjectTemplates/package.json b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/package.json similarity index 71% rename from src/ProjectTemplates/package.json rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/package.json index ff2090674f3..74a5786c461 100644 --- a/src/ProjectTemplates/package.json +++ b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/package.json @@ -6,16 +6,16 @@ "main": "index.js", "config": { "destRoot": { - "chat": "./Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/lib" + "aichatweb": "./templates/AIChatWeb-CSharp.Web/wwwroot/lib" } }, "scripts": { "copy-dependency": "node copyDependency.mjs", "copy-dependencies": "npm run copy-dompurify && npm run copy-marked && npm run copy-tailwindcss && npm run copy-pdfjs", - "copy-dompurify": "npm run copy-dependency -- --name dompurify --dest-root chat --src-root dist --files purify.es.mjs", - "copy-marked": "npm run copy-dependency -- --name marked --dest-root chat --src-root lib --files marked.esm.js", - "copy-tailwindcss": "npm run copy-dependency -- --name tailwindcss --dest-root chat --files preflight.css", - "copy-pdfjs": "npm run copy-dependency -- --name pdfjs-dist --dest-root chat --files build/pdf.min.mjs;build/pdf.worker.min.mjs;web/pdf_viewer.css;web/pdf_viewer.mjs;web/images/loading-icon.gif" + "copy-dompurify": "npm run copy-dependency -- --name dompurify --dest-root aichatweb --src-root dist --files purify.es.mjs", + "copy-marked": "npm run copy-dependency -- --name marked --dest-root aichatweb --src-root lib --files marked.esm.js", + "copy-tailwindcss": "npm run copy-dependency -- --name tailwindcss --dest-root aichatweb --files preflight.css", + "copy-pdfjs": "npm run copy-dependency -- --name pdfjs-dist --dest-root aichatweb --files build/pdf.min.mjs;build/pdf.worker.min.mjs;web/pdf_viewer.css;web/pdf_viewer.mjs;web/images/loading-icon.gif" }, "repository": { "type": "git", diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Directory.Build.targets.in b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Directory.Build.targets.in deleted file mode 100644 index f63c2a79144..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Directory.Build.targets.in +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - <_LocalChatTemplateVariant>${LocalChatTemplateVariant} - - - - - - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/Directory.Build.props.in b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/Directory.Build.props.in deleted file mode 100644 index 0eb47a5ac25..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/Directory.Build.props.in +++ /dev/null @@ -1,5 +0,0 @@ - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/Directory.Build.targets.in b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/Directory.Build.targets.in deleted file mode 100644 index 08d54995389..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/Directory.Build.targets.in +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/NuGet.config.in b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/NuGet.config.in deleted file mode 100644 index 76020d40e7f..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/NuGet.config.in +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/.template.config/dotnetcli.host.json b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/.template.config/dotnetcli.host.json similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/.template.config/dotnetcli.host.json rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/.template.config/dotnetcli.host.json diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/.template.config/ide.host.json b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/.template.config/ide.host.json similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/.template.config/ide.host.json rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/.template.config/ide.host.json diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/.template.config/ide/icon.ico b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/.template.config/ide/icon.ico similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/.template.config/ide/icon.ico rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/.template.config/ide/icon.ico diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/.template.config/template.json b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/.template.config/template.json similarity index 93% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/.template.config/template.json rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/.template.config/template.json index 54b38545be5..edaa71d617d 100644 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/.template.config/template.json +++ b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/.template.config/template.json @@ -7,7 +7,7 @@ "description": "A project template for creating an AI chat application, which uses retrieval-augmented generation (RAG) to chat with your own data.", "shortName": "aichatweb", "defaultName": "ChatApp", - "sourceName": "ChatWithCustomData-CSharp", + "sourceName": "AIChatWeb-CSharp", "preferNameDirectory": true, "tags": { "language": "C#", @@ -27,23 +27,23 @@ }, { "condition": "(!IsAspire)", - "path": "./ChatWithCustomData-CSharp.csproj" + "path": "./AIChatWeb-CSharp.csproj" }, { "condition": "(IsAspire && (hostIdentifier == \"dotnetcli\" || hostIdentifier == \"dotnetcli-preview\"))", - "path": "./ChatWithCustomData-CSharp.sln" + "path": "./AIChatWeb-CSharp.sln" }, { "condition": "(IsAspire)", - "path": "./ChatWithCustomData-CSharp.AppHost/ChatWithCustomData-CSharp.AppHost.csproj" + "path": "./AIChatWeb-CSharp.AppHost/AIChatWeb-CSharp.AppHost.csproj" }, { "condition": "(IsAspire)", - "path": "./ChatWithCustomData-CSharp.ServiceDefaults/ChatWithCustomData-CSharp.ServiceDefaults.csproj" + "path": "./AIChatWeb-CSharp.ServiceDefaults/AIChatWeb-CSharp.ServiceDefaults.csproj" }, { "condition": "(IsAspire)", - "path": "./ChatWithCustomData-CSharp.Web/ChatWithCustomData-CSharp.Web.csproj" + "path": "./AIChatWeb-CSharp.Web/AIChatWeb-CSharp.Web.csproj" } ], "sources": [{ @@ -53,13 +53,13 @@ { "condition": "(!IsAspire)", "rename": { - "ChatWithCustomData-CSharp.Web/ChatWithCustomData-CSharp.Web.csproj": "ChatWithCustomData-CSharp.csproj", - "ChatWithCustomData-CSharp.Web/": "./" + "AIChatWeb-CSharp.Web/AIChatWeb-CSharp.Web.csproj": "AIChatWeb-CSharp.csproj", + "AIChatWeb-CSharp.Web/": "./" }, "exclude": [ - "ChatWithCustomData-CSharp.AppHost/**", - "ChatWithCustomData-CSharp.ServiceDefaults/**", - "ChatWithCustomData-CSharp.Web/Program.Aspire.cs", + "AIChatWeb-CSharp.AppHost/**", + "AIChatWeb-CSharp.ServiceDefaults/**", + "AIChatWeb-CSharp.Web/Program.Aspire.cs", "README.Aspire.md", "*.sln" ] @@ -67,20 +67,20 @@ { "condition": "(!IsAspire || !IsOllama)", "exclude": [ - "ChatWithCustomData-CSharp.Web/OllamaResilienceHandlerExtensions.cs" + "AIChatWeb-CSharp.Web/OllamaResilienceHandlerExtensions.cs" ] }, { "condition": "(IsAspire)", "exclude": [ - "ChatWithCustomData-CSharp.Web/Services/Ingestion/PdfPigReader.cs" + "AIChatWeb-CSharp.Web/Services/Ingestion/PdfPigReader.cs" ] }, { "condition": "(IsAspire)", "exclude": [ - "ChatWithCustomData-CSharp.Web/Program.cs", - "ChatWithCustomData-CSharp.Web/README.md" + "AIChatWeb-CSharp.Web/Program.cs", + "AIChatWeb-CSharp.Web/README.md" ], "rename": { "Program.Aspire.cs": "Program.cs", @@ -96,7 +96,7 @@ { "condition": "(!IsLocalVectorStore)", "exclude": [ - "ChatWithCustomData-CSharp.Web/Services/JsonVectorStore.cs" + "AIChatWeb-CSharp.Web/Services/JsonVectorStore.cs" ] } ] @@ -521,22 +521,22 @@ "type": "derived", "valueSource": "name", "valueTransform": "vectorStoreIndexNameTransform", - "replaces": "data-ChatWithCustomData-CSharp.Web-" + "replaces": "data-AIChatWeb-CSharp.Web-" }, "aspireClassNameReplacer": { "type": "derived", "valueSource": "name", "valueTransform": "aspireClassName_ReplaceInvalidChars", - "replaces": "ChatWithCustomData_CSharp_Web_AspireClassName" + "replaces": "AIChatWeb_CSharp_Web_AspireClassName" }, "webProjectNamespaceAdjuster": { "type": "generated", "generator": "switch", "replaces": ".Web", "onlyIf": [{ - "after": "ChatWithCustomData_CSharp" + "after": "AIChatWeb_CSharp" }, { - "after": "ChatWithCustomData-CSharp" + "after": "AIChatWeb-CSharp" }], "parameters": { "evaluator": "C++", diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.AppHost/ChatWithCustomData-CSharp.AppHost.csproj.in b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.AppHost/AIChatWeb-CSharp.AppHost.csproj-in similarity index 63% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.AppHost/ChatWithCustomData-CSharp.AppHost.csproj.in rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.AppHost/AIChatWeb-CSharp.AppHost.csproj-in index 8d0e2a3a011..efaf93c8114 100644 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.AppHost/ChatWithCustomData-CSharp.AppHost.csproj.in +++ b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.AppHost/AIChatWeb-CSharp.AppHost.csproj-in @@ -1,6 +1,6 @@ - + Exe @@ -11,21 +11,21 @@ - + - + - + diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.AppHost/AppHost.cs b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.AppHost/AppHost.cs similarity index 96% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.AppHost/AppHost.cs rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.AppHost/AppHost.cs index c1ca040558b..3304884fa78 100644 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.AppHost/AppHost.cs +++ b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.AppHost/AppHost.cs @@ -55,7 +55,7 @@ .WithArgs("--http", "--host", "0.0.0.0", "--port", "3001") .WithHttpEndpoint(targetPort: 3001, name: "http"); -var webApp = builder.AddProject("aichatweb-app"); +var webApp = builder.AddProject("aichatweb-app"); #if (IsOllama) // AI SERVICE PROVIDER REFERENCES webApp .WithReference(chat) diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.AppHost/Properties/launchSettings.json b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.AppHost/Properties/launchSettings.json similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.AppHost/Properties/launchSettings.json rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.AppHost/Properties/launchSettings.json diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.AppHost/appsettings.Development.json b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.AppHost/appsettings.Development.json similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.AppHost/appsettings.Development.json rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.AppHost/appsettings.Development.json diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.AppHost/appsettings.json b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.AppHost/appsettings.json similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.AppHost/appsettings.json rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.AppHost/appsettings.json diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.ServiceDefaults/ChatWithCustomData-CSharp.ServiceDefaults.csproj.in b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.ServiceDefaults/AIChatWeb-CSharp.ServiceDefaults.csproj-in similarity index 60% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.ServiceDefaults/ChatWithCustomData-CSharp.ServiceDefaults.csproj.in rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.ServiceDefaults/AIChatWeb-CSharp.ServiceDefaults.csproj-in index 814c86384e7..ea596fc2036 100644 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.ServiceDefaults/ChatWithCustomData-CSharp.ServiceDefaults.csproj.in +++ b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.ServiceDefaults/AIChatWeb-CSharp.ServiceDefaults.csproj-in @@ -10,13 +10,13 @@ - - - - - - - + + + + + + + diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.ServiceDefaults/Extensions.cs b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.ServiceDefaults/Extensions.cs similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.ServiceDefaults/Extensions.cs rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.ServiceDefaults/Extensions.cs diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/ChatWithCustomData-CSharp.Web.csproj.in b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/AIChatWeb-CSharp.Web.csproj-in similarity index 55% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/ChatWithCustomData-CSharp.Web.csproj.in rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/AIChatWeb-CSharp.Web.csproj-in index d10c4cafd7e..9217a66b599 100644 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/ChatWithCustomData-CSharp.Web.csproj.in +++ b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/AIChatWeb-CSharp.Web.csproj-in @@ -9,57 +9,57 @@ - - + + - + - + - - - + + + - + - + - - + + - + - - + + - + - + diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/App.razor b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/App.razor similarity index 87% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/App.razor rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/App.razor index cdb94f6074b..b29ed3901dc 100644 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/App.razor +++ b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/App.razor @@ -6,7 +6,7 @@ - + diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Layout/LoadingSpinner.razor b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Layout/LoadingSpinner.razor similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Layout/LoadingSpinner.razor rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Layout/LoadingSpinner.razor diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Layout/LoadingSpinner.razor.css b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Layout/LoadingSpinner.razor.css similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Layout/LoadingSpinner.razor.css rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Layout/LoadingSpinner.razor.css diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Layout/MainLayout.razor b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Layout/MainLayout.razor similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Layout/MainLayout.razor rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Layout/MainLayout.razor diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Layout/MainLayout.razor.css b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Layout/MainLayout.razor.css similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Layout/MainLayout.razor.css rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Layout/MainLayout.razor.css diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Layout/SurveyPrompt.razor b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Layout/SurveyPrompt.razor similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Layout/SurveyPrompt.razor rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Layout/SurveyPrompt.razor diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Layout/SurveyPrompt.razor.css b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Layout/SurveyPrompt.razor.css similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Layout/SurveyPrompt.razor.css rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Layout/SurveyPrompt.razor.css diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Pages/Chat/Chat.razor b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Pages/Chat/Chat.razor similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Pages/Chat/Chat.razor rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Pages/Chat/Chat.razor diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Pages/Chat/Chat.razor.css b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Pages/Chat/Chat.razor.css similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Pages/Chat/Chat.razor.css rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Pages/Chat/Chat.razor.css diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Pages/Chat/ChatCitation.razor b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Pages/Chat/ChatCitation.razor similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Pages/Chat/ChatCitation.razor rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Pages/Chat/ChatCitation.razor diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Pages/Chat/ChatCitation.razor.css b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Pages/Chat/ChatCitation.razor.css similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Pages/Chat/ChatCitation.razor.css rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Pages/Chat/ChatCitation.razor.css diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Pages/Chat/ChatHeader.razor b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Pages/Chat/ChatHeader.razor similarity index 90% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Pages/Chat/ChatHeader.razor rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Pages/Chat/ChatHeader.razor index c6194fb6c3c..5e16ddcf717 100644 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Pages/Chat/ChatHeader.razor +++ b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Pages/Chat/ChatHeader.razor @@ -8,7 +8,7 @@ -

ChatWithCustomData-CSharp.Web

+

AIChatWeb-CSharp.Web

@code { diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Pages/Chat/ChatHeader.razor.css b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Pages/Chat/ChatHeader.razor.css similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Pages/Chat/ChatHeader.razor.css rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Pages/Chat/ChatHeader.razor.css diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Pages/Chat/ChatInput.razor b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Pages/Chat/ChatInput.razor similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Pages/Chat/ChatInput.razor rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Pages/Chat/ChatInput.razor diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Pages/Chat/ChatInput.razor.css b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Pages/Chat/ChatInput.razor.css similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Pages/Chat/ChatInput.razor.css rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Pages/Chat/ChatInput.razor.css diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Pages/Chat/ChatInput.razor.js b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Pages/Chat/ChatInput.razor.js similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Pages/Chat/ChatInput.razor.js rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Pages/Chat/ChatInput.razor.js diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Pages/Chat/ChatMessageItem.razor b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Pages/Chat/ChatMessageItem.razor similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Pages/Chat/ChatMessageItem.razor rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Pages/Chat/ChatMessageItem.razor diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Pages/Chat/ChatMessageItem.razor.css b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Pages/Chat/ChatMessageItem.razor.css similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Pages/Chat/ChatMessageItem.razor.css rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Pages/Chat/ChatMessageItem.razor.css diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Pages/Chat/ChatMessageList.razor b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Pages/Chat/ChatMessageList.razor similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Pages/Chat/ChatMessageList.razor rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Pages/Chat/ChatMessageList.razor diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Pages/Chat/ChatMessageList.razor.css b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Pages/Chat/ChatMessageList.razor.css similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Pages/Chat/ChatMessageList.razor.css rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Pages/Chat/ChatMessageList.razor.css diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Pages/Chat/ChatMessageList.razor.js b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Pages/Chat/ChatMessageList.razor.js similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Pages/Chat/ChatMessageList.razor.js rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Pages/Chat/ChatMessageList.razor.js diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Pages/Chat/ChatSuggestions.razor b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Pages/Chat/ChatSuggestions.razor similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Pages/Chat/ChatSuggestions.razor rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Pages/Chat/ChatSuggestions.razor diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Pages/Chat/ChatSuggestions.razor.css b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Pages/Chat/ChatSuggestions.razor.css similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Pages/Chat/ChatSuggestions.razor.css rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Pages/Chat/ChatSuggestions.razor.css diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Pages/Error.razor b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Pages/Error.razor similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Pages/Error.razor rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Pages/Error.razor diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Routes.razor b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Routes.razor similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/Routes.razor rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/Routes.razor diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/_Imports.razor b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/_Imports.razor similarity index 66% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/_Imports.razor rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/_Imports.razor index 9ad55554648..7464a453aee 100644 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Components/_Imports.razor +++ b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Components/_Imports.razor @@ -7,7 +7,7 @@ @using Microsoft.AspNetCore.Components.Web.Virtualization @using Microsoft.Extensions.AI @using Microsoft.JSInterop -@using ChatWithCustomData_CSharp.Web -@using ChatWithCustomData_CSharp.Web.Components -@using ChatWithCustomData_CSharp.Web.Components.Layout -@using ChatWithCustomData_CSharp.Web.Services +@using AIChatWeb_CSharp.Web +@using AIChatWeb_CSharp.Web.Components +@using AIChatWeb_CSharp.Web.Components.Layout +@using AIChatWeb_CSharp.Web.Services diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/OllamaResilienceHandlerExtensions.cs b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/OllamaResilienceHandlerExtensions.cs similarity index 95% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/OllamaResilienceHandlerExtensions.cs rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/OllamaResilienceHandlerExtensions.cs index fed9c91ca93..4454d8a5577 100644 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/OllamaResilienceHandlerExtensions.cs +++ b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/OllamaResilienceHandlerExtensions.cs @@ -1,7 +1,7 @@ using System; using Microsoft.Extensions.DependencyInjection; -namespace ChatWithCustomData_CSharp.Web.Services; +namespace AIChatWeb_CSharp.Web.Services; public static class OllamaResilienceHandlerExtensions { @@ -31,4 +31,3 @@ public static IServiceCollection AddOllamaResilienceHandler(this IServiceCollect return services; } } - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Program.Aspire.cs b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Program.Aspire.cs similarity index 94% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Program.Aspire.cs rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Program.Aspire.cs index 898b61efc53..31442718f1f 100644 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Program.Aspire.cs +++ b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Program.Aspire.cs @@ -2,9 +2,9 @@ #if (IsOpenAI || IsGHModels) using OpenAI; #endif -using ChatWithCustomData_CSharp.Web.Components; -using ChatWithCustomData_CSharp.Web.Services; -using ChatWithCustomData_CSharp.Web.Services.Ingestion; +using AIChatWeb_CSharp.Web.Components; +using AIChatWeb_CSharp.Web.Services; +using AIChatWeb_CSharp.Web.Services.Ingestion; var builder = WebApplication.CreateBuilder(args); builder.AddServiceDefaults(); diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Program.cs b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Program.cs similarity index 97% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Program.cs rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Program.cs index a51a674cf71..4b041f4a15f 100644 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Program.cs +++ b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Program.cs @@ -14,9 +14,9 @@ #elif (IsGHModels || IsOpenAI || IsAzureOpenAI) using OpenAI; #endif -using ChatWithCustomData_CSharp.Web.Components; -using ChatWithCustomData_CSharp.Web.Services; -using ChatWithCustomData_CSharp.Web.Services.Ingestion; +using AIChatWeb_CSharp.Web.Components; +using AIChatWeb_CSharp.Web.Services; +using AIChatWeb_CSharp.Web.Services.Ingestion; var builder = WebApplication.CreateBuilder(args); builder.Services.AddRazorComponents().AddInteractiveServerComponents(); diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Properties/launchSettings.json b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Properties/launchSettings.json similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Properties/launchSettings.json rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Properties/launchSettings.json diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/README.md b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/README.md similarity index 98% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/README.md rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/README.md index 88dff74d315..14677ca5372 100644 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/README.md +++ b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/README.md @@ -168,7 +168,7 @@ To use Azure AI Search, you will need an Azure account and an Azure AI Search re ### 1. Create an Azure AI Search Resource Follow the instructions in the [Azure portal](https://portal.azure.com/) to create an Azure AI Search resource. Note that there is a free tier for the service but it is not currently the default setting on the portal. -Note that if you previously used the same Azure AI Search resource with different model using this project name, you may need to delete your `data-ChatWithCustomData-CSharp.Web-chunks` and `data-ChatWithCustomData-CSharp.Web-documents` indexes using the [Azure portal](https://portal.azure.com/) first before continuing; otherwise, data ingestion may fail due to a vector dimension mismatch. +Note that if you previously used the same Azure AI Search resource with different model using this project name, you may need to delete your `data-AIChatWeb-CSharp.Web-chunks` and `data-AIChatWeb-CSharp.Web-documents` indexes using the [Azure portal](https://portal.azure.com/) first before continuing; otherwise, data ingestion may fail due to a vector dimension mismatch. #### ---#if (IsManagedIdentity) ### 2. Configure Azure AI Search for Keyless Authentication diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Services/IngestedChunk.cs b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Services/IngestedChunk.cs similarity index 90% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Services/IngestedChunk.cs rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Services/IngestedChunk.cs index 9316ee1dcfb..60e6b5684e4 100644 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Services/IngestedChunk.cs +++ b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Services/IngestedChunk.cs @@ -1,7 +1,7 @@ using System.Text.Json.Serialization; using Microsoft.Extensions.VectorData; -namespace ChatWithCustomData_CSharp.Web.Services; +namespace AIChatWeb_CSharp.Web.Services; public class IngestedChunk { @@ -15,7 +15,7 @@ public class IngestedChunk #else public const string VectorDistanceFunction = DistanceFunction.CosineDistance; #endif - public const string CollectionName = "data-ChatWithCustomData-CSharp.Web-chunks"; + public const string CollectionName = "data-AIChatWeb-CSharp.Web-chunks"; [VectorStoreKey(StorageName = "key")] [JsonPropertyName("key")] diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Services/Ingestion/DataIngestor.cs b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Services/Ingestion/DataIngestor.cs similarity index 95% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Services/Ingestion/DataIngestor.cs rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Services/Ingestion/DataIngestor.cs index af23c29f13c..c573403e618 100644 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Services/Ingestion/DataIngestor.cs +++ b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Services/Ingestion/DataIngestor.cs @@ -4,7 +4,7 @@ using Microsoft.Extensions.VectorData; using Microsoft.ML.Tokenizers; -namespace ChatWithCustomData_CSharp.Web.Services.Ingestion; +namespace AIChatWeb_CSharp.Web.Services.Ingestion; public class DataIngestor( ILogger logger, diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Services/Ingestion/DocumentReader.cs b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Services/Ingestion/DocumentReader.cs similarity index 96% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Services/Ingestion/DocumentReader.cs rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Services/Ingestion/DocumentReader.cs index 5122cde3e9a..0a27e628326 100644 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Services/Ingestion/DocumentReader.cs +++ b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Services/Ingestion/DocumentReader.cs @@ -1,6 +1,6 @@ using Microsoft.Extensions.DataIngestion; -namespace ChatWithCustomData_CSharp.Web.Services.Ingestion; +namespace AIChatWeb_CSharp.Web.Services.Ingestion; internal sealed class DocumentReader(DirectoryInfo rootDirectory) : IngestionDocumentReader { diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Services/Ingestion/PdfPigReader.cs b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Services/Ingestion/PdfPigReader.cs similarity index 95% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Services/Ingestion/PdfPigReader.cs rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Services/Ingestion/PdfPigReader.cs index 2e1ef18494d..ab8d61ac558 100644 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Services/Ingestion/PdfPigReader.cs +++ b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Services/Ingestion/PdfPigReader.cs @@ -4,7 +4,7 @@ using UglyToad.PdfPig.DocumentLayoutAnalysis.PageSegmenter; using UglyToad.PdfPig.DocumentLayoutAnalysis.WordExtractor; -namespace ChatWithCustomData_CSharp.Web.Services.Ingestion; +namespace AIChatWeb_CSharp.Web.Services.Ingestion; internal sealed class PdfPigReader : IngestionDocumentReader { diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Services/SemanticSearch.cs b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Services/SemanticSearch.cs similarity index 90% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Services/SemanticSearch.cs rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Services/SemanticSearch.cs index fb0c2eccef0..49bef8de3d1 100644 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/Services/SemanticSearch.cs +++ b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/Services/SemanticSearch.cs @@ -1,7 +1,7 @@ -using ChatWithCustomData_CSharp.Web.Services.Ingestion; +using AIChatWeb_CSharp.Web.Services.Ingestion; using Microsoft.Extensions.VectorData; -namespace ChatWithCustomData_CSharp.Web.Services; +namespace AIChatWeb_CSharp.Web.Services; public class SemanticSearch( #if (IsQdrant) diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/appsettings.Development.json b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/appsettings.Development.json similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/appsettings.Development.json rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/appsettings.Development.json diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/appsettings.json b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/appsettings.json similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/appsettings.json rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/appsettings.json diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/Data/Example_Emergency_Survival_Kit.pdf b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/Data/Example_Emergency_Survival_Kit.pdf similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/Data/Example_Emergency_Survival_Kit.pdf rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/Data/Example_Emergency_Survival_Kit.pdf diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/Data/Example_GPS_Watch.md b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/Data/Example_GPS_Watch.md similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/Data/Example_GPS_Watch.md rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/Data/Example_GPS_Watch.md diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/app.css b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/app.css similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/app.css rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/app.css diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/app.js b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/app.js similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/app.js rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/app.js diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/favicon.ico b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/favicon.ico similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/favicon.ico rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/favicon.ico diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/lib/dompurify/README.md b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/lib/dompurify/README.md similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/lib/dompurify/README.md rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/lib/dompurify/README.md diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/lib/dompurify/dist/purify.es.mjs b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/lib/dompurify/dist/purify.es.mjs similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/lib/dompurify/dist/purify.es.mjs rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/lib/dompurify/dist/purify.es.mjs diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/lib/markdown_viewer/viewer.html b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/lib/markdown_viewer/viewer.html similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/lib/markdown_viewer/viewer.html rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/lib/markdown_viewer/viewer.html diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/lib/markdown_viewer/viewer.mjs b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/lib/markdown_viewer/viewer.mjs similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/lib/markdown_viewer/viewer.mjs rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/lib/markdown_viewer/viewer.mjs diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/lib/marked/README.md b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/lib/marked/README.md similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/lib/marked/README.md rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/lib/marked/README.md diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/lib/marked/dist/marked.esm.js b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/lib/marked/dist/marked.esm.js similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/lib/marked/dist/marked.esm.js rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/lib/marked/dist/marked.esm.js diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/lib/pdf_viewer/viewer.html b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/lib/pdf_viewer/viewer.html similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/lib/pdf_viewer/viewer.html rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/lib/pdf_viewer/viewer.html diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/lib/pdf_viewer/viewer.mjs b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/lib/pdf_viewer/viewer.mjs similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/lib/pdf_viewer/viewer.mjs rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/lib/pdf_viewer/viewer.mjs diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/lib/pdfjs-dist/README.md b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/lib/pdfjs-dist/README.md similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/lib/pdfjs-dist/README.md rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/lib/pdfjs-dist/README.md diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/lib/pdfjs-dist/dist/build/pdf.min.mjs b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/lib/pdfjs-dist/dist/build/pdf.min.mjs similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/lib/pdfjs-dist/dist/build/pdf.min.mjs rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/lib/pdfjs-dist/dist/build/pdf.min.mjs diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/lib/pdfjs-dist/dist/build/pdf.worker.min.mjs b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/lib/pdfjs-dist/dist/build/pdf.worker.min.mjs similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/lib/pdfjs-dist/dist/build/pdf.worker.min.mjs rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/lib/pdfjs-dist/dist/build/pdf.worker.min.mjs diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/lib/pdfjs-dist/dist/web/images/loading-icon.gif b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/lib/pdfjs-dist/dist/web/images/loading-icon.gif similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/lib/pdfjs-dist/dist/web/images/loading-icon.gif rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/lib/pdfjs-dist/dist/web/images/loading-icon.gif diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.css b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.css similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.css rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.css diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.mjs b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.mjs similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.mjs rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.mjs diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/lib/tailwindcss/README.md b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/lib/tailwindcss/README.md similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/lib/tailwindcss/README.md rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/lib/tailwindcss/README.md diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/lib/tailwindcss/dist/preflight.css b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/lib/tailwindcss/dist/preflight.css similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.Web/wwwroot/lib/tailwindcss/dist/preflight.css rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.Web/wwwroot/lib/tailwindcss/dist/preflight.css diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.sln.in b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.sln similarity index 70% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.sln.in rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.sln index aa1c261a2a3..0959f5ab945 100644 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData-CSharp.sln.in +++ b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/AIChatWeb-CSharp.sln @@ -3,11 +3,11 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.31903.59 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ChatWithCustomData-CSharp.AppHost", "ChatWithCustomData-CSharp.AppHost\ChatWithCustomData-CSharp.AppHost.csproj", "{4DF52F58-4890-4A0A-BC25-5C3D167B3490}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AIChatWeb-CSharp.AppHost", "AIChatWeb-CSharp.AppHost\AIChatWeb-CSharp.AppHost.csproj", "{4DF52F58-4890-4A0A-BC25-5C3D167B3490}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ChatWithCustomData-CSharp.ServiceDefaults", "ChatWithCustomData-CSharp.ServiceDefaults\ChatWithCustomData-CSharp.ServiceDefaults.csproj", "{2222CF31-6E3A-42E7-AD3A-A56B14EAD9D0}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AIChatWeb-CSharp.ServiceDefaults", "AIChatWeb-CSharp.ServiceDefaults\AIChatWeb-CSharp.ServiceDefaults.csproj", "{2222CF31-6E3A-42E7-AD3A-A56B14EAD9D0}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ChatWithCustomData-CSharp.Web", "ChatWithCustomData-CSharp.Web\ChatWithCustomData-CSharp.Web.csproj", "{A7D19173-F0AD-4A8D-B8EA-E12DE203E409}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AIChatWeb-CSharp.Web", "AIChatWeb-CSharp.Web\AIChatWeb-CSharp.Web.csproj", "{A7D19173-F0AD-4A8D-B8EA-E12DE203E409}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/README.Aspire.md b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/README.Aspire.md similarity index 91% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/README.Aspire.md rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/README.Aspire.md index f30fcbfcf2e..0fff810489c 100644 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/README.Aspire.md +++ b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/AIChatWeb-CSharp/README.Aspire.md @@ -27,7 +27,7 @@ To use models hosted by GitHub Models, you will need to create a GitHub personal #### ---#if (hostIdentifier == "vs") Configure your token for this project using .NET User Secrets: -1. In Visual Studio, right-click on the ChatWithCustomData-CSharp.AppHost project in the Solution Explorer and select "Manage User Secrets". +1. In Visual Studio, right-click on the AIChatWeb-CSharp.AppHost project in the Solution Explorer and select "Manage User Secrets". 2. This opens a `secrets.json` file where you can store your API keys without them being tracked in source control. Add the following key and value: ```json @@ -39,7 +39,7 @@ Configure your token for this project using .NET User Secrets: From the command line, configure your token for this project using .NET User Secrets by running the following commands: ```sh -cd ChatWithCustomData-CSharp.AppHost +cd AIChatWeb-CSharp.AppHost dotnet user-secrets set ConnectionStrings:openai "Endpoint=https://models.inference.ai.azure.com;Key=YOUR-API-KEY" ``` #### ---#endif @@ -54,7 +54,7 @@ To call the OpenAI REST API, you will need an API key. To obtain one, first [cre #### ---#if (hostIdentifier == "vs") Configure your API key for this project, using .NET User Secrets: -1. In Visual Studio, right-click on the ChatWithCustomData-CSharp.AppHost project in the Solution Explorer and select "Manage User Secrets". +1. In Visual Studio, right-click on the AIChatWeb-CSharp.AppHost project in the Solution Explorer and select "Manage User Secrets". 2. This will open a secrets.json file where you can store your API key without them being tracked in source control. Add the following key and value to the file: ```json @@ -67,7 +67,7 @@ Configure your API key for this project, using .NET User Secrets: From the command line, configure your API key for this project using .NET User Secrets by running the following commands: ```sh -cd ChatWithCustomData-CSharp.AppHost +cd AIChatWeb-CSharp.AppHost dotnet user-secrets set ConnectionStrings:openai "Key=YOUR-API-KEY" ``` #### ---#endif @@ -108,7 +108,7 @@ Note: Qdrant and Docker are excellent open source products, but are not maintain 1. Open the project folder in Visual Studio Code. 2. Install the [C# Dev Kit extension](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csdevkit) for Visual Studio Code. -3. Once installed, Open the `Program.cs` file in the ChatWithCustomData-CSharp.AppHost project. +3. Once installed, Open the `Program.cs` file in the AIChatWeb-CSharp.AppHost project. 4. Run the project by clicking the "Run" button in the Debug view. ## Trust the localhost certificate @@ -119,7 +119,7 @@ See [Troubleshoot untrusted localhost certificate in Aspire](https://learn.micro # Updating JavaScript dependencies -This template leverages JavaScript libraries to provide essential functionality. These libraries are located in the wwwroot/lib folder of the ChatWithCustomData-CSharp.Web project. For instructions on updating each dependency, please refer to the README.md file in each respective folder. +This template leverages JavaScript libraries to provide essential functionality. These libraries are located in the wwwroot/lib folder of the AIChatWeb-CSharp.Web project. For instructions on updating each dependency, please refer to the README.md file in each respective folder. # Learn More To learn more about development with .NET and AI, check out the following links: diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/McpServer/McpServer-CSharp/.mcp/server.json b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp/.mcp/server.json similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/McpServer/McpServer-CSharp/.mcp/server.json rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp/.mcp/server.json diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/McpServer/McpServer-CSharp/.template.config/dotnetcli.host.json b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp/.template.config/dotnetcli.host.json similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/McpServer/McpServer-CSharp/.template.config/dotnetcli.host.json rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp/.template.config/dotnetcli.host.json diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/McpServer/McpServer-CSharp/.template.config/ide.host.json b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp/.template.config/ide.host.json similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/McpServer/McpServer-CSharp/.template.config/ide.host.json rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp/.template.config/ide.host.json diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/McpServer/McpServer-CSharp/.template.config/ide/icon.ico b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp/.template.config/ide/icon.ico similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/McpServer/McpServer-CSharp/.template.config/ide/icon.ico rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp/.template.config/ide/icon.ico diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/McpServer/McpServer-CSharp/.template.config/template.json b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp/.template.config/template.json similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/McpServer/McpServer-CSharp/.template.config/template.json rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp/.template.config/template.json diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/McpServer/McpServer-CSharp/McpServer-CSharp.csproj.in b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp/McpServer-CSharp.csproj-in similarity index 94% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/McpServer/McpServer-CSharp/McpServer-CSharp.csproj.in rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp/McpServer-CSharp.csproj-in index 799d5845c32..ae86a5b9475 100644 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/McpServer/McpServer-CSharp/McpServer-CSharp.csproj.in +++ b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp/McpServer-CSharp.csproj-in @@ -46,8 +46,8 @@ - - + +
diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/McpServer/McpServer-CSharp/Program.cs b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp/Program.cs similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/McpServer/McpServer-CSharp/Program.cs rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp/Program.cs diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/McpServer/McpServer-CSharp/README.md b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp/README.md similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/McpServer/McpServer-CSharp/README.md rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp/README.md diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/McpServer/McpServer-CSharp/Tools/RandomNumberTools.cs b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp/Tools/RandomNumberTools.cs similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/McpServer/McpServer-CSharp/Tools/RandomNumberTools.cs rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp/Tools/RandomNumberTools.cs diff --git a/src/ProjectTemplates/README.md b/src/ProjectTemplates/README.md index f527c08d74e..335a3881d96 100644 --- a/src/ProjectTemplates/README.md +++ b/src/ProjectTemplates/README.md @@ -2,10 +2,12 @@ ## Updating project template JavaScript dependencies -To update project template JavaScript dependencies: +The AIChatWeb project template within Microsoft.Extensions.AI.Templates bundles JavaScript dependencies into the package. To update those project template JavaScript dependencies: + +1. Navigate into the root of the Microsoft.Extensions.AI.Templates directory 1. Install a recent build of Node.js 2. Update the `package.json` file with added or updated dependencies -3. Run the following commands from this directory: +3. Run the following commands: ```sh npm install npm run copy-dependencies @@ -23,7 +25,7 @@ There are template execution tests in the `test/ProjectTemplates` folders that c However, CG can't detect JS dependencies by scanning execution test output, because the generated projects don't contain manifests describing JS dependencies. Instead, we have a `package.json` and `package-lock.json` in the same folder as this README that define which JS dependencies get included in the template and how they get copied into template content (see previous section in this document). CG then automatically tracks packages listed in this `package-lock.json`. -## Build the templates using just-built library package versions +## Build the templates By default the templates use just-built versions of library packages from this repository, so NuGet packages must be produced before the templates can be run: @@ -35,24 +37,84 @@ By default the templates use just-built versions of library packages from this r Once the library packages are built, the template packages can be built with references to the local package versions using the following commands: ```pwsh -.\build.cmd -pack -projects .\src\ProjectTemplates\Microsoft.Agents.AI.ProjectTemplates\Microsoft.Extensions.AI.Templates.csproj -.\build.cmd -pack -projects .\src\ProjectTemplates\Microsoft.Extensions.AI.Templates\Microsoft.Extensions.AI.Templates.csproj +.\build.cmd -build -pack -projects .\src\ProjectTemplates\Microsoft.Agents.AI.ProjectTemplates\Microsoft.Agents.AI.ProjectTemplates.csproj +.\build.cmd -build -pack -projects .\src\ProjectTemplates\Microsoft.Extensions.AI.Templates\Microsoft.Extensions.AI.Templates.csproj ``` -## Build the templates using pinned library package versions +## Package references in the project templates -The templates can also be built to reference pinned versions of the library packages. This approach is used when a templates package is updated off-cycle from the library packages. The pinned versions are hard-coded in the `GeneratedContent.targets` file in this directory. To build the templates package using the pinned versions, run: +The `Directory.Build.targets` file defines and configures the necessary targets for processing package references in the project template to insert the package versions into the produced `.csproj` files. -```pwsh -.\build.cmd -pack -projects .\src\ProjectTemplates\Microsoft.Agents.AI.ProjectTemplates\Microsoft.Agents.AI.ProjectTemplates.csproj /p:TemplateUsePinnedPackageVersions=true -.\build.cmd -pack -projects .\src\ProjectTemplates\Microsoft.Extensions.AI.Templates\Microsoft.Extensions.AI.Templates.csproj /p:TemplateUsePinnedPackageVersions=true +Template projects can reference packages either with pinned `` or have versions resolved from projects within the repository using `` items. If both a `` and `` are specified, the version from +the `` is used. + +```xml + + + + + + + + + + + ``` -Setting `/p:TemplateUsePinnedPackageVersions=true` will apply three different categories of pinned package versions: +Files in the template that need to reference the resolved versions must be pre-processed as generated template content. While this works with any text file, it is typically used with `.csproj` files. This is accomplished by: + +1. Rename the `.csproj` file to `.csproj-in` +2. Exclude the `.csproj-in` file from the project `` +3. Include the `.csproj-in` file in the project's `` + +**Project template project** +```xml + + -1. Packages from this repository that are _not_ part of `Microsoft.Extensions.AI*`, namely `Microsoft.Extensions.Http.Resilience` -2. Packages from this repository that _are_ part of `Microsoft.Extensions.AI*` -3. The `Microsoft.EntityFrameworkCoreSqlite` package + + + + +``` + +Note that for the 'ChangeExtension' behavior to work, the extension to be replaced cannot contain a '.'. Therefore, `.csproj.in` cannot be used, which is why `.csproj-in` is used instead. This is true for any extension, so `.md-in` can also be changed to `.md` using this same logic. + +**Project template csproj-in file** +```xml + +... + +... + +... + +``` + +During build, the generated content is saved into the `/artifacts/ProjectTemplates/GeneratedContent` folder, and the generated content is then added as `` included from the artifacts folder. ## Installing the templates locally @@ -77,20 +139,32 @@ dotnet new install .\artifacts\packages\Debug\Shipping\Microsoft.Extensions.AI.T Finally, create a project from the template and run it: ```pwsh -dotnet new aiagent-webapi ` - [--provider ] ` - [--managed-identity] + dotnet new aiagent-webapi ` + [--provider ] ` + [--managed-identity] # or -dotnet new aichatweb ` - [--provider ] ` - [--vector-store ] ` - [--aspire] ` - [--managed-identity] + dotnet new aichatweb ` + [--provider ] ` + [--vector-store ] ` + [--aspire] ` + [--managed-identity] -# If using `--aspire`, cd into the *AppHost directory -# Follow the instructions in the generated README for setting the necessary user-secrets + # If using `--aspire`, cd into the *AppHost directory + # Follow the instructions in the generated README for setting the necessary user-secrets + +# or + + dotnet new mcpserver [--aot] [--self-contained] dotnet run ``` + +## Cleaning ProjectTemplate build output + +Running the `clean` target for a Project Template project will remove its entire artifacts folder. This includes: + +- `/artifacts/ProjectTemplates//GeneratedContent` (generated template content files) +- `/artifacts/ProjectTemplates//Sandbox` (execution test sandbox) +- `/artifacts/ProjectTemplates//Snapshots` (snapshot test output) diff --git a/test/Directory.Build.props b/test/Directory.Build.props index 09ea86b52b4..f886872fa3d 100644 --- a/test/Directory.Build.props +++ b/test/Directory.Build.props @@ -1,8 +1,8 @@ - - + false + $(NoWarn);RT0000 diff --git a/test/Directory.Build.targets b/test/Directory.Build.targets index ddaf65de061..8cddc800bac 100644 --- a/test/Directory.Build.targets +++ b/test/Directory.Build.targets @@ -14,8 +14,4 @@ - - - $(NoWarn);RT0000 - diff --git a/test/Directory.Packages.props b/test/Directory.Packages.props new file mode 100644 index 00000000000..010335bc108 --- /dev/null +++ b/test/Directory.Packages.props @@ -0,0 +1,6 @@ + + + + + + diff --git a/test/ProjectTemplates/.gitignore b/test/ProjectTemplates/.gitignore deleted file mode 100644 index 6fbeae3c400..00000000000 --- a/test/ProjectTemplates/.gitignore +++ /dev/null @@ -1 +0,0 @@ -*/ExecutionTestSandbox diff --git a/test/ProjectTemplates/Infrastructure/TemplateExecutionTestBase.cs b/test/ProjectTemplates/Infrastructure/TemplateExecutionTestBase.cs index 430f731e0c8..188f5022fd1 100644 --- a/test/ProjectTemplates/Infrastructure/TemplateExecutionTestBase.cs +++ b/test/ProjectTemplates/Infrastructure/TemplateExecutionTestBase.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; +using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; @@ -29,6 +30,18 @@ protected TemplateExecutionTestBase(TemplateExecutionTestFixture fixture, ITestO OutputHelper = outputHelper; } + protected async Task CreateRestoreAndBuild(string projectName, string[] args, string? startupProjectRelativePath = null) + { + var project = await Fixture.CreateProjectAsync( + TConfiguration.Configuration.TemplateName, + projectName, + startupProjectRelativePath, + args); + + await Fixture.RestoreProjectAsync(project); + await Fixture.BuildProjectAsync(project); + } + protected virtual void Dispose(bool disposing) { if (_disposed) diff --git a/test/ProjectTemplates/Infrastructure/TemplateExecutionTestClassFixtureBase.cs b/test/ProjectTemplates/Infrastructure/TemplateExecutionTestClassFixtureBase.cs index 9144593db73..4c9939d960a 100644 --- a/test/ProjectTemplates/Infrastructure/TemplateExecutionTestClassFixtureBase.cs +++ b/test/ProjectTemplates/Infrastructure/TemplateExecutionTestClassFixtureBase.cs @@ -15,9 +15,12 @@ namespace Microsoft.Shared.ProjectTemplates.Tests; /// public abstract class TemplateExecutionTestClassFixtureBase : IAsyncLifetime { - private readonly TemplateExecutionTestConfiguration _configuration; - private readonly string _templateTestOutputPath; - private readonly string _customHivePath; + private readonly string _templatePackageName; + private readonly string _sandboxPackages; + private readonly string _sandboxOutput; + private readonly string _sandboxInstallPath; + private readonly string _sandboxProjectsPath; + private readonly MessageSinkTestOutputHelper _messageSinkTestOutputHelper; private ITestOutputHelper? _currentTestOutputHelper; @@ -30,46 +33,66 @@ public abstract class TemplateExecutionTestClassFixtureBase : IAsyncLifetime protected TemplateExecutionTestClassFixtureBase(TemplateExecutionTestConfiguration configuration, IMessageSink messageSink) { - _configuration = configuration; _messageSinkTestOutputHelper = new(messageSink); - var outputFolderName = GetRandomizedFileName(prefix: _configuration.TestOutputFolderPrefix); - _templateTestOutputPath = Path.Combine(WellKnownPaths.TemplateSandboxOutputRoot, outputFolderName); - _customHivePath = Path.Combine(_templateTestOutputPath, "hive"); - } + _templatePackageName = configuration.TemplatePackageName; + _sandboxPackages = configuration.TemplateSandboxPackages; + _sandboxOutput = configuration.TemplateSandboxOutput; - private static string GetRandomizedFileName(string prefix) - => prefix + "_" + Guid.NewGuid().ToString("N").Substring(0, 10).ToLowerInvariant(); + _sandboxInstallPath = Path.Combine(_sandboxOutput, "install"); + _sandboxProjectsPath = Path.Combine(_sandboxOutput, "projects"); + } public async Task InitializeAsync() { - Directory.CreateDirectory(_templateTestOutputPath); + // Here, we clear execution test output from the previous test run, if it exists. + // It's critical that this clearing happens *before* the tests start, *not* after they complete. + // + // This is because: + // 1. This enables debugging the previous test run by building/running generated projects manually. + // 2. The existence of a project.assets.json file on disk is what allows template content to get discovered + // for component governance reporting. + // Copy the template sandbox infrastructure to the output location for use during tests + CopySandboxDirectory(WellKnownPaths.TemplateSandboxSource, _sandboxOutput); + + var installResult = await new DotNetNewCommand("install", _templatePackageName) + .WithWorkingDirectory(_sandboxInstallPath) + .WithEnvironmentVariable("LOCAL_SHIPPING_PATH", WellKnownPaths.LocalShippingPackagesPath) + .WithEnvironmentVariable("NUGET_PACKAGES", _sandboxPackages) + .WithCustomHive(_sandboxInstallPath) + .ExecuteAsync(OutputHelper); + + installResult.AssertSucceeded($"dotnet new install {_templatePackageName}"); - await InstallTemplatesAsync(); + // Create the sub-directory for the generated projects + Directory.CreateDirectory(_sandboxProjectsPath); + } - async Task InstallTemplatesAsync() + private static void CopySandboxDirectory(string sandboxSource, string testSandbox) + { + if (Directory.Exists(testSandbox)) { - var installSandboxPath = Path.Combine(_templateTestOutputPath, "install"); - Directory.CreateDirectory(installSandboxPath); + Directory.Delete(testSandbox, recursive: true); + } - var installNuGetConfigPath = Path.Combine(installSandboxPath, "nuget.config"); - File.Copy(WellKnownPaths.TemplateInstallNuGetConfigPath, installNuGetConfigPath); + Directory.CreateDirectory(testSandbox); - var installResult = await new DotNetNewCommand("install", _configuration.TemplatePackageName) - .WithWorkingDirectory(installSandboxPath) - .WithEnvironmentVariable("LOCAL_SHIPPING_PATH", WellKnownPaths.LocalShippingPackagesPath) - .WithEnvironmentVariable("NUGET_PACKAGES", WellKnownPaths.NuGetPackagesPath) - .WithCustomHive(_customHivePath) - .ExecuteAsync(OutputHelper); + var source = new DirectoryInfo(sandboxSource); - installResult.AssertSucceeded($"dotnet new install {_configuration.TemplatePackageName}"); + foreach (FileInfo file in source.GetFiles()) + { + file.CopyTo(Path.Combine(testSandbox, file.Name)); + } + + foreach (DirectoryInfo subDir in source.GetDirectories()) + { + CopySandboxDirectory(subDir.FullName, Path.Combine(testSandbox, subDir.Name)); } } - public async Task CreateProjectAsync(string templateName, string projectName, params string[] args) + public async Task CreateProjectAsync(string templateName, string projectName, string? startupProjectRelativePath, params string[] args) { - var outputFolderName = GetRandomizedFileName(projectName); - var outputFolderPath = Path.Combine(_templateTestOutputPath, outputFolderName); + var outputFolderPath = Path.Combine(_sandboxProjectsPath, projectName); ReadOnlySpan dotNetNewCommandArgs = [ templateName, @@ -82,16 +105,13 @@ .. args var testDescription = string.Join(' ', dotNetNewCommandArgs); var newProjectResult = await new DotNetNewCommand(dotNetNewCommandArgs) - .WithWorkingDirectory(_templateTestOutputPath) - .WithCustomHive(_customHivePath) + .WithWorkingDirectory(_sandboxProjectsPath) + .WithCustomHive(_sandboxInstallPath) .ExecuteAsync(OutputHelper); newProjectResult.AssertSucceeded(testDescription); - var templateNuGetConfigPath = Path.Combine(outputFolderPath, "nuget.config"); - File.Copy(WellKnownPaths.TemplateTestNuGetConfigPath, templateNuGetConfigPath); - - return new Project(outputFolderPath, projectName); + return new Project(outputFolderPath, projectName) { StartupProjectRelativePath = startupProjectRelativePath }; } public async Task RestoreProjectAsync(Project project) @@ -99,7 +119,7 @@ public async Task RestoreProjectAsync(Project project) var restoreResult = await new DotNetCommand("restore") .WithWorkingDirectory(project.StartupProjectFullPath) .WithEnvironmentVariable("LOCAL_SHIPPING_PATH", WellKnownPaths.LocalShippingPackagesPath) - .WithEnvironmentVariable("NUGET_PACKAGES", WellKnownPaths.NuGetPackagesPath) + .WithEnvironmentVariable("NUGET_PACKAGES", _sandboxPackages) .ExecuteAsync(OutputHelper); restoreResult.AssertSucceeded($""" @@ -107,7 +127,7 @@ dotnet restore Working Directory: {project.StartupProjectFullPath} Local Shipping Path: {WellKnownPaths.LocalShippingPackagesPath} - NuGet Packages Path: {WellKnownPaths.NuGetPackagesPath} + NuGet Packages Path: {_sandboxPackages} """); } diff --git a/test/ProjectTemplates/Infrastructure/TemplateExecutionTestCollection.cs b/test/ProjectTemplates/Infrastructure/TemplateExecutionTestCollection.cs index dfabfb9a089..608b51eac07 100644 --- a/test/ProjectTemplates/Infrastructure/TemplateExecutionTestCollection.cs +++ b/test/ProjectTemplates/Infrastructure/TemplateExecutionTestCollection.cs @@ -6,7 +6,7 @@ namespace Microsoft.Shared.ProjectTemplates.Tests; [CollectionDefinition(name: Name)] -public sealed class TemplateExecutionTestCollection : ICollectionFixture +public sealed class TemplateExecutionTestCollection { public const string Name = "Template execution test"; } diff --git a/test/ProjectTemplates/Infrastructure/TemplateExecutionTestCollectionFixture.cs b/test/ProjectTemplates/Infrastructure/TemplateExecutionTestCollectionFixture.cs deleted file mode 100644 index 3b015d80202..00000000000 --- a/test/ProjectTemplates/Infrastructure/TemplateExecutionTestCollectionFixture.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -using System.IO; - -namespace Microsoft.Shared.ProjectTemplates.Tests; - -/// -/// Provides functionality scoped to the lifetime of all tests defined in -/// test classes extending . -/// -public sealed class TemplateExecutionTestCollectionFixture -{ - public TemplateExecutionTestCollectionFixture() - { - // Here, we clear execution test output from the previous test run, if it exists. - // - // It's critical that this clearing happens *before* the tests start, *not* after they complete. - // - // This is because: - // 1. This enables debugging the previous test run by building/running generated projects manually. - // 2. The existence of a project.assets.json file on disk is what allows template content to get discovered - // for component governance reporting. - if (Directory.Exists(WellKnownPaths.TemplateSandboxOutputRoot)) - { - Directory.Delete(WellKnownPaths.TemplateSandboxOutputRoot, recursive: true); - } - - // Then we copy the template sandbox infrastructure to the output location for use during tests. - Directory.CreateDirectory(WellKnownPaths.TemplateSandboxOutputRoot); - - foreach (var filePath in Directory.EnumerateFiles(WellKnownPaths.TemplateSandboxSource)) - { - var fileName = Path.GetFileName(filePath); - var destFilePath = Path.Combine(WellKnownPaths.TemplateSandboxOutputRoot, fileName); - File.Copy(filePath, destFilePath); - } - } -} diff --git a/test/ProjectTemplates/Infrastructure/TemplateExecutionTestConfiguration.cs b/test/ProjectTemplates/Infrastructure/TemplateExecutionTestConfiguration.cs index 060f28fe368..cf6bb3e5934 100644 --- a/test/ProjectTemplates/Infrastructure/TemplateExecutionTestConfiguration.cs +++ b/test/ProjectTemplates/Infrastructure/TemplateExecutionTestConfiguration.cs @@ -1,11 +1,16 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.IO; + namespace Microsoft.Shared.ProjectTemplates.Tests; public sealed class TemplateExecutionTestConfiguration { public required string TemplatePackageName { get; init; } + public required string TemplateName { get; init; } - public required string TestOutputFolderPrefix { get; init; } + private string TemplateSandboxRoot => Path.Combine(WellKnownPaths.ProjectTemplatesArtifactsRoot, TemplatePackageName, "Sandbox"); + public string TemplateSandboxPackages => Path.Combine(TemplateSandboxRoot, "packages"); + public string TemplateSandboxOutput => Path.Combine(TemplateSandboxRoot, TemplateName); } diff --git a/test/ProjectTemplates/Infrastructure/TemplateSandbox/README.md b/test/ProjectTemplates/Infrastructure/TemplateSandbox/README.md index 6a9ecb84b86..839ee778551 100644 --- a/test/ProjectTemplates/Infrastructure/TemplateSandbox/README.md +++ b/test/ProjectTemplates/Infrastructure/TemplateSandbox/README.md @@ -17,15 +17,16 @@ Template tests can be debugged either in VS or by running `dotnet test`. However, it's sometimes helpful to debug failures by building, running, and modifying the generated projects directly instead of tinkering with test code. To help with this scenario: -* The `ExecutionTestSandbox` folder containing the generated projects doesn't get cleared until the start of the next test run. +* The `/artifacts/ProjectTemplates/Sandbox/` folder containing the generated projects doesn't get cleared until the start of the next test run. * An `activate.ps1` script can be used to simulate the environment that the template execution tests use. This script: * Sets the active .NET installation to `/.dotnet`. - * Sets the `NUGET_PACKAGES` environment variable to the `ExecutionTestSandbox/packages` folder to use the isolated package cache. + * Sets the `NUGET_PACKAGES` environment variable to the `/artifacts/ProjectTemplates/Sandbox//packages` folder to use the isolated package cache. * Sets a `LOCAL_SHIPPING_PATH` environment variable so that locally-built packages can get picked up during restore. As an example, here's how you can build a project generated by the tests: ```sh +cd /artifacts/ProjectTemplates/Sandbox/ . ./activate.ps1 -cd ./[test_collection]/[generated_template] +cd .// dotnet build ``` diff --git a/test/ProjectTemplates/Infrastructure/TemplateSandbox/nuget.template_install.config b/test/ProjectTemplates/Infrastructure/TemplateSandbox/install/nuget.config similarity index 100% rename from test/ProjectTemplates/Infrastructure/TemplateSandbox/nuget.template_install.config rename to test/ProjectTemplates/Infrastructure/TemplateSandbox/install/nuget.config diff --git a/test/ProjectTemplates/Infrastructure/TemplateSandbox/Directory.Build.props b/test/ProjectTemplates/Infrastructure/TemplateSandbox/projects/Directory.Build.props similarity index 100% rename from test/ProjectTemplates/Infrastructure/TemplateSandbox/Directory.Build.props rename to test/ProjectTemplates/Infrastructure/TemplateSandbox/projects/Directory.Build.props diff --git a/test/ProjectTemplates/Infrastructure/TemplateSandbox/Directory.Build.targets b/test/ProjectTemplates/Infrastructure/TemplateSandbox/projects/Directory.Build.targets similarity index 100% rename from test/ProjectTemplates/Infrastructure/TemplateSandbox/Directory.Build.targets rename to test/ProjectTemplates/Infrastructure/TemplateSandbox/projects/Directory.Build.targets diff --git a/test/ProjectTemplates/Infrastructure/TemplateSandbox/nuget.template_test.config b/test/ProjectTemplates/Infrastructure/TemplateSandbox/projects/nuget.config similarity index 100% rename from test/ProjectTemplates/Infrastructure/TemplateSandbox/nuget.template_test.config rename to test/ProjectTemplates/Infrastructure/TemplateSandbox/projects/nuget.config diff --git a/test/ProjectTemplates/Infrastructure/TemplateSnapshotTestBase.cs b/test/ProjectTemplates/Infrastructure/TemplateSnapshotTestBase.cs new file mode 100644 index 00000000000..d716d0d5d8b --- /dev/null +++ b/test/ProjectTemplates/Infrastructure/TemplateSnapshotTestBase.cs @@ -0,0 +1,53 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.IO; +using System.Linq; +using Microsoft.TemplateEngine.Authoring.TemplateVerifier; + +namespace Microsoft.Shared.ProjectTemplates.Tests; + +public abstract class TemplateSnapshotTestBase +{ + protected virtual TemplateVerifierOptions PrepareSnapshotVerifier( + string projectNamePrefix, + string templatePackageName, + string templateName, + string[] templateArgs, + string[]? verificationExcludePatterns = null) + { + // TemplateVerifierOptions.DoNotPrependTemplateNameToScenarioName results in a '_' prefix. + // So skip setting a prefix here and let TemplateVerifier use the template name prefix. + string scenarioName = TemplateTestUtilities.GetProjectNameForArgs(templateArgs); + + // Create a working directory using the same prefixing approach as the TemplateVerifier + // to improve the debugging experience + string workingDir = Path.Combine(WellKnownPaths.ProjectTemplatesArtifactsRoot, templatePackageName, "Snapshots", templateName, $"{templateName}.{scenarioName}"); + + // Ensure the working directory is clean + if (Directory.Exists(workingDir)) + { + Directory.Delete(workingDir, recursive: true); + } + + // Get the template location from the template package. Use a wildcard for the version number in the file name. + string templateLocation = Path.Combine(WellKnownPaths.LocalShippingPackagesPath, $"{templatePackageName}.*.nupkg"); + + string[]? excludePatterns = Path.DirectorySeparatorChar is '/' + ? verificationExcludePatterns + : verificationExcludePatterns?.Select(p => p.Replace('/', Path.DirectorySeparatorChar)).ToArray(); + + return new TemplateVerifierOptions(templateName) + { + TemplatePath = templateLocation, + TemplateSpecificArgs = templateArgs, + SnapshotsDirectory = Path.Combine("Snapshots", templateName), + OutputDirectory = workingDir, + DoNotPrependCallerMethodNameToScenarioName = true, + DoNotAppendTemplateArgsToScenarioName = true, + ScenarioName = scenarioName, + VerificationExcludePatterns = excludePatterns + }; + } +} diff --git a/test/ProjectTemplates/Infrastructure/TemplateTestUtilities.cs b/test/ProjectTemplates/Infrastructure/TemplateTestUtilities.cs new file mode 100644 index 00000000000..051b9515ccd --- /dev/null +++ b/test/ProjectTemplates/Infrastructure/TemplateTestUtilities.cs @@ -0,0 +1,95 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; + +namespace Microsoft.Shared.ProjectTemplates.Tests; + +public static class TemplateTestUtilities +{ + /// Create a sanitized and standardized project name from the supplied args + /// + /// Framework name is shortened from "net10.0" to "net10", e.g. + /// Boolean options explicitly set to "true" use the option name followed by '_T'. + /// Boolean options explicitly set to "false" use the option name followed by '_F'. + /// Options with names and values use only the option value. + /// Options without values use the option name. + /// Non-word characters are removed. + /// Empty values are removed. + /// + /// Name parts are abbreviated to avoid path length limits + /// - AzureOpenAI -> aoai + /// - GitHubModels -> gh + /// - Ollama -> o + /// - OpenAI -> oai + /// - AzureAISearch -> aais + /// - Qdrant -> q + /// - Local -> l + /// - Aspire -> A + /// - ManagedIdentity -> ID + /// - aot -> AOT + /// - SelfContained -> SC + /// + public static string GetProjectNameForArgs(string[] args, string? prefix = null) + { + IEnumerable nameParts = args + .Select(arg => Regex.Replace(arg, @"--[Ff]ramework=(net[0-9]+)\.0", "$1")) + .Select(arg => Regex.Replace(arg, "--(.*?)=true", "$1_T")) + .Select(arg => Regex.Replace(arg, "--(.*?)=false", "$1_F")) + .Select(arg => Regex.Replace(arg, "--(.*?)=(.*)", "$2")) + .Select(arg => Regex.Replace(arg, "--(.*)", "$1")) + .Select(arg => Regex.Replace(arg, @"\W", "")) + .Select(arg => arg + .Replace("azureopenai", "aoai") + .Replace("githubmodels", "gh") + .Replace("ollama", "o") + .Replace("openai", "oai") + .Replace("azureaisearch", "aais") + .Replace("qdrant", "q") + .Replace("local", "l") + .Replace("aspire", "A") + .Replace("managedidentity", "ID") + .Replace("aot", "AOT") + .Replace("selfcontained", "SC")) + .Where(arg => !string.IsNullOrEmpty(arg)); + + return (nameParts.Any(), prefix is not null) switch + { + (false, false) => "_defaults", + (false, true) => $"{prefix}_defaults", + (true, false) => string.Join('_', nameParts), + _ => string.Join('_', nameParts.Prepend(prefix)), + }; + } + + /// Gets all combinations of options provided for a project template. + public static IEnumerable GetPossibleOptions(ReadOnlyMemory<(string name, string[] values)> options) + { + if (options.Length == 0) + { + yield return []; + yield break; + } + + var firstOption = options.Span[0]; + + foreach (var value in firstOption.values) + { + foreach (var otherOptions in GetPossibleOptions(options[1..])) + { + yield return [$"{firstOption.name}={value}", .. otherOptions]; + } + } + } + + /// Checks for a specific option/value pair + public static bool HasOption(string[] args, string option, string value) => + args.Contains($"{option}={value}"); + + /// Checks for a boolean option to be specified + public static bool HasOption(string[] args, string option) => + args.Contains(option) || args.Contains($"{option}=true"); +} diff --git a/test/ProjectTemplates/Infrastructure/VerifyScrubbers.cs b/test/ProjectTemplates/Infrastructure/VerifyScrubbers.cs index 505feb99c14..d172082c5e3 100644 --- a/test/ProjectTemplates/Infrastructure/VerifyScrubbers.cs +++ b/test/ProjectTemplates/Infrastructure/VerifyScrubbers.cs @@ -1,13 +1,58 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System; +using System.IO; using System.Text; using System.Text.RegularExpressions; +using Microsoft.TemplateEngine.Authoring.TemplateVerifier; namespace Microsoft.Shared.ProjectTemplates.Tests; internal static class VerifyScrubbers { + public static ScrubbersDefinition AddSolutionFileGuidScrubber(this ScrubbersDefinition scrubbers) => scrubbers + .AddScrubber( + content => content.ScrubByRegex(pattern: @"\{.{36}\}", replacement: "{00000000-0000-0000-0000-000000000000}"), + extension: "sln"); + + public static ScrubbersDefinition AddUserSecretsScrubber(this ScrubbersDefinition scrubbers) => scrubbers + .AddScrubber( + content => content.ScrubByRegex(pattern: ".{36}", replacement: "{00000000-0000-0000-0000-000000000000}"), + extension: "csproj"); + + public static ScrubbersDefinition AddPackageReferenceScrubber(this ScrubbersDefinition scrubbers) => scrubbers + .AddScrubber( + content => content.ScrubByRegex( + pattern: @"", + replacement: @""), + extension: "csproj"); + + public static ScrubbersDefinition AddLocalhostPortScrubber( + this ScrubbersDefinition scrubbers, + (string pattern, string replacement)? https = null, + (string pattern, string replacement)? http = null) + { + https ??= (@"\d{4,5}", "9995"); + http ??= (@"\d{4,5}", "9996"); + + Action scrubPorts = content => + { + content.ScrubByRegex($@"(https://localhost):({https.Value.pattern})", $"$1:{https.Value.replacement}"); + content.ScrubByRegex($@"(http://localhost):({http.Value.pattern})", $"$1:{http.Value.replacement}"); + }; + + return scrubbers + .AddScrubber(scrubPorts, extension: "md") + .AddScrubber((path, content) => + { + if (Path.GetFileName(path).Equals("launchSettings.json", StringComparison.OrdinalIgnoreCase)) + { + scrubPorts(content); + } + }); + } + /// /// Removes content after "Details: ". /// diff --git a/test/ProjectTemplates/Infrastructure/WellKnownPaths.cs b/test/ProjectTemplates/Infrastructure/WellKnownPaths.cs index 0ebb196fe84..3a30f84d4ff 100644 --- a/test/ProjectTemplates/Infrastructure/WellKnownPaths.cs +++ b/test/ProjectTemplates/Infrastructure/WellKnownPaths.cs @@ -9,38 +9,32 @@ namespace Microsoft.Shared.ProjectTemplates.Tests; internal static class WellKnownPaths { + private const string BuildConfigurationFolder = +#if DEBUG + "Debug"; +#else + "Release"; +#endif + public static readonly string RepoRoot; public static readonly string RepoDotNetExePath; - public static readonly string ThisProjectRoot; + public static readonly string LocalShippingPackagesPath; + public static readonly string ProjectTemplatesArtifactsRoot; - public static readonly string TemplateFeedLocation; + // Execution Test Paths public static readonly string TemplateSandboxSource; - public static readonly string TemplateSandboxOutputRoot; - public static readonly string TemplateInstallNuGetConfigPath; public static readonly string TemplateTestNuGetConfigPath; - public static readonly string LocalShippingPackagesPath; - public static readonly string NuGetPackagesPath; static WellKnownPaths() { RepoRoot = GetRepoRoot(); RepoDotNetExePath = GetRepoDotNetExePath(); - ThisProjectRoot = ProjectRootHelper.GetThisProjectRoot(); - TemplateFeedLocation = Path.Combine(RepoRoot, "src", "ProjectTemplates"); + ProjectTemplatesArtifactsRoot = Path.Combine(RepoRoot, "artifacts", "ProjectTemplates"); TemplateSandboxSource = Path.Combine(RepoRoot, "test", "ProjectTemplates", "Infrastructure", "TemplateSandbox"); - TemplateSandboxOutputRoot = Path.Combine(ThisProjectRoot, "ExecutionTestSandbox"); - TemplateInstallNuGetConfigPath = Path.Combine(TemplateSandboxSource, "nuget.template_install.config"); - TemplateTestNuGetConfigPath = Path.Combine(TemplateSandboxSource, "nuget.template_test.config"); + TemplateTestNuGetConfigPath = Path.Combine(TemplateSandboxSource, "nuget.config"); - const string BuildConfigurationFolder = -#if DEBUG - "Debug"; -#else - "Release"; -#endif LocalShippingPackagesPath = Path.Combine(RepoRoot, "artifacts", "packages", BuildConfigurationFolder, "Shipping"); - NuGetPackagesPath = Path.Combine(TemplateSandboxOutputRoot, "packages"); } private static string GetRepoRoot() diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/AIAgentWebAPIExecutionTests.cs b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/AIAgentWebAPIExecutionTests.cs new file mode 100644 index 00000000000..03806abac7c --- /dev/null +++ b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/AIAgentWebAPIExecutionTests.cs @@ -0,0 +1,65 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Collections.Generic; +using System.Threading.Tasks; +using Microsoft.Shared.ProjectTemplates.Tests; +using Xunit; +using Xunit.Abstractions; +using static Microsoft.Shared.ProjectTemplates.Tests.TemplateTestUtilities; + +namespace Microsoft.Agents.AI.ProjectTemplates.Tests; + +/// +/// Contains execution tests for the "AI Agent Web API" template. +/// +/// +/// In addition to validating that the templates build and restore correctly, +/// these tests are also responsible for template component governance reporting. +/// This is because the generated output is left on disk after tests complete, +/// most importantly the project.assets.json file that gets created during restore. +/// Therefore, it's *critical* that these tests remain in a working state, +/// as disabling them will also disable CG reporting. +/// +public class AIAgentWebAPIExecutionTests : TemplateExecutionTestBase, ITemplateExecutionTestConfigurationProvider +{ + public AIAgentWebAPIExecutionTests(TemplateExecutionTestFixture fixture, ITestOutputHelper outputHelper) + : base(fixture, outputHelper) + { + } + + public static TemplateExecutionTestConfiguration Configuration { get; } = new() + { + TemplatePackageName = "Microsoft.Agents.AI.ProjectTemplates", + TemplateName = "aiagent-webapi" + }; + + public static IEnumerable GetSupportedProjectConfigurations() + { + (string name, string[] values)[] allOptionValues = [ + ("--provider", ["azureopenai", "githubmodels", "ollama", "openai"]), + ("--managed-identity", ["true", "false"]), + ("--framework", [/* net8.0 is not supported until 1.0.0-preview.251125.1 */ "net9.0", "net10.0"]) + ]; + + foreach (var args in GetPossibleOptions(allOptionValues)) + { + // Managed Identity only applies when using an Azure service + if (HasOption(args, "--managed-identity") && !HasOption(args, "--provider", "azureopenai")) + { + continue; + } + + yield return args; + } + } + + // Do not skip. See XML docs for this test class. + [Theory] + [MemberData(nameof(GetSupportedProjectConfigurations))] + public async Task TestAllSupportedConfigurations(params string[] args) + { + string projectName = GetProjectNameForArgs(args, prefix: "AIAgentWebApi"); + await CreateRestoreAndBuild(projectName, args); + } +} diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/AIAgentWebAPISnapshotTests.cs b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/AIAgentWebAPISnapshotTests.cs new file mode 100644 index 00000000000..a93915e3252 --- /dev/null +++ b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/AIAgentWebAPISnapshotTests.cs @@ -0,0 +1,51 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using Microsoft.Shared.ProjectTemplates.Tests; +using Microsoft.TemplateEngine.Authoring.TemplateVerifier; +using Microsoft.TemplateEngine.TestHelper; +using Xunit; +using Xunit.Abstractions; +using static Microsoft.Shared.ProjectTemplates.Tests.TemplateTestUtilities; + +namespace Microsoft.Agents.AI.ProjectTemplates.Tests; + +public class AIAgentWebAPISnapshotTests : TemplateSnapshotTestBase +{ + private readonly ILogger _log; + + public AIAgentWebAPISnapshotTests(ITestOutputHelper log) + { +#pragma warning disable CA2000 // Dispose objects before losing scope + _log = new XunitLoggerProvider(log).CreateLogger("TestRun"); +#pragma warning restore CA2000 // Dispose objects before losing scope + } + + [Theory] + [InlineData /* Defaults: --provider=githubmodels */] + [InlineData("--provider=ollama")] + [InlineData("--provider=openai")] + [InlineData("--provider=azureopenai", "--managed-identity=true")] + [InlineData("--provider=azureopenai", "--managed-identity=false")] + public async Task RunSnapshotTests(params string[] templateArgs) + { + string projectNamePrefix = "AIAgentWebApi"; + string templatePackageName = "Microsoft.Agents.AI.ProjectTemplates"; + string templateName = "aiagent-webapi"; + + TemplateVerifierOptions options = PrepareSnapshotVerifier( + projectNamePrefix, + templatePackageName, + templateName, + templateArgs) + .WithCustomScrubbers(ScrubbersDefinition.Empty + .AddUserSecretsScrubber() + .AddPackageReferenceScrubber() + .AddLocalhostPortScrubber()); + + VerificationEngine engine = new VerificationEngine(_log); + await engine.Execute(options); + } +} diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Microsoft.Agents.AI.ProjectTemplates.Tests.csproj b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Microsoft.Agents.AI.ProjectTemplates.Tests.csproj index 1c529dff3f3..1ebf05491dc 100644 --- a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Microsoft.Agents.AI.ProjectTemplates.Tests.csproj +++ b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Microsoft.Agents.AI.ProjectTemplates.Tests.csproj @@ -17,16 +17,10 @@ - - - - - - diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/ProjectRootHelper.cs b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/ProjectRootHelper.cs deleted file mode 100644 index baca09bf468..00000000000 --- a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/ProjectRootHelper.cs +++ /dev/null @@ -1,35 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -using System; -using System.IO; -using System.Runtime.CompilerServices; - -namespace Microsoft.Shared.ProjectTemplates.Tests; - -/// -/// Contains a helper for determining the disk location of the containing project folder. -/// -/// -/// It's important that this file resides in the root of the containing project, or the returned -/// project root path will be incorrect. -/// -internal static class ProjectRootHelper -{ - public static string GetThisProjectRoot() - => GetThisProjectRootCore(); - - // This helper method is defined separately from its public variant because it extracts the - // caller file path via the [CallerFilePath] attribute. - // Therefore, the caller must be in a known location, i.e., this source file, to produce - // a reliable result. - private static string GetThisProjectRootCore([CallerFilePath] string callerFilePath = "") - { - if (Path.GetDirectoryName(callerFilePath) is not { Length: > 0 } testProjectRoot) - { - throw new InvalidOperationException("Could not determine the root of the test project."); - } - - return testProjectRoot; - } -} diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/README.md b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/README.md deleted file mode 100644 index 99247d4574c..00000000000 --- a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# Snapshots - -This directory contains verified snapshots of generated template output. These snapshots are used by the template snapshot tests to ensure templates generate expected output. - -When template content is added, this directory will contain subdirectories for each test scenario. diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.DefaultParameters.verified/aiagent-webapi/README.md b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.DefaultParameters.verified/aiagent-webapi/README.md deleted file mode 100644 index f13529d763e..00000000000 --- a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.DefaultParameters.verified/aiagent-webapi/README.md +++ /dev/null @@ -1,129 +0,0 @@ -# AI Agent Web API - -This is an AI Agent Web API application created from the `aiagent-webapi` template. This template is currently in a preview stage. If you have feedback, please take a [brief survey](https://aka.ms/dotnet/aiagent-webapi/preview1/survey). - -## Prerequisites - -- A GitHub Models API token (free to get started) - -## Getting Started - -### 1. Configure Your AI Service - -#### GitHub Models Configuration - -This application uses GitHub Models (model: gpt-4o-mini) for AI functionality. You'll need to configure your GitHub Models API token: - -**Option A: Using User Secrets (Recommended for Development)** - -```bash -dotnet user-secrets set "GITHUB_TOKEN" "your-github-models-token-here" -``` - -**Option B: Using Environment Variables** - -Set the `GITHUB_TOKEN` environment variable: - -- **Windows (PowerShell)**: - ```powershell - $env:GITHUB_TOKEN = "your-github-models-token-here" - ``` - -- **Linux/macOS**: - ```bash - export GITHUB_TOKEN="your-github-models-token-here" - ``` - -#### Get a GitHub Models Token - -1. Visit [GitHub Models](https://github.com/marketplace/models) -2. Sign in with your GitHub account -3. Select a model (e.g., gpt-4o-mini) -4. Click "Get API Key" or follow the authentication instructions -5. Copy your personal access token - - -### 2. Run the Application - -```bash -dotnet run -lp https -``` - -The application will start and listen on: -- HTTP: `http://localhost:9999` -- HTTPS: `https://localhost:9999` - -### 3. Test the Application - -The application exposes OpenAI-compatible API endpoints. You can interact with the AI agents using any OpenAI-compatible client or tools. - -In development environments, a `/devui/` route is mapped to the Agent Framework development UI (DevUI), and when the app is launched through an IDE a browser will open to this URL. DevUI provides a web-based UI for interacting with agents and workflows. DevUI operates as an OpenAI-compatible client using the Responses and Conversations endpoints. - -## How It Works - -This application demonstrates Agent Framework with: - -1. **Writer Agent**: Writes short stories (300 words or less) about specified topics -2. **Editor Agent**: Edits stories to improve grammar and style, ensuring they stay under 300 words -3. **Publisher Workflow Agent**: A sequential workflow agent that combines the writer and editor agents - -The agents are exposed through OpenAI-compatible API endpoints, making them easy to integrate with existing tools and applications. - -## Template Parameters - -When creating a new project, you can customize it using template parameters: - -```bash -# Specify AI service provider -dotnet new aiagent-webapi --provider azureopenai - -# Specify a custom chat model -dotnet new aiagent-webapi --chat-model gpt-4o - -# Use API key authentication for Azure OpenAI -dotnet new aiagent-webapi --provider azureopenai --managed-identity false - -# Use Ollama with a different model -dotnet new aiagent-webapi --provider ollama --chat-model llama3.1 -``` - -### Available Parameters - -- **`--provider`**: Choose the AI service provider - - `githubmodels` (default) - GitHub Models - - `azureopenai` - Azure OpenAI - - `openai` - OpenAI Platform - - `ollama` - Ollama (local development) - -- **`--chat-model`**: Specify the chat model/deployment name - - Default for OpenAI/Azure OpenAI/GitHub Models: `gpt-4o-mini` - - Default for Ollama: `llama3.2` - -- **`--managed-identity`**: Use managed identity for Azure services (default: `true`) - - Only applicable when `--provider azureopenai` - -- **`--framework`**: Target framework (default: `net10.0`) - - Options: `net10.0`, `net9.0`, `net8.0` - -## Project Structure - -- `Program.cs` - Application entry point and configuration -- `appsettings.json` - Application configuration -- `Properties/launchSettings.json` - Launch profiles for development - -## Learn More - -- [AI apps for .NET developers](https://learn.microsoft.com/dotnet/ai) -- [Microsoft Agent Framework Documentation](https://aka.ms/dotnet/agent-framework/docs) -- [GitHub Models](https://github.com/marketplace/models) - -## Troubleshooting - -**Problem**: Application fails with "Missing configuration: GITHUB_TOKEN" - -**Solution**: Make sure you've configured your GitHub Models API token using one of the methods described above. - -**Problem**: API requests fail with authentication errors - -**Solution**: Verify your GitHub Models token is valid and hasn't expired. You may need to regenerate it from the GitHub Models website. - diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.GitHubModels.verified/aiagent-webapi/Program.cs b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.GitHubModels.verified/aiagent-webapi/Program.cs deleted file mode 100644 index 025dffc9c9f..00000000000 --- a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.GitHubModels.verified/aiagent-webapi/Program.cs +++ /dev/null @@ -1,64 +0,0 @@ -using System.ClientModel; -using System.ComponentModel; -using Microsoft.Agents.AI; -using Microsoft.Agents.AI.DevUI; -using Microsoft.Agents.AI.Hosting; -using Microsoft.Agents.AI.Workflows; -using Microsoft.Extensions.AI; -using OpenAI; -using OpenAI.Chat; - -var builder = WebApplication.CreateBuilder(args); - -// You will need to set the token to your own value -// You can do this using Visual Studio's "Manage User Secrets" UI, or on the command line: -// cd this-project-directory -// dotnet user-secrets set "GITHUB_TOKEN" "your-github-models-token-here" -var chatClient = new ChatClient( - "gpt-4o-mini", - new ApiKeyCredential(builder.Configuration["GITHUB_TOKEN"] ?? throw new InvalidOperationException("Missing configuration: GITHUB_TOKEN")), - new OpenAIClientOptions { Endpoint = new Uri("https://models.inference.ai.azure.com") }) - .AsIChatClient(); - -builder.Services.AddChatClient(chatClient); - -builder.AddAIAgent("writer", "You write short stories (300 words or less) about the specified topic."); - -builder.AddAIAgent("editor", (sp, key) => new ChatClientAgent( - chatClient, - name: key, - instructions: "You edit short stories to improve grammar and style, ensuring the stories are less than 300 words. Once finished editing, you select a title and format the story for publishing.", - tools: [AIFunctionFactory.Create(FormatStory)] -)); - -builder.AddWorkflow("publisher", (sp, key) => AgentWorkflowBuilder.BuildSequential( - workflowName: key, - sp.GetRequiredKeyedService("writer"), - sp.GetRequiredKeyedService("editor") -)).AddAsAIAgent(); - -// Register services for OpenAI responses and conversations (also required for DevUI) -builder.Services.AddOpenAIResponses(); -builder.Services.AddOpenAIConversations(); - -var app = builder.Build(); -app.UseHttpsRedirection(); - -// Map endpoints for OpenAI responses and conversations (also required for DevUI) -app.MapOpenAIResponses(); -app.MapOpenAIConversations(); - -if (builder.Environment.IsDevelopment()) -{ - // Map DevUI endpoint to /devui - app.MapDevUI(); -} - -app.Run(); - -[Description("Formats the story for publication, revealing its title.")] -string FormatStory(string title, string story) => $""" - **Title**: {title} - - {story} - """; diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.Ollama.verified/aiagent-webapi/Properties/launchSettings.json b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.Ollama.verified/aiagent-webapi/Properties/launchSettings.json deleted file mode 100644 index c242aacc025..00000000000 --- a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.Ollama.verified/aiagent-webapi/Properties/launchSettings.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "$schema": "https://json.schemastore.org/launchsettings.json", - "profiles": { - "http": { - "commandName": "Project", - "dotnetRunMessages": true, - "launchBrowser": true, - "launchUrl": "devui/", - "applicationUrl": "http://localhost:9999", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - }, - "https": { - "commandName": "Project", - "dotnetRunMessages": true, - "launchBrowser": true, - "launchUrl": "devui/", - "applicationUrl": "https://localhost:9999;http://localhost:9999", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - } - } -} diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.OpenAI.verified/aiagent-webapi/Properties/launchSettings.json b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.OpenAI.verified/aiagent-webapi/Properties/launchSettings.json deleted file mode 100644 index c242aacc025..00000000000 --- a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.OpenAI.verified/aiagent-webapi/Properties/launchSettings.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "$schema": "https://json.schemastore.org/launchsettings.json", - "profiles": { - "http": { - "commandName": "Project", - "dotnetRunMessages": true, - "launchBrowser": true, - "launchUrl": "devui/", - "applicationUrl": "http://localhost:9999", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - }, - "https": { - "commandName": "Project", - "dotnetRunMessages": true, - "launchBrowser": true, - "launchUrl": "devui/", - "applicationUrl": "https://localhost:9999;http://localhost:9999", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - } - } -} diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.OpenAI.verified/aiagent-webapi/aiagent-webapi.csproj b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.OpenAI.verified/aiagent-webapi/aiagent-webapi.csproj deleted file mode 100644 index 337bfdd220c..00000000000 --- a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.OpenAI.verified/aiagent-webapi/aiagent-webapi.csproj +++ /dev/null @@ -1,19 +0,0 @@ - - - - net10.0 - enable - enable - secret - - - - - - - - - - - - diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.OpenAI.verified/aiagent-webapi/appsettings.json b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.OpenAI.verified/aiagent-webapi/appsettings.json deleted file mode 100644 index 223027717b4..00000000000 --- a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.OpenAI.verified/aiagent-webapi/appsettings.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - }, - "AllowedHosts": "*" -} diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.DefaultParameters.verified/aiagent-webapi/Program.cs b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi._defaults.verified/aiagent-webapi/Program.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.DefaultParameters.verified/aiagent-webapi/Program.cs rename to test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi._defaults.verified/aiagent-webapi/Program.cs diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.GitHubModels.verified/aiagent-webapi/Properties/launchSettings.json b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi._defaults.verified/aiagent-webapi/Properties/launchSettings.json similarity index 82% rename from test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.GitHubModels.verified/aiagent-webapi/Properties/launchSettings.json rename to test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi._defaults.verified/aiagent-webapi/Properties/launchSettings.json index c242aacc025..d71b1876d35 100644 --- a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.GitHubModels.verified/aiagent-webapi/Properties/launchSettings.json +++ b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi._defaults.verified/aiagent-webapi/Properties/launchSettings.json @@ -6,7 +6,7 @@ "dotnetRunMessages": true, "launchBrowser": true, "launchUrl": "devui/", - "applicationUrl": "http://localhost:9999", + "applicationUrl": "http://localhost:9996", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } @@ -16,7 +16,7 @@ "dotnetRunMessages": true, "launchBrowser": true, "launchUrl": "devui/", - "applicationUrl": "https://localhost:9999;http://localhost:9999", + "applicationUrl": "https://localhost:9995;http://localhost:9996", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.GitHubModels.verified/aiagent-webapi/README.md b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi._defaults.verified/aiagent-webapi/README.md similarity index 98% rename from test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.GitHubModels.verified/aiagent-webapi/README.md rename to test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi._defaults.verified/aiagent-webapi/README.md index f13529d763e..8ea2640ad89 100644 --- a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.GitHubModels.verified/aiagent-webapi/README.md +++ b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi._defaults.verified/aiagent-webapi/README.md @@ -50,8 +50,8 @@ dotnet run -lp https ``` The application will start and listen on: -- HTTP: `http://localhost:9999` -- HTTPS: `https://localhost:9999` +- HTTP: `http://localhost:9996` +- HTTPS: `https://localhost:9995` ### 3. Test the Application diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.AzureOpenAI_ApiKey.verified/aiagent-webapi/aiagent-webapi.csproj b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi._defaults.verified/aiagent-webapi/aiagent-webapi.csproj similarity index 69% rename from test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.AzureOpenAI_ApiKey.verified/aiagent-webapi/aiagent-webapi.csproj rename to test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi._defaults.verified/aiagent-webapi/aiagent-webapi.csproj index 337bfdd220c..6e5004343c4 100644 --- a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.AzureOpenAI_ApiKey.verified/aiagent-webapi/aiagent-webapi.csproj +++ b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi._defaults.verified/aiagent-webapi/aiagent-webapi.csproj @@ -4,16 +4,16 @@ net10.0 enable enable - secret + {00000000-0000-0000-0000-000000000000} - - - - - - + + + + + + diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.AzureOpenAI_ApiKey.verified/aiagent-webapi/appsettings.json b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi._defaults.verified/aiagent-webapi/appsettings.json similarity index 100% rename from test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.AzureOpenAI_ApiKey.verified/aiagent-webapi/appsettings.json rename to test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi._defaults.verified/aiagent-webapi/appsettings.json diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.AzureOpenAI_ApiKey.verified/aiagent-webapi/Program.cs b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.aoai_ID_F.verified/aiagent-webapi/Program.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.AzureOpenAI_ApiKey.verified/aiagent-webapi/Program.cs rename to test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.aoai_ID_F.verified/aiagent-webapi/Program.cs diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.AzureOpenAI_ApiKey.verified/aiagent-webapi/Properties/launchSettings.json b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.aoai_ID_F.verified/aiagent-webapi/Properties/launchSettings.json similarity index 82% rename from test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.AzureOpenAI_ApiKey.verified/aiagent-webapi/Properties/launchSettings.json rename to test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.aoai_ID_F.verified/aiagent-webapi/Properties/launchSettings.json index c242aacc025..d71b1876d35 100644 --- a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.AzureOpenAI_ApiKey.verified/aiagent-webapi/Properties/launchSettings.json +++ b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.aoai_ID_F.verified/aiagent-webapi/Properties/launchSettings.json @@ -6,7 +6,7 @@ "dotnetRunMessages": true, "launchBrowser": true, "launchUrl": "devui/", - "applicationUrl": "http://localhost:9999", + "applicationUrl": "http://localhost:9996", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } @@ -16,7 +16,7 @@ "dotnetRunMessages": true, "launchBrowser": true, "launchUrl": "devui/", - "applicationUrl": "https://localhost:9999;http://localhost:9999", + "applicationUrl": "https://localhost:9995;http://localhost:9996", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.AzureOpenAI_ApiKey.verified/aiagent-webapi/README.md b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.aoai_ID_F.verified/aiagent-webapi/README.md similarity index 98% rename from test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.AzureOpenAI_ApiKey.verified/aiagent-webapi/README.md rename to test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.aoai_ID_F.verified/aiagent-webapi/README.md index de250a2916e..222e83f1188 100644 --- a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.AzureOpenAI_ApiKey.verified/aiagent-webapi/README.md +++ b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.aoai_ID_F.verified/aiagent-webapi/README.md @@ -48,8 +48,8 @@ dotnet run -lp https ``` The application will start and listen on: -- HTTP: `http://localhost:9999` -- HTTPS: `https://localhost:9999` +- HTTP: `http://localhost:9996` +- HTTPS: `https://localhost:9995` ### 3. Test the Application diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.GitHubModels.verified/aiagent-webapi/aiagent-webapi.csproj b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.aoai_ID_F.verified/aiagent-webapi/aiagent-webapi.csproj similarity index 69% rename from test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.GitHubModels.verified/aiagent-webapi/aiagent-webapi.csproj rename to test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.aoai_ID_F.verified/aiagent-webapi/aiagent-webapi.csproj index 337bfdd220c..6e5004343c4 100644 --- a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.GitHubModels.verified/aiagent-webapi/aiagent-webapi.csproj +++ b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.aoai_ID_F.verified/aiagent-webapi/aiagent-webapi.csproj @@ -4,16 +4,16 @@ net10.0 enable enable - secret + {00000000-0000-0000-0000-000000000000} - - - - - - + + + + + + diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.AzureOpenAI_ManagedIdentity.verified/aiagent-webapi/appsettings.json b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.aoai_ID_F.verified/aiagent-webapi/appsettings.json similarity index 100% rename from test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.AzureOpenAI_ManagedIdentity.verified/aiagent-webapi/appsettings.json rename to test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.aoai_ID_F.verified/aiagent-webapi/appsettings.json diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.AzureOpenAI_ManagedIdentity.verified/aiagent-webapi/Program.cs b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.aoai_ID_T.verified/aiagent-webapi/Program.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.AzureOpenAI_ManagedIdentity.verified/aiagent-webapi/Program.cs rename to test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.aoai_ID_T.verified/aiagent-webapi/Program.cs diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.DefaultParameters.verified/aiagent-webapi/Properties/launchSettings.json b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.aoai_ID_T.verified/aiagent-webapi/Properties/launchSettings.json similarity index 82% rename from test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.DefaultParameters.verified/aiagent-webapi/Properties/launchSettings.json rename to test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.aoai_ID_T.verified/aiagent-webapi/Properties/launchSettings.json index c242aacc025..d71b1876d35 100644 --- a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.DefaultParameters.verified/aiagent-webapi/Properties/launchSettings.json +++ b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.aoai_ID_T.verified/aiagent-webapi/Properties/launchSettings.json @@ -6,7 +6,7 @@ "dotnetRunMessages": true, "launchBrowser": true, "launchUrl": "devui/", - "applicationUrl": "http://localhost:9999", + "applicationUrl": "http://localhost:9996", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } @@ -16,7 +16,7 @@ "dotnetRunMessages": true, "launchBrowser": true, "launchUrl": "devui/", - "applicationUrl": "https://localhost:9999;http://localhost:9999", + "applicationUrl": "https://localhost:9995;http://localhost:9996", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.AzureOpenAI_ManagedIdentity.verified/aiagent-webapi/README.md b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.aoai_ID_T.verified/aiagent-webapi/README.md similarity index 98% rename from test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.AzureOpenAI_ManagedIdentity.verified/aiagent-webapi/README.md rename to test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.aoai_ID_T.verified/aiagent-webapi/README.md index 3cb72789072..99157e36906 100644 --- a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.AzureOpenAI_ManagedIdentity.verified/aiagent-webapi/README.md +++ b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.aoai_ID_T.verified/aiagent-webapi/README.md @@ -20,8 +20,8 @@ dotnet run -lp https ``` The application will start and listen on: -- HTTP: `http://localhost:9999` -- HTTPS: `https://localhost:9999` +- HTTP: `http://localhost:9996` +- HTTPS: `https://localhost:9995` ### 3. Test the Application diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.AzureOpenAI_ManagedIdentity.verified/aiagent-webapi/aiagent-webapi.csproj b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.aoai_ID_T.verified/aiagent-webapi/aiagent-webapi.csproj similarity index 63% rename from test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.AzureOpenAI_ManagedIdentity.verified/aiagent-webapi/aiagent-webapi.csproj rename to test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.aoai_ID_T.verified/aiagent-webapi/aiagent-webapi.csproj index 0dab5ae9e6e..393be1ca919 100644 --- a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.AzureOpenAI_ManagedIdentity.verified/aiagent-webapi/aiagent-webapi.csproj +++ b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.aoai_ID_T.verified/aiagent-webapi/aiagent-webapi.csproj @@ -4,17 +4,17 @@ net10.0 enable enable - secret + {00000000-0000-0000-0000-000000000000} - - - - - - - + + + + + + + diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.DefaultParameters.verified/aiagent-webapi/appsettings.json b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.aoai_ID_T.verified/aiagent-webapi/appsettings.json similarity index 100% rename from test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.DefaultParameters.verified/aiagent-webapi/appsettings.json rename to test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.aoai_ID_T.verified/aiagent-webapi/appsettings.json diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.Ollama.verified/aiagent-webapi/Program.cs b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.o.verified/aiagent-webapi/Program.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.Ollama.verified/aiagent-webapi/Program.cs rename to test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.o.verified/aiagent-webapi/Program.cs diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.AzureOpenAI_ManagedIdentity.verified/aiagent-webapi/Properties/launchSettings.json b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.o.verified/aiagent-webapi/Properties/launchSettings.json similarity index 82% rename from test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.AzureOpenAI_ManagedIdentity.verified/aiagent-webapi/Properties/launchSettings.json rename to test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.o.verified/aiagent-webapi/Properties/launchSettings.json index c242aacc025..d71b1876d35 100644 --- a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.AzureOpenAI_ManagedIdentity.verified/aiagent-webapi/Properties/launchSettings.json +++ b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.o.verified/aiagent-webapi/Properties/launchSettings.json @@ -6,7 +6,7 @@ "dotnetRunMessages": true, "launchBrowser": true, "launchUrl": "devui/", - "applicationUrl": "http://localhost:9999", + "applicationUrl": "http://localhost:9996", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } @@ -16,7 +16,7 @@ "dotnetRunMessages": true, "launchBrowser": true, "launchUrl": "devui/", - "applicationUrl": "https://localhost:9999;http://localhost:9999", + "applicationUrl": "https://localhost:9995;http://localhost:9996", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.Ollama.verified/aiagent-webapi/README.md b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.o.verified/aiagent-webapi/README.md similarity index 96% rename from test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.Ollama.verified/aiagent-webapi/README.md rename to test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.o.verified/aiagent-webapi/README.md index 411f6c90acc..13f6f85451d 100644 --- a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.Ollama.verified/aiagent-webapi/README.md +++ b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.o.verified/aiagent-webapi/README.md @@ -21,7 +21,7 @@ This application uses Ollama running locally (model: llama3.2). You'll need to h ``` 3. Ensure Ollama is running (it starts automatically after installation) -The application is configured to connect to Ollama at `http://localhost:9999`. +The application is configured to connect to Ollama at `http://localhost:9996`. ### 2. Run the Application @@ -31,8 +31,8 @@ dotnet run -lp https ``` The application will start and listen on: -- HTTP: `http://localhost:9999` -- HTTPS: `https://localhost:9999` +- HTTP: `http://localhost:9996` +- HTTPS: `https://localhost:9995` ### 3. Test the Application @@ -104,7 +104,7 @@ dotnet new aiagent-webapi --provider ollama --chat-model llama3.1 **Solution**: - Ensure Ollama is running. On macOS/Linux, check with `pgrep ollama`. On Windows, check Task Manager. -- Verify Ollama is accessible at `http://localhost:9999` +- Verify Ollama is accessible at `http://localhost:9996` - Make sure you've downloaded the llama3.2 model: `ollama pull llama3.2` **Problem**: Model responses are slow or time out diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.Ollama.verified/aiagent-webapi/aiagent-webapi.csproj b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.o.verified/aiagent-webapi/aiagent-webapi.csproj similarity index 62% rename from test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.Ollama.verified/aiagent-webapi/aiagent-webapi.csproj rename to test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.o.verified/aiagent-webapi/aiagent-webapi.csproj index 1070edf0dad..4ee728aaba3 100644 --- a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.Ollama.verified/aiagent-webapi/aiagent-webapi.csproj +++ b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.o.verified/aiagent-webapi/aiagent-webapi.csproj @@ -4,16 +4,16 @@ net10.0 enable enable - secret + {00000000-0000-0000-0000-000000000000} - - - - - - + + + + + + diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.GitHubModels.verified/aiagent-webapi/appsettings.json b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.o.verified/aiagent-webapi/appsettings.json similarity index 100% rename from test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.GitHubModels.verified/aiagent-webapi/appsettings.json rename to test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.o.verified/aiagent-webapi/appsettings.json diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.OpenAI.verified/aiagent-webapi/Program.cs b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.oai.verified/aiagent-webapi/Program.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.OpenAI.verified/aiagent-webapi/Program.cs rename to test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.oai.verified/aiagent-webapi/Program.cs diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.oai.verified/aiagent-webapi/Properties/launchSettings.json b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.oai.verified/aiagent-webapi/Properties/launchSettings.json new file mode 100644 index 00000000000..d71b1876d35 --- /dev/null +++ b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.oai.verified/aiagent-webapi/Properties/launchSettings.json @@ -0,0 +1,25 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "devui/", + "applicationUrl": "http://localhost:9996", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "devui/", + "applicationUrl": "https://localhost:9995;http://localhost:9996", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.OpenAI.verified/aiagent-webapi/README.md b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.oai.verified/aiagent-webapi/README.md similarity index 98% rename from test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.OpenAI.verified/aiagent-webapi/README.md rename to test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.oai.verified/aiagent-webapi/README.md index a989e78b7d7..dfd846707b6 100644 --- a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.OpenAI.verified/aiagent-webapi/README.md +++ b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.oai.verified/aiagent-webapi/README.md @@ -50,8 +50,8 @@ dotnet run -lp https ``` The application will start and listen on: -- HTTP: `http://localhost:9999` -- HTTPS: `https://localhost:9999` +- HTTP: `http://localhost:9996` +- HTTPS: `https://localhost:9995` ### 3. Test the Application diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.DefaultParameters.verified/aiagent-webapi/aiagent-webapi.csproj b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.oai.verified/aiagent-webapi/aiagent-webapi.csproj similarity index 69% rename from test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.DefaultParameters.verified/aiagent-webapi/aiagent-webapi.csproj rename to test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.oai.verified/aiagent-webapi/aiagent-webapi.csproj index 337bfdd220c..6e5004343c4 100644 --- a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.DefaultParameters.verified/aiagent-webapi/aiagent-webapi.csproj +++ b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.oai.verified/aiagent-webapi/aiagent-webapi.csproj @@ -4,16 +4,16 @@ net10.0 enable enable - secret + {00000000-0000-0000-0000-000000000000} - - - - - - + + + + + + diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.Ollama.verified/aiagent-webapi/appsettings.json b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.oai.verified/aiagent-webapi/appsettings.json similarity index 100% rename from test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi.Ollama.verified/aiagent-webapi/appsettings.json rename to test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.oai.verified/aiagent-webapi/appsettings.json diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/WebApiAgentTemplateExecutionTests.cs b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/WebApiAgentTemplateExecutionTests.cs deleted file mode 100644 index 2462a7bd002..00000000000 --- a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/WebApiAgentTemplateExecutionTests.cs +++ /dev/null @@ -1,123 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using Microsoft.Shared.ProjectTemplates.Tests; -using Xunit; -using Xunit.Abstractions; - -namespace Microsoft.Agents.AI.ProjectTemplates.Tests; - -/// -/// Contains execution tests for the "AI Agent Web API" template. -/// -/// -/// In addition to validating that the templates build and restore correctly, -/// these tests are also responsible for template component governance reporting. -/// This is because the generated output is left on disk after tests complete, -/// most importantly the project.assets.json file that gets created during restore. -/// Therefore, it's *critical* that these tests remain in a working state, -/// as disabling them will also disable CG reporting. -/// -public class WebApiAgentTemplateExecutionTests : TemplateExecutionTestBase, ITemplateExecutionTestConfigurationProvider -{ - public WebApiAgentTemplateExecutionTests(TemplateExecutionTestFixture fixture, ITestOutputHelper outputHelper) - : base(fixture, outputHelper) - { - } - - public static TemplateExecutionTestConfiguration Configuration { get; } = new() - { - TemplatePackageName = "Microsoft.Agents.AI.ProjectTemplates", - TestOutputFolderPrefix = "WebApiAgent" - }; - - public static IEnumerable GetTemplateOptions() - => GetFilteredTemplateOptions(); - - // Do not skip. See XML docs for this test class. - [Theory] - [MemberData(nameof(GetTemplateOptions))] - public async Task CreateRestoreAndBuild(params string[] args) - { - const string ProjectName = "WebApiAgentApp"; - var project = await Fixture.CreateProjectAsync( - templateName: "aiagent-webapi", - projectName: ProjectName, - args); - - await Fixture.RestoreProjectAsync(project); - await Fixture.BuildProjectAsync(project); - } - - private static readonly (string name, string[] values)[] _templateOptions = [ - ("--provider", ["azureopenai", "githubmodels", "ollama", "openai"]), - ("--managed-identity", ["true", "false"]), - ]; - - private static IEnumerable GetFilteredTemplateOptions(params string[] filter) - { - foreach (var options in GetAllPossibleOptions(_templateOptions)) - { - if (!MatchesFilter()) - { - continue; - } - - if (HasOption("--managed-identity", "true") && !HasOption("--provider", "azureopenai")) - { - // The managed identity option is only valid for Azure OpenAI. - continue; - } - - yield return options; - - bool MatchesFilter() - { - for (var i = 0; i < filter.Length; i += 2) - { - if (!HasOption(filter[i], filter[i + 1])) - { - return false; - } - } - - return true; - } - - bool HasOption(string name, string value) - { - for (var i = 0; i < options.Length; i += 2) - { - if (string.Equals(name, options[i], StringComparison.Ordinal) && - string.Equals(value, options[i + 1], StringComparison.Ordinal)) - { - return true; - } - } - - return false; - } - } - } - - private static IEnumerable GetAllPossibleOptions(ReadOnlyMemory<(string name, string[] values)> options) - { - if (options.Length == 0) - { - yield return []; - yield break; - } - - var first = options.Span[0]; - foreach (var restSelection in GetAllPossibleOptions(options[1..])) - { - foreach (var value in first.values) - { - yield return [first.name, value, .. restSelection]; - } - } - } -} diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/WebApiAgentTemplateSnapshotTests.cs b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/WebApiAgentTemplateSnapshotTests.cs deleted file mode 100644 index dce7ca19646..00000000000 --- a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/WebApiAgentTemplateSnapshotTests.cs +++ /dev/null @@ -1,139 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.Extensions.Logging; -using Microsoft.Shared.ProjectTemplates.Tests; -using Microsoft.TemplateEngine.Authoring.TemplateVerifier; -using Microsoft.TemplateEngine.TestHelper; -using Xunit; -using Xunit.Abstractions; - -namespace Microsoft.Agents.AI.ProjectTemplates.Tests; - -public class WebApiAgentTemplateSnapshotTests -{ - // Keep the exclude patterns below in sync with those in Microsoft.Agents.AI.ProjectTemplates.csproj. - private static readonly string[] _verificationExcludePatterns = [ - "**/bin/**", - "**/obj/**", - "**/.vs/**", - "**/*.user", - "**/*.in", - "**/NuGet.config", - "**/Directory.Build.targets", - "**/Directory.Build.props" - ]; - - private readonly ILogger _log; - - public WebApiAgentTemplateSnapshotTests(ITestOutputHelper log) - { -#pragma warning disable CA2000 // Dispose objects before losing scope - _log = new XunitLoggerProvider(log).CreateLogger("TestRun"); -#pragma warning restore CA2000 // Dispose objects before losing scope - } - - [Fact] - public async Task DefaultParameters() - { - await TestTemplateCoreAsync(scenarioName: nameof(DefaultParameters)); - } - - [Fact] - public async Task GitHubModels() - { - await TestTemplateCoreAsync(scenarioName: nameof(GitHubModels), templateArgs: ["--provider", "githubmodels"]); - } - - [Fact] - public async Task OpenAI() - { - await TestTemplateCoreAsync(scenarioName: nameof(OpenAI), templateArgs: ["--provider", "openai"]); - } - - [Fact] - public async Task AzureOpenAI_ManagedIdentity() - { - await TestTemplateCoreAsync(scenarioName: nameof(AzureOpenAI_ManagedIdentity), templateArgs: ["--provider", "azureopenai"]); - } - - [Fact] - public async Task AzureOpenAI_ApiKey() - { - await TestTemplateCoreAsync(scenarioName: nameof(AzureOpenAI_ApiKey), templateArgs: ["--provider", "azureopenai", "--managed-identity", "false"]); - } - - [Fact] - public async Task Ollama() - { - await TestTemplateCoreAsync(scenarioName: nameof(Ollama), templateArgs: ["--provider", "ollama"]); - } - - private async Task TestTemplateCoreAsync(string scenarioName, IEnumerable? templateArgs = null) - { - string workingDir = TestUtils.CreateTemporaryFolder(); - string templateShortName = "aiagent-webapi"; - - // Get the template location - string templateLocation = Path.Combine(WellKnownPaths.TemplateFeedLocation, "Microsoft.Agents.AI.ProjectTemplates", "src", "WebApiAgent"); - - var verificationExcludePatterns = Path.DirectorySeparatorChar is '/' - ? _verificationExcludePatterns - : _verificationExcludePatterns.Select(p => p.Replace('/', Path.DirectorySeparatorChar)).ToArray(); - - TemplateVerifierOptions options = new TemplateVerifierOptions(templateName: templateShortName) - { - TemplatePath = templateLocation, - TemplateSpecificArgs = templateArgs, - SnapshotsDirectory = "Snapshots", - OutputDirectory = workingDir, - DoNotPrependCallerMethodNameToScenarioName = true, - DoNotAppendTemplateArgsToScenarioName = true, - ScenarioName = scenarioName, - VerificationExcludePatterns = verificationExcludePatterns, - } - .WithCustomScrubbers( - ScrubbersDefinition.Empty.AddScrubber((path, content) => - { - string filePath = path.UnixifyDirSeparators(); - if (filePath.EndsWith(".sln")) - { - // Scrub .sln file GUIDs. - content.ScrubByRegex(pattern: @"\{.{36}\}", replacement: "{00000000-0000-0000-0000-000000000000}"); - } - - if (filePath.EndsWith(".csproj")) - { - content.ScrubByRegex("(.*)<\\/UserSecretsId>", "secret"); - - // Scrub references to just-built packages and remove the suffix, if it exists. - // This allows the snapshots to remain the same regardless of where the repo is built (e.g., locally, public CI, internal CI). - var pattern = @"(?<=)"; - content.ScrubByRegex(pattern, replacement: "$2"); - } - - if (filePath.EndsWith("launchSettings.json") || filePath.EndsWith("README.md")) - { - content.ScrubByRegex("(http(s?):\\/\\/localhost)\\:(\\d*)", "$1:9999"); - } - })); - - VerificationEngine engine = new VerificationEngine(_log); - await engine.Execute(options); - -#pragma warning disable CA1031 // Do not catch general exception types - try - { - Directory.Delete(workingDir, recursive: true); - } - catch - { - /* don't care */ - } -#pragma warning restore CA1031 // Do not catch general exception types - } -} diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/AIChatWebExecutionTests.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/AIChatWebExecutionTests.cs index 1f82e25f135..513f4cf0394 100644 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/AIChatWebExecutionTests.cs +++ b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/AIChatWebExecutionTests.cs @@ -1,13 +1,13 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.Shared.ProjectTemplates.Tests; using Microsoft.TestUtilities; using Xunit; using Xunit.Abstractions; +using static Microsoft.Shared.ProjectTemplates.Tests.TemplateTestUtilities; namespace Microsoft.Extensions.AI.Templates.Tests; @@ -32,193 +32,91 @@ public AIChatWebExecutionTests(TemplateExecutionTestFixture fixture, ITestOutput public static TemplateExecutionTestConfiguration Configuration { get; } = new() { TemplatePackageName = "Microsoft.Extensions.AI.Templates", - TestOutputFolderPrefix = "AIChatWeb" + TemplateName = "aichatweb" }; - public static IEnumerable GetBasicTemplateOptions() - => GetFilteredTemplateOptions("--aspire", "false"); + public static IEnumerable GetSupportedProjectConfigurations() + { + (string name, string[] values)[] allOptionValues = [ + ("--provider", ["azureopenai", "githubmodels", "ollama", "openai" /*, "azureaifoundry" */]), + ("--vector-store", ["azureaisearch", "local", "qdrant"]), + ("--aspire", ["true", "false"]), + ("--managed-identity", ["true", "false"]), + ("--Framework", ["net9.0", "net10.0"]) + ]; + + foreach (var args in GetPossibleOptions(allOptionValues)) + { + // Managed Identity only applies when using an Azure service and not using aspire + if (HasOption(args, "--managed-identity")) + { + if (HasOption(args, "--aspire")) + { + continue; + } - public static IEnumerable GetAspireTemplateOptions() - => GetFilteredTemplateOptions("--aspire", "true"); + if (!HasOption(args, "--provider", "azureopenai") && + !HasOption(args, "--provider", "azureaifoundry") && + !HasOption(args, "--vector-store", "azureaisearch")) + { + continue; + } + } - // Do not skip. See XML docs for this test class. - [Theory] - [MemberData(nameof(GetBasicTemplateOptions))] - public async Task CreateRestoreAndBuild_BasicTemplate(params string[] args) - { - const string ProjectName = "BasicApp"; - var project = await Fixture.CreateProjectAsync( - templateName: "aichatweb", - projectName: ProjectName, - args); + // Qdrant requires using Aspire orchestration + if (HasOption(args, "--vector-store", "qdrant") && !HasOption(args, "--aspire")) + { + continue; + } - await Fixture.RestoreProjectAsync(project); - await Fixture.BuildProjectAsync(project); + yield return args; + } } // Do not skip. See XML docs for this test class. [Theory] - [MemberData(nameof(GetAspireTemplateOptions))] - public async Task CreateRestoreAndBuild_AspireTemplate(params string[] args) + [MemberData(nameof(GetSupportedProjectConfigurations))] + public async Task TestAllSupportedConfigurations(params string[] args) { - const string ProjectName = "AspireApp"; - var project = await Fixture.CreateProjectAsync( - templateName: "aichatweb", - ProjectName, - args); + string projectName = GetProjectNameForArgs(args, prefix: "AIChatWeb"); + string? startupProjectRelativePath = HasOption(args, "--aspire") ? $"{projectName}.AppHost" : null; - project.StartupProjectRelativePath = $"{ProjectName}.AppHost"; - - await Fixture.RestoreProjectAsync(project); - await Fixture.BuildProjectAsync(project); + await CreateRestoreAndBuild(projectName, args, startupProjectRelativePath); } /// - /// Runs a single test with --aspire true and a project name that will trigger the class - /// name normalization bug reported in https://github.com/dotnet/extensions/issues/6811. + /// Runs a single test with --aspire and a project name that will trigger the class name + /// normalization bug reported in https://github.com/dotnet/extensions/issues/6811. /// [Fact] public async Task CreateRestoreAndBuild_AspireProjectName() { - await CreateRestoreAndBuild_AspireProjectName_Variants("azureopenai", "mix.ed-dash_name 123"); + await CreateRestoreAndBuild("mix.ed-dash_name 123", ["--aspire", "--provider", "azureopenai"]); } /// /// Tests build for various project name formats, including dots and other /// separators, to trigger the class name normalization bug described /// in https://github.com/dotnet/extensions/issues/6811 - /// This runs for all provider combinations with --aspire true and different - /// project names to ensure the bug is caught in all scenarios. /// /// - /// Because this test takes a long time to run, it is skipped by default. Set the - /// environment variable AI_TEMPLATES_TEST_PROJECT_NAMES to "true" or "1" + /// Because this test takes a few minutes to run and is only needed for regression + /// testing of project name handing integration with Aspire, it is skipped by default. + /// Set the environment variable AI_TEMPLATES_TEST_PROJECT_NAMES to "true" or "1" /// to enable it. /// [ConditionalTheory] [EnvironmentVariableCondition("AI_TEMPLATES_TEST_PROJECT_NAMES", "true", "1")] - [MemberData(nameof(GetAspireProjectNameVariants))] - public async Task CreateRestoreAndBuild_AspireProjectName_Variants(string provider, string projectName) - { - var project = await Fixture.CreateProjectAsync( - templateName: "aichatweb", - projectName: projectName, - args: new[] { "--aspire", $"--provider={provider}" }); - - project.StartupProjectRelativePath = $"{projectName}.AppHost"; - - await Fixture.RestoreProjectAsync(project); - await Fixture.BuildProjectAsync(project); - } - - private static readonly (string name, string[] values)[] _templateOptions = [ - ("--provider", ["azureopenai", "githubmodels", "ollama", "openai"]), - ("--vector-store", ["azureaisearch", "local", "qdrant"]), - ("--managed-identity", ["true", "false"]), - ("--aspire", ["true", "false"]), - ("--Framework", ["net9.0", "net10.0"]) - ]; - - private static IEnumerable GetFilteredTemplateOptions(params string[] filter) - { - foreach (var options in GetAllPossibleOptions(_templateOptions)) - { - if (!MatchesFilter()) - { - continue; - } - - if (HasOption("--managed-identity", "true")) - { - if (HasOption("--aspire", "true")) - { - // The managed identity option is disabled for the Aspire template. - continue; - } - - if (!HasOption("--vector-store", "azureaisearch") && - !HasOption("--aspire", "false")) - { - // Can only use managed identity when using Azure in the non-Aspire template. - continue; - } - } - - if (HasOption("--vector-store", "qdrant") && - HasOption("--aspire", "false")) - { - // Can't use Qdrant without Aspire. - continue; - } - - yield return options; - - bool MatchesFilter() - { - for (var i = 0; i < filter.Length; i += 2) - { - if (!HasOption(filter[i], filter[i + 1])) - { - return false; - } - } - - return true; - } - - bool HasOption(string name, string value) - { - for (var i = 0; i < options.Length; i += 2) - { - if (string.Equals(name, options[i], StringComparison.Ordinal) && - string.Equals(value, options[i + 1], StringComparison.Ordinal)) - { - return true; - } - } - - return false; - } - } - } - - private static IEnumerable GetAllPossibleOptions(ReadOnlyMemory<(string name, string[] values)> options) - { - if (options.Length == 0) - { - yield return []; - yield break; - } - - var first = options.Span[0]; - foreach (var restSelection in GetAllPossibleOptions(options[1..])) - { - foreach (var value in first.values) - { - yield return [first.name, value, .. restSelection]; - } - } - } - - public static IEnumerable GetAspireProjectNameVariants() + [InlineData("dot.name")] + [InlineData("project.123")] + [InlineData("space name")] + [InlineData(".1My.Projec-")] + [InlineData("1Project123")] + [InlineData("11double")] + [InlineData("1")] + [InlineData("nomatch")] + public async Task CreateRestoreAndBuild_AspireProjectName_Variants(string projectName) { - foreach (string provider in new[] { "ollama", "openai", "azureopenai", "githubmodels" }) - { - foreach (string projectName in new[] - { - "mix.ed-dash_name 123", - "dot.name", - "project.123", - "space name", - ".1My.Projec-", - "1Project123", - "11double", - "1", - "nomatch" - }) - { - yield return new object[] { provider, projectName }; - } - } + await CreateRestoreAndBuild(projectName, ["--aspire", "--provider", "azureopenai"]); } } diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/AIChatWebSnapshotTests.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/AIChatWebSnapshotTests.cs index 487d83834a4..dbe71cdbdef 100644 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/AIChatWebSnapshotTests.cs +++ b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/AIChatWebSnapshotTests.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; -using System.IO; -using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Shared.ProjectTemplates.Tests; @@ -11,26 +8,15 @@ using Microsoft.TemplateEngine.TestHelper; using Xunit; using Xunit.Abstractions; +using static Microsoft.Shared.ProjectTemplates.Tests.TemplateTestUtilities; namespace Microsoft.Extensions.AI.Templates.Tests; -public class AIChatWebSnapshotTests +public class AIChatWebSnapshotTests : TemplateSnapshotTestBase { - // Keep the exclude patterns below in sync with those in Microsoft.Extensions.AI.Templates.csproj. + // The wwwroot folder contains static content private static readonly string[] _verificationExcludePatterns = [ - "**/bin/**", - "**/obj/**", - "**/.vs/**", - "**/node_modules/**", - "**/*.user", - "**/*.in", - "**/*.out.js", - "**/*.generated.css", - "**/package-lock.json", - "**/ingestioncache.*", - "**/NuGet.config", - "**/Directory.Build.targets", - "**/Directory.Build.props", + "**/wwwroot/**" ]; private readonly ILogger _log; @@ -42,97 +28,31 @@ public AIChatWebSnapshotTests(ITestOutputHelper log) #pragma warning restore CA2000 // Dispose objects before losing scope } - [Fact] - public async Task BasicTest() + [Theory] + [InlineData /* Defaults: --provider=githubmodels --vector-store=local */] + [InlineData("--provider=ollama", "--vector-store=qdrant")] + [InlineData("--provider=openai", "--vector-store=azureaisearch")] + [InlineData("--aspire")] + [InlineData("--aspire", "--provider=azureopenai", "--vector-store=azureaisearch")] + public async Task RunSnapshotTests(params string[] templateArgs) { - await TestTemplateCoreAsync(scenarioName: "Basic"); - } - - [Fact] - public async Task Ollama_Qdrant() - { - await TestTemplateCoreAsync(scenarioName: "Ollama_Qdrant", templateArgs: ["--provider", "ollama", "--vector-store", "qdrant"]); - } - - [Fact] - public async Task OpenAI_AzureAISearch() - { - await TestTemplateCoreAsync(scenarioName: "OpenAI_AzureAISearch", templateArgs: ["--provider", "openai", "--vector-store", "azureaisearch"]); - } - - [Fact] - public async Task BasicAspireTest() - { - await TestTemplateCoreAsync(scenarioName: "BasicAspire", templateArgs: ["--aspire"]); - } - - [Fact] - public async Task AzureOpenAI_AzureAISearch_Aspire() - { - await TestTemplateCoreAsync(scenarioName: "AzureOpenAI_Qdrant_Aspire", templateArgs: ["--provider", "azureopenai", "--vector-store", "azureaisearch", "--aspire"]); - } - - private async Task TestTemplateCoreAsync(string scenarioName, IEnumerable? templateArgs = null) - { - string workingDir = TestUtils.CreateTemporaryFolder(); - string templateShortName = "aichatweb"; - - // Get the template location - string templateLocation = Path.Combine(WellKnownPaths.TemplateFeedLocation, "Microsoft.Extensions.AI.Templates", "src", "ChatWithCustomData"); - - var verificationExcludePatterns = Path.DirectorySeparatorChar is '/' - ? _verificationExcludePatterns - : _verificationExcludePatterns.Select(p => p.Replace('/', Path.DirectorySeparatorChar)).ToArray(); - - TemplateVerifierOptions options = new TemplateVerifierOptions(templateName: templateShortName) - { - TemplatePath = templateLocation, - TemplateSpecificArgs = templateArgs, - SnapshotsDirectory = "Snapshots", - OutputDirectory = workingDir, - DoNotPrependCallerMethodNameToScenarioName = true, - DoNotAppendTemplateArgsToScenarioName = true, - ScenarioName = scenarioName, - VerificationExcludePatterns = verificationExcludePatterns, - } - .WithCustomScrubbers( - ScrubbersDefinition.Empty.AddScrubber((path, content) => - { - string filePath = path.UnixifyDirSeparators(); - if (filePath.EndsWith(".sln")) - { - // Scrub .sln file GUIDs. - content.ScrubByRegex(pattern: @"\{.{36}\}", replacement: "{00000000-0000-0000-0000-000000000000}"); - } - - if (filePath.EndsWith(".csproj")) - { - content.ScrubByRegex("(.*)<\\/UserSecretsId>", "secret"); - - // Scrub references to just-built packages and remove the suffix, if it exists. - // This allows the snapshots to remain the same regardless of where the repo is built (e.g., locally, public CI, internal CI). - var pattern = @"(?<=)"; - content.ScrubByRegex(pattern, replacement: "$1"); - } - - if (filePath.EndsWith("launchSettings.json")) - { - content.ScrubByRegex("(http(s?):\\/\\/localhost)\\:(\\d*)", "$1:9999"); - } - })); + string projectNamePrefix = "AIChatWeb"; + string templatePackageName = "Microsoft.Extensions.AI.Templates"; + string templateName = "aichatweb"; + + TemplateVerifierOptions options = PrepareSnapshotVerifier( + projectNamePrefix, + templatePackageName, + templateName, + templateArgs, + _verificationExcludePatterns) + .WithCustomScrubbers(ScrubbersDefinition.Empty + .AddSolutionFileGuidScrubber() + .AddUserSecretsScrubber() + .AddPackageReferenceScrubber() + .AddLocalhostPortScrubber()); VerificationEngine engine = new VerificationEngine(_log); await engine.Execute(options); - -#pragma warning disable CA1031 // Do not catch general exception types - try - { - Directory.Delete(workingDir, recursive: true); - } - catch - { - /* don't care */ - } -#pragma warning restore CA1031 // Do not catch general exception types } } diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/McpServerExecutionTests.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/McpServerExecutionTests.cs new file mode 100644 index 00000000000..5a3abd9591b --- /dev/null +++ b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/McpServerExecutionTests.cs @@ -0,0 +1,56 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Collections.Generic; +using System.Threading.Tasks; +using Microsoft.Shared.ProjectTemplates.Tests; +using Xunit; +using Xunit.Abstractions; +using static Microsoft.Shared.ProjectTemplates.Tests.TemplateTestUtilities; + +namespace Microsoft.Extensions.AI.Templates.Tests; + +/// +/// Contains execution tests for the "AI Chat Web" template. +/// +/// +/// In addition to validating that the templates build and restore correctly, +/// these tests are also responsible for template component governance reporting. +/// This is because the generated output is left on disk after tests complete, +/// most importantly the project.assets.json file that gets created during restore. +/// Therefore, it's *critical* that these tests remain in a working state, +/// as disabling them will also disable CG reporting. +/// +public class McpServerExecutionTests : TemplateExecutionTestBase, ITemplateExecutionTestConfigurationProvider +{ + public McpServerExecutionTests(TemplateExecutionTestFixture fixture, ITestOutputHelper outputHelper) + : base(fixture, outputHelper) + { + } + + public static TemplateExecutionTestConfiguration Configuration { get; } = new() + { + TemplatePackageName = "Microsoft.Extensions.AI.Templates", + TemplateName = "mcpserver" + }; + + public static IEnumerable GetSupportedProjectConfigurations() + { + (string name, string[] values)[] allOptionValues = [ + ("--aot", ["true", "false"]), + ("--self-contained", ["true", "false"]), + ("--framework", ["net8.0", "net9.0", "net10.0"]) + ]; + + return GetPossibleOptions(allOptionValues); + } + + // Do not skip. See XML docs for this test class. + [Theory] + [MemberData(nameof(GetSupportedProjectConfigurations))] + public async Task TestAllSupportedConfigurations(params string[] args) + { + string projectName = GetProjectNameForArgs(args, prefix: "McpServer"); + await CreateRestoreAndBuild(projectName, args); + } +} diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/McpServerSnapshotTests.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/McpServerSnapshotTests.cs index ccfce67367a..c20b9345606 100644 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/McpServerSnapshotTests.cs +++ b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/McpServerSnapshotTests.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; -using System.IO; -using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Shared.ProjectTemplates.Tests; @@ -14,17 +11,8 @@ namespace Microsoft.Extensions.AI.Templates.Tests; -public class McpServerSnapshotTests +public class McpServerSnapshotTests : TemplateSnapshotTestBase { - // Keep the exclude patterns below in sync with those in Microsoft.Extensions.AI.Templates.csproj. - private static readonly string[] _verificationExcludePatterns = [ - "**/bin/**", - "**/obj/**", - "**/.vs/**", - "**/*.sln", - "**/*.in", - ]; - private readonly ILogger _log; public McpServerSnapshotTests(ITestOutputHelper log) @@ -34,79 +22,26 @@ public McpServerSnapshotTests(ITestOutputHelper log) #pragma warning restore CA2000 // Dispose objects before losing scope } - [Fact] - public async Task BasicTest() - { - await TestTemplateCoreAsync(scenarioName: "Basic"); - } - - [Fact] - public async Task SelfContainedFalse() - { - await TestTemplateCoreAsync(scenarioName: "SelfContainedFalse", templateArgs: ["--self-contained", bool.FalseString]); - } - - [Fact] - public async Task AotTrue() - { - await TestTemplateCoreAsync(scenarioName: "AotTrue", templateArgs: ["--aot", bool.TrueString]); - } - - [Fact] - public async Task Net10() + [Theory] + [InlineData /* Defaults: --self-contained=true --aot=false --framework=net10.0 */] + [InlineData("--self-contained=false")] + [InlineData("--aot=true")] + [InlineData("--framework=net8.0")] + public async Task TestSnapshots(params string[] templateArgs) { - await TestTemplateCoreAsync(scenarioName: "net10", templateArgs: ["--framework", "net10.0"]); - } - - private async Task TestTemplateCoreAsync(string scenarioName, IEnumerable? templateArgs = null) - { - string workingDir = TestUtils.CreateTemporaryFolder(); - string templateShortName = "mcpserver"; - - // Get the template location - string templateLocation = Path.Combine(WellKnownPaths.TemplateFeedLocation, "Microsoft.Extensions.AI.Templates", "src", "McpServer"); - - var verificationExcludePatterns = Path.DirectorySeparatorChar is '/' - ? _verificationExcludePatterns - : _verificationExcludePatterns.Select(p => p.Replace('/', Path.DirectorySeparatorChar)).ToArray(); - - TemplateVerifierOptions options = new TemplateVerifierOptions(templateName: templateShortName) - { - TemplatePath = templateLocation, - TemplateSpecificArgs = templateArgs, - SnapshotsDirectory = "Snapshots", - OutputDirectory = workingDir, - DoNotPrependCallerMethodNameToScenarioName = true, - DoNotAppendTemplateArgsToScenarioName = true, - ScenarioName = scenarioName, - VerificationExcludePatterns = verificationExcludePatterns, - } - .WithCustomScrubbers( - ScrubbersDefinition.Empty.AddScrubber((path, content) => - { - string filePath = path.UnixifyDirSeparators(); - - if (filePath.EndsWith(".csproj")) - { - // Scrub references to just-built packages and remove the suffix, if it exists. - // This allows the snapshots to remain the same regardless of where the repo is built (e.g., locally, public CI, internal CI). - var pattern = @"(?<=)"; - content.ScrubByRegex(pattern, replacement: "$1"); - } - })); + string projectNamePrefix = "McpServer"; + string templatePackageName = "Microsoft.Extensions.AI.Templates"; + string templateName = "mcpserver"; + + TemplateVerifierOptions options = PrepareSnapshotVerifier( + projectNamePrefix, + templatePackageName, + templateName, + templateArgs) + .WithCustomScrubbers(ScrubbersDefinition.Empty + .AddPackageReferenceScrubber()); VerificationEngine engine = new VerificationEngine(_log); await engine.Execute(options); - -#pragma warning disable CA1031 // Do not catch general exception types - try - { - Directory.Delete(workingDir, recursive: true); - } - catch - { - /* don't care */ - } -#pragma warning restore CA1031 // Do not catch general exception types } } diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Microsoft.Extensions.AI.Templates.Tests.csproj b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Microsoft.Extensions.AI.Templates.Tests.csproj index bd83d4fa93e..93e7ab12b63 100644 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Microsoft.Extensions.AI.Templates.Tests.csproj +++ b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Microsoft.Extensions.AI.Templates.Tests.csproj @@ -25,9 +25,6 @@ - - - diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/ProjectRootHelper.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/ProjectRootHelper.cs deleted file mode 100644 index 97be1100c35..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/ProjectRootHelper.cs +++ /dev/null @@ -1,35 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -using System; -using System.IO; -using System.Runtime.CompilerServices; - -namespace Microsoft.Shared.ProjectTemplates.Tests; - -/// -/// Contains a helper for determining the disk location of the containing project folder. -/// -/// -/// It's important that this file resides in the root of the containing project, or the returned -/// project root path will be incorrect. -/// -internal static class ProjectRootHelper -{ - public static string GetThisProjectRoot() - => GetThisProjectRootCore(); - - // This helper method is defined separately from its public variant because it extracts the - // caller file path via the [CallerFilePath] attribute. - // Therefore, the caller must be in a known location, i.e., this source file, to produce - // a reliable result. - private static string GetThisProjectRootCore([CallerFilePath] string callerFilePath = "") - { - if (Path.GetDirectoryName(callerFilePath) is not { Length: > 0 } testProjectRoot) - { - throw new InvalidOperationException("Could not determine the root of the test project."); - } - - return testProjectRoot; - } -} diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/Data/Example_Emergency_Survival_Kit.pdf b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/Data/Example_Emergency_Survival_Kit.pdf deleted file mode 100644 index 94625f0e0e0617c1324cf5243b06d0e8a2da6177..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 153539 zcmdSC1yohr8aBM?5a|YC(;b^`knZlTO-OeONJ|MQAt`Cl-61W~og#uD4GM_Vzd?`U zIh;H0_nkAof7~&2Y!>^S^Q}3b`K~$FdZ1Dkmt+Dlb0AZVZhU%=3<9zO9Zc^b3ka~N zTf5qVfwU5KU}sCPy_pwK&CS`}+TFw!C}-_Ths+}83^s9fa0b#UICxvz+M2L%GP45p zX|=5F%^f^kfQsrs5Gyk)KM?W@E)IU6Cl`l49q_KBqb*nqYzpaug_E6|nVk#LL{3^= zL7ow4Yi$DtN`cL693X-P$HvOW!O8{V1%W_Z?3@g&tTd2+5IF@0 z^ZzU&B!moxI0Xp{`>*hrnE*k^ETRfP7DWeVI}_VqLR`OuB&}^-A*QiN+Cpp)2b(#V zgOOR}!S#1MEt zph%PqZtFr!hHGMqyk9i=ts~7*#%;pBT~_>4V(QFkj^(#uF#}_0?^@WeQ2Cy!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4j^q@|j!gUHX%kDDyI zd~wlA_HKjV`ZteVOx33 zjQ^i7DCVmO0QR5df#K-R3S;~~6I7t&|1J-?`h2eKIut)%s6pEpEqy`pcHi+57=RRP zZ8(0-OL8bh_Dn>kCEmL>RB@X^NLjA(p{{W!zUzMTPO@kIoR<5M`84LJVbeNU0P1zq z4^O(t7vkAuH@G=26!_ToGp8Xef3sV;1$v=+Rg=q 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - return apply(func, thisArg, args); - }; -} -/** - * Creates a new function that constructs an instance of the given constructor function with the provided arguments. - * - * @param func - The constructor function to be wrapped and called. - * @returns A new function that constructs an instance of the given constructor function with the provided arguments. - */ -function unconstruct(func) { - return function () { - for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - args[_key2] = arguments[_key2]; - } - return construct(func, args); - }; -} -/** - * Add properties to a lookup table - * - * @param set - The set to which elements will be added. - * @param array - The array containing elements to be added to the set. - * @param transformCaseFunc - An optional function to transform the case of each element before adding to the set. - * @returns The modified set with added elements. - */ -function addToSet(set, array) { - let transformCaseFunc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : stringToLowerCase; - if (setPrototypeOf) { - // Make 'in' and truthy checks like Boolean(set.constructor) - // independent of any properties defined on Object.prototype. - // Prevent prototype setters from intercepting set as a this value. - setPrototypeOf(set, null); - } - let l = array.length; - while (l--) { - let element = array[l]; - if (typeof element === 'string') { - const lcElement = transformCaseFunc(element); - if (lcElement !== element) { - // Config presets (e.g. tags.js, attrs.js) are immutable. - if (!isFrozen(array)) { - array[l] = lcElement; - } - element = lcElement; - } - } - set[element] = true; - } - return set; -} -/** - * Clean up an array to harden against CSPP - * - * @param array - The array to be cleaned. - * @returns The cleaned version of the array - */ -function cleanArray(array) { - for (let index = 0; index < array.length; index++) { - const isPropertyExist = objectHasOwnProperty(array, index); - if (!isPropertyExist) { - array[index] = null; - } - } - return array; -} -/** - * Shallow clone an object - * - * @param object - The object to be cloned. - * @returns A new object that copies the original. - */ -function clone(object) { - const newObject = create(null); - for (const [property, value] of entries(object)) { - const isPropertyExist = objectHasOwnProperty(object, property); - if (isPropertyExist) { - if (Array.isArray(value)) { - newObject[property] = cleanArray(value); - } else if (value && typeof value === 'object' && value.constructor === Object) { - newObject[property] = clone(value); - } else { - newObject[property] = value; - } - } - } - return newObject; -} -/** - * This method automatically checks if the prop is function or getter and behaves accordingly. - * - * @param object - The object to look up the getter function in its prototype chain. - * @param prop - The property name for which to find the getter function. - * @returns The getter function found in the prototype chain or a fallback function. - */ -function lookupGetter(object, prop) { - while (object !== null) { - const desc = getOwnPropertyDescriptor(object, prop); - if (desc) { - if (desc.get) { - return unapply(desc.get); - } - if (typeof desc.value === 'function') { - return unapply(desc.value); - } - } - object = getPrototypeOf(object); - } - function fallbackValue() { - return null; - } - return fallbackValue; -} - -const html$1 = freeze(['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'content', 'data', 'datalist', 'dd', 'decorator', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meter', 'nav', 'nobr', 'ol', 'optgroup', 'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'section', 'select', 'shadow', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr']); -const svg$1 = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']); -const svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feDropShadow', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']); -// List of SVG elements that are disallowed by default. -// We still need to know them so that we can do namespace -// checks properly in case one wants to add them to -// allow-list. -const svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignobject', 'hatch', 'hatchpath', 'mesh', 'meshgradient', 'meshpatch', 'meshrow', 'missing-glyph', 'script', 'set', 'solidcolor', 'unknown', 'use']); -const mathMl$1 = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover', 'mprescripts']); -// Similarly to SVG, we want to know all MathML elements, -// even those that we disallow by default. -const mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']); -const text = freeze(['#text']); - -const html = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'nonce', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'pattern', 'placeholder', 'playsinline', 'popover', 'popovertarget', 'popovertargetaction', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'wrap', 'xmlns', 'slot']); -const svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'amplitude', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dur', 'edgemode', 'elevation', 'end', 'exponent', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'intercept', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'slope', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'tablevalues', 'targetx', 'targety', 'transform', 'transform-origin', 'text-anchor', 'text-decoration', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']); -const mathMl = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnsalign', 'columnlines', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lspace', 'lquote', 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset', 'width', 'xmlns']); -const xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']); - -// eslint-disable-next-line unicorn/better-regex -const MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode -const ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm); -const TMPLIT_EXPR = seal(/\$\{[\w\W]*/gm); // eslint-disable-line unicorn/better-regex -const DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]+$/); // eslint-disable-line no-useless-escape -const ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape -const IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i // eslint-disable-line no-useless-escape -); -const IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i); -const ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex -); -const DOCTYPE_NAME = seal(/^html$/i); -const CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i); - -var EXPRESSIONS = /*#__PURE__*/Object.freeze({ - __proto__: null, - ARIA_ATTR: ARIA_ATTR, - ATTR_WHITESPACE: ATTR_WHITESPACE, - CUSTOM_ELEMENT: CUSTOM_ELEMENT, - DATA_ATTR: DATA_ATTR, - DOCTYPE_NAME: DOCTYPE_NAME, - ERB_EXPR: ERB_EXPR, - IS_ALLOWED_URI: IS_ALLOWED_URI, - IS_SCRIPT_OR_DATA: IS_SCRIPT_OR_DATA, - MUSTACHE_EXPR: MUSTACHE_EXPR, - TMPLIT_EXPR: TMPLIT_EXPR -}); - -/* eslint-disable @typescript-eslint/indent */ -// https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType -const NODE_TYPE = { - element: 1, - attribute: 2, - text: 3, - cdataSection: 4, - entityReference: 5, - // Deprecated - entityNode: 6, - // Deprecated - progressingInstruction: 7, - comment: 8, - document: 9, - documentType: 10, - documentFragment: 11, - notation: 12 // Deprecated -}; -const getGlobal = function getGlobal() { - return typeof window === 'undefined' ? null : window; -}; -/** - * Creates a no-op policy for internal use only. - * Don't export this function outside this module! - * @param trustedTypes The policy factory. - * @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix). - * @return The policy created (or null, if Trusted Types - * are not supported or creating the policy failed). - */ -const _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, purifyHostElement) { - if (typeof trustedTypes !== 'object' || typeof trustedTypes.createPolicy !== 'function') { - return null; - } - // Allow the callers to control the unique policy name - // by adding a data-tt-policy-suffix to the script element with the DOMPurify. - // Policy creation with duplicate names throws in Trusted Types. - let suffix = null; - const ATTR_NAME = 'data-tt-policy-suffix'; - if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) { - suffix = purifyHostElement.getAttribute(ATTR_NAME); - } - const policyName = 'dompurify' + (suffix ? '#' + suffix : ''); - try { - return trustedTypes.createPolicy(policyName, { - createHTML(html) { - return html; - }, - createScriptURL(scriptUrl) { - return scriptUrl; - } - }); - } catch (_) { - // Policy creation failed (most likely another DOMPurify script has - // already run). Skip creating the policy, as this will only cause errors - // if TT are enforced. - console.warn('TrustedTypes policy ' + policyName + ' could not be created.'); - return null; - } -}; -const _createHooksMap = function _createHooksMap() { - return { - afterSanitizeAttributes: [], - afterSanitizeElements: [], - afterSanitizeShadowDOM: [], - beforeSanitizeAttributes: [], - beforeSanitizeElements: [], - beforeSanitizeShadowDOM: [], - uponSanitizeAttribute: [], - uponSanitizeElement: [], - uponSanitizeShadowNode: [] - }; -}; -function createDOMPurify() { - let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal(); - const DOMPurify = root => createDOMPurify(root); - DOMPurify.version = '3.2.4'; - DOMPurify.removed = []; - if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) { - // Not running in a browser, provide a factory function - // so that you can pass your own Window - DOMPurify.isSupported = false; - return DOMPurify; - } - let { - document - } = window; - const originalDocument = document; - const currentScript = originalDocument.currentScript; - const { - DocumentFragment, - HTMLTemplateElement, - Node, - Element, - NodeFilter, - NamedNodeMap = window.NamedNodeMap || window.MozNamedAttrMap, - HTMLFormElement, - DOMParser, - trustedTypes - } = window; - const ElementPrototype = Element.prototype; - const cloneNode = lookupGetter(ElementPrototype, 'cloneNode'); - const remove = lookupGetter(ElementPrototype, 'remove'); - const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling'); - const getChildNodes = lookupGetter(ElementPrototype, 'childNodes'); - const getParentNode = lookupGetter(ElementPrototype, 'parentNode'); - // As per issue #47, the web-components registry is inherited by a - // new document created via createHTMLDocument. As per the spec - // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries) - // a new empty registry is used when creating a template contents owner - // document, so we use that as our parent document to ensure nothing - // is inherited. - if (typeof HTMLTemplateElement === 'function') { - const template = document.createElement('template'); - if (template.content && template.content.ownerDocument) { - document = template.content.ownerDocument; - } - } - let trustedTypesPolicy; - let emptyHTML = ''; - const { - implementation, - createNodeIterator, - createDocumentFragment, - getElementsByTagName - } = document; - const { - importNode - } = originalDocument; - let hooks = _createHooksMap(); - /** - * Expose whether this browser supports running the full DOMPurify. - */ - DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined; - const { - MUSTACHE_EXPR, - ERB_EXPR, - TMPLIT_EXPR, - DATA_ATTR, - ARIA_ATTR, - IS_SCRIPT_OR_DATA, - ATTR_WHITESPACE, - CUSTOM_ELEMENT - } = EXPRESSIONS; - let { - IS_ALLOWED_URI: IS_ALLOWED_URI$1 - } = EXPRESSIONS; - /** - * We consider the elements and attributes below to be safe. Ideally - * don't add any new ones but feel free to remove unwanted ones. - */ - /* allowed element names */ - let ALLOWED_TAGS = null; - const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]); - /* Allowed attribute names */ - let ALLOWED_ATTR = null; - const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]); - /* - * Configure how DOMPurify should handle custom elements and their attributes as well as customized built-in elements. - * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements) - * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list) - * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`. - */ - let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, { - tagNameCheck: { - writable: true, - configurable: false, - enumerable: true, - value: null - }, - attributeNameCheck: { - writable: true, - configurable: false, - enumerable: true, - value: null - }, - allowCustomizedBuiltInElements: { - writable: true, - configurable: false, - enumerable: true, - value: false - } - })); - /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */ - let FORBID_TAGS = null; - /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */ - let FORBID_ATTR = null; - /* Decide if ARIA attributes are okay */ - let ALLOW_ARIA_ATTR = true; - /* Decide if custom data attributes are okay */ - let ALLOW_DATA_ATTR = true; - /* Decide if unknown protocols are okay */ - let ALLOW_UNKNOWN_PROTOCOLS = false; - /* Decide if self-closing tags in attributes are allowed. - * Usually removed due to a mXSS issue in jQuery 3.0 */ - let ALLOW_SELF_CLOSE_IN_ATTR = true; - /* Output should be safe for common template engines. - * This means, DOMPurify removes data attributes, mustaches and ERB - */ - let SAFE_FOR_TEMPLATES = false; - /* Output should be safe even for XML used within HTML and alike. - * This means, DOMPurify removes comments when containing risky content. - */ - let SAFE_FOR_XML = true; - /* Decide if document with ... should be returned */ - let WHOLE_DOCUMENT = false; - /* Track whether config is already set on this instance of DOMPurify. */ - let SET_CONFIG = false; - /* Decide if all elements (e.g. style, script) must be children of - * document.body. By default, browsers might move them to document.head */ - let FORCE_BODY = false; - /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html - * string (or a TrustedHTML object if Trusted Types are supported). - * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead - */ - let RETURN_DOM = false; - /* Decide if a DOM `DocumentFragment` should be returned, instead of a html - * string (or a TrustedHTML object if Trusted Types are supported) */ - let RETURN_DOM_FRAGMENT = false; - /* Try to return a Trusted Type object instead of a string, return a string in - * case Trusted Types are not supported */ - let RETURN_TRUSTED_TYPE = false; - /* Output should be free from DOM clobbering attacks? - * This sanitizes markups named with colliding, clobberable built-in DOM APIs. - */ - let SANITIZE_DOM = true; - /* Achieve full DOM Clobbering protection by isolating the namespace of named - * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules. - * - * HTML/DOM spec rules that enable DOM Clobbering: - * - Named Access on Window (§7.3.3) - * - DOM Tree Accessors (§3.1.5) - * - Form Element Parent-Child Relations (§4.10.3) - * - Iframe srcdoc / Nested WindowProxies (§4.8.5) - * - HTMLCollection (§4.2.10.2) - * - * Namespace isolation is implemented by prefixing `id` and `name` attributes - * with a constant string, i.e., `user-content-` - */ - let SANITIZE_NAMED_PROPS = false; - const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-'; - /* Keep element content when removing element? */ - let KEEP_CONTENT = true; - /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead - * of importing it into a new Document and returning a sanitized copy */ - let IN_PLACE = false; - /* Allow usage of profiles like html, svg and mathMl */ - let USE_PROFILES = {}; - /* Tags to ignore content of when KEEP_CONTENT is true */ - let FORBID_CONTENTS = null; - const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']); - /* Tags that are safe for data: URIs */ - let DATA_URI_TAGS = null; - const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']); - /* Attributes safe for values like "javascript:" */ - let URI_SAFE_ATTRIBUTES = null; - const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']); - const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML'; - const SVG_NAMESPACE = 'http://www.w3.org/2000/svg'; - const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml'; - /* Document namespace */ - let NAMESPACE = HTML_NAMESPACE; - let IS_EMPTY_INPUT = false; - /* Allowed XHTML+XML namespaces */ - let ALLOWED_NAMESPACES = null; - const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString); - let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']); - let HTML_INTEGRATION_POINTS = addToSet({}, ['annotation-xml']); - // Certain elements are allowed in both SVG and HTML - // namespace. We need to specify them explicitly - // so that they don't get erroneously deleted from - // HTML namespace. - const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']); - /* Parsing of strict XHTML documents */ - let PARSER_MEDIA_TYPE = null; - const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html']; - const DEFAULT_PARSER_MEDIA_TYPE = 'text/html'; - let transformCaseFunc = null; - /* Keep a reference to config to pass to hooks */ - let CONFIG = null; - /* Ideally, do not touch anything below this line */ - /* ______________________________________________ */ - const formElement = document.createElement('form'); - const isRegexOrFunction = function isRegexOrFunction(testValue) { - return testValue instanceof RegExp || testValue instanceof Function; - }; - /** - * _parseConfig - * - * @param cfg optional config literal - */ - // eslint-disable-next-line complexity - const _parseConfig = function _parseConfig() { - let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - if (CONFIG && CONFIG === cfg) { - return; - } - /* Shield configuration object from tampering */ - if (!cfg || typeof cfg !== 'object') { - cfg = {}; - } - /* Shield configuration object from prototype pollution */ - cfg = clone(cfg); - PARSER_MEDIA_TYPE = - // eslint-disable-next-line unicorn/prefer-includes - SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE; - // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is. - transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase; - /* Set configuration parameters */ - ALLOWED_TAGS = objectHasOwnProperty(cfg, 'ALLOWED_TAGS') ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS; - ALLOWED_ATTR = objectHasOwnProperty(cfg, 'ALLOWED_ATTR') ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR; - ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, 'ALLOWED_NAMESPACES') ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES; - URI_SAFE_ATTRIBUTES = objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR, transformCaseFunc) : DEFAULT_URI_SAFE_ATTRIBUTES; - DATA_URI_TAGS = objectHasOwnProperty(cfg, 'ADD_DATA_URI_TAGS') ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS, transformCaseFunc) : DEFAULT_DATA_URI_TAGS; - FORBID_CONTENTS = objectHasOwnProperty(cfg, 'FORBID_CONTENTS') ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS; - FORBID_TAGS = objectHasOwnProperty(cfg, 'FORBID_TAGS') ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : {}; - FORBID_ATTR = objectHasOwnProperty(cfg, 'FORBID_ATTR') ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : {}; - USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES : false; - ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true - ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true - ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false - ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true - SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false - SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true - WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false - RETURN_DOM = cfg.RETURN_DOM || false; // Default false - RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false - RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false - FORCE_BODY = cfg.FORCE_BODY || false; // Default false - SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true - SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false - KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true - IN_PLACE = cfg.IN_PLACE || false; // Default false - IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI; - NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE; - MATHML_TEXT_INTEGRATION_POINTS = cfg.MATHML_TEXT_INTEGRATION_POINTS || MATHML_TEXT_INTEGRATION_POINTS; - HTML_INTEGRATION_POINTS = cfg.HTML_INTEGRATION_POINTS || HTML_INTEGRATION_POINTS; - CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || {}; - if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) { - CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck; - } - if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) { - CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck; - } - if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === 'boolean') { - CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements; - } - if (SAFE_FOR_TEMPLATES) { - ALLOW_DATA_ATTR = false; - } - if (RETURN_DOM_FRAGMENT) { - RETURN_DOM = true; - } - /* Parse profile info */ - if (USE_PROFILES) { - ALLOWED_TAGS = addToSet({}, text); - ALLOWED_ATTR = []; - if (USE_PROFILES.html === true) { - addToSet(ALLOWED_TAGS, html$1); - addToSet(ALLOWED_ATTR, html); - } - if (USE_PROFILES.svg === true) { - addToSet(ALLOWED_TAGS, svg$1); - addToSet(ALLOWED_ATTR, svg); - addToSet(ALLOWED_ATTR, xml); - } - if (USE_PROFILES.svgFilters === true) { - addToSet(ALLOWED_TAGS, svgFilters); - addToSet(ALLOWED_ATTR, svg); - addToSet(ALLOWED_ATTR, xml); - } - if (USE_PROFILES.mathMl === true) { - addToSet(ALLOWED_TAGS, mathMl$1); - addToSet(ALLOWED_ATTR, mathMl); - addToSet(ALLOWED_ATTR, xml); - } - } - /* Merge configuration parameters */ - if (cfg.ADD_TAGS) { - if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) { - ALLOWED_TAGS = clone(ALLOWED_TAGS); - } - addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc); - } - if (cfg.ADD_ATTR) { - if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) { - ALLOWED_ATTR = clone(ALLOWED_ATTR); - } - addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc); - } - if (cfg.ADD_URI_SAFE_ATTR) { - addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc); - } - if (cfg.FORBID_CONTENTS) { - if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) { - FORBID_CONTENTS = clone(FORBID_CONTENTS); - } - addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc); - } - /* Add #text in case KEEP_CONTENT is set to true */ - if (KEEP_CONTENT) { - ALLOWED_TAGS['#text'] = true; - } - /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */ - if (WHOLE_DOCUMENT) { - addToSet(ALLOWED_TAGS, ['html', 'head', 'body']); - } - /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */ - if (ALLOWED_TAGS.table) { - addToSet(ALLOWED_TAGS, ['tbody']); - delete FORBID_TAGS.tbody; - } - if (cfg.TRUSTED_TYPES_POLICY) { - if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') { - throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.'); - } - if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') { - throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.'); - } - // Overwrite existing TrustedTypes policy. - trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY; - // Sign local variables required by `sanitize`. - emptyHTML = trustedTypesPolicy.createHTML(''); - } else { - // Uninitialized policy, attempt to initialize the internal dompurify policy. - if (trustedTypesPolicy === undefined) { - trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript); - } - // If creating the internal policy succeeded sign internal variables. - if (trustedTypesPolicy !== null && typeof emptyHTML === 'string') { - emptyHTML = trustedTypesPolicy.createHTML(''); - } - } - // Prevent further manipulation of configuration. - // Not available in IE8, Safari 5, etc. - if (freeze) { - freeze(cfg); - } - CONFIG = cfg; - }; - /* Keep track of all possible SVG and MathML tags - * so that we can perform the namespace checks - * correctly. */ - const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]); - const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]); - /** - * @param element a DOM element whose namespace is being checked - * @returns Return false if the element has a - * namespace that a spec-compliant parser would never - * return. Return true otherwise. - */ - const _checkValidNamespace = function _checkValidNamespace(element) { - let parent = getParentNode(element); - // In JSDOM, if we're inside shadow DOM, then parentNode - // can be null. We just simulate parent in this case. - if (!parent || !parent.tagName) { - parent = { - namespaceURI: NAMESPACE, - tagName: 'template' - }; - } - const tagName = stringToLowerCase(element.tagName); - const parentTagName = stringToLowerCase(parent.tagName); - if (!ALLOWED_NAMESPACES[element.namespaceURI]) { - return false; - } - if (element.namespaceURI === SVG_NAMESPACE) { - // The only way to switch from HTML namespace to SVG - // is via . If it happens via any other tag, then - // it should be killed. - if (parent.namespaceURI === HTML_NAMESPACE) { - return tagName === 'svg'; - } - // The only way to switch from MathML to SVG is via` - // svg if parent is either or MathML - // text integration points. - if (parent.namespaceURI === MATHML_NAMESPACE) { - return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]); - } - // We only allow elements that are defined in SVG - // spec. All others are disallowed in SVG namespace. - return Boolean(ALL_SVG_TAGS[tagName]); - } - if (element.namespaceURI === MATHML_NAMESPACE) { - // The only way to switch from HTML namespace to MathML - // is via . If it happens via any other tag, then - // it should be killed. - if (parent.namespaceURI === HTML_NAMESPACE) { - return tagName === 'math'; - } - // The only way to switch from SVG to MathML is via - // and HTML integration points - if (parent.namespaceURI === SVG_NAMESPACE) { - return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName]; - } - // We only allow elements that are defined in MathML - // spec. All others are disallowed in MathML namespace. - return Boolean(ALL_MATHML_TAGS[tagName]); - } - if (element.namespaceURI === HTML_NAMESPACE) { - // The only way to switch from SVG to HTML is via - // HTML integration points, and from MathML to HTML - // is via MathML text integration points - if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) { - return false; - } - if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) { - return false; - } - // We disallow tags that are specific for MathML - // or SVG and should never appear in HTML namespace - return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]); - } - // For XHTML and XML documents that support custom namespaces - if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) { - return true; - } - // The code should never reach this place (this means - // that the element somehow got namespace that is not - // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES). - // Return false just in case. - return false; - }; - /** - * _forceRemove - * - * @param node a DOM node - */ - const _forceRemove = function _forceRemove(node) { - arrayPush(DOMPurify.removed, { - element: node - }); - try { - // eslint-disable-next-line unicorn/prefer-dom-node-remove - getParentNode(node).removeChild(node); - } catch (_) { - remove(node); - } - }; - /** - * _removeAttribute - * - * @param name an Attribute name - * @param element a DOM node - */ - const _removeAttribute = function _removeAttribute(name, element) { - try { - arrayPush(DOMPurify.removed, { - attribute: element.getAttributeNode(name), - from: element - }); - } catch (_) { - arrayPush(DOMPurify.removed, { - attribute: null, - from: element - }); - } - element.removeAttribute(name); - // We void attribute values for unremovable "is" attributes - if (name === 'is') { - if (RETURN_DOM || RETURN_DOM_FRAGMENT) { - try { - _forceRemove(element); - } catch (_) {} - } else { - try { - element.setAttribute(name, ''); - } catch (_) {} - } - } - }; - /** - * _initDocument - * - * @param dirty - a string of dirty markup - * @return a DOM, filled with the dirty markup - */ - const _initDocument = function _initDocument(dirty) { - /* Create a HTML document */ - let doc = null; - let leadingWhitespace = null; - if (FORCE_BODY) { - dirty = '' + dirty; - } else { - /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */ - const matches = stringMatch(dirty, /^[\r\n\t ]+/); - leadingWhitespace = matches && matches[0]; - } - if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) { - // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict) - dirty = '' + dirty + ''; - } - const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty; - /* - * Use the DOMParser API by default, fallback later if needs be - * DOMParser not work for svg when has multiple root element. - */ - if (NAMESPACE === HTML_NAMESPACE) { - try { - doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE); - } catch (_) {} - } - /* Use createHTMLDocument in case DOMParser is not available */ - if (!doc || !doc.documentElement) { - doc = implementation.createDocument(NAMESPACE, 'template', null); - try { - doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload; - } catch (_) { - // Syntax error if dirtyPayload is invalid xml - } - } - const body = doc.body || doc.documentElement; - if (dirty && leadingWhitespace) { - body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null); - } - /* Work on whole document or just its body */ - if (NAMESPACE === HTML_NAMESPACE) { - return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0]; - } - return WHOLE_DOCUMENT ? doc.documentElement : body; - }; - /** - * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. - * - * @param root The root element or node to start traversing on. - * @return The created NodeIterator - */ - const _createNodeIterator = function _createNodeIterator(root) { - return createNodeIterator.call(root.ownerDocument || root, root, - // eslint-disable-next-line no-bitwise - NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null); - }; - /** - * _isClobbered - * - * @param element element to check for clobbering attacks - * @return true if clobbered, false if safe - */ - const _isClobbered = function _isClobbered(element) { - return element instanceof HTMLFormElement && (typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' || !(element.attributes instanceof NamedNodeMap) || typeof element.removeAttribute !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function'); - }; - /** - * Checks whether the given object is a DOM node. - * - * @param value object to check whether it's a DOM node - * @return true is object is a DOM node - */ - const _isNode = function _isNode(value) { - return typeof Node === 'function' && value instanceof Node; - }; - function _executeHooks(hooks, currentNode, data) { - arrayForEach(hooks, hook => { - hook.call(DOMPurify, currentNode, data, CONFIG); - }); - } - /** - * _sanitizeElements - * - * @protect nodeName - * @protect textContent - * @protect removeChild - * @param currentNode to check for permission to exist - * @return true if node was killed, false if left alive - */ - const _sanitizeElements = function _sanitizeElements(currentNode) { - let content = null; - /* Execute a hook if present */ - _executeHooks(hooks.beforeSanitizeElements, currentNode, null); - /* Check if element is clobbered or can clobber */ - if (_isClobbered(currentNode)) { - _forceRemove(currentNode); - return true; - } - /* Now let's check the element's type and name */ - const tagName = transformCaseFunc(currentNode.nodeName); - /* Execute a hook if present */ - _executeHooks(hooks.uponSanitizeElement, currentNode, { - tagName, - allowedTags: ALLOWED_TAGS - }); - /* Detect mXSS attempts abusing namespace confusion */ - if (currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\w]/g, currentNode.innerHTML) && regExpTest(/<[/\w]/g, currentNode.textContent)) { - _forceRemove(currentNode); - return true; - } - /* Remove any occurrence of processing instructions */ - if (currentNode.nodeType === NODE_TYPE.progressingInstruction) { - _forceRemove(currentNode); - return true; - } - /* Remove any kind of possibly harmful comments */ - if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(/<[/\w]/g, currentNode.data)) { - _forceRemove(currentNode); - return true; - } - /* Remove element if anything forbids its presence */ - if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) { - /* Check if we have a custom element to handle */ - if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) { - if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) { - return false; - } - if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) { - return false; - } - } - /* Keep content except for bad-listed elements */ - if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) { - const parentNode = getParentNode(currentNode) || currentNode.parentNode; - const childNodes = getChildNodes(currentNode) || currentNode.childNodes; - if (childNodes && parentNode) { - const childCount = childNodes.length; - for (let i = childCount - 1; i >= 0; --i) { - const childClone = cloneNode(childNodes[i], true); - childClone.__removalCount = (currentNode.__removalCount || 0) + 1; - parentNode.insertBefore(childClone, getNextSibling(currentNode)); - } - } - } - _forceRemove(currentNode); - return true; - } - /* Check whether element has a valid namespace */ - if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) { - _forceRemove(currentNode); - return true; - } - /* Make sure that older browsers don't get fallback-tag mXSS */ - if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)) { - _forceRemove(currentNode); - return true; - } - /* Sanitize element content to be template-safe */ - if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) { - /* Get the element's text content */ - content = currentNode.textContent; - arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => { - content = stringReplace(content, expr, ' '); - }); - if (currentNode.textContent !== content) { - arrayPush(DOMPurify.removed, { - element: currentNode.cloneNode() - }); - currentNode.textContent = content; - } - } - /* Execute a hook if present */ - _executeHooks(hooks.afterSanitizeElements, currentNode, null); - return false; - }; - /** - * _isValidAttribute - * - * @param lcTag Lowercase tag name of containing element. - * @param lcName Lowercase attribute name. - * @param value Attribute value. - * @return Returns true if `value` is valid, otherwise false. - */ - // eslint-disable-next-line complexity - const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) { - /* Make sure attribute cannot clobber */ - if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) { - return false; - } - /* Allow valid data-* attributes: At least one character after "-" - (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes) - XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804) - We don't need to check the value; it's always URI safe. */ - if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR, lcName)) ; else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) { - if ( - // First condition does a very basic check if a) it's basically a valid custom element tagname AND - // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck - // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck - _isBasicCustomElement(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName)) || - // Alternative, second condition checks if it's an `is`-attribute, AND - // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck - lcName === 'is' && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))) ; else { - return false; - } - /* Check value is safe. First, is attr inert? If so, is safe */ - } else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) ; else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if (value) { - return false; - } else ; - return true; - }; - /** - * _isBasicCustomElement - * checks if at least one dash is included in tagName, and it's not the first char - * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name - * - * @param tagName name of the tag of the node to sanitize - * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false. - */ - const _isBasicCustomElement = function _isBasicCustomElement(tagName) { - return tagName !== 'annotation-xml' && stringMatch(tagName, CUSTOM_ELEMENT); - }; - /** - * _sanitizeAttributes - * - * @protect attributes - * @protect nodeName - * @protect removeAttribute - * @protect setAttribute - * - * @param currentNode to sanitize - */ - const _sanitizeAttributes = function _sanitizeAttributes(currentNode) { - /* Execute a hook if present */ - _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null); - const { - attributes - } = currentNode; - /* Check if we have attributes; if not we might have a text node */ - if (!attributes || _isClobbered(currentNode)) { - return; - } - const hookEvent = { - attrName: '', - attrValue: '', - keepAttr: true, - allowedAttributes: ALLOWED_ATTR, - forceKeepAttr: undefined - }; - let l = attributes.length; - /* Go backwards over all attributes; safely remove bad ones */ - while (l--) { - const attr = attributes[l]; - const { - name, - namespaceURI, - value: attrValue - } = attr; - const lcName = transformCaseFunc(name); - let value = name === 'value' ? attrValue : stringTrim(attrValue); - /* Execute a hook if present */ - hookEvent.attrName = lcName; - hookEvent.attrValue = value; - hookEvent.keepAttr = true; - hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set - _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent); - value = hookEvent.attrValue; - /* Full DOM Clobbering protection via namespace isolation, - * Prefix id and name attributes with `user-content-` - */ - if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name')) { - // Remove the attribute with this value - _removeAttribute(name, currentNode); - // Prefix the value and later re-create the attribute with the sanitized value - value = SANITIZE_NAMED_PROPS_PREFIX + value; - } - /* Work around a security issue with comments inside attributes */ - if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|title)/i, value)) { - _removeAttribute(name, currentNode); - continue; - } - /* Did the hooks approve of the attribute? */ - if (hookEvent.forceKeepAttr) { - continue; - } - /* Remove attribute */ - _removeAttribute(name, currentNode); - /* Did the hooks approve of the attribute? */ - if (!hookEvent.keepAttr) { - continue; - } - /* Work around a security issue in jQuery 3.0 */ - if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) { - _removeAttribute(name, currentNode); - continue; - } - /* Sanitize attribute content to be template-safe */ - if (SAFE_FOR_TEMPLATES) { - arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => { - value = stringReplace(value, expr, ' '); - }); - } - /* Is `value` valid for this attribute? */ - const lcTag = transformCaseFunc(currentNode.nodeName); - if (!_isValidAttribute(lcTag, lcName, value)) { - continue; - } - /* Handle attributes that require Trusted Types */ - if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function') { - if (namespaceURI) ; else { - switch (trustedTypes.getAttributeType(lcTag, lcName)) { - case 'TrustedHTML': - { - value = trustedTypesPolicy.createHTML(value); - break; - } - case 'TrustedScriptURL': - { - value = trustedTypesPolicy.createScriptURL(value); - break; - } - } - } - } - /* Handle invalid data-* attribute set by try-catching it */ - try { - if (namespaceURI) { - currentNode.setAttributeNS(namespaceURI, name, value); - } else { - /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */ - currentNode.setAttribute(name, value); - } - if (_isClobbered(currentNode)) { - _forceRemove(currentNode); - } else { - arrayPop(DOMPurify.removed); - } - } catch (_) {} - } - /* Execute a hook if present */ - _executeHooks(hooks.afterSanitizeAttributes, currentNode, null); - }; - /** - * _sanitizeShadowDOM - * - * @param fragment to iterate over recursively - */ - const _sanitizeShadowDOM = function _sanitizeShadowDOM(fragment) { - let shadowNode = null; - const shadowIterator = _createNodeIterator(fragment); - /* Execute a hook if present */ - _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null); - while (shadowNode = shadowIterator.nextNode()) { - /* Execute a hook if present */ - _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null); - /* Sanitize tags and elements */ - _sanitizeElements(shadowNode); - /* Check attributes next */ - _sanitizeAttributes(shadowNode); - /* Deep shadow DOM detected */ - if (shadowNode.content instanceof DocumentFragment) { - _sanitizeShadowDOM(shadowNode.content); - } - } - /* Execute a hook if present */ - _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null); - }; - // eslint-disable-next-line complexity - DOMPurify.sanitize = function (dirty) { - let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - let body = null; - let importedNode = null; - let currentNode = null; - let returnNode = null; - /* Make sure we have a string to sanitize. - DO NOT return early, as this will return the wrong type if - the user has requested a DOM object rather than a string */ - IS_EMPTY_INPUT = !dirty; - if (IS_EMPTY_INPUT) { - dirty = ''; - } - /* Stringify, in case dirty is an object */ - if (typeof dirty !== 'string' && !_isNode(dirty)) { - if (typeof dirty.toString === 'function') { - dirty = dirty.toString(); - if (typeof dirty !== 'string') { - throw typeErrorCreate('dirty is not a string, aborting'); - } - } else { - throw typeErrorCreate('toString is not a function'); - } - } - /* Return dirty HTML if DOMPurify cannot run */ - if (!DOMPurify.isSupported) { - return dirty; - } - /* Assign config vars */ - if (!SET_CONFIG) { - _parseConfig(cfg); - } - /* Clean up removed elements */ - DOMPurify.removed = []; - /* Check if dirty is correctly typed for IN_PLACE */ - if (typeof dirty === 'string') { - IN_PLACE = false; - } - if (IN_PLACE) { - /* Do some early pre-sanitization to avoid unsafe root nodes */ - if (dirty.nodeName) { - const tagName = transformCaseFunc(dirty.nodeName); - if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) { - throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place'); - } - } - } else if (dirty instanceof Node) { - /* If dirty is a DOM element, append to an empty document to avoid - elements being stripped by the parser */ - body = _initDocument(''); - importedNode = body.ownerDocument.importNode(dirty, true); - if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === 'BODY') { - /* Node is already a body, use as is */ - body = importedNode; - } else if (importedNode.nodeName === 'HTML') { - body = importedNode; - } else { - // eslint-disable-next-line unicorn/prefer-dom-node-append - body.appendChild(importedNode); - } - } else { - /* Exit directly if we have nothing to do */ - if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT && - // eslint-disable-next-line unicorn/prefer-includes - dirty.indexOf('<') === -1) { - return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty; - } - /* Initialize the document to work on */ - body = _initDocument(dirty); - /* Check we have a DOM node from the data */ - if (!body) { - return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : ''; - } - } - /* Remove first element node (ours) if FORCE_BODY is set */ - if (body && FORCE_BODY) { - _forceRemove(body.firstChild); - } - /* Get node iterator */ - const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body); - /* Now start iterating over the created document */ - while (currentNode = nodeIterator.nextNode()) { - /* Sanitize tags and elements */ - _sanitizeElements(currentNode); - /* Check attributes next */ - _sanitizeAttributes(currentNode); - /* Shadow DOM detected, sanitize it */ - if (currentNode.content instanceof DocumentFragment) { - _sanitizeShadowDOM(currentNode.content); - } - } - /* If we sanitized `dirty` in-place, return it. */ - if (IN_PLACE) { - return dirty; - } - /* Return sanitized string or DOM */ - if (RETURN_DOM) { - if (RETURN_DOM_FRAGMENT) { - returnNode = createDocumentFragment.call(body.ownerDocument); - while (body.firstChild) { - // eslint-disable-next-line unicorn/prefer-dom-node-append - returnNode.appendChild(body.firstChild); - } - } else { - returnNode = body; - } - if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) { - /* - AdoptNode() is not used because internal state is not reset - (e.g. the past names map of a HTMLFormElement), this is safe - in theory but we would rather not risk another attack vector. - The state that is cloned by importNode() is explicitly defined - by the specs. - */ - returnNode = importNode.call(originalDocument, returnNode, true); - } - return returnNode; - } - let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML; - /* Serialize doctype if allowed */ - if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) { - serializedHTML = '\n' + serializedHTML; - } - /* Sanitize final string template-safe */ - if (SAFE_FOR_TEMPLATES) { - arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => { - serializedHTML = stringReplace(serializedHTML, expr, ' '); - }); - } - return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML; - }; - DOMPurify.setConfig = function () { - let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - _parseConfig(cfg); - SET_CONFIG = true; - }; - DOMPurify.clearConfig = function () { - CONFIG = null; - SET_CONFIG = false; - }; - DOMPurify.isValidAttribute = function (tag, attr, value) { - /* Initialize shared config vars if necessary. */ - if (!CONFIG) { - _parseConfig({}); - } - const lcTag = transformCaseFunc(tag); - const lcName = transformCaseFunc(attr); - return _isValidAttribute(lcTag, lcName, value); - }; - DOMPurify.addHook = function (entryPoint, hookFunction) { - if (typeof hookFunction !== 'function') { - return; - } - arrayPush(hooks[entryPoint], hookFunction); - }; - DOMPurify.removeHook = function (entryPoint, hookFunction) { - if (hookFunction !== undefined) { - const index = arrayLastIndexOf(hooks[entryPoint], hookFunction); - return index === -1 ? undefined : arraySplice(hooks[entryPoint], index, 1)[0]; - } - return arrayPop(hooks[entryPoint]); - }; - DOMPurify.removeHooks = function (entryPoint) { - hooks[entryPoint] = []; - }; - DOMPurify.removeAllHooks = function () { - hooks = _createHooksMap(); - }; - return DOMPurify; -} -var purify = createDOMPurify(); - -export { purify as default }; -//# sourceMappingURL=purify.es.mjs.map diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/markdown_viewer/viewer.html b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/markdown_viewer/viewer.html deleted file mode 100644 index 94447ffc47e..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/markdown_viewer/viewer.html +++ /dev/null @@ -1,32 +0,0 @@ - - - - - Markdown viewer - - - - -

- - - diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/markdown_viewer/viewer.mjs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/markdown_viewer/viewer.mjs deleted file mode 100644 index 78eb819c9a8..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/markdown_viewer/viewer.mjs +++ /dev/null @@ -1,13 +0,0 @@ -import { parse } from '../marked/dist/marked.esm.js'; -import purify from '../dompurify/dist/purify.es.mjs'; - -const url = new URL(window.location); -const fileUrl = url.searchParams.get('file'); -if (!fileUrl) { - throw new Error('File not specified in the URL query string'); -} - -var response = await fetch(fileUrl); -var text = await response.text(); - -document.getElementById('content').innerHTML = purify.sanitize(parse(text)); diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/marked/README.md b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/marked/README.md deleted file mode 100644 index 352b52d5503..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/marked/README.md +++ /dev/null @@ -1,5 +0,0 @@ -marked version 15.0.6 -https://github.com/markedjs/marked -License: MIT - -To update, replace the `dist/marked.esm.js` file with with an updated version from https://www.npmjs.com/package/marked. diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/marked/dist/marked.esm.js b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/marked/dist/marked.esm.js deleted file mode 100644 index a32cd778363..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/marked/dist/marked.esm.js +++ /dev/null @@ -1,2568 +0,0 @@ -/** - * marked v15.0.6 - a markdown parser - * Copyright (c) 2011-2025, Christopher Jeffrey. (MIT Licensed) - * https://github.com/markedjs/marked - */ - -/** - * DO NOT EDIT THIS FILE - * The code in this file is generated from files in ./src/ - */ - -/** - * Gets the original marked default options. - */ -function _getDefaults() { - return { - async: false, - breaks: false, - extensions: null, - gfm: true, - hooks: null, - pedantic: false, - renderer: null, - silent: false, - tokenizer: null, - walkTokens: null, - }; -} -let _defaults = _getDefaults(); -function changeDefaults(newDefaults) { - _defaults = newDefaults; -} - -const noopTest = { exec: () => null }; -function edit(regex, opt = '') { - let source = typeof regex === 'string' ? regex : regex.source; - const obj = { - replace: (name, val) => { - let valSource = typeof val === 'string' ? val : val.source; - valSource = valSource.replace(other.caret, '$1'); - source = source.replace(name, valSource); - return obj; - }, - getRegex: () => { - return new RegExp(source, opt); - }, - }; - return obj; -} -const other = { - codeRemoveIndent: /^(?: {1,4}| {0,3}\t)/gm, - outputLinkReplace: /\\([\[\]])/g, - indentCodeCompensation: /^(\s+)(?:```)/, - beginningSpace: /^\s+/, - endingHash: /#$/, - startingSpaceChar: /^ /, - endingSpaceChar: / $/, - nonSpaceChar: /[^ ]/, - newLineCharGlobal: /\n/g, - tabCharGlobal: /\t/g, - multipleSpaceGlobal: /\s+/g, - blankLine: /^[ \t]*$/, - doubleBlankLine: /\n[ \t]*\n[ \t]*$/, - blockquoteStart: /^ {0,3}>/, - blockquoteSetextReplace: /\n {0,3}((?:=+|-+) *)(?=\n|$)/g, - blockquoteSetextReplace2: /^ {0,3}>[ \t]?/gm, - listReplaceTabs: /^\t+/, - listReplaceNesting: /^ {1,4}(?=( {4})*[^ ])/g, - listIsTask: /^\[[ xX]\] /, - listReplaceTask: /^\[[ xX]\] +/, - anyLine: /\n.*\n/, - hrefBrackets: /^<(.*)>$/, - tableDelimiter: /[:|]/, - tableAlignChars: /^\||\| *$/g, - tableRowBlankLine: /\n[ \t]*$/, - tableAlignRight: /^ *-+: *$/, - tableAlignCenter: /^ *:-+: *$/, - tableAlignLeft: /^ *:-+ *$/, - startATag: /^/i, - startPreScriptTag: /^<(pre|code|kbd|script)(\s|>)/i, - endPreScriptTag: /^<\/(pre|code|kbd|script)(\s|>)/i, - startAngleBracket: /^$/, - pedanticHrefTitle: /^([^'"]*[^\s])\s+(['"])(.*)\2/, - unicodeAlphaNumeric: /[\p{L}\p{N}]/u, - escapeTest: /[&<>"']/, - escapeReplace: /[&<>"']/g, - escapeTestNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/, - escapeReplaceNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g, - unescapeTest: /&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig, - caret: /(^|[^\[])\^/g, - percentDecode: /%25/g, - findPipe: /\|/g, - splitPipe: / \|/, - slashPipe: /\\\|/g, - carriageReturn: /\r\n|\r/g, - spaceLine: /^ +$/gm, - notSpaceStart: /^\S*/, - endingNewline: /\n$/, - listItemRegex: (bull) => new RegExp(`^( {0,3}${bull})((?:[\t ][^\\n]*)?(?:\\n|$))`), - nextBulletRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ \t][^\\n]*)?(?:\\n|$))`), - hrRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`), - fencesBeginRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\`\`\`|~~~)`), - headingBeginRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`), - htmlBeginRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}<(?:[a-z].*>|!--)`, 'i'), -}; -/** - * Block-Level Grammar - */ -const newline = /^(?:[ \t]*(?:\n|$))+/; -const blockCode = /^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/; -const fences = /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/; -const hr = /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/; -const heading = /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/; -const bullet = /(?:[*+-]|\d{1,9}[.)])/; -const lheading = edit(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/) - .replace(/bull/g, bullet) // lists can interrupt - .replace(/blockCode/g, /(?: {4}| {0,3}\t)/) // indented code blocks can interrupt - .replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/) // fenced code blocks can interrupt - .replace(/blockquote/g, / {0,3}>/) // blockquote can interrupt - .replace(/heading/g, / {0,3}#{1,6}/) // ATX heading can interrupt - .replace(/html/g, / {0,3}<[^\n>]+>\n/) // block html can interrupt - .getRegex(); -const _paragraph = /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/; -const blockText = /^[^\n]+/; -const _blockLabel = /(?!\s*\])(?:\\.|[^\[\]\\])+/; -const def = edit(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/) - .replace('label', _blockLabel) - .replace('title', /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/) - .getRegex(); -const list = edit(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/) - .replace(/bull/g, bullet) - .getRegex(); -const _tag = 'address|article|aside|base|basefont|blockquote|body|caption' - + '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption' - + '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe' - + '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option' - + '|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title' - + '|tr|track|ul'; -const _comment = /|$))/; -const html = edit('^ {0,3}(?:' // optional indentation - + '<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)' // (1) - + '|comment[^\\n]*(\\n+|$)' // (2) - + '|<\\?[\\s\\S]*?(?:\\?>\\n*|$)' // (3) - + '|\\n*|$)' // (4) - + '|\\n*|$)' // (5) - + '|)[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)' // (6) - + '|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)' // (7) open tag - + '|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)' // (7) closing tag - + ')', 'i') - .replace('comment', _comment) - .replace('tag', _tag) - .replace('attribute', / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/) - .getRegex(); -const paragraph = edit(_paragraph) - .replace('hr', hr) - .replace('heading', ' {0,3}#{1,6}(?:\\s|$)') - .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs - .replace('|table', '') - .replace('blockquote', ' {0,3}>') - .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n') - .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt - .replace('html', ')|<(?:script|pre|style|textarea|!--)') - .replace('tag', _tag) // pars can be interrupted by type (6) html blocks - .getRegex(); -const blockquote = edit(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/) - .replace('paragraph', paragraph) - .getRegex(); -/** - * Normal Block Grammar - */ -const blockNormal = { - blockquote, - code: blockCode, - def, - fences, - heading, - hr, - html, - lheading, - list, - newline, - paragraph, - table: noopTest, - text: blockText, -}; -/** - * GFM Block Grammar - */ -const gfmTable = edit('^ *([^\\n ].*)\\n' // Header - + ' {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)' // Align - + '(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)') // Cells - .replace('hr', hr) - .replace('heading', ' {0,3}#{1,6}(?:\\s|$)') - .replace('blockquote', ' {0,3}>') - .replace('code', '(?: {4}| {0,3}\t)[^\\n]') - .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n') - .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt - .replace('html', ')|<(?:script|pre|style|textarea|!--)') - .replace('tag', _tag) // tables can be interrupted by type (6) html blocks - .getRegex(); -const blockGfm = { - ...blockNormal, - table: gfmTable, - paragraph: edit(_paragraph) - .replace('hr', hr) - .replace('heading', ' {0,3}#{1,6}(?:\\s|$)') - .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs - .replace('table', gfmTable) // interrupt paragraphs with table - .replace('blockquote', ' {0,3}>') - .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n') - .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt - .replace('html', ')|<(?:script|pre|style|textarea|!--)') - .replace('tag', _tag) // pars can be interrupted by type (6) html blocks - .getRegex(), -}; -/** - * Pedantic grammar (original John Gruber's loose markdown specification) - */ -const blockPedantic = { - ...blockNormal, - html: edit('^ *(?:comment *(?:\\n|\\s*$)' - + '|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)' // closed tag - + '|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))') - .replace('comment', _comment) - .replace(/tag/g, '(?!(?:' - + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub' - + '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)' - + '\\b)\\w+(?!:|[^\\w\\s@]*@)\\b') - .getRegex(), - def: /^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/, - heading: /^(#{1,6})(.*)(?:\n+|$)/, - fences: noopTest, // fences not supported - lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/, - paragraph: edit(_paragraph) - .replace('hr', hr) - .replace('heading', ' *#{1,6} *[^\n]') - .replace('lheading', lheading) - .replace('|table', '') - .replace('blockquote', ' {0,3}>') - .replace('|fences', '') - .replace('|list', '') - .replace('|html', '') - .replace('|tag', '') - .getRegex(), -}; -/** - * Inline-Level Grammar - */ -const escape$1 = /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/; -const inlineCode = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/; -const br = /^( {2,}|\\)\n(?!\s*$)/; -const inlineText = /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\ -const blockSkip = /\[[^[\]]*?\]\((?:\\.|[^\\\(\)]|\((?:\\.|[^\\\(\)])*\))*\)|`[^`]*?`|<[^<>]*?>/g; -const emStrongLDelimCore = /^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/; -const emStrongLDelim = edit(emStrongLDelimCore, 'u') - .replace(/punct/g, _punctuation) - .getRegex(); -const emStrongLDelimGfm = edit(emStrongLDelimCore, 'u') - .replace(/punct/g, _punctuationGfmStrongEm) - .getRegex(); -const emStrongRDelimAstCore = '^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)' // Skip orphan inside strong - + '|[^*]+(?=[^*])' // Consume to delim - + '|(?!\\*)punct(\\*+)(?=[\\s]|$)' // (1) #*** can only be a Right Delimiter - + '|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)' // (2) a***#, a*** can only be a Right Delimiter - + '|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)' // (3) #***a, ***a can only be Left Delimiter - + '|[\\s](\\*+)(?!\\*)(?=punct)' // (4) ***# can only be Left Delimiter - + '|(?!\\*)punct(\\*+)(?!\\*)(?=punct)' // (5) #***# can be either Left or Right Delimiter - + '|notPunctSpace(\\*+)(?=notPunctSpace)'; // (6) a***a can be either Left or Right Delimiter -const emStrongRDelimAst = edit(emStrongRDelimAstCore, 'gu') - .replace(/notPunctSpace/g, _notPunctuationOrSpace) - .replace(/punctSpace/g, _punctuationOrSpace) - .replace(/punct/g, _punctuation) - .getRegex(); -const emStrongRDelimAstGfm = edit(emStrongRDelimAstCore, 'gu') - .replace(/notPunctSpace/g, _notPunctuationOrSpaceGfmStrongEm) - .replace(/punctSpace/g, _punctuationOrSpaceGfmStrongEm) - .replace(/punct/g, _punctuationGfmStrongEm) - .getRegex(); -// (6) Not allowed for _ -const emStrongRDelimUnd = edit('^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)' // Skip orphan inside strong - + '|[^_]+(?=[^_])' // Consume to delim - + '|(?!_)punct(_+)(?=[\\s]|$)' // (1) #___ can only be a Right Delimiter - + '|notPunctSpace(_+)(?!_)(?=punctSpace|$)' // (2) a___#, a___ can only be a Right Delimiter - + '|(?!_)punctSpace(_+)(?=notPunctSpace)' // (3) #___a, ___a can only be Left Delimiter - + '|[\\s](_+)(?!_)(?=punct)' // (4) ___# can only be Left Delimiter - + '|(?!_)punct(_+)(?!_)(?=punct)', 'gu') // (5) #___# can be either Left or Right Delimiter - .replace(/notPunctSpace/g, _notPunctuationOrSpace) - .replace(/punctSpace/g, _punctuationOrSpace) - .replace(/punct/g, _punctuation) - .getRegex(); -const anyPunctuation = edit(/\\(punct)/, 'gu') - .replace(/punct/g, _punctuation) - .getRegex(); -const autolink = edit(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/) - .replace('scheme', /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/) - .replace('email', /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/) - .getRegex(); -const _inlineComment = edit(_comment).replace('(?:-->|$)', '-->').getRegex(); -const tag = edit('^comment' - + '|^' // self-closing tag - + '|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>' // open tag - + '|^<\\?[\\s\\S]*?\\?>' // processing instruction, e.g. - + '|^' // declaration, e.g. - + '|^') // CDATA section - .replace('comment', _inlineComment) - .replace('attribute', /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/) - .getRegex(); -const _inlineLabel = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/; -const link = edit(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/) - .replace('label', _inlineLabel) - .replace('href', /<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/) - .replace('title', /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/) - .getRegex(); -const reflink = edit(/^!?\[(label)\]\[(ref)\]/) - .replace('label', _inlineLabel) - .replace('ref', _blockLabel) - .getRegex(); -const nolink = edit(/^!?\[(ref)\](?:\[\])?/) - .replace('ref', _blockLabel) - .getRegex(); -const reflinkSearch = edit('reflink|nolink(?!\\()', 'g') - .replace('reflink', reflink) - .replace('nolink', nolink) - .getRegex(); -/** - * Normal Inline Grammar - */ -const inlineNormal = { - _backpedal: noopTest, // only used for GFM url - anyPunctuation, - autolink, - blockSkip, - br, - code: inlineCode, - del: noopTest, - emStrongLDelim, - emStrongRDelimAst, - emStrongRDelimUnd, - escape: escape$1, - link, - nolink, - punctuation, - reflink, - reflinkSearch, - tag, - text: inlineText, - url: noopTest, -}; -/** - * Pedantic Inline Grammar - */ -const inlinePedantic = { - ...inlineNormal, - link: edit(/^!?\[(label)\]\((.*?)\)/) - .replace('label', _inlineLabel) - .getRegex(), - reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/) - .replace('label', _inlineLabel) - .getRegex(), -}; -/** - * GFM Inline Grammar - */ -const inlineGfm = { - ...inlineNormal, - emStrongRDelimAst: emStrongRDelimAstGfm, - emStrongLDelim: emStrongLDelimGfm, - url: edit(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/, 'i') - .replace('email', /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/) - .getRegex(), - _backpedal: /(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/, - del: /^(~~?)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/, - text: /^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\': '>', - '"': '"', - "'": ''', -}; -const getEscapeReplacement = (ch) => escapeReplacements[ch]; -function escape(html, encode) { - if (encode) { - if (other.escapeTest.test(html)) { - return html.replace(other.escapeReplace, getEscapeReplacement); - } - } - else { - if (other.escapeTestNoEncode.test(html)) { - return html.replace(other.escapeReplaceNoEncode, getEscapeReplacement); - } - } - return html; -} -function cleanUrl(href) { - try { - href = encodeURI(href).replace(other.percentDecode, '%'); - } - catch { - return null; - } - return href; -} -function splitCells(tableRow, count) { - // ensure that every cell-delimiting pipe has a space - // before it to distinguish it from an escaped pipe - const row = tableRow.replace(other.findPipe, (match, offset, str) => { - let escaped = false; - let curr = offset; - while (--curr >= 0 && str[curr] === '\\') - escaped = !escaped; - if (escaped) { - // odd number of slashes means | is escaped - // so we leave it alone - return '|'; - } - else { - // add space before unescaped | - return ' |'; - } - }), cells = row.split(other.splitPipe); - let i = 0; - // First/last cell in a row cannot be empty if it has no leading/trailing pipe - if (!cells[0].trim()) { - cells.shift(); - } - if (cells.length > 0 && !cells.at(-1)?.trim()) { - cells.pop(); - } - if (count) { - if (cells.length > count) { - cells.splice(count); - } - else { - while (cells.length < count) - cells.push(''); - } - } - for (; i < cells.length; i++) { - // leading or trailing whitespace is ignored per the gfm spec - cells[i] = cells[i].trim().replace(other.slashPipe, '|'); - } - return cells; -} -/** - * Remove trailing 'c's. Equivalent to str.replace(/c*$/, ''). - * /c*$/ is vulnerable to REDOS. - * - * @param str - * @param c - * @param invert Remove suffix of non-c chars instead. Default falsey. - */ -function rtrim(str, c, invert) { - const l = str.length; - if (l === 0) { - return ''; - } - // Length of suffix matching the invert condition. - let suffLen = 0; - // Step left until we fail to match the invert condition. - while (suffLen < l) { - const currChar = str.charAt(l - suffLen - 1); - if (currChar === c && true) { - suffLen++; - } - else { - break; - } - } - return str.slice(0, l - suffLen); -} -function findClosingBracket(str, b) { - if (str.indexOf(b[1]) === -1) { - return -1; - } - let level = 0; - for (let i = 0; i < str.length; i++) { - if (str[i] === '\\') { - i++; - } - else if (str[i] === b[0]) { - level++; - } - else if (str[i] === b[1]) { - level--; - if (level < 0) { - return i; - } - } - } - return -1; -} - -function outputLink(cap, link, raw, lexer, rules) { - const href = link.href; - const title = link.title || null; - const text = cap[1].replace(rules.other.outputLinkReplace, '$1'); - if (cap[0].charAt(0) !== '!') { - lexer.state.inLink = true; - const token = { - type: 'link', - raw, - href, - title, - text, - tokens: lexer.inlineTokens(text), - }; - lexer.state.inLink = false; - return token; - } - return { - type: 'image', - raw, - href, - title, - text, - }; -} -function indentCodeCompensation(raw, text, rules) { - const matchIndentToCode = raw.match(rules.other.indentCodeCompensation); - if (matchIndentToCode === null) { - return text; - } - const indentToCode = matchIndentToCode[1]; - return text - .split('\n') - .map(node => { - const matchIndentInNode = node.match(rules.other.beginningSpace); - if (matchIndentInNode === null) { - return node; - } - const [indentInNode] = matchIndentInNode; - if (indentInNode.length >= indentToCode.length) { - return node.slice(indentToCode.length); - } - return node; - }) - .join('\n'); -} -/** - * Tokenizer - */ -class _Tokenizer { - options; - rules; // set by the lexer - lexer; // set by the lexer - constructor(options) { - this.options = options || _defaults; - } - space(src) { - const cap = this.rules.block.newline.exec(src); - if (cap && cap[0].length > 0) { - return { - type: 'space', - raw: cap[0], - }; - } - } - code(src) { - const cap = this.rules.block.code.exec(src); - if (cap) { - const text = cap[0].replace(this.rules.other.codeRemoveIndent, ''); - return { - type: 'code', - raw: cap[0], - codeBlockStyle: 'indented', - text: !this.options.pedantic - ? rtrim(text, '\n') - : text, - }; - } - } - fences(src) { - const cap = this.rules.block.fences.exec(src); - if (cap) { - const raw = cap[0]; - const text = indentCodeCompensation(raw, cap[3] || '', this.rules); - return { - type: 'code', - raw, - lang: cap[2] ? cap[2].trim().replace(this.rules.inline.anyPunctuation, '$1') : cap[2], - text, - }; - } - } - heading(src) { - const cap = this.rules.block.heading.exec(src); - if (cap) { - let text = cap[2].trim(); - // remove trailing #s - if (this.rules.other.endingHash.test(text)) { - const trimmed = rtrim(text, '#'); - if (this.options.pedantic) { - text = trimmed.trim(); - } - else if (!trimmed || this.rules.other.endingSpaceChar.test(trimmed)) { - // CommonMark requires space before trailing #s - text = trimmed.trim(); - } - } - return { - type: 'heading', - raw: cap[0], - depth: cap[1].length, - text, - tokens: this.lexer.inline(text), - }; - } - } - hr(src) { - const cap = this.rules.block.hr.exec(src); - if (cap) { - return { - type: 'hr', - raw: rtrim(cap[0], '\n'), - }; - } - } - blockquote(src) { - const cap = this.rules.block.blockquote.exec(src); - if (cap) { - let lines = rtrim(cap[0], '\n').split('\n'); - let raw = ''; - let text = ''; - const tokens = []; - while (lines.length > 0) { - let inBlockquote = false; - const currentLines = []; - let i; - for (i = 0; i < lines.length; i++) { - // get lines up to a continuation - if (this.rules.other.blockquoteStart.test(lines[i])) { - currentLines.push(lines[i]); - inBlockquote = true; - } - else if (!inBlockquote) { - currentLines.push(lines[i]); - } - else { - break; - } - } - lines = lines.slice(i); - const currentRaw = currentLines.join('\n'); - const currentText = currentRaw - // precede setext continuation with 4 spaces so it isn't a setext - .replace(this.rules.other.blockquoteSetextReplace, '\n $1') - .replace(this.rules.other.blockquoteSetextReplace2, ''); - raw = raw ? `${raw}\n${currentRaw}` : currentRaw; - text = text ? `${text}\n${currentText}` : currentText; - // parse blockquote lines as top level tokens - // merge paragraphs if this is a continuation - const top = this.lexer.state.top; - this.lexer.state.top = true; - this.lexer.blockTokens(currentText, tokens, true); - this.lexer.state.top = top; - // if there is no continuation then we are done - if (lines.length === 0) { - break; - } - const lastToken = tokens.at(-1); - if (lastToken?.type === 'code') { - // blockquote continuation cannot be preceded by a code block - break; - } - else if (lastToken?.type === 'blockquote') { - // include continuation in nested blockquote - const oldToken = lastToken; - const newText = oldToken.raw + '\n' + lines.join('\n'); - const newToken = this.blockquote(newText); - tokens[tokens.length - 1] = newToken; - raw = raw.substring(0, raw.length - oldToken.raw.length) + newToken.raw; - text = text.substring(0, text.length - oldToken.text.length) + newToken.text; - break; - } - else if (lastToken?.type === 'list') { - // include continuation in nested list - const oldToken = lastToken; - const newText = oldToken.raw + '\n' + lines.join('\n'); - const newToken = this.list(newText); - tokens[tokens.length - 1] = newToken; - raw = raw.substring(0, raw.length - lastToken.raw.length) + newToken.raw; - text = text.substring(0, text.length - oldToken.raw.length) + newToken.raw; - lines = newText.substring(tokens.at(-1).raw.length).split('\n'); - continue; - } - } - return { - type: 'blockquote', - raw, - tokens, - text, - }; - } - } - list(src) { - let cap = this.rules.block.list.exec(src); - if (cap) { - let bull = cap[1].trim(); - const isordered = bull.length > 1; - const list = { - type: 'list', - raw: '', - ordered: isordered, - start: isordered ? +bull.slice(0, -1) : '', - loose: false, - items: [], - }; - bull = isordered ? `\\d{1,9}\\${bull.slice(-1)}` : `\\${bull}`; - if (this.options.pedantic) { - bull = isordered ? bull : '[*+-]'; - } - // Get next list item - const itemRegex = this.rules.other.listItemRegex(bull); - let endsWithBlankLine = false; - // Check if current bullet point can start a new List Item - while (src) { - let endEarly = false; - let raw = ''; - let itemContents = ''; - if (!(cap = itemRegex.exec(src))) { - break; - } - if (this.rules.block.hr.test(src)) { // End list if bullet was actually HR (possibly move into itemRegex?) - break; - } - raw = cap[0]; - src = src.substring(raw.length); - let line = cap[2].split('\n', 1)[0].replace(this.rules.other.listReplaceTabs, (t) => ' '.repeat(3 * t.length)); - let nextLine = src.split('\n', 1)[0]; - let blankLine = !line.trim(); - let indent = 0; - if (this.options.pedantic) { - indent = 2; - itemContents = line.trimStart(); - } - else if (blankLine) { - indent = cap[1].length + 1; - } - else { - indent = cap[2].search(this.rules.other.nonSpaceChar); // Find first non-space char - indent = indent > 4 ? 1 : indent; // Treat indented code blocks (> 4 spaces) as having only 1 indent - itemContents = line.slice(indent); - indent += cap[1].length; - } - if (blankLine && this.rules.other.blankLine.test(nextLine)) { // Items begin with at most one blank line - raw += nextLine + '\n'; - src = src.substring(nextLine.length + 1); - endEarly = true; - } - if (!endEarly) { - const nextBulletRegex = this.rules.other.nextBulletRegex(indent); - const hrRegex = this.rules.other.hrRegex(indent); - const fencesBeginRegex = this.rules.other.fencesBeginRegex(indent); - const headingBeginRegex = this.rules.other.headingBeginRegex(indent); - const htmlBeginRegex = this.rules.other.htmlBeginRegex(indent); - // Check if following lines should be included in List Item - while (src) { - const rawLine = src.split('\n', 1)[0]; - let nextLineWithoutTabs; - nextLine = rawLine; - // Re-align to follow commonmark nesting rules - if (this.options.pedantic) { - nextLine = nextLine.replace(this.rules.other.listReplaceNesting, ' '); - nextLineWithoutTabs = nextLine; - } - else { - nextLineWithoutTabs = nextLine.replace(this.rules.other.tabCharGlobal, ' '); - } - // End list item if found code fences - if (fencesBeginRegex.test(nextLine)) { - break; - } - // End list item if found start of new heading - if (headingBeginRegex.test(nextLine)) { - break; - } - // End list item if found start of html block - if (htmlBeginRegex.test(nextLine)) { - break; - } - // End list item if found start of new bullet - if (nextBulletRegex.test(nextLine)) { - break; - } - // Horizontal rule found - if (hrRegex.test(nextLine)) { - break; - } - if (nextLineWithoutTabs.search(this.rules.other.nonSpaceChar) >= indent || !nextLine.trim()) { // Dedent if possible - itemContents += '\n' + nextLineWithoutTabs.slice(indent); - } - else { - // not enough indentation - if (blankLine) { - break; - } - // paragraph continuation unless last line was a different block level element - if (line.replace(this.rules.other.tabCharGlobal, ' ').search(this.rules.other.nonSpaceChar) >= 4) { // indented code block - break; - } - if (fencesBeginRegex.test(line)) { - break; - } - if (headingBeginRegex.test(line)) { - break; - } - if (hrRegex.test(line)) { - break; - } - itemContents += '\n' + nextLine; - } - if (!blankLine && !nextLine.trim()) { // Check if current line is blank - blankLine = true; - } - raw += rawLine + '\n'; - src = src.substring(rawLine.length + 1); - line = nextLineWithoutTabs.slice(indent); - } - } - if (!list.loose) { - // If the previous item ended with a blank line, the list is loose - if (endsWithBlankLine) { - list.loose = true; - } - else if (this.rules.other.doubleBlankLine.test(raw)) { - endsWithBlankLine = true; - } - } - let istask = null; - let ischecked; - // Check for task list items - if (this.options.gfm) { - istask = this.rules.other.listIsTask.exec(itemContents); - if (istask) { - ischecked = istask[0] !== '[ ] '; - itemContents = itemContents.replace(this.rules.other.listReplaceTask, ''); - } - } - list.items.push({ - type: 'list_item', - raw, - task: !!istask, - checked: ischecked, - loose: false, - text: itemContents, - tokens: [], - }); - list.raw += raw; - } - // Do not consume newlines at end of final item. Alternatively, make itemRegex *start* with any newlines to simplify/speed up endsWithBlankLine logic - const lastItem = list.items.at(-1); - if (lastItem) { - lastItem.raw = lastItem.raw.trimEnd(); - lastItem.text = lastItem.text.trimEnd(); - } - else { - // not a list since there were no items - return; - } - list.raw = list.raw.trimEnd(); - // Item child tokens handled here at end because we needed to have the final item to trim it first - for (let i = 0; i < list.items.length; i++) { - this.lexer.state.top = false; - list.items[i].tokens = this.lexer.blockTokens(list.items[i].text, []); - if (!list.loose) { - // Check if list should be loose - const spacers = list.items[i].tokens.filter(t => t.type === 'space'); - const hasMultipleLineBreaks = spacers.length > 0 && spacers.some(t => this.rules.other.anyLine.test(t.raw)); - list.loose = hasMultipleLineBreaks; - } - } - // Set all items to loose if list is loose - if (list.loose) { - for (let i = 0; i < list.items.length; i++) { - list.items[i].loose = true; - } - } - return list; - } - } - html(src) { - const cap = this.rules.block.html.exec(src); - if (cap) { - const token = { - type: 'html', - block: true, - raw: cap[0], - pre: cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style', - text: cap[0], - }; - return token; - } - } - def(src) { - const cap = this.rules.block.def.exec(src); - if (cap) { - const tag = cap[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal, ' '); - const href = cap[2] ? cap[2].replace(this.rules.other.hrefBrackets, '$1').replace(this.rules.inline.anyPunctuation, '$1') : ''; - const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline.anyPunctuation, '$1') : cap[3]; - return { - type: 'def', - tag, - raw: cap[0], - href, - title, - }; - } - } - table(src) { - const cap = this.rules.block.table.exec(src); - if (!cap) { - return; - } - if (!this.rules.other.tableDelimiter.test(cap[2])) { - // delimiter row must have a pipe (|) or colon (:) otherwise it is a setext heading - return; - } - const headers = splitCells(cap[1]); - const aligns = cap[2].replace(this.rules.other.tableAlignChars, '').split('|'); - const rows = cap[3]?.trim() ? cap[3].replace(this.rules.other.tableRowBlankLine, '').split('\n') : []; - const item = { - type: 'table', - raw: cap[0], - header: [], - align: [], - rows: [], - }; - if (headers.length !== aligns.length) { - // header and align columns must be equal, rows can be different. - return; - } - for (const align of aligns) { - if (this.rules.other.tableAlignRight.test(align)) { - item.align.push('right'); - } - else if (this.rules.other.tableAlignCenter.test(align)) { - item.align.push('center'); - } - else if (this.rules.other.tableAlignLeft.test(align)) { - item.align.push('left'); - } - else { - item.align.push(null); - } - } - for (let i = 0; i < headers.length; i++) { - item.header.push({ - text: headers[i], - tokens: this.lexer.inline(headers[i]), - header: true, - align: item.align[i], - }); - } - for (const row of rows) { - item.rows.push(splitCells(row, item.header.length).map((cell, i) => { - return { - text: cell, - tokens: this.lexer.inline(cell), - header: false, - align: item.align[i], - }; - })); - } - return item; - } - lheading(src) { - const cap = this.rules.block.lheading.exec(src); - if (cap) { - return { - type: 'heading', - raw: cap[0], - depth: cap[2].charAt(0) === '=' ? 1 : 2, - text: cap[1], - tokens: this.lexer.inline(cap[1]), - }; - } - } - paragraph(src) { - const cap = this.rules.block.paragraph.exec(src); - if (cap) { - const text = cap[1].charAt(cap[1].length - 1) === '\n' - ? cap[1].slice(0, -1) - : cap[1]; - return { - type: 'paragraph', - raw: cap[0], - text, - tokens: this.lexer.inline(text), - }; - } - } - text(src) { - const cap = this.rules.block.text.exec(src); - if (cap) { - return { - type: 'text', - raw: cap[0], - text: cap[0], - tokens: this.lexer.inline(cap[0]), - }; - } - } - escape(src) { - const cap = this.rules.inline.escape.exec(src); - if (cap) { - return { - type: 'escape', - raw: cap[0], - text: cap[1], - }; - } - } - tag(src) { - const cap = this.rules.inline.tag.exec(src); - if (cap) { - if (!this.lexer.state.inLink && this.rules.other.startATag.test(cap[0])) { - this.lexer.state.inLink = true; - } - else if (this.lexer.state.inLink && this.rules.other.endATag.test(cap[0])) { - this.lexer.state.inLink = false; - } - if (!this.lexer.state.inRawBlock && this.rules.other.startPreScriptTag.test(cap[0])) { - this.lexer.state.inRawBlock = true; - } - else if (this.lexer.state.inRawBlock && this.rules.other.endPreScriptTag.test(cap[0])) { - this.lexer.state.inRawBlock = false; - } - return { - type: 'html', - raw: cap[0], - inLink: this.lexer.state.inLink, - inRawBlock: this.lexer.state.inRawBlock, - block: false, - text: cap[0], - }; - } - } - link(src) { - const cap = this.rules.inline.link.exec(src); - if (cap) { - const trimmedUrl = cap[2].trim(); - if (!this.options.pedantic && this.rules.other.startAngleBracket.test(trimmedUrl)) { - // commonmark requires matching angle brackets - if (!(this.rules.other.endAngleBracket.test(trimmedUrl))) { - return; - } - // ending angle bracket cannot be escaped - const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), '\\'); - if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) { - return; - } - } - else { - // find closing parenthesis - const lastParenIndex = findClosingBracket(cap[2], '()'); - if (lastParenIndex > -1) { - const start = cap[0].indexOf('!') === 0 ? 5 : 4; - const linkLen = start + cap[1].length + lastParenIndex; - cap[2] = cap[2].substring(0, lastParenIndex); - cap[0] = cap[0].substring(0, linkLen).trim(); - cap[3] = ''; - } - } - let href = cap[2]; - let title = ''; - if (this.options.pedantic) { - // split pedantic href and title - const link = this.rules.other.pedanticHrefTitle.exec(href); - if (link) { - href = link[1]; - title = link[3]; - } - } - else { - title = cap[3] ? cap[3].slice(1, -1) : ''; - } - href = href.trim(); - if (this.rules.other.startAngleBracket.test(href)) { - if (this.options.pedantic && !(this.rules.other.endAngleBracket.test(trimmedUrl))) { - // pedantic allows starting angle bracket without ending angle bracket - href = href.slice(1); - } - else { - href = href.slice(1, -1); - } - } - return outputLink(cap, { - href: href ? href.replace(this.rules.inline.anyPunctuation, '$1') : href, - title: title ? title.replace(this.rules.inline.anyPunctuation, '$1') : title, - }, cap[0], this.lexer, this.rules); - } - } - reflink(src, links) { - let cap; - if ((cap = this.rules.inline.reflink.exec(src)) - || (cap = this.rules.inline.nolink.exec(src))) { - const linkString = (cap[2] || cap[1]).replace(this.rules.other.multipleSpaceGlobal, ' '); - const link = links[linkString.toLowerCase()]; - if (!link) { - const text = cap[0].charAt(0); - return { - type: 'text', - raw: text, - text, - }; - } - return outputLink(cap, link, cap[0], this.lexer, this.rules); - } - } - emStrong(src, maskedSrc, prevChar = '') { - let match = this.rules.inline.emStrongLDelim.exec(src); - if (!match) - return; - // _ can't be between two alphanumerics. \p{L}\p{N} includes non-english alphabet/numbers as well - if (match[3] && prevChar.match(this.rules.other.unicodeAlphaNumeric)) - return; - const nextChar = match[1] || match[2] || ''; - if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) { - // unicode Regex counts emoji as 1 char; spread into array for proper count (used multiple times below) - const lLength = [...match[0]].length - 1; - let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0; - const endReg = match[0][0] === '*' ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd; - endReg.lastIndex = 0; - // Clip maskedSrc to same section of string as src (move to lexer?) - maskedSrc = maskedSrc.slice(-1 * src.length + lLength); - while ((match = endReg.exec(maskedSrc)) != null) { - rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6]; - if (!rDelim) - continue; // skip single * in __abc*abc__ - rLength = [...rDelim].length; - if (match[3] || match[4]) { // found another Left Delim - delimTotal += rLength; - continue; - } - else if (match[5] || match[6]) { // either Left or Right Delim - if (lLength % 3 && !((lLength + rLength) % 3)) { - midDelimTotal += rLength; - continue; // CommonMark Emphasis Rules 9-10 - } - } - delimTotal -= rLength; - if (delimTotal > 0) - continue; // Haven't found enough closing delimiters - // Remove extra characters. *a*** -> *a* - rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal); - // char length can be >1 for unicode characters; - const lastCharLength = [...match[0]][0].length; - const raw = src.slice(0, lLength + match.index + lastCharLength + rLength); - // Create `em` if smallest delimiter has odd char count. *a*** - if (Math.min(lLength, rLength) % 2) { - const text = raw.slice(1, -1); - return { - type: 'em', - raw, - text, - tokens: this.lexer.inlineTokens(text), - }; - } - // Create 'strong' if smallest delimiter has even char count. **a*** - const text = raw.slice(2, -2); - return { - type: 'strong', - raw, - text, - tokens: this.lexer.inlineTokens(text), - }; - } - } - } - codespan(src) { - const cap = this.rules.inline.code.exec(src); - if (cap) { - let text = cap[2].replace(this.rules.other.newLineCharGlobal, ' '); - const hasNonSpaceChars = this.rules.other.nonSpaceChar.test(text); - const hasSpaceCharsOnBothEnds = this.rules.other.startingSpaceChar.test(text) && this.rules.other.endingSpaceChar.test(text); - if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) { - text = text.substring(1, text.length - 1); - } - return { - type: 'codespan', - raw: cap[0], - text, - }; - } - } - br(src) { - const cap = this.rules.inline.br.exec(src); - if (cap) { - return { - type: 'br', - raw: cap[0], - }; - } - } - del(src) { - const cap = this.rules.inline.del.exec(src); - if (cap) { - return { - type: 'del', - raw: cap[0], - text: cap[2], - tokens: this.lexer.inlineTokens(cap[2]), - }; - } - } - autolink(src) { - const cap = this.rules.inline.autolink.exec(src); - if (cap) { - let text, href; - if (cap[2] === '@') { - text = cap[1]; - href = 'mailto:' + text; - } - else { - text = cap[1]; - href = text; - } - return { - type: 'link', - raw: cap[0], - text, - href, - tokens: [ - { - type: 'text', - raw: text, - text, - }, - ], - }; - } - } - url(src) { - let cap; - if (cap = this.rules.inline.url.exec(src)) { - let text, href; - if (cap[2] === '@') { - text = cap[0]; - href = 'mailto:' + text; - } - else { - // do extended autolink path validation - let prevCapZero; - do { - prevCapZero = cap[0]; - cap[0] = this.rules.inline._backpedal.exec(cap[0])?.[0] ?? ''; - } while (prevCapZero !== cap[0]); - text = cap[0]; - if (cap[1] === 'www.') { - href = 'http://' + cap[0]; - } - else { - href = cap[0]; - } - } - return { - type: 'link', - raw: cap[0], - text, - href, - tokens: [ - { - type: 'text', - raw: text, - text, - }, - ], - }; - } - } - inlineText(src) { - const cap = this.rules.inline.text.exec(src); - if (cap) { - const escaped = this.lexer.state.inRawBlock; - return { - type: 'text', - raw: cap[0], - text: cap[0], - escaped, - }; - } - } -} - -/** - * Block Lexer - */ -class _Lexer { - tokens; - options; - state; - tokenizer; - inlineQueue; - constructor(options) { - // TokenList cannot be created in one go - this.tokens = []; - this.tokens.links = Object.create(null); - this.options = options || _defaults; - this.options.tokenizer = this.options.tokenizer || new _Tokenizer(); - this.tokenizer = this.options.tokenizer; - this.tokenizer.options = this.options; - this.tokenizer.lexer = this; - this.inlineQueue = []; - this.state = { - inLink: false, - inRawBlock: false, - top: true, - }; - const rules = { - other, - block: block.normal, - inline: inline.normal, - }; - if (this.options.pedantic) { - rules.block = block.pedantic; - rules.inline = inline.pedantic; - } - else if (this.options.gfm) { - rules.block = block.gfm; - if (this.options.breaks) { - rules.inline = inline.breaks; - } - else { - rules.inline = inline.gfm; - } - } - this.tokenizer.rules = rules; - } - /** - * Expose Rules - */ - static get rules() { - return { - block, - inline, - }; - } - /** - * Static Lex Method - */ - static lex(src, options) { - const lexer = new _Lexer(options); - return lexer.lex(src); - } - /** - * Static Lex Inline Method - */ - static lexInline(src, options) { - const lexer = new _Lexer(options); - return lexer.inlineTokens(src); - } - /** - * Preprocessing - */ - lex(src) { - src = src.replace(other.carriageReturn, '\n'); - this.blockTokens(src, this.tokens); - for (let i = 0; i < this.inlineQueue.length; i++) { - const next = this.inlineQueue[i]; - this.inlineTokens(next.src, next.tokens); - } - this.inlineQueue = []; - return this.tokens; - } - blockTokens(src, tokens = [], lastParagraphClipped = false) { - if (this.options.pedantic) { - src = src.replace(other.tabCharGlobal, ' ').replace(other.spaceLine, ''); - } - while (src) { - let token; - if (this.options.extensions?.block?.some((extTokenizer) => { - if (token = extTokenizer.call({ lexer: this }, src, tokens)) { - src = src.substring(token.raw.length); - tokens.push(token); - return true; - } - return false; - })) { - continue; - } - // newline - if (token = this.tokenizer.space(src)) { - src = src.substring(token.raw.length); - const lastToken = tokens.at(-1); - if (token.raw.length === 1 && lastToken !== undefined) { - // if there's a single \n as a spacer, it's terminating the last line, - // so move it there so that we don't get unnecessary paragraph tags - lastToken.raw += '\n'; - } - else { - tokens.push(token); - } - continue; - } - // code - if (token = this.tokenizer.code(src)) { - src = src.substring(token.raw.length); - const lastToken = tokens.at(-1); - // An indented code block cannot interrupt a paragraph. - if (lastToken?.type === 'paragraph' || lastToken?.type === 'text') { - lastToken.raw += '\n' + token.raw; - lastToken.text += '\n' + token.text; - this.inlineQueue.at(-1).src = lastToken.text; - } - else { - tokens.push(token); - } - continue; - } - // fences - if (token = this.tokenizer.fences(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // heading - if (token = this.tokenizer.heading(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // hr - if (token = this.tokenizer.hr(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // blockquote - if (token = this.tokenizer.blockquote(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // list - if (token = this.tokenizer.list(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // html - if (token = this.tokenizer.html(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // def - if (token = this.tokenizer.def(src)) { - src = src.substring(token.raw.length); - const lastToken = tokens.at(-1); - if (lastToken?.type === 'paragraph' || lastToken?.type === 'text') { - lastToken.raw += '\n' + token.raw; - lastToken.text += '\n' + token.raw; - this.inlineQueue.at(-1).src = lastToken.text; - } - else if (!this.tokens.links[token.tag]) { - this.tokens.links[token.tag] = { - href: token.href, - title: token.title, - }; - } - continue; - } - // table (gfm) - if (token = this.tokenizer.table(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // lheading - if (token = this.tokenizer.lheading(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // top-level paragraph - // prevent paragraph consuming extensions by clipping 'src' to extension start - let cutSrc = src; - if (this.options.extensions?.startBlock) { - let startIndex = Infinity; - const tempSrc = src.slice(1); - let tempStart; - this.options.extensions.startBlock.forEach((getStartIndex) => { - tempStart = getStartIndex.call({ lexer: this }, tempSrc); - if (typeof tempStart === 'number' && tempStart >= 0) { - startIndex = Math.min(startIndex, tempStart); - } - }); - if (startIndex < Infinity && startIndex >= 0) { - cutSrc = src.substring(0, startIndex + 1); - } - } - if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) { - const lastToken = tokens.at(-1); - if (lastParagraphClipped && lastToken?.type === 'paragraph') { - lastToken.raw += '\n' + token.raw; - lastToken.text += '\n' + token.text; - this.inlineQueue.pop(); - this.inlineQueue.at(-1).src = lastToken.text; - } - else { - tokens.push(token); - } - lastParagraphClipped = cutSrc.length !== src.length; - src = src.substring(token.raw.length); - continue; - } - // text - if (token = this.tokenizer.text(src)) { - src = src.substring(token.raw.length); - const lastToken = tokens.at(-1); - if (lastToken?.type === 'text') { - lastToken.raw += '\n' + token.raw; - lastToken.text += '\n' + token.text; - this.inlineQueue.pop(); - this.inlineQueue.at(-1).src = lastToken.text; - } - else { - tokens.push(token); - } - continue; - } - if (src) { - const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0); - if (this.options.silent) { - console.error(errMsg); - break; - } - else { - throw new Error(errMsg); - } - } - } - this.state.top = true; - return tokens; - } - inline(src, tokens = []) { - this.inlineQueue.push({ src, tokens }); - return tokens; - } - /** - * Lexing/Compiling - */ - inlineTokens(src, tokens = []) { - // String with links masked to avoid interference with em and strong - let maskedSrc = src; - let match = null; - // Mask out reflinks - if (this.tokens.links) { - const links = Object.keys(this.tokens.links); - if (links.length > 0) { - while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) { - if (links.includes(match[0].slice(match[0].lastIndexOf('[') + 1, -1))) { - maskedSrc = maskedSrc.slice(0, match.index) - + '[' + 'a'.repeat(match[0].length - 2) + ']' - + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex); - } - } - } - } - // Mask out other blocks - while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) { - maskedSrc = maskedSrc.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex); - } - // Mask out escaped characters - while ((match = this.tokenizer.rules.inline.anyPunctuation.exec(maskedSrc)) != null) { - maskedSrc = maskedSrc.slice(0, match.index) + '++' + maskedSrc.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex); - } - let keepPrevChar = false; - let prevChar = ''; - while (src) { - if (!keepPrevChar) { - prevChar = ''; - } - keepPrevChar = false; - let token; - // extensions - if (this.options.extensions?.inline?.some((extTokenizer) => { - if (token = extTokenizer.call({ lexer: this }, src, tokens)) { - src = src.substring(token.raw.length); - tokens.push(token); - return true; - } - return false; - })) { - continue; - } - // escape - if (token = this.tokenizer.escape(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // tag - if (token = this.tokenizer.tag(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // link - if (token = this.tokenizer.link(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // reflink, nolink - if (token = this.tokenizer.reflink(src, this.tokens.links)) { - src = src.substring(token.raw.length); - const lastToken = tokens.at(-1); - if (token.type === 'text' && lastToken?.type === 'text') { - lastToken.raw += token.raw; - lastToken.text += token.text; - } - else { - tokens.push(token); - } - continue; - } - // em & strong - if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // code - if (token = this.tokenizer.codespan(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // br - if (token = this.tokenizer.br(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // del (gfm) - if (token = this.tokenizer.del(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // autolink - if (token = this.tokenizer.autolink(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // url (gfm) - if (!this.state.inLink && (token = this.tokenizer.url(src))) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // text - // prevent inlineText consuming extensions by clipping 'src' to extension start - let cutSrc = src; - if (this.options.extensions?.startInline) { - let startIndex = Infinity; - const tempSrc = src.slice(1); - let tempStart; - this.options.extensions.startInline.forEach((getStartIndex) => { - tempStart = getStartIndex.call({ lexer: this }, tempSrc); - if (typeof tempStart === 'number' && tempStart >= 0) { - startIndex = Math.min(startIndex, tempStart); - } - }); - if (startIndex < Infinity && startIndex >= 0) { - cutSrc = src.substring(0, startIndex + 1); - } - } - if (token = this.tokenizer.inlineText(cutSrc)) { - src = src.substring(token.raw.length); - if (token.raw.slice(-1) !== '_') { // Track prevChar before string of ____ started - prevChar = token.raw.slice(-1); - } - keepPrevChar = true; - const lastToken = tokens.at(-1); - if (lastToken?.type === 'text') { - lastToken.raw += token.raw; - lastToken.text += token.text; - } - else { - tokens.push(token); - } - continue; - } - if (src) { - const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0); - if (this.options.silent) { - console.error(errMsg); - break; - } - else { - throw new Error(errMsg); - } - } - } - return tokens; - } -} - -/** - * Renderer - */ -class _Renderer { - options; - parser; // set by the parser - constructor(options) { - this.options = options || _defaults; - } - space(token) { - return ''; - } - code({ text, lang, escaped }) { - const langString = (lang || '').match(other.notSpaceStart)?.[0]; - const code = text.replace(other.endingNewline, '') + '\n'; - if (!langString) { - return '
'
-                + (escaped ? code : escape(code, true))
-                + '
\n'; - } - return '
'
-            + (escaped ? code : escape(code, true))
-            + '
\n'; - } - blockquote({ tokens }) { - const body = this.parser.parse(tokens); - return `
\n${body}
\n`; - } - html({ text }) { - return text; - } - heading({ tokens, depth }) { - return `${this.parser.parseInline(tokens)}\n`; - } - hr(token) { - return '
\n'; - } - list(token) { - const ordered = token.ordered; - const start = token.start; - let body = ''; - for (let j = 0; j < token.items.length; j++) { - const item = token.items[j]; - body += this.listitem(item); - } - const type = ordered ? 'ol' : 'ul'; - const startAttr = (ordered && start !== 1) ? (' start="' + start + '"') : ''; - return '<' + type + startAttr + '>\n' + body + '\n'; - } - listitem(item) { - let itemBody = ''; - if (item.task) { - const checkbox = this.checkbox({ checked: !!item.checked }); - if (item.loose) { - if (item.tokens[0]?.type === 'paragraph') { - item.tokens[0].text = checkbox + ' ' + item.tokens[0].text; - if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') { - item.tokens[0].tokens[0].text = checkbox + ' ' + escape(item.tokens[0].tokens[0].text); - item.tokens[0].tokens[0].escaped = true; - } - } - else { - item.tokens.unshift({ - type: 'text', - raw: checkbox + ' ', - text: checkbox + ' ', - escaped: true, - }); - } - } - else { - itemBody += checkbox + ' '; - } - } - itemBody += this.parser.parse(item.tokens, !!item.loose); - return `
  • ${itemBody}
  • \n`; - } - checkbox({ checked }) { - return ''; - } - paragraph({ tokens }) { - return `

    ${this.parser.parseInline(tokens)}

    \n`; - } - table(token) { - let header = ''; - // header - let cell = ''; - for (let j = 0; j < token.header.length; j++) { - cell += this.tablecell(token.header[j]); - } - header += this.tablerow({ text: cell }); - let body = ''; - for (let j = 0; j < token.rows.length; j++) { - const row = token.rows[j]; - cell = ''; - for (let k = 0; k < row.length; k++) { - cell += this.tablecell(row[k]); - } - body += this.tablerow({ text: cell }); - } - if (body) - body = `${body}`; - return '\n' - + '\n' - + header - + '\n' - + body - + '
    \n'; - } - tablerow({ text }) { - return `\n${text}\n`; - } - tablecell(token) { - const content = this.parser.parseInline(token.tokens); - const type = token.header ? 'th' : 'td'; - const tag = token.align - ? `<${type} align="${token.align}">` - : `<${type}>`; - return tag + content + `\n`; - } - /** - * span level renderer - */ - strong({ tokens }) { - return `${this.parser.parseInline(tokens)}`; - } - em({ tokens }) { - return `${this.parser.parseInline(tokens)}`; - } - codespan({ text }) { - return `${escape(text, true)}`; - } - br(token) { - return '
    '; - } - del({ tokens }) { - return `${this.parser.parseInline(tokens)}`; - } - link({ href, title, tokens }) { - const text = this.parser.parseInline(tokens); - const cleanHref = cleanUrl(href); - if (cleanHref === null) { - return text; - } - href = cleanHref; - let out = '
    '; - return out; - } - image({ href, title, text }) { - const cleanHref = cleanUrl(href); - if (cleanHref === null) { - return escape(text); - } - href = cleanHref; - let out = `${text} { - const tokens = genericToken[childTokens].flat(Infinity); - values = values.concat(this.walkTokens(tokens, callback)); - }); - } - else if (genericToken.tokens) { - values = values.concat(this.walkTokens(genericToken.tokens, callback)); - } - } - } - } - return values; - } - use(...args) { - const extensions = this.defaults.extensions || { renderers: {}, childTokens: {} }; - args.forEach((pack) => { - // copy options to new object - const opts = { ...pack }; - // set async to true if it was set to true before - opts.async = this.defaults.async || opts.async || false; - // ==-- Parse "addon" extensions --== // - if (pack.extensions) { - pack.extensions.forEach((ext) => { - if (!ext.name) { - throw new Error('extension name required'); - } - if ('renderer' in ext) { // Renderer extensions - const prevRenderer = extensions.renderers[ext.name]; - if (prevRenderer) { - // Replace extension with func to run new extension but fall back if false - extensions.renderers[ext.name] = function (...args) { - let ret = ext.renderer.apply(this, args); - if (ret === false) { - ret = prevRenderer.apply(this, args); - } - return ret; - }; - } - else { - extensions.renderers[ext.name] = ext.renderer; - } - } - if ('tokenizer' in ext) { // Tokenizer Extensions - if (!ext.level || (ext.level !== 'block' && ext.level !== 'inline')) { - throw new Error("extension level must be 'block' or 'inline'"); - } - const extLevel = extensions[ext.level]; - if (extLevel) { - extLevel.unshift(ext.tokenizer); - } - else { - extensions[ext.level] = [ext.tokenizer]; - } - if (ext.start) { // Function to check for start of token - if (ext.level === 'block') { - if (extensions.startBlock) { - extensions.startBlock.push(ext.start); - } - else { - extensions.startBlock = [ext.start]; - } - } - else if (ext.level === 'inline') { - if (extensions.startInline) { - extensions.startInline.push(ext.start); - } - else { - extensions.startInline = [ext.start]; - } - } - } - } - if ('childTokens' in ext && ext.childTokens) { // Child tokens to be visited by walkTokens - extensions.childTokens[ext.name] = ext.childTokens; - } - }); - opts.extensions = extensions; - } - // ==-- Parse "overwrite" extensions --== // - if (pack.renderer) { - const renderer = this.defaults.renderer || new _Renderer(this.defaults); - for (const prop in pack.renderer) { - if (!(prop in renderer)) { - throw new Error(`renderer '${prop}' does not exist`); - } - if (['options', 'parser'].includes(prop)) { - // ignore options property - continue; - } - const rendererProp = prop; - const rendererFunc = pack.renderer[rendererProp]; - const prevRenderer = renderer[rendererProp]; - // Replace renderer with func to run extension, but fall back if false - renderer[rendererProp] = (...args) => { - let ret = rendererFunc.apply(renderer, args); - if (ret === false) { - ret = prevRenderer.apply(renderer, args); - } - return ret || ''; - }; - } - opts.renderer = renderer; - } - if (pack.tokenizer) { - const tokenizer = this.defaults.tokenizer || new _Tokenizer(this.defaults); - for (const prop in pack.tokenizer) { - if (!(prop in tokenizer)) { - throw new Error(`tokenizer '${prop}' does not exist`); - } - if (['options', 'rules', 'lexer'].includes(prop)) { - // ignore options, rules, and lexer properties - continue; - } - const tokenizerProp = prop; - const tokenizerFunc = pack.tokenizer[tokenizerProp]; - const prevTokenizer = tokenizer[tokenizerProp]; - // Replace tokenizer with func to run extension, but fall back if false - // @ts-expect-error cannot type tokenizer function dynamically - tokenizer[tokenizerProp] = (...args) => { - let ret = tokenizerFunc.apply(tokenizer, args); - if (ret === false) { - ret = prevTokenizer.apply(tokenizer, args); - } - return ret; - }; - } - opts.tokenizer = tokenizer; - } - // ==-- Parse Hooks extensions --== // - if (pack.hooks) { - const hooks = this.defaults.hooks || new _Hooks(); - for (const prop in pack.hooks) { - if (!(prop in hooks)) { - throw new Error(`hook '${prop}' does not exist`); - } - if (['options', 'block'].includes(prop)) { - // ignore options and block properties - continue; - } - const hooksProp = prop; - const hooksFunc = pack.hooks[hooksProp]; - const prevHook = hooks[hooksProp]; - if (_Hooks.passThroughHooks.has(prop)) { - // @ts-expect-error cannot type hook function dynamically - hooks[hooksProp] = (arg) => { - if (this.defaults.async) { - return Promise.resolve(hooksFunc.call(hooks, arg)).then(ret => { - return prevHook.call(hooks, ret); - }); - } - const ret = hooksFunc.call(hooks, arg); - return prevHook.call(hooks, ret); - }; - } - else { - // @ts-expect-error cannot type hook function dynamically - hooks[hooksProp] = (...args) => { - let ret = hooksFunc.apply(hooks, args); - if (ret === false) { - ret = prevHook.apply(hooks, args); - } - return ret; - }; - } - } - opts.hooks = hooks; - } - // ==-- Parse WalkTokens extensions --== // - if (pack.walkTokens) { - const walkTokens = this.defaults.walkTokens; - const packWalktokens = pack.walkTokens; - opts.walkTokens = function (token) { - let values = []; - values.push(packWalktokens.call(this, token)); - if (walkTokens) { - values = values.concat(walkTokens.call(this, token)); - } - return values; - }; - } - this.defaults = { ...this.defaults, ...opts }; - }); - return this; - } - setOptions(opt) { - this.defaults = { ...this.defaults, ...opt }; - return this; - } - lexer(src, options) { - return _Lexer.lex(src, options ?? this.defaults); - } - parser(tokens, options) { - return _Parser.parse(tokens, options ?? this.defaults); - } - parseMarkdown(blockType) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const parse = (src, options) => { - const origOpt = { ...options }; - const opt = { ...this.defaults, ...origOpt }; - const throwError = this.onError(!!opt.silent, !!opt.async); - // throw error if an extension set async to true but parse was called with async: false - if (this.defaults.async === true && origOpt.async === false) { - return throwError(new Error('marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.')); - } - // throw error in case of non string input - if (typeof src === 'undefined' || src === null) { - return throwError(new Error('marked(): input parameter is undefined or null')); - } - if (typeof src !== 'string') { - return throwError(new Error('marked(): input parameter is of type ' - + Object.prototype.toString.call(src) + ', string expected')); - } - if (opt.hooks) { - opt.hooks.options = opt; - opt.hooks.block = blockType; - } - const lexer = opt.hooks ? opt.hooks.provideLexer() : (blockType ? _Lexer.lex : _Lexer.lexInline); - const parser = opt.hooks ? opt.hooks.provideParser() : (blockType ? _Parser.parse : _Parser.parseInline); - if (opt.async) { - return Promise.resolve(opt.hooks ? opt.hooks.preprocess(src) : src) - .then(src => lexer(src, opt)) - .then(tokens => opt.hooks ? opt.hooks.processAllTokens(tokens) : tokens) - .then(tokens => opt.walkTokens ? Promise.all(this.walkTokens(tokens, opt.walkTokens)).then(() => tokens) : tokens) - .then(tokens => parser(tokens, opt)) - .then(html => opt.hooks ? opt.hooks.postprocess(html) : html) - .catch(throwError); - } - try { - if (opt.hooks) { - src = opt.hooks.preprocess(src); - } - let tokens = lexer(src, opt); - if (opt.hooks) { - tokens = opt.hooks.processAllTokens(tokens); - } - if (opt.walkTokens) { - this.walkTokens(tokens, opt.walkTokens); - } - let html = parser(tokens, opt); - if (opt.hooks) { - html = opt.hooks.postprocess(html); - } - return html; - } - catch (e) { - return throwError(e); - } - }; - return parse; - } - onError(silent, async) { - return (e) => { - e.message += '\nPlease report this to https://github.com/markedjs/marked.'; - if (silent) { - const msg = '

    An error occurred:

    '
    -                    + escape(e.message + '', true)
    -                    + '
    '; - if (async) { - return Promise.resolve(msg); - } - return msg; - } - if (async) { - return Promise.reject(e); - } - throw e; - }; - } -} - -const markedInstance = new Marked(); -function marked(src, opt) { - return markedInstance.parse(src, opt); -} -/** - * Sets the default options. - * - * @param options Hash of options - */ -marked.options = - marked.setOptions = function (options) { - markedInstance.setOptions(options); - marked.defaults = markedInstance.defaults; - changeDefaults(marked.defaults); - return marked; - }; -/** - * Gets the original marked default options. - */ -marked.getDefaults = _getDefaults; -marked.defaults = _defaults; -/** - * Use Extension - */ -marked.use = function (...args) { - markedInstance.use(...args); - marked.defaults = markedInstance.defaults; - changeDefaults(marked.defaults); - return marked; -}; -/** - * Run callback for every token - */ -marked.walkTokens = function (tokens, callback) { - return markedInstance.walkTokens(tokens, callback); -}; -/** - * Compiles markdown to HTML without enclosing `p` tag. - * - * @param src String of markdown source to be compiled - * @param options Hash of options - * @return String of compiled HTML - */ -marked.parseInline = markedInstance.parseInline; -/** - * Expose - */ -marked.Parser = _Parser; -marked.parser = _Parser.parse; -marked.Renderer = _Renderer; -marked.TextRenderer = _TextRenderer; -marked.Lexer = _Lexer; -marked.lexer = _Lexer.lex; -marked.Tokenizer = _Tokenizer; -marked.Hooks = _Hooks; -marked.parse = marked; -const options = marked.options; -const setOptions = marked.setOptions; -const use = marked.use; -const walkTokens = marked.walkTokens; -const parseInline = marked.parseInline; -const parse = marked; -const parser = _Parser.parse; -const lexer = _Lexer.lex; - -export { _Hooks as Hooks, _Lexer as Lexer, Marked, _Parser as Parser, _Renderer as Renderer, _TextRenderer as TextRenderer, _Tokenizer as Tokenizer, _defaults as defaults, _getDefaults as getDefaults, lexer, marked, options, parse, parseInline, parser, setOptions, use, walkTokens }; -//# sourceMappingURL=marked.esm.js.map diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdf_viewer/viewer.html b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdf_viewer/viewer.html deleted file mode 100644 index 32ac36286a7..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdf_viewer/viewer.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - PDF viewer - - - - - - -
    -
    -
    - - - - diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdf_viewer/viewer.mjs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdf_viewer/viewer.mjs deleted file mode 100644 index 8a4a6b76f5e..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdf_viewer/viewer.mjs +++ /dev/null @@ -1,62 +0,0 @@ -import { GlobalWorkerOptions } from '../pdfjs-dist/dist/build/pdf.min.mjs'; -import { EventBus, PDFLinkService, PDFFindController, PDFViewer } from '../pdfjs-dist/dist/web/pdf_viewer.mjs'; - -GlobalWorkerOptions.workerSrc = '../pdfjs-dist/dist/build/pdf.worker.min.mjs'; - -// Extract the file path from the URL query string. -const url = new URL(window.location); -const fileUrl = url.searchParams.get('file'); -if (!fileUrl) { - throw new Error('File not specified in the URL query string'); -} - -const container = document.getElementById('viewerContainer'); -const eventBus = new EventBus(); - -// Enable hyperlinks within PDF files. -const pdfLinkService = new PDFLinkService({ - eventBus, -}); - -// Enable the find controller. -const pdfFindController = new PDFFindController({ - eventBus, - linkService: pdfLinkService, -}); - -// Create the PDF viewer. -const pdfViewer = new PDFViewer({ - container, - eventBus, - linkService: pdfLinkService, - findController: pdfFindController, -}); -pdfLinkService.setViewer(pdfViewer); - -// Allow navigation to a citation from the URL hash. -eventBus.on('pagesinit', function () { - pdfLinkService.setHash(window.location.hash.substring(1)); -}); - -// Define how the "search" query parameter is handled. -eventBus.on('findfromurlhash', function(evt) { - eventBus.dispatch('find', { - source: evt.source, - type: '', - query: evt.query, - caseSensitive: false, - entireWord: false, - highlightAll: false, - findPrevious: false, - matchDiacritics: true, - }); -}); - -// Load and initialize the document. -const pdfDocument = await pdfjsLib.getDocument({ - url: fileUrl, - enableXfa: true, -}).promise; - -pdfViewer.setDocument(pdfDocument); -pdfLinkService.setDocument(pdfDocument, null); diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/README.md b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/README.md deleted file mode 100644 index 8e77fba7d43..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/README.md +++ /dev/null @@ -1,10 +0,0 @@ -pdfjs-dist version 4.10.38 -https://github.com/mozilla/pdf.js -License: Apache-2.0 - -To update, replace the following files with updated versions from https://www.npmjs.com/package/pdfjs-dist: -* `build/pdf.min.mjs` -* `build/pdf.worker.min.mjs` -* `web/pdf_viewer.css` -* `web/pdf_viewer.mjs` -* `web/images/loading-icon.gif` diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/build/pdf.min.mjs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/build/pdf.min.mjs deleted file mode 100644 index d7cfa914562..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/build/pdf.min.mjs +++ /dev/null @@ -1,21 +0,0 @@ -/** - * @licstart The following is the entire license notice for the - * JavaScript code in this page - * - * Copyright 2024 Mozilla Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * @licend The above is the entire license notice for the - * JavaScript code in this page - */var t={d:(e,i)=>{for(var s in i)t.o(i,s)&&!t.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:i[s]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e)},__webpack_exports__ = globalThis.pdfjsLib = {};t.d(__webpack_exports__,{AbortException:()=>AbortException,AnnotationEditorLayer:()=>AnnotationEditorLayer,AnnotationEditorParamsType:()=>m,AnnotationEditorType:()=>g,AnnotationEditorUIManager:()=>AnnotationEditorUIManager,AnnotationLayer:()=>AnnotationLayer,AnnotationMode:()=>p,ColorPicker:()=>ColorPicker,DOMSVGFactory:()=>DOMSVGFactory,DrawLayer:()=>DrawLayer,FeatureTest:()=>util_FeatureTest,GlobalWorkerOptions:()=>GlobalWorkerOptions,ImageKind:()=>_,InvalidPDFException:()=>InvalidPDFException,MissingPDFException:()=>MissingPDFException,OPS:()=>X,OutputScale:()=>OutputScale,PDFDataRangeTransport:()=>PDFDataRangeTransport,PDFDateString:()=>PDFDateString,PDFWorker:()=>PDFWorker,PasswordResponses:()=>K,PermissionFlag:()=>f,PixelsPerInch:()=>PixelsPerInch,RenderingCancelledException:()=>RenderingCancelledException,TextLayer:()=>TextLayer,TouchManager:()=>TouchManager,UnexpectedResponseException:()=>UnexpectedResponseException,Util:()=>Util,VerbosityLevel:()=>q,XfaLayer:()=>XfaLayer,build:()=>Nt,createValidAbsoluteUrl:()=>createValidAbsoluteUrl,fetchData:()=>fetchData,getDocument:()=>getDocument,getFilenameFromUrl:()=>getFilenameFromUrl,getPdfFilenameFromUrl:()=>getPdfFilenameFromUrl,getXfaPageViewport:()=>getXfaPageViewport,isDataScheme:()=>isDataScheme,isPdfFile:()=>isPdfFile,noContextMenu:()=>noContextMenu,normalizeUnicode:()=>normalizeUnicode,setLayerDimensions:()=>setLayerDimensions,shadow:()=>shadow,stopEvent:()=>stopEvent,version:()=>Ot});const e=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),i=[1,0,0,1,0,0],s=[.001,0,0,.001,0,0],n=1.35,a=1,r=2,o=4,l=16,h=32,d=64,c=128,u=256,p={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},g={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},m={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,HIGHLIGHT_COLOR:31,HIGHLIGHT_DEFAULT_COLOR:32,HIGHLIGHT_THICKNESS:33,HIGHLIGHT_FREE:34,HIGHLIGHT_SHOW_ALL:35,DRAW_STEP:41},f={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},b=0,A=1,w=2,v=3,y=3,x=4,_={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},E=1,S=2,C=3,T=4,M=5,P=6,D=7,k=8,R=9,I=10,F=11,L=12,O=13,N=14,B=15,H=16,z=17,U=20,G=1,$=2,V=3,j=4,W=5,q={ERRORS:0,WARNINGS:1,INFOS:5},X={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91,setStrokeTransparent:92,setFillTransparent:93},K={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let Y=q.WARNINGS;function setVerbosityLevel(t){Number.isInteger(t)&&(Y=t)}function getVerbosityLevel(){return Y}function info(t){Y>=q.INFOS&&console.log(`Info: ${t}`)}function warn(t){Y>=q.WARNINGS&&console.log(`Warning: ${t}`)}function unreachable(t){throw new Error(t)}function assert(t,e){t||unreachable(e)}function createValidAbsoluteUrl(t,e=null,i=null){if(!t)return null;try{if(i&&"string"==typeof t){if(i.addDefaultProtocol&&t.startsWith("www.")){const e=t.match(/\./g);e?.length>=2&&(t=`http://${t}`)}if(i.tryConvertEncoding)try{t=function stringToUTF8String(t){return decodeURIComponent(escape(t))}(t)}catch{}}const s=e?new URL(t,e):new URL(t);if(function _isValidProtocol(t){switch(t?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(s))return s}catch{}return null}function shadow(t,e,i,s=!1){Object.defineProperty(t,e,{value:i,enumerable:!s,configurable:!0,writable:!1});return i}const Q=function BaseExceptionClosure(){function BaseException(t,e){this.message=t;this.name=e}BaseException.prototype=new Error;BaseException.constructor=BaseException;return BaseException}();class PasswordException extends Q{constructor(t,e){super(t,"PasswordException");this.code=e}}class UnknownErrorException extends Q{constructor(t,e){super(t,"UnknownErrorException");this.details=e}}class InvalidPDFException extends Q{constructor(t){super(t,"InvalidPDFException")}}class MissingPDFException extends Q{constructor(t){super(t,"MissingPDFException")}}class UnexpectedResponseException extends Q{constructor(t,e){super(t,"UnexpectedResponseException");this.status=e}}class FormatError extends Q{constructor(t){super(t,"FormatError")}}class AbortException extends Q{constructor(t){super(t,"AbortException")}}function bytesToString(t){"object"==typeof t&&void 0!==t?.length||unreachable("Invalid argument for bytesToString");const e=t.length,i=8192;if(et.toString(16).padStart(2,"0")));class Util{static makeHexColor(t,e,i){return`#${J[t]}${J[e]}${J[i]}`}static scaleMinMax(t,e){let i;if(t[0]){if(t[0]<0){i=e[0];e[0]=e[2];e[2]=i}e[0]*=t[0];e[2]*=t[0];if(t[3]<0){i=e[1];e[1]=e[3];e[3]=i}e[1]*=t[3];e[3]*=t[3]}else{i=e[0];e[0]=e[1];e[1]=i;i=e[2];e[2]=e[3];e[3]=i;if(t[1]<0){i=e[1];e[1]=e[3];e[3]=i}e[1]*=t[1];e[3]*=t[1];if(t[2]<0){i=e[0];e[0]=e[2];e[2]=i}e[0]*=t[2];e[2]*=t[2]}e[0]+=t[4];e[1]+=t[5];e[2]+=t[4];e[3]+=t[5]}static transform(t,e){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],t[0]*e[4]+t[2]*e[5]+t[4],t[1]*e[4]+t[3]*e[5]+t[5]]}static applyTransform(t,e){return[t[0]*e[0]+t[1]*e[2]+e[4],t[0]*e[1]+t[1]*e[3]+e[5]]}static applyInverseTransform(t,e){const i=e[0]*e[3]-e[1]*e[2];return[(t[0]*e[3]-t[1]*e[2]+e[2]*e[5]-e[4]*e[3])/i,(-t[0]*e[1]+t[1]*e[0]+e[4]*e[1]-e[5]*e[0])/i]}static getAxialAlignedBoundingBox(t,e){const i=this.applyTransform(t,e),s=this.applyTransform(t.slice(2,4),e),n=this.applyTransform([t[0],t[3]],e),a=this.applyTransform([t[2],t[1]],e);return[Math.min(i[0],s[0],n[0],a[0]),Math.min(i[1],s[1],n[1],a[1]),Math.max(i[0],s[0],n[0],a[0]),Math.max(i[1],s[1],n[1],a[1])]}static inverseTransform(t){const e=t[0]*t[3]-t[1]*t[2];return[t[3]/e,-t[1]/e,-t[2]/e,t[0]/e,(t[2]*t[5]-t[4]*t[3])/e,(t[4]*t[1]-t[5]*t[0])/e]}static singularValueDecompose2dScale(t){const e=[t[0],t[2],t[1],t[3]],i=t[0]*e[0]+t[1]*e[2],s=t[0]*e[1]+t[1]*e[3],n=t[2]*e[0]+t[3]*e[2],a=t[2]*e[1]+t[3]*e[3],r=(i+a)/2,o=Math.sqrt((i+a)**2-4*(i*a-n*s))/2,l=r+o||1,h=r-o||1;return[Math.sqrt(l),Math.sqrt(h)]}static normalizeRect(t){const e=t.slice(0);if(t[0]>t[2]){e[0]=t[2];e[2]=t[0]}if(t[1]>t[3]){e[1]=t[3];e[3]=t[1]}return e}static intersect(t,e){const i=Math.max(Math.min(t[0],t[2]),Math.min(e[0],e[2])),s=Math.min(Math.max(t[0],t[2]),Math.max(e[0],e[2]));if(i>s)return null;const n=Math.max(Math.min(t[1],t[3]),Math.min(e[1],e[3])),a=Math.min(Math.max(t[1],t[3]),Math.max(e[1],e[3]));return n>a?null:[i,n,s,a]}static#t(t,e,i,s,n,a,r,o,l,h){if(l<=0||l>=1)return;const d=1-l,c=l*l,u=c*l,p=d*(d*(d*t+3*l*e)+3*c*i)+u*s,g=d*(d*(d*n+3*l*a)+3*c*r)+u*o;h[0]=Math.min(h[0],p);h[1]=Math.min(h[1],g);h[2]=Math.max(h[2],p);h[3]=Math.max(h[3],g)}static#e(t,e,i,s,n,a,r,o,l,h,d,c){if(Math.abs(l)<1e-12){Math.abs(h)>=1e-12&&this.#t(t,e,i,s,n,a,r,o,-d/h,c);return}const u=h**2-4*d*l;if(u<0)return;const p=Math.sqrt(u),g=2*l;this.#t(t,e,i,s,n,a,r,o,(-h+p)/g,c);this.#t(t,e,i,s,n,a,r,o,(-h-p)/g,c)}static bezierBoundingBox(t,e,i,s,n,a,r,o,l){if(l){l[0]=Math.min(l[0],t,r);l[1]=Math.min(l[1],e,o);l[2]=Math.max(l[2],t,r);l[3]=Math.max(l[3],e,o)}else l=[Math.min(t,r),Math.min(e,o),Math.max(t,r),Math.max(e,o)];this.#e(t,i,n,r,e,s,a,o,3*(3*(i-n)-t+r),6*(t-2*i+n),3*(i-t),l);this.#e(t,i,n,r,e,s,a,o,3*(3*(s-a)-e+o),6*(e-2*s+a),3*(s-e),l);return l}}let Z=null,tt=null;function normalizeUnicode(t){if(!Z){Z=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu;tt=new Map([["ſt","ſt"]])}return t.replaceAll(Z,((t,e,i)=>e?e.normalize("NFKC"):tt.get(i)))}const et="pdfjs_internal_id_";"function"!=typeof Promise.try&&(Promise.try=function(t,...e){return new Promise((i=>{i(t(...e))}))});const it="http://www.w3.org/2000/svg";class PixelsPerInch{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function fetchData(t,e="text"){if(isValidFetchUrl(t,document.baseURI)){const i=await fetch(t);if(!i.ok)throw new Error(i.statusText);switch(e){case"arraybuffer":return i.arrayBuffer();case"blob":return i.blob();case"json":return i.json()}return i.text()}return new Promise(((i,s)=>{const n=new XMLHttpRequest;n.open("GET",t,!0);n.responseType=e;n.onreadystatechange=()=>{if(n.readyState===XMLHttpRequest.DONE)if(200!==n.status&&0!==n.status)s(new Error(n.statusText));else{switch(e){case"arraybuffer":case"blob":case"json":i(n.response);return}i(n.responseText)}};n.send(null)}))}class PageViewport{constructor({viewBox:t,userUnit:e,scale:i,rotation:s,offsetX:n=0,offsetY:a=0,dontFlip:r=!1}){this.viewBox=t;this.userUnit=e;this.scale=i;this.rotation=s;this.offsetX=n;this.offsetY=a;i*=e;const o=(t[2]+t[0])/2,l=(t[3]+t[1])/2;let h,d,c,u,p,g,m,f;(s%=360)<0&&(s+=360);switch(s){case 180:h=-1;d=0;c=0;u=1;break;case 90:h=0;d=1;c=1;u=0;break;case 270:h=0;d=-1;c=-1;u=0;break;case 0:h=1;d=0;c=0;u=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}if(r){c=-c;u=-u}if(0===h){p=Math.abs(l-t[1])*i+n;g=Math.abs(o-t[0])*i+a;m=(t[3]-t[1])*i;f=(t[2]-t[0])*i}else{p=Math.abs(o-t[0])*i+n;g=Math.abs(l-t[1])*i+a;m=(t[2]-t[0])*i;f=(t[3]-t[1])*i}this.transform=[h*i,d*i,c*i,u*i,p-h*i*o-c*i*l,g-d*i*o-u*i*l];this.width=m;this.height=f}get rawDims(){const{userUnit:t,viewBox:e}=this,i=e.map((e=>e*t));return shadow(this,"rawDims",{pageWidth:i[2]-i[0],pageHeight:i[3]-i[1],pageX:i[0],pageY:i[1]})}clone({scale:t=this.scale,rotation:e=this.rotation,offsetX:i=this.offsetX,offsetY:s=this.offsetY,dontFlip:n=!1}={}){return new PageViewport({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:t,rotation:e,offsetX:i,offsetY:s,dontFlip:n})}convertToViewportPoint(t,e){return Util.applyTransform([t,e],this.transform)}convertToViewportRectangle(t){const e=Util.applyTransform([t[0],t[1]],this.transform),i=Util.applyTransform([t[2],t[3]],this.transform);return[e[0],e[1],i[0],i[1]]}convertToPdfPoint(t,e){return Util.applyInverseTransform([t,e],this.transform)}}class RenderingCancelledException extends Q{constructor(t,e=0){super(t,"RenderingCancelledException");this.extraDelay=e}}function isDataScheme(t){const e=t.length;let i=0;for(;i=1&&s<=12?s-1:0;let n=parseInt(e[3],10);n=n>=1&&n<=31?n:1;let a=parseInt(e[4],10);a=a>=0&&a<=23?a:0;let r=parseInt(e[5],10);r=r>=0&&r<=59?r:0;let o=parseInt(e[6],10);o=o>=0&&o<=59?o:0;const l=e[7]||"Z";let h=parseInt(e[8],10);h=h>=0&&h<=23?h:0;let d=parseInt(e[9],10)||0;d=d>=0&&d<=59?d:0;if("-"===l){a+=h;r+=d}else if("+"===l){a-=h;r-=d}return new Date(Date.UTC(i,s,n,a,r,o))}}function getXfaPageViewport(t,{scale:e=1,rotation:i=0}){const{width:s,height:n}=t.attributes.style,a=[0,0,parseInt(s),parseInt(n)];return new PageViewport({viewBox:a,userUnit:1,scale:e,rotation:i})}function getRGB(t){if(t.startsWith("#")){const e=parseInt(t.slice(1),16);return[(16711680&e)>>16,(65280&e)>>8,255&e]}if(t.startsWith("rgb("))return t.slice(4,-1).split(",").map((t=>parseInt(t)));if(t.startsWith("rgba("))return t.slice(5,-1).split(",").map((t=>parseInt(t))).slice(0,3);warn(`Not a valid color format: "${t}"`);return[0,0,0]}function getCurrentTransform(t){const{a:e,b:i,c:s,d:n,e:a,f:r}=t.getTransform();return[e,i,s,n,a,r]}function getCurrentTransformInverse(t){const{a:e,b:i,c:s,d:n,e:a,f:r}=t.getTransform().invertSelf();return[e,i,s,n,a,r]}function setLayerDimensions(t,e,i=!1,s=!0){if(e instanceof PageViewport){const{pageWidth:s,pageHeight:n}=e.rawDims,{style:a}=t,r=util_FeatureTest.isCSSRoundSupported,o=`var(--scale-factor) * ${s}px`,l=`var(--scale-factor) * ${n}px`,h=r?`round(down, ${o}, var(--scale-round-x, 1px))`:`calc(${o})`,d=r?`round(down, ${l}, var(--scale-round-y, 1px))`:`calc(${l})`;if(i&&e.rotation%180!=0){a.width=d;a.height=h}else{a.width=h;a.height=d}}s&&t.setAttribute("data-main-rotation",e.rotation)}class OutputScale{constructor(){const t=window.devicePixelRatio||1;this.sx=t;this.sy=t}get scaled(){return 1!==this.sx||1!==this.sy}get symmetric(){return this.sx===this.sy}}class EditorToolbar{#s=null;#n=null;#a;#r=null;#o=null;static#l=null;constructor(t){this.#a=t;EditorToolbar.#l||=Object.freeze({freetext:"pdfjs-editor-remove-freetext-button",highlight:"pdfjs-editor-remove-highlight-button",ink:"pdfjs-editor-remove-ink-button",stamp:"pdfjs-editor-remove-stamp-button"})}render(){const t=this.#s=document.createElement("div");t.classList.add("editToolbar","hidden");t.setAttribute("role","toolbar");const e=this.#a._uiManager._signal;t.addEventListener("contextmenu",noContextMenu,{signal:e});t.addEventListener("pointerdown",EditorToolbar.#h,{signal:e});const i=this.#r=document.createElement("div");i.className="buttons";t.append(i);const s=this.#a.toolbarPosition;if(s){const{style:e}=t,i="ltr"===this.#a._uiManager.direction?1-s[0]:s[0];e.insetInlineEnd=100*i+"%";e.top=`calc(${100*s[1]}% + var(--editor-toolbar-vert-offset))`}this.#d();return t}get div(){return this.#s}static#h(t){t.stopPropagation()}#c(t){this.#a._focusEventsAllowed=!1;stopEvent(t)}#u(t){this.#a._focusEventsAllowed=!0;stopEvent(t)}#p(t){const e=this.#a._uiManager._signal;t.addEventListener("focusin",this.#c.bind(this),{capture:!0,signal:e});t.addEventListener("focusout",this.#u.bind(this),{capture:!0,signal:e});t.addEventListener("contextmenu",noContextMenu,{signal:e})}hide(){this.#s.classList.add("hidden");this.#n?.hideDropdown()}show(){this.#s.classList.remove("hidden");this.#o?.shown()}#d(){const{editorType:t,_uiManager:e}=this.#a,i=document.createElement("button");i.className="delete";i.tabIndex=0;i.setAttribute("data-l10n-id",EditorToolbar.#l[t]);this.#p(i);i.addEventListener("click",(t=>{e.delete()}),{signal:e._signal});this.#r.append(i)}get#g(){const t=document.createElement("div");t.className="divider";return t}async addAltText(t){const e=await t.render();this.#p(e);this.#r.prepend(e,this.#g);this.#o=t}addColorPicker(t){this.#n=t;const e=t.renderButton();this.#p(e);this.#r.prepend(e,this.#g)}remove(){this.#s.remove();this.#n?.destroy();this.#n=null}}class HighlightToolbar{#r=null;#s=null;#m;constructor(t){this.#m=t}#f(){const t=this.#s=document.createElement("div");t.className="editToolbar";t.setAttribute("role","toolbar");t.addEventListener("contextmenu",noContextMenu,{signal:this.#m._signal});const e=this.#r=document.createElement("div");e.className="buttons";t.append(e);this.#b();return t}#A(t,e){let i=0,s=0;for(const n of t){const t=n.y+n.height;if(ti){s=a;i=t}else e?a>s&&(s=a):a{this.#m.highlightSelection("floating_button")}),{signal:i});this.#r.append(t)}}function bindEvents(t,e,i){for(const s of i)e.addEventListener(s,t[s].bind(t))}class IdManager{#w=0;get id(){return"pdfjs_internal_editor_"+this.#w++}}class ImageManager{#v=function getUuid(){if("function"==typeof crypto.randomUUID)return crypto.randomUUID();const t=new Uint8Array(32);crypto.getRandomValues(t);return bytesToString(t)}();#w=0;#y=null;static get _isSVGFittingCanvas(){const t=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),e=new Image;e.src='data:image/svg+xml;charset=UTF-8,';return shadow(this,"_isSVGFittingCanvas",e.decode().then((()=>{t.drawImage(e,0,0,1,1,0,0,1,3);return 0===new Uint32Array(t.getImageData(0,0,1,1).data.buffer)[0]})))}async#x(t,e){this.#y||=new Map;let i=this.#y.get(t);if(null===i)return null;if(i?.bitmap){i.refCounter+=1;return i}try{i||={bitmap:null,id:`image_${this.#v}_${this.#w++}`,refCounter:0,isSvg:!1};let t;if("string"==typeof e){i.url=e;t=await fetchData(e,"blob")}else e instanceof File?t=i.file=e:e instanceof Blob&&(t=e);if("image/svg+xml"===t.type){const e=ImageManager._isSVGFittingCanvas,s=new FileReader,n=new Image,a=new Promise(((t,a)=>{n.onload=()=>{i.bitmap=n;i.isSvg=!0;t()};s.onload=async()=>{const t=i.svgUrl=s.result;n.src=await e?`${t}#svgView(preserveAspectRatio(none))`:t};n.onerror=s.onerror=a}));s.readAsDataURL(t);await a}else i.bitmap=await createImageBitmap(t);i.refCounter=1}catch(t){warn(t);i=null}this.#y.set(t,i);i&&this.#y.set(i.id,i);return i}async getFromFile(t){const{lastModified:e,name:i,size:s,type:n}=t;return this.#x(`${e}_${i}_${s}_${n}`,t)}async getFromUrl(t){return this.#x(t,t)}async getFromBlob(t,e){const i=await e;return this.#x(t,i)}async getFromId(t){this.#y||=new Map;const e=this.#y.get(t);if(!e)return null;if(e.bitmap){e.refCounter+=1;return e}if(e.file)return this.getFromFile(e.file);if(e.blobPromise){const{blobPromise:t}=e;delete e.blobPromise;return this.getFromBlob(e.id,t)}return this.getFromUrl(e.url)}getFromCanvas(t,e){this.#y||=new Map;let i=this.#y.get(t);if(i?.bitmap){i.refCounter+=1;return i}const s=new OffscreenCanvas(e.width,e.height);s.getContext("2d").drawImage(e,0,0);i={bitmap:s.transferToImageBitmap(),id:`image_${this.#v}_${this.#w++}`,refCounter:1,isSvg:!1};this.#y.set(t,i);this.#y.set(i.id,i);return i}getSvgUrl(t){const e=this.#y.get(t);return e?.isSvg?e.svgUrl:null}deleteId(t){this.#y||=new Map;const e=this.#y.get(t);if(!e)return;e.refCounter-=1;if(0!==e.refCounter)return;const{bitmap:i}=e;if(!e.url&&!e.file){const t=new OffscreenCanvas(i.width,i.height);t.getContext("bitmaprenderer").transferFromImageBitmap(i);e.blobPromise=t.convertToBlob()}i.close?.();e.bitmap=null}isValidId(t){return t.startsWith(`image_${this.#v}_`)}}class CommandManager{#_=[];#E=!1;#S;#C=-1;constructor(t=128){this.#S=t}add({cmd:t,undo:e,post:i,mustExec:s,type:n=NaN,overwriteIfSameType:a=!1,keepUndo:r=!1}){s&&t();if(this.#E)return;const o={cmd:t,undo:e,post:i,type:n};if(-1===this.#C){this.#_.length>0&&(this.#_.length=0);this.#C=0;this.#_.push(o);return}if(a&&this.#_[this.#C].type===n){r&&(o.undo=this.#_[this.#C].undo);this.#_[this.#C]=o;return}const l=this.#C+1;if(l===this.#S)this.#_.splice(0,1);else{this.#C=l;l=0;e--)if(this.#_[e].type!==t){this.#_.splice(e+1,this.#C-e);this.#C=e;return}this.#_.length=0;this.#C=-1}}destroy(){this.#_=null}}class KeyboardManager{constructor(t){this.buffer=[];this.callbacks=new Map;this.allKeys=new Set;const{isMac:e}=util_FeatureTest.platform;for(const[i,s,n={}]of t)for(const t of i){const i=t.startsWith("mac+");if(e&&i){this.callbacks.set(t.slice(4),{callback:s,options:n});this.allKeys.add(t.split("+").at(-1))}else if(!e&&!i){this.callbacks.set(t,{callback:s,options:n});this.allKeys.add(t.split("+").at(-1))}}}#T(t){t.altKey&&this.buffer.push("alt");t.ctrlKey&&this.buffer.push("ctrl");t.metaKey&&this.buffer.push("meta");t.shiftKey&&this.buffer.push("shift");this.buffer.push(t.key);const e=this.buffer.join("+");this.buffer.length=0;return e}exec(t,e){if(!this.allKeys.has(e.key))return;const i=this.callbacks.get(this.#T(e));if(!i)return;const{callback:s,options:{bubbles:n=!1,args:a=[],checker:r=null}}=i;if(!r||r(t,e)){s.bind(t,...a,e)();n||stopEvent(e)}}}class ColorManager{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){const t=new Map([["CanvasText",null],["Canvas",null]]);!function getColorValues(t){const e=document.createElement("span");e.style.visibility="hidden";document.body.append(e);for(const i of t.keys()){e.style.color=i;const s=window.getComputedStyle(e).color;t.set(i,getRGB(s))}e.remove()}(t);return shadow(this,"_colors",t)}convert(t){const e=getRGB(t);if(!window.matchMedia("(forced-colors: active)").matches)return e;for(const[t,i]of this._colors)if(i.every(((t,i)=>t===e[i])))return ColorManager._colorsMapping.get(t);return e}getHexCode(t){const e=this._colors.get(t);return e?Util.makeHexColor(...e):t}}class AnnotationEditorUIManager{#M=new AbortController;#P=null;#D=new Map;#k=new Map;#R=null;#I=null;#F=null;#L=new CommandManager;#O=null;#N=null;#B=0;#H=new Set;#z=null;#U=null;#G=new Set;_editorUndoBar=null;#$=!1;#V=!1;#j=!1;#W=null;#q=null;#X=null;#K=null;#Y=!1;#Q=null;#J=new IdManager;#Z=!1;#tt=!1;#et=null;#it=null;#st=null;#nt=null;#at=g.NONE;#rt=new Set;#ot=null;#lt=null;#ht=null;#dt={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#ct=[0,0];#ut=null;#pt=null;#gt=null;#mt=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=AnnotationEditorUIManager.prototype,arrowChecker=t=>t.#pt.contains(document.activeElement)&&"BUTTON"!==document.activeElement.tagName&&t.hasSomethingToControl(),textInputChecker=(t,{target:e})=>{if(e instanceof HTMLInputElement){const{type:t}=e;return"text"!==t&&"number"!==t}return!0},e=this.TRANSLATE_SMALL,i=this.TRANSLATE_BIG;return shadow(this,"_keyboardManager",new KeyboardManager([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:textInputChecker}],[["ctrl+z","mac+meta+z"],t.undo,{checker:textInputChecker}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:textInputChecker}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],t.delete,{checker:textInputChecker}],[["Enter","mac+Enter"],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#pt.contains(e)&&!t.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#pt.contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-e,0],checker:arrowChecker}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-i,0],checker:arrowChecker}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[e,0],checker:arrowChecker}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[i,0],checker:arrowChecker}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-e],checker:arrowChecker}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-i],checker:arrowChecker}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,e],checker:arrowChecker}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,i],checker:arrowChecker}]]))}constructor(t,e,i,s,n,a,r,o,l,h,d,c,u){const p=this._signal=this.#M.signal;this.#pt=t;this.#gt=e;this.#R=i;this._eventBus=s;s._on("editingaction",this.onEditingAction.bind(this),{signal:p});s._on("pagechanging",this.onPageChanging.bind(this),{signal:p});s._on("scalechanging",this.onScaleChanging.bind(this),{signal:p});s._on("rotationchanging",this.onRotationChanging.bind(this),{signal:p});s._on("setpreference",this.onSetPreference.bind(this),{signal:p});s._on("switchannotationeditorparams",(t=>this.updateParams(t.type,t.value)),{signal:p});this.#ft();this.#bt();this.#At();this.#I=n.annotationStorage;this.#W=n.filterFactory;this.#lt=a;this.#K=r||null;this.#$=o;this.#V=l;this.#j=h;this.#nt=d||null;this.viewParameters={realScale:PixelsPerInch.PDF_TO_CSS_UNITS,rotation:0};this.isShiftKeyDown=!1;this._editorUndoBar=c||null;this._supportsPinchToZoom=!1!==u}destroy(){this.#mt?.resolve();this.#mt=null;this.#M?.abort();this.#M=null;this._signal=null;for(const t of this.#k.values())t.destroy();this.#k.clear();this.#D.clear();this.#G.clear();this.#P=null;this.#rt.clear();this.#L.destroy();this.#R?.destroy();this.#Q?.hide();this.#Q=null;if(this.#q){clearTimeout(this.#q);this.#q=null}if(this.#ut){clearTimeout(this.#ut);this.#ut=null}this._editorUndoBar?.destroy()}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return this.#nt}get useNewAltTextFlow(){return this.#V}get useNewAltTextWhenAddingImage(){return this.#j}get hcmFilter(){return shadow(this,"hcmFilter",this.#lt?this.#W.addHCMFilter(this.#lt.foreground,this.#lt.background):"none")}get direction(){return shadow(this,"direction",getComputedStyle(this.#pt).direction)}get highlightColors(){return shadow(this,"highlightColors",this.#K?new Map(this.#K.split(",").map((t=>t.split("=").map((t=>t.trim()))))):null)}get highlightColorNames(){return shadow(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,(t=>t.reverse()))):null)}setCurrentDrawingSession(t){if(t){this.unselectAll();this.disableUserSelect(!0)}else this.disableUserSelect(!1);this.#N=t}setMainHighlightColorPicker(t){this.#st=t}editAltText(t,e=!1){this.#R?.editAltText(this,t,e)}switchToMode(t,e){this._eventBus.on("annotationeditormodechanged",e,{once:!0,signal:this._signal});this._eventBus.dispatch("showannotationeditorui",{source:this,mode:t})}setPreference(t,e){this._eventBus.dispatch("setpreference",{source:this,name:t,value:e})}onSetPreference({name:t,value:e}){if("enableNewAltTextWhenAddingImage"===t)this.#j=e}onPageChanging({pageNumber:t}){this.#B=t-1}focusMainContainer(){this.#pt.focus()}findParent(t,e){for(const i of this.#k.values()){const{x:s,y:n,width:a,height:r}=i.div.getBoundingClientRect();if(t>=s&&t<=s+a&&e>=n&&e<=n+r)return i}return null}disableUserSelect(t=!1){this.#gt.classList.toggle("noUserSelect",t)}addShouldRescale(t){this.#G.add(t)}removeShouldRescale(t){this.#G.delete(t)}onScaleChanging({scale:t}){this.commitOrRemove();this.viewParameters.realScale=t*PixelsPerInch.PDF_TO_CSS_UNITS;for(const t of this.#G)t.onScaleChanging();this.#N?.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove();this.viewParameters.rotation=t}#wt({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}#vt(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const e of this.#k.values())if(e.hasTextLayer(t))return e;return null}highlightSelection(t=""){const e=document.getSelection();if(!e||e.isCollapsed)return;const{anchorNode:i,anchorOffset:s,focusNode:n,focusOffset:a}=e,r=e.toString(),o=this.#wt(e).closest(".textLayer"),l=this.getSelectionBoxes(o);if(!l)return;e.empty();const h=this.#vt(o),d=this.#at===g.NONE,callback=()=>{h?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:l,anchorNode:i,anchorOffset:s,focusNode:n,focusOffset:a,text:r});d&&this.showAllEditors("highlight",!0,!0)};d?this.switchToMode(g.HIGHLIGHT,callback):callback()}#yt(){const t=document.getSelection();if(!t||t.isCollapsed)return;const e=this.#wt(t).closest(".textLayer"),i=this.getSelectionBoxes(e);if(i){this.#Q||=new HighlightToolbar(this);this.#Q.show(e,i,"ltr"===this.direction)}}addToAnnotationStorage(t){t.isEmpty()||!this.#I||this.#I.has(t.id)||this.#I.setValue(t.id,t)}#xt(){const t=document.getSelection();if(!t||t.isCollapsed){if(this.#ot){this.#Q?.hide();this.#ot=null;this.#_t({hasSelectedText:!1})}return}const{anchorNode:e}=t;if(e===this.#ot)return;const i=this.#wt(t).closest(".textLayer");if(i){this.#Q?.hide();this.#ot=e;this.#_t({hasSelectedText:!0});if(this.#at===g.HIGHLIGHT||this.#at===g.NONE){this.#at===g.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0);this.#Y=this.isShiftKeyDown;if(!this.isShiftKeyDown){const t=this.#at===g.HIGHLIGHT?this.#vt(i):null;t?.toggleDrawing();const e=new AbortController,s=this.combinedSignal(e),pointerup=i=>{if("pointerup"!==i.type||0===i.button){e.abort();t?.toggleDrawing(!0);"pointerup"===i.type&&this.#Et("main_toolbar")}};window.addEventListener("pointerup",pointerup,{signal:s});window.addEventListener("blur",pointerup,{signal:s})}}}else if(this.#ot){this.#Q?.hide();this.#ot=null;this.#_t({hasSelectedText:!1})}}#Et(t=""){this.#at===g.HIGHLIGHT?this.highlightSelection(t):this.#$&&this.#yt()}#ft(){document.addEventListener("selectionchange",this.#xt.bind(this),{signal:this._signal})}#St(){if(this.#X)return;this.#X=new AbortController;const t=this.combinedSignal(this.#X);window.addEventListener("focus",this.focus.bind(this),{signal:t});window.addEventListener("blur",this.blur.bind(this),{signal:t})}#Ct(){this.#X?.abort();this.#X=null}blur(){this.isShiftKeyDown=!1;if(this.#Y){this.#Y=!1;this.#Et("main_toolbar")}if(!this.hasSelection)return;const{activeElement:t}=document;for(const e of this.#rt)if(e.div.contains(t)){this.#it=[e,t];e._focusEventsAllowed=!1;break}}focus(){if(!this.#it)return;const[t,e]=this.#it;this.#it=null;e.addEventListener("focusin",(()=>{t._focusEventsAllowed=!0}),{once:!0,signal:this._signal});e.focus()}#At(){if(this.#et)return;this.#et=new AbortController;const t=this.combinedSignal(this.#et);window.addEventListener("keydown",this.keydown.bind(this),{signal:t});window.addEventListener("keyup",this.keyup.bind(this),{signal:t})}#Tt(){this.#et?.abort();this.#et=null}#Mt(){if(this.#O)return;this.#O=new AbortController;const t=this.combinedSignal(this.#O);document.addEventListener("copy",this.copy.bind(this),{signal:t});document.addEventListener("cut",this.cut.bind(this),{signal:t});document.addEventListener("paste",this.paste.bind(this),{signal:t})}#Pt(){this.#O?.abort();this.#O=null}#bt(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t});document.addEventListener("drop",this.drop.bind(this),{signal:t})}addEditListeners(){this.#At();this.#Mt()}removeEditListeners(){this.#Tt();this.#Pt()}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const i of this.#U)if(i.isHandlingMimeForPasting(e)){t.dataTransfer.dropEffect="copy";t.preventDefault();return}}drop(t){for(const e of t.dataTransfer.items)for(const i of this.#U)if(i.isHandlingMimeForPasting(e.type)){i.paste(e,this.currentLayer);t.preventDefault();return}}copy(t){t.preventDefault();this.#P?.commitOrRemove();if(!this.hasSelection)return;const e=[];for(const t of this.#rt){const i=t.serialize(!0);i&&e.push(i)}0!==e.length&&t.clipboardData.setData("application/pdfjs",JSON.stringify(e))}cut(t){this.copy(t);this.delete()}async paste(t){t.preventDefault();const{clipboardData:e}=t;for(const t of e.items)for(const e of this.#U)if(e.isHandlingMimeForPasting(t.type)){e.paste(t,this.currentLayer);return}let i=e.getData("application/pdfjs");if(!i)return;try{i=JSON.parse(i)}catch(t){warn(`paste: "${t.message}".`);return}if(!Array.isArray(i))return;this.unselectAll();const s=this.currentLayer;try{const t=[];for(const e of i){const i=await s.deserialize(e);if(!i)return;t.push(i)}const cmd=()=>{for(const e of t)this.#Dt(e);this.#kt(t)},undo=()=>{for(const e of t)e.remove()};this.addCommands({cmd,undo,mustExec:!0})}catch(t){warn(`paste: "${t.message}".`)}}keydown(t){this.isShiftKeyDown||"Shift"!==t.key||(this.isShiftKeyDown=!0);this.#at===g.NONE||this.isEditorHandlingKeyboard||AnnotationEditorUIManager._keyboardManager.exec(this,t)}keyup(t){if(this.isShiftKeyDown&&"Shift"===t.key){this.isShiftKeyDown=!1;if(this.#Y){this.#Y=!1;this.#Et("main_toolbar")}}}onEditingAction({name:t}){switch(t){case"undo":case"redo":case"delete":case"selectAll":this[t]();break;case"highlightSelection":this.highlightSelection("context_menu")}}#_t(t){if(Object.entries(t).some((([t,e])=>this.#dt[t]!==e))){this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#dt,t)});this.#at===g.HIGHLIGHT&&!1===t.hasSelectedEditor&&this.#Rt([[m.HIGHLIGHT_FREE,!0]])}}#Rt(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){if(t){this.#St();this.#Mt();this.#_t({isEditing:this.#at!==g.NONE,isEmpty:this.#It(),hasSomethingToUndo:this.#L.hasSomethingToUndo(),hasSomethingToRedo:this.#L.hasSomethingToRedo(),hasSelectedEditor:!1})}else{this.#Ct();this.#Pt();this.#_t({isEditing:!1});this.disableUserSelect(!1)}}registerEditorTypes(t){if(!this.#U){this.#U=t;for(const t of this.#U)this.#Rt(t.defaultPropertiesToUpdate)}}getId(){return this.#J.id}get currentLayer(){return this.#k.get(this.#B)}getLayer(t){return this.#k.get(t)}get currentPageIndex(){return this.#B}addLayer(t){this.#k.set(t.pageIndex,t);this.#Z?t.enable():t.disable()}removeLayer(t){this.#k.delete(t.pageIndex)}async updateMode(t,e=null,i=!1){if(this.#at!==t){if(this.#mt){await this.#mt.promise;if(!this.#mt)return}this.#mt=Promise.withResolvers();this.#at=t;if(t!==g.NONE){this.setEditingState(!0);await this.#Ft();this.unselectAll();for(const e of this.#k.values())e.updateMode(t);if(e){for(const t of this.#D.values())if(t.annotationElementId===e){this.setSelected(t);t.enterInEditMode()}else t.unselect();this.#mt.resolve()}else{i&&this.addNewEditorFromKeyboard();this.#mt.resolve()}}else{this.setEditingState(!1);this.#Lt();this._editorUndoBar?.hide();this.#mt.resolve()}}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==this.#at&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,e){if(this.#U){switch(t){case m.CREATE:this.currentLayer.addNewEditor();return;case m.HIGHLIGHT_DEFAULT_COLOR:this.#st?.updateColor(e);break;case m.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}});(this.#ht||=new Map).set(t,e);this.showAllEditors("highlight",e)}for(const i of this.#rt)i.updateParams(t,e);for(const i of this.#U)i.updateDefaultParams(t,e)}}showAllEditors(t,e,i=!1){for(const i of this.#D.values())i.editorType===t&&i.show(e);(this.#ht?.get(m.HIGHLIGHT_SHOW_ALL)??!0)!==e&&this.#Rt([[m.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(this.#tt!==t){this.#tt=t;for(const e of this.#k.values()){t?e.disableClick():e.enableClick();e.div.classList.toggle("waiting",t)}}}async#Ft(){if(!this.#Z){this.#Z=!0;const t=[];for(const e of this.#k.values())t.push(e.enable());await Promise.all(t);for(const t of this.#D.values())t.enable()}}#Lt(){this.unselectAll();if(this.#Z){this.#Z=!1;for(const t of this.#k.values())t.disable();for(const t of this.#D.values())t.disable()}}getEditors(t){const e=[];for(const i of this.#D.values())i.pageIndex===t&&e.push(i);return e}getEditor(t){return this.#D.get(t)}addEditor(t){this.#D.set(t.id,t)}removeEditor(t){if(t.div.contains(document.activeElement)){this.#q&&clearTimeout(this.#q);this.#q=setTimeout((()=>{this.focusMainContainer();this.#q=null}),0)}this.#D.delete(t.id);this.unselect(t);t.annotationElementId&&this.#H.has(t.annotationElementId)||this.#I?.remove(t.id)}addDeletedAnnotationElement(t){this.#H.add(t.annotationElementId);this.addChangedExistingAnnotation(t);t.deleted=!0}isDeletedAnnotationElement(t){return this.#H.has(t)}removeDeletedAnnotationElement(t){this.#H.delete(t.annotationElementId);this.removeChangedExistingAnnotation(t);t.deleted=!1}#Dt(t){const e=this.#k.get(t.pageIndex);if(e)e.addOrRebuild(t);else{this.addEditor(t);this.addToAnnotationStorage(t)}}setActiveEditor(t){if(this.#P!==t){this.#P=t;t&&this.#Rt(t.propertiesToUpdate)}}get#Ot(){let t=null;for(t of this.#rt);return t}updateUI(t){this.#Ot===t&&this.#Rt(t.propertiesToUpdate)}updateUIForDefaultProperties(t){this.#Rt(t.defaultPropertiesToUpdate)}toggleSelected(t){if(this.#rt.has(t)){this.#rt.delete(t);t.unselect();this.#_t({hasSelectedEditor:this.hasSelection})}else{this.#rt.add(t);t.select();this.#Rt(t.propertiesToUpdate);this.#_t({hasSelectedEditor:!0})}}setSelected(t){this.#N?.commitOrRemove();for(const e of this.#rt)e!==t&&e.unselect();this.#rt.clear();this.#rt.add(t);t.select();this.#Rt(t.propertiesToUpdate);this.#_t({hasSelectedEditor:!0})}isSelected(t){return this.#rt.has(t)}get firstSelectedEditor(){return this.#rt.values().next().value}unselect(t){t.unselect();this.#rt.delete(t);this.#_t({hasSelectedEditor:this.hasSelection})}get hasSelection(){return 0!==this.#rt.size}get isEnterHandled(){return 1===this.#rt.size&&this.firstSelectedEditor.isEnterHandled}undo(){this.#L.undo();this.#_t({hasSomethingToUndo:this.#L.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#It()});this._editorUndoBar?.hide()}redo(){this.#L.redo();this.#_t({hasSomethingToUndo:!0,hasSomethingToRedo:this.#L.hasSomethingToRedo(),isEmpty:this.#It()})}addCommands(t){this.#L.add(t);this.#_t({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#It()})}cleanUndoStack(t){this.#L.cleanType(t)}#It(){if(0===this.#D.size)return!0;if(1===this.#D.size)for(const t of this.#D.values())return t.isEmpty();return!1}delete(){this.commitOrRemove();const t=this.currentLayer?.endDrawingSession(!0);if(!this.hasSelection&&!t)return;const e=t?[t]:[...this.#rt],undo=()=>{for(const t of e)this.#Dt(t)};this.addCommands({cmd:()=>{this._editorUndoBar?.show(undo,1===e.length?e[0].editorType:e.length);for(const t of e)t.remove()},undo,mustExec:!0})}commitOrRemove(){this.#P?.commitOrRemove()}hasSomethingToControl(){return this.#P||this.hasSelection}#kt(t){for(const t of this.#rt)t.unselect();this.#rt.clear();for(const e of t)if(!e.isEmpty()){this.#rt.add(e);e.select()}this.#_t({hasSelectedEditor:this.hasSelection})}selectAll(){for(const t of this.#rt)t.commit();this.#kt(this.#D.values())}unselectAll(){if(this.#P){this.#P.commitOrRemove();if(this.#at!==g.NONE)return}if(!this.#N?.commitOrRemove()&&this.hasSelection){for(const t of this.#rt)t.unselect();this.#rt.clear();this.#_t({hasSelectedEditor:!1})}}translateSelectedEditors(t,e,i=!1){i||this.commitOrRemove();if(!this.hasSelection)return;this.#ct[0]+=t;this.#ct[1]+=e;const[s,n]=this.#ct,a=[...this.#rt];this.#ut&&clearTimeout(this.#ut);this.#ut=setTimeout((()=>{this.#ut=null;this.#ct[0]=this.#ct[1]=0;this.addCommands({cmd:()=>{for(const t of a)this.#D.has(t.id)&&t.translateInPage(s,n)},undo:()=>{for(const t of a)this.#D.has(t.id)&&t.translateInPage(-s,-n)},mustExec:!1})}),1e3);for(const i of a)i.translateInPage(t,e)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0);this.#z=new Map;for(const t of this.#rt)this.#z.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#z)return!1;this.disableUserSelect(!1);const t=this.#z;this.#z=null;let e=!1;for(const[{x:i,y:s,pageIndex:n},a]of t){a.newX=i;a.newY=s;a.newPageIndex=n;e||=i!==a.savedX||s!==a.savedY||n!==a.savedPageIndex}if(!e)return!1;const move=(t,e,i,s)=>{if(this.#D.has(t.id)){const n=this.#k.get(s);if(n)t._setParentAndPosition(n,e,i);else{t.pageIndex=s;t.x=e;t.y=i}}};this.addCommands({cmd:()=>{for(const[e,{newX:i,newY:s,newPageIndex:n}]of t)move(e,i,s,n)},undo:()=>{for(const[e,{savedX:i,savedY:s,savedPageIndex:n}]of t)move(e,i,s,n)},mustExec:!0});return!0}dragSelectedEditors(t,e){if(this.#z)for(const i of this.#z.keys())i.drag(t,e)}rebuild(t){if(null===t.parent){const e=this.getLayer(t.pageIndex);if(e){e.changeParent(t);e.addOrRebuild(t)}else{this.addEditor(t);this.addToAnnotationStorage(t);t.rebuild()}}else t.parent.addOrRebuild(t)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||1===this.#rt.size&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#P===t}getActive(){return this.#P}getMode(){return this.#at}get imageManager(){return shadow(this,"imageManager",new ImageManager)}getSelectionBoxes(t){if(!t)return null;const e=document.getSelection();for(let i=0,s=e.rangeCount;i({x:(e-s)/a,y:1-(t+r-i)/n,width:o/a,height:r/n});break;case"180":r=(t,e,r,o)=>({x:1-(t+r-i)/n,y:1-(e+o-s)/a,width:r/n,height:o/a});break;case"270":r=(t,e,r,o)=>({x:1-(e+o-s)/a,y:(t-i)/n,width:o/a,height:r/n});break;default:r=(t,e,r,o)=>({x:(t-i)/n,y:(e-s)/a,width:r/n,height:o/a})}const o=[];for(let t=0,i=e.rangeCount;tt.stopPropagation()),{signal:i});const onClick=t=>{t.preventDefault();this.#a._uiManager.editAltText(this.#a);this.#Wt&&this.#a._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:this.#Xt}})};t.addEventListener("click",onClick,{capture:!0,signal:i});t.addEventListener("keydown",(e=>{if(e.target===t&&"Enter"===e.key){this.#Gt=!0;onClick(e)}}),{signal:i});await this.#Kt();return t}get#Xt(){return(this.#o?"added":null===this.#o&&this.guessedText&&"review")||"missing"}finish(){if(this.#Bt){this.#Bt.focus({focusVisible:this.#Gt});this.#Gt=!1}}isEmpty(){return this.#Wt?null===this.#o:!this.#o&&!this.#Nt}hasData(){return this.#Wt?null!==this.#o||!!this.#Vt:this.isEmpty()}get guessedText(){return this.#Vt}async setGuessedText(t){if(null===this.#o){this.#Vt=t;this.#jt=await AltText._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t});this.#Kt()}}toggleAltTextBadge(t=!1){if(this.#Wt&&!this.#o){if(!this.#$t){const t=this.#$t=document.createElement("div");t.className="noAltTextBadge";this.#a.div.append(t)}this.#$t.classList.toggle("hidden",!t)}else{this.#$t?.remove();this.#$t=null}}serialize(t){let e=this.#o;t||this.#Vt!==e||(e=this.#jt);return{altText:e,decorative:this.#Nt,guessedText:this.#Vt,textWithDisclaimer:this.#jt}}get data(){return{altText:this.#o,decorative:this.#Nt}}set data({altText:t,decorative:e,guessedText:i,textWithDisclaimer:s,cancel:n=!1}){if(i){this.#Vt=i;this.#jt=s}if(this.#o!==t||this.#Nt!==e){if(!n){this.#o=t;this.#Nt=e}this.#Kt()}}toggle(t=!1){if(this.#Bt){if(!t&&this.#Ut){clearTimeout(this.#Ut);this.#Ut=null}this.#Bt.disabled=!t}}shown(){this.#a._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:this.#Xt}})}destroy(){this.#Bt?.remove();this.#Bt=null;this.#Ht=null;this.#zt=null;this.#$t?.remove();this.#$t=null}async#Kt(){const t=this.#Bt;if(!t)return;if(this.#Wt){t.classList.toggle("done",!!this.#o);t.setAttribute("data-l10n-id",AltText.#qt[this.#Xt]);this.#Ht?.setAttribute("data-l10n-id",AltText.#qt[`${this.#Xt}-label`]);if(!this.#o){this.#zt?.remove();return}}else{if(!this.#o&&!this.#Nt){t.classList.remove("done");this.#zt?.remove();return}t.classList.add("done");t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let e=this.#zt;if(!e){this.#zt=e=document.createElement("span");e.className="tooltip";e.setAttribute("role","tooltip");e.id=`alt-text-tooltip-${this.#a.id}`;const i=100,s=this.#a._uiManager._signal;s.addEventListener("abort",(()=>{clearTimeout(this.#Ut);this.#Ut=null}),{once:!0});t.addEventListener("mouseenter",(()=>{this.#Ut=setTimeout((()=>{this.#Ut=null;this.#zt.classList.add("show");this.#a._reportTelemetry({action:"alt_text_tooltip"})}),i)}),{signal:s});t.addEventListener("mouseleave",(()=>{if(this.#Ut){clearTimeout(this.#Ut);this.#Ut=null}this.#zt?.classList.remove("show")}),{signal:s})}if(this.#Nt)e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip");else{e.removeAttribute("data-l10n-id");e.textContent=this.#o}e.parentNode||t.append(e);const i=this.#a.getImageForAltText();i?.setAttribute("aria-describedby",e.id)}}class TouchManager{#pt;#Yt=!1;#Qt=null;#Jt;#Zt;#te;#ee;#ie;#se=null;#ne;#ae=null;constructor({container:t,isPinchingDisabled:e=null,isPinchingStopped:i=null,onPinchStart:s=null,onPinching:n=null,onPinchEnd:a=null,signal:r}){this.#pt=t;this.#Qt=i;this.#Jt=e;this.#Zt=s;this.#te=n;this.#ee=a;this.#ne=new AbortController;this.#ie=AbortSignal.any([r,this.#ne.signal]);t.addEventListener("touchstart",this.#re.bind(this),{passive:!1,signal:this.#ie})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return shadow(this,"MIN_TOUCH_DISTANCE_TO_PINCH",35/(window.devicePixelRatio||1))}#re(t){if(this.#Jt?.()||t.touches.length<2)return;if(!this.#ae){this.#ae=new AbortController;const t=AbortSignal.any([this.#ie,this.#ae.signal]),e=this.#pt,i={signal:t,passive:!1};e.addEventListener("touchmove",this.#oe.bind(this),i);e.addEventListener("touchend",this.#le.bind(this),i);e.addEventListener("touchcancel",this.#le.bind(this),i);this.#Zt?.()}stopEvent(t);if(2!==t.touches.length||this.#Qt?.()){this.#se=null;return}let[e,i]=t.touches;e.identifier>i.identifier&&([e,i]=[i,e]);this.#se={touch0X:e.screenX,touch0Y:e.screenY,touch1X:i.screenX,touch1Y:i.screenY}}#oe(t){if(!this.#se||2!==t.touches.length)return;let[e,i]=t.touches;e.identifier>i.identifier&&([e,i]=[i,e]);const{screenX:s,screenY:n}=e,{screenX:a,screenY:r}=i,o=this.#se,{touch0X:l,touch0Y:h,touch1X:d,touch1Y:c}=o,u=d-l,p=c-h,g=a-s,m=r-n,f=Math.hypot(g,m)||1,b=Math.hypot(u,p)||1;if(!this.#Yt&&Math.abs(b-f)<=TouchManager.MIN_TOUCH_DISTANCE_TO_PINCH)return;o.touch0X=s;o.touch0Y=n;o.touch1X=a;o.touch1Y=r;t.preventDefault();if(!this.#Yt){this.#Yt=!0;return}const A=[(s+a)/2,(n+r)/2];this.#te?.(A,b,f)}#le(t){this.#ae.abort();this.#ae=null;this.#ee?.();if(this.#se){t.preventDefault();this.#se=null;this.#Yt=!1}}destroy(){this.#ne?.abort();this.#ne=null}}class AnnotationEditor{#he=null;#de=null;#o=null;#ce=!1;#ue=null;#pe="";#ge=!1;#me=null;#fe=null;#be=null;#Ae=null;#we="";#ve=!1;#ye=null;#xe=!1;#_e=!1;#Ee=!1;#Se=null;#Ce=0;#Te=0;#Me=null;#Pe=null;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nResizer=null;#De=!1;#ke=AnnotationEditor._zIndex++;static _borderLineWidth=-1;static _colorManager=new ColorManager;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){const t=AnnotationEditor.prototype._resizeWithKeyboard,e=AnnotationEditorUIManager.TRANSLATE_SMALL,i=AnnotationEditorUIManager.TRANSLATE_BIG;return shadow(this,"_resizerKeyboardManager",new KeyboardManager([[["ArrowLeft","mac+ArrowLeft"],t,{args:[-e,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-i,0]}],[["ArrowRight","mac+ArrowRight"],t,{args:[e,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[i,0]}],[["ArrowUp","mac+ArrowUp"],t,{args:[0,-e]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-i]}],[["ArrowDown","mac+ArrowDown"],t,{args:[0,e]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,i]}],[["Escape","mac+Escape"],AnnotationEditor.prototype._stopResizingWithKeyboard]]))}constructor(t){this.parent=t.parent;this.id=t.id;this.width=this.height=null;this.pageIndex=t.parent.pageIndex;this.name=t.name;this.div=null;this._uiManager=t.uiManager;this.annotationElementId=null;this._willKeepAspectRatio=!1;this._initialOptions.isCentered=t.isCentered;this._structTreeParentId=null;const{rotation:e,rawDims:{pageWidth:i,pageHeight:s,pageX:n,pageY:a}}=this.parent.viewport;this.rotation=e;this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360;this.pageDimensions=[i,s];this.pageTranslation=[n,a];const[r,o]=this.parentDimensions;this.x=t.x/r;this.y=t.y/o;this.isAttachedToDOM=!1;this.deleted=!1}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get isDrawer(){return!1}static get _defaultLineColor(){return shadow(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new FakeEditor({id:t.parent.getNextId(),parent:t.parent,uiManager:t._uiManager});e.annotationElementId=t.annotationElementId;e.deleted=!0;e._uiManager.addToAnnotationStorage(e)}static initialize(t,e){AnnotationEditor._l10n??=t;AnnotationEditor._l10nResizer||=Object.freeze({topLeft:"pdfjs-editor-resizer-top-left",topMiddle:"pdfjs-editor-resizer-top-middle",topRight:"pdfjs-editor-resizer-top-right",middleRight:"pdfjs-editor-resizer-middle-right",bottomRight:"pdfjs-editor-resizer-bottom-right",bottomMiddle:"pdfjs-editor-resizer-bottom-middle",bottomLeft:"pdfjs-editor-resizer-bottom-left",middleLeft:"pdfjs-editor-resizer-middle-left"});if(-1!==AnnotationEditor._borderLineWidth)return;const i=getComputedStyle(document.documentElement);AnnotationEditor._borderLineWidth=parseFloat(i.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){unreachable("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#De}set _isDraggable(t){this.#De=t;this.div?.classList.toggle("draggable",t)}get isEnterHandled(){return!0}center(){const[t,e]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*e/(2*t);this.y+=this.width*t/(2*e);break;case 180:this.x+=this.width/2;this.y+=this.height/2;break;case 270:this.x+=this.height*e/(2*t);this.y-=this.width*t/(2*e);break;default:this.x-=this.width/2;this.y-=this.height/2}this.fixAndSetPosition()}addCommands(t){this._uiManager.addCommands(t)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#ke}setParent(t){if(null!==t){this.pageIndex=t.pageIndex;this.pageDimensions=t.pageDimensions}else this.#Re();this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#ve?this.#ve=!1:this.parent.setSelected(this))}focusout(t){if(!this._focusEventsAllowed)return;if(!this.isAttachedToDOM)return;const e=t.relatedTarget;if(!e?.closest(`#${this.id}`)){t.preventDefault();this.parent?.isMultipleSelection||this.commitOrRemove()}}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(t,e,i,s){const[n,a]=this.parentDimensions;[i,s]=this.screenToPageTranslation(i,s);this.x=(t+i)/n;this.y=(e+s)/a;this.fixAndSetPosition()}#Ie([t,e],i,s){[i,s]=this.screenToPageTranslation(i,s);this.x+=i/t;this.y+=s/e;this._onTranslating(this.x,this.y);this.fixAndSetPosition()}translate(t,e){this.#Ie(this.parentDimensions,t,e)}translateInPage(t,e){this.#ye||=[this.x,this.y,this.width,this.height];this.#Ie(this.pageDimensions,t,e);this.div.scrollIntoView({block:"nearest"})}drag(t,e){this.#ye||=[this.x,this.y,this.width,this.height];const{div:i,parentDimensions:[s,n]}=this;this.x+=t/s;this.y+=e/n;if(this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:t,y:e}=this.div.getBoundingClientRect();if(this.parent.findNewParent(this,t,e)){this.x-=Math.floor(this.x);this.y-=Math.floor(this.y)}}let{x:a,y:r}=this;const[o,l]=this.getBaseTranslation();a+=o;r+=l;const{style:h}=i;h.left=`${(100*a).toFixed(2)}%`;h.top=`${(100*r).toFixed(2)}%`;this._onTranslating(a,r);i.scrollIntoView({block:"nearest"})}_onTranslating(t,e){}_onTranslated(t,e){}get _hasBeenMoved(){return!!this.#ye&&(this.#ye[0]!==this.x||this.#ye[1]!==this.y)}get _hasBeenResized(){return!!this.#ye&&(this.#ye[2]!==this.width||this.#ye[3]!==this.height)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:i}=AnnotationEditor,s=i/t,n=i/e;switch(this.rotation){case 90:return[-s,n];case 180:return[s,n];case 270:return[s,-n];default:return[-s,-n]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const{div:{style:e},pageDimensions:[i,s]}=this;let{x:n,y:a,width:r,height:o}=this;r*=i;o*=s;n*=i;a*=s;if(this._mustFixPosition)switch(t){case 0:n=Math.max(0,Math.min(i-r,n));a=Math.max(0,Math.min(s-o,a));break;case 90:n=Math.max(0,Math.min(i-o,n));a=Math.min(s,Math.max(r,a));break;case 180:n=Math.min(i,Math.max(r,n));a=Math.min(s,Math.max(o,a));break;case 270:n=Math.min(i,Math.max(o,n));a=Math.max(0,Math.min(s-r,a))}this.x=n/=i;this.y=a/=s;const[l,h]=this.getBaseTranslation();n+=l;a+=h;e.left=`${(100*n).toFixed(2)}%`;e.top=`${(100*a).toFixed(2)}%`;this.moveInDOM()}static#Fe(t,e,i){switch(i){case 90:return[e,-t];case 180:return[-t,-e];case 270:return[-e,t];default:return[t,e]}}screenToPageTranslation(t,e){return AnnotationEditor.#Fe(t,e,this.parentRotation)}pageTranslationToScreen(t,e){return AnnotationEditor.#Fe(t,e,360-this.parentRotation)}#Le(t){switch(t){case 90:{const[t,e]=this.pageDimensions;return[0,-t/e,e/t,0]}case 180:return[-1,0,0,-1];case 270:{const[t,e]=this.pageDimensions;return[0,t/e,-e/t,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:t,pageDimensions:[e,i]}=this;return[e*t,i*t]}setDims(t,e){const[i,s]=this.parentDimensions,{style:n}=this.div;n.width=`${(100*t/i).toFixed(2)}%`;this.#ge||(n.height=`${(100*e/s).toFixed(2)}%`)}fixDims(){const{style:t}=this.div,{height:e,width:i}=t,s=i.endsWith("%"),n=!this.#ge&&e.endsWith("%");if(s&&n)return;const[a,r]=this.parentDimensions;s||(t.width=`${(100*parseFloat(i)/a).toFixed(2)}%`);this.#ge||n||(t.height=`${(100*parseFloat(e)/r).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}#Oe(){if(this.#me)return;this.#me=document.createElement("div");this.#me.classList.add("resizers");const t=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],e=this._uiManager._signal;for(const i of t){const t=document.createElement("div");this.#me.append(t);t.classList.add("resizer",i);t.setAttribute("data-resizer-name",i);t.addEventListener("pointerdown",this.#Ne.bind(this,i),{signal:e});t.addEventListener("contextmenu",noContextMenu,{signal:e});t.tabIndex=-1}this.div.prepend(this.#me)}#Ne(t,e){e.preventDefault();const{isMac:i}=util_FeatureTest.platform;if(0!==e.button||e.ctrlKey&&i)return;this.#o?.toggle(!1);const s=this._isDraggable;this._isDraggable=!1;this.#fe=[e.screenX,e.screenY];const n=new AbortController,a=this._uiManager.combinedSignal(n);this.parent.togglePointerEvents(!1);window.addEventListener("pointermove",this.#Be.bind(this,t),{passive:!0,capture:!0,signal:a});window.addEventListener("touchmove",stopEvent,{passive:!1,signal:a});window.addEventListener("contextmenu",noContextMenu,{signal:a});this.#be={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const r=this.parent.div.style.cursor,o=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const pointerUpCallback=()=>{n.abort();this.parent.togglePointerEvents(!0);this.#o?.toggle(!0);this._isDraggable=s;this.parent.div.style.cursor=r;this.div.style.cursor=o;this.#He()};window.addEventListener("pointerup",pointerUpCallback,{signal:a});window.addEventListener("blur",pointerUpCallback,{signal:a})}#ze(t,e,i,s){this.width=i;this.height=s;this.x=t;this.y=e;const[n,a]=this.parentDimensions;this.setDims(n*i,a*s);this.fixAndSetPosition();this._onResized()}_onResized(){}#He(){if(!this.#be)return;const{savedX:t,savedY:e,savedWidth:i,savedHeight:s}=this.#be;this.#be=null;const n=this.x,a=this.y,r=this.width,o=this.height;n===t&&a===e&&r===i&&o===s||this.addCommands({cmd:this.#ze.bind(this,n,a,r,o),undo:this.#ze.bind(this,t,e,i,s),mustExec:!0})}static _round(t){return Math.round(1e4*t)/1e4}#Be(t,e){const[i,s]=this.parentDimensions,n=this.x,a=this.y,r=this.width,o=this.height,l=AnnotationEditor.MIN_SIZE/i,h=AnnotationEditor.MIN_SIZE/s,d=this.#Le(this.rotation),transf=(t,e)=>[d[0]*t+d[2]*e,d[1]*t+d[3]*e],c=this.#Le(360-this.rotation);let u,p,g=!1,m=!1;switch(t){case"topLeft":g=!0;u=(t,e)=>[0,0];p=(t,e)=>[t,e];break;case"topMiddle":u=(t,e)=>[t/2,0];p=(t,e)=>[t/2,e];break;case"topRight":g=!0;u=(t,e)=>[t,0];p=(t,e)=>[0,e];break;case"middleRight":m=!0;u=(t,e)=>[t,e/2];p=(t,e)=>[0,e/2];break;case"bottomRight":g=!0;u=(t,e)=>[t,e];p=(t,e)=>[0,0];break;case"bottomMiddle":u=(t,e)=>[t/2,e];p=(t,e)=>[t/2,0];break;case"bottomLeft":g=!0;u=(t,e)=>[0,e];p=(t,e)=>[t,0];break;case"middleLeft":m=!0;u=(t,e)=>[0,e/2];p=(t,e)=>[t,e/2]}const f=u(r,o),b=p(r,o);let A=transf(...b);const w=AnnotationEditor._round(n+A[0]),v=AnnotationEditor._round(a+A[1]);let y,x,_=1,E=1;if(e.fromKeyboard)({deltaX:y,deltaY:x}=e);else{const{screenX:t,screenY:i}=e,[s,n]=this.#fe;[y,x]=this.screenToPageTranslation(t-s,i-n);this.#fe[0]=t;this.#fe[1]=i}[y,x]=(S=y/i,C=x/s,[c[0]*S+c[2]*C,c[1]*S+c[3]*C]);var S,C;if(g){const t=Math.hypot(r,o);_=E=Math.max(Math.min(Math.hypot(b[0]-f[0]-y,b[1]-f[1]-x)/t,1/r,1/o),l/r,h/o)}else m?_=Math.max(l,Math.min(1,Math.abs(b[0]-f[0]-y)))/r:E=Math.max(h,Math.min(1,Math.abs(b[1]-f[1]-x)))/o;const T=AnnotationEditor._round(r*_),M=AnnotationEditor._round(o*E);A=transf(...p(T,M));const P=w-A[0],D=v-A[1];this.#ye||=[this.x,this.y,this.width,this.height];this.width=T;this.height=M;this.x=P;this.y=D;this.setDims(i*T,s*M);this.fixAndSetPosition();this._onResizing()}_onResizing(){}altTextFinish(){this.#o?.finish()}async addEditToolbar(){if(this._editToolbar||this.#_e)return this._editToolbar;this._editToolbar=new EditorToolbar(this);this.div.append(this._editToolbar.render());this.#o&&await this._editToolbar.addAltText(this.#o);return this._editToolbar}removeEditToolbar(){if(this._editToolbar){this._editToolbar.remove();this._editToolbar=null;this.#o?.destroy()}}addContainer(t){const e=this._editToolbar?.div;e?e.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){if(!this.#o){AltText.initialize(AnnotationEditor._l10n);this.#o=new AltText(this);if(this.#he){this.#o.data=this.#he;this.#he=null}await this.addEditToolbar()}}get altTextData(){return this.#o?.data}set altTextData(t){this.#o&&(this.#o.data=t)}get guessedAltText(){return this.#o?.guessedText}async setGuessedAltText(t){await(this.#o?.setGuessedText(t))}serializeAltText(t){return this.#o?.serialize(t)}hasAltText(){return!!this.#o&&!this.#o.isEmpty()}hasAltTextData(){return this.#o?.hasData()??!1}render(){this.div=document.createElement("div");this.div.setAttribute("data-editor-rotation",(360-this.rotation)%360);this.div.className=this.name;this.div.setAttribute("id",this.id);this.div.tabIndex=this.#ce?-1:0;this._isVisible||this.div.classList.add("hidden");this.setInForeground();this.#Ue();const[t,e]=this.parentDimensions;if(this.parentRotation%180!=0){this.div.style.maxWidth=`${(100*e/t).toFixed(2)}%`;this.div.style.maxHeight=`${(100*t/e).toFixed(2)}%`}const[i,s]=this.getInitialTranslation();this.translate(i,s);bindEvents(this,this.div,["pointerdown"]);this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#Pe||=new TouchManager({container:this.div,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#Ge.bind(this),onPinching:this.#$e.bind(this),onPinchEnd:this.#Ve.bind(this),signal:this._uiManager._signal}));this._uiManager._editorUndoBar?.hide();return this.div}#Ge(){this.#be={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};this.#o?.toggle(!1);this.parent.togglePointerEvents(!1)}#$e(t,e,i){let s=i/e*.7+1-.7;if(1===s)return;const n=this.#Le(this.rotation),transf=(t,e)=>[n[0]*t+n[2]*e,n[1]*t+n[3]*e],[a,r]=this.parentDimensions,o=this.x,l=this.y,h=this.width,d=this.height,c=AnnotationEditor.MIN_SIZE/a,u=AnnotationEditor.MIN_SIZE/r;s=Math.max(Math.min(s,1/h,1/d),c/h,u/d);const p=AnnotationEditor._round(h*s),g=AnnotationEditor._round(d*s);if(p===h&&g===d)return;this.#ye||=[o,l,h,d];const m=transf(h/2,d/2),f=AnnotationEditor._round(o+m[0]),b=AnnotationEditor._round(l+m[1]),A=transf(p/2,g/2);this.x=f-A[0];this.y=b-A[1];this.width=p;this.height=g;this.setDims(a*p,r*g);this.fixAndSetPosition();this._onResizing()}#Ve(){this.#o?.toggle(!0);this.parent.togglePointerEvents(!0);this.#He()}pointerdown(t){const{isMac:e}=util_FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)t.preventDefault();else{this.#ve=!0;this._isDraggable?this.#je(t):this.#We(t)}}get isSelected(){return this._uiManager.isSelected(this)}#We(t){const{isMac:e}=util_FeatureTest.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)}#je(t){const{isSelected:e}=this;this._uiManager.setUpDragSession();let i=!1;const s=new AbortController,n=this._uiManager.combinedSignal(s),a={capture:!0,passive:!1,signal:n},cancelDrag=t=>{s.abort();this.#ue=null;this.#ve=!1;this._uiManager.endDragSession()||this.#We(t);i&&this._onStopDragging()};if(e){this.#Ce=t.clientX;this.#Te=t.clientY;this.#ue=t.pointerId;this.#pe=t.pointerType;window.addEventListener("pointermove",(t=>{if(!i){i=!0;this._onStartDragging()}const{clientX:e,clientY:s,pointerId:n}=t;if(n!==this.#ue){stopEvent(t);return}const[a,r]=this.screenToPageTranslation(e-this.#Ce,s-this.#Te);this.#Ce=e;this.#Te=s;this._uiManager.dragSelectedEditors(a,r)}),a);window.addEventListener("touchmove",stopEvent,a);window.addEventListener("pointerdown",(t=>{t.pointerType===this.#pe&&(this.#Pe||t.isPrimary)&&cancelDrag(t);stopEvent(t)}),a)}const pointerUpCallback=t=>{this.#ue&&this.#ue!==t.pointerId?stopEvent(t):cancelDrag(t)};window.addEventListener("pointerup",pointerUpCallback,{signal:n});window.addEventListener("blur",pointerUpCallback,{signal:n})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#Se&&clearTimeout(this.#Se);this.#Se=setTimeout((()=>{this.#Se=null;this.parent?.moveEditorInDOM(this)}),0)}_setParentAndPosition(t,e,i){t.changeParent(this);this.x=e;this.y=i;this.fixAndSetPosition();this._onTranslated()}getRect(t,e,i=this.rotation){const s=this.parentScale,[n,a]=this.pageDimensions,[r,o]=this.pageTranslation,l=t/s,h=e/s,d=this.x*n,c=this.y*a,u=this.width*n,p=this.height*a;switch(i){case 0:return[d+l+r,a-c-h-p+o,d+l+u+r,a-c-h+o];case 90:return[d+h+r,a-c+l+o,d+h+p+r,a-c+l+u+o];case 180:return[d-l-u+r,a-c+h+o,d-l+r,a-c+h+p+o];case 270:return[d-h-p+r,a-c-l-u+o,d-h+r,a-c-l+o];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,e){const[i,s,n,a]=t,r=n-i,o=a-s;switch(this.rotation){case 0:return[i,e-a,r,o];case 90:return[i,e-s,o,r];case 180:return[n,e-s,r,o];case 270:return[n,e-a,o,r];default:throw new Error("Invalid rotation")}}onceAdded(t){}isEmpty(){return!1}enableEditMode(){this.#_e=!0}disableEditMode(){this.#_e=!1}isInEditMode(){return this.#_e}shouldGetKeyboardEvents(){return this.#Ee}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){const{top:t,left:e,bottom:i,right:s}=this.getClientDimensions(),{innerHeight:n,innerWidth:a}=window;return e0&&t0}#Ue(){if(this.#Ae||!this.div)return;this.#Ae=new AbortController;const t=this._uiManager.combinedSignal(this.#Ae);this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t});this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})}rebuild(){this.#Ue()}rotate(t){}resize(){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||""}}serialize(t=!1,e=null){unreachable("An editor must be serializable")}static async deserialize(t,e,i){const s=new this.prototype.constructor({parent:e,id:e.getNextId(),uiManager:i});s.rotation=t.rotation;s.#he=t.accessibilityData;const[n,a]=s.pageDimensions,[r,o,l,h]=s.getRectInCurrentCoords(t.rect,a);s.x=r/n;s.y=o/a;s.width=l/n;s.height=h/a;return s}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||null!==this.serialize())}remove(){this.#Ae?.abort();this.#Ae=null;this.isEmpty()||this.commit();this.parent?this.parent.remove(this):this._uiManager.removeEditor(this);if(this.#Se){clearTimeout(this.#Se);this.#Se=null}this.#Re();this.removeEditToolbar();if(this.#Me){for(const t of this.#Me.values())clearTimeout(t);this.#Me=null}this.parent=null;this.#Pe?.destroy();this.#Pe=null}get isResizable(){return!1}makeResizable(){if(this.isResizable){this.#Oe();this.#me.classList.remove("hidden");bindEvents(this,this.div,["keydown"])}}get toolbarPosition(){return null}keydown(t){if(!this.isResizable||t.target!==this.div||"Enter"!==t.key)return;this._uiManager.setSelected(this);this.#be={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const e=this.#me.children;if(!this.#de){this.#de=Array.from(e);const t=this.#qe.bind(this),i=this.#Xe.bind(this),s=this._uiManager._signal;for(const e of this.#de){const n=e.getAttribute("data-resizer-name");e.setAttribute("role","spinbutton");e.addEventListener("keydown",t,{signal:s});e.addEventListener("blur",i,{signal:s});e.addEventListener("focus",this.#Ke.bind(this,n),{signal:s});e.setAttribute("data-l10n-id",AnnotationEditor._l10nResizer[n])}}const i=this.#de[0];let s=0;for(const t of e){if(t===i)break;s++}const n=(360-this.rotation+this.parentRotation)%360/90*(this.#de.length/4);if(n!==s){if(ns)for(let t=0;t{this.div?.classList.contains("selectedEditor")&&this._editToolbar?.show()}))}unselect(){this.#me?.classList.add("hidden");this.div?.classList.remove("selectedEditor");this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0});this._editToolbar?.hide();this.#o?.toggleAltTextBadge(!0)}updateParams(t,e){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return this.#xe}set isEditing(t){this.#xe=t;if(this.parent)if(t){this.parent.setSelected(this);this.parent.setActiveEditor(this)}else this.parent.setActiveEditor(null)}setAspectRatio(t,e){this.#ge=!0;const i=t/e,{style:s}=this.div;s.aspectRatio=i;s.height="auto"}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(t,e=!1){if(e){this.#Me||=new Map;const{action:e}=t;let i=this.#Me.get(e);i&&clearTimeout(i);i=setTimeout((()=>{this._reportTelemetry(t);this.#Me.delete(e);0===this.#Me.size&&(this.#Me=null)}),AnnotationEditor._telemetryTimeout);this.#Me.set(e,i)}else{t.type||=this.editorType;this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:t}})}}show(t=this._isVisible){this.div.classList.toggle("hidden",!t);this._isVisible=t}enable(){this.div&&(this.div.tabIndex=0);this.#ce=!1}disable(){this.div&&(this.div.tabIndex=-1);this.#ce=!0}renderAnnotationElement(t){let e=t.container.querySelector(".annotationContent");if(e){if("CANVAS"===e.nodeName){const t=e;e=document.createElement("div");e.classList.add("annotationContent",this.editorType);t.before(e)}}else{e=document.createElement("div");e.classList.add("annotationContent",this.editorType);t.container.prepend(e)}return e}resetAnnotationElement(t){const{firstChild:e}=t.container;"DIV"===e?.nodeName&&e.classList.contains("annotationContent")&&e.remove()}}class FakeEditor extends AnnotationEditor{constructor(t){super(t);this.annotationElementId=t.annotationElementId;this.deleted=!0}serialize(){return this.serializeDeleted()}}const st=3285377520,nt=4294901760,at=65535;class MurmurHash3_64{constructor(t){this.h1=t?4294967295&t:st;this.h2=t?4294967295&t:st}update(t){let e,i;if("string"==typeof t){e=new Uint8Array(2*t.length);i=0;for(let s=0,n=t.length;s>>8;e[i++]=255&n}}}else{if(!ArrayBuffer.isView(t))throw new Error("Invalid data format, must be a string or TypedArray.");e=t.slice();i=e.byteLength}const s=i>>2,n=i-4*s,a=new Uint32Array(e.buffer,0,s);let r=0,o=0,l=this.h1,h=this.h2;const d=3432918353,c=461845907,u=11601,p=13715;for(let t=0;t>>17;r=r*c&nt|r*p&at;l^=r;l=l<<13|l>>>19;l=5*l+3864292196}else{o=a[t];o=o*d&nt|o*u&at;o=o<<15|o>>>17;o=o*c&nt|o*p&at;h^=o;h=h<<13|h>>>19;h=5*h+3864292196}r=0;switch(n){case 3:r^=e[4*s+2]<<16;case 2:r^=e[4*s+1]<<8;case 1:r^=e[4*s];r=r*d&nt|r*u&at;r=r<<15|r>>>17;r=r*c&nt|r*p&at;1&s?l^=r:h^=r}this.h1=l;this.h2=h}hexdigest(){let t=this.h1,e=this.h2;t^=e>>>1;t=3981806797*t&nt|36045*t&at;e=4283543511*e&nt|(2950163797*(e<<16|t>>>16)&nt)>>>16;t^=e>>>1;t=444984403*t&nt|60499*t&at;e=3301882366*e&nt|(3120437893*(e<<16|t>>>16)&nt)>>>16;t^=e>>>1;return(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const rt=Object.freeze({map:null,hash:"",transfer:void 0});class AnnotationStorage{#Qe=!1;#Je=null;#Ze=new Map;constructor(){this.onSetModified=null;this.onResetModified=null;this.onAnnotationEditor=null}getValue(t,e){const i=this.#Ze.get(t);return void 0===i?e:Object.assign(e,i)}getRawValue(t){return this.#Ze.get(t)}remove(t){this.#Ze.delete(t);0===this.#Ze.size&&this.resetModified();if("function"==typeof this.onAnnotationEditor){for(const t of this.#Ze.values())if(t instanceof AnnotationEditor)return;this.onAnnotationEditor(null)}}setValue(t,e){const i=this.#Ze.get(t);let s=!1;if(void 0!==i){for(const[t,n]of Object.entries(e))if(i[t]!==n){s=!0;i[t]=n}}else{s=!0;this.#Ze.set(t,e)}s&&this.#ti();e instanceof AnnotationEditor&&"function"==typeof this.onAnnotationEditor&&this.onAnnotationEditor(e.constructor._type)}has(t){return this.#Ze.has(t)}getAll(){return this.#Ze.size>0?objectFromMap(this.#Ze):null}setAll(t){for(const[e,i]of Object.entries(t))this.setValue(e,i)}get size(){return this.#Ze.size}#ti(){if(!this.#Qe){this.#Qe=!0;"function"==typeof this.onSetModified&&this.onSetModified()}}resetModified(){if(this.#Qe){this.#Qe=!1;"function"==typeof this.onResetModified&&this.onResetModified()}}get print(){return new PrintAnnotationStorage(this)}get serializable(){if(0===this.#Ze.size)return rt;const t=new Map,e=new MurmurHash3_64,i=[],s=Object.create(null);let n=!1;for(const[i,a]of this.#Ze){const r=a instanceof AnnotationEditor?a.serialize(!1,s):a;if(r){t.set(i,r);e.update(`${i}:${JSON.stringify(r)}`);n||=!!r.bitmap}}if(n)for(const e of t.values())e.bitmap&&i.push(e.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:i}:rt}get editorStats(){let t=null;const e=new Map;for(const i of this.#Ze.values()){if(!(i instanceof AnnotationEditor))continue;const s=i.telemetryFinalData;if(!s)continue;const{type:n}=s;e.has(n)||e.set(n,Object.getPrototypeOf(i).constructor);t||=Object.create(null);const a=t[n]||=new Map;for(const[t,e]of Object.entries(s)){if("type"===t)continue;let i=a.get(t);if(!i){i=new Map;a.set(t,i)}const s=i.get(e)??0;i.set(e,s+1)}}for(const[i,s]of e)t[i]=s.computeTelemetryFinalData(t[i]);return t}resetModifiedIds(){this.#Je=null}get modifiedIds(){if(this.#Je)return this.#Je;const t=[];for(const e of this.#Ze.values())e instanceof AnnotationEditor&&e.annotationElementId&&e.serialize()&&t.push(e.annotationElementId);return this.#Je={ids:new Set(t),hash:t.join(",")}}}class PrintAnnotationStorage extends AnnotationStorage{#ei;constructor(t){super();const{map:e,hash:i,transfer:s}=t.serializable,n=structuredClone(e,s?{transfer:s}:null);this.#ei={map:n,hash:i,transfer:s}}get print(){unreachable("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#ei}get modifiedIds(){return shadow(this,"modifiedIds",{ids:new Set,hash:""})}}class FontLoader{#ii=new Set;constructor({ownerDocument:t=globalThis.document,styleElement:e=null}){this._document=t;this.nativeFontFaces=new Set;this.styleElement=null;this.loadingRequests=[];this.loadTestFontId=0}addNativeFontFace(t){this.nativeFontFaces.add(t);this._document.fonts.add(t)}removeNativeFontFace(t){this.nativeFontFaces.delete(t);this._document.fonts.delete(t)}insertRule(t){if(!this.styleElement){this.styleElement=this._document.createElement("style");this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement)}const e=this.styleElement.sheet;e.insertRule(t,e.cssRules.length)}clear(){for(const t of this.nativeFontFaces)this._document.fonts.delete(t);this.nativeFontFaces.clear();this.#ii.clear();if(this.styleElement){this.styleElement.remove();this.styleElement=null}}async loadSystemFont({systemFontInfo:t,_inspectFont:e}){if(t&&!this.#ii.has(t.loadedName)){assert(!this.disableFontFace,"loadSystemFont shouldn't be called when `disableFontFace` is set.");if(this.isFontLoadingAPISupported){const{loadedName:i,src:s,style:n}=t,a=new FontFace(i,s,n);this.addNativeFontFace(a);try{await a.load();this.#ii.add(i);e?.(t)}catch{warn(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`);this.removeNativeFontFace(a)}}else unreachable("Not implemented: loadSystemFont without the Font Loading API.")}}async bind(t){if(t.attached||t.missingFile&&!t.systemFontInfo)return;t.attached=!0;if(t.systemFontInfo){await this.loadSystemFont(t);return}if(this.isFontLoadingAPISupported){const e=t.createNativeFontFace();if(e){this.addNativeFontFace(e);try{await e.loaded}catch(i){warn(`Failed to load font '${e.family}': '${i}'.`);t.disableFontFace=!0;throw i}}return}const e=t.createFontFaceRule();if(e){this.insertRule(e);if(this.isSyncFontLoadingSupported)return;await new Promise((e=>{const i=this._queueLoadingCallback(e);this._prepareFontLoadEvent(t,i)}))}}get isFontLoadingAPISupported(){return shadow(this,"isFontLoadingAPISupported",!!this._document?.fonts)}get isSyncFontLoadingSupported(){let t=!1;(e||"undefined"!=typeof navigator&&"string"==typeof navigator?.userAgent&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(t=!0);return shadow(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){const{loadingRequests:e}=this,i={done:!1,complete:function completeRequest(){assert(!i.done,"completeRequest() cannot be called twice.");i.done=!0;for(;e.length>0&&e[0].done;){const t=e.shift();setTimeout(t.callback,0)}},callback:t};e.push(i);return i}get _loadTestFont(){return shadow(this,"_loadTestFont",atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA=="))}_prepareFontLoadEvent(t,e){function int32(t,e){return t.charCodeAt(e)<<24|t.charCodeAt(e+1)<<16|t.charCodeAt(e+2)<<8|255&t.charCodeAt(e+3)}function spliceString(t,e,i,s){return t.substring(0,e)+s+t.substring(e+i)}let i,s;const n=this._document.createElement("canvas");n.width=1;n.height=1;const a=n.getContext("2d");let r=0;const o=`lt${Date.now()}${this.loadTestFontId++}`;let l=this._loadTestFont;l=spliceString(l,976,o.length,o);const h=1482184792;let d=int32(l,16);for(i=0,s=o.length-3;i>24&255,t>>16&255,t>>8&255,255&t)}(d));const c=`@font-face {font-family:"${o}";src:${`url(data:font/opentype;base64,${btoa(l)});`}}`;this.insertRule(c);const u=this._document.createElement("div");u.style.visibility="hidden";u.style.width=u.style.height="10px";u.style.position="absolute";u.style.top=u.style.left="0px";for(const e of[t.loadedName,o]){const t=this._document.createElement("span");t.textContent="Hi";t.style.fontFamily=e;u.append(t)}this._document.body.append(u);!function isFontReady(t,e){if(++r>30){warn("Load test font never loaded.");e();return}a.font="30px "+t;a.fillText(".",0,20);a.getImageData(0,0,1,1).data[3]>0?e():setTimeout(isFontReady.bind(null,t,e))}(o,(()=>{u.remove();e.complete()}))}}class FontFaceObject{constructor(t,{disableFontFace:e=!1,fontExtraProperties:i=!1,inspectFont:s=null}){this.compiledGlyphs=Object.create(null);for(const e in t)this[e]=t[e];this.disableFontFace=!0===e;this.fontExtraProperties=!0===i;this._inspectFont=s}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let t;if(this.cssFontInfo){const e={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(e.style=`oblique ${this.cssFontInfo.italicAngle}deg`);t=new FontFace(this.cssFontInfo.fontFamily,this.data,e)}else t=new FontFace(this.loadedName,this.data,{});this._inspectFont?.(this);return t}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;const t=`url(data:${this.mimetype};base64,${function toBase64Util(t){return Uint8Array.prototype.toBase64?t.toBase64():btoa(bytesToString(t))}(this.data)});`;let e;if(this.cssFontInfo){let i=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(i+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`);e=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${i}src:${t}}`}else e=`@font-face {font-family:"${this.loadedName}";src:${t}}`;this._inspectFont?.(this,t);return e}getPathGenerator(t,e){if(void 0!==this.compiledGlyphs[e])return this.compiledGlyphs[e];const i=this.loadedName+"_path_"+e;let s;try{s=t.get(i)}catch(t){warn(`getPathGenerator - ignoring character: "${t}".`)}const n=new Path2D(s||"");this.fontExtraProperties||t.delete(i);return this.compiledGlyphs[e]=n}}const ot=1,lt=2,ht=1,dt=2,ct=3,ut=4,pt=5,gt=6,mt=7,ft=8;function onFn(){}function wrapReason(t){if(t instanceof AbortException||t instanceof InvalidPDFException||t instanceof MissingPDFException||t instanceof PasswordException||t instanceof UnexpectedResponseException||t instanceof UnknownErrorException)return t;t instanceof Error||"object"==typeof t&&null!==t||unreachable('wrapReason: Expected "reason" to be a (possibly cloned) Error.');switch(t.name){case"AbortException":return new AbortException(t.message);case"InvalidPDFException":return new InvalidPDFException(t.message);case"MissingPDFException":return new MissingPDFException(t.message);case"PasswordException":return new PasswordException(t.message,t.code);case"UnexpectedResponseException":return new UnexpectedResponseException(t.message,t.status);case"UnknownErrorException":return new UnknownErrorException(t.message,t.details)}return new UnknownErrorException(t.message,t.toString())}class MessageHandler{#si=new AbortController;constructor(t,e,i){this.sourceName=t;this.targetName=e;this.comObj=i;this.callbackId=1;this.streamId=1;this.streamSinks=Object.create(null);this.streamControllers=Object.create(null);this.callbackCapabilities=Object.create(null);this.actionHandler=Object.create(null);i.addEventListener("message",this.#ni.bind(this),{signal:this.#si.signal})}#ni({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream){this.#ai(t);return}if(t.callback){const e=t.callbackId,i=this.callbackCapabilities[e];if(!i)throw new Error(`Cannot resolve callback ${e}`);delete this.callbackCapabilities[e];if(t.callback===ot)i.resolve(t.data);else{if(t.callback!==lt)throw new Error("Unexpected callback case");i.reject(wrapReason(t.reason))}return}const e=this.actionHandler[t.action];if(!e)throw new Error(`Unknown action from worker: ${t.action}`);if(t.callbackId){const i=this.sourceName,s=t.sourceName,n=this.comObj;Promise.try(e,t.data).then((function(e){n.postMessage({sourceName:i,targetName:s,callback:ot,callbackId:t.callbackId,data:e})}),(function(e){n.postMessage({sourceName:i,targetName:s,callback:lt,callbackId:t.callbackId,reason:wrapReason(e)})}))}else t.streamId?this.#ri(t):e(t.data)}on(t,e){const i=this.actionHandler;if(i[t])throw new Error(`There is already an actionName called "${t}"`);i[t]=e}send(t,e,i){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,data:e},i)}sendWithPromise(t,e,i){const s=this.callbackId++,n=Promise.withResolvers();this.callbackCapabilities[s]=n;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:s,data:e},i)}catch(t){n.reject(t)}return n.promise}sendWithStream(t,e,i,s){const n=this.streamId++,a=this.sourceName,r=this.targetName,o=this.comObj;return new ReadableStream({start:i=>{const l=Promise.withResolvers();this.streamControllers[n]={controller:i,startCall:l,pullCall:null,cancelCall:null,isClosed:!1};o.postMessage({sourceName:a,targetName:r,action:t,streamId:n,data:e,desiredSize:i.desiredSize},s);return l.promise},pull:t=>{const e=Promise.withResolvers();this.streamControllers[n].pullCall=e;o.postMessage({sourceName:a,targetName:r,stream:gt,streamId:n,desiredSize:t.desiredSize});return e.promise},cancel:t=>{assert(t instanceof Error,"cancel must have a valid reason");const e=Promise.withResolvers();this.streamControllers[n].cancelCall=e;this.streamControllers[n].isClosed=!0;o.postMessage({sourceName:a,targetName:r,stream:ht,streamId:n,reason:wrapReason(t)});return e.promise}},i)}#ri(t){const e=t.streamId,i=this.sourceName,s=t.sourceName,n=this.comObj,a=this,r=this.actionHandler[t.action],o={enqueue(t,a=1,r){if(this.isCancelled)return;const o=this.desiredSize;this.desiredSize-=a;if(o>0&&this.desiredSize<=0){this.sinkCapability=Promise.withResolvers();this.ready=this.sinkCapability.promise}n.postMessage({sourceName:i,targetName:s,stream:ut,streamId:e,chunk:t},r)},close(){if(!this.isCancelled){this.isCancelled=!0;n.postMessage({sourceName:i,targetName:s,stream:ct,streamId:e});delete a.streamSinks[e]}},error(t){assert(t instanceof Error,"error must have a valid reason");if(!this.isCancelled){this.isCancelled=!0;n.postMessage({sourceName:i,targetName:s,stream:pt,streamId:e,reason:wrapReason(t)})}},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};o.sinkCapability.resolve();o.ready=o.sinkCapability.promise;this.streamSinks[e]=o;Promise.try(r,t.data,o).then((function(){n.postMessage({sourceName:i,targetName:s,stream:ft,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:i,targetName:s,stream:ft,streamId:e,reason:wrapReason(t)})}))}#ai(t){const e=t.streamId,i=this.sourceName,s=t.sourceName,n=this.comObj,a=this.streamControllers[e],r=this.streamSinks[e];switch(t.stream){case ft:t.success?a.startCall.resolve():a.startCall.reject(wrapReason(t.reason));break;case mt:t.success?a.pullCall.resolve():a.pullCall.reject(wrapReason(t.reason));break;case gt:if(!r){n.postMessage({sourceName:i,targetName:s,stream:mt,streamId:e,success:!0});break}r.desiredSize<=0&&t.desiredSize>0&&r.sinkCapability.resolve();r.desiredSize=t.desiredSize;Promise.try(r.onPull||onFn).then((function(){n.postMessage({sourceName:i,targetName:s,stream:mt,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:i,targetName:s,stream:mt,streamId:e,reason:wrapReason(t)})}));break;case ut:assert(a,"enqueue should have stream controller");if(a.isClosed)break;a.controller.enqueue(t.chunk);break;case ct:assert(a,"close should have stream controller");if(a.isClosed)break;a.isClosed=!0;a.controller.close();this.#oi(a,e);break;case pt:assert(a,"error should have stream controller");a.controller.error(wrapReason(t.reason));this.#oi(a,e);break;case dt:t.success?a.cancelCall.resolve():a.cancelCall.reject(wrapReason(t.reason));this.#oi(a,e);break;case ht:if(!r)break;const o=wrapReason(t.reason);Promise.try(r.onCancel||onFn,o).then((function(){n.postMessage({sourceName:i,targetName:s,stream:dt,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:i,targetName:s,stream:dt,streamId:e,reason:wrapReason(t)})}));r.sinkCapability.reject(o);r.isCancelled=!0;delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}}async#oi(t,e){await Promise.allSettled([t.startCall?.promise,t.pullCall?.promise,t.cancelCall?.promise]);delete this.streamControllers[e]}destroy(){this.#si?.abort();this.#si=null}}class BaseCanvasFactory{#li=!1;constructor({enableHWA:t=!1}){this.#li=t}create(t,e){if(t<=0||e<=0)throw new Error("Invalid canvas size");const i=this._createCanvas(t,e);return{canvas:i,context:i.getContext("2d",{willReadFrequently:!this.#li})}}reset(t,e,i){if(!t.canvas)throw new Error("Canvas is not specified");if(e<=0||i<=0)throw new Error("Invalid canvas size");t.canvas.width=e;t.canvas.height=i}destroy(t){if(!t.canvas)throw new Error("Canvas is not specified");t.canvas.width=0;t.canvas.height=0;t.canvas=null;t.context=null}_createCanvas(t,e){unreachable("Abstract method `_createCanvas` called.")}}class BaseCMapReaderFactory{constructor({baseUrl:t=null,isCompressed:e=!0}){this.baseUrl=t;this.isCompressed=e}async fetch({name:t}){if(!this.baseUrl)throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.");if(!t)throw new Error("CMap name must be specified.");const e=this.baseUrl+t+(this.isCompressed?".bcmap":"");return this._fetch(e).then((t=>({cMapData:t,isCompressed:this.isCompressed}))).catch((t=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${e}`)}))}async _fetch(t){unreachable("Abstract method `_fetch` called.")}}class DOMCMapReaderFactory extends BaseCMapReaderFactory{async _fetch(t){const e=await fetchData(t,this.isCompressed?"arraybuffer":"text");return e instanceof ArrayBuffer?new Uint8Array(e):stringToBytes(e)}}class BaseFilterFactory{addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addHighlightHCMFilter(t,e,i,s,n){return"none"}destroy(t=!1){}}class BaseStandardFontDataFactory{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");if(!t)throw new Error("Font filename must be specified.");const e=`${this.baseUrl}${t}`;return this._fetch(e).catch((t=>{throw new Error(`Unable to load font data at: ${e}`)}))}async _fetch(t){unreachable("Abstract method `_fetch` called.")}}class DOMStandardFontDataFactory extends BaseStandardFontDataFactory{async _fetch(t){const e=await fetchData(t,"arraybuffer");return new Uint8Array(e)}}e&&warn("Please use the `legacy` build in Node.js environments.");async function node_utils_fetchData(t){const e=process.getBuiltinModule("fs"),i=await e.promises.readFile(t);return new Uint8Array(i)}const bt="Fill",At="Stroke",wt="Shading";function applyBoundingBox(t,e){if(!e)return;const i=e[2]-e[0],s=e[3]-e[1],n=new Path2D;n.rect(e[0],e[1],i,s);t.clip(n)}class BaseShadingPattern{getPattern(){unreachable("Abstract method `getPattern` called.")}}class RadialAxialShadingPattern extends BaseShadingPattern{constructor(t){super();this._type=t[1];this._bbox=t[2];this._colorStops=t[3];this._p0=t[4];this._p1=t[5];this._r0=t[6];this._r1=t[7];this.matrix=null}_createGradient(t){let e;"axial"===this._type?e=t.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):"radial"===this._type&&(e=t.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(const t of this._colorStops)e.addColorStop(t[0],t[1]);return e}getPattern(t,e,i,s){let n;if(s===At||s===bt){const a=e.current.getClippedPathBoundingBox(s,getCurrentTransform(t))||[0,0,0,0],r=Math.ceil(a[2]-a[0])||1,o=Math.ceil(a[3]-a[1])||1,l=e.cachedCanvases.getCanvas("pattern",r,o),h=l.context;h.clearRect(0,0,h.canvas.width,h.canvas.height);h.beginPath();h.rect(0,0,h.canvas.width,h.canvas.height);h.translate(-a[0],-a[1]);i=Util.transform(i,[1,0,0,1,a[0],a[1]]);h.transform(...e.baseTransform);this.matrix&&h.transform(...this.matrix);applyBoundingBox(h,this._bbox);h.fillStyle=this._createGradient(h);h.fill();n=t.createPattern(l.canvas,"no-repeat");const d=new DOMMatrix(i);n.setTransform(d)}else{applyBoundingBox(t,this._bbox);n=this._createGradient(t)}return n}}function drawTriangle(t,e,i,s,n,a,r,o){const l=e.coords,h=e.colors,d=t.data,c=4*t.width;let u;if(l[i+1]>l[s+1]){u=i;i=s;s=u;u=a;a=r;r=u}if(l[s+1]>l[n+1]){u=s;s=n;n=u;u=r;r=o;o=u}if(l[i+1]>l[s+1]){u=i;i=s;s=u;u=a;a=r;r=u}const p=(l[i]+e.offsetX)*e.scaleX,g=(l[i+1]+e.offsetY)*e.scaleY,m=(l[s]+e.offsetX)*e.scaleX,f=(l[s+1]+e.offsetY)*e.scaleY,b=(l[n]+e.offsetX)*e.scaleX,A=(l[n+1]+e.offsetY)*e.scaleY;if(g>=A)return;const w=h[a],v=h[a+1],y=h[a+2],x=h[r],_=h[r+1],E=h[r+2],S=h[o],C=h[o+1],T=h[o+2],M=Math.round(g),P=Math.round(A);let D,k,R,I,F,L,O,N;for(let t=M;t<=P;t++){if(tA?1:f===A?0:(f-t)/(f-A);D=m-(m-b)*e;k=x-(x-S)*e;R=_-(_-C)*e;I=E-(E-T)*e}let e;e=tA?1:(g-t)/(g-A);F=p-(p-b)*e;L=w-(w-S)*e;O=v-(v-C)*e;N=y-(y-T)*e;const i=Math.round(Math.min(D,F)),s=Math.round(Math.max(D,F));let n=c*t+4*i;for(let t=i;t<=s;t++){e=(D-t)/(D-F);e<0?e=0:e>1&&(e=1);d[n++]=k-(k-L)*e|0;d[n++]=R-(R-O)*e|0;d[n++]=I-(I-N)*e|0;d[n++]=255}}}function drawFigure(t,e,i){const s=e.coords,n=e.colors;let a,r;switch(e.type){case"lattice":const o=e.verticesPerRow,l=Math.floor(s.length/o)-1,h=o-1;for(a=0;a=Math.ceil(p*b)?w=o:y=!0;E>=Math.ceil(g*A)?v=l:x=!0;const S=this.getSizeAndScale(w,this.ctx.canvas.width,b),C=this.getSizeAndScale(v,this.ctx.canvas.height,A),T=t.cachedCanvases.getCanvas("pattern",S.size,C.size),M=T.context,P=r.createCanvasGraphics(M);P.groupLevel=t.groupLevel;this.setFillAndStrokeStyleToContext(P,s,a);M.translate(-S.scale*h,-C.scale*d);P.transform(S.scale,0,0,C.scale,0,0);M.save();this.clipBbox(P,h,d,c,u);P.baseTransform=getCurrentTransform(P.ctx);P.executeOperatorList(i);P.endDrawing();M.restore();if(y||x){const e=T.canvas;y&&(w=o);x&&(v=l);const i=this.getSizeAndScale(w,this.ctx.canvas.width,b),s=this.getSizeAndScale(v,this.ctx.canvas.height,A),n=i.size,a=s.size,r=t.cachedCanvases.getCanvas("pattern-workaround",n,a),c=r.context,u=y?Math.floor(p/o):0,m=x?Math.floor(g/l):0;for(let t=0;t<=u;t++)for(let i=0;i<=m;i++)c.drawImage(e,n*t,a*i,n,a,0,0,n,a);return{canvas:r.canvas,scaleX:i.scale,scaleY:s.scale,offsetX:h,offsetY:d}}return{canvas:T.canvas,scaleX:S.scale,scaleY:C.scale,offsetX:h,offsetY:d}}getSizeAndScale(t,e,i){const s=Math.max(TilingPattern.MAX_PATTERN_SIZE,e);let n=Math.ceil(t*i);n>=s?n=s:i=n/t;return{scale:i,size:n}}clipBbox(t,e,i,s,n){const a=s-e,r=n-i;t.ctx.rect(e,i,a,r);t.current.updateRectMinMax(getCurrentTransform(t.ctx),[e,i,s,n]);t.clip();t.endPath()}setFillAndStrokeStyleToContext(t,e,i){const s=t.ctx,n=t.current;switch(e){case vt:const t=this.ctx;s.fillStyle=t.fillStyle;s.strokeStyle=t.strokeStyle;n.fillColor=t.fillStyle;n.strokeColor=t.strokeStyle;break;case yt:const a=Util.makeHexColor(i[0],i[1],i[2]);s.fillStyle=a;s.strokeStyle=a;n.fillColor=a;n.strokeColor=a;break;default:throw new FormatError(`Unsupported paint type: ${e}`)}}getPattern(t,e,i,s){let n=i;if(s!==wt){n=Util.transform(n,e.baseTransform);this.matrix&&(n=Util.transform(n,this.matrix))}const a=this.createPatternCanvas(e);let r=new DOMMatrix(n);r=r.translate(a.offsetX,a.offsetY);r=r.scale(1/a.scaleX,1/a.scaleY);const o=t.createPattern(a.canvas,"repeat");o.setTransform(r);return o}}function convertBlackAndWhiteToRGBA({src:t,srcPos:e=0,dest:i,width:s,height:n,nonBlackColor:a=4294967295,inverseDecode:r=!1}){const o=util_FeatureTest.isLittleEndian?4278190080:255,[l,h]=r?[a,o]:[o,a],d=s>>3,c=7&s,u=t.length;i=new Uint32Array(i.buffer);let p=0;for(let s=0;s>2),m=i.length,f=s+7>>3,b=4294967295,A=util_FeatureTest.isLittleEndian?4278190080:255;for(u=0;uf?s:8*t-7,r=-8&a;let o=0,c=0;for(;n>=1}}for(;l=a){g=n;m=s*g}l=0;for(p=m;p--;){c[l++]=d[h++];c[l++]=d[h++];c[l++]=d[h++];c[l++]=255}t.putImageData(o,0,u*xt)}}}function putBinaryImageMask(t,e){if(e.bitmap){t.drawImage(e.bitmap,0,0);return}const i=e.height,s=e.width,n=i%xt,a=(i-n)/xt,r=0===n?a:a+1,o=t.createImageData(s,xt);let l=0;const h=e.data,d=o.data;for(let e=0;e10&&"function"==typeof i,h=l?Date.now()+15:0;let d=0;const c=this.commonObjs,u=this.objs;let p;for(;;){if(void 0!==s&&r===s.nextBreakPoint){s.breakIt(r,i);return r}p=a[r];if(p!==X.dependency)this[p].apply(this,n[r]);else for(const t of n[r]){const e=t.startsWith("g_")?c:u;if(!e.has(t)){e.get(t,i);return r}}r++;if(r===o)return r;if(l&&++d>10){if(Date.now()>h){i();return r}d=0}}}#hi(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null;this.ctx.restore();if(this.transparentCanvas){this.ctx=this.compositeCtx;this.ctx.save();this.ctx.setTransform(1,0,0,1,0,0);this.ctx.drawImage(this.transparentCanvas,0,0);this.ctx.restore();this.transparentCanvas=null}}endDrawing(){this.#hi();this.cachedCanvases.clear();this.cachedPatterns.clear();for(const t of this._cachedBitmapsMap.values()){for(const e of t.values())"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement&&(e.width=e.height=0);t.clear()}this._cachedBitmapsMap.clear();this.#di()}#di(){if(this.pageColors){const t=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if("none"!==t){const e=this.ctx.filter;this.ctx.filter=t;this.ctx.drawImage(this.ctx.canvas,0,0);this.ctx.filter=e}}}_scaleImage(t,e){const i=t.width??t.displayWidth,s=t.height??t.displayHeight;let n,a,r=Math.max(Math.hypot(e[0],e[1]),1),o=Math.max(Math.hypot(e[2],e[3]),1),l=i,h=s,d="prescale1";for(;r>2&&l>1||o>2&&h>1;){let e=l,i=h;if(r>2&&l>1){e=l>=16384?Math.floor(l/2)-1||1:Math.ceil(l/2);r/=l/e}if(o>2&&h>1){i=h>=16384?Math.floor(h/2)-1||1:Math.ceil(h)/2;o/=h/i}n=this.cachedCanvases.getCanvas(d,e,i);a=n.context;a.clearRect(0,0,e,i);a.drawImage(t,0,0,l,h,0,0,e,i);t=n.canvas;l=e;h=i;d="prescale1"===d?"prescale2":"prescale1"}return{img:t,paintWidth:l,paintHeight:h}}_createMaskCanvas(t){const e=this.ctx,{width:i,height:s}=t,n=this.current.fillColor,a=this.current.patternFill,r=getCurrentTransform(e);let o,l,h,d;if((t.bitmap||t.data)&&t.count>1){const e=t.bitmap||t.data.buffer;l=JSON.stringify(a?r:[r.slice(0,4),n]);o=this._cachedBitmapsMap.get(e);if(!o){o=new Map;this._cachedBitmapsMap.set(e,o)}const i=o.get(l);if(i&&!a){return{canvas:i,offsetX:Math.round(Math.min(r[0],r[2])+r[4]),offsetY:Math.round(Math.min(r[1],r[3])+r[5])}}h=i}if(!h){d=this.cachedCanvases.getCanvas("maskCanvas",i,s);putBinaryImageMask(d.context,t)}let c=Util.transform(r,[1/i,0,0,-1/s,0,0]);c=Util.transform(c,[1,0,0,1,0,-s]);const[u,p,g,m]=Util.getAxialAlignedBoundingBox([0,0,i,s],c),f=Math.round(g-u)||1,b=Math.round(m-p)||1,A=this.cachedCanvases.getCanvas("fillCanvas",f,b),w=A.context,v=u,y=p;w.translate(-v,-y);w.transform(...c);if(!h){h=this._scaleImage(d.canvas,getCurrentTransformInverse(w));h=h.img;o&&a&&o.set(l,h)}w.imageSmoothingEnabled=getImageSmoothingEnabled(getCurrentTransform(w),t.interpolate);drawImageAtIntegerCoords(w,h,0,0,h.width,h.height,0,0,i,s);w.globalCompositeOperation="source-in";const x=Util.transform(getCurrentTransformInverse(w),[1,0,0,1,-v,-y]);w.fillStyle=a?n.getPattern(e,this,x,bt):n;w.fillRect(0,0,i,s);if(o&&!a){this.cachedCanvases.delete("fillCanvas");o.set(l,A.canvas)}return{canvas:A.canvas,offsetX:Math.round(v),offsetY:Math.round(y)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1);this.current.lineWidth=t;this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=_t[t]}setLineJoin(t){this.ctx.lineJoin=Et[t]}setMiterLimit(t){this.ctx.miterLimit=t}setDash(t,e){const i=this.ctx;if(void 0!==i.setLineDash){i.setLineDash(t);i.lineDashOffset=e}}setRenderingIntent(t){}setFlatness(t){}setGState(t){for(const[e,i]of t)switch(e){case"LW":this.setLineWidth(i);break;case"LC":this.setLineCap(i);break;case"LJ":this.setLineJoin(i);break;case"ML":this.setMiterLimit(i);break;case"D":this.setDash(i[0],i[1]);break;case"RI":this.setRenderingIntent(i);break;case"FL":this.setFlatness(i);break;case"Font":this.setFont(i[0],i[1]);break;case"CA":this.current.strokeAlpha=i;break;case"ca":this.current.fillAlpha=i;this.ctx.globalAlpha=i;break;case"BM":this.ctx.globalCompositeOperation=i;break;case"SMask":this.current.activeSMask=i?this.tempSMask:null;this.tempSMask=null;this.checkSMaskState();break;case"TR":this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(i)}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){const t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode():!this.current.activeSMask&&t&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const t=this.ctx.canvas.width,e=this.ctx.canvas.height,i="smaskGroupAt"+this.groupLevel,s=this.cachedCanvases.getCanvas(i,t,e);this.suspendedCtx=this.ctx;this.ctx=s.context;const n=this.ctx;n.setTransform(...getCurrentTransform(this.suspendedCtx));copyCtxState(this.suspendedCtx,n);!function mirrorContextOperations(t,e){if(t._removeMirroring)throw new Error("Context is already forwarding operations.");t.__originalSave=t.save;t.__originalRestore=t.restore;t.__originalRotate=t.rotate;t.__originalScale=t.scale;t.__originalTranslate=t.translate;t.__originalTransform=t.transform;t.__originalSetTransform=t.setTransform;t.__originalResetTransform=t.resetTransform;t.__originalClip=t.clip;t.__originalMoveTo=t.moveTo;t.__originalLineTo=t.lineTo;t.__originalBezierCurveTo=t.bezierCurveTo;t.__originalRect=t.rect;t.__originalClosePath=t.closePath;t.__originalBeginPath=t.beginPath;t._removeMirroring=()=>{t.save=t.__originalSave;t.restore=t.__originalRestore;t.rotate=t.__originalRotate;t.scale=t.__originalScale;t.translate=t.__originalTranslate;t.transform=t.__originalTransform;t.setTransform=t.__originalSetTransform;t.resetTransform=t.__originalResetTransform;t.clip=t.__originalClip;t.moveTo=t.__originalMoveTo;t.lineTo=t.__originalLineTo;t.bezierCurveTo=t.__originalBezierCurveTo;t.rect=t.__originalRect;t.closePath=t.__originalClosePath;t.beginPath=t.__originalBeginPath;delete t._removeMirroring};t.save=function ctxSave(){e.save();this.__originalSave()};t.restore=function ctxRestore(){e.restore();this.__originalRestore()};t.translate=function ctxTranslate(t,i){e.translate(t,i);this.__originalTranslate(t,i)};t.scale=function ctxScale(t,i){e.scale(t,i);this.__originalScale(t,i)};t.transform=function ctxTransform(t,i,s,n,a,r){e.transform(t,i,s,n,a,r);this.__originalTransform(t,i,s,n,a,r)};t.setTransform=function ctxSetTransform(t,i,s,n,a,r){e.setTransform(t,i,s,n,a,r);this.__originalSetTransform(t,i,s,n,a,r)};t.resetTransform=function ctxResetTransform(){e.resetTransform();this.__originalResetTransform()};t.rotate=function ctxRotate(t){e.rotate(t);this.__originalRotate(t)};t.clip=function ctxRotate(t){e.clip(t);this.__originalClip(t)};t.moveTo=function(t,i){e.moveTo(t,i);this.__originalMoveTo(t,i)};t.lineTo=function(t,i){e.lineTo(t,i);this.__originalLineTo(t,i)};t.bezierCurveTo=function(t,i,s,n,a,r){e.bezierCurveTo(t,i,s,n,a,r);this.__originalBezierCurveTo(t,i,s,n,a,r)};t.rect=function(t,i,s,n){e.rect(t,i,s,n);this.__originalRect(t,i,s,n)};t.closePath=function(){e.closePath();this.__originalClosePath()};t.beginPath=function(){e.beginPath();this.__originalBeginPath()}}(n,this.suspendedCtx);this.setGState([["BM","source-over"],["ca",1],["CA",1]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring();copyCtxState(this.ctx,this.suspendedCtx);this.ctx=this.suspendedCtx;this.suspendedCtx=null}compose(t){if(!this.current.activeSMask)return;if(t){t[0]=Math.floor(t[0]);t[1]=Math.floor(t[1]);t[2]=Math.ceil(t[2]);t[3]=Math.ceil(t[3])}else t=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const e=this.current.activeSMask,i=this.suspendedCtx;this.composeSMask(i,e,this.ctx,t);this.ctx.save();this.ctx.setTransform(1,0,0,1,0,0);this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height);this.ctx.restore()}composeSMask(t,e,i,s){const n=s[0],a=s[1],r=s[2]-n,o=s[3]-a;if(0!==r&&0!==o){this.genericComposeSMask(e.context,i,r,o,e.subtype,e.backdrop,e.transferMap,n,a,e.offsetX,e.offsetY);t.save();t.globalAlpha=1;t.globalCompositeOperation="source-over";t.setTransform(1,0,0,1,0,0);t.drawImage(i.canvas,0,0);t.restore()}}genericComposeSMask(t,e,i,s,n,a,r,o,l,h,d){let c=t.canvas,u=o-h,p=l-d;if(a){const e=Util.makeHexColor(...a);if(u<0||p<0||u+i>c.width||p+s>c.height){const t=this.cachedCanvases.getCanvas("maskExtension",i,s),n=t.context;n.drawImage(c,-u,-p);n.globalCompositeOperation="destination-atop";n.fillStyle=e;n.fillRect(0,0,i,s);n.globalCompositeOperation="source-over";c=t.canvas;u=p=0}else{t.save();t.globalAlpha=1;t.setTransform(1,0,0,1,0,0);const n=new Path2D;n.rect(u,p,i,s);t.clip(n);t.globalCompositeOperation="destination-atop";t.fillStyle=e;t.fillRect(u,p,i,s);t.restore()}}e.save();e.globalAlpha=1;e.setTransform(1,0,0,1,0,0);"Alpha"===n&&r?e.filter=this.filterFactory.addAlphaFilter(r):"Luminosity"===n&&(e.filter=this.filterFactory.addLuminosityFilter(r));const g=new Path2D;g.rect(o,l,i,s);e.clip(g);e.globalCompositeOperation="destination-in";e.drawImage(c,u,p,i,s,o,l,i,s);e.restore()}save(){if(this.inSMaskMode){copyCtxState(this.ctx,this.suspendedCtx);this.suspendedCtx.save()}else this.ctx.save();const t=this.current;this.stateStack.push(t);this.current=t.clone()}restore(){0===this.stateStack.length&&this.inSMaskMode&&this.endSMaskMode();if(0!==this.stateStack.length){this.current=this.stateStack.pop();if(this.inSMaskMode){this.suspendedCtx.restore();copyCtxState(this.suspendedCtx,this.ctx)}else this.ctx.restore();this.checkSMaskState();this.pendingClip=null;this._cachedScaleForStroking[0]=-1;this._cachedGetSinglePixelWidth=null}}transform(t,e,i,s,n,a){this.ctx.transform(t,e,i,s,n,a);this._cachedScaleForStroking[0]=-1;this._cachedGetSinglePixelWidth=null}constructPath(t,e,i){const s=this.ctx,n=this.current;let a,r,o=n.x,l=n.y;const h=getCurrentTransform(s),d=0===h[0]&&0===h[3]||0===h[1]&&0===h[2],c=d?i.slice(0):null;for(let i=0,u=0,p=t.length;i100&&(h=100);this.current.fontSizeScale=e/h;this.ctx.font=`${l} ${o} ${h}px ${r}`}setTextRenderingMode(t){this.current.textRenderingMode=t}setTextRise(t){this.current.textRise=t}moveText(t,e){this.current.x=this.current.lineX+=t;this.current.y=this.current.lineY+=e}setLeadingMoveText(t,e){this.setLeading(-e);this.moveText(t,e)}setTextMatrix(t,e,i,s,n,a){this.current.textMatrix=[t,e,i,s,n,a];this.current.textMatrixScale=Math.hypot(t,e);this.current.x=this.current.lineX=0;this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}#ci(t,e,i){const s=new Path2D;s.addPath(t,new DOMMatrix(i).invertSelf().multiplySelf(e));return s}paintChar(t,e,i,s,n){const a=this.ctx,r=this.current,o=r.font,l=r.textRenderingMode,h=r.fontSize/r.fontSizeScale,d=l&y,c=!!(l&x),u=r.patternFill&&!o.missingFile,p=r.patternStroke&&!o.missingFile;let g;(o.disableFontFace||c||u||p)&&(g=o.getPathGenerator(this.commonObjs,t));if(o.disableFontFace||u||p){a.save();a.translate(e,i);a.scale(h,-h);if(d===b||d===w)if(s){const t=a.getTransform();a.setTransform(...s);a.fill(this.#ci(g,t,s))}else a.fill(g);if(d===A||d===w)if(n){const t=a.getTransform();a.setTransform(...n);a.stroke(this.#ci(g,t,n))}else{a.lineWidth/=h;a.stroke(g)}a.restore()}else{d!==b&&d!==w||a.fillText(t,e,i);d!==A&&d!==w||a.strokeText(t,e,i)}if(c){(this.pendingTextPaths||=[]).push({transform:getCurrentTransform(a),x:e,y:i,fontSize:h,path:g})}}get isFontSubpixelAAEnabled(){const{context:t}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);t.scale(1.5,1);t.fillText("I",0,10);const e=t.getImageData(0,0,10,10).data;let i=!1;for(let t=3;t0&&e[t]<255){i=!0;break}return shadow(this,"isFontSubpixelAAEnabled",i)}showText(t){const e=this.current,i=e.font;if(i.isType3Font)return this.showType3Text(t);const s=e.fontSize;if(0===s)return;const n=this.ctx,a=e.fontSizeScale,r=e.charSpacing,o=e.wordSpacing,l=e.fontDirection,h=e.textHScale*l,d=t.length,c=i.vertical,u=c?1:-1,p=i.defaultVMetrics,g=s*e.fontMatrix[0],m=e.textRenderingMode===b&&!i.disableFontFace&&!e.patternFill;n.save();n.transform(...e.textMatrix);n.translate(e.x,e.y+e.textRise);l>0?n.scale(h,-1):n.scale(h,1);let f,v;if(e.patternFill){n.save();const t=e.fillColor.getPattern(n,this,getCurrentTransformInverse(n),bt);f=getCurrentTransform(n);n.restore();n.fillStyle=t}if(e.patternStroke){n.save();const t=e.strokeColor.getPattern(n,this,getCurrentTransformInverse(n),At);v=getCurrentTransform(n);n.restore();n.strokeStyle=t}let x=e.lineWidth;const _=e.textMatrixScale;if(0===_||0===x){const t=e.textRenderingMode&y;t!==A&&t!==w||(x=this.getSinglePixelWidth())}else x/=_;if(1!==a){n.scale(a,a);x/=a}n.lineWidth=x;if(i.isInvalidPDFjsFont){const i=[];let s=0;for(const e of t){i.push(e.unicode);s+=e.width}n.fillText(i.join(""),0,0);e.x+=s*g*h;n.restore();this.compose();return}let E,S=0;for(E=0;E0){const t=1e3*n.measureText(b).width/s*a;if(xnew CanvasGraphics(t,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};e=new TilingPattern(t,i,this.ctx,n,s)}else e=this._getPattern(t[1],t[2]);return e}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments);this.current.patternStroke=!0}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments);this.current.patternFill=!0}setStrokeRGBColor(t,e,i){this.ctx.strokeStyle=this.current.strokeColor=Util.makeHexColor(t,e,i);this.current.patternStroke=!1}setStrokeTransparent(){this.ctx.strokeStyle=this.current.strokeColor="transparent";this.current.patternStroke=!1}setFillRGBColor(t,e,i){this.ctx.fillStyle=this.current.fillColor=Util.makeHexColor(t,e,i);this.current.patternFill=!1}setFillTransparent(){this.ctx.fillStyle=this.current.fillColor="transparent";this.current.patternFill=!1}_getPattern(t,e=null){let i;if(this.cachedPatterns.has(t))i=this.cachedPatterns.get(t);else{i=function getShadingPattern(t){switch(t[0]){case"RadialAxial":return new RadialAxialShadingPattern(t);case"Mesh":return new MeshShadingPattern(t);case"Dummy":return new DummyShadingPattern}throw new Error(`Unknown IR type: ${t[0]}`)}(this.getObject(t));this.cachedPatterns.set(t,i)}e&&(i.matrix=e);return i}shadingFill(t){if(!this.contentVisible)return;const e=this.ctx;this.save();const i=this._getPattern(t);e.fillStyle=i.getPattern(e,this,getCurrentTransformInverse(e),wt);const s=getCurrentTransformInverse(e);if(s){const{width:t,height:i}=e.canvas,[n,a,r,o]=Util.getAxialAlignedBoundingBox([0,0,t,i],s);this.ctx.fillRect(n,a,r-n,o-a)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox());this.restore()}beginInlineImage(){unreachable("Should not call beginInlineImage")}beginImageData(){unreachable("Should not call beginImageData")}paintFormXObjectBegin(t,e){if(this.contentVisible){this.save();this.baseTransformStack.push(this.baseTransform);t&&this.transform(...t);this.baseTransform=getCurrentTransform(this.ctx);if(e){const t=e[2]-e[0],i=e[3]-e[1];this.ctx.rect(e[0],e[1],t,i);this.current.updateRectMinMax(getCurrentTransform(this.ctx),e);this.clip();this.endPath()}}}paintFormXObjectEnd(){if(this.contentVisible){this.restore();this.baseTransform=this.baseTransformStack.pop()}}beginGroup(t){if(!this.contentVisible)return;this.save();if(this.inSMaskMode){this.endSMaskMode();this.current.activeSMask=null}const e=this.ctx;t.isolated||info("TODO: Support non-isolated groups.");t.knockout&&warn("Knockout groups not supported.");const i=getCurrentTransform(e);t.matrix&&e.transform(...t.matrix);if(!t.bbox)throw new Error("Bounding box is required.");let s=Util.getAxialAlignedBoundingBox(t.bbox,getCurrentTransform(e));const n=[0,0,e.canvas.width,e.canvas.height];s=Util.intersect(s,n)||[0,0,0,0];const a=Math.floor(s[0]),r=Math.floor(s[1]),o=Math.max(Math.ceil(s[2])-a,1),l=Math.max(Math.ceil(s[3])-r,1);this.current.startNewPathAndClipBox([0,0,o,l]);let h="groupAt"+this.groupLevel;t.smask&&(h+="_smask_"+this.smaskCounter++%2);const d=this.cachedCanvases.getCanvas(h,o,l),c=d.context;c.translate(-a,-r);c.transform(...i);if(t.smask)this.smaskStack.push({canvas:d.canvas,context:c,offsetX:a,offsetY:r,subtype:t.smask.subtype,backdrop:t.smask.backdrop,transferMap:t.smask.transferMap||null,startTransformInverse:null});else{e.setTransform(1,0,0,1,0,0);e.translate(a,r);e.save()}copyCtxState(e,c);this.ctx=c;this.setGState([["BM","source-over"],["ca",1],["CA",1]]);this.groupStack.push(e);this.groupLevel++}endGroup(t){if(!this.contentVisible)return;this.groupLevel--;const e=this.ctx,i=this.groupStack.pop();this.ctx=i;this.ctx.imageSmoothingEnabled=!1;if(t.smask){this.tempSMask=this.smaskStack.pop();this.restore()}else{this.ctx.restore();const t=getCurrentTransform(this.ctx);this.restore();this.ctx.save();this.ctx.setTransform(...t);const i=Util.getAxialAlignedBoundingBox([0,0,e.canvas.width,e.canvas.height],t);this.ctx.drawImage(e.canvas,0,0);this.ctx.restore();this.compose(i)}}beginAnnotation(t,e,i,s,n){this.#hi();resetCtxToDefault(this.ctx);this.ctx.save();this.save();this.baseTransform&&this.ctx.setTransform(...this.baseTransform);if(e){const s=e[2]-e[0],a=e[3]-e[1];if(n&&this.annotationCanvasMap){(i=i.slice())[4]-=e[0];i[5]-=e[1];(e=e.slice())[0]=e[1]=0;e[2]=s;e[3]=a;const[n,r]=Util.singularValueDecompose2dScale(getCurrentTransform(this.ctx)),{viewportScale:o}=this,l=Math.ceil(s*this.outputScaleX*o),h=Math.ceil(a*this.outputScaleY*o);this.annotationCanvas=this.canvasFactory.create(l,h);const{canvas:d,context:c}=this.annotationCanvas;this.annotationCanvasMap.set(t,d);this.annotationCanvas.savedCtx=this.ctx;this.ctx=c;this.ctx.save();this.ctx.setTransform(n,0,0,-r,0,a*r);resetCtxToDefault(this.ctx)}else{resetCtxToDefault(this.ctx);this.endPath();this.ctx.rect(e[0],e[1],s,a);this.ctx.clip();this.ctx.beginPath()}}this.current=new CanvasExtraState(this.ctx.canvas.width,this.ctx.canvas.height);this.transform(...i);this.transform(...s)}endAnnotation(){if(this.annotationCanvas){this.ctx.restore();this.#di();this.ctx=this.annotationCanvas.savedCtx;delete this.annotationCanvas.savedCtx;delete this.annotationCanvas}}paintImageMaskXObject(t){if(!this.contentVisible)return;const e=t.count;(t=this.getObject(t.data,t)).count=e;const i=this.ctx,s=this.processingType3;if(s){void 0===s.compiled&&(s.compiled=function compileType3Glyph(t){const{width:e,height:i}=t;if(e>1e3||i>1e3)return null;const s=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),n=e+1;let a,r,o,l=new Uint8Array(n*(i+1));const h=e+7&-8;let d=new Uint8Array(h*i),c=0;for(const e of t.data){let t=128;for(;t>0;){d[c++]=e&t?0:255;t>>=1}}let u=0;c=0;if(0!==d[c]){l[0]=1;++u}for(r=1;r>2)+(d[c+1]?4:0)+(d[c-h+1]?8:0);if(s[t]){l[o+r]=s[t];++u}c++}if(d[c-h]!==d[c]){l[o+r]=d[c]?2:4;++u}if(u>1e3)return null}c=h*(i-1);o=a*n;if(0!==d[c]){l[o]=8;++u}for(r=1;r1e3)return null;const p=new Int32Array([0,n,-1,0,-n,0,0,0,1]),g=new Path2D;for(a=0;u&&a<=i;a++){let t=a*n;const i=t+e;for(;t>4;l[t]&=r>>2|r<<2}g.lineTo(t%n,t/n|0);l[t]||--u}while(s!==t);--a}d=null;l=null;return function(t){t.save();t.scale(1/e,-1/i);t.translate(0,-i);t.fill(g);t.beginPath();t.restore()}}(t));if(s.compiled){s.compiled(i);return}}const n=this._createMaskCanvas(t),a=n.canvas;i.save();i.setTransform(1,0,0,1,0,0);i.drawImage(a,n.offsetX,n.offsetY);i.restore();this.compose()}paintImageMaskXObjectRepeat(t,e,i=0,s=0,n,a){if(!this.contentVisible)return;t=this.getObject(t.data,t);const r=this.ctx;r.save();const o=getCurrentTransform(r);r.transform(e,i,s,n,0,0);const l=this._createMaskCanvas(t);r.setTransform(1,0,0,1,l.offsetX-o[4],l.offsetY-o[5]);for(let t=0,h=a.length;te?h/e:1;r=l>e?l/e:1}}this._cachedScaleForStroking[0]=a;this._cachedScaleForStroking[1]=r}return this._cachedScaleForStroking}rescaleAndStroke(t){const{ctx:e}=this,{lineWidth:i}=this.current,[s,n]=this.getScaleForStroking();e.lineWidth=i||1;if(1===s&&1===n){e.stroke();return}const a=e.getLineDash();t&&e.save();e.scale(s,n);if(a.length>0){const t=Math.max(s,n);e.setLineDash(a.map((e=>e/t)));e.lineDashOffset/=t}e.stroke();t&&e.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}}for(const t in X)void 0!==CanvasGraphics.prototype[t]&&(CanvasGraphics.prototype[X[t]]=CanvasGraphics.prototype[t]);class GlobalWorkerOptions{static#ui=null;static#pi="";static get workerPort(){return this.#ui}static set workerPort(t){if(!("undefined"!=typeof Worker&&t instanceof Worker)&&null!==t)throw new Error("Invalid `workerPort` type.");this.#ui=t}static get workerSrc(){return this.#pi}static set workerSrc(t){if("string"!=typeof t)throw new Error("Invalid `workerSrc` type.");this.#pi=t}}class Metadata{#gi;#mi;constructor({parsedData:t,rawData:e}){this.#gi=t;this.#mi=e}getRaw(){return this.#mi}get(t){return this.#gi.get(t)??null}getAll(){return objectFromMap(this.#gi)}has(t){return this.#gi.has(t)}}const Tt=Symbol("INTERNAL");class OptionalContentGroup{#fi=!1;#bi=!1;#Ai=!1;#wi=!0;constructor(t,{name:e,intent:i,usage:s,rbGroups:n}){this.#fi=!!(t&r);this.#bi=!!(t&o);this.name=e;this.intent=i;this.usage=s;this.rbGroups=n}get visible(){if(this.#Ai)return this.#wi;if(!this.#wi)return!1;const{print:t,view:e}=this.usage;return this.#fi?"OFF"!==e?.viewState:!this.#bi||"OFF"!==t?.printState}_setVisible(t,e,i=!1){t!==Tt&&unreachable("Internal method `_setVisible` called.");this.#Ai=i;this.#wi=e}}class OptionalContentConfig{#vi=null;#yi=new Map;#xi=null;#_i=null;constructor(t,e=r){this.renderingIntent=e;this.name=null;this.creator=null;if(null!==t){this.name=t.name;this.creator=t.creator;this.#_i=t.order;for(const i of t.groups)this.#yi.set(i.id,new OptionalContentGroup(e,i));if("OFF"===t.baseState)for(const t of this.#yi.values())t._setVisible(Tt,!1);for(const e of t.on)this.#yi.get(e)._setVisible(Tt,!0);for(const e of t.off)this.#yi.get(e)._setVisible(Tt,!1);this.#xi=this.getHash()}}#Ei(t){const e=t.length;if(e<2)return!0;const i=t[0];for(let s=1;s0?objectFromMap(this.#yi):null}getGroup(t){return this.#yi.get(t)||null}getHash(){if(null!==this.#vi)return this.#vi;const t=new MurmurHash3_64;for(const[e,i]of this.#yi)t.update(`${e}:${i.visible}`);return this.#vi=t.hexdigest()}}class PDFDataTransportStream{constructor(t,{disableRange:e=!1,disableStream:i=!1}){assert(t,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');const{length:s,initialData:n,progressiveDone:a,contentDispositionFilename:r}=t;this._queuedChunks=[];this._progressiveDone=a;this._contentDispositionFilename=r;if(n?.length>0){const t=n instanceof Uint8Array&&n.byteLength===n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer;this._queuedChunks.push(t)}this._pdfDataRangeTransport=t;this._isStreamingSupported=!i;this._isRangeSupported=!e;this._contentLength=s;this._fullRequestReader=null;this._rangeReaders=[];t.addRangeListener(((t,e)=>{this._onReceiveData({begin:t,chunk:e})}));t.addProgressListener(((t,e)=>{this._onProgress({loaded:t,total:e})}));t.addProgressiveReadListener((t=>{this._onReceiveData({chunk:t})}));t.addProgressiveDoneListener((()=>{this._onProgressiveDone()}));t.transportReady()}_onReceiveData({begin:t,chunk:e}){const i=e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer;if(void 0===t)this._fullRequestReader?this._fullRequestReader._enqueue(i):this._queuedChunks.push(i);else{assert(this._rangeReaders.some((function(e){if(e._begin!==t)return!1;e._enqueue(i);return!0})),"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}_onProgress(t){void 0===t.total?this._rangeReaders[0]?.onProgress?.({loaded:t.loaded}):this._fullRequestReader?.onProgress?.({loaded:t.loaded,total:t.total})}_onProgressiveDone(){this._fullRequestReader?.progressiveDone();this._progressiveDone=!0}_removeRangeReader(t){const e=this._rangeReaders.indexOf(t);e>=0&&this._rangeReaders.splice(e,1)}getFullReader(){assert(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;this._queuedChunks=null;return new PDFDataTransportStreamReader(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new PDFDataTransportStreamRangeReader(this,t,e);this._pdfDataRangeTransport.requestDataRange(t,e);this._rangeReaders.push(i);return i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeReaders.slice(0))e.cancel(t);this._pdfDataRangeTransport.abort()}}class PDFDataTransportStreamReader{constructor(t,e,i=!1,s=null){this._stream=t;this._done=i||!1;this._filename=isPdfFile(s)?s:null;this._queuedChunks=e||[];this._loaded=0;for(const t of this._queuedChunks)this._loaded+=t.byteLength;this._requests=[];this._headersReady=Promise.resolve();t._fullRequestReader=this;this.onProgress=null}_enqueue(t){if(!this._done){if(this._requests.length>0){this._requests.shift().resolve({value:t,done:!1})}else this._queuedChunks.push(t);this._loaded+=t.byteLength}}get headersReady(){return this._headersReady}get filename(){return this._filename}get isRangeSupported(){return this._stream._isRangeSupported}get isStreamingSupported(){return this._stream._isStreamingSupported}get contentLength(){return this._stream._contentLength}async read(){if(this._queuedChunks.length>0){return{value:this._queuedChunks.shift(),done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||(this._done=!0)}}class PDFDataTransportStreamRangeReader{constructor(t,e,i){this._stream=t;this._begin=e;this._end=i;this._queuedChunk=null;this._requests=[];this._done=!1;this.onProgress=null}_enqueue(t){if(!this._done){if(0===this._requests.length)this._queuedChunk=t;else{this._requests.shift().resolve({value:t,done:!1});for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}this._done=!0;this._stream._removeRangeReader(this)}}get isStreamingSupported(){return!1}async read(){if(this._queuedChunk){const t=this._queuedChunk;this._queuedChunk=null;return{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0;this._stream._removeRangeReader(this)}}function createHeaders(t,e){const i=new Headers;if(!t||!e||"object"!=typeof e)return i;for(const t in e){const s=e[t];void 0!==s&&i.append(t,s)}return i}function getResponseOrigin(t){try{return new URL(t).origin}catch{}return null}function validateRangeRequestCapabilities({responseHeaders:t,isHttp:e,rangeChunkSize:i,disableRange:s}){const n={allowRangeRequests:!1,suggestedLength:void 0},a=parseInt(t.get("Content-Length"),10);if(!Number.isInteger(a))return n;n.suggestedLength=a;if(a<=2*i)return n;if(s||!e)return n;if("bytes"!==t.get("Accept-Ranges"))return n;if("identity"!==(t.get("Content-Encoding")||"identity"))return n;n.allowRangeRequests=!0;return n}function extractFilenameFromHeader(t){const e=t.get("Content-Disposition");if(e){let t=function getFilenameFromContentDispositionHeader(t){let e=!0,i=toParamRegExp("filename\\*","i").exec(t);if(i){i=i[1];let t=rfc2616unquote(i);t=unescape(t);t=rfc5987decode(t);t=rfc2047decode(t);return fixupEncoding(t)}i=function rfc2231getparam(t){const e=[];let i;const s=toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;null!==(i=s.exec(t));){let[,t,s,n]=i;t=parseInt(t,10);if(t in e){if(0===t)break}else e[t]=[s,n]}const n=[];for(let t=0;t{t._responseOrigin=getResponseOrigin(e.url);if(!validateResponseStatus(e.status))throw createResponseStatusError(e.status,s);this._reader=e.body.getReader();this._headersCapability.resolve();const i=e.headers,{allowRangeRequests:n,suggestedLength:a}=validateRangeRequestCapabilities({responseHeaders:i,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=n;this._contentLength=a||this._contentLength;this._filename=extractFilenameFromHeader(i);!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new AbortException("Streaming is disabled."))})).catch(this._headersCapability.reject);this.onProgress=null}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._headersCapability.promise;const{value:t,done:e}=await this._reader.read();if(e)return{value:t,done:e};this._loaded+=t.byteLength;this.onProgress?.({loaded:this._loaded,total:this._contentLength});return{value:getArrayBuffer(t),done:!1}}cancel(t){this._reader?.cancel(t);this._abortController.abort()}}class PDFFetchStreamRangeReader{constructor(t,e,i){this._stream=t;this._reader=null;this._loaded=0;const s=t.source;this._withCredentials=s.withCredentials||!1;this._readCapability=Promise.withResolvers();this._isStreamingSupported=!s.disableStream;this._abortController=new AbortController;const n=new Headers(t.headers);n.append("Range",`bytes=${e}-${i-1}`);const a=s.url;fetch(a,createFetchOptions(n,this._withCredentials,this._abortController)).then((e=>{const i=getResponseOrigin(e.url);if(i!==t._responseOrigin)throw new Error(`Expected range response-origin "${i}" to match "${t._responseOrigin}".`);if(!validateResponseStatus(e.status))throw createResponseStatusError(e.status,a);this._readCapability.resolve();this._reader=e.body.getReader()})).catch(this._readCapability.reject);this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();if(e)return{value:t,done:e};this._loaded+=t.byteLength;this.onProgress?.({loaded:this._loaded});return{value:getArrayBuffer(t),done:!1}}cancel(t){this._reader?.cancel(t);this._abortController.abort()}}class NetworkManager{_responseOrigin=null;constructor({url:t,httpHeaders:e,withCredentials:i}){this.url=t;this.isHttp=/^https?:/i.test(t);this.headers=createHeaders(this.isHttp,e);this.withCredentials=i||!1;this.currXhrId=0;this.pendingRequests=Object.create(null)}request(t){const e=new XMLHttpRequest,i=this.currXhrId++,s=this.pendingRequests[i]={xhr:e};e.open("GET",this.url);e.withCredentials=this.withCredentials;for(const[t,i]of this.headers)e.setRequestHeader(t,i);if(this.isHttp&&"begin"in t&&"end"in t){e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`);s.expectedStatus=206}else s.expectedStatus=200;e.responseType="arraybuffer";assert(t.onError,"Expected `onError` callback to be provided.");e.onerror=()=>{t.onError(e.status)};e.onreadystatechange=this.onStateChange.bind(this,i);e.onprogress=this.onProgress.bind(this,i);s.onHeadersReceived=t.onHeadersReceived;s.onDone=t.onDone;s.onError=t.onError;s.onProgress=t.onProgress;e.send(null);return i}onProgress(t,e){const i=this.pendingRequests[t];i&&i.onProgress?.(e)}onStateChange(t,e){const i=this.pendingRequests[t];if(!i)return;const s=i.xhr;if(s.readyState>=2&&i.onHeadersReceived){i.onHeadersReceived();delete i.onHeadersReceived}if(4!==s.readyState)return;if(!(t in this.pendingRequests))return;delete this.pendingRequests[t];if(0===s.status&&this.isHttp){i.onError(s.status);return}const n=s.status||200;if(!(200===n&&206===i.expectedStatus)&&n!==i.expectedStatus){i.onError(s.status);return}const a=function network_getArrayBuffer(t){const e=t.response;return"string"!=typeof e?e:stringToBytes(e).buffer}(s);if(206===n){const t=s.getResponseHeader("Content-Range"),e=/bytes (\d+)-(\d+)\/(\d+)/.exec(t);if(e)i.onDone({begin:parseInt(e[1],10),chunk:a});else{warn('Missing or invalid "Content-Range" header.');i.onError(0)}}else a?i.onDone({begin:0,chunk:a}):i.onError(s.status)}getRequestXhr(t){return this.pendingRequests[t].xhr}isPendingRequest(t){return t in this.pendingRequests}abortRequest(t){const e=this.pendingRequests[t].xhr;delete this.pendingRequests[t];e.abort()}}class PDFNetworkStream{constructor(t){this._source=t;this._manager=new NetworkManager(t);this._rangeChunkSize=t.rangeChunkSize;this._fullRequestReader=null;this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(t){const e=this._rangeRequestReaders.indexOf(t);e>=0&&this._rangeRequestReaders.splice(e,1)}getFullReader(){assert(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once.");this._fullRequestReader=new PDFNetworkStreamFullRequestReader(this._manager,this._source);return this._fullRequestReader}getRangeReader(t,e){const i=new PDFNetworkStreamRangeRequestReader(this._manager,t,e);i.onClosed=this._onRangeRequestReaderClosed.bind(this);this._rangeRequestReaders.push(i);return i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class PDFNetworkStreamFullRequestReader{constructor(t,e){this._manager=t;this._url=e.url;this._fullRequestId=t.request({onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)});this._headersCapability=Promise.withResolvers();this._disableRange=e.disableRange||!1;this._contentLength=e.length;this._rangeChunkSize=e.rangeChunkSize;this._rangeChunkSize||this._disableRange||(this._disableRange=!0);this._isStreamingSupported=!1;this._isRangeSupported=!1;this._cachedChunks=[];this._requests=[];this._done=!1;this._storedError=void 0;this._filename=null;this.onProgress=null}_onHeadersReceived(){const t=this._fullRequestId,e=this._manager.getRequestXhr(t);this._manager._responseOrigin=getResponseOrigin(e.responseURL);const i=e.getAllResponseHeaders(),s=new Headers(i?i.trimStart().replace(/[^\S ]+$/,"").split(/[\r\n]+/).map((t=>{const[e,...i]=t.split(": ");return[e,i.join(": ")]})):[]),{allowRangeRequests:n,suggestedLength:a}=validateRangeRequestCapabilities({responseHeaders:s,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});n&&(this._isRangeSupported=!0);this._contentLength=a||this._contentLength;this._filename=extractFilenameFromHeader(s);this._isRangeSupported&&this._manager.abortRequest(t);this._headersCapability.resolve()}_onDone(t){if(t)if(this._requests.length>0){this._requests.shift().resolve({value:t.chunk,done:!1})}else this._cachedChunks.push(t.chunk);this._done=!0;if(!(this._cachedChunks.length>0)){for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(t){this._storedError=createResponseStatusError(t,this._url);this._headersCapability.reject(this._storedError);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0;this._cachedChunks.length=0}_onProgress(t){this.onProgress?.({loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})}get filename(){return this._filename}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}get contentLength(){return this._contentLength}get headersReady(){return this._headersCapability.promise}async read(){await this._headersCapability.promise;if(this._storedError)throw this._storedError;if(this._cachedChunks.length>0){return{value:this._cachedChunks.shift(),done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;this._headersCapability.reject(t);for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0;this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId);this._fullRequestReader=null}}class PDFNetworkStreamRangeRequestReader{constructor(t,e,i){this._manager=t;this._url=t.url;this._requestId=t.request({begin:e,end:i,onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)});this._requests=[];this._queuedChunk=null;this._done=!1;this._storedError=void 0;this.onProgress=null;this.onClosed=null}_onHeadersReceived(){const t=getResponseOrigin(this._manager.getRequestXhr(this._requestId)?.responseURL);if(t!==this._manager._responseOrigin){this._storedError=new Error(`Expected range response-origin "${t}" to match "${this._manager._responseOrigin}".`);this._onError(0)}}_close(){this.onClosed?.(this)}_onDone(t){const e=t.chunk;if(this._requests.length>0){this._requests.shift().resolve({value:e,done:!1})}else this._queuedChunk=e;this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0;this._close()}_onError(t){this._storedError??=createResponseStatusError(t,this._url);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0;this._queuedChunk=null}_onProgress(t){this.isStreamingSupported||this.onProgress?.({loaded:t.loaded})}get isStreamingSupported(){return!1}async read(){if(this._storedError)throw this._storedError;if(null!==this._queuedChunk){const t=this._queuedChunk;this._queuedChunk=null;return{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0;this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId);this._close()}}const Mt=/^[a-z][a-z0-9\-+.]+:/i;class PDFNodeStream{constructor(t){this.source=t;this.url=function parseUrlOrPath(t){if(Mt.test(t))return new URL(t);const e=process.getBuiltinModule("url");return new URL(e.pathToFileURL(t))}(t.url);assert("file:"===this.url.protocol,"PDFNodeStream only supports file:// URLs.");this._fullRequestReader=null;this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){assert(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once.");this._fullRequestReader=new PDFNodeStreamFsFullReader(this);return this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new PDFNodeStreamFsRangeReader(this,t,e);this._rangeRequestReaders.push(i);return i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class PDFNodeStreamFsFullReader{constructor(t){this._url=t.url;this._done=!1;this._storedError=null;this.onProgress=null;const e=t.source;this._contentLength=e.length;this._loaded=0;this._filename=null;this._disableRange=e.disableRange||!1;this._rangeChunkSize=e.rangeChunkSize;this._rangeChunkSize||this._disableRange||(this._disableRange=!0);this._isStreamingSupported=!e.disableStream;this._isRangeSupported=!e.disableRange;this._readableStream=null;this._readCapability=Promise.withResolvers();this._headersCapability=Promise.withResolvers();const i=process.getBuiltinModule("fs");i.promises.lstat(this._url).then((t=>{this._contentLength=t.size;this._setReadableStream(i.createReadStream(this._url));this._headersCapability.resolve()}),(t=>{"ENOENT"===t.code&&(t=new MissingPDFException(`Missing PDF "${this._url}".`));this._storedError=t;this._headersCapability.reject(t)}))}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;if(this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();if(null===t){this._readCapability=Promise.withResolvers();return this.read()}this._loaded+=t.length;this.onProgress?.({loaded:this._loaded,total:this._contentLength});return{value:new Uint8Array(t).buffer,done:!1}}cancel(t){this._readableStream?this._readableStream.destroy(t):this._error(t)}_error(t){this._storedError=t;this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t;t.on("readable",(()=>{this._readCapability.resolve()}));t.on("end",(()=>{t.destroy();this._done=!0;this._readCapability.resolve()}));t.on("error",(t=>{this._error(t)}));!this._isStreamingSupported&&this._isRangeSupported&&this._error(new AbortException("streaming is disabled"));this._storedError&&this._readableStream.destroy(this._storedError)}}class PDFNodeStreamFsRangeReader{constructor(t,e,i){this._url=t.url;this._done=!1;this._storedError=null;this.onProgress=null;this._loaded=0;this._readableStream=null;this._readCapability=Promise.withResolvers();const s=t.source;this._isStreamingSupported=!s.disableStream;const n=process.getBuiltinModule("fs");this._setReadableStream(n.createReadStream(this._url,{start:e,end:i-1}))}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;if(this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();if(null===t){this._readCapability=Promise.withResolvers();return this.read()}this._loaded+=t.length;this.onProgress?.({loaded:this._loaded});return{value:new Uint8Array(t).buffer,done:!1}}cancel(t){this._readableStream?this._readableStream.destroy(t):this._error(t)}_error(t){this._storedError=t;this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t;t.on("readable",(()=>{this._readCapability.resolve()}));t.on("end",(()=>{t.destroy();this._done=!0;this._readCapability.resolve()}));t.on("error",(t=>{this._error(t)}));this._storedError&&this._readableStream.destroy(this._storedError)}}const Pt=30;class TextLayer{#Si=Promise.withResolvers();#pt=null;#Ci=!1;#Ti=!!globalThis.FontInspector?.enabled;#Mi=null;#Pi=null;#Di=0;#ki=0;#Ri=null;#Ii=null;#Fi=0;#Li=0;#Oi=Object.create(null);#Ni=[];#Bi=null;#Hi=[];#zi=new WeakMap;#Ui=null;static#Gi=new Map;static#$i=new Map;static#Vi=new WeakMap;static#ji=null;static#Wi=new Set;constructor({textContentSource:t,container:e,viewport:i}){if(t instanceof ReadableStream)this.#Bi=t;else{if("object"!=typeof t)throw new Error('No "textContentSource" parameter specified.');this.#Bi=new ReadableStream({start(e){e.enqueue(t);e.close()}})}this.#pt=this.#Ii=e;this.#Li=i.scale*(globalThis.devicePixelRatio||1);this.#Fi=i.rotation;this.#Pi={div:null,properties:null,ctx:null};const{pageWidth:s,pageHeight:n,pageX:a,pageY:r}=i.rawDims;this.#Ui=[1,0,0,-1,-a,r+n];this.#ki=s;this.#Di=n;TextLayer.#qi();setLayerDimensions(e,i);this.#Si.promise.finally((()=>{TextLayer.#Wi.delete(this);this.#Pi=null;this.#Oi=null})).catch((()=>{}))}static get fontFamilyMap(){const{isWindows:t,isFirefox:e}=util_FeatureTest.platform;return shadow(this,"fontFamilyMap",new Map([["sans-serif",(t&&e?"Calibri, ":"")+"sans-serif"],["monospace",(t&&e?"Lucida Console, ":"")+"monospace"]]))}render(){const pump=()=>{this.#Ri.read().then((({value:t,done:e})=>{if(e)this.#Si.resolve();else{this.#Mi??=t.lang;Object.assign(this.#Oi,t.styles);this.#Xi(t.items);pump()}}),this.#Si.reject)};this.#Ri=this.#Bi.getReader();TextLayer.#Wi.add(this);pump();return this.#Si.promise}update({viewport:t,onBefore:e=null}){const i=t.scale*(globalThis.devicePixelRatio||1),s=t.rotation;if(s!==this.#Fi){e?.();this.#Fi=s;setLayerDimensions(this.#Ii,{rotation:s})}if(i!==this.#Li){e?.();this.#Li=i;const t={div:null,properties:null,ctx:TextLayer.#Ki(this.#Mi)};for(const e of this.#Hi){t.properties=this.#zi.get(e);t.div=e;this.#Yi(t)}}}cancel(){const t=new AbortException("TextLayer task cancelled.");this.#Ri?.cancel(t).catch((()=>{}));this.#Ri=null;this.#Si.reject(t)}get textDivs(){return this.#Hi}get textContentItemsStr(){return this.#Ni}#Xi(t){if(this.#Ci)return;this.#Pi.ctx??=TextLayer.#Ki(this.#Mi);const e=this.#Hi,i=this.#Ni;for(const s of t){if(e.length>1e5){warn("Ignoring additional textDivs for performance reasons.");this.#Ci=!0;return}if(void 0!==s.str){i.push(s.str);this.#Qi(s)}else if("beginMarkedContentProps"===s.type||"beginMarkedContent"===s.type){const t=this.#pt;this.#pt=document.createElement("span");this.#pt.classList.add("markedContent");null!==s.id&&this.#pt.setAttribute("id",`${s.id}`);t.append(this.#pt)}else"endMarkedContent"===s.type&&(this.#pt=this.#pt.parentNode)}}#Qi(t){const e=document.createElement("span"),i={angle:0,canvasWidth:0,hasText:""!==t.str,hasEOL:t.hasEOL,fontSize:0};this.#Hi.push(e);const s=Util.transform(this.#Ui,t.transform);let n=Math.atan2(s[1],s[0]);const a=this.#Oi[t.fontName];a.vertical&&(n+=Math.PI/2);let r=this.#Ti&&a.fontSubstitution||a.fontFamily;r=TextLayer.fontFamilyMap.get(r)||r;const o=Math.hypot(s[2],s[3]),l=o*TextLayer.#Ji(r,this.#Mi);let h,d;if(0===n){h=s[4];d=s[5]-l}else{h=s[4]+l*Math.sin(n);d=s[5]-l*Math.cos(n)}const c="calc(var(--scale-factor)*",u=e.style;if(this.#pt===this.#Ii){u.left=`${(100*h/this.#ki).toFixed(2)}%`;u.top=`${(100*d/this.#Di).toFixed(2)}%`}else{u.left=`${c}${h.toFixed(2)}px)`;u.top=`${c}${d.toFixed(2)}px)`}u.fontSize=`${c}${(TextLayer.#ji*o).toFixed(2)}px)`;u.fontFamily=r;i.fontSize=o;e.setAttribute("role","presentation");e.textContent=t.str;e.dir=t.dir;this.#Ti&&(e.dataset.fontName=a.fontSubstitutionLoadedName||t.fontName);0!==n&&(i.angle=n*(180/Math.PI));let p=!1;if(t.str.length>1)p=!0;else if(" "!==t.str&&t.transform[0]!==t.transform[3]){const e=Math.abs(t.transform[0]),i=Math.abs(t.transform[3]);e!==i&&Math.max(e,i)/Math.min(e,i)>1.5&&(p=!0)}p&&(i.canvasWidth=a.vertical?t.height:t.width);this.#zi.set(e,i);this.#Pi.div=e;this.#Pi.properties=i;this.#Yi(this.#Pi);i.hasText&&this.#pt.append(e);if(i.hasEOL){const t=document.createElement("br");t.setAttribute("role","presentation");this.#pt.append(t)}}#Yi(t){const{div:e,properties:i,ctx:s}=t,{style:n}=e;let a="";TextLayer.#ji>1&&(a=`scale(${1/TextLayer.#ji})`);if(0!==i.canvasWidth&&i.hasText){const{fontFamily:t}=n,{canvasWidth:r,fontSize:o}=i;TextLayer.#Zi(s,o*this.#Li,t);const{width:l}=s.measureText(e.textContent);l>0&&(a=`scaleX(${r*this.#Li/l}) ${a}`)}0!==i.angle&&(a=`rotate(${i.angle}deg) ${a}`);a.length>0&&(n.transform=a)}static cleanup(){if(!(this.#Wi.size>0)){this.#Gi.clear();for(const{canvas:t}of this.#$i.values())t.remove();this.#$i.clear()}}static#Ki(t=null){let e=this.#$i.get(t||="");if(!e){const i=document.createElement("canvas");i.className="hiddenCanvasElement";i.lang=t;document.body.append(i);e=i.getContext("2d",{alpha:!1,willReadFrequently:!0});this.#$i.set(t,e);this.#Vi.set(e,{size:0,family:""})}return e}static#Zi(t,e,i){const s=this.#Vi.get(t);if(e!==s.size||i!==s.family){t.font=`${e}px ${i}`;s.size=e;s.family=i}}static#qi(){if(null!==this.#ji)return;const t=document.createElement("div");t.style.opacity=0;t.style.lineHeight=1;t.style.fontSize="1px";t.style.position="absolute";t.textContent="X";document.body.append(t);this.#ji=t.getBoundingClientRect().height;t.remove()}static#Ji(t,e){const i=this.#Gi.get(t);if(i)return i;const s=this.#Ki(e);s.canvas.width=s.canvas.height=Pt;this.#Zi(s,Pt,t);const n=s.measureText("");let a=n.fontBoundingBoxAscent,r=Math.abs(n.fontBoundingBoxDescent);if(a){const e=a/(a+r);this.#Gi.set(t,e);s.canvas.width=s.canvas.height=0;return e}s.strokeStyle="red";s.clearRect(0,0,Pt,Pt);s.strokeText("g",0,0);let o=s.getImageData(0,0,Pt,Pt).data;r=0;for(let t=o.length-1-3;t>=0;t-=4)if(o[t]>0){r=Math.ceil(t/4/Pt);break}s.clearRect(0,0,Pt,Pt);s.strokeText("A",0,Pt);o=s.getImageData(0,0,Pt,Pt).data;a=0;for(let t=0,e=o.length;t0){a=Pt-Math.floor(t/4/Pt);break}s.canvas.width=s.canvas.height=0;const l=a?a/(a+r):.8;this.#Gi.set(t,l);return l}}class XfaText{static textContent(t){const e=[],i={items:e,styles:Object.create(null)};!function walk(t){if(!t)return;let i=null;const s=t.name;if("#text"===s)i=t.value;else{if(!XfaText.shouldBuildText(s))return;t?.attributes?.textContent?i=t.attributes.textContent:t.value&&(i=t.value)}null!==i&&e.push({str:i});if(t.children)for(const e of t.children)walk(e)}(t);return i}static shouldBuildText(t){return!("textarea"===t||"input"===t||"option"===t||"select"===t)}}const Dt=65536,kt=e?class NodeCanvasFactory extends BaseCanvasFactory{_createCanvas(t,e){return process.getBuiltinModule("module").createRequire(import.meta.url)("@napi-rs/canvas").createCanvas(t,e)}}:class DOMCanvasFactory extends BaseCanvasFactory{constructor({ownerDocument:t=globalThis.document,enableHWA:e=!1}){super({enableHWA:e});this._document=t}_createCanvas(t,e){const i=this._document.createElement("canvas");i.width=t;i.height=e;return i}},Rt=e?class NodeCMapReaderFactory extends BaseCMapReaderFactory{async _fetch(t){return node_utils_fetchData(t)}}:DOMCMapReaderFactory,It=e?class NodeFilterFactory extends BaseFilterFactory{}:class DOMFilterFactory extends BaseFilterFactory{#ts;#es;#is;#ss;#ns;#as;#w=0;constructor({docId:t,ownerDocument:e=globalThis.document}){super();this.#ss=t;this.#ns=e}get#y(){return this.#es||=new Map}get#rs(){return this.#as||=new Map}get#os(){if(!this.#is){const t=this.#ns.createElement("div"),{style:e}=t;e.visibility="hidden";e.contain="strict";e.width=e.height=0;e.position="absolute";e.top=e.left=0;e.zIndex=-1;const i=this.#ns.createElementNS(it,"svg");i.setAttribute("width",0);i.setAttribute("height",0);this.#is=this.#ns.createElementNS(it,"defs");t.append(i);i.append(this.#is);this.#ns.body.append(t)}return this.#is}#ls(t){if(1===t.length){const e=t[0],i=new Array(256);for(let t=0;t<256;t++)i[t]=e[t]/255;const s=i.join(",");return[s,s,s]}const[e,i,s]=t,n=new Array(256),a=new Array(256),r=new Array(256);for(let t=0;t<256;t++){n[t]=e[t]/255;a[t]=i[t]/255;r[t]=s[t]/255}return[n.join(","),a.join(","),r.join(",")]}#hs(t){if(void 0===this.#ts){this.#ts="";const t=this.#ns.URL;t!==this.#ns.baseURI&&(isDataScheme(t)?warn('#createUrl: ignore "data:"-URL for performance reasons.'):this.#ts=t.split("#",1)[0])}return`url(${this.#ts}#${t})`}addFilter(t){if(!t)return"none";let e=this.#y.get(t);if(e)return e;const[i,s,n]=this.#ls(t),a=1===t.length?i:`${i}${s}${n}`;e=this.#y.get(a);if(e){this.#y.set(t,e);return e}const r=`g_${this.#ss}_transfer_map_${this.#w++}`,o=this.#hs(r);this.#y.set(t,o);this.#y.set(a,o);const l=this.#ds(r);this.#cs(i,s,n,l);return o}addHCMFilter(t,e){const i=`${t}-${e}`,s="base";let n=this.#rs.get(s);if(n?.key===i)return n.url;if(n){n.filter?.remove();n.key=i;n.url="none";n.filter=null}else{n={key:i,url:"none",filter:null};this.#rs.set(s,n)}if(!t||!e)return n.url;const a=this.#us(t);t=Util.makeHexColor(...a);const r=this.#us(e);e=Util.makeHexColor(...r);this.#os.style.color="";if("#000000"===t&&"#ffffff"===e||t===e)return n.url;const o=new Array(256);for(let t=0;t<=255;t++){const e=t/255;o[t]=e<=.03928?e/12.92:((e+.055)/1.055)**2.4}const l=o.join(","),h=`g_${this.#ss}_hcm_filter`,d=n.filter=this.#ds(h);this.#cs(l,l,l,d);this.#ps(d);const getSteps=(t,e)=>{const i=a[t]/255,s=r[t]/255,n=new Array(e+1);for(let t=0;t<=e;t++)n[t]=i+t/e*(s-i);return n.join(",")};this.#cs(getSteps(0,5),getSteps(1,5),getSteps(2,5),d);n.url=this.#hs(h);return n.url}addAlphaFilter(t){let e=this.#y.get(t);if(e)return e;const[i]=this.#ls([t]),s=`alpha_${i}`;e=this.#y.get(s);if(e){this.#y.set(t,e);return e}const n=`g_${this.#ss}_alpha_map_${this.#w++}`,a=this.#hs(n);this.#y.set(t,a);this.#y.set(s,a);const r=this.#ds(n);this.#gs(i,r);return a}addLuminosityFilter(t){let e,i,s=this.#y.get(t||"luminosity");if(s)return s;if(t){[e]=this.#ls([t]);i=`luminosity_${e}`}else i="luminosity";s=this.#y.get(i);if(s){this.#y.set(t,s);return s}const n=`g_${this.#ss}_luminosity_map_${this.#w++}`,a=this.#hs(n);this.#y.set(t,a);this.#y.set(i,a);const r=this.#ds(n);this.#ms(r);t&&this.#gs(e,r);return a}addHighlightHCMFilter(t,e,i,s,n){const a=`${e}-${i}-${s}-${n}`;let r=this.#rs.get(t);if(r?.key===a)return r.url;if(r){r.filter?.remove();r.key=a;r.url="none";r.filter=null}else{r={key:a,url:"none",filter:null};this.#rs.set(t,r)}if(!e||!i)return r.url;const[o,l]=[e,i].map(this.#us.bind(this));let h=Math.round(.2126*o[0]+.7152*o[1]+.0722*o[2]),d=Math.round(.2126*l[0]+.7152*l[1]+.0722*l[2]),[c,u]=[s,n].map(this.#us.bind(this));d{const s=new Array(256),n=(d-h)/i,a=t/255,r=(e-t)/(255*i);let o=0;for(let t=0;t<=i;t++){const e=Math.round(h+t*n),i=a+t*r;for(let t=o;t<=e;t++)s[t]=i;o=e+1}for(let t=o;t<256;t++)s[t]=s[o-1];return s.join(",")},p=`g_${this.#ss}_hcm_${t}_filter`,g=r.filter=this.#ds(p);this.#ps(g);this.#cs(getSteps(c[0],u[0],5),getSteps(c[1],u[1],5),getSteps(c[2],u[2],5),g);r.url=this.#hs(p);return r.url}destroy(t=!1){if(!t||!this.#as?.size){this.#is?.parentNode.parentNode.remove();this.#is=null;this.#es?.clear();this.#es=null;this.#as?.clear();this.#as=null;this.#w=0}}#ms(t){const e=this.#ns.createElementNS(it,"feColorMatrix");e.setAttribute("type","matrix");e.setAttribute("values","0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0");t.append(e)}#ps(t){const e=this.#ns.createElementNS(it,"feColorMatrix");e.setAttribute("type","matrix");e.setAttribute("values","0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0");t.append(e)}#ds(t){const e=this.#ns.createElementNS(it,"filter");e.setAttribute("color-interpolation-filters","sRGB");e.setAttribute("id",t);this.#os.append(e);return e}#fs(t,e,i){const s=this.#ns.createElementNS(it,e);s.setAttribute("type","discrete");s.setAttribute("tableValues",i);t.append(s)}#cs(t,e,i,s){const n=this.#ns.createElementNS(it,"feComponentTransfer");s.append(n);this.#fs(n,"feFuncR",t);this.#fs(n,"feFuncG",e);this.#fs(n,"feFuncB",i)}#gs(t,e){const i=this.#ns.createElementNS(it,"feComponentTransfer");e.append(i);this.#fs(i,"feFuncA",t)}#us(t){this.#os.style.color=t;return getRGB(getComputedStyle(this.#os).getPropertyValue("color"))}},Ft=e?class NodeStandardFontDataFactory extends BaseStandardFontDataFactory{async _fetch(t){return node_utils_fetchData(t)}}:DOMStandardFontDataFactory;function getDocument(t={}){"string"==typeof t||t instanceof URL?t={url:t}:(t instanceof ArrayBuffer||ArrayBuffer.isView(t))&&(t={data:t});const i=new PDFDocumentLoadingTask,{docId:s}=i,n=t.url?function getUrlProp(t){if(t instanceof URL)return t.href;try{return new URL(t,window.location).href}catch{if(e&&"string"==typeof t)return t}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}(t.url):null,a=t.data?function getDataProp(t){if(e&&"undefined"!=typeof Buffer&&t instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(t instanceof Uint8Array&&t.byteLength===t.buffer.byteLength)return t;if("string"==typeof t)return stringToBytes(t);if(t instanceof ArrayBuffer||ArrayBuffer.isView(t)||"object"==typeof t&&!isNaN(t?.length))return new Uint8Array(t);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}(t.data):null,r=t.httpHeaders||null,o=!0===t.withCredentials,l=t.password??null,h=t.range instanceof PDFDataRangeTransport?t.range:null,d=Number.isInteger(t.rangeChunkSize)&&t.rangeChunkSize>0?t.rangeChunkSize:Dt;let c=t.worker instanceof PDFWorker?t.worker:null;const u=t.verbosity,p="string"!=typeof t.docBaseUrl||isDataScheme(t.docBaseUrl)?null:t.docBaseUrl,g="string"==typeof t.cMapUrl?t.cMapUrl:null,m=!1!==t.cMapPacked,f=t.CMapReaderFactory||Rt,b="string"==typeof t.standardFontDataUrl?t.standardFontDataUrl:null,A=t.StandardFontDataFactory||Ft,w=!0!==t.stopAtErrors,v=Number.isInteger(t.maxImageSize)&&t.maxImageSize>-1?t.maxImageSize:-1,y=!1!==t.isEvalSupported,x="boolean"==typeof t.isOffscreenCanvasSupported?t.isOffscreenCanvasSupported:!e,_="boolean"==typeof t.isImageDecoderSupported?t.isImageDecoderSupported:!e&&(util_FeatureTest.platform.isFirefox||!globalThis.chrome),E=Number.isInteger(t.canvasMaxAreaInBytes)?t.canvasMaxAreaInBytes:-1,S="boolean"==typeof t.disableFontFace?t.disableFontFace:e,C=!0===t.fontExtraProperties,T=!0===t.enableXfa,M=t.ownerDocument||globalThis.document,P=!0===t.disableRange,D=!0===t.disableStream,k=!0===t.disableAutoFetch,R=!0===t.pdfBug,I=t.CanvasFactory||kt,F=t.FilterFactory||It,L=!0===t.enableHWA,O=h?h.length:t.length??NaN,N="boolean"==typeof t.useSystemFonts?t.useSystemFonts:!e&&!S,B="boolean"==typeof t.useWorkerFetch?t.useWorkerFetch:f===DOMCMapReaderFactory&&A===DOMStandardFontDataFactory&&g&&b&&isValidFetchUrl(g,document.baseURI)&&isValidFetchUrl(b,document.baseURI);setVerbosityLevel(u);const H={canvasFactory:new I({ownerDocument:M,enableHWA:L}),filterFactory:new F({docId:s,ownerDocument:M}),cMapReaderFactory:B?null:new f({baseUrl:g,isCompressed:m}),standardFontDataFactory:B?null:new A({baseUrl:b})};if(!c){const t={verbosity:u,port:GlobalWorkerOptions.workerPort};c=t.port?PDFWorker.fromPort(t):new PDFWorker(t);i._worker=c}const z={docId:s,apiVersion:"4.10.38",data:a,password:l,disableAutoFetch:k,rangeChunkSize:d,length:O,docBaseUrl:p,enableXfa:T,evaluatorOptions:{maxImageSize:v,disableFontFace:S,ignoreErrors:w,isEvalSupported:y,isOffscreenCanvasSupported:x,isImageDecoderSupported:_,canvasMaxAreaInBytes:E,fontExtraProperties:C,useSystemFonts:N,cMapUrl:B?g:null,standardFontDataUrl:B?b:null}},U={disableFontFace:S,fontExtraProperties:C,ownerDocument:M,pdfBug:R,styleElement:null,loadingParams:{disableAutoFetch:k,enableXfa:T}};c.promise.then((function(){if(i.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const t=c.messageHandler.sendWithPromise("GetDocRequest",z,a?[a.buffer]:null);let l;if(h)l=new PDFDataTransportStream(h,{disableRange:P,disableStream:D});else if(!a){if(!n)throw new Error("getDocument - no `url` parameter provided.");let t;if(e)if(isValidFetchUrl(n)){if("undefined"==typeof fetch||"undefined"==typeof Response||!("body"in Response.prototype))throw new Error("getDocument - the Fetch API was disabled in Node.js, see `--no-experimental-fetch`.");t=PDFFetchStream}else t=PDFNodeStream;else t=isValidFetchUrl(n)?PDFFetchStream:PDFNetworkStream;l=new t({url:n,length:O,httpHeaders:r,withCredentials:o,rangeChunkSize:d,disableRange:P,disableStream:D})}return t.then((t=>{if(i.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const e=new MessageHandler(s,t,c.port),n=new WorkerTransport(e,i,l,U,H);i._transport=n;e.send("Ready",null)}))})).catch(i._capability.reject);return i}function isRefProxy(t){return"object"==typeof t&&Number.isInteger(t?.num)&&t.num>=0&&Number.isInteger(t?.gen)&&t.gen>=0}class PDFDocumentLoadingTask{static#ss=0;constructor(){this._capability=Promise.withResolvers();this._transport=null;this._worker=null;this.docId="d"+PDFDocumentLoadingTask.#ss++;this.destroyed=!1;this.onPassword=null;this.onProgress=null}get promise(){return this._capability.promise}async destroy(){this.destroyed=!0;try{this._worker?.port&&(this._worker._pendingDestroy=!0);await(this._transport?.destroy())}catch(t){this._worker?.port&&delete this._worker._pendingDestroy;throw t}this._transport=null;this._worker?.destroy();this._worker=null}}class PDFDataRangeTransport{constructor(t,e,i=!1,s=null){this.length=t;this.initialData=e;this.progressiveDone=i;this.contentDispositionFilename=s;this._rangeListeners=[];this._progressListeners=[];this._progressiveReadListeners=[];this._progressiveDoneListeners=[];this._readyCapability=Promise.withResolvers()}addRangeListener(t){this._rangeListeners.push(t)}addProgressListener(t){this._progressListeners.push(t)}addProgressiveReadListener(t){this._progressiveReadListeners.push(t)}addProgressiveDoneListener(t){this._progressiveDoneListeners.push(t)}onDataRange(t,e){for(const i of this._rangeListeners)i(t,e)}onDataProgress(t,e){this._readyCapability.promise.then((()=>{for(const i of this._progressListeners)i(t,e)}))}onDataProgressiveRead(t){this._readyCapability.promise.then((()=>{for(const e of this._progressiveReadListeners)e(t)}))}onDataProgressiveDone(){this._readyCapability.promise.then((()=>{for(const t of this._progressiveDoneListeners)t()}))}transportReady(){this._readyCapability.resolve()}requestDataRange(t,e){unreachable("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class PDFDocumentProxy{constructor(t,e){this._pdfInfo=t;this._transport=e}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return shadow(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(t){return this._transport.getPage(t)}getPageIndex(t){return this._transport.getPageIndex(t)}getDestinations(){return this._transport.getDestinations()}getDestination(t){return this._transport.getDestination(t)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getOptionalContentConfig(e)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(t=!1){return this._transport.startCleanup(t||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}cachedPageNumber(t){return this._transport.cachedPageNumber(t)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}class PDFPageProxy{#bs=null;#As=!1;constructor(t,e,i,s=!1){this._pageIndex=t;this._pageInfo=e;this._transport=i;this._stats=s?new StatTimer:null;this._pdfBug=s;this.commonObjs=i.commonObjs;this.objs=new PDFObjects;this._maybeCleanupAfterRender=!1;this._intentStates=new Map;this.destroyed=!1}get pageNumber(){return this._pageIndex+1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:t,rotation:e=this.rotate,offsetX:i=0,offsetY:s=0,dontFlip:n=!1}={}){return new PageViewport({viewBox:this.view,userUnit:this.userUnit,scale:t,rotation:e,offsetX:i,offsetY:s,dontFlip:n})}getAnnotations({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getAnnotations(this._pageIndex,e)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return shadow(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:t,viewport:e,intent:i="display",annotationMode:s=p.ENABLE,transform:n=null,background:a=null,optionalContentConfigPromise:r=null,annotationCanvasMap:l=null,pageColors:h=null,printAnnotationStorage:d=null,isEditing:c=!1}){this._stats?.time("Overall");const u=this._transport.getRenderingIntent(i,s,d,c),{renderingIntent:g,cacheKey:m}=u;this.#As=!1;this.#ws();r||=this._transport.getOptionalContentConfig(g);let f=this._intentStates.get(m);if(!f){f=Object.create(null);this._intentStates.set(m,f)}if(f.streamReaderCancelTimeout){clearTimeout(f.streamReaderCancelTimeout);f.streamReaderCancelTimeout=null}const b=!!(g&o);if(!f.displayReadyCapability){f.displayReadyCapability=Promise.withResolvers();f.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null};this._stats?.time("Page Request");this._pumpOperatorList(u)}const complete=t=>{f.renderTasks.delete(A);(this._maybeCleanupAfterRender||b)&&(this.#As=!0);this.#vs(!b);if(t){A.capability.reject(t);this._abortOperatorList({intentState:f,reason:t instanceof Error?t:new Error(t)})}else A.capability.resolve();if(this._stats){this._stats.timeEnd("Rendering");this._stats.timeEnd("Overall");globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats)}},A=new InternalRenderTask({callback:complete,params:{canvasContext:t,viewport:e,transform:n,background:a},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:l,operatorList:f.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!b,pdfBug:this._pdfBug,pageColors:h});(f.renderTasks||=new Set).add(A);const w=A.task;Promise.all([f.displayReadyCapability.promise,r]).then((([t,e])=>{if(this.destroyed)complete();else{this._stats?.time("Rendering");if(!(e.renderingIntent&g))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");A.initializeGraphics({transparency:t,optionalContentConfig:e});A.operatorListChanged()}})).catch(complete);return w}getOperatorList({intent:t="display",annotationMode:e=p.ENABLE,printAnnotationStorage:i=null,isEditing:s=!1}={}){const n=this._transport.getRenderingIntent(t,e,i,s,!0);let a,r=this._intentStates.get(n.cacheKey);if(!r){r=Object.create(null);this._intentStates.set(n.cacheKey,r)}if(!r.opListReadCapability){a=Object.create(null);a.operatorListChanged=function operatorListChanged(){if(r.operatorList.lastChunk){r.opListReadCapability.resolve(r.operatorList);r.renderTasks.delete(a)}};r.opListReadCapability=Promise.withResolvers();(r.renderTasks||=new Set).add(a);r.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null};this._stats?.time("Page Request");this._pumpOperatorList(n)}return r.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=!1,disableNormalization:e=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,includeMarkedContent:!0===t,disableNormalization:!0===e},{highWaterMark:100,size:t=>t.items.length})}getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then((t=>XfaText.textContent(t)));const e=this.streamTextContent(t);return new Promise((function(t,i){const s=e.getReader(),n={items:[],styles:Object.create(null),lang:null};!function pump(){s.read().then((function({value:e,done:i}){if(i)t(n);else{n.lang??=e.lang;Object.assign(n.styles,e.styles);n.items.push(...e.items);pump()}}),i)}()}))}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const t=[];for(const e of this._intentStates.values()){this._abortOperatorList({intentState:e,reason:new Error("Page was destroyed."),force:!0});if(!e.opListReadCapability)for(const i of e.renderTasks){t.push(i.completed);i.cancel()}}this.objs.clear();this.#As=!1;this.#ws();return Promise.all(t)}cleanup(t=!1){this.#As=!0;const e=this.#vs(!1);t&&e&&(this._stats&&=new StatTimer);return e}#vs(t=!1){this.#ws();if(!this.#As||this.destroyed)return!1;if(t){this.#bs=setTimeout((()=>{this.#bs=null;this.#vs(!1)}),5e3);return!1}for(const{renderTasks:t,operatorList:e}of this._intentStates.values())if(t.size>0||!e.lastChunk)return!1;this._intentStates.clear();this.objs.clear();this.#As=!1;return!0}#ws(){if(this.#bs){clearTimeout(this.#bs);this.#bs=null}}_startRenderPage(t,e){const i=this._intentStates.get(e);if(i){this._stats?.timeEnd("Page Request");i.displayReadyCapability?.resolve(t)}}_renderPageChunk(t,e){for(let i=0,s=t.length;i{r.read().then((({value:t,done:e})=>{if(e)o.streamReader=null;else if(!this._transport.destroyed){this._renderPageChunk(t,o);pump()}}),(t=>{o.streamReader=null;if(!this._transport.destroyed){if(o.operatorList){o.operatorList.lastChunk=!0;for(const t of o.renderTasks)t.operatorListChanged();this.#vs(!0)}if(o.displayReadyCapability)o.displayReadyCapability.reject(t);else{if(!o.opListReadCapability)throw t;o.opListReadCapability.reject(t)}}}))};pump()}_abortOperatorList({intentState:t,reason:e,force:i=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout){clearTimeout(t.streamReaderCancelTimeout);t.streamReaderCancelTimeout=null}if(!i){if(t.renderTasks.size>0)return;if(e instanceof RenderingCancelledException){let i=100;e.extraDelay>0&&e.extraDelay<1e3&&(i+=e.extraDelay);t.streamReaderCancelTimeout=setTimeout((()=>{t.streamReaderCancelTimeout=null;this._abortOperatorList({intentState:t,reason:e,force:!0})}),i);return}}t.streamReader.cancel(new AbortException(e.message)).catch((()=>{}));t.streamReader=null;if(!this._transport.destroyed){for(const[e,i]of this._intentStates)if(i===t){this._intentStates.delete(e);break}this.cleanup()}}}get stats(){return this._stats}}class LoopbackPort{#ys=new Map;#xs=Promise.resolve();postMessage(t,e){const i={data:structuredClone(t,e?{transfer:e}:null)};this.#xs.then((()=>{for(const[t]of this.#ys)t.call(this,i)}))}addEventListener(t,e,i=null){let s=null;if(i?.signal instanceof AbortSignal){const{signal:n}=i;if(n.aborted){warn("LoopbackPort - cannot use an `aborted` signal.");return}const onAbort=()=>this.removeEventListener(t,e);s=()=>n.removeEventListener("abort",onAbort);n.addEventListener("abort",onAbort)}this.#ys.set(e,s)}removeEventListener(t,e){const i=this.#ys.get(e);i?.();this.#ys.delete(e)}terminate(){for(const[,t]of this.#ys)t?.();this.#ys.clear()}}class PDFWorker{static#_s=0;static#Es=!1;static#Ss;static{if(e){this.#Es=!0;GlobalWorkerOptions.workerSrc||="./pdf.worker.mjs"}this._isSameOrigin=(t,e)=>{let i;try{i=new URL(t);if(!i.origin||"null"===i.origin)return!1}catch{return!1}const s=new URL(e,i);return i.origin===s.origin};this._createCDNWrapper=t=>{const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))}}constructor({name:t=null,port:e=null,verbosity:i=getVerbosityLevel()}={}){this.name=t;this.destroyed=!1;this.verbosity=i;this._readyCapability=Promise.withResolvers();this._port=null;this._webWorker=null;this._messageHandler=null;if(e){if(PDFWorker.#Ss?.has(e))throw new Error("Cannot use more than one PDFWorker per port.");(PDFWorker.#Ss||=new WeakMap).set(e,this);this._initializeFromPort(e)}else this._initialize()}get promise(){return this._readyCapability.promise}#Cs(){this._readyCapability.resolve();this._messageHandler.send("configure",{verbosity:this.verbosity})}get port(){return this._port}get messageHandler(){return this._messageHandler}_initializeFromPort(t){this._port=t;this._messageHandler=new MessageHandler("main","worker",t);this._messageHandler.on("ready",(function(){}));this.#Cs()}_initialize(){if(PDFWorker.#Es||PDFWorker.#Ts){this._setupFakeWorker();return}let{workerSrc:t}=PDFWorker;try{PDFWorker._isSameOrigin(window.location.href,t)||(t=PDFWorker._createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),i=new MessageHandler("main","worker",e),terminateEarly=()=>{s.abort();i.destroy();e.terminate();this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()},s=new AbortController;e.addEventListener("error",(()=>{this._webWorker||terminateEarly()}),{signal:s.signal});i.on("test",(t=>{s.abort();if(!this.destroyed&&t){this._messageHandler=i;this._port=e;this._webWorker=e;this.#Cs()}else terminateEarly()}));i.on("ready",(t=>{s.abort();if(this.destroyed)terminateEarly();else try{sendTest()}catch{this._setupFakeWorker()}}));const sendTest=()=>{const t=new Uint8Array;i.send("test",t,[t.buffer])};sendTest();return}catch{info("The worker has been disabled.")}this._setupFakeWorker()}_setupFakeWorker(){if(!PDFWorker.#Es){warn("Setting up fake worker.");PDFWorker.#Es=!0}PDFWorker._setupFakeWorkerGlobal.then((t=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}const e=new LoopbackPort;this._port=e;const i="fake"+PDFWorker.#_s++,s=new MessageHandler(i+"_worker",i,e);t.setup(s,e);this._messageHandler=new MessageHandler(i,i+"_worker",e);this.#Cs()})).catch((t=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${t.message}".`))}))}destroy(){this.destroyed=!0;this._webWorker?.terminate();this._webWorker=null;PDFWorker.#Ss?.delete(this._port);this._port=null;this._messageHandler?.destroy();this._messageHandler=null}static fromPort(t){if(!t?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");const e=this.#Ss?.get(t.port);if(e){if(e._pendingDestroy)throw new Error("PDFWorker.fromPort - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return e}return new PDFWorker(t)}static get workerSrc(){if(GlobalWorkerOptions.workerSrc)return GlobalWorkerOptions.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get#Ts(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return shadow(this,"_setupFakeWorkerGlobal",(async()=>{if(this.#Ts)return this.#Ts;return(await import(this.workerSrc)).WorkerMessageHandler})())}}class WorkerTransport{#Ms=new Map;#Ps=new Map;#Ds=new Map;#ks=new Map;#Rs=null;constructor(t,e,i,s,n){this.messageHandler=t;this.loadingTask=e;this.commonObjs=new PDFObjects;this.fontLoader=new FontLoader({ownerDocument:s.ownerDocument,styleElement:s.styleElement});this.loadingParams=s.loadingParams;this._params=s;this.canvasFactory=n.canvasFactory;this.filterFactory=n.filterFactory;this.cMapReaderFactory=n.cMapReaderFactory;this.standardFontDataFactory=n.standardFontDataFactory;this.destroyed=!1;this.destroyCapability=null;this._networkStream=i;this._fullReader=null;this._lastProgress=null;this.downloadInfoCapability=Promise.withResolvers();this.setupMessageHandler()}#Is(t,e=null){const i=this.#Ms.get(t);if(i)return i;const s=this.messageHandler.sendWithPromise(t,e);this.#Ms.set(t,s);return s}get annotationStorage(){return shadow(this,"annotationStorage",new AnnotationStorage)}getRenderingIntent(t,e=p.ENABLE,i=null,s=!1,n=!1){let g=r,m=rt;switch(t){case"any":g=a;break;case"display":break;case"print":g=o;break;default:warn(`getRenderingIntent - invalid intent: ${t}`)}const f=g&o&&i instanceof PrintAnnotationStorage?i:this.annotationStorage;switch(e){case p.DISABLE:g+=d;break;case p.ENABLE:break;case p.ENABLE_FORMS:g+=l;break;case p.ENABLE_STORAGE:g+=h;m=f.serializable;break;default:warn(`getRenderingIntent - invalid annotationMode: ${e}`)}s&&(g+=c);n&&(g+=u);const{ids:b,hash:A}=f.modifiedIds;return{renderingIntent:g,cacheKey:[g,m.hash,A].join("_"),annotationStorageSerializable:m,modifiedIds:b}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0;this.destroyCapability=Promise.withResolvers();this.#Rs?.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const e of this.#Ps.values())t.push(e._destroy());this.#Ps.clear();this.#Ds.clear();this.#ks.clear();this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();const e=this.messageHandler.sendWithPromise("Terminate",null);t.push(e);Promise.all(t).then((()=>{this.commonObjs.clear();this.fontLoader.clear();this.#Ms.clear();this.filterFactory.destroy();TextLayer.cleanup();this._networkStream?.cancelAllRequests(new AbortException("Worker was terminated."));this.messageHandler?.destroy();this.messageHandler=null;this.destroyCapability.resolve()}),this.destroyCapability.reject);return this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:t,loadingTask:e}=this;t.on("GetReader",((t,e)=>{assert(this._networkStream,"GetReader - no `IPDFStream` instance available.");this._fullReader=this._networkStream.getFullReader();this._fullReader.onProgress=t=>{this._lastProgress={loaded:t.loaded,total:t.total}};e.onPull=()=>{this._fullReader.read().then((function({value:t,done:i}){if(i)e.close();else{assert(t instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer.");e.enqueue(new Uint8Array(t),1,[t])}})).catch((t=>{e.error(t)}))};e.onCancel=t=>{this._fullReader.cancel(t);e.ready.catch((t=>{if(!this.destroyed)throw t}))}}));t.on("ReaderHeadersReady",(async t=>{await this._fullReader.headersReady;const{isStreamingSupported:i,isRangeSupported:s,contentLength:n}=this._fullReader;if(!i||!s){this._lastProgress&&e.onProgress?.(this._lastProgress);this._fullReader.onProgress=t=>{e.onProgress?.({loaded:t.loaded,total:t.total})}}return{isStreamingSupported:i,isRangeSupported:s,contentLength:n}}));t.on("GetRangeReader",((t,e)=>{assert(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");const i=this._networkStream.getRangeReader(t.begin,t.end);if(i){e.onPull=()=>{i.read().then((function({value:t,done:i}){if(i)e.close();else{assert(t instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer.");e.enqueue(new Uint8Array(t),1,[t])}})).catch((t=>{e.error(t)}))};e.onCancel=t=>{i.cancel(t);e.ready.catch((t=>{if(!this.destroyed)throw t}))}}else e.close()}));t.on("GetDoc",(({pdfInfo:t})=>{this._numPages=t.numPages;this._htmlForXfa=t.htmlForXfa;delete t.htmlForXfa;e._capability.resolve(new PDFDocumentProxy(t,this))}));t.on("DocException",(t=>{e._capability.reject(wrapReason(t))}));t.on("PasswordRequest",(t=>{this.#Rs=Promise.withResolvers();try{if(!e.onPassword)throw wrapReason(t);const updatePassword=t=>{t instanceof Error?this.#Rs.reject(t):this.#Rs.resolve({password:t})};e.onPassword(updatePassword,t.code)}catch(t){this.#Rs.reject(t)}return this.#Rs.promise}));t.on("DataLoaded",(t=>{e.onProgress?.({loaded:t.length,total:t.length});this.downloadInfoCapability.resolve(t)}));t.on("StartRenderPage",(t=>{if(this.destroyed)return;this.#Ps.get(t.pageIndex)._startRenderPage(t.transparency,t.cacheKey)}));t.on("commonobj",(([e,i,s])=>{if(this.destroyed)return null;if(this.commonObjs.has(e))return null;switch(i){case"Font":const{disableFontFace:n,fontExtraProperties:a,pdfBug:r}=this._params;if("error"in s){const t=s.error;warn(`Error during font loading: ${t}`);this.commonObjs.resolve(e,t);break}const o=r&&globalThis.FontInspector?.enabled?(t,e)=>globalThis.FontInspector.fontAdded(t,e):null,l=new FontFaceObject(s,{disableFontFace:n,fontExtraProperties:a,inspectFont:o});this.fontLoader.bind(l).catch((()=>t.sendWithPromise("FontFallback",{id:e}))).finally((()=>{!a&&l.data&&(l.data=null);this.commonObjs.resolve(e,l)}));break;case"CopyLocalImage":const{imageRef:h}=s;assert(h,"The imageRef must be defined.");for(const t of this.#Ps.values())for(const[,i]of t.objs)if(i?.ref===h){if(!i.dataLen)return null;this.commonObjs.resolve(e,structuredClone(i));return i.dataLen}break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(e,s);break;default:throw new Error(`Got unknown common object type ${i}`)}return null}));t.on("obj",(([t,e,i,s])=>{if(this.destroyed)return;const n=this.#Ps.get(e);if(!n.objs.has(t))if(0!==n._intentStates.size)switch(i){case"Image":n.objs.resolve(t,s);s?.dataLen>1e7&&(n._maybeCleanupAfterRender=!0);break;case"Pattern":n.objs.resolve(t,s);break;default:throw new Error(`Got unknown object type ${i}`)}else s?.bitmap?.close()}));t.on("DocProgress",(t=>{this.destroyed||e.onProgress?.({loaded:t.loaded,total:t.total})}));t.on("FetchBuiltInCMap",(async t=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.cMapReaderFactory)throw new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter.");return this.cMapReaderFactory.fetch(t)}));t.on("FetchStandardFontData",(async t=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.standardFontDataFactory)throw new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter.");return this.standardFontDataFactory.fetch(t)}))}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&warn("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:t,transfer:e}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:this._fullReader?.filename??null},e).finally((()=>{this.annotationStorage.resetModified()}))}getPage(t){if(!Number.isInteger(t)||t<=0||t>this._numPages)return Promise.reject(new Error("Invalid page request."));const e=t-1,i=this.#Ds.get(e);if(i)return i;const s=this.messageHandler.sendWithPromise("GetPage",{pageIndex:e}).then((i=>{if(this.destroyed)throw new Error("Transport destroyed");i.refStr&&this.#ks.set(i.refStr,t);const s=new PDFPageProxy(e,i,this,this._params.pdfBug);this.#Ps.set(e,s);return s}));this.#Ds.set(e,s);return s}getPageIndex(t){return isRefProxy(t)?this.messageHandler.sendWithPromise("GetPageIndex",{num:t.num,gen:t.gen}):Promise.reject(new Error("Invalid pageIndex request."))}getAnnotations(t,e){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:t,intent:e})}getFieldObjects(){return this.#Is("GetFieldObjects")}hasJSActions(){return this.#Is("HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(t){return"string"!=typeof t?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:t})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getDocJSActions(){return this.#Is("GetDocJSActions")}getPageJSActions(t){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:t})}getStructTree(t){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:t})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(t){return this.#Is("GetOptionalContentConfig").then((e=>new OptionalContentConfig(e,t)))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",e=this.#Ms.get(t);if(e)return e;const i=this.messageHandler.sendWithPromise(t,null).then((t=>({info:t[0],metadata:t[1]?new Metadata(t[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null})));this.#Ms.set(t,i);return i}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(t=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const t of this.#Ps.values()){if(!t.cleanup())throw new Error(`startCleanup: Page ${t.pageNumber} is currently rendering.`)}this.commonObjs.clear();t||this.fontLoader.clear();this.#Ms.clear();this.filterFactory.destroy(!0);TextLayer.cleanup()}}cachedPageNumber(t){if(!isRefProxy(t))return null;const e=0===t.gen?`${t.num}R`:`${t.num}R${t.gen}`;return this.#ks.get(e)??null}}const Lt=Symbol("INITIAL_DATA");class PDFObjects{#Fs=Object.create(null);#Ls(t){return this.#Fs[t]||={...Promise.withResolvers(),data:Lt}}get(t,e=null){if(e){const i=this.#Ls(t);i.promise.then((()=>e(i.data)));return null}const i=this.#Fs[t];if(!i||i.data===Lt)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return i.data}has(t){const e=this.#Fs[t];return!!e&&e.data!==Lt}delete(t){const e=this.#Fs[t];if(!e||e.data===Lt)return!1;delete this.#Fs[t];return!0}resolve(t,e=null){const i=this.#Ls(t);i.data=e;i.resolve()}clear(){for(const t in this.#Fs){const{data:e}=this.#Fs[t];e?.bitmap?.close()}this.#Fs=Object.create(null)}*[Symbol.iterator](){for(const t in this.#Fs){const{data:e}=this.#Fs[t];e!==Lt&&(yield[t,e])}}}class RenderTask{#Os=null;constructor(t){this.#Os=t;this.onContinue=null}get promise(){return this.#Os.capability.promise}cancel(t=0){this.#Os.cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=this.#Os.operatorList;if(!t)return!1;const{annotationCanvasMap:e}=this.#Os;return t.form||t.canvas&&e?.size>0}}class InternalRenderTask{#Ns=null;static#Bs=new WeakSet;constructor({callback:t,params:e,objs:i,commonObjs:s,annotationCanvasMap:n,operatorList:a,pageIndex:r,canvasFactory:o,filterFactory:l,useRequestAnimationFrame:h=!1,pdfBug:d=!1,pageColors:c=null}){this.callback=t;this.params=e;this.objs=i;this.commonObjs=s;this.annotationCanvasMap=n;this.operatorListIdx=null;this.operatorList=a;this._pageIndex=r;this.canvasFactory=o;this.filterFactory=l;this._pdfBug=d;this.pageColors=c;this.running=!1;this.graphicsReadyCallback=null;this.graphicsReady=!1;this._useRequestAnimationFrame=!0===h&&"undefined"!=typeof window;this.cancelled=!1;this.capability=Promise.withResolvers();this.task=new RenderTask(this);this._cancelBound=this.cancel.bind(this);this._continueBound=this._continue.bind(this);this._scheduleNextBound=this._scheduleNext.bind(this);this._nextBound=this._next.bind(this);this._canvas=e.canvasContext.canvas}get completed(){return this.capability.promise.catch((function(){}))}initializeGraphics({transparency:t=!1,optionalContentConfig:e}){if(this.cancelled)return;if(this._canvas){if(InternalRenderTask.#Bs.has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");InternalRenderTask.#Bs.add(this._canvas)}if(this._pdfBug&&globalThis.StepperManager?.enabled){this.stepper=globalThis.StepperManager.create(this._pageIndex);this.stepper.init(this.operatorList);this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint()}const{canvasContext:i,viewport:s,transform:n,background:a}=this.params;this.gfx=new CanvasGraphics(i,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:e},this.annotationCanvasMap,this.pageColors);this.gfx.beginDrawing({transform:n,viewport:s,transparency:t,background:a});this.operatorListIdx=0;this.graphicsReady=!0;this.graphicsReadyCallback?.()}cancel(t=null,e=0){this.running=!1;this.cancelled=!0;this.gfx?.endDrawing();if(this.#Ns){window.cancelAnimationFrame(this.#Ns);this.#Ns=null}InternalRenderTask.#Bs.delete(this._canvas);this.callback(t||new RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex+1}`,e))}operatorListChanged(){if(this.graphicsReady){this.stepper?.updateOperatorList(this.operatorList);this.running||this._continue()}else this.graphicsReadyCallback||=this._continueBound}_continue(){this.running=!0;this.cancelled||(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?this.#Ns=window.requestAnimationFrame((()=>{this.#Ns=null;this._nextBound().catch(this._cancelBound)})):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){if(!this.cancelled){this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper);if(this.operatorListIdx===this.operatorList.argsArray.length){this.running=!1;if(this.operatorList.lastChunk){this.gfx.endDrawing();InternalRenderTask.#Bs.delete(this._canvas);this.callback()}}}}}const Ot="4.10.38",Nt="f9bea397f";function makeColorComp(t){return Math.floor(255*Math.max(0,Math.min(1,t))).toString(16).padStart(2,"0")}function scaleAndClamp(t){return Math.max(0,Math.min(255,255*t))}class ColorConverters{static CMYK_G([t,e,i,s]){return["G",1-Math.min(1,.3*t+.59*i+.11*e+s)]}static G_CMYK([t]){return["CMYK",0,0,0,1-t]}static G_RGB([t]){return["RGB",t,t,t]}static G_rgb([t]){return[t=scaleAndClamp(t),t,t]}static G_HTML([t]){const e=makeColorComp(t);return`#${e}${e}${e}`}static RGB_G([t,e,i]){return["G",.3*t+.59*e+.11*i]}static RGB_rgb(t){return t.map(scaleAndClamp)}static RGB_HTML(t){return`#${t.map(makeColorComp).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([t,e,i,s]){return["RGB",1-Math.min(1,t+s),1-Math.min(1,i+s),1-Math.min(1,e+s)]}static CMYK_rgb([t,e,i,s]){return[scaleAndClamp(1-Math.min(1,t+s)),scaleAndClamp(1-Math.min(1,i+s)),scaleAndClamp(1-Math.min(1,e+s))]}static CMYK_HTML(t){const e=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(e)}static RGB_CMYK([t,e,i]){const s=1-t,n=1-e,a=1-i;return["CMYK",s,n,a,Math.min(s,n,a)]}}class BaseSVGFactory{create(t,e,i=!1){if(t<=0||e<=0)throw new Error("Invalid SVG dimensions");const s=this._createSVG("svg:svg");s.setAttribute("version","1.1");if(!i){s.setAttribute("width",`${t}px`);s.setAttribute("height",`${e}px`)}s.setAttribute("preserveAspectRatio","none");s.setAttribute("viewBox",`0 0 ${t} ${e}`);return s}createElement(t){if("string"!=typeof t)throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){unreachable("Abstract method `_createSVG` called.")}}class DOMSVGFactory extends BaseSVGFactory{_createSVG(t){return document.createElementNS(it,t)}}class XfaLayer{static setupStorage(t,e,i,s,n){const a=s.getValue(e,{value:null});switch(i.name){case"textarea":null!==a.value&&(t.textContent=a.value);if("print"===n)break;t.addEventListener("input",(t=>{s.setValue(e,{value:t.target.value})}));break;case"input":if("radio"===i.attributes.type||"checkbox"===i.attributes.type){a.value===i.attributes.xfaOn?t.setAttribute("checked",!0):a.value===i.attributes.xfaOff&&t.removeAttribute("checked");if("print"===n)break;t.addEventListener("change",(t=>{s.setValue(e,{value:t.target.checked?t.target.getAttribute("xfaOn"):t.target.getAttribute("xfaOff")})}))}else{null!==a.value&&t.setAttribute("value",a.value);if("print"===n)break;t.addEventListener("input",(t=>{s.setValue(e,{value:t.target.value})}))}break;case"select":if(null!==a.value){t.setAttribute("value",a.value);for(const t of i.children)t.attributes.value===a.value?t.attributes.selected=!0:t.attributes.hasOwnProperty("selected")&&delete t.attributes.selected}t.addEventListener("input",(t=>{const i=t.target.options,n=-1===i.selectedIndex?"":i[i.selectedIndex].value;s.setValue(e,{value:n})}))}}static setAttributes({html:t,element:e,storage:i=null,intent:s,linkService:n}){const{attributes:a}=e,r=t instanceof HTMLAnchorElement;"radio"===a.type&&(a.name=`${a.name}-${s}`);for(const[e,i]of Object.entries(a))if(null!=i)switch(e){case"class":i.length&&t.setAttribute(e,i.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",i);break;case"style":Object.assign(t.style,i);break;case"textContent":t.textContent=i;break;default:(!r||"href"!==e&&"newWindow"!==e)&&t.setAttribute(e,i)}r&&n.addLinkAttributes(t,a.href,a.newWindow);i&&a.dataId&&this.setupStorage(t,a.dataId,e,i)}static render(t){const e=t.annotationStorage,i=t.linkService,s=t.xfaHtml,n=t.intent||"display",a=document.createElement(s.name);s.attributes&&this.setAttributes({html:a,element:s,intent:n,linkService:i});const r="richText"!==n,o=t.div;o.append(a);if(t.viewport){const e=`matrix(${t.viewport.transform.join(",")})`;o.style.transform=e}r&&o.setAttribute("class","xfaLayer xfaFont");const l=[];if(0===s.children.length){if(s.value){const t=document.createTextNode(s.value);a.append(t);r&&XfaText.shouldBuildText(s.name)&&l.push(t)}return{textDivs:l}}const h=[[s,-1,a]];for(;h.length>0;){const[t,s,a]=h.at(-1);if(s+1===t.children.length){h.pop();continue}const o=t.children[++h.at(-1)[1]];if(null===o)continue;const{name:d}=o;if("#text"===d){const t=document.createTextNode(o.value);l.push(t);a.append(t);continue}const c=o?.attributes?.xmlns?document.createElementNS(o.attributes.xmlns,d):document.createElement(d);a.append(c);o.attributes&&this.setAttributes({html:c,element:o,storage:e,intent:n,linkService:i});if(o.children?.length>0)h.push([o,-1,c]);else if(o.value){const t=document.createTextNode(o.value);r&&XfaText.shouldBuildText(d)&&l.push(t);c.append(t)}}for(const t of o.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))t.setAttribute("readOnly",!0);return{textDivs:l}}static update(t){const e=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=e;t.div.hidden=!1}}const Bt=1e3,Ht=new WeakSet;function getRectDims(t){return{width:t[2]-t[0],height:t[3]-t[1]}}class AnnotationElementFactory{static create(t){switch(t.data.annotationType){case S:return new LinkAnnotationElement(t);case E:return new TextAnnotationElement(t);case U:switch(t.data.fieldType){case"Tx":return new TextWidgetAnnotationElement(t);case"Btn":return t.data.radioButton?new RadioButtonWidgetAnnotationElement(t):t.data.checkBox?new CheckboxWidgetAnnotationElement(t):new PushButtonWidgetAnnotationElement(t);case"Ch":return new ChoiceWidgetAnnotationElement(t);case"Sig":return new SignatureWidgetAnnotationElement(t)}return new WidgetAnnotationElement(t);case H:return new PopupAnnotationElement(t);case C:return new FreeTextAnnotationElement(t);case T:return new LineAnnotationElement(t);case M:return new SquareAnnotationElement(t);case P:return new CircleAnnotationElement(t);case k:return new PolylineAnnotationElement(t);case N:return new CaretAnnotationElement(t);case B:return new InkAnnotationElement(t);case D:return new PolygonAnnotationElement(t);case R:return new HighlightAnnotationElement(t);case I:return new UnderlineAnnotationElement(t);case F:return new SquigglyAnnotationElement(t);case L:return new StrikeOutAnnotationElement(t);case O:return new StampAnnotationElement(t);case z:return new FileAttachmentAnnotationElement(t);default:return new AnnotationElement(t)}}}class AnnotationElement{#Hs=null;#zs=!1;#Us=null;constructor(t,{isRenderable:e=!1,ignoreBorder:i=!1,createQuadrilaterals:s=!1}={}){this.isRenderable=e;this.data=t.data;this.layer=t.layer;this.linkService=t.linkService;this.downloadManager=t.downloadManager;this.imageResourcesPath=t.imageResourcesPath;this.renderForms=t.renderForms;this.svgFactory=t.svgFactory;this.annotationStorage=t.annotationStorage;this.enableScripting=t.enableScripting;this.hasJSActions=t.hasJSActions;this._fieldObjects=t.fieldObjects;this.parent=t.parent;e&&(this.container=this._createContainer(i));s&&this._createQuadrilaterals()}static _hasPopupData({titleObj:t,contentsObj:e,richText:i}){return!!(t?.str||e?.str||i?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return AnnotationElement._hasPopupData(this.data)}updateEdited(t){if(!this.container)return;this.#Hs||={rect:this.data.rect.slice(0)};const{rect:e}=t;e&&this.#Gs(e);this.#Us?.popup.updateEdited(t)}resetEdited(){if(this.#Hs){this.#Gs(this.#Hs.rect);this.#Us?.popup.resetEdited();this.#Hs=null}}#Gs(t){const{container:{style:e},data:{rect:i,rotation:s},parent:{viewport:{rawDims:{pageWidth:n,pageHeight:a,pageX:r,pageY:o}}}}=this;i?.splice(0,4,...t);const{width:l,height:h}=getRectDims(t);e.left=100*(t[0]-r)/n+"%";e.top=100*(a-t[3]+o)/a+"%";if(0===s){e.width=100*l/n+"%";e.height=100*h/a+"%"}else this.setRotation(s)}_createContainer(t){const{data:e,parent:{page:i,viewport:s}}=this,n=document.createElement("section");n.setAttribute("data-annotation-id",e.id);this instanceof WidgetAnnotationElement||(n.tabIndex=Bt);const{style:a}=n;a.zIndex=this.parent.zIndex++;e.alternativeText&&(n.title=e.alternativeText);e.noRotate&&n.classList.add("norotate");if(!e.rect||this instanceof PopupAnnotationElement){const{rotation:t}=e;e.hasOwnCanvas||0===t||this.setRotation(t,n);return n}const{width:r,height:o}=getRectDims(e.rect);if(!t&&e.borderStyle.width>0){a.borderWidth=`${e.borderStyle.width}px`;const t=e.borderStyle.horizontalCornerRadius,i=e.borderStyle.verticalCornerRadius;if(t>0||i>0){const e=`calc(${t}px * var(--scale-factor)) / calc(${i}px * var(--scale-factor))`;a.borderRadius=e}else if(this instanceof RadioButtonWidgetAnnotationElement){const t=`calc(${r}px * var(--scale-factor)) / calc(${o}px * var(--scale-factor))`;a.borderRadius=t}switch(e.borderStyle.style){case G:a.borderStyle="solid";break;case $:a.borderStyle="dashed";break;case V:warn("Unimplemented border style: beveled");break;case j:warn("Unimplemented border style: inset");break;case W:a.borderBottomStyle="solid"}const s=e.borderColor||null;if(s){this.#zs=!0;a.borderColor=Util.makeHexColor(0|s[0],0|s[1],0|s[2])}else a.borderWidth=0}const l=Util.normalizeRect([e.rect[0],i.view[3]-e.rect[1]+i.view[1],e.rect[2],i.view[3]-e.rect[3]+i.view[1]]),{pageWidth:h,pageHeight:d,pageX:c,pageY:u}=s.rawDims;a.left=100*(l[0]-c)/h+"%";a.top=100*(l[1]-u)/d+"%";const{rotation:p}=e;if(e.hasOwnCanvas||0===p){a.width=100*r/h+"%";a.height=100*o/d+"%"}else this.setRotation(p,n);return n}setRotation(t,e=this.container){if(!this.data.rect)return;const{pageWidth:i,pageHeight:s}=this.parent.viewport.rawDims,{width:n,height:a}=getRectDims(this.data.rect);let r,o;if(t%180==0){r=100*n/i;o=100*a/s}else{r=100*a/i;o=100*n/s}e.style.width=`${r}%`;e.style.height=`${o}%`;e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const setColor=(t,e,i)=>{const s=i.detail[t],n=s[0],a=s.slice(1);i.target.style[e]=ColorConverters[`${n}_HTML`](a);this.annotationStorage.setValue(this.data.id,{[e]:ColorConverters[`${n}_rgb`](a)})};return shadow(this,"_commonActions",{display:t=>{const{display:e}=t.detail,i=e%2==1;this.container.style.visibility=i?"hidden":"visible";this.annotationStorage.setValue(this.data.id,{noView:i,noPrint:1===e||2===e})},print:t=>{this.annotationStorage.setValue(this.data.id,{noPrint:!t.detail.print})},hidden:t=>{const{hidden:e}=t.detail;this.container.style.visibility=e?"hidden":"visible";this.annotationStorage.setValue(this.data.id,{noPrint:e,noView:e})},focus:t=>{setTimeout((()=>t.target.focus({preventScroll:!1})),0)},userName:t=>{t.target.title=t.detail.userName},readonly:t=>{t.target.disabled=t.detail.readonly},required:t=>{this._setRequired(t.target,t.detail.required)},bgColor:t=>{setColor("bgColor","backgroundColor",t)},fillColor:t=>{setColor("fillColor","backgroundColor",t)},fgColor:t=>{setColor("fgColor","color",t)},textColor:t=>{setColor("textColor","color",t)},borderColor:t=>{setColor("borderColor","borderColor",t)},strokeColor:t=>{setColor("strokeColor","borderColor",t)},rotation:t=>{const e=t.detail.rotation;this.setRotation(e);this.annotationStorage.setValue(this.data.id,{rotation:e})}})}_dispatchEventFromSandbox(t,e){const i=this._commonActions;for(const s of Object.keys(e.detail)){const n=t[s]||i[s];n?.(e)}}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;const e=this.annotationStorage.getRawValue(this.data.id);if(!e)return;const i=this._commonActions;for(const[s,n]of Object.entries(e)){const a=i[s];if(a){a({detail:{[s]:n},target:t});delete e[s]}}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:t}=this.data;if(!t)return;const[e,i,s,n]=this.data.rect.map((t=>Math.fround(t)));if(8===t.length){const[a,r,o,l]=t.subarray(2,6);if(s===a&&n===r&&e===o&&i===l)return}const{style:a}=this.container;let r;if(this.#zs){const{borderColor:t,borderWidth:e}=a;a.borderWidth=0;r=["url('data:image/svg+xml;utf8,",'',``];this.container.classList.add("hasBorder")}const o=s-e,l=n-i,{svgFactory:h}=this,d=h.createElement("svg");d.classList.add("quadrilateralsContainer");d.setAttribute("width",0);d.setAttribute("height",0);const c=h.createElement("defs");d.append(c);const u=h.createElement("clipPath"),p=`clippath_${this.data.id}`;u.setAttribute("id",p);u.setAttribute("clipPathUnits","objectBoundingBox");c.append(u);for(let i=2,s=t.length;i`)}if(this.#zs){r.push("')");a.backgroundImage=r.join("")}this.container.append(d);this.container.style.clipPath=`url(#${p})`}_createPopup(){const{data:t}=this,e=this.#Us=new PopupAnnotationElement({data:{color:t.color,titleObj:t.titleObj,modificationDate:t.modificationDate,contentsObj:t.contentsObj,richText:t.richText,parentRect:t.rect,borderStyle:0,id:`popup_${t.id}`,rotation:t.rotation},parent:this.parent,elements:[this]});this.parent.div.append(e.render())}render(){unreachable("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){const i=[];if(this._fieldObjects){const s=this._fieldObjects[t];if(s)for(const{page:t,id:n,exportValues:a}of s){if(-1===t)continue;if(n===e)continue;const s="string"==typeof a?a:null,r=document.querySelector(`[data-element-id="${n}"]`);!r||Ht.has(r)?i.push({id:n,exportValue:s,domElement:r}):warn(`_getElementsByName - element not allowed: ${n}`)}return i}for(const s of document.getElementsByName(t)){const{exportValue:t}=s,n=s.getAttribute("data-element-id");n!==e&&(Ht.has(s)&&i.push({id:n,exportValue:t,domElement:s}))}return i}show(){this.container&&(this.container.hidden=!1);this.popup?.maybeShow()}hide(){this.container&&(this.container.hidden=!0);this.popup?.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){const t=this.getElementsToTriggerPopup();if(Array.isArray(t))for(const e of t)e.classList.add("highlightArea");else t.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;const{annotationEditorType:t,data:{id:e}}=this;this.container.addEventListener("dblclick",(()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:t,editId:e})}))}}class LinkAnnotationElement extends AnnotationElement{constructor(t,e=null){super(t,{isRenderable:!0,ignoreBorder:!!e?.ignoreBorder,createQuadrilaterals:!0});this.isTooltipOnly=t.data.isTooltipOnly}render(){const{data:t,linkService:e}=this,i=document.createElement("a");i.setAttribute("data-element-id",t.id);let s=!1;if(t.url){e.addLinkAttributes(i,t.url,t.newWindow);s=!0}else if(t.action){this._bindNamedAction(i,t.action);s=!0}else if(t.attachment){this.#$s(i,t.attachment,t.attachmentDest);s=!0}else if(t.setOCGState){this.#Vs(i,t.setOCGState);s=!0}else if(t.dest){this._bindLink(i,t.dest);s=!0}else{if(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions){this._bindJSAction(i,t);s=!0}if(t.resetForm){this._bindResetFormAction(i,t.resetForm);s=!0}else if(this.isTooltipOnly&&!s){this._bindLink(i,"");s=!0}}this.container.classList.add("linkAnnotation");s&&this.container.append(i);return this.container}#js(){this.container.setAttribute("data-internal-link","")}_bindLink(t,e){t.href=this.linkService.getDestinationHash(e);t.onclick=()=>{e&&this.linkService.goToDestination(e);return!1};(e||""===e)&&this.#js()}_bindNamedAction(t,e){t.href=this.linkService.getAnchorUrl("");t.onclick=()=>{this.linkService.executeNamedAction(e);return!1};this.#js()}#$s(t,e,i=null){t.href=this.linkService.getAnchorUrl("");e.description&&(t.title=e.description);t.onclick=()=>{this.downloadManager?.openOrDownloadData(e.content,e.filename,i);return!1};this.#js()}#Vs(t,e){t.href=this.linkService.getAnchorUrl("");t.onclick=()=>{this.linkService.executeSetOCGState(e);return!1};this.#js()}_bindJSAction(t,e){t.href=this.linkService.getAnchorUrl("");const i=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const s of Object.keys(e.actions)){const n=i.get(s);n&&(t[n]=()=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e.id,name:s}});return!1})}t.onclick||(t.onclick=()=>!1);this.#js()}_bindResetFormAction(t,e){const i=t.onclick;i||(t.href=this.linkService.getAnchorUrl(""));this.#js();if(this._fieldObjects)t.onclick=()=>{i?.();const{fields:t,refs:s,include:n}=e,a=[];if(0!==t.length||0!==s.length){const e=new Set(s);for(const i of t){const t=this._fieldObjects[i]||[];for(const{id:i}of t)e.add(i)}for(const t of Object.values(this._fieldObjects))for(const i of t)e.has(i.id)===n&&a.push(i)}else for(const t of Object.values(this._fieldObjects))a.push(...t);const r=this.annotationStorage,o=[];for(const t of a){const{id:e}=t;o.push(e);switch(t.type){case"text":{const i=t.defaultValue||"";r.setValue(e,{value:i});break}case"checkbox":case"radiobutton":{const i=t.defaultValue===t.exportValues;r.setValue(e,{value:i});break}case"combobox":case"listbox":{const i=t.defaultValue||"";r.setValue(e,{value:i});break}default:continue}const i=document.querySelector(`[data-element-id="${e}"]`);i&&(Ht.has(i)?i.dispatchEvent(new Event("resetform")):warn(`_bindResetFormAction - element not allowed: ${e}`))}this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:o,name:"ResetForm"}});return!1};else{warn('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.');i||(t.onclick=()=>!1)}}}class TextAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");const t=document.createElement("img");t.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg";t.setAttribute("data-l10n-id","pdfjs-text-annotation-type");t.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name}));!this.data.popupRef&&this.hasPopupData&&this._createPopup();this.container.append(t);return this.container}}class WidgetAnnotationElement extends AnnotationElement{render(){return this.container}showElementAndHideCanvas(t){if(this.data.hasOwnCanvas){"CANVAS"===t.previousSibling?.nodeName&&(t.previousSibling.hidden=!0);t.hidden=!1}}_getKeyModifier(t){return util_FeatureTest.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,e,i,s,n){i.includes("mouse")?t.addEventListener(i,(t=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:s,value:n(t),shift:t.shiftKey,modifier:this._getKeyModifier(t)}})})):t.addEventListener(i,(t=>{if("blur"===i){if(!e.focused||!t.relatedTarget)return;e.focused=!1}else if("focus"===i){if(e.focused)return;e.focused=!0}n&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:s,value:n(t)}})}))}_setEventListeners(t,e,i,s){for(const[n,a]of i)if("Action"===a||this.data.actions?.[a]){"Focus"!==a&&"Blur"!==a||(e||={focused:!1});this._setEventListener(t,e,n,a,s);"Focus"!==a||this.data.actions?.Blur?"Blur"!==a||this.data.actions?.Focus||this._setEventListener(t,e,"focus","Focus",null):this._setEventListener(t,e,"blur","Blur",null)}}_setBackgroundColor(t){const e=this.data.backgroundColor||null;t.style.backgroundColor=null===e?"transparent":Util.makeHexColor(e[0],e[1],e[2])}_setTextStyle(t){const e=["left","center","right"],{fontColor:i}=this.data.defaultAppearanceData,s=this.data.defaultAppearanceData.fontSize||9,a=t.style;let r;const roundToOneDecimal=t=>Math.round(10*t)/10;if(this.data.multiLine){const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2),e=t/(Math.round(t/(n*s))||1);r=Math.min(s,roundToOneDecimal(e/n))}else{const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2);r=Math.min(s,roundToOneDecimal(t/n))}a.fontSize=`calc(${r}px * var(--scale-factor))`;a.color=Util.makeHexColor(i[0],i[1],i[2]);null!==this.data.textAlignment&&(a.textAlign=e[this.data.textAlignment])}_setRequired(t,e){e?t.setAttribute("required",!0):t.removeAttribute("required");t.setAttribute("aria-required",e)}}class TextWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms||t.data.hasOwnCanvas||!t.data.hasAppearance&&!!t.data.fieldValue})}setPropertyOnSiblings(t,e,i,s){const n=this.annotationStorage;for(const a of this._getElementsByName(t.name,t.id)){a.domElement&&(a.domElement[e]=i);n.setValue(a.id,{[s]:i})}}render(){const t=this.annotationStorage,e=this.data.id;this.container.classList.add("textWidgetAnnotation");let i=null;if(this.renderForms){const s=t.getValue(e,{value:this.data.fieldValue});let n=s.value||"";const a=t.getValue(e,{charLimit:this.data.maxLen}).charLimit;a&&n.length>a&&(n=n.slice(0,a));let r=s.formattedValue||this.data.textContent?.join("\n")||null;r&&this.data.comb&&(r=r.replaceAll(/\s+/g,""));const o={userValue:n,formattedValue:r,lastCommittedValue:null,commitKey:1,focused:!1};if(this.data.multiLine){i=document.createElement("textarea");i.textContent=r??n;this.data.doNotScroll&&(i.style.overflowY="hidden")}else{i=document.createElement("input");i.type="text";i.setAttribute("value",r??n);this.data.doNotScroll&&(i.style.overflowX="hidden")}this.data.hasOwnCanvas&&(i.hidden=!0);Ht.add(i);i.setAttribute("data-element-id",e);i.disabled=this.data.readOnly;i.name=this.data.fieldName;i.tabIndex=Bt;this._setRequired(i,this.data.required);a&&(i.maxLength=a);i.addEventListener("input",(s=>{t.setValue(e,{value:s.target.value});this.setPropertyOnSiblings(i,"value",s.target.value,"value");o.formattedValue=null}));i.addEventListener("resetform",(t=>{const e=this.data.defaultFieldValue??"";i.value=o.userValue=e;o.formattedValue=null}));let blurListener=t=>{const{formattedValue:e}=o;null!=e&&(t.target.value=e);t.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){i.addEventListener("focus",(t=>{if(o.focused)return;const{target:e}=t;o.userValue&&(e.value=o.userValue);o.lastCommittedValue=e.value;o.commitKey=1;this.data.actions?.Focus||(o.focused=!0)}));i.addEventListener("updatefromsandbox",(i=>{this.showElementAndHideCanvas(i.target);const s={value(i){o.userValue=i.detail.value??"";t.setValue(e,{value:o.userValue.toString()});i.target.value=o.userValue},formattedValue(i){const{formattedValue:s}=i.detail;o.formattedValue=s;null!=s&&i.target!==document.activeElement&&(i.target.value=s);t.setValue(e,{formattedValue:s})},selRange(t){t.target.setSelectionRange(...t.detail.selRange)},charLimit:i=>{const{charLimit:s}=i.detail,{target:n}=i;if(0===s){n.removeAttribute("maxLength");return}n.setAttribute("maxLength",s);let a=o.userValue;if(a&&!(a.length<=s)){a=a.slice(0,s);n.value=o.userValue=a;t.setValue(e,{value:a});this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:a,willCommit:!0,commitKey:1,selStart:n.selectionStart,selEnd:n.selectionEnd}})}}};this._dispatchEventFromSandbox(s,i)}));i.addEventListener("keydown",(t=>{o.commitKey=1;let i=-1;"Escape"===t.key?i=0:"Enter"!==t.key||this.data.multiLine?"Tab"===t.key&&(o.commitKey=3):i=2;if(-1===i)return;const{value:s}=t.target;if(o.lastCommittedValue!==s){o.lastCommittedValue=s;o.userValue=s;this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:s,willCommit:!0,commitKey:i,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}})}}));const s=blurListener;blurListener=null;i.addEventListener("blur",(t=>{if(!o.focused||!t.relatedTarget)return;this.data.actions?.Blur||(o.focused=!1);const{value:i}=t.target;o.userValue=i;o.lastCommittedValue!==i&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:i,willCommit:!0,commitKey:o.commitKey,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}});s(t)}));this.data.actions?.Keystroke&&i.addEventListener("beforeinput",(t=>{o.lastCommittedValue=null;const{data:i,target:s}=t,{value:n,selectionStart:a,selectionEnd:r}=s;let l=a,h=r;switch(t.inputType){case"deleteWordBackward":{const t=n.substring(0,a).match(/\w*[^\w]*$/);t&&(l-=t[0].length);break}case"deleteWordForward":{const t=n.substring(a).match(/^[^\w]*\w*/);t&&(h+=t[0].length);break}case"deleteContentBackward":a===r&&(l-=1);break;case"deleteContentForward":a===r&&(h+=1)}t.preventDefault();this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:n,change:i||"",willCommit:!1,selStart:l,selEnd:h}})}));this._setEventListeners(i,o,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.value))}blurListener&&i.addEventListener("blur",blurListener);if(this.data.comb){const t=(this.data.rect[2]-this.data.rect[0])/a;i.classList.add("comb");i.style.letterSpacing=`calc(${t}px * var(--scale-factor) - 1ch)`}}else{i=document.createElement("div");i.textContent=this.data.fieldValue;i.style.verticalAlign="middle";i.style.display="table-cell";this.data.hasOwnCanvas&&(i.hidden=!0)}this._setTextStyle(i);this._setBackgroundColor(i);this._setDefaultPropertiesFromJS(i);this.container.append(i);return this.container}}class SignatureWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){const t=this.annotationStorage,e=this.data,i=e.id;let s=t.getValue(i,{value:e.exportValue===e.fieldValue}).value;if("string"==typeof s){s="Off"!==s;t.setValue(i,{value:s})}this.container.classList.add("buttonWidgetAnnotation","checkBox");const n=document.createElement("input");Ht.add(n);n.setAttribute("data-element-id",i);n.disabled=e.readOnly;this._setRequired(n,this.data.required);n.type="checkbox";n.name=e.fieldName;s&&n.setAttribute("checked",!0);n.setAttribute("exportValue",e.exportValue);n.tabIndex=Bt;n.addEventListener("change",(s=>{const{name:n,checked:a}=s.target;for(const s of this._getElementsByName(n,i)){const i=a&&s.exportValue===e.exportValue;s.domElement&&(s.domElement.checked=i);t.setValue(s.id,{value:i})}t.setValue(i,{value:a})}));n.addEventListener("resetform",(t=>{const i=e.defaultFieldValue||"Off";t.target.checked=i===e.exportValue}));if(this.enableScripting&&this.hasJSActions){n.addEventListener("updatefromsandbox",(e=>{const s={value(e){e.target.checked="Off"!==e.detail.value;t.setValue(i,{value:e.target.checked})}};this._dispatchEventFromSandbox(s,e)}));this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.checked))}this._setBackgroundColor(n);this._setDefaultPropertiesFromJS(n);this.container.append(n);return this.container}}class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const t=this.annotationStorage,e=this.data,i=e.id;let s=t.getValue(i,{value:e.fieldValue===e.buttonValue}).value;if("string"==typeof s){s=s!==e.buttonValue;t.setValue(i,{value:s})}if(s)for(const s of this._getElementsByName(e.fieldName,i))t.setValue(s.id,{value:!1});const n=document.createElement("input");Ht.add(n);n.setAttribute("data-element-id",i);n.disabled=e.readOnly;this._setRequired(n,this.data.required);n.type="radio";n.name=e.fieldName;s&&n.setAttribute("checked",!0);n.tabIndex=Bt;n.addEventListener("change",(e=>{const{name:s,checked:n}=e.target;for(const e of this._getElementsByName(s,i))t.setValue(e.id,{value:!1});t.setValue(i,{value:n})}));n.addEventListener("resetform",(t=>{const i=e.defaultFieldValue;t.target.checked=null!=i&&i===e.buttonValue}));if(this.enableScripting&&this.hasJSActions){const s=e.buttonValue;n.addEventListener("updatefromsandbox",(e=>{const n={value:e=>{const n=s===e.detail.value;for(const s of this._getElementsByName(e.target.name)){const e=n&&s.id===i;s.domElement&&(s.domElement.checked=e);t.setValue(s.id,{value:e})}}};this._dispatchEventFromSandbox(n,e)}));this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.checked))}this._setBackgroundColor(n);this._setDefaultPropertiesFromJS(n);this.container.append(n);return this.container}}class PushButtonWidgetAnnotationElement extends LinkAnnotationElement{constructor(t){super(t,{ignoreBorder:t.data.hasAppearance})}render(){const t=super.render();t.classList.add("buttonWidgetAnnotation","pushButton");const e=t.lastChild;if(this.enableScripting&&this.hasJSActions&&e){this._setDefaultPropertiesFromJS(e);e.addEventListener("updatefromsandbox",(t=>{this._dispatchEventFromSandbox({},t)}))}return t}}class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");const t=this.annotationStorage,e=this.data.id,i=t.getValue(e,{value:this.data.fieldValue}),s=document.createElement("select");Ht.add(s);s.setAttribute("data-element-id",e);s.disabled=this.data.readOnly;this._setRequired(s,this.data.required);s.name=this.data.fieldName;s.tabIndex=Bt;let n=this.data.combo&&this.data.options.length>0;if(!this.data.combo){s.size=this.data.options.length;this.data.multiSelect&&(s.multiple=!0)}s.addEventListener("resetform",(t=>{const e=this.data.defaultFieldValue;for(const t of s.options)t.selected=t.value===e}));for(const t of this.data.options){const e=document.createElement("option");e.textContent=t.displayValue;e.value=t.exportValue;if(i.value.includes(t.exportValue)){e.setAttribute("selected",!0);n=!1}s.append(e)}let a=null;if(n){const t=document.createElement("option");t.value=" ";t.setAttribute("hidden",!0);t.setAttribute("selected",!0);s.prepend(t);a=()=>{t.remove();s.removeEventListener("input",a);a=null};s.addEventListener("input",a)}const getValue=t=>{const e=t?"value":"textContent",{options:i,multiple:n}=s;return n?Array.prototype.filter.call(i,(t=>t.selected)).map((t=>t[e])):-1===i.selectedIndex?null:i[i.selectedIndex][e]};let r=getValue(!1);const getItems=t=>{const e=t.target.options;return Array.prototype.map.call(e,(t=>({displayValue:t.textContent,exportValue:t.value})))};if(this.enableScripting&&this.hasJSActions){s.addEventListener("updatefromsandbox",(i=>{const n={value(i){a?.();const n=i.detail.value,o=new Set(Array.isArray(n)?n:[n]);for(const t of s.options)t.selected=o.has(t.value);t.setValue(e,{value:getValue(!0)});r=getValue(!1)},multipleSelection(t){s.multiple=!0},remove(i){const n=s.options,a=i.detail.remove;n[a].selected=!1;s.remove(a);if(n.length>0){-1===Array.prototype.findIndex.call(n,(t=>t.selected))&&(n[0].selected=!0)}t.setValue(e,{value:getValue(!0),items:getItems(i)});r=getValue(!1)},clear(i){for(;0!==s.length;)s.remove(0);t.setValue(e,{value:null,items:[]});r=getValue(!1)},insert(i){const{index:n,displayValue:a,exportValue:o}=i.detail.insert,l=s.children[n],h=document.createElement("option");h.textContent=a;h.value=o;l?l.before(h):s.append(h);t.setValue(e,{value:getValue(!0),items:getItems(i)});r=getValue(!1)},items(i){const{items:n}=i.detail;for(;0!==s.length;)s.remove(0);for(const t of n){const{displayValue:e,exportValue:i}=t,n=document.createElement("option");n.textContent=e;n.value=i;s.append(n)}s.options.length>0&&(s.options[0].selected=!0);t.setValue(e,{value:getValue(!0),items:getItems(i)});r=getValue(!1)},indices(i){const s=new Set(i.detail.indices);for(const t of i.target.options)t.selected=s.has(t.index);t.setValue(e,{value:getValue(!0)});r=getValue(!1)},editable(t){t.target.disabled=!t.detail.editable}};this._dispatchEventFromSandbox(n,i)}));s.addEventListener("input",(i=>{const s=getValue(!0),n=getValue(!1);t.setValue(e,{value:s});i.preventDefault();this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:r,change:n,changeEx:s,willCommit:!1,commitKey:1,keyDown:!1}})}));this._setEventListeners(s,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],(t=>t.target.value))}else s.addEventListener("input",(function(i){t.setValue(e,{value:getValue(!0)})}));this.data.combo&&this._setTextStyle(s);this._setBackgroundColor(s);this._setDefaultPropertiesFromJS(s);this.container.append(s);return this.container}}class PopupAnnotationElement extends AnnotationElement{constructor(t){const{data:e,elements:i}=t;super(t,{isRenderable:AnnotationElement._hasPopupData(e)});this.elements=i;this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new PopupElement({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate,contentsObj:this.data.contentsObj,richText:this.data.richText,rect:this.data.rect,parentRect:this.data.parentRect||null,parent:this.parent,elements:this.elements,open:this.data.open}),e=[];for(const i of this.elements){i.popup=t;i.container.ariaHasPopup="dialog";e.push(i.data.id);i.addHighlightArea()}this.container.setAttribute("aria-controls",e.map((t=>`${et}${t}`)).join(","));return this.container}}class PopupElement{#Ws=this.#qs.bind(this);#Xs=this.#Ks.bind(this);#Ys=this.#Qs.bind(this);#Js=this.#Zs.bind(this);#tn=null;#pt=null;#en=null;#in=null;#sn=null;#nn=null;#an=null;#rn=!1;#on=null;#C=null;#ln=null;#hn=null;#dn=null;#Hs=null;#cn=!1;constructor({container:t,color:e,elements:i,titleObj:s,modificationDate:n,contentsObj:a,richText:r,parent:o,rect:l,parentRect:h,open:d}){this.#pt=t;this.#dn=s;this.#en=a;this.#hn=r;this.#nn=o;this.#tn=e;this.#ln=l;this.#an=h;this.#sn=i;this.#in=PDFDateString.toDateObject(n);this.trigger=i.flatMap((t=>t.getElementsToTriggerPopup()));for(const t of this.trigger){t.addEventListener("click",this.#Js);t.addEventListener("mouseenter",this.#Ys);t.addEventListener("mouseleave",this.#Xs);t.classList.add("popupTriggerArea")}for(const t of i)t.container?.addEventListener("keydown",this.#Ws);this.#pt.hidden=!0;d&&this.#Zs()}render(){if(this.#on)return;const t=this.#on=document.createElement("div");t.className="popup";if(this.#tn){const e=t.style.outlineColor=Util.makeHexColor(...this.#tn);if(CSS.supports("background-color","color-mix(in srgb, red 30%, white)"))t.style.backgroundColor=`color-mix(in srgb, ${e} 30%, white)`;else{const e=.7;t.style.backgroundColor=Util.makeHexColor(...this.#tn.map((t=>Math.floor(e*(255-t)+t))))}}const e=document.createElement("span");e.className="header";const i=document.createElement("h1");e.append(i);({dir:i.dir,str:i.textContent}=this.#dn);t.append(e);if(this.#in){const t=document.createElement("span");t.classList.add("popupDate");t.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string");t.setAttribute("data-l10n-args",JSON.stringify({dateObj:this.#in.valueOf()}));e.append(t)}const s=this.#un;if(s){XfaLayer.render({xfaHtml:s,intent:"richText",div:t});t.lastChild.classList.add("richText","popupContent")}else{const e=this._formatContents(this.#en);t.append(e)}this.#pt.append(t)}get#un(){const t=this.#hn,e=this.#en;return!t?.str||e?.str&&e.str!==t.str?null:this.#hn.html||null}get#pn(){return this.#un?.attributes?.style?.fontSize||0}get#gn(){return this.#un?.attributes?.style?.color||null}#mn(t){const e=[],i={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},s={style:{color:this.#gn,fontSize:this.#pn?`calc(${this.#pn}px * var(--scale-factor))`:""}};for(const i of t.split("\n"))e.push({name:"span",value:i,attributes:s});return i}_formatContents({str:t,dir:e}){const i=document.createElement("p");i.classList.add("popupContent");i.dir=e;const s=t.split(/(?:\r\n?|\n)/);for(let t=0,e=s.length;t=0&&n.setAttribute("stroke-width",e||1);if(i)for(let t=0,e=this.#xn.length;t{"Enter"===t.key&&(s?t.metaKey:t.ctrlKey)&&this.#Sn()}));!e.popupRef&&this.hasPopupData?this._createPopup():i.classList.add("popupTriggerArea");t.append(i);return t}getElementsToTriggerPopup(){return this.#En}addHighlightArea(){this.container.classList.add("highlightArea")}#Sn(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}}class AnnotationLayer{#Cn=null;#Tn=null;#Mn=new Map;#Pn=null;constructor({div:t,accessibilityManager:e,annotationCanvasMap:i,annotationEditorUIManager:s,page:n,viewport:a,structTreeLayer:r}){this.div=t;this.#Cn=e;this.#Tn=i;this.#Pn=r||null;this.page=n;this.viewport=a;this.zIndex=0;this._annotationEditorUIManager=s}hasEditableAnnotations(){return this.#Mn.size>0}async#Dn(t,e){const i=t.firstChild||t,s=i.id=`${et}${e}`,n=await(this.#Pn?.getAriaAttributes(s));if(n)for(const[t,e]of n)i.setAttribute(t,e);this.div.append(t);this.#Cn?.moveElementInDOM(this.div,t,i,!1)}async render(t){const{annotations:e}=t,i=this.div;setLayerDimensions(i,this.viewport);const s=new Map,n={data:null,layer:i,linkService:t.linkService,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:!1!==t.renderForms,svgFactory:new DOMSVGFactory,annotationStorage:t.annotationStorage||new AnnotationStorage,enableScripting:!0===t.enableScripting,hasJSActions:t.hasJSActions,fieldObjects:t.fieldObjects,parent:this,elements:null};for(const t of e){if(t.noHTML)continue;const e=t.annotationType===H;if(e){const e=s.get(t.id);if(!e)continue;n.elements=e}else{const{width:e,height:i}=getRectDims(t.rect);if(e<=0||i<=0)continue}n.data=t;const i=AnnotationElementFactory.create(n);if(!i.isRenderable)continue;if(!e&&t.popupRef){const e=s.get(t.popupRef);e?e.push(i):s.set(t.popupRef,[i])}const a=i.render();t.hidden&&(a.style.visibility="hidden");await this.#Dn(a,t.id);if(i._isEditable){this.#Mn.set(i.data.id,i);this._annotationEditorUIManager?.renderAnnotationElement(i)}}this.#kn()}update({viewport:t}){const e=this.div;this.viewport=t;setLayerDimensions(e,{rotation:t.rotation});this.#kn();e.hidden=!1}#kn(){if(!this.#Tn)return;const t=this.div;for(const[e,i]of this.#Tn){const s=t.querySelector(`[data-annotation-id="${e}"]`);if(!s)continue;i.className="annotationContent";const{firstChild:n}=s;n?"CANVAS"===n.nodeName?n.replaceWith(i):n.classList.contains("annotationContent")?n.after(i):n.before(i):s.append(i)}this.#Tn.clear()}getEditableAnnotations(){return Array.from(this.#Mn.values())}getEditableAnnotation(t){return this.#Mn.get(t)}}const zt=/\r\n?|\n/g;class FreeTextEditor extends AnnotationEditor{#tn;#Rn="";#In=`${this.id}-editor`;#Fn=null;#pn;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){const t=FreeTextEditor.prototype,arrowChecker=t=>t.isEmpty(),e=AnnotationEditorUIManager.TRANSLATE_SMALL,i=AnnotationEditorUIManager.TRANSLATE_BIG;return shadow(this,"_keyboardManager",new KeyboardManager([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],t.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],t.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],t._translateEmpty,{args:[-e,0],checker:arrowChecker}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t._translateEmpty,{args:[-i,0],checker:arrowChecker}],[["ArrowRight","mac+ArrowRight"],t._translateEmpty,{args:[e,0],checker:arrowChecker}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t._translateEmpty,{args:[i,0],checker:arrowChecker}],[["ArrowUp","mac+ArrowUp"],t._translateEmpty,{args:[0,-e],checker:arrowChecker}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t._translateEmpty,{args:[0,-i],checker:arrowChecker}],[["ArrowDown","mac+ArrowDown"],t._translateEmpty,{args:[0,e],checker:arrowChecker}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t._translateEmpty,{args:[0,i],checker:arrowChecker}]]))}static _type="freetext";static _editorType=g.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"});this.#tn=t.color||FreeTextEditor._defaultColor||AnnotationEditor._defaultLineColor;this.#pn=t.fontSize||FreeTextEditor._defaultFontSize}static initialize(t,e){AnnotationEditor.initialize(t,e);const i=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(i.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,e){switch(t){case m.FREETEXT_SIZE:FreeTextEditor._defaultFontSize=e;break;case m.FREETEXT_COLOR:FreeTextEditor._defaultColor=e}}updateParams(t,e){switch(t){case m.FREETEXT_SIZE:this.#Ln(e);break;case m.FREETEXT_COLOR:this.#On(e)}}static get defaultPropertiesToUpdate(){return[[m.FREETEXT_SIZE,FreeTextEditor._defaultFontSize],[m.FREETEXT_COLOR,FreeTextEditor._defaultColor||AnnotationEditor._defaultLineColor]]}get propertiesToUpdate(){return[[m.FREETEXT_SIZE,this.#pn],[m.FREETEXT_COLOR,this.#tn]]}#Ln(t){const setFontsize=t=>{this.editorDiv.style.fontSize=`calc(${t}px * var(--scale-factor))`;this.translate(0,-(t-this.#pn)*this.parentScale);this.#pn=t;this.#Nn()},e=this.#pn;this.addCommands({cmd:setFontsize.bind(this,t),undo:setFontsize.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:m.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}#On(t){const setColor=t=>{this.#tn=this.editorDiv.style.color=t},e=this.#tn;this.addCommands({cmd:setColor.bind(this,t),undo:setColor.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:m.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(t,e){this._uiManager.translateSelectedEditors(t,e,!0)}getInitialTranslation(){const t=this.parentScale;return[-FreeTextEditor._internalPadding*t,-(FreeTextEditor._internalPadding+this.#pn)*t]}rebuild(){if(this.parent){super.rebuild();null!==this.div&&(this.isAttachedToDOM||this.parent.add(this))}}enableEditMode(){if(this.isInEditMode())return;this.parent.setEditingState(!1);this.parent.updateToolbar(g.FREETEXT);super.enableEditMode();this.overlayDiv.classList.remove("enabled");this.editorDiv.contentEditable=!0;this._isDraggable=!1;this.div.removeAttribute("aria-activedescendant");this.#Fn=new AbortController;const t=this._uiManager.combinedSignal(this.#Fn);this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:t});this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:t});this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:t});this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:t});this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:t})}disableEditMode(){if(this.isInEditMode()){this.parent.setEditingState(!0);super.disableEditMode();this.overlayDiv.classList.add("enabled");this.editorDiv.contentEditable=!1;this.div.setAttribute("aria-activedescendant",this.#In);this._isDraggable=!0;this.#Fn?.abort();this.#Fn=null;this.div.focus({preventScroll:!0});this.isEditing=!1;this.parent.div.classList.add("freetextEditing")}}focusin(t){if(this._focusEventsAllowed){super.focusin(t);t.target!==this.editorDiv&&this.editorDiv.focus()}}onceAdded(t){if(!this.width){this.enableEditMode();t&&this.editorDiv.focus();this._initialOptions?.isCentered&&this.center();this._initialOptions=null}}isEmpty(){return!this.editorDiv||""===this.editorDiv.innerText.trim()}remove(){this.isEditing=!1;if(this.parent){this.parent.setEditingState(!0);this.parent.div.classList.add("freetextEditing")}super.remove()}#Bn(){const t=[];this.editorDiv.normalize();let e=null;for(const i of this.editorDiv.childNodes)if(e?.nodeType!==Node.TEXT_NODE||"BR"!==i.nodeName){t.push(FreeTextEditor.#Hn(i));e=i}return t.join("\n")}#Nn(){const[t,e]=this.parentDimensions;let i;if(this.isAttachedToDOM)i=this.div.getBoundingClientRect();else{const{currentLayer:t,div:e}=this,s=e.style.display,n=e.classList.contains("hidden");e.classList.remove("hidden");e.style.display="hidden";t.div.append(this.div);i=e.getBoundingClientRect();e.remove();e.style.display=s;e.classList.toggle("hidden",n)}if(this.rotation%180==this.parentRotation%180){this.width=i.width/t;this.height=i.height/e}else{this.width=i.height/t;this.height=i.width/e}this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit();this.disableEditMode();const t=this.#Rn,e=this.#Rn=this.#Bn().trimEnd();if(t===e)return;const setText=t=>{this.#Rn=t;if(t){this.#zn();this._uiManager.rebuild(this);this.#Nn()}else this.remove()};this.addCommands({cmd:()=>{setText(e)},undo:()=>{setText(t)},mustExec:!1});this.#Nn()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode();this.editorDiv.focus()}dblclick(t){this.enterInEditMode()}keydown(t){if(t.target===this.div&&"Enter"===t.key){this.enterInEditMode();t.preventDefault()}}editorDivKeydown(t){FreeTextEditor._keyboardManager.exec(this,t)}editorDivFocus(t){this.isEditing=!0}editorDivBlur(t){this.isEditing=!1}editorDivInput(t){this.parent.div.classList.toggle("freetextEditing",this.isEmpty())}disableEditing(){this.editorDiv.setAttribute("role","comment");this.editorDiv.removeAttribute("aria-multiline")}enableEditing(){this.editorDiv.setAttribute("role","textbox");this.editorDiv.setAttribute("aria-multiline",!0)}render(){if(this.div)return this.div;let t,e;if(this.width){t=this.x;e=this.y}super.render();this.editorDiv=document.createElement("div");this.editorDiv.className="internal";this.editorDiv.setAttribute("id",this.#In);this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text2");this.editorDiv.setAttribute("data-l10n-attrs","default-content");this.enableEditing();this.editorDiv.contentEditable=!0;const{style:i}=this.editorDiv;i.fontSize=`calc(${this.#pn}px * var(--scale-factor))`;i.color=this.#tn;this.div.append(this.editorDiv);this.overlayDiv=document.createElement("div");this.overlayDiv.classList.add("overlay","enabled");this.div.append(this.overlayDiv);bindEvents(this,this.div,["dblclick","keydown"]);if(this.width){const[i,s]=this.parentDimensions;if(this.annotationElementId){const{position:n}=this._initialData;let[a,r]=this.getInitialTranslation();[a,r]=this.pageTranslationToScreen(a,r);const[o,l]=this.pageDimensions,[h,d]=this.pageTranslation;let c,u;switch(this.rotation){case 0:c=t+(n[0]-h)/o;u=e+this.height-(n[1]-d)/l;break;case 90:c=t+(n[0]-h)/o;u=e-(n[1]-d)/l;[a,r]=[r,-a];break;case 180:c=t-this.width+(n[0]-h)/o;u=e-(n[1]-d)/l;[a,r]=[-a,-r];break;case 270:c=t+(n[0]-h-this.height*l)/o;u=e+(n[1]-d-this.width*o)/l;[a,r]=[-r,a]}this.setAt(c*i,u*s,a,r)}else this.setAt(t*i,e*s,this.width*i,this.height*s);this.#zn();this._isDraggable=!0;this.editorDiv.contentEditable=!1}else{this._isDraggable=!1;this.editorDiv.contentEditable=!0}return this.div}static#Hn(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(zt,"")}editorDivPaste(t){const e=t.clipboardData||window.clipboardData,{types:i}=e;if(1===i.length&&"text/plain"===i[0])return;t.preventDefault();const s=FreeTextEditor.#Un(e.getData("text")||"").replaceAll(zt,"\n");if(!s)return;const n=window.getSelection();if(!n.rangeCount)return;this.editorDiv.normalize();n.deleteFromDocument();const a=n.getRangeAt(0);if(!s.includes("\n")){a.insertNode(document.createTextNode(s));this.editorDiv.normalize();n.collapseToStart();return}const{startContainer:r,startOffset:o}=a,l=[],h=[];if(r.nodeType===Node.TEXT_NODE){const t=r.parentElement;h.push(r.nodeValue.slice(o).replaceAll(zt,""));if(t!==this.editorDiv){let e=l;for(const i of this.editorDiv.childNodes)i!==t?e.push(FreeTextEditor.#Hn(i)):e=h}l.push(r.nodeValue.slice(0,o).replaceAll(zt,""))}else if(r===this.editorDiv){let t=l,e=0;for(const i of this.editorDiv.childNodes){e++===o&&(t=h);t.push(FreeTextEditor.#Hn(i))}}this.#Rn=`${l.join("\n")}${s}${h.join("\n")}`;this.#zn();const d=new Range;let c=l.reduce(((t,e)=>t+e.length),0);for(const{firstChild:t}of this.editorDiv.childNodes)if(t.nodeType===Node.TEXT_NODE){const e=t.nodeValue.length;if(c<=e){d.setStart(t,c);d.setEnd(t,c);break}c-=e}n.removeAllRanges();n.addRange(d)}#zn(){this.editorDiv.replaceChildren();if(this.#Rn)for(const t of this.#Rn.split("\n")){const e=document.createElement("div");e.append(t?document.createTextNode(t):document.createElement("br"));this.editorDiv.append(e)}}#Gn(){return this.#Rn.replaceAll(" "," ")}static#Un(t){return t.replaceAll(" "," ")}get contentDiv(){return this.editorDiv}static async deserialize(t,e,i){let s=null;if(t instanceof FreeTextAnnotationElement){const{data:{defaultAppearanceData:{fontSize:e,fontColor:i},rect:n,rotation:a,id:r,popupRef:o},textContent:l,textPosition:h,parent:{page:{pageNumber:d}}}=t;if(!l||0===l.length)return null;s=t={annotationType:g.FREETEXT,color:Array.from(i),fontSize:e,value:l.join("\n"),position:h,pageIndex:d-1,rect:n.slice(0),rotation:a,id:r,deleted:!1,popupRef:o}}const n=await super.deserialize(t,e,i);n.#pn=t.fontSize;n.#tn=Util.makeHexColor(...t.color);n.#Rn=FreeTextEditor.#Un(t.value);n.annotationElementId=t.id||null;n._initialData=s;return n}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const e=FreeTextEditor._internalPadding*this.parentScale,i=this.getRect(e,e),s=AnnotationEditor._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.#tn),n={annotationType:g.FREETEXT,color:s,fontSize:this.#pn,value:this.#Gn(),pageIndex:this.pageIndex,rect:i,rotation:this.rotation,structTreeParentId:this._structTreeParentId};if(t)return n;if(this.annotationElementId&&!this.#$n(n))return null;n.id=this.annotationElementId;return n}#$n(t){const{value:e,fontSize:i,color:s,pageIndex:n}=this._initialData;return this._hasBeenMoved||t.value!==e||t.fontSize!==i||t.color.some(((t,e)=>t!==s[e]))||t.pageIndex!==n}renderAnnotationElement(t){const e=super.renderAnnotationElement(t);if(this.deleted)return e;const{style:i}=e;i.fontSize=`calc(${this.#pn}px * var(--scale-factor))`;i.color=this.#tn;e.replaceChildren();for(const t of this.#Rn.split("\n")){const i=document.createElement("div");i.append(t?document.createTextNode(t):document.createElement("br"));e.append(i)}const s=FreeTextEditor._internalPadding*this.parentScale;t.updateEdited({rect:this.getRect(s,s),popupContent:this.#Rn});return e}resetAnnotationElement(t){super.resetAnnotationElement(t);t.resetEdited()}}class Outline{static PRECISION=1e-4;toSVGPath(){unreachable("Abstract method `toSVGPath` must be implemented.")}get box(){unreachable("Abstract getter `box` must be implemented.")}serialize(t,e){unreachable("Abstract method `serialize` must be implemented.")}static _rescale(t,e,i,s,n,a){a||=new Float32Array(t.length);for(let r=0,o=t.length;r=6;t-=6)isNaN(e[t])?i.push(`L${e[t+4]} ${e[t+5]}`):i.push(`C${e[t]} ${e[t+1]} ${e[t+2]} ${e[t+3]} ${e[t+4]} ${e[t+5]}`);this.#ha(i);return i.join(" ")}#oa(){const[t,e,i,s]=this.#Vn,[n,a,r,o]=this.#ra();return`M${(this.#Kn[2]-t)/i} ${(this.#Kn[3]-e)/s} L${(this.#Kn[4]-t)/i} ${(this.#Kn[5]-e)/s} L${n} ${a} L${r} ${o} L${(this.#Kn[16]-t)/i} ${(this.#Kn[17]-e)/s} L${(this.#Kn[14]-t)/i} ${(this.#Kn[15]-e)/s} Z`}#ha(t){const e=this.#jn;t.push(`L${e[4]} ${e[5]} Z`)}#la(t){const[e,i,s,n]=this.#Vn,a=this.#Kn.subarray(4,6),r=this.#Kn.subarray(16,18),[o,l,h,d]=this.#ra();t.push(`L${(a[0]-e)/s} ${(a[1]-i)/n} L${o} ${l} L${h} ${d} L${(r[0]-e)/s} ${(r[1]-i)/n}`)}newFreeDrawOutline(t,e,i,s,n,a){return new FreeDrawOutline(t,e,i,s,n,a)}getOutlines(){const t=this.#Xn,e=this.#jn,i=this.#Kn,[s,n,a,r]=this.#Vn,o=new Float32Array((this.#ia?.length??0)+2);for(let t=0,e=o.length-2;t=6;t-=6)for(let i=0;i<6;i+=2)if(isNaN(e[t+i])){l[h]=l[h+1]=NaN;h+=2}else{l[h]=e[t+i];l[h+1]=e[t+i+1];h+=2}this.#ua(l,h);return this.newFreeDrawOutline(l,o,this.#Vn,this.#ta,this.#Wn,this.#qn)}#da(t){const e=this.#Kn,[i,s,n,a]=this.#Vn,[r,o,l,h]=this.#ra(),d=new Float32Array(36);d.set([NaN,NaN,NaN,NaN,(e[2]-i)/n,(e[3]-s)/a,NaN,NaN,NaN,NaN,(e[4]-i)/n,(e[5]-s)/a,NaN,NaN,NaN,NaN,r,o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,(e[16]-i)/n,(e[17]-s)/a,NaN,NaN,NaN,NaN,(e[14]-i)/n,(e[15]-s)/a],0);return this.newFreeDrawOutline(d,t,this.#Vn,this.#ta,this.#Wn,this.#qn)}#ua(t,e){const i=this.#jn;t.set([NaN,NaN,NaN,NaN,i[4],i[5]],e);return e+6}#ca(t,e){const i=this.#Kn.subarray(4,6),s=this.#Kn.subarray(16,18),[n,a,r,o]=this.#Vn,[l,h,d,c]=this.#ra();t.set([NaN,NaN,NaN,NaN,(i[0]-n)/r,(i[1]-a)/o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,d,c,NaN,NaN,NaN,NaN,(s[0]-n)/r,(s[1]-a)/o],e);return e+24}}class FreeDrawOutline extends Outline{#Vn;#pa=new Float32Array(4);#Wn;#qn;#ia;#ta;#ga;constructor(t,e,i,s,n,a){super();this.#ga=t;this.#ia=e;this.#Vn=i;this.#ta=s;this.#Wn=n;this.#qn=a;this.lastPoint=[NaN,NaN];this.#ma(a);const[r,o,l,h]=this.#pa;for(let e=0,i=t.length;et[0]-e[0]||t[1]-e[1]||t[2]-e[2]));const t=[];for(const e of this.#ba)if(e[3]){t.push(...this.#wa(e));this.#va(e)}else{this.#ya(e);t.push(...this.#wa(e))}return this.#xa(t)}#xa(t){const e=[],i=new Set;for(const i of t){const[t,s,n]=i;e.push([t,s,i],[t,n,i])}e.sort(((t,e)=>t[1]-e[1]||t[0]-e[0]));for(let t=0,s=e.length;t0;){const t=i.values().next().value;let[e,a,r,o,l]=t;i.delete(t);let h=e,d=a;n=[e,r];s.push(n);for(;;){let t;if(i.has(o))t=o;else{if(!i.has(l))break;t=l}i.delete(t);[e,a,r,o,l]=t;if(h!==e){n.push(h,d,e,d===a?a:r);h=e}d=d===a?r:a}n.push(h,d)}return new HighlightOutline(s,this.#Vn,this.#fa)}#_a(t){const e=this.#Aa;let i=0,s=e.length-1;for(;i<=s;){const n=i+s>>1,a=e[n][0];if(a===t)return n;a=0;s--){const[i,n]=this.#Aa[s];if(i!==t)break;if(i===t&&n===e){this.#Aa.splice(s,1);return}}}#wa(t){const[e,i,s]=t,n=[[e,i,s]],a=this.#_a(s);for(let t=0;t=i)if(o>s)n[t][1]=s;else{if(1===a)return[];n.splice(t,1);t--;a--}else{n[t][2]=i;o>s&&n.push([e,s,o])}}}return n}}class HighlightOutline extends Outline{#Vn;#Ea;constructor(t,e,i){super();this.#Ea=t;this.#Vn=e;this.lastPoint=i}toSVGPath(){const t=[];for(const e of this.#Ea){let[i,s]=e;t.push(`M${i} ${s}`);for(let n=2;n-1){this.#Xa=!0;this.#Za(t);this.#tr()}else if(this.#Ua){this.#Ha=t.anchorNode;this.#za=t.anchorOffset;this.#Va=t.focusNode;this.#ja=t.focusOffset;this.#er();this.#tr();this.rotate(this.rotation)}}get telemetryInitialData(){return{action:"added",type:this.#Xa?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:this.#ea,methodOfCreation:this.#Ja}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#er(){const t=new HighlightOutliner(this.#Ua,.001);this.#qa=t.getOutlines();[this.x,this.y,this.width,this.height]=this.#qa.box;const e=new HighlightOutliner(this.#Ua,.0025,.001,"ltr"===this._uiManager.direction);this.#$a=e.getOutlines();const{lastPoint:i}=this.#$a;this.#fa=[(i[0]-this.x)/this.width,(i[1]-this.y)/this.height]}#Za({highlightOutlines:t,highlightId:e,clipPathId:i}){this.#qa=t;this.#$a=t.getNewOutline(this.#ea/2+1.5,.0025);if(e>=0){this.#w=e;this.#Ga=i;this.parent.drawLayer.finalizeDraw(e,{bbox:t.box,path:{d:t.toSVGPath()}});this.#Ya=this.parent.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:!0},bbox:this.#$a.box,path:{d:this.#$a.toSVGPath()}},!0)}else if(this.parent){const e=this.parent.viewport.rotation;this.parent.drawLayer.updateProperties(this.#w,{bbox:HighlightEditor.#ir(this.#qa.box,(e-this.rotation+360)%360),path:{d:t.toSVGPath()}});this.parent.drawLayer.updateProperties(this.#Ya,{bbox:HighlightEditor.#ir(this.#$a.box,e),path:{d:this.#$a.toSVGPath()}})}const[s,n,a,r]=t.box;switch(this.rotation){case 0:this.x=s;this.y=n;this.width=a;this.height=r;break;case 90:{const[t,e]=this.parentDimensions;this.x=n;this.y=1-s;this.width=a*e/t;this.height=r*t/e;break}case 180:this.x=1-s;this.y=1-n;this.width=a;this.height=r;break;case 270:{const[t,e]=this.parentDimensions;this.x=1-n;this.y=s;this.width=a*e/t;this.height=r*t/e;break}}const{lastPoint:o}=this.#$a;this.#fa=[(o[0]-s)/a,(o[1]-n)/r]}static initialize(t,e){AnnotationEditor.initialize(t,e);HighlightEditor._defaultColor||=e.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,e){switch(t){case m.HIGHLIGHT_DEFAULT_COLOR:HighlightEditor._defaultColor=e;break;case m.HIGHLIGHT_THICKNESS:HighlightEditor._defaultThickness=e}}translateInPage(t,e){}get toolbarPosition(){return this.#fa}updateParams(t,e){switch(t){case m.HIGHLIGHT_COLOR:this.#On(e);break;case m.HIGHLIGHT_THICKNESS:this.#sr(e)}}static get defaultPropertiesToUpdate(){return[[m.HIGHLIGHT_DEFAULT_COLOR,HighlightEditor._defaultColor],[m.HIGHLIGHT_THICKNESS,HighlightEditor._defaultThickness]]}get propertiesToUpdate(){return[[m.HIGHLIGHT_COLOR,this.color||HighlightEditor._defaultColor],[m.HIGHLIGHT_THICKNESS,this.#ea||HighlightEditor._defaultThickness],[m.HIGHLIGHT_FREE,this.#Xa]]}#On(t){const setColorAndOpacity=(t,e)=>{this.color=t;this.#Ka=e;this.parent?.drawLayer.updateProperties(this.#w,{root:{fill:t,"fill-opacity":e}});this.#n?.updateColor(t)},e=this.color,i=this.#Ka;this.addCommands({cmd:setColorAndOpacity.bind(this,t,HighlightEditor._defaultOpacity),undo:setColorAndOpacity.bind(this,e,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:m.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0});this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(t)},!0)}#sr(t){const e=this.#ea,setThickness=t=>{this.#ea=t;this.#nr(t)};this.addCommands({cmd:setThickness.bind(this,t),undo:setThickness.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:m.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0});this._reportTelemetry({action:"thickness_changed",thickness:t},!0)}async addEditToolbar(){const t=await super.addEditToolbar();if(!t)return null;if(this._uiManager.highlightColors){this.#n=new ColorPicker({editor:this});t.addColorPicker(this.#n)}return t}disableEditing(){super.disableEditing();this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing();this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#ar())}getBaseTranslation(){return[0,0]}getRect(t,e){return super.getRect(t,e,this.#ar())}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this);t&&this.div.focus()}remove(){this.#rr();this._reportTelemetry({action:"deleted"});super.remove()}rebuild(){if(this.parent){super.rebuild();if(null!==this.div){this.#tr();this.isAttachedToDOM||this.parent.add(this)}}}setParent(t){let e=!1;if(this.parent&&!t)this.#rr();else if(t){this.#tr(t);e=!this.parent&&this.div?.classList.contains("selectedEditor")}super.setParent(t);this.show(this._isVisible);e&&this.select()}#nr(t){if(!this.#Xa)return;this.#Za({highlightOutlines:this.#qa.getNewOutline(t/2)});this.fixAndSetPosition();const[e,i]=this.parentDimensions;this.setDims(this.width*e,this.height*i)}#rr(){if(null!==this.#w&&this.parent){this.parent.drawLayer.remove(this.#w);this.#w=null;this.parent.drawLayer.remove(this.#Ya);this.#Ya=null}}#tr(t=this.parent){if(null===this.#w){({id:this.#w,clipPathId:this.#Ga}=t.drawLayer.draw({bbox:this.#qa.box,root:{viewBox:"0 0 1 1",fill:this.color,"fill-opacity":this.#Ka},rootClass:{highlight:!0,free:this.#Xa},path:{d:this.#qa.toSVGPath()}},!1,!0));this.#Ya=t.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:this.#Xa},bbox:this.#$a.box,path:{d:this.#$a.toSVGPath()}},this.#Xa);this.#Wa&&(this.#Wa.style.clipPath=this.#Ga)}}static#ir([t,e,i,s],n){switch(n){case 90:return[1-e-s,t,s,i];case 180:return[1-t-i,1-e-s,i,s];case 270:return[e,1-t-i,s,i]}return[t,e,i,s]}rotate(t){const{drawLayer:e}=this.parent;let i;if(this.#Xa){t=(t-this.rotation+360)%360;i=HighlightEditor.#ir(this.#qa.box,t)}else i=HighlightEditor.#ir([this.x,this.y,this.width,this.height],t);e.updateProperties(this.#w,{bbox:i,root:{"data-main-rotation":t}});e.updateProperties(this.#Ya,{bbox:HighlightEditor.#ir(this.#$a.box,t),root:{"data-main-rotation":t}})}render(){if(this.div)return this.div;const t=super.render();if(this.#Qa){t.setAttribute("aria-label",this.#Qa);t.setAttribute("role","mark")}this.#Xa?t.classList.add("free"):this.div.addEventListener("keydown",this.#or.bind(this),{signal:this._uiManager._signal});const e=this.#Wa=document.createElement("div");t.append(e);e.setAttribute("aria-hidden","true");e.className="internal";e.style.clipPath=this.#Ga;const[i,s]=this.parentDimensions;this.setDims(this.width*i,this.height*s);bindEvents(this,this.#Wa,["pointerover","pointerleave"]);this.enableEditing();return t}pointerover(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#Ya,{rootClass:{hovered:!0}})}pointerleave(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#Ya,{rootClass:{hovered:!1}})}#or(t){HighlightEditor._keyboardManager.exec(this,t)}_moveCaret(t){this.parent.unselect(this);switch(t){case 0:case 2:this.#lr(!0);break;case 1:case 3:this.#lr(!1)}}#lr(t){if(!this.#Ha)return;const e=window.getSelection();t?e.setPosition(this.#Ha,this.#za):e.setPosition(this.#Va,this.#ja)}select(){super.select();this.#Ya&&this.parent?.drawLayer.updateProperties(this.#Ya,{rootClass:{hovered:!1,selected:!0}})}unselect(){super.unselect();if(this.#Ya){this.parent?.drawLayer.updateProperties(this.#Ya,{rootClass:{selected:!1}});this.#Xa||this.#lr(!1)}}get _mustFixPosition(){return!this.#Xa}show(t=this._isVisible){super.show(t);if(this.parent){this.parent.drawLayer.updateProperties(this.#w,{rootClass:{hidden:!t}});this.parent.drawLayer.updateProperties(this.#Ya,{rootClass:{hidden:!t}})}}#ar(){return this.#Xa?this.rotation:0}#hr(){if(this.#Xa)return null;const[t,e]=this.pageDimensions,[i,s]=this.pageTranslation,n=this.#Ua,a=new Float32Array(8*n.length);let r=0;for(const{x:o,y:l,width:h,height:d}of n){const n=o*t+i,c=(1-l)*e+s;a[r]=a[r+4]=n;a[r+1]=a[r+3]=c;a[r+2]=a[r+6]=n+h*t;a[r+5]=a[r+7]=c-d*e;r+=8}return a}#dr(t){return this.#qa.serialize(t,this.#ar())}static startHighlighting(t,e,{target:i,x:s,y:n}){const{x:a,y:r,width:o,height:l}=i.getBoundingClientRect(),h=new AbortController,d=t.combinedSignal(h),pointerUpCallback=e=>{h.abort();this.#cr(t,e)};window.addEventListener("blur",pointerUpCallback,{signal:d});window.addEventListener("pointerup",pointerUpCallback,{signal:d});window.addEventListener("pointerdown",stopEvent,{capture:!0,passive:!1,signal:d});window.addEventListener("contextmenu",noContextMenu,{signal:d});i.addEventListener("pointermove",this.#ur.bind(this,t),{signal:d});this._freeHighlight=new FreeHighlightOutliner({x:s,y:n},[a,r,o,l],t.scale,this._defaultThickness/2,e,.001);({id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=t.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:this._defaultColor,"fill-opacity":this._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:this._freeHighlight.toSVGPath()}},!0,!0))}static#ur(t,e){this._freeHighlight.add(e)&&t.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})}static#cr(t,e){this._freeHighlight.isEmpty()?t.drawLayer.remove(this._freeHighlightId):t.createAndAddNewEditor(e,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"});this._freeHighlightId=-1;this._freeHighlight=null;this._freeHighlightClipId=""}static async deserialize(t,e,i){let s=null;if(t instanceof HighlightAnnotationElement){const{data:{quadPoints:e,rect:i,rotation:n,id:a,color:r,opacity:o,popupRef:l},parent:{page:{pageNumber:h}}}=t;s=t={annotationType:g.HIGHLIGHT,color:Array.from(r),opacity:o,quadPoints:e,boxes:null,pageIndex:h-1,rect:i.slice(0),rotation:n,id:a,deleted:!1,popupRef:l}}else if(t instanceof InkAnnotationElement){const{data:{inkLists:e,rect:i,rotation:n,id:a,color:r,borderStyle:{rawWidth:o},popupRef:l},parent:{page:{pageNumber:h}}}=t;s=t={annotationType:g.HIGHLIGHT,color:Array.from(r),thickness:o,inkLists:e,boxes:null,pageIndex:h-1,rect:i.slice(0),rotation:n,id:a,deleted:!1,popupRef:l}}const{color:n,quadPoints:a,inkLists:r,opacity:o}=t,l=await super.deserialize(t,e,i);l.color=Util.makeHexColor(...n);l.#Ka=o||1;r&&(l.#ea=t.thickness);l.annotationElementId=t.id||null;l._initialData=s;const[h,d]=l.pageDimensions,[c,u]=l.pageTranslation;if(a){const t=l.#Ua=[];for(let e=0;et!==e[i]))}renderAnnotationElement(t){t.updateEdited({rect:this.getRect(0,0)});return null}static canCreateNewEmptyEditor(){return!1}}class DrawingOptions{#pr=Object.create(null);updateProperty(t,e){this[t]=e;this.updateSVGProperty(t,e)}updateProperties(t){if(t)for(const[e,i]of Object.entries(t))this.updateProperty(e,i)}updateSVGProperty(t,e){this.#pr[t]=e}toSVGProperties(){const t=this.#pr;this.#pr=Object.create(null);return{root:t}}reset(){this.#pr=Object.create(null)}updateAll(t=this){this.updateProperties(t)}clone(){unreachable("Not implemented")}}class DrawingEditor extends AnnotationEditor{#gr=null;#mr;_drawId=null;static _currentDrawId=-1;static _currentParent=null;static#fr=null;static#br=null;static#Ar=null;static#wr=NaN;static#vr=null;static#yr=null;static#xr=NaN;static _INNER_MARGIN=3;constructor(t){super(t);this.#mr=t.mustBeCommitted||!1;if(t.drawOutlines){this.#_r(t);this.#tr()}}#_r({drawOutlines:t,drawId:e,drawingOptions:i}){this.#gr=t;this._drawingOptions||=i;if(e>=0){this._drawId=e;this.parent.drawLayer.finalizeDraw(e,t.defaultProperties)}else this._drawId=this.#Er(t,this.parent);this.#Sr(t.box)}#Er(t,e){const{id:i}=e.drawLayer.draw(DrawingEditor._mergeSVGProperties(this._drawingOptions.toSVGProperties(),t.defaultSVGProperties),!1,!1);return i}static _mergeSVGProperties(t,e){const i=new Set(Object.keys(t));for(const[s,n]of Object.entries(e))i.has(s)?Object.assign(t[s],n):t[s]=n;return t}static getDefaultDrawingOptions(t){unreachable("Not implemented")}static get typesMap(){unreachable("Not implemented")}static get isDrawer(){return!0}static get supportMultipleDrawings(){return!1}static updateDefaultParams(t,e){const i=this.typesMap.get(t);i&&this._defaultDrawingOptions.updateProperty(i,e);if(this._currentParent){DrawingEditor.#fr.updateProperty(i,e);this._currentParent.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties())}}updateParams(t,e){const i=this.constructor.typesMap.get(t);i&&this._updateProperty(t,i,e)}static get defaultPropertiesToUpdate(){const t=[],e=this._defaultDrawingOptions;for(const[i,s]of this.typesMap)t.push([i,e[s]]);return t}get propertiesToUpdate(){const t=[],{_drawingOptions:e}=this;for(const[i,s]of this.constructor.typesMap)t.push([i,e[s]]);return t}_updateProperty(t,e,i){const s=this._drawingOptions,n=s[e],setter=t=>{s.updateProperty(e,t);const i=this.#gr.updateProperty(e,t);i&&this.#Sr(i);this.parent?.drawLayer.updateProperties(this._drawId,s.toSVGProperties())};this.addCommands({cmd:setter.bind(this,i),undo:setter.bind(this,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:t,overwriteIfSameType:!0,keepUndo:!0})}_onResizing(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#gr.getPathResizingSVGProperties(this.#Cr()),{bbox:this.#Tr()}))}_onResized(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#gr.getPathResizedSVGProperties(this.#Cr()),{bbox:this.#Tr()}))}_onTranslating(t,e){this.parent?.drawLayer.updateProperties(this._drawId,{bbox:this.#Tr(t,e)})}_onTranslated(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#gr.getPathTranslatedSVGProperties(this.#Cr(),this.parentDimensions),{bbox:this.#Tr()}))}_onStartDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!0}})}_onStopDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!1}})}commit(){super.commit();this.disableEditMode();this.disableEditing()}disableEditing(){super.disableEditing();this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing();this.div.classList.toggle("disabled",!1)}getBaseTranslation(){return[0,0]}get isResizable(){return!0}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this);this._isDraggable=!0;if(this.#mr){this.#mr=!1;this.commit();this.parent.setSelected(this);t&&this.isOnScreen&&this.div.focus()}}remove(){this.#rr();super.remove()}rebuild(){if(this.parent){super.rebuild();if(null!==this.div){this.#tr();this.#Sr(this.#gr.box);this.isAttachedToDOM||this.parent.add(this)}}}setParent(t){let e=!1;if(this.parent&&!t){this._uiManager.removeShouldRescale(this);this.#rr()}else if(t){this._uiManager.addShouldRescale(this);this.#tr(t);e=!this.parent&&this.div?.classList.contains("selectedEditor")}super.setParent(t);e&&this.select()}#rr(){if(null!==this._drawId&&this.parent){this.parent.drawLayer.remove(this._drawId);this._drawId=null;this._drawingOptions.reset()}}#tr(t=this.parent){if(null===this._drawId||this.parent!==t)if(null===this._drawId){this._drawingOptions.updateAll();this._drawId=this.#Er(this.#gr,t)}else this.parent.drawLayer.updateParent(this._drawId,t.drawLayer)}#Mr([t,e,i,s]){const{parentDimensions:[n,a],rotation:r}=this;switch(r){case 90:return[e,1-t,i*(a/n),s*(n/a)];case 180:return[1-t,1-e,i,s];case 270:return[1-e,t,i*(a/n),s*(n/a)];default:return[t,e,i,s]}}#Cr(){const{x:t,y:e,width:i,height:s,parentDimensions:[n,a],rotation:r}=this;switch(r){case 90:return[1-e,t,i*(n/a),s*(a/n)];case 180:return[1-t,1-e,i,s];case 270:return[e,1-t,i*(n/a),s*(a/n)];default:return[t,e,i,s]}}#Sr(t){[this.x,this.y,this.width,this.height]=this.#Mr(t);if(this.div){this.fixAndSetPosition();const[t,e]=this.parentDimensions;this.setDims(this.width*t,this.height*e)}this._onResized()}#Tr(){const{x:t,y:e,width:i,height:s,rotation:n,parentRotation:a,parentDimensions:[r,o]}=this;switch((4*n+a)/90){case 1:return[1-e-s,t,s,i];case 2:return[1-t-i,1-e-s,i,s];case 3:return[e,1-t-i,s,i];case 4:return[t,e-i*(r/o),s*(o/r),i*(r/o)];case 5:return[1-e,t,i*(r/o),s*(o/r)];case 6:return[1-t-s*(o/r),1-e,s*(o/r),i*(r/o)];case 7:return[e-i*(r/o),1-t-s*(o/r),i*(r/o),s*(o/r)];case 8:return[t-i,e-s,i,s];case 9:return[1-e,t-i,s,i];case 10:return[1-t,1-e,i,s];case 11:return[e-s,1-t,s,i];case 12:return[t-s*(o/r),e,s*(o/r),i*(r/o)];case 13:return[1-e-i*(r/o),t-s*(o/r),i*(r/o),s*(o/r)];case 14:return[1-t,1-e-i*(r/o),s*(o/r),i*(r/o)];case 15:return[e,1-t,i*(r/o),s*(o/r)];default:return[t,e,i,s]}}rotate(){this.parent&&this.parent.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties({bbox:this.#Tr()},this.#gr.updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&this.#Sr(this.#gr.updateParentDimensions(this.parentDimensions,this.parent.scale))}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;const t=super.render();t.classList.add("draw");const e=document.createElement("div");t.append(e);e.setAttribute("aria-hidden","true");e.className="internal";const[i,s]=this.parentDimensions;this.setDims(this.width*i,this.height*s);this._uiManager.addShouldRescale(this);this.disableEditing();return t}static createDrawerInstance(t,e,i,s,n){unreachable("Not implemented")}static startDrawing(t,e,i,s){const{target:n,offsetX:a,offsetY:r,pointerId:o,pointerType:l}=s;if(DrawingEditor.#vr&&DrawingEditor.#vr!==l)return;const{viewport:{rotation:h}}=t,{width:d,height:c}=n.getBoundingClientRect(),u=DrawingEditor.#br=new AbortController,p=t.combinedSignal(u);DrawingEditor.#wr||=o;DrawingEditor.#vr??=l;window.addEventListener("pointerup",(t=>{DrawingEditor.#wr===t.pointerId?this._endDraw(t):DrawingEditor.#yr?.delete(t.pointerId)}),{signal:p});window.addEventListener("pointercancel",(t=>{DrawingEditor.#wr===t.pointerId?this._currentParent.endDrawingSession():DrawingEditor.#yr?.delete(t.pointerId)}),{signal:p});window.addEventListener("pointerdown",(t=>{if(DrawingEditor.#vr===t.pointerType){(DrawingEditor.#yr||=new Set).add(t.pointerId);if(DrawingEditor.#fr.isCancellable()){DrawingEditor.#fr.removeLastElement();DrawingEditor.#fr.isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)}}}),{capture:!0,passive:!1,signal:p});window.addEventListener("contextmenu",noContextMenu,{signal:p});n.addEventListener("pointermove",this._drawMove.bind(this),{signal:p});n.addEventListener("touchmove",(t=>{t.timeStamp===DrawingEditor.#xr&&stopEvent(t)}),{signal:p});t.toggleDrawing();e._editorUndoBar?.hide();if(DrawingEditor.#fr)t.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#fr.startNew(a,r,d,c,h));else{e.updateUIForDefaultProperties(this);DrawingEditor.#fr=this.createDrawerInstance(a,r,d,c,h);DrawingEditor.#Ar=this.getDefaultDrawingOptions();this._currentParent=t;({id:this._currentDrawId}=t.drawLayer.draw(this._mergeSVGProperties(DrawingEditor.#Ar.toSVGProperties(),DrawingEditor.#fr.defaultSVGProperties),!0,!1))}}static _drawMove(t){DrawingEditor.#xr=-1;if(!DrawingEditor.#fr)return;const{offsetX:e,offsetY:i,pointerId:s}=t;if(DrawingEditor.#wr===s)if(DrawingEditor.#yr?.size>=1)this._endDraw(t);else{this._currentParent.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#fr.add(e,i));DrawingEditor.#xr=t.timeStamp;stopEvent(t)}}static _cleanup(t){if(t){this._currentDrawId=-1;this._currentParent=null;DrawingEditor.#fr=null;DrawingEditor.#Ar=null;DrawingEditor.#vr=null;DrawingEditor.#xr=NaN}if(DrawingEditor.#br){DrawingEditor.#br.abort();DrawingEditor.#br=null;DrawingEditor.#wr=NaN;DrawingEditor.#yr=null}}static _endDraw(t){const e=this._currentParent;if(e){e.toggleDrawing(!0);this._cleanup(!1);t&&e.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#fr.end(t.offsetX,t.offsetY));if(this.supportMultipleDrawings){const t=DrawingEditor.#fr,i=this._currentDrawId,s=t.getLastElement();e.addCommands({cmd:()=>{e.drawLayer.updateProperties(i,t.setLastElement(s))},undo:()=>{e.drawLayer.updateProperties(i,t.removeLastElement())},mustExec:!1,type:m.DRAW_STEP})}else this.endDrawing(!1)}}static endDrawing(t){const e=this._currentParent;if(!e)return null;e.toggleDrawing(!0);e.cleanUndoStack(m.DRAW_STEP);if(!DrawingEditor.#fr.isEmpty()){const{pageDimensions:[i,s],scale:n}=e,a=e.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:DrawingEditor.#fr.getOutlines(i*n,s*n,n,this._INNER_MARGIN),drawingOptions:DrawingEditor.#Ar,mustBeCommitted:!t});this._cleanup(!0);return a}e.drawLayer.remove(this._currentDrawId);this._cleanup(!0);return null}createDrawingOptions(t){}static deserializeDraw(t,e,i,s,n,a){unreachable("Not implemented")}static async deserialize(t,e,i){const{rawDims:{pageWidth:s,pageHeight:n,pageX:a,pageY:r}}=e.viewport,o=this.deserializeDraw(a,r,s,n,this._INNER_MARGIN,t),l=await super.deserialize(t,e,i);l.createDrawingOptions(t);l.#_r({drawOutlines:o});l.#tr();l.onScaleChanging();l.rotate();return l}serializeDraw(t){const[e,i]=this.pageTranslation,[s,n]=this.pageDimensions;return this.#gr.serialize([e,i,s,n],t)}renderAnnotationElement(t){t.updateEdited({rect:this.getRect(0,0)});return null}static canCreateNewEmptyEditor(){return!1}}class InkDrawOutliner{#Kn=new Float64Array(6);#bn;#Pr;#Fi;#ea;#ia;#Dr="";#kr=0;#Ea=new InkDrawOutline;#Rr;#Ir;constructor(t,e,i,s,n,a){this.#Rr=i;this.#Ir=s;this.#Fi=n;this.#ea=a;[t,e]=this.#Fr(t,e);const r=this.#bn=[NaN,NaN,NaN,NaN,t,e];this.#ia=[t,e];this.#Pr=[{line:r,points:this.#ia}];this.#Kn.set(r,0)}updateProperty(t,e){"stroke-width"===t&&(this.#ea=e)}#Fr(t,e){return Outline._normalizePoint(t,e,this.#Rr,this.#Ir,this.#Fi)}isEmpty(){return!this.#Pr||0===this.#Pr.length}isCancellable(){return this.#ia.length<=10}add(t,e){[t,e]=this.#Fr(t,e);const[i,s,n,a]=this.#Kn.subarray(2,6),r=t-n,o=e-a;if(Math.hypot(this.#Rr*r,this.#Ir*o)<=2)return null;this.#ia.push(t,e);if(isNaN(i)){this.#Kn.set([n,a,t,e],2);this.#bn.push(NaN,NaN,NaN,NaN,t,e);return{path:{d:this.toSVGPath()}}}isNaN(this.#Kn[0])&&this.#bn.splice(6,6);this.#Kn.set([i,s,n,a,t,e],0);this.#bn.push(...Outline.createBezierPoints(i,s,n,a,t,e));return{path:{d:this.toSVGPath()}}}end(t,e){const i=this.add(t,e);return i||(2===this.#ia.length?{path:{d:this.toSVGPath()}}:null)}startNew(t,e,i,s,n){this.#Rr=i;this.#Ir=s;this.#Fi=n;[t,e]=this.#Fr(t,e);const a=this.#bn=[NaN,NaN,NaN,NaN,t,e];this.#ia=[t,e];const r=this.#Pr.at(-1);if(r){r.line=new Float32Array(r.line);r.points=new Float32Array(r.points)}this.#Pr.push({line:a,points:this.#ia});this.#Kn.set(a,0);this.#kr=0;this.toSVGPath();return null}getLastElement(){return this.#Pr.at(-1)}setLastElement(t){if(!this.#Pr)return this.#Ea.setLastElement(t);this.#Pr.push(t);this.#bn=t.line;this.#ia=t.points;this.#kr=0;return{path:{d:this.toSVGPath()}}}removeLastElement(){if(!this.#Pr)return this.#Ea.removeLastElement();this.#Pr.pop();this.#Dr="";for(let t=0,e=this.#Pr.length;tt??NaN)),d,c,u,p),points:g(r[t].map((t=>t??NaN)),d,c,u,p)});const m=new InkDrawOutline;m.build(h,i,s,1,o,l,n);return m}#Hr(t=this.#ea){const e=this.#Wn+t/2*this.#Or;return this.#Fi%180==0?[e/this.#Rr,e/this.#Ir]:[e/this.#Ir,e/this.#Rr]}#Br(){const[t,e,i,s]=this.#pa,[n,a]=this.#Hr(0);return[t+n,e+a,i-2*n,s-2*a]}#Nr(){const t=this.#pa=new Float32Array([1/0,1/0,-1/0,-1/0]);for(const{line:e}of this.#Pr){if(e.length<=12){for(let i=4,s=e.length;it!==e[i]))||t.thickness!==i||t.opacity!==s||t.pageIndex!==n}renderAnnotationElement(t){const{points:e,rect:i}=this.serializeDraw(!1);t.updateEdited({rect:i,thickness:this._drawingOptions["stroke-width"],points:e});return null}}class StampEditor extends AnnotationEditor{#Ur=null;#Gr=null;#$r=null;#Vr=null;#jr=null;#Wr="";#qr=null;#Xr=null;#Kr=!1;#Yr=!1;static _type="stamp";static _editorType=g.STAMP;constructor(t){super({...t,name:"stampEditor"});this.#Vr=t.bitmapUrl;this.#jr=t.bitmapFile}static initialize(t,e){AnnotationEditor.initialize(t,e)}static get supportedTypes(){return shadow(this,"supportedTypes",["apng","avif","bmp","gif","jpeg","png","svg+xml","webp","x-icon"].map((t=>`image/${t}`)))}static get supportedTypesStr(){return shadow(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(t){return this.supportedTypes.includes(t)}static paste(t,e){e.pasteEditor(g.STAMP,{bitmapFile:t.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1);super.altTextFinish()}get telemetryFinalData(){return{type:"stamp",hasAltText:!!this.altTextData?.altText}}static computeTelemetryFinalData(t){const e=t.get("hasAltText");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}#Qr(t,e=!1){if(t){this.#Ur=t.bitmap;if(!e){this.#Gr=t.id;this.#Kr=t.isSvg}t.file&&(this.#Wr=t.file.name);this.#Jr()}else this.remove()}#Zr(){this.#$r=null;this._uiManager.enableWaiting(!1);if(this.#qr)if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#Ur){this._editToolbar.hide();this._uiManager.editAltText(this,!0)}else{if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#Ur){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}}async mlGuessAltText(t=null,e=!0){if(this.hasAltTextData())return null;const{mlManager:i}=this._uiManager;if(!i)throw new Error("No ML.");if(!await i.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:s,width:n,height:a}=t||this.copyCanvas(null,null,!0).imageData,r=await i.guess({name:"altText",request:{data:s,width:n,height:a,channels:s.length/(n*a)}});if(!r)throw new Error("No response from the AI service.");if(r.error)throw new Error("Error from the AI service.");if(r.cancel)return null;if(!r.output)throw new Error("No valid response from the AI service.");const o=r.output;await this.setGuessedAltText(o);e&&!this.hasAltTextData()&&(this.altTextData={alt:o,decorative:!1});return o}#to(){if(this.#Gr){this._uiManager.enableWaiting(!0);this._uiManager.imageManager.getFromId(this.#Gr).then((t=>this.#Qr(t,!0))).finally((()=>this.#Zr()));return}if(this.#Vr){const t=this.#Vr;this.#Vr=null;this._uiManager.enableWaiting(!0);this.#$r=this._uiManager.imageManager.getFromUrl(t).then((t=>this.#Qr(t))).finally((()=>this.#Zr()));return}if(this.#jr){const t=this.#jr;this.#jr=null;this._uiManager.enableWaiting(!0);this.#$r=this._uiManager.imageManager.getFromFile(t).then((t=>this.#Qr(t))).finally((()=>this.#Zr()));return}const t=document.createElement("input");t.type="file";t.accept=StampEditor.supportedTypesStr;const e=this._uiManager._signal;this.#$r=new Promise((i=>{t.addEventListener("change",(async()=>{if(t.files&&0!==t.files.length){this._uiManager.enableWaiting(!0);const e=await this._uiManager.imageManager.getFromFile(t.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}});this.#Qr(e)}else this.remove();i()}),{signal:e});t.addEventListener("cancel",(()=>{this.remove();i()}),{signal:e})})).finally((()=>this.#Zr()));t.click()}remove(){if(this.#Gr){this.#Ur=null;this._uiManager.imageManager.deleteId(this.#Gr);this.#qr?.remove();this.#qr=null;if(this.#Xr){clearTimeout(this.#Xr);this.#Xr=null}}super.remove()}rebuild(){if(this.parent){super.rebuild();if(null!==this.div){this.#Gr&&null===this.#qr&&this.#to();this.isAttachedToDOM||this.parent.add(this)}}else this.#Gr&&this.#to()}onceAdded(t){this._isDraggable=!0;t&&this.div.focus()}isEmpty(){return!(this.#$r||this.#Ur||this.#Vr||this.#jr||this.#Gr)}get isResizable(){return!0}render(){if(this.div)return this.div;let t,e;if(this.width){t=this.x;e=this.y}super.render();this.div.hidden=!0;this.div.setAttribute("role","figure");this.addAltTextButton();this.#Ur?this.#Jr():this.#to();if(this.width&&!this.annotationElementId){const[i,s]=this.parentDimensions;this.setAt(t*i,e*s,this.width*i,this.height*s)}this._uiManager.addShouldRescale(this);return this.div}_onResized(){this.onScaleChanging()}onScaleChanging(){if(!this.parent)return;null!==this.#Xr&&clearTimeout(this.#Xr);this.#Xr=setTimeout((()=>{this.#Xr=null;this.#eo()}),200)}#Jr(){const{div:t}=this;let{width:e,height:i}=this.#Ur;const[s,n]=this.pageDimensions,a=.75;if(this.width){e=this.width*s;i=this.height*n}else if(e>a*s||i>a*n){const t=Math.min(a*s/e,a*n/i);e*=t;i*=t}const[r,o]=this.parentDimensions;this.setDims(e*r/s,i*o/n);this._uiManager.enableWaiting(!1);const l=this.#qr=document.createElement("canvas");l.setAttribute("role","img");this.addContainer(l);this.width=e/s;this.height=i/n;this._initialOptions?.isCentered?this.center():this.fixAndSetPosition();this._initialOptions=null;this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&!this.annotationElementId||(t.hidden=!1);this.#eo();if(!this.#Yr){this.parent.addUndoableEditor(this);this.#Yr=!0}this._reportTelemetry({action:"inserted_image"});this.#Wr&&l.setAttribute("aria-label",this.#Wr)}copyCanvas(t,e,i=!1){t||(t=224);const{width:s,height:n}=this.#Ur,a=new OutputScale;let r=this.#Ur,o=s,l=n,h=null;if(e){if(s>e||n>e){const t=Math.min(e/s,e/n);o=Math.floor(s*t);l=Math.floor(n*t)}h=document.createElement("canvas");const t=h.width=Math.ceil(o*a.sx),i=h.height=Math.ceil(l*a.sy);this.#Kr||(r=this.#io(t,i));const d=h.getContext("2d");d.filter=this._uiManager.hcmFilter;let c="white",u="#cfcfd8";if("none"!==this._uiManager.hcmFilter)u="black";else if(window.matchMedia?.("(prefers-color-scheme: dark)").matches){c="#8f8f9d";u="#42414d"}const p=15,g=p*a.sx,m=p*a.sy,f=new OffscreenCanvas(2*g,2*m),b=f.getContext("2d");b.fillStyle=c;b.fillRect(0,0,2*g,2*m);b.fillStyle=u;b.fillRect(0,0,g,m);b.fillRect(g,m,g,m);d.fillStyle=d.createPattern(f,"repeat");d.fillRect(0,0,t,i);d.drawImage(r,0,0,r.width,r.height,0,0,t,i)}let d=null;if(i){let e,i;if(a.symmetric&&r.widtht||n>t){const a=Math.min(t/s,t/n);e=Math.floor(s*a);i=Math.floor(n*a);this.#Kr||(r=this.#io(e,i))}}const o=new OffscreenCanvas(e,i).getContext("2d",{willReadFrequently:!0});o.drawImage(r,0,0,r.width,r.height,0,0,e,i);d={width:e,height:i,data:o.getImageData(0,0,e,i).data}}return{canvas:h,width:o,height:l,imageData:d}}#io(t,e){const{width:i,height:s}=this.#Ur;let n=i,a=s,r=this.#Ur;for(;n>2*t||a>2*e;){const i=n,s=a;n>2*t&&(n=n>=16384?Math.floor(n/2)-1:Math.ceil(n/2));a>2*e&&(a=a>=16384?Math.floor(a/2)-1:Math.ceil(a/2));const o=new OffscreenCanvas(n,a);o.getContext("2d").drawImage(r,0,0,i,s,0,0,n,a);r=o.transferToImageBitmap()}return r}#eo(){const[t,e]=this.parentDimensions,{width:i,height:s}=this,n=new OutputScale,a=Math.ceil(i*t*n.sx),r=Math.ceil(s*e*n.sy),o=this.#qr;if(!o||o.width===a&&o.height===r)return;o.width=a;o.height=r;const l=this.#Kr?this.#Ur:this.#io(a,r),h=o.getContext("2d");h.filter=this._uiManager.hcmFilter;h.drawImage(l,0,0,l.width,l.height,0,0,a,r)}getImageForAltText(){return this.#qr}#so(t){if(t){if(this.#Kr){const t=this._uiManager.imageManager.getSvgUrl(this.#Gr);if(t)return t}const t=document.createElement("canvas");({width:t.width,height:t.height}=this.#Ur);t.getContext("2d").drawImage(this.#Ur,0,0);return t.toDataURL()}if(this.#Kr){const[t,e]=this.pageDimensions,i=Math.round(this.width*t*PixelsPerInch.PDF_TO_CSS_UNITS),s=Math.round(this.height*e*PixelsPerInch.PDF_TO_CSS_UNITS),n=new OffscreenCanvas(i,s);n.getContext("2d").drawImage(this.#Ur,0,0,this.#Ur.width,this.#Ur.height,0,0,i,s);return n.transferToImageBitmap()}return structuredClone(this.#Ur)}static async deserialize(t,e,i){let s=null;if(t instanceof StampAnnotationElement){const{data:{rect:n,rotation:a,id:r,structParent:o,popupRef:l},container:h,parent:{page:{pageNumber:d}}}=t,c=h.querySelector("canvas"),u=i.imageManager.getFromCanvas(h.id,c);c.remove();const p=(await e._structTree.getAriaAttributes(`${et}${r}`))?.get("aria-label")||"";s=t={annotationType:g.STAMP,bitmapId:u.id,bitmap:u.bitmap,pageIndex:d-1,rect:n.slice(0),rotation:a,id:r,deleted:!1,accessibilityData:{decorative:!1,altText:p},isSvg:!1,structParent:o,popupRef:l}}const n=await super.deserialize(t,e,i),{rect:a,bitmap:r,bitmapUrl:o,bitmapId:l,isSvg:h,accessibilityData:d}=t;if(l&&i.imageManager.isValidId(l)){n.#Gr=l;r&&(n.#Ur=r)}else n.#Vr=o;n.#Kr=h;const[c,u]=n.pageDimensions;n.width=(a[2]-a[0])/c;n.height=(a[3]-a[1])/u;n.annotationElementId=t.id||null;d&&(n.altTextData=d);n._initialData=s;n.#Yr=!!s;return n}serialize(t=!1,e=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const i={annotationType:g.STAMP,bitmapId:this.#Gr,pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:this.#Kr,structTreeParentId:this._structTreeParentId};if(t){i.bitmapUrl=this.#so(!0);i.accessibilityData=this.serializeAltText(!0);return i}const{decorative:s,altText:n}=this.serializeAltText(!1);!s&&n&&(i.accessibilityData={type:"Figure",alt:n});if(this.annotationElementId){const t=this.#$n(i);if(t.isSame)return null;t.isSameAltText?delete i.accessibilityData:i.accessibilityData.structParent=this._initialData.structParent??-1}i.id=this.annotationElementId;if(null===e)return i;e.stamps||=new Map;const a=this.#Kr?(i.rect[2]-i.rect[0])*(i.rect[3]-i.rect[1]):null;if(e.stamps.has(this.#Gr)){if(this.#Kr){const t=e.stamps.get(this.#Gr);if(a>t.area){t.area=a;t.serialized.bitmap.close();t.serialized.bitmap=this.#so(!1)}}}else{e.stamps.set(this.#Gr,{area:a,serialized:i});i.bitmap=this.#so(!1)}return i}#$n(t){const{pageIndex:e,accessibilityData:{altText:i}}=this._initialData,s=t.pageIndex===e,n=(t.accessibilityData?.alt||"")===i;return{isSame:!this._hasBeenMoved&&!this._hasBeenResized&&s&&n,isSameAltText:n}}renderAnnotationElement(t){t.updateEdited({rect:this.getRect(0,0)});return null}}class AnnotationEditorLayer{#Cn;#no=!1;#ao=null;#ro=null;#oo=null;#lo=new Map;#ho=!1;#do=!1;#co=!1;#uo=null;#po=null;#go=null;#mo=null;#m;static _initialized=!1;static#U=new Map([FreeTextEditor,InkEditor,StampEditor,HighlightEditor].map((t=>[t._editorType,t])));constructor({uiManager:t,pageIndex:e,div:i,structTreeLayer:s,accessibilityManager:n,annotationLayer:a,drawLayer:r,textLayer:o,viewport:l,l10n:h}){const d=[...AnnotationEditorLayer.#U.values()];if(!AnnotationEditorLayer._initialized){AnnotationEditorLayer._initialized=!0;for(const e of d)e.initialize(h,t)}t.registerEditorTypes(d);this.#m=t;this.pageIndex=e;this.div=i;this.#Cn=n;this.#ao=a;this.viewport=l;this.#go=o;this.drawLayer=r;this._structTree=s;this.#m.addLayer(this)}get isEmpty(){return 0===this.#lo.size}get isInvisible(){return this.isEmpty&&this.#m.getMode()===g.NONE}updateToolbar(t){this.#m.updateToolbar(t)}updateMode(t=this.#m.getMode()){this.#fo();switch(t){case g.NONE:this.disableTextSelection();this.togglePointerEvents(!1);this.toggleAnnotationLayerPointerEvents(!0);this.disableClick();return;case g.INK:this.disableTextSelection();this.togglePointerEvents(!0);this.enableClick();break;case g.HIGHLIGHT:this.enableTextSelection();this.togglePointerEvents(!1);this.disableClick();break;default:this.disableTextSelection();this.togglePointerEvents(!0);this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);const{classList:e}=this.div;for(const i of AnnotationEditorLayer.#U.values())e.toggle(`${i._type}Editing`,t===i._editorType);this.div.hidden=!1}hasTextLayer(t){return t===this.#go?.div}setEditingState(t){this.#m.setEditingState(t)}addCommands(t){this.#m.addCommands(t)}cleanUndoStack(t){this.#m.cleanUndoStack(t)}toggleDrawing(t=!1){this.div.classList.toggle("drawing",!t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){this.#ao?.div.classList.toggle("disabled",!t)}async enable(){this.#co=!0;this.div.tabIndex=0;this.togglePointerEvents(!0);const t=new Set;for(const e of this.#lo.values()){e.enableEditing();e.show(!0);if(e.annotationElementId){this.#m.removeChangedExistingAnnotation(e);t.add(e.annotationElementId)}}if(!this.#ao){this.#co=!1;return}const e=this.#ao.getEditableAnnotations();for(const i of e){i.hide();if(this.#m.isDeletedAnnotationElement(i.data.id))continue;if(t.has(i.data.id))continue;const e=await this.deserialize(i);if(e){this.addOrRebuild(e);e.enableEditing()}}this.#co=!1}disable(){this.#do=!0;this.div.tabIndex=-1;this.togglePointerEvents(!1);const t=new Map,e=new Map;for(const i of this.#lo.values()){i.disableEditing();if(i.annotationElementId)if(null===i.serialize()){e.set(i.annotationElementId,i);this.getEditableAnnotation(i.annotationElementId)?.show();i.remove()}else t.set(i.annotationElementId,i)}if(this.#ao){const i=this.#ao.getEditableAnnotations();for(const s of i){const{id:i}=s.data;if(this.#m.isDeletedAnnotationElement(i))continue;let n=e.get(i);if(n){n.resetAnnotationElement(s);n.show(!1);s.show()}else{n=t.get(i);if(n){this.#m.addChangedExistingAnnotation(n);n.renderAnnotationElement(s)&&n.show(!1)}s.show()}}}this.#fo();this.isEmpty&&(this.div.hidden=!0);const{classList:i}=this.div;for(const t of AnnotationEditorLayer.#U.values())i.remove(`${t._type}Editing`);this.disableTextSelection();this.toggleAnnotationLayerPointerEvents(!0);this.#do=!1}getEditableAnnotation(t){return this.#ao?.getEditableAnnotation(t)||null}setActiveEditor(t){this.#m.getActive()!==t&&this.#m.setActiveEditor(t)}enableTextSelection(){this.div.tabIndex=-1;if(this.#go?.div&&!this.#mo){this.#mo=new AbortController;const t=this.#m.combinedSignal(this.#mo);this.#go.div.addEventListener("pointerdown",this.#bo.bind(this),{signal:t});this.#go.div.classList.add("highlighting")}}disableTextSelection(){this.div.tabIndex=0;if(this.#go?.div&&this.#mo){this.#mo.abort();this.#mo=null;this.#go.div.classList.remove("highlighting")}}#bo(t){this.#m.unselectAll();const{target:e}=t;if(e===this.#go.div||("img"===e.getAttribute("role")||e.classList.contains("endOfContent"))&&this.#go.div.contains(e)){const{isMac:e}=util_FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)return;this.#m.showAllEditors("highlight",!0,!0);this.#go.div.classList.add("free");this.toggleDrawing();HighlightEditor.startHighlighting(this,"ltr"===this.#m.direction,{target:this.#go.div,x:t.x,y:t.y});this.#go.div.addEventListener("pointerup",(()=>{this.#go.div.classList.remove("free");this.toggleDrawing(!0)}),{once:!0,signal:this.#m._signal});t.preventDefault()}}enableClick(){if(this.#ro)return;this.#ro=new AbortController;const t=this.#m.combinedSignal(this.#ro);this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t});const e=this.pointerup.bind(this);this.div.addEventListener("pointerup",e,{signal:t});this.div.addEventListener("pointercancel",e,{signal:t})}disableClick(){this.#ro?.abort();this.#ro=null}attach(t){this.#lo.set(t.id,t);const{annotationElementId:e}=t;e&&this.#m.isDeletedAnnotationElement(e)&&this.#m.removeDeletedAnnotationElement(t)}detach(t){this.#lo.delete(t.id);this.#Cn?.removePointerInTextLayer(t.contentDiv);!this.#do&&t.annotationElementId&&this.#m.addDeletedAnnotationElement(t)}remove(t){this.detach(t);this.#m.removeEditor(t);t.div.remove();t.isAttachedToDOM=!1}changeParent(t){if(t.parent!==this){if(t.parent&&t.annotationElementId){this.#m.addDeletedAnnotationElement(t.annotationElementId);AnnotationEditor.deleteAnnotationElement(t);t.annotationElementId=null}this.attach(t);t.parent?.detach(t);t.setParent(this);if(t.div&&t.isAttachedToDOM){t.div.remove();this.div.append(t.div)}}}add(t){if(t.parent!==this||!t.isAttachedToDOM){this.changeParent(t);this.#m.addEditor(t);this.attach(t);if(!t.isAttachedToDOM){const e=t.render();this.div.append(e);t.isAttachedToDOM=!0}t.fixAndSetPosition();t.onceAdded(!this.#co);this.#m.addToAnnotationStorage(t);t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){if(!t.isAttachedToDOM)return;const{activeElement:e}=document;if(t.div.contains(e)&&!this.#oo){t._focusEventsAllowed=!1;this.#oo=setTimeout((()=>{this.#oo=null;if(t.div.contains(document.activeElement))t._focusEventsAllowed=!0;else{t.div.addEventListener("focusin",(()=>{t._focusEventsAllowed=!0}),{once:!0,signal:this.#m._signal});e.focus()}}),0)}t._structTreeParentId=this.#Cn?.moveElementInDOM(this.div,t.div,t.contentDiv,!0)}addOrRebuild(t){if(t.needsToBeRebuilt()){t.parent||=this;t.rebuild();t.show()}else this.add(t)}addUndoableEditor(t){this.addCommands({cmd:()=>t._uiManager.rebuild(t),undo:()=>{t.remove()},mustExec:!1})}getNextId(){return this.#m.getId()}get#Ao(){return AnnotationEditorLayer.#U.get(this.#m.getMode())}combinedSignal(t){return this.#m.combinedSignal(t)}#wo(t){const e=this.#Ao;return e?new e.prototype.constructor(t):null}canCreateNewEmptyEditor(){return this.#Ao?.canCreateNewEmptyEditor()}pasteEditor(t,e){this.#m.updateToolbar(t);this.#m.updateMode(t);const{offsetX:i,offsetY:s}=this.#vo(),n=this.getNextId(),a=this.#wo({parent:this,id:n,x:i,y:s,uiManager:this.#m,isCentered:!0,...e});a&&this.add(a)}async deserialize(t){return await(AnnotationEditorLayer.#U.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#m))||null}createAndAddNewEditor(t,e,i={}){const s=this.getNextId(),n=this.#wo({parent:this,id:s,x:t.offsetX,y:t.offsetY,uiManager:this.#m,isCentered:e,...i});n&&this.add(n);return n}#vo(){const{x:t,y:e,width:i,height:s}=this.div.getBoundingClientRect(),n=Math.max(0,t),a=Math.max(0,e),r=(n+Math.min(window.innerWidth,t+i))/2-t,o=(a+Math.min(window.innerHeight,e+s))/2-e,[l,h]=this.viewport.rotation%180==0?[r,o]:[o,r];return{offsetX:l,offsetY:h}}addNewEditor(){this.createAndAddNewEditor(this.#vo(),!0)}setSelected(t){this.#m.setSelected(t)}toggleSelected(t){this.#m.toggleSelected(t)}unselect(t){this.#m.unselect(t)}pointerup(t){const{isMac:e}=util_FeatureTest.platform;if(!(0!==t.button||t.ctrlKey&&e)&&t.target===this.div&&this.#ho){this.#ho=!1;this.#Ao?.isDrawer&&this.#Ao.supportMultipleDrawings||(this.#no?this.#m.getMode()!==g.STAMP?this.createAndAddNewEditor(t,!1):this.#m.unselectAll():this.#no=!0)}}pointerdown(t){this.#m.getMode()===g.HIGHLIGHT&&this.enableTextSelection();if(this.#ho){this.#ho=!1;return}const{isMac:e}=util_FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)return;if(t.target!==this.div)return;this.#ho=!0;if(this.#Ao?.isDrawer){this.startDrawingSession(t);return}const i=this.#m.getActive();this.#no=!i||i.isEmpty()}startDrawingSession(t){this.div.focus();if(this.#uo){this.#Ao.startDrawing(this,this.#m,!1,t);return}this.#m.setCurrentDrawingSession(this);this.#uo=new AbortController;const e=this.#m.combinedSignal(this.#uo);this.div.addEventListener("blur",(({relatedTarget:t})=>{if(t&&!this.div.contains(t)){this.#po=null;this.commitOrRemove()}}),{signal:e});this.#Ao.startDrawing(this,this.#m,!1,t)}pause(t){if(t){const{activeElement:t}=document;this.div.contains(t)&&(this.#po=t)}else this.#po&&setTimeout((()=>{this.#po?.focus();this.#po=null}),0)}endDrawingSession(t=!1){if(!this.#uo)return null;this.#m.setCurrentDrawingSession(null);this.#uo.abort();this.#uo=null;this.#po=null;return this.#Ao.endDrawing(t)}findNewParent(t,e,i){const s=this.#m.findParent(e,i);if(null===s||s===this)return!1;s.changeParent(t);return!0}commitOrRemove(){if(this.#uo){this.endDrawingSession();return!0}return!1}onScaleChanging(){this.#uo&&this.#Ao.onScaleChangingWhenDrawing(this)}destroy(){this.commitOrRemove();if(this.#m.getActive()?.parent===this){this.#m.commitOrRemove();this.#m.setActiveEditor(null)}if(this.#oo){clearTimeout(this.#oo);this.#oo=null}for(const t of this.#lo.values()){this.#Cn?.removePointerInTextLayer(t.contentDiv);t.setParent(null);t.isAttachedToDOM=!1;t.div.remove()}this.div=null;this.#lo.clear();this.#m.removeLayer(this)}#fo(){for(const t of this.#lo.values())t.isEmpty()&&t.remove()}render({viewport:t}){this.viewport=t;setLayerDimensions(this.div,t);for(const t of this.#m.getEditors(this.pageIndex)){this.add(t);t.rebuild()}this.updateMode()}update({viewport:t}){this.#m.commitOrRemove();this.#fo();const e=this.viewport.rotation,i=t.rotation;this.viewport=t;setLayerDimensions(this.div,{rotation:i});if(e!==i)for(const t of this.#lo.values())t.rotate(i)}get pageDimensions(){const{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return this.#m.viewParameters.realScale}}class DrawLayer{#nn=null;#w=0;#yo=new Map;#xo=new Map;constructor({pageIndex:t}){this.pageIndex=t}setParent(t){if(this.#nn){if(this.#nn!==t){if(this.#yo.size>0)for(const e of this.#yo.values()){e.remove();t.append(e)}this.#nn=t}}else this.#nn=t}static get _svgFactory(){return shadow(this,"_svgFactory",new DOMSVGFactory)}static#_o(t,[e,i,s,n]){const{style:a}=t;a.top=100*i+"%";a.left=100*e+"%";a.width=100*s+"%";a.height=100*n+"%"}#Eo(){const t=DrawLayer._svgFactory.create(1,1,!0);this.#nn.append(t);t.setAttribute("aria-hidden",!0);return t}#So(t,e){const i=DrawLayer._svgFactory.createElement("clipPath");t.append(i);const s=`clip_${e}`;i.setAttribute("id",s);i.setAttribute("clipPathUnits","objectBoundingBox");const n=DrawLayer._svgFactory.createElement("use");i.append(n);n.setAttribute("href",`#${e}`);n.classList.add("clip");return s}#Co(t,e){for(const[i,s]of Object.entries(e))null===s?t.removeAttribute(i):t.setAttribute(i,s)}draw(t,e=!1,i=!1){const s=this.#w++,n=this.#Eo(),a=DrawLayer._svgFactory.createElement("defs");n.append(a);const r=DrawLayer._svgFactory.createElement("path");a.append(r);const o=`path_p${this.pageIndex}_${s}`;r.setAttribute("id",o);r.setAttribute("vector-effect","non-scaling-stroke");e&&this.#xo.set(s,r);const l=i?this.#So(a,o):null,h=DrawLayer._svgFactory.createElement("use");n.append(h);h.setAttribute("href",`#${o}`);this.updateProperties(n,t);this.#yo.set(s,n);return{id:s,clipPathId:`url(#${l})`}}drawOutline(t,e){const i=this.#w++,s=this.#Eo(),n=DrawLayer._svgFactory.createElement("defs");s.append(n);const a=DrawLayer._svgFactory.createElement("path");n.append(a);const r=`path_p${this.pageIndex}_${i}`;a.setAttribute("id",r);a.setAttribute("vector-effect","non-scaling-stroke");let o;if(e){const t=DrawLayer._svgFactory.createElement("mask");n.append(t);o=`mask_p${this.pageIndex}_${i}`;t.setAttribute("id",o);t.setAttribute("maskUnits","objectBoundingBox");const e=DrawLayer._svgFactory.createElement("rect");t.append(e);e.setAttribute("width","1");e.setAttribute("height","1");e.setAttribute("fill","white");const s=DrawLayer._svgFactory.createElement("use");t.append(s);s.setAttribute("href",`#${r}`);s.setAttribute("stroke","none");s.setAttribute("fill","black");s.setAttribute("fill-rule","nonzero");s.classList.add("mask")}const l=DrawLayer._svgFactory.createElement("use");s.append(l);l.setAttribute("href",`#${r}`);o&&l.setAttribute("mask",`url(#${o})`);const h=l.cloneNode();s.append(h);l.classList.add("mainOutline");h.classList.add("secondaryOutline");this.updateProperties(s,t);this.#yo.set(i,s);return i}finalizeDraw(t,e){this.#xo.delete(t);this.updateProperties(t,e)}updateProperties(t,e){if(!e)return;const{root:i,bbox:s,rootClass:n,path:a}=e,r="number"==typeof t?this.#yo.get(t):t;if(r){i&&this.#Co(r,i);s&&DrawLayer.#_o(r,s);if(n){const{classList:t}=r;for(const[e,i]of Object.entries(n))t.toggle(e,i)}if(a){const t=r.firstChild.firstChild;this.#Co(t,a)}}}updateParent(t,e){if(e===this)return;const i=this.#yo.get(t);if(i){e.#nn.append(i);this.#yo.delete(t);e.#yo.set(t,i)}}remove(t){this.#xo.delete(t);if(null!==this.#nn){this.#yo.get(t).remove();this.#yo.delete(t)}}destroy(){this.#nn=null;for(const t of this.#yo.values())t.remove();this.#yo.clear();this.#xo.clear()}}globalThis.pdfjsTestingUtils={HighlightOutliner};var Ut=__webpack_exports__.AbortException,Gt=__webpack_exports__.AnnotationEditorLayer,$t=__webpack_exports__.AnnotationEditorParamsType,Vt=__webpack_exports__.AnnotationEditorType,jt=__webpack_exports__.AnnotationEditorUIManager,Wt=__webpack_exports__.AnnotationLayer,qt=__webpack_exports__.AnnotationMode,Xt=__webpack_exports__.ColorPicker,Kt=__webpack_exports__.DOMSVGFactory,Yt=__webpack_exports__.DrawLayer,Qt=__webpack_exports__.FeatureTest,Jt=__webpack_exports__.GlobalWorkerOptions,Zt=__webpack_exports__.ImageKind,te=__webpack_exports__.InvalidPDFException,ee=__webpack_exports__.MissingPDFException,ie=__webpack_exports__.OPS,se=__webpack_exports__.OutputScale,ne=__webpack_exports__.PDFDataRangeTransport,ae=__webpack_exports__.PDFDateString,re=__webpack_exports__.PDFWorker,oe=__webpack_exports__.PasswordResponses,le=__webpack_exports__.PermissionFlag,he=__webpack_exports__.PixelsPerInch,de=__webpack_exports__.RenderingCancelledException,ce=__webpack_exports__.TextLayer,ue=__webpack_exports__.TouchManager,pe=__webpack_exports__.UnexpectedResponseException,ge=__webpack_exports__.Util,me=__webpack_exports__.VerbosityLevel,fe=__webpack_exports__.XfaLayer,be=__webpack_exports__.build,Ae=__webpack_exports__.createValidAbsoluteUrl,we=__webpack_exports__.fetchData,ve=__webpack_exports__.getDocument,ye=__webpack_exports__.getFilenameFromUrl,xe=__webpack_exports__.getPdfFilenameFromUrl,_e=__webpack_exports__.getXfaPageViewport,Ee=__webpack_exports__.isDataScheme,Se=__webpack_exports__.isPdfFile,Ce=__webpack_exports__.noContextMenu,Te=__webpack_exports__.normalizeUnicode,Me=__webpack_exports__.setLayerDimensions,Pe=__webpack_exports__.shadow,De=__webpack_exports__.stopEvent,ke=__webpack_exports__.version;export{Ut as AbortException,Gt as AnnotationEditorLayer,$t as AnnotationEditorParamsType,Vt as AnnotationEditorType,jt as AnnotationEditorUIManager,Wt as AnnotationLayer,qt as AnnotationMode,Xt as ColorPicker,Kt as DOMSVGFactory,Yt as DrawLayer,Qt as FeatureTest,Jt as GlobalWorkerOptions,Zt as ImageKind,te as InvalidPDFException,ee as MissingPDFException,ie as OPS,se as OutputScale,ne as PDFDataRangeTransport,ae as PDFDateString,re as PDFWorker,oe as PasswordResponses,le as PermissionFlag,he as PixelsPerInch,de as RenderingCancelledException,ce as TextLayer,ue as TouchManager,pe as UnexpectedResponseException,ge as Util,me as VerbosityLevel,fe as XfaLayer,be as build,Ae as createValidAbsoluteUrl,we as fetchData,ve as getDocument,ye as getFilenameFromUrl,xe as getPdfFilenameFromUrl,_e as getXfaPageViewport,Ee as isDataScheme,Se as isPdfFile,Ce as noContextMenu,Te as normalizeUnicode,Me as setLayerDimensions,Pe as shadow,De as stopEvent,ke as version}; \ No newline at end of file diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/build/pdf.worker.min.mjs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/build/pdf.worker.min.mjs deleted file mode 100644 index ee4038504a6..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/build/pdf.worker.min.mjs +++ /dev/null @@ -1,21 +0,0 @@ -/** - * @licstart The following is the entire license notice for the - * JavaScript code in this page - * - * Copyright 2024 Mozilla Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * @licend The above is the entire license notice for the - * JavaScript code in this page - */var e={d:(t,i)=>{for(var a in i)e.o(i,a)&&!e.o(t,a)&&Object.defineProperty(t,a,{enumerable:!0,get:i[a]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},__webpack_exports__ = globalThis.pdfjsWorker = {};e.d(__webpack_exports__,{WorkerMessageHandler:()=>WorkerMessageHandler});const t=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),i=[1,0,0,1,0,0],a=[.001,0,0,.001,0,0],s=1.35,r=.35,n=.25925925925925924,g=1,o=2,c=4,C=8,h=16,l=64,Q=128,E=256,u="pdfjs_internal_editor_",d=3,f=9,p=13,m=15,y={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},w=0,D=4,b=1,F=2,S=3,k=1,R=2,N=3,G=4,M=5,U=6,x=7,L=8,H=9,J=10,Y=11,v=12,K=13,T=14,q=15,O=16,W=17,j=20,X="Group",Z="R",V=1,z=2,_=4,$=16,AA=32,eA=128,tA=512,iA=1,aA=2,sA=4096,rA=8192,nA=32768,gA=65536,oA=131072,IA=1048576,cA=2097152,CA=8388608,hA=16777216,lA=1,BA=2,QA=3,EA=4,uA=5,dA={E:"Mouse Enter",X:"Mouse Exit",D:"Mouse Down",U:"Mouse Up",Fo:"Focus",Bl:"Blur",PO:"PageOpen",PC:"PageClose",PV:"PageVisible",PI:"PageInvisible",K:"Keystroke",F:"Format",V:"Validate",C:"Calculate"},fA={WC:"WillClose",WS:"WillSave",DS:"DidSave",WP:"WillPrint",DP:"DidPrint"},pA={O:"PageOpen",C:"PageClose"},mA=1,yA=5,wA=1,DA=2,bA=3,FA=4,SA=5,kA=6,RA=7,NA=8,GA=9,MA=10,UA=11,xA=12,LA=13,HA=14,JA=15,YA=16,vA=17,KA=18,TA=19,qA=20,OA=21,PA=22,WA=23,jA=24,XA=25,ZA=26,VA=27,zA=28,_A=29,$A=30,Ae=31,ee=32,te=33,ie=34,ae=35,se=36,re=37,ne=38,ge=39,oe=40,Ie=41,ce=42,Ce=43,he=44,le=45,Be=46,Qe=47,Ee=48,ue=49,de=50,fe=51,pe=52,me=53,ye=54,we=55,De=56,be=57,Fe=58,Se=59,ke=60,Re=61,Ne=62,Ge=63,Me=64,Ue=65,xe=66,Le=67,He=68,Je=69,Ye=70,ve=71,Ke=72,Te=73,qe=74,Oe=75,Pe=76,We=77,je=80,Xe=81,Ze=83,Ve=84,ze=85,_e=86,$e=87,At=88,et=89,tt=90,it=91,at=92,st=93,rt=1,nt=2;let gt=mA;function getVerbosityLevel(){return gt}function info(e){gt>=yA&&console.log(`Info: ${e}`)}function warn(e){gt>=mA&&console.log(`Warning: ${e}`)}function unreachable(e){throw new Error(e)}function assert(e,t){e||unreachable(t)}function createValidAbsoluteUrl(e,t=null,i=null){if(!e)return null;try{if(i&&"string"==typeof e){if(i.addDefaultProtocol&&e.startsWith("www.")){const t=e.match(/\./g);t?.length>=2&&(e=`http://${e}`)}if(i.tryConvertEncoding)try{e=stringToUTF8String(e)}catch{}}const a=t?new URL(e,t):new URL(e);if(function _isValidProtocol(e){switch(e?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(a))return a}catch{}return null}function shadow(e,t,i,a=!1){Object.defineProperty(e,t,{value:i,enumerable:!a,configurable:!0,writable:!1});return i}const ot=function BaseExceptionClosure(){function BaseException(e,t){this.message=e;this.name=t}BaseException.prototype=new Error;BaseException.constructor=BaseException;return BaseException}();class PasswordException extends ot{constructor(e,t){super(e,"PasswordException");this.code=t}}class UnknownErrorException extends ot{constructor(e,t){super(e,"UnknownErrorException");this.details=t}}class InvalidPDFException extends ot{constructor(e){super(e,"InvalidPDFException")}}class MissingPDFException extends ot{constructor(e){super(e,"MissingPDFException")}}class UnexpectedResponseException extends ot{constructor(e,t){super(e,"UnexpectedResponseException");this.status=t}}class FormatError extends ot{constructor(e){super(e,"FormatError")}}class AbortException extends ot{constructor(e){super(e,"AbortException")}}function bytesToString(e){"object"==typeof e&&void 0!==e?.length||unreachable("Invalid argument for bytesToString");const t=e.length,i=8192;if(t>24&255,e>>16&255,e>>8&255,255&e)}function objectSize(e){return Object.keys(e).length}class FeatureTest{static get isLittleEndian(){return shadow(this,"isLittleEndian",function isLittleEndian(){const e=new Uint8Array(4);e[0]=1;return 1===new Uint32Array(e.buffer,0,1)[0]}())}static get isEvalSupported(){return shadow(this,"isEvalSupported",function isEvalSupported(){try{new Function("");return!0}catch{return!1}}())}static get isOffscreenCanvasSupported(){return shadow(this,"isOffscreenCanvasSupported","undefined"!=typeof OffscreenCanvas)}static get isImageDecoderSupported(){return shadow(this,"isImageDecoderSupported","undefined"!=typeof ImageDecoder)}static get platform(){return"undefined"!=typeof navigator&&"string"==typeof navigator?.platform?shadow(this,"platform",{isMac:navigator.platform.includes("Mac"),isWindows:navigator.platform.includes("Win"),isFirefox:"string"==typeof navigator?.userAgent&&navigator.userAgent.includes("Firefox")}):shadow(this,"platform",{isMac:!1,isWindows:!1,isFirefox:!1})}static get isCSSRoundSupported(){return shadow(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}const It=Array.from(Array(256).keys(),(e=>e.toString(16).padStart(2,"0")));class Util{static makeHexColor(e,t,i){return`#${It[e]}${It[t]}${It[i]}`}static scaleMinMax(e,t){let i;if(e[0]){if(e[0]<0){i=t[0];t[0]=t[2];t[2]=i}t[0]*=e[0];t[2]*=e[0];if(e[3]<0){i=t[1];t[1]=t[3];t[3]=i}t[1]*=e[3];t[3]*=e[3]}else{i=t[0];t[0]=t[1];t[1]=i;i=t[2];t[2]=t[3];t[3]=i;if(e[1]<0){i=t[1];t[1]=t[3];t[3]=i}t[1]*=e[1];t[3]*=e[1];if(e[2]<0){i=t[0];t[0]=t[2];t[2]=i}t[0]*=e[2];t[2]*=e[2]}t[0]+=e[4];t[1]+=e[5];t[2]+=e[4];t[3]+=e[5]}static transform(e,t){return[e[0]*t[0]+e[2]*t[1],e[1]*t[0]+e[3]*t[1],e[0]*t[2]+e[2]*t[3],e[1]*t[2]+e[3]*t[3],e[0]*t[4]+e[2]*t[5]+e[4],e[1]*t[4]+e[3]*t[5]+e[5]]}static applyTransform(e,t){return[e[0]*t[0]+e[1]*t[2]+t[4],e[0]*t[1]+e[1]*t[3]+t[5]]}static applyInverseTransform(e,t){const i=t[0]*t[3]-t[1]*t[2];return[(e[0]*t[3]-e[1]*t[2]+t[2]*t[5]-t[4]*t[3])/i,(-e[0]*t[1]+e[1]*t[0]+t[4]*t[1]-t[5]*t[0])/i]}static getAxialAlignedBoundingBox(e,t){const i=this.applyTransform(e,t),a=this.applyTransform(e.slice(2,4),t),s=this.applyTransform([e[0],e[3]],t),r=this.applyTransform([e[2],e[1]],t);return[Math.min(i[0],a[0],s[0],r[0]),Math.min(i[1],a[1],s[1],r[1]),Math.max(i[0],a[0],s[0],r[0]),Math.max(i[1],a[1],s[1],r[1])]}static inverseTransform(e){const t=e[0]*e[3]-e[1]*e[2];return[e[3]/t,-e[1]/t,-e[2]/t,e[0]/t,(e[2]*e[5]-e[4]*e[3])/t,(e[4]*e[1]-e[5]*e[0])/t]}static singularValueDecompose2dScale(e){const t=[e[0],e[2],e[1],e[3]],i=e[0]*t[0]+e[1]*t[2],a=e[0]*t[1]+e[1]*t[3],s=e[2]*t[0]+e[3]*t[2],r=e[2]*t[1]+e[3]*t[3],n=(i+r)/2,g=Math.sqrt((i+r)**2-4*(i*r-s*a))/2,o=n+g||1,c=n-g||1;return[Math.sqrt(o),Math.sqrt(c)]}static normalizeRect(e){const t=e.slice(0);if(e[0]>e[2]){t[0]=e[2];t[2]=e[0]}if(e[1]>e[3]){t[1]=e[3];t[3]=e[1]}return t}static intersect(e,t){const i=Math.max(Math.min(e[0],e[2]),Math.min(t[0],t[2])),a=Math.min(Math.max(e[0],e[2]),Math.max(t[0],t[2]));if(i>a)return null;const s=Math.max(Math.min(e[1],e[3]),Math.min(t[1],t[3])),r=Math.min(Math.max(e[1],e[3]),Math.max(t[1],t[3]));return s>r?null:[i,s,a,r]}static#A(e,t,i,a,s,r,n,g,o,c){if(o<=0||o>=1)return;const C=1-o,h=o*o,l=h*o,Q=C*(C*(C*e+3*o*t)+3*h*i)+l*a,E=C*(C*(C*s+3*o*r)+3*h*n)+l*g;c[0]=Math.min(c[0],Q);c[1]=Math.min(c[1],E);c[2]=Math.max(c[2],Q);c[3]=Math.max(c[3],E)}static#e(e,t,i,a,s,r,n,g,o,c,C,h){if(Math.abs(o)<1e-12){Math.abs(c)>=1e-12&&this.#A(e,t,i,a,s,r,n,g,-C/c,h);return}const l=c**2-4*C*o;if(l<0)return;const Q=Math.sqrt(l),E=2*o;this.#A(e,t,i,a,s,r,n,g,(-c+Q)/E,h);this.#A(e,t,i,a,s,r,n,g,(-c-Q)/E,h)}static bezierBoundingBox(e,t,i,a,s,r,n,g,o){if(o){o[0]=Math.min(o[0],e,n);o[1]=Math.min(o[1],t,g);o[2]=Math.max(o[2],e,n);o[3]=Math.max(o[3],t,g)}else o=[Math.min(e,n),Math.min(t,g),Math.max(e,n),Math.max(t,g)];this.#e(e,i,s,n,t,a,r,g,3*(3*(i-s)-e+n),6*(e-2*i+s),3*(i-e),o);this.#e(e,i,s,n,t,a,r,g,3*(3*(a-r)-t+g),6*(t-2*a+r),3*(a-t),o);return o}}const ct=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,728,711,710,729,733,731,730,732,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8226,8224,8225,8230,8212,8211,402,8260,8249,8250,8722,8240,8222,8220,8221,8216,8217,8218,8482,64257,64258,321,338,352,376,381,305,322,339,353,382,0,8364];function stringToPDFString(e){if(e[0]>="ï"){let t;if("þ"===e[0]&&"ÿ"===e[1]){t="utf-16be";e.length%2==1&&(e=e.slice(0,-1))}else if("ÿ"===e[0]&&"þ"===e[1]){t="utf-16le";e.length%2==1&&(e=e.slice(0,-1))}else"ï"===e[0]&&"»"===e[1]&&"¿"===e[2]&&(t="utf-8");if(t)try{const i=new TextDecoder(t,{fatal:!0}),a=stringToBytes(e),s=i.decode(a);return s.includes("")?s.replaceAll(/\x1b[^\x1b]*(?:\x1b|$)/g,""):s}catch(e){warn(`stringToPDFString: "${e}".`)}}const t=[];for(let i=0,a=e.length;iIt[e])).join("")}"function"!=typeof Promise.try&&(Promise.try=function(e,...t){return new Promise((i=>{i(e(...t))}))});const lt=Symbol("CIRCULAR_REF"),Bt=Symbol("EOF");let Qt=Object.create(null),Et=Object.create(null),ut=Object.create(null);class Name{constructor(e){this.name=e}static get(e){return Et[e]||=new Name(e)}}class Cmd{constructor(e){this.cmd=e}static get(e){return Qt[e]||=new Cmd(e)}}const dt=function nonSerializableClosure(){return dt};class Dict{constructor(e=null){this._map=new Map;this.xref=e;this.objId=null;this.suppressEncryption=!1;this.__nonSerializable__=dt}assignXref(e){this.xref=e}get size(){return this._map.size}get(e,t,i){let a=this._map.get(e);if(void 0===a&&void 0!==t){a=this._map.get(t);void 0===a&&void 0!==i&&(a=this._map.get(i))}return a instanceof Ref&&this.xref?this.xref.fetch(a,this.suppressEncryption):a}async getAsync(e,t,i){let a=this._map.get(e);if(void 0===a&&void 0!==t){a=this._map.get(t);void 0===a&&void 0!==i&&(a=this._map.get(i))}return a instanceof Ref&&this.xref?this.xref.fetchAsync(a,this.suppressEncryption):a}getArray(e,t,i){let a=this._map.get(e);if(void 0===a&&void 0!==t){a=this._map.get(t);void 0===a&&void 0!==i&&(a=this._map.get(i))}a instanceof Ref&&this.xref&&(a=this.xref.fetch(a,this.suppressEncryption));if(Array.isArray(a)){a=a.slice();for(let e=0,t=a.length;e{unreachable("Should not call `set` on the empty dictionary.")};return shadow(this,"empty",e)}static merge({xref:e,dictArray:t,mergeSubDicts:i=!1}){const a=new Dict(e),s=new Map;for(const e of t)if(e instanceof Dict)for(const[t,a]of e._map){let e=s.get(t);if(void 0===e){e=[];s.set(t,e)}else if(!(i&&a instanceof Dict))continue;e.push(a)}for(const[t,i]of s){if(1===i.length||!(i[0]instanceof Dict)){a._map.set(t,i[0]);continue}const s=new Dict(e);for(const e of i)for(const[t,i]of e._map)s._map.has(t)||s._map.set(t,i);s.size>0&&a._map.set(t,s)}s.clear();return a.size>0?a:Dict.empty}clone(){const e=new Dict(this.xref);for(const t of this.getKeys())e.set(t,this.getRaw(t));return e}delete(e){delete this._map[e]}}class Ref{constructor(e,t){this.num=e;this.gen=t}toString(){return 0===this.gen?`${this.num}R`:`${this.num}R${this.gen}`}static fromString(e){const t=ut[e];if(t)return t;const i=/^(\d+)R(\d*)$/.exec(e);return i&&"0"!==i[1]?ut[e]=new Ref(parseInt(i[1]),i[2]?parseInt(i[2]):0):null}static get(e,t){const i=0===t?`${e}R`:`${e}R${t}`;return ut[i]||=new Ref(e,t)}}class RefSet{constructor(e=null){this._set=new Set(e?._set)}has(e){return this._set.has(e.toString())}put(e){this._set.add(e.toString())}remove(e){this._set.delete(e.toString())}[Symbol.iterator](){return this._set.values()}clear(){this._set.clear()}}class RefSetCache{constructor(){this._map=new Map}get size(){return this._map.size}get(e){return this._map.get(e.toString())}has(e){return this._map.has(e.toString())}put(e,t){this._map.set(e.toString(),t)}putAlias(e,t){this._map.set(e.toString(),this.get(t))}[Symbol.iterator](){return this._map.values()}clear(){this._map.clear()}*values(){yield*this._map.values()}*items(){for(const[e,t]of this._map)yield[Ref.fromString(e),t]}}function isName(e,t){return e instanceof Name&&(void 0===t||e.name===t)}function isCmd(e,t){return e instanceof Cmd&&(void 0===t||e.cmd===t)}function isDict(e,t){return e instanceof Dict&&(void 0===t||isName(e.get("Type"),t))}function isRefsEqual(e,t){return e.num===t.num&&e.gen===t.gen}class BaseStream{get length(){unreachable("Abstract getter `length` accessed")}get isEmpty(){unreachable("Abstract getter `isEmpty` accessed")}get isDataLoaded(){return shadow(this,"isDataLoaded",!0)}getByte(){unreachable("Abstract method `getByte` called")}getBytes(e){unreachable("Abstract method `getBytes` called")}async getImageData(e,t){return this.getBytes(e,t)}async asyncGetBytes(){unreachable("Abstract method `asyncGetBytes` called")}get isAsync(){return!1}get canAsyncDecodeImageFromBuffer(){return!1}async getTransferableImage(){return null}peekByte(){const e=this.getByte();-1!==e&&this.pos--;return e}peekBytes(e){const t=this.getBytes(e);this.pos-=t.length;return t}getUint16(){const e=this.getByte(),t=this.getByte();return-1===e||-1===t?-1:(e<<8)+t}getInt32(){return(this.getByte()<<24)+(this.getByte()<<16)+(this.getByte()<<8)+this.getByte()}getByteRange(e,t){unreachable("Abstract method `getByteRange` called")}getString(e){return bytesToString(this.getBytes(e))}skip(e){this.pos+=e||1}reset(){unreachable("Abstract method `reset` called")}moveStart(){unreachable("Abstract method `moveStart` called")}makeSubStream(e,t,i=null){unreachable("Abstract method `makeSubStream` called")}getBaseStreams(){return null}}const ft=/^[1-9]\.\d$/,pt=2**31-1;function getLookupTableFactory(e){let t;return function(){if(e){t=Object.create(null);e(t);e=null}return t}}class MissingDataException extends ot{constructor(e,t){super(`Missing data [${e}, ${t})`,"MissingDataException");this.begin=e;this.end=t}}class ParserEOFException extends ot{constructor(e){super(e,"ParserEOFException")}}class XRefEntryException extends ot{constructor(e){super(e,"XRefEntryException")}}class XRefParseException extends ot{constructor(e){super(e,"XRefParseException")}}function arrayBuffersToBytes(e){const t=e.length;if(0===t)return new Uint8Array(0);if(1===t)return new Uint8Array(e[0]);let i=0;for(let a=0;a0,"The number should be a positive integer.");const i="M".repeat(e/1e3|0)+mt[e%1e3/100|0]+mt[10+(e%100/10|0)]+mt[20+e%10];return t?i.toLowerCase():i}function log2(e){return e>0?Math.ceil(Math.log2(e)):0}function readInt8(e,t){return e[t]<<24>>24}function readUint16(e,t){return e[t]<<8|e[t+1]}function readUint32(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}function isWhiteSpace(e){return 32===e||9===e||13===e||10===e}function isNumberArray(e,t){return Array.isArray(e)?(null===t||e.length===t)&&e.every((e=>"number"==typeof e)):ArrayBuffer.isView(e)&&(0===e.length||"number"==typeof e[0])&&(null===t||e.length===t)}function lookupMatrix(e,t){return isNumberArray(e,6)?e:t}function lookupRect(e,t){return isNumberArray(e,4)?e:t}function lookupNormalRect(e,t){return isNumberArray(e,4)?Util.normalizeRect(e):t}function parseXFAPath(e){const t=/(.+)\[(\d+)\]$/;return e.split(".").map((e=>{const i=e.match(t);return i?{name:i[1],pos:parseInt(i[2],10)}:{name:e,pos:0}}))}function escapePDFName(e){const t=[];let i=0;for(let a=0,s=e.length;a126||35===s||40===s||41===s||60===s||62===s||91===s||93===s||123===s||125===s||47===s||37===s){i"\n"===e?"\\n":"\r"===e?"\\r":`\\${e}`))}function _collectJS(e,t,i,a){if(!e)return;let s=null;if(e instanceof Ref){if(a.has(e))return;s=e;a.put(s);e=t.fetch(e)}if(Array.isArray(e))for(const s of e)_collectJS(s,t,i,a);else if(e instanceof Dict){if(isName(e.get("S"),"JavaScript")){const t=e.get("JS");let a;t instanceof BaseStream?a=t.getString():"string"==typeof t&&(a=t);a&&=stringToPDFString(a).replaceAll("\0","");a&&i.push(a)}_collectJS(e.getRaw("Next"),t,i,a)}s&&a.remove(s)}function collectActions(e,t,i){const a=Object.create(null),s=getInheritableProperty({dict:t,key:"AA",stopWhenFound:!1});if(s)for(let t=s.length-1;t>=0;t--){const r=s[t];if(r instanceof Dict)for(const t of r.getKeys()){const s=i[t];if(!s)continue;const n=[];_collectJS(r.getRaw(t),e,n,new RefSet);n.length>0&&(a[s]=n)}}if(t.has("A")){const i=[];_collectJS(t.get("A"),e,i,new RefSet);i.length>0&&(a.Action=i)}return objectSize(a)>0?a:null}const yt={60:"<",62:">",38:"&",34:""",39:"'"};function*codePointIter(e){for(let t=0,i=e.length;t55295&&(i<57344||i>65533)&&t++;yield i}}function encodeToXmlString(e){const t=[];let i=0;for(let a=0,s=e.length;a55295&&(s<57344||s>65533)&&a++;i=a+1}}if(0===t.length)return e;i: ${e}.`);return!1}return!0}function validateCSSFont(e){const t=new Set(["100","200","300","400","500","600","700","800","900","1000","normal","bold","bolder","lighter"]),{fontFamily:i,fontWeight:a,italicAngle:s}=e;if(!validateFontName(i,!0))return!1;const r=a?a.toString():"";e.fontWeight=t.has(r)?r:"400";const n=parseFloat(s);e.italicAngle=isNaN(n)||n<-90||n>90?"14":s.toString();return!0}function recoverJsURL(e){const t=new RegExp("^\\s*("+["app.launchURL","window.open","xfa.host.gotoURL"].join("|").replaceAll(".","\\.")+")\\((?:'|\")([^'\"]*)(?:'|\")(?:,\\s*(\\w+)\\)|\\))","i").exec(e);return t?.[2]?{url:t[2],newWindow:"app.launchURL"===t[1]&&"true"===t[3]}:null}function numberToString(e){if(Number.isInteger(e))return e.toString();const t=Math.round(100*e);return t%100==0?(t/100).toString():t%10==0?e.toFixed(1):e.toFixed(2)}function getNewAnnotationsMap(e){if(!e)return null;const t=new Map;for(const[i,a]of e){if(!i.startsWith(u))continue;let e=t.get(a.pageIndex);if(!e){e=[];t.set(a.pageIndex,e)}e.push(a)}return t.size>0?t:null}function stringToAsciiOrUTF16BE(e){return function isAscii(e){return/^[\x00-\x7F]*$/.test(e)}(e)?e:stringToUTF16String(e,!0)}function stringToUTF16HexString(e){const t=[];for(let i=0,a=e.length;i>8&255],It[255&a])}return t.join("")}function stringToUTF16String(e,t=!1){const i=[];t&&i.push("þÿ");for(let t=0,a=e.length;t>8&255),String.fromCharCode(255&a))}return i.join("")}function getRotationMatrix(e,t,i){switch(e){case 90:return[0,1,-1,0,t,0];case 180:return[-1,0,0,-1,t,i];case 270:return[0,-1,1,0,0,i];default:throw new Error("Invalid rotation")}}function getSizeInBytes(e){return Math.ceil(Math.ceil(Math.log2(1+e))/8)}class Stream extends BaseStream{constructor(e,t,i,a){super();this.bytes=e instanceof Uint8Array?e:new Uint8Array(e);this.start=t||0;this.pos=this.start;this.end=t+i||this.bytes.length;this.dict=a}get length(){return this.end-this.start}get isEmpty(){return 0===this.length}getByte(){return this.pos>=this.end?-1:this.bytes[this.pos++]}getBytes(e){const t=this.bytes,i=this.pos,a=this.end;if(!e)return t.subarray(i,a);let s=i+e;s>a&&(s=a);this.pos=s;return t.subarray(i,s)}getByteRange(e,t){e<0&&(e=0);t>this.end&&(t=this.end);return this.bytes.subarray(e,t)}reset(){this.pos=this.start}moveStart(){this.start=this.pos}makeSubStream(e,t,i=null){return new Stream(this.bytes.buffer,e,t,i)}}class StringStream extends Stream{constructor(e){super(stringToBytes(e))}}class NullStream extends Stream{constructor(){super(new Uint8Array(0))}}class ChunkedStream extends Stream{constructor(e,t,i){super(new Uint8Array(e),0,e,null);this.chunkSize=t;this._loadedChunks=new Set;this.numChunks=Math.ceil(e/t);this.manager=i;this.progressiveDataLength=0;this.lastSuccessfulEnsureByteChunk=-1}getMissingChunks(){const e=[];for(let t=0,i=this.numChunks;t=this.end?this.numChunks:Math.floor(t/this.chunkSize);for(let e=i;ethis.numChunks)&&t!==this.lastSuccessfulEnsureByteChunk){if(!this._loadedChunks.has(t))throw new MissingDataException(e,e+1);this.lastSuccessfulEnsureByteChunk=t}}ensureRange(e,t){if(e>=t)return;if(t<=this.progressiveDataLength)return;const i=Math.floor(e/this.chunkSize);if(i>this.numChunks)return;const a=Math.min(Math.floor((t-1)/this.chunkSize)+1,this.numChunks);for(let s=i;s=this.end)return-1;e>=this.progressiveDataLength&&this.ensureByte(e);return this.bytes[this.pos++]}getBytes(e){const t=this.bytes,i=this.pos,a=this.end;if(!e){a>this.progressiveDataLength&&this.ensureRange(i,a);return t.subarray(i,a)}let s=i+e;s>a&&(s=a);s>this.progressiveDataLength&&this.ensureRange(i,s);this.pos=s;return t.subarray(i,s)}getByteRange(e,t){e<0&&(e=0);t>this.end&&(t=this.end);t>this.progressiveDataLength&&this.ensureRange(e,t);return this.bytes.subarray(e,t)}makeSubStream(e,t,i=null){t?e+t>this.progressiveDataLength&&this.ensureRange(e,e+t):e>=this.progressiveDataLength&&this.ensureByte(e);function ChunkedStreamSubstream(){}ChunkedStreamSubstream.prototype=Object.create(this);ChunkedStreamSubstream.prototype.getMissingChunks=function(){const e=this.chunkSize,t=Math.floor(this.start/e),i=Math.floor((this.end-1)/e)+1,a=[];for(let e=t;e{const readChunk=({value:r,done:n})=>{try{if(n){const t=arrayBuffersToBytes(a);a=null;e(t);return}s+=r.byteLength;i.isStreamingSupported&&this.onProgress({loaded:s});a.push(r);i.read().then(readChunk,t)}catch(e){t(e)}};i.read().then(readChunk,t)})).then((t=>{this.aborted||this.onReceiveData({chunk:t,begin:e})}))}requestAllChunks(e=!1){if(!e){const e=this.stream.getMissingChunks();this._requestChunks(e)}return this._loadedStreamCapability.promise}_requestChunks(e){const t=this.currRequestId++,i=new Set;this._chunksNeededByRequest.set(t,i);for(const t of e)this.stream.hasChunk(t)||i.add(t);if(0===i.size)return Promise.resolve();const a=Promise.withResolvers();this._promisesByRequest.set(t,a);const s=[];for(const e of i){let i=this._requestsByChunk.get(e);if(!i){i=[];this._requestsByChunk.set(e,i);s.push(e)}i.push(t)}if(s.length>0){const e=this.groupChunks(s);for(const t of e){const e=t.beginChunk*this.chunkSize,i=Math.min(t.endChunk*this.chunkSize,this.length);this.sendRequest(e,i).catch(a.reject)}}return a.promise.catch((e=>{if(!this.aborted)throw e}))}getStream(){return this.stream}requestRange(e,t){t=Math.min(t,this.length);const i=this.getBeginChunk(e),a=this.getEndChunk(t),s=[];for(let e=i;e=0&&a+1!==r){t.push({beginChunk:i,endChunk:a+1});i=r}s+1===e.length&&t.push({beginChunk:i,endChunk:r+1});a=r}return t}onProgress(e){this.msgHandler.send("DocProgress",{loaded:this.stream.numChunksLoaded*this.chunkSize+e.loaded,total:this.length})}onReceiveData(e){const t=e.chunk,i=void 0===e.begin,a=i?this.progressiveDataLength:e.begin,s=a+t.byteLength,r=Math.floor(a/this.chunkSize),n=s0||g.push(i)}}}if(!this.disableAutoFetch&&0===this._requestsByChunk.size){let e;if(1===this.stream.numChunksLoaded){const t=this.stream.numChunks-1;this.stream.hasChunk(t)||(e=t)}else e=this.stream.nextEmptyChunk(n);Number.isInteger(e)&&this._requestChunks([e])}for(const e of g){const t=this._promisesByRequest.get(e);this._promisesByRequest.delete(e);t.resolve()}this.msgHandler.send("DocProgress",{loaded:this.stream.numChunksLoaded*this.chunkSize,total:this.length})}onError(e){this._loadedStreamCapability.reject(e)}getBeginChunk(e){return Math.floor(e/this.chunkSize)}getEndChunk(e){return Math.floor((e-1)/this.chunkSize)+1}abort(e){this.aborted=!0;this.pdfNetworkStream?.cancelAllRequests(e);for(const t of this._promisesByRequest.values())t.reject(e)}}class ColorSpace{constructor(e,t){this.name=e;this.numComps=t}getRgb(e,t){const i=new Uint8ClampedArray(3);this.getRgbItem(e,t,i,0);return i}getRgbItem(e,t,i,a){unreachable("Should not call ColorSpace.getRgbItem")}getRgbBuffer(e,t,i,a,s,r,n){unreachable("Should not call ColorSpace.getRgbBuffer")}getOutputLength(e,t){unreachable("Should not call ColorSpace.getOutputLength")}isPassthrough(e){return!1}isDefaultDecode(e,t){return ColorSpace.isDefaultDecode(e,this.numComps)}fillRgb(e,t,i,a,s,r,n,g,o){const c=t*i;let C=null;const h=1<h&&"DeviceGray"!==this.name&&"DeviceRGB"!==this.name){const t=n<=8?new Uint8Array(h):new Uint16Array(h);for(let e=0;e=.99554525?1:this.#B(0,1,1.055*e**(1/2.4)-.055)}#B(e,t,i){return Math.max(e,Math.min(t,i))}#Q(e){return e<0?-this.#Q(-e):e>8?((e+16)/116)**3:e*CalRGBCS.#I}#E(e,t,i){if(0===e[0]&&0===e[1]&&0===e[2]){i[0]=t[0];i[1]=t[1];i[2]=t[2];return}const a=this.#Q(0),s=(1-a)/(1-this.#Q(e[0])),r=1-s,n=(1-a)/(1-this.#Q(e[1])),g=1-n,o=(1-a)/(1-this.#Q(e[2])),c=1-o;i[0]=t[0]*s+r;i[1]=t[1]*n+g;i[2]=t[2]*o+c}#u(e,t,i){if(1===e[0]&&1===e[2]){i[0]=t[0];i[1]=t[1];i[2]=t[2];return}const a=i;this.#c(CalRGBCS.#i,t,a);const s=CalRGBCS.#n;this.#C(e,a,s);this.#c(CalRGBCS.#a,s,i)}#d(e,t,i){const a=i;this.#c(CalRGBCS.#i,t,a);const s=CalRGBCS.#n;this.#h(e,a,s);this.#c(CalRGBCS.#a,s,i)}#t(e,t,i,a,s){const r=this.#B(0,1,e[t]*s),n=this.#B(0,1,e[t+1]*s),g=this.#B(0,1,e[t+2]*s),o=1===r?1:r**this.GR,c=1===n?1:n**this.GG,C=1===g?1:g**this.GB,h=this.MXA*o+this.MXB*c+this.MXC*C,l=this.MYA*o+this.MYB*c+this.MYC*C,Q=this.MZA*o+this.MZB*c+this.MZC*C,E=CalRGBCS.#g;E[0]=h;E[1]=l;E[2]=Q;const u=CalRGBCS.#o;this.#u(this.whitePoint,E,u);const d=CalRGBCS.#g;this.#E(this.blackPoint,u,d);const f=CalRGBCS.#o;this.#d(CalRGBCS.#r,d,f);const p=CalRGBCS.#g;this.#c(CalRGBCS.#s,f,p);i[a]=255*this.#l(p[0]);i[a+1]=255*this.#l(p[1]);i[a+2]=255*this.#l(p[2])}getRgbItem(e,t,i,a){this.#t(e,t,i,a,1)}getRgbBuffer(e,t,i,a,s,r,n){const g=1/((1<this.amax||this.bmin>this.bmax){info("Invalid Range, falling back to defaults");this.amin=-100;this.amax=100;this.bmin=-100;this.bmax=100}}#f(e){return e>=6/29?e**3:108/841*(e-4/29)}#p(e,t,i,a){return i+e*(a-i)/t}#t(e,t,i,a,s){let r=e[t],n=e[t+1],g=e[t+2];if(!1!==i){r=this.#p(r,i,0,100);n=this.#p(n,i,this.amin,this.amax);g=this.#p(g,i,this.bmin,this.bmax)}n>this.amax?n=this.amax:nthis.bmax?g=this.bmax:g>>0}function hexToStr(e,t){return 1===t?String.fromCharCode(e[0],e[1]):3===t?String.fromCharCode(e[0],e[1],e[2],e[3]):String.fromCharCode(...e.subarray(0,t+1))}function addHex(e,t,i){let a=0;for(let s=i;s>=0;s--){a+=e[s]+t[s];e[s]=255&a;a>>=8}}function incHex(e,t){let i=1;for(let a=t;a>=0&&i>0;a--){i+=e[a];e[a]=255&i;i>>=8}}const wt=16;class BinaryCMapStream{constructor(e){this.buffer=e;this.pos=0;this.end=e.length;this.tmpBuf=new Uint8Array(19)}readByte(){return this.pos>=this.end?-1:this.buffer[this.pos++]}readNumber(){let e,t=0;do{const i=this.readByte();if(i<0)throw new FormatError("unexpected EOF in bcmap");e=!(128&i);t=t<<7|127&i}while(!e);return t}readSigned(){const e=this.readNumber();return 1&e?~(e>>>1):e>>>1}readHex(e,t){e.set(this.buffer.subarray(this.pos,this.pos+t+1));this.pos+=t+1}readHexNumber(e,t){let i;const a=this.tmpBuf;let s=0;do{const e=this.readByte();if(e<0)throw new FormatError("unexpected EOF in bcmap");i=!(128&e);a[s++]=127&e}while(!i);let r=t,n=0,g=0;for(;r>=0;){for(;g<8&&a.length>0;){n|=a[--s]<>=8;g-=8}}readHexSigned(e,t){this.readHexNumber(e,t);const i=1&e[t]?255:0;let a=0;for(let s=0;s<=t;s++){a=(1&a)<<8|e[s];e[s]=a>>1^i}}readString(){const e=this.readNumber(),t=new Array(e);for(let i=0;i=0;){const e=l>>5;if(7===e){switch(31&l){case 0:a.readString();break;case 1:r=a.readString()}continue}const i=!!(16&l),s=15&l;if(s+1>wt)throw new Error("BinaryCMapReader.process: Invalid dataSize.");const Q=1,E=a.readNumber();switch(e){case 0:a.readHex(n,s);a.readHexNumber(g,s);addHex(g,n,s);t.addCodespaceRange(s+1,hexToInt(n,s),hexToInt(g,s));for(let e=1;es&&(a=s)}else{for(;!this.eof;)this.readBlock(t);a=this.bufferLength}this.pos=a;return this.buffer.subarray(i,a)}async getImageData(e,t=null){if(!this.canAsyncDecodeImageFromBuffer)return this.getBytes(e,t);const i=await this.stream.asyncGetBytes();return this.decodeImage(i,t)}reset(){this.pos=0}makeSubStream(e,t,i=null){if(void 0===t)for(;!this.eof;)this.readBlock();else{const i=e+t;for(;this.bufferLength<=i&&!this.eof;)this.readBlock()}return new Stream(this.buffer,e,t,i)}getBaseStreams(){return this.str?this.str.getBaseStreams():null}}class StreamsSequenceStream extends DecodeStream{constructor(e,t=null){e=e.filter((e=>e instanceof BaseStream));let i=0;for(const t of e)i+=t instanceof DecodeStream?t._rawMinBufferLength:t.length;super(i);this.streams=e;this._onError=t}readBlock(){const e=this.streams;if(0===e.length){this.eof=!0;return}const t=e.shift();let i;try{i=t.getBytes()}catch(e){if(this._onError){this._onError(e,t.dict?.objId);return}throw e}const a=this.bufferLength,s=a+i.length;this.ensureBuffer(s).set(i,a);this.bufferLength=s}getBaseStreams(){const e=[];for(const t of this.streams){const i=t.getBaseStreams();i&&e.push(...i)}return e.length>0?e:null}}class Ascii85Stream extends DecodeStream{constructor(e,t){t&&(t*=.8);super(t);this.str=e;this.dict=e.dict;this.input=new Uint8Array(5)}readBlock(){const e=this.str;let t=e.getByte();for(;isWhiteSpace(t);)t=e.getByte();if(-1===t||126===t){this.eof=!0;return}const i=this.bufferLength;let a,s;if(122===t){a=this.ensureBuffer(i+4);for(s=0;s<4;++s)a[i+s]=0;this.bufferLength+=4}else{const r=this.input;r[0]=t;for(s=1;s<5;++s){t=e.getByte();for(;isWhiteSpace(t);)t=e.getByte();r[s]=t;if(-1===t||126===t)break}a=this.ensureBuffer(i+s-1);this.bufferLength+=s-1;if(s<5){for(;s<5;++s)r[s]=117;this.eof=!0}let n=0;for(s=0;s<5;++s)n=85*n+(r[s]-33);for(s=3;s>=0;--s){a[i+s]=255&n;n>>=8}}}}class AsciiHexStream extends DecodeStream{constructor(e,t){t&&(t*=.5);super(t);this.str=e;this.dict=e.dict;this.firstDigit=-1}readBlock(){const e=this.str.getBytes(8e3);if(!e.length){this.eof=!0;return}const t=e.length+1>>1,i=this.ensureBuffer(this.bufferLength+t);let a=this.bufferLength,s=this.firstDigit;for(const t of e){let e;if(t>=48&&t<=57)e=15&t;else{if(!(t>=65&&t<=70||t>=97&&t<=102)){if(62===t){this.eof=!0;break}continue}e=9+(15&t)}if(s<0)s=e;else{i[a++]=s<<4|e;s=-1}}if(s>=0&&this.eof){i[a++]=s<<4;s=-1}this.firstDigit=s;this.bufferLength=a}}const bt=-1,Ft=[[-1,-1],[-1,-1],[7,8],[7,7],[6,6],[6,6],[6,5],[6,5],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2]],St=[[-1,-1],[12,-2],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[11,1792],[11,1792],[12,1984],[12,2048],[12,2112],[12,2176],[12,2240],[12,2304],[11,1856],[11,1856],[11,1920],[11,1920],[12,2368],[12,2432],[12,2496],[12,2560]],kt=[[-1,-1],[-1,-1],[-1,-1],[-1,-1],[8,29],[8,29],[8,30],[8,30],[8,45],[8,45],[8,46],[8,46],[7,22],[7,22],[7,22],[7,22],[7,23],[7,23],[7,23],[7,23],[8,47],[8,47],[8,48],[8,48],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[7,20],[7,20],[7,20],[7,20],[8,33],[8,33],[8,34],[8,34],[8,35],[8,35],[8,36],[8,36],[8,37],[8,37],[8,38],[8,38],[7,19],[7,19],[7,19],[7,19],[8,31],[8,31],[8,32],[8,32],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[8,53],[8,53],[8,54],[8,54],[7,26],[7,26],[7,26],[7,26],[8,39],[8,39],[8,40],[8,40],[8,41],[8,41],[8,42],[8,42],[8,43],[8,43],[8,44],[8,44],[7,21],[7,21],[7,21],[7,21],[7,28],[7,28],[7,28],[7,28],[8,61],[8,61],[8,62],[8,62],[8,63],[8,63],[8,0],[8,0],[8,320],[8,320],[8,384],[8,384],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[7,27],[7,27],[7,27],[7,27],[8,59],[8,59],[8,60],[8,60],[9,1472],[9,1536],[9,1600],[9,1728],[7,18],[7,18],[7,18],[7,18],[7,24],[7,24],[7,24],[7,24],[8,49],[8,49],[8,50],[8,50],[8,51],[8,51],[8,52],[8,52],[7,25],[7,25],[7,25],[7,25],[8,55],[8,55],[8,56],[8,56],[8,57],[8,57],[8,58],[8,58],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[8,448],[8,448],[8,512],[8,512],[9,704],[9,768],[8,640],[8,640],[8,576],[8,576],[9,832],[9,896],[9,960],[9,1024],[9,1088],[9,1152],[9,1216],[9,1280],[9,1344],[9,1408],[7,256],[7,256],[7,256],[7,256],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7]],Rt=[[-1,-1],[-1,-1],[12,-2],[12,-2],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[11,1792],[11,1792],[11,1792],[11,1792],[12,1984],[12,1984],[12,2048],[12,2048],[12,2112],[12,2112],[12,2176],[12,2176],[12,2240],[12,2240],[12,2304],[12,2304],[11,1856],[11,1856],[11,1856],[11,1856],[11,1920],[11,1920],[11,1920],[11,1920],[12,2368],[12,2368],[12,2432],[12,2432],[12,2496],[12,2496],[12,2560],[12,2560],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[12,52],[12,52],[13,640],[13,704],[13,768],[13,832],[12,55],[12,55],[12,56],[12,56],[13,1280],[13,1344],[13,1408],[13,1472],[12,59],[12,59],[12,60],[12,60],[13,1536],[13,1600],[11,24],[11,24],[11,24],[11,24],[11,25],[11,25],[11,25],[11,25],[13,1664],[13,1728],[12,320],[12,320],[12,384],[12,384],[12,448],[12,448],[13,512],[13,576],[12,53],[12,53],[12,54],[12,54],[13,896],[13,960],[13,1024],[13,1088],[13,1152],[13,1216],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64]],Nt=[[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[11,23],[11,23],[12,50],[12,51],[12,44],[12,45],[12,46],[12,47],[12,57],[12,58],[12,61],[12,256],[10,16],[10,16],[10,16],[10,16],[10,17],[10,17],[10,17],[10,17],[12,48],[12,49],[12,62],[12,63],[12,30],[12,31],[12,32],[12,33],[12,40],[12,41],[11,22],[11,22],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[12,128],[12,192],[12,26],[12,27],[12,28],[12,29],[11,19],[11,19],[11,20],[11,20],[12,34],[12,35],[12,36],[12,37],[12,38],[12,39],[11,21],[11,21],[12,42],[12,43],[10,0],[10,0],[10,0],[10,0],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12]],Gt=[[-1,-1],[-1,-1],[-1,-1],[-1,-1],[6,9],[6,8],[5,7],[5,7],[4,6],[4,6],[4,6],[4,6],[4,5],[4,5],[4,5],[4,5],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2]];class CCITTFaxDecoder{constructor(e,t={}){if("function"!=typeof e?.next)throw new Error('CCITTFaxDecoder - invalid "source" parameter.');this.source=e;this.eof=!1;this.encoding=t.K||0;this.eoline=t.EndOfLine||!1;this.byteAlign=t.EncodedByteAlign||!1;this.columns=t.Columns||1728;this.rows=t.Rows||0;this.eoblock=t.EndOfBlock??!0;this.black=t.BlackIs1||!1;this.codingLine=new Uint32Array(this.columns+1);this.refLine=new Uint32Array(this.columns+2);this.codingLine[0]=this.columns;this.codingPos=0;this.row=0;this.nextLine2D=this.encoding<0;this.inputBits=0;this.inputBuf=0;this.outputBits=0;this.rowsDone=!1;let i;for(;0===(i=this._lookBits(12));)this._eatBits(1);1===i&&this._eatBits(12);if(this.encoding>0){this.nextLine2D=!this._lookBits(1);this._eatBits(1)}}readNextChar(){if(this.eof)return-1;const e=this.refLine,t=this.codingLine,i=this.columns;let a,s,r,n,g;if(0===this.outputBits){this.rowsDone&&(this.eof=!0);if(this.eof)return-1;this.err=!1;let r,g,o;if(this.nextLine2D){for(n=0;t[n]=64);do{g+=o=this._getWhiteCode()}while(o>=64)}else{do{r+=o=this._getWhiteCode()}while(o>=64);do{g+=o=this._getBlackCode()}while(o>=64)}this._addPixels(t[this.codingPos]+r,s);t[this.codingPos]0?--a:++a;for(;e[a]<=t[this.codingPos]&&e[a]0?--a:++a;for(;e[a]<=t[this.codingPos]&&e[a]0?--a:++a;for(;e[a]<=t[this.codingPos]&&e[a]=64);else do{r+=o=this._getWhiteCode()}while(o>=64);this._addPixels(t[this.codingPos]+r,s);s^=1}}let c=!1;this.byteAlign&&(this.inputBits&=-8);if(this.eoblock||this.row!==this.rows-1){r=this._lookBits(12);if(this.eoline)for(;r!==bt&&1!==r;){this._eatBits(1);r=this._lookBits(12)}else for(;0===r;){this._eatBits(1);r=this._lookBits(12)}if(1===r){this._eatBits(12);c=!0}else r===bt&&(this.eof=!0)}else this.rowsDone=!0;if(!this.eof&&this.encoding>0&&!this.rowsDone){this.nextLine2D=!this._lookBits(1);this._eatBits(1)}if(this.eoblock&&c&&this.byteAlign){r=this._lookBits(12);if(1===r){this._eatBits(12);if(this.encoding>0){this._lookBits(1);this._eatBits(1)}if(this.encoding>=0)for(n=0;n<4;++n){r=this._lookBits(12);1!==r&&info("bad rtc code: "+r);this._eatBits(12);if(this.encoding>0){this._lookBits(1);this._eatBits(1)}}this.eof=!0}}else if(this.err&&this.eoline){for(;;){r=this._lookBits(13);if(r===bt){this.eof=!0;return-1}if(r>>1==1)break;this._eatBits(1)}this._eatBits(12);if(this.encoding>0){this._eatBits(1);this.nextLine2D=!(1&r)}}this.outputBits=t[0]>0?t[this.codingPos=0]:t[this.codingPos=1];this.row++}if(this.outputBits>=8){g=1&this.codingPos?0:255;this.outputBits-=8;if(0===this.outputBits&&t[this.codingPos]r){g<<=r;1&this.codingPos||(g|=255>>8-r);this.outputBits-=r;r=0}else{g<<=this.outputBits;1&this.codingPos||(g|=255>>8-this.outputBits);r-=this.outputBits;this.outputBits=0;if(t[this.codingPos]0){g<<=r;r=0}}}while(r)}this.black&&(g^=255);return g}_addPixels(e,t){const i=this.codingLine;let a=this.codingPos;if(e>i[a]){if(e>this.columns){info("row is wrong length");this.err=!0;e=this.columns}1&a^t&&++a;i[a]=e}this.codingPos=a}_addPixelsNeg(e,t){const i=this.codingLine;let a=this.codingPos;if(e>i[a]){if(e>this.columns){info("row is wrong length");this.err=!0;e=this.columns}1&a^t&&++a;i[a]=e}else if(e0&&e=s){const t=i[e-s];if(t[0]===a){this._eatBits(a);return[!0,t[1],!0]}}}return[!1,0,!1]}_getTwoDimCode(){let e,t=0;if(this.eoblock){t=this._lookBits(7);e=Ft[t];if(e?.[0]>0){this._eatBits(e[0]);return e[1]}}else{const e=this._findTableCode(1,7,Ft);if(e[0]&&e[2])return e[1]}info("Bad two dim code");return bt}_getWhiteCode(){let e,t=0;if(this.eoblock){t=this._lookBits(12);if(t===bt)return 1;e=t>>5?kt[t>>3]:St[t];if(e[0]>0){this._eatBits(e[0]);return e[1]}}else{let e=this._findTableCode(1,9,kt);if(e[0])return e[1];e=this._findTableCode(11,12,St);if(e[0])return e[1]}info("bad white code");this._eatBits(1);return 1}_getBlackCode(){let e,t;if(this.eoblock){e=this._lookBits(13);if(e===bt)return 1;t=e>>7?!(e>>9)&&e>>7?Nt[(e>>1)-64]:Gt[e>>7]:Rt[e];if(t[0]>0){this._eatBits(t[0]);return t[1]}}else{let e=this._findTableCode(2,6,Gt);if(e[0])return e[1];e=this._findTableCode(7,12,Nt,64);if(e[0])return e[1];e=this._findTableCode(10,13,Rt);if(e[0])return e[1]}info("bad black code");this._eatBits(1);return 1}_lookBits(e){let t;for(;this.inputBits>16-e;this.inputBuf=this.inputBuf<<8|t;this.inputBits+=8}return this.inputBuf>>this.inputBits-e&65535>>16-e}_eatBits(e){(this.inputBits-=e)<0&&(this.inputBits=0)}}class CCITTFaxStream extends DecodeStream{constructor(e,t,i){super(t);this.str=e;this.dict=e.dict;i instanceof Dict||(i=Dict.empty);const a={next:()=>e.getByte()};this.ccittFaxDecoder=new CCITTFaxDecoder(a,{K:i.get("K"),EndOfLine:i.get("EndOfLine"),EncodedByteAlign:i.get("EncodedByteAlign"),Columns:i.get("Columns"),Rows:i.get("Rows"),EndOfBlock:i.get("EndOfBlock"),BlackIs1:i.get("BlackIs1")})}readBlock(){for(;!this.eof;){const e=this.ccittFaxDecoder.readNextChar();if(-1===e){this.eof=!0;return}this.ensureBuffer(this.bufferLength+1);this.buffer[this.bufferLength++]=e}}}const Mt=new Int32Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ut=new Int32Array([3,4,5,6,7,8,9,10,65547,65549,65551,65553,131091,131095,131099,131103,196643,196651,196659,196667,262211,262227,262243,262259,327811,327843,327875,327907,258,258,258]),xt=new Int32Array([1,2,3,4,65541,65543,131081,131085,196625,196633,262177,262193,327745,327777,393345,393409,459009,459137,524801,525057,590849,591361,657409,658433,724993,727041,794625,798721,868353,876545]),Lt=[new Int32Array([459008,524368,524304,524568,459024,524400,524336,590016,459016,524384,524320,589984,524288,524416,524352,590048,459012,524376,524312,589968,459028,524408,524344,590032,459020,524392,524328,59e4,524296,524424,524360,590064,459010,524372,524308,524572,459026,524404,524340,590024,459018,524388,524324,589992,524292,524420,524356,590056,459014,524380,524316,589976,459030,524412,524348,590040,459022,524396,524332,590008,524300,524428,524364,590072,459009,524370,524306,524570,459025,524402,524338,590020,459017,524386,524322,589988,524290,524418,524354,590052,459013,524378,524314,589972,459029,524410,524346,590036,459021,524394,524330,590004,524298,524426,524362,590068,459011,524374,524310,524574,459027,524406,524342,590028,459019,524390,524326,589996,524294,524422,524358,590060,459015,524382,524318,589980,459031,524414,524350,590044,459023,524398,524334,590012,524302,524430,524366,590076,459008,524369,524305,524569,459024,524401,524337,590018,459016,524385,524321,589986,524289,524417,524353,590050,459012,524377,524313,589970,459028,524409,524345,590034,459020,524393,524329,590002,524297,524425,524361,590066,459010,524373,524309,524573,459026,524405,524341,590026,459018,524389,524325,589994,524293,524421,524357,590058,459014,524381,524317,589978,459030,524413,524349,590042,459022,524397,524333,590010,524301,524429,524365,590074,459009,524371,524307,524571,459025,524403,524339,590022,459017,524387,524323,589990,524291,524419,524355,590054,459013,524379,524315,589974,459029,524411,524347,590038,459021,524395,524331,590006,524299,524427,524363,590070,459011,524375,524311,524575,459027,524407,524343,590030,459019,524391,524327,589998,524295,524423,524359,590062,459015,524383,524319,589982,459031,524415,524351,590046,459023,524399,524335,590014,524303,524431,524367,590078,459008,524368,524304,524568,459024,524400,524336,590017,459016,524384,524320,589985,524288,524416,524352,590049,459012,524376,524312,589969,459028,524408,524344,590033,459020,524392,524328,590001,524296,524424,524360,590065,459010,524372,524308,524572,459026,524404,524340,590025,459018,524388,524324,589993,524292,524420,524356,590057,459014,524380,524316,589977,459030,524412,524348,590041,459022,524396,524332,590009,524300,524428,524364,590073,459009,524370,524306,524570,459025,524402,524338,590021,459017,524386,524322,589989,524290,524418,524354,590053,459013,524378,524314,589973,459029,524410,524346,590037,459021,524394,524330,590005,524298,524426,524362,590069,459011,524374,524310,524574,459027,524406,524342,590029,459019,524390,524326,589997,524294,524422,524358,590061,459015,524382,524318,589981,459031,524414,524350,590045,459023,524398,524334,590013,524302,524430,524366,590077,459008,524369,524305,524569,459024,524401,524337,590019,459016,524385,524321,589987,524289,524417,524353,590051,459012,524377,524313,589971,459028,524409,524345,590035,459020,524393,524329,590003,524297,524425,524361,590067,459010,524373,524309,524573,459026,524405,524341,590027,459018,524389,524325,589995,524293,524421,524357,590059,459014,524381,524317,589979,459030,524413,524349,590043,459022,524397,524333,590011,524301,524429,524365,590075,459009,524371,524307,524571,459025,524403,524339,590023,459017,524387,524323,589991,524291,524419,524355,590055,459013,524379,524315,589975,459029,524411,524347,590039,459021,524395,524331,590007,524299,524427,524363,590071,459011,524375,524311,524575,459027,524407,524343,590031,459019,524391,524327,589999,524295,524423,524359,590063,459015,524383,524319,589983,459031,524415,524351,590047,459023,524399,524335,590015,524303,524431,524367,590079]),9],Ht=[new Int32Array([327680,327696,327688,327704,327684,327700,327692,327708,327682,327698,327690,327706,327686,327702,327694,0,327681,327697,327689,327705,327685,327701,327693,327709,327683,327699,327691,327707,327687,327703,327695,0]),5];class FlateStream extends DecodeStream{constructor(e,t){super(t);this.str=e;this.dict=e.dict;const i=e.getByte(),a=e.getByte();if(-1===i||-1===a)throw new FormatError(`Invalid header in flate stream: ${i}, ${a}`);if(8!=(15&i))throw new FormatError(`Unknown compression method in flate stream: ${i}, ${a}`);if(((i<<8)+a)%31!=0)throw new FormatError(`Bad FCHECK in flate stream: ${i}, ${a}`);if(32&a)throw new FormatError(`FDICT bit set in flate stream: ${i}, ${a}`);this.codeSize=0;this.codeBuf=0}async getImageData(e,t){const i=await this.asyncGetBytes();return i?.subarray(0,e)||this.getBytes(e)}async asyncGetBytes(){this.str.reset();const e=this.str.getBytes();try{const{readable:t,writable:i}=new DecompressionStream("deflate"),a=i.getWriter();await a.ready;a.write(e).then((async()=>{await a.ready;await a.close()})).catch((()=>{}));const s=[];let r=0;for await(const e of t){s.push(e);r+=e.byteLength}const n=new Uint8Array(r);let g=0;for(const e of s){n.set(e,g);g+=e.byteLength}return n}catch{this.str=new Stream(e,2,e.length,this.str.dict);this.reset();return null}}get isAsync(){return!0}getBits(e){const t=this.str;let i,a=this.codeSize,s=this.codeBuf;for(;a>e;this.codeSize=a-=e;return i}getCode(e){const t=this.str,i=e[0],a=e[1];let s,r=this.codeSize,n=this.codeBuf;for(;r>16,c=65535&g;if(o<1||r>o;this.codeSize=r-o;return c}generateHuffmanTable(e){const t=e.length;let i,a=0;for(i=0;ia&&(a=e[i]);const s=1<>=1}for(i=e;i>=1;if(0===t){let t;if(-1===(t=a.getByte())){this.#m("Bad block header in flate stream");return}let i=t;if(-1===(t=a.getByte())){this.#m("Bad block header in flate stream");return}i|=t<<8;if(-1===(t=a.getByte())){this.#m("Bad block header in flate stream");return}let s=t;if(-1===(t=a.getByte())){this.#m("Bad block header in flate stream");return}s|=t<<8;if(s!==(65535&~i)&&(0!==i||0!==s))throw new FormatError("Bad uncompressed block length in flate stream");this.codeBuf=0;this.codeSize=0;const r=this.bufferLength,n=r+i;e=this.ensureBuffer(n);this.bufferLength=n;if(0===i)-1===a.peekByte()&&(this.eof=!0);else{const t=a.getBytes(i);e.set(t,r);t.length0;)C[g++]=Q}s=this.generateHuffmanTable(C.subarray(0,e));r=this.generateHuffmanTable(C.subarray(e,c))}}e=this.buffer;let n=e?e.length:0,g=this.bufferLength;for(;;){let t=this.getCode(s);if(t<256){if(g+1>=n){e=this.ensureBuffer(g+1);n=e.length}e[g++]=t;continue}if(256===t){this.bufferLength=g;return}t-=257;t=Ut[t];let a=t>>16;a>0&&(a=this.getBits(a));i=(65535&t)+a;t=this.getCode(r);t=xt[t];a=t>>16;a>0&&(a=this.getBits(a));const o=(65535&t)+a;if(g+i>=n){e=this.ensureBuffer(g+i);n=e.length}for(let t=0;t>9&127;this.clow=this.clow<<7&65535;this.ct-=7;this.a=32768}byteIn(){const e=this.data;let t=this.bp;if(255===e[t])if(e[t+1]>143){this.clow+=65280;this.ct=8}else{t++;this.clow+=e[t]<<9;this.ct=7;this.bp=t}else{t++;this.clow+=t65535){this.chigh+=this.clow>>16;this.clow&=65535}}readBit(e,t){let i=e[t]>>1,a=1&e[t];const s=Jt[i],r=s.qe;let n,g=this.a-r;if(this.chigh>15&1;this.clow=this.clow<<1&65535;this.ct--}while(!(32768&g));this.a=g;e[t]=i<<1|a;return n}}class Jbig2Error extends ot{constructor(e){super(e,"Jbig2Error")}}class ContextCache{getContexts(e){return e in this?this[e]:this[e]=new Int8Array(65536)}}class DecodingContext{constructor(e,t,i){this.data=e;this.start=t;this.end=i}get decoder(){return shadow(this,"decoder",new ArithmeticDecoder(this.data,this.start,this.end))}get contextCache(){return shadow(this,"contextCache",new ContextCache)}}function decodeInteger(e,t,i){const a=e.getContexts(t);let s=1;function readBits(e){let t=0;for(let r=0;r>>0}const r=readBits(1),n=readBits(1)?readBits(1)?readBits(1)?readBits(1)?readBits(1)?readBits(32)+4436:readBits(12)+340:readBits(8)+84:readBits(6)+20:readBits(4)+4:readBits(2);let g;0===r?g=n:n>0&&(g=-n);return g>=-2147483648&&g<=pt?g:null}function decodeIAID(e,t,i){const a=e.getContexts("IAID");let s=1;for(let e=0;e=F&&x=S){K=K<<1&d;for(u=0;u=0&&H=0){J=G[L][H];J&&(K|=J<=e?c<<=1:c=c<<1|w[g][o]}for(Q=0;Q=m||o<0||o>=p?c<<=1:c=c<<1|a[g][o]}const E=D.readBit(b,c);t[n]=E}}return w}function decodeTextRegion(e,t,i,a,s,r,n,g,o,c,C,h,l,Q,E,u,d,f,p){if(e&&t)throw new Jbig2Error("refinement with Huffman is not supported");const m=[];let y,w;for(y=0;y1&&(s=e?p.readBits(f):decodeInteger(b,"IAIT",D));const r=n*F+s,S=e?Q.symbolIDTable.decode(p):decodeIAID(b,D,o),k=t&&(e?p.readBit():decodeInteger(b,"IARI",D));let R=g[S],N=R[0].length,G=R.length;if(k){const e=decodeInteger(b,"IARDW",D),t=decodeInteger(b,"IARDH",D);N+=e;G+=t;R=decodeRefinement(N,G,E,R,(e>>1)+decodeInteger(b,"IARDX",D),(t>>1)+decodeInteger(b,"IARDY",D),!1,u,d)}let M=0;c?1&h?M=G-1:a+=G-1:h>1?a+=N-1:M=N-1;const U=r-(1&h?0:G-1),x=a-(2&h?N-1:0);let L,H,J;if(c)for(L=0;L>5&7;const o=[31&n];let c=t+6;if(7===n){g=536870911&readUint32(e,c-1);c+=3;let t=g+7>>3;o[0]=e[c++];for(;--t>0;)o.push(e[c++])}else if(5===n||6===n)throw new Jbig2Error("invalid referred-to flags");i.retainBits=o;let C=4;i.number<=256?C=1:i.number<=65536&&(C=2);const h=[];let l,Q;for(l=0;l>>24&255;r[3]=t.height>>16&255;r[4]=t.height>>8&255;r[5]=255&t.height;for(l=c,Q=e.length;l>2&3;e.huffmanDWSelector=t>>4&3;e.bitmapSizeSelector=t>>6&1;e.aggregationInstancesSelector=t>>7&1;e.bitmapCodingContextUsed=!!(256&t);e.bitmapCodingContextRetained=!!(512&t);e.template=t>>10&3;e.refinementTemplate=t>>12&1;c+=2;if(!e.huffman){o=0===e.template?4:1;n=[];for(g=0;g>2&3;C.stripSize=1<>4&3;C.transposed=!!(64&h);C.combinationOperator=h>>7&3;C.defaultPixelValue=h>>9&1;C.dsOffset=h<<17>>27;C.refinementTemplate=h>>15&1;if(C.huffman){const e=readUint16(a,c);c+=2;C.huffmanFS=3&e;C.huffmanDS=e>>2&3;C.huffmanDT=e>>4&3;C.huffmanRefinementDW=e>>6&3;C.huffmanRefinementDH=e>>8&3;C.huffmanRefinementDX=e>>10&3;C.huffmanRefinementDY=e>>12&3;C.huffmanRefinementSizeSelector=!!(16384&e)}if(C.refinement&&!C.refinementTemplate){n=[];for(g=0;g<2;g++){n.push({x:readInt8(a,c),y:readInt8(a,c+1)});c+=2}C.refinementAt=n}C.numberOfSymbolInstances=readUint32(a,c);c+=4;r=[C,i.referredTo,a,c,s];break;case 16:const l={},Q=a[c++];l.mmr=!!(1&Q);l.template=Q>>1&3;l.patternWidth=a[c++];l.patternHeight=a[c++];l.maxPatternIndex=readUint32(a,c);c+=4;r=[l,i.number,a,c,s];break;case 22:case 23:const E={};E.info=readRegionSegmentInformation(a,c);c+=Ot;const u=a[c++];E.mmr=!!(1&u);E.template=u>>1&3;E.enableSkip=!!(8&u);E.combinationOperator=u>>4&7;E.defaultPixelValue=u>>7&1;E.gridWidth=readUint32(a,c);c+=4;E.gridHeight=readUint32(a,c);c+=4;E.gridOffsetX=4294967295&readUint32(a,c);c+=4;E.gridOffsetY=4294967295&readUint32(a,c);c+=4;E.gridVectorX=readUint16(a,c);c+=2;E.gridVectorY=readUint16(a,c);c+=2;r=[E,i.referredTo,a,c,s];break;case 38:case 39:const d={};d.info=readRegionSegmentInformation(a,c);c+=Ot;const f=a[c++];d.mmr=!!(1&f);d.template=f>>1&3;d.prediction=!!(8&f);if(!d.mmr){o=0===d.template?4:1;n=[];for(g=0;g>2&1;p.combinationOperator=m>>3&3;p.requiresBuffer=!!(32&m);p.combinationOperatorOverride=!!(64&m);r=[p];break;case 49:case 50:case 51:case 62:break;case 53:r=[i.number,a,c,s];break;default:throw new Jbig2Error(`segment type ${i.typeName}(${i.type}) is not implemented`)}const C="on"+i.typeName;C in t&&t[C].apply(t,r)}function processSegments(e,t){for(let i=0,a=e.length;i>3,i=new Uint8ClampedArray(t*e.height);e.defaultPixelValue&&i.fill(255);this.buffer=i}drawBitmap(e,t){const i=this.currentPageInfo,a=e.width,s=e.height,r=i.width+7>>3,n=i.combinationOperatorOverride?e.combinationOperator:i.combinationOperator,g=this.buffer,o=128>>(7&e.x);let c,C,h,l,Q=e.y*r+(e.x>>3);switch(n){case 0:for(c=0;c>=1;if(!h){h=128;l++}}Q+=r}break;case 2:for(c=0;c>=1;if(!h){h=128;l++}}Q+=r}break;default:throw new Jbig2Error(`operator ${n} is not supported`)}}onImmediateGenericRegion(e,t,i,a){const s=e.info,r=new DecodingContext(t,i,a),n=decodeBitmap(e.mmr,s.width,s.height,e.template,e.prediction,null,e.at,r);this.drawBitmap(s,n)}onImmediateLosslessGenericRegion(){this.onImmediateGenericRegion(...arguments)}onSymbolDictionary(e,t,i,a,s,r){let n,g;if(e.huffman){n=function getSymbolDictionaryHuffmanTables(e,t,i){let a,s,r,n,g=0;switch(e.huffmanDHSelector){case 0:case 1:a=getStandardTable(e.huffmanDHSelector+4);break;case 3:a=getCustomHuffmanTable(g,t,i);g++;break;default:throw new Jbig2Error("invalid Huffman DH selector")}switch(e.huffmanDWSelector){case 0:case 1:s=getStandardTable(e.huffmanDWSelector+2);break;case 3:s=getCustomHuffmanTable(g,t,i);g++;break;default:throw new Jbig2Error("invalid Huffman DW selector")}if(e.bitmapSizeSelector){r=getCustomHuffmanTable(g,t,i);g++}else r=getStandardTable(1);n=e.aggregationInstancesSelector?getCustomHuffmanTable(g,t,i):getStandardTable(1);return{tableDeltaHeight:a,tableDeltaWidth:s,tableBitmapSize:r,tableAggregateInstances:n}}(e,i,this.customTables);g=new Reader(a,s,r)}let o=this.symbols;o||(this.symbols=o={});const c=[];for(const e of i){const t=o[e];t&&c.push(...t)}const C=new DecodingContext(a,s,r);o[t]=function decodeSymbolDictionary(e,t,i,a,s,r,n,g,o,c,C,h){if(e&&t)throw new Jbig2Error("symbol refinement with Huffman is not supported");const l=[];let Q=0,E=log2(i.length+a);const u=C.decoder,d=C.contextCache;let f,p;if(e){f=getStandardTable(1);p=[];E=Math.max(E,1)}for(;l.length1)m=decodeTextRegion(e,t,a,Q,0,s,1,i.concat(l),E,0,0,1,0,r,o,c,C,0,h);else{const e=decodeIAID(d,u,E),t=decodeInteger(d,"IARDX",u),s=decodeInteger(d,"IARDY",u);m=decodeRefinement(a,Q,o,e=32){let i,a,n;switch(t){case 32:if(0===e)throw new Jbig2Error("no previous value in symbol ID table");a=s.readBits(2)+3;i=r[e-1].prefixLength;break;case 33:a=s.readBits(3)+3;i=0;break;case 34:a=s.readBits(7)+11;i=0;break;default:throw new Jbig2Error("invalid code length in symbol ID table")}for(n=0;n=0;d--){R=e?decodeMMRBitmap(k,o,c,!0):decodeBitmap(!1,o,c,i,!1,null,F,E);S[d]=R}for(N=0;N=0;f--){M^=S[f][N][G];U|=M<>8;H=h+N*l-G*Q>>8;if(L>=0&&L+w<=a&&H>=0&&H+D<=s)for(d=0;d=s)){Y=u[t];J=x[d];for(f=0;f=0&&e>1&7),o=1+(a>>4&7),c=[];let C,h,l=s;do{C=n.readBits(g);h=n.readBits(o);c.push(new HuffmanLine([l,C,h,0]));l+=1<>t&1;if(t<=0)this.children[i]=new HuffmanTreeNode(e);else{let a=this.children[i];a||(this.children[i]=a=new HuffmanTreeNode(null));a.buildTree(e,t-1)}}decodeNode(e){if(this.isLeaf){if(this.isOOB)return null;const t=e.readBits(this.rangeLength);return this.rangeLow+(this.isLowerRange?-t:t)}const t=this.children[e.readBit()];if(!t)throw new Jbig2Error("invalid Huffman data");return t.decodeNode(e)}}class HuffmanTable{constructor(e,t){t||this.assignPrefixCodes(e);this.rootNode=new HuffmanTreeNode(null);for(let t=0,i=e.length;t0&&this.rootNode.buildTree(i,i.prefixLength-1)}}decode(e){return this.rootNode.decodeNode(e)}assignPrefixCodes(e){const t=e.length;let i=0;for(let a=0;a=this.end)throw new Jbig2Error("end of data while reading bit");this.currentByte=this.data[this.position++];this.shift=7}const e=this.currentByte>>this.shift&1;this.shift--;return e}readBits(e){let t,i=0;for(t=e-1;t>=0;t--)i|=this.readBit()<=this.end?-1:this.data[this.position++]}}function getCustomHuffmanTable(e,t,i){let a=0;for(let s=0,r=t.length;s>i&1;i--}}if(a&&!g){const e=5;for(let t=0;t>2,c=new Uint32Array(e.buffer,t,o);if(FeatureTest.isLittleEndian){for(;n>>24|t<<8|4278190080;i[a+2]=t>>>16|s<<16|4278190080;i[a+3]=s>>>8|4278190080}for(let s=4*n,r=t+g;s>>8|255;i[a+2]=t<<16|s>>>16|255;i[a+3]=s<<8|255}for(let s=4*n,r=t+g;s>3,h=7&a,l=e.length;i=new Uint32Array(i.buffer);let Q=0;for(let a=0;a0&&!e[r-1];)r--;const n=[{children:[],index:0}];let g,o=n[0];for(i=0;i0;)o=n.pop();o.index++;n.push(o);for(;n.length<=i;){n.push(g={children:[],index:0});o.children[o.index]=g.children;o=g}s++}if(i+10){E--;return Q>>E&1}Q=e[t++];if(255===Q){const a=e[t++];if(a){if(220===a&&c){const a=readUint16(e,t+=2);t+=2;if(a>0&&a!==i.scanLines)throw new DNLMarkerError("Found DNL marker (0xFFDC) while parsing scan data",a)}else if(217===a){if(c){const e=p*(8===i.precision?8:0);if(e>0&&Math.round(i.scanLines/e)>=5)throw new DNLMarkerError("Found EOI marker (0xFFD9) while parsing scan data, possibly caused by incorrect `scanLines` parameter",e)}throw new EOIMarkerError("Found EOI marker (0xFFD9) while parsing scan data")}throw new JpegError(`unexpected marker ${(Q<<8|a).toString(16)}`)}}E=7;return Q>>>7}function decodeHuffman(e){let t=e;for(;;){t=t[readBit()];switch(typeof t){case"number":return t;case"object":continue}throw new JpegError("invalid huffman sequence")}}function receive(e){let t=0;for(;e>0;){t=t<<1|readBit();e--}return t}function receiveAndExtend(e){if(1===e)return 1===readBit()?1:-1;const t=receive(e);return t>=1<0){u--;return}let i=r;const a=n;for(;i<=a;){const a=decodeHuffman(e.huffmanTableAC),s=15&a,r=a>>4;if(0===s){if(r<15){u=receive(r)+(1<>4;if(0===s)if(c<15){u=receive(c)+(1<>4;if(0===a){if(r<15)break;s+=16;continue}s+=r;const n=Wt[s];e.blockData[t+n]=receiveAndExtend(a);s++}};let k,R=0;const N=1===m?a[0].blocksPerLine*a[0].blocksPerColumn:C*i.mcusPerColumn;let G,M;for(;R<=N;){const i=s?Math.min(N-R,s):N;if(i>0){for(w=0;w0?"unexpected":"excessive"} MCU data, current marker is: ${k.invalid}`);t=k.offset}if(!(k.marker>=65488&&k.marker<=65495))break;t+=2}return t-l}function quantizeAndInverse(e,t,i){const a=e.quantizationTable,s=e.blockData;let r,n,g,o,c,C,h,l,Q,E,u,d,f,p,m,y,w;if(!a)throw new JpegError("missing required Quantization Table.");for(let e=0;e<64;e+=8){Q=s[t+e];E=s[t+e+1];u=s[t+e+2];d=s[t+e+3];f=s[t+e+4];p=s[t+e+5];m=s[t+e+6];y=s[t+e+7];Q*=a[e];if(E|u|d|f|p|m|y){E*=a[e+1];u*=a[e+2];d*=a[e+3];f*=a[e+4];p*=a[e+5];m*=a[e+6];y*=a[e+7];r=$t*Q+128>>8;n=$t*f+128>>8;g=u;o=m;c=Ai*(E-y)+128>>8;l=Ai*(E+y)+128>>8;C=d<<4;h=p<<4;r=r+n+1>>1;n=r-n;w=g*_t+o*zt+128>>8;g=g*zt-o*_t+128>>8;o=w;c=c+h+1>>1;h=c-h;l=l+C+1>>1;C=l-C;r=r+o+1>>1;o=r-o;n=n+g+1>>1;g=n-g;w=c*Vt+l*Zt+2048>>12;c=c*Zt-l*Vt+2048>>12;l=w;w=C*Xt+h*jt+2048>>12;C=C*jt-h*Xt+2048>>12;h=w;i[e]=r+l;i[e+7]=r-l;i[e+1]=n+h;i[e+6]=n-h;i[e+2]=g+C;i[e+5]=g-C;i[e+3]=o+c;i[e+4]=o-c}else{w=$t*Q+512>>10;i[e]=w;i[e+1]=w;i[e+2]=w;i[e+3]=w;i[e+4]=w;i[e+5]=w;i[e+6]=w;i[e+7]=w}}for(let e=0;e<8;++e){Q=i[e];E=i[e+8];u=i[e+16];d=i[e+24];f=i[e+32];p=i[e+40];m=i[e+48];y=i[e+56];if(E|u|d|f|p|m|y){r=$t*Q+2048>>12;n=$t*f+2048>>12;g=u;o=m;c=Ai*(E-y)+2048>>12;l=Ai*(E+y)+2048>>12;C=d;h=p;r=4112+(r+n+1>>1);n=r-n;w=g*_t+o*zt+2048>>12;g=g*zt-o*_t+2048>>12;o=w;c=c+h+1>>1;h=c-h;l=l+C+1>>1;C=l-C;r=r+o+1>>1;o=r-o;n=n+g+1>>1;g=n-g;w=c*Vt+l*Zt+2048>>12;c=c*Zt-l*Vt+2048>>12;l=w;w=C*Xt+h*jt+2048>>12;C=C*jt-h*Xt+2048>>12;h=w;Q=r+l;y=r-l;E=n+h;m=n-h;u=g+C;p=g-C;d=o+c;f=o-c;Q<16?Q=0:Q>=4080?Q=255:Q>>=4;E<16?E=0:E>=4080?E=255:E>>=4;u<16?u=0:u>=4080?u=255:u>>=4;d<16?d=0:d>=4080?d=255:d>>=4;f<16?f=0:f>=4080?f=255:f>>=4;p<16?p=0:p>=4080?p=255:p>>=4;m<16?m=0:m>=4080?m=255:m>>=4;y<16?y=0:y>=4080?y=255:y>>=4;s[t+e]=Q;s[t+e+8]=E;s[t+e+16]=u;s[t+e+24]=d;s[t+e+32]=f;s[t+e+40]=p;s[t+e+48]=m;s[t+e+56]=y}else{w=$t*Q+8192>>14;w=w<-2040?0:w>=2024?255:w+2056>>4;s[t+e]=w;s[t+e+8]=w;s[t+e+16]=w;s[t+e+24]=w;s[t+e+32]=w;s[t+e+40]=w;s[t+e+48]=w;s[t+e+56]=w}}}function buildComponentData(e,t){const i=t.blocksPerLine,a=t.blocksPerColumn,s=new Int16Array(64);for(let e=0;e=a)return null;const r=readUint16(e,t);if(r>=65472&&r<=65534)return{invalid:null,marker:r,offset:t};let n=readUint16(e,s);for(;!(n>=65472&&n<=65534);){if(++s>=a)return null;n=readUint16(e,s)}return{invalid:r.toString(16),marker:n,offset:s}}function prepareComponents(e){const t=Math.ceil(e.samplesPerLine/8/e.maxH),i=Math.ceil(e.scanLines/8/e.maxV);for(const a of e.components){const s=Math.ceil(Math.ceil(e.samplesPerLine/8)*a.h/e.maxH),r=Math.ceil(Math.ceil(e.scanLines/8)*a.v/e.maxV),n=t*a.h,g=64*(i*a.v)*(n+1);a.blockData=new Int16Array(g);a.blocksPerLine=s;a.blocksPerColumn=r}e.mcusPerLine=t;e.mcusPerColumn=i}function readDataBlock(e,t){const i=readUint16(e,t);let a=(t+=2)+i-2;const s=findNextFileMarker(e,a,t);if(s?.invalid){warn("readDataBlock - incorrect length, current marker is: "+s.invalid);a=s.offset}const r=e.subarray(t,a);return{appData:r,newOffset:t+=r.length}}function skipData(e,t){const i=readUint16(e,t),a=(t+=2)+i-2,s=findNextFileMarker(e,a,t);return s?.invalid?s.offset:a}class JpegImage{constructor({decodeTransform:e=null,colorTransform:t=-1}={}){this._decodeTransform=e;this._colorTransform=t}static canUseImageDecoder(e,t=-1){let i=0,a=null,s=readUint16(e,i);i+=2;if(65496!==s)throw new JpegError("SOI not found");s=readUint16(e,i);i+=2;A:for(;65497!==s;){switch(s){case 65472:case 65473:case 65474:a=e[i+7];break A;case 65535:255!==e[i]&&i--}i=skipData(e,i);s=readUint16(e,i);i+=2}return 4!==a&&(3!==a||0!==t)}parse(e,{dnlScanLines:t=null}={}){let i,a,s=0,r=null,n=null,g=0;const o=[],c=[],C=[];let h=readUint16(e,s);s+=2;if(65496!==h)throw new JpegError("SOI not found");h=readUint16(e,s);s+=2;A:for(;65497!==h;){let l,Q,E;switch(h){case 65504:case 65505:case 65506:case 65507:case 65508:case 65509:case 65510:case 65511:case 65512:case 65513:case 65514:case 65515:case 65516:case 65517:case 65518:case 65519:case 65534:const{appData:u,newOffset:d}=readDataBlock(e,s);s=d;65504===h&&74===u[0]&&70===u[1]&&73===u[2]&&70===u[3]&&0===u[4]&&(r={version:{major:u[5],minor:u[6]},densityUnits:u[7],xDensity:u[8]<<8|u[9],yDensity:u[10]<<8|u[11],thumbWidth:u[12],thumbHeight:u[13],thumbData:u.subarray(14,14+3*u[12]*u[13])});65518===h&&65===u[0]&&100===u[1]&&111===u[2]&&98===u[3]&&101===u[4]&&(n={version:u[5]<<8|u[6],flags0:u[7]<<8|u[8],flags1:u[9]<<8|u[10],transformCode:u[11]});break;case 65499:const f=readUint16(e,s);s+=2;const p=f+s-2;let m;for(;s>4){if(t>>4!=1)throw new JpegError("DQT - invalid table spec");for(Q=0;Q<64;Q++){m=Wt[Q];i[m]=readUint16(e,s);s+=2}}else for(Q=0;Q<64;Q++){m=Wt[Q];i[m]=e[s++]}o[15&t]=i}break;case 65472:case 65473:case 65474:if(i)throw new JpegError("Only single frame JPEGs supported");s+=2;i={};i.extended=65473===h;i.progressive=65474===h;i.precision=e[s++];const y=readUint16(e,s);s+=2;i.scanLines=t||y;i.samplesPerLine=readUint16(e,s);s+=2;i.components=[];i.componentIds={};const w=e[s++];let D=0,b=0;for(l=0;l>4,r=15&e[s+1];D>4?c:C)[15&t]=buildHuffmanTable(i,r)}break;case 65501:s+=2;a=readUint16(e,s);s+=2;break;case 65498:const S=1==++g&&!t;s+=2;const k=e[s++],R=[];for(l=0;l>4];r.huffmanTableAC=c[15&n];R.push(r)}const N=e[s++],G=e[s++],M=e[s++];try{s+=decodeScan(e,s,i,R,a,N,G,M>>4,15&M,S)}catch(t){if(t instanceof DNLMarkerError){warn(`${t.message} -- attempting to re-parse the JPEG image.`);return this.parse(e,{dnlScanLines:t.scanLines})}if(t instanceof EOIMarkerError){warn(`${t.message} -- ignoring the rest of the image data.`);break A}throw t}break;case 65500:s+=4;break;case 65535:255!==e[s]&&s--;break;default:const U=findNextFileMarker(e,s-2,s-3);if(U?.invalid){warn("JpegImage.parse - unexpected data, current marker is: "+U.invalid);s=U.offset;break}if(!U||s>=e.length-1){warn("JpegImage.parse - reached the end of the image data without finding an EOI marker (0xFFD9).");break A}throw new JpegError("JpegImage.parse - unknown marker: "+h.toString(16))}h=readUint16(e,s);s+=2}if(!i)throw new JpegError("JpegImage.parse - no frame data found.");this.width=i.samplesPerLine;this.height=i.scanLines;this.jfif=r;this.adobe=n;this.components=[];for(const e of i.components){const t=o[e.quantizationId];t&&(e.quantizationTable=t);this.components.push({index:e.index,output:buildComponentData(0,e),scaleX:e.h/i.maxH,scaleY:e.v/i.maxV,blocksPerLine:e.blocksPerLine,blocksPerColumn:e.blocksPerColumn})}this.numComponents=this.components.length}_getLinearizedBlockData(e,t,i=!1){const a=this.width/e,s=this.height/t;let r,n,g,o,c,C,h,l,Q,E,u,d=0;const f=this.components.length,p=e*t*f,m=new Uint8ClampedArray(p),y=new Uint32Array(e),w=4294967288;let D;for(h=0;h>8)+b[Q+1];return m}get _isColorConversionNeeded(){return this.adobe?!!this.adobe.transformCode:3===this.numComponents?0!==this._colorTransform&&(82!==this.components[0].index||71!==this.components[1].index||66!==this.components[2].index):1===this._colorTransform}_convertYccToRgb(e){let t,i,a;for(let s=0,r=e.length;s4)throw new JpegError("Unsupported color mode");const r=this._getLinearizedBlockData(e,t,s);if(1===this.numComponents&&(i||a)){const e=r.length*(i?4:3),t=new Uint8ClampedArray(e);let a=0;if(i)!function grayToRGBA(e,t){if(FeatureTest.isLittleEndian)for(let i=0,a=e.length;i0&&(e=e.subarray(t));break}return e}decodeImage(e){if(this.eof)return this.buffer;e=this.#w(e||this.bytes);const t=new JpegImage(this.jpegOptions);t.parse(e);const i=t.getData({width:this.drawWidth,height:this.drawHeight,forceRGBA:this.forceRGBA,forceRGB:this.forceRGB,isSourcePDF:!0});this.buffer=i;this.bufferLength=i.length;this.eof=!0;return this.buffer}get canAsyncDecodeImageFromBuffer(){return this.stream.isAsync}async getTransferableImage(){if(!await JpegStream.canUseImageDecoder)return null;const e=this.jpegOptions;if(e.decodeTransform)return null;let t;try{const i=this.canAsyncDecodeImageFromBuffer&&await this.stream.asyncGetBytes()||this.bytes;if(!i)return null;const a=this.#w(i);if(!JpegImage.canUseImageDecoder(a,e.colorTransform))return null;t=new ImageDecoder({data:a,type:"image/jpeg",preferAnimation:!1});return(await t.decode()).image}catch(e){warn(`getTransferableImage - failed: "${e}".`);return null}finally{t?.close()}}}var ei,ti=(ei="undefined"!=typeof document?document.currentScript?.src:void 0,function(e={}){var t,i,a=e;new Promise(((e,a)=>{t=e;i=a}));a.decode=function(e,{numComponents:t=4,isIndexedColormap:i=!1,smaskInData:s=!1}){const r=e.length,n=a._malloc(r);a.HEAPU8.set(e,n);const g=a._jp2_decode(n,r,t>0?t:0,!!i,!!s);a._free(n);if(g){const{errorMessages:e}=a;if(e){delete a.errorMessages;return e}return"Unknown error"}const{imageData:o}=a;a.imageData=null;return o};var s=Object.assign({},a),r="./this.program",quit_=(e,t)=>{throw t},n="";"undefined"!=typeof document&&document.currentScript&&(n=document.currentScript.src);ei&&(n=ei);n=n.startsWith("blob:")?"":n.substr(0,n.replace(/[?#].*/,"").lastIndexOf("/")+1);var g=a.print||console.log.bind(console),o=a.printErr||console.error.bind(console);Object.assign(a,s);s=null;a.arguments&&a.arguments;a.thisProgram&&(r=a.thisProgram);var c,C=a.wasmBinary;function tryParseAsDataURI(e){if(isDataURI(e))return function intArrayFromBase64(e){for(var t=atob(e),i=new Uint8Array(t.length),a=0;ae.startsWith(b);function instantiateSync(e,t){var i,a=function getBinarySync(e){if(e==d&&C)return new Uint8Array(C);var t=tryParseAsDataURI(e);if(t)return t;throw'sync fetching of the wasm failed: you can preload it to Module["wasmBinary"] manually, or emcc.py will do that for you when generating HTML (but not JS)'}(e);i=new WebAssembly.Module(a);return[new WebAssembly.Instance(i,t),i]}class ExitStatus{name="ExitStatus";constructor(e){this.message=`Program terminated with exit(${e})`;this.status=e}}var F,callRuntimeCallbacks=e=>{for(;e.length>0;)e.shift()(a)},S=a.noExitRuntime||!0,k=0,R={},handleException=e=>{if(e instanceof ExitStatus||"unwind"==e)return h;quit_(0,e)},keepRuntimeAlive=()=>S||k>0,_proc_exit=e=>{h=e;if(!keepRuntimeAlive()){a.onExit?.(e);u=!0}quit_(0,new ExitStatus(e))},_exit=(e,t)=>{h=e;_proc_exit(e)},callUserCallback=e=>{if(!u)try{e();(()=>{if(!keepRuntimeAlive())try{_exit(h)}catch(e){handleException(e)}})()}catch(e){handleException(e)}},growMemory=e=>{var t=(e-c.buffer.byteLength+65535)/65536|0;try{c.grow(t);updateMemoryViews();return 1}catch(e){}},N={},getEnvStrings=()=>{if(!getEnvStrings.strings){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:r||"./this.program"};for(var t in N)void 0===N[t]?delete e[t]:e[t]=N[t];var i=[];for(var t in e)i.push(`${t}=${e[t]}`);getEnvStrings.strings=i}return getEnvStrings.strings},G=[null,[],[]],M="undefined"!=typeof TextDecoder?new TextDecoder:void 0,UTF8ArrayToString=(e,t=0,i=NaN)=>{for(var a=t+i,s=t;e[s]&&!(s>=a);)++s;if(s-t>16&&e.buffer&&M)return M.decode(e.subarray(t,s));for(var r="";t>10,56320|1023&c)}}else r+=String.fromCharCode((31&n)<<6|g)}else r+=String.fromCharCode(n)}return r},printChar=(e,t)=>{var i=G[e];if(0===t||10===t){(1===e?g:o)(UTF8ArrayToString(i));i.length=0}else i.push(t)},UTF8ToString=(e,t)=>e?UTF8ArrayToString(Q,e,t):"",U={m:()=>function abort(e){a.onAbort?.(e);o(e="Aborted("+e+")");u=!0;e+=". Build with -sASSERTIONS for more info.";var t=new WebAssembly.RuntimeError(e);i(t);throw t}(""),c:(e,t,i)=>Q.copyWithin(e,t,t+i),l:()=>{S=!1;k=0},n:(e,t)=>{if(R[e]){clearTimeout(R[e].id);delete R[e]}if(!t)return 0;var i=setTimeout((()=>{delete R[e];callUserCallback((()=>L(e,performance.now())))}),t);R[e]={id:i,timeout_ms:t};return 0},g:function _copy_pixels_1(e,t){e>>=2;const i=a.imageData=new Uint8ClampedArray(t),s=a.HEAP32.subarray(e,e+t);i.set(s)},f:function _copy_pixels_3(e,t,i,s){e>>=2;t>>=2;i>>=2;const r=a.imageData=new Uint8ClampedArray(3*s),n=a.HEAP32.subarray(e,e+s),g=a.HEAP32.subarray(t,t+s),o=a.HEAP32.subarray(i,i+s);for(let e=0;e>=2;t>>=2;i>>=2;s>>=2;const n=a.imageData=new Uint8ClampedArray(4*r),g=a.HEAP32.subarray(e,e+r),o=a.HEAP32.subarray(t,t+r),c=a.HEAP32.subarray(i,i+r),C=a.HEAP32.subarray(s,s+r);for(let e=0;e{var t,i,a=Q.length,s=2147483648;if((e>>>=0)>s)return!1;for(var r=1;r<=4;r*=2){var n=a*(1+.2/r);n=Math.min(n,e+100663296);var g=Math.min(s,(t=Math.max(e,n),i=65536,Math.ceil(t/i)*i));if(growMemory(g))return!0}return!1},p:(e,t)=>{var i=0;getEnvStrings().forEach(((a,s)=>{var r=t+i;E[e+4*s>>2]=r;((e,t)=>{for(var i=0;i{var i=getEnvStrings();E[e>>2]=i.length;var a=0;i.forEach((e=>a+=e.length+1));E[t>>2]=a;return 0},r:e=>52,j:function _fd_seek(e,t,i,a,s){return 70},b:(e,t,i,a)=>{for(var s=0,r=0;r>2],g=E[t+4>>2];t+=8;for(var o=0;o>2]=s;return 0},s:function _gray_to_rgba(e,t){e>>=2;const i=a.imageData=new Uint8ClampedArray(4*t),s=a.HEAP32.subarray(e,e+t);for(let e=0;e>=2;t>>=2;const s=a.imageData=new Uint8ClampedArray(4*i),r=a.HEAP32.subarray(e,e+i),n=a.HEAP32.subarray(t,t+i);for(let e=0;e>=2;t>>=2;i>>=2;const r=a.imageData=new Uint8ClampedArray(4*s),n=a.HEAP32.subarray(e,e+s),g=a.HEAP32.subarray(t,t+s),o=a.HEAP32.subarray(i,i+s);for(let e=0;e0)){!function preRun(){if(a.preRun){"function"==typeof a.preRun&&(a.preRun=[a.preRun]);for(;a.preRun.length;)e=a.preRun.shift(),f.unshift(e)}var e;callRuntimeCallbacks(f)}();if(!(y>0))if(a.setStatus){a.setStatus("Running...");setTimeout((()=>{setTimeout((()=>a.setStatus("")),1);doRun()}),1)}else doRun()}function doRun(){if(!F){F=!0;a.calledRun=!0;if(!u){!function initRuntime(){callRuntimeCallbacks(p)}();t(a);a.onRuntimeInitialized?.();!function postRun(){if(a.postRun){"function"==typeof a.postRun&&(a.postRun=[a.postRun]);for(;a.postRun.length;)e=a.postRun.shift(),m.unshift(e)}var e;callRuntimeCallbacks(m)}()}}}}if(a.preInit){"function"==typeof a.preInit&&(a.preInit=[a.preInit]);for(;a.preInit.length>0;)a.preInit.pop()()}run();return a});const ii=ti;class JpxError extends ot{constructor(e){super(e,"JpxError")}}class JpxImage{static#D=null;static decode(e,t){t||={};this.#D||=ii({warn});const i=this.#D.decode(e,t);if("string"==typeof i)throw new JpxError(i);return i}static cleanup(){this.#D=null}static parseImageProperties(e){let t=e.getByte();for(;t>=0;){const i=t;t=e.getByte();if(65361===(i<<8|t)){e.skip(4);const t=e.getInt32()>>>0,i=e.getInt32()>>>0,a=e.getInt32()>>>0,s=e.getInt32()>>>0;e.skip(16);return{width:t-a,height:i-s,bitsPerComponent:8,componentsCount:e.getUint16()}}}throw new JpxError("No size marker found in JPX stream")}}class JpxStream extends DecodeStream{constructor(e,t,i){super(t);this.stream=e;this.dict=e.dict;this.maybeLength=t;this.params=i}get bytes(){return shadow(this,"bytes",this.stream.getBytes(this.maybeLength))}ensureBuffer(e){}readBlock(e){this.decodeImage(null,e)}decodeImage(e,t){if(this.eof)return this.buffer;e||=this.bytes;this.buffer=JpxImage.decode(e,t);this.bufferLength=this.buffer.length;this.eof=!0;return this.buffer}get canAsyncDecodeImageFromBuffer(){return this.stream.isAsync}}class LZWStream extends DecodeStream{constructor(e,t,i){super(t);this.str=e;this.dict=e.dict;this.cachedData=0;this.bitsCached=0;const a=4096,s={earlyChange:i,codeLength:9,nextCode:258,dictionaryValues:new Uint8Array(a),dictionaryLengths:new Uint16Array(a),dictionaryPrevCodes:new Uint16Array(a),currentSequence:new Uint8Array(a),currentSequenceLength:0};for(let e=0;e<256;++e){s.dictionaryValues[e]=e;s.dictionaryLengths[e]=1}this.lzwState=s}readBits(e){let t=this.bitsCached,i=this.cachedData;for(;t>>t&(1<0;if(e<256){l[0]=e;Q=1}else{if(!(e>=258)){if(256===e){C=9;n=258;Q=0;continue}this.eof=!0;delete this.lzwState;break}if(e=0;t--){l[t]=g[i];i=c[i]}}else l[Q++]=l[0]}if(s){c[n]=h;o[n]=o[h]+1;g[n]=l[0];n++;C=n+r&n+r-1?C:0|Math.min(Math.log(n+r)/.6931471805599453+1,12)}h=e;E+=Q;if(a15))throw new FormatError(`Unsupported predictor: ${a}`);this.readBlock=2===a?this.readBlockTiff:this.readBlockPng;this.str=e;this.dict=e.dict;const s=this.colors=i.get("Colors")||1,r=this.bits=i.get("BPC","BitsPerComponent")||8,n=this.columns=i.get("Columns")||1;this.pixBytes=s*r+7>>3;this.rowBytes=n*s*r+7>>3;return this}readBlockTiff(){const e=this.rowBytes,t=this.bufferLength,i=this.ensureBuffer(t+e),a=this.bits,s=this.colors,r=this.str.getBytes(e);this.eof=!r.length;if(this.eof)return;let n,g=0,o=0,c=0,C=0,h=t;if(1===a&&1===s)for(n=0;n>1;e^=e>>2;e^=e>>4;g=(1&e)<<7;i[h++]=e}else if(8===a){for(n=0;n>8&255;i[h++]=255&e}}else{const e=new Uint8Array(s+1),h=(1<>c-a)&h;c-=a;o=o<=8){i[Q++]=o>>C-8&255;C-=8}}C>0&&(i[Q++]=(o<<8-C)+(g&(1<<8-C)-1))}this.bufferLength+=e}readBlockPng(){const e=this.rowBytes,t=this.pixBytes,i=this.str.getByte(),a=this.str.getBytes(e);this.eof=!a.length;if(this.eof)return;const s=this.bufferLength,r=this.ensureBuffer(s+e);let n=r.subarray(s-e,s);0===n.length&&(n=new Uint8Array(e));let g,o,c,C=s;switch(i){case 0:for(g=0;g>1)+a[g];for(;g>1)+a[g]&255;C++}break;case 4:for(g=0;g0){const e=this.str.getBytes(a);t.set(e,i);i+=a}}else{a=257-a;const s=e[1];t=this.ensureBuffer(i+a+1);for(let e=0;e>")&&this.buf1!==Bt;){if(!(this.buf1 instanceof Name)){info("Malformed dictionary: key must be a name object");this.shift();continue}const t=this.buf1.name;this.shift();if(this.buf1===Bt)break;a.set(t,this.getObj(e))}if(this.buf1===Bt){if(this.recoveryMode)return a;throw new ParserEOFException("End of file inside dictionary.")}if(isCmd(this.buf2,"stream"))return this.allowStreams?this.makeStream(a,e):a;this.shift();return a;default:return t}if(Number.isInteger(t)){if(Number.isInteger(this.buf1)&&isCmd(this.buf2,"R")){const e=Ref.get(t,this.buf1);this.shift();this.shift();return e}return t}return"string"==typeof t&&e?e.decryptString(t):t}findDefaultInlineStreamEnd(e){const{knownCommands:t}=this.lexer,i=e.pos;let a,s,r=0;for(;-1!==(a=e.getByte());)if(0===r)r=69===a?1:0;else if(1===r)r=73===a?2:0;else if(32===a||10===a||13===a){s=e.pos;const i=e.peekBytes(15),n=i.length;if(0===n)break;for(let e=0;e127))){r=0;break}}if(2!==r)continue;if(!t){warn("findDefaultInlineStreamEnd - `lexer.knownCommands` is undefined.");continue}const g=new Lexer(new Stream(i.slice()),t);g._hexStringWarn=()=>{};let o=0;for(;;){const e=g.getObj();if(e===Bt){r=0;break}if(e instanceof Cmd){const i=t[e.cmd];if(!i){r=0;break}if(i.variableArgs?o<=i.numArgs:o===i.numArgs)break;o=0}else o++}if(2===r)break}else r=0;if(-1===a){warn("findDefaultInlineStreamEnd: Reached the end of the stream without finding a valid EI marker");if(s){warn('... trying to recover by using the last "EI" occurrence.');e.skip(-(e.pos-s))}}let n=4;e.skip(-n);a=e.peekByte();e.skip(n);isWhiteSpace(a)||n--;return e.pos-n-i}findDCTDecodeInlineStreamEnd(e){const t=e.pos;let i,a,s=!1;for(;-1!==(i=e.getByte());)if(255===i){switch(e.getByte()){case 0:break;case 255:e.skip(-1);break;case 217:s=!0;break;case 192:case 193:case 194:case 195:case 197:case 198:case 199:case 201:case 202:case 203:case 205:case 206:case 207:case 196:case 204:case 218:case 219:case 220:case 221:case 222:case 223:case 224:case 225:case 226:case 227:case 228:case 229:case 230:case 231:case 232:case 233:case 234:case 235:case 236:case 237:case 238:case 239:case 254:a=e.getUint16();a>2?e.skip(a-2):e.skip(-2)}if(s)break}const r=e.pos-t;if(-1===i){warn("Inline DCTDecode image stream: EOI marker not found, searching for /EI/ instead.");e.skip(-r);return this.findDefaultInlineStreamEnd(e)}this.inlineStreamSkipEI(e);return r}findASCII85DecodeInlineStreamEnd(e){const t=e.pos;let i;for(;-1!==(i=e.getByte());)if(126===i){const t=e.pos;i=e.peekByte();for(;isWhiteSpace(i);){e.skip();i=e.peekByte()}if(62===i){e.skip();break}if(e.pos>t){const t=e.peekBytes(2);if(69===t[0]&&73===t[1])break}}const a=e.pos-t;if(-1===i){warn("Inline ASCII85Decode image stream: EOD marker not found, searching for /EI/ instead.");e.skip(-a);return this.findDefaultInlineStreamEnd(e)}this.inlineStreamSkipEI(e);return a}findASCIIHexDecodeInlineStreamEnd(e){const t=e.pos;let i;for(;-1!==(i=e.getByte())&&62!==i;);const a=e.pos-t;if(-1===i){warn("Inline ASCIIHexDecode image stream: EOD marker not found, searching for /EI/ instead.");e.skip(-a);return this.findDefaultInlineStreamEnd(e)}this.inlineStreamSkipEI(e);return a}inlineStreamSkipEI(e){let t,i=0;for(;-1!==(t=e.getByte());)if(0===i)i=69===t?1:0;else if(1===i)i=73===t?2:0;else if(2===i)break}makeInlineImage(e){const t=this.lexer,i=t.stream,a=Object.create(null);let s;for(;!isCmd(this.buf1,"ID")&&this.buf1!==Bt;){if(!(this.buf1 instanceof Name))throw new FormatError("Dictionary key must be a name object");const t=this.buf1.name;this.shift();if(this.buf1===Bt)break;a[t]=this.getObj(e)}-1!==t.beginInlineImagePos&&(s=i.pos-t.beginInlineImagePos);const r=this.xref.fetchIfRef(a.F||a.Filter);let n;if(r instanceof Name)n=r.name;else if(Array.isArray(r)){const e=this.xref.fetchIfRef(r[0]);e instanceof Name&&(n=e.name)}const g=i.pos;let o,c;switch(n){case"DCT":case"DCTDecode":o=this.findDCTDecodeInlineStreamEnd(i);break;case"A85":case"ASCII85Decode":o=this.findASCII85DecodeInlineStreamEnd(i);break;case"AHx":case"ASCIIHexDecode":o=this.findASCIIHexDecodeInlineStreamEnd(i);break;default:o=this.findDefaultInlineStreamEnd(i)}if(o<1e3&&s>0){const e=i.pos;i.pos=t.beginInlineImagePos;c=function getInlineImageCacheKey(e){const t=[],i=e.length;let a=0;for(;a=a){let a=!1;for(const e of s){const t=e.length;let s=0;for(;s=r){a=!0;break}if(s>=t){if(isWhiteSpace(n[o+g+s])){info(`Found "${bytesToString([...i,...e])}" when searching for endstream command.`);a=!0}break}}if(a){t.pos+=o;return t.pos-e}}o++}t.pos+=g}return-1}makeStream(e,t){const i=this.lexer;let a=i.stream;i.skipToNextLine();const s=a.pos-1;let r=e.get("Length");if(!Number.isInteger(r)){info(`Bad length "${r&&r.toString()}" in stream.`);r=0}a.pos=s+r;i.nextChar();if(this.tryShift()&&isCmd(this.buf2,"endstream"))this.shift();else{r=this.#b(s);if(r<0)throw new FormatError("Missing endstream command.");i.nextChar();this.shift();this.shift()}this.shift();a=a.makeSubStream(s,r,e);t&&(a=t.createStream(a,r));a=this.filter(a,e,r);a.dict=e;return a}filter(e,t,i){let a=t.get("F","Filter"),s=t.get("DP","DecodeParms");if(a instanceof Name){Array.isArray(s)&&warn("/DecodeParms should not be an Array, when /Filter is a Name.");return this.makeFilter(e,a.name,i,s)}let r=i;if(Array.isArray(a)){const t=a,i=s;for(let n=0,g=t.length;n=48&&e<=57?15&e:e>=65&&e<=70||e>=97&&e<=102?9+(15&e):-1}class Lexer{constructor(e,t=null){this.stream=e;this.nextChar();this.strBuf=[];this.knownCommands=t;this._hexStringNumWarn=0;this.beginInlineImagePos=-1}nextChar(){return this.currentChar=this.stream.getByte()}peekChar(){return this.stream.peekByte()}getNumber(){let e=this.currentChar,t=!1,i=0,a=1;if(45===e){a=-1;e=this.nextChar();45===e&&(e=this.nextChar())}else 43===e&&(e=this.nextChar());if(10===e||13===e)do{e=this.nextChar()}while(10===e||13===e);if(46===e){i=10;e=this.nextChar()}if(e<48||e>57){const t=`Invalid number: ${String.fromCharCode(e)} (charCode ${e})`;if(isWhiteSpace(e)||-1===e){info(`Lexer.getNumber - "${t}".`);return 0}throw new FormatError(t)}let s=e-48,r=0,n=1;for(;(e=this.nextChar())>=0;)if(e>=48&&e<=57){const a=e-48;if(t)r=10*r+a;else{0!==i&&(i*=10);s=10*s+a}}else if(46===e){if(0!==i)break;i=1}else if(45===e)warn("Badly formatted number: minus sign in the middle");else{if(69!==e&&101!==e)break;e=this.peekChar();if(43===e||45===e){n=45===e?-1:1;this.nextChar()}else if(e<48||e>57)break;t=!0}0!==i&&(s/=i);t&&(s*=10**(n*r));return a*s}getString(){let e=1,t=!1;const i=this.strBuf;i.length=0;let a=this.nextChar();for(;;){let s=!1;switch(0|a){case-1:warn("Unterminated string");t=!0;break;case 40:++e;i.push("(");break;case 41:if(0==--e){this.nextChar();t=!0}else i.push(")");break;case 92:a=this.nextChar();switch(a){case-1:warn("Unterminated string");t=!0;break;case 110:i.push("\n");break;case 114:i.push("\r");break;case 116:i.push("\t");break;case 98:i.push("\b");break;case 102:i.push("\f");break;case 92:case 40:case 41:i.push(String.fromCharCode(a));break;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:let e=15&a;a=this.nextChar();s=!0;if(a>=48&&a<=55){e=(e<<3)+(15&a);a=this.nextChar();if(a>=48&&a<=55){s=!1;e=(e<<3)+(15&a)}}i.push(String.fromCharCode(e));break;case 13:10===this.peekChar()&&this.nextChar();break;case 10:break;default:i.push(String.fromCharCode(a))}break;default:i.push(String.fromCharCode(a))}if(t)break;s||(a=this.nextChar())}return i.join("")}getName(){let e,t;const i=this.strBuf;i.length=0;for(;(e=this.nextChar())>=0&&!ai[e];)if(35===e){e=this.nextChar();if(ai[e]){warn("Lexer_getName: NUMBER SIGN (#) should be followed by a hexadecimal number.");i.push("#");break}const a=toHexDigit(e);if(-1!==a){t=e;e=this.nextChar();const s=toHexDigit(e);if(-1===s){warn(`Lexer_getName: Illegal digit (${String.fromCharCode(e)}) in hexadecimal number.`);i.push("#",String.fromCharCode(t));if(ai[e])break;i.push(String.fromCharCode(e));continue}i.push(String.fromCharCode(a<<4|s))}else i.push("#",String.fromCharCode(e))}else i.push(String.fromCharCode(e));i.length>127&&warn(`Name token is longer than allowed by the spec: ${i.length}`);return Name.get(i.join(""))}_hexStringWarn(e){5!=this._hexStringNumWarn++?this._hexStringNumWarn>5||warn(`getHexString - ignoring invalid character: ${e}`):warn("getHexString - ignoring additional invalid characters.")}getHexString(){const e=this.strBuf;e.length=0;let t=this.currentChar,i=-1,a=-1;this._hexStringNumWarn=0;for(;;){if(t<0){warn("Unterminated hex string");break}if(62===t){this.nextChar();break}if(1!==ai[t]){a=toHexDigit(t);if(-1===a)this._hexStringWarn(t);else if(-1===i)i=a;else{e.push(String.fromCharCode(i<<4|a));i=-1}t=this.nextChar()}else t=this.nextChar()}-1!==i&&e.push(String.fromCharCode(i<<4));return e.join("")}getObj(){let e=!1,t=this.currentChar;for(;;){if(t<0)return Bt;if(e)10!==t&&13!==t||(e=!1);else if(37===t)e=!0;else if(1!==ai[t])break;t=this.nextChar()}switch(0|t){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 43:case 45:case 46:return this.getNumber();case 40:return this.getString();case 47:return this.getName();case 91:this.nextChar();return Cmd.get("[");case 93:this.nextChar();return Cmd.get("]");case 60:t=this.nextChar();if(60===t){this.nextChar();return Cmd.get("<<")}return this.getHexString();case 62:t=this.nextChar();if(62===t){this.nextChar();return Cmd.get(">>")}return Cmd.get(">");case 123:this.nextChar();return Cmd.get("{");case 125:this.nextChar();return Cmd.get("}");case 41:this.nextChar();throw new FormatError(`Illegal character: ${t}`)}let i=String.fromCharCode(t);if(t<32||t>127){const e=this.peekChar();if(e>=32&&e<=127){this.nextChar();return Cmd.get(i)}}const a=this.knownCommands;let s=void 0!==a?.[i];for(;(t=this.nextChar())>=0&&!ai[t];){const e=i+String.fromCharCode(t);if(s&&void 0===a[e])break;if(128===i.length)throw new FormatError(`Command token too long: ${i.length}`);i=e;s=void 0!==a?.[i]}if("true"===i)return!0;if("false"===i)return!1;if("null"===i)return null;"BI"===i&&(this.beginInlineImagePos=this.stream.pos);return Cmd.get(i)}skipToNextLine(){let e=this.currentChar;for(;e>=0;){if(13===e){e=this.nextChar();10===e&&this.nextChar();break}if(10===e){this.nextChar();break}e=this.nextChar()}}}class Linearization{static create(e){function getInt(e,t,i=!1){const a=e.get(t);if(Number.isInteger(a)&&(i?a>=0:a>0))return a;throw new Error(`The "${t}" parameter in the linearization dictionary is invalid.`)}const t=new Parser({lexer:new Lexer(e),xref:null}),i=t.getObj(),a=t.getObj(),s=t.getObj(),r=t.getObj();let n,g;if(!(Number.isInteger(i)&&Number.isInteger(a)&&isCmd(s,"obj")&&r instanceof Dict&&"number"==typeof(n=r.get("Linearized"))&&n>0))return null;if((g=getInt(r,"L"))!==e.length)throw new Error('The "L" parameter in the linearization dictionary does not equal the stream length.');return{length:g,hints:function getHints(e){const t=e.get("H");let i;if(Array.isArray(t)&&(2===(i=t.length)||4===i)){for(let e=0;e0))throw new Error(`Hint (${e}) in the linearization dictionary is invalid.`)}return t}throw new Error("Hint array in the linearization dictionary is invalid.")}(r),objectNumberFirst:getInt(r,"O"),endFirst:getInt(r,"E"),numPages:getInt(r,"N"),mainXRefEntriesOffset:getInt(r,"T"),pageFirst:r.has("P")?getInt(r,"P",!0):0}}}const si=["Adobe-GB1-UCS2","Adobe-CNS1-UCS2","Adobe-Japan1-UCS2","Adobe-Korea1-UCS2","78-EUC-H","78-EUC-V","78-H","78-RKSJ-H","78-RKSJ-V","78-V","78ms-RKSJ-H","78ms-RKSJ-V","83pv-RKSJ-H","90ms-RKSJ-H","90ms-RKSJ-V","90msp-RKSJ-H","90msp-RKSJ-V","90pv-RKSJ-H","90pv-RKSJ-V","Add-H","Add-RKSJ-H","Add-RKSJ-V","Add-V","Adobe-CNS1-0","Adobe-CNS1-1","Adobe-CNS1-2","Adobe-CNS1-3","Adobe-CNS1-4","Adobe-CNS1-5","Adobe-CNS1-6","Adobe-GB1-0","Adobe-GB1-1","Adobe-GB1-2","Adobe-GB1-3","Adobe-GB1-4","Adobe-GB1-5","Adobe-Japan1-0","Adobe-Japan1-1","Adobe-Japan1-2","Adobe-Japan1-3","Adobe-Japan1-4","Adobe-Japan1-5","Adobe-Japan1-6","Adobe-Korea1-0","Adobe-Korea1-1","Adobe-Korea1-2","B5-H","B5-V","B5pc-H","B5pc-V","CNS-EUC-H","CNS-EUC-V","CNS1-H","CNS1-V","CNS2-H","CNS2-V","ETHK-B5-H","ETHK-B5-V","ETen-B5-H","ETen-B5-V","ETenms-B5-H","ETenms-B5-V","EUC-H","EUC-V","Ext-H","Ext-RKSJ-H","Ext-RKSJ-V","Ext-V","GB-EUC-H","GB-EUC-V","GB-H","GB-V","GBK-EUC-H","GBK-EUC-V","GBK2K-H","GBK2K-V","GBKp-EUC-H","GBKp-EUC-V","GBT-EUC-H","GBT-EUC-V","GBT-H","GBT-V","GBTpc-EUC-H","GBTpc-EUC-V","GBpc-EUC-H","GBpc-EUC-V","H","HKdla-B5-H","HKdla-B5-V","HKdlb-B5-H","HKdlb-B5-V","HKgccs-B5-H","HKgccs-B5-V","HKm314-B5-H","HKm314-B5-V","HKm471-B5-H","HKm471-B5-V","HKscs-B5-H","HKscs-B5-V","Hankaku","Hiragana","KSC-EUC-H","KSC-EUC-V","KSC-H","KSC-Johab-H","KSC-Johab-V","KSC-V","KSCms-UHC-H","KSCms-UHC-HW-H","KSCms-UHC-HW-V","KSCms-UHC-V","KSCpc-EUC-H","KSCpc-EUC-V","Katakana","NWP-H","NWP-V","RKSJ-H","RKSJ-V","Roman","UniCNS-UCS2-H","UniCNS-UCS2-V","UniCNS-UTF16-H","UniCNS-UTF16-V","UniCNS-UTF32-H","UniCNS-UTF32-V","UniCNS-UTF8-H","UniCNS-UTF8-V","UniGB-UCS2-H","UniGB-UCS2-V","UniGB-UTF16-H","UniGB-UTF16-V","UniGB-UTF32-H","UniGB-UTF32-V","UniGB-UTF8-H","UniGB-UTF8-V","UniJIS-UCS2-H","UniJIS-UCS2-HW-H","UniJIS-UCS2-HW-V","UniJIS-UCS2-V","UniJIS-UTF16-H","UniJIS-UTF16-V","UniJIS-UTF32-H","UniJIS-UTF32-V","UniJIS-UTF8-H","UniJIS-UTF8-V","UniJIS2004-UTF16-H","UniJIS2004-UTF16-V","UniJIS2004-UTF32-H","UniJIS2004-UTF32-V","UniJIS2004-UTF8-H","UniJIS2004-UTF8-V","UniJISPro-UCS2-HW-V","UniJISPro-UCS2-V","UniJISPro-UTF8-V","UniJISX0213-UTF32-H","UniJISX0213-UTF32-V","UniJISX02132004-UTF32-H","UniJISX02132004-UTF32-V","UniKS-UCS2-H","UniKS-UCS2-V","UniKS-UTF16-H","UniKS-UTF16-V","UniKS-UTF32-H","UniKS-UTF32-V","UniKS-UTF8-H","UniKS-UTF8-V","V","WP-Symbol"],ri=2**24-1;class CMap{constructor(e=!1){this.codespaceRanges=[[],[],[],[]];this.numCodespaceRanges=0;this._map=[];this.name="";this.vertical=!1;this.useCMap=null;this.builtInCMap=e}addCodespaceRange(e,t,i){this.codespaceRanges[e-1].push(t,i);this.numCodespaceRanges++}mapCidRange(e,t,i){if(t-e>ri)throw new Error("mapCidRange - ignoring data above MAX_MAP_RANGE.");for(;e<=t;)this._map[e++]=i++}mapBfRange(e,t,i){if(t-e>ri)throw new Error("mapBfRange - ignoring data above MAX_MAP_RANGE.");const a=i.length-1;for(;e<=t;){this._map[e++]=i;const t=i.charCodeAt(a)+1;t>255?i=i.substring(0,a-1)+String.fromCharCode(i.charCodeAt(a-1)+1)+"\0":i=i.substring(0,a)+String.fromCharCode(t)}}mapBfRangeToArray(e,t,i){if(t-e>ri)throw new Error("mapBfRangeToArray - ignoring data above MAX_MAP_RANGE.");const a=i.length;let s=0;for(;e<=t&&s>>0;const n=s[r];for(let e=0,t=n.length;e=t&&a<=s){i.charcode=a;i.length=r+1;return}}}i.charcode=0;i.length=1}getCharCodeLength(e){const t=this.codespaceRanges;for(let i=0,a=t.length;i=s&&e<=r)return i+1}}return 1}get length(){return this._map.length}get isIdentityCMap(){if("Identity-H"!==this.name&&"Identity-V"!==this.name)return!1;if(65536!==this._map.length)return!1;for(let e=0;e<65536;e++)if(this._map[e]!==e)return!1;return!0}}class IdentityCMap extends CMap{constructor(e,t){super();this.vertical=e;this.addCodespaceRange(t,0,65535)}mapCidRange(e,t,i){unreachable("should not call mapCidRange")}mapBfRange(e,t,i){unreachable("should not call mapBfRange")}mapBfRangeToArray(e,t,i){unreachable("should not call mapBfRangeToArray")}mapOne(e,t){unreachable("should not call mapCidOne")}lookup(e){return Number.isInteger(e)&&e<=65535?e:void 0}contains(e){return Number.isInteger(e)&&e<=65535}forEach(e){for(let t=0;t<=65535;t++)e(t,t)}charCodeOf(e){return Number.isInteger(e)&&e<=65535?e:-1}getMap(){const e=new Array(65536);for(let t=0;t<=65535;t++)e[t]=t;return e}get length(){return 65536}get isIdentityCMap(){unreachable("should not access .isIdentityCMap")}}function strToInt(e){let t=0;for(let i=0;i>>0}function expectString(e){if("string"!=typeof e)throw new FormatError("Malformed CMap: expected string.")}function expectInt(e){if(!Number.isInteger(e))throw new FormatError("Malformed CMap: expected int.")}function parseBfChar(e,t){for(;;){let i=t.getObj();if(i===Bt)break;if(isCmd(i,"endbfchar"))return;expectString(i);const a=strToInt(i);i=t.getObj();expectString(i);const s=i;e.mapOne(a,s)}}function parseBfRange(e,t){for(;;){let i=t.getObj();if(i===Bt)break;if(isCmd(i,"endbfrange"))return;expectString(i);const a=strToInt(i);i=t.getObj();expectString(i);const s=strToInt(i);i=t.getObj();if(Number.isInteger(i)||"string"==typeof i){const t=Number.isInteger(i)?String.fromCharCode(i):i;e.mapBfRange(a,s,t)}else{if(!isCmd(i,"["))break;{i=t.getObj();const r=[];for(;!isCmd(i,"]")&&i!==Bt;){r.push(i);i=t.getObj()}e.mapBfRangeToArray(a,s,r)}}}throw new FormatError("Invalid bf range.")}function parseCidChar(e,t){for(;;){let i=t.getObj();if(i===Bt)break;if(isCmd(i,"endcidchar"))return;expectString(i);const a=strToInt(i);i=t.getObj();expectInt(i);const s=i;e.mapOne(a,s)}}function parseCidRange(e,t){for(;;){let i=t.getObj();if(i===Bt)break;if(isCmd(i,"endcidrange"))return;expectString(i);const a=strToInt(i);i=t.getObj();expectString(i);const s=strToInt(i);i=t.getObj();expectInt(i);const r=i;e.mapCidRange(a,s,r)}}function parseCodespaceRange(e,t){for(;;){let i=t.getObj();if(i===Bt)break;if(isCmd(i,"endcodespacerange"))return;if("string"!=typeof i)break;const a=strToInt(i);i=t.getObj();if("string"!=typeof i)break;const s=strToInt(i);e.addCodespaceRange(i.length,a,s)}throw new FormatError("Invalid codespace range.")}function parseWMode(e,t){const i=t.getObj();Number.isInteger(i)&&(e.vertical=!!i)}function parseCMapName(e,t){const i=t.getObj();i instanceof Name&&(e.name=i.name)}async function parseCMap(e,t,i,a){let s,r;A:for(;;)try{const i=t.getObj();if(i===Bt)break;if(i instanceof Name){"WMode"===i.name?parseWMode(e,t):"CMapName"===i.name&&parseCMapName(e,t);s=i}else if(i instanceof Cmd)switch(i.cmd){case"endcmap":break A;case"usecmap":s instanceof Name&&(r=s.name);break;case"begincodespacerange":parseCodespaceRange(e,t);break;case"beginbfchar":parseBfChar(e,t);break;case"begincidchar":parseCidChar(e,t);break;case"beginbfrange":parseBfRange(e,t);break;case"begincidrange":parseCidRange(e,t)}}catch(e){if(e instanceof MissingDataException)throw e;warn("Invalid cMap data: "+e);continue}!a&&r&&(a=r);return a?extendCMap(e,i,a):e}async function extendCMap(e,t,i){e.useCMap=await createBuiltInCMap(i,t);if(0===e.numCodespaceRanges){const t=e.useCMap.codespaceRanges;for(let i=0;iextendCMap(s,t,e)));const r=new Lexer(new Stream(i));return parseCMap(s,r,t,null)}class CMapFactory{static async create({encoding:e,fetchBuiltInCMap:t,useCMap:i}){if(e instanceof Name)return createBuiltInCMap(e.name,t);if(e instanceof BaseStream){const a=await parseCMap(new CMap,new Lexer(e),t,i);return a.isIdentityCMap?createBuiltInCMap(a.name,t):a}throw new Error("Encoding required.")}}const ni=[".notdef","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","endash","dagger","daggerdbl","periodcentered","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","questiondown","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","ring","cedilla","hungarumlaut","ogonek","caron","emdash","AE","ordfeminine","Lslash","Oslash","OE","ordmasculine","ae","dotlessi","lslash","oslash","oe","germandbls","onesuperior","logicalnot","mu","trademark","Eth","onehalf","plusminus","Thorn","onequarter","divide","brokenbar","degree","thorn","threequarters","twosuperior","registered","minus","eth","multiply","threesuperior","copyright","Aacute","Acircumflex","Adieresis","Agrave","Aring","Atilde","Ccedilla","Eacute","Ecircumflex","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Ntilde","Oacute","Ocircumflex","Odieresis","Ograve","Otilde","Scaron","Uacute","Ucircumflex","Udieresis","Ugrave","Yacute","Ydieresis","Zcaron","aacute","acircumflex","adieresis","agrave","aring","atilde","ccedilla","eacute","ecircumflex","edieresis","egrave","iacute","icircumflex","idieresis","igrave","ntilde","oacute","ocircumflex","odieresis","ograve","otilde","scaron","uacute","ucircumflex","udieresis","ugrave","yacute","ydieresis","zcaron"],gi=[".notdef","space","exclamsmall","Hungarumlautsmall","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","questionsmall","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","fi","fl","ffi","ffl","parenleftinferior","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","exclamdownsmall","centoldstyle","Lslashsmall","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","Dotaccentsmall","Macronsmall","figuredash","hypheninferior","Ogoneksmall","Ringsmall","Cedillasmall","onequarter","onehalf","threequarters","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall"],oi=[".notdef","space","dollaroldstyle","dollarsuperior","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","fi","fl","ffi","ffl","parenleftinferior","parenrightinferior","hyphensuperior","colonmonetary","onefitted","rupiah","centoldstyle","figuredash","hypheninferior","onequarter","onehalf","threequarters","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior"],Ii=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclamsmall","Hungarumlautsmall","","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","questionsmall","","asuperior","bsuperior","centsuperior","dsuperior","esuperior","","","","isuperior","","","lsuperior","msuperior","nsuperior","osuperior","","","rsuperior","ssuperior","tsuperior","","ff","fi","fl","ffi","ffl","parenleftinferior","","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","exclamdownsmall","centoldstyle","Lslashsmall","","","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","","Dotaccentsmall","","","Macronsmall","","","figuredash","hypheninferior","","","Ogoneksmall","Ringsmall","Cedillasmall","","","","onequarter","onehalf","threequarters","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","","","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall"],ci=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclamsmall","Hungarumlautsmall","centoldstyle","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","","threequartersemdash","","questionsmall","","","","","Ethsmall","","","onequarter","onehalf","threequarters","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","","","","","","","ff","fi","fl","ffi","ffl","parenleftinferior","","parenrightinferior","Circumflexsmall","hypheninferior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","","","asuperior","centsuperior","","","","","Aacutesmall","Agravesmall","Acircumflexsmall","Adieresissmall","Atildesmall","Aringsmall","Ccedillasmall","Eacutesmall","Egravesmall","Ecircumflexsmall","Edieresissmall","Iacutesmall","Igravesmall","Icircumflexsmall","Idieresissmall","Ntildesmall","Oacutesmall","Ogravesmall","Ocircumflexsmall","Odieresissmall","Otildesmall","Uacutesmall","Ugravesmall","Ucircumflexsmall","Udieresissmall","","eightsuperior","fourinferior","threeinferior","sixinferior","eightinferior","seveninferior","Scaronsmall","","centinferior","twoinferior","","Dieresissmall","","Caronsmall","osuperior","fiveinferior","","commainferior","periodinferior","Yacutesmall","","dollarinferior","","","Thornsmall","","nineinferior","zeroinferior","Zcaronsmall","AEsmall","Oslashsmall","questiondownsmall","oneinferior","Lslashsmall","","","","","","","Cedillasmall","","","","","","OEsmall","figuredash","hyphensuperior","","","","","exclamdownsmall","","Ydieresissmall","","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","ninesuperior","zerosuperior","","esuperior","rsuperior","tsuperior","","","isuperior","ssuperior","dsuperior","","","","","","lsuperior","Ogoneksmall","Brevesmall","Macronsmall","bsuperior","nsuperior","msuperior","commasuperior","periodsuperior","Dotaccentsmall","Ringsmall","","","",""],Ci=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","","Adieresis","Aring","Ccedilla","Eacute","Ntilde","Odieresis","Udieresis","aacute","agrave","acircumflex","adieresis","atilde","aring","ccedilla","eacute","egrave","ecircumflex","edieresis","iacute","igrave","icircumflex","idieresis","ntilde","oacute","ograve","ocircumflex","odieresis","otilde","uacute","ugrave","ucircumflex","udieresis","dagger","degree","cent","sterling","section","bullet","paragraph","germandbls","registered","copyright","trademark","acute","dieresis","notequal","AE","Oslash","infinity","plusminus","lessequal","greaterequal","yen","mu","partialdiff","summation","product","pi","integral","ordfeminine","ordmasculine","Omega","ae","oslash","questiondown","exclamdown","logicalnot","radical","florin","approxequal","Delta","guillemotleft","guillemotright","ellipsis","space","Agrave","Atilde","Otilde","OE","oe","endash","emdash","quotedblleft","quotedblright","quoteleft","quoteright","divide","lozenge","ydieresis","Ydieresis","fraction","currency","guilsinglleft","guilsinglright","fi","fl","daggerdbl","periodcentered","quotesinglbase","quotedblbase","perthousand","Acircumflex","Ecircumflex","Aacute","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Oacute","Ocircumflex","apple","Ograve","Uacute","Ucircumflex","Ugrave","dotlessi","circumflex","tilde","macron","breve","dotaccent","ring","cedilla","hungarumlaut","ogonek","caron"],hi=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","","endash","dagger","daggerdbl","periodcentered","","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","","questiondown","","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","","ring","cedilla","","hungarumlaut","ogonek","caron","emdash","","","","","","","","","","","","","","","","","AE","","ordfeminine","","","","","Lslash","Oslash","OE","ordmasculine","","","","","","ae","","","","dotlessi","","","lslash","oslash","oe","germandbls","","","",""],li=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","bullet","Euro","bullet","quotesinglbase","florin","quotedblbase","ellipsis","dagger","daggerdbl","circumflex","perthousand","Scaron","guilsinglleft","OE","bullet","Zcaron","bullet","bullet","quoteleft","quoteright","quotedblleft","quotedblright","bullet","endash","emdash","tilde","trademark","scaron","guilsinglright","oe","bullet","zcaron","Ydieresis","space","exclamdown","cent","sterling","currency","yen","brokenbar","section","dieresis","copyright","ordfeminine","guillemotleft","logicalnot","hyphen","registered","macron","degree","plusminus","twosuperior","threesuperior","acute","mu","paragraph","periodcentered","cedilla","onesuperior","ordmasculine","guillemotright","onequarter","onehalf","threequarters","questiondown","Agrave","Aacute","Acircumflex","Atilde","Adieresis","Aring","AE","Ccedilla","Egrave","Eacute","Ecircumflex","Edieresis","Igrave","Iacute","Icircumflex","Idieresis","Eth","Ntilde","Ograve","Oacute","Ocircumflex","Otilde","Odieresis","multiply","Oslash","Ugrave","Uacute","Ucircumflex","Udieresis","Yacute","Thorn","germandbls","agrave","aacute","acircumflex","atilde","adieresis","aring","ae","ccedilla","egrave","eacute","ecircumflex","edieresis","igrave","iacute","icircumflex","idieresis","eth","ntilde","ograve","oacute","ocircumflex","otilde","odieresis","divide","oslash","ugrave","uacute","ucircumflex","udieresis","yacute","thorn","ydieresis"],Bi=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","universal","numbersign","existential","percent","ampersand","suchthat","parenleft","parenright","asteriskmath","plus","comma","minus","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","congruent","Alpha","Beta","Chi","Delta","Epsilon","Phi","Gamma","Eta","Iota","theta1","Kappa","Lambda","Mu","Nu","Omicron","Pi","Theta","Rho","Sigma","Tau","Upsilon","sigma1","Omega","Xi","Psi","Zeta","bracketleft","therefore","bracketright","perpendicular","underscore","radicalex","alpha","beta","chi","delta","epsilon","phi","gamma","eta","iota","phi1","kappa","lambda","mu","nu","omicron","pi","theta","rho","sigma","tau","upsilon","omega1","omega","xi","psi","zeta","braceleft","bar","braceright","similar","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","Euro","Upsilon1","minute","lessequal","fraction","infinity","florin","club","diamond","heart","spade","arrowboth","arrowleft","arrowup","arrowright","arrowdown","degree","plusminus","second","greaterequal","multiply","proportional","partialdiff","bullet","divide","notequal","equivalence","approxequal","ellipsis","arrowvertex","arrowhorizex","carriagereturn","aleph","Ifraktur","Rfraktur","weierstrass","circlemultiply","circleplus","emptyset","intersection","union","propersuperset","reflexsuperset","notsubset","propersubset","reflexsubset","element","notelement","angle","gradient","registerserif","copyrightserif","trademarkserif","product","radical","dotmath","logicalnot","logicaland","logicalor","arrowdblboth","arrowdblleft","arrowdblup","arrowdblright","arrowdbldown","lozenge","angleleft","registersans","copyrightsans","trademarksans","summation","parenlefttp","parenleftex","parenleftbt","bracketlefttp","bracketleftex","bracketleftbt","bracelefttp","braceleftmid","braceleftbt","braceex","","angleright","integral","integraltp","integralex","integralbt","parenrighttp","parenrightex","parenrightbt","bracketrighttp","bracketrightex","bracketrightbt","bracerighttp","bracerightmid","bracerightbt",""],Qi=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","a1","a2","a202","a3","a4","a5","a119","a118","a117","a11","a12","a13","a14","a15","a16","a105","a17","a18","a19","a20","a21","a22","a23","a24","a25","a26","a27","a28","a6","a7","a8","a9","a10","a29","a30","a31","a32","a33","a34","a35","a36","a37","a38","a39","a40","a41","a42","a43","a44","a45","a46","a47","a48","a49","a50","a51","a52","a53","a54","a55","a56","a57","a58","a59","a60","a61","a62","a63","a64","a65","a66","a67","a68","a69","a70","a71","a72","a73","a74","a203","a75","a204","a76","a77","a78","a79","a81","a82","a83","a84","a97","a98","a99","a100","","a89","a90","a93","a94","a91","a92","a205","a85","a206","a86","a87","a88","a95","a96","","","","","","","","","","","","","","","","","","","","a101","a102","a103","a104","a106","a107","a108","a112","a111","a110","a109","a120","a121","a122","a123","a124","a125","a126","a127","a128","a129","a130","a131","a132","a133","a134","a135","a136","a137","a138","a139","a140","a141","a142","a143","a144","a145","a146","a147","a148","a149","a150","a151","a152","a153","a154","a155","a156","a157","a158","a159","a160","a161","a163","a164","a196","a165","a192","a166","a167","a168","a169","a170","a171","a172","a173","a162","a174","a175","a176","a177","a178","a179","a193","a180","a199","a181","a200","a182","","a201","a183","a184","a197","a185","a194","a198","a186","a195","a187","a188","a189","a190","a191",""];function getEncoding(e){switch(e){case"WinAnsiEncoding":return li;case"StandardEncoding":return hi;case"MacRomanEncoding":return Ci;case"SymbolSetEncoding":return Bi;case"ZapfDingbatsEncoding":return Qi;case"ExpertEncoding":return Ii;case"MacExpertEncoding":return ci;default:return null}}const Ei=[".notdef","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","endash","dagger","daggerdbl","periodcentered","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","questiondown","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","ring","cedilla","hungarumlaut","ogonek","caron","emdash","AE","ordfeminine","Lslash","Oslash","OE","ordmasculine","ae","dotlessi","lslash","oslash","oe","germandbls","onesuperior","logicalnot","mu","trademark","Eth","onehalf","plusminus","Thorn","onequarter","divide","brokenbar","degree","thorn","threequarters","twosuperior","registered","minus","eth","multiply","threesuperior","copyright","Aacute","Acircumflex","Adieresis","Agrave","Aring","Atilde","Ccedilla","Eacute","Ecircumflex","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Ntilde","Oacute","Ocircumflex","Odieresis","Ograve","Otilde","Scaron","Uacute","Ucircumflex","Udieresis","Ugrave","Yacute","Ydieresis","Zcaron","aacute","acircumflex","adieresis","agrave","aring","atilde","ccedilla","eacute","ecircumflex","edieresis","egrave","iacute","icircumflex","idieresis","igrave","ntilde","oacute","ocircumflex","odieresis","ograve","otilde","scaron","uacute","ucircumflex","udieresis","ugrave","yacute","ydieresis","zcaron","exclamsmall","Hungarumlautsmall","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","commasuperior","threequartersemdash","periodsuperior","questionsmall","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","ffi","ffl","parenleftinferior","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","exclamdownsmall","centoldstyle","Lslashsmall","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","Dotaccentsmall","Macronsmall","figuredash","hypheninferior","Ogoneksmall","Ringsmall","Cedillasmall","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall","001.000","001.001","001.002","001.003","Black","Bold","Book","Light","Medium","Regular","Roman","Semibold"],ui=391,di=[null,{id:"hstem",min:2,stackClearing:!0,stem:!0},null,{id:"vstem",min:2,stackClearing:!0,stem:!0},{id:"vmoveto",min:1,stackClearing:!0},{id:"rlineto",min:2,resetStack:!0},{id:"hlineto",min:1,resetStack:!0},{id:"vlineto",min:1,resetStack:!0},{id:"rrcurveto",min:6,resetStack:!0},null,{id:"callsubr",min:1,undefStack:!0},{id:"return",min:0,undefStack:!0},null,null,{id:"endchar",min:0,stackClearing:!0},null,null,null,{id:"hstemhm",min:2,stackClearing:!0,stem:!0},{id:"hintmask",min:0,stackClearing:!0},{id:"cntrmask",min:0,stackClearing:!0},{id:"rmoveto",min:2,stackClearing:!0},{id:"hmoveto",min:1,stackClearing:!0},{id:"vstemhm",min:2,stackClearing:!0,stem:!0},{id:"rcurveline",min:8,resetStack:!0},{id:"rlinecurve",min:8,resetStack:!0},{id:"vvcurveto",min:4,resetStack:!0},{id:"hhcurveto",min:4,resetStack:!0},null,{id:"callgsubr",min:1,undefStack:!0},{id:"vhcurveto",min:4,resetStack:!0},{id:"hvcurveto",min:4,resetStack:!0}],fi=[null,null,null,{id:"and",min:2,stackDelta:-1},{id:"or",min:2,stackDelta:-1},{id:"not",min:1,stackDelta:0},null,null,null,{id:"abs",min:1,stackDelta:0},{id:"add",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]+e[t-1]}},{id:"sub",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]-e[t-1]}},{id:"div",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]/e[t-1]}},null,{id:"neg",min:1,stackDelta:0,stackFn(e,t){e[t-1]=-e[t-1]}},{id:"eq",min:2,stackDelta:-1},null,null,{id:"drop",min:1,stackDelta:-1},null,{id:"put",min:2,stackDelta:-2},{id:"get",min:1,stackDelta:0},{id:"ifelse",min:4,stackDelta:-3},{id:"random",min:0,stackDelta:1},{id:"mul",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]*e[t-1]}},null,{id:"sqrt",min:1,stackDelta:0},{id:"dup",min:1,stackDelta:1},{id:"exch",min:2,stackDelta:0},{id:"index",min:2,stackDelta:0},{id:"roll",min:3,stackDelta:-2},null,null,null,{id:"hflex",min:7,resetStack:!0},{id:"flex",min:13,resetStack:!0},{id:"hflex1",min:9,resetStack:!0},{id:"flex1",min:11,resetStack:!0}];class CFFParser{constructor(e,t,i){this.bytes=e.getBytes();this.properties=t;this.seacAnalysisEnabled=!!i}parse(){const e=this.properties,t=new CFF;this.cff=t;const i=this.parseHeader(),a=this.parseIndex(i.endPos),s=this.parseIndex(a.endPos),r=this.parseIndex(s.endPos),n=this.parseIndex(r.endPos),g=this.parseDict(s.obj.get(0)),o=this.createDict(CFFTopDict,g,t.strings);t.header=i.obj;t.names=this.parseNameIndex(a.obj);t.strings=this.parseStringIndex(r.obj);t.topDict=o;t.globalSubrIndex=n.obj;this.parsePrivateDict(t.topDict);t.isCIDFont=o.hasName("ROS");const c=o.getByName("CharStrings"),C=this.parseIndex(c).obj,h=o.getByName("FontMatrix");h&&(e.fontMatrix=h);const l=o.getByName("FontBBox");if(l){e.ascent=Math.max(l[3],l[1]);e.descent=Math.min(l[1],l[3]);e.ascentScaled=!0}let Q,E;if(t.isCIDFont){const e=this.parseIndex(o.getByName("FDArray")).obj;for(let i=0,a=e.count;i=t)throw new FormatError("Invalid CFF header");if(0!==i){info("cff data is shifted");e=e.subarray(i);this.bytes=e}const a=e[0],s=e[1],r=e[2],n=e[3];return{obj:new CFFHeader(a,s,r,n),endPos:r}}parseDict(e){let t=0;function parseOperand(){let i=e[t++];if(30===i)return function parseFloatOperand(){let i="";const a=15,s=["0","1","2","3","4","5","6","7","8","9",".","E","E-",null,"-"],r=e.length;for(;t>4,g=15&r;if(n===a)break;i+=s[n];if(g===a)break;i+=s[g]}return parseFloat(i)}();if(28===i){i=e[t++];i=(i<<24|e[t++]<<16)>>16;return i}if(29===i){i=e[t++];i=i<<8|e[t++];i=i<<8|e[t++];i=i<<8|e[t++];return i}if(i>=32&&i<=246)return i-139;if(i>=247&&i<=250)return 256*(i-247)+e[t++]+108;if(i>=251&&i<=254)return-256*(i-251)-e[t++]-108;warn('CFFParser_parseDict: "'+i+'" is a reserved command.');return NaN}let i=[];const a=[];t=0;const s=e.length;for(;t10)return!1;let s=e.stackSize;const r=e.stack;let n=t.length;for(let g=0;g>16;g+=2;s++}else if(14===o){if(s>=4){s-=4;if(this.seacAnalysisEnabled){e.seac=r.slice(s,s+4);return!1}}c=di[o]}else if(o>=32&&o<=246){r[s]=o-139;s++}else if(o>=247&&o<=254){r[s]=o<251?(o-247<<8)+t[g]+108:-(o-251<<8)-t[g]-108;g++;s++}else if(255===o){r[s]=(t[g]<<24|t[g+1]<<16|t[g+2]<<8|t[g+3])/65536;g+=4;s++}else if(19===o||20===o){e.hints+=s>>1;if(0===e.hints){t.copyWithin(g-1,g,-1);g-=1;n-=1;continue}g+=e.hints+7>>3;s%=2;c=di[o]}else{if(10===o||29===o){const t=10===o?i:a;if(!t){c=di[o];warn("Missing subrsIndex for "+c.id);return!1}let n=32768;t.count<1240?n=107:t.count<33900&&(n=1131);const g=r[--s]+n;if(g<0||g>=t.count||isNaN(g)){c=di[o];warn("Out of bounds subrIndex for "+c.id);return!1}e.stackSize=s;e.callDepth++;if(!this.parseCharString(e,t.get(g),i,a))return!1;e.callDepth--;s=e.stackSize;continue}if(11===o){e.stackSize=s;return!0}if(0===o&&g===t.length){t[g-1]=14;c=di[14]}else{if(9===o){t.copyWithin(g-1,g,-1);g-=1;n-=1;continue}c=di[o]}}if(c){if(c.stem){e.hints+=s>>1;if(3===o||23===o)e.hasVStems=!0;else if(e.hasVStems&&(1===o||18===o)){warn("CFF stem hints are in wrong order");t[g-1]=1===o?3:23}}if("min"in c&&!e.undefStack&&s=2&&c.stem?s%=2:s>1&&warn("Found too many parameters for stack-clearing command");s>0&&(e.width=r[s-1])}if("stackDelta"in c){"stackFn"in c&&c.stackFn(r,s);s+=c.stackDelta}else if(c.stackClearing)s=0;else if(c.resetStack){s=0;e.undefStack=!1}else if(c.undefStack){s=0;e.undefStack=!0;e.firstStackClearing=!1}}}n=s.length){warn("Invalid fd index for glyph index.");h=!1}if(h){Q=s[e].privateDict;l=Q.subrsIndex}}else t&&(l=t);h&&(h=this.parseCharString(C,o,l,i));if(null!==C.width){const e=Q.getByName("nominalWidthX");g[c]=e+C.width}else{const e=Q.getByName("defaultWidthX");g[c]=e}null!==C.seac&&(n[c]=C.seac);h||e.set(c,new Uint8Array([14]))}return{charStrings:e,seacs:n,widths:g}}emptyPrivateDictionary(e){const t=this.createDict(CFFPrivateDict,[],e.strings);e.setByKey(18,[0,0]);e.privateDict=t}parsePrivateDict(e){if(!e.hasName("Private")){this.emptyPrivateDictionary(e);return}const t=e.getByName("Private");if(!Array.isArray(t)||2!==t.length){e.removeByName("Private");return}const i=t[0],a=t[1];if(0===i||a>=this.bytes.length){this.emptyPrivateDictionary(e);return}const s=a+i,r=this.bytes.subarray(a,s),n=this.parseDict(r),g=this.createDict(CFFPrivateDict,n,e.strings);e.privateDict=g;0===g.getByName("ExpansionFactor")&&g.setByName("ExpansionFactor",.06);if(!g.getByName("Subrs"))return;const o=g.getByName("Subrs"),c=a+o;if(0===o||c>=this.bytes.length){this.emptyPrivateDictionary(e);return}const C=this.parseIndex(c);g.subrsIndex=C.obj}parseCharsets(e,t,i,a){if(0===e)return new CFFCharset(!0,yi.ISO_ADOBE,ni);if(1===e)return new CFFCharset(!0,yi.EXPERT,gi);if(2===e)return new CFFCharset(!0,yi.EXPERT_SUBSET,oi);const s=this.bytes,r=e,n=s[e++],g=[a?0:".notdef"];let o,c,C;t-=1;switch(n){case 0:for(C=0;C=65535){warn("Not enough space in charstrings to duplicate first glyph.");return}const e=this.charStrings.get(0);this.charStrings.add(e);this.isCIDFont&&this.fdSelect.fdSelect.push(this.fdSelect.fdSelect[0])}hasGlyphId(e){if(e<0||e>=this.charStrings.count)return!1;return this.charStrings.get(e).length>0}}class CFFHeader{constructor(e,t,i,a){this.major=e;this.minor=t;this.hdrSize=i;this.offSize=a}}class CFFStrings{constructor(){this.strings=[]}get(e){return e>=0&&e<=390?Ei[e]:e-ui<=this.strings.length?this.strings[e-ui]:Ei[0]}getSID(e){let t=Ei.indexOf(e);if(-1!==t)return t;t=this.strings.indexOf(e);return-1!==t?t+ui:-1}add(e){this.strings.push(e)}get count(){return this.strings.length}}class CFFIndex{constructor(){this.objects=[];this.length=0}add(e){this.length+=e.length;this.objects.push(e)}set(e,t){this.length+=t.length-this.objects[e].length;this.objects[e]=t}get(e){return this.objects[e]}get count(){return this.objects.length}}class CFFDict{constructor(e,t){this.keyToNameMap=e.keyToNameMap;this.nameToKeyMap=e.nameToKeyMap;this.defaults=e.defaults;this.types=e.types;this.opcodes=e.opcodes;this.order=e.order;this.strings=t;this.values=Object.create(null)}setByKey(e,t){if(!(e in this.keyToNameMap))return!1;if(0===t.length)return!0;for(const i of t)if(isNaN(i)){warn(`Invalid CFFDict value: "${t}" for key "${e}".`);return!0}const i=this.types[e];"num"!==i&&"sid"!==i&&"offset"!==i||(t=t[0]);this.values[e]=t;return!0}setByName(e,t){if(!(e in this.nameToKeyMap))throw new FormatError(`Invalid dictionary name "${e}"`);this.values[this.nameToKeyMap[e]]=t}hasName(e){return this.nameToKeyMap[e]in this.values}getByName(e){if(!(e in this.nameToKeyMap))throw new FormatError(`Invalid dictionary name ${e}"`);const t=this.nameToKeyMap[e];return t in this.values?this.values[t]:this.defaults[t]}removeByName(e){delete this.values[this.nameToKeyMap[e]]}static createTables(e){const t={keyToNameMap:{},nameToKeyMap:{},defaults:{},types:{},opcodes:{},order:[]};for(const i of e){const e=Array.isArray(i[0])?(i[0][0]<<8)+i[0][1]:i[0];t.keyToNameMap[e]=i[1];t.nameToKeyMap[i[1]]=e;t.types[e]=i[2];t.defaults[e]=i[3];t.opcodes[e]=Array.isArray(i[0])?i[0]:[i[0]];t.order.push(e)}return t}}const pi=[[[12,30],"ROS",["sid","sid","num"],null],[[12,20],"SyntheticBase","num",null],[0,"version","sid",null],[1,"Notice","sid",null],[[12,0],"Copyright","sid",null],[2,"FullName","sid",null],[3,"FamilyName","sid",null],[4,"Weight","sid",null],[[12,1],"isFixedPitch","num",0],[[12,2],"ItalicAngle","num",0],[[12,3],"UnderlinePosition","num",-100],[[12,4],"UnderlineThickness","num",50],[[12,5],"PaintType","num",0],[[12,6],"CharstringType","num",2],[[12,7],"FontMatrix",["num","num","num","num","num","num"],[.001,0,0,.001,0,0]],[13,"UniqueID","num",null],[5,"FontBBox",["num","num","num","num"],[0,0,0,0]],[[12,8],"StrokeWidth","num",0],[14,"XUID","array",null],[15,"charset","offset",0],[16,"Encoding","offset",0],[17,"CharStrings","offset",0],[18,"Private",["offset","offset"],null],[[12,21],"PostScript","sid",null],[[12,22],"BaseFontName","sid",null],[[12,23],"BaseFontBlend","delta",null],[[12,31],"CIDFontVersion","num",0],[[12,32],"CIDFontRevision","num",0],[[12,33],"CIDFontType","num",0],[[12,34],"CIDCount","num",8720],[[12,35],"UIDBase","num",null],[[12,37],"FDSelect","offset",null],[[12,36],"FDArray","offset",null],[[12,38],"FontName","sid",null]];class CFFTopDict extends CFFDict{static get tables(){return shadow(this,"tables",this.createTables(pi))}constructor(e){super(CFFTopDict.tables,e);this.privateDict=null}}const mi=[[6,"BlueValues","delta",null],[7,"OtherBlues","delta",null],[8,"FamilyBlues","delta",null],[9,"FamilyOtherBlues","delta",null],[[12,9],"BlueScale","num",.039625],[[12,10],"BlueShift","num",7],[[12,11],"BlueFuzz","num",1],[10,"StdHW","num",null],[11,"StdVW","num",null],[[12,12],"StemSnapH","delta",null],[[12,13],"StemSnapV","delta",null],[[12,14],"ForceBold","num",0],[[12,17],"LanguageGroup","num",0],[[12,18],"ExpansionFactor","num",.06],[[12,19],"initialRandomSeed","num",0],[20,"defaultWidthX","num",0],[21,"nominalWidthX","num",0],[19,"Subrs","offset",null]];class CFFPrivateDict extends CFFDict{static get tables(){return shadow(this,"tables",this.createTables(mi))}constructor(e){super(CFFPrivateDict.tables,e);this.subrsIndex=null}}const yi={ISO_ADOBE:0,EXPERT:1,EXPERT_SUBSET:2};class CFFCharset{constructor(e,t,i,a){this.predefined=e;this.format=t;this.charset=i;this.raw=a}}class CFFEncoding{constructor(e,t,i,a){this.predefined=e;this.format=t;this.encoding=i;this.raw=a}}class CFFFDSelect{constructor(e,t){this.format=e;this.fdSelect=t}getFDIndex(e){return e<0||e>=this.fdSelect.length?-1:this.fdSelect[e]}}class CFFOffsetTracker{constructor(){this.offsets=Object.create(null)}isTracking(e){return e in this.offsets}track(e,t){if(e in this.offsets)throw new FormatError(`Already tracking location of ${e}`);this.offsets[e]=t}offset(e){for(const t in this.offsets)this.offsets[t]+=e}setEntryLocation(e,t,i){if(!(e in this.offsets))throw new FormatError(`Not tracking location of ${e}`);const a=i.data,s=this.offsets[e];for(let e=0,i=t.length;e>24&255;a[n]=c>>16&255;a[g]=c>>8&255;a[o]=255&c}}}class CFFCompiler{constructor(e){this.cff=e}compile(){const e=this.cff,t={data:[],length:0,add(e){try{this.data.push(...e)}catch{this.data=this.data.concat(e)}this.length=this.data.length}},i=this.compileHeader(e.header);t.add(i);const a=this.compileNameIndex(e.names);t.add(a);if(e.isCIDFont&&e.topDict.hasName("FontMatrix")){const t=e.topDict.getByName("FontMatrix");e.topDict.removeByName("FontMatrix");for(const i of e.fdArray){let e=t.slice(0);i.hasName("FontMatrix")&&(e=Util.transform(e,i.getByName("FontMatrix")));i.setByName("FontMatrix",e)}}const s=e.topDict.getByName("XUID");s?.length>16&&e.topDict.removeByName("XUID");e.topDict.setByName("charset",0);let r=this.compileTopDicts([e.topDict],t.length,e.isCIDFont);t.add(r.output);const n=r.trackers[0],g=this.compileStringIndex(e.strings.strings);t.add(g);const o=this.compileIndex(e.globalSubrIndex);t.add(o);if(e.encoding&&e.topDict.hasName("Encoding"))if(e.encoding.predefined)n.setEntryLocation("Encoding",[e.encoding.format],t);else{const i=this.compileEncoding(e.encoding);n.setEntryLocation("Encoding",[t.length],t);t.add(i)}const c=this.compileCharset(e.charset,e.charStrings.count,e.strings,e.isCIDFont);n.setEntryLocation("charset",[t.length],t);t.add(c);const C=this.compileCharStrings(e.charStrings);n.setEntryLocation("CharStrings",[t.length],t);t.add(C);if(e.isCIDFont){n.setEntryLocation("FDSelect",[t.length],t);const i=this.compileFDSelect(e.fdSelect);t.add(i);r=this.compileTopDicts(e.fdArray,t.length,!0);n.setEntryLocation("FDArray",[t.length],t);t.add(r.output);const a=r.trackers;this.compilePrivateDicts(e.fdArray,a,t)}this.compilePrivateDicts([e.topDict],[n],t);t.add([0]);return t.data}encodeNumber(e){return Number.isInteger(e)?this.encodeInteger(e):this.encodeFloat(e)}static get EncodeFloatRegExp(){return shadow(this,"EncodeFloatRegExp",/\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/)}encodeFloat(e){let t=e.toString();const i=CFFCompiler.EncodeFloatRegExp.exec(t);if(i){const a=parseFloat("1e"+((i[2]?+i[2]:0)+i[1].length));t=(Math.round(e*a)/a).toString()}let a,s,r="";for(a=0,s=t.length;a=-107&&e<=107?[e+139]:e>=108&&e<=1131?[247+((e-=108)>>8),255&e]:e>=-1131&&e<=-108?[251+((e=-e-108)>>8),255&e]:e>=-32768&&e<=32767?[28,e>>8&255,255&e]:[29,e>>24&255,e>>16&255,e>>8&255,255&e];return t}compileHeader(e){return[e.major,e.minor,4,e.offSize]}compileNameIndex(e){const t=new CFFIndex;for(const i of e){const e=Math.min(i.length,127);let a=new Array(e);for(let t=0;t"~"||"["===e||"]"===e||"("===e||")"===e||"{"===e||"}"===e||"<"===e||">"===e||"/"===e||"%"===e)&&(e="_");a[t]=e}a=a.join("");""===a&&(a="Bad_Font_Name");t.add(stringToBytes(a))}return this.compileIndex(t)}compileTopDicts(e,t,i){const a=[];let s=new CFFIndex;for(const r of e){if(i){r.removeByName("CIDFontVersion");r.removeByName("CIDFontRevision");r.removeByName("CIDFontType");r.removeByName("CIDCount");r.removeByName("UIDBase")}const e=new CFFOffsetTracker,n=this.compileDict(r,e);a.push(e);s.add(n);e.offset(t)}s=this.compileIndex(s,a);return{trackers:a,output:s}}compilePrivateDicts(e,t,i){for(let a=0,s=e.length;a>8&255,255&r]);else{s=new Uint8Array(1+2*r);s[0]=0;let t=0;const a=e.charset.length;let n=!1;for(let r=1;r>8&255;s[r+1]=255&g}}return this.compileTypedArray(s)}compileEncoding(e){return this.compileTypedArray(e.raw)}compileFDSelect(e){const t=e.format;let i,a;switch(t){case 0:i=new Uint8Array(1+e.fdSelect.length);i[0]=t;for(a=0;a>8&255,255&s,r];for(a=1;a>8&255,255&a,t);r=t}}const g=(n.length-3)/3;n[1]=g>>8&255;n[2]=255&g;n.push(a>>8&255,255&a);i=new Uint8Array(n)}return this.compileTypedArray(i)}compileTypedArray(e){return Array.from(e)}compileIndex(e,t=[]){const i=e.objects,a=i.length;if(0===a)return[0,0];const s=[a>>8&255,255&a];let r,n,g=1;for(r=0;r>8&255,255&o):3===n?s.push(o>>16&255,o>>8&255,255&o):s.push(o>>>24&255,o>>16&255,o>>8&255,255&o);i[r]&&(o+=i[r].length)}for(r=0;r=5&&t<=7))return-1;a=e.substring(1)}if(a===a.toUpperCase()){i=parseInt(a,16);if(i>=0)return i}}return-1}const Fi=[[0,127],[128,255],[256,383],[384,591],[592,687,7424,7551,7552,7615],[688,767,42752,42783],[768,879,7616,7679],[880,1023],[11392,11519],[1024,1279,1280,1327,11744,11775,42560,42655],[1328,1423],[1424,1535],[42240,42559],[1536,1791,1872,1919],[1984,2047],[2304,2431],[2432,2559],[2560,2687],[2688,2815],[2816,2943],[2944,3071],[3072,3199],[3200,3327],[3328,3455],[3584,3711],[3712,3839],[4256,4351,11520,11567],[6912,7039],[4352,4607],[7680,7935,11360,11391,42784,43007],[7936,8191],[8192,8303,11776,11903],[8304,8351],[8352,8399],[8400,8447],[8448,8527],[8528,8591],[8592,8703,10224,10239,10496,10623,11008,11263],[8704,8959,10752,11007,10176,10223,10624,10751],[8960,9215],[9216,9279],[9280,9311],[9312,9471],[9472,9599],[9600,9631],[9632,9727],[9728,9983],[9984,10175],[12288,12351],[12352,12447],[12448,12543,12784,12799],[12544,12591,12704,12735],[12592,12687],[43072,43135],[12800,13055],[13056,13311],[44032,55215],[55296,57343],[67840,67871],[19968,40959,11904,12031,12032,12255,12272,12287,13312,19903,131072,173791,12688,12703],[57344,63743],[12736,12783,63744,64255,194560,195103],[64256,64335],[64336,65023],[65056,65071],[65040,65055],[65104,65135],[65136,65279],[65280,65519],[65520,65535],[3840,4095],[1792,1871],[1920,1983],[3456,3583],[4096,4255],[4608,4991,4992,5023,11648,11743],[5024,5119],[5120,5759],[5760,5791],[5792,5887],[6016,6143],[6144,6319],[10240,10495],[40960,42127],[5888,5919,5920,5951,5952,5983,5984,6015],[66304,66351],[66352,66383],[66560,66639],[118784,119039,119040,119295,119296,119375],[119808,120831],[1044480,1048573],[65024,65039,917760,917999],[917504,917631],[6400,6479],[6480,6527],[6528,6623],[6656,6687],[11264,11359],[11568,11647],[19904,19967],[43008,43055],[65536,65663,65664,65791,65792,65855],[65856,65935],[66432,66463],[66464,66527],[66640,66687],[66688,66735],[67584,67647],[68096,68191],[119552,119647],[73728,74751,74752,74879],[119648,119679],[7040,7103],[7168,7247],[7248,7295],[43136,43231],[43264,43311],[43312,43359],[43520,43615],[65936,65999],[66e3,66047],[66208,66271,66176,66207,67872,67903],[127024,127135,126976,127023]];function getUnicodeRangeFor(e,t=-1){if(-1!==t){const i=Fi[t];for(let a=0,s=i.length;a=i[a]&&e<=i[a+1])return t}for(let t=0,i=Fi.length;t=i[a]&&e<=i[a+1])return t}return-1}const Si=new RegExp("^(\\s)|(\\p{Mn})|(\\p{Cf})$","u"),ki=new Map;const Ri=!0,Ni=1,Gi=2,Mi=4,xi=32,Hi=[".notdef",".null","nonmarkingreturn","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","Adieresis","Aring","Ccedilla","Eacute","Ntilde","Odieresis","Udieresis","aacute","agrave","acircumflex","adieresis","atilde","aring","ccedilla","eacute","egrave","ecircumflex","edieresis","iacute","igrave","icircumflex","idieresis","ntilde","oacute","ograve","ocircumflex","odieresis","otilde","uacute","ugrave","ucircumflex","udieresis","dagger","degree","cent","sterling","section","bullet","paragraph","germandbls","registered","copyright","trademark","acute","dieresis","notequal","AE","Oslash","infinity","plusminus","lessequal","greaterequal","yen","mu","partialdiff","summation","product","pi","integral","ordfeminine","ordmasculine","Omega","ae","oslash","questiondown","exclamdown","logicalnot","radical","florin","approxequal","Delta","guillemotleft","guillemotright","ellipsis","nonbreakingspace","Agrave","Atilde","Otilde","OE","oe","endash","emdash","quotedblleft","quotedblright","quoteleft","quoteright","divide","lozenge","ydieresis","Ydieresis","fraction","currency","guilsinglleft","guilsinglright","fi","fl","daggerdbl","periodcentered","quotesinglbase","quotedblbase","perthousand","Acircumflex","Ecircumflex","Aacute","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Oacute","Ocircumflex","apple","Ograve","Uacute","Ucircumflex","Ugrave","dotlessi","circumflex","tilde","macron","breve","dotaccent","ring","cedilla","hungarumlaut","ogonek","caron","Lslash","lslash","Scaron","scaron","Zcaron","zcaron","brokenbar","Eth","eth","Yacute","yacute","Thorn","thorn","minus","multiply","onesuperior","twosuperior","threesuperior","onehalf","onequarter","threequarters","franc","Gbreve","gbreve","Idotaccent","Scedilla","scedilla","Cacute","cacute","Ccaron","ccaron","dcroat"];function recoverGlyphName(e,t){if(void 0!==t[e])return e;const i=getUnicodeForGlyph(e,t);if(-1!==i)for(const e in t)if(t[e]===i)return e;info("Unable to recover a standard glyph name for: "+e);return e}function type1FontGlyphMapping(e,t,i){const a=Object.create(null);let s,r,n;const g=!!(e.flags&Mi);if(e.isInternalFont){n=t;for(r=0;r=0?s:0}}else if(e.baseEncodingName){n=getEncoding(e.baseEncodingName);for(r=0;r=0?s:0}}else if(g)for(r in t)a[r]=t[r];else{n=hi;for(r=0;r=0?s:0}}const o=e.differences;let c;if(o)for(r in o){const e=o[r];s=i.indexOf(e);if(-1===s){c||(c=wi());const t=recoverGlyphName(e,c);t!==e&&(s=i.indexOf(t))}a[r]=s>=0?s:0}return a}function normalizeFontName(e){return e.replaceAll(/[,_]/g,"-").replaceAll(/\s/g,"")}const Ji=getLookupTableFactory((e=>{e[8211]=65074;e[8212]=65073;e[8229]=65072;e[8230]=65049;e[12289]=65041;e[12290]=65042;e[12296]=65087;e[12297]=65088;e[12298]=65085;e[12299]=65086;e[12300]=65089;e[12301]=65090;e[12302]=65091;e[12303]=65092;e[12304]=65083;e[12305]=65084;e[12308]=65081;e[12309]=65082;e[12310]=65047;e[12311]=65048;e[65103]=65076;e[65281]=65045;e[65288]=65077;e[65289]=65078;e[65292]=65040;e[65306]=65043;e[65307]=65044;e[65311]=65046;e[65339]=65095;e[65341]=65096;e[65343]=65075;e[65371]=65079;e[65373]=65080})),Yi=getLookupTableFactory((function(e){e["Times-Roman"]="Times-Roman";e.Helvetica="Helvetica";e.Courier="Courier";e.Symbol="Symbol";e["Times-Bold"]="Times-Bold";e["Helvetica-Bold"]="Helvetica-Bold";e["Courier-Bold"]="Courier-Bold";e.ZapfDingbats="ZapfDingbats";e["Times-Italic"]="Times-Italic";e["Helvetica-Oblique"]="Helvetica-Oblique";e["Courier-Oblique"]="Courier-Oblique";e["Times-BoldItalic"]="Times-BoldItalic";e["Helvetica-BoldOblique"]="Helvetica-BoldOblique";e["Courier-BoldOblique"]="Courier-BoldOblique";e.ArialNarrow="Helvetica";e["ArialNarrow-Bold"]="Helvetica-Bold";e["ArialNarrow-BoldItalic"]="Helvetica-BoldOblique";e["ArialNarrow-Italic"]="Helvetica-Oblique";e.ArialBlack="Helvetica";e["ArialBlack-Bold"]="Helvetica-Bold";e["ArialBlack-BoldItalic"]="Helvetica-BoldOblique";e["ArialBlack-Italic"]="Helvetica-Oblique";e["Arial-Black"]="Helvetica";e["Arial-Black-Bold"]="Helvetica-Bold";e["Arial-Black-BoldItalic"]="Helvetica-BoldOblique";e["Arial-Black-Italic"]="Helvetica-Oblique";e.Arial="Helvetica";e["Arial-Bold"]="Helvetica-Bold";e["Arial-BoldItalic"]="Helvetica-BoldOblique";e["Arial-Italic"]="Helvetica-Oblique";e.ArialMT="Helvetica";e["Arial-BoldItalicMT"]="Helvetica-BoldOblique";e["Arial-BoldMT"]="Helvetica-Bold";e["Arial-ItalicMT"]="Helvetica-Oblique";e["Arial-BoldItalicMT-BoldItalic"]="Helvetica-BoldOblique";e["Arial-BoldMT-Bold"]="Helvetica-Bold";e["Arial-ItalicMT-Italic"]="Helvetica-Oblique";e.ArialUnicodeMS="Helvetica";e["ArialUnicodeMS-Bold"]="Helvetica-Bold";e["ArialUnicodeMS-BoldItalic"]="Helvetica-BoldOblique";e["ArialUnicodeMS-Italic"]="Helvetica-Oblique";e["Courier-BoldItalic"]="Courier-BoldOblique";e["Courier-Italic"]="Courier-Oblique";e.CourierNew="Courier";e["CourierNew-Bold"]="Courier-Bold";e["CourierNew-BoldItalic"]="Courier-BoldOblique";e["CourierNew-Italic"]="Courier-Oblique";e["CourierNewPS-BoldItalicMT"]="Courier-BoldOblique";e["CourierNewPS-BoldMT"]="Courier-Bold";e["CourierNewPS-ItalicMT"]="Courier-Oblique";e.CourierNewPSMT="Courier";e["Helvetica-BoldItalic"]="Helvetica-BoldOblique";e["Helvetica-Italic"]="Helvetica-Oblique";e["HelveticaLTStd-Bold"]="Helvetica-Bold";e["Symbol-Bold"]="Symbol";e["Symbol-BoldItalic"]="Symbol";e["Symbol-Italic"]="Symbol";e.TimesNewRoman="Times-Roman";e["TimesNewRoman-Bold"]="Times-Bold";e["TimesNewRoman-BoldItalic"]="Times-BoldItalic";e["TimesNewRoman-Italic"]="Times-Italic";e.TimesNewRomanPS="Times-Roman";e["TimesNewRomanPS-Bold"]="Times-Bold";e["TimesNewRomanPS-BoldItalic"]="Times-BoldItalic";e["TimesNewRomanPS-BoldItalicMT"]="Times-BoldItalic";e["TimesNewRomanPS-BoldMT"]="Times-Bold";e["TimesNewRomanPS-Italic"]="Times-Italic";e["TimesNewRomanPS-ItalicMT"]="Times-Italic";e.TimesNewRomanPSMT="Times-Roman";e["TimesNewRomanPSMT-Bold"]="Times-Bold";e["TimesNewRomanPSMT-BoldItalic"]="Times-BoldItalic";e["TimesNewRomanPSMT-Italic"]="Times-Italic"})),vi=getLookupTableFactory((function(e){e.Courier="FoxitFixed.pfb";e["Courier-Bold"]="FoxitFixedBold.pfb";e["Courier-BoldOblique"]="FoxitFixedBoldItalic.pfb";e["Courier-Oblique"]="FoxitFixedItalic.pfb";e.Helvetica="LiberationSans-Regular.ttf";e["Helvetica-Bold"]="LiberationSans-Bold.ttf";e["Helvetica-BoldOblique"]="LiberationSans-BoldItalic.ttf";e["Helvetica-Oblique"]="LiberationSans-Italic.ttf";e["Times-Roman"]="FoxitSerif.pfb";e["Times-Bold"]="FoxitSerifBold.pfb";e["Times-BoldItalic"]="FoxitSerifBoldItalic.pfb";e["Times-Italic"]="FoxitSerifItalic.pfb";e.Symbol="FoxitSymbol.pfb";e.ZapfDingbats="FoxitDingbats.pfb";e["LiberationSans-Regular"]="LiberationSans-Regular.ttf";e["LiberationSans-Bold"]="LiberationSans-Bold.ttf";e["LiberationSans-Italic"]="LiberationSans-Italic.ttf";e["LiberationSans-BoldItalic"]="LiberationSans-BoldItalic.ttf"})),Ki=getLookupTableFactory((function(e){e.Calibri="Helvetica";e["Calibri-Bold"]="Helvetica-Bold";e["Calibri-BoldItalic"]="Helvetica-BoldOblique";e["Calibri-Italic"]="Helvetica-Oblique";e.CenturyGothic="Helvetica";e["CenturyGothic-Bold"]="Helvetica-Bold";e["CenturyGothic-BoldItalic"]="Helvetica-BoldOblique";e["CenturyGothic-Italic"]="Helvetica-Oblique";e.ComicSansMS="Comic Sans MS";e["ComicSansMS-Bold"]="Comic Sans MS-Bold";e["ComicSansMS-BoldItalic"]="Comic Sans MS-BoldItalic";e["ComicSansMS-Italic"]="Comic Sans MS-Italic";e.GillSansMT="Helvetica";e["GillSansMT-Bold"]="Helvetica-Bold";e["GillSansMT-BoldItalic"]="Helvetica-BoldOblique";e["GillSansMT-Italic"]="Helvetica-Oblique";e.Impact="Helvetica";e["ItcSymbol-Bold"]="Helvetica-Bold";e["ItcSymbol-BoldItalic"]="Helvetica-BoldOblique";e["ItcSymbol-Book"]="Helvetica";e["ItcSymbol-BookItalic"]="Helvetica-Oblique";e["ItcSymbol-Medium"]="Helvetica";e["ItcSymbol-MediumItalic"]="Helvetica-Oblique";e.LucidaConsole="Courier";e["LucidaConsole-Bold"]="Courier-Bold";e["LucidaConsole-BoldItalic"]="Courier-BoldOblique";e["LucidaConsole-Italic"]="Courier-Oblique";e["LucidaSans-Demi"]="Helvetica-Bold";e["MS-Gothic"]="MS Gothic";e["MS-Gothic-Bold"]="MS Gothic-Bold";e["MS-Gothic-BoldItalic"]="MS Gothic-BoldItalic";e["MS-Gothic-Italic"]="MS Gothic-Italic";e["MS-Mincho"]="MS Mincho";e["MS-Mincho-Bold"]="MS Mincho-Bold";e["MS-Mincho-BoldItalic"]="MS Mincho-BoldItalic";e["MS-Mincho-Italic"]="MS Mincho-Italic";e["MS-PGothic"]="MS PGothic";e["MS-PGothic-Bold"]="MS PGothic-Bold";e["MS-PGothic-BoldItalic"]="MS PGothic-BoldItalic";e["MS-PGothic-Italic"]="MS PGothic-Italic";e["MS-PMincho"]="MS PMincho";e["MS-PMincho-Bold"]="MS PMincho-Bold";e["MS-PMincho-BoldItalic"]="MS PMincho-BoldItalic";e["MS-PMincho-Italic"]="MS PMincho-Italic";e.NuptialScript="Times-Italic";e.SegoeUISymbol="Helvetica"})),Ti=getLookupTableFactory((function(e){e["Adobe Jenson"]=!0;e["Adobe Text"]=!0;e.Albertus=!0;e.Aldus=!0;e.Alexandria=!0;e.Algerian=!0;e["American Typewriter"]=!0;e.Antiqua=!0;e.Apex=!0;e.Arno=!0;e.Aster=!0;e.Aurora=!0;e.Baskerville=!0;e.Bell=!0;e.Bembo=!0;e["Bembo Schoolbook"]=!0;e.Benguiat=!0;e["Berkeley Old Style"]=!0;e["Bernhard Modern"]=!0;e["Berthold City"]=!0;e.Bodoni=!0;e["Bauer Bodoni"]=!0;e["Book Antiqua"]=!0;e.Bookman=!0;e["Bordeaux Roman"]=!0;e["Californian FB"]=!0;e.Calisto=!0;e.Calvert=!0;e.Capitals=!0;e.Cambria=!0;e.Cartier=!0;e.Caslon=!0;e.Catull=!0;e.Centaur=!0;e["Century Old Style"]=!0;e["Century Schoolbook"]=!0;e.Chaparral=!0;e["Charis SIL"]=!0;e.Cheltenham=!0;e["Cholla Slab"]=!0;e.Clarendon=!0;e.Clearface=!0;e.Cochin=!0;e.Colonna=!0;e["Computer Modern"]=!0;e["Concrete Roman"]=!0;e.Constantia=!0;e["Cooper Black"]=!0;e.Corona=!0;e.Ecotype=!0;e.Egyptienne=!0;e.Elephant=!0;e.Excelsior=!0;e.Fairfield=!0;e["FF Scala"]=!0;e.Folkard=!0;e.Footlight=!0;e.FreeSerif=!0;e["Friz Quadrata"]=!0;e.Garamond=!0;e.Gentium=!0;e.Georgia=!0;e.Gloucester=!0;e["Goudy Old Style"]=!0;e["Goudy Schoolbook"]=!0;e["Goudy Pro Font"]=!0;e.Granjon=!0;e["Guardian Egyptian"]=!0;e.Heather=!0;e.Hercules=!0;e["High Tower Text"]=!0;e.Hiroshige=!0;e["Hoefler Text"]=!0;e["Humana Serif"]=!0;e.Imprint=!0;e["Ionic No. 5"]=!0;e.Janson=!0;e.Joanna=!0;e.Korinna=!0;e.Lexicon=!0;e.LiberationSerif=!0;e["Liberation Serif"]=!0;e["Linux Libertine"]=!0;e.Literaturnaya=!0;e.Lucida=!0;e["Lucida Bright"]=!0;e.Melior=!0;e.Memphis=!0;e.Miller=!0;e.Minion=!0;e.Modern=!0;e["Mona Lisa"]=!0;e["Mrs Eaves"]=!0;e["MS Serif"]=!0;e["Museo Slab"]=!0;e["New York"]=!0;e["Nimbus Roman"]=!0;e["NPS Rawlinson Roadway"]=!0;e.NuptialScript=!0;e.Palatino=!0;e.Perpetua=!0;e.Plantin=!0;e["Plantin Schoolbook"]=!0;e.Playbill=!0;e["Poor Richard"]=!0;e["Rawlinson Roadway"]=!0;e.Renault=!0;e.Requiem=!0;e.Rockwell=!0;e.Roman=!0;e["Rotis Serif"]=!0;e.Sabon=!0;e.Scala=!0;e.Seagull=!0;e.Sistina=!0;e.Souvenir=!0;e.STIX=!0;e["Stone Informal"]=!0;e["Stone Serif"]=!0;e.Sylfaen=!0;e.Times=!0;e.Trajan=!0;e["Trinité"]=!0;e["Trump Mediaeval"]=!0;e.Utopia=!0;e["Vale Type"]=!0;e["Bitstream Vera"]=!0;e["Vera Serif"]=!0;e.Versailles=!0;e.Wanted=!0;e.Weiss=!0;e["Wide Latin"]=!0;e.Windsor=!0;e.XITS=!0})),qi=getLookupTableFactory((function(e){e.Dingbats=!0;e.Symbol=!0;e.ZapfDingbats=!0;e.Wingdings=!0;e["Wingdings-Bold"]=!0;e["Wingdings-Regular"]=!0})),Oi=getLookupTableFactory((function(e){e[2]=10;e[3]=32;e[4]=33;e[5]=34;e[6]=35;e[7]=36;e[8]=37;e[9]=38;e[10]=39;e[11]=40;e[12]=41;e[13]=42;e[14]=43;e[15]=44;e[16]=45;e[17]=46;e[18]=47;e[19]=48;e[20]=49;e[21]=50;e[22]=51;e[23]=52;e[24]=53;e[25]=54;e[26]=55;e[27]=56;e[28]=57;e[29]=58;e[30]=894;e[31]=60;e[32]=61;e[33]=62;e[34]=63;e[35]=64;e[36]=65;e[37]=66;e[38]=67;e[39]=68;e[40]=69;e[41]=70;e[42]=71;e[43]=72;e[44]=73;e[45]=74;e[46]=75;e[47]=76;e[48]=77;e[49]=78;e[50]=79;e[51]=80;e[52]=81;e[53]=82;e[54]=83;e[55]=84;e[56]=85;e[57]=86;e[58]=87;e[59]=88;e[60]=89;e[61]=90;e[62]=91;e[63]=92;e[64]=93;e[65]=94;e[66]=95;e[67]=96;e[68]=97;e[69]=98;e[70]=99;e[71]=100;e[72]=101;e[73]=102;e[74]=103;e[75]=104;e[76]=105;e[77]=106;e[78]=107;e[79]=108;e[80]=109;e[81]=110;e[82]=111;e[83]=112;e[84]=113;e[85]=114;e[86]=115;e[87]=116;e[88]=117;e[89]=118;e[90]=119;e[91]=120;e[92]=121;e[93]=122;e[94]=123;e[95]=124;e[96]=125;e[97]=126;e[98]=196;e[99]=197;e[100]=199;e[101]=201;e[102]=209;e[103]=214;e[104]=220;e[105]=225;e[106]=224;e[107]=226;e[108]=228;e[109]=227;e[110]=229;e[111]=231;e[112]=233;e[113]=232;e[114]=234;e[115]=235;e[116]=237;e[117]=236;e[118]=238;e[119]=239;e[120]=241;e[121]=243;e[122]=242;e[123]=244;e[124]=246;e[125]=245;e[126]=250;e[127]=249;e[128]=251;e[129]=252;e[130]=8224;e[131]=176;e[132]=162;e[133]=163;e[134]=167;e[135]=8226;e[136]=182;e[137]=223;e[138]=174;e[139]=169;e[140]=8482;e[141]=180;e[142]=168;e[143]=8800;e[144]=198;e[145]=216;e[146]=8734;e[147]=177;e[148]=8804;e[149]=8805;e[150]=165;e[151]=181;e[152]=8706;e[153]=8721;e[154]=8719;e[156]=8747;e[157]=170;e[158]=186;e[159]=8486;e[160]=230;e[161]=248;e[162]=191;e[163]=161;e[164]=172;e[165]=8730;e[166]=402;e[167]=8776;e[168]=8710;e[169]=171;e[170]=187;e[171]=8230;e[179]=8220;e[180]=8221;e[181]=8216;e[182]=8217;e[200]=193;e[203]=205;e[207]=211;e[210]=218;e[223]=711;e[224]=321;e[225]=322;e[226]=352;e[227]=353;e[228]=381;e[229]=382;e[233]=221;e[234]=253;e[252]=263;e[253]=268;e[254]=269;e[258]=258;e[260]=260;e[261]=261;e[265]=280;e[266]=281;e[267]=282;e[268]=283;e[269]=313;e[275]=323;e[276]=324;e[278]=328;e[283]=344;e[284]=345;e[285]=346;e[286]=347;e[292]=367;e[295]=377;e[296]=378;e[298]=380;e[305]=963;e[306]=964;e[307]=966;e[308]=8215;e[309]=8252;e[310]=8319;e[311]=8359;e[312]=8592;e[313]=8593;e[337]=9552;e[493]=1039;e[494]=1040;e[672]=1488;e[673]=1489;e[674]=1490;e[675]=1491;e[676]=1492;e[677]=1493;e[678]=1494;e[679]=1495;e[680]=1496;e[681]=1497;e[682]=1498;e[683]=1499;e[684]=1500;e[685]=1501;e[686]=1502;e[687]=1503;e[688]=1504;e[689]=1505;e[690]=1506;e[691]=1507;e[692]=1508;e[693]=1509;e[694]=1510;e[695]=1511;e[696]=1512;e[697]=1513;e[698]=1514;e[705]=1524;e[706]=8362;e[710]=64288;e[711]=64298;e[759]=1617;e[761]=1776;e[763]=1778;e[775]=1652;e[777]=1764;e[778]=1780;e[779]=1781;e[780]=1782;e[782]=771;e[783]=64726;e[786]=8363;e[788]=8532;e[790]=768;e[791]=769;e[792]=768;e[795]=803;e[797]=64336;e[798]=64337;e[799]=64342;e[800]=64343;e[801]=64344;e[802]=64345;e[803]=64362;e[804]=64363;e[805]=64364;e[2424]=7821;e[2425]=7822;e[2426]=7823;e[2427]=7824;e[2428]=7825;e[2429]=7826;e[2430]=7827;e[2433]=7682;e[2678]=8045;e[2679]=8046;e[2830]=1552;e[2838]=686;e[2840]=751;e[2842]=753;e[2843]=754;e[2844]=755;e[2846]=757;e[2856]=767;e[2857]=848;e[2858]=849;e[2862]=853;e[2863]=854;e[2864]=855;e[2865]=861;e[2866]=862;e[2906]=7460;e[2908]=7462;e[2909]=7463;e[2910]=7464;e[2912]=7466;e[2913]=7467;e[2914]=7468;e[2916]=7470;e[2917]=7471;e[2918]=7472;e[2920]=7474;e[2921]=7475;e[2922]=7476;e[2924]=7478;e[2925]=7479;e[2926]=7480;e[2928]=7482;e[2929]=7483;e[2930]=7484;e[2932]=7486;e[2933]=7487;e[2934]=7488;e[2936]=7490;e[2937]=7491;e[2938]=7492;e[2940]=7494;e[2941]=7495;e[2942]=7496;e[2944]=7498;e[2946]=7500;e[2948]=7502;e[2950]=7504;e[2951]=7505;e[2952]=7506;e[2954]=7508;e[2955]=7509;e[2956]=7510;e[2958]=7512;e[2959]=7513;e[2960]=7514;e[2962]=7516;e[2963]=7517;e[2964]=7518;e[2966]=7520;e[2967]=7521;e[2968]=7522;e[2970]=7524;e[2971]=7525;e[2972]=7526;e[2974]=7528;e[2975]=7529;e[2976]=7530;e[2978]=1537;e[2979]=1538;e[2980]=1539;e[2982]=1549;e[2983]=1551;e[2984]=1552;e[2986]=1554;e[2987]=1555;e[2988]=1556;e[2990]=1623;e[2991]=1624;e[2995]=1775;e[2999]=1791;e[3002]=64290;e[3003]=64291;e[3004]=64292;e[3006]=64294;e[3007]=64295;e[3008]=64296;e[3011]=1900;e[3014]=8223;e[3015]=8244;e[3017]=7532;e[3018]=7533;e[3019]=7534;e[3075]=7590;e[3076]=7591;e[3079]=7594;e[3080]=7595;e[3083]=7598;e[3084]=7599;e[3087]=7602;e[3088]=7603;e[3091]=7606;e[3092]=7607;e[3095]=7610;e[3096]=7611;e[3099]=7614;e[3100]=7615;e[3103]=7618;e[3104]=7619;e[3107]=8337;e[3108]=8338;e[3116]=1884;e[3119]=1885;e[3120]=1885;e[3123]=1886;e[3124]=1886;e[3127]=1887;e[3128]=1887;e[3131]=1888;e[3132]=1888;e[3135]=1889;e[3136]=1889;e[3139]=1890;e[3140]=1890;e[3143]=1891;e[3144]=1891;e[3147]=1892;e[3148]=1892;e[3153]=580;e[3154]=581;e[3157]=584;e[3158]=585;e[3161]=588;e[3162]=589;e[3165]=891;e[3166]=892;e[3169]=1274;e[3170]=1275;e[3173]=1278;e[3174]=1279;e[3181]=7622;e[3182]=7623;e[3282]=11799;e[3316]=578;e[3379]=42785;e[3393]=1159;e[3416]=8377})),Pi=getLookupTableFactory((function(e){e[227]=322;e[264]=261;e[291]=346})),Wi=getLookupTableFactory((function(e){e[1]=32;e[4]=65;e[5]=192;e[6]=193;e[9]=196;e[17]=66;e[18]=67;e[21]=268;e[24]=68;e[28]=69;e[29]=200;e[30]=201;e[32]=282;e[38]=70;e[39]=71;e[44]=72;e[47]=73;e[48]=204;e[49]=205;e[58]=74;e[60]=75;e[62]=76;e[68]=77;e[69]=78;e[75]=79;e[76]=210;e[80]=214;e[87]=80;e[89]=81;e[90]=82;e[92]=344;e[94]=83;e[97]=352;e[100]=84;e[104]=85;e[109]=220;e[115]=86;e[116]=87;e[121]=88;e[122]=89;e[124]=221;e[127]=90;e[129]=381;e[258]=97;e[259]=224;e[260]=225;e[263]=228;e[268]=261;e[271]=98;e[272]=99;e[273]=263;e[275]=269;e[282]=100;e[286]=101;e[287]=232;e[288]=233;e[290]=283;e[295]=281;e[296]=102;e[336]=103;e[346]=104;e[349]=105;e[350]=236;e[351]=237;e[361]=106;e[364]=107;e[367]=108;e[371]=322;e[373]=109;e[374]=110;e[381]=111;e[382]=242;e[383]=243;e[386]=246;e[393]=112;e[395]=113;e[396]=114;e[398]=345;e[400]=115;e[401]=347;e[403]=353;e[410]=116;e[437]=117;e[442]=252;e[448]=118;e[449]=119;e[454]=120;e[455]=121;e[457]=253;e[460]=122;e[462]=382;e[463]=380;e[853]=44;e[855]=58;e[856]=46;e[876]=47;e[878]=45;e[882]=45;e[894]=40;e[895]=41;e[896]=91;e[897]=93;e[923]=64;e[1004]=48;e[1005]=49;e[1006]=50;e[1007]=51;e[1008]=52;e[1009]=53;e[1010]=54;e[1011]=55;e[1012]=56;e[1013]=57;e[1081]=37;e[1085]=43;e[1086]=45}));function getStandardFontName(e){const t=normalizeFontName(e);return Yi()[t]}function isKnownFontName(e){const t=normalizeFontName(e);return!!(Yi()[t]||Ki()[t]||Ti()[t]||qi()[t])}class ToUnicodeMap{constructor(e=[]){this._map=e}get length(){return this._map.length}forEach(e){for(const t in this._map)e(t,this._map[t].codePointAt(0))}has(e){return void 0!==this._map[e]}get(e){return this._map[e]}charCodeOf(e){const t=this._map;if(t.length<=65536)return t.indexOf(e);for(const i in t)if(t[i]===e)return 0|i;return-1}amend(e){for(const t in e)this._map[t]=e[t]}}class IdentityToUnicodeMap{constructor(e,t){this.firstChar=e;this.lastChar=t}get length(){return this.lastChar+1-this.firstChar}forEach(e){for(let t=this.firstChar,i=this.lastChar;t<=i;t++)e(t,t)}has(e){return this.firstChar<=e&&e<=this.lastChar}get(e){if(this.firstChar<=e&&e<=this.lastChar)return String.fromCharCode(e)}charCodeOf(e){return Number.isInteger(e)&&e>=this.firstChar&&e<=this.lastChar?e:-1}amend(e){unreachable("Should not call amend()")}}class CFFFont{constructor(e,t){this.properties=t;const i=new CFFParser(e,t,Ri);this.cff=i.parse();this.cff.duplicateFirstGlyph();const a=new CFFCompiler(this.cff);this.seacs=this.cff.seacs;try{this.data=a.compile()}catch{warn("Failed to compile font "+t.loadedName);this.data=e}this._createBuiltInEncoding()}get numGlyphs(){return this.cff.charStrings.count}getCharset(){return this.cff.charset.charset}getGlyphMapping(){const e=this.cff,t=this.properties,{cidToGidMap:i,cMap:a}=t,s=e.charset.charset;let r,n;if(t.composite){let t,g;if(i?.length>0){t=Object.create(null);for(let e=0,a=i.length;e=0){const a=i[t];a&&(s[e]=a)}}s.length>0&&(this.properties.builtInEncoding=s)}}function getUint32(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}function getUint16(e,t){return e[t]<<8|e[t+1]}function getInt16(e,t){return(e[t]<<24|e[t+1]<<16)>>16}function getInt8(e,t){return e[t]<<24>>24}function getFloat214(e,t){return getInt16(e,t)/16384}function getSubroutineBias(e){const t=e.length;let i=32768;t<1240?i=107:t<33900&&(i=1131);return i}function parseCmap(e,t,i){const a=1===getUint16(e,t+2)?getUint32(e,t+8):getUint32(e,t+16),s=getUint16(e,t+a);let r,n,g;if(4===s){getUint16(e,t+a+2);const i=getUint16(e,t+a+6)>>1;n=t+a+14;r=[];for(g=0;g>1;i0;)C.push({flags:r})}for(i=0;i>1;p=!0;break;case 4:n+=s.pop();moveTo(r,n);p=!0;break;case 5:for(;s.length>0;){r+=s.shift();n+=s.shift();lineTo(r,n)}break;case 6:for(;s.length>0;){r+=s.shift();lineTo(r,n);if(0===s.length)break;n+=s.shift();lineTo(r,n)}break;case 7:for(;s.length>0;){n+=s.shift();lineTo(r,n);if(0===s.length)break;r+=s.shift();lineTo(r,n)}break;case 8:for(;s.length>0;){c=r+s.shift();h=n+s.shift();C=c+s.shift();l=h+s.shift();r=C+s.shift();n=l+s.shift();bezierCurveTo(c,h,C,l,r,n)}break;case 10:d=s.pop();f=null;if(i.isCFFCIDFont){const e=i.fdSelect.getFDIndex(a);if(e>=0&&eMath.abs(n-t)?r+=s.shift():n+=s.shift();bezierCurveTo(c,h,C,l,r,n);break;default:throw new FormatError(`unknown operator: 12 ${m}`)}break;case 14:if(s.length>=4){const e=s.pop(),a=s.pop();n=s.pop();r=s.pop();t.save();t.translate(r,n);let g=lookupCmap(i.cmap,String.fromCharCode(i.glyphNameMap[hi[e]]));compileCharString(i.glyphs[g.glyphId],t,i,g.glyphId);t.restore();g=lookupCmap(i.cmap,String.fromCharCode(i.glyphNameMap[hi[a]]));compileCharString(i.glyphs[g.glyphId],t,i,g.glyphId)}return;case 19:case 20:g+=s.length>>1;o+=g+7>>3;p=!0;break;case 21:n+=s.pop();r+=s.pop();moveTo(r,n);p=!0;break;case 22:r+=s.pop();moveTo(r,n);p=!0;break;case 24:for(;s.length>2;){c=r+s.shift();h=n+s.shift();C=c+s.shift();l=h+s.shift();r=C+s.shift();n=l+s.shift();bezierCurveTo(c,h,C,l,r,n)}r+=s.shift();n+=s.shift();lineTo(r,n);break;case 25:for(;s.length>6;){r+=s.shift();n+=s.shift();lineTo(r,n)}c=r+s.shift();h=n+s.shift();C=c+s.shift();l=h+s.shift();r=C+s.shift();n=l+s.shift();bezierCurveTo(c,h,C,l,r,n);break;case 26:s.length%2&&(r+=s.shift());for(;s.length>0;){c=r;h=n+s.shift();C=c+s.shift();l=h+s.shift();r=C;n=l+s.shift();bezierCurveTo(c,h,C,l,r,n)}break;case 27:s.length%2&&(n+=s.shift());for(;s.length>0;){c=r+s.shift();h=n;C=c+s.shift();l=h+s.shift();r=C+s.shift();n=l;bezierCurveTo(c,h,C,l,r,n)}break;case 28:s.push((e[o]<<24|e[o+1]<<16)>>16);o+=2;break;case 29:d=s.pop()+i.gsubrsBias;f=i.gsubrs[d];f&&parse(f);break;case 30:for(;s.length>0;){c=r;h=n+s.shift();C=c+s.shift();l=h+s.shift();r=C+s.shift();n=l+(1===s.length?s.shift():0);bezierCurveTo(c,h,C,l,r,n);if(0===s.length)break;c=r+s.shift();h=n;C=c+s.shift();l=h+s.shift();n=l+s.shift();r=C+(1===s.length?s.shift():0);bezierCurveTo(c,h,C,l,r,n)}break;case 31:for(;s.length>0;){c=r+s.shift();h=n;C=c+s.shift();l=h+s.shift();n=l+s.shift();r=C+(1===s.length?s.shift():0);bezierCurveTo(c,h,C,l,r,n);if(0===s.length)break;c=r;h=n+s.shift();C=c+s.shift();l=h+s.shift();r=C+s.shift();n=l+(1===s.length?s.shift():0);bezierCurveTo(c,h,C,l,r,n)}break;default:if(m<32)throw new FormatError(`unknown operator: ${m}`);if(m<247)s.push(m-139);else if(m<251)s.push(256*(m-247)+e[o++]+108);else if(m<255)s.push(256*-(m-251)-e[o++]-108);else{s.push((e[o]<<24|e[o+1]<<16|e[o+2]<<8|e[o+3])/65536);o+=4}}p&&(s.length=0)}}(e)}class Commands{cmds=[];transformStack=[];currentTransform=[1,0,0,1,0,0];add(e,t){if(t){const[i,a,s,r,n,g]=this.currentTransform;for(let e=0,o=t.length;e=0&&e2*getUint16(e,t)}const r=[];let n=s(t,0);for(let i=a;ie+(t.getSize()+3&-4)),0)}write(){const e=this.getSize(),t=new DataView(new ArrayBuffer(e)),i=e>131070,a=i?4:2,s=new DataView(new ArrayBuffer((this.glyphs.length+1)*a));i?s.setUint32(0,0):s.setUint16(0,0);let r=0,n=0;for(const e of this.glyphs){r+=e.write(r,t);r=r+3&-4;n+=a;i?s.setUint32(n,r):s.setUint16(n,r>>1)}return{isLocationLong:i,loca:new Uint8Array(s.buffer),glyf:new Uint8Array(t.buffer)}}scale(e){for(let t=0,i=this.glyphs.length;te+t.getSize()),0);return this.header.getSize()+e}write(e,t){if(!this.header)return 0;const i=e;e+=this.header.write(e,t);if(this.simple)e+=this.simple.write(e,t);else for(const i of this.composites)e+=i.write(e,t);return e-i}scale(e){if(!this.header)return;const t=(this.header.xMin+this.header.xMax)/2;this.header.scale(t,e);if(this.simple)this.simple.scale(t,e);else for(const i of this.composites)i.scale(t,e)}}class GlyphHeader{constructor({numberOfContours:e,xMin:t,yMin:i,xMax:a,yMax:s}){this.numberOfContours=e;this.xMin=t;this.yMin=i;this.xMax=a;this.yMax=s}static parse(e,t){return[10,new GlyphHeader({numberOfContours:t.getInt16(e),xMin:t.getInt16(e+2),yMin:t.getInt16(e+4),xMax:t.getInt16(e+6),yMax:t.getInt16(e+8)})]}getSize(){return 10}write(e,t){t.setInt16(e,this.numberOfContours);t.setInt16(e+2,this.xMin);t.setInt16(e+4,this.yMin);t.setInt16(e+6,this.xMax);t.setInt16(e+8,this.yMax);return 10}scale(e,t){this.xMin=Math.round(e+(this.xMin-e)*t);this.xMax=Math.round(e+(this.xMax-e)*t)}}class Contour{constructor({flags:e,xCoordinates:t,yCoordinates:i}){this.xCoordinates=t;this.yCoordinates=i;this.flags=e}}class SimpleGlyph{constructor({contours:e,instructions:t}){this.contours=e;this.instructions=t}static parse(e,t,i){const a=[];for(let s=0;s255?e+=2:g>0&&(e+=1);t=r;g=Math.abs(n-i);g>255?e+=2:g>0&&(e+=1);i=n}}return e}write(e,t){const i=e,a=[],s=[],r=[];let n=0,g=0;for(const i of this.contours){for(let e=0,t=i.xCoordinates.length;e=0?18:2;a.push(e)}else a.push(c)}n=o;const C=i.yCoordinates[e];c=C-g;if(0===c){t|=32;s.push(0)}else{const e=Math.abs(c);if(e<=255){t|=c>=0?36:4;s.push(e)}else s.push(c)}g=C;r.push(t)}t.setUint16(e,a.length-1);e+=2}t.setUint16(e,this.instructions.length);e+=2;if(this.instructions.length){new Uint8Array(t.buffer,0,t.buffer.byteLength).set(this.instructions,e);e+=this.instructions.length}for(const i of r)t.setUint8(e++,i);for(let i=0,s=a.length;i=-128&&this.argument1<=127&&this.argument2>=-128&&this.argument2<=127||(e+=2):this.argument1>=0&&this.argument1<=255&&this.argument2>=0&&this.argument2<=255||(e+=2);return e}write(e,t){const i=e;2&this.flags?this.argument1>=-128&&this.argument1<=127&&this.argument2>=-128&&this.argument2<=127||(this.flags|=1):this.argument1>=0&&this.argument1<=255&&this.argument2>=0&&this.argument2<=255||(this.flags|=1);t.setUint16(e,this.flags);t.setUint16(e+2,this.glyphIndex);e+=4;if(1&this.flags){if(2&this.flags){t.setInt16(e,this.argument1);t.setInt16(e+2,this.argument2)}else{t.setUint16(e,this.argument1);t.setUint16(e+2,this.argument2)}e+=4}else{t.setUint8(e,this.argument1);t.setUint8(e+1,this.argument2);e+=2}if(256&this.flags){t.setUint16(e,this.instructions.length);e+=2;if(this.instructions.length){new Uint8Array(t.buffer,0,t.buffer.byteLength).set(this.instructions,e);e+=this.instructions.length}}return e-i}scale(e,t){}}function writeInt16(e,t,i){e[t]=i>>8&255;e[t+1]=255&i}function writeInt32(e,t,i){e[t]=i>>24&255;e[t+1]=i>>16&255;e[t+2]=i>>8&255;e[t+3]=255&i}function writeData(e,t,i){if(i instanceof Uint8Array)e.set(i,t);else if("string"==typeof i)for(let a=0,s=i.length;ai;){i<<=1;a++}const s=i*t;return{range:s,entry:a,rangeShift:t*e-s}}toArray(){let e=this.sfnt;const t=this.tables,i=Object.keys(t);i.sort();const a=i.length;let s,r,n,g,o,c=12+16*a;const C=[c];for(s=0;s>>0;C.push(c)}const h=new Uint8Array(c);for(s=0;s>>0}writeInt32(h,c+4,e);writeInt32(h,c+8,C[s]);writeInt32(h,c+12,t[o].length);c+=16}return h}addTable(e,t){if(e in this.tables)throw new Error("Table "+e+" already exists");this.tables[e]=t}}const Zi=[4],Vi=[5],zi=[6],_i=[7],$i=[8],Aa=[12,35],ea=[14],ta=[21],ia=[22],aa=[30],sa=[31];class Type1CharString{constructor(){this.width=0;this.lsb=0;this.flexing=!1;this.output=[];this.stack=[]}convert(e,t,i){const a=e.length;let s,r,n,g=!1;for(let o=0;oa)return!0;const s=a-e;for(let e=s;e>8&255,255&t);else{t=65536*t|0;this.output.push(255,t>>24&255,t>>16&255,t>>8&255,255&t)}}this.output.push(...t);i?this.stack.splice(s,e):this.stack.length=0;return!1}}function isHexDigit(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function decrypt(e,t,i){if(i>=e.length)return new Uint8Array(0);let a,s,r=0|t;for(a=0;a>8;r=52845*(t+r)+22719&65535}return g}function isSpecial(e){return 47===e||91===e||93===e||123===e||125===e||40===e||41===e}class Type1Parser{constructor(e,t,i){if(t){const t=e.getBytes(),i=!((isHexDigit(t[0])||isWhiteSpace(t[0]))&&isHexDigit(t[1])&&isHexDigit(t[2])&&isHexDigit(t[3])&&isHexDigit(t[4])&&isHexDigit(t[5])&&isHexDigit(t[6])&&isHexDigit(t[7]));e=new Stream(i?decrypt(t,55665,4):function decryptAscii(e,t,i){let a=0|t;const s=e.length,r=new Uint8Array(s>>>1);let n,g;for(n=0,g=0;n>8;a=52845*(e+a)+22719&65535}}return r.slice(i,g)}(t,55665,4))}this.seacAnalysisEnabled=!!i;this.stream=e;this.nextChar()}readNumberArray(){this.getToken();const e=[];for(;;){const t=this.getToken();if(null===t||"]"===t||"}"===t)break;e.push(parseFloat(t||0))}return e}readNumber(){const e=this.getToken();return parseFloat(e||0)}readInt(){const e=this.getToken();return 0|parseInt(e||0,10)}readBoolean(){return"true"===this.getToken()?1:0}nextChar(){return this.currentChar=this.stream.getByte()}prevChar(){this.stream.skip(-2);return this.currentChar=this.stream.getByte()}getToken(){let e=!1,t=this.currentChar;for(;;){if(-1===t)return null;if(e)10!==t&&13!==t||(e=!1);else if(37===t)e=!0;else if(!isWhiteSpace(t))break;t=this.nextChar()}if(isSpecial(t)){this.nextChar();return String.fromCharCode(t)}let i="";do{i+=String.fromCharCode(t);t=this.nextChar()}while(t>=0&&!isWhiteSpace(t)&&!isSpecial(t));return i}readCharStrings(e,t){return-1===t?e:decrypt(e,4330,t)}extractFontProgram(e){const t=this.stream,i=[],a=[],s=Object.create(null);s.lenIV=4;const r={subrs:[],charstrings:[],properties:{privateData:s}};let n,g,o,c;for(;null!==(n=this.getToken());)if("/"===n){n=this.getToken();switch(n){case"CharStrings":this.getToken();this.getToken();this.getToken();this.getToken();for(;;){n=this.getToken();if(null===n||"end"===n)break;if("/"!==n)continue;const e=this.getToken();g=this.readInt();this.getToken();o=g>0?t.getBytes(g):new Uint8Array(0);c=r.properties.privateData.lenIV;const i=this.readCharStrings(o,c);this.nextChar();n=this.getToken();"noaccess"===n?this.getToken():"/"===n&&this.prevChar();a.push({glyph:e,encoded:i})}break;case"Subrs":this.readInt();this.getToken();for(;"dup"===this.getToken();){const e=this.readInt();g=this.readInt();this.getToken();o=g>0?t.getBytes(g):new Uint8Array(0);c=r.properties.privateData.lenIV;const a=this.readCharStrings(o,c);this.nextChar();n=this.getToken();"noaccess"===n&&this.getToken();i[e]=a}break;case"BlueValues":case"OtherBlues":case"FamilyBlues":case"FamilyOtherBlues":const e=this.readNumberArray();e.length>0&&e.length,0;break;case"StemSnapH":case"StemSnapV":r.properties.privateData[n]=this.readNumberArray();break;case"StdHW":case"StdVW":r.properties.privateData[n]=this.readNumberArray()[0];break;case"BlueShift":case"lenIV":case"BlueFuzz":case"BlueScale":case"LanguageGroup":r.properties.privateData[n]=this.readNumber();break;case"ExpansionFactor":r.properties.privateData[n]=this.readNumber()||.06;break;case"ForceBold":r.properties.privateData[n]=this.readBoolean()}}for(const{encoded:t,glyph:s}of a){const a=new Type1CharString,n=a.convert(t,i,this.seacAnalysisEnabled);let g=a.output;n&&(g=[14]);const o={glyphName:s,charstring:g,width:a.width,lsb:a.lsb,seac:a.seac};".notdef"===s?r.charstrings.unshift(o):r.charstrings.push(o);if(e.builtInEncoding){const t=e.builtInEncoding.indexOf(s);t>-1&&void 0===e.widths[t]&&t>=e.firstChar&&t<=e.lastChar&&(e.widths[t]=a.width)}}return r}extractFontHeader(e){let t;for(;null!==(t=this.getToken());)if("/"===t){t=this.getToken();switch(t){case"FontMatrix":const i=this.readNumberArray();e.fontMatrix=i;break;case"Encoding":const a=this.getToken();let s;if(/^\d+$/.test(a)){s=[];const e=0|parseInt(a,10);this.getToken();for(let i=0;i=s){n+=i;for(;n=0&&(a[e]=s)}}return type1FontGlyphMapping(e,a,i)}hasGlyphId(e){if(e<0||e>=this.numGlyphs)return!1;if(0===e)return!0;return this.charstrings[e-1].charstring.length>0}getSeacs(e){const t=[];for(let i=0,a=e.length;i0;e--)t[e]-=t[e-1];Q.setByName(e,t)}r.topDict.privateDict=Q;const u=new CFFIndex;for(C=0,h=a.length;C0&&e.toUnicode.amend(t)}class fonts_Glyph{constructor(e,t,i,a,s,r,n,g,o){this.originalCharCode=e;this.fontChar=t;this.unicode=i;this.accent=a;this.width=s;this.vmetric=r;this.operatorListId=n;this.isSpace=g;this.isInFont=o}get category(){return shadow(this,"category",function getCharUnicodeCategory(e){const t=ki.get(e);if(t)return t;const i=e.match(Si),a={isWhitespace:!!i?.[1],isZeroWidthDiacritic:!!i?.[2],isInvisibleFormatMark:!!i?.[3]};ki.set(e,a);return a}(this.unicode),!0)}}function int16(e,t){return(e<<8)+t}function writeSignedInt16(e,t,i){e[t+1]=i;e[t]=i>>>8}function signedInt16(e,t){const i=(e<<8)+t;return 32768&i?i-65536:i}function string16(e){return String.fromCharCode(e>>8&255,255&e)}function safeString16(e){e>32767?e=32767:e<-32768&&(e=-32768);return String.fromCharCode(e>>8&255,255&e)}function isTrueTypeCollectionFile(e){return"ttcf"===bytesToString(e.peekBytes(4))}function getFontFileType(e,{type:t,subtype:i,composite:a}){let s,r;if(function isTrueTypeFile(e){const t=e.peekBytes(4);return 65536===readUint32(t,0)||"true"===bytesToString(t)}(e)||isTrueTypeCollectionFile(e))s=a?"CIDFontType2":"TrueType";else if(function isOpenTypeFile(e){return"OTTO"===bytesToString(e.peekBytes(4))}(e))s=a?"CIDFontType2":"OpenType";else if(function isType1File(e){const t=e.peekBytes(2);return 37===t[0]&&33===t[1]||128===t[0]&&1===t[1]}(e))s=a?"CIDFontType0":"MMType1"===t?"MMType1":"Type1";else if(function isCFFFile(e){const t=e.peekBytes(4);return t[0]>=1&&t[3]>=1&&t[3]<=4}(e))if(a){s="CIDFontType0";r="CIDFontType0C"}else{s="MMType1"===t?"MMType1":"Type1";r="Type1C"}else{warn("getFontFileType: Unable to detect correct font file Type/Subtype.");s=t;r=i}return[s,r]}function applyStandardFontGlyphMap(e,t){for(const i in t)e[+i]=t[i]}function buildToFontChar(e,t,i){const a=[];let s;for(let i=0,r=e.length;iC){o++;if(o>=ra.length){warn("Ran out of space in font private use area.");break}c=ra[o][0];C=ra[o][1]}const E=c++;0===Q&&(Q=i);let u=a.get(l);"string"==typeof u&&(u=u.codePointAt(0));if(u&&!(h=u,ra[0][0]<=h&&h<=ra[0][1]||ra[1][0]<=h&&h<=ra[1][1])&&!g.has(Q)){r.set(u,Q);g.add(Q)}s[E]=Q;n[l]=E}var h;return{toFontChar:n,charCodeToGlyphId:s,toUnicodeExtraMap:r,nextAvailableFontCharCode:c}}function createCmapTable(e,t,i){const a=function getRanges(e,t,i){const a=[];for(const t in e)e[t]>=i||a.push({fontCharCode:0|t,glyphId:e[t]});if(t)for(const[e,s]of t)s>=i||a.push({fontCharCode:e,glyphId:s});0===a.length&&a.push({fontCharCode:0,glyphId:0});a.sort((function fontGetRangesSort(e,t){return e.fontCharCode-t.fontCharCode}));const s=[],r=a.length;for(let e=0;e65535?2:1;let r,n,g,o,c="\0\0"+string16(s)+"\0\0"+string32(4+8*s);for(r=a.length-1;r>=0&&!(a[r][0]<=65535);--r);const C=r+1;a[r][0]<65535&&65535===a[r][1]&&(a[r][1]=65534);const h=a[r][1]<65535?1:0,l=C+h,Q=OpenTypeFileBuilder.getSearchParams(l,2);let E,u,d,f,p="",m="",y="",w="",D="",b=0;for(r=0,n=C;r0){m+="ÿÿ";p+="ÿÿ";y+="\0";w+="\0\0"}const F="\0\0"+string16(2*l)+string16(Q.range)+string16(Q.entry)+string16(Q.rangeShift)+m+"\0\0"+p+y+w+D;let S="",k="";if(s>1){c+="\0\0\n"+string32(4+8*s+4+F.length);S="";for(r=0,n=a.length;re||!g)&&(g=e);o 123 are reserved for internal usage");n|=1<65535&&(o=65535)}else{g=0;o=255}const C=e.bbox||[0,0,0,0],h=i.unitsPerEm||(e.fontMatrix?1/Math.max(...e.fontMatrix.slice(0,4).map(Math.abs)):1e3),l=e.ascentScaled?1:h/na,Q=i.ascent||Math.round(l*(e.ascent||C[3]));let E=i.descent||Math.round(l*(e.descent||C[1]));E>0&&e.descent>0&&C[1]<0&&(E=-E);const u=i.yMax||Q,d=-i.yMin||-E;return"\0$ô\0\0\0Š»\0\0\0ŒŠ»\0\0ß\x001\0\0\0\0"+String.fromCharCode(e.fixedPitch?9:0)+"\0\0\0\0\0\0"+string32(a)+string32(s)+string32(r)+string32(n)+"*21*"+string16(e.italicAngle?1:0)+string16(g||e.firstChar)+string16(o||e.lastChar)+string16(Q)+string16(E)+"\0d"+string16(u)+string16(d)+"\0\0\0\0\0\0\0\0"+string16(e.xHeight)+string16(e.capHeight)+string16(0)+string16(g||e.firstChar)+"\0"}function createPostTable(e){return"\0\0\0"+string32(Math.floor(65536*e.italicAngle))+"\0\0\0\0"+string32(e.fixedPitch?1:0)+"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"}function createPostscriptName(e){return e.replaceAll(/[^\x21-\x7E]|[[\](){}<>/%]/g,"").slice(0,63)}function createNameTable(e,t){t||(t=[[],[]]);const i=[t[0][0]||"Original licence",t[0][1]||e,t[0][2]||"Unknown",t[0][3]||"uniqueID",t[0][4]||e,t[0][5]||"Version 0.11",t[0][6]||createPostscriptName(e),t[0][7]||"Unknown",t[0][8]||"Unknown",t[0][9]||"Unknown"],a=[];let s,r,n,g,o;for(s=0,r=i.length;s0;if((n||g)&&"CIDFontType2"===i&&this.cidEncoding.startsWith("Identity-")){const i=e.cidToGidMap,a=[];applyStandardFontGlyphMap(a,Oi());/Arial-?Black/i.test(t)?applyStandardFontGlyphMap(a,Pi()):/Calibri/i.test(t)&&applyStandardFontGlyphMap(a,Wi());if(i){for(const e in a){const t=a[e];void 0!==i[t]&&(a[+e]=i[t])}i.length!==this.toUnicode.length&&e.hasIncludedToUnicodeMap&&this.toUnicode instanceof IdentityToUnicodeMap&&this.toUnicode.forEach((function(e,t){const s=a[e];void 0===i[s]&&(a[+e]=t)}))}this.toUnicode instanceof IdentityToUnicodeMap||this.toUnicode.forEach((function(e,t){a[+e]=t}));this.toFontChar=a;this.toUnicode=new ToUnicodeMap(a)}else if(/Symbol/i.test(a))this.toFontChar=buildToFontChar(Bi,wi(),this.differences);else if(/Dingbats/i.test(a))this.toFontChar=buildToFontChar(Qi,Di(),this.differences);else if(n||g){const e=buildToFontChar(this.defaultEncoding,wi(),this.differences);"CIDFontType2"!==i||this.cidEncoding.startsWith("Identity-")||this.toUnicode instanceof IdentityToUnicodeMap||this.toUnicode.forEach((function(t,i){e[+t]=i}));this.toFontChar=e}else{const e=wi(),i=[];this.toUnicode.forEach(((t,a)=>{if(!this.composite){const i=getUnicodeForGlyph(this.differences[t]||this.defaultEncoding[t],e);-1!==i&&(a=i)}i[+t]=a}));this.composite&&this.toUnicode instanceof IdentityToUnicodeMap&&/Tahoma|Verdana/i.test(t)&&applyStandardFontGlyphMap(i,Oi());this.toFontChar=i}amendFallbackToUnicode(e);this.loadedName=a.split("-",1)[0]}checkAndRepair(e,t,i){const a=["OS/2","cmap","head","hhea","hmtx","maxp","name","post","loca","glyf","fpgm","prep","cvt ","CFF "];function readTables(e,t){const i=Object.create(null);i["OS/2"]=null;i.cmap=null;i.head=null;i.hhea=null;i.hmtx=null;i.maxp=null;i.name=null;i.post=null;for(let s=0;s>>0,a=e.getInt32()>>>0,s=e.getInt32()>>>0,r=e.pos;e.pos=e.start||0;e.skip(a);const n=e.getBytes(s);e.pos=r;if("head"===t){n[8]=n[9]=n[10]=n[11]=0;n[17]|=32}return{tag:t,checksum:i,length:s,offset:a,data:n}}function readOpenTypeHeader(e){return{version:e.getString(4),numTables:e.getUint16(),searchRange:e.getUint16(),entrySelector:e.getUint16(),rangeShift:e.getUint16()}}function sanitizeGlyph(e,t,i,a,s,r){const n={length:0,sizeOfInstructions:0};if(t<0||t>=e.length||i>e.length||i-t<=12)return n;const g=e.subarray(t,i),o=signedInt16(g[2],g[3]),c=signedInt16(g[4],g[5]),C=signedInt16(g[6],g[7]),h=signedInt16(g[8],g[9]);if(o>C){writeSignedInt16(g,2,C);writeSignedInt16(g,6,o)}if(c>h){writeSignedInt16(g,4,h);writeSignedInt16(g,8,c)}const l=signedInt16(g[0],g[1]);if(l<0){if(l<-1)return n;a.set(g,s);n.length=g.length;return n}let Q,E=10,u=0;for(Q=0;Qg.length)return n;if(!r&&f>0){a.set(g.subarray(0,d),s);a.set([0,0],s+d);a.set(g.subarray(p,y),s+d+2);y-=f;g.length-y>3&&(y=y+3&-4);n.length=y;return n}if(g.length-y>3){y=y+3&-4;a.set(g.subarray(0,y),s);n.length=y;return n}a.set(g,s);n.length=g.length;return n}function readNameTable(e){const i=(t.start||0)+e.offset;t.pos=i;const a=[[],[]],s=[],r=e.length,n=i+r;if(0!==t.getUint16()||r<6)return[a,s];const g=t.getUint16(),o=t.getUint16();let c,C;for(c=0;cn)continue;t.pos=r;const g=e.name;if(e.encoding){let i="";for(let a=0,s=e.length;a0&&(c+=e-1)}}else{if(d||p){warn("TT: nested FDEFs not allowed");u=!0}d=!0;h=c;n=l.pop();t.functionsDefined[n]={data:o,i:c}}else if(!d&&!p){n=l.at(-1);if(isNaN(n))info("TT: CALL empty stack (or invalid entry).");else{t.functionsUsed[n]=!0;if(n in t.functionsStackDeltas){const e=l.length+t.functionsStackDeltas[n];if(e<0){warn("TT: CALL invalid functions stack delta.");t.hintsValid=!1;return}l.length=e}else if(n in t.functionsDefined&&!E.includes(n)){Q.push({data:o,i:c,stackTop:l.length-1});E.push(n);g=t.functionsDefined[n];if(!g){warn("TT: CALL non-existent function");t.hintsValid=!1;return}o=g.data;c=g.i}}}if(!d&&!p){let t=0;e<=142?t=s[e]:e>=192&&e<=223?t=-1:e>=224&&(t=-2);if(e>=113&&e<=117){a=l.pop();isNaN(a)||(t=2*-a)}for(;t<0&&l.length>0;){l.pop();t++}for(;t>0;){l.push(NaN);t--}}}t.tooComplexToFollowFunctions=u;const m=[o];c>o.length&&m.push(new Uint8Array(c-o.length));if(h>C){warn("TT: complementing a missing function tail");m.push(new Uint8Array([34,45]))}!function foldTTTable(e,t){if(t.length>1){let i,a,s=0;for(i=0,a=t.length;i>>0,r=[];for(let t=0;t>>0);const n={ttcTag:t,majorVersion:i,minorVersion:a,numFonts:s,offsetTable:r};switch(i){case 1:return n;case 2:n.dsigTag=e.getInt32()>>>0;n.dsigLength=e.getInt32()>>>0;n.dsigOffset=e.getInt32()>>>0;return n}throw new FormatError(`Invalid TrueType Collection majorVersion: ${i}.`)}(e),s=t.split("+");let r;for(let n=0;n0||!(i.cMap instanceof IdentityCMap));if("OTTO"===r.version&&!t||!n.head||!n.hhea||!n.maxp||!n.post){o=new Stream(n["CFF "].data);g=new CFFFont(o,i);adjustWidths(i);return this.convert(e,g,i)}delete n.glyf;delete n.loca;delete n.fpgm;delete n.prep;delete n["cvt "];this.isOpenType=!0}if(!n.maxp)throw new FormatError('Required "maxp" table is not found');t.pos=(t.start||0)+n.maxp.offset;let C=t.getInt32();const h=t.getUint16();if(65536!==C&&20480!==C){if(6===n.maxp.length)C=20480;else{if(!(n.maxp.length>=32))throw new FormatError('"maxp" table has a wrong version number');C=65536}!function writeUint32(e,t,i){e[t+3]=255&i;e[t+2]=i>>>8;e[t+1]=i>>>16;e[t]=i>>>24}(n.maxp.data,0,C)}if(i.scaleFactors?.length===h&&c){const{scaleFactors:e}=i,t=int16(n.head.data[50],n.head.data[51]),a=new GlyfTable({glyfTable:n.glyf.data,isGlyphLocationsLong:t,locaTable:n.loca.data,numGlyphs:h});a.scale(e);const{glyf:s,loca:r,isLocationLong:g}=a.write();n.glyf.data=s;n.loca.data=r;if(g!==!!t){n.head.data[50]=0;n.head.data[51]=g?1:0}const o=n.hmtx.data;for(let t=0;t>8&255;o[i+1]=255&a;writeSignedInt16(o,i+2,Math.round(e[t]*signedInt16(o[i+2],o[i+3])))}}let l=h+1,Q=!0;if(l>65535){Q=!1;l=h;warn("Not enough space in glyfs to duplicate first glyph.")}let E=0,u=0;if(C>=65536&&n.maxp.length>=32){t.pos+=8;if(t.getUint16()>2){n.maxp.data[14]=0;n.maxp.data[15]=2}t.pos+=4;E=t.getUint16();t.pos+=4;u=t.getUint16()}n.maxp.data[4]=l>>8;n.maxp.data[5]=255&l;const d=function sanitizeTTPrograms(e,t,i,a){const s={functionsDefined:[],functionsUsed:[],functionsStackDeltas:[],tooComplexToFollowFunctions:!1,hintsValid:!0};e&&sanitizeTTProgram(e,s);t&&sanitizeTTProgram(t,s);e&&function checkInvalidFunctions(e,t){if(!e.tooComplexToFollowFunctions)if(e.functionsDefined.length>t){warn("TT: more functions defined than expected");e.hintsValid=!1}else for(let i=0,a=e.functionsUsed.length;it){warn("TT: invalid function id: "+i);e.hintsValid=!1;return}if(e.functionsUsed[i]&&!e.functionsDefined[i]){warn("TT: undefined function: "+i);e.hintsValid=!1;return}}}(s,a);if(i&&1&i.length){const e=new Uint8Array(i.length+1);e.set(i.data);i.data=e}return s.hintsValid}(n.fpgm,n.prep,n["cvt "],E);if(!d){delete n.fpgm;delete n.prep;delete n["cvt "]}!function sanitizeMetrics(e,t,i,a,s,r){if(!t){i&&(i.data=null);return}e.pos=(e.start||0)+t.offset;e.pos+=4;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;const n=e.getUint16();e.pos+=8;e.pos+=2;let g=e.getUint16();if(0!==n){if(!(2&int16(a.data[44],a.data[45]))){t.data[22]=0;t.data[23]=0}}if(g>s){info(`The numOfMetrics (${g}) should not be greater than the numGlyphs (${s}).`);g=s;t.data[34]=(65280&g)>>8;t.data[35]=255&g}const o=s-g-(i.length-4*g>>1);if(o>0){const e=new Uint8Array(i.length+2*o);e.set(i.data);if(r){e[i.length]=i.data[2];e[i.length+1]=i.data[3]}i.data=e}}(t,n.hhea,n.hmtx,n.head,l,Q);if(!n.head)throw new FormatError('Required "head" table is not found');!function sanitizeHead(e,t,i){const a=e.data,s=function int32(e,t,i,a){return(e<<24)+(t<<16)+(i<<8)+a}(a[0],a[1],a[2],a[3]);if(s>>16!=1){info("Attempting to fix invalid version in head table: "+s);a[0]=0;a[1]=1;a[2]=0;a[3]=0}const r=int16(a[50],a[51]);if(r<0||r>1){info("Attempting to fix invalid indexToLocFormat in head table: "+r);const e=t+1;if(i===e<<1){a[50]=0;a[51]=0}else{if(i!==e<<2)throw new FormatError("Could not fix indexToLocFormat: "+r);a[50]=0;a[51]=1}}}(n.head,h,c?n.loca.length:0);let f=Object.create(null);if(c){const e=int16(n.head.data[50],n.head.data[51]),t=function sanitizeGlyphLocations(e,t,i,a,s,r,n){let g,o,c;if(a){g=4;o=function fontItemDecodeLong(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]};c=function fontItemEncodeLong(e,t,i){e[t]=i>>>24&255;e[t+1]=i>>16&255;e[t+2]=i>>8&255;e[t+3]=255&i}}else{g=2;o=function fontItemDecode(e,t){return e[t]<<9|e[t+1]<<1};c=function fontItemEncode(e,t,i){e[t]=i>>9&255;e[t+1]=i>>1&255}}const C=r?i+1:i,h=g*(1+C),l=new Uint8Array(h);l.set(e.data.subarray(0,h));e.data=l;const Q=t.data,E=Q.length,u=new Uint8Array(E);let d,f;const p=[];for(d=0,f=0;dE&&(e=E);p.push({index:d,offset:e,endOffset:0})}p.sort(((e,t)=>e.offset-t.offset));for(d=0;de.index-t.index));for(d=0;dn&&(n=e.sizeOfInstructions);w+=t;c(l,f,w)}if(0===w){const e=new Uint8Array([0,1,0,0,0,0,0,0,0,0,0,0,0,0,49,0]);for(d=0,f=g;di+w)t.data=u.subarray(0,i+w);else{t.data=new Uint8Array(i+w);t.data.set(u.subarray(0,w))}t.data.set(u.subarray(0,i),w);c(e.data,l.length-g,w+i)}else t.data=u.subarray(0,w);return{missingGlyphs:y,maxSizeOfInstructions:n}}(n.loca,n.glyf,h,e,d,Q,u);f=t.missingGlyphs;if(C>=65536&&n.maxp.length>=32){n.maxp.data[26]=t.maxSizeOfInstructions>>8;n.maxp.data[27]=255&t.maxSizeOfInstructions}}if(!n.hhea)throw new FormatError('Required "hhea" table is not found');if(0===n.hhea.data[10]&&0===n.hhea.data[11]){n.hhea.data[10]=255;n.hhea.data[11]=255}const p={unitsPerEm:int16(n.head.data[18],n.head.data[19]),yMax:signedInt16(n.head.data[42],n.head.data[43]),yMin:signedInt16(n.head.data[38],n.head.data[39]),ascent:signedInt16(n.hhea.data[4],n.hhea.data[5]),descent:signedInt16(n.hhea.data[6],n.hhea.data[7]),lineGap:signedInt16(n.hhea.data[8],n.hhea.data[9])};this.ascent=p.ascent/p.unitsPerEm;this.descent=p.descent/p.unitsPerEm;this.lineGap=p.lineGap/p.unitsPerEm;if(this.cssFontInfo?.lineHeight){this.lineHeight=this.cssFontInfo.metrics.lineHeight;this.lineGap=this.cssFontInfo.metrics.lineGap}else this.lineHeight=this.ascent-this.descent+this.lineGap;n.post&&function readPostScriptTable(e,i,a){const s=(t.start||0)+e.offset;t.pos=s;const r=s+e.length,n=t.getInt32();t.skip(28);let g,o,c=!0;switch(n){case 65536:g=Hi;break;case 131072:const e=t.getUint16();if(e!==a){c=!1;break}const s=[];for(o=0;o=32768){c=!1;break}s.push(e)}if(!c)break;const C=[],h=[];for(;t.pos65535)throw new FormatError("Max size of CID is 65,535");let s=-1;t?s=a:void 0!==e[a]&&(s=e[a]);s>=0&&s>>0;let C=!1;if(g?.platformId!==s||g?.encodingId!==r){if(0!==s||0!==r&&1!==r&&3!==r)if(1===s&&0===r)C=!0;else if(3!==s||1!==r||!a&&g){if(i&&3===s&&0===r){C=!0;let i=!0;if(e>3;e.push(a);i=Math.max(a,i)}const a=[];for(let e=0;e<=i;e++)a.push({firstCode:t.getUint16(),entryCount:t.getUint16(),idDelta:signedInt16(t.getByte(),t.getByte()),idRangePos:t.pos+t.getUint16()});for(let i=0;i<256;i++)if(0===e[i]){t.pos=a[0].idRangePos+2*i;Q=t.getUint16();h.push({charCode:i,glyphId:Q})}else{const s=a[e[i]];for(l=0;l>1;t.skip(6);const i=[];let a;for(a=0;a>1)-(e-a);s.offsetIndex=n;g=Math.max(g,n+s.end-s.start+1)}else s.offsetIndex=-1}const o=[];for(l=0;l>>0;for(l=0;l>>0,i=t.getInt32()>>>0;let a=t.getInt32()>>>0;for(let t=e;t<=i;t++)h.push({charCode:t,glyphId:a++})}}}h.sort((function(e,t){return e.charCode-t.charCode}));for(let e=1;e=61440&&t<=61695&&(t&=255);m[t]=e.glyphId}else for(const e of r)m[e.charCode]=e.glyphId;if(i.glyphNames&&(g.length||this.differences.length))for(let e=0;e<256;++e){if(!o&&void 0!==m[e])continue;const t=this.differences[e]||g[e];if(!t)continue;const a=i.glyphNames.indexOf(t);a>0&&hasGlyph(a)&&(m[e]=a)}}0===m.length&&(m[0]=0);let y=l-1;Q||(y=0);if(!i.cssFontInfo){const e=adjustMapping(m,hasGlyph,y,this.toUnicode);this.toFontChar=e.toFontChar;n.cmap={tag:"cmap",data:createCmapTable(e.charCodeToGlyphId,e.toUnicodeExtraMap,l)};n["OS/2"]&&function validateOS2Table(e,t){t.pos=(t.start||0)+e.offset;const i=t.getUint16();t.skip(60);const a=t.getUint16();if(i<4&&768&a)return!1;if(t.getUint16()>t.getUint16())return!1;t.skip(6);if(0===t.getUint16())return!1;e.data[8]=e.data[9]=0;return!0}(n["OS/2"],t)||(n["OS/2"]={tag:"OS/2",data:createOS2Table(i,e.charCodeToGlyphId,p)})}if(!c)try{o=new Stream(n["CFF "].data);g=new CFFParser(o,i,Ri).parse();g.duplicateFirstGlyph();const e=new CFFCompiler(g);n["CFF "].data=e.compile()}catch{warn("Failed to compile font "+i.loadedName)}if(n.name){const[t,a]=readNameTable(n.name);n.name.data=createNameTable(e,t);this.psName=t[0][6]||null;i.composite||function adjustTrueTypeToUnicode(e,t,i){if(e.isInternalFont)return;if(e.hasIncludedToUnicodeMap)return;if(e.hasEncoding)return;if(e.toUnicode instanceof IdentityToUnicodeMap)return;if(!t)return;if(0===i.length)return;if(e.defaultEncoding===li)return;for(const e of i)if(!isWinNameRecord(e))return;const a=li,s=[],r=wi();for(const e in a){const t=a[e];if(""===t)continue;const i=r[t];void 0!==i&&(s[e]=String.fromCharCode(i))}s.length>0&&e.toUnicode.amend(s)}(i,this.isSymbolicFont,a)}else n.name={tag:"name",data:createNameTable(this.name)};const w=new OpenTypeFileBuilder(r.version);for(const e in n)w.addTable(e,n[e].data);return w.toArray()}convert(e,t,i){i.fixedPitch=!1;i.builtInEncoding&&function adjustType1ToUnicode(e,t){if(e.isInternalFont)return;if(e.hasIncludedToUnicodeMap)return;if(t===e.defaultEncoding)return;if(e.toUnicode instanceof IdentityToUnicodeMap)return;const i=[],a=wi();for(const s in t){if(e.hasEncoding&&(e.baseEncodingName||void 0!==e.differences[s]))continue;const r=getUnicodeForGlyph(t[s],a);-1!==r&&(i[s]=String.fromCharCode(r))}i.length>0&&e.toUnicode.amend(i)}(i,i.builtInEncoding);let s=1;t instanceof CFFFont&&(s=t.numGlyphs-1);const r=t.getGlyphMapping(i);let n=null,g=r,o=null;if(!i.cssFontInfo){n=adjustMapping(r,t.hasGlyphId.bind(t),s,this.toUnicode);this.toFontChar=n.toFontChar;g=n.charCodeToGlyphId;o=n.toUnicodeExtraMap}const c=t.numGlyphs;function getCharCodes(e,t){let i=null;for(const a in e)t===e[a]&&(i||=[]).push(0|a);return i}function createCharCode(e,t){for(const i in e)if(t===e[i])return 0|i;n.charCodeToGlyphId[n.nextAvailableFontCharCode]=t;return n.nextAvailableFontCharCode++}const C=t.seacs;if(n&&C?.length){const e=i.fontMatrix||a,s=t.getCharset(),g=Object.create(null);for(let t in C){t|=0;const i=C[t],a=hi[i[2]],o=hi[i[3]],c=s.indexOf(a),h=s.indexOf(o);if(c<0||h<0)continue;const l={x:i[0]*e[0]+i[1]*e[2]+e[4],y:i[0]*e[1]+i[1]*e[3]+e[5]},Q=getCharCodes(r,t);if(Q)for(const e of Q){const t=n.charCodeToGlyphId,i=createCharCode(t,c),a=createCharCode(t,h);g[e]={baseFontCharCode:i,accentFontCharCode:a,accentOffset:l}}}i.seacMap=g}const h=i.fontMatrix?1/Math.max(...i.fontMatrix.slice(0,4).map(Math.abs)):1e3,l=new OpenTypeFileBuilder("OTTO");l.addTable("CFF ",t.data);l.addTable("OS/2",createOS2Table(i,g));l.addTable("cmap",createCmapTable(g,o,c));l.addTable("head","\0\0\0\0\0\0\0\0\0\0_<õ\0\0"+safeString16(h)+"\0\0\0\0ž\v~'\0\0\0\0ž\v~'\0\0"+safeString16(i.descent)+"ÿ"+safeString16(i.ascent)+string16(i.italicAngle?2:0)+"\0\0\0\0\0\0\0");l.addTable("hhea","\0\0\0"+safeString16(i.ascent)+safeString16(i.descent)+"\0\0ÿÿ\0\0\0\0\0\0"+safeString16(i.capHeight)+safeString16(Math.tan(i.italicAngle)*i.xHeight)+"\0\0\0\0\0\0\0\0\0\0\0\0"+string16(c));l.addTable("hmtx",function fontFieldsHmtx(){const e=t.charstrings,i=t.cff?t.cff.widths:null;let a="\0\0\0\0";for(let t=1,s=c;t=65520&&e<=65535?0:e>=62976&&e<=63743?bi()[e]||e:173===e?45:e}(i)}this.isType3Font&&(s=i);let C=null;if(this.seacMap?.[e]){c=!0;const t=this.seacMap[e];i=t.baseFontCharCode;C={fontChar:String.fromCodePoint(t.accentFontCharCode),offset:t.accentOffset}}let h="";"number"==typeof i&&(i<=1114111?h=String.fromCodePoint(i):warn(`charToGlyph - invalid fontCharCode: ${i}`));if(this.missingFile&&this.vertical&&1===h.length){const e=Ji()[h.charCodeAt(0)];e&&(h=o=String.fromCharCode(e))}r=new fonts_Glyph(e,h,o,C,a,g,s,t,c);return this._glyphCache[e]=r}charsToGlyphs(e){let t=this._charsCache[e];if(t)return t;t=[];if(this.cMap){const i=Object.create(null),a=e.length;let s=0;for(;st.length%2==1,a=this.toUnicode instanceof IdentityToUnicodeMap?e=>this.toUnicode.charCodeOf(e):e=>this.toUnicode.charCodeOf(String.fromCodePoint(e));for(let s=0,r=e.length;s55295&&(r<57344||r>65533)&&s++;if(this.toUnicode){const e=a(r);if(-1!==e){if(hasCurrentBufErrors()){t.push(i.join(""));i.length=0}for(let t=(this.cMap?this.cMap.getCharCodeLength(e):1)-1;t>=0;t--)i.push(String.fromCharCode(e>>8*t&255));continue}}if(!hasCurrentBufErrors()){t.push(i.join(""));i.length=0}i.push(String.fromCodePoint(r))}t.push(i.join(""));return t}}class ErrorFont{constructor(e){this.error=e;this.loadedName="g_font_error";this.missingFile=!0}charsToGlyphs(){return[]}encodeString(e){return[e]}exportData(e=!1){return{error:this.error}}}const Ia=2,ca=3,Ca=4,ha=5,la=6,Ba=7;class Pattern{constructor(){unreachable("Cannot initialize Pattern.")}static parseShading(e,t,i,a,s){const r=e instanceof BaseStream?e.dict:e,n=r.get("ShadingType");try{switch(n){case Ia:case ca:return new RadialAxialShading(r,t,i,a,s);case Ca:case ha:case la:case Ba:return new MeshShading(e,t,i,a,s);default:throw new FormatError("Unsupported ShadingType: "+n)}}catch(e){if(e instanceof MissingDataException)throw e;warn(e);return new DummyShading}}}class BaseShading{static SMALL_NUMBER=1e-6;getIR(){unreachable("Abstract method `getIR` called.")}}class RadialAxialShading extends BaseShading{constructor(e,t,i,a,s){super();this.shadingType=e.get("ShadingType");let r=0;this.shadingType===Ia?r=4:this.shadingType===ca&&(r=6);this.coordsArr=e.getArray("Coords");if(!isNumberArray(this.coordsArr,r))throw new FormatError("RadialAxialShading: Invalid /Coords array.");const n=ColorSpace.parse({cs:e.getRaw("CS")||e.getRaw("ColorSpace"),xref:t,resources:i,pdfFunctionFactory:a,localColorSpaceCache:s});this.bbox=lookupNormalRect(e.getArray("BBox"),null);let g=0,o=1;const c=e.getArray("Domain");isNumberArray(c,2)&&([g,o]=c);let C=!1,h=!1;const l=e.getArray("Extend");(function isBooleanArray(e,t){return Array.isArray(e)&&(null===t||e.length===t)&&e.every((e=>"boolean"==typeof e))})(l,2)&&([C,h]=l);if(!(this.shadingType!==ca||C&&h)){const[e,t,i,a,s,r]=this.coordsArr,n=Math.hypot(e-a,t-s);i<=r+n&&r<=i+n&&warn("Unsupported radial gradient.")}this.extendStart=C;this.extendEnd=h;const Q=e.getRaw("Function"),E=a.createFromArray(Q),u=(o-g)/840,d=this.colorStops=[];if(g>=o||u<=0){info("Bad shading domain.");return}const f=new Float32Array(n.numComps),p=new Float32Array(1);let m,y=0;p[0]=g;E(p,0,f,0);let w=n.getRgb(f,0);const D=Util.makeHexColor(w[0],w[1],w[2]);d.push([0,D]);let b=1;p[0]=g+u;E(p,0,f,0);let F=n.getRgb(f,0),S=F[0]-w[0]+1,k=F[1]-w[1]+1,R=F[2]-w[2]+1,N=F[0]-w[0]-1,G=F[1]-w[1]-1,M=F[2]-w[2]-1;for(let e=2;e<840;e++){p[0]=g+e*u;E(p,0,f,0);m=n.getRgb(f,0);const t=e-y;S=Math.min(S,(m[0]-w[0]+1)/t);k=Math.min(k,(m[1]-w[1]+1)/t);R=Math.min(R,(m[2]-w[2]+1)/t);N=Math.max(N,(m[0]-w[0]-1)/t);G=Math.max(G,(m[1]-w[1]-1)/t);M=Math.max(M,(m[2]-w[2]-1)/t);if(!(N<=S&&G<=k&&M<=R)){const e=Util.makeHexColor(F[0],F[1],F[2]);d.push([b/840,e]);S=m[0]-F[0]+1;k=m[1]-F[1]+1;R=m[2]-F[2]+1;N=m[0]-F[0]-1;G=m[1]-F[1]-1;M=m[2]-F[2]-1;y=b;w=F}b=e;F=m}const U=Util.makeHexColor(F[0],F[1],F[2]);d.push([1,U]);let x="transparent";if(e.has("Background")){m=n.getRgb(e.get("Background"),0);x=Util.makeHexColor(m[0],m[1],m[2])}if(!C){d.unshift([0,x]);d[1][0]+=BaseShading.SMALL_NUMBER}if(!h){d.at(-1)[0]-=BaseShading.SMALL_NUMBER;d.push([1,x])}this.colorStops=d}getIR(){const{coordsArr:e,shadingType:t}=this;let i,a,s,r,n;if(t===Ia){a=[e[0],e[1]];s=[e[2],e[3]];r=null;n=null;i="axial"}else if(t===ca){a=[e[0],e[1]];s=[e[3],e[4]];r=e[2];n=e[5];i="radial"}else unreachable(`getPattern type unknown: ${t}`);return["RadialAxial",i,this.bbox,this.colorStops,a,s,r,n]}}class MeshStreamReader{constructor(e,t){this.stream=e;this.context=t;this.buffer=0;this.bufferLength=0;const i=t.numComps;this.tmpCompsBuf=new Float32Array(i);const a=t.colorSpace.numComps;this.tmpCsCompsBuf=t.colorFn?new Float32Array(a):this.tmpCompsBuf}get hasData(){if(this.stream.end)return this.stream.pos0)return!0;const e=this.stream.getByte();if(e<0)return!1;this.buffer=e;this.bufferLength=8;return!0}readBits(e){let t=this.buffer,i=this.bufferLength;if(32===e){if(0===i)return(this.stream.getByte()<<24|this.stream.getByte()<<16|this.stream.getByte()<<8|this.stream.getByte())>>>0;t=t<<24|this.stream.getByte()<<16|this.stream.getByte()<<8|this.stream.getByte();const e=this.stream.getByte();this.buffer=e&(1<>i)>>>0}if(8===e&&0===i)return this.stream.getByte();for(;i>i}align(){this.buffer=0;this.bufferLength=0}readFlag(){return this.readBits(this.context.bitsPerFlag)}readCoordinate(){const e=this.context.bitsPerCoordinate,t=this.readBits(e),i=this.readBits(e),a=this.context.decode,s=e<32?1/((1<r?r:e;t=t>n?n:t;i=ie*s[t])):i;let n,g=-2;const o=[];for(const[e,t]of a.map(((e,t)=>[e,t])).sort((([e],[t])=>e-t)))if(-1!==e)if(e===g+1){n.push(r[t]);g+=1}else{g=e;n=[r[t]];o.push(e,n)}return o}(e),i=new Dict(null);i.set("BaseFont",Name.get(e));i.set("Type",Name.get("Font"));i.set("Subtype",Name.get("CIDFontType2"));i.set("Encoding",Name.get("Identity-H"));i.set("CIDToGIDMap",Name.get("Identity"));i.set("W",t);i.set("FirstChar",t[0]);i.set("LastChar",t.at(-2)+t.at(-1).length-1);const a=new Dict(null);i.set("FontDescriptor",a);const s=new Dict(null);s.set("Ordering","Identity");s.set("Registry","Adobe");s.set("Supplement",0);i.set("CIDSystemInfo",s);return i}class PostScriptParser{constructor(e){this.lexer=e;this.operators=[];this.token=null;this.prev=null}nextToken(){this.prev=this.token;this.token=this.lexer.getToken()}accept(e){if(this.token.type===e){this.nextToken();return!0}return!1}expect(e){if(this.accept(e))return!0;throw new FormatError(`Unexpected symbol: found ${this.token.type} expected ${e}.`)}parse(){this.nextToken();this.expect(as.LBRACE);this.parseBlock();this.expect(as.RBRACE);return this.operators}parseBlock(){for(;;)if(this.accept(as.NUMBER))this.operators.push(this.prev.value);else if(this.accept(as.OPERATOR))this.operators.push(this.prev.value);else{if(!this.accept(as.LBRACE))return;this.parseCondition()}}parseCondition(){const e=this.operators.length;this.operators.push(null,null);this.parseBlock();this.expect(as.RBRACE);if(this.accept(as.IF)){this.operators[e]=this.operators.length;this.operators[e+1]="jz"}else{if(!this.accept(as.LBRACE))throw new FormatError("PS Function: error parsing conditional.");{const t=this.operators.length;this.operators.push(null,null);const i=this.operators.length;this.parseBlock();this.expect(as.RBRACE);this.expect(as.IFELSE);this.operators[t]=this.operators.length;this.operators[t+1]="j";this.operators[e]=i;this.operators[e+1]="jz"}}}}const as={LBRACE:0,RBRACE:1,NUMBER:2,OPERATOR:3,IF:4,IFELSE:5};class PostScriptToken{static get opCache(){return shadow(this,"opCache",Object.create(null))}constructor(e,t){this.type=e;this.value=t}static getOperator(e){return PostScriptToken.opCache[e]||=new PostScriptToken(as.OPERATOR,e)}static get LBRACE(){return shadow(this,"LBRACE",new PostScriptToken(as.LBRACE,"{"))}static get RBRACE(){return shadow(this,"RBRACE",new PostScriptToken(as.RBRACE,"}"))}static get IF(){return shadow(this,"IF",new PostScriptToken(as.IF,"IF"))}static get IFELSE(){return shadow(this,"IFELSE",new PostScriptToken(as.IFELSE,"IFELSE"))}}class PostScriptLexer{constructor(e){this.stream=e;this.nextChar();this.strBuf=[]}nextChar(){return this.currentChar=this.stream.getByte()}getToken(){let e=!1,t=this.currentChar;for(;;){if(t<0)return Bt;if(e)10!==t&&13!==t||(e=!1);else if(37===t)e=!0;else if(!isWhiteSpace(t))break;t=this.nextChar()}switch(0|t){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 43:case 45:case 46:return new PostScriptToken(as.NUMBER,this.getNumber());case 123:this.nextChar();return PostScriptToken.LBRACE;case 125:this.nextChar();return PostScriptToken.RBRACE}const i=this.strBuf;i.length=0;i[0]=String.fromCharCode(t);for(;(t=this.nextChar())>=0&&(t>=65&&t<=90||t>=97&&t<=122);)i.push(String.fromCharCode(t));const a=i.join("");switch(a.toLowerCase()){case"if":return PostScriptToken.IF;case"ifelse":return PostScriptToken.IFELSE;default:return PostScriptToken.getOperator(a)}}getNumber(){let e=this.currentChar;const t=this.strBuf;t.length=0;t[0]=String.fromCharCode(e);for(;(e=this.nextChar())>=0&&(e>=48&&e<=57||45===e||46===e);)t.push(String.fromCharCode(e));const i=parseFloat(t.join(""));if(isNaN(i))throw new FormatError(`Invalid floating point number: ${i}`);return i}}class BaseLocalCache{constructor(e){this._onlyRefs=!0===e?.onlyRefs;if(!this._onlyRefs){this._nameRefMap=new Map;this._imageMap=new Map}this._imageCache=new RefSetCache}getByName(e){this._onlyRefs&&unreachable("Should not call `getByName` method.");const t=this._nameRefMap.get(e);return t?this.getByRef(t):this._imageMap.get(e)||null}getByRef(e){return this._imageCache.get(e)||null}set(e,t,i){unreachable("Abstract method `set` called.")}}class LocalImageCache extends BaseLocalCache{set(e,t=null,i){if("string"!=typeof e)throw new Error('LocalImageCache.set - expected "name" argument.');if(t){if(this._imageCache.has(t))return;this._nameRefMap.set(e,t);this._imageCache.put(t,i)}else this._imageMap.has(e)||this._imageMap.set(e,i)}}class LocalColorSpaceCache extends BaseLocalCache{set(e=null,t=null,i){if("string"!=typeof e&&!t)throw new Error('LocalColorSpaceCache.set - expected "name" and/or "ref" argument.');if(t){if(this._imageCache.has(t))return;null!==e&&this._nameRefMap.set(e,t);this._imageCache.put(t,i)}else this._imageMap.has(e)||this._imageMap.set(e,i)}}class LocalFunctionCache extends BaseLocalCache{constructor(e){super({onlyRefs:!0})}set(e=null,t,i){if(!t)throw new Error('LocalFunctionCache.set - expected "ref" argument.');this._imageCache.has(t)||this._imageCache.put(t,i)}}class LocalGStateCache extends BaseLocalCache{set(e,t=null,i){if("string"!=typeof e)throw new Error('LocalGStateCache.set - expected "name" argument.');if(t){if(this._imageCache.has(t))return;this._nameRefMap.set(e,t);this._imageCache.put(t,i)}else this._imageMap.has(e)||this._imageMap.set(e,i)}}class LocalTilingPatternCache extends BaseLocalCache{constructor(e){super({onlyRefs:!0})}set(e=null,t,i){if(!t)throw new Error('LocalTilingPatternCache.set - expected "ref" argument.');this._imageCache.has(t)||this._imageCache.put(t,i)}}class RegionalImageCache extends BaseLocalCache{constructor(e){super({onlyRefs:!0})}set(e=null,t,i){if(!t)throw new Error('RegionalImageCache.set - expected "ref" argument.');this._imageCache.has(t)||this._imageCache.put(t,i)}}class GlobalImageCache{static NUM_PAGES_THRESHOLD=2;static MIN_IMAGES_TO_CACHE=10;static MAX_BYTE_SIZE=5e7;#F=new RefSet;constructor(){this._refCache=new RefSetCache;this._imageCache=new RefSetCache}get#S(){let e=0;for(const t of this._imageCache)e+=t.byteSize;return e}get#k(){return!(this._imageCache.size+e)):null}class PDFFunction{static getSampleArray(e,t,i,a){let s,r,n=1;for(s=0,r=e.length;s>o)*C;c&=(1<i?e=i:e0&&(l=r[h-1]);let Q=a[1];h>1,c=s.length>>1,C=new PostScriptEvaluator(g),h=Object.create(null);let l=8192;const Q=new Float32Array(c);return function constructPostScriptFn(e,t,i,a){let s,n,g="";const E=Q;for(s=0;se&&(n=e)}d[s]=n}if(l>0){l--;h[g]=d}i.set(d,a)}}}function isPDFFunction(e){let t;if(e instanceof Dict)t=e;else{if(!(e instanceof BaseStream))return!1;t=e.dict}return t.has("FunctionType")}class PostScriptStack{static MAX_STACK_SIZE=100;constructor(e){this.stack=e?Array.from(e):[]}push(e){if(this.stack.length>=PostScriptStack.MAX_STACK_SIZE)throw new Error("PostScript function stack overflow.");this.stack.push(e)}pop(){if(this.stack.length<=0)throw new Error("PostScript function stack underflow.");return this.stack.pop()}copy(e){if(this.stack.length+e>=PostScriptStack.MAX_STACK_SIZE)throw new Error("PostScript function stack overflow.");const t=this.stack;for(let i=t.length-e,a=e-1;a>=0;a--,i++)t.push(t[i])}index(e){this.push(this.stack[this.stack.length-e-1])}roll(e,t){const i=this.stack,a=i.length-e,s=i.length-1,r=a+(t-Math.floor(t/e)*e);for(let e=a,t=s;e0?t.push(n<>g);break;case"ceiling":n=t.pop();t.push(Math.ceil(n));break;case"copy":n=t.pop();t.copy(n);break;case"cos":n=t.pop();t.push(Math.cos(n%360/180*Math.PI));break;case"cvi":n=0|t.pop();t.push(n);break;case"cvr":break;case"div":g=t.pop();n=t.pop();t.push(n/g);break;case"dup":t.copy(1);break;case"eq":g=t.pop();n=t.pop();t.push(n===g);break;case"exch":t.roll(2,1);break;case"exp":g=t.pop();n=t.pop();t.push(n**g);break;case"false":t.push(!1);break;case"floor":n=t.pop();t.push(Math.floor(n));break;case"ge":g=t.pop();n=t.pop();t.push(n>=g);break;case"gt":g=t.pop();n=t.pop();t.push(n>g);break;case"idiv":g=t.pop();n=t.pop();t.push(n/g|0);break;case"index":n=t.pop();t.index(n);break;case"le":g=t.pop();n=t.pop();t.push(n<=g);break;case"ln":n=t.pop();t.push(Math.log(n));break;case"log":n=t.pop();t.push(Math.log10(n));break;case"lt":g=t.pop();n=t.pop();t.push(n=t?new AstLiteral(t):e.max<=t?e:new AstMin(e,t)}class PostScriptCompiler{compile(e,t,i){const a=[],s=[],r=t.length>>1,n=i.length>>1;let g,o,c,C,h,l,Q,E,u=0;for(let e=0;et.min){g.unshift("Math.max(",r,", ");g.push(")")}if(n4){a=!0;t=0}else{a=!1;t=1}const o=[];for(r=0;r=0&&"ET"===gs[e];--e)gs[e]="EN";for(let e=r+1;e0&&(t=gs[r-1]);let i=h;e+1E&&isOdd(E)&&(d=E)}for(E=u;E>=d;--E){let e=-1;for(r=0,n=o.length;r=0){reverseValues(ns,e,r);e=-1}}else e<0&&(e=r);e>=0&&reverseValues(ns,e,o.length)}for(r=0,n=ns.length;r"!==e||(ns[r]="")}return createBidiText(ns.join(""),a)}const os={style:"normal",weight:"normal"},Is={style:"normal",weight:"bold"},cs={style:"italic",weight:"normal"},Cs={style:"italic",weight:"bold"},hs=new Map([["Times-Roman",{local:["Times New Roman","Times-Roman","Times","Liberation Serif","Nimbus Roman","Nimbus Roman L","Tinos","Thorndale","TeX Gyre Termes","FreeSerif","Linux Libertine O","Libertinus Serif","DejaVu Serif","Bitstream Vera Serif","Ubuntu"],style:os,ultimate:"serif"}],["Times-Bold",{alias:"Times-Roman",style:Is,ultimate:"serif"}],["Times-Italic",{alias:"Times-Roman",style:cs,ultimate:"serif"}],["Times-BoldItalic",{alias:"Times-Roman",style:Cs,ultimate:"serif"}],["Helvetica",{local:["Helvetica","Helvetica Neue","Arial","Arial Nova","Liberation Sans","Arimo","Nimbus Sans","Nimbus Sans L","A030","TeX Gyre Heros","FreeSans","DejaVu Sans","Albany","Bitstream Vera Sans","Arial Unicode MS","Microsoft Sans Serif","Apple Symbols","Cantarell"],path:"LiberationSans-Regular.ttf",style:os,ultimate:"sans-serif"}],["Helvetica-Bold",{alias:"Helvetica",path:"LiberationSans-Bold.ttf",style:Is,ultimate:"sans-serif"}],["Helvetica-Oblique",{alias:"Helvetica",path:"LiberationSans-Italic.ttf",style:cs,ultimate:"sans-serif"}],["Helvetica-BoldOblique",{alias:"Helvetica",path:"LiberationSans-BoldItalic.ttf",style:Cs,ultimate:"sans-serif"}],["Courier",{local:["Courier","Courier New","Liberation Mono","Nimbus Mono","Nimbus Mono L","Cousine","Cumberland","TeX Gyre Cursor","FreeMono","Linux Libertine Mono O","Libertinus Mono"],style:os,ultimate:"monospace"}],["Courier-Bold",{alias:"Courier",style:Is,ultimate:"monospace"}],["Courier-Oblique",{alias:"Courier",style:cs,ultimate:"monospace"}],["Courier-BoldOblique",{alias:"Courier",style:Cs,ultimate:"monospace"}],["ArialBlack",{local:["Arial Black"],style:{style:"normal",weight:"900"},fallback:"Helvetica-Bold"}],["ArialBlack-Bold",{alias:"ArialBlack"}],["ArialBlack-Italic",{alias:"ArialBlack",style:{style:"italic",weight:"900"},fallback:"Helvetica-BoldOblique"}],["ArialBlack-BoldItalic",{alias:"ArialBlack-Italic"}],["ArialNarrow",{local:["Arial Narrow","Liberation Sans Narrow","Helvetica Condensed","Nimbus Sans Narrow","TeX Gyre Heros Cn"],style:os,fallback:"Helvetica"}],["ArialNarrow-Bold",{alias:"ArialNarrow",style:Is,fallback:"Helvetica-Bold"}],["ArialNarrow-Italic",{alias:"ArialNarrow",style:cs,fallback:"Helvetica-Oblique"}],["ArialNarrow-BoldItalic",{alias:"ArialNarrow",style:Cs,fallback:"Helvetica-BoldOblique"}],["Calibri",{local:["Calibri","Carlito"],style:os,fallback:"Helvetica"}],["Calibri-Bold",{alias:"Calibri",style:Is,fallback:"Helvetica-Bold"}],["Calibri-Italic",{alias:"Calibri",style:cs,fallback:"Helvetica-Oblique"}],["Calibri-BoldItalic",{alias:"Calibri",style:Cs,fallback:"Helvetica-BoldOblique"}],["Wingdings",{local:["Wingdings","URW Dingbats"],style:os}],["Wingdings-Regular",{alias:"Wingdings"}],["Wingdings-Bold",{alias:"Wingdings"}]]),ls=new Map([["Arial-Black","ArialBlack"]]);function getFamilyName(e){const t=new Set(["thin","extralight","ultralight","demilight","semilight","light","book","regular","normal","medium","demibold","semibold","bold","extrabold","ultrabold","black","heavy","extrablack","ultrablack","roman","italic","oblique","ultracondensed","extracondensed","condensed","semicondensed","normal","semiexpanded","expanded","extraexpanded","ultraexpanded","bolditalic"]);return e.split(/[- ,+]+/g).filter((e=>!t.has(e.toLowerCase()))).join(" ")}function generateFont({alias:e,local:t,path:i,fallback:a,style:s,ultimate:r},n,g,o=!0,c=!0,C=""){const h={style:null,ultimate:null};if(t){const e=C?` ${C}`:"";for(const i of t)n.push(`local(${i}${e})`)}if(e){const t=hs.get(e),r=C||function getStyleToAppend(e){switch(e){case Is:return"Bold";case cs:return"Italic";case Cs:return"Bold Italic";default:if("bold"===e?.weight)return"Bold";if("italic"===e?.style)return"Italic"}return""}(s);Object.assign(h,generateFont(t,n,g,o&&!a,c&&!i,r))}s&&(h.style=s);r&&(h.ultimate=r);if(o&&a){const e=hs.get(a),{ultimate:t}=generateFont(e,n,g,o,c&&!i,C);h.ultimate||=t}c&&i&&g&&n.push(`url(${g}${i})`);return h}function getFontSubstitution(e,t,i,a,s,r){if(a.startsWith("InvalidPDFjsFont_"))return null;"TrueType"!==r&&"Type1"!==r||!/^[A-Z]{6}\+/.test(a)||(a=a.slice(7));const n=a=normalizeFontName(a);let g=e.get(n);if(g)return g;let o=hs.get(a);if(!o)for(const[e,t]of ls)if(a.startsWith(e)){a=`${t}${a.substring(e.length)}`;o=hs.get(a);break}let c=!1;if(!o){o=hs.get(s);c=!0}const C=`${t.getDocId()}_s${t.createFontId()}`;if(!o){if(!validateFontName(a)){warn(`Cannot substitute the font because of its name: ${a}`);e.set(n,null);return null}const t=/bold/gi.test(a),i=/oblique|italic/gi.test(a),s=t&&i&&Cs||t&&Is||i&&cs||os;g={css:`"${getFamilyName(a)}",${C}`,guessFallback:!0,loadedName:C,baseFontName:a,src:`local(${a})`,style:s};e.set(n,g);return g}const h=[];c&&validateFontName(a)&&h.push(`local(${a})`);const{style:l,ultimate:Q}=generateFont(o,h,i),E=null===Q,u=E?"":`,${Q}`;g={css:`"${getFamilyName(a)}",${C}${u}`,guessFallback:E,loadedName:C,baseFontName:a,src:h.join(","),style:l};e.set(n,g);return g}class ImageResizer{static#R=2048;static#y=FeatureTest.isImageDecoderSupported;constructor(e,t){this._imgData=e;this._isMask=t}static get canUseImageDecoder(){return shadow(this,"canUseImageDecoder",this.#y?ImageDecoder.isTypeSupported("image/bmp"):Promise.resolve(!1))}static needsToBeResized(e,t){if(e<=this.#R&&t<=this.#R)return!1;const{MAX_DIM:i}=this;if(e>i||t>i)return!0;const a=e*t;if(this._hasMaxArea)return a>this.MAX_AREA;if(a(this.MAX_AREA=this.#R**2)}static get MAX_DIM(){return shadow(this,"MAX_DIM",this._guessMax(2048,65537,0,1))}static get MAX_AREA(){this._hasMaxArea=!0;return shadow(this,"MAX_AREA",this._guessMax(this.#R,this.MAX_DIM,128,0)**2)}static set MAX_AREA(e){if(e>=0){this._hasMaxArea=!0;shadow(this,"MAX_AREA",e)}}static setOptions({canvasMaxAreaInBytes:e=-1,isImageDecoderSupported:t=!1}){this._hasMaxArea||(this.MAX_AREA=e>>2);this.#y=t}static _areGoodDims(e,t){try{const i=new OffscreenCanvas(e,t),a=i.getContext("2d");a.fillRect(0,0,1,1);const s=a.getImageData(0,0,1,1).data[3];i.width=i.height=1;return 0!==s}catch{return!1}}static _guessMax(e,t,i,a){for(;e+i+1pt){const e=this.#N();if(e)return e}const a=this._encodeBMP();let s,r;if(await ImageResizer.canUseImageDecoder){s=new ImageDecoder({data:a,type:"image/bmp",preferAnimation:!1,transfer:[a.buffer]});r=s.decode().catch((e=>{warn(`BMP image decoding failed: ${e}`);return createImageBitmap(new Blob([this._encodeBMP().buffer],{type:"image/bmp"}))})).finally((()=>{s.close()}))}else r=createImageBitmap(new Blob([a.buffer],{type:"image/bmp"}));const{MAX_AREA:n,MAX_DIM:g}=ImageResizer,o=Math.max(t/g,i/g,Math.sqrt(t*i/n)),c=Math.max(o,2),C=Math.round(10*(o+1.25))/10/c,h=Math.floor(Math.log2(C)),l=new Array(h+2).fill(2);l[0]=c;l.splice(-1,1,C/(1<>n,o=a>>n;let c,C=a;try{c=new Uint8Array(r)}catch{let e=Math.floor(Math.log2(r+1));for(;;)try{c=new Uint8Array(2**e-1);break}catch{e-=1}C=Math.floor((2**e-1)/(4*i));const t=i*C*4;t>n;e>3,n=i+3&-4;if(i!==n){const e=new Uint8Array(n*t);let a=0;for(let r=0,g=t*i;r>>8;t[i++]=255&s}}}else{if(!ArrayBuffer.isView(e))throw new Error("Invalid data format, must be a string or TypedArray.");t=e.slice();i=t.byteLength}const a=i>>2,s=i-4*a,r=new Uint32Array(t.buffer,0,a);let n=0,g=0,o=this.h1,c=this.h2;const C=3432918353,h=461845907,l=11601,Q=13715;for(let e=0;e>>17;n=n*h&Qs|n*Q&Es;o^=n;o=o<<13|o>>>19;o=5*o+3864292196}else{g=r[e];g=g*C&Qs|g*l&Es;g=g<<15|g>>>17;g=g*h&Qs|g*Q&Es;c^=g;c=c<<13|c>>>19;c=5*c+3864292196}n=0;switch(s){case 3:n^=t[4*a+2]<<16;case 2:n^=t[4*a+1]<<8;case 1:n^=t[4*a];n=n*C&Qs|n*l&Es;n=n<<15|n>>>17;n=n*h&Qs|n*Q&Es;1&a?o^=n:c^=n}this.h1=o;this.h2=c}hexdigest(){let e=this.h1,t=this.h2;e^=t>>>1;e=3981806797*e&Qs|36045*e&Es;t=4283543511*t&Qs|(2950163797*(t<<16|e>>>16)&Qs)>>>16;e^=t>>>1;e=444984403*e&Qs|60499*e&Es;t=3301882366*t&Qs|(3120437893*(t<<16|e>>>16)&Qs)>>>16;e^=t>>>1;return(e>>>0).toString(16).padStart(8,"0")+(t>>>0).toString(16).padStart(8,"0")}}function addState(e,t,i,a,s){let r=e;for(let e=0,i=t.length-1;e1e3){c=Math.max(c,l);Q+=h+2;l=0;h=0}C.push({transform:t,x:l,y:Q,w:i.width,h:i.height});l+=i.width+2;h=Math.max(h,i.height)}const E=Math.max(c,l)+1,u=Q+h+1,d=new Uint8Array(E*u*4),f=E<<2;for(let e=0;e=0;){t[r-4]=t[r];t[r-3]=t[r+1];t[r-2]=t[r+2];t[r-1]=t[r+3];t[r+i]=t[r+i-4];t[r+i+1]=t[r+i-3];t[r+i+2]=t[r+i-2];t[r+i+3]=t[r+i-1];r-=f}}const p={width:E,height:u};if(e.isOffscreenCanvasSupported){const e=new OffscreenCanvas(E,u);e.getContext("2d").putImageData(new ImageData(new Uint8ClampedArray(d.buffer),E,u),0,0);p.bitmap=e.transferToImageBitmap();p.data=null}else{p.kind=S;p.data=d}i.splice(r,4*o,$e);a.splice(r,4*o,[p,C]);return r+1}));addState(us,[MA,xA,Ze,UA],null,(function iterateImageMaskGroup(e,t){const i=e.fnArray,a=(t-(e.iCurr-3))%4;switch(a){case 0:return i[t]===MA;case 1:return i[t]===xA;case 2:return i[t]===Ze;case 3:return i[t]===UA}throw new Error(`iterateImageMaskGroup - invalid pos: ${a}`)}),(function foundImageMaskGroup(e,t){const i=e.fnArray,a=e.argsArray,s=e.iCurr,r=s-3,n=s-2,g=s-1;let o=Math.floor((t-r)/4);if(o<10)return t-(t-r)%4;let c,C,h=!1;const l=a[g][0],Q=a[n][0],E=a[n][1],u=a[n][2],d=a[n][3];if(E===u){h=!0;c=n+4;let e=g+4;for(let t=1;t=4&&i[r-4]===i[n]&&i[r-3]===i[g]&&i[r-2]===i[o]&&i[r-1]===i[c]&&a[r-4][0]===C&&a[r-4][1]===h){l++;Q-=5}let E=Q+4;for(let e=1;e=i)break}a=(a||us)[e[t]];if(a&&!Array.isArray(a)){r.iCurr=t;t++;if(!a.checkFn||(0,a.checkFn)(r)){s=a;a=null}else a=null}else t++}this.state=a;this.match=s;this.lastProcessed=t}flush(){for(;this.match;){const e=this.queue.fnArray.length;this.lastProcessed=(0,this.match.processFn)(this.context,e);this.match=null;this.state=null;this._optimize()}}reset(){this.state=null;this.match=null;this.lastProcessed=0}}class OperatorList{static CHUNK_SIZE=1e3;static CHUNK_SIZE_ABOUT=this.CHUNK_SIZE-5;constructor(e=0,t){this._streamSink=t;this.fnArray=[];this.argsArray=[];this.optimizer=!t||e&E?new NullOptimizer(this):new QueueOptimizer(this);this.dependencies=new Set;this._totalLength=0;this.weight=0;this._resolved=t?null:Promise.resolve()}set isOffscreenCanvasSupported(e){this.optimizer.isOffscreenCanvasSupported=e}get length(){return this.argsArray.length}get ready(){return this._resolved||this._streamSink.ready}get totalLength(){return this._totalLength+this.length}addOp(e,t){this.optimizer.push(e,t);this.weight++;this._streamSink&&(this.weight>=OperatorList.CHUNK_SIZE||this.weight>=OperatorList.CHUNK_SIZE_ABOUT&&(e===UA||e===ee))&&this.flush()}addImageOps(e,t,i,a=!1){if(a){this.addOp(MA);this.addOp(GA,[[["SMask",!1]]])}void 0!==i&&this.addOp(Ye,["OC",i]);this.addOp(e,t);void 0!==i&&this.addOp(ve,[]);a&&this.addOp(UA)}addDependency(e){if(!this.dependencies.has(e)){this.dependencies.add(e);this.addOp(wA,[e])}}addDependencies(e){for(const t of e)this.addDependency(t)}addOpList(e){if(e instanceof OperatorList){for(const t of e.dependencies)this.dependencies.add(t);for(let t=0,i=e.length;ta&&(e=a);return e}function resizeImageMask(e,t,i,a,s,r){const n=s*r;let g;g=t<=8?new Uint8Array(n):t<=16?new Uint16Array(n):new Uint32Array(n);const o=i/s,c=a/r;let C,h,l,Q,E=0;const u=new Uint16Array(s),d=i;for(C=0;C0&&Number.isInteger(i.height)&&i.height>0&&(i.width!==l||i.height!==Q)){warn("PDFImage - using the Width/Height of the image data, rather than the image dictionary.");l=i.width;Q=i.height}if(l<1||Q<1)throw new FormatError(`Invalid image width: ${l} or height: ${Q}`);this.width=l;this.height=Q;this.interpolate=c.get("I","Interpolate");this.imageMask=c.get("IM","ImageMask")||!1;this.matte=c.get("Matte")||!1;let E=i.bitsPerComponent;if(!E){E=c.get("BPC","BitsPerComponent");if(!E){if(!this.imageMask)throw new FormatError(`Bits per component missing in image: ${this.imageMask}`);E=1}}this.bpc=E;if(!this.imageMask){let s=c.getRaw("CS")||c.getRaw("ColorSpace");const r=!!s;if(r)this.jpxDecoderOptions?.smaskInData&&(s=Name.get("DeviceRGBA"));else if(this.jpxDecoderOptions)s=Name.get("DeviceRGBA");else switch(i.numComps){case 1:s=Name.get("DeviceGray");break;case 3:s=Name.get("DeviceRGB");break;case 4:s=Name.get("DeviceCMYK");break;default:throw new Error(`Images with ${i.numComps} color components not supported.`)}this.colorSpace=ColorSpace.parse({cs:s,xref:e,resources:a?t:null,pdfFunctionFactory:g,localColorSpaceCache:o});this.numComps=this.colorSpace.numComps;if(this.jpxDecoderOptions){this.jpxDecoderOptions.numComponents=r?this.numComp:0;this.jpxDecoderOptions.isIndexedColormap="Indexed"===this.colorSpace.name}}this.decode=c.getArray("D","Decode");this.needsDecode=!1;if(this.decode&&(this.colorSpace&&!this.colorSpace.isDefaultDecode(this.decode,E)||n&&!ColorSpace.isDefaultDecode(this.decode,1))){this.needsDecode=!0;const e=(1<>3)*i,g=e.byteLength;let o,c;if(!a||s&&!(n===g))if(s){o=new Uint8Array(n);o.set(e);o.fill(255,g)}else o=new Uint8Array(e);else o=e;if(s)for(c=0;c>7&1;n[l+1]=h>>6&1;n[l+2]=h>>5&1;n[l+3]=h>>4&1;n[l+4]=h>>3&1;n[l+5]=h>>2&1;n[l+6]=h>>1&1;n[l+7]=1&h;l+=8}if(l>=1}}}}else{let i=0;h=0;for(l=0,C=r;l>a;s<0?s=0:s>c&&(s=c);n[l]=s;h&=(1<n[a+1]){t=255;break}}g[C]=t}}}if(g)for(C=0,l=3,h=t*a;C>3,C=t&&ImageResizer.needsToBeResized(i,a);if(!this.smask&&!this.mask&&"DeviceRGBA"===this.colorSpace.name){s.kind=S;const e=s.data=await this.getImageBytes(g*n*4,{});return t?C?ImageResizer.createImage(s,!1):this.createBitmap(S,i,a,e):s}if(!e){let e;"DeviceGray"===this.colorSpace.name&&1===o?e=b:"DeviceRGB"!==this.colorSpace.name||8!==o||this.needsDecode||(e=F);if(e&&!this.smask&&!this.mask&&i===n&&a===g){const r=await this.#G(n,g);if(r)return r;const o=await this.getImageBytes(g*c,{});if(t)return C?ImageResizer.createImage({data:o,kind:e,width:i,height:a,interpolate:this.interpolate},this.needsDecode):this.createBitmap(e,n,g,o);s.kind=e;s.data=o;if(this.needsDecode){assert(e===b,"PDFImage.createImageData: The image must be grayscale.");const t=s.data;for(let e=0,i=t.length;e>3,n=await this.getImageBytes(a*r,{internal:!0}),g=this.getComponents(n);let o,c;if(1===s){c=i*a;if(this.needsDecode)for(o=0;o0&&t.args[0].count++}class TimeSlotManager{static TIME_SLOT_DURATION_MS=20;static CHECK_TIME_EVERY=100;constructor(){this.reset()}check(){if(++this.checkedh){const e="Image exceeded maximum allowed size and was removed.";if(this.options.ignoreErrors){warn(e);return}throw new Error(e)}let l;g.has("OC")&&(l=await this.parseMarkedContentProps(g.get("OC"),e));let Q,E;if(g.get("IM","ImageMask")||!1){const e=g.get("I","Interpolate"),i=c+7>>3,n=t.getBytes(i*C),h=g.getArray("D","Decode");if(this.parsingType3Font){Q=PDFImage.createRawMask({imgArray:n,width:c,height:C,imageIsFromDecodeStream:t instanceof DecodeStream,inverseDecode:h?.[0]>0,interpolate:e});Q.cached=!!s;E=[Q];a.addImageOps(Ze,E,l);if(s){const e={fn:Ze,args:E,optionalContent:l};r.set(s,o,e);o&&this._regionalImageCache.set(null,o,e)}return}Q=await PDFImage.createMask({imgArray:n,width:c,height:C,imageIsFromDecodeStream:t instanceof DecodeStream,inverseDecode:h?.[0]>0,interpolate:e,isOffscreenCanvasSupported:this.options.isOffscreenCanvasSupported});if(Q.isSingleOpaquePixel){a.addImageOps(tt,[],l);if(s){const e={fn:tt,args:[],optionalContent:l};r.set(s,o,e);o&&this._regionalImageCache.set(null,o,e)}return}const u=`mask_${this.idFactory.createObjId()}`;a.addDependency(u);Q.dataLen=Q.bitmap?Q.width*Q.height*4:Q.data.length;this._sendImgData(u,Q);E=[{data:u,width:Q.width,height:Q.height,interpolate:Q.interpolate,count:1}];a.addImageOps(Ze,E,l);if(s){const e={objId:u,fn:Ze,args:E,optionalContent:l};r.set(s,o,e);o&&this._regionalImageCache.set(null,o,e)}return}const u=g.has("SMask")||g.has("Mask");if(i&&c+C<200&&!u){try{const s=new PDFImage({xref:this.xref,res:e,image:t,isInline:i,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:n});Q=await s.createImageData(!0,!1);a.isOffscreenCanvasSupported=this.options.isOffscreenCanvasSupported;a.addImageOps(_e,[Q],l)}catch(e){const t=`Unable to decode inline image: "${e}".`;if(!this.options.ignoreErrors)throw new Error(t);warn(t)}return}let d=`img_${this.idFactory.createObjId()}`,f=!1;if(this.parsingType3Font)d=`${this.idFactory.getDocId()}_type3_${d}`;else if(s&&o){f=this.globalImageCache.shouldCache(o,this.pageIndex);if(f){assert(!i,"Cannot cache an inline image globally.");d=`${this.idFactory.getDocId()}_${d}`}}a.addDependency(d);E=[d,c,C];a.addImageOps(ze,E,l,u);if(f){if(this.globalImageCache.hasDecodeFailed(o)){this.globalImageCache.setData(o,{objId:d,fn:ze,args:E,optionalContent:l,hasMask:u,byteSize:0});this._sendImgData(d,null,f);return}if(c*C>25e4||u){const e=await this.handler.sendWithPromise("commonobj",[d,"CopyLocalImage",{imageRef:o}]);if(e){this.globalImageCache.setData(o,{objId:d,fn:ze,args:E,optionalContent:l,hasMask:u,byteSize:0});this.globalImageCache.addByteSize(o,e);return}}}PDFImage.buildImage({xref:this.xref,res:e,image:t,isInline:i,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:n}).then((async e=>{Q=await e.createImageData(!1,this.options.isOffscreenCanvasSupported);Q.dataLen=Q.bitmap?Q.width*Q.height*4:Q.data.length;Q.ref=o;f&&this.globalImageCache.addByteSize(o,Q.dataLen);return this._sendImgData(d,Q,f)})).catch((e=>{warn(`Unable to decode image "${d}": "${e}".`);o&&this.globalImageCache.addDecodeFailed(o);return this._sendImgData(d,null,f)}));if(s){const e={objId:d,fn:ze,args:E,optionalContent:l,hasMask:u};r.set(s,o,e);if(o){this._regionalImageCache.set(null,o,e);f&&this.globalImageCache.setData(o,{objId:d,fn:ze,args:E,optionalContent:l,hasMask:u,byteSize:0})}}}handleSMask(e,t,i,a,s,r){const n=e.get("G"),g={subtype:e.get("S").name,backdrop:e.get("BC")},o=e.get("TR");if(isPDFFunction(o)){const e=this._pdfFunctionFactory.create(o),t=new Uint8Array(256),i=new Float32Array(1);for(let a=0;a<256;a++){i[0]=a/255;e(i,0,i,0);t[a]=255*i[0]|0}g.transferMap=t}return this.buildFormXObject(t,n,g,i,a,s.state.clone(),r)}handleTransferFunction(e){let t;if(Array.isArray(e))t=e;else{if(!isPDFFunction(e))return null;t=[e]}const i=[];let a=0,s=0;for(const e of t){const t=this.xref.fetchIfRef(e);a++;if(isName(t,"Identity")){i.push(null);continue}if(!isPDFFunction(t))return null;const r=this._pdfFunctionFactory.create(t),n=new Uint8Array(256),g=new Float32Array(1);for(let e=0;e<256;e++){g[0]=e/255;r(g,0,g,0);n[e]=255*g[0]|0}i.push(n);s++}return 1!==a&&4!==a||0===s?null:i}handleTilingType(e,t,i,a,s,r,n,g){const o=new OperatorList,c=Dict.merge({xref:this.xref,dictArray:[s.get("Resources"),i]});return this.getOperatorList({stream:a,task:n,resources:c,operatorList:o}).then((function(){const i=o.getIR(),a=getTilingPatternIR(i,s,t);r.addDependencies(o.dependencies);r.addOp(e,a);s.objId&&g.set(null,s.objId,{operatorListIR:i,dict:s})})).catch((e=>{if(!(e instanceof AbortException)){if(!this.options.ignoreErrors)throw e;warn(`handleTilingType - ignoring pattern: "${e}".`)}}))}async handleSetFont(e,t,i,a,s,r,n=null,g=null){const o=t?.[0]instanceof Name?t[0].name:null;let c=await this.loadFont(o,i,e,n,g);if(c.font.isType3Font)try{await c.loadType3Data(this,e,s);a.addDependencies(c.type3Dependencies)}catch(e){c=new TranslatedFont({loadedName:"g_font_error",font:new ErrorFont(`Type3 font load error: ${e}`),dict:c.font,evaluatorOptions:this.options})}r.font=c.font;c.send(this.handler);return c.loadedName}handleText(e,t){const i=t.font,a=i.charsToGlyphs(e);if(i.data){(!!(t.textRenderingMode&D)||"Pattern"===t.fillColorSpace.name||i.disableFontFace||this.options.disableFontFace)&&PartialEvaluator.buildFontPaths(i,a,this.handler,this.options)}return a}ensureStateFont(e){if(e.font)return;const t=new FormatError("Missing setFont (Tf) operator before text rendering operator.");if(!this.options.ignoreErrors)throw t;warn(`ensureStateFont: "${t}".`)}async setGState({resources:e,gState:t,operatorList:i,cacheKey:a,task:s,stateManager:r,localGStateCache:n,localColorSpaceCache:g}){const o=t.objId;let c=!0;const C=[];let h=Promise.resolve();for(const a of t.getKeys()){const n=t.get(a);switch(a){case"Type":break;case"LW":case"LC":case"LJ":case"ML":case"D":case"RI":case"FL":case"CA":case"ca":C.push([a,n]);break;case"Font":c=!1;h=h.then((()=>this.handleSetFont(e,null,n[0],i,s,r.state).then((function(e){i.addDependency(e);C.push([a,[e,n[1]]])}))));break;case"BM":C.push([a,normalizeBlendMode(n)]);break;case"SMask":if(isName(n,"None")){C.push([a,!1]);break}if(n instanceof Dict){c=!1;h=h.then((()=>this.handleSMask(n,e,i,s,r,g)));C.push([a,!0])}else warn("Unsupported SMask type");break;case"TR":const t=this.handleTransferFunction(n);C.push([a,t]);break;case"OP":case"op":case"OPM":case"BG":case"BG2":case"UCR":case"UCR2":case"TR2":case"HT":case"SM":case"SA":case"AIS":case"TK":info("graphic state operator "+a);break;default:info("Unknown graphic state operator "+a)}}await h;C.length>0&&i.addOp(GA,[C]);c&&n.set(a,o,C)}loadFont(e,t,i,a=null,s=null){const errorFont=async()=>new TranslatedFont({loadedName:"g_font_error",font:new ErrorFont(`Font "${e}" is not available.`),dict:t,evaluatorOptions:this.options});let r;if(t)t instanceof Ref&&(r=t);else{const t=i.get("Font");t&&(r=t.getRaw(e))}if(r){if(this.type3FontRefs?.has(r))return errorFont();if(this.fontCache.has(r))return this.fontCache.get(r);try{t=this.xref.fetchIfRef(r)}catch(e){warn(`loadFont - lookup failed: "${e}".`)}}if(!(t instanceof Dict)){if(!this.options.ignoreErrors&&!this.parsingType3Font){warn(`Font "${e}" is not available.`);return errorFont()}warn(`Font "${e}" is not available -- attempting to fallback to a default font.`);t=a||PartialEvaluator.fallbackFontDict}if(t.cacheKey&&this.fontCache.has(t.cacheKey))return this.fontCache.get(t.cacheKey);const{promise:n,resolve:g}=Promise.withResolvers();let o;try{o=this.preEvaluateFont(t);o.cssFontInfo=s}catch(e){warn(`loadFont - preEvaluateFont failed: "${e}".`);return errorFont()}const{descriptor:c,hash:C}=o,h=r instanceof Ref;let l;if(C&&c instanceof Dict){const e=c.fontAliases||=Object.create(null);if(e[C]){const t=e[C].aliasRef;if(h&&t&&this.fontCache.has(t)){this.fontCache.putAlias(r,t);return this.fontCache.get(r)}}else e[C]={fontID:this.idFactory.createFontId()};h&&(e[C].aliasRef=r);l=e[C].fontID}else l=this.idFactory.createFontId();assert(l?.startsWith("f"),'The "fontID" must be (correctly) defined.');if(h)this.fontCache.put(r,n);else{t.cacheKey=`cacheKey_${l}`;this.fontCache.put(t.cacheKey,n)}t.loadedName=`${this.idFactory.getDocId()}_${l}`;this.translateFont(o).then((e=>{g(new TranslatedFont({loadedName:t.loadedName,font:e,dict:t,evaluatorOptions:this.options}))})).catch((e=>{warn(`loadFont - translateFont failed: "${e}".`);g(new TranslatedFont({loadedName:t.loadedName,font:new ErrorFont(e instanceof Error?e.message:e),dict:t,evaluatorOptions:this.options}))}));return n}buildPath(e,t,i,a=!1){const s=e.length-1;i||(i=[]);if(s<0||e.fnArray[s]!==it){if(a){warn(`Encountered path operator "${t}" inside of a text object.`);e.addOp(MA,null)}let s;switch(t){case TA:const e=i[0]+i[2],t=i[1]+i[3];s=[Math.min(i[0],e),Math.min(i[1],t),Math.max(i[0],e),Math.max(i[1],t)];break;case LA:case HA:s=[i[0],i[1],i[0],i[1]];break;default:s=[1/0,1/0,-1/0,-1/0]}e.addOp(it,[[t],i,s]);a&&e.addOp(UA,null)}else{const a=e.argsArray[s];a[0].push(t);a[1].push(...i);const r=a[2];switch(t){case TA:const e=i[0]+i[2],t=i[1]+i[3];r[0]=Math.min(r[0],i[0],e);r[1]=Math.min(r[1],i[1],t);r[2]=Math.max(r[2],i[0],e);r[3]=Math.max(r[3],i[1],t);break;case LA:case HA:r[0]=Math.min(r[0],i[0]);r[1]=Math.min(r[1],i[1]);r[2]=Math.max(r[2],i[0]);r[3]=Math.max(r[3],i[1])}}}parseColorSpace({cs:e,resources:t,localColorSpaceCache:i}){return ColorSpace.parseAsync({cs:e,xref:this.xref,resources:t,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:i}).catch((e=>{if(e instanceof AbortException)return null;if(this.options.ignoreErrors){warn(`parseColorSpace - ignoring ColorSpace: "${e}".`);return null}throw e}))}parseShading({shading:e,resources:t,localColorSpaceCache:i,localShadingPatternCache:a}){let s,r=a.get(e);if(r)return r;try{s=Pattern.parseShading(e,this.xref,t,this._pdfFunctionFactory,i).getIR()}catch(t){if(t instanceof AbortException)return null;if(this.options.ignoreErrors){warn(`parseShading - ignoring shading: "${t}".`);a.set(e,null);return null}throw t}r=`pattern_${this.idFactory.createObjId()}`;this.parsingType3Font&&(r=`${this.idFactory.getDocId()}_type3_${r}`);a.set(e,r);this.parsingType3Font?this.handler.send("commonobj",[r,"Pattern",s]):this.handler.send("obj",[r,this.pageIndex,"Pattern",s]);return r}handleColorN(e,t,i,a,s,r,n,g,o,c){const C=i.pop();if(C instanceof Name){const h=s.getRaw(C.name),l=h instanceof Ref&&o.getByRef(h);if(l)try{const s=a.base?a.base.getRgb(i,0):null,r=getTilingPatternIR(l.operatorListIR,l.dict,s);e.addOp(t,r);return}catch{}const Q=this.xref.fetchIfRef(h);if(Q){const s=Q instanceof BaseStream?Q.dict:Q,C=s.get("PatternType");if(C===fs){const g=a.base?a.base.getRgb(i,0):null;return this.handleTilingType(t,g,r,Q,s,e,n,o)}if(C===ps){const i=s.get("Shading"),a=this.parseShading({shading:i,resources:r,localColorSpaceCache:g,localShadingPatternCache:c});if(a){const i=lookupMatrix(s.getArray("Matrix"),null);e.addOp(t,["Shading",a,i])}return}throw new FormatError(`Unknown PatternType: ${C}`)}}throw new FormatError(`Unknown PatternName: ${C}`)}_parseVisibilityExpression(e,t,i){if(++t>10){warn("Visibility expression is too deeply nested");return}const a=e.length,s=this.xref.fetchIfRef(e[0]);if(!(a<2)&&s instanceof Name){switch(s.name){case"And":case"Or":case"Not":i.push(s.name);break;default:warn(`Invalid operator ${s.name} in visibility expression`);return}for(let s=1;s0)return{type:"OCMD",expression:t}}const t=i.get("OCGs");if(Array.isArray(t)||t instanceof Dict){const e=[];if(Array.isArray(t))for(const i of t)e.push(i.toString());else e.push(t.objId);return{type:a,ids:e,policy:i.get("P")instanceof Name?i.get("P").name:null,expression:null}}if(t instanceof Ref)return{type:a,id:t.toString()}}return null}getOperatorList({stream:e,task:t,resources:i,operatorList:a,initialState:s=null,fallbackFontDict:r=null}){i||=Dict.empty;s||=new EvalState;if(!a)throw new Error('getOperatorList: missing "operatorList" parameter');const n=this,g=this.xref;let o=!1;const c=new LocalImageCache,C=new LocalColorSpaceCache,h=new LocalGStateCache,l=new LocalTilingPatternCache,Q=new Map,E=i.get("XObject")||Dict.empty,u=i.get("Pattern")||Dict.empty,d=new StateManager(s),f=new EvaluatorPreprocessor(e,g,d),p=new TimeSlotManager;function closePendingRestoreOPS(e){for(let e=0,t=f.savedStatesDepth;e0&&a.addOp(GA,[t]);e=null;continue}}next(new Promise((function(e,s){if(!S)throw new FormatError("GState must be referred to by name.");const r=i.get("ExtGState");if(!(r instanceof Dict))throw new FormatError("ExtGState should be a dictionary.");const g=r.get(F);if(!(g instanceof Dict))throw new FormatError("GState should be a dictionary.");n.setGState({resources:i,gState:g,operatorList:a,cacheKey:F,task:t,stateManager:d,localGStateCache:h,localColorSpaceCache:C}).then(e,s)})).catch((function(e){if(!(e instanceof AbortException)){if(!n.options.ignoreErrors)throw e;warn(`getOperatorList - ignoring ExtGState: "${e}".`)}})));return;case LA:case HA:case JA:case YA:case vA:case KA:case TA:n.buildPath(a,s,e,o);continue;case Le:case He:case Ke:case Te:continue;case Ye:if(!(e[0]instanceof Name)){warn(`Expected name for beginMarkedContentProps arg0=${e[0]}`);a.addOp(Ye,["OC",null]);continue}if("OC"===e[0].name){next(n.parseMarkedContentProps(e[1],i).then((e=>{a.addOp(Ye,["OC",e])})).catch((e=>{if(!(e instanceof AbortException)){if(!n.options.ignoreErrors)throw e;warn(`getOperatorList - ignoring beginMarkedContentProps: "${e}".`);a.addOp(Ye,["OC",null])}})));return}e=[e[0].name,e[1]instanceof Dict?e[1].get("MCID"):null];break;default:if(null!==e){for(w=0,D=e.length;w{if(!(e instanceof AbortException)){if(!this.options.ignoreErrors)throw e;warn(`getOperatorList - ignoring errors during "${t.name}" task: "${e}".`);closePendingRestoreOPS()}}))}getTextContent({stream:e,task:t,resources:s,stateManager:r=null,includeMarkedContent:n=!1,sink:g,seenStyles:o=new Set,viewBox:c,lang:C=null,markedContentData:h=null,disableNormalization:l=!1,keepWhiteSpace:Q=!1}){s||=Dict.empty;r||=new StateManager(new TextState);n&&(h||={level:0});const E={items:[],styles:Object.create(null),lang:C},u={initialized:!1,str:[],totalWidth:0,totalHeight:0,width:0,height:0,vertical:!1,prevTransform:null,textAdvanceScale:0,spaceInFlowMin:0,spaceInFlowMax:0,trackingSpaceMin:1/0,negativeSpaceMax:-1/0,notASpace:-1/0,transform:null,fontName:null,hasEOL:!1},d=[" "," "];let f=0;function saveLastChar(e){const t=(f+1)%2,i=" "!==d[f]&&" "===d[t];d[f]=e;f=t;return!Q&&i}function shouldAddWhitepsace(){return!Q&&" "!==d[f]&&" "===d[(f+1)%2]}function resetLastChars(){d[0]=d[1]=" ";f=0}const p=this,m=this.xref,y=[];let w=null;const D=new LocalImageCache,b=new LocalGStateCache,F=new EvaluatorPreprocessor(e,m,r);let S;function pushWhitespace({width:e=0,height:t=0,transform:i=u.prevTransform,fontName:a=u.fontName}){E.items.push({str:" ",dir:"ltr",width:e,height:t,transform:i,fontName:a,hasEOL:!1})}function getCurrentTextTransform(){const e=S.font,t=[S.fontSize*S.textHScale,0,0,S.fontSize,0,S.textRise];if(e.isType3Font&&(S.fontSize<=1||e.isCharBBox)&&!isArrayEqual(S.fontMatrix,a)){const i=e.bbox[3]-e.bbox[1];i>0&&(t[3]*=i*S.fontMatrix[3])}return Util.transform(S.ctm,Util.transform(S.textMatrix,t))}function ensureTextContentItem(){if(u.initialized)return u;const{font:e,loadedName:t}=S;if(!o.has(t)){o.add(t);E.styles[t]={fontFamily:e.fallbackName,ascent:e.ascent,descent:e.descent,vertical:e.vertical};if(p.options.fontExtraProperties&&e.systemFontInfo){const i=E.styles[t];i.fontSubstitution=e.systemFontInfo.css;i.fontSubstitutionLoadedName=e.systemFontInfo.loadedName}}u.fontName=t;const i=u.transform=getCurrentTextTransform();if(e.vertical){u.width=u.totalWidth=Math.hypot(i[0],i[1]);u.height=u.totalHeight=0;u.vertical=!0}else{u.width=u.totalWidth=0;u.height=u.totalHeight=Math.hypot(i[2],i[3]);u.vertical=!1}const a=Math.hypot(S.textLineMatrix[0],S.textLineMatrix[1]),s=Math.hypot(S.ctm[0],S.ctm[1]);u.textAdvanceScale=s*a;const{fontSize:r}=S;u.trackingSpaceMin=.102*r;u.notASpace=.03*r;u.negativeSpaceMax=-.2*r;u.spaceInFlowMin=.102*r;u.spaceInFlowMax=.6*r;u.hasEOL=!1;u.initialized=!0;return u}function updateAdvanceScale(){if(!u.initialized)return;const e=Math.hypot(S.textLineMatrix[0],S.textLineMatrix[1]),t=Math.hypot(S.ctm[0],S.ctm[1])*e;if(t!==u.textAdvanceScale){if(u.vertical){u.totalHeight+=u.height*u.textAdvanceScale;u.height=0}else{u.totalWidth+=u.width*u.textAdvanceScale;u.width=0}u.textAdvanceScale=t}}function runBidiTransform(e){let t=e.str.join("");l||(t=function normalizeUnicode(e){if(!Ct){Ct=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu;ht=new Map([["ſt","ſt"]])}return e.replaceAll(Ct,((e,t,i)=>t?t.normalize("NFKC"):ht.get(i)))}(t));const i=bidi(t,-1,e.vertical);return{str:i.str,dir:i.dir,width:Math.abs(e.totalWidth),height:Math.abs(e.totalHeight),transform:e.transform,fontName:e.fontName,hasEOL:e.hasEOL}}async function handleSetFont(e,i){const r=await p.loadFont(e,i,s);if(r.font.isType3Font)try{await r.loadType3Data(p,s,t)}catch{}S.loadedName=r.loadedName;S.font=r.font;S.fontMatrix=r.font.fontMatrix||a}function applyInverseRotation(e,t,i){const a=Math.hypot(i[0],i[1]);return[(i[0]*e+i[1]*t)/a,(i[2]*e+i[3]*t)/a]}function compareWithLastPosition(e){const t=getCurrentTextTransform();let i=t[4],a=t[5];if(S.font?.vertical){if(ic[2]||a+ec[3])return!1}else if(i+ec[2]||ac[3])return!1;if(!S.font||!u.prevTransform)return!0;let s=u.prevTransform[4],r=u.prevTransform[5];if(s===i&&r===a)return!0;let n=-1;t[0]&&0===t[1]&&0===t[2]?n=t[0]>0?0:180:t[1]&&0===t[0]&&0===t[3]&&(n=t[1]>0?90:270);switch(n){case 0:break;case 90:[i,a]=[a,i];[s,r]=[r,s];break;case 180:[i,a,s,r]=[-i,-a,-s,-r];break;case 270:[i,a]=[-a,-i];[s,r]=[-r,-s];break;default:[i,a]=applyInverseRotation(i,a,t);[s,r]=applyInverseRotation(s,r,u.prevTransform)}if(S.font.vertical){const e=(r-a)/u.textAdvanceScale,t=i-s,n=Math.sign(u.height);if(e.5*u.width){appendEOL();return!0}resetLastChars();flushTextContentItem();return!0}if(Math.abs(t)>u.width){appendEOL();return!0}e<=n*u.notASpace&&resetLastChars();if(e<=n*u.trackingSpaceMin)if(shouldAddWhitepsace()){resetLastChars();flushTextContentItem();pushWhitespace({height:Math.abs(e)})}else u.height+=e;else if(!addFakeSpaces(e,u.prevTransform,n))if(0===u.str.length){resetLastChars();pushWhitespace({height:Math.abs(e)})}else u.height+=e;Math.abs(t)>.25*u.width&&flushTextContentItem();return!0}const g=(i-s)/u.textAdvanceScale,o=a-r,C=Math.sign(u.width);if(g.5*u.height){appendEOL();return!0}resetLastChars();flushTextContentItem();return!0}if(Math.abs(o)>u.height){appendEOL();return!0}g<=C*u.notASpace&&resetLastChars();if(g<=C*u.trackingSpaceMin)if(shouldAddWhitepsace()){resetLastChars();flushTextContentItem();pushWhitespace({width:Math.abs(g)})}else u.width+=g;else if(!addFakeSpaces(g,u.prevTransform,C))if(0===u.str.length){resetLastChars();pushWhitespace({width:Math.abs(g)})}else u.width+=g;Math.abs(o)>.25*u.height&&flushTextContentItem();return!0}function buildTextContentItem({chars:e,extraSpacing:t}){const i=S.font;if(!e){const e=S.charSpacing+t;e&&(i.vertical?S.translateTextMatrix(0,-e):S.translateTextMatrix(e*S.textHScale,0));Q&&compareWithLastPosition(0);return}const a=i.charsToGlyphs(e),s=S.fontMatrix[0]*S.fontSize;for(let e=0,r=a.length;e0){const e=y.join("");y.length=0;buildTextContentItem({chars:e,extraSpacing:0})}break;case he:if(!r.state.font){p.ensureStateFont(r.state);continue}buildTextContentItem({chars:N[0],extraSpacing:0});break;case Be:if(!r.state.font){p.ensureStateFont(r.state);continue}S.carriageReturn();buildTextContentItem({chars:N[0],extraSpacing:0});break;case Qe:if(!r.state.font){p.ensureStateFont(r.state);continue}S.wordSpacing=N[0];S.charSpacing=N[1];S.carriageReturn();buildTextContentItem({chars:N[2],extraSpacing:0});break;case xe:flushTextContentItem();w??=s.get("XObject")||Dict.empty;R=N[0]instanceof Name;f=N[0].name;if(R&&D.getByName(f))break;next(new Promise((function(e,i){if(!R)throw new FormatError("XObject must be referred to by name.");let a=w.getRaw(f);if(a instanceof Ref){if(D.getByRef(a)){e();return}if(p.globalImageCache.getData(a,p.pageIndex)){e();return}a=m.fetch(a)}if(!(a instanceof BaseStream))throw new FormatError("XObject should be a stream");const E=a.dict.get("Subtype");if(!(E instanceof Name))throw new FormatError("XObject should have a Name subtype");if("Form"!==E.name){D.set(f,a.dict.objId,!0);e();return}const u=r.state.clone(),d=new StateManager(u),y=lookupMatrix(a.dict.getArray("Matrix"),null);y&&d.transform(y);enqueueChunk();const b={enqueueInvoked:!1,enqueue(e,t){this.enqueueInvoked=!0;g.enqueue(e,t)},get desiredSize(){return g.desiredSize},get ready(){return g.ready}};p.getTextContent({stream:a,task:t,resources:a.dict.get("Resources")||s,stateManager:d,includeMarkedContent:n,sink:b,seenStyles:o,viewBox:c,lang:C,markedContentData:h,disableNormalization:l,keepWhiteSpace:Q}).then((function(){b.enqueueInvoked||D.set(f,a.dict.objId,!0);e()}),i)})).catch((function(e){if(!(e instanceof AbortException)){if(!p.options.ignoreErrors)throw e;warn(`getTextContent - ignoring XObject: "${e}".`)}})));return;case GA:R=N[0]instanceof Name;f=N[0].name;if(R&&b.getByName(f))break;next(new Promise((function(e,t){if(!R)throw new FormatError("GState must be referred to by name.");const i=s.get("ExtGState");if(!(i instanceof Dict))throw new FormatError("ExtGState should be a dictionary.");const a=i.get(f);if(!(a instanceof Dict))throw new FormatError("GState should be a dictionary.");const r=a.get("Font");if(r){flushTextContentItem();S.fontName=null;S.fontSize=r[1];handleSetFont(null,r[0]).then(e,t)}else{b.set(f,a.objId,!0);e()}})).catch((function(e){if(!(e instanceof AbortException)){if(!p.options.ignoreErrors)throw e;warn(`getTextContent - ignoring ExtGState: "${e}".`)}})));return;case Je:flushTextContentItem();if(n){h.level++;E.items.push({type:"beginMarkedContent",tag:N[0]instanceof Name?N[0].name:null})}break;case Ye:flushTextContentItem();if(n){h.level++;let e=null;N[1]instanceof Dict&&(e=N[1].get("MCID"));E.items.push({type:"beginMarkedContentProps",id:Number.isInteger(e)?`${p.idFactory.getPageObjId()}_mc${e}`:null,tag:N[0]instanceof Name?N[0].name:null})}break;case ve:flushTextContentItem();if(n){if(0===h.level)break;h.level--;E.items.push({type:"endMarkedContent"})}break;case UA:!e||e.font===S.font&&e.fontSize===S.fontSize&&e.fontName===S.fontName||flushTextContentItem()}if(E.items.length>=g.desiredSize){d=!0;break}}if(d)next(ms);else{flushTextContentItem();enqueueChunk();e()}})).catch((e=>{if(!(e instanceof AbortException)){if(!this.options.ignoreErrors)throw e;warn(`getTextContent - ignoring errors during "${t.name}" task: "${e}".`);flushTextContentItem();enqueueChunk()}}))}async extractDataStructures(e,t){const i=this.xref;let a;const s=this.readToUnicode(t.toUnicode);if(t.composite){const i=e.get("CIDSystemInfo");i instanceof Dict&&(t.cidSystemInfo={registry:stringToPDFString(i.get("Registry")),ordering:stringToPDFString(i.get("Ordering")),supplement:i.get("Supplement")});try{const t=e.get("CIDToGIDMap");t instanceof BaseStream&&(a=t.getBytes())}catch(e){if(!this.options.ignoreErrors)throw e;warn(`extractDataStructures - ignoring CIDToGIDMap data: "${e}".`)}}const r=[];let n,g=null;if(e.has("Encoding")){n=e.get("Encoding");if(n instanceof Dict){g=n.get("BaseEncoding");g=g instanceof Name?g.name:null;if(n.has("Differences")){const e=n.get("Differences");let t=0;for(const a of e){const e=i.fetchIfRef(a);if("number"==typeof e)t=e;else{if(!(e instanceof Name))throw new FormatError(`Invalid entry in 'Differences' array: ${e}`);r[t++]=e.name}}}}else if(n instanceof Name)g=n.name;else{const e="Encoding is not a Name nor a Dict";if(!this.options.ignoreErrors)throw new FormatError(e);warn(e)}"MacRomanEncoding"!==g&&"MacExpertEncoding"!==g&&"WinAnsiEncoding"!==g&&(g=null)}const o=!t.file||t.isInternalFont,c=qi()[t.name];g&&o&&c&&(g=null);if(g)t.defaultEncoding=getEncoding(g);else{const e=!!(t.flags&Mi),i=!!(t.flags&xi);n=hi;"TrueType"!==t.type||i||(n=li);if(e||c){n=Ci;o&&(/Symbol/i.test(t.name)?n=Bi:/Dingbats/i.test(t.name)?n=Qi:/Wingdings/i.test(t.name)&&(n=li))}t.defaultEncoding=n}t.differences=r;t.baseEncodingName=g;t.hasEncoding=!!g||r.length>0;t.dict=e;t.toUnicode=await s;const C=await this.buildToUnicode(t);t.toUnicode=C;a&&(t.cidToGidMap=this.readCidToGidMap(a,C));return t}_simpleFontToUnicode(e,t=!1){assert(!e.composite,"Must be a simple font.");const i=[],a=e.defaultEncoding.slice(),s=e.baseEncodingName,r=e.differences;for(const e in r){const t=r[e];".notdef"!==t&&(a[e]=t)}const n=wi();for(const r in a){let g=a[r];if(""===g)continue;let o=n[g];if(void 0!==o){i[r]=String.fromCharCode(o);continue}let c=0;switch(g[0]){case"G":3===g.length&&(c=parseInt(g.substring(1),16));break;case"g":5===g.length&&(c=parseInt(g.substring(1),16));break;case"C":case"c":if(g.length>=3&&g.length<=4){const i=g.substring(1);if(t){c=parseInt(i,16);break}c=+i;if(Number.isNaN(c)&&Number.isInteger(parseInt(i,16)))return this._simpleFontToUnicode(e,!0)}break;case"u":o=getUnicodeForGlyph(g,n);-1!==o&&(c=o);break;default:switch(g){case"f_h":case"f_t":case"T_h":i[r]=g.replaceAll("_","");continue}}if(c>0&&c<=1114111&&Number.isInteger(c)){if(s&&c===+r){const e=getEncoding(s);if(e&&(g=e[r])){i[r]=String.fromCharCode(n[g]);continue}}i[r]=String.fromCodePoint(c)}}return i}async buildToUnicode(e){e.hasIncludedToUnicodeMap=e.toUnicode?.length>0;if(e.hasIncludedToUnicodeMap){!e.composite&&e.hasEncoding&&(e.fallbackToUnicode=this._simpleFontToUnicode(e));return e.toUnicode}if(!e.composite)return new ToUnicodeMap(this._simpleFontToUnicode(e));if(e.composite&&(e.cMap.builtInCMap&&!(e.cMap instanceof IdentityCMap)||"Adobe"===e.cidSystemInfo?.registry&&("GB1"===e.cidSystemInfo.ordering||"CNS1"===e.cidSystemInfo.ordering||"Japan1"===e.cidSystemInfo.ordering||"Korea1"===e.cidSystemInfo.ordering))){const{registry:t,ordering:i}=e.cidSystemInfo,a=Name.get(`${t}-${i}-UCS2`),s=await CMapFactory.create({encoding:a,fetchBuiltInCMap:this._fetchBuiltInCMapBound,useCMap:null}),r=[],n=[];e.cMap.forEach((function(e,t){if(t>65535)throw new FormatError("Max size of CID is 65,535");const i=s.lookup(t);if(i){n.length=0;for(let e=0,t=i.length;e>1;(0!==s||t.has(r))&&(i[r]=s)}return i}extractWidths(e,t,i){const a=this.xref;let s=[],r=0;const n=[];let g;if(i.composite){const t=e.get("DW");r="number"==typeof t?Math.ceil(t):1e3;const o=e.get("W");if(Array.isArray(o))for(let e=0,t=o.length;e{const t=o.get(e),s=new OperatorList;return a.getOperatorList({stream:t,task:i,resources:c,operatorList:s}).then((()=>{s.fnArray[0]===ue&&this._removeType3ColorOperators(s,E);C[e]=s.getIR();for(const e of s.dependencies)n.add(e)})).catch((function(t){warn(`Type3 font resource "${e}" is not available.`);const i=new OperatorList;C[e]=i.getIR()}))}));this.type3Loaded=g.then((()=>{r.charProcOperatorList=C;if(this._bbox){r.isCharBBox=!0;r.bbox=this._bbox}}));return this.type3Loaded}_removeType3ColorOperators(e,t=NaN){const i=Util.normalizeRect(e.argsArray[0].slice(2)),a=i[2]-i[0],s=i[3]-i[1],r=Math.hypot(a,s);if(0===a||0===s){e.fnArray.splice(0,1);e.argsArray.splice(0,1)}else if(0===t||Math.round(r/t)>=10){this._bbox||(this._bbox=[1/0,1/0,-1/0,-1/0]);this._bbox[0]=Math.min(this._bbox[0],i[0]);this._bbox[1]=Math.min(this._bbox[1],i[1]);this._bbox[2]=Math.max(this._bbox[2],i[2]);this._bbox[3]=Math.max(this._bbox[3],i[3])}let n=0,g=e.length;for(;n=LA&&r<=zA;if(s.variableArgs)g>n&&info(`Command ${a}: expected [0, ${n}] args, but received ${g} args.`);else{if(g!==n){const e=this.nonProcessedArgs;for(;g>n;){e.push(t.shift());g--}for(;gEvaluatorPreprocessor.MAX_INVALID_PATH_OPS)throw new FormatError(`Invalid ${e}`);warn(`Skipping ${e}`);null!==t&&(t.length=0);continue}}this.preprocessCommand(r,t);e.fn=r;e.args=t;return!0}if(i===Bt)return!1;if(null!==i){null===t&&(t=[]);t.push(i);if(t.length>33)throw new FormatError("Too many arguments")}}}preprocessCommand(e,t){switch(0|e){case MA:this.stateManager.save();break;case UA:this.stateManager.restore();break;case xA:this.stateManager.transform(t)}}}class DefaultAppearanceEvaluator extends EvaluatorPreprocessor{constructor(e){super(new StringStream(e))}parse(){const e={fn:0,args:[]},t={fontSize:0,fontName:"",fontColor:new Uint8ClampedArray(3)};try{for(;;){e.args.length=0;if(!this.read(e))break;if(0!==this.savedStatesDepth)continue;const{fn:i,args:a}=e;switch(0|i){case re:const[e,i]=a;e instanceof Name&&(t.fontName=e.name);"number"==typeof i&&i>0&&(t.fontSize=i);break;case Se:ColorSpace.singletons.rgb.getRgbItem(a,0,t.fontColor,0);break;case be:ColorSpace.singletons.gray.getRgbItem(a,0,t.fontColor,0);break;case Re:ColorSpace.singletons.cmyk.getRgbItem(a,0,t.fontColor,0)}}}catch(e){warn(`parseDefaultAppearance - ignoring errors: "${e}".`)}return t}}function parseDefaultAppearance(e){return new DefaultAppearanceEvaluator(e).parse()}class AppearanceStreamEvaluator extends EvaluatorPreprocessor{constructor(e,t,i){super(e);this.stream=e;this.evaluatorOptions=t;this.xref=i;this.resources=e.dict?.get("Resources")}parse(){const e={fn:0,args:[]};let t={scaleFactor:1,fontSize:0,fontName:"",fontColor:new Uint8ClampedArray(3),fillColorSpace:ColorSpace.singletons.gray},i=!1;const a=[];try{for(;;){e.args.length=0;if(i||!this.read(e))break;const{fn:s,args:r}=e;switch(0|s){case MA:a.push({scaleFactor:t.scaleFactor,fontSize:t.fontSize,fontName:t.fontName,fontColor:t.fontColor.slice(),fillColorSpace:t.fillColorSpace});break;case UA:t=a.pop()||t;break;case ce:t.scaleFactor*=Math.hypot(r[0],r[1]);break;case re:const[e,s]=r;e instanceof Name&&(t.fontName=e.name);"number"==typeof s&&s>0&&(t.fontSize=s*t.scaleFactor);break;case fe:t.fillColorSpace=ColorSpace.parse({cs:r[0],xref:this.xref,resources:this.resources,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:this._localColorSpaceCache});break;case ye:t.fillColorSpace.getRgbItem(r,0,t.fontColor,0);break;case Se:ColorSpace.singletons.rgb.getRgbItem(r,0,t.fontColor,0);break;case be:ColorSpace.singletons.gray.getRgbItem(r,0,t.fontColor,0);break;case Re:ColorSpace.singletons.cmyk.getRgbItem(r,0,t.fontColor,0);break;case he:case le:case Be:case Qe:i=!0}}}catch(e){warn(`parseAppearanceStream - ignoring errors: "${e}".`)}this.stream.reset();delete t.scaleFactor;delete t.fillColorSpace;return t}get _localColorSpaceCache(){return shadow(this,"_localColorSpaceCache",new LocalColorSpaceCache)}get _pdfFunctionFactory(){return shadow(this,"_pdfFunctionFactory",new PDFFunctionFactory({xref:this.xref,isEvalSupported:this.evaluatorOptions.isEvalSupported}))}}function getPdfColor(e,t){if(e[0]===e[1]&&e[1]===e[2]){return`${numberToString(e[0]/255)} ${t?"g":"G"}`}return Array.from(e,(e=>numberToString(e/255))).join(" ")+" "+(t?"rg":"RG")}class FakeUnicodeFont{constructor(e,t){this.xref=e;this.widths=null;this.firstChar=1/0;this.lastChar=-1/0;this.fontFamily=t;const i=new OffscreenCanvas(1,1);this.ctxMeasure=i.getContext("2d",{willReadFrequently:!0});FakeUnicodeFont._fontNameId||(FakeUnicodeFont._fontNameId=1);this.fontName=Name.get(`InvalidPDFjsFont_${t}_${FakeUnicodeFont._fontNameId++}`)}get fontDescriptorRef(){if(!FakeUnicodeFont._fontDescriptorRef){const e=new Dict(this.xref);e.set("Type",Name.get("FontDescriptor"));e.set("FontName",this.fontName);e.set("FontFamily","MyriadPro Regular");e.set("FontBBox",[0,0,0,0]);e.set("FontStretch",Name.get("Normal"));e.set("FontWeight",400);e.set("ItalicAngle",0);FakeUnicodeFont._fontDescriptorRef=this.xref.getNewPersistentRef(e)}return FakeUnicodeFont._fontDescriptorRef}get descendantFontRef(){const e=new Dict(this.xref);e.set("BaseFont",this.fontName);e.set("Type",Name.get("Font"));e.set("Subtype",Name.get("CIDFontType0"));e.set("CIDToGIDMap",Name.get("Identity"));e.set("FirstChar",this.firstChar);e.set("LastChar",this.lastChar);e.set("FontDescriptor",this.fontDescriptorRef);e.set("DW",1e3);const t=[],i=[...this.widths.entries()].sort();let a=null,s=null;for(const[e,r]of i)if(a)if(e===a+s.length)s.push(r);else{t.push(a,s);a=e;s=[r]}else{a=e;s=[r]}a&&t.push(a,s);e.set("W",t);const r=new Dict(this.xref);r.set("Ordering","Identity");r.set("Registry","Adobe");r.set("Supplement",0);e.set("CIDSystemInfo",r);return this.xref.getNewPersistentRef(e)}get baseFontRef(){const e=new Dict(this.xref);e.set("BaseFont",this.fontName);e.set("Type",Name.get("Font"));e.set("Subtype",Name.get("Type0"));e.set("Encoding",Name.get("Identity-H"));e.set("DescendantFonts",[this.descendantFontRef]);e.set("ToUnicode",Name.get("Identity-H"));return this.xref.getNewPersistentRef(e)}get resources(){const e=new Dict(this.xref),t=new Dict(this.xref);t.set(this.fontName.name,this.baseFontRef);e.set("Font",t);return e}_createContext(){this.widths=new Map;this.ctxMeasure.font=`1000px ${this.fontFamily}`;return this.ctxMeasure}createFontResources(e){const t=this._createContext();for(const i of e.split(/\r\n?|\n/))for(const e of i.split("")){const i=e.charCodeAt(0);if(this.widths.has(i))continue;const a=t.measureText(e),s=Math.ceil(a.width);this.widths.set(i,s);this.firstChar=Math.min(i,this.firstChar);this.lastChar=Math.max(i,this.lastChar)}return this.resources}static getFirstPositionInfo(e,t,i){const[a,n,g,o]=e;let c=g-a,C=o-n;t%180!=0&&([c,C]=[C,c]);const h=s*i;return{coords:[0,C+r*i-h],bbox:[0,0,c,C],matrix:0!==t?getRotationMatrix(t,C,h):void 0}}createAppearance(e,t,i,a,n,g){const o=this._createContext(),c=[];let C=-1/0;for(const t of e.split(/\r\n?|\n/)){c.push(t);const e=o.measureText(t).width;C=Math.max(C,e);for(const e of codePointIter(t)){const t=String.fromCodePoint(e);let i=this.widths.get(e);if(void 0===i){const a=o.measureText(t);i=Math.ceil(a.width);this.widths.set(e,i);this.firstChar=Math.min(e,this.firstChar);this.lastChar=Math.max(e,this.lastChar)}}}C*=a/1e3;const[h,l,Q,E]=t;let u=Q-h,d=E-l;i%180!=0&&([u,d]=[d,u]);let f=1;C>u&&(f=u/C);let p=1;const m=s*a,y=r*a,w=m*c.length;w>d&&(p=d/w);const D=a*Math.min(f,p),b=["q",`0 0 ${numberToString(u)} ${numberToString(d)} re W n`,"BT",`1 0 0 1 0 ${numberToString(d+y)} Tm 0 Tc ${getPdfColor(n,!0)}`,`/${this.fontName.name} ${numberToString(D)} Tf`],{resources:F}=this;if(1!==(g="number"==typeof g&&g>=0&&g<=1?g:1)){b.push("/R0 gs");const e=new Dict(this.xref),t=new Dict(this.xref);t.set("ca",g);t.set("CA",g);t.set("Type",Name.get("ExtGState"));e.set("R0",t);F.set("ExtGState",e)}const S=numberToString(m);for(const e of c)b.push(`0 -${S} Td <${stringToUTF16HexString(e)}> Tj`);b.push("ET","Q");const k=b.join("\n"),R=new Dict(this.xref);R.set("Subtype",Name.get("Form"));R.set("Type",Name.get("XObject"));R.set("BBox",[0,0,u,d]);R.set("Length",k.length);R.set("Resources",F);if(i){const e=getRotationMatrix(i,u,d);R.set("Matrix",e)}const N=new StringStream(k);N.dict=R;return N}}class NameOrNumberTree{constructor(e,t,i){this.root=e;this.xref=t;this._type=i}getAll(){const e=new Map;if(!this.root)return e;const t=this.xref,i=new RefSet;i.put(this.root);const a=[this.root];for(;a.length>0;){const s=t.fetchIfRef(a.shift());if(!(s instanceof Dict))continue;if(s.has("Kids")){const e=s.get("Kids");if(!Array.isArray(e))continue;for(const t of e){if(i.has(t))throw new FormatError(`Duplicate entry in "${this._type}" tree.`);a.push(t);i.put(t)}continue}const r=s.get(this._type);if(Array.isArray(r))for(let i=0,a=r.length;i10){warn(`Search depth limit reached for "${this._type}" tree.`);return null}const s=i.get("Kids");if(!Array.isArray(s))return null;let r=0,n=s.length-1;for(;r<=n;){const a=r+n>>1,g=t.fetchIfRef(s[a]),o=g.get("Limits");if(et.fetchIfRef(o[1]))){i=g;break}r=a+1}}if(r>n)return null}const s=i.get(this._type);if(Array.isArray(s)){let i=0,a=s.length-2;for(;i<=a;){const r=i+a>>1,n=r+(1&r),g=t.fetchIfRef(s[n]);if(eg))return s[n+1];i=n+2}}}return null}get(e){return this.xref.fetchIfRef(this.getRaw(e))}}class NameTree extends NameOrNumberTree{constructor(e,t){super(e,t,"Names")}}class NumberTree extends NameOrNumberTree{constructor(e,t){super(e,t,"Nums")}}function clearGlobalCaches(){!function clearPatternCaches(){Qa=Object.create(null)}();!function clearPrimitiveCaches(){Qt=Object.create(null);Et=Object.create(null);ut=Object.create(null)}();!function clearUnicodeCaches(){ki.clear()}();JpxImage.cleanup()}function pickPlatformItem(e){return e instanceof Dict?e.has("UF")?e.get("UF"):e.has("F")?e.get("F"):e.has("Unix")?e.get("Unix"):e.has("Mac")?e.get("Mac"):e.has("DOS")?e.get("DOS"):null:null}class FileSpec{#U=!1;constructor(e,t,i=!1){if(e instanceof Dict){this.xref=t;this.root=e;e.has("FS")&&(this.fs=e.get("FS"));e.has("RF")&&warn("Related file specifications are not supported");i||(e.has("EF")?this.#U=!0:warn("Non-embedded file specifications are not supported"))}}get filename(){let e="";const t=pickPlatformItem(this.root);t&&"string"==typeof t&&(e=stringToPDFString(t).replaceAll("\\\\","\\").replaceAll("\\/","/").replaceAll("\\","/"));return shadow(this,"filename",e||"unnamed")}get content(){if(!this.#U)return null;this._contentRef||=pickPlatformItem(this.root?.get("EF"));let e=null;if(this._contentRef){const t=this.xref.fetchIfRef(this._contentRef);t instanceof BaseStream?e=t.getBytes():warn("Embedded file specification points to non-existing/invalid content")}else warn("Embedded file specification does not have any content");return e}get description(){let e="";const t=this.root?.get("Desc");t&&"string"==typeof t&&(e=stringToPDFString(t));return shadow(this,"description",e)}get serializable(){return{rawFilename:this.filename,filename:(e=this.filename,e.substring(e.lastIndexOf("/")+1)),content:this.content,description:this.description};var e}}const ys=0,ws=-2,Ds=-3,bs=-4,Fs=-5,Ss=-6,ks=-9;function isWhitespace(e,t){const i=e[t];return" "===i||"\n"===i||"\r"===i||"\t"===i}class XMLParserBase{_resolveEntities(e){return e.replaceAll(/&([^;]+);/g,((e,t)=>{if("#x"===t.substring(0,2))return String.fromCodePoint(parseInt(t.substring(2),16));if("#"===t.substring(0,1))return String.fromCodePoint(parseInt(t.substring(1),10));switch(t){case"lt":return"<";case"gt":return">";case"amp":return"&";case"quot":return'"';case"apos":return"'"}return this.onResolveEntity(t)}))}_parseContent(e,t){const i=[];let a=t;function skipWs(){for(;a"!==e[a]&&"/"!==e[a];)++a;const s=e.substring(t,a);skipWs();for(;a"!==e[a]&&"/"!==e[a]&&"?"!==e[a];){skipWs();let t="",s="";for(;a"!==e[i]&&"?"!==e[i]&&"/"!==e[i];)++i;const a=e.substring(t,i);!function skipWs(){for(;i"!==e[i+1]);)++i;return{name:a,value:e.substring(s,i),parsed:i-t}}parseXml(e){let t=0;for(;t",i);if(t<0){this.onError(ks);return}this.onEndElement(e.substring(i,t));i=t+1;break;case"?":++i;const a=this._parseProcessingInstruction(e,i);if("?>"!==e.substring(i+a.parsed,i+a.parsed+2)){this.onError(Ds);return}this.onPi(a.name,a.value);i+=a.parsed+2;break;case"!":if("--"===e.substring(i+1,i+3)){t=e.indexOf("--\x3e",i+3);if(t<0){this.onError(Fs);return}this.onComment(e.substring(i+3,t));i=t+3}else if("[CDATA["===e.substring(i+1,i+8)){t=e.indexOf("]]>",i+8);if(t<0){this.onError(ws);return}this.onCdata(e.substring(i+8,t));i=t+3}else{if("DOCTYPE"!==e.substring(i+1,i+8)){this.onError(Ss);return}{const a=e.indexOf("[",i+8);let s=!1;t=e.indexOf(">",i+8);if(t<0){this.onError(bs);return}if(a>0&&t>a){t=e.indexOf("]>",i+8);if(t<0){this.onError(bs);return}s=!0}const r=e.substring(i+8,t+(s?1:0));this.onDoctype(r);i=t+(s?2:1)}}break;default:const s=this._parseContent(e,i);if(null===s){this.onError(Ss);return}let r=!1;if("/>"===e.substring(i+s.parsed,i+s.parsed+2))r=!0;else if(">"!==e.substring(i+s.parsed,i+s.parsed+1)){this.onError(ks);return}this.onBeginElement(s.name,s.attributes,r);i+=s.parsed+(r?2:1)}}else{for(;i0}searchNode(e,t){if(t>=e.length)return this;const i=e[t];if(i.name.startsWith("#")&&t0){a.push([s,0]);s=s.childNodes[0]}else{if(0===a.length)return null;for(;0!==a.length;){const[e,t]=a.pop(),i=t+1;if(i");for(const t of this.childNodes)t.dump(e);e.push(``)}else this.nodeValue?e.push(`>${encodeToXmlString(this.nodeValue)}`):e.push("/>")}else e.push(encodeToXmlString(this.nodeValue))}}class SimpleXMLParser extends XMLParserBase{constructor({hasAttributes:e=!1,lowerCaseName:t=!1}){super();this._currentFragment=null;this._stack=null;this._errorCode=ys;this._hasAttributes=e;this._lowerCaseName=t}parseFromString(e){this._currentFragment=[];this._stack=[];this._errorCode=ys;this.parseXml(e);if(this._errorCode!==ys)return;const[t]=this._currentFragment;return t?{documentElement:t}:void 0}onText(e){if(function isWhitespaceString(e){for(let t=0,i=e.length;t\\376\\377([^<]+)/g,(function(e,t){const i=t.replaceAll(/\\([0-3])([0-7])([0-7])/g,(function(e,t,i,a){return String.fromCharCode(64*t+8*i+1*a)})).replaceAll(/&(amp|apos|gt|lt|quot);/g,(function(e,t){switch(t){case"amp":return"&";case"apos":return"'";case"gt":return">";case"lt":return"<";case"quot":return'"'}throw new Error(`_repair: ${t} isn't defined.`)})),a=[">"];for(let e=0,t=i.length;e=32&&t<127&&60!==t&&62!==t&&38!==t?a.push(String.fromCharCode(t)):a.push("&#x"+(65536+t).toString(16).substring(1)+";")}return a.join("")}))}_getSequence(e){const t=e.nodeName;return"rdf:bag"!==t&&"rdf:seq"!==t&&"rdf:alt"!==t?null:e.childNodes.filter((e=>"rdf:li"===e.nodeName))}_parseArray(e){if(!e.hasChildNodes())return;const[t]=e.childNodes,i=this._getSequence(t)||[];this._metadataMap.set(e.nodeName,i.map((e=>e.textContent.trim())))}_parse(e){let t=e.documentElement;if("rdf:rdf"!==t.nodeName){t=t.firstChild;for(;t&&"rdf:rdf"!==t.nodeName;)t=t.nextSibling}if(t&&"rdf:rdf"===t.nodeName&&t.hasChildNodes())for(const e of t.childNodes)if("rdf:description"===e.nodeName)for(const t of e.childNodes){const e=t.nodeName;switch(e){case"#text":continue;case"dc:creator":case"dc:subject":this._parseArray(t);continue}this._metadataMap.set(e,t.textContent.trim())}}get serializable(){return{parsedData:this._metadataMap,rawData:this._data}}}const Rs=1,Ns=2,Gs=3,Ms=4,Us=5;class StructTreeRoot{constructor(e,t){this.dict=e;this.ref=t instanceof Ref?t:null;this.roleMap=new Map;this.structParentIds=null}init(){this.readRoleMap()}#x(e,t,i){if(!(e instanceof Ref)||t<0)return;this.structParentIds||=new RefSetCache;let a=this.structParentIds.get(e);if(!a){a=[];this.structParentIds.put(e,a)}a.push([t,i])}addAnnotationIdToPage(e,t){this.#x(e,t,Ms)}readRoleMap(){const e=this.dict.get("RoleMap");if(e instanceof Dict)for(const[t,i]of e)i instanceof Name&&this.roleMap.set(t,i.name)}static async canCreateStructureTree({catalogRef:e,pdfManager:t,newAnnotationsByPage:i}){if(!(e instanceof Ref)){warn("Cannot save the struct tree: no catalog reference.");return!1}let a=0,s=!0;for(const[e,r]of i){const{ref:i}=await t.getPage(e);if(!(i instanceof Ref)){warn(`Cannot save the struct tree: page ${e} has no ref.`);s=!0;break}for(const e of r)if(e.accessibilityData?.type){e.parentTreeId=a++;s=!1}}if(s){for(const e of i.values())for(const t of e)delete t.parentTreeId;return!1}return!0}static async createStructureTree({newAnnotationsByPage:e,xref:t,catalogRef:i,pdfManager:a,changes:s}){const r=a.catalog.cloneDict(),n=new RefSetCache;n.put(i,r);const g=t.getNewTemporaryRef();r.set("StructTreeRoot",g);const o=new Dict(t);o.set("Type",Name.get("StructTreeRoot"));const c=t.getNewTemporaryRef();o.set("ParentTree",c);const C=[];o.set("K",C);n.put(g,o);const h=new Dict(t),l=[];h.set("Nums",l);const Q=await this.#L({newAnnotationsByPage:e,structTreeRootRef:g,structTreeRoot:null,kids:C,nums:l,xref:t,pdfManager:a,changes:s,cache:n});o.set("ParentTreeNextKey",Q);n.put(c,h);for(const[e,t]of n.items())s.put(e,{data:t})}async canUpdateStructTree({pdfManager:e,xref:t,newAnnotationsByPage:i}){if(!this.ref){warn("Cannot update the struct tree: no root reference.");return!1}let a=this.dict.get("ParentTreeNextKey");if(!Number.isInteger(a)||a<0){warn("Cannot update the struct tree: invalid next key.");return!1}const s=this.dict.get("ParentTree");if(!(s instanceof Dict)){warn("Cannot update the struct tree: ParentTree isn't a dict.");return!1}const r=s.get("Nums");if(!Array.isArray(r)){warn("Cannot update the struct tree: nums isn't an array.");return!1}const n=new NumberTree(s,t);for(const t of i.keys()){const{pageDict:i}=await e.getPage(t);if(!i.has("StructParents"))continue;const a=i.get("StructParents");if(!Number.isInteger(a)||!Array.isArray(n.get(a))){warn(`Cannot save the struct tree: page ${t} has a wrong id.`);return!1}}let g=!0;for(const[t,s]of i){const{pageDict:i}=await e.getPage(t);StructTreeRoot.#H({elements:s,xref:this.dict.xref,pageDict:i,numberTree:n});for(const e of s)if(e.accessibilityData?.type){e.accessibilityData.structParent>=0||(e.parentTreeId=a++);g=!1}}if(g){for(const e of i.values())for(const t of e){delete t.parentTreeId;delete t.structTreeParent}return!1}return!0}async updateStructureTree({newAnnotationsByPage:e,pdfManager:t,changes:i}){const a=this.dict.xref,s=this.dict.clone(),r=this.ref,n=new RefSetCache;n.put(r,s);let g,o=s.getRaw("ParentTree");if(o instanceof Ref)g=a.fetch(o);else{g=o;o=a.getNewTemporaryRef();s.set("ParentTree",o)}g=g.clone();n.put(o,g);let c=g.getRaw("Nums"),C=null;if(c instanceof Ref){C=c;c=a.fetch(C)}c=c.slice();C||g.set("Nums",c);const h=await StructTreeRoot.#L({newAnnotationsByPage:e,structTreeRootRef:r,structTreeRoot:this,kids:null,nums:c,xref:a,pdfManager:t,changes:i,cache:n});if(-1!==h){s.set("ParentTreeNextKey",h);C&&n.put(C,c);for(const[e,t]of n.items())i.put(e,{data:t})}}static async#L({newAnnotationsByPage:e,structTreeRootRef:t,structTreeRoot:i,kids:a,nums:s,xref:r,pdfManager:n,changes:g,cache:o}){const c=Name.get("OBJR");let C,h=-1;for(const[l,Q]of e){const e=await n.getPage(l),{ref:E}=e,u=E instanceof Ref;for(const{accessibilityData:n,ref:d,parentTreeId:f,structTreeParent:p}of Q){if(!n?.type)continue;const{structParent:Q}=n;if(i&&Number.isInteger(Q)&&Q>=0){let t=(C||=new Map).get(l);if(void 0===t){t=new StructTreePage(i,e.pageDict).collectObjects(E);C.set(l,t)}const a=t?.get(Q);if(a){const e=r.fetch(a).clone();StructTreeRoot.#J(e,n);g.put(a,{data:e});continue}}h=Math.max(h,f);const m=r.getNewTemporaryRef(),y=new Dict(r);StructTreeRoot.#J(y,n);await this.#Y({structTreeParent:p,tagDict:y,newTagRef:m,structTreeRootRef:t,fallbackKids:a,xref:r,cache:o});const w=new Dict(r);y.set("K",w);w.set("Type",c);u&&w.set("Pg",E);w.set("Obj",d);o.put(m,y);s.push(f,m)}}return h+1}static#J(e,{type:t,title:i,lang:a,alt:s,expanded:r,actualText:n}){e.set("S",Name.get(t));i&&e.set("T",stringToAsciiOrUTF16BE(i));a&&e.set("Lang",stringToAsciiOrUTF16BE(a));s&&e.set("Alt",stringToAsciiOrUTF16BE(s));r&&e.set("E",stringToAsciiOrUTF16BE(r));n&&e.set("ActualText",stringToAsciiOrUTF16BE(n))}static#H({elements:e,xref:t,pageDict:i,numberTree:a}){const s=new Map;for(const t of e)if(t.structTreeParentId){const e=parseInt(t.structTreeParentId.split("_mc")[1],10);let i=s.get(e);if(!i){i=[];s.set(e,i)}i.push(t)}const r=i.get("StructParents");if(!Number.isInteger(r))return;const n=a.get(r),updateElement=(e,i,a)=>{const r=s.get(e);if(r){const e=i.getRaw("P"),s=t.fetchIfRef(e);if(e instanceof Ref&&s instanceof Dict){const e={ref:a,dict:i};for(const t of r)t.structTreeParent=e}return!0}return!1};for(const e of n){if(!(e instanceof Ref))continue;const i=t.fetch(e),a=i.get("K");if(Number.isInteger(a))updateElement(a,i,e);else if(Array.isArray(a))for(let s of a){s=t.fetchIfRef(s);if(Number.isInteger(s)&&updateElement(s,i,e))break;if(!(s instanceof Dict))continue;if(!isName(s.get("Type"),"MCR"))break;const a=s.get("MCID");if(Number.isInteger(a)&&updateElement(a,i,e))break}}}static async#Y({structTreeParent:e,tagDict:t,newTagRef:i,structTreeRootRef:a,fallbackKids:s,xref:r,cache:n}){let g,o=null;if(e){({ref:o}=e);g=e.dict.getRaw("P")||a}else g=a;t.set("P",g);const c=r.fetchIfRef(g);if(!c){s.push(i);return}let C=n.get(g);if(!C){C=c.clone();n.put(g,C)}const h=C.getRaw("K");let l=h instanceof Ref?n.get(h):null;if(!l){l=r.fetchIfRef(h);l=Array.isArray(l)?l.slice():[h];const e=r.getNewTemporaryRef();C.set("K",e);n.put(e,l)}const Q=l.indexOf(o);l.splice(Q>=0?Q+1:l.length,0,i)}}class StructElementNode{constructor(e,t){this.tree=e;this.dict=t;this.kids=[];this.parseKids()}get role(){const e=this.dict.get("S"),t=e instanceof Name?e.name:"",{root:i}=this.tree;return i.roleMap.has(t)?i.roleMap.get(t):t}parseKids(){let e=null;const t=this.dict.getRaw("Pg");t instanceof Ref&&(e=t.toString());const i=this.dict.get("K");if(Array.isArray(i))for(const t of i){const i=this.parseKid(e,t);i&&this.kids.push(i)}else{const t=this.parseKid(e,i);t&&this.kids.push(t)}}parseKid(e,t){if(Number.isInteger(t))return this.tree.pageDict.objId!==e?null:new StructElement({type:Rs,mcid:t,pageObjId:e});let i=null;t instanceof Ref?i=this.dict.xref.fetch(t):t instanceof Dict&&(i=t);if(!i)return null;const a=i.getRaw("Pg");a instanceof Ref&&(e=a.toString());const s=i.get("Type")instanceof Name?i.get("Type").name:null;if("MCR"===s){if(this.tree.pageDict.objId!==e)return null;const t=i.getRaw("Stm");return new StructElement({type:Ns,refObjId:t instanceof Ref?t.toString():null,pageObjId:e,mcid:i.get("MCID")})}if("OBJR"===s){if(this.tree.pageDict.objId!==e)return null;const t=i.getRaw("Obj");return new StructElement({type:Gs,refObjId:t instanceof Ref?t.toString():null,pageObjId:e})}return new StructElement({type:Us,dict:i})}}class StructElement{constructor({type:e,dict:t=null,mcid:i=null,pageObjId:a=null,refObjId:s=null}){this.type=e;this.dict=t;this.mcid=i;this.pageObjId=a;this.refObjId=s;this.parentNode=null}}class StructTreePage{constructor(e,t){this.root=e;this.rootDict=e?e.dict:null;this.pageDict=t;this.nodes=[]}collectObjects(e){if(!(this.root&&this.rootDict&&e instanceof Ref))return null;const t=this.rootDict.get("ParentTree");if(!t)return null;const i=this.root.structParentIds?.get(e);if(!i)return null;const a=new Map,s=new NumberTree(t,this.rootDict.xref);for(const[e]of i){const t=s.getRaw(e);t instanceof Ref&&a.set(e,t)}return a}parse(e){if(!(this.root&&this.rootDict&&e instanceof Ref))return;const t=this.rootDict.get("ParentTree");if(!t)return;const i=this.pageDict.get("StructParents"),a=this.root.structParentIds?.get(e);if(!Number.isInteger(i)&&!a)return;const s=new Map,r=new NumberTree(t,this.rootDict.xref);if(Number.isInteger(i)){const e=r.get(i);if(Array.isArray(e))for(const t of e)t instanceof Ref&&this.addNode(this.rootDict.xref.fetch(t),s)}if(a)for(const[e,t]of a){const i=r.get(e);if(i){const e=this.addNode(this.rootDict.xref.fetchIfRef(i),s);1===e?.kids?.length&&e.kids[0].type===Gs&&(e.kids[0].type=t)}}}addNode(e,t,i=0){if(i>40){warn("StructTree MAX_DEPTH reached.");return null}if(!(e instanceof Dict))return null;if(t.has(e))return t.get(e);const a=new StructElementNode(this,e);t.set(e,a);const s=e.get("P");if(!s||isName(s.get("Type"),"StructTreeRoot")){this.addTopLevelNode(e,a)||t.delete(e);return a}const r=this.addNode(s,t,i+1);if(!r)return a;let n=!1;for(const t of r.kids)if(t.type===Us&&t.dict===e){t.parentNode=a;n=!0}n||t.delete(e);return a}addTopLevelNode(e,t){const i=this.rootDict.get("K");if(!i)return!1;if(i instanceof Dict){if(i.objId!==e.objId)return!1;this.nodes[0]=t;return!0}if(!Array.isArray(i))return!0;let a=!1;for(let s=0;s40){warn("StructTree too deep to be fully serialized.");return}const a=Object.create(null);a.role=e.role;a.children=[];t.children.push(a);let s=e.dict.get("Alt");"string"!=typeof s&&(s=e.dict.get("ActualText"));"string"==typeof s&&(a.alt=stringToPDFString(s));const r=e.dict.get("A");if(r instanceof Dict){const e=lookupNormalRect(r.getArray("BBox"),null);if(e)a.bbox=e;else{const e=r.get("Width"),t=r.get("Height");"number"==typeof e&&e>0&&"number"==typeof t&&t>0&&(a.bbox=[0,0,e,t])}}const n=e.dict.get("Lang");"string"==typeof n&&(a.lang=stringToPDFString(n));for(const t of e.kids){const e=t.type===Us?t.parentNode:null;e?nodeToSerializable(e,a,i+1):t.type===Rs||t.type===Ns?a.children.push({type:"content",id:`p${t.pageObjId}_mc${t.mcid}`}):t.type===Gs?a.children.push({type:"object",id:t.refObjId}):t.type===Ms&&a.children.push({type:"annotation",id:`pdfjs_internal_id_${t.refObjId}`})}}const e=Object.create(null);e.children=[];e.role="Root";for(const t of this.nodes)t&&nodeToSerializable(t,e);return e}}function isValidExplicitDest(e){if(!Array.isArray(e)||e.length<2)return!1;const[t,i,...a]=e;if(!(t instanceof Ref||Number.isInteger(t)))return!1;if(!(i instanceof Name))return!1;const s=a.length;let r=!0;switch(i.name){case"XYZ":if(s<2||s>3)return!1;break;case"Fit":case"FitB":return 0===s;case"FitH":case"FitBH":case"FitV":case"FitBV":if(s>1)return!1;break;case"FitR":if(4!==s)return!1;r=!1;break;default:return!1}for(const e of a)if(!("number"==typeof e||r&&null===e))return!1;return!0}function fetchDest(e){e instanceof Dict&&(e=e.get("D"));return isValidExplicitDest(e)?e:null}function fetchRemoteDest(e){let t=e.get("D");if(t){t instanceof Name&&(t=t.name);if("string"==typeof t)return stringToPDFString(t);if(isValidExplicitDest(t))return JSON.stringify(t)}return null}class Catalog{constructor(e,t){this.pdfManager=e;this.xref=t;this._catDict=t.getCatalogObj();if(!(this._catDict instanceof Dict))throw new FormatError("Catalog object is not a dictionary.");this.toplevelPagesDict;this._actualNumPages=null;this.fontCache=new RefSetCache;this.builtInCMapCache=new Map;this.standardFontDataCache=new Map;this.globalImageCache=new GlobalImageCache;this.pageKidsCountCache=new RefSetCache;this.pageIndexCache=new RefSetCache;this.pageDictCache=new RefSetCache;this.nonBlendModesSet=new RefSet;this.systemFontCache=new Map}cloneDict(){return this._catDict.clone()}get version(){const e=this._catDict.get("Version");if(e instanceof Name){if(ft.test(e.name))return shadow(this,"version",e.name);warn(`Invalid PDF catalog version: ${e.name}`)}return shadow(this,"version",null)}get lang(){const e=this._catDict.get("Lang");return shadow(this,"lang",e&&"string"==typeof e?stringToPDFString(e):null)}get needsRendering(){const e=this._catDict.get("NeedsRendering");return shadow(this,"needsRendering","boolean"==typeof e&&e)}get collection(){let e=null;try{const t=this._catDict.get("Collection");t instanceof Dict&&t.size>0&&(e=t)}catch(e){if(e instanceof MissingDataException)throw e;info("Cannot fetch Collection entry; assuming no collection is present.")}return shadow(this,"collection",e)}get acroForm(){let e=null;try{const t=this._catDict.get("AcroForm");t instanceof Dict&&t.size>0&&(e=t)}catch(e){if(e instanceof MissingDataException)throw e;info("Cannot fetch AcroForm entry; assuming no forms are present.")}return shadow(this,"acroForm",e)}get acroFormRef(){const e=this._catDict.getRaw("AcroForm");return shadow(this,"acroFormRef",e instanceof Ref?e:null)}get metadata(){const e=this._catDict.getRaw("Metadata");if(!(e instanceof Ref))return shadow(this,"metadata",null);let t=null;try{const i=this.xref.fetch(e,!this.xref.encrypt?.encryptMetadata);if(i instanceof BaseStream&&i.dict instanceof Dict){const e=i.dict.get("Type"),a=i.dict.get("Subtype");if(isName(e,"Metadata")&&isName(a,"XML")){const e=stringToUTF8String(i.getString());e&&(t=new MetadataParser(e).serializable)}}}catch(e){if(e instanceof MissingDataException)throw e;info(`Skipping invalid Metadata: "${e}".`)}return shadow(this,"metadata",t)}get markInfo(){let e=null;try{e=this._readMarkInfo()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read mark info.")}return shadow(this,"markInfo",e)}_readMarkInfo(){const e=this._catDict.get("MarkInfo");if(!(e instanceof Dict))return null;const t={Marked:!1,UserProperties:!1,Suspects:!1};for(const i in t){const a=e.get(i);"boolean"==typeof a&&(t[i]=a)}return t}get structTreeRoot(){let e=null;try{e=this._readStructTreeRoot()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable read to structTreeRoot info.")}return shadow(this,"structTreeRoot",e)}_readStructTreeRoot(){const e=this._catDict.getRaw("StructTreeRoot"),t=this.xref.fetchIfRef(e);if(!(t instanceof Dict))return null;const i=new StructTreeRoot(t,e);i.init();return i}get toplevelPagesDict(){const e=this._catDict.get("Pages");if(!(e instanceof Dict))throw new FormatError("Invalid top-level pages dictionary.");return shadow(this,"toplevelPagesDict",e)}get documentOutline(){let e=null;try{e=this._readDocumentOutline()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read document outline.")}return shadow(this,"documentOutline",e)}_readDocumentOutline(){let e=this._catDict.get("Outlines");if(!(e instanceof Dict))return null;e=e.getRaw("First");if(!(e instanceof Ref))return null;const t={items:[]},i=[{obj:e,parent:t}],a=new RefSet;a.put(e);const s=this.xref,r=new Uint8ClampedArray(3);for(;i.length>0;){const t=i.shift(),n=s.fetchIfRef(t.obj);if(null===n)continue;n.has("Title")||warn("Invalid outline item encountered.");const g={url:null,dest:null,action:null};Catalog.parseDestDictionary({destDict:n,resultObj:g,docBaseUrl:this.baseUrl,docAttachments:this.attachments});const o=n.get("Title"),c=n.get("F")||0,C=n.getArray("C"),h=n.get("Count");let l=r;!isNumberArray(C,3)||0===C[0]&&0===C[1]&&0===C[2]||(l=ColorSpace.singletons.rgb.getRgb(C,0));const Q={action:g.action,attachment:g.attachment,dest:g.dest,url:g.url,unsafeUrl:g.unsafeUrl,newWindow:g.newWindow,setOCGState:g.setOCGState,title:"string"==typeof o?stringToPDFString(o):"",color:l,count:Number.isInteger(h)?h:void 0,bold:!!(2&c),italic:!!(1&c),items:[]};t.parent.items.push(Q);e=n.getRaw("First");if(e instanceof Ref&&!a.has(e)){i.push({obj:e,parent:Q});a.put(e)}e=n.getRaw("Next");if(e instanceof Ref&&!a.has(e)){i.push({obj:e,parent:t.parent});a.put(e)}}return t.items.length>0?t.items:null}get permissions(){let e=null;try{e=this._readPermissions()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read permissions.")}return shadow(this,"permissions",e)}_readPermissions(){const e=this.xref.trailer.get("Encrypt");if(!(e instanceof Dict))return null;let t=e.get("P");if("number"!=typeof t)return null;t+=2**32;const i=[];for(const e in y){const a=y[e];t&a&&i.push(a)}return i}get optionalContentConfig(){let e=null;try{const t=this._catDict.get("OCProperties");if(!t)return shadow(this,"optionalContentConfig",null);const i=t.get("D");if(!i)return shadow(this,"optionalContentConfig",null);const a=t.get("OCGs");if(!Array.isArray(a))return shadow(this,"optionalContentConfig",null);const s=new RefSetCache;for(const e of a)e instanceof Ref&&!s.has(e)&&s.put(e,this.#v(e));e=this.#K(i,s)}catch(e){if(e instanceof MissingDataException)throw e;warn(`Unable to read optional content config: ${e}`)}return shadow(this,"optionalContentConfig",e)}#v(e){const t=this.xref.fetch(e),i={id:e.toString(),name:null,intent:null,usage:{print:null,view:null},rbGroups:[]},a=t.get("Name");"string"==typeof a&&(i.name=stringToPDFString(a));let s=t.getArray("Intent");Array.isArray(s)||(s=[s]);s.every((e=>e instanceof Name))&&(i.intent=s.map((e=>e.name)));const r=t.get("Usage");if(!(r instanceof Dict))return i;const n=i.usage,g=r.get("Print");if(g instanceof Dict){const e=g.get("PrintState");if(e instanceof Name)switch(e.name){case"ON":case"OFF":n.print={printState:e.name}}}const o=r.get("View");if(o instanceof Dict){const e=o.get("ViewState");if(e instanceof Name)switch(e.name){case"ON":case"OFF":n.view={viewState:e.name}}}return i}#K(e,t){function parseOnOff(e){const i=[];if(Array.isArray(e))for(const a of e)a instanceof Ref&&t.has(a)&&i.push(a.toString());return i}function parseOrder(e,i=0){if(!Array.isArray(e))return null;const s=[];for(const r of e){if(r instanceof Ref&&t.has(r)){a.put(r);s.push(r.toString());continue}const e=parseNestedOrder(r,i);e&&s.push(e)}if(i>0)return s;const r=[];for(const[e]of t.items())a.has(e)||r.push(e.toString());r.length&&s.push({name:null,order:r});return s}function parseNestedOrder(e,t){if(++t>s){warn("parseNestedOrder - reached MAX_NESTED_LEVELS.");return null}const a=i.fetchIfRef(e);if(!Array.isArray(a))return null;const r=i.fetchIfRef(a[0]);if("string"!=typeof r)return null;const n=parseOrder(a.slice(1),t);return n?.length?{name:stringToPDFString(r),order:n}:null}const i=this.xref,a=new RefSet,s=10;!function parseRBGroups(e){if(Array.isArray(e))for(const a of e){const e=i.fetchIfRef(a);if(!Array.isArray(e)||!e.length)continue;const s=new Set;for(const i of e)if(i instanceof Ref&&t.has(i)&&!s.has(i.toString())){s.add(i.toString());t.get(i).rbGroups.push(s)}}}(e.get("RBGroups"));return{name:"string"==typeof e.get("Name")?stringToPDFString(e.get("Name")):null,creator:"string"==typeof e.get("Creator")?stringToPDFString(e.get("Creator")):null,baseState:e.get("BaseState")instanceof Name?e.get("BaseState").name:null,on:parseOnOff(e.get("ON")),off:parseOnOff(e.get("OFF")),order:parseOrder(e.get("Order")),groups:[...t]}}setActualNumPages(e=null){this._actualNumPages=e}get hasActualNumPages(){return null!==this._actualNumPages}get _pagesCount(){const e=this.toplevelPagesDict.get("Count");if(!Number.isInteger(e))throw new FormatError("Page count in top-level pages dictionary is not an integer.");return shadow(this,"_pagesCount",e)}get numPages(){return this.hasActualNumPages?this._actualNumPages:this._pagesCount}get destinations(){const e=this._readDests(),t=Object.create(null);if(e instanceof NameTree)for(const[i,a]of e.getAll()){const e=fetchDest(a);e&&(t[stringToPDFString(i)]=e)}else if(e instanceof Dict)for(const[i,a]of e){const e=fetchDest(a);e&&(t[i]=e)}return shadow(this,"destinations",t)}getDestination(e){const t=this._readDests();if(t instanceof NameTree){const i=fetchDest(t.get(e));if(i)return i;const a=this.destinations[e];if(a){warn(`Found "${e}" at an incorrect position in the NameTree.`);return a}}else if(t instanceof Dict){const i=fetchDest(t.get(e));if(i)return i}return null}_readDests(){const e=this._catDict.get("Names");return e?.has("Dests")?new NameTree(e.getRaw("Dests"),this.xref):this._catDict.has("Dests")?this._catDict.get("Dests"):void 0}get pageLabels(){let e=null;try{e=this._readPageLabels()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read page labels.")}return shadow(this,"pageLabels",e)}_readPageLabels(){const e=this._catDict.getRaw("PageLabels");if(!e)return null;const t=new Array(this.numPages);let i=null,a="";const s=new NumberTree(e,this.xref).getAll();let r="",n=1;for(let e=0,g=this.numPages;e=1))throw new FormatError("Invalid start in PageLabel dictionary.");n=e}else n=1}switch(i){case"D":r=n;break;case"R":case"r":r=toRomanNumerals(n,"r"===i);break;case"A":case"a":const e=26,t="a"===i?97:65,a=n-1;r=String.fromCharCode(t+a%e).repeat(Math.floor(a/e)+1);break;default:if(i)throw new FormatError(`Invalid style "${i}" in PageLabel dictionary.`);r=""}t[e]=a+r;n++}return t}get pageLayout(){const e=this._catDict.get("PageLayout");let t="";if(e instanceof Name)switch(e.name){case"SinglePage":case"OneColumn":case"TwoColumnLeft":case"TwoColumnRight":case"TwoPageLeft":case"TwoPageRight":t=e.name}return shadow(this,"pageLayout",t)}get pageMode(){const e=this._catDict.get("PageMode");let t="UseNone";if(e instanceof Name)switch(e.name){case"UseNone":case"UseOutlines":case"UseThumbs":case"FullScreen":case"UseOC":case"UseAttachments":t=e.name}return shadow(this,"pageMode",t)}get viewerPreferences(){const e=this._catDict.get("ViewerPreferences");if(!(e instanceof Dict))return shadow(this,"viewerPreferences",null);let t=null;for(const i of e.getKeys()){const a=e.get(i);let s;switch(i){case"HideToolbar":case"HideMenubar":case"HideWindowUI":case"FitWindow":case"CenterWindow":case"DisplayDocTitle":case"PickTrayByPDFSize":"boolean"==typeof a&&(s=a);break;case"NonFullScreenPageMode":if(a instanceof Name)switch(a.name){case"UseNone":case"UseOutlines":case"UseThumbs":case"UseOC":s=a.name;break;default:s="UseNone"}break;case"Direction":if(a instanceof Name)switch(a.name){case"L2R":case"R2L":s=a.name;break;default:s="L2R"}break;case"ViewArea":case"ViewClip":case"PrintArea":case"PrintClip":if(a instanceof Name)switch(a.name){case"MediaBox":case"CropBox":case"BleedBox":case"TrimBox":case"ArtBox":s=a.name;break;default:s="CropBox"}break;case"PrintScaling":if(a instanceof Name)switch(a.name){case"None":case"AppDefault":s=a.name;break;default:s="AppDefault"}break;case"Duplex":if(a instanceof Name)switch(a.name){case"Simplex":case"DuplexFlipShortEdge":case"DuplexFlipLongEdge":s=a.name;break;default:s="None"}break;case"PrintPageRange":if(Array.isArray(a)&&a.length%2==0){a.every(((e,t,i)=>Number.isInteger(e)&&e>0&&(0===t||e>=i[t-1])&&e<=this.numPages))&&(s=a)}break;case"NumCopies":Number.isInteger(a)&&a>0&&(s=a);break;default:warn(`Ignoring non-standard key in ViewerPreferences: ${i}.`);continue}if(void 0!==s){t||(t=Object.create(null));t[i]=s}else warn(`Bad value, for key "${i}", in ViewerPreferences: ${a}.`)}return shadow(this,"viewerPreferences",t)}get openAction(){const e=this._catDict.get("OpenAction"),t=Object.create(null);if(e instanceof Dict){const i=new Dict(this.xref);i.set("A",e);const a={url:null,dest:null,action:null};Catalog.parseDestDictionary({destDict:i,resultObj:a});Array.isArray(a.dest)?t.dest=a.dest:a.action&&(t.action=a.action)}else Array.isArray(e)&&(t.dest=e);return shadow(this,"openAction",objectSize(t)>0?t:null)}get attachments(){const e=this._catDict.get("Names");let t=null;if(e instanceof Dict&&e.has("EmbeddedFiles")){const i=new NameTree(e.getRaw("EmbeddedFiles"),this.xref);for(const[e,a]of i.getAll()){const i=new FileSpec(a,this.xref);t||(t=Object.create(null));t[stringToPDFString(e)]=i.serializable}}return shadow(this,"attachments",t)}get xfaImages(){const e=this._catDict.get("Names");let t=null;if(e instanceof Dict&&e.has("XFAImages")){const i=new NameTree(e.getRaw("XFAImages"),this.xref);for(const[e,a]of i.getAll()){t||(t=new Dict(this.xref));t.set(stringToPDFString(e),a)}}return shadow(this,"xfaImages",t)}_collectJavaScript(){const e=this._catDict.get("Names");let t=null;function appendIfJavaScriptDict(e,i){if(!(i instanceof Dict))return;if(!isName(i.get("S"),"JavaScript"))return;let a=i.get("JS");if(a instanceof BaseStream)a=a.getString();else if("string"!=typeof a)return;a=stringToPDFString(a).replaceAll("\0","");a&&(t||=new Map).set(e,a)}if(e instanceof Dict&&e.has("JavaScript")){const t=new NameTree(e.getRaw("JavaScript"),this.xref);for(const[e,i]of t.getAll())appendIfJavaScriptDict(stringToPDFString(e),i)}const i=this._catDict.get("OpenAction");i&&appendIfJavaScriptDict("OpenAction",i);return t}get jsActions(){const e=this._collectJavaScript();let t=collectActions(this.xref,this._catDict,fA);if(e){t||=Object.create(null);for(const[i,a]of e)i in t?t[i].push(a):t[i]=[a]}return shadow(this,"jsActions",t)}async fontFallback(e,t){const i=await Promise.all(this.fontCache);for(const a of i)if(a.loadedName===e){a.fallback(t);return}}async cleanup(e=!1){clearGlobalCaches();this.globalImageCache.clear(e);this.pageKidsCountCache.clear();this.pageIndexCache.clear();this.pageDictCache.clear();this.nonBlendModesSet.clear();const t=await Promise.all(this.fontCache);for(const{dict:e}of t)delete e.cacheKey;this.fontCache.clear();this.builtInCMapCache.clear();this.standardFontDataCache.clear();this.systemFontCache.clear()}async getPageDict(e){const t=[this.toplevelPagesDict],i=new RefSet,a=this._catDict.getRaw("Pages");a instanceof Ref&&i.put(a);const s=this.xref,r=this.pageKidsCountCache,n=this.pageIndexCache,g=this.pageDictCache;let o=0;for(;t.length;){const a=t.pop();if(a instanceof Ref){const c=r.get(a);if(c>=0&&o+c<=e){o+=c;continue}if(i.has(a))throw new FormatError("Pages tree contains circular reference.");i.put(a);const C=await(g.get(a)||s.fetchAsync(a));if(C instanceof Dict){let t=C.getRaw("Type");t instanceof Ref&&(t=await s.fetchAsync(t));if(isName(t,"Page")||!C.has("Kids")){r.has(a)||r.put(a,1);n.has(a)||n.put(a,o);if(o===e)return[C,a];o++;continue}}t.push(C);continue}if(!(a instanceof Dict))throw new FormatError("Page dictionary kid reference points to wrong type of object.");const{objId:c}=a;let C=a.getRaw("Count");C instanceof Ref&&(C=await s.fetchAsync(C));if(Number.isInteger(C)&&C>=0){c&&!r.has(c)&&r.put(c,C);if(o+C<=e){o+=C;continue}}let h=a.getRaw("Kids");h instanceof Ref&&(h=await s.fetchAsync(h));if(!Array.isArray(h)){let t=a.getRaw("Type");t instanceof Ref&&(t=await s.fetchAsync(t));if(isName(t,"Page")||!a.has("Kids")){if(o===e)return[a,null];o++;continue}throw new FormatError("Page dictionary kids object is not an array.")}for(let e=h.length-1;e>=0;e--){const i=h[e];t.push(i);a===this.toplevelPagesDict&&i instanceof Ref&&!g.has(i)&&g.put(i,s.fetchAsync(i))}}throw new Error(`Page index ${e} not found.`)}async getAllPageDicts(e=!1){const{ignoreErrors:t}=this.pdfManager.evaluatorOptions,i=[{currentNode:this.toplevelPagesDict,posInKids:0}],a=new RefSet,s=this._catDict.getRaw("Pages");s instanceof Ref&&a.put(s);const r=new Map,n=this.xref,g=this.pageIndexCache;let o=0;function addPageDict(e,t){t&&!g.has(t)&&g.put(t,o);r.set(o++,[e,t])}function addPageError(i){if(i instanceof XRefEntryException&&!e)throw i;if(e&&t&&0===o){warn(`getAllPageDicts - Skipping invalid first page: "${i}".`);i=Dict.empty}r.set(o++,[i,null])}for(;i.length>0;){const e=i.at(-1),{currentNode:t,posInKids:s}=e;let r=t.getRaw("Kids");if(r instanceof Ref)try{r=await n.fetchAsync(r)}catch(e){addPageError(e);break}if(!Array.isArray(r)){addPageError(new FormatError("Page dictionary kids object is not an array."));break}if(s>=r.length){i.pop();continue}const g=r[s];let o;if(g instanceof Ref){if(a.has(g)){addPageError(new FormatError("Pages tree contains circular reference."));break}a.put(g);try{o=await n.fetchAsync(g)}catch(e){addPageError(e);break}}else o=g;if(!(o instanceof Dict)){addPageError(new FormatError("Page dictionary kid reference points to wrong type of object."));break}let c=o.getRaw("Type");if(c instanceof Ref)try{c=await n.fetchAsync(c)}catch(e){addPageError(e);break}isName(c,"Page")||!o.has("Kids")?addPageDict(o,g instanceof Ref?g:null):i.push({currentNode:o,posInKids:0});e.posInKids++}return r}getPageIndex(e){const t=this.pageIndexCache.get(e);if(void 0!==t)return Promise.resolve(t);const i=this.xref;let a=0;const next=t=>function pagesBeforeRef(t){let a,s=0;return i.fetchAsync(t).then((function(i){if(isRefsEqual(t,e)&&!isDict(i,"Page")&&!(i instanceof Dict&&!i.has("Type")&&i.has("Contents")))throw new FormatError("The reference does not point to a /Page dictionary.");if(!i)return null;if(!(i instanceof Dict))throw new FormatError("Node must be a dictionary.");a=i.getRaw("Parent");return i.getAsync("Parent")})).then((function(e){if(!e)return null;if(!(e instanceof Dict))throw new FormatError("Parent must be a dictionary.");return e.getAsync("Kids")})).then((function(e){if(!e)return null;const r=[];let n=!1;for(const a of e){if(!(a instanceof Ref))throw new FormatError("Kid must be a reference.");if(isRefsEqual(a,t)){n=!0;break}r.push(i.fetchAsync(a).then((function(e){if(!(e instanceof Dict))throw new FormatError("Kid node must be a dictionary.");e.has("Count")?s+=e.get("Count"):s++})))}if(!n)throw new FormatError("Kid reference not found in parent's kids.");return Promise.all(r).then((function(){return[s,a]}))}))}(t).then((t=>{if(!t){this.pageIndexCache.put(e,a);return a}const[i,s]=t;a+=i;return next(s)}));return next(e)}get baseUrl(){const e=this._catDict.get("URI");if(e instanceof Dict){const t=e.get("Base");if("string"==typeof t){const e=createValidAbsoluteUrl(t,null,{tryConvertEncoding:!0});if(e)return shadow(this,"baseUrl",e.href)}}return shadow(this,"baseUrl",this.pdfManager.docBaseUrl)}static parseDestDictionary({destDict:e,resultObj:t,docBaseUrl:i=null,docAttachments:a=null}){if(!(e instanceof Dict)){warn("parseDestDictionary: `destDict` must be a dictionary.");return}let s,r,n=e.get("A");if(!(n instanceof Dict))if(e.has("Dest"))n=e.get("Dest");else{n=e.get("AA");n instanceof Dict&&(n.has("D")?n=n.get("D"):n.has("U")&&(n=n.get("U")))}if(n instanceof Dict){const e=n.get("S");if(!(e instanceof Name)){warn("parseDestDictionary: Invalid type in Action dictionary.");return}const i=e.name;switch(i){case"ResetForm":const e=n.get("Flags"),g=!(1&("number"==typeof e?e:0)),o=[],c=[];for(const e of n.get("Fields")||[])e instanceof Ref?c.push(e.toString()):"string"==typeof e&&o.push(stringToPDFString(e));t.resetForm={fields:o,refs:c,include:g};break;case"URI":s=n.get("URI");s instanceof Name&&(s="/"+s.name);break;case"GoTo":r=n.get("D");break;case"Launch":case"GoToR":const C=n.get("F");if(C instanceof Dict){const e=new FileSpec(C,null,!0),{rawFilename:t}=e.serializable;s=t}else"string"==typeof C&&(s=C);const h=fetchRemoteDest(n);h&&"string"==typeof s&&(s=s.split("#",1)[0]+"#"+h);const l=n.get("NewWindow");"boolean"==typeof l&&(t.newWindow=l);break;case"GoToE":const Q=n.get("T");let E;if(a&&Q instanceof Dict){const e=Q.get("R"),t=Q.get("N");isName(e,"C")&&"string"==typeof t&&(E=a[stringToPDFString(t)])}if(E){t.attachment=E;const e=fetchRemoteDest(n);e&&(t.attachmentDest=e)}else warn('parseDestDictionary - unimplemented "GoToE" action.');break;case"Named":const u=n.get("N");u instanceof Name&&(t.action=u.name);break;case"SetOCGState":const d=n.get("State"),f=n.get("PreserveRB");if(!Array.isArray(d)||0===d.length)break;const p=[];for(const e of d)if(e instanceof Name)switch(e.name){case"ON":case"OFF":case"Toggle":p.push(e.name)}else e instanceof Ref&&p.push(e.toString());if(p.length!==d.length)break;t.setOCGState={state:p,preserveRB:"boolean"!=typeof f||f};break;case"JavaScript":const m=n.get("JS");let y;m instanceof BaseStream?y=m.getString():"string"==typeof m&&(y=m);const w=y&&recoverJsURL(stringToPDFString(y));if(w){s=w.url;t.newWindow=w.newWindow;break}default:if("JavaScript"===i||"SubmitForm"===i)break;warn(`parseDestDictionary - unsupported action: "${i}".`)}}else e.has("Dest")&&(r=e.get("Dest"));if("string"==typeof s){const e=createValidAbsoluteUrl(s,i,{addDefaultProtocol:!0,tryConvertEncoding:!0});e&&(t.url=e.href);t.unsafeUrl=s}if(r){r instanceof Name&&(r=r.name);"string"==typeof r?t.dest=stringToPDFString(r):isValidExplicitDest(r)&&(t.dest=r)}}}function addChildren(e,t){if(e instanceof Dict)e=e.getRawValues();else if(e instanceof BaseStream)e=e.dict.getRawValues();else if(!Array.isArray(e))return;for(const a of e)((i=a)instanceof Ref||i instanceof Dict||i instanceof BaseStream||Array.isArray(i))&&t.push(a);var i}class ObjectLoader{constructor(e,t,i){this.dict=e;this.keys=t;this.xref=i;this.refSet=null}async load(){if(this.xref.stream.isDataLoaded)return;const{keys:e,dict:t}=this;this.refSet=new RefSet;const i=[];for(const a of e){const e=t.getRaw(a);void 0!==e&&i.push(e)}return this._walk(i)}async _walk(e){const t=[],i=[];for(;e.length;){let a=e.pop();if(a instanceof Ref){if(this.refSet.has(a))continue;try{this.refSet.put(a);a=this.xref.fetch(a)}catch(e){if(!(e instanceof MissingDataException)){warn(`ObjectLoader._walk - requesting all data: "${e}".`);this.refSet=null;const{manager:t}=this.xref.stream;return t.requestAllChunks()}t.push(a);i.push({begin:e.begin,end:e.end})}}if(a instanceof BaseStream){const e=a.getBaseStreams();if(e){let s=!1;for(const t of e)if(!t.isDataLoaded){s=!0;i.push({begin:t.start,end:t.end})}s&&t.push(a)}}addChildren(a,e)}if(i.length){await this.xref.stream.manager.requestRanges(i);for(const e of t)e instanceof Ref&&this.refSet.remove(e);return this._walk(t)}this.refSet=null}}const xs=Symbol(),Ls=Symbol(),Hs=Symbol(),Js=Symbol(),Ys=Symbol(),vs=Symbol(),Ks=Symbol(),Ts=Symbol(),qs=Symbol(),Os=Symbol("content"),Ws=Symbol("data"),js=Symbol(),Xs=Symbol("extra"),Zs=Symbol(),Vs=Symbol(),zs=Symbol(),_s=Symbol(),$s=Symbol(),Ar=Symbol(),er=Symbol(),tr=Symbol(),ir=Symbol(),ar=Symbol(),sr=Symbol(),rr=Symbol(),nr=Symbol(),gr=Symbol(),or=Symbol(),Ir=Symbol(),cr=Symbol(),Cr=Symbol(),hr=Symbol(),lr=Symbol(),Qr=Symbol(),Er=Symbol(),ur=Symbol(),dr=Symbol(),fr=Symbol(),pr=Symbol(),mr=Symbol(),yr=Symbol(),wr=Symbol(),Dr=Symbol(),br=Symbol(),Fr=Symbol(),Sr=Symbol("namespaceId"),kr=Symbol("nodeName"),Rr=Symbol(),Nr=Symbol(),Gr=Symbol(),Mr=Symbol(),Ur=Symbol(),xr=Symbol(),Lr=Symbol(),Hr=Symbol(),Jr=Symbol("root"),Yr=Symbol(),vr=Symbol(),Kr=Symbol(),Tr=Symbol(),qr=Symbol(),Or=Symbol(),Pr=Symbol(),Wr=Symbol(),jr=Symbol(),Xr=Symbol(),Zr=Symbol(),Vr=Symbol("uid"),zr=Symbol(),_r={config:{id:0,check:e=>e.startsWith("http://www.xfa.org/schema/xci/")},connectionSet:{id:1,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-connection-set/")},datasets:{id:2,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-data/")},form:{id:3,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-form/")},localeSet:{id:4,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-locale-set/")},pdf:{id:5,check:e=>"http://ns.adobe.com/xdp/pdf/"===e},signature:{id:6,check:e=>"http://www.w3.org/2000/09/xmldsig#"===e},sourceSet:{id:7,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-source-set/")},stylesheet:{id:8,check:e=>"http://www.w3.org/1999/XSL/Transform"===e},template:{id:9,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-template/")},xdc:{id:10,check:e=>e.startsWith("http://www.xfa.org/schema/xdc/")},xdp:{id:11,check:e=>"http://ns.adobe.com/xdp/"===e},xfdf:{id:12,check:e=>"http://ns.adobe.com/xfdf/"===e},xhtml:{id:13,check:e=>"http://www.w3.org/1999/xhtml"===e},xmpmeta:{id:14,check:e=>"http://ns.adobe.com/xmpmeta/"===e}},$r={pt:e=>e,cm:e=>e/2.54*72,mm:e=>e/25.4*72,in:e=>72*e,px:e=>e},An=/([+-]?\d+\.?\d*)(.*)/;function stripQuotes(e){return e.startsWith("'")||e.startsWith('"')?e.slice(1,-1):e}function getInteger({data:e,defaultValue:t,validate:i}){if(!e)return t;e=e.trim();const a=parseInt(e,10);return!isNaN(a)&&i(a)?a:t}function getFloat({data:e,defaultValue:t,validate:i}){if(!e)return t;e=e.trim();const a=parseFloat(e);return!isNaN(a)&&i(a)?a:t}function getKeyword({data:e,defaultValue:t,validate:i}){return e&&i(e=e.trim())?e:t}function getStringOption(e,t){return getKeyword({data:e,defaultValue:t[0],validate:e=>t.includes(e)})}function getMeasurement(e,t="0"){t||="0";if(!e)return getMeasurement(t);const i=e.trim().match(An);if(!i)return getMeasurement(t);const[,a,s]=i,r=parseFloat(a);if(isNaN(r))return getMeasurement(t);if(0===r)return 0;const n=$r[s];return n?n(r):r}function getRatio(e){if(!e)return{num:1,den:1};const t=e.trim().split(/\s*:\s*/).map((e=>parseFloat(e))).filter((e=>!isNaN(e)));1===t.length&&t.push(1);if(0===t.length)return{num:1,den:1};const[i,a]=t;return{num:i,den:a}}function getRelevant(e){return e?e.trim().split(/\s+/).map((e=>({excluded:"-"===e[0],viewname:e.substring(1)}))):[]}class HTMLResult{static get FAILURE(){return shadow(this,"FAILURE",new HTMLResult(!1,null,null,null))}static get EMPTY(){return shadow(this,"EMPTY",new HTMLResult(!0,null,null,null))}constructor(e,t,i,a){this.success=e;this.html=t;this.bbox=i;this.breakNode=a}isBreak(){return!!this.breakNode}static breakNode(e){return new HTMLResult(!1,null,null,e)}static success(e,t=null){return new HTMLResult(!0,e,t,null)}}class FontFinder{constructor(e){this.fonts=new Map;this.cache=new Map;this.warned=new Set;this.defaultFont=null;this.add(e)}add(e,t=null){for(const t of e)this.addPdfFont(t);for(const e of this.fonts.values())e.regular||(e.regular=e.italic||e.bold||e.bolditalic);if(!t||0===t.size)return;const i=this.fonts.get("PdfJS-Fallback-PdfJS-XFA");for(const e of t)this.fonts.set(e,i)}addPdfFont(e){const t=e.cssFontInfo,i=t.fontFamily;let a=this.fonts.get(i);if(!a){a=Object.create(null);this.fonts.set(i,a);this.defaultFont||(this.defaultFont=a)}let s="";const r=parseFloat(t.fontWeight);0!==parseFloat(t.italicAngle)?s=r>=700?"bolditalic":"italic":r>=700&&(s="bold");if(!s){(e.name.includes("Bold")||e.psName?.includes("Bold"))&&(s="bold");(e.name.includes("Italic")||e.name.endsWith("It")||e.psName?.includes("Italic")||e.psName?.endsWith("It"))&&(s+="italic")}s||(s="regular");a[s]=e}getDefault(){return this.defaultFont}find(e,t=!0){let i=this.fonts.get(e)||this.cache.get(e);if(i)return i;const a=/,|-|_| |bolditalic|bold|italic|regular|it/gi;let s=e.replaceAll(a,"");i=this.fonts.get(s);if(i){this.cache.set(e,i);return i}s=s.toLowerCase();const r=[];for(const[e,t]of this.fonts.entries())e.replaceAll(a,"").toLowerCase().startsWith(s)&&r.push(t);if(0===r.length)for(const[,e]of this.fonts.entries())e.regular.name?.replaceAll(a,"").toLowerCase().startsWith(s)&&r.push(e);if(0===r.length){s=s.replaceAll(/psmt|mt/gi,"");for(const[e,t]of this.fonts.entries())e.replaceAll(a,"").toLowerCase().startsWith(s)&&r.push(t)}if(0===r.length)for(const e of this.fonts.values())e.regular.name?.replaceAll(a,"").toLowerCase().startsWith(s)&&r.push(e);if(r.length>=1){1!==r.length&&t&&warn(`XFA - Too many choices to guess the correct font: ${e}`);this.cache.set(e,r[0]);return r[0]}if(t&&!this.warned.has(e)){this.warned.add(e);warn(`XFA - Cannot find the font: ${e}`)}return null}}function selectFont(e,t){return"italic"===e.posture?"bold"===e.weight?t.bolditalic:t.italic:"bold"===e.weight?t.bold:t.regular}class FontInfo{constructor(e,t,i,a){this.lineHeight=i;this.paraMargin=t||{top:0,bottom:0,left:0,right:0};if(!e){[this.pdfFont,this.xfaFont]=this.defaultFont(a);return}this.xfaFont={typeface:e.typeface,posture:e.posture,weight:e.weight,size:e.size,letterSpacing:e.letterSpacing};const s=a.find(e.typeface);if(s){this.pdfFont=selectFont(e,s);this.pdfFont||([this.pdfFont,this.xfaFont]=this.defaultFont(a))}else[this.pdfFont,this.xfaFont]=this.defaultFont(a)}defaultFont(e){const t=e.find("Helvetica",!1)||e.find("Myriad Pro",!1)||e.find("Arial",!1)||e.getDefault();if(t?.regular){const e=t.regular;return[e,{typeface:e.cssFontInfo.fontFamily,posture:"normal",weight:"normal",size:10,letterSpacing:0}]}return[null,{typeface:"Courier",posture:"normal",weight:"normal",size:10,letterSpacing:0}]}}class FontSelector{constructor(e,t,i,a){this.fontFinder=a;this.stack=[new FontInfo(e,t,i,a)]}pushData(e,t,i){const a=this.stack.at(-1);for(const t of["typeface","posture","weight","size","letterSpacing"])e[t]||(e[t]=a.xfaFont[t]);for(const e of["top","bottom","left","right"])isNaN(t[e])&&(t[e]=a.paraMargin[e]);const s=new FontInfo(e,t,i||a.lineHeight,this.fontFinder);s.pdfFont||(s.pdfFont=a.pdfFont);this.stack.push(s)}popFont(){this.stack.pop()}topFont(){return this.stack.at(-1)}}class TextMeasure{constructor(e,t,i,a){this.glyphs=[];this.fontSelector=new FontSelector(e,t,i,a);this.extraHeight=0}pushData(e,t,i){this.fontSelector.pushData(e,t,i)}popFont(e){return this.fontSelector.popFont()}addPara(){const e=this.fontSelector.topFont();this.extraHeight+=e.paraMargin.top+e.paraMargin.bottom}addString(e){if(!e)return;const t=this.fontSelector.topFont(),i=t.xfaFont.size;if(t.pdfFont){const a=t.xfaFont.letterSpacing,s=t.pdfFont,r=s.lineHeight||1.2,n=t.lineHeight||Math.max(1.2,r)*i,g=r-(void 0===s.lineGap?.2:s.lineGap),o=Math.max(1,g)*i,c=i/1e3,C=s.defaultWidth||s.charsToGlyphs(" ")[0].width;for(const t of e.split(/[\u2029\n]/)){const e=s.encodeString(t).join(""),i=s.charsToGlyphs(e);for(const e of i){const t=e.width||C;this.glyphs.push([t*c+a,n,o,e.unicode,!1])}this.glyphs.push([0,0,0,"\n",!0])}this.glyphs.pop()}else{for(const t of e.split(/[\u2029\n]/)){for(const e of t.split(""))this.glyphs.push([i,1.2*i,i,e,!1]);this.glyphs.push([0,0,0,"\n",!0])}this.glyphs.pop()}}compute(e){let t=-1,i=0,a=0,s=0,r=0,n=0,g=!1,o=!0;for(let c=0,C=this.glyphs.length;ce){a=Math.max(a,r);r=0;s+=n;n=d;t=-1;i=0;g=!0;o=!1}else{n=Math.max(d,n);i=r;r+=C;t=c}else if(r+C>e){s+=n;n=d;if(-1!==t){c=t;a=Math.max(a,i);r=0;t=-1;i=0}else{a=Math.max(a,r);r=C}g=!0;o=!1}else{r+=C;n=Math.max(d,n)}}a=Math.max(a,r);s+=n+this.extraHeight;return{width:1.02*a,height:s,isBroken:g}}}const en=/^[^.[]+/,tn=/^[^\]]+/,an=0,sn=1,rn=2,nn=3,gn=4,on=new Map([["$data",(e,t)=>e.datasets?e.datasets.data:e],["$record",(e,t)=>(e.datasets?e.datasets.data:e)[rr]()[0]],["$template",(e,t)=>e.template],["$connectionSet",(e,t)=>e.connectionSet],["$form",(e,t)=>e.form],["$layout",(e,t)=>e.layout],["$host",(e,t)=>e.host],["$dataWindow",(e,t)=>e.dataWindow],["$event",(e,t)=>e.event],["!",(e,t)=>e.datasets],["$xfa",(e,t)=>e],["xfa",(e,t)=>e],["$",(e,t)=>t]]),In=new WeakMap;function parseExpression(e,t,i=!0){let a=e.match(en);if(!a)return null;let[s]=a;const r=[{name:s,cacheName:"."+s,index:0,js:null,formCalc:null,operator:an}];let n=s.length;for(;n0&&C.push(e)}if(0!==C.length||g||0!==o)e=isFinite(c)?C.filter((e=>ce[c])):C.flat();else{const i=t[Ir]();if(!(t=i))return null;o=-1;e=[t]}}return 0===e.length?null:e}function createDataNode(e,t,i){const a=parseExpression(i);if(!a)return null;if(a.some((e=>e.operator===sn)))return null;const s=on.get(a[0].name);let r=0;if(s){e=s(e,t);r=1}else e=t||e;for(let t=a.length;re[Pr]())).join("")}get[hn](){const e=Object.getPrototypeOf(this);if(!e._attributes){const t=e._attributes=new Set;for(const e of Object.getOwnPropertyNames(this)){if(null===this[e]||this[e]instanceof XFAObject||this[e]instanceof XFAObjectArray)break;t.add(e)}}return shadow(this,hn,e._attributes)}[pr](e){let t=this;for(;t;){if(t===e)return!0;t=t[Ir]()}return!1}[Ir](){return this[wn]}[or](){return this[Ir]()}[rr](e=null){return e?this[e]:this[ln]}[js](){const e=Object.create(null);this[Os]&&(e.$content=this[Os]);for(const t of Object.getOwnPropertyNames(this)){const i=this[t];null!==i&&(i instanceof XFAObject?e[t]=i[js]():i instanceof XFAObjectArray?i.isEmpty()||(e[t]=i.dump()):e[t]=i)}return e}[Zr](){return null}[jr](){return HTMLResult.EMPTY}*[nr](){for(const e of this[rr]())yield e}*[un](e,t){for(const i of this[nr]())if(!e||t===e.has(i[kr])){const e=this[$s](),t=i[jr](e);t.success||(this[Xs].failingNode=i);yield t}}[Vs](){return null}[Ls](e,t){this[Xs].children.push(e)}[$s](){}[Js]({filter:e=null,include:t=!0}){if(this[Xs].generator){const e=this[$s](),t=this[Xs].failingNode[jr](e);if(!t.success)return t;t.html&&this[Ls](t.html,t.bbox);delete this[Xs].failingNode}else this[Xs].generator=this[un](e,t);for(;;){const e=this[Xs].generator.next();if(e.done)break;const t=e.value;if(!t.success)return t;t.html&&this[Ls](t.html,t.bbox)}this[Xs].generator=null;return HTMLResult.EMPTY}[Tr](e){this[bn]=new Set(Object.keys(e))}[fn](e){const t=this[hn],i=this[bn];return[...e].filter((e=>t.has(e)&&!i.has(e)))}[Yr](e,t=new Set){for(const i of this[ln])i[Dn](e,t)}[Dn](e,t){const i=this[dn](e,t);i?this[cn](i,e,t):this[Yr](e,t)}[dn](e,t){const{use:i,usehref:a}=this;if(!i&&!a)return null;let s=null,r=null,n=null,g=i;if(a){g=a;a.startsWith("#som(")&&a.endsWith(")")?r=a.slice(5,-1):a.startsWith(".#som(")&&a.endsWith(")")?r=a.slice(6,-1):a.startsWith("#")?n=a.slice(1):a.startsWith(".#")&&(n=a.slice(2))}else i.startsWith("#")?n=i.slice(1):r=i;this.use=this.usehref="";if(n)s=e.get(n);else{s=searchNode(e.get(Jr),this,r,!0,!1);s&&(s=s[0])}if(!s){warn(`XFA - Invalid prototype reference: ${g}.`);return null}if(s[kr]!==this[kr]){warn(`XFA - Incompatible prototype: ${s[kr]} !== ${this[kr]}.`);return null}if(t.has(s)){warn("XFA - Cycle detected in prototypes use.");return null}t.add(s);const o=s[dn](e,t);o&&s[cn](o,e,t);s[Yr](e,t);t.delete(s);return s}[cn](e,t,i){if(i.has(e)){warn("XFA - Cycle detected in prototypes use.");return}!this[Os]&&e[Os]&&(this[Os]=e[Os]);new Set(i).add(e);for(const t of this[fn](e[bn])){this[t]=e[t];this[bn]&&this[bn].add(t)}for(const a of Object.getOwnPropertyNames(this)){if(this[hn].has(a))continue;const s=this[a],r=e[a];if(s instanceof XFAObjectArray){for(const e of s[ln])e[Dn](t,i);for(let a=s[ln].length,n=r[ln].length;aXFAObject[Bn](e))):"object"==typeof e&&null!==e?Object.assign({},e):e}[Ts](){const e=Object.create(Object.getPrototypeOf(this));for(const t of Object.getOwnPropertySymbols(this))try{e[t]=this[t]}catch{shadow(e,t,this[t])}e[Vr]=`${e[kr]}${Sn++}`;e[ln]=[];for(const t of Object.getOwnPropertyNames(this)){if(this[hn].has(t)){e[t]=XFAObject[Bn](this[t]);continue}const i=this[t];e[t]=i instanceof XFAObjectArray?new XFAObjectArray(i[mn]):null}for(const t of this[ln]){const i=t[kr],a=t[Ts]();e[ln].push(a);a[wn]=e;null===e[i]?e[i]=a:e[i][ln].push(a)}return e}[rr](e=null){return e?this[ln].filter((t=>t[kr]===e)):this[ln]}[Ar](e){return this[e]}[er](e,t,i=!0){return Array.from(this[tr](e,t,i))}*[tr](e,t,i=!0){if("parent"!==e){for(const i of this[ln]){i[kr]===e&&(yield i);i.name===e&&(yield i);(t||i[Dr]())&&(yield*i[tr](e,t,!1))}i&&this[hn].has(e)&&(yield new XFAAttribute(this,e,this[e]))}else yield this[wn]}}class XFAObjectArray{constructor(e=1/0){this[mn]=e;this[ln]=[]}get isXFAObject(){return!1}get isXFAObjectArray(){return!0}push(e){if(this[ln].length<=this[mn]){this[ln].push(e);return!0}warn(`XFA - node "${e[kr]}" accepts no more than ${this[mn]} children`);return!1}isEmpty(){return 0===this[ln].length}dump(){return 1===this[ln].length?this[ln][0][js]():this[ln].map((e=>e[js]()))}[Ts](){const e=new XFAObjectArray(this[mn]);e[ln]=this[ln].map((e=>e[Ts]()));return e}get children(){return this[ln]}clear(){this[ln].length=0}}class XFAAttribute{constructor(e,t,i){this[wn]=e;this[kr]=t;this[Os]=i;this[qs]=!1;this[Vr]="attribute"+Sn++}[Ir](){return this[wn]}[fr](){return!0}[ir](){return this[Os].trim()}[qr](e){e=e.value||"";this[Os]=e.toString()}[Pr](){return this[Os]}[pr](e){return this[wn]===e||this[wn][pr](e)}}class XmlObject extends XFAObject{constructor(e,t,i={}){super(e,t);this[Os]="";this[Qn]=null;if("#text"!==t){const e=new Map;this[Cn]=e;for(const[t,a]of Object.entries(i))e.set(t,new XFAAttribute(this,t,a));if(i.hasOwnProperty(Rr)){const e=i[Rr].xfa.dataNode;void 0!==e&&("dataGroup"===e?this[Qn]=!1:"dataValue"===e&&(this[Qn]=!0))}}this[qs]=!1}[Xr](e){const t=this[kr];if("#text"===t){e.push(encodeToXmlString(this[Os]));return}const i=utf8StringToString(t),a=this[Sr]===kn?"xfa:":"";e.push(`<${a}${i}`);for(const[t,i]of this[Cn].entries()){const a=utf8StringToString(t);e.push(` ${a}="${encodeToXmlString(i[Os])}"`)}null!==this[Qn]&&(this[Qn]?e.push(' xfa:dataNode="dataValue"'):e.push(' xfa:dataNode="dataGroup"'));if(this[Os]||0!==this[ln].length){e.push(">");if(this[Os])"string"==typeof this[Os]?e.push(encodeToXmlString(this[Os])):this[Os][Xr](e);else for(const t of this[ln])t[Xr](e);e.push(``)}else e.push("/>")}[Nr](e){if(this[Os]){const e=new XmlObject(this[Sr],"#text");this[Hs](e);e[Os]=this[Os];this[Os]=""}this[Hs](e);return!0}[Mr](e){this[Os]+=e}[Zs](){if(this[Os]&&this[ln].length>0){const e=new XmlObject(this[Sr],"#text");this[Hs](e);e[Os]=this[Os];delete this[Os]}}[jr](){return"#text"===this[kr]?HTMLResult.success({name:"#text",value:this[Os]}):HTMLResult.EMPTY}[rr](e=null){return e?this[ln].filter((t=>t[kr]===e)):this[ln]}[_s](){return this[Cn]}[Ar](e){const t=this[Cn].get(e);return void 0!==t?t:this[rr](e)}*[tr](e,t){const i=this[Cn].get(e);i&&(yield i);for(const i of this[ln]){i[kr]===e&&(yield i);t&&(yield*i[tr](e,t))}}*[zs](e,t){const i=this[Cn].get(e);!i||t&&i[qs]||(yield i);for(const i of this[ln])yield*i[zs](e,t)}*[sr](e,t,i){for(const a of this[ln]){a[kr]!==e||i&&a[qs]||(yield a);t&&(yield*a[sr](e,t,i))}}[fr](){return null===this[Qn]?0===this[ln].length||this[ln][0][Sr]===_r.xhtml.id:this[Qn]}[ir](){return null===this[Qn]?0===this[ln].length?this[Os].trim():this[ln][0][Sr]===_r.xhtml.id?this[ln][0][Pr]().trim():null:this[Os].trim()}[qr](e){e=e.value||"";this[Os]=e.toString()}[js](e=!1){const t=Object.create(null);e&&(t.$ns=this[Sr]);this[Os]&&(t.$content=this[Os]);t.$name=this[kr];t.children=[];for(const i of this[ln])t.children.push(i[js](e));t.attributes=Object.create(null);for(const[e,i]of this[Cn])t.attributes[e]=i[Os];return t}}class ContentObject extends XFAObject{constructor(e,t){super(e,t);this[Os]=""}[Mr](e){this[Os]+=e}[Zs](){}}class OptionObject extends ContentObject{constructor(e,t,i){super(e,t);this[yn]=i}[Zs](){this[Os]=getKeyword({data:this[Os],defaultValue:this[yn][0],validate:e=>this[yn].includes(e)})}[Ys](e){super[Ys](e);delete this[yn]}}class StringObject extends ContentObject{[Zs](){this[Os]=this[Os].trim()}}class IntegerObject extends ContentObject{constructor(e,t,i,a){super(e,t);this[En]=i;this[Fn]=a}[Zs](){this[Os]=getInteger({data:this[Os],defaultValue:this[En],validate:this[Fn]})}[Ys](e){super[Ys](e);delete this[En];delete this[Fn]}}class Option01 extends IntegerObject{constructor(e,t){super(e,t,0,(e=>1===e))}}class Option10 extends IntegerObject{constructor(e,t){super(e,t,1,(e=>0===e))}}function measureToString(e){return"string"==typeof e?"0px":Number.isInteger(e)?`${e}px`:`${e.toFixed(2)}px`}const Rn={anchorType(e,t){const i=e[or]();if(i&&(!i.layout||"position"===i.layout)){"transform"in t||(t.transform="");switch(e.anchorType){case"bottomCenter":t.transform+="translate(-50%, -100%)";break;case"bottomLeft":t.transform+="translate(0,-100%)";break;case"bottomRight":t.transform+="translate(-100%,-100%)";break;case"middleCenter":t.transform+="translate(-50%,-50%)";break;case"middleLeft":t.transform+="translate(0,-50%)";break;case"middleRight":t.transform+="translate(-100%,-50%)";break;case"topCenter":t.transform+="translate(-50%,0)";break;case"topRight":t.transform+="translate(-100%,0)"}}},dimensions(e,t){const i=e[or]();let a=e.w;const s=e.h;if(i.layout?.includes("row")){const t=i[Xs],s=e.colSpan;let r;if(-1===s){r=t.columnWidths.slice(t.currentColumn).reduce(((e,t)=>e+t),0);t.currentColumn=0}else{r=t.columnWidths.slice(t.currentColumn,t.currentColumn+s).reduce(((e,t)=>e+t),0);t.currentColumn=(t.currentColumn+e.colSpan)%t.columnWidths.length}isNaN(r)||(a=e.w=r)}t.width=""!==a?measureToString(a):"auto";t.height=""!==s?measureToString(s):"auto"},position(e,t){const i=e[or]();if(!i?.layout||"position"===i.layout){t.position="absolute";t.left=measureToString(e.x);t.top=measureToString(e.y)}},rotate(e,t){if(e.rotate){"transform"in t||(t.transform="");t.transform+=`rotate(-${e.rotate}deg)`;t.transformOrigin="top left"}},presence(e,t){switch(e.presence){case"invisible":t.visibility="hidden";break;case"hidden":case"inactive":t.display="none"}},hAlign(e,t){if("para"===e[kr])switch(e.hAlign){case"justifyAll":t.textAlign="justify-all";break;case"radix":t.textAlign="left";break;default:t.textAlign=e.hAlign}else switch(e.hAlign){case"left":t.alignSelf="start";break;case"center":t.alignSelf="center";break;case"right":t.alignSelf="end"}},margin(e,t){e.margin&&(t.margin=e.margin[Zr]().margin)}};function setMinMaxDimensions(e,t){if("position"===e[or]().layout){e.minW>0&&(t.minWidth=measureToString(e.minW));e.maxW>0&&(t.maxWidth=measureToString(e.maxW));e.minH>0&&(t.minHeight=measureToString(e.minH));e.maxH>0&&(t.maxHeight=measureToString(e.maxH))}}function layoutText(e,t,i,a,s,r){const n=new TextMeasure(t,i,a,s);"string"==typeof e?n.addString(e):e[Ur](n);return n.compute(r)}function layoutNode(e,t){let i=null,a=null,s=!1;if((!e.w||!e.h)&&e.value){let r=0,n=0;if(e.margin){r=e.margin.leftInset+e.margin.rightInset;n=e.margin.topInset+e.margin.bottomInset}let g=null,o=null;if(e.para){o=Object.create(null);g=""===e.para.lineHeight?null:e.para.lineHeight;o.top=""===e.para.spaceAbove?0:e.para.spaceAbove;o.bottom=""===e.para.spaceBelow?0:e.para.spaceBelow;o.left=""===e.para.marginLeft?0:e.para.marginLeft;o.right=""===e.para.marginRight?0:e.para.marginRight}let c=e.font;if(!c){const t=e[cr]();let i=e[Ir]();for(;i&&i!==t;){if(i.font){c=i.font;break}i=i[Ir]()}}const C=(e.w||t.width)-r,h=e[Cr].fontFinder;if(e.value.exData&&e.value.exData[Os]&&"text/html"===e.value.exData.contentType){const t=layoutText(e.value.exData[Os],c,o,g,h,C);a=t.width;i=t.height;s=t.isBroken}else{const t=e.value[Pr]();if(t){const e=layoutText(t,c,o,g,h,C);a=e.width;i=e.height;s=e.isBroken}}null===a||e.w||(a+=r);null===i||e.h||(i+=n)}return{w:a,h:i,isBroken:s}}function computeBbox(e,t,i){let a;if(""!==e.w&&""!==e.h)a=[e.x,e.y,e.w,e.h];else{if(!i)return null;let s=e.w;if(""===s){if(0===e.maxW){const t=e[or]();s="position"===t.layout&&""!==t.w?0:e.minW}else s=Math.min(e.maxW,i.width);t.attributes.style.width=measureToString(s)}let r=e.h;if(""===r){if(0===e.maxH){const t=e[or]();r="position"===t.layout&&""!==t.h?0:e.minH}else r=Math.min(e.maxH,i.height);t.attributes.style.height=measureToString(r)}a=[e.x,e.y,s,r]}return a}function fixDimensions(e){const t=e[or]();if(t.layout?.includes("row")){const i=t[Xs],a=e.colSpan;let s;s=-1===a?i.columnWidths.slice(i.currentColumn).reduce(((e,t)=>e+t),0):i.columnWidths.slice(i.currentColumn,i.currentColumn+a).reduce(((e,t)=>e+t),0);isNaN(s)||(e.w=s)}t.layout&&"position"!==t.layout&&(e.x=e.y=0);"table"===e.layout&&""===e.w&&Array.isArray(e.columnWidths)&&(e.w=e.columnWidths.reduce(((e,t)=>e+t),0))}function layoutClass(e){switch(e.layout){case"position":default:return"xfaPosition";case"lr-tb":return"xfaLrTb";case"rl-row":return"xfaRlRow";case"rl-tb":return"xfaRlTb";case"row":return"xfaRow";case"table":return"xfaTable";case"tb":return"xfaTb"}}function toStyle(e,...t){const i=Object.create(null);for(const a of t){const t=e[a];if(null!==t)if(Rn.hasOwnProperty(a))Rn[a](e,i);else if(t instanceof XFAObject){const e=t[Zr]();e?Object.assign(i,e):warn(`(DEBUG) - XFA - style for ${a} not implemented yet`)}}return i}function createWrapper(e,t){const{attributes:i}=t,{style:a}=i,s={name:"div",attributes:{class:["xfaWrapper"],style:Object.create(null)},children:[]};i.class.push("xfaWrapped");if(e.border){const{widths:i,insets:r}=e.border[Xs];let n,g,o=r[0],c=r[3];const C=r[0]+r[2],h=r[1]+r[3];switch(e.border.hand){case"even":o-=i[0]/2;c-=i[3]/2;n=`calc(100% + ${(i[1]+i[3])/2-h}px)`;g=`calc(100% + ${(i[0]+i[2])/2-C}px)`;break;case"left":o-=i[0];c-=i[3];n=`calc(100% + ${i[1]+i[3]-h}px)`;g=`calc(100% + ${i[0]+i[2]-C}px)`;break;case"right":n=h?`calc(100% - ${h}px)`:"100%";g=C?`calc(100% - ${C}px)`:"100%"}const l=["xfaBorder"];isPrintOnly(e.border)&&l.push("xfaPrintOnly");const Q={name:"div",attributes:{class:l,style:{top:`${o}px`,left:`${c}px`,width:n,height:g}},children:[]};for(const e of["border","borderWidth","borderColor","borderRadius","borderStyle"])if(void 0!==a[e]){Q.attributes.style[e]=a[e];delete a[e]}s.children.push(Q,t)}else s.children.push(t);for(const e of["background","backgroundClip","top","left","width","height","minWidth","minHeight","maxWidth","maxHeight","transform","transformOrigin","visibility"])if(void 0!==a[e]){s.attributes.style[e]=a[e];delete a[e]}s.attributes.style.position="absolute"===a.position?"absolute":"relative";delete a.position;if(a.alignSelf){s.attributes.style.alignSelf=a.alignSelf;delete a.alignSelf}return s}function fixTextIndent(e){const t=getMeasurement(e.textIndent,"0px");if(t>=0)return;const i="padding"+("left"===("right"===e.textAlign?"right":"left")?"Left":"Right"),a=getMeasurement(e[i],"0px");e[i]=a-t+"px"}function setAccess(e,t){switch(e.access){case"nonInteractive":t.push("xfaNonInteractive");break;case"readOnly":t.push("xfaReadOnly");break;case"protected":t.push("xfaDisabled")}}function isPrintOnly(e){return e.relevant.length>0&&!e.relevant[0].excluded&&"print"===e.relevant[0].viewname}function getCurrentPara(e){const t=e[cr]()[Xs].paraStack;return t.length?t.at(-1):null}function setPara(e,t,i){if(i.attributes.class?.includes("xfaRich")){if(t){""===e.h&&(t.height="auto");""===e.w&&(t.width="auto")}const a=getCurrentPara(e);if(a){const e=i.attributes.style;e.display="flex";e.flexDirection="column";switch(a.vAlign){case"top":e.justifyContent="start";break;case"bottom":e.justifyContent="end";break;case"middle":e.justifyContent="center"}const t=a[Zr]();for(const[i,a]of Object.entries(t))i in e||(e[i]=a)}}}function setFontFamily(e,t,i,a){if(!i){delete a.fontFamily;return}const s=stripQuotes(e.typeface);a.fontFamily=`"${s}"`;const r=i.find(s);if(r){const{fontFamily:i}=r.regular.cssFontInfo;i!==s&&(a.fontFamily=`"${i}"`);const n=getCurrentPara(t);if(n&&""!==n.lineHeight)return;if(a.lineHeight)return;const g=selectFont(e,r);g&&(a.lineHeight=Math.max(1.2,g.lineHeight))}}function fixURL(e){const t=createValidAbsoluteUrl(e,null,{addDefaultProtocol:!0,tryConvertEncoding:!0});return t?t.href:null}function createLine(e,t){return{name:"div",attributes:{class:["lr-tb"===e.layout?"xfaLr":"xfaRl"]},children:t}}function flushHTML(e){if(!e[Xs])return null;const t={name:"div",attributes:e[Xs].attributes,children:e[Xs].children};if(e[Xs].failingNode){const i=e[Xs].failingNode[Vs]();i&&(e.layout.endsWith("-tb")?t.children.push(createLine(e,[i])):t.children.push(i))}return 0===t.children.length?null:t}function addHTML(e,t,i){const a=e[Xs],s=a.availableSpace,[r,n,g,o]=i;switch(e.layout){case"position":a.width=Math.max(a.width,r+g);a.height=Math.max(a.height,n+o);a.children.push(t);break;case"lr-tb":case"rl-tb":if(!a.line||1===a.attempt){a.line=createLine(e,[]);a.children.push(a.line);a.numberInLine=0}a.numberInLine+=1;a.line.children.push(t);if(0===a.attempt){a.currentWidth+=g;a.height=Math.max(a.height,a.prevHeight+o)}else{a.currentWidth=g;a.prevHeight=a.height;a.height+=o;a.attempt=0}a.width=Math.max(a.width,a.currentWidth);break;case"rl-row":case"row":{a.children.push(t);a.width+=g;a.height=Math.max(a.height,o);const e=measureToString(a.height);for(const t of a.children)t.attributes.style.height=e;break}case"table":case"tb":a.width=Math.min(s.width,Math.max(a.width,g));a.height+=o;a.children.push(t)}}function getAvailableSpace(e){const t=e[Xs].availableSpace,i=e.margin?e.margin.topInset+e.margin.bottomInset:0,a=e.margin?e.margin.leftInset+e.margin.rightInset:0;switch(e.layout){case"lr-tb":case"rl-tb":return 0===e[Xs].attempt?{width:t.width-a-e[Xs].currentWidth,height:t.height-i-e[Xs].prevHeight}:{width:t.width-a,height:t.height-i-e[Xs].height};case"rl-row":case"row":return{width:e[Xs].columnWidths.slice(e[Xs].currentColumn).reduce(((e,t)=>e+t)),height:t.height-a};case"table":case"tb":return{width:t.width-a,height:t.height-i-e[Xs].height};default:return t}}function checkDimensions(e,t){if(null===e[cr]()[Xs].firstUnsplittable)return!0;if(0===e.w||0===e.h)return!0;const i=e[or](),a=i[Xs]?.attempt||0,[,s,r,n]=function getTransformedBBox(e){let t,i,a=""===e.w?NaN:e.w,s=""===e.h?NaN:e.h,[r,n]=[0,0];switch(e.anchorType||""){case"bottomCenter":[r,n]=[a/2,s];break;case"bottomLeft":[r,n]=[0,s];break;case"bottomRight":[r,n]=[a,s];break;case"middleCenter":[r,n]=[a/2,s/2];break;case"middleLeft":[r,n]=[0,s/2];break;case"middleRight":[r,n]=[a,s/2];break;case"topCenter":[r,n]=[a/2,0];break;case"topRight":[r,n]=[a,0]}switch(e.rotate||0){case 0:[t,i]=[-r,-n];break;case 90:[t,i]=[-n,r];[a,s]=[s,-a];break;case 180:[t,i]=[r,n];[a,s]=[-a,-s];break;case 270:[t,i]=[n,-r];[a,s]=[-s,a]}return[e.x+t+Math.min(0,a),e.y+i+Math.min(0,s),Math.abs(a),Math.abs(s)]}(e);switch(i.layout){case"lr-tb":case"rl-tb":return 0===a?e[cr]()[Xs].noLayoutFailure?""!==e.w?Math.round(r-t.width)<=2:t.width>2:!(""!==e.h&&Math.round(n-t.height)>2)&&(""!==e.w?Math.round(r-t.width)<=2||0===i[Xs].numberInLine&&t.height>2:t.width>2):!!e[cr]()[Xs].noLayoutFailure||!(""!==e.h&&Math.round(n-t.height)>2)&&((""===e.w||Math.round(r-t.width)<=2||!i[wr]())&&t.height>2);case"table":case"tb":return!!e[cr]()[Xs].noLayoutFailure||(""===e.h||e[yr]()?(""===e.w||Math.round(r-t.width)<=2||!i[wr]())&&t.height>2:Math.round(n-t.height)<=2);case"position":if(e[cr]()[Xs].noLayoutFailure)return!0;if(""===e.h||Math.round(n+s-t.height)<=2)return!0;return n+s>e[cr]()[Xs].currentContentArea.h;case"rl-row":case"row":return!!e[cr]()[Xs].noLayoutFailure||(""===e.h||Math.round(n-t.height)<=2);default:return!0}}const Nn=_r.template.id,Gn="http://www.w3.org/2000/svg",Mn=/^H(\d+)$/,Un=new Set(["image/gif","image/jpeg","image/jpg","image/pjpeg","image/png","image/apng","image/x-png","image/bmp","image/x-ms-bmp","image/tiff","image/tif","application/octet-stream"]),xn=[[[66,77],"image/bmp"],[[255,216,255],"image/jpeg"],[[73,73,42,0],"image/tiff"],[[77,77,0,42],"image/tiff"],[[71,73,70,56,57,97],"image/gif"],[[137,80,78,71,13,10,26,10],"image/png"]];function getBorderDims(e){if(!e||!e.border)return{w:0,h:0};const t=e.border[ar]();return t?{w:t.widths[0]+t.widths[2]+t.insets[0]+t.insets[2],h:t.widths[1]+t.widths[3]+t.insets[1]+t.insets[3]}:{w:0,h:0}}function hasMargin(e){return e.margin&&(e.margin.topInset||e.margin.rightInset||e.margin.bottomInset||e.margin.leftInset)}function _setValue(e,t){if(!e.value){const t=new Value({});e[Hs](t);e.value=t}e.value[qr](t)}function*getContainedChildren(e){for(const t of e[rr]())t instanceof SubformSet?yield*t[nr]():yield t}function isRequired(e){return"error"===e.validate?.nullTest}function setTabIndex(e){for(;e;){if(!e.traversal){e[Or]=e[Ir]()[Or];return}if(e[Or])return;let t=null;for(const i of e.traversal[rr]())if("next"===i.operation){t=i;break}if(!t||!t.ref){e[Or]=e[Ir]()[Or];return}const i=e[cr]();e[Or]=++i[Or];const a=i[vr](t.ref,e);if(!a)return;e=a[0]}}function applyAssist(e,t){const i=e.assist;if(i){const e=i[jr]();e&&(t.title=e);const a=i.role.match(Mn);if(a){const e="heading",i=a[1];t.role=e;t["aria-level"]=i}}if("table"===e.layout)t.role="table";else if("row"===e.layout)t.role="row";else{const i=e[Ir]();"row"===i.layout&&(t.role="TH"===i.assist?.role?"columnheader":"cell")}}function ariaLabel(e){if(!e.assist)return null;const t=e.assist;return t.speak&&""!==t.speak[Os]?t.speak[Os]:t.toolTip?t.toolTip[Os]:null}function valueToHtml(e){return HTMLResult.success({name:"div",attributes:{class:["xfaRich"],style:Object.create(null)},children:[{name:"span",attributes:{style:Object.create(null)},value:e}]})}function setFirstUnsplittable(e){const t=e[cr]();if(null===t[Xs].firstUnsplittable){t[Xs].firstUnsplittable=e;t[Xs].noLayoutFailure=!0}}function unsetFirstUnsplittable(e){const t=e[cr]();t[Xs].firstUnsplittable===e&&(t[Xs].noLayoutFailure=!1)}function handleBreak(e){if(e[Xs])return!1;e[Xs]=Object.create(null);if("auto"===e.targetType)return!1;const t=e[cr]();let i=null;if(e.target){i=t[vr](e.target,e[Ir]());if(!i)return!1;i=i[0]}const{currentPageArea:a,currentContentArea:s}=t[Xs];if("pageArea"===e.targetType){i instanceof PageArea||(i=null);if(e.startNew){e[Xs].target=i||a;return!0}if(i&&i!==a){e[Xs].target=i;return!0}return!1}i instanceof ContentArea||(i=null);const r=i&&i[Ir]();let n,g=r;if(e.startNew)if(i){const e=r.contentArea.children,t=e.indexOf(s),a=e.indexOf(i);-1!==t&&te;a[Xs].noLayoutFailure=!0;const n=t[jr](i);e[Ls](n.html,n.bbox);a[Xs].noLayoutFailure=s;t[or]=r}class AppearanceFilter extends StringObject{constructor(e){super(Nn,"appearanceFilter");this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Arc extends XFAObject{constructor(e){super(Nn,"arc",!0);this.circular=getInteger({data:e.circular,defaultValue:0,validate:e=>1===e});this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.startAngle=getFloat({data:e.startAngle,defaultValue:0,validate:e=>!0});this.sweepAngle=getFloat({data:e.sweepAngle,defaultValue:360,validate:e=>!0});this.use=e.use||"";this.usehref=e.usehref||"";this.edge=null;this.fill=null}[jr](){const e=this.edge||new Edge({}),t=e[Zr](),i=Object.create(null);"visible"===this.fill?.presence?Object.assign(i,this.fill[Zr]()):i.fill="transparent";i.strokeWidth=measureToString("visible"===e.presence?e.thickness:0);i.stroke=t.color;let a;const s={xmlns:Gn,style:{width:"100%",height:"100%",overflow:"visible"}};if(360===this.sweepAngle)a={name:"ellipse",attributes:{xmlns:Gn,cx:"50%",cy:"50%",rx:"50%",ry:"50%",style:i}};else{const e=this.startAngle*Math.PI/180,t=this.sweepAngle*Math.PI/180,r=this.sweepAngle>180?1:0,[n,g,o,c]=[50*(1+Math.cos(e)),50*(1-Math.sin(e)),50*(1+Math.cos(e+t)),50*(1-Math.sin(e+t))];a={name:"path",attributes:{xmlns:Gn,d:`M ${n} ${g} A 50 50 0 ${r} 0 ${o} ${c}`,vectorEffect:"non-scaling-stroke",style:i}};Object.assign(s,{viewBox:"0 0 100 100",preserveAspectRatio:"none"})}const r={name:"svg",children:[a],attributes:s};if(hasMargin(this[Ir]()[Ir]()))return HTMLResult.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[r]});r.attributes.style.position="absolute";return HTMLResult.success(r)}}class Area extends XFAObject{constructor(e){super(Nn,"area",!0);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.id=e.id||"";this.name=e.name||"";this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.desc=null;this.extras=null;this.area=new XFAObjectArray;this.draw=new XFAObjectArray;this.exObject=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.field=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray}*[nr](){yield*getContainedChildren(this)}[Dr](){return!0}[dr](){return!0}[Ls](e,t){const[i,a,s,r]=t;this[Xs].width=Math.max(this[Xs].width,i+s);this[Xs].height=Math.max(this[Xs].height,a+r);this[Xs].children.push(e)}[$s](){return this[Xs].availableSpace}[jr](e){const t=toStyle(this,"position"),i={style:t,id:this[Vr],class:["xfaArea"]};isPrintOnly(this)&&i.class.push("xfaPrintOnly");this.name&&(i.xfaName=this.name);const a=[];this[Xs]={children:a,width:0,height:0,availableSpace:e};const s=this[Js]({filter:new Set(["area","draw","field","exclGroup","subform","subformSet"]),include:!0});if(!s.success){if(s.isBreak())return s;delete this[Xs];return HTMLResult.FAILURE}t.width=measureToString(this[Xs].width);t.height=measureToString(this[Xs].height);const r={name:"div",attributes:i,children:a},n=[this.x,this.y,this[Xs].width,this[Xs].height];delete this[Xs];return HTMLResult.success(r,n)}}class Assist extends XFAObject{constructor(e){super(Nn,"assist",!0);this.id=e.id||"";this.role=e.role||"";this.use=e.use||"";this.usehref=e.usehref||"";this.speak=null;this.toolTip=null}[jr](){return this.toolTip?.[Os]||null}}class Barcode extends XFAObject{constructor(e){super(Nn,"barcode",!0);this.charEncoding=getKeyword({data:e.charEncoding?e.charEncoding.toLowerCase():"",defaultValue:"",validate:e=>["utf-8","big-five","fontspecific","gbk","gb-18030","gb-2312","ksc-5601","none","shift-jis","ucs-2","utf-16"].includes(e)||e.match(/iso-8859-\d{2}/)});this.checksum=getStringOption(e.checksum,["none","1mod10","1mod10_1mod11","2mod10","auto"]);this.dataColumnCount=getInteger({data:e.dataColumnCount,defaultValue:-1,validate:e=>e>=0});this.dataLength=getInteger({data:e.dataLength,defaultValue:-1,validate:e=>e>=0});this.dataPrep=getStringOption(e.dataPrep,["none","flateCompress"]);this.dataRowCount=getInteger({data:e.dataRowCount,defaultValue:-1,validate:e=>e>=0});this.endChar=e.endChar||"";this.errorCorrectionLevel=getInteger({data:e.errorCorrectionLevel,defaultValue:-1,validate:e=>e>=0&&e<=8});this.id=e.id||"";this.moduleHeight=getMeasurement(e.moduleHeight,"5mm");this.moduleWidth=getMeasurement(e.moduleWidth,"0.25mm");this.printCheckDigit=getInteger({data:e.printCheckDigit,defaultValue:0,validate:e=>1===e});this.rowColumnRatio=getRatio(e.rowColumnRatio);this.startChar=e.startChar||"";this.textLocation=getStringOption(e.textLocation,["below","above","aboveEmbedded","belowEmbedded","none"]);this.truncate=getInteger({data:e.truncate,defaultValue:0,validate:e=>1===e});this.type=getStringOption(e.type?e.type.toLowerCase():"",["aztec","codabar","code2of5industrial","code2of5interleaved","code2of5matrix","code2of5standard","code3of9","code3of9extended","code11","code49","code93","code128","code128a","code128b","code128c","code128sscc","datamatrix","ean8","ean8add2","ean8add5","ean13","ean13add2","ean13add5","ean13pwcd","fim","logmars","maxicode","msi","pdf417","pdf417macro","plessey","postauscust2","postauscust3","postausreplypaid","postausstandard","postukrm4scc","postusdpbc","postusimb","postusstandard","postus5zip","qrcode","rfid","rss14","rss14expanded","rss14limited","rss14stacked","rss14stackedomni","rss14truncated","telepen","ucc128","ucc128random","ucc128sscc","upca","upcaadd2","upcaadd5","upcapwcd","upce","upceadd2","upceadd5","upcean2","upcean5","upsmaxicode"]);this.upsMode=getStringOption(e.upsMode,["usCarrier","internationalCarrier","secureSymbol","standardSymbol"]);this.use=e.use||"";this.usehref=e.usehref||"";this.wideNarrowRatio=getRatio(e.wideNarrowRatio);this.encrypt=null;this.extras=null}}class Bind extends XFAObject{constructor(e){super(Nn,"bind",!0);this.match=getStringOption(e.match,["once","dataRef","global","none"]);this.ref=e.ref||"";this.picture=null}}class BindItems extends XFAObject{constructor(e){super(Nn,"bindItems");this.connection=e.connection||"";this.labelRef=e.labelRef||"";this.ref=e.ref||"";this.valueRef=e.valueRef||""}}class Bookend extends XFAObject{constructor(e){super(Nn,"bookend");this.id=e.id||"";this.leader=e.leader||"";this.trailer=e.trailer||"";this.use=e.use||"";this.usehref=e.usehref||""}}class BooleanElement extends Option01{constructor(e){super(Nn,"boolean");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[jr](e){return valueToHtml(1===this[Os]?"1":"0")}}class Border extends XFAObject{constructor(e){super(Nn,"border",!0);this.break=getStringOption(e.break,["close","open"]);this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.corner=new XFAObjectArray(4);this.edge=new XFAObjectArray(4);this.extras=null;this.fill=null;this.margin=null}[ar](){if(!this[Xs]){const e=this.edge.children.slice();if(e.length<4){const t=e.at(-1)||new Edge({});for(let i=e.length;i<4;i++)e.push(t)}const t=e.map((e=>e.thickness)),i=[0,0,0,0];if(this.margin){i[0]=this.margin.topInset;i[1]=this.margin.rightInset;i[2]=this.margin.bottomInset;i[3]=this.margin.leftInset}this[Xs]={widths:t,insets:i,edges:e}}return this[Xs]}[Zr](){const{edges:e}=this[ar](),t=e.map((e=>{const t=e[Zr]();t.color||="#000000";return t})),i=Object.create(null);this.margin&&Object.assign(i,this.margin[Zr]());"visible"===this.fill?.presence&&Object.assign(i,this.fill[Zr]());if(this.corner.children.some((e=>0!==e.radius))){const e=this.corner.children.map((e=>e[Zr]()));if(2===e.length||3===e.length){const t=e.at(-1);for(let i=e.length;i<4;i++)e.push(t)}i.borderRadius=e.map((e=>e.radius)).join(" ")}switch(this.presence){case"invisible":case"hidden":i.borderStyle="";break;case"inactive":i.borderStyle="none";break;default:i.borderStyle=t.map((e=>e.style)).join(" ")}i.borderWidth=t.map((e=>e.width)).join(" ");i.borderColor=t.map((e=>e.color)).join(" ");return i}}class Break extends XFAObject{constructor(e){super(Nn,"break",!0);this.after=getStringOption(e.after,["auto","contentArea","pageArea","pageEven","pageOdd"]);this.afterTarget=e.afterTarget||"";this.before=getStringOption(e.before,["auto","contentArea","pageArea","pageEven","pageOdd"]);this.beforeTarget=e.beforeTarget||"";this.bookendLeader=e.bookendLeader||"";this.bookendTrailer=e.bookendTrailer||"";this.id=e.id||"";this.overflowLeader=e.overflowLeader||"";this.overflowTarget=e.overflowTarget||"";this.overflowTrailer=e.overflowTrailer||"";this.startNew=getInteger({data:e.startNew,defaultValue:0,validate:e=>1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}}class BreakAfter extends XFAObject{constructor(e){super(Nn,"breakAfter",!0);this.id=e.id||"";this.leader=e.leader||"";this.startNew=getInteger({data:e.startNew,defaultValue:0,validate:e=>1===e});this.target=e.target||"";this.targetType=getStringOption(e.targetType,["auto","contentArea","pageArea"]);this.trailer=e.trailer||"";this.use=e.use||"";this.usehref=e.usehref||"";this.script=null}}class BreakBefore extends XFAObject{constructor(e){super(Nn,"breakBefore",!0);this.id=e.id||"";this.leader=e.leader||"";this.startNew=getInteger({data:e.startNew,defaultValue:0,validate:e=>1===e});this.target=e.target||"";this.targetType=getStringOption(e.targetType,["auto","contentArea","pageArea"]);this.trailer=e.trailer||"";this.use=e.use||"";this.usehref=e.usehref||"";this.script=null}[jr](e){this[Xs]={};return HTMLResult.FAILURE}}class Button extends XFAObject{constructor(e){super(Nn,"button",!0);this.highlight=getStringOption(e.highlight,["inverted","none","outline","push"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[jr](e){const t=this[Ir]()[Ir](),i={name:"button",attributes:{id:this[Vr],class:["xfaButton"],style:{}},children:[]};for(const e of t.event.children){if("click"!==e.activity||!e.script)continue;const t=recoverJsURL(e.script[Os]);if(!t)continue;const a=fixURL(t.url);a&&i.children.push({name:"a",attributes:{id:"link"+this[Vr],href:a,newWindow:t.newWindow,class:["xfaLink"],style:{}},children:[]})}return HTMLResult.success(i)}}class Calculate extends XFAObject{constructor(e){super(Nn,"calculate",!0);this.id=e.id||"";this.override=getStringOption(e.override,["disabled","error","ignore","warning"]);this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.message=null;this.script=null}}class Caption extends XFAObject{constructor(e){super(Nn,"caption",!0);this.id=e.id||"";this.placement=getStringOption(e.placement,["left","bottom","inline","right","top"]);this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.reserve=Math.ceil(getMeasurement(e.reserve));this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.font=null;this.margin=null;this.para=null;this.value=null}[qr](e){_setValue(this,e)}[ar](e){if(!this[Xs]){let{width:t,height:i}=e;switch(this.placement){case"left":case"right":case"inline":t=this.reserve<=0?t:this.reserve;break;case"top":case"bottom":i=this.reserve<=0?i:this.reserve}this[Xs]=layoutNode(this,{width:t,height:i})}return this[Xs]}[jr](e){if(!this.value)return HTMLResult.EMPTY;this[Lr]();const t=this.value[jr](e).html;if(!t){this[xr]();return HTMLResult.EMPTY}const i=this.reserve;if(this.reserve<=0){const{w:t,h:i}=this[ar](e);switch(this.placement){case"left":case"right":case"inline":this.reserve=t;break;case"top":case"bottom":this.reserve=i}}const a=[];"string"==typeof t?a.push({name:"#text",value:t}):a.push(t);const s=toStyle(this,"font","margin","visibility");switch(this.placement){case"left":case"right":this.reserve>0&&(s.width=measureToString(this.reserve));break;case"top":case"bottom":this.reserve>0&&(s.height=measureToString(this.reserve))}setPara(this,null,t);this[xr]();this.reserve=i;return HTMLResult.success({name:"div",attributes:{style:s,class:["xfaCaption"]},children:a})}}class Certificate extends StringObject{constructor(e){super(Nn,"certificate");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Certificates extends XFAObject{constructor(e){super(Nn,"certificates",!0);this.credentialServerPolicy=getStringOption(e.credentialServerPolicy,["optional","required"]);this.id=e.id||"";this.url=e.url||"";this.urlPolicy=e.urlPolicy||"";this.use=e.use||"";this.usehref=e.usehref||"";this.encryption=null;this.issuers=null;this.keyUsage=null;this.oids=null;this.signing=null;this.subjectDNs=null}}class CheckButton extends XFAObject{constructor(e){super(Nn,"checkButton",!0);this.id=e.id||"";this.mark=getStringOption(e.mark,["default","check","circle","cross","diamond","square","star"]);this.shape=getStringOption(e.shape,["square","round"]);this.size=getMeasurement(e.size,"10pt");this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}[jr](e){const t=toStyle("margin"),i=measureToString(this.size);t.width=t.height=i;let a,s,r;const n=this[Ir]()[Ir](),g=n.items.children.length&&n.items.children[0][jr]().html||[],o={on:(void 0!==g[0]?g[0]:"on").toString(),off:(void 0!==g[1]?g[1]:"off").toString()},c=(n.value?.[Pr]()||"off")===o.on||void 0,C=n[or](),h=n[Vr];let l;if(C instanceof ExclGroup){r=C[Vr];a="radio";s="xfaRadio";l=C[Ws]?.[Vr]||C[Vr]}else{a="checkbox";s="xfaCheckbox";l=n[Ws]?.[Vr]||n[Vr]}const Q={name:"input",attributes:{class:[s],style:t,fieldId:h,dataId:l,type:a,checked:c,xfaOn:o.on,xfaOff:o.off,"aria-label":ariaLabel(n),"aria-required":!1}};r&&(Q.attributes.name=r);if(isRequired(n)){Q.attributes["aria-required"]=!0;Q.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[Q]})}}class ChoiceList extends XFAObject{constructor(e){super(Nn,"choiceList",!0);this.commitOn=getStringOption(e.commitOn,["select","exit"]);this.id=e.id||"";this.open=getStringOption(e.open,["userControl","always","multiSelect","onEntry"]);this.textEntry=getInteger({data:e.textEntry,defaultValue:0,validate:e=>1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}[jr](e){const t=toStyle(this,"border","margin"),i=this[Ir]()[Ir](),a={fontSize:`calc(${i.font?.size||10}px * var(--scale-factor))`},s=[];if(i.items.children.length>0){const e=i.items;let t=0,r=0;if(2===e.children.length){t=e.children[0].save;r=1-t}const n=e.children[t][jr]().html,g=e.children[r][jr]().html;let o=!1;const c=i.value?.[Pr]()||"";for(let e=0,t=n.length;eMath.min(Math.max(0,parseInt(e.trim(),10)),255))).map((e=>isNaN(e)?0:e));if(r.length<3)return{r:i,g:a,b:s};[i,a,s]=r;return{r:i,g:a,b:s}}(e.value):"";this.extras=null}[hr](){return!1}[Zr](){return this.value?Util.makeHexColor(this.value.r,this.value.g,this.value.b):null}}class Comb extends XFAObject{constructor(e){super(Nn,"comb");this.id=e.id||"";this.numberOfCells=getInteger({data:e.numberOfCells,defaultValue:0,validate:e=>e>=0});this.use=e.use||"";this.usehref=e.usehref||""}}class Connect extends XFAObject{constructor(e){super(Nn,"connect",!0);this.connection=e.connection||"";this.id=e.id||"";this.ref=e.ref||"";this.usage=getStringOption(e.usage,["exportAndImport","exportOnly","importOnly"]);this.use=e.use||"";this.usehref=e.usehref||"";this.picture=null}}class ContentArea extends XFAObject{constructor(e){super(Nn,"contentArea",!0);this.h=getMeasurement(e.h);this.id=e.id||"";this.name=e.name||"";this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.w=getMeasurement(e.w);this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.desc=null;this.extras=null}[jr](e){const t={left:measureToString(this.x),top:measureToString(this.y),width:measureToString(this.w),height:measureToString(this.h)},i=["xfaContentarea"];isPrintOnly(this)&&i.push("xfaPrintOnly");return HTMLResult.success({name:"div",children:[],attributes:{style:t,class:i,id:this[Vr]}})}}class Corner extends XFAObject{constructor(e){super(Nn,"corner",!0);this.id=e.id||"";this.inverted=getInteger({data:e.inverted,defaultValue:0,validate:e=>1===e});this.join=getStringOption(e.join,["square","round"]);this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.radius=getMeasurement(e.radius);this.stroke=getStringOption(e.stroke,["solid","dashDot","dashDotDot","dashed","dotted","embossed","etched","lowered","raised"]);this.thickness=getMeasurement(e.thickness,"0.5pt");this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zr](){const e=toStyle(this,"visibility");e.radius=measureToString("square"===this.join?0:this.radius);return e}}class DateElement extends ContentObject{constructor(e){super(Nn,"date");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){const e=this[Os].trim();this[Os]=e?new Date(e):null}[jr](e){return valueToHtml(this[Os]?this[Os].toString():"")}}class DateTime extends ContentObject{constructor(e){super(Nn,"dateTime");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){const e=this[Os].trim();this[Os]=e?new Date(e):null}[jr](e){return valueToHtml(this[Os]?this[Os].toString():"")}}class DateTimeEdit extends XFAObject{constructor(e){super(Nn,"dateTimeEdit",!0);this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.picker=getStringOption(e.picker,["host","none"]);this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.comb=null;this.extras=null;this.margin=null}[jr](e){const t=toStyle(this,"border","font","margin"),i=this[Ir]()[Ir](),a={name:"input",attributes:{type:"text",fieldId:i[Vr],dataId:i[Ws]?.[Vr]||i[Vr],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(i),"aria-required":!1}};if(isRequired(i)){a.attributes["aria-required"]=!0;a.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[a]})}}class Decimal extends ContentObject{constructor(e){super(Nn,"decimal");this.fracDigits=getInteger({data:e.fracDigits,defaultValue:2,validate:e=>!0});this.id=e.id||"";this.leadDigits=getInteger({data:e.leadDigits,defaultValue:-1,validate:e=>!0});this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){const e=parseFloat(this[Os].trim());this[Os]=isNaN(e)?null:e}[jr](e){return valueToHtml(null!==this[Os]?this[Os].toString():"")}}class DefaultUi extends XFAObject{constructor(e){super(Nn,"defaultUi",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}}class Desc extends XFAObject{constructor(e){super(Nn,"desc",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}}class DigestMethod extends OptionObject{constructor(e){super(Nn,"digestMethod",["","SHA1","SHA256","SHA512","RIPEMD160"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class DigestMethods extends XFAObject{constructor(e){super(Nn,"digestMethods",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.digestMethod=new XFAObjectArray}}class Draw extends XFAObject{constructor(e){super(Nn,"draw",!0);this.anchorType=getStringOption(e.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.locale=e.locale||"";this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.rotate=getInteger({data:e.rotate,defaultValue:0,validate:e=>e%90==0});this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.border=null;this.caption=null;this.desc=null;this.extras=null;this.font=null;this.keep=null;this.margin=null;this.para=null;this.traversal=null;this.ui=null;this.value=null;this.setProperty=new XFAObjectArray}[qr](e){_setValue(this,e)}[jr](e){setTabIndex(this);if("hidden"===this.presence||"inactive"===this.presence)return HTMLResult.EMPTY;fixDimensions(this);this[Lr]();const t=this.w,i=this.h,{w:a,h:s,isBroken:r}=layoutNode(this,e);if(a&&""===this.w){if(r&&this[or]()[wr]()){this[xr]();return HTMLResult.FAILURE}this.w=a}s&&""===this.h&&(this.h=s);setFirstUnsplittable(this);if(!checkDimensions(this,e)){this.w=t;this.h=i;this[xr]();return HTMLResult.FAILURE}unsetFirstUnsplittable(this);const n=toStyle(this,"font","hAlign","dimensions","position","presence","rotate","anchorType","border","margin");setMinMaxDimensions(this,n);if(n.margin){n.padding=n.margin;delete n.margin}const g=["xfaDraw"];this.font&&g.push("xfaFont");isPrintOnly(this)&&g.push("xfaPrintOnly");const o={style:n,id:this[Vr],class:g};this.name&&(o.xfaName=this.name);const c={name:"div",attributes:o,children:[]};applyAssist(this,o);const C=computeBbox(this,c,e),h=this.value?this.value[jr](e).html:null;if(null===h){this.w=t;this.h=i;this[xr]();return HTMLResult.success(createWrapper(this,c),C)}c.children.push(h);setPara(this,n,h);this.w=t;this.h=i;this[xr]();return HTMLResult.success(createWrapper(this,c),C)}}class Edge extends XFAObject{constructor(e){super(Nn,"edge",!0);this.cap=getStringOption(e.cap,["square","butt","round"]);this.id=e.id||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.stroke=getStringOption(e.stroke,["solid","dashDot","dashDotDot","dashed","dotted","embossed","etched","lowered","raised"]);this.thickness=getMeasurement(e.thickness,"0.5pt");this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zr](){const e=toStyle(this,"visibility");Object.assign(e,{linecap:this.cap,width:measureToString(this.thickness),color:this.color?this.color[Zr]():"#000000",style:""});if("visible"!==this.presence)e.style="none";else switch(this.stroke){case"solid":e.style="solid";break;case"dashDot":case"dashDotDot":case"dashed":e.style="dashed";break;case"dotted":e.style="dotted";break;case"embossed":e.style="ridge";break;case"etched":e.style="groove";break;case"lowered":e.style="inset";break;case"raised":e.style="outset"}return e}}class Encoding extends OptionObject{constructor(e){super(Nn,"encoding",["adbe.x509.rsa_sha1","adbe.pkcs7.detached","adbe.pkcs7.sha1"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Encodings extends XFAObject{constructor(e){super(Nn,"encodings",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.encoding=new XFAObjectArray}}class Encrypt extends XFAObject{constructor(e){super(Nn,"encrypt",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=null}}class EncryptData extends XFAObject{constructor(e){super(Nn,"encryptData",!0);this.id=e.id||"";this.operation=getStringOption(e.operation,["encrypt","decrypt"]);this.target=e.target||"";this.use=e.use||"";this.usehref=e.usehref||"";this.filter=null;this.manifest=null}}class Encryption extends XFAObject{constructor(e){super(Nn,"encryption",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=new XFAObjectArray}}class EncryptionMethod extends OptionObject{constructor(e){super(Nn,"encryptionMethod",["","AES256-CBC","TRIPLEDES-CBC","AES128-CBC","AES192-CBC"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class EncryptionMethods extends XFAObject{constructor(e){super(Nn,"encryptionMethods",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.encryptionMethod=new XFAObjectArray}}class Event extends XFAObject{constructor(e){super(Nn,"event",!0);this.activity=getStringOption(e.activity,["click","change","docClose","docReady","enter","exit","full","indexChange","initialize","mouseDown","mouseEnter","mouseExit","mouseUp","postExecute","postOpen","postPrint","postSave","postSign","postSubmit","preExecute","preOpen","prePrint","preSave","preSign","preSubmit","ready","validationState"]);this.id=e.id||"";this.listen=getStringOption(e.listen,["refOnly","refAndDescendents"]);this.name=e.name||"";this.ref=e.ref||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.encryptData=null;this.execute=null;this.script=null;this.signData=null;this.submit=null}}class ExData extends ContentObject{constructor(e){super(Nn,"exData");this.contentType=e.contentType||"";this.href=e.href||"";this.id=e.id||"";this.maxLength=getInteger({data:e.maxLength,defaultValue:-1,validate:e=>e>=-1});this.name=e.name||"";this.rid=e.rid||"";this.transferEncoding=getStringOption(e.transferEncoding,["none","base64","package"]);this.use=e.use||"";this.usehref=e.usehref||""}[ur](){return"text/html"===this.contentType}[Nr](e){if("text/html"===this.contentType&&e[Sr]===_r.xhtml.id){this[Os]=e;return!0}if("text/xml"===this.contentType){this[Os]=e;return!0}return!1}[jr](e){return"text/html"===this.contentType&&this[Os]?this[Os][jr](e):HTMLResult.EMPTY}}class ExObject extends XFAObject{constructor(e){super(Nn,"exObject",!0);this.archive=e.archive||"";this.classId=e.classId||"";this.codeBase=e.codeBase||"";this.codeType=e.codeType||"";this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.exObject=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}}class ExclGroup extends XFAObject{constructor(e){super(Nn,"exclGroup",!0);this.access=getStringOption(e.access,["open","nonInteractive","protected","readOnly"]);this.accessKey=e.accessKey||"";this.anchorType=getStringOption(e.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.layout=getStringOption(e.layout,["position","lr-tb","rl-row","rl-tb","row","table","tb"]);this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.bind=null;this.border=null;this.calculate=null;this.caption=null;this.desc=null;this.extras=null;this.margin=null;this.para=null;this.traversal=null;this.validate=null;this.connect=new XFAObjectArray;this.event=new XFAObjectArray;this.field=new XFAObjectArray;this.setProperty=new XFAObjectArray}[dr](){return!0}[hr](){return!0}[qr](e){for(const t of this.field.children){if(!t.value){const e=new Value({});t[Hs](e);t.value=e}t.value[qr](e)}}[wr](){return this.layout.endsWith("-tb")&&0===this[Xs].attempt&&this[Xs].numberInLine>0||this[Ir]()[wr]()}[yr](){const e=this[or]();if(!e[yr]())return!1;if(void 0!==this[Xs]._isSplittable)return this[Xs]._isSplittable;if("position"===this.layout||this.layout.includes("row")){this[Xs]._isSplittable=!1;return!1}if(e.layout?.endsWith("-tb")&&0!==e[Xs].numberInLine)return!1;this[Xs]._isSplittable=!0;return!0}[Vs](){return flushHTML(this)}[Ls](e,t){addHTML(this,e,t)}[$s](){return getAvailableSpace(this)}[jr](e){setTabIndex(this);if("hidden"===this.presence||"inactive"===this.presence||0===this.h||0===this.w)return HTMLResult.EMPTY;fixDimensions(this);const t=[],i={id:this[Vr],class:[]};setAccess(this,i.class);this[Xs]||(this[Xs]=Object.create(null));Object.assign(this[Xs],{children:t,attributes:i,attempt:0,line:null,numberInLine:0,availableSpace:{width:Math.min(this.w||1/0,e.width),height:Math.min(this.h||1/0,e.height)},width:0,height:0,prevHeight:0,currentWidth:0});const a=this[yr]();a||setFirstUnsplittable(this);if(!checkDimensions(this,e))return HTMLResult.FAILURE;const s=new Set(["field"]);if(this.layout.includes("row")){const e=this[or]().columnWidths;if(Array.isArray(e)&&e.length>0){this[Xs].columnWidths=e;this[Xs].currentColumn=0}}const r=toStyle(this,"anchorType","dimensions","position","presence","border","margin","hAlign"),n=["xfaExclgroup"],g=layoutClass(this);g&&n.push(g);isPrintOnly(this)&&n.push("xfaPrintOnly");i.style=r;i.class=n;this.name&&(i.xfaName=this.name);this[Lr]();const o="lr-tb"===this.layout||"rl-tb"===this.layout,c=o?2:1;for(;this[Xs].attempte>=1||-1===e});this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.locale=e.locale||"";this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.rotate=getInteger({data:e.rotate,defaultValue:0,validate:e=>e%90==0});this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.bind=null;this.border=null;this.calculate=null;this.caption=null;this.desc=null;this.extras=null;this.font=null;this.format=null;this.items=new XFAObjectArray(2);this.keep=null;this.margin=null;this.para=null;this.traversal=null;this.ui=null;this.validate=null;this.value=null;this.bindItems=new XFAObjectArray;this.connect=new XFAObjectArray;this.event=new XFAObjectArray;this.setProperty=new XFAObjectArray}[dr](){return!0}[qr](e){_setValue(this,e)}[jr](e){setTabIndex(this);if(!this.ui){this.ui=new Ui({});this.ui[Cr]=this[Cr];this[Hs](this.ui);let e;switch(this.items.children.length){case 0:e=new TextEdit({});this.ui.textEdit=e;break;case 1:e=new CheckButton({});this.ui.checkButton=e;break;case 2:e=new ChoiceList({});this.ui.choiceList=e}this.ui[Hs](e)}if(!this.ui||"hidden"===this.presence||"inactive"===this.presence||0===this.h||0===this.w)return HTMLResult.EMPTY;this.caption&&delete this.caption[Xs];this[Lr]();const t=this.caption?this.caption[jr](e).html:null,i=this.w,a=this.h;let s=0,r=0;if(this.margin){s=this.margin.leftInset+this.margin.rightInset;r=this.margin.topInset+this.margin.bottomInset}let n=null;if(""===this.w||""===this.h){let t=null,i=null,a=0,g=0;if(this.ui.checkButton)a=g=this.ui.checkButton.size;else{const{w:t,h:i}=layoutNode(this,e);if(null!==t){a=t;g=i}else g=function fonts_getMetrics(e,t=!1){let i=null;if(e){const t=stripQuotes(e.typeface),a=e[Cr].fontFinder.find(t);i=selectFont(e,a)}if(!i)return{lineHeight:12,lineGap:2,lineNoGap:10};const a=e.size||10,s=i.lineHeight?Math.max(t?0:1.2,i.lineHeight):1.2,r=void 0===i.lineGap?.2:i.lineGap;return{lineHeight:s*a,lineGap:r*a,lineNoGap:Math.max(1,s-r)*a}}(this.font,!0).lineNoGap}n=getBorderDims(this.ui[ar]());a+=n.w;g+=n.h;if(this.caption){const{w:s,h:r,isBroken:n}=this.caption[ar](e);if(n&&this[or]()[wr]()){this[xr]();return HTMLResult.FAILURE}t=s;i=r;switch(this.caption.placement){case"left":case"right":case"inline":t+=a;break;case"top":case"bottom":i+=g}}else{t=a;i=g}if(t&&""===this.w){t+=s;this.w=Math.min(this.maxW<=0?1/0:this.maxW,this.minW+1e>=1&&e<=5});this.appearanceFilter=null;this.certificates=null;this.digestMethods=null;this.encodings=null;this.encryptionMethods=null;this.handler=null;this.lockDocument=null;this.mdp=null;this.reasons=null;this.timeStamp=null}}class Float extends ContentObject{constructor(e){super(Nn,"float");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){const e=parseFloat(this[Os].trim());this[Os]=isNaN(e)?null:e}[jr](e){return valueToHtml(null!==this[Os]?this[Os].toString():"")}}class template_Font extends XFAObject{constructor(e){super(Nn,"font",!0);this.baselineShift=getMeasurement(e.baselineShift);this.fontHorizontalScale=getFloat({data:e.fontHorizontalScale,defaultValue:100,validate:e=>e>=0});this.fontVerticalScale=getFloat({data:e.fontVerticalScale,defaultValue:100,validate:e=>e>=0});this.id=e.id||"";this.kerningMode=getStringOption(e.kerningMode,["none","pair"]);this.letterSpacing=getMeasurement(e.letterSpacing,"0");this.lineThrough=getInteger({data:e.lineThrough,defaultValue:0,validate:e=>1===e||2===e});this.lineThroughPeriod=getStringOption(e.lineThroughPeriod,["all","word"]);this.overline=getInteger({data:e.overline,defaultValue:0,validate:e=>1===e||2===e});this.overlinePeriod=getStringOption(e.overlinePeriod,["all","word"]);this.posture=getStringOption(e.posture,["normal","italic"]);this.size=getMeasurement(e.size,"10pt");this.typeface=e.typeface||"Courier";this.underline=getInteger({data:e.underline,defaultValue:0,validate:e=>1===e||2===e});this.underlinePeriod=getStringOption(e.underlinePeriod,["all","word"]);this.use=e.use||"";this.usehref=e.usehref||"";this.weight=getStringOption(e.weight,["normal","bold"]);this.extras=null;this.fill=null}[Ys](e){super[Ys](e);this[Cr].usedTypefaces.add(this.typeface)}[Zr](){const e=toStyle(this,"fill"),t=e.color;if(t)if("#000000"===t)delete e.color;else if(!t.startsWith("#")){e.background=t;e.backgroundClip="text";e.color="transparent"}this.baselineShift&&(e.verticalAlign=measureToString(this.baselineShift));e.fontKerning="none"===this.kerningMode?"none":"normal";e.letterSpacing=measureToString(this.letterSpacing);if(0!==this.lineThrough){e.textDecoration="line-through";2===this.lineThrough&&(e.textDecorationStyle="double")}if(0!==this.overline){e.textDecoration="overline";2===this.overline&&(e.textDecorationStyle="double")}e.fontStyle=this.posture;e.fontSize=measureToString(.99*this.size);setFontFamily(this,this,this[Cr].fontFinder,e);if(0!==this.underline){e.textDecoration="underline";2===this.underline&&(e.textDecorationStyle="double")}e.fontWeight=this.weight;return e}}class Format extends XFAObject{constructor(e){super(Nn,"format",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.picture=null}}class Handler extends StringObject{constructor(e){super(Nn,"handler");this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Hyphenation extends XFAObject{constructor(e){super(Nn,"hyphenation");this.excludeAllCaps=getInteger({data:e.excludeAllCaps,defaultValue:0,validate:e=>1===e});this.excludeInitialCap=getInteger({data:e.excludeInitialCap,defaultValue:0,validate:e=>1===e});this.hyphenate=getInteger({data:e.hyphenate,defaultValue:0,validate:e=>1===e});this.id=e.id||"";this.pushCharacterCount=getInteger({data:e.pushCharacterCount,defaultValue:3,validate:e=>e>=0});this.remainCharacterCount=getInteger({data:e.remainCharacterCount,defaultValue:3,validate:e=>e>=0});this.use=e.use||"";this.usehref=e.usehref||"";this.wordCharacterCount=getInteger({data:e.wordCharacterCount,defaultValue:7,validate:e=>e>=0})}}class Image extends StringObject{constructor(e){super(Nn,"image");this.aspect=getStringOption(e.aspect,["fit","actual","height","none","width"]);this.contentType=e.contentType||"";this.href=e.href||"";this.id=e.id||"";this.name=e.name||"";this.transferEncoding=getStringOption(e.transferEncoding,["base64","none","package"]);this.use=e.use||"";this.usehref=e.usehref||""}[jr](){if(this.contentType&&!Un.has(this.contentType.toLowerCase()))return HTMLResult.EMPTY;let e=this[Cr].images&&this[Cr].images.get(this.href);if(!e&&(this.href||!this[Os]))return HTMLResult.EMPTY;e||"base64"!==this.transferEncoding||(e=function fromBase64Util(e){return Uint8Array.fromBase64?Uint8Array.fromBase64(e):stringToBytes(atob(e))}(this[Os]));if(!e)return HTMLResult.EMPTY;if(!this.contentType){for(const[t,i]of xn)if(e.length>t.length&&t.every(((t,i)=>t===e[i]))){this.contentType=i;break}if(!this.contentType)return HTMLResult.EMPTY}const t=new Blob([e],{type:this.contentType});let i;switch(this.aspect){case"fit":case"actual":break;case"height":i={height:"100%",objectFit:"fill"};break;case"none":i={width:"100%",height:"100%",objectFit:"fill"};break;case"width":i={width:"100%",objectFit:"fill"}}const a=this[Ir]();return HTMLResult.success({name:"img",attributes:{class:["xfaImage"],style:i,src:URL.createObjectURL(t),alt:a?ariaLabel(a[Ir]()):null}})}}class ImageEdit extends XFAObject{constructor(e){super(Nn,"imageEdit",!0);this.data=getStringOption(e.data,["link","embed"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}[jr](e){return"embed"===this.data?HTMLResult.success({name:"div",children:[],attributes:{}}):HTMLResult.EMPTY}}class Integer extends ContentObject{constructor(e){super(Nn,"integer");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){const e=parseInt(this[Os].trim(),10);this[Os]=isNaN(e)?null:e}[jr](e){return valueToHtml(null!==this[Os]?this[Os].toString():"")}}class Issuers extends XFAObject{constructor(e){super(Nn,"issuers",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=new XFAObjectArray}}class Items extends XFAObject{constructor(e){super(Nn,"items",!0);this.id=e.id||"";this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.ref=e.ref||"";this.save=getInteger({data:e.save,defaultValue:0,validate:e=>1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}[jr](){const e=[];for(const t of this[rr]())e.push(t[Pr]());return HTMLResult.success(e)}}class Keep extends XFAObject{constructor(e){super(Nn,"keep",!0);this.id=e.id||"";const t=["none","contentArea","pageArea"];this.intact=getStringOption(e.intact,t);this.next=getStringOption(e.next,t);this.previous=getStringOption(e.previous,t);this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}}class KeyUsage extends XFAObject{constructor(e){super(Nn,"keyUsage");const t=["","yes","no"];this.crlSign=getStringOption(e.crlSign,t);this.dataEncipherment=getStringOption(e.dataEncipherment,t);this.decipherOnly=getStringOption(e.decipherOnly,t);this.digitalSignature=getStringOption(e.digitalSignature,t);this.encipherOnly=getStringOption(e.encipherOnly,t);this.id=e.id||"";this.keyAgreement=getStringOption(e.keyAgreement,t);this.keyCertSign=getStringOption(e.keyCertSign,t);this.keyEncipherment=getStringOption(e.keyEncipherment,t);this.nonRepudiation=getStringOption(e.nonRepudiation,t);this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Line extends XFAObject{constructor(e){super(Nn,"line",!0);this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.slope=getStringOption(e.slope,["\\","/"]);this.use=e.use||"";this.usehref=e.usehref||"";this.edge=null}[jr](){const e=this[Ir]()[Ir](),t=this.edge||new Edge({}),i=t[Zr](),a=Object.create(null),s="visible"===t.presence?t.thickness:0;a.strokeWidth=measureToString(s);a.stroke=i.color;let r,n,g,o,c="100%",C="100%";if(e.w<=s){[r,n,g,o]=["50%",0,"50%","100%"];c=a.strokeWidth}else if(e.h<=s){[r,n,g,o]=[0,"50%","100%","50%"];C=a.strokeWidth}else"\\"===this.slope?[r,n,g,o]=[0,0,"100%","100%"]:[r,n,g,o]=[0,"100%","100%",0];const h={name:"svg",children:[{name:"line",attributes:{xmlns:Gn,x1:r,y1:n,x2:g,y2:o,style:a}}],attributes:{xmlns:Gn,width:c,height:C,style:{overflow:"visible"}}};if(hasMargin(e))return HTMLResult.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[h]});h.attributes.style.position="absolute";return HTMLResult.success(h)}}class Linear extends XFAObject{constructor(e){super(Nn,"linear",!0);this.id=e.id||"";this.type=getStringOption(e.type,["toRight","toBottom","toLeft","toTop"]);this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zr](e){e=e?e[Zr]():"#FFFFFF";return`linear-gradient(${this.type.replace(/([RBLT])/," $1").toLowerCase()}, ${e}, ${this.color?this.color[Zr]():"#000000"})`}}class LockDocument extends ContentObject{constructor(e){super(Nn,"lockDocument");this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){this[Os]=getStringOption(this[Os],["auto","0","1"])}}class Manifest extends XFAObject{constructor(e){super(Nn,"manifest",!0);this.action=getStringOption(e.action,["include","all","exclude"]);this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.ref=new XFAObjectArray}}class Margin extends XFAObject{constructor(e){super(Nn,"margin",!0);this.bottomInset=getMeasurement(e.bottomInset,"0");this.id=e.id||"";this.leftInset=getMeasurement(e.leftInset,"0");this.rightInset=getMeasurement(e.rightInset,"0");this.topInset=getMeasurement(e.topInset,"0");this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[Zr](){return{margin:measureToString(this.topInset)+" "+measureToString(this.rightInset)+" "+measureToString(this.bottomInset)+" "+measureToString(this.leftInset)}}}class Mdp extends XFAObject{constructor(e){super(Nn,"mdp");this.id=e.id||"";this.permissions=getInteger({data:e.permissions,defaultValue:2,validate:e=>1===e||3===e});this.signatureType=getStringOption(e.signatureType,["filler","author"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Medium extends XFAObject{constructor(e){super(Nn,"medium");this.id=e.id||"";this.imagingBBox=function getBBox(e){const t=-1;if(!e)return{x:t,y:t,width:t,height:t};const i=e.trim().split(/\s*,\s*/).map((e=>getMeasurement(e,"-1")));if(i.length<4||i[2]<0||i[3]<0)return{x:t,y:t,width:t,height:t};const[a,s,r,n]=i;return{x:a,y:s,width:r,height:n}}(e.imagingBBox);this.long=getMeasurement(e.long);this.orientation=getStringOption(e.orientation,["portrait","landscape"]);this.short=getMeasurement(e.short);this.stock=e.stock||"";this.trayIn=getStringOption(e.trayIn,["auto","delegate","pageFront"]);this.trayOut=getStringOption(e.trayOut,["auto","delegate"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Message extends XFAObject{constructor(e){super(Nn,"message",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.text=new XFAObjectArray}}class NumericEdit extends XFAObject{constructor(e){super(Nn,"numericEdit",!0);this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.comb=null;this.extras=null;this.margin=null}[jr](e){const t=toStyle(this,"border","font","margin"),i=this[Ir]()[Ir](),a={name:"input",attributes:{type:"text",fieldId:i[Vr],dataId:i[Ws]?.[Vr]||i[Vr],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(i),"aria-required":!1}};if(isRequired(i)){a.attributes["aria-required"]=!0;a.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[a]})}}class Occur extends XFAObject{constructor(e){super(Nn,"occur",!0);this.id=e.id||"";this.initial=""!==e.initial?getInteger({data:e.initial,defaultValue:"",validate:e=>!0}):"";this.max=""!==e.max?getInteger({data:e.max,defaultValue:1,validate:e=>!0}):"";this.min=""!==e.min?getInteger({data:e.min,defaultValue:1,validate:e=>!0}):"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[Ys](){const e=this[Ir](),t=this.min;""===this.min&&(this.min=e instanceof PageArea||e instanceof PageSet?0:1);""===this.max&&(this.max=""===t?e instanceof PageArea||e instanceof PageSet?-1:1:this.min);-1!==this.max&&this.max!0});this.name=e.name||"";this.numbered=getInteger({data:e.numbered,defaultValue:1,validate:e=>!0});this.oddOrEven=getStringOption(e.oddOrEven,["any","even","odd"]);this.pagePosition=getStringOption(e.pagePosition,["any","first","last","only","rest"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.desc=null;this.extras=null;this.medium=null;this.occur=null;this.area=new XFAObjectArray;this.contentArea=new XFAObjectArray;this.draw=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.field=new XFAObjectArray;this.subform=new XFAObjectArray}[br](){if(!this[Xs]){this[Xs]={numberOfUse:0};return!0}return!this.occur||-1===this.occur.max||this[Xs].numberOfUsee.oddOrEven===t&&e.pagePosition===i));if(a)return a;a=this.pageArea.children.find((e=>"any"===e.oddOrEven&&e.pagePosition===i));if(a)return a;a=this.pageArea.children.find((e=>"any"===e.oddOrEven&&"any"===e.pagePosition));return a||this.pageArea.children[0]}}class Para extends XFAObject{constructor(e){super(Nn,"para",!0);this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.lineHeight=e.lineHeight?getMeasurement(e.lineHeight,"0pt"):"";this.marginLeft=e.marginLeft?getMeasurement(e.marginLeft,"0pt"):"";this.marginRight=e.marginRight?getMeasurement(e.marginRight,"0pt"):"";this.orphans=getInteger({data:e.orphans,defaultValue:0,validate:e=>e>=0});this.preserve=e.preserve||"";this.radixOffset=e.radixOffset?getMeasurement(e.radixOffset,"0pt"):"";this.spaceAbove=e.spaceAbove?getMeasurement(e.spaceAbove,"0pt"):"";this.spaceBelow=e.spaceBelow?getMeasurement(e.spaceBelow,"0pt"):"";this.tabDefault=e.tabDefault?getMeasurement(this.tabDefault):"";this.tabStops=(e.tabStops||"").trim().split(/\s+/).map(((e,t)=>t%2==1?getMeasurement(e):e));this.textIndent=e.textIndent?getMeasurement(e.textIndent,"0pt"):"";this.use=e.use||"";this.usehref=e.usehref||"";this.vAlign=getStringOption(e.vAlign,["top","bottom","middle"]);this.widows=getInteger({data:e.widows,defaultValue:0,validate:e=>e>=0});this.hyphenation=null}[Zr](){const e=toStyle(this,"hAlign");""!==this.marginLeft&&(e.paddingLeft=measureToString(this.marginLeft));""!==this.marginRight&&(e.paddingRight=measureToString(this.marginRight));""!==this.spaceAbove&&(e.paddingTop=measureToString(this.spaceAbove));""!==this.spaceBelow&&(e.paddingBottom=measureToString(this.spaceBelow));if(""!==this.textIndent){e.textIndent=measureToString(this.textIndent);fixTextIndent(e)}this.lineHeight>0&&(e.lineHeight=measureToString(this.lineHeight));""!==this.tabDefault&&(e.tabSize=measureToString(this.tabDefault));this.tabStops.length;this.hyphenatation&&Object.assign(e,this.hyphenatation[Zr]());return e}}class PasswordEdit extends XFAObject{constructor(e){super(Nn,"passwordEdit",!0);this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.passwordChar=e.passwordChar||"*";this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}}class template_Pattern extends XFAObject{constructor(e){super(Nn,"pattern",!0);this.id=e.id||"";this.type=getStringOption(e.type,["crossHatch","crossDiagonal","diagonalLeft","diagonalRight","horizontal","vertical"]);this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zr](e){e=e?e[Zr]():"#FFFFFF";const t=this.color?this.color[Zr]():"#000000",i="repeating-linear-gradient",a=`${e},${e} 5px,${t} 5px,${t} 10px`;switch(this.type){case"crossHatch":return`${i}(to top,${a}) ${i}(to right,${a})`;case"crossDiagonal":return`${i}(45deg,${a}) ${i}(-45deg,${a})`;case"diagonalLeft":return`${i}(45deg,${a})`;case"diagonalRight":return`${i}(-45deg,${a})`;case"horizontal":return`${i}(to top,${a})`;case"vertical":return`${i}(to right,${a})`}return""}}class Picture extends StringObject{constructor(e){super(Nn,"picture");this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Proto extends XFAObject{constructor(e){super(Nn,"proto",!0);this.appearanceFilter=new XFAObjectArray;this.arc=new XFAObjectArray;this.area=new XFAObjectArray;this.assist=new XFAObjectArray;this.barcode=new XFAObjectArray;this.bindItems=new XFAObjectArray;this.bookend=new XFAObjectArray;this.boolean=new XFAObjectArray;this.border=new XFAObjectArray;this.break=new XFAObjectArray;this.breakAfter=new XFAObjectArray;this.breakBefore=new XFAObjectArray;this.button=new XFAObjectArray;this.calculate=new XFAObjectArray;this.caption=new XFAObjectArray;this.certificate=new XFAObjectArray;this.certificates=new XFAObjectArray;this.checkButton=new XFAObjectArray;this.choiceList=new XFAObjectArray;this.color=new XFAObjectArray;this.comb=new XFAObjectArray;this.connect=new XFAObjectArray;this.contentArea=new XFAObjectArray;this.corner=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.dateTimeEdit=new XFAObjectArray;this.decimal=new XFAObjectArray;this.defaultUi=new XFAObjectArray;this.desc=new XFAObjectArray;this.digestMethod=new XFAObjectArray;this.digestMethods=new XFAObjectArray;this.draw=new XFAObjectArray;this.edge=new XFAObjectArray;this.encoding=new XFAObjectArray;this.encodings=new XFAObjectArray;this.encrypt=new XFAObjectArray;this.encryptData=new XFAObjectArray;this.encryption=new XFAObjectArray;this.encryptionMethod=new XFAObjectArray;this.encryptionMethods=new XFAObjectArray;this.event=new XFAObjectArray;this.exData=new XFAObjectArray;this.exObject=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.execute=new XFAObjectArray;this.extras=new XFAObjectArray;this.field=new XFAObjectArray;this.fill=new XFAObjectArray;this.filter=new XFAObjectArray;this.float=new XFAObjectArray;this.font=new XFAObjectArray;this.format=new XFAObjectArray;this.handler=new XFAObjectArray;this.hyphenation=new XFAObjectArray;this.image=new XFAObjectArray;this.imageEdit=new XFAObjectArray;this.integer=new XFAObjectArray;this.issuers=new XFAObjectArray;this.items=new XFAObjectArray;this.keep=new XFAObjectArray;this.keyUsage=new XFAObjectArray;this.line=new XFAObjectArray;this.linear=new XFAObjectArray;this.lockDocument=new XFAObjectArray;this.manifest=new XFAObjectArray;this.margin=new XFAObjectArray;this.mdp=new XFAObjectArray;this.medium=new XFAObjectArray;this.message=new XFAObjectArray;this.numericEdit=new XFAObjectArray;this.occur=new XFAObjectArray;this.oid=new XFAObjectArray;this.oids=new XFAObjectArray;this.overflow=new XFAObjectArray;this.pageArea=new XFAObjectArray;this.pageSet=new XFAObjectArray;this.para=new XFAObjectArray;this.passwordEdit=new XFAObjectArray;this.pattern=new XFAObjectArray;this.picture=new XFAObjectArray;this.radial=new XFAObjectArray;this.reason=new XFAObjectArray;this.reasons=new XFAObjectArray;this.rectangle=new XFAObjectArray;this.ref=new XFAObjectArray;this.script=new XFAObjectArray;this.setProperty=new XFAObjectArray;this.signData=new XFAObjectArray;this.signature=new XFAObjectArray;this.signing=new XFAObjectArray;this.solid=new XFAObjectArray;this.speak=new XFAObjectArray;this.stipple=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray;this.subjectDN=new XFAObjectArray;this.subjectDNs=new XFAObjectArray;this.submit=new XFAObjectArray;this.text=new XFAObjectArray;this.textEdit=new XFAObjectArray;this.time=new XFAObjectArray;this.timeStamp=new XFAObjectArray;this.toolTip=new XFAObjectArray;this.traversal=new XFAObjectArray;this.traverse=new XFAObjectArray;this.ui=new XFAObjectArray;this.validate=new XFAObjectArray;this.value=new XFAObjectArray;this.variables=new XFAObjectArray}}class Radial extends XFAObject{constructor(e){super(Nn,"radial",!0);this.id=e.id||"";this.type=getStringOption(e.type,["toEdge","toCenter"]);this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zr](e){e=e?e[Zr]():"#FFFFFF";const t=this.color?this.color[Zr]():"#000000";return`radial-gradient(circle at center, ${"toEdge"===this.type?`${e},${t}`:`${t},${e}`})`}}class Reason extends StringObject{constructor(e){super(Nn,"reason");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Reasons extends XFAObject{constructor(e){super(Nn,"reasons",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.reason=new XFAObjectArray}}class Rectangle extends XFAObject{constructor(e){super(Nn,"rectangle",!0);this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.corner=new XFAObjectArray(4);this.edge=new XFAObjectArray(4);this.fill=null}[jr](){const e=this.edge.children.length?this.edge.children[0]:new Edge({}),t=e[Zr](),i=Object.create(null);"visible"===this.fill?.presence?Object.assign(i,this.fill[Zr]()):i.fill="transparent";i.strokeWidth=measureToString("visible"===e.presence?e.thickness:0);i.stroke=t.color;const a=(this.corner.children.length?this.corner.children[0]:new Corner({}))[Zr](),s={name:"svg",children:[{name:"rect",attributes:{xmlns:Gn,width:"100%",height:"100%",x:0,y:0,rx:a.radius,ry:a.radius,style:i}}],attributes:{xmlns:Gn,style:{overflow:"visible"},width:"100%",height:"100%"}};if(hasMargin(this[Ir]()[Ir]()))return HTMLResult.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[s]});s.attributes.style.position="absolute";return HTMLResult.success(s)}}class RefElement extends StringObject{constructor(e){super(Nn,"ref");this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Script extends StringObject{constructor(e){super(Nn,"script");this.binding=e.binding||"";this.contentType=e.contentType||"";this.id=e.id||"";this.name=e.name||"";this.runAt=getStringOption(e.runAt,["client","both","server"]);this.use=e.use||"";this.usehref=e.usehref||""}}class SetProperty extends XFAObject{constructor(e){super(Nn,"setProperty");this.connection=e.connection||"";this.ref=e.ref||"";this.target=e.target||""}}class SignData extends XFAObject{constructor(e){super(Nn,"signData",!0);this.id=e.id||"";this.operation=getStringOption(e.operation,["sign","clear","verify"]);this.ref=e.ref||"";this.target=e.target||"";this.use=e.use||"";this.usehref=e.usehref||"";this.filter=null;this.manifest=null}}class Signature extends XFAObject{constructor(e){super(Nn,"signature",!0);this.id=e.id||"";this.type=getStringOption(e.type,["PDF1.3","PDF1.6"]);this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.filter=null;this.manifest=null;this.margin=null}}class Signing extends XFAObject{constructor(e){super(Nn,"signing",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=new XFAObjectArray}}class Solid extends XFAObject{constructor(e){super(Nn,"solid",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[Zr](e){return e?e[Zr]():"#FFFFFF"}}class Speak extends StringObject{constructor(e){super(Nn,"speak");this.disable=getInteger({data:e.disable,defaultValue:0,validate:e=>1===e});this.id=e.id||"";this.priority=getStringOption(e.priority,["custom","caption","name","toolTip"]);this.rid=e.rid||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Stipple extends XFAObject{constructor(e){super(Nn,"stipple",!0);this.id=e.id||"";this.rate=getInteger({data:e.rate,defaultValue:50,validate:e=>e>=0&&e<=100});this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zr](e){const t=this.rate/100;return Util.makeHexColor(Math.round(e.value.r*(1-t)+this.value.r*t),Math.round(e.value.g*(1-t)+this.value.g*t),Math.round(e.value.b*(1-t)+this.value.b*t))}}class Subform extends XFAObject{constructor(e){super(Nn,"subform",!0);this.access=getStringOption(e.access,["open","nonInteractive","protected","readOnly"]);this.allowMacro=getInteger({data:e.allowMacro,defaultValue:0,validate:e=>1===e});this.anchorType=getStringOption(e.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.columnWidths=(e.columnWidths||"").trim().split(/\s+/).map((e=>"-1"===e?-1:getMeasurement(e)));this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.layout=getStringOption(e.layout,["position","lr-tb","rl-row","rl-tb","row","table","tb"]);this.locale=e.locale||"";this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.mergeMode=getStringOption(e.mergeMode,["consumeData","matchTemplate"]);this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.restoreState=getStringOption(e.restoreState,["manual","auto"]);this.scope=getStringOption(e.scope,["name","none"]);this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.bind=null;this.bookend=null;this.border=null;this.break=null;this.calculate=null;this.desc=null;this.extras=null;this.keep=null;this.margin=null;this.occur=null;this.overflow=null;this.pageSet=null;this.para=null;this.traversal=null;this.validate=null;this.variables=null;this.area=new XFAObjectArray;this.breakAfter=new XFAObjectArray;this.breakBefore=new XFAObjectArray;this.connect=new XFAObjectArray;this.draw=new XFAObjectArray;this.event=new XFAObjectArray;this.exObject=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.field=new XFAObjectArray;this.proto=new XFAObjectArray;this.setProperty=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray}[or](){const e=this[Ir]();return e instanceof SubformSet?e[or]():e}[dr](){return!0}[wr](){return this.layout.endsWith("-tb")&&0===this[Xs].attempt&&this[Xs].numberInLine>0||this[Ir]()[wr]()}*[nr](){yield*getContainedChildren(this)}[Vs](){return flushHTML(this)}[Ls](e,t){addHTML(this,e,t)}[$s](){return getAvailableSpace(this)}[yr](){const e=this[or]();if(!e[yr]())return!1;if(void 0!==this[Xs]._isSplittable)return this[Xs]._isSplittable;if("position"===this.layout||this.layout.includes("row")){this[Xs]._isSplittable=!1;return!1}if(this.keep&&"none"!==this.keep.intact){this[Xs]._isSplittable=!1;return!1}if(e.layout?.endsWith("-tb")&&0!==e[Xs].numberInLine)return!1;this[Xs]._isSplittable=!0;return!0}[jr](e){setTabIndex(this);if(this.break){if("auto"!==this.break.after||""!==this.break.afterTarget){const e=new BreakAfter({targetType:this.break.after,target:this.break.afterTarget,startNew:this.break.startNew.toString()});e[Cr]=this[Cr];this[Hs](e);this.breakAfter.push(e)}if("auto"!==this.break.before||""!==this.break.beforeTarget){const e=new BreakBefore({targetType:this.break.before,target:this.break.beforeTarget,startNew:this.break.startNew.toString()});e[Cr]=this[Cr];this[Hs](e);this.breakBefore.push(e)}if(""!==this.break.overflowTarget){const e=new Overflow({target:this.break.overflowTarget,leader:this.break.overflowLeader,trailer:this.break.overflowTrailer});e[Cr]=this[Cr];this[Hs](e);this.overflow.push(e)}this[Hr](this.break);this.break=null}if("hidden"===this.presence||"inactive"===this.presence)return HTMLResult.EMPTY;(this.breakBefore.children.length>1||this.breakAfter.children.length>1)&&warn("XFA - Several breakBefore or breakAfter in subforms: please file a bug.");if(this.breakBefore.children.length>=1){const e=this.breakBefore.children[0];if(handleBreak(e))return HTMLResult.breakNode(e)}if(this[Xs]?.afterBreakAfter)return HTMLResult.EMPTY;fixDimensions(this);const t=[],i={id:this[Vr],class:[]};setAccess(this,i.class);this[Xs]||(this[Xs]=Object.create(null));Object.assign(this[Xs],{children:t,line:null,attributes:i,attempt:0,numberInLine:0,availableSpace:{width:Math.min(this.w||1/0,e.width),height:Math.min(this.h||1/0,e.height)},width:0,height:0,prevHeight:0,currentWidth:0});const a=this[cr](),s=a[Xs].noLayoutFailure,r=this[yr]();r||setFirstUnsplittable(this);if(!checkDimensions(this,e))return HTMLResult.FAILURE;const n=new Set(["area","draw","exclGroup","field","subform","subformSet"]);if(this.layout.includes("row")){const e=this[or]().columnWidths;if(Array.isArray(e)&&e.length>0){this[Xs].columnWidths=e;this[Xs].currentColumn=0}}const g=toStyle(this,"anchorType","dimensions","position","presence","border","margin","hAlign"),o=["xfaSubform"],c=layoutClass(this);c&&o.push(c);i.style=g;i.class=o;this.name&&(i.xfaName=this.name);if(this.overflow){const t=this.overflow[ar]();if(t.addLeader){t.addLeader=!1;handleOverflow(this,t.leader,e)}}this[Lr]();const C="lr-tb"===this.layout||"rl-tb"===this.layout,h=C?2:1;for(;this[Xs].attempt=1){const e=this.breakAfter.children[0];if(handleBreak(e)){this[Xs].afterBreakAfter=p;return HTMLResult.breakNode(e)}}delete this[Xs];return p}}class SubformSet extends XFAObject{constructor(e){super(Nn,"subformSet",!0);this.id=e.id||"";this.name=e.name||"";this.relation=getStringOption(e.relation,["ordered","choice","unordered"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.bookend=null;this.break=null;this.desc=null;this.extras=null;this.occur=null;this.overflow=null;this.breakAfter=new XFAObjectArray;this.breakBefore=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray}*[nr](){yield*getContainedChildren(this)}[or](){let e=this[Ir]();for(;!(e instanceof Subform);)e=e[Ir]();return e}[dr](){return!0}}class SubjectDN extends ContentObject{constructor(e){super(Nn,"subjectDN");this.delimiter=e.delimiter||",";this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){this[Os]=new Map(this[Os].split(this.delimiter).map((e=>{(e=e.split("=",2))[0]=e[0].trim();return e})))}}class SubjectDNs extends XFAObject{constructor(e){super(Nn,"subjectDNs",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.subjectDN=new XFAObjectArray}}class Submit extends XFAObject{constructor(e){super(Nn,"submit",!0);this.embedPDF=getInteger({data:e.embedPDF,defaultValue:0,validate:e=>1===e});this.format=getStringOption(e.format,["xdp","formdata","pdf","urlencoded","xfd","xml"]);this.id=e.id||"";this.target=e.target||"";this.textEncoding=getKeyword({data:e.textEncoding?e.textEncoding.toLowerCase():"",defaultValue:"",validate:e=>["utf-8","big-five","fontspecific","gbk","gb-18030","gb-2312","ksc-5601","none","shift-jis","ucs-2","utf-16"].includes(e)||e.match(/iso-8859-\d{2}/)});this.use=e.use||"";this.usehref=e.usehref||"";this.xdpContent=e.xdpContent||"";this.encrypt=null;this.encryptData=new XFAObjectArray;this.signData=new XFAObjectArray}}class Template extends XFAObject{constructor(e){super(Nn,"template",!0);this.baseProfile=getStringOption(e.baseProfile,["full","interactiveForms"]);this.extras=null;this.subform=new XFAObjectArray}[Zs](){0===this.subform.children.length&&warn("XFA - No subforms in template node.");this.subform.children.length>=2&&warn("XFA - Several subforms in template node: please file a bug.");this[Or]=5e3}[yr](){return!0}[vr](e,t){return e.startsWith("#")?[this[lr].get(e.slice(1))]:searchNode(this,t,e,!0,!0)}*[Wr](){if(!this.subform.children.length)return HTMLResult.success({name:"div",children:[]});this[Xs]={overflowNode:null,firstUnsplittable:null,currentContentArea:null,currentPageArea:null,noLayoutFailure:!1,pageNumber:1,pagePosition:"first",oddOrEven:"odd",blankOrNotBlank:"nonBlank",paraStack:[]};const e=this.subform.children[0];e.pageSet[vs]();const t=e.pageSet.pageArea.children,i={name:"div",children:[]};let a=null,s=null,r=null;if(e.breakBefore.children.length>=1){s=e.breakBefore.children[0];r=s.target}else if(e.subform.children.length>=1&&e.subform.children[0].breakBefore.children.length>=1){s=e.subform.children[0].breakBefore.children[0];r=s.target}else if(e.break?.beforeTarget){s=e.break;r=s.beforeTarget}else if(e.subform.children.length>=1&&e.subform.children[0].break?.beforeTarget){s=e.subform.children[0].break;r=s.beforeTarget}if(s){const e=this[vr](r,s[Ir]());if(e instanceof PageArea){a=e;s[Xs]={}}}a||(a=t[0]);a[Xs]={numberOfUse:1};const n=a[Ir]();n[Xs]={numberOfUse:1,pageIndex:n.pageArea.children.indexOf(a),pageSetIndex:0};let g,o=null,c=null,C=!0,h=0,l=0;for(;;){if(C)h=0;else{i.children.pop();if(3==++h){warn("XFA - Something goes wrong: please file a bug.");return i}}g=null;this[Xs].currentPageArea=a;const t=a[jr]().html;i.children.push(t);if(o){this[Xs].noLayoutFailure=!0;t.children.push(o[jr](a[Xs].space).html);o=null}if(c){this[Xs].noLayoutFailure=!0;t.children.push(c[jr](a[Xs].space).html);c=null}const s=a.contentArea.children,r=t.children.filter((e=>e.attributes.class.includes("xfaContentarea")));C=!1;this[Xs].firstUnsplittable=null;this[Xs].noLayoutFailure=!1;const flush=t=>{const i=e[Vs]();if(i){C||=i.children?.length>0;r[t].children.push(i)}};for(let t=l,a=s.length;t0;r[t].children.push(h.html)}else!C&&i.children.length>1&&i.children.pop();return i}if(h.isBreak()){const e=h.breakNode;flush(t);if("auto"===e.targetType)continue;if(e.leader){o=this[vr](e.leader,e[Ir]());o=o?o[0]:null}if(e.trailer){c=this[vr](e.trailer,e[Ir]());c=c?c[0]:null}if("pageArea"===e.targetType){g=e[Xs].target;t=1/0}else if(e[Xs].target){g=e[Xs].target;l=e[Xs].index+1;t=1/0}else t=e[Xs].index}else if(this[Xs].overflowNode){const e=this[Xs].overflowNode;this[Xs].overflowNode=null;const i=e[ar](),a=i.target;i.addLeader=null!==i.leader;i.addTrailer=null!==i.trailer;flush(t);const r=t;t=1/0;if(a instanceof PageArea)g=a;else if(a instanceof ContentArea){const e=s.indexOf(a);if(-1!==e)e>r?t=e-1:l=e;else{g=a[Ir]();l=g.contentArea.children.indexOf(a)}}}else flush(t)}this[Xs].pageNumber+=1;g&&(g[br]()?g[Xs].numberOfUse+=1:g=null);a=g||a[gr]();yield null}}}class Text extends ContentObject{constructor(e){super(Nn,"text");this.id=e.id||"";this.maxChars=getInteger({data:e.maxChars,defaultValue:0,validate:e=>e>=0});this.name=e.name||"";this.rid=e.rid||"";this.use=e.use||"";this.usehref=e.usehref||""}[xs](){return!0}[Nr](e){if(e[Sr]===_r.xhtml.id){this[Os]=e;return!0}warn(`XFA - Invalid content in Text: ${e[kr]}.`);return!1}[Mr](e){this[Os]instanceof XFAObject||super[Mr](e)}[Zs](){"string"==typeof this[Os]&&(this[Os]=this[Os].replaceAll("\r\n","\n"))}[ar](){return"string"==typeof this[Os]?this[Os].split(/[\u2029\u2028\n]/).reduce(((e,t)=>{t&&e.push(t);return e}),[]).join("\n"):this[Os][Pr]()}[jr](e){if("string"==typeof this[Os]){const e=valueToHtml(this[Os]).html;if(this[Os].includes("\u2029")){e.name="div";e.children=[];this[Os].split("\u2029").map((e=>e.split(/[\u2028\n]/).reduce(((e,t)=>{e.push({name:"span",value:t},{name:"br"});return e}),[]))).forEach((t=>{e.children.push({name:"p",children:t})}))}else if(/[\u2028\n]/.test(this[Os])){e.name="div";e.children=[];this[Os].split(/[\u2028\n]/).forEach((t=>{e.children.push({name:"span",value:t},{name:"br"})}))}return HTMLResult.success(e)}return this[Os][jr](e)}}class TextEdit extends XFAObject{constructor(e){super(Nn,"textEdit",!0);this.allowRichText=getInteger({data:e.allowRichText,defaultValue:0,validate:e=>1===e});this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.multiLine=getInteger({data:e.multiLine,defaultValue:"",validate:e=>0===e||1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.vScrollPolicy=getStringOption(e.vScrollPolicy,["auto","off","on"]);this.border=null;this.comb=null;this.extras=null;this.margin=null}[jr](e){const t=toStyle(this,"border","font","margin");let i;const a=this[Ir]()[Ir]();""===this.multiLine&&(this.multiLine=a instanceof Draw?1:0);i=1===this.multiLine?{name:"textarea",attributes:{dataId:a[Ws]?.[Vr]||a[Vr],fieldId:a[Vr],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(a),"aria-required":!1}}:{name:"input",attributes:{type:"text",dataId:a[Ws]?.[Vr]||a[Vr],fieldId:a[Vr],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(a),"aria-required":!1}};if(isRequired(a)){i.attributes["aria-required"]=!0;i.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[i]})}}class Time extends StringObject{constructor(e){super(Nn,"time");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){const e=this[Os].trim();this[Os]=e?new Date(e):null}[jr](e){return valueToHtml(this[Os]?this[Os].toString():"")}}class TimeStamp extends XFAObject{constructor(e){super(Nn,"timeStamp");this.id=e.id||"";this.server=e.server||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class ToolTip extends StringObject{constructor(e){super(Nn,"toolTip");this.id=e.id||"";this.rid=e.rid||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Traversal extends XFAObject{constructor(e){super(Nn,"traversal",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.traverse=new XFAObjectArray}}class Traverse extends XFAObject{constructor(e){super(Nn,"traverse",!0);this.id=e.id||"";this.operation=getStringOption(e.operation,["next","back","down","first","left","right","up"]);this.ref=e.ref||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.script=null}get name(){return this.operation}[Dr](){return!1}}class Ui extends XFAObject{constructor(e){super(Nn,"ui",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.picture=null;this.barcode=null;this.button=null;this.checkButton=null;this.choiceList=null;this.dateTimeEdit=null;this.defaultUi=null;this.imageEdit=null;this.numericEdit=null;this.passwordEdit=null;this.signature=null;this.textEdit=null}[ar](){if(void 0===this[Xs]){for(const e of Object.getOwnPropertyNames(this)){if("extras"===e||"picture"===e)continue;const t=this[e];if(t instanceof XFAObject){this[Xs]=t;return t}}this[Xs]=null}return this[Xs]}[jr](e){const t=this[ar]();return t?t[jr](e):HTMLResult.EMPTY}}class Validate extends XFAObject{constructor(e){super(Nn,"validate",!0);this.formatTest=getStringOption(e.formatTest,["warning","disabled","error"]);this.id=e.id||"";this.nullTest=getStringOption(e.nullTest,["disabled","error","warning"]);this.scriptTest=getStringOption(e.scriptTest,["error","disabled","warning"]);this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.message=null;this.picture=null;this.script=null}}class Value extends XFAObject{constructor(e){super(Nn,"value",!0);this.id=e.id||"";this.override=getInteger({data:e.override,defaultValue:0,validate:e=>1===e});this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.arc=null;this.boolean=null;this.date=null;this.dateTime=null;this.decimal=null;this.exData=null;this.float=null;this.image=null;this.integer=null;this.line=null;this.rectangle=null;this.text=null;this.time=null}[qr](e){const t=this[Ir]();if(t instanceof Field&&t.ui?.imageEdit){if(!this.image){this.image=new Image({});this[Hs](this.image)}this.image[Os]=e[Os];return}const i=e[kr];if(null===this[i]){for(const e of Object.getOwnPropertyNames(this)){const t=this[e];if(t instanceof XFAObject){this[e]=null;this[Hr](t)}}this[e[kr]]=e;this[Hs](e)}else this[i][Os]=e[Os]}[Pr](){if(this.exData)return"string"==typeof this.exData[Os]?this.exData[Os].trim():this.exData[Os][Pr]().trim();for(const e of Object.getOwnPropertyNames(this)){if("image"===e)continue;const t=this[e];if(t instanceof XFAObject)return(t[Os]||"").toString().trim()}return null}[jr](e){for(const t of Object.getOwnPropertyNames(this)){const i=this[t];if(i instanceof XFAObject)return i[jr](e)}return HTMLResult.EMPTY}}class Variables extends XFAObject{constructor(e){super(Nn,"variables",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.manifest=new XFAObjectArray;this.script=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}[Dr](){return!0}}class TemplateNamespace{static[zr](e,t){if(TemplateNamespace.hasOwnProperty(e)){const i=TemplateNamespace[e](t);i[Tr](t);return i}}static appearanceFilter(e){return new AppearanceFilter(e)}static arc(e){return new Arc(e)}static area(e){return new Area(e)}static assist(e){return new Assist(e)}static barcode(e){return new Barcode(e)}static bind(e){return new Bind(e)}static bindItems(e){return new BindItems(e)}static bookend(e){return new Bookend(e)}static boolean(e){return new BooleanElement(e)}static border(e){return new Border(e)}static break(e){return new Break(e)}static breakAfter(e){return new BreakAfter(e)}static breakBefore(e){return new BreakBefore(e)}static button(e){return new Button(e)}static calculate(e){return new Calculate(e)}static caption(e){return new Caption(e)}static certificate(e){return new Certificate(e)}static certificates(e){return new Certificates(e)}static checkButton(e){return new CheckButton(e)}static choiceList(e){return new ChoiceList(e)}static color(e){return new Color(e)}static comb(e){return new Comb(e)}static connect(e){return new Connect(e)}static contentArea(e){return new ContentArea(e)}static corner(e){return new Corner(e)}static date(e){return new DateElement(e)}static dateTime(e){return new DateTime(e)}static dateTimeEdit(e){return new DateTimeEdit(e)}static decimal(e){return new Decimal(e)}static defaultUi(e){return new DefaultUi(e)}static desc(e){return new Desc(e)}static digestMethod(e){return new DigestMethod(e)}static digestMethods(e){return new DigestMethods(e)}static draw(e){return new Draw(e)}static edge(e){return new Edge(e)}static encoding(e){return new Encoding(e)}static encodings(e){return new Encodings(e)}static encrypt(e){return new Encrypt(e)}static encryptData(e){return new EncryptData(e)}static encryption(e){return new Encryption(e)}static encryptionMethod(e){return new EncryptionMethod(e)}static encryptionMethods(e){return new EncryptionMethods(e)}static event(e){return new Event(e)}static exData(e){return new ExData(e)}static exObject(e){return new ExObject(e)}static exclGroup(e){return new ExclGroup(e)}static execute(e){return new Execute(e)}static extras(e){return new Extras(e)}static field(e){return new Field(e)}static fill(e){return new Fill(e)}static filter(e){return new Filter(e)}static float(e){return new Float(e)}static font(e){return new template_Font(e)}static format(e){return new Format(e)}static handler(e){return new Handler(e)}static hyphenation(e){return new Hyphenation(e)}static image(e){return new Image(e)}static imageEdit(e){return new ImageEdit(e)}static integer(e){return new Integer(e)}static issuers(e){return new Issuers(e)}static items(e){return new Items(e)}static keep(e){return new Keep(e)}static keyUsage(e){return new KeyUsage(e)}static line(e){return new Line(e)}static linear(e){return new Linear(e)}static lockDocument(e){return new LockDocument(e)}static manifest(e){return new Manifest(e)}static margin(e){return new Margin(e)}static mdp(e){return new Mdp(e)}static medium(e){return new Medium(e)}static message(e){return new Message(e)}static numericEdit(e){return new NumericEdit(e)}static occur(e){return new Occur(e)}static oid(e){return new Oid(e)}static oids(e){return new Oids(e)}static overflow(e){return new Overflow(e)}static pageArea(e){return new PageArea(e)}static pageSet(e){return new PageSet(e)}static para(e){return new Para(e)}static passwordEdit(e){return new PasswordEdit(e)}static pattern(e){return new template_Pattern(e)}static picture(e){return new Picture(e)}static proto(e){return new Proto(e)}static radial(e){return new Radial(e)}static reason(e){return new Reason(e)}static reasons(e){return new Reasons(e)}static rectangle(e){return new Rectangle(e)}static ref(e){return new RefElement(e)}static script(e){return new Script(e)}static setProperty(e){return new SetProperty(e)}static signData(e){return new SignData(e)}static signature(e){return new Signature(e)}static signing(e){return new Signing(e)}static solid(e){return new Solid(e)}static speak(e){return new Speak(e)}static stipple(e){return new Stipple(e)}static subform(e){return new Subform(e)}static subformSet(e){return new SubformSet(e)}static subjectDN(e){return new SubjectDN(e)}static subjectDNs(e){return new SubjectDNs(e)}static submit(e){return new Submit(e)}static template(e){return new Template(e)}static text(e){return new Text(e)}static textEdit(e){return new TextEdit(e)}static time(e){return new Time(e)}static timeStamp(e){return new TimeStamp(e)}static toolTip(e){return new ToolTip(e)}static traversal(e){return new Traversal(e)}static traverse(e){return new Traverse(e)}static ui(e){return new Ui(e)}static validate(e){return new Validate(e)}static value(e){return new Value(e)}static variables(e){return new Variables(e)}}const Ln=_r.datasets.id;function createText(e){const t=new Text({});t[Os]=e;return t}class Binder{constructor(e){this.root=e;this.datasets=e.datasets;this.data=e.datasets?.data||new XmlObject(_r.datasets.id,"data");this.emptyMerge=0===this.data[rr]().length;this.root.form=this.form=e.template[Ts]()}_isConsumeData(){return!this.emptyMerge&&this._mergeMode}_isMatchTemplate(){return!this._isConsumeData()}bind(){this._bindElement(this.form,this.data);return this.form}getData(){return this.data}_bindValue(e,t,i){e[Ws]=t;if(e[hr]())if(t[fr]()){const i=t[ir]();e[qr](createText(i))}else if(e instanceof Field&&"multiSelect"===e.ui?.choiceList?.open){const i=t[rr]().map((e=>e[Os].trim())).join("\n");e[qr](createText(i))}else this._isConsumeData()&&warn("XFA - Nodes haven't the same type.");else!t[fr]()||this._isMatchTemplate()?this._bindElement(e,t):warn("XFA - Nodes haven't the same type.")}_findDataByNameToConsume(e,t,i,a){if(!e)return null;let s,r;for(let a=0;a<3;a++){s=i[sr](e,!1,!0);for(;;){r=s.next().value;if(!r)break;if(t===r[fr]())return r}if(i[Sr]===_r.datasets.id&&"data"===i[kr])break;i=i[Ir]()}if(!a)return null;s=this.data[sr](e,!0,!1);r=s.next().value;if(r)return r;s=this.data[zs](e,!0);r=s.next().value;return r?.[fr]()?r:null}_setProperties(e,t){if(e.hasOwnProperty("setProperty"))for(const{ref:i,target:a,connection:s}of e.setProperty.children){if(s)continue;if(!i)continue;const r=searchNode(this.root,t,i,!1,!1);if(!r){warn(`XFA - Invalid reference: ${i}.`);continue}const[n]=r;if(!n[pr](this.data)){warn("XFA - Invalid node: must be a data node.");continue}const g=searchNode(this.root,e,a,!1,!1);if(!g){warn(`XFA - Invalid target: ${a}.`);continue}const[o]=g;if(!o[pr](e)){warn("XFA - Invalid target: must be a property or subproperty.");continue}const c=o[Ir]();if(o instanceof SetProperty||c instanceof SetProperty){warn("XFA - Invalid target: cannot be a setProperty or one of its properties.");continue}if(o instanceof BindItems||c instanceof BindItems){warn("XFA - Invalid target: cannot be a bindItems or one of its properties.");continue}const C=n[Pr](),h=o[kr];if(o instanceof XFAAttribute){const e=Object.create(null);e[h]=C;const t=Reflect.construct(Object.getPrototypeOf(c).constructor,[e]);c[h]=t[h]}else if(o.hasOwnProperty(Os)){o[Ws]=n;o[Os]=C;o[Zs]()}else warn("XFA - Invalid node to use in setProperty")}}_bindItems(e,t){if(!e.hasOwnProperty("items")||!e.hasOwnProperty("bindItems")||e.bindItems.isEmpty())return;for(const t of e.items.children)e[Hr](t);e.items.clear();const i=new Items({}),a=new Items({});e[Hs](i);e.items.push(i);e[Hs](a);e.items.push(a);for(const{ref:s,labelRef:r,valueRef:n,connection:g}of e.bindItems.children){if(g)continue;if(!s)continue;const e=searchNode(this.root,t,s,!1,!1);if(e)for(const t of e){if(!t[pr](this.datasets)){warn(`XFA - Invalid ref (${s}): must be a datasets child.`);continue}const e=searchNode(this.root,t,r,!0,!1);if(!e){warn(`XFA - Invalid label: ${r}.`);continue}const[g]=e;if(!g[pr](this.datasets)){warn("XFA - Invalid label: must be a datasets child.");continue}const o=searchNode(this.root,t,n,!0,!1);if(!o){warn(`XFA - Invalid value: ${n}.`);continue}const[c]=o;if(!c[pr](this.datasets)){warn("XFA - Invalid value: must be a datasets child.");continue}const C=createText(g[Pr]()),h=createText(c[Pr]());i[Hs](C);i.text.push(C);a[Hs](h);a.text.push(h)}else warn(`XFA - Invalid reference: ${s}.`)}}_bindOccurrences(e,t,i){let a;if(t.length>1){a=e[Ts]();a[Hr](a.occur);a.occur=null}this._bindValue(e,t[0],i);this._setProperties(e,t[0]);this._bindItems(e,t[0]);if(1===t.length)return;const s=e[Ir](),r=e[kr],n=s[Qr](e);for(let e=1,g=t.length;et.name===e.name)).length:i[a].children.length;const r=i[Qr](e)+1,n=t.initial-s;if(n){const t=e[Ts]();t[Hr](t.occur);t.occur=null;i[a].push(t);i[Er](r,t);for(let e=1;e0)this._bindOccurrences(a,[e[0]],null);else if(this.emptyMerge){const e=t[Sr]===Ln?-1:t[Sr],i=a[Ws]=new XmlObject(e,a.name||"root");t[Hs](i);this._bindElement(a,i)}continue}if(!a[dr]())continue;let e=!1,s=null,r=null,n=null;if(a.bind){switch(a.bind.match){case"none":this._setAndBind(a,t);continue;case"global":e=!0;break;case"dataRef":if(!a.bind.ref){warn(`XFA - ref is empty in node ${a[kr]}.`);this._setAndBind(a,t);continue}r=a.bind.ref}a.bind.picture&&(s=a.bind.picture[Os])}const[g,o]=this._getOccurInfo(a);if(r){n=searchNode(this.root,t,r,!0,!1);if(null===n){n=createDataNode(this.data,t,r);if(!n)continue;this._isConsumeData()&&(n[qs]=!0);this._setAndBind(a,n);continue}this._isConsumeData()&&(n=n.filter((e=>!e[qs])));n.length>o?n=n.slice(0,o):0===n.length&&(n=null);n&&this._isConsumeData()&&n.forEach((e=>{e[qs]=!0}))}else{if(!a.name){this._setAndBind(a,t);continue}if(this._isConsumeData()){const i=[];for(;i.length0?i:null}else{n=t[sr](a.name,!1,this.emptyMerge).next().value;if(!n){if(0===g){i.push(a);continue}const e=t[Sr]===Ln?-1:t[Sr];n=a[Ws]=new XmlObject(e,a.name);this.emptyMerge&&(n[qs]=!0);t[Hs](n);this._setAndBind(a,n);continue}this.emptyMerge&&(n[qs]=!0);n=[n]}}n?this._bindOccurrences(a,n,s):g>0?this._setAndBind(a,t):i.push(a)}i.forEach((e=>e[Ir]()[Hr](e)))}}class DataHandler{constructor(e,t){this.data=t;this.dataset=e.datasets||null}serialize(e){const t=[[-1,this.data[rr]()]];for(;t.length>0;){const i=t.at(-1),[a,s]=i;if(a+1===s.length){t.pop();continue}const r=s[++i[0]],n=e.get(r[Vr]);if(n)r[qr](n);else{const t=r[_s]();for(const i of t.values()){const t=e.get(i[Vr]);if(t){i[qr](t);break}}}const g=r[rr]();g.length>0&&t.push([-1,g])}const i=[''];if(this.dataset)for(const e of this.dataset[rr]())"data"!==e[kr]&&e[Xr](i);this.data[Xr](i);i.push("");return i.join("")}}const Hn=_r.config.id;class Acrobat extends XFAObject{constructor(e){super(Hn,"acrobat",!0);this.acrobat7=null;this.autoSave=null;this.common=null;this.validate=null;this.validateApprovalSignatures=null;this.submitUrl=new XFAObjectArray}}class Acrobat7 extends XFAObject{constructor(e){super(Hn,"acrobat7",!0);this.dynamicRender=null}}class ADBE_JSConsole extends OptionObject{constructor(e){super(Hn,"ADBE_JSConsole",["delegate","Enable","Disable"])}}class ADBE_JSDebugger extends OptionObject{constructor(e){super(Hn,"ADBE_JSDebugger",["delegate","Enable","Disable"])}}class AddSilentPrint extends Option01{constructor(e){super(Hn,"addSilentPrint")}}class AddViewerPreferences extends Option01{constructor(e){super(Hn,"addViewerPreferences")}}class AdjustData extends Option10{constructor(e){super(Hn,"adjustData")}}class AdobeExtensionLevel extends IntegerObject{constructor(e){super(Hn,"adobeExtensionLevel",0,(e=>e>=1&&e<=8))}}class Agent extends XFAObject{constructor(e){super(Hn,"agent",!0);this.name=e.name?e.name.trim():"";this.common=new XFAObjectArray}}class AlwaysEmbed extends ContentObject{constructor(e){super(Hn,"alwaysEmbed")}}class Amd extends StringObject{constructor(e){super(Hn,"amd")}}class config_Area extends XFAObject{constructor(e){super(Hn,"area");this.level=getInteger({data:e.level,defaultValue:0,validate:e=>e>=1&&e<=3});this.name=getStringOption(e.name,["","barcode","coreinit","deviceDriver","font","general","layout","merge","script","signature","sourceSet","templateCache"])}}class Attributes extends OptionObject{constructor(e){super(Hn,"attributes",["preserve","delegate","ignore"])}}class AutoSave extends OptionObject{constructor(e){super(Hn,"autoSave",["disabled","enabled"])}}class Base extends StringObject{constructor(e){super(Hn,"base")}}class BatchOutput extends XFAObject{constructor(e){super(Hn,"batchOutput");this.format=getStringOption(e.format,["none","concat","zip","zipCompress"])}}class BehaviorOverride extends ContentObject{constructor(e){super(Hn,"behaviorOverride")}[Zs](){this[Os]=new Map(this[Os].trim().split(/\s+/).filter((e=>e.includes(":"))).map((e=>e.split(":",2))))}}class Cache extends XFAObject{constructor(e){super(Hn,"cache",!0);this.templateCache=null}}class Change extends Option01{constructor(e){super(Hn,"change")}}class Common extends XFAObject{constructor(e){super(Hn,"common",!0);this.data=null;this.locale=null;this.localeSet=null;this.messaging=null;this.suppressBanner=null;this.template=null;this.validationMessaging=null;this.versionControl=null;this.log=new XFAObjectArray}}class Compress extends XFAObject{constructor(e){super(Hn,"compress");this.scope=getStringOption(e.scope,["imageOnly","document"])}}class CompressLogicalStructure extends Option01{constructor(e){super(Hn,"compressLogicalStructure")}}class CompressObjectStream extends Option10{constructor(e){super(Hn,"compressObjectStream")}}class Compression extends XFAObject{constructor(e){super(Hn,"compression",!0);this.compressLogicalStructure=null;this.compressObjectStream=null;this.level=null;this.type=null}}class Config extends XFAObject{constructor(e){super(Hn,"config",!0);this.acrobat=null;this.present=null;this.trace=null;this.agent=new XFAObjectArray}}class Conformance extends OptionObject{constructor(e){super(Hn,"conformance",["A","B"])}}class ContentCopy extends Option01{constructor(e){super(Hn,"contentCopy")}}class Copies extends IntegerObject{constructor(e){super(Hn,"copies",1,(e=>e>=1))}}class Creator extends StringObject{constructor(e){super(Hn,"creator")}}class CurrentPage extends IntegerObject{constructor(e){super(Hn,"currentPage",0,(e=>e>=0))}}class Data extends XFAObject{constructor(e){super(Hn,"data",!0);this.adjustData=null;this.attributes=null;this.incrementalLoad=null;this.outputXSL=null;this.range=null;this.record=null;this.startNode=null;this.uri=null;this.window=null;this.xsl=null;this.excludeNS=new XFAObjectArray;this.transform=new XFAObjectArray}}class Debug extends XFAObject{constructor(e){super(Hn,"debug",!0);this.uri=null}}class DefaultTypeface extends ContentObject{constructor(e){super(Hn,"defaultTypeface");this.writingScript=getStringOption(e.writingScript,["*","Arabic","Cyrillic","EastEuropeanRoman","Greek","Hebrew","Japanese","Korean","Roman","SimplifiedChinese","Thai","TraditionalChinese","Vietnamese"])}}class Destination extends OptionObject{constructor(e){super(Hn,"destination",["pdf","pcl","ps","webClient","zpl"])}}class DocumentAssembly extends Option01{constructor(e){super(Hn,"documentAssembly")}}class Driver extends XFAObject{constructor(e){super(Hn,"driver",!0);this.name=e.name?e.name.trim():"";this.fontInfo=null;this.xdc=null}}class DuplexOption extends OptionObject{constructor(e){super(Hn,"duplexOption",["simplex","duplexFlipLongEdge","duplexFlipShortEdge"])}}class DynamicRender extends OptionObject{constructor(e){super(Hn,"dynamicRender",["forbidden","required"])}}class Embed extends Option01{constructor(e){super(Hn,"embed")}}class config_Encrypt extends Option01{constructor(e){super(Hn,"encrypt")}}class config_Encryption extends XFAObject{constructor(e){super(Hn,"encryption",!0);this.encrypt=null;this.encryptionLevel=null;this.permissions=null}}class EncryptionLevel extends OptionObject{constructor(e){super(Hn,"encryptionLevel",["40bit","128bit"])}}class Enforce extends StringObject{constructor(e){super(Hn,"enforce")}}class Equate extends XFAObject{constructor(e){super(Hn,"equate");this.force=getInteger({data:e.force,defaultValue:1,validate:e=>0===e});this.from=e.from||"";this.to=e.to||""}}class EquateRange extends XFAObject{constructor(e){super(Hn,"equateRange");this.from=e.from||"";this.to=e.to||"";this._unicodeRange=e.unicodeRange||""}get unicodeRange(){const e=[],t=/U\+([0-9a-fA-F]+)/,i=this._unicodeRange;for(let a of i.split(",").map((e=>e.trim())).filter((e=>!!e))){a=a.split("-",2).map((e=>{const i=e.match(t);return i?parseInt(i[1],16):0}));1===a.length&&a.push(a[0]);e.push(a)}return shadow(this,"unicodeRange",e)}}class Exclude extends ContentObject{constructor(e){super(Hn,"exclude")}[Zs](){this[Os]=this[Os].trim().split(/\s+/).filter((e=>e&&["calculate","close","enter","exit","initialize","ready","validate"].includes(e)))}}class ExcludeNS extends StringObject{constructor(e){super(Hn,"excludeNS")}}class FlipLabel extends OptionObject{constructor(e){super(Hn,"flipLabel",["usePrinterSetting","on","off"])}}class config_FontInfo extends XFAObject{constructor(e){super(Hn,"fontInfo",!0);this.embed=null;this.map=null;this.subsetBelow=null;this.alwaysEmbed=new XFAObjectArray;this.defaultTypeface=new XFAObjectArray;this.neverEmbed=new XFAObjectArray}}class FormFieldFilling extends Option01{constructor(e){super(Hn,"formFieldFilling")}}class GroupParent extends StringObject{constructor(e){super(Hn,"groupParent")}}class IfEmpty extends OptionObject{constructor(e){super(Hn,"ifEmpty",["dataValue","dataGroup","ignore","remove"])}}class IncludeXDPContent extends StringObject{constructor(e){super(Hn,"includeXDPContent")}}class IncrementalLoad extends OptionObject{constructor(e){super(Hn,"incrementalLoad",["none","forwardOnly"])}}class IncrementalMerge extends Option01{constructor(e){super(Hn,"incrementalMerge")}}class Interactive extends Option01{constructor(e){super(Hn,"interactive")}}class Jog extends OptionObject{constructor(e){super(Hn,"jog",["usePrinterSetting","none","pageSet"])}}class LabelPrinter extends XFAObject{constructor(e){super(Hn,"labelPrinter",!0);this.name=getStringOption(e.name,["zpl","dpl","ipl","tcpl"]);this.batchOutput=null;this.flipLabel=null;this.fontInfo=null;this.xdc=null}}class Layout extends OptionObject{constructor(e){super(Hn,"layout",["paginate","panel"])}}class Level extends IntegerObject{constructor(e){super(Hn,"level",0,(e=>e>0))}}class Linearized extends Option01{constructor(e){super(Hn,"linearized")}}class Locale extends StringObject{constructor(e){super(Hn,"locale")}}class LocaleSet extends StringObject{constructor(e){super(Hn,"localeSet")}}class Log extends XFAObject{constructor(e){super(Hn,"log",!0);this.mode=null;this.threshold=null;this.to=null;this.uri=null}}class MapElement extends XFAObject{constructor(e){super(Hn,"map",!0);this.equate=new XFAObjectArray;this.equateRange=new XFAObjectArray}}class MediumInfo extends XFAObject{constructor(e){super(Hn,"mediumInfo",!0);this.map=null}}class config_Message extends XFAObject{constructor(e){super(Hn,"message",!0);this.msgId=null;this.severity=null}}class Messaging extends XFAObject{constructor(e){super(Hn,"messaging",!0);this.message=new XFAObjectArray}}class Mode extends OptionObject{constructor(e){super(Hn,"mode",["append","overwrite"])}}class ModifyAnnots extends Option01{constructor(e){super(Hn,"modifyAnnots")}}class MsgId extends IntegerObject{constructor(e){super(Hn,"msgId",1,(e=>e>=1))}}class NameAttr extends StringObject{constructor(e){super(Hn,"nameAttr")}}class NeverEmbed extends ContentObject{constructor(e){super(Hn,"neverEmbed")}}class NumberOfCopies extends IntegerObject{constructor(e){super(Hn,"numberOfCopies",null,(e=>e>=2&&e<=5))}}class OpenAction extends XFAObject{constructor(e){super(Hn,"openAction",!0);this.destination=null}}class Output extends XFAObject{constructor(e){super(Hn,"output",!0);this.to=null;this.type=null;this.uri=null}}class OutputBin extends StringObject{constructor(e){super(Hn,"outputBin")}}class OutputXSL extends XFAObject{constructor(e){super(Hn,"outputXSL",!0);this.uri=null}}class Overprint extends OptionObject{constructor(e){super(Hn,"overprint",["none","both","draw","field"])}}class Packets extends StringObject{constructor(e){super(Hn,"packets")}[Zs](){"*"!==this[Os]&&(this[Os]=this[Os].trim().split(/\s+/).filter((e=>["config","datasets","template","xfdf","xslt"].includes(e))))}}class PageOffset extends XFAObject{constructor(e){super(Hn,"pageOffset");this.x=getInteger({data:e.x,defaultValue:"useXDCSetting",validate:e=>!0});this.y=getInteger({data:e.y,defaultValue:"useXDCSetting",validate:e=>!0})}}class PageRange extends StringObject{constructor(e){super(Hn,"pageRange")}[Zs](){const e=this[Os].trim().split(/\s+/).map((e=>parseInt(e,10))),t=[];for(let i=0,a=e.length;i!1))}}class Pcl extends XFAObject{constructor(e){super(Hn,"pcl",!0);this.name=e.name||"";this.batchOutput=null;this.fontInfo=null;this.jog=null;this.mediumInfo=null;this.outputBin=null;this.pageOffset=null;this.staple=null;this.xdc=null}}class Pdf extends XFAObject{constructor(e){super(Hn,"pdf",!0);this.name=e.name||"";this.adobeExtensionLevel=null;this.batchOutput=null;this.compression=null;this.creator=null;this.encryption=null;this.fontInfo=null;this.interactive=null;this.linearized=null;this.openAction=null;this.pdfa=null;this.producer=null;this.renderPolicy=null;this.scriptModel=null;this.silentPrint=null;this.submitFormat=null;this.tagged=null;this.version=null;this.viewerPreferences=null;this.xdc=null}}class Pdfa extends XFAObject{constructor(e){super(Hn,"pdfa",!0);this.amd=null;this.conformance=null;this.includeXDPContent=null;this.part=null}}class Permissions extends XFAObject{constructor(e){super(Hn,"permissions",!0);this.accessibleContent=null;this.change=null;this.contentCopy=null;this.documentAssembly=null;this.formFieldFilling=null;this.modifyAnnots=null;this.plaintextMetadata=null;this.print=null;this.printHighQuality=null}}class PickTrayByPDFSize extends Option01{constructor(e){super(Hn,"pickTrayByPDFSize")}}class config_Picture extends StringObject{constructor(e){super(Hn,"picture")}}class PlaintextMetadata extends Option01{constructor(e){super(Hn,"plaintextMetadata")}}class Presence extends OptionObject{constructor(e){super(Hn,"presence",["preserve","dissolve","dissolveStructure","ignore","remove"])}}class Present extends XFAObject{constructor(e){super(Hn,"present",!0);this.behaviorOverride=null;this.cache=null;this.common=null;this.copies=null;this.destination=null;this.incrementalMerge=null;this.layout=null;this.output=null;this.overprint=null;this.pagination=null;this.paginationOverride=null;this.script=null;this.validate=null;this.xdp=null;this.driver=new XFAObjectArray;this.labelPrinter=new XFAObjectArray;this.pcl=new XFAObjectArray;this.pdf=new XFAObjectArray;this.ps=new XFAObjectArray;this.submitUrl=new XFAObjectArray;this.webClient=new XFAObjectArray;this.zpl=new XFAObjectArray}}class Print extends Option01{constructor(e){super(Hn,"print")}}class PrintHighQuality extends Option01{constructor(e){super(Hn,"printHighQuality")}}class PrintScaling extends OptionObject{constructor(e){super(Hn,"printScaling",["appdefault","noScaling"])}}class PrinterName extends StringObject{constructor(e){super(Hn,"printerName")}}class Producer extends StringObject{constructor(e){super(Hn,"producer")}}class Ps extends XFAObject{constructor(e){super(Hn,"ps",!0);this.name=e.name||"";this.batchOutput=null;this.fontInfo=null;this.jog=null;this.mediumInfo=null;this.outputBin=null;this.staple=null;this.xdc=null}}class Range extends ContentObject{constructor(e){super(Hn,"range")}[Zs](){this[Os]=this[Os].trim().split(/\s*,\s*/,2).map((e=>e.split("-").map((e=>parseInt(e.trim(),10))))).filter((e=>e.every((e=>!isNaN(e))))).map((e=>{1===e.length&&e.push(e[0]);return e}))}}class Record extends ContentObject{constructor(e){super(Hn,"record")}[Zs](){this[Os]=this[Os].trim();const e=parseInt(this[Os],10);!isNaN(e)&&e>=0&&(this[Os]=e)}}class Relevant extends ContentObject{constructor(e){super(Hn,"relevant")}[Zs](){this[Os]=this[Os].trim().split(/\s+/)}}class Rename extends ContentObject{constructor(e){super(Hn,"rename")}[Zs](){this[Os]=this[Os].trim();(this[Os].toLowerCase().startsWith("xml")||new RegExp("[\\p{L}_][\\p{L}\\d._\\p{M}-]*","u").test(this[Os]))&&warn("XFA - Rename: invalid XFA name")}}class RenderPolicy extends OptionObject{constructor(e){super(Hn,"renderPolicy",["server","client"])}}class RunScripts extends OptionObject{constructor(e){super(Hn,"runScripts",["both","client","none","server"])}}class config_Script extends XFAObject{constructor(e){super(Hn,"script",!0);this.currentPage=null;this.exclude=null;this.runScripts=null}}class ScriptModel extends OptionObject{constructor(e){super(Hn,"scriptModel",["XFA","none"])}}class Severity extends OptionObject{constructor(e){super(Hn,"severity",["ignore","error","information","trace","warning"])}}class SilentPrint extends XFAObject{constructor(e){super(Hn,"silentPrint",!0);this.addSilentPrint=null;this.printerName=null}}class Staple extends XFAObject{constructor(e){super(Hn,"staple");this.mode=getStringOption(e.mode,["usePrinterSetting","on","off"])}}class StartNode extends StringObject{constructor(e){super(Hn,"startNode")}}class StartPage extends IntegerObject{constructor(e){super(Hn,"startPage",0,(e=>!0))}}class SubmitFormat extends OptionObject{constructor(e){super(Hn,"submitFormat",["html","delegate","fdf","xml","pdf"])}}class SubmitUrl extends StringObject{constructor(e){super(Hn,"submitUrl")}}class SubsetBelow extends IntegerObject{constructor(e){super(Hn,"subsetBelow",100,(e=>e>=0&&e<=100))}}class SuppressBanner extends Option01{constructor(e){super(Hn,"suppressBanner")}}class Tagged extends Option01{constructor(e){super(Hn,"tagged")}}class config_Template extends XFAObject{constructor(e){super(Hn,"template",!0);this.base=null;this.relevant=null;this.startPage=null;this.uri=null;this.xsl=null}}class Threshold extends OptionObject{constructor(e){super(Hn,"threshold",["trace","error","information","warning"])}}class To extends OptionObject{constructor(e){super(Hn,"to",["null","memory","stderr","stdout","system","uri"])}}class TemplateCache extends XFAObject{constructor(e){super(Hn,"templateCache");this.maxEntries=getInteger({data:e.maxEntries,defaultValue:5,validate:e=>e>=0})}}class Trace extends XFAObject{constructor(e){super(Hn,"trace",!0);this.area=new XFAObjectArray}}class Transform extends XFAObject{constructor(e){super(Hn,"transform",!0);this.groupParent=null;this.ifEmpty=null;this.nameAttr=null;this.picture=null;this.presence=null;this.rename=null;this.whitespace=null}}class Type extends OptionObject{constructor(e){super(Hn,"type",["none","ascii85","asciiHex","ccittfax","flate","lzw","runLength","native","xdp","mergedXDP"])}}class Uri extends StringObject{constructor(e){super(Hn,"uri")}}class config_Validate extends OptionObject{constructor(e){super(Hn,"validate",["preSubmit","prePrint","preExecute","preSave"])}}class ValidateApprovalSignatures extends ContentObject{constructor(e){super(Hn,"validateApprovalSignatures")}[Zs](){this[Os]=this[Os].trim().split(/\s+/).filter((e=>["docReady","postSign"].includes(e)))}}class ValidationMessaging extends OptionObject{constructor(e){super(Hn,"validationMessaging",["allMessagesIndividually","allMessagesTogether","firstMessageOnly","noMessages"])}}class Version extends OptionObject{constructor(e){super(Hn,"version",["1.7","1.6","1.5","1.4","1.3","1.2"])}}class VersionControl extends XFAObject{constructor(e){super(Hn,"VersionControl");this.outputBelow=getStringOption(e.outputBelow,["warn","error","update"]);this.sourceAbove=getStringOption(e.sourceAbove,["warn","error"]);this.sourceBelow=getStringOption(e.sourceBelow,["update","maintain"])}}class ViewerPreferences extends XFAObject{constructor(e){super(Hn,"viewerPreferences",!0);this.ADBE_JSConsole=null;this.ADBE_JSDebugger=null;this.addViewerPreferences=null;this.duplexOption=null;this.enforce=null;this.numberOfCopies=null;this.pageRange=null;this.pickTrayByPDFSize=null;this.printScaling=null}}class WebClient extends XFAObject{constructor(e){super(Hn,"webClient",!0);this.name=e.name?e.name.trim():"";this.fontInfo=null;this.xdc=null}}class Whitespace extends OptionObject{constructor(e){super(Hn,"whitespace",["preserve","ltrim","normalize","rtrim","trim"])}}class Window extends ContentObject{constructor(e){super(Hn,"window")}[Zs](){const e=this[Os].trim().split(/\s*,\s*/,2).map((e=>parseInt(e,10)));if(e.some((e=>isNaN(e))))this[Os]=[0,0];else{1===e.length&&e.push(e[0]);this[Os]=e}}}class Xdc extends XFAObject{constructor(e){super(Hn,"xdc",!0);this.uri=new XFAObjectArray;this.xsl=new XFAObjectArray}}class Xdp extends XFAObject{constructor(e){super(Hn,"xdp",!0);this.packets=null}}class Xsl extends XFAObject{constructor(e){super(Hn,"xsl",!0);this.debug=null;this.uri=null}}class Zpl extends XFAObject{constructor(e){super(Hn,"zpl",!0);this.name=e.name?e.name.trim():"";this.batchOutput=null;this.flipLabel=null;this.fontInfo=null;this.xdc=null}}class ConfigNamespace{static[zr](e,t){if(ConfigNamespace.hasOwnProperty(e))return ConfigNamespace[e](t)}static acrobat(e){return new Acrobat(e)}static acrobat7(e){return new Acrobat7(e)}static ADBE_JSConsole(e){return new ADBE_JSConsole(e)}static ADBE_JSDebugger(e){return new ADBE_JSDebugger(e)}static addSilentPrint(e){return new AddSilentPrint(e)}static addViewerPreferences(e){return new AddViewerPreferences(e)}static adjustData(e){return new AdjustData(e)}static adobeExtensionLevel(e){return new AdobeExtensionLevel(e)}static agent(e){return new Agent(e)}static alwaysEmbed(e){return new AlwaysEmbed(e)}static amd(e){return new Amd(e)}static area(e){return new config_Area(e)}static attributes(e){return new Attributes(e)}static autoSave(e){return new AutoSave(e)}static base(e){return new Base(e)}static batchOutput(e){return new BatchOutput(e)}static behaviorOverride(e){return new BehaviorOverride(e)}static cache(e){return new Cache(e)}static change(e){return new Change(e)}static common(e){return new Common(e)}static compress(e){return new Compress(e)}static compressLogicalStructure(e){return new CompressLogicalStructure(e)}static compressObjectStream(e){return new CompressObjectStream(e)}static compression(e){return new Compression(e)}static config(e){return new Config(e)}static conformance(e){return new Conformance(e)}static contentCopy(e){return new ContentCopy(e)}static copies(e){return new Copies(e)}static creator(e){return new Creator(e)}static currentPage(e){return new CurrentPage(e)}static data(e){return new Data(e)}static debug(e){return new Debug(e)}static defaultTypeface(e){return new DefaultTypeface(e)}static destination(e){return new Destination(e)}static documentAssembly(e){return new DocumentAssembly(e)}static driver(e){return new Driver(e)}static duplexOption(e){return new DuplexOption(e)}static dynamicRender(e){return new DynamicRender(e)}static embed(e){return new Embed(e)}static encrypt(e){return new config_Encrypt(e)}static encryption(e){return new config_Encryption(e)}static encryptionLevel(e){return new EncryptionLevel(e)}static enforce(e){return new Enforce(e)}static equate(e){return new Equate(e)}static equateRange(e){return new EquateRange(e)}static exclude(e){return new Exclude(e)}static excludeNS(e){return new ExcludeNS(e)}static flipLabel(e){return new FlipLabel(e)}static fontInfo(e){return new config_FontInfo(e)}static formFieldFilling(e){return new FormFieldFilling(e)}static groupParent(e){return new GroupParent(e)}static ifEmpty(e){return new IfEmpty(e)}static includeXDPContent(e){return new IncludeXDPContent(e)}static incrementalLoad(e){return new IncrementalLoad(e)}static incrementalMerge(e){return new IncrementalMerge(e)}static interactive(e){return new Interactive(e)}static jog(e){return new Jog(e)}static labelPrinter(e){return new LabelPrinter(e)}static layout(e){return new Layout(e)}static level(e){return new Level(e)}static linearized(e){return new Linearized(e)}static locale(e){return new Locale(e)}static localeSet(e){return new LocaleSet(e)}static log(e){return new Log(e)}static map(e){return new MapElement(e)}static mediumInfo(e){return new MediumInfo(e)}static message(e){return new config_Message(e)}static messaging(e){return new Messaging(e)}static mode(e){return new Mode(e)}static modifyAnnots(e){return new ModifyAnnots(e)}static msgId(e){return new MsgId(e)}static nameAttr(e){return new NameAttr(e)}static neverEmbed(e){return new NeverEmbed(e)}static numberOfCopies(e){return new NumberOfCopies(e)}static openAction(e){return new OpenAction(e)}static output(e){return new Output(e)}static outputBin(e){return new OutputBin(e)}static outputXSL(e){return new OutputXSL(e)}static overprint(e){return new Overprint(e)}static packets(e){return new Packets(e)}static pageOffset(e){return new PageOffset(e)}static pageRange(e){return new PageRange(e)}static pagination(e){return new Pagination(e)}static paginationOverride(e){return new PaginationOverride(e)}static part(e){return new Part(e)}static pcl(e){return new Pcl(e)}static pdf(e){return new Pdf(e)}static pdfa(e){return new Pdfa(e)}static permissions(e){return new Permissions(e)}static pickTrayByPDFSize(e){return new PickTrayByPDFSize(e)}static picture(e){return new config_Picture(e)}static plaintextMetadata(e){return new PlaintextMetadata(e)}static presence(e){return new Presence(e)}static present(e){return new Present(e)}static print(e){return new Print(e)}static printHighQuality(e){return new PrintHighQuality(e)}static printScaling(e){return new PrintScaling(e)}static printerName(e){return new PrinterName(e)}static producer(e){return new Producer(e)}static ps(e){return new Ps(e)}static range(e){return new Range(e)}static record(e){return new Record(e)}static relevant(e){return new Relevant(e)}static rename(e){return new Rename(e)}static renderPolicy(e){return new RenderPolicy(e)}static runScripts(e){return new RunScripts(e)}static script(e){return new config_Script(e)}static scriptModel(e){return new ScriptModel(e)}static severity(e){return new Severity(e)}static silentPrint(e){return new SilentPrint(e)}static staple(e){return new Staple(e)}static startNode(e){return new StartNode(e)}static startPage(e){return new StartPage(e)}static submitFormat(e){return new SubmitFormat(e)}static submitUrl(e){return new SubmitUrl(e)}static subsetBelow(e){return new SubsetBelow(e)}static suppressBanner(e){return new SuppressBanner(e)}static tagged(e){return new Tagged(e)}static template(e){return new config_Template(e)}static templateCache(e){return new TemplateCache(e)}static threshold(e){return new Threshold(e)}static to(e){return new To(e)}static trace(e){return new Trace(e)}static transform(e){return new Transform(e)}static type(e){return new Type(e)}static uri(e){return new Uri(e)}static validate(e){return new config_Validate(e)}static validateApprovalSignatures(e){return new ValidateApprovalSignatures(e)}static validationMessaging(e){return new ValidationMessaging(e)}static version(e){return new Version(e)}static versionControl(e){return new VersionControl(e)}static viewerPreferences(e){return new ViewerPreferences(e)}static webClient(e){return new WebClient(e)}static whitespace(e){return new Whitespace(e)}static window(e){return new Window(e)}static xdc(e){return new Xdc(e)}static xdp(e){return new Xdp(e)}static xsl(e){return new Xsl(e)}static zpl(e){return new Zpl(e)}}const Jn=_r.connectionSet.id;class ConnectionSet extends XFAObject{constructor(e){super(Jn,"connectionSet",!0);this.wsdlConnection=new XFAObjectArray;this.xmlConnection=new XFAObjectArray;this.xsdConnection=new XFAObjectArray}}class EffectiveInputPolicy extends XFAObject{constructor(e){super(Jn,"effectiveInputPolicy");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class EffectiveOutputPolicy extends XFAObject{constructor(e){super(Jn,"effectiveOutputPolicy");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Operation extends StringObject{constructor(e){super(Jn,"operation");this.id=e.id||"";this.input=e.input||"";this.name=e.name||"";this.output=e.output||"";this.use=e.use||"";this.usehref=e.usehref||""}}class RootElement extends StringObject{constructor(e){super(Jn,"rootElement");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class SoapAction extends StringObject{constructor(e){super(Jn,"soapAction");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class SoapAddress extends StringObject{constructor(e){super(Jn,"soapAddress");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class connection_set_Uri extends StringObject{constructor(e){super(Jn,"uri");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class WsdlAddress extends StringObject{constructor(e){super(Jn,"wsdlAddress");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class WsdlConnection extends XFAObject{constructor(e){super(Jn,"wsdlConnection",!0);this.dataDescription=e.dataDescription||"";this.name=e.name||"";this.effectiveInputPolicy=null;this.effectiveOutputPolicy=null;this.operation=null;this.soapAction=null;this.soapAddress=null;this.wsdlAddress=null}}class XmlConnection extends XFAObject{constructor(e){super(Jn,"xmlConnection",!0);this.dataDescription=e.dataDescription||"";this.name=e.name||"";this.uri=null}}class XsdConnection extends XFAObject{constructor(e){super(Jn,"xsdConnection",!0);this.dataDescription=e.dataDescription||"";this.name=e.name||"";this.rootElement=null;this.uri=null}}class ConnectionSetNamespace{static[zr](e,t){if(ConnectionSetNamespace.hasOwnProperty(e))return ConnectionSetNamespace[e](t)}static connectionSet(e){return new ConnectionSet(e)}static effectiveInputPolicy(e){return new EffectiveInputPolicy(e)}static effectiveOutputPolicy(e){return new EffectiveOutputPolicy(e)}static operation(e){return new Operation(e)}static rootElement(e){return new RootElement(e)}static soapAction(e){return new SoapAction(e)}static soapAddress(e){return new SoapAddress(e)}static uri(e){return new connection_set_Uri(e)}static wsdlAddress(e){return new WsdlAddress(e)}static wsdlConnection(e){return new WsdlConnection(e)}static xmlConnection(e){return new XmlConnection(e)}static xsdConnection(e){return new XsdConnection(e)}}const Yn=_r.datasets.id;class datasets_Data extends XmlObject{constructor(e){super(Yn,"data",e)}[mr](){return!0}}class Datasets extends XFAObject{constructor(e){super(Yn,"datasets",!0);this.data=null;this.Signature=null}[Nr](e){const t=e[kr];("data"===t&&e[Sr]===Yn||"Signature"===t&&e[Sr]===_r.signature.id)&&(this[t]=e);this[Hs](e)}}class DatasetsNamespace{static[zr](e,t){if(DatasetsNamespace.hasOwnProperty(e))return DatasetsNamespace[e](t)}static datasets(e){return new Datasets(e)}static data(e){return new datasets_Data(e)}}const vn=_r.localeSet.id;class CalendarSymbols extends XFAObject{constructor(e){super(vn,"calendarSymbols",!0);this.name="gregorian";this.dayNames=new XFAObjectArray(2);this.eraNames=null;this.meridiemNames=null;this.monthNames=new XFAObjectArray(2)}}class CurrencySymbol extends StringObject{constructor(e){super(vn,"currencySymbol");this.name=getStringOption(e.name,["symbol","isoname","decimal"])}}class CurrencySymbols extends XFAObject{constructor(e){super(vn,"currencySymbols",!0);this.currencySymbol=new XFAObjectArray(3)}}class DatePattern extends StringObject{constructor(e){super(vn,"datePattern");this.name=getStringOption(e.name,["full","long","med","short"])}}class DatePatterns extends XFAObject{constructor(e){super(vn,"datePatterns",!0);this.datePattern=new XFAObjectArray(4)}}class DateTimeSymbols extends ContentObject{constructor(e){super(vn,"dateTimeSymbols")}}class Day extends StringObject{constructor(e){super(vn,"day")}}class DayNames extends XFAObject{constructor(e){super(vn,"dayNames",!0);this.abbr=getInteger({data:e.abbr,defaultValue:0,validate:e=>1===e});this.day=new XFAObjectArray(7)}}class Era extends StringObject{constructor(e){super(vn,"era")}}class EraNames extends XFAObject{constructor(e){super(vn,"eraNames",!0);this.era=new XFAObjectArray(2)}}class locale_set_Locale extends XFAObject{constructor(e){super(vn,"locale",!0);this.desc=e.desc||"";this.name="isoname";this.calendarSymbols=null;this.currencySymbols=null;this.datePatterns=null;this.dateTimeSymbols=null;this.numberPatterns=null;this.numberSymbols=null;this.timePatterns=null;this.typeFaces=null}}class locale_set_LocaleSet extends XFAObject{constructor(e){super(vn,"localeSet",!0);this.locale=new XFAObjectArray}}class Meridiem extends StringObject{constructor(e){super(vn,"meridiem")}}class MeridiemNames extends XFAObject{constructor(e){super(vn,"meridiemNames",!0);this.meridiem=new XFAObjectArray(2)}}class Month extends StringObject{constructor(e){super(vn,"month")}}class MonthNames extends XFAObject{constructor(e){super(vn,"monthNames",!0);this.abbr=getInteger({data:e.abbr,defaultValue:0,validate:e=>1===e});this.month=new XFAObjectArray(12)}}class NumberPattern extends StringObject{constructor(e){super(vn,"numberPattern");this.name=getStringOption(e.name,["full","long","med","short"])}}class NumberPatterns extends XFAObject{constructor(e){super(vn,"numberPatterns",!0);this.numberPattern=new XFAObjectArray(4)}}class NumberSymbol extends StringObject{constructor(e){super(vn,"numberSymbol");this.name=getStringOption(e.name,["decimal","grouping","percent","minus","zero"])}}class NumberSymbols extends XFAObject{constructor(e){super(vn,"numberSymbols",!0);this.numberSymbol=new XFAObjectArray(5)}}class TimePattern extends StringObject{constructor(e){super(vn,"timePattern");this.name=getStringOption(e.name,["full","long","med","short"])}}class TimePatterns extends XFAObject{constructor(e){super(vn,"timePatterns",!0);this.timePattern=new XFAObjectArray(4)}}class TypeFace extends XFAObject{constructor(e){super(vn,"typeFace",!0);this.name=""|e.name}}class TypeFaces extends XFAObject{constructor(e){super(vn,"typeFaces",!0);this.typeFace=new XFAObjectArray}}class LocaleSetNamespace{static[zr](e,t){if(LocaleSetNamespace.hasOwnProperty(e))return LocaleSetNamespace[e](t)}static calendarSymbols(e){return new CalendarSymbols(e)}static currencySymbol(e){return new CurrencySymbol(e)}static currencySymbols(e){return new CurrencySymbols(e)}static datePattern(e){return new DatePattern(e)}static datePatterns(e){return new DatePatterns(e)}static dateTimeSymbols(e){return new DateTimeSymbols(e)}static day(e){return new Day(e)}static dayNames(e){return new DayNames(e)}static era(e){return new Era(e)}static eraNames(e){return new EraNames(e)}static locale(e){return new locale_set_Locale(e)}static localeSet(e){return new locale_set_LocaleSet(e)}static meridiem(e){return new Meridiem(e)}static meridiemNames(e){return new MeridiemNames(e)}static month(e){return new Month(e)}static monthNames(e){return new MonthNames(e)}static numberPattern(e){return new NumberPattern(e)}static numberPatterns(e){return new NumberPatterns(e)}static numberSymbol(e){return new NumberSymbol(e)}static numberSymbols(e){return new NumberSymbols(e)}static timePattern(e){return new TimePattern(e)}static timePatterns(e){return new TimePatterns(e)}static typeFace(e){return new TypeFace(e)}static typeFaces(e){return new TypeFaces(e)}}const Kn=_r.signature.id;class signature_Signature extends XFAObject{constructor(e){super(Kn,"signature",!0)}}class SignatureNamespace{static[zr](e,t){if(SignatureNamespace.hasOwnProperty(e))return SignatureNamespace[e](t)}static signature(e){return new signature_Signature(e)}}const Tn=_r.stylesheet.id;class Stylesheet extends XFAObject{constructor(e){super(Tn,"stylesheet",!0)}}class StylesheetNamespace{static[zr](e,t){if(StylesheetNamespace.hasOwnProperty(e))return StylesheetNamespace[e](t)}static stylesheet(e){return new Stylesheet(e)}}const qn=_r.xdp.id;class xdp_Xdp extends XFAObject{constructor(e){super(qn,"xdp",!0);this.uuid=e.uuid||"";this.timeStamp=e.timeStamp||"";this.config=null;this.connectionSet=null;this.datasets=null;this.localeSet=null;this.stylesheet=new XFAObjectArray;this.template=null}[Gr](e){const t=_r[e[kr]];return t&&e[Sr]===t.id}}class XdpNamespace{static[zr](e,t){if(XdpNamespace.hasOwnProperty(e))return XdpNamespace[e](t)}static xdp(e){return new xdp_Xdp(e)}}const On=_r.xhtml.id,Pn=Symbol(),Wn=new Set(["color","font","font-family","font-size","font-stretch","font-style","font-weight","margin","margin-bottom","margin-left","margin-right","margin-top","letter-spacing","line-height","orphans","page-break-after","page-break-before","page-break-inside","tab-interval","tab-stop","text-align","text-decoration","text-indent","vertical-align","widows","kerning-mode","xfa-font-horizontal-scale","xfa-font-vertical-scale","xfa-spacerun","xfa-tab-stops"]),jn=new Map([["page-break-after","breakAfter"],["page-break-before","breakBefore"],["page-break-inside","breakInside"],["kerning-mode",e=>"none"===e?"none":"normal"],["xfa-font-horizontal-scale",e=>`scaleX(${Math.max(0,Math.min(parseInt(e)/100)).toFixed(2)})`],["xfa-font-vertical-scale",e=>`scaleY(${Math.max(0,Math.min(parseInt(e)/100)).toFixed(2)})`],["xfa-spacerun",""],["xfa-tab-stops",""],["font-size",(e,t)=>measureToString(.99*(e=t.fontSize=Math.abs(getMeasurement(e))))],["letter-spacing",e=>measureToString(getMeasurement(e))],["line-height",e=>measureToString(getMeasurement(e))],["margin",e=>measureToString(getMeasurement(e))],["margin-bottom",e=>measureToString(getMeasurement(e))],["margin-left",e=>measureToString(getMeasurement(e))],["margin-right",e=>measureToString(getMeasurement(e))],["margin-top",e=>measureToString(getMeasurement(e))],["text-indent",e=>measureToString(getMeasurement(e))],["font-family",e=>e],["vertical-align",e=>measureToString(getMeasurement(e))]]),Xn=/\s+/g,Zn=/[\r\n]+/g,Vn=/\r\n?/g;function mapStyle(e,t,i){const a=Object.create(null);if(!e)return a;const s=Object.create(null);for(const[t,i]of e.split(";").map((e=>e.split(":",2)))){const e=jn.get(t);if(""===e)continue;let r=i;e&&(r="string"==typeof e?e:e(i,s));t.endsWith("scale")?a.transform=a.transform?`${a[t]} ${r}`:r:a[t.replaceAll(/-([a-zA-Z])/g,((e,t)=>t.toUpperCase()))]=r}a.fontFamily&&setFontFamily({typeface:a.fontFamily,weight:a.fontWeight||"normal",posture:a.fontStyle||"normal",size:s.fontSize||0},t,t[Cr].fontFinder,a);if(i&&a.verticalAlign&&"0px"!==a.verticalAlign&&a.fontSize){const e=.583,t=.333,i=getMeasurement(a.fontSize);a.fontSize=measureToString(i*e);a.verticalAlign=measureToString(Math.sign(getMeasurement(a.verticalAlign))*i*t)}i&&a.fontSize&&(a.fontSize=`calc(${a.fontSize} * var(--scale-factor))`);fixTextIndent(a);return a}const zn=new Set(["body","html"]);class XhtmlObject extends XmlObject{constructor(e,t){super(On,t);this[Pn]=!1;this.style=e.style||""}[Ys](e){super[Ys](e);this.style=function checkStyle(e){return e.style?e.style.trim().split(/\s*;\s*/).filter((e=>!!e)).map((e=>e.split(/\s*:\s*/,2))).filter((([t,i])=>{"font-family"===t&&e[Cr].usedTypefaces.add(i);return Wn.has(t)})).map((e=>e.join(":"))).join(";"):""}(this)}[xs](){return!zn.has(this[kr])}[Mr](e,t=!1){if(t)this[Pn]=!0;else{e=e.replaceAll(Zn,"");this.style.includes("xfa-spacerun:yes")||(e=e.replaceAll(Xn," "))}e&&(this[Os]+=e)}[Ur](e,t=!0){const i=Object.create(null),a={top:NaN,bottom:NaN,left:NaN,right:NaN};let s=null;for(const[e,t]of this.style.split(";").map((e=>e.split(":",2))))switch(e){case"font-family":i.typeface=stripQuotes(t);break;case"font-size":i.size=getMeasurement(t);break;case"font-weight":i.weight=t;break;case"font-style":i.posture=t;break;case"letter-spacing":i.letterSpacing=getMeasurement(t);break;case"margin":const e=t.split(/ \t/).map((e=>getMeasurement(e)));switch(e.length){case 1:a.top=a.bottom=a.left=a.right=e[0];break;case 2:a.top=a.bottom=e[0];a.left=a.right=e[1];break;case 3:a.top=e[0];a.bottom=e[2];a.left=a.right=e[1];break;case 4:a.top=e[0];a.left=e[1];a.bottom=e[2];a.right=e[3]}break;case"margin-top":a.top=getMeasurement(t);break;case"margin-bottom":a.bottom=getMeasurement(t);break;case"margin-left":a.left=getMeasurement(t);break;case"margin-right":a.right=getMeasurement(t);break;case"line-height":s=getMeasurement(t)}e.pushData(i,a,s);if(this[Os])e.addString(this[Os]);else for(const t of this[rr]())"#text"!==t[kr]?t[Ur](e):e.addString(t[Os]);t&&e.popFont()}[jr](e){const t=[];this[Xs]={children:t};this[Js]({});if(0===t.length&&!this[Os])return HTMLResult.EMPTY;let i;i=this[Pn]?this[Os]?this[Os].replaceAll(Vn,"\n"):void 0:this[Os]||void 0;return HTMLResult.success({name:this[kr],attributes:{href:this.href,style:mapStyle(this.style,this,this[Pn])},children:t,value:i})}}class A extends XhtmlObject{constructor(e){super(e,"a");this.href=fixURL(e.href)||""}}class B extends XhtmlObject{constructor(e){super(e,"b")}[Ur](e){e.pushFont({weight:"bold"});super[Ur](e);e.popFont()}}class Body extends XhtmlObject{constructor(e){super(e,"body")}[jr](e){const t=super[jr](e),{html:i}=t;if(!i)return HTMLResult.EMPTY;i.name="div";i.attributes.class=["xfaRich"];return t}}class Br extends XhtmlObject{constructor(e){super(e,"br")}[Pr](){return"\n"}[Ur](e){e.addString("\n")}[jr](e){return HTMLResult.success({name:"br"})}}class Html extends XhtmlObject{constructor(e){super(e,"html")}[jr](e){const t=[];this[Xs]={children:t};this[Js]({});if(0===t.length)return HTMLResult.success({name:"div",attributes:{class:["xfaRich"],style:{}},value:this[Os]||""});if(1===t.length){const e=t[0];if(e.attributes?.class.includes("xfaRich"))return HTMLResult.success(e)}return HTMLResult.success({name:"div",attributes:{class:["xfaRich"],style:{}},children:t})}}class I extends XhtmlObject{constructor(e){super(e,"i")}[Ur](e){e.pushFont({posture:"italic"});super[Ur](e);e.popFont()}}class Li extends XhtmlObject{constructor(e){super(e,"li")}}class Ol extends XhtmlObject{constructor(e){super(e,"ol")}}class P extends XhtmlObject{constructor(e){super(e,"p")}[Ur](e){super[Ur](e,!1);e.addString("\n");e.addPara();e.popFont()}[Pr](){return this[Ir]()[rr]().at(-1)===this?super[Pr]():super[Pr]()+"\n"}}class Span extends XhtmlObject{constructor(e){super(e,"span")}}class Sub extends XhtmlObject{constructor(e){super(e,"sub")}}class Sup extends XhtmlObject{constructor(e){super(e,"sup")}}class Ul extends XhtmlObject{constructor(e){super(e,"ul")}}class XhtmlNamespace{static[zr](e,t){if(XhtmlNamespace.hasOwnProperty(e))return XhtmlNamespace[e](t)}static a(e){return new A(e)}static b(e){return new B(e)}static body(e){return new Body(e)}static br(e){return new Br(e)}static html(e){return new Html(e)}static i(e){return new I(e)}static li(e){return new Li(e)}static ol(e){return new Ol(e)}static p(e){return new P(e)}static span(e){return new Span(e)}static sub(e){return new Sub(e)}static sup(e){return new Sup(e)}static ul(e){return new Ul(e)}}const _n={config:ConfigNamespace,connection:ConnectionSetNamespace,datasets:DatasetsNamespace,localeSet:LocaleSetNamespace,signature:SignatureNamespace,stylesheet:StylesheetNamespace,template:TemplateNamespace,xdp:XdpNamespace,xhtml:XhtmlNamespace};class UnknownNamespace{constructor(e){this.namespaceId=e}[zr](e,t){return new XmlObject(this.namespaceId,e,t)}}class Root extends XFAObject{constructor(e){super(-1,"root",Object.create(null));this.element=null;this[lr]=e}[Nr](e){this.element=e;return!0}[Zs](){super[Zs]();if(this.element.template instanceof Template){this[lr].set(Jr,this.element);this.element.template[Yr](this[lr]);this.element.template[lr]=this[lr]}}}class Empty extends XFAObject{constructor(){super(-1,"",Object.create(null))}[Nr](e){return!1}}class Builder{constructor(e=null){this._namespaceStack=[];this._nsAgnosticLevel=0;this._namespacePrefixes=new Map;this._namespaces=new Map;this._nextNsId=Math.max(...Object.values(_r).map((({id:e})=>e)));this._currentNamespace=e||new UnknownNamespace(++this._nextNsId)}buildRoot(e){return new Root(e)}build({nsPrefix:e,name:t,attributes:i,namespace:a,prefixes:s}){const r=null!==a;if(r){this._namespaceStack.push(this._currentNamespace);this._currentNamespace=this._searchNamespace(a)}s&&this._addNamespacePrefix(s);if(i.hasOwnProperty(Rr)){const e=_n.datasets,t=i[Rr];let a=null;for(const[i,s]of Object.entries(t)){if(this._getNamespaceToUse(i)===e){a={xfa:s};break}}a?i[Rr]=a:delete i[Rr]}const n=this._getNamespaceToUse(e),g=n?.[zr](t,i)||new Empty;g[mr]()&&this._nsAgnosticLevel++;(r||s||g[mr]())&&(g[Ks]={hasNamespace:r,prefixes:s,nsAgnostic:g[mr]()});return g}isNsAgnostic(){return this._nsAgnosticLevel>0}_searchNamespace(e){let t=this._namespaces.get(e);if(t)return t;for(const[i,{check:a}]of Object.entries(_r))if(a(e)){t=_n[i];if(t){this._namespaces.set(e,t);return t}break}t=new UnknownNamespace(++this._nextNsId);this._namespaces.set(e,t);return t}_addNamespacePrefix(e){for(const{prefix:t,value:i}of e){const e=this._searchNamespace(i);let a=this._namespacePrefixes.get(t);if(!a){a=[];this._namespacePrefixes.set(t,a)}a.push(e)}}_getNamespaceToUse(e){if(!e)return this._currentNamespace;const t=this._namespacePrefixes.get(e);if(t?.length>0)return t.at(-1);warn(`Unknown namespace prefix: ${e}.`);return null}clean(e){const{hasNamespace:t,prefixes:i,nsAgnostic:a}=e;t&&(this._currentNamespace=this._namespaceStack.pop());i&&i.forEach((({prefix:e})=>{this._namespacePrefixes.get(e).pop()}));a&&this._nsAgnosticLevel--}}class XFAParser extends XMLParserBase{constructor(e=null,t=!1){super();this._builder=new Builder(e);this._stack=[];this._globalData={usedTypefaces:new Set};this._ids=new Map;this._current=this._builder.buildRoot(this._ids);this._errorCode=ys;this._whiteRegex=/^\s+$/;this._nbsps=/\xa0+/g;this._richText=t}parse(e){this.parseXml(e);if(this._errorCode===ys){this._current[Zs]();return this._current.element}}onText(e){e=e.replace(this._nbsps,(e=>e.slice(1)+" "));this._richText||this._current[xs]()?this._current[Mr](e,this._richText):this._whiteRegex.test(e)||this._current[Mr](e.trim())}onCdata(e){this._current[Mr](e)}_mkAttributes(e,t){let i=null,a=null;const s=Object.create({});for(const{name:r,value:n}of e)if("xmlns"===r)i?warn(`XFA - multiple namespace definition in <${t}>`):i=n;else if(r.startsWith("xmlns:")){const e=r.substring(6);a||(a=[]);a.push({prefix:e,value:n})}else{const e=r.indexOf(":");if(-1===e)s[r]=n;else{let t=s[Rr];t||(t=s[Rr]=Object.create(null));const[i,a]=[r.slice(0,e),r.slice(e+1)];(t[i]||=Object.create(null))[a]=n}}return[i,a,s]}_getNameAndPrefix(e,t){const i=e.indexOf(":");return-1===i?[e,null]:[e.substring(i+1),t?"":e.substring(0,i)]}onBeginElement(e,t,i){const[a,s,r]=this._mkAttributes(t,e),[n,g]=this._getNameAndPrefix(e,this._builder.isNsAgnostic()),o=this._builder.build({nsPrefix:g,name:n,attributes:r,namespace:a,prefixes:s});o[Cr]=this._globalData;if(i){o[Zs]();this._current[Nr](o)&&o[Kr](this._ids);o[Ys](this._builder)}else{this._stack.push(this._current);this._current=o}}onEndElement(e){const t=this._current;if(t[ur]()&&"string"==typeof t[Os]){const e=new XFAParser;e._globalData=this._globalData;const i=e.parse(t[Os]);t[Os]=null;t[Nr](i)}t[Zs]();this._current=this._stack.pop();this._current[Nr](t)&&t[Kr](this._ids);t[Ys](this._builder)}onError(e){this._errorCode=e}}class XFAFactory{constructor(e){try{this.root=(new XFAParser).parse(XFAFactory._createDocument(e));const t=new Binder(this.root);this.form=t.bind();this.dataHandler=new DataHandler(this.root,t.getData());this.form[Cr].template=this.form}catch(e){warn(`XFA - an error occurred during parsing and binding: ${e}`)}}isValid(){return this.root&&this.form}_createPagesHelper(){const e=this.form[Wr]();return new Promise(((t,i)=>{const nextIteration=()=>{try{const i=e.next();i.done?t(i.value):setTimeout(nextIteration,0)}catch(e){i(e)}};setTimeout(nextIteration,0)}))}async _createPages(){try{this.pages=await this._createPagesHelper();this.dims=this.pages.children.map((e=>{const{width:t,height:i}=e.attributes.style;return[0,0,parseInt(t),parseInt(i)]}))}catch(e){warn(`XFA - an error occurred during layout: ${e}`)}}getBoundingBox(e){return this.dims[e]}async getNumPages(){this.pages||await this._createPages();return this.dims.length}setImages(e){this.form[Cr].images=e}setFonts(e){this.form[Cr].fontFinder=new FontFinder(e);const t=[];for(let e of this.form[Cr].usedTypefaces){e=stripQuotes(e);this.form[Cr].fontFinder.find(e)||t.push(e)}return t.length>0?t:null}appendFonts(e,t){this.form[Cr].fontFinder.add(e,t)}async getPages(){this.pages||await this._createPages();const e=this.pages;this.pages=null;return e}serializeData(e){return this.dataHandler.serialize(e)}static _createDocument(e){return e["/xdp:xdp"]?Object.values(e).join(""):e["xdp:xdp"]}static getRichTextAsHtml(e){if(!e||"string"!=typeof e)return null;try{let t=new XFAParser(XhtmlNamespace,!0).parse(e);if(!["body","xhtml"].includes(t[kr])){const e=XhtmlNamespace.body({});e[Hs](t);t=e}const i=t[jr]();if(!i.success)return null;const{html:a}=i,{attributes:s}=a;if(s){s.class&&(s.class=s.class.filter((e=>!e.startsWith("xfa"))));s.dir="auto"}return{html:a,str:t[Pr]()}}catch(e){warn(`XFA - an error occurred during parsing of rich text: ${e}`)}return null}}class AnnotationFactory{static createGlobals(e){return Promise.all([e.ensureCatalog("acroForm"),e.ensureDoc("xfaDatasets"),e.ensureCatalog("structTreeRoot"),e.ensureCatalog("baseUrl"),e.ensureCatalog("attachments")]).then((([t,i,a,s,r])=>({pdfManager:e,acroForm:t instanceof Dict?t:Dict.empty,xfaDatasets:i,structTreeRoot:a,baseUrl:s,attachments:r})),(e=>{warn(`createGlobals: "${e}".`);return null}))}static async create(e,t,i,a,s,r,n){const g=s?await this._getPageIndex(e,t,i.pdfManager):null;return i.pdfManager.ensure(this,"_create",[e,t,i,a,s,r,g,n])}static _create(e,t,i,a,s=!1,r=null,n=null,g=null){const o=e.fetchIfRef(t);if(!(o instanceof Dict))return;const{acroForm:c,pdfManager:C}=i,h=t instanceof Ref?t.toString():`annot_${a.createObjId()}`;let l=o.get("Subtype");l=l instanceof Name?l.name:null;const Q={xref:e,ref:t,dict:o,subtype:l,id:h,annotationGlobals:i,collectFields:s,orphanFields:r,needAppearances:!s&&!0===c.get("NeedAppearances"),pageIndex:n,evaluatorOptions:C.evaluatorOptions,pageRef:g};switch(l){case"Link":return new LinkAnnotation(Q);case"Text":return new TextAnnotation(Q);case"Widget":let e=getInheritableProperty({dict:o,key:"FT"});e=e instanceof Name?e.name:null;switch(e){case"Tx":return new TextWidgetAnnotation(Q);case"Btn":return new ButtonWidgetAnnotation(Q);case"Ch":return new ChoiceWidgetAnnotation(Q);case"Sig":return new SignatureWidgetAnnotation(Q)}warn(`Unimplemented widget field type "${e}", falling back to base field type.`);return new WidgetAnnotation(Q);case"Popup":return new PopupAnnotation(Q);case"FreeText":return new FreeTextAnnotation(Q);case"Line":return new LineAnnotation(Q);case"Square":return new SquareAnnotation(Q);case"Circle":return new CircleAnnotation(Q);case"PolyLine":return new PolylineAnnotation(Q);case"Polygon":return new PolygonAnnotation(Q);case"Caret":return new CaretAnnotation(Q);case"Ink":return new InkAnnotation(Q);case"Highlight":return new HighlightAnnotation(Q);case"Underline":return new UnderlineAnnotation(Q);case"Squiggly":return new SquigglyAnnotation(Q);case"StrikeOut":return new StrikeOutAnnotation(Q);case"Stamp":return new StampAnnotation(Q);case"FileAttachment":return new FileAttachmentAnnotation(Q);default:s||warn(l?`Unimplemented annotation type "${l}", falling back to base annotation.`:"Annotation is missing the required /Subtype.");return new Annotation(Q)}}static async _getPageIndex(e,t,i){try{const a=await e.fetchIfRefAsync(t);if(!(a instanceof Dict))return-1;const s=a.getRaw("P");if(s instanceof Ref)try{return await i.ensureCatalog("getPageIndex",[s])}catch(e){info(`_getPageIndex -- not a valid page reference: "${e}".`)}if(a.has("Kids"))return-1;const r=await i.ensureDoc("numPages");for(let e=0;ee/255))}function getQuadPoints(e,t){const i=e.getArray("QuadPoints");if(!isNumberArray(i,null)||0===i.length||i.length%8>0)return null;const a=new Float32Array(i.length);for(let e=0,s=i.length;et[2]||Et[3]))return null;a.set([l,u,Q,u,l,E,Q,E],e)}return a}function getTransformMatrix(e,t,i){const[a,s,r,n]=Util.getAxialAlignedBoundingBox(t,i);if(a===r||s===n)return[1,0,0,1,e[0],e[1]];const g=(e[2]-e[0])/(r-a),o=(e[3]-e[1])/(n-s);return[g,0,0,o,e[0]-a*g,e[1]-s*o]}class Annotation{constructor(e){const{dict:t,xref:i,annotationGlobals:a,ref:s,orphanFields:r}=e,n=r?.get(s);n&&t.set("Parent",n);this.setTitle(t.get("T"));this.setContents(t.get("Contents"));this.setModificationDate(t.get("M"));this.setFlags(t.get("F"));this.setRectangle(t.getArray("Rect"));this.setColor(t.getArray("C"));this.setBorderStyle(t);this.setAppearance(t);this.setOptionalContent(t);const g=t.get("MK");this.setBorderAndBackgroundColors(g);this.setRotation(g,t);this.ref=e.ref instanceof Ref?e.ref:null;this._streams=[];this.appearance&&this._streams.push(this.appearance);const o=!!(this.flags&eA),c=!!(this.flags&tA);this.data={annotationFlags:this.flags,borderStyle:this.borderStyle,color:this.color,backgroundColor:this.backgroundColor,borderColor:this.borderColor,rotation:this.rotation,contentsObj:this._contents,hasAppearance:!!this.appearance,id:e.id,modificationDate:this.modificationDate,rect:this.rectangle,subtype:e.subtype,hasOwnCanvas:!1,noRotate:!!(this.flags&$),noHTML:o&&c,isEditable:!1,structParent:-1};if(a.structTreeRoot){let i=t.get("StructParent");this.data.structParent=i=Number.isInteger(i)&&i>=0?i:-1;a.structTreeRoot.addAnnotationIdToPage(e.pageRef,i)}if(e.collectFields){const a=t.get("Kids");if(Array.isArray(a)){const e=[];for(const t of a)t instanceof Ref&&e.push(t.toString());0!==e.length&&(this.data.kidIds=e)}this.data.actions=collectActions(i,t,dA);this.data.fieldName=this._constructFieldName(t);this.data.pageIndex=e.pageIndex}const C=t.get("IT");C instanceof Name&&(this.data.it=C.name);this._isOffscreenCanvasSupported=e.evaluatorOptions.isOffscreenCanvasSupported;this._fallbackFontDict=null;this._needAppearances=!1}_hasFlag(e,t){return!!(e&t)}_buildFlags(e,t){let{flags:i}=this;if(void 0===e){if(void 0===t)return;return t?i&~_:i&~z|_}if(e){i|=_;return t?i&~AA|z:i&~z|AA}i&=~(z|AA);return t?i&~_:i|_}_isViewable(e){return!this._hasFlag(e,V)&&!this._hasFlag(e,AA)}_isPrintable(e){return this._hasFlag(e,_)&&!this._hasFlag(e,z)&&!this._hasFlag(e,V)}mustBeViewed(e,t){const i=e?.get(this.data.id)?.noView;return void 0!==i?!i:this.viewable&&!this._hasFlag(this.flags,z)}mustBePrinted(e){const t=e?.get(this.data.id)?.noPrint;return void 0!==t?!t:this.printable}mustBeViewedWhenEditing(e,t=null){return e?!this.data.isEditable:!t?.has(this.data.id)}get viewable(){return null!==this.data.quadPoints&&(0===this.flags||this._isViewable(this.flags))}get printable(){return null!==this.data.quadPoints&&(0!==this.flags&&this._isPrintable(this.flags))}_parseStringHelper(e){const t="string"==typeof e?stringToPDFString(e):"";return{str:t,dir:t&&"rtl"===bidi(t).dir?"rtl":"ltr"}}setDefaultAppearance(e){const{dict:t,annotationGlobals:i}=e,a=getInheritableProperty({dict:t,key:"DA"})||i.acroForm.get("DA");this._defaultAppearance="string"==typeof a?a:"";this.data.defaultAppearanceData=parseDefaultAppearance(this._defaultAppearance)}setTitle(e){this._title=this._parseStringHelper(e)}setContents(e){this._contents=this._parseStringHelper(e)}setModificationDate(e){this.modificationDate="string"==typeof e?e:null}setFlags(e){this.flags=Number.isInteger(e)&&e>0?e:0;this.flags&V&&"Annotation"!==this.constructor.name&&(this.flags^=V)}hasFlag(e){return this._hasFlag(this.flags,e)}setRectangle(e){this.rectangle=lookupNormalRect(e,[0,0,0,0])}setColor(e){this.color=getRgbColor(e)}setLineEndings(e){this.lineEndings=["None","None"];if(Array.isArray(e)&&2===e.length)for(let t=0;t<2;t++){const i=e[t];if(i instanceof Name)switch(i.name){case"None":continue;case"Square":case"Circle":case"Diamond":case"OpenArrow":case"ClosedArrow":case"Butt":case"ROpenArrow":case"RClosedArrow":case"Slash":this.lineEndings[t]=i.name;continue}warn(`Ignoring invalid lineEnding: ${i}`)}}setRotation(e,t){this.rotation=0;let i=e instanceof Dict?e.get("R")||0:t.get("Rotate")||0;if(Number.isInteger(i)&&0!==i){i%=360;i<0&&(i+=360);i%90==0&&(this.rotation=i)}}setBorderAndBackgroundColors(e){if(e instanceof Dict){this.borderColor=getRgbColor(e.getArray("BC"),null);this.backgroundColor=getRgbColor(e.getArray("BG"),null)}else this.borderColor=this.backgroundColor=null}setBorderStyle(e){this.borderStyle=new AnnotationBorderStyle;if(e instanceof Dict)if(e.has("BS")){const t=e.get("BS");if(t instanceof Dict){const e=t.get("Type");if(!e||isName(e,"Border")){this.borderStyle.setWidth(t.get("W"),this.rectangle);this.borderStyle.setStyle(t.get("S"));this.borderStyle.setDashArray(t.getArray("D"))}}}else if(e.has("Border")){const t=e.getArray("Border");if(Array.isArray(t)&&t.length>=3){this.borderStyle.setHorizontalCornerRadius(t[0]);this.borderStyle.setVerticalCornerRadius(t[1]);this.borderStyle.setWidth(t[2],this.rectangle);4===t.length&&this.borderStyle.setDashArray(t[3],!0)}}else this.borderStyle.setWidth(0)}setAppearance(e){this.appearance=null;const t=e.get("AP");if(!(t instanceof Dict))return;const i=t.get("N");if(i instanceof BaseStream){this.appearance=i;return}if(!(i instanceof Dict))return;const a=e.get("AS");if(!(a instanceof Name&&i.has(a.name)))return;const s=i.get(a.name);s instanceof BaseStream&&(this.appearance=s)}setOptionalContent(e){this.oc=null;const t=e.get("OC");t instanceof Name?warn("setOptionalContent: Support for /Name-entry is not implemented."):t instanceof Dict&&(this.oc=t)}loadResources(e,t){return t.dict.getAsync("Resources").then((t=>{if(!t)return;return new ObjectLoader(t,e,t.xref).load().then((function(){return t}))}))}async getOperatorList(e,t,a,s){const{hasOwnCanvas:r,id:n,rect:g}=this.data;let c=this.appearance;const C=!!(r&&a&o);if(C&&(g[0]===g[2]||g[1]===g[3])){this.data.hasOwnCanvas=!1;return{opList:new OperatorList,separateForm:!1,separateCanvas:!1}}if(!c){if(!C)return{opList:new OperatorList,separateForm:!1,separateCanvas:!1};c=new StringStream("");c.dict=new Dict}const h=c.dict,l=await this.loadResources(["ExtGState","ColorSpace","Pattern","Shading","XObject","Font"],c),Q=lookupRect(h.getArray("BBox"),[0,0,1,1]),E=lookupMatrix(h.getArray("Matrix"),i),u=getTransformMatrix(g,Q,E),d=new OperatorList;let f;this.oc&&(f=await e.parseMarkedContentProps(this.oc,null));void 0!==f&&d.addOp(Ye,["OC",f]);d.addOp(je,[n,g,u,E,C]);await e.getOperatorList({stream:c,task:t,resources:l,operatorList:d,fallbackFontDict:this._fallbackFontDict});d.addOp(Xe,[]);void 0!==f&&d.addOp(ve,[]);this.reset();return{opList:d,separateForm:!1,separateCanvas:C}}async save(e,t,i,a){return null}get hasTextContent(){return!1}async extractTextContent(e,t,i){if(!this.appearance)return;const a=await this.loadResources(["ExtGState","Font","Properties","XObject"],this.appearance),s=[],r=[];let n=null;const g={desiredSize:Math.Infinity,ready:!0,enqueue(e,t){for(const t of e.items)if(void 0!==t.str){n||=t.transform.slice(-2);r.push(t.str);if(t.hasEOL){s.push(r.join("").trimEnd());r.length=0}}}};await e.getTextContent({stream:this.appearance,task:t,resources:a,includeMarkedContent:!0,keepWhiteSpace:!0,sink:g,viewBox:i});this.reset();r.length&&s.push(r.join("").trimEnd());if(s.length>1||s[0]){const e=this.appearance.dict,t=lookupRect(e.getArray("BBox"),null),i=lookupMatrix(e.getArray("Matrix"),null);this.data.textPosition=this._transformPoint(n,t,i);this.data.textContent=s}}_transformPoint(e,t,i){const{rect:a}=this.data;t||=[0,0,1,1];i||=[1,0,0,1,0,0];const s=getTransformMatrix(a,t,i);s[4]-=a[0];s[5]-=a[1];e=Util.applyTransform(e,s);return Util.applyTransform(e,i)}getFieldObject(){return this.data.kidIds?{id:this.data.id,actions:this.data.actions,name:this.data.fieldName,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,type:"",kidIds:this.data.kidIds,page:this.data.pageIndex,rotation:this.rotation}:null}reset(){for(const e of this._streams)e.reset()}_constructFieldName(e){if(!e.has("T")&&!e.has("Parent")){warn("Unknown field name, falling back to empty field name.");return""}if(!e.has("Parent"))return stringToPDFString(e.get("T"));const t=[];e.has("T")&&t.unshift(stringToPDFString(e.get("T")));let i=e;const a=new RefSet;e.objId&&a.put(e.objId);for(;i.has("Parent");){i=i.get("Parent");if(!(i instanceof Dict)||i.objId&&a.has(i.objId))break;i.objId&&a.put(i.objId);i.has("T")&&t.unshift(stringToPDFString(i.get("T")))}return t.join(".")}}class AnnotationBorderStyle{constructor(){this.width=1;this.rawWidth=1;this.style=lA;this.dashArray=[3];this.horizontalCornerRadius=0;this.verticalCornerRadius=0}setWidth(e,t=[0,0,0,0]){if(e instanceof Name)this.width=0;else if("number"==typeof e){if(e>0){this.rawWidth=e;const i=(t[2]-t[0])/2,a=(t[3]-t[1])/2;if(i>0&&a>0&&(e>i||e>a)){warn(`AnnotationBorderStyle.setWidth - ignoring width: ${e}`);e=1}}this.width=e}}setStyle(e){if(e instanceof Name)switch(e.name){case"S":this.style=lA;break;case"D":this.style=BA;break;case"B":this.style=QA;break;case"I":this.style=EA;break;case"U":this.style=uA}}setDashArray(e,t=!1){if(Array.isArray(e)){let i=!0,a=!0;for(const t of e){if(!(+t>=0)){i=!1;break}t>0&&(a=!1)}if(0===e.length||i&&!a){this.dashArray=e;t&&this.setStyle(Name.get("D"))}else this.width=0}else e&&(this.width=0)}setHorizontalCornerRadius(e){Number.isInteger(e)&&(this.horizontalCornerRadius=e)}setVerticalCornerRadius(e){Number.isInteger(e)&&(this.verticalCornerRadius=e)}}class MarkupAnnotation extends Annotation{constructor(e){super(e);const{dict:t}=e;if(t.has("IRT")){const e=t.getRaw("IRT");this.data.inReplyTo=e instanceof Ref?e.toString():null;const i=t.get("RT");this.data.replyType=i instanceof Name?i.name:Z}let i=null;if(this.data.replyType===X){const e=t.get("IRT");this.setTitle(e.get("T"));this.data.titleObj=this._title;this.setContents(e.get("Contents"));this.data.contentsObj=this._contents;if(e.has("CreationDate")){this.setCreationDate(e.get("CreationDate"));this.data.creationDate=this.creationDate}else this.data.creationDate=null;if(e.has("M")){this.setModificationDate(e.get("M"));this.data.modificationDate=this.modificationDate}else this.data.modificationDate=null;i=e.getRaw("Popup");if(e.has("C")){this.setColor(e.getArray("C"));this.data.color=this.color}else this.data.color=null}else{this.data.titleObj=this._title;this.setCreationDate(t.get("CreationDate"));this.data.creationDate=this.creationDate;i=t.getRaw("Popup");t.has("C")||(this.data.color=null)}this.data.popupRef=i instanceof Ref?i.toString():null;t.has("RC")&&(this.data.richText=XFAFactory.getRichTextAsHtml(t.get("RC")))}setCreationDate(e){this.creationDate="string"==typeof e?e:null}_setDefaultAppearance({xref:e,extra:t,strokeColor:i,fillColor:a,blendMode:s,strokeAlpha:r,fillAlpha:n,pointsCallback:g}){let o=Number.MAX_VALUE,c=Number.MAX_VALUE,C=Number.MIN_VALUE,h=Number.MIN_VALUE;const l=["q"];t&&l.push(t);i&&l.push(`${i[0]} ${i[1]} ${i[2]} RG`);a&&l.push(`${a[0]} ${a[1]} ${a[2]} rg`);const Q=this.data.quadPoints||Float32Array.from([this.rectangle[0],this.rectangle[3],this.rectangle[2],this.rectangle[3],this.rectangle[0],this.rectangle[1],this.rectangle[2],this.rectangle[1]]);for(let e=0,t=Q.length;e"string"==typeof e)).map((e=>stringToPDFString(e))):e instanceof Name?stringToPDFString(e.name):"string"==typeof e?stringToPDFString(e):null}hasFieldFlag(e){return!!(this.data.fieldFlags&e)}_isViewable(e){return!0}mustBeViewed(e,t){return t?this.viewable:super.mustBeViewed(e,t)&&!this._hasFlag(this.flags,AA)}getRotationMatrix(e){let t=e?.get(this.data.id)?.rotation;void 0===t&&(t=this.rotation);if(0===t)return i;return getRotationMatrix(t,this.data.rect[2]-this.data.rect[0],this.data.rect[3]-this.data.rect[1])}getBorderAndBackgroundAppearances(e){let t=e?.get(this.data.id)?.rotation;void 0===t&&(t=this.rotation);if(!this.backgroundColor&&!this.borderColor)return"";const i=this.data.rect[2]-this.data.rect[0],a=this.data.rect[3]-this.data.rect[1],s=0===t||180===t?`0 0 ${i} ${a} re`:`0 0 ${a} ${i} re`;let r="";this.backgroundColor&&(r=`${getPdfColor(this.backgroundColor,!0)} ${s} f `);if(this.borderColor){r+=`${this.borderStyle.width||1} w ${getPdfColor(this.borderColor,!1)} ${s} S `}return r}async getOperatorList(e,t,i,a){if(i&h&&!(this instanceof SignatureWidgetAnnotation)&&!this.data.noHTML&&!this.data.hasOwnCanvas)return{opList:new OperatorList,separateForm:!0,separateCanvas:!1};if(!this._hasText)return super.getOperatorList(e,t,i,a);const s=await this._getAppearance(e,t,i,a);if(this.appearance&&null===s)return super.getOperatorList(e,t,i,a);const r=new OperatorList;if(!this._defaultAppearance||null===s)return{opList:r,separateForm:!1,separateCanvas:!1};const n=!!(this.data.hasOwnCanvas&&i&o),g=[0,0,this.data.rect[2]-this.data.rect[0],this.data.rect[3]-this.data.rect[1]],c=getTransformMatrix(this.data.rect,g,[1,0,0,1,0,0]);let C;this.oc&&(C=await e.parseMarkedContentProps(this.oc,null));void 0!==C&&r.addOp(Ye,["OC",C]);r.addOp(je,[this.data.id,this.data.rect,c,this.getRotationMatrix(a),n]);const l=new StringStream(s);await e.getOperatorList({stream:l,task:t,resources:this._fieldResources.mergedResources,operatorList:r});r.addOp(Xe,[]);void 0!==C&&r.addOp(ve,[]);return{opList:r,separateForm:!1,separateCanvas:n}}_getMKDict(e){const t=new Dict(null);e&&t.set("R",e);this.borderColor&&t.set("BC",getPdfColorArray(this.borderColor));this.backgroundColor&&t.set("BG",getPdfColorArray(this.backgroundColor));return t.size>0?t:null}amendSavedDict(e,t){}setValue(e,t,i,a){const{dict:s,ref:r}=function getParentToUpdate(e,t,i){const a=new RefSet,s=e,r={dict:null,ref:null};for(;e instanceof Dict&&!a.has(t);){a.put(t);if(e.has("T"))break;if(!((t=e.getRaw("Parent"))instanceof Ref))return r;e=i.fetch(t)}if(e instanceof Dict&&e!==s){r.dict=e;r.ref=t}return r}(e,this.ref,i);if(s){if(!a.has(r)){const e=s.clone();e.set("V",t);a.put(r,{data:e});return e}}else e.set("V",t);return null}async save(e,t,a,s){const r=a?.get(this.data.id),n=this._buildFlags(r?.noView,r?.noPrint);let g=r?.value,o=r?.rotation;if(g===this.data.fieldValue||void 0===g){if(!this._hasValueFromXFA&&void 0===o&&void 0===n)return;g||=this.data.fieldValue}if(void 0===o&&!this._hasValueFromXFA&&Array.isArray(g)&&Array.isArray(this.data.fieldValue)&&isArrayEqual(g,this.data.fieldValue)&&void 0===n)return;void 0===o&&(o=this.rotation);let c=null;if(!this._needAppearances){c=await this._getAppearance(e,t,C,a);if(null===c&&void 0===n)return}let h=!1;if(c?.needAppearances){h=!0;c=null}const{xref:l}=e,Q=l.fetchIfRef(this.ref);if(!(Q instanceof Dict))return;const E=new Dict(l);for(const e of Q.getKeys())"AP"!==e&&E.set(e,Q.getRaw(e));if(void 0!==n){E.set("F",n);if(null===c&&!h){const e=Q.getRaw("AP");e&&E.set("AP",e)}}const u={path:this.data.fieldName,value:g},d=this.setValue(E,Array.isArray(g)?g.map(stringToAsciiOrUTF16BE):stringToAsciiOrUTF16BE(g),l,s);this.amendSavedDict(a,d||E);const f=this._getMKDict(o);f&&E.set("MK",f);s.put(this.ref,{data:E,xfa:u,needAppearances:h});if(null!==c){const e=l.getNewTemporaryRef(),t=new Dict(l);E.set("AP",t);t.set("N",e);const r=this._getSaveFieldResources(l),n=new StringStream(c),g=n.dict=new Dict(l);g.set("Subtype",Name.get("Form"));g.set("Resources",r);g.set("BBox",[0,0,this.data.rect[2]-this.data.rect[0],this.data.rect[3]-this.data.rect[1]]);const o=this.getRotationMatrix(a);o!==i&&g.set("Matrix",o);s.put(e,{data:n,xfa:null,needAppearances:!1})}E.set("M",`D:${getModificationDate()}`)}async _getAppearance(e,t,i,a){if(this.hasFieldFlag(rA))return null;const s=a?.get(this.data.id);let r,g;if(s){r=s.formattedValue||s.value;g=s.rotation}if(void 0===g&&void 0===r&&!this._needAppearances&&(!this._hasValueFromXFA||this.appearance))return null;const o=this.getBorderAndBackgroundAppearances(a);if(void 0===r){r=this.data.fieldValue;if(!r)return`/Tx BMC q ${o}Q EMC`}Array.isArray(r)&&1===r.length&&(r=r[0]);assert("string"==typeof r,"Expected `value` to be a string.");r=r.trimEnd();if(this.data.combo){const e=this.data.options.find((({exportValue:e})=>r===e));r=e?.displayValue||r}if(""===r)return`/Tx BMC q ${o}Q EMC`;void 0===g&&(g=this.rotation);let c,h=-1;if(this.data.multiLine){c=r.split(/\r\n?|\n/).map((e=>e.normalize("NFC")));h=c.length}else c=[r.replace(/\r\n?|\n/,"").normalize("NFC")];let l=this.data.rect[3]-this.data.rect[1],Q=this.data.rect[2]-this.data.rect[0];90!==g&&270!==g||([Q,l]=[l,Q]);this._defaultAppearance||(this.data.defaultAppearanceData=parseDefaultAppearance(this._defaultAppearance="/Helvetica 0 Tf 0 g"));let E,u,d,f=await WidgetAnnotation._getFontData(e,t,this.data.defaultAppearanceData,this._fieldResources.mergedResources);const p=[];let m=!1;for(const e of c){const t=f.encodeString(e);t.length>1&&(m=!0);p.push(t.join(""))}if(m&&i&C)return{needAppearances:!0};if(m&&this._isOffscreenCanvasSupported){const i=this.data.comb?"monospace":"sans-serif",a=new FakeUnicodeFont(e.xref,i),s=a.createFontResources(c.join("")),n=s.getRaw("Font");if(this._fieldResources.mergedResources.has("Font")){const e=this._fieldResources.mergedResources.get("Font");for(const t of n.getKeys())e.set(t,n.getRaw(t))}else this._fieldResources.mergedResources.set("Font",n);const g=a.fontName.name;f=await WidgetAnnotation._getFontData(e,t,{fontName:g,fontSize:0},s);for(let e=0,t=p.length;e2)return`/Tx BMC q ${o}BT `+E+` 1 0 0 1 ${numberToString(2)} ${numberToString(b)} Tm (${escapeString(p[0])}) Tj ET Q EMC`;return`/Tx BMC q ${o}BT `+E+` 1 0 0 1 0 0 Tm ${this._renderText(p[0],f,u,Q,D,{shift:0},2,b)} ET Q EMC`}static async _getFontData(e,t,i,a){const s=new OperatorList,r={font:null,clone(){return this}},{fontName:n,fontSize:g}=i;await e.handleSetFont(a,[n&&Name.get(n),g],null,s,t,r,null);return r.font}_getTextWidth(e,t){return t.charsToGlyphs(e).reduce(((e,t)=>e+t.width),0)/1e3}_computeFontSize(e,t,i,a,r){let{fontSize:n}=this.data.defaultAppearanceData,g=(n||12)*s,o=Math.round(e/g);if(!n){const roundWithTwoDigits=e=>Math.floor(100*e)/100;if(-1===r){const r=this._getTextWidth(i,a);n=roundWithTwoDigits(Math.min(e/s,t/r));o=1}else{const c=i.split(/\r\n?|\n/),C=[];for(const e of c){const t=a.encodeString(e).join(""),i=a.charsToGlyphs(t),s=a.getCharPositions(t);C.push({line:t,glyphs:i,positions:s})}const isTooBig=i=>{let s=0;for(const r of C){s+=this._splitLine(null,a,i,t,r).length*i;if(s>e)return!0}return!1};o=Math.max(o,r);for(;;){g=e/o;n=roundWithTwoDigits(g/s);if(!isTooBig(n))break;o++}}const{fontName:c,fontColor:C}=this.data.defaultAppearanceData;this._defaultAppearance=function createDefaultAppearance({fontSize:e,fontName:t,fontColor:i}){return`/${escapePDFName(t)} ${e} Tf ${getPdfColor(i,!0)}`}({fontSize:n,fontName:c,fontColor:C})}return[this._defaultAppearance,n,e/o]}_renderText(e,t,i,a,s,r,n,g){let o;if(1===s){o=(a-this._getTextWidth(e,t)*i)/2}else if(2===s){o=a-this._getTextWidth(e,t)*i-n}else o=n;const c=numberToString(o-r.shift);r.shift=o;return`${c} ${g=numberToString(g)} Td (${escapeString(e)}) Tj`}_getSaveFieldResources(e){const{localResources:t,appearanceResources:i,acroFormResources:a}=this._fieldResources,s=this.data.defaultAppearanceData?.fontName;if(!s)return t||Dict.empty;for(const e of[t,i])if(e instanceof Dict){const t=e.get("Font");if(t instanceof Dict&&t.has(s))return e}if(a instanceof Dict){const i=a.get("Font");if(i instanceof Dict&&i.has(s)){const a=new Dict(e);a.set(s,i.getRaw(s));const r=new Dict(e);r.set("Font",a);return Dict.merge({xref:e,dictArray:[r,t],mergeSubDicts:!0})}}return t||Dict.empty}getFieldObject(){return null}}class TextWidgetAnnotation extends WidgetAnnotation{constructor(e){super(e);const{dict:t}=e;if(t.has("PMD")){this.flags|=z;this.data.hidden=!0;warn("Barcodes are not supported")}this.data.hasOwnCanvas=this.data.readOnly&&!this.data.noHTML;this._hasText=!0;"string"!=typeof this.data.fieldValue&&(this.data.fieldValue="");let i=getInheritableProperty({dict:t,key:"Q"});(!Number.isInteger(i)||i<0||i>2)&&(i=null);this.data.textAlignment=i;let a=getInheritableProperty({dict:t,key:"MaxLen"});(!Number.isInteger(a)||a<0)&&(a=0);this.data.maxLen=a;this.data.multiLine=this.hasFieldFlag(sA);this.data.comb=this.hasFieldFlag(hA)&&!this.hasFieldFlag(sA)&&!this.hasFieldFlag(rA)&&!this.hasFieldFlag(IA)&&0!==this.data.maxLen;this.data.doNotScroll=this.hasFieldFlag(CA)}get hasTextContent(){return!!this.appearance&&!this._needAppearances}_getCombAppearance(e,t,i,a,s,r,n,g,o,c,C){const h=s/this.data.maxLen,l=this.getBorderAndBackgroundAppearances(C),Q=[],E=t.getCharPositions(i);for(const[e,t]of E)Q.push(`(${escapeString(i.substring(e,t))}) Tj`);const u=Q.join(` ${numberToString(h)} 0 Td `);return`/Tx BMC q ${l}BT `+e+` 1 0 0 1 ${numberToString(n)} ${numberToString(g+o)} Tm ${u} ET Q EMC`}_getMultilineAppearance(e,t,i,a,s,r,n,g,o,c,C,h){const l=[],Q=s-2*g,E={shift:0};for(let e=0,r=t.length;ea){o.push(e.substring(l,i));l=i;Q=u;c=-1;h=-1}else{Q+=u;c=i;C=s;h=t}else if(Q+u>a)if(-1!==c){o.push(e.substring(l,C));l=C;t=h+1;c=-1;Q=0}else{o.push(e.substring(l,i));l=i;Q=u}else Q+=u}lt?`\\${t}`:"\\s+"));new RegExp(`^\\s*${r}\\s*$`).test(this.data.fieldValue)&&(this.data.textContent=this.data.fieldValue.split("\n"))}getFieldObject(){return{id:this.data.id,value:this.data.fieldValue,defaultValue:this.data.defaultFieldValue||"",multiline:this.data.multiLine,password:this.hasFieldFlag(rA),charLimit:this.data.maxLen,comb:this.data.comb,editable:!this.data.readOnly,hidden:this.data.hidden,name:this.data.fieldName,rect:this.data.rect,actions:this.data.actions,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,type:"text"}}}class ButtonWidgetAnnotation extends WidgetAnnotation{constructor(e){super(e);this.checkedAppearance=null;this.uncheckedAppearance=null;this.data.checkBox=!this.hasFieldFlag(nA)&&!this.hasFieldFlag(gA);this.data.radioButton=this.hasFieldFlag(nA)&&!this.hasFieldFlag(gA);this.data.pushButton=this.hasFieldFlag(gA);this.data.isTooltipOnly=!1;if(this.data.checkBox)this._processCheckBox(e);else if(this.data.radioButton)this._processRadioButton(e);else if(this.data.pushButton){this.data.hasOwnCanvas=!0;this.data.noHTML=!1;this._processPushButton(e)}else warn("Invalid field flags for button widget annotation")}async getOperatorList(e,t,a,s){if(this.data.pushButton)return super.getOperatorList(e,t,a,!1,s);let r=null,n=null;if(s){const e=s.get(this.data.id);r=e?e.value:null;n=e?e.rotation:null}if(null===r&&this.appearance)return super.getOperatorList(e,t,a,s);null==r&&(r=this.data.checkBox?this.data.fieldValue===this.data.exportValue:this.data.fieldValue===this.data.buttonValue);const g=r?this.checkedAppearance:this.uncheckedAppearance;if(g){const r=this.appearance,o=lookupMatrix(g.dict.getArray("Matrix"),i);n&&g.dict.set("Matrix",this.getRotationMatrix(s));this.appearance=g;const c=super.getOperatorList(e,t,a,s);this.appearance=r;g.dict.set("Matrix",o);return c}return{opList:new OperatorList,separateForm:!1,separateCanvas:!1}}async save(e,t,i,a){this.data.checkBox?this._saveCheckbox(e,t,i,a):this.data.radioButton&&this._saveRadioButton(e,t,i,a)}async _saveCheckbox(e,t,i,a){if(!i)return;const s=i.get(this.data.id),r=this._buildFlags(s?.noView,s?.noPrint);let n=s?.rotation,g=s?.value;if(void 0===n&&void 0===r){if(void 0===g)return;if(this.data.fieldValue===this.data.exportValue===g)return}let o=e.xref.fetchIfRef(this.ref);if(!(o instanceof Dict))return;o=o.clone();void 0===n&&(n=this.rotation);void 0===g&&(g=this.data.fieldValue===this.data.exportValue);const c={path:this.data.fieldName,value:g?this.data.exportValue:""},C=Name.get(g?this.data.exportValue:"Off");this.setValue(o,C,e.xref,a);o.set("AS",C);o.set("M",`D:${getModificationDate()}`);void 0!==r&&o.set("F",r);const h=this._getMKDict(n);h&&o.set("MK",h);a.put(this.ref,{data:o,xfa:c,needAppearances:!1})}async _saveRadioButton(e,t,i,a){if(!i)return;const s=i.get(this.data.id),r=this._buildFlags(s?.noView,s?.noPrint);let n=s?.rotation,g=s?.value;if(void 0===n&&void 0===r){if(void 0===g)return;if(this.data.fieldValue===this.data.buttonValue===g)return}let o=e.xref.fetchIfRef(this.ref);if(!(o instanceof Dict))return;o=o.clone();void 0===g&&(g=this.data.fieldValue===this.data.buttonValue);void 0===n&&(n=this.rotation);const c={path:this.data.fieldName,value:g?this.data.buttonValue:""},C=Name.get(g?this.data.buttonValue:"Off");g&&this.setValue(o,C,e.xref,a);o.set("AS",C);o.set("M",`D:${getModificationDate()}`);void 0!==r&&o.set("F",r);const h=this._getMKDict(n);h&&o.set("MK",h);a.put(this.ref,{data:o,xfa:c,needAppearances:!1})}_getDefaultCheckedAppearance(e,t){const i=this.data.rect[2]-this.data.rect[0],a=this.data.rect[3]-this.data.rect[1],s=[0,0,i,a],r=.8*Math.min(i,a);let n,g;if("check"===t){n={width:.755*r,height:.705*r};g="3"}else if("disc"===t){n={width:.791*r,height:.705*r};g="l"}else unreachable(`_getDefaultCheckedAppearance - unsupported type: ${t}`);const o=`q BT /PdfJsZaDb ${r} Tf 0 g ${numberToString((i-n.width)/2)} ${numberToString((a-n.height)/2)} Td (${g}) Tj ET Q`,c=new Dict(e.xref);c.set("FormType",1);c.set("Subtype",Name.get("Form"));c.set("Type",Name.get("XObject"));c.set("BBox",s);c.set("Matrix",[1,0,0,1,0,0]);c.set("Length",o.length);const C=new Dict(e.xref),h=new Dict(e.xref);h.set("PdfJsZaDb",this.fallbackFontDict);C.set("Font",h);c.set("Resources",C);this.checkedAppearance=new StringStream(o);this.checkedAppearance.dict=c;this._streams.push(this.checkedAppearance)}_processCheckBox(e){const t=e.dict.get("AP");if(!(t instanceof Dict))return;const i=t.get("N");if(!(i instanceof Dict))return;const a=this._decodeFormValue(e.dict.get("AS"));"string"==typeof a&&(this.data.fieldValue=a);const s=null!==this.data.fieldValue&&"Off"!==this.data.fieldValue?this.data.fieldValue:"Yes",r=i.getKeys();if(0===r.length)r.push("Off",s);else if(1===r.length)"Off"===r[0]?r.push(s):r.unshift("Off");else if(r.includes(s)){r.length=0;r.push("Off",s)}else{const e=r.find((e=>"Off"!==e));r.length=0;r.push("Off",e)}r.includes(this.data.fieldValue)||(this.data.fieldValue="Off");this.data.exportValue=r[1];const n=i.get(this.data.exportValue);this.checkedAppearance=n instanceof BaseStream?n:null;const g=i.get("Off");this.uncheckedAppearance=g instanceof BaseStream?g:null;this.checkedAppearance?this._streams.push(this.checkedAppearance):this._getDefaultCheckedAppearance(e,"check");this.uncheckedAppearance&&this._streams.push(this.uncheckedAppearance);this._fallbackFontDict=this.fallbackFontDict;null===this.data.defaultFieldValue&&(this.data.defaultFieldValue="Off")}_processRadioButton(e){this.data.buttonValue=null;const t=e.dict.get("Parent");if(t instanceof Dict){this.parent=e.dict.getRaw("Parent");const i=t.get("V");i instanceof Name&&(this.data.fieldValue=this._decodeFormValue(i))}const i=e.dict.get("AP");if(!(i instanceof Dict))return;const a=i.get("N");if(!(a instanceof Dict))return;for(const e of a.getKeys())if("Off"!==e){this.data.buttonValue=this._decodeFormValue(e);break}const s=a.get(this.data.buttonValue);this.checkedAppearance=s instanceof BaseStream?s:null;const r=a.get("Off");this.uncheckedAppearance=r instanceof BaseStream?r:null;this.checkedAppearance?this._streams.push(this.checkedAppearance):this._getDefaultCheckedAppearance(e,"disc");this.uncheckedAppearance&&this._streams.push(this.uncheckedAppearance);this._fallbackFontDict=this.fallbackFontDict;null===this.data.defaultFieldValue&&(this.data.defaultFieldValue="Off")}_processPushButton(e){const{dict:t,annotationGlobals:i}=e;if(t.has("A")||t.has("AA")||this.data.alternativeText){this.data.isTooltipOnly=!t.has("A")&&!t.has("AA");Catalog.parseDestDictionary({destDict:t,resultObj:this.data,docBaseUrl:i.baseUrl,docAttachments:i.attachments})}else warn("Push buttons without action dictionaries are not supported")}getFieldObject(){let e,t="button";if(this.data.checkBox){t="checkbox";e=this.data.exportValue}else if(this.data.radioButton){t="radiobutton";e=this.data.buttonValue}return{id:this.data.id,value:this.data.fieldValue||"Off",defaultValue:this.data.defaultFieldValue,exportValues:e,editable:!this.data.readOnly,name:this.data.fieldName,rect:this.data.rect,hidden:this.data.hidden,actions:this.data.actions,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,type:t}}get fallbackFontDict(){const e=new Dict;e.set("BaseFont",Name.get("ZapfDingbats"));e.set("Type",Name.get("FallbackType"));e.set("Subtype",Name.get("FallbackType"));e.set("Encoding",Name.get("ZapfDingbatsEncoding"));return shadow(this,"fallbackFontDict",e)}}class ChoiceWidgetAnnotation extends WidgetAnnotation{constructor(e){super(e);const{dict:t,xref:i}=e;this.indices=t.getArray("I");this.hasIndices=Array.isArray(this.indices)&&this.indices.length>0;this.data.options=[];const a=getInheritableProperty({dict:t,key:"Opt"});if(Array.isArray(a))for(let e=0,t=a.length;e=0&&t0&&(this.data.options=this.data.fieldValue.map((e=>({exportValue:e,displayValue:e}))));this.data.combo=this.hasFieldFlag(oA);this.data.multiSelect=this.hasFieldFlag(cA);this._hasText=!0}getFieldObject(){const e=this.data.combo?"combobox":"listbox",t=this.data.fieldValue.length>0?this.data.fieldValue[0]:null;return{id:this.data.id,value:t,defaultValue:this.data.defaultFieldValue,editable:!this.data.readOnly,name:this.data.fieldName,rect:this.data.rect,numItems:this.data.fieldValue.length,multipleSelection:this.data.multiSelect,hidden:this.data.hidden,actions:this.data.actions,items:this.data.options,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,type:e}}amendSavedDict(e,t){if(!this.hasIndices)return;let i=e?.get(this.data.id)?.value;Array.isArray(i)||(i=[i]);const a=[],{options:s}=this.data;for(let e=0,t=0,r=s.length;ei){i=a;t=e}}[Q,E]=this._computeFontSize(e,c-4,t,l,-1)}const u=E*s,d=(u-E)/2,f=Math.floor(o/u);let p=0;if(h.length>0){const e=Math.min(...h),t=Math.max(...h);p=Math.max(0,t-f+1);p>e&&(p=e)}const m=Math.min(p+f+1,C),y=["/Tx BMC q",`1 1 ${c} ${o} re W n`];if(h.length){y.push("0.600006 0.756866 0.854904 rg");for(const e of h)p<=e&&ee.trimEnd()));const{coords:e,bbox:t,matrix:i}=FakeUnicodeFont.getFirstPositionInfo(this.rectangle,this.rotation,a);this.data.textPosition=this._transformPoint(e,t,i)}if(this._isOffscreenCanvasSupported){const s=e.dict.get("CA"),r=new FakeUnicodeFont(i,"sans-serif");this.appearance=r.createAppearance(this._contents.str,this.rectangle,this.rotation,a,t,s);this._streams.push(this.appearance)}else warn("FreeTextAnnotation: OffscreenCanvas is not supported, annotation may not render correctly.")}}get hasTextContent(){return this._hasAppearance}static createNewDict(e,t,{apRef:i,ap:a}){const{color:s,fontSize:r,oldAnnotation:n,rect:g,rotation:o,user:c,value:C}=e,h=n||new Dict(t);h.set("Type",Name.get("Annot"));h.set("Subtype",Name.get("FreeText"));if(n){h.set("M",`D:${getModificationDate()}`);h.delete("RC")}else h.set("CreationDate",`D:${getModificationDate()}`);h.set("Rect",g);const l=`/Helv ${r} Tf ${getPdfColor(s,!0)}`;h.set("DA",l);h.set("Contents",stringToAsciiOrUTF16BE(C));h.set("F",4);h.set("Border",[0,0,0]);h.set("Rotate",o);c&&h.set("T",stringToAsciiOrUTF16BE(c));if(i||a){const e=new Dict(t);h.set("AP",e);i?e.set("N",i):e.set("N",a)}return h}static async createNewAppearanceStream(e,t,i){const{baseFontRef:a,evaluator:r,task:n}=i,{color:g,fontSize:o,rect:c,rotation:C,value:h}=e,l=new Dict(t),Q=new Dict(t);if(a)Q.set("Helv",a);else{const e=new Dict(t);e.set("BaseFont",Name.get("Helvetica"));e.set("Type",Name.get("Font"));e.set("Subtype",Name.get("Type1"));e.set("Encoding",Name.get("WinAnsiEncoding"));Q.set("Helv",e)}l.set("Font",Q);const E=await WidgetAnnotation._getFontData(r,n,{fontName:"Helv",fontSize:o},l),[u,d,f,p]=c;let m=f-u,y=p-d;C%180!=0&&([m,y]=[y,m]);const w=h.split("\n"),D=o/1e3;let b=-1/0;const F=[];for(let e of w){const t=E.encodeString(e);if(t.length>1)return null;e=t.join("");F.push(e);let i=0;const a=E.charsToGlyphs(e);for(const e of a)i+=e.width*D;b=Math.max(b,i)}let S=1;b>m&&(S=m/b);let k=1;const R=s*o,N=1*o,G=R*w.length;G>y&&(k=y/G);const M=o*Math.min(S,k);let U,x,L;switch(C){case 0:L=[1,0,0,1];x=[c[0],c[1],m,y];U=[c[0],c[3]-N];break;case 90:L=[0,1,-1,0];x=[c[1],-c[2],m,y];U=[c[1],-c[0]-N];break;case 180:L=[-1,0,0,-1];x=[-c[2],-c[3],m,y];U=[-c[2],-c[1]-N];break;case 270:L=[0,-1,1,0];x=[-c[3],c[0],m,y];U=[-c[3],c[2]-N]}const H=["q",`${L.join(" ")} 0 0 cm`,`${x.join(" ")} re W n`,"BT",`${getPdfColor(g,!0)}`,`0 Tc /Helv ${numberToString(M)} Tf`];H.push(`${U.join(" ")} Td (${escapeString(F[0])}) Tj`);const J=numberToString(R);for(let e=1,t=F.length;e{e.push(`${a[0]} ${a[1]} m`,`${a[2]} ${a[3]} l`,"S");return[t[0]-o,t[2]+o,t[7]-o,t[3]+o]}})}}}class SquareAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:i}=e;this.data.annotationType=M;this.data.hasOwnCanvas=this.data.noRotate;this.data.noHTML=!1;if(!this.appearance){const e=this.color?getPdfColorArray(this.color):[0,0,0],a=t.get("CA"),s=getRgbColor(t.getArray("IC"),null),r=s?getPdfColorArray(s):null,n=r?a:null;if(0===this.borderStyle.width&&!r)return;this._setDefaultAppearance({xref:i,extra:`${this.borderStyle.width} w`,strokeColor:e,fillColor:r,strokeAlpha:a,fillAlpha:n,pointsCallback:(e,t)=>{const i=t[4]+this.borderStyle.width/2,a=t[5]+this.borderStyle.width/2,s=t[6]-t[4]-this.borderStyle.width,n=t[3]-t[7]-this.borderStyle.width;e.push(`${i} ${a} ${s} ${n} re`);r?e.push("B"):e.push("S");return[t[0],t[2],t[7],t[3]]}})}}}class CircleAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:i}=e;this.data.annotationType=U;if(!this.appearance){const e=this.color?getPdfColorArray(this.color):[0,0,0],a=t.get("CA"),s=getRgbColor(t.getArray("IC"),null),r=s?getPdfColorArray(s):null,n=r?a:null;if(0===this.borderStyle.width&&!r)return;const g=4/3*Math.tan(Math.PI/8);this._setDefaultAppearance({xref:i,extra:`${this.borderStyle.width} w`,strokeColor:e,fillColor:r,strokeAlpha:a,fillAlpha:n,pointsCallback:(e,t)=>{const i=t[0]+this.borderStyle.width/2,a=t[1]-this.borderStyle.width/2,s=t[6]-this.borderStyle.width/2,n=t[7]+this.borderStyle.width/2,o=i+(s-i)/2,c=a+(n-a)/2,C=(s-i)/2*g,h=(n-a)/2*g;e.push(`${o} ${n} m`,`${o+C} ${n} ${s} ${c+h} ${s} ${c} c`,`${s} ${c-h} ${o+C} ${a} ${o} ${a} c`,`${o-C} ${a} ${i} ${c-h} ${i} ${c} c`,`${i} ${c+h} ${o-C} ${n} ${o} ${n} c`,"h");r?e.push("B"):e.push("S");return[t[0],t[2],t[7],t[3]]}})}}}class PolylineAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:i}=e;this.data.annotationType=L;this.data.hasOwnCanvas=this.data.noRotate;this.data.noHTML=!1;this.data.vertices=null;if(!(this instanceof PolygonAnnotation)){this.setLineEndings(t.getArray("LE"));this.data.lineEndings=this.lineEndings}const a=t.getArray("Vertices");if(!isNumberArray(a,null))return;const s=this.data.vertices=Float32Array.from(a);if(!this.appearance){const e=this.color?getPdfColorArray(this.color):[0,0,0],a=t.get("CA"),r=this.borderStyle.width||1,n=2*r,g=[1/0,1/0,-1/0,-1/0];for(let e=0,t=s.length;e{for(let t=0,i=s.length;t{for(const t of this.data.inkLists){for(let i=0,a=t.length;ie/255)));Q.set("CA",n);const u=new Dict(t);Q.set("AP",u);i?u.set("N",i):u.set("N",a);return Q}static async createNewAppearanceStream(e,t,i){if(e.outlines)return this.createNewAppearanceStreamForHighlight(e,t,i);const{color:a,rect:s,paths:r,thickness:n,opacity:g}=e,o=[`${n} w 1 J 1 j`,`${getPdfColor(a,!1)}`];1!==g&&o.push("/R0 gs");for(const e of r.lines){o.push(`${numberToString(e[4])} ${numberToString(e[5])} m`);for(let t=6,i=e.length;t{e.push(`${t[0]} ${t[1]} m`,`${t[2]} ${t[3]} l`,`${t[6]} ${t[7]} l`,`${t[4]} ${t[5]} l`,"f");return[t[0],t[2],t[7],t[3]]}})}}else this.data.popupRef=null}static createNewDict(e,t,{apRef:i,ap:a}){const{color:s,oldAnnotation:r,opacity:n,rect:g,rotation:o,user:c,quadPoints:C}=e,h=r||new Dict(t);h.set("Type",Name.get("Annot"));h.set("Subtype",Name.get("Highlight"));h.set(r?"M":"CreationDate",`D:${getModificationDate()}`);h.set("CreationDate",`D:${getModificationDate()}`);h.set("Rect",g);h.set("F",4);h.set("Border",[0,0,0]);h.set("Rotate",o);h.set("QuadPoints",C);h.set("C",Array.from(s,(e=>e/255)));h.set("CA",n);c&&h.set("T",stringToAsciiOrUTF16BE(c));if(i||a){const e=new Dict(t);h.set("AP",e);e.set("N",i||a)}return h}static async createNewAppearanceStream(e,t,i){const{color:a,rect:s,outlines:r,opacity:n}=e,g=[`${getPdfColor(a,!0)}`,"/R0 gs"],o=[];for(const e of r){o.length=0;o.push(`${numberToString(e[0])} ${numberToString(e[1])} m`);for(let t=2,i=e.length;t{e.push(`${t[4]} ${t[5]+1.3} m`,`${t[6]} ${t[7]+1.3} l`,"S");return[t[0],t[2],t[7],t[3]]}})}}else this.data.popupRef=null}}class SquigglyAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:i}=e;this.data.annotationType=Y;if(this.data.quadPoints=getQuadPoints(t,null)){if(!this.appearance){const e=this.color?getPdfColorArray(this.color):[0,0,0],a=t.get("CA");this._setDefaultAppearance({xref:i,extra:"[] 0 d 1 w",strokeColor:e,strokeAlpha:a,pointsCallback:(e,t)=>{const i=(t[1]-t[5])/6;let a=i,s=t[4];const r=t[5],n=t[6];e.push(`${s} ${r+a} m`);do{s+=2;a=0===a?i:0;e.push(`${s} ${r+a} l`)}while(s{e.push((t[0]+t[4])/2+" "+(t[1]+t[5])/2+" m",(t[2]+t[6])/2+" "+(t[3]+t[7])/2+" l","S");return[t[0],t[2],t[7],t[3]]}})}}else this.data.popupRef=null}}class StampAnnotation extends MarkupAnnotation{#T;constructor(e){super(e);this.data.annotationType=K;this.#T=this.data.hasOwnCanvas=this.data.noRotate;this.data.isEditable=!this.data.noHTML;this.data.noHTML=!1}mustBeViewedWhenEditing(e,t=null){if(e){if(!this.data.isEditable)return!1;this.#T=this.data.hasOwnCanvas;this.data.hasOwnCanvas=!0;return!0}this.data.hasOwnCanvas=this.#T;return!t?.has(this.data.id)}static async createImage(e,t){const{width:i,height:a}=e,s=new OffscreenCanvas(i,a),r=s.getContext("2d",{alpha:!0});r.drawImage(e,0,0);const n=r.getImageData(0,0,i,a).data,g=new Uint32Array(n.buffer),o=g.some(FeatureTest.isLittleEndian?e=>e>>>24!=255:e=>!!(255&~e));if(o){r.fillStyle="white";r.fillRect(0,0,i,a);r.drawImage(e,0,0)}const c=s.convertToBlob({type:"image/jpeg",quality:1}).then((e=>e.arrayBuffer())),C=Name.get("XObject"),h=Name.get("Image"),l=new Dict(t);l.set("Type",C);l.set("Subtype",h);l.set("BitsPerComponent",8);l.set("ColorSpace",Name.get("DeviceRGB"));l.set("Filter",Name.get("DCTDecode"));l.set("BBox",[0,0,i,a]);l.set("Width",i);l.set("Height",a);let Q=null;if(o){const e=new Uint8Array(g.length);if(FeatureTest.isLittleEndian)for(let t=0,i=g.length;t>>24;else for(let t=0,i=g.length;t=0&&r<=1?r:null}}class DecryptStream extends DecodeStream{constructor(e,t,i){super(t);this.str=e;this.dict=e.dict;this.decrypt=i;this.nextChunk=null;this.initialized=!1}readBlock(){let e;if(this.initialized)e=this.nextChunk;else{e=this.str.getBytes(512);this.initialized=!0}if(!e?.length){this.eof=!0;return}this.nextChunk=this.str.getBytes(512);const t=this.nextChunk?.length>0;e=(0,this.decrypt)(e,!t);const i=this.bufferLength,a=i+e.length;this.ensureBuffer(a).set(e,i);this.bufferLength=a}}class ARCFourCipher{constructor(e){this.a=0;this.b=0;const t=new Uint8Array(256),i=e.length;for(let e=0;e<256;++e)t[e]=e;for(let a=0,s=0;a<256;++a){const r=t[a];s=s+r+e[a%i]&255;t[a]=t[s];t[s]=r}this.s=t}encryptBlock(e){let t=this.a,i=this.b;const a=this.s,s=e.length,r=new Uint8Array(s);for(let n=0;n>5&255;C[h++]=s>>13&255;C[h++]=s>>21&255;C[h++]=s>>>29&255;C[h++]=0;C[h++]=0;C[h++]=0;const E=new Int32Array(16);for(h=0;h>>32-g)|0;s=r}r=r+s|0;n=n+c|0;g=g+Q|0;o=o+u|0}return new Uint8Array([255&r,r>>8&255,r>>16&255,r>>>24&255,255&n,n>>8&255,n>>16&255,n>>>24&255,255&g,g>>8&255,g>>16&255,g>>>24&255,255&o,o>>8&255,o>>16&255,o>>>24&255])}}();class Word64{constructor(e,t){this.high=0|e;this.low=0|t}and(e){this.high&=e.high;this.low&=e.low}xor(e){this.high^=e.high;this.low^=e.low}or(e){this.high|=e.high;this.low|=e.low}shiftRight(e){if(e>=32){this.low=this.high>>>e-32|0;this.high=0}else{this.low=this.low>>>e|this.high<<32-e;this.high=this.high>>>e|0}}shiftLeft(e){if(e>=32){this.high=this.low<>>32-e;this.low<<=e}}rotateRight(e){let t,i;if(32&e){i=this.low;t=this.high}else{t=this.low;i=this.high}e&=31;this.low=t>>>e|i<<32-e;this.high=i>>>e|t<<32-e}not(){this.high=~this.high;this.low=~this.low}add(e){const t=(this.low>>>0)+(e.low>>>0);let i=(this.high>>>0)+(e.high>>>0);t>4294967295&&(i+=1);this.low=0|t;this.high=0|i}copyTo(e,t){e[t]=this.high>>>24&255;e[t+1]=this.high>>16&255;e[t+2]=this.high>>8&255;e[t+3]=255&this.high;e[t+4]=this.low>>>24&255;e[t+5]=this.low>>16&255;e[t+6]=this.low>>8&255;e[t+7]=255&this.low}assign(e){this.high=e.high;this.low=e.low}}const Ag=function calculateSHA256Closure(){function rotr(e,t){return e>>>t|e<<32-t}function ch(e,t,i){return e&t^~e&i}function maj(e,t,i){return e&t^e&i^t&i}function sigma(e){return rotr(e,2)^rotr(e,13)^rotr(e,22)}function sigmaPrime(e){return rotr(e,6)^rotr(e,11)^rotr(e,25)}function littleSigma(e){return rotr(e,7)^rotr(e,18)^e>>>3}const e=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];return function hash(t,i,a){let s=1779033703,r=3144134277,n=1013904242,g=2773480762,o=1359893119,c=2600822924,C=528734635,h=1541459225;const l=64*Math.ceil((a+9)/64),Q=new Uint8Array(l);let E,u;for(E=0;E>>29&255;Q[E++]=a>>21&255;Q[E++]=a>>13&255;Q[E++]=a>>5&255;Q[E++]=a<<3&255;const f=new Uint32Array(64);for(E=0;E>>10)+f[u-7]+littleSigma(f[u-15])+f[u-16]|0;let t,i,a=s,l=r,d=n,m=g,y=o,w=c,D=C,b=h;for(u=0;u<64;++u){t=b+sigmaPrime(y)+ch(y,w,D)+e[u]+f[u];i=sigma(a)+maj(a,l,d);b=D;D=w;w=y;y=m+t|0;m=d;d=l;l=a;a=t+i|0}s=s+a|0;r=r+l|0;n=n+d|0;g=g+m|0;o=o+y|0;c=c+w|0;C=C+D|0;h=h+b|0}var p;return new Uint8Array([s>>24&255,s>>16&255,s>>8&255,255&s,r>>24&255,r>>16&255,r>>8&255,255&r,n>>24&255,n>>16&255,n>>8&255,255&n,g>>24&255,g>>16&255,g>>8&255,255&g,o>>24&255,o>>16&255,o>>8&255,255&o,c>>24&255,c>>16&255,c>>8&255,255&c,C>>24&255,C>>16&255,C>>8&255,255&C,h>>24&255,h>>16&255,h>>8&255,255&h])}}(),eg=function calculateSHA512Closure(){function ch(e,t,i,a,s){e.assign(t);e.and(i);s.assign(t);s.not();s.and(a);e.xor(s)}function maj(e,t,i,a,s){e.assign(t);e.and(i);s.assign(t);s.and(a);e.xor(s);s.assign(i);s.and(a);e.xor(s)}function sigma(e,t,i){e.assign(t);e.rotateRight(28);i.assign(t);i.rotateRight(34);e.xor(i);i.assign(t);i.rotateRight(39);e.xor(i)}function sigmaPrime(e,t,i){e.assign(t);e.rotateRight(14);i.assign(t);i.rotateRight(18);e.xor(i);i.assign(t);i.rotateRight(41);e.xor(i)}function littleSigma(e,t,i){e.assign(t);e.rotateRight(1);i.assign(t);i.rotateRight(8);e.xor(i);i.assign(t);i.shiftRight(7);e.xor(i)}function littleSigmaPrime(e,t,i){e.assign(t);e.rotateRight(19);i.assign(t);i.rotateRight(61);e.xor(i);i.assign(t);i.shiftRight(6);e.xor(i)}const e=[new Word64(1116352408,3609767458),new Word64(1899447441,602891725),new Word64(3049323471,3964484399),new Word64(3921009573,2173295548),new Word64(961987163,4081628472),new Word64(1508970993,3053834265),new Word64(2453635748,2937671579),new Word64(2870763221,3664609560),new Word64(3624381080,2734883394),new Word64(310598401,1164996542),new Word64(607225278,1323610764),new Word64(1426881987,3590304994),new Word64(1925078388,4068182383),new Word64(2162078206,991336113),new Word64(2614888103,633803317),new Word64(3248222580,3479774868),new Word64(3835390401,2666613458),new Word64(4022224774,944711139),new Word64(264347078,2341262773),new Word64(604807628,2007800933),new Word64(770255983,1495990901),new Word64(1249150122,1856431235),new Word64(1555081692,3175218132),new Word64(1996064986,2198950837),new Word64(2554220882,3999719339),new Word64(2821834349,766784016),new Word64(2952996808,2566594879),new Word64(3210313671,3203337956),new Word64(3336571891,1034457026),new Word64(3584528711,2466948901),new Word64(113926993,3758326383),new Word64(338241895,168717936),new Word64(666307205,1188179964),new Word64(773529912,1546045734),new Word64(1294757372,1522805485),new Word64(1396182291,2643833823),new Word64(1695183700,2343527390),new Word64(1986661051,1014477480),new Word64(2177026350,1206759142),new Word64(2456956037,344077627),new Word64(2730485921,1290863460),new Word64(2820302411,3158454273),new Word64(3259730800,3505952657),new Word64(3345764771,106217008),new Word64(3516065817,3606008344),new Word64(3600352804,1432725776),new Word64(4094571909,1467031594),new Word64(275423344,851169720),new Word64(430227734,3100823752),new Word64(506948616,1363258195),new Word64(659060556,3750685593),new Word64(883997877,3785050280),new Word64(958139571,3318307427),new Word64(1322822218,3812723403),new Word64(1537002063,2003034995),new Word64(1747873779,3602036899),new Word64(1955562222,1575990012),new Word64(2024104815,1125592928),new Word64(2227730452,2716904306),new Word64(2361852424,442776044),new Word64(2428436474,593698344),new Word64(2756734187,3733110249),new Word64(3204031479,2999351573),new Word64(3329325298,3815920427),new Word64(3391569614,3928383900),new Word64(3515267271,566280711),new Word64(3940187606,3454069534),new Word64(4118630271,4000239992),new Word64(116418474,1914138554),new Word64(174292421,2731055270),new Word64(289380356,3203993006),new Word64(460393269,320620315),new Word64(685471733,587496836),new Word64(852142971,1086792851),new Word64(1017036298,365543100),new Word64(1126000580,2618297676),new Word64(1288033470,3409855158),new Word64(1501505948,4234509866),new Word64(1607167915,987167468),new Word64(1816402316,1246189591)];return function hash(t,i,a,s=!1){let r,n,g,o,c,C,h,l;if(s){r=new Word64(3418070365,3238371032);n=new Word64(1654270250,914150663);g=new Word64(2438529370,812702999);o=new Word64(355462360,4144912697);c=new Word64(1731405415,4290775857);C=new Word64(2394180231,1750603025);h=new Word64(3675008525,1694076839);l=new Word64(1203062813,3204075428)}else{r=new Word64(1779033703,4089235720);n=new Word64(3144134277,2227873595);g=new Word64(1013904242,4271175723);o=new Word64(2773480762,1595750129);c=new Word64(1359893119,2917565137);C=new Word64(2600822924,725511199);h=new Word64(528734635,4215389547);l=new Word64(1541459225,327033209)}const Q=128*Math.ceil((a+17)/128),E=new Uint8Array(Q);let u,d;for(u=0;u>>29&255;E[u++]=a>>21&255;E[u++]=a>>13&255;E[u++]=a>>5&255;E[u++]=a<<3&255;const p=new Array(80);for(u=0;u<80;u++)p[u]=new Word64(0,0);let m=new Word64(0,0),y=new Word64(0,0),w=new Word64(0,0),D=new Word64(0,0),b=new Word64(0,0),F=new Word64(0,0),S=new Word64(0,0),k=new Word64(0,0);const R=new Word64(0,0),N=new Word64(0,0),G=new Word64(0,0),M=new Word64(0,0);let U,x;for(u=0;u=1;--e){i=r[13];r[13]=r[9];r[9]=r[5];r[5]=r[1];r[1]=i;i=r[14];a=r[10];r[14]=r[6];r[10]=r[2];r[6]=i;r[2]=a;i=r[15];a=r[11];s=r[7];r[15]=r[3];r[11]=i;r[7]=a;r[3]=s;for(let e=0;e<16;++e)r[e]=this._inv_s[r[e]];for(let i=0,a=16*e;i<16;++i,++a)r[i]^=t[a];for(let e=0;e<16;e+=4){const t=this._mix[r[e]],a=this._mix[r[e+1]],s=this._mix[r[e+2]],n=this._mix[r[e+3]];i=t^a>>>8^a<<24^s>>>16^s<<16^n>>>24^n<<8;r[e]=i>>>24&255;r[e+1]=i>>16&255;r[e+2]=i>>8&255;r[e+3]=255&i}}i=r[13];r[13]=r[9];r[9]=r[5];r[5]=r[1];r[1]=i;i=r[14];a=r[10];r[14]=r[6];r[10]=r[2];r[6]=i;r[2]=a;i=r[15];a=r[11];s=r[7];r[15]=r[3];r[11]=i;r[7]=a;r[3]=s;for(let e=0;e<16;++e){r[e]=this._inv_s[r[e]];r[e]^=t[e]}return r}_encrypt(e,t){const i=this._s;let a,s,r;const n=new Uint8Array(16);n.set(e);for(let e=0;e<16;++e)n[e]^=t[e];for(let e=1;e=a;--i)if(e[i]!==t){t=0;break}g-=t;r[r.length-1]=e.subarray(0,16-t)}}const o=new Uint8Array(g);for(let e=0,t=0,i=r.length;e=256&&(g=255&(27^g))}for(let t=0;t<4;++t){i[e]=a^=i[e-32];e++;i[e]=s^=i[e-32];e++;i[e]=r^=i[e-32];e++;i[e]=n^=i[e-32];e++}}return i}}class PDF17{checkOwnerPassword(e,t,i,a){const s=new Uint8Array(e.length+56);s.set(e,0);s.set(t,e.length);s.set(i,e.length+t.length);return isArrayEqual(Ag(s,0,s.length),a)}checkUserPassword(e,t,i){const a=new Uint8Array(e.length+8);a.set(e,0);a.set(t,e.length);return isArrayEqual(Ag(a,0,a.length),i)}getOwnerKey(e,t,i,a){const s=new Uint8Array(e.length+56);s.set(e,0);s.set(t,e.length);s.set(i,e.length+t.length);const r=Ag(s,0,s.length);return new AES256Cipher(r).decryptBlock(a,!1,new Uint8Array(16))}getUserKey(e,t,i){const a=new Uint8Array(e.length+8);a.set(e,0);a.set(t,e.length);const s=Ag(a,0,a.length);return new AES256Cipher(s).decryptBlock(i,!1,new Uint8Array(16))}}class PDF20{_hash(e,t,i){let a=Ag(t,0,t.length).subarray(0,32),s=[0],r=0;for(;r<64||s.at(-1)>r-32;){const t=e.length+a.length+i.length,c=new Uint8Array(t);let C=0;c.set(e,C);C+=e.length;c.set(a,C);C+=a.length;c.set(i,C);const h=new Uint8Array(64*t);for(let e=0,i=0;e<64;e++,i+=t)h.set(c,i);s=new AES128Cipher(a.subarray(0,16)).encrypt(h,a.subarray(16,32));const l=s.slice(0,16).reduce(((e,t)=>e+t),0)%3;0===l?a=Ag(s,0,s.length):1===l?a=(n=s,g=0,o=s.length,eg(n,g,o,!0)):2===l&&(a=eg(s,0,s.length));r++}var n,g,o;return a.subarray(0,32)}checkOwnerPassword(e,t,i,a){const s=new Uint8Array(e.length+56);s.set(e,0);s.set(t,e.length);s.set(i,e.length+t.length);return isArrayEqual(this._hash(e,s,i),a)}checkUserPassword(e,t,i){const a=new Uint8Array(e.length+8);a.set(e,0);a.set(t,e.length);return isArrayEqual(this._hash(e,a,[]),i)}getOwnerKey(e,t,i,a){const s=new Uint8Array(e.length+56);s.set(e,0);s.set(t,e.length);s.set(i,e.length+t.length);const r=this._hash(e,s,i);return new AES256Cipher(r).decryptBlock(a,!1,new Uint8Array(16))}getUserKey(e,t,i){const a=new Uint8Array(e.length+8);a.set(e,0);a.set(t,e.length);const s=this._hash(e,a,[]);return new AES256Cipher(s).decryptBlock(i,!1,new Uint8Array(16))}}class CipherTransform{constructor(e,t){this.StringCipherConstructor=e;this.StreamCipherConstructor=t}createStream(e,t){const i=new this.StreamCipherConstructor;return new DecryptStream(e,t,(function cipherTransformDecryptStream(e,t){return i.decryptBlock(e,t)}))}decryptString(e){const t=new this.StringCipherConstructor;let i=stringToBytes(e);i=t.decryptBlock(i,!0);return bytesToString(i)}encryptString(e){const t=new this.StringCipherConstructor;if(t instanceof AESBaseCipher){const i=16-e.length%16;e+=String.fromCharCode(i).repeat(i);const a=new Uint8Array(16);if("undefined"!=typeof crypto)crypto.getRandomValues(a);else for(let e=0;e<16;e++)a[e]=Math.floor(256*Math.random());let s=stringToBytes(e);s=t.encrypt(s,a);const r=new Uint8Array(16+s.length);r.set(a);r.set(s,16);return bytesToString(r)}let i=stringToBytes(e);i=t.encrypt(i);return bytesToString(i)}}class CipherTransformFactory{static#q=new Uint8Array([40,191,78,94,78,117,138,65,100,0,78,86,255,250,1,8,46,46,0,182,208,104,62,128,47,12,169,254,100,83,105,122]);#O(e,t,i,a,s,r,n,g,o,c,C,h){if(t){const e=Math.min(127,t.length);t=t.subarray(0,e)}else t=[];const l=6===e?new PDF20:new PDF17;return l.checkUserPassword(t,g,n)?l.getUserKey(t,o,C):t.length&&l.checkOwnerPassword(t,a,r,i)?l.getOwnerKey(t,s,r,c):null}#P(e,t,i,a,s,r,n,g){const o=40+i.length+e.length,c=new Uint8Array(o);let C,h,l=0;if(t){h=Math.min(32,t.length);for(;l>8&255;c[l++]=s>>16&255;c[l++]=s>>>24&255;for(C=0,h=e.length;C=4&&!g){c[l++]=255;c[l++]=255;c[l++]=255;c[l++]=255}let Q=$n(c,0,l);const E=n>>3;if(r>=3)for(C=0;C<50;++C)Q=$n(Q,0,E);const u=Q.subarray(0,E);let d,f;if(r>=3){for(l=0;l<32;++l)c[l]=CipherTransformFactory.#q[l];for(C=0,h=e.length;C>3;if(i>=3)for(g=0;g<50;++g)o=$n(o,0,o.length);let C,h;if(i>=3){h=t;const e=new Uint8Array(c);for(g=19;g>=0;g--){for(let t=0;t>8&255;s[n++]=e>>16&255;s[n++]=255&t;s[n++]=t>>8&255;if(a){s[n++]=115;s[n++]=65;s[n++]=108;s[n++]=84}return $n(s,0,n).subarray(0,Math.min(i.length+5,16))}#X(e,t,i,a,s){if(!(t instanceof Name))throw new FormatError("Invalid crypt filter name.");const r=this,n=e.get(t.name),g=n?.get("CFM");if(!g||"None"===g.name)return function(){return new NullCipher};if("V2"===g.name)return function(){return new ARCFourCipher(r.#j(i,a,s,!1))};if("AESV2"===g.name)return function(){return new AES128Cipher(r.#j(i,a,s,!0))};if("AESV3"===g.name)return function(){return new AES256Cipher(s)};throw new FormatError("Unknown crypto method")}constructor(e,t,i){const a=e.get("Filter");if(!isName(a,"Standard"))throw new FormatError("unknown encryption method");this.filterName=a.name;this.dict=e;const s=e.get("V");if(!Number.isInteger(s)||1!==s&&2!==s&&4!==s&&5!==s)throw new FormatError("unsupported encryption algorithm");this.algorithm=s;let r=e.get("Length");if(!r)if(s<=3)r=40;else{const t=e.get("CF"),i=e.get("StmF");if(t instanceof Dict&&i instanceof Name){t.suppressEncryption=!0;const e=t.get(i.name);r=e?.get("Length")||128;r<40&&(r<<=3)}}if(!Number.isInteger(r)||r<40||r%8!=0)throw new FormatError("invalid key length");const n=stringToBytes(e.get("O")),g=stringToBytes(e.get("U")),o=n.subarray(0,32),c=g.subarray(0,32),C=e.get("P"),h=e.get("R"),l=(4===s||5===s)&&!1!==e.get("EncryptMetadata");this.encryptMetadata=l;const Q=stringToBytes(t);let E,u;if(i){if(6===h)try{i=utf8StringToString(i)}catch{warn("CipherTransformFactory: Unable to convert UTF8 encoded password.")}E=stringToBytes(i)}if(5!==s)u=this.#P(Q,E,o,c,C,h,r,l);else{const t=n.subarray(32,40),i=n.subarray(40,48),a=g.subarray(0,48),s=g.subarray(32,40),r=g.subarray(40,48),C=stringToBytes(e.get("OE")),l=stringToBytes(e.get("UE")),Q=stringToBytes(e.get("Perms"));u=this.#O(h,E,o,t,i,a,c,s,r,C,l,Q)}if(!u&&!i)throw new PasswordException("No password given",rt);if(!u&&i){const e=this.#W(E,o,h,r);u=this.#P(Q,e,o,c,C,h,r,l)}if(!u)throw new PasswordException("Incorrect Password",nt);this.encryptionKey=u;if(s>=4){const t=e.get("CF");t instanceof Dict&&(t.suppressEncryption=!0);this.cf=t;this.stmf=e.get("StmF")||Name.get("Identity");this.strf=e.get("StrF")||Name.get("Identity");this.eff=e.get("EFF")||this.stmf}}createCipherTransform(e,t){if(4===this.algorithm||5===this.algorithm)return new CipherTransform(this.#X(this.cf,this.strf,e,t,this.encryptionKey),this.#X(this.cf,this.stmf,e,t,this.encryptionKey));const i=this.#j(e,t,this.encryptionKey,!1),cipherConstructor=function(){return new ARCFourCipher(i)};return new CipherTransform(cipherConstructor,cipherConstructor)}}function decodeString(e){try{return stringToUTF8String(e)}catch(t){warn(`UTF-8 decoding failed: "${t}".`);return e}}class DatasetXMLParser extends SimpleXMLParser{constructor(e){super(e);this.node=null}onEndElement(e){const t=super.onEndElement(e);if(t&&"xfa:datasets"===e){this.node=t;throw new Error("Aborting DatasetXMLParser.")}}}class DatasetReader{constructor(e){if(e.datasets)this.node=new SimpleXMLParser({hasAttributes:!0}).parseFromString(e.datasets).documentElement;else{const t=new DatasetXMLParser({hasAttributes:!0});try{t.parseFromString(e["xdp:xdp"])}catch{}this.node=t.node}}getValue(e){if(!this.node||!e)return"";const t=this.node.searchNode(parseXFAPath(e),0);if(!t)return"";const i=t.firstChild;return"value"===i?.nodeName?t.children.map((e=>decodeString(e.textContent))):decodeString(t.textContent)}}class XRef{#Z=null;constructor(e,t){this.stream=e;this.pdfManager=t;this.entries=[];this._xrefStms=new Set;this._cacheMap=new Map;this._pendingRefs=new RefSet;this._newPersistentRefNum=null;this._newTemporaryRefNum=null;this._persistentRefsCache=null}getNewPersistentRef(e){null===this._newPersistentRefNum&&(this._newPersistentRefNum=this.entries.length||1);const t=this._newPersistentRefNum++;this._cacheMap.set(t,e);return Ref.get(t,0)}getNewTemporaryRef(){if(null===this._newTemporaryRefNum){this._newTemporaryRefNum=this.entries.length||1;if(this._newPersistentRefNum){this._persistentRefsCache=new Map;for(let e=this._newTemporaryRefNum;e0;){const[n,g]=r;if(!Number.isInteger(n)||!Number.isInteger(g))throw new FormatError(`Invalid XRef range fields: ${n}, ${g}`);if(!Number.isInteger(i)||!Number.isInteger(a)||!Number.isInteger(s))throw new FormatError(`Invalid XRef entry fields length: ${n}, ${g}`);for(let r=t.entryNum;r=e.length);){i+=String.fromCharCode(a);a=e[t]}return i}function skipUntil(e,t,i){const a=i.length,s=e.length;let r=0;for(;t=a)break;t++;r++}return r}const e=/\b(endobj|\d+\s+\d+\s+obj|xref|trailer\s*<<)\b/g,t=/\b(startxref|\d+\s+\d+\s+obj)\b/g,i=/^(\d+)\s+(\d+)\s+obj\b/,a=new Uint8Array([116,114,97,105,108,101,114]),s=new Uint8Array([115,116,97,114,116,120,114,101,102]),r=new Uint8Array([47,88,82,101,102]);this.entries.length=0;this._cacheMap.clear();const n=this.stream;n.pos=0;const g=n.getBytes(),o=bytesToString(g),c=g.length;let C=n.start;const h=[],l=[];for(;C=c)break;Q=g[C]}while(10!==Q&&13!==Q);continue}const E=readToken(g,C);let u;if(E.startsWith("xref")&&(4===E.length||/\s/.test(E[4]))){C+=skipUntil(g,C,a);h.push(C);C+=skipUntil(g,C,s)}else if(u=i.exec(E)){const t=0|u[1],i=0|u[2],a=C+E.length;let s,h=!1;if(this.entries[t]){if(this.entries[t].gen===i)try{new Parser({lexer:new Lexer(n.makeSubStream(a))}).getObj();h=!0}catch(e){e instanceof ParserEOFException?warn(`indexObjects -- checking object (${E}): "${e}".`):h=!0}}else h=!0;h&&(this.entries[t]={offset:C-n.start,gen:i,uncompressed:!0});e.lastIndex=a;const Q=e.exec(o);if(Q){s=e.lastIndex+1-C;if("endobj"!==Q[1]){warn(`indexObjects: Found "${Q[1]}" inside of another "obj", caused by missing "endobj" -- trying to recover.`);s-=Q[1].length+1}}else s=c-C;const d=g.subarray(C,C+s),f=skipUntil(d,0,r);if(f0?Math.max(...this._xrefStms):null)}getEntry(e){const t=this.entries[e];return t&&!t.free&&t.offset?t:null}fetchIfRef(e,t=!1){return e instanceof Ref?this.fetch(e,t):e}fetch(e,t=!1){if(!(e instanceof Ref))throw new Error("ref object is not a reference");const i=e.num,a=this._cacheMap.get(i);if(void 0!==a){a instanceof Dict&&!a.objId&&(a.objId=e.toString());return a}let s=this.getEntry(i);if(null===s){this._cacheMap.set(i,s);return s}if(this._pendingRefs.has(e)){this._pendingRefs.remove(e);warn(`Ignoring circular reference: ${e}.`);return lt}this._pendingRefs.put(e);try{s=s.uncompressed?this.fetchUncompressed(e,s,t):this.fetchCompressed(e,s,t);this._pendingRefs.remove(e)}catch(t){this._pendingRefs.remove(e);throw t}s instanceof Dict?s.objId=e.toString():s instanceof BaseStream&&(s.dict.objId=e.toString());return s}fetchUncompressed(e,t,i=!1){const a=e.gen;let s=e.num;if(t.gen!==a){const r=`Inconsistent generation in XRef: ${e}`;if(this._generationFallback&&t.gen0&&t[3]-t[1]>0)return t;warn(`Empty, or invalid, /${e} entry.`)}return null}get mediaBox(){return shadow(this,"mediaBox",this._getBoundingBox("MediaBox")||tg)}get cropBox(){return shadow(this,"cropBox",this._getBoundingBox("CropBox")||this.mediaBox)}get userUnit(){const e=this.pageDict.get("UserUnit");return shadow(this,"userUnit","number"==typeof e&&e>0?e:1)}get view(){const{cropBox:e,mediaBox:t}=this;if(e!==t&&!isArrayEqual(e,t)){const i=Util.intersect(e,t);if(i&&i[2]-i[0]>0&&i[3]-i[1]>0)return shadow(this,"view",i);warn("Empty /CropBox and /MediaBox intersection.")}return shadow(this,"view",t)}get rotate(){let e=this._getInheritableProperty("Rotate")||0;e%90!=0?e=0:e>=360?e%=360:e<0&&(e=(e%360+360)%360);return shadow(this,"rotate",e)}_onSubStreamError(e,t){if(!this.evaluatorOptions.ignoreErrors)throw e;warn(`getContentStream - ignoring sub-stream (${t}): "${e}".`)}getContentStream(){return this.pdfManager.ensure(this,"content").then((e=>e instanceof BaseStream?e:Array.isArray(e)?new StreamsSequenceStream(e,this._onSubStreamError.bind(this)):new NullStream))}get xfaData(){return shadow(this,"xfaData",this.xfaFactory?{bbox:this.xfaFactory.getBoundingBox(this.pageIndex)}:null)}async#V(e,t,i){const a=[];for(const s of e)if(s.id){const e=Ref.fromString(s.id);if(!e){warn(`A non-linked annotation cannot be modified: ${s.id}`);continue}if(s.deleted){t.put(e,e);if(s.popupRef){const e=Ref.fromString(s.popupRef);e&&t.put(e,e)}continue}i?.put(e);s.ref=e;a.push(this.xref.fetchAsync(e).then((e=>{e instanceof Dict&&(s.oldAnnotation=e.clone())}),(()=>{warn(`Cannot fetch \`oldAnnotation\` for: ${e}.`)})));delete s.id}await Promise.all(a)}async saveNewAnnotations(e,t,i,a,s){if(this.xfaFactory)throw new Error("XFA: Cannot save new annotations.");const r=new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions}),n=new RefSetCache,g=new RefSet;await this.#V(i,n,g);const o=this.pageDict,c=this.annotations.filter((e=>!(e instanceof Ref&&n.has(e)))),C=await AnnotationFactory.saveNewAnnotations(r,t,i,a,s);for(const{ref:e}of C.annotations)e instanceof Ref&&!g.has(e)&&c.push(e);const h=o.clone();h.set("Annots",c);s.put(this.ref,{data:h});for(const e of n)s.put(e,{data:null})}save(e,t,i,a){const s=new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions});return this._parsedAnnotations.then((function(e){const r=[];for(const n of e)r.push(n.save(s,t,i,a).catch((function(e){warn(`save - ignoring annotation data during "${t.name}" task: "${e}".`);return null})));return Promise.all(r)}))}loadResources(e){this.resourcesPromise||=this.pdfManager.ensure(this,"resources");return this.resourcesPromise.then((()=>new ObjectLoader(this.resources,e,this.xref).load()))}getOperatorList({handler:e,sink:t,task:i,intent:a,cacheKey:s,annotationStorage:r=null,modifiedIds:n=null}){const C=this.getContentStream(),E=this.loadResources(["ColorSpace","ExtGState","Font","Pattern","Properties","Shading","XObject"]),d=new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions}),f=this.xfaFactory?null:getNewAnnotationsMap(r),p=f?.get(this.pageIndex);let m=Promise.resolve(null),y=null;if(p){const e=this.pdfManager.ensureDoc("annotationGlobals");let t;const a=new Set;for(const{bitmapId:e,bitmap:t}of p)!e||t||a.has(e)||a.add(e);const{isOffscreenCanvasSupported:s}=this.evaluatorOptions;if(a.size>0){const e=p.slice();for(const[t,i]of r)t.startsWith(u)&&i.bitmap&&a.has(i.bitmapId)&&e.push(i);t=AnnotationFactory.generateImages(e,this.xref,s)}else t=AnnotationFactory.generateImages(p,this.xref,s);y=new RefSet;m=Promise.all([e,this.#V(p,y,null)]).then((([e])=>e?AnnotationFactory.printNewAnnotations(e,d,i,p,t):null))}const w=Promise.all([C,E]).then((([r])=>{const n=new OperatorList(a,t);e.send("StartRenderPage",{transparency:d.hasBlendModes(this.resources,this.nonBlendModesSet),pageIndex:this.pageIndex,cacheKey:s});return d.getOperatorList({stream:r,task:i,resources:this.resources,operatorList:n}).then((function(){return n}))}));return Promise.all([w,this._parsedAnnotations,m]).then((function([e,t,s]){if(s){t=t.filter((e=>!(e.ref&&y.has(e.ref))));for(let e=0,i=s.length;ee.ref&&isRefsEqual(e.ref,a.refToReplace)));if(r>=0){t.splice(r,1,a);s.splice(e--,1);i--}}}t=t.concat(s)}if(0===t.length||a&l){e.flush(!0);return{length:e.totalLength}}const C=!!(a&h),E=!!(a&Q),u=!!(a&g),f=!!(a&o),p=!!(a&c),m=[];for(const e of t)(u||f&&e.mustBeViewed(r,C)&&e.mustBeViewedWhenEditing(E,n)||p&&e.mustBePrinted(r))&&m.push(e.getOperatorList(d,i,a,r).catch((function(e){warn(`getOperatorList - ignoring annotation data during "${i.name}" task: "${e}".`);return{opList:null,separateForm:!1,separateCanvas:!1}})));return Promise.all(m).then((function(t){let i=!1,a=!1;for(const{opList:s,separateForm:r,separateCanvas:n}of t){e.addOpList(s);i||=r;a||=n}e.flush(!0,{form:i,canvas:a});return{length:e.totalLength}}))}))}async extractTextContent({handler:e,task:t,includeMarkedContent:i,disableNormalization:a,sink:s}){const r=this.getContentStream(),n=this.loadResources(["ExtGState","Font","Properties","XObject"]),g=this.pdfManager.ensureCatalog("lang"),[o,,c]=await Promise.all([r,n,g]);return new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions}).getTextContent({stream:o,task:t,resources:this.resources,includeMarkedContent:i,disableNormalization:a,sink:s,viewBox:this.view,lang:c})}async getStructTree(){const e=await this.pdfManager.ensureCatalog("structTreeRoot");if(!e)return null;await this._parsedAnnotations;const t=await this.pdfManager.ensure(this,"_parseStructTree",[e]);return this.pdfManager.ensure(t,"serializable")}_parseStructTree(e){const t=new StructTreePage(e,this.pageDict);t.parse(this.ref);return t}async getAnnotationsData(e,t,i){const a=await this._parsedAnnotations;if(0===a.length)return a;const s=[],r=[];let n;const C=!!(i&g),h=!!(i&o),l=!!(i&c);for(const i of a){const a=C||h&&i.viewable;(a||l&&i.printable)&&s.push(i.data);if(i.hasTextContent&&a){n||=new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions});r.push(i.extractTextContent(n,t,[-1/0,-1/0,1/0,1/0]).catch((function(e){warn(`getAnnotationsData - ignoring textContent during "${t.name}" task: "${e}".`)})))}}await Promise.all(r);return s}get annotations(){const e=this._getInheritableProperty("Annots");return shadow(this,"annotations",Array.isArray(e)?e:[])}get _parsedAnnotations(){return shadow(this,"_parsedAnnotations",this.pdfManager.ensure(this,"annotations").then((async e=>{if(0===e.length)return e;const[t,i]=await Promise.all([this.pdfManager.ensureDoc("annotationGlobals"),this.pdfManager.ensureDoc("fieldObjects")]);if(!t)return[];const a=i?.orphanFields,s=[];for(const i of e)s.push(AnnotationFactory.create(this.xref,i,t,this._localIdFactory,!1,a,this.ref).catch((function(e){warn(`_parsedAnnotations: "${e}".`);return null})));const r=[];let n,g;for(const e of await Promise.all(s))e&&(e instanceof WidgetAnnotation?(g||=[]).push(e):e instanceof PopupAnnotation?(n||=[]).push(e):r.push(e));g&&r.push(...g);n&&r.push(...n);return r})))}get jsActions(){return shadow(this,"jsActions",collectActions(this.xref,this.pageDict,pA))}}const ig=new Uint8Array([37,80,68,70,45]),ag=new Uint8Array([115,116,97,114,116,120,114,101,102]),sg=new Uint8Array([101,110,100,111,98,106]);function find(e,t,i=1024,a=!1){const s=t.length,r=e.peekBytes(i),n=r.length-s;if(n<=0)return!1;if(a){const i=s-1;let a=r.length-1;for(;a>=i;){let n=0;for(;n=s){e.pos+=a-i;return!0}a--}}else{let i=0;for(;i<=n;){let a=0;for(;a=s){e.pos+=i;return!0}i++}}return!1}class PDFDocument{constructor(e,t){if(t.length<=0)throw new InvalidPDFException("The PDF file is empty, i.e. its size is zero bytes.");this.pdfManager=e;this.stream=t;this.xref=new XRef(t,e);this._pagePromises=new Map;this._version=null;const i={font:0};this._globalIdFactory=class{static getDocId(){return`g_${e.docId}`}static createFontId(){return"f"+ ++i.font}static createObjId(){unreachable("Abstract method `createObjId` called.")}static getPageObjId(){unreachable("Abstract method `getPageObjId` called.")}}}parse(e){this.xref.parse(e);this.catalog=new Catalog(this.pdfManager,this.xref)}get linearization(){let e=null;try{e=Linearization.create(this.stream)}catch(e){if(e instanceof MissingDataException)throw e;info(e)}return shadow(this,"linearization",e)}get startXRef(){const e=this.stream;let t=0;if(this.linearization){e.reset();if(find(e,sg)){e.skip(6);let i=e.peekByte();for(;isWhiteSpace(i);){e.pos++;i=e.peekByte()}t=e.pos-e.start}}else{const i=1024,a=ag.length;let s=!1,r=e.end;for(;!s&&r>0;){r-=i-a;r<0&&(r=0);e.pos=r;s=find(e,ag,i,!0)}if(s){e.skip(9);let i;do{i=e.getByte()}while(isWhiteSpace(i));let a="";for(;i>=32&&i<=57;){a+=String.fromCharCode(i);i=e.getByte()}t=parseInt(a,10);isNaN(t)&&(t=0)}}return shadow(this,"startXRef",t)}checkHeader(){const e=this.stream;e.reset();if(!find(e,ig))return;e.moveStart();e.skip(ig.length);let t,i="";for(;(t=e.getByte())>32&&i.length<7;)i+=String.fromCharCode(t);ft.test(i)?this._version=i:warn(`Invalid PDF header version: ${i}`)}parseStartXRef(){this.xref.setStartXRef(this.startXRef)}get numPages(){let e=0;e=this.catalog.hasActualNumPages?this.catalog.numPages:this.xfaFactory?this.xfaFactory.getNumPages():this.linearization?this.linearization.numPages:this.catalog.numPages;return shadow(this,"numPages",e)}_hasOnlyDocumentSignatures(e,t=0){return!!Array.isArray(e)&&e.every((e=>{if(!((e=this.xref.fetchIfRef(e))instanceof Dict))return!1;if(e.has("Kids")){if(++t>10){warn("_hasOnlyDocumentSignatures: maximum recursion depth reached");return!1}return this._hasOnlyDocumentSignatures(e.get("Kids"),t)}const i=isName(e.get("FT"),"Sig"),a=e.get("Rect"),s=Array.isArray(a)&&a.every((e=>0===e));return i&&s}))}get _xfaStreams(){const e=this.catalog.acroForm;if(!e)return null;const t=e.get("XFA"),i={"xdp:xdp":"",template:"",datasets:"",config:"",connectionSet:"",localeSet:"",stylesheet:"","/xdp:xdp":""};if(t instanceof BaseStream&&!t.isEmpty){i["xdp:xdp"]=t;return i}if(!Array.isArray(t)||0===t.length)return null;for(let e=0,a=t.length;e0;e.hasFields=a;const s=t.get("XFA");e.hasXfa=Array.isArray(s)&&s.length>0||s instanceof BaseStream&&!s.isEmpty;const r=!!(1&t.get("SigFlags")),n=r&&this._hasOnlyDocumentSignatures(i);e.hasAcroForm=a&&!n;e.hasSignatures=r}catch(e){if(e instanceof MissingDataException)throw e;warn(`Cannot fetch form information: "${e}".`)}return shadow(this,"formInfo",e)}get documentInfo(){const e={PDFFormatVersion:this.version,Language:this.catalog.lang,EncryptFilterName:this.xref.encrypt?this.xref.encrypt.filterName:null,IsLinearized:!!this.linearization,IsAcroFormPresent:this.formInfo.hasAcroForm,IsXFAPresent:this.formInfo.hasXfa,IsCollectionPresent:!!this.catalog.collection,IsSignaturesPresent:this.formInfo.hasSignatures};let t;try{t=this.xref.trailer.get("Info")}catch(e){if(e instanceof MissingDataException)throw e;info("The document information dictionary is invalid.")}if(!(t instanceof Dict))return shadow(this,"documentInfo",e);for(const i of t.getKeys()){const a=t.get(i);switch(i){case"Title":case"Author":case"Subject":case"Keywords":case"Creator":case"Producer":case"CreationDate":case"ModDate":if("string"==typeof a){e[i]=stringToPDFString(a);continue}break;case"Trapped":if(a instanceof Name){e[i]=a;continue}break;default:let t;switch(typeof a){case"string":t=stringToPDFString(a);break;case"number":case"boolean":t=a;break;default:a instanceof Name&&(t=a)}if(void 0===t){warn(`Bad value, for custom key "${i}", in Info: ${a}.`);continue}e.Custom||(e.Custom=Object.create(null));e.Custom[i]=t;continue}warn(`Bad value, for key "${i}", in Info: ${a}.`)}return shadow(this,"documentInfo",e)}get fingerprints(){const e="\0".repeat(16);function validate(t){return"string"==typeof t&&16===t.length&&t!==e}const t=this.xref.trailer.get("ID");let i,a;if(Array.isArray(t)&&validate(t[0])){i=stringToBytes(t[0]);t[1]!==t[0]&&validate(t[1])&&(a=stringToBytes(t[1]))}else i=$n(this.stream.getByteRange(0,1024),0,1024);return shadow(this,"fingerprints",[toHexUtil(i),a?toHexUtil(a):null])}async _getLinearizationPage(e){const{catalog:t,linearization:i,xref:a}=this,s=Ref.get(i.objectNumberFirst,0);try{const e=await a.fetchAsync(s);if(e instanceof Dict){let i=e.getRaw("Type");i instanceof Ref&&(i=await a.fetchAsync(i));if(isName(i,"Page")||!e.has("Type")&&!e.has("Kids")&&e.has("Contents")){t.pageKidsCountCache.has(s)||t.pageKidsCountCache.put(s,1);t.pageIndexCache.has(s)||t.pageIndexCache.put(s,0);return[e,s]}}throw new FormatError("The Linearization dictionary doesn't point to a valid Page dictionary.")}catch(i){warn(`_getLinearizationPage: "${i.message}".`);return t.getPageDict(e)}}getPage(e){const t=this._pagePromises.get(e);if(t)return t;const{catalog:i,linearization:a,xfaFactory:s}=this;let r;r=s?Promise.resolve([Dict.empty,null]):a?.pageFirst===e?this._getLinearizationPage(e):i.getPageDict(e);r=r.then((([t,a])=>new Page({pdfManager:this.pdfManager,xref:this.xref,pageIndex:e,pageDict:t,ref:a,globalIdFactory:this._globalIdFactory,fontCache:i.fontCache,builtInCMapCache:i.builtInCMapCache,standardFontDataCache:i.standardFontDataCache,globalImageCache:i.globalImageCache,systemFontCache:i.systemFontCache,nonBlendModesSet:i.nonBlendModesSet,xfaFactory:s})));this._pagePromises.set(e,r);return r}async checkFirstPage(e=!1){if(!e)try{await this.getPage(0)}catch(e){if(e instanceof XRefEntryException){this._pagePromises.delete(0);await this.cleanup();throw new XRefParseException}}}async checkLastPage(e=!1){const{catalog:t,pdfManager:i}=this;t.setActualNumPages();let a;try{await Promise.all([i.ensureDoc("xfaFactory"),i.ensureDoc("linearization"),i.ensureCatalog("numPages")]);if(this.xfaFactory)return;a=this.linearization?this.linearization.numPages:t.numPages;if(!Number.isInteger(a))throw new FormatError("Page count is not an integer.");if(a<=1)return;await this.getPage(a-1)}catch(s){this._pagePromises.delete(a-1);await this.cleanup();if(s instanceof XRefEntryException&&!e)throw new XRefParseException;warn(`checkLastPage - invalid /Pages tree /Count: ${a}.`);let r;try{r=await t.getAllPageDicts(e)}catch(i){if(i instanceof XRefEntryException&&!e)throw new XRefParseException;t.setActualNumPages(1);return}for(const[e,[a,s]]of r){let r;if(a instanceof Error){r=Promise.reject(a);r.catch((()=>{}))}else r=Promise.resolve(new Page({pdfManager:i,xref:this.xref,pageIndex:e,pageDict:a,ref:s,globalIdFactory:this._globalIdFactory,fontCache:t.fontCache,builtInCMapCache:t.builtInCMapCache,standardFontDataCache:t.standardFontDataCache,globalImageCache:t.globalImageCache,systemFontCache:t.systemFontCache,nonBlendModesSet:t.nonBlendModesSet,xfaFactory:null}));this._pagePromises.set(e,r)}t.setActualNumPages(r.size)}}fontFallback(e,t){return this.catalog.fontFallback(e,t)}async cleanup(e=!1){return this.catalog?this.catalog.cleanup(e):clearGlobalCaches()}async#z(e,t,i,a,s,r,n){const{xref:g}=this;if(!(i instanceof Ref)||r.has(i))return;r.put(i);const o=await g.fetchAsync(i);if(!(o instanceof Dict))return;if(o.has("T")){const t=stringToPDFString(await o.getAsync("T"));e=""===e?t:`${e}.${t}`}else{let i=o;for(;;){i=i.getRaw("Parent")||t;if(i instanceof Ref){if(r.has(i))break;i=await g.fetchAsync(i)}if(!(i instanceof Dict))break;if(i.has("T")){const t=stringToPDFString(await i.getAsync("T"));e=""===e?t:`${e}.${t}`;break}}}t&&!o.has("Parent")&&isName(o.get("Subtype"),"Widget")&&n.put(i,t);a.has(e)||a.set(e,[]);a.get(e).push(AnnotationFactory.create(g,i,s,null,!0,n,null).then((e=>e?.getFieldObject())).catch((function(e){warn(`#collectFieldObjects: "${e}".`);return null})));if(!o.has("Kids"))return;const c=await o.getAsync("Kids");if(Array.isArray(c))for(const t of c)await this.#z(e,i,t,a,s,r,n)}get fieldObjects(){return shadow(this,"fieldObjects",this.pdfManager.ensureDoc("formInfo").then((async e=>{if(!e.hasFields)return null;const[t,i]=await Promise.all([this.pdfManager.ensureDoc("annotationGlobals"),this.pdfManager.ensureCatalog("acroForm")]);if(!t)return null;const a=new RefSet,s=Object.create(null),r=new Map,n=new RefSetCache;for(const e of await i.getAsync("Fields"))await this.#z("",null,e,r,t,a,n);const g=[];for(const[e,t]of r)g.push(Promise.all(t).then((t=>{(t=t.filter((e=>!!e))).length>0&&(s[e]=t)})));await Promise.all(g);return{allFields:s,orphanFields:n}})))}get hasJSActions(){return shadow(this,"hasJSActions",this.pdfManager.ensureDoc("_parseHasJSActions"))}async _parseHasJSActions(){const[e,t]=await Promise.all([this.pdfManager.ensureCatalog("jsActions"),this.pdfManager.ensureDoc("fieldObjects")]);return!!e||!!t&&Object.values(t.allFields).some((e=>e.some((e=>null!==e.actions))))}get calculationOrderIds(){const e=this.catalog.acroForm?.get("CO");if(!Array.isArray(e)||0===e.length)return shadow(this,"calculationOrderIds",null);const t=[];for(const i of e)i instanceof Ref&&t.push(i.toString());return shadow(this,"calculationOrderIds",t.length?t:null)}get annotationGlobals(){return shadow(this,"annotationGlobals",AnnotationFactory.createGlobals(this.pdfManager))}}class BasePdfManager{constructor(e){this._docBaseUrl=function parseDocBaseUrl(e){if(e){const t=createValidAbsoluteUrl(e);if(t)return t.href;warn(`Invalid absolute docBaseUrl: "${e}".`)}return null}(e.docBaseUrl);this._docId=e.docId;this._password=e.password;this.enableXfa=e.enableXfa;e.evaluatorOptions.isOffscreenCanvasSupported&&=FeatureTest.isOffscreenCanvasSupported;e.evaluatorOptions.isImageDecoderSupported&&=FeatureTest.isImageDecoderSupported;this.evaluatorOptions=Object.freeze(e.evaluatorOptions)}get docId(){return this._docId}get password(){return this._password}get docBaseUrl(){return this._docBaseUrl}get catalog(){return this.pdfDocument.catalog}ensureDoc(e,t){return this.ensure(this.pdfDocument,e,t)}ensureXRef(e,t){return this.ensure(this.pdfDocument.xref,e,t)}ensureCatalog(e,t){return this.ensure(this.pdfDocument.catalog,e,t)}getPage(e){return this.pdfDocument.getPage(e)}fontFallback(e,t){return this.pdfDocument.fontFallback(e,t)}loadXfaFonts(e,t){return this.pdfDocument.loadXfaFonts(e,t)}loadXfaImages(){return this.pdfDocument.loadXfaImages()}serializeXfaData(e){return this.pdfDocument.serializeXfaData(e)}cleanup(e=!1){return this.pdfDocument.cleanup(e)}async ensure(e,t,i){unreachable("Abstract method `ensure` called")}requestRange(e,t){unreachable("Abstract method `requestRange` called")}requestLoadedStream(e=!1){unreachable("Abstract method `requestLoadedStream` called")}sendProgressiveData(e){unreachable("Abstract method `sendProgressiveData` called")}updatePassword(e){this._password=e}terminate(e){unreachable("Abstract method `terminate` called")}}class LocalPdfManager extends BasePdfManager{constructor(e){super(e);const t=new Stream(e.source);this.pdfDocument=new PDFDocument(this,t);this._loadedStreamPromise=Promise.resolve(t)}async ensure(e,t,i){const a=e[t];return"function"==typeof a?a.apply(e,i):a}requestRange(e,t){return Promise.resolve()}requestLoadedStream(e=!1){return this._loadedStreamPromise}terminate(e){}}class NetworkPdfManager extends BasePdfManager{constructor(e){super(e);this.streamManager=new ChunkedStreamManager(e.source,{msgHandler:e.handler,length:e.length,disableAutoFetch:e.disableAutoFetch,rangeChunkSize:e.rangeChunkSize});this.pdfDocument=new PDFDocument(this,this.streamManager.getStream())}async ensure(e,t,i){try{const a=e[t];return"function"==typeof a?a.apply(e,i):a}catch(a){if(!(a instanceof MissingDataException))throw a;await this.requestRange(a.begin,a.end);return this.ensure(e,t,i)}}requestRange(e,t){return this.streamManager.requestRange(e,t)}requestLoadedStream(e=!1){return this.streamManager.requestAllChunks(e)}sendProgressiveData(e){this.streamManager.onReceiveData({chunk:e})}terminate(e){this.streamManager.abort(e)}}const rg=1,ng=2,gg=1,og=2,Ig=3,cg=4,Cg=5,hg=6,lg=7,Bg=8;function onFn(){}function wrapReason(e){if(e instanceof AbortException||e instanceof InvalidPDFException||e instanceof MissingPDFException||e instanceof PasswordException||e instanceof UnexpectedResponseException||e instanceof UnknownErrorException)return e;e instanceof Error||"object"==typeof e&&null!==e||unreachable('wrapReason: Expected "reason" to be a (possibly cloned) Error.');switch(e.name){case"AbortException":return new AbortException(e.message);case"InvalidPDFException":return new InvalidPDFException(e.message);case"MissingPDFException":return new MissingPDFException(e.message);case"PasswordException":return new PasswordException(e.message,e.code);case"UnexpectedResponseException":return new UnexpectedResponseException(e.message,e.status);case"UnknownErrorException":return new UnknownErrorException(e.message,e.details)}return new UnknownErrorException(e.message,e.toString())}class MessageHandler{#_=new AbortController;constructor(e,t,i){this.sourceName=e;this.targetName=t;this.comObj=i;this.callbackId=1;this.streamId=1;this.streamSinks=Object.create(null);this.streamControllers=Object.create(null);this.callbackCapabilities=Object.create(null);this.actionHandler=Object.create(null);i.addEventListener("message",this.#$.bind(this),{signal:this.#_.signal})}#$({data:e}){if(e.targetName!==this.sourceName)return;if(e.stream){this.#AA(e);return}if(e.callback){const t=e.callbackId,i=this.callbackCapabilities[t];if(!i)throw new Error(`Cannot resolve callback ${t}`);delete this.callbackCapabilities[t];if(e.callback===rg)i.resolve(e.data);else{if(e.callback!==ng)throw new Error("Unexpected callback case");i.reject(wrapReason(e.reason))}return}const t=this.actionHandler[e.action];if(!t)throw new Error(`Unknown action from worker: ${e.action}`);if(e.callbackId){const i=this.sourceName,a=e.sourceName,s=this.comObj;Promise.try(t,e.data).then((function(t){s.postMessage({sourceName:i,targetName:a,callback:rg,callbackId:e.callbackId,data:t})}),(function(t){s.postMessage({sourceName:i,targetName:a,callback:ng,callbackId:e.callbackId,reason:wrapReason(t)})}))}else e.streamId?this.#eA(e):t(e.data)}on(e,t){const i=this.actionHandler;if(i[e])throw new Error(`There is already an actionName called "${e}"`);i[e]=t}send(e,t,i){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,data:t},i)}sendWithPromise(e,t,i){const a=this.callbackId++,s=Promise.withResolvers();this.callbackCapabilities[a]=s;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,callbackId:a,data:t},i)}catch(e){s.reject(e)}return s.promise}sendWithStream(e,t,i,a){const s=this.streamId++,r=this.sourceName,n=this.targetName,g=this.comObj;return new ReadableStream({start:i=>{const o=Promise.withResolvers();this.streamControllers[s]={controller:i,startCall:o,pullCall:null,cancelCall:null,isClosed:!1};g.postMessage({sourceName:r,targetName:n,action:e,streamId:s,data:t,desiredSize:i.desiredSize},a);return o.promise},pull:e=>{const t=Promise.withResolvers();this.streamControllers[s].pullCall=t;g.postMessage({sourceName:r,targetName:n,stream:hg,streamId:s,desiredSize:e.desiredSize});return t.promise},cancel:e=>{assert(e instanceof Error,"cancel must have a valid reason");const t=Promise.withResolvers();this.streamControllers[s].cancelCall=t;this.streamControllers[s].isClosed=!0;g.postMessage({sourceName:r,targetName:n,stream:gg,streamId:s,reason:wrapReason(e)});return t.promise}},i)}#eA(e){const t=e.streamId,i=this.sourceName,a=e.sourceName,s=this.comObj,r=this,n=this.actionHandler[e.action],g={enqueue(e,r=1,n){if(this.isCancelled)return;const g=this.desiredSize;this.desiredSize-=r;if(g>0&&this.desiredSize<=0){this.sinkCapability=Promise.withResolvers();this.ready=this.sinkCapability.promise}s.postMessage({sourceName:i,targetName:a,stream:cg,streamId:t,chunk:e},n)},close(){if(!this.isCancelled){this.isCancelled=!0;s.postMessage({sourceName:i,targetName:a,stream:Ig,streamId:t});delete r.streamSinks[t]}},error(e){assert(e instanceof Error,"error must have a valid reason");if(!this.isCancelled){this.isCancelled=!0;s.postMessage({sourceName:i,targetName:a,stream:Cg,streamId:t,reason:wrapReason(e)})}},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:e.desiredSize,ready:null};g.sinkCapability.resolve();g.ready=g.sinkCapability.promise;this.streamSinks[t]=g;Promise.try(n,e.data,g).then((function(){s.postMessage({sourceName:i,targetName:a,stream:Bg,streamId:t,success:!0})}),(function(e){s.postMessage({sourceName:i,targetName:a,stream:Bg,streamId:t,reason:wrapReason(e)})}))}#AA(e){const t=e.streamId,i=this.sourceName,a=e.sourceName,s=this.comObj,r=this.streamControllers[t],n=this.streamSinks[t];switch(e.stream){case Bg:e.success?r.startCall.resolve():r.startCall.reject(wrapReason(e.reason));break;case lg:e.success?r.pullCall.resolve():r.pullCall.reject(wrapReason(e.reason));break;case hg:if(!n){s.postMessage({sourceName:i,targetName:a,stream:lg,streamId:t,success:!0});break}n.desiredSize<=0&&e.desiredSize>0&&n.sinkCapability.resolve();n.desiredSize=e.desiredSize;Promise.try(n.onPull||onFn).then((function(){s.postMessage({sourceName:i,targetName:a,stream:lg,streamId:t,success:!0})}),(function(e){s.postMessage({sourceName:i,targetName:a,stream:lg,streamId:t,reason:wrapReason(e)})}));break;case cg:assert(r,"enqueue should have stream controller");if(r.isClosed)break;r.controller.enqueue(e.chunk);break;case Ig:assert(r,"close should have stream controller");if(r.isClosed)break;r.isClosed=!0;r.controller.close();this.#tA(r,t);break;case Cg:assert(r,"error should have stream controller");r.controller.error(wrapReason(e.reason));this.#tA(r,t);break;case og:e.success?r.cancelCall.resolve():r.cancelCall.reject(wrapReason(e.reason));this.#tA(r,t);break;case gg:if(!n)break;const g=wrapReason(e.reason);Promise.try(n.onCancel||onFn,g).then((function(){s.postMessage({sourceName:i,targetName:a,stream:og,streamId:t,success:!0})}),(function(e){s.postMessage({sourceName:i,targetName:a,stream:og,streamId:t,reason:wrapReason(e)})}));n.sinkCapability.reject(g);n.isCancelled=!0;delete this.streamSinks[t];break;default:throw new Error("Unexpected stream case")}}async#tA(e,t){await Promise.allSettled([e.startCall?.promise,e.pullCall?.promise,e.cancelCall?.promise]);delete this.streamControllers[t]}destroy(){this.#_?.abort();this.#_=null}}async function writeObject(e,t,i,{encrypt:a=null}){const s=a?.createCipherTransform(e.num,e.gen);i.push(`${e.num} ${e.gen} obj\n`);t instanceof Dict?await writeDict(t,i,s):t instanceof BaseStream?await writeStream(t,i,s):(Array.isArray(t)||ArrayBuffer.isView(t))&&await writeArray(t,i,s);i.push("\nendobj\n")}async function writeDict(e,t,i){t.push("<<");for(const a of e.getKeys()){t.push(` /${escapePDFName(a)} `);await writeValue(e.getRaw(a),t,i)}t.push(">>")}async function writeStream(e,t,i){let a=e.getBytes();const{dict:s}=e,[r,n]=await Promise.all([s.getAsync("Filter"),s.getAsync("DecodeParms")]),g=isName(Array.isArray(r)?await s.xref.fetchIfRefAsync(r[0]):r,"FlateDecode");if(a.length>=256||g)try{const e=new CompressionStream("deflate"),t=e.writable.getWriter();await t.ready;t.write(a).then((async()=>{await t.ready;await t.close()})).catch((()=>{}));const i=await new Response(e.readable).arrayBuffer();a=new Uint8Array(i);let o,c;if(r){if(!g){o=Array.isArray(r)?[Name.get("FlateDecode"),...r]:[Name.get("FlateDecode"),r];n&&(c=Array.isArray(n)?[null,...n]:[null,n])}}else o=Name.get("FlateDecode");o&&s.set("Filter",o);c&&s.set("DecodeParms",c)}catch(e){info(`writeStream - cannot compress data: "${e}".`)}let o=bytesToString(a);i&&(o=i.encryptString(o));s.set("Length",o.length);await writeDict(s,t,i);t.push(" stream\n",o,"\nendstream")}async function writeArray(e,t,i){t.push("[");let a=!0;for(const s of e){a?a=!1:t.push(" ");await writeValue(s,t,i)}t.push("]")}async function writeValue(e,t,i){if(e instanceof Name)t.push(`/${escapePDFName(e.name)}`);else if(e instanceof Ref)t.push(`${e.num} ${e.gen} R`);else if(Array.isArray(e)||ArrayBuffer.isView(e))await writeArray(e,t,i);else if("string"==typeof e){i&&(e=i.encryptString(e));t.push(`(${escapeString(e)})`)}else"number"==typeof e?t.push(numberToString(e)):"boolean"==typeof e?t.push(e.toString()):e instanceof Dict?await writeDict(e,t,i):e instanceof BaseStream?await writeStream(e,t,i):null===e?t.push("null"):warn(`Unhandled value in writer: ${typeof e}, please file a bug.`)}function writeInt(e,t,i,a){for(let s=t+i-1;s>i-1;s--){a[s]=255&e;e>>=8}return i+t}function writeString(e,t,i){for(let a=0,s=e.length;a1&&(r=i.documentElement.searchNode([s.at(-1)],0));r?r.childNodes=Array.isArray(a)?a.map((e=>new SimpleDOMNode("value",e))):[new SimpleDOMNode("#text",a)]:warn(`Node not found for path: ${t}`)}const a=[];i.documentElement.dump(a);return a.join("")}(a.fetchIfRef(t).getString(),i)}const s=new StringStream(e);s.dict=new Dict(a);s.dict.set("Type",Name.get("EmbeddedFile"));i.put(t,{data:s})}function getIndexes(e){const t=[];for(const{ref:i}of e)i.num===t.at(-2)+t.at(-1)?t[t.length-1]+=1:t.push(i.num,1);return t}function computeIDs(e,t,i){if(Array.isArray(t.fileIds)&&t.fileIds.length>0){const a=function computeMD5(e,t){const i=Math.floor(Date.now()/1e3),a=t.filename||"",s=[i.toString(),a,e.toString()];let r=s.reduce(((e,t)=>e+t.length),0);for(const e of Object.values(t.info)){s.push(e);r+=e.length}const n=new Uint8Array(r);let g=0;for(const e of s){writeString(e,g,n);g+=e.length}return bytesToString($n(n))}(e,t);i.set("ID",[t.fileIds[0],a])}}async function incrementalUpdate({originalData:e,xrefInfo:t,changes:i,xref:a=null,hasXfa:s=!1,xfaDatasetsRef:r=null,hasXfaDatasetsEntry:n=!1,needAppearances:g,acroFormRef:o=null,acroForm:c=null,xfaData:C=null,useXrefStream:h=!1}){await async function updateAcroform({xref:e,acroForm:t,acroFormRef:i,hasXfa:a,hasXfaDatasetsEntry:s,xfaDatasetsRef:r,needAppearances:n,changes:g}){!a||s||r||warn("XFA - Cannot save it");if(!n&&(!a||!r||s))return;const o=t.clone();if(a&&!s){const e=t.get("XFA").slice();e.splice(2,0,"datasets");e.splice(3,0,r);o.set("XFA",e)}n&&o.set("NeedAppearances",!0);g.put(i,{data:o})}({xref:a,acroForm:c,acroFormRef:o,hasXfa:s,hasXfaDatasetsEntry:n,xfaDatasetsRef:r,needAppearances:g,changes:i});s&&updateXFA({xfaData:C,xfaDatasetsRef:r,changes:i,xref:a});const l=function getTrailerDict(e,t,i){const a=new Dict(null);a.set("Prev",e.startXRef);const s=e.newRef;if(i){t.put(s,{data:""});a.set("Size",s.num+1);a.set("Type",Name.get("XRef"))}else a.set("Size",s.num);null!==e.rootRef&&a.set("Root",e.rootRef);null!==e.infoRef&&a.set("Info",e.infoRef);null!==e.encryptRef&&a.set("Encrypt",e.encryptRef);return a}(t,i,h),Q=[],E=await async function writeChanges(e,t,i=[]){const a=[];for(const[s,{data:r}]of e.items())if(null!==r&&"string"!=typeof r){await writeObject(s,r,i,t);a.push({ref:s,data:i.join("")});i.length=0}else a.push({ref:s,data:r});return a.sort(((e,t)=>e.ref.num-t.ref.num))}(i,a,Q);let u=e.length;const d=e.at(-1);if(10!==d&&13!==d){Q.push("\n");u+=1}for(const{data:e}of E)null!==e&&Q.push(e);await(h?async function getXRefStreamTable(e,t,i,a,s){const r=[];let n=0,g=0;for(const{ref:e,data:a}of i){let i;n=Math.max(n,t);if(null!==a){i=Math.min(e.gen,65535);r.push([1,t,i]);t+=a.length}else{i=Math.min(e.gen+1,65535);r.push([0,0,i])}g=Math.max(g,i)}a.set("Index",getIndexes(i));const o=[1,getSizeInBytes(n),getSizeInBytes(g)];a.set("W",o);computeIDs(t,e,a);const c=o.reduce(((e,t)=>e+t),0),C=new Uint8Array(c*r.length),h=new Stream(C);h.dict=a;let l=0;for(const[e,t,i]of r){l=writeInt(e,o[0],l,C);l=writeInt(t,o[1],l,C);l=writeInt(i,o[2],l,C)}await writeObject(e.newRef,h,s,{});s.push("startxref\n",t.toString(),"\n%%EOF\n")}(t,u,E,l,Q):async function getXRefTable(e,t,i,a,s){s.push("xref\n");const r=getIndexes(i);let n=0;for(const{ref:e,data:a}of i){if(e.num===r[n]){s.push(`${r[n]} ${r[n+1]}\n`);n+=2}if(null!==a){s.push(`${t.toString().padStart(10,"0")} ${Math.min(e.gen,65535).toString().padStart(5,"0")} n\r\n`);t+=a.length}else s.push(`0000000000 ${Math.min(e.gen+1,65535).toString().padStart(5,"0")} f\r\n`)}computeIDs(t,e,a);s.push("trailer\n");await writeDict(a,s);s.push("\nstartxref\n",t.toString(),"\n%%EOF\n")}(t,u,E,l,Q));const f=Q.reduce(((e,t)=>e+t.length),e.length),p=new Uint8Array(f);p.set(e);let m=e.length;for(const e of Q){writeString(e,m,p);m+=e.length}return p}class PDFWorkerStream{constructor(e){this._msgHandler=e;this._contentLength=null;this._fullRequestReader=null;this._rangeRequestReaders=[]}getFullReader(){assert(!this._fullRequestReader,"PDFWorkerStream.getFullReader can only be called once.");this._fullRequestReader=new PDFWorkerStreamReader(this._msgHandler);return this._fullRequestReader}getRangeReader(e,t){const i=new PDFWorkerStreamRangeReader(e,t,this._msgHandler);this._rangeRequestReaders.push(i);return i}cancelAllRequests(e){this._fullRequestReader?.cancel(e);for(const t of this._rangeRequestReaders.slice(0))t.cancel(e)}}class PDFWorkerStreamReader{constructor(e){this._msgHandler=e;this.onProgress=null;this._contentLength=null;this._isRangeSupported=!1;this._isStreamingSupported=!1;const t=this._msgHandler.sendWithStream("GetReader");this._reader=t.getReader();this._headersReady=this._msgHandler.sendWithPromise("ReaderHeadersReady").then((e=>{this._isStreamingSupported=e.isStreamingSupported;this._isRangeSupported=e.isRangeSupported;this._contentLength=e.contentLength}))}get headersReady(){return this._headersReady}get contentLength(){return this._contentLength}get isStreamingSupported(){return this._isStreamingSupported}get isRangeSupported(){return this._isRangeSupported}async read(){const{value:e,done:t}=await this._reader.read();return t?{value:void 0,done:!0}:{value:e.buffer,done:!1}}cancel(e){this._reader.cancel(e)}}class PDFWorkerStreamRangeReader{constructor(e,t,i){this._msgHandler=i;this.onProgress=null;const a=this._msgHandler.sendWithStream("GetRangeReader",{begin:e,end:t});this._reader=a.getReader()}get isStreamingSupported(){return!1}async read(){const{value:e,done:t}=await this._reader.read();return t?{value:void 0,done:!0}:{value:e.buffer,done:!1}}cancel(e){this._reader.cancel(e)}}class WorkerTask{constructor(e){this.name=e;this.terminated=!1;this._capability=Promise.withResolvers()}get finished(){return this._capability.promise}finish(){this._capability.resolve()}terminate(){this.terminated=!0}ensureNotTerminated(){if(this.terminated)throw new Error("Worker task was terminated")}}class WorkerMessageHandler{static{"undefined"==typeof window&&!t&&"undefined"!=typeof self&&"function"==typeof self.postMessage&&"onmessage"in self&&this.initializeFromPort(self)}static setup(e,t){let i=!1;e.on("test",(t=>{if(!i){i=!0;e.send("test",t instanceof Uint8Array)}}));e.on("configure",(e=>{!function setVerbosityLevel(e){Number.isInteger(e)&&(gt=e)}(e.verbosity)}));e.on("GetDocRequest",(e=>this.createDocumentHandler(e,t)))}static createDocumentHandler(e,t){let i,a=!1,s=null;const r=new Set,n=getVerbosityLevel(),{docId:g,apiVersion:o}=e,c="4.10.38";if(o!==c)throw new Error(`The API version "${o}" does not match the Worker version "${c}".`);const C=[];for(const e in[])C.push(e);if(C.length)throw new Error("The `Array.prototype` contains unexpected enumerable properties: "+C.join(", ")+"; thus breaking e.g. `for...in` iteration of `Array`s.");const h=g+"_worker";let l=new MessageHandler(h,g,t);function ensureNotTerminated(){if(a)throw new Error("Worker was terminated")}function startWorkerTask(e){r.add(e)}function finishWorkerTask(e){e.finish();r.delete(e)}async function loadDocument(e){await i.ensureDoc("checkHeader");await i.ensureDoc("parseStartXRef");await i.ensureDoc("parse",[e]);await i.ensureDoc("checkFirstPage",[e]);await i.ensureDoc("checkLastPage",[e]);const t=await i.ensureDoc("isPureXfa");if(t){const e=new WorkerTask("loadXfaFonts");startWorkerTask(e);await Promise.all([i.loadXfaFonts(l,e).catch((e=>{})).then((()=>finishWorkerTask(e))),i.loadXfaImages()])}const[a,s]=await Promise.all([i.ensureDoc("numPages"),i.ensureDoc("fingerprints")]);return{numPages:a,fingerprints:s,htmlForXfa:t?await i.ensureDoc("htmlForXfa"):null}}function setupDoc(e){function onSuccess(e){ensureNotTerminated();l.send("GetDoc",{pdfInfo:e})}function onFailure(e){ensureNotTerminated();if(e instanceof PasswordException){const t=new WorkerTask(`PasswordException: response ${e.code}`);startWorkerTask(t);l.sendWithPromise("PasswordRequest",e).then((function({password:e}){finishWorkerTask(t);i.updatePassword(e);pdfManagerReady()})).catch((function(){finishWorkerTask(t);l.send("DocException",e)}))}else l.send("DocException",wrapReason(e))}function pdfManagerReady(){ensureNotTerminated();loadDocument(!1).then(onSuccess,(function(e){ensureNotTerminated();e instanceof XRefParseException?i.requestLoadedStream().then((function(){ensureNotTerminated();loadDocument(!0).then(onSuccess,onFailure)})):onFailure(e)}))}ensureNotTerminated();(async function getPdfManager({data:e,password:t,disableAutoFetch:i,rangeChunkSize:a,length:r,docBaseUrl:n,enableXfa:o,evaluatorOptions:c}){const C={source:null,disableAutoFetch:i,docBaseUrl:n,docId:g,enableXfa:o,evaluatorOptions:c,handler:l,length:r,password:t,rangeChunkSize:a};if(e){C.source=e;return new LocalPdfManager(C)}const h=new PDFWorkerStream(l),Q=h.getFullReader(),E=Promise.withResolvers();let u,d=[],f=0;Q.headersReady.then((function(){if(Q.isRangeSupported){C.source=h;C.length=Q.contentLength;C.disableAutoFetch||=Q.isStreamingSupported;u=new NetworkPdfManager(C);for(const e of d)u.sendProgressiveData(e);d=[];E.resolve(u);s=null}})).catch((function(e){E.reject(e);s=null}));new Promise((function(e,t){const readChunk=function({value:e,done:i}){try{ensureNotTerminated();if(i){if(!u){const e=arrayBuffersToBytes(d);d=[];r&&e.length!==r&&warn("reported HTTP length is different from actual");C.source=e;u=new LocalPdfManager(C);E.resolve(u)}s=null;return}f+=e.byteLength;Q.isStreamingSupported||l.send("DocProgress",{loaded:f,total:Math.max(f,Q.contentLength||0)});u?u.sendProgressiveData(e):d.push(e);Q.read().then(readChunk,t)}catch(e){t(e)}};Q.read().then(readChunk,t)})).catch((function(e){E.reject(e);s=null}));s=e=>{h.cancelAllRequests(e)};return E.promise})(e).then((function(e){if(a){e.terminate(new AbortException("Worker was terminated."));throw new Error("Worker was terminated")}i=e;i.requestLoadedStream(!0).then((e=>{l.send("DataLoaded",{length:e.bytes.byteLength})}))})).then(pdfManagerReady,onFailure)}l.on("GetPage",(function(e){return i.getPage(e.pageIndex).then((function(e){return Promise.all([i.ensure(e,"rotate"),i.ensure(e,"ref"),i.ensure(e,"userUnit"),i.ensure(e,"view")]).then((function([e,t,i,a]){return{rotate:e,ref:t,refStr:t?.toString()??null,userUnit:i,view:a}}))}))}));l.on("GetPageIndex",(function(e){const t=Ref.get(e.num,e.gen);return i.ensureCatalog("getPageIndex",[t])}));l.on("GetDestinations",(function(e){return i.ensureCatalog("destinations")}));l.on("GetDestination",(function(e){return i.ensureCatalog("getDestination",[e.id])}));l.on("GetPageLabels",(function(e){return i.ensureCatalog("pageLabels")}));l.on("GetPageLayout",(function(e){return i.ensureCatalog("pageLayout")}));l.on("GetPageMode",(function(e){return i.ensureCatalog("pageMode")}));l.on("GetViewerPreferences",(function(e){return i.ensureCatalog("viewerPreferences")}));l.on("GetOpenAction",(function(e){return i.ensureCatalog("openAction")}));l.on("GetAttachments",(function(e){return i.ensureCatalog("attachments")}));l.on("GetDocJSActions",(function(e){return i.ensureCatalog("jsActions")}));l.on("GetPageJSActions",(function({pageIndex:e}){return i.getPage(e).then((function(e){return i.ensure(e,"jsActions")}))}));l.on("GetOutline",(function(e){return i.ensureCatalog("documentOutline")}));l.on("GetOptionalContentConfig",(function(e){return i.ensureCatalog("optionalContentConfig")}));l.on("GetPermissions",(function(e){return i.ensureCatalog("permissions")}));l.on("GetMetadata",(function(e){return Promise.all([i.ensureDoc("documentInfo"),i.ensureCatalog("metadata")])}));l.on("GetMarkInfo",(function(e){return i.ensureCatalog("markInfo")}));l.on("GetData",(function(e){return i.requestLoadedStream().then((function(e){return e.bytes}))}));l.on("GetAnnotations",(function({pageIndex:e,intent:t}){return i.getPage(e).then((function(i){const a=new WorkerTask(`GetAnnotations: page ${e}`);startWorkerTask(a);return i.getAnnotationsData(l,a,t).then((e=>{finishWorkerTask(a);return e}),(e=>{finishWorkerTask(a);throw e}))}))}));l.on("GetFieldObjects",(function(e){return i.ensureDoc("fieldObjects").then((e=>e?.allFields||null))}));l.on("HasJSActions",(function(e){return i.ensureDoc("hasJSActions")}));l.on("GetCalculationOrderIds",(function(e){return i.ensureDoc("calculationOrderIds")}));l.on("SaveDocument",(async function({isPureXfa:e,numPages:t,annotationStorage:a,filename:s}){const r=[i.requestLoadedStream(),i.ensureCatalog("acroForm"),i.ensureCatalog("acroFormRef"),i.ensureDoc("startXRef"),i.ensureDoc("xref"),i.ensureDoc("linearization"),i.ensureCatalog("structTreeRoot")],n=new RefSetCache,g=[],o=e?null:getNewAnnotationsMap(a),[c,C,h,Q,E,u,d]=await Promise.all(r),f=E.trailer.getRaw("Root")||null;let p;if(o){d?await d.canUpdateStructTree({pdfManager:i,xref:E,newAnnotationsByPage:o})&&(p=d):await StructTreeRoot.canCreateStructureTree({catalogRef:f,pdfManager:i,newAnnotationsByPage:o})&&(p=null);const e=AnnotationFactory.generateImages(a.values(),E,i.evaluatorOptions.isOffscreenCanvasSupported),t=void 0===p?g:[];for(const[a,s]of o)t.push(i.getPage(a).then((t=>{const i=new WorkerTask(`Save (editor): page ${a}`);startWorkerTask(i);return t.saveNewAnnotations(l,i,s,e,n).finally((function(){finishWorkerTask(i)}))})));null===p?g.push(Promise.all(t).then((async()=>{await StructTreeRoot.createStructureTree({newAnnotationsByPage:o,xref:E,catalogRef:f,pdfManager:i,changes:n})}))):p&&g.push(Promise.all(t).then((async()=>{await p.updateStructureTree({newAnnotationsByPage:o,pdfManager:i,changes:n})})))}if(e)g.push(i.serializeXfaData(a));else for(let e=0;ee.needAppearances)),D=C instanceof Dict&&C.get("XFA")||null;let b=null,F=!1;if(Array.isArray(D)){for(let e=0,t=D.length;e{E.resetNewTemporaryRef()}))}));l.on("GetOperatorList",(function(e,t){const a=e.pageIndex;i.getPage(a).then((function(i){const s=new WorkerTask(`GetOperatorList: page ${a}`);startWorkerTask(s);const r=n>=yA?Date.now():0;i.getOperatorList({handler:l,sink:t,task:s,intent:e.intent,cacheKey:e.cacheKey,annotationStorage:e.annotationStorage,modifiedIds:e.modifiedIds}).then((function(e){finishWorkerTask(s);r&&info(`page=${a+1} - getOperatorList: time=${Date.now()-r}ms, len=${e.length}`);t.close()}),(function(e){finishWorkerTask(s);s.terminated||t.error(e)}))}))}));l.on("GetTextContent",(function(e,t){const{pageIndex:a,includeMarkedContent:s,disableNormalization:r}=e;i.getPage(a).then((function(e){const i=new WorkerTask("GetTextContent: page "+a);startWorkerTask(i);const g=n>=yA?Date.now():0;e.extractTextContent({handler:l,task:i,sink:t,includeMarkedContent:s,disableNormalization:r}).then((function(){finishWorkerTask(i);g&&info(`page=${a+1} - getTextContent: time=`+(Date.now()-g)+"ms");t.close()}),(function(e){finishWorkerTask(i);i.terminated||t.error(e)}))}))}));l.on("GetStructTree",(function(e){return i.getPage(e.pageIndex).then((function(e){return i.ensure(e,"getStructTree")}))}));l.on("FontFallback",(function(e){return i.fontFallback(e.id,l)}));l.on("Cleanup",(function(e){return i.cleanup(!0)}));l.on("Terminate",(function(e){a=!0;const t=[];if(i){i.terminate(new AbortException("Worker was terminated."));const e=i.cleanup();t.push(e);i=null}else clearGlobalCaches();s?.(new AbortException("Worker was terminated."));for(const e of r){t.push(e.finished);e.terminate()}return Promise.all(t).then((function(){l.destroy();l=null}))}));l.on("Ready",(function(t){setupDoc(e);e=null}));return h}static initializeFromPort(e){const t=new MessageHandler("worker","main",e);this.setup(t,e);t.send("ready",null)}}var Qg=__webpack_exports__.WorkerMessageHandler;export{Qg as WorkerMessageHandler}; \ No newline at end of file diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/web/images/loading-icon.gif b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/web/images/loading-icon.gif deleted file mode 100644 index 1c72ebb554be018511ae972c3f2361dff02dce02..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2545 zcma*pX;2es8VB%~zPr=ibVMCx-JQ^BhLDAsK)^**h(ZDp9YGuzZ%~j!}+w%FI;|aC7){7CdVvG)P{bng1y9Te*f}~*`1kQl$jwb z$tlW~rRS!X?#xfm_&6tTdp_`cjgYwbRFLNdoJCN$S-yhg`ZnC-yvedRSmOh%;Y`Gl6bY$Z-}#C=#F4%9!I1b zWQ~f+9P?;vhCxWwlwl=lrWG|7IYo;{jjmzJ5R9?f>n%-d@>kLINUc z4wM5dAO;kq<$}Dk{2-u0$I6@2N}&cUx9nmV1dYc8jfC}%=F9WCg^OQK9C6poh#2!A z3^EU*UFZvS^)?bu3T?J;@Ahb~%I?+@4!l5!*TjC}GIslNan-RCrrd~PdHYnNLJk+m&`$Y+NV(e>CCu%R#_8GqY4cv#j`#uRWdsg9DxWy(?oOvgCU}&@jy%c!H&-Q zqXJxajAtmQRoRa9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xT^J^-VAk)Z@$4^XrPrFP-Co+MXZ+KJ(W z{JNYvraLLWA;&tRhIKOvhW|HC|L-dLvAUF(MG0(Nl?4tB{RzN7I(}Cb%hwN{crFC8 zji#aJElKvDFV+&VI1V?oUMA>*kto0^;3W8FQBSZ|{ z$v~TqE=(8DZa^i$^oht&h};P1N&wMXorKh*Z68gPV&ouy>%f36Oqkwemyeas$Qbz# zV?7Jy%o7KY6^I=P@eCji%W`o5sf(5hySYo9$l4e2`(hIV_?=H-#R6}0$WVA|*(K@3 z=5?@RlcLh(meW%A4)hGzcvEpm(_w?>zhL*i&s9$2>r zAtk{8Cia|+Y+V!uX9BtpXoF%lswuRKsM!pSs!?yhlCy!269K0|b M?FSZn2B>%I-}ej|s{jB1 diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.css deleted file mode 100644 index 86a3716c501..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.css +++ /dev/null @@ -1,3274 +0,0 @@ -/* Copyright 2014 Mozilla Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -.messageBar{ - --closing-button-icon:url(images/messageBar_closingButton.svg); - --message-bar-close-button-color:var(--text-primary-color); - --message-bar-close-button-color-hover:var(--text-primary-color); - --message-bar-close-button-border-radius:4px; - --message-bar-close-button-border:none; - --message-bar-close-button-hover-bg-color:rgb(21 20 26 / 0.14); - --message-bar-close-button-active-bg-color:rgb(21 20 26 / 0.21); - --message-bar-close-button-focus-bg-color:rgb(21 20 26 / 0.07); -} - -@media (prefers-color-scheme: dark){ - -.messageBar{ - --message-bar-close-button-hover-bg-color:rgb(251 251 254 / 0.14); - --message-bar-close-button-active-bg-color:rgb(251 251 254 / 0.21); - --message-bar-close-button-focus-bg-color:rgb(251 251 254 / 0.07); -} - } - -@media screen and (forced-colors: active){ - -.messageBar{ - --message-bar-close-button-color:ButtonText; - --message-bar-close-button-border:1px solid ButtonText; - --message-bar-close-button-hover-bg-color:ButtonText; - --message-bar-close-button-active-bg-color:ButtonText; - --message-bar-close-button-focus-bg-color:ButtonText; - --message-bar-close-button-color-hover:HighlightText; -} - } - -.messageBar{ - - display:flex; - position:relative; - padding:8px 8px 8px 16px; - flex-direction:column; - justify-content:center; - align-items:center; - gap:8px; - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; - - border-radius:4px; - - border:1px solid var(--message-bar-border-color); - background:var(--message-bar-bg-color); - color:var(--message-bar-fg-color); -} - -.messageBar > div{ - display:flex; - align-items:flex-start; - gap:8px; - align-self:stretch; - } - -:is(.messageBar > div)::before{ - content:""; - display:inline-block; - width:16px; - height:16px; - -webkit-mask-image:var(--message-bar-icon); - mask-image:var(--message-bar-icon); - -webkit-mask-size:cover; - mask-size:cover; - background-color:var(--message-bar-icon-color); - flex-shrink:0; - } - -.messageBar button{ - cursor:pointer; - } - -:is(.messageBar button):focus-visible{ - outline:var(--focus-ring-outline); - outline-offset:2px; - } - -.messageBar .closeButton{ - width:32px; - height:32px; - background:none; - border-radius:var(--message-bar-close-button-border-radius); - border:var(--message-bar-close-button-border); - - display:flex; - align-items:center; - justify-content:center; - } - -:is(.messageBar .closeButton)::before{ - content:""; - display:inline-block; - width:16px; - height:16px; - -webkit-mask-image:var(--closing-button-icon); - mask-image:var(--closing-button-icon); - -webkit-mask-size:cover; - mask-size:cover; - background-color:var(--message-bar-close-button-color); - } - -:is(.messageBar .closeButton):is(:hover,:active,:focus)::before{ - background-color:var(--message-bar-close-button-color-hover); - } - -:is(.messageBar .closeButton):hover{ - background-color:var(--message-bar-close-button-hover-bg-color); - } - -:is(.messageBar .closeButton):active{ - background-color:var(--message-bar-close-button-active-bg-color); - } - -:is(.messageBar .closeButton):focus{ - background-color:var(--message-bar-close-button-focus-bg-color); - } - -:is(.messageBar .closeButton) > span{ - display:inline-block; - width:0; - height:0; - overflow:hidden; - } - -#editorUndoBar{ - --text-primary-color:#15141a; - - --message-bar-icon:url(images/secondaryToolbarButton-documentProperties.svg); - --message-bar-icon-color:#0060df; - --message-bar-bg-color:#deeafc; - --message-bar-fg-color:var(--text-primary-color); - --message-bar-border-color:rgb(0 0 0 / 0.08); - - --undo-button-bg-color:rgb(21 20 26 / 0.07); - --undo-button-bg-color-hover:rgb(21 20 26 / 0.14); - --undo-button-bg-color-active:rgb(21 20 26 / 0.21); - - --undo-button-fg-color:var(--message-bar-fg-color); - --undo-button-fg-color-hover:var(--undo-button-fg-color); - --undo-button-fg-color-active:var(--undo-button-fg-color); - - --focus-ring-color:#0060df; - --focus-ring-outline:2px solid var(--focus-ring-color); -} - -@media (prefers-color-scheme: dark){ - -#editorUndoBar{ - --text-primary-color:#fbfbfe; - - --message-bar-icon-color:#73a7f3; - --message-bar-bg-color:#003070; - --message-bar-border-color:rgb(255 255 255 / 0.08); - - --undo-button-bg-color:rgb(255 255 255 / 0.08); - --undo-button-bg-color-hover:rgb(255 255 255 / 0.14); - --undo-button-bg-color-active:rgb(255 255 255 / 0.21); -} - } - -@media screen and (forced-colors: active){ - -#editorUndoBar{ - --text-primary-color:CanvasText; - - --message-bar-icon-color:CanvasText; - --message-bar-bg-color:Canvas; - --message-bar-border-color:CanvasText; - - --undo-button-bg-color:ButtonText; - --undo-button-bg-color-hover:SelectedItem; - --undo-button-bg-color-active:SelectedItem; - - --undo-button-fg-color:ButtonFace; - --undo-button-fg-color-hover:SelectedItemText; - --undo-button-fg-color-active:SelectedItemText; - - --focus-ring-color:CanvasText; -} - } - -#editorUndoBar{ - - position:fixed; - top:50px; - left:50%; - transform:translateX(-50%); - z-index:10; - - padding-block:8px; - padding-inline:16px 8px; - - font:menu; - font-size:15px; - - cursor:default; -} - -#editorUndoBar button{ - cursor:pointer; - } - -#editorUndoBar #editorUndoBarUndoButton{ - border-radius:4px; - font-weight:590; - line-height:19.5px; - color:var(--undo-button-fg-color); - border:none; - padding:4px 16px; - margin-inline-start:8px; - height:32px; - - background-color:var(--undo-button-bg-color); - } - -:is(#editorUndoBar #editorUndoBarUndoButton):hover{ - background-color:var(--undo-button-bg-color-hover); - color:var(--undo-button-fg-color-hover); - } - -:is(#editorUndoBar #editorUndoBarUndoButton):active{ - background-color:var(--undo-button-bg-color-active); - color:var(--undo-button-fg-color-active); - } - -#editorUndoBar > div{ - align-items:center; - } - -.dialog{ - --dialog-bg-color:white; - --dialog-border-color:white; - --dialog-shadow:0 2px 14px 0 rgb(58 57 68 / 0.2); - --text-primary-color:#15141a; - --text-secondary-color:#5b5b66; - --hover-filter:brightness(0.9); - --focus-ring-color:#0060df; - --focus-ring-outline:2px solid var(--focus-ring-color); - --link-fg-color:#0060df; - --link-hover-fg-color:#0250bb; - --separator-color:#f0f0f4; - - --textarea-border-color:#8f8f9d; - --textarea-bg-color:white; - --textarea-fg-color:var(--text-secondary-color); - - --radio-bg-color:#f0f0f4; - --radio-checked-bg-color:#fbfbfe; - --radio-border-color:#8f8f9d; - --radio-checked-border-color:#0060df; - - --button-secondary-bg-color:#f0f0f4; - --button-secondary-fg-color:var(--text-primary-color); - --button-secondary-border-color:var(--button-secondary-bg-color); - --button-secondary-hover-bg-color:var(--button-secondary-bg-color); - --button-secondary-hover-fg-color:var(--button-secondary-fg-color); - --button-secondary-hover-border-color:var(--button-secondary-hover-bg-color); - - --button-primary-bg-color:#0060df; - --button-primary-fg-color:#fbfbfe; - --button-primary-border-color:var(--button-primary-bg-color); - --button-primary-hover-bg-color:var(--button-primary-bg-color); - --button-primary-hover-fg-color:var(--button-primary-fg-color); - --button-primary-hover-border-color:var(--button-primary-hover-bg-color); -} - -@media (prefers-color-scheme: dark){ - -.dialog{ - --dialog-bg-color:#1c1b22; - --dialog-border-color:#1c1b22; - --dialog-shadow:0 2px 14px 0 #15141a; - --text-primary-color:#fbfbfe; - --text-secondary-color:#cfcfd8; - --focus-ring-color:#0df; - --hover-filter:brightness(1.4); - --link-fg-color:#0df; - --link-hover-fg-color:#80ebff; - --separator-color:#52525e; - - --textarea-bg-color:#42414d; - - --radio-bg-color:#2b2a33; - --radio-checked-bg-color:#15141a; - --radio-checked-border-color:#0df; - - --button-secondary-bg-color:#2b2a33; - --button-primary-bg-color:#0df; - --button-primary-fg-color:#15141a; -} - } - -@media screen and (forced-colors: active){ - -.dialog{ - --dialog-bg-color:Canvas; - --dialog-border-color:CanvasText; - --dialog-shadow:none; - --text-primary-color:CanvasText; - --text-secondary-color:CanvasText; - --hover-filter:none; - --focus-ring-color:ButtonBorder; - --link-fg-color:LinkText; - --link-hover-fg-color:LinkText; - --separator-color:CanvasText; - - --textarea-border-color:ButtonBorder; - --textarea-bg-color:Field; - --textarea-fg-color:ButtonText; - - --radio-bg-color:ButtonFace; - --radio-checked-bg-color:ButtonFace; - --radio-border-color:ButtonText; - --radio-checked-border-color:ButtonText; - - --button-secondary-bg-color:ButtonFace; - --button-secondary-fg-color:ButtonText; - --button-secondary-border-color:ButtonText; - --button-secondary-hover-bg-color:AccentColor; - --button-secondary-hover-fg-color:AccentColorText; - - --button-primary-bg-color:ButtonText; - --button-primary-fg-color:ButtonFace; - --button-primary-hover-bg-color:AccentColor; - --button-primary-hover-fg-color:AccentColorText; -} - } - -.dialog{ - - font:message-box; - font-size:13px; - font-weight:400; - line-height:150%; - border-radius:4px; - padding:12px 16px; - border:1px solid var(--dialog-border-color); - background:var(--dialog-bg-color); - color:var(--text-primary-color); - box-shadow:var(--dialog-shadow); -} - -:is(.dialog .mainContainer) *:focus-visible{ - outline:var(--focus-ring-outline); - outline-offset:2px; - } - -:is(.dialog .mainContainer) .title{ - display:flex; - width:auto; - flex-direction:column; - justify-content:flex-end; - align-items:flex-start; - gap:12px; - } - -:is(:is(.dialog .mainContainer) .title) > span{ - font-size:13px; - font-style:normal; - font-weight:590; - line-height:150%; - } - -:is(.dialog .mainContainer) .dialogSeparator{ - width:100%; - height:0; - margin-block:4px; - border-top:1px solid var(--separator-color); - border-bottom:none; - } - -:is(.dialog .mainContainer) .dialogButtonsGroup{ - display:flex; - gap:12px; - align-self:flex-end; - } - -:is(.dialog .mainContainer) .radio{ - display:flex; - flex-direction:column; - align-items:flex-start; - gap:4px; - } - -:is(:is(.dialog .mainContainer) .radio) > .radioButton{ - display:flex; - gap:8px; - align-self:stretch; - align-items:center; - } - -:is(:is(:is(.dialog .mainContainer) .radio) > .radioButton) input{ - -webkit-appearance:none; - -moz-appearance:none; - appearance:none; - box-sizing:border-box; - width:16px; - height:16px; - border-radius:50%; - background-color:var(--radio-bg-color); - border:1px solid var(--radio-border-color); - } - -:is(:is(:is(:is(.dialog .mainContainer) .radio) > .radioButton) input):hover{ - filter:var(--hover-filter); - } - -:is(:is(:is(:is(.dialog .mainContainer) .radio) > .radioButton) input):checked{ - background-color:var(--radio-checked-bg-color); - border:4px solid var(--radio-checked-border-color); - } - -:is(:is(.dialog .mainContainer) .radio) > .radioLabel{ - display:flex; - padding-inline-start:24px; - align-items:flex-start; - gap:10px; - align-self:stretch; - } - -:is(:is(:is(.dialog .mainContainer) .radio) > .radioLabel) > span{ - flex:1 0 0; - font-size:11px; - color:var(--text-secondary-color); - } - -:is(.dialog .mainContainer) button:not(:is(.toggle-button,.closeButton)){ - border-radius:4px; - border:1px solid; - font:menu; - font-weight:600; - padding:4px 16px; - width:auto; - height:32px; - } - -:is(:is(.dialog .mainContainer) button:not(:is(.toggle-button,.closeButton))):hover{ - cursor:pointer; - filter:var(--hover-filter); - } - -.secondaryButton:is(:is(.dialog .mainContainer) button:not(:is(.toggle-button,.closeButton))){ - color:var(--button-secondary-fg-color); - background-color:var(--button-secondary-bg-color); - border-color:var(--button-secondary-border-color); - } - -.secondaryButton:is(:is(.dialog .mainContainer) button:not(:is(.toggle-button,.closeButton))):hover{ - color:var(--button-secondary-hover-fg-color); - background-color:var(--button-secondary-hover-bg-color); - border-color:var(--button-secondary-hover-border-color); - } - -.primaryButton:is(:is(.dialog .mainContainer) button:not(:is(.toggle-button,.closeButton))){ - color:var(--button-primary-fg-color); - background-color:var(--button-primary-bg-color); - border-color:var(--button-primary-border-color); - opacity:1; - } - -.primaryButton:is(:is(.dialog .mainContainer) button:not(:is(.toggle-button,.closeButton))):hover{ - color:var(--button-primary-hover-fg-color); - background-color:var(--button-primary-hover-bg-color); - border-color:var(--button-primary-hover-border-color); - } - -:is(.dialog .mainContainer) a{ - color:var(--link-fg-color); - } - -:is(:is(.dialog .mainContainer) a):hover{ - color:var(--link-hover-fg-color); - } - -:is(.dialog .mainContainer) textarea{ - font:inherit; - padding:8px; - resize:none; - margin:0; - box-sizing:border-box; - border-radius:4px; - border:1px solid var(--textarea-border-color); - background:var(--textarea-bg-color); - color:var(--textarea-fg-color); - } - -:is(:is(.dialog .mainContainer) textarea):focus{ - outline-offset:0; - border-color:transparent; - } - -:is(:is(.dialog .mainContainer) textarea):disabled{ - pointer-events:none; - opacity:0.4; - } - -:is(.dialog .mainContainer) .messageBar{ - --message-bar-bg-color:#ffebcd; - --message-bar-fg-color:#15141a; - --message-bar-border-color:rgb(0 0 0 / 0.08); - --message-bar-icon:url(images/messageBar_warning.svg); - --message-bar-icon-color:#cd411e; - } - -@media (prefers-color-scheme: dark){ - -:is(.dialog .mainContainer) .messageBar{ - --message-bar-bg-color:#5a3100; - --message-bar-fg-color:#fbfbfe; - --message-bar-border-color:rgb(255 255 255 / 0.08); - --message-bar-icon-color:#e49c49; - } - } - -@media screen and (forced-colors: active){ - -:is(.dialog .mainContainer) .messageBar{ - --message-bar-bg-color:HighlightText; - --message-bar-fg-color:CanvasText; - --message-bar-border-color:CanvasText; - --message-bar-icon-color:CanvasText; - } - } - -:is(.dialog .mainContainer) .messageBar{ - - align-self:stretch; - } - -:is(:is(:is(.dialog .mainContainer) .messageBar) > div)::before,:is(:is(:is(.dialog .mainContainer) .messageBar) > div) > div{ - margin-block:4px; - } - -:is(:is(:is(.dialog .mainContainer) .messageBar) > div) > div{ - display:flex; - flex-direction:column; - align-items:flex-start; - gap:8px; - flex:1 0 0; - } - -:is(:is(:is(:is(.dialog .mainContainer) .messageBar) > div) > div) .title{ - font-size:13px; - font-weight:590; - } - -:is(:is(:is(:is(.dialog .mainContainer) .messageBar) > div) > div) .description{ - font-size:13px; - } - -:is(.dialog .mainContainer) .toggler{ - display:flex; - align-items:center; - gap:8px; - align-self:stretch; - } - -:is(:is(.dialog .mainContainer) .toggler) > .togglerLabel{ - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; - } - -.textLayer{ - position:absolute; - text-align:initial; - inset:0; - overflow:clip; - opacity:1; - line-height:1; - -webkit-text-size-adjust:none; - -moz-text-size-adjust:none; - text-size-adjust:none; - forced-color-adjust:none; - transform-origin:0 0; - caret-color:CanvasText; - z-index:0; -} - -.textLayer.highlighting{ - touch-action:none; - } - -.textLayer :is(span,br){ - color:transparent; - position:absolute; - white-space:pre; - cursor:text; - transform-origin:0% 0%; - } - -.textLayer > :not(.markedContent),.textLayer .markedContent span:not(.markedContent){ - z-index:1; - } - -.textLayer span.markedContent{ - top:0; - height:0; - } - -.textLayer span[role="img"]{ - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; - cursor:default; - } - -.textLayer .highlight{ - --highlight-bg-color:rgb(180 0 170 / 0.25); - --highlight-selected-bg-color:rgb(0 100 0 / 0.25); - --highlight-backdrop-filter:none; - --highlight-selected-backdrop-filter:none; - } - -@media screen and (forced-colors: active){ - -.textLayer .highlight{ - --highlight-bg-color:transparent; - --highlight-selected-bg-color:transparent; - --highlight-backdrop-filter:var(--hcm-highlight-filter); - --highlight-selected-backdrop-filter:var( - --hcm-highlight-selected-filter - ); - } - } - -.textLayer .highlight{ - - margin:-1px; - padding:1px; - background-color:var(--highlight-bg-color); - -webkit-backdrop-filter:var(--highlight-backdrop-filter); - backdrop-filter:var(--highlight-backdrop-filter); - border-radius:4px; - } - -.appended:is(.textLayer .highlight){ - position:initial; - } - -.begin:is(.textLayer .highlight){ - border-radius:4px 0 0 4px; - } - -.end:is(.textLayer .highlight){ - border-radius:0 4px 4px 0; - } - -.middle:is(.textLayer .highlight){ - border-radius:0; - } - -.selected:is(.textLayer .highlight){ - background-color:var(--highlight-selected-bg-color); - -webkit-backdrop-filter:var(--highlight-selected-backdrop-filter); - backdrop-filter:var(--highlight-selected-backdrop-filter); - } - -.textLayer ::-moz-selection{ - background:rgba(0 0 255 / 0.25); - background:color-mix(in srgb, AccentColor, transparent 75%); - } - -.textLayer ::selection{ - background:rgba(0 0 255 / 0.25); - background:color-mix(in srgb, AccentColor, transparent 75%); - } - -.textLayer br::-moz-selection{ - background:transparent; - } - -.textLayer br::selection{ - background:transparent; - } - -.textLayer .endOfContent{ - display:block; - position:absolute; - inset:100% 0 0; - z-index:0; - cursor:default; - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; - } - -.textLayer.selecting .endOfContent{ - top:0; - } - -.annotationLayer{ - --annotation-unfocused-field-background:url("data:image/svg+xml;charset=UTF-8,"); - --input-focus-border-color:Highlight; - --input-focus-outline:1px solid Canvas; - --input-unfocused-border-color:transparent; - --input-disabled-border-color:transparent; - --input-hover-border-color:black; - --link-outline:none; -} - -@media screen and (forced-colors: active){ - -.annotationLayer{ - --input-focus-border-color:CanvasText; - --input-unfocused-border-color:ActiveText; - --input-disabled-border-color:GrayText; - --input-hover-border-color:Highlight; - --link-outline:1.5px solid LinkText; -} - - .annotationLayer .textWidgetAnnotation :is(input,textarea):required,.annotationLayer .choiceWidgetAnnotation select:required,.annotationLayer .buttonWidgetAnnotation:is(.checkBox,.radioButton) input:required{ - outline:1.5px solid selectedItem; - } - - .annotationLayer .linkAnnotation{ - outline:var(--link-outline); - } - - :is(.annotationLayer .linkAnnotation):hover{ - -webkit-backdrop-filter:var(--hcm-highlight-filter); - backdrop-filter:var(--hcm-highlight-filter); - } - - :is(.annotationLayer .linkAnnotation) > a:hover{ - opacity:0 !important; - background:none !important; - box-shadow:none; - } - - .annotationLayer .popupAnnotation .popup{ - outline:calc(1.5px * var(--scale-factor)) solid CanvasText !important; - background-color:ButtonFace !important; - color:ButtonText !important; - } - - .annotationLayer .highlightArea:hover::after{ - position:absolute; - top:0; - left:0; - width:100%; - height:100%; - -webkit-backdrop-filter:var(--hcm-highlight-filter); - backdrop-filter:var(--hcm-highlight-filter); - content:""; - pointer-events:none; - } - - .annotationLayer .popupAnnotation.focused .popup{ - outline:calc(3px * var(--scale-factor)) solid Highlight !important; - } - } - -.annotationLayer{ - - position:absolute; - top:0; - left:0; - pointer-events:none; - transform-origin:0 0; -} - -.annotationLayer[data-main-rotation="90"] .norotate{ - transform:rotate(270deg) translateX(-100%); - } - -.annotationLayer[data-main-rotation="180"] .norotate{ - transform:rotate(180deg) translate(-100%, -100%); - } - -.annotationLayer[data-main-rotation="270"] .norotate{ - transform:rotate(90deg) translateY(-100%); - } - -.annotationLayer.disabled section,.annotationLayer.disabled .popup{ - pointer-events:none; - } - -.annotationLayer .annotationContent{ - position:absolute; - width:100%; - height:100%; - pointer-events:none; - } - -.freetext:is(.annotationLayer .annotationContent){ - background:transparent; - border:none; - inset:0; - overflow:visible; - white-space:nowrap; - font:10px sans-serif; - line-height:1.35; - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; - } - -.annotationLayer section{ - position:absolute; - text-align:initial; - pointer-events:auto; - box-sizing:border-box; - transform-origin:0 0; - } - -:is(.annotationLayer section):has(div.annotationContent) canvas.annotationContent{ - display:none; - } - -.textLayer.selecting ~ .annotationLayer section{ - pointer-events:none; - } - -.annotationLayer :is(.linkAnnotation,.buttonWidgetAnnotation.pushButton) > a{ - position:absolute; - font-size:1em; - top:0; - left:0; - width:100%; - height:100%; - } - -.annotationLayer :is(.linkAnnotation,.buttonWidgetAnnotation.pushButton):not(.hasBorder) > a:hover{ - opacity:0.2; - background-color:rgb(255 255 0); - box-shadow:0 2px 10px rgb(255 255 0); - } - -.annotationLayer .linkAnnotation.hasBorder:hover{ - background-color:rgb(255 255 0 / 0.2); - } - -.annotationLayer .hasBorder{ - background-size:100% 100%; - } - -.annotationLayer .textAnnotation img{ - position:absolute; - cursor:pointer; - width:100%; - height:100%; - top:0; - left:0; - } - -.annotationLayer .textWidgetAnnotation :is(input,textarea),.annotationLayer .choiceWidgetAnnotation select,.annotationLayer .buttonWidgetAnnotation:is(.checkBox,.radioButton) input{ - background-image:var(--annotation-unfocused-field-background); - border:2px solid var(--input-unfocused-border-color); - box-sizing:border-box; - font:calc(9px * var(--scale-factor)) sans-serif; - height:100%; - margin:0; - vertical-align:top; - width:100%; - } - -.annotationLayer .textWidgetAnnotation :is(input,textarea):required,.annotationLayer .choiceWidgetAnnotation select:required,.annotationLayer .buttonWidgetAnnotation:is(.checkBox,.radioButton) input:required{ - outline:1.5px solid red; - } - -.annotationLayer .choiceWidgetAnnotation select option{ - padding:0; - } - -.annotationLayer .buttonWidgetAnnotation.radioButton input{ - border-radius:50%; - } - -.annotationLayer .textWidgetAnnotation textarea{ - resize:none; - } - -.annotationLayer .textWidgetAnnotation [disabled]:is(input,textarea),.annotationLayer .choiceWidgetAnnotation select[disabled],.annotationLayer .buttonWidgetAnnotation:is(.checkBox,.radioButton) input[disabled]{ - background:none; - border:2px solid var(--input-disabled-border-color); - cursor:not-allowed; - } - -.annotationLayer .textWidgetAnnotation :is(input,textarea):hover,.annotationLayer .choiceWidgetAnnotation select:hover,.annotationLayer .buttonWidgetAnnotation:is(.checkBox,.radioButton) input:hover{ - border:2px solid var(--input-hover-border-color); - } - -.annotationLayer .textWidgetAnnotation :is(input,textarea):hover,.annotationLayer .choiceWidgetAnnotation select:hover,.annotationLayer .buttonWidgetAnnotation.checkBox input:hover{ - border-radius:2px; - } - -.annotationLayer .textWidgetAnnotation :is(input,textarea):focus,.annotationLayer .choiceWidgetAnnotation select:focus{ - background:none; - border:2px solid var(--input-focus-border-color); - border-radius:2px; - outline:var(--input-focus-outline); - } - -.annotationLayer .buttonWidgetAnnotation:is(.checkBox,.radioButton) :focus{ - background-image:none; - background-color:transparent; - } - -.annotationLayer .buttonWidgetAnnotation.checkBox :focus{ - border:2px solid var(--input-focus-border-color); - border-radius:2px; - outline:var(--input-focus-outline); - } - -.annotationLayer .buttonWidgetAnnotation.radioButton :focus{ - border:2px solid var(--input-focus-border-color); - outline:var(--input-focus-outline); - } - -.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::before,.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::after,.annotationLayer .buttonWidgetAnnotation.radioButton input:checked::before{ - background-color:CanvasText; - content:""; - display:block; - position:absolute; - } - -.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::before,.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::after{ - height:80%; - left:45%; - width:1px; - } - -.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::before{ - transform:rotate(45deg); - } - -.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::after{ - transform:rotate(-45deg); - } - -.annotationLayer .buttonWidgetAnnotation.radioButton input:checked::before{ - border-radius:50%; - height:50%; - left:25%; - top:25%; - width:50%; - } - -.annotationLayer .textWidgetAnnotation input.comb{ - font-family:monospace; - padding-left:2px; - padding-right:0; - } - -.annotationLayer .textWidgetAnnotation input.comb:focus{ - width:103%; - } - -.annotationLayer .buttonWidgetAnnotation:is(.checkBox,.radioButton) input{ - -webkit-appearance:none; - -moz-appearance:none; - appearance:none; - } - -.annotationLayer .fileAttachmentAnnotation .popupTriggerArea{ - height:100%; - width:100%; - } - -.annotationLayer .popupAnnotation{ - position:absolute; - font-size:calc(9px * var(--scale-factor)); - pointer-events:none; - width:-moz-max-content; - width:max-content; - max-width:45%; - height:auto; - } - -.annotationLayer .popup{ - background-color:rgb(255 255 153); - box-shadow:0 calc(2px * var(--scale-factor)) calc(5px * var(--scale-factor)) rgb(136 136 136); - border-radius:calc(2px * var(--scale-factor)); - outline:1.5px solid rgb(255 255 74); - padding:calc(6px * var(--scale-factor)); - cursor:pointer; - font:message-box; - white-space:normal; - word-wrap:break-word; - pointer-events:auto; - } - -.annotationLayer .popupAnnotation.focused .popup{ - outline-width:3px; - } - -.annotationLayer .popup *{ - font-size:calc(9px * var(--scale-factor)); - } - -.annotationLayer .popup > .header{ - display:inline-block; - } - -.annotationLayer .popup > .header h1{ - display:inline; - } - -.annotationLayer .popup > .header .popupDate{ - display:inline-block; - margin-left:calc(5px * var(--scale-factor)); - width:-moz-fit-content; - width:fit-content; - } - -.annotationLayer .popupContent{ - border-top:1px solid rgb(51 51 51); - margin-top:calc(2px * var(--scale-factor)); - padding-top:calc(2px * var(--scale-factor)); - } - -.annotationLayer .richText > *{ - white-space:pre-wrap; - font-size:calc(9px * var(--scale-factor)); - } - -.annotationLayer .popupTriggerArea{ - cursor:pointer; - } - -.annotationLayer section svg{ - position:absolute; - width:100%; - height:100%; - top:0; - left:0; - } - -.annotationLayer .annotationTextContent{ - position:absolute; - width:100%; - height:100%; - opacity:0; - color:transparent; - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; - pointer-events:none; - } - -:is(.annotationLayer .annotationTextContent) span{ - width:100%; - display:inline-block; - } - -.annotationLayer svg.quadrilateralsContainer{ - contain:strict; - width:0; - height:0; - position:absolute; - top:0; - left:0; - z-index:-1; - } - -:root{ - --xfa-unfocused-field-background:url("data:image/svg+xml;charset=UTF-8,"); - --xfa-focus-outline:auto; -} - -@media screen and (forced-colors: active){ - :root{ - --xfa-focus-outline:2px solid CanvasText; - } - .xfaLayer *:required{ - outline:1.5px solid selectedItem; - } -} - -.xfaLayer{ - background-color:transparent; -} - -.xfaLayer .highlight{ - margin:-1px; - padding:1px; - background-color:rgb(239 203 237); - border-radius:4px; -} - -.xfaLayer .highlight.appended{ - position:initial; -} - -.xfaLayer .highlight.begin{ - border-radius:4px 0 0 4px; -} - -.xfaLayer .highlight.end{ - border-radius:0 4px 4px 0; -} - -.xfaLayer .highlight.middle{ - border-radius:0; -} - -.xfaLayer .highlight.selected{ - background-color:rgb(203 223 203); -} - -.xfaPage{ - overflow:hidden; - position:relative; -} - -.xfaContentarea{ - position:absolute; -} - -.xfaPrintOnly{ - display:none; -} - -.xfaLayer{ - position:absolute; - text-align:initial; - top:0; - left:0; - transform-origin:0 0; - line-height:1.2; -} - -.xfaLayer *{ - color:inherit; - font:inherit; - font-style:inherit; - font-weight:inherit; - font-kerning:inherit; - letter-spacing:-0.01px; - text-align:inherit; - text-decoration:inherit; - box-sizing:border-box; - background-color:transparent; - padding:0; - margin:0; - pointer-events:auto; - line-height:inherit; -} - -.xfaLayer *:required{ - outline:1.5px solid red; -} - -.xfaLayer div, -.xfaLayer svg, -.xfaLayer svg *{ - pointer-events:none; -} - -.xfaLayer a{ - color:blue; -} - -.xfaRich li{ - margin-left:3em; -} - -.xfaFont{ - color:black; - font-weight:normal; - font-kerning:none; - font-size:10px; - font-style:normal; - letter-spacing:0; - text-decoration:none; - vertical-align:0; -} - -.xfaCaption{ - overflow:hidden; - flex:0 0 auto; -} - -.xfaCaptionForCheckButton{ - overflow:hidden; - flex:1 1 auto; -} - -.xfaLabel{ - height:100%; - width:100%; -} - -.xfaLeft{ - display:flex; - flex-direction:row; - align-items:center; -} - -.xfaRight{ - display:flex; - flex-direction:row-reverse; - align-items:center; -} - -:is(.xfaLeft, .xfaRight) > :is(.xfaCaption, .xfaCaptionForCheckButton){ - max-height:100%; -} - -.xfaTop{ - display:flex; - flex-direction:column; - align-items:flex-start; -} - -.xfaBottom{ - display:flex; - flex-direction:column-reverse; - align-items:flex-start; -} - -:is(.xfaTop, .xfaBottom) > :is(.xfaCaption, .xfaCaptionForCheckButton){ - width:100%; -} - -.xfaBorder{ - background-color:transparent; - position:absolute; - pointer-events:none; -} - -.xfaWrapped{ - width:100%; - height:100%; -} - -:is(.xfaTextfield, .xfaSelect):focus{ - background-image:none; - background-color:transparent; - outline:var(--xfa-focus-outline); - outline-offset:-1px; -} - -:is(.xfaCheckbox, .xfaRadio):focus{ - outline:var(--xfa-focus-outline); -} - -.xfaTextfield, -.xfaSelect{ - height:100%; - width:100%; - flex:1 1 auto; - border:none; - resize:none; - background-image:var(--xfa-unfocused-field-background); -} - -.xfaSelect{ - padding-inline:2px; -} - -:is(.xfaTop, .xfaBottom) > :is(.xfaTextfield, .xfaSelect){ - flex:0 1 auto; -} - -.xfaButton{ - cursor:pointer; - width:100%; - height:100%; - border:none; - text-align:center; -} - -.xfaLink{ - width:100%; - height:100%; - position:absolute; - top:0; - left:0; -} - -.xfaCheckbox, -.xfaRadio{ - width:100%; - height:100%; - flex:0 0 auto; - border:none; -} - -.xfaRich{ - white-space:pre-wrap; - width:100%; - height:100%; -} - -.xfaImage{ - -o-object-position:left top; - object-position:left top; - -o-object-fit:contain; - object-fit:contain; - width:100%; - height:100%; -} - -.xfaLrTb, -.xfaRlTb, -.xfaTb{ - display:flex; - flex-direction:column; - align-items:stretch; -} - -.xfaLr{ - display:flex; - flex-direction:row; - align-items:stretch; -} - -.xfaRl{ - display:flex; - flex-direction:row-reverse; - align-items:stretch; -} - -.xfaTb > div{ - justify-content:left; -} - -.xfaPosition{ - position:relative; -} - -.xfaArea{ - position:relative; -} - -.xfaValignMiddle{ - display:flex; - align-items:center; -} - -.xfaTable{ - display:flex; - flex-direction:column; - align-items:stretch; -} - -.xfaTable .xfaRow{ - display:flex; - flex-direction:row; - align-items:stretch; -} - -.xfaTable .xfaRlRow{ - display:flex; - flex-direction:row-reverse; - align-items:stretch; - flex:1; -} - -.xfaTable .xfaRlRow > div{ - flex:1; -} - -:is(.xfaNonInteractive, .xfaDisabled, .xfaReadOnly) :is(input, textarea){ - background:initial; -} - -@media print{ - .xfaTextfield, - .xfaSelect{ - background:transparent; - } - - .xfaSelect{ - -webkit-appearance:none; - -moz-appearance:none; - appearance:none; - text-indent:1px; - text-overflow:""; - } -} - -.canvasWrapper svg{ - transform:none; - } - -.moving:is(.canvasWrapper svg){ - z-index:100000; - } - -[data-main-rotation="90"]:is(.highlight:is(.canvasWrapper svg),.highlightOutline:is(.canvasWrapper svg)) mask,[data-main-rotation="90"]:is(.highlight:is(.canvasWrapper svg),.highlightOutline:is(.canvasWrapper svg)) use:not(.clip,.mask){ - transform:matrix(0, 1, -1, 0, 1, 0); - } - -[data-main-rotation="180"]:is(.highlight:is(.canvasWrapper svg),.highlightOutline:is(.canvasWrapper svg)) mask,[data-main-rotation="180"]:is(.highlight:is(.canvasWrapper svg),.highlightOutline:is(.canvasWrapper svg)) use:not(.clip,.mask){ - transform:matrix(-1, 0, 0, -1, 1, 1); - } - -[data-main-rotation="270"]:is(.highlight:is(.canvasWrapper svg),.highlightOutline:is(.canvasWrapper svg)) mask,[data-main-rotation="270"]:is(.highlight:is(.canvasWrapper svg),.highlightOutline:is(.canvasWrapper svg)) use:not(.clip,.mask){ - transform:matrix(0, -1, 1, 0, 0, 1); - } - -.draw:is(.canvasWrapper svg){ - position:absolute; - mix-blend-mode:normal; - } - -.draw[data-draw-rotation="90"]:is(.canvasWrapper svg){ - transform:rotate(90deg); - } - -.draw[data-draw-rotation="180"]:is(.canvasWrapper svg){ - transform:rotate(180deg); - } - -.draw[data-draw-rotation="270"]:is(.canvasWrapper svg){ - transform:rotate(270deg); - } - -.highlight:is(.canvasWrapper svg){ - --blend-mode:multiply; - } - -@media screen and (forced-colors: active){ - -.highlight:is(.canvasWrapper svg){ - --blend-mode:difference; - } - } - -.highlight:is(.canvasWrapper svg){ - - position:absolute; - mix-blend-mode:var(--blend-mode); - } - -.highlight:is(.canvasWrapper svg):not(.free){ - fill-rule:evenodd; - } - -.highlightOutline:is(.canvasWrapper svg){ - position:absolute; - mix-blend-mode:normal; - fill-rule:evenodd; - fill:none; - } - -.highlightOutline.hovered:is(.canvasWrapper svg):not(.free):not(.selected){ - stroke:var(--hover-outline-color); - stroke-width:var(--outline-width); - } - -.highlightOutline.selected:is(.canvasWrapper svg):not(.free) .mainOutline{ - stroke:var(--outline-around-color); - stroke-width:calc( - var(--outline-width) + 2 * var(--outline-around-width) - ); - } - -.highlightOutline.selected:is(.canvasWrapper svg):not(.free) .secondaryOutline{ - stroke:var(--outline-color); - stroke-width:var(--outline-width); - } - -.highlightOutline.free.hovered:is(.canvasWrapper svg):not(.selected){ - stroke:var(--hover-outline-color); - stroke-width:calc(2 * var(--outline-width)); - } - -.highlightOutline.free.selected:is(.canvasWrapper svg) .mainOutline{ - stroke:var(--outline-around-color); - stroke-width:calc( - 2 * (var(--outline-width) + var(--outline-around-width)) - ); - } - -.highlightOutline.free.selected:is(.canvasWrapper svg) .secondaryOutline{ - stroke:var(--outline-color); - stroke-width:calc(2 * var(--outline-width)); - } - -.toggle-button{ - --button-background-color:#f0f0f4; - --button-background-color-hover:#e0e0e6; - --button-background-color-active:#cfcfd8; - --color-accent-primary:#0060df; - --color-accent-primary-hover:#0250bb; - --color-accent-primary-active:#054096; - --border-interactive-color:#8f8f9d; - --border-radius-circle:9999px; - --border-width:1px; - --size-item-small:16px; - --size-item-large:32px; - --color-canvas:white; -} - -@media (prefers-color-scheme: dark){ - -.toggle-button{ - --button-background-color:color-mix(in srgb, currentColor 7%, transparent); - --button-background-color-hover:color-mix( - in srgb, - currentColor 14%, - transparent - ); - --button-background-color-active:color-mix( - in srgb, - currentColor 21%, - transparent - ); - --color-accent-primary:#0df; - --color-accent-primary-hover:#80ebff; - --color-accent-primary-active:#aaf2ff; - --border-interactive-color:#bfbfc9; - --color-canvas:#1c1b22; -} - } - -@media (forced-colors: active){ - -.toggle-button{ - --color-accent-primary:ButtonText; - --color-accent-primary-hover:SelectedItem; - --color-accent-primary-active:SelectedItem; - --border-interactive-color:ButtonText; - --button-background-color:ButtonFace; - --border-interactive-color-hover:SelectedItem; - --border-interactive-color-active:SelectedItem; - --border-interactive-color-disabled:GrayText; - --color-canvas:ButtonText; -} - } - -.toggle-button{ - - --toggle-background-color:var(--button-background-color); - --toggle-background-color-hover:var(--button-background-color-hover); - --toggle-background-color-active:var(--button-background-color-active); - --toggle-background-color-pressed:var(--color-accent-primary); - --toggle-background-color-pressed-hover:var(--color-accent-primary-hover); - --toggle-background-color-pressed-active:var(--color-accent-primary-active); - --toggle-border-color:var(--border-interactive-color); - --toggle-border-color-hover:var(--toggle-border-color); - --toggle-border-color-active:var(--toggle-border-color); - --toggle-border-radius:var(--border-radius-circle); - --toggle-border-width:var(--border-width); - --toggle-height:var(--size-item-small); - --toggle-width:var(--size-item-large); - --toggle-dot-background-color:var(--toggle-border-color); - --toggle-dot-background-color-hover:var(--toggle-dot-background-color); - --toggle-dot-background-color-active:var(--toggle-dot-background-color); - --toggle-dot-background-color-on-pressed:var(--color-canvas); - --toggle-dot-margin:1px; - --toggle-dot-height:calc( - var(--toggle-height) - 2 * var(--toggle-dot-margin) - 2 * - var(--toggle-border-width) - ); - --toggle-dot-width:var(--toggle-dot-height); - --toggle-dot-transform-x:calc( - var(--toggle-width) - 4 * var(--toggle-dot-margin) - var(--toggle-dot-width) - ); - - -webkit-appearance:none; - - -moz-appearance:none; - - appearance:none; - padding:0; - margin:0; - border:var(--toggle-border-width) solid var(--toggle-border-color); - height:var(--toggle-height); - width:var(--toggle-width); - border-radius:var(--toggle-border-radius); - background:var(--toggle-background-color); - box-sizing:border-box; - flex-shrink:0; -} - -.toggle-button:focus-visible{ - outline:var(--focus-outline); - outline-offset:var(--focus-outline-offset); - } - -.toggle-button:enabled:hover{ - background:var(--toggle-background-color-hover); - border-color:var(--toggle-border-color); - } - -.toggle-button:enabled:active{ - background:var(--toggle-background-color-active); - border-color:var(--toggle-border-color); - } - -.toggle-button[aria-pressed="true"]{ - background:var(--toggle-background-color-pressed); - border-color:transparent; - } - -.toggle-button[aria-pressed="true"]:enabled:hover{ - background:var(--toggle-background-color-pressed-hover); - border-color:transparent; - } - -.toggle-button[aria-pressed="true"]:enabled:active{ - background:var(--toggle-background-color-pressed-active); - border-color:transparent; - } - -.toggle-button::before{ - display:block; - content:""; - background-color:var(--toggle-dot-background-color); - height:var(--toggle-dot-height); - width:var(--toggle-dot-width); - margin:var(--toggle-dot-margin); - border-radius:var(--toggle-border-radius); - translate:0; - } - -.toggle-button[aria-pressed="true"]::before{ - translate:var(--toggle-dot-transform-x); - background-color:var(--toggle-dot-background-color-on-pressed); - } - -.toggle-button[aria-pressed="true"]:enabled:hover::before,.toggle-button[aria-pressed="true"]:enabled:active::before{ - background-color:var(--toggle-dot-background-color-on-pressed); - } - -[dir="rtl"] .toggle-button[aria-pressed="true"]::before{ - translate:calc(-1 * var(--toggle-dot-transform-x)); - } - -@media (prefers-reduced-motion: no-preference){ - .toggle-button::before{ - transition:translate 100ms; - } - } - -@media (prefers-contrast){ - .toggle-button:enabled:hover{ - border-color:var(--toggle-border-color-hover); - } - - .toggle-button:enabled:active{ - border-color:var(--toggle-border-color-active); - } - - .toggle-button[aria-pressed="true"]:enabled{ - border-color:var(--toggle-border-color); - position:relative; - } - - .toggle-button[aria-pressed="true"]:enabled:hover,.toggle-button[aria-pressed="true"]:enabled:hover:active{ - border-color:var(--toggle-border-color-hover); - } - - .toggle-button[aria-pressed="true"]:enabled:active{ - background-color:var(--toggle-dot-background-color-active); - border-color:var(--toggle-dot-background-color-hover); - } - - .toggle-button:hover::before,.toggle-button:active::before{ - background-color:var(--toggle-dot-background-color-hover); - } - } - -@media (forced-colors){ - -.toggle-button{ - --toggle-dot-background-color:var(--color-accent-primary); - --toggle-dot-background-color-hover:var(--color-accent-primary-hover); - --toggle-dot-background-color-active:var(--color-accent-primary-active); - --toggle-dot-background-color-on-pressed:var(--button-background-color); - --toggle-background-color-disabled:var(--button-background-color-disabled); - --toggle-border-color-hover:var(--border-interactive-color-hover); - --toggle-border-color-active:var(--border-interactive-color-active); - --toggle-border-color-disabled:var(--border-interactive-color-disabled); -} - - .toggle-button[aria-pressed="true"]:enabled::after{ - border:1px solid var(--button-background-color); - content:""; - position:absolute; - height:var(--toggle-height); - width:var(--toggle-width); - display:block; - border-radius:var(--toggle-border-radius); - inset:-2px; - } - - .toggle-button[aria-pressed="true"]:enabled:active::after{ - border-color:var(--toggle-border-color-active); - } - } - -:root{ - --outline-width:2px; - --outline-color:#0060df; - --outline-around-width:1px; - --outline-around-color:#f0f0f4; - --hover-outline-around-color:var(--outline-around-color); - --focus-outline:solid var(--outline-width) var(--outline-color); - --unfocus-outline:solid var(--outline-width) transparent; - --focus-outline-around:solid var(--outline-around-width) var(--outline-around-color); - --hover-outline-color:#8f8f9d; - --hover-outline:solid var(--outline-width) var(--hover-outline-color); - --hover-outline-around:solid var(--outline-around-width) var(--hover-outline-around-color); - --freetext-line-height:1.35; - --freetext-padding:2px; - --resizer-bg-color:var(--outline-color); - --resizer-size:6px; - --resizer-shift:calc( - 0px - (var(--outline-width) + var(--resizer-size)) / 2 - - var(--outline-around-width) - ); - --editorFreeText-editing-cursor:text; - --editorInk-editing-cursor:url(images/cursor-editorInk.svg) 0 16, pointer; - --editorHighlight-editing-cursor:url(images/cursor-editorTextHighlight.svg) 24 24, text; - --editorFreeHighlight-editing-cursor:url(images/cursor-editorFreeHighlight.svg) 1 18, pointer; - - --new-alt-text-warning-image:url(images/altText_warning.svg); -} -.visuallyHidden{ - position:absolute; - top:0; - left:0; - border:0; - margin:0; - padding:0; - width:0; - height:0; - overflow:hidden; - white-space:nowrap; - font-size:0; -} - -.textLayer.highlighting{ - cursor:var(--editorFreeHighlight-editing-cursor); - } - -.textLayer.highlighting:not(.free) span{ - cursor:var(--editorHighlight-editing-cursor); - } - -[role="img"]:is(.textLayer.highlighting:not(.free) span){ - cursor:var(--editorFreeHighlight-editing-cursor); - } - -.textLayer.highlighting.free span{ - cursor:var(--editorFreeHighlight-editing-cursor); - } - -:is(#viewerContainer.pdfPresentationMode:fullscreen,.annotationEditorLayer.disabled) .noAltTextBadge{ - display:none !important; - } - -@media (min-resolution: 1.1dppx){ - :root{ - --editorFreeText-editing-cursor:url(images/cursor-editorFreeText.svg) 0 16, text; - } -} - -@media screen and (forced-colors: active){ - :root{ - --outline-color:CanvasText; - --outline-around-color:ButtonFace; - --resizer-bg-color:ButtonText; - --hover-outline-color:Highlight; - --hover-outline-around-color:SelectedItemText; - } -} - -[data-editor-rotation="90"]{ - transform:rotate(90deg); -} - -[data-editor-rotation="180"]{ - transform:rotate(180deg); -} - -[data-editor-rotation="270"]{ - transform:rotate(270deg); -} - -.annotationEditorLayer{ - background:transparent; - position:absolute; - inset:0; - font-size:calc(100px * var(--scale-factor)); - transform-origin:0 0; - cursor:auto; -} - -.annotationEditorLayer .selectedEditor{ - z-index:100000 !important; - } - -.annotationEditorLayer.drawing *{ - pointer-events:none !important; - } - -.annotationEditorLayer.waiting{ - content:""; - cursor:wait; - position:absolute; - inset:0; - width:100%; - height:100%; -} - -.annotationEditorLayer.disabled{ - pointer-events:none; -} - -.annotationEditorLayer.freetextEditing{ - cursor:var(--editorFreeText-editing-cursor); -} - -.annotationEditorLayer.inkEditing{ - cursor:var(--editorInk-editing-cursor); -} - -.annotationEditorLayer .draw{ - box-sizing:border-box; -} - -.annotationEditorLayer :is(.freeTextEditor, .inkEditor, .stampEditor){ - position:absolute; - background:transparent; - z-index:1; - transform-origin:0 0; - cursor:auto; - max-width:100%; - max-height:100%; - border:var(--unfocus-outline); -} - -.draggable.selectedEditor:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)){ - cursor:move; - } - -.selectedEditor:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)){ - border:var(--focus-outline); - outline:var(--focus-outline-around); - } - -.selectedEditor:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor))::before{ - content:""; - position:absolute; - inset:0; - border:var(--focus-outline-around); - pointer-events:none; - } - -:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)):hover:not(.selectedEditor){ - border:var(--hover-outline); - outline:var(--hover-outline-around); - } - -:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)):hover:not(.selectedEditor)::before{ - content:""; - position:absolute; - inset:0; - border:var(--focus-outline-around); - } - -:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar{ - --editor-toolbar-delete-image:url(images/editor-toolbar-delete.svg); - --editor-toolbar-bg-color:#f0f0f4; - --editor-toolbar-highlight-image:url(images/toolbarButton-editorHighlight.svg); - --editor-toolbar-fg-color:#2e2e56; - --editor-toolbar-border-color:#8f8f9d; - --editor-toolbar-hover-border-color:var(--editor-toolbar-border-color); - --editor-toolbar-hover-bg-color:#e0e0e6; - --editor-toolbar-hover-fg-color:var(--editor-toolbar-fg-color); - --editor-toolbar-hover-outline:none; - --editor-toolbar-focus-outline-color:#0060df; - --editor-toolbar-shadow:0 2px 6px 0 rgb(58 57 68 / 0.2); - --editor-toolbar-vert-offset:6px; - --editor-toolbar-height:28px; - --editor-toolbar-padding:2px; - --alt-text-done-color:#2ac3a2; - --alt-text-warning-color:#0090ed; - --alt-text-hover-done-color:var(--alt-text-done-color); - --alt-text-hover-warning-color:var(--alt-text-warning-color); - } - -@media (prefers-color-scheme: dark){ - -:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar{ - --editor-toolbar-bg-color:#2b2a33; - --editor-toolbar-fg-color:#fbfbfe; - --editor-toolbar-hover-bg-color:#52525e; - --editor-toolbar-focus-outline-color:#0df; - --alt-text-done-color:#54ffbd; - --alt-text-warning-color:#80ebff; - } - } - -@media screen and (forced-colors: active){ - -:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar{ - --editor-toolbar-bg-color:ButtonFace; - --editor-toolbar-fg-color:ButtonText; - --editor-toolbar-border-color:ButtonText; - --editor-toolbar-hover-border-color:AccentColor; - --editor-toolbar-hover-bg-color:ButtonFace; - --editor-toolbar-hover-fg-color:AccentColor; - --editor-toolbar-hover-outline:2px solid var(--editor-toolbar-hover-border-color); - --editor-toolbar-focus-outline-color:ButtonBorder; - --editor-toolbar-shadow:none; - --alt-text-done-color:var(--editor-toolbar-fg-color); - --alt-text-warning-color:var(--editor-toolbar-fg-color); - --alt-text-hover-done-color:var(--editor-toolbar-hover-fg-color); - --alt-text-hover-warning-color:var(--editor-toolbar-hover-fg-color); - } - } - -:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar{ - - display:flex; - width:-moz-fit-content; - width:fit-content; - height:var(--editor-toolbar-height); - flex-direction:column; - justify-content:center; - align-items:center; - cursor:default; - pointer-events:auto; - box-sizing:content-box; - padding:var(--editor-toolbar-padding); - - position:absolute; - inset-inline-end:0; - inset-block-start:calc(100% + var(--editor-toolbar-vert-offset)); - - border-radius:6px; - background-color:var(--editor-toolbar-bg-color); - border:1px solid var(--editor-toolbar-border-color); - box-shadow:var(--editor-toolbar-shadow); - } - -.hidden:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar){ - display:none; - } - -:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar):has(:focus-visible){ - border-color:transparent; - } - -[dir="ltr"] :is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar){ - transform-origin:100% 0; - } - -[dir="rtl"] :is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar){ - transform-origin:0 0; - } - -:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons{ - display:flex; - justify-content:center; - align-items:center; - gap:0; - height:100%; - } - -:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) button{ - padding:0; - } - -:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .divider{ - width:0; - height:calc( - 2 * var(--editor-toolbar-padding) + var(--editor-toolbar-height) - ); - border-left:1px solid var(--editor-toolbar-border-color); - border-right:none; - display:inline-block; - margin-inline:2px; - } - -:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .highlightButton{ - width:var(--editor-toolbar-height); - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .highlightButton)::before{ - content:""; - -webkit-mask-image:var(--editor-toolbar-highlight-image); - mask-image:var(--editor-toolbar-highlight-image); - -webkit-mask-repeat:no-repeat; - mask-repeat:no-repeat; - -webkit-mask-position:center; - mask-position:center; - display:inline-block; - background-color:var(--editor-toolbar-fg-color); - width:100%; - height:100%; - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .highlightButton):hover::before{ - background-color:var(--editor-toolbar-hover-fg-color); - } - -:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .delete{ - width:var(--editor-toolbar-height); - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .delete)::before{ - content:""; - -webkit-mask-image:var(--editor-toolbar-delete-image); - mask-image:var(--editor-toolbar-delete-image); - -webkit-mask-repeat:no-repeat; - mask-repeat:no-repeat; - -webkit-mask-position:center; - mask-position:center; - display:inline-block; - background-color:var(--editor-toolbar-fg-color); - width:100%; - height:100%; - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .delete):hover::before{ - background-color:var(--editor-toolbar-hover-fg-color); - } - -:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) > *{ - height:var(--editor-toolbar-height); - } - -:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) > :not(.divider){ - border:none; - background-color:transparent; - cursor:pointer; - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) > :not(.divider)):hover{ - border-radius:2px; - background-color:var(--editor-toolbar-hover-bg-color); - color:var(--editor-toolbar-hover-fg-color); - outline:var(--editor-toolbar-hover-outline); - outline-offset:1px; - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) > :not(.divider)):hover:active{ - outline:none; - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) > :not(.divider)):focus-visible{ - border-radius:2px; - outline:2px solid var(--editor-toolbar-focus-outline-color); - } - -:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText{ - --alt-text-add-image:url(images/altText_add.svg); - --alt-text-done-image:url(images/altText_done.svg); - - display:flex; - align-items:center; - justify-content:center; - width:-moz-max-content; - width:max-content; - padding-inline:8px; - pointer-events:all; - font:menu; - font-weight:590; - font-size:12px; - color:var(--editor-toolbar-fg-color); - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText):disabled{ - pointer-events:none; - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText)::before{ - content:""; - -webkit-mask-image:var(--alt-text-add-image); - mask-image:var(--alt-text-add-image); - -webkit-mask-repeat:no-repeat; - mask-repeat:no-repeat; - -webkit-mask-position:center; - mask-position:center; - display:inline-block; - width:12px; - height:13px; - background-color:var(--editor-toolbar-fg-color); - margin-inline-end:4px; - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText):hover::before{ - background-color:var(--editor-toolbar-hover-fg-color); - } - -.done:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText)::before{ - -webkit-mask-image:var(--alt-text-done-image); - mask-image:var(--alt-text-done-image); - } - -.new:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText)::before{ - width:16px; - height:16px; - -webkit-mask-image:var(--new-alt-text-warning-image); - mask-image:var(--new-alt-text-warning-image); - background-color:var(--alt-text-warning-color); - -webkit-mask-size:cover; - mask-size:cover; - } - -.new:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText):hover::before{ - background-color:var(--alt-text-hover-warning-color); - } - -.new.done:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText)::before{ - -webkit-mask-image:var(--alt-text-done-image); - mask-image:var(--alt-text-done-image); - background-color:var(--alt-text-done-color); - } - -.new.done:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText):hover::before{ - background-color:var(--alt-text-hover-done-color); - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText) .tooltip{ - display:none; - word-wrap:anywhere; - } - -.show:is(:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText) .tooltip){ - --alt-text-tooltip-bg:#f0f0f4; - --alt-text-tooltip-fg:#15141a; - --alt-text-tooltip-border:#8f8f9d; - --alt-text-tooltip-shadow:0px 2px 6px 0px rgb(58 57 68 / 0.2); - } - -@media (prefers-color-scheme: dark){ - -.show:is(:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText) .tooltip){ - --alt-text-tooltip-bg:#1c1b22; - --alt-text-tooltip-fg:#fbfbfe; - --alt-text-tooltip-shadow:0px 2px 6px 0px #15141a; - } - } - -@media screen and (forced-colors: active){ - -.show:is(:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText) .tooltip){ - --alt-text-tooltip-bg:Canvas; - --alt-text-tooltip-fg:CanvasText; - --alt-text-tooltip-border:CanvasText; - --alt-text-tooltip-shadow:none; - } - } - -.show:is(:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText) .tooltip){ - - display:inline-flex; - flex-direction:column; - align-items:center; - justify-content:center; - position:absolute; - top:calc(100% + 2px); - inset-inline-start:0; - padding-block:2px 3px; - padding-inline:3px; - max-width:300px; - width:-moz-max-content; - width:max-content; - height:auto; - font-size:12px; - - border:0.5px solid var(--alt-text-tooltip-border); - background:var(--alt-text-tooltip-bg); - box-shadow:var(--alt-text-tooltip-shadow); - color:var(--alt-text-tooltip-fg); - - pointer-events:none; - } - -.annotationEditorLayer .freeTextEditor{ - padding:calc(var(--freetext-padding) * var(--scale-factor)); - width:auto; - height:auto; - touch-action:none; -} - -.annotationEditorLayer .freeTextEditor .internal{ - background:transparent; - border:none; - inset:0; - overflow:visible; - white-space:nowrap; - font:10px sans-serif; - line-height:var(--freetext-line-height); - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; -} - -.annotationEditorLayer .freeTextEditor .overlay{ - position:absolute; - display:none; - background:transparent; - inset:0; - width:100%; - height:100%; -} - -.annotationEditorLayer freeTextEditor .overlay.enabled{ - display:block; -} - -.annotationEditorLayer .freeTextEditor .internal:empty::before{ - content:attr(default-content); - color:gray; -} - -.annotationEditorLayer .freeTextEditor .internal:focus{ - outline:none; - -webkit-user-select:auto; - -moz-user-select:auto; - user-select:auto; -} - -.annotationEditorLayer .inkEditor{ - width:100%; - height:100%; -} - -.annotationEditorLayer .inkEditor.editing{ - cursor:inherit; -} - -.annotationEditorLayer .inkEditor .inkEditorCanvas{ - position:absolute; - inset:0; - width:100%; - height:100%; - touch-action:none; -} - -.annotationEditorLayer .stampEditor{ - width:auto; - height:auto; -} - -:is(.annotationEditorLayer .stampEditor) canvas{ - position:absolute; - width:100%; - height:100%; - margin:0; - top:0; - left:0; - } - -:is(.annotationEditorLayer .stampEditor) .noAltTextBadge{ - --no-alt-text-badge-border-color:#f0f0f4; - --no-alt-text-badge-bg-color:#cfcfd8; - --no-alt-text-badge-fg-color:#5b5b66; - } - -@media (prefers-color-scheme: dark){ - -:is(.annotationEditorLayer .stampEditor) .noAltTextBadge{ - --no-alt-text-badge-border-color:#52525e; - --no-alt-text-badge-bg-color:#fbfbfe; - --no-alt-text-badge-fg-color:#15141a; - } - } - -@media screen and (forced-colors: active){ - -:is(.annotationEditorLayer .stampEditor) .noAltTextBadge{ - --no-alt-text-badge-border-color:ButtonText; - --no-alt-text-badge-bg-color:ButtonFace; - --no-alt-text-badge-fg-color:ButtonText; - } - } - -:is(.annotationEditorLayer .stampEditor) .noAltTextBadge{ - - position:absolute; - inset-inline-end:5px; - inset-block-end:5px; - display:inline-flex; - width:32px; - height:32px; - padding:3px; - justify-content:center; - align-items:center; - pointer-events:none; - z-index:1; - - border-radius:2px; - border:1px solid var(--no-alt-text-badge-border-color); - background:var(--no-alt-text-badge-bg-color); - } - -:is(:is(.annotationEditorLayer .stampEditor) .noAltTextBadge)::before{ - content:""; - display:inline-block; - width:16px; - height:16px; - -webkit-mask-image:var(--new-alt-text-warning-image); - mask-image:var(--new-alt-text-warning-image); - -webkit-mask-size:cover; - mask-size:cover; - background-color:var(--no-alt-text-badge-fg-color); - } - -:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers{ - position:absolute; - inset:0; - } - -.hidden:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers){ - display:none; - } - -:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer{ - width:var(--resizer-size); - height:var(--resizer-size); - background:content-box var(--resizer-bg-color); - border:var(--focus-outline-around); - border-radius:2px; - position:absolute; - } - -.topLeft:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer){ - top:var(--resizer-shift); - left:var(--resizer-shift); - } - -.topMiddle:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer){ - top:var(--resizer-shift); - left:calc(50% + var(--resizer-shift)); - } - -.topRight:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer){ - top:var(--resizer-shift); - right:var(--resizer-shift); - } - -.middleRight:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer){ - top:calc(50% + var(--resizer-shift)); - right:var(--resizer-shift); - } - -.bottomRight:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer){ - bottom:var(--resizer-shift); - right:var(--resizer-shift); - } - -.bottomMiddle:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer){ - bottom:var(--resizer-shift); - left:calc(50% + var(--resizer-shift)); - } - -.bottomLeft:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer){ - bottom:var(--resizer-shift); - left:var(--resizer-shift); - } - -.middleLeft:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer){ - top:calc(50% + var(--resizer-shift)); - left:var(--resizer-shift); - } - -.topLeft:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="180"],[data-editor-rotation="0"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="90"],[data-editor-rotation="270"])) > .resizers > .resizer),.bottomRight:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="180"],[data-editor-rotation="0"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="90"],[data-editor-rotation="270"])) > .resizers > .resizer){ - cursor:nwse-resize; - } - -.topMiddle:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="180"],[data-editor-rotation="0"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="90"],[data-editor-rotation="270"])) > .resizers > .resizer),.bottomMiddle:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="180"],[data-editor-rotation="0"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="90"],[data-editor-rotation="270"])) > .resizers > .resizer){ - cursor:ns-resize; - } - -.topRight:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="180"],[data-editor-rotation="0"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="90"],[data-editor-rotation="270"])) > .resizers > .resizer),.bottomLeft:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="180"],[data-editor-rotation="0"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="90"],[data-editor-rotation="270"])) > .resizers > .resizer){ - cursor:nesw-resize; - } - -.middleRight:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="180"],[data-editor-rotation="0"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="90"],[data-editor-rotation="270"])) > .resizers > .resizer),.middleLeft:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="180"],[data-editor-rotation="0"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="90"],[data-editor-rotation="270"])) > .resizers > .resizer){ - cursor:ew-resize; - } - -.topLeft:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="90"],[data-editor-rotation="270"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="180"],[data-editor-rotation="0"])) > .resizers > .resizer),.bottomRight:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="90"],[data-editor-rotation="270"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="180"],[data-editor-rotation="0"])) > .resizers > .resizer){ - cursor:nesw-resize; - } - -.topMiddle:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="90"],[data-editor-rotation="270"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="180"],[data-editor-rotation="0"])) > .resizers > .resizer),.bottomMiddle:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="90"],[data-editor-rotation="270"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="180"],[data-editor-rotation="0"])) > .resizers > .resizer){ - cursor:ew-resize; - } - -.topRight:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="90"],[data-editor-rotation="270"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="180"],[data-editor-rotation="0"])) > .resizers > .resizer),.bottomLeft:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="90"],[data-editor-rotation="270"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="180"],[data-editor-rotation="0"])) > .resizers > .resizer){ - cursor:nwse-resize; - } - -.middleRight:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="90"],[data-editor-rotation="270"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="180"],[data-editor-rotation="0"])) > .resizers > .resizer),.middleLeft:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="90"],[data-editor-rotation="270"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="180"],[data-editor-rotation="0"])) > .resizers > .resizer){ - cursor:ns-resize; - } - -:is(.annotationEditorLayer :is([data-main-rotation="0"] [data-editor-rotation="90"],[data-main-rotation="90"] [data-editor-rotation="0"],[data-main-rotation="180"] [data-editor-rotation="270"],[data-main-rotation="270"] [data-editor-rotation="180"])) .editToolbar{ - rotate:270deg; - } - -[dir="ltr"] :is(:is(.annotationEditorLayer :is([data-main-rotation="0"] [data-editor-rotation="90"],[data-main-rotation="90"] [data-editor-rotation="0"],[data-main-rotation="180"] [data-editor-rotation="270"],[data-main-rotation="270"] [data-editor-rotation="180"])) .editToolbar){ - inset-inline-end:calc(0px - var(--editor-toolbar-vert-offset)); - inset-block-start:0; - } - -[dir="rtl"] :is(:is(.annotationEditorLayer :is([data-main-rotation="0"] [data-editor-rotation="90"],[data-main-rotation="90"] [data-editor-rotation="0"],[data-main-rotation="180"] [data-editor-rotation="270"],[data-main-rotation="270"] [data-editor-rotation="180"])) .editToolbar){ - inset-inline-end:calc(100% + var(--editor-toolbar-vert-offset)); - inset-block-start:0; - } - -:is(.annotationEditorLayer :is([data-main-rotation="0"] [data-editor-rotation="180"],[data-main-rotation="90"] [data-editor-rotation="90"],[data-main-rotation="180"] [data-editor-rotation="0"],[data-main-rotation="270"] [data-editor-rotation="270"])) .editToolbar{ - rotate:180deg; - inset-inline-end:100%; - inset-block-start:calc(0pc - var(--editor-toolbar-vert-offset)); - } - -:is(.annotationEditorLayer :is([data-main-rotation="0"] [data-editor-rotation="270"],[data-main-rotation="90"] [data-editor-rotation="180"],[data-main-rotation="180"] [data-editor-rotation="90"],[data-main-rotation="270"] [data-editor-rotation="0"])) .editToolbar{ - rotate:90deg; - } - -[dir="ltr"] :is(:is(.annotationEditorLayer :is([data-main-rotation="0"] [data-editor-rotation="270"],[data-main-rotation="90"] [data-editor-rotation="180"],[data-main-rotation="180"] [data-editor-rotation="90"],[data-main-rotation="270"] [data-editor-rotation="0"])) .editToolbar){ - inset-inline-end:calc(100% + var(--editor-toolbar-vert-offset)); - inset-block-start:100%; - } - -[dir="rtl"] :is(:is(.annotationEditorLayer :is([data-main-rotation="0"] [data-editor-rotation="270"],[data-main-rotation="90"] [data-editor-rotation="180"],[data-main-rotation="180"] [data-editor-rotation="90"],[data-main-rotation="270"] [data-editor-rotation="0"])) .editToolbar){ - inset-inline-start:calc(0px - var(--editor-toolbar-vert-offset)); - inset-block-start:0; - } - -.dialog.altText::backdrop{ - -webkit-mask:url(#alttext-manager-mask); - mask:url(#alttext-manager-mask); - } - -.dialog.altText.positioned{ - margin:0; - } - -.dialog.altText #altTextContainer{ - width:300px; - height:-moz-fit-content; - height:fit-content; - display:inline-flex; - flex-direction:column; - align-items:flex-start; - gap:16px; - } - -:is(.dialog.altText #altTextContainer) #overallDescription{ - display:flex; - flex-direction:column; - align-items:flex-start; - gap:4px; - align-self:stretch; - } - -:is(:is(.dialog.altText #altTextContainer) #overallDescription) span{ - align-self:stretch; - } - -:is(:is(.dialog.altText #altTextContainer) #overallDescription) .title{ - font-size:13px; - font-style:normal; - font-weight:590; - } - -:is(.dialog.altText #altTextContainer) #addDescription{ - display:flex; - flex-direction:column; - align-items:stretch; - gap:8px; - } - -:is(:is(.dialog.altText #altTextContainer) #addDescription) .descriptionArea{ - flex:1; - padding-inline:24px 10px; - } - -:is(:is(:is(.dialog.altText #altTextContainer) #addDescription) .descriptionArea) textarea{ - width:100%; - min-height:75px; - } - -:is(.dialog.altText #altTextContainer) #buttons{ - display:flex; - justify-content:flex-end; - align-items:flex-start; - gap:8px; - align-self:stretch; - } - -.dialog.newAltText{ - --new-alt-text-ai-disclaimer-icon:url(images/altText_disclaimer.svg); - --new-alt-text-spinner-icon:url(images/altText_spinner.svg); - --preview-image-bg-color:#f0f0f4; - --preview-image-border:none; -} - -@media (prefers-color-scheme: dark){ - -.dialog.newAltText{ - --preview-image-bg-color:#2b2a33; -} - } - -@media screen and (forced-colors: active){ - -.dialog.newAltText{ - --preview-image-bg-color:ButtonFace; - --preview-image-border:1px solid ButtonText; -} - } - -.dialog.newAltText{ - - width:80%; - max-width:570px; - min-width:300px; - padding:0; -} - -.dialog.newAltText.noAi #newAltTextDisclaimer,.dialog.newAltText.noAi #newAltTextCreateAutomatically{ - display:none !important; - } - -.dialog.newAltText.aiInstalling #newAltTextCreateAutomatically{ - display:none !important; - } - -.dialog.newAltText.aiInstalling #newAltTextDownloadModel{ - display:flex !important; - } - -.dialog.newAltText.error #newAltTextNotNow{ - display:none !important; - } - -.dialog.newAltText.error #newAltTextCancel{ - display:inline-block !important; - } - -.dialog.newAltText:not(.error) #newAltTextError{ - display:none !important; - } - -.dialog.newAltText #newAltTextContainer{ - display:flex; - width:auto; - padding:16px; - flex-direction:column; - justify-content:flex-end; - align-items:flex-start; - gap:12px; - flex:0 1 auto; - line-height:normal; - } - -:is(.dialog.newAltText #newAltTextContainer) #mainContent{ - display:flex; - justify-content:flex-end; - align-items:flex-start; - gap:12px; - align-self:stretch; - flex:1 1 auto; - } - -:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionAndSettings{ - display:flex; - flex-direction:column; - align-items:flex-start; - gap:16px; - flex:1 0 0; - align-self:stretch; - } - -:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction{ - display:flex; - flex-direction:column; - align-items:flex-start; - gap:8px; - align-self:stretch; - flex:1 1 auto; - } - -:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescriptionContainer{ - width:100%; - height:70px; - position:relative; - } - -:is(:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescriptionContainer) textarea{ - width:100%; - height:100%; - padding:8px; - } - -:is(:is(:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescriptionContainer) textarea)::-moz-placeholder{ - color:var(--text-secondary-color); - } - -:is(:is(:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescriptionContainer) textarea)::placeholder{ - color:var(--text-secondary-color); - } - -:is(:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescriptionContainer) .altTextSpinner{ - display:none; - position:absolute; - width:16px; - height:16px; - inset-inline-start:8px; - inset-block-start:8px; - -webkit-mask-size:cover; - mask-size:cover; - background-color:var(--text-secondary-color); - pointer-events:none; - } - -.loading:is(:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescriptionContainer) textarea::-moz-placeholder{ - color:transparent; - } - -.loading:is(:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescriptionContainer) textarea::placeholder{ - color:transparent; - } - -.loading:is(:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescriptionContainer) .altTextSpinner{ - display:inline-block; - -webkit-mask-image:var(--new-alt-text-spinner-icon); - mask-image:var(--new-alt-text-spinner-icon); - } - -:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescription{ - font-size:11px; - } - -:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDisclaimer{ - display:flex; - flex-direction:row; - align-items:flex-start; - gap:4px; - font-size:11px; - } - -:is(:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDisclaimer)::before{ - content:""; - display:inline-block; - width:17px; - height:16px; - -webkit-mask-image:var(--new-alt-text-ai-disclaimer-icon); - mask-image:var(--new-alt-text-ai-disclaimer-icon); - -webkit-mask-size:cover; - mask-size:cover; - background-color:var(--text-secondary-color); - flex:1 0 auto; - } - -:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #newAltTextDownloadModel{ - display:flex; - align-items:center; - gap:4px; - align-self:stretch; - } - -:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #newAltTextDownloadModel)::before{ - content:""; - display:inline-block; - width:16px; - height:16px; - -webkit-mask-image:var(--new-alt-text-spinner-icon); - mask-image:var(--new-alt-text-spinner-icon); - -webkit-mask-size:cover; - mask-size:cover; - background-color:var(--text-secondary-color); - } - -:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #newAltTextImagePreview{ - width:180px; - aspect-ratio:1; - display:flex; - justify-content:center; - align-items:center; - flex:0 0 auto; - background-color:var(--preview-image-bg-color); - border:var(--preview-image-border); - } - -:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #newAltTextImagePreview) > canvas{ - max-width:100%; - max-height:100%; - } - -.colorPicker{ - --hover-outline-color:#0250bb; - --selected-outline-color:#0060df; - --swatch-border-color:#cfcfd8; -} - -@media (prefers-color-scheme: dark){ - -.colorPicker{ - --hover-outline-color:#80ebff; - --selected-outline-color:#aaf2ff; - --swatch-border-color:#52525e; -} - } - -@media screen and (forced-colors: active){ - -.colorPicker{ - --hover-outline-color:Highlight; - --selected-outline-color:var(--hover-outline-color); - --swatch-border-color:ButtonText; -} - } - -.colorPicker .swatch{ - width:16px; - height:16px; - border:1px solid var(--swatch-border-color); - border-radius:100%; - outline-offset:2px; - box-sizing:border-box; - forced-color-adjust:none; - } - -.colorPicker button:is(:hover,.selected) > .swatch{ - border:none; - } - -.annotationEditorLayer[data-main-rotation="0"] .highlightEditor:not(.free) > .editToolbar{ - rotate:0deg; - } - -.annotationEditorLayer[data-main-rotation="90"] .highlightEditor:not(.free) > .editToolbar{ - rotate:270deg; - } - -.annotationEditorLayer[data-main-rotation="180"] .highlightEditor:not(.free) > .editToolbar{ - rotate:180deg; - } - -.annotationEditorLayer[data-main-rotation="270"] .highlightEditor:not(.free) > .editToolbar{ - rotate:90deg; - } - -.annotationEditorLayer .highlightEditor{ - position:absolute; - background:transparent; - z-index:1; - cursor:auto; - max-width:100%; - max-height:100%; - border:none; - outline:none; - pointer-events:none; - transform-origin:0 0; - } - -:is(.annotationEditorLayer .highlightEditor):not(.free){ - transform:none; - } - -:is(.annotationEditorLayer .highlightEditor) .internal{ - position:absolute; - top:0; - left:0; - width:100%; - height:100%; - pointer-events:auto; - } - -.disabled:is(.annotationEditorLayer .highlightEditor) .internal{ - pointer-events:none; - } - -.selectedEditor:is(.annotationEditorLayer .highlightEditor) .internal{ - cursor:pointer; - } - -:is(.annotationEditorLayer .highlightEditor) .editToolbar{ - --editor-toolbar-colorpicker-arrow-image:url(images/toolbarButton-menuArrow.svg); - - transform-origin:center !important; - } - -:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker{ - position:relative; - width:auto; - display:flex; - justify-content:center; - align-items:center; - gap:4px; - padding:4px; - } - -:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker)::after{ - content:""; - -webkit-mask-image:var(--editor-toolbar-colorpicker-arrow-image); - mask-image:var(--editor-toolbar-colorpicker-arrow-image); - -webkit-mask-repeat:no-repeat; - mask-repeat:no-repeat; - -webkit-mask-position:center; - mask-position:center; - display:inline-block; - background-color:var(--editor-toolbar-fg-color); - width:12px; - height:12px; - } - -:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker):hover::after{ - background-color:var(--editor-toolbar-hover-fg-color); - } - -:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker):has(.dropdown:not(.hidden)){ - background-color:var(--editor-toolbar-hover-bg-color); - } - -:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker):has(.dropdown:not(.hidden))::after{ - scale:-1; - } - -:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker) .dropdown{ - position:absolute; - display:flex; - justify-content:center; - align-items:center; - flex-direction:column; - gap:11px; - padding-block:8px; - border-radius:6px; - background-color:var(--editor-toolbar-bg-color); - border:1px solid var(--editor-toolbar-border-color); - box-shadow:var(--editor-toolbar-shadow); - inset-block-start:calc(100% + 4px); - width:calc(100% + 2 * var(--editor-toolbar-padding)); - } - -:is(:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker) .dropdown) button{ - width:100%; - height:auto; - border:none; - cursor:pointer; - display:flex; - justify-content:center; - align-items:center; - background:none; - } - -:is(:is(:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker) .dropdown) button):is(:active,:focus-visible){ - outline:none; - } - -:is(:is(:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker) .dropdown) button) > .swatch{ - outline-offset:2px; - } - -[aria-selected="true"]:is(:is(:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker) .dropdown) button) > .swatch{ - outline:2px solid var(--selected-outline-color); - } - -:is(:is(:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker) .dropdown) button):is(:hover,:active,:focus-visible) > .swatch{ - outline:2px solid var(--hover-outline-color); - } - -.editorParamsToolbar:has(#highlightParamsToolbarContainer){ - padding:unset; -} - -#highlightParamsToolbarContainer{ - gap:16px; - padding-inline:10px; - padding-block-end:12px; -} - -#highlightParamsToolbarContainer .colorPicker{ - display:flex; - flex-direction:column; - gap:8px; - } - -:is(#highlightParamsToolbarContainer .colorPicker) .dropdown{ - display:flex; - justify-content:space-between; - align-items:center; - flex-direction:row; - height:auto; - } - -:is(:is(#highlightParamsToolbarContainer .colorPicker) .dropdown) button{ - width:auto; - height:auto; - border:none; - cursor:pointer; - display:flex; - justify-content:center; - align-items:center; - background:none; - flex:0 0 auto; - padding:0; - } - -:is(:is(:is(#highlightParamsToolbarContainer .colorPicker) .dropdown) button) .swatch{ - width:24px; - height:24px; - } - -:is(:is(:is(#highlightParamsToolbarContainer .colorPicker) .dropdown) button):is(:active,:focus-visible){ - outline:none; - } - -[aria-selected="true"]:is(:is(:is(#highlightParamsToolbarContainer .colorPicker) .dropdown) button) > .swatch{ - outline:2px solid var(--selected-outline-color); - } - -:is(:is(:is(#highlightParamsToolbarContainer .colorPicker) .dropdown) button):is(:hover,:active,:focus-visible) > .swatch{ - outline:2px solid var(--hover-outline-color); - } - -#highlightParamsToolbarContainer #editorHighlightThickness{ - display:flex; - flex-direction:column; - align-items:center; - gap:4px; - align-self:stretch; - } - -:is(#highlightParamsToolbarContainer #editorHighlightThickness) .editorParamsLabel{ - height:auto; - align-self:stretch; - } - -:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker{ - display:flex; - justify-content:space-between; - align-items:center; - align-self:stretch; - - --example-color:#bfbfc9; - } - -@media (prefers-color-scheme: dark){ - -:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker{ - --example-color:#80808e; - } - } - -@media screen and (forced-colors: active){ - -:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker{ - --example-color:CanvasText; - } - } - -:is(:is(:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker) > .editorParamsSlider[disabled]){ - opacity:0.4; - } - -:is(:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker)::before,:is(:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker)::after{ - content:""; - width:8px; - aspect-ratio:1; - display:block; - border-radius:100%; - background-color:var(--example-color); - } - -:is(:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker)::after{ - width:24px; - } - -:is(:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker) .editorParamsSlider{ - width:unset; - height:14px; - } - -#highlightParamsToolbarContainer #editorHighlightVisibility{ - display:flex; - flex-direction:column; - align-items:flex-start; - gap:8px; - align-self:stretch; - } - -:is(#highlightParamsToolbarContainer #editorHighlightVisibility) .divider{ - --divider-color:#d7d7db; - } - -@media (prefers-color-scheme: dark){ - -:is(#highlightParamsToolbarContainer #editorHighlightVisibility) .divider{ - --divider-color:#8f8f9d; - } - } - -@media screen and (forced-colors: active){ - -:is(#highlightParamsToolbarContainer #editorHighlightVisibility) .divider{ - --divider-color:CanvasText; - } - } - -:is(#highlightParamsToolbarContainer #editorHighlightVisibility) .divider{ - - margin-block:4px; - width:100%; - height:1px; - background-color:var(--divider-color); - } - -:is(#highlightParamsToolbarContainer #editorHighlightVisibility) .toggler{ - display:flex; - justify-content:space-between; - align-items:center; - align-self:stretch; - } - -#altTextSettingsDialog{ - padding:16px; -} - -#altTextSettingsDialog #altTextSettingsContainer{ - display:flex; - width:573px; - flex-direction:column; - gap:16px; - } - -:is(#altTextSettingsDialog #altTextSettingsContainer) .mainContainer{ - gap:16px; - } - -:is(#altTextSettingsDialog #altTextSettingsContainer) .description{ - color:var(--text-secondary-color); - } - -:is(#altTextSettingsDialog #altTextSettingsContainer) #aiModelSettings{ - display:flex; - flex-direction:column; - gap:12px; - } - -:is(:is(#altTextSettingsDialog #altTextSettingsContainer) #aiModelSettings) button{ - width:-moz-fit-content; - width:fit-content; - } - -.download:is(:is(#altTextSettingsDialog #altTextSettingsContainer) #aiModelSettings) #deleteModelButton{ - display:none; - } - -:is(:is(#altTextSettingsDialog #altTextSettingsContainer) #aiModelSettings):not(.download) #downloadModelButton{ - display:none; - } - -:is(#altTextSettingsDialog #altTextSettingsContainer) #automaticAltText,:is(#altTextSettingsDialog #altTextSettingsContainer) #altTextEditor{ - display:flex; - flex-direction:column; - gap:8px; - } - -:is(#altTextSettingsDialog #altTextSettingsContainer) #createModelDescription,:is(#altTextSettingsDialog #altTextSettingsContainer) #aiModelSettings,:is(#altTextSettingsDialog #altTextSettingsContainer) #showAltTextDialogDescription{ - padding-inline-start:40px; - } - -:is(#altTextSettingsDialog #altTextSettingsContainer) #automaticSettings{ - display:flex; - flex-direction:column; - gap:16px; - } - -:root{ - --viewer-container-height:0; - --pdfViewer-padding-bottom:0; - --page-margin:1px auto -8px; - --page-border:9px solid transparent; - --spreadHorizontalWrapped-margin-LR:-3.5px; - --loading-icon-delay:400ms; -} - -@media screen and (forced-colors: active){ - :root{ - --pdfViewer-padding-bottom:9px; - --page-margin:8px auto -1px; - --page-border:1px solid CanvasText; - --spreadHorizontalWrapped-margin-LR:3.5px; - } -} - -[data-main-rotation="90"]{ - transform:rotate(90deg) translateY(-100%); -} -[data-main-rotation="180"]{ - transform:rotate(180deg) translate(-100%, -100%); -} -[data-main-rotation="270"]{ - transform:rotate(270deg) translateX(-100%); -} - -#hiddenCopyElement, -.hiddenCanvasElement{ - position:absolute; - top:0; - left:0; - width:0; - height:0; - display:none; -} - -.pdfViewer{ - --scale-factor:1; - --page-bg-color:unset; - - padding-bottom:var(--pdfViewer-padding-bottom); - - --hcm-highlight-filter:none; - --hcm-highlight-selected-filter:none; -} - -@media screen and (forced-colors: active){ - -.pdfViewer{ - --hcm-highlight-filter:invert(100%); -} - } - -.pdfViewer.copyAll{ - cursor:wait; - } - -.pdfViewer .canvasWrapper{ - overflow:hidden; - width:100%; - height:100%; - } - -:is(.pdfViewer .canvasWrapper) canvas{ - position:absolute; - top:0; - left:0; - margin:0; - display:block; - width:100%; - height:100%; - contain:content; - } - -:is(:is(.pdfViewer .canvasWrapper) canvas) .structTree{ - contain:strict; - } - -.pdfViewer .page{ - --scale-round-x:1px; - --scale-round-y:1px; - - direction:ltr; - width:816px; - height:1056px; - margin:var(--page-margin); - position:relative; - overflow:visible; - border:var(--page-border); - background-clip:content-box; - background-color:var(--page-bg-color, rgb(255 255 255)); -} - -.pdfViewer .dummyPage{ - position:relative; - width:0; - height:var(--viewer-container-height); -} - -.pdfViewer.noUserSelect{ - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; -} - -.pdfViewer.removePageBorders .page{ - margin:0 auto 10px; - border:none; -} - -.pdfViewer.singlePageView{ - display:inline-block; -} - -.pdfViewer.singlePageView .page{ - margin:0; - border:none; -} - -.pdfViewer:is(.scrollHorizontal, .scrollWrapped), -.spread{ - margin-inline:3.5px; - text-align:center; -} - -.pdfViewer.scrollHorizontal, -.spread{ - white-space:nowrap; -} - -.pdfViewer.removePageBorders, -.pdfViewer:is(.scrollHorizontal, .scrollWrapped) .spread{ - margin-inline:0; -} - -.spread :is(.page, .dummyPage), -.pdfViewer:is(.scrollHorizontal, .scrollWrapped) :is(.page, .spread){ - display:inline-block; - vertical-align:middle; -} - -.spread .page, -.pdfViewer:is(.scrollHorizontal, .scrollWrapped) .page{ - margin-inline:var(--spreadHorizontalWrapped-margin-LR); -} - -.pdfViewer.removePageBorders .spread .page, -.pdfViewer.removePageBorders:is(.scrollHorizontal, .scrollWrapped) .page{ - margin-inline:5px; -} - -.pdfViewer .page.loadingIcon::after{ - position:absolute; - top:0; - left:0; - content:""; - width:100%; - height:100%; - background:url("images/loading-icon.gif") center no-repeat; - display:none; - transition-property:display; - transition-delay:var(--loading-icon-delay); - z-index:5; - contain:strict; -} - -.pdfViewer .page.loading::after{ - display:block; -} - -.pdfViewer .page:not(.loading)::after{ - transition-property:none; - display:none; -} - -.pdfPresentationMode .pdfViewer{ - padding-bottom:0; -} - -.pdfPresentationMode .spread{ - margin:0; -} - -.pdfPresentationMode .pdfViewer .page{ - margin:0 auto; - border:2px solid transparent; -} diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.mjs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.mjs deleted file mode 100644 index 9b2c200c99e..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.mjs +++ /dev/null @@ -1,8435 +0,0 @@ -/** - * @licstart The following is the entire license notice for the - * JavaScript code in this page - * - * Copyright 2024 Mozilla Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * @licend The above is the entire license notice for the - * JavaScript code in this page - */ - -/******/ // The require scope -/******/ var __webpack_require__ = {}; -/******/ -/************************************************************************/ -/******/ /* webpack/runtime/define property getters */ -/******/ (() => { -/******/ // define getter functions for harmony exports -/******/ __webpack_require__.d = (exports, definition) => { -/******/ for(var key in definition) { -/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { -/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); -/******/ } -/******/ } -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/hasOwnProperty shorthand */ -/******/ (() => { -/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) -/******/ })(); -/******/ -/************************************************************************/ -var __webpack_exports__ = globalThis.pdfjsViewer = {}; - -// EXPORTS -__webpack_require__.d(__webpack_exports__, { - AnnotationLayerBuilder: () => (/* reexport */ AnnotationLayerBuilder), - DownloadManager: () => (/* reexport */ DownloadManager), - EventBus: () => (/* reexport */ EventBus), - FindState: () => (/* reexport */ FindState), - GenericL10n: () => (/* reexport */ genericl10n_GenericL10n), - LinkTarget: () => (/* reexport */ LinkTarget), - PDFFindController: () => (/* reexport */ PDFFindController), - PDFHistory: () => (/* reexport */ PDFHistory), - PDFLinkService: () => (/* reexport */ PDFLinkService), - PDFPageView: () => (/* reexport */ PDFPageView), - PDFScriptingManager: () => (/* reexport */ PDFScriptingManagerComponents), - PDFSinglePageViewer: () => (/* reexport */ PDFSinglePageViewer), - PDFViewer: () => (/* reexport */ PDFViewer), - ProgressBar: () => (/* reexport */ ProgressBar), - RenderingStates: () => (/* reexport */ RenderingStates), - ScrollMode: () => (/* reexport */ ScrollMode), - SimpleLinkService: () => (/* reexport */ SimpleLinkService), - SpreadMode: () => (/* reexport */ SpreadMode), - StructTreeLayerBuilder: () => (/* reexport */ StructTreeLayerBuilder), - TextLayerBuilder: () => (/* reexport */ TextLayerBuilder), - XfaLayerBuilder: () => (/* reexport */ XfaLayerBuilder), - parseQueryString: () => (/* reexport */ parseQueryString) -}); - -;// ./web/ui_utils.js -const DEFAULT_SCALE_VALUE = "auto"; -const DEFAULT_SCALE = 1.0; -const DEFAULT_SCALE_DELTA = 1.1; -const MIN_SCALE = 0.1; -const MAX_SCALE = 10.0; -const UNKNOWN_SCALE = 0; -const MAX_AUTO_SCALE = 1.25; -const SCROLLBAR_PADDING = 40; -const VERTICAL_PADDING = 5; -const RenderingStates = { - INITIAL: 0, - RUNNING: 1, - PAUSED: 2, - FINISHED: 3 -}; -const PresentationModeState = { - UNKNOWN: 0, - NORMAL: 1, - CHANGING: 2, - FULLSCREEN: 3 -}; -const SidebarView = { - UNKNOWN: -1, - NONE: 0, - THUMBS: 1, - OUTLINE: 2, - ATTACHMENTS: 3, - LAYERS: 4 -}; -const TextLayerMode = { - DISABLE: 0, - ENABLE: 1, - ENABLE_PERMISSIONS: 2 -}; -const ScrollMode = { - UNKNOWN: -1, - VERTICAL: 0, - HORIZONTAL: 1, - WRAPPED: 2, - PAGE: 3 -}; -const SpreadMode = { - UNKNOWN: -1, - NONE: 0, - ODD: 1, - EVEN: 2 -}; -const CursorTool = { - SELECT: 0, - HAND: 1, - ZOOM: 2 -}; -const AutoPrintRegExp = /\bprint\s*\(/; -function scrollIntoView(element, spot, scrollMatches = false) { - let parent = element.offsetParent; - if (!parent) { - console.error("offsetParent is not set -- cannot scroll"); - return; - } - let offsetY = element.offsetTop + element.clientTop; - let offsetX = element.offsetLeft + element.clientLeft; - while (parent.clientHeight === parent.scrollHeight && parent.clientWidth === parent.scrollWidth || scrollMatches && (parent.classList.contains("markedContent") || getComputedStyle(parent).overflow === "hidden")) { - offsetY += parent.offsetTop; - offsetX += parent.offsetLeft; - parent = parent.offsetParent; - if (!parent) { - return; - } - } - if (spot) { - if (spot.top !== undefined) { - offsetY += spot.top; - } - if (spot.left !== undefined) { - offsetX += spot.left; - parent.scrollLeft = offsetX; - } - } - parent.scrollTop = offsetY; -} -function watchScroll(viewAreaElement, callback, abortSignal = undefined) { - const debounceScroll = function (evt) { - if (rAF) { - return; - } - rAF = window.requestAnimationFrame(function viewAreaElementScrolled() { - rAF = null; - const currentX = viewAreaElement.scrollLeft; - const lastX = state.lastX; - if (currentX !== lastX) { - state.right = currentX > lastX; - } - state.lastX = currentX; - const currentY = viewAreaElement.scrollTop; - const lastY = state.lastY; - if (currentY !== lastY) { - state.down = currentY > lastY; - } - state.lastY = currentY; - callback(state); - }); - }; - const state = { - right: true, - down: true, - lastX: viewAreaElement.scrollLeft, - lastY: viewAreaElement.scrollTop, - _eventHandler: debounceScroll - }; - let rAF = null; - viewAreaElement.addEventListener("scroll", debounceScroll, { - useCapture: true, - signal: abortSignal - }); - abortSignal?.addEventListener("abort", () => window.cancelAnimationFrame(rAF), { - once: true - }); - return state; -} -function parseQueryString(query) { - const params = new Map(); - for (const [key, value] of new URLSearchParams(query)) { - params.set(key.toLowerCase(), value); - } - return params; -} -const InvisibleCharsRegExp = /[\x00-\x1F]/g; -function removeNullCharacters(str, replaceInvisible = false) { - if (!InvisibleCharsRegExp.test(str)) { - return str; - } - if (replaceInvisible) { - return str.replaceAll(InvisibleCharsRegExp, m => m === "\x00" ? "" : " "); - } - return str.replaceAll("\x00", ""); -} -function binarySearchFirstItem(items, condition, start = 0) { - let minIndex = start; - let maxIndex = items.length - 1; - if (maxIndex < 0 || !condition(items[maxIndex])) { - return items.length; - } - if (condition(items[minIndex])) { - return minIndex; - } - while (minIndex < maxIndex) { - const currentIndex = minIndex + maxIndex >> 1; - const currentItem = items[currentIndex]; - if (condition(currentItem)) { - maxIndex = currentIndex; - } else { - minIndex = currentIndex + 1; - } - } - return minIndex; -} -function approximateFraction(x) { - if (Math.floor(x) === x) { - return [x, 1]; - } - const xinv = 1 / x; - const limit = 8; - if (xinv > limit) { - return [1, limit]; - } else if (Math.floor(xinv) === xinv) { - return [1, xinv]; - } - const x_ = x > 1 ? xinv : x; - let a = 0, - b = 1, - c = 1, - d = 1; - while (true) { - const p = a + c, - q = b + d; - if (q > limit) { - break; - } - if (x_ <= p / q) { - c = p; - d = q; - } else { - a = p; - b = q; - } - } - let result; - if (x_ - a / b < c / d - x_) { - result = x_ === x ? [a, b] : [b, a]; - } else { - result = x_ === x ? [c, d] : [d, c]; - } - return result; -} -function floorToDivide(x, div) { - return x - x % div; -} -function getPageSizeInches({ - view, - userUnit, - rotate -}) { - const [x1, y1, x2, y2] = view; - const changeOrientation = rotate % 180 !== 0; - const width = (x2 - x1) / 72 * userUnit; - const height = (y2 - y1) / 72 * userUnit; - return { - width: changeOrientation ? height : width, - height: changeOrientation ? width : height - }; -} -function backtrackBeforeAllVisibleElements(index, views, top) { - if (index < 2) { - return index; - } - let elt = views[index].div; - let pageTop = elt.offsetTop + elt.clientTop; - if (pageTop >= top) { - elt = views[index - 1].div; - pageTop = elt.offsetTop + elt.clientTop; - } - for (let i = index - 2; i >= 0; --i) { - elt = views[i].div; - if (elt.offsetTop + elt.clientTop + elt.clientHeight <= pageTop) { - break; - } - index = i; - } - return index; -} -function getVisibleElements({ - scrollEl, - views, - sortByVisibility = false, - horizontal = false, - rtl = false -}) { - const top = scrollEl.scrollTop, - bottom = top + scrollEl.clientHeight; - const left = scrollEl.scrollLeft, - right = left + scrollEl.clientWidth; - function isElementBottomAfterViewTop(view) { - const element = view.div; - const elementBottom = element.offsetTop + element.clientTop + element.clientHeight; - return elementBottom > top; - } - function isElementNextAfterViewHorizontally(view) { - const element = view.div; - const elementLeft = element.offsetLeft + element.clientLeft; - const elementRight = elementLeft + element.clientWidth; - return rtl ? elementLeft < right : elementRight > left; - } - const visible = [], - ids = new Set(), - numViews = views.length; - let firstVisibleElementInd = binarySearchFirstItem(views, horizontal ? isElementNextAfterViewHorizontally : isElementBottomAfterViewTop); - if (firstVisibleElementInd > 0 && firstVisibleElementInd < numViews && !horizontal) { - firstVisibleElementInd = backtrackBeforeAllVisibleElements(firstVisibleElementInd, views, top); - } - let lastEdge = horizontal ? right : -1; - for (let i = firstVisibleElementInd; i < numViews; i++) { - const view = views[i], - element = view.div; - const currentWidth = element.offsetLeft + element.clientLeft; - const currentHeight = element.offsetTop + element.clientTop; - const viewWidth = element.clientWidth, - viewHeight = element.clientHeight; - const viewRight = currentWidth + viewWidth; - const viewBottom = currentHeight + viewHeight; - if (lastEdge === -1) { - if (viewBottom >= bottom) { - lastEdge = viewBottom; - } - } else if ((horizontal ? currentWidth : currentHeight) > lastEdge) { - break; - } - if (viewBottom <= top || currentHeight >= bottom || viewRight <= left || currentWidth >= right) { - continue; - } - const hiddenHeight = Math.max(0, top - currentHeight) + Math.max(0, viewBottom - bottom); - const hiddenWidth = Math.max(0, left - currentWidth) + Math.max(0, viewRight - right); - const fractionHeight = (viewHeight - hiddenHeight) / viewHeight, - fractionWidth = (viewWidth - hiddenWidth) / viewWidth; - const percent = fractionHeight * fractionWidth * 100 | 0; - visible.push({ - id: view.id, - x: currentWidth, - y: currentHeight, - view, - percent, - widthPercent: fractionWidth * 100 | 0 - }); - ids.add(view.id); - } - const first = visible[0], - last = visible.at(-1); - if (sortByVisibility) { - visible.sort(function (a, b) { - const pc = a.percent - b.percent; - if (Math.abs(pc) > 0.001) { - return -pc; - } - return a.id - b.id; - }); - } - return { - first, - last, - views: visible, - ids - }; -} -function normalizeWheelEventDirection(evt) { - let delta = Math.hypot(evt.deltaX, evt.deltaY); - const angle = Math.atan2(evt.deltaY, evt.deltaX); - if (-0.25 * Math.PI < angle && angle < 0.75 * Math.PI) { - delta = -delta; - } - return delta; -} -function normalizeWheelEventDelta(evt) { - const deltaMode = evt.deltaMode; - let delta = normalizeWheelEventDirection(evt); - const MOUSE_PIXELS_PER_LINE = 30; - const MOUSE_LINES_PER_PAGE = 30; - if (deltaMode === WheelEvent.DOM_DELTA_PIXEL) { - delta /= MOUSE_PIXELS_PER_LINE * MOUSE_LINES_PER_PAGE; - } else if (deltaMode === WheelEvent.DOM_DELTA_LINE) { - delta /= MOUSE_LINES_PER_PAGE; - } - return delta; -} -function isValidRotation(angle) { - return Number.isInteger(angle) && angle % 90 === 0; -} -function isValidScrollMode(mode) { - return Number.isInteger(mode) && Object.values(ScrollMode).includes(mode) && mode !== ScrollMode.UNKNOWN; -} -function isValidSpreadMode(mode) { - return Number.isInteger(mode) && Object.values(SpreadMode).includes(mode) && mode !== SpreadMode.UNKNOWN; -} -function isPortraitOrientation(size) { - return size.width <= size.height; -} -const animationStarted = new Promise(function (resolve) { - window.requestAnimationFrame(resolve); -}); -const docStyle = document.documentElement.style; -function clamp(v, min, max) { - return Math.min(Math.max(v, min), max); -} -class ProgressBar { - #classList = null; - #disableAutoFetchTimeout = null; - #percent = 0; - #style = null; - #visible = true; - constructor(bar) { - this.#classList = bar.classList; - this.#style = bar.style; - } - get percent() { - return this.#percent; - } - set percent(val) { - this.#percent = clamp(val, 0, 100); - if (isNaN(val)) { - this.#classList.add("indeterminate"); - return; - } - this.#classList.remove("indeterminate"); - this.#style.setProperty("--progressBar-percent", `${this.#percent}%`); - } - setWidth(viewer) { - if (!viewer) { - return; - } - const container = viewer.parentNode; - const scrollbarWidth = container.offsetWidth - viewer.offsetWidth; - if (scrollbarWidth > 0) { - this.#style.setProperty("--progressBar-end-offset", `${scrollbarWidth}px`); - } - } - setDisableAutoFetch(delay = 5000) { - if (this.#percent === 100 || isNaN(this.#percent)) { - return; - } - if (this.#disableAutoFetchTimeout) { - clearTimeout(this.#disableAutoFetchTimeout); - } - this.show(); - this.#disableAutoFetchTimeout = setTimeout(() => { - this.#disableAutoFetchTimeout = null; - this.hide(); - }, delay); - } - hide() { - if (!this.#visible) { - return; - } - this.#visible = false; - this.#classList.add("hidden"); - } - show() { - if (this.#visible) { - return; - } - this.#visible = true; - this.#classList.remove("hidden"); - } -} -function getActiveOrFocusedElement() { - let curRoot = document; - let curActiveOrFocused = curRoot.activeElement || curRoot.querySelector(":focus"); - while (curActiveOrFocused?.shadowRoot) { - curRoot = curActiveOrFocused.shadowRoot; - curActiveOrFocused = curRoot.activeElement || curRoot.querySelector(":focus"); - } - return curActiveOrFocused; -} -function apiPageLayoutToViewerModes(layout) { - let scrollMode = ScrollMode.VERTICAL, - spreadMode = SpreadMode.NONE; - switch (layout) { - case "SinglePage": - scrollMode = ScrollMode.PAGE; - break; - case "OneColumn": - break; - case "TwoPageLeft": - scrollMode = ScrollMode.PAGE; - case "TwoColumnLeft": - spreadMode = SpreadMode.ODD; - break; - case "TwoPageRight": - scrollMode = ScrollMode.PAGE; - case "TwoColumnRight": - spreadMode = SpreadMode.EVEN; - break; - } - return { - scrollMode, - spreadMode - }; -} -function apiPageModeToSidebarView(mode) { - switch (mode) { - case "UseNone": - return SidebarView.NONE; - case "UseThumbs": - return SidebarView.THUMBS; - case "UseOutlines": - return SidebarView.OUTLINE; - case "UseAttachments": - return SidebarView.ATTACHMENTS; - case "UseOC": - return SidebarView.LAYERS; - } - return SidebarView.NONE; -} -function toggleCheckedBtn(button, toggle, view = null) { - button.classList.toggle("toggled", toggle); - button.setAttribute("aria-checked", toggle); - view?.classList.toggle("hidden", !toggle); -} -function toggleExpandedBtn(button, toggle, view = null) { - button.classList.toggle("toggled", toggle); - button.setAttribute("aria-expanded", toggle); - view?.classList.toggle("hidden", !toggle); -} -const calcRound = function () { - const e = document.createElement("div"); - e.style.width = "round(down, calc(1.6666666666666665 * 792px), 1px)"; - return e.style.width === "calc(1320px)" ? Math.fround : x => x; -}(); - -;// ./web/pdf_find_utils.js -const CharacterType = { - SPACE: 0, - ALPHA_LETTER: 1, - PUNCT: 2, - HAN_LETTER: 3, - KATAKANA_LETTER: 4, - HIRAGANA_LETTER: 5, - HALFWIDTH_KATAKANA_LETTER: 6, - THAI_LETTER: 7 -}; -function isAlphabeticalScript(charCode) { - return charCode < 0x2e80; -} -function isAscii(charCode) { - return (charCode & 0xff80) === 0; -} -function isAsciiAlpha(charCode) { - return charCode >= 0x61 && charCode <= 0x7a || charCode >= 0x41 && charCode <= 0x5a; -} -function isAsciiDigit(charCode) { - return charCode >= 0x30 && charCode <= 0x39; -} -function isAsciiSpace(charCode) { - return charCode === 0x20 || charCode === 0x09 || charCode === 0x0d || charCode === 0x0a; -} -function isHan(charCode) { - return charCode >= 0x3400 && charCode <= 0x9fff || charCode >= 0xf900 && charCode <= 0xfaff; -} -function isKatakana(charCode) { - return charCode >= 0x30a0 && charCode <= 0x30ff; -} -function isHiragana(charCode) { - return charCode >= 0x3040 && charCode <= 0x309f; -} -function isHalfwidthKatakana(charCode) { - return charCode >= 0xff60 && charCode <= 0xff9f; -} -function isThai(charCode) { - return (charCode & 0xff80) === 0x0e00; -} -function getCharacterType(charCode) { - if (isAlphabeticalScript(charCode)) { - if (isAscii(charCode)) { - if (isAsciiSpace(charCode)) { - return CharacterType.SPACE; - } else if (isAsciiAlpha(charCode) || isAsciiDigit(charCode) || charCode === 0x5f) { - return CharacterType.ALPHA_LETTER; - } - return CharacterType.PUNCT; - } else if (isThai(charCode)) { - return CharacterType.THAI_LETTER; - } else if (charCode === 0xa0) { - return CharacterType.SPACE; - } - return CharacterType.ALPHA_LETTER; - } - if (isHan(charCode)) { - return CharacterType.HAN_LETTER; - } else if (isKatakana(charCode)) { - return CharacterType.KATAKANA_LETTER; - } else if (isHiragana(charCode)) { - return CharacterType.HIRAGANA_LETTER; - } else if (isHalfwidthKatakana(charCode)) { - return CharacterType.HALFWIDTH_KATAKANA_LETTER; - } - return CharacterType.ALPHA_LETTER; -} -let NormalizeWithNFKC; -function getNormalizeWithNFKC() { - NormalizeWithNFKC ||= ` ¨ª¯²-µ¸-º¼-¾IJ-ijĿ-ŀʼnſDŽ-njDZ-dzʰ-ʸ˘-˝ˠ-ˤʹͺ;΄-΅·ϐ-ϖϰ-ϲϴ-ϵϹևٵ-ٸक़-य़ড়-ঢ়য়ਲ਼ਸ਼ਖ਼-ਜ਼ਫ਼ଡ଼-ଢ଼ำຳໜ-ໝ༌གྷཌྷདྷབྷཛྷཀྵჼᴬ-ᴮᴰ-ᴺᴼ-ᵍᵏ-ᵪᵸᶛ-ᶿẚ-ẛάέήίόύώΆ᾽-῁ΈΉ῍-῏ΐΊ῝-῟ΰΎ῭-`ΌΏ´-῾ - ‑‗․-… ″-‴‶-‷‼‾⁇-⁉⁗ ⁰-ⁱ⁴-₎ₐ-ₜ₨℀-℃℅-ℇ℉-ℓℕ-№ℙ-ℝ℠-™ℤΩℨK-ℭℯ-ℱℳ-ℹ℻-⅀ⅅ-ⅉ⅐-ⅿ↉∬-∭∯-∰〈-〉①-⓪⨌⩴-⩶⫝̸ⱼ-ⱽⵯ⺟⻳⼀-⿕ 〶〸-〺゛-゜ゟヿㄱ-ㆎ㆒-㆟㈀-㈞㈠-㉇㉐-㉾㊀-㏿ꚜ-ꚝꝰꟲ-ꟴꟸ-ꟹꭜ-ꭟꭩ豈-嗀塚晴凞-羽蘒諸逸-都飯-舘並-龎ff-stﬓ-ﬗיִײַ-זּטּ-לּמּנּ-סּףּ-פּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-﷼︐-︙︰-﹄﹇-﹒﹔-﹦﹨-﹫ﹰ-ﹲﹴﹶ-ﻼ!-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ¢-₩`; - return NormalizeWithNFKC; -} - -;// ./web/pdf_find_controller.js - - -const FindState = { - FOUND: 0, - NOT_FOUND: 1, - WRAPPED: 2, - PENDING: 3 -}; -const FIND_TIMEOUT = 250; -const MATCH_SCROLL_OFFSET_TOP = -50; -const MATCH_SCROLL_OFFSET_LEFT = -400; -const CHARACTERS_TO_NORMALIZE = { - "\u2010": "-", - "\u2018": "'", - "\u2019": "'", - "\u201A": "'", - "\u201B": "'", - "\u201C": '"', - "\u201D": '"', - "\u201E": '"', - "\u201F": '"', - "\u00BC": "1/4", - "\u00BD": "1/2", - "\u00BE": "3/4" -}; -const DIACRITICS_EXCEPTION = new Set([0x3099, 0x309a, 0x094d, 0x09cd, 0x0a4d, 0x0acd, 0x0b4d, 0x0bcd, 0x0c4d, 0x0ccd, 0x0d3b, 0x0d3c, 0x0d4d, 0x0dca, 0x0e3a, 0x0eba, 0x0f84, 0x1039, 0x103a, 0x1714, 0x1734, 0x17d2, 0x1a60, 0x1b44, 0x1baa, 0x1bab, 0x1bf2, 0x1bf3, 0x2d7f, 0xa806, 0xa82c, 0xa8c4, 0xa953, 0xa9c0, 0xaaf6, 0xabed, 0x0c56, 0x0f71, 0x0f72, 0x0f7a, 0x0f7b, 0x0f7c, 0x0f7d, 0x0f80, 0x0f74]); -let DIACRITICS_EXCEPTION_STR; -const DIACRITICS_REG_EXP = /\p{M}+/gu; -const SPECIAL_CHARS_REG_EXP = /([.*+?^${}()|[\]\\])|(\p{P})|(\s+)|(\p{M})|(\p{L})/gu; -const NOT_DIACRITIC_FROM_END_REG_EXP = /([^\p{M}])\p{M}*$/u; -const NOT_DIACRITIC_FROM_START_REG_EXP = /^\p{M}*([^\p{M}])/u; -const SYLLABLES_REG_EXP = /[\uAC00-\uD7AF\uFA6C\uFACF-\uFAD1\uFAD5-\uFAD7]+/g; -const SYLLABLES_LENGTHS = new Map(); -const FIRST_CHAR_SYLLABLES_REG_EXP = "[\\u1100-\\u1112\\ud7a4-\\ud7af\\ud84a\\ud84c\\ud850\\ud854\\ud857\\ud85f]"; -const NFKC_CHARS_TO_NORMALIZE = new Map(); -let noSyllablesRegExp = null; -let withSyllablesRegExp = null; -function normalize(text) { - const syllablePositions = []; - let m; - while ((m = SYLLABLES_REG_EXP.exec(text)) !== null) { - let { - index - } = m; - for (const char of m[0]) { - let len = SYLLABLES_LENGTHS.get(char); - if (!len) { - len = char.normalize("NFD").length; - SYLLABLES_LENGTHS.set(char, len); - } - syllablePositions.push([len, index++]); - } - } - let normalizationRegex; - if (syllablePositions.length === 0 && noSyllablesRegExp) { - normalizationRegex = noSyllablesRegExp; - } else if (syllablePositions.length > 0 && withSyllablesRegExp) { - normalizationRegex = withSyllablesRegExp; - } else { - const replace = Object.keys(CHARACTERS_TO_NORMALIZE).join(""); - const toNormalizeWithNFKC = getNormalizeWithNFKC(); - const CJK = "(?:\\p{Ideographic}|[\u3040-\u30FF])"; - const HKDiacritics = "(?:\u3099|\u309A)"; - const CompoundWord = "\\p{Ll}-\\n\\p{Lu}"; - const regexp = `([${replace}])|([${toNormalizeWithNFKC}])|(${HKDiacritics}\\n)|(\\p{M}+(?:-\\n)?)|(${CompoundWord})|(\\S-\\n)|(${CJK}\\n)|(\\n)`; - if (syllablePositions.length === 0) { - normalizationRegex = noSyllablesRegExp = new RegExp(regexp + "|(\\u0000)", "gum"); - } else { - normalizationRegex = withSyllablesRegExp = new RegExp(regexp + `|(${FIRST_CHAR_SYLLABLES_REG_EXP})`, "gum"); - } - } - const rawDiacriticsPositions = []; - while ((m = DIACRITICS_REG_EXP.exec(text)) !== null) { - rawDiacriticsPositions.push([m[0].length, m.index]); - } - let normalized = text.normalize("NFD"); - const positions = [0, 0]; - let rawDiacriticsIndex = 0; - let syllableIndex = 0; - let shift = 0; - let shiftOrigin = 0; - let eol = 0; - let hasDiacritics = false; - normalized = normalized.replace(normalizationRegex, (match, p1, p2, p3, p4, p5, p6, p7, p8, p9, i) => { - i -= shiftOrigin; - if (p1) { - const replacement = CHARACTERS_TO_NORMALIZE[p1]; - const jj = replacement.length; - for (let j = 1; j < jj; j++) { - positions.push(i - shift + j, shift - j); - } - shift -= jj - 1; - return replacement; - } - if (p2) { - let replacement = NFKC_CHARS_TO_NORMALIZE.get(p2); - if (!replacement) { - replacement = p2.normalize("NFKC"); - NFKC_CHARS_TO_NORMALIZE.set(p2, replacement); - } - const jj = replacement.length; - for (let j = 1; j < jj; j++) { - positions.push(i - shift + j, shift - j); - } - shift -= jj - 1; - return replacement; - } - if (p3) { - hasDiacritics = true; - if (i + eol === rawDiacriticsPositions[rawDiacriticsIndex]?.[1]) { - ++rawDiacriticsIndex; - } else { - positions.push(i - 1 - shift + 1, shift - 1); - shift -= 1; - shiftOrigin += 1; - } - positions.push(i - shift + 1, shift); - shiftOrigin += 1; - eol += 1; - return p3.charAt(0); - } - if (p4) { - const hasTrailingDashEOL = p4.endsWith("\n"); - const len = hasTrailingDashEOL ? p4.length - 2 : p4.length; - hasDiacritics = true; - let jj = len; - if (i + eol === rawDiacriticsPositions[rawDiacriticsIndex]?.[1]) { - jj -= rawDiacriticsPositions[rawDiacriticsIndex][0]; - ++rawDiacriticsIndex; - } - for (let j = 1; j <= jj; j++) { - positions.push(i - 1 - shift + j, shift - j); - } - shift -= jj; - shiftOrigin += jj; - if (hasTrailingDashEOL) { - i += len - 1; - positions.push(i - shift + 1, 1 + shift); - shift += 1; - shiftOrigin += 1; - eol += 1; - return p4.slice(0, len); - } - return p4; - } - if (p5) { - shiftOrigin += 1; - eol += 1; - return p5.replace("\n", ""); - } - if (p6) { - const len = p6.length - 2; - positions.push(i - shift + len, 1 + shift); - shift += 1; - shiftOrigin += 1; - eol += 1; - return p6.slice(0, -2); - } - if (p7) { - const len = p7.length - 1; - positions.push(i - shift + len, shift); - shiftOrigin += 1; - eol += 1; - return p7.slice(0, -1); - } - if (p8) { - positions.push(i - shift + 1, shift - 1); - shift -= 1; - shiftOrigin += 1; - eol += 1; - return " "; - } - if (i + eol === syllablePositions[syllableIndex]?.[1]) { - const newCharLen = syllablePositions[syllableIndex][0] - 1; - ++syllableIndex; - for (let j = 1; j <= newCharLen; j++) { - positions.push(i - (shift - j), shift - j); - } - shift -= newCharLen; - shiftOrigin += newCharLen; - } - return p9; - }); - positions.push(normalized.length, shift); - const starts = new Uint32Array(positions.length >> 1); - const shifts = new Int32Array(positions.length >> 1); - for (let i = 0, ii = positions.length; i < ii; i += 2) { - starts[i >> 1] = positions[i]; - shifts[i >> 1] = positions[i + 1]; - } - return [normalized, [starts, shifts], hasDiacritics]; -} -function getOriginalIndex(diffs, pos, len) { - if (!diffs) { - return [pos, len]; - } - const [starts, shifts] = diffs; - const start = pos; - const end = pos + len - 1; - let i = binarySearchFirstItem(starts, x => x >= start); - if (starts[i] > start) { - --i; - } - let j = binarySearchFirstItem(starts, x => x >= end, i); - if (starts[j] > end) { - --j; - } - const oldStart = start + shifts[i]; - const oldEnd = end + shifts[j]; - const oldLen = oldEnd + 1 - oldStart; - return [oldStart, oldLen]; -} -class PDFFindController { - #state = null; - #updateMatchesCountOnProgress = true; - #visitedPagesCount = 0; - constructor({ - linkService, - eventBus, - updateMatchesCountOnProgress = true - }) { - this._linkService = linkService; - this._eventBus = eventBus; - this.#updateMatchesCountOnProgress = updateMatchesCountOnProgress; - this.onIsPageVisible = null; - this.#reset(); - eventBus._on("find", this.#onFind.bind(this)); - eventBus._on("findbarclose", this.#onFindBarClose.bind(this)); - } - get highlightMatches() { - return this._highlightMatches; - } - get pageMatches() { - return this._pageMatches; - } - get pageMatchesLength() { - return this._pageMatchesLength; - } - get selected() { - return this._selected; - } - get state() { - return this.#state; - } - setDocument(pdfDocument) { - if (this._pdfDocument) { - this.#reset(); - } - if (!pdfDocument) { - return; - } - this._pdfDocument = pdfDocument; - this._firstPageCapability.resolve(); - } - #onFind(state) { - if (!state) { - return; - } - const pdfDocument = this._pdfDocument; - const { - type - } = state; - if (this.#state === null || this.#shouldDirtyMatch(state)) { - this._dirtyMatch = true; - } - this.#state = state; - if (type !== "highlightallchange") { - this.#updateUIState(FindState.PENDING); - } - this._firstPageCapability.promise.then(() => { - if (!this._pdfDocument || pdfDocument && this._pdfDocument !== pdfDocument) { - return; - } - this.#extractText(); - const findbarClosed = !this._highlightMatches; - const pendingTimeout = !!this._findTimeout; - if (this._findTimeout) { - clearTimeout(this._findTimeout); - this._findTimeout = null; - } - if (!type) { - this._findTimeout = setTimeout(() => { - this.#nextMatch(); - this._findTimeout = null; - }, FIND_TIMEOUT); - } else if (this._dirtyMatch) { - this.#nextMatch(); - } else if (type === "again") { - this.#nextMatch(); - if (findbarClosed && this.#state.highlightAll) { - this.#updateAllPages(); - } - } else if (type === "highlightallchange") { - if (pendingTimeout) { - this.#nextMatch(); - } else { - this._highlightMatches = true; - } - this.#updateAllPages(); - } else { - this.#nextMatch(); - } - }); - } - scrollMatchIntoView({ - element = null, - selectedLeft = 0, - pageIndex = -1, - matchIndex = -1 - }) { - if (!this._scrollMatches || !element) { - return; - } else if (matchIndex === -1 || matchIndex !== this._selected.matchIdx) { - return; - } else if (pageIndex === -1 || pageIndex !== this._selected.pageIdx) { - return; - } - this._scrollMatches = false; - const spot = { - top: MATCH_SCROLL_OFFSET_TOP, - left: selectedLeft + MATCH_SCROLL_OFFSET_LEFT - }; - scrollIntoView(element, spot, true); - } - #reset() { - this._highlightMatches = false; - this._scrollMatches = false; - this._pdfDocument = null; - this._pageMatches = []; - this._pageMatchesLength = []; - this.#visitedPagesCount = 0; - this.#state = null; - this._selected = { - pageIdx: -1, - matchIdx: -1 - }; - this._offset = { - pageIdx: null, - matchIdx: null, - wrapped: false - }; - this._extractTextPromises = []; - this._pageContents = []; - this._pageDiffs = []; - this._hasDiacritics = []; - this._matchesCountTotal = 0; - this._pagesToSearch = null; - this._pendingFindMatches = new Set(); - this._resumePageIdx = null; - this._dirtyMatch = false; - clearTimeout(this._findTimeout); - this._findTimeout = null; - this._firstPageCapability = Promise.withResolvers(); - } - get #query() { - const { - query - } = this.#state; - if (typeof query === "string") { - if (query !== this._rawQuery) { - this._rawQuery = query; - [this._normalizedQuery] = normalize(query); - } - return this._normalizedQuery; - } - return (query || []).filter(q => !!q).map(q => normalize(q)[0]); - } - #shouldDirtyMatch(state) { - const newQuery = state.query, - prevQuery = this.#state.query; - const newType = typeof newQuery, - prevType = typeof prevQuery; - if (newType !== prevType) { - return true; - } - if (newType === "string") { - if (newQuery !== prevQuery) { - return true; - } - } else if (JSON.stringify(newQuery) !== JSON.stringify(prevQuery)) { - return true; - } - switch (state.type) { - case "again": - const pageNumber = this._selected.pageIdx + 1; - const linkService = this._linkService; - return pageNumber >= 1 && pageNumber <= linkService.pagesCount && pageNumber !== linkService.page && !(this.onIsPageVisible?.(pageNumber) ?? true); - case "highlightallchange": - return false; - } - return true; - } - #isEntireWord(content, startIdx, length) { - let match = content.slice(0, startIdx).match(NOT_DIACRITIC_FROM_END_REG_EXP); - if (match) { - const first = content.charCodeAt(startIdx); - const limit = match[1].charCodeAt(0); - if (getCharacterType(first) === getCharacterType(limit)) { - return false; - } - } - match = content.slice(startIdx + length).match(NOT_DIACRITIC_FROM_START_REG_EXP); - if (match) { - const last = content.charCodeAt(startIdx + length - 1); - const limit = match[1].charCodeAt(0); - if (getCharacterType(last) === getCharacterType(limit)) { - return false; - } - } - return true; - } - #convertToRegExpString(query, hasDiacritics) { - const { - matchDiacritics - } = this.#state; - let isUnicode = false; - query = query.replaceAll(SPECIAL_CHARS_REG_EXP, (match, p1, p2, p3, p4, p5) => { - if (p1) { - return `[ ]*\\${p1}[ ]*`; - } - if (p2) { - return `[ ]*${p2}[ ]*`; - } - if (p3) { - return "[ ]+"; - } - if (matchDiacritics) { - return p4 || p5; - } - if (p4) { - return DIACRITICS_EXCEPTION.has(p4.charCodeAt(0)) ? p4 : ""; - } - if (hasDiacritics) { - isUnicode = true; - return `${p5}\\p{M}*`; - } - return p5; - }); - const trailingSpaces = "[ ]*"; - if (query.endsWith(trailingSpaces)) { - query = query.slice(0, query.length - trailingSpaces.length); - } - if (matchDiacritics) { - if (hasDiacritics) { - DIACRITICS_EXCEPTION_STR ||= String.fromCharCode(...DIACRITICS_EXCEPTION); - isUnicode = true; - query = `${query}(?=[${DIACRITICS_EXCEPTION_STR}]|[^\\p{M}]|$)`; - } - } - return [isUnicode, query]; - } - #calculateMatch(pageIndex) { - const query = this.#query; - if (query.length === 0) { - return; - } - const pageContent = this._pageContents[pageIndex]; - const matcherResult = this.match(query, pageContent, pageIndex); - const matches = this._pageMatches[pageIndex] = []; - const matchesLength = this._pageMatchesLength[pageIndex] = []; - const diffs = this._pageDiffs[pageIndex]; - matcherResult?.forEach(({ - index, - length - }) => { - const [matchPos, matchLen] = getOriginalIndex(diffs, index, length); - if (matchLen) { - matches.push(matchPos); - matchesLength.push(matchLen); - } - }); - if (this.#state.highlightAll) { - this.#updatePage(pageIndex); - } - if (this._resumePageIdx === pageIndex) { - this._resumePageIdx = null; - this.#nextPageMatch(); - } - const pageMatchesCount = matches.length; - this._matchesCountTotal += pageMatchesCount; - if (this.#updateMatchesCountOnProgress) { - if (pageMatchesCount > 0) { - this.#updateUIResultsCount(); - } - } else if (++this.#visitedPagesCount === this._linkService.pagesCount) { - this.#updateUIResultsCount(); - } - } - match(query, pageContent, pageIndex) { - const hasDiacritics = this._hasDiacritics[pageIndex]; - let isUnicode = false; - if (typeof query === "string") { - [isUnicode, query] = this.#convertToRegExpString(query, hasDiacritics); - } else { - query = query.sort().reverse().map(q => { - const [isUnicodePart, queryPart] = this.#convertToRegExpString(q, hasDiacritics); - isUnicode ||= isUnicodePart; - return `(${queryPart})`; - }).join("|"); - } - if (!query) { - return undefined; - } - const { - caseSensitive, - entireWord - } = this.#state; - const flags = `g${isUnicode ? "u" : ""}${caseSensitive ? "" : "i"}`; - query = new RegExp(query, flags); - const matches = []; - let match; - while ((match = query.exec(pageContent)) !== null) { - if (entireWord && !this.#isEntireWord(pageContent, match.index, match[0].length)) { - continue; - } - matches.push({ - index: match.index, - length: match[0].length - }); - } - return matches; - } - #extractText() { - if (this._extractTextPromises.length > 0) { - return; - } - let deferred = Promise.resolve(); - const textOptions = { - disableNormalization: true - }; - for (let i = 0, ii = this._linkService.pagesCount; i < ii; i++) { - const { - promise, - resolve - } = Promise.withResolvers(); - this._extractTextPromises[i] = promise; - deferred = deferred.then(() => { - return this._pdfDocument.getPage(i + 1).then(pdfPage => pdfPage.getTextContent(textOptions)).then(textContent => { - const strBuf = []; - for (const textItem of textContent.items) { - strBuf.push(textItem.str); - if (textItem.hasEOL) { - strBuf.push("\n"); - } - } - [this._pageContents[i], this._pageDiffs[i], this._hasDiacritics[i]] = normalize(strBuf.join("")); - resolve(); - }, reason => { - console.error(`Unable to get text content for page ${i + 1}`, reason); - this._pageContents[i] = ""; - this._pageDiffs[i] = null; - this._hasDiacritics[i] = false; - resolve(); - }); - }); - } - } - #updatePage(index) { - if (this._scrollMatches && this._selected.pageIdx === index) { - this._linkService.page = index + 1; - } - this._eventBus.dispatch("updatetextlayermatches", { - source: this, - pageIndex: index - }); - } - #updateAllPages() { - this._eventBus.dispatch("updatetextlayermatches", { - source: this, - pageIndex: -1 - }); - } - #nextMatch() { - const previous = this.#state.findPrevious; - const currentPageIndex = this._linkService.page - 1; - const numPages = this._linkService.pagesCount; - this._highlightMatches = true; - if (this._dirtyMatch) { - this._dirtyMatch = false; - this._selected.pageIdx = this._selected.matchIdx = -1; - this._offset.pageIdx = currentPageIndex; - this._offset.matchIdx = null; - this._offset.wrapped = false; - this._resumePageIdx = null; - this._pageMatches.length = 0; - this._pageMatchesLength.length = 0; - this.#visitedPagesCount = 0; - this._matchesCountTotal = 0; - this.#updateAllPages(); - for (let i = 0; i < numPages; i++) { - if (this._pendingFindMatches.has(i)) { - continue; - } - this._pendingFindMatches.add(i); - this._extractTextPromises[i].then(() => { - this._pendingFindMatches.delete(i); - this.#calculateMatch(i); - }); - } - } - const query = this.#query; - if (query.length === 0) { - this.#updateUIState(FindState.FOUND); - return; - } - if (this._resumePageIdx) { - return; - } - const offset = this._offset; - this._pagesToSearch = numPages; - if (offset.matchIdx !== null) { - const numPageMatches = this._pageMatches[offset.pageIdx].length; - if (!previous && offset.matchIdx + 1 < numPageMatches || previous && offset.matchIdx > 0) { - offset.matchIdx = previous ? offset.matchIdx - 1 : offset.matchIdx + 1; - this.#updateMatch(true); - return; - } - this.#advanceOffsetPage(previous); - } - this.#nextPageMatch(); - } - #matchesReady(matches) { - const offset = this._offset; - const numMatches = matches.length; - const previous = this.#state.findPrevious; - if (numMatches) { - offset.matchIdx = previous ? numMatches - 1 : 0; - this.#updateMatch(true); - return true; - } - this.#advanceOffsetPage(previous); - if (offset.wrapped) { - offset.matchIdx = null; - if (this._pagesToSearch < 0) { - this.#updateMatch(false); - return true; - } - } - return false; - } - #nextPageMatch() { - if (this._resumePageIdx !== null) { - console.error("There can only be one pending page."); - } - let matches = null; - do { - const pageIdx = this._offset.pageIdx; - matches = this._pageMatches[pageIdx]; - if (!matches) { - this._resumePageIdx = pageIdx; - break; - } - } while (!this.#matchesReady(matches)); - } - #advanceOffsetPage(previous) { - const offset = this._offset; - const numPages = this._linkService.pagesCount; - offset.pageIdx = previous ? offset.pageIdx - 1 : offset.pageIdx + 1; - offset.matchIdx = null; - this._pagesToSearch--; - if (offset.pageIdx >= numPages || offset.pageIdx < 0) { - offset.pageIdx = previous ? numPages - 1 : 0; - offset.wrapped = true; - } - } - #updateMatch(found = false) { - let state = FindState.NOT_FOUND; - const wrapped = this._offset.wrapped; - this._offset.wrapped = false; - if (found) { - const previousPage = this._selected.pageIdx; - this._selected.pageIdx = this._offset.pageIdx; - this._selected.matchIdx = this._offset.matchIdx; - state = wrapped ? FindState.WRAPPED : FindState.FOUND; - if (previousPage !== -1 && previousPage !== this._selected.pageIdx) { - this.#updatePage(previousPage); - } - } - this.#updateUIState(state, this.#state.findPrevious); - if (this._selected.pageIdx !== -1) { - this._scrollMatches = true; - this.#updatePage(this._selected.pageIdx); - } - } - #onFindBarClose(evt) { - const pdfDocument = this._pdfDocument; - this._firstPageCapability.promise.then(() => { - if (!this._pdfDocument || pdfDocument && this._pdfDocument !== pdfDocument) { - return; - } - if (this._findTimeout) { - clearTimeout(this._findTimeout); - this._findTimeout = null; - } - if (this._resumePageIdx) { - this._resumePageIdx = null; - this._dirtyMatch = true; - } - this.#updateUIState(FindState.FOUND); - this._highlightMatches = false; - this.#updateAllPages(); - }); - } - #requestMatchesCount() { - const { - pageIdx, - matchIdx - } = this._selected; - let current = 0, - total = this._matchesCountTotal; - if (matchIdx !== -1) { - for (let i = 0; i < pageIdx; i++) { - current += this._pageMatches[i]?.length || 0; - } - current += matchIdx + 1; - } - if (current < 1 || current > total) { - current = total = 0; - } - return { - current, - total - }; - } - #updateUIResultsCount() { - this._eventBus.dispatch("updatefindmatchescount", { - source: this, - matchesCount: this.#requestMatchesCount() - }); - } - #updateUIState(state, previous = false) { - if (!this.#updateMatchesCountOnProgress && (this.#visitedPagesCount !== this._linkService.pagesCount || state === FindState.PENDING)) { - return; - } - this._eventBus.dispatch("updatefindcontrolstate", { - source: this, - state, - previous, - entireWord: this.#state?.entireWord ?? null, - matchesCount: this.#requestMatchesCount(), - rawQuery: this.#state?.query ?? null - }); - } -} - -;// ./web/pdf_link_service.js - -const DEFAULT_LINK_REL = "noopener noreferrer nofollow"; -const LinkTarget = { - NONE: 0, - SELF: 1, - BLANK: 2, - PARENT: 3, - TOP: 4 -}; -class PDFLinkService { - externalLinkEnabled = true; - constructor({ - eventBus, - externalLinkTarget = null, - externalLinkRel = null, - ignoreDestinationZoom = false - } = {}) { - this.eventBus = eventBus; - this.externalLinkTarget = externalLinkTarget; - this.externalLinkRel = externalLinkRel; - this._ignoreDestinationZoom = ignoreDestinationZoom; - this.baseUrl = null; - this.pdfDocument = null; - this.pdfViewer = null; - this.pdfHistory = null; - } - setDocument(pdfDocument, baseUrl = null) { - this.baseUrl = baseUrl; - this.pdfDocument = pdfDocument; - } - setViewer(pdfViewer) { - this.pdfViewer = pdfViewer; - } - setHistory(pdfHistory) { - this.pdfHistory = pdfHistory; - } - get pagesCount() { - return this.pdfDocument ? this.pdfDocument.numPages : 0; - } - get page() { - return this.pdfDocument ? this.pdfViewer.currentPageNumber : 1; - } - set page(value) { - if (this.pdfDocument) { - this.pdfViewer.currentPageNumber = value; - } - } - get rotation() { - return this.pdfDocument ? this.pdfViewer.pagesRotation : 0; - } - set rotation(value) { - if (this.pdfDocument) { - this.pdfViewer.pagesRotation = value; - } - } - get isInPresentationMode() { - return this.pdfDocument ? this.pdfViewer.isInPresentationMode : false; - } - async goToDestination(dest) { - if (!this.pdfDocument) { - return; - } - let namedDest, explicitDest, pageNumber; - if (typeof dest === "string") { - namedDest = dest; - explicitDest = await this.pdfDocument.getDestination(dest); - } else { - namedDest = null; - explicitDest = await dest; - } - if (!Array.isArray(explicitDest)) { - console.error(`goToDestination: "${explicitDest}" is not a valid destination array, for dest="${dest}".`); - return; - } - const [destRef] = explicitDest; - if (destRef && typeof destRef === "object") { - pageNumber = this.pdfDocument.cachedPageNumber(destRef); - if (!pageNumber) { - try { - pageNumber = (await this.pdfDocument.getPageIndex(destRef)) + 1; - } catch { - console.error(`goToDestination: "${destRef}" is not a valid page reference, for dest="${dest}".`); - return; - } - } - } else if (Number.isInteger(destRef)) { - pageNumber = destRef + 1; - } - if (!pageNumber || pageNumber < 1 || pageNumber > this.pagesCount) { - console.error(`goToDestination: "${pageNumber}" is not a valid page number, for dest="${dest}".`); - return; - } - if (this.pdfHistory) { - this.pdfHistory.pushCurrentPosition(); - this.pdfHistory.push({ - namedDest, - explicitDest, - pageNumber - }); - } - this.pdfViewer.scrollPageIntoView({ - pageNumber, - destArray: explicitDest, - ignoreDestinationZoom: this._ignoreDestinationZoom - }); - } - goToPage(val) { - if (!this.pdfDocument) { - return; - } - const pageNumber = typeof val === "string" && this.pdfViewer.pageLabelToPageNumber(val) || val | 0; - if (!(Number.isInteger(pageNumber) && pageNumber > 0 && pageNumber <= this.pagesCount)) { - console.error(`PDFLinkService.goToPage: "${val}" is not a valid page.`); - return; - } - if (this.pdfHistory) { - this.pdfHistory.pushCurrentPosition(); - this.pdfHistory.pushPage(pageNumber); - } - this.pdfViewer.scrollPageIntoView({ - pageNumber - }); - } - addLinkAttributes(link, url, newWindow = false) { - if (!url || typeof url !== "string") { - throw new Error('A valid "url" parameter must provided.'); - } - const target = newWindow ? LinkTarget.BLANK : this.externalLinkTarget, - rel = this.externalLinkRel; - if (this.externalLinkEnabled) { - link.href = link.title = url; - } else { - link.href = ""; - link.title = `Disabled: ${url}`; - link.onclick = () => false; - } - let targetStr = ""; - switch (target) { - case LinkTarget.NONE: - break; - case LinkTarget.SELF: - targetStr = "_self"; - break; - case LinkTarget.BLANK: - targetStr = "_blank"; - break; - case LinkTarget.PARENT: - targetStr = "_parent"; - break; - case LinkTarget.TOP: - targetStr = "_top"; - break; - } - link.target = targetStr; - link.rel = typeof rel === "string" ? rel : DEFAULT_LINK_REL; - } - getDestinationHash(dest) { - if (typeof dest === "string") { - if (dest.length > 0) { - return this.getAnchorUrl("#" + escape(dest)); - } - } else if (Array.isArray(dest)) { - const str = JSON.stringify(dest); - if (str.length > 0) { - return this.getAnchorUrl("#" + escape(str)); - } - } - return this.getAnchorUrl(""); - } - getAnchorUrl(anchor) { - return this.baseUrl ? this.baseUrl + anchor : anchor; - } - setHash(hash) { - if (!this.pdfDocument) { - return; - } - let pageNumber, dest; - if (hash.includes("=")) { - const params = parseQueryString(hash); - if (params.has("search")) { - const query = params.get("search").replaceAll('"', ""), - phrase = params.get("phrase") === "true"; - this.eventBus.dispatch("findfromurlhash", { - source: this, - query: phrase ? query : query.match(/\S+/g) - }); - } - if (params.has("page")) { - pageNumber = params.get("page") | 0 || 1; - } - if (params.has("zoom")) { - const zoomArgs = params.get("zoom").split(","); - const zoomArg = zoomArgs[0]; - const zoomArgNumber = parseFloat(zoomArg); - if (!zoomArg.includes("Fit")) { - dest = [null, { - name: "XYZ" - }, zoomArgs.length > 1 ? zoomArgs[1] | 0 : null, zoomArgs.length > 2 ? zoomArgs[2] | 0 : null, zoomArgNumber ? zoomArgNumber / 100 : zoomArg]; - } else if (zoomArg === "Fit" || zoomArg === "FitB") { - dest = [null, { - name: zoomArg - }]; - } else if (zoomArg === "FitH" || zoomArg === "FitBH" || zoomArg === "FitV" || zoomArg === "FitBV") { - dest = [null, { - name: zoomArg - }, zoomArgs.length > 1 ? zoomArgs[1] | 0 : null]; - } else if (zoomArg === "FitR") { - if (zoomArgs.length !== 5) { - console.error('PDFLinkService.setHash: Not enough parameters for "FitR".'); - } else { - dest = [null, { - name: zoomArg - }, zoomArgs[1] | 0, zoomArgs[2] | 0, zoomArgs[3] | 0, zoomArgs[4] | 0]; - } - } else { - console.error(`PDFLinkService.setHash: "${zoomArg}" is not a valid zoom value.`); - } - } - if (dest) { - this.pdfViewer.scrollPageIntoView({ - pageNumber: pageNumber || this.page, - destArray: dest, - allowNegativeOffset: true - }); - } else if (pageNumber) { - this.page = pageNumber; - } - if (params.has("pagemode")) { - this.eventBus.dispatch("pagemode", { - source: this, - mode: params.get("pagemode") - }); - } - if (params.has("nameddest")) { - this.goToDestination(params.get("nameddest")); - } - return; - } - dest = unescape(hash); - try { - dest = JSON.parse(dest); - if (!Array.isArray(dest)) { - dest = dest.toString(); - } - } catch {} - if (typeof dest === "string" || PDFLinkService.#isValidExplicitDest(dest)) { - this.goToDestination(dest); - return; - } - console.error(`PDFLinkService.setHash: "${unescape(hash)}" is not a valid destination.`); - } - executeNamedAction(action) { - if (!this.pdfDocument) { - return; - } - switch (action) { - case "GoBack": - this.pdfHistory?.back(); - break; - case "GoForward": - this.pdfHistory?.forward(); - break; - case "NextPage": - this.pdfViewer.nextPage(); - break; - case "PrevPage": - this.pdfViewer.previousPage(); - break; - case "LastPage": - this.page = this.pagesCount; - break; - case "FirstPage": - this.page = 1; - break; - default: - break; - } - this.eventBus.dispatch("namedaction", { - source: this, - action - }); - } - async executeSetOCGState(action) { - if (!this.pdfDocument) { - return; - } - const pdfDocument = this.pdfDocument, - optionalContentConfig = await this.pdfViewer.optionalContentConfigPromise; - if (pdfDocument !== this.pdfDocument) { - return; - } - optionalContentConfig.setOCGState(action); - this.pdfViewer.optionalContentConfigPromise = Promise.resolve(optionalContentConfig); - } - static #isValidExplicitDest(dest) { - if (!Array.isArray(dest) || dest.length < 2) { - return false; - } - const [page, zoom, ...args] = dest; - if (!(typeof page === "object" && Number.isInteger(page?.num) && Number.isInteger(page?.gen)) && !Number.isInteger(page)) { - return false; - } - if (!(typeof zoom === "object" && typeof zoom?.name === "string")) { - return false; - } - const argsLen = args.length; - let allowNull = true; - switch (zoom.name) { - case "XYZ": - if (argsLen < 2 || argsLen > 3) { - return false; - } - break; - case "Fit": - case "FitB": - return argsLen === 0; - case "FitH": - case "FitBH": - case "FitV": - case "FitBV": - if (argsLen > 1) { - return false; - } - break; - case "FitR": - if (argsLen !== 4) { - return false; - } - allowNull = false; - break; - default: - return false; - } - for (const arg of args) { - if (!(typeof arg === "number" || allowNull && arg === null)) { - return false; - } - } - return true; - } -} -class SimpleLinkService extends PDFLinkService { - setDocument(pdfDocument, baseUrl = null) {} -} - -;// ./web/pdfjs.js -const { - AbortException, - AnnotationEditorLayer, - AnnotationEditorParamsType, - AnnotationEditorType, - AnnotationEditorUIManager, - AnnotationLayer, - AnnotationMode, - build, - ColorPicker, - createValidAbsoluteUrl, - DOMSVGFactory, - DrawLayer, - FeatureTest, - fetchData, - getDocument, - getFilenameFromUrl, - getPdfFilenameFromUrl, - getXfaPageViewport, - GlobalWorkerOptions, - ImageKind, - InvalidPDFException, - isDataScheme, - isPdfFile, - MissingPDFException, - noContextMenu, - normalizeUnicode, - OPS, - OutputScale, - PasswordResponses, - PDFDataRangeTransport, - PDFDateString, - PDFWorker, - PermissionFlag, - PixelsPerInch, - RenderingCancelledException, - setLayerDimensions, - shadow, - stopEvent, - TextLayer, - TouchManager, - UnexpectedResponseException, - Util, - VerbosityLevel, - version, - XfaLayer -} = globalThis.pdfjsLib; - -;// ./web/annotation_layer_builder.js - - -class AnnotationLayerBuilder { - #onAppend = null; - #eventAbortController = null; - constructor({ - pdfPage, - linkService, - downloadManager, - annotationStorage = null, - imageResourcesPath = "", - renderForms = true, - enableScripting = false, - hasJSActionsPromise = null, - fieldObjectsPromise = null, - annotationCanvasMap = null, - accessibilityManager = null, - annotationEditorUIManager = null, - onAppend = null - }) { - this.pdfPage = pdfPage; - this.linkService = linkService; - this.downloadManager = downloadManager; - this.imageResourcesPath = imageResourcesPath; - this.renderForms = renderForms; - this.annotationStorage = annotationStorage; - this.enableScripting = enableScripting; - this._hasJSActionsPromise = hasJSActionsPromise || Promise.resolve(false); - this._fieldObjectsPromise = fieldObjectsPromise || Promise.resolve(null); - this._annotationCanvasMap = annotationCanvasMap; - this._accessibilityManager = accessibilityManager; - this._annotationEditorUIManager = annotationEditorUIManager; - this.#onAppend = onAppend; - this.annotationLayer = null; - this.div = null; - this._cancelled = false; - this._eventBus = linkService.eventBus; - } - async render(viewport, options, intent = "display") { - if (this.div) { - if (this._cancelled || !this.annotationLayer) { - return; - } - this.annotationLayer.update({ - viewport: viewport.clone({ - dontFlip: true - }) - }); - return; - } - const [annotations, hasJSActions, fieldObjects] = await Promise.all([this.pdfPage.getAnnotations({ - intent - }), this._hasJSActionsPromise, this._fieldObjectsPromise]); - if (this._cancelled) { - return; - } - const div = this.div = document.createElement("div"); - div.className = "annotationLayer"; - this.#onAppend?.(div); - if (annotations.length === 0) { - this.hide(); - return; - } - this.annotationLayer = new AnnotationLayer({ - div, - accessibilityManager: this._accessibilityManager, - annotationCanvasMap: this._annotationCanvasMap, - annotationEditorUIManager: this._annotationEditorUIManager, - page: this.pdfPage, - viewport: viewport.clone({ - dontFlip: true - }), - structTreeLayer: options?.structTreeLayer || null - }); - await this.annotationLayer.render({ - annotations, - imageResourcesPath: this.imageResourcesPath, - renderForms: this.renderForms, - linkService: this.linkService, - downloadManager: this.downloadManager, - annotationStorage: this.annotationStorage, - enableScripting: this.enableScripting, - hasJSActions, - fieldObjects - }); - if (this.linkService.isInPresentationMode) { - this.#updatePresentationModeState(PresentationModeState.FULLSCREEN); - } - if (!this.#eventAbortController) { - this.#eventAbortController = new AbortController(); - this._eventBus?._on("presentationmodechanged", evt => { - this.#updatePresentationModeState(evt.state); - }, { - signal: this.#eventAbortController.signal - }); - } - } - cancel() { - this._cancelled = true; - this.#eventAbortController?.abort(); - this.#eventAbortController = null; - } - hide() { - if (!this.div) { - return; - } - this.div.hidden = true; - } - hasEditableAnnotations() { - return !!this.annotationLayer?.hasEditableAnnotations(); - } - #updatePresentationModeState(state) { - if (!this.div) { - return; - } - let disableFormElements = false; - switch (state) { - case PresentationModeState.FULLSCREEN: - disableFormElements = true; - break; - case PresentationModeState.NORMAL: - break; - default: - return; - } - for (const section of this.div.childNodes) { - if (section.hasAttribute("data-internal-link")) { - continue; - } - section.inert = disableFormElements; - } - } -} - -;// ./web/download_manager.js - -function download(blobUrl, filename) { - const a = document.createElement("a"); - if (!a.click) { - throw new Error('DownloadManager: "a.click()" is not supported.'); - } - a.href = blobUrl; - a.target = "_parent"; - if ("download" in a) { - a.download = filename; - } - (document.body || document.documentElement).append(a); - a.click(); - a.remove(); -} -class DownloadManager { - #openBlobUrls = new WeakMap(); - downloadData(data, filename, contentType) { - const blobUrl = URL.createObjectURL(new Blob([data], { - type: contentType - })); - download(blobUrl, filename); - } - openOrDownloadData(data, filename, dest = null) { - const isPdfData = isPdfFile(filename); - const contentType = isPdfData ? "application/pdf" : ""; - this.downloadData(data, filename, contentType); - return false; - } - download(data, url, filename) { - let blobUrl; - if (data) { - blobUrl = URL.createObjectURL(new Blob([data], { - type: "application/pdf" - })); - } else { - if (!createValidAbsoluteUrl(url, "http://example.com")) { - console.error(`download - not a valid URL: ${url}`); - return; - } - blobUrl = url + "#pdfjs.action=download"; - } - download(blobUrl, filename); - } -} - -;// ./web/event_utils.js -const WaitOnType = { - EVENT: "event", - TIMEOUT: "timeout" -}; -async function waitOnEventOrTimeout({ - target, - name, - delay = 0 -}) { - if (typeof target !== "object" || !(name && typeof name === "string") || !(Number.isInteger(delay) && delay >= 0)) { - throw new Error("waitOnEventOrTimeout - invalid parameters."); - } - const { - promise, - resolve - } = Promise.withResolvers(); - const ac = new AbortController(); - function handler(type) { - ac.abort(); - clearTimeout(timeout); - resolve(type); - } - const evtMethod = target instanceof EventBus ? "_on" : "addEventListener"; - target[evtMethod](name, handler.bind(null, WaitOnType.EVENT), { - signal: ac.signal - }); - const timeout = setTimeout(handler.bind(null, WaitOnType.TIMEOUT), delay); - return promise; -} -class EventBus { - #listeners = Object.create(null); - on(eventName, listener, options = null) { - this._on(eventName, listener, { - external: true, - once: options?.once, - signal: options?.signal - }); - } - off(eventName, listener, options = null) { - this._off(eventName, listener); - } - dispatch(eventName, data) { - const eventListeners = this.#listeners[eventName]; - if (!eventListeners || eventListeners.length === 0) { - return; - } - let externalListeners; - for (const { - listener, - external, - once - } of eventListeners.slice(0)) { - if (once) { - this._off(eventName, listener); - } - if (external) { - (externalListeners ||= []).push(listener); - continue; - } - listener(data); - } - if (externalListeners) { - for (const listener of externalListeners) { - listener(data); - } - externalListeners = null; - } - } - _on(eventName, listener, options = null) { - let rmAbort = null; - if (options?.signal instanceof AbortSignal) { - const { - signal - } = options; - if (signal.aborted) { - console.error("Cannot use an `aborted` signal."); - return; - } - const onAbort = () => this._off(eventName, listener); - rmAbort = () => signal.removeEventListener("abort", onAbort); - signal.addEventListener("abort", onAbort); - } - const eventListeners = this.#listeners[eventName] ||= []; - eventListeners.push({ - listener, - external: options?.external === true, - once: options?.once === true, - rmAbort - }); - } - _off(eventName, listener, options = null) { - const eventListeners = this.#listeners[eventName]; - if (!eventListeners) { - return; - } - for (let i = 0, ii = eventListeners.length; i < ii; i++) { - const evt = eventListeners[i]; - if (evt.listener === listener) { - evt.rmAbort?.(); - eventListeners.splice(i, 1); - return; - } - } - } -} -class FirefoxEventBus extends EventBus { - #externalServices; - #globalEventNames; - #isInAutomation; - constructor(globalEventNames, externalServices, isInAutomation) { - super(); - this.#globalEventNames = globalEventNames; - this.#externalServices = externalServices; - this.#isInAutomation = isInAutomation; - } - dispatch(eventName, data) { - throw new Error("Not implemented: FirefoxEventBus.dispatch"); - } -} - -;// ./node_modules/@fluent/bundle/esm/types.js -class FluentType { - constructor(value) { - this.value = value; - } - valueOf() { - return this.value; - } -} -class FluentNone extends FluentType { - constructor(value = "???") { - super(value); - } - toString(scope) { - return `{${this.value}}`; - } -} -class FluentNumber extends FluentType { - constructor(value, opts = {}) { - super(value); - this.opts = opts; - } - toString(scope) { - try { - const nf = scope.memoizeIntlObject(Intl.NumberFormat, this.opts); - return nf.format(this.value); - } catch (err) { - scope.reportError(err); - return this.value.toString(10); - } - } -} -class FluentDateTime extends FluentType { - constructor(value, opts = {}) { - super(value); - this.opts = opts; - } - toString(scope) { - try { - const dtf = scope.memoizeIntlObject(Intl.DateTimeFormat, this.opts); - return dtf.format(this.value); - } catch (err) { - scope.reportError(err); - return new Date(this.value).toISOString(); - } - } -} -;// ./node_modules/@fluent/bundle/esm/resolver.js - -const MAX_PLACEABLES = 100; -const FSI = "\u2068"; -const PDI = "\u2069"; -function match(scope, selector, key) { - if (key === selector) { - return true; - } - if (key instanceof FluentNumber && selector instanceof FluentNumber && key.value === selector.value) { - return true; - } - if (selector instanceof FluentNumber && typeof key === "string") { - let category = scope.memoizeIntlObject(Intl.PluralRules, selector.opts).select(selector.value); - if (key === category) { - return true; - } - } - return false; -} -function getDefault(scope, variants, star) { - if (variants[star]) { - return resolvePattern(scope, variants[star].value); - } - scope.reportError(new RangeError("No default")); - return new FluentNone(); -} -function getArguments(scope, args) { - const positional = []; - const named = Object.create(null); - for (const arg of args) { - if (arg.type === "narg") { - named[arg.name] = resolveExpression(scope, arg.value); - } else { - positional.push(resolveExpression(scope, arg)); - } - } - return { - positional, - named - }; -} -function resolveExpression(scope, expr) { - switch (expr.type) { - case "str": - return expr.value; - case "num": - return new FluentNumber(expr.value, { - minimumFractionDigits: expr.precision - }); - case "var": - return resolveVariableReference(scope, expr); - case "mesg": - return resolveMessageReference(scope, expr); - case "term": - return resolveTermReference(scope, expr); - case "func": - return resolveFunctionReference(scope, expr); - case "select": - return resolveSelectExpression(scope, expr); - default: - return new FluentNone(); - } -} -function resolveVariableReference(scope, { - name -}) { - let arg; - if (scope.params) { - if (Object.prototype.hasOwnProperty.call(scope.params, name)) { - arg = scope.params[name]; - } else { - return new FluentNone(`$${name}`); - } - } else if (scope.args && Object.prototype.hasOwnProperty.call(scope.args, name)) { - arg = scope.args[name]; - } else { - scope.reportError(new ReferenceError(`Unknown variable: $${name}`)); - return new FluentNone(`$${name}`); - } - if (arg instanceof FluentType) { - return arg; - } - switch (typeof arg) { - case "string": - return arg; - case "number": - return new FluentNumber(arg); - case "object": - if (arg instanceof Date) { - return new FluentDateTime(arg.getTime()); - } - default: - scope.reportError(new TypeError(`Variable type not supported: $${name}, ${typeof arg}`)); - return new FluentNone(`$${name}`); - } -} -function resolveMessageReference(scope, { - name, - attr -}) { - const message = scope.bundle._messages.get(name); - if (!message) { - scope.reportError(new ReferenceError(`Unknown message: ${name}`)); - return new FluentNone(name); - } - if (attr) { - const attribute = message.attributes[attr]; - if (attribute) { - return resolvePattern(scope, attribute); - } - scope.reportError(new ReferenceError(`Unknown attribute: ${attr}`)); - return new FluentNone(`${name}.${attr}`); - } - if (message.value) { - return resolvePattern(scope, message.value); - } - scope.reportError(new ReferenceError(`No value: ${name}`)); - return new FluentNone(name); -} -function resolveTermReference(scope, { - name, - attr, - args -}) { - const id = `-${name}`; - const term = scope.bundle._terms.get(id); - if (!term) { - scope.reportError(new ReferenceError(`Unknown term: ${id}`)); - return new FluentNone(id); - } - if (attr) { - const attribute = term.attributes[attr]; - if (attribute) { - scope.params = getArguments(scope, args).named; - const resolved = resolvePattern(scope, attribute); - scope.params = null; - return resolved; - } - scope.reportError(new ReferenceError(`Unknown attribute: ${attr}`)); - return new FluentNone(`${id}.${attr}`); - } - scope.params = getArguments(scope, args).named; - const resolved = resolvePattern(scope, term.value); - scope.params = null; - return resolved; -} -function resolveFunctionReference(scope, { - name, - args -}) { - let func = scope.bundle._functions[name]; - if (!func) { - scope.reportError(new ReferenceError(`Unknown function: ${name}()`)); - return new FluentNone(`${name}()`); - } - if (typeof func !== "function") { - scope.reportError(new TypeError(`Function ${name}() is not callable`)); - return new FluentNone(`${name}()`); - } - try { - let resolved = getArguments(scope, args); - return func(resolved.positional, resolved.named); - } catch (err) { - scope.reportError(err); - return new FluentNone(`${name}()`); - } -} -function resolveSelectExpression(scope, { - selector, - variants, - star -}) { - let sel = resolveExpression(scope, selector); - if (sel instanceof FluentNone) { - return getDefault(scope, variants, star); - } - for (const variant of variants) { - const key = resolveExpression(scope, variant.key); - if (match(scope, sel, key)) { - return resolvePattern(scope, variant.value); - } - } - return getDefault(scope, variants, star); -} -function resolveComplexPattern(scope, ptn) { - if (scope.dirty.has(ptn)) { - scope.reportError(new RangeError("Cyclic reference")); - return new FluentNone(); - } - scope.dirty.add(ptn); - const result = []; - const useIsolating = scope.bundle._useIsolating && ptn.length > 1; - for (const elem of ptn) { - if (typeof elem === "string") { - result.push(scope.bundle._transform(elem)); - continue; - } - scope.placeables++; - if (scope.placeables > MAX_PLACEABLES) { - scope.dirty.delete(ptn); - throw new RangeError(`Too many placeables expanded: ${scope.placeables}, ` + `max allowed is ${MAX_PLACEABLES}`); - } - if (useIsolating) { - result.push(FSI); - } - result.push(resolveExpression(scope, elem).toString(scope)); - if (useIsolating) { - result.push(PDI); - } - } - scope.dirty.delete(ptn); - return result.join(""); -} -function resolvePattern(scope, value) { - if (typeof value === "string") { - return scope.bundle._transform(value); - } - return resolveComplexPattern(scope, value); -} -;// ./node_modules/@fluent/bundle/esm/scope.js -class Scope { - constructor(bundle, errors, args) { - this.dirty = new WeakSet(); - this.params = null; - this.placeables = 0; - this.bundle = bundle; - this.errors = errors; - this.args = args; - } - reportError(error) { - if (!this.errors || !(error instanceof Error)) { - throw error; - } - this.errors.push(error); - } - memoizeIntlObject(ctor, opts) { - let cache = this.bundle._intls.get(ctor); - if (!cache) { - cache = {}; - this.bundle._intls.set(ctor, cache); - } - let id = JSON.stringify(opts); - if (!cache[id]) { - cache[id] = new ctor(this.bundle.locales, opts); - } - return cache[id]; - } -} -;// ./node_modules/@fluent/bundle/esm/builtins.js - -function values(opts, allowed) { - const unwrapped = Object.create(null); - for (const [name, opt] of Object.entries(opts)) { - if (allowed.includes(name)) { - unwrapped[name] = opt.valueOf(); - } - } - return unwrapped; -} -const NUMBER_ALLOWED = ["unitDisplay", "currencyDisplay", "useGrouping", "minimumIntegerDigits", "minimumFractionDigits", "maximumFractionDigits", "minimumSignificantDigits", "maximumSignificantDigits"]; -function NUMBER(args, opts) { - let arg = args[0]; - if (arg instanceof FluentNone) { - return new FluentNone(`NUMBER(${arg.valueOf()})`); - } - if (arg instanceof FluentNumber) { - return new FluentNumber(arg.valueOf(), { - ...arg.opts, - ...values(opts, NUMBER_ALLOWED) - }); - } - if (arg instanceof FluentDateTime) { - return new FluentNumber(arg.valueOf(), { - ...values(opts, NUMBER_ALLOWED) - }); - } - throw new TypeError("Invalid argument to NUMBER"); -} -const DATETIME_ALLOWED = ["dateStyle", "timeStyle", "fractionalSecondDigits", "dayPeriod", "hour12", "weekday", "era", "year", "month", "day", "hour", "minute", "second", "timeZoneName"]; -function DATETIME(args, opts) { - let arg = args[0]; - if (arg instanceof FluentNone) { - return new FluentNone(`DATETIME(${arg.valueOf()})`); - } - if (arg instanceof FluentDateTime) { - return new FluentDateTime(arg.valueOf(), { - ...arg.opts, - ...values(opts, DATETIME_ALLOWED) - }); - } - if (arg instanceof FluentNumber) { - return new FluentDateTime(arg.valueOf(), { - ...values(opts, DATETIME_ALLOWED) - }); - } - throw new TypeError("Invalid argument to DATETIME"); -} -;// ./node_modules/@fluent/bundle/esm/memoizer.js -const cache = new Map(); -function getMemoizerForLocale(locales) { - const stringLocale = Array.isArray(locales) ? locales.join(" ") : locales; - let memoizer = cache.get(stringLocale); - if (memoizer === undefined) { - memoizer = new Map(); - cache.set(stringLocale, memoizer); - } - return memoizer; -} -;// ./node_modules/@fluent/bundle/esm/bundle.js - - - - - -class FluentBundle { - constructor(locales, { - functions, - useIsolating = true, - transform = v => v - } = {}) { - this._terms = new Map(); - this._messages = new Map(); - this.locales = Array.isArray(locales) ? locales : [locales]; - this._functions = { - NUMBER: NUMBER, - DATETIME: DATETIME, - ...functions - }; - this._useIsolating = useIsolating; - this._transform = transform; - this._intls = getMemoizerForLocale(locales); - } - hasMessage(id) { - return this._messages.has(id); - } - getMessage(id) { - return this._messages.get(id); - } - addResource(res, { - allowOverrides = false - } = {}) { - const errors = []; - for (let i = 0; i < res.body.length; i++) { - let entry = res.body[i]; - if (entry.id.startsWith("-")) { - if (allowOverrides === false && this._terms.has(entry.id)) { - errors.push(new Error(`Attempt to override an existing term: "${entry.id}"`)); - continue; - } - this._terms.set(entry.id, entry); - } else { - if (allowOverrides === false && this._messages.has(entry.id)) { - errors.push(new Error(`Attempt to override an existing message: "${entry.id}"`)); - continue; - } - this._messages.set(entry.id, entry); - } - } - return errors; - } - formatPattern(pattern, args = null, errors = null) { - if (typeof pattern === "string") { - return this._transform(pattern); - } - let scope = new Scope(this, errors, args); - try { - let value = resolveComplexPattern(scope, pattern); - return value.toString(scope); - } catch (err) { - if (scope.errors && err instanceof Error) { - scope.errors.push(err); - return new FluentNone().toString(scope); - } - throw err; - } - } -} -;// ./node_modules/@fluent/bundle/esm/resource.js -const RE_MESSAGE_START = /^(-?[a-zA-Z][\w-]*) *= */gm; -const RE_ATTRIBUTE_START = /\.([a-zA-Z][\w-]*) *= */y; -const RE_VARIANT_START = /\*?\[/y; -const RE_NUMBER_LITERAL = /(-?[0-9]+(?:\.([0-9]+))?)/y; -const RE_IDENTIFIER = /([a-zA-Z][\w-]*)/y; -const RE_REFERENCE = /([$-])?([a-zA-Z][\w-]*)(?:\.([a-zA-Z][\w-]*))?/y; -const RE_FUNCTION_NAME = /^[A-Z][A-Z0-9_-]*$/; -const RE_TEXT_RUN = /([^{}\n\r]+)/y; -const RE_STRING_RUN = /([^\\"\n\r]*)/y; -const RE_STRING_ESCAPE = /\\([\\"])/y; -const RE_UNICODE_ESCAPE = /\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{6})/y; -const RE_LEADING_NEWLINES = /^\n+/; -const RE_TRAILING_SPACES = / +$/; -const RE_BLANK_LINES = / *\r?\n/g; -const RE_INDENT = /( *)$/; -const TOKEN_BRACE_OPEN = /{\s*/y; -const TOKEN_BRACE_CLOSE = /\s*}/y; -const TOKEN_BRACKET_OPEN = /\[\s*/y; -const TOKEN_BRACKET_CLOSE = /\s*] */y; -const TOKEN_PAREN_OPEN = /\s*\(\s*/y; -const TOKEN_ARROW = /\s*->\s*/y; -const TOKEN_COLON = /\s*:\s*/y; -const TOKEN_COMMA = /\s*,?\s*/y; -const TOKEN_BLANK = /\s+/y; -class FluentResource { - constructor(source) { - this.body = []; - RE_MESSAGE_START.lastIndex = 0; - let cursor = 0; - while (true) { - let next = RE_MESSAGE_START.exec(source); - if (next === null) { - break; - } - cursor = RE_MESSAGE_START.lastIndex; - try { - this.body.push(parseMessage(next[1])); - } catch (err) { - if (err instanceof SyntaxError) { - continue; - } - throw err; - } - } - function test(re) { - re.lastIndex = cursor; - return re.test(source); - } - function consumeChar(char, errorClass) { - if (source[cursor] === char) { - cursor++; - return true; - } - if (errorClass) { - throw new errorClass(`Expected ${char}`); - } - return false; - } - function consumeToken(re, errorClass) { - if (test(re)) { - cursor = re.lastIndex; - return true; - } - if (errorClass) { - throw new errorClass(`Expected ${re.toString()}`); - } - return false; - } - function match(re) { - re.lastIndex = cursor; - let result = re.exec(source); - if (result === null) { - throw new SyntaxError(`Expected ${re.toString()}`); - } - cursor = re.lastIndex; - return result; - } - function match1(re) { - return match(re)[1]; - } - function parseMessage(id) { - let value = parsePattern(); - let attributes = parseAttributes(); - if (value === null && Object.keys(attributes).length === 0) { - throw new SyntaxError("Expected message value or attributes"); - } - return { - id, - value, - attributes - }; - } - function parseAttributes() { - let attrs = Object.create(null); - while (test(RE_ATTRIBUTE_START)) { - let name = match1(RE_ATTRIBUTE_START); - let value = parsePattern(); - if (value === null) { - throw new SyntaxError("Expected attribute value"); - } - attrs[name] = value; - } - return attrs; - } - function parsePattern() { - let first; - if (test(RE_TEXT_RUN)) { - first = match1(RE_TEXT_RUN); - } - if (source[cursor] === "{" || source[cursor] === "}") { - return parsePatternElements(first ? [first] : [], Infinity); - } - let indent = parseIndent(); - if (indent) { - if (first) { - return parsePatternElements([first, indent], indent.length); - } - indent.value = trim(indent.value, RE_LEADING_NEWLINES); - return parsePatternElements([indent], indent.length); - } - if (first) { - return trim(first, RE_TRAILING_SPACES); - } - return null; - } - function parsePatternElements(elements = [], commonIndent) { - while (true) { - if (test(RE_TEXT_RUN)) { - elements.push(match1(RE_TEXT_RUN)); - continue; - } - if (source[cursor] === "{") { - elements.push(parsePlaceable()); - continue; - } - if (source[cursor] === "}") { - throw new SyntaxError("Unbalanced closing brace"); - } - let indent = parseIndent(); - if (indent) { - elements.push(indent); - commonIndent = Math.min(commonIndent, indent.length); - continue; - } - break; - } - let lastIndex = elements.length - 1; - let lastElement = elements[lastIndex]; - if (typeof lastElement === "string") { - elements[lastIndex] = trim(lastElement, RE_TRAILING_SPACES); - } - let baked = []; - for (let element of elements) { - if (element instanceof Indent) { - element = element.value.slice(0, element.value.length - commonIndent); - } - if (element) { - baked.push(element); - } - } - return baked; - } - function parsePlaceable() { - consumeToken(TOKEN_BRACE_OPEN, SyntaxError); - let selector = parseInlineExpression(); - if (consumeToken(TOKEN_BRACE_CLOSE)) { - return selector; - } - if (consumeToken(TOKEN_ARROW)) { - let variants = parseVariants(); - consumeToken(TOKEN_BRACE_CLOSE, SyntaxError); - return { - type: "select", - selector, - ...variants - }; - } - throw new SyntaxError("Unclosed placeable"); - } - function parseInlineExpression() { - if (source[cursor] === "{") { - return parsePlaceable(); - } - if (test(RE_REFERENCE)) { - let [, sigil, name, attr = null] = match(RE_REFERENCE); - if (sigil === "$") { - return { - type: "var", - name - }; - } - if (consumeToken(TOKEN_PAREN_OPEN)) { - let args = parseArguments(); - if (sigil === "-") { - return { - type: "term", - name, - attr, - args - }; - } - if (RE_FUNCTION_NAME.test(name)) { - return { - type: "func", - name, - args - }; - } - throw new SyntaxError("Function names must be all upper-case"); - } - if (sigil === "-") { - return { - type: "term", - name, - attr, - args: [] - }; - } - return { - type: "mesg", - name, - attr - }; - } - return parseLiteral(); - } - function parseArguments() { - let args = []; - while (true) { - switch (source[cursor]) { - case ")": - cursor++; - return args; - case undefined: - throw new SyntaxError("Unclosed argument list"); - } - args.push(parseArgument()); - consumeToken(TOKEN_COMMA); - } - } - function parseArgument() { - let expr = parseInlineExpression(); - if (expr.type !== "mesg") { - return expr; - } - if (consumeToken(TOKEN_COLON)) { - return { - type: "narg", - name: expr.name, - value: parseLiteral() - }; - } - return expr; - } - function parseVariants() { - let variants = []; - let count = 0; - let star; - while (test(RE_VARIANT_START)) { - if (consumeChar("*")) { - star = count; - } - let key = parseVariantKey(); - let value = parsePattern(); - if (value === null) { - throw new SyntaxError("Expected variant value"); - } - variants[count++] = { - key, - value - }; - } - if (count === 0) { - return null; - } - if (star === undefined) { - throw new SyntaxError("Expected default variant"); - } - return { - variants, - star - }; - } - function parseVariantKey() { - consumeToken(TOKEN_BRACKET_OPEN, SyntaxError); - let key; - if (test(RE_NUMBER_LITERAL)) { - key = parseNumberLiteral(); - } else { - key = { - type: "str", - value: match1(RE_IDENTIFIER) - }; - } - consumeToken(TOKEN_BRACKET_CLOSE, SyntaxError); - return key; - } - function parseLiteral() { - if (test(RE_NUMBER_LITERAL)) { - return parseNumberLiteral(); - } - if (source[cursor] === '"') { - return parseStringLiteral(); - } - throw new SyntaxError("Invalid expression"); - } - function parseNumberLiteral() { - let [, value, fraction = ""] = match(RE_NUMBER_LITERAL); - let precision = fraction.length; - return { - type: "num", - value: parseFloat(value), - precision - }; - } - function parseStringLiteral() { - consumeChar('"', SyntaxError); - let value = ""; - while (true) { - value += match1(RE_STRING_RUN); - if (source[cursor] === "\\") { - value += parseEscapeSequence(); - continue; - } - if (consumeChar('"')) { - return { - type: "str", - value - }; - } - throw new SyntaxError("Unclosed string literal"); - } - } - function parseEscapeSequence() { - if (test(RE_STRING_ESCAPE)) { - return match1(RE_STRING_ESCAPE); - } - if (test(RE_UNICODE_ESCAPE)) { - let [, codepoint4, codepoint6] = match(RE_UNICODE_ESCAPE); - let codepoint = parseInt(codepoint4 || codepoint6, 16); - return codepoint <= 0xd7ff || 0xe000 <= codepoint ? String.fromCodePoint(codepoint) : "�"; - } - throw new SyntaxError("Unknown escape sequence"); - } - function parseIndent() { - let start = cursor; - consumeToken(TOKEN_BLANK); - switch (source[cursor]) { - case ".": - case "[": - case "*": - case "}": - case undefined: - return false; - case "{": - return makeIndent(source.slice(start, cursor)); - } - if (source[cursor - 1] === " ") { - return makeIndent(source.slice(start, cursor)); - } - return false; - } - function trim(text, re) { - return text.replace(re, ""); - } - function makeIndent(blank) { - let value = blank.replace(RE_BLANK_LINES, "\n"); - let length = RE_INDENT.exec(blank)[1].length; - return new Indent(value, length); - } - } -} -class Indent { - constructor(value, length) { - this.value = value; - this.length = length; - } -} -;// ./node_modules/@fluent/bundle/esm/index.js - - - -;// ./node_modules/@fluent/dom/esm/overlay.js -const reOverlay = /<|&#?\w+;/; -const TEXT_LEVEL_ELEMENTS = { - "http://www.w3.org/1999/xhtml": ["em", "strong", "small", "s", "cite", "q", "dfn", "abbr", "data", "time", "code", "var", "samp", "kbd", "sub", "sup", "i", "b", "u", "mark", "bdi", "bdo", "span", "br", "wbr"] -}; -const LOCALIZABLE_ATTRIBUTES = { - "http://www.w3.org/1999/xhtml": { - global: ["title", "aria-label", "aria-valuetext"], - a: ["download"], - area: ["download", "alt"], - input: ["alt", "placeholder"], - menuitem: ["label"], - menu: ["label"], - optgroup: ["label"], - option: ["label"], - track: ["label"], - img: ["alt"], - textarea: ["placeholder"], - th: ["abbr"] - }, - "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul": { - global: ["accesskey", "aria-label", "aria-valuetext", "label", "title", "tooltiptext"], - description: ["value"], - key: ["key", "keycode"], - label: ["value"], - textbox: ["placeholder", "value"] - } -}; -function translateElement(element, translation) { - const { - value - } = translation; - if (typeof value === "string") { - if (element.localName === "title" && element.namespaceURI === "http://www.w3.org/1999/xhtml") { - element.textContent = value; - } else if (!reOverlay.test(value)) { - element.textContent = value; - } else { - const templateElement = element.ownerDocument.createElementNS("http://www.w3.org/1999/xhtml", "template"); - templateElement.innerHTML = value; - overlayChildNodes(templateElement.content, element); - } - } - overlayAttributes(translation, element); -} -function overlayChildNodes(fromFragment, toElement) { - for (const childNode of fromFragment.childNodes) { - if (childNode.nodeType === childNode.TEXT_NODE) { - continue; - } - if (childNode.hasAttribute("data-l10n-name")) { - const sanitized = getNodeForNamedElement(toElement, childNode); - fromFragment.replaceChild(sanitized, childNode); - continue; - } - if (isElementAllowed(childNode)) { - const sanitized = createSanitizedElement(childNode); - fromFragment.replaceChild(sanitized, childNode); - continue; - } - console.warn(`An element of forbidden type "${childNode.localName}" was found in ` + "the translation. Only safe text-level elements and elements with " + "data-l10n-name are allowed."); - fromFragment.replaceChild(createTextNodeFromTextContent(childNode), childNode); - } - toElement.textContent = ""; - toElement.appendChild(fromFragment); -} -function hasAttribute(attributes, name) { - if (!attributes) { - return false; - } - for (let attr of attributes) { - if (attr.name === name) { - return true; - } - } - return false; -} -function overlayAttributes(fromElement, toElement) { - const explicitlyAllowed = toElement.hasAttribute("data-l10n-attrs") ? toElement.getAttribute("data-l10n-attrs").split(",").map(i => i.trim()) : null; - for (const attr of Array.from(toElement.attributes)) { - if (isAttrNameLocalizable(attr.name, toElement, explicitlyAllowed) && !hasAttribute(fromElement.attributes, attr.name)) { - toElement.removeAttribute(attr.name); - } - } - if (!fromElement.attributes) { - return; - } - for (const attr of Array.from(fromElement.attributes)) { - if (isAttrNameLocalizable(attr.name, toElement, explicitlyAllowed) && toElement.getAttribute(attr.name) !== attr.value) { - toElement.setAttribute(attr.name, attr.value); - } - } -} -function getNodeForNamedElement(sourceElement, translatedChild) { - const childName = translatedChild.getAttribute("data-l10n-name"); - const sourceChild = sourceElement.querySelector(`[data-l10n-name="${childName}"]`); - if (!sourceChild) { - console.warn(`An element named "${childName}" wasn't found in the source.`); - return createTextNodeFromTextContent(translatedChild); - } - if (sourceChild.localName !== translatedChild.localName) { - console.warn(`An element named "${childName}" was found in the translation ` + `but its type ${translatedChild.localName} didn't match the ` + `element found in the source (${sourceChild.localName}).`); - return createTextNodeFromTextContent(translatedChild); - } - sourceElement.removeChild(sourceChild); - const clone = sourceChild.cloneNode(false); - return shallowPopulateUsing(translatedChild, clone); -} -function createSanitizedElement(element) { - const clone = element.ownerDocument.createElement(element.localName); - return shallowPopulateUsing(element, clone); -} -function createTextNodeFromTextContent(element) { - return element.ownerDocument.createTextNode(element.textContent); -} -function isElementAllowed(element) { - const allowed = TEXT_LEVEL_ELEMENTS[element.namespaceURI]; - return allowed && allowed.includes(element.localName); -} -function isAttrNameLocalizable(name, element, explicitlyAllowed = null) { - if (explicitlyAllowed && explicitlyAllowed.includes(name)) { - return true; - } - const allowed = LOCALIZABLE_ATTRIBUTES[element.namespaceURI]; - if (!allowed) { - return false; - } - const attrName = name.toLowerCase(); - const elemName = element.localName; - if (allowed.global.includes(attrName)) { - return true; - } - if (!allowed[elemName]) { - return false; - } - if (allowed[elemName].includes(attrName)) { - return true; - } - if (element.namespaceURI === "http://www.w3.org/1999/xhtml" && elemName === "input" && attrName === "value") { - const type = element.type.toLowerCase(); - if (type === "submit" || type === "button" || type === "reset") { - return true; - } - } - return false; -} -function shallowPopulateUsing(fromElement, toElement) { - toElement.textContent = fromElement.textContent; - overlayAttributes(fromElement, toElement); - return toElement; -} -;// ./node_modules/cached-iterable/src/cached_iterable.mjs -class CachedIterable extends Array { - static from(iterable) { - if (iterable instanceof this) { - return iterable; - } - return new this(iterable); - } -} -;// ./node_modules/cached-iterable/src/cached_sync_iterable.mjs - -class CachedSyncIterable extends CachedIterable { - constructor(iterable) { - super(); - if (Symbol.iterator in Object(iterable)) { - this.iterator = iterable[Symbol.iterator](); - } else { - throw new TypeError("Argument must implement the iteration protocol."); - } - } - [Symbol.iterator]() { - const cached = this; - let cur = 0; - return { - next() { - if (cached.length <= cur) { - cached.push(cached.iterator.next()); - } - return cached[cur++]; - } - }; - } - touchNext(count = 1) { - let idx = 0; - while (idx++ < count) { - const last = this[this.length - 1]; - if (last && last.done) { - break; - } - this.push(this.iterator.next()); - } - return this[this.length - 1]; - } -} -;// ./node_modules/cached-iterable/src/cached_async_iterable.mjs - -class CachedAsyncIterable extends CachedIterable { - constructor(iterable) { - super(); - if (Symbol.asyncIterator in Object(iterable)) { - this.iterator = iterable[Symbol.asyncIterator](); - } else if (Symbol.iterator in Object(iterable)) { - this.iterator = iterable[Symbol.iterator](); - } else { - throw new TypeError("Argument must implement the iteration protocol."); - } - } - [Symbol.asyncIterator]() { - const cached = this; - let cur = 0; - return { - async next() { - if (cached.length <= cur) { - cached.push(cached.iterator.next()); - } - return cached[cur++]; - } - }; - } - async touchNext(count = 1) { - let idx = 0; - while (idx++ < count) { - const last = this[this.length - 1]; - if (last && (await last).done) { - break; - } - this.push(this.iterator.next()); - } - return this[this.length - 1]; - } -} -;// ./node_modules/cached-iterable/src/index.mjs - - -;// ./node_modules/@fluent/dom/esm/localization.js - -class Localization { - constructor(resourceIds = [], generateBundles) { - this.resourceIds = resourceIds; - this.generateBundles = generateBundles; - this.onChange(true); - } - addResourceIds(resourceIds, eager = false) { - this.resourceIds.push(...resourceIds); - this.onChange(eager); - return this.resourceIds.length; - } - removeResourceIds(resourceIds) { - this.resourceIds = this.resourceIds.filter(r => !resourceIds.includes(r)); - this.onChange(); - return this.resourceIds.length; - } - async formatWithFallback(keys, method) { - const translations = []; - let hasAtLeastOneBundle = false; - for await (const bundle of this.bundles) { - hasAtLeastOneBundle = true; - const missingIds = keysFromBundle(method, bundle, keys, translations); - if (missingIds.size === 0) { - break; - } - if (typeof console !== "undefined") { - const locale = bundle.locales[0]; - const ids = Array.from(missingIds).join(", "); - console.warn(`[fluent] Missing translations in ${locale}: ${ids}`); - } - } - if (!hasAtLeastOneBundle && typeof console !== "undefined") { - console.warn(`[fluent] Request for keys failed because no resource bundles got generated. - keys: ${JSON.stringify(keys)}. - resourceIds: ${JSON.stringify(this.resourceIds)}.`); - } - return translations; - } - formatMessages(keys) { - return this.formatWithFallback(keys, messageFromBundle); - } - formatValues(keys) { - return this.formatWithFallback(keys, valueFromBundle); - } - async formatValue(id, args) { - const [val] = await this.formatValues([{ - id, - args - }]); - return val; - } - handleEvent() { - this.onChange(); - } - onChange(eager = false) { - this.bundles = CachedAsyncIterable.from(this.generateBundles(this.resourceIds)); - if (eager) { - this.bundles.touchNext(2); - } - } -} -function valueFromBundle(bundle, errors, message, args) { - if (message.value) { - return bundle.formatPattern(message.value, args, errors); - } - return null; -} -function messageFromBundle(bundle, errors, message, args) { - const formatted = { - value: null, - attributes: null - }; - if (message.value) { - formatted.value = bundle.formatPattern(message.value, args, errors); - } - let attrNames = Object.keys(message.attributes); - if (attrNames.length > 0) { - formatted.attributes = new Array(attrNames.length); - for (let [i, name] of attrNames.entries()) { - let value = bundle.formatPattern(message.attributes[name], args, errors); - formatted.attributes[i] = { - name, - value - }; - } - } - return formatted; -} -function keysFromBundle(method, bundle, keys, translations) { - const messageErrors = []; - const missingIds = new Set(); - keys.forEach(({ - id, - args - }, i) => { - if (translations[i] !== undefined) { - return; - } - let message = bundle.getMessage(id); - if (message) { - messageErrors.length = 0; - translations[i] = method(bundle, messageErrors, message, args); - if (messageErrors.length > 0 && typeof console !== "undefined") { - const locale = bundle.locales[0]; - const errors = messageErrors.join(", "); - console.warn(`[fluent][resolver] errors in ${locale}/${id}: ${errors}.`); - } - } else { - missingIds.add(id); - } - }); - return missingIds; -} -;// ./node_modules/@fluent/dom/esm/dom_localization.js - - -const L10NID_ATTR_NAME = "data-l10n-id"; -const L10NARGS_ATTR_NAME = "data-l10n-args"; -const L10N_ELEMENT_QUERY = `[${L10NID_ATTR_NAME}]`; -class DOMLocalization extends Localization { - constructor(resourceIds, generateBundles) { - super(resourceIds, generateBundles); - this.roots = new Set(); - this.pendingrAF = null; - this.pendingElements = new Set(); - this.windowElement = null; - this.mutationObserver = null; - this.observerConfig = { - attributes: true, - characterData: false, - childList: true, - subtree: true, - attributeFilter: [L10NID_ATTR_NAME, L10NARGS_ATTR_NAME] - }; - } - onChange(eager = false) { - super.onChange(eager); - if (this.roots) { - this.translateRoots(); - } - } - setAttributes(element, id, args) { - element.setAttribute(L10NID_ATTR_NAME, id); - if (args) { - element.setAttribute(L10NARGS_ATTR_NAME, JSON.stringify(args)); - } else { - element.removeAttribute(L10NARGS_ATTR_NAME); - } - return element; - } - getAttributes(element) { - return { - id: element.getAttribute(L10NID_ATTR_NAME), - args: JSON.parse(element.getAttribute(L10NARGS_ATTR_NAME) || null) - }; - } - connectRoot(newRoot) { - for (const root of this.roots) { - if (root === newRoot || root.contains(newRoot) || newRoot.contains(root)) { - throw new Error("Cannot add a root that overlaps with existing root."); - } - } - if (this.windowElement) { - if (this.windowElement !== newRoot.ownerDocument.defaultView) { - throw new Error(`Cannot connect a root: - DOMLocalization already has a root from a different window.`); - } - } else { - this.windowElement = newRoot.ownerDocument.defaultView; - this.mutationObserver = new this.windowElement.MutationObserver(mutations => this.translateMutations(mutations)); - } - this.roots.add(newRoot); - this.mutationObserver.observe(newRoot, this.observerConfig); - } - disconnectRoot(root) { - this.roots.delete(root); - this.pauseObserving(); - if (this.roots.size === 0) { - this.mutationObserver = null; - if (this.windowElement && this.pendingrAF) { - this.windowElement.cancelAnimationFrame(this.pendingrAF); - } - this.windowElement = null; - this.pendingrAF = null; - this.pendingElements.clear(); - return true; - } - this.resumeObserving(); - return false; - } - translateRoots() { - const roots = Array.from(this.roots); - return Promise.all(roots.map(root => this.translateFragment(root))); - } - pauseObserving() { - if (!this.mutationObserver) { - return; - } - this.translateMutations(this.mutationObserver.takeRecords()); - this.mutationObserver.disconnect(); - } - resumeObserving() { - if (!this.mutationObserver) { - return; - } - for (const root of this.roots) { - this.mutationObserver.observe(root, this.observerConfig); - } - } - translateMutations(mutations) { - for (const mutation of mutations) { - switch (mutation.type) { - case "attributes": - if (mutation.target.hasAttribute("data-l10n-id")) { - this.pendingElements.add(mutation.target); - } - break; - case "childList": - for (const addedNode of mutation.addedNodes) { - if (addedNode.nodeType === addedNode.ELEMENT_NODE) { - if (addedNode.childElementCount) { - for (const element of this.getTranslatables(addedNode)) { - this.pendingElements.add(element); - } - } else if (addedNode.hasAttribute(L10NID_ATTR_NAME)) { - this.pendingElements.add(addedNode); - } - } - } - break; - } - } - if (this.pendingElements.size > 0) { - if (this.pendingrAF === null) { - this.pendingrAF = this.windowElement.requestAnimationFrame(() => { - this.translateElements(Array.from(this.pendingElements)); - this.pendingElements.clear(); - this.pendingrAF = null; - }); - } - } - } - translateFragment(frag) { - return this.translateElements(this.getTranslatables(frag)); - } - async translateElements(elements) { - if (!elements.length) { - return undefined; - } - const keys = elements.map(this.getKeysForElement); - const translations = await this.formatMessages(keys); - return this.applyTranslations(elements, translations); - } - applyTranslations(elements, translations) { - this.pauseObserving(); - for (let i = 0; i < elements.length; i++) { - if (translations[i] !== undefined) { - translateElement(elements[i], translations[i]); - } - } - this.resumeObserving(); - } - getTranslatables(element) { - const nodes = Array.from(element.querySelectorAll(L10N_ELEMENT_QUERY)); - if (typeof element.hasAttribute === "function" && element.hasAttribute(L10NID_ATTR_NAME)) { - nodes.push(element); - } - return nodes; - } - getKeysForElement(element) { - return { - id: element.getAttribute(L10NID_ATTR_NAME), - args: JSON.parse(element.getAttribute(L10NARGS_ATTR_NAME) || null) - }; - } -} -;// ./node_modules/@fluent/dom/esm/index.js - - -;// ./web/l10n.js -class L10n { - #dir; - #elements; - #lang; - #l10n; - constructor({ - lang, - isRTL - }, l10n = null) { - this.#lang = L10n.#fixupLangCode(lang); - this.#l10n = l10n; - this.#dir = isRTL ?? L10n.#isRTL(this.#lang) ? "rtl" : "ltr"; - } - _setL10n(l10n) { - this.#l10n = l10n; - } - getLanguage() { - return this.#lang; - } - getDirection() { - return this.#dir; - } - async get(ids, args = null, fallback) { - if (Array.isArray(ids)) { - ids = ids.map(id => ({ - id - })); - const messages = await this.#l10n.formatMessages(ids); - return messages.map(message => message.value); - } - const messages = await this.#l10n.formatMessages([{ - id: ids, - args - }]); - return messages[0]?.value || fallback; - } - async translate(element) { - (this.#elements ||= new Set()).add(element); - try { - this.#l10n.connectRoot(element); - await this.#l10n.translateRoots(); - } catch {} - } - async translateOnce(element) { - try { - await this.#l10n.translateElements([element]); - } catch (ex) { - console.error("translateOnce:", ex); - } - } - async destroy() { - if (this.#elements) { - for (const element of this.#elements) { - this.#l10n.disconnectRoot(element); - } - this.#elements.clear(); - this.#elements = null; - } - this.#l10n.pauseObserving(); - } - pause() { - this.#l10n.pauseObserving(); - } - resume() { - this.#l10n.resumeObserving(); - } - static #fixupLangCode(langCode) { - langCode = langCode?.toLowerCase() || "en-us"; - const PARTIAL_LANG_CODES = { - en: "en-us", - es: "es-es", - fy: "fy-nl", - ga: "ga-ie", - gu: "gu-in", - hi: "hi-in", - hy: "hy-am", - nb: "nb-no", - ne: "ne-np", - nn: "nn-no", - pa: "pa-in", - pt: "pt-pt", - sv: "sv-se", - zh: "zh-cn" - }; - return PARTIAL_LANG_CODES[langCode] || langCode; - } - static #isRTL(lang) { - const shortCode = lang.split("-", 1)[0]; - return ["ar", "he", "fa", "ps", "ur"].includes(shortCode); - } -} -const GenericL10n = null; - -;// ./web/genericl10n.js - - - - -function createBundle(lang, text) { - const resource = new FluentResource(text); - const bundle = new FluentBundle(lang); - const errors = bundle.addResource(resource); - if (errors.length) { - console.error("L10n errors", errors); - } - return bundle; -} -class genericl10n_GenericL10n extends L10n { - constructor(lang) { - super({ - lang - }); - const generateBundles = !lang ? genericl10n_GenericL10n.#generateBundlesFallback.bind(genericl10n_GenericL10n, this.getLanguage()) : genericl10n_GenericL10n.#generateBundles.bind(genericl10n_GenericL10n, "en-us", this.getLanguage()); - this._setL10n(new DOMLocalization([], generateBundles)); - } - static async *#generateBundles(defaultLang, baseLang) { - const { - baseURL, - paths - } = await this.#getPaths(); - const langs = [baseLang]; - if (defaultLang !== baseLang) { - const shortLang = baseLang.split("-", 1)[0]; - if (shortLang !== baseLang) { - langs.push(shortLang); - } - langs.push(defaultLang); - } - for (const lang of langs) { - const bundle = await this.#createBundle(lang, baseURL, paths); - if (bundle) { - yield bundle; - } else if (lang === "en-us") { - yield this.#createBundleFallback(lang); - } - } - } - static async #createBundle(lang, baseURL, paths) { - const path = paths[lang]; - if (!path) { - return null; - } - const url = new URL(path, baseURL); - const text = await fetchData(url, "text"); - return createBundle(lang, text); - } - static async #getPaths() { - try { - const { - href - } = document.querySelector(`link[type="application/l10n"]`); - const paths = await fetchData(href, "json"); - return { - baseURL: href.replace(/[^/]*$/, "") || "./", - paths - }; - } catch {} - return { - baseURL: "./", - paths: Object.create(null) - }; - } - static async *#generateBundlesFallback(lang) { - yield this.#createBundleFallback(lang); - } - static async #createBundleFallback(lang) { - const text = "pdfjs-previous-button =\n .title = Previous Page\npdfjs-previous-button-label = Previous\npdfjs-next-button =\n .title = Next Page\npdfjs-next-button-label = Next\npdfjs-page-input =\n .title = Page\npdfjs-of-pages = of { $pagesCount }\npdfjs-page-of-pages = ({ $pageNumber } of { $pagesCount })\npdfjs-zoom-out-button =\n .title = Zoom Out\npdfjs-zoom-out-button-label = Zoom Out\npdfjs-zoom-in-button =\n .title = Zoom In\npdfjs-zoom-in-button-label = Zoom In\npdfjs-zoom-select =\n .title = Zoom\npdfjs-presentation-mode-button =\n .title = Switch to Presentation Mode\npdfjs-presentation-mode-button-label = Presentation Mode\npdfjs-open-file-button =\n .title = Open File\npdfjs-open-file-button-label = Open\npdfjs-print-button =\n .title = Print\npdfjs-print-button-label = Print\npdfjs-save-button =\n .title = Save\npdfjs-save-button-label = Save\npdfjs-download-button =\n .title = Download\npdfjs-download-button-label = Download\npdfjs-bookmark-button =\n .title = Current Page (View URL from Current Page)\npdfjs-bookmark-button-label = Current Page\npdfjs-tools-button =\n .title = Tools\npdfjs-tools-button-label = Tools\npdfjs-first-page-button =\n .title = Go to First Page\npdfjs-first-page-button-label = Go to First Page\npdfjs-last-page-button =\n .title = Go to Last Page\npdfjs-last-page-button-label = Go to Last Page\npdfjs-page-rotate-cw-button =\n .title = Rotate Clockwise\npdfjs-page-rotate-cw-button-label = Rotate Clockwise\npdfjs-page-rotate-ccw-button =\n .title = Rotate Counterclockwise\npdfjs-page-rotate-ccw-button-label = Rotate Counterclockwise\npdfjs-cursor-text-select-tool-button =\n .title = Enable Text Selection Tool\npdfjs-cursor-text-select-tool-button-label = Text Selection Tool\npdfjs-cursor-hand-tool-button =\n .title = Enable Hand Tool\npdfjs-cursor-hand-tool-button-label = Hand Tool\npdfjs-scroll-page-button =\n .title = Use Page Scrolling\npdfjs-scroll-page-button-label = Page Scrolling\npdfjs-scroll-vertical-button =\n .title = Use Vertical Scrolling\npdfjs-scroll-vertical-button-label = Vertical Scrolling\npdfjs-scroll-horizontal-button =\n .title = Use Horizontal Scrolling\npdfjs-scroll-horizontal-button-label = Horizontal Scrolling\npdfjs-scroll-wrapped-button =\n .title = Use Wrapped Scrolling\npdfjs-scroll-wrapped-button-label = Wrapped Scrolling\npdfjs-spread-none-button =\n .title = Do not join page spreads\npdfjs-spread-none-button-label = No Spreads\npdfjs-spread-odd-button =\n .title = Join page spreads starting with odd-numbered pages\npdfjs-spread-odd-button-label = Odd Spreads\npdfjs-spread-even-button =\n .title = Join page spreads starting with even-numbered pages\npdfjs-spread-even-button-label = Even Spreads\npdfjs-document-properties-button =\n .title = Document Properties\u2026\npdfjs-document-properties-button-label = Document Properties\u2026\npdfjs-document-properties-file-name = File name:\npdfjs-document-properties-file-size = File size:\npdfjs-document-properties-size-kb = { NUMBER($kb, maximumSignificantDigits: 3) } KB ({ $b } bytes)\npdfjs-document-properties-size-mb = { NUMBER($mb, maximumSignificantDigits: 3) } MB ({ $b } bytes)\npdfjs-document-properties-title = Title:\npdfjs-document-properties-author = Author:\npdfjs-document-properties-subject = Subject:\npdfjs-document-properties-keywords = Keywords:\npdfjs-document-properties-creation-date = Creation Date:\npdfjs-document-properties-modification-date = Modification Date:\npdfjs-document-properties-date-time-string = { DATETIME($dateObj, dateStyle: \"short\", timeStyle: \"medium\") }\npdfjs-document-properties-creator = Creator:\npdfjs-document-properties-producer = PDF Producer:\npdfjs-document-properties-version = PDF Version:\npdfjs-document-properties-page-count = Page Count:\npdfjs-document-properties-page-size = Page Size:\npdfjs-document-properties-page-size-unit-inches = in\npdfjs-document-properties-page-size-unit-millimeters = mm\npdfjs-document-properties-page-size-orientation-portrait = portrait\npdfjs-document-properties-page-size-orientation-landscape = landscape\npdfjs-document-properties-page-size-name-a-three = A3\npdfjs-document-properties-page-size-name-a-four = A4\npdfjs-document-properties-page-size-name-letter = Letter\npdfjs-document-properties-page-size-name-legal = Legal\npdfjs-document-properties-page-size-dimension-string = { $width } \xD7 { $height } { $unit } ({ $orientation })\npdfjs-document-properties-page-size-dimension-name-string = { $width } \xD7 { $height } { $unit } ({ $name }, { $orientation })\npdfjs-document-properties-linearized = Fast Web View:\npdfjs-document-properties-linearized-yes = Yes\npdfjs-document-properties-linearized-no = No\npdfjs-document-properties-close-button = Close\npdfjs-print-progress-message = Preparing document for printing\u2026\npdfjs-print-progress-percent = { $progress }%\npdfjs-print-progress-close-button = Cancel\npdfjs-printing-not-supported = Warning: Printing is not fully supported by this browser.\npdfjs-printing-not-ready = Warning: The PDF is not fully loaded for printing.\npdfjs-toggle-sidebar-button =\n .title = Toggle Sidebar\npdfjs-toggle-sidebar-notification-button =\n .title = Toggle Sidebar (document contains outline/attachments/layers)\npdfjs-toggle-sidebar-button-label = Toggle Sidebar\npdfjs-document-outline-button =\n .title = Show Document Outline (double-click to expand/collapse all items)\npdfjs-document-outline-button-label = Document Outline\npdfjs-attachments-button =\n .title = Show Attachments\npdfjs-attachments-button-label = Attachments\npdfjs-layers-button =\n .title = Show Layers (double-click to reset all layers to the default state)\npdfjs-layers-button-label = Layers\npdfjs-thumbs-button =\n .title = Show Thumbnails\npdfjs-thumbs-button-label = Thumbnails\npdfjs-current-outline-item-button =\n .title = Find Current Outline Item\npdfjs-current-outline-item-button-label = Current Outline Item\npdfjs-findbar-button =\n .title = Find in Document\npdfjs-findbar-button-label = Find\npdfjs-additional-layers = Additional Layers\npdfjs-thumb-page-title =\n .title = Page { $page }\npdfjs-thumb-page-canvas =\n .aria-label = Thumbnail of Page { $page }\npdfjs-find-input =\n .title = Find\n .placeholder = Find in document\u2026\npdfjs-find-previous-button =\n .title = Find the previous occurrence of the phrase\npdfjs-find-previous-button-label = Previous\npdfjs-find-next-button =\n .title = Find the next occurrence of the phrase\npdfjs-find-next-button-label = Next\npdfjs-find-highlight-checkbox = Highlight All\npdfjs-find-match-case-checkbox-label = Match Case\npdfjs-find-match-diacritics-checkbox-label = Match Diacritics\npdfjs-find-entire-word-checkbox-label = Whole Words\npdfjs-find-reached-top = Reached top of document, continued from bottom\npdfjs-find-reached-bottom = Reached end of document, continued from top\npdfjs-find-match-count =\n { $total ->\n [one] { $current } of { $total } match\n *[other] { $current } of { $total } matches\n }\npdfjs-find-match-count-limit =\n { $limit ->\n [one] More than { $limit } match\n *[other] More than { $limit } matches\n }\npdfjs-find-not-found = Phrase not found\npdfjs-page-scale-width = Page Width\npdfjs-page-scale-fit = Page Fit\npdfjs-page-scale-auto = Automatic Zoom\npdfjs-page-scale-actual = Actual Size\npdfjs-page-scale-percent = { $scale }%\npdfjs-page-landmark =\n .aria-label = Page { $page }\npdfjs-loading-error = An error occurred while loading the PDF.\npdfjs-invalid-file-error = Invalid or corrupted PDF file.\npdfjs-missing-file-error = Missing PDF file.\npdfjs-unexpected-response-error = Unexpected server response.\npdfjs-rendering-error = An error occurred while rendering the page.\npdfjs-annotation-date-time-string = { DATETIME($dateObj, dateStyle: \"short\", timeStyle: \"medium\") }\npdfjs-text-annotation-type =\n .alt = [{ $type } Annotation]\npdfjs-password-label = Enter the password to open this PDF file.\npdfjs-password-invalid = Invalid password. Please try again.\npdfjs-password-ok-button = OK\npdfjs-password-cancel-button = Cancel\npdfjs-web-fonts-disabled = Web fonts are disabled: unable to use embedded PDF fonts.\npdfjs-editor-free-text-button =\n .title = Text\npdfjs-editor-free-text-button-label = Text\npdfjs-editor-ink-button =\n .title = Draw\npdfjs-editor-ink-button-label = Draw\npdfjs-editor-stamp-button =\n .title = Add or edit images\npdfjs-editor-stamp-button-label = Add or edit images\npdfjs-editor-highlight-button =\n .title = Highlight\npdfjs-editor-highlight-button-label = Highlight\npdfjs-highlight-floating-button1 =\n .title = Highlight\n .aria-label = Highlight\npdfjs-highlight-floating-button-label = Highlight\npdfjs-editor-remove-ink-button =\n .title = Remove drawing\npdfjs-editor-remove-freetext-button =\n .title = Remove text\npdfjs-editor-remove-stamp-button =\n .title = Remove image\npdfjs-editor-remove-highlight-button =\n .title = Remove highlight\npdfjs-editor-free-text-color-input = Color\npdfjs-editor-free-text-size-input = Size\npdfjs-editor-ink-color-input = Color\npdfjs-editor-ink-thickness-input = Thickness\npdfjs-editor-ink-opacity-input = Opacity\npdfjs-editor-stamp-add-image-button =\n .title = Add image\npdfjs-editor-stamp-add-image-button-label = Add image\npdfjs-editor-free-highlight-thickness-input = Thickness\npdfjs-editor-free-highlight-thickness-title =\n .title = Change thickness when highlighting items other than text\npdfjs-free-text2 =\n .aria-label = Text Editor\n .default-content = Start typing\u2026\npdfjs-ink =\n .aria-label = Draw Editor\npdfjs-ink-canvas =\n .aria-label = User-created image\npdfjs-editor-alt-text-button =\n .aria-label = Alt text\npdfjs-editor-alt-text-button-label = Alt text\npdfjs-editor-alt-text-edit-button =\n .aria-label = Edit alt text\npdfjs-editor-alt-text-dialog-label = Choose an option\npdfjs-editor-alt-text-dialog-description = Alt text (alternative text) helps when people can\u2019t see the image or when it doesn\u2019t load.\npdfjs-editor-alt-text-add-description-label = Add a description\npdfjs-editor-alt-text-add-description-description = Aim for 1-2 sentences that describe the subject, setting, or actions.\npdfjs-editor-alt-text-mark-decorative-label = Mark as decorative\npdfjs-editor-alt-text-mark-decorative-description = This is used for ornamental images, like borders or watermarks.\npdfjs-editor-alt-text-cancel-button = Cancel\npdfjs-editor-alt-text-save-button = Save\npdfjs-editor-alt-text-decorative-tooltip = Marked as decorative\npdfjs-editor-alt-text-textarea =\n .placeholder = For example, \u201CA young man sits down at a table to eat a meal\u201D\npdfjs-editor-resizer-top-left =\n .aria-label = Top left corner \u2014 resize\npdfjs-editor-resizer-top-middle =\n .aria-label = Top middle \u2014 resize\npdfjs-editor-resizer-top-right =\n .aria-label = Top right corner \u2014 resize\npdfjs-editor-resizer-middle-right =\n .aria-label = Middle right \u2014 resize\npdfjs-editor-resizer-bottom-right =\n .aria-label = Bottom right corner \u2014 resize\npdfjs-editor-resizer-bottom-middle =\n .aria-label = Bottom middle \u2014 resize\npdfjs-editor-resizer-bottom-left =\n .aria-label = Bottom left corner \u2014 resize\npdfjs-editor-resizer-middle-left =\n .aria-label = Middle left \u2014 resize\npdfjs-editor-highlight-colorpicker-label = Highlight color\npdfjs-editor-colorpicker-button =\n .title = Change color\npdfjs-editor-colorpicker-dropdown =\n .aria-label = Color choices\npdfjs-editor-colorpicker-yellow =\n .title = Yellow\npdfjs-editor-colorpicker-green =\n .title = Green\npdfjs-editor-colorpicker-blue =\n .title = Blue\npdfjs-editor-colorpicker-pink =\n .title = Pink\npdfjs-editor-colorpicker-red =\n .title = Red\npdfjs-editor-highlight-show-all-button-label = Show all\npdfjs-editor-highlight-show-all-button =\n .title = Show all\npdfjs-editor-new-alt-text-dialog-edit-label = Edit alt text (image description)\npdfjs-editor-new-alt-text-dialog-add-label = Add alt text (image description)\npdfjs-editor-new-alt-text-textarea =\n .placeholder = Write your description here\u2026\npdfjs-editor-new-alt-text-description = Short description for people who can\u2019t see the image or when the image doesn\u2019t load.\npdfjs-editor-new-alt-text-disclaimer1 = This alt text was created automatically and may be inaccurate.\npdfjs-editor-new-alt-text-disclaimer-learn-more-url = Learn more\npdfjs-editor-new-alt-text-create-automatically-button-label = Create alt text automatically\npdfjs-editor-new-alt-text-not-now-button = Not now\npdfjs-editor-new-alt-text-error-title = Couldn\u2019t create alt text automatically\npdfjs-editor-new-alt-text-error-description = Please write your own alt text or try again later.\npdfjs-editor-new-alt-text-error-close-button = Close\npdfjs-editor-new-alt-text-ai-model-downloading-progress = Downloading alt text AI model ({ $downloadedSize } of { $totalSize } MB)\n .aria-valuetext = Downloading alt text AI model ({ $downloadedSize } of { $totalSize } MB)\npdfjs-editor-new-alt-text-added-button =\n .aria-label = Alt text added\npdfjs-editor-new-alt-text-added-button-label = Alt text added\npdfjs-editor-new-alt-text-missing-button =\n .aria-label = Missing alt text\npdfjs-editor-new-alt-text-missing-button-label = Missing alt text\npdfjs-editor-new-alt-text-to-review-button =\n .aria-label = Review alt text\npdfjs-editor-new-alt-text-to-review-button-label = Review alt text\npdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer = Created automatically: { $generatedAltText }\npdfjs-image-alt-text-settings-button =\n .title = Image alt text settings\npdfjs-image-alt-text-settings-button-label = Image alt text settings\npdfjs-editor-alt-text-settings-dialog-label = Image alt text settings\npdfjs-editor-alt-text-settings-automatic-title = Automatic alt text\npdfjs-editor-alt-text-settings-create-model-button-label = Create alt text automatically\npdfjs-editor-alt-text-settings-create-model-description = Suggests descriptions to help people who can\u2019t see the image or when the image doesn\u2019t load.\npdfjs-editor-alt-text-settings-download-model-label = Alt text AI model ({ $totalSize } MB)\npdfjs-editor-alt-text-settings-ai-model-description = Runs locally on your device so your data stays private. Required for automatic alt text.\npdfjs-editor-alt-text-settings-delete-model-button = Delete\npdfjs-editor-alt-text-settings-download-model-button = Download\npdfjs-editor-alt-text-settings-downloading-model-button = Downloading\u2026\npdfjs-editor-alt-text-settings-editor-title = Alt text editor\npdfjs-editor-alt-text-settings-show-dialog-button-label = Show alt text editor right away when adding an image\npdfjs-editor-alt-text-settings-show-dialog-description = Helps you make sure all your images have alt text.\npdfjs-editor-alt-text-settings-close-button = Close\npdfjs-editor-undo-bar-message-highlight = Highlight removed\npdfjs-editor-undo-bar-message-freetext = Text removed\npdfjs-editor-undo-bar-message-ink = Drawing removed\npdfjs-editor-undo-bar-message-stamp = Image removed\npdfjs-editor-undo-bar-message-multiple =\n { $count ->\n [one] { $count } annotation removed\n *[other] { $count } annotations removed\n }\npdfjs-editor-undo-bar-undo-button =\n .title = Undo\npdfjs-editor-undo-bar-undo-button-label = Undo\npdfjs-editor-undo-bar-close-button =\n .title = Close\npdfjs-editor-undo-bar-close-button-label = Close"; - return createBundle(lang, text); - } -} - -;// ./web/pdf_history.js - - -const HASH_CHANGE_TIMEOUT = 1000; -const POSITION_UPDATED_THRESHOLD = 50; -const UPDATE_VIEWAREA_TIMEOUT = 1000; -function getCurrentHash() { - return document.location.hash; -} -class PDFHistory { - #eventAbortController = null; - constructor({ - linkService, - eventBus - }) { - this.linkService = linkService; - this.eventBus = eventBus; - this._initialized = false; - this._fingerprint = ""; - this.reset(); - this.eventBus._on("pagesinit", () => { - this._isPagesLoaded = false; - this.eventBus._on("pagesloaded", evt => { - this._isPagesLoaded = !!evt.pagesCount; - }, { - once: true - }); - }); - } - initialize({ - fingerprint, - resetHistory = false, - updateUrl = false - }) { - if (!fingerprint || typeof fingerprint !== "string") { - console.error('PDFHistory.initialize: The "fingerprint" must be a non-empty string.'); - return; - } - if (this._initialized) { - this.reset(); - } - const reInitialized = this._fingerprint !== "" && this._fingerprint !== fingerprint; - this._fingerprint = fingerprint; - this._updateUrl = updateUrl === true; - this._initialized = true; - this.#bindEvents(); - const state = window.history.state; - this._popStateInProgress = false; - this._blockHashChange = 0; - this._currentHash = getCurrentHash(); - this._numPositionUpdates = 0; - this._uid = this._maxUid = 0; - this._destination = null; - this._position = null; - if (!this.#isValidState(state, true) || resetHistory) { - const { - hash, - page, - rotation - } = this.#parseCurrentHash(true); - if (!hash || reInitialized || resetHistory) { - this.#pushOrReplaceState(null, true); - return; - } - this.#pushOrReplaceState({ - hash, - page, - rotation - }, true); - return; - } - const destination = state.destination; - this.#updateInternalState(destination, state.uid, true); - if (destination.rotation !== undefined) { - this._initialRotation = destination.rotation; - } - if (destination.dest) { - this._initialBookmark = JSON.stringify(destination.dest); - this._destination.page = null; - } else if (destination.hash) { - this._initialBookmark = destination.hash; - } else if (destination.page) { - this._initialBookmark = `page=${destination.page}`; - } - } - reset() { - if (this._initialized) { - this.#pageHide(); - this._initialized = false; - this.#unbindEvents(); - } - if (this._updateViewareaTimeout) { - clearTimeout(this._updateViewareaTimeout); - this._updateViewareaTimeout = null; - } - this._initialBookmark = null; - this._initialRotation = null; - } - push({ - namedDest = null, - explicitDest, - pageNumber - }) { - if (!this._initialized) { - return; - } - if (namedDest && typeof namedDest !== "string") { - console.error("PDFHistory.push: " + `"${namedDest}" is not a valid namedDest parameter.`); - return; - } else if (!Array.isArray(explicitDest)) { - console.error("PDFHistory.push: " + `"${explicitDest}" is not a valid explicitDest parameter.`); - return; - } else if (!this.#isValidPage(pageNumber)) { - if (pageNumber !== null || this._destination) { - console.error("PDFHistory.push: " + `"${pageNumber}" is not a valid pageNumber parameter.`); - return; - } - } - const hash = namedDest || JSON.stringify(explicitDest); - if (!hash) { - return; - } - let forceReplace = false; - if (this._destination && (isDestHashesEqual(this._destination.hash, hash) || isDestArraysEqual(this._destination.dest, explicitDest))) { - if (this._destination.page) { - return; - } - forceReplace = true; - } - if (this._popStateInProgress && !forceReplace) { - return; - } - this.#pushOrReplaceState({ - dest: explicitDest, - hash, - page: pageNumber, - rotation: this.linkService.rotation - }, forceReplace); - if (!this._popStateInProgress) { - this._popStateInProgress = true; - Promise.resolve().then(() => { - this._popStateInProgress = false; - }); - } - } - pushPage(pageNumber) { - if (!this._initialized) { - return; - } - if (!this.#isValidPage(pageNumber)) { - console.error(`PDFHistory.pushPage: "${pageNumber}" is not a valid page number.`); - return; - } - if (this._destination?.page === pageNumber) { - return; - } - if (this._popStateInProgress) { - return; - } - this.#pushOrReplaceState({ - dest: null, - hash: `page=${pageNumber}`, - page: pageNumber, - rotation: this.linkService.rotation - }); - if (!this._popStateInProgress) { - this._popStateInProgress = true; - Promise.resolve().then(() => { - this._popStateInProgress = false; - }); - } - } - pushCurrentPosition() { - if (!this._initialized || this._popStateInProgress) { - return; - } - this.#tryPushCurrentPosition(); - } - back() { - if (!this._initialized || this._popStateInProgress) { - return; - } - const state = window.history.state; - if (this.#isValidState(state) && state.uid > 0) { - window.history.back(); - } - } - forward() { - if (!this._initialized || this._popStateInProgress) { - return; - } - const state = window.history.state; - if (this.#isValidState(state) && state.uid < this._maxUid) { - window.history.forward(); - } - } - get popStateInProgress() { - return this._initialized && (this._popStateInProgress || this._blockHashChange > 0); - } - get initialBookmark() { - return this._initialized ? this._initialBookmark : null; - } - get initialRotation() { - return this._initialized ? this._initialRotation : null; - } - #pushOrReplaceState(destination, forceReplace = false) { - const shouldReplace = forceReplace || !this._destination; - const newState = { - fingerprint: this._fingerprint, - uid: shouldReplace ? this._uid : this._uid + 1, - destination - }; - this.#updateInternalState(destination, newState.uid); - let newUrl; - if (this._updateUrl && destination?.hash) { - const baseUrl = document.location.href.split("#", 1)[0]; - if (!baseUrl.startsWith("file://")) { - newUrl = `${baseUrl}#${destination.hash}`; - } - } - if (shouldReplace) { - window.history.replaceState(newState, "", newUrl); - } else { - window.history.pushState(newState, "", newUrl); - } - } - #tryPushCurrentPosition(temporary = false) { - if (!this._position) { - return; - } - let position = this._position; - if (temporary) { - position = Object.assign(Object.create(null), this._position); - position.temporary = true; - } - if (!this._destination) { - this.#pushOrReplaceState(position); - return; - } - if (this._destination.temporary) { - this.#pushOrReplaceState(position, true); - return; - } - if (this._destination.hash === position.hash) { - return; - } - if (!this._destination.page && (POSITION_UPDATED_THRESHOLD <= 0 || this._numPositionUpdates <= POSITION_UPDATED_THRESHOLD)) { - return; - } - let forceReplace = false; - if (this._destination.page >= position.first && this._destination.page <= position.page) { - if (this._destination.dest !== undefined || !this._destination.first) { - return; - } - forceReplace = true; - } - this.#pushOrReplaceState(position, forceReplace); - } - #isValidPage(val) { - return Number.isInteger(val) && val > 0 && val <= this.linkService.pagesCount; - } - #isValidState(state, checkReload = false) { - if (!state) { - return false; - } - if (state.fingerprint !== this._fingerprint) { - if (checkReload) { - if (typeof state.fingerprint !== "string" || state.fingerprint.length !== this._fingerprint.length) { - return false; - } - const [perfEntry] = performance.getEntriesByType("navigation"); - if (perfEntry?.type !== "reload") { - return false; - } - } else { - return false; - } - } - if (!Number.isInteger(state.uid) || state.uid < 0) { - return false; - } - if (state.destination === null || typeof state.destination !== "object") { - return false; - } - return true; - } - #updateInternalState(destination, uid, removeTemporary = false) { - if (this._updateViewareaTimeout) { - clearTimeout(this._updateViewareaTimeout); - this._updateViewareaTimeout = null; - } - if (removeTemporary && destination?.temporary) { - delete destination.temporary; - } - this._destination = destination; - this._uid = uid; - this._maxUid = Math.max(this._maxUid, uid); - this._numPositionUpdates = 0; - } - #parseCurrentHash(checkNameddest = false) { - const hash = unescape(getCurrentHash()).substring(1); - const params = parseQueryString(hash); - const nameddest = params.get("nameddest") || ""; - let page = params.get("page") | 0; - if (!this.#isValidPage(page) || checkNameddest && nameddest.length > 0) { - page = null; - } - return { - hash, - page, - rotation: this.linkService.rotation - }; - } - #updateViewarea({ - location - }) { - if (this._updateViewareaTimeout) { - clearTimeout(this._updateViewareaTimeout); - this._updateViewareaTimeout = null; - } - this._position = { - hash: location.pdfOpenParams.substring(1), - page: this.linkService.page, - first: location.pageNumber, - rotation: location.rotation - }; - if (this._popStateInProgress) { - return; - } - if (POSITION_UPDATED_THRESHOLD > 0 && this._isPagesLoaded && this._destination && !this._destination.page) { - this._numPositionUpdates++; - } - if (UPDATE_VIEWAREA_TIMEOUT > 0) { - this._updateViewareaTimeout = setTimeout(() => { - if (!this._popStateInProgress) { - this.#tryPushCurrentPosition(true); - } - this._updateViewareaTimeout = null; - }, UPDATE_VIEWAREA_TIMEOUT); - } - } - #popState({ - state - }) { - const newHash = getCurrentHash(), - hashChanged = this._currentHash !== newHash; - this._currentHash = newHash; - if (!state) { - this._uid++; - const { - hash, - page, - rotation - } = this.#parseCurrentHash(); - this.#pushOrReplaceState({ - hash, - page, - rotation - }, true); - return; - } - if (!this.#isValidState(state)) { - return; - } - this._popStateInProgress = true; - if (hashChanged) { - this._blockHashChange++; - waitOnEventOrTimeout({ - target: window, - name: "hashchange", - delay: HASH_CHANGE_TIMEOUT - }).then(() => { - this._blockHashChange--; - }); - } - const destination = state.destination; - this.#updateInternalState(destination, state.uid, true); - if (isValidRotation(destination.rotation)) { - this.linkService.rotation = destination.rotation; - } - if (destination.dest) { - this.linkService.goToDestination(destination.dest); - } else if (destination.hash) { - this.linkService.setHash(destination.hash); - } else if (destination.page) { - this.linkService.page = destination.page; - } - Promise.resolve().then(() => { - this._popStateInProgress = false; - }); - } - #pageHide() { - if (!this._destination || this._destination.temporary) { - this.#tryPushCurrentPosition(); - } - } - #bindEvents() { - if (this.#eventAbortController) { - return; - } - this.#eventAbortController = new AbortController(); - const { - signal - } = this.#eventAbortController; - this.eventBus._on("updateviewarea", this.#updateViewarea.bind(this), { - signal - }); - window.addEventListener("popstate", this.#popState.bind(this), { - signal - }); - window.addEventListener("pagehide", this.#pageHide.bind(this), { - signal - }); - } - #unbindEvents() { - this.#eventAbortController?.abort(); - this.#eventAbortController = null; - } -} -function isDestHashesEqual(destHash, pushHash) { - if (typeof destHash !== "string" || typeof pushHash !== "string") { - return false; - } - if (destHash === pushHash) { - return true; - } - const nameddest = parseQueryString(destHash).get("nameddest"); - if (nameddest === pushHash) { - return true; - } - return false; -} -function isDestArraysEqual(firstDest, secondDest) { - function isEntryEqual(first, second) { - if (typeof first !== typeof second) { - return false; - } - if (Array.isArray(first) || Array.isArray(second)) { - return false; - } - if (first !== null && typeof first === "object" && second !== null) { - if (Object.keys(first).length !== Object.keys(second).length) { - return false; - } - for (const key in first) { - if (!isEntryEqual(first[key], second[key])) { - return false; - } - } - return true; - } - return first === second || Number.isNaN(first) && Number.isNaN(second); - } - if (!(Array.isArray(firstDest) && Array.isArray(secondDest))) { - return false; - } - if (firstDest.length !== secondDest.length) { - return false; - } - for (let i = 0, ii = firstDest.length; i < ii; i++) { - if (!isEntryEqual(firstDest[i], secondDest[i])) { - return false; - } - } - return true; -} - -;// ./web/annotation_editor_layer_builder.js - - -class AnnotationEditorLayerBuilder { - #annotationLayer = null; - #drawLayer = null; - #onAppend = null; - #structTreeLayer = null; - #textLayer = null; - #uiManager; - constructor(options) { - this.pdfPage = options.pdfPage; - this.accessibilityManager = options.accessibilityManager; - this.l10n = options.l10n; - this.l10n ||= new genericl10n_GenericL10n(); - this.annotationEditorLayer = null; - this.div = null; - this._cancelled = false; - this.#uiManager = options.uiManager; - this.#annotationLayer = options.annotationLayer || null; - this.#textLayer = options.textLayer || null; - this.#drawLayer = options.drawLayer || null; - this.#onAppend = options.onAppend || null; - this.#structTreeLayer = options.structTreeLayer || null; - } - async render(viewport, intent = "display") { - if (intent !== "display") { - return; - } - if (this._cancelled) { - return; - } - const clonedViewport = viewport.clone({ - dontFlip: true - }); - if (this.div) { - this.annotationEditorLayer.update({ - viewport: clonedViewport - }); - this.show(); - return; - } - const div = this.div = document.createElement("div"); - div.className = "annotationEditorLayer"; - div.hidden = true; - div.dir = this.#uiManager.direction; - this.#onAppend?.(div); - this.annotationEditorLayer = new AnnotationEditorLayer({ - uiManager: this.#uiManager, - div, - structTreeLayer: this.#structTreeLayer, - accessibilityManager: this.accessibilityManager, - pageIndex: this.pdfPage.pageNumber - 1, - l10n: this.l10n, - viewport: clonedViewport, - annotationLayer: this.#annotationLayer, - textLayer: this.#textLayer, - drawLayer: this.#drawLayer - }); - const parameters = { - viewport: clonedViewport, - div, - annotations: null, - intent - }; - this.annotationEditorLayer.render(parameters); - this.show(); - } - cancel() { - this._cancelled = true; - if (!this.div) { - return; - } - this.annotationEditorLayer.destroy(); - } - hide() { - if (!this.div) { - return; - } - this.annotationEditorLayer.pause(true); - this.div.hidden = true; - } - show() { - if (!this.div || this.annotationEditorLayer.isInvisible) { - return; - } - this.div.hidden = false; - this.annotationEditorLayer.pause(false); - } -} - -;// ./web/app_options.js -{ - var compatParams = new Map(); - const userAgent = navigator.userAgent || ""; - const platform = navigator.platform || ""; - const maxTouchPoints = navigator.maxTouchPoints || 1; - const isAndroid = /Android/.test(userAgent); - const isIOS = /\b(iPad|iPhone|iPod)(?=;)/.test(userAgent) || platform === "MacIntel" && maxTouchPoints > 1; - (function () { - if (isIOS || isAndroid) { - compatParams.set("maxCanvasPixels", 5242880); - } - })(); - (function () { - if (isAndroid) { - compatParams.set("useSystemFonts", false); - } - })(); -} -const OptionKind = { - BROWSER: 0x01, - VIEWER: 0x02, - API: 0x04, - WORKER: 0x08, - EVENT_DISPATCH: 0x10, - PREFERENCE: 0x80 -}; -const Type = { - BOOLEAN: 0x01, - NUMBER: 0x02, - OBJECT: 0x04, - STRING: 0x08, - UNDEFINED: 0x10 -}; -const defaultOptions = { - allowedGlobalEvents: { - value: null, - kind: OptionKind.BROWSER - }, - canvasMaxAreaInBytes: { - value: -1, - kind: OptionKind.BROWSER + OptionKind.API - }, - isInAutomation: { - value: false, - kind: OptionKind.BROWSER - }, - localeProperties: { - value: { - lang: navigator.language || "en-US" - }, - kind: OptionKind.BROWSER - }, - nimbusDataStr: { - value: "", - kind: OptionKind.BROWSER - }, - supportsCaretBrowsingMode: { - value: false, - kind: OptionKind.BROWSER - }, - supportsDocumentFonts: { - value: true, - kind: OptionKind.BROWSER - }, - supportsIntegratedFind: { - value: false, - kind: OptionKind.BROWSER - }, - supportsMouseWheelZoomCtrlKey: { - value: true, - kind: OptionKind.BROWSER - }, - supportsMouseWheelZoomMetaKey: { - value: true, - kind: OptionKind.BROWSER - }, - supportsPinchToZoom: { - value: true, - kind: OptionKind.BROWSER - }, - toolbarDensity: { - value: 0, - kind: OptionKind.BROWSER + OptionKind.EVENT_DISPATCH - }, - altTextLearnMoreUrl: { - value: "", - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - annotationEditorMode: { - value: 0, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - annotationMode: { - value: 2, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - cursorToolOnLoad: { - value: 0, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - debuggerSrc: { - value: "./debugger.mjs", - kind: OptionKind.VIEWER - }, - defaultZoomDelay: { - value: 400, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - defaultZoomValue: { - value: "", - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - disableHistory: { - value: false, - kind: OptionKind.VIEWER - }, - disablePageLabels: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enableAltText: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enableAltTextModelDownload: { - value: true, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE + OptionKind.EVENT_DISPATCH - }, - enableGuessAltText: { - value: true, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE + OptionKind.EVENT_DISPATCH - }, - enableHighlightFloatingButton: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enableNewAltTextWhenAddingImage: { - value: true, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enablePermissions: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enablePrintAutoRotate: { - value: true, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enableScripting: { - value: true, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enableUpdatedAddImage: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - externalLinkRel: { - value: "noopener noreferrer nofollow", - kind: OptionKind.VIEWER - }, - externalLinkTarget: { - value: 0, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - highlightEditorColors: { - value: "yellow=#FFFF98,green=#53FFBC,blue=#80EBFF,pink=#FFCBE6,red=#FF4F5F", - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - historyUpdateUrl: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - ignoreDestinationZoom: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - imageResourcesPath: { - value: "./images/", - kind: OptionKind.VIEWER - }, - maxCanvasPixels: { - value: 2 ** 25, - kind: OptionKind.VIEWER - }, - forcePageColors: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - pageColorsBackground: { - value: "Canvas", - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - pageColorsForeground: { - value: "CanvasText", - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - pdfBugEnabled: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - printResolution: { - value: 150, - kind: OptionKind.VIEWER - }, - sidebarViewOnLoad: { - value: -1, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - scrollModeOnLoad: { - value: -1, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - spreadModeOnLoad: { - value: -1, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - textLayerMode: { - value: 1, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - viewOnLoad: { - value: 0, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - cMapPacked: { - value: true, - kind: OptionKind.API - }, - cMapUrl: { - value: "../web/cmaps/", - kind: OptionKind.API - }, - disableAutoFetch: { - value: false, - kind: OptionKind.API + OptionKind.PREFERENCE - }, - disableFontFace: { - value: false, - kind: OptionKind.API + OptionKind.PREFERENCE - }, - disableRange: { - value: false, - kind: OptionKind.API + OptionKind.PREFERENCE - }, - disableStream: { - value: false, - kind: OptionKind.API + OptionKind.PREFERENCE - }, - docBaseUrl: { - value: "", - kind: OptionKind.API - }, - enableHWA: { - value: true, - kind: OptionKind.API + OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enableXfa: { - value: true, - kind: OptionKind.API + OptionKind.PREFERENCE - }, - fontExtraProperties: { - value: false, - kind: OptionKind.API - }, - isEvalSupported: { - value: true, - kind: OptionKind.API - }, - isOffscreenCanvasSupported: { - value: true, - kind: OptionKind.API - }, - maxImageSize: { - value: -1, - kind: OptionKind.API - }, - pdfBug: { - value: false, - kind: OptionKind.API - }, - standardFontDataUrl: { - value: "../web/standard_fonts/", - kind: OptionKind.API - }, - useSystemFonts: { - value: undefined, - kind: OptionKind.API, - type: Type.BOOLEAN + Type.UNDEFINED - }, - verbosity: { - value: 1, - kind: OptionKind.API - }, - workerPort: { - value: null, - kind: OptionKind.WORKER - }, - workerSrc: { - value: "../build/pdf.worker.mjs", - kind: OptionKind.WORKER - } -}; -{ - defaultOptions.defaultUrl = { - value: "compressed.tracemonkey-pldi-09.pdf", - kind: OptionKind.VIEWER - }; - defaultOptions.sandboxBundleSrc = { - value: "../build/pdf.sandbox.mjs", - kind: OptionKind.VIEWER - }; - defaultOptions.viewerCssTheme = { - value: 0, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }; - defaultOptions.enableFakeMLManager = { - value: true, - kind: OptionKind.VIEWER - }; -} -{ - defaultOptions.disablePreferences = { - value: false, - kind: OptionKind.VIEWER - }; -} -class AppOptions { - static eventBus; - static #opts = new Map(); - static { - for (const name in defaultOptions) { - this.#opts.set(name, defaultOptions[name].value); - } - for (const [name, value] of compatParams) { - this.#opts.set(name, value); - } - this._hasInvokedSet = false; - this._checkDisablePreferences = () => { - if (this.get("disablePreferences")) { - return true; - } - if (this._hasInvokedSet) { - console.warn("The Preferences may override manually set AppOptions; " + 'please use the "disablePreferences"-option to prevent that.'); - } - return false; - }; - } - static get(name) { - return this.#opts.get(name); - } - static getAll(kind = null, defaultOnly = false) { - const options = Object.create(null); - for (const name in defaultOptions) { - const defaultOpt = defaultOptions[name]; - if (kind && !(kind & defaultOpt.kind)) { - continue; - } - options[name] = !defaultOnly ? this.#opts.get(name) : defaultOpt.value; - } - return options; - } - static set(name, value) { - this.setAll({ - [name]: value - }); - } - static setAll(options, prefs = false) { - this._hasInvokedSet ||= true; - let events; - for (const name in options) { - const defaultOpt = defaultOptions[name], - userOpt = options[name]; - if (!defaultOpt || !(typeof userOpt === typeof defaultOpt.value || Type[(typeof userOpt).toUpperCase()] & defaultOpt.type)) { - continue; - } - const { - kind - } = defaultOpt; - if (prefs && !(kind & OptionKind.BROWSER || kind & OptionKind.PREFERENCE)) { - continue; - } - if (this.eventBus && kind & OptionKind.EVENT_DISPATCH) { - (events ||= new Map()).set(name, userOpt); - } - this.#opts.set(name, userOpt); - } - if (events) { - for (const [name, value] of events) { - this.eventBus.dispatch(name.toLowerCase(), { - source: this, - value - }); - } - } - } -} - -;// ./web/draw_layer_builder.js - -class DrawLayerBuilder { - #drawLayer = null; - constructor(options) { - this.pageIndex = options.pageIndex; - } - async render(intent = "display") { - if (intent !== "display" || this.#drawLayer || this._cancelled) { - return; - } - this.#drawLayer = new DrawLayer({ - pageIndex: this.pageIndex - }); - } - cancel() { - this._cancelled = true; - if (!this.#drawLayer) { - return; - } - this.#drawLayer.destroy(); - this.#drawLayer = null; - } - setParent(parent) { - this.#drawLayer?.setParent(parent); - } - getDrawLayer() { - return this.#drawLayer; - } -} - -;// ./web/struct_tree_layer_builder.js - -const PDF_ROLE_TO_HTML_ROLE = { - Document: null, - DocumentFragment: null, - Part: "group", - Sect: "group", - Div: "group", - Aside: "note", - NonStruct: "none", - P: null, - H: "heading", - Title: null, - FENote: "note", - Sub: "group", - Lbl: null, - Span: null, - Em: null, - Strong: null, - Link: "link", - Annot: "note", - Form: "form", - Ruby: null, - RB: null, - RT: null, - RP: null, - Warichu: null, - WT: null, - WP: null, - L: "list", - LI: "listitem", - LBody: null, - Table: "table", - TR: "row", - TH: "columnheader", - TD: "cell", - THead: "columnheader", - TBody: null, - TFoot: null, - Caption: null, - Figure: "figure", - Formula: null, - Artifact: null -}; -const HEADING_PATTERN = /^H(\d+)$/; -class StructTreeLayerBuilder { - #promise; - #treeDom = null; - #treePromise; - #elementAttributes = new Map(); - #rawDims; - #elementsToAddToTextLayer = null; - constructor(pdfPage, rawDims) { - this.#promise = pdfPage.getStructTree(); - this.#rawDims = rawDims; - } - async render() { - if (this.#treePromise) { - return this.#treePromise; - } - const { - promise, - resolve, - reject - } = Promise.withResolvers(); - this.#treePromise = promise; - try { - this.#treeDom = this.#walk(await this.#promise); - } catch (ex) { - reject(ex); - } - this.#promise = null; - this.#treeDom?.classList.add("structTree"); - resolve(this.#treeDom); - return promise; - } - async getAriaAttributes(annotationId) { - try { - await this.render(); - return this.#elementAttributes.get(annotationId); - } catch {} - return null; - } - hide() { - if (this.#treeDom && !this.#treeDom.hidden) { - this.#treeDom.hidden = true; - } - } - show() { - if (this.#treeDom?.hidden) { - this.#treeDom.hidden = false; - } - } - #setAttributes(structElement, htmlElement) { - const { - alt, - id, - lang - } = structElement; - if (alt !== undefined) { - let added = false; - const label = removeNullCharacters(alt); - for (const child of structElement.children) { - if (child.type === "annotation") { - let attrs = this.#elementAttributes.get(child.id); - if (!attrs) { - attrs = new Map(); - this.#elementAttributes.set(child.id, attrs); - } - attrs.set("aria-label", label); - added = true; - } - } - if (!added) { - htmlElement.setAttribute("aria-label", label); - } - } - if (id !== undefined) { - htmlElement.setAttribute("aria-owns", id); - } - if (lang !== undefined) { - htmlElement.setAttribute("lang", removeNullCharacters(lang, true)); - } - } - #addImageInTextLayer(node, element) { - const { - alt, - bbox, - children - } = node; - const child = children?.[0]; - if (!this.#rawDims || !alt || !bbox || child?.type !== "content") { - return false; - } - const { - id - } = child; - if (!id) { - return false; - } - element.setAttribute("aria-owns", id); - const img = document.createElement("span"); - (this.#elementsToAddToTextLayer ||= new Map()).set(id, img); - img.setAttribute("role", "img"); - img.setAttribute("aria-label", removeNullCharacters(alt)); - const { - pageHeight, - pageX, - pageY - } = this.#rawDims; - const calc = "calc(var(--scale-factor)*"; - const { - style - } = img; - style.width = `${calc}${bbox[2] - bbox[0]}px)`; - style.height = `${calc}${bbox[3] - bbox[1]}px)`; - style.left = `${calc}${bbox[0] - pageX}px)`; - style.top = `${calc}${pageHeight - bbox[3] + pageY}px)`; - return true; - } - addElementsToTextLayer() { - if (!this.#elementsToAddToTextLayer) { - return; - } - for (const [id, img] of this.#elementsToAddToTextLayer) { - document.getElementById(id)?.append(img); - } - this.#elementsToAddToTextLayer.clear(); - this.#elementsToAddToTextLayer = null; - } - #walk(node) { - if (!node) { - return null; - } - const element = document.createElement("span"); - if ("role" in node) { - const { - role - } = node; - const match = role.match(HEADING_PATTERN); - if (match) { - element.setAttribute("role", "heading"); - element.setAttribute("aria-level", match[1]); - } else if (PDF_ROLE_TO_HTML_ROLE[role]) { - element.setAttribute("role", PDF_ROLE_TO_HTML_ROLE[role]); - } - if (role === "Figure" && this.#addImageInTextLayer(node, element)) { - return element; - } - } - this.#setAttributes(node, element); - if (node.children) { - if (node.children.length === 1 && "id" in node.children[0]) { - this.#setAttributes(node.children[0], element); - } else { - for (const kid of node.children) { - element.append(this.#walk(kid)); - } - } - } - return element; - } -} - -;// ./web/text_accessibility.js - -class TextAccessibilityManager { - #enabled = false; - #textChildren = null; - #textNodes = new Map(); - #waitingElements = new Map(); - setTextMapping(textDivs) { - this.#textChildren = textDivs; - } - static #compareElementPositions(e1, e2) { - const rect1 = e1.getBoundingClientRect(); - const rect2 = e2.getBoundingClientRect(); - if (rect1.width === 0 && rect1.height === 0) { - return +1; - } - if (rect2.width === 0 && rect2.height === 0) { - return -1; - } - const top1 = rect1.y; - const bot1 = rect1.y + rect1.height; - const mid1 = rect1.y + rect1.height / 2; - const top2 = rect2.y; - const bot2 = rect2.y + rect2.height; - const mid2 = rect2.y + rect2.height / 2; - if (mid1 <= top2 && mid2 >= bot1) { - return -1; - } - if (mid2 <= top1 && mid1 >= bot2) { - return +1; - } - const centerX1 = rect1.x + rect1.width / 2; - const centerX2 = rect2.x + rect2.width / 2; - return centerX1 - centerX2; - } - enable() { - if (this.#enabled) { - throw new Error("TextAccessibilityManager is already enabled."); - } - if (!this.#textChildren) { - throw new Error("Text divs and strings have not been set."); - } - this.#enabled = true; - this.#textChildren = this.#textChildren.slice(); - this.#textChildren.sort(TextAccessibilityManager.#compareElementPositions); - if (this.#textNodes.size > 0) { - const textChildren = this.#textChildren; - for (const [id, nodeIndex] of this.#textNodes) { - const element = document.getElementById(id); - if (!element) { - this.#textNodes.delete(id); - continue; - } - this.#addIdToAriaOwns(id, textChildren[nodeIndex]); - } - } - for (const [element, isRemovable] of this.#waitingElements) { - this.addPointerInTextLayer(element, isRemovable); - } - this.#waitingElements.clear(); - } - disable() { - if (!this.#enabled) { - return; - } - this.#waitingElements.clear(); - this.#textChildren = null; - this.#enabled = false; - } - removePointerInTextLayer(element) { - if (!this.#enabled) { - this.#waitingElements.delete(element); - return; - } - const children = this.#textChildren; - if (!children || children.length === 0) { - return; - } - const { - id - } = element; - const nodeIndex = this.#textNodes.get(id); - if (nodeIndex === undefined) { - return; - } - const node = children[nodeIndex]; - this.#textNodes.delete(id); - let owns = node.getAttribute("aria-owns"); - if (owns?.includes(id)) { - owns = owns.split(" ").filter(x => x !== id).join(" "); - if (owns) { - node.setAttribute("aria-owns", owns); - } else { - node.removeAttribute("aria-owns"); - node.setAttribute("role", "presentation"); - } - } - } - #addIdToAriaOwns(id, node) { - const owns = node.getAttribute("aria-owns"); - if (!owns?.includes(id)) { - node.setAttribute("aria-owns", owns ? `${owns} ${id}` : id); - } - node.removeAttribute("role"); - } - addPointerInTextLayer(element, isRemovable) { - const { - id - } = element; - if (!id) { - return null; - } - if (!this.#enabled) { - this.#waitingElements.set(element, isRemovable); - return null; - } - if (isRemovable) { - this.removePointerInTextLayer(element); - } - const children = this.#textChildren; - if (!children || children.length === 0) { - return null; - } - const index = binarySearchFirstItem(children, node => TextAccessibilityManager.#compareElementPositions(element, node) < 0); - const nodeIndex = Math.max(0, index - 1); - const child = children[nodeIndex]; - this.#addIdToAriaOwns(id, child); - this.#textNodes.set(id, nodeIndex); - const parent = child.parentNode; - return parent?.classList.contains("markedContent") ? parent.id : null; - } - moveElementInDOM(container, element, contentElement, isRemovable) { - const id = this.addPointerInTextLayer(contentElement, isRemovable); - if (!container.hasChildNodes()) { - container.append(element); - return id; - } - const children = Array.from(container.childNodes).filter(node => node !== element); - if (children.length === 0) { - return id; - } - const elementToCompare = contentElement || element; - const index = binarySearchFirstItem(children, node => TextAccessibilityManager.#compareElementPositions(elementToCompare, node) < 0); - if (index === 0) { - children[0].before(element); - } else { - children[index - 1].after(element); - } - return id; - } -} - -;// ./web/text_highlighter.js -class TextHighlighter { - #eventAbortController = null; - constructor({ - findController, - eventBus, - pageIndex - }) { - this.findController = findController; - this.matches = []; - this.eventBus = eventBus; - this.pageIdx = pageIndex; - this.textDivs = null; - this.textContentItemsStr = null; - this.enabled = false; - } - setTextMapping(divs, texts) { - this.textDivs = divs; - this.textContentItemsStr = texts; - } - enable() { - if (!this.textDivs || !this.textContentItemsStr) { - throw new Error("Text divs and strings have not been set."); - } - if (this.enabled) { - throw new Error("TextHighlighter is already enabled."); - } - this.enabled = true; - if (!this.#eventAbortController) { - this.#eventAbortController = new AbortController(); - this.eventBus._on("updatetextlayermatches", evt => { - if (evt.pageIndex === this.pageIdx || evt.pageIndex === -1) { - this._updateMatches(); - } - }, { - signal: this.#eventAbortController.signal - }); - } - this._updateMatches(); - } - disable() { - if (!this.enabled) { - return; - } - this.enabled = false; - this.#eventAbortController?.abort(); - this.#eventAbortController = null; - this._updateMatches(true); - } - _convertMatches(matches, matchesLength) { - if (!matches) { - return []; - } - const { - textContentItemsStr - } = this; - let i = 0, - iIndex = 0; - const end = textContentItemsStr.length - 1; - const result = []; - for (let m = 0, mm = matches.length; m < mm; m++) { - let matchIdx = matches[m]; - while (i !== end && matchIdx >= iIndex + textContentItemsStr[i].length) { - iIndex += textContentItemsStr[i].length; - i++; - } - if (i === textContentItemsStr.length) { - console.error("Could not find a matching mapping"); - } - const match = { - begin: { - divIdx: i, - offset: matchIdx - iIndex - } - }; - matchIdx += matchesLength[m]; - while (i !== end && matchIdx > iIndex + textContentItemsStr[i].length) { - iIndex += textContentItemsStr[i].length; - i++; - } - match.end = { - divIdx: i, - offset: matchIdx - iIndex - }; - result.push(match); - } - return result; - } - _renderMatches(matches) { - if (matches.length === 0) { - return; - } - const { - findController, - pageIdx - } = this; - const { - textContentItemsStr, - textDivs - } = this; - const isSelectedPage = pageIdx === findController.selected.pageIdx; - const selectedMatchIdx = findController.selected.matchIdx; - const highlightAll = findController.state.highlightAll; - let prevEnd = null; - const infinity = { - divIdx: -1, - offset: undefined - }; - function beginText(begin, className) { - const divIdx = begin.divIdx; - textDivs[divIdx].textContent = ""; - return appendTextToDiv(divIdx, 0, begin.offset, className); - } - function appendTextToDiv(divIdx, fromOffset, toOffset, className) { - let div = textDivs[divIdx]; - if (div.nodeType === Node.TEXT_NODE) { - const span = document.createElement("span"); - div.before(span); - span.append(div); - textDivs[divIdx] = span; - div = span; - } - const content = textContentItemsStr[divIdx].substring(fromOffset, toOffset); - const node = document.createTextNode(content); - if (className) { - const span = document.createElement("span"); - span.className = `${className} appended`; - span.append(node); - div.append(span); - if (className.includes("selected")) { - const { - left - } = span.getClientRects()[0]; - const parentLeft = div.getBoundingClientRect().left; - return left - parentLeft; - } - return 0; - } - div.append(node); - return 0; - } - let i0 = selectedMatchIdx, - i1 = i0 + 1; - if (highlightAll) { - i0 = 0; - i1 = matches.length; - } else if (!isSelectedPage) { - return; - } - let lastDivIdx = -1; - let lastOffset = -1; - for (let i = i0; i < i1; i++) { - const match = matches[i]; - const begin = match.begin; - if (begin.divIdx === lastDivIdx && begin.offset === lastOffset) { - continue; - } - lastDivIdx = begin.divIdx; - lastOffset = begin.offset; - const end = match.end; - const isSelected = isSelectedPage && i === selectedMatchIdx; - const highlightSuffix = isSelected ? " selected" : ""; - let selectedLeft = 0; - if (!prevEnd || begin.divIdx !== prevEnd.divIdx) { - if (prevEnd !== null) { - appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset); - } - beginText(begin); - } else { - appendTextToDiv(prevEnd.divIdx, prevEnd.offset, begin.offset); - } - if (begin.divIdx === end.divIdx) { - selectedLeft = appendTextToDiv(begin.divIdx, begin.offset, end.offset, "highlight" + highlightSuffix); - } else { - selectedLeft = appendTextToDiv(begin.divIdx, begin.offset, infinity.offset, "highlight begin" + highlightSuffix); - for (let n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) { - textDivs[n0].className = "highlight middle" + highlightSuffix; - } - beginText(end, "highlight end" + highlightSuffix); - } - prevEnd = end; - if (isSelected) { - findController.scrollMatchIntoView({ - element: textDivs[begin.divIdx], - selectedLeft, - pageIndex: pageIdx, - matchIndex: selectedMatchIdx - }); - } - } - if (prevEnd) { - appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset); - } - } - _updateMatches(reset = false) { - if (!this.enabled && !reset) { - return; - } - const { - findController, - matches, - pageIdx - } = this; - const { - textContentItemsStr, - textDivs - } = this; - let clearedUntilDivIdx = -1; - for (const match of matches) { - const begin = Math.max(clearedUntilDivIdx, match.begin.divIdx); - for (let n = begin, end = match.end.divIdx; n <= end; n++) { - const div = textDivs[n]; - div.textContent = textContentItemsStr[n]; - div.className = ""; - } - clearedUntilDivIdx = match.end.divIdx + 1; - } - if (!findController?.highlightMatches || reset) { - return; - } - const pageMatches = findController.pageMatches[pageIdx] || null; - const pageMatchesLength = findController.pageMatchesLength[pageIdx] || null; - this.matches = this._convertMatches(pageMatches, pageMatchesLength); - this._renderMatches(this.matches); - } -} - -;// ./web/text_layer_builder.js - - -class TextLayerBuilder { - #enablePermissions = false; - #onAppend = null; - #renderingDone = false; - #textLayer = null; - static #textLayers = new Map(); - static #selectionChangeAbortController = null; - constructor({ - pdfPage, - highlighter = null, - accessibilityManager = null, - enablePermissions = false, - onAppend = null - }) { - this.pdfPage = pdfPage; - this.highlighter = highlighter; - this.accessibilityManager = accessibilityManager; - this.#enablePermissions = enablePermissions === true; - this.#onAppend = onAppend; - this.div = document.createElement("div"); - this.div.tabIndex = 0; - this.div.className = "textLayer"; - } - async render(viewport, textContentParams = null) { - if (this.#renderingDone && this.#textLayer) { - this.#textLayer.update({ - viewport, - onBefore: this.hide.bind(this) - }); - this.show(); - return; - } - this.cancel(); - this.#textLayer = new TextLayer({ - textContentSource: this.pdfPage.streamTextContent(textContentParams || { - includeMarkedContent: true, - disableNormalization: true - }), - container: this.div, - viewport - }); - const { - textDivs, - textContentItemsStr - } = this.#textLayer; - this.highlighter?.setTextMapping(textDivs, textContentItemsStr); - this.accessibilityManager?.setTextMapping(textDivs); - await this.#textLayer.render(); - this.#renderingDone = true; - const endOfContent = document.createElement("div"); - endOfContent.className = "endOfContent"; - this.div.append(endOfContent); - this.#bindMouse(endOfContent); - this.#onAppend?.(this.div); - this.highlighter?.enable(); - this.accessibilityManager?.enable(); - } - hide() { - if (!this.div.hidden && this.#renderingDone) { - this.highlighter?.disable(); - this.div.hidden = true; - } - } - show() { - if (this.div.hidden && this.#renderingDone) { - this.div.hidden = false; - this.highlighter?.enable(); - } - } - cancel() { - this.#textLayer?.cancel(); - this.#textLayer = null; - this.highlighter?.disable(); - this.accessibilityManager?.disable(); - TextLayerBuilder.#removeGlobalSelectionListener(this.div); - } - #bindMouse(end) { - const { - div - } = this; - div.addEventListener("mousedown", () => { - div.classList.add("selecting"); - }); - div.addEventListener("copy", event => { - if (!this.#enablePermissions) { - const selection = document.getSelection(); - event.clipboardData.setData("text/plain", removeNullCharacters(normalizeUnicode(selection.toString()))); - } - stopEvent(event); - }); - TextLayerBuilder.#textLayers.set(div, end); - TextLayerBuilder.#enableGlobalSelectionListener(); - } - static #removeGlobalSelectionListener(textLayerDiv) { - this.#textLayers.delete(textLayerDiv); - if (this.#textLayers.size === 0) { - this.#selectionChangeAbortController?.abort(); - this.#selectionChangeAbortController = null; - } - } - static #enableGlobalSelectionListener() { - if (this.#selectionChangeAbortController) { - return; - } - this.#selectionChangeAbortController = new AbortController(); - const { - signal - } = this.#selectionChangeAbortController; - const reset = (end, textLayer) => { - textLayer.append(end); - end.style.width = ""; - end.style.height = ""; - textLayer.classList.remove("selecting"); - }; - let isPointerDown = false; - document.addEventListener("pointerdown", () => { - isPointerDown = true; - }, { - signal - }); - document.addEventListener("pointerup", () => { - isPointerDown = false; - this.#textLayers.forEach(reset); - }, { - signal - }); - window.addEventListener("blur", () => { - isPointerDown = false; - this.#textLayers.forEach(reset); - }, { - signal - }); - document.addEventListener("keyup", () => { - if (!isPointerDown) { - this.#textLayers.forEach(reset); - } - }, { - signal - }); - var isFirefox, prevRange; - document.addEventListener("selectionchange", () => { - const selection = document.getSelection(); - if (selection.rangeCount === 0) { - this.#textLayers.forEach(reset); - return; - } - const activeTextLayers = new Set(); - for (let i = 0; i < selection.rangeCount; i++) { - const range = selection.getRangeAt(i); - for (const textLayerDiv of this.#textLayers.keys()) { - if (!activeTextLayers.has(textLayerDiv) && range.intersectsNode(textLayerDiv)) { - activeTextLayers.add(textLayerDiv); - } - } - } - for (const [textLayerDiv, endDiv] of this.#textLayers) { - if (activeTextLayers.has(textLayerDiv)) { - textLayerDiv.classList.add("selecting"); - } else { - reset(endDiv, textLayerDiv); - } - } - isFirefox ??= getComputedStyle(this.#textLayers.values().next().value).getPropertyValue("-moz-user-select") === "none"; - if (isFirefox) { - return; - } - const range = selection.getRangeAt(0); - const modifyStart = prevRange && (range.compareBoundaryPoints(Range.END_TO_END, prevRange) === 0 || range.compareBoundaryPoints(Range.START_TO_END, prevRange) === 0); - let anchor = modifyStart ? range.startContainer : range.endContainer; - if (anchor.nodeType === Node.TEXT_NODE) { - anchor = anchor.parentNode; - } - const parentTextLayer = anchor.parentElement?.closest(".textLayer"); - const endDiv = this.#textLayers.get(parentTextLayer); - if (endDiv) { - endDiv.style.width = parentTextLayer.style.width; - endDiv.style.height = parentTextLayer.style.height; - anchor.parentElement.insertBefore(endDiv, modifyStart ? anchor : anchor.nextSibling); - } - prevRange = range.cloneRange(); - }, { - signal - }); - } -} - -;// ./web/xfa_layer_builder.js - -class XfaLayerBuilder { - constructor({ - pdfPage, - annotationStorage = null, - linkService, - xfaHtml = null - }) { - this.pdfPage = pdfPage; - this.annotationStorage = annotationStorage; - this.linkService = linkService; - this.xfaHtml = xfaHtml; - this.div = null; - this._cancelled = false; - } - async render(viewport, intent = "display") { - if (intent === "print") { - const parameters = { - viewport: viewport.clone({ - dontFlip: true - }), - div: this.div, - xfaHtml: this.xfaHtml, - annotationStorage: this.annotationStorage, - linkService: this.linkService, - intent - }; - this.div = document.createElement("div"); - parameters.div = this.div; - return XfaLayer.render(parameters); - } - const xfaHtml = await this.pdfPage.getXfa(); - if (this._cancelled || !xfaHtml) { - return { - textDivs: [] - }; - } - const parameters = { - viewport: viewport.clone({ - dontFlip: true - }), - div: this.div, - xfaHtml, - annotationStorage: this.annotationStorage, - linkService: this.linkService, - intent - }; - if (this.div) { - return XfaLayer.update(parameters); - } - this.div = document.createElement("div"); - parameters.div = this.div; - return XfaLayer.render(parameters); - } - cancel() { - this._cancelled = true; - } - hide() { - if (!this.div) { - return; - } - this.div.hidden = true; - } -} - -;// ./web/pdf_page_view.js - - - - - - - - - - - - - -const DEFAULT_LAYER_PROPERTIES = { - annotationEditorUIManager: null, - annotationStorage: null, - downloadManager: null, - enableScripting: false, - fieldObjectsPromise: null, - findController: null, - hasJSActionsPromise: null, - get linkService() { - return new SimpleLinkService(); - } -}; -const LAYERS_ORDER = new Map([["canvasWrapper", 0], ["textLayer", 1], ["annotationLayer", 2], ["annotationEditorLayer", 3], ["xfaLayer", 3]]); -class PDFPageView { - #annotationMode = AnnotationMode.ENABLE_FORMS; - #canvasWrapper = null; - #enableHWA = false; - #hasRestrictedScaling = false; - #isEditing = false; - #layerProperties = null; - #loadingId = null; - #originalViewport = null; - #previousRotation = null; - #scaleRoundX = 1; - #scaleRoundY = 1; - #renderError = null; - #renderingState = RenderingStates.INITIAL; - #textLayerMode = TextLayerMode.ENABLE; - #useThumbnailCanvas = { - directDrawing: true, - initialOptionalContent: true, - regularAnnotations: true - }; - #layers = [null, null, null, null]; - constructor(options) { - const container = options.container; - const defaultViewport = options.defaultViewport; - this.id = options.id; - this.renderingId = "page" + this.id; - this.#layerProperties = options.layerProperties || DEFAULT_LAYER_PROPERTIES; - this.pdfPage = null; - this.pageLabel = null; - this.rotation = 0; - this.scale = options.scale || DEFAULT_SCALE; - this.viewport = defaultViewport; - this.pdfPageRotate = defaultViewport.rotation; - this._optionalContentConfigPromise = options.optionalContentConfigPromise || null; - this.#textLayerMode = options.textLayerMode ?? TextLayerMode.ENABLE; - this.#annotationMode = options.annotationMode ?? AnnotationMode.ENABLE_FORMS; - this.imageResourcesPath = options.imageResourcesPath || ""; - this.maxCanvasPixels = options.maxCanvasPixels ?? AppOptions.get("maxCanvasPixels"); - this.pageColors = options.pageColors || null; - this.#enableHWA = options.enableHWA || false; - this.eventBus = options.eventBus; - this.renderingQueue = options.renderingQueue; - this.l10n = options.l10n; - this.l10n ||= new genericl10n_GenericL10n(); - this.renderTask = null; - this.resume = null; - this._isStandalone = !this.renderingQueue?.hasViewer(); - this._container = container; - this._annotationCanvasMap = null; - this.annotationLayer = null; - this.annotationEditorLayer = null; - this.textLayer = null; - this.xfaLayer = null; - this.structTreeLayer = null; - this.drawLayer = null; - const div = document.createElement("div"); - div.className = "page"; - div.setAttribute("data-page-number", this.id); - div.setAttribute("role", "region"); - div.setAttribute("data-l10n-id", "pdfjs-page-landmark"); - div.setAttribute("data-l10n-args", JSON.stringify({ - page: this.id - })); - this.div = div; - this.#setDimensions(); - container?.append(div); - if (this._isStandalone) { - container?.style.setProperty("--scale-factor", this.scale * PixelsPerInch.PDF_TO_CSS_UNITS); - if (this.pageColors?.background) { - container?.style.setProperty("--page-bg-color", this.pageColors.background); - } - const { - optionalContentConfigPromise - } = options; - if (optionalContentConfigPromise) { - optionalContentConfigPromise.then(optionalContentConfig => { - if (optionalContentConfigPromise !== this._optionalContentConfigPromise) { - return; - } - this.#useThumbnailCanvas.initialOptionalContent = optionalContentConfig.hasInitialVisibility; - }); - } - if (!options.l10n) { - this.l10n.translate(this.div); - } - } - } - #addLayer(div, name) { - const pos = LAYERS_ORDER.get(name); - const oldDiv = this.#layers[pos]; - this.#layers[pos] = div; - if (oldDiv) { - oldDiv.replaceWith(div); - return; - } - for (let i = pos - 1; i >= 0; i--) { - const layer = this.#layers[i]; - if (layer) { - layer.after(div); - return; - } - } - this.div.prepend(div); - } - get renderingState() { - return this.#renderingState; - } - set renderingState(state) { - if (state === this.#renderingState) { - return; - } - this.#renderingState = state; - if (this.#loadingId) { - clearTimeout(this.#loadingId); - this.#loadingId = null; - } - switch (state) { - case RenderingStates.PAUSED: - this.div.classList.remove("loading"); - break; - case RenderingStates.RUNNING: - this.div.classList.add("loadingIcon"); - this.#loadingId = setTimeout(() => { - this.div.classList.add("loading"); - this.#loadingId = null; - }, 0); - break; - case RenderingStates.INITIAL: - case RenderingStates.FINISHED: - this.div.classList.remove("loadingIcon", "loading"); - break; - } - } - #setDimensions() { - const { - viewport - } = this; - if (this.pdfPage) { - if (this.#previousRotation === viewport.rotation) { - return; - } - this.#previousRotation = viewport.rotation; - } - setLayerDimensions(this.div, viewport, true, false); - } - setPdfPage(pdfPage) { - if (this._isStandalone && (this.pageColors?.foreground === "CanvasText" || this.pageColors?.background === "Canvas")) { - this._container?.style.setProperty("--hcm-highlight-filter", pdfPage.filterFactory.addHighlightHCMFilter("highlight", "CanvasText", "Canvas", "HighlightText", "Highlight")); - this._container?.style.setProperty("--hcm-highlight-selected-filter", pdfPage.filterFactory.addHighlightHCMFilter("highlight_selected", "CanvasText", "Canvas", "HighlightText", "Highlight")); - } - this.pdfPage = pdfPage; - this.pdfPageRotate = pdfPage.rotate; - const totalRotation = (this.rotation + this.pdfPageRotate) % 360; - this.viewport = pdfPage.getViewport({ - scale: this.scale * PixelsPerInch.PDF_TO_CSS_UNITS, - rotation: totalRotation - }); - this.#setDimensions(); - this.reset(); - } - destroy() { - this.reset(); - this.pdfPage?.cleanup(); - } - hasEditableAnnotations() { - return !!this.annotationLayer?.hasEditableAnnotations(); - } - get _textHighlighter() { - return shadow(this, "_textHighlighter", new TextHighlighter({ - pageIndex: this.id - 1, - eventBus: this.eventBus, - findController: this.#layerProperties.findController - })); - } - #dispatchLayerRendered(name, error) { - this.eventBus.dispatch(name, { - source: this, - pageNumber: this.id, - error - }); - } - async #renderAnnotationLayer() { - let error = null; - try { - await this.annotationLayer.render(this.viewport, { - structTreeLayer: this.structTreeLayer - }, "display"); - } catch (ex) { - console.error("#renderAnnotationLayer:", ex); - error = ex; - } finally { - this.#dispatchLayerRendered("annotationlayerrendered", error); - } - } - async #renderAnnotationEditorLayer() { - let error = null; - try { - await this.annotationEditorLayer.render(this.viewport, "display"); - } catch (ex) { - console.error("#renderAnnotationEditorLayer:", ex); - error = ex; - } finally { - this.#dispatchLayerRendered("annotationeditorlayerrendered", error); - } - } - async #renderDrawLayer() { - try { - await this.drawLayer.render("display"); - } catch (ex) { - console.error("#renderDrawLayer:", ex); - } - } - async #renderXfaLayer() { - let error = null; - try { - const result = await this.xfaLayer.render(this.viewport, "display"); - if (result?.textDivs && this._textHighlighter) { - this.#buildXfaTextContentItems(result.textDivs); - } - } catch (ex) { - console.error("#renderXfaLayer:", ex); - error = ex; - } finally { - if (this.xfaLayer?.div) { - this.l10n.pause(); - this.#addLayer(this.xfaLayer.div, "xfaLayer"); - this.l10n.resume(); - } - this.#dispatchLayerRendered("xfalayerrendered", error); - } - } - async #renderTextLayer() { - if (!this.textLayer) { - return; - } - let error = null; - try { - await this.textLayer.render(this.viewport); - } catch (ex) { - if (ex instanceof AbortException) { - return; - } - console.error("#renderTextLayer:", ex); - error = ex; - } - this.#dispatchLayerRendered("textlayerrendered", error); - this.#renderStructTreeLayer(); - } - async #renderStructTreeLayer() { - if (!this.textLayer) { - return; - } - const treeDom = await this.structTreeLayer?.render(); - if (treeDom) { - this.l10n.pause(); - this.structTreeLayer?.addElementsToTextLayer(); - if (this.canvas && treeDom.parentNode !== this.canvas) { - this.canvas.append(treeDom); - } - this.l10n.resume(); - } - this.structTreeLayer?.show(); - } - async #buildXfaTextContentItems(textDivs) { - const text = await this.pdfPage.getTextContent(); - const items = []; - for (const item of text.items) { - items.push(item.str); - } - this._textHighlighter.setTextMapping(textDivs, items); - this._textHighlighter.enable(); - } - #resetCanvas() { - const { - canvas - } = this; - if (!canvas) { - return; - } - canvas.remove(); - canvas.width = canvas.height = 0; - this.canvas = null; - this.#originalViewport = null; - } - reset({ - keepAnnotationLayer = false, - keepAnnotationEditorLayer = false, - keepXfaLayer = false, - keepTextLayer = false, - keepCanvasWrapper = false - } = {}) { - this.cancelRendering({ - keepAnnotationLayer, - keepAnnotationEditorLayer, - keepXfaLayer, - keepTextLayer - }); - this.renderingState = RenderingStates.INITIAL; - const div = this.div; - const childNodes = div.childNodes, - annotationLayerNode = keepAnnotationLayer && this.annotationLayer?.div || null, - annotationEditorLayerNode = keepAnnotationEditorLayer && this.annotationEditorLayer?.div || null, - xfaLayerNode = keepXfaLayer && this.xfaLayer?.div || null, - textLayerNode = keepTextLayer && this.textLayer?.div || null, - canvasWrapperNode = keepCanvasWrapper && this.#canvasWrapper || null; - for (let i = childNodes.length - 1; i >= 0; i--) { - const node = childNodes[i]; - switch (node) { - case annotationLayerNode: - case annotationEditorLayerNode: - case xfaLayerNode: - case textLayerNode: - case canvasWrapperNode: - continue; - } - node.remove(); - const layerIndex = this.#layers.indexOf(node); - if (layerIndex >= 0) { - this.#layers[layerIndex] = null; - } - } - div.removeAttribute("data-loaded"); - if (annotationLayerNode) { - this.annotationLayer.hide(); - } - if (annotationEditorLayerNode) { - this.annotationEditorLayer.hide(); - } - if (xfaLayerNode) { - this.xfaLayer.hide(); - } - if (textLayerNode) { - this.textLayer.hide(); - } - this.structTreeLayer?.hide(); - if (!keepCanvasWrapper && this.#canvasWrapper) { - this.#canvasWrapper = null; - this.#resetCanvas(); - } - } - toggleEditingMode(isEditing) { - if (!this.hasEditableAnnotations()) { - return; - } - this.#isEditing = isEditing; - this.reset({ - keepAnnotationLayer: true, - keepAnnotationEditorLayer: true, - keepXfaLayer: true, - keepTextLayer: true, - keepCanvasWrapper: true - }); - } - update({ - scale = 0, - rotation = null, - optionalContentConfigPromise = null, - drawingDelay = -1 - }) { - this.scale = scale || this.scale; - if (typeof rotation === "number") { - this.rotation = rotation; - } - if (optionalContentConfigPromise instanceof Promise) { - this._optionalContentConfigPromise = optionalContentConfigPromise; - optionalContentConfigPromise.then(optionalContentConfig => { - if (optionalContentConfigPromise !== this._optionalContentConfigPromise) { - return; - } - this.#useThumbnailCanvas.initialOptionalContent = optionalContentConfig.hasInitialVisibility; - }); - } - this.#useThumbnailCanvas.directDrawing = true; - const totalRotation = (this.rotation + this.pdfPageRotate) % 360; - this.viewport = this.viewport.clone({ - scale: this.scale * PixelsPerInch.PDF_TO_CSS_UNITS, - rotation: totalRotation - }); - this.#setDimensions(); - if (this._isStandalone) { - this._container?.style.setProperty("--scale-factor", this.viewport.scale); - } - if (this.canvas) { - let onlyCssZoom = false; - if (this.#hasRestrictedScaling) { - if (this.maxCanvasPixels === 0) { - onlyCssZoom = true; - } else if (this.maxCanvasPixels > 0) { - const { - width, - height - } = this.viewport; - const { - sx, - sy - } = this.outputScale; - onlyCssZoom = (Math.floor(width) * sx | 0) * (Math.floor(height) * sy | 0) > this.maxCanvasPixels; - } - } - const postponeDrawing = drawingDelay >= 0 && drawingDelay < 1000; - if (postponeDrawing || onlyCssZoom) { - if (postponeDrawing && !onlyCssZoom && this.renderingState !== RenderingStates.FINISHED) { - this.cancelRendering({ - keepAnnotationLayer: true, - keepAnnotationEditorLayer: true, - keepXfaLayer: true, - keepTextLayer: true, - cancelExtraDelay: drawingDelay - }); - this.renderingState = RenderingStates.FINISHED; - this.#useThumbnailCanvas.directDrawing = false; - } - this.cssTransform({ - redrawAnnotationLayer: true, - redrawAnnotationEditorLayer: true, - redrawXfaLayer: true, - redrawTextLayer: !postponeDrawing, - hideTextLayer: postponeDrawing - }); - if (postponeDrawing) { - return; - } - this.eventBus.dispatch("pagerendered", { - source: this, - pageNumber: this.id, - cssTransform: true, - timestamp: performance.now(), - error: this.#renderError - }); - return; - } - } - this.cssTransform({}); - this.reset({ - keepAnnotationLayer: true, - keepAnnotationEditorLayer: true, - keepXfaLayer: true, - keepTextLayer: true, - keepCanvasWrapper: true - }); - } - cancelRendering({ - keepAnnotationLayer = false, - keepAnnotationEditorLayer = false, - keepXfaLayer = false, - keepTextLayer = false, - cancelExtraDelay = 0 - } = {}) { - if (this.renderTask) { - this.renderTask.cancel(cancelExtraDelay); - this.renderTask = null; - } - this.resume = null; - if (this.textLayer && (!keepTextLayer || !this.textLayer.div)) { - this.textLayer.cancel(); - this.textLayer = null; - } - if (this.annotationLayer && (!keepAnnotationLayer || !this.annotationLayer.div)) { - this.annotationLayer.cancel(); - this.annotationLayer = null; - this._annotationCanvasMap = null; - } - if (this.structTreeLayer && !this.textLayer) { - this.structTreeLayer = null; - } - if (this.annotationEditorLayer && (!keepAnnotationEditorLayer || !this.annotationEditorLayer.div)) { - if (this.drawLayer) { - this.drawLayer.cancel(); - this.drawLayer = null; - } - this.annotationEditorLayer.cancel(); - this.annotationEditorLayer = null; - } - if (this.xfaLayer && (!keepXfaLayer || !this.xfaLayer.div)) { - this.xfaLayer.cancel(); - this.xfaLayer = null; - this._textHighlighter?.disable(); - } - } - cssTransform({ - redrawAnnotationLayer = false, - redrawAnnotationEditorLayer = false, - redrawXfaLayer = false, - redrawTextLayer = false, - hideTextLayer = false - }) { - const { - canvas - } = this; - if (!canvas) { - return; - } - const originalViewport = this.#originalViewport; - if (this.viewport !== originalViewport) { - const relativeRotation = (360 + this.viewport.rotation - originalViewport.rotation) % 360; - if (relativeRotation === 90 || relativeRotation === 270) { - const { - width, - height - } = this.viewport; - const scaleX = height / width; - const scaleY = width / height; - canvas.style.transform = `rotate(${relativeRotation}deg) scale(${scaleX},${scaleY})`; - } else { - canvas.style.transform = relativeRotation === 0 ? "" : `rotate(${relativeRotation}deg)`; - } - } - if (redrawAnnotationLayer && this.annotationLayer) { - this.#renderAnnotationLayer(); - } - if (redrawAnnotationEditorLayer && this.annotationEditorLayer) { - if (this.drawLayer) { - this.#renderDrawLayer(); - } - this.#renderAnnotationEditorLayer(); - } - if (redrawXfaLayer && this.xfaLayer) { - this.#renderXfaLayer(); - } - if (this.textLayer) { - if (hideTextLayer) { - this.textLayer.hide(); - this.structTreeLayer?.hide(); - } else if (redrawTextLayer) { - this.#renderTextLayer(); - } - } - } - get width() { - return this.viewport.width; - } - get height() { - return this.viewport.height; - } - getPagePoint(x, y) { - return this.viewport.convertToPdfPoint(x, y); - } - async #finishRenderTask(renderTask, error = null) { - if (renderTask === this.renderTask) { - this.renderTask = null; - } - if (error instanceof RenderingCancelledException) { - this.#renderError = null; - return; - } - this.#renderError = error; - this.renderingState = RenderingStates.FINISHED; - this.#useThumbnailCanvas.regularAnnotations = !renderTask.separateAnnots; - this.eventBus.dispatch("pagerendered", { - source: this, - pageNumber: this.id, - cssTransform: false, - timestamp: performance.now(), - error: this.#renderError - }); - if (error) { - throw error; - } - } - async draw() { - if (this.renderingState !== RenderingStates.INITIAL) { - console.error("Must be in new state before drawing"); - this.reset(); - } - const { - div, - l10n, - pageColors, - pdfPage, - viewport - } = this; - if (!pdfPage) { - this.renderingState = RenderingStates.FINISHED; - throw new Error("pdfPage is not loaded"); - } - this.renderingState = RenderingStates.RUNNING; - let canvasWrapper = this.#canvasWrapper; - if (!canvasWrapper) { - canvasWrapper = this.#canvasWrapper = document.createElement("div"); - canvasWrapper.classList.add("canvasWrapper"); - this.#addLayer(canvasWrapper, "canvasWrapper"); - } - if (!this.textLayer && this.#textLayerMode !== TextLayerMode.DISABLE && !pdfPage.isPureXfa) { - this._accessibilityManager ||= new TextAccessibilityManager(); - this.textLayer = new TextLayerBuilder({ - pdfPage, - highlighter: this._textHighlighter, - accessibilityManager: this._accessibilityManager, - enablePermissions: this.#textLayerMode === TextLayerMode.ENABLE_PERMISSIONS, - onAppend: textLayerDiv => { - this.l10n.pause(); - this.#addLayer(textLayerDiv, "textLayer"); - this.l10n.resume(); - } - }); - } - if (!this.annotationLayer && this.#annotationMode !== AnnotationMode.DISABLE) { - const { - annotationStorage, - annotationEditorUIManager, - downloadManager, - enableScripting, - fieldObjectsPromise, - hasJSActionsPromise, - linkService - } = this.#layerProperties; - this._annotationCanvasMap ||= new Map(); - this.annotationLayer = new AnnotationLayerBuilder({ - pdfPage, - annotationStorage, - imageResourcesPath: this.imageResourcesPath, - renderForms: this.#annotationMode === AnnotationMode.ENABLE_FORMS, - linkService, - downloadManager, - enableScripting, - hasJSActionsPromise, - fieldObjectsPromise, - annotationCanvasMap: this._annotationCanvasMap, - accessibilityManager: this._accessibilityManager, - annotationEditorUIManager, - onAppend: annotationLayerDiv => { - this.#addLayer(annotationLayerDiv, "annotationLayer"); - } - }); - } - const renderContinueCallback = cont => { - showCanvas?.(false); - if (this.renderingQueue && !this.renderingQueue.isHighestPriority(this)) { - this.renderingState = RenderingStates.PAUSED; - this.resume = () => { - this.renderingState = RenderingStates.RUNNING; - cont(); - }; - return; - } - cont(); - }; - const { - width, - height - } = viewport; - const canvas = document.createElement("canvas"); - canvas.setAttribute("role", "presentation"); - const hasHCM = !!(pageColors?.background && pageColors?.foreground); - const prevCanvas = this.canvas; - const updateOnFirstShow = !prevCanvas && !hasHCM; - this.canvas = canvas; - this.#originalViewport = viewport; - let showCanvas = isLastShow => { - if (updateOnFirstShow) { - canvasWrapper.prepend(canvas); - showCanvas = null; - return; - } - if (!isLastShow) { - return; - } - if (prevCanvas) { - prevCanvas.replaceWith(canvas); - prevCanvas.width = prevCanvas.height = 0; - } else { - canvasWrapper.prepend(canvas); - } - showCanvas = null; - }; - const ctx = canvas.getContext("2d", { - alpha: false, - willReadFrequently: !this.#enableHWA - }); - const outputScale = this.outputScale = new OutputScale(); - if (this.maxCanvasPixels === 0) { - const invScale = 1 / this.scale; - outputScale.sx *= invScale; - outputScale.sy *= invScale; - this.#hasRestrictedScaling = true; - } else if (this.maxCanvasPixels > 0) { - const pixelsInViewport = width * height; - const maxScale = Math.sqrt(this.maxCanvasPixels / pixelsInViewport); - if (outputScale.sx > maxScale || outputScale.sy > maxScale) { - outputScale.sx = maxScale; - outputScale.sy = maxScale; - this.#hasRestrictedScaling = true; - } else { - this.#hasRestrictedScaling = false; - } - } - const sfx = approximateFraction(outputScale.sx); - const sfy = approximateFraction(outputScale.sy); - const canvasWidth = canvas.width = floorToDivide(calcRound(width * outputScale.sx), sfx[0]); - const canvasHeight = canvas.height = floorToDivide(calcRound(height * outputScale.sy), sfy[0]); - const pageWidth = floorToDivide(calcRound(width), sfx[1]); - const pageHeight = floorToDivide(calcRound(height), sfy[1]); - outputScale.sx = canvasWidth / pageWidth; - outputScale.sy = canvasHeight / pageHeight; - if (this.#scaleRoundX !== sfx[1]) { - div.style.setProperty("--scale-round-x", `${sfx[1]}px`); - this.#scaleRoundX = sfx[1]; - } - if (this.#scaleRoundY !== sfy[1]) { - div.style.setProperty("--scale-round-y", `${sfy[1]}px`); - this.#scaleRoundY = sfy[1]; - } - const transform = outputScale.scaled ? [outputScale.sx, 0, 0, outputScale.sy, 0, 0] : null; - const renderContext = { - canvasContext: ctx, - transform, - viewport, - annotationMode: this.#annotationMode, - optionalContentConfigPromise: this._optionalContentConfigPromise, - annotationCanvasMap: this._annotationCanvasMap, - pageColors, - isEditing: this.#isEditing - }; - const renderTask = this.renderTask = pdfPage.render(renderContext); - renderTask.onContinue = renderContinueCallback; - const resultPromise = renderTask.promise.then(async () => { - showCanvas?.(true); - await this.#finishRenderTask(renderTask); - this.structTreeLayer ||= new StructTreeLayerBuilder(pdfPage, viewport.rawDims); - this.#renderTextLayer(); - if (this.annotationLayer) { - await this.#renderAnnotationLayer(); - } - const { - annotationEditorUIManager - } = this.#layerProperties; - if (!annotationEditorUIManager) { - return; - } - this.drawLayer ||= new DrawLayerBuilder({ - pageIndex: this.id - }); - await this.#renderDrawLayer(); - this.drawLayer.setParent(canvasWrapper); - this.annotationEditorLayer ||= new AnnotationEditorLayerBuilder({ - uiManager: annotationEditorUIManager, - pdfPage, - l10n, - structTreeLayer: this.structTreeLayer, - accessibilityManager: this._accessibilityManager, - annotationLayer: this.annotationLayer?.annotationLayer, - textLayer: this.textLayer, - drawLayer: this.drawLayer.getDrawLayer(), - onAppend: annotationEditorLayerDiv => { - this.#addLayer(annotationEditorLayerDiv, "annotationEditorLayer"); - } - }); - this.#renderAnnotationEditorLayer(); - }, error => { - if (!(error instanceof RenderingCancelledException)) { - showCanvas?.(true); - } else { - prevCanvas?.remove(); - this.#resetCanvas(); - } - return this.#finishRenderTask(renderTask, error); - }); - if (pdfPage.isPureXfa) { - if (!this.xfaLayer) { - const { - annotationStorage, - linkService - } = this.#layerProperties; - this.xfaLayer = new XfaLayerBuilder({ - pdfPage, - annotationStorage, - linkService - }); - } - this.#renderXfaLayer(); - } - div.setAttribute("data-loaded", true); - this.eventBus.dispatch("pagerender", { - source: this, - pageNumber: this.id - }); - return resultPromise; - } - setPageLabel(label) { - this.pageLabel = typeof label === "string" ? label : null; - this.div.setAttribute("data-l10n-args", JSON.stringify({ - page: this.pageLabel ?? this.id - })); - if (this.pageLabel !== null) { - this.div.setAttribute("data-page-label", this.pageLabel); - } else { - this.div.removeAttribute("data-page-label"); - } - } - get thumbnailCanvas() { - const { - directDrawing, - initialOptionalContent, - regularAnnotations - } = this.#useThumbnailCanvas; - return directDrawing && initialOptionalContent && regularAnnotations ? this.canvas : null; - } -} - -;// ./web/generic_scripting.js - -async function docProperties(pdfDocument) { - const url = "", - baseUrl = url.split("#", 1)[0]; - let { - info, - metadata, - contentDispositionFilename, - contentLength - } = await pdfDocument.getMetadata(); - if (!contentLength) { - const { - length - } = await pdfDocument.getDownloadInfo(); - contentLength = length; - } - return { - ...info, - baseURL: baseUrl, - filesize: contentLength, - filename: contentDispositionFilename || getPdfFilenameFromUrl(url), - metadata: metadata?.getRaw(), - authors: metadata?.get("dc:creator"), - numPages: pdfDocument.numPages, - URL: url - }; -} -class GenericScripting { - constructor(sandboxBundleSrc) { - this._ready = new Promise((resolve, reject) => { - const sandbox = import(/*webpackIgnore: true*/sandboxBundleSrc); - sandbox.then(pdfjsSandbox => { - resolve(pdfjsSandbox.QuickJSSandbox()); - }).catch(reject); - }); - } - async createSandbox(data) { - const sandbox = await this._ready; - sandbox.create(data); - } - async dispatchEventInSandbox(event) { - const sandbox = await this._ready; - setTimeout(() => sandbox.dispatchEvent(event), 0); - } - async destroySandbox() { - const sandbox = await this._ready; - sandbox.nukeSandbox(); - } -} - -;// ./web/pdf_scripting_manager.js - - -class PDFScriptingManager { - #closeCapability = null; - #destroyCapability = null; - #docProperties = null; - #eventAbortController = null; - #eventBus = null; - #externalServices = null; - #pdfDocument = null; - #pdfViewer = null; - #ready = false; - #scripting = null; - #willPrintCapability = null; - constructor({ - eventBus, - externalServices = null, - docProperties = null - }) { - this.#eventBus = eventBus; - this.#externalServices = externalServices; - this.#docProperties = docProperties; - } - setViewer(pdfViewer) { - this.#pdfViewer = pdfViewer; - } - async setDocument(pdfDocument) { - if (this.#pdfDocument) { - await this.#destroyScripting(); - } - this.#pdfDocument = pdfDocument; - if (!pdfDocument) { - return; - } - const [objects, calculationOrder, docActions] = await Promise.all([pdfDocument.getFieldObjects(), pdfDocument.getCalculationOrderIds(), pdfDocument.getJSActions()]); - if (!objects && !docActions) { - await this.#destroyScripting(); - return; - } - if (pdfDocument !== this.#pdfDocument) { - return; - } - try { - this.#scripting = this.#initScripting(); - } catch (error) { - console.error("setDocument:", error); - await this.#destroyScripting(); - return; - } - const eventBus = this.#eventBus; - this.#eventAbortController = new AbortController(); - const { - signal - } = this.#eventAbortController; - eventBus._on("updatefromsandbox", event => { - if (event?.source === window) { - this.#updateFromSandbox(event.detail); - } - }, { - signal - }); - eventBus._on("dispatcheventinsandbox", event => { - this.#scripting?.dispatchEventInSandbox(event.detail); - }, { - signal - }); - eventBus._on("pagechanging", ({ - pageNumber, - previous - }) => { - if (pageNumber === previous) { - return; - } - this.#dispatchPageClose(previous); - this.#dispatchPageOpen(pageNumber); - }, { - signal - }); - eventBus._on("pagerendered", ({ - pageNumber - }) => { - if (!this._pageOpenPending.has(pageNumber)) { - return; - } - if (pageNumber !== this.#pdfViewer.currentPageNumber) { - return; - } - this.#dispatchPageOpen(pageNumber); - }, { - signal - }); - eventBus._on("pagesdestroy", async () => { - await this.#dispatchPageClose(this.#pdfViewer.currentPageNumber); - await this.#scripting?.dispatchEventInSandbox({ - id: "doc", - name: "WillClose" - }); - this.#closeCapability?.resolve(); - }, { - signal - }); - try { - const docProperties = await this.#docProperties(pdfDocument); - if (pdfDocument !== this.#pdfDocument) { - return; - } - await this.#scripting.createSandbox({ - objects, - calculationOrder, - appInfo: { - platform: navigator.platform, - language: navigator.language - }, - docInfo: { - ...docProperties, - actions: docActions - } - }); - eventBus.dispatch("sandboxcreated", { - source: this - }); - } catch (error) { - console.error("setDocument:", error); - await this.#destroyScripting(); - return; - } - await this.#scripting?.dispatchEventInSandbox({ - id: "doc", - name: "Open" - }); - await this.#dispatchPageOpen(this.#pdfViewer.currentPageNumber, true); - Promise.resolve().then(() => { - if (pdfDocument === this.#pdfDocument) { - this.#ready = true; - } - }); - } - async dispatchWillSave() { - return this.#scripting?.dispatchEventInSandbox({ - id: "doc", - name: "WillSave" - }); - } - async dispatchDidSave() { - return this.#scripting?.dispatchEventInSandbox({ - id: "doc", - name: "DidSave" - }); - } - async dispatchWillPrint() { - if (!this.#scripting) { - return; - } - await this.#willPrintCapability?.promise; - this.#willPrintCapability = Promise.withResolvers(); - try { - await this.#scripting.dispatchEventInSandbox({ - id: "doc", - name: "WillPrint" - }); - } catch (ex) { - this.#willPrintCapability.resolve(); - this.#willPrintCapability = null; - throw ex; - } - await this.#willPrintCapability.promise; - } - async dispatchDidPrint() { - return this.#scripting?.dispatchEventInSandbox({ - id: "doc", - name: "DidPrint" - }); - } - get destroyPromise() { - return this.#destroyCapability?.promise || null; - } - get ready() { - return this.#ready; - } - get _pageOpenPending() { - return shadow(this, "_pageOpenPending", new Set()); - } - get _visitedPages() { - return shadow(this, "_visitedPages", new Map()); - } - async #updateFromSandbox(detail) { - const pdfViewer = this.#pdfViewer; - const isInPresentationMode = pdfViewer.isInPresentationMode || pdfViewer.isChangingPresentationMode; - const { - id, - siblings, - command, - value - } = detail; - if (!id) { - switch (command) { - case "clear": - console.clear(); - break; - case "error": - console.error(value); - break; - case "layout": - if (!isInPresentationMode) { - const modes = apiPageLayoutToViewerModes(value); - pdfViewer.spreadMode = modes.spreadMode; - } - break; - case "page-num": - pdfViewer.currentPageNumber = value + 1; - break; - case "print": - await pdfViewer.pagesPromise; - this.#eventBus.dispatch("print", { - source: this - }); - break; - case "println": - console.log(value); - break; - case "zoom": - if (!isInPresentationMode) { - pdfViewer.currentScaleValue = value; - } - break; - case "SaveAs": - this.#eventBus.dispatch("download", { - source: this - }); - break; - case "FirstPage": - pdfViewer.currentPageNumber = 1; - break; - case "LastPage": - pdfViewer.currentPageNumber = pdfViewer.pagesCount; - break; - case "NextPage": - pdfViewer.nextPage(); - break; - case "PrevPage": - pdfViewer.previousPage(); - break; - case "ZoomViewIn": - if (!isInPresentationMode) { - pdfViewer.increaseScale(); - } - break; - case "ZoomViewOut": - if (!isInPresentationMode) { - pdfViewer.decreaseScale(); - } - break; - case "WillPrintFinished": - this.#willPrintCapability?.resolve(); - this.#willPrintCapability = null; - break; - } - return; - } - if (isInPresentationMode && detail.focus) { - return; - } - delete detail.id; - delete detail.siblings; - const ids = siblings ? [id, ...siblings] : [id]; - for (const elementId of ids) { - const element = document.querySelector(`[data-element-id="${elementId}"]`); - if (element) { - element.dispatchEvent(new CustomEvent("updatefromsandbox", { - detail - })); - } else { - this.#pdfDocument?.annotationStorage.setValue(elementId, detail); - } - } - } - async #dispatchPageOpen(pageNumber, initialize = false) { - const pdfDocument = this.#pdfDocument, - visitedPages = this._visitedPages; - if (initialize) { - this.#closeCapability = Promise.withResolvers(); - } - if (!this.#closeCapability) { - return; - } - const pageView = this.#pdfViewer.getPageView(pageNumber - 1); - if (pageView?.renderingState !== RenderingStates.FINISHED) { - this._pageOpenPending.add(pageNumber); - return; - } - this._pageOpenPending.delete(pageNumber); - const actionsPromise = (async () => { - const actions = await (!visitedPages.has(pageNumber) ? pageView.pdfPage?.getJSActions() : null); - if (pdfDocument !== this.#pdfDocument) { - return; - } - await this.#scripting?.dispatchEventInSandbox({ - id: "page", - name: "PageOpen", - pageNumber, - actions - }); - })(); - visitedPages.set(pageNumber, actionsPromise); - } - async #dispatchPageClose(pageNumber) { - const pdfDocument = this.#pdfDocument, - visitedPages = this._visitedPages; - if (!this.#closeCapability) { - return; - } - if (this._pageOpenPending.has(pageNumber)) { - return; - } - const actionsPromise = visitedPages.get(pageNumber); - if (!actionsPromise) { - return; - } - visitedPages.set(pageNumber, null); - await actionsPromise; - if (pdfDocument !== this.#pdfDocument) { - return; - } - await this.#scripting?.dispatchEventInSandbox({ - id: "page", - name: "PageClose", - pageNumber - }); - } - #initScripting() { - this.#destroyCapability = Promise.withResolvers(); - if (this.#scripting) { - throw new Error("#initScripting: Scripting already exists."); - } - return this.#externalServices.createScripting(); - } - async #destroyScripting() { - if (!this.#scripting) { - this.#pdfDocument = null; - this.#destroyCapability?.resolve(); - return; - } - if (this.#closeCapability) { - await Promise.race([this.#closeCapability.promise, new Promise(resolve => { - setTimeout(resolve, 1000); - })]).catch(() => {}); - this.#closeCapability = null; - } - this.#pdfDocument = null; - try { - await this.#scripting.destroySandbox(); - } catch {} - this.#willPrintCapability?.reject(new Error("Scripting destroyed.")); - this.#willPrintCapability = null; - this.#eventAbortController?.abort(); - this.#eventAbortController = null; - this._pageOpenPending.clear(); - this._visitedPages.clear(); - this.#scripting = null; - this.#ready = false; - this.#destroyCapability?.resolve(); - } -} - -;// ./web/pdf_scripting_manager.component.js - - -class PDFScriptingManagerComponents extends PDFScriptingManager { - constructor(options) { - if (!options.externalServices) { - window.addEventListener("updatefromsandbox", event => { - options.eventBus.dispatch("updatefromsandbox", { - source: window, - detail: event.detail - }); - }); - } - options.externalServices ||= { - createScripting: () => new GenericScripting(options.sandboxBundleSrc) - }; - options.docProperties ||= pdfDocument => docProperties(pdfDocument); - super(options); - } -} - -;// ./web/pdf_rendering_queue.js - - -const CLEANUP_TIMEOUT = 30000; -class PDFRenderingQueue { - constructor() { - this.pdfViewer = null; - this.pdfThumbnailViewer = null; - this.onIdle = null; - this.highestPriorityPage = null; - this.idleTimeout = null; - this.printing = false; - this.isThumbnailViewEnabled = false; - Object.defineProperty(this, "hasViewer", { - value: () => !!this.pdfViewer - }); - } - setViewer(pdfViewer) { - this.pdfViewer = pdfViewer; - } - setThumbnailViewer(pdfThumbnailViewer) { - this.pdfThumbnailViewer = pdfThumbnailViewer; - } - isHighestPriority(view) { - return this.highestPriorityPage === view.renderingId; - } - renderHighestPriority(currentlyVisiblePages) { - if (this.idleTimeout) { - clearTimeout(this.idleTimeout); - this.idleTimeout = null; - } - if (this.pdfViewer.forceRendering(currentlyVisiblePages)) { - return; - } - if (this.isThumbnailViewEnabled && this.pdfThumbnailViewer?.forceRendering()) { - return; - } - if (this.printing) { - return; - } - if (this.onIdle) { - this.idleTimeout = setTimeout(this.onIdle.bind(this), CLEANUP_TIMEOUT); - } - } - getHighestPriority(visible, views, scrolledDown, preRenderExtra = false) { - const visibleViews = visible.views, - numVisible = visibleViews.length; - if (numVisible === 0) { - return null; - } - for (let i = 0; i < numVisible; i++) { - const view = visibleViews[i].view; - if (!this.isViewFinished(view)) { - return view; - } - } - const firstId = visible.first.id, - lastId = visible.last.id; - if (lastId - firstId + 1 > numVisible) { - const visibleIds = visible.ids; - for (let i = 1, ii = lastId - firstId; i < ii; i++) { - const holeId = scrolledDown ? firstId + i : lastId - i; - if (visibleIds.has(holeId)) { - continue; - } - const holeView = views[holeId - 1]; - if (!this.isViewFinished(holeView)) { - return holeView; - } - } - } - let preRenderIndex = scrolledDown ? lastId : firstId - 2; - let preRenderView = views[preRenderIndex]; - if (preRenderView && !this.isViewFinished(preRenderView)) { - return preRenderView; - } - if (preRenderExtra) { - preRenderIndex += scrolledDown ? 1 : -1; - preRenderView = views[preRenderIndex]; - if (preRenderView && !this.isViewFinished(preRenderView)) { - return preRenderView; - } - } - return null; - } - isViewFinished(view) { - return view.renderingState === RenderingStates.FINISHED; - } - renderView(view) { - switch (view.renderingState) { - case RenderingStates.FINISHED: - return false; - case RenderingStates.PAUSED: - this.highestPriorityPage = view.renderingId; - view.resume(); - break; - case RenderingStates.RUNNING: - this.highestPriorityPage = view.renderingId; - break; - case RenderingStates.INITIAL: - this.highestPriorityPage = view.renderingId; - view.draw().finally(() => { - this.renderHighestPriority(); - }).catch(reason => { - if (reason instanceof RenderingCancelledException) { - return; - } - console.error("renderView:", reason); - }); - break; - } - return true; - } -} - -;// ./web/pdf_viewer.js - - - - - - -const DEFAULT_CACHE_SIZE = 10; -const PagesCountLimit = { - FORCE_SCROLL_MODE_PAGE: 10000, - FORCE_LAZY_PAGE_INIT: 5000, - PAUSE_EAGER_PAGE_INIT: 250 -}; -function isValidAnnotationEditorMode(mode) { - return Object.values(AnnotationEditorType).includes(mode) && mode !== AnnotationEditorType.DISABLE; -} -class PDFPageViewBuffer { - #buf = new Set(); - #size = 0; - constructor(size) { - this.#size = size; - } - push(view) { - const buf = this.#buf; - if (buf.has(view)) { - buf.delete(view); - } - buf.add(view); - if (buf.size > this.#size) { - this.#destroyFirstView(); - } - } - resize(newSize, idsToKeep = null) { - this.#size = newSize; - const buf = this.#buf; - if (idsToKeep) { - const ii = buf.size; - let i = 1; - for (const view of buf) { - if (idsToKeep.has(view.id)) { - buf.delete(view); - buf.add(view); - } - if (++i > ii) { - break; - } - } - } - while (buf.size > this.#size) { - this.#destroyFirstView(); - } - } - has(view) { - return this.#buf.has(view); - } - [Symbol.iterator]() { - return this.#buf.keys(); - } - #destroyFirstView() { - const firstView = this.#buf.keys().next().value; - firstView?.destroy(); - this.#buf.delete(firstView); - } -} -class PDFViewer { - #buffer = null; - #altTextManager = null; - #annotationEditorHighlightColors = null; - #annotationEditorMode = AnnotationEditorType.NONE; - #annotationEditorUIManager = null; - #annotationMode = AnnotationMode.ENABLE_FORMS; - #containerTopLeft = null; - #editorUndoBar = null; - #enableHWA = false; - #enableHighlightFloatingButton = false; - #enablePermissions = false; - #enableUpdatedAddImage = false; - #enableNewAltTextWhenAddingImage = false; - #eventAbortController = null; - #mlManager = null; - #switchAnnotationEditorModeAC = null; - #switchAnnotationEditorModeTimeoutId = null; - #getAllTextInProgress = false; - #hiddenCopyElement = null; - #interruptCopyCondition = false; - #previousContainerHeight = 0; - #resizeObserver = new ResizeObserver(this.#resizeObserverCallback.bind(this)); - #scrollModePageState = null; - #scaleTimeoutId = null; - #supportsPinchToZoom = true; - #textLayerMode = TextLayerMode.ENABLE; - constructor(options) { - const viewerVersion = "4.10.38"; - if (version !== viewerVersion) { - throw new Error(`The API version "${version}" does not match the Viewer version "${viewerVersion}".`); - } - this.container = options.container; - this.viewer = options.viewer || options.container.firstElementChild; - if (this.container?.tagName !== "DIV" || this.viewer?.tagName !== "DIV") { - throw new Error("Invalid `container` and/or `viewer` option."); - } - if (this.container.offsetParent && getComputedStyle(this.container).position !== "absolute") { - throw new Error("The `container` must be absolutely positioned."); - } - this.#resizeObserver.observe(this.container); - this.eventBus = options.eventBus; - this.linkService = options.linkService || new SimpleLinkService(); - this.downloadManager = options.downloadManager || null; - this.findController = options.findController || null; - this.#altTextManager = options.altTextManager || null; - this.#editorUndoBar = options.editorUndoBar || null; - if (this.findController) { - this.findController.onIsPageVisible = pageNumber => this._getVisiblePages().ids.has(pageNumber); - } - this._scriptingManager = options.scriptingManager || null; - this.#textLayerMode = options.textLayerMode ?? TextLayerMode.ENABLE; - this.#annotationMode = options.annotationMode ?? AnnotationMode.ENABLE_FORMS; - this.#annotationEditorMode = options.annotationEditorMode ?? AnnotationEditorType.NONE; - this.#annotationEditorHighlightColors = options.annotationEditorHighlightColors || null; - this.#enableHighlightFloatingButton = options.enableHighlightFloatingButton === true; - this.#enableUpdatedAddImage = options.enableUpdatedAddImage === true; - this.#enableNewAltTextWhenAddingImage = options.enableNewAltTextWhenAddingImage === true; - this.imageResourcesPath = options.imageResourcesPath || ""; - this.enablePrintAutoRotate = options.enablePrintAutoRotate || false; - this.removePageBorders = options.removePageBorders || false; - this.maxCanvasPixels = options.maxCanvasPixels; - this.l10n = options.l10n; - this.l10n ||= new genericl10n_GenericL10n(); - this.#enablePermissions = options.enablePermissions || false; - this.pageColors = options.pageColors || null; - this.#mlManager = options.mlManager || null; - this.#enableHWA = options.enableHWA || false; - this.#supportsPinchToZoom = options.supportsPinchToZoom !== false; - this.defaultRenderingQueue = !options.renderingQueue; - if (this.defaultRenderingQueue) { - this.renderingQueue = new PDFRenderingQueue(); - this.renderingQueue.setViewer(this); - } else { - this.renderingQueue = options.renderingQueue; - } - const { - abortSignal - } = options; - abortSignal?.addEventListener("abort", () => { - this.#resizeObserver.disconnect(); - this.#resizeObserver = null; - }, { - once: true - }); - this.scroll = watchScroll(this.container, this._scrollUpdate.bind(this), abortSignal); - this.presentationModeState = PresentationModeState.UNKNOWN; - this._resetView(); - if (this.removePageBorders) { - this.viewer.classList.add("removePageBorders"); - } - this.#updateContainerHeightCss(); - this.eventBus._on("thumbnailrendered", ({ - pageNumber, - pdfPage - }) => { - const pageView = this._pages[pageNumber - 1]; - if (!this.#buffer.has(pageView)) { - pdfPage?.cleanup(); - } - }); - if (!options.l10n) { - this.l10n.translate(this.container); - } - } - get pagesCount() { - return this._pages.length; - } - getPageView(index) { - return this._pages[index]; - } - getCachedPageViews() { - return new Set(this.#buffer); - } - get pageViewsReady() { - return this._pages.every(pageView => pageView?.pdfPage); - } - get renderForms() { - return this.#annotationMode === AnnotationMode.ENABLE_FORMS; - } - get enableScripting() { - return !!this._scriptingManager; - } - get currentPageNumber() { - return this._currentPageNumber; - } - set currentPageNumber(val) { - if (!Number.isInteger(val)) { - throw new Error("Invalid page number."); - } - if (!this.pdfDocument) { - return; - } - if (!this._setCurrentPageNumber(val, true)) { - console.error(`currentPageNumber: "${val}" is not a valid page.`); - } - } - _setCurrentPageNumber(val, resetCurrentPageView = false) { - if (this._currentPageNumber === val) { - if (resetCurrentPageView) { - this.#resetCurrentPageView(); - } - return true; - } - if (!(0 < val && val <= this.pagesCount)) { - return false; - } - const previous = this._currentPageNumber; - this._currentPageNumber = val; - this.eventBus.dispatch("pagechanging", { - source: this, - pageNumber: val, - pageLabel: this._pageLabels?.[val - 1] ?? null, - previous - }); - if (resetCurrentPageView) { - this.#resetCurrentPageView(); - } - return true; - } - get currentPageLabel() { - return this._pageLabels?.[this._currentPageNumber - 1] ?? null; - } - set currentPageLabel(val) { - if (!this.pdfDocument) { - return; - } - let page = val | 0; - if (this._pageLabels) { - const i = this._pageLabels.indexOf(val); - if (i >= 0) { - page = i + 1; - } - } - if (!this._setCurrentPageNumber(page, true)) { - console.error(`currentPageLabel: "${val}" is not a valid page.`); - } - } - get currentScale() { - return this._currentScale !== UNKNOWN_SCALE ? this._currentScale : DEFAULT_SCALE; - } - set currentScale(val) { - if (isNaN(val)) { - throw new Error("Invalid numeric scale."); - } - if (!this.pdfDocument) { - return; - } - this.#setScale(val, { - noScroll: false - }); - } - get currentScaleValue() { - return this._currentScaleValue; - } - set currentScaleValue(val) { - if (!this.pdfDocument) { - return; - } - this.#setScale(val, { - noScroll: false - }); - } - get pagesRotation() { - return this._pagesRotation; - } - set pagesRotation(rotation) { - if (!isValidRotation(rotation)) { - throw new Error("Invalid pages rotation angle."); - } - if (!this.pdfDocument) { - return; - } - rotation %= 360; - if (rotation < 0) { - rotation += 360; - } - if (this._pagesRotation === rotation) { - return; - } - this._pagesRotation = rotation; - const pageNumber = this._currentPageNumber; - this.refresh(true, { - rotation - }); - if (this._currentScaleValue) { - this.#setScale(this._currentScaleValue, { - noScroll: true - }); - } - this.eventBus.dispatch("rotationchanging", { - source: this, - pagesRotation: rotation, - pageNumber - }); - if (this.defaultRenderingQueue) { - this.update(); - } - } - get firstPagePromise() { - return this.pdfDocument ? this._firstPageCapability.promise : null; - } - get onePageRendered() { - return this.pdfDocument ? this._onePageRenderedCapability.promise : null; - } - get pagesPromise() { - return this.pdfDocument ? this._pagesCapability.promise : null; - } - get _layerProperties() { - const self = this; - return shadow(this, "_layerProperties", { - get annotationEditorUIManager() { - return self.#annotationEditorUIManager; - }, - get annotationStorage() { - return self.pdfDocument?.annotationStorage; - }, - get downloadManager() { - return self.downloadManager; - }, - get enableScripting() { - return !!self._scriptingManager; - }, - get fieldObjectsPromise() { - return self.pdfDocument?.getFieldObjects(); - }, - get findController() { - return self.findController; - }, - get hasJSActionsPromise() { - return self.pdfDocument?.hasJSActions(); - }, - get linkService() { - return self.linkService; - } - }); - } - #initializePermissions(permissions) { - const params = { - annotationEditorMode: this.#annotationEditorMode, - annotationMode: this.#annotationMode, - textLayerMode: this.#textLayerMode - }; - if (!permissions) { - return params; - } - if (!permissions.includes(PermissionFlag.COPY) && this.#textLayerMode === TextLayerMode.ENABLE) { - params.textLayerMode = TextLayerMode.ENABLE_PERMISSIONS; - } - if (!permissions.includes(PermissionFlag.MODIFY_CONTENTS)) { - params.annotationEditorMode = AnnotationEditorType.DISABLE; - } - if (!permissions.includes(PermissionFlag.MODIFY_ANNOTATIONS) && !permissions.includes(PermissionFlag.FILL_INTERACTIVE_FORMS) && this.#annotationMode === AnnotationMode.ENABLE_FORMS) { - params.annotationMode = AnnotationMode.ENABLE; - } - return params; - } - async #onePageRenderedOrForceFetch(signal) { - if (document.visibilityState === "hidden" || !this.container.offsetParent || this._getVisiblePages().views.length === 0) { - return; - } - const hiddenCapability = Promise.withResolvers(), - ac = new AbortController(); - document.addEventListener("visibilitychange", () => { - if (document.visibilityState === "hidden") { - hiddenCapability.resolve(); - } - }, { - signal: typeof AbortSignal.any === "function" ? AbortSignal.any([signal, ac.signal]) : signal - }); - await Promise.race([this._onePageRenderedCapability.promise, hiddenCapability.promise]); - ac.abort(); - } - async getAllText() { - const texts = []; - const buffer = []; - for (let pageNum = 1, pagesCount = this.pdfDocument.numPages; pageNum <= pagesCount; ++pageNum) { - if (this.#interruptCopyCondition) { - return null; - } - buffer.length = 0; - const page = await this.pdfDocument.getPage(pageNum); - const { - items - } = await page.getTextContent(); - for (const item of items) { - if (item.str) { - buffer.push(item.str); - } - if (item.hasEOL) { - buffer.push("\n"); - } - } - texts.push(removeNullCharacters(buffer.join(""))); - } - return texts.join("\n"); - } - #copyCallback(textLayerMode, event) { - const selection = document.getSelection(); - const { - focusNode, - anchorNode - } = selection; - if (anchorNode && focusNode && selection.containsNode(this.#hiddenCopyElement)) { - if (this.#getAllTextInProgress || textLayerMode === TextLayerMode.ENABLE_PERMISSIONS) { - stopEvent(event); - return; - } - this.#getAllTextInProgress = true; - const { - classList - } = this.viewer; - classList.add("copyAll"); - const ac = new AbortController(); - window.addEventListener("keydown", ev => this.#interruptCopyCondition = ev.key === "Escape", { - signal: ac.signal - }); - this.getAllText().then(async text => { - if (text !== null) { - await navigator.clipboard.writeText(text); - } - }).catch(reason => { - console.warn(`Something goes wrong when extracting the text: ${reason.message}`); - }).finally(() => { - this.#getAllTextInProgress = false; - this.#interruptCopyCondition = false; - ac.abort(); - classList.remove("copyAll"); - }); - stopEvent(event); - } - } - setDocument(pdfDocument) { - if (this.pdfDocument) { - this.eventBus.dispatch("pagesdestroy", { - source: this - }); - this._cancelRendering(); - this._resetView(); - this.findController?.setDocument(null); - this._scriptingManager?.setDocument(null); - this.#annotationEditorUIManager?.destroy(); - this.#annotationEditorUIManager = null; - } - this.pdfDocument = pdfDocument; - if (!pdfDocument) { - return; - } - const pagesCount = pdfDocument.numPages; - const firstPagePromise = pdfDocument.getPage(1); - const optionalContentConfigPromise = pdfDocument.getOptionalContentConfig({ - intent: "display" - }); - const permissionsPromise = this.#enablePermissions ? pdfDocument.getPermissions() : Promise.resolve(); - const { - eventBus, - pageColors, - viewer - } = this; - this.#eventAbortController = new AbortController(); - const { - signal - } = this.#eventAbortController; - if (pagesCount > PagesCountLimit.FORCE_SCROLL_MODE_PAGE) { - console.warn("Forcing PAGE-scrolling for performance reasons, given the length of the document."); - const mode = this._scrollMode = ScrollMode.PAGE; - eventBus.dispatch("scrollmodechanged", { - source: this, - mode - }); - } - this._pagesCapability.promise.then(() => { - eventBus.dispatch("pagesloaded", { - source: this, - pagesCount - }); - }, () => {}); - const onBeforeDraw = evt => { - const pageView = this._pages[evt.pageNumber - 1]; - if (!pageView) { - return; - } - this.#buffer.push(pageView); - }; - eventBus._on("pagerender", onBeforeDraw, { - signal - }); - const onAfterDraw = evt => { - if (evt.cssTransform) { - return; - } - this._onePageRenderedCapability.resolve({ - timestamp: evt.timestamp - }); - eventBus._off("pagerendered", onAfterDraw); - }; - eventBus._on("pagerendered", onAfterDraw, { - signal - }); - Promise.all([firstPagePromise, permissionsPromise]).then(([firstPdfPage, permissions]) => { - if (pdfDocument !== this.pdfDocument) { - return; - } - this._firstPageCapability.resolve(firstPdfPage); - this._optionalContentConfigPromise = optionalContentConfigPromise; - const { - annotationEditorMode, - annotationMode, - textLayerMode - } = this.#initializePermissions(permissions); - if (textLayerMode !== TextLayerMode.DISABLE) { - const element = this.#hiddenCopyElement = document.createElement("div"); - element.id = "hiddenCopyElement"; - viewer.before(element); - } - if (typeof AbortSignal.any === "function" && annotationEditorMode !== AnnotationEditorType.DISABLE) { - const mode = annotationEditorMode; - if (pdfDocument.isPureXfa) { - console.warn("Warning: XFA-editing is not implemented."); - } else if (isValidAnnotationEditorMode(mode)) { - this.#annotationEditorUIManager = new AnnotationEditorUIManager(this.container, viewer, this.#altTextManager, eventBus, pdfDocument, pageColors, this.#annotationEditorHighlightColors, this.#enableHighlightFloatingButton, this.#enableUpdatedAddImage, this.#enableNewAltTextWhenAddingImage, this.#mlManager, this.#editorUndoBar, this.#supportsPinchToZoom); - eventBus.dispatch("annotationeditoruimanager", { - source: this, - uiManager: this.#annotationEditorUIManager - }); - if (mode !== AnnotationEditorType.NONE) { - if (mode === AnnotationEditorType.STAMP) { - this.#mlManager?.loadModel("altText"); - } - this.#annotationEditorUIManager.updateMode(mode); - } - } else { - console.error(`Invalid AnnotationEditor mode: ${mode}`); - } - } - const viewerElement = this._scrollMode === ScrollMode.PAGE ? null : viewer; - const scale = this.currentScale; - const viewport = firstPdfPage.getViewport({ - scale: scale * PixelsPerInch.PDF_TO_CSS_UNITS - }); - viewer.style.setProperty("--scale-factor", viewport.scale); - if (pageColors?.background) { - viewer.style.setProperty("--page-bg-color", pageColors.background); - } - if (pageColors?.foreground === "CanvasText" || pageColors?.background === "Canvas") { - viewer.style.setProperty("--hcm-highlight-filter", pdfDocument.filterFactory.addHighlightHCMFilter("highlight", "CanvasText", "Canvas", "HighlightText", "Highlight")); - viewer.style.setProperty("--hcm-highlight-selected-filter", pdfDocument.filterFactory.addHighlightHCMFilter("highlight_selected", "CanvasText", "Canvas", "HighlightText", "ButtonText")); - } - for (let pageNum = 1; pageNum <= pagesCount; ++pageNum) { - const pageView = new PDFPageView({ - container: viewerElement, - eventBus, - id: pageNum, - scale, - defaultViewport: viewport.clone(), - optionalContentConfigPromise, - renderingQueue: this.renderingQueue, - textLayerMode, - annotationMode, - imageResourcesPath: this.imageResourcesPath, - maxCanvasPixels: this.maxCanvasPixels, - pageColors, - l10n: this.l10n, - layerProperties: this._layerProperties, - enableHWA: this.#enableHWA - }); - this._pages.push(pageView); - } - this._pages[0]?.setPdfPage(firstPdfPage); - if (this._scrollMode === ScrollMode.PAGE) { - this.#ensurePageViewVisible(); - } else if (this._spreadMode !== SpreadMode.NONE) { - this._updateSpreadMode(); - } - this.#onePageRenderedOrForceFetch(signal).then(async () => { - if (pdfDocument !== this.pdfDocument) { - return; - } - this.findController?.setDocument(pdfDocument); - this._scriptingManager?.setDocument(pdfDocument); - if (this.#hiddenCopyElement) { - document.addEventListener("copy", this.#copyCallback.bind(this, textLayerMode), { - signal - }); - } - if (this.#annotationEditorUIManager) { - eventBus.dispatch("annotationeditormodechanged", { - source: this, - mode: this.#annotationEditorMode - }); - } - if (pdfDocument.loadingParams.disableAutoFetch || pagesCount > PagesCountLimit.FORCE_LAZY_PAGE_INIT) { - this._pagesCapability.resolve(); - return; - } - let getPagesLeft = pagesCount - 1; - if (getPagesLeft <= 0) { - this._pagesCapability.resolve(); - return; - } - for (let pageNum = 2; pageNum <= pagesCount; ++pageNum) { - const promise = pdfDocument.getPage(pageNum).then(pdfPage => { - const pageView = this._pages[pageNum - 1]; - if (!pageView.pdfPage) { - pageView.setPdfPage(pdfPage); - } - if (--getPagesLeft === 0) { - this._pagesCapability.resolve(); - } - }, reason => { - console.error(`Unable to get page ${pageNum} to initialize viewer`, reason); - if (--getPagesLeft === 0) { - this._pagesCapability.resolve(); - } - }); - if (pageNum % PagesCountLimit.PAUSE_EAGER_PAGE_INIT === 0) { - await promise; - } - } - }); - eventBus.dispatch("pagesinit", { - source: this - }); - pdfDocument.getMetadata().then(({ - info - }) => { - if (pdfDocument !== this.pdfDocument) { - return; - } - if (info.Language) { - viewer.lang = info.Language; - } - }); - if (this.defaultRenderingQueue) { - this.update(); - } - }).catch(reason => { - console.error("Unable to initialize viewer", reason); - this._pagesCapability.reject(reason); - }); - } - setPageLabels(labels) { - if (!this.pdfDocument) { - return; - } - if (!labels) { - this._pageLabels = null; - } else if (!(Array.isArray(labels) && this.pdfDocument.numPages === labels.length)) { - this._pageLabels = null; - console.error(`setPageLabels: Invalid page labels.`); - } else { - this._pageLabels = labels; - } - for (let i = 0, ii = this._pages.length; i < ii; i++) { - this._pages[i].setPageLabel(this._pageLabels?.[i] ?? null); - } - } - _resetView() { - this._pages = []; - this._currentPageNumber = 1; - this._currentScale = UNKNOWN_SCALE; - this._currentScaleValue = null; - this._pageLabels = null; - this.#buffer = new PDFPageViewBuffer(DEFAULT_CACHE_SIZE); - this._location = null; - this._pagesRotation = 0; - this._optionalContentConfigPromise = null; - this._firstPageCapability = Promise.withResolvers(); - this._onePageRenderedCapability = Promise.withResolvers(); - this._pagesCapability = Promise.withResolvers(); - this._scrollMode = ScrollMode.VERTICAL; - this._previousScrollMode = ScrollMode.UNKNOWN; - this._spreadMode = SpreadMode.NONE; - this.#scrollModePageState = { - previousPageNumber: 1, - scrollDown: true, - pages: [] - }; - this.#eventAbortController?.abort(); - this.#eventAbortController = null; - this.viewer.textContent = ""; - this._updateScrollMode(); - this.viewer.removeAttribute("lang"); - this.#hiddenCopyElement?.remove(); - this.#hiddenCopyElement = null; - this.#cleanupSwitchAnnotationEditorMode(); - } - #ensurePageViewVisible() { - if (this._scrollMode !== ScrollMode.PAGE) { - throw new Error("#ensurePageViewVisible: Invalid scrollMode value."); - } - const pageNumber = this._currentPageNumber, - state = this.#scrollModePageState, - viewer = this.viewer; - viewer.textContent = ""; - state.pages.length = 0; - if (this._spreadMode === SpreadMode.NONE && !this.isInPresentationMode) { - const pageView = this._pages[pageNumber - 1]; - viewer.append(pageView.div); - state.pages.push(pageView); - } else { - const pageIndexSet = new Set(), - parity = this._spreadMode - 1; - if (parity === -1) { - pageIndexSet.add(pageNumber - 1); - } else if (pageNumber % 2 !== parity) { - pageIndexSet.add(pageNumber - 1); - pageIndexSet.add(pageNumber); - } else { - pageIndexSet.add(pageNumber - 2); - pageIndexSet.add(pageNumber - 1); - } - const spread = document.createElement("div"); - spread.className = "spread"; - if (this.isInPresentationMode) { - const dummyPage = document.createElement("div"); - dummyPage.className = "dummyPage"; - spread.append(dummyPage); - } - for (const i of pageIndexSet) { - const pageView = this._pages[i]; - if (!pageView) { - continue; - } - spread.append(pageView.div); - state.pages.push(pageView); - } - viewer.append(spread); - } - state.scrollDown = pageNumber >= state.previousPageNumber; - state.previousPageNumber = pageNumber; - } - _scrollUpdate() { - if (this.pagesCount === 0) { - return; - } - this.update(); - } - #scrollIntoView(pageView, pageSpot = null) { - const { - div, - id - } = pageView; - if (this._currentPageNumber !== id) { - this._setCurrentPageNumber(id); - } - if (this._scrollMode === ScrollMode.PAGE) { - this.#ensurePageViewVisible(); - this.update(); - } - if (!pageSpot && !this.isInPresentationMode) { - const left = div.offsetLeft + div.clientLeft, - right = left + div.clientWidth; - const { - scrollLeft, - clientWidth - } = this.container; - if (this._scrollMode === ScrollMode.HORIZONTAL || left < scrollLeft || right > scrollLeft + clientWidth) { - pageSpot = { - left: 0, - top: 0 - }; - } - } - scrollIntoView(div, pageSpot); - if (!this._currentScaleValue && this._location) { - this._location = null; - } - } - #isSameScale(newScale) { - return newScale === this._currentScale || Math.abs(newScale - this._currentScale) < 1e-15; - } - #setScaleUpdatePages(newScale, newValue, { - noScroll = false, - preset = false, - drawingDelay = -1, - origin = null - }) { - this._currentScaleValue = newValue.toString(); - if (this.#isSameScale(newScale)) { - if (preset) { - this.eventBus.dispatch("scalechanging", { - source: this, - scale: newScale, - presetValue: newValue - }); - } - return; - } - this.viewer.style.setProperty("--scale-factor", newScale * PixelsPerInch.PDF_TO_CSS_UNITS); - const postponeDrawing = drawingDelay >= 0 && drawingDelay < 1000; - this.refresh(true, { - scale: newScale, - drawingDelay: postponeDrawing ? drawingDelay : -1 - }); - if (postponeDrawing) { - this.#scaleTimeoutId = setTimeout(() => { - this.#scaleTimeoutId = null; - this.refresh(); - }, drawingDelay); - } - const previousScale = this._currentScale; - this._currentScale = newScale; - if (!noScroll) { - let page = this._currentPageNumber, - dest; - if (this._location && !(this.isInPresentationMode || this.isChangingPresentationMode)) { - page = this._location.pageNumber; - dest = [null, { - name: "XYZ" - }, this._location.left, this._location.top, null]; - } - this.scrollPageIntoView({ - pageNumber: page, - destArray: dest, - allowNegativeOffset: true - }); - if (Array.isArray(origin)) { - const scaleDiff = newScale / previousScale - 1; - const [top, left] = this.containerTopLeft; - this.container.scrollLeft += (origin[0] - left) * scaleDiff; - this.container.scrollTop += (origin[1] - top) * scaleDiff; - } - } - this.eventBus.dispatch("scalechanging", { - source: this, - scale: newScale, - presetValue: preset ? newValue : undefined - }); - if (this.defaultRenderingQueue) { - this.update(); - } - } - get #pageWidthScaleFactor() { - if (this._spreadMode !== SpreadMode.NONE && this._scrollMode !== ScrollMode.HORIZONTAL) { - return 2; - } - return 1; - } - #setScale(value, options) { - let scale = parseFloat(value); - if (scale > 0) { - options.preset = false; - this.#setScaleUpdatePages(scale, value, options); - } else { - const currentPage = this._pages[this._currentPageNumber - 1]; - if (!currentPage) { - return; - } - let hPadding = SCROLLBAR_PADDING, - vPadding = VERTICAL_PADDING; - if (this.isInPresentationMode) { - hPadding = vPadding = 4; - if (this._spreadMode !== SpreadMode.NONE) { - hPadding *= 2; - } - } else if (this.removePageBorders) { - hPadding = vPadding = 0; - } else if (this._scrollMode === ScrollMode.HORIZONTAL) { - [hPadding, vPadding] = [vPadding, hPadding]; - } - const pageWidthScale = (this.container.clientWidth - hPadding) / currentPage.width * currentPage.scale / this.#pageWidthScaleFactor; - const pageHeightScale = (this.container.clientHeight - vPadding) / currentPage.height * currentPage.scale; - switch (value) { - case "page-actual": - scale = 1; - break; - case "page-width": - scale = pageWidthScale; - break; - case "page-height": - scale = pageHeightScale; - break; - case "page-fit": - scale = Math.min(pageWidthScale, pageHeightScale); - break; - case "auto": - const horizontalScale = isPortraitOrientation(currentPage) ? pageWidthScale : Math.min(pageHeightScale, pageWidthScale); - scale = Math.min(MAX_AUTO_SCALE, horizontalScale); - break; - default: - console.error(`#setScale: "${value}" is an unknown zoom value.`); - return; - } - options.preset = true; - this.#setScaleUpdatePages(scale, value, options); - } - } - #resetCurrentPageView() { - const pageView = this._pages[this._currentPageNumber - 1]; - if (this.isInPresentationMode) { - this.#setScale(this._currentScaleValue, { - noScroll: true - }); - } - this.#scrollIntoView(pageView); - } - pageLabelToPageNumber(label) { - if (!this._pageLabels) { - return null; - } - const i = this._pageLabels.indexOf(label); - if (i < 0) { - return null; - } - return i + 1; - } - scrollPageIntoView({ - pageNumber, - destArray = null, - allowNegativeOffset = false, - ignoreDestinationZoom = false - }) { - if (!this.pdfDocument) { - return; - } - const pageView = Number.isInteger(pageNumber) && this._pages[pageNumber - 1]; - if (!pageView) { - console.error(`scrollPageIntoView: "${pageNumber}" is not a valid pageNumber parameter.`); - return; - } - if (this.isInPresentationMode || !destArray) { - this._setCurrentPageNumber(pageNumber, true); - return; - } - let x = 0, - y = 0; - let width = 0, - height = 0, - widthScale, - heightScale; - const changeOrientation = pageView.rotation % 180 !== 0; - const pageWidth = (changeOrientation ? pageView.height : pageView.width) / pageView.scale / PixelsPerInch.PDF_TO_CSS_UNITS; - const pageHeight = (changeOrientation ? pageView.width : pageView.height) / pageView.scale / PixelsPerInch.PDF_TO_CSS_UNITS; - let scale = 0; - switch (destArray[1].name) { - case "XYZ": - x = destArray[2]; - y = destArray[3]; - scale = destArray[4]; - x = x !== null ? x : 0; - y = y !== null ? y : pageHeight; - break; - case "Fit": - case "FitB": - scale = "page-fit"; - break; - case "FitH": - case "FitBH": - y = destArray[2]; - scale = "page-width"; - if (y === null && this._location) { - x = this._location.left; - y = this._location.top; - } else if (typeof y !== "number" || y < 0) { - y = pageHeight; - } - break; - case "FitV": - case "FitBV": - x = destArray[2]; - width = pageWidth; - height = pageHeight; - scale = "page-height"; - break; - case "FitR": - x = destArray[2]; - y = destArray[3]; - width = destArray[4] - x; - height = destArray[5] - y; - let hPadding = SCROLLBAR_PADDING, - vPadding = VERTICAL_PADDING; - if (this.removePageBorders) { - hPadding = vPadding = 0; - } - widthScale = (this.container.clientWidth - hPadding) / width / PixelsPerInch.PDF_TO_CSS_UNITS; - heightScale = (this.container.clientHeight - vPadding) / height / PixelsPerInch.PDF_TO_CSS_UNITS; - scale = Math.min(Math.abs(widthScale), Math.abs(heightScale)); - break; - default: - console.error(`scrollPageIntoView: "${destArray[1].name}" is not a valid destination type.`); - return; - } - if (!ignoreDestinationZoom) { - if (scale && scale !== this._currentScale) { - this.currentScaleValue = scale; - } else if (this._currentScale === UNKNOWN_SCALE) { - this.currentScaleValue = DEFAULT_SCALE_VALUE; - } - } - if (scale === "page-fit" && !destArray[4]) { - this.#scrollIntoView(pageView); - return; - } - const boundingRect = [pageView.viewport.convertToViewportPoint(x, y), pageView.viewport.convertToViewportPoint(x + width, y + height)]; - let left = Math.min(boundingRect[0][0], boundingRect[1][0]); - let top = Math.min(boundingRect[0][1], boundingRect[1][1]); - if (!allowNegativeOffset) { - left = Math.max(left, 0); - top = Math.max(top, 0); - } - this.#scrollIntoView(pageView, { - left, - top - }); - } - _updateLocation(firstPage) { - const currentScale = this._currentScale; - const currentScaleValue = this._currentScaleValue; - const normalizedScaleValue = parseFloat(currentScaleValue) === currentScale ? Math.round(currentScale * 10000) / 100 : currentScaleValue; - const pageNumber = firstPage.id; - const currentPageView = this._pages[pageNumber - 1]; - const container = this.container; - const topLeft = currentPageView.getPagePoint(container.scrollLeft - firstPage.x, container.scrollTop - firstPage.y); - const intLeft = Math.round(topLeft[0]); - const intTop = Math.round(topLeft[1]); - let pdfOpenParams = `#page=${pageNumber}`; - if (!this.isInPresentationMode) { - pdfOpenParams += `&zoom=${normalizedScaleValue},${intLeft},${intTop}`; - } - this._location = { - pageNumber, - scale: normalizedScaleValue, - top: intTop, - left: intLeft, - rotation: this._pagesRotation, - pdfOpenParams - }; - } - update() { - const visible = this._getVisiblePages(); - const visiblePages = visible.views, - numVisiblePages = visiblePages.length; - if (numVisiblePages === 0) { - return; - } - const newCacheSize = Math.max(DEFAULT_CACHE_SIZE, 2 * numVisiblePages + 1); - this.#buffer.resize(newCacheSize, visible.ids); - this.renderingQueue.renderHighestPriority(visible); - const isSimpleLayout = this._spreadMode === SpreadMode.NONE && (this._scrollMode === ScrollMode.PAGE || this._scrollMode === ScrollMode.VERTICAL); - const currentId = this._currentPageNumber; - let stillFullyVisible = false; - for (const page of visiblePages) { - if (page.percent < 100) { - break; - } - if (page.id === currentId && isSimpleLayout) { - stillFullyVisible = true; - break; - } - } - this._setCurrentPageNumber(stillFullyVisible ? currentId : visiblePages[0].id); - this._updateLocation(visible.first); - this.eventBus.dispatch("updateviewarea", { - source: this, - location: this._location - }); - } - #switchToEditAnnotationMode() { - const visible = this._getVisiblePages(); - const pagesToRefresh = []; - const { - ids, - views - } = visible; - for (const page of views) { - const { - view - } = page; - if (!view.hasEditableAnnotations()) { - ids.delete(view.id); - continue; - } - pagesToRefresh.push(page); - } - if (pagesToRefresh.length === 0) { - return null; - } - this.renderingQueue.renderHighestPriority({ - first: pagesToRefresh[0], - last: pagesToRefresh.at(-1), - views: pagesToRefresh, - ids - }); - return ids; - } - containsElement(element) { - return this.container.contains(element); - } - focus() { - this.container.focus(); - } - get _isContainerRtl() { - return getComputedStyle(this.container).direction === "rtl"; - } - get isInPresentationMode() { - return this.presentationModeState === PresentationModeState.FULLSCREEN; - } - get isChangingPresentationMode() { - return this.presentationModeState === PresentationModeState.CHANGING; - } - get isHorizontalScrollbarEnabled() { - return this.isInPresentationMode ? false : this.container.scrollWidth > this.container.clientWidth; - } - get isVerticalScrollbarEnabled() { - return this.isInPresentationMode ? false : this.container.scrollHeight > this.container.clientHeight; - } - _getVisiblePages() { - const views = this._scrollMode === ScrollMode.PAGE ? this.#scrollModePageState.pages : this._pages, - horizontal = this._scrollMode === ScrollMode.HORIZONTAL, - rtl = horizontal && this._isContainerRtl; - return getVisibleElements({ - scrollEl: this.container, - views, - sortByVisibility: true, - horizontal, - rtl - }); - } - cleanup() { - for (const pageView of this._pages) { - if (pageView.renderingState !== RenderingStates.FINISHED) { - pageView.reset(); - } - } - } - _cancelRendering() { - for (const pageView of this._pages) { - pageView.cancelRendering(); - } - } - async #ensurePdfPageLoaded(pageView) { - if (pageView.pdfPage) { - return pageView.pdfPage; - } - try { - const pdfPage = await this.pdfDocument.getPage(pageView.id); - if (!pageView.pdfPage) { - pageView.setPdfPage(pdfPage); - } - return pdfPage; - } catch (reason) { - console.error("Unable to get page for page view", reason); - return null; - } - } - #getScrollAhead(visible) { - if (visible.first?.id === 1) { - return true; - } else if (visible.last?.id === this.pagesCount) { - return false; - } - switch (this._scrollMode) { - case ScrollMode.PAGE: - return this.#scrollModePageState.scrollDown; - case ScrollMode.HORIZONTAL: - return this.scroll.right; - } - return this.scroll.down; - } - forceRendering(currentlyVisiblePages) { - const visiblePages = currentlyVisiblePages || this._getVisiblePages(); - const scrollAhead = this.#getScrollAhead(visiblePages); - const preRenderExtra = this._spreadMode !== SpreadMode.NONE && this._scrollMode !== ScrollMode.HORIZONTAL; - const pageView = this.renderingQueue.getHighestPriority(visiblePages, this._pages, scrollAhead, preRenderExtra); - if (pageView) { - this.#ensurePdfPageLoaded(pageView).then(() => { - this.renderingQueue.renderView(pageView); - }); - return true; - } - return false; - } - get hasEqualPageSizes() { - const firstPageView = this._pages[0]; - for (let i = 1, ii = this._pages.length; i < ii; ++i) { - const pageView = this._pages[i]; - if (pageView.width !== firstPageView.width || pageView.height !== firstPageView.height) { - return false; - } - } - return true; - } - getPagesOverview() { - let initialOrientation; - return this._pages.map(pageView => { - const viewport = pageView.pdfPage.getViewport({ - scale: 1 - }); - const orientation = isPortraitOrientation(viewport); - if (initialOrientation === undefined) { - initialOrientation = orientation; - } else if (this.enablePrintAutoRotate && orientation !== initialOrientation) { - return { - width: viewport.height, - height: viewport.width, - rotation: (viewport.rotation - 90) % 360 - }; - } - return { - width: viewport.width, - height: viewport.height, - rotation: viewport.rotation - }; - }); - } - get optionalContentConfigPromise() { - if (!this.pdfDocument) { - return Promise.resolve(null); - } - if (!this._optionalContentConfigPromise) { - console.error("optionalContentConfigPromise: Not initialized yet."); - return this.pdfDocument.getOptionalContentConfig({ - intent: "display" - }); - } - return this._optionalContentConfigPromise; - } - set optionalContentConfigPromise(promise) { - if (!(promise instanceof Promise)) { - throw new Error(`Invalid optionalContentConfigPromise: ${promise}`); - } - if (!this.pdfDocument) { - return; - } - if (!this._optionalContentConfigPromise) { - return; - } - this._optionalContentConfigPromise = promise; - this.refresh(false, { - optionalContentConfigPromise: promise - }); - this.eventBus.dispatch("optionalcontentconfigchanged", { - source: this, - promise - }); - } - get scrollMode() { - return this._scrollMode; - } - set scrollMode(mode) { - if (this._scrollMode === mode) { - return; - } - if (!isValidScrollMode(mode)) { - throw new Error(`Invalid scroll mode: ${mode}`); - } - if (this.pagesCount > PagesCountLimit.FORCE_SCROLL_MODE_PAGE) { - return; - } - this._previousScrollMode = this._scrollMode; - this._scrollMode = mode; - this.eventBus.dispatch("scrollmodechanged", { - source: this, - mode - }); - this._updateScrollMode(this._currentPageNumber); - } - _updateScrollMode(pageNumber = null) { - const scrollMode = this._scrollMode, - viewer = this.viewer; - viewer.classList.toggle("scrollHorizontal", scrollMode === ScrollMode.HORIZONTAL); - viewer.classList.toggle("scrollWrapped", scrollMode === ScrollMode.WRAPPED); - if (!this.pdfDocument || !pageNumber) { - return; - } - if (scrollMode === ScrollMode.PAGE) { - this.#ensurePageViewVisible(); - } else if (this._previousScrollMode === ScrollMode.PAGE) { - this._updateSpreadMode(); - } - if (this._currentScaleValue && isNaN(this._currentScaleValue)) { - this.#setScale(this._currentScaleValue, { - noScroll: true - }); - } - this._setCurrentPageNumber(pageNumber, true); - this.update(); - } - get spreadMode() { - return this._spreadMode; - } - set spreadMode(mode) { - if (this._spreadMode === mode) { - return; - } - if (!isValidSpreadMode(mode)) { - throw new Error(`Invalid spread mode: ${mode}`); - } - this._spreadMode = mode; - this.eventBus.dispatch("spreadmodechanged", { - source: this, - mode - }); - this._updateSpreadMode(this._currentPageNumber); - } - _updateSpreadMode(pageNumber = null) { - if (!this.pdfDocument) { - return; - } - const viewer = this.viewer, - pages = this._pages; - if (this._scrollMode === ScrollMode.PAGE) { - this.#ensurePageViewVisible(); - } else { - viewer.textContent = ""; - if (this._spreadMode === SpreadMode.NONE) { - for (const pageView of this._pages) { - viewer.append(pageView.div); - } - } else { - const parity = this._spreadMode - 1; - let spread = null; - for (let i = 0, ii = pages.length; i < ii; ++i) { - if (spread === null) { - spread = document.createElement("div"); - spread.className = "spread"; - viewer.append(spread); - } else if (i % 2 === parity) { - spread = spread.cloneNode(false); - viewer.append(spread); - } - spread.append(pages[i].div); - } - } - } - if (!pageNumber) { - return; - } - if (this._currentScaleValue && isNaN(this._currentScaleValue)) { - this.#setScale(this._currentScaleValue, { - noScroll: true - }); - } - this._setCurrentPageNumber(pageNumber, true); - this.update(); - } - _getPageAdvance(currentPageNumber, previous = false) { - switch (this._scrollMode) { - case ScrollMode.WRAPPED: - { - const { - views - } = this._getVisiblePages(), - pageLayout = new Map(); - for (const { - id, - y, - percent, - widthPercent - } of views) { - if (percent === 0 || widthPercent < 100) { - continue; - } - let yArray = pageLayout.get(y); - if (!yArray) { - pageLayout.set(y, yArray ||= []); - } - yArray.push(id); - } - for (const yArray of pageLayout.values()) { - const currentIndex = yArray.indexOf(currentPageNumber); - if (currentIndex === -1) { - continue; - } - const numPages = yArray.length; - if (numPages === 1) { - break; - } - if (previous) { - for (let i = currentIndex - 1, ii = 0; i >= ii; i--) { - const currentId = yArray[i], - expectedId = yArray[i + 1] - 1; - if (currentId < expectedId) { - return currentPageNumber - expectedId; - } - } - } else { - for (let i = currentIndex + 1, ii = numPages; i < ii; i++) { - const currentId = yArray[i], - expectedId = yArray[i - 1] + 1; - if (currentId > expectedId) { - return expectedId - currentPageNumber; - } - } - } - if (previous) { - const firstId = yArray[0]; - if (firstId < currentPageNumber) { - return currentPageNumber - firstId + 1; - } - } else { - const lastId = yArray[numPages - 1]; - if (lastId > currentPageNumber) { - return lastId - currentPageNumber + 1; - } - } - break; - } - break; - } - case ScrollMode.HORIZONTAL: - { - break; - } - case ScrollMode.PAGE: - case ScrollMode.VERTICAL: - { - if (this._spreadMode === SpreadMode.NONE) { - break; - } - const parity = this._spreadMode - 1; - if (previous && currentPageNumber % 2 !== parity) { - break; - } else if (!previous && currentPageNumber % 2 === parity) { - break; - } - const { - views - } = this._getVisiblePages(), - expectedId = previous ? currentPageNumber - 1 : currentPageNumber + 1; - for (const { - id, - percent, - widthPercent - } of views) { - if (id !== expectedId) { - continue; - } - if (percent > 0 && widthPercent === 100) { - return 2; - } - break; - } - break; - } - } - return 1; - } - nextPage() { - const currentPageNumber = this._currentPageNumber, - pagesCount = this.pagesCount; - if (currentPageNumber >= pagesCount) { - return false; - } - const advance = this._getPageAdvance(currentPageNumber, false) || 1; - this.currentPageNumber = Math.min(currentPageNumber + advance, pagesCount); - return true; - } - previousPage() { - const currentPageNumber = this._currentPageNumber; - if (currentPageNumber <= 1) { - return false; - } - const advance = this._getPageAdvance(currentPageNumber, true) || 1; - this.currentPageNumber = Math.max(currentPageNumber - advance, 1); - return true; - } - updateScale({ - drawingDelay, - scaleFactor = null, - steps = null, - origin - }) { - if (steps === null && scaleFactor === null) { - throw new Error("Invalid updateScale options: either `steps` or `scaleFactor` must be provided."); - } - if (!this.pdfDocument) { - return; - } - let newScale = this._currentScale; - if (scaleFactor > 0 && scaleFactor !== 1) { - newScale = Math.round(newScale * scaleFactor * 100) / 100; - } else if (steps) { - const delta = steps > 0 ? DEFAULT_SCALE_DELTA : 1 / DEFAULT_SCALE_DELTA; - const round = steps > 0 ? Math.ceil : Math.floor; - steps = Math.abs(steps); - do { - newScale = round((newScale * delta).toFixed(2) * 10) / 10; - } while (--steps > 0); - } - newScale = Math.max(MIN_SCALE, Math.min(MAX_SCALE, newScale)); - this.#setScale(newScale, { - noScroll: false, - drawingDelay, - origin - }); - } - increaseScale(options = {}) { - this.updateScale({ - ...options, - steps: options.steps ?? 1 - }); - } - decreaseScale(options = {}) { - this.updateScale({ - ...options, - steps: -(options.steps ?? 1) - }); - } - #updateContainerHeightCss(height = this.container.clientHeight) { - if (height !== this.#previousContainerHeight) { - this.#previousContainerHeight = height; - docStyle.setProperty("--viewer-container-height", `${height}px`); - } - } - #resizeObserverCallback(entries) { - for (const entry of entries) { - if (entry.target === this.container) { - this.#updateContainerHeightCss(Math.floor(entry.borderBoxSize[0].blockSize)); - this.#containerTopLeft = null; - break; - } - } - } - get containerTopLeft() { - return this.#containerTopLeft ||= [this.container.offsetTop, this.container.offsetLeft]; - } - #cleanupSwitchAnnotationEditorMode() { - this.#switchAnnotationEditorModeAC?.abort(); - this.#switchAnnotationEditorModeAC = null; - if (this.#switchAnnotationEditorModeTimeoutId !== null) { - clearTimeout(this.#switchAnnotationEditorModeTimeoutId); - this.#switchAnnotationEditorModeTimeoutId = null; - } - } - get annotationEditorMode() { - return this.#annotationEditorUIManager ? this.#annotationEditorMode : AnnotationEditorType.DISABLE; - } - set annotationEditorMode({ - mode, - editId = null, - isFromKeyboard = false - }) { - if (!this.#annotationEditorUIManager) { - throw new Error(`The AnnotationEditor is not enabled.`); - } - if (this.#annotationEditorMode === mode) { - return; - } - if (!isValidAnnotationEditorMode(mode)) { - throw new Error(`Invalid AnnotationEditor mode: ${mode}`); - } - if (!this.pdfDocument) { - return; - } - if (mode === AnnotationEditorType.STAMP) { - this.#mlManager?.loadModel("altText"); - } - const { - eventBus - } = this; - const updater = () => { - this.#cleanupSwitchAnnotationEditorMode(); - this.#annotationEditorMode = mode; - this.#annotationEditorUIManager.updateMode(mode, editId, isFromKeyboard); - eventBus.dispatch("annotationeditormodechanged", { - source: this, - mode - }); - }; - if (mode === AnnotationEditorType.NONE || this.#annotationEditorMode === AnnotationEditorType.NONE) { - const isEditing = mode !== AnnotationEditorType.NONE; - if (!isEditing) { - this.pdfDocument.annotationStorage.resetModifiedIds(); - } - for (const pageView of this._pages) { - pageView.toggleEditingMode(isEditing); - } - const idsToRefresh = this.#switchToEditAnnotationMode(); - if (isEditing && idsToRefresh) { - this.#cleanupSwitchAnnotationEditorMode(); - this.#switchAnnotationEditorModeAC = new AbortController(); - const signal = AbortSignal.any([this.#eventAbortController.signal, this.#switchAnnotationEditorModeAC.signal]); - eventBus._on("pagerendered", ({ - pageNumber - }) => { - idsToRefresh.delete(pageNumber); - if (idsToRefresh.size === 0) { - this.#switchAnnotationEditorModeTimeoutId = setTimeout(updater, 0); - } - }, { - signal - }); - return; - } - } - updater(); - } - refresh(noUpdate = false, updateArgs = Object.create(null)) { - if (!this.pdfDocument) { - return; - } - for (const pageView of this._pages) { - pageView.update(updateArgs); - } - if (this.#scaleTimeoutId !== null) { - clearTimeout(this.#scaleTimeoutId); - this.#scaleTimeoutId = null; - } - if (!noUpdate) { - this.update(); - } - } -} - -;// ./web/pdf_single_page_viewer.js - - -class PDFSinglePageViewer extends PDFViewer { - _resetView() { - super._resetView(); - this._scrollMode = ScrollMode.PAGE; - this._spreadMode = SpreadMode.NONE; - } - set scrollMode(mode) {} - _updateScrollMode() {} - set spreadMode(mode) {} - _updateSpreadMode() {} -} - -;// ./web/pdf_viewer.component.js - - - - - - - - - - - - - - - -const pdfjsVersion = "4.10.38"; -const pdfjsBuild = "f9bea397f"; - -var __webpack_exports__AnnotationLayerBuilder = __webpack_exports__.AnnotationLayerBuilder; -var __webpack_exports__DownloadManager = __webpack_exports__.DownloadManager; -var __webpack_exports__EventBus = __webpack_exports__.EventBus; -var __webpack_exports__FindState = __webpack_exports__.FindState; -var __webpack_exports__GenericL10n = __webpack_exports__.GenericL10n; -var __webpack_exports__LinkTarget = __webpack_exports__.LinkTarget; -var __webpack_exports__PDFFindController = __webpack_exports__.PDFFindController; -var __webpack_exports__PDFHistory = __webpack_exports__.PDFHistory; -var __webpack_exports__PDFLinkService = __webpack_exports__.PDFLinkService; -var __webpack_exports__PDFPageView = __webpack_exports__.PDFPageView; -var __webpack_exports__PDFScriptingManager = __webpack_exports__.PDFScriptingManager; -var __webpack_exports__PDFSinglePageViewer = __webpack_exports__.PDFSinglePageViewer; -var __webpack_exports__PDFViewer = __webpack_exports__.PDFViewer; -var __webpack_exports__ProgressBar = __webpack_exports__.ProgressBar; -var __webpack_exports__RenderingStates = __webpack_exports__.RenderingStates; -var __webpack_exports__ScrollMode = __webpack_exports__.ScrollMode; -var __webpack_exports__SimpleLinkService = __webpack_exports__.SimpleLinkService; -var __webpack_exports__SpreadMode = __webpack_exports__.SpreadMode; -var __webpack_exports__StructTreeLayerBuilder = __webpack_exports__.StructTreeLayerBuilder; -var __webpack_exports__TextLayerBuilder = __webpack_exports__.TextLayerBuilder; -var __webpack_exports__XfaLayerBuilder = __webpack_exports__.XfaLayerBuilder; -var __webpack_exports__parseQueryString = __webpack_exports__.parseQueryString; -export { __webpack_exports__AnnotationLayerBuilder as AnnotationLayerBuilder, __webpack_exports__DownloadManager as DownloadManager, __webpack_exports__EventBus as EventBus, __webpack_exports__FindState as FindState, __webpack_exports__GenericL10n as GenericL10n, __webpack_exports__LinkTarget as LinkTarget, __webpack_exports__PDFFindController as PDFFindController, __webpack_exports__PDFHistory as PDFHistory, __webpack_exports__PDFLinkService as PDFLinkService, __webpack_exports__PDFPageView as PDFPageView, __webpack_exports__PDFScriptingManager as PDFScriptingManager, __webpack_exports__PDFSinglePageViewer as PDFSinglePageViewer, __webpack_exports__PDFViewer as PDFViewer, __webpack_exports__ProgressBar as ProgressBar, __webpack_exports__RenderingStates as RenderingStates, __webpack_exports__ScrollMode as ScrollMode, __webpack_exports__SimpleLinkService as SimpleLinkService, __webpack_exports__SpreadMode as SpreadMode, __webpack_exports__StructTreeLayerBuilder as StructTreeLayerBuilder, __webpack_exports__TextLayerBuilder as TextLayerBuilder, __webpack_exports__XfaLayerBuilder as XfaLayerBuilder, __webpack_exports__parseQueryString as parseQueryString }; - -//# sourceMappingURL=pdf_viewer.mjs.map \ No newline at end of file diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/tailwindcss/README.md b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/tailwindcss/README.md deleted file mode 100644 index 69fb53bf322..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/tailwindcss/README.md +++ /dev/null @@ -1,7 +0,0 @@ -tailwindcss version 4.0.3 -https://github.com/tailwindlabs/tailwindcss -License: MIT - -This template uses only `preflight.css`, the CSS reset stylesheet from Tailwind. For simplicity, this template doesn't use a complete deployment of Tailwind. If you want to use the full Tailwind library, remove `preflight.css` and reference the full version of Tailwind. - -To update, replace the `preflight.css` file with the one in an updated build from https://www.npmjs.com/package/tailwindcss diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/tailwindcss/dist/preflight.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/tailwindcss/dist/preflight.css deleted file mode 100644 index 178c881dd23..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/tailwindcss/dist/preflight.css +++ /dev/null @@ -1,383 +0,0 @@ -/* - 1. Prevent padding and border from affecting element width. (https://github.com/mozdevs/cssremedy/issues/4) - 2. Remove default margins and padding - 3. Reset all borders. -*/ - -*, -::after, -::before, -::backdrop, -::file-selector-button { - box-sizing: border-box; /* 1 */ - margin: 0; /* 2 */ - padding: 0; /* 2 */ - border: 0 solid; /* 3 */ -} - -/* - 1. Use a consistent sensible line-height in all browsers. - 2. Prevent adjustments of font size after orientation changes in iOS. - 3. Use a more readable tab size. - 4. Use the user's configured `sans` font-family by default. - 5. Use the user's configured `sans` font-feature-settings by default. - 6. Use the user's configured `sans` font-variation-settings by default. - 7. Disable tap highlights on iOS. -*/ - -html, -:host { - line-height: 1.5; /* 1 */ - -webkit-text-size-adjust: 100%; /* 2 */ - tab-size: 4; /* 3 */ - font-family: var( - --default-font-family, - ui-sans-serif, - system-ui, - sans-serif, - 'Apple Color Emoji', - 'Segoe UI Emoji', - 'Segoe UI Symbol', - 'Noto Color Emoji' - ); /* 4 */ - font-feature-settings: var(--default-font-feature-settings, normal); /* 5 */ - font-variation-settings: var(--default-font-variation-settings, normal); /* 6 */ - -webkit-tap-highlight-color: transparent; /* 7 */ -} - -/* - Inherit line-height from `html` so users can set them as a class directly on the `html` element. -*/ - -body { - line-height: inherit; -} - -/* - 1. Add the correct height in Firefox. - 2. Correct the inheritance of border color in Firefox. (https://bugzilla.mozilla.org/show_bug.cgi?id=190655) - 3. Reset the default border style to a 1px solid border. -*/ - -hr { - height: 0; /* 1 */ - color: inherit; /* 2 */ - border-top-width: 1px; /* 3 */ -} - -/* - Add the correct text decoration in Chrome, Edge, and Safari. -*/ - -abbr:where([title]) { - -webkit-text-decoration: underline dotted; - text-decoration: underline dotted; -} - -/* - Remove the default font size and weight for headings. -*/ - -h1, -h2, -h3, -h4, -h5, -h6 { - font-size: inherit; - font-weight: inherit; -} - -/* - Reset links to optimize for opt-in styling instead of opt-out. -*/ - -a { - color: inherit; - -webkit-text-decoration: inherit; - text-decoration: inherit; -} - -/* - Add the correct font weight in Edge and Safari. -*/ - -b, -strong { - font-weight: bolder; -} - -/* - 1. Use the user's configured `mono` font-family by default. - 2. Use the user's configured `mono` font-feature-settings by default. - 3. Use the user's configured `mono` font-variation-settings by default. - 4. Correct the odd `em` font sizing in all browsers. -*/ - -code, -kbd, -samp, -pre { - font-family: var( - --default-mono-font-family, - ui-monospace, - SFMono-Regular, - Menlo, - Monaco, - Consolas, - 'Liberation Mono', - 'Courier New', - monospace - ); /* 4 */ - font-feature-settings: var(--default-mono-font-feature-settings, normal); /* 5 */ - font-variation-settings: var(--default-mono-font-variation-settings, normal); /* 6 */ - font-size: 1em; /* 4 */ -} - -/* - Add the correct font size in all browsers. -*/ - -small { - font-size: 80%; -} - -/* - Prevent `sub` and `sup` elements from affecting the line height in all browsers. -*/ - -sub, -sup { - font-size: 75%; - line-height: 0; - position: relative; - vertical-align: baseline; -} - -sub { - bottom: -0.25em; -} - -sup { - top: -0.5em; -} - -/* - 1. Remove text indentation from table contents in Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=999088, https://bugs.webkit.org/show_bug.cgi?id=201297) - 2. Correct table border color inheritance in all Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=935729, https://bugs.webkit.org/show_bug.cgi?id=195016) - 3. Remove gaps between table borders by default. -*/ - -table { - text-indent: 0; /* 1 */ - border-color: inherit; /* 2 */ - border-collapse: collapse; /* 3 */ -} - -/* - Use the modern Firefox focus style for all focusable elements. -*/ - -:-moz-focusring { - outline: auto; -} - -/* - Add the correct vertical alignment in Chrome and Firefox. -*/ - -progress { - vertical-align: baseline; -} - -/* - Add the correct display in Chrome and Safari. -*/ - -summary { - display: list-item; -} - -/* - Make lists unstyled by default. -*/ - -ol, -ul, -menu { - list-style: none; -} - -/* - 1. Make replaced elements `display: block` by default. (https://github.com/mozdevs/cssremedy/issues/14) - 2. Add `vertical-align: middle` to align replaced elements more sensibly by default. (https://github.com/jensimmons/cssremedy/issues/14#issuecomment-634934210) - This can trigger a poorly considered lint error in some tools but is included by design. -*/ - -img, -svg, -video, -canvas, -audio, -iframe, -embed, -object { - display: block; /* 1 */ - vertical-align: middle; /* 2 */ -} - -/* - Constrain images and videos to the parent width and preserve their intrinsic aspect ratio. (https://github.com/mozdevs/cssremedy/issues/14) -*/ - -img, -video { - max-width: 100%; - height: auto; -} - -/* - 1. Inherit font styles in all browsers. - 2. Remove border radius in all browsers. - 3. Remove background color in all browsers. - 4. Ensure consistent opacity for disabled states in all browsers. -*/ - -button, -input, -select, -optgroup, -textarea, -::file-selector-button { - font: inherit; /* 1 */ - font-feature-settings: inherit; /* 1 */ - font-variation-settings: inherit; /* 1 */ - letter-spacing: inherit; /* 1 */ - color: inherit; /* 1 */ - border-radius: 0; /* 2 */ - background-color: transparent; /* 3 */ - opacity: 1; /* 4 */ -} - -/* - Restore default font weight. -*/ - -:where(select:is([multiple], [size])) optgroup { - font-weight: bolder; -} - -/* - Restore indentation. -*/ - -:where(select:is([multiple], [size])) optgroup option { - padding-inline-start: 20px; -} - -/* - Restore space after button. -*/ - -::file-selector-button { - margin-inline-end: 4px; -} - -/* - 1. Reset the default placeholder opacity in Firefox. (https://github.com/tailwindlabs/tailwindcss/issues/3300) - 2. Set the default placeholder color to a semi-transparent version of the current text color. -*/ - -::placeholder { - opacity: 1; /* 1 */ - color: color-mix(in oklab, currentColor 50%, transparent); /* 2 */ -} - -/* - Prevent resizing textareas horizontally by default. -*/ - -textarea { - resize: vertical; -} - -/* - Remove the inner padding in Chrome and Safari on macOS. -*/ - -::-webkit-search-decoration { - -webkit-appearance: none; -} - -/* - 1. Ensure date/time inputs have the same height when empty in iOS Safari. - 2. Ensure text alignment can be changed on date/time inputs in iOS Safari. -*/ - -::-webkit-date-and-time-value { - min-height: 1lh; /* 1 */ - text-align: inherit; /* 2 */ -} - -/* - Prevent height from changing on date/time inputs in macOS Safari when the input is set to `display: block`. -*/ - -::-webkit-datetime-edit { - display: inline-flex; -} - -/* - Remove excess padding from pseudo-elements in date/time inputs to ensure consistent height across browsers. -*/ - -::-webkit-datetime-edit-fields-wrapper { - padding: 0; -} - -::-webkit-datetime-edit, -::-webkit-datetime-edit-year-field, -::-webkit-datetime-edit-month-field, -::-webkit-datetime-edit-day-field, -::-webkit-datetime-edit-hour-field, -::-webkit-datetime-edit-minute-field, -::-webkit-datetime-edit-second-field, -::-webkit-datetime-edit-millisecond-field, -::-webkit-datetime-edit-meridiem-field { - padding-block: 0; -} - -/* - Remove the additional `:invalid` styles in Firefox. (https://github.com/mozilla/gecko-dev/blob/2f9eacd9d3d995c937b4251a5557d95d494c9be1/layout/style/res/forms.css#L728-L737) -*/ - -:-moz-ui-invalid { - box-shadow: none; -} - -/* - Correct the inability to style the border radius in iOS Safari. -*/ - -button, -input:where([type='button'], [type='reset'], [type='submit']), -::file-selector-button { - appearance: button; -} - -/* - Correct the cursor style of increment and decrement buttons in Safari. -*/ - -::-webkit-inner-spin-button, -::-webkit-outer-spin-button { - height: auto; -} - -/* - Make elements with the HTML hidden attribute stay hidden by default. -*/ - -[hidden]:where(:not([hidden='until-found'])) { - display: none !important; -} diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/Data/Example_Emergency_Survival_Kit.pdf b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/Data/Example_Emergency_Survival_Kit.pdf deleted file mode 100644 index 94625f0e0e0617c1324cf5243b06d0e8a2da6177..0000000000000000000000000000000000000000 GIT binary patch literal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y8q55K}&S%s}Q z=B#c^+D1l3YPEyVI1M(ImMGE!W0X%gIo7HMxBXRpgg+ZDuU1*_qgY|kXDcFLO+s@& z^3=xF^F?uJDApV`GPi^|K z(CIW}w{?P@{;ASW5LD8!(&a88$HYuXyN%(v!Mor~z@ORUx%F~fK-f81#Kze2zP$Bq zr&h>m>wd=P2y>+DYj1fj6*3#sAYm=Bm655wjBs9lrZrvOuD$vap0=$m{L;kHCq(YG zMpuui&}rmh{+i!cQe=9-pR7O$OkWtEd$Tcmbjt^nxQLs)CQ31S_AG-vL-;qC_h3`H z{t-2c(BWg#e&b&kg@sIW*;IhfPQa5h7~G3qs)VdSs=hHjJ>5%2{sFd{h9Hr^H2Sn@ zR%OVrx6n+?9U@h`c4GmRLTBMx((b(%?2c61^lO|$opC-95fRZ73H%%Ms<@?umXtM7 zjg_qSNUX4@fdw4_aeI0*koC)Vu4*fT)IY+!q9}=_AdK!!Q(4j^q@|j!gUHX%kDDyI zd~wlA_HKjV`ZteVOx33 zjQ^i7DCVmO0QR5df#K-R3S;~~6I7t&|1J-?`h2eKIut)%s6pEpEqy`pcHi+57=RRP zZ8(0-OL8bh_Dn>kCEmL>RB@X^NLjA(p{{W!zUzMTPO@kIoR<5M`84LJVbeNU0P1zq z4^O(t7vkAuH@G=26!_ToGp8Xef3sV;1$v=+Rg=q 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - return apply(func, thisArg, args); - }; -} -/** - * Creates a new function that constructs an instance of the given constructor function with the provided arguments. - * - * @param func - The constructor function to be wrapped and called. - * @returns A new function that constructs an instance of the given constructor function with the provided arguments. - */ -function unconstruct(func) { - return function () { - for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - args[_key2] = arguments[_key2]; - } - return construct(func, args); - }; -} -/** - * Add properties to a lookup table - * - * @param set - The set to which elements will be added. - * @param array - The array containing elements to be added to the set. - * @param transformCaseFunc - An optional function to transform the case of each element before adding to the set. - * @returns The modified set with added elements. - */ -function addToSet(set, array) { - let transformCaseFunc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : stringToLowerCase; - if (setPrototypeOf) { - // Make 'in' and truthy checks like Boolean(set.constructor) - // independent of any properties defined on Object.prototype. - // Prevent prototype setters from intercepting set as a this value. - setPrototypeOf(set, null); - } - let l = array.length; - while (l--) { - let element = array[l]; - if (typeof element === 'string') { - const lcElement = transformCaseFunc(element); - if (lcElement !== element) { - // Config presets (e.g. tags.js, attrs.js) are immutable. - if (!isFrozen(array)) { - array[l] = lcElement; - } - element = lcElement; - } - } - set[element] = true; - } - return set; -} -/** - * Clean up an array to harden against CSPP - * - * @param array - The array to be cleaned. - * @returns The cleaned version of the array - */ -function cleanArray(array) { - for (let index = 0; index < array.length; index++) { - const isPropertyExist = objectHasOwnProperty(array, index); - if (!isPropertyExist) { - array[index] = null; - } - } - return array; -} -/** - * Shallow clone an object - * - * @param object - The object to be cloned. - * @returns A new object that copies the original. - */ -function clone(object) { - const newObject = create(null); - for (const [property, value] of entries(object)) { - const isPropertyExist = objectHasOwnProperty(object, property); - if (isPropertyExist) { - if (Array.isArray(value)) { - newObject[property] = cleanArray(value); - } else if (value && typeof value === 'object' && value.constructor === Object) { - newObject[property] = clone(value); - } else { - newObject[property] = value; - } - } - } - return newObject; -} -/** - * This method automatically checks if the prop is function or getter and behaves accordingly. - * - * @param object - The object to look up the getter function in its prototype chain. - * @param prop - The property name for which to find the getter function. - * @returns The getter function found in the prototype chain or a fallback function. - */ -function lookupGetter(object, prop) { - while (object !== null) { - const desc = getOwnPropertyDescriptor(object, prop); - if (desc) { - if (desc.get) { - return unapply(desc.get); - } - if (typeof desc.value === 'function') { - return unapply(desc.value); - } - } - object = getPrototypeOf(object); - } - function fallbackValue() { - return null; - } - return fallbackValue; -} - -const html$1 = freeze(['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'content', 'data', 'datalist', 'dd', 'decorator', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meter', 'nav', 'nobr', 'ol', 'optgroup', 'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'section', 'select', 'shadow', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr']); -const svg$1 = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']); -const svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feDropShadow', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']); -// List of SVG elements that are disallowed by default. -// We still need to know them so that we can do namespace -// checks properly in case one wants to add them to -// allow-list. -const svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignobject', 'hatch', 'hatchpath', 'mesh', 'meshgradient', 'meshpatch', 'meshrow', 'missing-glyph', 'script', 'set', 'solidcolor', 'unknown', 'use']); -const mathMl$1 = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover', 'mprescripts']); -// Similarly to SVG, we want to know all MathML elements, -// even those that we disallow by default. -const mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']); -const text = freeze(['#text']); - -const html = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'nonce', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'pattern', 'placeholder', 'playsinline', 'popover', 'popovertarget', 'popovertargetaction', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'wrap', 'xmlns', 'slot']); -const svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'amplitude', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dur', 'edgemode', 'elevation', 'end', 'exponent', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'intercept', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'slope', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'tablevalues', 'targetx', 'targety', 'transform', 'transform-origin', 'text-anchor', 'text-decoration', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']); -const mathMl = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnsalign', 'columnlines', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lspace', 'lquote', 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset', 'width', 'xmlns']); -const xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']); - -// eslint-disable-next-line unicorn/better-regex -const MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode -const ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm); -const TMPLIT_EXPR = seal(/\$\{[\w\W]*/gm); // eslint-disable-line unicorn/better-regex -const DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]+$/); // eslint-disable-line no-useless-escape -const ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape -const IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i // eslint-disable-line no-useless-escape -); -const IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i); -const ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex -); -const DOCTYPE_NAME = seal(/^html$/i); -const CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i); - -var EXPRESSIONS = /*#__PURE__*/Object.freeze({ - __proto__: null, - ARIA_ATTR: ARIA_ATTR, - ATTR_WHITESPACE: ATTR_WHITESPACE, - CUSTOM_ELEMENT: CUSTOM_ELEMENT, - DATA_ATTR: DATA_ATTR, - DOCTYPE_NAME: DOCTYPE_NAME, - ERB_EXPR: ERB_EXPR, - IS_ALLOWED_URI: IS_ALLOWED_URI, - IS_SCRIPT_OR_DATA: IS_SCRIPT_OR_DATA, - MUSTACHE_EXPR: MUSTACHE_EXPR, - TMPLIT_EXPR: TMPLIT_EXPR -}); - -/* eslint-disable @typescript-eslint/indent */ -// https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType -const NODE_TYPE = { - element: 1, - attribute: 2, - text: 3, - cdataSection: 4, - entityReference: 5, - // Deprecated - entityNode: 6, - // Deprecated - progressingInstruction: 7, - comment: 8, - document: 9, - documentType: 10, - documentFragment: 11, - notation: 12 // Deprecated -}; -const getGlobal = function getGlobal() { - return typeof window === 'undefined' ? null : window; -}; -/** - * Creates a no-op policy for internal use only. - * Don't export this function outside this module! - * @param trustedTypes The policy factory. - * @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix). - * @return The policy created (or null, if Trusted Types - * are not supported or creating the policy failed). - */ -const _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, purifyHostElement) { - if (typeof trustedTypes !== 'object' || typeof trustedTypes.createPolicy !== 'function') { - return null; - } - // Allow the callers to control the unique policy name - // by adding a data-tt-policy-suffix to the script element with the DOMPurify. - // Policy creation with duplicate names throws in Trusted Types. - let suffix = null; - const ATTR_NAME = 'data-tt-policy-suffix'; - if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) { - suffix = purifyHostElement.getAttribute(ATTR_NAME); - } - const policyName = 'dompurify' + (suffix ? '#' + suffix : ''); - try { - return trustedTypes.createPolicy(policyName, { - createHTML(html) { - return html; - }, - createScriptURL(scriptUrl) { - return scriptUrl; - } - }); - } catch (_) { - // Policy creation failed (most likely another DOMPurify script has - // already run). Skip creating the policy, as this will only cause errors - // if TT are enforced. - console.warn('TrustedTypes policy ' + policyName + ' could not be created.'); - return null; - } -}; -const _createHooksMap = function _createHooksMap() { - return { - afterSanitizeAttributes: [], - afterSanitizeElements: [], - afterSanitizeShadowDOM: [], - beforeSanitizeAttributes: [], - beforeSanitizeElements: [], - beforeSanitizeShadowDOM: [], - uponSanitizeAttribute: [], - uponSanitizeElement: [], - uponSanitizeShadowNode: [] - }; -}; -function createDOMPurify() { - let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal(); - const DOMPurify = root => createDOMPurify(root); - DOMPurify.version = '3.2.4'; - DOMPurify.removed = []; - if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) { - // Not running in a browser, provide a factory function - // so that you can pass your own Window - DOMPurify.isSupported = false; - return DOMPurify; - } - let { - document - } = window; - const originalDocument = document; - const currentScript = originalDocument.currentScript; - const { - DocumentFragment, - HTMLTemplateElement, - Node, - Element, - NodeFilter, - NamedNodeMap = window.NamedNodeMap || window.MozNamedAttrMap, - HTMLFormElement, - DOMParser, - trustedTypes - } = window; - const ElementPrototype = Element.prototype; - const cloneNode = lookupGetter(ElementPrototype, 'cloneNode'); - const remove = lookupGetter(ElementPrototype, 'remove'); - const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling'); - const getChildNodes = lookupGetter(ElementPrototype, 'childNodes'); - const getParentNode = lookupGetter(ElementPrototype, 'parentNode'); - // As per issue #47, the web-components registry is inherited by a - // new document created via createHTMLDocument. As per the spec - // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries) - // a new empty registry is used when creating a template contents owner - // document, so we use that as our parent document to ensure nothing - // is inherited. - if (typeof HTMLTemplateElement === 'function') { - const template = document.createElement('template'); - if (template.content && template.content.ownerDocument) { - document = template.content.ownerDocument; - } - } - let trustedTypesPolicy; - let emptyHTML = ''; - const { - implementation, - createNodeIterator, - createDocumentFragment, - getElementsByTagName - } = document; - const { - importNode - } = originalDocument; - let hooks = _createHooksMap(); - /** - * Expose whether this browser supports running the full DOMPurify. - */ - DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined; - const { - MUSTACHE_EXPR, - ERB_EXPR, - TMPLIT_EXPR, - DATA_ATTR, - ARIA_ATTR, - IS_SCRIPT_OR_DATA, - ATTR_WHITESPACE, - CUSTOM_ELEMENT - } = EXPRESSIONS; - let { - IS_ALLOWED_URI: IS_ALLOWED_URI$1 - } = EXPRESSIONS; - /** - * We consider the elements and attributes below to be safe. Ideally - * don't add any new ones but feel free to remove unwanted ones. - */ - /* allowed element names */ - let ALLOWED_TAGS = null; - const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]); - /* Allowed attribute names */ - let ALLOWED_ATTR = null; - const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]); - /* - * Configure how DOMPurify should handle custom elements and their attributes as well as customized built-in elements. - * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements) - * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list) - * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`. - */ - let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, { - tagNameCheck: { - writable: true, - configurable: false, - enumerable: true, - value: null - }, - attributeNameCheck: { - writable: true, - configurable: false, - enumerable: true, - value: null - }, - allowCustomizedBuiltInElements: { - writable: true, - configurable: false, - enumerable: true, - value: false - } - })); - /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */ - let FORBID_TAGS = null; - /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */ - let FORBID_ATTR = null; - /* Decide if ARIA attributes are okay */ - let ALLOW_ARIA_ATTR = true; - /* Decide if custom data attributes are okay */ - let ALLOW_DATA_ATTR = true; - /* Decide if unknown protocols are okay */ - let ALLOW_UNKNOWN_PROTOCOLS = false; - /* Decide if self-closing tags in attributes are allowed. - * Usually removed due to a mXSS issue in jQuery 3.0 */ - let ALLOW_SELF_CLOSE_IN_ATTR = true; - /* Output should be safe for common template engines. - * This means, DOMPurify removes data attributes, mustaches and ERB - */ - let SAFE_FOR_TEMPLATES = false; - /* Output should be safe even for XML used within HTML and alike. - * This means, DOMPurify removes comments when containing risky content. - */ - let SAFE_FOR_XML = true; - /* Decide if document with ... should be returned */ - let WHOLE_DOCUMENT = false; - /* Track whether config is already set on this instance of DOMPurify. */ - let SET_CONFIG = false; - /* Decide if all elements (e.g. style, script) must be children of - * document.body. By default, browsers might move them to document.head */ - let FORCE_BODY = false; - /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html - * string (or a TrustedHTML object if Trusted Types are supported). - * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead - */ - let RETURN_DOM = false; - /* Decide if a DOM `DocumentFragment` should be returned, instead of a html - * string (or a TrustedHTML object if Trusted Types are supported) */ - let RETURN_DOM_FRAGMENT = false; - /* Try to return a Trusted Type object instead of a string, return a string in - * case Trusted Types are not supported */ - let RETURN_TRUSTED_TYPE = false; - /* Output should be free from DOM clobbering attacks? - * This sanitizes markups named with colliding, clobberable built-in DOM APIs. - */ - let SANITIZE_DOM = true; - /* Achieve full DOM Clobbering protection by isolating the namespace of named - * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules. - * - * HTML/DOM spec rules that enable DOM Clobbering: - * - Named Access on Window (§7.3.3) - * - DOM Tree Accessors (§3.1.5) - * - Form Element Parent-Child Relations (§4.10.3) - * - Iframe srcdoc / Nested WindowProxies (§4.8.5) - * - HTMLCollection (§4.2.10.2) - * - * Namespace isolation is implemented by prefixing `id` and `name` attributes - * with a constant string, i.e., `user-content-` - */ - let SANITIZE_NAMED_PROPS = false; - const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-'; - /* Keep element content when removing element? */ - let KEEP_CONTENT = true; - /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead - * of importing it into a new Document and returning a sanitized copy */ - let IN_PLACE = false; - /* Allow usage of profiles like html, svg and mathMl */ - let USE_PROFILES = {}; - /* Tags to ignore content of when KEEP_CONTENT is true */ - let FORBID_CONTENTS = null; - const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']); - /* Tags that are safe for data: URIs */ - let DATA_URI_TAGS = null; - const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']); - /* Attributes safe for values like "javascript:" */ - let URI_SAFE_ATTRIBUTES = null; - const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']); - const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML'; - const SVG_NAMESPACE = 'http://www.w3.org/2000/svg'; - const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml'; - /* Document namespace */ - let NAMESPACE = HTML_NAMESPACE; - let IS_EMPTY_INPUT = false; - /* Allowed XHTML+XML namespaces */ - let ALLOWED_NAMESPACES = null; - const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString); - let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']); - let HTML_INTEGRATION_POINTS = addToSet({}, ['annotation-xml']); - // Certain elements are allowed in both SVG and HTML - // namespace. We need to specify them explicitly - // so that they don't get erroneously deleted from - // HTML namespace. - const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']); - /* Parsing of strict XHTML documents */ - let PARSER_MEDIA_TYPE = null; - const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html']; - const DEFAULT_PARSER_MEDIA_TYPE = 'text/html'; - let transformCaseFunc = null; - /* Keep a reference to config to pass to hooks */ - let CONFIG = null; - /* Ideally, do not touch anything below this line */ - /* ______________________________________________ */ - const formElement = document.createElement('form'); - const isRegexOrFunction = function isRegexOrFunction(testValue) { - return testValue instanceof RegExp || testValue instanceof Function; - }; - /** - * _parseConfig - * - * @param cfg optional config literal - */ - // eslint-disable-next-line complexity - const _parseConfig = function _parseConfig() { - let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - if (CONFIG && CONFIG === cfg) { - return; - } - /* Shield configuration object from tampering */ - if (!cfg || typeof cfg !== 'object') { - cfg = {}; - } - /* Shield configuration object from prototype pollution */ - cfg = clone(cfg); - PARSER_MEDIA_TYPE = - // eslint-disable-next-line unicorn/prefer-includes - SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE; - // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is. - transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase; - /* Set configuration parameters */ - ALLOWED_TAGS = objectHasOwnProperty(cfg, 'ALLOWED_TAGS') ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS; - ALLOWED_ATTR = objectHasOwnProperty(cfg, 'ALLOWED_ATTR') ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR; - ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, 'ALLOWED_NAMESPACES') ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES; - URI_SAFE_ATTRIBUTES = objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR, transformCaseFunc) : DEFAULT_URI_SAFE_ATTRIBUTES; - DATA_URI_TAGS = objectHasOwnProperty(cfg, 'ADD_DATA_URI_TAGS') ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS, transformCaseFunc) : DEFAULT_DATA_URI_TAGS; - FORBID_CONTENTS = objectHasOwnProperty(cfg, 'FORBID_CONTENTS') ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS; - FORBID_TAGS = objectHasOwnProperty(cfg, 'FORBID_TAGS') ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : {}; - FORBID_ATTR = objectHasOwnProperty(cfg, 'FORBID_ATTR') ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : {}; - USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES : false; - ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true - ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true - ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false - ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true - SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false - SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true - WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false - RETURN_DOM = cfg.RETURN_DOM || false; // Default false - RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false - RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false - FORCE_BODY = cfg.FORCE_BODY || false; // Default false - SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true - SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false - KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true - IN_PLACE = cfg.IN_PLACE || false; // Default false - IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI; - NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE; - MATHML_TEXT_INTEGRATION_POINTS = cfg.MATHML_TEXT_INTEGRATION_POINTS || MATHML_TEXT_INTEGRATION_POINTS; - HTML_INTEGRATION_POINTS = cfg.HTML_INTEGRATION_POINTS || HTML_INTEGRATION_POINTS; - CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || {}; - if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) { - CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck; - } - if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) { - CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck; - } - if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === 'boolean') { - CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements; - } - if (SAFE_FOR_TEMPLATES) { - ALLOW_DATA_ATTR = false; - } - if (RETURN_DOM_FRAGMENT) { - RETURN_DOM = true; - } - /* Parse profile info */ - if (USE_PROFILES) { - ALLOWED_TAGS = addToSet({}, text); - ALLOWED_ATTR = []; - if (USE_PROFILES.html === true) { - addToSet(ALLOWED_TAGS, html$1); - addToSet(ALLOWED_ATTR, html); - } - if (USE_PROFILES.svg === true) { - addToSet(ALLOWED_TAGS, svg$1); - addToSet(ALLOWED_ATTR, svg); - addToSet(ALLOWED_ATTR, xml); - } - if (USE_PROFILES.svgFilters === true) { - addToSet(ALLOWED_TAGS, svgFilters); - addToSet(ALLOWED_ATTR, svg); - addToSet(ALLOWED_ATTR, xml); - } - if (USE_PROFILES.mathMl === true) { - addToSet(ALLOWED_TAGS, mathMl$1); - addToSet(ALLOWED_ATTR, mathMl); - addToSet(ALLOWED_ATTR, xml); - } - } - /* Merge configuration parameters */ - if (cfg.ADD_TAGS) { - if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) { - ALLOWED_TAGS = clone(ALLOWED_TAGS); - } - addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc); - } - if (cfg.ADD_ATTR) { - if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) { - ALLOWED_ATTR = clone(ALLOWED_ATTR); - } - addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc); - } - if (cfg.ADD_URI_SAFE_ATTR) { - addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc); - } - if (cfg.FORBID_CONTENTS) { - if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) { - FORBID_CONTENTS = clone(FORBID_CONTENTS); - } - addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc); - } - /* Add #text in case KEEP_CONTENT is set to true */ - if (KEEP_CONTENT) { - ALLOWED_TAGS['#text'] = true; - } - /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */ - if (WHOLE_DOCUMENT) { - addToSet(ALLOWED_TAGS, ['html', 'head', 'body']); - } - /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */ - if (ALLOWED_TAGS.table) { - addToSet(ALLOWED_TAGS, ['tbody']); - delete FORBID_TAGS.tbody; - } - if (cfg.TRUSTED_TYPES_POLICY) { - if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') { - throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.'); - } - if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') { - throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.'); - } - // Overwrite existing TrustedTypes policy. - trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY; - // Sign local variables required by `sanitize`. - emptyHTML = trustedTypesPolicy.createHTML(''); - } else { - // Uninitialized policy, attempt to initialize the internal dompurify policy. - if (trustedTypesPolicy === undefined) { - trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript); - } - // If creating the internal policy succeeded sign internal variables. - if (trustedTypesPolicy !== null && typeof emptyHTML === 'string') { - emptyHTML = trustedTypesPolicy.createHTML(''); - } - } - // Prevent further manipulation of configuration. - // Not available in IE8, Safari 5, etc. - if (freeze) { - freeze(cfg); - } - CONFIG = cfg; - }; - /* Keep track of all possible SVG and MathML tags - * so that we can perform the namespace checks - * correctly. */ - const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]); - const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]); - /** - * @param element a DOM element whose namespace is being checked - * @returns Return false if the element has a - * namespace that a spec-compliant parser would never - * return. Return true otherwise. - */ - const _checkValidNamespace = function _checkValidNamespace(element) { - let parent = getParentNode(element); - // In JSDOM, if we're inside shadow DOM, then parentNode - // can be null. We just simulate parent in this case. - if (!parent || !parent.tagName) { - parent = { - namespaceURI: NAMESPACE, - tagName: 'template' - }; - } - const tagName = stringToLowerCase(element.tagName); - const parentTagName = stringToLowerCase(parent.tagName); - if (!ALLOWED_NAMESPACES[element.namespaceURI]) { - return false; - } - if (element.namespaceURI === SVG_NAMESPACE) { - // The only way to switch from HTML namespace to SVG - // is via . If it happens via any other tag, then - // it should be killed. - if (parent.namespaceURI === HTML_NAMESPACE) { - return tagName === 'svg'; - } - // The only way to switch from MathML to SVG is via` - // svg if parent is either or MathML - // text integration points. - if (parent.namespaceURI === MATHML_NAMESPACE) { - return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]); - } - // We only allow elements that are defined in SVG - // spec. All others are disallowed in SVG namespace. - return Boolean(ALL_SVG_TAGS[tagName]); - } - if (element.namespaceURI === MATHML_NAMESPACE) { - // The only way to switch from HTML namespace to MathML - // is via . If it happens via any other tag, then - // it should be killed. - if (parent.namespaceURI === HTML_NAMESPACE) { - return tagName === 'math'; - } - // The only way to switch from SVG to MathML is via - // and HTML integration points - if (parent.namespaceURI === SVG_NAMESPACE) { - return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName]; - } - // We only allow elements that are defined in MathML - // spec. All others are disallowed in MathML namespace. - return Boolean(ALL_MATHML_TAGS[tagName]); - } - if (element.namespaceURI === HTML_NAMESPACE) { - // The only way to switch from SVG to HTML is via - // HTML integration points, and from MathML to HTML - // is via MathML text integration points - if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) { - return false; - } - if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) { - return false; - } - // We disallow tags that are specific for MathML - // or SVG and should never appear in HTML namespace - return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]); - } - // For XHTML and XML documents that support custom namespaces - if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) { - return true; - } - // The code should never reach this place (this means - // that the element somehow got namespace that is not - // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES). - // Return false just in case. - return false; - }; - /** - * _forceRemove - * - * @param node a DOM node - */ - const _forceRemove = function _forceRemove(node) { - arrayPush(DOMPurify.removed, { - element: node - }); - try { - // eslint-disable-next-line unicorn/prefer-dom-node-remove - getParentNode(node).removeChild(node); - } catch (_) { - remove(node); - } - }; - /** - * _removeAttribute - * - * @param name an Attribute name - * @param element a DOM node - */ - const _removeAttribute = function _removeAttribute(name, element) { - try { - arrayPush(DOMPurify.removed, { - attribute: element.getAttributeNode(name), - from: element - }); - } catch (_) { - arrayPush(DOMPurify.removed, { - attribute: null, - from: element - }); - } - element.removeAttribute(name); - // We void attribute values for unremovable "is" attributes - if (name === 'is') { - if (RETURN_DOM || RETURN_DOM_FRAGMENT) { - try { - _forceRemove(element); - } catch (_) {} - } else { - try { - element.setAttribute(name, ''); - } catch (_) {} - } - } - }; - /** - * _initDocument - * - * @param dirty - a string of dirty markup - * @return a DOM, filled with the dirty markup - */ - const _initDocument = function _initDocument(dirty) { - /* Create a HTML document */ - let doc = null; - let leadingWhitespace = null; - if (FORCE_BODY) { - dirty = '' + dirty; - } else { - /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */ - const matches = stringMatch(dirty, /^[\r\n\t ]+/); - leadingWhitespace = matches && matches[0]; - } - if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) { - // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict) - dirty = '' + dirty + ''; - } - const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty; - /* - * Use the DOMParser API by default, fallback later if needs be - * DOMParser not work for svg when has multiple root element. - */ - if (NAMESPACE === HTML_NAMESPACE) { - try { - doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE); - } catch (_) {} - } - /* Use createHTMLDocument in case DOMParser is not available */ - if (!doc || !doc.documentElement) { - doc = implementation.createDocument(NAMESPACE, 'template', null); - try { - doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload; - } catch (_) { - // Syntax error if dirtyPayload is invalid xml - } - } - const body = doc.body || doc.documentElement; - if (dirty && leadingWhitespace) { - body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null); - } - /* Work on whole document or just its body */ - if (NAMESPACE === HTML_NAMESPACE) { - return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0]; - } - return WHOLE_DOCUMENT ? doc.documentElement : body; - }; - /** - * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. - * - * @param root The root element or node to start traversing on. - * @return The created NodeIterator - */ - const _createNodeIterator = function _createNodeIterator(root) { - return createNodeIterator.call(root.ownerDocument || root, root, - // eslint-disable-next-line no-bitwise - NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null); - }; - /** - * _isClobbered - * - * @param element element to check for clobbering attacks - * @return true if clobbered, false if safe - */ - const _isClobbered = function _isClobbered(element) { - return element instanceof HTMLFormElement && (typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' || !(element.attributes instanceof NamedNodeMap) || typeof element.removeAttribute !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function'); - }; - /** - * Checks whether the given object is a DOM node. - * - * @param value object to check whether it's a DOM node - * @return true is object is a DOM node - */ - const _isNode = function _isNode(value) { - return typeof Node === 'function' && value instanceof Node; - }; - function _executeHooks(hooks, currentNode, data) { - arrayForEach(hooks, hook => { - hook.call(DOMPurify, currentNode, data, CONFIG); - }); - } - /** - * _sanitizeElements - * - * @protect nodeName - * @protect textContent - * @protect removeChild - * @param currentNode to check for permission to exist - * @return true if node was killed, false if left alive - */ - const _sanitizeElements = function _sanitizeElements(currentNode) { - let content = null; - /* Execute a hook if present */ - _executeHooks(hooks.beforeSanitizeElements, currentNode, null); - /* Check if element is clobbered or can clobber */ - if (_isClobbered(currentNode)) { - _forceRemove(currentNode); - return true; - } - /* Now let's check the element's type and name */ - const tagName = transformCaseFunc(currentNode.nodeName); - /* Execute a hook if present */ - _executeHooks(hooks.uponSanitizeElement, currentNode, { - tagName, - allowedTags: ALLOWED_TAGS - }); - /* Detect mXSS attempts abusing namespace confusion */ - if (currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\w]/g, currentNode.innerHTML) && regExpTest(/<[/\w]/g, currentNode.textContent)) { - _forceRemove(currentNode); - return true; - } - /* Remove any occurrence of processing instructions */ - if (currentNode.nodeType === NODE_TYPE.progressingInstruction) { - _forceRemove(currentNode); - return true; - } - /* Remove any kind of possibly harmful comments */ - if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(/<[/\w]/g, currentNode.data)) { - _forceRemove(currentNode); - return true; - } - /* Remove element if anything forbids its presence */ - if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) { - /* Check if we have a custom element to handle */ - if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) { - if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) { - return false; - } - if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) { - return false; - } - } - /* Keep content except for bad-listed elements */ - if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) { - const parentNode = getParentNode(currentNode) || currentNode.parentNode; - const childNodes = getChildNodes(currentNode) || currentNode.childNodes; - if (childNodes && parentNode) { - const childCount = childNodes.length; - for (let i = childCount - 1; i >= 0; --i) { - const childClone = cloneNode(childNodes[i], true); - childClone.__removalCount = (currentNode.__removalCount || 0) + 1; - parentNode.insertBefore(childClone, getNextSibling(currentNode)); - } - } - } - _forceRemove(currentNode); - return true; - } - /* Check whether element has a valid namespace */ - if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) { - _forceRemove(currentNode); - return true; - } - /* Make sure that older browsers don't get fallback-tag mXSS */ - if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)) { - _forceRemove(currentNode); - return true; - } - /* Sanitize element content to be template-safe */ - if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) { - /* Get the element's text content */ - content = currentNode.textContent; - arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => { - content = stringReplace(content, expr, ' '); - }); - if (currentNode.textContent !== content) { - arrayPush(DOMPurify.removed, { - element: currentNode.cloneNode() - }); - currentNode.textContent = content; - } - } - /* Execute a hook if present */ - _executeHooks(hooks.afterSanitizeElements, currentNode, null); - return false; - }; - /** - * _isValidAttribute - * - * @param lcTag Lowercase tag name of containing element. - * @param lcName Lowercase attribute name. - * @param value Attribute value. - * @return Returns true if `value` is valid, otherwise false. - */ - // eslint-disable-next-line complexity - const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) { - /* Make sure attribute cannot clobber */ - if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) { - return false; - } - /* Allow valid data-* attributes: At least one character after "-" - (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes) - XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804) - We don't need to check the value; it's always URI safe. */ - if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR, lcName)) ; else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) { - if ( - // First condition does a very basic check if a) it's basically a valid custom element tagname AND - // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck - // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck - _isBasicCustomElement(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName)) || - // Alternative, second condition checks if it's an `is`-attribute, AND - // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck - lcName === 'is' && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))) ; else { - return false; - } - /* Check value is safe. First, is attr inert? If so, is safe */ - } else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) ; else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if (value) { - return false; - } else ; - return true; - }; - /** - * _isBasicCustomElement - * checks if at least one dash is included in tagName, and it's not the first char - * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name - * - * @param tagName name of the tag of the node to sanitize - * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false. - */ - const _isBasicCustomElement = function _isBasicCustomElement(tagName) { - return tagName !== 'annotation-xml' && stringMatch(tagName, CUSTOM_ELEMENT); - }; - /** - * _sanitizeAttributes - * - * @protect attributes - * @protect nodeName - * @protect removeAttribute - * @protect setAttribute - * - * @param currentNode to sanitize - */ - const _sanitizeAttributes = function _sanitizeAttributes(currentNode) { - /* Execute a hook if present */ - _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null); - const { - attributes - } = currentNode; - /* Check if we have attributes; if not we might have a text node */ - if (!attributes || _isClobbered(currentNode)) { - return; - } - const hookEvent = { - attrName: '', - attrValue: '', - keepAttr: true, - allowedAttributes: ALLOWED_ATTR, - forceKeepAttr: undefined - }; - let l = attributes.length; - /* Go backwards over all attributes; safely remove bad ones */ - while (l--) { - const attr = attributes[l]; - const { - name, - namespaceURI, - value: attrValue - } = attr; - const lcName = transformCaseFunc(name); - let value = name === 'value' ? attrValue : stringTrim(attrValue); - /* Execute a hook if present */ - hookEvent.attrName = lcName; - hookEvent.attrValue = value; - hookEvent.keepAttr = true; - hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set - _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent); - value = hookEvent.attrValue; - /* Full DOM Clobbering protection via namespace isolation, - * Prefix id and name attributes with `user-content-` - */ - if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name')) { - // Remove the attribute with this value - _removeAttribute(name, currentNode); - // Prefix the value and later re-create the attribute with the sanitized value - value = SANITIZE_NAMED_PROPS_PREFIX + value; - } - /* Work around a security issue with comments inside attributes */ - if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|title)/i, value)) { - _removeAttribute(name, currentNode); - continue; - } - /* Did the hooks approve of the attribute? */ - if (hookEvent.forceKeepAttr) { - continue; - } - /* Remove attribute */ - _removeAttribute(name, currentNode); - /* Did the hooks approve of the attribute? */ - if (!hookEvent.keepAttr) { - continue; - } - /* Work around a security issue in jQuery 3.0 */ - if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) { - _removeAttribute(name, currentNode); - continue; - } - /* Sanitize attribute content to be template-safe */ - if (SAFE_FOR_TEMPLATES) { - arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => { - value = stringReplace(value, expr, ' '); - }); - } - /* Is `value` valid for this attribute? */ - const lcTag = transformCaseFunc(currentNode.nodeName); - if (!_isValidAttribute(lcTag, lcName, value)) { - continue; - } - /* Handle attributes that require Trusted Types */ - if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function') { - if (namespaceURI) ; else { - switch (trustedTypes.getAttributeType(lcTag, lcName)) { - case 'TrustedHTML': - { - value = trustedTypesPolicy.createHTML(value); - break; - } - case 'TrustedScriptURL': - { - value = trustedTypesPolicy.createScriptURL(value); - break; - } - } - } - } - /* Handle invalid data-* attribute set by try-catching it */ - try { - if (namespaceURI) { - currentNode.setAttributeNS(namespaceURI, name, value); - } else { - /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */ - currentNode.setAttribute(name, value); - } - if (_isClobbered(currentNode)) { - _forceRemove(currentNode); - } else { - arrayPop(DOMPurify.removed); - } - } catch (_) {} - } - /* Execute a hook if present */ - _executeHooks(hooks.afterSanitizeAttributes, currentNode, null); - }; - /** - * _sanitizeShadowDOM - * - * @param fragment to iterate over recursively - */ - const _sanitizeShadowDOM = function _sanitizeShadowDOM(fragment) { - let shadowNode = null; - const shadowIterator = _createNodeIterator(fragment); - /* Execute a hook if present */ - _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null); - while (shadowNode = shadowIterator.nextNode()) { - /* Execute a hook if present */ - _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null); - /* Sanitize tags and elements */ - _sanitizeElements(shadowNode); - /* Check attributes next */ - _sanitizeAttributes(shadowNode); - /* Deep shadow DOM detected */ - if (shadowNode.content instanceof DocumentFragment) { - _sanitizeShadowDOM(shadowNode.content); - } - } - /* Execute a hook if present */ - _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null); - }; - // eslint-disable-next-line complexity - DOMPurify.sanitize = function (dirty) { - let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - let body = null; - let importedNode = null; - let currentNode = null; - let returnNode = null; - /* Make sure we have a string to sanitize. - DO NOT return early, as this will return the wrong type if - the user has requested a DOM object rather than a string */ - IS_EMPTY_INPUT = !dirty; - if (IS_EMPTY_INPUT) { - dirty = ''; - } - /* Stringify, in case dirty is an object */ - if (typeof dirty !== 'string' && !_isNode(dirty)) { - if (typeof dirty.toString === 'function') { - dirty = dirty.toString(); - if (typeof dirty !== 'string') { - throw typeErrorCreate('dirty is not a string, aborting'); - } - } else { - throw typeErrorCreate('toString is not a function'); - } - } - /* Return dirty HTML if DOMPurify cannot run */ - if (!DOMPurify.isSupported) { - return dirty; - } - /* Assign config vars */ - if (!SET_CONFIG) { - _parseConfig(cfg); - } - /* Clean up removed elements */ - DOMPurify.removed = []; - /* Check if dirty is correctly typed for IN_PLACE */ - if (typeof dirty === 'string') { - IN_PLACE = false; - } - if (IN_PLACE) { - /* Do some early pre-sanitization to avoid unsafe root nodes */ - if (dirty.nodeName) { - const tagName = transformCaseFunc(dirty.nodeName); - if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) { - throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place'); - } - } - } else if (dirty instanceof Node) { - /* If dirty is a DOM element, append to an empty document to avoid - elements being stripped by the parser */ - body = _initDocument(''); - importedNode = body.ownerDocument.importNode(dirty, true); - if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === 'BODY') { - /* Node is already a body, use as is */ - body = importedNode; - } else if (importedNode.nodeName === 'HTML') { - body = importedNode; - } else { - // eslint-disable-next-line unicorn/prefer-dom-node-append - body.appendChild(importedNode); - } - } else { - /* Exit directly if we have nothing to do */ - if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT && - // eslint-disable-next-line unicorn/prefer-includes - dirty.indexOf('<') === -1) { - return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty; - } - /* Initialize the document to work on */ - body = _initDocument(dirty); - /* Check we have a DOM node from the data */ - if (!body) { - return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : ''; - } - } - /* Remove first element node (ours) if FORCE_BODY is set */ - if (body && FORCE_BODY) { - _forceRemove(body.firstChild); - } - /* Get node iterator */ - const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body); - /* Now start iterating over the created document */ - while (currentNode = nodeIterator.nextNode()) { - /* Sanitize tags and elements */ - _sanitizeElements(currentNode); - /* Check attributes next */ - _sanitizeAttributes(currentNode); - /* Shadow DOM detected, sanitize it */ - if (currentNode.content instanceof DocumentFragment) { - _sanitizeShadowDOM(currentNode.content); - } - } - /* If we sanitized `dirty` in-place, return it. */ - if (IN_PLACE) { - return dirty; - } - /* Return sanitized string or DOM */ - if (RETURN_DOM) { - if (RETURN_DOM_FRAGMENT) { - returnNode = createDocumentFragment.call(body.ownerDocument); - while (body.firstChild) { - // eslint-disable-next-line unicorn/prefer-dom-node-append - returnNode.appendChild(body.firstChild); - } - } else { - returnNode = body; - } - if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) { - /* - AdoptNode() is not used because internal state is not reset - (e.g. the past names map of a HTMLFormElement), this is safe - in theory but we would rather not risk another attack vector. - The state that is cloned by importNode() is explicitly defined - by the specs. - */ - returnNode = importNode.call(originalDocument, returnNode, true); - } - return returnNode; - } - let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML; - /* Serialize doctype if allowed */ - if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) { - serializedHTML = '\n' + serializedHTML; - } - /* Sanitize final string template-safe */ - if (SAFE_FOR_TEMPLATES) { - arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => { - serializedHTML = stringReplace(serializedHTML, expr, ' '); - }); - } - return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML; - }; - DOMPurify.setConfig = function () { - let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - _parseConfig(cfg); - SET_CONFIG = true; - }; - DOMPurify.clearConfig = function () { - CONFIG = null; - SET_CONFIG = false; - }; - DOMPurify.isValidAttribute = function (tag, attr, value) { - /* Initialize shared config vars if necessary. */ - if (!CONFIG) { - _parseConfig({}); - } - const lcTag = transformCaseFunc(tag); - const lcName = transformCaseFunc(attr); - return _isValidAttribute(lcTag, lcName, value); - }; - DOMPurify.addHook = function (entryPoint, hookFunction) { - if (typeof hookFunction !== 'function') { - return; - } - arrayPush(hooks[entryPoint], hookFunction); - }; - DOMPurify.removeHook = function (entryPoint, hookFunction) { - if (hookFunction !== undefined) { - const index = arrayLastIndexOf(hooks[entryPoint], hookFunction); - return index === -1 ? undefined : arraySplice(hooks[entryPoint], index, 1)[0]; - } - return arrayPop(hooks[entryPoint]); - }; - DOMPurify.removeHooks = function (entryPoint) { - hooks[entryPoint] = []; - }; - DOMPurify.removeAllHooks = function () { - hooks = _createHooksMap(); - }; - return DOMPurify; -} -var purify = createDOMPurify(); - -export { purify as default }; -//# sourceMappingURL=purify.es.mjs.map diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/markdown_viewer/viewer.html b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/markdown_viewer/viewer.html deleted file mode 100644 index 94447ffc47e..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/markdown_viewer/viewer.html +++ /dev/null @@ -1,32 +0,0 @@ - - - - - Markdown viewer - - - - -

    - - - diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/markdown_viewer/viewer.mjs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/markdown_viewer/viewer.mjs deleted file mode 100644 index 78eb819c9a8..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/markdown_viewer/viewer.mjs +++ /dev/null @@ -1,13 +0,0 @@ -import { parse } from '../marked/dist/marked.esm.js'; -import purify from '../dompurify/dist/purify.es.mjs'; - -const url = new URL(window.location); -const fileUrl = url.searchParams.get('file'); -if (!fileUrl) { - throw new Error('File not specified in the URL query string'); -} - -var response = await fetch(fileUrl); -var text = await response.text(); - -document.getElementById('content').innerHTML = purify.sanitize(parse(text)); diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/marked/README.md b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/marked/README.md deleted file mode 100644 index 352b52d5503..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/marked/README.md +++ /dev/null @@ -1,5 +0,0 @@ -marked version 15.0.6 -https://github.com/markedjs/marked -License: MIT - -To update, replace the `dist/marked.esm.js` file with with an updated version from https://www.npmjs.com/package/marked. diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/marked/dist/marked.esm.js b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/marked/dist/marked.esm.js deleted file mode 100644 index a32cd778363..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/marked/dist/marked.esm.js +++ /dev/null @@ -1,2568 +0,0 @@ -/** - * marked v15.0.6 - a markdown parser - * Copyright (c) 2011-2025, Christopher Jeffrey. (MIT Licensed) - * https://github.com/markedjs/marked - */ - -/** - * DO NOT EDIT THIS FILE - * The code in this file is generated from files in ./src/ - */ - -/** - * Gets the original marked default options. - */ -function _getDefaults() { - return { - async: false, - breaks: false, - extensions: null, - gfm: true, - hooks: null, - pedantic: false, - renderer: null, - silent: false, - tokenizer: null, - walkTokens: null, - }; -} -let _defaults = _getDefaults(); -function changeDefaults(newDefaults) { - _defaults = newDefaults; -} - -const noopTest = { exec: () => null }; -function edit(regex, opt = '') { - let source = typeof regex === 'string' ? regex : regex.source; - const obj = { - replace: (name, val) => { - let valSource = typeof val === 'string' ? val : val.source; - valSource = valSource.replace(other.caret, '$1'); - source = source.replace(name, valSource); - return obj; - }, - getRegex: () => { - return new RegExp(source, opt); - }, - }; - return obj; -} -const other = { - codeRemoveIndent: /^(?: {1,4}| {0,3}\t)/gm, - outputLinkReplace: /\\([\[\]])/g, - indentCodeCompensation: /^(\s+)(?:```)/, - beginningSpace: /^\s+/, - endingHash: /#$/, - startingSpaceChar: /^ /, - endingSpaceChar: / $/, - nonSpaceChar: /[^ ]/, - newLineCharGlobal: /\n/g, - tabCharGlobal: /\t/g, - multipleSpaceGlobal: /\s+/g, - blankLine: /^[ \t]*$/, - doubleBlankLine: /\n[ \t]*\n[ \t]*$/, - blockquoteStart: /^ {0,3}>/, - blockquoteSetextReplace: /\n {0,3}((?:=+|-+) *)(?=\n|$)/g, - blockquoteSetextReplace2: /^ {0,3}>[ \t]?/gm, - listReplaceTabs: /^\t+/, - listReplaceNesting: /^ {1,4}(?=( {4})*[^ ])/g, - listIsTask: /^\[[ xX]\] /, - listReplaceTask: /^\[[ xX]\] +/, - anyLine: /\n.*\n/, - hrefBrackets: /^<(.*)>$/, - tableDelimiter: /[:|]/, - tableAlignChars: /^\||\| *$/g, - tableRowBlankLine: /\n[ \t]*$/, - tableAlignRight: /^ *-+: *$/, - tableAlignCenter: /^ *:-+: *$/, - tableAlignLeft: /^ *:-+ *$/, - startATag: /^
    /i, - startPreScriptTag: /^<(pre|code|kbd|script)(\s|>)/i, - endPreScriptTag: /^<\/(pre|code|kbd|script)(\s|>)/i, - startAngleBracket: /^$/, - pedanticHrefTitle: /^([^'"]*[^\s])\s+(['"])(.*)\2/, - unicodeAlphaNumeric: /[\p{L}\p{N}]/u, - escapeTest: /[&<>"']/, - escapeReplace: /[&<>"']/g, - escapeTestNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/, - escapeReplaceNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g, - unescapeTest: /&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig, - caret: /(^|[^\[])\^/g, - percentDecode: /%25/g, - findPipe: /\|/g, - splitPipe: / \|/, - slashPipe: /\\\|/g, - carriageReturn: /\r\n|\r/g, - spaceLine: /^ +$/gm, - notSpaceStart: /^\S*/, - endingNewline: /\n$/, - listItemRegex: (bull) => new RegExp(`^( {0,3}${bull})((?:[\t ][^\\n]*)?(?:\\n|$))`), - nextBulletRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ \t][^\\n]*)?(?:\\n|$))`), - hrRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`), - fencesBeginRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\`\`\`|~~~)`), - headingBeginRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`), - htmlBeginRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}<(?:[a-z].*>|!--)`, 'i'), -}; -/** - * Block-Level Grammar - */ -const newline = /^(?:[ \t]*(?:\n|$))+/; -const blockCode = /^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/; -const fences = /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/; -const hr = /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/; -const heading = /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/; -const bullet = /(?:[*+-]|\d{1,9}[.)])/; -const lheading = edit(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/) - .replace(/bull/g, bullet) // lists can interrupt - .replace(/blockCode/g, /(?: {4}| {0,3}\t)/) // indented code blocks can interrupt - .replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/) // fenced code blocks can interrupt - .replace(/blockquote/g, / {0,3}>/) // blockquote can interrupt - .replace(/heading/g, / {0,3}#{1,6}/) // ATX heading can interrupt - .replace(/html/g, / {0,3}<[^\n>]+>\n/) // block html can interrupt - .getRegex(); -const _paragraph = /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/; -const blockText = /^[^\n]+/; -const _blockLabel = /(?!\s*\])(?:\\.|[^\[\]\\])+/; -const def = edit(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/) - .replace('label', _blockLabel) - .replace('title', /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/) - .getRegex(); -const list = edit(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/) - .replace(/bull/g, bullet) - .getRegex(); -const _tag = 'address|article|aside|base|basefont|blockquote|body|caption' - + '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption' - + '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe' - + '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option' - + '|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title' - + '|tr|track|ul'; -const _comment = /|$))/; -const html = edit('^ {0,3}(?:' // optional indentation - + '<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)' // (1) - + '|comment[^\\n]*(\\n+|$)' // (2) - + '|<\\?[\\s\\S]*?(?:\\?>\\n*|$)' // (3) - + '|\\n*|$)' // (4) - + '|\\n*|$)' // (5) - + '|)[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)' // (6) - + '|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)' // (7) open tag - + '|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)' // (7) closing tag - + ')', 'i') - .replace('comment', _comment) - .replace('tag', _tag) - .replace('attribute', / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/) - .getRegex(); -const paragraph = edit(_paragraph) - .replace('hr', hr) - .replace('heading', ' {0,3}#{1,6}(?:\\s|$)') - .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs - .replace('|table', '') - .replace('blockquote', ' {0,3}>') - .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n') - .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt - .replace('html', ')|<(?:script|pre|style|textarea|!--)') - .replace('tag', _tag) // pars can be interrupted by type (6) html blocks - .getRegex(); -const blockquote = edit(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/) - .replace('paragraph', paragraph) - .getRegex(); -/** - * Normal Block Grammar - */ -const blockNormal = { - blockquote, - code: blockCode, - def, - fences, - heading, - hr, - html, - lheading, - list, - newline, - paragraph, - table: noopTest, - text: blockText, -}; -/** - * GFM Block Grammar - */ -const gfmTable = edit('^ *([^\\n ].*)\\n' // Header - + ' {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)' // Align - + '(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)') // Cells - .replace('hr', hr) - .replace('heading', ' {0,3}#{1,6}(?:\\s|$)') - .replace('blockquote', ' {0,3}>') - .replace('code', '(?: {4}| {0,3}\t)[^\\n]') - .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n') - .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt - .replace('html', ')|<(?:script|pre|style|textarea|!--)') - .replace('tag', _tag) // tables can be interrupted by type (6) html blocks - .getRegex(); -const blockGfm = { - ...blockNormal, - table: gfmTable, - paragraph: edit(_paragraph) - .replace('hr', hr) - .replace('heading', ' {0,3}#{1,6}(?:\\s|$)') - .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs - .replace('table', gfmTable) // interrupt paragraphs with table - .replace('blockquote', ' {0,3}>') - .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n') - .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt - .replace('html', ')|<(?:script|pre|style|textarea|!--)') - .replace('tag', _tag) // pars can be interrupted by type (6) html blocks - .getRegex(), -}; -/** - * Pedantic grammar (original John Gruber's loose markdown specification) - */ -const blockPedantic = { - ...blockNormal, - html: edit('^ *(?:comment *(?:\\n|\\s*$)' - + '|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)' // closed tag - + '|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))') - .replace('comment', _comment) - .replace(/tag/g, '(?!(?:' - + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub' - + '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)' - + '\\b)\\w+(?!:|[^\\w\\s@]*@)\\b') - .getRegex(), - def: /^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/, - heading: /^(#{1,6})(.*)(?:\n+|$)/, - fences: noopTest, // fences not supported - lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/, - paragraph: edit(_paragraph) - .replace('hr', hr) - .replace('heading', ' *#{1,6} *[^\n]') - .replace('lheading', lheading) - .replace('|table', '') - .replace('blockquote', ' {0,3}>') - .replace('|fences', '') - .replace('|list', '') - .replace('|html', '') - .replace('|tag', '') - .getRegex(), -}; -/** - * Inline-Level Grammar - */ -const escape$1 = /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/; -const inlineCode = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/; -const br = /^( {2,}|\\)\n(?!\s*$)/; -const inlineText = /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\ -const blockSkip = /\[[^[\]]*?\]\((?:\\.|[^\\\(\)]|\((?:\\.|[^\\\(\)])*\))*\)|`[^`]*?`|<[^<>]*?>/g; -const emStrongLDelimCore = /^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/; -const emStrongLDelim = edit(emStrongLDelimCore, 'u') - .replace(/punct/g, _punctuation) - .getRegex(); -const emStrongLDelimGfm = edit(emStrongLDelimCore, 'u') - .replace(/punct/g, _punctuationGfmStrongEm) - .getRegex(); -const emStrongRDelimAstCore = '^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)' // Skip orphan inside strong - + '|[^*]+(?=[^*])' // Consume to delim - + '|(?!\\*)punct(\\*+)(?=[\\s]|$)' // (1) #*** can only be a Right Delimiter - + '|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)' // (2) a***#, a*** can only be a Right Delimiter - + '|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)' // (3) #***a, ***a can only be Left Delimiter - + '|[\\s](\\*+)(?!\\*)(?=punct)' // (4) ***# can only be Left Delimiter - + '|(?!\\*)punct(\\*+)(?!\\*)(?=punct)' // (5) #***# can be either Left or Right Delimiter - + '|notPunctSpace(\\*+)(?=notPunctSpace)'; // (6) a***a can be either Left or Right Delimiter -const emStrongRDelimAst = edit(emStrongRDelimAstCore, 'gu') - .replace(/notPunctSpace/g, _notPunctuationOrSpace) - .replace(/punctSpace/g, _punctuationOrSpace) - .replace(/punct/g, _punctuation) - .getRegex(); -const emStrongRDelimAstGfm = edit(emStrongRDelimAstCore, 'gu') - .replace(/notPunctSpace/g, _notPunctuationOrSpaceGfmStrongEm) - .replace(/punctSpace/g, _punctuationOrSpaceGfmStrongEm) - .replace(/punct/g, _punctuationGfmStrongEm) - .getRegex(); -// (6) Not allowed for _ -const emStrongRDelimUnd = edit('^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)' // Skip orphan inside strong - + '|[^_]+(?=[^_])' // Consume to delim - + '|(?!_)punct(_+)(?=[\\s]|$)' // (1) #___ can only be a Right Delimiter - + '|notPunctSpace(_+)(?!_)(?=punctSpace|$)' // (2) a___#, a___ can only be a Right Delimiter - + '|(?!_)punctSpace(_+)(?=notPunctSpace)' // (3) #___a, ___a can only be Left Delimiter - + '|[\\s](_+)(?!_)(?=punct)' // (4) ___# can only be Left Delimiter - + '|(?!_)punct(_+)(?!_)(?=punct)', 'gu') // (5) #___# can be either Left or Right Delimiter - .replace(/notPunctSpace/g, _notPunctuationOrSpace) - .replace(/punctSpace/g, _punctuationOrSpace) - .replace(/punct/g, _punctuation) - .getRegex(); -const anyPunctuation = edit(/\\(punct)/, 'gu') - .replace(/punct/g, _punctuation) - .getRegex(); -const autolink = edit(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/) - .replace('scheme', /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/) - .replace('email', /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/) - .getRegex(); -const _inlineComment = edit(_comment).replace('(?:-->|$)', '-->').getRegex(); -const tag = edit('^comment' - + '|^' // self-closing tag - + '|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>' // open tag - + '|^<\\?[\\s\\S]*?\\?>' // processing instruction, e.g. - + '|^' // declaration, e.g. - + '|^') // CDATA section - .replace('comment', _inlineComment) - .replace('attribute', /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/) - .getRegex(); -const _inlineLabel = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/; -const link = edit(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/) - .replace('label', _inlineLabel) - .replace('href', /<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/) - .replace('title', /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/) - .getRegex(); -const reflink = edit(/^!?\[(label)\]\[(ref)\]/) - .replace('label', _inlineLabel) - .replace('ref', _blockLabel) - .getRegex(); -const nolink = edit(/^!?\[(ref)\](?:\[\])?/) - .replace('ref', _blockLabel) - .getRegex(); -const reflinkSearch = edit('reflink|nolink(?!\\()', 'g') - .replace('reflink', reflink) - .replace('nolink', nolink) - .getRegex(); -/** - * Normal Inline Grammar - */ -const inlineNormal = { - _backpedal: noopTest, // only used for GFM url - anyPunctuation, - autolink, - blockSkip, - br, - code: inlineCode, - del: noopTest, - emStrongLDelim, - emStrongRDelimAst, - emStrongRDelimUnd, - escape: escape$1, - link, - nolink, - punctuation, - reflink, - reflinkSearch, - tag, - text: inlineText, - url: noopTest, -}; -/** - * Pedantic Inline Grammar - */ -const inlinePedantic = { - ...inlineNormal, - link: edit(/^!?\[(label)\]\((.*?)\)/) - .replace('label', _inlineLabel) - .getRegex(), - reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/) - .replace('label', _inlineLabel) - .getRegex(), -}; -/** - * GFM Inline Grammar - */ -const inlineGfm = { - ...inlineNormal, - emStrongRDelimAst: emStrongRDelimAstGfm, - emStrongLDelim: emStrongLDelimGfm, - url: edit(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/, 'i') - .replace('email', /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/) - .getRegex(), - _backpedal: /(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/, - del: /^(~~?)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/, - text: /^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\': '>', - '"': '"', - "'": ''', -}; -const getEscapeReplacement = (ch) => escapeReplacements[ch]; -function escape(html, encode) { - if (encode) { - if (other.escapeTest.test(html)) { - return html.replace(other.escapeReplace, getEscapeReplacement); - } - } - else { - if (other.escapeTestNoEncode.test(html)) { - return html.replace(other.escapeReplaceNoEncode, getEscapeReplacement); - } - } - return html; -} -function cleanUrl(href) { - try { - href = encodeURI(href).replace(other.percentDecode, '%'); - } - catch { - return null; - } - return href; -} -function splitCells(tableRow, count) { - // ensure that every cell-delimiting pipe has a space - // before it to distinguish it from an escaped pipe - const row = tableRow.replace(other.findPipe, (match, offset, str) => { - let escaped = false; - let curr = offset; - while (--curr >= 0 && str[curr] === '\\') - escaped = !escaped; - if (escaped) { - // odd number of slashes means | is escaped - // so we leave it alone - return '|'; - } - else { - // add space before unescaped | - return ' |'; - } - }), cells = row.split(other.splitPipe); - let i = 0; - // First/last cell in a row cannot be empty if it has no leading/trailing pipe - if (!cells[0].trim()) { - cells.shift(); - } - if (cells.length > 0 && !cells.at(-1)?.trim()) { - cells.pop(); - } - if (count) { - if (cells.length > count) { - cells.splice(count); - } - else { - while (cells.length < count) - cells.push(''); - } - } - for (; i < cells.length; i++) { - // leading or trailing whitespace is ignored per the gfm spec - cells[i] = cells[i].trim().replace(other.slashPipe, '|'); - } - return cells; -} -/** - * Remove trailing 'c's. Equivalent to str.replace(/c*$/, ''). - * /c*$/ is vulnerable to REDOS. - * - * @param str - * @param c - * @param invert Remove suffix of non-c chars instead. Default falsey. - */ -function rtrim(str, c, invert) { - const l = str.length; - if (l === 0) { - return ''; - } - // Length of suffix matching the invert condition. - let suffLen = 0; - // Step left until we fail to match the invert condition. - while (suffLen < l) { - const currChar = str.charAt(l - suffLen - 1); - if (currChar === c && true) { - suffLen++; - } - else { - break; - } - } - return str.slice(0, l - suffLen); -} -function findClosingBracket(str, b) { - if (str.indexOf(b[1]) === -1) { - return -1; - } - let level = 0; - for (let i = 0; i < str.length; i++) { - if (str[i] === '\\') { - i++; - } - else if (str[i] === b[0]) { - level++; - } - else if (str[i] === b[1]) { - level--; - if (level < 0) { - return i; - } - } - } - return -1; -} - -function outputLink(cap, link, raw, lexer, rules) { - const href = link.href; - const title = link.title || null; - const text = cap[1].replace(rules.other.outputLinkReplace, '$1'); - if (cap[0].charAt(0) !== '!') { - lexer.state.inLink = true; - const token = { - type: 'link', - raw, - href, - title, - text, - tokens: lexer.inlineTokens(text), - }; - lexer.state.inLink = false; - return token; - } - return { - type: 'image', - raw, - href, - title, - text, - }; -} -function indentCodeCompensation(raw, text, rules) { - const matchIndentToCode = raw.match(rules.other.indentCodeCompensation); - if (matchIndentToCode === null) { - return text; - } - const indentToCode = matchIndentToCode[1]; - return text - .split('\n') - .map(node => { - const matchIndentInNode = node.match(rules.other.beginningSpace); - if (matchIndentInNode === null) { - return node; - } - const [indentInNode] = matchIndentInNode; - if (indentInNode.length >= indentToCode.length) { - return node.slice(indentToCode.length); - } - return node; - }) - .join('\n'); -} -/** - * Tokenizer - */ -class _Tokenizer { - options; - rules; // set by the lexer - lexer; // set by the lexer - constructor(options) { - this.options = options || _defaults; - } - space(src) { - const cap = this.rules.block.newline.exec(src); - if (cap && cap[0].length > 0) { - return { - type: 'space', - raw: cap[0], - }; - } - } - code(src) { - const cap = this.rules.block.code.exec(src); - if (cap) { - const text = cap[0].replace(this.rules.other.codeRemoveIndent, ''); - return { - type: 'code', - raw: cap[0], - codeBlockStyle: 'indented', - text: !this.options.pedantic - ? rtrim(text, '\n') - : text, - }; - } - } - fences(src) { - const cap = this.rules.block.fences.exec(src); - if (cap) { - const raw = cap[0]; - const text = indentCodeCompensation(raw, cap[3] || '', this.rules); - return { - type: 'code', - raw, - lang: cap[2] ? cap[2].trim().replace(this.rules.inline.anyPunctuation, '$1') : cap[2], - text, - }; - } - } - heading(src) { - const cap = this.rules.block.heading.exec(src); - if (cap) { - let text = cap[2].trim(); - // remove trailing #s - if (this.rules.other.endingHash.test(text)) { - const trimmed = rtrim(text, '#'); - if (this.options.pedantic) { - text = trimmed.trim(); - } - else if (!trimmed || this.rules.other.endingSpaceChar.test(trimmed)) { - // CommonMark requires space before trailing #s - text = trimmed.trim(); - } - } - return { - type: 'heading', - raw: cap[0], - depth: cap[1].length, - text, - tokens: this.lexer.inline(text), - }; - } - } - hr(src) { - const cap = this.rules.block.hr.exec(src); - if (cap) { - return { - type: 'hr', - raw: rtrim(cap[0], '\n'), - }; - } - } - blockquote(src) { - const cap = this.rules.block.blockquote.exec(src); - if (cap) { - let lines = rtrim(cap[0], '\n').split('\n'); - let raw = ''; - let text = ''; - const tokens = []; - while (lines.length > 0) { - let inBlockquote = false; - const currentLines = []; - let i; - for (i = 0; i < lines.length; i++) { - // get lines up to a continuation - if (this.rules.other.blockquoteStart.test(lines[i])) { - currentLines.push(lines[i]); - inBlockquote = true; - } - else if (!inBlockquote) { - currentLines.push(lines[i]); - } - else { - break; - } - } - lines = lines.slice(i); - const currentRaw = currentLines.join('\n'); - const currentText = currentRaw - // precede setext continuation with 4 spaces so it isn't a setext - .replace(this.rules.other.blockquoteSetextReplace, '\n $1') - .replace(this.rules.other.blockquoteSetextReplace2, ''); - raw = raw ? `${raw}\n${currentRaw}` : currentRaw; - text = text ? `${text}\n${currentText}` : currentText; - // parse blockquote lines as top level tokens - // merge paragraphs if this is a continuation - const top = this.lexer.state.top; - this.lexer.state.top = true; - this.lexer.blockTokens(currentText, tokens, true); - this.lexer.state.top = top; - // if there is no continuation then we are done - if (lines.length === 0) { - break; - } - const lastToken = tokens.at(-1); - if (lastToken?.type === 'code') { - // blockquote continuation cannot be preceded by a code block - break; - } - else if (lastToken?.type === 'blockquote') { - // include continuation in nested blockquote - const oldToken = lastToken; - const newText = oldToken.raw + '\n' + lines.join('\n'); - const newToken = this.blockquote(newText); - tokens[tokens.length - 1] = newToken; - raw = raw.substring(0, raw.length - oldToken.raw.length) + newToken.raw; - text = text.substring(0, text.length - oldToken.text.length) + newToken.text; - break; - } - else if (lastToken?.type === 'list') { - // include continuation in nested list - const oldToken = lastToken; - const newText = oldToken.raw + '\n' + lines.join('\n'); - const newToken = this.list(newText); - tokens[tokens.length - 1] = newToken; - raw = raw.substring(0, raw.length - lastToken.raw.length) + newToken.raw; - text = text.substring(0, text.length - oldToken.raw.length) + newToken.raw; - lines = newText.substring(tokens.at(-1).raw.length).split('\n'); - continue; - } - } - return { - type: 'blockquote', - raw, - tokens, - text, - }; - } - } - list(src) { - let cap = this.rules.block.list.exec(src); - if (cap) { - let bull = cap[1].trim(); - const isordered = bull.length > 1; - const list = { - type: 'list', - raw: '', - ordered: isordered, - start: isordered ? +bull.slice(0, -1) : '', - loose: false, - items: [], - }; - bull = isordered ? `\\d{1,9}\\${bull.slice(-1)}` : `\\${bull}`; - if (this.options.pedantic) { - bull = isordered ? bull : '[*+-]'; - } - // Get next list item - const itemRegex = this.rules.other.listItemRegex(bull); - let endsWithBlankLine = false; - // Check if current bullet point can start a new List Item - while (src) { - let endEarly = false; - let raw = ''; - let itemContents = ''; - if (!(cap = itemRegex.exec(src))) { - break; - } - if (this.rules.block.hr.test(src)) { // End list if bullet was actually HR (possibly move into itemRegex?) - break; - } - raw = cap[0]; - src = src.substring(raw.length); - let line = cap[2].split('\n', 1)[0].replace(this.rules.other.listReplaceTabs, (t) => ' '.repeat(3 * t.length)); - let nextLine = src.split('\n', 1)[0]; - let blankLine = !line.trim(); - let indent = 0; - if (this.options.pedantic) { - indent = 2; - itemContents = line.trimStart(); - } - else if (blankLine) { - indent = cap[1].length + 1; - } - else { - indent = cap[2].search(this.rules.other.nonSpaceChar); // Find first non-space char - indent = indent > 4 ? 1 : indent; // Treat indented code blocks (> 4 spaces) as having only 1 indent - itemContents = line.slice(indent); - indent += cap[1].length; - } - if (blankLine && this.rules.other.blankLine.test(nextLine)) { // Items begin with at most one blank line - raw += nextLine + '\n'; - src = src.substring(nextLine.length + 1); - endEarly = true; - } - if (!endEarly) { - const nextBulletRegex = this.rules.other.nextBulletRegex(indent); - const hrRegex = this.rules.other.hrRegex(indent); - const fencesBeginRegex = this.rules.other.fencesBeginRegex(indent); - const headingBeginRegex = this.rules.other.headingBeginRegex(indent); - const htmlBeginRegex = this.rules.other.htmlBeginRegex(indent); - // Check if following lines should be included in List Item - while (src) { - const rawLine = src.split('\n', 1)[0]; - let nextLineWithoutTabs; - nextLine = rawLine; - // Re-align to follow commonmark nesting rules - if (this.options.pedantic) { - nextLine = nextLine.replace(this.rules.other.listReplaceNesting, ' '); - nextLineWithoutTabs = nextLine; - } - else { - nextLineWithoutTabs = nextLine.replace(this.rules.other.tabCharGlobal, ' '); - } - // End list item if found code fences - if (fencesBeginRegex.test(nextLine)) { - break; - } - // End list item if found start of new heading - if (headingBeginRegex.test(nextLine)) { - break; - } - // End list item if found start of html block - if (htmlBeginRegex.test(nextLine)) { - break; - } - // End list item if found start of new bullet - if (nextBulletRegex.test(nextLine)) { - break; - } - // Horizontal rule found - if (hrRegex.test(nextLine)) { - break; - } - if (nextLineWithoutTabs.search(this.rules.other.nonSpaceChar) >= indent || !nextLine.trim()) { // Dedent if possible - itemContents += '\n' + nextLineWithoutTabs.slice(indent); - } - else { - // not enough indentation - if (blankLine) { - break; - } - // paragraph continuation unless last line was a different block level element - if (line.replace(this.rules.other.tabCharGlobal, ' ').search(this.rules.other.nonSpaceChar) >= 4) { // indented code block - break; - } - if (fencesBeginRegex.test(line)) { - break; - } - if (headingBeginRegex.test(line)) { - break; - } - if (hrRegex.test(line)) { - break; - } - itemContents += '\n' + nextLine; - } - if (!blankLine && !nextLine.trim()) { // Check if current line is blank - blankLine = true; - } - raw += rawLine + '\n'; - src = src.substring(rawLine.length + 1); - line = nextLineWithoutTabs.slice(indent); - } - } - if (!list.loose) { - // If the previous item ended with a blank line, the list is loose - if (endsWithBlankLine) { - list.loose = true; - } - else if (this.rules.other.doubleBlankLine.test(raw)) { - endsWithBlankLine = true; - } - } - let istask = null; - let ischecked; - // Check for task list items - if (this.options.gfm) { - istask = this.rules.other.listIsTask.exec(itemContents); - if (istask) { - ischecked = istask[0] !== '[ ] '; - itemContents = itemContents.replace(this.rules.other.listReplaceTask, ''); - } - } - list.items.push({ - type: 'list_item', - raw, - task: !!istask, - checked: ischecked, - loose: false, - text: itemContents, - tokens: [], - }); - list.raw += raw; - } - // Do not consume newlines at end of final item. Alternatively, make itemRegex *start* with any newlines to simplify/speed up endsWithBlankLine logic - const lastItem = list.items.at(-1); - if (lastItem) { - lastItem.raw = lastItem.raw.trimEnd(); - lastItem.text = lastItem.text.trimEnd(); - } - else { - // not a list since there were no items - return; - } - list.raw = list.raw.trimEnd(); - // Item child tokens handled here at end because we needed to have the final item to trim it first - for (let i = 0; i < list.items.length; i++) { - this.lexer.state.top = false; - list.items[i].tokens = this.lexer.blockTokens(list.items[i].text, []); - if (!list.loose) { - // Check if list should be loose - const spacers = list.items[i].tokens.filter(t => t.type === 'space'); - const hasMultipleLineBreaks = spacers.length > 0 && spacers.some(t => this.rules.other.anyLine.test(t.raw)); - list.loose = hasMultipleLineBreaks; - } - } - // Set all items to loose if list is loose - if (list.loose) { - for (let i = 0; i < list.items.length; i++) { - list.items[i].loose = true; - } - } - return list; - } - } - html(src) { - const cap = this.rules.block.html.exec(src); - if (cap) { - const token = { - type: 'html', - block: true, - raw: cap[0], - pre: cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style', - text: cap[0], - }; - return token; - } - } - def(src) { - const cap = this.rules.block.def.exec(src); - if (cap) { - const tag = cap[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal, ' '); - const href = cap[2] ? cap[2].replace(this.rules.other.hrefBrackets, '$1').replace(this.rules.inline.anyPunctuation, '$1') : ''; - const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline.anyPunctuation, '$1') : cap[3]; - return { - type: 'def', - tag, - raw: cap[0], - href, - title, - }; - } - } - table(src) { - const cap = this.rules.block.table.exec(src); - if (!cap) { - return; - } - if (!this.rules.other.tableDelimiter.test(cap[2])) { - // delimiter row must have a pipe (|) or colon (:) otherwise it is a setext heading - return; - } - const headers = splitCells(cap[1]); - const aligns = cap[2].replace(this.rules.other.tableAlignChars, '').split('|'); - const rows = cap[3]?.trim() ? cap[3].replace(this.rules.other.tableRowBlankLine, '').split('\n') : []; - const item = { - type: 'table', - raw: cap[0], - header: [], - align: [], - rows: [], - }; - if (headers.length !== aligns.length) { - // header and align columns must be equal, rows can be different. - return; - } - for (const align of aligns) { - if (this.rules.other.tableAlignRight.test(align)) { - item.align.push('right'); - } - else if (this.rules.other.tableAlignCenter.test(align)) { - item.align.push('center'); - } - else if (this.rules.other.tableAlignLeft.test(align)) { - item.align.push('left'); - } - else { - item.align.push(null); - } - } - for (let i = 0; i < headers.length; i++) { - item.header.push({ - text: headers[i], - tokens: this.lexer.inline(headers[i]), - header: true, - align: item.align[i], - }); - } - for (const row of rows) { - item.rows.push(splitCells(row, item.header.length).map((cell, i) => { - return { - text: cell, - tokens: this.lexer.inline(cell), - header: false, - align: item.align[i], - }; - })); - } - return item; - } - lheading(src) { - const cap = this.rules.block.lheading.exec(src); - if (cap) { - return { - type: 'heading', - raw: cap[0], - depth: cap[2].charAt(0) === '=' ? 1 : 2, - text: cap[1], - tokens: this.lexer.inline(cap[1]), - }; - } - } - paragraph(src) { - const cap = this.rules.block.paragraph.exec(src); - if (cap) { - const text = cap[1].charAt(cap[1].length - 1) === '\n' - ? cap[1].slice(0, -1) - : cap[1]; - return { - type: 'paragraph', - raw: cap[0], - text, - tokens: this.lexer.inline(text), - }; - } - } - text(src) { - const cap = this.rules.block.text.exec(src); - if (cap) { - return { - type: 'text', - raw: cap[0], - text: cap[0], - tokens: this.lexer.inline(cap[0]), - }; - } - } - escape(src) { - const cap = this.rules.inline.escape.exec(src); - if (cap) { - return { - type: 'escape', - raw: cap[0], - text: cap[1], - }; - } - } - tag(src) { - const cap = this.rules.inline.tag.exec(src); - if (cap) { - if (!this.lexer.state.inLink && this.rules.other.startATag.test(cap[0])) { - this.lexer.state.inLink = true; - } - else if (this.lexer.state.inLink && this.rules.other.endATag.test(cap[0])) { - this.lexer.state.inLink = false; - } - if (!this.lexer.state.inRawBlock && this.rules.other.startPreScriptTag.test(cap[0])) { - this.lexer.state.inRawBlock = true; - } - else if (this.lexer.state.inRawBlock && this.rules.other.endPreScriptTag.test(cap[0])) { - this.lexer.state.inRawBlock = false; - } - return { - type: 'html', - raw: cap[0], - inLink: this.lexer.state.inLink, - inRawBlock: this.lexer.state.inRawBlock, - block: false, - text: cap[0], - }; - } - } - link(src) { - const cap = this.rules.inline.link.exec(src); - if (cap) { - const trimmedUrl = cap[2].trim(); - if (!this.options.pedantic && this.rules.other.startAngleBracket.test(trimmedUrl)) { - // commonmark requires matching angle brackets - if (!(this.rules.other.endAngleBracket.test(trimmedUrl))) { - return; - } - // ending angle bracket cannot be escaped - const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), '\\'); - if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) { - return; - } - } - else { - // find closing parenthesis - const lastParenIndex = findClosingBracket(cap[2], '()'); - if (lastParenIndex > -1) { - const start = cap[0].indexOf('!') === 0 ? 5 : 4; - const linkLen = start + cap[1].length + lastParenIndex; - cap[2] = cap[2].substring(0, lastParenIndex); - cap[0] = cap[0].substring(0, linkLen).trim(); - cap[3] = ''; - } - } - let href = cap[2]; - let title = ''; - if (this.options.pedantic) { - // split pedantic href and title - const link = this.rules.other.pedanticHrefTitle.exec(href); - if (link) { - href = link[1]; - title = link[3]; - } - } - else { - title = cap[3] ? cap[3].slice(1, -1) : ''; - } - href = href.trim(); - if (this.rules.other.startAngleBracket.test(href)) { - if (this.options.pedantic && !(this.rules.other.endAngleBracket.test(trimmedUrl))) { - // pedantic allows starting angle bracket without ending angle bracket - href = href.slice(1); - } - else { - href = href.slice(1, -1); - } - } - return outputLink(cap, { - href: href ? href.replace(this.rules.inline.anyPunctuation, '$1') : href, - title: title ? title.replace(this.rules.inline.anyPunctuation, '$1') : title, - }, cap[0], this.lexer, this.rules); - } - } - reflink(src, links) { - let cap; - if ((cap = this.rules.inline.reflink.exec(src)) - || (cap = this.rules.inline.nolink.exec(src))) { - const linkString = (cap[2] || cap[1]).replace(this.rules.other.multipleSpaceGlobal, ' '); - const link = links[linkString.toLowerCase()]; - if (!link) { - const text = cap[0].charAt(0); - return { - type: 'text', - raw: text, - text, - }; - } - return outputLink(cap, link, cap[0], this.lexer, this.rules); - } - } - emStrong(src, maskedSrc, prevChar = '') { - let match = this.rules.inline.emStrongLDelim.exec(src); - if (!match) - return; - // _ can't be between two alphanumerics. \p{L}\p{N} includes non-english alphabet/numbers as well - if (match[3] && prevChar.match(this.rules.other.unicodeAlphaNumeric)) - return; - const nextChar = match[1] || match[2] || ''; - if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) { - // unicode Regex counts emoji as 1 char; spread into array for proper count (used multiple times below) - const lLength = [...match[0]].length - 1; - let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0; - const endReg = match[0][0] === '*' ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd; - endReg.lastIndex = 0; - // Clip maskedSrc to same section of string as src (move to lexer?) - maskedSrc = maskedSrc.slice(-1 * src.length + lLength); - while ((match = endReg.exec(maskedSrc)) != null) { - rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6]; - if (!rDelim) - continue; // skip single * in __abc*abc__ - rLength = [...rDelim].length; - if (match[3] || match[4]) { // found another Left Delim - delimTotal += rLength; - continue; - } - else if (match[5] || match[6]) { // either Left or Right Delim - if (lLength % 3 && !((lLength + rLength) % 3)) { - midDelimTotal += rLength; - continue; // CommonMark Emphasis Rules 9-10 - } - } - delimTotal -= rLength; - if (delimTotal > 0) - continue; // Haven't found enough closing delimiters - // Remove extra characters. *a*** -> *a* - rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal); - // char length can be >1 for unicode characters; - const lastCharLength = [...match[0]][0].length; - const raw = src.slice(0, lLength + match.index + lastCharLength + rLength); - // Create `em` if smallest delimiter has odd char count. *a*** - if (Math.min(lLength, rLength) % 2) { - const text = raw.slice(1, -1); - return { - type: 'em', - raw, - text, - tokens: this.lexer.inlineTokens(text), - }; - } - // Create 'strong' if smallest delimiter has even char count. **a*** - const text = raw.slice(2, -2); - return { - type: 'strong', - raw, - text, - tokens: this.lexer.inlineTokens(text), - }; - } - } - } - codespan(src) { - const cap = this.rules.inline.code.exec(src); - if (cap) { - let text = cap[2].replace(this.rules.other.newLineCharGlobal, ' '); - const hasNonSpaceChars = this.rules.other.nonSpaceChar.test(text); - const hasSpaceCharsOnBothEnds = this.rules.other.startingSpaceChar.test(text) && this.rules.other.endingSpaceChar.test(text); - if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) { - text = text.substring(1, text.length - 1); - } - return { - type: 'codespan', - raw: cap[0], - text, - }; - } - } - br(src) { - const cap = this.rules.inline.br.exec(src); - if (cap) { - return { - type: 'br', - raw: cap[0], - }; - } - } - del(src) { - const cap = this.rules.inline.del.exec(src); - if (cap) { - return { - type: 'del', - raw: cap[0], - text: cap[2], - tokens: this.lexer.inlineTokens(cap[2]), - }; - } - } - autolink(src) { - const cap = this.rules.inline.autolink.exec(src); - if (cap) { - let text, href; - if (cap[2] === '@') { - text = cap[1]; - href = 'mailto:' + text; - } - else { - text = cap[1]; - href = text; - } - return { - type: 'link', - raw: cap[0], - text, - href, - tokens: [ - { - type: 'text', - raw: text, - text, - }, - ], - }; - } - } - url(src) { - let cap; - if (cap = this.rules.inline.url.exec(src)) { - let text, href; - if (cap[2] === '@') { - text = cap[0]; - href = 'mailto:' + text; - } - else { - // do extended autolink path validation - let prevCapZero; - do { - prevCapZero = cap[0]; - cap[0] = this.rules.inline._backpedal.exec(cap[0])?.[0] ?? ''; - } while (prevCapZero !== cap[0]); - text = cap[0]; - if (cap[1] === 'www.') { - href = 'http://' + cap[0]; - } - else { - href = cap[0]; - } - } - return { - type: 'link', - raw: cap[0], - text, - href, - tokens: [ - { - type: 'text', - raw: text, - text, - }, - ], - }; - } - } - inlineText(src) { - const cap = this.rules.inline.text.exec(src); - if (cap) { - const escaped = this.lexer.state.inRawBlock; - return { - type: 'text', - raw: cap[0], - text: cap[0], - escaped, - }; - } - } -} - -/** - * Block Lexer - */ -class _Lexer { - tokens; - options; - state; - tokenizer; - inlineQueue; - constructor(options) { - // TokenList cannot be created in one go - this.tokens = []; - this.tokens.links = Object.create(null); - this.options = options || _defaults; - this.options.tokenizer = this.options.tokenizer || new _Tokenizer(); - this.tokenizer = this.options.tokenizer; - this.tokenizer.options = this.options; - this.tokenizer.lexer = this; - this.inlineQueue = []; - this.state = { - inLink: false, - inRawBlock: false, - top: true, - }; - const rules = { - other, - block: block.normal, - inline: inline.normal, - }; - if (this.options.pedantic) { - rules.block = block.pedantic; - rules.inline = inline.pedantic; - } - else if (this.options.gfm) { - rules.block = block.gfm; - if (this.options.breaks) { - rules.inline = inline.breaks; - } - else { - rules.inline = inline.gfm; - } - } - this.tokenizer.rules = rules; - } - /** - * Expose Rules - */ - static get rules() { - return { - block, - inline, - }; - } - /** - * Static Lex Method - */ - static lex(src, options) { - const lexer = new _Lexer(options); - return lexer.lex(src); - } - /** - * Static Lex Inline Method - */ - static lexInline(src, options) { - const lexer = new _Lexer(options); - return lexer.inlineTokens(src); - } - /** - * Preprocessing - */ - lex(src) { - src = src.replace(other.carriageReturn, '\n'); - this.blockTokens(src, this.tokens); - for (let i = 0; i < this.inlineQueue.length; i++) { - const next = this.inlineQueue[i]; - this.inlineTokens(next.src, next.tokens); - } - this.inlineQueue = []; - return this.tokens; - } - blockTokens(src, tokens = [], lastParagraphClipped = false) { - if (this.options.pedantic) { - src = src.replace(other.tabCharGlobal, ' ').replace(other.spaceLine, ''); - } - while (src) { - let token; - if (this.options.extensions?.block?.some((extTokenizer) => { - if (token = extTokenizer.call({ lexer: this }, src, tokens)) { - src = src.substring(token.raw.length); - tokens.push(token); - return true; - } - return false; - })) { - continue; - } - // newline - if (token = this.tokenizer.space(src)) { - src = src.substring(token.raw.length); - const lastToken = tokens.at(-1); - if (token.raw.length === 1 && lastToken !== undefined) { - // if there's a single \n as a spacer, it's terminating the last line, - // so move it there so that we don't get unnecessary paragraph tags - lastToken.raw += '\n'; - } - else { - tokens.push(token); - } - continue; - } - // code - if (token = this.tokenizer.code(src)) { - src = src.substring(token.raw.length); - const lastToken = tokens.at(-1); - // An indented code block cannot interrupt a paragraph. - if (lastToken?.type === 'paragraph' || lastToken?.type === 'text') { - lastToken.raw += '\n' + token.raw; - lastToken.text += '\n' + token.text; - this.inlineQueue.at(-1).src = lastToken.text; - } - else { - tokens.push(token); - } - continue; - } - // fences - if (token = this.tokenizer.fences(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // heading - if (token = this.tokenizer.heading(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // hr - if (token = this.tokenizer.hr(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // blockquote - if (token = this.tokenizer.blockquote(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // list - if (token = this.tokenizer.list(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // html - if (token = this.tokenizer.html(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // def - if (token = this.tokenizer.def(src)) { - src = src.substring(token.raw.length); - const lastToken = tokens.at(-1); - if (lastToken?.type === 'paragraph' || lastToken?.type === 'text') { - lastToken.raw += '\n' + token.raw; - lastToken.text += '\n' + token.raw; - this.inlineQueue.at(-1).src = lastToken.text; - } - else if (!this.tokens.links[token.tag]) { - this.tokens.links[token.tag] = { - href: token.href, - title: token.title, - }; - } - continue; - } - // table (gfm) - if (token = this.tokenizer.table(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // lheading - if (token = this.tokenizer.lheading(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // top-level paragraph - // prevent paragraph consuming extensions by clipping 'src' to extension start - let cutSrc = src; - if (this.options.extensions?.startBlock) { - let startIndex = Infinity; - const tempSrc = src.slice(1); - let tempStart; - this.options.extensions.startBlock.forEach((getStartIndex) => { - tempStart = getStartIndex.call({ lexer: this }, tempSrc); - if (typeof tempStart === 'number' && tempStart >= 0) { - startIndex = Math.min(startIndex, tempStart); - } - }); - if (startIndex < Infinity && startIndex >= 0) { - cutSrc = src.substring(0, startIndex + 1); - } - } - if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) { - const lastToken = tokens.at(-1); - if (lastParagraphClipped && lastToken?.type === 'paragraph') { - lastToken.raw += '\n' + token.raw; - lastToken.text += '\n' + token.text; - this.inlineQueue.pop(); - this.inlineQueue.at(-1).src = lastToken.text; - } - else { - tokens.push(token); - } - lastParagraphClipped = cutSrc.length !== src.length; - src = src.substring(token.raw.length); - continue; - } - // text - if (token = this.tokenizer.text(src)) { - src = src.substring(token.raw.length); - const lastToken = tokens.at(-1); - if (lastToken?.type === 'text') { - lastToken.raw += '\n' + token.raw; - lastToken.text += '\n' + token.text; - this.inlineQueue.pop(); - this.inlineQueue.at(-1).src = lastToken.text; - } - else { - tokens.push(token); - } - continue; - } - if (src) { - const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0); - if (this.options.silent) { - console.error(errMsg); - break; - } - else { - throw new Error(errMsg); - } - } - } - this.state.top = true; - return tokens; - } - inline(src, tokens = []) { - this.inlineQueue.push({ src, tokens }); - return tokens; - } - /** - * Lexing/Compiling - */ - inlineTokens(src, tokens = []) { - // String with links masked to avoid interference with em and strong - let maskedSrc = src; - let match = null; - // Mask out reflinks - if (this.tokens.links) { - const links = Object.keys(this.tokens.links); - if (links.length > 0) { - while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) { - if (links.includes(match[0].slice(match[0].lastIndexOf('[') + 1, -1))) { - maskedSrc = maskedSrc.slice(0, match.index) - + '[' + 'a'.repeat(match[0].length - 2) + ']' - + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex); - } - } - } - } - // Mask out other blocks - while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) { - maskedSrc = maskedSrc.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex); - } - // Mask out escaped characters - while ((match = this.tokenizer.rules.inline.anyPunctuation.exec(maskedSrc)) != null) { - maskedSrc = maskedSrc.slice(0, match.index) + '++' + maskedSrc.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex); - } - let keepPrevChar = false; - let prevChar = ''; - while (src) { - if (!keepPrevChar) { - prevChar = ''; - } - keepPrevChar = false; - let token; - // extensions - if (this.options.extensions?.inline?.some((extTokenizer) => { - if (token = extTokenizer.call({ lexer: this }, src, tokens)) { - src = src.substring(token.raw.length); - tokens.push(token); - return true; - } - return false; - })) { - continue; - } - // escape - if (token = this.tokenizer.escape(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // tag - if (token = this.tokenizer.tag(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // link - if (token = this.tokenizer.link(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // reflink, nolink - if (token = this.tokenizer.reflink(src, this.tokens.links)) { - src = src.substring(token.raw.length); - const lastToken = tokens.at(-1); - if (token.type === 'text' && lastToken?.type === 'text') { - lastToken.raw += token.raw; - lastToken.text += token.text; - } - else { - tokens.push(token); - } - continue; - } - // em & strong - if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // code - if (token = this.tokenizer.codespan(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // br - if (token = this.tokenizer.br(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // del (gfm) - if (token = this.tokenizer.del(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // autolink - if (token = this.tokenizer.autolink(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // url (gfm) - if (!this.state.inLink && (token = this.tokenizer.url(src))) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // text - // prevent inlineText consuming extensions by clipping 'src' to extension start - let cutSrc = src; - if (this.options.extensions?.startInline) { - let startIndex = Infinity; - const tempSrc = src.slice(1); - let tempStart; - this.options.extensions.startInline.forEach((getStartIndex) => { - tempStart = getStartIndex.call({ lexer: this }, tempSrc); - if (typeof tempStart === 'number' && tempStart >= 0) { - startIndex = Math.min(startIndex, tempStart); - } - }); - if (startIndex < Infinity && startIndex >= 0) { - cutSrc = src.substring(0, startIndex + 1); - } - } - if (token = this.tokenizer.inlineText(cutSrc)) { - src = src.substring(token.raw.length); - if (token.raw.slice(-1) !== '_') { // Track prevChar before string of ____ started - prevChar = token.raw.slice(-1); - } - keepPrevChar = true; - const lastToken = tokens.at(-1); - if (lastToken?.type === 'text') { - lastToken.raw += token.raw; - lastToken.text += token.text; - } - else { - tokens.push(token); - } - continue; - } - if (src) { - const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0); - if (this.options.silent) { - console.error(errMsg); - break; - } - else { - throw new Error(errMsg); - } - } - } - return tokens; - } -} - -/** - * Renderer - */ -class _Renderer { - options; - parser; // set by the parser - constructor(options) { - this.options = options || _defaults; - } - space(token) { - return ''; - } - code({ text, lang, escaped }) { - const langString = (lang || '').match(other.notSpaceStart)?.[0]; - const code = text.replace(other.endingNewline, '') + '\n'; - if (!langString) { - return '
    '
    -                + (escaped ? code : escape(code, true))
    -                + '
    \n'; - } - return '
    '
    -            + (escaped ? code : escape(code, true))
    -            + '
    \n'; - } - blockquote({ tokens }) { - const body = this.parser.parse(tokens); - return `
    \n${body}
    \n`; - } - html({ text }) { - return text; - } - heading({ tokens, depth }) { - return `${this.parser.parseInline(tokens)}\n`; - } - hr(token) { - return '
    \n'; - } - list(token) { - const ordered = token.ordered; - const start = token.start; - let body = ''; - for (let j = 0; j < token.items.length; j++) { - const item = token.items[j]; - body += this.listitem(item); - } - const type = ordered ? 'ol' : 'ul'; - const startAttr = (ordered && start !== 1) ? (' start="' + start + '"') : ''; - return '<' + type + startAttr + '>\n' + body + '\n'; - } - listitem(item) { - let itemBody = ''; - if (item.task) { - const checkbox = this.checkbox({ checked: !!item.checked }); - if (item.loose) { - if (item.tokens[0]?.type === 'paragraph') { - item.tokens[0].text = checkbox + ' ' + item.tokens[0].text; - if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') { - item.tokens[0].tokens[0].text = checkbox + ' ' + escape(item.tokens[0].tokens[0].text); - item.tokens[0].tokens[0].escaped = true; - } - } - else { - item.tokens.unshift({ - type: 'text', - raw: checkbox + ' ', - text: checkbox + ' ', - escaped: true, - }); - } - } - else { - itemBody += checkbox + ' '; - } - } - itemBody += this.parser.parse(item.tokens, !!item.loose); - return `
  • ${itemBody}
  • \n`; - } - checkbox({ checked }) { - return ''; - } - paragraph({ tokens }) { - return `

    ${this.parser.parseInline(tokens)}

    \n`; - } - table(token) { - let header = ''; - // header - let cell = ''; - for (let j = 0; j < token.header.length; j++) { - cell += this.tablecell(token.header[j]); - } - header += this.tablerow({ text: cell }); - let body = ''; - for (let j = 0; j < token.rows.length; j++) { - const row = token.rows[j]; - cell = ''; - for (let k = 0; k < row.length; k++) { - cell += this.tablecell(row[k]); - } - body += this.tablerow({ text: cell }); - } - if (body) - body = `${body}`; - return '\n' - + '\n' - + header - + '\n' - + body - + '
    \n'; - } - tablerow({ text }) { - return `\n${text}\n`; - } - tablecell(token) { - const content = this.parser.parseInline(token.tokens); - const type = token.header ? 'th' : 'td'; - const tag = token.align - ? `<${type} align="${token.align}">` - : `<${type}>`; - return tag + content + `\n`; - } - /** - * span level renderer - */ - strong({ tokens }) { - return `${this.parser.parseInline(tokens)}`; - } - em({ tokens }) { - return `${this.parser.parseInline(tokens)}`; - } - codespan({ text }) { - return `${escape(text, true)}`; - } - br(token) { - return '
    '; - } - del({ tokens }) { - return `${this.parser.parseInline(tokens)}`; - } - link({ href, title, tokens }) { - const text = this.parser.parseInline(tokens); - const cleanHref = cleanUrl(href); - if (cleanHref === null) { - return text; - } - href = cleanHref; - let out = '
    '; - return out; - } - image({ href, title, text }) { - const cleanHref = cleanUrl(href); - if (cleanHref === null) { - return escape(text); - } - href = cleanHref; - let out = `${text} { - const tokens = genericToken[childTokens].flat(Infinity); - values = values.concat(this.walkTokens(tokens, callback)); - }); - } - else if (genericToken.tokens) { - values = values.concat(this.walkTokens(genericToken.tokens, callback)); - } - } - } - } - return values; - } - use(...args) { - const extensions = this.defaults.extensions || { renderers: {}, childTokens: {} }; - args.forEach((pack) => { - // copy options to new object - const opts = { ...pack }; - // set async to true if it was set to true before - opts.async = this.defaults.async || opts.async || false; - // ==-- Parse "addon" extensions --== // - if (pack.extensions) { - pack.extensions.forEach((ext) => { - if (!ext.name) { - throw new Error('extension name required'); - } - if ('renderer' in ext) { // Renderer extensions - const prevRenderer = extensions.renderers[ext.name]; - if (prevRenderer) { - // Replace extension with func to run new extension but fall back if false - extensions.renderers[ext.name] = function (...args) { - let ret = ext.renderer.apply(this, args); - if (ret === false) { - ret = prevRenderer.apply(this, args); - } - return ret; - }; - } - else { - extensions.renderers[ext.name] = ext.renderer; - } - } - if ('tokenizer' in ext) { // Tokenizer Extensions - if (!ext.level || (ext.level !== 'block' && ext.level !== 'inline')) { - throw new Error("extension level must be 'block' or 'inline'"); - } - const extLevel = extensions[ext.level]; - if (extLevel) { - extLevel.unshift(ext.tokenizer); - } - else { - extensions[ext.level] = [ext.tokenizer]; - } - if (ext.start) { // Function to check for start of token - if (ext.level === 'block') { - if (extensions.startBlock) { - extensions.startBlock.push(ext.start); - } - else { - extensions.startBlock = [ext.start]; - } - } - else if (ext.level === 'inline') { - if (extensions.startInline) { - extensions.startInline.push(ext.start); - } - else { - extensions.startInline = [ext.start]; - } - } - } - } - if ('childTokens' in ext && ext.childTokens) { // Child tokens to be visited by walkTokens - extensions.childTokens[ext.name] = ext.childTokens; - } - }); - opts.extensions = extensions; - } - // ==-- Parse "overwrite" extensions --== // - if (pack.renderer) { - const renderer = this.defaults.renderer || new _Renderer(this.defaults); - for (const prop in pack.renderer) { - if (!(prop in renderer)) { - throw new Error(`renderer '${prop}' does not exist`); - } - if (['options', 'parser'].includes(prop)) { - // ignore options property - continue; - } - const rendererProp = prop; - const rendererFunc = pack.renderer[rendererProp]; - const prevRenderer = renderer[rendererProp]; - // Replace renderer with func to run extension, but fall back if false - renderer[rendererProp] = (...args) => { - let ret = rendererFunc.apply(renderer, args); - if (ret === false) { - ret = prevRenderer.apply(renderer, args); - } - return ret || ''; - }; - } - opts.renderer = renderer; - } - if (pack.tokenizer) { - const tokenizer = this.defaults.tokenizer || new _Tokenizer(this.defaults); - for (const prop in pack.tokenizer) { - if (!(prop in tokenizer)) { - throw new Error(`tokenizer '${prop}' does not exist`); - } - if (['options', 'rules', 'lexer'].includes(prop)) { - // ignore options, rules, and lexer properties - continue; - } - const tokenizerProp = prop; - const tokenizerFunc = pack.tokenizer[tokenizerProp]; - const prevTokenizer = tokenizer[tokenizerProp]; - // Replace tokenizer with func to run extension, but fall back if false - // @ts-expect-error cannot type tokenizer function dynamically - tokenizer[tokenizerProp] = (...args) => { - let ret = tokenizerFunc.apply(tokenizer, args); - if (ret === false) { - ret = prevTokenizer.apply(tokenizer, args); - } - return ret; - }; - } - opts.tokenizer = tokenizer; - } - // ==-- Parse Hooks extensions --== // - if (pack.hooks) { - const hooks = this.defaults.hooks || new _Hooks(); - for (const prop in pack.hooks) { - if (!(prop in hooks)) { - throw new Error(`hook '${prop}' does not exist`); - } - if (['options', 'block'].includes(prop)) { - // ignore options and block properties - continue; - } - const hooksProp = prop; - const hooksFunc = pack.hooks[hooksProp]; - const prevHook = hooks[hooksProp]; - if (_Hooks.passThroughHooks.has(prop)) { - // @ts-expect-error cannot type hook function dynamically - hooks[hooksProp] = (arg) => { - if (this.defaults.async) { - return Promise.resolve(hooksFunc.call(hooks, arg)).then(ret => { - return prevHook.call(hooks, ret); - }); - } - const ret = hooksFunc.call(hooks, arg); - return prevHook.call(hooks, ret); - }; - } - else { - // @ts-expect-error cannot type hook function dynamically - hooks[hooksProp] = (...args) => { - let ret = hooksFunc.apply(hooks, args); - if (ret === false) { - ret = prevHook.apply(hooks, args); - } - return ret; - }; - } - } - opts.hooks = hooks; - } - // ==-- Parse WalkTokens extensions --== // - if (pack.walkTokens) { - const walkTokens = this.defaults.walkTokens; - const packWalktokens = pack.walkTokens; - opts.walkTokens = function (token) { - let values = []; - values.push(packWalktokens.call(this, token)); - if (walkTokens) { - values = values.concat(walkTokens.call(this, token)); - } - return values; - }; - } - this.defaults = { ...this.defaults, ...opts }; - }); - return this; - } - setOptions(opt) { - this.defaults = { ...this.defaults, ...opt }; - return this; - } - lexer(src, options) { - return _Lexer.lex(src, options ?? this.defaults); - } - parser(tokens, options) { - return _Parser.parse(tokens, options ?? this.defaults); - } - parseMarkdown(blockType) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const parse = (src, options) => { - const origOpt = { ...options }; - const opt = { ...this.defaults, ...origOpt }; - const throwError = this.onError(!!opt.silent, !!opt.async); - // throw error if an extension set async to true but parse was called with async: false - if (this.defaults.async === true && origOpt.async === false) { - return throwError(new Error('marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.')); - } - // throw error in case of non string input - if (typeof src === 'undefined' || src === null) { - return throwError(new Error('marked(): input parameter is undefined or null')); - } - if (typeof src !== 'string') { - return throwError(new Error('marked(): input parameter is of type ' - + Object.prototype.toString.call(src) + ', string expected')); - } - if (opt.hooks) { - opt.hooks.options = opt; - opt.hooks.block = blockType; - } - const lexer = opt.hooks ? opt.hooks.provideLexer() : (blockType ? _Lexer.lex : _Lexer.lexInline); - const parser = opt.hooks ? opt.hooks.provideParser() : (blockType ? _Parser.parse : _Parser.parseInline); - if (opt.async) { - return Promise.resolve(opt.hooks ? opt.hooks.preprocess(src) : src) - .then(src => lexer(src, opt)) - .then(tokens => opt.hooks ? opt.hooks.processAllTokens(tokens) : tokens) - .then(tokens => opt.walkTokens ? Promise.all(this.walkTokens(tokens, opt.walkTokens)).then(() => tokens) : tokens) - .then(tokens => parser(tokens, opt)) - .then(html => opt.hooks ? opt.hooks.postprocess(html) : html) - .catch(throwError); - } - try { - if (opt.hooks) { - src = opt.hooks.preprocess(src); - } - let tokens = lexer(src, opt); - if (opt.hooks) { - tokens = opt.hooks.processAllTokens(tokens); - } - if (opt.walkTokens) { - this.walkTokens(tokens, opt.walkTokens); - } - let html = parser(tokens, opt); - if (opt.hooks) { - html = opt.hooks.postprocess(html); - } - return html; - } - catch (e) { - return throwError(e); - } - }; - return parse; - } - onError(silent, async) { - return (e) => { - e.message += '\nPlease report this to https://github.com/markedjs/marked.'; - if (silent) { - const msg = '

    An error occurred:

    '
    -                    + escape(e.message + '', true)
    -                    + '
    '; - if (async) { - return Promise.resolve(msg); - } - return msg; - } - if (async) { - return Promise.reject(e); - } - throw e; - }; - } -} - -const markedInstance = new Marked(); -function marked(src, opt) { - return markedInstance.parse(src, opt); -} -/** - * Sets the default options. - * - * @param options Hash of options - */ -marked.options = - marked.setOptions = function (options) { - markedInstance.setOptions(options); - marked.defaults = markedInstance.defaults; - changeDefaults(marked.defaults); - return marked; - }; -/** - * Gets the original marked default options. - */ -marked.getDefaults = _getDefaults; -marked.defaults = _defaults; -/** - * Use Extension - */ -marked.use = function (...args) { - markedInstance.use(...args); - marked.defaults = markedInstance.defaults; - changeDefaults(marked.defaults); - return marked; -}; -/** - * Run callback for every token - */ -marked.walkTokens = function (tokens, callback) { - return markedInstance.walkTokens(tokens, callback); -}; -/** - * Compiles markdown to HTML without enclosing `p` tag. - * - * @param src String of markdown source to be compiled - * @param options Hash of options - * @return String of compiled HTML - */ -marked.parseInline = markedInstance.parseInline; -/** - * Expose - */ -marked.Parser = _Parser; -marked.parser = _Parser.parse; -marked.Renderer = _Renderer; -marked.TextRenderer = _TextRenderer; -marked.Lexer = _Lexer; -marked.lexer = _Lexer.lex; -marked.Tokenizer = _Tokenizer; -marked.Hooks = _Hooks; -marked.parse = marked; -const options = marked.options; -const setOptions = marked.setOptions; -const use = marked.use; -const walkTokens = marked.walkTokens; -const parseInline = marked.parseInline; -const parse = marked; -const parser = _Parser.parse; -const lexer = _Lexer.lex; - -export { _Hooks as Hooks, _Lexer as Lexer, Marked, _Parser as Parser, _Renderer as Renderer, _TextRenderer as TextRenderer, _Tokenizer as Tokenizer, _defaults as defaults, _getDefaults as getDefaults, lexer, marked, options, parse, parseInline, parser, setOptions, use, walkTokens }; -//# sourceMappingURL=marked.esm.js.map diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/pdf_viewer/viewer.html b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/pdf_viewer/viewer.html deleted file mode 100644 index 32ac36286a7..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/pdf_viewer/viewer.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - PDF viewer - - - - - - -
    -
    -
    - - - - diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/pdf_viewer/viewer.mjs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/pdf_viewer/viewer.mjs deleted file mode 100644 index 8a4a6b76f5e..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/pdf_viewer/viewer.mjs +++ /dev/null @@ -1,62 +0,0 @@ -import { GlobalWorkerOptions } from '../pdfjs-dist/dist/build/pdf.min.mjs'; -import { EventBus, PDFLinkService, PDFFindController, PDFViewer } from '../pdfjs-dist/dist/web/pdf_viewer.mjs'; - -GlobalWorkerOptions.workerSrc = '../pdfjs-dist/dist/build/pdf.worker.min.mjs'; - -// Extract the file path from the URL query string. -const url = new URL(window.location); -const fileUrl = url.searchParams.get('file'); -if (!fileUrl) { - throw new Error('File not specified in the URL query string'); -} - -const container = document.getElementById('viewerContainer'); -const eventBus = new EventBus(); - -// Enable hyperlinks within PDF files. -const pdfLinkService = new PDFLinkService({ - eventBus, -}); - -// Enable the find controller. -const pdfFindController = new PDFFindController({ - eventBus, - linkService: pdfLinkService, -}); - -// Create the PDF viewer. -const pdfViewer = new PDFViewer({ - container, - eventBus, - linkService: pdfLinkService, - findController: pdfFindController, -}); -pdfLinkService.setViewer(pdfViewer); - -// Allow navigation to a citation from the URL hash. -eventBus.on('pagesinit', function () { - pdfLinkService.setHash(window.location.hash.substring(1)); -}); - -// Define how the "search" query parameter is handled. -eventBus.on('findfromurlhash', function(evt) { - eventBus.dispatch('find', { - source: evt.source, - type: '', - query: evt.query, - caseSensitive: false, - entireWord: false, - highlightAll: false, - findPrevious: false, - matchDiacritics: true, - }); -}); - -// Load and initialize the document. -const pdfDocument = await pdfjsLib.getDocument({ - url: fileUrl, - enableXfa: true, -}).promise; - -pdfViewer.setDocument(pdfDocument); -pdfLinkService.setDocument(pdfDocument, null); diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/pdfjs-dist/README.md b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/pdfjs-dist/README.md deleted file mode 100644 index 8e77fba7d43..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/pdfjs-dist/README.md +++ /dev/null @@ -1,10 +0,0 @@ -pdfjs-dist version 4.10.38 -https://github.com/mozilla/pdf.js -License: Apache-2.0 - -To update, replace the following files with updated versions from https://www.npmjs.com/package/pdfjs-dist: -* `build/pdf.min.mjs` -* `build/pdf.worker.min.mjs` -* `web/pdf_viewer.css` -* `web/pdf_viewer.mjs` -* `web/images/loading-icon.gif` diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/pdfjs-dist/dist/build/pdf.min.mjs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/pdfjs-dist/dist/build/pdf.min.mjs deleted file mode 100644 index d7cfa914562..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/pdfjs-dist/dist/build/pdf.min.mjs +++ /dev/null @@ -1,21 +0,0 @@ -/** - * @licstart The following is the entire license notice for the - * JavaScript code in this page - * - * Copyright 2024 Mozilla Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * @licend The above is the entire license notice for the - * JavaScript code in this page - */var t={d:(e,i)=>{for(var s in i)t.o(i,s)&&!t.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:i[s]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e)},__webpack_exports__ = globalThis.pdfjsLib = {};t.d(__webpack_exports__,{AbortException:()=>AbortException,AnnotationEditorLayer:()=>AnnotationEditorLayer,AnnotationEditorParamsType:()=>m,AnnotationEditorType:()=>g,AnnotationEditorUIManager:()=>AnnotationEditorUIManager,AnnotationLayer:()=>AnnotationLayer,AnnotationMode:()=>p,ColorPicker:()=>ColorPicker,DOMSVGFactory:()=>DOMSVGFactory,DrawLayer:()=>DrawLayer,FeatureTest:()=>util_FeatureTest,GlobalWorkerOptions:()=>GlobalWorkerOptions,ImageKind:()=>_,InvalidPDFException:()=>InvalidPDFException,MissingPDFException:()=>MissingPDFException,OPS:()=>X,OutputScale:()=>OutputScale,PDFDataRangeTransport:()=>PDFDataRangeTransport,PDFDateString:()=>PDFDateString,PDFWorker:()=>PDFWorker,PasswordResponses:()=>K,PermissionFlag:()=>f,PixelsPerInch:()=>PixelsPerInch,RenderingCancelledException:()=>RenderingCancelledException,TextLayer:()=>TextLayer,TouchManager:()=>TouchManager,UnexpectedResponseException:()=>UnexpectedResponseException,Util:()=>Util,VerbosityLevel:()=>q,XfaLayer:()=>XfaLayer,build:()=>Nt,createValidAbsoluteUrl:()=>createValidAbsoluteUrl,fetchData:()=>fetchData,getDocument:()=>getDocument,getFilenameFromUrl:()=>getFilenameFromUrl,getPdfFilenameFromUrl:()=>getPdfFilenameFromUrl,getXfaPageViewport:()=>getXfaPageViewport,isDataScheme:()=>isDataScheme,isPdfFile:()=>isPdfFile,noContextMenu:()=>noContextMenu,normalizeUnicode:()=>normalizeUnicode,setLayerDimensions:()=>setLayerDimensions,shadow:()=>shadow,stopEvent:()=>stopEvent,version:()=>Ot});const e=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),i=[1,0,0,1,0,0],s=[.001,0,0,.001,0,0],n=1.35,a=1,r=2,o=4,l=16,h=32,d=64,c=128,u=256,p={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},g={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},m={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,HIGHLIGHT_COLOR:31,HIGHLIGHT_DEFAULT_COLOR:32,HIGHLIGHT_THICKNESS:33,HIGHLIGHT_FREE:34,HIGHLIGHT_SHOW_ALL:35,DRAW_STEP:41},f={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},b=0,A=1,w=2,v=3,y=3,x=4,_={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},E=1,S=2,C=3,T=4,M=5,P=6,D=7,k=8,R=9,I=10,F=11,L=12,O=13,N=14,B=15,H=16,z=17,U=20,G=1,$=2,V=3,j=4,W=5,q={ERRORS:0,WARNINGS:1,INFOS:5},X={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91,setStrokeTransparent:92,setFillTransparent:93},K={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let Y=q.WARNINGS;function setVerbosityLevel(t){Number.isInteger(t)&&(Y=t)}function getVerbosityLevel(){return Y}function info(t){Y>=q.INFOS&&console.log(`Info: ${t}`)}function warn(t){Y>=q.WARNINGS&&console.log(`Warning: ${t}`)}function unreachable(t){throw new Error(t)}function assert(t,e){t||unreachable(e)}function createValidAbsoluteUrl(t,e=null,i=null){if(!t)return null;try{if(i&&"string"==typeof t){if(i.addDefaultProtocol&&t.startsWith("www.")){const e=t.match(/\./g);e?.length>=2&&(t=`http://${t}`)}if(i.tryConvertEncoding)try{t=function stringToUTF8String(t){return decodeURIComponent(escape(t))}(t)}catch{}}const s=e?new URL(t,e):new URL(t);if(function _isValidProtocol(t){switch(t?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(s))return s}catch{}return null}function shadow(t,e,i,s=!1){Object.defineProperty(t,e,{value:i,enumerable:!s,configurable:!0,writable:!1});return i}const Q=function BaseExceptionClosure(){function BaseException(t,e){this.message=t;this.name=e}BaseException.prototype=new Error;BaseException.constructor=BaseException;return BaseException}();class PasswordException extends Q{constructor(t,e){super(t,"PasswordException");this.code=e}}class UnknownErrorException extends Q{constructor(t,e){super(t,"UnknownErrorException");this.details=e}}class InvalidPDFException extends Q{constructor(t){super(t,"InvalidPDFException")}}class MissingPDFException extends Q{constructor(t){super(t,"MissingPDFException")}}class UnexpectedResponseException extends Q{constructor(t,e){super(t,"UnexpectedResponseException");this.status=e}}class FormatError extends Q{constructor(t){super(t,"FormatError")}}class AbortException extends Q{constructor(t){super(t,"AbortException")}}function bytesToString(t){"object"==typeof t&&void 0!==t?.length||unreachable("Invalid argument for bytesToString");const e=t.length,i=8192;if(et.toString(16).padStart(2,"0")));class Util{static makeHexColor(t,e,i){return`#${J[t]}${J[e]}${J[i]}`}static scaleMinMax(t,e){let i;if(t[0]){if(t[0]<0){i=e[0];e[0]=e[2];e[2]=i}e[0]*=t[0];e[2]*=t[0];if(t[3]<0){i=e[1];e[1]=e[3];e[3]=i}e[1]*=t[3];e[3]*=t[3]}else{i=e[0];e[0]=e[1];e[1]=i;i=e[2];e[2]=e[3];e[3]=i;if(t[1]<0){i=e[1];e[1]=e[3];e[3]=i}e[1]*=t[1];e[3]*=t[1];if(t[2]<0){i=e[0];e[0]=e[2];e[2]=i}e[0]*=t[2];e[2]*=t[2]}e[0]+=t[4];e[1]+=t[5];e[2]+=t[4];e[3]+=t[5]}static transform(t,e){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],t[0]*e[4]+t[2]*e[5]+t[4],t[1]*e[4]+t[3]*e[5]+t[5]]}static applyTransform(t,e){return[t[0]*e[0]+t[1]*e[2]+e[4],t[0]*e[1]+t[1]*e[3]+e[5]]}static applyInverseTransform(t,e){const i=e[0]*e[3]-e[1]*e[2];return[(t[0]*e[3]-t[1]*e[2]+e[2]*e[5]-e[4]*e[3])/i,(-t[0]*e[1]+t[1]*e[0]+e[4]*e[1]-e[5]*e[0])/i]}static getAxialAlignedBoundingBox(t,e){const i=this.applyTransform(t,e),s=this.applyTransform(t.slice(2,4),e),n=this.applyTransform([t[0],t[3]],e),a=this.applyTransform([t[2],t[1]],e);return[Math.min(i[0],s[0],n[0],a[0]),Math.min(i[1],s[1],n[1],a[1]),Math.max(i[0],s[0],n[0],a[0]),Math.max(i[1],s[1],n[1],a[1])]}static inverseTransform(t){const e=t[0]*t[3]-t[1]*t[2];return[t[3]/e,-t[1]/e,-t[2]/e,t[0]/e,(t[2]*t[5]-t[4]*t[3])/e,(t[4]*t[1]-t[5]*t[0])/e]}static singularValueDecompose2dScale(t){const e=[t[0],t[2],t[1],t[3]],i=t[0]*e[0]+t[1]*e[2],s=t[0]*e[1]+t[1]*e[3],n=t[2]*e[0]+t[3]*e[2],a=t[2]*e[1]+t[3]*e[3],r=(i+a)/2,o=Math.sqrt((i+a)**2-4*(i*a-n*s))/2,l=r+o||1,h=r-o||1;return[Math.sqrt(l),Math.sqrt(h)]}static normalizeRect(t){const e=t.slice(0);if(t[0]>t[2]){e[0]=t[2];e[2]=t[0]}if(t[1]>t[3]){e[1]=t[3];e[3]=t[1]}return e}static intersect(t,e){const i=Math.max(Math.min(t[0],t[2]),Math.min(e[0],e[2])),s=Math.min(Math.max(t[0],t[2]),Math.max(e[0],e[2]));if(i>s)return null;const n=Math.max(Math.min(t[1],t[3]),Math.min(e[1],e[3])),a=Math.min(Math.max(t[1],t[3]),Math.max(e[1],e[3]));return n>a?null:[i,n,s,a]}static#t(t,e,i,s,n,a,r,o,l,h){if(l<=0||l>=1)return;const d=1-l,c=l*l,u=c*l,p=d*(d*(d*t+3*l*e)+3*c*i)+u*s,g=d*(d*(d*n+3*l*a)+3*c*r)+u*o;h[0]=Math.min(h[0],p);h[1]=Math.min(h[1],g);h[2]=Math.max(h[2],p);h[3]=Math.max(h[3],g)}static#e(t,e,i,s,n,a,r,o,l,h,d,c){if(Math.abs(l)<1e-12){Math.abs(h)>=1e-12&&this.#t(t,e,i,s,n,a,r,o,-d/h,c);return}const u=h**2-4*d*l;if(u<0)return;const p=Math.sqrt(u),g=2*l;this.#t(t,e,i,s,n,a,r,o,(-h+p)/g,c);this.#t(t,e,i,s,n,a,r,o,(-h-p)/g,c)}static bezierBoundingBox(t,e,i,s,n,a,r,o,l){if(l){l[0]=Math.min(l[0],t,r);l[1]=Math.min(l[1],e,o);l[2]=Math.max(l[2],t,r);l[3]=Math.max(l[3],e,o)}else l=[Math.min(t,r),Math.min(e,o),Math.max(t,r),Math.max(e,o)];this.#e(t,i,n,r,e,s,a,o,3*(3*(i-n)-t+r),6*(t-2*i+n),3*(i-t),l);this.#e(t,i,n,r,e,s,a,o,3*(3*(s-a)-e+o),6*(e-2*s+a),3*(s-e),l);return l}}let Z=null,tt=null;function normalizeUnicode(t){if(!Z){Z=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu;tt=new Map([["ſt","ſt"]])}return t.replaceAll(Z,((t,e,i)=>e?e.normalize("NFKC"):tt.get(i)))}const et="pdfjs_internal_id_";"function"!=typeof Promise.try&&(Promise.try=function(t,...e){return new Promise((i=>{i(t(...e))}))});const it="http://www.w3.org/2000/svg";class PixelsPerInch{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function fetchData(t,e="text"){if(isValidFetchUrl(t,document.baseURI)){const i=await fetch(t);if(!i.ok)throw new Error(i.statusText);switch(e){case"arraybuffer":return i.arrayBuffer();case"blob":return i.blob();case"json":return i.json()}return i.text()}return new Promise(((i,s)=>{const n=new XMLHttpRequest;n.open("GET",t,!0);n.responseType=e;n.onreadystatechange=()=>{if(n.readyState===XMLHttpRequest.DONE)if(200!==n.status&&0!==n.status)s(new Error(n.statusText));else{switch(e){case"arraybuffer":case"blob":case"json":i(n.response);return}i(n.responseText)}};n.send(null)}))}class PageViewport{constructor({viewBox:t,userUnit:e,scale:i,rotation:s,offsetX:n=0,offsetY:a=0,dontFlip:r=!1}){this.viewBox=t;this.userUnit=e;this.scale=i;this.rotation=s;this.offsetX=n;this.offsetY=a;i*=e;const o=(t[2]+t[0])/2,l=(t[3]+t[1])/2;let h,d,c,u,p,g,m,f;(s%=360)<0&&(s+=360);switch(s){case 180:h=-1;d=0;c=0;u=1;break;case 90:h=0;d=1;c=1;u=0;break;case 270:h=0;d=-1;c=-1;u=0;break;case 0:h=1;d=0;c=0;u=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}if(r){c=-c;u=-u}if(0===h){p=Math.abs(l-t[1])*i+n;g=Math.abs(o-t[0])*i+a;m=(t[3]-t[1])*i;f=(t[2]-t[0])*i}else{p=Math.abs(o-t[0])*i+n;g=Math.abs(l-t[1])*i+a;m=(t[2]-t[0])*i;f=(t[3]-t[1])*i}this.transform=[h*i,d*i,c*i,u*i,p-h*i*o-c*i*l,g-d*i*o-u*i*l];this.width=m;this.height=f}get rawDims(){const{userUnit:t,viewBox:e}=this,i=e.map((e=>e*t));return shadow(this,"rawDims",{pageWidth:i[2]-i[0],pageHeight:i[3]-i[1],pageX:i[0],pageY:i[1]})}clone({scale:t=this.scale,rotation:e=this.rotation,offsetX:i=this.offsetX,offsetY:s=this.offsetY,dontFlip:n=!1}={}){return new PageViewport({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:t,rotation:e,offsetX:i,offsetY:s,dontFlip:n})}convertToViewportPoint(t,e){return Util.applyTransform([t,e],this.transform)}convertToViewportRectangle(t){const e=Util.applyTransform([t[0],t[1]],this.transform),i=Util.applyTransform([t[2],t[3]],this.transform);return[e[0],e[1],i[0],i[1]]}convertToPdfPoint(t,e){return Util.applyInverseTransform([t,e],this.transform)}}class RenderingCancelledException extends Q{constructor(t,e=0){super(t,"RenderingCancelledException");this.extraDelay=e}}function isDataScheme(t){const e=t.length;let i=0;for(;i=1&&s<=12?s-1:0;let n=parseInt(e[3],10);n=n>=1&&n<=31?n:1;let a=parseInt(e[4],10);a=a>=0&&a<=23?a:0;let r=parseInt(e[5],10);r=r>=0&&r<=59?r:0;let o=parseInt(e[6],10);o=o>=0&&o<=59?o:0;const l=e[7]||"Z";let h=parseInt(e[8],10);h=h>=0&&h<=23?h:0;let d=parseInt(e[9],10)||0;d=d>=0&&d<=59?d:0;if("-"===l){a+=h;r+=d}else if("+"===l){a-=h;r-=d}return new Date(Date.UTC(i,s,n,a,r,o))}}function getXfaPageViewport(t,{scale:e=1,rotation:i=0}){const{width:s,height:n}=t.attributes.style,a=[0,0,parseInt(s),parseInt(n)];return new PageViewport({viewBox:a,userUnit:1,scale:e,rotation:i})}function getRGB(t){if(t.startsWith("#")){const e=parseInt(t.slice(1),16);return[(16711680&e)>>16,(65280&e)>>8,255&e]}if(t.startsWith("rgb("))return t.slice(4,-1).split(",").map((t=>parseInt(t)));if(t.startsWith("rgba("))return t.slice(5,-1).split(",").map((t=>parseInt(t))).slice(0,3);warn(`Not a valid color format: "${t}"`);return[0,0,0]}function getCurrentTransform(t){const{a:e,b:i,c:s,d:n,e:a,f:r}=t.getTransform();return[e,i,s,n,a,r]}function getCurrentTransformInverse(t){const{a:e,b:i,c:s,d:n,e:a,f:r}=t.getTransform().invertSelf();return[e,i,s,n,a,r]}function setLayerDimensions(t,e,i=!1,s=!0){if(e instanceof PageViewport){const{pageWidth:s,pageHeight:n}=e.rawDims,{style:a}=t,r=util_FeatureTest.isCSSRoundSupported,o=`var(--scale-factor) * ${s}px`,l=`var(--scale-factor) * ${n}px`,h=r?`round(down, ${o}, var(--scale-round-x, 1px))`:`calc(${o})`,d=r?`round(down, ${l}, var(--scale-round-y, 1px))`:`calc(${l})`;if(i&&e.rotation%180!=0){a.width=d;a.height=h}else{a.width=h;a.height=d}}s&&t.setAttribute("data-main-rotation",e.rotation)}class OutputScale{constructor(){const t=window.devicePixelRatio||1;this.sx=t;this.sy=t}get scaled(){return 1!==this.sx||1!==this.sy}get symmetric(){return this.sx===this.sy}}class EditorToolbar{#s=null;#n=null;#a;#r=null;#o=null;static#l=null;constructor(t){this.#a=t;EditorToolbar.#l||=Object.freeze({freetext:"pdfjs-editor-remove-freetext-button",highlight:"pdfjs-editor-remove-highlight-button",ink:"pdfjs-editor-remove-ink-button",stamp:"pdfjs-editor-remove-stamp-button"})}render(){const t=this.#s=document.createElement("div");t.classList.add("editToolbar","hidden");t.setAttribute("role","toolbar");const e=this.#a._uiManager._signal;t.addEventListener("contextmenu",noContextMenu,{signal:e});t.addEventListener("pointerdown",EditorToolbar.#h,{signal:e});const i=this.#r=document.createElement("div");i.className="buttons";t.append(i);const s=this.#a.toolbarPosition;if(s){const{style:e}=t,i="ltr"===this.#a._uiManager.direction?1-s[0]:s[0];e.insetInlineEnd=100*i+"%";e.top=`calc(${100*s[1]}% + var(--editor-toolbar-vert-offset))`}this.#d();return t}get div(){return this.#s}static#h(t){t.stopPropagation()}#c(t){this.#a._focusEventsAllowed=!1;stopEvent(t)}#u(t){this.#a._focusEventsAllowed=!0;stopEvent(t)}#p(t){const e=this.#a._uiManager._signal;t.addEventListener("focusin",this.#c.bind(this),{capture:!0,signal:e});t.addEventListener("focusout",this.#u.bind(this),{capture:!0,signal:e});t.addEventListener("contextmenu",noContextMenu,{signal:e})}hide(){this.#s.classList.add("hidden");this.#n?.hideDropdown()}show(){this.#s.classList.remove("hidden");this.#o?.shown()}#d(){const{editorType:t,_uiManager:e}=this.#a,i=document.createElement("button");i.className="delete";i.tabIndex=0;i.setAttribute("data-l10n-id",EditorToolbar.#l[t]);this.#p(i);i.addEventListener("click",(t=>{e.delete()}),{signal:e._signal});this.#r.append(i)}get#g(){const t=document.createElement("div");t.className="divider";return t}async addAltText(t){const e=await t.render();this.#p(e);this.#r.prepend(e,this.#g);this.#o=t}addColorPicker(t){this.#n=t;const e=t.renderButton();this.#p(e);this.#r.prepend(e,this.#g)}remove(){this.#s.remove();this.#n?.destroy();this.#n=null}}class HighlightToolbar{#r=null;#s=null;#m;constructor(t){this.#m=t}#f(){const t=this.#s=document.createElement("div");t.className="editToolbar";t.setAttribute("role","toolbar");t.addEventListener("contextmenu",noContextMenu,{signal:this.#m._signal});const e=this.#r=document.createElement("div");e.className="buttons";t.append(e);this.#b();return t}#A(t,e){let i=0,s=0;for(const n of t){const t=n.y+n.height;if(ti){s=a;i=t}else e?a>s&&(s=a):a{this.#m.highlightSelection("floating_button")}),{signal:i});this.#r.append(t)}}function bindEvents(t,e,i){for(const s of i)e.addEventListener(s,t[s].bind(t))}class IdManager{#w=0;get id(){return"pdfjs_internal_editor_"+this.#w++}}class ImageManager{#v=function getUuid(){if("function"==typeof crypto.randomUUID)return crypto.randomUUID();const t=new Uint8Array(32);crypto.getRandomValues(t);return bytesToString(t)}();#w=0;#y=null;static get _isSVGFittingCanvas(){const t=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),e=new Image;e.src='data:image/svg+xml;charset=UTF-8,';return shadow(this,"_isSVGFittingCanvas",e.decode().then((()=>{t.drawImage(e,0,0,1,1,0,0,1,3);return 0===new Uint32Array(t.getImageData(0,0,1,1).data.buffer)[0]})))}async#x(t,e){this.#y||=new Map;let i=this.#y.get(t);if(null===i)return null;if(i?.bitmap){i.refCounter+=1;return i}try{i||={bitmap:null,id:`image_${this.#v}_${this.#w++}`,refCounter:0,isSvg:!1};let t;if("string"==typeof e){i.url=e;t=await fetchData(e,"blob")}else e instanceof File?t=i.file=e:e instanceof Blob&&(t=e);if("image/svg+xml"===t.type){const e=ImageManager._isSVGFittingCanvas,s=new FileReader,n=new Image,a=new Promise(((t,a)=>{n.onload=()=>{i.bitmap=n;i.isSvg=!0;t()};s.onload=async()=>{const t=i.svgUrl=s.result;n.src=await e?`${t}#svgView(preserveAspectRatio(none))`:t};n.onerror=s.onerror=a}));s.readAsDataURL(t);await a}else i.bitmap=await createImageBitmap(t);i.refCounter=1}catch(t){warn(t);i=null}this.#y.set(t,i);i&&this.#y.set(i.id,i);return i}async getFromFile(t){const{lastModified:e,name:i,size:s,type:n}=t;return this.#x(`${e}_${i}_${s}_${n}`,t)}async getFromUrl(t){return this.#x(t,t)}async getFromBlob(t,e){const i=await e;return this.#x(t,i)}async getFromId(t){this.#y||=new Map;const e=this.#y.get(t);if(!e)return null;if(e.bitmap){e.refCounter+=1;return e}if(e.file)return this.getFromFile(e.file);if(e.blobPromise){const{blobPromise:t}=e;delete e.blobPromise;return this.getFromBlob(e.id,t)}return this.getFromUrl(e.url)}getFromCanvas(t,e){this.#y||=new Map;let i=this.#y.get(t);if(i?.bitmap){i.refCounter+=1;return i}const s=new OffscreenCanvas(e.width,e.height);s.getContext("2d").drawImage(e,0,0);i={bitmap:s.transferToImageBitmap(),id:`image_${this.#v}_${this.#w++}`,refCounter:1,isSvg:!1};this.#y.set(t,i);this.#y.set(i.id,i);return i}getSvgUrl(t){const e=this.#y.get(t);return e?.isSvg?e.svgUrl:null}deleteId(t){this.#y||=new Map;const e=this.#y.get(t);if(!e)return;e.refCounter-=1;if(0!==e.refCounter)return;const{bitmap:i}=e;if(!e.url&&!e.file){const t=new OffscreenCanvas(i.width,i.height);t.getContext("bitmaprenderer").transferFromImageBitmap(i);e.blobPromise=t.convertToBlob()}i.close?.();e.bitmap=null}isValidId(t){return t.startsWith(`image_${this.#v}_`)}}class CommandManager{#_=[];#E=!1;#S;#C=-1;constructor(t=128){this.#S=t}add({cmd:t,undo:e,post:i,mustExec:s,type:n=NaN,overwriteIfSameType:a=!1,keepUndo:r=!1}){s&&t();if(this.#E)return;const o={cmd:t,undo:e,post:i,type:n};if(-1===this.#C){this.#_.length>0&&(this.#_.length=0);this.#C=0;this.#_.push(o);return}if(a&&this.#_[this.#C].type===n){r&&(o.undo=this.#_[this.#C].undo);this.#_[this.#C]=o;return}const l=this.#C+1;if(l===this.#S)this.#_.splice(0,1);else{this.#C=l;l=0;e--)if(this.#_[e].type!==t){this.#_.splice(e+1,this.#C-e);this.#C=e;return}this.#_.length=0;this.#C=-1}}destroy(){this.#_=null}}class KeyboardManager{constructor(t){this.buffer=[];this.callbacks=new Map;this.allKeys=new Set;const{isMac:e}=util_FeatureTest.platform;for(const[i,s,n={}]of t)for(const t of i){const i=t.startsWith("mac+");if(e&&i){this.callbacks.set(t.slice(4),{callback:s,options:n});this.allKeys.add(t.split("+").at(-1))}else if(!e&&!i){this.callbacks.set(t,{callback:s,options:n});this.allKeys.add(t.split("+").at(-1))}}}#T(t){t.altKey&&this.buffer.push("alt");t.ctrlKey&&this.buffer.push("ctrl");t.metaKey&&this.buffer.push("meta");t.shiftKey&&this.buffer.push("shift");this.buffer.push(t.key);const e=this.buffer.join("+");this.buffer.length=0;return e}exec(t,e){if(!this.allKeys.has(e.key))return;const i=this.callbacks.get(this.#T(e));if(!i)return;const{callback:s,options:{bubbles:n=!1,args:a=[],checker:r=null}}=i;if(!r||r(t,e)){s.bind(t,...a,e)();n||stopEvent(e)}}}class ColorManager{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){const t=new Map([["CanvasText",null],["Canvas",null]]);!function getColorValues(t){const e=document.createElement("span");e.style.visibility="hidden";document.body.append(e);for(const i of t.keys()){e.style.color=i;const s=window.getComputedStyle(e).color;t.set(i,getRGB(s))}e.remove()}(t);return shadow(this,"_colors",t)}convert(t){const e=getRGB(t);if(!window.matchMedia("(forced-colors: active)").matches)return e;for(const[t,i]of this._colors)if(i.every(((t,i)=>t===e[i])))return ColorManager._colorsMapping.get(t);return e}getHexCode(t){const e=this._colors.get(t);return e?Util.makeHexColor(...e):t}}class AnnotationEditorUIManager{#M=new AbortController;#P=null;#D=new Map;#k=new Map;#R=null;#I=null;#F=null;#L=new CommandManager;#O=null;#N=null;#B=0;#H=new Set;#z=null;#U=null;#G=new Set;_editorUndoBar=null;#$=!1;#V=!1;#j=!1;#W=null;#q=null;#X=null;#K=null;#Y=!1;#Q=null;#J=new IdManager;#Z=!1;#tt=!1;#et=null;#it=null;#st=null;#nt=null;#at=g.NONE;#rt=new Set;#ot=null;#lt=null;#ht=null;#dt={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#ct=[0,0];#ut=null;#pt=null;#gt=null;#mt=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=AnnotationEditorUIManager.prototype,arrowChecker=t=>t.#pt.contains(document.activeElement)&&"BUTTON"!==document.activeElement.tagName&&t.hasSomethingToControl(),textInputChecker=(t,{target:e})=>{if(e instanceof HTMLInputElement){const{type:t}=e;return"text"!==t&&"number"!==t}return!0},e=this.TRANSLATE_SMALL,i=this.TRANSLATE_BIG;return shadow(this,"_keyboardManager",new KeyboardManager([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:textInputChecker}],[["ctrl+z","mac+meta+z"],t.undo,{checker:textInputChecker}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:textInputChecker}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],t.delete,{checker:textInputChecker}],[["Enter","mac+Enter"],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#pt.contains(e)&&!t.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#pt.contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-e,0],checker:arrowChecker}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-i,0],checker:arrowChecker}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[e,0],checker:arrowChecker}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[i,0],checker:arrowChecker}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-e],checker:arrowChecker}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-i],checker:arrowChecker}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,e],checker:arrowChecker}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,i],checker:arrowChecker}]]))}constructor(t,e,i,s,n,a,r,o,l,h,d,c,u){const p=this._signal=this.#M.signal;this.#pt=t;this.#gt=e;this.#R=i;this._eventBus=s;s._on("editingaction",this.onEditingAction.bind(this),{signal:p});s._on("pagechanging",this.onPageChanging.bind(this),{signal:p});s._on("scalechanging",this.onScaleChanging.bind(this),{signal:p});s._on("rotationchanging",this.onRotationChanging.bind(this),{signal:p});s._on("setpreference",this.onSetPreference.bind(this),{signal:p});s._on("switchannotationeditorparams",(t=>this.updateParams(t.type,t.value)),{signal:p});this.#ft();this.#bt();this.#At();this.#I=n.annotationStorage;this.#W=n.filterFactory;this.#lt=a;this.#K=r||null;this.#$=o;this.#V=l;this.#j=h;this.#nt=d||null;this.viewParameters={realScale:PixelsPerInch.PDF_TO_CSS_UNITS,rotation:0};this.isShiftKeyDown=!1;this._editorUndoBar=c||null;this._supportsPinchToZoom=!1!==u}destroy(){this.#mt?.resolve();this.#mt=null;this.#M?.abort();this.#M=null;this._signal=null;for(const t of this.#k.values())t.destroy();this.#k.clear();this.#D.clear();this.#G.clear();this.#P=null;this.#rt.clear();this.#L.destroy();this.#R?.destroy();this.#Q?.hide();this.#Q=null;if(this.#q){clearTimeout(this.#q);this.#q=null}if(this.#ut){clearTimeout(this.#ut);this.#ut=null}this._editorUndoBar?.destroy()}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return this.#nt}get useNewAltTextFlow(){return this.#V}get useNewAltTextWhenAddingImage(){return this.#j}get hcmFilter(){return shadow(this,"hcmFilter",this.#lt?this.#W.addHCMFilter(this.#lt.foreground,this.#lt.background):"none")}get direction(){return shadow(this,"direction",getComputedStyle(this.#pt).direction)}get highlightColors(){return shadow(this,"highlightColors",this.#K?new Map(this.#K.split(",").map((t=>t.split("=").map((t=>t.trim()))))):null)}get highlightColorNames(){return shadow(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,(t=>t.reverse()))):null)}setCurrentDrawingSession(t){if(t){this.unselectAll();this.disableUserSelect(!0)}else this.disableUserSelect(!1);this.#N=t}setMainHighlightColorPicker(t){this.#st=t}editAltText(t,e=!1){this.#R?.editAltText(this,t,e)}switchToMode(t,e){this._eventBus.on("annotationeditormodechanged",e,{once:!0,signal:this._signal});this._eventBus.dispatch("showannotationeditorui",{source:this,mode:t})}setPreference(t,e){this._eventBus.dispatch("setpreference",{source:this,name:t,value:e})}onSetPreference({name:t,value:e}){if("enableNewAltTextWhenAddingImage"===t)this.#j=e}onPageChanging({pageNumber:t}){this.#B=t-1}focusMainContainer(){this.#pt.focus()}findParent(t,e){for(const i of this.#k.values()){const{x:s,y:n,width:a,height:r}=i.div.getBoundingClientRect();if(t>=s&&t<=s+a&&e>=n&&e<=n+r)return i}return null}disableUserSelect(t=!1){this.#gt.classList.toggle("noUserSelect",t)}addShouldRescale(t){this.#G.add(t)}removeShouldRescale(t){this.#G.delete(t)}onScaleChanging({scale:t}){this.commitOrRemove();this.viewParameters.realScale=t*PixelsPerInch.PDF_TO_CSS_UNITS;for(const t of this.#G)t.onScaleChanging();this.#N?.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove();this.viewParameters.rotation=t}#wt({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}#vt(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const e of this.#k.values())if(e.hasTextLayer(t))return e;return null}highlightSelection(t=""){const e=document.getSelection();if(!e||e.isCollapsed)return;const{anchorNode:i,anchorOffset:s,focusNode:n,focusOffset:a}=e,r=e.toString(),o=this.#wt(e).closest(".textLayer"),l=this.getSelectionBoxes(o);if(!l)return;e.empty();const h=this.#vt(o),d=this.#at===g.NONE,callback=()=>{h?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:l,anchorNode:i,anchorOffset:s,focusNode:n,focusOffset:a,text:r});d&&this.showAllEditors("highlight",!0,!0)};d?this.switchToMode(g.HIGHLIGHT,callback):callback()}#yt(){const t=document.getSelection();if(!t||t.isCollapsed)return;const e=this.#wt(t).closest(".textLayer"),i=this.getSelectionBoxes(e);if(i){this.#Q||=new HighlightToolbar(this);this.#Q.show(e,i,"ltr"===this.direction)}}addToAnnotationStorage(t){t.isEmpty()||!this.#I||this.#I.has(t.id)||this.#I.setValue(t.id,t)}#xt(){const t=document.getSelection();if(!t||t.isCollapsed){if(this.#ot){this.#Q?.hide();this.#ot=null;this.#_t({hasSelectedText:!1})}return}const{anchorNode:e}=t;if(e===this.#ot)return;const i=this.#wt(t).closest(".textLayer");if(i){this.#Q?.hide();this.#ot=e;this.#_t({hasSelectedText:!0});if(this.#at===g.HIGHLIGHT||this.#at===g.NONE){this.#at===g.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0);this.#Y=this.isShiftKeyDown;if(!this.isShiftKeyDown){const t=this.#at===g.HIGHLIGHT?this.#vt(i):null;t?.toggleDrawing();const e=new AbortController,s=this.combinedSignal(e),pointerup=i=>{if("pointerup"!==i.type||0===i.button){e.abort();t?.toggleDrawing(!0);"pointerup"===i.type&&this.#Et("main_toolbar")}};window.addEventListener("pointerup",pointerup,{signal:s});window.addEventListener("blur",pointerup,{signal:s})}}}else if(this.#ot){this.#Q?.hide();this.#ot=null;this.#_t({hasSelectedText:!1})}}#Et(t=""){this.#at===g.HIGHLIGHT?this.highlightSelection(t):this.#$&&this.#yt()}#ft(){document.addEventListener("selectionchange",this.#xt.bind(this),{signal:this._signal})}#St(){if(this.#X)return;this.#X=new AbortController;const t=this.combinedSignal(this.#X);window.addEventListener("focus",this.focus.bind(this),{signal:t});window.addEventListener("blur",this.blur.bind(this),{signal:t})}#Ct(){this.#X?.abort();this.#X=null}blur(){this.isShiftKeyDown=!1;if(this.#Y){this.#Y=!1;this.#Et("main_toolbar")}if(!this.hasSelection)return;const{activeElement:t}=document;for(const e of this.#rt)if(e.div.contains(t)){this.#it=[e,t];e._focusEventsAllowed=!1;break}}focus(){if(!this.#it)return;const[t,e]=this.#it;this.#it=null;e.addEventListener("focusin",(()=>{t._focusEventsAllowed=!0}),{once:!0,signal:this._signal});e.focus()}#At(){if(this.#et)return;this.#et=new AbortController;const t=this.combinedSignal(this.#et);window.addEventListener("keydown",this.keydown.bind(this),{signal:t});window.addEventListener("keyup",this.keyup.bind(this),{signal:t})}#Tt(){this.#et?.abort();this.#et=null}#Mt(){if(this.#O)return;this.#O=new AbortController;const t=this.combinedSignal(this.#O);document.addEventListener("copy",this.copy.bind(this),{signal:t});document.addEventListener("cut",this.cut.bind(this),{signal:t});document.addEventListener("paste",this.paste.bind(this),{signal:t})}#Pt(){this.#O?.abort();this.#O=null}#bt(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t});document.addEventListener("drop",this.drop.bind(this),{signal:t})}addEditListeners(){this.#At();this.#Mt()}removeEditListeners(){this.#Tt();this.#Pt()}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const i of this.#U)if(i.isHandlingMimeForPasting(e)){t.dataTransfer.dropEffect="copy";t.preventDefault();return}}drop(t){for(const e of t.dataTransfer.items)for(const i of this.#U)if(i.isHandlingMimeForPasting(e.type)){i.paste(e,this.currentLayer);t.preventDefault();return}}copy(t){t.preventDefault();this.#P?.commitOrRemove();if(!this.hasSelection)return;const e=[];for(const t of this.#rt){const i=t.serialize(!0);i&&e.push(i)}0!==e.length&&t.clipboardData.setData("application/pdfjs",JSON.stringify(e))}cut(t){this.copy(t);this.delete()}async paste(t){t.preventDefault();const{clipboardData:e}=t;for(const t of e.items)for(const e of this.#U)if(e.isHandlingMimeForPasting(t.type)){e.paste(t,this.currentLayer);return}let i=e.getData("application/pdfjs");if(!i)return;try{i=JSON.parse(i)}catch(t){warn(`paste: "${t.message}".`);return}if(!Array.isArray(i))return;this.unselectAll();const s=this.currentLayer;try{const t=[];for(const e of i){const i=await s.deserialize(e);if(!i)return;t.push(i)}const cmd=()=>{for(const e of t)this.#Dt(e);this.#kt(t)},undo=()=>{for(const e of t)e.remove()};this.addCommands({cmd,undo,mustExec:!0})}catch(t){warn(`paste: "${t.message}".`)}}keydown(t){this.isShiftKeyDown||"Shift"!==t.key||(this.isShiftKeyDown=!0);this.#at===g.NONE||this.isEditorHandlingKeyboard||AnnotationEditorUIManager._keyboardManager.exec(this,t)}keyup(t){if(this.isShiftKeyDown&&"Shift"===t.key){this.isShiftKeyDown=!1;if(this.#Y){this.#Y=!1;this.#Et("main_toolbar")}}}onEditingAction({name:t}){switch(t){case"undo":case"redo":case"delete":case"selectAll":this[t]();break;case"highlightSelection":this.highlightSelection("context_menu")}}#_t(t){if(Object.entries(t).some((([t,e])=>this.#dt[t]!==e))){this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#dt,t)});this.#at===g.HIGHLIGHT&&!1===t.hasSelectedEditor&&this.#Rt([[m.HIGHLIGHT_FREE,!0]])}}#Rt(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){if(t){this.#St();this.#Mt();this.#_t({isEditing:this.#at!==g.NONE,isEmpty:this.#It(),hasSomethingToUndo:this.#L.hasSomethingToUndo(),hasSomethingToRedo:this.#L.hasSomethingToRedo(),hasSelectedEditor:!1})}else{this.#Ct();this.#Pt();this.#_t({isEditing:!1});this.disableUserSelect(!1)}}registerEditorTypes(t){if(!this.#U){this.#U=t;for(const t of this.#U)this.#Rt(t.defaultPropertiesToUpdate)}}getId(){return this.#J.id}get currentLayer(){return this.#k.get(this.#B)}getLayer(t){return this.#k.get(t)}get currentPageIndex(){return this.#B}addLayer(t){this.#k.set(t.pageIndex,t);this.#Z?t.enable():t.disable()}removeLayer(t){this.#k.delete(t.pageIndex)}async updateMode(t,e=null,i=!1){if(this.#at!==t){if(this.#mt){await this.#mt.promise;if(!this.#mt)return}this.#mt=Promise.withResolvers();this.#at=t;if(t!==g.NONE){this.setEditingState(!0);await this.#Ft();this.unselectAll();for(const e of this.#k.values())e.updateMode(t);if(e){for(const t of this.#D.values())if(t.annotationElementId===e){this.setSelected(t);t.enterInEditMode()}else t.unselect();this.#mt.resolve()}else{i&&this.addNewEditorFromKeyboard();this.#mt.resolve()}}else{this.setEditingState(!1);this.#Lt();this._editorUndoBar?.hide();this.#mt.resolve()}}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==this.#at&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,e){if(this.#U){switch(t){case m.CREATE:this.currentLayer.addNewEditor();return;case m.HIGHLIGHT_DEFAULT_COLOR:this.#st?.updateColor(e);break;case m.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}});(this.#ht||=new Map).set(t,e);this.showAllEditors("highlight",e)}for(const i of this.#rt)i.updateParams(t,e);for(const i of this.#U)i.updateDefaultParams(t,e)}}showAllEditors(t,e,i=!1){for(const i of this.#D.values())i.editorType===t&&i.show(e);(this.#ht?.get(m.HIGHLIGHT_SHOW_ALL)??!0)!==e&&this.#Rt([[m.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(this.#tt!==t){this.#tt=t;for(const e of this.#k.values()){t?e.disableClick():e.enableClick();e.div.classList.toggle("waiting",t)}}}async#Ft(){if(!this.#Z){this.#Z=!0;const t=[];for(const e of this.#k.values())t.push(e.enable());await Promise.all(t);for(const t of this.#D.values())t.enable()}}#Lt(){this.unselectAll();if(this.#Z){this.#Z=!1;for(const t of this.#k.values())t.disable();for(const t of this.#D.values())t.disable()}}getEditors(t){const e=[];for(const i of this.#D.values())i.pageIndex===t&&e.push(i);return e}getEditor(t){return this.#D.get(t)}addEditor(t){this.#D.set(t.id,t)}removeEditor(t){if(t.div.contains(document.activeElement)){this.#q&&clearTimeout(this.#q);this.#q=setTimeout((()=>{this.focusMainContainer();this.#q=null}),0)}this.#D.delete(t.id);this.unselect(t);t.annotationElementId&&this.#H.has(t.annotationElementId)||this.#I?.remove(t.id)}addDeletedAnnotationElement(t){this.#H.add(t.annotationElementId);this.addChangedExistingAnnotation(t);t.deleted=!0}isDeletedAnnotationElement(t){return this.#H.has(t)}removeDeletedAnnotationElement(t){this.#H.delete(t.annotationElementId);this.removeChangedExistingAnnotation(t);t.deleted=!1}#Dt(t){const e=this.#k.get(t.pageIndex);if(e)e.addOrRebuild(t);else{this.addEditor(t);this.addToAnnotationStorage(t)}}setActiveEditor(t){if(this.#P!==t){this.#P=t;t&&this.#Rt(t.propertiesToUpdate)}}get#Ot(){let t=null;for(t of this.#rt);return t}updateUI(t){this.#Ot===t&&this.#Rt(t.propertiesToUpdate)}updateUIForDefaultProperties(t){this.#Rt(t.defaultPropertiesToUpdate)}toggleSelected(t){if(this.#rt.has(t)){this.#rt.delete(t);t.unselect();this.#_t({hasSelectedEditor:this.hasSelection})}else{this.#rt.add(t);t.select();this.#Rt(t.propertiesToUpdate);this.#_t({hasSelectedEditor:!0})}}setSelected(t){this.#N?.commitOrRemove();for(const e of this.#rt)e!==t&&e.unselect();this.#rt.clear();this.#rt.add(t);t.select();this.#Rt(t.propertiesToUpdate);this.#_t({hasSelectedEditor:!0})}isSelected(t){return this.#rt.has(t)}get firstSelectedEditor(){return this.#rt.values().next().value}unselect(t){t.unselect();this.#rt.delete(t);this.#_t({hasSelectedEditor:this.hasSelection})}get hasSelection(){return 0!==this.#rt.size}get isEnterHandled(){return 1===this.#rt.size&&this.firstSelectedEditor.isEnterHandled}undo(){this.#L.undo();this.#_t({hasSomethingToUndo:this.#L.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#It()});this._editorUndoBar?.hide()}redo(){this.#L.redo();this.#_t({hasSomethingToUndo:!0,hasSomethingToRedo:this.#L.hasSomethingToRedo(),isEmpty:this.#It()})}addCommands(t){this.#L.add(t);this.#_t({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#It()})}cleanUndoStack(t){this.#L.cleanType(t)}#It(){if(0===this.#D.size)return!0;if(1===this.#D.size)for(const t of this.#D.values())return t.isEmpty();return!1}delete(){this.commitOrRemove();const t=this.currentLayer?.endDrawingSession(!0);if(!this.hasSelection&&!t)return;const e=t?[t]:[...this.#rt],undo=()=>{for(const t of e)this.#Dt(t)};this.addCommands({cmd:()=>{this._editorUndoBar?.show(undo,1===e.length?e[0].editorType:e.length);for(const t of e)t.remove()},undo,mustExec:!0})}commitOrRemove(){this.#P?.commitOrRemove()}hasSomethingToControl(){return this.#P||this.hasSelection}#kt(t){for(const t of this.#rt)t.unselect();this.#rt.clear();for(const e of t)if(!e.isEmpty()){this.#rt.add(e);e.select()}this.#_t({hasSelectedEditor:this.hasSelection})}selectAll(){for(const t of this.#rt)t.commit();this.#kt(this.#D.values())}unselectAll(){if(this.#P){this.#P.commitOrRemove();if(this.#at!==g.NONE)return}if(!this.#N?.commitOrRemove()&&this.hasSelection){for(const t of this.#rt)t.unselect();this.#rt.clear();this.#_t({hasSelectedEditor:!1})}}translateSelectedEditors(t,e,i=!1){i||this.commitOrRemove();if(!this.hasSelection)return;this.#ct[0]+=t;this.#ct[1]+=e;const[s,n]=this.#ct,a=[...this.#rt];this.#ut&&clearTimeout(this.#ut);this.#ut=setTimeout((()=>{this.#ut=null;this.#ct[0]=this.#ct[1]=0;this.addCommands({cmd:()=>{for(const t of a)this.#D.has(t.id)&&t.translateInPage(s,n)},undo:()=>{for(const t of a)this.#D.has(t.id)&&t.translateInPage(-s,-n)},mustExec:!1})}),1e3);for(const i of a)i.translateInPage(t,e)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0);this.#z=new Map;for(const t of this.#rt)this.#z.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#z)return!1;this.disableUserSelect(!1);const t=this.#z;this.#z=null;let e=!1;for(const[{x:i,y:s,pageIndex:n},a]of t){a.newX=i;a.newY=s;a.newPageIndex=n;e||=i!==a.savedX||s!==a.savedY||n!==a.savedPageIndex}if(!e)return!1;const move=(t,e,i,s)=>{if(this.#D.has(t.id)){const n=this.#k.get(s);if(n)t._setParentAndPosition(n,e,i);else{t.pageIndex=s;t.x=e;t.y=i}}};this.addCommands({cmd:()=>{for(const[e,{newX:i,newY:s,newPageIndex:n}]of t)move(e,i,s,n)},undo:()=>{for(const[e,{savedX:i,savedY:s,savedPageIndex:n}]of t)move(e,i,s,n)},mustExec:!0});return!0}dragSelectedEditors(t,e){if(this.#z)for(const i of this.#z.keys())i.drag(t,e)}rebuild(t){if(null===t.parent){const e=this.getLayer(t.pageIndex);if(e){e.changeParent(t);e.addOrRebuild(t)}else{this.addEditor(t);this.addToAnnotationStorage(t);t.rebuild()}}else t.parent.addOrRebuild(t)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||1===this.#rt.size&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#P===t}getActive(){return this.#P}getMode(){return this.#at}get imageManager(){return shadow(this,"imageManager",new ImageManager)}getSelectionBoxes(t){if(!t)return null;const e=document.getSelection();for(let i=0,s=e.rangeCount;i({x:(e-s)/a,y:1-(t+r-i)/n,width:o/a,height:r/n});break;case"180":r=(t,e,r,o)=>({x:1-(t+r-i)/n,y:1-(e+o-s)/a,width:r/n,height:o/a});break;case"270":r=(t,e,r,o)=>({x:1-(e+o-s)/a,y:(t-i)/n,width:o/a,height:r/n});break;default:r=(t,e,r,o)=>({x:(t-i)/n,y:(e-s)/a,width:r/n,height:o/a})}const o=[];for(let t=0,i=e.rangeCount;tt.stopPropagation()),{signal:i});const onClick=t=>{t.preventDefault();this.#a._uiManager.editAltText(this.#a);this.#Wt&&this.#a._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:this.#Xt}})};t.addEventListener("click",onClick,{capture:!0,signal:i});t.addEventListener("keydown",(e=>{if(e.target===t&&"Enter"===e.key){this.#Gt=!0;onClick(e)}}),{signal:i});await this.#Kt();return t}get#Xt(){return(this.#o?"added":null===this.#o&&this.guessedText&&"review")||"missing"}finish(){if(this.#Bt){this.#Bt.focus({focusVisible:this.#Gt});this.#Gt=!1}}isEmpty(){return this.#Wt?null===this.#o:!this.#o&&!this.#Nt}hasData(){return this.#Wt?null!==this.#o||!!this.#Vt:this.isEmpty()}get guessedText(){return this.#Vt}async setGuessedText(t){if(null===this.#o){this.#Vt=t;this.#jt=await AltText._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t});this.#Kt()}}toggleAltTextBadge(t=!1){if(this.#Wt&&!this.#o){if(!this.#$t){const t=this.#$t=document.createElement("div");t.className="noAltTextBadge";this.#a.div.append(t)}this.#$t.classList.toggle("hidden",!t)}else{this.#$t?.remove();this.#$t=null}}serialize(t){let e=this.#o;t||this.#Vt!==e||(e=this.#jt);return{altText:e,decorative:this.#Nt,guessedText:this.#Vt,textWithDisclaimer:this.#jt}}get data(){return{altText:this.#o,decorative:this.#Nt}}set data({altText:t,decorative:e,guessedText:i,textWithDisclaimer:s,cancel:n=!1}){if(i){this.#Vt=i;this.#jt=s}if(this.#o!==t||this.#Nt!==e){if(!n){this.#o=t;this.#Nt=e}this.#Kt()}}toggle(t=!1){if(this.#Bt){if(!t&&this.#Ut){clearTimeout(this.#Ut);this.#Ut=null}this.#Bt.disabled=!t}}shown(){this.#a._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:this.#Xt}})}destroy(){this.#Bt?.remove();this.#Bt=null;this.#Ht=null;this.#zt=null;this.#$t?.remove();this.#$t=null}async#Kt(){const t=this.#Bt;if(!t)return;if(this.#Wt){t.classList.toggle("done",!!this.#o);t.setAttribute("data-l10n-id",AltText.#qt[this.#Xt]);this.#Ht?.setAttribute("data-l10n-id",AltText.#qt[`${this.#Xt}-label`]);if(!this.#o){this.#zt?.remove();return}}else{if(!this.#o&&!this.#Nt){t.classList.remove("done");this.#zt?.remove();return}t.classList.add("done");t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let e=this.#zt;if(!e){this.#zt=e=document.createElement("span");e.className="tooltip";e.setAttribute("role","tooltip");e.id=`alt-text-tooltip-${this.#a.id}`;const i=100,s=this.#a._uiManager._signal;s.addEventListener("abort",(()=>{clearTimeout(this.#Ut);this.#Ut=null}),{once:!0});t.addEventListener("mouseenter",(()=>{this.#Ut=setTimeout((()=>{this.#Ut=null;this.#zt.classList.add("show");this.#a._reportTelemetry({action:"alt_text_tooltip"})}),i)}),{signal:s});t.addEventListener("mouseleave",(()=>{if(this.#Ut){clearTimeout(this.#Ut);this.#Ut=null}this.#zt?.classList.remove("show")}),{signal:s})}if(this.#Nt)e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip");else{e.removeAttribute("data-l10n-id");e.textContent=this.#o}e.parentNode||t.append(e);const i=this.#a.getImageForAltText();i?.setAttribute("aria-describedby",e.id)}}class TouchManager{#pt;#Yt=!1;#Qt=null;#Jt;#Zt;#te;#ee;#ie;#se=null;#ne;#ae=null;constructor({container:t,isPinchingDisabled:e=null,isPinchingStopped:i=null,onPinchStart:s=null,onPinching:n=null,onPinchEnd:a=null,signal:r}){this.#pt=t;this.#Qt=i;this.#Jt=e;this.#Zt=s;this.#te=n;this.#ee=a;this.#ne=new AbortController;this.#ie=AbortSignal.any([r,this.#ne.signal]);t.addEventListener("touchstart",this.#re.bind(this),{passive:!1,signal:this.#ie})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return shadow(this,"MIN_TOUCH_DISTANCE_TO_PINCH",35/(window.devicePixelRatio||1))}#re(t){if(this.#Jt?.()||t.touches.length<2)return;if(!this.#ae){this.#ae=new AbortController;const t=AbortSignal.any([this.#ie,this.#ae.signal]),e=this.#pt,i={signal:t,passive:!1};e.addEventListener("touchmove",this.#oe.bind(this),i);e.addEventListener("touchend",this.#le.bind(this),i);e.addEventListener("touchcancel",this.#le.bind(this),i);this.#Zt?.()}stopEvent(t);if(2!==t.touches.length||this.#Qt?.()){this.#se=null;return}let[e,i]=t.touches;e.identifier>i.identifier&&([e,i]=[i,e]);this.#se={touch0X:e.screenX,touch0Y:e.screenY,touch1X:i.screenX,touch1Y:i.screenY}}#oe(t){if(!this.#se||2!==t.touches.length)return;let[e,i]=t.touches;e.identifier>i.identifier&&([e,i]=[i,e]);const{screenX:s,screenY:n}=e,{screenX:a,screenY:r}=i,o=this.#se,{touch0X:l,touch0Y:h,touch1X:d,touch1Y:c}=o,u=d-l,p=c-h,g=a-s,m=r-n,f=Math.hypot(g,m)||1,b=Math.hypot(u,p)||1;if(!this.#Yt&&Math.abs(b-f)<=TouchManager.MIN_TOUCH_DISTANCE_TO_PINCH)return;o.touch0X=s;o.touch0Y=n;o.touch1X=a;o.touch1Y=r;t.preventDefault();if(!this.#Yt){this.#Yt=!0;return}const A=[(s+a)/2,(n+r)/2];this.#te?.(A,b,f)}#le(t){this.#ae.abort();this.#ae=null;this.#ee?.();if(this.#se){t.preventDefault();this.#se=null;this.#Yt=!1}}destroy(){this.#ne?.abort();this.#ne=null}}class AnnotationEditor{#he=null;#de=null;#o=null;#ce=!1;#ue=null;#pe="";#ge=!1;#me=null;#fe=null;#be=null;#Ae=null;#we="";#ve=!1;#ye=null;#xe=!1;#_e=!1;#Ee=!1;#Se=null;#Ce=0;#Te=0;#Me=null;#Pe=null;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nResizer=null;#De=!1;#ke=AnnotationEditor._zIndex++;static _borderLineWidth=-1;static _colorManager=new ColorManager;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){const t=AnnotationEditor.prototype._resizeWithKeyboard,e=AnnotationEditorUIManager.TRANSLATE_SMALL,i=AnnotationEditorUIManager.TRANSLATE_BIG;return shadow(this,"_resizerKeyboardManager",new KeyboardManager([[["ArrowLeft","mac+ArrowLeft"],t,{args:[-e,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-i,0]}],[["ArrowRight","mac+ArrowRight"],t,{args:[e,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[i,0]}],[["ArrowUp","mac+ArrowUp"],t,{args:[0,-e]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-i]}],[["ArrowDown","mac+ArrowDown"],t,{args:[0,e]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,i]}],[["Escape","mac+Escape"],AnnotationEditor.prototype._stopResizingWithKeyboard]]))}constructor(t){this.parent=t.parent;this.id=t.id;this.width=this.height=null;this.pageIndex=t.parent.pageIndex;this.name=t.name;this.div=null;this._uiManager=t.uiManager;this.annotationElementId=null;this._willKeepAspectRatio=!1;this._initialOptions.isCentered=t.isCentered;this._structTreeParentId=null;const{rotation:e,rawDims:{pageWidth:i,pageHeight:s,pageX:n,pageY:a}}=this.parent.viewport;this.rotation=e;this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360;this.pageDimensions=[i,s];this.pageTranslation=[n,a];const[r,o]=this.parentDimensions;this.x=t.x/r;this.y=t.y/o;this.isAttachedToDOM=!1;this.deleted=!1}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get isDrawer(){return!1}static get _defaultLineColor(){return shadow(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new FakeEditor({id:t.parent.getNextId(),parent:t.parent,uiManager:t._uiManager});e.annotationElementId=t.annotationElementId;e.deleted=!0;e._uiManager.addToAnnotationStorage(e)}static initialize(t,e){AnnotationEditor._l10n??=t;AnnotationEditor._l10nResizer||=Object.freeze({topLeft:"pdfjs-editor-resizer-top-left",topMiddle:"pdfjs-editor-resizer-top-middle",topRight:"pdfjs-editor-resizer-top-right",middleRight:"pdfjs-editor-resizer-middle-right",bottomRight:"pdfjs-editor-resizer-bottom-right",bottomMiddle:"pdfjs-editor-resizer-bottom-middle",bottomLeft:"pdfjs-editor-resizer-bottom-left",middleLeft:"pdfjs-editor-resizer-middle-left"});if(-1!==AnnotationEditor._borderLineWidth)return;const i=getComputedStyle(document.documentElement);AnnotationEditor._borderLineWidth=parseFloat(i.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){unreachable("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#De}set _isDraggable(t){this.#De=t;this.div?.classList.toggle("draggable",t)}get isEnterHandled(){return!0}center(){const[t,e]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*e/(2*t);this.y+=this.width*t/(2*e);break;case 180:this.x+=this.width/2;this.y+=this.height/2;break;case 270:this.x+=this.height*e/(2*t);this.y-=this.width*t/(2*e);break;default:this.x-=this.width/2;this.y-=this.height/2}this.fixAndSetPosition()}addCommands(t){this._uiManager.addCommands(t)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#ke}setParent(t){if(null!==t){this.pageIndex=t.pageIndex;this.pageDimensions=t.pageDimensions}else this.#Re();this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#ve?this.#ve=!1:this.parent.setSelected(this))}focusout(t){if(!this._focusEventsAllowed)return;if(!this.isAttachedToDOM)return;const e=t.relatedTarget;if(!e?.closest(`#${this.id}`)){t.preventDefault();this.parent?.isMultipleSelection||this.commitOrRemove()}}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(t,e,i,s){const[n,a]=this.parentDimensions;[i,s]=this.screenToPageTranslation(i,s);this.x=(t+i)/n;this.y=(e+s)/a;this.fixAndSetPosition()}#Ie([t,e],i,s){[i,s]=this.screenToPageTranslation(i,s);this.x+=i/t;this.y+=s/e;this._onTranslating(this.x,this.y);this.fixAndSetPosition()}translate(t,e){this.#Ie(this.parentDimensions,t,e)}translateInPage(t,e){this.#ye||=[this.x,this.y,this.width,this.height];this.#Ie(this.pageDimensions,t,e);this.div.scrollIntoView({block:"nearest"})}drag(t,e){this.#ye||=[this.x,this.y,this.width,this.height];const{div:i,parentDimensions:[s,n]}=this;this.x+=t/s;this.y+=e/n;if(this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:t,y:e}=this.div.getBoundingClientRect();if(this.parent.findNewParent(this,t,e)){this.x-=Math.floor(this.x);this.y-=Math.floor(this.y)}}let{x:a,y:r}=this;const[o,l]=this.getBaseTranslation();a+=o;r+=l;const{style:h}=i;h.left=`${(100*a).toFixed(2)}%`;h.top=`${(100*r).toFixed(2)}%`;this._onTranslating(a,r);i.scrollIntoView({block:"nearest"})}_onTranslating(t,e){}_onTranslated(t,e){}get _hasBeenMoved(){return!!this.#ye&&(this.#ye[0]!==this.x||this.#ye[1]!==this.y)}get _hasBeenResized(){return!!this.#ye&&(this.#ye[2]!==this.width||this.#ye[3]!==this.height)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:i}=AnnotationEditor,s=i/t,n=i/e;switch(this.rotation){case 90:return[-s,n];case 180:return[s,n];case 270:return[s,-n];default:return[-s,-n]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const{div:{style:e},pageDimensions:[i,s]}=this;let{x:n,y:a,width:r,height:o}=this;r*=i;o*=s;n*=i;a*=s;if(this._mustFixPosition)switch(t){case 0:n=Math.max(0,Math.min(i-r,n));a=Math.max(0,Math.min(s-o,a));break;case 90:n=Math.max(0,Math.min(i-o,n));a=Math.min(s,Math.max(r,a));break;case 180:n=Math.min(i,Math.max(r,n));a=Math.min(s,Math.max(o,a));break;case 270:n=Math.min(i,Math.max(o,n));a=Math.max(0,Math.min(s-r,a))}this.x=n/=i;this.y=a/=s;const[l,h]=this.getBaseTranslation();n+=l;a+=h;e.left=`${(100*n).toFixed(2)}%`;e.top=`${(100*a).toFixed(2)}%`;this.moveInDOM()}static#Fe(t,e,i){switch(i){case 90:return[e,-t];case 180:return[-t,-e];case 270:return[-e,t];default:return[t,e]}}screenToPageTranslation(t,e){return AnnotationEditor.#Fe(t,e,this.parentRotation)}pageTranslationToScreen(t,e){return AnnotationEditor.#Fe(t,e,360-this.parentRotation)}#Le(t){switch(t){case 90:{const[t,e]=this.pageDimensions;return[0,-t/e,e/t,0]}case 180:return[-1,0,0,-1];case 270:{const[t,e]=this.pageDimensions;return[0,t/e,-e/t,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:t,pageDimensions:[e,i]}=this;return[e*t,i*t]}setDims(t,e){const[i,s]=this.parentDimensions,{style:n}=this.div;n.width=`${(100*t/i).toFixed(2)}%`;this.#ge||(n.height=`${(100*e/s).toFixed(2)}%`)}fixDims(){const{style:t}=this.div,{height:e,width:i}=t,s=i.endsWith("%"),n=!this.#ge&&e.endsWith("%");if(s&&n)return;const[a,r]=this.parentDimensions;s||(t.width=`${(100*parseFloat(i)/a).toFixed(2)}%`);this.#ge||n||(t.height=`${(100*parseFloat(e)/r).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}#Oe(){if(this.#me)return;this.#me=document.createElement("div");this.#me.classList.add("resizers");const t=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],e=this._uiManager._signal;for(const i of t){const t=document.createElement("div");this.#me.append(t);t.classList.add("resizer",i);t.setAttribute("data-resizer-name",i);t.addEventListener("pointerdown",this.#Ne.bind(this,i),{signal:e});t.addEventListener("contextmenu",noContextMenu,{signal:e});t.tabIndex=-1}this.div.prepend(this.#me)}#Ne(t,e){e.preventDefault();const{isMac:i}=util_FeatureTest.platform;if(0!==e.button||e.ctrlKey&&i)return;this.#o?.toggle(!1);const s=this._isDraggable;this._isDraggable=!1;this.#fe=[e.screenX,e.screenY];const n=new AbortController,a=this._uiManager.combinedSignal(n);this.parent.togglePointerEvents(!1);window.addEventListener("pointermove",this.#Be.bind(this,t),{passive:!0,capture:!0,signal:a});window.addEventListener("touchmove",stopEvent,{passive:!1,signal:a});window.addEventListener("contextmenu",noContextMenu,{signal:a});this.#be={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const r=this.parent.div.style.cursor,o=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const pointerUpCallback=()=>{n.abort();this.parent.togglePointerEvents(!0);this.#o?.toggle(!0);this._isDraggable=s;this.parent.div.style.cursor=r;this.div.style.cursor=o;this.#He()};window.addEventListener("pointerup",pointerUpCallback,{signal:a});window.addEventListener("blur",pointerUpCallback,{signal:a})}#ze(t,e,i,s){this.width=i;this.height=s;this.x=t;this.y=e;const[n,a]=this.parentDimensions;this.setDims(n*i,a*s);this.fixAndSetPosition();this._onResized()}_onResized(){}#He(){if(!this.#be)return;const{savedX:t,savedY:e,savedWidth:i,savedHeight:s}=this.#be;this.#be=null;const n=this.x,a=this.y,r=this.width,o=this.height;n===t&&a===e&&r===i&&o===s||this.addCommands({cmd:this.#ze.bind(this,n,a,r,o),undo:this.#ze.bind(this,t,e,i,s),mustExec:!0})}static _round(t){return Math.round(1e4*t)/1e4}#Be(t,e){const[i,s]=this.parentDimensions,n=this.x,a=this.y,r=this.width,o=this.height,l=AnnotationEditor.MIN_SIZE/i,h=AnnotationEditor.MIN_SIZE/s,d=this.#Le(this.rotation),transf=(t,e)=>[d[0]*t+d[2]*e,d[1]*t+d[3]*e],c=this.#Le(360-this.rotation);let u,p,g=!1,m=!1;switch(t){case"topLeft":g=!0;u=(t,e)=>[0,0];p=(t,e)=>[t,e];break;case"topMiddle":u=(t,e)=>[t/2,0];p=(t,e)=>[t/2,e];break;case"topRight":g=!0;u=(t,e)=>[t,0];p=(t,e)=>[0,e];break;case"middleRight":m=!0;u=(t,e)=>[t,e/2];p=(t,e)=>[0,e/2];break;case"bottomRight":g=!0;u=(t,e)=>[t,e];p=(t,e)=>[0,0];break;case"bottomMiddle":u=(t,e)=>[t/2,e];p=(t,e)=>[t/2,0];break;case"bottomLeft":g=!0;u=(t,e)=>[0,e];p=(t,e)=>[t,0];break;case"middleLeft":m=!0;u=(t,e)=>[0,e/2];p=(t,e)=>[t,e/2]}const f=u(r,o),b=p(r,o);let A=transf(...b);const w=AnnotationEditor._round(n+A[0]),v=AnnotationEditor._round(a+A[1]);let y,x,_=1,E=1;if(e.fromKeyboard)({deltaX:y,deltaY:x}=e);else{const{screenX:t,screenY:i}=e,[s,n]=this.#fe;[y,x]=this.screenToPageTranslation(t-s,i-n);this.#fe[0]=t;this.#fe[1]=i}[y,x]=(S=y/i,C=x/s,[c[0]*S+c[2]*C,c[1]*S+c[3]*C]);var S,C;if(g){const t=Math.hypot(r,o);_=E=Math.max(Math.min(Math.hypot(b[0]-f[0]-y,b[1]-f[1]-x)/t,1/r,1/o),l/r,h/o)}else m?_=Math.max(l,Math.min(1,Math.abs(b[0]-f[0]-y)))/r:E=Math.max(h,Math.min(1,Math.abs(b[1]-f[1]-x)))/o;const T=AnnotationEditor._round(r*_),M=AnnotationEditor._round(o*E);A=transf(...p(T,M));const P=w-A[0],D=v-A[1];this.#ye||=[this.x,this.y,this.width,this.height];this.width=T;this.height=M;this.x=P;this.y=D;this.setDims(i*T,s*M);this.fixAndSetPosition();this._onResizing()}_onResizing(){}altTextFinish(){this.#o?.finish()}async addEditToolbar(){if(this._editToolbar||this.#_e)return this._editToolbar;this._editToolbar=new EditorToolbar(this);this.div.append(this._editToolbar.render());this.#o&&await this._editToolbar.addAltText(this.#o);return this._editToolbar}removeEditToolbar(){if(this._editToolbar){this._editToolbar.remove();this._editToolbar=null;this.#o?.destroy()}}addContainer(t){const e=this._editToolbar?.div;e?e.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){if(!this.#o){AltText.initialize(AnnotationEditor._l10n);this.#o=new AltText(this);if(this.#he){this.#o.data=this.#he;this.#he=null}await this.addEditToolbar()}}get altTextData(){return this.#o?.data}set altTextData(t){this.#o&&(this.#o.data=t)}get guessedAltText(){return this.#o?.guessedText}async setGuessedAltText(t){await(this.#o?.setGuessedText(t))}serializeAltText(t){return this.#o?.serialize(t)}hasAltText(){return!!this.#o&&!this.#o.isEmpty()}hasAltTextData(){return this.#o?.hasData()??!1}render(){this.div=document.createElement("div");this.div.setAttribute("data-editor-rotation",(360-this.rotation)%360);this.div.className=this.name;this.div.setAttribute("id",this.id);this.div.tabIndex=this.#ce?-1:0;this._isVisible||this.div.classList.add("hidden");this.setInForeground();this.#Ue();const[t,e]=this.parentDimensions;if(this.parentRotation%180!=0){this.div.style.maxWidth=`${(100*e/t).toFixed(2)}%`;this.div.style.maxHeight=`${(100*t/e).toFixed(2)}%`}const[i,s]=this.getInitialTranslation();this.translate(i,s);bindEvents(this,this.div,["pointerdown"]);this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#Pe||=new TouchManager({container:this.div,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#Ge.bind(this),onPinching:this.#$e.bind(this),onPinchEnd:this.#Ve.bind(this),signal:this._uiManager._signal}));this._uiManager._editorUndoBar?.hide();return this.div}#Ge(){this.#be={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};this.#o?.toggle(!1);this.parent.togglePointerEvents(!1)}#$e(t,e,i){let s=i/e*.7+1-.7;if(1===s)return;const n=this.#Le(this.rotation),transf=(t,e)=>[n[0]*t+n[2]*e,n[1]*t+n[3]*e],[a,r]=this.parentDimensions,o=this.x,l=this.y,h=this.width,d=this.height,c=AnnotationEditor.MIN_SIZE/a,u=AnnotationEditor.MIN_SIZE/r;s=Math.max(Math.min(s,1/h,1/d),c/h,u/d);const p=AnnotationEditor._round(h*s),g=AnnotationEditor._round(d*s);if(p===h&&g===d)return;this.#ye||=[o,l,h,d];const m=transf(h/2,d/2),f=AnnotationEditor._round(o+m[0]),b=AnnotationEditor._round(l+m[1]),A=transf(p/2,g/2);this.x=f-A[0];this.y=b-A[1];this.width=p;this.height=g;this.setDims(a*p,r*g);this.fixAndSetPosition();this._onResizing()}#Ve(){this.#o?.toggle(!0);this.parent.togglePointerEvents(!0);this.#He()}pointerdown(t){const{isMac:e}=util_FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)t.preventDefault();else{this.#ve=!0;this._isDraggable?this.#je(t):this.#We(t)}}get isSelected(){return this._uiManager.isSelected(this)}#We(t){const{isMac:e}=util_FeatureTest.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)}#je(t){const{isSelected:e}=this;this._uiManager.setUpDragSession();let i=!1;const s=new AbortController,n=this._uiManager.combinedSignal(s),a={capture:!0,passive:!1,signal:n},cancelDrag=t=>{s.abort();this.#ue=null;this.#ve=!1;this._uiManager.endDragSession()||this.#We(t);i&&this._onStopDragging()};if(e){this.#Ce=t.clientX;this.#Te=t.clientY;this.#ue=t.pointerId;this.#pe=t.pointerType;window.addEventListener("pointermove",(t=>{if(!i){i=!0;this._onStartDragging()}const{clientX:e,clientY:s,pointerId:n}=t;if(n!==this.#ue){stopEvent(t);return}const[a,r]=this.screenToPageTranslation(e-this.#Ce,s-this.#Te);this.#Ce=e;this.#Te=s;this._uiManager.dragSelectedEditors(a,r)}),a);window.addEventListener("touchmove",stopEvent,a);window.addEventListener("pointerdown",(t=>{t.pointerType===this.#pe&&(this.#Pe||t.isPrimary)&&cancelDrag(t);stopEvent(t)}),a)}const pointerUpCallback=t=>{this.#ue&&this.#ue!==t.pointerId?stopEvent(t):cancelDrag(t)};window.addEventListener("pointerup",pointerUpCallback,{signal:n});window.addEventListener("blur",pointerUpCallback,{signal:n})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#Se&&clearTimeout(this.#Se);this.#Se=setTimeout((()=>{this.#Se=null;this.parent?.moveEditorInDOM(this)}),0)}_setParentAndPosition(t,e,i){t.changeParent(this);this.x=e;this.y=i;this.fixAndSetPosition();this._onTranslated()}getRect(t,e,i=this.rotation){const s=this.parentScale,[n,a]=this.pageDimensions,[r,o]=this.pageTranslation,l=t/s,h=e/s,d=this.x*n,c=this.y*a,u=this.width*n,p=this.height*a;switch(i){case 0:return[d+l+r,a-c-h-p+o,d+l+u+r,a-c-h+o];case 90:return[d+h+r,a-c+l+o,d+h+p+r,a-c+l+u+o];case 180:return[d-l-u+r,a-c+h+o,d-l+r,a-c+h+p+o];case 270:return[d-h-p+r,a-c-l-u+o,d-h+r,a-c-l+o];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,e){const[i,s,n,a]=t,r=n-i,o=a-s;switch(this.rotation){case 0:return[i,e-a,r,o];case 90:return[i,e-s,o,r];case 180:return[n,e-s,r,o];case 270:return[n,e-a,o,r];default:throw new Error("Invalid rotation")}}onceAdded(t){}isEmpty(){return!1}enableEditMode(){this.#_e=!0}disableEditMode(){this.#_e=!1}isInEditMode(){return this.#_e}shouldGetKeyboardEvents(){return this.#Ee}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){const{top:t,left:e,bottom:i,right:s}=this.getClientDimensions(),{innerHeight:n,innerWidth:a}=window;return e0&&t0}#Ue(){if(this.#Ae||!this.div)return;this.#Ae=new AbortController;const t=this._uiManager.combinedSignal(this.#Ae);this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t});this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})}rebuild(){this.#Ue()}rotate(t){}resize(){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||""}}serialize(t=!1,e=null){unreachable("An editor must be serializable")}static async deserialize(t,e,i){const s=new this.prototype.constructor({parent:e,id:e.getNextId(),uiManager:i});s.rotation=t.rotation;s.#he=t.accessibilityData;const[n,a]=s.pageDimensions,[r,o,l,h]=s.getRectInCurrentCoords(t.rect,a);s.x=r/n;s.y=o/a;s.width=l/n;s.height=h/a;return s}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||null!==this.serialize())}remove(){this.#Ae?.abort();this.#Ae=null;this.isEmpty()||this.commit();this.parent?this.parent.remove(this):this._uiManager.removeEditor(this);if(this.#Se){clearTimeout(this.#Se);this.#Se=null}this.#Re();this.removeEditToolbar();if(this.#Me){for(const t of this.#Me.values())clearTimeout(t);this.#Me=null}this.parent=null;this.#Pe?.destroy();this.#Pe=null}get isResizable(){return!1}makeResizable(){if(this.isResizable){this.#Oe();this.#me.classList.remove("hidden");bindEvents(this,this.div,["keydown"])}}get toolbarPosition(){return null}keydown(t){if(!this.isResizable||t.target!==this.div||"Enter"!==t.key)return;this._uiManager.setSelected(this);this.#be={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const e=this.#me.children;if(!this.#de){this.#de=Array.from(e);const t=this.#qe.bind(this),i=this.#Xe.bind(this),s=this._uiManager._signal;for(const e of this.#de){const n=e.getAttribute("data-resizer-name");e.setAttribute("role","spinbutton");e.addEventListener("keydown",t,{signal:s});e.addEventListener("blur",i,{signal:s});e.addEventListener("focus",this.#Ke.bind(this,n),{signal:s});e.setAttribute("data-l10n-id",AnnotationEditor._l10nResizer[n])}}const i=this.#de[0];let s=0;for(const t of e){if(t===i)break;s++}const n=(360-this.rotation+this.parentRotation)%360/90*(this.#de.length/4);if(n!==s){if(ns)for(let t=0;t{this.div?.classList.contains("selectedEditor")&&this._editToolbar?.show()}))}unselect(){this.#me?.classList.add("hidden");this.div?.classList.remove("selectedEditor");this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0});this._editToolbar?.hide();this.#o?.toggleAltTextBadge(!0)}updateParams(t,e){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return this.#xe}set isEditing(t){this.#xe=t;if(this.parent)if(t){this.parent.setSelected(this);this.parent.setActiveEditor(this)}else this.parent.setActiveEditor(null)}setAspectRatio(t,e){this.#ge=!0;const i=t/e,{style:s}=this.div;s.aspectRatio=i;s.height="auto"}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(t,e=!1){if(e){this.#Me||=new Map;const{action:e}=t;let i=this.#Me.get(e);i&&clearTimeout(i);i=setTimeout((()=>{this._reportTelemetry(t);this.#Me.delete(e);0===this.#Me.size&&(this.#Me=null)}),AnnotationEditor._telemetryTimeout);this.#Me.set(e,i)}else{t.type||=this.editorType;this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:t}})}}show(t=this._isVisible){this.div.classList.toggle("hidden",!t);this._isVisible=t}enable(){this.div&&(this.div.tabIndex=0);this.#ce=!1}disable(){this.div&&(this.div.tabIndex=-1);this.#ce=!0}renderAnnotationElement(t){let e=t.container.querySelector(".annotationContent");if(e){if("CANVAS"===e.nodeName){const t=e;e=document.createElement("div");e.classList.add("annotationContent",this.editorType);t.before(e)}}else{e=document.createElement("div");e.classList.add("annotationContent",this.editorType);t.container.prepend(e)}return e}resetAnnotationElement(t){const{firstChild:e}=t.container;"DIV"===e?.nodeName&&e.classList.contains("annotationContent")&&e.remove()}}class FakeEditor extends AnnotationEditor{constructor(t){super(t);this.annotationElementId=t.annotationElementId;this.deleted=!0}serialize(){return this.serializeDeleted()}}const st=3285377520,nt=4294901760,at=65535;class MurmurHash3_64{constructor(t){this.h1=t?4294967295&t:st;this.h2=t?4294967295&t:st}update(t){let e,i;if("string"==typeof t){e=new Uint8Array(2*t.length);i=0;for(let s=0,n=t.length;s>>8;e[i++]=255&n}}}else{if(!ArrayBuffer.isView(t))throw new Error("Invalid data format, must be a string or TypedArray.");e=t.slice();i=e.byteLength}const s=i>>2,n=i-4*s,a=new Uint32Array(e.buffer,0,s);let r=0,o=0,l=this.h1,h=this.h2;const d=3432918353,c=461845907,u=11601,p=13715;for(let t=0;t>>17;r=r*c&nt|r*p&at;l^=r;l=l<<13|l>>>19;l=5*l+3864292196}else{o=a[t];o=o*d&nt|o*u&at;o=o<<15|o>>>17;o=o*c&nt|o*p&at;h^=o;h=h<<13|h>>>19;h=5*h+3864292196}r=0;switch(n){case 3:r^=e[4*s+2]<<16;case 2:r^=e[4*s+1]<<8;case 1:r^=e[4*s];r=r*d&nt|r*u&at;r=r<<15|r>>>17;r=r*c&nt|r*p&at;1&s?l^=r:h^=r}this.h1=l;this.h2=h}hexdigest(){let t=this.h1,e=this.h2;t^=e>>>1;t=3981806797*t&nt|36045*t&at;e=4283543511*e&nt|(2950163797*(e<<16|t>>>16)&nt)>>>16;t^=e>>>1;t=444984403*t&nt|60499*t&at;e=3301882366*e&nt|(3120437893*(e<<16|t>>>16)&nt)>>>16;t^=e>>>1;return(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const rt=Object.freeze({map:null,hash:"",transfer:void 0});class AnnotationStorage{#Qe=!1;#Je=null;#Ze=new Map;constructor(){this.onSetModified=null;this.onResetModified=null;this.onAnnotationEditor=null}getValue(t,e){const i=this.#Ze.get(t);return void 0===i?e:Object.assign(e,i)}getRawValue(t){return this.#Ze.get(t)}remove(t){this.#Ze.delete(t);0===this.#Ze.size&&this.resetModified();if("function"==typeof this.onAnnotationEditor){for(const t of this.#Ze.values())if(t instanceof AnnotationEditor)return;this.onAnnotationEditor(null)}}setValue(t,e){const i=this.#Ze.get(t);let s=!1;if(void 0!==i){for(const[t,n]of Object.entries(e))if(i[t]!==n){s=!0;i[t]=n}}else{s=!0;this.#Ze.set(t,e)}s&&this.#ti();e instanceof AnnotationEditor&&"function"==typeof this.onAnnotationEditor&&this.onAnnotationEditor(e.constructor._type)}has(t){return this.#Ze.has(t)}getAll(){return this.#Ze.size>0?objectFromMap(this.#Ze):null}setAll(t){for(const[e,i]of Object.entries(t))this.setValue(e,i)}get size(){return this.#Ze.size}#ti(){if(!this.#Qe){this.#Qe=!0;"function"==typeof this.onSetModified&&this.onSetModified()}}resetModified(){if(this.#Qe){this.#Qe=!1;"function"==typeof this.onResetModified&&this.onResetModified()}}get print(){return new PrintAnnotationStorage(this)}get serializable(){if(0===this.#Ze.size)return rt;const t=new Map,e=new MurmurHash3_64,i=[],s=Object.create(null);let n=!1;for(const[i,a]of this.#Ze){const r=a instanceof AnnotationEditor?a.serialize(!1,s):a;if(r){t.set(i,r);e.update(`${i}:${JSON.stringify(r)}`);n||=!!r.bitmap}}if(n)for(const e of t.values())e.bitmap&&i.push(e.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:i}:rt}get editorStats(){let t=null;const e=new Map;for(const i of this.#Ze.values()){if(!(i instanceof AnnotationEditor))continue;const s=i.telemetryFinalData;if(!s)continue;const{type:n}=s;e.has(n)||e.set(n,Object.getPrototypeOf(i).constructor);t||=Object.create(null);const a=t[n]||=new Map;for(const[t,e]of Object.entries(s)){if("type"===t)continue;let i=a.get(t);if(!i){i=new Map;a.set(t,i)}const s=i.get(e)??0;i.set(e,s+1)}}for(const[i,s]of e)t[i]=s.computeTelemetryFinalData(t[i]);return t}resetModifiedIds(){this.#Je=null}get modifiedIds(){if(this.#Je)return this.#Je;const t=[];for(const e of this.#Ze.values())e instanceof AnnotationEditor&&e.annotationElementId&&e.serialize()&&t.push(e.annotationElementId);return this.#Je={ids:new Set(t),hash:t.join(",")}}}class PrintAnnotationStorage extends AnnotationStorage{#ei;constructor(t){super();const{map:e,hash:i,transfer:s}=t.serializable,n=structuredClone(e,s?{transfer:s}:null);this.#ei={map:n,hash:i,transfer:s}}get print(){unreachable("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#ei}get modifiedIds(){return shadow(this,"modifiedIds",{ids:new Set,hash:""})}}class FontLoader{#ii=new Set;constructor({ownerDocument:t=globalThis.document,styleElement:e=null}){this._document=t;this.nativeFontFaces=new Set;this.styleElement=null;this.loadingRequests=[];this.loadTestFontId=0}addNativeFontFace(t){this.nativeFontFaces.add(t);this._document.fonts.add(t)}removeNativeFontFace(t){this.nativeFontFaces.delete(t);this._document.fonts.delete(t)}insertRule(t){if(!this.styleElement){this.styleElement=this._document.createElement("style");this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement)}const e=this.styleElement.sheet;e.insertRule(t,e.cssRules.length)}clear(){for(const t of this.nativeFontFaces)this._document.fonts.delete(t);this.nativeFontFaces.clear();this.#ii.clear();if(this.styleElement){this.styleElement.remove();this.styleElement=null}}async loadSystemFont({systemFontInfo:t,_inspectFont:e}){if(t&&!this.#ii.has(t.loadedName)){assert(!this.disableFontFace,"loadSystemFont shouldn't be called when `disableFontFace` is set.");if(this.isFontLoadingAPISupported){const{loadedName:i,src:s,style:n}=t,a=new FontFace(i,s,n);this.addNativeFontFace(a);try{await a.load();this.#ii.add(i);e?.(t)}catch{warn(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`);this.removeNativeFontFace(a)}}else unreachable("Not implemented: loadSystemFont without the Font Loading API.")}}async bind(t){if(t.attached||t.missingFile&&!t.systemFontInfo)return;t.attached=!0;if(t.systemFontInfo){await this.loadSystemFont(t);return}if(this.isFontLoadingAPISupported){const e=t.createNativeFontFace();if(e){this.addNativeFontFace(e);try{await e.loaded}catch(i){warn(`Failed to load font '${e.family}': '${i}'.`);t.disableFontFace=!0;throw i}}return}const e=t.createFontFaceRule();if(e){this.insertRule(e);if(this.isSyncFontLoadingSupported)return;await new Promise((e=>{const i=this._queueLoadingCallback(e);this._prepareFontLoadEvent(t,i)}))}}get isFontLoadingAPISupported(){return shadow(this,"isFontLoadingAPISupported",!!this._document?.fonts)}get isSyncFontLoadingSupported(){let t=!1;(e||"undefined"!=typeof navigator&&"string"==typeof navigator?.userAgent&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(t=!0);return shadow(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){const{loadingRequests:e}=this,i={done:!1,complete:function completeRequest(){assert(!i.done,"completeRequest() cannot be called twice.");i.done=!0;for(;e.length>0&&e[0].done;){const t=e.shift();setTimeout(t.callback,0)}},callback:t};e.push(i);return i}get _loadTestFont(){return shadow(this,"_loadTestFont",atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA=="))}_prepareFontLoadEvent(t,e){function int32(t,e){return t.charCodeAt(e)<<24|t.charCodeAt(e+1)<<16|t.charCodeAt(e+2)<<8|255&t.charCodeAt(e+3)}function spliceString(t,e,i,s){return t.substring(0,e)+s+t.substring(e+i)}let i,s;const n=this._document.createElement("canvas");n.width=1;n.height=1;const a=n.getContext("2d");let r=0;const o=`lt${Date.now()}${this.loadTestFontId++}`;let l=this._loadTestFont;l=spliceString(l,976,o.length,o);const h=1482184792;let d=int32(l,16);for(i=0,s=o.length-3;i>24&255,t>>16&255,t>>8&255,255&t)}(d));const c=`@font-face {font-family:"${o}";src:${`url(data:font/opentype;base64,${btoa(l)});`}}`;this.insertRule(c);const u=this._document.createElement("div");u.style.visibility="hidden";u.style.width=u.style.height="10px";u.style.position="absolute";u.style.top=u.style.left="0px";for(const e of[t.loadedName,o]){const t=this._document.createElement("span");t.textContent="Hi";t.style.fontFamily=e;u.append(t)}this._document.body.append(u);!function isFontReady(t,e){if(++r>30){warn("Load test font never loaded.");e();return}a.font="30px "+t;a.fillText(".",0,20);a.getImageData(0,0,1,1).data[3]>0?e():setTimeout(isFontReady.bind(null,t,e))}(o,(()=>{u.remove();e.complete()}))}}class FontFaceObject{constructor(t,{disableFontFace:e=!1,fontExtraProperties:i=!1,inspectFont:s=null}){this.compiledGlyphs=Object.create(null);for(const e in t)this[e]=t[e];this.disableFontFace=!0===e;this.fontExtraProperties=!0===i;this._inspectFont=s}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let t;if(this.cssFontInfo){const e={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(e.style=`oblique ${this.cssFontInfo.italicAngle}deg`);t=new FontFace(this.cssFontInfo.fontFamily,this.data,e)}else t=new FontFace(this.loadedName,this.data,{});this._inspectFont?.(this);return t}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;const t=`url(data:${this.mimetype};base64,${function toBase64Util(t){return Uint8Array.prototype.toBase64?t.toBase64():btoa(bytesToString(t))}(this.data)});`;let e;if(this.cssFontInfo){let i=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(i+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`);e=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${i}src:${t}}`}else e=`@font-face {font-family:"${this.loadedName}";src:${t}}`;this._inspectFont?.(this,t);return e}getPathGenerator(t,e){if(void 0!==this.compiledGlyphs[e])return this.compiledGlyphs[e];const i=this.loadedName+"_path_"+e;let s;try{s=t.get(i)}catch(t){warn(`getPathGenerator - ignoring character: "${t}".`)}const n=new Path2D(s||"");this.fontExtraProperties||t.delete(i);return this.compiledGlyphs[e]=n}}const ot=1,lt=2,ht=1,dt=2,ct=3,ut=4,pt=5,gt=6,mt=7,ft=8;function onFn(){}function wrapReason(t){if(t instanceof AbortException||t instanceof InvalidPDFException||t instanceof MissingPDFException||t instanceof PasswordException||t instanceof UnexpectedResponseException||t instanceof UnknownErrorException)return t;t instanceof Error||"object"==typeof t&&null!==t||unreachable('wrapReason: Expected "reason" to be a (possibly cloned) Error.');switch(t.name){case"AbortException":return new AbortException(t.message);case"InvalidPDFException":return new InvalidPDFException(t.message);case"MissingPDFException":return new MissingPDFException(t.message);case"PasswordException":return new PasswordException(t.message,t.code);case"UnexpectedResponseException":return new UnexpectedResponseException(t.message,t.status);case"UnknownErrorException":return new UnknownErrorException(t.message,t.details)}return new UnknownErrorException(t.message,t.toString())}class MessageHandler{#si=new AbortController;constructor(t,e,i){this.sourceName=t;this.targetName=e;this.comObj=i;this.callbackId=1;this.streamId=1;this.streamSinks=Object.create(null);this.streamControllers=Object.create(null);this.callbackCapabilities=Object.create(null);this.actionHandler=Object.create(null);i.addEventListener("message",this.#ni.bind(this),{signal:this.#si.signal})}#ni({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream){this.#ai(t);return}if(t.callback){const e=t.callbackId,i=this.callbackCapabilities[e];if(!i)throw new Error(`Cannot resolve callback ${e}`);delete this.callbackCapabilities[e];if(t.callback===ot)i.resolve(t.data);else{if(t.callback!==lt)throw new Error("Unexpected callback case");i.reject(wrapReason(t.reason))}return}const e=this.actionHandler[t.action];if(!e)throw new Error(`Unknown action from worker: ${t.action}`);if(t.callbackId){const i=this.sourceName,s=t.sourceName,n=this.comObj;Promise.try(e,t.data).then((function(e){n.postMessage({sourceName:i,targetName:s,callback:ot,callbackId:t.callbackId,data:e})}),(function(e){n.postMessage({sourceName:i,targetName:s,callback:lt,callbackId:t.callbackId,reason:wrapReason(e)})}))}else t.streamId?this.#ri(t):e(t.data)}on(t,e){const i=this.actionHandler;if(i[t])throw new Error(`There is already an actionName called "${t}"`);i[t]=e}send(t,e,i){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,data:e},i)}sendWithPromise(t,e,i){const s=this.callbackId++,n=Promise.withResolvers();this.callbackCapabilities[s]=n;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:s,data:e},i)}catch(t){n.reject(t)}return n.promise}sendWithStream(t,e,i,s){const n=this.streamId++,a=this.sourceName,r=this.targetName,o=this.comObj;return new ReadableStream({start:i=>{const l=Promise.withResolvers();this.streamControllers[n]={controller:i,startCall:l,pullCall:null,cancelCall:null,isClosed:!1};o.postMessage({sourceName:a,targetName:r,action:t,streamId:n,data:e,desiredSize:i.desiredSize},s);return l.promise},pull:t=>{const e=Promise.withResolvers();this.streamControllers[n].pullCall=e;o.postMessage({sourceName:a,targetName:r,stream:gt,streamId:n,desiredSize:t.desiredSize});return e.promise},cancel:t=>{assert(t instanceof Error,"cancel must have a valid reason");const e=Promise.withResolvers();this.streamControllers[n].cancelCall=e;this.streamControllers[n].isClosed=!0;o.postMessage({sourceName:a,targetName:r,stream:ht,streamId:n,reason:wrapReason(t)});return e.promise}},i)}#ri(t){const e=t.streamId,i=this.sourceName,s=t.sourceName,n=this.comObj,a=this,r=this.actionHandler[t.action],o={enqueue(t,a=1,r){if(this.isCancelled)return;const o=this.desiredSize;this.desiredSize-=a;if(o>0&&this.desiredSize<=0){this.sinkCapability=Promise.withResolvers();this.ready=this.sinkCapability.promise}n.postMessage({sourceName:i,targetName:s,stream:ut,streamId:e,chunk:t},r)},close(){if(!this.isCancelled){this.isCancelled=!0;n.postMessage({sourceName:i,targetName:s,stream:ct,streamId:e});delete a.streamSinks[e]}},error(t){assert(t instanceof Error,"error must have a valid reason");if(!this.isCancelled){this.isCancelled=!0;n.postMessage({sourceName:i,targetName:s,stream:pt,streamId:e,reason:wrapReason(t)})}},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};o.sinkCapability.resolve();o.ready=o.sinkCapability.promise;this.streamSinks[e]=o;Promise.try(r,t.data,o).then((function(){n.postMessage({sourceName:i,targetName:s,stream:ft,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:i,targetName:s,stream:ft,streamId:e,reason:wrapReason(t)})}))}#ai(t){const e=t.streamId,i=this.sourceName,s=t.sourceName,n=this.comObj,a=this.streamControllers[e],r=this.streamSinks[e];switch(t.stream){case ft:t.success?a.startCall.resolve():a.startCall.reject(wrapReason(t.reason));break;case mt:t.success?a.pullCall.resolve():a.pullCall.reject(wrapReason(t.reason));break;case gt:if(!r){n.postMessage({sourceName:i,targetName:s,stream:mt,streamId:e,success:!0});break}r.desiredSize<=0&&t.desiredSize>0&&r.sinkCapability.resolve();r.desiredSize=t.desiredSize;Promise.try(r.onPull||onFn).then((function(){n.postMessage({sourceName:i,targetName:s,stream:mt,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:i,targetName:s,stream:mt,streamId:e,reason:wrapReason(t)})}));break;case ut:assert(a,"enqueue should have stream controller");if(a.isClosed)break;a.controller.enqueue(t.chunk);break;case ct:assert(a,"close should have stream controller");if(a.isClosed)break;a.isClosed=!0;a.controller.close();this.#oi(a,e);break;case pt:assert(a,"error should have stream controller");a.controller.error(wrapReason(t.reason));this.#oi(a,e);break;case dt:t.success?a.cancelCall.resolve():a.cancelCall.reject(wrapReason(t.reason));this.#oi(a,e);break;case ht:if(!r)break;const o=wrapReason(t.reason);Promise.try(r.onCancel||onFn,o).then((function(){n.postMessage({sourceName:i,targetName:s,stream:dt,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:i,targetName:s,stream:dt,streamId:e,reason:wrapReason(t)})}));r.sinkCapability.reject(o);r.isCancelled=!0;delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}}async#oi(t,e){await Promise.allSettled([t.startCall?.promise,t.pullCall?.promise,t.cancelCall?.promise]);delete this.streamControllers[e]}destroy(){this.#si?.abort();this.#si=null}}class BaseCanvasFactory{#li=!1;constructor({enableHWA:t=!1}){this.#li=t}create(t,e){if(t<=0||e<=0)throw new Error("Invalid canvas size");const i=this._createCanvas(t,e);return{canvas:i,context:i.getContext("2d",{willReadFrequently:!this.#li})}}reset(t,e,i){if(!t.canvas)throw new Error("Canvas is not specified");if(e<=0||i<=0)throw new Error("Invalid canvas size");t.canvas.width=e;t.canvas.height=i}destroy(t){if(!t.canvas)throw new Error("Canvas is not specified");t.canvas.width=0;t.canvas.height=0;t.canvas=null;t.context=null}_createCanvas(t,e){unreachable("Abstract method `_createCanvas` called.")}}class BaseCMapReaderFactory{constructor({baseUrl:t=null,isCompressed:e=!0}){this.baseUrl=t;this.isCompressed=e}async fetch({name:t}){if(!this.baseUrl)throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.");if(!t)throw new Error("CMap name must be specified.");const e=this.baseUrl+t+(this.isCompressed?".bcmap":"");return this._fetch(e).then((t=>({cMapData:t,isCompressed:this.isCompressed}))).catch((t=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${e}`)}))}async _fetch(t){unreachable("Abstract method `_fetch` called.")}}class DOMCMapReaderFactory extends BaseCMapReaderFactory{async _fetch(t){const e=await fetchData(t,this.isCompressed?"arraybuffer":"text");return e instanceof ArrayBuffer?new Uint8Array(e):stringToBytes(e)}}class BaseFilterFactory{addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addHighlightHCMFilter(t,e,i,s,n){return"none"}destroy(t=!1){}}class BaseStandardFontDataFactory{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");if(!t)throw new Error("Font filename must be specified.");const e=`${this.baseUrl}${t}`;return this._fetch(e).catch((t=>{throw new Error(`Unable to load font data at: ${e}`)}))}async _fetch(t){unreachable("Abstract method `_fetch` called.")}}class DOMStandardFontDataFactory extends BaseStandardFontDataFactory{async _fetch(t){const e=await fetchData(t,"arraybuffer");return new Uint8Array(e)}}e&&warn("Please use the `legacy` build in Node.js environments.");async function node_utils_fetchData(t){const e=process.getBuiltinModule("fs"),i=await e.promises.readFile(t);return new Uint8Array(i)}const bt="Fill",At="Stroke",wt="Shading";function applyBoundingBox(t,e){if(!e)return;const i=e[2]-e[0],s=e[3]-e[1],n=new Path2D;n.rect(e[0],e[1],i,s);t.clip(n)}class BaseShadingPattern{getPattern(){unreachable("Abstract method `getPattern` called.")}}class RadialAxialShadingPattern extends BaseShadingPattern{constructor(t){super();this._type=t[1];this._bbox=t[2];this._colorStops=t[3];this._p0=t[4];this._p1=t[5];this._r0=t[6];this._r1=t[7];this.matrix=null}_createGradient(t){let e;"axial"===this._type?e=t.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):"radial"===this._type&&(e=t.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(const t of this._colorStops)e.addColorStop(t[0],t[1]);return e}getPattern(t,e,i,s){let n;if(s===At||s===bt){const a=e.current.getClippedPathBoundingBox(s,getCurrentTransform(t))||[0,0,0,0],r=Math.ceil(a[2]-a[0])||1,o=Math.ceil(a[3]-a[1])||1,l=e.cachedCanvases.getCanvas("pattern",r,o),h=l.context;h.clearRect(0,0,h.canvas.width,h.canvas.height);h.beginPath();h.rect(0,0,h.canvas.width,h.canvas.height);h.translate(-a[0],-a[1]);i=Util.transform(i,[1,0,0,1,a[0],a[1]]);h.transform(...e.baseTransform);this.matrix&&h.transform(...this.matrix);applyBoundingBox(h,this._bbox);h.fillStyle=this._createGradient(h);h.fill();n=t.createPattern(l.canvas,"no-repeat");const d=new DOMMatrix(i);n.setTransform(d)}else{applyBoundingBox(t,this._bbox);n=this._createGradient(t)}return n}}function drawTriangle(t,e,i,s,n,a,r,o){const l=e.coords,h=e.colors,d=t.data,c=4*t.width;let u;if(l[i+1]>l[s+1]){u=i;i=s;s=u;u=a;a=r;r=u}if(l[s+1]>l[n+1]){u=s;s=n;n=u;u=r;r=o;o=u}if(l[i+1]>l[s+1]){u=i;i=s;s=u;u=a;a=r;r=u}const p=(l[i]+e.offsetX)*e.scaleX,g=(l[i+1]+e.offsetY)*e.scaleY,m=(l[s]+e.offsetX)*e.scaleX,f=(l[s+1]+e.offsetY)*e.scaleY,b=(l[n]+e.offsetX)*e.scaleX,A=(l[n+1]+e.offsetY)*e.scaleY;if(g>=A)return;const w=h[a],v=h[a+1],y=h[a+2],x=h[r],_=h[r+1],E=h[r+2],S=h[o],C=h[o+1],T=h[o+2],M=Math.round(g),P=Math.round(A);let D,k,R,I,F,L,O,N;for(let t=M;t<=P;t++){if(tA?1:f===A?0:(f-t)/(f-A);D=m-(m-b)*e;k=x-(x-S)*e;R=_-(_-C)*e;I=E-(E-T)*e}let e;e=tA?1:(g-t)/(g-A);F=p-(p-b)*e;L=w-(w-S)*e;O=v-(v-C)*e;N=y-(y-T)*e;const i=Math.round(Math.min(D,F)),s=Math.round(Math.max(D,F));let n=c*t+4*i;for(let t=i;t<=s;t++){e=(D-t)/(D-F);e<0?e=0:e>1&&(e=1);d[n++]=k-(k-L)*e|0;d[n++]=R-(R-O)*e|0;d[n++]=I-(I-N)*e|0;d[n++]=255}}}function drawFigure(t,e,i){const s=e.coords,n=e.colors;let a,r;switch(e.type){case"lattice":const o=e.verticesPerRow,l=Math.floor(s.length/o)-1,h=o-1;for(a=0;a=Math.ceil(p*b)?w=o:y=!0;E>=Math.ceil(g*A)?v=l:x=!0;const S=this.getSizeAndScale(w,this.ctx.canvas.width,b),C=this.getSizeAndScale(v,this.ctx.canvas.height,A),T=t.cachedCanvases.getCanvas("pattern",S.size,C.size),M=T.context,P=r.createCanvasGraphics(M);P.groupLevel=t.groupLevel;this.setFillAndStrokeStyleToContext(P,s,a);M.translate(-S.scale*h,-C.scale*d);P.transform(S.scale,0,0,C.scale,0,0);M.save();this.clipBbox(P,h,d,c,u);P.baseTransform=getCurrentTransform(P.ctx);P.executeOperatorList(i);P.endDrawing();M.restore();if(y||x){const e=T.canvas;y&&(w=o);x&&(v=l);const i=this.getSizeAndScale(w,this.ctx.canvas.width,b),s=this.getSizeAndScale(v,this.ctx.canvas.height,A),n=i.size,a=s.size,r=t.cachedCanvases.getCanvas("pattern-workaround",n,a),c=r.context,u=y?Math.floor(p/o):0,m=x?Math.floor(g/l):0;for(let t=0;t<=u;t++)for(let i=0;i<=m;i++)c.drawImage(e,n*t,a*i,n,a,0,0,n,a);return{canvas:r.canvas,scaleX:i.scale,scaleY:s.scale,offsetX:h,offsetY:d}}return{canvas:T.canvas,scaleX:S.scale,scaleY:C.scale,offsetX:h,offsetY:d}}getSizeAndScale(t,e,i){const s=Math.max(TilingPattern.MAX_PATTERN_SIZE,e);let n=Math.ceil(t*i);n>=s?n=s:i=n/t;return{scale:i,size:n}}clipBbox(t,e,i,s,n){const a=s-e,r=n-i;t.ctx.rect(e,i,a,r);t.current.updateRectMinMax(getCurrentTransform(t.ctx),[e,i,s,n]);t.clip();t.endPath()}setFillAndStrokeStyleToContext(t,e,i){const s=t.ctx,n=t.current;switch(e){case vt:const t=this.ctx;s.fillStyle=t.fillStyle;s.strokeStyle=t.strokeStyle;n.fillColor=t.fillStyle;n.strokeColor=t.strokeStyle;break;case yt:const a=Util.makeHexColor(i[0],i[1],i[2]);s.fillStyle=a;s.strokeStyle=a;n.fillColor=a;n.strokeColor=a;break;default:throw new FormatError(`Unsupported paint type: ${e}`)}}getPattern(t,e,i,s){let n=i;if(s!==wt){n=Util.transform(n,e.baseTransform);this.matrix&&(n=Util.transform(n,this.matrix))}const a=this.createPatternCanvas(e);let r=new DOMMatrix(n);r=r.translate(a.offsetX,a.offsetY);r=r.scale(1/a.scaleX,1/a.scaleY);const o=t.createPattern(a.canvas,"repeat");o.setTransform(r);return o}}function convertBlackAndWhiteToRGBA({src:t,srcPos:e=0,dest:i,width:s,height:n,nonBlackColor:a=4294967295,inverseDecode:r=!1}){const o=util_FeatureTest.isLittleEndian?4278190080:255,[l,h]=r?[a,o]:[o,a],d=s>>3,c=7&s,u=t.length;i=new Uint32Array(i.buffer);let p=0;for(let s=0;s>2),m=i.length,f=s+7>>3,b=4294967295,A=util_FeatureTest.isLittleEndian?4278190080:255;for(u=0;uf?s:8*t-7,r=-8&a;let o=0,c=0;for(;n>=1}}for(;l=a){g=n;m=s*g}l=0;for(p=m;p--;){c[l++]=d[h++];c[l++]=d[h++];c[l++]=d[h++];c[l++]=255}t.putImageData(o,0,u*xt)}}}function putBinaryImageMask(t,e){if(e.bitmap){t.drawImage(e.bitmap,0,0);return}const i=e.height,s=e.width,n=i%xt,a=(i-n)/xt,r=0===n?a:a+1,o=t.createImageData(s,xt);let l=0;const h=e.data,d=o.data;for(let e=0;e10&&"function"==typeof i,h=l?Date.now()+15:0;let d=0;const c=this.commonObjs,u=this.objs;let p;for(;;){if(void 0!==s&&r===s.nextBreakPoint){s.breakIt(r,i);return r}p=a[r];if(p!==X.dependency)this[p].apply(this,n[r]);else for(const t of n[r]){const e=t.startsWith("g_")?c:u;if(!e.has(t)){e.get(t,i);return r}}r++;if(r===o)return r;if(l&&++d>10){if(Date.now()>h){i();return r}d=0}}}#hi(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null;this.ctx.restore();if(this.transparentCanvas){this.ctx=this.compositeCtx;this.ctx.save();this.ctx.setTransform(1,0,0,1,0,0);this.ctx.drawImage(this.transparentCanvas,0,0);this.ctx.restore();this.transparentCanvas=null}}endDrawing(){this.#hi();this.cachedCanvases.clear();this.cachedPatterns.clear();for(const t of this._cachedBitmapsMap.values()){for(const e of t.values())"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement&&(e.width=e.height=0);t.clear()}this._cachedBitmapsMap.clear();this.#di()}#di(){if(this.pageColors){const t=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if("none"!==t){const e=this.ctx.filter;this.ctx.filter=t;this.ctx.drawImage(this.ctx.canvas,0,0);this.ctx.filter=e}}}_scaleImage(t,e){const i=t.width??t.displayWidth,s=t.height??t.displayHeight;let n,a,r=Math.max(Math.hypot(e[0],e[1]),1),o=Math.max(Math.hypot(e[2],e[3]),1),l=i,h=s,d="prescale1";for(;r>2&&l>1||o>2&&h>1;){let e=l,i=h;if(r>2&&l>1){e=l>=16384?Math.floor(l/2)-1||1:Math.ceil(l/2);r/=l/e}if(o>2&&h>1){i=h>=16384?Math.floor(h/2)-1||1:Math.ceil(h)/2;o/=h/i}n=this.cachedCanvases.getCanvas(d,e,i);a=n.context;a.clearRect(0,0,e,i);a.drawImage(t,0,0,l,h,0,0,e,i);t=n.canvas;l=e;h=i;d="prescale1"===d?"prescale2":"prescale1"}return{img:t,paintWidth:l,paintHeight:h}}_createMaskCanvas(t){const e=this.ctx,{width:i,height:s}=t,n=this.current.fillColor,a=this.current.patternFill,r=getCurrentTransform(e);let o,l,h,d;if((t.bitmap||t.data)&&t.count>1){const e=t.bitmap||t.data.buffer;l=JSON.stringify(a?r:[r.slice(0,4),n]);o=this._cachedBitmapsMap.get(e);if(!o){o=new Map;this._cachedBitmapsMap.set(e,o)}const i=o.get(l);if(i&&!a){return{canvas:i,offsetX:Math.round(Math.min(r[0],r[2])+r[4]),offsetY:Math.round(Math.min(r[1],r[3])+r[5])}}h=i}if(!h){d=this.cachedCanvases.getCanvas("maskCanvas",i,s);putBinaryImageMask(d.context,t)}let c=Util.transform(r,[1/i,0,0,-1/s,0,0]);c=Util.transform(c,[1,0,0,1,0,-s]);const[u,p,g,m]=Util.getAxialAlignedBoundingBox([0,0,i,s],c),f=Math.round(g-u)||1,b=Math.round(m-p)||1,A=this.cachedCanvases.getCanvas("fillCanvas",f,b),w=A.context,v=u,y=p;w.translate(-v,-y);w.transform(...c);if(!h){h=this._scaleImage(d.canvas,getCurrentTransformInverse(w));h=h.img;o&&a&&o.set(l,h)}w.imageSmoothingEnabled=getImageSmoothingEnabled(getCurrentTransform(w),t.interpolate);drawImageAtIntegerCoords(w,h,0,0,h.width,h.height,0,0,i,s);w.globalCompositeOperation="source-in";const x=Util.transform(getCurrentTransformInverse(w),[1,0,0,1,-v,-y]);w.fillStyle=a?n.getPattern(e,this,x,bt):n;w.fillRect(0,0,i,s);if(o&&!a){this.cachedCanvases.delete("fillCanvas");o.set(l,A.canvas)}return{canvas:A.canvas,offsetX:Math.round(v),offsetY:Math.round(y)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1);this.current.lineWidth=t;this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=_t[t]}setLineJoin(t){this.ctx.lineJoin=Et[t]}setMiterLimit(t){this.ctx.miterLimit=t}setDash(t,e){const i=this.ctx;if(void 0!==i.setLineDash){i.setLineDash(t);i.lineDashOffset=e}}setRenderingIntent(t){}setFlatness(t){}setGState(t){for(const[e,i]of t)switch(e){case"LW":this.setLineWidth(i);break;case"LC":this.setLineCap(i);break;case"LJ":this.setLineJoin(i);break;case"ML":this.setMiterLimit(i);break;case"D":this.setDash(i[0],i[1]);break;case"RI":this.setRenderingIntent(i);break;case"FL":this.setFlatness(i);break;case"Font":this.setFont(i[0],i[1]);break;case"CA":this.current.strokeAlpha=i;break;case"ca":this.current.fillAlpha=i;this.ctx.globalAlpha=i;break;case"BM":this.ctx.globalCompositeOperation=i;break;case"SMask":this.current.activeSMask=i?this.tempSMask:null;this.tempSMask=null;this.checkSMaskState();break;case"TR":this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(i)}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){const t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode():!this.current.activeSMask&&t&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const t=this.ctx.canvas.width,e=this.ctx.canvas.height,i="smaskGroupAt"+this.groupLevel,s=this.cachedCanvases.getCanvas(i,t,e);this.suspendedCtx=this.ctx;this.ctx=s.context;const n=this.ctx;n.setTransform(...getCurrentTransform(this.suspendedCtx));copyCtxState(this.suspendedCtx,n);!function mirrorContextOperations(t,e){if(t._removeMirroring)throw new Error("Context is already forwarding operations.");t.__originalSave=t.save;t.__originalRestore=t.restore;t.__originalRotate=t.rotate;t.__originalScale=t.scale;t.__originalTranslate=t.translate;t.__originalTransform=t.transform;t.__originalSetTransform=t.setTransform;t.__originalResetTransform=t.resetTransform;t.__originalClip=t.clip;t.__originalMoveTo=t.moveTo;t.__originalLineTo=t.lineTo;t.__originalBezierCurveTo=t.bezierCurveTo;t.__originalRect=t.rect;t.__originalClosePath=t.closePath;t.__originalBeginPath=t.beginPath;t._removeMirroring=()=>{t.save=t.__originalSave;t.restore=t.__originalRestore;t.rotate=t.__originalRotate;t.scale=t.__originalScale;t.translate=t.__originalTranslate;t.transform=t.__originalTransform;t.setTransform=t.__originalSetTransform;t.resetTransform=t.__originalResetTransform;t.clip=t.__originalClip;t.moveTo=t.__originalMoveTo;t.lineTo=t.__originalLineTo;t.bezierCurveTo=t.__originalBezierCurveTo;t.rect=t.__originalRect;t.closePath=t.__originalClosePath;t.beginPath=t.__originalBeginPath;delete t._removeMirroring};t.save=function ctxSave(){e.save();this.__originalSave()};t.restore=function ctxRestore(){e.restore();this.__originalRestore()};t.translate=function ctxTranslate(t,i){e.translate(t,i);this.__originalTranslate(t,i)};t.scale=function ctxScale(t,i){e.scale(t,i);this.__originalScale(t,i)};t.transform=function ctxTransform(t,i,s,n,a,r){e.transform(t,i,s,n,a,r);this.__originalTransform(t,i,s,n,a,r)};t.setTransform=function ctxSetTransform(t,i,s,n,a,r){e.setTransform(t,i,s,n,a,r);this.__originalSetTransform(t,i,s,n,a,r)};t.resetTransform=function ctxResetTransform(){e.resetTransform();this.__originalResetTransform()};t.rotate=function ctxRotate(t){e.rotate(t);this.__originalRotate(t)};t.clip=function ctxRotate(t){e.clip(t);this.__originalClip(t)};t.moveTo=function(t,i){e.moveTo(t,i);this.__originalMoveTo(t,i)};t.lineTo=function(t,i){e.lineTo(t,i);this.__originalLineTo(t,i)};t.bezierCurveTo=function(t,i,s,n,a,r){e.bezierCurveTo(t,i,s,n,a,r);this.__originalBezierCurveTo(t,i,s,n,a,r)};t.rect=function(t,i,s,n){e.rect(t,i,s,n);this.__originalRect(t,i,s,n)};t.closePath=function(){e.closePath();this.__originalClosePath()};t.beginPath=function(){e.beginPath();this.__originalBeginPath()}}(n,this.suspendedCtx);this.setGState([["BM","source-over"],["ca",1],["CA",1]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring();copyCtxState(this.ctx,this.suspendedCtx);this.ctx=this.suspendedCtx;this.suspendedCtx=null}compose(t){if(!this.current.activeSMask)return;if(t){t[0]=Math.floor(t[0]);t[1]=Math.floor(t[1]);t[2]=Math.ceil(t[2]);t[3]=Math.ceil(t[3])}else t=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const e=this.current.activeSMask,i=this.suspendedCtx;this.composeSMask(i,e,this.ctx,t);this.ctx.save();this.ctx.setTransform(1,0,0,1,0,0);this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height);this.ctx.restore()}composeSMask(t,e,i,s){const n=s[0],a=s[1],r=s[2]-n,o=s[3]-a;if(0!==r&&0!==o){this.genericComposeSMask(e.context,i,r,o,e.subtype,e.backdrop,e.transferMap,n,a,e.offsetX,e.offsetY);t.save();t.globalAlpha=1;t.globalCompositeOperation="source-over";t.setTransform(1,0,0,1,0,0);t.drawImage(i.canvas,0,0);t.restore()}}genericComposeSMask(t,e,i,s,n,a,r,o,l,h,d){let c=t.canvas,u=o-h,p=l-d;if(a){const e=Util.makeHexColor(...a);if(u<0||p<0||u+i>c.width||p+s>c.height){const t=this.cachedCanvases.getCanvas("maskExtension",i,s),n=t.context;n.drawImage(c,-u,-p);n.globalCompositeOperation="destination-atop";n.fillStyle=e;n.fillRect(0,0,i,s);n.globalCompositeOperation="source-over";c=t.canvas;u=p=0}else{t.save();t.globalAlpha=1;t.setTransform(1,0,0,1,0,0);const n=new Path2D;n.rect(u,p,i,s);t.clip(n);t.globalCompositeOperation="destination-atop";t.fillStyle=e;t.fillRect(u,p,i,s);t.restore()}}e.save();e.globalAlpha=1;e.setTransform(1,0,0,1,0,0);"Alpha"===n&&r?e.filter=this.filterFactory.addAlphaFilter(r):"Luminosity"===n&&(e.filter=this.filterFactory.addLuminosityFilter(r));const g=new Path2D;g.rect(o,l,i,s);e.clip(g);e.globalCompositeOperation="destination-in";e.drawImage(c,u,p,i,s,o,l,i,s);e.restore()}save(){if(this.inSMaskMode){copyCtxState(this.ctx,this.suspendedCtx);this.suspendedCtx.save()}else this.ctx.save();const t=this.current;this.stateStack.push(t);this.current=t.clone()}restore(){0===this.stateStack.length&&this.inSMaskMode&&this.endSMaskMode();if(0!==this.stateStack.length){this.current=this.stateStack.pop();if(this.inSMaskMode){this.suspendedCtx.restore();copyCtxState(this.suspendedCtx,this.ctx)}else this.ctx.restore();this.checkSMaskState();this.pendingClip=null;this._cachedScaleForStroking[0]=-1;this._cachedGetSinglePixelWidth=null}}transform(t,e,i,s,n,a){this.ctx.transform(t,e,i,s,n,a);this._cachedScaleForStroking[0]=-1;this._cachedGetSinglePixelWidth=null}constructPath(t,e,i){const s=this.ctx,n=this.current;let a,r,o=n.x,l=n.y;const h=getCurrentTransform(s),d=0===h[0]&&0===h[3]||0===h[1]&&0===h[2],c=d?i.slice(0):null;for(let i=0,u=0,p=t.length;i100&&(h=100);this.current.fontSizeScale=e/h;this.ctx.font=`${l} ${o} ${h}px ${r}`}setTextRenderingMode(t){this.current.textRenderingMode=t}setTextRise(t){this.current.textRise=t}moveText(t,e){this.current.x=this.current.lineX+=t;this.current.y=this.current.lineY+=e}setLeadingMoveText(t,e){this.setLeading(-e);this.moveText(t,e)}setTextMatrix(t,e,i,s,n,a){this.current.textMatrix=[t,e,i,s,n,a];this.current.textMatrixScale=Math.hypot(t,e);this.current.x=this.current.lineX=0;this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}#ci(t,e,i){const s=new Path2D;s.addPath(t,new DOMMatrix(i).invertSelf().multiplySelf(e));return s}paintChar(t,e,i,s,n){const a=this.ctx,r=this.current,o=r.font,l=r.textRenderingMode,h=r.fontSize/r.fontSizeScale,d=l&y,c=!!(l&x),u=r.patternFill&&!o.missingFile,p=r.patternStroke&&!o.missingFile;let g;(o.disableFontFace||c||u||p)&&(g=o.getPathGenerator(this.commonObjs,t));if(o.disableFontFace||u||p){a.save();a.translate(e,i);a.scale(h,-h);if(d===b||d===w)if(s){const t=a.getTransform();a.setTransform(...s);a.fill(this.#ci(g,t,s))}else a.fill(g);if(d===A||d===w)if(n){const t=a.getTransform();a.setTransform(...n);a.stroke(this.#ci(g,t,n))}else{a.lineWidth/=h;a.stroke(g)}a.restore()}else{d!==b&&d!==w||a.fillText(t,e,i);d!==A&&d!==w||a.strokeText(t,e,i)}if(c){(this.pendingTextPaths||=[]).push({transform:getCurrentTransform(a),x:e,y:i,fontSize:h,path:g})}}get isFontSubpixelAAEnabled(){const{context:t}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);t.scale(1.5,1);t.fillText("I",0,10);const e=t.getImageData(0,0,10,10).data;let i=!1;for(let t=3;t0&&e[t]<255){i=!0;break}return shadow(this,"isFontSubpixelAAEnabled",i)}showText(t){const e=this.current,i=e.font;if(i.isType3Font)return this.showType3Text(t);const s=e.fontSize;if(0===s)return;const n=this.ctx,a=e.fontSizeScale,r=e.charSpacing,o=e.wordSpacing,l=e.fontDirection,h=e.textHScale*l,d=t.length,c=i.vertical,u=c?1:-1,p=i.defaultVMetrics,g=s*e.fontMatrix[0],m=e.textRenderingMode===b&&!i.disableFontFace&&!e.patternFill;n.save();n.transform(...e.textMatrix);n.translate(e.x,e.y+e.textRise);l>0?n.scale(h,-1):n.scale(h,1);let f,v;if(e.patternFill){n.save();const t=e.fillColor.getPattern(n,this,getCurrentTransformInverse(n),bt);f=getCurrentTransform(n);n.restore();n.fillStyle=t}if(e.patternStroke){n.save();const t=e.strokeColor.getPattern(n,this,getCurrentTransformInverse(n),At);v=getCurrentTransform(n);n.restore();n.strokeStyle=t}let x=e.lineWidth;const _=e.textMatrixScale;if(0===_||0===x){const t=e.textRenderingMode&y;t!==A&&t!==w||(x=this.getSinglePixelWidth())}else x/=_;if(1!==a){n.scale(a,a);x/=a}n.lineWidth=x;if(i.isInvalidPDFjsFont){const i=[];let s=0;for(const e of t){i.push(e.unicode);s+=e.width}n.fillText(i.join(""),0,0);e.x+=s*g*h;n.restore();this.compose();return}let E,S=0;for(E=0;E0){const t=1e3*n.measureText(b).width/s*a;if(xnew CanvasGraphics(t,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};e=new TilingPattern(t,i,this.ctx,n,s)}else e=this._getPattern(t[1],t[2]);return e}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments);this.current.patternStroke=!0}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments);this.current.patternFill=!0}setStrokeRGBColor(t,e,i){this.ctx.strokeStyle=this.current.strokeColor=Util.makeHexColor(t,e,i);this.current.patternStroke=!1}setStrokeTransparent(){this.ctx.strokeStyle=this.current.strokeColor="transparent";this.current.patternStroke=!1}setFillRGBColor(t,e,i){this.ctx.fillStyle=this.current.fillColor=Util.makeHexColor(t,e,i);this.current.patternFill=!1}setFillTransparent(){this.ctx.fillStyle=this.current.fillColor="transparent";this.current.patternFill=!1}_getPattern(t,e=null){let i;if(this.cachedPatterns.has(t))i=this.cachedPatterns.get(t);else{i=function getShadingPattern(t){switch(t[0]){case"RadialAxial":return new RadialAxialShadingPattern(t);case"Mesh":return new MeshShadingPattern(t);case"Dummy":return new DummyShadingPattern}throw new Error(`Unknown IR type: ${t[0]}`)}(this.getObject(t));this.cachedPatterns.set(t,i)}e&&(i.matrix=e);return i}shadingFill(t){if(!this.contentVisible)return;const e=this.ctx;this.save();const i=this._getPattern(t);e.fillStyle=i.getPattern(e,this,getCurrentTransformInverse(e),wt);const s=getCurrentTransformInverse(e);if(s){const{width:t,height:i}=e.canvas,[n,a,r,o]=Util.getAxialAlignedBoundingBox([0,0,t,i],s);this.ctx.fillRect(n,a,r-n,o-a)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox());this.restore()}beginInlineImage(){unreachable("Should not call beginInlineImage")}beginImageData(){unreachable("Should not call beginImageData")}paintFormXObjectBegin(t,e){if(this.contentVisible){this.save();this.baseTransformStack.push(this.baseTransform);t&&this.transform(...t);this.baseTransform=getCurrentTransform(this.ctx);if(e){const t=e[2]-e[0],i=e[3]-e[1];this.ctx.rect(e[0],e[1],t,i);this.current.updateRectMinMax(getCurrentTransform(this.ctx),e);this.clip();this.endPath()}}}paintFormXObjectEnd(){if(this.contentVisible){this.restore();this.baseTransform=this.baseTransformStack.pop()}}beginGroup(t){if(!this.contentVisible)return;this.save();if(this.inSMaskMode){this.endSMaskMode();this.current.activeSMask=null}const e=this.ctx;t.isolated||info("TODO: Support non-isolated groups.");t.knockout&&warn("Knockout groups not supported.");const i=getCurrentTransform(e);t.matrix&&e.transform(...t.matrix);if(!t.bbox)throw new Error("Bounding box is required.");let s=Util.getAxialAlignedBoundingBox(t.bbox,getCurrentTransform(e));const n=[0,0,e.canvas.width,e.canvas.height];s=Util.intersect(s,n)||[0,0,0,0];const a=Math.floor(s[0]),r=Math.floor(s[1]),o=Math.max(Math.ceil(s[2])-a,1),l=Math.max(Math.ceil(s[3])-r,1);this.current.startNewPathAndClipBox([0,0,o,l]);let h="groupAt"+this.groupLevel;t.smask&&(h+="_smask_"+this.smaskCounter++%2);const d=this.cachedCanvases.getCanvas(h,o,l),c=d.context;c.translate(-a,-r);c.transform(...i);if(t.smask)this.smaskStack.push({canvas:d.canvas,context:c,offsetX:a,offsetY:r,subtype:t.smask.subtype,backdrop:t.smask.backdrop,transferMap:t.smask.transferMap||null,startTransformInverse:null});else{e.setTransform(1,0,0,1,0,0);e.translate(a,r);e.save()}copyCtxState(e,c);this.ctx=c;this.setGState([["BM","source-over"],["ca",1],["CA",1]]);this.groupStack.push(e);this.groupLevel++}endGroup(t){if(!this.contentVisible)return;this.groupLevel--;const e=this.ctx,i=this.groupStack.pop();this.ctx=i;this.ctx.imageSmoothingEnabled=!1;if(t.smask){this.tempSMask=this.smaskStack.pop();this.restore()}else{this.ctx.restore();const t=getCurrentTransform(this.ctx);this.restore();this.ctx.save();this.ctx.setTransform(...t);const i=Util.getAxialAlignedBoundingBox([0,0,e.canvas.width,e.canvas.height],t);this.ctx.drawImage(e.canvas,0,0);this.ctx.restore();this.compose(i)}}beginAnnotation(t,e,i,s,n){this.#hi();resetCtxToDefault(this.ctx);this.ctx.save();this.save();this.baseTransform&&this.ctx.setTransform(...this.baseTransform);if(e){const s=e[2]-e[0],a=e[3]-e[1];if(n&&this.annotationCanvasMap){(i=i.slice())[4]-=e[0];i[5]-=e[1];(e=e.slice())[0]=e[1]=0;e[2]=s;e[3]=a;const[n,r]=Util.singularValueDecompose2dScale(getCurrentTransform(this.ctx)),{viewportScale:o}=this,l=Math.ceil(s*this.outputScaleX*o),h=Math.ceil(a*this.outputScaleY*o);this.annotationCanvas=this.canvasFactory.create(l,h);const{canvas:d,context:c}=this.annotationCanvas;this.annotationCanvasMap.set(t,d);this.annotationCanvas.savedCtx=this.ctx;this.ctx=c;this.ctx.save();this.ctx.setTransform(n,0,0,-r,0,a*r);resetCtxToDefault(this.ctx)}else{resetCtxToDefault(this.ctx);this.endPath();this.ctx.rect(e[0],e[1],s,a);this.ctx.clip();this.ctx.beginPath()}}this.current=new CanvasExtraState(this.ctx.canvas.width,this.ctx.canvas.height);this.transform(...i);this.transform(...s)}endAnnotation(){if(this.annotationCanvas){this.ctx.restore();this.#di();this.ctx=this.annotationCanvas.savedCtx;delete this.annotationCanvas.savedCtx;delete this.annotationCanvas}}paintImageMaskXObject(t){if(!this.contentVisible)return;const e=t.count;(t=this.getObject(t.data,t)).count=e;const i=this.ctx,s=this.processingType3;if(s){void 0===s.compiled&&(s.compiled=function compileType3Glyph(t){const{width:e,height:i}=t;if(e>1e3||i>1e3)return null;const s=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),n=e+1;let a,r,o,l=new Uint8Array(n*(i+1));const h=e+7&-8;let d=new Uint8Array(h*i),c=0;for(const e of t.data){let t=128;for(;t>0;){d[c++]=e&t?0:255;t>>=1}}let u=0;c=0;if(0!==d[c]){l[0]=1;++u}for(r=1;r>2)+(d[c+1]?4:0)+(d[c-h+1]?8:0);if(s[t]){l[o+r]=s[t];++u}c++}if(d[c-h]!==d[c]){l[o+r]=d[c]?2:4;++u}if(u>1e3)return null}c=h*(i-1);o=a*n;if(0!==d[c]){l[o]=8;++u}for(r=1;r1e3)return null;const p=new Int32Array([0,n,-1,0,-n,0,0,0,1]),g=new Path2D;for(a=0;u&&a<=i;a++){let t=a*n;const i=t+e;for(;t>4;l[t]&=r>>2|r<<2}g.lineTo(t%n,t/n|0);l[t]||--u}while(s!==t);--a}d=null;l=null;return function(t){t.save();t.scale(1/e,-1/i);t.translate(0,-i);t.fill(g);t.beginPath();t.restore()}}(t));if(s.compiled){s.compiled(i);return}}const n=this._createMaskCanvas(t),a=n.canvas;i.save();i.setTransform(1,0,0,1,0,0);i.drawImage(a,n.offsetX,n.offsetY);i.restore();this.compose()}paintImageMaskXObjectRepeat(t,e,i=0,s=0,n,a){if(!this.contentVisible)return;t=this.getObject(t.data,t);const r=this.ctx;r.save();const o=getCurrentTransform(r);r.transform(e,i,s,n,0,0);const l=this._createMaskCanvas(t);r.setTransform(1,0,0,1,l.offsetX-o[4],l.offsetY-o[5]);for(let t=0,h=a.length;te?h/e:1;r=l>e?l/e:1}}this._cachedScaleForStroking[0]=a;this._cachedScaleForStroking[1]=r}return this._cachedScaleForStroking}rescaleAndStroke(t){const{ctx:e}=this,{lineWidth:i}=this.current,[s,n]=this.getScaleForStroking();e.lineWidth=i||1;if(1===s&&1===n){e.stroke();return}const a=e.getLineDash();t&&e.save();e.scale(s,n);if(a.length>0){const t=Math.max(s,n);e.setLineDash(a.map((e=>e/t)));e.lineDashOffset/=t}e.stroke();t&&e.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}}for(const t in X)void 0!==CanvasGraphics.prototype[t]&&(CanvasGraphics.prototype[X[t]]=CanvasGraphics.prototype[t]);class GlobalWorkerOptions{static#ui=null;static#pi="";static get workerPort(){return this.#ui}static set workerPort(t){if(!("undefined"!=typeof Worker&&t instanceof Worker)&&null!==t)throw new Error("Invalid `workerPort` type.");this.#ui=t}static get workerSrc(){return this.#pi}static set workerSrc(t){if("string"!=typeof t)throw new Error("Invalid `workerSrc` type.");this.#pi=t}}class Metadata{#gi;#mi;constructor({parsedData:t,rawData:e}){this.#gi=t;this.#mi=e}getRaw(){return this.#mi}get(t){return this.#gi.get(t)??null}getAll(){return objectFromMap(this.#gi)}has(t){return this.#gi.has(t)}}const Tt=Symbol("INTERNAL");class OptionalContentGroup{#fi=!1;#bi=!1;#Ai=!1;#wi=!0;constructor(t,{name:e,intent:i,usage:s,rbGroups:n}){this.#fi=!!(t&r);this.#bi=!!(t&o);this.name=e;this.intent=i;this.usage=s;this.rbGroups=n}get visible(){if(this.#Ai)return this.#wi;if(!this.#wi)return!1;const{print:t,view:e}=this.usage;return this.#fi?"OFF"!==e?.viewState:!this.#bi||"OFF"!==t?.printState}_setVisible(t,e,i=!1){t!==Tt&&unreachable("Internal method `_setVisible` called.");this.#Ai=i;this.#wi=e}}class OptionalContentConfig{#vi=null;#yi=new Map;#xi=null;#_i=null;constructor(t,e=r){this.renderingIntent=e;this.name=null;this.creator=null;if(null!==t){this.name=t.name;this.creator=t.creator;this.#_i=t.order;for(const i of t.groups)this.#yi.set(i.id,new OptionalContentGroup(e,i));if("OFF"===t.baseState)for(const t of this.#yi.values())t._setVisible(Tt,!1);for(const e of t.on)this.#yi.get(e)._setVisible(Tt,!0);for(const e of t.off)this.#yi.get(e)._setVisible(Tt,!1);this.#xi=this.getHash()}}#Ei(t){const e=t.length;if(e<2)return!0;const i=t[0];for(let s=1;s0?objectFromMap(this.#yi):null}getGroup(t){return this.#yi.get(t)||null}getHash(){if(null!==this.#vi)return this.#vi;const t=new MurmurHash3_64;for(const[e,i]of this.#yi)t.update(`${e}:${i.visible}`);return this.#vi=t.hexdigest()}}class PDFDataTransportStream{constructor(t,{disableRange:e=!1,disableStream:i=!1}){assert(t,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');const{length:s,initialData:n,progressiveDone:a,contentDispositionFilename:r}=t;this._queuedChunks=[];this._progressiveDone=a;this._contentDispositionFilename=r;if(n?.length>0){const t=n instanceof Uint8Array&&n.byteLength===n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer;this._queuedChunks.push(t)}this._pdfDataRangeTransport=t;this._isStreamingSupported=!i;this._isRangeSupported=!e;this._contentLength=s;this._fullRequestReader=null;this._rangeReaders=[];t.addRangeListener(((t,e)=>{this._onReceiveData({begin:t,chunk:e})}));t.addProgressListener(((t,e)=>{this._onProgress({loaded:t,total:e})}));t.addProgressiveReadListener((t=>{this._onReceiveData({chunk:t})}));t.addProgressiveDoneListener((()=>{this._onProgressiveDone()}));t.transportReady()}_onReceiveData({begin:t,chunk:e}){const i=e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer;if(void 0===t)this._fullRequestReader?this._fullRequestReader._enqueue(i):this._queuedChunks.push(i);else{assert(this._rangeReaders.some((function(e){if(e._begin!==t)return!1;e._enqueue(i);return!0})),"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}_onProgress(t){void 0===t.total?this._rangeReaders[0]?.onProgress?.({loaded:t.loaded}):this._fullRequestReader?.onProgress?.({loaded:t.loaded,total:t.total})}_onProgressiveDone(){this._fullRequestReader?.progressiveDone();this._progressiveDone=!0}_removeRangeReader(t){const e=this._rangeReaders.indexOf(t);e>=0&&this._rangeReaders.splice(e,1)}getFullReader(){assert(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;this._queuedChunks=null;return new PDFDataTransportStreamReader(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new PDFDataTransportStreamRangeReader(this,t,e);this._pdfDataRangeTransport.requestDataRange(t,e);this._rangeReaders.push(i);return i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeReaders.slice(0))e.cancel(t);this._pdfDataRangeTransport.abort()}}class PDFDataTransportStreamReader{constructor(t,e,i=!1,s=null){this._stream=t;this._done=i||!1;this._filename=isPdfFile(s)?s:null;this._queuedChunks=e||[];this._loaded=0;for(const t of this._queuedChunks)this._loaded+=t.byteLength;this._requests=[];this._headersReady=Promise.resolve();t._fullRequestReader=this;this.onProgress=null}_enqueue(t){if(!this._done){if(this._requests.length>0){this._requests.shift().resolve({value:t,done:!1})}else this._queuedChunks.push(t);this._loaded+=t.byteLength}}get headersReady(){return this._headersReady}get filename(){return this._filename}get isRangeSupported(){return this._stream._isRangeSupported}get isStreamingSupported(){return this._stream._isStreamingSupported}get contentLength(){return this._stream._contentLength}async read(){if(this._queuedChunks.length>0){return{value:this._queuedChunks.shift(),done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||(this._done=!0)}}class PDFDataTransportStreamRangeReader{constructor(t,e,i){this._stream=t;this._begin=e;this._end=i;this._queuedChunk=null;this._requests=[];this._done=!1;this.onProgress=null}_enqueue(t){if(!this._done){if(0===this._requests.length)this._queuedChunk=t;else{this._requests.shift().resolve({value:t,done:!1});for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}this._done=!0;this._stream._removeRangeReader(this)}}get isStreamingSupported(){return!1}async read(){if(this._queuedChunk){const t=this._queuedChunk;this._queuedChunk=null;return{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0;this._stream._removeRangeReader(this)}}function createHeaders(t,e){const i=new Headers;if(!t||!e||"object"!=typeof e)return i;for(const t in e){const s=e[t];void 0!==s&&i.append(t,s)}return i}function getResponseOrigin(t){try{return new URL(t).origin}catch{}return null}function validateRangeRequestCapabilities({responseHeaders:t,isHttp:e,rangeChunkSize:i,disableRange:s}){const n={allowRangeRequests:!1,suggestedLength:void 0},a=parseInt(t.get("Content-Length"),10);if(!Number.isInteger(a))return n;n.suggestedLength=a;if(a<=2*i)return n;if(s||!e)return n;if("bytes"!==t.get("Accept-Ranges"))return n;if("identity"!==(t.get("Content-Encoding")||"identity"))return n;n.allowRangeRequests=!0;return n}function extractFilenameFromHeader(t){const e=t.get("Content-Disposition");if(e){let t=function getFilenameFromContentDispositionHeader(t){let e=!0,i=toParamRegExp("filename\\*","i").exec(t);if(i){i=i[1];let t=rfc2616unquote(i);t=unescape(t);t=rfc5987decode(t);t=rfc2047decode(t);return fixupEncoding(t)}i=function rfc2231getparam(t){const e=[];let i;const s=toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;null!==(i=s.exec(t));){let[,t,s,n]=i;t=parseInt(t,10);if(t in e){if(0===t)break}else e[t]=[s,n]}const n=[];for(let t=0;t{t._responseOrigin=getResponseOrigin(e.url);if(!validateResponseStatus(e.status))throw createResponseStatusError(e.status,s);this._reader=e.body.getReader();this._headersCapability.resolve();const i=e.headers,{allowRangeRequests:n,suggestedLength:a}=validateRangeRequestCapabilities({responseHeaders:i,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=n;this._contentLength=a||this._contentLength;this._filename=extractFilenameFromHeader(i);!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new AbortException("Streaming is disabled."))})).catch(this._headersCapability.reject);this.onProgress=null}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._headersCapability.promise;const{value:t,done:e}=await this._reader.read();if(e)return{value:t,done:e};this._loaded+=t.byteLength;this.onProgress?.({loaded:this._loaded,total:this._contentLength});return{value:getArrayBuffer(t),done:!1}}cancel(t){this._reader?.cancel(t);this._abortController.abort()}}class PDFFetchStreamRangeReader{constructor(t,e,i){this._stream=t;this._reader=null;this._loaded=0;const s=t.source;this._withCredentials=s.withCredentials||!1;this._readCapability=Promise.withResolvers();this._isStreamingSupported=!s.disableStream;this._abortController=new AbortController;const n=new Headers(t.headers);n.append("Range",`bytes=${e}-${i-1}`);const a=s.url;fetch(a,createFetchOptions(n,this._withCredentials,this._abortController)).then((e=>{const i=getResponseOrigin(e.url);if(i!==t._responseOrigin)throw new Error(`Expected range response-origin "${i}" to match "${t._responseOrigin}".`);if(!validateResponseStatus(e.status))throw createResponseStatusError(e.status,a);this._readCapability.resolve();this._reader=e.body.getReader()})).catch(this._readCapability.reject);this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();if(e)return{value:t,done:e};this._loaded+=t.byteLength;this.onProgress?.({loaded:this._loaded});return{value:getArrayBuffer(t),done:!1}}cancel(t){this._reader?.cancel(t);this._abortController.abort()}}class NetworkManager{_responseOrigin=null;constructor({url:t,httpHeaders:e,withCredentials:i}){this.url=t;this.isHttp=/^https?:/i.test(t);this.headers=createHeaders(this.isHttp,e);this.withCredentials=i||!1;this.currXhrId=0;this.pendingRequests=Object.create(null)}request(t){const e=new XMLHttpRequest,i=this.currXhrId++,s=this.pendingRequests[i]={xhr:e};e.open("GET",this.url);e.withCredentials=this.withCredentials;for(const[t,i]of this.headers)e.setRequestHeader(t,i);if(this.isHttp&&"begin"in t&&"end"in t){e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`);s.expectedStatus=206}else s.expectedStatus=200;e.responseType="arraybuffer";assert(t.onError,"Expected `onError` callback to be provided.");e.onerror=()=>{t.onError(e.status)};e.onreadystatechange=this.onStateChange.bind(this,i);e.onprogress=this.onProgress.bind(this,i);s.onHeadersReceived=t.onHeadersReceived;s.onDone=t.onDone;s.onError=t.onError;s.onProgress=t.onProgress;e.send(null);return i}onProgress(t,e){const i=this.pendingRequests[t];i&&i.onProgress?.(e)}onStateChange(t,e){const i=this.pendingRequests[t];if(!i)return;const s=i.xhr;if(s.readyState>=2&&i.onHeadersReceived){i.onHeadersReceived();delete i.onHeadersReceived}if(4!==s.readyState)return;if(!(t in this.pendingRequests))return;delete this.pendingRequests[t];if(0===s.status&&this.isHttp){i.onError(s.status);return}const n=s.status||200;if(!(200===n&&206===i.expectedStatus)&&n!==i.expectedStatus){i.onError(s.status);return}const a=function network_getArrayBuffer(t){const e=t.response;return"string"!=typeof e?e:stringToBytes(e).buffer}(s);if(206===n){const t=s.getResponseHeader("Content-Range"),e=/bytes (\d+)-(\d+)\/(\d+)/.exec(t);if(e)i.onDone({begin:parseInt(e[1],10),chunk:a});else{warn('Missing or invalid "Content-Range" header.');i.onError(0)}}else a?i.onDone({begin:0,chunk:a}):i.onError(s.status)}getRequestXhr(t){return this.pendingRequests[t].xhr}isPendingRequest(t){return t in this.pendingRequests}abortRequest(t){const e=this.pendingRequests[t].xhr;delete this.pendingRequests[t];e.abort()}}class PDFNetworkStream{constructor(t){this._source=t;this._manager=new NetworkManager(t);this._rangeChunkSize=t.rangeChunkSize;this._fullRequestReader=null;this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(t){const e=this._rangeRequestReaders.indexOf(t);e>=0&&this._rangeRequestReaders.splice(e,1)}getFullReader(){assert(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once.");this._fullRequestReader=new PDFNetworkStreamFullRequestReader(this._manager,this._source);return this._fullRequestReader}getRangeReader(t,e){const i=new PDFNetworkStreamRangeRequestReader(this._manager,t,e);i.onClosed=this._onRangeRequestReaderClosed.bind(this);this._rangeRequestReaders.push(i);return i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class PDFNetworkStreamFullRequestReader{constructor(t,e){this._manager=t;this._url=e.url;this._fullRequestId=t.request({onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)});this._headersCapability=Promise.withResolvers();this._disableRange=e.disableRange||!1;this._contentLength=e.length;this._rangeChunkSize=e.rangeChunkSize;this._rangeChunkSize||this._disableRange||(this._disableRange=!0);this._isStreamingSupported=!1;this._isRangeSupported=!1;this._cachedChunks=[];this._requests=[];this._done=!1;this._storedError=void 0;this._filename=null;this.onProgress=null}_onHeadersReceived(){const t=this._fullRequestId,e=this._manager.getRequestXhr(t);this._manager._responseOrigin=getResponseOrigin(e.responseURL);const i=e.getAllResponseHeaders(),s=new Headers(i?i.trimStart().replace(/[^\S ]+$/,"").split(/[\r\n]+/).map((t=>{const[e,...i]=t.split(": ");return[e,i.join(": ")]})):[]),{allowRangeRequests:n,suggestedLength:a}=validateRangeRequestCapabilities({responseHeaders:s,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});n&&(this._isRangeSupported=!0);this._contentLength=a||this._contentLength;this._filename=extractFilenameFromHeader(s);this._isRangeSupported&&this._manager.abortRequest(t);this._headersCapability.resolve()}_onDone(t){if(t)if(this._requests.length>0){this._requests.shift().resolve({value:t.chunk,done:!1})}else this._cachedChunks.push(t.chunk);this._done=!0;if(!(this._cachedChunks.length>0)){for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(t){this._storedError=createResponseStatusError(t,this._url);this._headersCapability.reject(this._storedError);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0;this._cachedChunks.length=0}_onProgress(t){this.onProgress?.({loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})}get filename(){return this._filename}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}get contentLength(){return this._contentLength}get headersReady(){return this._headersCapability.promise}async read(){await this._headersCapability.promise;if(this._storedError)throw this._storedError;if(this._cachedChunks.length>0){return{value:this._cachedChunks.shift(),done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;this._headersCapability.reject(t);for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0;this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId);this._fullRequestReader=null}}class PDFNetworkStreamRangeRequestReader{constructor(t,e,i){this._manager=t;this._url=t.url;this._requestId=t.request({begin:e,end:i,onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)});this._requests=[];this._queuedChunk=null;this._done=!1;this._storedError=void 0;this.onProgress=null;this.onClosed=null}_onHeadersReceived(){const t=getResponseOrigin(this._manager.getRequestXhr(this._requestId)?.responseURL);if(t!==this._manager._responseOrigin){this._storedError=new Error(`Expected range response-origin "${t}" to match "${this._manager._responseOrigin}".`);this._onError(0)}}_close(){this.onClosed?.(this)}_onDone(t){const e=t.chunk;if(this._requests.length>0){this._requests.shift().resolve({value:e,done:!1})}else this._queuedChunk=e;this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0;this._close()}_onError(t){this._storedError??=createResponseStatusError(t,this._url);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0;this._queuedChunk=null}_onProgress(t){this.isStreamingSupported||this.onProgress?.({loaded:t.loaded})}get isStreamingSupported(){return!1}async read(){if(this._storedError)throw this._storedError;if(null!==this._queuedChunk){const t=this._queuedChunk;this._queuedChunk=null;return{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0;this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId);this._close()}}const Mt=/^[a-z][a-z0-9\-+.]+:/i;class PDFNodeStream{constructor(t){this.source=t;this.url=function parseUrlOrPath(t){if(Mt.test(t))return new URL(t);const e=process.getBuiltinModule("url");return new URL(e.pathToFileURL(t))}(t.url);assert("file:"===this.url.protocol,"PDFNodeStream only supports file:// URLs.");this._fullRequestReader=null;this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){assert(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once.");this._fullRequestReader=new PDFNodeStreamFsFullReader(this);return this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new PDFNodeStreamFsRangeReader(this,t,e);this._rangeRequestReaders.push(i);return i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class PDFNodeStreamFsFullReader{constructor(t){this._url=t.url;this._done=!1;this._storedError=null;this.onProgress=null;const e=t.source;this._contentLength=e.length;this._loaded=0;this._filename=null;this._disableRange=e.disableRange||!1;this._rangeChunkSize=e.rangeChunkSize;this._rangeChunkSize||this._disableRange||(this._disableRange=!0);this._isStreamingSupported=!e.disableStream;this._isRangeSupported=!e.disableRange;this._readableStream=null;this._readCapability=Promise.withResolvers();this._headersCapability=Promise.withResolvers();const i=process.getBuiltinModule("fs");i.promises.lstat(this._url).then((t=>{this._contentLength=t.size;this._setReadableStream(i.createReadStream(this._url));this._headersCapability.resolve()}),(t=>{"ENOENT"===t.code&&(t=new MissingPDFException(`Missing PDF "${this._url}".`));this._storedError=t;this._headersCapability.reject(t)}))}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;if(this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();if(null===t){this._readCapability=Promise.withResolvers();return this.read()}this._loaded+=t.length;this.onProgress?.({loaded:this._loaded,total:this._contentLength});return{value:new Uint8Array(t).buffer,done:!1}}cancel(t){this._readableStream?this._readableStream.destroy(t):this._error(t)}_error(t){this._storedError=t;this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t;t.on("readable",(()=>{this._readCapability.resolve()}));t.on("end",(()=>{t.destroy();this._done=!0;this._readCapability.resolve()}));t.on("error",(t=>{this._error(t)}));!this._isStreamingSupported&&this._isRangeSupported&&this._error(new AbortException("streaming is disabled"));this._storedError&&this._readableStream.destroy(this._storedError)}}class PDFNodeStreamFsRangeReader{constructor(t,e,i){this._url=t.url;this._done=!1;this._storedError=null;this.onProgress=null;this._loaded=0;this._readableStream=null;this._readCapability=Promise.withResolvers();const s=t.source;this._isStreamingSupported=!s.disableStream;const n=process.getBuiltinModule("fs");this._setReadableStream(n.createReadStream(this._url,{start:e,end:i-1}))}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;if(this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();if(null===t){this._readCapability=Promise.withResolvers();return this.read()}this._loaded+=t.length;this.onProgress?.({loaded:this._loaded});return{value:new Uint8Array(t).buffer,done:!1}}cancel(t){this._readableStream?this._readableStream.destroy(t):this._error(t)}_error(t){this._storedError=t;this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t;t.on("readable",(()=>{this._readCapability.resolve()}));t.on("end",(()=>{t.destroy();this._done=!0;this._readCapability.resolve()}));t.on("error",(t=>{this._error(t)}));this._storedError&&this._readableStream.destroy(this._storedError)}}const Pt=30;class TextLayer{#Si=Promise.withResolvers();#pt=null;#Ci=!1;#Ti=!!globalThis.FontInspector?.enabled;#Mi=null;#Pi=null;#Di=0;#ki=0;#Ri=null;#Ii=null;#Fi=0;#Li=0;#Oi=Object.create(null);#Ni=[];#Bi=null;#Hi=[];#zi=new WeakMap;#Ui=null;static#Gi=new Map;static#$i=new Map;static#Vi=new WeakMap;static#ji=null;static#Wi=new Set;constructor({textContentSource:t,container:e,viewport:i}){if(t instanceof ReadableStream)this.#Bi=t;else{if("object"!=typeof t)throw new Error('No "textContentSource" parameter specified.');this.#Bi=new ReadableStream({start(e){e.enqueue(t);e.close()}})}this.#pt=this.#Ii=e;this.#Li=i.scale*(globalThis.devicePixelRatio||1);this.#Fi=i.rotation;this.#Pi={div:null,properties:null,ctx:null};const{pageWidth:s,pageHeight:n,pageX:a,pageY:r}=i.rawDims;this.#Ui=[1,0,0,-1,-a,r+n];this.#ki=s;this.#Di=n;TextLayer.#qi();setLayerDimensions(e,i);this.#Si.promise.finally((()=>{TextLayer.#Wi.delete(this);this.#Pi=null;this.#Oi=null})).catch((()=>{}))}static get fontFamilyMap(){const{isWindows:t,isFirefox:e}=util_FeatureTest.platform;return shadow(this,"fontFamilyMap",new Map([["sans-serif",(t&&e?"Calibri, ":"")+"sans-serif"],["monospace",(t&&e?"Lucida Console, ":"")+"monospace"]]))}render(){const pump=()=>{this.#Ri.read().then((({value:t,done:e})=>{if(e)this.#Si.resolve();else{this.#Mi??=t.lang;Object.assign(this.#Oi,t.styles);this.#Xi(t.items);pump()}}),this.#Si.reject)};this.#Ri=this.#Bi.getReader();TextLayer.#Wi.add(this);pump();return this.#Si.promise}update({viewport:t,onBefore:e=null}){const i=t.scale*(globalThis.devicePixelRatio||1),s=t.rotation;if(s!==this.#Fi){e?.();this.#Fi=s;setLayerDimensions(this.#Ii,{rotation:s})}if(i!==this.#Li){e?.();this.#Li=i;const t={div:null,properties:null,ctx:TextLayer.#Ki(this.#Mi)};for(const e of this.#Hi){t.properties=this.#zi.get(e);t.div=e;this.#Yi(t)}}}cancel(){const t=new AbortException("TextLayer task cancelled.");this.#Ri?.cancel(t).catch((()=>{}));this.#Ri=null;this.#Si.reject(t)}get textDivs(){return this.#Hi}get textContentItemsStr(){return this.#Ni}#Xi(t){if(this.#Ci)return;this.#Pi.ctx??=TextLayer.#Ki(this.#Mi);const e=this.#Hi,i=this.#Ni;for(const s of t){if(e.length>1e5){warn("Ignoring additional textDivs for performance reasons.");this.#Ci=!0;return}if(void 0!==s.str){i.push(s.str);this.#Qi(s)}else if("beginMarkedContentProps"===s.type||"beginMarkedContent"===s.type){const t=this.#pt;this.#pt=document.createElement("span");this.#pt.classList.add("markedContent");null!==s.id&&this.#pt.setAttribute("id",`${s.id}`);t.append(this.#pt)}else"endMarkedContent"===s.type&&(this.#pt=this.#pt.parentNode)}}#Qi(t){const e=document.createElement("span"),i={angle:0,canvasWidth:0,hasText:""!==t.str,hasEOL:t.hasEOL,fontSize:0};this.#Hi.push(e);const s=Util.transform(this.#Ui,t.transform);let n=Math.atan2(s[1],s[0]);const a=this.#Oi[t.fontName];a.vertical&&(n+=Math.PI/2);let r=this.#Ti&&a.fontSubstitution||a.fontFamily;r=TextLayer.fontFamilyMap.get(r)||r;const o=Math.hypot(s[2],s[3]),l=o*TextLayer.#Ji(r,this.#Mi);let h,d;if(0===n){h=s[4];d=s[5]-l}else{h=s[4]+l*Math.sin(n);d=s[5]-l*Math.cos(n)}const c="calc(var(--scale-factor)*",u=e.style;if(this.#pt===this.#Ii){u.left=`${(100*h/this.#ki).toFixed(2)}%`;u.top=`${(100*d/this.#Di).toFixed(2)}%`}else{u.left=`${c}${h.toFixed(2)}px)`;u.top=`${c}${d.toFixed(2)}px)`}u.fontSize=`${c}${(TextLayer.#ji*o).toFixed(2)}px)`;u.fontFamily=r;i.fontSize=o;e.setAttribute("role","presentation");e.textContent=t.str;e.dir=t.dir;this.#Ti&&(e.dataset.fontName=a.fontSubstitutionLoadedName||t.fontName);0!==n&&(i.angle=n*(180/Math.PI));let p=!1;if(t.str.length>1)p=!0;else if(" "!==t.str&&t.transform[0]!==t.transform[3]){const e=Math.abs(t.transform[0]),i=Math.abs(t.transform[3]);e!==i&&Math.max(e,i)/Math.min(e,i)>1.5&&(p=!0)}p&&(i.canvasWidth=a.vertical?t.height:t.width);this.#zi.set(e,i);this.#Pi.div=e;this.#Pi.properties=i;this.#Yi(this.#Pi);i.hasText&&this.#pt.append(e);if(i.hasEOL){const t=document.createElement("br");t.setAttribute("role","presentation");this.#pt.append(t)}}#Yi(t){const{div:e,properties:i,ctx:s}=t,{style:n}=e;let a="";TextLayer.#ji>1&&(a=`scale(${1/TextLayer.#ji})`);if(0!==i.canvasWidth&&i.hasText){const{fontFamily:t}=n,{canvasWidth:r,fontSize:o}=i;TextLayer.#Zi(s,o*this.#Li,t);const{width:l}=s.measureText(e.textContent);l>0&&(a=`scaleX(${r*this.#Li/l}) ${a}`)}0!==i.angle&&(a=`rotate(${i.angle}deg) ${a}`);a.length>0&&(n.transform=a)}static cleanup(){if(!(this.#Wi.size>0)){this.#Gi.clear();for(const{canvas:t}of this.#$i.values())t.remove();this.#$i.clear()}}static#Ki(t=null){let e=this.#$i.get(t||="");if(!e){const i=document.createElement("canvas");i.className="hiddenCanvasElement";i.lang=t;document.body.append(i);e=i.getContext("2d",{alpha:!1,willReadFrequently:!0});this.#$i.set(t,e);this.#Vi.set(e,{size:0,family:""})}return e}static#Zi(t,e,i){const s=this.#Vi.get(t);if(e!==s.size||i!==s.family){t.font=`${e}px ${i}`;s.size=e;s.family=i}}static#qi(){if(null!==this.#ji)return;const t=document.createElement("div");t.style.opacity=0;t.style.lineHeight=1;t.style.fontSize="1px";t.style.position="absolute";t.textContent="X";document.body.append(t);this.#ji=t.getBoundingClientRect().height;t.remove()}static#Ji(t,e){const i=this.#Gi.get(t);if(i)return i;const s=this.#Ki(e);s.canvas.width=s.canvas.height=Pt;this.#Zi(s,Pt,t);const n=s.measureText("");let a=n.fontBoundingBoxAscent,r=Math.abs(n.fontBoundingBoxDescent);if(a){const e=a/(a+r);this.#Gi.set(t,e);s.canvas.width=s.canvas.height=0;return e}s.strokeStyle="red";s.clearRect(0,0,Pt,Pt);s.strokeText("g",0,0);let o=s.getImageData(0,0,Pt,Pt).data;r=0;for(let t=o.length-1-3;t>=0;t-=4)if(o[t]>0){r=Math.ceil(t/4/Pt);break}s.clearRect(0,0,Pt,Pt);s.strokeText("A",0,Pt);o=s.getImageData(0,0,Pt,Pt).data;a=0;for(let t=0,e=o.length;t0){a=Pt-Math.floor(t/4/Pt);break}s.canvas.width=s.canvas.height=0;const l=a?a/(a+r):.8;this.#Gi.set(t,l);return l}}class XfaText{static textContent(t){const e=[],i={items:e,styles:Object.create(null)};!function walk(t){if(!t)return;let i=null;const s=t.name;if("#text"===s)i=t.value;else{if(!XfaText.shouldBuildText(s))return;t?.attributes?.textContent?i=t.attributes.textContent:t.value&&(i=t.value)}null!==i&&e.push({str:i});if(t.children)for(const e of t.children)walk(e)}(t);return i}static shouldBuildText(t){return!("textarea"===t||"input"===t||"option"===t||"select"===t)}}const Dt=65536,kt=e?class NodeCanvasFactory extends BaseCanvasFactory{_createCanvas(t,e){return process.getBuiltinModule("module").createRequire(import.meta.url)("@napi-rs/canvas").createCanvas(t,e)}}:class DOMCanvasFactory extends BaseCanvasFactory{constructor({ownerDocument:t=globalThis.document,enableHWA:e=!1}){super({enableHWA:e});this._document=t}_createCanvas(t,e){const i=this._document.createElement("canvas");i.width=t;i.height=e;return i}},Rt=e?class NodeCMapReaderFactory extends BaseCMapReaderFactory{async _fetch(t){return node_utils_fetchData(t)}}:DOMCMapReaderFactory,It=e?class NodeFilterFactory extends BaseFilterFactory{}:class DOMFilterFactory extends BaseFilterFactory{#ts;#es;#is;#ss;#ns;#as;#w=0;constructor({docId:t,ownerDocument:e=globalThis.document}){super();this.#ss=t;this.#ns=e}get#y(){return this.#es||=new Map}get#rs(){return this.#as||=new Map}get#os(){if(!this.#is){const t=this.#ns.createElement("div"),{style:e}=t;e.visibility="hidden";e.contain="strict";e.width=e.height=0;e.position="absolute";e.top=e.left=0;e.zIndex=-1;const i=this.#ns.createElementNS(it,"svg");i.setAttribute("width",0);i.setAttribute("height",0);this.#is=this.#ns.createElementNS(it,"defs");t.append(i);i.append(this.#is);this.#ns.body.append(t)}return this.#is}#ls(t){if(1===t.length){const e=t[0],i=new Array(256);for(let t=0;t<256;t++)i[t]=e[t]/255;const s=i.join(",");return[s,s,s]}const[e,i,s]=t,n=new Array(256),a=new Array(256),r=new Array(256);for(let t=0;t<256;t++){n[t]=e[t]/255;a[t]=i[t]/255;r[t]=s[t]/255}return[n.join(","),a.join(","),r.join(",")]}#hs(t){if(void 0===this.#ts){this.#ts="";const t=this.#ns.URL;t!==this.#ns.baseURI&&(isDataScheme(t)?warn('#createUrl: ignore "data:"-URL for performance reasons.'):this.#ts=t.split("#",1)[0])}return`url(${this.#ts}#${t})`}addFilter(t){if(!t)return"none";let e=this.#y.get(t);if(e)return e;const[i,s,n]=this.#ls(t),a=1===t.length?i:`${i}${s}${n}`;e=this.#y.get(a);if(e){this.#y.set(t,e);return e}const r=`g_${this.#ss}_transfer_map_${this.#w++}`,o=this.#hs(r);this.#y.set(t,o);this.#y.set(a,o);const l=this.#ds(r);this.#cs(i,s,n,l);return o}addHCMFilter(t,e){const i=`${t}-${e}`,s="base";let n=this.#rs.get(s);if(n?.key===i)return n.url;if(n){n.filter?.remove();n.key=i;n.url="none";n.filter=null}else{n={key:i,url:"none",filter:null};this.#rs.set(s,n)}if(!t||!e)return n.url;const a=this.#us(t);t=Util.makeHexColor(...a);const r=this.#us(e);e=Util.makeHexColor(...r);this.#os.style.color="";if("#000000"===t&&"#ffffff"===e||t===e)return n.url;const o=new Array(256);for(let t=0;t<=255;t++){const e=t/255;o[t]=e<=.03928?e/12.92:((e+.055)/1.055)**2.4}const l=o.join(","),h=`g_${this.#ss}_hcm_filter`,d=n.filter=this.#ds(h);this.#cs(l,l,l,d);this.#ps(d);const getSteps=(t,e)=>{const i=a[t]/255,s=r[t]/255,n=new Array(e+1);for(let t=0;t<=e;t++)n[t]=i+t/e*(s-i);return n.join(",")};this.#cs(getSteps(0,5),getSteps(1,5),getSteps(2,5),d);n.url=this.#hs(h);return n.url}addAlphaFilter(t){let e=this.#y.get(t);if(e)return e;const[i]=this.#ls([t]),s=`alpha_${i}`;e=this.#y.get(s);if(e){this.#y.set(t,e);return e}const n=`g_${this.#ss}_alpha_map_${this.#w++}`,a=this.#hs(n);this.#y.set(t,a);this.#y.set(s,a);const r=this.#ds(n);this.#gs(i,r);return a}addLuminosityFilter(t){let e,i,s=this.#y.get(t||"luminosity");if(s)return s;if(t){[e]=this.#ls([t]);i=`luminosity_${e}`}else i="luminosity";s=this.#y.get(i);if(s){this.#y.set(t,s);return s}const n=`g_${this.#ss}_luminosity_map_${this.#w++}`,a=this.#hs(n);this.#y.set(t,a);this.#y.set(i,a);const r=this.#ds(n);this.#ms(r);t&&this.#gs(e,r);return a}addHighlightHCMFilter(t,e,i,s,n){const a=`${e}-${i}-${s}-${n}`;let r=this.#rs.get(t);if(r?.key===a)return r.url;if(r){r.filter?.remove();r.key=a;r.url="none";r.filter=null}else{r={key:a,url:"none",filter:null};this.#rs.set(t,r)}if(!e||!i)return r.url;const[o,l]=[e,i].map(this.#us.bind(this));let h=Math.round(.2126*o[0]+.7152*o[1]+.0722*o[2]),d=Math.round(.2126*l[0]+.7152*l[1]+.0722*l[2]),[c,u]=[s,n].map(this.#us.bind(this));d{const s=new Array(256),n=(d-h)/i,a=t/255,r=(e-t)/(255*i);let o=0;for(let t=0;t<=i;t++){const e=Math.round(h+t*n),i=a+t*r;for(let t=o;t<=e;t++)s[t]=i;o=e+1}for(let t=o;t<256;t++)s[t]=s[o-1];return s.join(",")},p=`g_${this.#ss}_hcm_${t}_filter`,g=r.filter=this.#ds(p);this.#ps(g);this.#cs(getSteps(c[0],u[0],5),getSteps(c[1],u[1],5),getSteps(c[2],u[2],5),g);r.url=this.#hs(p);return r.url}destroy(t=!1){if(!t||!this.#as?.size){this.#is?.parentNode.parentNode.remove();this.#is=null;this.#es?.clear();this.#es=null;this.#as?.clear();this.#as=null;this.#w=0}}#ms(t){const e=this.#ns.createElementNS(it,"feColorMatrix");e.setAttribute("type","matrix");e.setAttribute("values","0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0");t.append(e)}#ps(t){const e=this.#ns.createElementNS(it,"feColorMatrix");e.setAttribute("type","matrix");e.setAttribute("values","0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0");t.append(e)}#ds(t){const e=this.#ns.createElementNS(it,"filter");e.setAttribute("color-interpolation-filters","sRGB");e.setAttribute("id",t);this.#os.append(e);return e}#fs(t,e,i){const s=this.#ns.createElementNS(it,e);s.setAttribute("type","discrete");s.setAttribute("tableValues",i);t.append(s)}#cs(t,e,i,s){const n=this.#ns.createElementNS(it,"feComponentTransfer");s.append(n);this.#fs(n,"feFuncR",t);this.#fs(n,"feFuncG",e);this.#fs(n,"feFuncB",i)}#gs(t,e){const i=this.#ns.createElementNS(it,"feComponentTransfer");e.append(i);this.#fs(i,"feFuncA",t)}#us(t){this.#os.style.color=t;return getRGB(getComputedStyle(this.#os).getPropertyValue("color"))}},Ft=e?class NodeStandardFontDataFactory extends BaseStandardFontDataFactory{async _fetch(t){return node_utils_fetchData(t)}}:DOMStandardFontDataFactory;function getDocument(t={}){"string"==typeof t||t instanceof URL?t={url:t}:(t instanceof ArrayBuffer||ArrayBuffer.isView(t))&&(t={data:t});const i=new PDFDocumentLoadingTask,{docId:s}=i,n=t.url?function getUrlProp(t){if(t instanceof URL)return t.href;try{return new URL(t,window.location).href}catch{if(e&&"string"==typeof t)return t}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}(t.url):null,a=t.data?function getDataProp(t){if(e&&"undefined"!=typeof Buffer&&t instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(t instanceof Uint8Array&&t.byteLength===t.buffer.byteLength)return t;if("string"==typeof t)return stringToBytes(t);if(t instanceof ArrayBuffer||ArrayBuffer.isView(t)||"object"==typeof t&&!isNaN(t?.length))return new Uint8Array(t);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}(t.data):null,r=t.httpHeaders||null,o=!0===t.withCredentials,l=t.password??null,h=t.range instanceof PDFDataRangeTransport?t.range:null,d=Number.isInteger(t.rangeChunkSize)&&t.rangeChunkSize>0?t.rangeChunkSize:Dt;let c=t.worker instanceof PDFWorker?t.worker:null;const u=t.verbosity,p="string"!=typeof t.docBaseUrl||isDataScheme(t.docBaseUrl)?null:t.docBaseUrl,g="string"==typeof t.cMapUrl?t.cMapUrl:null,m=!1!==t.cMapPacked,f=t.CMapReaderFactory||Rt,b="string"==typeof t.standardFontDataUrl?t.standardFontDataUrl:null,A=t.StandardFontDataFactory||Ft,w=!0!==t.stopAtErrors,v=Number.isInteger(t.maxImageSize)&&t.maxImageSize>-1?t.maxImageSize:-1,y=!1!==t.isEvalSupported,x="boolean"==typeof t.isOffscreenCanvasSupported?t.isOffscreenCanvasSupported:!e,_="boolean"==typeof t.isImageDecoderSupported?t.isImageDecoderSupported:!e&&(util_FeatureTest.platform.isFirefox||!globalThis.chrome),E=Number.isInteger(t.canvasMaxAreaInBytes)?t.canvasMaxAreaInBytes:-1,S="boolean"==typeof t.disableFontFace?t.disableFontFace:e,C=!0===t.fontExtraProperties,T=!0===t.enableXfa,M=t.ownerDocument||globalThis.document,P=!0===t.disableRange,D=!0===t.disableStream,k=!0===t.disableAutoFetch,R=!0===t.pdfBug,I=t.CanvasFactory||kt,F=t.FilterFactory||It,L=!0===t.enableHWA,O=h?h.length:t.length??NaN,N="boolean"==typeof t.useSystemFonts?t.useSystemFonts:!e&&!S,B="boolean"==typeof t.useWorkerFetch?t.useWorkerFetch:f===DOMCMapReaderFactory&&A===DOMStandardFontDataFactory&&g&&b&&isValidFetchUrl(g,document.baseURI)&&isValidFetchUrl(b,document.baseURI);setVerbosityLevel(u);const H={canvasFactory:new I({ownerDocument:M,enableHWA:L}),filterFactory:new F({docId:s,ownerDocument:M}),cMapReaderFactory:B?null:new f({baseUrl:g,isCompressed:m}),standardFontDataFactory:B?null:new A({baseUrl:b})};if(!c){const t={verbosity:u,port:GlobalWorkerOptions.workerPort};c=t.port?PDFWorker.fromPort(t):new PDFWorker(t);i._worker=c}const z={docId:s,apiVersion:"4.10.38",data:a,password:l,disableAutoFetch:k,rangeChunkSize:d,length:O,docBaseUrl:p,enableXfa:T,evaluatorOptions:{maxImageSize:v,disableFontFace:S,ignoreErrors:w,isEvalSupported:y,isOffscreenCanvasSupported:x,isImageDecoderSupported:_,canvasMaxAreaInBytes:E,fontExtraProperties:C,useSystemFonts:N,cMapUrl:B?g:null,standardFontDataUrl:B?b:null}},U={disableFontFace:S,fontExtraProperties:C,ownerDocument:M,pdfBug:R,styleElement:null,loadingParams:{disableAutoFetch:k,enableXfa:T}};c.promise.then((function(){if(i.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const t=c.messageHandler.sendWithPromise("GetDocRequest",z,a?[a.buffer]:null);let l;if(h)l=new PDFDataTransportStream(h,{disableRange:P,disableStream:D});else if(!a){if(!n)throw new Error("getDocument - no `url` parameter provided.");let t;if(e)if(isValidFetchUrl(n)){if("undefined"==typeof fetch||"undefined"==typeof Response||!("body"in Response.prototype))throw new Error("getDocument - the Fetch API was disabled in Node.js, see `--no-experimental-fetch`.");t=PDFFetchStream}else t=PDFNodeStream;else t=isValidFetchUrl(n)?PDFFetchStream:PDFNetworkStream;l=new t({url:n,length:O,httpHeaders:r,withCredentials:o,rangeChunkSize:d,disableRange:P,disableStream:D})}return t.then((t=>{if(i.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const e=new MessageHandler(s,t,c.port),n=new WorkerTransport(e,i,l,U,H);i._transport=n;e.send("Ready",null)}))})).catch(i._capability.reject);return i}function isRefProxy(t){return"object"==typeof t&&Number.isInteger(t?.num)&&t.num>=0&&Number.isInteger(t?.gen)&&t.gen>=0}class PDFDocumentLoadingTask{static#ss=0;constructor(){this._capability=Promise.withResolvers();this._transport=null;this._worker=null;this.docId="d"+PDFDocumentLoadingTask.#ss++;this.destroyed=!1;this.onPassword=null;this.onProgress=null}get promise(){return this._capability.promise}async destroy(){this.destroyed=!0;try{this._worker?.port&&(this._worker._pendingDestroy=!0);await(this._transport?.destroy())}catch(t){this._worker?.port&&delete this._worker._pendingDestroy;throw t}this._transport=null;this._worker?.destroy();this._worker=null}}class PDFDataRangeTransport{constructor(t,e,i=!1,s=null){this.length=t;this.initialData=e;this.progressiveDone=i;this.contentDispositionFilename=s;this._rangeListeners=[];this._progressListeners=[];this._progressiveReadListeners=[];this._progressiveDoneListeners=[];this._readyCapability=Promise.withResolvers()}addRangeListener(t){this._rangeListeners.push(t)}addProgressListener(t){this._progressListeners.push(t)}addProgressiveReadListener(t){this._progressiveReadListeners.push(t)}addProgressiveDoneListener(t){this._progressiveDoneListeners.push(t)}onDataRange(t,e){for(const i of this._rangeListeners)i(t,e)}onDataProgress(t,e){this._readyCapability.promise.then((()=>{for(const i of this._progressListeners)i(t,e)}))}onDataProgressiveRead(t){this._readyCapability.promise.then((()=>{for(const e of this._progressiveReadListeners)e(t)}))}onDataProgressiveDone(){this._readyCapability.promise.then((()=>{for(const t of this._progressiveDoneListeners)t()}))}transportReady(){this._readyCapability.resolve()}requestDataRange(t,e){unreachable("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class PDFDocumentProxy{constructor(t,e){this._pdfInfo=t;this._transport=e}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return shadow(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(t){return this._transport.getPage(t)}getPageIndex(t){return this._transport.getPageIndex(t)}getDestinations(){return this._transport.getDestinations()}getDestination(t){return this._transport.getDestination(t)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getOptionalContentConfig(e)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(t=!1){return this._transport.startCleanup(t||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}cachedPageNumber(t){return this._transport.cachedPageNumber(t)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}class PDFPageProxy{#bs=null;#As=!1;constructor(t,e,i,s=!1){this._pageIndex=t;this._pageInfo=e;this._transport=i;this._stats=s?new StatTimer:null;this._pdfBug=s;this.commonObjs=i.commonObjs;this.objs=new PDFObjects;this._maybeCleanupAfterRender=!1;this._intentStates=new Map;this.destroyed=!1}get pageNumber(){return this._pageIndex+1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:t,rotation:e=this.rotate,offsetX:i=0,offsetY:s=0,dontFlip:n=!1}={}){return new PageViewport({viewBox:this.view,userUnit:this.userUnit,scale:t,rotation:e,offsetX:i,offsetY:s,dontFlip:n})}getAnnotations({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getAnnotations(this._pageIndex,e)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return shadow(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:t,viewport:e,intent:i="display",annotationMode:s=p.ENABLE,transform:n=null,background:a=null,optionalContentConfigPromise:r=null,annotationCanvasMap:l=null,pageColors:h=null,printAnnotationStorage:d=null,isEditing:c=!1}){this._stats?.time("Overall");const u=this._transport.getRenderingIntent(i,s,d,c),{renderingIntent:g,cacheKey:m}=u;this.#As=!1;this.#ws();r||=this._transport.getOptionalContentConfig(g);let f=this._intentStates.get(m);if(!f){f=Object.create(null);this._intentStates.set(m,f)}if(f.streamReaderCancelTimeout){clearTimeout(f.streamReaderCancelTimeout);f.streamReaderCancelTimeout=null}const b=!!(g&o);if(!f.displayReadyCapability){f.displayReadyCapability=Promise.withResolvers();f.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null};this._stats?.time("Page Request");this._pumpOperatorList(u)}const complete=t=>{f.renderTasks.delete(A);(this._maybeCleanupAfterRender||b)&&(this.#As=!0);this.#vs(!b);if(t){A.capability.reject(t);this._abortOperatorList({intentState:f,reason:t instanceof Error?t:new Error(t)})}else A.capability.resolve();if(this._stats){this._stats.timeEnd("Rendering");this._stats.timeEnd("Overall");globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats)}},A=new InternalRenderTask({callback:complete,params:{canvasContext:t,viewport:e,transform:n,background:a},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:l,operatorList:f.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!b,pdfBug:this._pdfBug,pageColors:h});(f.renderTasks||=new Set).add(A);const w=A.task;Promise.all([f.displayReadyCapability.promise,r]).then((([t,e])=>{if(this.destroyed)complete();else{this._stats?.time("Rendering");if(!(e.renderingIntent&g))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");A.initializeGraphics({transparency:t,optionalContentConfig:e});A.operatorListChanged()}})).catch(complete);return w}getOperatorList({intent:t="display",annotationMode:e=p.ENABLE,printAnnotationStorage:i=null,isEditing:s=!1}={}){const n=this._transport.getRenderingIntent(t,e,i,s,!0);let a,r=this._intentStates.get(n.cacheKey);if(!r){r=Object.create(null);this._intentStates.set(n.cacheKey,r)}if(!r.opListReadCapability){a=Object.create(null);a.operatorListChanged=function operatorListChanged(){if(r.operatorList.lastChunk){r.opListReadCapability.resolve(r.operatorList);r.renderTasks.delete(a)}};r.opListReadCapability=Promise.withResolvers();(r.renderTasks||=new Set).add(a);r.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null};this._stats?.time("Page Request");this._pumpOperatorList(n)}return r.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=!1,disableNormalization:e=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,includeMarkedContent:!0===t,disableNormalization:!0===e},{highWaterMark:100,size:t=>t.items.length})}getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then((t=>XfaText.textContent(t)));const e=this.streamTextContent(t);return new Promise((function(t,i){const s=e.getReader(),n={items:[],styles:Object.create(null),lang:null};!function pump(){s.read().then((function({value:e,done:i}){if(i)t(n);else{n.lang??=e.lang;Object.assign(n.styles,e.styles);n.items.push(...e.items);pump()}}),i)}()}))}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const t=[];for(const e of this._intentStates.values()){this._abortOperatorList({intentState:e,reason:new Error("Page was destroyed."),force:!0});if(!e.opListReadCapability)for(const i of e.renderTasks){t.push(i.completed);i.cancel()}}this.objs.clear();this.#As=!1;this.#ws();return Promise.all(t)}cleanup(t=!1){this.#As=!0;const e=this.#vs(!1);t&&e&&(this._stats&&=new StatTimer);return e}#vs(t=!1){this.#ws();if(!this.#As||this.destroyed)return!1;if(t){this.#bs=setTimeout((()=>{this.#bs=null;this.#vs(!1)}),5e3);return!1}for(const{renderTasks:t,operatorList:e}of this._intentStates.values())if(t.size>0||!e.lastChunk)return!1;this._intentStates.clear();this.objs.clear();this.#As=!1;return!0}#ws(){if(this.#bs){clearTimeout(this.#bs);this.#bs=null}}_startRenderPage(t,e){const i=this._intentStates.get(e);if(i){this._stats?.timeEnd("Page Request");i.displayReadyCapability?.resolve(t)}}_renderPageChunk(t,e){for(let i=0,s=t.length;i{r.read().then((({value:t,done:e})=>{if(e)o.streamReader=null;else if(!this._transport.destroyed){this._renderPageChunk(t,o);pump()}}),(t=>{o.streamReader=null;if(!this._transport.destroyed){if(o.operatorList){o.operatorList.lastChunk=!0;for(const t of o.renderTasks)t.operatorListChanged();this.#vs(!0)}if(o.displayReadyCapability)o.displayReadyCapability.reject(t);else{if(!o.opListReadCapability)throw t;o.opListReadCapability.reject(t)}}}))};pump()}_abortOperatorList({intentState:t,reason:e,force:i=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout){clearTimeout(t.streamReaderCancelTimeout);t.streamReaderCancelTimeout=null}if(!i){if(t.renderTasks.size>0)return;if(e instanceof RenderingCancelledException){let i=100;e.extraDelay>0&&e.extraDelay<1e3&&(i+=e.extraDelay);t.streamReaderCancelTimeout=setTimeout((()=>{t.streamReaderCancelTimeout=null;this._abortOperatorList({intentState:t,reason:e,force:!0})}),i);return}}t.streamReader.cancel(new AbortException(e.message)).catch((()=>{}));t.streamReader=null;if(!this._transport.destroyed){for(const[e,i]of this._intentStates)if(i===t){this._intentStates.delete(e);break}this.cleanup()}}}get stats(){return this._stats}}class LoopbackPort{#ys=new Map;#xs=Promise.resolve();postMessage(t,e){const i={data:structuredClone(t,e?{transfer:e}:null)};this.#xs.then((()=>{for(const[t]of this.#ys)t.call(this,i)}))}addEventListener(t,e,i=null){let s=null;if(i?.signal instanceof AbortSignal){const{signal:n}=i;if(n.aborted){warn("LoopbackPort - cannot use an `aborted` signal.");return}const onAbort=()=>this.removeEventListener(t,e);s=()=>n.removeEventListener("abort",onAbort);n.addEventListener("abort",onAbort)}this.#ys.set(e,s)}removeEventListener(t,e){const i=this.#ys.get(e);i?.();this.#ys.delete(e)}terminate(){for(const[,t]of this.#ys)t?.();this.#ys.clear()}}class PDFWorker{static#_s=0;static#Es=!1;static#Ss;static{if(e){this.#Es=!0;GlobalWorkerOptions.workerSrc||="./pdf.worker.mjs"}this._isSameOrigin=(t,e)=>{let i;try{i=new URL(t);if(!i.origin||"null"===i.origin)return!1}catch{return!1}const s=new URL(e,i);return i.origin===s.origin};this._createCDNWrapper=t=>{const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))}}constructor({name:t=null,port:e=null,verbosity:i=getVerbosityLevel()}={}){this.name=t;this.destroyed=!1;this.verbosity=i;this._readyCapability=Promise.withResolvers();this._port=null;this._webWorker=null;this._messageHandler=null;if(e){if(PDFWorker.#Ss?.has(e))throw new Error("Cannot use more than one PDFWorker per port.");(PDFWorker.#Ss||=new WeakMap).set(e,this);this._initializeFromPort(e)}else this._initialize()}get promise(){return this._readyCapability.promise}#Cs(){this._readyCapability.resolve();this._messageHandler.send("configure",{verbosity:this.verbosity})}get port(){return this._port}get messageHandler(){return this._messageHandler}_initializeFromPort(t){this._port=t;this._messageHandler=new MessageHandler("main","worker",t);this._messageHandler.on("ready",(function(){}));this.#Cs()}_initialize(){if(PDFWorker.#Es||PDFWorker.#Ts){this._setupFakeWorker();return}let{workerSrc:t}=PDFWorker;try{PDFWorker._isSameOrigin(window.location.href,t)||(t=PDFWorker._createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),i=new MessageHandler("main","worker",e),terminateEarly=()=>{s.abort();i.destroy();e.terminate();this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()},s=new AbortController;e.addEventListener("error",(()=>{this._webWorker||terminateEarly()}),{signal:s.signal});i.on("test",(t=>{s.abort();if(!this.destroyed&&t){this._messageHandler=i;this._port=e;this._webWorker=e;this.#Cs()}else terminateEarly()}));i.on("ready",(t=>{s.abort();if(this.destroyed)terminateEarly();else try{sendTest()}catch{this._setupFakeWorker()}}));const sendTest=()=>{const t=new Uint8Array;i.send("test",t,[t.buffer])};sendTest();return}catch{info("The worker has been disabled.")}this._setupFakeWorker()}_setupFakeWorker(){if(!PDFWorker.#Es){warn("Setting up fake worker.");PDFWorker.#Es=!0}PDFWorker._setupFakeWorkerGlobal.then((t=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}const e=new LoopbackPort;this._port=e;const i="fake"+PDFWorker.#_s++,s=new MessageHandler(i+"_worker",i,e);t.setup(s,e);this._messageHandler=new MessageHandler(i,i+"_worker",e);this.#Cs()})).catch((t=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${t.message}".`))}))}destroy(){this.destroyed=!0;this._webWorker?.terminate();this._webWorker=null;PDFWorker.#Ss?.delete(this._port);this._port=null;this._messageHandler?.destroy();this._messageHandler=null}static fromPort(t){if(!t?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");const e=this.#Ss?.get(t.port);if(e){if(e._pendingDestroy)throw new Error("PDFWorker.fromPort - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return e}return new PDFWorker(t)}static get workerSrc(){if(GlobalWorkerOptions.workerSrc)return GlobalWorkerOptions.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get#Ts(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return shadow(this,"_setupFakeWorkerGlobal",(async()=>{if(this.#Ts)return this.#Ts;return(await import(this.workerSrc)).WorkerMessageHandler})())}}class WorkerTransport{#Ms=new Map;#Ps=new Map;#Ds=new Map;#ks=new Map;#Rs=null;constructor(t,e,i,s,n){this.messageHandler=t;this.loadingTask=e;this.commonObjs=new PDFObjects;this.fontLoader=new FontLoader({ownerDocument:s.ownerDocument,styleElement:s.styleElement});this.loadingParams=s.loadingParams;this._params=s;this.canvasFactory=n.canvasFactory;this.filterFactory=n.filterFactory;this.cMapReaderFactory=n.cMapReaderFactory;this.standardFontDataFactory=n.standardFontDataFactory;this.destroyed=!1;this.destroyCapability=null;this._networkStream=i;this._fullReader=null;this._lastProgress=null;this.downloadInfoCapability=Promise.withResolvers();this.setupMessageHandler()}#Is(t,e=null){const i=this.#Ms.get(t);if(i)return i;const s=this.messageHandler.sendWithPromise(t,e);this.#Ms.set(t,s);return s}get annotationStorage(){return shadow(this,"annotationStorage",new AnnotationStorage)}getRenderingIntent(t,e=p.ENABLE,i=null,s=!1,n=!1){let g=r,m=rt;switch(t){case"any":g=a;break;case"display":break;case"print":g=o;break;default:warn(`getRenderingIntent - invalid intent: ${t}`)}const f=g&o&&i instanceof PrintAnnotationStorage?i:this.annotationStorage;switch(e){case p.DISABLE:g+=d;break;case p.ENABLE:break;case p.ENABLE_FORMS:g+=l;break;case p.ENABLE_STORAGE:g+=h;m=f.serializable;break;default:warn(`getRenderingIntent - invalid annotationMode: ${e}`)}s&&(g+=c);n&&(g+=u);const{ids:b,hash:A}=f.modifiedIds;return{renderingIntent:g,cacheKey:[g,m.hash,A].join("_"),annotationStorageSerializable:m,modifiedIds:b}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0;this.destroyCapability=Promise.withResolvers();this.#Rs?.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const e of this.#Ps.values())t.push(e._destroy());this.#Ps.clear();this.#Ds.clear();this.#ks.clear();this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();const e=this.messageHandler.sendWithPromise("Terminate",null);t.push(e);Promise.all(t).then((()=>{this.commonObjs.clear();this.fontLoader.clear();this.#Ms.clear();this.filterFactory.destroy();TextLayer.cleanup();this._networkStream?.cancelAllRequests(new AbortException("Worker was terminated."));this.messageHandler?.destroy();this.messageHandler=null;this.destroyCapability.resolve()}),this.destroyCapability.reject);return this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:t,loadingTask:e}=this;t.on("GetReader",((t,e)=>{assert(this._networkStream,"GetReader - no `IPDFStream` instance available.");this._fullReader=this._networkStream.getFullReader();this._fullReader.onProgress=t=>{this._lastProgress={loaded:t.loaded,total:t.total}};e.onPull=()=>{this._fullReader.read().then((function({value:t,done:i}){if(i)e.close();else{assert(t instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer.");e.enqueue(new Uint8Array(t),1,[t])}})).catch((t=>{e.error(t)}))};e.onCancel=t=>{this._fullReader.cancel(t);e.ready.catch((t=>{if(!this.destroyed)throw t}))}}));t.on("ReaderHeadersReady",(async t=>{await this._fullReader.headersReady;const{isStreamingSupported:i,isRangeSupported:s,contentLength:n}=this._fullReader;if(!i||!s){this._lastProgress&&e.onProgress?.(this._lastProgress);this._fullReader.onProgress=t=>{e.onProgress?.({loaded:t.loaded,total:t.total})}}return{isStreamingSupported:i,isRangeSupported:s,contentLength:n}}));t.on("GetRangeReader",((t,e)=>{assert(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");const i=this._networkStream.getRangeReader(t.begin,t.end);if(i){e.onPull=()=>{i.read().then((function({value:t,done:i}){if(i)e.close();else{assert(t instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer.");e.enqueue(new Uint8Array(t),1,[t])}})).catch((t=>{e.error(t)}))};e.onCancel=t=>{i.cancel(t);e.ready.catch((t=>{if(!this.destroyed)throw t}))}}else e.close()}));t.on("GetDoc",(({pdfInfo:t})=>{this._numPages=t.numPages;this._htmlForXfa=t.htmlForXfa;delete t.htmlForXfa;e._capability.resolve(new PDFDocumentProxy(t,this))}));t.on("DocException",(t=>{e._capability.reject(wrapReason(t))}));t.on("PasswordRequest",(t=>{this.#Rs=Promise.withResolvers();try{if(!e.onPassword)throw wrapReason(t);const updatePassword=t=>{t instanceof Error?this.#Rs.reject(t):this.#Rs.resolve({password:t})};e.onPassword(updatePassword,t.code)}catch(t){this.#Rs.reject(t)}return this.#Rs.promise}));t.on("DataLoaded",(t=>{e.onProgress?.({loaded:t.length,total:t.length});this.downloadInfoCapability.resolve(t)}));t.on("StartRenderPage",(t=>{if(this.destroyed)return;this.#Ps.get(t.pageIndex)._startRenderPage(t.transparency,t.cacheKey)}));t.on("commonobj",(([e,i,s])=>{if(this.destroyed)return null;if(this.commonObjs.has(e))return null;switch(i){case"Font":const{disableFontFace:n,fontExtraProperties:a,pdfBug:r}=this._params;if("error"in s){const t=s.error;warn(`Error during font loading: ${t}`);this.commonObjs.resolve(e,t);break}const o=r&&globalThis.FontInspector?.enabled?(t,e)=>globalThis.FontInspector.fontAdded(t,e):null,l=new FontFaceObject(s,{disableFontFace:n,fontExtraProperties:a,inspectFont:o});this.fontLoader.bind(l).catch((()=>t.sendWithPromise("FontFallback",{id:e}))).finally((()=>{!a&&l.data&&(l.data=null);this.commonObjs.resolve(e,l)}));break;case"CopyLocalImage":const{imageRef:h}=s;assert(h,"The imageRef must be defined.");for(const t of this.#Ps.values())for(const[,i]of t.objs)if(i?.ref===h){if(!i.dataLen)return null;this.commonObjs.resolve(e,structuredClone(i));return i.dataLen}break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(e,s);break;default:throw new Error(`Got unknown common object type ${i}`)}return null}));t.on("obj",(([t,e,i,s])=>{if(this.destroyed)return;const n=this.#Ps.get(e);if(!n.objs.has(t))if(0!==n._intentStates.size)switch(i){case"Image":n.objs.resolve(t,s);s?.dataLen>1e7&&(n._maybeCleanupAfterRender=!0);break;case"Pattern":n.objs.resolve(t,s);break;default:throw new Error(`Got unknown object type ${i}`)}else s?.bitmap?.close()}));t.on("DocProgress",(t=>{this.destroyed||e.onProgress?.({loaded:t.loaded,total:t.total})}));t.on("FetchBuiltInCMap",(async t=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.cMapReaderFactory)throw new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter.");return this.cMapReaderFactory.fetch(t)}));t.on("FetchStandardFontData",(async t=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.standardFontDataFactory)throw new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter.");return this.standardFontDataFactory.fetch(t)}))}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&warn("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:t,transfer:e}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:this._fullReader?.filename??null},e).finally((()=>{this.annotationStorage.resetModified()}))}getPage(t){if(!Number.isInteger(t)||t<=0||t>this._numPages)return Promise.reject(new Error("Invalid page request."));const e=t-1,i=this.#Ds.get(e);if(i)return i;const s=this.messageHandler.sendWithPromise("GetPage",{pageIndex:e}).then((i=>{if(this.destroyed)throw new Error("Transport destroyed");i.refStr&&this.#ks.set(i.refStr,t);const s=new PDFPageProxy(e,i,this,this._params.pdfBug);this.#Ps.set(e,s);return s}));this.#Ds.set(e,s);return s}getPageIndex(t){return isRefProxy(t)?this.messageHandler.sendWithPromise("GetPageIndex",{num:t.num,gen:t.gen}):Promise.reject(new Error("Invalid pageIndex request."))}getAnnotations(t,e){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:t,intent:e})}getFieldObjects(){return this.#Is("GetFieldObjects")}hasJSActions(){return this.#Is("HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(t){return"string"!=typeof t?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:t})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getDocJSActions(){return this.#Is("GetDocJSActions")}getPageJSActions(t){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:t})}getStructTree(t){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:t})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(t){return this.#Is("GetOptionalContentConfig").then((e=>new OptionalContentConfig(e,t)))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",e=this.#Ms.get(t);if(e)return e;const i=this.messageHandler.sendWithPromise(t,null).then((t=>({info:t[0],metadata:t[1]?new Metadata(t[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null})));this.#Ms.set(t,i);return i}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(t=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const t of this.#Ps.values()){if(!t.cleanup())throw new Error(`startCleanup: Page ${t.pageNumber} is currently rendering.`)}this.commonObjs.clear();t||this.fontLoader.clear();this.#Ms.clear();this.filterFactory.destroy(!0);TextLayer.cleanup()}}cachedPageNumber(t){if(!isRefProxy(t))return null;const e=0===t.gen?`${t.num}R`:`${t.num}R${t.gen}`;return this.#ks.get(e)??null}}const Lt=Symbol("INITIAL_DATA");class PDFObjects{#Fs=Object.create(null);#Ls(t){return this.#Fs[t]||={...Promise.withResolvers(),data:Lt}}get(t,e=null){if(e){const i=this.#Ls(t);i.promise.then((()=>e(i.data)));return null}const i=this.#Fs[t];if(!i||i.data===Lt)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return i.data}has(t){const e=this.#Fs[t];return!!e&&e.data!==Lt}delete(t){const e=this.#Fs[t];if(!e||e.data===Lt)return!1;delete this.#Fs[t];return!0}resolve(t,e=null){const i=this.#Ls(t);i.data=e;i.resolve()}clear(){for(const t in this.#Fs){const{data:e}=this.#Fs[t];e?.bitmap?.close()}this.#Fs=Object.create(null)}*[Symbol.iterator](){for(const t in this.#Fs){const{data:e}=this.#Fs[t];e!==Lt&&(yield[t,e])}}}class RenderTask{#Os=null;constructor(t){this.#Os=t;this.onContinue=null}get promise(){return this.#Os.capability.promise}cancel(t=0){this.#Os.cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=this.#Os.operatorList;if(!t)return!1;const{annotationCanvasMap:e}=this.#Os;return t.form||t.canvas&&e?.size>0}}class InternalRenderTask{#Ns=null;static#Bs=new WeakSet;constructor({callback:t,params:e,objs:i,commonObjs:s,annotationCanvasMap:n,operatorList:a,pageIndex:r,canvasFactory:o,filterFactory:l,useRequestAnimationFrame:h=!1,pdfBug:d=!1,pageColors:c=null}){this.callback=t;this.params=e;this.objs=i;this.commonObjs=s;this.annotationCanvasMap=n;this.operatorListIdx=null;this.operatorList=a;this._pageIndex=r;this.canvasFactory=o;this.filterFactory=l;this._pdfBug=d;this.pageColors=c;this.running=!1;this.graphicsReadyCallback=null;this.graphicsReady=!1;this._useRequestAnimationFrame=!0===h&&"undefined"!=typeof window;this.cancelled=!1;this.capability=Promise.withResolvers();this.task=new RenderTask(this);this._cancelBound=this.cancel.bind(this);this._continueBound=this._continue.bind(this);this._scheduleNextBound=this._scheduleNext.bind(this);this._nextBound=this._next.bind(this);this._canvas=e.canvasContext.canvas}get completed(){return this.capability.promise.catch((function(){}))}initializeGraphics({transparency:t=!1,optionalContentConfig:e}){if(this.cancelled)return;if(this._canvas){if(InternalRenderTask.#Bs.has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");InternalRenderTask.#Bs.add(this._canvas)}if(this._pdfBug&&globalThis.StepperManager?.enabled){this.stepper=globalThis.StepperManager.create(this._pageIndex);this.stepper.init(this.operatorList);this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint()}const{canvasContext:i,viewport:s,transform:n,background:a}=this.params;this.gfx=new CanvasGraphics(i,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:e},this.annotationCanvasMap,this.pageColors);this.gfx.beginDrawing({transform:n,viewport:s,transparency:t,background:a});this.operatorListIdx=0;this.graphicsReady=!0;this.graphicsReadyCallback?.()}cancel(t=null,e=0){this.running=!1;this.cancelled=!0;this.gfx?.endDrawing();if(this.#Ns){window.cancelAnimationFrame(this.#Ns);this.#Ns=null}InternalRenderTask.#Bs.delete(this._canvas);this.callback(t||new RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex+1}`,e))}operatorListChanged(){if(this.graphicsReady){this.stepper?.updateOperatorList(this.operatorList);this.running||this._continue()}else this.graphicsReadyCallback||=this._continueBound}_continue(){this.running=!0;this.cancelled||(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?this.#Ns=window.requestAnimationFrame((()=>{this.#Ns=null;this._nextBound().catch(this._cancelBound)})):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){if(!this.cancelled){this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper);if(this.operatorListIdx===this.operatorList.argsArray.length){this.running=!1;if(this.operatorList.lastChunk){this.gfx.endDrawing();InternalRenderTask.#Bs.delete(this._canvas);this.callback()}}}}}const Ot="4.10.38",Nt="f9bea397f";function makeColorComp(t){return Math.floor(255*Math.max(0,Math.min(1,t))).toString(16).padStart(2,"0")}function scaleAndClamp(t){return Math.max(0,Math.min(255,255*t))}class ColorConverters{static CMYK_G([t,e,i,s]){return["G",1-Math.min(1,.3*t+.59*i+.11*e+s)]}static G_CMYK([t]){return["CMYK",0,0,0,1-t]}static G_RGB([t]){return["RGB",t,t,t]}static G_rgb([t]){return[t=scaleAndClamp(t),t,t]}static G_HTML([t]){const e=makeColorComp(t);return`#${e}${e}${e}`}static RGB_G([t,e,i]){return["G",.3*t+.59*e+.11*i]}static RGB_rgb(t){return t.map(scaleAndClamp)}static RGB_HTML(t){return`#${t.map(makeColorComp).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([t,e,i,s]){return["RGB",1-Math.min(1,t+s),1-Math.min(1,i+s),1-Math.min(1,e+s)]}static CMYK_rgb([t,e,i,s]){return[scaleAndClamp(1-Math.min(1,t+s)),scaleAndClamp(1-Math.min(1,i+s)),scaleAndClamp(1-Math.min(1,e+s))]}static CMYK_HTML(t){const e=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(e)}static RGB_CMYK([t,e,i]){const s=1-t,n=1-e,a=1-i;return["CMYK",s,n,a,Math.min(s,n,a)]}}class BaseSVGFactory{create(t,e,i=!1){if(t<=0||e<=0)throw new Error("Invalid SVG dimensions");const s=this._createSVG("svg:svg");s.setAttribute("version","1.1");if(!i){s.setAttribute("width",`${t}px`);s.setAttribute("height",`${e}px`)}s.setAttribute("preserveAspectRatio","none");s.setAttribute("viewBox",`0 0 ${t} ${e}`);return s}createElement(t){if("string"!=typeof t)throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){unreachable("Abstract method `_createSVG` called.")}}class DOMSVGFactory extends BaseSVGFactory{_createSVG(t){return document.createElementNS(it,t)}}class XfaLayer{static setupStorage(t,e,i,s,n){const a=s.getValue(e,{value:null});switch(i.name){case"textarea":null!==a.value&&(t.textContent=a.value);if("print"===n)break;t.addEventListener("input",(t=>{s.setValue(e,{value:t.target.value})}));break;case"input":if("radio"===i.attributes.type||"checkbox"===i.attributes.type){a.value===i.attributes.xfaOn?t.setAttribute("checked",!0):a.value===i.attributes.xfaOff&&t.removeAttribute("checked");if("print"===n)break;t.addEventListener("change",(t=>{s.setValue(e,{value:t.target.checked?t.target.getAttribute("xfaOn"):t.target.getAttribute("xfaOff")})}))}else{null!==a.value&&t.setAttribute("value",a.value);if("print"===n)break;t.addEventListener("input",(t=>{s.setValue(e,{value:t.target.value})}))}break;case"select":if(null!==a.value){t.setAttribute("value",a.value);for(const t of i.children)t.attributes.value===a.value?t.attributes.selected=!0:t.attributes.hasOwnProperty("selected")&&delete t.attributes.selected}t.addEventListener("input",(t=>{const i=t.target.options,n=-1===i.selectedIndex?"":i[i.selectedIndex].value;s.setValue(e,{value:n})}))}}static setAttributes({html:t,element:e,storage:i=null,intent:s,linkService:n}){const{attributes:a}=e,r=t instanceof HTMLAnchorElement;"radio"===a.type&&(a.name=`${a.name}-${s}`);for(const[e,i]of Object.entries(a))if(null!=i)switch(e){case"class":i.length&&t.setAttribute(e,i.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",i);break;case"style":Object.assign(t.style,i);break;case"textContent":t.textContent=i;break;default:(!r||"href"!==e&&"newWindow"!==e)&&t.setAttribute(e,i)}r&&n.addLinkAttributes(t,a.href,a.newWindow);i&&a.dataId&&this.setupStorage(t,a.dataId,e,i)}static render(t){const e=t.annotationStorage,i=t.linkService,s=t.xfaHtml,n=t.intent||"display",a=document.createElement(s.name);s.attributes&&this.setAttributes({html:a,element:s,intent:n,linkService:i});const r="richText"!==n,o=t.div;o.append(a);if(t.viewport){const e=`matrix(${t.viewport.transform.join(",")})`;o.style.transform=e}r&&o.setAttribute("class","xfaLayer xfaFont");const l=[];if(0===s.children.length){if(s.value){const t=document.createTextNode(s.value);a.append(t);r&&XfaText.shouldBuildText(s.name)&&l.push(t)}return{textDivs:l}}const h=[[s,-1,a]];for(;h.length>0;){const[t,s,a]=h.at(-1);if(s+1===t.children.length){h.pop();continue}const o=t.children[++h.at(-1)[1]];if(null===o)continue;const{name:d}=o;if("#text"===d){const t=document.createTextNode(o.value);l.push(t);a.append(t);continue}const c=o?.attributes?.xmlns?document.createElementNS(o.attributes.xmlns,d):document.createElement(d);a.append(c);o.attributes&&this.setAttributes({html:c,element:o,storage:e,intent:n,linkService:i});if(o.children?.length>0)h.push([o,-1,c]);else if(o.value){const t=document.createTextNode(o.value);r&&XfaText.shouldBuildText(d)&&l.push(t);c.append(t)}}for(const t of o.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))t.setAttribute("readOnly",!0);return{textDivs:l}}static update(t){const e=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=e;t.div.hidden=!1}}const Bt=1e3,Ht=new WeakSet;function getRectDims(t){return{width:t[2]-t[0],height:t[3]-t[1]}}class AnnotationElementFactory{static create(t){switch(t.data.annotationType){case S:return new LinkAnnotationElement(t);case E:return new TextAnnotationElement(t);case U:switch(t.data.fieldType){case"Tx":return new TextWidgetAnnotationElement(t);case"Btn":return t.data.radioButton?new RadioButtonWidgetAnnotationElement(t):t.data.checkBox?new CheckboxWidgetAnnotationElement(t):new PushButtonWidgetAnnotationElement(t);case"Ch":return new ChoiceWidgetAnnotationElement(t);case"Sig":return new SignatureWidgetAnnotationElement(t)}return new WidgetAnnotationElement(t);case H:return new PopupAnnotationElement(t);case C:return new FreeTextAnnotationElement(t);case T:return new LineAnnotationElement(t);case M:return new SquareAnnotationElement(t);case P:return new CircleAnnotationElement(t);case k:return new PolylineAnnotationElement(t);case N:return new CaretAnnotationElement(t);case B:return new InkAnnotationElement(t);case D:return new PolygonAnnotationElement(t);case R:return new HighlightAnnotationElement(t);case I:return new UnderlineAnnotationElement(t);case F:return new SquigglyAnnotationElement(t);case L:return new StrikeOutAnnotationElement(t);case O:return new StampAnnotationElement(t);case z:return new FileAttachmentAnnotationElement(t);default:return new AnnotationElement(t)}}}class AnnotationElement{#Hs=null;#zs=!1;#Us=null;constructor(t,{isRenderable:e=!1,ignoreBorder:i=!1,createQuadrilaterals:s=!1}={}){this.isRenderable=e;this.data=t.data;this.layer=t.layer;this.linkService=t.linkService;this.downloadManager=t.downloadManager;this.imageResourcesPath=t.imageResourcesPath;this.renderForms=t.renderForms;this.svgFactory=t.svgFactory;this.annotationStorage=t.annotationStorage;this.enableScripting=t.enableScripting;this.hasJSActions=t.hasJSActions;this._fieldObjects=t.fieldObjects;this.parent=t.parent;e&&(this.container=this._createContainer(i));s&&this._createQuadrilaterals()}static _hasPopupData({titleObj:t,contentsObj:e,richText:i}){return!!(t?.str||e?.str||i?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return AnnotationElement._hasPopupData(this.data)}updateEdited(t){if(!this.container)return;this.#Hs||={rect:this.data.rect.slice(0)};const{rect:e}=t;e&&this.#Gs(e);this.#Us?.popup.updateEdited(t)}resetEdited(){if(this.#Hs){this.#Gs(this.#Hs.rect);this.#Us?.popup.resetEdited();this.#Hs=null}}#Gs(t){const{container:{style:e},data:{rect:i,rotation:s},parent:{viewport:{rawDims:{pageWidth:n,pageHeight:a,pageX:r,pageY:o}}}}=this;i?.splice(0,4,...t);const{width:l,height:h}=getRectDims(t);e.left=100*(t[0]-r)/n+"%";e.top=100*(a-t[3]+o)/a+"%";if(0===s){e.width=100*l/n+"%";e.height=100*h/a+"%"}else this.setRotation(s)}_createContainer(t){const{data:e,parent:{page:i,viewport:s}}=this,n=document.createElement("section");n.setAttribute("data-annotation-id",e.id);this instanceof WidgetAnnotationElement||(n.tabIndex=Bt);const{style:a}=n;a.zIndex=this.parent.zIndex++;e.alternativeText&&(n.title=e.alternativeText);e.noRotate&&n.classList.add("norotate");if(!e.rect||this instanceof PopupAnnotationElement){const{rotation:t}=e;e.hasOwnCanvas||0===t||this.setRotation(t,n);return n}const{width:r,height:o}=getRectDims(e.rect);if(!t&&e.borderStyle.width>0){a.borderWidth=`${e.borderStyle.width}px`;const t=e.borderStyle.horizontalCornerRadius,i=e.borderStyle.verticalCornerRadius;if(t>0||i>0){const e=`calc(${t}px * var(--scale-factor)) / calc(${i}px * var(--scale-factor))`;a.borderRadius=e}else if(this instanceof RadioButtonWidgetAnnotationElement){const t=`calc(${r}px * var(--scale-factor)) / calc(${o}px * var(--scale-factor))`;a.borderRadius=t}switch(e.borderStyle.style){case G:a.borderStyle="solid";break;case $:a.borderStyle="dashed";break;case V:warn("Unimplemented border style: beveled");break;case j:warn("Unimplemented border style: inset");break;case W:a.borderBottomStyle="solid"}const s=e.borderColor||null;if(s){this.#zs=!0;a.borderColor=Util.makeHexColor(0|s[0],0|s[1],0|s[2])}else a.borderWidth=0}const l=Util.normalizeRect([e.rect[0],i.view[3]-e.rect[1]+i.view[1],e.rect[2],i.view[3]-e.rect[3]+i.view[1]]),{pageWidth:h,pageHeight:d,pageX:c,pageY:u}=s.rawDims;a.left=100*(l[0]-c)/h+"%";a.top=100*(l[1]-u)/d+"%";const{rotation:p}=e;if(e.hasOwnCanvas||0===p){a.width=100*r/h+"%";a.height=100*o/d+"%"}else this.setRotation(p,n);return n}setRotation(t,e=this.container){if(!this.data.rect)return;const{pageWidth:i,pageHeight:s}=this.parent.viewport.rawDims,{width:n,height:a}=getRectDims(this.data.rect);let r,o;if(t%180==0){r=100*n/i;o=100*a/s}else{r=100*a/i;o=100*n/s}e.style.width=`${r}%`;e.style.height=`${o}%`;e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const setColor=(t,e,i)=>{const s=i.detail[t],n=s[0],a=s.slice(1);i.target.style[e]=ColorConverters[`${n}_HTML`](a);this.annotationStorage.setValue(this.data.id,{[e]:ColorConverters[`${n}_rgb`](a)})};return shadow(this,"_commonActions",{display:t=>{const{display:e}=t.detail,i=e%2==1;this.container.style.visibility=i?"hidden":"visible";this.annotationStorage.setValue(this.data.id,{noView:i,noPrint:1===e||2===e})},print:t=>{this.annotationStorage.setValue(this.data.id,{noPrint:!t.detail.print})},hidden:t=>{const{hidden:e}=t.detail;this.container.style.visibility=e?"hidden":"visible";this.annotationStorage.setValue(this.data.id,{noPrint:e,noView:e})},focus:t=>{setTimeout((()=>t.target.focus({preventScroll:!1})),0)},userName:t=>{t.target.title=t.detail.userName},readonly:t=>{t.target.disabled=t.detail.readonly},required:t=>{this._setRequired(t.target,t.detail.required)},bgColor:t=>{setColor("bgColor","backgroundColor",t)},fillColor:t=>{setColor("fillColor","backgroundColor",t)},fgColor:t=>{setColor("fgColor","color",t)},textColor:t=>{setColor("textColor","color",t)},borderColor:t=>{setColor("borderColor","borderColor",t)},strokeColor:t=>{setColor("strokeColor","borderColor",t)},rotation:t=>{const e=t.detail.rotation;this.setRotation(e);this.annotationStorage.setValue(this.data.id,{rotation:e})}})}_dispatchEventFromSandbox(t,e){const i=this._commonActions;for(const s of Object.keys(e.detail)){const n=t[s]||i[s];n?.(e)}}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;const e=this.annotationStorage.getRawValue(this.data.id);if(!e)return;const i=this._commonActions;for(const[s,n]of Object.entries(e)){const a=i[s];if(a){a({detail:{[s]:n},target:t});delete e[s]}}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:t}=this.data;if(!t)return;const[e,i,s,n]=this.data.rect.map((t=>Math.fround(t)));if(8===t.length){const[a,r,o,l]=t.subarray(2,6);if(s===a&&n===r&&e===o&&i===l)return}const{style:a}=this.container;let r;if(this.#zs){const{borderColor:t,borderWidth:e}=a;a.borderWidth=0;r=["url('data:image/svg+xml;utf8,",'',``];this.container.classList.add("hasBorder")}const o=s-e,l=n-i,{svgFactory:h}=this,d=h.createElement("svg");d.classList.add("quadrilateralsContainer");d.setAttribute("width",0);d.setAttribute("height",0);const c=h.createElement("defs");d.append(c);const u=h.createElement("clipPath"),p=`clippath_${this.data.id}`;u.setAttribute("id",p);u.setAttribute("clipPathUnits","objectBoundingBox");c.append(u);for(let i=2,s=t.length;i`)}if(this.#zs){r.push("')");a.backgroundImage=r.join("")}this.container.append(d);this.container.style.clipPath=`url(#${p})`}_createPopup(){const{data:t}=this,e=this.#Us=new PopupAnnotationElement({data:{color:t.color,titleObj:t.titleObj,modificationDate:t.modificationDate,contentsObj:t.contentsObj,richText:t.richText,parentRect:t.rect,borderStyle:0,id:`popup_${t.id}`,rotation:t.rotation},parent:this.parent,elements:[this]});this.parent.div.append(e.render())}render(){unreachable("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){const i=[];if(this._fieldObjects){const s=this._fieldObjects[t];if(s)for(const{page:t,id:n,exportValues:a}of s){if(-1===t)continue;if(n===e)continue;const s="string"==typeof a?a:null,r=document.querySelector(`[data-element-id="${n}"]`);!r||Ht.has(r)?i.push({id:n,exportValue:s,domElement:r}):warn(`_getElementsByName - element not allowed: ${n}`)}return i}for(const s of document.getElementsByName(t)){const{exportValue:t}=s,n=s.getAttribute("data-element-id");n!==e&&(Ht.has(s)&&i.push({id:n,exportValue:t,domElement:s}))}return i}show(){this.container&&(this.container.hidden=!1);this.popup?.maybeShow()}hide(){this.container&&(this.container.hidden=!0);this.popup?.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){const t=this.getElementsToTriggerPopup();if(Array.isArray(t))for(const e of t)e.classList.add("highlightArea");else t.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;const{annotationEditorType:t,data:{id:e}}=this;this.container.addEventListener("dblclick",(()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:t,editId:e})}))}}class LinkAnnotationElement extends AnnotationElement{constructor(t,e=null){super(t,{isRenderable:!0,ignoreBorder:!!e?.ignoreBorder,createQuadrilaterals:!0});this.isTooltipOnly=t.data.isTooltipOnly}render(){const{data:t,linkService:e}=this,i=document.createElement("a");i.setAttribute("data-element-id",t.id);let s=!1;if(t.url){e.addLinkAttributes(i,t.url,t.newWindow);s=!0}else if(t.action){this._bindNamedAction(i,t.action);s=!0}else if(t.attachment){this.#$s(i,t.attachment,t.attachmentDest);s=!0}else if(t.setOCGState){this.#Vs(i,t.setOCGState);s=!0}else if(t.dest){this._bindLink(i,t.dest);s=!0}else{if(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions){this._bindJSAction(i,t);s=!0}if(t.resetForm){this._bindResetFormAction(i,t.resetForm);s=!0}else if(this.isTooltipOnly&&!s){this._bindLink(i,"");s=!0}}this.container.classList.add("linkAnnotation");s&&this.container.append(i);return this.container}#js(){this.container.setAttribute("data-internal-link","")}_bindLink(t,e){t.href=this.linkService.getDestinationHash(e);t.onclick=()=>{e&&this.linkService.goToDestination(e);return!1};(e||""===e)&&this.#js()}_bindNamedAction(t,e){t.href=this.linkService.getAnchorUrl("");t.onclick=()=>{this.linkService.executeNamedAction(e);return!1};this.#js()}#$s(t,e,i=null){t.href=this.linkService.getAnchorUrl("");e.description&&(t.title=e.description);t.onclick=()=>{this.downloadManager?.openOrDownloadData(e.content,e.filename,i);return!1};this.#js()}#Vs(t,e){t.href=this.linkService.getAnchorUrl("");t.onclick=()=>{this.linkService.executeSetOCGState(e);return!1};this.#js()}_bindJSAction(t,e){t.href=this.linkService.getAnchorUrl("");const i=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const s of Object.keys(e.actions)){const n=i.get(s);n&&(t[n]=()=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e.id,name:s}});return!1})}t.onclick||(t.onclick=()=>!1);this.#js()}_bindResetFormAction(t,e){const i=t.onclick;i||(t.href=this.linkService.getAnchorUrl(""));this.#js();if(this._fieldObjects)t.onclick=()=>{i?.();const{fields:t,refs:s,include:n}=e,a=[];if(0!==t.length||0!==s.length){const e=new Set(s);for(const i of t){const t=this._fieldObjects[i]||[];for(const{id:i}of t)e.add(i)}for(const t of Object.values(this._fieldObjects))for(const i of t)e.has(i.id)===n&&a.push(i)}else for(const t of Object.values(this._fieldObjects))a.push(...t);const r=this.annotationStorage,o=[];for(const t of a){const{id:e}=t;o.push(e);switch(t.type){case"text":{const i=t.defaultValue||"";r.setValue(e,{value:i});break}case"checkbox":case"radiobutton":{const i=t.defaultValue===t.exportValues;r.setValue(e,{value:i});break}case"combobox":case"listbox":{const i=t.defaultValue||"";r.setValue(e,{value:i});break}default:continue}const i=document.querySelector(`[data-element-id="${e}"]`);i&&(Ht.has(i)?i.dispatchEvent(new Event("resetform")):warn(`_bindResetFormAction - element not allowed: ${e}`))}this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:o,name:"ResetForm"}});return!1};else{warn('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.');i||(t.onclick=()=>!1)}}}class TextAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");const t=document.createElement("img");t.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg";t.setAttribute("data-l10n-id","pdfjs-text-annotation-type");t.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name}));!this.data.popupRef&&this.hasPopupData&&this._createPopup();this.container.append(t);return this.container}}class WidgetAnnotationElement extends AnnotationElement{render(){return this.container}showElementAndHideCanvas(t){if(this.data.hasOwnCanvas){"CANVAS"===t.previousSibling?.nodeName&&(t.previousSibling.hidden=!0);t.hidden=!1}}_getKeyModifier(t){return util_FeatureTest.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,e,i,s,n){i.includes("mouse")?t.addEventListener(i,(t=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:s,value:n(t),shift:t.shiftKey,modifier:this._getKeyModifier(t)}})})):t.addEventListener(i,(t=>{if("blur"===i){if(!e.focused||!t.relatedTarget)return;e.focused=!1}else if("focus"===i){if(e.focused)return;e.focused=!0}n&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:s,value:n(t)}})}))}_setEventListeners(t,e,i,s){for(const[n,a]of i)if("Action"===a||this.data.actions?.[a]){"Focus"!==a&&"Blur"!==a||(e||={focused:!1});this._setEventListener(t,e,n,a,s);"Focus"!==a||this.data.actions?.Blur?"Blur"!==a||this.data.actions?.Focus||this._setEventListener(t,e,"focus","Focus",null):this._setEventListener(t,e,"blur","Blur",null)}}_setBackgroundColor(t){const e=this.data.backgroundColor||null;t.style.backgroundColor=null===e?"transparent":Util.makeHexColor(e[0],e[1],e[2])}_setTextStyle(t){const e=["left","center","right"],{fontColor:i}=this.data.defaultAppearanceData,s=this.data.defaultAppearanceData.fontSize||9,a=t.style;let r;const roundToOneDecimal=t=>Math.round(10*t)/10;if(this.data.multiLine){const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2),e=t/(Math.round(t/(n*s))||1);r=Math.min(s,roundToOneDecimal(e/n))}else{const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2);r=Math.min(s,roundToOneDecimal(t/n))}a.fontSize=`calc(${r}px * var(--scale-factor))`;a.color=Util.makeHexColor(i[0],i[1],i[2]);null!==this.data.textAlignment&&(a.textAlign=e[this.data.textAlignment])}_setRequired(t,e){e?t.setAttribute("required",!0):t.removeAttribute("required");t.setAttribute("aria-required",e)}}class TextWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms||t.data.hasOwnCanvas||!t.data.hasAppearance&&!!t.data.fieldValue})}setPropertyOnSiblings(t,e,i,s){const n=this.annotationStorage;for(const a of this._getElementsByName(t.name,t.id)){a.domElement&&(a.domElement[e]=i);n.setValue(a.id,{[s]:i})}}render(){const t=this.annotationStorage,e=this.data.id;this.container.classList.add("textWidgetAnnotation");let i=null;if(this.renderForms){const s=t.getValue(e,{value:this.data.fieldValue});let n=s.value||"";const a=t.getValue(e,{charLimit:this.data.maxLen}).charLimit;a&&n.length>a&&(n=n.slice(0,a));let r=s.formattedValue||this.data.textContent?.join("\n")||null;r&&this.data.comb&&(r=r.replaceAll(/\s+/g,""));const o={userValue:n,formattedValue:r,lastCommittedValue:null,commitKey:1,focused:!1};if(this.data.multiLine){i=document.createElement("textarea");i.textContent=r??n;this.data.doNotScroll&&(i.style.overflowY="hidden")}else{i=document.createElement("input");i.type="text";i.setAttribute("value",r??n);this.data.doNotScroll&&(i.style.overflowX="hidden")}this.data.hasOwnCanvas&&(i.hidden=!0);Ht.add(i);i.setAttribute("data-element-id",e);i.disabled=this.data.readOnly;i.name=this.data.fieldName;i.tabIndex=Bt;this._setRequired(i,this.data.required);a&&(i.maxLength=a);i.addEventListener("input",(s=>{t.setValue(e,{value:s.target.value});this.setPropertyOnSiblings(i,"value",s.target.value,"value");o.formattedValue=null}));i.addEventListener("resetform",(t=>{const e=this.data.defaultFieldValue??"";i.value=o.userValue=e;o.formattedValue=null}));let blurListener=t=>{const{formattedValue:e}=o;null!=e&&(t.target.value=e);t.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){i.addEventListener("focus",(t=>{if(o.focused)return;const{target:e}=t;o.userValue&&(e.value=o.userValue);o.lastCommittedValue=e.value;o.commitKey=1;this.data.actions?.Focus||(o.focused=!0)}));i.addEventListener("updatefromsandbox",(i=>{this.showElementAndHideCanvas(i.target);const s={value(i){o.userValue=i.detail.value??"";t.setValue(e,{value:o.userValue.toString()});i.target.value=o.userValue},formattedValue(i){const{formattedValue:s}=i.detail;o.formattedValue=s;null!=s&&i.target!==document.activeElement&&(i.target.value=s);t.setValue(e,{formattedValue:s})},selRange(t){t.target.setSelectionRange(...t.detail.selRange)},charLimit:i=>{const{charLimit:s}=i.detail,{target:n}=i;if(0===s){n.removeAttribute("maxLength");return}n.setAttribute("maxLength",s);let a=o.userValue;if(a&&!(a.length<=s)){a=a.slice(0,s);n.value=o.userValue=a;t.setValue(e,{value:a});this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:a,willCommit:!0,commitKey:1,selStart:n.selectionStart,selEnd:n.selectionEnd}})}}};this._dispatchEventFromSandbox(s,i)}));i.addEventListener("keydown",(t=>{o.commitKey=1;let i=-1;"Escape"===t.key?i=0:"Enter"!==t.key||this.data.multiLine?"Tab"===t.key&&(o.commitKey=3):i=2;if(-1===i)return;const{value:s}=t.target;if(o.lastCommittedValue!==s){o.lastCommittedValue=s;o.userValue=s;this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:s,willCommit:!0,commitKey:i,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}})}}));const s=blurListener;blurListener=null;i.addEventListener("blur",(t=>{if(!o.focused||!t.relatedTarget)return;this.data.actions?.Blur||(o.focused=!1);const{value:i}=t.target;o.userValue=i;o.lastCommittedValue!==i&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:i,willCommit:!0,commitKey:o.commitKey,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}});s(t)}));this.data.actions?.Keystroke&&i.addEventListener("beforeinput",(t=>{o.lastCommittedValue=null;const{data:i,target:s}=t,{value:n,selectionStart:a,selectionEnd:r}=s;let l=a,h=r;switch(t.inputType){case"deleteWordBackward":{const t=n.substring(0,a).match(/\w*[^\w]*$/);t&&(l-=t[0].length);break}case"deleteWordForward":{const t=n.substring(a).match(/^[^\w]*\w*/);t&&(h+=t[0].length);break}case"deleteContentBackward":a===r&&(l-=1);break;case"deleteContentForward":a===r&&(h+=1)}t.preventDefault();this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:n,change:i||"",willCommit:!1,selStart:l,selEnd:h}})}));this._setEventListeners(i,o,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.value))}blurListener&&i.addEventListener("blur",blurListener);if(this.data.comb){const t=(this.data.rect[2]-this.data.rect[0])/a;i.classList.add("comb");i.style.letterSpacing=`calc(${t}px * var(--scale-factor) - 1ch)`}}else{i=document.createElement("div");i.textContent=this.data.fieldValue;i.style.verticalAlign="middle";i.style.display="table-cell";this.data.hasOwnCanvas&&(i.hidden=!0)}this._setTextStyle(i);this._setBackgroundColor(i);this._setDefaultPropertiesFromJS(i);this.container.append(i);return this.container}}class SignatureWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){const t=this.annotationStorage,e=this.data,i=e.id;let s=t.getValue(i,{value:e.exportValue===e.fieldValue}).value;if("string"==typeof s){s="Off"!==s;t.setValue(i,{value:s})}this.container.classList.add("buttonWidgetAnnotation","checkBox");const n=document.createElement("input");Ht.add(n);n.setAttribute("data-element-id",i);n.disabled=e.readOnly;this._setRequired(n,this.data.required);n.type="checkbox";n.name=e.fieldName;s&&n.setAttribute("checked",!0);n.setAttribute("exportValue",e.exportValue);n.tabIndex=Bt;n.addEventListener("change",(s=>{const{name:n,checked:a}=s.target;for(const s of this._getElementsByName(n,i)){const i=a&&s.exportValue===e.exportValue;s.domElement&&(s.domElement.checked=i);t.setValue(s.id,{value:i})}t.setValue(i,{value:a})}));n.addEventListener("resetform",(t=>{const i=e.defaultFieldValue||"Off";t.target.checked=i===e.exportValue}));if(this.enableScripting&&this.hasJSActions){n.addEventListener("updatefromsandbox",(e=>{const s={value(e){e.target.checked="Off"!==e.detail.value;t.setValue(i,{value:e.target.checked})}};this._dispatchEventFromSandbox(s,e)}));this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.checked))}this._setBackgroundColor(n);this._setDefaultPropertiesFromJS(n);this.container.append(n);return this.container}}class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const t=this.annotationStorage,e=this.data,i=e.id;let s=t.getValue(i,{value:e.fieldValue===e.buttonValue}).value;if("string"==typeof s){s=s!==e.buttonValue;t.setValue(i,{value:s})}if(s)for(const s of this._getElementsByName(e.fieldName,i))t.setValue(s.id,{value:!1});const n=document.createElement("input");Ht.add(n);n.setAttribute("data-element-id",i);n.disabled=e.readOnly;this._setRequired(n,this.data.required);n.type="radio";n.name=e.fieldName;s&&n.setAttribute("checked",!0);n.tabIndex=Bt;n.addEventListener("change",(e=>{const{name:s,checked:n}=e.target;for(const e of this._getElementsByName(s,i))t.setValue(e.id,{value:!1});t.setValue(i,{value:n})}));n.addEventListener("resetform",(t=>{const i=e.defaultFieldValue;t.target.checked=null!=i&&i===e.buttonValue}));if(this.enableScripting&&this.hasJSActions){const s=e.buttonValue;n.addEventListener("updatefromsandbox",(e=>{const n={value:e=>{const n=s===e.detail.value;for(const s of this._getElementsByName(e.target.name)){const e=n&&s.id===i;s.domElement&&(s.domElement.checked=e);t.setValue(s.id,{value:e})}}};this._dispatchEventFromSandbox(n,e)}));this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.checked))}this._setBackgroundColor(n);this._setDefaultPropertiesFromJS(n);this.container.append(n);return this.container}}class PushButtonWidgetAnnotationElement extends LinkAnnotationElement{constructor(t){super(t,{ignoreBorder:t.data.hasAppearance})}render(){const t=super.render();t.classList.add("buttonWidgetAnnotation","pushButton");const e=t.lastChild;if(this.enableScripting&&this.hasJSActions&&e){this._setDefaultPropertiesFromJS(e);e.addEventListener("updatefromsandbox",(t=>{this._dispatchEventFromSandbox({},t)}))}return t}}class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");const t=this.annotationStorage,e=this.data.id,i=t.getValue(e,{value:this.data.fieldValue}),s=document.createElement("select");Ht.add(s);s.setAttribute("data-element-id",e);s.disabled=this.data.readOnly;this._setRequired(s,this.data.required);s.name=this.data.fieldName;s.tabIndex=Bt;let n=this.data.combo&&this.data.options.length>0;if(!this.data.combo){s.size=this.data.options.length;this.data.multiSelect&&(s.multiple=!0)}s.addEventListener("resetform",(t=>{const e=this.data.defaultFieldValue;for(const t of s.options)t.selected=t.value===e}));for(const t of this.data.options){const e=document.createElement("option");e.textContent=t.displayValue;e.value=t.exportValue;if(i.value.includes(t.exportValue)){e.setAttribute("selected",!0);n=!1}s.append(e)}let a=null;if(n){const t=document.createElement("option");t.value=" ";t.setAttribute("hidden",!0);t.setAttribute("selected",!0);s.prepend(t);a=()=>{t.remove();s.removeEventListener("input",a);a=null};s.addEventListener("input",a)}const getValue=t=>{const e=t?"value":"textContent",{options:i,multiple:n}=s;return n?Array.prototype.filter.call(i,(t=>t.selected)).map((t=>t[e])):-1===i.selectedIndex?null:i[i.selectedIndex][e]};let r=getValue(!1);const getItems=t=>{const e=t.target.options;return Array.prototype.map.call(e,(t=>({displayValue:t.textContent,exportValue:t.value})))};if(this.enableScripting&&this.hasJSActions){s.addEventListener("updatefromsandbox",(i=>{const n={value(i){a?.();const n=i.detail.value,o=new Set(Array.isArray(n)?n:[n]);for(const t of s.options)t.selected=o.has(t.value);t.setValue(e,{value:getValue(!0)});r=getValue(!1)},multipleSelection(t){s.multiple=!0},remove(i){const n=s.options,a=i.detail.remove;n[a].selected=!1;s.remove(a);if(n.length>0){-1===Array.prototype.findIndex.call(n,(t=>t.selected))&&(n[0].selected=!0)}t.setValue(e,{value:getValue(!0),items:getItems(i)});r=getValue(!1)},clear(i){for(;0!==s.length;)s.remove(0);t.setValue(e,{value:null,items:[]});r=getValue(!1)},insert(i){const{index:n,displayValue:a,exportValue:o}=i.detail.insert,l=s.children[n],h=document.createElement("option");h.textContent=a;h.value=o;l?l.before(h):s.append(h);t.setValue(e,{value:getValue(!0),items:getItems(i)});r=getValue(!1)},items(i){const{items:n}=i.detail;for(;0!==s.length;)s.remove(0);for(const t of n){const{displayValue:e,exportValue:i}=t,n=document.createElement("option");n.textContent=e;n.value=i;s.append(n)}s.options.length>0&&(s.options[0].selected=!0);t.setValue(e,{value:getValue(!0),items:getItems(i)});r=getValue(!1)},indices(i){const s=new Set(i.detail.indices);for(const t of i.target.options)t.selected=s.has(t.index);t.setValue(e,{value:getValue(!0)});r=getValue(!1)},editable(t){t.target.disabled=!t.detail.editable}};this._dispatchEventFromSandbox(n,i)}));s.addEventListener("input",(i=>{const s=getValue(!0),n=getValue(!1);t.setValue(e,{value:s});i.preventDefault();this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:r,change:n,changeEx:s,willCommit:!1,commitKey:1,keyDown:!1}})}));this._setEventListeners(s,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],(t=>t.target.value))}else s.addEventListener("input",(function(i){t.setValue(e,{value:getValue(!0)})}));this.data.combo&&this._setTextStyle(s);this._setBackgroundColor(s);this._setDefaultPropertiesFromJS(s);this.container.append(s);return this.container}}class PopupAnnotationElement extends AnnotationElement{constructor(t){const{data:e,elements:i}=t;super(t,{isRenderable:AnnotationElement._hasPopupData(e)});this.elements=i;this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new PopupElement({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate,contentsObj:this.data.contentsObj,richText:this.data.richText,rect:this.data.rect,parentRect:this.data.parentRect||null,parent:this.parent,elements:this.elements,open:this.data.open}),e=[];for(const i of this.elements){i.popup=t;i.container.ariaHasPopup="dialog";e.push(i.data.id);i.addHighlightArea()}this.container.setAttribute("aria-controls",e.map((t=>`${et}${t}`)).join(","));return this.container}}class PopupElement{#Ws=this.#qs.bind(this);#Xs=this.#Ks.bind(this);#Ys=this.#Qs.bind(this);#Js=this.#Zs.bind(this);#tn=null;#pt=null;#en=null;#in=null;#sn=null;#nn=null;#an=null;#rn=!1;#on=null;#C=null;#ln=null;#hn=null;#dn=null;#Hs=null;#cn=!1;constructor({container:t,color:e,elements:i,titleObj:s,modificationDate:n,contentsObj:a,richText:r,parent:o,rect:l,parentRect:h,open:d}){this.#pt=t;this.#dn=s;this.#en=a;this.#hn=r;this.#nn=o;this.#tn=e;this.#ln=l;this.#an=h;this.#sn=i;this.#in=PDFDateString.toDateObject(n);this.trigger=i.flatMap((t=>t.getElementsToTriggerPopup()));for(const t of this.trigger){t.addEventListener("click",this.#Js);t.addEventListener("mouseenter",this.#Ys);t.addEventListener("mouseleave",this.#Xs);t.classList.add("popupTriggerArea")}for(const t of i)t.container?.addEventListener("keydown",this.#Ws);this.#pt.hidden=!0;d&&this.#Zs()}render(){if(this.#on)return;const t=this.#on=document.createElement("div");t.className="popup";if(this.#tn){const e=t.style.outlineColor=Util.makeHexColor(...this.#tn);if(CSS.supports("background-color","color-mix(in srgb, red 30%, white)"))t.style.backgroundColor=`color-mix(in srgb, ${e} 30%, white)`;else{const e=.7;t.style.backgroundColor=Util.makeHexColor(...this.#tn.map((t=>Math.floor(e*(255-t)+t))))}}const e=document.createElement("span");e.className="header";const i=document.createElement("h1");e.append(i);({dir:i.dir,str:i.textContent}=this.#dn);t.append(e);if(this.#in){const t=document.createElement("span");t.classList.add("popupDate");t.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string");t.setAttribute("data-l10n-args",JSON.stringify({dateObj:this.#in.valueOf()}));e.append(t)}const s=this.#un;if(s){XfaLayer.render({xfaHtml:s,intent:"richText",div:t});t.lastChild.classList.add("richText","popupContent")}else{const e=this._formatContents(this.#en);t.append(e)}this.#pt.append(t)}get#un(){const t=this.#hn,e=this.#en;return!t?.str||e?.str&&e.str!==t.str?null:this.#hn.html||null}get#pn(){return this.#un?.attributes?.style?.fontSize||0}get#gn(){return this.#un?.attributes?.style?.color||null}#mn(t){const e=[],i={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},s={style:{color:this.#gn,fontSize:this.#pn?`calc(${this.#pn}px * var(--scale-factor))`:""}};for(const i of t.split("\n"))e.push({name:"span",value:i,attributes:s});return i}_formatContents({str:t,dir:e}){const i=document.createElement("p");i.classList.add("popupContent");i.dir=e;const s=t.split(/(?:\r\n?|\n)/);for(let t=0,e=s.length;t=0&&n.setAttribute("stroke-width",e||1);if(i)for(let t=0,e=this.#xn.length;t{"Enter"===t.key&&(s?t.metaKey:t.ctrlKey)&&this.#Sn()}));!e.popupRef&&this.hasPopupData?this._createPopup():i.classList.add("popupTriggerArea");t.append(i);return t}getElementsToTriggerPopup(){return this.#En}addHighlightArea(){this.container.classList.add("highlightArea")}#Sn(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}}class AnnotationLayer{#Cn=null;#Tn=null;#Mn=new Map;#Pn=null;constructor({div:t,accessibilityManager:e,annotationCanvasMap:i,annotationEditorUIManager:s,page:n,viewport:a,structTreeLayer:r}){this.div=t;this.#Cn=e;this.#Tn=i;this.#Pn=r||null;this.page=n;this.viewport=a;this.zIndex=0;this._annotationEditorUIManager=s}hasEditableAnnotations(){return this.#Mn.size>0}async#Dn(t,e){const i=t.firstChild||t,s=i.id=`${et}${e}`,n=await(this.#Pn?.getAriaAttributes(s));if(n)for(const[t,e]of n)i.setAttribute(t,e);this.div.append(t);this.#Cn?.moveElementInDOM(this.div,t,i,!1)}async render(t){const{annotations:e}=t,i=this.div;setLayerDimensions(i,this.viewport);const s=new Map,n={data:null,layer:i,linkService:t.linkService,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:!1!==t.renderForms,svgFactory:new DOMSVGFactory,annotationStorage:t.annotationStorage||new AnnotationStorage,enableScripting:!0===t.enableScripting,hasJSActions:t.hasJSActions,fieldObjects:t.fieldObjects,parent:this,elements:null};for(const t of e){if(t.noHTML)continue;const e=t.annotationType===H;if(e){const e=s.get(t.id);if(!e)continue;n.elements=e}else{const{width:e,height:i}=getRectDims(t.rect);if(e<=0||i<=0)continue}n.data=t;const i=AnnotationElementFactory.create(n);if(!i.isRenderable)continue;if(!e&&t.popupRef){const e=s.get(t.popupRef);e?e.push(i):s.set(t.popupRef,[i])}const a=i.render();t.hidden&&(a.style.visibility="hidden");await this.#Dn(a,t.id);if(i._isEditable){this.#Mn.set(i.data.id,i);this._annotationEditorUIManager?.renderAnnotationElement(i)}}this.#kn()}update({viewport:t}){const e=this.div;this.viewport=t;setLayerDimensions(e,{rotation:t.rotation});this.#kn();e.hidden=!1}#kn(){if(!this.#Tn)return;const t=this.div;for(const[e,i]of this.#Tn){const s=t.querySelector(`[data-annotation-id="${e}"]`);if(!s)continue;i.className="annotationContent";const{firstChild:n}=s;n?"CANVAS"===n.nodeName?n.replaceWith(i):n.classList.contains("annotationContent")?n.after(i):n.before(i):s.append(i)}this.#Tn.clear()}getEditableAnnotations(){return Array.from(this.#Mn.values())}getEditableAnnotation(t){return this.#Mn.get(t)}}const zt=/\r\n?|\n/g;class FreeTextEditor extends AnnotationEditor{#tn;#Rn="";#In=`${this.id}-editor`;#Fn=null;#pn;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){const t=FreeTextEditor.prototype,arrowChecker=t=>t.isEmpty(),e=AnnotationEditorUIManager.TRANSLATE_SMALL,i=AnnotationEditorUIManager.TRANSLATE_BIG;return shadow(this,"_keyboardManager",new KeyboardManager([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],t.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],t.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],t._translateEmpty,{args:[-e,0],checker:arrowChecker}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t._translateEmpty,{args:[-i,0],checker:arrowChecker}],[["ArrowRight","mac+ArrowRight"],t._translateEmpty,{args:[e,0],checker:arrowChecker}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t._translateEmpty,{args:[i,0],checker:arrowChecker}],[["ArrowUp","mac+ArrowUp"],t._translateEmpty,{args:[0,-e],checker:arrowChecker}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t._translateEmpty,{args:[0,-i],checker:arrowChecker}],[["ArrowDown","mac+ArrowDown"],t._translateEmpty,{args:[0,e],checker:arrowChecker}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t._translateEmpty,{args:[0,i],checker:arrowChecker}]]))}static _type="freetext";static _editorType=g.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"});this.#tn=t.color||FreeTextEditor._defaultColor||AnnotationEditor._defaultLineColor;this.#pn=t.fontSize||FreeTextEditor._defaultFontSize}static initialize(t,e){AnnotationEditor.initialize(t,e);const i=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(i.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,e){switch(t){case m.FREETEXT_SIZE:FreeTextEditor._defaultFontSize=e;break;case m.FREETEXT_COLOR:FreeTextEditor._defaultColor=e}}updateParams(t,e){switch(t){case m.FREETEXT_SIZE:this.#Ln(e);break;case m.FREETEXT_COLOR:this.#On(e)}}static get defaultPropertiesToUpdate(){return[[m.FREETEXT_SIZE,FreeTextEditor._defaultFontSize],[m.FREETEXT_COLOR,FreeTextEditor._defaultColor||AnnotationEditor._defaultLineColor]]}get propertiesToUpdate(){return[[m.FREETEXT_SIZE,this.#pn],[m.FREETEXT_COLOR,this.#tn]]}#Ln(t){const setFontsize=t=>{this.editorDiv.style.fontSize=`calc(${t}px * var(--scale-factor))`;this.translate(0,-(t-this.#pn)*this.parentScale);this.#pn=t;this.#Nn()},e=this.#pn;this.addCommands({cmd:setFontsize.bind(this,t),undo:setFontsize.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:m.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}#On(t){const setColor=t=>{this.#tn=this.editorDiv.style.color=t},e=this.#tn;this.addCommands({cmd:setColor.bind(this,t),undo:setColor.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:m.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(t,e){this._uiManager.translateSelectedEditors(t,e,!0)}getInitialTranslation(){const t=this.parentScale;return[-FreeTextEditor._internalPadding*t,-(FreeTextEditor._internalPadding+this.#pn)*t]}rebuild(){if(this.parent){super.rebuild();null!==this.div&&(this.isAttachedToDOM||this.parent.add(this))}}enableEditMode(){if(this.isInEditMode())return;this.parent.setEditingState(!1);this.parent.updateToolbar(g.FREETEXT);super.enableEditMode();this.overlayDiv.classList.remove("enabled");this.editorDiv.contentEditable=!0;this._isDraggable=!1;this.div.removeAttribute("aria-activedescendant");this.#Fn=new AbortController;const t=this._uiManager.combinedSignal(this.#Fn);this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:t});this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:t});this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:t});this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:t});this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:t})}disableEditMode(){if(this.isInEditMode()){this.parent.setEditingState(!0);super.disableEditMode();this.overlayDiv.classList.add("enabled");this.editorDiv.contentEditable=!1;this.div.setAttribute("aria-activedescendant",this.#In);this._isDraggable=!0;this.#Fn?.abort();this.#Fn=null;this.div.focus({preventScroll:!0});this.isEditing=!1;this.parent.div.classList.add("freetextEditing")}}focusin(t){if(this._focusEventsAllowed){super.focusin(t);t.target!==this.editorDiv&&this.editorDiv.focus()}}onceAdded(t){if(!this.width){this.enableEditMode();t&&this.editorDiv.focus();this._initialOptions?.isCentered&&this.center();this._initialOptions=null}}isEmpty(){return!this.editorDiv||""===this.editorDiv.innerText.trim()}remove(){this.isEditing=!1;if(this.parent){this.parent.setEditingState(!0);this.parent.div.classList.add("freetextEditing")}super.remove()}#Bn(){const t=[];this.editorDiv.normalize();let e=null;for(const i of this.editorDiv.childNodes)if(e?.nodeType!==Node.TEXT_NODE||"BR"!==i.nodeName){t.push(FreeTextEditor.#Hn(i));e=i}return t.join("\n")}#Nn(){const[t,e]=this.parentDimensions;let i;if(this.isAttachedToDOM)i=this.div.getBoundingClientRect();else{const{currentLayer:t,div:e}=this,s=e.style.display,n=e.classList.contains("hidden");e.classList.remove("hidden");e.style.display="hidden";t.div.append(this.div);i=e.getBoundingClientRect();e.remove();e.style.display=s;e.classList.toggle("hidden",n)}if(this.rotation%180==this.parentRotation%180){this.width=i.width/t;this.height=i.height/e}else{this.width=i.height/t;this.height=i.width/e}this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit();this.disableEditMode();const t=this.#Rn,e=this.#Rn=this.#Bn().trimEnd();if(t===e)return;const setText=t=>{this.#Rn=t;if(t){this.#zn();this._uiManager.rebuild(this);this.#Nn()}else this.remove()};this.addCommands({cmd:()=>{setText(e)},undo:()=>{setText(t)},mustExec:!1});this.#Nn()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode();this.editorDiv.focus()}dblclick(t){this.enterInEditMode()}keydown(t){if(t.target===this.div&&"Enter"===t.key){this.enterInEditMode();t.preventDefault()}}editorDivKeydown(t){FreeTextEditor._keyboardManager.exec(this,t)}editorDivFocus(t){this.isEditing=!0}editorDivBlur(t){this.isEditing=!1}editorDivInput(t){this.parent.div.classList.toggle("freetextEditing",this.isEmpty())}disableEditing(){this.editorDiv.setAttribute("role","comment");this.editorDiv.removeAttribute("aria-multiline")}enableEditing(){this.editorDiv.setAttribute("role","textbox");this.editorDiv.setAttribute("aria-multiline",!0)}render(){if(this.div)return this.div;let t,e;if(this.width){t=this.x;e=this.y}super.render();this.editorDiv=document.createElement("div");this.editorDiv.className="internal";this.editorDiv.setAttribute("id",this.#In);this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text2");this.editorDiv.setAttribute("data-l10n-attrs","default-content");this.enableEditing();this.editorDiv.contentEditable=!0;const{style:i}=this.editorDiv;i.fontSize=`calc(${this.#pn}px * var(--scale-factor))`;i.color=this.#tn;this.div.append(this.editorDiv);this.overlayDiv=document.createElement("div");this.overlayDiv.classList.add("overlay","enabled");this.div.append(this.overlayDiv);bindEvents(this,this.div,["dblclick","keydown"]);if(this.width){const[i,s]=this.parentDimensions;if(this.annotationElementId){const{position:n}=this._initialData;let[a,r]=this.getInitialTranslation();[a,r]=this.pageTranslationToScreen(a,r);const[o,l]=this.pageDimensions,[h,d]=this.pageTranslation;let c,u;switch(this.rotation){case 0:c=t+(n[0]-h)/o;u=e+this.height-(n[1]-d)/l;break;case 90:c=t+(n[0]-h)/o;u=e-(n[1]-d)/l;[a,r]=[r,-a];break;case 180:c=t-this.width+(n[0]-h)/o;u=e-(n[1]-d)/l;[a,r]=[-a,-r];break;case 270:c=t+(n[0]-h-this.height*l)/o;u=e+(n[1]-d-this.width*o)/l;[a,r]=[-r,a]}this.setAt(c*i,u*s,a,r)}else this.setAt(t*i,e*s,this.width*i,this.height*s);this.#zn();this._isDraggable=!0;this.editorDiv.contentEditable=!1}else{this._isDraggable=!1;this.editorDiv.contentEditable=!0}return this.div}static#Hn(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(zt,"")}editorDivPaste(t){const e=t.clipboardData||window.clipboardData,{types:i}=e;if(1===i.length&&"text/plain"===i[0])return;t.preventDefault();const s=FreeTextEditor.#Un(e.getData("text")||"").replaceAll(zt,"\n");if(!s)return;const n=window.getSelection();if(!n.rangeCount)return;this.editorDiv.normalize();n.deleteFromDocument();const a=n.getRangeAt(0);if(!s.includes("\n")){a.insertNode(document.createTextNode(s));this.editorDiv.normalize();n.collapseToStart();return}const{startContainer:r,startOffset:o}=a,l=[],h=[];if(r.nodeType===Node.TEXT_NODE){const t=r.parentElement;h.push(r.nodeValue.slice(o).replaceAll(zt,""));if(t!==this.editorDiv){let e=l;for(const i of this.editorDiv.childNodes)i!==t?e.push(FreeTextEditor.#Hn(i)):e=h}l.push(r.nodeValue.slice(0,o).replaceAll(zt,""))}else if(r===this.editorDiv){let t=l,e=0;for(const i of this.editorDiv.childNodes){e++===o&&(t=h);t.push(FreeTextEditor.#Hn(i))}}this.#Rn=`${l.join("\n")}${s}${h.join("\n")}`;this.#zn();const d=new Range;let c=l.reduce(((t,e)=>t+e.length),0);for(const{firstChild:t}of this.editorDiv.childNodes)if(t.nodeType===Node.TEXT_NODE){const e=t.nodeValue.length;if(c<=e){d.setStart(t,c);d.setEnd(t,c);break}c-=e}n.removeAllRanges();n.addRange(d)}#zn(){this.editorDiv.replaceChildren();if(this.#Rn)for(const t of this.#Rn.split("\n")){const e=document.createElement("div");e.append(t?document.createTextNode(t):document.createElement("br"));this.editorDiv.append(e)}}#Gn(){return this.#Rn.replaceAll(" "," ")}static#Un(t){return t.replaceAll(" "," ")}get contentDiv(){return this.editorDiv}static async deserialize(t,e,i){let s=null;if(t instanceof FreeTextAnnotationElement){const{data:{defaultAppearanceData:{fontSize:e,fontColor:i},rect:n,rotation:a,id:r,popupRef:o},textContent:l,textPosition:h,parent:{page:{pageNumber:d}}}=t;if(!l||0===l.length)return null;s=t={annotationType:g.FREETEXT,color:Array.from(i),fontSize:e,value:l.join("\n"),position:h,pageIndex:d-1,rect:n.slice(0),rotation:a,id:r,deleted:!1,popupRef:o}}const n=await super.deserialize(t,e,i);n.#pn=t.fontSize;n.#tn=Util.makeHexColor(...t.color);n.#Rn=FreeTextEditor.#Un(t.value);n.annotationElementId=t.id||null;n._initialData=s;return n}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const e=FreeTextEditor._internalPadding*this.parentScale,i=this.getRect(e,e),s=AnnotationEditor._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.#tn),n={annotationType:g.FREETEXT,color:s,fontSize:this.#pn,value:this.#Gn(),pageIndex:this.pageIndex,rect:i,rotation:this.rotation,structTreeParentId:this._structTreeParentId};if(t)return n;if(this.annotationElementId&&!this.#$n(n))return null;n.id=this.annotationElementId;return n}#$n(t){const{value:e,fontSize:i,color:s,pageIndex:n}=this._initialData;return this._hasBeenMoved||t.value!==e||t.fontSize!==i||t.color.some(((t,e)=>t!==s[e]))||t.pageIndex!==n}renderAnnotationElement(t){const e=super.renderAnnotationElement(t);if(this.deleted)return e;const{style:i}=e;i.fontSize=`calc(${this.#pn}px * var(--scale-factor))`;i.color=this.#tn;e.replaceChildren();for(const t of this.#Rn.split("\n")){const i=document.createElement("div");i.append(t?document.createTextNode(t):document.createElement("br"));e.append(i)}const s=FreeTextEditor._internalPadding*this.parentScale;t.updateEdited({rect:this.getRect(s,s),popupContent:this.#Rn});return e}resetAnnotationElement(t){super.resetAnnotationElement(t);t.resetEdited()}}class Outline{static PRECISION=1e-4;toSVGPath(){unreachable("Abstract method `toSVGPath` must be implemented.")}get box(){unreachable("Abstract getter `box` must be implemented.")}serialize(t,e){unreachable("Abstract method `serialize` must be implemented.")}static _rescale(t,e,i,s,n,a){a||=new Float32Array(t.length);for(let r=0,o=t.length;r=6;t-=6)isNaN(e[t])?i.push(`L${e[t+4]} ${e[t+5]}`):i.push(`C${e[t]} ${e[t+1]} ${e[t+2]} ${e[t+3]} ${e[t+4]} ${e[t+5]}`);this.#ha(i);return i.join(" ")}#oa(){const[t,e,i,s]=this.#Vn,[n,a,r,o]=this.#ra();return`M${(this.#Kn[2]-t)/i} ${(this.#Kn[3]-e)/s} L${(this.#Kn[4]-t)/i} ${(this.#Kn[5]-e)/s} L${n} ${a} L${r} ${o} L${(this.#Kn[16]-t)/i} ${(this.#Kn[17]-e)/s} L${(this.#Kn[14]-t)/i} ${(this.#Kn[15]-e)/s} Z`}#ha(t){const e=this.#jn;t.push(`L${e[4]} ${e[5]} Z`)}#la(t){const[e,i,s,n]=this.#Vn,a=this.#Kn.subarray(4,6),r=this.#Kn.subarray(16,18),[o,l,h,d]=this.#ra();t.push(`L${(a[0]-e)/s} ${(a[1]-i)/n} L${o} ${l} L${h} ${d} L${(r[0]-e)/s} ${(r[1]-i)/n}`)}newFreeDrawOutline(t,e,i,s,n,a){return new FreeDrawOutline(t,e,i,s,n,a)}getOutlines(){const t=this.#Xn,e=this.#jn,i=this.#Kn,[s,n,a,r]=this.#Vn,o=new Float32Array((this.#ia?.length??0)+2);for(let t=0,e=o.length-2;t=6;t-=6)for(let i=0;i<6;i+=2)if(isNaN(e[t+i])){l[h]=l[h+1]=NaN;h+=2}else{l[h]=e[t+i];l[h+1]=e[t+i+1];h+=2}this.#ua(l,h);return this.newFreeDrawOutline(l,o,this.#Vn,this.#ta,this.#Wn,this.#qn)}#da(t){const e=this.#Kn,[i,s,n,a]=this.#Vn,[r,o,l,h]=this.#ra(),d=new Float32Array(36);d.set([NaN,NaN,NaN,NaN,(e[2]-i)/n,(e[3]-s)/a,NaN,NaN,NaN,NaN,(e[4]-i)/n,(e[5]-s)/a,NaN,NaN,NaN,NaN,r,o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,(e[16]-i)/n,(e[17]-s)/a,NaN,NaN,NaN,NaN,(e[14]-i)/n,(e[15]-s)/a],0);return this.newFreeDrawOutline(d,t,this.#Vn,this.#ta,this.#Wn,this.#qn)}#ua(t,e){const i=this.#jn;t.set([NaN,NaN,NaN,NaN,i[4],i[5]],e);return e+6}#ca(t,e){const i=this.#Kn.subarray(4,6),s=this.#Kn.subarray(16,18),[n,a,r,o]=this.#Vn,[l,h,d,c]=this.#ra();t.set([NaN,NaN,NaN,NaN,(i[0]-n)/r,(i[1]-a)/o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,d,c,NaN,NaN,NaN,NaN,(s[0]-n)/r,(s[1]-a)/o],e);return e+24}}class FreeDrawOutline extends Outline{#Vn;#pa=new Float32Array(4);#Wn;#qn;#ia;#ta;#ga;constructor(t,e,i,s,n,a){super();this.#ga=t;this.#ia=e;this.#Vn=i;this.#ta=s;this.#Wn=n;this.#qn=a;this.lastPoint=[NaN,NaN];this.#ma(a);const[r,o,l,h]=this.#pa;for(let e=0,i=t.length;et[0]-e[0]||t[1]-e[1]||t[2]-e[2]));const t=[];for(const e of this.#ba)if(e[3]){t.push(...this.#wa(e));this.#va(e)}else{this.#ya(e);t.push(...this.#wa(e))}return this.#xa(t)}#xa(t){const e=[],i=new Set;for(const i of t){const[t,s,n]=i;e.push([t,s,i],[t,n,i])}e.sort(((t,e)=>t[1]-e[1]||t[0]-e[0]));for(let t=0,s=e.length;t0;){const t=i.values().next().value;let[e,a,r,o,l]=t;i.delete(t);let h=e,d=a;n=[e,r];s.push(n);for(;;){let t;if(i.has(o))t=o;else{if(!i.has(l))break;t=l}i.delete(t);[e,a,r,o,l]=t;if(h!==e){n.push(h,d,e,d===a?a:r);h=e}d=d===a?r:a}n.push(h,d)}return new HighlightOutline(s,this.#Vn,this.#fa)}#_a(t){const e=this.#Aa;let i=0,s=e.length-1;for(;i<=s;){const n=i+s>>1,a=e[n][0];if(a===t)return n;a=0;s--){const[i,n]=this.#Aa[s];if(i!==t)break;if(i===t&&n===e){this.#Aa.splice(s,1);return}}}#wa(t){const[e,i,s]=t,n=[[e,i,s]],a=this.#_a(s);for(let t=0;t=i)if(o>s)n[t][1]=s;else{if(1===a)return[];n.splice(t,1);t--;a--}else{n[t][2]=i;o>s&&n.push([e,s,o])}}}return n}}class HighlightOutline extends Outline{#Vn;#Ea;constructor(t,e,i){super();this.#Ea=t;this.#Vn=e;this.lastPoint=i}toSVGPath(){const t=[];for(const e of this.#Ea){let[i,s]=e;t.push(`M${i} ${s}`);for(let n=2;n-1){this.#Xa=!0;this.#Za(t);this.#tr()}else if(this.#Ua){this.#Ha=t.anchorNode;this.#za=t.anchorOffset;this.#Va=t.focusNode;this.#ja=t.focusOffset;this.#er();this.#tr();this.rotate(this.rotation)}}get telemetryInitialData(){return{action:"added",type:this.#Xa?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:this.#ea,methodOfCreation:this.#Ja}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#er(){const t=new HighlightOutliner(this.#Ua,.001);this.#qa=t.getOutlines();[this.x,this.y,this.width,this.height]=this.#qa.box;const e=new HighlightOutliner(this.#Ua,.0025,.001,"ltr"===this._uiManager.direction);this.#$a=e.getOutlines();const{lastPoint:i}=this.#$a;this.#fa=[(i[0]-this.x)/this.width,(i[1]-this.y)/this.height]}#Za({highlightOutlines:t,highlightId:e,clipPathId:i}){this.#qa=t;this.#$a=t.getNewOutline(this.#ea/2+1.5,.0025);if(e>=0){this.#w=e;this.#Ga=i;this.parent.drawLayer.finalizeDraw(e,{bbox:t.box,path:{d:t.toSVGPath()}});this.#Ya=this.parent.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:!0},bbox:this.#$a.box,path:{d:this.#$a.toSVGPath()}},!0)}else if(this.parent){const e=this.parent.viewport.rotation;this.parent.drawLayer.updateProperties(this.#w,{bbox:HighlightEditor.#ir(this.#qa.box,(e-this.rotation+360)%360),path:{d:t.toSVGPath()}});this.parent.drawLayer.updateProperties(this.#Ya,{bbox:HighlightEditor.#ir(this.#$a.box,e),path:{d:this.#$a.toSVGPath()}})}const[s,n,a,r]=t.box;switch(this.rotation){case 0:this.x=s;this.y=n;this.width=a;this.height=r;break;case 90:{const[t,e]=this.parentDimensions;this.x=n;this.y=1-s;this.width=a*e/t;this.height=r*t/e;break}case 180:this.x=1-s;this.y=1-n;this.width=a;this.height=r;break;case 270:{const[t,e]=this.parentDimensions;this.x=1-n;this.y=s;this.width=a*e/t;this.height=r*t/e;break}}const{lastPoint:o}=this.#$a;this.#fa=[(o[0]-s)/a,(o[1]-n)/r]}static initialize(t,e){AnnotationEditor.initialize(t,e);HighlightEditor._defaultColor||=e.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,e){switch(t){case m.HIGHLIGHT_DEFAULT_COLOR:HighlightEditor._defaultColor=e;break;case m.HIGHLIGHT_THICKNESS:HighlightEditor._defaultThickness=e}}translateInPage(t,e){}get toolbarPosition(){return this.#fa}updateParams(t,e){switch(t){case m.HIGHLIGHT_COLOR:this.#On(e);break;case m.HIGHLIGHT_THICKNESS:this.#sr(e)}}static get defaultPropertiesToUpdate(){return[[m.HIGHLIGHT_DEFAULT_COLOR,HighlightEditor._defaultColor],[m.HIGHLIGHT_THICKNESS,HighlightEditor._defaultThickness]]}get propertiesToUpdate(){return[[m.HIGHLIGHT_COLOR,this.color||HighlightEditor._defaultColor],[m.HIGHLIGHT_THICKNESS,this.#ea||HighlightEditor._defaultThickness],[m.HIGHLIGHT_FREE,this.#Xa]]}#On(t){const setColorAndOpacity=(t,e)=>{this.color=t;this.#Ka=e;this.parent?.drawLayer.updateProperties(this.#w,{root:{fill:t,"fill-opacity":e}});this.#n?.updateColor(t)},e=this.color,i=this.#Ka;this.addCommands({cmd:setColorAndOpacity.bind(this,t,HighlightEditor._defaultOpacity),undo:setColorAndOpacity.bind(this,e,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:m.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0});this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(t)},!0)}#sr(t){const e=this.#ea,setThickness=t=>{this.#ea=t;this.#nr(t)};this.addCommands({cmd:setThickness.bind(this,t),undo:setThickness.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:m.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0});this._reportTelemetry({action:"thickness_changed",thickness:t},!0)}async addEditToolbar(){const t=await super.addEditToolbar();if(!t)return null;if(this._uiManager.highlightColors){this.#n=new ColorPicker({editor:this});t.addColorPicker(this.#n)}return t}disableEditing(){super.disableEditing();this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing();this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#ar())}getBaseTranslation(){return[0,0]}getRect(t,e){return super.getRect(t,e,this.#ar())}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this);t&&this.div.focus()}remove(){this.#rr();this._reportTelemetry({action:"deleted"});super.remove()}rebuild(){if(this.parent){super.rebuild();if(null!==this.div){this.#tr();this.isAttachedToDOM||this.parent.add(this)}}}setParent(t){let e=!1;if(this.parent&&!t)this.#rr();else if(t){this.#tr(t);e=!this.parent&&this.div?.classList.contains("selectedEditor")}super.setParent(t);this.show(this._isVisible);e&&this.select()}#nr(t){if(!this.#Xa)return;this.#Za({highlightOutlines:this.#qa.getNewOutline(t/2)});this.fixAndSetPosition();const[e,i]=this.parentDimensions;this.setDims(this.width*e,this.height*i)}#rr(){if(null!==this.#w&&this.parent){this.parent.drawLayer.remove(this.#w);this.#w=null;this.parent.drawLayer.remove(this.#Ya);this.#Ya=null}}#tr(t=this.parent){if(null===this.#w){({id:this.#w,clipPathId:this.#Ga}=t.drawLayer.draw({bbox:this.#qa.box,root:{viewBox:"0 0 1 1",fill:this.color,"fill-opacity":this.#Ka},rootClass:{highlight:!0,free:this.#Xa},path:{d:this.#qa.toSVGPath()}},!1,!0));this.#Ya=t.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:this.#Xa},bbox:this.#$a.box,path:{d:this.#$a.toSVGPath()}},this.#Xa);this.#Wa&&(this.#Wa.style.clipPath=this.#Ga)}}static#ir([t,e,i,s],n){switch(n){case 90:return[1-e-s,t,s,i];case 180:return[1-t-i,1-e-s,i,s];case 270:return[e,1-t-i,s,i]}return[t,e,i,s]}rotate(t){const{drawLayer:e}=this.parent;let i;if(this.#Xa){t=(t-this.rotation+360)%360;i=HighlightEditor.#ir(this.#qa.box,t)}else i=HighlightEditor.#ir([this.x,this.y,this.width,this.height],t);e.updateProperties(this.#w,{bbox:i,root:{"data-main-rotation":t}});e.updateProperties(this.#Ya,{bbox:HighlightEditor.#ir(this.#$a.box,t),root:{"data-main-rotation":t}})}render(){if(this.div)return this.div;const t=super.render();if(this.#Qa){t.setAttribute("aria-label",this.#Qa);t.setAttribute("role","mark")}this.#Xa?t.classList.add("free"):this.div.addEventListener("keydown",this.#or.bind(this),{signal:this._uiManager._signal});const e=this.#Wa=document.createElement("div");t.append(e);e.setAttribute("aria-hidden","true");e.className="internal";e.style.clipPath=this.#Ga;const[i,s]=this.parentDimensions;this.setDims(this.width*i,this.height*s);bindEvents(this,this.#Wa,["pointerover","pointerleave"]);this.enableEditing();return t}pointerover(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#Ya,{rootClass:{hovered:!0}})}pointerleave(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#Ya,{rootClass:{hovered:!1}})}#or(t){HighlightEditor._keyboardManager.exec(this,t)}_moveCaret(t){this.parent.unselect(this);switch(t){case 0:case 2:this.#lr(!0);break;case 1:case 3:this.#lr(!1)}}#lr(t){if(!this.#Ha)return;const e=window.getSelection();t?e.setPosition(this.#Ha,this.#za):e.setPosition(this.#Va,this.#ja)}select(){super.select();this.#Ya&&this.parent?.drawLayer.updateProperties(this.#Ya,{rootClass:{hovered:!1,selected:!0}})}unselect(){super.unselect();if(this.#Ya){this.parent?.drawLayer.updateProperties(this.#Ya,{rootClass:{selected:!1}});this.#Xa||this.#lr(!1)}}get _mustFixPosition(){return!this.#Xa}show(t=this._isVisible){super.show(t);if(this.parent){this.parent.drawLayer.updateProperties(this.#w,{rootClass:{hidden:!t}});this.parent.drawLayer.updateProperties(this.#Ya,{rootClass:{hidden:!t}})}}#ar(){return this.#Xa?this.rotation:0}#hr(){if(this.#Xa)return null;const[t,e]=this.pageDimensions,[i,s]=this.pageTranslation,n=this.#Ua,a=new Float32Array(8*n.length);let r=0;for(const{x:o,y:l,width:h,height:d}of n){const n=o*t+i,c=(1-l)*e+s;a[r]=a[r+4]=n;a[r+1]=a[r+3]=c;a[r+2]=a[r+6]=n+h*t;a[r+5]=a[r+7]=c-d*e;r+=8}return a}#dr(t){return this.#qa.serialize(t,this.#ar())}static startHighlighting(t,e,{target:i,x:s,y:n}){const{x:a,y:r,width:o,height:l}=i.getBoundingClientRect(),h=new AbortController,d=t.combinedSignal(h),pointerUpCallback=e=>{h.abort();this.#cr(t,e)};window.addEventListener("blur",pointerUpCallback,{signal:d});window.addEventListener("pointerup",pointerUpCallback,{signal:d});window.addEventListener("pointerdown",stopEvent,{capture:!0,passive:!1,signal:d});window.addEventListener("contextmenu",noContextMenu,{signal:d});i.addEventListener("pointermove",this.#ur.bind(this,t),{signal:d});this._freeHighlight=new FreeHighlightOutliner({x:s,y:n},[a,r,o,l],t.scale,this._defaultThickness/2,e,.001);({id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=t.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:this._defaultColor,"fill-opacity":this._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:this._freeHighlight.toSVGPath()}},!0,!0))}static#ur(t,e){this._freeHighlight.add(e)&&t.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})}static#cr(t,e){this._freeHighlight.isEmpty()?t.drawLayer.remove(this._freeHighlightId):t.createAndAddNewEditor(e,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"});this._freeHighlightId=-1;this._freeHighlight=null;this._freeHighlightClipId=""}static async deserialize(t,e,i){let s=null;if(t instanceof HighlightAnnotationElement){const{data:{quadPoints:e,rect:i,rotation:n,id:a,color:r,opacity:o,popupRef:l},parent:{page:{pageNumber:h}}}=t;s=t={annotationType:g.HIGHLIGHT,color:Array.from(r),opacity:o,quadPoints:e,boxes:null,pageIndex:h-1,rect:i.slice(0),rotation:n,id:a,deleted:!1,popupRef:l}}else if(t instanceof InkAnnotationElement){const{data:{inkLists:e,rect:i,rotation:n,id:a,color:r,borderStyle:{rawWidth:o},popupRef:l},parent:{page:{pageNumber:h}}}=t;s=t={annotationType:g.HIGHLIGHT,color:Array.from(r),thickness:o,inkLists:e,boxes:null,pageIndex:h-1,rect:i.slice(0),rotation:n,id:a,deleted:!1,popupRef:l}}const{color:n,quadPoints:a,inkLists:r,opacity:o}=t,l=await super.deserialize(t,e,i);l.color=Util.makeHexColor(...n);l.#Ka=o||1;r&&(l.#ea=t.thickness);l.annotationElementId=t.id||null;l._initialData=s;const[h,d]=l.pageDimensions,[c,u]=l.pageTranslation;if(a){const t=l.#Ua=[];for(let e=0;et!==e[i]))}renderAnnotationElement(t){t.updateEdited({rect:this.getRect(0,0)});return null}static canCreateNewEmptyEditor(){return!1}}class DrawingOptions{#pr=Object.create(null);updateProperty(t,e){this[t]=e;this.updateSVGProperty(t,e)}updateProperties(t){if(t)for(const[e,i]of Object.entries(t))this.updateProperty(e,i)}updateSVGProperty(t,e){this.#pr[t]=e}toSVGProperties(){const t=this.#pr;this.#pr=Object.create(null);return{root:t}}reset(){this.#pr=Object.create(null)}updateAll(t=this){this.updateProperties(t)}clone(){unreachable("Not implemented")}}class DrawingEditor extends AnnotationEditor{#gr=null;#mr;_drawId=null;static _currentDrawId=-1;static _currentParent=null;static#fr=null;static#br=null;static#Ar=null;static#wr=NaN;static#vr=null;static#yr=null;static#xr=NaN;static _INNER_MARGIN=3;constructor(t){super(t);this.#mr=t.mustBeCommitted||!1;if(t.drawOutlines){this.#_r(t);this.#tr()}}#_r({drawOutlines:t,drawId:e,drawingOptions:i}){this.#gr=t;this._drawingOptions||=i;if(e>=0){this._drawId=e;this.parent.drawLayer.finalizeDraw(e,t.defaultProperties)}else this._drawId=this.#Er(t,this.parent);this.#Sr(t.box)}#Er(t,e){const{id:i}=e.drawLayer.draw(DrawingEditor._mergeSVGProperties(this._drawingOptions.toSVGProperties(),t.defaultSVGProperties),!1,!1);return i}static _mergeSVGProperties(t,e){const i=new Set(Object.keys(t));for(const[s,n]of Object.entries(e))i.has(s)?Object.assign(t[s],n):t[s]=n;return t}static getDefaultDrawingOptions(t){unreachable("Not implemented")}static get typesMap(){unreachable("Not implemented")}static get isDrawer(){return!0}static get supportMultipleDrawings(){return!1}static updateDefaultParams(t,e){const i=this.typesMap.get(t);i&&this._defaultDrawingOptions.updateProperty(i,e);if(this._currentParent){DrawingEditor.#fr.updateProperty(i,e);this._currentParent.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties())}}updateParams(t,e){const i=this.constructor.typesMap.get(t);i&&this._updateProperty(t,i,e)}static get defaultPropertiesToUpdate(){const t=[],e=this._defaultDrawingOptions;for(const[i,s]of this.typesMap)t.push([i,e[s]]);return t}get propertiesToUpdate(){const t=[],{_drawingOptions:e}=this;for(const[i,s]of this.constructor.typesMap)t.push([i,e[s]]);return t}_updateProperty(t,e,i){const s=this._drawingOptions,n=s[e],setter=t=>{s.updateProperty(e,t);const i=this.#gr.updateProperty(e,t);i&&this.#Sr(i);this.parent?.drawLayer.updateProperties(this._drawId,s.toSVGProperties())};this.addCommands({cmd:setter.bind(this,i),undo:setter.bind(this,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:t,overwriteIfSameType:!0,keepUndo:!0})}_onResizing(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#gr.getPathResizingSVGProperties(this.#Cr()),{bbox:this.#Tr()}))}_onResized(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#gr.getPathResizedSVGProperties(this.#Cr()),{bbox:this.#Tr()}))}_onTranslating(t,e){this.parent?.drawLayer.updateProperties(this._drawId,{bbox:this.#Tr(t,e)})}_onTranslated(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#gr.getPathTranslatedSVGProperties(this.#Cr(),this.parentDimensions),{bbox:this.#Tr()}))}_onStartDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!0}})}_onStopDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!1}})}commit(){super.commit();this.disableEditMode();this.disableEditing()}disableEditing(){super.disableEditing();this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing();this.div.classList.toggle("disabled",!1)}getBaseTranslation(){return[0,0]}get isResizable(){return!0}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this);this._isDraggable=!0;if(this.#mr){this.#mr=!1;this.commit();this.parent.setSelected(this);t&&this.isOnScreen&&this.div.focus()}}remove(){this.#rr();super.remove()}rebuild(){if(this.parent){super.rebuild();if(null!==this.div){this.#tr();this.#Sr(this.#gr.box);this.isAttachedToDOM||this.parent.add(this)}}}setParent(t){let e=!1;if(this.parent&&!t){this._uiManager.removeShouldRescale(this);this.#rr()}else if(t){this._uiManager.addShouldRescale(this);this.#tr(t);e=!this.parent&&this.div?.classList.contains("selectedEditor")}super.setParent(t);e&&this.select()}#rr(){if(null!==this._drawId&&this.parent){this.parent.drawLayer.remove(this._drawId);this._drawId=null;this._drawingOptions.reset()}}#tr(t=this.parent){if(null===this._drawId||this.parent!==t)if(null===this._drawId){this._drawingOptions.updateAll();this._drawId=this.#Er(this.#gr,t)}else this.parent.drawLayer.updateParent(this._drawId,t.drawLayer)}#Mr([t,e,i,s]){const{parentDimensions:[n,a],rotation:r}=this;switch(r){case 90:return[e,1-t,i*(a/n),s*(n/a)];case 180:return[1-t,1-e,i,s];case 270:return[1-e,t,i*(a/n),s*(n/a)];default:return[t,e,i,s]}}#Cr(){const{x:t,y:e,width:i,height:s,parentDimensions:[n,a],rotation:r}=this;switch(r){case 90:return[1-e,t,i*(n/a),s*(a/n)];case 180:return[1-t,1-e,i,s];case 270:return[e,1-t,i*(n/a),s*(a/n)];default:return[t,e,i,s]}}#Sr(t){[this.x,this.y,this.width,this.height]=this.#Mr(t);if(this.div){this.fixAndSetPosition();const[t,e]=this.parentDimensions;this.setDims(this.width*t,this.height*e)}this._onResized()}#Tr(){const{x:t,y:e,width:i,height:s,rotation:n,parentRotation:a,parentDimensions:[r,o]}=this;switch((4*n+a)/90){case 1:return[1-e-s,t,s,i];case 2:return[1-t-i,1-e-s,i,s];case 3:return[e,1-t-i,s,i];case 4:return[t,e-i*(r/o),s*(o/r),i*(r/o)];case 5:return[1-e,t,i*(r/o),s*(o/r)];case 6:return[1-t-s*(o/r),1-e,s*(o/r),i*(r/o)];case 7:return[e-i*(r/o),1-t-s*(o/r),i*(r/o),s*(o/r)];case 8:return[t-i,e-s,i,s];case 9:return[1-e,t-i,s,i];case 10:return[1-t,1-e,i,s];case 11:return[e-s,1-t,s,i];case 12:return[t-s*(o/r),e,s*(o/r),i*(r/o)];case 13:return[1-e-i*(r/o),t-s*(o/r),i*(r/o),s*(o/r)];case 14:return[1-t,1-e-i*(r/o),s*(o/r),i*(r/o)];case 15:return[e,1-t,i*(r/o),s*(o/r)];default:return[t,e,i,s]}}rotate(){this.parent&&this.parent.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties({bbox:this.#Tr()},this.#gr.updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&this.#Sr(this.#gr.updateParentDimensions(this.parentDimensions,this.parent.scale))}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;const t=super.render();t.classList.add("draw");const e=document.createElement("div");t.append(e);e.setAttribute("aria-hidden","true");e.className="internal";const[i,s]=this.parentDimensions;this.setDims(this.width*i,this.height*s);this._uiManager.addShouldRescale(this);this.disableEditing();return t}static createDrawerInstance(t,e,i,s,n){unreachable("Not implemented")}static startDrawing(t,e,i,s){const{target:n,offsetX:a,offsetY:r,pointerId:o,pointerType:l}=s;if(DrawingEditor.#vr&&DrawingEditor.#vr!==l)return;const{viewport:{rotation:h}}=t,{width:d,height:c}=n.getBoundingClientRect(),u=DrawingEditor.#br=new AbortController,p=t.combinedSignal(u);DrawingEditor.#wr||=o;DrawingEditor.#vr??=l;window.addEventListener("pointerup",(t=>{DrawingEditor.#wr===t.pointerId?this._endDraw(t):DrawingEditor.#yr?.delete(t.pointerId)}),{signal:p});window.addEventListener("pointercancel",(t=>{DrawingEditor.#wr===t.pointerId?this._currentParent.endDrawingSession():DrawingEditor.#yr?.delete(t.pointerId)}),{signal:p});window.addEventListener("pointerdown",(t=>{if(DrawingEditor.#vr===t.pointerType){(DrawingEditor.#yr||=new Set).add(t.pointerId);if(DrawingEditor.#fr.isCancellable()){DrawingEditor.#fr.removeLastElement();DrawingEditor.#fr.isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)}}}),{capture:!0,passive:!1,signal:p});window.addEventListener("contextmenu",noContextMenu,{signal:p});n.addEventListener("pointermove",this._drawMove.bind(this),{signal:p});n.addEventListener("touchmove",(t=>{t.timeStamp===DrawingEditor.#xr&&stopEvent(t)}),{signal:p});t.toggleDrawing();e._editorUndoBar?.hide();if(DrawingEditor.#fr)t.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#fr.startNew(a,r,d,c,h));else{e.updateUIForDefaultProperties(this);DrawingEditor.#fr=this.createDrawerInstance(a,r,d,c,h);DrawingEditor.#Ar=this.getDefaultDrawingOptions();this._currentParent=t;({id:this._currentDrawId}=t.drawLayer.draw(this._mergeSVGProperties(DrawingEditor.#Ar.toSVGProperties(),DrawingEditor.#fr.defaultSVGProperties),!0,!1))}}static _drawMove(t){DrawingEditor.#xr=-1;if(!DrawingEditor.#fr)return;const{offsetX:e,offsetY:i,pointerId:s}=t;if(DrawingEditor.#wr===s)if(DrawingEditor.#yr?.size>=1)this._endDraw(t);else{this._currentParent.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#fr.add(e,i));DrawingEditor.#xr=t.timeStamp;stopEvent(t)}}static _cleanup(t){if(t){this._currentDrawId=-1;this._currentParent=null;DrawingEditor.#fr=null;DrawingEditor.#Ar=null;DrawingEditor.#vr=null;DrawingEditor.#xr=NaN}if(DrawingEditor.#br){DrawingEditor.#br.abort();DrawingEditor.#br=null;DrawingEditor.#wr=NaN;DrawingEditor.#yr=null}}static _endDraw(t){const e=this._currentParent;if(e){e.toggleDrawing(!0);this._cleanup(!1);t&&e.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#fr.end(t.offsetX,t.offsetY));if(this.supportMultipleDrawings){const t=DrawingEditor.#fr,i=this._currentDrawId,s=t.getLastElement();e.addCommands({cmd:()=>{e.drawLayer.updateProperties(i,t.setLastElement(s))},undo:()=>{e.drawLayer.updateProperties(i,t.removeLastElement())},mustExec:!1,type:m.DRAW_STEP})}else this.endDrawing(!1)}}static endDrawing(t){const e=this._currentParent;if(!e)return null;e.toggleDrawing(!0);e.cleanUndoStack(m.DRAW_STEP);if(!DrawingEditor.#fr.isEmpty()){const{pageDimensions:[i,s],scale:n}=e,a=e.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:DrawingEditor.#fr.getOutlines(i*n,s*n,n,this._INNER_MARGIN),drawingOptions:DrawingEditor.#Ar,mustBeCommitted:!t});this._cleanup(!0);return a}e.drawLayer.remove(this._currentDrawId);this._cleanup(!0);return null}createDrawingOptions(t){}static deserializeDraw(t,e,i,s,n,a){unreachable("Not implemented")}static async deserialize(t,e,i){const{rawDims:{pageWidth:s,pageHeight:n,pageX:a,pageY:r}}=e.viewport,o=this.deserializeDraw(a,r,s,n,this._INNER_MARGIN,t),l=await super.deserialize(t,e,i);l.createDrawingOptions(t);l.#_r({drawOutlines:o});l.#tr();l.onScaleChanging();l.rotate();return l}serializeDraw(t){const[e,i]=this.pageTranslation,[s,n]=this.pageDimensions;return this.#gr.serialize([e,i,s,n],t)}renderAnnotationElement(t){t.updateEdited({rect:this.getRect(0,0)});return null}static canCreateNewEmptyEditor(){return!1}}class InkDrawOutliner{#Kn=new Float64Array(6);#bn;#Pr;#Fi;#ea;#ia;#Dr="";#kr=0;#Ea=new InkDrawOutline;#Rr;#Ir;constructor(t,e,i,s,n,a){this.#Rr=i;this.#Ir=s;this.#Fi=n;this.#ea=a;[t,e]=this.#Fr(t,e);const r=this.#bn=[NaN,NaN,NaN,NaN,t,e];this.#ia=[t,e];this.#Pr=[{line:r,points:this.#ia}];this.#Kn.set(r,0)}updateProperty(t,e){"stroke-width"===t&&(this.#ea=e)}#Fr(t,e){return Outline._normalizePoint(t,e,this.#Rr,this.#Ir,this.#Fi)}isEmpty(){return!this.#Pr||0===this.#Pr.length}isCancellable(){return this.#ia.length<=10}add(t,e){[t,e]=this.#Fr(t,e);const[i,s,n,a]=this.#Kn.subarray(2,6),r=t-n,o=e-a;if(Math.hypot(this.#Rr*r,this.#Ir*o)<=2)return null;this.#ia.push(t,e);if(isNaN(i)){this.#Kn.set([n,a,t,e],2);this.#bn.push(NaN,NaN,NaN,NaN,t,e);return{path:{d:this.toSVGPath()}}}isNaN(this.#Kn[0])&&this.#bn.splice(6,6);this.#Kn.set([i,s,n,a,t,e],0);this.#bn.push(...Outline.createBezierPoints(i,s,n,a,t,e));return{path:{d:this.toSVGPath()}}}end(t,e){const i=this.add(t,e);return i||(2===this.#ia.length?{path:{d:this.toSVGPath()}}:null)}startNew(t,e,i,s,n){this.#Rr=i;this.#Ir=s;this.#Fi=n;[t,e]=this.#Fr(t,e);const a=this.#bn=[NaN,NaN,NaN,NaN,t,e];this.#ia=[t,e];const r=this.#Pr.at(-1);if(r){r.line=new Float32Array(r.line);r.points=new Float32Array(r.points)}this.#Pr.push({line:a,points:this.#ia});this.#Kn.set(a,0);this.#kr=0;this.toSVGPath();return null}getLastElement(){return this.#Pr.at(-1)}setLastElement(t){if(!this.#Pr)return this.#Ea.setLastElement(t);this.#Pr.push(t);this.#bn=t.line;this.#ia=t.points;this.#kr=0;return{path:{d:this.toSVGPath()}}}removeLastElement(){if(!this.#Pr)return this.#Ea.removeLastElement();this.#Pr.pop();this.#Dr="";for(let t=0,e=this.#Pr.length;tt??NaN)),d,c,u,p),points:g(r[t].map((t=>t??NaN)),d,c,u,p)});const m=new InkDrawOutline;m.build(h,i,s,1,o,l,n);return m}#Hr(t=this.#ea){const e=this.#Wn+t/2*this.#Or;return this.#Fi%180==0?[e/this.#Rr,e/this.#Ir]:[e/this.#Ir,e/this.#Rr]}#Br(){const[t,e,i,s]=this.#pa,[n,a]=this.#Hr(0);return[t+n,e+a,i-2*n,s-2*a]}#Nr(){const t=this.#pa=new Float32Array([1/0,1/0,-1/0,-1/0]);for(const{line:e}of this.#Pr){if(e.length<=12){for(let i=4,s=e.length;it!==e[i]))||t.thickness!==i||t.opacity!==s||t.pageIndex!==n}renderAnnotationElement(t){const{points:e,rect:i}=this.serializeDraw(!1);t.updateEdited({rect:i,thickness:this._drawingOptions["stroke-width"],points:e});return null}}class StampEditor extends AnnotationEditor{#Ur=null;#Gr=null;#$r=null;#Vr=null;#jr=null;#Wr="";#qr=null;#Xr=null;#Kr=!1;#Yr=!1;static _type="stamp";static _editorType=g.STAMP;constructor(t){super({...t,name:"stampEditor"});this.#Vr=t.bitmapUrl;this.#jr=t.bitmapFile}static initialize(t,e){AnnotationEditor.initialize(t,e)}static get supportedTypes(){return shadow(this,"supportedTypes",["apng","avif","bmp","gif","jpeg","png","svg+xml","webp","x-icon"].map((t=>`image/${t}`)))}static get supportedTypesStr(){return shadow(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(t){return this.supportedTypes.includes(t)}static paste(t,e){e.pasteEditor(g.STAMP,{bitmapFile:t.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1);super.altTextFinish()}get telemetryFinalData(){return{type:"stamp",hasAltText:!!this.altTextData?.altText}}static computeTelemetryFinalData(t){const e=t.get("hasAltText");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}#Qr(t,e=!1){if(t){this.#Ur=t.bitmap;if(!e){this.#Gr=t.id;this.#Kr=t.isSvg}t.file&&(this.#Wr=t.file.name);this.#Jr()}else this.remove()}#Zr(){this.#$r=null;this._uiManager.enableWaiting(!1);if(this.#qr)if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#Ur){this._editToolbar.hide();this._uiManager.editAltText(this,!0)}else{if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#Ur){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}}async mlGuessAltText(t=null,e=!0){if(this.hasAltTextData())return null;const{mlManager:i}=this._uiManager;if(!i)throw new Error("No ML.");if(!await i.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:s,width:n,height:a}=t||this.copyCanvas(null,null,!0).imageData,r=await i.guess({name:"altText",request:{data:s,width:n,height:a,channels:s.length/(n*a)}});if(!r)throw new Error("No response from the AI service.");if(r.error)throw new Error("Error from the AI service.");if(r.cancel)return null;if(!r.output)throw new Error("No valid response from the AI service.");const o=r.output;await this.setGuessedAltText(o);e&&!this.hasAltTextData()&&(this.altTextData={alt:o,decorative:!1});return o}#to(){if(this.#Gr){this._uiManager.enableWaiting(!0);this._uiManager.imageManager.getFromId(this.#Gr).then((t=>this.#Qr(t,!0))).finally((()=>this.#Zr()));return}if(this.#Vr){const t=this.#Vr;this.#Vr=null;this._uiManager.enableWaiting(!0);this.#$r=this._uiManager.imageManager.getFromUrl(t).then((t=>this.#Qr(t))).finally((()=>this.#Zr()));return}if(this.#jr){const t=this.#jr;this.#jr=null;this._uiManager.enableWaiting(!0);this.#$r=this._uiManager.imageManager.getFromFile(t).then((t=>this.#Qr(t))).finally((()=>this.#Zr()));return}const t=document.createElement("input");t.type="file";t.accept=StampEditor.supportedTypesStr;const e=this._uiManager._signal;this.#$r=new Promise((i=>{t.addEventListener("change",(async()=>{if(t.files&&0!==t.files.length){this._uiManager.enableWaiting(!0);const e=await this._uiManager.imageManager.getFromFile(t.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}});this.#Qr(e)}else this.remove();i()}),{signal:e});t.addEventListener("cancel",(()=>{this.remove();i()}),{signal:e})})).finally((()=>this.#Zr()));t.click()}remove(){if(this.#Gr){this.#Ur=null;this._uiManager.imageManager.deleteId(this.#Gr);this.#qr?.remove();this.#qr=null;if(this.#Xr){clearTimeout(this.#Xr);this.#Xr=null}}super.remove()}rebuild(){if(this.parent){super.rebuild();if(null!==this.div){this.#Gr&&null===this.#qr&&this.#to();this.isAttachedToDOM||this.parent.add(this)}}else this.#Gr&&this.#to()}onceAdded(t){this._isDraggable=!0;t&&this.div.focus()}isEmpty(){return!(this.#$r||this.#Ur||this.#Vr||this.#jr||this.#Gr)}get isResizable(){return!0}render(){if(this.div)return this.div;let t,e;if(this.width){t=this.x;e=this.y}super.render();this.div.hidden=!0;this.div.setAttribute("role","figure");this.addAltTextButton();this.#Ur?this.#Jr():this.#to();if(this.width&&!this.annotationElementId){const[i,s]=this.parentDimensions;this.setAt(t*i,e*s,this.width*i,this.height*s)}this._uiManager.addShouldRescale(this);return this.div}_onResized(){this.onScaleChanging()}onScaleChanging(){if(!this.parent)return;null!==this.#Xr&&clearTimeout(this.#Xr);this.#Xr=setTimeout((()=>{this.#Xr=null;this.#eo()}),200)}#Jr(){const{div:t}=this;let{width:e,height:i}=this.#Ur;const[s,n]=this.pageDimensions,a=.75;if(this.width){e=this.width*s;i=this.height*n}else if(e>a*s||i>a*n){const t=Math.min(a*s/e,a*n/i);e*=t;i*=t}const[r,o]=this.parentDimensions;this.setDims(e*r/s,i*o/n);this._uiManager.enableWaiting(!1);const l=this.#qr=document.createElement("canvas");l.setAttribute("role","img");this.addContainer(l);this.width=e/s;this.height=i/n;this._initialOptions?.isCentered?this.center():this.fixAndSetPosition();this._initialOptions=null;this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&!this.annotationElementId||(t.hidden=!1);this.#eo();if(!this.#Yr){this.parent.addUndoableEditor(this);this.#Yr=!0}this._reportTelemetry({action:"inserted_image"});this.#Wr&&l.setAttribute("aria-label",this.#Wr)}copyCanvas(t,e,i=!1){t||(t=224);const{width:s,height:n}=this.#Ur,a=new OutputScale;let r=this.#Ur,o=s,l=n,h=null;if(e){if(s>e||n>e){const t=Math.min(e/s,e/n);o=Math.floor(s*t);l=Math.floor(n*t)}h=document.createElement("canvas");const t=h.width=Math.ceil(o*a.sx),i=h.height=Math.ceil(l*a.sy);this.#Kr||(r=this.#io(t,i));const d=h.getContext("2d");d.filter=this._uiManager.hcmFilter;let c="white",u="#cfcfd8";if("none"!==this._uiManager.hcmFilter)u="black";else if(window.matchMedia?.("(prefers-color-scheme: dark)").matches){c="#8f8f9d";u="#42414d"}const p=15,g=p*a.sx,m=p*a.sy,f=new OffscreenCanvas(2*g,2*m),b=f.getContext("2d");b.fillStyle=c;b.fillRect(0,0,2*g,2*m);b.fillStyle=u;b.fillRect(0,0,g,m);b.fillRect(g,m,g,m);d.fillStyle=d.createPattern(f,"repeat");d.fillRect(0,0,t,i);d.drawImage(r,0,0,r.width,r.height,0,0,t,i)}let d=null;if(i){let e,i;if(a.symmetric&&r.widtht||n>t){const a=Math.min(t/s,t/n);e=Math.floor(s*a);i=Math.floor(n*a);this.#Kr||(r=this.#io(e,i))}}const o=new OffscreenCanvas(e,i).getContext("2d",{willReadFrequently:!0});o.drawImage(r,0,0,r.width,r.height,0,0,e,i);d={width:e,height:i,data:o.getImageData(0,0,e,i).data}}return{canvas:h,width:o,height:l,imageData:d}}#io(t,e){const{width:i,height:s}=this.#Ur;let n=i,a=s,r=this.#Ur;for(;n>2*t||a>2*e;){const i=n,s=a;n>2*t&&(n=n>=16384?Math.floor(n/2)-1:Math.ceil(n/2));a>2*e&&(a=a>=16384?Math.floor(a/2)-1:Math.ceil(a/2));const o=new OffscreenCanvas(n,a);o.getContext("2d").drawImage(r,0,0,i,s,0,0,n,a);r=o.transferToImageBitmap()}return r}#eo(){const[t,e]=this.parentDimensions,{width:i,height:s}=this,n=new OutputScale,a=Math.ceil(i*t*n.sx),r=Math.ceil(s*e*n.sy),o=this.#qr;if(!o||o.width===a&&o.height===r)return;o.width=a;o.height=r;const l=this.#Kr?this.#Ur:this.#io(a,r),h=o.getContext("2d");h.filter=this._uiManager.hcmFilter;h.drawImage(l,0,0,l.width,l.height,0,0,a,r)}getImageForAltText(){return this.#qr}#so(t){if(t){if(this.#Kr){const t=this._uiManager.imageManager.getSvgUrl(this.#Gr);if(t)return t}const t=document.createElement("canvas");({width:t.width,height:t.height}=this.#Ur);t.getContext("2d").drawImage(this.#Ur,0,0);return t.toDataURL()}if(this.#Kr){const[t,e]=this.pageDimensions,i=Math.round(this.width*t*PixelsPerInch.PDF_TO_CSS_UNITS),s=Math.round(this.height*e*PixelsPerInch.PDF_TO_CSS_UNITS),n=new OffscreenCanvas(i,s);n.getContext("2d").drawImage(this.#Ur,0,0,this.#Ur.width,this.#Ur.height,0,0,i,s);return n.transferToImageBitmap()}return structuredClone(this.#Ur)}static async deserialize(t,e,i){let s=null;if(t instanceof StampAnnotationElement){const{data:{rect:n,rotation:a,id:r,structParent:o,popupRef:l},container:h,parent:{page:{pageNumber:d}}}=t,c=h.querySelector("canvas"),u=i.imageManager.getFromCanvas(h.id,c);c.remove();const p=(await e._structTree.getAriaAttributes(`${et}${r}`))?.get("aria-label")||"";s=t={annotationType:g.STAMP,bitmapId:u.id,bitmap:u.bitmap,pageIndex:d-1,rect:n.slice(0),rotation:a,id:r,deleted:!1,accessibilityData:{decorative:!1,altText:p},isSvg:!1,structParent:o,popupRef:l}}const n=await super.deserialize(t,e,i),{rect:a,bitmap:r,bitmapUrl:o,bitmapId:l,isSvg:h,accessibilityData:d}=t;if(l&&i.imageManager.isValidId(l)){n.#Gr=l;r&&(n.#Ur=r)}else n.#Vr=o;n.#Kr=h;const[c,u]=n.pageDimensions;n.width=(a[2]-a[0])/c;n.height=(a[3]-a[1])/u;n.annotationElementId=t.id||null;d&&(n.altTextData=d);n._initialData=s;n.#Yr=!!s;return n}serialize(t=!1,e=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const i={annotationType:g.STAMP,bitmapId:this.#Gr,pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:this.#Kr,structTreeParentId:this._structTreeParentId};if(t){i.bitmapUrl=this.#so(!0);i.accessibilityData=this.serializeAltText(!0);return i}const{decorative:s,altText:n}=this.serializeAltText(!1);!s&&n&&(i.accessibilityData={type:"Figure",alt:n});if(this.annotationElementId){const t=this.#$n(i);if(t.isSame)return null;t.isSameAltText?delete i.accessibilityData:i.accessibilityData.structParent=this._initialData.structParent??-1}i.id=this.annotationElementId;if(null===e)return i;e.stamps||=new Map;const a=this.#Kr?(i.rect[2]-i.rect[0])*(i.rect[3]-i.rect[1]):null;if(e.stamps.has(this.#Gr)){if(this.#Kr){const t=e.stamps.get(this.#Gr);if(a>t.area){t.area=a;t.serialized.bitmap.close();t.serialized.bitmap=this.#so(!1)}}}else{e.stamps.set(this.#Gr,{area:a,serialized:i});i.bitmap=this.#so(!1)}return i}#$n(t){const{pageIndex:e,accessibilityData:{altText:i}}=this._initialData,s=t.pageIndex===e,n=(t.accessibilityData?.alt||"")===i;return{isSame:!this._hasBeenMoved&&!this._hasBeenResized&&s&&n,isSameAltText:n}}renderAnnotationElement(t){t.updateEdited({rect:this.getRect(0,0)});return null}}class AnnotationEditorLayer{#Cn;#no=!1;#ao=null;#ro=null;#oo=null;#lo=new Map;#ho=!1;#do=!1;#co=!1;#uo=null;#po=null;#go=null;#mo=null;#m;static _initialized=!1;static#U=new Map([FreeTextEditor,InkEditor,StampEditor,HighlightEditor].map((t=>[t._editorType,t])));constructor({uiManager:t,pageIndex:e,div:i,structTreeLayer:s,accessibilityManager:n,annotationLayer:a,drawLayer:r,textLayer:o,viewport:l,l10n:h}){const d=[...AnnotationEditorLayer.#U.values()];if(!AnnotationEditorLayer._initialized){AnnotationEditorLayer._initialized=!0;for(const e of d)e.initialize(h,t)}t.registerEditorTypes(d);this.#m=t;this.pageIndex=e;this.div=i;this.#Cn=n;this.#ao=a;this.viewport=l;this.#go=o;this.drawLayer=r;this._structTree=s;this.#m.addLayer(this)}get isEmpty(){return 0===this.#lo.size}get isInvisible(){return this.isEmpty&&this.#m.getMode()===g.NONE}updateToolbar(t){this.#m.updateToolbar(t)}updateMode(t=this.#m.getMode()){this.#fo();switch(t){case g.NONE:this.disableTextSelection();this.togglePointerEvents(!1);this.toggleAnnotationLayerPointerEvents(!0);this.disableClick();return;case g.INK:this.disableTextSelection();this.togglePointerEvents(!0);this.enableClick();break;case g.HIGHLIGHT:this.enableTextSelection();this.togglePointerEvents(!1);this.disableClick();break;default:this.disableTextSelection();this.togglePointerEvents(!0);this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);const{classList:e}=this.div;for(const i of AnnotationEditorLayer.#U.values())e.toggle(`${i._type}Editing`,t===i._editorType);this.div.hidden=!1}hasTextLayer(t){return t===this.#go?.div}setEditingState(t){this.#m.setEditingState(t)}addCommands(t){this.#m.addCommands(t)}cleanUndoStack(t){this.#m.cleanUndoStack(t)}toggleDrawing(t=!1){this.div.classList.toggle("drawing",!t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){this.#ao?.div.classList.toggle("disabled",!t)}async enable(){this.#co=!0;this.div.tabIndex=0;this.togglePointerEvents(!0);const t=new Set;for(const e of this.#lo.values()){e.enableEditing();e.show(!0);if(e.annotationElementId){this.#m.removeChangedExistingAnnotation(e);t.add(e.annotationElementId)}}if(!this.#ao){this.#co=!1;return}const e=this.#ao.getEditableAnnotations();for(const i of e){i.hide();if(this.#m.isDeletedAnnotationElement(i.data.id))continue;if(t.has(i.data.id))continue;const e=await this.deserialize(i);if(e){this.addOrRebuild(e);e.enableEditing()}}this.#co=!1}disable(){this.#do=!0;this.div.tabIndex=-1;this.togglePointerEvents(!1);const t=new Map,e=new Map;for(const i of this.#lo.values()){i.disableEditing();if(i.annotationElementId)if(null===i.serialize()){e.set(i.annotationElementId,i);this.getEditableAnnotation(i.annotationElementId)?.show();i.remove()}else t.set(i.annotationElementId,i)}if(this.#ao){const i=this.#ao.getEditableAnnotations();for(const s of i){const{id:i}=s.data;if(this.#m.isDeletedAnnotationElement(i))continue;let n=e.get(i);if(n){n.resetAnnotationElement(s);n.show(!1);s.show()}else{n=t.get(i);if(n){this.#m.addChangedExistingAnnotation(n);n.renderAnnotationElement(s)&&n.show(!1)}s.show()}}}this.#fo();this.isEmpty&&(this.div.hidden=!0);const{classList:i}=this.div;for(const t of AnnotationEditorLayer.#U.values())i.remove(`${t._type}Editing`);this.disableTextSelection();this.toggleAnnotationLayerPointerEvents(!0);this.#do=!1}getEditableAnnotation(t){return this.#ao?.getEditableAnnotation(t)||null}setActiveEditor(t){this.#m.getActive()!==t&&this.#m.setActiveEditor(t)}enableTextSelection(){this.div.tabIndex=-1;if(this.#go?.div&&!this.#mo){this.#mo=new AbortController;const t=this.#m.combinedSignal(this.#mo);this.#go.div.addEventListener("pointerdown",this.#bo.bind(this),{signal:t});this.#go.div.classList.add("highlighting")}}disableTextSelection(){this.div.tabIndex=0;if(this.#go?.div&&this.#mo){this.#mo.abort();this.#mo=null;this.#go.div.classList.remove("highlighting")}}#bo(t){this.#m.unselectAll();const{target:e}=t;if(e===this.#go.div||("img"===e.getAttribute("role")||e.classList.contains("endOfContent"))&&this.#go.div.contains(e)){const{isMac:e}=util_FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)return;this.#m.showAllEditors("highlight",!0,!0);this.#go.div.classList.add("free");this.toggleDrawing();HighlightEditor.startHighlighting(this,"ltr"===this.#m.direction,{target:this.#go.div,x:t.x,y:t.y});this.#go.div.addEventListener("pointerup",(()=>{this.#go.div.classList.remove("free");this.toggleDrawing(!0)}),{once:!0,signal:this.#m._signal});t.preventDefault()}}enableClick(){if(this.#ro)return;this.#ro=new AbortController;const t=this.#m.combinedSignal(this.#ro);this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t});const e=this.pointerup.bind(this);this.div.addEventListener("pointerup",e,{signal:t});this.div.addEventListener("pointercancel",e,{signal:t})}disableClick(){this.#ro?.abort();this.#ro=null}attach(t){this.#lo.set(t.id,t);const{annotationElementId:e}=t;e&&this.#m.isDeletedAnnotationElement(e)&&this.#m.removeDeletedAnnotationElement(t)}detach(t){this.#lo.delete(t.id);this.#Cn?.removePointerInTextLayer(t.contentDiv);!this.#do&&t.annotationElementId&&this.#m.addDeletedAnnotationElement(t)}remove(t){this.detach(t);this.#m.removeEditor(t);t.div.remove();t.isAttachedToDOM=!1}changeParent(t){if(t.parent!==this){if(t.parent&&t.annotationElementId){this.#m.addDeletedAnnotationElement(t.annotationElementId);AnnotationEditor.deleteAnnotationElement(t);t.annotationElementId=null}this.attach(t);t.parent?.detach(t);t.setParent(this);if(t.div&&t.isAttachedToDOM){t.div.remove();this.div.append(t.div)}}}add(t){if(t.parent!==this||!t.isAttachedToDOM){this.changeParent(t);this.#m.addEditor(t);this.attach(t);if(!t.isAttachedToDOM){const e=t.render();this.div.append(e);t.isAttachedToDOM=!0}t.fixAndSetPosition();t.onceAdded(!this.#co);this.#m.addToAnnotationStorage(t);t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){if(!t.isAttachedToDOM)return;const{activeElement:e}=document;if(t.div.contains(e)&&!this.#oo){t._focusEventsAllowed=!1;this.#oo=setTimeout((()=>{this.#oo=null;if(t.div.contains(document.activeElement))t._focusEventsAllowed=!0;else{t.div.addEventListener("focusin",(()=>{t._focusEventsAllowed=!0}),{once:!0,signal:this.#m._signal});e.focus()}}),0)}t._structTreeParentId=this.#Cn?.moveElementInDOM(this.div,t.div,t.contentDiv,!0)}addOrRebuild(t){if(t.needsToBeRebuilt()){t.parent||=this;t.rebuild();t.show()}else this.add(t)}addUndoableEditor(t){this.addCommands({cmd:()=>t._uiManager.rebuild(t),undo:()=>{t.remove()},mustExec:!1})}getNextId(){return this.#m.getId()}get#Ao(){return AnnotationEditorLayer.#U.get(this.#m.getMode())}combinedSignal(t){return this.#m.combinedSignal(t)}#wo(t){const e=this.#Ao;return e?new e.prototype.constructor(t):null}canCreateNewEmptyEditor(){return this.#Ao?.canCreateNewEmptyEditor()}pasteEditor(t,e){this.#m.updateToolbar(t);this.#m.updateMode(t);const{offsetX:i,offsetY:s}=this.#vo(),n=this.getNextId(),a=this.#wo({parent:this,id:n,x:i,y:s,uiManager:this.#m,isCentered:!0,...e});a&&this.add(a)}async deserialize(t){return await(AnnotationEditorLayer.#U.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#m))||null}createAndAddNewEditor(t,e,i={}){const s=this.getNextId(),n=this.#wo({parent:this,id:s,x:t.offsetX,y:t.offsetY,uiManager:this.#m,isCentered:e,...i});n&&this.add(n);return n}#vo(){const{x:t,y:e,width:i,height:s}=this.div.getBoundingClientRect(),n=Math.max(0,t),a=Math.max(0,e),r=(n+Math.min(window.innerWidth,t+i))/2-t,o=(a+Math.min(window.innerHeight,e+s))/2-e,[l,h]=this.viewport.rotation%180==0?[r,o]:[o,r];return{offsetX:l,offsetY:h}}addNewEditor(){this.createAndAddNewEditor(this.#vo(),!0)}setSelected(t){this.#m.setSelected(t)}toggleSelected(t){this.#m.toggleSelected(t)}unselect(t){this.#m.unselect(t)}pointerup(t){const{isMac:e}=util_FeatureTest.platform;if(!(0!==t.button||t.ctrlKey&&e)&&t.target===this.div&&this.#ho){this.#ho=!1;this.#Ao?.isDrawer&&this.#Ao.supportMultipleDrawings||(this.#no?this.#m.getMode()!==g.STAMP?this.createAndAddNewEditor(t,!1):this.#m.unselectAll():this.#no=!0)}}pointerdown(t){this.#m.getMode()===g.HIGHLIGHT&&this.enableTextSelection();if(this.#ho){this.#ho=!1;return}const{isMac:e}=util_FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)return;if(t.target!==this.div)return;this.#ho=!0;if(this.#Ao?.isDrawer){this.startDrawingSession(t);return}const i=this.#m.getActive();this.#no=!i||i.isEmpty()}startDrawingSession(t){this.div.focus();if(this.#uo){this.#Ao.startDrawing(this,this.#m,!1,t);return}this.#m.setCurrentDrawingSession(this);this.#uo=new AbortController;const e=this.#m.combinedSignal(this.#uo);this.div.addEventListener("blur",(({relatedTarget:t})=>{if(t&&!this.div.contains(t)){this.#po=null;this.commitOrRemove()}}),{signal:e});this.#Ao.startDrawing(this,this.#m,!1,t)}pause(t){if(t){const{activeElement:t}=document;this.div.contains(t)&&(this.#po=t)}else this.#po&&setTimeout((()=>{this.#po?.focus();this.#po=null}),0)}endDrawingSession(t=!1){if(!this.#uo)return null;this.#m.setCurrentDrawingSession(null);this.#uo.abort();this.#uo=null;this.#po=null;return this.#Ao.endDrawing(t)}findNewParent(t,e,i){const s=this.#m.findParent(e,i);if(null===s||s===this)return!1;s.changeParent(t);return!0}commitOrRemove(){if(this.#uo){this.endDrawingSession();return!0}return!1}onScaleChanging(){this.#uo&&this.#Ao.onScaleChangingWhenDrawing(this)}destroy(){this.commitOrRemove();if(this.#m.getActive()?.parent===this){this.#m.commitOrRemove();this.#m.setActiveEditor(null)}if(this.#oo){clearTimeout(this.#oo);this.#oo=null}for(const t of this.#lo.values()){this.#Cn?.removePointerInTextLayer(t.contentDiv);t.setParent(null);t.isAttachedToDOM=!1;t.div.remove()}this.div=null;this.#lo.clear();this.#m.removeLayer(this)}#fo(){for(const t of this.#lo.values())t.isEmpty()&&t.remove()}render({viewport:t}){this.viewport=t;setLayerDimensions(this.div,t);for(const t of this.#m.getEditors(this.pageIndex)){this.add(t);t.rebuild()}this.updateMode()}update({viewport:t}){this.#m.commitOrRemove();this.#fo();const e=this.viewport.rotation,i=t.rotation;this.viewport=t;setLayerDimensions(this.div,{rotation:i});if(e!==i)for(const t of this.#lo.values())t.rotate(i)}get pageDimensions(){const{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return this.#m.viewParameters.realScale}}class DrawLayer{#nn=null;#w=0;#yo=new Map;#xo=new Map;constructor({pageIndex:t}){this.pageIndex=t}setParent(t){if(this.#nn){if(this.#nn!==t){if(this.#yo.size>0)for(const e of this.#yo.values()){e.remove();t.append(e)}this.#nn=t}}else this.#nn=t}static get _svgFactory(){return shadow(this,"_svgFactory",new DOMSVGFactory)}static#_o(t,[e,i,s,n]){const{style:a}=t;a.top=100*i+"%";a.left=100*e+"%";a.width=100*s+"%";a.height=100*n+"%"}#Eo(){const t=DrawLayer._svgFactory.create(1,1,!0);this.#nn.append(t);t.setAttribute("aria-hidden",!0);return t}#So(t,e){const i=DrawLayer._svgFactory.createElement("clipPath");t.append(i);const s=`clip_${e}`;i.setAttribute("id",s);i.setAttribute("clipPathUnits","objectBoundingBox");const n=DrawLayer._svgFactory.createElement("use");i.append(n);n.setAttribute("href",`#${e}`);n.classList.add("clip");return s}#Co(t,e){for(const[i,s]of Object.entries(e))null===s?t.removeAttribute(i):t.setAttribute(i,s)}draw(t,e=!1,i=!1){const s=this.#w++,n=this.#Eo(),a=DrawLayer._svgFactory.createElement("defs");n.append(a);const r=DrawLayer._svgFactory.createElement("path");a.append(r);const o=`path_p${this.pageIndex}_${s}`;r.setAttribute("id",o);r.setAttribute("vector-effect","non-scaling-stroke");e&&this.#xo.set(s,r);const l=i?this.#So(a,o):null,h=DrawLayer._svgFactory.createElement("use");n.append(h);h.setAttribute("href",`#${o}`);this.updateProperties(n,t);this.#yo.set(s,n);return{id:s,clipPathId:`url(#${l})`}}drawOutline(t,e){const i=this.#w++,s=this.#Eo(),n=DrawLayer._svgFactory.createElement("defs");s.append(n);const a=DrawLayer._svgFactory.createElement("path");n.append(a);const r=`path_p${this.pageIndex}_${i}`;a.setAttribute("id",r);a.setAttribute("vector-effect","non-scaling-stroke");let o;if(e){const t=DrawLayer._svgFactory.createElement("mask");n.append(t);o=`mask_p${this.pageIndex}_${i}`;t.setAttribute("id",o);t.setAttribute("maskUnits","objectBoundingBox");const e=DrawLayer._svgFactory.createElement("rect");t.append(e);e.setAttribute("width","1");e.setAttribute("height","1");e.setAttribute("fill","white");const s=DrawLayer._svgFactory.createElement("use");t.append(s);s.setAttribute("href",`#${r}`);s.setAttribute("stroke","none");s.setAttribute("fill","black");s.setAttribute("fill-rule","nonzero");s.classList.add("mask")}const l=DrawLayer._svgFactory.createElement("use");s.append(l);l.setAttribute("href",`#${r}`);o&&l.setAttribute("mask",`url(#${o})`);const h=l.cloneNode();s.append(h);l.classList.add("mainOutline");h.classList.add("secondaryOutline");this.updateProperties(s,t);this.#yo.set(i,s);return i}finalizeDraw(t,e){this.#xo.delete(t);this.updateProperties(t,e)}updateProperties(t,e){if(!e)return;const{root:i,bbox:s,rootClass:n,path:a}=e,r="number"==typeof t?this.#yo.get(t):t;if(r){i&&this.#Co(r,i);s&&DrawLayer.#_o(r,s);if(n){const{classList:t}=r;for(const[e,i]of Object.entries(n))t.toggle(e,i)}if(a){const t=r.firstChild.firstChild;this.#Co(t,a)}}}updateParent(t,e){if(e===this)return;const i=this.#yo.get(t);if(i){e.#nn.append(i);this.#yo.delete(t);e.#yo.set(t,i)}}remove(t){this.#xo.delete(t);if(null!==this.#nn){this.#yo.get(t).remove();this.#yo.delete(t)}}destroy(){this.#nn=null;for(const t of this.#yo.values())t.remove();this.#yo.clear();this.#xo.clear()}}globalThis.pdfjsTestingUtils={HighlightOutliner};var Ut=__webpack_exports__.AbortException,Gt=__webpack_exports__.AnnotationEditorLayer,$t=__webpack_exports__.AnnotationEditorParamsType,Vt=__webpack_exports__.AnnotationEditorType,jt=__webpack_exports__.AnnotationEditorUIManager,Wt=__webpack_exports__.AnnotationLayer,qt=__webpack_exports__.AnnotationMode,Xt=__webpack_exports__.ColorPicker,Kt=__webpack_exports__.DOMSVGFactory,Yt=__webpack_exports__.DrawLayer,Qt=__webpack_exports__.FeatureTest,Jt=__webpack_exports__.GlobalWorkerOptions,Zt=__webpack_exports__.ImageKind,te=__webpack_exports__.InvalidPDFException,ee=__webpack_exports__.MissingPDFException,ie=__webpack_exports__.OPS,se=__webpack_exports__.OutputScale,ne=__webpack_exports__.PDFDataRangeTransport,ae=__webpack_exports__.PDFDateString,re=__webpack_exports__.PDFWorker,oe=__webpack_exports__.PasswordResponses,le=__webpack_exports__.PermissionFlag,he=__webpack_exports__.PixelsPerInch,de=__webpack_exports__.RenderingCancelledException,ce=__webpack_exports__.TextLayer,ue=__webpack_exports__.TouchManager,pe=__webpack_exports__.UnexpectedResponseException,ge=__webpack_exports__.Util,me=__webpack_exports__.VerbosityLevel,fe=__webpack_exports__.XfaLayer,be=__webpack_exports__.build,Ae=__webpack_exports__.createValidAbsoluteUrl,we=__webpack_exports__.fetchData,ve=__webpack_exports__.getDocument,ye=__webpack_exports__.getFilenameFromUrl,xe=__webpack_exports__.getPdfFilenameFromUrl,_e=__webpack_exports__.getXfaPageViewport,Ee=__webpack_exports__.isDataScheme,Se=__webpack_exports__.isPdfFile,Ce=__webpack_exports__.noContextMenu,Te=__webpack_exports__.normalizeUnicode,Me=__webpack_exports__.setLayerDimensions,Pe=__webpack_exports__.shadow,De=__webpack_exports__.stopEvent,ke=__webpack_exports__.version;export{Ut as AbortException,Gt as AnnotationEditorLayer,$t as AnnotationEditorParamsType,Vt as AnnotationEditorType,jt as AnnotationEditorUIManager,Wt as AnnotationLayer,qt as AnnotationMode,Xt as ColorPicker,Kt as DOMSVGFactory,Yt as DrawLayer,Qt as FeatureTest,Jt as GlobalWorkerOptions,Zt as ImageKind,te as InvalidPDFException,ee as MissingPDFException,ie as OPS,se as OutputScale,ne as PDFDataRangeTransport,ae as PDFDateString,re as PDFWorker,oe as PasswordResponses,le as PermissionFlag,he as PixelsPerInch,de as RenderingCancelledException,ce as TextLayer,ue as TouchManager,pe as UnexpectedResponseException,ge as Util,me as VerbosityLevel,fe as XfaLayer,be as build,Ae as createValidAbsoluteUrl,we as fetchData,ve as getDocument,ye as getFilenameFromUrl,xe as getPdfFilenameFromUrl,_e as getXfaPageViewport,Ee as isDataScheme,Se as isPdfFile,Ce as noContextMenu,Te as normalizeUnicode,Me as setLayerDimensions,Pe as shadow,De as stopEvent,ke as version}; \ No newline at end of file diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/pdfjs-dist/dist/build/pdf.worker.min.mjs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/pdfjs-dist/dist/build/pdf.worker.min.mjs deleted file mode 100644 index ee4038504a6..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/pdfjs-dist/dist/build/pdf.worker.min.mjs +++ /dev/null @@ -1,21 +0,0 @@ -/** - * @licstart The following is the entire license notice for the - * JavaScript code in this page - * - * Copyright 2024 Mozilla Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * @licend The above is the entire license notice for the - * JavaScript code in this page - */var e={d:(t,i)=>{for(var a in i)e.o(i,a)&&!e.o(t,a)&&Object.defineProperty(t,a,{enumerable:!0,get:i[a]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},__webpack_exports__ = globalThis.pdfjsWorker = {};e.d(__webpack_exports__,{WorkerMessageHandler:()=>WorkerMessageHandler});const t=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),i=[1,0,0,1,0,0],a=[.001,0,0,.001,0,0],s=1.35,r=.35,n=.25925925925925924,g=1,o=2,c=4,C=8,h=16,l=64,Q=128,E=256,u="pdfjs_internal_editor_",d=3,f=9,p=13,m=15,y={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},w=0,D=4,b=1,F=2,S=3,k=1,R=2,N=3,G=4,M=5,U=6,x=7,L=8,H=9,J=10,Y=11,v=12,K=13,T=14,q=15,O=16,W=17,j=20,X="Group",Z="R",V=1,z=2,_=4,$=16,AA=32,eA=128,tA=512,iA=1,aA=2,sA=4096,rA=8192,nA=32768,gA=65536,oA=131072,IA=1048576,cA=2097152,CA=8388608,hA=16777216,lA=1,BA=2,QA=3,EA=4,uA=5,dA={E:"Mouse Enter",X:"Mouse Exit",D:"Mouse Down",U:"Mouse Up",Fo:"Focus",Bl:"Blur",PO:"PageOpen",PC:"PageClose",PV:"PageVisible",PI:"PageInvisible",K:"Keystroke",F:"Format",V:"Validate",C:"Calculate"},fA={WC:"WillClose",WS:"WillSave",DS:"DidSave",WP:"WillPrint",DP:"DidPrint"},pA={O:"PageOpen",C:"PageClose"},mA=1,yA=5,wA=1,DA=2,bA=3,FA=4,SA=5,kA=6,RA=7,NA=8,GA=9,MA=10,UA=11,xA=12,LA=13,HA=14,JA=15,YA=16,vA=17,KA=18,TA=19,qA=20,OA=21,PA=22,WA=23,jA=24,XA=25,ZA=26,VA=27,zA=28,_A=29,$A=30,Ae=31,ee=32,te=33,ie=34,ae=35,se=36,re=37,ne=38,ge=39,oe=40,Ie=41,ce=42,Ce=43,he=44,le=45,Be=46,Qe=47,Ee=48,ue=49,de=50,fe=51,pe=52,me=53,ye=54,we=55,De=56,be=57,Fe=58,Se=59,ke=60,Re=61,Ne=62,Ge=63,Me=64,Ue=65,xe=66,Le=67,He=68,Je=69,Ye=70,ve=71,Ke=72,Te=73,qe=74,Oe=75,Pe=76,We=77,je=80,Xe=81,Ze=83,Ve=84,ze=85,_e=86,$e=87,At=88,et=89,tt=90,it=91,at=92,st=93,rt=1,nt=2;let gt=mA;function getVerbosityLevel(){return gt}function info(e){gt>=yA&&console.log(`Info: ${e}`)}function warn(e){gt>=mA&&console.log(`Warning: ${e}`)}function unreachable(e){throw new Error(e)}function assert(e,t){e||unreachable(t)}function createValidAbsoluteUrl(e,t=null,i=null){if(!e)return null;try{if(i&&"string"==typeof e){if(i.addDefaultProtocol&&e.startsWith("www.")){const t=e.match(/\./g);t?.length>=2&&(e=`http://${e}`)}if(i.tryConvertEncoding)try{e=stringToUTF8String(e)}catch{}}const a=t?new URL(e,t):new URL(e);if(function _isValidProtocol(e){switch(e?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(a))return a}catch{}return null}function shadow(e,t,i,a=!1){Object.defineProperty(e,t,{value:i,enumerable:!a,configurable:!0,writable:!1});return i}const ot=function BaseExceptionClosure(){function BaseException(e,t){this.message=e;this.name=t}BaseException.prototype=new Error;BaseException.constructor=BaseException;return BaseException}();class PasswordException extends ot{constructor(e,t){super(e,"PasswordException");this.code=t}}class UnknownErrorException extends ot{constructor(e,t){super(e,"UnknownErrorException");this.details=t}}class InvalidPDFException extends ot{constructor(e){super(e,"InvalidPDFException")}}class MissingPDFException extends ot{constructor(e){super(e,"MissingPDFException")}}class UnexpectedResponseException extends ot{constructor(e,t){super(e,"UnexpectedResponseException");this.status=t}}class FormatError extends ot{constructor(e){super(e,"FormatError")}}class AbortException extends ot{constructor(e){super(e,"AbortException")}}function bytesToString(e){"object"==typeof e&&void 0!==e?.length||unreachable("Invalid argument for bytesToString");const t=e.length,i=8192;if(t>24&255,e>>16&255,e>>8&255,255&e)}function objectSize(e){return Object.keys(e).length}class FeatureTest{static get isLittleEndian(){return shadow(this,"isLittleEndian",function isLittleEndian(){const e=new Uint8Array(4);e[0]=1;return 1===new Uint32Array(e.buffer,0,1)[0]}())}static get isEvalSupported(){return shadow(this,"isEvalSupported",function isEvalSupported(){try{new Function("");return!0}catch{return!1}}())}static get isOffscreenCanvasSupported(){return shadow(this,"isOffscreenCanvasSupported","undefined"!=typeof OffscreenCanvas)}static get isImageDecoderSupported(){return shadow(this,"isImageDecoderSupported","undefined"!=typeof ImageDecoder)}static get platform(){return"undefined"!=typeof navigator&&"string"==typeof navigator?.platform?shadow(this,"platform",{isMac:navigator.platform.includes("Mac"),isWindows:navigator.platform.includes("Win"),isFirefox:"string"==typeof navigator?.userAgent&&navigator.userAgent.includes("Firefox")}):shadow(this,"platform",{isMac:!1,isWindows:!1,isFirefox:!1})}static get isCSSRoundSupported(){return shadow(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}const It=Array.from(Array(256).keys(),(e=>e.toString(16).padStart(2,"0")));class Util{static makeHexColor(e,t,i){return`#${It[e]}${It[t]}${It[i]}`}static scaleMinMax(e,t){let i;if(e[0]){if(e[0]<0){i=t[0];t[0]=t[2];t[2]=i}t[0]*=e[0];t[2]*=e[0];if(e[3]<0){i=t[1];t[1]=t[3];t[3]=i}t[1]*=e[3];t[3]*=e[3]}else{i=t[0];t[0]=t[1];t[1]=i;i=t[2];t[2]=t[3];t[3]=i;if(e[1]<0){i=t[1];t[1]=t[3];t[3]=i}t[1]*=e[1];t[3]*=e[1];if(e[2]<0){i=t[0];t[0]=t[2];t[2]=i}t[0]*=e[2];t[2]*=e[2]}t[0]+=e[4];t[1]+=e[5];t[2]+=e[4];t[3]+=e[5]}static transform(e,t){return[e[0]*t[0]+e[2]*t[1],e[1]*t[0]+e[3]*t[1],e[0]*t[2]+e[2]*t[3],e[1]*t[2]+e[3]*t[3],e[0]*t[4]+e[2]*t[5]+e[4],e[1]*t[4]+e[3]*t[5]+e[5]]}static applyTransform(e,t){return[e[0]*t[0]+e[1]*t[2]+t[4],e[0]*t[1]+e[1]*t[3]+t[5]]}static applyInverseTransform(e,t){const i=t[0]*t[3]-t[1]*t[2];return[(e[0]*t[3]-e[1]*t[2]+t[2]*t[5]-t[4]*t[3])/i,(-e[0]*t[1]+e[1]*t[0]+t[4]*t[1]-t[5]*t[0])/i]}static getAxialAlignedBoundingBox(e,t){const i=this.applyTransform(e,t),a=this.applyTransform(e.slice(2,4),t),s=this.applyTransform([e[0],e[3]],t),r=this.applyTransform([e[2],e[1]],t);return[Math.min(i[0],a[0],s[0],r[0]),Math.min(i[1],a[1],s[1],r[1]),Math.max(i[0],a[0],s[0],r[0]),Math.max(i[1],a[1],s[1],r[1])]}static inverseTransform(e){const t=e[0]*e[3]-e[1]*e[2];return[e[3]/t,-e[1]/t,-e[2]/t,e[0]/t,(e[2]*e[5]-e[4]*e[3])/t,(e[4]*e[1]-e[5]*e[0])/t]}static singularValueDecompose2dScale(e){const t=[e[0],e[2],e[1],e[3]],i=e[0]*t[0]+e[1]*t[2],a=e[0]*t[1]+e[1]*t[3],s=e[2]*t[0]+e[3]*t[2],r=e[2]*t[1]+e[3]*t[3],n=(i+r)/2,g=Math.sqrt((i+r)**2-4*(i*r-s*a))/2,o=n+g||1,c=n-g||1;return[Math.sqrt(o),Math.sqrt(c)]}static normalizeRect(e){const t=e.slice(0);if(e[0]>e[2]){t[0]=e[2];t[2]=e[0]}if(e[1]>e[3]){t[1]=e[3];t[3]=e[1]}return t}static intersect(e,t){const i=Math.max(Math.min(e[0],e[2]),Math.min(t[0],t[2])),a=Math.min(Math.max(e[0],e[2]),Math.max(t[0],t[2]));if(i>a)return null;const s=Math.max(Math.min(e[1],e[3]),Math.min(t[1],t[3])),r=Math.min(Math.max(e[1],e[3]),Math.max(t[1],t[3]));return s>r?null:[i,s,a,r]}static#A(e,t,i,a,s,r,n,g,o,c){if(o<=0||o>=1)return;const C=1-o,h=o*o,l=h*o,Q=C*(C*(C*e+3*o*t)+3*h*i)+l*a,E=C*(C*(C*s+3*o*r)+3*h*n)+l*g;c[0]=Math.min(c[0],Q);c[1]=Math.min(c[1],E);c[2]=Math.max(c[2],Q);c[3]=Math.max(c[3],E)}static#e(e,t,i,a,s,r,n,g,o,c,C,h){if(Math.abs(o)<1e-12){Math.abs(c)>=1e-12&&this.#A(e,t,i,a,s,r,n,g,-C/c,h);return}const l=c**2-4*C*o;if(l<0)return;const Q=Math.sqrt(l),E=2*o;this.#A(e,t,i,a,s,r,n,g,(-c+Q)/E,h);this.#A(e,t,i,a,s,r,n,g,(-c-Q)/E,h)}static bezierBoundingBox(e,t,i,a,s,r,n,g,o){if(o){o[0]=Math.min(o[0],e,n);o[1]=Math.min(o[1],t,g);o[2]=Math.max(o[2],e,n);o[3]=Math.max(o[3],t,g)}else o=[Math.min(e,n),Math.min(t,g),Math.max(e,n),Math.max(t,g)];this.#e(e,i,s,n,t,a,r,g,3*(3*(i-s)-e+n),6*(e-2*i+s),3*(i-e),o);this.#e(e,i,s,n,t,a,r,g,3*(3*(a-r)-t+g),6*(t-2*a+r),3*(a-t),o);return o}}const ct=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,728,711,710,729,733,731,730,732,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8226,8224,8225,8230,8212,8211,402,8260,8249,8250,8722,8240,8222,8220,8221,8216,8217,8218,8482,64257,64258,321,338,352,376,381,305,322,339,353,382,0,8364];function stringToPDFString(e){if(e[0]>="ï"){let t;if("þ"===e[0]&&"ÿ"===e[1]){t="utf-16be";e.length%2==1&&(e=e.slice(0,-1))}else if("ÿ"===e[0]&&"þ"===e[1]){t="utf-16le";e.length%2==1&&(e=e.slice(0,-1))}else"ï"===e[0]&&"»"===e[1]&&"¿"===e[2]&&(t="utf-8");if(t)try{const i=new TextDecoder(t,{fatal:!0}),a=stringToBytes(e),s=i.decode(a);return s.includes("")?s.replaceAll(/\x1b[^\x1b]*(?:\x1b|$)/g,""):s}catch(e){warn(`stringToPDFString: "${e}".`)}}const t=[];for(let i=0,a=e.length;iIt[e])).join("")}"function"!=typeof Promise.try&&(Promise.try=function(e,...t){return new Promise((i=>{i(e(...t))}))});const lt=Symbol("CIRCULAR_REF"),Bt=Symbol("EOF");let Qt=Object.create(null),Et=Object.create(null),ut=Object.create(null);class Name{constructor(e){this.name=e}static get(e){return Et[e]||=new Name(e)}}class Cmd{constructor(e){this.cmd=e}static get(e){return Qt[e]||=new Cmd(e)}}const dt=function nonSerializableClosure(){return dt};class Dict{constructor(e=null){this._map=new Map;this.xref=e;this.objId=null;this.suppressEncryption=!1;this.__nonSerializable__=dt}assignXref(e){this.xref=e}get size(){return this._map.size}get(e,t,i){let a=this._map.get(e);if(void 0===a&&void 0!==t){a=this._map.get(t);void 0===a&&void 0!==i&&(a=this._map.get(i))}return a instanceof Ref&&this.xref?this.xref.fetch(a,this.suppressEncryption):a}async getAsync(e,t,i){let a=this._map.get(e);if(void 0===a&&void 0!==t){a=this._map.get(t);void 0===a&&void 0!==i&&(a=this._map.get(i))}return a instanceof Ref&&this.xref?this.xref.fetchAsync(a,this.suppressEncryption):a}getArray(e,t,i){let a=this._map.get(e);if(void 0===a&&void 0!==t){a=this._map.get(t);void 0===a&&void 0!==i&&(a=this._map.get(i))}a instanceof Ref&&this.xref&&(a=this.xref.fetch(a,this.suppressEncryption));if(Array.isArray(a)){a=a.slice();for(let e=0,t=a.length;e{unreachable("Should not call `set` on the empty dictionary.")};return shadow(this,"empty",e)}static merge({xref:e,dictArray:t,mergeSubDicts:i=!1}){const a=new Dict(e),s=new Map;for(const e of t)if(e instanceof Dict)for(const[t,a]of e._map){let e=s.get(t);if(void 0===e){e=[];s.set(t,e)}else if(!(i&&a instanceof Dict))continue;e.push(a)}for(const[t,i]of s){if(1===i.length||!(i[0]instanceof Dict)){a._map.set(t,i[0]);continue}const s=new Dict(e);for(const e of i)for(const[t,i]of e._map)s._map.has(t)||s._map.set(t,i);s.size>0&&a._map.set(t,s)}s.clear();return a.size>0?a:Dict.empty}clone(){const e=new Dict(this.xref);for(const t of this.getKeys())e.set(t,this.getRaw(t));return e}delete(e){delete this._map[e]}}class Ref{constructor(e,t){this.num=e;this.gen=t}toString(){return 0===this.gen?`${this.num}R`:`${this.num}R${this.gen}`}static fromString(e){const t=ut[e];if(t)return t;const i=/^(\d+)R(\d*)$/.exec(e);return i&&"0"!==i[1]?ut[e]=new Ref(parseInt(i[1]),i[2]?parseInt(i[2]):0):null}static get(e,t){const i=0===t?`${e}R`:`${e}R${t}`;return ut[i]||=new Ref(e,t)}}class RefSet{constructor(e=null){this._set=new Set(e?._set)}has(e){return this._set.has(e.toString())}put(e){this._set.add(e.toString())}remove(e){this._set.delete(e.toString())}[Symbol.iterator](){return this._set.values()}clear(){this._set.clear()}}class RefSetCache{constructor(){this._map=new Map}get size(){return this._map.size}get(e){return this._map.get(e.toString())}has(e){return this._map.has(e.toString())}put(e,t){this._map.set(e.toString(),t)}putAlias(e,t){this._map.set(e.toString(),this.get(t))}[Symbol.iterator](){return this._map.values()}clear(){this._map.clear()}*values(){yield*this._map.values()}*items(){for(const[e,t]of this._map)yield[Ref.fromString(e),t]}}function isName(e,t){return e instanceof Name&&(void 0===t||e.name===t)}function isCmd(e,t){return e instanceof Cmd&&(void 0===t||e.cmd===t)}function isDict(e,t){return e instanceof Dict&&(void 0===t||isName(e.get("Type"),t))}function isRefsEqual(e,t){return e.num===t.num&&e.gen===t.gen}class BaseStream{get length(){unreachable("Abstract getter `length` accessed")}get isEmpty(){unreachable("Abstract getter `isEmpty` accessed")}get isDataLoaded(){return shadow(this,"isDataLoaded",!0)}getByte(){unreachable("Abstract method `getByte` called")}getBytes(e){unreachable("Abstract method `getBytes` called")}async getImageData(e,t){return this.getBytes(e,t)}async asyncGetBytes(){unreachable("Abstract method `asyncGetBytes` called")}get isAsync(){return!1}get canAsyncDecodeImageFromBuffer(){return!1}async getTransferableImage(){return null}peekByte(){const e=this.getByte();-1!==e&&this.pos--;return e}peekBytes(e){const t=this.getBytes(e);this.pos-=t.length;return t}getUint16(){const e=this.getByte(),t=this.getByte();return-1===e||-1===t?-1:(e<<8)+t}getInt32(){return(this.getByte()<<24)+(this.getByte()<<16)+(this.getByte()<<8)+this.getByte()}getByteRange(e,t){unreachable("Abstract method `getByteRange` called")}getString(e){return bytesToString(this.getBytes(e))}skip(e){this.pos+=e||1}reset(){unreachable("Abstract method `reset` called")}moveStart(){unreachable("Abstract method `moveStart` called")}makeSubStream(e,t,i=null){unreachable("Abstract method `makeSubStream` called")}getBaseStreams(){return null}}const ft=/^[1-9]\.\d$/,pt=2**31-1;function getLookupTableFactory(e){let t;return function(){if(e){t=Object.create(null);e(t);e=null}return t}}class MissingDataException extends ot{constructor(e,t){super(`Missing data [${e}, ${t})`,"MissingDataException");this.begin=e;this.end=t}}class ParserEOFException extends ot{constructor(e){super(e,"ParserEOFException")}}class XRefEntryException extends ot{constructor(e){super(e,"XRefEntryException")}}class XRefParseException extends ot{constructor(e){super(e,"XRefParseException")}}function arrayBuffersToBytes(e){const t=e.length;if(0===t)return new Uint8Array(0);if(1===t)return new Uint8Array(e[0]);let i=0;for(let a=0;a0,"The number should be a positive integer.");const i="M".repeat(e/1e3|0)+mt[e%1e3/100|0]+mt[10+(e%100/10|0)]+mt[20+e%10];return t?i.toLowerCase():i}function log2(e){return e>0?Math.ceil(Math.log2(e)):0}function readInt8(e,t){return e[t]<<24>>24}function readUint16(e,t){return e[t]<<8|e[t+1]}function readUint32(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}function isWhiteSpace(e){return 32===e||9===e||13===e||10===e}function isNumberArray(e,t){return Array.isArray(e)?(null===t||e.length===t)&&e.every((e=>"number"==typeof e)):ArrayBuffer.isView(e)&&(0===e.length||"number"==typeof e[0])&&(null===t||e.length===t)}function lookupMatrix(e,t){return isNumberArray(e,6)?e:t}function lookupRect(e,t){return isNumberArray(e,4)?e:t}function lookupNormalRect(e,t){return isNumberArray(e,4)?Util.normalizeRect(e):t}function parseXFAPath(e){const t=/(.+)\[(\d+)\]$/;return e.split(".").map((e=>{const i=e.match(t);return i?{name:i[1],pos:parseInt(i[2],10)}:{name:e,pos:0}}))}function escapePDFName(e){const t=[];let i=0;for(let a=0,s=e.length;a126||35===s||40===s||41===s||60===s||62===s||91===s||93===s||123===s||125===s||47===s||37===s){i"\n"===e?"\\n":"\r"===e?"\\r":`\\${e}`))}function _collectJS(e,t,i,a){if(!e)return;let s=null;if(e instanceof Ref){if(a.has(e))return;s=e;a.put(s);e=t.fetch(e)}if(Array.isArray(e))for(const s of e)_collectJS(s,t,i,a);else if(e instanceof Dict){if(isName(e.get("S"),"JavaScript")){const t=e.get("JS");let a;t instanceof BaseStream?a=t.getString():"string"==typeof t&&(a=t);a&&=stringToPDFString(a).replaceAll("\0","");a&&i.push(a)}_collectJS(e.getRaw("Next"),t,i,a)}s&&a.remove(s)}function collectActions(e,t,i){const a=Object.create(null),s=getInheritableProperty({dict:t,key:"AA",stopWhenFound:!1});if(s)for(let t=s.length-1;t>=0;t--){const r=s[t];if(r instanceof Dict)for(const t of r.getKeys()){const s=i[t];if(!s)continue;const n=[];_collectJS(r.getRaw(t),e,n,new RefSet);n.length>0&&(a[s]=n)}}if(t.has("A")){const i=[];_collectJS(t.get("A"),e,i,new RefSet);i.length>0&&(a.Action=i)}return objectSize(a)>0?a:null}const yt={60:"<",62:">",38:"&",34:""",39:"'"};function*codePointIter(e){for(let t=0,i=e.length;t55295&&(i<57344||i>65533)&&t++;yield i}}function encodeToXmlString(e){const t=[];let i=0;for(let a=0,s=e.length;a55295&&(s<57344||s>65533)&&a++;i=a+1}}if(0===t.length)return e;i: ${e}.`);return!1}return!0}function validateCSSFont(e){const t=new Set(["100","200","300","400","500","600","700","800","900","1000","normal","bold","bolder","lighter"]),{fontFamily:i,fontWeight:a,italicAngle:s}=e;if(!validateFontName(i,!0))return!1;const r=a?a.toString():"";e.fontWeight=t.has(r)?r:"400";const n=parseFloat(s);e.italicAngle=isNaN(n)||n<-90||n>90?"14":s.toString();return!0}function recoverJsURL(e){const t=new RegExp("^\\s*("+["app.launchURL","window.open","xfa.host.gotoURL"].join("|").replaceAll(".","\\.")+")\\((?:'|\")([^'\"]*)(?:'|\")(?:,\\s*(\\w+)\\)|\\))","i").exec(e);return t?.[2]?{url:t[2],newWindow:"app.launchURL"===t[1]&&"true"===t[3]}:null}function numberToString(e){if(Number.isInteger(e))return e.toString();const t=Math.round(100*e);return t%100==0?(t/100).toString():t%10==0?e.toFixed(1):e.toFixed(2)}function getNewAnnotationsMap(e){if(!e)return null;const t=new Map;for(const[i,a]of e){if(!i.startsWith(u))continue;let e=t.get(a.pageIndex);if(!e){e=[];t.set(a.pageIndex,e)}e.push(a)}return t.size>0?t:null}function stringToAsciiOrUTF16BE(e){return function isAscii(e){return/^[\x00-\x7F]*$/.test(e)}(e)?e:stringToUTF16String(e,!0)}function stringToUTF16HexString(e){const t=[];for(let i=0,a=e.length;i>8&255],It[255&a])}return t.join("")}function stringToUTF16String(e,t=!1){const i=[];t&&i.push("þÿ");for(let t=0,a=e.length;t>8&255),String.fromCharCode(255&a))}return i.join("")}function getRotationMatrix(e,t,i){switch(e){case 90:return[0,1,-1,0,t,0];case 180:return[-1,0,0,-1,t,i];case 270:return[0,-1,1,0,0,i];default:throw new Error("Invalid rotation")}}function getSizeInBytes(e){return Math.ceil(Math.ceil(Math.log2(1+e))/8)}class Stream extends BaseStream{constructor(e,t,i,a){super();this.bytes=e instanceof Uint8Array?e:new Uint8Array(e);this.start=t||0;this.pos=this.start;this.end=t+i||this.bytes.length;this.dict=a}get length(){return this.end-this.start}get isEmpty(){return 0===this.length}getByte(){return this.pos>=this.end?-1:this.bytes[this.pos++]}getBytes(e){const t=this.bytes,i=this.pos,a=this.end;if(!e)return t.subarray(i,a);let s=i+e;s>a&&(s=a);this.pos=s;return t.subarray(i,s)}getByteRange(e,t){e<0&&(e=0);t>this.end&&(t=this.end);return this.bytes.subarray(e,t)}reset(){this.pos=this.start}moveStart(){this.start=this.pos}makeSubStream(e,t,i=null){return new Stream(this.bytes.buffer,e,t,i)}}class StringStream extends Stream{constructor(e){super(stringToBytes(e))}}class NullStream extends Stream{constructor(){super(new Uint8Array(0))}}class ChunkedStream extends Stream{constructor(e,t,i){super(new Uint8Array(e),0,e,null);this.chunkSize=t;this._loadedChunks=new Set;this.numChunks=Math.ceil(e/t);this.manager=i;this.progressiveDataLength=0;this.lastSuccessfulEnsureByteChunk=-1}getMissingChunks(){const e=[];for(let t=0,i=this.numChunks;t=this.end?this.numChunks:Math.floor(t/this.chunkSize);for(let e=i;ethis.numChunks)&&t!==this.lastSuccessfulEnsureByteChunk){if(!this._loadedChunks.has(t))throw new MissingDataException(e,e+1);this.lastSuccessfulEnsureByteChunk=t}}ensureRange(e,t){if(e>=t)return;if(t<=this.progressiveDataLength)return;const i=Math.floor(e/this.chunkSize);if(i>this.numChunks)return;const a=Math.min(Math.floor((t-1)/this.chunkSize)+1,this.numChunks);for(let s=i;s=this.end)return-1;e>=this.progressiveDataLength&&this.ensureByte(e);return this.bytes[this.pos++]}getBytes(e){const t=this.bytes,i=this.pos,a=this.end;if(!e){a>this.progressiveDataLength&&this.ensureRange(i,a);return t.subarray(i,a)}let s=i+e;s>a&&(s=a);s>this.progressiveDataLength&&this.ensureRange(i,s);this.pos=s;return t.subarray(i,s)}getByteRange(e,t){e<0&&(e=0);t>this.end&&(t=this.end);t>this.progressiveDataLength&&this.ensureRange(e,t);return this.bytes.subarray(e,t)}makeSubStream(e,t,i=null){t?e+t>this.progressiveDataLength&&this.ensureRange(e,e+t):e>=this.progressiveDataLength&&this.ensureByte(e);function ChunkedStreamSubstream(){}ChunkedStreamSubstream.prototype=Object.create(this);ChunkedStreamSubstream.prototype.getMissingChunks=function(){const e=this.chunkSize,t=Math.floor(this.start/e),i=Math.floor((this.end-1)/e)+1,a=[];for(let e=t;e{const readChunk=({value:r,done:n})=>{try{if(n){const t=arrayBuffersToBytes(a);a=null;e(t);return}s+=r.byteLength;i.isStreamingSupported&&this.onProgress({loaded:s});a.push(r);i.read().then(readChunk,t)}catch(e){t(e)}};i.read().then(readChunk,t)})).then((t=>{this.aborted||this.onReceiveData({chunk:t,begin:e})}))}requestAllChunks(e=!1){if(!e){const e=this.stream.getMissingChunks();this._requestChunks(e)}return this._loadedStreamCapability.promise}_requestChunks(e){const t=this.currRequestId++,i=new Set;this._chunksNeededByRequest.set(t,i);for(const t of e)this.stream.hasChunk(t)||i.add(t);if(0===i.size)return Promise.resolve();const a=Promise.withResolvers();this._promisesByRequest.set(t,a);const s=[];for(const e of i){let i=this._requestsByChunk.get(e);if(!i){i=[];this._requestsByChunk.set(e,i);s.push(e)}i.push(t)}if(s.length>0){const e=this.groupChunks(s);for(const t of e){const e=t.beginChunk*this.chunkSize,i=Math.min(t.endChunk*this.chunkSize,this.length);this.sendRequest(e,i).catch(a.reject)}}return a.promise.catch((e=>{if(!this.aborted)throw e}))}getStream(){return this.stream}requestRange(e,t){t=Math.min(t,this.length);const i=this.getBeginChunk(e),a=this.getEndChunk(t),s=[];for(let e=i;e=0&&a+1!==r){t.push({beginChunk:i,endChunk:a+1});i=r}s+1===e.length&&t.push({beginChunk:i,endChunk:r+1});a=r}return t}onProgress(e){this.msgHandler.send("DocProgress",{loaded:this.stream.numChunksLoaded*this.chunkSize+e.loaded,total:this.length})}onReceiveData(e){const t=e.chunk,i=void 0===e.begin,a=i?this.progressiveDataLength:e.begin,s=a+t.byteLength,r=Math.floor(a/this.chunkSize),n=s0||g.push(i)}}}if(!this.disableAutoFetch&&0===this._requestsByChunk.size){let e;if(1===this.stream.numChunksLoaded){const t=this.stream.numChunks-1;this.stream.hasChunk(t)||(e=t)}else e=this.stream.nextEmptyChunk(n);Number.isInteger(e)&&this._requestChunks([e])}for(const e of g){const t=this._promisesByRequest.get(e);this._promisesByRequest.delete(e);t.resolve()}this.msgHandler.send("DocProgress",{loaded:this.stream.numChunksLoaded*this.chunkSize,total:this.length})}onError(e){this._loadedStreamCapability.reject(e)}getBeginChunk(e){return Math.floor(e/this.chunkSize)}getEndChunk(e){return Math.floor((e-1)/this.chunkSize)+1}abort(e){this.aborted=!0;this.pdfNetworkStream?.cancelAllRequests(e);for(const t of this._promisesByRequest.values())t.reject(e)}}class ColorSpace{constructor(e,t){this.name=e;this.numComps=t}getRgb(e,t){const i=new Uint8ClampedArray(3);this.getRgbItem(e,t,i,0);return i}getRgbItem(e,t,i,a){unreachable("Should not call ColorSpace.getRgbItem")}getRgbBuffer(e,t,i,a,s,r,n){unreachable("Should not call ColorSpace.getRgbBuffer")}getOutputLength(e,t){unreachable("Should not call ColorSpace.getOutputLength")}isPassthrough(e){return!1}isDefaultDecode(e,t){return ColorSpace.isDefaultDecode(e,this.numComps)}fillRgb(e,t,i,a,s,r,n,g,o){const c=t*i;let C=null;const h=1<h&&"DeviceGray"!==this.name&&"DeviceRGB"!==this.name){const t=n<=8?new Uint8Array(h):new Uint16Array(h);for(let e=0;e=.99554525?1:this.#B(0,1,1.055*e**(1/2.4)-.055)}#B(e,t,i){return Math.max(e,Math.min(t,i))}#Q(e){return e<0?-this.#Q(-e):e>8?((e+16)/116)**3:e*CalRGBCS.#I}#E(e,t,i){if(0===e[0]&&0===e[1]&&0===e[2]){i[0]=t[0];i[1]=t[1];i[2]=t[2];return}const a=this.#Q(0),s=(1-a)/(1-this.#Q(e[0])),r=1-s,n=(1-a)/(1-this.#Q(e[1])),g=1-n,o=(1-a)/(1-this.#Q(e[2])),c=1-o;i[0]=t[0]*s+r;i[1]=t[1]*n+g;i[2]=t[2]*o+c}#u(e,t,i){if(1===e[0]&&1===e[2]){i[0]=t[0];i[1]=t[1];i[2]=t[2];return}const a=i;this.#c(CalRGBCS.#i,t,a);const s=CalRGBCS.#n;this.#C(e,a,s);this.#c(CalRGBCS.#a,s,i)}#d(e,t,i){const a=i;this.#c(CalRGBCS.#i,t,a);const s=CalRGBCS.#n;this.#h(e,a,s);this.#c(CalRGBCS.#a,s,i)}#t(e,t,i,a,s){const r=this.#B(0,1,e[t]*s),n=this.#B(0,1,e[t+1]*s),g=this.#B(0,1,e[t+2]*s),o=1===r?1:r**this.GR,c=1===n?1:n**this.GG,C=1===g?1:g**this.GB,h=this.MXA*o+this.MXB*c+this.MXC*C,l=this.MYA*o+this.MYB*c+this.MYC*C,Q=this.MZA*o+this.MZB*c+this.MZC*C,E=CalRGBCS.#g;E[0]=h;E[1]=l;E[2]=Q;const u=CalRGBCS.#o;this.#u(this.whitePoint,E,u);const d=CalRGBCS.#g;this.#E(this.blackPoint,u,d);const f=CalRGBCS.#o;this.#d(CalRGBCS.#r,d,f);const p=CalRGBCS.#g;this.#c(CalRGBCS.#s,f,p);i[a]=255*this.#l(p[0]);i[a+1]=255*this.#l(p[1]);i[a+2]=255*this.#l(p[2])}getRgbItem(e,t,i,a){this.#t(e,t,i,a,1)}getRgbBuffer(e,t,i,a,s,r,n){const g=1/((1<this.amax||this.bmin>this.bmax){info("Invalid Range, falling back to defaults");this.amin=-100;this.amax=100;this.bmin=-100;this.bmax=100}}#f(e){return e>=6/29?e**3:108/841*(e-4/29)}#p(e,t,i,a){return i+e*(a-i)/t}#t(e,t,i,a,s){let r=e[t],n=e[t+1],g=e[t+2];if(!1!==i){r=this.#p(r,i,0,100);n=this.#p(n,i,this.amin,this.amax);g=this.#p(g,i,this.bmin,this.bmax)}n>this.amax?n=this.amax:nthis.bmax?g=this.bmax:g>>0}function hexToStr(e,t){return 1===t?String.fromCharCode(e[0],e[1]):3===t?String.fromCharCode(e[0],e[1],e[2],e[3]):String.fromCharCode(...e.subarray(0,t+1))}function addHex(e,t,i){let a=0;for(let s=i;s>=0;s--){a+=e[s]+t[s];e[s]=255&a;a>>=8}}function incHex(e,t){let i=1;for(let a=t;a>=0&&i>0;a--){i+=e[a];e[a]=255&i;i>>=8}}const wt=16;class BinaryCMapStream{constructor(e){this.buffer=e;this.pos=0;this.end=e.length;this.tmpBuf=new Uint8Array(19)}readByte(){return this.pos>=this.end?-1:this.buffer[this.pos++]}readNumber(){let e,t=0;do{const i=this.readByte();if(i<0)throw new FormatError("unexpected EOF in bcmap");e=!(128&i);t=t<<7|127&i}while(!e);return t}readSigned(){const e=this.readNumber();return 1&e?~(e>>>1):e>>>1}readHex(e,t){e.set(this.buffer.subarray(this.pos,this.pos+t+1));this.pos+=t+1}readHexNumber(e,t){let i;const a=this.tmpBuf;let s=0;do{const e=this.readByte();if(e<0)throw new FormatError("unexpected EOF in bcmap");i=!(128&e);a[s++]=127&e}while(!i);let r=t,n=0,g=0;for(;r>=0;){for(;g<8&&a.length>0;){n|=a[--s]<>=8;g-=8}}readHexSigned(e,t){this.readHexNumber(e,t);const i=1&e[t]?255:0;let a=0;for(let s=0;s<=t;s++){a=(1&a)<<8|e[s];e[s]=a>>1^i}}readString(){const e=this.readNumber(),t=new Array(e);for(let i=0;i=0;){const e=l>>5;if(7===e){switch(31&l){case 0:a.readString();break;case 1:r=a.readString()}continue}const i=!!(16&l),s=15&l;if(s+1>wt)throw new Error("BinaryCMapReader.process: Invalid dataSize.");const Q=1,E=a.readNumber();switch(e){case 0:a.readHex(n,s);a.readHexNumber(g,s);addHex(g,n,s);t.addCodespaceRange(s+1,hexToInt(n,s),hexToInt(g,s));for(let e=1;es&&(a=s)}else{for(;!this.eof;)this.readBlock(t);a=this.bufferLength}this.pos=a;return this.buffer.subarray(i,a)}async getImageData(e,t=null){if(!this.canAsyncDecodeImageFromBuffer)return this.getBytes(e,t);const i=await this.stream.asyncGetBytes();return this.decodeImage(i,t)}reset(){this.pos=0}makeSubStream(e,t,i=null){if(void 0===t)for(;!this.eof;)this.readBlock();else{const i=e+t;for(;this.bufferLength<=i&&!this.eof;)this.readBlock()}return new Stream(this.buffer,e,t,i)}getBaseStreams(){return this.str?this.str.getBaseStreams():null}}class StreamsSequenceStream extends DecodeStream{constructor(e,t=null){e=e.filter((e=>e instanceof BaseStream));let i=0;for(const t of e)i+=t instanceof DecodeStream?t._rawMinBufferLength:t.length;super(i);this.streams=e;this._onError=t}readBlock(){const e=this.streams;if(0===e.length){this.eof=!0;return}const t=e.shift();let i;try{i=t.getBytes()}catch(e){if(this._onError){this._onError(e,t.dict?.objId);return}throw e}const a=this.bufferLength,s=a+i.length;this.ensureBuffer(s).set(i,a);this.bufferLength=s}getBaseStreams(){const e=[];for(const t of this.streams){const i=t.getBaseStreams();i&&e.push(...i)}return e.length>0?e:null}}class Ascii85Stream extends DecodeStream{constructor(e,t){t&&(t*=.8);super(t);this.str=e;this.dict=e.dict;this.input=new Uint8Array(5)}readBlock(){const e=this.str;let t=e.getByte();for(;isWhiteSpace(t);)t=e.getByte();if(-1===t||126===t){this.eof=!0;return}const i=this.bufferLength;let a,s;if(122===t){a=this.ensureBuffer(i+4);for(s=0;s<4;++s)a[i+s]=0;this.bufferLength+=4}else{const r=this.input;r[0]=t;for(s=1;s<5;++s){t=e.getByte();for(;isWhiteSpace(t);)t=e.getByte();r[s]=t;if(-1===t||126===t)break}a=this.ensureBuffer(i+s-1);this.bufferLength+=s-1;if(s<5){for(;s<5;++s)r[s]=117;this.eof=!0}let n=0;for(s=0;s<5;++s)n=85*n+(r[s]-33);for(s=3;s>=0;--s){a[i+s]=255&n;n>>=8}}}}class AsciiHexStream extends DecodeStream{constructor(e,t){t&&(t*=.5);super(t);this.str=e;this.dict=e.dict;this.firstDigit=-1}readBlock(){const e=this.str.getBytes(8e3);if(!e.length){this.eof=!0;return}const t=e.length+1>>1,i=this.ensureBuffer(this.bufferLength+t);let a=this.bufferLength,s=this.firstDigit;for(const t of e){let e;if(t>=48&&t<=57)e=15&t;else{if(!(t>=65&&t<=70||t>=97&&t<=102)){if(62===t){this.eof=!0;break}continue}e=9+(15&t)}if(s<0)s=e;else{i[a++]=s<<4|e;s=-1}}if(s>=0&&this.eof){i[a++]=s<<4;s=-1}this.firstDigit=s;this.bufferLength=a}}const bt=-1,Ft=[[-1,-1],[-1,-1],[7,8],[7,7],[6,6],[6,6],[6,5],[6,5],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2]],St=[[-1,-1],[12,-2],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[11,1792],[11,1792],[12,1984],[12,2048],[12,2112],[12,2176],[12,2240],[12,2304],[11,1856],[11,1856],[11,1920],[11,1920],[12,2368],[12,2432],[12,2496],[12,2560]],kt=[[-1,-1],[-1,-1],[-1,-1],[-1,-1],[8,29],[8,29],[8,30],[8,30],[8,45],[8,45],[8,46],[8,46],[7,22],[7,22],[7,22],[7,22],[7,23],[7,23],[7,23],[7,23],[8,47],[8,47],[8,48],[8,48],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[7,20],[7,20],[7,20],[7,20],[8,33],[8,33],[8,34],[8,34],[8,35],[8,35],[8,36],[8,36],[8,37],[8,37],[8,38],[8,38],[7,19],[7,19],[7,19],[7,19],[8,31],[8,31],[8,32],[8,32],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[8,53],[8,53],[8,54],[8,54],[7,26],[7,26],[7,26],[7,26],[8,39],[8,39],[8,40],[8,40],[8,41],[8,41],[8,42],[8,42],[8,43],[8,43],[8,44],[8,44],[7,21],[7,21],[7,21],[7,21],[7,28],[7,28],[7,28],[7,28],[8,61],[8,61],[8,62],[8,62],[8,63],[8,63],[8,0],[8,0],[8,320],[8,320],[8,384],[8,384],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[7,27],[7,27],[7,27],[7,27],[8,59],[8,59],[8,60],[8,60],[9,1472],[9,1536],[9,1600],[9,1728],[7,18],[7,18],[7,18],[7,18],[7,24],[7,24],[7,24],[7,24],[8,49],[8,49],[8,50],[8,50],[8,51],[8,51],[8,52],[8,52],[7,25],[7,25],[7,25],[7,25],[8,55],[8,55],[8,56],[8,56],[8,57],[8,57],[8,58],[8,58],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[8,448],[8,448],[8,512],[8,512],[9,704],[9,768],[8,640],[8,640],[8,576],[8,576],[9,832],[9,896],[9,960],[9,1024],[9,1088],[9,1152],[9,1216],[9,1280],[9,1344],[9,1408],[7,256],[7,256],[7,256],[7,256],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7]],Rt=[[-1,-1],[-1,-1],[12,-2],[12,-2],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[11,1792],[11,1792],[11,1792],[11,1792],[12,1984],[12,1984],[12,2048],[12,2048],[12,2112],[12,2112],[12,2176],[12,2176],[12,2240],[12,2240],[12,2304],[12,2304],[11,1856],[11,1856],[11,1856],[11,1856],[11,1920],[11,1920],[11,1920],[11,1920],[12,2368],[12,2368],[12,2432],[12,2432],[12,2496],[12,2496],[12,2560],[12,2560],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[12,52],[12,52],[13,640],[13,704],[13,768],[13,832],[12,55],[12,55],[12,56],[12,56],[13,1280],[13,1344],[13,1408],[13,1472],[12,59],[12,59],[12,60],[12,60],[13,1536],[13,1600],[11,24],[11,24],[11,24],[11,24],[11,25],[11,25],[11,25],[11,25],[13,1664],[13,1728],[12,320],[12,320],[12,384],[12,384],[12,448],[12,448],[13,512],[13,576],[12,53],[12,53],[12,54],[12,54],[13,896],[13,960],[13,1024],[13,1088],[13,1152],[13,1216],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64]],Nt=[[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[11,23],[11,23],[12,50],[12,51],[12,44],[12,45],[12,46],[12,47],[12,57],[12,58],[12,61],[12,256],[10,16],[10,16],[10,16],[10,16],[10,17],[10,17],[10,17],[10,17],[12,48],[12,49],[12,62],[12,63],[12,30],[12,31],[12,32],[12,33],[12,40],[12,41],[11,22],[11,22],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[12,128],[12,192],[12,26],[12,27],[12,28],[12,29],[11,19],[11,19],[11,20],[11,20],[12,34],[12,35],[12,36],[12,37],[12,38],[12,39],[11,21],[11,21],[12,42],[12,43],[10,0],[10,0],[10,0],[10,0],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12]],Gt=[[-1,-1],[-1,-1],[-1,-1],[-1,-1],[6,9],[6,8],[5,7],[5,7],[4,6],[4,6],[4,6],[4,6],[4,5],[4,5],[4,5],[4,5],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2]];class CCITTFaxDecoder{constructor(e,t={}){if("function"!=typeof e?.next)throw new Error('CCITTFaxDecoder - invalid "source" parameter.');this.source=e;this.eof=!1;this.encoding=t.K||0;this.eoline=t.EndOfLine||!1;this.byteAlign=t.EncodedByteAlign||!1;this.columns=t.Columns||1728;this.rows=t.Rows||0;this.eoblock=t.EndOfBlock??!0;this.black=t.BlackIs1||!1;this.codingLine=new Uint32Array(this.columns+1);this.refLine=new Uint32Array(this.columns+2);this.codingLine[0]=this.columns;this.codingPos=0;this.row=0;this.nextLine2D=this.encoding<0;this.inputBits=0;this.inputBuf=0;this.outputBits=0;this.rowsDone=!1;let i;for(;0===(i=this._lookBits(12));)this._eatBits(1);1===i&&this._eatBits(12);if(this.encoding>0){this.nextLine2D=!this._lookBits(1);this._eatBits(1)}}readNextChar(){if(this.eof)return-1;const e=this.refLine,t=this.codingLine,i=this.columns;let a,s,r,n,g;if(0===this.outputBits){this.rowsDone&&(this.eof=!0);if(this.eof)return-1;this.err=!1;let r,g,o;if(this.nextLine2D){for(n=0;t[n]=64);do{g+=o=this._getWhiteCode()}while(o>=64)}else{do{r+=o=this._getWhiteCode()}while(o>=64);do{g+=o=this._getBlackCode()}while(o>=64)}this._addPixels(t[this.codingPos]+r,s);t[this.codingPos]0?--a:++a;for(;e[a]<=t[this.codingPos]&&e[a]0?--a:++a;for(;e[a]<=t[this.codingPos]&&e[a]0?--a:++a;for(;e[a]<=t[this.codingPos]&&e[a]=64);else do{r+=o=this._getWhiteCode()}while(o>=64);this._addPixels(t[this.codingPos]+r,s);s^=1}}let c=!1;this.byteAlign&&(this.inputBits&=-8);if(this.eoblock||this.row!==this.rows-1){r=this._lookBits(12);if(this.eoline)for(;r!==bt&&1!==r;){this._eatBits(1);r=this._lookBits(12)}else for(;0===r;){this._eatBits(1);r=this._lookBits(12)}if(1===r){this._eatBits(12);c=!0}else r===bt&&(this.eof=!0)}else this.rowsDone=!0;if(!this.eof&&this.encoding>0&&!this.rowsDone){this.nextLine2D=!this._lookBits(1);this._eatBits(1)}if(this.eoblock&&c&&this.byteAlign){r=this._lookBits(12);if(1===r){this._eatBits(12);if(this.encoding>0){this._lookBits(1);this._eatBits(1)}if(this.encoding>=0)for(n=0;n<4;++n){r=this._lookBits(12);1!==r&&info("bad rtc code: "+r);this._eatBits(12);if(this.encoding>0){this._lookBits(1);this._eatBits(1)}}this.eof=!0}}else if(this.err&&this.eoline){for(;;){r=this._lookBits(13);if(r===bt){this.eof=!0;return-1}if(r>>1==1)break;this._eatBits(1)}this._eatBits(12);if(this.encoding>0){this._eatBits(1);this.nextLine2D=!(1&r)}}this.outputBits=t[0]>0?t[this.codingPos=0]:t[this.codingPos=1];this.row++}if(this.outputBits>=8){g=1&this.codingPos?0:255;this.outputBits-=8;if(0===this.outputBits&&t[this.codingPos]r){g<<=r;1&this.codingPos||(g|=255>>8-r);this.outputBits-=r;r=0}else{g<<=this.outputBits;1&this.codingPos||(g|=255>>8-this.outputBits);r-=this.outputBits;this.outputBits=0;if(t[this.codingPos]0){g<<=r;r=0}}}while(r)}this.black&&(g^=255);return g}_addPixels(e,t){const i=this.codingLine;let a=this.codingPos;if(e>i[a]){if(e>this.columns){info("row is wrong length");this.err=!0;e=this.columns}1&a^t&&++a;i[a]=e}this.codingPos=a}_addPixelsNeg(e,t){const i=this.codingLine;let a=this.codingPos;if(e>i[a]){if(e>this.columns){info("row is wrong length");this.err=!0;e=this.columns}1&a^t&&++a;i[a]=e}else if(e0&&e=s){const t=i[e-s];if(t[0]===a){this._eatBits(a);return[!0,t[1],!0]}}}return[!1,0,!1]}_getTwoDimCode(){let e,t=0;if(this.eoblock){t=this._lookBits(7);e=Ft[t];if(e?.[0]>0){this._eatBits(e[0]);return e[1]}}else{const e=this._findTableCode(1,7,Ft);if(e[0]&&e[2])return e[1]}info("Bad two dim code");return bt}_getWhiteCode(){let e,t=0;if(this.eoblock){t=this._lookBits(12);if(t===bt)return 1;e=t>>5?kt[t>>3]:St[t];if(e[0]>0){this._eatBits(e[0]);return e[1]}}else{let e=this._findTableCode(1,9,kt);if(e[0])return e[1];e=this._findTableCode(11,12,St);if(e[0])return e[1]}info("bad white code");this._eatBits(1);return 1}_getBlackCode(){let e,t;if(this.eoblock){e=this._lookBits(13);if(e===bt)return 1;t=e>>7?!(e>>9)&&e>>7?Nt[(e>>1)-64]:Gt[e>>7]:Rt[e];if(t[0]>0){this._eatBits(t[0]);return t[1]}}else{let e=this._findTableCode(2,6,Gt);if(e[0])return e[1];e=this._findTableCode(7,12,Nt,64);if(e[0])return e[1];e=this._findTableCode(10,13,Rt);if(e[0])return e[1]}info("bad black code");this._eatBits(1);return 1}_lookBits(e){let t;for(;this.inputBits>16-e;this.inputBuf=this.inputBuf<<8|t;this.inputBits+=8}return this.inputBuf>>this.inputBits-e&65535>>16-e}_eatBits(e){(this.inputBits-=e)<0&&(this.inputBits=0)}}class CCITTFaxStream extends DecodeStream{constructor(e,t,i){super(t);this.str=e;this.dict=e.dict;i instanceof Dict||(i=Dict.empty);const a={next:()=>e.getByte()};this.ccittFaxDecoder=new CCITTFaxDecoder(a,{K:i.get("K"),EndOfLine:i.get("EndOfLine"),EncodedByteAlign:i.get("EncodedByteAlign"),Columns:i.get("Columns"),Rows:i.get("Rows"),EndOfBlock:i.get("EndOfBlock"),BlackIs1:i.get("BlackIs1")})}readBlock(){for(;!this.eof;){const e=this.ccittFaxDecoder.readNextChar();if(-1===e){this.eof=!0;return}this.ensureBuffer(this.bufferLength+1);this.buffer[this.bufferLength++]=e}}}const Mt=new Int32Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ut=new Int32Array([3,4,5,6,7,8,9,10,65547,65549,65551,65553,131091,131095,131099,131103,196643,196651,196659,196667,262211,262227,262243,262259,327811,327843,327875,327907,258,258,258]),xt=new Int32Array([1,2,3,4,65541,65543,131081,131085,196625,196633,262177,262193,327745,327777,393345,393409,459009,459137,524801,525057,590849,591361,657409,658433,724993,727041,794625,798721,868353,876545]),Lt=[new Int32Array([459008,524368,524304,524568,459024,524400,524336,590016,459016,524384,524320,589984,524288,524416,524352,590048,459012,524376,524312,589968,459028,524408,524344,590032,459020,524392,524328,59e4,524296,524424,524360,590064,459010,524372,524308,524572,459026,524404,524340,590024,459018,524388,524324,589992,524292,524420,524356,590056,459014,524380,524316,589976,459030,524412,524348,590040,459022,524396,524332,590008,524300,524428,524364,590072,459009,524370,524306,524570,459025,524402,524338,590020,459017,524386,524322,589988,524290,524418,524354,590052,459013,524378,524314,589972,459029,524410,524346,590036,459021,524394,524330,590004,524298,524426,524362,590068,459011,524374,524310,524574,459027,524406,524342,590028,459019,524390,524326,589996,524294,524422,524358,590060,459015,524382,524318,589980,459031,524414,524350,590044,459023,524398,524334,590012,524302,524430,524366,590076,459008,524369,524305,524569,459024,524401,524337,590018,459016,524385,524321,589986,524289,524417,524353,590050,459012,524377,524313,589970,459028,524409,524345,590034,459020,524393,524329,590002,524297,524425,524361,590066,459010,524373,524309,524573,459026,524405,524341,590026,459018,524389,524325,589994,524293,524421,524357,590058,459014,524381,524317,589978,459030,524413,524349,590042,459022,524397,524333,590010,524301,524429,524365,590074,459009,524371,524307,524571,459025,524403,524339,590022,459017,524387,524323,589990,524291,524419,524355,590054,459013,524379,524315,589974,459029,524411,524347,590038,459021,524395,524331,590006,524299,524427,524363,590070,459011,524375,524311,524575,459027,524407,524343,590030,459019,524391,524327,589998,524295,524423,524359,590062,459015,524383,524319,589982,459031,524415,524351,590046,459023,524399,524335,590014,524303,524431,524367,590078,459008,524368,524304,524568,459024,524400,524336,590017,459016,524384,524320,589985,524288,524416,524352,590049,459012,524376,524312,589969,459028,524408,524344,590033,459020,524392,524328,590001,524296,524424,524360,590065,459010,524372,524308,524572,459026,524404,524340,590025,459018,524388,524324,589993,524292,524420,524356,590057,459014,524380,524316,589977,459030,524412,524348,590041,459022,524396,524332,590009,524300,524428,524364,590073,459009,524370,524306,524570,459025,524402,524338,590021,459017,524386,524322,589989,524290,524418,524354,590053,459013,524378,524314,589973,459029,524410,524346,590037,459021,524394,524330,590005,524298,524426,524362,590069,459011,524374,524310,524574,459027,524406,524342,590029,459019,524390,524326,589997,524294,524422,524358,590061,459015,524382,524318,589981,459031,524414,524350,590045,459023,524398,524334,590013,524302,524430,524366,590077,459008,524369,524305,524569,459024,524401,524337,590019,459016,524385,524321,589987,524289,524417,524353,590051,459012,524377,524313,589971,459028,524409,524345,590035,459020,524393,524329,590003,524297,524425,524361,590067,459010,524373,524309,524573,459026,524405,524341,590027,459018,524389,524325,589995,524293,524421,524357,590059,459014,524381,524317,589979,459030,524413,524349,590043,459022,524397,524333,590011,524301,524429,524365,590075,459009,524371,524307,524571,459025,524403,524339,590023,459017,524387,524323,589991,524291,524419,524355,590055,459013,524379,524315,589975,459029,524411,524347,590039,459021,524395,524331,590007,524299,524427,524363,590071,459011,524375,524311,524575,459027,524407,524343,590031,459019,524391,524327,589999,524295,524423,524359,590063,459015,524383,524319,589983,459031,524415,524351,590047,459023,524399,524335,590015,524303,524431,524367,590079]),9],Ht=[new Int32Array([327680,327696,327688,327704,327684,327700,327692,327708,327682,327698,327690,327706,327686,327702,327694,0,327681,327697,327689,327705,327685,327701,327693,327709,327683,327699,327691,327707,327687,327703,327695,0]),5];class FlateStream extends DecodeStream{constructor(e,t){super(t);this.str=e;this.dict=e.dict;const i=e.getByte(),a=e.getByte();if(-1===i||-1===a)throw new FormatError(`Invalid header in flate stream: ${i}, ${a}`);if(8!=(15&i))throw new FormatError(`Unknown compression method in flate stream: ${i}, ${a}`);if(((i<<8)+a)%31!=0)throw new FormatError(`Bad FCHECK in flate stream: ${i}, ${a}`);if(32&a)throw new FormatError(`FDICT bit set in flate stream: ${i}, ${a}`);this.codeSize=0;this.codeBuf=0}async getImageData(e,t){const i=await this.asyncGetBytes();return i?.subarray(0,e)||this.getBytes(e)}async asyncGetBytes(){this.str.reset();const e=this.str.getBytes();try{const{readable:t,writable:i}=new DecompressionStream("deflate"),a=i.getWriter();await a.ready;a.write(e).then((async()=>{await a.ready;await a.close()})).catch((()=>{}));const s=[];let r=0;for await(const e of t){s.push(e);r+=e.byteLength}const n=new Uint8Array(r);let g=0;for(const e of s){n.set(e,g);g+=e.byteLength}return n}catch{this.str=new Stream(e,2,e.length,this.str.dict);this.reset();return null}}get isAsync(){return!0}getBits(e){const t=this.str;let i,a=this.codeSize,s=this.codeBuf;for(;a>e;this.codeSize=a-=e;return i}getCode(e){const t=this.str,i=e[0],a=e[1];let s,r=this.codeSize,n=this.codeBuf;for(;r>16,c=65535&g;if(o<1||r>o;this.codeSize=r-o;return c}generateHuffmanTable(e){const t=e.length;let i,a=0;for(i=0;ia&&(a=e[i]);const s=1<>=1}for(i=e;i>=1;if(0===t){let t;if(-1===(t=a.getByte())){this.#m("Bad block header in flate stream");return}let i=t;if(-1===(t=a.getByte())){this.#m("Bad block header in flate stream");return}i|=t<<8;if(-1===(t=a.getByte())){this.#m("Bad block header in flate stream");return}let s=t;if(-1===(t=a.getByte())){this.#m("Bad block header in flate stream");return}s|=t<<8;if(s!==(65535&~i)&&(0!==i||0!==s))throw new FormatError("Bad uncompressed block length in flate stream");this.codeBuf=0;this.codeSize=0;const r=this.bufferLength,n=r+i;e=this.ensureBuffer(n);this.bufferLength=n;if(0===i)-1===a.peekByte()&&(this.eof=!0);else{const t=a.getBytes(i);e.set(t,r);t.length0;)C[g++]=Q}s=this.generateHuffmanTable(C.subarray(0,e));r=this.generateHuffmanTable(C.subarray(e,c))}}e=this.buffer;let n=e?e.length:0,g=this.bufferLength;for(;;){let t=this.getCode(s);if(t<256){if(g+1>=n){e=this.ensureBuffer(g+1);n=e.length}e[g++]=t;continue}if(256===t){this.bufferLength=g;return}t-=257;t=Ut[t];let a=t>>16;a>0&&(a=this.getBits(a));i=(65535&t)+a;t=this.getCode(r);t=xt[t];a=t>>16;a>0&&(a=this.getBits(a));const o=(65535&t)+a;if(g+i>=n){e=this.ensureBuffer(g+i);n=e.length}for(let t=0;t>9&127;this.clow=this.clow<<7&65535;this.ct-=7;this.a=32768}byteIn(){const e=this.data;let t=this.bp;if(255===e[t])if(e[t+1]>143){this.clow+=65280;this.ct=8}else{t++;this.clow+=e[t]<<9;this.ct=7;this.bp=t}else{t++;this.clow+=t65535){this.chigh+=this.clow>>16;this.clow&=65535}}readBit(e,t){let i=e[t]>>1,a=1&e[t];const s=Jt[i],r=s.qe;let n,g=this.a-r;if(this.chigh>15&1;this.clow=this.clow<<1&65535;this.ct--}while(!(32768&g));this.a=g;e[t]=i<<1|a;return n}}class Jbig2Error extends ot{constructor(e){super(e,"Jbig2Error")}}class ContextCache{getContexts(e){return e in this?this[e]:this[e]=new Int8Array(65536)}}class DecodingContext{constructor(e,t,i){this.data=e;this.start=t;this.end=i}get decoder(){return shadow(this,"decoder",new ArithmeticDecoder(this.data,this.start,this.end))}get contextCache(){return shadow(this,"contextCache",new ContextCache)}}function decodeInteger(e,t,i){const a=e.getContexts(t);let s=1;function readBits(e){let t=0;for(let r=0;r>>0}const r=readBits(1),n=readBits(1)?readBits(1)?readBits(1)?readBits(1)?readBits(1)?readBits(32)+4436:readBits(12)+340:readBits(8)+84:readBits(6)+20:readBits(4)+4:readBits(2);let g;0===r?g=n:n>0&&(g=-n);return g>=-2147483648&&g<=pt?g:null}function decodeIAID(e,t,i){const a=e.getContexts("IAID");let s=1;for(let e=0;e=F&&x=S){K=K<<1&d;for(u=0;u=0&&H=0){J=G[L][H];J&&(K|=J<=e?c<<=1:c=c<<1|w[g][o]}for(Q=0;Q=m||o<0||o>=p?c<<=1:c=c<<1|a[g][o]}const E=D.readBit(b,c);t[n]=E}}return w}function decodeTextRegion(e,t,i,a,s,r,n,g,o,c,C,h,l,Q,E,u,d,f,p){if(e&&t)throw new Jbig2Error("refinement with Huffman is not supported");const m=[];let y,w;for(y=0;y1&&(s=e?p.readBits(f):decodeInteger(b,"IAIT",D));const r=n*F+s,S=e?Q.symbolIDTable.decode(p):decodeIAID(b,D,o),k=t&&(e?p.readBit():decodeInteger(b,"IARI",D));let R=g[S],N=R[0].length,G=R.length;if(k){const e=decodeInteger(b,"IARDW",D),t=decodeInteger(b,"IARDH",D);N+=e;G+=t;R=decodeRefinement(N,G,E,R,(e>>1)+decodeInteger(b,"IARDX",D),(t>>1)+decodeInteger(b,"IARDY",D),!1,u,d)}let M=0;c?1&h?M=G-1:a+=G-1:h>1?a+=N-1:M=N-1;const U=r-(1&h?0:G-1),x=a-(2&h?N-1:0);let L,H,J;if(c)for(L=0;L>5&7;const o=[31&n];let c=t+6;if(7===n){g=536870911&readUint32(e,c-1);c+=3;let t=g+7>>3;o[0]=e[c++];for(;--t>0;)o.push(e[c++])}else if(5===n||6===n)throw new Jbig2Error("invalid referred-to flags");i.retainBits=o;let C=4;i.number<=256?C=1:i.number<=65536&&(C=2);const h=[];let l,Q;for(l=0;l>>24&255;r[3]=t.height>>16&255;r[4]=t.height>>8&255;r[5]=255&t.height;for(l=c,Q=e.length;l>2&3;e.huffmanDWSelector=t>>4&3;e.bitmapSizeSelector=t>>6&1;e.aggregationInstancesSelector=t>>7&1;e.bitmapCodingContextUsed=!!(256&t);e.bitmapCodingContextRetained=!!(512&t);e.template=t>>10&3;e.refinementTemplate=t>>12&1;c+=2;if(!e.huffman){o=0===e.template?4:1;n=[];for(g=0;g>2&3;C.stripSize=1<>4&3;C.transposed=!!(64&h);C.combinationOperator=h>>7&3;C.defaultPixelValue=h>>9&1;C.dsOffset=h<<17>>27;C.refinementTemplate=h>>15&1;if(C.huffman){const e=readUint16(a,c);c+=2;C.huffmanFS=3&e;C.huffmanDS=e>>2&3;C.huffmanDT=e>>4&3;C.huffmanRefinementDW=e>>6&3;C.huffmanRefinementDH=e>>8&3;C.huffmanRefinementDX=e>>10&3;C.huffmanRefinementDY=e>>12&3;C.huffmanRefinementSizeSelector=!!(16384&e)}if(C.refinement&&!C.refinementTemplate){n=[];for(g=0;g<2;g++){n.push({x:readInt8(a,c),y:readInt8(a,c+1)});c+=2}C.refinementAt=n}C.numberOfSymbolInstances=readUint32(a,c);c+=4;r=[C,i.referredTo,a,c,s];break;case 16:const l={},Q=a[c++];l.mmr=!!(1&Q);l.template=Q>>1&3;l.patternWidth=a[c++];l.patternHeight=a[c++];l.maxPatternIndex=readUint32(a,c);c+=4;r=[l,i.number,a,c,s];break;case 22:case 23:const E={};E.info=readRegionSegmentInformation(a,c);c+=Ot;const u=a[c++];E.mmr=!!(1&u);E.template=u>>1&3;E.enableSkip=!!(8&u);E.combinationOperator=u>>4&7;E.defaultPixelValue=u>>7&1;E.gridWidth=readUint32(a,c);c+=4;E.gridHeight=readUint32(a,c);c+=4;E.gridOffsetX=4294967295&readUint32(a,c);c+=4;E.gridOffsetY=4294967295&readUint32(a,c);c+=4;E.gridVectorX=readUint16(a,c);c+=2;E.gridVectorY=readUint16(a,c);c+=2;r=[E,i.referredTo,a,c,s];break;case 38:case 39:const d={};d.info=readRegionSegmentInformation(a,c);c+=Ot;const f=a[c++];d.mmr=!!(1&f);d.template=f>>1&3;d.prediction=!!(8&f);if(!d.mmr){o=0===d.template?4:1;n=[];for(g=0;g>2&1;p.combinationOperator=m>>3&3;p.requiresBuffer=!!(32&m);p.combinationOperatorOverride=!!(64&m);r=[p];break;case 49:case 50:case 51:case 62:break;case 53:r=[i.number,a,c,s];break;default:throw new Jbig2Error(`segment type ${i.typeName}(${i.type}) is not implemented`)}const C="on"+i.typeName;C in t&&t[C].apply(t,r)}function processSegments(e,t){for(let i=0,a=e.length;i>3,i=new Uint8ClampedArray(t*e.height);e.defaultPixelValue&&i.fill(255);this.buffer=i}drawBitmap(e,t){const i=this.currentPageInfo,a=e.width,s=e.height,r=i.width+7>>3,n=i.combinationOperatorOverride?e.combinationOperator:i.combinationOperator,g=this.buffer,o=128>>(7&e.x);let c,C,h,l,Q=e.y*r+(e.x>>3);switch(n){case 0:for(c=0;c>=1;if(!h){h=128;l++}}Q+=r}break;case 2:for(c=0;c>=1;if(!h){h=128;l++}}Q+=r}break;default:throw new Jbig2Error(`operator ${n} is not supported`)}}onImmediateGenericRegion(e,t,i,a){const s=e.info,r=new DecodingContext(t,i,a),n=decodeBitmap(e.mmr,s.width,s.height,e.template,e.prediction,null,e.at,r);this.drawBitmap(s,n)}onImmediateLosslessGenericRegion(){this.onImmediateGenericRegion(...arguments)}onSymbolDictionary(e,t,i,a,s,r){let n,g;if(e.huffman){n=function getSymbolDictionaryHuffmanTables(e,t,i){let a,s,r,n,g=0;switch(e.huffmanDHSelector){case 0:case 1:a=getStandardTable(e.huffmanDHSelector+4);break;case 3:a=getCustomHuffmanTable(g,t,i);g++;break;default:throw new Jbig2Error("invalid Huffman DH selector")}switch(e.huffmanDWSelector){case 0:case 1:s=getStandardTable(e.huffmanDWSelector+2);break;case 3:s=getCustomHuffmanTable(g,t,i);g++;break;default:throw new Jbig2Error("invalid Huffman DW selector")}if(e.bitmapSizeSelector){r=getCustomHuffmanTable(g,t,i);g++}else r=getStandardTable(1);n=e.aggregationInstancesSelector?getCustomHuffmanTable(g,t,i):getStandardTable(1);return{tableDeltaHeight:a,tableDeltaWidth:s,tableBitmapSize:r,tableAggregateInstances:n}}(e,i,this.customTables);g=new Reader(a,s,r)}let o=this.symbols;o||(this.symbols=o={});const c=[];for(const e of i){const t=o[e];t&&c.push(...t)}const C=new DecodingContext(a,s,r);o[t]=function decodeSymbolDictionary(e,t,i,a,s,r,n,g,o,c,C,h){if(e&&t)throw new Jbig2Error("symbol refinement with Huffman is not supported");const l=[];let Q=0,E=log2(i.length+a);const u=C.decoder,d=C.contextCache;let f,p;if(e){f=getStandardTable(1);p=[];E=Math.max(E,1)}for(;l.length1)m=decodeTextRegion(e,t,a,Q,0,s,1,i.concat(l),E,0,0,1,0,r,o,c,C,0,h);else{const e=decodeIAID(d,u,E),t=decodeInteger(d,"IARDX",u),s=decodeInteger(d,"IARDY",u);m=decodeRefinement(a,Q,o,e=32){let i,a,n;switch(t){case 32:if(0===e)throw new Jbig2Error("no previous value in symbol ID table");a=s.readBits(2)+3;i=r[e-1].prefixLength;break;case 33:a=s.readBits(3)+3;i=0;break;case 34:a=s.readBits(7)+11;i=0;break;default:throw new Jbig2Error("invalid code length in symbol ID table")}for(n=0;n=0;d--){R=e?decodeMMRBitmap(k,o,c,!0):decodeBitmap(!1,o,c,i,!1,null,F,E);S[d]=R}for(N=0;N=0;f--){M^=S[f][N][G];U|=M<>8;H=h+N*l-G*Q>>8;if(L>=0&&L+w<=a&&H>=0&&H+D<=s)for(d=0;d=s)){Y=u[t];J=x[d];for(f=0;f=0&&e>1&7),o=1+(a>>4&7),c=[];let C,h,l=s;do{C=n.readBits(g);h=n.readBits(o);c.push(new HuffmanLine([l,C,h,0]));l+=1<>t&1;if(t<=0)this.children[i]=new HuffmanTreeNode(e);else{let a=this.children[i];a||(this.children[i]=a=new HuffmanTreeNode(null));a.buildTree(e,t-1)}}decodeNode(e){if(this.isLeaf){if(this.isOOB)return null;const t=e.readBits(this.rangeLength);return this.rangeLow+(this.isLowerRange?-t:t)}const t=this.children[e.readBit()];if(!t)throw new Jbig2Error("invalid Huffman data");return t.decodeNode(e)}}class HuffmanTable{constructor(e,t){t||this.assignPrefixCodes(e);this.rootNode=new HuffmanTreeNode(null);for(let t=0,i=e.length;t0&&this.rootNode.buildTree(i,i.prefixLength-1)}}decode(e){return this.rootNode.decodeNode(e)}assignPrefixCodes(e){const t=e.length;let i=0;for(let a=0;a=this.end)throw new Jbig2Error("end of data while reading bit");this.currentByte=this.data[this.position++];this.shift=7}const e=this.currentByte>>this.shift&1;this.shift--;return e}readBits(e){let t,i=0;for(t=e-1;t>=0;t--)i|=this.readBit()<=this.end?-1:this.data[this.position++]}}function getCustomHuffmanTable(e,t,i){let a=0;for(let s=0,r=t.length;s>i&1;i--}}if(a&&!g){const e=5;for(let t=0;t>2,c=new Uint32Array(e.buffer,t,o);if(FeatureTest.isLittleEndian){for(;n>>24|t<<8|4278190080;i[a+2]=t>>>16|s<<16|4278190080;i[a+3]=s>>>8|4278190080}for(let s=4*n,r=t+g;s>>8|255;i[a+2]=t<<16|s>>>16|255;i[a+3]=s<<8|255}for(let s=4*n,r=t+g;s>3,h=7&a,l=e.length;i=new Uint32Array(i.buffer);let Q=0;for(let a=0;a0&&!e[r-1];)r--;const n=[{children:[],index:0}];let g,o=n[0];for(i=0;i0;)o=n.pop();o.index++;n.push(o);for(;n.length<=i;){n.push(g={children:[],index:0});o.children[o.index]=g.children;o=g}s++}if(i+10){E--;return Q>>E&1}Q=e[t++];if(255===Q){const a=e[t++];if(a){if(220===a&&c){const a=readUint16(e,t+=2);t+=2;if(a>0&&a!==i.scanLines)throw new DNLMarkerError("Found DNL marker (0xFFDC) while parsing scan data",a)}else if(217===a){if(c){const e=p*(8===i.precision?8:0);if(e>0&&Math.round(i.scanLines/e)>=5)throw new DNLMarkerError("Found EOI marker (0xFFD9) while parsing scan data, possibly caused by incorrect `scanLines` parameter",e)}throw new EOIMarkerError("Found EOI marker (0xFFD9) while parsing scan data")}throw new JpegError(`unexpected marker ${(Q<<8|a).toString(16)}`)}}E=7;return Q>>>7}function decodeHuffman(e){let t=e;for(;;){t=t[readBit()];switch(typeof t){case"number":return t;case"object":continue}throw new JpegError("invalid huffman sequence")}}function receive(e){let t=0;for(;e>0;){t=t<<1|readBit();e--}return t}function receiveAndExtend(e){if(1===e)return 1===readBit()?1:-1;const t=receive(e);return t>=1<0){u--;return}let i=r;const a=n;for(;i<=a;){const a=decodeHuffman(e.huffmanTableAC),s=15&a,r=a>>4;if(0===s){if(r<15){u=receive(r)+(1<>4;if(0===s)if(c<15){u=receive(c)+(1<>4;if(0===a){if(r<15)break;s+=16;continue}s+=r;const n=Wt[s];e.blockData[t+n]=receiveAndExtend(a);s++}};let k,R=0;const N=1===m?a[0].blocksPerLine*a[0].blocksPerColumn:C*i.mcusPerColumn;let G,M;for(;R<=N;){const i=s?Math.min(N-R,s):N;if(i>0){for(w=0;w0?"unexpected":"excessive"} MCU data, current marker is: ${k.invalid}`);t=k.offset}if(!(k.marker>=65488&&k.marker<=65495))break;t+=2}return t-l}function quantizeAndInverse(e,t,i){const a=e.quantizationTable,s=e.blockData;let r,n,g,o,c,C,h,l,Q,E,u,d,f,p,m,y,w;if(!a)throw new JpegError("missing required Quantization Table.");for(let e=0;e<64;e+=8){Q=s[t+e];E=s[t+e+1];u=s[t+e+2];d=s[t+e+3];f=s[t+e+4];p=s[t+e+5];m=s[t+e+6];y=s[t+e+7];Q*=a[e];if(E|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4;u<16?u=0:u>=4080?u=255:u>>=4;d<16?d=0:d>=4080?d=255:d>>=4;f<16?f=0:f>=4080?f=255:f>>=4;p<16?p=0:p>=4080?p=255:p>>=4;m<16?m=0:m>=4080?m=255:m>>=4;y<16?y=0:y>=4080?y=255:y>>=4;s[t+e]=Q;s[t+e+8]=E;s[t+e+16]=u;s[t+e+24]=d;s[t+e+32]=f;s[t+e+40]=p;s[t+e+48]=m;s[t+e+56]=y}else{w=$t*Q+8192>>14;w=w<-2040?0:w>=2024?255:w+2056>>4;s[t+e]=w;s[t+e+8]=w;s[t+e+16]=w;s[t+e+24]=w;s[t+e+32]=w;s[t+e+40]=w;s[t+e+48]=w;s[t+e+56]=w}}}function buildComponentData(e,t){const i=t.blocksPerLine,a=t.blocksPerColumn,s=new Int16Array(64);for(let e=0;e=a)return null;const r=readUint16(e,t);if(r>=65472&&r<=65534)return{invalid:null,marker:r,offset:t};let n=readUint16(e,s);for(;!(n>=65472&&n<=65534);){if(++s>=a)return null;n=readUint16(e,s)}return{invalid:r.toString(16),marker:n,offset:s}}function prepareComponents(e){const t=Math.ceil(e.samplesPerLine/8/e.maxH),i=Math.ceil(e.scanLines/8/e.maxV);for(const a of e.components){const s=Math.ceil(Math.ceil(e.samplesPerLine/8)*a.h/e.maxH),r=Math.ceil(Math.ceil(e.scanLines/8)*a.v/e.maxV),n=t*a.h,g=64*(i*a.v)*(n+1);a.blockData=new Int16Array(g);a.blocksPerLine=s;a.blocksPerColumn=r}e.mcusPerLine=t;e.mcusPerColumn=i}function readDataBlock(e,t){const i=readUint16(e,t);let a=(t+=2)+i-2;const s=findNextFileMarker(e,a,t);if(s?.invalid){warn("readDataBlock - incorrect length, current marker is: "+s.invalid);a=s.offset}const r=e.subarray(t,a);return{appData:r,newOffset:t+=r.length}}function skipData(e,t){const i=readUint16(e,t),a=(t+=2)+i-2,s=findNextFileMarker(e,a,t);return s?.invalid?s.offset:a}class JpegImage{constructor({decodeTransform:e=null,colorTransform:t=-1}={}){this._decodeTransform=e;this._colorTransform=t}static canUseImageDecoder(e,t=-1){let i=0,a=null,s=readUint16(e,i);i+=2;if(65496!==s)throw new JpegError("SOI not found");s=readUint16(e,i);i+=2;A:for(;65497!==s;){switch(s){case 65472:case 65473:case 65474:a=e[i+7];break A;case 65535:255!==e[i]&&i--}i=skipData(e,i);s=readUint16(e,i);i+=2}return 4!==a&&(3!==a||0!==t)}parse(e,{dnlScanLines:t=null}={}){let i,a,s=0,r=null,n=null,g=0;const o=[],c=[],C=[];let h=readUint16(e,s);s+=2;if(65496!==h)throw new JpegError("SOI not found");h=readUint16(e,s);s+=2;A:for(;65497!==h;){let l,Q,E;switch(h){case 65504:case 65505:case 65506:case 65507:case 65508:case 65509:case 65510:case 65511:case 65512:case 65513:case 65514:case 65515:case 65516:case 65517:case 65518:case 65519:case 65534:const{appData:u,newOffset:d}=readDataBlock(e,s);s=d;65504===h&&74===u[0]&&70===u[1]&&73===u[2]&&70===u[3]&&0===u[4]&&(r={version:{major:u[5],minor:u[6]},densityUnits:u[7],xDensity:u[8]<<8|u[9],yDensity:u[10]<<8|u[11],thumbWidth:u[12],thumbHeight:u[13],thumbData:u.subarray(14,14+3*u[12]*u[13])});65518===h&&65===u[0]&&100===u[1]&&111===u[2]&&98===u[3]&&101===u[4]&&(n={version:u[5]<<8|u[6],flags0:u[7]<<8|u[8],flags1:u[9]<<8|u[10],transformCode:u[11]});break;case 65499:const f=readUint16(e,s);s+=2;const p=f+s-2;let m;for(;s>4){if(t>>4!=1)throw new JpegError("DQT - invalid table spec");for(Q=0;Q<64;Q++){m=Wt[Q];i[m]=readUint16(e,s);s+=2}}else for(Q=0;Q<64;Q++){m=Wt[Q];i[m]=e[s++]}o[15&t]=i}break;case 65472:case 65473:case 65474:if(i)throw new JpegError("Only single frame JPEGs supported");s+=2;i={};i.extended=65473===h;i.progressive=65474===h;i.precision=e[s++];const y=readUint16(e,s);s+=2;i.scanLines=t||y;i.samplesPerLine=readUint16(e,s);s+=2;i.components=[];i.componentIds={};const w=e[s++];let D=0,b=0;for(l=0;l>4,r=15&e[s+1];D>4?c:C)[15&t]=buildHuffmanTable(i,r)}break;case 65501:s+=2;a=readUint16(e,s);s+=2;break;case 65498:const S=1==++g&&!t;s+=2;const k=e[s++],R=[];for(l=0;l>4];r.huffmanTableAC=c[15&n];R.push(r)}const N=e[s++],G=e[s++],M=e[s++];try{s+=decodeScan(e,s,i,R,a,N,G,M>>4,15&M,S)}catch(t){if(t instanceof DNLMarkerError){warn(`${t.message} -- attempting to re-parse the JPEG image.`);return this.parse(e,{dnlScanLines:t.scanLines})}if(t instanceof EOIMarkerError){warn(`${t.message} -- ignoring the rest of the image data.`);break A}throw t}break;case 65500:s+=4;break;case 65535:255!==e[s]&&s--;break;default:const U=findNextFileMarker(e,s-2,s-3);if(U?.invalid){warn("JpegImage.parse - unexpected data, current marker is: "+U.invalid);s=U.offset;break}if(!U||s>=e.length-1){warn("JpegImage.parse - reached the end of the image data without finding an EOI marker (0xFFD9).");break A}throw new JpegError("JpegImage.parse - unknown marker: "+h.toString(16))}h=readUint16(e,s);s+=2}if(!i)throw new JpegError("JpegImage.parse - no frame data found.");this.width=i.samplesPerLine;this.height=i.scanLines;this.jfif=r;this.adobe=n;this.components=[];for(const e of i.components){const t=o[e.quantizationId];t&&(e.quantizationTable=t);this.components.push({index:e.index,output:buildComponentData(0,e),scaleX:e.h/i.maxH,scaleY:e.v/i.maxV,blocksPerLine:e.blocksPerLine,blocksPerColumn:e.blocksPerColumn})}this.numComponents=this.components.length}_getLinearizedBlockData(e,t,i=!1){const a=this.width/e,s=this.height/t;let r,n,g,o,c,C,h,l,Q,E,u,d=0;const f=this.components.length,p=e*t*f,m=new Uint8ClampedArray(p),y=new Uint32Array(e),w=4294967288;let D;for(h=0;h>8)+b[Q+1];return m}get _isColorConversionNeeded(){return this.adobe?!!this.adobe.transformCode:3===this.numComponents?0!==this._colorTransform&&(82!==this.components[0].index||71!==this.components[1].index||66!==this.components[2].index):1===this._colorTransform}_convertYccToRgb(e){let t,i,a;for(let s=0,r=e.length;s4)throw new JpegError("Unsupported color mode");const r=this._getLinearizedBlockData(e,t,s);if(1===this.numComponents&&(i||a)){const e=r.length*(i?4:3),t=new Uint8ClampedArray(e);let a=0;if(i)!function grayToRGBA(e,t){if(FeatureTest.isLittleEndian)for(let i=0,a=e.length;i0&&(e=e.subarray(t));break}return e}decodeImage(e){if(this.eof)return this.buffer;e=this.#w(e||this.bytes);const t=new JpegImage(this.jpegOptions);t.parse(e);const i=t.getData({width:this.drawWidth,height:this.drawHeight,forceRGBA:this.forceRGBA,forceRGB:this.forceRGB,isSourcePDF:!0});this.buffer=i;this.bufferLength=i.length;this.eof=!0;return this.buffer}get canAsyncDecodeImageFromBuffer(){return this.stream.isAsync}async getTransferableImage(){if(!await JpegStream.canUseImageDecoder)return null;const e=this.jpegOptions;if(e.decodeTransform)return null;let t;try{const i=this.canAsyncDecodeImageFromBuffer&&await this.stream.asyncGetBytes()||this.bytes;if(!i)return null;const a=this.#w(i);if(!JpegImage.canUseImageDecoder(a,e.colorTransform))return null;t=new ImageDecoder({data:a,type:"image/jpeg",preferAnimation:!1});return(await t.decode()).image}catch(e){warn(`getTransferableImage - failed: "${e}".`);return null}finally{t?.close()}}}var ei,ti=(ei="undefined"!=typeof document?document.currentScript?.src:void 0,function(e={}){var t,i,a=e;new Promise(((e,a)=>{t=e;i=a}));a.decode=function(e,{numComponents:t=4,isIndexedColormap:i=!1,smaskInData:s=!1}){const r=e.length,n=a._malloc(r);a.HEAPU8.set(e,n);const g=a._jp2_decode(n,r,t>0?t:0,!!i,!!s);a._free(n);if(g){const{errorMessages:e}=a;if(e){delete a.errorMessages;return e}return"Unknown error"}const{imageData:o}=a;a.imageData=null;return o};var s=Object.assign({},a),r="./this.program",quit_=(e,t)=>{throw t},n="";"undefined"!=typeof document&&document.currentScript&&(n=document.currentScript.src);ei&&(n=ei);n=n.startsWith("blob:")?"":n.substr(0,n.replace(/[?#].*/,"").lastIndexOf("/")+1);var g=a.print||console.log.bind(console),o=a.printErr||console.error.bind(console);Object.assign(a,s);s=null;a.arguments&&a.arguments;a.thisProgram&&(r=a.thisProgram);var c,C=a.wasmBinary;function tryParseAsDataURI(e){if(isDataURI(e))return function intArrayFromBase64(e){for(var t=atob(e),i=new Uint8Array(t.length),a=0;ae.startsWith(b);function instantiateSync(e,t){var i,a=function getBinarySync(e){if(e==d&&C)return new Uint8Array(C);var t=tryParseAsDataURI(e);if(t)return t;throw'sync fetching of the wasm failed: you can preload it to Module["wasmBinary"] manually, or emcc.py will do that for you when generating HTML (but not JS)'}(e);i=new WebAssembly.Module(a);return[new WebAssembly.Instance(i,t),i]}class ExitStatus{name="ExitStatus";constructor(e){this.message=`Program terminated with exit(${e})`;this.status=e}}var F,callRuntimeCallbacks=e=>{for(;e.length>0;)e.shift()(a)},S=a.noExitRuntime||!0,k=0,R={},handleException=e=>{if(e instanceof ExitStatus||"unwind"==e)return h;quit_(0,e)},keepRuntimeAlive=()=>S||k>0,_proc_exit=e=>{h=e;if(!keepRuntimeAlive()){a.onExit?.(e);u=!0}quit_(0,new ExitStatus(e))},_exit=(e,t)=>{h=e;_proc_exit(e)},callUserCallback=e=>{if(!u)try{e();(()=>{if(!keepRuntimeAlive())try{_exit(h)}catch(e){handleException(e)}})()}catch(e){handleException(e)}},growMemory=e=>{var t=(e-c.buffer.byteLength+65535)/65536|0;try{c.grow(t);updateMemoryViews();return 1}catch(e){}},N={},getEnvStrings=()=>{if(!getEnvStrings.strings){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:r||"./this.program"};for(var t in N)void 0===N[t]?delete e[t]:e[t]=N[t];var i=[];for(var t in e)i.push(`${t}=${e[t]}`);getEnvStrings.strings=i}return getEnvStrings.strings},G=[null,[],[]],M="undefined"!=typeof TextDecoder?new TextDecoder:void 0,UTF8ArrayToString=(e,t=0,i=NaN)=>{for(var a=t+i,s=t;e[s]&&!(s>=a);)++s;if(s-t>16&&e.buffer&&M)return M.decode(e.subarray(t,s));for(var r="";t>10,56320|1023&c)}}else r+=String.fromCharCode((31&n)<<6|g)}else r+=String.fromCharCode(n)}return r},printChar=(e,t)=>{var i=G[e];if(0===t||10===t){(1===e?g:o)(UTF8ArrayToString(i));i.length=0}else i.push(t)},UTF8ToString=(e,t)=>e?UTF8ArrayToString(Q,e,t):"",U={m:()=>function abort(e){a.onAbort?.(e);o(e="Aborted("+e+")");u=!0;e+=". Build with -sASSERTIONS for more info.";var t=new WebAssembly.RuntimeError(e);i(t);throw t}(""),c:(e,t,i)=>Q.copyWithin(e,t,t+i),l:()=>{S=!1;k=0},n:(e,t)=>{if(R[e]){clearTimeout(R[e].id);delete R[e]}if(!t)return 0;var i=setTimeout((()=>{delete R[e];callUserCallback((()=>L(e,performance.now())))}),t);R[e]={id:i,timeout_ms:t};return 0},g:function _copy_pixels_1(e,t){e>>=2;const i=a.imageData=new Uint8ClampedArray(t),s=a.HEAP32.subarray(e,e+t);i.set(s)},f:function _copy_pixels_3(e,t,i,s){e>>=2;t>>=2;i>>=2;const r=a.imageData=new Uint8ClampedArray(3*s),n=a.HEAP32.subarray(e,e+s),g=a.HEAP32.subarray(t,t+s),o=a.HEAP32.subarray(i,i+s);for(let e=0;e>=2;t>>=2;i>>=2;s>>=2;const n=a.imageData=new Uint8ClampedArray(4*r),g=a.HEAP32.subarray(e,e+r),o=a.HEAP32.subarray(t,t+r),c=a.HEAP32.subarray(i,i+r),C=a.HEAP32.subarray(s,s+r);for(let e=0;e{var t,i,a=Q.length,s=2147483648;if((e>>>=0)>s)return!1;for(var r=1;r<=4;r*=2){var n=a*(1+.2/r);n=Math.min(n,e+100663296);var g=Math.min(s,(t=Math.max(e,n),i=65536,Math.ceil(t/i)*i));if(growMemory(g))return!0}return!1},p:(e,t)=>{var i=0;getEnvStrings().forEach(((a,s)=>{var r=t+i;E[e+4*s>>2]=r;((e,t)=>{for(var i=0;i{var i=getEnvStrings();E[e>>2]=i.length;var a=0;i.forEach((e=>a+=e.length+1));E[t>>2]=a;return 0},r:e=>52,j:function _fd_seek(e,t,i,a,s){return 70},b:(e,t,i,a)=>{for(var s=0,r=0;r>2],g=E[t+4>>2];t+=8;for(var o=0;o>2]=s;return 0},s:function _gray_to_rgba(e,t){e>>=2;const i=a.imageData=new Uint8ClampedArray(4*t),s=a.HEAP32.subarray(e,e+t);for(let e=0;e>=2;t>>=2;const s=a.imageData=new Uint8ClampedArray(4*i),r=a.HEAP32.subarray(e,e+i),n=a.HEAP32.subarray(t,t+i);for(let e=0;e>=2;t>>=2;i>>=2;const r=a.imageData=new Uint8ClampedArray(4*s),n=a.HEAP32.subarray(e,e+s),g=a.HEAP32.subarray(t,t+s),o=a.HEAP32.subarray(i,i+s);for(let e=0;e0)){!function preRun(){if(a.preRun){"function"==typeof a.preRun&&(a.preRun=[a.preRun]);for(;a.preRun.length;)e=a.preRun.shift(),f.unshift(e)}var e;callRuntimeCallbacks(f)}();if(!(y>0))if(a.setStatus){a.setStatus("Running...");setTimeout((()=>{setTimeout((()=>a.setStatus("")),1);doRun()}),1)}else doRun()}function doRun(){if(!F){F=!0;a.calledRun=!0;if(!u){!function initRuntime(){callRuntimeCallbacks(p)}();t(a);a.onRuntimeInitialized?.();!function postRun(){if(a.postRun){"function"==typeof a.postRun&&(a.postRun=[a.postRun]);for(;a.postRun.length;)e=a.postRun.shift(),m.unshift(e)}var e;callRuntimeCallbacks(m)}()}}}}if(a.preInit){"function"==typeof a.preInit&&(a.preInit=[a.preInit]);for(;a.preInit.length>0;)a.preInit.pop()()}run();return a});const ii=ti;class JpxError extends ot{constructor(e){super(e,"JpxError")}}class JpxImage{static#D=null;static decode(e,t){t||={};this.#D||=ii({warn});const i=this.#D.decode(e,t);if("string"==typeof i)throw new JpxError(i);return i}static cleanup(){this.#D=null}static parseImageProperties(e){let t=e.getByte();for(;t>=0;){const i=t;t=e.getByte();if(65361===(i<<8|t)){e.skip(4);const t=e.getInt32()>>>0,i=e.getInt32()>>>0,a=e.getInt32()>>>0,s=e.getInt32()>>>0;e.skip(16);return{width:t-a,height:i-s,bitsPerComponent:8,componentsCount:e.getUint16()}}}throw new JpxError("No size marker found in JPX stream")}}class JpxStream extends DecodeStream{constructor(e,t,i){super(t);this.stream=e;this.dict=e.dict;this.maybeLength=t;this.params=i}get bytes(){return shadow(this,"bytes",this.stream.getBytes(this.maybeLength))}ensureBuffer(e){}readBlock(e){this.decodeImage(null,e)}decodeImage(e,t){if(this.eof)return this.buffer;e||=this.bytes;this.buffer=JpxImage.decode(e,t);this.bufferLength=this.buffer.length;this.eof=!0;return this.buffer}get canAsyncDecodeImageFromBuffer(){return this.stream.isAsync}}class LZWStream extends DecodeStream{constructor(e,t,i){super(t);this.str=e;this.dict=e.dict;this.cachedData=0;this.bitsCached=0;const a=4096,s={earlyChange:i,codeLength:9,nextCode:258,dictionaryValues:new Uint8Array(a),dictionaryLengths:new Uint16Array(a),dictionaryPrevCodes:new Uint16Array(a),currentSequence:new Uint8Array(a),currentSequenceLength:0};for(let e=0;e<256;++e){s.dictionaryValues[e]=e;s.dictionaryLengths[e]=1}this.lzwState=s}readBits(e){let t=this.bitsCached,i=this.cachedData;for(;t>>t&(1<0;if(e<256){l[0]=e;Q=1}else{if(!(e>=258)){if(256===e){C=9;n=258;Q=0;continue}this.eof=!0;delete this.lzwState;break}if(e=0;t--){l[t]=g[i];i=c[i]}}else l[Q++]=l[0]}if(s){c[n]=h;o[n]=o[h]+1;g[n]=l[0];n++;C=n+r&n+r-1?C:0|Math.min(Math.log(n+r)/.6931471805599453+1,12)}h=e;E+=Q;if(a15))throw new FormatError(`Unsupported predictor: ${a}`);this.readBlock=2===a?this.readBlockTiff:this.readBlockPng;this.str=e;this.dict=e.dict;const s=this.colors=i.get("Colors")||1,r=this.bits=i.get("BPC","BitsPerComponent")||8,n=this.columns=i.get("Columns")||1;this.pixBytes=s*r+7>>3;this.rowBytes=n*s*r+7>>3;return this}readBlockTiff(){const e=this.rowBytes,t=this.bufferLength,i=this.ensureBuffer(t+e),a=this.bits,s=this.colors,r=this.str.getBytes(e);this.eof=!r.length;if(this.eof)return;let n,g=0,o=0,c=0,C=0,h=t;if(1===a&&1===s)for(n=0;n>1;e^=e>>2;e^=e>>4;g=(1&e)<<7;i[h++]=e}else if(8===a){for(n=0;n>8&255;i[h++]=255&e}}else{const e=new Uint8Array(s+1),h=(1<>c-a)&h;c-=a;o=o<=8){i[Q++]=o>>C-8&255;C-=8}}C>0&&(i[Q++]=(o<<8-C)+(g&(1<<8-C)-1))}this.bufferLength+=e}readBlockPng(){const e=this.rowBytes,t=this.pixBytes,i=this.str.getByte(),a=this.str.getBytes(e);this.eof=!a.length;if(this.eof)return;const s=this.bufferLength,r=this.ensureBuffer(s+e);let n=r.subarray(s-e,s);0===n.length&&(n=new Uint8Array(e));let g,o,c,C=s;switch(i){case 0:for(g=0;g>1)+a[g];for(;g>1)+a[g]&255;C++}break;case 4:for(g=0;g0){const e=this.str.getBytes(a);t.set(e,i);i+=a}}else{a=257-a;const s=e[1];t=this.ensureBuffer(i+a+1);for(let e=0;e>")&&this.buf1!==Bt;){if(!(this.buf1 instanceof Name)){info("Malformed dictionary: key must be a name object");this.shift();continue}const t=this.buf1.name;this.shift();if(this.buf1===Bt)break;a.set(t,this.getObj(e))}if(this.buf1===Bt){if(this.recoveryMode)return a;throw new ParserEOFException("End of file inside dictionary.")}if(isCmd(this.buf2,"stream"))return this.allowStreams?this.makeStream(a,e):a;this.shift();return a;default:return t}if(Number.isInteger(t)){if(Number.isInteger(this.buf1)&&isCmd(this.buf2,"R")){const e=Ref.get(t,this.buf1);this.shift();this.shift();return e}return t}return"string"==typeof t&&e?e.decryptString(t):t}findDefaultInlineStreamEnd(e){const{knownCommands:t}=this.lexer,i=e.pos;let a,s,r=0;for(;-1!==(a=e.getByte());)if(0===r)r=69===a?1:0;else if(1===r)r=73===a?2:0;else if(32===a||10===a||13===a){s=e.pos;const i=e.peekBytes(15),n=i.length;if(0===n)break;for(let e=0;e127))){r=0;break}}if(2!==r)continue;if(!t){warn("findDefaultInlineStreamEnd - `lexer.knownCommands` is undefined.");continue}const g=new Lexer(new Stream(i.slice()),t);g._hexStringWarn=()=>{};let o=0;for(;;){const e=g.getObj();if(e===Bt){r=0;break}if(e instanceof Cmd){const i=t[e.cmd];if(!i){r=0;break}if(i.variableArgs?o<=i.numArgs:o===i.numArgs)break;o=0}else o++}if(2===r)break}else r=0;if(-1===a){warn("findDefaultInlineStreamEnd: Reached the end of the stream without finding a valid EI marker");if(s){warn('... trying to recover by using the last "EI" occurrence.');e.skip(-(e.pos-s))}}let n=4;e.skip(-n);a=e.peekByte();e.skip(n);isWhiteSpace(a)||n--;return e.pos-n-i}findDCTDecodeInlineStreamEnd(e){const t=e.pos;let i,a,s=!1;for(;-1!==(i=e.getByte());)if(255===i){switch(e.getByte()){case 0:break;case 255:e.skip(-1);break;case 217:s=!0;break;case 192:case 193:case 194:case 195:case 197:case 198:case 199:case 201:case 202:case 203:case 205:case 206:case 207:case 196:case 204:case 218:case 219:case 220:case 221:case 222:case 223:case 224:case 225:case 226:case 227:case 228:case 229:case 230:case 231:case 232:case 233:case 234:case 235:case 236:case 237:case 238:case 239:case 254:a=e.getUint16();a>2?e.skip(a-2):e.skip(-2)}if(s)break}const r=e.pos-t;if(-1===i){warn("Inline DCTDecode image stream: EOI marker not found, searching for /EI/ instead.");e.skip(-r);return this.findDefaultInlineStreamEnd(e)}this.inlineStreamSkipEI(e);return r}findASCII85DecodeInlineStreamEnd(e){const t=e.pos;let i;for(;-1!==(i=e.getByte());)if(126===i){const t=e.pos;i=e.peekByte();for(;isWhiteSpace(i);){e.skip();i=e.peekByte()}if(62===i){e.skip();break}if(e.pos>t){const t=e.peekBytes(2);if(69===t[0]&&73===t[1])break}}const a=e.pos-t;if(-1===i){warn("Inline ASCII85Decode image stream: EOD marker not found, searching for /EI/ instead.");e.skip(-a);return this.findDefaultInlineStreamEnd(e)}this.inlineStreamSkipEI(e);return a}findASCIIHexDecodeInlineStreamEnd(e){const t=e.pos;let i;for(;-1!==(i=e.getByte())&&62!==i;);const a=e.pos-t;if(-1===i){warn("Inline ASCIIHexDecode image stream: EOD marker not found, searching for /EI/ instead.");e.skip(-a);return this.findDefaultInlineStreamEnd(e)}this.inlineStreamSkipEI(e);return a}inlineStreamSkipEI(e){let t,i=0;for(;-1!==(t=e.getByte());)if(0===i)i=69===t?1:0;else if(1===i)i=73===t?2:0;else if(2===i)break}makeInlineImage(e){const t=this.lexer,i=t.stream,a=Object.create(null);let s;for(;!isCmd(this.buf1,"ID")&&this.buf1!==Bt;){if(!(this.buf1 instanceof Name))throw new FormatError("Dictionary key must be a name object");const t=this.buf1.name;this.shift();if(this.buf1===Bt)break;a[t]=this.getObj(e)}-1!==t.beginInlineImagePos&&(s=i.pos-t.beginInlineImagePos);const r=this.xref.fetchIfRef(a.F||a.Filter);let n;if(r instanceof Name)n=r.name;else if(Array.isArray(r)){const e=this.xref.fetchIfRef(r[0]);e instanceof Name&&(n=e.name)}const g=i.pos;let o,c;switch(n){case"DCT":case"DCTDecode":o=this.findDCTDecodeInlineStreamEnd(i);break;case"A85":case"ASCII85Decode":o=this.findASCII85DecodeInlineStreamEnd(i);break;case"AHx":case"ASCIIHexDecode":o=this.findASCIIHexDecodeInlineStreamEnd(i);break;default:o=this.findDefaultInlineStreamEnd(i)}if(o<1e3&&s>0){const e=i.pos;i.pos=t.beginInlineImagePos;c=function getInlineImageCacheKey(e){const t=[],i=e.length;let a=0;for(;a=a){let a=!1;for(const e of s){const t=e.length;let s=0;for(;s=r){a=!0;break}if(s>=t){if(isWhiteSpace(n[o+g+s])){info(`Found "${bytesToString([...i,...e])}" when searching for endstream command.`);a=!0}break}}if(a){t.pos+=o;return t.pos-e}}o++}t.pos+=g}return-1}makeStream(e,t){const i=this.lexer;let a=i.stream;i.skipToNextLine();const s=a.pos-1;let r=e.get("Length");if(!Number.isInteger(r)){info(`Bad length "${r&&r.toString()}" in stream.`);r=0}a.pos=s+r;i.nextChar();if(this.tryShift()&&isCmd(this.buf2,"endstream"))this.shift();else{r=this.#b(s);if(r<0)throw new FormatError("Missing endstream command.");i.nextChar();this.shift();this.shift()}this.shift();a=a.makeSubStream(s,r,e);t&&(a=t.createStream(a,r));a=this.filter(a,e,r);a.dict=e;return a}filter(e,t,i){let a=t.get("F","Filter"),s=t.get("DP","DecodeParms");if(a instanceof Name){Array.isArray(s)&&warn("/DecodeParms should not be an Array, when /Filter is a Name.");return this.makeFilter(e,a.name,i,s)}let r=i;if(Array.isArray(a)){const t=a,i=s;for(let n=0,g=t.length;n=48&&e<=57?15&e:e>=65&&e<=70||e>=97&&e<=102?9+(15&e):-1}class Lexer{constructor(e,t=null){this.stream=e;this.nextChar();this.strBuf=[];this.knownCommands=t;this._hexStringNumWarn=0;this.beginInlineImagePos=-1}nextChar(){return this.currentChar=this.stream.getByte()}peekChar(){return this.stream.peekByte()}getNumber(){let e=this.currentChar,t=!1,i=0,a=1;if(45===e){a=-1;e=this.nextChar();45===e&&(e=this.nextChar())}else 43===e&&(e=this.nextChar());if(10===e||13===e)do{e=this.nextChar()}while(10===e||13===e);if(46===e){i=10;e=this.nextChar()}if(e<48||e>57){const t=`Invalid number: ${String.fromCharCode(e)} (charCode ${e})`;if(isWhiteSpace(e)||-1===e){info(`Lexer.getNumber - "${t}".`);return 0}throw new FormatError(t)}let s=e-48,r=0,n=1;for(;(e=this.nextChar())>=0;)if(e>=48&&e<=57){const a=e-48;if(t)r=10*r+a;else{0!==i&&(i*=10);s=10*s+a}}else if(46===e){if(0!==i)break;i=1}else if(45===e)warn("Badly formatted number: minus sign in the middle");else{if(69!==e&&101!==e)break;e=this.peekChar();if(43===e||45===e){n=45===e?-1:1;this.nextChar()}else if(e<48||e>57)break;t=!0}0!==i&&(s/=i);t&&(s*=10**(n*r));return a*s}getString(){let e=1,t=!1;const i=this.strBuf;i.length=0;let a=this.nextChar();for(;;){let s=!1;switch(0|a){case-1:warn("Unterminated string");t=!0;break;case 40:++e;i.push("(");break;case 41:if(0==--e){this.nextChar();t=!0}else i.push(")");break;case 92:a=this.nextChar();switch(a){case-1:warn("Unterminated string");t=!0;break;case 110:i.push("\n");break;case 114:i.push("\r");break;case 116:i.push("\t");break;case 98:i.push("\b");break;case 102:i.push("\f");break;case 92:case 40:case 41:i.push(String.fromCharCode(a));break;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:let e=15&a;a=this.nextChar();s=!0;if(a>=48&&a<=55){e=(e<<3)+(15&a);a=this.nextChar();if(a>=48&&a<=55){s=!1;e=(e<<3)+(15&a)}}i.push(String.fromCharCode(e));break;case 13:10===this.peekChar()&&this.nextChar();break;case 10:break;default:i.push(String.fromCharCode(a))}break;default:i.push(String.fromCharCode(a))}if(t)break;s||(a=this.nextChar())}return i.join("")}getName(){let e,t;const i=this.strBuf;i.length=0;for(;(e=this.nextChar())>=0&&!ai[e];)if(35===e){e=this.nextChar();if(ai[e]){warn("Lexer_getName: NUMBER SIGN (#) should be followed by a hexadecimal number.");i.push("#");break}const a=toHexDigit(e);if(-1!==a){t=e;e=this.nextChar();const s=toHexDigit(e);if(-1===s){warn(`Lexer_getName: Illegal digit (${String.fromCharCode(e)}) in hexadecimal number.`);i.push("#",String.fromCharCode(t));if(ai[e])break;i.push(String.fromCharCode(e));continue}i.push(String.fromCharCode(a<<4|s))}else i.push("#",String.fromCharCode(e))}else i.push(String.fromCharCode(e));i.length>127&&warn(`Name token is longer than allowed by the spec: ${i.length}`);return Name.get(i.join(""))}_hexStringWarn(e){5!=this._hexStringNumWarn++?this._hexStringNumWarn>5||warn(`getHexString - ignoring invalid character: ${e}`):warn("getHexString - ignoring additional invalid characters.")}getHexString(){const e=this.strBuf;e.length=0;let t=this.currentChar,i=-1,a=-1;this._hexStringNumWarn=0;for(;;){if(t<0){warn("Unterminated hex string");break}if(62===t){this.nextChar();break}if(1!==ai[t]){a=toHexDigit(t);if(-1===a)this._hexStringWarn(t);else if(-1===i)i=a;else{e.push(String.fromCharCode(i<<4|a));i=-1}t=this.nextChar()}else t=this.nextChar()}-1!==i&&e.push(String.fromCharCode(i<<4));return e.join("")}getObj(){let e=!1,t=this.currentChar;for(;;){if(t<0)return Bt;if(e)10!==t&&13!==t||(e=!1);else if(37===t)e=!0;else if(1!==ai[t])break;t=this.nextChar()}switch(0|t){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 43:case 45:case 46:return this.getNumber();case 40:return this.getString();case 47:return this.getName();case 91:this.nextChar();return Cmd.get("[");case 93:this.nextChar();return Cmd.get("]");case 60:t=this.nextChar();if(60===t){this.nextChar();return Cmd.get("<<")}return this.getHexString();case 62:t=this.nextChar();if(62===t){this.nextChar();return Cmd.get(">>")}return Cmd.get(">");case 123:this.nextChar();return Cmd.get("{");case 125:this.nextChar();return Cmd.get("}");case 41:this.nextChar();throw new FormatError(`Illegal character: ${t}`)}let i=String.fromCharCode(t);if(t<32||t>127){const e=this.peekChar();if(e>=32&&e<=127){this.nextChar();return Cmd.get(i)}}const a=this.knownCommands;let s=void 0!==a?.[i];for(;(t=this.nextChar())>=0&&!ai[t];){const e=i+String.fromCharCode(t);if(s&&void 0===a[e])break;if(128===i.length)throw new FormatError(`Command token too long: ${i.length}`);i=e;s=void 0!==a?.[i]}if("true"===i)return!0;if("false"===i)return!1;if("null"===i)return null;"BI"===i&&(this.beginInlineImagePos=this.stream.pos);return Cmd.get(i)}skipToNextLine(){let e=this.currentChar;for(;e>=0;){if(13===e){e=this.nextChar();10===e&&this.nextChar();break}if(10===e){this.nextChar();break}e=this.nextChar()}}}class Linearization{static create(e){function getInt(e,t,i=!1){const a=e.get(t);if(Number.isInteger(a)&&(i?a>=0:a>0))return a;throw new Error(`The "${t}" parameter in the linearization dictionary is invalid.`)}const t=new Parser({lexer:new Lexer(e),xref:null}),i=t.getObj(),a=t.getObj(),s=t.getObj(),r=t.getObj();let n,g;if(!(Number.isInteger(i)&&Number.isInteger(a)&&isCmd(s,"obj")&&r instanceof Dict&&"number"==typeof(n=r.get("Linearized"))&&n>0))return null;if((g=getInt(r,"L"))!==e.length)throw new Error('The "L" parameter in the linearization dictionary does not equal the stream length.');return{length:g,hints:function getHints(e){const t=e.get("H");let i;if(Array.isArray(t)&&(2===(i=t.length)||4===i)){for(let e=0;e0))throw new Error(`Hint (${e}) in the linearization dictionary is invalid.`)}return t}throw new Error("Hint array in the linearization dictionary is invalid.")}(r),objectNumberFirst:getInt(r,"O"),endFirst:getInt(r,"E"),numPages:getInt(r,"N"),mainXRefEntriesOffset:getInt(r,"T"),pageFirst:r.has("P")?getInt(r,"P",!0):0}}}const si=["Adobe-GB1-UCS2","Adobe-CNS1-UCS2","Adobe-Japan1-UCS2","Adobe-Korea1-UCS2","78-EUC-H","78-EUC-V","78-H","78-RKSJ-H","78-RKSJ-V","78-V","78ms-RKSJ-H","78ms-RKSJ-V","83pv-RKSJ-H","90ms-RKSJ-H","90ms-RKSJ-V","90msp-RKSJ-H","90msp-RKSJ-V","90pv-RKSJ-H","90pv-RKSJ-V","Add-H","Add-RKSJ-H","Add-RKSJ-V","Add-V","Adobe-CNS1-0","Adobe-CNS1-1","Adobe-CNS1-2","Adobe-CNS1-3","Adobe-CNS1-4","Adobe-CNS1-5","Adobe-CNS1-6","Adobe-GB1-0","Adobe-GB1-1","Adobe-GB1-2","Adobe-GB1-3","Adobe-GB1-4","Adobe-GB1-5","Adobe-Japan1-0","Adobe-Japan1-1","Adobe-Japan1-2","Adobe-Japan1-3","Adobe-Japan1-4","Adobe-Japan1-5","Adobe-Japan1-6","Adobe-Korea1-0","Adobe-Korea1-1","Adobe-Korea1-2","B5-H","B5-V","B5pc-H","B5pc-V","CNS-EUC-H","CNS-EUC-V","CNS1-H","CNS1-V","CNS2-H","CNS2-V","ETHK-B5-H","ETHK-B5-V","ETen-B5-H","ETen-B5-V","ETenms-B5-H","ETenms-B5-V","EUC-H","EUC-V","Ext-H","Ext-RKSJ-H","Ext-RKSJ-V","Ext-V","GB-EUC-H","GB-EUC-V","GB-H","GB-V","GBK-EUC-H","GBK-EUC-V","GBK2K-H","GBK2K-V","GBKp-EUC-H","GBKp-EUC-V","GBT-EUC-H","GBT-EUC-V","GBT-H","GBT-V","GBTpc-EUC-H","GBTpc-EUC-V","GBpc-EUC-H","GBpc-EUC-V","H","HKdla-B5-H","HKdla-B5-V","HKdlb-B5-H","HKdlb-B5-V","HKgccs-B5-H","HKgccs-B5-V","HKm314-B5-H","HKm314-B5-V","HKm471-B5-H","HKm471-B5-V","HKscs-B5-H","HKscs-B5-V","Hankaku","Hiragana","KSC-EUC-H","KSC-EUC-V","KSC-H","KSC-Johab-H","KSC-Johab-V","KSC-V","KSCms-UHC-H","KSCms-UHC-HW-H","KSCms-UHC-HW-V","KSCms-UHC-V","KSCpc-EUC-H","KSCpc-EUC-V","Katakana","NWP-H","NWP-V","RKSJ-H","RKSJ-V","Roman","UniCNS-UCS2-H","UniCNS-UCS2-V","UniCNS-UTF16-H","UniCNS-UTF16-V","UniCNS-UTF32-H","UniCNS-UTF32-V","UniCNS-UTF8-H","UniCNS-UTF8-V","UniGB-UCS2-H","UniGB-UCS2-V","UniGB-UTF16-H","UniGB-UTF16-V","UniGB-UTF32-H","UniGB-UTF32-V","UniGB-UTF8-H","UniGB-UTF8-V","UniJIS-UCS2-H","UniJIS-UCS2-HW-H","UniJIS-UCS2-HW-V","UniJIS-UCS2-V","UniJIS-UTF16-H","UniJIS-UTF16-V","UniJIS-UTF32-H","UniJIS-UTF32-V","UniJIS-UTF8-H","UniJIS-UTF8-V","UniJIS2004-UTF16-H","UniJIS2004-UTF16-V","UniJIS2004-UTF32-H","UniJIS2004-UTF32-V","UniJIS2004-UTF8-H","UniJIS2004-UTF8-V","UniJISPro-UCS2-HW-V","UniJISPro-UCS2-V","UniJISPro-UTF8-V","UniJISX0213-UTF32-H","UniJISX0213-UTF32-V","UniJISX02132004-UTF32-H","UniJISX02132004-UTF32-V","UniKS-UCS2-H","UniKS-UCS2-V","UniKS-UTF16-H","UniKS-UTF16-V","UniKS-UTF32-H","UniKS-UTF32-V","UniKS-UTF8-H","UniKS-UTF8-V","V","WP-Symbol"],ri=2**24-1;class CMap{constructor(e=!1){this.codespaceRanges=[[],[],[],[]];this.numCodespaceRanges=0;this._map=[];this.name="";this.vertical=!1;this.useCMap=null;this.builtInCMap=e}addCodespaceRange(e,t,i){this.codespaceRanges[e-1].push(t,i);this.numCodespaceRanges++}mapCidRange(e,t,i){if(t-e>ri)throw new Error("mapCidRange - ignoring data above MAX_MAP_RANGE.");for(;e<=t;)this._map[e++]=i++}mapBfRange(e,t,i){if(t-e>ri)throw new Error("mapBfRange - ignoring data above MAX_MAP_RANGE.");const a=i.length-1;for(;e<=t;){this._map[e++]=i;const t=i.charCodeAt(a)+1;t>255?i=i.substring(0,a-1)+String.fromCharCode(i.charCodeAt(a-1)+1)+"\0":i=i.substring(0,a)+String.fromCharCode(t)}}mapBfRangeToArray(e,t,i){if(t-e>ri)throw new Error("mapBfRangeToArray - ignoring data above MAX_MAP_RANGE.");const a=i.length;let s=0;for(;e<=t&&s>>0;const n=s[r];for(let e=0,t=n.length;e=t&&a<=s){i.charcode=a;i.length=r+1;return}}}i.charcode=0;i.length=1}getCharCodeLength(e){const t=this.codespaceRanges;for(let i=0,a=t.length;i=s&&e<=r)return i+1}}return 1}get length(){return this._map.length}get isIdentityCMap(){if("Identity-H"!==this.name&&"Identity-V"!==this.name)return!1;if(65536!==this._map.length)return!1;for(let e=0;e<65536;e++)if(this._map[e]!==e)return!1;return!0}}class IdentityCMap extends CMap{constructor(e,t){super();this.vertical=e;this.addCodespaceRange(t,0,65535)}mapCidRange(e,t,i){unreachable("should not call mapCidRange")}mapBfRange(e,t,i){unreachable("should not call mapBfRange")}mapBfRangeToArray(e,t,i){unreachable("should not call mapBfRangeToArray")}mapOne(e,t){unreachable("should not call mapCidOne")}lookup(e){return Number.isInteger(e)&&e<=65535?e:void 0}contains(e){return Number.isInteger(e)&&e<=65535}forEach(e){for(let t=0;t<=65535;t++)e(t,t)}charCodeOf(e){return Number.isInteger(e)&&e<=65535?e:-1}getMap(){const e=new Array(65536);for(let t=0;t<=65535;t++)e[t]=t;return e}get length(){return 65536}get isIdentityCMap(){unreachable("should not access .isIdentityCMap")}}function strToInt(e){let t=0;for(let i=0;i>>0}function expectString(e){if("string"!=typeof e)throw new FormatError("Malformed CMap: expected string.")}function expectInt(e){if(!Number.isInteger(e))throw new FormatError("Malformed CMap: expected int.")}function parseBfChar(e,t){for(;;){let i=t.getObj();if(i===Bt)break;if(isCmd(i,"endbfchar"))return;expectString(i);const a=strToInt(i);i=t.getObj();expectString(i);const s=i;e.mapOne(a,s)}}function parseBfRange(e,t){for(;;){let i=t.getObj();if(i===Bt)break;if(isCmd(i,"endbfrange"))return;expectString(i);const a=strToInt(i);i=t.getObj();expectString(i);const s=strToInt(i);i=t.getObj();if(Number.isInteger(i)||"string"==typeof i){const t=Number.isInteger(i)?String.fromCharCode(i):i;e.mapBfRange(a,s,t)}else{if(!isCmd(i,"["))break;{i=t.getObj();const r=[];for(;!isCmd(i,"]")&&i!==Bt;){r.push(i);i=t.getObj()}e.mapBfRangeToArray(a,s,r)}}}throw new FormatError("Invalid bf range.")}function parseCidChar(e,t){for(;;){let i=t.getObj();if(i===Bt)break;if(isCmd(i,"endcidchar"))return;expectString(i);const a=strToInt(i);i=t.getObj();expectInt(i);const s=i;e.mapOne(a,s)}}function parseCidRange(e,t){for(;;){let i=t.getObj();if(i===Bt)break;if(isCmd(i,"endcidrange"))return;expectString(i);const a=strToInt(i);i=t.getObj();expectString(i);const s=strToInt(i);i=t.getObj();expectInt(i);const r=i;e.mapCidRange(a,s,r)}}function parseCodespaceRange(e,t){for(;;){let i=t.getObj();if(i===Bt)break;if(isCmd(i,"endcodespacerange"))return;if("string"!=typeof i)break;const a=strToInt(i);i=t.getObj();if("string"!=typeof i)break;const s=strToInt(i);e.addCodespaceRange(i.length,a,s)}throw new FormatError("Invalid codespace range.")}function parseWMode(e,t){const i=t.getObj();Number.isInteger(i)&&(e.vertical=!!i)}function parseCMapName(e,t){const i=t.getObj();i instanceof Name&&(e.name=i.name)}async function parseCMap(e,t,i,a){let s,r;A:for(;;)try{const i=t.getObj();if(i===Bt)break;if(i instanceof Name){"WMode"===i.name?parseWMode(e,t):"CMapName"===i.name&&parseCMapName(e,t);s=i}else if(i instanceof Cmd)switch(i.cmd){case"endcmap":break A;case"usecmap":s instanceof Name&&(r=s.name);break;case"begincodespacerange":parseCodespaceRange(e,t);break;case"beginbfchar":parseBfChar(e,t);break;case"begincidchar":parseCidChar(e,t);break;case"beginbfrange":parseBfRange(e,t);break;case"begincidrange":parseCidRange(e,t)}}catch(e){if(e instanceof MissingDataException)throw e;warn("Invalid cMap data: "+e);continue}!a&&r&&(a=r);return a?extendCMap(e,i,a):e}async function extendCMap(e,t,i){e.useCMap=await createBuiltInCMap(i,t);if(0===e.numCodespaceRanges){const t=e.useCMap.codespaceRanges;for(let i=0;iextendCMap(s,t,e)));const r=new Lexer(new Stream(i));return parseCMap(s,r,t,null)}class CMapFactory{static async create({encoding:e,fetchBuiltInCMap:t,useCMap:i}){if(e instanceof Name)return createBuiltInCMap(e.name,t);if(e instanceof BaseStream){const a=await parseCMap(new CMap,new Lexer(e),t,i);return a.isIdentityCMap?createBuiltInCMap(a.name,t):a}throw new Error("Encoding required.")}}const ni=[".notdef","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","endash","dagger","daggerdbl","periodcentered","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","questiondown","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","ring","cedilla","hungarumlaut","ogonek","caron","emdash","AE","ordfeminine","Lslash","Oslash","OE","ordmasculine","ae","dotlessi","lslash","oslash","oe","germandbls","onesuperior","logicalnot","mu","trademark","Eth","onehalf","plusminus","Thorn","onequarter","divide","brokenbar","degree","thorn","threequarters","twosuperior","registered","minus","eth","multiply","threesuperior","copyright","Aacute","Acircumflex","Adieresis","Agrave","Aring","Atilde","Ccedilla","Eacute","Ecircumflex","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Ntilde","Oacute","Ocircumflex","Odieresis","Ograve","Otilde","Scaron","Uacute","Ucircumflex","Udieresis","Ugrave","Yacute","Ydieresis","Zcaron","aacute","acircumflex","adieresis","agrave","aring","atilde","ccedilla","eacute","ecircumflex","edieresis","egrave","iacute","icircumflex","idieresis","igrave","ntilde","oacute","ocircumflex","odieresis","ograve","otilde","scaron","uacute","ucircumflex","udieresis","ugrave","yacute","ydieresis","zcaron"],gi=[".notdef","space","exclamsmall","Hungarumlautsmall","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","questionsmall","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","fi","fl","ffi","ffl","parenleftinferior","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","exclamdownsmall","centoldstyle","Lslashsmall","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","Dotaccentsmall","Macronsmall","figuredash","hypheninferior","Ogoneksmall","Ringsmall","Cedillasmall","onequarter","onehalf","threequarters","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall"],oi=[".notdef","space","dollaroldstyle","dollarsuperior","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","fi","fl","ffi","ffl","parenleftinferior","parenrightinferior","hyphensuperior","colonmonetary","onefitted","rupiah","centoldstyle","figuredash","hypheninferior","onequarter","onehalf","threequarters","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior"],Ii=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclamsmall","Hungarumlautsmall","","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","questionsmall","","asuperior","bsuperior","centsuperior","dsuperior","esuperior","","","","isuperior","","","lsuperior","msuperior","nsuperior","osuperior","","","rsuperior","ssuperior","tsuperior","","ff","fi","fl","ffi","ffl","parenleftinferior","","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","exclamdownsmall","centoldstyle","Lslashsmall","","","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","","Dotaccentsmall","","","Macronsmall","","","figuredash","hypheninferior","","","Ogoneksmall","Ringsmall","Cedillasmall","","","","onequarter","onehalf","threequarters","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","","","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall"],ci=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclamsmall","Hungarumlautsmall","centoldstyle","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","","threequartersemdash","","questionsmall","","","","","Ethsmall","","","onequarter","onehalf","threequarters","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","","","","","","","ff","fi","fl","ffi","ffl","parenleftinferior","","parenrightinferior","Circumflexsmall","hypheninferior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","","","asuperior","centsuperior","","","","","Aacutesmall","Agravesmall","Acircumflexsmall","Adieresissmall","Atildesmall","Aringsmall","Ccedillasmall","Eacutesmall","Egravesmall","Ecircumflexsmall","Edieresissmall","Iacutesmall","Igravesmall","Icircumflexsmall","Idieresissmall","Ntildesmall","Oacutesmall","Ogravesmall","Ocircumflexsmall","Odieresissmall","Otildesmall","Uacutesmall","Ugravesmall","Ucircumflexsmall","Udieresissmall","","eightsuperior","fourinferior","threeinferior","sixinferior","eightinferior","seveninferior","Scaronsmall","","centinferior","twoinferior","","Dieresissmall","","Caronsmall","osuperior","fiveinferior","","commainferior","periodinferior","Yacutesmall","","dollarinferior","","","Thornsmall","","nineinferior","zeroinferior","Zcaronsmall","AEsmall","Oslashsmall","questiondownsmall","oneinferior","Lslashsmall","","","","","","","Cedillasmall","","","","","","OEsmall","figuredash","hyphensuperior","","","","","exclamdownsmall","","Ydieresissmall","","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","ninesuperior","zerosuperior","","esuperior","rsuperior","tsuperior","","","isuperior","ssuperior","dsuperior","","","","","","lsuperior","Ogoneksmall","Brevesmall","Macronsmall","bsuperior","nsuperior","msuperior","commasuperior","periodsuperior","Dotaccentsmall","Ringsmall","","","",""],Ci=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","","Adieresis","Aring","Ccedilla","Eacute","Ntilde","Odieresis","Udieresis","aacute","agrave","acircumflex","adieresis","atilde","aring","ccedilla","eacute","egrave","ecircumflex","edieresis","iacute","igrave","icircumflex","idieresis","ntilde","oacute","ograve","ocircumflex","odieresis","otilde","uacute","ugrave","ucircumflex","udieresis","dagger","degree","cent","sterling","section","bullet","paragraph","germandbls","registered","copyright","trademark","acute","dieresis","notequal","AE","Oslash","infinity","plusminus","lessequal","greaterequal","yen","mu","partialdiff","summation","product","pi","integral","ordfeminine","ordmasculine","Omega","ae","oslash","questiondown","exclamdown","logicalnot","radical","florin","approxequal","Delta","guillemotleft","guillemotright","ellipsis","space","Agrave","Atilde","Otilde","OE","oe","endash","emdash","quotedblleft","quotedblright","quoteleft","quoteright","divide","lozenge","ydieresis","Ydieresis","fraction","currency","guilsinglleft","guilsinglright","fi","fl","daggerdbl","periodcentered","quotesinglbase","quotedblbase","perthousand","Acircumflex","Ecircumflex","Aacute","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Oacute","Ocircumflex","apple","Ograve","Uacute","Ucircumflex","Ugrave","dotlessi","circumflex","tilde","macron","breve","dotaccent","ring","cedilla","hungarumlaut","ogonek","caron"],hi=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","","endash","dagger","daggerdbl","periodcentered","","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","","questiondown","","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","","ring","cedilla","","hungarumlaut","ogonek","caron","emdash","","","","","","","","","","","","","","","","","AE","","ordfeminine","","","","","Lslash","Oslash","OE","ordmasculine","","","","","","ae","","","","dotlessi","","","lslash","oslash","oe","germandbls","","","",""],li=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","bullet","Euro","bullet","quotesinglbase","florin","quotedblbase","ellipsis","dagger","daggerdbl","circumflex","perthousand","Scaron","guilsinglleft","OE","bullet","Zcaron","bullet","bullet","quoteleft","quoteright","quotedblleft","quotedblright","bullet","endash","emdash","tilde","trademark","scaron","guilsinglright","oe","bullet","zcaron","Ydieresis","space","exclamdown","cent","sterling","currency","yen","brokenbar","section","dieresis","copyright","ordfeminine","guillemotleft","logicalnot","hyphen","registered","macron","degree","plusminus","twosuperior","threesuperior","acute","mu","paragraph","periodcentered","cedilla","onesuperior","ordmasculine","guillemotright","onequarter","onehalf","threequarters","questiondown","Agrave","Aacute","Acircumflex","Atilde","Adieresis","Aring","AE","Ccedilla","Egrave","Eacute","Ecircumflex","Edieresis","Igrave","Iacute","Icircumflex","Idieresis","Eth","Ntilde","Ograve","Oacute","Ocircumflex","Otilde","Odieresis","multiply","Oslash","Ugrave","Uacute","Ucircumflex","Udieresis","Yacute","Thorn","germandbls","agrave","aacute","acircumflex","atilde","adieresis","aring","ae","ccedilla","egrave","eacute","ecircumflex","edieresis","igrave","iacute","icircumflex","idieresis","eth","ntilde","ograve","oacute","ocircumflex","otilde","odieresis","divide","oslash","ugrave","uacute","ucircumflex","udieresis","yacute","thorn","ydieresis"],Bi=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","universal","numbersign","existential","percent","ampersand","suchthat","parenleft","parenright","asteriskmath","plus","comma","minus","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","congruent","Alpha","Beta","Chi","Delta","Epsilon","Phi","Gamma","Eta","Iota","theta1","Kappa","Lambda","Mu","Nu","Omicron","Pi","Theta","Rho","Sigma","Tau","Upsilon","sigma1","Omega","Xi","Psi","Zeta","bracketleft","therefore","bracketright","perpendicular","underscore","radicalex","alpha","beta","chi","delta","epsilon","phi","gamma","eta","iota","phi1","kappa","lambda","mu","nu","omicron","pi","theta","rho","sigma","tau","upsilon","omega1","omega","xi","psi","zeta","braceleft","bar","braceright","similar","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","Euro","Upsilon1","minute","lessequal","fraction","infinity","florin","club","diamond","heart","spade","arrowboth","arrowleft","arrowup","arrowright","arrowdown","degree","plusminus","second","greaterequal","multiply","proportional","partialdiff","bullet","divide","notequal","equivalence","approxequal","ellipsis","arrowvertex","arrowhorizex","carriagereturn","aleph","Ifraktur","Rfraktur","weierstrass","circlemultiply","circleplus","emptyset","intersection","union","propersuperset","reflexsuperset","notsubset","propersubset","reflexsubset","element","notelement","angle","gradient","registerserif","copyrightserif","trademarkserif","product","radical","dotmath","logicalnot","logicaland","logicalor","arrowdblboth","arrowdblleft","arrowdblup","arrowdblright","arrowdbldown","lozenge","angleleft","registersans","copyrightsans","trademarksans","summation","parenlefttp","parenleftex","parenleftbt","bracketlefttp","bracketleftex","bracketleftbt","bracelefttp","braceleftmid","braceleftbt","braceex","","angleright","integral","integraltp","integralex","integralbt","parenrighttp","parenrightex","parenrightbt","bracketrighttp","bracketrightex","bracketrightbt","bracerighttp","bracerightmid","bracerightbt",""],Qi=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","a1","a2","a202","a3","a4","a5","a119","a118","a117","a11","a12","a13","a14","a15","a16","a105","a17","a18","a19","a20","a21","a22","a23","a24","a25","a26","a27","a28","a6","a7","a8","a9","a10","a29","a30","a31","a32","a33","a34","a35","a36","a37","a38","a39","a40","a41","a42","a43","a44","a45","a46","a47","a48","a49","a50","a51","a52","a53","a54","a55","a56","a57","a58","a59","a60","a61","a62","a63","a64","a65","a66","a67","a68","a69","a70","a71","a72","a73","a74","a203","a75","a204","a76","a77","a78","a79","a81","a82","a83","a84","a97","a98","a99","a100","","a89","a90","a93","a94","a91","a92","a205","a85","a206","a86","a87","a88","a95","a96","","","","","","","","","","","","","","","","","","","","a101","a102","a103","a104","a106","a107","a108","a112","a111","a110","a109","a120","a121","a122","a123","a124","a125","a126","a127","a128","a129","a130","a131","a132","a133","a134","a135","a136","a137","a138","a139","a140","a141","a142","a143","a144","a145","a146","a147","a148","a149","a150","a151","a152","a153","a154","a155","a156","a157","a158","a159","a160","a161","a163","a164","a196","a165","a192","a166","a167","a168","a169","a170","a171","a172","a173","a162","a174","a175","a176","a177","a178","a179","a193","a180","a199","a181","a200","a182","","a201","a183","a184","a197","a185","a194","a198","a186","a195","a187","a188","a189","a190","a191",""];function getEncoding(e){switch(e){case"WinAnsiEncoding":return li;case"StandardEncoding":return hi;case"MacRomanEncoding":return Ci;case"SymbolSetEncoding":return Bi;case"ZapfDingbatsEncoding":return Qi;case"ExpertEncoding":return Ii;case"MacExpertEncoding":return ci;default:return null}}const Ei=[".notdef","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","endash","dagger","daggerdbl","periodcentered","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","questiondown","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","ring","cedilla","hungarumlaut","ogonek","caron","emdash","AE","ordfeminine","Lslash","Oslash","OE","ordmasculine","ae","dotlessi","lslash","oslash","oe","germandbls","onesuperior","logicalnot","mu","trademark","Eth","onehalf","plusminus","Thorn","onequarter","divide","brokenbar","degree","thorn","threequarters","twosuperior","registered","minus","eth","multiply","threesuperior","copyright","Aacute","Acircumflex","Adieresis","Agrave","Aring","Atilde","Ccedilla","Eacute","Ecircumflex","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Ntilde","Oacute","Ocircumflex","Odieresis","Ograve","Otilde","Scaron","Uacute","Ucircumflex","Udieresis","Ugrave","Yacute","Ydieresis","Zcaron","aacute","acircumflex","adieresis","agrave","aring","atilde","ccedilla","eacute","ecircumflex","edieresis","egrave","iacute","icircumflex","idieresis","igrave","ntilde","oacute","ocircumflex","odieresis","ograve","otilde","scaron","uacute","ucircumflex","udieresis","ugrave","yacute","ydieresis","zcaron","exclamsmall","Hungarumlautsmall","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","commasuperior","threequartersemdash","periodsuperior","questionsmall","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","ffi","ffl","parenleftinferior","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","exclamdownsmall","centoldstyle","Lslashsmall","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","Dotaccentsmall","Macronsmall","figuredash","hypheninferior","Ogoneksmall","Ringsmall","Cedillasmall","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall","001.000","001.001","001.002","001.003","Black","Bold","Book","Light","Medium","Regular","Roman","Semibold"],ui=391,di=[null,{id:"hstem",min:2,stackClearing:!0,stem:!0},null,{id:"vstem",min:2,stackClearing:!0,stem:!0},{id:"vmoveto",min:1,stackClearing:!0},{id:"rlineto",min:2,resetStack:!0},{id:"hlineto",min:1,resetStack:!0},{id:"vlineto",min:1,resetStack:!0},{id:"rrcurveto",min:6,resetStack:!0},null,{id:"callsubr",min:1,undefStack:!0},{id:"return",min:0,undefStack:!0},null,null,{id:"endchar",min:0,stackClearing:!0},null,null,null,{id:"hstemhm",min:2,stackClearing:!0,stem:!0},{id:"hintmask",min:0,stackClearing:!0},{id:"cntrmask",min:0,stackClearing:!0},{id:"rmoveto",min:2,stackClearing:!0},{id:"hmoveto",min:1,stackClearing:!0},{id:"vstemhm",min:2,stackClearing:!0,stem:!0},{id:"rcurveline",min:8,resetStack:!0},{id:"rlinecurve",min:8,resetStack:!0},{id:"vvcurveto",min:4,resetStack:!0},{id:"hhcurveto",min:4,resetStack:!0},null,{id:"callgsubr",min:1,undefStack:!0},{id:"vhcurveto",min:4,resetStack:!0},{id:"hvcurveto",min:4,resetStack:!0}],fi=[null,null,null,{id:"and",min:2,stackDelta:-1},{id:"or",min:2,stackDelta:-1},{id:"not",min:1,stackDelta:0},null,null,null,{id:"abs",min:1,stackDelta:0},{id:"add",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]+e[t-1]}},{id:"sub",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]-e[t-1]}},{id:"div",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]/e[t-1]}},null,{id:"neg",min:1,stackDelta:0,stackFn(e,t){e[t-1]=-e[t-1]}},{id:"eq",min:2,stackDelta:-1},null,null,{id:"drop",min:1,stackDelta:-1},null,{id:"put",min:2,stackDelta:-2},{id:"get",min:1,stackDelta:0},{id:"ifelse",min:4,stackDelta:-3},{id:"random",min:0,stackDelta:1},{id:"mul",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]*e[t-1]}},null,{id:"sqrt",min:1,stackDelta:0},{id:"dup",min:1,stackDelta:1},{id:"exch",min:2,stackDelta:0},{id:"index",min:2,stackDelta:0},{id:"roll",min:3,stackDelta:-2},null,null,null,{id:"hflex",min:7,resetStack:!0},{id:"flex",min:13,resetStack:!0},{id:"hflex1",min:9,resetStack:!0},{id:"flex1",min:11,resetStack:!0}];class CFFParser{constructor(e,t,i){this.bytes=e.getBytes();this.properties=t;this.seacAnalysisEnabled=!!i}parse(){const e=this.properties,t=new CFF;this.cff=t;const i=this.parseHeader(),a=this.parseIndex(i.endPos),s=this.parseIndex(a.endPos),r=this.parseIndex(s.endPos),n=this.parseIndex(r.endPos),g=this.parseDict(s.obj.get(0)),o=this.createDict(CFFTopDict,g,t.strings);t.header=i.obj;t.names=this.parseNameIndex(a.obj);t.strings=this.parseStringIndex(r.obj);t.topDict=o;t.globalSubrIndex=n.obj;this.parsePrivateDict(t.topDict);t.isCIDFont=o.hasName("ROS");const c=o.getByName("CharStrings"),C=this.parseIndex(c).obj,h=o.getByName("FontMatrix");h&&(e.fontMatrix=h);const l=o.getByName("FontBBox");if(l){e.ascent=Math.max(l[3],l[1]);e.descent=Math.min(l[1],l[3]);e.ascentScaled=!0}let Q,E;if(t.isCIDFont){const e=this.parseIndex(o.getByName("FDArray")).obj;for(let i=0,a=e.count;i=t)throw new FormatError("Invalid CFF header");if(0!==i){info("cff data is shifted");e=e.subarray(i);this.bytes=e}const a=e[0],s=e[1],r=e[2],n=e[3];return{obj:new CFFHeader(a,s,r,n),endPos:r}}parseDict(e){let t=0;function parseOperand(){let i=e[t++];if(30===i)return function parseFloatOperand(){let i="";const a=15,s=["0","1","2","3","4","5","6","7","8","9",".","E","E-",null,"-"],r=e.length;for(;t>4,g=15&r;if(n===a)break;i+=s[n];if(g===a)break;i+=s[g]}return parseFloat(i)}();if(28===i){i=e[t++];i=(i<<24|e[t++]<<16)>>16;return i}if(29===i){i=e[t++];i=i<<8|e[t++];i=i<<8|e[t++];i=i<<8|e[t++];return i}if(i>=32&&i<=246)return i-139;if(i>=247&&i<=250)return 256*(i-247)+e[t++]+108;if(i>=251&&i<=254)return-256*(i-251)-e[t++]-108;warn('CFFParser_parseDict: "'+i+'" is a reserved command.');return NaN}let i=[];const a=[];t=0;const s=e.length;for(;t10)return!1;let s=e.stackSize;const r=e.stack;let n=t.length;for(let g=0;g>16;g+=2;s++}else if(14===o){if(s>=4){s-=4;if(this.seacAnalysisEnabled){e.seac=r.slice(s,s+4);return!1}}c=di[o]}else if(o>=32&&o<=246){r[s]=o-139;s++}else if(o>=247&&o<=254){r[s]=o<251?(o-247<<8)+t[g]+108:-(o-251<<8)-t[g]-108;g++;s++}else if(255===o){r[s]=(t[g]<<24|t[g+1]<<16|t[g+2]<<8|t[g+3])/65536;g+=4;s++}else if(19===o||20===o){e.hints+=s>>1;if(0===e.hints){t.copyWithin(g-1,g,-1);g-=1;n-=1;continue}g+=e.hints+7>>3;s%=2;c=di[o]}else{if(10===o||29===o){const t=10===o?i:a;if(!t){c=di[o];warn("Missing subrsIndex for "+c.id);return!1}let n=32768;t.count<1240?n=107:t.count<33900&&(n=1131);const g=r[--s]+n;if(g<0||g>=t.count||isNaN(g)){c=di[o];warn("Out of bounds subrIndex for "+c.id);return!1}e.stackSize=s;e.callDepth++;if(!this.parseCharString(e,t.get(g),i,a))return!1;e.callDepth--;s=e.stackSize;continue}if(11===o){e.stackSize=s;return!0}if(0===o&&g===t.length){t[g-1]=14;c=di[14]}else{if(9===o){t.copyWithin(g-1,g,-1);g-=1;n-=1;continue}c=di[o]}}if(c){if(c.stem){e.hints+=s>>1;if(3===o||23===o)e.hasVStems=!0;else if(e.hasVStems&&(1===o||18===o)){warn("CFF stem hints are in wrong order");t[g-1]=1===o?3:23}}if("min"in c&&!e.undefStack&&s=2&&c.stem?s%=2:s>1&&warn("Found too many parameters for stack-clearing command");s>0&&(e.width=r[s-1])}if("stackDelta"in c){"stackFn"in c&&c.stackFn(r,s);s+=c.stackDelta}else if(c.stackClearing)s=0;else if(c.resetStack){s=0;e.undefStack=!1}else if(c.undefStack){s=0;e.undefStack=!0;e.firstStackClearing=!1}}}n=s.length){warn("Invalid fd index for glyph index.");h=!1}if(h){Q=s[e].privateDict;l=Q.subrsIndex}}else t&&(l=t);h&&(h=this.parseCharString(C,o,l,i));if(null!==C.width){const e=Q.getByName("nominalWidthX");g[c]=e+C.width}else{const e=Q.getByName("defaultWidthX");g[c]=e}null!==C.seac&&(n[c]=C.seac);h||e.set(c,new Uint8Array([14]))}return{charStrings:e,seacs:n,widths:g}}emptyPrivateDictionary(e){const t=this.createDict(CFFPrivateDict,[],e.strings);e.setByKey(18,[0,0]);e.privateDict=t}parsePrivateDict(e){if(!e.hasName("Private")){this.emptyPrivateDictionary(e);return}const t=e.getByName("Private");if(!Array.isArray(t)||2!==t.length){e.removeByName("Private");return}const i=t[0],a=t[1];if(0===i||a>=this.bytes.length){this.emptyPrivateDictionary(e);return}const s=a+i,r=this.bytes.subarray(a,s),n=this.parseDict(r),g=this.createDict(CFFPrivateDict,n,e.strings);e.privateDict=g;0===g.getByName("ExpansionFactor")&&g.setByName("ExpansionFactor",.06);if(!g.getByName("Subrs"))return;const o=g.getByName("Subrs"),c=a+o;if(0===o||c>=this.bytes.length){this.emptyPrivateDictionary(e);return}const C=this.parseIndex(c);g.subrsIndex=C.obj}parseCharsets(e,t,i,a){if(0===e)return new CFFCharset(!0,yi.ISO_ADOBE,ni);if(1===e)return new CFFCharset(!0,yi.EXPERT,gi);if(2===e)return new CFFCharset(!0,yi.EXPERT_SUBSET,oi);const s=this.bytes,r=e,n=s[e++],g=[a?0:".notdef"];let o,c,C;t-=1;switch(n){case 0:for(C=0;C=65535){warn("Not enough space in charstrings to duplicate first glyph.");return}const e=this.charStrings.get(0);this.charStrings.add(e);this.isCIDFont&&this.fdSelect.fdSelect.push(this.fdSelect.fdSelect[0])}hasGlyphId(e){if(e<0||e>=this.charStrings.count)return!1;return this.charStrings.get(e).length>0}}class CFFHeader{constructor(e,t,i,a){this.major=e;this.minor=t;this.hdrSize=i;this.offSize=a}}class CFFStrings{constructor(){this.strings=[]}get(e){return e>=0&&e<=390?Ei[e]:e-ui<=this.strings.length?this.strings[e-ui]:Ei[0]}getSID(e){let t=Ei.indexOf(e);if(-1!==t)return t;t=this.strings.indexOf(e);return-1!==t?t+ui:-1}add(e){this.strings.push(e)}get count(){return this.strings.length}}class CFFIndex{constructor(){this.objects=[];this.length=0}add(e){this.length+=e.length;this.objects.push(e)}set(e,t){this.length+=t.length-this.objects[e].length;this.objects[e]=t}get(e){return this.objects[e]}get count(){return this.objects.length}}class CFFDict{constructor(e,t){this.keyToNameMap=e.keyToNameMap;this.nameToKeyMap=e.nameToKeyMap;this.defaults=e.defaults;this.types=e.types;this.opcodes=e.opcodes;this.order=e.order;this.strings=t;this.values=Object.create(null)}setByKey(e,t){if(!(e in this.keyToNameMap))return!1;if(0===t.length)return!0;for(const i of t)if(isNaN(i)){warn(`Invalid CFFDict value: "${t}" for key "${e}".`);return!0}const i=this.types[e];"num"!==i&&"sid"!==i&&"offset"!==i||(t=t[0]);this.values[e]=t;return!0}setByName(e,t){if(!(e in this.nameToKeyMap))throw new FormatError(`Invalid dictionary name "${e}"`);this.values[this.nameToKeyMap[e]]=t}hasName(e){return this.nameToKeyMap[e]in this.values}getByName(e){if(!(e in this.nameToKeyMap))throw new FormatError(`Invalid dictionary name ${e}"`);const t=this.nameToKeyMap[e];return t in this.values?this.values[t]:this.defaults[t]}removeByName(e){delete this.values[this.nameToKeyMap[e]]}static createTables(e){const t={keyToNameMap:{},nameToKeyMap:{},defaults:{},types:{},opcodes:{},order:[]};for(const i of e){const e=Array.isArray(i[0])?(i[0][0]<<8)+i[0][1]:i[0];t.keyToNameMap[e]=i[1];t.nameToKeyMap[i[1]]=e;t.types[e]=i[2];t.defaults[e]=i[3];t.opcodes[e]=Array.isArray(i[0])?i[0]:[i[0]];t.order.push(e)}return t}}const pi=[[[12,30],"ROS",["sid","sid","num"],null],[[12,20],"SyntheticBase","num",null],[0,"version","sid",null],[1,"Notice","sid",null],[[12,0],"Copyright","sid",null],[2,"FullName","sid",null],[3,"FamilyName","sid",null],[4,"Weight","sid",null],[[12,1],"isFixedPitch","num",0],[[12,2],"ItalicAngle","num",0],[[12,3],"UnderlinePosition","num",-100],[[12,4],"UnderlineThickness","num",50],[[12,5],"PaintType","num",0],[[12,6],"CharstringType","num",2],[[12,7],"FontMatrix",["num","num","num","num","num","num"],[.001,0,0,.001,0,0]],[13,"UniqueID","num",null],[5,"FontBBox",["num","num","num","num"],[0,0,0,0]],[[12,8],"StrokeWidth","num",0],[14,"XUID","array",null],[15,"charset","offset",0],[16,"Encoding","offset",0],[17,"CharStrings","offset",0],[18,"Private",["offset","offset"],null],[[12,21],"PostScript","sid",null],[[12,22],"BaseFontName","sid",null],[[12,23],"BaseFontBlend","delta",null],[[12,31],"CIDFontVersion","num",0],[[12,32],"CIDFontRevision","num",0],[[12,33],"CIDFontType","num",0],[[12,34],"CIDCount","num",8720],[[12,35],"UIDBase","num",null],[[12,37],"FDSelect","offset",null],[[12,36],"FDArray","offset",null],[[12,38],"FontName","sid",null]];class CFFTopDict extends CFFDict{static get tables(){return shadow(this,"tables",this.createTables(pi))}constructor(e){super(CFFTopDict.tables,e);this.privateDict=null}}const mi=[[6,"BlueValues","delta",null],[7,"OtherBlues","delta",null],[8,"FamilyBlues","delta",null],[9,"FamilyOtherBlues","delta",null],[[12,9],"BlueScale","num",.039625],[[12,10],"BlueShift","num",7],[[12,11],"BlueFuzz","num",1],[10,"StdHW","num",null],[11,"StdVW","num",null],[[12,12],"StemSnapH","delta",null],[[12,13],"StemSnapV","delta",null],[[12,14],"ForceBold","num",0],[[12,17],"LanguageGroup","num",0],[[12,18],"ExpansionFactor","num",.06],[[12,19],"initialRandomSeed","num",0],[20,"defaultWidthX","num",0],[21,"nominalWidthX","num",0],[19,"Subrs","offset",null]];class CFFPrivateDict extends CFFDict{static get tables(){return shadow(this,"tables",this.createTables(mi))}constructor(e){super(CFFPrivateDict.tables,e);this.subrsIndex=null}}const yi={ISO_ADOBE:0,EXPERT:1,EXPERT_SUBSET:2};class CFFCharset{constructor(e,t,i,a){this.predefined=e;this.format=t;this.charset=i;this.raw=a}}class CFFEncoding{constructor(e,t,i,a){this.predefined=e;this.format=t;this.encoding=i;this.raw=a}}class CFFFDSelect{constructor(e,t){this.format=e;this.fdSelect=t}getFDIndex(e){return e<0||e>=this.fdSelect.length?-1:this.fdSelect[e]}}class CFFOffsetTracker{constructor(){this.offsets=Object.create(null)}isTracking(e){return e in this.offsets}track(e,t){if(e in this.offsets)throw new FormatError(`Already tracking location of ${e}`);this.offsets[e]=t}offset(e){for(const t in this.offsets)this.offsets[t]+=e}setEntryLocation(e,t,i){if(!(e in this.offsets))throw new FormatError(`Not tracking location of ${e}`);const a=i.data,s=this.offsets[e];for(let e=0,i=t.length;e>24&255;a[n]=c>>16&255;a[g]=c>>8&255;a[o]=255&c}}}class CFFCompiler{constructor(e){this.cff=e}compile(){const e=this.cff,t={data:[],length:0,add(e){try{this.data.push(...e)}catch{this.data=this.data.concat(e)}this.length=this.data.length}},i=this.compileHeader(e.header);t.add(i);const a=this.compileNameIndex(e.names);t.add(a);if(e.isCIDFont&&e.topDict.hasName("FontMatrix")){const t=e.topDict.getByName("FontMatrix");e.topDict.removeByName("FontMatrix");for(const i of e.fdArray){let e=t.slice(0);i.hasName("FontMatrix")&&(e=Util.transform(e,i.getByName("FontMatrix")));i.setByName("FontMatrix",e)}}const s=e.topDict.getByName("XUID");s?.length>16&&e.topDict.removeByName("XUID");e.topDict.setByName("charset",0);let r=this.compileTopDicts([e.topDict],t.length,e.isCIDFont);t.add(r.output);const n=r.trackers[0],g=this.compileStringIndex(e.strings.strings);t.add(g);const o=this.compileIndex(e.globalSubrIndex);t.add(o);if(e.encoding&&e.topDict.hasName("Encoding"))if(e.encoding.predefined)n.setEntryLocation("Encoding",[e.encoding.format],t);else{const i=this.compileEncoding(e.encoding);n.setEntryLocation("Encoding",[t.length],t);t.add(i)}const c=this.compileCharset(e.charset,e.charStrings.count,e.strings,e.isCIDFont);n.setEntryLocation("charset",[t.length],t);t.add(c);const C=this.compileCharStrings(e.charStrings);n.setEntryLocation("CharStrings",[t.length],t);t.add(C);if(e.isCIDFont){n.setEntryLocation("FDSelect",[t.length],t);const i=this.compileFDSelect(e.fdSelect);t.add(i);r=this.compileTopDicts(e.fdArray,t.length,!0);n.setEntryLocation("FDArray",[t.length],t);t.add(r.output);const a=r.trackers;this.compilePrivateDicts(e.fdArray,a,t)}this.compilePrivateDicts([e.topDict],[n],t);t.add([0]);return t.data}encodeNumber(e){return Number.isInteger(e)?this.encodeInteger(e):this.encodeFloat(e)}static get EncodeFloatRegExp(){return shadow(this,"EncodeFloatRegExp",/\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/)}encodeFloat(e){let t=e.toString();const i=CFFCompiler.EncodeFloatRegExp.exec(t);if(i){const a=parseFloat("1e"+((i[2]?+i[2]:0)+i[1].length));t=(Math.round(e*a)/a).toString()}let a,s,r="";for(a=0,s=t.length;a=-107&&e<=107?[e+139]:e>=108&&e<=1131?[247+((e-=108)>>8),255&e]:e>=-1131&&e<=-108?[251+((e=-e-108)>>8),255&e]:e>=-32768&&e<=32767?[28,e>>8&255,255&e]:[29,e>>24&255,e>>16&255,e>>8&255,255&e];return t}compileHeader(e){return[e.major,e.minor,4,e.offSize]}compileNameIndex(e){const t=new CFFIndex;for(const i of e){const e=Math.min(i.length,127);let a=new Array(e);for(let t=0;t"~"||"["===e||"]"===e||"("===e||")"===e||"{"===e||"}"===e||"<"===e||">"===e||"/"===e||"%"===e)&&(e="_");a[t]=e}a=a.join("");""===a&&(a="Bad_Font_Name");t.add(stringToBytes(a))}return this.compileIndex(t)}compileTopDicts(e,t,i){const a=[];let s=new CFFIndex;for(const r of e){if(i){r.removeByName("CIDFontVersion");r.removeByName("CIDFontRevision");r.removeByName("CIDFontType");r.removeByName("CIDCount");r.removeByName("UIDBase")}const e=new CFFOffsetTracker,n=this.compileDict(r,e);a.push(e);s.add(n);e.offset(t)}s=this.compileIndex(s,a);return{trackers:a,output:s}}compilePrivateDicts(e,t,i){for(let a=0,s=e.length;a>8&255,255&r]);else{s=new Uint8Array(1+2*r);s[0]=0;let t=0;const a=e.charset.length;let n=!1;for(let r=1;r>8&255;s[r+1]=255&g}}return this.compileTypedArray(s)}compileEncoding(e){return this.compileTypedArray(e.raw)}compileFDSelect(e){const t=e.format;let i,a;switch(t){case 0:i=new Uint8Array(1+e.fdSelect.length);i[0]=t;for(a=0;a>8&255,255&s,r];for(a=1;a>8&255,255&a,t);r=t}}const g=(n.length-3)/3;n[1]=g>>8&255;n[2]=255&g;n.push(a>>8&255,255&a);i=new Uint8Array(n)}return this.compileTypedArray(i)}compileTypedArray(e){return Array.from(e)}compileIndex(e,t=[]){const i=e.objects,a=i.length;if(0===a)return[0,0];const s=[a>>8&255,255&a];let r,n,g=1;for(r=0;r>8&255,255&o):3===n?s.push(o>>16&255,o>>8&255,255&o):s.push(o>>>24&255,o>>16&255,o>>8&255,255&o);i[r]&&(o+=i[r].length)}for(r=0;r=5&&t<=7))return-1;a=e.substring(1)}if(a===a.toUpperCase()){i=parseInt(a,16);if(i>=0)return i}}return-1}const Fi=[[0,127],[128,255],[256,383],[384,591],[592,687,7424,7551,7552,7615],[688,767,42752,42783],[768,879,7616,7679],[880,1023],[11392,11519],[1024,1279,1280,1327,11744,11775,42560,42655],[1328,1423],[1424,1535],[42240,42559],[1536,1791,1872,1919],[1984,2047],[2304,2431],[2432,2559],[2560,2687],[2688,2815],[2816,2943],[2944,3071],[3072,3199],[3200,3327],[3328,3455],[3584,3711],[3712,3839],[4256,4351,11520,11567],[6912,7039],[4352,4607],[7680,7935,11360,11391,42784,43007],[7936,8191],[8192,8303,11776,11903],[8304,8351],[8352,8399],[8400,8447],[8448,8527],[8528,8591],[8592,8703,10224,10239,10496,10623,11008,11263],[8704,8959,10752,11007,10176,10223,10624,10751],[8960,9215],[9216,9279],[9280,9311],[9312,9471],[9472,9599],[9600,9631],[9632,9727],[9728,9983],[9984,10175],[12288,12351],[12352,12447],[12448,12543,12784,12799],[12544,12591,12704,12735],[12592,12687],[43072,43135],[12800,13055],[13056,13311],[44032,55215],[55296,57343],[67840,67871],[19968,40959,11904,12031,12032,12255,12272,12287,13312,19903,131072,173791,12688,12703],[57344,63743],[12736,12783,63744,64255,194560,195103],[64256,64335],[64336,65023],[65056,65071],[65040,65055],[65104,65135],[65136,65279],[65280,65519],[65520,65535],[3840,4095],[1792,1871],[1920,1983],[3456,3583],[4096,4255],[4608,4991,4992,5023,11648,11743],[5024,5119],[5120,5759],[5760,5791],[5792,5887],[6016,6143],[6144,6319],[10240,10495],[40960,42127],[5888,5919,5920,5951,5952,5983,5984,6015],[66304,66351],[66352,66383],[66560,66639],[118784,119039,119040,119295,119296,119375],[119808,120831],[1044480,1048573],[65024,65039,917760,917999],[917504,917631],[6400,6479],[6480,6527],[6528,6623],[6656,6687],[11264,11359],[11568,11647],[19904,19967],[43008,43055],[65536,65663,65664,65791,65792,65855],[65856,65935],[66432,66463],[66464,66527],[66640,66687],[66688,66735],[67584,67647],[68096,68191],[119552,119647],[73728,74751,74752,74879],[119648,119679],[7040,7103],[7168,7247],[7248,7295],[43136,43231],[43264,43311],[43312,43359],[43520,43615],[65936,65999],[66e3,66047],[66208,66271,66176,66207,67872,67903],[127024,127135,126976,127023]];function getUnicodeRangeFor(e,t=-1){if(-1!==t){const i=Fi[t];for(let a=0,s=i.length;a=i[a]&&e<=i[a+1])return t}for(let t=0,i=Fi.length;t=i[a]&&e<=i[a+1])return t}return-1}const Si=new RegExp("^(\\s)|(\\p{Mn})|(\\p{Cf})$","u"),ki=new Map;const Ri=!0,Ni=1,Gi=2,Mi=4,xi=32,Hi=[".notdef",".null","nonmarkingreturn","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","Adieresis","Aring","Ccedilla","Eacute","Ntilde","Odieresis","Udieresis","aacute","agrave","acircumflex","adieresis","atilde","aring","ccedilla","eacute","egrave","ecircumflex","edieresis","iacute","igrave","icircumflex","idieresis","ntilde","oacute","ograve","ocircumflex","odieresis","otilde","uacute","ugrave","ucircumflex","udieresis","dagger","degree","cent","sterling","section","bullet","paragraph","germandbls","registered","copyright","trademark","acute","dieresis","notequal","AE","Oslash","infinity","plusminus","lessequal","greaterequal","yen","mu","partialdiff","summation","product","pi","integral","ordfeminine","ordmasculine","Omega","ae","oslash","questiondown","exclamdown","logicalnot","radical","florin","approxequal","Delta","guillemotleft","guillemotright","ellipsis","nonbreakingspace","Agrave","Atilde","Otilde","OE","oe","endash","emdash","quotedblleft","quotedblright","quoteleft","quoteright","divide","lozenge","ydieresis","Ydieresis","fraction","currency","guilsinglleft","guilsinglright","fi","fl","daggerdbl","periodcentered","quotesinglbase","quotedblbase","perthousand","Acircumflex","Ecircumflex","Aacute","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Oacute","Ocircumflex","apple","Ograve","Uacute","Ucircumflex","Ugrave","dotlessi","circumflex","tilde","macron","breve","dotaccent","ring","cedilla","hungarumlaut","ogonek","caron","Lslash","lslash","Scaron","scaron","Zcaron","zcaron","brokenbar","Eth","eth","Yacute","yacute","Thorn","thorn","minus","multiply","onesuperior","twosuperior","threesuperior","onehalf","onequarter","threequarters","franc","Gbreve","gbreve","Idotaccent","Scedilla","scedilla","Cacute","cacute","Ccaron","ccaron","dcroat"];function recoverGlyphName(e,t){if(void 0!==t[e])return e;const i=getUnicodeForGlyph(e,t);if(-1!==i)for(const e in t)if(t[e]===i)return e;info("Unable to recover a standard glyph name for: "+e);return e}function type1FontGlyphMapping(e,t,i){const a=Object.create(null);let s,r,n;const g=!!(e.flags&Mi);if(e.isInternalFont){n=t;for(r=0;r=0?s:0}}else if(e.baseEncodingName){n=getEncoding(e.baseEncodingName);for(r=0;r=0?s:0}}else if(g)for(r in t)a[r]=t[r];else{n=hi;for(r=0;r=0?s:0}}const o=e.differences;let c;if(o)for(r in o){const e=o[r];s=i.indexOf(e);if(-1===s){c||(c=wi());const t=recoverGlyphName(e,c);t!==e&&(s=i.indexOf(t))}a[r]=s>=0?s:0}return a}function normalizeFontName(e){return e.replaceAll(/[,_]/g,"-").replaceAll(/\s/g,"")}const Ji=getLookupTableFactory((e=>{e[8211]=65074;e[8212]=65073;e[8229]=65072;e[8230]=65049;e[12289]=65041;e[12290]=65042;e[12296]=65087;e[12297]=65088;e[12298]=65085;e[12299]=65086;e[12300]=65089;e[12301]=65090;e[12302]=65091;e[12303]=65092;e[12304]=65083;e[12305]=65084;e[12308]=65081;e[12309]=65082;e[12310]=65047;e[12311]=65048;e[65103]=65076;e[65281]=65045;e[65288]=65077;e[65289]=65078;e[65292]=65040;e[65306]=65043;e[65307]=65044;e[65311]=65046;e[65339]=65095;e[65341]=65096;e[65343]=65075;e[65371]=65079;e[65373]=65080})),Yi=getLookupTableFactory((function(e){e["Times-Roman"]="Times-Roman";e.Helvetica="Helvetica";e.Courier="Courier";e.Symbol="Symbol";e["Times-Bold"]="Times-Bold";e["Helvetica-Bold"]="Helvetica-Bold";e["Courier-Bold"]="Courier-Bold";e.ZapfDingbats="ZapfDingbats";e["Times-Italic"]="Times-Italic";e["Helvetica-Oblique"]="Helvetica-Oblique";e["Courier-Oblique"]="Courier-Oblique";e["Times-BoldItalic"]="Times-BoldItalic";e["Helvetica-BoldOblique"]="Helvetica-BoldOblique";e["Courier-BoldOblique"]="Courier-BoldOblique";e.ArialNarrow="Helvetica";e["ArialNarrow-Bold"]="Helvetica-Bold";e["ArialNarrow-BoldItalic"]="Helvetica-BoldOblique";e["ArialNarrow-Italic"]="Helvetica-Oblique";e.ArialBlack="Helvetica";e["ArialBlack-Bold"]="Helvetica-Bold";e["ArialBlack-BoldItalic"]="Helvetica-BoldOblique";e["ArialBlack-Italic"]="Helvetica-Oblique";e["Arial-Black"]="Helvetica";e["Arial-Black-Bold"]="Helvetica-Bold";e["Arial-Black-BoldItalic"]="Helvetica-BoldOblique";e["Arial-Black-Italic"]="Helvetica-Oblique";e.Arial="Helvetica";e["Arial-Bold"]="Helvetica-Bold";e["Arial-BoldItalic"]="Helvetica-BoldOblique";e["Arial-Italic"]="Helvetica-Oblique";e.ArialMT="Helvetica";e["Arial-BoldItalicMT"]="Helvetica-BoldOblique";e["Arial-BoldMT"]="Helvetica-Bold";e["Arial-ItalicMT"]="Helvetica-Oblique";e["Arial-BoldItalicMT-BoldItalic"]="Helvetica-BoldOblique";e["Arial-BoldMT-Bold"]="Helvetica-Bold";e["Arial-ItalicMT-Italic"]="Helvetica-Oblique";e.ArialUnicodeMS="Helvetica";e["ArialUnicodeMS-Bold"]="Helvetica-Bold";e["ArialUnicodeMS-BoldItalic"]="Helvetica-BoldOblique";e["ArialUnicodeMS-Italic"]="Helvetica-Oblique";e["Courier-BoldItalic"]="Courier-BoldOblique";e["Courier-Italic"]="Courier-Oblique";e.CourierNew="Courier";e["CourierNew-Bold"]="Courier-Bold";e["CourierNew-BoldItalic"]="Courier-BoldOblique";e["CourierNew-Italic"]="Courier-Oblique";e["CourierNewPS-BoldItalicMT"]="Courier-BoldOblique";e["CourierNewPS-BoldMT"]="Courier-Bold";e["CourierNewPS-ItalicMT"]="Courier-Oblique";e.CourierNewPSMT="Courier";e["Helvetica-BoldItalic"]="Helvetica-BoldOblique";e["Helvetica-Italic"]="Helvetica-Oblique";e["HelveticaLTStd-Bold"]="Helvetica-Bold";e["Symbol-Bold"]="Symbol";e["Symbol-BoldItalic"]="Symbol";e["Symbol-Italic"]="Symbol";e.TimesNewRoman="Times-Roman";e["TimesNewRoman-Bold"]="Times-Bold";e["TimesNewRoman-BoldItalic"]="Times-BoldItalic";e["TimesNewRoman-Italic"]="Times-Italic";e.TimesNewRomanPS="Times-Roman";e["TimesNewRomanPS-Bold"]="Times-Bold";e["TimesNewRomanPS-BoldItalic"]="Times-BoldItalic";e["TimesNewRomanPS-BoldItalicMT"]="Times-BoldItalic";e["TimesNewRomanPS-BoldMT"]="Times-Bold";e["TimesNewRomanPS-Italic"]="Times-Italic";e["TimesNewRomanPS-ItalicMT"]="Times-Italic";e.TimesNewRomanPSMT="Times-Roman";e["TimesNewRomanPSMT-Bold"]="Times-Bold";e["TimesNewRomanPSMT-BoldItalic"]="Times-BoldItalic";e["TimesNewRomanPSMT-Italic"]="Times-Italic"})),vi=getLookupTableFactory((function(e){e.Courier="FoxitFixed.pfb";e["Courier-Bold"]="FoxitFixedBold.pfb";e["Courier-BoldOblique"]="FoxitFixedBoldItalic.pfb";e["Courier-Oblique"]="FoxitFixedItalic.pfb";e.Helvetica="LiberationSans-Regular.ttf";e["Helvetica-Bold"]="LiberationSans-Bold.ttf";e["Helvetica-BoldOblique"]="LiberationSans-BoldItalic.ttf";e["Helvetica-Oblique"]="LiberationSans-Italic.ttf";e["Times-Roman"]="FoxitSerif.pfb";e["Times-Bold"]="FoxitSerifBold.pfb";e["Times-BoldItalic"]="FoxitSerifBoldItalic.pfb";e["Times-Italic"]="FoxitSerifItalic.pfb";e.Symbol="FoxitSymbol.pfb";e.ZapfDingbats="FoxitDingbats.pfb";e["LiberationSans-Regular"]="LiberationSans-Regular.ttf";e["LiberationSans-Bold"]="LiberationSans-Bold.ttf";e["LiberationSans-Italic"]="LiberationSans-Italic.ttf";e["LiberationSans-BoldItalic"]="LiberationSans-BoldItalic.ttf"})),Ki=getLookupTableFactory((function(e){e.Calibri="Helvetica";e["Calibri-Bold"]="Helvetica-Bold";e["Calibri-BoldItalic"]="Helvetica-BoldOblique";e["Calibri-Italic"]="Helvetica-Oblique";e.CenturyGothic="Helvetica";e["CenturyGothic-Bold"]="Helvetica-Bold";e["CenturyGothic-BoldItalic"]="Helvetica-BoldOblique";e["CenturyGothic-Italic"]="Helvetica-Oblique";e.ComicSansMS="Comic Sans MS";e["ComicSansMS-Bold"]="Comic Sans MS-Bold";e["ComicSansMS-BoldItalic"]="Comic Sans MS-BoldItalic";e["ComicSansMS-Italic"]="Comic Sans MS-Italic";e.GillSansMT="Helvetica";e["GillSansMT-Bold"]="Helvetica-Bold";e["GillSansMT-BoldItalic"]="Helvetica-BoldOblique";e["GillSansMT-Italic"]="Helvetica-Oblique";e.Impact="Helvetica";e["ItcSymbol-Bold"]="Helvetica-Bold";e["ItcSymbol-BoldItalic"]="Helvetica-BoldOblique";e["ItcSymbol-Book"]="Helvetica";e["ItcSymbol-BookItalic"]="Helvetica-Oblique";e["ItcSymbol-Medium"]="Helvetica";e["ItcSymbol-MediumItalic"]="Helvetica-Oblique";e.LucidaConsole="Courier";e["LucidaConsole-Bold"]="Courier-Bold";e["LucidaConsole-BoldItalic"]="Courier-BoldOblique";e["LucidaConsole-Italic"]="Courier-Oblique";e["LucidaSans-Demi"]="Helvetica-Bold";e["MS-Gothic"]="MS Gothic";e["MS-Gothic-Bold"]="MS Gothic-Bold";e["MS-Gothic-BoldItalic"]="MS Gothic-BoldItalic";e["MS-Gothic-Italic"]="MS Gothic-Italic";e["MS-Mincho"]="MS Mincho";e["MS-Mincho-Bold"]="MS Mincho-Bold";e["MS-Mincho-BoldItalic"]="MS Mincho-BoldItalic";e["MS-Mincho-Italic"]="MS Mincho-Italic";e["MS-PGothic"]="MS PGothic";e["MS-PGothic-Bold"]="MS PGothic-Bold";e["MS-PGothic-BoldItalic"]="MS PGothic-BoldItalic";e["MS-PGothic-Italic"]="MS PGothic-Italic";e["MS-PMincho"]="MS PMincho";e["MS-PMincho-Bold"]="MS PMincho-Bold";e["MS-PMincho-BoldItalic"]="MS PMincho-BoldItalic";e["MS-PMincho-Italic"]="MS PMincho-Italic";e.NuptialScript="Times-Italic";e.SegoeUISymbol="Helvetica"})),Ti=getLookupTableFactory((function(e){e["Adobe Jenson"]=!0;e["Adobe Text"]=!0;e.Albertus=!0;e.Aldus=!0;e.Alexandria=!0;e.Algerian=!0;e["American Typewriter"]=!0;e.Antiqua=!0;e.Apex=!0;e.Arno=!0;e.Aster=!0;e.Aurora=!0;e.Baskerville=!0;e.Bell=!0;e.Bembo=!0;e["Bembo Schoolbook"]=!0;e.Benguiat=!0;e["Berkeley Old Style"]=!0;e["Bernhard Modern"]=!0;e["Berthold City"]=!0;e.Bodoni=!0;e["Bauer Bodoni"]=!0;e["Book Antiqua"]=!0;e.Bookman=!0;e["Bordeaux Roman"]=!0;e["Californian FB"]=!0;e.Calisto=!0;e.Calvert=!0;e.Capitals=!0;e.Cambria=!0;e.Cartier=!0;e.Caslon=!0;e.Catull=!0;e.Centaur=!0;e["Century Old Style"]=!0;e["Century Schoolbook"]=!0;e.Chaparral=!0;e["Charis SIL"]=!0;e.Cheltenham=!0;e["Cholla Slab"]=!0;e.Clarendon=!0;e.Clearface=!0;e.Cochin=!0;e.Colonna=!0;e["Computer Modern"]=!0;e["Concrete Roman"]=!0;e.Constantia=!0;e["Cooper Black"]=!0;e.Corona=!0;e.Ecotype=!0;e.Egyptienne=!0;e.Elephant=!0;e.Excelsior=!0;e.Fairfield=!0;e["FF Scala"]=!0;e.Folkard=!0;e.Footlight=!0;e.FreeSerif=!0;e["Friz Quadrata"]=!0;e.Garamond=!0;e.Gentium=!0;e.Georgia=!0;e.Gloucester=!0;e["Goudy Old Style"]=!0;e["Goudy Schoolbook"]=!0;e["Goudy Pro Font"]=!0;e.Granjon=!0;e["Guardian Egyptian"]=!0;e.Heather=!0;e.Hercules=!0;e["High Tower Text"]=!0;e.Hiroshige=!0;e["Hoefler Text"]=!0;e["Humana Serif"]=!0;e.Imprint=!0;e["Ionic No. 5"]=!0;e.Janson=!0;e.Joanna=!0;e.Korinna=!0;e.Lexicon=!0;e.LiberationSerif=!0;e["Liberation Serif"]=!0;e["Linux Libertine"]=!0;e.Literaturnaya=!0;e.Lucida=!0;e["Lucida Bright"]=!0;e.Melior=!0;e.Memphis=!0;e.Miller=!0;e.Minion=!0;e.Modern=!0;e["Mona Lisa"]=!0;e["Mrs Eaves"]=!0;e["MS Serif"]=!0;e["Museo Slab"]=!0;e["New York"]=!0;e["Nimbus Roman"]=!0;e["NPS Rawlinson Roadway"]=!0;e.NuptialScript=!0;e.Palatino=!0;e.Perpetua=!0;e.Plantin=!0;e["Plantin Schoolbook"]=!0;e.Playbill=!0;e["Poor Richard"]=!0;e["Rawlinson Roadway"]=!0;e.Renault=!0;e.Requiem=!0;e.Rockwell=!0;e.Roman=!0;e["Rotis Serif"]=!0;e.Sabon=!0;e.Scala=!0;e.Seagull=!0;e.Sistina=!0;e.Souvenir=!0;e.STIX=!0;e["Stone Informal"]=!0;e["Stone Serif"]=!0;e.Sylfaen=!0;e.Times=!0;e.Trajan=!0;e["Trinité"]=!0;e["Trump Mediaeval"]=!0;e.Utopia=!0;e["Vale Type"]=!0;e["Bitstream Vera"]=!0;e["Vera Serif"]=!0;e.Versailles=!0;e.Wanted=!0;e.Weiss=!0;e["Wide Latin"]=!0;e.Windsor=!0;e.XITS=!0})),qi=getLookupTableFactory((function(e){e.Dingbats=!0;e.Symbol=!0;e.ZapfDingbats=!0;e.Wingdings=!0;e["Wingdings-Bold"]=!0;e["Wingdings-Regular"]=!0})),Oi=getLookupTableFactory((function(e){e[2]=10;e[3]=32;e[4]=33;e[5]=34;e[6]=35;e[7]=36;e[8]=37;e[9]=38;e[10]=39;e[11]=40;e[12]=41;e[13]=42;e[14]=43;e[15]=44;e[16]=45;e[17]=46;e[18]=47;e[19]=48;e[20]=49;e[21]=50;e[22]=51;e[23]=52;e[24]=53;e[25]=54;e[26]=55;e[27]=56;e[28]=57;e[29]=58;e[30]=894;e[31]=60;e[32]=61;e[33]=62;e[34]=63;e[35]=64;e[36]=65;e[37]=66;e[38]=67;e[39]=68;e[40]=69;e[41]=70;e[42]=71;e[43]=72;e[44]=73;e[45]=74;e[46]=75;e[47]=76;e[48]=77;e[49]=78;e[50]=79;e[51]=80;e[52]=81;e[53]=82;e[54]=83;e[55]=84;e[56]=85;e[57]=86;e[58]=87;e[59]=88;e[60]=89;e[61]=90;e[62]=91;e[63]=92;e[64]=93;e[65]=94;e[66]=95;e[67]=96;e[68]=97;e[69]=98;e[70]=99;e[71]=100;e[72]=101;e[73]=102;e[74]=103;e[75]=104;e[76]=105;e[77]=106;e[78]=107;e[79]=108;e[80]=109;e[81]=110;e[82]=111;e[83]=112;e[84]=113;e[85]=114;e[86]=115;e[87]=116;e[88]=117;e[89]=118;e[90]=119;e[91]=120;e[92]=121;e[93]=122;e[94]=123;e[95]=124;e[96]=125;e[97]=126;e[98]=196;e[99]=197;e[100]=199;e[101]=201;e[102]=209;e[103]=214;e[104]=220;e[105]=225;e[106]=224;e[107]=226;e[108]=228;e[109]=227;e[110]=229;e[111]=231;e[112]=233;e[113]=232;e[114]=234;e[115]=235;e[116]=237;e[117]=236;e[118]=238;e[119]=239;e[120]=241;e[121]=243;e[122]=242;e[123]=244;e[124]=246;e[125]=245;e[126]=250;e[127]=249;e[128]=251;e[129]=252;e[130]=8224;e[131]=176;e[132]=162;e[133]=163;e[134]=167;e[135]=8226;e[136]=182;e[137]=223;e[138]=174;e[139]=169;e[140]=8482;e[141]=180;e[142]=168;e[143]=8800;e[144]=198;e[145]=216;e[146]=8734;e[147]=177;e[148]=8804;e[149]=8805;e[150]=165;e[151]=181;e[152]=8706;e[153]=8721;e[154]=8719;e[156]=8747;e[157]=170;e[158]=186;e[159]=8486;e[160]=230;e[161]=248;e[162]=191;e[163]=161;e[164]=172;e[165]=8730;e[166]=402;e[167]=8776;e[168]=8710;e[169]=171;e[170]=187;e[171]=8230;e[179]=8220;e[180]=8221;e[181]=8216;e[182]=8217;e[200]=193;e[203]=205;e[207]=211;e[210]=218;e[223]=711;e[224]=321;e[225]=322;e[226]=352;e[227]=353;e[228]=381;e[229]=382;e[233]=221;e[234]=253;e[252]=263;e[253]=268;e[254]=269;e[258]=258;e[260]=260;e[261]=261;e[265]=280;e[266]=281;e[267]=282;e[268]=283;e[269]=313;e[275]=323;e[276]=324;e[278]=328;e[283]=344;e[284]=345;e[285]=346;e[286]=347;e[292]=367;e[295]=377;e[296]=378;e[298]=380;e[305]=963;e[306]=964;e[307]=966;e[308]=8215;e[309]=8252;e[310]=8319;e[311]=8359;e[312]=8592;e[313]=8593;e[337]=9552;e[493]=1039;e[494]=1040;e[672]=1488;e[673]=1489;e[674]=1490;e[675]=1491;e[676]=1492;e[677]=1493;e[678]=1494;e[679]=1495;e[680]=1496;e[681]=1497;e[682]=1498;e[683]=1499;e[684]=1500;e[685]=1501;e[686]=1502;e[687]=1503;e[688]=1504;e[689]=1505;e[690]=1506;e[691]=1507;e[692]=1508;e[693]=1509;e[694]=1510;e[695]=1511;e[696]=1512;e[697]=1513;e[698]=1514;e[705]=1524;e[706]=8362;e[710]=64288;e[711]=64298;e[759]=1617;e[761]=1776;e[763]=1778;e[775]=1652;e[777]=1764;e[778]=1780;e[779]=1781;e[780]=1782;e[782]=771;e[783]=64726;e[786]=8363;e[788]=8532;e[790]=768;e[791]=769;e[792]=768;e[795]=803;e[797]=64336;e[798]=64337;e[799]=64342;e[800]=64343;e[801]=64344;e[802]=64345;e[803]=64362;e[804]=64363;e[805]=64364;e[2424]=7821;e[2425]=7822;e[2426]=7823;e[2427]=7824;e[2428]=7825;e[2429]=7826;e[2430]=7827;e[2433]=7682;e[2678]=8045;e[2679]=8046;e[2830]=1552;e[2838]=686;e[2840]=751;e[2842]=753;e[2843]=754;e[2844]=755;e[2846]=757;e[2856]=767;e[2857]=848;e[2858]=849;e[2862]=853;e[2863]=854;e[2864]=855;e[2865]=861;e[2866]=862;e[2906]=7460;e[2908]=7462;e[2909]=7463;e[2910]=7464;e[2912]=7466;e[2913]=7467;e[2914]=7468;e[2916]=7470;e[2917]=7471;e[2918]=7472;e[2920]=7474;e[2921]=7475;e[2922]=7476;e[2924]=7478;e[2925]=7479;e[2926]=7480;e[2928]=7482;e[2929]=7483;e[2930]=7484;e[2932]=7486;e[2933]=7487;e[2934]=7488;e[2936]=7490;e[2937]=7491;e[2938]=7492;e[2940]=7494;e[2941]=7495;e[2942]=7496;e[2944]=7498;e[2946]=7500;e[2948]=7502;e[2950]=7504;e[2951]=7505;e[2952]=7506;e[2954]=7508;e[2955]=7509;e[2956]=7510;e[2958]=7512;e[2959]=7513;e[2960]=7514;e[2962]=7516;e[2963]=7517;e[2964]=7518;e[2966]=7520;e[2967]=7521;e[2968]=7522;e[2970]=7524;e[2971]=7525;e[2972]=7526;e[2974]=7528;e[2975]=7529;e[2976]=7530;e[2978]=1537;e[2979]=1538;e[2980]=1539;e[2982]=1549;e[2983]=1551;e[2984]=1552;e[2986]=1554;e[2987]=1555;e[2988]=1556;e[2990]=1623;e[2991]=1624;e[2995]=1775;e[2999]=1791;e[3002]=64290;e[3003]=64291;e[3004]=64292;e[3006]=64294;e[3007]=64295;e[3008]=64296;e[3011]=1900;e[3014]=8223;e[3015]=8244;e[3017]=7532;e[3018]=7533;e[3019]=7534;e[3075]=7590;e[3076]=7591;e[3079]=7594;e[3080]=7595;e[3083]=7598;e[3084]=7599;e[3087]=7602;e[3088]=7603;e[3091]=7606;e[3092]=7607;e[3095]=7610;e[3096]=7611;e[3099]=7614;e[3100]=7615;e[3103]=7618;e[3104]=7619;e[3107]=8337;e[3108]=8338;e[3116]=1884;e[3119]=1885;e[3120]=1885;e[3123]=1886;e[3124]=1886;e[3127]=1887;e[3128]=1887;e[3131]=1888;e[3132]=1888;e[3135]=1889;e[3136]=1889;e[3139]=1890;e[3140]=1890;e[3143]=1891;e[3144]=1891;e[3147]=1892;e[3148]=1892;e[3153]=580;e[3154]=581;e[3157]=584;e[3158]=585;e[3161]=588;e[3162]=589;e[3165]=891;e[3166]=892;e[3169]=1274;e[3170]=1275;e[3173]=1278;e[3174]=1279;e[3181]=7622;e[3182]=7623;e[3282]=11799;e[3316]=578;e[3379]=42785;e[3393]=1159;e[3416]=8377})),Pi=getLookupTableFactory((function(e){e[227]=322;e[264]=261;e[291]=346})),Wi=getLookupTableFactory((function(e){e[1]=32;e[4]=65;e[5]=192;e[6]=193;e[9]=196;e[17]=66;e[18]=67;e[21]=268;e[24]=68;e[28]=69;e[29]=200;e[30]=201;e[32]=282;e[38]=70;e[39]=71;e[44]=72;e[47]=73;e[48]=204;e[49]=205;e[58]=74;e[60]=75;e[62]=76;e[68]=77;e[69]=78;e[75]=79;e[76]=210;e[80]=214;e[87]=80;e[89]=81;e[90]=82;e[92]=344;e[94]=83;e[97]=352;e[100]=84;e[104]=85;e[109]=220;e[115]=86;e[116]=87;e[121]=88;e[122]=89;e[124]=221;e[127]=90;e[129]=381;e[258]=97;e[259]=224;e[260]=225;e[263]=228;e[268]=261;e[271]=98;e[272]=99;e[273]=263;e[275]=269;e[282]=100;e[286]=101;e[287]=232;e[288]=233;e[290]=283;e[295]=281;e[296]=102;e[336]=103;e[346]=104;e[349]=105;e[350]=236;e[351]=237;e[361]=106;e[364]=107;e[367]=108;e[371]=322;e[373]=109;e[374]=110;e[381]=111;e[382]=242;e[383]=243;e[386]=246;e[393]=112;e[395]=113;e[396]=114;e[398]=345;e[400]=115;e[401]=347;e[403]=353;e[410]=116;e[437]=117;e[442]=252;e[448]=118;e[449]=119;e[454]=120;e[455]=121;e[457]=253;e[460]=122;e[462]=382;e[463]=380;e[853]=44;e[855]=58;e[856]=46;e[876]=47;e[878]=45;e[882]=45;e[894]=40;e[895]=41;e[896]=91;e[897]=93;e[923]=64;e[1004]=48;e[1005]=49;e[1006]=50;e[1007]=51;e[1008]=52;e[1009]=53;e[1010]=54;e[1011]=55;e[1012]=56;e[1013]=57;e[1081]=37;e[1085]=43;e[1086]=45}));function getStandardFontName(e){const t=normalizeFontName(e);return Yi()[t]}function isKnownFontName(e){const t=normalizeFontName(e);return!!(Yi()[t]||Ki()[t]||Ti()[t]||qi()[t])}class ToUnicodeMap{constructor(e=[]){this._map=e}get length(){return this._map.length}forEach(e){for(const t in this._map)e(t,this._map[t].codePointAt(0))}has(e){return void 0!==this._map[e]}get(e){return this._map[e]}charCodeOf(e){const t=this._map;if(t.length<=65536)return t.indexOf(e);for(const i in t)if(t[i]===e)return 0|i;return-1}amend(e){for(const t in e)this._map[t]=e[t]}}class IdentityToUnicodeMap{constructor(e,t){this.firstChar=e;this.lastChar=t}get length(){return this.lastChar+1-this.firstChar}forEach(e){for(let t=this.firstChar,i=this.lastChar;t<=i;t++)e(t,t)}has(e){return this.firstChar<=e&&e<=this.lastChar}get(e){if(this.firstChar<=e&&e<=this.lastChar)return String.fromCharCode(e)}charCodeOf(e){return Number.isInteger(e)&&e>=this.firstChar&&e<=this.lastChar?e:-1}amend(e){unreachable("Should not call amend()")}}class CFFFont{constructor(e,t){this.properties=t;const i=new CFFParser(e,t,Ri);this.cff=i.parse();this.cff.duplicateFirstGlyph();const a=new CFFCompiler(this.cff);this.seacs=this.cff.seacs;try{this.data=a.compile()}catch{warn("Failed to compile font "+t.loadedName);this.data=e}this._createBuiltInEncoding()}get numGlyphs(){return this.cff.charStrings.count}getCharset(){return this.cff.charset.charset}getGlyphMapping(){const e=this.cff,t=this.properties,{cidToGidMap:i,cMap:a}=t,s=e.charset.charset;let r,n;if(t.composite){let t,g;if(i?.length>0){t=Object.create(null);for(let e=0,a=i.length;e=0){const a=i[t];a&&(s[e]=a)}}s.length>0&&(this.properties.builtInEncoding=s)}}function getUint32(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}function getUint16(e,t){return e[t]<<8|e[t+1]}function getInt16(e,t){return(e[t]<<24|e[t+1]<<16)>>16}function getInt8(e,t){return e[t]<<24>>24}function getFloat214(e,t){return getInt16(e,t)/16384}function getSubroutineBias(e){const t=e.length;let i=32768;t<1240?i=107:t<33900&&(i=1131);return i}function parseCmap(e,t,i){const a=1===getUint16(e,t+2)?getUint32(e,t+8):getUint32(e,t+16),s=getUint16(e,t+a);let r,n,g;if(4===s){getUint16(e,t+a+2);const i=getUint16(e,t+a+6)>>1;n=t+a+14;r=[];for(g=0;g>1;i0;)C.push({flags:r})}for(i=0;i>1;p=!0;break;case 4:n+=s.pop();moveTo(r,n);p=!0;break;case 5:for(;s.length>0;){r+=s.shift();n+=s.shift();lineTo(r,n)}break;case 6:for(;s.length>0;){r+=s.shift();lineTo(r,n);if(0===s.length)break;n+=s.shift();lineTo(r,n)}break;case 7:for(;s.length>0;){n+=s.shift();lineTo(r,n);if(0===s.length)break;r+=s.shift();lineTo(r,n)}break;case 8:for(;s.length>0;){c=r+s.shift();h=n+s.shift();C=c+s.shift();l=h+s.shift();r=C+s.shift();n=l+s.shift();bezierCurveTo(c,h,C,l,r,n)}break;case 10:d=s.pop();f=null;if(i.isCFFCIDFont){const e=i.fdSelect.getFDIndex(a);if(e>=0&&eMath.abs(n-t)?r+=s.shift():n+=s.shift();bezierCurveTo(c,h,C,l,r,n);break;default:throw new FormatError(`unknown operator: 12 ${m}`)}break;case 14:if(s.length>=4){const e=s.pop(),a=s.pop();n=s.pop();r=s.pop();t.save();t.translate(r,n);let g=lookupCmap(i.cmap,String.fromCharCode(i.glyphNameMap[hi[e]]));compileCharString(i.glyphs[g.glyphId],t,i,g.glyphId);t.restore();g=lookupCmap(i.cmap,String.fromCharCode(i.glyphNameMap[hi[a]]));compileCharString(i.glyphs[g.glyphId],t,i,g.glyphId)}return;case 19:case 20:g+=s.length>>1;o+=g+7>>3;p=!0;break;case 21:n+=s.pop();r+=s.pop();moveTo(r,n);p=!0;break;case 22:r+=s.pop();moveTo(r,n);p=!0;break;case 24:for(;s.length>2;){c=r+s.shift();h=n+s.shift();C=c+s.shift();l=h+s.shift();r=C+s.shift();n=l+s.shift();bezierCurveTo(c,h,C,l,r,n)}r+=s.shift();n+=s.shift();lineTo(r,n);break;case 25:for(;s.length>6;){r+=s.shift();n+=s.shift();lineTo(r,n)}c=r+s.shift();h=n+s.shift();C=c+s.shift();l=h+s.shift();r=C+s.shift();n=l+s.shift();bezierCurveTo(c,h,C,l,r,n);break;case 26:s.length%2&&(r+=s.shift());for(;s.length>0;){c=r;h=n+s.shift();C=c+s.shift();l=h+s.shift();r=C;n=l+s.shift();bezierCurveTo(c,h,C,l,r,n)}break;case 27:s.length%2&&(n+=s.shift());for(;s.length>0;){c=r+s.shift();h=n;C=c+s.shift();l=h+s.shift();r=C+s.shift();n=l;bezierCurveTo(c,h,C,l,r,n)}break;case 28:s.push((e[o]<<24|e[o+1]<<16)>>16);o+=2;break;case 29:d=s.pop()+i.gsubrsBias;f=i.gsubrs[d];f&&parse(f);break;case 30:for(;s.length>0;){c=r;h=n+s.shift();C=c+s.shift();l=h+s.shift();r=C+s.shift();n=l+(1===s.length?s.shift():0);bezierCurveTo(c,h,C,l,r,n);if(0===s.length)break;c=r+s.shift();h=n;C=c+s.shift();l=h+s.shift();n=l+s.shift();r=C+(1===s.length?s.shift():0);bezierCurveTo(c,h,C,l,r,n)}break;case 31:for(;s.length>0;){c=r+s.shift();h=n;C=c+s.shift();l=h+s.shift();n=l+s.shift();r=C+(1===s.length?s.shift():0);bezierCurveTo(c,h,C,l,r,n);if(0===s.length)break;c=r;h=n+s.shift();C=c+s.shift();l=h+s.shift();r=C+s.shift();n=l+(1===s.length?s.shift():0);bezierCurveTo(c,h,C,l,r,n)}break;default:if(m<32)throw new FormatError(`unknown operator: ${m}`);if(m<247)s.push(m-139);else if(m<251)s.push(256*(m-247)+e[o++]+108);else if(m<255)s.push(256*-(m-251)-e[o++]-108);else{s.push((e[o]<<24|e[o+1]<<16|e[o+2]<<8|e[o+3])/65536);o+=4}}p&&(s.length=0)}}(e)}class Commands{cmds=[];transformStack=[];currentTransform=[1,0,0,1,0,0];add(e,t){if(t){const[i,a,s,r,n,g]=this.currentTransform;for(let e=0,o=t.length;e=0&&e2*getUint16(e,t)}const r=[];let n=s(t,0);for(let i=a;ie+(t.getSize()+3&-4)),0)}write(){const e=this.getSize(),t=new DataView(new ArrayBuffer(e)),i=e>131070,a=i?4:2,s=new DataView(new ArrayBuffer((this.glyphs.length+1)*a));i?s.setUint32(0,0):s.setUint16(0,0);let r=0,n=0;for(const e of this.glyphs){r+=e.write(r,t);r=r+3&-4;n+=a;i?s.setUint32(n,r):s.setUint16(n,r>>1)}return{isLocationLong:i,loca:new Uint8Array(s.buffer),glyf:new Uint8Array(t.buffer)}}scale(e){for(let t=0,i=this.glyphs.length;te+t.getSize()),0);return this.header.getSize()+e}write(e,t){if(!this.header)return 0;const i=e;e+=this.header.write(e,t);if(this.simple)e+=this.simple.write(e,t);else for(const i of this.composites)e+=i.write(e,t);return e-i}scale(e){if(!this.header)return;const t=(this.header.xMin+this.header.xMax)/2;this.header.scale(t,e);if(this.simple)this.simple.scale(t,e);else for(const i of this.composites)i.scale(t,e)}}class GlyphHeader{constructor({numberOfContours:e,xMin:t,yMin:i,xMax:a,yMax:s}){this.numberOfContours=e;this.xMin=t;this.yMin=i;this.xMax=a;this.yMax=s}static parse(e,t){return[10,new GlyphHeader({numberOfContours:t.getInt16(e),xMin:t.getInt16(e+2),yMin:t.getInt16(e+4),xMax:t.getInt16(e+6),yMax:t.getInt16(e+8)})]}getSize(){return 10}write(e,t){t.setInt16(e,this.numberOfContours);t.setInt16(e+2,this.xMin);t.setInt16(e+4,this.yMin);t.setInt16(e+6,this.xMax);t.setInt16(e+8,this.yMax);return 10}scale(e,t){this.xMin=Math.round(e+(this.xMin-e)*t);this.xMax=Math.round(e+(this.xMax-e)*t)}}class Contour{constructor({flags:e,xCoordinates:t,yCoordinates:i}){this.xCoordinates=t;this.yCoordinates=i;this.flags=e}}class SimpleGlyph{constructor({contours:e,instructions:t}){this.contours=e;this.instructions=t}static parse(e,t,i){const a=[];for(let s=0;s255?e+=2:g>0&&(e+=1);t=r;g=Math.abs(n-i);g>255?e+=2:g>0&&(e+=1);i=n}}return e}write(e,t){const i=e,a=[],s=[],r=[];let n=0,g=0;for(const i of this.contours){for(let e=0,t=i.xCoordinates.length;e=0?18:2;a.push(e)}else a.push(c)}n=o;const C=i.yCoordinates[e];c=C-g;if(0===c){t|=32;s.push(0)}else{const e=Math.abs(c);if(e<=255){t|=c>=0?36:4;s.push(e)}else s.push(c)}g=C;r.push(t)}t.setUint16(e,a.length-1);e+=2}t.setUint16(e,this.instructions.length);e+=2;if(this.instructions.length){new Uint8Array(t.buffer,0,t.buffer.byteLength).set(this.instructions,e);e+=this.instructions.length}for(const i of r)t.setUint8(e++,i);for(let i=0,s=a.length;i=-128&&this.argument1<=127&&this.argument2>=-128&&this.argument2<=127||(e+=2):this.argument1>=0&&this.argument1<=255&&this.argument2>=0&&this.argument2<=255||(e+=2);return e}write(e,t){const i=e;2&this.flags?this.argument1>=-128&&this.argument1<=127&&this.argument2>=-128&&this.argument2<=127||(this.flags|=1):this.argument1>=0&&this.argument1<=255&&this.argument2>=0&&this.argument2<=255||(this.flags|=1);t.setUint16(e,this.flags);t.setUint16(e+2,this.glyphIndex);e+=4;if(1&this.flags){if(2&this.flags){t.setInt16(e,this.argument1);t.setInt16(e+2,this.argument2)}else{t.setUint16(e,this.argument1);t.setUint16(e+2,this.argument2)}e+=4}else{t.setUint8(e,this.argument1);t.setUint8(e+1,this.argument2);e+=2}if(256&this.flags){t.setUint16(e,this.instructions.length);e+=2;if(this.instructions.length){new Uint8Array(t.buffer,0,t.buffer.byteLength).set(this.instructions,e);e+=this.instructions.length}}return e-i}scale(e,t){}}function writeInt16(e,t,i){e[t]=i>>8&255;e[t+1]=255&i}function writeInt32(e,t,i){e[t]=i>>24&255;e[t+1]=i>>16&255;e[t+2]=i>>8&255;e[t+3]=255&i}function writeData(e,t,i){if(i instanceof Uint8Array)e.set(i,t);else if("string"==typeof i)for(let a=0,s=i.length;ai;){i<<=1;a++}const s=i*t;return{range:s,entry:a,rangeShift:t*e-s}}toArray(){let e=this.sfnt;const t=this.tables,i=Object.keys(t);i.sort();const a=i.length;let s,r,n,g,o,c=12+16*a;const C=[c];for(s=0;s>>0;C.push(c)}const h=new Uint8Array(c);for(s=0;s>>0}writeInt32(h,c+4,e);writeInt32(h,c+8,C[s]);writeInt32(h,c+12,t[o].length);c+=16}return h}addTable(e,t){if(e in this.tables)throw new Error("Table "+e+" already exists");this.tables[e]=t}}const Zi=[4],Vi=[5],zi=[6],_i=[7],$i=[8],Aa=[12,35],ea=[14],ta=[21],ia=[22],aa=[30],sa=[31];class Type1CharString{constructor(){this.width=0;this.lsb=0;this.flexing=!1;this.output=[];this.stack=[]}convert(e,t,i){const a=e.length;let s,r,n,g=!1;for(let o=0;oa)return!0;const s=a-e;for(let e=s;e>8&255,255&t);else{t=65536*t|0;this.output.push(255,t>>24&255,t>>16&255,t>>8&255,255&t)}}this.output.push(...t);i?this.stack.splice(s,e):this.stack.length=0;return!1}}function isHexDigit(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function decrypt(e,t,i){if(i>=e.length)return new Uint8Array(0);let a,s,r=0|t;for(a=0;a>8;r=52845*(t+r)+22719&65535}return g}function isSpecial(e){return 47===e||91===e||93===e||123===e||125===e||40===e||41===e}class Type1Parser{constructor(e,t,i){if(t){const t=e.getBytes(),i=!((isHexDigit(t[0])||isWhiteSpace(t[0]))&&isHexDigit(t[1])&&isHexDigit(t[2])&&isHexDigit(t[3])&&isHexDigit(t[4])&&isHexDigit(t[5])&&isHexDigit(t[6])&&isHexDigit(t[7]));e=new Stream(i?decrypt(t,55665,4):function decryptAscii(e,t,i){let a=0|t;const s=e.length,r=new Uint8Array(s>>>1);let n,g;for(n=0,g=0;n>8;a=52845*(e+a)+22719&65535}}return r.slice(i,g)}(t,55665,4))}this.seacAnalysisEnabled=!!i;this.stream=e;this.nextChar()}readNumberArray(){this.getToken();const e=[];for(;;){const t=this.getToken();if(null===t||"]"===t||"}"===t)break;e.push(parseFloat(t||0))}return e}readNumber(){const e=this.getToken();return parseFloat(e||0)}readInt(){const e=this.getToken();return 0|parseInt(e||0,10)}readBoolean(){return"true"===this.getToken()?1:0}nextChar(){return this.currentChar=this.stream.getByte()}prevChar(){this.stream.skip(-2);return this.currentChar=this.stream.getByte()}getToken(){let e=!1,t=this.currentChar;for(;;){if(-1===t)return null;if(e)10!==t&&13!==t||(e=!1);else if(37===t)e=!0;else if(!isWhiteSpace(t))break;t=this.nextChar()}if(isSpecial(t)){this.nextChar();return String.fromCharCode(t)}let i="";do{i+=String.fromCharCode(t);t=this.nextChar()}while(t>=0&&!isWhiteSpace(t)&&!isSpecial(t));return i}readCharStrings(e,t){return-1===t?e:decrypt(e,4330,t)}extractFontProgram(e){const t=this.stream,i=[],a=[],s=Object.create(null);s.lenIV=4;const r={subrs:[],charstrings:[],properties:{privateData:s}};let n,g,o,c;for(;null!==(n=this.getToken());)if("/"===n){n=this.getToken();switch(n){case"CharStrings":this.getToken();this.getToken();this.getToken();this.getToken();for(;;){n=this.getToken();if(null===n||"end"===n)break;if("/"!==n)continue;const e=this.getToken();g=this.readInt();this.getToken();o=g>0?t.getBytes(g):new Uint8Array(0);c=r.properties.privateData.lenIV;const i=this.readCharStrings(o,c);this.nextChar();n=this.getToken();"noaccess"===n?this.getToken():"/"===n&&this.prevChar();a.push({glyph:e,encoded:i})}break;case"Subrs":this.readInt();this.getToken();for(;"dup"===this.getToken();){const e=this.readInt();g=this.readInt();this.getToken();o=g>0?t.getBytes(g):new Uint8Array(0);c=r.properties.privateData.lenIV;const a=this.readCharStrings(o,c);this.nextChar();n=this.getToken();"noaccess"===n&&this.getToken();i[e]=a}break;case"BlueValues":case"OtherBlues":case"FamilyBlues":case"FamilyOtherBlues":const e=this.readNumberArray();e.length>0&&e.length,0;break;case"StemSnapH":case"StemSnapV":r.properties.privateData[n]=this.readNumberArray();break;case"StdHW":case"StdVW":r.properties.privateData[n]=this.readNumberArray()[0];break;case"BlueShift":case"lenIV":case"BlueFuzz":case"BlueScale":case"LanguageGroup":r.properties.privateData[n]=this.readNumber();break;case"ExpansionFactor":r.properties.privateData[n]=this.readNumber()||.06;break;case"ForceBold":r.properties.privateData[n]=this.readBoolean()}}for(const{encoded:t,glyph:s}of a){const a=new Type1CharString,n=a.convert(t,i,this.seacAnalysisEnabled);let g=a.output;n&&(g=[14]);const o={glyphName:s,charstring:g,width:a.width,lsb:a.lsb,seac:a.seac};".notdef"===s?r.charstrings.unshift(o):r.charstrings.push(o);if(e.builtInEncoding){const t=e.builtInEncoding.indexOf(s);t>-1&&void 0===e.widths[t]&&t>=e.firstChar&&t<=e.lastChar&&(e.widths[t]=a.width)}}return r}extractFontHeader(e){let t;for(;null!==(t=this.getToken());)if("/"===t){t=this.getToken();switch(t){case"FontMatrix":const i=this.readNumberArray();e.fontMatrix=i;break;case"Encoding":const a=this.getToken();let s;if(/^\d+$/.test(a)){s=[];const e=0|parseInt(a,10);this.getToken();for(let i=0;i=s){n+=i;for(;n=0&&(a[e]=s)}}return type1FontGlyphMapping(e,a,i)}hasGlyphId(e){if(e<0||e>=this.numGlyphs)return!1;if(0===e)return!0;return this.charstrings[e-1].charstring.length>0}getSeacs(e){const t=[];for(let i=0,a=e.length;i0;e--)t[e]-=t[e-1];Q.setByName(e,t)}r.topDict.privateDict=Q;const u=new CFFIndex;for(C=0,h=a.length;C0&&e.toUnicode.amend(t)}class fonts_Glyph{constructor(e,t,i,a,s,r,n,g,o){this.originalCharCode=e;this.fontChar=t;this.unicode=i;this.accent=a;this.width=s;this.vmetric=r;this.operatorListId=n;this.isSpace=g;this.isInFont=o}get category(){return shadow(this,"category",function getCharUnicodeCategory(e){const t=ki.get(e);if(t)return t;const i=e.match(Si),a={isWhitespace:!!i?.[1],isZeroWidthDiacritic:!!i?.[2],isInvisibleFormatMark:!!i?.[3]};ki.set(e,a);return a}(this.unicode),!0)}}function int16(e,t){return(e<<8)+t}function writeSignedInt16(e,t,i){e[t+1]=i;e[t]=i>>>8}function signedInt16(e,t){const i=(e<<8)+t;return 32768&i?i-65536:i}function string16(e){return String.fromCharCode(e>>8&255,255&e)}function safeString16(e){e>32767?e=32767:e<-32768&&(e=-32768);return String.fromCharCode(e>>8&255,255&e)}function isTrueTypeCollectionFile(e){return"ttcf"===bytesToString(e.peekBytes(4))}function getFontFileType(e,{type:t,subtype:i,composite:a}){let s,r;if(function isTrueTypeFile(e){const t=e.peekBytes(4);return 65536===readUint32(t,0)||"true"===bytesToString(t)}(e)||isTrueTypeCollectionFile(e))s=a?"CIDFontType2":"TrueType";else if(function isOpenTypeFile(e){return"OTTO"===bytesToString(e.peekBytes(4))}(e))s=a?"CIDFontType2":"OpenType";else if(function isType1File(e){const t=e.peekBytes(2);return 37===t[0]&&33===t[1]||128===t[0]&&1===t[1]}(e))s=a?"CIDFontType0":"MMType1"===t?"MMType1":"Type1";else if(function isCFFFile(e){const t=e.peekBytes(4);return t[0]>=1&&t[3]>=1&&t[3]<=4}(e))if(a){s="CIDFontType0";r="CIDFontType0C"}else{s="MMType1"===t?"MMType1":"Type1";r="Type1C"}else{warn("getFontFileType: Unable to detect correct font file Type/Subtype.");s=t;r=i}return[s,r]}function applyStandardFontGlyphMap(e,t){for(const i in t)e[+i]=t[i]}function buildToFontChar(e,t,i){const a=[];let s;for(let i=0,r=e.length;iC){o++;if(o>=ra.length){warn("Ran out of space in font private use area.");break}c=ra[o][0];C=ra[o][1]}const E=c++;0===Q&&(Q=i);let u=a.get(l);"string"==typeof u&&(u=u.codePointAt(0));if(u&&!(h=u,ra[0][0]<=h&&h<=ra[0][1]||ra[1][0]<=h&&h<=ra[1][1])&&!g.has(Q)){r.set(u,Q);g.add(Q)}s[E]=Q;n[l]=E}var h;return{toFontChar:n,charCodeToGlyphId:s,toUnicodeExtraMap:r,nextAvailableFontCharCode:c}}function createCmapTable(e,t,i){const a=function getRanges(e,t,i){const a=[];for(const t in e)e[t]>=i||a.push({fontCharCode:0|t,glyphId:e[t]});if(t)for(const[e,s]of t)s>=i||a.push({fontCharCode:e,glyphId:s});0===a.length&&a.push({fontCharCode:0,glyphId:0});a.sort((function fontGetRangesSort(e,t){return e.fontCharCode-t.fontCharCode}));const s=[],r=a.length;for(let e=0;e65535?2:1;let r,n,g,o,c="\0\0"+string16(s)+"\0\0"+string32(4+8*s);for(r=a.length-1;r>=0&&!(a[r][0]<=65535);--r);const C=r+1;a[r][0]<65535&&65535===a[r][1]&&(a[r][1]=65534);const h=a[r][1]<65535?1:0,l=C+h,Q=OpenTypeFileBuilder.getSearchParams(l,2);let E,u,d,f,p="",m="",y="",w="",D="",b=0;for(r=0,n=C;r0){m+="ÿÿ";p+="ÿÿ";y+="\0";w+="\0\0"}const F="\0\0"+string16(2*l)+string16(Q.range)+string16(Q.entry)+string16(Q.rangeShift)+m+"\0\0"+p+y+w+D;let S="",k="";if(s>1){c+="\0\0\n"+string32(4+8*s+4+F.length);S="";for(r=0,n=a.length;re||!g)&&(g=e);o 123 are reserved for internal usage");n|=1<65535&&(o=65535)}else{g=0;o=255}const C=e.bbox||[0,0,0,0],h=i.unitsPerEm||(e.fontMatrix?1/Math.max(...e.fontMatrix.slice(0,4).map(Math.abs)):1e3),l=e.ascentScaled?1:h/na,Q=i.ascent||Math.round(l*(e.ascent||C[3]));let E=i.descent||Math.round(l*(e.descent||C[1]));E>0&&e.descent>0&&C[1]<0&&(E=-E);const u=i.yMax||Q,d=-i.yMin||-E;return"\0$ô\0\0\0Š»\0\0\0ŒŠ»\0\0ß\x001\0\0\0\0"+String.fromCharCode(e.fixedPitch?9:0)+"\0\0\0\0\0\0"+string32(a)+string32(s)+string32(r)+string32(n)+"*21*"+string16(e.italicAngle?1:0)+string16(g||e.firstChar)+string16(o||e.lastChar)+string16(Q)+string16(E)+"\0d"+string16(u)+string16(d)+"\0\0\0\0\0\0\0\0"+string16(e.xHeight)+string16(e.capHeight)+string16(0)+string16(g||e.firstChar)+"\0"}function createPostTable(e){return"\0\0\0"+string32(Math.floor(65536*e.italicAngle))+"\0\0\0\0"+string32(e.fixedPitch?1:0)+"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"}function createPostscriptName(e){return e.replaceAll(/[^\x21-\x7E]|[[\](){}<>/%]/g,"").slice(0,63)}function createNameTable(e,t){t||(t=[[],[]]);const i=[t[0][0]||"Original licence",t[0][1]||e,t[0][2]||"Unknown",t[0][3]||"uniqueID",t[0][4]||e,t[0][5]||"Version 0.11",t[0][6]||createPostscriptName(e),t[0][7]||"Unknown",t[0][8]||"Unknown",t[0][9]||"Unknown"],a=[];let s,r,n,g,o;for(s=0,r=i.length;s0;if((n||g)&&"CIDFontType2"===i&&this.cidEncoding.startsWith("Identity-")){const i=e.cidToGidMap,a=[];applyStandardFontGlyphMap(a,Oi());/Arial-?Black/i.test(t)?applyStandardFontGlyphMap(a,Pi()):/Calibri/i.test(t)&&applyStandardFontGlyphMap(a,Wi());if(i){for(const e in a){const t=a[e];void 0!==i[t]&&(a[+e]=i[t])}i.length!==this.toUnicode.length&&e.hasIncludedToUnicodeMap&&this.toUnicode instanceof IdentityToUnicodeMap&&this.toUnicode.forEach((function(e,t){const s=a[e];void 0===i[s]&&(a[+e]=t)}))}this.toUnicode instanceof IdentityToUnicodeMap||this.toUnicode.forEach((function(e,t){a[+e]=t}));this.toFontChar=a;this.toUnicode=new ToUnicodeMap(a)}else if(/Symbol/i.test(a))this.toFontChar=buildToFontChar(Bi,wi(),this.differences);else if(/Dingbats/i.test(a))this.toFontChar=buildToFontChar(Qi,Di(),this.differences);else if(n||g){const e=buildToFontChar(this.defaultEncoding,wi(),this.differences);"CIDFontType2"!==i||this.cidEncoding.startsWith("Identity-")||this.toUnicode instanceof IdentityToUnicodeMap||this.toUnicode.forEach((function(t,i){e[+t]=i}));this.toFontChar=e}else{const e=wi(),i=[];this.toUnicode.forEach(((t,a)=>{if(!this.composite){const i=getUnicodeForGlyph(this.differences[t]||this.defaultEncoding[t],e);-1!==i&&(a=i)}i[+t]=a}));this.composite&&this.toUnicode instanceof IdentityToUnicodeMap&&/Tahoma|Verdana/i.test(t)&&applyStandardFontGlyphMap(i,Oi());this.toFontChar=i}amendFallbackToUnicode(e);this.loadedName=a.split("-",1)[0]}checkAndRepair(e,t,i){const a=["OS/2","cmap","head","hhea","hmtx","maxp","name","post","loca","glyf","fpgm","prep","cvt ","CFF "];function readTables(e,t){const i=Object.create(null);i["OS/2"]=null;i.cmap=null;i.head=null;i.hhea=null;i.hmtx=null;i.maxp=null;i.name=null;i.post=null;for(let s=0;s>>0,a=e.getInt32()>>>0,s=e.getInt32()>>>0,r=e.pos;e.pos=e.start||0;e.skip(a);const n=e.getBytes(s);e.pos=r;if("head"===t){n[8]=n[9]=n[10]=n[11]=0;n[17]|=32}return{tag:t,checksum:i,length:s,offset:a,data:n}}function readOpenTypeHeader(e){return{version:e.getString(4),numTables:e.getUint16(),searchRange:e.getUint16(),entrySelector:e.getUint16(),rangeShift:e.getUint16()}}function sanitizeGlyph(e,t,i,a,s,r){const n={length:0,sizeOfInstructions:0};if(t<0||t>=e.length||i>e.length||i-t<=12)return n;const g=e.subarray(t,i),o=signedInt16(g[2],g[3]),c=signedInt16(g[4],g[5]),C=signedInt16(g[6],g[7]),h=signedInt16(g[8],g[9]);if(o>C){writeSignedInt16(g,2,C);writeSignedInt16(g,6,o)}if(c>h){writeSignedInt16(g,4,h);writeSignedInt16(g,8,c)}const l=signedInt16(g[0],g[1]);if(l<0){if(l<-1)return n;a.set(g,s);n.length=g.length;return n}let Q,E=10,u=0;for(Q=0;Qg.length)return n;if(!r&&f>0){a.set(g.subarray(0,d),s);a.set([0,0],s+d);a.set(g.subarray(p,y),s+d+2);y-=f;g.length-y>3&&(y=y+3&-4);n.length=y;return n}if(g.length-y>3){y=y+3&-4;a.set(g.subarray(0,y),s);n.length=y;return n}a.set(g,s);n.length=g.length;return n}function readNameTable(e){const i=(t.start||0)+e.offset;t.pos=i;const a=[[],[]],s=[],r=e.length,n=i+r;if(0!==t.getUint16()||r<6)return[a,s];const g=t.getUint16(),o=t.getUint16();let c,C;for(c=0;cn)continue;t.pos=r;const g=e.name;if(e.encoding){let i="";for(let a=0,s=e.length;a0&&(c+=e-1)}}else{if(d||p){warn("TT: nested FDEFs not allowed");u=!0}d=!0;h=c;n=l.pop();t.functionsDefined[n]={data:o,i:c}}else if(!d&&!p){n=l.at(-1);if(isNaN(n))info("TT: CALL empty stack (or invalid entry).");else{t.functionsUsed[n]=!0;if(n in t.functionsStackDeltas){const e=l.length+t.functionsStackDeltas[n];if(e<0){warn("TT: CALL invalid functions stack delta.");t.hintsValid=!1;return}l.length=e}else if(n in t.functionsDefined&&!E.includes(n)){Q.push({data:o,i:c,stackTop:l.length-1});E.push(n);g=t.functionsDefined[n];if(!g){warn("TT: CALL non-existent function");t.hintsValid=!1;return}o=g.data;c=g.i}}}if(!d&&!p){let t=0;e<=142?t=s[e]:e>=192&&e<=223?t=-1:e>=224&&(t=-2);if(e>=113&&e<=117){a=l.pop();isNaN(a)||(t=2*-a)}for(;t<0&&l.length>0;){l.pop();t++}for(;t>0;){l.push(NaN);t--}}}t.tooComplexToFollowFunctions=u;const m=[o];c>o.length&&m.push(new Uint8Array(c-o.length));if(h>C){warn("TT: complementing a missing function tail");m.push(new Uint8Array([34,45]))}!function foldTTTable(e,t){if(t.length>1){let i,a,s=0;for(i=0,a=t.length;i>>0,r=[];for(let t=0;t>>0);const n={ttcTag:t,majorVersion:i,minorVersion:a,numFonts:s,offsetTable:r};switch(i){case 1:return n;case 2:n.dsigTag=e.getInt32()>>>0;n.dsigLength=e.getInt32()>>>0;n.dsigOffset=e.getInt32()>>>0;return n}throw new FormatError(`Invalid TrueType Collection majorVersion: ${i}.`)}(e),s=t.split("+");let r;for(let n=0;n0||!(i.cMap instanceof IdentityCMap));if("OTTO"===r.version&&!t||!n.head||!n.hhea||!n.maxp||!n.post){o=new Stream(n["CFF "].data);g=new CFFFont(o,i);adjustWidths(i);return this.convert(e,g,i)}delete n.glyf;delete n.loca;delete n.fpgm;delete n.prep;delete n["cvt "];this.isOpenType=!0}if(!n.maxp)throw new FormatError('Required "maxp" table is not found');t.pos=(t.start||0)+n.maxp.offset;let C=t.getInt32();const h=t.getUint16();if(65536!==C&&20480!==C){if(6===n.maxp.length)C=20480;else{if(!(n.maxp.length>=32))throw new FormatError('"maxp" table has a wrong version number');C=65536}!function writeUint32(e,t,i){e[t+3]=255&i;e[t+2]=i>>>8;e[t+1]=i>>>16;e[t]=i>>>24}(n.maxp.data,0,C)}if(i.scaleFactors?.length===h&&c){const{scaleFactors:e}=i,t=int16(n.head.data[50],n.head.data[51]),a=new GlyfTable({glyfTable:n.glyf.data,isGlyphLocationsLong:t,locaTable:n.loca.data,numGlyphs:h});a.scale(e);const{glyf:s,loca:r,isLocationLong:g}=a.write();n.glyf.data=s;n.loca.data=r;if(g!==!!t){n.head.data[50]=0;n.head.data[51]=g?1:0}const o=n.hmtx.data;for(let t=0;t>8&255;o[i+1]=255&a;writeSignedInt16(o,i+2,Math.round(e[t]*signedInt16(o[i+2],o[i+3])))}}let l=h+1,Q=!0;if(l>65535){Q=!1;l=h;warn("Not enough space in glyfs to duplicate first glyph.")}let E=0,u=0;if(C>=65536&&n.maxp.length>=32){t.pos+=8;if(t.getUint16()>2){n.maxp.data[14]=0;n.maxp.data[15]=2}t.pos+=4;E=t.getUint16();t.pos+=4;u=t.getUint16()}n.maxp.data[4]=l>>8;n.maxp.data[5]=255&l;const d=function sanitizeTTPrograms(e,t,i,a){const s={functionsDefined:[],functionsUsed:[],functionsStackDeltas:[],tooComplexToFollowFunctions:!1,hintsValid:!0};e&&sanitizeTTProgram(e,s);t&&sanitizeTTProgram(t,s);e&&function checkInvalidFunctions(e,t){if(!e.tooComplexToFollowFunctions)if(e.functionsDefined.length>t){warn("TT: more functions defined than expected");e.hintsValid=!1}else for(let i=0,a=e.functionsUsed.length;it){warn("TT: invalid function id: "+i);e.hintsValid=!1;return}if(e.functionsUsed[i]&&!e.functionsDefined[i]){warn("TT: undefined function: "+i);e.hintsValid=!1;return}}}(s,a);if(i&&1&i.length){const e=new Uint8Array(i.length+1);e.set(i.data);i.data=e}return s.hintsValid}(n.fpgm,n.prep,n["cvt "],E);if(!d){delete n.fpgm;delete n.prep;delete n["cvt "]}!function sanitizeMetrics(e,t,i,a,s,r){if(!t){i&&(i.data=null);return}e.pos=(e.start||0)+t.offset;e.pos+=4;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;const n=e.getUint16();e.pos+=8;e.pos+=2;let g=e.getUint16();if(0!==n){if(!(2&int16(a.data[44],a.data[45]))){t.data[22]=0;t.data[23]=0}}if(g>s){info(`The numOfMetrics (${g}) should not be greater than the numGlyphs (${s}).`);g=s;t.data[34]=(65280&g)>>8;t.data[35]=255&g}const o=s-g-(i.length-4*g>>1);if(o>0){const e=new Uint8Array(i.length+2*o);e.set(i.data);if(r){e[i.length]=i.data[2];e[i.length+1]=i.data[3]}i.data=e}}(t,n.hhea,n.hmtx,n.head,l,Q);if(!n.head)throw new FormatError('Required "head" table is not found');!function sanitizeHead(e,t,i){const a=e.data,s=function int32(e,t,i,a){return(e<<24)+(t<<16)+(i<<8)+a}(a[0],a[1],a[2],a[3]);if(s>>16!=1){info("Attempting to fix invalid version in head table: "+s);a[0]=0;a[1]=1;a[2]=0;a[3]=0}const r=int16(a[50],a[51]);if(r<0||r>1){info("Attempting to fix invalid indexToLocFormat in head table: "+r);const e=t+1;if(i===e<<1){a[50]=0;a[51]=0}else{if(i!==e<<2)throw new FormatError("Could not fix indexToLocFormat: "+r);a[50]=0;a[51]=1}}}(n.head,h,c?n.loca.length:0);let f=Object.create(null);if(c){const e=int16(n.head.data[50],n.head.data[51]),t=function sanitizeGlyphLocations(e,t,i,a,s,r,n){let g,o,c;if(a){g=4;o=function fontItemDecodeLong(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]};c=function fontItemEncodeLong(e,t,i){e[t]=i>>>24&255;e[t+1]=i>>16&255;e[t+2]=i>>8&255;e[t+3]=255&i}}else{g=2;o=function fontItemDecode(e,t){return e[t]<<9|e[t+1]<<1};c=function fontItemEncode(e,t,i){e[t]=i>>9&255;e[t+1]=i>>1&255}}const C=r?i+1:i,h=g*(1+C),l=new Uint8Array(h);l.set(e.data.subarray(0,h));e.data=l;const Q=t.data,E=Q.length,u=new Uint8Array(E);let d,f;const p=[];for(d=0,f=0;dE&&(e=E);p.push({index:d,offset:e,endOffset:0})}p.sort(((e,t)=>e.offset-t.offset));for(d=0;de.index-t.index));for(d=0;dn&&(n=e.sizeOfInstructions);w+=t;c(l,f,w)}if(0===w){const e=new Uint8Array([0,1,0,0,0,0,0,0,0,0,0,0,0,0,49,0]);for(d=0,f=g;di+w)t.data=u.subarray(0,i+w);else{t.data=new Uint8Array(i+w);t.data.set(u.subarray(0,w))}t.data.set(u.subarray(0,i),w);c(e.data,l.length-g,w+i)}else t.data=u.subarray(0,w);return{missingGlyphs:y,maxSizeOfInstructions:n}}(n.loca,n.glyf,h,e,d,Q,u);f=t.missingGlyphs;if(C>=65536&&n.maxp.length>=32){n.maxp.data[26]=t.maxSizeOfInstructions>>8;n.maxp.data[27]=255&t.maxSizeOfInstructions}}if(!n.hhea)throw new FormatError('Required "hhea" table is not found');if(0===n.hhea.data[10]&&0===n.hhea.data[11]){n.hhea.data[10]=255;n.hhea.data[11]=255}const p={unitsPerEm:int16(n.head.data[18],n.head.data[19]),yMax:signedInt16(n.head.data[42],n.head.data[43]),yMin:signedInt16(n.head.data[38],n.head.data[39]),ascent:signedInt16(n.hhea.data[4],n.hhea.data[5]),descent:signedInt16(n.hhea.data[6],n.hhea.data[7]),lineGap:signedInt16(n.hhea.data[8],n.hhea.data[9])};this.ascent=p.ascent/p.unitsPerEm;this.descent=p.descent/p.unitsPerEm;this.lineGap=p.lineGap/p.unitsPerEm;if(this.cssFontInfo?.lineHeight){this.lineHeight=this.cssFontInfo.metrics.lineHeight;this.lineGap=this.cssFontInfo.metrics.lineGap}else this.lineHeight=this.ascent-this.descent+this.lineGap;n.post&&function readPostScriptTable(e,i,a){const s=(t.start||0)+e.offset;t.pos=s;const r=s+e.length,n=t.getInt32();t.skip(28);let g,o,c=!0;switch(n){case 65536:g=Hi;break;case 131072:const e=t.getUint16();if(e!==a){c=!1;break}const s=[];for(o=0;o=32768){c=!1;break}s.push(e)}if(!c)break;const C=[],h=[];for(;t.pos65535)throw new FormatError("Max size of CID is 65,535");let s=-1;t?s=a:void 0!==e[a]&&(s=e[a]);s>=0&&s>>0;let C=!1;if(g?.platformId!==s||g?.encodingId!==r){if(0!==s||0!==r&&1!==r&&3!==r)if(1===s&&0===r)C=!0;else if(3!==s||1!==r||!a&&g){if(i&&3===s&&0===r){C=!0;let i=!0;if(e>3;e.push(a);i=Math.max(a,i)}const a=[];for(let e=0;e<=i;e++)a.push({firstCode:t.getUint16(),entryCount:t.getUint16(),idDelta:signedInt16(t.getByte(),t.getByte()),idRangePos:t.pos+t.getUint16()});for(let i=0;i<256;i++)if(0===e[i]){t.pos=a[0].idRangePos+2*i;Q=t.getUint16();h.push({charCode:i,glyphId:Q})}else{const s=a[e[i]];for(l=0;l>1;t.skip(6);const i=[];let a;for(a=0;a>1)-(e-a);s.offsetIndex=n;g=Math.max(g,n+s.end-s.start+1)}else s.offsetIndex=-1}const o=[];for(l=0;l>>0;for(l=0;l>>0,i=t.getInt32()>>>0;let a=t.getInt32()>>>0;for(let t=e;t<=i;t++)h.push({charCode:t,glyphId:a++})}}}h.sort((function(e,t){return e.charCode-t.charCode}));for(let e=1;e=61440&&t<=61695&&(t&=255);m[t]=e.glyphId}else for(const e of r)m[e.charCode]=e.glyphId;if(i.glyphNames&&(g.length||this.differences.length))for(let e=0;e<256;++e){if(!o&&void 0!==m[e])continue;const t=this.differences[e]||g[e];if(!t)continue;const a=i.glyphNames.indexOf(t);a>0&&hasGlyph(a)&&(m[e]=a)}}0===m.length&&(m[0]=0);let y=l-1;Q||(y=0);if(!i.cssFontInfo){const e=adjustMapping(m,hasGlyph,y,this.toUnicode);this.toFontChar=e.toFontChar;n.cmap={tag:"cmap",data:createCmapTable(e.charCodeToGlyphId,e.toUnicodeExtraMap,l)};n["OS/2"]&&function validateOS2Table(e,t){t.pos=(t.start||0)+e.offset;const i=t.getUint16();t.skip(60);const a=t.getUint16();if(i<4&&768&a)return!1;if(t.getUint16()>t.getUint16())return!1;t.skip(6);if(0===t.getUint16())return!1;e.data[8]=e.data[9]=0;return!0}(n["OS/2"],t)||(n["OS/2"]={tag:"OS/2",data:createOS2Table(i,e.charCodeToGlyphId,p)})}if(!c)try{o=new Stream(n["CFF "].data);g=new CFFParser(o,i,Ri).parse();g.duplicateFirstGlyph();const e=new CFFCompiler(g);n["CFF "].data=e.compile()}catch{warn("Failed to compile font "+i.loadedName)}if(n.name){const[t,a]=readNameTable(n.name);n.name.data=createNameTable(e,t);this.psName=t[0][6]||null;i.composite||function adjustTrueTypeToUnicode(e,t,i){if(e.isInternalFont)return;if(e.hasIncludedToUnicodeMap)return;if(e.hasEncoding)return;if(e.toUnicode instanceof IdentityToUnicodeMap)return;if(!t)return;if(0===i.length)return;if(e.defaultEncoding===li)return;for(const e of i)if(!isWinNameRecord(e))return;const a=li,s=[],r=wi();for(const e in a){const t=a[e];if(""===t)continue;const i=r[t];void 0!==i&&(s[e]=String.fromCharCode(i))}s.length>0&&e.toUnicode.amend(s)}(i,this.isSymbolicFont,a)}else n.name={tag:"name",data:createNameTable(this.name)};const w=new OpenTypeFileBuilder(r.version);for(const e in n)w.addTable(e,n[e].data);return w.toArray()}convert(e,t,i){i.fixedPitch=!1;i.builtInEncoding&&function adjustType1ToUnicode(e,t){if(e.isInternalFont)return;if(e.hasIncludedToUnicodeMap)return;if(t===e.defaultEncoding)return;if(e.toUnicode instanceof IdentityToUnicodeMap)return;const i=[],a=wi();for(const s in t){if(e.hasEncoding&&(e.baseEncodingName||void 0!==e.differences[s]))continue;const r=getUnicodeForGlyph(t[s],a);-1!==r&&(i[s]=String.fromCharCode(r))}i.length>0&&e.toUnicode.amend(i)}(i,i.builtInEncoding);let s=1;t instanceof CFFFont&&(s=t.numGlyphs-1);const r=t.getGlyphMapping(i);let n=null,g=r,o=null;if(!i.cssFontInfo){n=adjustMapping(r,t.hasGlyphId.bind(t),s,this.toUnicode);this.toFontChar=n.toFontChar;g=n.charCodeToGlyphId;o=n.toUnicodeExtraMap}const c=t.numGlyphs;function getCharCodes(e,t){let i=null;for(const a in e)t===e[a]&&(i||=[]).push(0|a);return i}function createCharCode(e,t){for(const i in e)if(t===e[i])return 0|i;n.charCodeToGlyphId[n.nextAvailableFontCharCode]=t;return n.nextAvailableFontCharCode++}const C=t.seacs;if(n&&C?.length){const e=i.fontMatrix||a,s=t.getCharset(),g=Object.create(null);for(let t in C){t|=0;const i=C[t],a=hi[i[2]],o=hi[i[3]],c=s.indexOf(a),h=s.indexOf(o);if(c<0||h<0)continue;const l={x:i[0]*e[0]+i[1]*e[2]+e[4],y:i[0]*e[1]+i[1]*e[3]+e[5]},Q=getCharCodes(r,t);if(Q)for(const e of Q){const t=n.charCodeToGlyphId,i=createCharCode(t,c),a=createCharCode(t,h);g[e]={baseFontCharCode:i,accentFontCharCode:a,accentOffset:l}}}i.seacMap=g}const h=i.fontMatrix?1/Math.max(...i.fontMatrix.slice(0,4).map(Math.abs)):1e3,l=new OpenTypeFileBuilder("OTTO");l.addTable("CFF ",t.data);l.addTable("OS/2",createOS2Table(i,g));l.addTable("cmap",createCmapTable(g,o,c));l.addTable("head","\0\0\0\0\0\0\0\0\0\0_<õ\0\0"+safeString16(h)+"\0\0\0\0ž\v~'\0\0\0\0ž\v~'\0\0"+safeString16(i.descent)+"ÿ"+safeString16(i.ascent)+string16(i.italicAngle?2:0)+"\0\0\0\0\0\0\0");l.addTable("hhea","\0\0\0"+safeString16(i.ascent)+safeString16(i.descent)+"\0\0ÿÿ\0\0\0\0\0\0"+safeString16(i.capHeight)+safeString16(Math.tan(i.italicAngle)*i.xHeight)+"\0\0\0\0\0\0\0\0\0\0\0\0"+string16(c));l.addTable("hmtx",function fontFieldsHmtx(){const e=t.charstrings,i=t.cff?t.cff.widths:null;let a="\0\0\0\0";for(let t=1,s=c;t=65520&&e<=65535?0:e>=62976&&e<=63743?bi()[e]||e:173===e?45:e}(i)}this.isType3Font&&(s=i);let C=null;if(this.seacMap?.[e]){c=!0;const t=this.seacMap[e];i=t.baseFontCharCode;C={fontChar:String.fromCodePoint(t.accentFontCharCode),offset:t.accentOffset}}let h="";"number"==typeof i&&(i<=1114111?h=String.fromCodePoint(i):warn(`charToGlyph - invalid fontCharCode: ${i}`));if(this.missingFile&&this.vertical&&1===h.length){const e=Ji()[h.charCodeAt(0)];e&&(h=o=String.fromCharCode(e))}r=new fonts_Glyph(e,h,o,C,a,g,s,t,c);return this._glyphCache[e]=r}charsToGlyphs(e){let t=this._charsCache[e];if(t)return t;t=[];if(this.cMap){const i=Object.create(null),a=e.length;let s=0;for(;st.length%2==1,a=this.toUnicode instanceof IdentityToUnicodeMap?e=>this.toUnicode.charCodeOf(e):e=>this.toUnicode.charCodeOf(String.fromCodePoint(e));for(let s=0,r=e.length;s55295&&(r<57344||r>65533)&&s++;if(this.toUnicode){const e=a(r);if(-1!==e){if(hasCurrentBufErrors()){t.push(i.join(""));i.length=0}for(let t=(this.cMap?this.cMap.getCharCodeLength(e):1)-1;t>=0;t--)i.push(String.fromCharCode(e>>8*t&255));continue}}if(!hasCurrentBufErrors()){t.push(i.join(""));i.length=0}i.push(String.fromCodePoint(r))}t.push(i.join(""));return t}}class ErrorFont{constructor(e){this.error=e;this.loadedName="g_font_error";this.missingFile=!0}charsToGlyphs(){return[]}encodeString(e){return[e]}exportData(e=!1){return{error:this.error}}}const Ia=2,ca=3,Ca=4,ha=5,la=6,Ba=7;class Pattern{constructor(){unreachable("Cannot initialize Pattern.")}static parseShading(e,t,i,a,s){const r=e instanceof BaseStream?e.dict:e,n=r.get("ShadingType");try{switch(n){case Ia:case ca:return new RadialAxialShading(r,t,i,a,s);case Ca:case ha:case la:case Ba:return new MeshShading(e,t,i,a,s);default:throw new FormatError("Unsupported ShadingType: "+n)}}catch(e){if(e instanceof MissingDataException)throw e;warn(e);return new DummyShading}}}class BaseShading{static SMALL_NUMBER=1e-6;getIR(){unreachable("Abstract method `getIR` called.")}}class RadialAxialShading extends BaseShading{constructor(e,t,i,a,s){super();this.shadingType=e.get("ShadingType");let r=0;this.shadingType===Ia?r=4:this.shadingType===ca&&(r=6);this.coordsArr=e.getArray("Coords");if(!isNumberArray(this.coordsArr,r))throw new FormatError("RadialAxialShading: Invalid /Coords array.");const n=ColorSpace.parse({cs:e.getRaw("CS")||e.getRaw("ColorSpace"),xref:t,resources:i,pdfFunctionFactory:a,localColorSpaceCache:s});this.bbox=lookupNormalRect(e.getArray("BBox"),null);let g=0,o=1;const c=e.getArray("Domain");isNumberArray(c,2)&&([g,o]=c);let C=!1,h=!1;const l=e.getArray("Extend");(function isBooleanArray(e,t){return Array.isArray(e)&&(null===t||e.length===t)&&e.every((e=>"boolean"==typeof e))})(l,2)&&([C,h]=l);if(!(this.shadingType!==ca||C&&h)){const[e,t,i,a,s,r]=this.coordsArr,n=Math.hypot(e-a,t-s);i<=r+n&&r<=i+n&&warn("Unsupported radial gradient.")}this.extendStart=C;this.extendEnd=h;const Q=e.getRaw("Function"),E=a.createFromArray(Q),u=(o-g)/840,d=this.colorStops=[];if(g>=o||u<=0){info("Bad shading domain.");return}const f=new Float32Array(n.numComps),p=new Float32Array(1);let m,y=0;p[0]=g;E(p,0,f,0);let w=n.getRgb(f,0);const D=Util.makeHexColor(w[0],w[1],w[2]);d.push([0,D]);let b=1;p[0]=g+u;E(p,0,f,0);let F=n.getRgb(f,0),S=F[0]-w[0]+1,k=F[1]-w[1]+1,R=F[2]-w[2]+1,N=F[0]-w[0]-1,G=F[1]-w[1]-1,M=F[2]-w[2]-1;for(let e=2;e<840;e++){p[0]=g+e*u;E(p,0,f,0);m=n.getRgb(f,0);const t=e-y;S=Math.min(S,(m[0]-w[0]+1)/t);k=Math.min(k,(m[1]-w[1]+1)/t);R=Math.min(R,(m[2]-w[2]+1)/t);N=Math.max(N,(m[0]-w[0]-1)/t);G=Math.max(G,(m[1]-w[1]-1)/t);M=Math.max(M,(m[2]-w[2]-1)/t);if(!(N<=S&&G<=k&&M<=R)){const e=Util.makeHexColor(F[0],F[1],F[2]);d.push([b/840,e]);S=m[0]-F[0]+1;k=m[1]-F[1]+1;R=m[2]-F[2]+1;N=m[0]-F[0]-1;G=m[1]-F[1]-1;M=m[2]-F[2]-1;y=b;w=F}b=e;F=m}const U=Util.makeHexColor(F[0],F[1],F[2]);d.push([1,U]);let x="transparent";if(e.has("Background")){m=n.getRgb(e.get("Background"),0);x=Util.makeHexColor(m[0],m[1],m[2])}if(!C){d.unshift([0,x]);d[1][0]+=BaseShading.SMALL_NUMBER}if(!h){d.at(-1)[0]-=BaseShading.SMALL_NUMBER;d.push([1,x])}this.colorStops=d}getIR(){const{coordsArr:e,shadingType:t}=this;let i,a,s,r,n;if(t===Ia){a=[e[0],e[1]];s=[e[2],e[3]];r=null;n=null;i="axial"}else if(t===ca){a=[e[0],e[1]];s=[e[3],e[4]];r=e[2];n=e[5];i="radial"}else unreachable(`getPattern type unknown: ${t}`);return["RadialAxial",i,this.bbox,this.colorStops,a,s,r,n]}}class MeshStreamReader{constructor(e,t){this.stream=e;this.context=t;this.buffer=0;this.bufferLength=0;const i=t.numComps;this.tmpCompsBuf=new Float32Array(i);const a=t.colorSpace.numComps;this.tmpCsCompsBuf=t.colorFn?new Float32Array(a):this.tmpCompsBuf}get hasData(){if(this.stream.end)return this.stream.pos0)return!0;const e=this.stream.getByte();if(e<0)return!1;this.buffer=e;this.bufferLength=8;return!0}readBits(e){let t=this.buffer,i=this.bufferLength;if(32===e){if(0===i)return(this.stream.getByte()<<24|this.stream.getByte()<<16|this.stream.getByte()<<8|this.stream.getByte())>>>0;t=t<<24|this.stream.getByte()<<16|this.stream.getByte()<<8|this.stream.getByte();const e=this.stream.getByte();this.buffer=e&(1<>i)>>>0}if(8===e&&0===i)return this.stream.getByte();for(;i>i}align(){this.buffer=0;this.bufferLength=0}readFlag(){return this.readBits(this.context.bitsPerFlag)}readCoordinate(){const e=this.context.bitsPerCoordinate,t=this.readBits(e),i=this.readBits(e),a=this.context.decode,s=e<32?1/((1<r?r:e;t=t>n?n:t;i=ie*s[t])):i;let n,g=-2;const o=[];for(const[e,t]of a.map(((e,t)=>[e,t])).sort((([e],[t])=>e-t)))if(-1!==e)if(e===g+1){n.push(r[t]);g+=1}else{g=e;n=[r[t]];o.push(e,n)}return o}(e),i=new Dict(null);i.set("BaseFont",Name.get(e));i.set("Type",Name.get("Font"));i.set("Subtype",Name.get("CIDFontType2"));i.set("Encoding",Name.get("Identity-H"));i.set("CIDToGIDMap",Name.get("Identity"));i.set("W",t);i.set("FirstChar",t[0]);i.set("LastChar",t.at(-2)+t.at(-1).length-1);const a=new Dict(null);i.set("FontDescriptor",a);const s=new Dict(null);s.set("Ordering","Identity");s.set("Registry","Adobe");s.set("Supplement",0);i.set("CIDSystemInfo",s);return i}class PostScriptParser{constructor(e){this.lexer=e;this.operators=[];this.token=null;this.prev=null}nextToken(){this.prev=this.token;this.token=this.lexer.getToken()}accept(e){if(this.token.type===e){this.nextToken();return!0}return!1}expect(e){if(this.accept(e))return!0;throw new FormatError(`Unexpected symbol: found ${this.token.type} expected ${e}.`)}parse(){this.nextToken();this.expect(as.LBRACE);this.parseBlock();this.expect(as.RBRACE);return this.operators}parseBlock(){for(;;)if(this.accept(as.NUMBER))this.operators.push(this.prev.value);else if(this.accept(as.OPERATOR))this.operators.push(this.prev.value);else{if(!this.accept(as.LBRACE))return;this.parseCondition()}}parseCondition(){const e=this.operators.length;this.operators.push(null,null);this.parseBlock();this.expect(as.RBRACE);if(this.accept(as.IF)){this.operators[e]=this.operators.length;this.operators[e+1]="jz"}else{if(!this.accept(as.LBRACE))throw new FormatError("PS Function: error parsing conditional.");{const t=this.operators.length;this.operators.push(null,null);const i=this.operators.length;this.parseBlock();this.expect(as.RBRACE);this.expect(as.IFELSE);this.operators[t]=this.operators.length;this.operators[t+1]="j";this.operators[e]=i;this.operators[e+1]="jz"}}}}const as={LBRACE:0,RBRACE:1,NUMBER:2,OPERATOR:3,IF:4,IFELSE:5};class PostScriptToken{static get opCache(){return shadow(this,"opCache",Object.create(null))}constructor(e,t){this.type=e;this.value=t}static getOperator(e){return PostScriptToken.opCache[e]||=new PostScriptToken(as.OPERATOR,e)}static get LBRACE(){return shadow(this,"LBRACE",new PostScriptToken(as.LBRACE,"{"))}static get RBRACE(){return shadow(this,"RBRACE",new PostScriptToken(as.RBRACE,"}"))}static get IF(){return shadow(this,"IF",new PostScriptToken(as.IF,"IF"))}static get IFELSE(){return shadow(this,"IFELSE",new PostScriptToken(as.IFELSE,"IFELSE"))}}class PostScriptLexer{constructor(e){this.stream=e;this.nextChar();this.strBuf=[]}nextChar(){return this.currentChar=this.stream.getByte()}getToken(){let e=!1,t=this.currentChar;for(;;){if(t<0)return Bt;if(e)10!==t&&13!==t||(e=!1);else if(37===t)e=!0;else if(!isWhiteSpace(t))break;t=this.nextChar()}switch(0|t){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 43:case 45:case 46:return new PostScriptToken(as.NUMBER,this.getNumber());case 123:this.nextChar();return PostScriptToken.LBRACE;case 125:this.nextChar();return PostScriptToken.RBRACE}const i=this.strBuf;i.length=0;i[0]=String.fromCharCode(t);for(;(t=this.nextChar())>=0&&(t>=65&&t<=90||t>=97&&t<=122);)i.push(String.fromCharCode(t));const a=i.join("");switch(a.toLowerCase()){case"if":return PostScriptToken.IF;case"ifelse":return PostScriptToken.IFELSE;default:return PostScriptToken.getOperator(a)}}getNumber(){let e=this.currentChar;const t=this.strBuf;t.length=0;t[0]=String.fromCharCode(e);for(;(e=this.nextChar())>=0&&(e>=48&&e<=57||45===e||46===e);)t.push(String.fromCharCode(e));const i=parseFloat(t.join(""));if(isNaN(i))throw new FormatError(`Invalid floating point number: ${i}`);return i}}class BaseLocalCache{constructor(e){this._onlyRefs=!0===e?.onlyRefs;if(!this._onlyRefs){this._nameRefMap=new Map;this._imageMap=new Map}this._imageCache=new RefSetCache}getByName(e){this._onlyRefs&&unreachable("Should not call `getByName` method.");const t=this._nameRefMap.get(e);return t?this.getByRef(t):this._imageMap.get(e)||null}getByRef(e){return this._imageCache.get(e)||null}set(e,t,i){unreachable("Abstract method `set` called.")}}class LocalImageCache extends BaseLocalCache{set(e,t=null,i){if("string"!=typeof e)throw new Error('LocalImageCache.set - expected "name" argument.');if(t){if(this._imageCache.has(t))return;this._nameRefMap.set(e,t);this._imageCache.put(t,i)}else this._imageMap.has(e)||this._imageMap.set(e,i)}}class LocalColorSpaceCache extends BaseLocalCache{set(e=null,t=null,i){if("string"!=typeof e&&!t)throw new Error('LocalColorSpaceCache.set - expected "name" and/or "ref" argument.');if(t){if(this._imageCache.has(t))return;null!==e&&this._nameRefMap.set(e,t);this._imageCache.put(t,i)}else this._imageMap.has(e)||this._imageMap.set(e,i)}}class LocalFunctionCache extends BaseLocalCache{constructor(e){super({onlyRefs:!0})}set(e=null,t,i){if(!t)throw new Error('LocalFunctionCache.set - expected "ref" argument.');this._imageCache.has(t)||this._imageCache.put(t,i)}}class LocalGStateCache extends BaseLocalCache{set(e,t=null,i){if("string"!=typeof e)throw new Error('LocalGStateCache.set - expected "name" argument.');if(t){if(this._imageCache.has(t))return;this._nameRefMap.set(e,t);this._imageCache.put(t,i)}else this._imageMap.has(e)||this._imageMap.set(e,i)}}class LocalTilingPatternCache extends BaseLocalCache{constructor(e){super({onlyRefs:!0})}set(e=null,t,i){if(!t)throw new Error('LocalTilingPatternCache.set - expected "ref" argument.');this._imageCache.has(t)||this._imageCache.put(t,i)}}class RegionalImageCache extends BaseLocalCache{constructor(e){super({onlyRefs:!0})}set(e=null,t,i){if(!t)throw new Error('RegionalImageCache.set - expected "ref" argument.');this._imageCache.has(t)||this._imageCache.put(t,i)}}class GlobalImageCache{static NUM_PAGES_THRESHOLD=2;static MIN_IMAGES_TO_CACHE=10;static MAX_BYTE_SIZE=5e7;#F=new RefSet;constructor(){this._refCache=new RefSetCache;this._imageCache=new RefSetCache}get#S(){let e=0;for(const t of this._imageCache)e+=t.byteSize;return e}get#k(){return!(this._imageCache.size+e)):null}class PDFFunction{static getSampleArray(e,t,i,a){let s,r,n=1;for(s=0,r=e.length;s>o)*C;c&=(1<i?e=i:e0&&(l=r[h-1]);let Q=a[1];h>1,c=s.length>>1,C=new PostScriptEvaluator(g),h=Object.create(null);let l=8192;const Q=new Float32Array(c);return function constructPostScriptFn(e,t,i,a){let s,n,g="";const E=Q;for(s=0;se&&(n=e)}d[s]=n}if(l>0){l--;h[g]=d}i.set(d,a)}}}function isPDFFunction(e){let t;if(e instanceof Dict)t=e;else{if(!(e instanceof BaseStream))return!1;t=e.dict}return t.has("FunctionType")}class PostScriptStack{static MAX_STACK_SIZE=100;constructor(e){this.stack=e?Array.from(e):[]}push(e){if(this.stack.length>=PostScriptStack.MAX_STACK_SIZE)throw new Error("PostScript function stack overflow.");this.stack.push(e)}pop(){if(this.stack.length<=0)throw new Error("PostScript function stack underflow.");return this.stack.pop()}copy(e){if(this.stack.length+e>=PostScriptStack.MAX_STACK_SIZE)throw new Error("PostScript function stack overflow.");const t=this.stack;for(let i=t.length-e,a=e-1;a>=0;a--,i++)t.push(t[i])}index(e){this.push(this.stack[this.stack.length-e-1])}roll(e,t){const i=this.stack,a=i.length-e,s=i.length-1,r=a+(t-Math.floor(t/e)*e);for(let e=a,t=s;e0?t.push(n<>g);break;case"ceiling":n=t.pop();t.push(Math.ceil(n));break;case"copy":n=t.pop();t.copy(n);break;case"cos":n=t.pop();t.push(Math.cos(n%360/180*Math.PI));break;case"cvi":n=0|t.pop();t.push(n);break;case"cvr":break;case"div":g=t.pop();n=t.pop();t.push(n/g);break;case"dup":t.copy(1);break;case"eq":g=t.pop();n=t.pop();t.push(n===g);break;case"exch":t.roll(2,1);break;case"exp":g=t.pop();n=t.pop();t.push(n**g);break;case"false":t.push(!1);break;case"floor":n=t.pop();t.push(Math.floor(n));break;case"ge":g=t.pop();n=t.pop();t.push(n>=g);break;case"gt":g=t.pop();n=t.pop();t.push(n>g);break;case"idiv":g=t.pop();n=t.pop();t.push(n/g|0);break;case"index":n=t.pop();t.index(n);break;case"le":g=t.pop();n=t.pop();t.push(n<=g);break;case"ln":n=t.pop();t.push(Math.log(n));break;case"log":n=t.pop();t.push(Math.log10(n));break;case"lt":g=t.pop();n=t.pop();t.push(n=t?new AstLiteral(t):e.max<=t?e:new AstMin(e,t)}class PostScriptCompiler{compile(e,t,i){const a=[],s=[],r=t.length>>1,n=i.length>>1;let g,o,c,C,h,l,Q,E,u=0;for(let e=0;et.min){g.unshift("Math.max(",r,", ");g.push(")")}if(n4){a=!0;t=0}else{a=!1;t=1}const o=[];for(r=0;r=0&&"ET"===gs[e];--e)gs[e]="EN";for(let e=r+1;e0&&(t=gs[r-1]);let i=h;e+1E&&isOdd(E)&&(d=E)}for(E=u;E>=d;--E){let e=-1;for(r=0,n=o.length;r=0){reverseValues(ns,e,r);e=-1}}else e<0&&(e=r);e>=0&&reverseValues(ns,e,o.length)}for(r=0,n=ns.length;r"!==e||(ns[r]="")}return createBidiText(ns.join(""),a)}const os={style:"normal",weight:"normal"},Is={style:"normal",weight:"bold"},cs={style:"italic",weight:"normal"},Cs={style:"italic",weight:"bold"},hs=new Map([["Times-Roman",{local:["Times New Roman","Times-Roman","Times","Liberation Serif","Nimbus Roman","Nimbus Roman L","Tinos","Thorndale","TeX Gyre Termes","FreeSerif","Linux Libertine O","Libertinus Serif","DejaVu Serif","Bitstream Vera Serif","Ubuntu"],style:os,ultimate:"serif"}],["Times-Bold",{alias:"Times-Roman",style:Is,ultimate:"serif"}],["Times-Italic",{alias:"Times-Roman",style:cs,ultimate:"serif"}],["Times-BoldItalic",{alias:"Times-Roman",style:Cs,ultimate:"serif"}],["Helvetica",{local:["Helvetica","Helvetica Neue","Arial","Arial Nova","Liberation Sans","Arimo","Nimbus Sans","Nimbus Sans L","A030","TeX Gyre Heros","FreeSans","DejaVu Sans","Albany","Bitstream Vera Sans","Arial Unicode MS","Microsoft Sans Serif","Apple Symbols","Cantarell"],path:"LiberationSans-Regular.ttf",style:os,ultimate:"sans-serif"}],["Helvetica-Bold",{alias:"Helvetica",path:"LiberationSans-Bold.ttf",style:Is,ultimate:"sans-serif"}],["Helvetica-Oblique",{alias:"Helvetica",path:"LiberationSans-Italic.ttf",style:cs,ultimate:"sans-serif"}],["Helvetica-BoldOblique",{alias:"Helvetica",path:"LiberationSans-BoldItalic.ttf",style:Cs,ultimate:"sans-serif"}],["Courier",{local:["Courier","Courier New","Liberation Mono","Nimbus Mono","Nimbus Mono L","Cousine","Cumberland","TeX Gyre Cursor","FreeMono","Linux Libertine Mono O","Libertinus Mono"],style:os,ultimate:"monospace"}],["Courier-Bold",{alias:"Courier",style:Is,ultimate:"monospace"}],["Courier-Oblique",{alias:"Courier",style:cs,ultimate:"monospace"}],["Courier-BoldOblique",{alias:"Courier",style:Cs,ultimate:"monospace"}],["ArialBlack",{local:["Arial Black"],style:{style:"normal",weight:"900"},fallback:"Helvetica-Bold"}],["ArialBlack-Bold",{alias:"ArialBlack"}],["ArialBlack-Italic",{alias:"ArialBlack",style:{style:"italic",weight:"900"},fallback:"Helvetica-BoldOblique"}],["ArialBlack-BoldItalic",{alias:"ArialBlack-Italic"}],["ArialNarrow",{local:["Arial Narrow","Liberation Sans Narrow","Helvetica Condensed","Nimbus Sans Narrow","TeX Gyre Heros Cn"],style:os,fallback:"Helvetica"}],["ArialNarrow-Bold",{alias:"ArialNarrow",style:Is,fallback:"Helvetica-Bold"}],["ArialNarrow-Italic",{alias:"ArialNarrow",style:cs,fallback:"Helvetica-Oblique"}],["ArialNarrow-BoldItalic",{alias:"ArialNarrow",style:Cs,fallback:"Helvetica-BoldOblique"}],["Calibri",{local:["Calibri","Carlito"],style:os,fallback:"Helvetica"}],["Calibri-Bold",{alias:"Calibri",style:Is,fallback:"Helvetica-Bold"}],["Calibri-Italic",{alias:"Calibri",style:cs,fallback:"Helvetica-Oblique"}],["Calibri-BoldItalic",{alias:"Calibri",style:Cs,fallback:"Helvetica-BoldOblique"}],["Wingdings",{local:["Wingdings","URW Dingbats"],style:os}],["Wingdings-Regular",{alias:"Wingdings"}],["Wingdings-Bold",{alias:"Wingdings"}]]),ls=new Map([["Arial-Black","ArialBlack"]]);function getFamilyName(e){const t=new Set(["thin","extralight","ultralight","demilight","semilight","light","book","regular","normal","medium","demibold","semibold","bold","extrabold","ultrabold","black","heavy","extrablack","ultrablack","roman","italic","oblique","ultracondensed","extracondensed","condensed","semicondensed","normal","semiexpanded","expanded","extraexpanded","ultraexpanded","bolditalic"]);return e.split(/[- ,+]+/g).filter((e=>!t.has(e.toLowerCase()))).join(" ")}function generateFont({alias:e,local:t,path:i,fallback:a,style:s,ultimate:r},n,g,o=!0,c=!0,C=""){const h={style:null,ultimate:null};if(t){const e=C?` ${C}`:"";for(const i of t)n.push(`local(${i}${e})`)}if(e){const t=hs.get(e),r=C||function getStyleToAppend(e){switch(e){case Is:return"Bold";case cs:return"Italic";case Cs:return"Bold Italic";default:if("bold"===e?.weight)return"Bold";if("italic"===e?.style)return"Italic"}return""}(s);Object.assign(h,generateFont(t,n,g,o&&!a,c&&!i,r))}s&&(h.style=s);r&&(h.ultimate=r);if(o&&a){const e=hs.get(a),{ultimate:t}=generateFont(e,n,g,o,c&&!i,C);h.ultimate||=t}c&&i&&g&&n.push(`url(${g}${i})`);return h}function getFontSubstitution(e,t,i,a,s,r){if(a.startsWith("InvalidPDFjsFont_"))return null;"TrueType"!==r&&"Type1"!==r||!/^[A-Z]{6}\+/.test(a)||(a=a.slice(7));const n=a=normalizeFontName(a);let g=e.get(n);if(g)return g;let o=hs.get(a);if(!o)for(const[e,t]of ls)if(a.startsWith(e)){a=`${t}${a.substring(e.length)}`;o=hs.get(a);break}let c=!1;if(!o){o=hs.get(s);c=!0}const C=`${t.getDocId()}_s${t.createFontId()}`;if(!o){if(!validateFontName(a)){warn(`Cannot substitute the font because of its name: ${a}`);e.set(n,null);return null}const t=/bold/gi.test(a),i=/oblique|italic/gi.test(a),s=t&&i&&Cs||t&&Is||i&&cs||os;g={css:`"${getFamilyName(a)}",${C}`,guessFallback:!0,loadedName:C,baseFontName:a,src:`local(${a})`,style:s};e.set(n,g);return g}const h=[];c&&validateFontName(a)&&h.push(`local(${a})`);const{style:l,ultimate:Q}=generateFont(o,h,i),E=null===Q,u=E?"":`,${Q}`;g={css:`"${getFamilyName(a)}",${C}${u}`,guessFallback:E,loadedName:C,baseFontName:a,src:h.join(","),style:l};e.set(n,g);return g}class ImageResizer{static#R=2048;static#y=FeatureTest.isImageDecoderSupported;constructor(e,t){this._imgData=e;this._isMask=t}static get canUseImageDecoder(){return shadow(this,"canUseImageDecoder",this.#y?ImageDecoder.isTypeSupported("image/bmp"):Promise.resolve(!1))}static needsToBeResized(e,t){if(e<=this.#R&&t<=this.#R)return!1;const{MAX_DIM:i}=this;if(e>i||t>i)return!0;const a=e*t;if(this._hasMaxArea)return a>this.MAX_AREA;if(a(this.MAX_AREA=this.#R**2)}static get MAX_DIM(){return shadow(this,"MAX_DIM",this._guessMax(2048,65537,0,1))}static get MAX_AREA(){this._hasMaxArea=!0;return shadow(this,"MAX_AREA",this._guessMax(this.#R,this.MAX_DIM,128,0)**2)}static set MAX_AREA(e){if(e>=0){this._hasMaxArea=!0;shadow(this,"MAX_AREA",e)}}static setOptions({canvasMaxAreaInBytes:e=-1,isImageDecoderSupported:t=!1}){this._hasMaxArea||(this.MAX_AREA=e>>2);this.#y=t}static _areGoodDims(e,t){try{const i=new OffscreenCanvas(e,t),a=i.getContext("2d");a.fillRect(0,0,1,1);const s=a.getImageData(0,0,1,1).data[3];i.width=i.height=1;return 0!==s}catch{return!1}}static _guessMax(e,t,i,a){for(;e+i+1pt){const e=this.#N();if(e)return e}const a=this._encodeBMP();let s,r;if(await ImageResizer.canUseImageDecoder){s=new ImageDecoder({data:a,type:"image/bmp",preferAnimation:!1,transfer:[a.buffer]});r=s.decode().catch((e=>{warn(`BMP image decoding failed: ${e}`);return createImageBitmap(new Blob([this._encodeBMP().buffer],{type:"image/bmp"}))})).finally((()=>{s.close()}))}else r=createImageBitmap(new Blob([a.buffer],{type:"image/bmp"}));const{MAX_AREA:n,MAX_DIM:g}=ImageResizer,o=Math.max(t/g,i/g,Math.sqrt(t*i/n)),c=Math.max(o,2),C=Math.round(10*(o+1.25))/10/c,h=Math.floor(Math.log2(C)),l=new Array(h+2).fill(2);l[0]=c;l.splice(-1,1,C/(1<>n,o=a>>n;let c,C=a;try{c=new Uint8Array(r)}catch{let e=Math.floor(Math.log2(r+1));for(;;)try{c=new Uint8Array(2**e-1);break}catch{e-=1}C=Math.floor((2**e-1)/(4*i));const t=i*C*4;t>n;e>3,n=i+3&-4;if(i!==n){const e=new Uint8Array(n*t);let a=0;for(let r=0,g=t*i;r>>8;t[i++]=255&s}}}else{if(!ArrayBuffer.isView(e))throw new Error("Invalid data format, must be a string or TypedArray.");t=e.slice();i=t.byteLength}const a=i>>2,s=i-4*a,r=new Uint32Array(t.buffer,0,a);let n=0,g=0,o=this.h1,c=this.h2;const C=3432918353,h=461845907,l=11601,Q=13715;for(let e=0;e>>17;n=n*h&Qs|n*Q&Es;o^=n;o=o<<13|o>>>19;o=5*o+3864292196}else{g=r[e];g=g*C&Qs|g*l&Es;g=g<<15|g>>>17;g=g*h&Qs|g*Q&Es;c^=g;c=c<<13|c>>>19;c=5*c+3864292196}n=0;switch(s){case 3:n^=t[4*a+2]<<16;case 2:n^=t[4*a+1]<<8;case 1:n^=t[4*a];n=n*C&Qs|n*l&Es;n=n<<15|n>>>17;n=n*h&Qs|n*Q&Es;1&a?o^=n:c^=n}this.h1=o;this.h2=c}hexdigest(){let e=this.h1,t=this.h2;e^=t>>>1;e=3981806797*e&Qs|36045*e&Es;t=4283543511*t&Qs|(2950163797*(t<<16|e>>>16)&Qs)>>>16;e^=t>>>1;e=444984403*e&Qs|60499*e&Es;t=3301882366*t&Qs|(3120437893*(t<<16|e>>>16)&Qs)>>>16;e^=t>>>1;return(e>>>0).toString(16).padStart(8,"0")+(t>>>0).toString(16).padStart(8,"0")}}function addState(e,t,i,a,s){let r=e;for(let e=0,i=t.length-1;e1e3){c=Math.max(c,l);Q+=h+2;l=0;h=0}C.push({transform:t,x:l,y:Q,w:i.width,h:i.height});l+=i.width+2;h=Math.max(h,i.height)}const E=Math.max(c,l)+1,u=Q+h+1,d=new Uint8Array(E*u*4),f=E<<2;for(let e=0;e=0;){t[r-4]=t[r];t[r-3]=t[r+1];t[r-2]=t[r+2];t[r-1]=t[r+3];t[r+i]=t[r+i-4];t[r+i+1]=t[r+i-3];t[r+i+2]=t[r+i-2];t[r+i+3]=t[r+i-1];r-=f}}const p={width:E,height:u};if(e.isOffscreenCanvasSupported){const e=new OffscreenCanvas(E,u);e.getContext("2d").putImageData(new ImageData(new Uint8ClampedArray(d.buffer),E,u),0,0);p.bitmap=e.transferToImageBitmap();p.data=null}else{p.kind=S;p.data=d}i.splice(r,4*o,$e);a.splice(r,4*o,[p,C]);return r+1}));addState(us,[MA,xA,Ze,UA],null,(function iterateImageMaskGroup(e,t){const i=e.fnArray,a=(t-(e.iCurr-3))%4;switch(a){case 0:return i[t]===MA;case 1:return i[t]===xA;case 2:return i[t]===Ze;case 3:return i[t]===UA}throw new Error(`iterateImageMaskGroup - invalid pos: ${a}`)}),(function foundImageMaskGroup(e,t){const i=e.fnArray,a=e.argsArray,s=e.iCurr,r=s-3,n=s-2,g=s-1;let o=Math.floor((t-r)/4);if(o<10)return t-(t-r)%4;let c,C,h=!1;const l=a[g][0],Q=a[n][0],E=a[n][1],u=a[n][2],d=a[n][3];if(E===u){h=!0;c=n+4;let e=g+4;for(let t=1;t=4&&i[r-4]===i[n]&&i[r-3]===i[g]&&i[r-2]===i[o]&&i[r-1]===i[c]&&a[r-4][0]===C&&a[r-4][1]===h){l++;Q-=5}let E=Q+4;for(let e=1;e=i)break}a=(a||us)[e[t]];if(a&&!Array.isArray(a)){r.iCurr=t;t++;if(!a.checkFn||(0,a.checkFn)(r)){s=a;a=null}else a=null}else t++}this.state=a;this.match=s;this.lastProcessed=t}flush(){for(;this.match;){const e=this.queue.fnArray.length;this.lastProcessed=(0,this.match.processFn)(this.context,e);this.match=null;this.state=null;this._optimize()}}reset(){this.state=null;this.match=null;this.lastProcessed=0}}class OperatorList{static CHUNK_SIZE=1e3;static CHUNK_SIZE_ABOUT=this.CHUNK_SIZE-5;constructor(e=0,t){this._streamSink=t;this.fnArray=[];this.argsArray=[];this.optimizer=!t||e&E?new NullOptimizer(this):new QueueOptimizer(this);this.dependencies=new Set;this._totalLength=0;this.weight=0;this._resolved=t?null:Promise.resolve()}set isOffscreenCanvasSupported(e){this.optimizer.isOffscreenCanvasSupported=e}get length(){return this.argsArray.length}get ready(){return this._resolved||this._streamSink.ready}get totalLength(){return this._totalLength+this.length}addOp(e,t){this.optimizer.push(e,t);this.weight++;this._streamSink&&(this.weight>=OperatorList.CHUNK_SIZE||this.weight>=OperatorList.CHUNK_SIZE_ABOUT&&(e===UA||e===ee))&&this.flush()}addImageOps(e,t,i,a=!1){if(a){this.addOp(MA);this.addOp(GA,[[["SMask",!1]]])}void 0!==i&&this.addOp(Ye,["OC",i]);this.addOp(e,t);void 0!==i&&this.addOp(ve,[]);a&&this.addOp(UA)}addDependency(e){if(!this.dependencies.has(e)){this.dependencies.add(e);this.addOp(wA,[e])}}addDependencies(e){for(const t of e)this.addDependency(t)}addOpList(e){if(e instanceof OperatorList){for(const t of e.dependencies)this.dependencies.add(t);for(let t=0,i=e.length;ta&&(e=a);return e}function resizeImageMask(e,t,i,a,s,r){const n=s*r;let g;g=t<=8?new Uint8Array(n):t<=16?new Uint16Array(n):new Uint32Array(n);const o=i/s,c=a/r;let C,h,l,Q,E=0;const u=new Uint16Array(s),d=i;for(C=0;C0&&Number.isInteger(i.height)&&i.height>0&&(i.width!==l||i.height!==Q)){warn("PDFImage - using the Width/Height of the image data, rather than the image dictionary.");l=i.width;Q=i.height}if(l<1||Q<1)throw new FormatError(`Invalid image width: ${l} or height: ${Q}`);this.width=l;this.height=Q;this.interpolate=c.get("I","Interpolate");this.imageMask=c.get("IM","ImageMask")||!1;this.matte=c.get("Matte")||!1;let E=i.bitsPerComponent;if(!E){E=c.get("BPC","BitsPerComponent");if(!E){if(!this.imageMask)throw new FormatError(`Bits per component missing in image: ${this.imageMask}`);E=1}}this.bpc=E;if(!this.imageMask){let s=c.getRaw("CS")||c.getRaw("ColorSpace");const r=!!s;if(r)this.jpxDecoderOptions?.smaskInData&&(s=Name.get("DeviceRGBA"));else if(this.jpxDecoderOptions)s=Name.get("DeviceRGBA");else switch(i.numComps){case 1:s=Name.get("DeviceGray");break;case 3:s=Name.get("DeviceRGB");break;case 4:s=Name.get("DeviceCMYK");break;default:throw new Error(`Images with ${i.numComps} color components not supported.`)}this.colorSpace=ColorSpace.parse({cs:s,xref:e,resources:a?t:null,pdfFunctionFactory:g,localColorSpaceCache:o});this.numComps=this.colorSpace.numComps;if(this.jpxDecoderOptions){this.jpxDecoderOptions.numComponents=r?this.numComp:0;this.jpxDecoderOptions.isIndexedColormap="Indexed"===this.colorSpace.name}}this.decode=c.getArray("D","Decode");this.needsDecode=!1;if(this.decode&&(this.colorSpace&&!this.colorSpace.isDefaultDecode(this.decode,E)||n&&!ColorSpace.isDefaultDecode(this.decode,1))){this.needsDecode=!0;const e=(1<>3)*i,g=e.byteLength;let o,c;if(!a||s&&!(n===g))if(s){o=new Uint8Array(n);o.set(e);o.fill(255,g)}else o=new Uint8Array(e);else o=e;if(s)for(c=0;c>7&1;n[l+1]=h>>6&1;n[l+2]=h>>5&1;n[l+3]=h>>4&1;n[l+4]=h>>3&1;n[l+5]=h>>2&1;n[l+6]=h>>1&1;n[l+7]=1&h;l+=8}if(l>=1}}}}else{let i=0;h=0;for(l=0,C=r;l>a;s<0?s=0:s>c&&(s=c);n[l]=s;h&=(1<n[a+1]){t=255;break}}g[C]=t}}}if(g)for(C=0,l=3,h=t*a;C>3,C=t&&ImageResizer.needsToBeResized(i,a);if(!this.smask&&!this.mask&&"DeviceRGBA"===this.colorSpace.name){s.kind=S;const e=s.data=await this.getImageBytes(g*n*4,{});return t?C?ImageResizer.createImage(s,!1):this.createBitmap(S,i,a,e):s}if(!e){let e;"DeviceGray"===this.colorSpace.name&&1===o?e=b:"DeviceRGB"!==this.colorSpace.name||8!==o||this.needsDecode||(e=F);if(e&&!this.smask&&!this.mask&&i===n&&a===g){const r=await this.#G(n,g);if(r)return r;const o=await this.getImageBytes(g*c,{});if(t)return C?ImageResizer.createImage({data:o,kind:e,width:i,height:a,interpolate:this.interpolate},this.needsDecode):this.createBitmap(e,n,g,o);s.kind=e;s.data=o;if(this.needsDecode){assert(e===b,"PDFImage.createImageData: The image must be grayscale.");const t=s.data;for(let e=0,i=t.length;e>3,n=await this.getImageBytes(a*r,{internal:!0}),g=this.getComponents(n);let o,c;if(1===s){c=i*a;if(this.needsDecode)for(o=0;o0&&t.args[0].count++}class TimeSlotManager{static TIME_SLOT_DURATION_MS=20;static CHECK_TIME_EVERY=100;constructor(){this.reset()}check(){if(++this.checkedh){const e="Image exceeded maximum allowed size and was removed.";if(this.options.ignoreErrors){warn(e);return}throw new Error(e)}let l;g.has("OC")&&(l=await this.parseMarkedContentProps(g.get("OC"),e));let Q,E;if(g.get("IM","ImageMask")||!1){const e=g.get("I","Interpolate"),i=c+7>>3,n=t.getBytes(i*C),h=g.getArray("D","Decode");if(this.parsingType3Font){Q=PDFImage.createRawMask({imgArray:n,width:c,height:C,imageIsFromDecodeStream:t instanceof DecodeStream,inverseDecode:h?.[0]>0,interpolate:e});Q.cached=!!s;E=[Q];a.addImageOps(Ze,E,l);if(s){const e={fn:Ze,args:E,optionalContent:l};r.set(s,o,e);o&&this._regionalImageCache.set(null,o,e)}return}Q=await PDFImage.createMask({imgArray:n,width:c,height:C,imageIsFromDecodeStream:t instanceof DecodeStream,inverseDecode:h?.[0]>0,interpolate:e,isOffscreenCanvasSupported:this.options.isOffscreenCanvasSupported});if(Q.isSingleOpaquePixel){a.addImageOps(tt,[],l);if(s){const e={fn:tt,args:[],optionalContent:l};r.set(s,o,e);o&&this._regionalImageCache.set(null,o,e)}return}const u=`mask_${this.idFactory.createObjId()}`;a.addDependency(u);Q.dataLen=Q.bitmap?Q.width*Q.height*4:Q.data.length;this._sendImgData(u,Q);E=[{data:u,width:Q.width,height:Q.height,interpolate:Q.interpolate,count:1}];a.addImageOps(Ze,E,l);if(s){const e={objId:u,fn:Ze,args:E,optionalContent:l};r.set(s,o,e);o&&this._regionalImageCache.set(null,o,e)}return}const u=g.has("SMask")||g.has("Mask");if(i&&c+C<200&&!u){try{const s=new PDFImage({xref:this.xref,res:e,image:t,isInline:i,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:n});Q=await s.createImageData(!0,!1);a.isOffscreenCanvasSupported=this.options.isOffscreenCanvasSupported;a.addImageOps(_e,[Q],l)}catch(e){const t=`Unable to decode inline image: "${e}".`;if(!this.options.ignoreErrors)throw new Error(t);warn(t)}return}let d=`img_${this.idFactory.createObjId()}`,f=!1;if(this.parsingType3Font)d=`${this.idFactory.getDocId()}_type3_${d}`;else if(s&&o){f=this.globalImageCache.shouldCache(o,this.pageIndex);if(f){assert(!i,"Cannot cache an inline image globally.");d=`${this.idFactory.getDocId()}_${d}`}}a.addDependency(d);E=[d,c,C];a.addImageOps(ze,E,l,u);if(f){if(this.globalImageCache.hasDecodeFailed(o)){this.globalImageCache.setData(o,{objId:d,fn:ze,args:E,optionalContent:l,hasMask:u,byteSize:0});this._sendImgData(d,null,f);return}if(c*C>25e4||u){const e=await this.handler.sendWithPromise("commonobj",[d,"CopyLocalImage",{imageRef:o}]);if(e){this.globalImageCache.setData(o,{objId:d,fn:ze,args:E,optionalContent:l,hasMask:u,byteSize:0});this.globalImageCache.addByteSize(o,e);return}}}PDFImage.buildImage({xref:this.xref,res:e,image:t,isInline:i,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:n}).then((async e=>{Q=await e.createImageData(!1,this.options.isOffscreenCanvasSupported);Q.dataLen=Q.bitmap?Q.width*Q.height*4:Q.data.length;Q.ref=o;f&&this.globalImageCache.addByteSize(o,Q.dataLen);return this._sendImgData(d,Q,f)})).catch((e=>{warn(`Unable to decode image "${d}": "${e}".`);o&&this.globalImageCache.addDecodeFailed(o);return this._sendImgData(d,null,f)}));if(s){const e={objId:d,fn:ze,args:E,optionalContent:l,hasMask:u};r.set(s,o,e);if(o){this._regionalImageCache.set(null,o,e);f&&this.globalImageCache.setData(o,{objId:d,fn:ze,args:E,optionalContent:l,hasMask:u,byteSize:0})}}}handleSMask(e,t,i,a,s,r){const n=e.get("G"),g={subtype:e.get("S").name,backdrop:e.get("BC")},o=e.get("TR");if(isPDFFunction(o)){const e=this._pdfFunctionFactory.create(o),t=new Uint8Array(256),i=new Float32Array(1);for(let a=0;a<256;a++){i[0]=a/255;e(i,0,i,0);t[a]=255*i[0]|0}g.transferMap=t}return this.buildFormXObject(t,n,g,i,a,s.state.clone(),r)}handleTransferFunction(e){let t;if(Array.isArray(e))t=e;else{if(!isPDFFunction(e))return null;t=[e]}const i=[];let a=0,s=0;for(const e of t){const t=this.xref.fetchIfRef(e);a++;if(isName(t,"Identity")){i.push(null);continue}if(!isPDFFunction(t))return null;const r=this._pdfFunctionFactory.create(t),n=new Uint8Array(256),g=new Float32Array(1);for(let e=0;e<256;e++){g[0]=e/255;r(g,0,g,0);n[e]=255*g[0]|0}i.push(n);s++}return 1!==a&&4!==a||0===s?null:i}handleTilingType(e,t,i,a,s,r,n,g){const o=new OperatorList,c=Dict.merge({xref:this.xref,dictArray:[s.get("Resources"),i]});return this.getOperatorList({stream:a,task:n,resources:c,operatorList:o}).then((function(){const i=o.getIR(),a=getTilingPatternIR(i,s,t);r.addDependencies(o.dependencies);r.addOp(e,a);s.objId&&g.set(null,s.objId,{operatorListIR:i,dict:s})})).catch((e=>{if(!(e instanceof AbortException)){if(!this.options.ignoreErrors)throw e;warn(`handleTilingType - ignoring pattern: "${e}".`)}}))}async handleSetFont(e,t,i,a,s,r,n=null,g=null){const o=t?.[0]instanceof Name?t[0].name:null;let c=await this.loadFont(o,i,e,n,g);if(c.font.isType3Font)try{await c.loadType3Data(this,e,s);a.addDependencies(c.type3Dependencies)}catch(e){c=new TranslatedFont({loadedName:"g_font_error",font:new ErrorFont(`Type3 font load error: ${e}`),dict:c.font,evaluatorOptions:this.options})}r.font=c.font;c.send(this.handler);return c.loadedName}handleText(e,t){const i=t.font,a=i.charsToGlyphs(e);if(i.data){(!!(t.textRenderingMode&D)||"Pattern"===t.fillColorSpace.name||i.disableFontFace||this.options.disableFontFace)&&PartialEvaluator.buildFontPaths(i,a,this.handler,this.options)}return a}ensureStateFont(e){if(e.font)return;const t=new FormatError("Missing setFont (Tf) operator before text rendering operator.");if(!this.options.ignoreErrors)throw t;warn(`ensureStateFont: "${t}".`)}async setGState({resources:e,gState:t,operatorList:i,cacheKey:a,task:s,stateManager:r,localGStateCache:n,localColorSpaceCache:g}){const o=t.objId;let c=!0;const C=[];let h=Promise.resolve();for(const a of t.getKeys()){const n=t.get(a);switch(a){case"Type":break;case"LW":case"LC":case"LJ":case"ML":case"D":case"RI":case"FL":case"CA":case"ca":C.push([a,n]);break;case"Font":c=!1;h=h.then((()=>this.handleSetFont(e,null,n[0],i,s,r.state).then((function(e){i.addDependency(e);C.push([a,[e,n[1]]])}))));break;case"BM":C.push([a,normalizeBlendMode(n)]);break;case"SMask":if(isName(n,"None")){C.push([a,!1]);break}if(n instanceof Dict){c=!1;h=h.then((()=>this.handleSMask(n,e,i,s,r,g)));C.push([a,!0])}else warn("Unsupported SMask type");break;case"TR":const t=this.handleTransferFunction(n);C.push([a,t]);break;case"OP":case"op":case"OPM":case"BG":case"BG2":case"UCR":case"UCR2":case"TR2":case"HT":case"SM":case"SA":case"AIS":case"TK":info("graphic state operator "+a);break;default:info("Unknown graphic state operator "+a)}}await h;C.length>0&&i.addOp(GA,[C]);c&&n.set(a,o,C)}loadFont(e,t,i,a=null,s=null){const errorFont=async()=>new TranslatedFont({loadedName:"g_font_error",font:new ErrorFont(`Font "${e}" is not available.`),dict:t,evaluatorOptions:this.options});let r;if(t)t instanceof Ref&&(r=t);else{const t=i.get("Font");t&&(r=t.getRaw(e))}if(r){if(this.type3FontRefs?.has(r))return errorFont();if(this.fontCache.has(r))return this.fontCache.get(r);try{t=this.xref.fetchIfRef(r)}catch(e){warn(`loadFont - lookup failed: "${e}".`)}}if(!(t instanceof Dict)){if(!this.options.ignoreErrors&&!this.parsingType3Font){warn(`Font "${e}" is not available.`);return errorFont()}warn(`Font "${e}" is not available -- attempting to fallback to a default font.`);t=a||PartialEvaluator.fallbackFontDict}if(t.cacheKey&&this.fontCache.has(t.cacheKey))return this.fontCache.get(t.cacheKey);const{promise:n,resolve:g}=Promise.withResolvers();let o;try{o=this.preEvaluateFont(t);o.cssFontInfo=s}catch(e){warn(`loadFont - preEvaluateFont failed: "${e}".`);return errorFont()}const{descriptor:c,hash:C}=o,h=r instanceof Ref;let l;if(C&&c instanceof Dict){const e=c.fontAliases||=Object.create(null);if(e[C]){const t=e[C].aliasRef;if(h&&t&&this.fontCache.has(t)){this.fontCache.putAlias(r,t);return this.fontCache.get(r)}}else e[C]={fontID:this.idFactory.createFontId()};h&&(e[C].aliasRef=r);l=e[C].fontID}else l=this.idFactory.createFontId();assert(l?.startsWith("f"),'The "fontID" must be (correctly) defined.');if(h)this.fontCache.put(r,n);else{t.cacheKey=`cacheKey_${l}`;this.fontCache.put(t.cacheKey,n)}t.loadedName=`${this.idFactory.getDocId()}_${l}`;this.translateFont(o).then((e=>{g(new TranslatedFont({loadedName:t.loadedName,font:e,dict:t,evaluatorOptions:this.options}))})).catch((e=>{warn(`loadFont - translateFont failed: "${e}".`);g(new TranslatedFont({loadedName:t.loadedName,font:new ErrorFont(e instanceof Error?e.message:e),dict:t,evaluatorOptions:this.options}))}));return n}buildPath(e,t,i,a=!1){const s=e.length-1;i||(i=[]);if(s<0||e.fnArray[s]!==it){if(a){warn(`Encountered path operator "${t}" inside of a text object.`);e.addOp(MA,null)}let s;switch(t){case TA:const e=i[0]+i[2],t=i[1]+i[3];s=[Math.min(i[0],e),Math.min(i[1],t),Math.max(i[0],e),Math.max(i[1],t)];break;case LA:case HA:s=[i[0],i[1],i[0],i[1]];break;default:s=[1/0,1/0,-1/0,-1/0]}e.addOp(it,[[t],i,s]);a&&e.addOp(UA,null)}else{const a=e.argsArray[s];a[0].push(t);a[1].push(...i);const r=a[2];switch(t){case TA:const e=i[0]+i[2],t=i[1]+i[3];r[0]=Math.min(r[0],i[0],e);r[1]=Math.min(r[1],i[1],t);r[2]=Math.max(r[2],i[0],e);r[3]=Math.max(r[3],i[1],t);break;case LA:case HA:r[0]=Math.min(r[0],i[0]);r[1]=Math.min(r[1],i[1]);r[2]=Math.max(r[2],i[0]);r[3]=Math.max(r[3],i[1])}}}parseColorSpace({cs:e,resources:t,localColorSpaceCache:i}){return ColorSpace.parseAsync({cs:e,xref:this.xref,resources:t,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:i}).catch((e=>{if(e instanceof AbortException)return null;if(this.options.ignoreErrors){warn(`parseColorSpace - ignoring ColorSpace: "${e}".`);return null}throw e}))}parseShading({shading:e,resources:t,localColorSpaceCache:i,localShadingPatternCache:a}){let s,r=a.get(e);if(r)return r;try{s=Pattern.parseShading(e,this.xref,t,this._pdfFunctionFactory,i).getIR()}catch(t){if(t instanceof AbortException)return null;if(this.options.ignoreErrors){warn(`parseShading - ignoring shading: "${t}".`);a.set(e,null);return null}throw t}r=`pattern_${this.idFactory.createObjId()}`;this.parsingType3Font&&(r=`${this.idFactory.getDocId()}_type3_${r}`);a.set(e,r);this.parsingType3Font?this.handler.send("commonobj",[r,"Pattern",s]):this.handler.send("obj",[r,this.pageIndex,"Pattern",s]);return r}handleColorN(e,t,i,a,s,r,n,g,o,c){const C=i.pop();if(C instanceof Name){const h=s.getRaw(C.name),l=h instanceof Ref&&o.getByRef(h);if(l)try{const s=a.base?a.base.getRgb(i,0):null,r=getTilingPatternIR(l.operatorListIR,l.dict,s);e.addOp(t,r);return}catch{}const Q=this.xref.fetchIfRef(h);if(Q){const s=Q instanceof BaseStream?Q.dict:Q,C=s.get("PatternType");if(C===fs){const g=a.base?a.base.getRgb(i,0):null;return this.handleTilingType(t,g,r,Q,s,e,n,o)}if(C===ps){const i=s.get("Shading"),a=this.parseShading({shading:i,resources:r,localColorSpaceCache:g,localShadingPatternCache:c});if(a){const i=lookupMatrix(s.getArray("Matrix"),null);e.addOp(t,["Shading",a,i])}return}throw new FormatError(`Unknown PatternType: ${C}`)}}throw new FormatError(`Unknown PatternName: ${C}`)}_parseVisibilityExpression(e,t,i){if(++t>10){warn("Visibility expression is too deeply nested");return}const a=e.length,s=this.xref.fetchIfRef(e[0]);if(!(a<2)&&s instanceof Name){switch(s.name){case"And":case"Or":case"Not":i.push(s.name);break;default:warn(`Invalid operator ${s.name} in visibility expression`);return}for(let s=1;s0)return{type:"OCMD",expression:t}}const t=i.get("OCGs");if(Array.isArray(t)||t instanceof Dict){const e=[];if(Array.isArray(t))for(const i of t)e.push(i.toString());else e.push(t.objId);return{type:a,ids:e,policy:i.get("P")instanceof Name?i.get("P").name:null,expression:null}}if(t instanceof Ref)return{type:a,id:t.toString()}}return null}getOperatorList({stream:e,task:t,resources:i,operatorList:a,initialState:s=null,fallbackFontDict:r=null}){i||=Dict.empty;s||=new EvalState;if(!a)throw new Error('getOperatorList: missing "operatorList" parameter');const n=this,g=this.xref;let o=!1;const c=new LocalImageCache,C=new LocalColorSpaceCache,h=new LocalGStateCache,l=new LocalTilingPatternCache,Q=new Map,E=i.get("XObject")||Dict.empty,u=i.get("Pattern")||Dict.empty,d=new StateManager(s),f=new EvaluatorPreprocessor(e,g,d),p=new TimeSlotManager;function closePendingRestoreOPS(e){for(let e=0,t=f.savedStatesDepth;e0&&a.addOp(GA,[t]);e=null;continue}}next(new Promise((function(e,s){if(!S)throw new FormatError("GState must be referred to by name.");const r=i.get("ExtGState");if(!(r instanceof Dict))throw new FormatError("ExtGState should be a dictionary.");const g=r.get(F);if(!(g instanceof Dict))throw new FormatError("GState should be a dictionary.");n.setGState({resources:i,gState:g,operatorList:a,cacheKey:F,task:t,stateManager:d,localGStateCache:h,localColorSpaceCache:C}).then(e,s)})).catch((function(e){if(!(e instanceof AbortException)){if(!n.options.ignoreErrors)throw e;warn(`getOperatorList - ignoring ExtGState: "${e}".`)}})));return;case LA:case HA:case JA:case YA:case vA:case KA:case TA:n.buildPath(a,s,e,o);continue;case Le:case He:case Ke:case Te:continue;case Ye:if(!(e[0]instanceof Name)){warn(`Expected name for beginMarkedContentProps arg0=${e[0]}`);a.addOp(Ye,["OC",null]);continue}if("OC"===e[0].name){next(n.parseMarkedContentProps(e[1],i).then((e=>{a.addOp(Ye,["OC",e])})).catch((e=>{if(!(e instanceof AbortException)){if(!n.options.ignoreErrors)throw e;warn(`getOperatorList - ignoring beginMarkedContentProps: "${e}".`);a.addOp(Ye,["OC",null])}})));return}e=[e[0].name,e[1]instanceof Dict?e[1].get("MCID"):null];break;default:if(null!==e){for(w=0,D=e.length;w{if(!(e instanceof AbortException)){if(!this.options.ignoreErrors)throw e;warn(`getOperatorList - ignoring errors during "${t.name}" task: "${e}".`);closePendingRestoreOPS()}}))}getTextContent({stream:e,task:t,resources:s,stateManager:r=null,includeMarkedContent:n=!1,sink:g,seenStyles:o=new Set,viewBox:c,lang:C=null,markedContentData:h=null,disableNormalization:l=!1,keepWhiteSpace:Q=!1}){s||=Dict.empty;r||=new StateManager(new TextState);n&&(h||={level:0});const E={items:[],styles:Object.create(null),lang:C},u={initialized:!1,str:[],totalWidth:0,totalHeight:0,width:0,height:0,vertical:!1,prevTransform:null,textAdvanceScale:0,spaceInFlowMin:0,spaceInFlowMax:0,trackingSpaceMin:1/0,negativeSpaceMax:-1/0,notASpace:-1/0,transform:null,fontName:null,hasEOL:!1},d=[" "," "];let f=0;function saveLastChar(e){const t=(f+1)%2,i=" "!==d[f]&&" "===d[t];d[f]=e;f=t;return!Q&&i}function shouldAddWhitepsace(){return!Q&&" "!==d[f]&&" "===d[(f+1)%2]}function resetLastChars(){d[0]=d[1]=" ";f=0}const p=this,m=this.xref,y=[];let w=null;const D=new LocalImageCache,b=new LocalGStateCache,F=new EvaluatorPreprocessor(e,m,r);let S;function pushWhitespace({width:e=0,height:t=0,transform:i=u.prevTransform,fontName:a=u.fontName}){E.items.push({str:" ",dir:"ltr",width:e,height:t,transform:i,fontName:a,hasEOL:!1})}function getCurrentTextTransform(){const e=S.font,t=[S.fontSize*S.textHScale,0,0,S.fontSize,0,S.textRise];if(e.isType3Font&&(S.fontSize<=1||e.isCharBBox)&&!isArrayEqual(S.fontMatrix,a)){const i=e.bbox[3]-e.bbox[1];i>0&&(t[3]*=i*S.fontMatrix[3])}return Util.transform(S.ctm,Util.transform(S.textMatrix,t))}function ensureTextContentItem(){if(u.initialized)return u;const{font:e,loadedName:t}=S;if(!o.has(t)){o.add(t);E.styles[t]={fontFamily:e.fallbackName,ascent:e.ascent,descent:e.descent,vertical:e.vertical};if(p.options.fontExtraProperties&&e.systemFontInfo){const i=E.styles[t];i.fontSubstitution=e.systemFontInfo.css;i.fontSubstitutionLoadedName=e.systemFontInfo.loadedName}}u.fontName=t;const i=u.transform=getCurrentTextTransform();if(e.vertical){u.width=u.totalWidth=Math.hypot(i[0],i[1]);u.height=u.totalHeight=0;u.vertical=!0}else{u.width=u.totalWidth=0;u.height=u.totalHeight=Math.hypot(i[2],i[3]);u.vertical=!1}const a=Math.hypot(S.textLineMatrix[0],S.textLineMatrix[1]),s=Math.hypot(S.ctm[0],S.ctm[1]);u.textAdvanceScale=s*a;const{fontSize:r}=S;u.trackingSpaceMin=.102*r;u.notASpace=.03*r;u.negativeSpaceMax=-.2*r;u.spaceInFlowMin=.102*r;u.spaceInFlowMax=.6*r;u.hasEOL=!1;u.initialized=!0;return u}function updateAdvanceScale(){if(!u.initialized)return;const e=Math.hypot(S.textLineMatrix[0],S.textLineMatrix[1]),t=Math.hypot(S.ctm[0],S.ctm[1])*e;if(t!==u.textAdvanceScale){if(u.vertical){u.totalHeight+=u.height*u.textAdvanceScale;u.height=0}else{u.totalWidth+=u.width*u.textAdvanceScale;u.width=0}u.textAdvanceScale=t}}function runBidiTransform(e){let t=e.str.join("");l||(t=function normalizeUnicode(e){if(!Ct){Ct=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu;ht=new Map([["ſt","ſt"]])}return e.replaceAll(Ct,((e,t,i)=>t?t.normalize("NFKC"):ht.get(i)))}(t));const i=bidi(t,-1,e.vertical);return{str:i.str,dir:i.dir,width:Math.abs(e.totalWidth),height:Math.abs(e.totalHeight),transform:e.transform,fontName:e.fontName,hasEOL:e.hasEOL}}async function handleSetFont(e,i){const r=await p.loadFont(e,i,s);if(r.font.isType3Font)try{await r.loadType3Data(p,s,t)}catch{}S.loadedName=r.loadedName;S.font=r.font;S.fontMatrix=r.font.fontMatrix||a}function applyInverseRotation(e,t,i){const a=Math.hypot(i[0],i[1]);return[(i[0]*e+i[1]*t)/a,(i[2]*e+i[3]*t)/a]}function compareWithLastPosition(e){const t=getCurrentTextTransform();let i=t[4],a=t[5];if(S.font?.vertical){if(ic[2]||a+ec[3])return!1}else if(i+ec[2]||ac[3])return!1;if(!S.font||!u.prevTransform)return!0;let s=u.prevTransform[4],r=u.prevTransform[5];if(s===i&&r===a)return!0;let n=-1;t[0]&&0===t[1]&&0===t[2]?n=t[0]>0?0:180:t[1]&&0===t[0]&&0===t[3]&&(n=t[1]>0?90:270);switch(n){case 0:break;case 90:[i,a]=[a,i];[s,r]=[r,s];break;case 180:[i,a,s,r]=[-i,-a,-s,-r];break;case 270:[i,a]=[-a,-i];[s,r]=[-r,-s];break;default:[i,a]=applyInverseRotation(i,a,t);[s,r]=applyInverseRotation(s,r,u.prevTransform)}if(S.font.vertical){const e=(r-a)/u.textAdvanceScale,t=i-s,n=Math.sign(u.height);if(e.5*u.width){appendEOL();return!0}resetLastChars();flushTextContentItem();return!0}if(Math.abs(t)>u.width){appendEOL();return!0}e<=n*u.notASpace&&resetLastChars();if(e<=n*u.trackingSpaceMin)if(shouldAddWhitepsace()){resetLastChars();flushTextContentItem();pushWhitespace({height:Math.abs(e)})}else u.height+=e;else if(!addFakeSpaces(e,u.prevTransform,n))if(0===u.str.length){resetLastChars();pushWhitespace({height:Math.abs(e)})}else u.height+=e;Math.abs(t)>.25*u.width&&flushTextContentItem();return!0}const g=(i-s)/u.textAdvanceScale,o=a-r,C=Math.sign(u.width);if(g.5*u.height){appendEOL();return!0}resetLastChars();flushTextContentItem();return!0}if(Math.abs(o)>u.height){appendEOL();return!0}g<=C*u.notASpace&&resetLastChars();if(g<=C*u.trackingSpaceMin)if(shouldAddWhitepsace()){resetLastChars();flushTextContentItem();pushWhitespace({width:Math.abs(g)})}else u.width+=g;else if(!addFakeSpaces(g,u.prevTransform,C))if(0===u.str.length){resetLastChars();pushWhitespace({width:Math.abs(g)})}else u.width+=g;Math.abs(o)>.25*u.height&&flushTextContentItem();return!0}function buildTextContentItem({chars:e,extraSpacing:t}){const i=S.font;if(!e){const e=S.charSpacing+t;e&&(i.vertical?S.translateTextMatrix(0,-e):S.translateTextMatrix(e*S.textHScale,0));Q&&compareWithLastPosition(0);return}const a=i.charsToGlyphs(e),s=S.fontMatrix[0]*S.fontSize;for(let e=0,r=a.length;e0){const e=y.join("");y.length=0;buildTextContentItem({chars:e,extraSpacing:0})}break;case he:if(!r.state.font){p.ensureStateFont(r.state);continue}buildTextContentItem({chars:N[0],extraSpacing:0});break;case Be:if(!r.state.font){p.ensureStateFont(r.state);continue}S.carriageReturn();buildTextContentItem({chars:N[0],extraSpacing:0});break;case Qe:if(!r.state.font){p.ensureStateFont(r.state);continue}S.wordSpacing=N[0];S.charSpacing=N[1];S.carriageReturn();buildTextContentItem({chars:N[2],extraSpacing:0});break;case xe:flushTextContentItem();w??=s.get("XObject")||Dict.empty;R=N[0]instanceof Name;f=N[0].name;if(R&&D.getByName(f))break;next(new Promise((function(e,i){if(!R)throw new FormatError("XObject must be referred to by name.");let a=w.getRaw(f);if(a instanceof Ref){if(D.getByRef(a)){e();return}if(p.globalImageCache.getData(a,p.pageIndex)){e();return}a=m.fetch(a)}if(!(a instanceof BaseStream))throw new FormatError("XObject should be a stream");const E=a.dict.get("Subtype");if(!(E instanceof Name))throw new FormatError("XObject should have a Name subtype");if("Form"!==E.name){D.set(f,a.dict.objId,!0);e();return}const u=r.state.clone(),d=new StateManager(u),y=lookupMatrix(a.dict.getArray("Matrix"),null);y&&d.transform(y);enqueueChunk();const b={enqueueInvoked:!1,enqueue(e,t){this.enqueueInvoked=!0;g.enqueue(e,t)},get desiredSize(){return g.desiredSize},get ready(){return g.ready}};p.getTextContent({stream:a,task:t,resources:a.dict.get("Resources")||s,stateManager:d,includeMarkedContent:n,sink:b,seenStyles:o,viewBox:c,lang:C,markedContentData:h,disableNormalization:l,keepWhiteSpace:Q}).then((function(){b.enqueueInvoked||D.set(f,a.dict.objId,!0);e()}),i)})).catch((function(e){if(!(e instanceof AbortException)){if(!p.options.ignoreErrors)throw e;warn(`getTextContent - ignoring XObject: "${e}".`)}})));return;case GA:R=N[0]instanceof Name;f=N[0].name;if(R&&b.getByName(f))break;next(new Promise((function(e,t){if(!R)throw new FormatError("GState must be referred to by name.");const i=s.get("ExtGState");if(!(i instanceof Dict))throw new FormatError("ExtGState should be a dictionary.");const a=i.get(f);if(!(a instanceof Dict))throw new FormatError("GState should be a dictionary.");const r=a.get("Font");if(r){flushTextContentItem();S.fontName=null;S.fontSize=r[1];handleSetFont(null,r[0]).then(e,t)}else{b.set(f,a.objId,!0);e()}})).catch((function(e){if(!(e instanceof AbortException)){if(!p.options.ignoreErrors)throw e;warn(`getTextContent - ignoring ExtGState: "${e}".`)}})));return;case Je:flushTextContentItem();if(n){h.level++;E.items.push({type:"beginMarkedContent",tag:N[0]instanceof Name?N[0].name:null})}break;case Ye:flushTextContentItem();if(n){h.level++;let e=null;N[1]instanceof Dict&&(e=N[1].get("MCID"));E.items.push({type:"beginMarkedContentProps",id:Number.isInteger(e)?`${p.idFactory.getPageObjId()}_mc${e}`:null,tag:N[0]instanceof Name?N[0].name:null})}break;case ve:flushTextContentItem();if(n){if(0===h.level)break;h.level--;E.items.push({type:"endMarkedContent"})}break;case UA:!e||e.font===S.font&&e.fontSize===S.fontSize&&e.fontName===S.fontName||flushTextContentItem()}if(E.items.length>=g.desiredSize){d=!0;break}}if(d)next(ms);else{flushTextContentItem();enqueueChunk();e()}})).catch((e=>{if(!(e instanceof AbortException)){if(!this.options.ignoreErrors)throw e;warn(`getTextContent - ignoring errors during "${t.name}" task: "${e}".`);flushTextContentItem();enqueueChunk()}}))}async extractDataStructures(e,t){const i=this.xref;let a;const s=this.readToUnicode(t.toUnicode);if(t.composite){const i=e.get("CIDSystemInfo");i instanceof Dict&&(t.cidSystemInfo={registry:stringToPDFString(i.get("Registry")),ordering:stringToPDFString(i.get("Ordering")),supplement:i.get("Supplement")});try{const t=e.get("CIDToGIDMap");t instanceof BaseStream&&(a=t.getBytes())}catch(e){if(!this.options.ignoreErrors)throw e;warn(`extractDataStructures - ignoring CIDToGIDMap data: "${e}".`)}}const r=[];let n,g=null;if(e.has("Encoding")){n=e.get("Encoding");if(n instanceof Dict){g=n.get("BaseEncoding");g=g instanceof Name?g.name:null;if(n.has("Differences")){const e=n.get("Differences");let t=0;for(const a of e){const e=i.fetchIfRef(a);if("number"==typeof e)t=e;else{if(!(e instanceof Name))throw new FormatError(`Invalid entry in 'Differences' array: ${e}`);r[t++]=e.name}}}}else if(n instanceof Name)g=n.name;else{const e="Encoding is not a Name nor a Dict";if(!this.options.ignoreErrors)throw new FormatError(e);warn(e)}"MacRomanEncoding"!==g&&"MacExpertEncoding"!==g&&"WinAnsiEncoding"!==g&&(g=null)}const o=!t.file||t.isInternalFont,c=qi()[t.name];g&&o&&c&&(g=null);if(g)t.defaultEncoding=getEncoding(g);else{const e=!!(t.flags&Mi),i=!!(t.flags&xi);n=hi;"TrueType"!==t.type||i||(n=li);if(e||c){n=Ci;o&&(/Symbol/i.test(t.name)?n=Bi:/Dingbats/i.test(t.name)?n=Qi:/Wingdings/i.test(t.name)&&(n=li))}t.defaultEncoding=n}t.differences=r;t.baseEncodingName=g;t.hasEncoding=!!g||r.length>0;t.dict=e;t.toUnicode=await s;const C=await this.buildToUnicode(t);t.toUnicode=C;a&&(t.cidToGidMap=this.readCidToGidMap(a,C));return t}_simpleFontToUnicode(e,t=!1){assert(!e.composite,"Must be a simple font.");const i=[],a=e.defaultEncoding.slice(),s=e.baseEncodingName,r=e.differences;for(const e in r){const t=r[e];".notdef"!==t&&(a[e]=t)}const n=wi();for(const r in a){let g=a[r];if(""===g)continue;let o=n[g];if(void 0!==o){i[r]=String.fromCharCode(o);continue}let c=0;switch(g[0]){case"G":3===g.length&&(c=parseInt(g.substring(1),16));break;case"g":5===g.length&&(c=parseInt(g.substring(1),16));break;case"C":case"c":if(g.length>=3&&g.length<=4){const i=g.substring(1);if(t){c=parseInt(i,16);break}c=+i;if(Number.isNaN(c)&&Number.isInteger(parseInt(i,16)))return this._simpleFontToUnicode(e,!0)}break;case"u":o=getUnicodeForGlyph(g,n);-1!==o&&(c=o);break;default:switch(g){case"f_h":case"f_t":case"T_h":i[r]=g.replaceAll("_","");continue}}if(c>0&&c<=1114111&&Number.isInteger(c)){if(s&&c===+r){const e=getEncoding(s);if(e&&(g=e[r])){i[r]=String.fromCharCode(n[g]);continue}}i[r]=String.fromCodePoint(c)}}return i}async buildToUnicode(e){e.hasIncludedToUnicodeMap=e.toUnicode?.length>0;if(e.hasIncludedToUnicodeMap){!e.composite&&e.hasEncoding&&(e.fallbackToUnicode=this._simpleFontToUnicode(e));return e.toUnicode}if(!e.composite)return new ToUnicodeMap(this._simpleFontToUnicode(e));if(e.composite&&(e.cMap.builtInCMap&&!(e.cMap instanceof IdentityCMap)||"Adobe"===e.cidSystemInfo?.registry&&("GB1"===e.cidSystemInfo.ordering||"CNS1"===e.cidSystemInfo.ordering||"Japan1"===e.cidSystemInfo.ordering||"Korea1"===e.cidSystemInfo.ordering))){const{registry:t,ordering:i}=e.cidSystemInfo,a=Name.get(`${t}-${i}-UCS2`),s=await CMapFactory.create({encoding:a,fetchBuiltInCMap:this._fetchBuiltInCMapBound,useCMap:null}),r=[],n=[];e.cMap.forEach((function(e,t){if(t>65535)throw new FormatError("Max size of CID is 65,535");const i=s.lookup(t);if(i){n.length=0;for(let e=0,t=i.length;e>1;(0!==s||t.has(r))&&(i[r]=s)}return i}extractWidths(e,t,i){const a=this.xref;let s=[],r=0;const n=[];let g;if(i.composite){const t=e.get("DW");r="number"==typeof t?Math.ceil(t):1e3;const o=e.get("W");if(Array.isArray(o))for(let e=0,t=o.length;e{const t=o.get(e),s=new OperatorList;return a.getOperatorList({stream:t,task:i,resources:c,operatorList:s}).then((()=>{s.fnArray[0]===ue&&this._removeType3ColorOperators(s,E);C[e]=s.getIR();for(const e of s.dependencies)n.add(e)})).catch((function(t){warn(`Type3 font resource "${e}" is not available.`);const i=new OperatorList;C[e]=i.getIR()}))}));this.type3Loaded=g.then((()=>{r.charProcOperatorList=C;if(this._bbox){r.isCharBBox=!0;r.bbox=this._bbox}}));return this.type3Loaded}_removeType3ColorOperators(e,t=NaN){const i=Util.normalizeRect(e.argsArray[0].slice(2)),a=i[2]-i[0],s=i[3]-i[1],r=Math.hypot(a,s);if(0===a||0===s){e.fnArray.splice(0,1);e.argsArray.splice(0,1)}else if(0===t||Math.round(r/t)>=10){this._bbox||(this._bbox=[1/0,1/0,-1/0,-1/0]);this._bbox[0]=Math.min(this._bbox[0],i[0]);this._bbox[1]=Math.min(this._bbox[1],i[1]);this._bbox[2]=Math.max(this._bbox[2],i[2]);this._bbox[3]=Math.max(this._bbox[3],i[3])}let n=0,g=e.length;for(;n=LA&&r<=zA;if(s.variableArgs)g>n&&info(`Command ${a}: expected [0, ${n}] args, but received ${g} args.`);else{if(g!==n){const e=this.nonProcessedArgs;for(;g>n;){e.push(t.shift());g--}for(;gEvaluatorPreprocessor.MAX_INVALID_PATH_OPS)throw new FormatError(`Invalid ${e}`);warn(`Skipping ${e}`);null!==t&&(t.length=0);continue}}this.preprocessCommand(r,t);e.fn=r;e.args=t;return!0}if(i===Bt)return!1;if(null!==i){null===t&&(t=[]);t.push(i);if(t.length>33)throw new FormatError("Too many arguments")}}}preprocessCommand(e,t){switch(0|e){case MA:this.stateManager.save();break;case UA:this.stateManager.restore();break;case xA:this.stateManager.transform(t)}}}class DefaultAppearanceEvaluator extends EvaluatorPreprocessor{constructor(e){super(new StringStream(e))}parse(){const e={fn:0,args:[]},t={fontSize:0,fontName:"",fontColor:new Uint8ClampedArray(3)};try{for(;;){e.args.length=0;if(!this.read(e))break;if(0!==this.savedStatesDepth)continue;const{fn:i,args:a}=e;switch(0|i){case re:const[e,i]=a;e instanceof Name&&(t.fontName=e.name);"number"==typeof i&&i>0&&(t.fontSize=i);break;case Se:ColorSpace.singletons.rgb.getRgbItem(a,0,t.fontColor,0);break;case be:ColorSpace.singletons.gray.getRgbItem(a,0,t.fontColor,0);break;case Re:ColorSpace.singletons.cmyk.getRgbItem(a,0,t.fontColor,0)}}}catch(e){warn(`parseDefaultAppearance - ignoring errors: "${e}".`)}return t}}function parseDefaultAppearance(e){return new DefaultAppearanceEvaluator(e).parse()}class AppearanceStreamEvaluator extends EvaluatorPreprocessor{constructor(e,t,i){super(e);this.stream=e;this.evaluatorOptions=t;this.xref=i;this.resources=e.dict?.get("Resources")}parse(){const e={fn:0,args:[]};let t={scaleFactor:1,fontSize:0,fontName:"",fontColor:new Uint8ClampedArray(3),fillColorSpace:ColorSpace.singletons.gray},i=!1;const a=[];try{for(;;){e.args.length=0;if(i||!this.read(e))break;const{fn:s,args:r}=e;switch(0|s){case MA:a.push({scaleFactor:t.scaleFactor,fontSize:t.fontSize,fontName:t.fontName,fontColor:t.fontColor.slice(),fillColorSpace:t.fillColorSpace});break;case UA:t=a.pop()||t;break;case ce:t.scaleFactor*=Math.hypot(r[0],r[1]);break;case re:const[e,s]=r;e instanceof Name&&(t.fontName=e.name);"number"==typeof s&&s>0&&(t.fontSize=s*t.scaleFactor);break;case fe:t.fillColorSpace=ColorSpace.parse({cs:r[0],xref:this.xref,resources:this.resources,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:this._localColorSpaceCache});break;case ye:t.fillColorSpace.getRgbItem(r,0,t.fontColor,0);break;case Se:ColorSpace.singletons.rgb.getRgbItem(r,0,t.fontColor,0);break;case be:ColorSpace.singletons.gray.getRgbItem(r,0,t.fontColor,0);break;case Re:ColorSpace.singletons.cmyk.getRgbItem(r,0,t.fontColor,0);break;case he:case le:case Be:case Qe:i=!0}}}catch(e){warn(`parseAppearanceStream - ignoring errors: "${e}".`)}this.stream.reset();delete t.scaleFactor;delete t.fillColorSpace;return t}get _localColorSpaceCache(){return shadow(this,"_localColorSpaceCache",new LocalColorSpaceCache)}get _pdfFunctionFactory(){return shadow(this,"_pdfFunctionFactory",new PDFFunctionFactory({xref:this.xref,isEvalSupported:this.evaluatorOptions.isEvalSupported}))}}function getPdfColor(e,t){if(e[0]===e[1]&&e[1]===e[2]){return`${numberToString(e[0]/255)} ${t?"g":"G"}`}return Array.from(e,(e=>numberToString(e/255))).join(" ")+" "+(t?"rg":"RG")}class FakeUnicodeFont{constructor(e,t){this.xref=e;this.widths=null;this.firstChar=1/0;this.lastChar=-1/0;this.fontFamily=t;const i=new OffscreenCanvas(1,1);this.ctxMeasure=i.getContext("2d",{willReadFrequently:!0});FakeUnicodeFont._fontNameId||(FakeUnicodeFont._fontNameId=1);this.fontName=Name.get(`InvalidPDFjsFont_${t}_${FakeUnicodeFont._fontNameId++}`)}get fontDescriptorRef(){if(!FakeUnicodeFont._fontDescriptorRef){const e=new Dict(this.xref);e.set("Type",Name.get("FontDescriptor"));e.set("FontName",this.fontName);e.set("FontFamily","MyriadPro Regular");e.set("FontBBox",[0,0,0,0]);e.set("FontStretch",Name.get("Normal"));e.set("FontWeight",400);e.set("ItalicAngle",0);FakeUnicodeFont._fontDescriptorRef=this.xref.getNewPersistentRef(e)}return FakeUnicodeFont._fontDescriptorRef}get descendantFontRef(){const e=new Dict(this.xref);e.set("BaseFont",this.fontName);e.set("Type",Name.get("Font"));e.set("Subtype",Name.get("CIDFontType0"));e.set("CIDToGIDMap",Name.get("Identity"));e.set("FirstChar",this.firstChar);e.set("LastChar",this.lastChar);e.set("FontDescriptor",this.fontDescriptorRef);e.set("DW",1e3);const t=[],i=[...this.widths.entries()].sort();let a=null,s=null;for(const[e,r]of i)if(a)if(e===a+s.length)s.push(r);else{t.push(a,s);a=e;s=[r]}else{a=e;s=[r]}a&&t.push(a,s);e.set("W",t);const r=new Dict(this.xref);r.set("Ordering","Identity");r.set("Registry","Adobe");r.set("Supplement",0);e.set("CIDSystemInfo",r);return this.xref.getNewPersistentRef(e)}get baseFontRef(){const e=new Dict(this.xref);e.set("BaseFont",this.fontName);e.set("Type",Name.get("Font"));e.set("Subtype",Name.get("Type0"));e.set("Encoding",Name.get("Identity-H"));e.set("DescendantFonts",[this.descendantFontRef]);e.set("ToUnicode",Name.get("Identity-H"));return this.xref.getNewPersistentRef(e)}get resources(){const e=new Dict(this.xref),t=new Dict(this.xref);t.set(this.fontName.name,this.baseFontRef);e.set("Font",t);return e}_createContext(){this.widths=new Map;this.ctxMeasure.font=`1000px ${this.fontFamily}`;return this.ctxMeasure}createFontResources(e){const t=this._createContext();for(const i of e.split(/\r\n?|\n/))for(const e of i.split("")){const i=e.charCodeAt(0);if(this.widths.has(i))continue;const a=t.measureText(e),s=Math.ceil(a.width);this.widths.set(i,s);this.firstChar=Math.min(i,this.firstChar);this.lastChar=Math.max(i,this.lastChar)}return this.resources}static getFirstPositionInfo(e,t,i){const[a,n,g,o]=e;let c=g-a,C=o-n;t%180!=0&&([c,C]=[C,c]);const h=s*i;return{coords:[0,C+r*i-h],bbox:[0,0,c,C],matrix:0!==t?getRotationMatrix(t,C,h):void 0}}createAppearance(e,t,i,a,n,g){const o=this._createContext(),c=[];let C=-1/0;for(const t of e.split(/\r\n?|\n/)){c.push(t);const e=o.measureText(t).width;C=Math.max(C,e);for(const e of codePointIter(t)){const t=String.fromCodePoint(e);let i=this.widths.get(e);if(void 0===i){const a=o.measureText(t);i=Math.ceil(a.width);this.widths.set(e,i);this.firstChar=Math.min(e,this.firstChar);this.lastChar=Math.max(e,this.lastChar)}}}C*=a/1e3;const[h,l,Q,E]=t;let u=Q-h,d=E-l;i%180!=0&&([u,d]=[d,u]);let f=1;C>u&&(f=u/C);let p=1;const m=s*a,y=r*a,w=m*c.length;w>d&&(p=d/w);const D=a*Math.min(f,p),b=["q",`0 0 ${numberToString(u)} ${numberToString(d)} re W n`,"BT",`1 0 0 1 0 ${numberToString(d+y)} Tm 0 Tc ${getPdfColor(n,!0)}`,`/${this.fontName.name} ${numberToString(D)} Tf`],{resources:F}=this;if(1!==(g="number"==typeof g&&g>=0&&g<=1?g:1)){b.push("/R0 gs");const e=new Dict(this.xref),t=new Dict(this.xref);t.set("ca",g);t.set("CA",g);t.set("Type",Name.get("ExtGState"));e.set("R0",t);F.set("ExtGState",e)}const S=numberToString(m);for(const e of c)b.push(`0 -${S} Td <${stringToUTF16HexString(e)}> Tj`);b.push("ET","Q");const k=b.join("\n"),R=new Dict(this.xref);R.set("Subtype",Name.get("Form"));R.set("Type",Name.get("XObject"));R.set("BBox",[0,0,u,d]);R.set("Length",k.length);R.set("Resources",F);if(i){const e=getRotationMatrix(i,u,d);R.set("Matrix",e)}const N=new StringStream(k);N.dict=R;return N}}class NameOrNumberTree{constructor(e,t,i){this.root=e;this.xref=t;this._type=i}getAll(){const e=new Map;if(!this.root)return e;const t=this.xref,i=new RefSet;i.put(this.root);const a=[this.root];for(;a.length>0;){const s=t.fetchIfRef(a.shift());if(!(s instanceof Dict))continue;if(s.has("Kids")){const e=s.get("Kids");if(!Array.isArray(e))continue;for(const t of e){if(i.has(t))throw new FormatError(`Duplicate entry in "${this._type}" tree.`);a.push(t);i.put(t)}continue}const r=s.get(this._type);if(Array.isArray(r))for(let i=0,a=r.length;i10){warn(`Search depth limit reached for "${this._type}" tree.`);return null}const s=i.get("Kids");if(!Array.isArray(s))return null;let r=0,n=s.length-1;for(;r<=n;){const a=r+n>>1,g=t.fetchIfRef(s[a]),o=g.get("Limits");if(et.fetchIfRef(o[1]))){i=g;break}r=a+1}}if(r>n)return null}const s=i.get(this._type);if(Array.isArray(s)){let i=0,a=s.length-2;for(;i<=a;){const r=i+a>>1,n=r+(1&r),g=t.fetchIfRef(s[n]);if(eg))return s[n+1];i=n+2}}}return null}get(e){return this.xref.fetchIfRef(this.getRaw(e))}}class NameTree extends NameOrNumberTree{constructor(e,t){super(e,t,"Names")}}class NumberTree extends NameOrNumberTree{constructor(e,t){super(e,t,"Nums")}}function clearGlobalCaches(){!function clearPatternCaches(){Qa=Object.create(null)}();!function clearPrimitiveCaches(){Qt=Object.create(null);Et=Object.create(null);ut=Object.create(null)}();!function clearUnicodeCaches(){ki.clear()}();JpxImage.cleanup()}function pickPlatformItem(e){return e instanceof Dict?e.has("UF")?e.get("UF"):e.has("F")?e.get("F"):e.has("Unix")?e.get("Unix"):e.has("Mac")?e.get("Mac"):e.has("DOS")?e.get("DOS"):null:null}class FileSpec{#U=!1;constructor(e,t,i=!1){if(e instanceof Dict){this.xref=t;this.root=e;e.has("FS")&&(this.fs=e.get("FS"));e.has("RF")&&warn("Related file specifications are not supported");i||(e.has("EF")?this.#U=!0:warn("Non-embedded file specifications are not supported"))}}get filename(){let e="";const t=pickPlatformItem(this.root);t&&"string"==typeof t&&(e=stringToPDFString(t).replaceAll("\\\\","\\").replaceAll("\\/","/").replaceAll("\\","/"));return shadow(this,"filename",e||"unnamed")}get content(){if(!this.#U)return null;this._contentRef||=pickPlatformItem(this.root?.get("EF"));let e=null;if(this._contentRef){const t=this.xref.fetchIfRef(this._contentRef);t instanceof BaseStream?e=t.getBytes():warn("Embedded file specification points to non-existing/invalid content")}else warn("Embedded file specification does not have any content");return e}get description(){let e="";const t=this.root?.get("Desc");t&&"string"==typeof t&&(e=stringToPDFString(t));return shadow(this,"description",e)}get serializable(){return{rawFilename:this.filename,filename:(e=this.filename,e.substring(e.lastIndexOf("/")+1)),content:this.content,description:this.description};var e}}const ys=0,ws=-2,Ds=-3,bs=-4,Fs=-5,Ss=-6,ks=-9;function isWhitespace(e,t){const i=e[t];return" "===i||"\n"===i||"\r"===i||"\t"===i}class XMLParserBase{_resolveEntities(e){return e.replaceAll(/&([^;]+);/g,((e,t)=>{if("#x"===t.substring(0,2))return String.fromCodePoint(parseInt(t.substring(2),16));if("#"===t.substring(0,1))return String.fromCodePoint(parseInt(t.substring(1),10));switch(t){case"lt":return"<";case"gt":return">";case"amp":return"&";case"quot":return'"';case"apos":return"'"}return this.onResolveEntity(t)}))}_parseContent(e,t){const i=[];let a=t;function skipWs(){for(;a"!==e[a]&&"/"!==e[a];)++a;const s=e.substring(t,a);skipWs();for(;a"!==e[a]&&"/"!==e[a]&&"?"!==e[a];){skipWs();let t="",s="";for(;a"!==e[i]&&"?"!==e[i]&&"/"!==e[i];)++i;const a=e.substring(t,i);!function skipWs(){for(;i"!==e[i+1]);)++i;return{name:a,value:e.substring(s,i),parsed:i-t}}parseXml(e){let t=0;for(;t",i);if(t<0){this.onError(ks);return}this.onEndElement(e.substring(i,t));i=t+1;break;case"?":++i;const a=this._parseProcessingInstruction(e,i);if("?>"!==e.substring(i+a.parsed,i+a.parsed+2)){this.onError(Ds);return}this.onPi(a.name,a.value);i+=a.parsed+2;break;case"!":if("--"===e.substring(i+1,i+3)){t=e.indexOf("--\x3e",i+3);if(t<0){this.onError(Fs);return}this.onComment(e.substring(i+3,t));i=t+3}else if("[CDATA["===e.substring(i+1,i+8)){t=e.indexOf("]]>",i+8);if(t<0){this.onError(ws);return}this.onCdata(e.substring(i+8,t));i=t+3}else{if("DOCTYPE"!==e.substring(i+1,i+8)){this.onError(Ss);return}{const a=e.indexOf("[",i+8);let s=!1;t=e.indexOf(">",i+8);if(t<0){this.onError(bs);return}if(a>0&&t>a){t=e.indexOf("]>",i+8);if(t<0){this.onError(bs);return}s=!0}const r=e.substring(i+8,t+(s?1:0));this.onDoctype(r);i=t+(s?2:1)}}break;default:const s=this._parseContent(e,i);if(null===s){this.onError(Ss);return}let r=!1;if("/>"===e.substring(i+s.parsed,i+s.parsed+2))r=!0;else if(">"!==e.substring(i+s.parsed,i+s.parsed+1)){this.onError(ks);return}this.onBeginElement(s.name,s.attributes,r);i+=s.parsed+(r?2:1)}}else{for(;i0}searchNode(e,t){if(t>=e.length)return this;const i=e[t];if(i.name.startsWith("#")&&t0){a.push([s,0]);s=s.childNodes[0]}else{if(0===a.length)return null;for(;0!==a.length;){const[e,t]=a.pop(),i=t+1;if(i");for(const t of this.childNodes)t.dump(e);e.push(``)}else this.nodeValue?e.push(`>${encodeToXmlString(this.nodeValue)}`):e.push("/>")}else e.push(encodeToXmlString(this.nodeValue))}}class SimpleXMLParser extends XMLParserBase{constructor({hasAttributes:e=!1,lowerCaseName:t=!1}){super();this._currentFragment=null;this._stack=null;this._errorCode=ys;this._hasAttributes=e;this._lowerCaseName=t}parseFromString(e){this._currentFragment=[];this._stack=[];this._errorCode=ys;this.parseXml(e);if(this._errorCode!==ys)return;const[t]=this._currentFragment;return t?{documentElement:t}:void 0}onText(e){if(function isWhitespaceString(e){for(let t=0,i=e.length;t\\376\\377([^<]+)/g,(function(e,t){const i=t.replaceAll(/\\([0-3])([0-7])([0-7])/g,(function(e,t,i,a){return String.fromCharCode(64*t+8*i+1*a)})).replaceAll(/&(amp|apos|gt|lt|quot);/g,(function(e,t){switch(t){case"amp":return"&";case"apos":return"'";case"gt":return">";case"lt":return"<";case"quot":return'"'}throw new Error(`_repair: ${t} isn't defined.`)})),a=[">"];for(let e=0,t=i.length;e=32&&t<127&&60!==t&&62!==t&&38!==t?a.push(String.fromCharCode(t)):a.push("&#x"+(65536+t).toString(16).substring(1)+";")}return a.join("")}))}_getSequence(e){const t=e.nodeName;return"rdf:bag"!==t&&"rdf:seq"!==t&&"rdf:alt"!==t?null:e.childNodes.filter((e=>"rdf:li"===e.nodeName))}_parseArray(e){if(!e.hasChildNodes())return;const[t]=e.childNodes,i=this._getSequence(t)||[];this._metadataMap.set(e.nodeName,i.map((e=>e.textContent.trim())))}_parse(e){let t=e.documentElement;if("rdf:rdf"!==t.nodeName){t=t.firstChild;for(;t&&"rdf:rdf"!==t.nodeName;)t=t.nextSibling}if(t&&"rdf:rdf"===t.nodeName&&t.hasChildNodes())for(const e of t.childNodes)if("rdf:description"===e.nodeName)for(const t of e.childNodes){const e=t.nodeName;switch(e){case"#text":continue;case"dc:creator":case"dc:subject":this._parseArray(t);continue}this._metadataMap.set(e,t.textContent.trim())}}get serializable(){return{parsedData:this._metadataMap,rawData:this._data}}}const Rs=1,Ns=2,Gs=3,Ms=4,Us=5;class StructTreeRoot{constructor(e,t){this.dict=e;this.ref=t instanceof Ref?t:null;this.roleMap=new Map;this.structParentIds=null}init(){this.readRoleMap()}#x(e,t,i){if(!(e instanceof Ref)||t<0)return;this.structParentIds||=new RefSetCache;let a=this.structParentIds.get(e);if(!a){a=[];this.structParentIds.put(e,a)}a.push([t,i])}addAnnotationIdToPage(e,t){this.#x(e,t,Ms)}readRoleMap(){const e=this.dict.get("RoleMap");if(e instanceof Dict)for(const[t,i]of e)i instanceof Name&&this.roleMap.set(t,i.name)}static async canCreateStructureTree({catalogRef:e,pdfManager:t,newAnnotationsByPage:i}){if(!(e instanceof Ref)){warn("Cannot save the struct tree: no catalog reference.");return!1}let a=0,s=!0;for(const[e,r]of i){const{ref:i}=await t.getPage(e);if(!(i instanceof Ref)){warn(`Cannot save the struct tree: page ${e} has no ref.`);s=!0;break}for(const e of r)if(e.accessibilityData?.type){e.parentTreeId=a++;s=!1}}if(s){for(const e of i.values())for(const t of e)delete t.parentTreeId;return!1}return!0}static async createStructureTree({newAnnotationsByPage:e,xref:t,catalogRef:i,pdfManager:a,changes:s}){const r=a.catalog.cloneDict(),n=new RefSetCache;n.put(i,r);const g=t.getNewTemporaryRef();r.set("StructTreeRoot",g);const o=new Dict(t);o.set("Type",Name.get("StructTreeRoot"));const c=t.getNewTemporaryRef();o.set("ParentTree",c);const C=[];o.set("K",C);n.put(g,o);const h=new Dict(t),l=[];h.set("Nums",l);const Q=await this.#L({newAnnotationsByPage:e,structTreeRootRef:g,structTreeRoot:null,kids:C,nums:l,xref:t,pdfManager:a,changes:s,cache:n});o.set("ParentTreeNextKey",Q);n.put(c,h);for(const[e,t]of n.items())s.put(e,{data:t})}async canUpdateStructTree({pdfManager:e,xref:t,newAnnotationsByPage:i}){if(!this.ref){warn("Cannot update the struct tree: no root reference.");return!1}let a=this.dict.get("ParentTreeNextKey");if(!Number.isInteger(a)||a<0){warn("Cannot update the struct tree: invalid next key.");return!1}const s=this.dict.get("ParentTree");if(!(s instanceof Dict)){warn("Cannot update the struct tree: ParentTree isn't a dict.");return!1}const r=s.get("Nums");if(!Array.isArray(r)){warn("Cannot update the struct tree: nums isn't an array.");return!1}const n=new NumberTree(s,t);for(const t of i.keys()){const{pageDict:i}=await e.getPage(t);if(!i.has("StructParents"))continue;const a=i.get("StructParents");if(!Number.isInteger(a)||!Array.isArray(n.get(a))){warn(`Cannot save the struct tree: page ${t} has a wrong id.`);return!1}}let g=!0;for(const[t,s]of i){const{pageDict:i}=await e.getPage(t);StructTreeRoot.#H({elements:s,xref:this.dict.xref,pageDict:i,numberTree:n});for(const e of s)if(e.accessibilityData?.type){e.accessibilityData.structParent>=0||(e.parentTreeId=a++);g=!1}}if(g){for(const e of i.values())for(const t of e){delete t.parentTreeId;delete t.structTreeParent}return!1}return!0}async updateStructureTree({newAnnotationsByPage:e,pdfManager:t,changes:i}){const a=this.dict.xref,s=this.dict.clone(),r=this.ref,n=new RefSetCache;n.put(r,s);let g,o=s.getRaw("ParentTree");if(o instanceof Ref)g=a.fetch(o);else{g=o;o=a.getNewTemporaryRef();s.set("ParentTree",o)}g=g.clone();n.put(o,g);let c=g.getRaw("Nums"),C=null;if(c instanceof Ref){C=c;c=a.fetch(C)}c=c.slice();C||g.set("Nums",c);const h=await StructTreeRoot.#L({newAnnotationsByPage:e,structTreeRootRef:r,structTreeRoot:this,kids:null,nums:c,xref:a,pdfManager:t,changes:i,cache:n});if(-1!==h){s.set("ParentTreeNextKey",h);C&&n.put(C,c);for(const[e,t]of n.items())i.put(e,{data:t})}}static async#L({newAnnotationsByPage:e,structTreeRootRef:t,structTreeRoot:i,kids:a,nums:s,xref:r,pdfManager:n,changes:g,cache:o}){const c=Name.get("OBJR");let C,h=-1;for(const[l,Q]of e){const e=await n.getPage(l),{ref:E}=e,u=E instanceof Ref;for(const{accessibilityData:n,ref:d,parentTreeId:f,structTreeParent:p}of Q){if(!n?.type)continue;const{structParent:Q}=n;if(i&&Number.isInteger(Q)&&Q>=0){let t=(C||=new Map).get(l);if(void 0===t){t=new StructTreePage(i,e.pageDict).collectObjects(E);C.set(l,t)}const a=t?.get(Q);if(a){const e=r.fetch(a).clone();StructTreeRoot.#J(e,n);g.put(a,{data:e});continue}}h=Math.max(h,f);const m=r.getNewTemporaryRef(),y=new Dict(r);StructTreeRoot.#J(y,n);await this.#Y({structTreeParent:p,tagDict:y,newTagRef:m,structTreeRootRef:t,fallbackKids:a,xref:r,cache:o});const w=new Dict(r);y.set("K",w);w.set("Type",c);u&&w.set("Pg",E);w.set("Obj",d);o.put(m,y);s.push(f,m)}}return h+1}static#J(e,{type:t,title:i,lang:a,alt:s,expanded:r,actualText:n}){e.set("S",Name.get(t));i&&e.set("T",stringToAsciiOrUTF16BE(i));a&&e.set("Lang",stringToAsciiOrUTF16BE(a));s&&e.set("Alt",stringToAsciiOrUTF16BE(s));r&&e.set("E",stringToAsciiOrUTF16BE(r));n&&e.set("ActualText",stringToAsciiOrUTF16BE(n))}static#H({elements:e,xref:t,pageDict:i,numberTree:a}){const s=new Map;for(const t of e)if(t.structTreeParentId){const e=parseInt(t.structTreeParentId.split("_mc")[1],10);let i=s.get(e);if(!i){i=[];s.set(e,i)}i.push(t)}const r=i.get("StructParents");if(!Number.isInteger(r))return;const n=a.get(r),updateElement=(e,i,a)=>{const r=s.get(e);if(r){const e=i.getRaw("P"),s=t.fetchIfRef(e);if(e instanceof Ref&&s instanceof Dict){const e={ref:a,dict:i};for(const t of r)t.structTreeParent=e}return!0}return!1};for(const e of n){if(!(e instanceof Ref))continue;const i=t.fetch(e),a=i.get("K");if(Number.isInteger(a))updateElement(a,i,e);else if(Array.isArray(a))for(let s of a){s=t.fetchIfRef(s);if(Number.isInteger(s)&&updateElement(s,i,e))break;if(!(s instanceof Dict))continue;if(!isName(s.get("Type"),"MCR"))break;const a=s.get("MCID");if(Number.isInteger(a)&&updateElement(a,i,e))break}}}static async#Y({structTreeParent:e,tagDict:t,newTagRef:i,structTreeRootRef:a,fallbackKids:s,xref:r,cache:n}){let g,o=null;if(e){({ref:o}=e);g=e.dict.getRaw("P")||a}else g=a;t.set("P",g);const c=r.fetchIfRef(g);if(!c){s.push(i);return}let C=n.get(g);if(!C){C=c.clone();n.put(g,C)}const h=C.getRaw("K");let l=h instanceof Ref?n.get(h):null;if(!l){l=r.fetchIfRef(h);l=Array.isArray(l)?l.slice():[h];const e=r.getNewTemporaryRef();C.set("K",e);n.put(e,l)}const Q=l.indexOf(o);l.splice(Q>=0?Q+1:l.length,0,i)}}class StructElementNode{constructor(e,t){this.tree=e;this.dict=t;this.kids=[];this.parseKids()}get role(){const e=this.dict.get("S"),t=e instanceof Name?e.name:"",{root:i}=this.tree;return i.roleMap.has(t)?i.roleMap.get(t):t}parseKids(){let e=null;const t=this.dict.getRaw("Pg");t instanceof Ref&&(e=t.toString());const i=this.dict.get("K");if(Array.isArray(i))for(const t of i){const i=this.parseKid(e,t);i&&this.kids.push(i)}else{const t=this.parseKid(e,i);t&&this.kids.push(t)}}parseKid(e,t){if(Number.isInteger(t))return this.tree.pageDict.objId!==e?null:new StructElement({type:Rs,mcid:t,pageObjId:e});let i=null;t instanceof Ref?i=this.dict.xref.fetch(t):t instanceof Dict&&(i=t);if(!i)return null;const a=i.getRaw("Pg");a instanceof Ref&&(e=a.toString());const s=i.get("Type")instanceof Name?i.get("Type").name:null;if("MCR"===s){if(this.tree.pageDict.objId!==e)return null;const t=i.getRaw("Stm");return new StructElement({type:Ns,refObjId:t instanceof Ref?t.toString():null,pageObjId:e,mcid:i.get("MCID")})}if("OBJR"===s){if(this.tree.pageDict.objId!==e)return null;const t=i.getRaw("Obj");return new StructElement({type:Gs,refObjId:t instanceof Ref?t.toString():null,pageObjId:e})}return new StructElement({type:Us,dict:i})}}class StructElement{constructor({type:e,dict:t=null,mcid:i=null,pageObjId:a=null,refObjId:s=null}){this.type=e;this.dict=t;this.mcid=i;this.pageObjId=a;this.refObjId=s;this.parentNode=null}}class StructTreePage{constructor(e,t){this.root=e;this.rootDict=e?e.dict:null;this.pageDict=t;this.nodes=[]}collectObjects(e){if(!(this.root&&this.rootDict&&e instanceof Ref))return null;const t=this.rootDict.get("ParentTree");if(!t)return null;const i=this.root.structParentIds?.get(e);if(!i)return null;const a=new Map,s=new NumberTree(t,this.rootDict.xref);for(const[e]of i){const t=s.getRaw(e);t instanceof Ref&&a.set(e,t)}return a}parse(e){if(!(this.root&&this.rootDict&&e instanceof Ref))return;const t=this.rootDict.get("ParentTree");if(!t)return;const i=this.pageDict.get("StructParents"),a=this.root.structParentIds?.get(e);if(!Number.isInteger(i)&&!a)return;const s=new Map,r=new NumberTree(t,this.rootDict.xref);if(Number.isInteger(i)){const e=r.get(i);if(Array.isArray(e))for(const t of e)t instanceof Ref&&this.addNode(this.rootDict.xref.fetch(t),s)}if(a)for(const[e,t]of a){const i=r.get(e);if(i){const e=this.addNode(this.rootDict.xref.fetchIfRef(i),s);1===e?.kids?.length&&e.kids[0].type===Gs&&(e.kids[0].type=t)}}}addNode(e,t,i=0){if(i>40){warn("StructTree MAX_DEPTH reached.");return null}if(!(e instanceof Dict))return null;if(t.has(e))return t.get(e);const a=new StructElementNode(this,e);t.set(e,a);const s=e.get("P");if(!s||isName(s.get("Type"),"StructTreeRoot")){this.addTopLevelNode(e,a)||t.delete(e);return a}const r=this.addNode(s,t,i+1);if(!r)return a;let n=!1;for(const t of r.kids)if(t.type===Us&&t.dict===e){t.parentNode=a;n=!0}n||t.delete(e);return a}addTopLevelNode(e,t){const i=this.rootDict.get("K");if(!i)return!1;if(i instanceof Dict){if(i.objId!==e.objId)return!1;this.nodes[0]=t;return!0}if(!Array.isArray(i))return!0;let a=!1;for(let s=0;s40){warn("StructTree too deep to be fully serialized.");return}const a=Object.create(null);a.role=e.role;a.children=[];t.children.push(a);let s=e.dict.get("Alt");"string"!=typeof s&&(s=e.dict.get("ActualText"));"string"==typeof s&&(a.alt=stringToPDFString(s));const r=e.dict.get("A");if(r instanceof Dict){const e=lookupNormalRect(r.getArray("BBox"),null);if(e)a.bbox=e;else{const e=r.get("Width"),t=r.get("Height");"number"==typeof e&&e>0&&"number"==typeof t&&t>0&&(a.bbox=[0,0,e,t])}}const n=e.dict.get("Lang");"string"==typeof n&&(a.lang=stringToPDFString(n));for(const t of e.kids){const e=t.type===Us?t.parentNode:null;e?nodeToSerializable(e,a,i+1):t.type===Rs||t.type===Ns?a.children.push({type:"content",id:`p${t.pageObjId}_mc${t.mcid}`}):t.type===Gs?a.children.push({type:"object",id:t.refObjId}):t.type===Ms&&a.children.push({type:"annotation",id:`pdfjs_internal_id_${t.refObjId}`})}}const e=Object.create(null);e.children=[];e.role="Root";for(const t of this.nodes)t&&nodeToSerializable(t,e);return e}}function isValidExplicitDest(e){if(!Array.isArray(e)||e.length<2)return!1;const[t,i,...a]=e;if(!(t instanceof Ref||Number.isInteger(t)))return!1;if(!(i instanceof Name))return!1;const s=a.length;let r=!0;switch(i.name){case"XYZ":if(s<2||s>3)return!1;break;case"Fit":case"FitB":return 0===s;case"FitH":case"FitBH":case"FitV":case"FitBV":if(s>1)return!1;break;case"FitR":if(4!==s)return!1;r=!1;break;default:return!1}for(const e of a)if(!("number"==typeof e||r&&null===e))return!1;return!0}function fetchDest(e){e instanceof Dict&&(e=e.get("D"));return isValidExplicitDest(e)?e:null}function fetchRemoteDest(e){let t=e.get("D");if(t){t instanceof Name&&(t=t.name);if("string"==typeof t)return stringToPDFString(t);if(isValidExplicitDest(t))return JSON.stringify(t)}return null}class Catalog{constructor(e,t){this.pdfManager=e;this.xref=t;this._catDict=t.getCatalogObj();if(!(this._catDict instanceof Dict))throw new FormatError("Catalog object is not a dictionary.");this.toplevelPagesDict;this._actualNumPages=null;this.fontCache=new RefSetCache;this.builtInCMapCache=new Map;this.standardFontDataCache=new Map;this.globalImageCache=new GlobalImageCache;this.pageKidsCountCache=new RefSetCache;this.pageIndexCache=new RefSetCache;this.pageDictCache=new RefSetCache;this.nonBlendModesSet=new RefSet;this.systemFontCache=new Map}cloneDict(){return this._catDict.clone()}get version(){const e=this._catDict.get("Version");if(e instanceof Name){if(ft.test(e.name))return shadow(this,"version",e.name);warn(`Invalid PDF catalog version: ${e.name}`)}return shadow(this,"version",null)}get lang(){const e=this._catDict.get("Lang");return shadow(this,"lang",e&&"string"==typeof e?stringToPDFString(e):null)}get needsRendering(){const e=this._catDict.get("NeedsRendering");return shadow(this,"needsRendering","boolean"==typeof e&&e)}get collection(){let e=null;try{const t=this._catDict.get("Collection");t instanceof Dict&&t.size>0&&(e=t)}catch(e){if(e instanceof MissingDataException)throw e;info("Cannot fetch Collection entry; assuming no collection is present.")}return shadow(this,"collection",e)}get acroForm(){let e=null;try{const t=this._catDict.get("AcroForm");t instanceof Dict&&t.size>0&&(e=t)}catch(e){if(e instanceof MissingDataException)throw e;info("Cannot fetch AcroForm entry; assuming no forms are present.")}return shadow(this,"acroForm",e)}get acroFormRef(){const e=this._catDict.getRaw("AcroForm");return shadow(this,"acroFormRef",e instanceof Ref?e:null)}get metadata(){const e=this._catDict.getRaw("Metadata");if(!(e instanceof Ref))return shadow(this,"metadata",null);let t=null;try{const i=this.xref.fetch(e,!this.xref.encrypt?.encryptMetadata);if(i instanceof BaseStream&&i.dict instanceof Dict){const e=i.dict.get("Type"),a=i.dict.get("Subtype");if(isName(e,"Metadata")&&isName(a,"XML")){const e=stringToUTF8String(i.getString());e&&(t=new MetadataParser(e).serializable)}}}catch(e){if(e instanceof MissingDataException)throw e;info(`Skipping invalid Metadata: "${e}".`)}return shadow(this,"metadata",t)}get markInfo(){let e=null;try{e=this._readMarkInfo()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read mark info.")}return shadow(this,"markInfo",e)}_readMarkInfo(){const e=this._catDict.get("MarkInfo");if(!(e instanceof Dict))return null;const t={Marked:!1,UserProperties:!1,Suspects:!1};for(const i in t){const a=e.get(i);"boolean"==typeof a&&(t[i]=a)}return t}get structTreeRoot(){let e=null;try{e=this._readStructTreeRoot()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable read to structTreeRoot info.")}return shadow(this,"structTreeRoot",e)}_readStructTreeRoot(){const e=this._catDict.getRaw("StructTreeRoot"),t=this.xref.fetchIfRef(e);if(!(t instanceof Dict))return null;const i=new StructTreeRoot(t,e);i.init();return i}get toplevelPagesDict(){const e=this._catDict.get("Pages");if(!(e instanceof Dict))throw new FormatError("Invalid top-level pages dictionary.");return shadow(this,"toplevelPagesDict",e)}get documentOutline(){let e=null;try{e=this._readDocumentOutline()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read document outline.")}return shadow(this,"documentOutline",e)}_readDocumentOutline(){let e=this._catDict.get("Outlines");if(!(e instanceof Dict))return null;e=e.getRaw("First");if(!(e instanceof Ref))return null;const t={items:[]},i=[{obj:e,parent:t}],a=new RefSet;a.put(e);const s=this.xref,r=new Uint8ClampedArray(3);for(;i.length>0;){const t=i.shift(),n=s.fetchIfRef(t.obj);if(null===n)continue;n.has("Title")||warn("Invalid outline item encountered.");const g={url:null,dest:null,action:null};Catalog.parseDestDictionary({destDict:n,resultObj:g,docBaseUrl:this.baseUrl,docAttachments:this.attachments});const o=n.get("Title"),c=n.get("F")||0,C=n.getArray("C"),h=n.get("Count");let l=r;!isNumberArray(C,3)||0===C[0]&&0===C[1]&&0===C[2]||(l=ColorSpace.singletons.rgb.getRgb(C,0));const Q={action:g.action,attachment:g.attachment,dest:g.dest,url:g.url,unsafeUrl:g.unsafeUrl,newWindow:g.newWindow,setOCGState:g.setOCGState,title:"string"==typeof o?stringToPDFString(o):"",color:l,count:Number.isInteger(h)?h:void 0,bold:!!(2&c),italic:!!(1&c),items:[]};t.parent.items.push(Q);e=n.getRaw("First");if(e instanceof Ref&&!a.has(e)){i.push({obj:e,parent:Q});a.put(e)}e=n.getRaw("Next");if(e instanceof Ref&&!a.has(e)){i.push({obj:e,parent:t.parent});a.put(e)}}return t.items.length>0?t.items:null}get permissions(){let e=null;try{e=this._readPermissions()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read permissions.")}return shadow(this,"permissions",e)}_readPermissions(){const e=this.xref.trailer.get("Encrypt");if(!(e instanceof Dict))return null;let t=e.get("P");if("number"!=typeof t)return null;t+=2**32;const i=[];for(const e in y){const a=y[e];t&a&&i.push(a)}return i}get optionalContentConfig(){let e=null;try{const t=this._catDict.get("OCProperties");if(!t)return shadow(this,"optionalContentConfig",null);const i=t.get("D");if(!i)return shadow(this,"optionalContentConfig",null);const a=t.get("OCGs");if(!Array.isArray(a))return shadow(this,"optionalContentConfig",null);const s=new RefSetCache;for(const e of a)e instanceof Ref&&!s.has(e)&&s.put(e,this.#v(e));e=this.#K(i,s)}catch(e){if(e instanceof MissingDataException)throw e;warn(`Unable to read optional content config: ${e}`)}return shadow(this,"optionalContentConfig",e)}#v(e){const t=this.xref.fetch(e),i={id:e.toString(),name:null,intent:null,usage:{print:null,view:null},rbGroups:[]},a=t.get("Name");"string"==typeof a&&(i.name=stringToPDFString(a));let s=t.getArray("Intent");Array.isArray(s)||(s=[s]);s.every((e=>e instanceof Name))&&(i.intent=s.map((e=>e.name)));const r=t.get("Usage");if(!(r instanceof Dict))return i;const n=i.usage,g=r.get("Print");if(g instanceof Dict){const e=g.get("PrintState");if(e instanceof Name)switch(e.name){case"ON":case"OFF":n.print={printState:e.name}}}const o=r.get("View");if(o instanceof Dict){const e=o.get("ViewState");if(e instanceof Name)switch(e.name){case"ON":case"OFF":n.view={viewState:e.name}}}return i}#K(e,t){function parseOnOff(e){const i=[];if(Array.isArray(e))for(const a of e)a instanceof Ref&&t.has(a)&&i.push(a.toString());return i}function parseOrder(e,i=0){if(!Array.isArray(e))return null;const s=[];for(const r of e){if(r instanceof Ref&&t.has(r)){a.put(r);s.push(r.toString());continue}const e=parseNestedOrder(r,i);e&&s.push(e)}if(i>0)return s;const r=[];for(const[e]of t.items())a.has(e)||r.push(e.toString());r.length&&s.push({name:null,order:r});return s}function parseNestedOrder(e,t){if(++t>s){warn("parseNestedOrder - reached MAX_NESTED_LEVELS.");return null}const a=i.fetchIfRef(e);if(!Array.isArray(a))return null;const r=i.fetchIfRef(a[0]);if("string"!=typeof r)return null;const n=parseOrder(a.slice(1),t);return n?.length?{name:stringToPDFString(r),order:n}:null}const i=this.xref,a=new RefSet,s=10;!function parseRBGroups(e){if(Array.isArray(e))for(const a of e){const e=i.fetchIfRef(a);if(!Array.isArray(e)||!e.length)continue;const s=new Set;for(const i of e)if(i instanceof Ref&&t.has(i)&&!s.has(i.toString())){s.add(i.toString());t.get(i).rbGroups.push(s)}}}(e.get("RBGroups"));return{name:"string"==typeof e.get("Name")?stringToPDFString(e.get("Name")):null,creator:"string"==typeof e.get("Creator")?stringToPDFString(e.get("Creator")):null,baseState:e.get("BaseState")instanceof Name?e.get("BaseState").name:null,on:parseOnOff(e.get("ON")),off:parseOnOff(e.get("OFF")),order:parseOrder(e.get("Order")),groups:[...t]}}setActualNumPages(e=null){this._actualNumPages=e}get hasActualNumPages(){return null!==this._actualNumPages}get _pagesCount(){const e=this.toplevelPagesDict.get("Count");if(!Number.isInteger(e))throw new FormatError("Page count in top-level pages dictionary is not an integer.");return shadow(this,"_pagesCount",e)}get numPages(){return this.hasActualNumPages?this._actualNumPages:this._pagesCount}get destinations(){const e=this._readDests(),t=Object.create(null);if(e instanceof NameTree)for(const[i,a]of e.getAll()){const e=fetchDest(a);e&&(t[stringToPDFString(i)]=e)}else if(e instanceof Dict)for(const[i,a]of e){const e=fetchDest(a);e&&(t[i]=e)}return shadow(this,"destinations",t)}getDestination(e){const t=this._readDests();if(t instanceof NameTree){const i=fetchDest(t.get(e));if(i)return i;const a=this.destinations[e];if(a){warn(`Found "${e}" at an incorrect position in the NameTree.`);return a}}else if(t instanceof Dict){const i=fetchDest(t.get(e));if(i)return i}return null}_readDests(){const e=this._catDict.get("Names");return e?.has("Dests")?new NameTree(e.getRaw("Dests"),this.xref):this._catDict.has("Dests")?this._catDict.get("Dests"):void 0}get pageLabels(){let e=null;try{e=this._readPageLabels()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read page labels.")}return shadow(this,"pageLabels",e)}_readPageLabels(){const e=this._catDict.getRaw("PageLabels");if(!e)return null;const t=new Array(this.numPages);let i=null,a="";const s=new NumberTree(e,this.xref).getAll();let r="",n=1;for(let e=0,g=this.numPages;e=1))throw new FormatError("Invalid start in PageLabel dictionary.");n=e}else n=1}switch(i){case"D":r=n;break;case"R":case"r":r=toRomanNumerals(n,"r"===i);break;case"A":case"a":const e=26,t="a"===i?97:65,a=n-1;r=String.fromCharCode(t+a%e).repeat(Math.floor(a/e)+1);break;default:if(i)throw new FormatError(`Invalid style "${i}" in PageLabel dictionary.`);r=""}t[e]=a+r;n++}return t}get pageLayout(){const e=this._catDict.get("PageLayout");let t="";if(e instanceof Name)switch(e.name){case"SinglePage":case"OneColumn":case"TwoColumnLeft":case"TwoColumnRight":case"TwoPageLeft":case"TwoPageRight":t=e.name}return shadow(this,"pageLayout",t)}get pageMode(){const e=this._catDict.get("PageMode");let t="UseNone";if(e instanceof Name)switch(e.name){case"UseNone":case"UseOutlines":case"UseThumbs":case"FullScreen":case"UseOC":case"UseAttachments":t=e.name}return shadow(this,"pageMode",t)}get viewerPreferences(){const e=this._catDict.get("ViewerPreferences");if(!(e instanceof Dict))return shadow(this,"viewerPreferences",null);let t=null;for(const i of e.getKeys()){const a=e.get(i);let s;switch(i){case"HideToolbar":case"HideMenubar":case"HideWindowUI":case"FitWindow":case"CenterWindow":case"DisplayDocTitle":case"PickTrayByPDFSize":"boolean"==typeof a&&(s=a);break;case"NonFullScreenPageMode":if(a instanceof Name)switch(a.name){case"UseNone":case"UseOutlines":case"UseThumbs":case"UseOC":s=a.name;break;default:s="UseNone"}break;case"Direction":if(a instanceof Name)switch(a.name){case"L2R":case"R2L":s=a.name;break;default:s="L2R"}break;case"ViewArea":case"ViewClip":case"PrintArea":case"PrintClip":if(a instanceof Name)switch(a.name){case"MediaBox":case"CropBox":case"BleedBox":case"TrimBox":case"ArtBox":s=a.name;break;default:s="CropBox"}break;case"PrintScaling":if(a instanceof Name)switch(a.name){case"None":case"AppDefault":s=a.name;break;default:s="AppDefault"}break;case"Duplex":if(a instanceof Name)switch(a.name){case"Simplex":case"DuplexFlipShortEdge":case"DuplexFlipLongEdge":s=a.name;break;default:s="None"}break;case"PrintPageRange":if(Array.isArray(a)&&a.length%2==0){a.every(((e,t,i)=>Number.isInteger(e)&&e>0&&(0===t||e>=i[t-1])&&e<=this.numPages))&&(s=a)}break;case"NumCopies":Number.isInteger(a)&&a>0&&(s=a);break;default:warn(`Ignoring non-standard key in ViewerPreferences: ${i}.`);continue}if(void 0!==s){t||(t=Object.create(null));t[i]=s}else warn(`Bad value, for key "${i}", in ViewerPreferences: ${a}.`)}return shadow(this,"viewerPreferences",t)}get openAction(){const e=this._catDict.get("OpenAction"),t=Object.create(null);if(e instanceof Dict){const i=new Dict(this.xref);i.set("A",e);const a={url:null,dest:null,action:null};Catalog.parseDestDictionary({destDict:i,resultObj:a});Array.isArray(a.dest)?t.dest=a.dest:a.action&&(t.action=a.action)}else Array.isArray(e)&&(t.dest=e);return shadow(this,"openAction",objectSize(t)>0?t:null)}get attachments(){const e=this._catDict.get("Names");let t=null;if(e instanceof Dict&&e.has("EmbeddedFiles")){const i=new NameTree(e.getRaw("EmbeddedFiles"),this.xref);for(const[e,a]of i.getAll()){const i=new FileSpec(a,this.xref);t||(t=Object.create(null));t[stringToPDFString(e)]=i.serializable}}return shadow(this,"attachments",t)}get xfaImages(){const e=this._catDict.get("Names");let t=null;if(e instanceof Dict&&e.has("XFAImages")){const i=new NameTree(e.getRaw("XFAImages"),this.xref);for(const[e,a]of i.getAll()){t||(t=new Dict(this.xref));t.set(stringToPDFString(e),a)}}return shadow(this,"xfaImages",t)}_collectJavaScript(){const e=this._catDict.get("Names");let t=null;function appendIfJavaScriptDict(e,i){if(!(i instanceof Dict))return;if(!isName(i.get("S"),"JavaScript"))return;let a=i.get("JS");if(a instanceof BaseStream)a=a.getString();else if("string"!=typeof a)return;a=stringToPDFString(a).replaceAll("\0","");a&&(t||=new Map).set(e,a)}if(e instanceof Dict&&e.has("JavaScript")){const t=new NameTree(e.getRaw("JavaScript"),this.xref);for(const[e,i]of t.getAll())appendIfJavaScriptDict(stringToPDFString(e),i)}const i=this._catDict.get("OpenAction");i&&appendIfJavaScriptDict("OpenAction",i);return t}get jsActions(){const e=this._collectJavaScript();let t=collectActions(this.xref,this._catDict,fA);if(e){t||=Object.create(null);for(const[i,a]of e)i in t?t[i].push(a):t[i]=[a]}return shadow(this,"jsActions",t)}async fontFallback(e,t){const i=await Promise.all(this.fontCache);for(const a of i)if(a.loadedName===e){a.fallback(t);return}}async cleanup(e=!1){clearGlobalCaches();this.globalImageCache.clear(e);this.pageKidsCountCache.clear();this.pageIndexCache.clear();this.pageDictCache.clear();this.nonBlendModesSet.clear();const t=await Promise.all(this.fontCache);for(const{dict:e}of t)delete e.cacheKey;this.fontCache.clear();this.builtInCMapCache.clear();this.standardFontDataCache.clear();this.systemFontCache.clear()}async getPageDict(e){const t=[this.toplevelPagesDict],i=new RefSet,a=this._catDict.getRaw("Pages");a instanceof Ref&&i.put(a);const s=this.xref,r=this.pageKidsCountCache,n=this.pageIndexCache,g=this.pageDictCache;let o=0;for(;t.length;){const a=t.pop();if(a instanceof Ref){const c=r.get(a);if(c>=0&&o+c<=e){o+=c;continue}if(i.has(a))throw new FormatError("Pages tree contains circular reference.");i.put(a);const C=await(g.get(a)||s.fetchAsync(a));if(C instanceof Dict){let t=C.getRaw("Type");t instanceof Ref&&(t=await s.fetchAsync(t));if(isName(t,"Page")||!C.has("Kids")){r.has(a)||r.put(a,1);n.has(a)||n.put(a,o);if(o===e)return[C,a];o++;continue}}t.push(C);continue}if(!(a instanceof Dict))throw new FormatError("Page dictionary kid reference points to wrong type of object.");const{objId:c}=a;let C=a.getRaw("Count");C instanceof Ref&&(C=await s.fetchAsync(C));if(Number.isInteger(C)&&C>=0){c&&!r.has(c)&&r.put(c,C);if(o+C<=e){o+=C;continue}}let h=a.getRaw("Kids");h instanceof Ref&&(h=await s.fetchAsync(h));if(!Array.isArray(h)){let t=a.getRaw("Type");t instanceof Ref&&(t=await s.fetchAsync(t));if(isName(t,"Page")||!a.has("Kids")){if(o===e)return[a,null];o++;continue}throw new FormatError("Page dictionary kids object is not an array.")}for(let e=h.length-1;e>=0;e--){const i=h[e];t.push(i);a===this.toplevelPagesDict&&i instanceof Ref&&!g.has(i)&&g.put(i,s.fetchAsync(i))}}throw new Error(`Page index ${e} not found.`)}async getAllPageDicts(e=!1){const{ignoreErrors:t}=this.pdfManager.evaluatorOptions,i=[{currentNode:this.toplevelPagesDict,posInKids:0}],a=new RefSet,s=this._catDict.getRaw("Pages");s instanceof Ref&&a.put(s);const r=new Map,n=this.xref,g=this.pageIndexCache;let o=0;function addPageDict(e,t){t&&!g.has(t)&&g.put(t,o);r.set(o++,[e,t])}function addPageError(i){if(i instanceof XRefEntryException&&!e)throw i;if(e&&t&&0===o){warn(`getAllPageDicts - Skipping invalid first page: "${i}".`);i=Dict.empty}r.set(o++,[i,null])}for(;i.length>0;){const e=i.at(-1),{currentNode:t,posInKids:s}=e;let r=t.getRaw("Kids");if(r instanceof Ref)try{r=await n.fetchAsync(r)}catch(e){addPageError(e);break}if(!Array.isArray(r)){addPageError(new FormatError("Page dictionary kids object is not an array."));break}if(s>=r.length){i.pop();continue}const g=r[s];let o;if(g instanceof Ref){if(a.has(g)){addPageError(new FormatError("Pages tree contains circular reference."));break}a.put(g);try{o=await n.fetchAsync(g)}catch(e){addPageError(e);break}}else o=g;if(!(o instanceof Dict)){addPageError(new FormatError("Page dictionary kid reference points to wrong type of object."));break}let c=o.getRaw("Type");if(c instanceof Ref)try{c=await n.fetchAsync(c)}catch(e){addPageError(e);break}isName(c,"Page")||!o.has("Kids")?addPageDict(o,g instanceof Ref?g:null):i.push({currentNode:o,posInKids:0});e.posInKids++}return r}getPageIndex(e){const t=this.pageIndexCache.get(e);if(void 0!==t)return Promise.resolve(t);const i=this.xref;let a=0;const next=t=>function pagesBeforeRef(t){let a,s=0;return i.fetchAsync(t).then((function(i){if(isRefsEqual(t,e)&&!isDict(i,"Page")&&!(i instanceof Dict&&!i.has("Type")&&i.has("Contents")))throw new FormatError("The reference does not point to a /Page dictionary.");if(!i)return null;if(!(i instanceof Dict))throw new FormatError("Node must be a dictionary.");a=i.getRaw("Parent");return i.getAsync("Parent")})).then((function(e){if(!e)return null;if(!(e instanceof Dict))throw new FormatError("Parent must be a dictionary.");return e.getAsync("Kids")})).then((function(e){if(!e)return null;const r=[];let n=!1;for(const a of e){if(!(a instanceof Ref))throw new FormatError("Kid must be a reference.");if(isRefsEqual(a,t)){n=!0;break}r.push(i.fetchAsync(a).then((function(e){if(!(e instanceof Dict))throw new FormatError("Kid node must be a dictionary.");e.has("Count")?s+=e.get("Count"):s++})))}if(!n)throw new FormatError("Kid reference not found in parent's kids.");return Promise.all(r).then((function(){return[s,a]}))}))}(t).then((t=>{if(!t){this.pageIndexCache.put(e,a);return a}const[i,s]=t;a+=i;return next(s)}));return next(e)}get baseUrl(){const e=this._catDict.get("URI");if(e instanceof Dict){const t=e.get("Base");if("string"==typeof t){const e=createValidAbsoluteUrl(t,null,{tryConvertEncoding:!0});if(e)return shadow(this,"baseUrl",e.href)}}return shadow(this,"baseUrl",this.pdfManager.docBaseUrl)}static parseDestDictionary({destDict:e,resultObj:t,docBaseUrl:i=null,docAttachments:a=null}){if(!(e instanceof Dict)){warn("parseDestDictionary: `destDict` must be a dictionary.");return}let s,r,n=e.get("A");if(!(n instanceof Dict))if(e.has("Dest"))n=e.get("Dest");else{n=e.get("AA");n instanceof Dict&&(n.has("D")?n=n.get("D"):n.has("U")&&(n=n.get("U")))}if(n instanceof Dict){const e=n.get("S");if(!(e instanceof Name)){warn("parseDestDictionary: Invalid type in Action dictionary.");return}const i=e.name;switch(i){case"ResetForm":const e=n.get("Flags"),g=!(1&("number"==typeof e?e:0)),o=[],c=[];for(const e of n.get("Fields")||[])e instanceof Ref?c.push(e.toString()):"string"==typeof e&&o.push(stringToPDFString(e));t.resetForm={fields:o,refs:c,include:g};break;case"URI":s=n.get("URI");s instanceof Name&&(s="/"+s.name);break;case"GoTo":r=n.get("D");break;case"Launch":case"GoToR":const C=n.get("F");if(C instanceof Dict){const e=new FileSpec(C,null,!0),{rawFilename:t}=e.serializable;s=t}else"string"==typeof C&&(s=C);const h=fetchRemoteDest(n);h&&"string"==typeof s&&(s=s.split("#",1)[0]+"#"+h);const l=n.get("NewWindow");"boolean"==typeof l&&(t.newWindow=l);break;case"GoToE":const Q=n.get("T");let E;if(a&&Q instanceof Dict){const e=Q.get("R"),t=Q.get("N");isName(e,"C")&&"string"==typeof t&&(E=a[stringToPDFString(t)])}if(E){t.attachment=E;const e=fetchRemoteDest(n);e&&(t.attachmentDest=e)}else warn('parseDestDictionary - unimplemented "GoToE" action.');break;case"Named":const u=n.get("N");u instanceof Name&&(t.action=u.name);break;case"SetOCGState":const d=n.get("State"),f=n.get("PreserveRB");if(!Array.isArray(d)||0===d.length)break;const p=[];for(const e of d)if(e instanceof Name)switch(e.name){case"ON":case"OFF":case"Toggle":p.push(e.name)}else e instanceof Ref&&p.push(e.toString());if(p.length!==d.length)break;t.setOCGState={state:p,preserveRB:"boolean"!=typeof f||f};break;case"JavaScript":const m=n.get("JS");let y;m instanceof BaseStream?y=m.getString():"string"==typeof m&&(y=m);const w=y&&recoverJsURL(stringToPDFString(y));if(w){s=w.url;t.newWindow=w.newWindow;break}default:if("JavaScript"===i||"SubmitForm"===i)break;warn(`parseDestDictionary - unsupported action: "${i}".`)}}else e.has("Dest")&&(r=e.get("Dest"));if("string"==typeof s){const e=createValidAbsoluteUrl(s,i,{addDefaultProtocol:!0,tryConvertEncoding:!0});e&&(t.url=e.href);t.unsafeUrl=s}if(r){r instanceof Name&&(r=r.name);"string"==typeof r?t.dest=stringToPDFString(r):isValidExplicitDest(r)&&(t.dest=r)}}}function addChildren(e,t){if(e instanceof Dict)e=e.getRawValues();else if(e instanceof BaseStream)e=e.dict.getRawValues();else if(!Array.isArray(e))return;for(const a of e)((i=a)instanceof Ref||i instanceof Dict||i instanceof BaseStream||Array.isArray(i))&&t.push(a);var i}class ObjectLoader{constructor(e,t,i){this.dict=e;this.keys=t;this.xref=i;this.refSet=null}async load(){if(this.xref.stream.isDataLoaded)return;const{keys:e,dict:t}=this;this.refSet=new RefSet;const i=[];for(const a of e){const e=t.getRaw(a);void 0!==e&&i.push(e)}return this._walk(i)}async _walk(e){const t=[],i=[];for(;e.length;){let a=e.pop();if(a instanceof Ref){if(this.refSet.has(a))continue;try{this.refSet.put(a);a=this.xref.fetch(a)}catch(e){if(!(e instanceof MissingDataException)){warn(`ObjectLoader._walk - requesting all data: "${e}".`);this.refSet=null;const{manager:t}=this.xref.stream;return t.requestAllChunks()}t.push(a);i.push({begin:e.begin,end:e.end})}}if(a instanceof BaseStream){const e=a.getBaseStreams();if(e){let s=!1;for(const t of e)if(!t.isDataLoaded){s=!0;i.push({begin:t.start,end:t.end})}s&&t.push(a)}}addChildren(a,e)}if(i.length){await this.xref.stream.manager.requestRanges(i);for(const e of t)e instanceof Ref&&this.refSet.remove(e);return this._walk(t)}this.refSet=null}}const xs=Symbol(),Ls=Symbol(),Hs=Symbol(),Js=Symbol(),Ys=Symbol(),vs=Symbol(),Ks=Symbol(),Ts=Symbol(),qs=Symbol(),Os=Symbol("content"),Ws=Symbol("data"),js=Symbol(),Xs=Symbol("extra"),Zs=Symbol(),Vs=Symbol(),zs=Symbol(),_s=Symbol(),$s=Symbol(),Ar=Symbol(),er=Symbol(),tr=Symbol(),ir=Symbol(),ar=Symbol(),sr=Symbol(),rr=Symbol(),nr=Symbol(),gr=Symbol(),or=Symbol(),Ir=Symbol(),cr=Symbol(),Cr=Symbol(),hr=Symbol(),lr=Symbol(),Qr=Symbol(),Er=Symbol(),ur=Symbol(),dr=Symbol(),fr=Symbol(),pr=Symbol(),mr=Symbol(),yr=Symbol(),wr=Symbol(),Dr=Symbol(),br=Symbol(),Fr=Symbol(),Sr=Symbol("namespaceId"),kr=Symbol("nodeName"),Rr=Symbol(),Nr=Symbol(),Gr=Symbol(),Mr=Symbol(),Ur=Symbol(),xr=Symbol(),Lr=Symbol(),Hr=Symbol(),Jr=Symbol("root"),Yr=Symbol(),vr=Symbol(),Kr=Symbol(),Tr=Symbol(),qr=Symbol(),Or=Symbol(),Pr=Symbol(),Wr=Symbol(),jr=Symbol(),Xr=Symbol(),Zr=Symbol(),Vr=Symbol("uid"),zr=Symbol(),_r={config:{id:0,check:e=>e.startsWith("http://www.xfa.org/schema/xci/")},connectionSet:{id:1,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-connection-set/")},datasets:{id:2,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-data/")},form:{id:3,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-form/")},localeSet:{id:4,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-locale-set/")},pdf:{id:5,check:e=>"http://ns.adobe.com/xdp/pdf/"===e},signature:{id:6,check:e=>"http://www.w3.org/2000/09/xmldsig#"===e},sourceSet:{id:7,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-source-set/")},stylesheet:{id:8,check:e=>"http://www.w3.org/1999/XSL/Transform"===e},template:{id:9,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-template/")},xdc:{id:10,check:e=>e.startsWith("http://www.xfa.org/schema/xdc/")},xdp:{id:11,check:e=>"http://ns.adobe.com/xdp/"===e},xfdf:{id:12,check:e=>"http://ns.adobe.com/xfdf/"===e},xhtml:{id:13,check:e=>"http://www.w3.org/1999/xhtml"===e},xmpmeta:{id:14,check:e=>"http://ns.adobe.com/xmpmeta/"===e}},$r={pt:e=>e,cm:e=>e/2.54*72,mm:e=>e/25.4*72,in:e=>72*e,px:e=>e},An=/([+-]?\d+\.?\d*)(.*)/;function stripQuotes(e){return e.startsWith("'")||e.startsWith('"')?e.slice(1,-1):e}function getInteger({data:e,defaultValue:t,validate:i}){if(!e)return t;e=e.trim();const a=parseInt(e,10);return!isNaN(a)&&i(a)?a:t}function getFloat({data:e,defaultValue:t,validate:i}){if(!e)return t;e=e.trim();const a=parseFloat(e);return!isNaN(a)&&i(a)?a:t}function getKeyword({data:e,defaultValue:t,validate:i}){return e&&i(e=e.trim())?e:t}function getStringOption(e,t){return getKeyword({data:e,defaultValue:t[0],validate:e=>t.includes(e)})}function getMeasurement(e,t="0"){t||="0";if(!e)return getMeasurement(t);const i=e.trim().match(An);if(!i)return getMeasurement(t);const[,a,s]=i,r=parseFloat(a);if(isNaN(r))return getMeasurement(t);if(0===r)return 0;const n=$r[s];return n?n(r):r}function getRatio(e){if(!e)return{num:1,den:1};const t=e.trim().split(/\s*:\s*/).map((e=>parseFloat(e))).filter((e=>!isNaN(e)));1===t.length&&t.push(1);if(0===t.length)return{num:1,den:1};const[i,a]=t;return{num:i,den:a}}function getRelevant(e){return e?e.trim().split(/\s+/).map((e=>({excluded:"-"===e[0],viewname:e.substring(1)}))):[]}class HTMLResult{static get FAILURE(){return shadow(this,"FAILURE",new HTMLResult(!1,null,null,null))}static get EMPTY(){return shadow(this,"EMPTY",new HTMLResult(!0,null,null,null))}constructor(e,t,i,a){this.success=e;this.html=t;this.bbox=i;this.breakNode=a}isBreak(){return!!this.breakNode}static breakNode(e){return new HTMLResult(!1,null,null,e)}static success(e,t=null){return new HTMLResult(!0,e,t,null)}}class FontFinder{constructor(e){this.fonts=new Map;this.cache=new Map;this.warned=new Set;this.defaultFont=null;this.add(e)}add(e,t=null){for(const t of e)this.addPdfFont(t);for(const e of this.fonts.values())e.regular||(e.regular=e.italic||e.bold||e.bolditalic);if(!t||0===t.size)return;const i=this.fonts.get("PdfJS-Fallback-PdfJS-XFA");for(const e of t)this.fonts.set(e,i)}addPdfFont(e){const t=e.cssFontInfo,i=t.fontFamily;let a=this.fonts.get(i);if(!a){a=Object.create(null);this.fonts.set(i,a);this.defaultFont||(this.defaultFont=a)}let s="";const r=parseFloat(t.fontWeight);0!==parseFloat(t.italicAngle)?s=r>=700?"bolditalic":"italic":r>=700&&(s="bold");if(!s){(e.name.includes("Bold")||e.psName?.includes("Bold"))&&(s="bold");(e.name.includes("Italic")||e.name.endsWith("It")||e.psName?.includes("Italic")||e.psName?.endsWith("It"))&&(s+="italic")}s||(s="regular");a[s]=e}getDefault(){return this.defaultFont}find(e,t=!0){let i=this.fonts.get(e)||this.cache.get(e);if(i)return i;const a=/,|-|_| |bolditalic|bold|italic|regular|it/gi;let s=e.replaceAll(a,"");i=this.fonts.get(s);if(i){this.cache.set(e,i);return i}s=s.toLowerCase();const r=[];for(const[e,t]of this.fonts.entries())e.replaceAll(a,"").toLowerCase().startsWith(s)&&r.push(t);if(0===r.length)for(const[,e]of this.fonts.entries())e.regular.name?.replaceAll(a,"").toLowerCase().startsWith(s)&&r.push(e);if(0===r.length){s=s.replaceAll(/psmt|mt/gi,"");for(const[e,t]of this.fonts.entries())e.replaceAll(a,"").toLowerCase().startsWith(s)&&r.push(t)}if(0===r.length)for(const e of this.fonts.values())e.regular.name?.replaceAll(a,"").toLowerCase().startsWith(s)&&r.push(e);if(r.length>=1){1!==r.length&&t&&warn(`XFA - Too many choices to guess the correct font: ${e}`);this.cache.set(e,r[0]);return r[0]}if(t&&!this.warned.has(e)){this.warned.add(e);warn(`XFA - Cannot find the font: ${e}`)}return null}}function selectFont(e,t){return"italic"===e.posture?"bold"===e.weight?t.bolditalic:t.italic:"bold"===e.weight?t.bold:t.regular}class FontInfo{constructor(e,t,i,a){this.lineHeight=i;this.paraMargin=t||{top:0,bottom:0,left:0,right:0};if(!e){[this.pdfFont,this.xfaFont]=this.defaultFont(a);return}this.xfaFont={typeface:e.typeface,posture:e.posture,weight:e.weight,size:e.size,letterSpacing:e.letterSpacing};const s=a.find(e.typeface);if(s){this.pdfFont=selectFont(e,s);this.pdfFont||([this.pdfFont,this.xfaFont]=this.defaultFont(a))}else[this.pdfFont,this.xfaFont]=this.defaultFont(a)}defaultFont(e){const t=e.find("Helvetica",!1)||e.find("Myriad Pro",!1)||e.find("Arial",!1)||e.getDefault();if(t?.regular){const e=t.regular;return[e,{typeface:e.cssFontInfo.fontFamily,posture:"normal",weight:"normal",size:10,letterSpacing:0}]}return[null,{typeface:"Courier",posture:"normal",weight:"normal",size:10,letterSpacing:0}]}}class FontSelector{constructor(e,t,i,a){this.fontFinder=a;this.stack=[new FontInfo(e,t,i,a)]}pushData(e,t,i){const a=this.stack.at(-1);for(const t of["typeface","posture","weight","size","letterSpacing"])e[t]||(e[t]=a.xfaFont[t]);for(const e of["top","bottom","left","right"])isNaN(t[e])&&(t[e]=a.paraMargin[e]);const s=new FontInfo(e,t,i||a.lineHeight,this.fontFinder);s.pdfFont||(s.pdfFont=a.pdfFont);this.stack.push(s)}popFont(){this.stack.pop()}topFont(){return this.stack.at(-1)}}class TextMeasure{constructor(e,t,i,a){this.glyphs=[];this.fontSelector=new FontSelector(e,t,i,a);this.extraHeight=0}pushData(e,t,i){this.fontSelector.pushData(e,t,i)}popFont(e){return this.fontSelector.popFont()}addPara(){const e=this.fontSelector.topFont();this.extraHeight+=e.paraMargin.top+e.paraMargin.bottom}addString(e){if(!e)return;const t=this.fontSelector.topFont(),i=t.xfaFont.size;if(t.pdfFont){const a=t.xfaFont.letterSpacing,s=t.pdfFont,r=s.lineHeight||1.2,n=t.lineHeight||Math.max(1.2,r)*i,g=r-(void 0===s.lineGap?.2:s.lineGap),o=Math.max(1,g)*i,c=i/1e3,C=s.defaultWidth||s.charsToGlyphs(" ")[0].width;for(const t of e.split(/[\u2029\n]/)){const e=s.encodeString(t).join(""),i=s.charsToGlyphs(e);for(const e of i){const t=e.width||C;this.glyphs.push([t*c+a,n,o,e.unicode,!1])}this.glyphs.push([0,0,0,"\n",!0])}this.glyphs.pop()}else{for(const t of e.split(/[\u2029\n]/)){for(const e of t.split(""))this.glyphs.push([i,1.2*i,i,e,!1]);this.glyphs.push([0,0,0,"\n",!0])}this.glyphs.pop()}}compute(e){let t=-1,i=0,a=0,s=0,r=0,n=0,g=!1,o=!0;for(let c=0,C=this.glyphs.length;ce){a=Math.max(a,r);r=0;s+=n;n=d;t=-1;i=0;g=!0;o=!1}else{n=Math.max(d,n);i=r;r+=C;t=c}else if(r+C>e){s+=n;n=d;if(-1!==t){c=t;a=Math.max(a,i);r=0;t=-1;i=0}else{a=Math.max(a,r);r=C}g=!0;o=!1}else{r+=C;n=Math.max(d,n)}}a=Math.max(a,r);s+=n+this.extraHeight;return{width:1.02*a,height:s,isBroken:g}}}const en=/^[^.[]+/,tn=/^[^\]]+/,an=0,sn=1,rn=2,nn=3,gn=4,on=new Map([["$data",(e,t)=>e.datasets?e.datasets.data:e],["$record",(e,t)=>(e.datasets?e.datasets.data:e)[rr]()[0]],["$template",(e,t)=>e.template],["$connectionSet",(e,t)=>e.connectionSet],["$form",(e,t)=>e.form],["$layout",(e,t)=>e.layout],["$host",(e,t)=>e.host],["$dataWindow",(e,t)=>e.dataWindow],["$event",(e,t)=>e.event],["!",(e,t)=>e.datasets],["$xfa",(e,t)=>e],["xfa",(e,t)=>e],["$",(e,t)=>t]]),In=new WeakMap;function parseExpression(e,t,i=!0){let a=e.match(en);if(!a)return null;let[s]=a;const r=[{name:s,cacheName:"."+s,index:0,js:null,formCalc:null,operator:an}];let n=s.length;for(;n0&&C.push(e)}if(0!==C.length||g||0!==o)e=isFinite(c)?C.filter((e=>ce[c])):C.flat();else{const i=t[Ir]();if(!(t=i))return null;o=-1;e=[t]}}return 0===e.length?null:e}function createDataNode(e,t,i){const a=parseExpression(i);if(!a)return null;if(a.some((e=>e.operator===sn)))return null;const s=on.get(a[0].name);let r=0;if(s){e=s(e,t);r=1}else e=t||e;for(let t=a.length;re[Pr]())).join("")}get[hn](){const e=Object.getPrototypeOf(this);if(!e._attributes){const t=e._attributes=new Set;for(const e of Object.getOwnPropertyNames(this)){if(null===this[e]||this[e]instanceof XFAObject||this[e]instanceof XFAObjectArray)break;t.add(e)}}return shadow(this,hn,e._attributes)}[pr](e){let t=this;for(;t;){if(t===e)return!0;t=t[Ir]()}return!1}[Ir](){return this[wn]}[or](){return this[Ir]()}[rr](e=null){return e?this[e]:this[ln]}[js](){const e=Object.create(null);this[Os]&&(e.$content=this[Os]);for(const t of Object.getOwnPropertyNames(this)){const i=this[t];null!==i&&(i instanceof XFAObject?e[t]=i[js]():i instanceof XFAObjectArray?i.isEmpty()||(e[t]=i.dump()):e[t]=i)}return e}[Zr](){return null}[jr](){return HTMLResult.EMPTY}*[nr](){for(const e of this[rr]())yield e}*[un](e,t){for(const i of this[nr]())if(!e||t===e.has(i[kr])){const e=this[$s](),t=i[jr](e);t.success||(this[Xs].failingNode=i);yield t}}[Vs](){return null}[Ls](e,t){this[Xs].children.push(e)}[$s](){}[Js]({filter:e=null,include:t=!0}){if(this[Xs].generator){const e=this[$s](),t=this[Xs].failingNode[jr](e);if(!t.success)return t;t.html&&this[Ls](t.html,t.bbox);delete this[Xs].failingNode}else this[Xs].generator=this[un](e,t);for(;;){const e=this[Xs].generator.next();if(e.done)break;const t=e.value;if(!t.success)return t;t.html&&this[Ls](t.html,t.bbox)}this[Xs].generator=null;return HTMLResult.EMPTY}[Tr](e){this[bn]=new Set(Object.keys(e))}[fn](e){const t=this[hn],i=this[bn];return[...e].filter((e=>t.has(e)&&!i.has(e)))}[Yr](e,t=new Set){for(const i of this[ln])i[Dn](e,t)}[Dn](e,t){const i=this[dn](e,t);i?this[cn](i,e,t):this[Yr](e,t)}[dn](e,t){const{use:i,usehref:a}=this;if(!i&&!a)return null;let s=null,r=null,n=null,g=i;if(a){g=a;a.startsWith("#som(")&&a.endsWith(")")?r=a.slice(5,-1):a.startsWith(".#som(")&&a.endsWith(")")?r=a.slice(6,-1):a.startsWith("#")?n=a.slice(1):a.startsWith(".#")&&(n=a.slice(2))}else i.startsWith("#")?n=i.slice(1):r=i;this.use=this.usehref="";if(n)s=e.get(n);else{s=searchNode(e.get(Jr),this,r,!0,!1);s&&(s=s[0])}if(!s){warn(`XFA - Invalid prototype reference: ${g}.`);return null}if(s[kr]!==this[kr]){warn(`XFA - Incompatible prototype: ${s[kr]} !== ${this[kr]}.`);return null}if(t.has(s)){warn("XFA - Cycle detected in prototypes use.");return null}t.add(s);const o=s[dn](e,t);o&&s[cn](o,e,t);s[Yr](e,t);t.delete(s);return s}[cn](e,t,i){if(i.has(e)){warn("XFA - Cycle detected in prototypes use.");return}!this[Os]&&e[Os]&&(this[Os]=e[Os]);new Set(i).add(e);for(const t of this[fn](e[bn])){this[t]=e[t];this[bn]&&this[bn].add(t)}for(const a of Object.getOwnPropertyNames(this)){if(this[hn].has(a))continue;const s=this[a],r=e[a];if(s instanceof XFAObjectArray){for(const e of s[ln])e[Dn](t,i);for(let a=s[ln].length,n=r[ln].length;aXFAObject[Bn](e))):"object"==typeof e&&null!==e?Object.assign({},e):e}[Ts](){const e=Object.create(Object.getPrototypeOf(this));for(const t of Object.getOwnPropertySymbols(this))try{e[t]=this[t]}catch{shadow(e,t,this[t])}e[Vr]=`${e[kr]}${Sn++}`;e[ln]=[];for(const t of Object.getOwnPropertyNames(this)){if(this[hn].has(t)){e[t]=XFAObject[Bn](this[t]);continue}const i=this[t];e[t]=i instanceof XFAObjectArray?new XFAObjectArray(i[mn]):null}for(const t of this[ln]){const i=t[kr],a=t[Ts]();e[ln].push(a);a[wn]=e;null===e[i]?e[i]=a:e[i][ln].push(a)}return e}[rr](e=null){return e?this[ln].filter((t=>t[kr]===e)):this[ln]}[Ar](e){return this[e]}[er](e,t,i=!0){return Array.from(this[tr](e,t,i))}*[tr](e,t,i=!0){if("parent"!==e){for(const i of this[ln]){i[kr]===e&&(yield i);i.name===e&&(yield i);(t||i[Dr]())&&(yield*i[tr](e,t,!1))}i&&this[hn].has(e)&&(yield new XFAAttribute(this,e,this[e]))}else yield this[wn]}}class XFAObjectArray{constructor(e=1/0){this[mn]=e;this[ln]=[]}get isXFAObject(){return!1}get isXFAObjectArray(){return!0}push(e){if(this[ln].length<=this[mn]){this[ln].push(e);return!0}warn(`XFA - node "${e[kr]}" accepts no more than ${this[mn]} children`);return!1}isEmpty(){return 0===this[ln].length}dump(){return 1===this[ln].length?this[ln][0][js]():this[ln].map((e=>e[js]()))}[Ts](){const e=new XFAObjectArray(this[mn]);e[ln]=this[ln].map((e=>e[Ts]()));return e}get children(){return this[ln]}clear(){this[ln].length=0}}class XFAAttribute{constructor(e,t,i){this[wn]=e;this[kr]=t;this[Os]=i;this[qs]=!1;this[Vr]="attribute"+Sn++}[Ir](){return this[wn]}[fr](){return!0}[ir](){return this[Os].trim()}[qr](e){e=e.value||"";this[Os]=e.toString()}[Pr](){return this[Os]}[pr](e){return this[wn]===e||this[wn][pr](e)}}class XmlObject extends XFAObject{constructor(e,t,i={}){super(e,t);this[Os]="";this[Qn]=null;if("#text"!==t){const e=new Map;this[Cn]=e;for(const[t,a]of Object.entries(i))e.set(t,new XFAAttribute(this,t,a));if(i.hasOwnProperty(Rr)){const e=i[Rr].xfa.dataNode;void 0!==e&&("dataGroup"===e?this[Qn]=!1:"dataValue"===e&&(this[Qn]=!0))}}this[qs]=!1}[Xr](e){const t=this[kr];if("#text"===t){e.push(encodeToXmlString(this[Os]));return}const i=utf8StringToString(t),a=this[Sr]===kn?"xfa:":"";e.push(`<${a}${i}`);for(const[t,i]of this[Cn].entries()){const a=utf8StringToString(t);e.push(` ${a}="${encodeToXmlString(i[Os])}"`)}null!==this[Qn]&&(this[Qn]?e.push(' xfa:dataNode="dataValue"'):e.push(' xfa:dataNode="dataGroup"'));if(this[Os]||0!==this[ln].length){e.push(">");if(this[Os])"string"==typeof this[Os]?e.push(encodeToXmlString(this[Os])):this[Os][Xr](e);else for(const t of this[ln])t[Xr](e);e.push(``)}else e.push("/>")}[Nr](e){if(this[Os]){const e=new XmlObject(this[Sr],"#text");this[Hs](e);e[Os]=this[Os];this[Os]=""}this[Hs](e);return!0}[Mr](e){this[Os]+=e}[Zs](){if(this[Os]&&this[ln].length>0){const e=new XmlObject(this[Sr],"#text");this[Hs](e);e[Os]=this[Os];delete this[Os]}}[jr](){return"#text"===this[kr]?HTMLResult.success({name:"#text",value:this[Os]}):HTMLResult.EMPTY}[rr](e=null){return e?this[ln].filter((t=>t[kr]===e)):this[ln]}[_s](){return this[Cn]}[Ar](e){const t=this[Cn].get(e);return void 0!==t?t:this[rr](e)}*[tr](e,t){const i=this[Cn].get(e);i&&(yield i);for(const i of this[ln]){i[kr]===e&&(yield i);t&&(yield*i[tr](e,t))}}*[zs](e,t){const i=this[Cn].get(e);!i||t&&i[qs]||(yield i);for(const i of this[ln])yield*i[zs](e,t)}*[sr](e,t,i){for(const a of this[ln]){a[kr]!==e||i&&a[qs]||(yield a);t&&(yield*a[sr](e,t,i))}}[fr](){return null===this[Qn]?0===this[ln].length||this[ln][0][Sr]===_r.xhtml.id:this[Qn]}[ir](){return null===this[Qn]?0===this[ln].length?this[Os].trim():this[ln][0][Sr]===_r.xhtml.id?this[ln][0][Pr]().trim():null:this[Os].trim()}[qr](e){e=e.value||"";this[Os]=e.toString()}[js](e=!1){const t=Object.create(null);e&&(t.$ns=this[Sr]);this[Os]&&(t.$content=this[Os]);t.$name=this[kr];t.children=[];for(const i of this[ln])t.children.push(i[js](e));t.attributes=Object.create(null);for(const[e,i]of this[Cn])t.attributes[e]=i[Os];return t}}class ContentObject extends XFAObject{constructor(e,t){super(e,t);this[Os]=""}[Mr](e){this[Os]+=e}[Zs](){}}class OptionObject extends ContentObject{constructor(e,t,i){super(e,t);this[yn]=i}[Zs](){this[Os]=getKeyword({data:this[Os],defaultValue:this[yn][0],validate:e=>this[yn].includes(e)})}[Ys](e){super[Ys](e);delete this[yn]}}class StringObject extends ContentObject{[Zs](){this[Os]=this[Os].trim()}}class IntegerObject extends ContentObject{constructor(e,t,i,a){super(e,t);this[En]=i;this[Fn]=a}[Zs](){this[Os]=getInteger({data:this[Os],defaultValue:this[En],validate:this[Fn]})}[Ys](e){super[Ys](e);delete this[En];delete this[Fn]}}class Option01 extends IntegerObject{constructor(e,t){super(e,t,0,(e=>1===e))}}class Option10 extends IntegerObject{constructor(e,t){super(e,t,1,(e=>0===e))}}function measureToString(e){return"string"==typeof e?"0px":Number.isInteger(e)?`${e}px`:`${e.toFixed(2)}px`}const Rn={anchorType(e,t){const i=e[or]();if(i&&(!i.layout||"position"===i.layout)){"transform"in t||(t.transform="");switch(e.anchorType){case"bottomCenter":t.transform+="translate(-50%, -100%)";break;case"bottomLeft":t.transform+="translate(0,-100%)";break;case"bottomRight":t.transform+="translate(-100%,-100%)";break;case"middleCenter":t.transform+="translate(-50%,-50%)";break;case"middleLeft":t.transform+="translate(0,-50%)";break;case"middleRight":t.transform+="translate(-100%,-50%)";break;case"topCenter":t.transform+="translate(-50%,0)";break;case"topRight":t.transform+="translate(-100%,0)"}}},dimensions(e,t){const i=e[or]();let a=e.w;const s=e.h;if(i.layout?.includes("row")){const t=i[Xs],s=e.colSpan;let r;if(-1===s){r=t.columnWidths.slice(t.currentColumn).reduce(((e,t)=>e+t),0);t.currentColumn=0}else{r=t.columnWidths.slice(t.currentColumn,t.currentColumn+s).reduce(((e,t)=>e+t),0);t.currentColumn=(t.currentColumn+e.colSpan)%t.columnWidths.length}isNaN(r)||(a=e.w=r)}t.width=""!==a?measureToString(a):"auto";t.height=""!==s?measureToString(s):"auto"},position(e,t){const i=e[or]();if(!i?.layout||"position"===i.layout){t.position="absolute";t.left=measureToString(e.x);t.top=measureToString(e.y)}},rotate(e,t){if(e.rotate){"transform"in t||(t.transform="");t.transform+=`rotate(-${e.rotate}deg)`;t.transformOrigin="top left"}},presence(e,t){switch(e.presence){case"invisible":t.visibility="hidden";break;case"hidden":case"inactive":t.display="none"}},hAlign(e,t){if("para"===e[kr])switch(e.hAlign){case"justifyAll":t.textAlign="justify-all";break;case"radix":t.textAlign="left";break;default:t.textAlign=e.hAlign}else switch(e.hAlign){case"left":t.alignSelf="start";break;case"center":t.alignSelf="center";break;case"right":t.alignSelf="end"}},margin(e,t){e.margin&&(t.margin=e.margin[Zr]().margin)}};function setMinMaxDimensions(e,t){if("position"===e[or]().layout){e.minW>0&&(t.minWidth=measureToString(e.minW));e.maxW>0&&(t.maxWidth=measureToString(e.maxW));e.minH>0&&(t.minHeight=measureToString(e.minH));e.maxH>0&&(t.maxHeight=measureToString(e.maxH))}}function layoutText(e,t,i,a,s,r){const n=new TextMeasure(t,i,a,s);"string"==typeof e?n.addString(e):e[Ur](n);return n.compute(r)}function layoutNode(e,t){let i=null,a=null,s=!1;if((!e.w||!e.h)&&e.value){let r=0,n=0;if(e.margin){r=e.margin.leftInset+e.margin.rightInset;n=e.margin.topInset+e.margin.bottomInset}let g=null,o=null;if(e.para){o=Object.create(null);g=""===e.para.lineHeight?null:e.para.lineHeight;o.top=""===e.para.spaceAbove?0:e.para.spaceAbove;o.bottom=""===e.para.spaceBelow?0:e.para.spaceBelow;o.left=""===e.para.marginLeft?0:e.para.marginLeft;o.right=""===e.para.marginRight?0:e.para.marginRight}let c=e.font;if(!c){const t=e[cr]();let i=e[Ir]();for(;i&&i!==t;){if(i.font){c=i.font;break}i=i[Ir]()}}const C=(e.w||t.width)-r,h=e[Cr].fontFinder;if(e.value.exData&&e.value.exData[Os]&&"text/html"===e.value.exData.contentType){const t=layoutText(e.value.exData[Os],c,o,g,h,C);a=t.width;i=t.height;s=t.isBroken}else{const t=e.value[Pr]();if(t){const e=layoutText(t,c,o,g,h,C);a=e.width;i=e.height;s=e.isBroken}}null===a||e.w||(a+=r);null===i||e.h||(i+=n)}return{w:a,h:i,isBroken:s}}function computeBbox(e,t,i){let a;if(""!==e.w&&""!==e.h)a=[e.x,e.y,e.w,e.h];else{if(!i)return null;let s=e.w;if(""===s){if(0===e.maxW){const t=e[or]();s="position"===t.layout&&""!==t.w?0:e.minW}else s=Math.min(e.maxW,i.width);t.attributes.style.width=measureToString(s)}let r=e.h;if(""===r){if(0===e.maxH){const t=e[or]();r="position"===t.layout&&""!==t.h?0:e.minH}else r=Math.min(e.maxH,i.height);t.attributes.style.height=measureToString(r)}a=[e.x,e.y,s,r]}return a}function fixDimensions(e){const t=e[or]();if(t.layout?.includes("row")){const i=t[Xs],a=e.colSpan;let s;s=-1===a?i.columnWidths.slice(i.currentColumn).reduce(((e,t)=>e+t),0):i.columnWidths.slice(i.currentColumn,i.currentColumn+a).reduce(((e,t)=>e+t),0);isNaN(s)||(e.w=s)}t.layout&&"position"!==t.layout&&(e.x=e.y=0);"table"===e.layout&&""===e.w&&Array.isArray(e.columnWidths)&&(e.w=e.columnWidths.reduce(((e,t)=>e+t),0))}function layoutClass(e){switch(e.layout){case"position":default:return"xfaPosition";case"lr-tb":return"xfaLrTb";case"rl-row":return"xfaRlRow";case"rl-tb":return"xfaRlTb";case"row":return"xfaRow";case"table":return"xfaTable";case"tb":return"xfaTb"}}function toStyle(e,...t){const i=Object.create(null);for(const a of t){const t=e[a];if(null!==t)if(Rn.hasOwnProperty(a))Rn[a](e,i);else if(t instanceof XFAObject){const e=t[Zr]();e?Object.assign(i,e):warn(`(DEBUG) - XFA - style for ${a} not implemented yet`)}}return i}function createWrapper(e,t){const{attributes:i}=t,{style:a}=i,s={name:"div",attributes:{class:["xfaWrapper"],style:Object.create(null)},children:[]};i.class.push("xfaWrapped");if(e.border){const{widths:i,insets:r}=e.border[Xs];let n,g,o=r[0],c=r[3];const C=r[0]+r[2],h=r[1]+r[3];switch(e.border.hand){case"even":o-=i[0]/2;c-=i[3]/2;n=`calc(100% + ${(i[1]+i[3])/2-h}px)`;g=`calc(100% + ${(i[0]+i[2])/2-C}px)`;break;case"left":o-=i[0];c-=i[3];n=`calc(100% + ${i[1]+i[3]-h}px)`;g=`calc(100% + ${i[0]+i[2]-C}px)`;break;case"right":n=h?`calc(100% - ${h}px)`:"100%";g=C?`calc(100% - ${C}px)`:"100%"}const l=["xfaBorder"];isPrintOnly(e.border)&&l.push("xfaPrintOnly");const Q={name:"div",attributes:{class:l,style:{top:`${o}px`,left:`${c}px`,width:n,height:g}},children:[]};for(const e of["border","borderWidth","borderColor","borderRadius","borderStyle"])if(void 0!==a[e]){Q.attributes.style[e]=a[e];delete a[e]}s.children.push(Q,t)}else s.children.push(t);for(const e of["background","backgroundClip","top","left","width","height","minWidth","minHeight","maxWidth","maxHeight","transform","transformOrigin","visibility"])if(void 0!==a[e]){s.attributes.style[e]=a[e];delete a[e]}s.attributes.style.position="absolute"===a.position?"absolute":"relative";delete a.position;if(a.alignSelf){s.attributes.style.alignSelf=a.alignSelf;delete a.alignSelf}return s}function fixTextIndent(e){const t=getMeasurement(e.textIndent,"0px");if(t>=0)return;const i="padding"+("left"===("right"===e.textAlign?"right":"left")?"Left":"Right"),a=getMeasurement(e[i],"0px");e[i]=a-t+"px"}function setAccess(e,t){switch(e.access){case"nonInteractive":t.push("xfaNonInteractive");break;case"readOnly":t.push("xfaReadOnly");break;case"protected":t.push("xfaDisabled")}}function isPrintOnly(e){return e.relevant.length>0&&!e.relevant[0].excluded&&"print"===e.relevant[0].viewname}function getCurrentPara(e){const t=e[cr]()[Xs].paraStack;return t.length?t.at(-1):null}function setPara(e,t,i){if(i.attributes.class?.includes("xfaRich")){if(t){""===e.h&&(t.height="auto");""===e.w&&(t.width="auto")}const a=getCurrentPara(e);if(a){const e=i.attributes.style;e.display="flex";e.flexDirection="column";switch(a.vAlign){case"top":e.justifyContent="start";break;case"bottom":e.justifyContent="end";break;case"middle":e.justifyContent="center"}const t=a[Zr]();for(const[i,a]of Object.entries(t))i in e||(e[i]=a)}}}function setFontFamily(e,t,i,a){if(!i){delete a.fontFamily;return}const s=stripQuotes(e.typeface);a.fontFamily=`"${s}"`;const r=i.find(s);if(r){const{fontFamily:i}=r.regular.cssFontInfo;i!==s&&(a.fontFamily=`"${i}"`);const n=getCurrentPara(t);if(n&&""!==n.lineHeight)return;if(a.lineHeight)return;const g=selectFont(e,r);g&&(a.lineHeight=Math.max(1.2,g.lineHeight))}}function fixURL(e){const t=createValidAbsoluteUrl(e,null,{addDefaultProtocol:!0,tryConvertEncoding:!0});return t?t.href:null}function createLine(e,t){return{name:"div",attributes:{class:["lr-tb"===e.layout?"xfaLr":"xfaRl"]},children:t}}function flushHTML(e){if(!e[Xs])return null;const t={name:"div",attributes:e[Xs].attributes,children:e[Xs].children};if(e[Xs].failingNode){const i=e[Xs].failingNode[Vs]();i&&(e.layout.endsWith("-tb")?t.children.push(createLine(e,[i])):t.children.push(i))}return 0===t.children.length?null:t}function addHTML(e,t,i){const a=e[Xs],s=a.availableSpace,[r,n,g,o]=i;switch(e.layout){case"position":a.width=Math.max(a.width,r+g);a.height=Math.max(a.height,n+o);a.children.push(t);break;case"lr-tb":case"rl-tb":if(!a.line||1===a.attempt){a.line=createLine(e,[]);a.children.push(a.line);a.numberInLine=0}a.numberInLine+=1;a.line.children.push(t);if(0===a.attempt){a.currentWidth+=g;a.height=Math.max(a.height,a.prevHeight+o)}else{a.currentWidth=g;a.prevHeight=a.height;a.height+=o;a.attempt=0}a.width=Math.max(a.width,a.currentWidth);break;case"rl-row":case"row":{a.children.push(t);a.width+=g;a.height=Math.max(a.height,o);const e=measureToString(a.height);for(const t of a.children)t.attributes.style.height=e;break}case"table":case"tb":a.width=Math.min(s.width,Math.max(a.width,g));a.height+=o;a.children.push(t)}}function getAvailableSpace(e){const t=e[Xs].availableSpace,i=e.margin?e.margin.topInset+e.margin.bottomInset:0,a=e.margin?e.margin.leftInset+e.margin.rightInset:0;switch(e.layout){case"lr-tb":case"rl-tb":return 0===e[Xs].attempt?{width:t.width-a-e[Xs].currentWidth,height:t.height-i-e[Xs].prevHeight}:{width:t.width-a,height:t.height-i-e[Xs].height};case"rl-row":case"row":return{width:e[Xs].columnWidths.slice(e[Xs].currentColumn).reduce(((e,t)=>e+t)),height:t.height-a};case"table":case"tb":return{width:t.width-a,height:t.height-i-e[Xs].height};default:return t}}function checkDimensions(e,t){if(null===e[cr]()[Xs].firstUnsplittable)return!0;if(0===e.w||0===e.h)return!0;const i=e[or](),a=i[Xs]?.attempt||0,[,s,r,n]=function getTransformedBBox(e){let t,i,a=""===e.w?NaN:e.w,s=""===e.h?NaN:e.h,[r,n]=[0,0];switch(e.anchorType||""){case"bottomCenter":[r,n]=[a/2,s];break;case"bottomLeft":[r,n]=[0,s];break;case"bottomRight":[r,n]=[a,s];break;case"middleCenter":[r,n]=[a/2,s/2];break;case"middleLeft":[r,n]=[0,s/2];break;case"middleRight":[r,n]=[a,s/2];break;case"topCenter":[r,n]=[a/2,0];break;case"topRight":[r,n]=[a,0]}switch(e.rotate||0){case 0:[t,i]=[-r,-n];break;case 90:[t,i]=[-n,r];[a,s]=[s,-a];break;case 180:[t,i]=[r,n];[a,s]=[-a,-s];break;case 270:[t,i]=[n,-r];[a,s]=[-s,a]}return[e.x+t+Math.min(0,a),e.y+i+Math.min(0,s),Math.abs(a),Math.abs(s)]}(e);switch(i.layout){case"lr-tb":case"rl-tb":return 0===a?e[cr]()[Xs].noLayoutFailure?""!==e.w?Math.round(r-t.width)<=2:t.width>2:!(""!==e.h&&Math.round(n-t.height)>2)&&(""!==e.w?Math.round(r-t.width)<=2||0===i[Xs].numberInLine&&t.height>2:t.width>2):!!e[cr]()[Xs].noLayoutFailure||!(""!==e.h&&Math.round(n-t.height)>2)&&((""===e.w||Math.round(r-t.width)<=2||!i[wr]())&&t.height>2);case"table":case"tb":return!!e[cr]()[Xs].noLayoutFailure||(""===e.h||e[yr]()?(""===e.w||Math.round(r-t.width)<=2||!i[wr]())&&t.height>2:Math.round(n-t.height)<=2);case"position":if(e[cr]()[Xs].noLayoutFailure)return!0;if(""===e.h||Math.round(n+s-t.height)<=2)return!0;return n+s>e[cr]()[Xs].currentContentArea.h;case"rl-row":case"row":return!!e[cr]()[Xs].noLayoutFailure||(""===e.h||Math.round(n-t.height)<=2);default:return!0}}const Nn=_r.template.id,Gn="http://www.w3.org/2000/svg",Mn=/^H(\d+)$/,Un=new Set(["image/gif","image/jpeg","image/jpg","image/pjpeg","image/png","image/apng","image/x-png","image/bmp","image/x-ms-bmp","image/tiff","image/tif","application/octet-stream"]),xn=[[[66,77],"image/bmp"],[[255,216,255],"image/jpeg"],[[73,73,42,0],"image/tiff"],[[77,77,0,42],"image/tiff"],[[71,73,70,56,57,97],"image/gif"],[[137,80,78,71,13,10,26,10],"image/png"]];function getBorderDims(e){if(!e||!e.border)return{w:0,h:0};const t=e.border[ar]();return t?{w:t.widths[0]+t.widths[2]+t.insets[0]+t.insets[2],h:t.widths[1]+t.widths[3]+t.insets[1]+t.insets[3]}:{w:0,h:0}}function hasMargin(e){return e.margin&&(e.margin.topInset||e.margin.rightInset||e.margin.bottomInset||e.margin.leftInset)}function _setValue(e,t){if(!e.value){const t=new Value({});e[Hs](t);e.value=t}e.value[qr](t)}function*getContainedChildren(e){for(const t of e[rr]())t instanceof SubformSet?yield*t[nr]():yield t}function isRequired(e){return"error"===e.validate?.nullTest}function setTabIndex(e){for(;e;){if(!e.traversal){e[Or]=e[Ir]()[Or];return}if(e[Or])return;let t=null;for(const i of e.traversal[rr]())if("next"===i.operation){t=i;break}if(!t||!t.ref){e[Or]=e[Ir]()[Or];return}const i=e[cr]();e[Or]=++i[Or];const a=i[vr](t.ref,e);if(!a)return;e=a[0]}}function applyAssist(e,t){const i=e.assist;if(i){const e=i[jr]();e&&(t.title=e);const a=i.role.match(Mn);if(a){const e="heading",i=a[1];t.role=e;t["aria-level"]=i}}if("table"===e.layout)t.role="table";else if("row"===e.layout)t.role="row";else{const i=e[Ir]();"row"===i.layout&&(t.role="TH"===i.assist?.role?"columnheader":"cell")}}function ariaLabel(e){if(!e.assist)return null;const t=e.assist;return t.speak&&""!==t.speak[Os]?t.speak[Os]:t.toolTip?t.toolTip[Os]:null}function valueToHtml(e){return HTMLResult.success({name:"div",attributes:{class:["xfaRich"],style:Object.create(null)},children:[{name:"span",attributes:{style:Object.create(null)},value:e}]})}function setFirstUnsplittable(e){const t=e[cr]();if(null===t[Xs].firstUnsplittable){t[Xs].firstUnsplittable=e;t[Xs].noLayoutFailure=!0}}function unsetFirstUnsplittable(e){const t=e[cr]();t[Xs].firstUnsplittable===e&&(t[Xs].noLayoutFailure=!1)}function handleBreak(e){if(e[Xs])return!1;e[Xs]=Object.create(null);if("auto"===e.targetType)return!1;const t=e[cr]();let i=null;if(e.target){i=t[vr](e.target,e[Ir]());if(!i)return!1;i=i[0]}const{currentPageArea:a,currentContentArea:s}=t[Xs];if("pageArea"===e.targetType){i instanceof PageArea||(i=null);if(e.startNew){e[Xs].target=i||a;return!0}if(i&&i!==a){e[Xs].target=i;return!0}return!1}i instanceof ContentArea||(i=null);const r=i&&i[Ir]();let n,g=r;if(e.startNew)if(i){const e=r.contentArea.children,t=e.indexOf(s),a=e.indexOf(i);-1!==t&&te;a[Xs].noLayoutFailure=!0;const n=t[jr](i);e[Ls](n.html,n.bbox);a[Xs].noLayoutFailure=s;t[or]=r}class AppearanceFilter extends StringObject{constructor(e){super(Nn,"appearanceFilter");this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Arc extends XFAObject{constructor(e){super(Nn,"arc",!0);this.circular=getInteger({data:e.circular,defaultValue:0,validate:e=>1===e});this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.startAngle=getFloat({data:e.startAngle,defaultValue:0,validate:e=>!0});this.sweepAngle=getFloat({data:e.sweepAngle,defaultValue:360,validate:e=>!0});this.use=e.use||"";this.usehref=e.usehref||"";this.edge=null;this.fill=null}[jr](){const e=this.edge||new Edge({}),t=e[Zr](),i=Object.create(null);"visible"===this.fill?.presence?Object.assign(i,this.fill[Zr]()):i.fill="transparent";i.strokeWidth=measureToString("visible"===e.presence?e.thickness:0);i.stroke=t.color;let a;const s={xmlns:Gn,style:{width:"100%",height:"100%",overflow:"visible"}};if(360===this.sweepAngle)a={name:"ellipse",attributes:{xmlns:Gn,cx:"50%",cy:"50%",rx:"50%",ry:"50%",style:i}};else{const e=this.startAngle*Math.PI/180,t=this.sweepAngle*Math.PI/180,r=this.sweepAngle>180?1:0,[n,g,o,c]=[50*(1+Math.cos(e)),50*(1-Math.sin(e)),50*(1+Math.cos(e+t)),50*(1-Math.sin(e+t))];a={name:"path",attributes:{xmlns:Gn,d:`M ${n} ${g} A 50 50 0 ${r} 0 ${o} ${c}`,vectorEffect:"non-scaling-stroke",style:i}};Object.assign(s,{viewBox:"0 0 100 100",preserveAspectRatio:"none"})}const r={name:"svg",children:[a],attributes:s};if(hasMargin(this[Ir]()[Ir]()))return HTMLResult.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[r]});r.attributes.style.position="absolute";return HTMLResult.success(r)}}class Area extends XFAObject{constructor(e){super(Nn,"area",!0);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.id=e.id||"";this.name=e.name||"";this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.desc=null;this.extras=null;this.area=new XFAObjectArray;this.draw=new XFAObjectArray;this.exObject=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.field=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray}*[nr](){yield*getContainedChildren(this)}[Dr](){return!0}[dr](){return!0}[Ls](e,t){const[i,a,s,r]=t;this[Xs].width=Math.max(this[Xs].width,i+s);this[Xs].height=Math.max(this[Xs].height,a+r);this[Xs].children.push(e)}[$s](){return this[Xs].availableSpace}[jr](e){const t=toStyle(this,"position"),i={style:t,id:this[Vr],class:["xfaArea"]};isPrintOnly(this)&&i.class.push("xfaPrintOnly");this.name&&(i.xfaName=this.name);const a=[];this[Xs]={children:a,width:0,height:0,availableSpace:e};const s=this[Js]({filter:new Set(["area","draw","field","exclGroup","subform","subformSet"]),include:!0});if(!s.success){if(s.isBreak())return s;delete this[Xs];return HTMLResult.FAILURE}t.width=measureToString(this[Xs].width);t.height=measureToString(this[Xs].height);const r={name:"div",attributes:i,children:a},n=[this.x,this.y,this[Xs].width,this[Xs].height];delete this[Xs];return HTMLResult.success(r,n)}}class Assist extends XFAObject{constructor(e){super(Nn,"assist",!0);this.id=e.id||"";this.role=e.role||"";this.use=e.use||"";this.usehref=e.usehref||"";this.speak=null;this.toolTip=null}[jr](){return this.toolTip?.[Os]||null}}class Barcode extends XFAObject{constructor(e){super(Nn,"barcode",!0);this.charEncoding=getKeyword({data:e.charEncoding?e.charEncoding.toLowerCase():"",defaultValue:"",validate:e=>["utf-8","big-five","fontspecific","gbk","gb-18030","gb-2312","ksc-5601","none","shift-jis","ucs-2","utf-16"].includes(e)||e.match(/iso-8859-\d{2}/)});this.checksum=getStringOption(e.checksum,["none","1mod10","1mod10_1mod11","2mod10","auto"]);this.dataColumnCount=getInteger({data:e.dataColumnCount,defaultValue:-1,validate:e=>e>=0});this.dataLength=getInteger({data:e.dataLength,defaultValue:-1,validate:e=>e>=0});this.dataPrep=getStringOption(e.dataPrep,["none","flateCompress"]);this.dataRowCount=getInteger({data:e.dataRowCount,defaultValue:-1,validate:e=>e>=0});this.endChar=e.endChar||"";this.errorCorrectionLevel=getInteger({data:e.errorCorrectionLevel,defaultValue:-1,validate:e=>e>=0&&e<=8});this.id=e.id||"";this.moduleHeight=getMeasurement(e.moduleHeight,"5mm");this.moduleWidth=getMeasurement(e.moduleWidth,"0.25mm");this.printCheckDigit=getInteger({data:e.printCheckDigit,defaultValue:0,validate:e=>1===e});this.rowColumnRatio=getRatio(e.rowColumnRatio);this.startChar=e.startChar||"";this.textLocation=getStringOption(e.textLocation,["below","above","aboveEmbedded","belowEmbedded","none"]);this.truncate=getInteger({data:e.truncate,defaultValue:0,validate:e=>1===e});this.type=getStringOption(e.type?e.type.toLowerCase():"",["aztec","codabar","code2of5industrial","code2of5interleaved","code2of5matrix","code2of5standard","code3of9","code3of9extended","code11","code49","code93","code128","code128a","code128b","code128c","code128sscc","datamatrix","ean8","ean8add2","ean8add5","ean13","ean13add2","ean13add5","ean13pwcd","fim","logmars","maxicode","msi","pdf417","pdf417macro","plessey","postauscust2","postauscust3","postausreplypaid","postausstandard","postukrm4scc","postusdpbc","postusimb","postusstandard","postus5zip","qrcode","rfid","rss14","rss14expanded","rss14limited","rss14stacked","rss14stackedomni","rss14truncated","telepen","ucc128","ucc128random","ucc128sscc","upca","upcaadd2","upcaadd5","upcapwcd","upce","upceadd2","upceadd5","upcean2","upcean5","upsmaxicode"]);this.upsMode=getStringOption(e.upsMode,["usCarrier","internationalCarrier","secureSymbol","standardSymbol"]);this.use=e.use||"";this.usehref=e.usehref||"";this.wideNarrowRatio=getRatio(e.wideNarrowRatio);this.encrypt=null;this.extras=null}}class Bind extends XFAObject{constructor(e){super(Nn,"bind",!0);this.match=getStringOption(e.match,["once","dataRef","global","none"]);this.ref=e.ref||"";this.picture=null}}class BindItems extends XFAObject{constructor(e){super(Nn,"bindItems");this.connection=e.connection||"";this.labelRef=e.labelRef||"";this.ref=e.ref||"";this.valueRef=e.valueRef||""}}class Bookend extends XFAObject{constructor(e){super(Nn,"bookend");this.id=e.id||"";this.leader=e.leader||"";this.trailer=e.trailer||"";this.use=e.use||"";this.usehref=e.usehref||""}}class BooleanElement extends Option01{constructor(e){super(Nn,"boolean");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[jr](e){return valueToHtml(1===this[Os]?"1":"0")}}class Border extends XFAObject{constructor(e){super(Nn,"border",!0);this.break=getStringOption(e.break,["close","open"]);this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.corner=new XFAObjectArray(4);this.edge=new XFAObjectArray(4);this.extras=null;this.fill=null;this.margin=null}[ar](){if(!this[Xs]){const e=this.edge.children.slice();if(e.length<4){const t=e.at(-1)||new Edge({});for(let i=e.length;i<4;i++)e.push(t)}const t=e.map((e=>e.thickness)),i=[0,0,0,0];if(this.margin){i[0]=this.margin.topInset;i[1]=this.margin.rightInset;i[2]=this.margin.bottomInset;i[3]=this.margin.leftInset}this[Xs]={widths:t,insets:i,edges:e}}return this[Xs]}[Zr](){const{edges:e}=this[ar](),t=e.map((e=>{const t=e[Zr]();t.color||="#000000";return t})),i=Object.create(null);this.margin&&Object.assign(i,this.margin[Zr]());"visible"===this.fill?.presence&&Object.assign(i,this.fill[Zr]());if(this.corner.children.some((e=>0!==e.radius))){const e=this.corner.children.map((e=>e[Zr]()));if(2===e.length||3===e.length){const t=e.at(-1);for(let i=e.length;i<4;i++)e.push(t)}i.borderRadius=e.map((e=>e.radius)).join(" ")}switch(this.presence){case"invisible":case"hidden":i.borderStyle="";break;case"inactive":i.borderStyle="none";break;default:i.borderStyle=t.map((e=>e.style)).join(" ")}i.borderWidth=t.map((e=>e.width)).join(" ");i.borderColor=t.map((e=>e.color)).join(" ");return i}}class Break extends XFAObject{constructor(e){super(Nn,"break",!0);this.after=getStringOption(e.after,["auto","contentArea","pageArea","pageEven","pageOdd"]);this.afterTarget=e.afterTarget||"";this.before=getStringOption(e.before,["auto","contentArea","pageArea","pageEven","pageOdd"]);this.beforeTarget=e.beforeTarget||"";this.bookendLeader=e.bookendLeader||"";this.bookendTrailer=e.bookendTrailer||"";this.id=e.id||"";this.overflowLeader=e.overflowLeader||"";this.overflowTarget=e.overflowTarget||"";this.overflowTrailer=e.overflowTrailer||"";this.startNew=getInteger({data:e.startNew,defaultValue:0,validate:e=>1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}}class BreakAfter extends XFAObject{constructor(e){super(Nn,"breakAfter",!0);this.id=e.id||"";this.leader=e.leader||"";this.startNew=getInteger({data:e.startNew,defaultValue:0,validate:e=>1===e});this.target=e.target||"";this.targetType=getStringOption(e.targetType,["auto","contentArea","pageArea"]);this.trailer=e.trailer||"";this.use=e.use||"";this.usehref=e.usehref||"";this.script=null}}class BreakBefore extends XFAObject{constructor(e){super(Nn,"breakBefore",!0);this.id=e.id||"";this.leader=e.leader||"";this.startNew=getInteger({data:e.startNew,defaultValue:0,validate:e=>1===e});this.target=e.target||"";this.targetType=getStringOption(e.targetType,["auto","contentArea","pageArea"]);this.trailer=e.trailer||"";this.use=e.use||"";this.usehref=e.usehref||"";this.script=null}[jr](e){this[Xs]={};return HTMLResult.FAILURE}}class Button extends XFAObject{constructor(e){super(Nn,"button",!0);this.highlight=getStringOption(e.highlight,["inverted","none","outline","push"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[jr](e){const t=this[Ir]()[Ir](),i={name:"button",attributes:{id:this[Vr],class:["xfaButton"],style:{}},children:[]};for(const e of t.event.children){if("click"!==e.activity||!e.script)continue;const t=recoverJsURL(e.script[Os]);if(!t)continue;const a=fixURL(t.url);a&&i.children.push({name:"a",attributes:{id:"link"+this[Vr],href:a,newWindow:t.newWindow,class:["xfaLink"],style:{}},children:[]})}return HTMLResult.success(i)}}class Calculate extends XFAObject{constructor(e){super(Nn,"calculate",!0);this.id=e.id||"";this.override=getStringOption(e.override,["disabled","error","ignore","warning"]);this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.message=null;this.script=null}}class Caption extends XFAObject{constructor(e){super(Nn,"caption",!0);this.id=e.id||"";this.placement=getStringOption(e.placement,["left","bottom","inline","right","top"]);this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.reserve=Math.ceil(getMeasurement(e.reserve));this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.font=null;this.margin=null;this.para=null;this.value=null}[qr](e){_setValue(this,e)}[ar](e){if(!this[Xs]){let{width:t,height:i}=e;switch(this.placement){case"left":case"right":case"inline":t=this.reserve<=0?t:this.reserve;break;case"top":case"bottom":i=this.reserve<=0?i:this.reserve}this[Xs]=layoutNode(this,{width:t,height:i})}return this[Xs]}[jr](e){if(!this.value)return HTMLResult.EMPTY;this[Lr]();const t=this.value[jr](e).html;if(!t){this[xr]();return HTMLResult.EMPTY}const i=this.reserve;if(this.reserve<=0){const{w:t,h:i}=this[ar](e);switch(this.placement){case"left":case"right":case"inline":this.reserve=t;break;case"top":case"bottom":this.reserve=i}}const a=[];"string"==typeof t?a.push({name:"#text",value:t}):a.push(t);const s=toStyle(this,"font","margin","visibility");switch(this.placement){case"left":case"right":this.reserve>0&&(s.width=measureToString(this.reserve));break;case"top":case"bottom":this.reserve>0&&(s.height=measureToString(this.reserve))}setPara(this,null,t);this[xr]();this.reserve=i;return HTMLResult.success({name:"div",attributes:{style:s,class:["xfaCaption"]},children:a})}}class Certificate extends StringObject{constructor(e){super(Nn,"certificate");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Certificates extends XFAObject{constructor(e){super(Nn,"certificates",!0);this.credentialServerPolicy=getStringOption(e.credentialServerPolicy,["optional","required"]);this.id=e.id||"";this.url=e.url||"";this.urlPolicy=e.urlPolicy||"";this.use=e.use||"";this.usehref=e.usehref||"";this.encryption=null;this.issuers=null;this.keyUsage=null;this.oids=null;this.signing=null;this.subjectDNs=null}}class CheckButton extends XFAObject{constructor(e){super(Nn,"checkButton",!0);this.id=e.id||"";this.mark=getStringOption(e.mark,["default","check","circle","cross","diamond","square","star"]);this.shape=getStringOption(e.shape,["square","round"]);this.size=getMeasurement(e.size,"10pt");this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}[jr](e){const t=toStyle("margin"),i=measureToString(this.size);t.width=t.height=i;let a,s,r;const n=this[Ir]()[Ir](),g=n.items.children.length&&n.items.children[0][jr]().html||[],o={on:(void 0!==g[0]?g[0]:"on").toString(),off:(void 0!==g[1]?g[1]:"off").toString()},c=(n.value?.[Pr]()||"off")===o.on||void 0,C=n[or](),h=n[Vr];let l;if(C instanceof ExclGroup){r=C[Vr];a="radio";s="xfaRadio";l=C[Ws]?.[Vr]||C[Vr]}else{a="checkbox";s="xfaCheckbox";l=n[Ws]?.[Vr]||n[Vr]}const Q={name:"input",attributes:{class:[s],style:t,fieldId:h,dataId:l,type:a,checked:c,xfaOn:o.on,xfaOff:o.off,"aria-label":ariaLabel(n),"aria-required":!1}};r&&(Q.attributes.name=r);if(isRequired(n)){Q.attributes["aria-required"]=!0;Q.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[Q]})}}class ChoiceList extends XFAObject{constructor(e){super(Nn,"choiceList",!0);this.commitOn=getStringOption(e.commitOn,["select","exit"]);this.id=e.id||"";this.open=getStringOption(e.open,["userControl","always","multiSelect","onEntry"]);this.textEntry=getInteger({data:e.textEntry,defaultValue:0,validate:e=>1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}[jr](e){const t=toStyle(this,"border","margin"),i=this[Ir]()[Ir](),a={fontSize:`calc(${i.font?.size||10}px * var(--scale-factor))`},s=[];if(i.items.children.length>0){const e=i.items;let t=0,r=0;if(2===e.children.length){t=e.children[0].save;r=1-t}const n=e.children[t][jr]().html,g=e.children[r][jr]().html;let o=!1;const c=i.value?.[Pr]()||"";for(let e=0,t=n.length;eMath.min(Math.max(0,parseInt(e.trim(),10)),255))).map((e=>isNaN(e)?0:e));if(r.length<3)return{r:i,g:a,b:s};[i,a,s]=r;return{r:i,g:a,b:s}}(e.value):"";this.extras=null}[hr](){return!1}[Zr](){return this.value?Util.makeHexColor(this.value.r,this.value.g,this.value.b):null}}class Comb extends XFAObject{constructor(e){super(Nn,"comb");this.id=e.id||"";this.numberOfCells=getInteger({data:e.numberOfCells,defaultValue:0,validate:e=>e>=0});this.use=e.use||"";this.usehref=e.usehref||""}}class Connect extends XFAObject{constructor(e){super(Nn,"connect",!0);this.connection=e.connection||"";this.id=e.id||"";this.ref=e.ref||"";this.usage=getStringOption(e.usage,["exportAndImport","exportOnly","importOnly"]);this.use=e.use||"";this.usehref=e.usehref||"";this.picture=null}}class ContentArea extends XFAObject{constructor(e){super(Nn,"contentArea",!0);this.h=getMeasurement(e.h);this.id=e.id||"";this.name=e.name||"";this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.w=getMeasurement(e.w);this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.desc=null;this.extras=null}[jr](e){const t={left:measureToString(this.x),top:measureToString(this.y),width:measureToString(this.w),height:measureToString(this.h)},i=["xfaContentarea"];isPrintOnly(this)&&i.push("xfaPrintOnly");return HTMLResult.success({name:"div",children:[],attributes:{style:t,class:i,id:this[Vr]}})}}class Corner extends XFAObject{constructor(e){super(Nn,"corner",!0);this.id=e.id||"";this.inverted=getInteger({data:e.inverted,defaultValue:0,validate:e=>1===e});this.join=getStringOption(e.join,["square","round"]);this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.radius=getMeasurement(e.radius);this.stroke=getStringOption(e.stroke,["solid","dashDot","dashDotDot","dashed","dotted","embossed","etched","lowered","raised"]);this.thickness=getMeasurement(e.thickness,"0.5pt");this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zr](){const e=toStyle(this,"visibility");e.radius=measureToString("square"===this.join?0:this.radius);return e}}class DateElement extends ContentObject{constructor(e){super(Nn,"date");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){const e=this[Os].trim();this[Os]=e?new Date(e):null}[jr](e){return valueToHtml(this[Os]?this[Os].toString():"")}}class DateTime extends ContentObject{constructor(e){super(Nn,"dateTime");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){const e=this[Os].trim();this[Os]=e?new Date(e):null}[jr](e){return valueToHtml(this[Os]?this[Os].toString():"")}}class DateTimeEdit extends XFAObject{constructor(e){super(Nn,"dateTimeEdit",!0);this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.picker=getStringOption(e.picker,["host","none"]);this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.comb=null;this.extras=null;this.margin=null}[jr](e){const t=toStyle(this,"border","font","margin"),i=this[Ir]()[Ir](),a={name:"input",attributes:{type:"text",fieldId:i[Vr],dataId:i[Ws]?.[Vr]||i[Vr],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(i),"aria-required":!1}};if(isRequired(i)){a.attributes["aria-required"]=!0;a.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[a]})}}class Decimal extends ContentObject{constructor(e){super(Nn,"decimal");this.fracDigits=getInteger({data:e.fracDigits,defaultValue:2,validate:e=>!0});this.id=e.id||"";this.leadDigits=getInteger({data:e.leadDigits,defaultValue:-1,validate:e=>!0});this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){const e=parseFloat(this[Os].trim());this[Os]=isNaN(e)?null:e}[jr](e){return valueToHtml(null!==this[Os]?this[Os].toString():"")}}class DefaultUi extends XFAObject{constructor(e){super(Nn,"defaultUi",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}}class Desc extends XFAObject{constructor(e){super(Nn,"desc",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}}class DigestMethod extends OptionObject{constructor(e){super(Nn,"digestMethod",["","SHA1","SHA256","SHA512","RIPEMD160"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class DigestMethods extends XFAObject{constructor(e){super(Nn,"digestMethods",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.digestMethod=new XFAObjectArray}}class Draw extends XFAObject{constructor(e){super(Nn,"draw",!0);this.anchorType=getStringOption(e.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.locale=e.locale||"";this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.rotate=getInteger({data:e.rotate,defaultValue:0,validate:e=>e%90==0});this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.border=null;this.caption=null;this.desc=null;this.extras=null;this.font=null;this.keep=null;this.margin=null;this.para=null;this.traversal=null;this.ui=null;this.value=null;this.setProperty=new XFAObjectArray}[qr](e){_setValue(this,e)}[jr](e){setTabIndex(this);if("hidden"===this.presence||"inactive"===this.presence)return HTMLResult.EMPTY;fixDimensions(this);this[Lr]();const t=this.w,i=this.h,{w:a,h:s,isBroken:r}=layoutNode(this,e);if(a&&""===this.w){if(r&&this[or]()[wr]()){this[xr]();return HTMLResult.FAILURE}this.w=a}s&&""===this.h&&(this.h=s);setFirstUnsplittable(this);if(!checkDimensions(this,e)){this.w=t;this.h=i;this[xr]();return HTMLResult.FAILURE}unsetFirstUnsplittable(this);const n=toStyle(this,"font","hAlign","dimensions","position","presence","rotate","anchorType","border","margin");setMinMaxDimensions(this,n);if(n.margin){n.padding=n.margin;delete n.margin}const g=["xfaDraw"];this.font&&g.push("xfaFont");isPrintOnly(this)&&g.push("xfaPrintOnly");const o={style:n,id:this[Vr],class:g};this.name&&(o.xfaName=this.name);const c={name:"div",attributes:o,children:[]};applyAssist(this,o);const C=computeBbox(this,c,e),h=this.value?this.value[jr](e).html:null;if(null===h){this.w=t;this.h=i;this[xr]();return HTMLResult.success(createWrapper(this,c),C)}c.children.push(h);setPara(this,n,h);this.w=t;this.h=i;this[xr]();return HTMLResult.success(createWrapper(this,c),C)}}class Edge extends XFAObject{constructor(e){super(Nn,"edge",!0);this.cap=getStringOption(e.cap,["square","butt","round"]);this.id=e.id||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.stroke=getStringOption(e.stroke,["solid","dashDot","dashDotDot","dashed","dotted","embossed","etched","lowered","raised"]);this.thickness=getMeasurement(e.thickness,"0.5pt");this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zr](){const e=toStyle(this,"visibility");Object.assign(e,{linecap:this.cap,width:measureToString(this.thickness),color:this.color?this.color[Zr]():"#000000",style:""});if("visible"!==this.presence)e.style="none";else switch(this.stroke){case"solid":e.style="solid";break;case"dashDot":case"dashDotDot":case"dashed":e.style="dashed";break;case"dotted":e.style="dotted";break;case"embossed":e.style="ridge";break;case"etched":e.style="groove";break;case"lowered":e.style="inset";break;case"raised":e.style="outset"}return e}}class Encoding extends OptionObject{constructor(e){super(Nn,"encoding",["adbe.x509.rsa_sha1","adbe.pkcs7.detached","adbe.pkcs7.sha1"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Encodings extends XFAObject{constructor(e){super(Nn,"encodings",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.encoding=new XFAObjectArray}}class Encrypt extends XFAObject{constructor(e){super(Nn,"encrypt",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=null}}class EncryptData extends XFAObject{constructor(e){super(Nn,"encryptData",!0);this.id=e.id||"";this.operation=getStringOption(e.operation,["encrypt","decrypt"]);this.target=e.target||"";this.use=e.use||"";this.usehref=e.usehref||"";this.filter=null;this.manifest=null}}class Encryption extends XFAObject{constructor(e){super(Nn,"encryption",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=new XFAObjectArray}}class EncryptionMethod extends OptionObject{constructor(e){super(Nn,"encryptionMethod",["","AES256-CBC","TRIPLEDES-CBC","AES128-CBC","AES192-CBC"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class EncryptionMethods extends XFAObject{constructor(e){super(Nn,"encryptionMethods",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.encryptionMethod=new XFAObjectArray}}class Event extends XFAObject{constructor(e){super(Nn,"event",!0);this.activity=getStringOption(e.activity,["click","change","docClose","docReady","enter","exit","full","indexChange","initialize","mouseDown","mouseEnter","mouseExit","mouseUp","postExecute","postOpen","postPrint","postSave","postSign","postSubmit","preExecute","preOpen","prePrint","preSave","preSign","preSubmit","ready","validationState"]);this.id=e.id||"";this.listen=getStringOption(e.listen,["refOnly","refAndDescendents"]);this.name=e.name||"";this.ref=e.ref||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.encryptData=null;this.execute=null;this.script=null;this.signData=null;this.submit=null}}class ExData extends ContentObject{constructor(e){super(Nn,"exData");this.contentType=e.contentType||"";this.href=e.href||"";this.id=e.id||"";this.maxLength=getInteger({data:e.maxLength,defaultValue:-1,validate:e=>e>=-1});this.name=e.name||"";this.rid=e.rid||"";this.transferEncoding=getStringOption(e.transferEncoding,["none","base64","package"]);this.use=e.use||"";this.usehref=e.usehref||""}[ur](){return"text/html"===this.contentType}[Nr](e){if("text/html"===this.contentType&&e[Sr]===_r.xhtml.id){this[Os]=e;return!0}if("text/xml"===this.contentType){this[Os]=e;return!0}return!1}[jr](e){return"text/html"===this.contentType&&this[Os]?this[Os][jr](e):HTMLResult.EMPTY}}class ExObject extends XFAObject{constructor(e){super(Nn,"exObject",!0);this.archive=e.archive||"";this.classId=e.classId||"";this.codeBase=e.codeBase||"";this.codeType=e.codeType||"";this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.exObject=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}}class ExclGroup extends XFAObject{constructor(e){super(Nn,"exclGroup",!0);this.access=getStringOption(e.access,["open","nonInteractive","protected","readOnly"]);this.accessKey=e.accessKey||"";this.anchorType=getStringOption(e.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.layout=getStringOption(e.layout,["position","lr-tb","rl-row","rl-tb","row","table","tb"]);this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.bind=null;this.border=null;this.calculate=null;this.caption=null;this.desc=null;this.extras=null;this.margin=null;this.para=null;this.traversal=null;this.validate=null;this.connect=new XFAObjectArray;this.event=new XFAObjectArray;this.field=new XFAObjectArray;this.setProperty=new XFAObjectArray}[dr](){return!0}[hr](){return!0}[qr](e){for(const t of this.field.children){if(!t.value){const e=new Value({});t[Hs](e);t.value=e}t.value[qr](e)}}[wr](){return this.layout.endsWith("-tb")&&0===this[Xs].attempt&&this[Xs].numberInLine>0||this[Ir]()[wr]()}[yr](){const e=this[or]();if(!e[yr]())return!1;if(void 0!==this[Xs]._isSplittable)return this[Xs]._isSplittable;if("position"===this.layout||this.layout.includes("row")){this[Xs]._isSplittable=!1;return!1}if(e.layout?.endsWith("-tb")&&0!==e[Xs].numberInLine)return!1;this[Xs]._isSplittable=!0;return!0}[Vs](){return flushHTML(this)}[Ls](e,t){addHTML(this,e,t)}[$s](){return getAvailableSpace(this)}[jr](e){setTabIndex(this);if("hidden"===this.presence||"inactive"===this.presence||0===this.h||0===this.w)return HTMLResult.EMPTY;fixDimensions(this);const t=[],i={id:this[Vr],class:[]};setAccess(this,i.class);this[Xs]||(this[Xs]=Object.create(null));Object.assign(this[Xs],{children:t,attributes:i,attempt:0,line:null,numberInLine:0,availableSpace:{width:Math.min(this.w||1/0,e.width),height:Math.min(this.h||1/0,e.height)},width:0,height:0,prevHeight:0,currentWidth:0});const a=this[yr]();a||setFirstUnsplittable(this);if(!checkDimensions(this,e))return HTMLResult.FAILURE;const s=new Set(["field"]);if(this.layout.includes("row")){const e=this[or]().columnWidths;if(Array.isArray(e)&&e.length>0){this[Xs].columnWidths=e;this[Xs].currentColumn=0}}const r=toStyle(this,"anchorType","dimensions","position","presence","border","margin","hAlign"),n=["xfaExclgroup"],g=layoutClass(this);g&&n.push(g);isPrintOnly(this)&&n.push("xfaPrintOnly");i.style=r;i.class=n;this.name&&(i.xfaName=this.name);this[Lr]();const o="lr-tb"===this.layout||"rl-tb"===this.layout,c=o?2:1;for(;this[Xs].attempte>=1||-1===e});this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.locale=e.locale||"";this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.rotate=getInteger({data:e.rotate,defaultValue:0,validate:e=>e%90==0});this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.bind=null;this.border=null;this.calculate=null;this.caption=null;this.desc=null;this.extras=null;this.font=null;this.format=null;this.items=new XFAObjectArray(2);this.keep=null;this.margin=null;this.para=null;this.traversal=null;this.ui=null;this.validate=null;this.value=null;this.bindItems=new XFAObjectArray;this.connect=new XFAObjectArray;this.event=new XFAObjectArray;this.setProperty=new XFAObjectArray}[dr](){return!0}[qr](e){_setValue(this,e)}[jr](e){setTabIndex(this);if(!this.ui){this.ui=new Ui({});this.ui[Cr]=this[Cr];this[Hs](this.ui);let e;switch(this.items.children.length){case 0:e=new TextEdit({});this.ui.textEdit=e;break;case 1:e=new CheckButton({});this.ui.checkButton=e;break;case 2:e=new ChoiceList({});this.ui.choiceList=e}this.ui[Hs](e)}if(!this.ui||"hidden"===this.presence||"inactive"===this.presence||0===this.h||0===this.w)return HTMLResult.EMPTY;this.caption&&delete this.caption[Xs];this[Lr]();const t=this.caption?this.caption[jr](e).html:null,i=this.w,a=this.h;let s=0,r=0;if(this.margin){s=this.margin.leftInset+this.margin.rightInset;r=this.margin.topInset+this.margin.bottomInset}let n=null;if(""===this.w||""===this.h){let t=null,i=null,a=0,g=0;if(this.ui.checkButton)a=g=this.ui.checkButton.size;else{const{w:t,h:i}=layoutNode(this,e);if(null!==t){a=t;g=i}else g=function fonts_getMetrics(e,t=!1){let i=null;if(e){const t=stripQuotes(e.typeface),a=e[Cr].fontFinder.find(t);i=selectFont(e,a)}if(!i)return{lineHeight:12,lineGap:2,lineNoGap:10};const a=e.size||10,s=i.lineHeight?Math.max(t?0:1.2,i.lineHeight):1.2,r=void 0===i.lineGap?.2:i.lineGap;return{lineHeight:s*a,lineGap:r*a,lineNoGap:Math.max(1,s-r)*a}}(this.font,!0).lineNoGap}n=getBorderDims(this.ui[ar]());a+=n.w;g+=n.h;if(this.caption){const{w:s,h:r,isBroken:n}=this.caption[ar](e);if(n&&this[or]()[wr]()){this[xr]();return HTMLResult.FAILURE}t=s;i=r;switch(this.caption.placement){case"left":case"right":case"inline":t+=a;break;case"top":case"bottom":i+=g}}else{t=a;i=g}if(t&&""===this.w){t+=s;this.w=Math.min(this.maxW<=0?1/0:this.maxW,this.minW+1e>=1&&e<=5});this.appearanceFilter=null;this.certificates=null;this.digestMethods=null;this.encodings=null;this.encryptionMethods=null;this.handler=null;this.lockDocument=null;this.mdp=null;this.reasons=null;this.timeStamp=null}}class Float extends ContentObject{constructor(e){super(Nn,"float");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){const e=parseFloat(this[Os].trim());this[Os]=isNaN(e)?null:e}[jr](e){return valueToHtml(null!==this[Os]?this[Os].toString():"")}}class template_Font extends XFAObject{constructor(e){super(Nn,"font",!0);this.baselineShift=getMeasurement(e.baselineShift);this.fontHorizontalScale=getFloat({data:e.fontHorizontalScale,defaultValue:100,validate:e=>e>=0});this.fontVerticalScale=getFloat({data:e.fontVerticalScale,defaultValue:100,validate:e=>e>=0});this.id=e.id||"";this.kerningMode=getStringOption(e.kerningMode,["none","pair"]);this.letterSpacing=getMeasurement(e.letterSpacing,"0");this.lineThrough=getInteger({data:e.lineThrough,defaultValue:0,validate:e=>1===e||2===e});this.lineThroughPeriod=getStringOption(e.lineThroughPeriod,["all","word"]);this.overline=getInteger({data:e.overline,defaultValue:0,validate:e=>1===e||2===e});this.overlinePeriod=getStringOption(e.overlinePeriod,["all","word"]);this.posture=getStringOption(e.posture,["normal","italic"]);this.size=getMeasurement(e.size,"10pt");this.typeface=e.typeface||"Courier";this.underline=getInteger({data:e.underline,defaultValue:0,validate:e=>1===e||2===e});this.underlinePeriod=getStringOption(e.underlinePeriod,["all","word"]);this.use=e.use||"";this.usehref=e.usehref||"";this.weight=getStringOption(e.weight,["normal","bold"]);this.extras=null;this.fill=null}[Ys](e){super[Ys](e);this[Cr].usedTypefaces.add(this.typeface)}[Zr](){const e=toStyle(this,"fill"),t=e.color;if(t)if("#000000"===t)delete e.color;else if(!t.startsWith("#")){e.background=t;e.backgroundClip="text";e.color="transparent"}this.baselineShift&&(e.verticalAlign=measureToString(this.baselineShift));e.fontKerning="none"===this.kerningMode?"none":"normal";e.letterSpacing=measureToString(this.letterSpacing);if(0!==this.lineThrough){e.textDecoration="line-through";2===this.lineThrough&&(e.textDecorationStyle="double")}if(0!==this.overline){e.textDecoration="overline";2===this.overline&&(e.textDecorationStyle="double")}e.fontStyle=this.posture;e.fontSize=measureToString(.99*this.size);setFontFamily(this,this,this[Cr].fontFinder,e);if(0!==this.underline){e.textDecoration="underline";2===this.underline&&(e.textDecorationStyle="double")}e.fontWeight=this.weight;return e}}class Format extends XFAObject{constructor(e){super(Nn,"format",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.picture=null}}class Handler extends StringObject{constructor(e){super(Nn,"handler");this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Hyphenation extends XFAObject{constructor(e){super(Nn,"hyphenation");this.excludeAllCaps=getInteger({data:e.excludeAllCaps,defaultValue:0,validate:e=>1===e});this.excludeInitialCap=getInteger({data:e.excludeInitialCap,defaultValue:0,validate:e=>1===e});this.hyphenate=getInteger({data:e.hyphenate,defaultValue:0,validate:e=>1===e});this.id=e.id||"";this.pushCharacterCount=getInteger({data:e.pushCharacterCount,defaultValue:3,validate:e=>e>=0});this.remainCharacterCount=getInteger({data:e.remainCharacterCount,defaultValue:3,validate:e=>e>=0});this.use=e.use||"";this.usehref=e.usehref||"";this.wordCharacterCount=getInteger({data:e.wordCharacterCount,defaultValue:7,validate:e=>e>=0})}}class Image extends StringObject{constructor(e){super(Nn,"image");this.aspect=getStringOption(e.aspect,["fit","actual","height","none","width"]);this.contentType=e.contentType||"";this.href=e.href||"";this.id=e.id||"";this.name=e.name||"";this.transferEncoding=getStringOption(e.transferEncoding,["base64","none","package"]);this.use=e.use||"";this.usehref=e.usehref||""}[jr](){if(this.contentType&&!Un.has(this.contentType.toLowerCase()))return HTMLResult.EMPTY;let e=this[Cr].images&&this[Cr].images.get(this.href);if(!e&&(this.href||!this[Os]))return HTMLResult.EMPTY;e||"base64"!==this.transferEncoding||(e=function fromBase64Util(e){return Uint8Array.fromBase64?Uint8Array.fromBase64(e):stringToBytes(atob(e))}(this[Os]));if(!e)return HTMLResult.EMPTY;if(!this.contentType){for(const[t,i]of xn)if(e.length>t.length&&t.every(((t,i)=>t===e[i]))){this.contentType=i;break}if(!this.contentType)return HTMLResult.EMPTY}const t=new Blob([e],{type:this.contentType});let i;switch(this.aspect){case"fit":case"actual":break;case"height":i={height:"100%",objectFit:"fill"};break;case"none":i={width:"100%",height:"100%",objectFit:"fill"};break;case"width":i={width:"100%",objectFit:"fill"}}const a=this[Ir]();return HTMLResult.success({name:"img",attributes:{class:["xfaImage"],style:i,src:URL.createObjectURL(t),alt:a?ariaLabel(a[Ir]()):null}})}}class ImageEdit extends XFAObject{constructor(e){super(Nn,"imageEdit",!0);this.data=getStringOption(e.data,["link","embed"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}[jr](e){return"embed"===this.data?HTMLResult.success({name:"div",children:[],attributes:{}}):HTMLResult.EMPTY}}class Integer extends ContentObject{constructor(e){super(Nn,"integer");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){const e=parseInt(this[Os].trim(),10);this[Os]=isNaN(e)?null:e}[jr](e){return valueToHtml(null!==this[Os]?this[Os].toString():"")}}class Issuers extends XFAObject{constructor(e){super(Nn,"issuers",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=new XFAObjectArray}}class Items extends XFAObject{constructor(e){super(Nn,"items",!0);this.id=e.id||"";this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.ref=e.ref||"";this.save=getInteger({data:e.save,defaultValue:0,validate:e=>1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}[jr](){const e=[];for(const t of this[rr]())e.push(t[Pr]());return HTMLResult.success(e)}}class Keep extends XFAObject{constructor(e){super(Nn,"keep",!0);this.id=e.id||"";const t=["none","contentArea","pageArea"];this.intact=getStringOption(e.intact,t);this.next=getStringOption(e.next,t);this.previous=getStringOption(e.previous,t);this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}}class KeyUsage extends XFAObject{constructor(e){super(Nn,"keyUsage");const t=["","yes","no"];this.crlSign=getStringOption(e.crlSign,t);this.dataEncipherment=getStringOption(e.dataEncipherment,t);this.decipherOnly=getStringOption(e.decipherOnly,t);this.digitalSignature=getStringOption(e.digitalSignature,t);this.encipherOnly=getStringOption(e.encipherOnly,t);this.id=e.id||"";this.keyAgreement=getStringOption(e.keyAgreement,t);this.keyCertSign=getStringOption(e.keyCertSign,t);this.keyEncipherment=getStringOption(e.keyEncipherment,t);this.nonRepudiation=getStringOption(e.nonRepudiation,t);this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Line extends XFAObject{constructor(e){super(Nn,"line",!0);this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.slope=getStringOption(e.slope,["\\","/"]);this.use=e.use||"";this.usehref=e.usehref||"";this.edge=null}[jr](){const e=this[Ir]()[Ir](),t=this.edge||new Edge({}),i=t[Zr](),a=Object.create(null),s="visible"===t.presence?t.thickness:0;a.strokeWidth=measureToString(s);a.stroke=i.color;let r,n,g,o,c="100%",C="100%";if(e.w<=s){[r,n,g,o]=["50%",0,"50%","100%"];c=a.strokeWidth}else if(e.h<=s){[r,n,g,o]=[0,"50%","100%","50%"];C=a.strokeWidth}else"\\"===this.slope?[r,n,g,o]=[0,0,"100%","100%"]:[r,n,g,o]=[0,"100%","100%",0];const h={name:"svg",children:[{name:"line",attributes:{xmlns:Gn,x1:r,y1:n,x2:g,y2:o,style:a}}],attributes:{xmlns:Gn,width:c,height:C,style:{overflow:"visible"}}};if(hasMargin(e))return HTMLResult.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[h]});h.attributes.style.position="absolute";return HTMLResult.success(h)}}class Linear extends XFAObject{constructor(e){super(Nn,"linear",!0);this.id=e.id||"";this.type=getStringOption(e.type,["toRight","toBottom","toLeft","toTop"]);this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zr](e){e=e?e[Zr]():"#FFFFFF";return`linear-gradient(${this.type.replace(/([RBLT])/," $1").toLowerCase()}, ${e}, ${this.color?this.color[Zr]():"#000000"})`}}class LockDocument extends ContentObject{constructor(e){super(Nn,"lockDocument");this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){this[Os]=getStringOption(this[Os],["auto","0","1"])}}class Manifest extends XFAObject{constructor(e){super(Nn,"manifest",!0);this.action=getStringOption(e.action,["include","all","exclude"]);this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.ref=new XFAObjectArray}}class Margin extends XFAObject{constructor(e){super(Nn,"margin",!0);this.bottomInset=getMeasurement(e.bottomInset,"0");this.id=e.id||"";this.leftInset=getMeasurement(e.leftInset,"0");this.rightInset=getMeasurement(e.rightInset,"0");this.topInset=getMeasurement(e.topInset,"0");this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[Zr](){return{margin:measureToString(this.topInset)+" "+measureToString(this.rightInset)+" "+measureToString(this.bottomInset)+" "+measureToString(this.leftInset)}}}class Mdp extends XFAObject{constructor(e){super(Nn,"mdp");this.id=e.id||"";this.permissions=getInteger({data:e.permissions,defaultValue:2,validate:e=>1===e||3===e});this.signatureType=getStringOption(e.signatureType,["filler","author"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Medium extends XFAObject{constructor(e){super(Nn,"medium");this.id=e.id||"";this.imagingBBox=function getBBox(e){const t=-1;if(!e)return{x:t,y:t,width:t,height:t};const i=e.trim().split(/\s*,\s*/).map((e=>getMeasurement(e,"-1")));if(i.length<4||i[2]<0||i[3]<0)return{x:t,y:t,width:t,height:t};const[a,s,r,n]=i;return{x:a,y:s,width:r,height:n}}(e.imagingBBox);this.long=getMeasurement(e.long);this.orientation=getStringOption(e.orientation,["portrait","landscape"]);this.short=getMeasurement(e.short);this.stock=e.stock||"";this.trayIn=getStringOption(e.trayIn,["auto","delegate","pageFront"]);this.trayOut=getStringOption(e.trayOut,["auto","delegate"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Message extends XFAObject{constructor(e){super(Nn,"message",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.text=new XFAObjectArray}}class NumericEdit extends XFAObject{constructor(e){super(Nn,"numericEdit",!0);this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.comb=null;this.extras=null;this.margin=null}[jr](e){const t=toStyle(this,"border","font","margin"),i=this[Ir]()[Ir](),a={name:"input",attributes:{type:"text",fieldId:i[Vr],dataId:i[Ws]?.[Vr]||i[Vr],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(i),"aria-required":!1}};if(isRequired(i)){a.attributes["aria-required"]=!0;a.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[a]})}}class Occur extends XFAObject{constructor(e){super(Nn,"occur",!0);this.id=e.id||"";this.initial=""!==e.initial?getInteger({data:e.initial,defaultValue:"",validate:e=>!0}):"";this.max=""!==e.max?getInteger({data:e.max,defaultValue:1,validate:e=>!0}):"";this.min=""!==e.min?getInteger({data:e.min,defaultValue:1,validate:e=>!0}):"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[Ys](){const e=this[Ir](),t=this.min;""===this.min&&(this.min=e instanceof PageArea||e instanceof PageSet?0:1);""===this.max&&(this.max=""===t?e instanceof PageArea||e instanceof PageSet?-1:1:this.min);-1!==this.max&&this.max!0});this.name=e.name||"";this.numbered=getInteger({data:e.numbered,defaultValue:1,validate:e=>!0});this.oddOrEven=getStringOption(e.oddOrEven,["any","even","odd"]);this.pagePosition=getStringOption(e.pagePosition,["any","first","last","only","rest"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.desc=null;this.extras=null;this.medium=null;this.occur=null;this.area=new XFAObjectArray;this.contentArea=new XFAObjectArray;this.draw=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.field=new XFAObjectArray;this.subform=new XFAObjectArray}[br](){if(!this[Xs]){this[Xs]={numberOfUse:0};return!0}return!this.occur||-1===this.occur.max||this[Xs].numberOfUsee.oddOrEven===t&&e.pagePosition===i));if(a)return a;a=this.pageArea.children.find((e=>"any"===e.oddOrEven&&e.pagePosition===i));if(a)return a;a=this.pageArea.children.find((e=>"any"===e.oddOrEven&&"any"===e.pagePosition));return a||this.pageArea.children[0]}}class Para extends XFAObject{constructor(e){super(Nn,"para",!0);this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.lineHeight=e.lineHeight?getMeasurement(e.lineHeight,"0pt"):"";this.marginLeft=e.marginLeft?getMeasurement(e.marginLeft,"0pt"):"";this.marginRight=e.marginRight?getMeasurement(e.marginRight,"0pt"):"";this.orphans=getInteger({data:e.orphans,defaultValue:0,validate:e=>e>=0});this.preserve=e.preserve||"";this.radixOffset=e.radixOffset?getMeasurement(e.radixOffset,"0pt"):"";this.spaceAbove=e.spaceAbove?getMeasurement(e.spaceAbove,"0pt"):"";this.spaceBelow=e.spaceBelow?getMeasurement(e.spaceBelow,"0pt"):"";this.tabDefault=e.tabDefault?getMeasurement(this.tabDefault):"";this.tabStops=(e.tabStops||"").trim().split(/\s+/).map(((e,t)=>t%2==1?getMeasurement(e):e));this.textIndent=e.textIndent?getMeasurement(e.textIndent,"0pt"):"";this.use=e.use||"";this.usehref=e.usehref||"";this.vAlign=getStringOption(e.vAlign,["top","bottom","middle"]);this.widows=getInteger({data:e.widows,defaultValue:0,validate:e=>e>=0});this.hyphenation=null}[Zr](){const e=toStyle(this,"hAlign");""!==this.marginLeft&&(e.paddingLeft=measureToString(this.marginLeft));""!==this.marginRight&&(e.paddingRight=measureToString(this.marginRight));""!==this.spaceAbove&&(e.paddingTop=measureToString(this.spaceAbove));""!==this.spaceBelow&&(e.paddingBottom=measureToString(this.spaceBelow));if(""!==this.textIndent){e.textIndent=measureToString(this.textIndent);fixTextIndent(e)}this.lineHeight>0&&(e.lineHeight=measureToString(this.lineHeight));""!==this.tabDefault&&(e.tabSize=measureToString(this.tabDefault));this.tabStops.length;this.hyphenatation&&Object.assign(e,this.hyphenatation[Zr]());return e}}class PasswordEdit extends XFAObject{constructor(e){super(Nn,"passwordEdit",!0);this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.passwordChar=e.passwordChar||"*";this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}}class template_Pattern extends XFAObject{constructor(e){super(Nn,"pattern",!0);this.id=e.id||"";this.type=getStringOption(e.type,["crossHatch","crossDiagonal","diagonalLeft","diagonalRight","horizontal","vertical"]);this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zr](e){e=e?e[Zr]():"#FFFFFF";const t=this.color?this.color[Zr]():"#000000",i="repeating-linear-gradient",a=`${e},${e} 5px,${t} 5px,${t} 10px`;switch(this.type){case"crossHatch":return`${i}(to top,${a}) ${i}(to right,${a})`;case"crossDiagonal":return`${i}(45deg,${a}) ${i}(-45deg,${a})`;case"diagonalLeft":return`${i}(45deg,${a})`;case"diagonalRight":return`${i}(-45deg,${a})`;case"horizontal":return`${i}(to top,${a})`;case"vertical":return`${i}(to right,${a})`}return""}}class Picture extends StringObject{constructor(e){super(Nn,"picture");this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Proto extends XFAObject{constructor(e){super(Nn,"proto",!0);this.appearanceFilter=new XFAObjectArray;this.arc=new XFAObjectArray;this.area=new XFAObjectArray;this.assist=new XFAObjectArray;this.barcode=new XFAObjectArray;this.bindItems=new XFAObjectArray;this.bookend=new XFAObjectArray;this.boolean=new XFAObjectArray;this.border=new XFAObjectArray;this.break=new XFAObjectArray;this.breakAfter=new XFAObjectArray;this.breakBefore=new XFAObjectArray;this.button=new XFAObjectArray;this.calculate=new XFAObjectArray;this.caption=new XFAObjectArray;this.certificate=new XFAObjectArray;this.certificates=new XFAObjectArray;this.checkButton=new XFAObjectArray;this.choiceList=new XFAObjectArray;this.color=new XFAObjectArray;this.comb=new XFAObjectArray;this.connect=new XFAObjectArray;this.contentArea=new XFAObjectArray;this.corner=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.dateTimeEdit=new XFAObjectArray;this.decimal=new XFAObjectArray;this.defaultUi=new XFAObjectArray;this.desc=new XFAObjectArray;this.digestMethod=new XFAObjectArray;this.digestMethods=new XFAObjectArray;this.draw=new XFAObjectArray;this.edge=new XFAObjectArray;this.encoding=new XFAObjectArray;this.encodings=new XFAObjectArray;this.encrypt=new XFAObjectArray;this.encryptData=new XFAObjectArray;this.encryption=new XFAObjectArray;this.encryptionMethod=new XFAObjectArray;this.encryptionMethods=new XFAObjectArray;this.event=new XFAObjectArray;this.exData=new XFAObjectArray;this.exObject=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.execute=new XFAObjectArray;this.extras=new XFAObjectArray;this.field=new XFAObjectArray;this.fill=new XFAObjectArray;this.filter=new XFAObjectArray;this.float=new XFAObjectArray;this.font=new XFAObjectArray;this.format=new XFAObjectArray;this.handler=new XFAObjectArray;this.hyphenation=new XFAObjectArray;this.image=new XFAObjectArray;this.imageEdit=new XFAObjectArray;this.integer=new XFAObjectArray;this.issuers=new XFAObjectArray;this.items=new XFAObjectArray;this.keep=new XFAObjectArray;this.keyUsage=new XFAObjectArray;this.line=new XFAObjectArray;this.linear=new XFAObjectArray;this.lockDocument=new XFAObjectArray;this.manifest=new XFAObjectArray;this.margin=new XFAObjectArray;this.mdp=new XFAObjectArray;this.medium=new XFAObjectArray;this.message=new XFAObjectArray;this.numericEdit=new XFAObjectArray;this.occur=new XFAObjectArray;this.oid=new XFAObjectArray;this.oids=new XFAObjectArray;this.overflow=new XFAObjectArray;this.pageArea=new XFAObjectArray;this.pageSet=new XFAObjectArray;this.para=new XFAObjectArray;this.passwordEdit=new XFAObjectArray;this.pattern=new XFAObjectArray;this.picture=new XFAObjectArray;this.radial=new XFAObjectArray;this.reason=new XFAObjectArray;this.reasons=new XFAObjectArray;this.rectangle=new XFAObjectArray;this.ref=new XFAObjectArray;this.script=new XFAObjectArray;this.setProperty=new XFAObjectArray;this.signData=new XFAObjectArray;this.signature=new XFAObjectArray;this.signing=new XFAObjectArray;this.solid=new XFAObjectArray;this.speak=new XFAObjectArray;this.stipple=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray;this.subjectDN=new XFAObjectArray;this.subjectDNs=new XFAObjectArray;this.submit=new XFAObjectArray;this.text=new XFAObjectArray;this.textEdit=new XFAObjectArray;this.time=new XFAObjectArray;this.timeStamp=new XFAObjectArray;this.toolTip=new XFAObjectArray;this.traversal=new XFAObjectArray;this.traverse=new XFAObjectArray;this.ui=new XFAObjectArray;this.validate=new XFAObjectArray;this.value=new XFAObjectArray;this.variables=new XFAObjectArray}}class Radial extends XFAObject{constructor(e){super(Nn,"radial",!0);this.id=e.id||"";this.type=getStringOption(e.type,["toEdge","toCenter"]);this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zr](e){e=e?e[Zr]():"#FFFFFF";const t=this.color?this.color[Zr]():"#000000";return`radial-gradient(circle at center, ${"toEdge"===this.type?`${e},${t}`:`${t},${e}`})`}}class Reason extends StringObject{constructor(e){super(Nn,"reason");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Reasons extends XFAObject{constructor(e){super(Nn,"reasons",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.reason=new XFAObjectArray}}class Rectangle extends XFAObject{constructor(e){super(Nn,"rectangle",!0);this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.corner=new XFAObjectArray(4);this.edge=new XFAObjectArray(4);this.fill=null}[jr](){const e=this.edge.children.length?this.edge.children[0]:new Edge({}),t=e[Zr](),i=Object.create(null);"visible"===this.fill?.presence?Object.assign(i,this.fill[Zr]()):i.fill="transparent";i.strokeWidth=measureToString("visible"===e.presence?e.thickness:0);i.stroke=t.color;const a=(this.corner.children.length?this.corner.children[0]:new Corner({}))[Zr](),s={name:"svg",children:[{name:"rect",attributes:{xmlns:Gn,width:"100%",height:"100%",x:0,y:0,rx:a.radius,ry:a.radius,style:i}}],attributes:{xmlns:Gn,style:{overflow:"visible"},width:"100%",height:"100%"}};if(hasMargin(this[Ir]()[Ir]()))return HTMLResult.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[s]});s.attributes.style.position="absolute";return HTMLResult.success(s)}}class RefElement extends StringObject{constructor(e){super(Nn,"ref");this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Script extends StringObject{constructor(e){super(Nn,"script");this.binding=e.binding||"";this.contentType=e.contentType||"";this.id=e.id||"";this.name=e.name||"";this.runAt=getStringOption(e.runAt,["client","both","server"]);this.use=e.use||"";this.usehref=e.usehref||""}}class SetProperty extends XFAObject{constructor(e){super(Nn,"setProperty");this.connection=e.connection||"";this.ref=e.ref||"";this.target=e.target||""}}class SignData extends XFAObject{constructor(e){super(Nn,"signData",!0);this.id=e.id||"";this.operation=getStringOption(e.operation,["sign","clear","verify"]);this.ref=e.ref||"";this.target=e.target||"";this.use=e.use||"";this.usehref=e.usehref||"";this.filter=null;this.manifest=null}}class Signature extends XFAObject{constructor(e){super(Nn,"signature",!0);this.id=e.id||"";this.type=getStringOption(e.type,["PDF1.3","PDF1.6"]);this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.filter=null;this.manifest=null;this.margin=null}}class Signing extends XFAObject{constructor(e){super(Nn,"signing",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=new XFAObjectArray}}class Solid extends XFAObject{constructor(e){super(Nn,"solid",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[Zr](e){return e?e[Zr]():"#FFFFFF"}}class Speak extends StringObject{constructor(e){super(Nn,"speak");this.disable=getInteger({data:e.disable,defaultValue:0,validate:e=>1===e});this.id=e.id||"";this.priority=getStringOption(e.priority,["custom","caption","name","toolTip"]);this.rid=e.rid||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Stipple extends XFAObject{constructor(e){super(Nn,"stipple",!0);this.id=e.id||"";this.rate=getInteger({data:e.rate,defaultValue:50,validate:e=>e>=0&&e<=100});this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zr](e){const t=this.rate/100;return Util.makeHexColor(Math.round(e.value.r*(1-t)+this.value.r*t),Math.round(e.value.g*(1-t)+this.value.g*t),Math.round(e.value.b*(1-t)+this.value.b*t))}}class Subform extends XFAObject{constructor(e){super(Nn,"subform",!0);this.access=getStringOption(e.access,["open","nonInteractive","protected","readOnly"]);this.allowMacro=getInteger({data:e.allowMacro,defaultValue:0,validate:e=>1===e});this.anchorType=getStringOption(e.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.columnWidths=(e.columnWidths||"").trim().split(/\s+/).map((e=>"-1"===e?-1:getMeasurement(e)));this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.layout=getStringOption(e.layout,["position","lr-tb","rl-row","rl-tb","row","table","tb"]);this.locale=e.locale||"";this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.mergeMode=getStringOption(e.mergeMode,["consumeData","matchTemplate"]);this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.restoreState=getStringOption(e.restoreState,["manual","auto"]);this.scope=getStringOption(e.scope,["name","none"]);this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.bind=null;this.bookend=null;this.border=null;this.break=null;this.calculate=null;this.desc=null;this.extras=null;this.keep=null;this.margin=null;this.occur=null;this.overflow=null;this.pageSet=null;this.para=null;this.traversal=null;this.validate=null;this.variables=null;this.area=new XFAObjectArray;this.breakAfter=new XFAObjectArray;this.breakBefore=new XFAObjectArray;this.connect=new XFAObjectArray;this.draw=new XFAObjectArray;this.event=new XFAObjectArray;this.exObject=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.field=new XFAObjectArray;this.proto=new XFAObjectArray;this.setProperty=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray}[or](){const e=this[Ir]();return e instanceof SubformSet?e[or]():e}[dr](){return!0}[wr](){return this.layout.endsWith("-tb")&&0===this[Xs].attempt&&this[Xs].numberInLine>0||this[Ir]()[wr]()}*[nr](){yield*getContainedChildren(this)}[Vs](){return flushHTML(this)}[Ls](e,t){addHTML(this,e,t)}[$s](){return getAvailableSpace(this)}[yr](){const e=this[or]();if(!e[yr]())return!1;if(void 0!==this[Xs]._isSplittable)return this[Xs]._isSplittable;if("position"===this.layout||this.layout.includes("row")){this[Xs]._isSplittable=!1;return!1}if(this.keep&&"none"!==this.keep.intact){this[Xs]._isSplittable=!1;return!1}if(e.layout?.endsWith("-tb")&&0!==e[Xs].numberInLine)return!1;this[Xs]._isSplittable=!0;return!0}[jr](e){setTabIndex(this);if(this.break){if("auto"!==this.break.after||""!==this.break.afterTarget){const e=new BreakAfter({targetType:this.break.after,target:this.break.afterTarget,startNew:this.break.startNew.toString()});e[Cr]=this[Cr];this[Hs](e);this.breakAfter.push(e)}if("auto"!==this.break.before||""!==this.break.beforeTarget){const e=new BreakBefore({targetType:this.break.before,target:this.break.beforeTarget,startNew:this.break.startNew.toString()});e[Cr]=this[Cr];this[Hs](e);this.breakBefore.push(e)}if(""!==this.break.overflowTarget){const e=new Overflow({target:this.break.overflowTarget,leader:this.break.overflowLeader,trailer:this.break.overflowTrailer});e[Cr]=this[Cr];this[Hs](e);this.overflow.push(e)}this[Hr](this.break);this.break=null}if("hidden"===this.presence||"inactive"===this.presence)return HTMLResult.EMPTY;(this.breakBefore.children.length>1||this.breakAfter.children.length>1)&&warn("XFA - Several breakBefore or breakAfter in subforms: please file a bug.");if(this.breakBefore.children.length>=1){const e=this.breakBefore.children[0];if(handleBreak(e))return HTMLResult.breakNode(e)}if(this[Xs]?.afterBreakAfter)return HTMLResult.EMPTY;fixDimensions(this);const t=[],i={id:this[Vr],class:[]};setAccess(this,i.class);this[Xs]||(this[Xs]=Object.create(null));Object.assign(this[Xs],{children:t,line:null,attributes:i,attempt:0,numberInLine:0,availableSpace:{width:Math.min(this.w||1/0,e.width),height:Math.min(this.h||1/0,e.height)},width:0,height:0,prevHeight:0,currentWidth:0});const a=this[cr](),s=a[Xs].noLayoutFailure,r=this[yr]();r||setFirstUnsplittable(this);if(!checkDimensions(this,e))return HTMLResult.FAILURE;const n=new Set(["area","draw","exclGroup","field","subform","subformSet"]);if(this.layout.includes("row")){const e=this[or]().columnWidths;if(Array.isArray(e)&&e.length>0){this[Xs].columnWidths=e;this[Xs].currentColumn=0}}const g=toStyle(this,"anchorType","dimensions","position","presence","border","margin","hAlign"),o=["xfaSubform"],c=layoutClass(this);c&&o.push(c);i.style=g;i.class=o;this.name&&(i.xfaName=this.name);if(this.overflow){const t=this.overflow[ar]();if(t.addLeader){t.addLeader=!1;handleOverflow(this,t.leader,e)}}this[Lr]();const C="lr-tb"===this.layout||"rl-tb"===this.layout,h=C?2:1;for(;this[Xs].attempt=1){const e=this.breakAfter.children[0];if(handleBreak(e)){this[Xs].afterBreakAfter=p;return HTMLResult.breakNode(e)}}delete this[Xs];return p}}class SubformSet extends XFAObject{constructor(e){super(Nn,"subformSet",!0);this.id=e.id||"";this.name=e.name||"";this.relation=getStringOption(e.relation,["ordered","choice","unordered"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.bookend=null;this.break=null;this.desc=null;this.extras=null;this.occur=null;this.overflow=null;this.breakAfter=new XFAObjectArray;this.breakBefore=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray}*[nr](){yield*getContainedChildren(this)}[or](){let e=this[Ir]();for(;!(e instanceof Subform);)e=e[Ir]();return e}[dr](){return!0}}class SubjectDN extends ContentObject{constructor(e){super(Nn,"subjectDN");this.delimiter=e.delimiter||",";this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){this[Os]=new Map(this[Os].split(this.delimiter).map((e=>{(e=e.split("=",2))[0]=e[0].trim();return e})))}}class SubjectDNs extends XFAObject{constructor(e){super(Nn,"subjectDNs",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.subjectDN=new XFAObjectArray}}class Submit extends XFAObject{constructor(e){super(Nn,"submit",!0);this.embedPDF=getInteger({data:e.embedPDF,defaultValue:0,validate:e=>1===e});this.format=getStringOption(e.format,["xdp","formdata","pdf","urlencoded","xfd","xml"]);this.id=e.id||"";this.target=e.target||"";this.textEncoding=getKeyword({data:e.textEncoding?e.textEncoding.toLowerCase():"",defaultValue:"",validate:e=>["utf-8","big-five","fontspecific","gbk","gb-18030","gb-2312","ksc-5601","none","shift-jis","ucs-2","utf-16"].includes(e)||e.match(/iso-8859-\d{2}/)});this.use=e.use||"";this.usehref=e.usehref||"";this.xdpContent=e.xdpContent||"";this.encrypt=null;this.encryptData=new XFAObjectArray;this.signData=new XFAObjectArray}}class Template extends XFAObject{constructor(e){super(Nn,"template",!0);this.baseProfile=getStringOption(e.baseProfile,["full","interactiveForms"]);this.extras=null;this.subform=new XFAObjectArray}[Zs](){0===this.subform.children.length&&warn("XFA - No subforms in template node.");this.subform.children.length>=2&&warn("XFA - Several subforms in template node: please file a bug.");this[Or]=5e3}[yr](){return!0}[vr](e,t){return e.startsWith("#")?[this[lr].get(e.slice(1))]:searchNode(this,t,e,!0,!0)}*[Wr](){if(!this.subform.children.length)return HTMLResult.success({name:"div",children:[]});this[Xs]={overflowNode:null,firstUnsplittable:null,currentContentArea:null,currentPageArea:null,noLayoutFailure:!1,pageNumber:1,pagePosition:"first",oddOrEven:"odd",blankOrNotBlank:"nonBlank",paraStack:[]};const e=this.subform.children[0];e.pageSet[vs]();const t=e.pageSet.pageArea.children,i={name:"div",children:[]};let a=null,s=null,r=null;if(e.breakBefore.children.length>=1){s=e.breakBefore.children[0];r=s.target}else if(e.subform.children.length>=1&&e.subform.children[0].breakBefore.children.length>=1){s=e.subform.children[0].breakBefore.children[0];r=s.target}else if(e.break?.beforeTarget){s=e.break;r=s.beforeTarget}else if(e.subform.children.length>=1&&e.subform.children[0].break?.beforeTarget){s=e.subform.children[0].break;r=s.beforeTarget}if(s){const e=this[vr](r,s[Ir]());if(e instanceof PageArea){a=e;s[Xs]={}}}a||(a=t[0]);a[Xs]={numberOfUse:1};const n=a[Ir]();n[Xs]={numberOfUse:1,pageIndex:n.pageArea.children.indexOf(a),pageSetIndex:0};let g,o=null,c=null,C=!0,h=0,l=0;for(;;){if(C)h=0;else{i.children.pop();if(3==++h){warn("XFA - Something goes wrong: please file a bug.");return i}}g=null;this[Xs].currentPageArea=a;const t=a[jr]().html;i.children.push(t);if(o){this[Xs].noLayoutFailure=!0;t.children.push(o[jr](a[Xs].space).html);o=null}if(c){this[Xs].noLayoutFailure=!0;t.children.push(c[jr](a[Xs].space).html);c=null}const s=a.contentArea.children,r=t.children.filter((e=>e.attributes.class.includes("xfaContentarea")));C=!1;this[Xs].firstUnsplittable=null;this[Xs].noLayoutFailure=!1;const flush=t=>{const i=e[Vs]();if(i){C||=i.children?.length>0;r[t].children.push(i)}};for(let t=l,a=s.length;t0;r[t].children.push(h.html)}else!C&&i.children.length>1&&i.children.pop();return i}if(h.isBreak()){const e=h.breakNode;flush(t);if("auto"===e.targetType)continue;if(e.leader){o=this[vr](e.leader,e[Ir]());o=o?o[0]:null}if(e.trailer){c=this[vr](e.trailer,e[Ir]());c=c?c[0]:null}if("pageArea"===e.targetType){g=e[Xs].target;t=1/0}else if(e[Xs].target){g=e[Xs].target;l=e[Xs].index+1;t=1/0}else t=e[Xs].index}else if(this[Xs].overflowNode){const e=this[Xs].overflowNode;this[Xs].overflowNode=null;const i=e[ar](),a=i.target;i.addLeader=null!==i.leader;i.addTrailer=null!==i.trailer;flush(t);const r=t;t=1/0;if(a instanceof PageArea)g=a;else if(a instanceof ContentArea){const e=s.indexOf(a);if(-1!==e)e>r?t=e-1:l=e;else{g=a[Ir]();l=g.contentArea.children.indexOf(a)}}}else flush(t)}this[Xs].pageNumber+=1;g&&(g[br]()?g[Xs].numberOfUse+=1:g=null);a=g||a[gr]();yield null}}}class Text extends ContentObject{constructor(e){super(Nn,"text");this.id=e.id||"";this.maxChars=getInteger({data:e.maxChars,defaultValue:0,validate:e=>e>=0});this.name=e.name||"";this.rid=e.rid||"";this.use=e.use||"";this.usehref=e.usehref||""}[xs](){return!0}[Nr](e){if(e[Sr]===_r.xhtml.id){this[Os]=e;return!0}warn(`XFA - Invalid content in Text: ${e[kr]}.`);return!1}[Mr](e){this[Os]instanceof XFAObject||super[Mr](e)}[Zs](){"string"==typeof this[Os]&&(this[Os]=this[Os].replaceAll("\r\n","\n"))}[ar](){return"string"==typeof this[Os]?this[Os].split(/[\u2029\u2028\n]/).reduce(((e,t)=>{t&&e.push(t);return e}),[]).join("\n"):this[Os][Pr]()}[jr](e){if("string"==typeof this[Os]){const e=valueToHtml(this[Os]).html;if(this[Os].includes("\u2029")){e.name="div";e.children=[];this[Os].split("\u2029").map((e=>e.split(/[\u2028\n]/).reduce(((e,t)=>{e.push({name:"span",value:t},{name:"br"});return e}),[]))).forEach((t=>{e.children.push({name:"p",children:t})}))}else if(/[\u2028\n]/.test(this[Os])){e.name="div";e.children=[];this[Os].split(/[\u2028\n]/).forEach((t=>{e.children.push({name:"span",value:t},{name:"br"})}))}return HTMLResult.success(e)}return this[Os][jr](e)}}class TextEdit extends XFAObject{constructor(e){super(Nn,"textEdit",!0);this.allowRichText=getInteger({data:e.allowRichText,defaultValue:0,validate:e=>1===e});this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.multiLine=getInteger({data:e.multiLine,defaultValue:"",validate:e=>0===e||1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.vScrollPolicy=getStringOption(e.vScrollPolicy,["auto","off","on"]);this.border=null;this.comb=null;this.extras=null;this.margin=null}[jr](e){const t=toStyle(this,"border","font","margin");let i;const a=this[Ir]()[Ir]();""===this.multiLine&&(this.multiLine=a instanceof Draw?1:0);i=1===this.multiLine?{name:"textarea",attributes:{dataId:a[Ws]?.[Vr]||a[Vr],fieldId:a[Vr],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(a),"aria-required":!1}}:{name:"input",attributes:{type:"text",dataId:a[Ws]?.[Vr]||a[Vr],fieldId:a[Vr],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(a),"aria-required":!1}};if(isRequired(a)){i.attributes["aria-required"]=!0;i.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[i]})}}class Time extends StringObject{constructor(e){super(Nn,"time");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){const e=this[Os].trim();this[Os]=e?new Date(e):null}[jr](e){return valueToHtml(this[Os]?this[Os].toString():"")}}class TimeStamp extends XFAObject{constructor(e){super(Nn,"timeStamp");this.id=e.id||"";this.server=e.server||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class ToolTip extends StringObject{constructor(e){super(Nn,"toolTip");this.id=e.id||"";this.rid=e.rid||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Traversal extends XFAObject{constructor(e){super(Nn,"traversal",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.traverse=new XFAObjectArray}}class Traverse extends XFAObject{constructor(e){super(Nn,"traverse",!0);this.id=e.id||"";this.operation=getStringOption(e.operation,["next","back","down","first","left","right","up"]);this.ref=e.ref||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.script=null}get name(){return this.operation}[Dr](){return!1}}class Ui extends XFAObject{constructor(e){super(Nn,"ui",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.picture=null;this.barcode=null;this.button=null;this.checkButton=null;this.choiceList=null;this.dateTimeEdit=null;this.defaultUi=null;this.imageEdit=null;this.numericEdit=null;this.passwordEdit=null;this.signature=null;this.textEdit=null}[ar](){if(void 0===this[Xs]){for(const e of Object.getOwnPropertyNames(this)){if("extras"===e||"picture"===e)continue;const t=this[e];if(t instanceof XFAObject){this[Xs]=t;return t}}this[Xs]=null}return this[Xs]}[jr](e){const t=this[ar]();return t?t[jr](e):HTMLResult.EMPTY}}class Validate extends XFAObject{constructor(e){super(Nn,"validate",!0);this.formatTest=getStringOption(e.formatTest,["warning","disabled","error"]);this.id=e.id||"";this.nullTest=getStringOption(e.nullTest,["disabled","error","warning"]);this.scriptTest=getStringOption(e.scriptTest,["error","disabled","warning"]);this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.message=null;this.picture=null;this.script=null}}class Value extends XFAObject{constructor(e){super(Nn,"value",!0);this.id=e.id||"";this.override=getInteger({data:e.override,defaultValue:0,validate:e=>1===e});this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.arc=null;this.boolean=null;this.date=null;this.dateTime=null;this.decimal=null;this.exData=null;this.float=null;this.image=null;this.integer=null;this.line=null;this.rectangle=null;this.text=null;this.time=null}[qr](e){const t=this[Ir]();if(t instanceof Field&&t.ui?.imageEdit){if(!this.image){this.image=new Image({});this[Hs](this.image)}this.image[Os]=e[Os];return}const i=e[kr];if(null===this[i]){for(const e of Object.getOwnPropertyNames(this)){const t=this[e];if(t instanceof XFAObject){this[e]=null;this[Hr](t)}}this[e[kr]]=e;this[Hs](e)}else this[i][Os]=e[Os]}[Pr](){if(this.exData)return"string"==typeof this.exData[Os]?this.exData[Os].trim():this.exData[Os][Pr]().trim();for(const e of Object.getOwnPropertyNames(this)){if("image"===e)continue;const t=this[e];if(t instanceof XFAObject)return(t[Os]||"").toString().trim()}return null}[jr](e){for(const t of Object.getOwnPropertyNames(this)){const i=this[t];if(i instanceof XFAObject)return i[jr](e)}return HTMLResult.EMPTY}}class Variables extends XFAObject{constructor(e){super(Nn,"variables",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.manifest=new XFAObjectArray;this.script=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}[Dr](){return!0}}class TemplateNamespace{static[zr](e,t){if(TemplateNamespace.hasOwnProperty(e)){const i=TemplateNamespace[e](t);i[Tr](t);return i}}static appearanceFilter(e){return new AppearanceFilter(e)}static arc(e){return new Arc(e)}static area(e){return new Area(e)}static assist(e){return new Assist(e)}static barcode(e){return new Barcode(e)}static bind(e){return new Bind(e)}static bindItems(e){return new BindItems(e)}static bookend(e){return new Bookend(e)}static boolean(e){return new BooleanElement(e)}static border(e){return new Border(e)}static break(e){return new Break(e)}static breakAfter(e){return new BreakAfter(e)}static breakBefore(e){return new BreakBefore(e)}static button(e){return new Button(e)}static calculate(e){return new Calculate(e)}static caption(e){return new Caption(e)}static certificate(e){return new Certificate(e)}static certificates(e){return new Certificates(e)}static checkButton(e){return new CheckButton(e)}static choiceList(e){return new ChoiceList(e)}static color(e){return new Color(e)}static comb(e){return new Comb(e)}static connect(e){return new Connect(e)}static contentArea(e){return new ContentArea(e)}static corner(e){return new Corner(e)}static date(e){return new DateElement(e)}static dateTime(e){return new DateTime(e)}static dateTimeEdit(e){return new DateTimeEdit(e)}static decimal(e){return new Decimal(e)}static defaultUi(e){return new DefaultUi(e)}static desc(e){return new Desc(e)}static digestMethod(e){return new DigestMethod(e)}static digestMethods(e){return new DigestMethods(e)}static draw(e){return new Draw(e)}static edge(e){return new Edge(e)}static encoding(e){return new Encoding(e)}static encodings(e){return new Encodings(e)}static encrypt(e){return new Encrypt(e)}static encryptData(e){return new EncryptData(e)}static encryption(e){return new Encryption(e)}static encryptionMethod(e){return new EncryptionMethod(e)}static encryptionMethods(e){return new EncryptionMethods(e)}static event(e){return new Event(e)}static exData(e){return new ExData(e)}static exObject(e){return new ExObject(e)}static exclGroup(e){return new ExclGroup(e)}static execute(e){return new Execute(e)}static extras(e){return new Extras(e)}static field(e){return new Field(e)}static fill(e){return new Fill(e)}static filter(e){return new Filter(e)}static float(e){return new Float(e)}static font(e){return new template_Font(e)}static format(e){return new Format(e)}static handler(e){return new Handler(e)}static hyphenation(e){return new Hyphenation(e)}static image(e){return new Image(e)}static imageEdit(e){return new ImageEdit(e)}static integer(e){return new Integer(e)}static issuers(e){return new Issuers(e)}static items(e){return new Items(e)}static keep(e){return new Keep(e)}static keyUsage(e){return new KeyUsage(e)}static line(e){return new Line(e)}static linear(e){return new Linear(e)}static lockDocument(e){return new LockDocument(e)}static manifest(e){return new Manifest(e)}static margin(e){return new Margin(e)}static mdp(e){return new Mdp(e)}static medium(e){return new Medium(e)}static message(e){return new Message(e)}static numericEdit(e){return new NumericEdit(e)}static occur(e){return new Occur(e)}static oid(e){return new Oid(e)}static oids(e){return new Oids(e)}static overflow(e){return new Overflow(e)}static pageArea(e){return new PageArea(e)}static pageSet(e){return new PageSet(e)}static para(e){return new Para(e)}static passwordEdit(e){return new PasswordEdit(e)}static pattern(e){return new template_Pattern(e)}static picture(e){return new Picture(e)}static proto(e){return new Proto(e)}static radial(e){return new Radial(e)}static reason(e){return new Reason(e)}static reasons(e){return new Reasons(e)}static rectangle(e){return new Rectangle(e)}static ref(e){return new RefElement(e)}static script(e){return new Script(e)}static setProperty(e){return new SetProperty(e)}static signData(e){return new SignData(e)}static signature(e){return new Signature(e)}static signing(e){return new Signing(e)}static solid(e){return new Solid(e)}static speak(e){return new Speak(e)}static stipple(e){return new Stipple(e)}static subform(e){return new Subform(e)}static subformSet(e){return new SubformSet(e)}static subjectDN(e){return new SubjectDN(e)}static subjectDNs(e){return new SubjectDNs(e)}static submit(e){return new Submit(e)}static template(e){return new Template(e)}static text(e){return new Text(e)}static textEdit(e){return new TextEdit(e)}static time(e){return new Time(e)}static timeStamp(e){return new TimeStamp(e)}static toolTip(e){return new ToolTip(e)}static traversal(e){return new Traversal(e)}static traverse(e){return new Traverse(e)}static ui(e){return new Ui(e)}static validate(e){return new Validate(e)}static value(e){return new Value(e)}static variables(e){return new Variables(e)}}const Ln=_r.datasets.id;function createText(e){const t=new Text({});t[Os]=e;return t}class Binder{constructor(e){this.root=e;this.datasets=e.datasets;this.data=e.datasets?.data||new XmlObject(_r.datasets.id,"data");this.emptyMerge=0===this.data[rr]().length;this.root.form=this.form=e.template[Ts]()}_isConsumeData(){return!this.emptyMerge&&this._mergeMode}_isMatchTemplate(){return!this._isConsumeData()}bind(){this._bindElement(this.form,this.data);return this.form}getData(){return this.data}_bindValue(e,t,i){e[Ws]=t;if(e[hr]())if(t[fr]()){const i=t[ir]();e[qr](createText(i))}else if(e instanceof Field&&"multiSelect"===e.ui?.choiceList?.open){const i=t[rr]().map((e=>e[Os].trim())).join("\n");e[qr](createText(i))}else this._isConsumeData()&&warn("XFA - Nodes haven't the same type.");else!t[fr]()||this._isMatchTemplate()?this._bindElement(e,t):warn("XFA - Nodes haven't the same type.")}_findDataByNameToConsume(e,t,i,a){if(!e)return null;let s,r;for(let a=0;a<3;a++){s=i[sr](e,!1,!0);for(;;){r=s.next().value;if(!r)break;if(t===r[fr]())return r}if(i[Sr]===_r.datasets.id&&"data"===i[kr])break;i=i[Ir]()}if(!a)return null;s=this.data[sr](e,!0,!1);r=s.next().value;if(r)return r;s=this.data[zs](e,!0);r=s.next().value;return r?.[fr]()?r:null}_setProperties(e,t){if(e.hasOwnProperty("setProperty"))for(const{ref:i,target:a,connection:s}of e.setProperty.children){if(s)continue;if(!i)continue;const r=searchNode(this.root,t,i,!1,!1);if(!r){warn(`XFA - Invalid reference: ${i}.`);continue}const[n]=r;if(!n[pr](this.data)){warn("XFA - Invalid node: must be a data node.");continue}const g=searchNode(this.root,e,a,!1,!1);if(!g){warn(`XFA - Invalid target: ${a}.`);continue}const[o]=g;if(!o[pr](e)){warn("XFA - Invalid target: must be a property or subproperty.");continue}const c=o[Ir]();if(o instanceof SetProperty||c instanceof SetProperty){warn("XFA - Invalid target: cannot be a setProperty or one of its properties.");continue}if(o instanceof BindItems||c instanceof BindItems){warn("XFA - Invalid target: cannot be a bindItems or one of its properties.");continue}const C=n[Pr](),h=o[kr];if(o instanceof XFAAttribute){const e=Object.create(null);e[h]=C;const t=Reflect.construct(Object.getPrototypeOf(c).constructor,[e]);c[h]=t[h]}else if(o.hasOwnProperty(Os)){o[Ws]=n;o[Os]=C;o[Zs]()}else warn("XFA - Invalid node to use in setProperty")}}_bindItems(e,t){if(!e.hasOwnProperty("items")||!e.hasOwnProperty("bindItems")||e.bindItems.isEmpty())return;for(const t of e.items.children)e[Hr](t);e.items.clear();const i=new Items({}),a=new Items({});e[Hs](i);e.items.push(i);e[Hs](a);e.items.push(a);for(const{ref:s,labelRef:r,valueRef:n,connection:g}of e.bindItems.children){if(g)continue;if(!s)continue;const e=searchNode(this.root,t,s,!1,!1);if(e)for(const t of e){if(!t[pr](this.datasets)){warn(`XFA - Invalid ref (${s}): must be a datasets child.`);continue}const e=searchNode(this.root,t,r,!0,!1);if(!e){warn(`XFA - Invalid label: ${r}.`);continue}const[g]=e;if(!g[pr](this.datasets)){warn("XFA - Invalid label: must be a datasets child.");continue}const o=searchNode(this.root,t,n,!0,!1);if(!o){warn(`XFA - Invalid value: ${n}.`);continue}const[c]=o;if(!c[pr](this.datasets)){warn("XFA - Invalid value: must be a datasets child.");continue}const C=createText(g[Pr]()),h=createText(c[Pr]());i[Hs](C);i.text.push(C);a[Hs](h);a.text.push(h)}else warn(`XFA - Invalid reference: ${s}.`)}}_bindOccurrences(e,t,i){let a;if(t.length>1){a=e[Ts]();a[Hr](a.occur);a.occur=null}this._bindValue(e,t[0],i);this._setProperties(e,t[0]);this._bindItems(e,t[0]);if(1===t.length)return;const s=e[Ir](),r=e[kr],n=s[Qr](e);for(let e=1,g=t.length;et.name===e.name)).length:i[a].children.length;const r=i[Qr](e)+1,n=t.initial-s;if(n){const t=e[Ts]();t[Hr](t.occur);t.occur=null;i[a].push(t);i[Er](r,t);for(let e=1;e0)this._bindOccurrences(a,[e[0]],null);else if(this.emptyMerge){const e=t[Sr]===Ln?-1:t[Sr],i=a[Ws]=new XmlObject(e,a.name||"root");t[Hs](i);this._bindElement(a,i)}continue}if(!a[dr]())continue;let e=!1,s=null,r=null,n=null;if(a.bind){switch(a.bind.match){case"none":this._setAndBind(a,t);continue;case"global":e=!0;break;case"dataRef":if(!a.bind.ref){warn(`XFA - ref is empty in node ${a[kr]}.`);this._setAndBind(a,t);continue}r=a.bind.ref}a.bind.picture&&(s=a.bind.picture[Os])}const[g,o]=this._getOccurInfo(a);if(r){n=searchNode(this.root,t,r,!0,!1);if(null===n){n=createDataNode(this.data,t,r);if(!n)continue;this._isConsumeData()&&(n[qs]=!0);this._setAndBind(a,n);continue}this._isConsumeData()&&(n=n.filter((e=>!e[qs])));n.length>o?n=n.slice(0,o):0===n.length&&(n=null);n&&this._isConsumeData()&&n.forEach((e=>{e[qs]=!0}))}else{if(!a.name){this._setAndBind(a,t);continue}if(this._isConsumeData()){const i=[];for(;i.length0?i:null}else{n=t[sr](a.name,!1,this.emptyMerge).next().value;if(!n){if(0===g){i.push(a);continue}const e=t[Sr]===Ln?-1:t[Sr];n=a[Ws]=new XmlObject(e,a.name);this.emptyMerge&&(n[qs]=!0);t[Hs](n);this._setAndBind(a,n);continue}this.emptyMerge&&(n[qs]=!0);n=[n]}}n?this._bindOccurrences(a,n,s):g>0?this._setAndBind(a,t):i.push(a)}i.forEach((e=>e[Ir]()[Hr](e)))}}class DataHandler{constructor(e,t){this.data=t;this.dataset=e.datasets||null}serialize(e){const t=[[-1,this.data[rr]()]];for(;t.length>0;){const i=t.at(-1),[a,s]=i;if(a+1===s.length){t.pop();continue}const r=s[++i[0]],n=e.get(r[Vr]);if(n)r[qr](n);else{const t=r[_s]();for(const i of t.values()){const t=e.get(i[Vr]);if(t){i[qr](t);break}}}const g=r[rr]();g.length>0&&t.push([-1,g])}const i=[''];if(this.dataset)for(const e of this.dataset[rr]())"data"!==e[kr]&&e[Xr](i);this.data[Xr](i);i.push("");return i.join("")}}const Hn=_r.config.id;class Acrobat extends XFAObject{constructor(e){super(Hn,"acrobat",!0);this.acrobat7=null;this.autoSave=null;this.common=null;this.validate=null;this.validateApprovalSignatures=null;this.submitUrl=new XFAObjectArray}}class Acrobat7 extends XFAObject{constructor(e){super(Hn,"acrobat7",!0);this.dynamicRender=null}}class ADBE_JSConsole extends OptionObject{constructor(e){super(Hn,"ADBE_JSConsole",["delegate","Enable","Disable"])}}class ADBE_JSDebugger extends OptionObject{constructor(e){super(Hn,"ADBE_JSDebugger",["delegate","Enable","Disable"])}}class AddSilentPrint extends Option01{constructor(e){super(Hn,"addSilentPrint")}}class AddViewerPreferences extends Option01{constructor(e){super(Hn,"addViewerPreferences")}}class AdjustData extends Option10{constructor(e){super(Hn,"adjustData")}}class AdobeExtensionLevel extends IntegerObject{constructor(e){super(Hn,"adobeExtensionLevel",0,(e=>e>=1&&e<=8))}}class Agent extends XFAObject{constructor(e){super(Hn,"agent",!0);this.name=e.name?e.name.trim():"";this.common=new XFAObjectArray}}class AlwaysEmbed extends ContentObject{constructor(e){super(Hn,"alwaysEmbed")}}class Amd extends StringObject{constructor(e){super(Hn,"amd")}}class config_Area extends XFAObject{constructor(e){super(Hn,"area");this.level=getInteger({data:e.level,defaultValue:0,validate:e=>e>=1&&e<=3});this.name=getStringOption(e.name,["","barcode","coreinit","deviceDriver","font","general","layout","merge","script","signature","sourceSet","templateCache"])}}class Attributes extends OptionObject{constructor(e){super(Hn,"attributes",["preserve","delegate","ignore"])}}class AutoSave extends OptionObject{constructor(e){super(Hn,"autoSave",["disabled","enabled"])}}class Base extends StringObject{constructor(e){super(Hn,"base")}}class BatchOutput extends XFAObject{constructor(e){super(Hn,"batchOutput");this.format=getStringOption(e.format,["none","concat","zip","zipCompress"])}}class BehaviorOverride extends ContentObject{constructor(e){super(Hn,"behaviorOverride")}[Zs](){this[Os]=new Map(this[Os].trim().split(/\s+/).filter((e=>e.includes(":"))).map((e=>e.split(":",2))))}}class Cache extends XFAObject{constructor(e){super(Hn,"cache",!0);this.templateCache=null}}class Change extends Option01{constructor(e){super(Hn,"change")}}class Common extends XFAObject{constructor(e){super(Hn,"common",!0);this.data=null;this.locale=null;this.localeSet=null;this.messaging=null;this.suppressBanner=null;this.template=null;this.validationMessaging=null;this.versionControl=null;this.log=new XFAObjectArray}}class Compress extends XFAObject{constructor(e){super(Hn,"compress");this.scope=getStringOption(e.scope,["imageOnly","document"])}}class CompressLogicalStructure extends Option01{constructor(e){super(Hn,"compressLogicalStructure")}}class CompressObjectStream extends Option10{constructor(e){super(Hn,"compressObjectStream")}}class Compression extends XFAObject{constructor(e){super(Hn,"compression",!0);this.compressLogicalStructure=null;this.compressObjectStream=null;this.level=null;this.type=null}}class Config extends XFAObject{constructor(e){super(Hn,"config",!0);this.acrobat=null;this.present=null;this.trace=null;this.agent=new XFAObjectArray}}class Conformance extends OptionObject{constructor(e){super(Hn,"conformance",["A","B"])}}class ContentCopy extends Option01{constructor(e){super(Hn,"contentCopy")}}class Copies extends IntegerObject{constructor(e){super(Hn,"copies",1,(e=>e>=1))}}class Creator extends StringObject{constructor(e){super(Hn,"creator")}}class CurrentPage extends IntegerObject{constructor(e){super(Hn,"currentPage",0,(e=>e>=0))}}class Data extends XFAObject{constructor(e){super(Hn,"data",!0);this.adjustData=null;this.attributes=null;this.incrementalLoad=null;this.outputXSL=null;this.range=null;this.record=null;this.startNode=null;this.uri=null;this.window=null;this.xsl=null;this.excludeNS=new XFAObjectArray;this.transform=new XFAObjectArray}}class Debug extends XFAObject{constructor(e){super(Hn,"debug",!0);this.uri=null}}class DefaultTypeface extends ContentObject{constructor(e){super(Hn,"defaultTypeface");this.writingScript=getStringOption(e.writingScript,["*","Arabic","Cyrillic","EastEuropeanRoman","Greek","Hebrew","Japanese","Korean","Roman","SimplifiedChinese","Thai","TraditionalChinese","Vietnamese"])}}class Destination extends OptionObject{constructor(e){super(Hn,"destination",["pdf","pcl","ps","webClient","zpl"])}}class DocumentAssembly extends Option01{constructor(e){super(Hn,"documentAssembly")}}class Driver extends XFAObject{constructor(e){super(Hn,"driver",!0);this.name=e.name?e.name.trim():"";this.fontInfo=null;this.xdc=null}}class DuplexOption extends OptionObject{constructor(e){super(Hn,"duplexOption",["simplex","duplexFlipLongEdge","duplexFlipShortEdge"])}}class DynamicRender extends OptionObject{constructor(e){super(Hn,"dynamicRender",["forbidden","required"])}}class Embed extends Option01{constructor(e){super(Hn,"embed")}}class config_Encrypt extends Option01{constructor(e){super(Hn,"encrypt")}}class config_Encryption extends XFAObject{constructor(e){super(Hn,"encryption",!0);this.encrypt=null;this.encryptionLevel=null;this.permissions=null}}class EncryptionLevel extends OptionObject{constructor(e){super(Hn,"encryptionLevel",["40bit","128bit"])}}class Enforce extends StringObject{constructor(e){super(Hn,"enforce")}}class Equate extends XFAObject{constructor(e){super(Hn,"equate");this.force=getInteger({data:e.force,defaultValue:1,validate:e=>0===e});this.from=e.from||"";this.to=e.to||""}}class EquateRange extends XFAObject{constructor(e){super(Hn,"equateRange");this.from=e.from||"";this.to=e.to||"";this._unicodeRange=e.unicodeRange||""}get unicodeRange(){const e=[],t=/U\+([0-9a-fA-F]+)/,i=this._unicodeRange;for(let a of i.split(",").map((e=>e.trim())).filter((e=>!!e))){a=a.split("-",2).map((e=>{const i=e.match(t);return i?parseInt(i[1],16):0}));1===a.length&&a.push(a[0]);e.push(a)}return shadow(this,"unicodeRange",e)}}class Exclude extends ContentObject{constructor(e){super(Hn,"exclude")}[Zs](){this[Os]=this[Os].trim().split(/\s+/).filter((e=>e&&["calculate","close","enter","exit","initialize","ready","validate"].includes(e)))}}class ExcludeNS extends StringObject{constructor(e){super(Hn,"excludeNS")}}class FlipLabel extends OptionObject{constructor(e){super(Hn,"flipLabel",["usePrinterSetting","on","off"])}}class config_FontInfo extends XFAObject{constructor(e){super(Hn,"fontInfo",!0);this.embed=null;this.map=null;this.subsetBelow=null;this.alwaysEmbed=new XFAObjectArray;this.defaultTypeface=new XFAObjectArray;this.neverEmbed=new XFAObjectArray}}class FormFieldFilling extends Option01{constructor(e){super(Hn,"formFieldFilling")}}class GroupParent extends StringObject{constructor(e){super(Hn,"groupParent")}}class IfEmpty extends OptionObject{constructor(e){super(Hn,"ifEmpty",["dataValue","dataGroup","ignore","remove"])}}class IncludeXDPContent extends StringObject{constructor(e){super(Hn,"includeXDPContent")}}class IncrementalLoad extends OptionObject{constructor(e){super(Hn,"incrementalLoad",["none","forwardOnly"])}}class IncrementalMerge extends Option01{constructor(e){super(Hn,"incrementalMerge")}}class Interactive extends Option01{constructor(e){super(Hn,"interactive")}}class Jog extends OptionObject{constructor(e){super(Hn,"jog",["usePrinterSetting","none","pageSet"])}}class LabelPrinter extends XFAObject{constructor(e){super(Hn,"labelPrinter",!0);this.name=getStringOption(e.name,["zpl","dpl","ipl","tcpl"]);this.batchOutput=null;this.flipLabel=null;this.fontInfo=null;this.xdc=null}}class Layout extends OptionObject{constructor(e){super(Hn,"layout",["paginate","panel"])}}class Level extends IntegerObject{constructor(e){super(Hn,"level",0,(e=>e>0))}}class Linearized extends Option01{constructor(e){super(Hn,"linearized")}}class Locale extends StringObject{constructor(e){super(Hn,"locale")}}class LocaleSet extends StringObject{constructor(e){super(Hn,"localeSet")}}class Log extends XFAObject{constructor(e){super(Hn,"log",!0);this.mode=null;this.threshold=null;this.to=null;this.uri=null}}class MapElement extends XFAObject{constructor(e){super(Hn,"map",!0);this.equate=new XFAObjectArray;this.equateRange=new XFAObjectArray}}class MediumInfo extends XFAObject{constructor(e){super(Hn,"mediumInfo",!0);this.map=null}}class config_Message extends XFAObject{constructor(e){super(Hn,"message",!0);this.msgId=null;this.severity=null}}class Messaging extends XFAObject{constructor(e){super(Hn,"messaging",!0);this.message=new XFAObjectArray}}class Mode extends OptionObject{constructor(e){super(Hn,"mode",["append","overwrite"])}}class ModifyAnnots extends Option01{constructor(e){super(Hn,"modifyAnnots")}}class MsgId extends IntegerObject{constructor(e){super(Hn,"msgId",1,(e=>e>=1))}}class NameAttr extends StringObject{constructor(e){super(Hn,"nameAttr")}}class NeverEmbed extends ContentObject{constructor(e){super(Hn,"neverEmbed")}}class NumberOfCopies extends IntegerObject{constructor(e){super(Hn,"numberOfCopies",null,(e=>e>=2&&e<=5))}}class OpenAction extends XFAObject{constructor(e){super(Hn,"openAction",!0);this.destination=null}}class Output extends XFAObject{constructor(e){super(Hn,"output",!0);this.to=null;this.type=null;this.uri=null}}class OutputBin extends StringObject{constructor(e){super(Hn,"outputBin")}}class OutputXSL extends XFAObject{constructor(e){super(Hn,"outputXSL",!0);this.uri=null}}class Overprint extends OptionObject{constructor(e){super(Hn,"overprint",["none","both","draw","field"])}}class Packets extends StringObject{constructor(e){super(Hn,"packets")}[Zs](){"*"!==this[Os]&&(this[Os]=this[Os].trim().split(/\s+/).filter((e=>["config","datasets","template","xfdf","xslt"].includes(e))))}}class PageOffset extends XFAObject{constructor(e){super(Hn,"pageOffset");this.x=getInteger({data:e.x,defaultValue:"useXDCSetting",validate:e=>!0});this.y=getInteger({data:e.y,defaultValue:"useXDCSetting",validate:e=>!0})}}class PageRange extends StringObject{constructor(e){super(Hn,"pageRange")}[Zs](){const e=this[Os].trim().split(/\s+/).map((e=>parseInt(e,10))),t=[];for(let i=0,a=e.length;i!1))}}class Pcl extends XFAObject{constructor(e){super(Hn,"pcl",!0);this.name=e.name||"";this.batchOutput=null;this.fontInfo=null;this.jog=null;this.mediumInfo=null;this.outputBin=null;this.pageOffset=null;this.staple=null;this.xdc=null}}class Pdf extends XFAObject{constructor(e){super(Hn,"pdf",!0);this.name=e.name||"";this.adobeExtensionLevel=null;this.batchOutput=null;this.compression=null;this.creator=null;this.encryption=null;this.fontInfo=null;this.interactive=null;this.linearized=null;this.openAction=null;this.pdfa=null;this.producer=null;this.renderPolicy=null;this.scriptModel=null;this.silentPrint=null;this.submitFormat=null;this.tagged=null;this.version=null;this.viewerPreferences=null;this.xdc=null}}class Pdfa extends XFAObject{constructor(e){super(Hn,"pdfa",!0);this.amd=null;this.conformance=null;this.includeXDPContent=null;this.part=null}}class Permissions extends XFAObject{constructor(e){super(Hn,"permissions",!0);this.accessibleContent=null;this.change=null;this.contentCopy=null;this.documentAssembly=null;this.formFieldFilling=null;this.modifyAnnots=null;this.plaintextMetadata=null;this.print=null;this.printHighQuality=null}}class PickTrayByPDFSize extends Option01{constructor(e){super(Hn,"pickTrayByPDFSize")}}class config_Picture extends StringObject{constructor(e){super(Hn,"picture")}}class PlaintextMetadata extends Option01{constructor(e){super(Hn,"plaintextMetadata")}}class Presence extends OptionObject{constructor(e){super(Hn,"presence",["preserve","dissolve","dissolveStructure","ignore","remove"])}}class Present extends XFAObject{constructor(e){super(Hn,"present",!0);this.behaviorOverride=null;this.cache=null;this.common=null;this.copies=null;this.destination=null;this.incrementalMerge=null;this.layout=null;this.output=null;this.overprint=null;this.pagination=null;this.paginationOverride=null;this.script=null;this.validate=null;this.xdp=null;this.driver=new XFAObjectArray;this.labelPrinter=new XFAObjectArray;this.pcl=new XFAObjectArray;this.pdf=new XFAObjectArray;this.ps=new XFAObjectArray;this.submitUrl=new XFAObjectArray;this.webClient=new XFAObjectArray;this.zpl=new XFAObjectArray}}class Print extends Option01{constructor(e){super(Hn,"print")}}class PrintHighQuality extends Option01{constructor(e){super(Hn,"printHighQuality")}}class PrintScaling extends OptionObject{constructor(e){super(Hn,"printScaling",["appdefault","noScaling"])}}class PrinterName extends StringObject{constructor(e){super(Hn,"printerName")}}class Producer extends StringObject{constructor(e){super(Hn,"producer")}}class Ps extends XFAObject{constructor(e){super(Hn,"ps",!0);this.name=e.name||"";this.batchOutput=null;this.fontInfo=null;this.jog=null;this.mediumInfo=null;this.outputBin=null;this.staple=null;this.xdc=null}}class Range extends ContentObject{constructor(e){super(Hn,"range")}[Zs](){this[Os]=this[Os].trim().split(/\s*,\s*/,2).map((e=>e.split("-").map((e=>parseInt(e.trim(),10))))).filter((e=>e.every((e=>!isNaN(e))))).map((e=>{1===e.length&&e.push(e[0]);return e}))}}class Record extends ContentObject{constructor(e){super(Hn,"record")}[Zs](){this[Os]=this[Os].trim();const e=parseInt(this[Os],10);!isNaN(e)&&e>=0&&(this[Os]=e)}}class Relevant extends ContentObject{constructor(e){super(Hn,"relevant")}[Zs](){this[Os]=this[Os].trim().split(/\s+/)}}class Rename extends ContentObject{constructor(e){super(Hn,"rename")}[Zs](){this[Os]=this[Os].trim();(this[Os].toLowerCase().startsWith("xml")||new RegExp("[\\p{L}_][\\p{L}\\d._\\p{M}-]*","u").test(this[Os]))&&warn("XFA - Rename: invalid XFA name")}}class RenderPolicy extends OptionObject{constructor(e){super(Hn,"renderPolicy",["server","client"])}}class RunScripts extends OptionObject{constructor(e){super(Hn,"runScripts",["both","client","none","server"])}}class config_Script extends XFAObject{constructor(e){super(Hn,"script",!0);this.currentPage=null;this.exclude=null;this.runScripts=null}}class ScriptModel extends OptionObject{constructor(e){super(Hn,"scriptModel",["XFA","none"])}}class Severity extends OptionObject{constructor(e){super(Hn,"severity",["ignore","error","information","trace","warning"])}}class SilentPrint extends XFAObject{constructor(e){super(Hn,"silentPrint",!0);this.addSilentPrint=null;this.printerName=null}}class Staple extends XFAObject{constructor(e){super(Hn,"staple");this.mode=getStringOption(e.mode,["usePrinterSetting","on","off"])}}class StartNode extends StringObject{constructor(e){super(Hn,"startNode")}}class StartPage extends IntegerObject{constructor(e){super(Hn,"startPage",0,(e=>!0))}}class SubmitFormat extends OptionObject{constructor(e){super(Hn,"submitFormat",["html","delegate","fdf","xml","pdf"])}}class SubmitUrl extends StringObject{constructor(e){super(Hn,"submitUrl")}}class SubsetBelow extends IntegerObject{constructor(e){super(Hn,"subsetBelow",100,(e=>e>=0&&e<=100))}}class SuppressBanner extends Option01{constructor(e){super(Hn,"suppressBanner")}}class Tagged extends Option01{constructor(e){super(Hn,"tagged")}}class config_Template extends XFAObject{constructor(e){super(Hn,"template",!0);this.base=null;this.relevant=null;this.startPage=null;this.uri=null;this.xsl=null}}class Threshold extends OptionObject{constructor(e){super(Hn,"threshold",["trace","error","information","warning"])}}class To extends OptionObject{constructor(e){super(Hn,"to",["null","memory","stderr","stdout","system","uri"])}}class TemplateCache extends XFAObject{constructor(e){super(Hn,"templateCache");this.maxEntries=getInteger({data:e.maxEntries,defaultValue:5,validate:e=>e>=0})}}class Trace extends XFAObject{constructor(e){super(Hn,"trace",!0);this.area=new XFAObjectArray}}class Transform extends XFAObject{constructor(e){super(Hn,"transform",!0);this.groupParent=null;this.ifEmpty=null;this.nameAttr=null;this.picture=null;this.presence=null;this.rename=null;this.whitespace=null}}class Type extends OptionObject{constructor(e){super(Hn,"type",["none","ascii85","asciiHex","ccittfax","flate","lzw","runLength","native","xdp","mergedXDP"])}}class Uri extends StringObject{constructor(e){super(Hn,"uri")}}class config_Validate extends OptionObject{constructor(e){super(Hn,"validate",["preSubmit","prePrint","preExecute","preSave"])}}class ValidateApprovalSignatures extends ContentObject{constructor(e){super(Hn,"validateApprovalSignatures")}[Zs](){this[Os]=this[Os].trim().split(/\s+/).filter((e=>["docReady","postSign"].includes(e)))}}class ValidationMessaging extends OptionObject{constructor(e){super(Hn,"validationMessaging",["allMessagesIndividually","allMessagesTogether","firstMessageOnly","noMessages"])}}class Version extends OptionObject{constructor(e){super(Hn,"version",["1.7","1.6","1.5","1.4","1.3","1.2"])}}class VersionControl extends XFAObject{constructor(e){super(Hn,"VersionControl");this.outputBelow=getStringOption(e.outputBelow,["warn","error","update"]);this.sourceAbove=getStringOption(e.sourceAbove,["warn","error"]);this.sourceBelow=getStringOption(e.sourceBelow,["update","maintain"])}}class ViewerPreferences extends XFAObject{constructor(e){super(Hn,"viewerPreferences",!0);this.ADBE_JSConsole=null;this.ADBE_JSDebugger=null;this.addViewerPreferences=null;this.duplexOption=null;this.enforce=null;this.numberOfCopies=null;this.pageRange=null;this.pickTrayByPDFSize=null;this.printScaling=null}}class WebClient extends XFAObject{constructor(e){super(Hn,"webClient",!0);this.name=e.name?e.name.trim():"";this.fontInfo=null;this.xdc=null}}class Whitespace extends OptionObject{constructor(e){super(Hn,"whitespace",["preserve","ltrim","normalize","rtrim","trim"])}}class Window extends ContentObject{constructor(e){super(Hn,"window")}[Zs](){const e=this[Os].trim().split(/\s*,\s*/,2).map((e=>parseInt(e,10)));if(e.some((e=>isNaN(e))))this[Os]=[0,0];else{1===e.length&&e.push(e[0]);this[Os]=e}}}class Xdc extends XFAObject{constructor(e){super(Hn,"xdc",!0);this.uri=new XFAObjectArray;this.xsl=new XFAObjectArray}}class Xdp extends XFAObject{constructor(e){super(Hn,"xdp",!0);this.packets=null}}class Xsl extends XFAObject{constructor(e){super(Hn,"xsl",!0);this.debug=null;this.uri=null}}class Zpl extends XFAObject{constructor(e){super(Hn,"zpl",!0);this.name=e.name?e.name.trim():"";this.batchOutput=null;this.flipLabel=null;this.fontInfo=null;this.xdc=null}}class ConfigNamespace{static[zr](e,t){if(ConfigNamespace.hasOwnProperty(e))return ConfigNamespace[e](t)}static acrobat(e){return new Acrobat(e)}static acrobat7(e){return new Acrobat7(e)}static ADBE_JSConsole(e){return new ADBE_JSConsole(e)}static ADBE_JSDebugger(e){return new ADBE_JSDebugger(e)}static addSilentPrint(e){return new AddSilentPrint(e)}static addViewerPreferences(e){return new AddViewerPreferences(e)}static adjustData(e){return new AdjustData(e)}static adobeExtensionLevel(e){return new AdobeExtensionLevel(e)}static agent(e){return new Agent(e)}static alwaysEmbed(e){return new AlwaysEmbed(e)}static amd(e){return new Amd(e)}static area(e){return new config_Area(e)}static attributes(e){return new Attributes(e)}static autoSave(e){return new AutoSave(e)}static base(e){return new Base(e)}static batchOutput(e){return new BatchOutput(e)}static behaviorOverride(e){return new BehaviorOverride(e)}static cache(e){return new Cache(e)}static change(e){return new Change(e)}static common(e){return new Common(e)}static compress(e){return new Compress(e)}static compressLogicalStructure(e){return new CompressLogicalStructure(e)}static compressObjectStream(e){return new CompressObjectStream(e)}static compression(e){return new Compression(e)}static config(e){return new Config(e)}static conformance(e){return new Conformance(e)}static contentCopy(e){return new ContentCopy(e)}static copies(e){return new Copies(e)}static creator(e){return new Creator(e)}static currentPage(e){return new CurrentPage(e)}static data(e){return new Data(e)}static debug(e){return new Debug(e)}static defaultTypeface(e){return new DefaultTypeface(e)}static destination(e){return new Destination(e)}static documentAssembly(e){return new DocumentAssembly(e)}static driver(e){return new Driver(e)}static duplexOption(e){return new DuplexOption(e)}static dynamicRender(e){return new DynamicRender(e)}static embed(e){return new Embed(e)}static encrypt(e){return new config_Encrypt(e)}static encryption(e){return new config_Encryption(e)}static encryptionLevel(e){return new EncryptionLevel(e)}static enforce(e){return new Enforce(e)}static equate(e){return new Equate(e)}static equateRange(e){return new EquateRange(e)}static exclude(e){return new Exclude(e)}static excludeNS(e){return new ExcludeNS(e)}static flipLabel(e){return new FlipLabel(e)}static fontInfo(e){return new config_FontInfo(e)}static formFieldFilling(e){return new FormFieldFilling(e)}static groupParent(e){return new GroupParent(e)}static ifEmpty(e){return new IfEmpty(e)}static includeXDPContent(e){return new IncludeXDPContent(e)}static incrementalLoad(e){return new IncrementalLoad(e)}static incrementalMerge(e){return new IncrementalMerge(e)}static interactive(e){return new Interactive(e)}static jog(e){return new Jog(e)}static labelPrinter(e){return new LabelPrinter(e)}static layout(e){return new Layout(e)}static level(e){return new Level(e)}static linearized(e){return new Linearized(e)}static locale(e){return new Locale(e)}static localeSet(e){return new LocaleSet(e)}static log(e){return new Log(e)}static map(e){return new MapElement(e)}static mediumInfo(e){return new MediumInfo(e)}static message(e){return new config_Message(e)}static messaging(e){return new Messaging(e)}static mode(e){return new Mode(e)}static modifyAnnots(e){return new ModifyAnnots(e)}static msgId(e){return new MsgId(e)}static nameAttr(e){return new NameAttr(e)}static neverEmbed(e){return new NeverEmbed(e)}static numberOfCopies(e){return new NumberOfCopies(e)}static openAction(e){return new OpenAction(e)}static output(e){return new Output(e)}static outputBin(e){return new OutputBin(e)}static outputXSL(e){return new OutputXSL(e)}static overprint(e){return new Overprint(e)}static packets(e){return new Packets(e)}static pageOffset(e){return new PageOffset(e)}static pageRange(e){return new PageRange(e)}static pagination(e){return new Pagination(e)}static paginationOverride(e){return new PaginationOverride(e)}static part(e){return new Part(e)}static pcl(e){return new Pcl(e)}static pdf(e){return new Pdf(e)}static pdfa(e){return new Pdfa(e)}static permissions(e){return new Permissions(e)}static pickTrayByPDFSize(e){return new PickTrayByPDFSize(e)}static picture(e){return new config_Picture(e)}static plaintextMetadata(e){return new PlaintextMetadata(e)}static presence(e){return new Presence(e)}static present(e){return new Present(e)}static print(e){return new Print(e)}static printHighQuality(e){return new PrintHighQuality(e)}static printScaling(e){return new PrintScaling(e)}static printerName(e){return new PrinterName(e)}static producer(e){return new Producer(e)}static ps(e){return new Ps(e)}static range(e){return new Range(e)}static record(e){return new Record(e)}static relevant(e){return new Relevant(e)}static rename(e){return new Rename(e)}static renderPolicy(e){return new RenderPolicy(e)}static runScripts(e){return new RunScripts(e)}static script(e){return new config_Script(e)}static scriptModel(e){return new ScriptModel(e)}static severity(e){return new Severity(e)}static silentPrint(e){return new SilentPrint(e)}static staple(e){return new Staple(e)}static startNode(e){return new StartNode(e)}static startPage(e){return new StartPage(e)}static submitFormat(e){return new SubmitFormat(e)}static submitUrl(e){return new SubmitUrl(e)}static subsetBelow(e){return new SubsetBelow(e)}static suppressBanner(e){return new SuppressBanner(e)}static tagged(e){return new Tagged(e)}static template(e){return new config_Template(e)}static templateCache(e){return new TemplateCache(e)}static threshold(e){return new Threshold(e)}static to(e){return new To(e)}static trace(e){return new Trace(e)}static transform(e){return new Transform(e)}static type(e){return new Type(e)}static uri(e){return new Uri(e)}static validate(e){return new config_Validate(e)}static validateApprovalSignatures(e){return new ValidateApprovalSignatures(e)}static validationMessaging(e){return new ValidationMessaging(e)}static version(e){return new Version(e)}static versionControl(e){return new VersionControl(e)}static viewerPreferences(e){return new ViewerPreferences(e)}static webClient(e){return new WebClient(e)}static whitespace(e){return new Whitespace(e)}static window(e){return new Window(e)}static xdc(e){return new Xdc(e)}static xdp(e){return new Xdp(e)}static xsl(e){return new Xsl(e)}static zpl(e){return new Zpl(e)}}const Jn=_r.connectionSet.id;class ConnectionSet extends XFAObject{constructor(e){super(Jn,"connectionSet",!0);this.wsdlConnection=new XFAObjectArray;this.xmlConnection=new XFAObjectArray;this.xsdConnection=new XFAObjectArray}}class EffectiveInputPolicy extends XFAObject{constructor(e){super(Jn,"effectiveInputPolicy");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class EffectiveOutputPolicy extends XFAObject{constructor(e){super(Jn,"effectiveOutputPolicy");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Operation extends StringObject{constructor(e){super(Jn,"operation");this.id=e.id||"";this.input=e.input||"";this.name=e.name||"";this.output=e.output||"";this.use=e.use||"";this.usehref=e.usehref||""}}class RootElement extends StringObject{constructor(e){super(Jn,"rootElement");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class SoapAction extends StringObject{constructor(e){super(Jn,"soapAction");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class SoapAddress extends StringObject{constructor(e){super(Jn,"soapAddress");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class connection_set_Uri extends StringObject{constructor(e){super(Jn,"uri");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class WsdlAddress extends StringObject{constructor(e){super(Jn,"wsdlAddress");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class WsdlConnection extends XFAObject{constructor(e){super(Jn,"wsdlConnection",!0);this.dataDescription=e.dataDescription||"";this.name=e.name||"";this.effectiveInputPolicy=null;this.effectiveOutputPolicy=null;this.operation=null;this.soapAction=null;this.soapAddress=null;this.wsdlAddress=null}}class XmlConnection extends XFAObject{constructor(e){super(Jn,"xmlConnection",!0);this.dataDescription=e.dataDescription||"";this.name=e.name||"";this.uri=null}}class XsdConnection extends XFAObject{constructor(e){super(Jn,"xsdConnection",!0);this.dataDescription=e.dataDescription||"";this.name=e.name||"";this.rootElement=null;this.uri=null}}class ConnectionSetNamespace{static[zr](e,t){if(ConnectionSetNamespace.hasOwnProperty(e))return ConnectionSetNamespace[e](t)}static connectionSet(e){return new ConnectionSet(e)}static effectiveInputPolicy(e){return new EffectiveInputPolicy(e)}static effectiveOutputPolicy(e){return new EffectiveOutputPolicy(e)}static operation(e){return new Operation(e)}static rootElement(e){return new RootElement(e)}static soapAction(e){return new SoapAction(e)}static soapAddress(e){return new SoapAddress(e)}static uri(e){return new connection_set_Uri(e)}static wsdlAddress(e){return new WsdlAddress(e)}static wsdlConnection(e){return new WsdlConnection(e)}static xmlConnection(e){return new XmlConnection(e)}static xsdConnection(e){return new XsdConnection(e)}}const Yn=_r.datasets.id;class datasets_Data extends XmlObject{constructor(e){super(Yn,"data",e)}[mr](){return!0}}class Datasets extends XFAObject{constructor(e){super(Yn,"datasets",!0);this.data=null;this.Signature=null}[Nr](e){const t=e[kr];("data"===t&&e[Sr]===Yn||"Signature"===t&&e[Sr]===_r.signature.id)&&(this[t]=e);this[Hs](e)}}class DatasetsNamespace{static[zr](e,t){if(DatasetsNamespace.hasOwnProperty(e))return DatasetsNamespace[e](t)}static datasets(e){return new Datasets(e)}static data(e){return new datasets_Data(e)}}const vn=_r.localeSet.id;class CalendarSymbols extends XFAObject{constructor(e){super(vn,"calendarSymbols",!0);this.name="gregorian";this.dayNames=new XFAObjectArray(2);this.eraNames=null;this.meridiemNames=null;this.monthNames=new XFAObjectArray(2)}}class CurrencySymbol extends StringObject{constructor(e){super(vn,"currencySymbol");this.name=getStringOption(e.name,["symbol","isoname","decimal"])}}class CurrencySymbols extends XFAObject{constructor(e){super(vn,"currencySymbols",!0);this.currencySymbol=new XFAObjectArray(3)}}class DatePattern extends StringObject{constructor(e){super(vn,"datePattern");this.name=getStringOption(e.name,["full","long","med","short"])}}class DatePatterns extends XFAObject{constructor(e){super(vn,"datePatterns",!0);this.datePattern=new XFAObjectArray(4)}}class DateTimeSymbols extends ContentObject{constructor(e){super(vn,"dateTimeSymbols")}}class Day extends StringObject{constructor(e){super(vn,"day")}}class DayNames extends XFAObject{constructor(e){super(vn,"dayNames",!0);this.abbr=getInteger({data:e.abbr,defaultValue:0,validate:e=>1===e});this.day=new XFAObjectArray(7)}}class Era extends StringObject{constructor(e){super(vn,"era")}}class EraNames extends XFAObject{constructor(e){super(vn,"eraNames",!0);this.era=new XFAObjectArray(2)}}class locale_set_Locale extends XFAObject{constructor(e){super(vn,"locale",!0);this.desc=e.desc||"";this.name="isoname";this.calendarSymbols=null;this.currencySymbols=null;this.datePatterns=null;this.dateTimeSymbols=null;this.numberPatterns=null;this.numberSymbols=null;this.timePatterns=null;this.typeFaces=null}}class locale_set_LocaleSet extends XFAObject{constructor(e){super(vn,"localeSet",!0);this.locale=new XFAObjectArray}}class Meridiem extends StringObject{constructor(e){super(vn,"meridiem")}}class MeridiemNames extends XFAObject{constructor(e){super(vn,"meridiemNames",!0);this.meridiem=new XFAObjectArray(2)}}class Month extends StringObject{constructor(e){super(vn,"month")}}class MonthNames extends XFAObject{constructor(e){super(vn,"monthNames",!0);this.abbr=getInteger({data:e.abbr,defaultValue:0,validate:e=>1===e});this.month=new XFAObjectArray(12)}}class NumberPattern extends StringObject{constructor(e){super(vn,"numberPattern");this.name=getStringOption(e.name,["full","long","med","short"])}}class NumberPatterns extends XFAObject{constructor(e){super(vn,"numberPatterns",!0);this.numberPattern=new XFAObjectArray(4)}}class NumberSymbol extends StringObject{constructor(e){super(vn,"numberSymbol");this.name=getStringOption(e.name,["decimal","grouping","percent","minus","zero"])}}class NumberSymbols extends XFAObject{constructor(e){super(vn,"numberSymbols",!0);this.numberSymbol=new XFAObjectArray(5)}}class TimePattern extends StringObject{constructor(e){super(vn,"timePattern");this.name=getStringOption(e.name,["full","long","med","short"])}}class TimePatterns extends XFAObject{constructor(e){super(vn,"timePatterns",!0);this.timePattern=new XFAObjectArray(4)}}class TypeFace extends XFAObject{constructor(e){super(vn,"typeFace",!0);this.name=""|e.name}}class TypeFaces extends XFAObject{constructor(e){super(vn,"typeFaces",!0);this.typeFace=new XFAObjectArray}}class LocaleSetNamespace{static[zr](e,t){if(LocaleSetNamespace.hasOwnProperty(e))return LocaleSetNamespace[e](t)}static calendarSymbols(e){return new CalendarSymbols(e)}static currencySymbol(e){return new CurrencySymbol(e)}static currencySymbols(e){return new CurrencySymbols(e)}static datePattern(e){return new DatePattern(e)}static datePatterns(e){return new DatePatterns(e)}static dateTimeSymbols(e){return new DateTimeSymbols(e)}static day(e){return new Day(e)}static dayNames(e){return new DayNames(e)}static era(e){return new Era(e)}static eraNames(e){return new EraNames(e)}static locale(e){return new locale_set_Locale(e)}static localeSet(e){return new locale_set_LocaleSet(e)}static meridiem(e){return new Meridiem(e)}static meridiemNames(e){return new MeridiemNames(e)}static month(e){return new Month(e)}static monthNames(e){return new MonthNames(e)}static numberPattern(e){return new NumberPattern(e)}static numberPatterns(e){return new NumberPatterns(e)}static numberSymbol(e){return new NumberSymbol(e)}static numberSymbols(e){return new NumberSymbols(e)}static timePattern(e){return new TimePattern(e)}static timePatterns(e){return new TimePatterns(e)}static typeFace(e){return new TypeFace(e)}static typeFaces(e){return new TypeFaces(e)}}const Kn=_r.signature.id;class signature_Signature extends XFAObject{constructor(e){super(Kn,"signature",!0)}}class SignatureNamespace{static[zr](e,t){if(SignatureNamespace.hasOwnProperty(e))return SignatureNamespace[e](t)}static signature(e){return new signature_Signature(e)}}const Tn=_r.stylesheet.id;class Stylesheet extends XFAObject{constructor(e){super(Tn,"stylesheet",!0)}}class StylesheetNamespace{static[zr](e,t){if(StylesheetNamespace.hasOwnProperty(e))return StylesheetNamespace[e](t)}static stylesheet(e){return new Stylesheet(e)}}const qn=_r.xdp.id;class xdp_Xdp extends XFAObject{constructor(e){super(qn,"xdp",!0);this.uuid=e.uuid||"";this.timeStamp=e.timeStamp||"";this.config=null;this.connectionSet=null;this.datasets=null;this.localeSet=null;this.stylesheet=new XFAObjectArray;this.template=null}[Gr](e){const t=_r[e[kr]];return t&&e[Sr]===t.id}}class XdpNamespace{static[zr](e,t){if(XdpNamespace.hasOwnProperty(e))return XdpNamespace[e](t)}static xdp(e){return new xdp_Xdp(e)}}const On=_r.xhtml.id,Pn=Symbol(),Wn=new Set(["color","font","font-family","font-size","font-stretch","font-style","font-weight","margin","margin-bottom","margin-left","margin-right","margin-top","letter-spacing","line-height","orphans","page-break-after","page-break-before","page-break-inside","tab-interval","tab-stop","text-align","text-decoration","text-indent","vertical-align","widows","kerning-mode","xfa-font-horizontal-scale","xfa-font-vertical-scale","xfa-spacerun","xfa-tab-stops"]),jn=new Map([["page-break-after","breakAfter"],["page-break-before","breakBefore"],["page-break-inside","breakInside"],["kerning-mode",e=>"none"===e?"none":"normal"],["xfa-font-horizontal-scale",e=>`scaleX(${Math.max(0,Math.min(parseInt(e)/100)).toFixed(2)})`],["xfa-font-vertical-scale",e=>`scaleY(${Math.max(0,Math.min(parseInt(e)/100)).toFixed(2)})`],["xfa-spacerun",""],["xfa-tab-stops",""],["font-size",(e,t)=>measureToString(.99*(e=t.fontSize=Math.abs(getMeasurement(e))))],["letter-spacing",e=>measureToString(getMeasurement(e))],["line-height",e=>measureToString(getMeasurement(e))],["margin",e=>measureToString(getMeasurement(e))],["margin-bottom",e=>measureToString(getMeasurement(e))],["margin-left",e=>measureToString(getMeasurement(e))],["margin-right",e=>measureToString(getMeasurement(e))],["margin-top",e=>measureToString(getMeasurement(e))],["text-indent",e=>measureToString(getMeasurement(e))],["font-family",e=>e],["vertical-align",e=>measureToString(getMeasurement(e))]]),Xn=/\s+/g,Zn=/[\r\n]+/g,Vn=/\r\n?/g;function mapStyle(e,t,i){const a=Object.create(null);if(!e)return a;const s=Object.create(null);for(const[t,i]of e.split(";").map((e=>e.split(":",2)))){const e=jn.get(t);if(""===e)continue;let r=i;e&&(r="string"==typeof e?e:e(i,s));t.endsWith("scale")?a.transform=a.transform?`${a[t]} ${r}`:r:a[t.replaceAll(/-([a-zA-Z])/g,((e,t)=>t.toUpperCase()))]=r}a.fontFamily&&setFontFamily({typeface:a.fontFamily,weight:a.fontWeight||"normal",posture:a.fontStyle||"normal",size:s.fontSize||0},t,t[Cr].fontFinder,a);if(i&&a.verticalAlign&&"0px"!==a.verticalAlign&&a.fontSize){const e=.583,t=.333,i=getMeasurement(a.fontSize);a.fontSize=measureToString(i*e);a.verticalAlign=measureToString(Math.sign(getMeasurement(a.verticalAlign))*i*t)}i&&a.fontSize&&(a.fontSize=`calc(${a.fontSize} * var(--scale-factor))`);fixTextIndent(a);return a}const zn=new Set(["body","html"]);class XhtmlObject extends XmlObject{constructor(e,t){super(On,t);this[Pn]=!1;this.style=e.style||""}[Ys](e){super[Ys](e);this.style=function checkStyle(e){return e.style?e.style.trim().split(/\s*;\s*/).filter((e=>!!e)).map((e=>e.split(/\s*:\s*/,2))).filter((([t,i])=>{"font-family"===t&&e[Cr].usedTypefaces.add(i);return Wn.has(t)})).map((e=>e.join(":"))).join(";"):""}(this)}[xs](){return!zn.has(this[kr])}[Mr](e,t=!1){if(t)this[Pn]=!0;else{e=e.replaceAll(Zn,"");this.style.includes("xfa-spacerun:yes")||(e=e.replaceAll(Xn," "))}e&&(this[Os]+=e)}[Ur](e,t=!0){const i=Object.create(null),a={top:NaN,bottom:NaN,left:NaN,right:NaN};let s=null;for(const[e,t]of this.style.split(";").map((e=>e.split(":",2))))switch(e){case"font-family":i.typeface=stripQuotes(t);break;case"font-size":i.size=getMeasurement(t);break;case"font-weight":i.weight=t;break;case"font-style":i.posture=t;break;case"letter-spacing":i.letterSpacing=getMeasurement(t);break;case"margin":const e=t.split(/ \t/).map((e=>getMeasurement(e)));switch(e.length){case 1:a.top=a.bottom=a.left=a.right=e[0];break;case 2:a.top=a.bottom=e[0];a.left=a.right=e[1];break;case 3:a.top=e[0];a.bottom=e[2];a.left=a.right=e[1];break;case 4:a.top=e[0];a.left=e[1];a.bottom=e[2];a.right=e[3]}break;case"margin-top":a.top=getMeasurement(t);break;case"margin-bottom":a.bottom=getMeasurement(t);break;case"margin-left":a.left=getMeasurement(t);break;case"margin-right":a.right=getMeasurement(t);break;case"line-height":s=getMeasurement(t)}e.pushData(i,a,s);if(this[Os])e.addString(this[Os]);else for(const t of this[rr]())"#text"!==t[kr]?t[Ur](e):e.addString(t[Os]);t&&e.popFont()}[jr](e){const t=[];this[Xs]={children:t};this[Js]({});if(0===t.length&&!this[Os])return HTMLResult.EMPTY;let i;i=this[Pn]?this[Os]?this[Os].replaceAll(Vn,"\n"):void 0:this[Os]||void 0;return HTMLResult.success({name:this[kr],attributes:{href:this.href,style:mapStyle(this.style,this,this[Pn])},children:t,value:i})}}class A extends XhtmlObject{constructor(e){super(e,"a");this.href=fixURL(e.href)||""}}class B extends XhtmlObject{constructor(e){super(e,"b")}[Ur](e){e.pushFont({weight:"bold"});super[Ur](e);e.popFont()}}class Body extends XhtmlObject{constructor(e){super(e,"body")}[jr](e){const t=super[jr](e),{html:i}=t;if(!i)return HTMLResult.EMPTY;i.name="div";i.attributes.class=["xfaRich"];return t}}class Br extends XhtmlObject{constructor(e){super(e,"br")}[Pr](){return"\n"}[Ur](e){e.addString("\n")}[jr](e){return HTMLResult.success({name:"br"})}}class Html extends XhtmlObject{constructor(e){super(e,"html")}[jr](e){const t=[];this[Xs]={children:t};this[Js]({});if(0===t.length)return HTMLResult.success({name:"div",attributes:{class:["xfaRich"],style:{}},value:this[Os]||""});if(1===t.length){const e=t[0];if(e.attributes?.class.includes("xfaRich"))return HTMLResult.success(e)}return HTMLResult.success({name:"div",attributes:{class:["xfaRich"],style:{}},children:t})}}class I extends XhtmlObject{constructor(e){super(e,"i")}[Ur](e){e.pushFont({posture:"italic"});super[Ur](e);e.popFont()}}class Li extends XhtmlObject{constructor(e){super(e,"li")}}class Ol extends XhtmlObject{constructor(e){super(e,"ol")}}class P extends XhtmlObject{constructor(e){super(e,"p")}[Ur](e){super[Ur](e,!1);e.addString("\n");e.addPara();e.popFont()}[Pr](){return this[Ir]()[rr]().at(-1)===this?super[Pr]():super[Pr]()+"\n"}}class Span extends XhtmlObject{constructor(e){super(e,"span")}}class Sub extends XhtmlObject{constructor(e){super(e,"sub")}}class Sup extends XhtmlObject{constructor(e){super(e,"sup")}}class Ul extends XhtmlObject{constructor(e){super(e,"ul")}}class XhtmlNamespace{static[zr](e,t){if(XhtmlNamespace.hasOwnProperty(e))return XhtmlNamespace[e](t)}static a(e){return new A(e)}static b(e){return new B(e)}static body(e){return new Body(e)}static br(e){return new Br(e)}static html(e){return new Html(e)}static i(e){return new I(e)}static li(e){return new Li(e)}static ol(e){return new Ol(e)}static p(e){return new P(e)}static span(e){return new Span(e)}static sub(e){return new Sub(e)}static sup(e){return new Sup(e)}static ul(e){return new Ul(e)}}const _n={config:ConfigNamespace,connection:ConnectionSetNamespace,datasets:DatasetsNamespace,localeSet:LocaleSetNamespace,signature:SignatureNamespace,stylesheet:StylesheetNamespace,template:TemplateNamespace,xdp:XdpNamespace,xhtml:XhtmlNamespace};class UnknownNamespace{constructor(e){this.namespaceId=e}[zr](e,t){return new XmlObject(this.namespaceId,e,t)}}class Root extends XFAObject{constructor(e){super(-1,"root",Object.create(null));this.element=null;this[lr]=e}[Nr](e){this.element=e;return!0}[Zs](){super[Zs]();if(this.element.template instanceof Template){this[lr].set(Jr,this.element);this.element.template[Yr](this[lr]);this.element.template[lr]=this[lr]}}}class Empty extends XFAObject{constructor(){super(-1,"",Object.create(null))}[Nr](e){return!1}}class Builder{constructor(e=null){this._namespaceStack=[];this._nsAgnosticLevel=0;this._namespacePrefixes=new Map;this._namespaces=new Map;this._nextNsId=Math.max(...Object.values(_r).map((({id:e})=>e)));this._currentNamespace=e||new UnknownNamespace(++this._nextNsId)}buildRoot(e){return new Root(e)}build({nsPrefix:e,name:t,attributes:i,namespace:a,prefixes:s}){const r=null!==a;if(r){this._namespaceStack.push(this._currentNamespace);this._currentNamespace=this._searchNamespace(a)}s&&this._addNamespacePrefix(s);if(i.hasOwnProperty(Rr)){const e=_n.datasets,t=i[Rr];let a=null;for(const[i,s]of Object.entries(t)){if(this._getNamespaceToUse(i)===e){a={xfa:s};break}}a?i[Rr]=a:delete i[Rr]}const n=this._getNamespaceToUse(e),g=n?.[zr](t,i)||new Empty;g[mr]()&&this._nsAgnosticLevel++;(r||s||g[mr]())&&(g[Ks]={hasNamespace:r,prefixes:s,nsAgnostic:g[mr]()});return g}isNsAgnostic(){return this._nsAgnosticLevel>0}_searchNamespace(e){let t=this._namespaces.get(e);if(t)return t;for(const[i,{check:a}]of Object.entries(_r))if(a(e)){t=_n[i];if(t){this._namespaces.set(e,t);return t}break}t=new UnknownNamespace(++this._nextNsId);this._namespaces.set(e,t);return t}_addNamespacePrefix(e){for(const{prefix:t,value:i}of e){const e=this._searchNamespace(i);let a=this._namespacePrefixes.get(t);if(!a){a=[];this._namespacePrefixes.set(t,a)}a.push(e)}}_getNamespaceToUse(e){if(!e)return this._currentNamespace;const t=this._namespacePrefixes.get(e);if(t?.length>0)return t.at(-1);warn(`Unknown namespace prefix: ${e}.`);return null}clean(e){const{hasNamespace:t,prefixes:i,nsAgnostic:a}=e;t&&(this._currentNamespace=this._namespaceStack.pop());i&&i.forEach((({prefix:e})=>{this._namespacePrefixes.get(e).pop()}));a&&this._nsAgnosticLevel--}}class XFAParser extends XMLParserBase{constructor(e=null,t=!1){super();this._builder=new Builder(e);this._stack=[];this._globalData={usedTypefaces:new Set};this._ids=new Map;this._current=this._builder.buildRoot(this._ids);this._errorCode=ys;this._whiteRegex=/^\s+$/;this._nbsps=/\xa0+/g;this._richText=t}parse(e){this.parseXml(e);if(this._errorCode===ys){this._current[Zs]();return this._current.element}}onText(e){e=e.replace(this._nbsps,(e=>e.slice(1)+" "));this._richText||this._current[xs]()?this._current[Mr](e,this._richText):this._whiteRegex.test(e)||this._current[Mr](e.trim())}onCdata(e){this._current[Mr](e)}_mkAttributes(e,t){let i=null,a=null;const s=Object.create({});for(const{name:r,value:n}of e)if("xmlns"===r)i?warn(`XFA - multiple namespace definition in <${t}>`):i=n;else if(r.startsWith("xmlns:")){const e=r.substring(6);a||(a=[]);a.push({prefix:e,value:n})}else{const e=r.indexOf(":");if(-1===e)s[r]=n;else{let t=s[Rr];t||(t=s[Rr]=Object.create(null));const[i,a]=[r.slice(0,e),r.slice(e+1)];(t[i]||=Object.create(null))[a]=n}}return[i,a,s]}_getNameAndPrefix(e,t){const i=e.indexOf(":");return-1===i?[e,null]:[e.substring(i+1),t?"":e.substring(0,i)]}onBeginElement(e,t,i){const[a,s,r]=this._mkAttributes(t,e),[n,g]=this._getNameAndPrefix(e,this._builder.isNsAgnostic()),o=this._builder.build({nsPrefix:g,name:n,attributes:r,namespace:a,prefixes:s});o[Cr]=this._globalData;if(i){o[Zs]();this._current[Nr](o)&&o[Kr](this._ids);o[Ys](this._builder)}else{this._stack.push(this._current);this._current=o}}onEndElement(e){const t=this._current;if(t[ur]()&&"string"==typeof t[Os]){const e=new XFAParser;e._globalData=this._globalData;const i=e.parse(t[Os]);t[Os]=null;t[Nr](i)}t[Zs]();this._current=this._stack.pop();this._current[Nr](t)&&t[Kr](this._ids);t[Ys](this._builder)}onError(e){this._errorCode=e}}class XFAFactory{constructor(e){try{this.root=(new XFAParser).parse(XFAFactory._createDocument(e));const t=new Binder(this.root);this.form=t.bind();this.dataHandler=new DataHandler(this.root,t.getData());this.form[Cr].template=this.form}catch(e){warn(`XFA - an error occurred during parsing and binding: ${e}`)}}isValid(){return this.root&&this.form}_createPagesHelper(){const e=this.form[Wr]();return new Promise(((t,i)=>{const nextIteration=()=>{try{const i=e.next();i.done?t(i.value):setTimeout(nextIteration,0)}catch(e){i(e)}};setTimeout(nextIteration,0)}))}async _createPages(){try{this.pages=await this._createPagesHelper();this.dims=this.pages.children.map((e=>{const{width:t,height:i}=e.attributes.style;return[0,0,parseInt(t),parseInt(i)]}))}catch(e){warn(`XFA - an error occurred during layout: ${e}`)}}getBoundingBox(e){return this.dims[e]}async getNumPages(){this.pages||await this._createPages();return this.dims.length}setImages(e){this.form[Cr].images=e}setFonts(e){this.form[Cr].fontFinder=new FontFinder(e);const t=[];for(let e of this.form[Cr].usedTypefaces){e=stripQuotes(e);this.form[Cr].fontFinder.find(e)||t.push(e)}return t.length>0?t:null}appendFonts(e,t){this.form[Cr].fontFinder.add(e,t)}async getPages(){this.pages||await this._createPages();const e=this.pages;this.pages=null;return e}serializeData(e){return this.dataHandler.serialize(e)}static _createDocument(e){return e["/xdp:xdp"]?Object.values(e).join(""):e["xdp:xdp"]}static getRichTextAsHtml(e){if(!e||"string"!=typeof e)return null;try{let t=new XFAParser(XhtmlNamespace,!0).parse(e);if(!["body","xhtml"].includes(t[kr])){const e=XhtmlNamespace.body({});e[Hs](t);t=e}const i=t[jr]();if(!i.success)return null;const{html:a}=i,{attributes:s}=a;if(s){s.class&&(s.class=s.class.filter((e=>!e.startsWith("xfa"))));s.dir="auto"}return{html:a,str:t[Pr]()}}catch(e){warn(`XFA - an error occurred during parsing of rich text: ${e}`)}return null}}class AnnotationFactory{static createGlobals(e){return Promise.all([e.ensureCatalog("acroForm"),e.ensureDoc("xfaDatasets"),e.ensureCatalog("structTreeRoot"),e.ensureCatalog("baseUrl"),e.ensureCatalog("attachments")]).then((([t,i,a,s,r])=>({pdfManager:e,acroForm:t instanceof Dict?t:Dict.empty,xfaDatasets:i,structTreeRoot:a,baseUrl:s,attachments:r})),(e=>{warn(`createGlobals: "${e}".`);return null}))}static async create(e,t,i,a,s,r,n){const g=s?await this._getPageIndex(e,t,i.pdfManager):null;return i.pdfManager.ensure(this,"_create",[e,t,i,a,s,r,g,n])}static _create(e,t,i,a,s=!1,r=null,n=null,g=null){const o=e.fetchIfRef(t);if(!(o instanceof Dict))return;const{acroForm:c,pdfManager:C}=i,h=t instanceof Ref?t.toString():`annot_${a.createObjId()}`;let l=o.get("Subtype");l=l instanceof Name?l.name:null;const Q={xref:e,ref:t,dict:o,subtype:l,id:h,annotationGlobals:i,collectFields:s,orphanFields:r,needAppearances:!s&&!0===c.get("NeedAppearances"),pageIndex:n,evaluatorOptions:C.evaluatorOptions,pageRef:g};switch(l){case"Link":return new LinkAnnotation(Q);case"Text":return new TextAnnotation(Q);case"Widget":let e=getInheritableProperty({dict:o,key:"FT"});e=e instanceof Name?e.name:null;switch(e){case"Tx":return new TextWidgetAnnotation(Q);case"Btn":return new ButtonWidgetAnnotation(Q);case"Ch":return new ChoiceWidgetAnnotation(Q);case"Sig":return new SignatureWidgetAnnotation(Q)}warn(`Unimplemented widget field type "${e}", falling back to base field type.`);return new WidgetAnnotation(Q);case"Popup":return new PopupAnnotation(Q);case"FreeText":return new FreeTextAnnotation(Q);case"Line":return new LineAnnotation(Q);case"Square":return new SquareAnnotation(Q);case"Circle":return new CircleAnnotation(Q);case"PolyLine":return new PolylineAnnotation(Q);case"Polygon":return new PolygonAnnotation(Q);case"Caret":return new CaretAnnotation(Q);case"Ink":return new InkAnnotation(Q);case"Highlight":return new HighlightAnnotation(Q);case"Underline":return new UnderlineAnnotation(Q);case"Squiggly":return new SquigglyAnnotation(Q);case"StrikeOut":return new StrikeOutAnnotation(Q);case"Stamp":return new StampAnnotation(Q);case"FileAttachment":return new FileAttachmentAnnotation(Q);default:s||warn(l?`Unimplemented annotation type "${l}", falling back to base annotation.`:"Annotation is missing the required /Subtype.");return new Annotation(Q)}}static async _getPageIndex(e,t,i){try{const a=await e.fetchIfRefAsync(t);if(!(a instanceof Dict))return-1;const s=a.getRaw("P");if(s instanceof Ref)try{return await i.ensureCatalog("getPageIndex",[s])}catch(e){info(`_getPageIndex -- not a valid page reference: "${e}".`)}if(a.has("Kids"))return-1;const r=await i.ensureDoc("numPages");for(let e=0;ee/255))}function getQuadPoints(e,t){const i=e.getArray("QuadPoints");if(!isNumberArray(i,null)||0===i.length||i.length%8>0)return null;const a=new Float32Array(i.length);for(let e=0,s=i.length;et[2]||Et[3]))return null;a.set([l,u,Q,u,l,E,Q,E],e)}return a}function getTransformMatrix(e,t,i){const[a,s,r,n]=Util.getAxialAlignedBoundingBox(t,i);if(a===r||s===n)return[1,0,0,1,e[0],e[1]];const g=(e[2]-e[0])/(r-a),o=(e[3]-e[1])/(n-s);return[g,0,0,o,e[0]-a*g,e[1]-s*o]}class Annotation{constructor(e){const{dict:t,xref:i,annotationGlobals:a,ref:s,orphanFields:r}=e,n=r?.get(s);n&&t.set("Parent",n);this.setTitle(t.get("T"));this.setContents(t.get("Contents"));this.setModificationDate(t.get("M"));this.setFlags(t.get("F"));this.setRectangle(t.getArray("Rect"));this.setColor(t.getArray("C"));this.setBorderStyle(t);this.setAppearance(t);this.setOptionalContent(t);const g=t.get("MK");this.setBorderAndBackgroundColors(g);this.setRotation(g,t);this.ref=e.ref instanceof Ref?e.ref:null;this._streams=[];this.appearance&&this._streams.push(this.appearance);const o=!!(this.flags&eA),c=!!(this.flags&tA);this.data={annotationFlags:this.flags,borderStyle:this.borderStyle,color:this.color,backgroundColor:this.backgroundColor,borderColor:this.borderColor,rotation:this.rotation,contentsObj:this._contents,hasAppearance:!!this.appearance,id:e.id,modificationDate:this.modificationDate,rect:this.rectangle,subtype:e.subtype,hasOwnCanvas:!1,noRotate:!!(this.flags&$),noHTML:o&&c,isEditable:!1,structParent:-1};if(a.structTreeRoot){let i=t.get("StructParent");this.data.structParent=i=Number.isInteger(i)&&i>=0?i:-1;a.structTreeRoot.addAnnotationIdToPage(e.pageRef,i)}if(e.collectFields){const a=t.get("Kids");if(Array.isArray(a)){const e=[];for(const t of a)t instanceof Ref&&e.push(t.toString());0!==e.length&&(this.data.kidIds=e)}this.data.actions=collectActions(i,t,dA);this.data.fieldName=this._constructFieldName(t);this.data.pageIndex=e.pageIndex}const C=t.get("IT");C instanceof Name&&(this.data.it=C.name);this._isOffscreenCanvasSupported=e.evaluatorOptions.isOffscreenCanvasSupported;this._fallbackFontDict=null;this._needAppearances=!1}_hasFlag(e,t){return!!(e&t)}_buildFlags(e,t){let{flags:i}=this;if(void 0===e){if(void 0===t)return;return t?i&~_:i&~z|_}if(e){i|=_;return t?i&~AA|z:i&~z|AA}i&=~(z|AA);return t?i&~_:i|_}_isViewable(e){return!this._hasFlag(e,V)&&!this._hasFlag(e,AA)}_isPrintable(e){return this._hasFlag(e,_)&&!this._hasFlag(e,z)&&!this._hasFlag(e,V)}mustBeViewed(e,t){const i=e?.get(this.data.id)?.noView;return void 0!==i?!i:this.viewable&&!this._hasFlag(this.flags,z)}mustBePrinted(e){const t=e?.get(this.data.id)?.noPrint;return void 0!==t?!t:this.printable}mustBeViewedWhenEditing(e,t=null){return e?!this.data.isEditable:!t?.has(this.data.id)}get viewable(){return null!==this.data.quadPoints&&(0===this.flags||this._isViewable(this.flags))}get printable(){return null!==this.data.quadPoints&&(0!==this.flags&&this._isPrintable(this.flags))}_parseStringHelper(e){const t="string"==typeof e?stringToPDFString(e):"";return{str:t,dir:t&&"rtl"===bidi(t).dir?"rtl":"ltr"}}setDefaultAppearance(e){const{dict:t,annotationGlobals:i}=e,a=getInheritableProperty({dict:t,key:"DA"})||i.acroForm.get("DA");this._defaultAppearance="string"==typeof a?a:"";this.data.defaultAppearanceData=parseDefaultAppearance(this._defaultAppearance)}setTitle(e){this._title=this._parseStringHelper(e)}setContents(e){this._contents=this._parseStringHelper(e)}setModificationDate(e){this.modificationDate="string"==typeof e?e:null}setFlags(e){this.flags=Number.isInteger(e)&&e>0?e:0;this.flags&V&&"Annotation"!==this.constructor.name&&(this.flags^=V)}hasFlag(e){return this._hasFlag(this.flags,e)}setRectangle(e){this.rectangle=lookupNormalRect(e,[0,0,0,0])}setColor(e){this.color=getRgbColor(e)}setLineEndings(e){this.lineEndings=["None","None"];if(Array.isArray(e)&&2===e.length)for(let t=0;t<2;t++){const i=e[t];if(i instanceof Name)switch(i.name){case"None":continue;case"Square":case"Circle":case"Diamond":case"OpenArrow":case"ClosedArrow":case"Butt":case"ROpenArrow":case"RClosedArrow":case"Slash":this.lineEndings[t]=i.name;continue}warn(`Ignoring invalid lineEnding: ${i}`)}}setRotation(e,t){this.rotation=0;let i=e instanceof Dict?e.get("R")||0:t.get("Rotate")||0;if(Number.isInteger(i)&&0!==i){i%=360;i<0&&(i+=360);i%90==0&&(this.rotation=i)}}setBorderAndBackgroundColors(e){if(e instanceof Dict){this.borderColor=getRgbColor(e.getArray("BC"),null);this.backgroundColor=getRgbColor(e.getArray("BG"),null)}else this.borderColor=this.backgroundColor=null}setBorderStyle(e){this.borderStyle=new AnnotationBorderStyle;if(e instanceof Dict)if(e.has("BS")){const t=e.get("BS");if(t instanceof Dict){const e=t.get("Type");if(!e||isName(e,"Border")){this.borderStyle.setWidth(t.get("W"),this.rectangle);this.borderStyle.setStyle(t.get("S"));this.borderStyle.setDashArray(t.getArray("D"))}}}else if(e.has("Border")){const t=e.getArray("Border");if(Array.isArray(t)&&t.length>=3){this.borderStyle.setHorizontalCornerRadius(t[0]);this.borderStyle.setVerticalCornerRadius(t[1]);this.borderStyle.setWidth(t[2],this.rectangle);4===t.length&&this.borderStyle.setDashArray(t[3],!0)}}else this.borderStyle.setWidth(0)}setAppearance(e){this.appearance=null;const t=e.get("AP");if(!(t instanceof Dict))return;const i=t.get("N");if(i instanceof BaseStream){this.appearance=i;return}if(!(i instanceof Dict))return;const a=e.get("AS");if(!(a instanceof Name&&i.has(a.name)))return;const s=i.get(a.name);s instanceof BaseStream&&(this.appearance=s)}setOptionalContent(e){this.oc=null;const t=e.get("OC");t instanceof Name?warn("setOptionalContent: Support for /Name-entry is not implemented."):t instanceof Dict&&(this.oc=t)}loadResources(e,t){return t.dict.getAsync("Resources").then((t=>{if(!t)return;return new ObjectLoader(t,e,t.xref).load().then((function(){return t}))}))}async getOperatorList(e,t,a,s){const{hasOwnCanvas:r,id:n,rect:g}=this.data;let c=this.appearance;const C=!!(r&&a&o);if(C&&(g[0]===g[2]||g[1]===g[3])){this.data.hasOwnCanvas=!1;return{opList:new OperatorList,separateForm:!1,separateCanvas:!1}}if(!c){if(!C)return{opList:new OperatorList,separateForm:!1,separateCanvas:!1};c=new StringStream("");c.dict=new Dict}const h=c.dict,l=await this.loadResources(["ExtGState","ColorSpace","Pattern","Shading","XObject","Font"],c),Q=lookupRect(h.getArray("BBox"),[0,0,1,1]),E=lookupMatrix(h.getArray("Matrix"),i),u=getTransformMatrix(g,Q,E),d=new OperatorList;let f;this.oc&&(f=await e.parseMarkedContentProps(this.oc,null));void 0!==f&&d.addOp(Ye,["OC",f]);d.addOp(je,[n,g,u,E,C]);await e.getOperatorList({stream:c,task:t,resources:l,operatorList:d,fallbackFontDict:this._fallbackFontDict});d.addOp(Xe,[]);void 0!==f&&d.addOp(ve,[]);this.reset();return{opList:d,separateForm:!1,separateCanvas:C}}async save(e,t,i,a){return null}get hasTextContent(){return!1}async extractTextContent(e,t,i){if(!this.appearance)return;const a=await this.loadResources(["ExtGState","Font","Properties","XObject"],this.appearance),s=[],r=[];let n=null;const g={desiredSize:Math.Infinity,ready:!0,enqueue(e,t){for(const t of e.items)if(void 0!==t.str){n||=t.transform.slice(-2);r.push(t.str);if(t.hasEOL){s.push(r.join("").trimEnd());r.length=0}}}};await e.getTextContent({stream:this.appearance,task:t,resources:a,includeMarkedContent:!0,keepWhiteSpace:!0,sink:g,viewBox:i});this.reset();r.length&&s.push(r.join("").trimEnd());if(s.length>1||s[0]){const e=this.appearance.dict,t=lookupRect(e.getArray("BBox"),null),i=lookupMatrix(e.getArray("Matrix"),null);this.data.textPosition=this._transformPoint(n,t,i);this.data.textContent=s}}_transformPoint(e,t,i){const{rect:a}=this.data;t||=[0,0,1,1];i||=[1,0,0,1,0,0];const s=getTransformMatrix(a,t,i);s[4]-=a[0];s[5]-=a[1];e=Util.applyTransform(e,s);return Util.applyTransform(e,i)}getFieldObject(){return this.data.kidIds?{id:this.data.id,actions:this.data.actions,name:this.data.fieldName,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,type:"",kidIds:this.data.kidIds,page:this.data.pageIndex,rotation:this.rotation}:null}reset(){for(const e of this._streams)e.reset()}_constructFieldName(e){if(!e.has("T")&&!e.has("Parent")){warn("Unknown field name, falling back to empty field name.");return""}if(!e.has("Parent"))return stringToPDFString(e.get("T"));const t=[];e.has("T")&&t.unshift(stringToPDFString(e.get("T")));let i=e;const a=new RefSet;e.objId&&a.put(e.objId);for(;i.has("Parent");){i=i.get("Parent");if(!(i instanceof Dict)||i.objId&&a.has(i.objId))break;i.objId&&a.put(i.objId);i.has("T")&&t.unshift(stringToPDFString(i.get("T")))}return t.join(".")}}class AnnotationBorderStyle{constructor(){this.width=1;this.rawWidth=1;this.style=lA;this.dashArray=[3];this.horizontalCornerRadius=0;this.verticalCornerRadius=0}setWidth(e,t=[0,0,0,0]){if(e instanceof Name)this.width=0;else if("number"==typeof e){if(e>0){this.rawWidth=e;const i=(t[2]-t[0])/2,a=(t[3]-t[1])/2;if(i>0&&a>0&&(e>i||e>a)){warn(`AnnotationBorderStyle.setWidth - ignoring width: ${e}`);e=1}}this.width=e}}setStyle(e){if(e instanceof Name)switch(e.name){case"S":this.style=lA;break;case"D":this.style=BA;break;case"B":this.style=QA;break;case"I":this.style=EA;break;case"U":this.style=uA}}setDashArray(e,t=!1){if(Array.isArray(e)){let i=!0,a=!0;for(const t of e){if(!(+t>=0)){i=!1;break}t>0&&(a=!1)}if(0===e.length||i&&!a){this.dashArray=e;t&&this.setStyle(Name.get("D"))}else this.width=0}else e&&(this.width=0)}setHorizontalCornerRadius(e){Number.isInteger(e)&&(this.horizontalCornerRadius=e)}setVerticalCornerRadius(e){Number.isInteger(e)&&(this.verticalCornerRadius=e)}}class MarkupAnnotation extends Annotation{constructor(e){super(e);const{dict:t}=e;if(t.has("IRT")){const e=t.getRaw("IRT");this.data.inReplyTo=e instanceof Ref?e.toString():null;const i=t.get("RT");this.data.replyType=i instanceof Name?i.name:Z}let i=null;if(this.data.replyType===X){const e=t.get("IRT");this.setTitle(e.get("T"));this.data.titleObj=this._title;this.setContents(e.get("Contents"));this.data.contentsObj=this._contents;if(e.has("CreationDate")){this.setCreationDate(e.get("CreationDate"));this.data.creationDate=this.creationDate}else this.data.creationDate=null;if(e.has("M")){this.setModificationDate(e.get("M"));this.data.modificationDate=this.modificationDate}else this.data.modificationDate=null;i=e.getRaw("Popup");if(e.has("C")){this.setColor(e.getArray("C"));this.data.color=this.color}else this.data.color=null}else{this.data.titleObj=this._title;this.setCreationDate(t.get("CreationDate"));this.data.creationDate=this.creationDate;i=t.getRaw("Popup");t.has("C")||(this.data.color=null)}this.data.popupRef=i instanceof Ref?i.toString():null;t.has("RC")&&(this.data.richText=XFAFactory.getRichTextAsHtml(t.get("RC")))}setCreationDate(e){this.creationDate="string"==typeof e?e:null}_setDefaultAppearance({xref:e,extra:t,strokeColor:i,fillColor:a,blendMode:s,strokeAlpha:r,fillAlpha:n,pointsCallback:g}){let o=Number.MAX_VALUE,c=Number.MAX_VALUE,C=Number.MIN_VALUE,h=Number.MIN_VALUE;const l=["q"];t&&l.push(t);i&&l.push(`${i[0]} ${i[1]} ${i[2]} RG`);a&&l.push(`${a[0]} ${a[1]} ${a[2]} rg`);const Q=this.data.quadPoints||Float32Array.from([this.rectangle[0],this.rectangle[3],this.rectangle[2],this.rectangle[3],this.rectangle[0],this.rectangle[1],this.rectangle[2],this.rectangle[1]]);for(let e=0,t=Q.length;e"string"==typeof e)).map((e=>stringToPDFString(e))):e instanceof Name?stringToPDFString(e.name):"string"==typeof e?stringToPDFString(e):null}hasFieldFlag(e){return!!(this.data.fieldFlags&e)}_isViewable(e){return!0}mustBeViewed(e,t){return t?this.viewable:super.mustBeViewed(e,t)&&!this._hasFlag(this.flags,AA)}getRotationMatrix(e){let t=e?.get(this.data.id)?.rotation;void 0===t&&(t=this.rotation);if(0===t)return i;return getRotationMatrix(t,this.data.rect[2]-this.data.rect[0],this.data.rect[3]-this.data.rect[1])}getBorderAndBackgroundAppearances(e){let t=e?.get(this.data.id)?.rotation;void 0===t&&(t=this.rotation);if(!this.backgroundColor&&!this.borderColor)return"";const i=this.data.rect[2]-this.data.rect[0],a=this.data.rect[3]-this.data.rect[1],s=0===t||180===t?`0 0 ${i} ${a} re`:`0 0 ${a} ${i} re`;let r="";this.backgroundColor&&(r=`${getPdfColor(this.backgroundColor,!0)} ${s} f `);if(this.borderColor){r+=`${this.borderStyle.width||1} w ${getPdfColor(this.borderColor,!1)} ${s} S `}return r}async getOperatorList(e,t,i,a){if(i&h&&!(this instanceof SignatureWidgetAnnotation)&&!this.data.noHTML&&!this.data.hasOwnCanvas)return{opList:new OperatorList,separateForm:!0,separateCanvas:!1};if(!this._hasText)return super.getOperatorList(e,t,i,a);const s=await this._getAppearance(e,t,i,a);if(this.appearance&&null===s)return super.getOperatorList(e,t,i,a);const r=new OperatorList;if(!this._defaultAppearance||null===s)return{opList:r,separateForm:!1,separateCanvas:!1};const n=!!(this.data.hasOwnCanvas&&i&o),g=[0,0,this.data.rect[2]-this.data.rect[0],this.data.rect[3]-this.data.rect[1]],c=getTransformMatrix(this.data.rect,g,[1,0,0,1,0,0]);let C;this.oc&&(C=await e.parseMarkedContentProps(this.oc,null));void 0!==C&&r.addOp(Ye,["OC",C]);r.addOp(je,[this.data.id,this.data.rect,c,this.getRotationMatrix(a),n]);const l=new StringStream(s);await e.getOperatorList({stream:l,task:t,resources:this._fieldResources.mergedResources,operatorList:r});r.addOp(Xe,[]);void 0!==C&&r.addOp(ve,[]);return{opList:r,separateForm:!1,separateCanvas:n}}_getMKDict(e){const t=new Dict(null);e&&t.set("R",e);this.borderColor&&t.set("BC",getPdfColorArray(this.borderColor));this.backgroundColor&&t.set("BG",getPdfColorArray(this.backgroundColor));return t.size>0?t:null}amendSavedDict(e,t){}setValue(e,t,i,a){const{dict:s,ref:r}=function getParentToUpdate(e,t,i){const a=new RefSet,s=e,r={dict:null,ref:null};for(;e instanceof Dict&&!a.has(t);){a.put(t);if(e.has("T"))break;if(!((t=e.getRaw("Parent"))instanceof Ref))return r;e=i.fetch(t)}if(e instanceof Dict&&e!==s){r.dict=e;r.ref=t}return r}(e,this.ref,i);if(s){if(!a.has(r)){const e=s.clone();e.set("V",t);a.put(r,{data:e});return e}}else e.set("V",t);return null}async save(e,t,a,s){const r=a?.get(this.data.id),n=this._buildFlags(r?.noView,r?.noPrint);let g=r?.value,o=r?.rotation;if(g===this.data.fieldValue||void 0===g){if(!this._hasValueFromXFA&&void 0===o&&void 0===n)return;g||=this.data.fieldValue}if(void 0===o&&!this._hasValueFromXFA&&Array.isArray(g)&&Array.isArray(this.data.fieldValue)&&isArrayEqual(g,this.data.fieldValue)&&void 0===n)return;void 0===o&&(o=this.rotation);let c=null;if(!this._needAppearances){c=await this._getAppearance(e,t,C,a);if(null===c&&void 0===n)return}let h=!1;if(c?.needAppearances){h=!0;c=null}const{xref:l}=e,Q=l.fetchIfRef(this.ref);if(!(Q instanceof Dict))return;const E=new Dict(l);for(const e of Q.getKeys())"AP"!==e&&E.set(e,Q.getRaw(e));if(void 0!==n){E.set("F",n);if(null===c&&!h){const e=Q.getRaw("AP");e&&E.set("AP",e)}}const u={path:this.data.fieldName,value:g},d=this.setValue(E,Array.isArray(g)?g.map(stringToAsciiOrUTF16BE):stringToAsciiOrUTF16BE(g),l,s);this.amendSavedDict(a,d||E);const f=this._getMKDict(o);f&&E.set("MK",f);s.put(this.ref,{data:E,xfa:u,needAppearances:h});if(null!==c){const e=l.getNewTemporaryRef(),t=new Dict(l);E.set("AP",t);t.set("N",e);const r=this._getSaveFieldResources(l),n=new StringStream(c),g=n.dict=new Dict(l);g.set("Subtype",Name.get("Form"));g.set("Resources",r);g.set("BBox",[0,0,this.data.rect[2]-this.data.rect[0],this.data.rect[3]-this.data.rect[1]]);const o=this.getRotationMatrix(a);o!==i&&g.set("Matrix",o);s.put(e,{data:n,xfa:null,needAppearances:!1})}E.set("M",`D:${getModificationDate()}`)}async _getAppearance(e,t,i,a){if(this.hasFieldFlag(rA))return null;const s=a?.get(this.data.id);let r,g;if(s){r=s.formattedValue||s.value;g=s.rotation}if(void 0===g&&void 0===r&&!this._needAppearances&&(!this._hasValueFromXFA||this.appearance))return null;const o=this.getBorderAndBackgroundAppearances(a);if(void 0===r){r=this.data.fieldValue;if(!r)return`/Tx BMC q ${o}Q EMC`}Array.isArray(r)&&1===r.length&&(r=r[0]);assert("string"==typeof r,"Expected `value` to be a string.");r=r.trimEnd();if(this.data.combo){const e=this.data.options.find((({exportValue:e})=>r===e));r=e?.displayValue||r}if(""===r)return`/Tx BMC q ${o}Q EMC`;void 0===g&&(g=this.rotation);let c,h=-1;if(this.data.multiLine){c=r.split(/\r\n?|\n/).map((e=>e.normalize("NFC")));h=c.length}else c=[r.replace(/\r\n?|\n/,"").normalize("NFC")];let l=this.data.rect[3]-this.data.rect[1],Q=this.data.rect[2]-this.data.rect[0];90!==g&&270!==g||([Q,l]=[l,Q]);this._defaultAppearance||(this.data.defaultAppearanceData=parseDefaultAppearance(this._defaultAppearance="/Helvetica 0 Tf 0 g"));let E,u,d,f=await WidgetAnnotation._getFontData(e,t,this.data.defaultAppearanceData,this._fieldResources.mergedResources);const p=[];let m=!1;for(const e of c){const t=f.encodeString(e);t.length>1&&(m=!0);p.push(t.join(""))}if(m&&i&C)return{needAppearances:!0};if(m&&this._isOffscreenCanvasSupported){const i=this.data.comb?"monospace":"sans-serif",a=new FakeUnicodeFont(e.xref,i),s=a.createFontResources(c.join("")),n=s.getRaw("Font");if(this._fieldResources.mergedResources.has("Font")){const e=this._fieldResources.mergedResources.get("Font");for(const t of n.getKeys())e.set(t,n.getRaw(t))}else this._fieldResources.mergedResources.set("Font",n);const g=a.fontName.name;f=await WidgetAnnotation._getFontData(e,t,{fontName:g,fontSize:0},s);for(let e=0,t=p.length;e2)return`/Tx BMC q ${o}BT `+E+` 1 0 0 1 ${numberToString(2)} ${numberToString(b)} Tm (${escapeString(p[0])}) Tj ET Q EMC`;return`/Tx BMC q ${o}BT `+E+` 1 0 0 1 0 0 Tm ${this._renderText(p[0],f,u,Q,D,{shift:0},2,b)} ET Q EMC`}static async _getFontData(e,t,i,a){const s=new OperatorList,r={font:null,clone(){return this}},{fontName:n,fontSize:g}=i;await e.handleSetFont(a,[n&&Name.get(n),g],null,s,t,r,null);return r.font}_getTextWidth(e,t){return t.charsToGlyphs(e).reduce(((e,t)=>e+t.width),0)/1e3}_computeFontSize(e,t,i,a,r){let{fontSize:n}=this.data.defaultAppearanceData,g=(n||12)*s,o=Math.round(e/g);if(!n){const roundWithTwoDigits=e=>Math.floor(100*e)/100;if(-1===r){const r=this._getTextWidth(i,a);n=roundWithTwoDigits(Math.min(e/s,t/r));o=1}else{const c=i.split(/\r\n?|\n/),C=[];for(const e of c){const t=a.encodeString(e).join(""),i=a.charsToGlyphs(t),s=a.getCharPositions(t);C.push({line:t,glyphs:i,positions:s})}const isTooBig=i=>{let s=0;for(const r of C){s+=this._splitLine(null,a,i,t,r).length*i;if(s>e)return!0}return!1};o=Math.max(o,r);for(;;){g=e/o;n=roundWithTwoDigits(g/s);if(!isTooBig(n))break;o++}}const{fontName:c,fontColor:C}=this.data.defaultAppearanceData;this._defaultAppearance=function createDefaultAppearance({fontSize:e,fontName:t,fontColor:i}){return`/${escapePDFName(t)} ${e} Tf ${getPdfColor(i,!0)}`}({fontSize:n,fontName:c,fontColor:C})}return[this._defaultAppearance,n,e/o]}_renderText(e,t,i,a,s,r,n,g){let o;if(1===s){o=(a-this._getTextWidth(e,t)*i)/2}else if(2===s){o=a-this._getTextWidth(e,t)*i-n}else o=n;const c=numberToString(o-r.shift);r.shift=o;return`${c} ${g=numberToString(g)} Td (${escapeString(e)}) Tj`}_getSaveFieldResources(e){const{localResources:t,appearanceResources:i,acroFormResources:a}=this._fieldResources,s=this.data.defaultAppearanceData?.fontName;if(!s)return t||Dict.empty;for(const e of[t,i])if(e instanceof Dict){const t=e.get("Font");if(t instanceof Dict&&t.has(s))return e}if(a instanceof Dict){const i=a.get("Font");if(i instanceof Dict&&i.has(s)){const a=new Dict(e);a.set(s,i.getRaw(s));const r=new Dict(e);r.set("Font",a);return Dict.merge({xref:e,dictArray:[r,t],mergeSubDicts:!0})}}return t||Dict.empty}getFieldObject(){return null}}class TextWidgetAnnotation extends WidgetAnnotation{constructor(e){super(e);const{dict:t}=e;if(t.has("PMD")){this.flags|=z;this.data.hidden=!0;warn("Barcodes are not supported")}this.data.hasOwnCanvas=this.data.readOnly&&!this.data.noHTML;this._hasText=!0;"string"!=typeof this.data.fieldValue&&(this.data.fieldValue="");let i=getInheritableProperty({dict:t,key:"Q"});(!Number.isInteger(i)||i<0||i>2)&&(i=null);this.data.textAlignment=i;let a=getInheritableProperty({dict:t,key:"MaxLen"});(!Number.isInteger(a)||a<0)&&(a=0);this.data.maxLen=a;this.data.multiLine=this.hasFieldFlag(sA);this.data.comb=this.hasFieldFlag(hA)&&!this.hasFieldFlag(sA)&&!this.hasFieldFlag(rA)&&!this.hasFieldFlag(IA)&&0!==this.data.maxLen;this.data.doNotScroll=this.hasFieldFlag(CA)}get hasTextContent(){return!!this.appearance&&!this._needAppearances}_getCombAppearance(e,t,i,a,s,r,n,g,o,c,C){const h=s/this.data.maxLen,l=this.getBorderAndBackgroundAppearances(C),Q=[],E=t.getCharPositions(i);for(const[e,t]of E)Q.push(`(${escapeString(i.substring(e,t))}) Tj`);const u=Q.join(` ${numberToString(h)} 0 Td `);return`/Tx BMC q ${l}BT `+e+` 1 0 0 1 ${numberToString(n)} ${numberToString(g+o)} Tm ${u} ET Q EMC`}_getMultilineAppearance(e,t,i,a,s,r,n,g,o,c,C,h){const l=[],Q=s-2*g,E={shift:0};for(let e=0,r=t.length;ea){o.push(e.substring(l,i));l=i;Q=u;c=-1;h=-1}else{Q+=u;c=i;C=s;h=t}else if(Q+u>a)if(-1!==c){o.push(e.substring(l,C));l=C;t=h+1;c=-1;Q=0}else{o.push(e.substring(l,i));l=i;Q=u}else Q+=u}lt?`\\${t}`:"\\s+"));new RegExp(`^\\s*${r}\\s*$`).test(this.data.fieldValue)&&(this.data.textContent=this.data.fieldValue.split("\n"))}getFieldObject(){return{id:this.data.id,value:this.data.fieldValue,defaultValue:this.data.defaultFieldValue||"",multiline:this.data.multiLine,password:this.hasFieldFlag(rA),charLimit:this.data.maxLen,comb:this.data.comb,editable:!this.data.readOnly,hidden:this.data.hidden,name:this.data.fieldName,rect:this.data.rect,actions:this.data.actions,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,type:"text"}}}class ButtonWidgetAnnotation extends WidgetAnnotation{constructor(e){super(e);this.checkedAppearance=null;this.uncheckedAppearance=null;this.data.checkBox=!this.hasFieldFlag(nA)&&!this.hasFieldFlag(gA);this.data.radioButton=this.hasFieldFlag(nA)&&!this.hasFieldFlag(gA);this.data.pushButton=this.hasFieldFlag(gA);this.data.isTooltipOnly=!1;if(this.data.checkBox)this._processCheckBox(e);else if(this.data.radioButton)this._processRadioButton(e);else if(this.data.pushButton){this.data.hasOwnCanvas=!0;this.data.noHTML=!1;this._processPushButton(e)}else warn("Invalid field flags for button widget annotation")}async getOperatorList(e,t,a,s){if(this.data.pushButton)return super.getOperatorList(e,t,a,!1,s);let r=null,n=null;if(s){const e=s.get(this.data.id);r=e?e.value:null;n=e?e.rotation:null}if(null===r&&this.appearance)return super.getOperatorList(e,t,a,s);null==r&&(r=this.data.checkBox?this.data.fieldValue===this.data.exportValue:this.data.fieldValue===this.data.buttonValue);const g=r?this.checkedAppearance:this.uncheckedAppearance;if(g){const r=this.appearance,o=lookupMatrix(g.dict.getArray("Matrix"),i);n&&g.dict.set("Matrix",this.getRotationMatrix(s));this.appearance=g;const c=super.getOperatorList(e,t,a,s);this.appearance=r;g.dict.set("Matrix",o);return c}return{opList:new OperatorList,separateForm:!1,separateCanvas:!1}}async save(e,t,i,a){this.data.checkBox?this._saveCheckbox(e,t,i,a):this.data.radioButton&&this._saveRadioButton(e,t,i,a)}async _saveCheckbox(e,t,i,a){if(!i)return;const s=i.get(this.data.id),r=this._buildFlags(s?.noView,s?.noPrint);let n=s?.rotation,g=s?.value;if(void 0===n&&void 0===r){if(void 0===g)return;if(this.data.fieldValue===this.data.exportValue===g)return}let o=e.xref.fetchIfRef(this.ref);if(!(o instanceof Dict))return;o=o.clone();void 0===n&&(n=this.rotation);void 0===g&&(g=this.data.fieldValue===this.data.exportValue);const c={path:this.data.fieldName,value:g?this.data.exportValue:""},C=Name.get(g?this.data.exportValue:"Off");this.setValue(o,C,e.xref,a);o.set("AS",C);o.set("M",`D:${getModificationDate()}`);void 0!==r&&o.set("F",r);const h=this._getMKDict(n);h&&o.set("MK",h);a.put(this.ref,{data:o,xfa:c,needAppearances:!1})}async _saveRadioButton(e,t,i,a){if(!i)return;const s=i.get(this.data.id),r=this._buildFlags(s?.noView,s?.noPrint);let n=s?.rotation,g=s?.value;if(void 0===n&&void 0===r){if(void 0===g)return;if(this.data.fieldValue===this.data.buttonValue===g)return}let o=e.xref.fetchIfRef(this.ref);if(!(o instanceof Dict))return;o=o.clone();void 0===g&&(g=this.data.fieldValue===this.data.buttonValue);void 0===n&&(n=this.rotation);const c={path:this.data.fieldName,value:g?this.data.buttonValue:""},C=Name.get(g?this.data.buttonValue:"Off");g&&this.setValue(o,C,e.xref,a);o.set("AS",C);o.set("M",`D:${getModificationDate()}`);void 0!==r&&o.set("F",r);const h=this._getMKDict(n);h&&o.set("MK",h);a.put(this.ref,{data:o,xfa:c,needAppearances:!1})}_getDefaultCheckedAppearance(e,t){const i=this.data.rect[2]-this.data.rect[0],a=this.data.rect[3]-this.data.rect[1],s=[0,0,i,a],r=.8*Math.min(i,a);let n,g;if("check"===t){n={width:.755*r,height:.705*r};g="3"}else if("disc"===t){n={width:.791*r,height:.705*r};g="l"}else unreachable(`_getDefaultCheckedAppearance - unsupported type: ${t}`);const o=`q BT /PdfJsZaDb ${r} Tf 0 g ${numberToString((i-n.width)/2)} ${numberToString((a-n.height)/2)} Td (${g}) Tj ET Q`,c=new Dict(e.xref);c.set("FormType",1);c.set("Subtype",Name.get("Form"));c.set("Type",Name.get("XObject"));c.set("BBox",s);c.set("Matrix",[1,0,0,1,0,0]);c.set("Length",o.length);const C=new Dict(e.xref),h=new Dict(e.xref);h.set("PdfJsZaDb",this.fallbackFontDict);C.set("Font",h);c.set("Resources",C);this.checkedAppearance=new StringStream(o);this.checkedAppearance.dict=c;this._streams.push(this.checkedAppearance)}_processCheckBox(e){const t=e.dict.get("AP");if(!(t instanceof Dict))return;const i=t.get("N");if(!(i instanceof Dict))return;const a=this._decodeFormValue(e.dict.get("AS"));"string"==typeof a&&(this.data.fieldValue=a);const s=null!==this.data.fieldValue&&"Off"!==this.data.fieldValue?this.data.fieldValue:"Yes",r=i.getKeys();if(0===r.length)r.push("Off",s);else if(1===r.length)"Off"===r[0]?r.push(s):r.unshift("Off");else if(r.includes(s)){r.length=0;r.push("Off",s)}else{const e=r.find((e=>"Off"!==e));r.length=0;r.push("Off",e)}r.includes(this.data.fieldValue)||(this.data.fieldValue="Off");this.data.exportValue=r[1];const n=i.get(this.data.exportValue);this.checkedAppearance=n instanceof BaseStream?n:null;const g=i.get("Off");this.uncheckedAppearance=g instanceof BaseStream?g:null;this.checkedAppearance?this._streams.push(this.checkedAppearance):this._getDefaultCheckedAppearance(e,"check");this.uncheckedAppearance&&this._streams.push(this.uncheckedAppearance);this._fallbackFontDict=this.fallbackFontDict;null===this.data.defaultFieldValue&&(this.data.defaultFieldValue="Off")}_processRadioButton(e){this.data.buttonValue=null;const t=e.dict.get("Parent");if(t instanceof Dict){this.parent=e.dict.getRaw("Parent");const i=t.get("V");i instanceof Name&&(this.data.fieldValue=this._decodeFormValue(i))}const i=e.dict.get("AP");if(!(i instanceof Dict))return;const a=i.get("N");if(!(a instanceof Dict))return;for(const e of a.getKeys())if("Off"!==e){this.data.buttonValue=this._decodeFormValue(e);break}const s=a.get(this.data.buttonValue);this.checkedAppearance=s instanceof BaseStream?s:null;const r=a.get("Off");this.uncheckedAppearance=r instanceof BaseStream?r:null;this.checkedAppearance?this._streams.push(this.checkedAppearance):this._getDefaultCheckedAppearance(e,"disc");this.uncheckedAppearance&&this._streams.push(this.uncheckedAppearance);this._fallbackFontDict=this.fallbackFontDict;null===this.data.defaultFieldValue&&(this.data.defaultFieldValue="Off")}_processPushButton(e){const{dict:t,annotationGlobals:i}=e;if(t.has("A")||t.has("AA")||this.data.alternativeText){this.data.isTooltipOnly=!t.has("A")&&!t.has("AA");Catalog.parseDestDictionary({destDict:t,resultObj:this.data,docBaseUrl:i.baseUrl,docAttachments:i.attachments})}else warn("Push buttons without action dictionaries are not supported")}getFieldObject(){let e,t="button";if(this.data.checkBox){t="checkbox";e=this.data.exportValue}else if(this.data.radioButton){t="radiobutton";e=this.data.buttonValue}return{id:this.data.id,value:this.data.fieldValue||"Off",defaultValue:this.data.defaultFieldValue,exportValues:e,editable:!this.data.readOnly,name:this.data.fieldName,rect:this.data.rect,hidden:this.data.hidden,actions:this.data.actions,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,type:t}}get fallbackFontDict(){const e=new Dict;e.set("BaseFont",Name.get("ZapfDingbats"));e.set("Type",Name.get("FallbackType"));e.set("Subtype",Name.get("FallbackType"));e.set("Encoding",Name.get("ZapfDingbatsEncoding"));return shadow(this,"fallbackFontDict",e)}}class ChoiceWidgetAnnotation extends WidgetAnnotation{constructor(e){super(e);const{dict:t,xref:i}=e;this.indices=t.getArray("I");this.hasIndices=Array.isArray(this.indices)&&this.indices.length>0;this.data.options=[];const a=getInheritableProperty({dict:t,key:"Opt"});if(Array.isArray(a))for(let e=0,t=a.length;e=0&&t0&&(this.data.options=this.data.fieldValue.map((e=>({exportValue:e,displayValue:e}))));this.data.combo=this.hasFieldFlag(oA);this.data.multiSelect=this.hasFieldFlag(cA);this._hasText=!0}getFieldObject(){const e=this.data.combo?"combobox":"listbox",t=this.data.fieldValue.length>0?this.data.fieldValue[0]:null;return{id:this.data.id,value:t,defaultValue:this.data.defaultFieldValue,editable:!this.data.readOnly,name:this.data.fieldName,rect:this.data.rect,numItems:this.data.fieldValue.length,multipleSelection:this.data.multiSelect,hidden:this.data.hidden,actions:this.data.actions,items:this.data.options,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,type:e}}amendSavedDict(e,t){if(!this.hasIndices)return;let i=e?.get(this.data.id)?.value;Array.isArray(i)||(i=[i]);const a=[],{options:s}=this.data;for(let e=0,t=0,r=s.length;ei){i=a;t=e}}[Q,E]=this._computeFontSize(e,c-4,t,l,-1)}const u=E*s,d=(u-E)/2,f=Math.floor(o/u);let p=0;if(h.length>0){const e=Math.min(...h),t=Math.max(...h);p=Math.max(0,t-f+1);p>e&&(p=e)}const m=Math.min(p+f+1,C),y=["/Tx BMC q",`1 1 ${c} ${o} re W n`];if(h.length){y.push("0.600006 0.756866 0.854904 rg");for(const e of h)p<=e&&ee.trimEnd()));const{coords:e,bbox:t,matrix:i}=FakeUnicodeFont.getFirstPositionInfo(this.rectangle,this.rotation,a);this.data.textPosition=this._transformPoint(e,t,i)}if(this._isOffscreenCanvasSupported){const s=e.dict.get("CA"),r=new FakeUnicodeFont(i,"sans-serif");this.appearance=r.createAppearance(this._contents.str,this.rectangle,this.rotation,a,t,s);this._streams.push(this.appearance)}else warn("FreeTextAnnotation: OffscreenCanvas is not supported, annotation may not render correctly.")}}get hasTextContent(){return this._hasAppearance}static createNewDict(e,t,{apRef:i,ap:a}){const{color:s,fontSize:r,oldAnnotation:n,rect:g,rotation:o,user:c,value:C}=e,h=n||new Dict(t);h.set("Type",Name.get("Annot"));h.set("Subtype",Name.get("FreeText"));if(n){h.set("M",`D:${getModificationDate()}`);h.delete("RC")}else h.set("CreationDate",`D:${getModificationDate()}`);h.set("Rect",g);const l=`/Helv ${r} Tf ${getPdfColor(s,!0)}`;h.set("DA",l);h.set("Contents",stringToAsciiOrUTF16BE(C));h.set("F",4);h.set("Border",[0,0,0]);h.set("Rotate",o);c&&h.set("T",stringToAsciiOrUTF16BE(c));if(i||a){const e=new Dict(t);h.set("AP",e);i?e.set("N",i):e.set("N",a)}return h}static async createNewAppearanceStream(e,t,i){const{baseFontRef:a,evaluator:r,task:n}=i,{color:g,fontSize:o,rect:c,rotation:C,value:h}=e,l=new Dict(t),Q=new Dict(t);if(a)Q.set("Helv",a);else{const e=new Dict(t);e.set("BaseFont",Name.get("Helvetica"));e.set("Type",Name.get("Font"));e.set("Subtype",Name.get("Type1"));e.set("Encoding",Name.get("WinAnsiEncoding"));Q.set("Helv",e)}l.set("Font",Q);const E=await WidgetAnnotation._getFontData(r,n,{fontName:"Helv",fontSize:o},l),[u,d,f,p]=c;let m=f-u,y=p-d;C%180!=0&&([m,y]=[y,m]);const w=h.split("\n"),D=o/1e3;let b=-1/0;const F=[];for(let e of w){const t=E.encodeString(e);if(t.length>1)return null;e=t.join("");F.push(e);let i=0;const a=E.charsToGlyphs(e);for(const e of a)i+=e.width*D;b=Math.max(b,i)}let S=1;b>m&&(S=m/b);let k=1;const R=s*o,N=1*o,G=R*w.length;G>y&&(k=y/G);const M=o*Math.min(S,k);let U,x,L;switch(C){case 0:L=[1,0,0,1];x=[c[0],c[1],m,y];U=[c[0],c[3]-N];break;case 90:L=[0,1,-1,0];x=[c[1],-c[2],m,y];U=[c[1],-c[0]-N];break;case 180:L=[-1,0,0,-1];x=[-c[2],-c[3],m,y];U=[-c[2],-c[1]-N];break;case 270:L=[0,-1,1,0];x=[-c[3],c[0],m,y];U=[-c[3],c[2]-N]}const H=["q",`${L.join(" ")} 0 0 cm`,`${x.join(" ")} re W n`,"BT",`${getPdfColor(g,!0)}`,`0 Tc /Helv ${numberToString(M)} Tf`];H.push(`${U.join(" ")} Td (${escapeString(F[0])}) Tj`);const J=numberToString(R);for(let e=1,t=F.length;e{e.push(`${a[0]} ${a[1]} m`,`${a[2]} ${a[3]} l`,"S");return[t[0]-o,t[2]+o,t[7]-o,t[3]+o]}})}}}class SquareAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:i}=e;this.data.annotationType=M;this.data.hasOwnCanvas=this.data.noRotate;this.data.noHTML=!1;if(!this.appearance){const e=this.color?getPdfColorArray(this.color):[0,0,0],a=t.get("CA"),s=getRgbColor(t.getArray("IC"),null),r=s?getPdfColorArray(s):null,n=r?a:null;if(0===this.borderStyle.width&&!r)return;this._setDefaultAppearance({xref:i,extra:`${this.borderStyle.width} w`,strokeColor:e,fillColor:r,strokeAlpha:a,fillAlpha:n,pointsCallback:(e,t)=>{const i=t[4]+this.borderStyle.width/2,a=t[5]+this.borderStyle.width/2,s=t[6]-t[4]-this.borderStyle.width,n=t[3]-t[7]-this.borderStyle.width;e.push(`${i} ${a} ${s} ${n} re`);r?e.push("B"):e.push("S");return[t[0],t[2],t[7],t[3]]}})}}}class CircleAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:i}=e;this.data.annotationType=U;if(!this.appearance){const e=this.color?getPdfColorArray(this.color):[0,0,0],a=t.get("CA"),s=getRgbColor(t.getArray("IC"),null),r=s?getPdfColorArray(s):null,n=r?a:null;if(0===this.borderStyle.width&&!r)return;const g=4/3*Math.tan(Math.PI/8);this._setDefaultAppearance({xref:i,extra:`${this.borderStyle.width} w`,strokeColor:e,fillColor:r,strokeAlpha:a,fillAlpha:n,pointsCallback:(e,t)=>{const i=t[0]+this.borderStyle.width/2,a=t[1]-this.borderStyle.width/2,s=t[6]-this.borderStyle.width/2,n=t[7]+this.borderStyle.width/2,o=i+(s-i)/2,c=a+(n-a)/2,C=(s-i)/2*g,h=(n-a)/2*g;e.push(`${o} ${n} m`,`${o+C} ${n} ${s} ${c+h} ${s} ${c} c`,`${s} ${c-h} ${o+C} ${a} ${o} ${a} c`,`${o-C} ${a} ${i} ${c-h} ${i} ${c} c`,`${i} ${c+h} ${o-C} ${n} ${o} ${n} c`,"h");r?e.push("B"):e.push("S");return[t[0],t[2],t[7],t[3]]}})}}}class PolylineAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:i}=e;this.data.annotationType=L;this.data.hasOwnCanvas=this.data.noRotate;this.data.noHTML=!1;this.data.vertices=null;if(!(this instanceof PolygonAnnotation)){this.setLineEndings(t.getArray("LE"));this.data.lineEndings=this.lineEndings}const a=t.getArray("Vertices");if(!isNumberArray(a,null))return;const s=this.data.vertices=Float32Array.from(a);if(!this.appearance){const e=this.color?getPdfColorArray(this.color):[0,0,0],a=t.get("CA"),r=this.borderStyle.width||1,n=2*r,g=[1/0,1/0,-1/0,-1/0];for(let e=0,t=s.length;e{for(let t=0,i=s.length;t{for(const t of this.data.inkLists){for(let i=0,a=t.length;ie/255)));Q.set("CA",n);const u=new Dict(t);Q.set("AP",u);i?u.set("N",i):u.set("N",a);return Q}static async createNewAppearanceStream(e,t,i){if(e.outlines)return this.createNewAppearanceStreamForHighlight(e,t,i);const{color:a,rect:s,paths:r,thickness:n,opacity:g}=e,o=[`${n} w 1 J 1 j`,`${getPdfColor(a,!1)}`];1!==g&&o.push("/R0 gs");for(const e of r.lines){o.push(`${numberToString(e[4])} ${numberToString(e[5])} m`);for(let t=6,i=e.length;t{e.push(`${t[0]} ${t[1]} m`,`${t[2]} ${t[3]} l`,`${t[6]} ${t[7]} l`,`${t[4]} ${t[5]} l`,"f");return[t[0],t[2],t[7],t[3]]}})}}else this.data.popupRef=null}static createNewDict(e,t,{apRef:i,ap:a}){const{color:s,oldAnnotation:r,opacity:n,rect:g,rotation:o,user:c,quadPoints:C}=e,h=r||new Dict(t);h.set("Type",Name.get("Annot"));h.set("Subtype",Name.get("Highlight"));h.set(r?"M":"CreationDate",`D:${getModificationDate()}`);h.set("CreationDate",`D:${getModificationDate()}`);h.set("Rect",g);h.set("F",4);h.set("Border",[0,0,0]);h.set("Rotate",o);h.set("QuadPoints",C);h.set("C",Array.from(s,(e=>e/255)));h.set("CA",n);c&&h.set("T",stringToAsciiOrUTF16BE(c));if(i||a){const e=new Dict(t);h.set("AP",e);e.set("N",i||a)}return h}static async createNewAppearanceStream(e,t,i){const{color:a,rect:s,outlines:r,opacity:n}=e,g=[`${getPdfColor(a,!0)}`,"/R0 gs"],o=[];for(const e of r){o.length=0;o.push(`${numberToString(e[0])} ${numberToString(e[1])} m`);for(let t=2,i=e.length;t{e.push(`${t[4]} ${t[5]+1.3} m`,`${t[6]} ${t[7]+1.3} l`,"S");return[t[0],t[2],t[7],t[3]]}})}}else this.data.popupRef=null}}class SquigglyAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:i}=e;this.data.annotationType=Y;if(this.data.quadPoints=getQuadPoints(t,null)){if(!this.appearance){const e=this.color?getPdfColorArray(this.color):[0,0,0],a=t.get("CA");this._setDefaultAppearance({xref:i,extra:"[] 0 d 1 w",strokeColor:e,strokeAlpha:a,pointsCallback:(e,t)=>{const i=(t[1]-t[5])/6;let a=i,s=t[4];const r=t[5],n=t[6];e.push(`${s} ${r+a} m`);do{s+=2;a=0===a?i:0;e.push(`${s} ${r+a} l`)}while(s{e.push((t[0]+t[4])/2+" "+(t[1]+t[5])/2+" m",(t[2]+t[6])/2+" "+(t[3]+t[7])/2+" l","S");return[t[0],t[2],t[7],t[3]]}})}}else this.data.popupRef=null}}class StampAnnotation extends MarkupAnnotation{#T;constructor(e){super(e);this.data.annotationType=K;this.#T=this.data.hasOwnCanvas=this.data.noRotate;this.data.isEditable=!this.data.noHTML;this.data.noHTML=!1}mustBeViewedWhenEditing(e,t=null){if(e){if(!this.data.isEditable)return!1;this.#T=this.data.hasOwnCanvas;this.data.hasOwnCanvas=!0;return!0}this.data.hasOwnCanvas=this.#T;return!t?.has(this.data.id)}static async createImage(e,t){const{width:i,height:a}=e,s=new OffscreenCanvas(i,a),r=s.getContext("2d",{alpha:!0});r.drawImage(e,0,0);const n=r.getImageData(0,0,i,a).data,g=new Uint32Array(n.buffer),o=g.some(FeatureTest.isLittleEndian?e=>e>>>24!=255:e=>!!(255&~e));if(o){r.fillStyle="white";r.fillRect(0,0,i,a);r.drawImage(e,0,0)}const c=s.convertToBlob({type:"image/jpeg",quality:1}).then((e=>e.arrayBuffer())),C=Name.get("XObject"),h=Name.get("Image"),l=new Dict(t);l.set("Type",C);l.set("Subtype",h);l.set("BitsPerComponent",8);l.set("ColorSpace",Name.get("DeviceRGB"));l.set("Filter",Name.get("DCTDecode"));l.set("BBox",[0,0,i,a]);l.set("Width",i);l.set("Height",a);let Q=null;if(o){const e=new Uint8Array(g.length);if(FeatureTest.isLittleEndian)for(let t=0,i=g.length;t>>24;else for(let t=0,i=g.length;t=0&&r<=1?r:null}}class DecryptStream extends DecodeStream{constructor(e,t,i){super(t);this.str=e;this.dict=e.dict;this.decrypt=i;this.nextChunk=null;this.initialized=!1}readBlock(){let e;if(this.initialized)e=this.nextChunk;else{e=this.str.getBytes(512);this.initialized=!0}if(!e?.length){this.eof=!0;return}this.nextChunk=this.str.getBytes(512);const t=this.nextChunk?.length>0;e=(0,this.decrypt)(e,!t);const i=this.bufferLength,a=i+e.length;this.ensureBuffer(a).set(e,i);this.bufferLength=a}}class ARCFourCipher{constructor(e){this.a=0;this.b=0;const t=new Uint8Array(256),i=e.length;for(let e=0;e<256;++e)t[e]=e;for(let a=0,s=0;a<256;++a){const r=t[a];s=s+r+e[a%i]&255;t[a]=t[s];t[s]=r}this.s=t}encryptBlock(e){let t=this.a,i=this.b;const a=this.s,s=e.length,r=new Uint8Array(s);for(let n=0;n>5&255;C[h++]=s>>13&255;C[h++]=s>>21&255;C[h++]=s>>>29&255;C[h++]=0;C[h++]=0;C[h++]=0;const E=new Int32Array(16);for(h=0;h>>32-g)|0;s=r}r=r+s|0;n=n+c|0;g=g+Q|0;o=o+u|0}return new Uint8Array([255&r,r>>8&255,r>>16&255,r>>>24&255,255&n,n>>8&255,n>>16&255,n>>>24&255,255&g,g>>8&255,g>>16&255,g>>>24&255,255&o,o>>8&255,o>>16&255,o>>>24&255])}}();class Word64{constructor(e,t){this.high=0|e;this.low=0|t}and(e){this.high&=e.high;this.low&=e.low}xor(e){this.high^=e.high;this.low^=e.low}or(e){this.high|=e.high;this.low|=e.low}shiftRight(e){if(e>=32){this.low=this.high>>>e-32|0;this.high=0}else{this.low=this.low>>>e|this.high<<32-e;this.high=this.high>>>e|0}}shiftLeft(e){if(e>=32){this.high=this.low<>>32-e;this.low<<=e}}rotateRight(e){let t,i;if(32&e){i=this.low;t=this.high}else{t=this.low;i=this.high}e&=31;this.low=t>>>e|i<<32-e;this.high=i>>>e|t<<32-e}not(){this.high=~this.high;this.low=~this.low}add(e){const t=(this.low>>>0)+(e.low>>>0);let i=(this.high>>>0)+(e.high>>>0);t>4294967295&&(i+=1);this.low=0|t;this.high=0|i}copyTo(e,t){e[t]=this.high>>>24&255;e[t+1]=this.high>>16&255;e[t+2]=this.high>>8&255;e[t+3]=255&this.high;e[t+4]=this.low>>>24&255;e[t+5]=this.low>>16&255;e[t+6]=this.low>>8&255;e[t+7]=255&this.low}assign(e){this.high=e.high;this.low=e.low}}const Ag=function calculateSHA256Closure(){function rotr(e,t){return e>>>t|e<<32-t}function ch(e,t,i){return e&t^~e&i}function maj(e,t,i){return e&t^e&i^t&i}function sigma(e){return rotr(e,2)^rotr(e,13)^rotr(e,22)}function sigmaPrime(e){return rotr(e,6)^rotr(e,11)^rotr(e,25)}function littleSigma(e){return rotr(e,7)^rotr(e,18)^e>>>3}const e=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];return function hash(t,i,a){let s=1779033703,r=3144134277,n=1013904242,g=2773480762,o=1359893119,c=2600822924,C=528734635,h=1541459225;const l=64*Math.ceil((a+9)/64),Q=new Uint8Array(l);let E,u;for(E=0;E>>29&255;Q[E++]=a>>21&255;Q[E++]=a>>13&255;Q[E++]=a>>5&255;Q[E++]=a<<3&255;const f=new Uint32Array(64);for(E=0;E>>10)+f[u-7]+littleSigma(f[u-15])+f[u-16]|0;let t,i,a=s,l=r,d=n,m=g,y=o,w=c,D=C,b=h;for(u=0;u<64;++u){t=b+sigmaPrime(y)+ch(y,w,D)+e[u]+f[u];i=sigma(a)+maj(a,l,d);b=D;D=w;w=y;y=m+t|0;m=d;d=l;l=a;a=t+i|0}s=s+a|0;r=r+l|0;n=n+d|0;g=g+m|0;o=o+y|0;c=c+w|0;C=C+D|0;h=h+b|0}var p;return new Uint8Array([s>>24&255,s>>16&255,s>>8&255,255&s,r>>24&255,r>>16&255,r>>8&255,255&r,n>>24&255,n>>16&255,n>>8&255,255&n,g>>24&255,g>>16&255,g>>8&255,255&g,o>>24&255,o>>16&255,o>>8&255,255&o,c>>24&255,c>>16&255,c>>8&255,255&c,C>>24&255,C>>16&255,C>>8&255,255&C,h>>24&255,h>>16&255,h>>8&255,255&h])}}(),eg=function calculateSHA512Closure(){function ch(e,t,i,a,s){e.assign(t);e.and(i);s.assign(t);s.not();s.and(a);e.xor(s)}function maj(e,t,i,a,s){e.assign(t);e.and(i);s.assign(t);s.and(a);e.xor(s);s.assign(i);s.and(a);e.xor(s)}function sigma(e,t,i){e.assign(t);e.rotateRight(28);i.assign(t);i.rotateRight(34);e.xor(i);i.assign(t);i.rotateRight(39);e.xor(i)}function sigmaPrime(e,t,i){e.assign(t);e.rotateRight(14);i.assign(t);i.rotateRight(18);e.xor(i);i.assign(t);i.rotateRight(41);e.xor(i)}function littleSigma(e,t,i){e.assign(t);e.rotateRight(1);i.assign(t);i.rotateRight(8);e.xor(i);i.assign(t);i.shiftRight(7);e.xor(i)}function littleSigmaPrime(e,t,i){e.assign(t);e.rotateRight(19);i.assign(t);i.rotateRight(61);e.xor(i);i.assign(t);i.shiftRight(6);e.xor(i)}const e=[new Word64(1116352408,3609767458),new Word64(1899447441,602891725),new Word64(3049323471,3964484399),new Word64(3921009573,2173295548),new Word64(961987163,4081628472),new Word64(1508970993,3053834265),new Word64(2453635748,2937671579),new Word64(2870763221,3664609560),new Word64(3624381080,2734883394),new Word64(310598401,1164996542),new Word64(607225278,1323610764),new Word64(1426881987,3590304994),new Word64(1925078388,4068182383),new Word64(2162078206,991336113),new Word64(2614888103,633803317),new Word64(3248222580,3479774868),new Word64(3835390401,2666613458),new Word64(4022224774,944711139),new Word64(264347078,2341262773),new Word64(604807628,2007800933),new Word64(770255983,1495990901),new Word64(1249150122,1856431235),new Word64(1555081692,3175218132),new Word64(1996064986,2198950837),new Word64(2554220882,3999719339),new Word64(2821834349,766784016),new Word64(2952996808,2566594879),new Word64(3210313671,3203337956),new Word64(3336571891,1034457026),new Word64(3584528711,2466948901),new Word64(113926993,3758326383),new Word64(338241895,168717936),new Word64(666307205,1188179964),new Word64(773529912,1546045734),new Word64(1294757372,1522805485),new Word64(1396182291,2643833823),new Word64(1695183700,2343527390),new Word64(1986661051,1014477480),new Word64(2177026350,1206759142),new Word64(2456956037,344077627),new Word64(2730485921,1290863460),new Word64(2820302411,3158454273),new Word64(3259730800,3505952657),new Word64(3345764771,106217008),new Word64(3516065817,3606008344),new Word64(3600352804,1432725776),new Word64(4094571909,1467031594),new Word64(275423344,851169720),new Word64(430227734,3100823752),new Word64(506948616,1363258195),new Word64(659060556,3750685593),new Word64(883997877,3785050280),new Word64(958139571,3318307427),new Word64(1322822218,3812723403),new Word64(1537002063,2003034995),new Word64(1747873779,3602036899),new Word64(1955562222,1575990012),new Word64(2024104815,1125592928),new Word64(2227730452,2716904306),new Word64(2361852424,442776044),new Word64(2428436474,593698344),new Word64(2756734187,3733110249),new Word64(3204031479,2999351573),new Word64(3329325298,3815920427),new Word64(3391569614,3928383900),new Word64(3515267271,566280711),new Word64(3940187606,3454069534),new Word64(4118630271,4000239992),new Word64(116418474,1914138554),new Word64(174292421,2731055270),new Word64(289380356,3203993006),new Word64(460393269,320620315),new Word64(685471733,587496836),new Word64(852142971,1086792851),new Word64(1017036298,365543100),new Word64(1126000580,2618297676),new Word64(1288033470,3409855158),new Word64(1501505948,4234509866),new Word64(1607167915,987167468),new Word64(1816402316,1246189591)];return function hash(t,i,a,s=!1){let r,n,g,o,c,C,h,l;if(s){r=new Word64(3418070365,3238371032);n=new Word64(1654270250,914150663);g=new Word64(2438529370,812702999);o=new Word64(355462360,4144912697);c=new Word64(1731405415,4290775857);C=new Word64(2394180231,1750603025);h=new Word64(3675008525,1694076839);l=new Word64(1203062813,3204075428)}else{r=new Word64(1779033703,4089235720);n=new Word64(3144134277,2227873595);g=new Word64(1013904242,4271175723);o=new Word64(2773480762,1595750129);c=new Word64(1359893119,2917565137);C=new Word64(2600822924,725511199);h=new Word64(528734635,4215389547);l=new Word64(1541459225,327033209)}const Q=128*Math.ceil((a+17)/128),E=new Uint8Array(Q);let u,d;for(u=0;u>>29&255;E[u++]=a>>21&255;E[u++]=a>>13&255;E[u++]=a>>5&255;E[u++]=a<<3&255;const p=new Array(80);for(u=0;u<80;u++)p[u]=new Word64(0,0);let m=new Word64(0,0),y=new Word64(0,0),w=new Word64(0,0),D=new Word64(0,0),b=new Word64(0,0),F=new Word64(0,0),S=new Word64(0,0),k=new Word64(0,0);const R=new Word64(0,0),N=new Word64(0,0),G=new Word64(0,0),M=new Word64(0,0);let U,x;for(u=0;u=1;--e){i=r[13];r[13]=r[9];r[9]=r[5];r[5]=r[1];r[1]=i;i=r[14];a=r[10];r[14]=r[6];r[10]=r[2];r[6]=i;r[2]=a;i=r[15];a=r[11];s=r[7];r[15]=r[3];r[11]=i;r[7]=a;r[3]=s;for(let e=0;e<16;++e)r[e]=this._inv_s[r[e]];for(let i=0,a=16*e;i<16;++i,++a)r[i]^=t[a];for(let e=0;e<16;e+=4){const t=this._mix[r[e]],a=this._mix[r[e+1]],s=this._mix[r[e+2]],n=this._mix[r[e+3]];i=t^a>>>8^a<<24^s>>>16^s<<16^n>>>24^n<<8;r[e]=i>>>24&255;r[e+1]=i>>16&255;r[e+2]=i>>8&255;r[e+3]=255&i}}i=r[13];r[13]=r[9];r[9]=r[5];r[5]=r[1];r[1]=i;i=r[14];a=r[10];r[14]=r[6];r[10]=r[2];r[6]=i;r[2]=a;i=r[15];a=r[11];s=r[7];r[15]=r[3];r[11]=i;r[7]=a;r[3]=s;for(let e=0;e<16;++e){r[e]=this._inv_s[r[e]];r[e]^=t[e]}return r}_encrypt(e,t){const i=this._s;let a,s,r;const n=new Uint8Array(16);n.set(e);for(let e=0;e<16;++e)n[e]^=t[e];for(let e=1;e=a;--i)if(e[i]!==t){t=0;break}g-=t;r[r.length-1]=e.subarray(0,16-t)}}const o=new Uint8Array(g);for(let e=0,t=0,i=r.length;e=256&&(g=255&(27^g))}for(let t=0;t<4;++t){i[e]=a^=i[e-32];e++;i[e]=s^=i[e-32];e++;i[e]=r^=i[e-32];e++;i[e]=n^=i[e-32];e++}}return i}}class PDF17{checkOwnerPassword(e,t,i,a){const s=new Uint8Array(e.length+56);s.set(e,0);s.set(t,e.length);s.set(i,e.length+t.length);return isArrayEqual(Ag(s,0,s.length),a)}checkUserPassword(e,t,i){const a=new Uint8Array(e.length+8);a.set(e,0);a.set(t,e.length);return isArrayEqual(Ag(a,0,a.length),i)}getOwnerKey(e,t,i,a){const s=new Uint8Array(e.length+56);s.set(e,0);s.set(t,e.length);s.set(i,e.length+t.length);const r=Ag(s,0,s.length);return new AES256Cipher(r).decryptBlock(a,!1,new Uint8Array(16))}getUserKey(e,t,i){const a=new Uint8Array(e.length+8);a.set(e,0);a.set(t,e.length);const s=Ag(a,0,a.length);return new AES256Cipher(s).decryptBlock(i,!1,new Uint8Array(16))}}class PDF20{_hash(e,t,i){let a=Ag(t,0,t.length).subarray(0,32),s=[0],r=0;for(;r<64||s.at(-1)>r-32;){const t=e.length+a.length+i.length,c=new Uint8Array(t);let C=0;c.set(e,C);C+=e.length;c.set(a,C);C+=a.length;c.set(i,C);const h=new Uint8Array(64*t);for(let e=0,i=0;e<64;e++,i+=t)h.set(c,i);s=new AES128Cipher(a.subarray(0,16)).encrypt(h,a.subarray(16,32));const l=s.slice(0,16).reduce(((e,t)=>e+t),0)%3;0===l?a=Ag(s,0,s.length):1===l?a=(n=s,g=0,o=s.length,eg(n,g,o,!0)):2===l&&(a=eg(s,0,s.length));r++}var n,g,o;return a.subarray(0,32)}checkOwnerPassword(e,t,i,a){const s=new Uint8Array(e.length+56);s.set(e,0);s.set(t,e.length);s.set(i,e.length+t.length);return isArrayEqual(this._hash(e,s,i),a)}checkUserPassword(e,t,i){const a=new Uint8Array(e.length+8);a.set(e,0);a.set(t,e.length);return isArrayEqual(this._hash(e,a,[]),i)}getOwnerKey(e,t,i,a){const s=new Uint8Array(e.length+56);s.set(e,0);s.set(t,e.length);s.set(i,e.length+t.length);const r=this._hash(e,s,i);return new AES256Cipher(r).decryptBlock(a,!1,new Uint8Array(16))}getUserKey(e,t,i){const a=new Uint8Array(e.length+8);a.set(e,0);a.set(t,e.length);const s=this._hash(e,a,[]);return new AES256Cipher(s).decryptBlock(i,!1,new Uint8Array(16))}}class CipherTransform{constructor(e,t){this.StringCipherConstructor=e;this.StreamCipherConstructor=t}createStream(e,t){const i=new this.StreamCipherConstructor;return new DecryptStream(e,t,(function cipherTransformDecryptStream(e,t){return i.decryptBlock(e,t)}))}decryptString(e){const t=new this.StringCipherConstructor;let i=stringToBytes(e);i=t.decryptBlock(i,!0);return bytesToString(i)}encryptString(e){const t=new this.StringCipherConstructor;if(t instanceof AESBaseCipher){const i=16-e.length%16;e+=String.fromCharCode(i).repeat(i);const a=new Uint8Array(16);if("undefined"!=typeof crypto)crypto.getRandomValues(a);else for(let e=0;e<16;e++)a[e]=Math.floor(256*Math.random());let s=stringToBytes(e);s=t.encrypt(s,a);const r=new Uint8Array(16+s.length);r.set(a);r.set(s,16);return bytesToString(r)}let i=stringToBytes(e);i=t.encrypt(i);return bytesToString(i)}}class CipherTransformFactory{static#q=new Uint8Array([40,191,78,94,78,117,138,65,100,0,78,86,255,250,1,8,46,46,0,182,208,104,62,128,47,12,169,254,100,83,105,122]);#O(e,t,i,a,s,r,n,g,o,c,C,h){if(t){const e=Math.min(127,t.length);t=t.subarray(0,e)}else t=[];const l=6===e?new PDF20:new PDF17;return l.checkUserPassword(t,g,n)?l.getUserKey(t,o,C):t.length&&l.checkOwnerPassword(t,a,r,i)?l.getOwnerKey(t,s,r,c):null}#P(e,t,i,a,s,r,n,g){const o=40+i.length+e.length,c=new Uint8Array(o);let C,h,l=0;if(t){h=Math.min(32,t.length);for(;l>8&255;c[l++]=s>>16&255;c[l++]=s>>>24&255;for(C=0,h=e.length;C=4&&!g){c[l++]=255;c[l++]=255;c[l++]=255;c[l++]=255}let Q=$n(c,0,l);const E=n>>3;if(r>=3)for(C=0;C<50;++C)Q=$n(Q,0,E);const u=Q.subarray(0,E);let d,f;if(r>=3){for(l=0;l<32;++l)c[l]=CipherTransformFactory.#q[l];for(C=0,h=e.length;C>3;if(i>=3)for(g=0;g<50;++g)o=$n(o,0,o.length);let C,h;if(i>=3){h=t;const e=new Uint8Array(c);for(g=19;g>=0;g--){for(let t=0;t>8&255;s[n++]=e>>16&255;s[n++]=255&t;s[n++]=t>>8&255;if(a){s[n++]=115;s[n++]=65;s[n++]=108;s[n++]=84}return $n(s,0,n).subarray(0,Math.min(i.length+5,16))}#X(e,t,i,a,s){if(!(t instanceof Name))throw new FormatError("Invalid crypt filter name.");const r=this,n=e.get(t.name),g=n?.get("CFM");if(!g||"None"===g.name)return function(){return new NullCipher};if("V2"===g.name)return function(){return new ARCFourCipher(r.#j(i,a,s,!1))};if("AESV2"===g.name)return function(){return new AES128Cipher(r.#j(i,a,s,!0))};if("AESV3"===g.name)return function(){return new AES256Cipher(s)};throw new FormatError("Unknown crypto method")}constructor(e,t,i){const a=e.get("Filter");if(!isName(a,"Standard"))throw new FormatError("unknown encryption method");this.filterName=a.name;this.dict=e;const s=e.get("V");if(!Number.isInteger(s)||1!==s&&2!==s&&4!==s&&5!==s)throw new FormatError("unsupported encryption algorithm");this.algorithm=s;let r=e.get("Length");if(!r)if(s<=3)r=40;else{const t=e.get("CF"),i=e.get("StmF");if(t instanceof Dict&&i instanceof Name){t.suppressEncryption=!0;const e=t.get(i.name);r=e?.get("Length")||128;r<40&&(r<<=3)}}if(!Number.isInteger(r)||r<40||r%8!=0)throw new FormatError("invalid key length");const n=stringToBytes(e.get("O")),g=stringToBytes(e.get("U")),o=n.subarray(0,32),c=g.subarray(0,32),C=e.get("P"),h=e.get("R"),l=(4===s||5===s)&&!1!==e.get("EncryptMetadata");this.encryptMetadata=l;const Q=stringToBytes(t);let E,u;if(i){if(6===h)try{i=utf8StringToString(i)}catch{warn("CipherTransformFactory: Unable to convert UTF8 encoded password.")}E=stringToBytes(i)}if(5!==s)u=this.#P(Q,E,o,c,C,h,r,l);else{const t=n.subarray(32,40),i=n.subarray(40,48),a=g.subarray(0,48),s=g.subarray(32,40),r=g.subarray(40,48),C=stringToBytes(e.get("OE")),l=stringToBytes(e.get("UE")),Q=stringToBytes(e.get("Perms"));u=this.#O(h,E,o,t,i,a,c,s,r,C,l,Q)}if(!u&&!i)throw new PasswordException("No password given",rt);if(!u&&i){const e=this.#W(E,o,h,r);u=this.#P(Q,e,o,c,C,h,r,l)}if(!u)throw new PasswordException("Incorrect Password",nt);this.encryptionKey=u;if(s>=4){const t=e.get("CF");t instanceof Dict&&(t.suppressEncryption=!0);this.cf=t;this.stmf=e.get("StmF")||Name.get("Identity");this.strf=e.get("StrF")||Name.get("Identity");this.eff=e.get("EFF")||this.stmf}}createCipherTransform(e,t){if(4===this.algorithm||5===this.algorithm)return new CipherTransform(this.#X(this.cf,this.strf,e,t,this.encryptionKey),this.#X(this.cf,this.stmf,e,t,this.encryptionKey));const i=this.#j(e,t,this.encryptionKey,!1),cipherConstructor=function(){return new ARCFourCipher(i)};return new CipherTransform(cipherConstructor,cipherConstructor)}}function decodeString(e){try{return stringToUTF8String(e)}catch(t){warn(`UTF-8 decoding failed: "${t}".`);return e}}class DatasetXMLParser extends SimpleXMLParser{constructor(e){super(e);this.node=null}onEndElement(e){const t=super.onEndElement(e);if(t&&"xfa:datasets"===e){this.node=t;throw new Error("Aborting DatasetXMLParser.")}}}class DatasetReader{constructor(e){if(e.datasets)this.node=new SimpleXMLParser({hasAttributes:!0}).parseFromString(e.datasets).documentElement;else{const t=new DatasetXMLParser({hasAttributes:!0});try{t.parseFromString(e["xdp:xdp"])}catch{}this.node=t.node}}getValue(e){if(!this.node||!e)return"";const t=this.node.searchNode(parseXFAPath(e),0);if(!t)return"";const i=t.firstChild;return"value"===i?.nodeName?t.children.map((e=>decodeString(e.textContent))):decodeString(t.textContent)}}class XRef{#Z=null;constructor(e,t){this.stream=e;this.pdfManager=t;this.entries=[];this._xrefStms=new Set;this._cacheMap=new Map;this._pendingRefs=new RefSet;this._newPersistentRefNum=null;this._newTemporaryRefNum=null;this._persistentRefsCache=null}getNewPersistentRef(e){null===this._newPersistentRefNum&&(this._newPersistentRefNum=this.entries.length||1);const t=this._newPersistentRefNum++;this._cacheMap.set(t,e);return Ref.get(t,0)}getNewTemporaryRef(){if(null===this._newTemporaryRefNum){this._newTemporaryRefNum=this.entries.length||1;if(this._newPersistentRefNum){this._persistentRefsCache=new Map;for(let e=this._newTemporaryRefNum;e0;){const[n,g]=r;if(!Number.isInteger(n)||!Number.isInteger(g))throw new FormatError(`Invalid XRef range fields: ${n}, ${g}`);if(!Number.isInteger(i)||!Number.isInteger(a)||!Number.isInteger(s))throw new FormatError(`Invalid XRef entry fields length: ${n}, ${g}`);for(let r=t.entryNum;r=e.length);){i+=String.fromCharCode(a);a=e[t]}return i}function skipUntil(e,t,i){const a=i.length,s=e.length;let r=0;for(;t=a)break;t++;r++}return r}const e=/\b(endobj|\d+\s+\d+\s+obj|xref|trailer\s*<<)\b/g,t=/\b(startxref|\d+\s+\d+\s+obj)\b/g,i=/^(\d+)\s+(\d+)\s+obj\b/,a=new Uint8Array([116,114,97,105,108,101,114]),s=new Uint8Array([115,116,97,114,116,120,114,101,102]),r=new Uint8Array([47,88,82,101,102]);this.entries.length=0;this._cacheMap.clear();const n=this.stream;n.pos=0;const g=n.getBytes(),o=bytesToString(g),c=g.length;let C=n.start;const h=[],l=[];for(;C=c)break;Q=g[C]}while(10!==Q&&13!==Q);continue}const E=readToken(g,C);let u;if(E.startsWith("xref")&&(4===E.length||/\s/.test(E[4]))){C+=skipUntil(g,C,a);h.push(C);C+=skipUntil(g,C,s)}else if(u=i.exec(E)){const t=0|u[1],i=0|u[2],a=C+E.length;let s,h=!1;if(this.entries[t]){if(this.entries[t].gen===i)try{new Parser({lexer:new Lexer(n.makeSubStream(a))}).getObj();h=!0}catch(e){e instanceof ParserEOFException?warn(`indexObjects -- checking object (${E}): "${e}".`):h=!0}}else h=!0;h&&(this.entries[t]={offset:C-n.start,gen:i,uncompressed:!0});e.lastIndex=a;const Q=e.exec(o);if(Q){s=e.lastIndex+1-C;if("endobj"!==Q[1]){warn(`indexObjects: Found "${Q[1]}" inside of another "obj", caused by missing "endobj" -- trying to recover.`);s-=Q[1].length+1}}else s=c-C;const d=g.subarray(C,C+s),f=skipUntil(d,0,r);if(f0?Math.max(...this._xrefStms):null)}getEntry(e){const t=this.entries[e];return t&&!t.free&&t.offset?t:null}fetchIfRef(e,t=!1){return e instanceof Ref?this.fetch(e,t):e}fetch(e,t=!1){if(!(e instanceof Ref))throw new Error("ref object is not a reference");const i=e.num,a=this._cacheMap.get(i);if(void 0!==a){a instanceof Dict&&!a.objId&&(a.objId=e.toString());return a}let s=this.getEntry(i);if(null===s){this._cacheMap.set(i,s);return s}if(this._pendingRefs.has(e)){this._pendingRefs.remove(e);warn(`Ignoring circular reference: ${e}.`);return lt}this._pendingRefs.put(e);try{s=s.uncompressed?this.fetchUncompressed(e,s,t):this.fetchCompressed(e,s,t);this._pendingRefs.remove(e)}catch(t){this._pendingRefs.remove(e);throw t}s instanceof Dict?s.objId=e.toString():s instanceof BaseStream&&(s.dict.objId=e.toString());return s}fetchUncompressed(e,t,i=!1){const a=e.gen;let s=e.num;if(t.gen!==a){const r=`Inconsistent generation in XRef: ${e}`;if(this._generationFallback&&t.gen0&&t[3]-t[1]>0)return t;warn(`Empty, or invalid, /${e} entry.`)}return null}get mediaBox(){return shadow(this,"mediaBox",this._getBoundingBox("MediaBox")||tg)}get cropBox(){return shadow(this,"cropBox",this._getBoundingBox("CropBox")||this.mediaBox)}get userUnit(){const e=this.pageDict.get("UserUnit");return shadow(this,"userUnit","number"==typeof e&&e>0?e:1)}get view(){const{cropBox:e,mediaBox:t}=this;if(e!==t&&!isArrayEqual(e,t)){const i=Util.intersect(e,t);if(i&&i[2]-i[0]>0&&i[3]-i[1]>0)return shadow(this,"view",i);warn("Empty /CropBox and /MediaBox intersection.")}return shadow(this,"view",t)}get rotate(){let e=this._getInheritableProperty("Rotate")||0;e%90!=0?e=0:e>=360?e%=360:e<0&&(e=(e%360+360)%360);return shadow(this,"rotate",e)}_onSubStreamError(e,t){if(!this.evaluatorOptions.ignoreErrors)throw e;warn(`getContentStream - ignoring sub-stream (${t}): "${e}".`)}getContentStream(){return this.pdfManager.ensure(this,"content").then((e=>e instanceof BaseStream?e:Array.isArray(e)?new StreamsSequenceStream(e,this._onSubStreamError.bind(this)):new NullStream))}get xfaData(){return shadow(this,"xfaData",this.xfaFactory?{bbox:this.xfaFactory.getBoundingBox(this.pageIndex)}:null)}async#V(e,t,i){const a=[];for(const s of e)if(s.id){const e=Ref.fromString(s.id);if(!e){warn(`A non-linked annotation cannot be modified: ${s.id}`);continue}if(s.deleted){t.put(e,e);if(s.popupRef){const e=Ref.fromString(s.popupRef);e&&t.put(e,e)}continue}i?.put(e);s.ref=e;a.push(this.xref.fetchAsync(e).then((e=>{e instanceof Dict&&(s.oldAnnotation=e.clone())}),(()=>{warn(`Cannot fetch \`oldAnnotation\` for: ${e}.`)})));delete s.id}await Promise.all(a)}async saveNewAnnotations(e,t,i,a,s){if(this.xfaFactory)throw new Error("XFA: Cannot save new annotations.");const r=new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions}),n=new RefSetCache,g=new RefSet;await this.#V(i,n,g);const o=this.pageDict,c=this.annotations.filter((e=>!(e instanceof Ref&&n.has(e)))),C=await AnnotationFactory.saveNewAnnotations(r,t,i,a,s);for(const{ref:e}of C.annotations)e instanceof Ref&&!g.has(e)&&c.push(e);const h=o.clone();h.set("Annots",c);s.put(this.ref,{data:h});for(const e of n)s.put(e,{data:null})}save(e,t,i,a){const s=new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions});return this._parsedAnnotations.then((function(e){const r=[];for(const n of e)r.push(n.save(s,t,i,a).catch((function(e){warn(`save - ignoring annotation data during "${t.name}" task: "${e}".`);return null})));return Promise.all(r)}))}loadResources(e){this.resourcesPromise||=this.pdfManager.ensure(this,"resources");return this.resourcesPromise.then((()=>new ObjectLoader(this.resources,e,this.xref).load()))}getOperatorList({handler:e,sink:t,task:i,intent:a,cacheKey:s,annotationStorage:r=null,modifiedIds:n=null}){const C=this.getContentStream(),E=this.loadResources(["ColorSpace","ExtGState","Font","Pattern","Properties","Shading","XObject"]),d=new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions}),f=this.xfaFactory?null:getNewAnnotationsMap(r),p=f?.get(this.pageIndex);let m=Promise.resolve(null),y=null;if(p){const e=this.pdfManager.ensureDoc("annotationGlobals");let t;const a=new Set;for(const{bitmapId:e,bitmap:t}of p)!e||t||a.has(e)||a.add(e);const{isOffscreenCanvasSupported:s}=this.evaluatorOptions;if(a.size>0){const e=p.slice();for(const[t,i]of r)t.startsWith(u)&&i.bitmap&&a.has(i.bitmapId)&&e.push(i);t=AnnotationFactory.generateImages(e,this.xref,s)}else t=AnnotationFactory.generateImages(p,this.xref,s);y=new RefSet;m=Promise.all([e,this.#V(p,y,null)]).then((([e])=>e?AnnotationFactory.printNewAnnotations(e,d,i,p,t):null))}const w=Promise.all([C,E]).then((([r])=>{const n=new OperatorList(a,t);e.send("StartRenderPage",{transparency:d.hasBlendModes(this.resources,this.nonBlendModesSet),pageIndex:this.pageIndex,cacheKey:s});return d.getOperatorList({stream:r,task:i,resources:this.resources,operatorList:n}).then((function(){return n}))}));return Promise.all([w,this._parsedAnnotations,m]).then((function([e,t,s]){if(s){t=t.filter((e=>!(e.ref&&y.has(e.ref))));for(let e=0,i=s.length;ee.ref&&isRefsEqual(e.ref,a.refToReplace)));if(r>=0){t.splice(r,1,a);s.splice(e--,1);i--}}}t=t.concat(s)}if(0===t.length||a&l){e.flush(!0);return{length:e.totalLength}}const C=!!(a&h),E=!!(a&Q),u=!!(a&g),f=!!(a&o),p=!!(a&c),m=[];for(const e of t)(u||f&&e.mustBeViewed(r,C)&&e.mustBeViewedWhenEditing(E,n)||p&&e.mustBePrinted(r))&&m.push(e.getOperatorList(d,i,a,r).catch((function(e){warn(`getOperatorList - ignoring annotation data during "${i.name}" task: "${e}".`);return{opList:null,separateForm:!1,separateCanvas:!1}})));return Promise.all(m).then((function(t){let i=!1,a=!1;for(const{opList:s,separateForm:r,separateCanvas:n}of t){e.addOpList(s);i||=r;a||=n}e.flush(!0,{form:i,canvas:a});return{length:e.totalLength}}))}))}async extractTextContent({handler:e,task:t,includeMarkedContent:i,disableNormalization:a,sink:s}){const r=this.getContentStream(),n=this.loadResources(["ExtGState","Font","Properties","XObject"]),g=this.pdfManager.ensureCatalog("lang"),[o,,c]=await Promise.all([r,n,g]);return new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions}).getTextContent({stream:o,task:t,resources:this.resources,includeMarkedContent:i,disableNormalization:a,sink:s,viewBox:this.view,lang:c})}async getStructTree(){const e=await this.pdfManager.ensureCatalog("structTreeRoot");if(!e)return null;await this._parsedAnnotations;const t=await this.pdfManager.ensure(this,"_parseStructTree",[e]);return this.pdfManager.ensure(t,"serializable")}_parseStructTree(e){const t=new StructTreePage(e,this.pageDict);t.parse(this.ref);return t}async getAnnotationsData(e,t,i){const a=await this._parsedAnnotations;if(0===a.length)return a;const s=[],r=[];let n;const C=!!(i&g),h=!!(i&o),l=!!(i&c);for(const i of a){const a=C||h&&i.viewable;(a||l&&i.printable)&&s.push(i.data);if(i.hasTextContent&&a){n||=new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions});r.push(i.extractTextContent(n,t,[-1/0,-1/0,1/0,1/0]).catch((function(e){warn(`getAnnotationsData - ignoring textContent during "${t.name}" task: "${e}".`)})))}}await Promise.all(r);return s}get annotations(){const e=this._getInheritableProperty("Annots");return shadow(this,"annotations",Array.isArray(e)?e:[])}get _parsedAnnotations(){return shadow(this,"_parsedAnnotations",this.pdfManager.ensure(this,"annotations").then((async e=>{if(0===e.length)return e;const[t,i]=await Promise.all([this.pdfManager.ensureDoc("annotationGlobals"),this.pdfManager.ensureDoc("fieldObjects")]);if(!t)return[];const a=i?.orphanFields,s=[];for(const i of e)s.push(AnnotationFactory.create(this.xref,i,t,this._localIdFactory,!1,a,this.ref).catch((function(e){warn(`_parsedAnnotations: "${e}".`);return null})));const r=[];let n,g;for(const e of await Promise.all(s))e&&(e instanceof WidgetAnnotation?(g||=[]).push(e):e instanceof PopupAnnotation?(n||=[]).push(e):r.push(e));g&&r.push(...g);n&&r.push(...n);return r})))}get jsActions(){return shadow(this,"jsActions",collectActions(this.xref,this.pageDict,pA))}}const ig=new Uint8Array([37,80,68,70,45]),ag=new Uint8Array([115,116,97,114,116,120,114,101,102]),sg=new Uint8Array([101,110,100,111,98,106]);function find(e,t,i=1024,a=!1){const s=t.length,r=e.peekBytes(i),n=r.length-s;if(n<=0)return!1;if(a){const i=s-1;let a=r.length-1;for(;a>=i;){let n=0;for(;n=s){e.pos+=a-i;return!0}a--}}else{let i=0;for(;i<=n;){let a=0;for(;a=s){e.pos+=i;return!0}i++}}return!1}class PDFDocument{constructor(e,t){if(t.length<=0)throw new InvalidPDFException("The PDF file is empty, i.e. its size is zero bytes.");this.pdfManager=e;this.stream=t;this.xref=new XRef(t,e);this._pagePromises=new Map;this._version=null;const i={font:0};this._globalIdFactory=class{static getDocId(){return`g_${e.docId}`}static createFontId(){return"f"+ ++i.font}static createObjId(){unreachable("Abstract method `createObjId` called.")}static getPageObjId(){unreachable("Abstract method `getPageObjId` called.")}}}parse(e){this.xref.parse(e);this.catalog=new Catalog(this.pdfManager,this.xref)}get linearization(){let e=null;try{e=Linearization.create(this.stream)}catch(e){if(e instanceof MissingDataException)throw e;info(e)}return shadow(this,"linearization",e)}get startXRef(){const e=this.stream;let t=0;if(this.linearization){e.reset();if(find(e,sg)){e.skip(6);let i=e.peekByte();for(;isWhiteSpace(i);){e.pos++;i=e.peekByte()}t=e.pos-e.start}}else{const i=1024,a=ag.length;let s=!1,r=e.end;for(;!s&&r>0;){r-=i-a;r<0&&(r=0);e.pos=r;s=find(e,ag,i,!0)}if(s){e.skip(9);let i;do{i=e.getByte()}while(isWhiteSpace(i));let a="";for(;i>=32&&i<=57;){a+=String.fromCharCode(i);i=e.getByte()}t=parseInt(a,10);isNaN(t)&&(t=0)}}return shadow(this,"startXRef",t)}checkHeader(){const e=this.stream;e.reset();if(!find(e,ig))return;e.moveStart();e.skip(ig.length);let t,i="";for(;(t=e.getByte())>32&&i.length<7;)i+=String.fromCharCode(t);ft.test(i)?this._version=i:warn(`Invalid PDF header version: ${i}`)}parseStartXRef(){this.xref.setStartXRef(this.startXRef)}get numPages(){let e=0;e=this.catalog.hasActualNumPages?this.catalog.numPages:this.xfaFactory?this.xfaFactory.getNumPages():this.linearization?this.linearization.numPages:this.catalog.numPages;return shadow(this,"numPages",e)}_hasOnlyDocumentSignatures(e,t=0){return!!Array.isArray(e)&&e.every((e=>{if(!((e=this.xref.fetchIfRef(e))instanceof Dict))return!1;if(e.has("Kids")){if(++t>10){warn("_hasOnlyDocumentSignatures: maximum recursion depth reached");return!1}return this._hasOnlyDocumentSignatures(e.get("Kids"),t)}const i=isName(e.get("FT"),"Sig"),a=e.get("Rect"),s=Array.isArray(a)&&a.every((e=>0===e));return i&&s}))}get _xfaStreams(){const e=this.catalog.acroForm;if(!e)return null;const t=e.get("XFA"),i={"xdp:xdp":"",template:"",datasets:"",config:"",connectionSet:"",localeSet:"",stylesheet:"","/xdp:xdp":""};if(t instanceof BaseStream&&!t.isEmpty){i["xdp:xdp"]=t;return i}if(!Array.isArray(t)||0===t.length)return null;for(let e=0,a=t.length;e0;e.hasFields=a;const s=t.get("XFA");e.hasXfa=Array.isArray(s)&&s.length>0||s instanceof BaseStream&&!s.isEmpty;const r=!!(1&t.get("SigFlags")),n=r&&this._hasOnlyDocumentSignatures(i);e.hasAcroForm=a&&!n;e.hasSignatures=r}catch(e){if(e instanceof MissingDataException)throw e;warn(`Cannot fetch form information: "${e}".`)}return shadow(this,"formInfo",e)}get documentInfo(){const e={PDFFormatVersion:this.version,Language:this.catalog.lang,EncryptFilterName:this.xref.encrypt?this.xref.encrypt.filterName:null,IsLinearized:!!this.linearization,IsAcroFormPresent:this.formInfo.hasAcroForm,IsXFAPresent:this.formInfo.hasXfa,IsCollectionPresent:!!this.catalog.collection,IsSignaturesPresent:this.formInfo.hasSignatures};let t;try{t=this.xref.trailer.get("Info")}catch(e){if(e instanceof MissingDataException)throw e;info("The document information dictionary is invalid.")}if(!(t instanceof Dict))return shadow(this,"documentInfo",e);for(const i of t.getKeys()){const a=t.get(i);switch(i){case"Title":case"Author":case"Subject":case"Keywords":case"Creator":case"Producer":case"CreationDate":case"ModDate":if("string"==typeof a){e[i]=stringToPDFString(a);continue}break;case"Trapped":if(a instanceof Name){e[i]=a;continue}break;default:let t;switch(typeof a){case"string":t=stringToPDFString(a);break;case"number":case"boolean":t=a;break;default:a instanceof Name&&(t=a)}if(void 0===t){warn(`Bad value, for custom key "${i}", in Info: ${a}.`);continue}e.Custom||(e.Custom=Object.create(null));e.Custom[i]=t;continue}warn(`Bad value, for key "${i}", in Info: ${a}.`)}return shadow(this,"documentInfo",e)}get fingerprints(){const e="\0".repeat(16);function validate(t){return"string"==typeof t&&16===t.length&&t!==e}const t=this.xref.trailer.get("ID");let i,a;if(Array.isArray(t)&&validate(t[0])){i=stringToBytes(t[0]);t[1]!==t[0]&&validate(t[1])&&(a=stringToBytes(t[1]))}else i=$n(this.stream.getByteRange(0,1024),0,1024);return shadow(this,"fingerprints",[toHexUtil(i),a?toHexUtil(a):null])}async _getLinearizationPage(e){const{catalog:t,linearization:i,xref:a}=this,s=Ref.get(i.objectNumberFirst,0);try{const e=await a.fetchAsync(s);if(e instanceof Dict){let i=e.getRaw("Type");i instanceof Ref&&(i=await a.fetchAsync(i));if(isName(i,"Page")||!e.has("Type")&&!e.has("Kids")&&e.has("Contents")){t.pageKidsCountCache.has(s)||t.pageKidsCountCache.put(s,1);t.pageIndexCache.has(s)||t.pageIndexCache.put(s,0);return[e,s]}}throw new FormatError("The Linearization dictionary doesn't point to a valid Page dictionary.")}catch(i){warn(`_getLinearizationPage: "${i.message}".`);return t.getPageDict(e)}}getPage(e){const t=this._pagePromises.get(e);if(t)return t;const{catalog:i,linearization:a,xfaFactory:s}=this;let r;r=s?Promise.resolve([Dict.empty,null]):a?.pageFirst===e?this._getLinearizationPage(e):i.getPageDict(e);r=r.then((([t,a])=>new Page({pdfManager:this.pdfManager,xref:this.xref,pageIndex:e,pageDict:t,ref:a,globalIdFactory:this._globalIdFactory,fontCache:i.fontCache,builtInCMapCache:i.builtInCMapCache,standardFontDataCache:i.standardFontDataCache,globalImageCache:i.globalImageCache,systemFontCache:i.systemFontCache,nonBlendModesSet:i.nonBlendModesSet,xfaFactory:s})));this._pagePromises.set(e,r);return r}async checkFirstPage(e=!1){if(!e)try{await this.getPage(0)}catch(e){if(e instanceof XRefEntryException){this._pagePromises.delete(0);await this.cleanup();throw new XRefParseException}}}async checkLastPage(e=!1){const{catalog:t,pdfManager:i}=this;t.setActualNumPages();let a;try{await Promise.all([i.ensureDoc("xfaFactory"),i.ensureDoc("linearization"),i.ensureCatalog("numPages")]);if(this.xfaFactory)return;a=this.linearization?this.linearization.numPages:t.numPages;if(!Number.isInteger(a))throw new FormatError("Page count is not an integer.");if(a<=1)return;await this.getPage(a-1)}catch(s){this._pagePromises.delete(a-1);await this.cleanup();if(s instanceof XRefEntryException&&!e)throw new XRefParseException;warn(`checkLastPage - invalid /Pages tree /Count: ${a}.`);let r;try{r=await t.getAllPageDicts(e)}catch(i){if(i instanceof XRefEntryException&&!e)throw new XRefParseException;t.setActualNumPages(1);return}for(const[e,[a,s]]of r){let r;if(a instanceof Error){r=Promise.reject(a);r.catch((()=>{}))}else r=Promise.resolve(new Page({pdfManager:i,xref:this.xref,pageIndex:e,pageDict:a,ref:s,globalIdFactory:this._globalIdFactory,fontCache:t.fontCache,builtInCMapCache:t.builtInCMapCache,standardFontDataCache:t.standardFontDataCache,globalImageCache:t.globalImageCache,systemFontCache:t.systemFontCache,nonBlendModesSet:t.nonBlendModesSet,xfaFactory:null}));this._pagePromises.set(e,r)}t.setActualNumPages(r.size)}}fontFallback(e,t){return this.catalog.fontFallback(e,t)}async cleanup(e=!1){return this.catalog?this.catalog.cleanup(e):clearGlobalCaches()}async#z(e,t,i,a,s,r,n){const{xref:g}=this;if(!(i instanceof Ref)||r.has(i))return;r.put(i);const o=await g.fetchAsync(i);if(!(o instanceof Dict))return;if(o.has("T")){const t=stringToPDFString(await o.getAsync("T"));e=""===e?t:`${e}.${t}`}else{let i=o;for(;;){i=i.getRaw("Parent")||t;if(i instanceof Ref){if(r.has(i))break;i=await g.fetchAsync(i)}if(!(i instanceof Dict))break;if(i.has("T")){const t=stringToPDFString(await i.getAsync("T"));e=""===e?t:`${e}.${t}`;break}}}t&&!o.has("Parent")&&isName(o.get("Subtype"),"Widget")&&n.put(i,t);a.has(e)||a.set(e,[]);a.get(e).push(AnnotationFactory.create(g,i,s,null,!0,n,null).then((e=>e?.getFieldObject())).catch((function(e){warn(`#collectFieldObjects: "${e}".`);return null})));if(!o.has("Kids"))return;const c=await o.getAsync("Kids");if(Array.isArray(c))for(const t of c)await this.#z(e,i,t,a,s,r,n)}get fieldObjects(){return shadow(this,"fieldObjects",this.pdfManager.ensureDoc("formInfo").then((async e=>{if(!e.hasFields)return null;const[t,i]=await Promise.all([this.pdfManager.ensureDoc("annotationGlobals"),this.pdfManager.ensureCatalog("acroForm")]);if(!t)return null;const a=new RefSet,s=Object.create(null),r=new Map,n=new RefSetCache;for(const e of await i.getAsync("Fields"))await this.#z("",null,e,r,t,a,n);const g=[];for(const[e,t]of r)g.push(Promise.all(t).then((t=>{(t=t.filter((e=>!!e))).length>0&&(s[e]=t)})));await Promise.all(g);return{allFields:s,orphanFields:n}})))}get hasJSActions(){return shadow(this,"hasJSActions",this.pdfManager.ensureDoc("_parseHasJSActions"))}async _parseHasJSActions(){const[e,t]=await Promise.all([this.pdfManager.ensureCatalog("jsActions"),this.pdfManager.ensureDoc("fieldObjects")]);return!!e||!!t&&Object.values(t.allFields).some((e=>e.some((e=>null!==e.actions))))}get calculationOrderIds(){const e=this.catalog.acroForm?.get("CO");if(!Array.isArray(e)||0===e.length)return shadow(this,"calculationOrderIds",null);const t=[];for(const i of e)i instanceof Ref&&t.push(i.toString());return shadow(this,"calculationOrderIds",t.length?t:null)}get annotationGlobals(){return shadow(this,"annotationGlobals",AnnotationFactory.createGlobals(this.pdfManager))}}class BasePdfManager{constructor(e){this._docBaseUrl=function parseDocBaseUrl(e){if(e){const t=createValidAbsoluteUrl(e);if(t)return t.href;warn(`Invalid absolute docBaseUrl: "${e}".`)}return null}(e.docBaseUrl);this._docId=e.docId;this._password=e.password;this.enableXfa=e.enableXfa;e.evaluatorOptions.isOffscreenCanvasSupported&&=FeatureTest.isOffscreenCanvasSupported;e.evaluatorOptions.isImageDecoderSupported&&=FeatureTest.isImageDecoderSupported;this.evaluatorOptions=Object.freeze(e.evaluatorOptions)}get docId(){return this._docId}get password(){return this._password}get docBaseUrl(){return this._docBaseUrl}get catalog(){return this.pdfDocument.catalog}ensureDoc(e,t){return this.ensure(this.pdfDocument,e,t)}ensureXRef(e,t){return this.ensure(this.pdfDocument.xref,e,t)}ensureCatalog(e,t){return this.ensure(this.pdfDocument.catalog,e,t)}getPage(e){return this.pdfDocument.getPage(e)}fontFallback(e,t){return this.pdfDocument.fontFallback(e,t)}loadXfaFonts(e,t){return this.pdfDocument.loadXfaFonts(e,t)}loadXfaImages(){return this.pdfDocument.loadXfaImages()}serializeXfaData(e){return this.pdfDocument.serializeXfaData(e)}cleanup(e=!1){return this.pdfDocument.cleanup(e)}async ensure(e,t,i){unreachable("Abstract method `ensure` called")}requestRange(e,t){unreachable("Abstract method `requestRange` called")}requestLoadedStream(e=!1){unreachable("Abstract method `requestLoadedStream` called")}sendProgressiveData(e){unreachable("Abstract method `sendProgressiveData` called")}updatePassword(e){this._password=e}terminate(e){unreachable("Abstract method `terminate` called")}}class LocalPdfManager extends BasePdfManager{constructor(e){super(e);const t=new Stream(e.source);this.pdfDocument=new PDFDocument(this,t);this._loadedStreamPromise=Promise.resolve(t)}async ensure(e,t,i){const a=e[t];return"function"==typeof a?a.apply(e,i):a}requestRange(e,t){return Promise.resolve()}requestLoadedStream(e=!1){return this._loadedStreamPromise}terminate(e){}}class NetworkPdfManager extends BasePdfManager{constructor(e){super(e);this.streamManager=new ChunkedStreamManager(e.source,{msgHandler:e.handler,length:e.length,disableAutoFetch:e.disableAutoFetch,rangeChunkSize:e.rangeChunkSize});this.pdfDocument=new PDFDocument(this,this.streamManager.getStream())}async ensure(e,t,i){try{const a=e[t];return"function"==typeof a?a.apply(e,i):a}catch(a){if(!(a instanceof MissingDataException))throw a;await this.requestRange(a.begin,a.end);return this.ensure(e,t,i)}}requestRange(e,t){return this.streamManager.requestRange(e,t)}requestLoadedStream(e=!1){return this.streamManager.requestAllChunks(e)}sendProgressiveData(e){this.streamManager.onReceiveData({chunk:e})}terminate(e){this.streamManager.abort(e)}}const rg=1,ng=2,gg=1,og=2,Ig=3,cg=4,Cg=5,hg=6,lg=7,Bg=8;function onFn(){}function wrapReason(e){if(e instanceof AbortException||e instanceof InvalidPDFException||e instanceof MissingPDFException||e instanceof PasswordException||e instanceof UnexpectedResponseException||e instanceof UnknownErrorException)return e;e instanceof Error||"object"==typeof e&&null!==e||unreachable('wrapReason: Expected "reason" to be a (possibly cloned) Error.');switch(e.name){case"AbortException":return new AbortException(e.message);case"InvalidPDFException":return new InvalidPDFException(e.message);case"MissingPDFException":return new MissingPDFException(e.message);case"PasswordException":return new PasswordException(e.message,e.code);case"UnexpectedResponseException":return new UnexpectedResponseException(e.message,e.status);case"UnknownErrorException":return new UnknownErrorException(e.message,e.details)}return new UnknownErrorException(e.message,e.toString())}class MessageHandler{#_=new AbortController;constructor(e,t,i){this.sourceName=e;this.targetName=t;this.comObj=i;this.callbackId=1;this.streamId=1;this.streamSinks=Object.create(null);this.streamControllers=Object.create(null);this.callbackCapabilities=Object.create(null);this.actionHandler=Object.create(null);i.addEventListener("message",this.#$.bind(this),{signal:this.#_.signal})}#$({data:e}){if(e.targetName!==this.sourceName)return;if(e.stream){this.#AA(e);return}if(e.callback){const t=e.callbackId,i=this.callbackCapabilities[t];if(!i)throw new Error(`Cannot resolve callback ${t}`);delete this.callbackCapabilities[t];if(e.callback===rg)i.resolve(e.data);else{if(e.callback!==ng)throw new Error("Unexpected callback case");i.reject(wrapReason(e.reason))}return}const t=this.actionHandler[e.action];if(!t)throw new Error(`Unknown action from worker: ${e.action}`);if(e.callbackId){const i=this.sourceName,a=e.sourceName,s=this.comObj;Promise.try(t,e.data).then((function(t){s.postMessage({sourceName:i,targetName:a,callback:rg,callbackId:e.callbackId,data:t})}),(function(t){s.postMessage({sourceName:i,targetName:a,callback:ng,callbackId:e.callbackId,reason:wrapReason(t)})}))}else e.streamId?this.#eA(e):t(e.data)}on(e,t){const i=this.actionHandler;if(i[e])throw new Error(`There is already an actionName called "${e}"`);i[e]=t}send(e,t,i){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,data:t},i)}sendWithPromise(e,t,i){const a=this.callbackId++,s=Promise.withResolvers();this.callbackCapabilities[a]=s;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,callbackId:a,data:t},i)}catch(e){s.reject(e)}return s.promise}sendWithStream(e,t,i,a){const s=this.streamId++,r=this.sourceName,n=this.targetName,g=this.comObj;return new ReadableStream({start:i=>{const o=Promise.withResolvers();this.streamControllers[s]={controller:i,startCall:o,pullCall:null,cancelCall:null,isClosed:!1};g.postMessage({sourceName:r,targetName:n,action:e,streamId:s,data:t,desiredSize:i.desiredSize},a);return o.promise},pull:e=>{const t=Promise.withResolvers();this.streamControllers[s].pullCall=t;g.postMessage({sourceName:r,targetName:n,stream:hg,streamId:s,desiredSize:e.desiredSize});return t.promise},cancel:e=>{assert(e instanceof Error,"cancel must have a valid reason");const t=Promise.withResolvers();this.streamControllers[s].cancelCall=t;this.streamControllers[s].isClosed=!0;g.postMessage({sourceName:r,targetName:n,stream:gg,streamId:s,reason:wrapReason(e)});return t.promise}},i)}#eA(e){const t=e.streamId,i=this.sourceName,a=e.sourceName,s=this.comObj,r=this,n=this.actionHandler[e.action],g={enqueue(e,r=1,n){if(this.isCancelled)return;const g=this.desiredSize;this.desiredSize-=r;if(g>0&&this.desiredSize<=0){this.sinkCapability=Promise.withResolvers();this.ready=this.sinkCapability.promise}s.postMessage({sourceName:i,targetName:a,stream:cg,streamId:t,chunk:e},n)},close(){if(!this.isCancelled){this.isCancelled=!0;s.postMessage({sourceName:i,targetName:a,stream:Ig,streamId:t});delete r.streamSinks[t]}},error(e){assert(e instanceof Error,"error must have a valid reason");if(!this.isCancelled){this.isCancelled=!0;s.postMessage({sourceName:i,targetName:a,stream:Cg,streamId:t,reason:wrapReason(e)})}},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:e.desiredSize,ready:null};g.sinkCapability.resolve();g.ready=g.sinkCapability.promise;this.streamSinks[t]=g;Promise.try(n,e.data,g).then((function(){s.postMessage({sourceName:i,targetName:a,stream:Bg,streamId:t,success:!0})}),(function(e){s.postMessage({sourceName:i,targetName:a,stream:Bg,streamId:t,reason:wrapReason(e)})}))}#AA(e){const t=e.streamId,i=this.sourceName,a=e.sourceName,s=this.comObj,r=this.streamControllers[t],n=this.streamSinks[t];switch(e.stream){case Bg:e.success?r.startCall.resolve():r.startCall.reject(wrapReason(e.reason));break;case lg:e.success?r.pullCall.resolve():r.pullCall.reject(wrapReason(e.reason));break;case hg:if(!n){s.postMessage({sourceName:i,targetName:a,stream:lg,streamId:t,success:!0});break}n.desiredSize<=0&&e.desiredSize>0&&n.sinkCapability.resolve();n.desiredSize=e.desiredSize;Promise.try(n.onPull||onFn).then((function(){s.postMessage({sourceName:i,targetName:a,stream:lg,streamId:t,success:!0})}),(function(e){s.postMessage({sourceName:i,targetName:a,stream:lg,streamId:t,reason:wrapReason(e)})}));break;case cg:assert(r,"enqueue should have stream controller");if(r.isClosed)break;r.controller.enqueue(e.chunk);break;case Ig:assert(r,"close should have stream controller");if(r.isClosed)break;r.isClosed=!0;r.controller.close();this.#tA(r,t);break;case Cg:assert(r,"error should have stream controller");r.controller.error(wrapReason(e.reason));this.#tA(r,t);break;case og:e.success?r.cancelCall.resolve():r.cancelCall.reject(wrapReason(e.reason));this.#tA(r,t);break;case gg:if(!n)break;const g=wrapReason(e.reason);Promise.try(n.onCancel||onFn,g).then((function(){s.postMessage({sourceName:i,targetName:a,stream:og,streamId:t,success:!0})}),(function(e){s.postMessage({sourceName:i,targetName:a,stream:og,streamId:t,reason:wrapReason(e)})}));n.sinkCapability.reject(g);n.isCancelled=!0;delete this.streamSinks[t];break;default:throw new Error("Unexpected stream case")}}async#tA(e,t){await Promise.allSettled([e.startCall?.promise,e.pullCall?.promise,e.cancelCall?.promise]);delete this.streamControllers[t]}destroy(){this.#_?.abort();this.#_=null}}async function writeObject(e,t,i,{encrypt:a=null}){const s=a?.createCipherTransform(e.num,e.gen);i.push(`${e.num} ${e.gen} obj\n`);t instanceof Dict?await writeDict(t,i,s):t instanceof BaseStream?await writeStream(t,i,s):(Array.isArray(t)||ArrayBuffer.isView(t))&&await writeArray(t,i,s);i.push("\nendobj\n")}async function writeDict(e,t,i){t.push("<<");for(const a of e.getKeys()){t.push(` /${escapePDFName(a)} `);await writeValue(e.getRaw(a),t,i)}t.push(">>")}async function writeStream(e,t,i){let a=e.getBytes();const{dict:s}=e,[r,n]=await Promise.all([s.getAsync("Filter"),s.getAsync("DecodeParms")]),g=isName(Array.isArray(r)?await s.xref.fetchIfRefAsync(r[0]):r,"FlateDecode");if(a.length>=256||g)try{const e=new CompressionStream("deflate"),t=e.writable.getWriter();await t.ready;t.write(a).then((async()=>{await t.ready;await t.close()})).catch((()=>{}));const i=await new Response(e.readable).arrayBuffer();a=new Uint8Array(i);let o,c;if(r){if(!g){o=Array.isArray(r)?[Name.get("FlateDecode"),...r]:[Name.get("FlateDecode"),r];n&&(c=Array.isArray(n)?[null,...n]:[null,n])}}else o=Name.get("FlateDecode");o&&s.set("Filter",o);c&&s.set("DecodeParms",c)}catch(e){info(`writeStream - cannot compress data: "${e}".`)}let o=bytesToString(a);i&&(o=i.encryptString(o));s.set("Length",o.length);await writeDict(s,t,i);t.push(" stream\n",o,"\nendstream")}async function writeArray(e,t,i){t.push("[");let a=!0;for(const s of e){a?a=!1:t.push(" ");await writeValue(s,t,i)}t.push("]")}async function writeValue(e,t,i){if(e instanceof Name)t.push(`/${escapePDFName(e.name)}`);else if(e instanceof Ref)t.push(`${e.num} ${e.gen} R`);else if(Array.isArray(e)||ArrayBuffer.isView(e))await writeArray(e,t,i);else if("string"==typeof e){i&&(e=i.encryptString(e));t.push(`(${escapeString(e)})`)}else"number"==typeof e?t.push(numberToString(e)):"boolean"==typeof e?t.push(e.toString()):e instanceof Dict?await writeDict(e,t,i):e instanceof BaseStream?await writeStream(e,t,i):null===e?t.push("null"):warn(`Unhandled value in writer: ${typeof e}, please file a bug.`)}function writeInt(e,t,i,a){for(let s=t+i-1;s>i-1;s--){a[s]=255&e;e>>=8}return i+t}function writeString(e,t,i){for(let a=0,s=e.length;a1&&(r=i.documentElement.searchNode([s.at(-1)],0));r?r.childNodes=Array.isArray(a)?a.map((e=>new SimpleDOMNode("value",e))):[new SimpleDOMNode("#text",a)]:warn(`Node not found for path: ${t}`)}const a=[];i.documentElement.dump(a);return a.join("")}(a.fetchIfRef(t).getString(),i)}const s=new StringStream(e);s.dict=new Dict(a);s.dict.set("Type",Name.get("EmbeddedFile"));i.put(t,{data:s})}function getIndexes(e){const t=[];for(const{ref:i}of e)i.num===t.at(-2)+t.at(-1)?t[t.length-1]+=1:t.push(i.num,1);return t}function computeIDs(e,t,i){if(Array.isArray(t.fileIds)&&t.fileIds.length>0){const a=function computeMD5(e,t){const i=Math.floor(Date.now()/1e3),a=t.filename||"",s=[i.toString(),a,e.toString()];let r=s.reduce(((e,t)=>e+t.length),0);for(const e of Object.values(t.info)){s.push(e);r+=e.length}const n=new Uint8Array(r);let g=0;for(const e of s){writeString(e,g,n);g+=e.length}return bytesToString($n(n))}(e,t);i.set("ID",[t.fileIds[0],a])}}async function incrementalUpdate({originalData:e,xrefInfo:t,changes:i,xref:a=null,hasXfa:s=!1,xfaDatasetsRef:r=null,hasXfaDatasetsEntry:n=!1,needAppearances:g,acroFormRef:o=null,acroForm:c=null,xfaData:C=null,useXrefStream:h=!1}){await async function updateAcroform({xref:e,acroForm:t,acroFormRef:i,hasXfa:a,hasXfaDatasetsEntry:s,xfaDatasetsRef:r,needAppearances:n,changes:g}){!a||s||r||warn("XFA - Cannot save it");if(!n&&(!a||!r||s))return;const o=t.clone();if(a&&!s){const e=t.get("XFA").slice();e.splice(2,0,"datasets");e.splice(3,0,r);o.set("XFA",e)}n&&o.set("NeedAppearances",!0);g.put(i,{data:o})}({xref:a,acroForm:c,acroFormRef:o,hasXfa:s,hasXfaDatasetsEntry:n,xfaDatasetsRef:r,needAppearances:g,changes:i});s&&updateXFA({xfaData:C,xfaDatasetsRef:r,changes:i,xref:a});const l=function getTrailerDict(e,t,i){const a=new Dict(null);a.set("Prev",e.startXRef);const s=e.newRef;if(i){t.put(s,{data:""});a.set("Size",s.num+1);a.set("Type",Name.get("XRef"))}else a.set("Size",s.num);null!==e.rootRef&&a.set("Root",e.rootRef);null!==e.infoRef&&a.set("Info",e.infoRef);null!==e.encryptRef&&a.set("Encrypt",e.encryptRef);return a}(t,i,h),Q=[],E=await async function writeChanges(e,t,i=[]){const a=[];for(const[s,{data:r}]of e.items())if(null!==r&&"string"!=typeof r){await writeObject(s,r,i,t);a.push({ref:s,data:i.join("")});i.length=0}else a.push({ref:s,data:r});return a.sort(((e,t)=>e.ref.num-t.ref.num))}(i,a,Q);let u=e.length;const d=e.at(-1);if(10!==d&&13!==d){Q.push("\n");u+=1}for(const{data:e}of E)null!==e&&Q.push(e);await(h?async function getXRefStreamTable(e,t,i,a,s){const r=[];let n=0,g=0;for(const{ref:e,data:a}of i){let i;n=Math.max(n,t);if(null!==a){i=Math.min(e.gen,65535);r.push([1,t,i]);t+=a.length}else{i=Math.min(e.gen+1,65535);r.push([0,0,i])}g=Math.max(g,i)}a.set("Index",getIndexes(i));const o=[1,getSizeInBytes(n),getSizeInBytes(g)];a.set("W",o);computeIDs(t,e,a);const c=o.reduce(((e,t)=>e+t),0),C=new Uint8Array(c*r.length),h=new Stream(C);h.dict=a;let l=0;for(const[e,t,i]of r){l=writeInt(e,o[0],l,C);l=writeInt(t,o[1],l,C);l=writeInt(i,o[2],l,C)}await writeObject(e.newRef,h,s,{});s.push("startxref\n",t.toString(),"\n%%EOF\n")}(t,u,E,l,Q):async function getXRefTable(e,t,i,a,s){s.push("xref\n");const r=getIndexes(i);let n=0;for(const{ref:e,data:a}of i){if(e.num===r[n]){s.push(`${r[n]} ${r[n+1]}\n`);n+=2}if(null!==a){s.push(`${t.toString().padStart(10,"0")} ${Math.min(e.gen,65535).toString().padStart(5,"0")} n\r\n`);t+=a.length}else s.push(`0000000000 ${Math.min(e.gen+1,65535).toString().padStart(5,"0")} f\r\n`)}computeIDs(t,e,a);s.push("trailer\n");await writeDict(a,s);s.push("\nstartxref\n",t.toString(),"\n%%EOF\n")}(t,u,E,l,Q));const f=Q.reduce(((e,t)=>e+t.length),e.length),p=new Uint8Array(f);p.set(e);let m=e.length;for(const e of Q){writeString(e,m,p);m+=e.length}return p}class PDFWorkerStream{constructor(e){this._msgHandler=e;this._contentLength=null;this._fullRequestReader=null;this._rangeRequestReaders=[]}getFullReader(){assert(!this._fullRequestReader,"PDFWorkerStream.getFullReader can only be called once.");this._fullRequestReader=new PDFWorkerStreamReader(this._msgHandler);return this._fullRequestReader}getRangeReader(e,t){const i=new PDFWorkerStreamRangeReader(e,t,this._msgHandler);this._rangeRequestReaders.push(i);return i}cancelAllRequests(e){this._fullRequestReader?.cancel(e);for(const t of this._rangeRequestReaders.slice(0))t.cancel(e)}}class PDFWorkerStreamReader{constructor(e){this._msgHandler=e;this.onProgress=null;this._contentLength=null;this._isRangeSupported=!1;this._isStreamingSupported=!1;const t=this._msgHandler.sendWithStream("GetReader");this._reader=t.getReader();this._headersReady=this._msgHandler.sendWithPromise("ReaderHeadersReady").then((e=>{this._isStreamingSupported=e.isStreamingSupported;this._isRangeSupported=e.isRangeSupported;this._contentLength=e.contentLength}))}get headersReady(){return this._headersReady}get contentLength(){return this._contentLength}get isStreamingSupported(){return this._isStreamingSupported}get isRangeSupported(){return this._isRangeSupported}async read(){const{value:e,done:t}=await this._reader.read();return t?{value:void 0,done:!0}:{value:e.buffer,done:!1}}cancel(e){this._reader.cancel(e)}}class PDFWorkerStreamRangeReader{constructor(e,t,i){this._msgHandler=i;this.onProgress=null;const a=this._msgHandler.sendWithStream("GetRangeReader",{begin:e,end:t});this._reader=a.getReader()}get isStreamingSupported(){return!1}async read(){const{value:e,done:t}=await this._reader.read();return t?{value:void 0,done:!0}:{value:e.buffer,done:!1}}cancel(e){this._reader.cancel(e)}}class WorkerTask{constructor(e){this.name=e;this.terminated=!1;this._capability=Promise.withResolvers()}get finished(){return this._capability.promise}finish(){this._capability.resolve()}terminate(){this.terminated=!0}ensureNotTerminated(){if(this.terminated)throw new Error("Worker task was terminated")}}class WorkerMessageHandler{static{"undefined"==typeof window&&!t&&"undefined"!=typeof self&&"function"==typeof self.postMessage&&"onmessage"in self&&this.initializeFromPort(self)}static setup(e,t){let i=!1;e.on("test",(t=>{if(!i){i=!0;e.send("test",t instanceof Uint8Array)}}));e.on("configure",(e=>{!function setVerbosityLevel(e){Number.isInteger(e)&&(gt=e)}(e.verbosity)}));e.on("GetDocRequest",(e=>this.createDocumentHandler(e,t)))}static createDocumentHandler(e,t){let i,a=!1,s=null;const r=new Set,n=getVerbosityLevel(),{docId:g,apiVersion:o}=e,c="4.10.38";if(o!==c)throw new Error(`The API version "${o}" does not match the Worker version "${c}".`);const C=[];for(const e in[])C.push(e);if(C.length)throw new Error("The `Array.prototype` contains unexpected enumerable properties: "+C.join(", ")+"; thus breaking e.g. `for...in` iteration of `Array`s.");const h=g+"_worker";let l=new MessageHandler(h,g,t);function ensureNotTerminated(){if(a)throw new Error("Worker was terminated")}function startWorkerTask(e){r.add(e)}function finishWorkerTask(e){e.finish();r.delete(e)}async function loadDocument(e){await i.ensureDoc("checkHeader");await i.ensureDoc("parseStartXRef");await i.ensureDoc("parse",[e]);await i.ensureDoc("checkFirstPage",[e]);await i.ensureDoc("checkLastPage",[e]);const t=await i.ensureDoc("isPureXfa");if(t){const e=new WorkerTask("loadXfaFonts");startWorkerTask(e);await Promise.all([i.loadXfaFonts(l,e).catch((e=>{})).then((()=>finishWorkerTask(e))),i.loadXfaImages()])}const[a,s]=await Promise.all([i.ensureDoc("numPages"),i.ensureDoc("fingerprints")]);return{numPages:a,fingerprints:s,htmlForXfa:t?await i.ensureDoc("htmlForXfa"):null}}function setupDoc(e){function onSuccess(e){ensureNotTerminated();l.send("GetDoc",{pdfInfo:e})}function onFailure(e){ensureNotTerminated();if(e instanceof PasswordException){const t=new WorkerTask(`PasswordException: response ${e.code}`);startWorkerTask(t);l.sendWithPromise("PasswordRequest",e).then((function({password:e}){finishWorkerTask(t);i.updatePassword(e);pdfManagerReady()})).catch((function(){finishWorkerTask(t);l.send("DocException",e)}))}else l.send("DocException",wrapReason(e))}function pdfManagerReady(){ensureNotTerminated();loadDocument(!1).then(onSuccess,(function(e){ensureNotTerminated();e instanceof XRefParseException?i.requestLoadedStream().then((function(){ensureNotTerminated();loadDocument(!0).then(onSuccess,onFailure)})):onFailure(e)}))}ensureNotTerminated();(async function getPdfManager({data:e,password:t,disableAutoFetch:i,rangeChunkSize:a,length:r,docBaseUrl:n,enableXfa:o,evaluatorOptions:c}){const C={source:null,disableAutoFetch:i,docBaseUrl:n,docId:g,enableXfa:o,evaluatorOptions:c,handler:l,length:r,password:t,rangeChunkSize:a};if(e){C.source=e;return new LocalPdfManager(C)}const h=new PDFWorkerStream(l),Q=h.getFullReader(),E=Promise.withResolvers();let u,d=[],f=0;Q.headersReady.then((function(){if(Q.isRangeSupported){C.source=h;C.length=Q.contentLength;C.disableAutoFetch||=Q.isStreamingSupported;u=new NetworkPdfManager(C);for(const e of d)u.sendProgressiveData(e);d=[];E.resolve(u);s=null}})).catch((function(e){E.reject(e);s=null}));new Promise((function(e,t){const readChunk=function({value:e,done:i}){try{ensureNotTerminated();if(i){if(!u){const e=arrayBuffersToBytes(d);d=[];r&&e.length!==r&&warn("reported HTTP length is different from actual");C.source=e;u=new LocalPdfManager(C);E.resolve(u)}s=null;return}f+=e.byteLength;Q.isStreamingSupported||l.send("DocProgress",{loaded:f,total:Math.max(f,Q.contentLength||0)});u?u.sendProgressiveData(e):d.push(e);Q.read().then(readChunk,t)}catch(e){t(e)}};Q.read().then(readChunk,t)})).catch((function(e){E.reject(e);s=null}));s=e=>{h.cancelAllRequests(e)};return E.promise})(e).then((function(e){if(a){e.terminate(new AbortException("Worker was terminated."));throw new Error("Worker was terminated")}i=e;i.requestLoadedStream(!0).then((e=>{l.send("DataLoaded",{length:e.bytes.byteLength})}))})).then(pdfManagerReady,onFailure)}l.on("GetPage",(function(e){return i.getPage(e.pageIndex).then((function(e){return Promise.all([i.ensure(e,"rotate"),i.ensure(e,"ref"),i.ensure(e,"userUnit"),i.ensure(e,"view")]).then((function([e,t,i,a]){return{rotate:e,ref:t,refStr:t?.toString()??null,userUnit:i,view:a}}))}))}));l.on("GetPageIndex",(function(e){const t=Ref.get(e.num,e.gen);return i.ensureCatalog("getPageIndex",[t])}));l.on("GetDestinations",(function(e){return i.ensureCatalog("destinations")}));l.on("GetDestination",(function(e){return i.ensureCatalog("getDestination",[e.id])}));l.on("GetPageLabels",(function(e){return i.ensureCatalog("pageLabels")}));l.on("GetPageLayout",(function(e){return i.ensureCatalog("pageLayout")}));l.on("GetPageMode",(function(e){return i.ensureCatalog("pageMode")}));l.on("GetViewerPreferences",(function(e){return i.ensureCatalog("viewerPreferences")}));l.on("GetOpenAction",(function(e){return i.ensureCatalog("openAction")}));l.on("GetAttachments",(function(e){return i.ensureCatalog("attachments")}));l.on("GetDocJSActions",(function(e){return i.ensureCatalog("jsActions")}));l.on("GetPageJSActions",(function({pageIndex:e}){return i.getPage(e).then((function(e){return i.ensure(e,"jsActions")}))}));l.on("GetOutline",(function(e){return i.ensureCatalog("documentOutline")}));l.on("GetOptionalContentConfig",(function(e){return i.ensureCatalog("optionalContentConfig")}));l.on("GetPermissions",(function(e){return i.ensureCatalog("permissions")}));l.on("GetMetadata",(function(e){return Promise.all([i.ensureDoc("documentInfo"),i.ensureCatalog("metadata")])}));l.on("GetMarkInfo",(function(e){return i.ensureCatalog("markInfo")}));l.on("GetData",(function(e){return i.requestLoadedStream().then((function(e){return e.bytes}))}));l.on("GetAnnotations",(function({pageIndex:e,intent:t}){return i.getPage(e).then((function(i){const a=new WorkerTask(`GetAnnotations: page ${e}`);startWorkerTask(a);return i.getAnnotationsData(l,a,t).then((e=>{finishWorkerTask(a);return e}),(e=>{finishWorkerTask(a);throw e}))}))}));l.on("GetFieldObjects",(function(e){return i.ensureDoc("fieldObjects").then((e=>e?.allFields||null))}));l.on("HasJSActions",(function(e){return i.ensureDoc("hasJSActions")}));l.on("GetCalculationOrderIds",(function(e){return i.ensureDoc("calculationOrderIds")}));l.on("SaveDocument",(async function({isPureXfa:e,numPages:t,annotationStorage:a,filename:s}){const r=[i.requestLoadedStream(),i.ensureCatalog("acroForm"),i.ensureCatalog("acroFormRef"),i.ensureDoc("startXRef"),i.ensureDoc("xref"),i.ensureDoc("linearization"),i.ensureCatalog("structTreeRoot")],n=new RefSetCache,g=[],o=e?null:getNewAnnotationsMap(a),[c,C,h,Q,E,u,d]=await Promise.all(r),f=E.trailer.getRaw("Root")||null;let p;if(o){d?await d.canUpdateStructTree({pdfManager:i,xref:E,newAnnotationsByPage:o})&&(p=d):await StructTreeRoot.canCreateStructureTree({catalogRef:f,pdfManager:i,newAnnotationsByPage:o})&&(p=null);const e=AnnotationFactory.generateImages(a.values(),E,i.evaluatorOptions.isOffscreenCanvasSupported),t=void 0===p?g:[];for(const[a,s]of o)t.push(i.getPage(a).then((t=>{const i=new WorkerTask(`Save (editor): page ${a}`);startWorkerTask(i);return t.saveNewAnnotations(l,i,s,e,n).finally((function(){finishWorkerTask(i)}))})));null===p?g.push(Promise.all(t).then((async()=>{await StructTreeRoot.createStructureTree({newAnnotationsByPage:o,xref:E,catalogRef:f,pdfManager:i,changes:n})}))):p&&g.push(Promise.all(t).then((async()=>{await p.updateStructureTree({newAnnotationsByPage:o,pdfManager:i,changes:n})})))}if(e)g.push(i.serializeXfaData(a));else for(let e=0;ee.needAppearances)),D=C instanceof Dict&&C.get("XFA")||null;let b=null,F=!1;if(Array.isArray(D)){for(let e=0,t=D.length;e{E.resetNewTemporaryRef()}))}));l.on("GetOperatorList",(function(e,t){const a=e.pageIndex;i.getPage(a).then((function(i){const s=new WorkerTask(`GetOperatorList: page ${a}`);startWorkerTask(s);const r=n>=yA?Date.now():0;i.getOperatorList({handler:l,sink:t,task:s,intent:e.intent,cacheKey:e.cacheKey,annotationStorage:e.annotationStorage,modifiedIds:e.modifiedIds}).then((function(e){finishWorkerTask(s);r&&info(`page=${a+1} - getOperatorList: time=${Date.now()-r}ms, len=${e.length}`);t.close()}),(function(e){finishWorkerTask(s);s.terminated||t.error(e)}))}))}));l.on("GetTextContent",(function(e,t){const{pageIndex:a,includeMarkedContent:s,disableNormalization:r}=e;i.getPage(a).then((function(e){const i=new WorkerTask("GetTextContent: page "+a);startWorkerTask(i);const g=n>=yA?Date.now():0;e.extractTextContent({handler:l,task:i,sink:t,includeMarkedContent:s,disableNormalization:r}).then((function(){finishWorkerTask(i);g&&info(`page=${a+1} - getTextContent: time=`+(Date.now()-g)+"ms");t.close()}),(function(e){finishWorkerTask(i);i.terminated||t.error(e)}))}))}));l.on("GetStructTree",(function(e){return i.getPage(e.pageIndex).then((function(e){return i.ensure(e,"getStructTree")}))}));l.on("FontFallback",(function(e){return i.fontFallback(e.id,l)}));l.on("Cleanup",(function(e){return i.cleanup(!0)}));l.on("Terminate",(function(e){a=!0;const t=[];if(i){i.terminate(new AbortException("Worker was terminated."));const e=i.cleanup();t.push(e);i=null}else clearGlobalCaches();s?.(new AbortException("Worker was terminated."));for(const e of r){t.push(e.finished);e.terminate()}return Promise.all(t).then((function(){l.destroy();l=null}))}));l.on("Ready",(function(t){setupDoc(e);e=null}));return h}static initializeFromPort(e){const t=new MessageHandler("worker","main",e);this.setup(t,e);t.send("ready",null)}}var Qg=__webpack_exports__.WorkerMessageHandler;export{Qg as WorkerMessageHandler}; \ No newline at end of file diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/pdfjs-dist/dist/web/images/loading-icon.gif b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/pdfjs-dist/dist/web/images/loading-icon.gif deleted file mode 100644 index 1c72ebb554be018511ae972c3f2361dff02dce02..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2545 zcma*pX;2es8VB%~zPr=ibVMCx-JQ^BhLDAsK)^**h(ZDp9YGuzZ%~j!}+w%FI;|aC7){7CdVvG)P{bng1y9Te*f}~*`1kQl$jwb z$tlW~rRS!X?#xfm_&6tTdp_`cjgYwbRFLNdoJCN$S-yhg`ZnC-yvedRSmOh%;Y`Gl6bY$Z-}#C=#F4%9!I1b zWQ~f+9P?;vhCxWwlwl=lrWG|7IYo;{jjmzJ5R9?f>n%-d@>kLINUc z4wM5dAO;kq<$}Dk{2-u0$I6@2N}&cUx9nmV1dYc8jfC}%=F9WCg^OQK9C6poh#2!A z3^EU*UFZvS^)?bu3T?J;@Ahb~%I?+@4!l5!*TjC}GIslNan-RCrrd~PdHYnNLJk+m&`$Y+NV(e>CCu%R#_8GqY4cv#j`#uRWdsg9DxWy(?oOvgCU}&@jy%c!H&-Q zqXJxajAtmQRoRa9V-RFXXh-bK*;Fum{BjpkYQGX~i@OZ^Dx0n&H}kvGKqQ?w(6iGXu_g08T|_hp#ZvFzIwKF*a=oMJ~3UGAjZ?g}GOxm44td zXoyYrU*I=y*vHv89hkYH(v5R#wc)BC3dZJKb3K)f>zaM3%JP(mpecViP0eKKYf3zy z->jx_mc?mCtPEvCQ?uppk?eLJt}_IR7giW%Jr)RyI!+E-voIs*lXI*z`GQc_&D#X( z{6G};HPYj6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f(5hySYo9$l4e2`(hIV_?=H-#R6}0$WVA|*(K@3 z=5?@RlcLh(meW%A4)hGzcvEpm(_w?>zhL*i&s9$2>r zAtk{8Cia|+Y+V!uX9BtpXoF%lswuRKsM!pSs!?yhlCy!269K0|b M?FSZn2B>%I-}ej|s{jB1 diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.css deleted file mode 100644 index 86a3716c501..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.css +++ /dev/null @@ -1,3274 +0,0 @@ -/* Copyright 2014 Mozilla Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -.messageBar{ - --closing-button-icon:url(images/messageBar_closingButton.svg); - --message-bar-close-button-color:var(--text-primary-color); - --message-bar-close-button-color-hover:var(--text-primary-color); - --message-bar-close-button-border-radius:4px; - --message-bar-close-button-border:none; - --message-bar-close-button-hover-bg-color:rgb(21 20 26 / 0.14); - --message-bar-close-button-active-bg-color:rgb(21 20 26 / 0.21); - --message-bar-close-button-focus-bg-color:rgb(21 20 26 / 0.07); -} - -@media (prefers-color-scheme: dark){ - -.messageBar{ - --message-bar-close-button-hover-bg-color:rgb(251 251 254 / 0.14); - --message-bar-close-button-active-bg-color:rgb(251 251 254 / 0.21); - --message-bar-close-button-focus-bg-color:rgb(251 251 254 / 0.07); -} - } - -@media screen and (forced-colors: active){ - -.messageBar{ - --message-bar-close-button-color:ButtonText; - --message-bar-close-button-border:1px solid ButtonText; - --message-bar-close-button-hover-bg-color:ButtonText; - --message-bar-close-button-active-bg-color:ButtonText; - --message-bar-close-button-focus-bg-color:ButtonText; - --message-bar-close-button-color-hover:HighlightText; -} - } - -.messageBar{ - - display:flex; - position:relative; - padding:8px 8px 8px 16px; - flex-direction:column; - justify-content:center; - align-items:center; - gap:8px; - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; - - border-radius:4px; - - border:1px solid var(--message-bar-border-color); - background:var(--message-bar-bg-color); - color:var(--message-bar-fg-color); -} - -.messageBar > div{ - display:flex; - align-items:flex-start; - gap:8px; - align-self:stretch; - } - -:is(.messageBar > div)::before{ - content:""; - display:inline-block; - width:16px; - height:16px; - -webkit-mask-image:var(--message-bar-icon); - mask-image:var(--message-bar-icon); - -webkit-mask-size:cover; - mask-size:cover; - background-color:var(--message-bar-icon-color); - flex-shrink:0; - } - -.messageBar button{ - cursor:pointer; - } - -:is(.messageBar button):focus-visible{ - outline:var(--focus-ring-outline); - outline-offset:2px; - } - -.messageBar .closeButton{ - width:32px; - height:32px; - background:none; - border-radius:var(--message-bar-close-button-border-radius); - border:var(--message-bar-close-button-border); - - display:flex; - align-items:center; - justify-content:center; - } - -:is(.messageBar .closeButton)::before{ - content:""; - display:inline-block; - width:16px; - height:16px; - -webkit-mask-image:var(--closing-button-icon); - mask-image:var(--closing-button-icon); - -webkit-mask-size:cover; - mask-size:cover; - background-color:var(--message-bar-close-button-color); - } - -:is(.messageBar .closeButton):is(:hover,:active,:focus)::before{ - background-color:var(--message-bar-close-button-color-hover); - } - -:is(.messageBar .closeButton):hover{ - background-color:var(--message-bar-close-button-hover-bg-color); - } - -:is(.messageBar .closeButton):active{ - background-color:var(--message-bar-close-button-active-bg-color); - } - -:is(.messageBar .closeButton):focus{ - background-color:var(--message-bar-close-button-focus-bg-color); - } - -:is(.messageBar .closeButton) > span{ - display:inline-block; - width:0; - height:0; - overflow:hidden; - } - -#editorUndoBar{ - --text-primary-color:#15141a; - - --message-bar-icon:url(images/secondaryToolbarButton-documentProperties.svg); - --message-bar-icon-color:#0060df; - --message-bar-bg-color:#deeafc; - --message-bar-fg-color:var(--text-primary-color); - --message-bar-border-color:rgb(0 0 0 / 0.08); - - --undo-button-bg-color:rgb(21 20 26 / 0.07); - --undo-button-bg-color-hover:rgb(21 20 26 / 0.14); - --undo-button-bg-color-active:rgb(21 20 26 / 0.21); - - --undo-button-fg-color:var(--message-bar-fg-color); - --undo-button-fg-color-hover:var(--undo-button-fg-color); - --undo-button-fg-color-active:var(--undo-button-fg-color); - - --focus-ring-color:#0060df; - --focus-ring-outline:2px solid var(--focus-ring-color); -} - -@media (prefers-color-scheme: dark){ - -#editorUndoBar{ - --text-primary-color:#fbfbfe; - - --message-bar-icon-color:#73a7f3; - --message-bar-bg-color:#003070; - --message-bar-border-color:rgb(255 255 255 / 0.08); - - --undo-button-bg-color:rgb(255 255 255 / 0.08); - --undo-button-bg-color-hover:rgb(255 255 255 / 0.14); - --undo-button-bg-color-active:rgb(255 255 255 / 0.21); -} - } - -@media screen and (forced-colors: active){ - -#editorUndoBar{ - --text-primary-color:CanvasText; - - --message-bar-icon-color:CanvasText; - --message-bar-bg-color:Canvas; - --message-bar-border-color:CanvasText; - - --undo-button-bg-color:ButtonText; - --undo-button-bg-color-hover:SelectedItem; - --undo-button-bg-color-active:SelectedItem; - - --undo-button-fg-color:ButtonFace; - --undo-button-fg-color-hover:SelectedItemText; - --undo-button-fg-color-active:SelectedItemText; - - --focus-ring-color:CanvasText; -} - } - -#editorUndoBar{ - - position:fixed; - top:50px; - left:50%; - transform:translateX(-50%); - z-index:10; - - padding-block:8px; - padding-inline:16px 8px; - - font:menu; - font-size:15px; - - cursor:default; -} - -#editorUndoBar button{ - cursor:pointer; - } - -#editorUndoBar #editorUndoBarUndoButton{ - border-radius:4px; - font-weight:590; - line-height:19.5px; - color:var(--undo-button-fg-color); - border:none; - padding:4px 16px; - margin-inline-start:8px; - height:32px; - - background-color:var(--undo-button-bg-color); - } - -:is(#editorUndoBar #editorUndoBarUndoButton):hover{ - background-color:var(--undo-button-bg-color-hover); - color:var(--undo-button-fg-color-hover); - } - -:is(#editorUndoBar #editorUndoBarUndoButton):active{ - background-color:var(--undo-button-bg-color-active); - color:var(--undo-button-fg-color-active); - } - -#editorUndoBar > div{ - align-items:center; - } - -.dialog{ - --dialog-bg-color:white; - --dialog-border-color:white; - --dialog-shadow:0 2px 14px 0 rgb(58 57 68 / 0.2); - --text-primary-color:#15141a; - --text-secondary-color:#5b5b66; - --hover-filter:brightness(0.9); - --focus-ring-color:#0060df; - --focus-ring-outline:2px solid var(--focus-ring-color); - --link-fg-color:#0060df; - --link-hover-fg-color:#0250bb; - --separator-color:#f0f0f4; - - --textarea-border-color:#8f8f9d; - --textarea-bg-color:white; - --textarea-fg-color:var(--text-secondary-color); - - --radio-bg-color:#f0f0f4; - --radio-checked-bg-color:#fbfbfe; - --radio-border-color:#8f8f9d; - --radio-checked-border-color:#0060df; - - --button-secondary-bg-color:#f0f0f4; - --button-secondary-fg-color:var(--text-primary-color); - --button-secondary-border-color:var(--button-secondary-bg-color); - --button-secondary-hover-bg-color:var(--button-secondary-bg-color); - --button-secondary-hover-fg-color:var(--button-secondary-fg-color); - --button-secondary-hover-border-color:var(--button-secondary-hover-bg-color); - - --button-primary-bg-color:#0060df; - --button-primary-fg-color:#fbfbfe; - --button-primary-border-color:var(--button-primary-bg-color); - --button-primary-hover-bg-color:var(--button-primary-bg-color); - --button-primary-hover-fg-color:var(--button-primary-fg-color); - --button-primary-hover-border-color:var(--button-primary-hover-bg-color); -} - -@media (prefers-color-scheme: dark){ - -.dialog{ - --dialog-bg-color:#1c1b22; - --dialog-border-color:#1c1b22; - --dialog-shadow:0 2px 14px 0 #15141a; - --text-primary-color:#fbfbfe; - --text-secondary-color:#cfcfd8; - --focus-ring-color:#0df; - --hover-filter:brightness(1.4); - --link-fg-color:#0df; - --link-hover-fg-color:#80ebff; - --separator-color:#52525e; - - --textarea-bg-color:#42414d; - - --radio-bg-color:#2b2a33; - --radio-checked-bg-color:#15141a; - --radio-checked-border-color:#0df; - - --button-secondary-bg-color:#2b2a33; - --button-primary-bg-color:#0df; - --button-primary-fg-color:#15141a; -} - } - -@media screen and (forced-colors: active){ - -.dialog{ - --dialog-bg-color:Canvas; - --dialog-border-color:CanvasText; - --dialog-shadow:none; - --text-primary-color:CanvasText; - --text-secondary-color:CanvasText; - --hover-filter:none; - --focus-ring-color:ButtonBorder; - --link-fg-color:LinkText; - --link-hover-fg-color:LinkText; - --separator-color:CanvasText; - - --textarea-border-color:ButtonBorder; - --textarea-bg-color:Field; - --textarea-fg-color:ButtonText; - - --radio-bg-color:ButtonFace; - --radio-checked-bg-color:ButtonFace; - --radio-border-color:ButtonText; - --radio-checked-border-color:ButtonText; - - --button-secondary-bg-color:ButtonFace; - --button-secondary-fg-color:ButtonText; - --button-secondary-border-color:ButtonText; - --button-secondary-hover-bg-color:AccentColor; - --button-secondary-hover-fg-color:AccentColorText; - - --button-primary-bg-color:ButtonText; - --button-primary-fg-color:ButtonFace; - --button-primary-hover-bg-color:AccentColor; - --button-primary-hover-fg-color:AccentColorText; -} - } - -.dialog{ - - font:message-box; - font-size:13px; - font-weight:400; - line-height:150%; - border-radius:4px; - padding:12px 16px; - border:1px solid var(--dialog-border-color); - background:var(--dialog-bg-color); - color:var(--text-primary-color); - box-shadow:var(--dialog-shadow); -} - -:is(.dialog .mainContainer) *:focus-visible{ - outline:var(--focus-ring-outline); - outline-offset:2px; - } - -:is(.dialog .mainContainer) .title{ - display:flex; - width:auto; - flex-direction:column; - justify-content:flex-end; - align-items:flex-start; - gap:12px; - } - -:is(:is(.dialog .mainContainer) .title) > span{ - font-size:13px; - font-style:normal; - font-weight:590; - line-height:150%; - } - -:is(.dialog .mainContainer) .dialogSeparator{ - width:100%; - height:0; - margin-block:4px; - border-top:1px solid var(--separator-color); - border-bottom:none; - } - -:is(.dialog .mainContainer) .dialogButtonsGroup{ - display:flex; - gap:12px; - align-self:flex-end; - } - -:is(.dialog .mainContainer) .radio{ - display:flex; - flex-direction:column; - align-items:flex-start; - gap:4px; - } - -:is(:is(.dialog .mainContainer) .radio) > .radioButton{ - display:flex; - gap:8px; - align-self:stretch; - align-items:center; - } - -:is(:is(:is(.dialog .mainContainer) .radio) > .radioButton) input{ - -webkit-appearance:none; - -moz-appearance:none; - appearance:none; - box-sizing:border-box; - width:16px; - height:16px; - border-radius:50%; - background-color:var(--radio-bg-color); - border:1px solid var(--radio-border-color); - } - -:is(:is(:is(:is(.dialog .mainContainer) .radio) > .radioButton) input):hover{ - filter:var(--hover-filter); - } - -:is(:is(:is(:is(.dialog .mainContainer) .radio) > .radioButton) input):checked{ - background-color:var(--radio-checked-bg-color); - border:4px solid var(--radio-checked-border-color); - } - -:is(:is(.dialog .mainContainer) .radio) > .radioLabel{ - display:flex; - padding-inline-start:24px; - align-items:flex-start; - gap:10px; - align-self:stretch; - } - -:is(:is(:is(.dialog .mainContainer) .radio) > .radioLabel) > span{ - flex:1 0 0; - font-size:11px; - color:var(--text-secondary-color); - } - -:is(.dialog .mainContainer) button:not(:is(.toggle-button,.closeButton)){ - border-radius:4px; - border:1px solid; - font:menu; - font-weight:600; - padding:4px 16px; - width:auto; - height:32px; - } - -:is(:is(.dialog .mainContainer) button:not(:is(.toggle-button,.closeButton))):hover{ - cursor:pointer; - filter:var(--hover-filter); - } - -.secondaryButton:is(:is(.dialog .mainContainer) button:not(:is(.toggle-button,.closeButton))){ - color:var(--button-secondary-fg-color); - background-color:var(--button-secondary-bg-color); - border-color:var(--button-secondary-border-color); - } - -.secondaryButton:is(:is(.dialog .mainContainer) button:not(:is(.toggle-button,.closeButton))):hover{ - color:var(--button-secondary-hover-fg-color); - background-color:var(--button-secondary-hover-bg-color); - border-color:var(--button-secondary-hover-border-color); - } - -.primaryButton:is(:is(.dialog .mainContainer) button:not(:is(.toggle-button,.closeButton))){ - color:var(--button-primary-fg-color); - background-color:var(--button-primary-bg-color); - border-color:var(--button-primary-border-color); - opacity:1; - } - -.primaryButton:is(:is(.dialog .mainContainer) button:not(:is(.toggle-button,.closeButton))):hover{ - color:var(--button-primary-hover-fg-color); - background-color:var(--button-primary-hover-bg-color); - border-color:var(--button-primary-hover-border-color); - } - -:is(.dialog .mainContainer) a{ - color:var(--link-fg-color); - } - -:is(:is(.dialog .mainContainer) a):hover{ - color:var(--link-hover-fg-color); - } - -:is(.dialog .mainContainer) textarea{ - font:inherit; - padding:8px; - resize:none; - margin:0; - box-sizing:border-box; - border-radius:4px; - border:1px solid var(--textarea-border-color); - background:var(--textarea-bg-color); - color:var(--textarea-fg-color); - } - -:is(:is(.dialog .mainContainer) textarea):focus{ - outline-offset:0; - border-color:transparent; - } - -:is(:is(.dialog .mainContainer) textarea):disabled{ - pointer-events:none; - opacity:0.4; - } - -:is(.dialog .mainContainer) .messageBar{ - --message-bar-bg-color:#ffebcd; - --message-bar-fg-color:#15141a; - --message-bar-border-color:rgb(0 0 0 / 0.08); - --message-bar-icon:url(images/messageBar_warning.svg); - --message-bar-icon-color:#cd411e; - } - -@media (prefers-color-scheme: dark){ - -:is(.dialog .mainContainer) .messageBar{ - --message-bar-bg-color:#5a3100; - --message-bar-fg-color:#fbfbfe; - --message-bar-border-color:rgb(255 255 255 / 0.08); - --message-bar-icon-color:#e49c49; - } - } - -@media screen and (forced-colors: active){ - -:is(.dialog .mainContainer) .messageBar{ - --message-bar-bg-color:HighlightText; - --message-bar-fg-color:CanvasText; - --message-bar-border-color:CanvasText; - --message-bar-icon-color:CanvasText; - } - } - -:is(.dialog .mainContainer) .messageBar{ - - align-self:stretch; - } - -:is(:is(:is(.dialog .mainContainer) .messageBar) > div)::before,:is(:is(:is(.dialog .mainContainer) .messageBar) > div) > div{ - margin-block:4px; - } - -:is(:is(:is(.dialog .mainContainer) .messageBar) > div) > div{ - display:flex; - flex-direction:column; - align-items:flex-start; - gap:8px; - flex:1 0 0; - } - -:is(:is(:is(:is(.dialog .mainContainer) .messageBar) > div) > div) .title{ - font-size:13px; - font-weight:590; - } - -:is(:is(:is(:is(.dialog .mainContainer) .messageBar) > div) > div) .description{ - font-size:13px; - } - -:is(.dialog .mainContainer) .toggler{ - display:flex; - align-items:center; - gap:8px; - align-self:stretch; - } - -:is(:is(.dialog .mainContainer) .toggler) > .togglerLabel{ - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; - } - -.textLayer{ - position:absolute; - text-align:initial; - inset:0; - overflow:clip; - opacity:1; - line-height:1; - -webkit-text-size-adjust:none; - -moz-text-size-adjust:none; - text-size-adjust:none; - forced-color-adjust:none; - transform-origin:0 0; - caret-color:CanvasText; - z-index:0; -} - -.textLayer.highlighting{ - touch-action:none; - } - -.textLayer :is(span,br){ - color:transparent; - position:absolute; - white-space:pre; - cursor:text; - transform-origin:0% 0%; - } - -.textLayer > :not(.markedContent),.textLayer .markedContent span:not(.markedContent){ - z-index:1; - } - -.textLayer span.markedContent{ - top:0; - height:0; - } - -.textLayer span[role="img"]{ - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; - cursor:default; - } - -.textLayer .highlight{ - --highlight-bg-color:rgb(180 0 170 / 0.25); - --highlight-selected-bg-color:rgb(0 100 0 / 0.25); - --highlight-backdrop-filter:none; - --highlight-selected-backdrop-filter:none; - } - -@media screen and (forced-colors: active){ - -.textLayer .highlight{ - --highlight-bg-color:transparent; - --highlight-selected-bg-color:transparent; - --highlight-backdrop-filter:var(--hcm-highlight-filter); - --highlight-selected-backdrop-filter:var( - --hcm-highlight-selected-filter - ); - } - } - -.textLayer .highlight{ - - margin:-1px; - padding:1px; - background-color:var(--highlight-bg-color); - -webkit-backdrop-filter:var(--highlight-backdrop-filter); - backdrop-filter:var(--highlight-backdrop-filter); - border-radius:4px; - } - -.appended:is(.textLayer .highlight){ - position:initial; - } - -.begin:is(.textLayer .highlight){ - border-radius:4px 0 0 4px; - } - -.end:is(.textLayer .highlight){ - border-radius:0 4px 4px 0; - } - -.middle:is(.textLayer .highlight){ - border-radius:0; - } - -.selected:is(.textLayer .highlight){ - background-color:var(--highlight-selected-bg-color); - -webkit-backdrop-filter:var(--highlight-selected-backdrop-filter); - backdrop-filter:var(--highlight-selected-backdrop-filter); - } - -.textLayer ::-moz-selection{ - background:rgba(0 0 255 / 0.25); - background:color-mix(in srgb, AccentColor, transparent 75%); - } - -.textLayer ::selection{ - background:rgba(0 0 255 / 0.25); - background:color-mix(in srgb, AccentColor, transparent 75%); - } - -.textLayer br::-moz-selection{ - background:transparent; - } - -.textLayer br::selection{ - background:transparent; - } - -.textLayer .endOfContent{ - display:block; - position:absolute; - inset:100% 0 0; - z-index:0; - cursor:default; - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; - } - -.textLayer.selecting .endOfContent{ - top:0; - } - -.annotationLayer{ - --annotation-unfocused-field-background:url("data:image/svg+xml;charset=UTF-8,"); - --input-focus-border-color:Highlight; - --input-focus-outline:1px solid Canvas; - --input-unfocused-border-color:transparent; - --input-disabled-border-color:transparent; - --input-hover-border-color:black; - --link-outline:none; -} - -@media screen and (forced-colors: active){ - -.annotationLayer{ - --input-focus-border-color:CanvasText; - --input-unfocused-border-color:ActiveText; - --input-disabled-border-color:GrayText; - --input-hover-border-color:Highlight; - --link-outline:1.5px solid LinkText; -} - - .annotationLayer .textWidgetAnnotation :is(input,textarea):required,.annotationLayer .choiceWidgetAnnotation select:required,.annotationLayer .buttonWidgetAnnotation:is(.checkBox,.radioButton) input:required{ - outline:1.5px solid selectedItem; - } - - .annotationLayer .linkAnnotation{ - outline:var(--link-outline); - } - - :is(.annotationLayer .linkAnnotation):hover{ - -webkit-backdrop-filter:var(--hcm-highlight-filter); - backdrop-filter:var(--hcm-highlight-filter); - } - - :is(.annotationLayer .linkAnnotation) > a:hover{ - opacity:0 !important; - background:none !important; - box-shadow:none; - } - - .annotationLayer .popupAnnotation .popup{ - outline:calc(1.5px * var(--scale-factor)) solid CanvasText !important; - background-color:ButtonFace !important; - color:ButtonText !important; - } - - .annotationLayer .highlightArea:hover::after{ - position:absolute; - top:0; - left:0; - width:100%; - height:100%; - -webkit-backdrop-filter:var(--hcm-highlight-filter); - backdrop-filter:var(--hcm-highlight-filter); - content:""; - pointer-events:none; - } - - .annotationLayer .popupAnnotation.focused .popup{ - outline:calc(3px * var(--scale-factor)) solid Highlight !important; - } - } - -.annotationLayer{ - - position:absolute; - top:0; - left:0; - pointer-events:none; - transform-origin:0 0; -} - -.annotationLayer[data-main-rotation="90"] .norotate{ - transform:rotate(270deg) translateX(-100%); - } - -.annotationLayer[data-main-rotation="180"] .norotate{ - transform:rotate(180deg) translate(-100%, -100%); - } - -.annotationLayer[data-main-rotation="270"] .norotate{ - transform:rotate(90deg) translateY(-100%); - } - -.annotationLayer.disabled section,.annotationLayer.disabled .popup{ - pointer-events:none; - } - -.annotationLayer .annotationContent{ - position:absolute; - width:100%; - height:100%; - pointer-events:none; - } - -.freetext:is(.annotationLayer .annotationContent){ - background:transparent; - border:none; - inset:0; - overflow:visible; - white-space:nowrap; - font:10px sans-serif; - line-height:1.35; - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; - } - -.annotationLayer section{ - position:absolute; - text-align:initial; - pointer-events:auto; - box-sizing:border-box; - transform-origin:0 0; - } - -:is(.annotationLayer section):has(div.annotationContent) canvas.annotationContent{ - display:none; - } - -.textLayer.selecting ~ .annotationLayer section{ - pointer-events:none; - } - -.annotationLayer :is(.linkAnnotation,.buttonWidgetAnnotation.pushButton) > a{ - position:absolute; - font-size:1em; - top:0; - left:0; - width:100%; - height:100%; - } - -.annotationLayer :is(.linkAnnotation,.buttonWidgetAnnotation.pushButton):not(.hasBorder) > a:hover{ - opacity:0.2; - background-color:rgb(255 255 0); - box-shadow:0 2px 10px rgb(255 255 0); - } - -.annotationLayer .linkAnnotation.hasBorder:hover{ - background-color:rgb(255 255 0 / 0.2); - } - -.annotationLayer .hasBorder{ - background-size:100% 100%; - } - -.annotationLayer .textAnnotation img{ - position:absolute; - cursor:pointer; - width:100%; - height:100%; - top:0; - left:0; - } - -.annotationLayer .textWidgetAnnotation :is(input,textarea),.annotationLayer .choiceWidgetAnnotation select,.annotationLayer .buttonWidgetAnnotation:is(.checkBox,.radioButton) input{ - background-image:var(--annotation-unfocused-field-background); - border:2px solid var(--input-unfocused-border-color); - box-sizing:border-box; - font:calc(9px * var(--scale-factor)) sans-serif; - height:100%; - margin:0; - vertical-align:top; - width:100%; - } - -.annotationLayer .textWidgetAnnotation :is(input,textarea):required,.annotationLayer .choiceWidgetAnnotation select:required,.annotationLayer .buttonWidgetAnnotation:is(.checkBox,.radioButton) input:required{ - outline:1.5px solid red; - } - -.annotationLayer .choiceWidgetAnnotation select option{ - padding:0; - } - -.annotationLayer .buttonWidgetAnnotation.radioButton input{ - border-radius:50%; - } - -.annotationLayer .textWidgetAnnotation textarea{ - resize:none; - } - -.annotationLayer .textWidgetAnnotation [disabled]:is(input,textarea),.annotationLayer .choiceWidgetAnnotation select[disabled],.annotationLayer .buttonWidgetAnnotation:is(.checkBox,.radioButton) input[disabled]{ - background:none; - border:2px solid var(--input-disabled-border-color); - cursor:not-allowed; - } - -.annotationLayer .textWidgetAnnotation :is(input,textarea):hover,.annotationLayer .choiceWidgetAnnotation select:hover,.annotationLayer .buttonWidgetAnnotation:is(.checkBox,.radioButton) input:hover{ - border:2px solid var(--input-hover-border-color); - } - -.annotationLayer .textWidgetAnnotation :is(input,textarea):hover,.annotationLayer .choiceWidgetAnnotation select:hover,.annotationLayer .buttonWidgetAnnotation.checkBox input:hover{ - border-radius:2px; - } - -.annotationLayer .textWidgetAnnotation :is(input,textarea):focus,.annotationLayer .choiceWidgetAnnotation select:focus{ - background:none; - border:2px solid var(--input-focus-border-color); - border-radius:2px; - outline:var(--input-focus-outline); - } - -.annotationLayer .buttonWidgetAnnotation:is(.checkBox,.radioButton) :focus{ - background-image:none; - background-color:transparent; - } - -.annotationLayer .buttonWidgetAnnotation.checkBox :focus{ - border:2px solid var(--input-focus-border-color); - border-radius:2px; - outline:var(--input-focus-outline); - } - -.annotationLayer .buttonWidgetAnnotation.radioButton :focus{ - border:2px solid var(--input-focus-border-color); - outline:var(--input-focus-outline); - } - -.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::before,.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::after,.annotationLayer .buttonWidgetAnnotation.radioButton input:checked::before{ - background-color:CanvasText; - content:""; - display:block; - position:absolute; - } - -.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::before,.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::after{ - height:80%; - left:45%; - width:1px; - } - -.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::before{ - transform:rotate(45deg); - } - -.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::after{ - transform:rotate(-45deg); - } - -.annotationLayer .buttonWidgetAnnotation.radioButton input:checked::before{ - border-radius:50%; - height:50%; - left:25%; - top:25%; - width:50%; - } - -.annotationLayer .textWidgetAnnotation input.comb{ - font-family:monospace; - padding-left:2px; - padding-right:0; - } - -.annotationLayer .textWidgetAnnotation input.comb:focus{ - width:103%; - } - -.annotationLayer .buttonWidgetAnnotation:is(.checkBox,.radioButton) input{ - -webkit-appearance:none; - -moz-appearance:none; - appearance:none; - } - -.annotationLayer .fileAttachmentAnnotation .popupTriggerArea{ - height:100%; - width:100%; - } - -.annotationLayer .popupAnnotation{ - position:absolute; - font-size:calc(9px * var(--scale-factor)); - pointer-events:none; - width:-moz-max-content; - width:max-content; - max-width:45%; - height:auto; - } - -.annotationLayer .popup{ - background-color:rgb(255 255 153); - box-shadow:0 calc(2px * var(--scale-factor)) calc(5px * var(--scale-factor)) rgb(136 136 136); - border-radius:calc(2px * var(--scale-factor)); - outline:1.5px solid rgb(255 255 74); - padding:calc(6px * var(--scale-factor)); - cursor:pointer; - font:message-box; - white-space:normal; - word-wrap:break-word; - pointer-events:auto; - } - -.annotationLayer .popupAnnotation.focused .popup{ - outline-width:3px; - } - -.annotationLayer .popup *{ - font-size:calc(9px * var(--scale-factor)); - } - -.annotationLayer .popup > .header{ - display:inline-block; - } - -.annotationLayer .popup > .header h1{ - display:inline; - } - -.annotationLayer .popup > .header .popupDate{ - display:inline-block; - margin-left:calc(5px * var(--scale-factor)); - width:-moz-fit-content; - width:fit-content; - } - -.annotationLayer .popupContent{ - border-top:1px solid rgb(51 51 51); - margin-top:calc(2px * var(--scale-factor)); - padding-top:calc(2px * var(--scale-factor)); - } - -.annotationLayer .richText > *{ - white-space:pre-wrap; - font-size:calc(9px * var(--scale-factor)); - } - -.annotationLayer .popupTriggerArea{ - cursor:pointer; - } - -.annotationLayer section svg{ - position:absolute; - width:100%; - height:100%; - top:0; - left:0; - } - -.annotationLayer .annotationTextContent{ - position:absolute; - width:100%; - height:100%; - opacity:0; - color:transparent; - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; - pointer-events:none; - } - -:is(.annotationLayer .annotationTextContent) span{ - width:100%; - display:inline-block; - } - -.annotationLayer svg.quadrilateralsContainer{ - contain:strict; - width:0; - height:0; - position:absolute; - top:0; - left:0; - z-index:-1; - } - -:root{ - --xfa-unfocused-field-background:url("data:image/svg+xml;charset=UTF-8,"); - --xfa-focus-outline:auto; -} - -@media screen and (forced-colors: active){ - :root{ - --xfa-focus-outline:2px solid CanvasText; - } - .xfaLayer *:required{ - outline:1.5px solid selectedItem; - } -} - -.xfaLayer{ - background-color:transparent; -} - -.xfaLayer .highlight{ - margin:-1px; - padding:1px; - background-color:rgb(239 203 237); - border-radius:4px; -} - -.xfaLayer .highlight.appended{ - position:initial; -} - -.xfaLayer .highlight.begin{ - border-radius:4px 0 0 4px; -} - -.xfaLayer .highlight.end{ - border-radius:0 4px 4px 0; -} - -.xfaLayer .highlight.middle{ - border-radius:0; -} - -.xfaLayer .highlight.selected{ - background-color:rgb(203 223 203); -} - -.xfaPage{ - overflow:hidden; - position:relative; -} - -.xfaContentarea{ - position:absolute; -} - -.xfaPrintOnly{ - display:none; -} - -.xfaLayer{ - position:absolute; - text-align:initial; - top:0; - left:0; - transform-origin:0 0; - line-height:1.2; -} - -.xfaLayer *{ - color:inherit; - font:inherit; - font-style:inherit; - font-weight:inherit; - font-kerning:inherit; - letter-spacing:-0.01px; - text-align:inherit; - text-decoration:inherit; - box-sizing:border-box; - background-color:transparent; - padding:0; - margin:0; - pointer-events:auto; - line-height:inherit; -} - -.xfaLayer *:required{ - outline:1.5px solid red; -} - -.xfaLayer div, -.xfaLayer svg, -.xfaLayer svg *{ - pointer-events:none; -} - -.xfaLayer a{ - color:blue; -} - -.xfaRich li{ - margin-left:3em; -} - -.xfaFont{ - color:black; - font-weight:normal; - font-kerning:none; - font-size:10px; - font-style:normal; - letter-spacing:0; - text-decoration:none; - vertical-align:0; -} - -.xfaCaption{ - overflow:hidden; - flex:0 0 auto; -} - -.xfaCaptionForCheckButton{ - overflow:hidden; - flex:1 1 auto; -} - -.xfaLabel{ - height:100%; - width:100%; -} - -.xfaLeft{ - display:flex; - flex-direction:row; - align-items:center; -} - -.xfaRight{ - display:flex; - flex-direction:row-reverse; - align-items:center; -} - -:is(.xfaLeft, .xfaRight) > :is(.xfaCaption, .xfaCaptionForCheckButton){ - max-height:100%; -} - -.xfaTop{ - display:flex; - flex-direction:column; - align-items:flex-start; -} - -.xfaBottom{ - display:flex; - flex-direction:column-reverse; - align-items:flex-start; -} - -:is(.xfaTop, .xfaBottom) > :is(.xfaCaption, .xfaCaptionForCheckButton){ - width:100%; -} - -.xfaBorder{ - background-color:transparent; - position:absolute; - pointer-events:none; -} - -.xfaWrapped{ - width:100%; - height:100%; -} - -:is(.xfaTextfield, .xfaSelect):focus{ - background-image:none; - background-color:transparent; - outline:var(--xfa-focus-outline); - outline-offset:-1px; -} - -:is(.xfaCheckbox, .xfaRadio):focus{ - outline:var(--xfa-focus-outline); -} - -.xfaTextfield, -.xfaSelect{ - height:100%; - width:100%; - flex:1 1 auto; - border:none; - resize:none; - background-image:var(--xfa-unfocused-field-background); -} - -.xfaSelect{ - padding-inline:2px; -} - -:is(.xfaTop, .xfaBottom) > :is(.xfaTextfield, .xfaSelect){ - flex:0 1 auto; -} - -.xfaButton{ - cursor:pointer; - width:100%; - height:100%; - border:none; - text-align:center; -} - -.xfaLink{ - width:100%; - height:100%; - position:absolute; - top:0; - left:0; -} - -.xfaCheckbox, -.xfaRadio{ - width:100%; - height:100%; - flex:0 0 auto; - border:none; -} - -.xfaRich{ - white-space:pre-wrap; - width:100%; - height:100%; -} - -.xfaImage{ - -o-object-position:left top; - object-position:left top; - -o-object-fit:contain; - object-fit:contain; - width:100%; - height:100%; -} - -.xfaLrTb, -.xfaRlTb, -.xfaTb{ - display:flex; - flex-direction:column; - align-items:stretch; -} - -.xfaLr{ - display:flex; - flex-direction:row; - align-items:stretch; -} - -.xfaRl{ - display:flex; - flex-direction:row-reverse; - align-items:stretch; -} - -.xfaTb > div{ - justify-content:left; -} - -.xfaPosition{ - position:relative; -} - -.xfaArea{ - position:relative; -} - -.xfaValignMiddle{ - display:flex; - align-items:center; -} - -.xfaTable{ - display:flex; - flex-direction:column; - align-items:stretch; -} - -.xfaTable .xfaRow{ - display:flex; - flex-direction:row; - align-items:stretch; -} - -.xfaTable .xfaRlRow{ - display:flex; - flex-direction:row-reverse; - align-items:stretch; - flex:1; -} - -.xfaTable .xfaRlRow > div{ - flex:1; -} - -:is(.xfaNonInteractive, .xfaDisabled, .xfaReadOnly) :is(input, textarea){ - background:initial; -} - -@media print{ - .xfaTextfield, - .xfaSelect{ - background:transparent; - } - - .xfaSelect{ - -webkit-appearance:none; - -moz-appearance:none; - appearance:none; - text-indent:1px; - text-overflow:""; - } -} - -.canvasWrapper svg{ - transform:none; - } - -.moving:is(.canvasWrapper svg){ - z-index:100000; - } - -[data-main-rotation="90"]:is(.highlight:is(.canvasWrapper svg),.highlightOutline:is(.canvasWrapper svg)) mask,[data-main-rotation="90"]:is(.highlight:is(.canvasWrapper svg),.highlightOutline:is(.canvasWrapper svg)) use:not(.clip,.mask){ - transform:matrix(0, 1, -1, 0, 1, 0); - } - -[data-main-rotation="180"]:is(.highlight:is(.canvasWrapper svg),.highlightOutline:is(.canvasWrapper svg)) mask,[data-main-rotation="180"]:is(.highlight:is(.canvasWrapper svg),.highlightOutline:is(.canvasWrapper svg)) use:not(.clip,.mask){ - transform:matrix(-1, 0, 0, -1, 1, 1); - } - -[data-main-rotation="270"]:is(.highlight:is(.canvasWrapper svg),.highlightOutline:is(.canvasWrapper svg)) mask,[data-main-rotation="270"]:is(.highlight:is(.canvasWrapper svg),.highlightOutline:is(.canvasWrapper svg)) use:not(.clip,.mask){ - transform:matrix(0, -1, 1, 0, 0, 1); - } - -.draw:is(.canvasWrapper svg){ - position:absolute; - mix-blend-mode:normal; - } - -.draw[data-draw-rotation="90"]:is(.canvasWrapper svg){ - transform:rotate(90deg); - } - -.draw[data-draw-rotation="180"]:is(.canvasWrapper svg){ - transform:rotate(180deg); - } - -.draw[data-draw-rotation="270"]:is(.canvasWrapper svg){ - transform:rotate(270deg); - } - -.highlight:is(.canvasWrapper svg){ - --blend-mode:multiply; - } - -@media screen and (forced-colors: active){ - -.highlight:is(.canvasWrapper svg){ - --blend-mode:difference; - } - } - -.highlight:is(.canvasWrapper svg){ - - position:absolute; - mix-blend-mode:var(--blend-mode); - } - -.highlight:is(.canvasWrapper svg):not(.free){ - fill-rule:evenodd; - } - -.highlightOutline:is(.canvasWrapper svg){ - position:absolute; - mix-blend-mode:normal; - fill-rule:evenodd; - fill:none; - } - -.highlightOutline.hovered:is(.canvasWrapper svg):not(.free):not(.selected){ - stroke:var(--hover-outline-color); - stroke-width:var(--outline-width); - } - -.highlightOutline.selected:is(.canvasWrapper svg):not(.free) .mainOutline{ - stroke:var(--outline-around-color); - stroke-width:calc( - var(--outline-width) + 2 * var(--outline-around-width) - ); - } - -.highlightOutline.selected:is(.canvasWrapper svg):not(.free) .secondaryOutline{ - stroke:var(--outline-color); - stroke-width:var(--outline-width); - } - -.highlightOutline.free.hovered:is(.canvasWrapper svg):not(.selected){ - stroke:var(--hover-outline-color); - stroke-width:calc(2 * var(--outline-width)); - } - -.highlightOutline.free.selected:is(.canvasWrapper svg) .mainOutline{ - stroke:var(--outline-around-color); - stroke-width:calc( - 2 * (var(--outline-width) + var(--outline-around-width)) - ); - } - -.highlightOutline.free.selected:is(.canvasWrapper svg) .secondaryOutline{ - stroke:var(--outline-color); - stroke-width:calc(2 * var(--outline-width)); - } - -.toggle-button{ - --button-background-color:#f0f0f4; - --button-background-color-hover:#e0e0e6; - --button-background-color-active:#cfcfd8; - --color-accent-primary:#0060df; - --color-accent-primary-hover:#0250bb; - --color-accent-primary-active:#054096; - --border-interactive-color:#8f8f9d; - --border-radius-circle:9999px; - --border-width:1px; - --size-item-small:16px; - --size-item-large:32px; - --color-canvas:white; -} - -@media (prefers-color-scheme: dark){ - -.toggle-button{ - --button-background-color:color-mix(in srgb, currentColor 7%, transparent); - --button-background-color-hover:color-mix( - in srgb, - currentColor 14%, - transparent - ); - --button-background-color-active:color-mix( - in srgb, - currentColor 21%, - transparent - ); - --color-accent-primary:#0df; - --color-accent-primary-hover:#80ebff; - --color-accent-primary-active:#aaf2ff; - --border-interactive-color:#bfbfc9; - --color-canvas:#1c1b22; -} - } - -@media (forced-colors: active){ - -.toggle-button{ - --color-accent-primary:ButtonText; - --color-accent-primary-hover:SelectedItem; - --color-accent-primary-active:SelectedItem; - --border-interactive-color:ButtonText; - --button-background-color:ButtonFace; - --border-interactive-color-hover:SelectedItem; - --border-interactive-color-active:SelectedItem; - --border-interactive-color-disabled:GrayText; - --color-canvas:ButtonText; -} - } - -.toggle-button{ - - --toggle-background-color:var(--button-background-color); - --toggle-background-color-hover:var(--button-background-color-hover); - --toggle-background-color-active:var(--button-background-color-active); - --toggle-background-color-pressed:var(--color-accent-primary); - --toggle-background-color-pressed-hover:var(--color-accent-primary-hover); - --toggle-background-color-pressed-active:var(--color-accent-primary-active); - --toggle-border-color:var(--border-interactive-color); - --toggle-border-color-hover:var(--toggle-border-color); - --toggle-border-color-active:var(--toggle-border-color); - --toggle-border-radius:var(--border-radius-circle); - --toggle-border-width:var(--border-width); - --toggle-height:var(--size-item-small); - --toggle-width:var(--size-item-large); - --toggle-dot-background-color:var(--toggle-border-color); - --toggle-dot-background-color-hover:var(--toggle-dot-background-color); - --toggle-dot-background-color-active:var(--toggle-dot-background-color); - --toggle-dot-background-color-on-pressed:var(--color-canvas); - --toggle-dot-margin:1px; - --toggle-dot-height:calc( - var(--toggle-height) - 2 * var(--toggle-dot-margin) - 2 * - var(--toggle-border-width) - ); - --toggle-dot-width:var(--toggle-dot-height); - --toggle-dot-transform-x:calc( - var(--toggle-width) - 4 * var(--toggle-dot-margin) - var(--toggle-dot-width) - ); - - -webkit-appearance:none; - - -moz-appearance:none; - - appearance:none; - padding:0; - margin:0; - border:var(--toggle-border-width) solid var(--toggle-border-color); - height:var(--toggle-height); - width:var(--toggle-width); - border-radius:var(--toggle-border-radius); - background:var(--toggle-background-color); - box-sizing:border-box; - flex-shrink:0; -} - -.toggle-button:focus-visible{ - outline:var(--focus-outline); - outline-offset:var(--focus-outline-offset); - } - -.toggle-button:enabled:hover{ - background:var(--toggle-background-color-hover); - border-color:var(--toggle-border-color); - } - -.toggle-button:enabled:active{ - background:var(--toggle-background-color-active); - border-color:var(--toggle-border-color); - } - -.toggle-button[aria-pressed="true"]{ - background:var(--toggle-background-color-pressed); - border-color:transparent; - } - -.toggle-button[aria-pressed="true"]:enabled:hover{ - background:var(--toggle-background-color-pressed-hover); - border-color:transparent; - } - -.toggle-button[aria-pressed="true"]:enabled:active{ - background:var(--toggle-background-color-pressed-active); - border-color:transparent; - } - -.toggle-button::before{ - display:block; - content:""; - background-color:var(--toggle-dot-background-color); - height:var(--toggle-dot-height); - width:var(--toggle-dot-width); - margin:var(--toggle-dot-margin); - border-radius:var(--toggle-border-radius); - translate:0; - } - -.toggle-button[aria-pressed="true"]::before{ - translate:var(--toggle-dot-transform-x); - background-color:var(--toggle-dot-background-color-on-pressed); - } - -.toggle-button[aria-pressed="true"]:enabled:hover::before,.toggle-button[aria-pressed="true"]:enabled:active::before{ - background-color:var(--toggle-dot-background-color-on-pressed); - } - -[dir="rtl"] .toggle-button[aria-pressed="true"]::before{ - translate:calc(-1 * var(--toggle-dot-transform-x)); - } - -@media (prefers-reduced-motion: no-preference){ - .toggle-button::before{ - transition:translate 100ms; - } - } - -@media (prefers-contrast){ - .toggle-button:enabled:hover{ - border-color:var(--toggle-border-color-hover); - } - - .toggle-button:enabled:active{ - border-color:var(--toggle-border-color-active); - } - - .toggle-button[aria-pressed="true"]:enabled{ - border-color:var(--toggle-border-color); - position:relative; - } - - .toggle-button[aria-pressed="true"]:enabled:hover,.toggle-button[aria-pressed="true"]:enabled:hover:active{ - border-color:var(--toggle-border-color-hover); - } - - .toggle-button[aria-pressed="true"]:enabled:active{ - background-color:var(--toggle-dot-background-color-active); - border-color:var(--toggle-dot-background-color-hover); - } - - .toggle-button:hover::before,.toggle-button:active::before{ - background-color:var(--toggle-dot-background-color-hover); - } - } - -@media (forced-colors){ - -.toggle-button{ - --toggle-dot-background-color:var(--color-accent-primary); - --toggle-dot-background-color-hover:var(--color-accent-primary-hover); - --toggle-dot-background-color-active:var(--color-accent-primary-active); - --toggle-dot-background-color-on-pressed:var(--button-background-color); - --toggle-background-color-disabled:var(--button-background-color-disabled); - --toggle-border-color-hover:var(--border-interactive-color-hover); - --toggle-border-color-active:var(--border-interactive-color-active); - --toggle-border-color-disabled:var(--border-interactive-color-disabled); -} - - .toggle-button[aria-pressed="true"]:enabled::after{ - border:1px solid var(--button-background-color); - content:""; - position:absolute; - height:var(--toggle-height); - width:var(--toggle-width); - display:block; - border-radius:var(--toggle-border-radius); - inset:-2px; - } - - .toggle-button[aria-pressed="true"]:enabled:active::after{ - border-color:var(--toggle-border-color-active); - } - } - -:root{ - --outline-width:2px; - --outline-color:#0060df; - --outline-around-width:1px; - --outline-around-color:#f0f0f4; - --hover-outline-around-color:var(--outline-around-color); - --focus-outline:solid var(--outline-width) var(--outline-color); - --unfocus-outline:solid var(--outline-width) transparent; - --focus-outline-around:solid var(--outline-around-width) var(--outline-around-color); - --hover-outline-color:#8f8f9d; - --hover-outline:solid var(--outline-width) var(--hover-outline-color); - --hover-outline-around:solid var(--outline-around-width) var(--hover-outline-around-color); - --freetext-line-height:1.35; - --freetext-padding:2px; - --resizer-bg-color:var(--outline-color); - --resizer-size:6px; - --resizer-shift:calc( - 0px - (var(--outline-width) + var(--resizer-size)) / 2 - - var(--outline-around-width) - ); - --editorFreeText-editing-cursor:text; - --editorInk-editing-cursor:url(images/cursor-editorInk.svg) 0 16, pointer; - --editorHighlight-editing-cursor:url(images/cursor-editorTextHighlight.svg) 24 24, text; - --editorFreeHighlight-editing-cursor:url(images/cursor-editorFreeHighlight.svg) 1 18, pointer; - - --new-alt-text-warning-image:url(images/altText_warning.svg); -} -.visuallyHidden{ - position:absolute; - top:0; - left:0; - border:0; - margin:0; - padding:0; - width:0; - height:0; - overflow:hidden; - white-space:nowrap; - font-size:0; -} - -.textLayer.highlighting{ - cursor:var(--editorFreeHighlight-editing-cursor); - } - -.textLayer.highlighting:not(.free) span{ - cursor:var(--editorHighlight-editing-cursor); - } - -[role="img"]:is(.textLayer.highlighting:not(.free) span){ - cursor:var(--editorFreeHighlight-editing-cursor); - } - -.textLayer.highlighting.free span{ - cursor:var(--editorFreeHighlight-editing-cursor); - } - -:is(#viewerContainer.pdfPresentationMode:fullscreen,.annotationEditorLayer.disabled) .noAltTextBadge{ - display:none !important; - } - -@media (min-resolution: 1.1dppx){ - :root{ - --editorFreeText-editing-cursor:url(images/cursor-editorFreeText.svg) 0 16, text; - } -} - -@media screen and (forced-colors: active){ - :root{ - --outline-color:CanvasText; - --outline-around-color:ButtonFace; - --resizer-bg-color:ButtonText; - --hover-outline-color:Highlight; - --hover-outline-around-color:SelectedItemText; - } -} - -[data-editor-rotation="90"]{ - transform:rotate(90deg); -} - -[data-editor-rotation="180"]{ - transform:rotate(180deg); -} - -[data-editor-rotation="270"]{ - transform:rotate(270deg); -} - -.annotationEditorLayer{ - background:transparent; - position:absolute; - inset:0; - font-size:calc(100px * var(--scale-factor)); - transform-origin:0 0; - cursor:auto; -} - -.annotationEditorLayer .selectedEditor{ - z-index:100000 !important; - } - -.annotationEditorLayer.drawing *{ - pointer-events:none !important; - } - -.annotationEditorLayer.waiting{ - content:""; - cursor:wait; - position:absolute; - inset:0; - width:100%; - height:100%; -} - -.annotationEditorLayer.disabled{ - pointer-events:none; -} - -.annotationEditorLayer.freetextEditing{ - cursor:var(--editorFreeText-editing-cursor); -} - -.annotationEditorLayer.inkEditing{ - cursor:var(--editorInk-editing-cursor); -} - -.annotationEditorLayer .draw{ - box-sizing:border-box; -} - -.annotationEditorLayer :is(.freeTextEditor, .inkEditor, .stampEditor){ - position:absolute; - background:transparent; - z-index:1; - transform-origin:0 0; - cursor:auto; - max-width:100%; - max-height:100%; - border:var(--unfocus-outline); -} - -.draggable.selectedEditor:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)){ - cursor:move; - } - -.selectedEditor:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)){ - border:var(--focus-outline); - outline:var(--focus-outline-around); - } - -.selectedEditor:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor))::before{ - content:""; - position:absolute; - inset:0; - border:var(--focus-outline-around); - pointer-events:none; - } - -:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)):hover:not(.selectedEditor){ - border:var(--hover-outline); - outline:var(--hover-outline-around); - } - -:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)):hover:not(.selectedEditor)::before{ - content:""; - position:absolute; - inset:0; - border:var(--focus-outline-around); - } - -:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar{ - --editor-toolbar-delete-image:url(images/editor-toolbar-delete.svg); - --editor-toolbar-bg-color:#f0f0f4; - --editor-toolbar-highlight-image:url(images/toolbarButton-editorHighlight.svg); - --editor-toolbar-fg-color:#2e2e56; - --editor-toolbar-border-color:#8f8f9d; - --editor-toolbar-hover-border-color:var(--editor-toolbar-border-color); - --editor-toolbar-hover-bg-color:#e0e0e6; - --editor-toolbar-hover-fg-color:var(--editor-toolbar-fg-color); - --editor-toolbar-hover-outline:none; - --editor-toolbar-focus-outline-color:#0060df; - --editor-toolbar-shadow:0 2px 6px 0 rgb(58 57 68 / 0.2); - --editor-toolbar-vert-offset:6px; - --editor-toolbar-height:28px; - --editor-toolbar-padding:2px; - --alt-text-done-color:#2ac3a2; - --alt-text-warning-color:#0090ed; - --alt-text-hover-done-color:var(--alt-text-done-color); - --alt-text-hover-warning-color:var(--alt-text-warning-color); - } - -@media (prefers-color-scheme: dark){ - -:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar{ - --editor-toolbar-bg-color:#2b2a33; - --editor-toolbar-fg-color:#fbfbfe; - --editor-toolbar-hover-bg-color:#52525e; - --editor-toolbar-focus-outline-color:#0df; - --alt-text-done-color:#54ffbd; - --alt-text-warning-color:#80ebff; - } - } - -@media screen and (forced-colors: active){ - -:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar{ - --editor-toolbar-bg-color:ButtonFace; - --editor-toolbar-fg-color:ButtonText; - --editor-toolbar-border-color:ButtonText; - --editor-toolbar-hover-border-color:AccentColor; - --editor-toolbar-hover-bg-color:ButtonFace; - --editor-toolbar-hover-fg-color:AccentColor; - --editor-toolbar-hover-outline:2px solid var(--editor-toolbar-hover-border-color); - --editor-toolbar-focus-outline-color:ButtonBorder; - --editor-toolbar-shadow:none; - --alt-text-done-color:var(--editor-toolbar-fg-color); - --alt-text-warning-color:var(--editor-toolbar-fg-color); - --alt-text-hover-done-color:var(--editor-toolbar-hover-fg-color); - --alt-text-hover-warning-color:var(--editor-toolbar-hover-fg-color); - } - } - -:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar{ - - display:flex; - width:-moz-fit-content; - width:fit-content; - height:var(--editor-toolbar-height); - flex-direction:column; - justify-content:center; - align-items:center; - cursor:default; - pointer-events:auto; - box-sizing:content-box; - padding:var(--editor-toolbar-padding); - - position:absolute; - inset-inline-end:0; - inset-block-start:calc(100% + var(--editor-toolbar-vert-offset)); - - border-radius:6px; - background-color:var(--editor-toolbar-bg-color); - border:1px solid var(--editor-toolbar-border-color); - box-shadow:var(--editor-toolbar-shadow); - } - -.hidden:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar){ - display:none; - } - -:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar):has(:focus-visible){ - border-color:transparent; - } - -[dir="ltr"] :is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar){ - transform-origin:100% 0; - } - -[dir="rtl"] :is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar){ - transform-origin:0 0; - } - -:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons{ - display:flex; - justify-content:center; - align-items:center; - gap:0; - height:100%; - } - -:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) button{ - padding:0; - } - -:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .divider{ - width:0; - height:calc( - 2 * var(--editor-toolbar-padding) + var(--editor-toolbar-height) - ); - border-left:1px solid var(--editor-toolbar-border-color); - border-right:none; - display:inline-block; - margin-inline:2px; - } - -:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .highlightButton{ - width:var(--editor-toolbar-height); - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .highlightButton)::before{ - content:""; - -webkit-mask-image:var(--editor-toolbar-highlight-image); - mask-image:var(--editor-toolbar-highlight-image); - -webkit-mask-repeat:no-repeat; - mask-repeat:no-repeat; - -webkit-mask-position:center; - mask-position:center; - display:inline-block; - background-color:var(--editor-toolbar-fg-color); - width:100%; - height:100%; - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .highlightButton):hover::before{ - background-color:var(--editor-toolbar-hover-fg-color); - } - -:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .delete{ - width:var(--editor-toolbar-height); - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .delete)::before{ - content:""; - -webkit-mask-image:var(--editor-toolbar-delete-image); - mask-image:var(--editor-toolbar-delete-image); - -webkit-mask-repeat:no-repeat; - mask-repeat:no-repeat; - -webkit-mask-position:center; - mask-position:center; - display:inline-block; - background-color:var(--editor-toolbar-fg-color); - width:100%; - height:100%; - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .delete):hover::before{ - background-color:var(--editor-toolbar-hover-fg-color); - } - -:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) > *{ - height:var(--editor-toolbar-height); - } - -:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) > :not(.divider){ - border:none; - background-color:transparent; - cursor:pointer; - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) > :not(.divider)):hover{ - border-radius:2px; - background-color:var(--editor-toolbar-hover-bg-color); - color:var(--editor-toolbar-hover-fg-color); - outline:var(--editor-toolbar-hover-outline); - outline-offset:1px; - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) > :not(.divider)):hover:active{ - outline:none; - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) > :not(.divider)):focus-visible{ - border-radius:2px; - outline:2px solid var(--editor-toolbar-focus-outline-color); - } - -:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText{ - --alt-text-add-image:url(images/altText_add.svg); - --alt-text-done-image:url(images/altText_done.svg); - - display:flex; - align-items:center; - justify-content:center; - width:-moz-max-content; - width:max-content; - padding-inline:8px; - pointer-events:all; - font:menu; - font-weight:590; - font-size:12px; - color:var(--editor-toolbar-fg-color); - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText):disabled{ - pointer-events:none; - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText)::before{ - content:""; - -webkit-mask-image:var(--alt-text-add-image); - mask-image:var(--alt-text-add-image); - -webkit-mask-repeat:no-repeat; - mask-repeat:no-repeat; - -webkit-mask-position:center; - mask-position:center; - display:inline-block; - width:12px; - height:13px; - background-color:var(--editor-toolbar-fg-color); - margin-inline-end:4px; - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText):hover::before{ - background-color:var(--editor-toolbar-hover-fg-color); - } - -.done:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText)::before{ - -webkit-mask-image:var(--alt-text-done-image); - mask-image:var(--alt-text-done-image); - } - -.new:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText)::before{ - width:16px; - height:16px; - -webkit-mask-image:var(--new-alt-text-warning-image); - mask-image:var(--new-alt-text-warning-image); - background-color:var(--alt-text-warning-color); - -webkit-mask-size:cover; - mask-size:cover; - } - -.new:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText):hover::before{ - background-color:var(--alt-text-hover-warning-color); - } - -.new.done:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText)::before{ - -webkit-mask-image:var(--alt-text-done-image); - mask-image:var(--alt-text-done-image); - background-color:var(--alt-text-done-color); - } - -.new.done:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText):hover::before{ - background-color:var(--alt-text-hover-done-color); - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText) .tooltip{ - display:none; - word-wrap:anywhere; - } - -.show:is(:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText) .tooltip){ - --alt-text-tooltip-bg:#f0f0f4; - --alt-text-tooltip-fg:#15141a; - --alt-text-tooltip-border:#8f8f9d; - --alt-text-tooltip-shadow:0px 2px 6px 0px rgb(58 57 68 / 0.2); - } - -@media (prefers-color-scheme: dark){ - -.show:is(:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText) .tooltip){ - --alt-text-tooltip-bg:#1c1b22; - --alt-text-tooltip-fg:#fbfbfe; - --alt-text-tooltip-shadow:0px 2px 6px 0px #15141a; - } - } - -@media screen and (forced-colors: active){ - -.show:is(:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText) .tooltip){ - --alt-text-tooltip-bg:Canvas; - --alt-text-tooltip-fg:CanvasText; - --alt-text-tooltip-border:CanvasText; - --alt-text-tooltip-shadow:none; - } - } - -.show:is(:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText) .tooltip){ - - display:inline-flex; - flex-direction:column; - align-items:center; - justify-content:center; - position:absolute; - top:calc(100% + 2px); - inset-inline-start:0; - padding-block:2px 3px; - padding-inline:3px; - max-width:300px; - width:-moz-max-content; - width:max-content; - height:auto; - font-size:12px; - - border:0.5px solid var(--alt-text-tooltip-border); - background:var(--alt-text-tooltip-bg); - box-shadow:var(--alt-text-tooltip-shadow); - color:var(--alt-text-tooltip-fg); - - pointer-events:none; - } - -.annotationEditorLayer .freeTextEditor{ - padding:calc(var(--freetext-padding) * var(--scale-factor)); - width:auto; - height:auto; - touch-action:none; -} - -.annotationEditorLayer .freeTextEditor .internal{ - background:transparent; - border:none; - inset:0; - overflow:visible; - white-space:nowrap; - font:10px sans-serif; - line-height:var(--freetext-line-height); - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; -} - -.annotationEditorLayer .freeTextEditor .overlay{ - position:absolute; - display:none; - background:transparent; - inset:0; - width:100%; - height:100%; -} - -.annotationEditorLayer freeTextEditor .overlay.enabled{ - display:block; -} - -.annotationEditorLayer .freeTextEditor .internal:empty::before{ - content:attr(default-content); - color:gray; -} - -.annotationEditorLayer .freeTextEditor .internal:focus{ - outline:none; - -webkit-user-select:auto; - -moz-user-select:auto; - user-select:auto; -} - -.annotationEditorLayer .inkEditor{ - width:100%; - height:100%; -} - -.annotationEditorLayer .inkEditor.editing{ - cursor:inherit; -} - -.annotationEditorLayer .inkEditor .inkEditorCanvas{ - position:absolute; - inset:0; - width:100%; - height:100%; - touch-action:none; -} - -.annotationEditorLayer .stampEditor{ - width:auto; - height:auto; -} - -:is(.annotationEditorLayer .stampEditor) canvas{ - position:absolute; - width:100%; - height:100%; - margin:0; - top:0; - left:0; - } - -:is(.annotationEditorLayer .stampEditor) .noAltTextBadge{ - --no-alt-text-badge-border-color:#f0f0f4; - --no-alt-text-badge-bg-color:#cfcfd8; - --no-alt-text-badge-fg-color:#5b5b66; - } - -@media (prefers-color-scheme: dark){ - -:is(.annotationEditorLayer .stampEditor) .noAltTextBadge{ - --no-alt-text-badge-border-color:#52525e; - --no-alt-text-badge-bg-color:#fbfbfe; - --no-alt-text-badge-fg-color:#15141a; - } - } - -@media screen and (forced-colors: active){ - -:is(.annotationEditorLayer .stampEditor) .noAltTextBadge{ - --no-alt-text-badge-border-color:ButtonText; - --no-alt-text-badge-bg-color:ButtonFace; - --no-alt-text-badge-fg-color:ButtonText; - } - } - -:is(.annotationEditorLayer .stampEditor) .noAltTextBadge{ - - position:absolute; - inset-inline-end:5px; - inset-block-end:5px; - display:inline-flex; - width:32px; - height:32px; - padding:3px; - justify-content:center; - align-items:center; - pointer-events:none; - z-index:1; - - border-radius:2px; - border:1px solid var(--no-alt-text-badge-border-color); - background:var(--no-alt-text-badge-bg-color); - } - -:is(:is(.annotationEditorLayer .stampEditor) .noAltTextBadge)::before{ - content:""; - display:inline-block; - width:16px; - height:16px; - -webkit-mask-image:var(--new-alt-text-warning-image); - mask-image:var(--new-alt-text-warning-image); - -webkit-mask-size:cover; - mask-size:cover; - background-color:var(--no-alt-text-badge-fg-color); - } - -:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers{ - position:absolute; - inset:0; - } - -.hidden:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers){ - display:none; - } - -:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer{ - width:var(--resizer-size); - height:var(--resizer-size); - background:content-box var(--resizer-bg-color); - border:var(--focus-outline-around); - border-radius:2px; - position:absolute; - } - -.topLeft:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer){ - top:var(--resizer-shift); - left:var(--resizer-shift); - } - -.topMiddle:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer){ - top:var(--resizer-shift); - left:calc(50% + var(--resizer-shift)); - } - -.topRight:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer){ - top:var(--resizer-shift); - right:var(--resizer-shift); - } - -.middleRight:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer){ - top:calc(50% + var(--resizer-shift)); - right:var(--resizer-shift); - } - -.bottomRight:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer){ - bottom:var(--resizer-shift); - right:var(--resizer-shift); - } - -.bottomMiddle:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer){ - bottom:var(--resizer-shift); - left:calc(50% + var(--resizer-shift)); - } - -.bottomLeft:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer){ - bottom:var(--resizer-shift); - left:var(--resizer-shift); - } - -.middleLeft:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer){ - top:calc(50% + var(--resizer-shift)); - left:var(--resizer-shift); - } - -.topLeft:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="180"],[data-editor-rotation="0"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="90"],[data-editor-rotation="270"])) > .resizers > .resizer),.bottomRight:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="180"],[data-editor-rotation="0"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="90"],[data-editor-rotation="270"])) > .resizers > .resizer){ - cursor:nwse-resize; - } - -.topMiddle:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="180"],[data-editor-rotation="0"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="90"],[data-editor-rotation="270"])) > .resizers > .resizer),.bottomMiddle:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="180"],[data-editor-rotation="0"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="90"],[data-editor-rotation="270"])) > .resizers > .resizer){ - cursor:ns-resize; - } - -.topRight:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="180"],[data-editor-rotation="0"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="90"],[data-editor-rotation="270"])) > .resizers > .resizer),.bottomLeft:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="180"],[data-editor-rotation="0"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="90"],[data-editor-rotation="270"])) > .resizers > .resizer){ - cursor:nesw-resize; - } - -.middleRight:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="180"],[data-editor-rotation="0"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="90"],[data-editor-rotation="270"])) > .resizers > .resizer),.middleLeft:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="180"],[data-editor-rotation="0"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="90"],[data-editor-rotation="270"])) > .resizers > .resizer){ - cursor:ew-resize; - } - -.topLeft:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="90"],[data-editor-rotation="270"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="180"],[data-editor-rotation="0"])) > .resizers > .resizer),.bottomRight:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="90"],[data-editor-rotation="270"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="180"],[data-editor-rotation="0"])) > .resizers > .resizer){ - cursor:nesw-resize; - } - -.topMiddle:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="90"],[data-editor-rotation="270"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="180"],[data-editor-rotation="0"])) > .resizers > .resizer),.bottomMiddle:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="90"],[data-editor-rotation="270"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="180"],[data-editor-rotation="0"])) > .resizers > .resizer){ - cursor:ew-resize; - } - -.topRight:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="90"],[data-editor-rotation="270"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="180"],[data-editor-rotation="0"])) > .resizers > .resizer),.bottomLeft:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="90"],[data-editor-rotation="270"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="180"],[data-editor-rotation="0"])) > .resizers > .resizer){ - cursor:nwse-resize; - } - -.middleRight:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="90"],[data-editor-rotation="270"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="180"],[data-editor-rotation="0"])) > .resizers > .resizer),.middleLeft:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="90"],[data-editor-rotation="270"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="180"],[data-editor-rotation="0"])) > .resizers > .resizer){ - cursor:ns-resize; - } - -:is(.annotationEditorLayer :is([data-main-rotation="0"] [data-editor-rotation="90"],[data-main-rotation="90"] [data-editor-rotation="0"],[data-main-rotation="180"] [data-editor-rotation="270"],[data-main-rotation="270"] [data-editor-rotation="180"])) .editToolbar{ - rotate:270deg; - } - -[dir="ltr"] :is(:is(.annotationEditorLayer :is([data-main-rotation="0"] [data-editor-rotation="90"],[data-main-rotation="90"] [data-editor-rotation="0"],[data-main-rotation="180"] [data-editor-rotation="270"],[data-main-rotation="270"] [data-editor-rotation="180"])) .editToolbar){ - inset-inline-end:calc(0px - var(--editor-toolbar-vert-offset)); - inset-block-start:0; - } - -[dir="rtl"] :is(:is(.annotationEditorLayer :is([data-main-rotation="0"] [data-editor-rotation="90"],[data-main-rotation="90"] [data-editor-rotation="0"],[data-main-rotation="180"] [data-editor-rotation="270"],[data-main-rotation="270"] [data-editor-rotation="180"])) .editToolbar){ - inset-inline-end:calc(100% + var(--editor-toolbar-vert-offset)); - inset-block-start:0; - } - -:is(.annotationEditorLayer :is([data-main-rotation="0"] [data-editor-rotation="180"],[data-main-rotation="90"] [data-editor-rotation="90"],[data-main-rotation="180"] [data-editor-rotation="0"],[data-main-rotation="270"] [data-editor-rotation="270"])) .editToolbar{ - rotate:180deg; - inset-inline-end:100%; - inset-block-start:calc(0pc - var(--editor-toolbar-vert-offset)); - } - -:is(.annotationEditorLayer :is([data-main-rotation="0"] [data-editor-rotation="270"],[data-main-rotation="90"] [data-editor-rotation="180"],[data-main-rotation="180"] [data-editor-rotation="90"],[data-main-rotation="270"] [data-editor-rotation="0"])) .editToolbar{ - rotate:90deg; - } - -[dir="ltr"] :is(:is(.annotationEditorLayer :is([data-main-rotation="0"] [data-editor-rotation="270"],[data-main-rotation="90"] [data-editor-rotation="180"],[data-main-rotation="180"] [data-editor-rotation="90"],[data-main-rotation="270"] [data-editor-rotation="0"])) .editToolbar){ - inset-inline-end:calc(100% + var(--editor-toolbar-vert-offset)); - inset-block-start:100%; - } - -[dir="rtl"] :is(:is(.annotationEditorLayer :is([data-main-rotation="0"] [data-editor-rotation="270"],[data-main-rotation="90"] [data-editor-rotation="180"],[data-main-rotation="180"] [data-editor-rotation="90"],[data-main-rotation="270"] [data-editor-rotation="0"])) .editToolbar){ - inset-inline-start:calc(0px - var(--editor-toolbar-vert-offset)); - inset-block-start:0; - } - -.dialog.altText::backdrop{ - -webkit-mask:url(#alttext-manager-mask); - mask:url(#alttext-manager-mask); - } - -.dialog.altText.positioned{ - margin:0; - } - -.dialog.altText #altTextContainer{ - width:300px; - height:-moz-fit-content; - height:fit-content; - display:inline-flex; - flex-direction:column; - align-items:flex-start; - gap:16px; - } - -:is(.dialog.altText #altTextContainer) #overallDescription{ - display:flex; - flex-direction:column; - align-items:flex-start; - gap:4px; - align-self:stretch; - } - -:is(:is(.dialog.altText #altTextContainer) #overallDescription) span{ - align-self:stretch; - } - -:is(:is(.dialog.altText #altTextContainer) #overallDescription) .title{ - font-size:13px; - font-style:normal; - font-weight:590; - } - -:is(.dialog.altText #altTextContainer) #addDescription{ - display:flex; - flex-direction:column; - align-items:stretch; - gap:8px; - } - -:is(:is(.dialog.altText #altTextContainer) #addDescription) .descriptionArea{ - flex:1; - padding-inline:24px 10px; - } - -:is(:is(:is(.dialog.altText #altTextContainer) #addDescription) .descriptionArea) textarea{ - width:100%; - min-height:75px; - } - -:is(.dialog.altText #altTextContainer) #buttons{ - display:flex; - justify-content:flex-end; - align-items:flex-start; - gap:8px; - align-self:stretch; - } - -.dialog.newAltText{ - --new-alt-text-ai-disclaimer-icon:url(images/altText_disclaimer.svg); - --new-alt-text-spinner-icon:url(images/altText_spinner.svg); - --preview-image-bg-color:#f0f0f4; - --preview-image-border:none; -} - -@media (prefers-color-scheme: dark){ - -.dialog.newAltText{ - --preview-image-bg-color:#2b2a33; -} - } - -@media screen and (forced-colors: active){ - -.dialog.newAltText{ - --preview-image-bg-color:ButtonFace; - --preview-image-border:1px solid ButtonText; -} - } - -.dialog.newAltText{ - - width:80%; - max-width:570px; - min-width:300px; - padding:0; -} - -.dialog.newAltText.noAi #newAltTextDisclaimer,.dialog.newAltText.noAi #newAltTextCreateAutomatically{ - display:none !important; - } - -.dialog.newAltText.aiInstalling #newAltTextCreateAutomatically{ - display:none !important; - } - -.dialog.newAltText.aiInstalling #newAltTextDownloadModel{ - display:flex !important; - } - -.dialog.newAltText.error #newAltTextNotNow{ - display:none !important; - } - -.dialog.newAltText.error #newAltTextCancel{ - display:inline-block !important; - } - -.dialog.newAltText:not(.error) #newAltTextError{ - display:none !important; - } - -.dialog.newAltText #newAltTextContainer{ - display:flex; - width:auto; - padding:16px; - flex-direction:column; - justify-content:flex-end; - align-items:flex-start; - gap:12px; - flex:0 1 auto; - line-height:normal; - } - -:is(.dialog.newAltText #newAltTextContainer) #mainContent{ - display:flex; - justify-content:flex-end; - align-items:flex-start; - gap:12px; - align-self:stretch; - flex:1 1 auto; - } - -:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionAndSettings{ - display:flex; - flex-direction:column; - align-items:flex-start; - gap:16px; - flex:1 0 0; - align-self:stretch; - } - -:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction{ - display:flex; - flex-direction:column; - align-items:flex-start; - gap:8px; - align-self:stretch; - flex:1 1 auto; - } - -:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescriptionContainer{ - width:100%; - height:70px; - position:relative; - } - -:is(:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescriptionContainer) textarea{ - width:100%; - height:100%; - padding:8px; - } - -:is(:is(:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescriptionContainer) textarea)::-moz-placeholder{ - color:var(--text-secondary-color); - } - -:is(:is(:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescriptionContainer) textarea)::placeholder{ - color:var(--text-secondary-color); - } - -:is(:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescriptionContainer) .altTextSpinner{ - display:none; - position:absolute; - width:16px; - height:16px; - inset-inline-start:8px; - inset-block-start:8px; - -webkit-mask-size:cover; - mask-size:cover; - background-color:var(--text-secondary-color); - pointer-events:none; - } - -.loading:is(:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescriptionContainer) textarea::-moz-placeholder{ - color:transparent; - } - -.loading:is(:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescriptionContainer) textarea::placeholder{ - color:transparent; - } - -.loading:is(:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescriptionContainer) .altTextSpinner{ - display:inline-block; - -webkit-mask-image:var(--new-alt-text-spinner-icon); - mask-image:var(--new-alt-text-spinner-icon); - } - -:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescription{ - font-size:11px; - } - -:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDisclaimer{ - display:flex; - flex-direction:row; - align-items:flex-start; - gap:4px; - font-size:11px; - } - -:is(:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDisclaimer)::before{ - content:""; - display:inline-block; - width:17px; - height:16px; - -webkit-mask-image:var(--new-alt-text-ai-disclaimer-icon); - mask-image:var(--new-alt-text-ai-disclaimer-icon); - -webkit-mask-size:cover; - mask-size:cover; - background-color:var(--text-secondary-color); - flex:1 0 auto; - } - -:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #newAltTextDownloadModel{ - display:flex; - align-items:center; - gap:4px; - align-self:stretch; - } - -:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #newAltTextDownloadModel)::before{ - content:""; - display:inline-block; - width:16px; - height:16px; - -webkit-mask-image:var(--new-alt-text-spinner-icon); - mask-image:var(--new-alt-text-spinner-icon); - -webkit-mask-size:cover; - mask-size:cover; - background-color:var(--text-secondary-color); - } - -:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #newAltTextImagePreview{ - width:180px; - aspect-ratio:1; - display:flex; - justify-content:center; - align-items:center; - flex:0 0 auto; - background-color:var(--preview-image-bg-color); - border:var(--preview-image-border); - } - -:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #newAltTextImagePreview) > canvas{ - max-width:100%; - max-height:100%; - } - -.colorPicker{ - --hover-outline-color:#0250bb; - --selected-outline-color:#0060df; - --swatch-border-color:#cfcfd8; -} - -@media (prefers-color-scheme: dark){ - -.colorPicker{ - --hover-outline-color:#80ebff; - --selected-outline-color:#aaf2ff; - --swatch-border-color:#52525e; -} - } - -@media screen and (forced-colors: active){ - -.colorPicker{ - --hover-outline-color:Highlight; - --selected-outline-color:var(--hover-outline-color); - --swatch-border-color:ButtonText; -} - } - -.colorPicker .swatch{ - width:16px; - height:16px; - border:1px solid var(--swatch-border-color); - border-radius:100%; - outline-offset:2px; - box-sizing:border-box; - forced-color-adjust:none; - } - -.colorPicker button:is(:hover,.selected) > .swatch{ - border:none; - } - -.annotationEditorLayer[data-main-rotation="0"] .highlightEditor:not(.free) > .editToolbar{ - rotate:0deg; - } - -.annotationEditorLayer[data-main-rotation="90"] .highlightEditor:not(.free) > .editToolbar{ - rotate:270deg; - } - -.annotationEditorLayer[data-main-rotation="180"] .highlightEditor:not(.free) > .editToolbar{ - rotate:180deg; - } - -.annotationEditorLayer[data-main-rotation="270"] .highlightEditor:not(.free) > .editToolbar{ - rotate:90deg; - } - -.annotationEditorLayer .highlightEditor{ - position:absolute; - background:transparent; - z-index:1; - cursor:auto; - max-width:100%; - max-height:100%; - border:none; - outline:none; - pointer-events:none; - transform-origin:0 0; - } - -:is(.annotationEditorLayer .highlightEditor):not(.free){ - transform:none; - } - -:is(.annotationEditorLayer .highlightEditor) .internal{ - position:absolute; - top:0; - left:0; - width:100%; - height:100%; - pointer-events:auto; - } - -.disabled:is(.annotationEditorLayer .highlightEditor) .internal{ - pointer-events:none; - } - -.selectedEditor:is(.annotationEditorLayer .highlightEditor) .internal{ - cursor:pointer; - } - -:is(.annotationEditorLayer .highlightEditor) .editToolbar{ - --editor-toolbar-colorpicker-arrow-image:url(images/toolbarButton-menuArrow.svg); - - transform-origin:center !important; - } - -:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker{ - position:relative; - width:auto; - display:flex; - justify-content:center; - align-items:center; - gap:4px; - padding:4px; - } - -:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker)::after{ - content:""; - -webkit-mask-image:var(--editor-toolbar-colorpicker-arrow-image); - mask-image:var(--editor-toolbar-colorpicker-arrow-image); - -webkit-mask-repeat:no-repeat; - mask-repeat:no-repeat; - -webkit-mask-position:center; - mask-position:center; - display:inline-block; - background-color:var(--editor-toolbar-fg-color); - width:12px; - height:12px; - } - -:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker):hover::after{ - background-color:var(--editor-toolbar-hover-fg-color); - } - -:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker):has(.dropdown:not(.hidden)){ - background-color:var(--editor-toolbar-hover-bg-color); - } - -:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker):has(.dropdown:not(.hidden))::after{ - scale:-1; - } - -:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker) .dropdown{ - position:absolute; - display:flex; - justify-content:center; - align-items:center; - flex-direction:column; - gap:11px; - padding-block:8px; - border-radius:6px; - background-color:var(--editor-toolbar-bg-color); - border:1px solid var(--editor-toolbar-border-color); - box-shadow:var(--editor-toolbar-shadow); - inset-block-start:calc(100% + 4px); - width:calc(100% + 2 * var(--editor-toolbar-padding)); - } - -:is(:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker) .dropdown) button{ - width:100%; - height:auto; - border:none; - cursor:pointer; - display:flex; - justify-content:center; - align-items:center; - background:none; - } - -:is(:is(:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker) .dropdown) button):is(:active,:focus-visible){ - outline:none; - } - -:is(:is(:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker) .dropdown) button) > .swatch{ - outline-offset:2px; - } - -[aria-selected="true"]:is(:is(:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker) .dropdown) button) > .swatch{ - outline:2px solid var(--selected-outline-color); - } - -:is(:is(:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker) .dropdown) button):is(:hover,:active,:focus-visible) > .swatch{ - outline:2px solid var(--hover-outline-color); - } - -.editorParamsToolbar:has(#highlightParamsToolbarContainer){ - padding:unset; -} - -#highlightParamsToolbarContainer{ - gap:16px; - padding-inline:10px; - padding-block-end:12px; -} - -#highlightParamsToolbarContainer .colorPicker{ - display:flex; - flex-direction:column; - gap:8px; - } - -:is(#highlightParamsToolbarContainer .colorPicker) .dropdown{ - display:flex; - justify-content:space-between; - align-items:center; - flex-direction:row; - height:auto; - } - -:is(:is(#highlightParamsToolbarContainer .colorPicker) .dropdown) button{ - width:auto; - height:auto; - border:none; - cursor:pointer; - display:flex; - justify-content:center; - align-items:center; - background:none; - flex:0 0 auto; - padding:0; - } - -:is(:is(:is(#highlightParamsToolbarContainer .colorPicker) .dropdown) button) .swatch{ - width:24px; - height:24px; - } - -:is(:is(:is(#highlightParamsToolbarContainer .colorPicker) .dropdown) button):is(:active,:focus-visible){ - outline:none; - } - -[aria-selected="true"]:is(:is(:is(#highlightParamsToolbarContainer .colorPicker) .dropdown) button) > .swatch{ - outline:2px solid var(--selected-outline-color); - } - -:is(:is(:is(#highlightParamsToolbarContainer .colorPicker) .dropdown) button):is(:hover,:active,:focus-visible) > .swatch{ - outline:2px solid var(--hover-outline-color); - } - -#highlightParamsToolbarContainer #editorHighlightThickness{ - display:flex; - flex-direction:column; - align-items:center; - gap:4px; - align-self:stretch; - } - -:is(#highlightParamsToolbarContainer #editorHighlightThickness) .editorParamsLabel{ - height:auto; - align-self:stretch; - } - -:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker{ - display:flex; - justify-content:space-between; - align-items:center; - align-self:stretch; - - --example-color:#bfbfc9; - } - -@media (prefers-color-scheme: dark){ - -:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker{ - --example-color:#80808e; - } - } - -@media screen and (forced-colors: active){ - -:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker{ - --example-color:CanvasText; - } - } - -:is(:is(:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker) > .editorParamsSlider[disabled]){ - opacity:0.4; - } - -:is(:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker)::before,:is(:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker)::after{ - content:""; - width:8px; - aspect-ratio:1; - display:block; - border-radius:100%; - background-color:var(--example-color); - } - -:is(:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker)::after{ - width:24px; - } - -:is(:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker) .editorParamsSlider{ - width:unset; - height:14px; - } - -#highlightParamsToolbarContainer #editorHighlightVisibility{ - display:flex; - flex-direction:column; - align-items:flex-start; - gap:8px; - align-self:stretch; - } - -:is(#highlightParamsToolbarContainer #editorHighlightVisibility) .divider{ - --divider-color:#d7d7db; - } - -@media (prefers-color-scheme: dark){ - -:is(#highlightParamsToolbarContainer #editorHighlightVisibility) .divider{ - --divider-color:#8f8f9d; - } - } - -@media screen and (forced-colors: active){ - -:is(#highlightParamsToolbarContainer #editorHighlightVisibility) .divider{ - --divider-color:CanvasText; - } - } - -:is(#highlightParamsToolbarContainer #editorHighlightVisibility) .divider{ - - margin-block:4px; - width:100%; - height:1px; - background-color:var(--divider-color); - } - -:is(#highlightParamsToolbarContainer #editorHighlightVisibility) .toggler{ - display:flex; - justify-content:space-between; - align-items:center; - align-self:stretch; - } - -#altTextSettingsDialog{ - padding:16px; -} - -#altTextSettingsDialog #altTextSettingsContainer{ - display:flex; - width:573px; - flex-direction:column; - gap:16px; - } - -:is(#altTextSettingsDialog #altTextSettingsContainer) .mainContainer{ - gap:16px; - } - -:is(#altTextSettingsDialog #altTextSettingsContainer) .description{ - color:var(--text-secondary-color); - } - -:is(#altTextSettingsDialog #altTextSettingsContainer) #aiModelSettings{ - display:flex; - flex-direction:column; - gap:12px; - } - -:is(:is(#altTextSettingsDialog #altTextSettingsContainer) #aiModelSettings) button{ - width:-moz-fit-content; - width:fit-content; - } - -.download:is(:is(#altTextSettingsDialog #altTextSettingsContainer) #aiModelSettings) #deleteModelButton{ - display:none; - } - -:is(:is(#altTextSettingsDialog #altTextSettingsContainer) #aiModelSettings):not(.download) #downloadModelButton{ - display:none; - } - -:is(#altTextSettingsDialog #altTextSettingsContainer) #automaticAltText,:is(#altTextSettingsDialog #altTextSettingsContainer) #altTextEditor{ - display:flex; - flex-direction:column; - gap:8px; - } - -:is(#altTextSettingsDialog #altTextSettingsContainer) #createModelDescription,:is(#altTextSettingsDialog #altTextSettingsContainer) #aiModelSettings,:is(#altTextSettingsDialog #altTextSettingsContainer) #showAltTextDialogDescription{ - padding-inline-start:40px; - } - -:is(#altTextSettingsDialog #altTextSettingsContainer) #automaticSettings{ - display:flex; - flex-direction:column; - gap:16px; - } - -:root{ - --viewer-container-height:0; - --pdfViewer-padding-bottom:0; - --page-margin:1px auto -8px; - --page-border:9px solid transparent; - --spreadHorizontalWrapped-margin-LR:-3.5px; - --loading-icon-delay:400ms; -} - -@media screen and (forced-colors: active){ - :root{ - --pdfViewer-padding-bottom:9px; - --page-margin:8px auto -1px; - --page-border:1px solid CanvasText; - --spreadHorizontalWrapped-margin-LR:3.5px; - } -} - -[data-main-rotation="90"]{ - transform:rotate(90deg) translateY(-100%); -} -[data-main-rotation="180"]{ - transform:rotate(180deg) translate(-100%, -100%); -} -[data-main-rotation="270"]{ - transform:rotate(270deg) translateX(-100%); -} - -#hiddenCopyElement, -.hiddenCanvasElement{ - position:absolute; - top:0; - left:0; - width:0; - height:0; - display:none; -} - -.pdfViewer{ - --scale-factor:1; - --page-bg-color:unset; - - padding-bottom:var(--pdfViewer-padding-bottom); - - --hcm-highlight-filter:none; - --hcm-highlight-selected-filter:none; -} - -@media screen and (forced-colors: active){ - -.pdfViewer{ - --hcm-highlight-filter:invert(100%); -} - } - -.pdfViewer.copyAll{ - cursor:wait; - } - -.pdfViewer .canvasWrapper{ - overflow:hidden; - width:100%; - height:100%; - } - -:is(.pdfViewer .canvasWrapper) canvas{ - position:absolute; - top:0; - left:0; - margin:0; - display:block; - width:100%; - height:100%; - contain:content; - } - -:is(:is(.pdfViewer .canvasWrapper) canvas) .structTree{ - contain:strict; - } - -.pdfViewer .page{ - --scale-round-x:1px; - --scale-round-y:1px; - - direction:ltr; - width:816px; - height:1056px; - margin:var(--page-margin); - position:relative; - overflow:visible; - border:var(--page-border); - background-clip:content-box; - background-color:var(--page-bg-color, rgb(255 255 255)); -} - -.pdfViewer .dummyPage{ - position:relative; - width:0; - height:var(--viewer-container-height); -} - -.pdfViewer.noUserSelect{ - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; -} - -.pdfViewer.removePageBorders .page{ - margin:0 auto 10px; - border:none; -} - -.pdfViewer.singlePageView{ - display:inline-block; -} - -.pdfViewer.singlePageView .page{ - margin:0; - border:none; -} - -.pdfViewer:is(.scrollHorizontal, .scrollWrapped), -.spread{ - margin-inline:3.5px; - text-align:center; -} - -.pdfViewer.scrollHorizontal, -.spread{ - white-space:nowrap; -} - -.pdfViewer.removePageBorders, -.pdfViewer:is(.scrollHorizontal, .scrollWrapped) .spread{ - margin-inline:0; -} - -.spread :is(.page, .dummyPage), -.pdfViewer:is(.scrollHorizontal, .scrollWrapped) :is(.page, .spread){ - display:inline-block; - vertical-align:middle; -} - -.spread .page, -.pdfViewer:is(.scrollHorizontal, .scrollWrapped) .page{ - margin-inline:var(--spreadHorizontalWrapped-margin-LR); -} - -.pdfViewer.removePageBorders .spread .page, -.pdfViewer.removePageBorders:is(.scrollHorizontal, .scrollWrapped) .page{ - margin-inline:5px; -} - -.pdfViewer .page.loadingIcon::after{ - position:absolute; - top:0; - left:0; - content:""; - width:100%; - height:100%; - background:url("images/loading-icon.gif") center no-repeat; - display:none; - transition-property:display; - transition-delay:var(--loading-icon-delay); - z-index:5; - contain:strict; -} - -.pdfViewer .page.loading::after{ - display:block; -} - -.pdfViewer .page:not(.loading)::after{ - transition-property:none; - display:none; -} - -.pdfPresentationMode .pdfViewer{ - padding-bottom:0; -} - -.pdfPresentationMode .spread{ - margin:0; -} - -.pdfPresentationMode .pdfViewer .page{ - margin:0 auto; - border:2px solid transparent; -} diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.mjs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.mjs deleted file mode 100644 index 9b2c200c99e..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.mjs +++ /dev/null @@ -1,8435 +0,0 @@ -/** - * @licstart The following is the entire license notice for the - * JavaScript code in this page - * - * Copyright 2024 Mozilla Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * @licend The above is the entire license notice for the - * JavaScript code in this page - */ - -/******/ // The require scope -/******/ var __webpack_require__ = {}; -/******/ -/************************************************************************/ -/******/ /* webpack/runtime/define property getters */ -/******/ (() => { -/******/ // define getter functions for harmony exports -/******/ __webpack_require__.d = (exports, definition) => { -/******/ for(var key in definition) { -/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { -/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); -/******/ } -/******/ } -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/hasOwnProperty shorthand */ -/******/ (() => { -/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) -/******/ })(); -/******/ -/************************************************************************/ -var __webpack_exports__ = globalThis.pdfjsViewer = {}; - -// EXPORTS -__webpack_require__.d(__webpack_exports__, { - AnnotationLayerBuilder: () => (/* reexport */ AnnotationLayerBuilder), - DownloadManager: () => (/* reexport */ DownloadManager), - EventBus: () => (/* reexport */ EventBus), - FindState: () => (/* reexport */ FindState), - GenericL10n: () => (/* reexport */ genericl10n_GenericL10n), - LinkTarget: () => (/* reexport */ LinkTarget), - PDFFindController: () => (/* reexport */ PDFFindController), - PDFHistory: () => (/* reexport */ PDFHistory), - PDFLinkService: () => (/* reexport */ PDFLinkService), - PDFPageView: () => (/* reexport */ PDFPageView), - PDFScriptingManager: () => (/* reexport */ PDFScriptingManagerComponents), - PDFSinglePageViewer: () => (/* reexport */ PDFSinglePageViewer), - PDFViewer: () => (/* reexport */ PDFViewer), - ProgressBar: () => (/* reexport */ ProgressBar), - RenderingStates: () => (/* reexport */ RenderingStates), - ScrollMode: () => (/* reexport */ ScrollMode), - SimpleLinkService: () => (/* reexport */ SimpleLinkService), - SpreadMode: () => (/* reexport */ SpreadMode), - StructTreeLayerBuilder: () => (/* reexport */ StructTreeLayerBuilder), - TextLayerBuilder: () => (/* reexport */ TextLayerBuilder), - XfaLayerBuilder: () => (/* reexport */ XfaLayerBuilder), - parseQueryString: () => (/* reexport */ parseQueryString) -}); - -;// ./web/ui_utils.js -const DEFAULT_SCALE_VALUE = "auto"; -const DEFAULT_SCALE = 1.0; -const DEFAULT_SCALE_DELTA = 1.1; -const MIN_SCALE = 0.1; -const MAX_SCALE = 10.0; -const UNKNOWN_SCALE = 0; -const MAX_AUTO_SCALE = 1.25; -const SCROLLBAR_PADDING = 40; -const VERTICAL_PADDING = 5; -const RenderingStates = { - INITIAL: 0, - RUNNING: 1, - PAUSED: 2, - FINISHED: 3 -}; -const PresentationModeState = { - UNKNOWN: 0, - NORMAL: 1, - CHANGING: 2, - FULLSCREEN: 3 -}; -const SidebarView = { - UNKNOWN: -1, - NONE: 0, - THUMBS: 1, - OUTLINE: 2, - ATTACHMENTS: 3, - LAYERS: 4 -}; -const TextLayerMode = { - DISABLE: 0, - ENABLE: 1, - ENABLE_PERMISSIONS: 2 -}; -const ScrollMode = { - UNKNOWN: -1, - VERTICAL: 0, - HORIZONTAL: 1, - WRAPPED: 2, - PAGE: 3 -}; -const SpreadMode = { - UNKNOWN: -1, - NONE: 0, - ODD: 1, - EVEN: 2 -}; -const CursorTool = { - SELECT: 0, - HAND: 1, - ZOOM: 2 -}; -const AutoPrintRegExp = /\bprint\s*\(/; -function scrollIntoView(element, spot, scrollMatches = false) { - let parent = element.offsetParent; - if (!parent) { - console.error("offsetParent is not set -- cannot scroll"); - return; - } - let offsetY = element.offsetTop + element.clientTop; - let offsetX = element.offsetLeft + element.clientLeft; - while (parent.clientHeight === parent.scrollHeight && parent.clientWidth === parent.scrollWidth || scrollMatches && (parent.classList.contains("markedContent") || getComputedStyle(parent).overflow === "hidden")) { - offsetY += parent.offsetTop; - offsetX += parent.offsetLeft; - parent = parent.offsetParent; - if (!parent) { - return; - } - } - if (spot) { - if (spot.top !== undefined) { - offsetY += spot.top; - } - if (spot.left !== undefined) { - offsetX += spot.left; - parent.scrollLeft = offsetX; - } - } - parent.scrollTop = offsetY; -} -function watchScroll(viewAreaElement, callback, abortSignal = undefined) { - const debounceScroll = function (evt) { - if (rAF) { - return; - } - rAF = window.requestAnimationFrame(function viewAreaElementScrolled() { - rAF = null; - const currentX = viewAreaElement.scrollLeft; - const lastX = state.lastX; - if (currentX !== lastX) { - state.right = currentX > lastX; - } - state.lastX = currentX; - const currentY = viewAreaElement.scrollTop; - const lastY = state.lastY; - if (currentY !== lastY) { - state.down = currentY > lastY; - } - state.lastY = currentY; - callback(state); - }); - }; - const state = { - right: true, - down: true, - lastX: viewAreaElement.scrollLeft, - lastY: viewAreaElement.scrollTop, - _eventHandler: debounceScroll - }; - let rAF = null; - viewAreaElement.addEventListener("scroll", debounceScroll, { - useCapture: true, - signal: abortSignal - }); - abortSignal?.addEventListener("abort", () => window.cancelAnimationFrame(rAF), { - once: true - }); - return state; -} -function parseQueryString(query) { - const params = new Map(); - for (const [key, value] of new URLSearchParams(query)) { - params.set(key.toLowerCase(), value); - } - return params; -} -const InvisibleCharsRegExp = /[\x00-\x1F]/g; -function removeNullCharacters(str, replaceInvisible = false) { - if (!InvisibleCharsRegExp.test(str)) { - return str; - } - if (replaceInvisible) { - return str.replaceAll(InvisibleCharsRegExp, m => m === "\x00" ? "" : " "); - } - return str.replaceAll("\x00", ""); -} -function binarySearchFirstItem(items, condition, start = 0) { - let minIndex = start; - let maxIndex = items.length - 1; - if (maxIndex < 0 || !condition(items[maxIndex])) { - return items.length; - } - if (condition(items[minIndex])) { - return minIndex; - } - while (minIndex < maxIndex) { - const currentIndex = minIndex + maxIndex >> 1; - const currentItem = items[currentIndex]; - if (condition(currentItem)) { - maxIndex = currentIndex; - } else { - minIndex = currentIndex + 1; - } - } - return minIndex; -} -function approximateFraction(x) { - if (Math.floor(x) === x) { - return [x, 1]; - } - const xinv = 1 / x; - const limit = 8; - if (xinv > limit) { - return [1, limit]; - } else if (Math.floor(xinv) === xinv) { - return [1, xinv]; - } - const x_ = x > 1 ? xinv : x; - let a = 0, - b = 1, - c = 1, - d = 1; - while (true) { - const p = a + c, - q = b + d; - if (q > limit) { - break; - } - if (x_ <= p / q) { - c = p; - d = q; - } else { - a = p; - b = q; - } - } - let result; - if (x_ - a / b < c / d - x_) { - result = x_ === x ? [a, b] : [b, a]; - } else { - result = x_ === x ? [c, d] : [d, c]; - } - return result; -} -function floorToDivide(x, div) { - return x - x % div; -} -function getPageSizeInches({ - view, - userUnit, - rotate -}) { - const [x1, y1, x2, y2] = view; - const changeOrientation = rotate % 180 !== 0; - const width = (x2 - x1) / 72 * userUnit; - const height = (y2 - y1) / 72 * userUnit; - return { - width: changeOrientation ? height : width, - height: changeOrientation ? width : height - }; -} -function backtrackBeforeAllVisibleElements(index, views, top) { - if (index < 2) { - return index; - } - let elt = views[index].div; - let pageTop = elt.offsetTop + elt.clientTop; - if (pageTop >= top) { - elt = views[index - 1].div; - pageTop = elt.offsetTop + elt.clientTop; - } - for (let i = index - 2; i >= 0; --i) { - elt = views[i].div; - if (elt.offsetTop + elt.clientTop + elt.clientHeight <= pageTop) { - break; - } - index = i; - } - return index; -} -function getVisibleElements({ - scrollEl, - views, - sortByVisibility = false, - horizontal = false, - rtl = false -}) { - const top = scrollEl.scrollTop, - bottom = top + scrollEl.clientHeight; - const left = scrollEl.scrollLeft, - right = left + scrollEl.clientWidth; - function isElementBottomAfterViewTop(view) { - const element = view.div; - const elementBottom = element.offsetTop + element.clientTop + element.clientHeight; - return elementBottom > top; - } - function isElementNextAfterViewHorizontally(view) { - const element = view.div; - const elementLeft = element.offsetLeft + element.clientLeft; - const elementRight = elementLeft + element.clientWidth; - return rtl ? elementLeft < right : elementRight > left; - } - const visible = [], - ids = new Set(), - numViews = views.length; - let firstVisibleElementInd = binarySearchFirstItem(views, horizontal ? isElementNextAfterViewHorizontally : isElementBottomAfterViewTop); - if (firstVisibleElementInd > 0 && firstVisibleElementInd < numViews && !horizontal) { - firstVisibleElementInd = backtrackBeforeAllVisibleElements(firstVisibleElementInd, views, top); - } - let lastEdge = horizontal ? right : -1; - for (let i = firstVisibleElementInd; i < numViews; i++) { - const view = views[i], - element = view.div; - const currentWidth = element.offsetLeft + element.clientLeft; - const currentHeight = element.offsetTop + element.clientTop; - const viewWidth = element.clientWidth, - viewHeight = element.clientHeight; - const viewRight = currentWidth + viewWidth; - const viewBottom = currentHeight + viewHeight; - if (lastEdge === -1) { - if (viewBottom >= bottom) { - lastEdge = viewBottom; - } - } else if ((horizontal ? currentWidth : currentHeight) > lastEdge) { - break; - } - if (viewBottom <= top || currentHeight >= bottom || viewRight <= left || currentWidth >= right) { - continue; - } - const hiddenHeight = Math.max(0, top - currentHeight) + Math.max(0, viewBottom - bottom); - const hiddenWidth = Math.max(0, left - currentWidth) + Math.max(0, viewRight - right); - const fractionHeight = (viewHeight - hiddenHeight) / viewHeight, - fractionWidth = (viewWidth - hiddenWidth) / viewWidth; - const percent = fractionHeight * fractionWidth * 100 | 0; - visible.push({ - id: view.id, - x: currentWidth, - y: currentHeight, - view, - percent, - widthPercent: fractionWidth * 100 | 0 - }); - ids.add(view.id); - } - const first = visible[0], - last = visible.at(-1); - if (sortByVisibility) { - visible.sort(function (a, b) { - const pc = a.percent - b.percent; - if (Math.abs(pc) > 0.001) { - return -pc; - } - return a.id - b.id; - }); - } - return { - first, - last, - views: visible, - ids - }; -} -function normalizeWheelEventDirection(evt) { - let delta = Math.hypot(evt.deltaX, evt.deltaY); - const angle = Math.atan2(evt.deltaY, evt.deltaX); - if (-0.25 * Math.PI < angle && angle < 0.75 * Math.PI) { - delta = -delta; - } - return delta; -} -function normalizeWheelEventDelta(evt) { - const deltaMode = evt.deltaMode; - let delta = normalizeWheelEventDirection(evt); - const MOUSE_PIXELS_PER_LINE = 30; - const MOUSE_LINES_PER_PAGE = 30; - if (deltaMode === WheelEvent.DOM_DELTA_PIXEL) { - delta /= MOUSE_PIXELS_PER_LINE * MOUSE_LINES_PER_PAGE; - } else if (deltaMode === WheelEvent.DOM_DELTA_LINE) { - delta /= MOUSE_LINES_PER_PAGE; - } - return delta; -} -function isValidRotation(angle) { - return Number.isInteger(angle) && angle % 90 === 0; -} -function isValidScrollMode(mode) { - return Number.isInteger(mode) && Object.values(ScrollMode).includes(mode) && mode !== ScrollMode.UNKNOWN; -} -function isValidSpreadMode(mode) { - return Number.isInteger(mode) && Object.values(SpreadMode).includes(mode) && mode !== SpreadMode.UNKNOWN; -} -function isPortraitOrientation(size) { - return size.width <= size.height; -} -const animationStarted = new Promise(function (resolve) { - window.requestAnimationFrame(resolve); -}); -const docStyle = document.documentElement.style; -function clamp(v, min, max) { - return Math.min(Math.max(v, min), max); -} -class ProgressBar { - #classList = null; - #disableAutoFetchTimeout = null; - #percent = 0; - #style = null; - #visible = true; - constructor(bar) { - this.#classList = bar.classList; - this.#style = bar.style; - } - get percent() { - return this.#percent; - } - set percent(val) { - this.#percent = clamp(val, 0, 100); - if (isNaN(val)) { - this.#classList.add("indeterminate"); - return; - } - this.#classList.remove("indeterminate"); - this.#style.setProperty("--progressBar-percent", `${this.#percent}%`); - } - setWidth(viewer) { - if (!viewer) { - return; - } - const container = viewer.parentNode; - const scrollbarWidth = container.offsetWidth - viewer.offsetWidth; - if (scrollbarWidth > 0) { - this.#style.setProperty("--progressBar-end-offset", `${scrollbarWidth}px`); - } - } - setDisableAutoFetch(delay = 5000) { - if (this.#percent === 100 || isNaN(this.#percent)) { - return; - } - if (this.#disableAutoFetchTimeout) { - clearTimeout(this.#disableAutoFetchTimeout); - } - this.show(); - this.#disableAutoFetchTimeout = setTimeout(() => { - this.#disableAutoFetchTimeout = null; - this.hide(); - }, delay); - } - hide() { - if (!this.#visible) { - return; - } - this.#visible = false; - this.#classList.add("hidden"); - } - show() { - if (this.#visible) { - return; - } - this.#visible = true; - this.#classList.remove("hidden"); - } -} -function getActiveOrFocusedElement() { - let curRoot = document; - let curActiveOrFocused = curRoot.activeElement || curRoot.querySelector(":focus"); - while (curActiveOrFocused?.shadowRoot) { - curRoot = curActiveOrFocused.shadowRoot; - curActiveOrFocused = curRoot.activeElement || curRoot.querySelector(":focus"); - } - return curActiveOrFocused; -} -function apiPageLayoutToViewerModes(layout) { - let scrollMode = ScrollMode.VERTICAL, - spreadMode = SpreadMode.NONE; - switch (layout) { - case "SinglePage": - scrollMode = ScrollMode.PAGE; - break; - case "OneColumn": - break; - case "TwoPageLeft": - scrollMode = ScrollMode.PAGE; - case "TwoColumnLeft": - spreadMode = SpreadMode.ODD; - break; - case "TwoPageRight": - scrollMode = ScrollMode.PAGE; - case "TwoColumnRight": - spreadMode = SpreadMode.EVEN; - break; - } - return { - scrollMode, - spreadMode - }; -} -function apiPageModeToSidebarView(mode) { - switch (mode) { - case "UseNone": - return SidebarView.NONE; - case "UseThumbs": - return SidebarView.THUMBS; - case "UseOutlines": - return SidebarView.OUTLINE; - case "UseAttachments": - return SidebarView.ATTACHMENTS; - case "UseOC": - return SidebarView.LAYERS; - } - return SidebarView.NONE; -} -function toggleCheckedBtn(button, toggle, view = null) { - button.classList.toggle("toggled", toggle); - button.setAttribute("aria-checked", toggle); - view?.classList.toggle("hidden", !toggle); -} -function toggleExpandedBtn(button, toggle, view = null) { - button.classList.toggle("toggled", toggle); - button.setAttribute("aria-expanded", toggle); - view?.classList.toggle("hidden", !toggle); -} -const calcRound = function () { - const e = document.createElement("div"); - e.style.width = "round(down, calc(1.6666666666666665 * 792px), 1px)"; - return e.style.width === "calc(1320px)" ? Math.fround : x => x; -}(); - -;// ./web/pdf_find_utils.js -const CharacterType = { - SPACE: 0, - ALPHA_LETTER: 1, - PUNCT: 2, - HAN_LETTER: 3, - KATAKANA_LETTER: 4, - HIRAGANA_LETTER: 5, - HALFWIDTH_KATAKANA_LETTER: 6, - THAI_LETTER: 7 -}; -function isAlphabeticalScript(charCode) { - return charCode < 0x2e80; -} -function isAscii(charCode) { - return (charCode & 0xff80) === 0; -} -function isAsciiAlpha(charCode) { - return charCode >= 0x61 && charCode <= 0x7a || charCode >= 0x41 && charCode <= 0x5a; -} -function isAsciiDigit(charCode) { - return charCode >= 0x30 && charCode <= 0x39; -} -function isAsciiSpace(charCode) { - return charCode === 0x20 || charCode === 0x09 || charCode === 0x0d || charCode === 0x0a; -} -function isHan(charCode) { - return charCode >= 0x3400 && charCode <= 0x9fff || charCode >= 0xf900 && charCode <= 0xfaff; -} -function isKatakana(charCode) { - return charCode >= 0x30a0 && charCode <= 0x30ff; -} -function isHiragana(charCode) { - return charCode >= 0x3040 && charCode <= 0x309f; -} -function isHalfwidthKatakana(charCode) { - return charCode >= 0xff60 && charCode <= 0xff9f; -} -function isThai(charCode) { - return (charCode & 0xff80) === 0x0e00; -} -function getCharacterType(charCode) { - if (isAlphabeticalScript(charCode)) { - if (isAscii(charCode)) { - if (isAsciiSpace(charCode)) { - return CharacterType.SPACE; - } else if (isAsciiAlpha(charCode) || isAsciiDigit(charCode) || charCode === 0x5f) { - return CharacterType.ALPHA_LETTER; - } - return CharacterType.PUNCT; - } else if (isThai(charCode)) { - return CharacterType.THAI_LETTER; - } else if (charCode === 0xa0) { - return CharacterType.SPACE; - } - return CharacterType.ALPHA_LETTER; - } - if (isHan(charCode)) { - return CharacterType.HAN_LETTER; - } else if (isKatakana(charCode)) { - return CharacterType.KATAKANA_LETTER; - } else if (isHiragana(charCode)) { - return CharacterType.HIRAGANA_LETTER; - } else if (isHalfwidthKatakana(charCode)) { - return CharacterType.HALFWIDTH_KATAKANA_LETTER; - } - return CharacterType.ALPHA_LETTER; -} -let NormalizeWithNFKC; -function getNormalizeWithNFKC() { - NormalizeWithNFKC ||= ` ¨ª¯²-µ¸-º¼-¾IJ-ijĿ-ŀʼnſDŽ-njDZ-dzʰ-ʸ˘-˝ˠ-ˤʹͺ;΄-΅·ϐ-ϖϰ-ϲϴ-ϵϹևٵ-ٸक़-य़ড়-ঢ়য়ਲ਼ਸ਼ਖ਼-ਜ਼ਫ਼ଡ଼-ଢ଼ำຳໜ-ໝ༌གྷཌྷདྷབྷཛྷཀྵჼᴬ-ᴮᴰ-ᴺᴼ-ᵍᵏ-ᵪᵸᶛ-ᶿẚ-ẛάέήίόύώΆ᾽-῁ΈΉ῍-῏ΐΊ῝-῟ΰΎ῭-`ΌΏ´-῾ - ‑‗․-… ″-‴‶-‷‼‾⁇-⁉⁗ ⁰-ⁱ⁴-₎ₐ-ₜ₨℀-℃℅-ℇ℉-ℓℕ-№ℙ-ℝ℠-™ℤΩℨK-ℭℯ-ℱℳ-ℹ℻-⅀ⅅ-ⅉ⅐-ⅿ↉∬-∭∯-∰〈-〉①-⓪⨌⩴-⩶⫝̸ⱼ-ⱽⵯ⺟⻳⼀-⿕ 〶〸-〺゛-゜ゟヿㄱ-ㆎ㆒-㆟㈀-㈞㈠-㉇㉐-㉾㊀-㏿ꚜ-ꚝꝰꟲ-ꟴꟸ-ꟹꭜ-ꭟꭩ豈-嗀塚晴凞-羽蘒諸逸-都飯-舘並-龎ff-stﬓ-ﬗיִײַ-זּטּ-לּמּנּ-סּףּ-פּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-﷼︐-︙︰-﹄﹇-﹒﹔-﹦﹨-﹫ﹰ-ﹲﹴﹶ-ﻼ!-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ¢-₩`; - return NormalizeWithNFKC; -} - -;// ./web/pdf_find_controller.js - - -const FindState = { - FOUND: 0, - NOT_FOUND: 1, - WRAPPED: 2, - PENDING: 3 -}; -const FIND_TIMEOUT = 250; -const MATCH_SCROLL_OFFSET_TOP = -50; -const MATCH_SCROLL_OFFSET_LEFT = -400; -const CHARACTERS_TO_NORMALIZE = { - "\u2010": "-", - "\u2018": "'", - "\u2019": "'", - "\u201A": "'", - "\u201B": "'", - "\u201C": '"', - "\u201D": '"', - "\u201E": '"', - "\u201F": '"', - "\u00BC": "1/4", - "\u00BD": "1/2", - "\u00BE": "3/4" -}; -const DIACRITICS_EXCEPTION = new Set([0x3099, 0x309a, 0x094d, 0x09cd, 0x0a4d, 0x0acd, 0x0b4d, 0x0bcd, 0x0c4d, 0x0ccd, 0x0d3b, 0x0d3c, 0x0d4d, 0x0dca, 0x0e3a, 0x0eba, 0x0f84, 0x1039, 0x103a, 0x1714, 0x1734, 0x17d2, 0x1a60, 0x1b44, 0x1baa, 0x1bab, 0x1bf2, 0x1bf3, 0x2d7f, 0xa806, 0xa82c, 0xa8c4, 0xa953, 0xa9c0, 0xaaf6, 0xabed, 0x0c56, 0x0f71, 0x0f72, 0x0f7a, 0x0f7b, 0x0f7c, 0x0f7d, 0x0f80, 0x0f74]); -let DIACRITICS_EXCEPTION_STR; -const DIACRITICS_REG_EXP = /\p{M}+/gu; -const SPECIAL_CHARS_REG_EXP = /([.*+?^${}()|[\]\\])|(\p{P})|(\s+)|(\p{M})|(\p{L})/gu; -const NOT_DIACRITIC_FROM_END_REG_EXP = /([^\p{M}])\p{M}*$/u; -const NOT_DIACRITIC_FROM_START_REG_EXP = /^\p{M}*([^\p{M}])/u; -const SYLLABLES_REG_EXP = /[\uAC00-\uD7AF\uFA6C\uFACF-\uFAD1\uFAD5-\uFAD7]+/g; -const SYLLABLES_LENGTHS = new Map(); -const FIRST_CHAR_SYLLABLES_REG_EXP = "[\\u1100-\\u1112\\ud7a4-\\ud7af\\ud84a\\ud84c\\ud850\\ud854\\ud857\\ud85f]"; -const NFKC_CHARS_TO_NORMALIZE = new Map(); -let noSyllablesRegExp = null; -let withSyllablesRegExp = null; -function normalize(text) { - const syllablePositions = []; - let m; - while ((m = SYLLABLES_REG_EXP.exec(text)) !== null) { - let { - index - } = m; - for (const char of m[0]) { - let len = SYLLABLES_LENGTHS.get(char); - if (!len) { - len = char.normalize("NFD").length; - SYLLABLES_LENGTHS.set(char, len); - } - syllablePositions.push([len, index++]); - } - } - let normalizationRegex; - if (syllablePositions.length === 0 && noSyllablesRegExp) { - normalizationRegex = noSyllablesRegExp; - } else if (syllablePositions.length > 0 && withSyllablesRegExp) { - normalizationRegex = withSyllablesRegExp; - } else { - const replace = Object.keys(CHARACTERS_TO_NORMALIZE).join(""); - const toNormalizeWithNFKC = getNormalizeWithNFKC(); - const CJK = "(?:\\p{Ideographic}|[\u3040-\u30FF])"; - const HKDiacritics = "(?:\u3099|\u309A)"; - const CompoundWord = "\\p{Ll}-\\n\\p{Lu}"; - const regexp = `([${replace}])|([${toNormalizeWithNFKC}])|(${HKDiacritics}\\n)|(\\p{M}+(?:-\\n)?)|(${CompoundWord})|(\\S-\\n)|(${CJK}\\n)|(\\n)`; - if (syllablePositions.length === 0) { - normalizationRegex = noSyllablesRegExp = new RegExp(regexp + "|(\\u0000)", "gum"); - } else { - normalizationRegex = withSyllablesRegExp = new RegExp(regexp + `|(${FIRST_CHAR_SYLLABLES_REG_EXP})`, "gum"); - } - } - const rawDiacriticsPositions = []; - while ((m = DIACRITICS_REG_EXP.exec(text)) !== null) { - rawDiacriticsPositions.push([m[0].length, m.index]); - } - let normalized = text.normalize("NFD"); - const positions = [0, 0]; - let rawDiacriticsIndex = 0; - let syllableIndex = 0; - let shift = 0; - let shiftOrigin = 0; - let eol = 0; - let hasDiacritics = false; - normalized = normalized.replace(normalizationRegex, (match, p1, p2, p3, p4, p5, p6, p7, p8, p9, i) => { - i -= shiftOrigin; - if (p1) { - const replacement = CHARACTERS_TO_NORMALIZE[p1]; - const jj = replacement.length; - for (let j = 1; j < jj; j++) { - positions.push(i - shift + j, shift - j); - } - shift -= jj - 1; - return replacement; - } - if (p2) { - let replacement = NFKC_CHARS_TO_NORMALIZE.get(p2); - if (!replacement) { - replacement = p2.normalize("NFKC"); - NFKC_CHARS_TO_NORMALIZE.set(p2, replacement); - } - const jj = replacement.length; - for (let j = 1; j < jj; j++) { - positions.push(i - shift + j, shift - j); - } - shift -= jj - 1; - return replacement; - } - if (p3) { - hasDiacritics = true; - if (i + eol === rawDiacriticsPositions[rawDiacriticsIndex]?.[1]) { - ++rawDiacriticsIndex; - } else { - positions.push(i - 1 - shift + 1, shift - 1); - shift -= 1; - shiftOrigin += 1; - } - positions.push(i - shift + 1, shift); - shiftOrigin += 1; - eol += 1; - return p3.charAt(0); - } - if (p4) { - const hasTrailingDashEOL = p4.endsWith("\n"); - const len = hasTrailingDashEOL ? p4.length - 2 : p4.length; - hasDiacritics = true; - let jj = len; - if (i + eol === rawDiacriticsPositions[rawDiacriticsIndex]?.[1]) { - jj -= rawDiacriticsPositions[rawDiacriticsIndex][0]; - ++rawDiacriticsIndex; - } - for (let j = 1; j <= jj; j++) { - positions.push(i - 1 - shift + j, shift - j); - } - shift -= jj; - shiftOrigin += jj; - if (hasTrailingDashEOL) { - i += len - 1; - positions.push(i - shift + 1, 1 + shift); - shift += 1; - shiftOrigin += 1; - eol += 1; - return p4.slice(0, len); - } - return p4; - } - if (p5) { - shiftOrigin += 1; - eol += 1; - return p5.replace("\n", ""); - } - if (p6) { - const len = p6.length - 2; - positions.push(i - shift + len, 1 + shift); - shift += 1; - shiftOrigin += 1; - eol += 1; - return p6.slice(0, -2); - } - if (p7) { - const len = p7.length - 1; - positions.push(i - shift + len, shift); - shiftOrigin += 1; - eol += 1; - return p7.slice(0, -1); - } - if (p8) { - positions.push(i - shift + 1, shift - 1); - shift -= 1; - shiftOrigin += 1; - eol += 1; - return " "; - } - if (i + eol === syllablePositions[syllableIndex]?.[1]) { - const newCharLen = syllablePositions[syllableIndex][0] - 1; - ++syllableIndex; - for (let j = 1; j <= newCharLen; j++) { - positions.push(i - (shift - j), shift - j); - } - shift -= newCharLen; - shiftOrigin += newCharLen; - } - return p9; - }); - positions.push(normalized.length, shift); - const starts = new Uint32Array(positions.length >> 1); - const shifts = new Int32Array(positions.length >> 1); - for (let i = 0, ii = positions.length; i < ii; i += 2) { - starts[i >> 1] = positions[i]; - shifts[i >> 1] = positions[i + 1]; - } - return [normalized, [starts, shifts], hasDiacritics]; -} -function getOriginalIndex(diffs, pos, len) { - if (!diffs) { - return [pos, len]; - } - const [starts, shifts] = diffs; - const start = pos; - const end = pos + len - 1; - let i = binarySearchFirstItem(starts, x => x >= start); - if (starts[i] > start) { - --i; - } - let j = binarySearchFirstItem(starts, x => x >= end, i); - if (starts[j] > end) { - --j; - } - const oldStart = start + shifts[i]; - const oldEnd = end + shifts[j]; - const oldLen = oldEnd + 1 - oldStart; - return [oldStart, oldLen]; -} -class PDFFindController { - #state = null; - #updateMatchesCountOnProgress = true; - #visitedPagesCount = 0; - constructor({ - linkService, - eventBus, - updateMatchesCountOnProgress = true - }) { - this._linkService = linkService; - this._eventBus = eventBus; - this.#updateMatchesCountOnProgress = updateMatchesCountOnProgress; - this.onIsPageVisible = null; - this.#reset(); - eventBus._on("find", this.#onFind.bind(this)); - eventBus._on("findbarclose", this.#onFindBarClose.bind(this)); - } - get highlightMatches() { - return this._highlightMatches; - } - get pageMatches() { - return this._pageMatches; - } - get pageMatchesLength() { - return this._pageMatchesLength; - } - get selected() { - return this._selected; - } - get state() { - return this.#state; - } - setDocument(pdfDocument) { - if (this._pdfDocument) { - this.#reset(); - } - if (!pdfDocument) { - return; - } - this._pdfDocument = pdfDocument; - this._firstPageCapability.resolve(); - } - #onFind(state) { - if (!state) { - return; - } - const pdfDocument = this._pdfDocument; - const { - type - } = state; - if (this.#state === null || this.#shouldDirtyMatch(state)) { - this._dirtyMatch = true; - } - this.#state = state; - if (type !== "highlightallchange") { - this.#updateUIState(FindState.PENDING); - } - this._firstPageCapability.promise.then(() => { - if (!this._pdfDocument || pdfDocument && this._pdfDocument !== pdfDocument) { - return; - } - this.#extractText(); - const findbarClosed = !this._highlightMatches; - const pendingTimeout = !!this._findTimeout; - if (this._findTimeout) { - clearTimeout(this._findTimeout); - this._findTimeout = null; - } - if (!type) { - this._findTimeout = setTimeout(() => { - this.#nextMatch(); - this._findTimeout = null; - }, FIND_TIMEOUT); - } else if (this._dirtyMatch) { - this.#nextMatch(); - } else if (type === "again") { - this.#nextMatch(); - if (findbarClosed && this.#state.highlightAll) { - this.#updateAllPages(); - } - } else if (type === "highlightallchange") { - if (pendingTimeout) { - this.#nextMatch(); - } else { - this._highlightMatches = true; - } - this.#updateAllPages(); - } else { - this.#nextMatch(); - } - }); - } - scrollMatchIntoView({ - element = null, - selectedLeft = 0, - pageIndex = -1, - matchIndex = -1 - }) { - if (!this._scrollMatches || !element) { - return; - } else if (matchIndex === -1 || matchIndex !== this._selected.matchIdx) { - return; - } else if (pageIndex === -1 || pageIndex !== this._selected.pageIdx) { - return; - } - this._scrollMatches = false; - const spot = { - top: MATCH_SCROLL_OFFSET_TOP, - left: selectedLeft + MATCH_SCROLL_OFFSET_LEFT - }; - scrollIntoView(element, spot, true); - } - #reset() { - this._highlightMatches = false; - this._scrollMatches = false; - this._pdfDocument = null; - this._pageMatches = []; - this._pageMatchesLength = []; - this.#visitedPagesCount = 0; - this.#state = null; - this._selected = { - pageIdx: -1, - matchIdx: -1 - }; - this._offset = { - pageIdx: null, - matchIdx: null, - wrapped: false - }; - this._extractTextPromises = []; - this._pageContents = []; - this._pageDiffs = []; - this._hasDiacritics = []; - this._matchesCountTotal = 0; - this._pagesToSearch = null; - this._pendingFindMatches = new Set(); - this._resumePageIdx = null; - this._dirtyMatch = false; - clearTimeout(this._findTimeout); - this._findTimeout = null; - this._firstPageCapability = Promise.withResolvers(); - } - get #query() { - const { - query - } = this.#state; - if (typeof query === "string") { - if (query !== this._rawQuery) { - this._rawQuery = query; - [this._normalizedQuery] = normalize(query); - } - return this._normalizedQuery; - } - return (query || []).filter(q => !!q).map(q => normalize(q)[0]); - } - #shouldDirtyMatch(state) { - const newQuery = state.query, - prevQuery = this.#state.query; - const newType = typeof newQuery, - prevType = typeof prevQuery; - if (newType !== prevType) { - return true; - } - if (newType === "string") { - if (newQuery !== prevQuery) { - return true; - } - } else if (JSON.stringify(newQuery) !== JSON.stringify(prevQuery)) { - return true; - } - switch (state.type) { - case "again": - const pageNumber = this._selected.pageIdx + 1; - const linkService = this._linkService; - return pageNumber >= 1 && pageNumber <= linkService.pagesCount && pageNumber !== linkService.page && !(this.onIsPageVisible?.(pageNumber) ?? true); - case "highlightallchange": - return false; - } - return true; - } - #isEntireWord(content, startIdx, length) { - let match = content.slice(0, startIdx).match(NOT_DIACRITIC_FROM_END_REG_EXP); - if (match) { - const first = content.charCodeAt(startIdx); - const limit = match[1].charCodeAt(0); - if (getCharacterType(first) === getCharacterType(limit)) { - return false; - } - } - match = content.slice(startIdx + length).match(NOT_DIACRITIC_FROM_START_REG_EXP); - if (match) { - const last = content.charCodeAt(startIdx + length - 1); - const limit = match[1].charCodeAt(0); - if (getCharacterType(last) === getCharacterType(limit)) { - return false; - } - } - return true; - } - #convertToRegExpString(query, hasDiacritics) { - const { - matchDiacritics - } = this.#state; - let isUnicode = false; - query = query.replaceAll(SPECIAL_CHARS_REG_EXP, (match, p1, p2, p3, p4, p5) => { - if (p1) { - return `[ ]*\\${p1}[ ]*`; - } - if (p2) { - return `[ ]*${p2}[ ]*`; - } - if (p3) { - return "[ ]+"; - } - if (matchDiacritics) { - return p4 || p5; - } - if (p4) { - return DIACRITICS_EXCEPTION.has(p4.charCodeAt(0)) ? p4 : ""; - } - if (hasDiacritics) { - isUnicode = true; - return `${p5}\\p{M}*`; - } - return p5; - }); - const trailingSpaces = "[ ]*"; - if (query.endsWith(trailingSpaces)) { - query = query.slice(0, query.length - trailingSpaces.length); - } - if (matchDiacritics) { - if (hasDiacritics) { - DIACRITICS_EXCEPTION_STR ||= String.fromCharCode(...DIACRITICS_EXCEPTION); - isUnicode = true; - query = `${query}(?=[${DIACRITICS_EXCEPTION_STR}]|[^\\p{M}]|$)`; - } - } - return [isUnicode, query]; - } - #calculateMatch(pageIndex) { - const query = this.#query; - if (query.length === 0) { - return; - } - const pageContent = this._pageContents[pageIndex]; - const matcherResult = this.match(query, pageContent, pageIndex); - const matches = this._pageMatches[pageIndex] = []; - const matchesLength = this._pageMatchesLength[pageIndex] = []; - const diffs = this._pageDiffs[pageIndex]; - matcherResult?.forEach(({ - index, - length - }) => { - const [matchPos, matchLen] = getOriginalIndex(diffs, index, length); - if (matchLen) { - matches.push(matchPos); - matchesLength.push(matchLen); - } - }); - if (this.#state.highlightAll) { - this.#updatePage(pageIndex); - } - if (this._resumePageIdx === pageIndex) { - this._resumePageIdx = null; - this.#nextPageMatch(); - } - const pageMatchesCount = matches.length; - this._matchesCountTotal += pageMatchesCount; - if (this.#updateMatchesCountOnProgress) { - if (pageMatchesCount > 0) { - this.#updateUIResultsCount(); - } - } else if (++this.#visitedPagesCount === this._linkService.pagesCount) { - this.#updateUIResultsCount(); - } - } - match(query, pageContent, pageIndex) { - const hasDiacritics = this._hasDiacritics[pageIndex]; - let isUnicode = false; - if (typeof query === "string") { - [isUnicode, query] = this.#convertToRegExpString(query, hasDiacritics); - } else { - query = query.sort().reverse().map(q => { - const [isUnicodePart, queryPart] = this.#convertToRegExpString(q, hasDiacritics); - isUnicode ||= isUnicodePart; - return `(${queryPart})`; - }).join("|"); - } - if (!query) { - return undefined; - } - const { - caseSensitive, - entireWord - } = this.#state; - const flags = `g${isUnicode ? "u" : ""}${caseSensitive ? "" : "i"}`; - query = new RegExp(query, flags); - const matches = []; - let match; - while ((match = query.exec(pageContent)) !== null) { - if (entireWord && !this.#isEntireWord(pageContent, match.index, match[0].length)) { - continue; - } - matches.push({ - index: match.index, - length: match[0].length - }); - } - return matches; - } - #extractText() { - if (this._extractTextPromises.length > 0) { - return; - } - let deferred = Promise.resolve(); - const textOptions = { - disableNormalization: true - }; - for (let i = 0, ii = this._linkService.pagesCount; i < ii; i++) { - const { - promise, - resolve - } = Promise.withResolvers(); - this._extractTextPromises[i] = promise; - deferred = deferred.then(() => { - return this._pdfDocument.getPage(i + 1).then(pdfPage => pdfPage.getTextContent(textOptions)).then(textContent => { - const strBuf = []; - for (const textItem of textContent.items) { - strBuf.push(textItem.str); - if (textItem.hasEOL) { - strBuf.push("\n"); - } - } - [this._pageContents[i], this._pageDiffs[i], this._hasDiacritics[i]] = normalize(strBuf.join("")); - resolve(); - }, reason => { - console.error(`Unable to get text content for page ${i + 1}`, reason); - this._pageContents[i] = ""; - this._pageDiffs[i] = null; - this._hasDiacritics[i] = false; - resolve(); - }); - }); - } - } - #updatePage(index) { - if (this._scrollMatches && this._selected.pageIdx === index) { - this._linkService.page = index + 1; - } - this._eventBus.dispatch("updatetextlayermatches", { - source: this, - pageIndex: index - }); - } - #updateAllPages() { - this._eventBus.dispatch("updatetextlayermatches", { - source: this, - pageIndex: -1 - }); - } - #nextMatch() { - const previous = this.#state.findPrevious; - const currentPageIndex = this._linkService.page - 1; - const numPages = this._linkService.pagesCount; - this._highlightMatches = true; - if (this._dirtyMatch) { - this._dirtyMatch = false; - this._selected.pageIdx = this._selected.matchIdx = -1; - this._offset.pageIdx = currentPageIndex; - this._offset.matchIdx = null; - this._offset.wrapped = false; - this._resumePageIdx = null; - this._pageMatches.length = 0; - this._pageMatchesLength.length = 0; - this.#visitedPagesCount = 0; - this._matchesCountTotal = 0; - this.#updateAllPages(); - for (let i = 0; i < numPages; i++) { - if (this._pendingFindMatches.has(i)) { - continue; - } - this._pendingFindMatches.add(i); - this._extractTextPromises[i].then(() => { - this._pendingFindMatches.delete(i); - this.#calculateMatch(i); - }); - } - } - const query = this.#query; - if (query.length === 0) { - this.#updateUIState(FindState.FOUND); - return; - } - if (this._resumePageIdx) { - return; - } - const offset = this._offset; - this._pagesToSearch = numPages; - if (offset.matchIdx !== null) { - const numPageMatches = this._pageMatches[offset.pageIdx].length; - if (!previous && offset.matchIdx + 1 < numPageMatches || previous && offset.matchIdx > 0) { - offset.matchIdx = previous ? offset.matchIdx - 1 : offset.matchIdx + 1; - this.#updateMatch(true); - return; - } - this.#advanceOffsetPage(previous); - } - this.#nextPageMatch(); - } - #matchesReady(matches) { - const offset = this._offset; - const numMatches = matches.length; - const previous = this.#state.findPrevious; - if (numMatches) { - offset.matchIdx = previous ? numMatches - 1 : 0; - this.#updateMatch(true); - return true; - } - this.#advanceOffsetPage(previous); - if (offset.wrapped) { - offset.matchIdx = null; - if (this._pagesToSearch < 0) { - this.#updateMatch(false); - return true; - } - } - return false; - } - #nextPageMatch() { - if (this._resumePageIdx !== null) { - console.error("There can only be one pending page."); - } - let matches = null; - do { - const pageIdx = this._offset.pageIdx; - matches = this._pageMatches[pageIdx]; - if (!matches) { - this._resumePageIdx = pageIdx; - break; - } - } while (!this.#matchesReady(matches)); - } - #advanceOffsetPage(previous) { - const offset = this._offset; - const numPages = this._linkService.pagesCount; - offset.pageIdx = previous ? offset.pageIdx - 1 : offset.pageIdx + 1; - offset.matchIdx = null; - this._pagesToSearch--; - if (offset.pageIdx >= numPages || offset.pageIdx < 0) { - offset.pageIdx = previous ? numPages - 1 : 0; - offset.wrapped = true; - } - } - #updateMatch(found = false) { - let state = FindState.NOT_FOUND; - const wrapped = this._offset.wrapped; - this._offset.wrapped = false; - if (found) { - const previousPage = this._selected.pageIdx; - this._selected.pageIdx = this._offset.pageIdx; - this._selected.matchIdx = this._offset.matchIdx; - state = wrapped ? FindState.WRAPPED : FindState.FOUND; - if (previousPage !== -1 && previousPage !== this._selected.pageIdx) { - this.#updatePage(previousPage); - } - } - this.#updateUIState(state, this.#state.findPrevious); - if (this._selected.pageIdx !== -1) { - this._scrollMatches = true; - this.#updatePage(this._selected.pageIdx); - } - } - #onFindBarClose(evt) { - const pdfDocument = this._pdfDocument; - this._firstPageCapability.promise.then(() => { - if (!this._pdfDocument || pdfDocument && this._pdfDocument !== pdfDocument) { - return; - } - if (this._findTimeout) { - clearTimeout(this._findTimeout); - this._findTimeout = null; - } - if (this._resumePageIdx) { - this._resumePageIdx = null; - this._dirtyMatch = true; - } - this.#updateUIState(FindState.FOUND); - this._highlightMatches = false; - this.#updateAllPages(); - }); - } - #requestMatchesCount() { - const { - pageIdx, - matchIdx - } = this._selected; - let current = 0, - total = this._matchesCountTotal; - if (matchIdx !== -1) { - for (let i = 0; i < pageIdx; i++) { - current += this._pageMatches[i]?.length || 0; - } - current += matchIdx + 1; - } - if (current < 1 || current > total) { - current = total = 0; - } - return { - current, - total - }; - } - #updateUIResultsCount() { - this._eventBus.dispatch("updatefindmatchescount", { - source: this, - matchesCount: this.#requestMatchesCount() - }); - } - #updateUIState(state, previous = false) { - if (!this.#updateMatchesCountOnProgress && (this.#visitedPagesCount !== this._linkService.pagesCount || state === FindState.PENDING)) { - return; - } - this._eventBus.dispatch("updatefindcontrolstate", { - source: this, - state, - previous, - entireWord: this.#state?.entireWord ?? null, - matchesCount: this.#requestMatchesCount(), - rawQuery: this.#state?.query ?? null - }); - } -} - -;// ./web/pdf_link_service.js - -const DEFAULT_LINK_REL = "noopener noreferrer nofollow"; -const LinkTarget = { - NONE: 0, - SELF: 1, - BLANK: 2, - PARENT: 3, - TOP: 4 -}; -class PDFLinkService { - externalLinkEnabled = true; - constructor({ - eventBus, - externalLinkTarget = null, - externalLinkRel = null, - ignoreDestinationZoom = false - } = {}) { - this.eventBus = eventBus; - this.externalLinkTarget = externalLinkTarget; - this.externalLinkRel = externalLinkRel; - this._ignoreDestinationZoom = ignoreDestinationZoom; - this.baseUrl = null; - this.pdfDocument = null; - this.pdfViewer = null; - this.pdfHistory = null; - } - setDocument(pdfDocument, baseUrl = null) { - this.baseUrl = baseUrl; - this.pdfDocument = pdfDocument; - } - setViewer(pdfViewer) { - this.pdfViewer = pdfViewer; - } - setHistory(pdfHistory) { - this.pdfHistory = pdfHistory; - } - get pagesCount() { - return this.pdfDocument ? this.pdfDocument.numPages : 0; - } - get page() { - return this.pdfDocument ? this.pdfViewer.currentPageNumber : 1; - } - set page(value) { - if (this.pdfDocument) { - this.pdfViewer.currentPageNumber = value; - } - } - get rotation() { - return this.pdfDocument ? this.pdfViewer.pagesRotation : 0; - } - set rotation(value) { - if (this.pdfDocument) { - this.pdfViewer.pagesRotation = value; - } - } - get isInPresentationMode() { - return this.pdfDocument ? this.pdfViewer.isInPresentationMode : false; - } - async goToDestination(dest) { - if (!this.pdfDocument) { - return; - } - let namedDest, explicitDest, pageNumber; - if (typeof dest === "string") { - namedDest = dest; - explicitDest = await this.pdfDocument.getDestination(dest); - } else { - namedDest = null; - explicitDest = await dest; - } - if (!Array.isArray(explicitDest)) { - console.error(`goToDestination: "${explicitDest}" is not a valid destination array, for dest="${dest}".`); - return; - } - const [destRef] = explicitDest; - if (destRef && typeof destRef === "object") { - pageNumber = this.pdfDocument.cachedPageNumber(destRef); - if (!pageNumber) { - try { - pageNumber = (await this.pdfDocument.getPageIndex(destRef)) + 1; - } catch { - console.error(`goToDestination: "${destRef}" is not a valid page reference, for dest="${dest}".`); - return; - } - } - } else if (Number.isInteger(destRef)) { - pageNumber = destRef + 1; - } - if (!pageNumber || pageNumber < 1 || pageNumber > this.pagesCount) { - console.error(`goToDestination: "${pageNumber}" is not a valid page number, for dest="${dest}".`); - return; - } - if (this.pdfHistory) { - this.pdfHistory.pushCurrentPosition(); - this.pdfHistory.push({ - namedDest, - explicitDest, - pageNumber - }); - } - this.pdfViewer.scrollPageIntoView({ - pageNumber, - destArray: explicitDest, - ignoreDestinationZoom: this._ignoreDestinationZoom - }); - } - goToPage(val) { - if (!this.pdfDocument) { - return; - } - const pageNumber = typeof val === "string" && this.pdfViewer.pageLabelToPageNumber(val) || val | 0; - if (!(Number.isInteger(pageNumber) && pageNumber > 0 && pageNumber <= this.pagesCount)) { - console.error(`PDFLinkService.goToPage: "${val}" is not a valid page.`); - return; - } - if (this.pdfHistory) { - this.pdfHistory.pushCurrentPosition(); - this.pdfHistory.pushPage(pageNumber); - } - this.pdfViewer.scrollPageIntoView({ - pageNumber - }); - } - addLinkAttributes(link, url, newWindow = false) { - if (!url || typeof url !== "string") { - throw new Error('A valid "url" parameter must provided.'); - } - const target = newWindow ? LinkTarget.BLANK : this.externalLinkTarget, - rel = this.externalLinkRel; - if (this.externalLinkEnabled) { - link.href = link.title = url; - } else { - link.href = ""; - link.title = `Disabled: ${url}`; - link.onclick = () => false; - } - let targetStr = ""; - switch (target) { - case LinkTarget.NONE: - break; - case LinkTarget.SELF: - targetStr = "_self"; - break; - case LinkTarget.BLANK: - targetStr = "_blank"; - break; - case LinkTarget.PARENT: - targetStr = "_parent"; - break; - case LinkTarget.TOP: - targetStr = "_top"; - break; - } - link.target = targetStr; - link.rel = typeof rel === "string" ? rel : DEFAULT_LINK_REL; - } - getDestinationHash(dest) { - if (typeof dest === "string") { - if (dest.length > 0) { - return this.getAnchorUrl("#" + escape(dest)); - } - } else if (Array.isArray(dest)) { - const str = JSON.stringify(dest); - if (str.length > 0) { - return this.getAnchorUrl("#" + escape(str)); - } - } - return this.getAnchorUrl(""); - } - getAnchorUrl(anchor) { - return this.baseUrl ? this.baseUrl + anchor : anchor; - } - setHash(hash) { - if (!this.pdfDocument) { - return; - } - let pageNumber, dest; - if (hash.includes("=")) { - const params = parseQueryString(hash); - if (params.has("search")) { - const query = params.get("search").replaceAll('"', ""), - phrase = params.get("phrase") === "true"; - this.eventBus.dispatch("findfromurlhash", { - source: this, - query: phrase ? query : query.match(/\S+/g) - }); - } - if (params.has("page")) { - pageNumber = params.get("page") | 0 || 1; - } - if (params.has("zoom")) { - const zoomArgs = params.get("zoom").split(","); - const zoomArg = zoomArgs[0]; - const zoomArgNumber = parseFloat(zoomArg); - if (!zoomArg.includes("Fit")) { - dest = [null, { - name: "XYZ" - }, zoomArgs.length > 1 ? zoomArgs[1] | 0 : null, zoomArgs.length > 2 ? zoomArgs[2] | 0 : null, zoomArgNumber ? zoomArgNumber / 100 : zoomArg]; - } else if (zoomArg === "Fit" || zoomArg === "FitB") { - dest = [null, { - name: zoomArg - }]; - } else if (zoomArg === "FitH" || zoomArg === "FitBH" || zoomArg === "FitV" || zoomArg === "FitBV") { - dest = [null, { - name: zoomArg - }, zoomArgs.length > 1 ? zoomArgs[1] | 0 : null]; - } else if (zoomArg === "FitR") { - if (zoomArgs.length !== 5) { - console.error('PDFLinkService.setHash: Not enough parameters for "FitR".'); - } else { - dest = [null, { - name: zoomArg - }, zoomArgs[1] | 0, zoomArgs[2] | 0, zoomArgs[3] | 0, zoomArgs[4] | 0]; - } - } else { - console.error(`PDFLinkService.setHash: "${zoomArg}" is not a valid zoom value.`); - } - } - if (dest) { - this.pdfViewer.scrollPageIntoView({ - pageNumber: pageNumber || this.page, - destArray: dest, - allowNegativeOffset: true - }); - } else if (pageNumber) { - this.page = pageNumber; - } - if (params.has("pagemode")) { - this.eventBus.dispatch("pagemode", { - source: this, - mode: params.get("pagemode") - }); - } - if (params.has("nameddest")) { - this.goToDestination(params.get("nameddest")); - } - return; - } - dest = unescape(hash); - try { - dest = JSON.parse(dest); - if (!Array.isArray(dest)) { - dest = dest.toString(); - } - } catch {} - if (typeof dest === "string" || PDFLinkService.#isValidExplicitDest(dest)) { - this.goToDestination(dest); - return; - } - console.error(`PDFLinkService.setHash: "${unescape(hash)}" is not a valid destination.`); - } - executeNamedAction(action) { - if (!this.pdfDocument) { - return; - } - switch (action) { - case "GoBack": - this.pdfHistory?.back(); - break; - case "GoForward": - this.pdfHistory?.forward(); - break; - case "NextPage": - this.pdfViewer.nextPage(); - break; - case "PrevPage": - this.pdfViewer.previousPage(); - break; - case "LastPage": - this.page = this.pagesCount; - break; - case "FirstPage": - this.page = 1; - break; - default: - break; - } - this.eventBus.dispatch("namedaction", { - source: this, - action - }); - } - async executeSetOCGState(action) { - if (!this.pdfDocument) { - return; - } - const pdfDocument = this.pdfDocument, - optionalContentConfig = await this.pdfViewer.optionalContentConfigPromise; - if (pdfDocument !== this.pdfDocument) { - return; - } - optionalContentConfig.setOCGState(action); - this.pdfViewer.optionalContentConfigPromise = Promise.resolve(optionalContentConfig); - } - static #isValidExplicitDest(dest) { - if (!Array.isArray(dest) || dest.length < 2) { - return false; - } - const [page, zoom, ...args] = dest; - if (!(typeof page === "object" && Number.isInteger(page?.num) && Number.isInteger(page?.gen)) && !Number.isInteger(page)) { - return false; - } - if (!(typeof zoom === "object" && typeof zoom?.name === "string")) { - return false; - } - const argsLen = args.length; - let allowNull = true; - switch (zoom.name) { - case "XYZ": - if (argsLen < 2 || argsLen > 3) { - return false; - } - break; - case "Fit": - case "FitB": - return argsLen === 0; - case "FitH": - case "FitBH": - case "FitV": - case "FitBV": - if (argsLen > 1) { - return false; - } - break; - case "FitR": - if (argsLen !== 4) { - return false; - } - allowNull = false; - break; - default: - return false; - } - for (const arg of args) { - if (!(typeof arg === "number" || allowNull && arg === null)) { - return false; - } - } - return true; - } -} -class SimpleLinkService extends PDFLinkService { - setDocument(pdfDocument, baseUrl = null) {} -} - -;// ./web/pdfjs.js -const { - AbortException, - AnnotationEditorLayer, - AnnotationEditorParamsType, - AnnotationEditorType, - AnnotationEditorUIManager, - AnnotationLayer, - AnnotationMode, - build, - ColorPicker, - createValidAbsoluteUrl, - DOMSVGFactory, - DrawLayer, - FeatureTest, - fetchData, - getDocument, - getFilenameFromUrl, - getPdfFilenameFromUrl, - getXfaPageViewport, - GlobalWorkerOptions, - ImageKind, - InvalidPDFException, - isDataScheme, - isPdfFile, - MissingPDFException, - noContextMenu, - normalizeUnicode, - OPS, - OutputScale, - PasswordResponses, - PDFDataRangeTransport, - PDFDateString, - PDFWorker, - PermissionFlag, - PixelsPerInch, - RenderingCancelledException, - setLayerDimensions, - shadow, - stopEvent, - TextLayer, - TouchManager, - UnexpectedResponseException, - Util, - VerbosityLevel, - version, - XfaLayer -} = globalThis.pdfjsLib; - -;// ./web/annotation_layer_builder.js - - -class AnnotationLayerBuilder { - #onAppend = null; - #eventAbortController = null; - constructor({ - pdfPage, - linkService, - downloadManager, - annotationStorage = null, - imageResourcesPath = "", - renderForms = true, - enableScripting = false, - hasJSActionsPromise = null, - fieldObjectsPromise = null, - annotationCanvasMap = null, - accessibilityManager = null, - annotationEditorUIManager = null, - onAppend = null - }) { - this.pdfPage = pdfPage; - this.linkService = linkService; - this.downloadManager = downloadManager; - this.imageResourcesPath = imageResourcesPath; - this.renderForms = renderForms; - this.annotationStorage = annotationStorage; - this.enableScripting = enableScripting; - this._hasJSActionsPromise = hasJSActionsPromise || Promise.resolve(false); - this._fieldObjectsPromise = fieldObjectsPromise || Promise.resolve(null); - this._annotationCanvasMap = annotationCanvasMap; - this._accessibilityManager = accessibilityManager; - this._annotationEditorUIManager = annotationEditorUIManager; - this.#onAppend = onAppend; - this.annotationLayer = null; - this.div = null; - this._cancelled = false; - this._eventBus = linkService.eventBus; - } - async render(viewport, options, intent = "display") { - if (this.div) { - if (this._cancelled || !this.annotationLayer) { - return; - } - this.annotationLayer.update({ - viewport: viewport.clone({ - dontFlip: true - }) - }); - return; - } - const [annotations, hasJSActions, fieldObjects] = await Promise.all([this.pdfPage.getAnnotations({ - intent - }), this._hasJSActionsPromise, this._fieldObjectsPromise]); - if (this._cancelled) { - return; - } - const div = this.div = document.createElement("div"); - div.className = "annotationLayer"; - this.#onAppend?.(div); - if (annotations.length === 0) { - this.hide(); - return; - } - this.annotationLayer = new AnnotationLayer({ - div, - accessibilityManager: this._accessibilityManager, - annotationCanvasMap: this._annotationCanvasMap, - annotationEditorUIManager: this._annotationEditorUIManager, - page: this.pdfPage, - viewport: viewport.clone({ - dontFlip: true - }), - structTreeLayer: options?.structTreeLayer || null - }); - await this.annotationLayer.render({ - annotations, - imageResourcesPath: this.imageResourcesPath, - renderForms: this.renderForms, - linkService: this.linkService, - downloadManager: this.downloadManager, - annotationStorage: this.annotationStorage, - enableScripting: this.enableScripting, - hasJSActions, - fieldObjects - }); - if (this.linkService.isInPresentationMode) { - this.#updatePresentationModeState(PresentationModeState.FULLSCREEN); - } - if (!this.#eventAbortController) { - this.#eventAbortController = new AbortController(); - this._eventBus?._on("presentationmodechanged", evt => { - this.#updatePresentationModeState(evt.state); - }, { - signal: this.#eventAbortController.signal - }); - } - } - cancel() { - this._cancelled = true; - this.#eventAbortController?.abort(); - this.#eventAbortController = null; - } - hide() { - if (!this.div) { - return; - } - this.div.hidden = true; - } - hasEditableAnnotations() { - return !!this.annotationLayer?.hasEditableAnnotations(); - } - #updatePresentationModeState(state) { - if (!this.div) { - return; - } - let disableFormElements = false; - switch (state) { - case PresentationModeState.FULLSCREEN: - disableFormElements = true; - break; - case PresentationModeState.NORMAL: - break; - default: - return; - } - for (const section of this.div.childNodes) { - if (section.hasAttribute("data-internal-link")) { - continue; - } - section.inert = disableFormElements; - } - } -} - -;// ./web/download_manager.js - -function download(blobUrl, filename) { - const a = document.createElement("a"); - if (!a.click) { - throw new Error('DownloadManager: "a.click()" is not supported.'); - } - a.href = blobUrl; - a.target = "_parent"; - if ("download" in a) { - a.download = filename; - } - (document.body || document.documentElement).append(a); - a.click(); - a.remove(); -} -class DownloadManager { - #openBlobUrls = new WeakMap(); - downloadData(data, filename, contentType) { - const blobUrl = URL.createObjectURL(new Blob([data], { - type: contentType - })); - download(blobUrl, filename); - } - openOrDownloadData(data, filename, dest = null) { - const isPdfData = isPdfFile(filename); - const contentType = isPdfData ? "application/pdf" : ""; - this.downloadData(data, filename, contentType); - return false; - } - download(data, url, filename) { - let blobUrl; - if (data) { - blobUrl = URL.createObjectURL(new Blob([data], { - type: "application/pdf" - })); - } else { - if (!createValidAbsoluteUrl(url, "http://example.com")) { - console.error(`download - not a valid URL: ${url}`); - return; - } - blobUrl = url + "#pdfjs.action=download"; - } - download(blobUrl, filename); - } -} - -;// ./web/event_utils.js -const WaitOnType = { - EVENT: "event", - TIMEOUT: "timeout" -}; -async function waitOnEventOrTimeout({ - target, - name, - delay = 0 -}) { - if (typeof target !== "object" || !(name && typeof name === "string") || !(Number.isInteger(delay) && delay >= 0)) { - throw new Error("waitOnEventOrTimeout - invalid parameters."); - } - const { - promise, - resolve - } = Promise.withResolvers(); - const ac = new AbortController(); - function handler(type) { - ac.abort(); - clearTimeout(timeout); - resolve(type); - } - const evtMethod = target instanceof EventBus ? "_on" : "addEventListener"; - target[evtMethod](name, handler.bind(null, WaitOnType.EVENT), { - signal: ac.signal - }); - const timeout = setTimeout(handler.bind(null, WaitOnType.TIMEOUT), delay); - return promise; -} -class EventBus { - #listeners = Object.create(null); - on(eventName, listener, options = null) { - this._on(eventName, listener, { - external: true, - once: options?.once, - signal: options?.signal - }); - } - off(eventName, listener, options = null) { - this._off(eventName, listener); - } - dispatch(eventName, data) { - const eventListeners = this.#listeners[eventName]; - if (!eventListeners || eventListeners.length === 0) { - return; - } - let externalListeners; - for (const { - listener, - external, - once - } of eventListeners.slice(0)) { - if (once) { - this._off(eventName, listener); - } - if (external) { - (externalListeners ||= []).push(listener); - continue; - } - listener(data); - } - if (externalListeners) { - for (const listener of externalListeners) { - listener(data); - } - externalListeners = null; - } - } - _on(eventName, listener, options = null) { - let rmAbort = null; - if (options?.signal instanceof AbortSignal) { - const { - signal - } = options; - if (signal.aborted) { - console.error("Cannot use an `aborted` signal."); - return; - } - const onAbort = () => this._off(eventName, listener); - rmAbort = () => signal.removeEventListener("abort", onAbort); - signal.addEventListener("abort", onAbort); - } - const eventListeners = this.#listeners[eventName] ||= []; - eventListeners.push({ - listener, - external: options?.external === true, - once: options?.once === true, - rmAbort - }); - } - _off(eventName, listener, options = null) { - const eventListeners = this.#listeners[eventName]; - if (!eventListeners) { - return; - } - for (let i = 0, ii = eventListeners.length; i < ii; i++) { - const evt = eventListeners[i]; - if (evt.listener === listener) { - evt.rmAbort?.(); - eventListeners.splice(i, 1); - return; - } - } - } -} -class FirefoxEventBus extends EventBus { - #externalServices; - #globalEventNames; - #isInAutomation; - constructor(globalEventNames, externalServices, isInAutomation) { - super(); - this.#globalEventNames = globalEventNames; - this.#externalServices = externalServices; - this.#isInAutomation = isInAutomation; - } - dispatch(eventName, data) { - throw new Error("Not implemented: FirefoxEventBus.dispatch"); - } -} - -;// ./node_modules/@fluent/bundle/esm/types.js -class FluentType { - constructor(value) { - this.value = value; - } - valueOf() { - return this.value; - } -} -class FluentNone extends FluentType { - constructor(value = "???") { - super(value); - } - toString(scope) { - return `{${this.value}}`; - } -} -class FluentNumber extends FluentType { - constructor(value, opts = {}) { - super(value); - this.opts = opts; - } - toString(scope) { - try { - const nf = scope.memoizeIntlObject(Intl.NumberFormat, this.opts); - return nf.format(this.value); - } catch (err) { - scope.reportError(err); - return this.value.toString(10); - } - } -} -class FluentDateTime extends FluentType { - constructor(value, opts = {}) { - super(value); - this.opts = opts; - } - toString(scope) { - try { - const dtf = scope.memoizeIntlObject(Intl.DateTimeFormat, this.opts); - return dtf.format(this.value); - } catch (err) { - scope.reportError(err); - return new Date(this.value).toISOString(); - } - } -} -;// ./node_modules/@fluent/bundle/esm/resolver.js - -const MAX_PLACEABLES = 100; -const FSI = "\u2068"; -const PDI = "\u2069"; -function match(scope, selector, key) { - if (key === selector) { - return true; - } - if (key instanceof FluentNumber && selector instanceof FluentNumber && key.value === selector.value) { - return true; - } - if (selector instanceof FluentNumber && typeof key === "string") { - let category = scope.memoizeIntlObject(Intl.PluralRules, selector.opts).select(selector.value); - if (key === category) { - return true; - } - } - return false; -} -function getDefault(scope, variants, star) { - if (variants[star]) { - return resolvePattern(scope, variants[star].value); - } - scope.reportError(new RangeError("No default")); - return new FluentNone(); -} -function getArguments(scope, args) { - const positional = []; - const named = Object.create(null); - for (const arg of args) { - if (arg.type === "narg") { - named[arg.name] = resolveExpression(scope, arg.value); - } else { - positional.push(resolveExpression(scope, arg)); - } - } - return { - positional, - named - }; -} -function resolveExpression(scope, expr) { - switch (expr.type) { - case "str": - return expr.value; - case "num": - return new FluentNumber(expr.value, { - minimumFractionDigits: expr.precision - }); - case "var": - return resolveVariableReference(scope, expr); - case "mesg": - return resolveMessageReference(scope, expr); - case "term": - return resolveTermReference(scope, expr); - case "func": - return resolveFunctionReference(scope, expr); - case "select": - return resolveSelectExpression(scope, expr); - default: - return new FluentNone(); - } -} -function resolveVariableReference(scope, { - name -}) { - let arg; - if (scope.params) { - if (Object.prototype.hasOwnProperty.call(scope.params, name)) { - arg = scope.params[name]; - } else { - return new FluentNone(`$${name}`); - } - } else if (scope.args && Object.prototype.hasOwnProperty.call(scope.args, name)) { - arg = scope.args[name]; - } else { - scope.reportError(new ReferenceError(`Unknown variable: $${name}`)); - return new FluentNone(`$${name}`); - } - if (arg instanceof FluentType) { - return arg; - } - switch (typeof arg) { - case "string": - return arg; - case "number": - return new FluentNumber(arg); - case "object": - if (arg instanceof Date) { - return new FluentDateTime(arg.getTime()); - } - default: - scope.reportError(new TypeError(`Variable type not supported: $${name}, ${typeof arg}`)); - return new FluentNone(`$${name}`); - } -} -function resolveMessageReference(scope, { - name, - attr -}) { - const message = scope.bundle._messages.get(name); - if (!message) { - scope.reportError(new ReferenceError(`Unknown message: ${name}`)); - return new FluentNone(name); - } - if (attr) { - const attribute = message.attributes[attr]; - if (attribute) { - return resolvePattern(scope, attribute); - } - scope.reportError(new ReferenceError(`Unknown attribute: ${attr}`)); - return new FluentNone(`${name}.${attr}`); - } - if (message.value) { - return resolvePattern(scope, message.value); - } - scope.reportError(new ReferenceError(`No value: ${name}`)); - return new FluentNone(name); -} -function resolveTermReference(scope, { - name, - attr, - args -}) { - const id = `-${name}`; - const term = scope.bundle._terms.get(id); - if (!term) { - scope.reportError(new ReferenceError(`Unknown term: ${id}`)); - return new FluentNone(id); - } - if (attr) { - const attribute = term.attributes[attr]; - if (attribute) { - scope.params = getArguments(scope, args).named; - const resolved = resolvePattern(scope, attribute); - scope.params = null; - return resolved; - } - scope.reportError(new ReferenceError(`Unknown attribute: ${attr}`)); - return new FluentNone(`${id}.${attr}`); - } - scope.params = getArguments(scope, args).named; - const resolved = resolvePattern(scope, term.value); - scope.params = null; - return resolved; -} -function resolveFunctionReference(scope, { - name, - args -}) { - let func = scope.bundle._functions[name]; - if (!func) { - scope.reportError(new ReferenceError(`Unknown function: ${name}()`)); - return new FluentNone(`${name}()`); - } - if (typeof func !== "function") { - scope.reportError(new TypeError(`Function ${name}() is not callable`)); - return new FluentNone(`${name}()`); - } - try { - let resolved = getArguments(scope, args); - return func(resolved.positional, resolved.named); - } catch (err) { - scope.reportError(err); - return new FluentNone(`${name}()`); - } -} -function resolveSelectExpression(scope, { - selector, - variants, - star -}) { - let sel = resolveExpression(scope, selector); - if (sel instanceof FluentNone) { - return getDefault(scope, variants, star); - } - for (const variant of variants) { - const key = resolveExpression(scope, variant.key); - if (match(scope, sel, key)) { - return resolvePattern(scope, variant.value); - } - } - return getDefault(scope, variants, star); -} -function resolveComplexPattern(scope, ptn) { - if (scope.dirty.has(ptn)) { - scope.reportError(new RangeError("Cyclic reference")); - return new FluentNone(); - } - scope.dirty.add(ptn); - const result = []; - const useIsolating = scope.bundle._useIsolating && ptn.length > 1; - for (const elem of ptn) { - if (typeof elem === "string") { - result.push(scope.bundle._transform(elem)); - continue; - } - scope.placeables++; - if (scope.placeables > MAX_PLACEABLES) { - scope.dirty.delete(ptn); - throw new RangeError(`Too many placeables expanded: ${scope.placeables}, ` + `max allowed is ${MAX_PLACEABLES}`); - } - if (useIsolating) { - result.push(FSI); - } - result.push(resolveExpression(scope, elem).toString(scope)); - if (useIsolating) { - result.push(PDI); - } - } - scope.dirty.delete(ptn); - return result.join(""); -} -function resolvePattern(scope, value) { - if (typeof value === "string") { - return scope.bundle._transform(value); - } - return resolveComplexPattern(scope, value); -} -;// ./node_modules/@fluent/bundle/esm/scope.js -class Scope { - constructor(bundle, errors, args) { - this.dirty = new WeakSet(); - this.params = null; - this.placeables = 0; - this.bundle = bundle; - this.errors = errors; - this.args = args; - } - reportError(error) { - if (!this.errors || !(error instanceof Error)) { - throw error; - } - this.errors.push(error); - } - memoizeIntlObject(ctor, opts) { - let cache = this.bundle._intls.get(ctor); - if (!cache) { - cache = {}; - this.bundle._intls.set(ctor, cache); - } - let id = JSON.stringify(opts); - if (!cache[id]) { - cache[id] = new ctor(this.bundle.locales, opts); - } - return cache[id]; - } -} -;// ./node_modules/@fluent/bundle/esm/builtins.js - -function values(opts, allowed) { - const unwrapped = Object.create(null); - for (const [name, opt] of Object.entries(opts)) { - if (allowed.includes(name)) { - unwrapped[name] = opt.valueOf(); - } - } - return unwrapped; -} -const NUMBER_ALLOWED = ["unitDisplay", "currencyDisplay", "useGrouping", "minimumIntegerDigits", "minimumFractionDigits", "maximumFractionDigits", "minimumSignificantDigits", "maximumSignificantDigits"]; -function NUMBER(args, opts) { - let arg = args[0]; - if (arg instanceof FluentNone) { - return new FluentNone(`NUMBER(${arg.valueOf()})`); - } - if (arg instanceof FluentNumber) { - return new FluentNumber(arg.valueOf(), { - ...arg.opts, - ...values(opts, NUMBER_ALLOWED) - }); - } - if (arg instanceof FluentDateTime) { - return new FluentNumber(arg.valueOf(), { - ...values(opts, NUMBER_ALLOWED) - }); - } - throw new TypeError("Invalid argument to NUMBER"); -} -const DATETIME_ALLOWED = ["dateStyle", "timeStyle", "fractionalSecondDigits", "dayPeriod", "hour12", "weekday", "era", "year", "month", "day", "hour", "minute", "second", "timeZoneName"]; -function DATETIME(args, opts) { - let arg = args[0]; - if (arg instanceof FluentNone) { - return new FluentNone(`DATETIME(${arg.valueOf()})`); - } - if (arg instanceof FluentDateTime) { - return new FluentDateTime(arg.valueOf(), { - ...arg.opts, - ...values(opts, DATETIME_ALLOWED) - }); - } - if (arg instanceof FluentNumber) { - return new FluentDateTime(arg.valueOf(), { - ...values(opts, DATETIME_ALLOWED) - }); - } - throw new TypeError("Invalid argument to DATETIME"); -} -;// ./node_modules/@fluent/bundle/esm/memoizer.js -const cache = new Map(); -function getMemoizerForLocale(locales) { - const stringLocale = Array.isArray(locales) ? locales.join(" ") : locales; - let memoizer = cache.get(stringLocale); - if (memoizer === undefined) { - memoizer = new Map(); - cache.set(stringLocale, memoizer); - } - return memoizer; -} -;// ./node_modules/@fluent/bundle/esm/bundle.js - - - - - -class FluentBundle { - constructor(locales, { - functions, - useIsolating = true, - transform = v => v - } = {}) { - this._terms = new Map(); - this._messages = new Map(); - this.locales = Array.isArray(locales) ? locales : [locales]; - this._functions = { - NUMBER: NUMBER, - DATETIME: DATETIME, - ...functions - }; - this._useIsolating = useIsolating; - this._transform = transform; - this._intls = getMemoizerForLocale(locales); - } - hasMessage(id) { - return this._messages.has(id); - } - getMessage(id) { - return this._messages.get(id); - } - addResource(res, { - allowOverrides = false - } = {}) { - const errors = []; - for (let i = 0; i < res.body.length; i++) { - let entry = res.body[i]; - if (entry.id.startsWith("-")) { - if (allowOverrides === false && this._terms.has(entry.id)) { - errors.push(new Error(`Attempt to override an existing term: "${entry.id}"`)); - continue; - } - this._terms.set(entry.id, entry); - } else { - if (allowOverrides === false && this._messages.has(entry.id)) { - errors.push(new Error(`Attempt to override an existing message: "${entry.id}"`)); - continue; - } - this._messages.set(entry.id, entry); - } - } - return errors; - } - formatPattern(pattern, args = null, errors = null) { - if (typeof pattern === "string") { - return this._transform(pattern); - } - let scope = new Scope(this, errors, args); - try { - let value = resolveComplexPattern(scope, pattern); - return value.toString(scope); - } catch (err) { - if (scope.errors && err instanceof Error) { - scope.errors.push(err); - return new FluentNone().toString(scope); - } - throw err; - } - } -} -;// ./node_modules/@fluent/bundle/esm/resource.js -const RE_MESSAGE_START = /^(-?[a-zA-Z][\w-]*) *= */gm; -const RE_ATTRIBUTE_START = /\.([a-zA-Z][\w-]*) *= */y; -const RE_VARIANT_START = /\*?\[/y; -const RE_NUMBER_LITERAL = /(-?[0-9]+(?:\.([0-9]+))?)/y; -const RE_IDENTIFIER = /([a-zA-Z][\w-]*)/y; -const RE_REFERENCE = /([$-])?([a-zA-Z][\w-]*)(?:\.([a-zA-Z][\w-]*))?/y; -const RE_FUNCTION_NAME = /^[A-Z][A-Z0-9_-]*$/; -const RE_TEXT_RUN = /([^{}\n\r]+)/y; -const RE_STRING_RUN = /([^\\"\n\r]*)/y; -const RE_STRING_ESCAPE = /\\([\\"])/y; -const RE_UNICODE_ESCAPE = /\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{6})/y; -const RE_LEADING_NEWLINES = /^\n+/; -const RE_TRAILING_SPACES = / +$/; -const RE_BLANK_LINES = / *\r?\n/g; -const RE_INDENT = /( *)$/; -const TOKEN_BRACE_OPEN = /{\s*/y; -const TOKEN_BRACE_CLOSE = /\s*}/y; -const TOKEN_BRACKET_OPEN = /\[\s*/y; -const TOKEN_BRACKET_CLOSE = /\s*] */y; -const TOKEN_PAREN_OPEN = /\s*\(\s*/y; -const TOKEN_ARROW = /\s*->\s*/y; -const TOKEN_COLON = /\s*:\s*/y; -const TOKEN_COMMA = /\s*,?\s*/y; -const TOKEN_BLANK = /\s+/y; -class FluentResource { - constructor(source) { - this.body = []; - RE_MESSAGE_START.lastIndex = 0; - let cursor = 0; - while (true) { - let next = RE_MESSAGE_START.exec(source); - if (next === null) { - break; - } - cursor = RE_MESSAGE_START.lastIndex; - try { - this.body.push(parseMessage(next[1])); - } catch (err) { - if (err instanceof SyntaxError) { - continue; - } - throw err; - } - } - function test(re) { - re.lastIndex = cursor; - return re.test(source); - } - function consumeChar(char, errorClass) { - if (source[cursor] === char) { - cursor++; - return true; - } - if (errorClass) { - throw new errorClass(`Expected ${char}`); - } - return false; - } - function consumeToken(re, errorClass) { - if (test(re)) { - cursor = re.lastIndex; - return true; - } - if (errorClass) { - throw new errorClass(`Expected ${re.toString()}`); - } - return false; - } - function match(re) { - re.lastIndex = cursor; - let result = re.exec(source); - if (result === null) { - throw new SyntaxError(`Expected ${re.toString()}`); - } - cursor = re.lastIndex; - return result; - } - function match1(re) { - return match(re)[1]; - } - function parseMessage(id) { - let value = parsePattern(); - let attributes = parseAttributes(); - if (value === null && Object.keys(attributes).length === 0) { - throw new SyntaxError("Expected message value or attributes"); - } - return { - id, - value, - attributes - }; - } - function parseAttributes() { - let attrs = Object.create(null); - while (test(RE_ATTRIBUTE_START)) { - let name = match1(RE_ATTRIBUTE_START); - let value = parsePattern(); - if (value === null) { - throw new SyntaxError("Expected attribute value"); - } - attrs[name] = value; - } - return attrs; - } - function parsePattern() { - let first; - if (test(RE_TEXT_RUN)) { - first = match1(RE_TEXT_RUN); - } - if (source[cursor] === "{" || source[cursor] === "}") { - return parsePatternElements(first ? [first] : [], Infinity); - } - let indent = parseIndent(); - if (indent) { - if (first) { - return parsePatternElements([first, indent], indent.length); - } - indent.value = trim(indent.value, RE_LEADING_NEWLINES); - return parsePatternElements([indent], indent.length); - } - if (first) { - return trim(first, RE_TRAILING_SPACES); - } - return null; - } - function parsePatternElements(elements = [], commonIndent) { - while (true) { - if (test(RE_TEXT_RUN)) { - elements.push(match1(RE_TEXT_RUN)); - continue; - } - if (source[cursor] === "{") { - elements.push(parsePlaceable()); - continue; - } - if (source[cursor] === "}") { - throw new SyntaxError("Unbalanced closing brace"); - } - let indent = parseIndent(); - if (indent) { - elements.push(indent); - commonIndent = Math.min(commonIndent, indent.length); - continue; - } - break; - } - let lastIndex = elements.length - 1; - let lastElement = elements[lastIndex]; - if (typeof lastElement === "string") { - elements[lastIndex] = trim(lastElement, RE_TRAILING_SPACES); - } - let baked = []; - for (let element of elements) { - if (element instanceof Indent) { - element = element.value.slice(0, element.value.length - commonIndent); - } - if (element) { - baked.push(element); - } - } - return baked; - } - function parsePlaceable() { - consumeToken(TOKEN_BRACE_OPEN, SyntaxError); - let selector = parseInlineExpression(); - if (consumeToken(TOKEN_BRACE_CLOSE)) { - return selector; - } - if (consumeToken(TOKEN_ARROW)) { - let variants = parseVariants(); - consumeToken(TOKEN_BRACE_CLOSE, SyntaxError); - return { - type: "select", - selector, - ...variants - }; - } - throw new SyntaxError("Unclosed placeable"); - } - function parseInlineExpression() { - if (source[cursor] === "{") { - return parsePlaceable(); - } - if (test(RE_REFERENCE)) { - let [, sigil, name, attr = null] = match(RE_REFERENCE); - if (sigil === "$") { - return { - type: "var", - name - }; - } - if (consumeToken(TOKEN_PAREN_OPEN)) { - let args = parseArguments(); - if (sigil === "-") { - return { - type: "term", - name, - attr, - args - }; - } - if (RE_FUNCTION_NAME.test(name)) { - return { - type: "func", - name, - args - }; - } - throw new SyntaxError("Function names must be all upper-case"); - } - if (sigil === "-") { - return { - type: "term", - name, - attr, - args: [] - }; - } - return { - type: "mesg", - name, - attr - }; - } - return parseLiteral(); - } - function parseArguments() { - let args = []; - while (true) { - switch (source[cursor]) { - case ")": - cursor++; - return args; - case undefined: - throw new SyntaxError("Unclosed argument list"); - } - args.push(parseArgument()); - consumeToken(TOKEN_COMMA); - } - } - function parseArgument() { - let expr = parseInlineExpression(); - if (expr.type !== "mesg") { - return expr; - } - if (consumeToken(TOKEN_COLON)) { - return { - type: "narg", - name: expr.name, - value: parseLiteral() - }; - } - return expr; - } - function parseVariants() { - let variants = []; - let count = 0; - let star; - while (test(RE_VARIANT_START)) { - if (consumeChar("*")) { - star = count; - } - let key = parseVariantKey(); - let value = parsePattern(); - if (value === null) { - throw new SyntaxError("Expected variant value"); - } - variants[count++] = { - key, - value - }; - } - if (count === 0) { - return null; - } - if (star === undefined) { - throw new SyntaxError("Expected default variant"); - } - return { - variants, - star - }; - } - function parseVariantKey() { - consumeToken(TOKEN_BRACKET_OPEN, SyntaxError); - let key; - if (test(RE_NUMBER_LITERAL)) { - key = parseNumberLiteral(); - } else { - key = { - type: "str", - value: match1(RE_IDENTIFIER) - }; - } - consumeToken(TOKEN_BRACKET_CLOSE, SyntaxError); - return key; - } - function parseLiteral() { - if (test(RE_NUMBER_LITERAL)) { - return parseNumberLiteral(); - } - if (source[cursor] === '"') { - return parseStringLiteral(); - } - throw new SyntaxError("Invalid expression"); - } - function parseNumberLiteral() { - let [, value, fraction = ""] = match(RE_NUMBER_LITERAL); - let precision = fraction.length; - return { - type: "num", - value: parseFloat(value), - precision - }; - } - function parseStringLiteral() { - consumeChar('"', SyntaxError); - let value = ""; - while (true) { - value += match1(RE_STRING_RUN); - if (source[cursor] === "\\") { - value += parseEscapeSequence(); - continue; - } - if (consumeChar('"')) { - return { - type: "str", - value - }; - } - throw new SyntaxError("Unclosed string literal"); - } - } - function parseEscapeSequence() { - if (test(RE_STRING_ESCAPE)) { - return match1(RE_STRING_ESCAPE); - } - if (test(RE_UNICODE_ESCAPE)) { - let [, codepoint4, codepoint6] = match(RE_UNICODE_ESCAPE); - let codepoint = parseInt(codepoint4 || codepoint6, 16); - return codepoint <= 0xd7ff || 0xe000 <= codepoint ? String.fromCodePoint(codepoint) : "�"; - } - throw new SyntaxError("Unknown escape sequence"); - } - function parseIndent() { - let start = cursor; - consumeToken(TOKEN_BLANK); - switch (source[cursor]) { - case ".": - case "[": - case "*": - case "}": - case undefined: - return false; - case "{": - return makeIndent(source.slice(start, cursor)); - } - if (source[cursor - 1] === " ") { - return makeIndent(source.slice(start, cursor)); - } - return false; - } - function trim(text, re) { - return text.replace(re, ""); - } - function makeIndent(blank) { - let value = blank.replace(RE_BLANK_LINES, "\n"); - let length = RE_INDENT.exec(blank)[1].length; - return new Indent(value, length); - } - } -} -class Indent { - constructor(value, length) { - this.value = value; - this.length = length; - } -} -;// ./node_modules/@fluent/bundle/esm/index.js - - - -;// ./node_modules/@fluent/dom/esm/overlay.js -const reOverlay = /<|&#?\w+;/; -const TEXT_LEVEL_ELEMENTS = { - "http://www.w3.org/1999/xhtml": ["em", "strong", "small", "s", "cite", "q", "dfn", "abbr", "data", "time", "code", "var", "samp", "kbd", "sub", "sup", "i", "b", "u", "mark", "bdi", "bdo", "span", "br", "wbr"] -}; -const LOCALIZABLE_ATTRIBUTES = { - "http://www.w3.org/1999/xhtml": { - global: ["title", "aria-label", "aria-valuetext"], - a: ["download"], - area: ["download", "alt"], - input: ["alt", "placeholder"], - menuitem: ["label"], - menu: ["label"], - optgroup: ["label"], - option: ["label"], - track: ["label"], - img: ["alt"], - textarea: ["placeholder"], - th: ["abbr"] - }, - "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul": { - global: ["accesskey", "aria-label", "aria-valuetext", "label", "title", "tooltiptext"], - description: ["value"], - key: ["key", "keycode"], - label: ["value"], - textbox: ["placeholder", "value"] - } -}; -function translateElement(element, translation) { - const { - value - } = translation; - if (typeof value === "string") { - if (element.localName === "title" && element.namespaceURI === "http://www.w3.org/1999/xhtml") { - element.textContent = value; - } else if (!reOverlay.test(value)) { - element.textContent = value; - } else { - const templateElement = element.ownerDocument.createElementNS("http://www.w3.org/1999/xhtml", "template"); - templateElement.innerHTML = value; - overlayChildNodes(templateElement.content, element); - } - } - overlayAttributes(translation, element); -} -function overlayChildNodes(fromFragment, toElement) { - for (const childNode of fromFragment.childNodes) { - if (childNode.nodeType === childNode.TEXT_NODE) { - continue; - } - if (childNode.hasAttribute("data-l10n-name")) { - const sanitized = getNodeForNamedElement(toElement, childNode); - fromFragment.replaceChild(sanitized, childNode); - continue; - } - if (isElementAllowed(childNode)) { - const sanitized = createSanitizedElement(childNode); - fromFragment.replaceChild(sanitized, childNode); - continue; - } - console.warn(`An element of forbidden type "${childNode.localName}" was found in ` + "the translation. Only safe text-level elements and elements with " + "data-l10n-name are allowed."); - fromFragment.replaceChild(createTextNodeFromTextContent(childNode), childNode); - } - toElement.textContent = ""; - toElement.appendChild(fromFragment); -} -function hasAttribute(attributes, name) { - if (!attributes) { - return false; - } - for (let attr of attributes) { - if (attr.name === name) { - return true; - } - } - return false; -} -function overlayAttributes(fromElement, toElement) { - const explicitlyAllowed = toElement.hasAttribute("data-l10n-attrs") ? toElement.getAttribute("data-l10n-attrs").split(",").map(i => i.trim()) : null; - for (const attr of Array.from(toElement.attributes)) { - if (isAttrNameLocalizable(attr.name, toElement, explicitlyAllowed) && !hasAttribute(fromElement.attributes, attr.name)) { - toElement.removeAttribute(attr.name); - } - } - if (!fromElement.attributes) { - return; - } - for (const attr of Array.from(fromElement.attributes)) { - if (isAttrNameLocalizable(attr.name, toElement, explicitlyAllowed) && toElement.getAttribute(attr.name) !== attr.value) { - toElement.setAttribute(attr.name, attr.value); - } - } -} -function getNodeForNamedElement(sourceElement, translatedChild) { - const childName = translatedChild.getAttribute("data-l10n-name"); - const sourceChild = sourceElement.querySelector(`[data-l10n-name="${childName}"]`); - if (!sourceChild) { - console.warn(`An element named "${childName}" wasn't found in the source.`); - return createTextNodeFromTextContent(translatedChild); - } - if (sourceChild.localName !== translatedChild.localName) { - console.warn(`An element named "${childName}" was found in the translation ` + `but its type ${translatedChild.localName} didn't match the ` + `element found in the source (${sourceChild.localName}).`); - return createTextNodeFromTextContent(translatedChild); - } - sourceElement.removeChild(sourceChild); - const clone = sourceChild.cloneNode(false); - return shallowPopulateUsing(translatedChild, clone); -} -function createSanitizedElement(element) { - const clone = element.ownerDocument.createElement(element.localName); - return shallowPopulateUsing(element, clone); -} -function createTextNodeFromTextContent(element) { - return element.ownerDocument.createTextNode(element.textContent); -} -function isElementAllowed(element) { - const allowed = TEXT_LEVEL_ELEMENTS[element.namespaceURI]; - return allowed && allowed.includes(element.localName); -} -function isAttrNameLocalizable(name, element, explicitlyAllowed = null) { - if (explicitlyAllowed && explicitlyAllowed.includes(name)) { - return true; - } - const allowed = LOCALIZABLE_ATTRIBUTES[element.namespaceURI]; - if (!allowed) { - return false; - } - const attrName = name.toLowerCase(); - const elemName = element.localName; - if (allowed.global.includes(attrName)) { - return true; - } - if (!allowed[elemName]) { - return false; - } - if (allowed[elemName].includes(attrName)) { - return true; - } - if (element.namespaceURI === "http://www.w3.org/1999/xhtml" && elemName === "input" && attrName === "value") { - const type = element.type.toLowerCase(); - if (type === "submit" || type === "button" || type === "reset") { - return true; - } - } - return false; -} -function shallowPopulateUsing(fromElement, toElement) { - toElement.textContent = fromElement.textContent; - overlayAttributes(fromElement, toElement); - return toElement; -} -;// ./node_modules/cached-iterable/src/cached_iterable.mjs -class CachedIterable extends Array { - static from(iterable) { - if (iterable instanceof this) { - return iterable; - } - return new this(iterable); - } -} -;// ./node_modules/cached-iterable/src/cached_sync_iterable.mjs - -class CachedSyncIterable extends CachedIterable { - constructor(iterable) { - super(); - if (Symbol.iterator in Object(iterable)) { - this.iterator = iterable[Symbol.iterator](); - } else { - throw new TypeError("Argument must implement the iteration protocol."); - } - } - [Symbol.iterator]() { - const cached = this; - let cur = 0; - return { - next() { - if (cached.length <= cur) { - cached.push(cached.iterator.next()); - } - return cached[cur++]; - } - }; - } - touchNext(count = 1) { - let idx = 0; - while (idx++ < count) { - const last = this[this.length - 1]; - if (last && last.done) { - break; - } - this.push(this.iterator.next()); - } - return this[this.length - 1]; - } -} -;// ./node_modules/cached-iterable/src/cached_async_iterable.mjs - -class CachedAsyncIterable extends CachedIterable { - constructor(iterable) { - super(); - if (Symbol.asyncIterator in Object(iterable)) { - this.iterator = iterable[Symbol.asyncIterator](); - } else if (Symbol.iterator in Object(iterable)) { - this.iterator = iterable[Symbol.iterator](); - } else { - throw new TypeError("Argument must implement the iteration protocol."); - } - } - [Symbol.asyncIterator]() { - const cached = this; - let cur = 0; - return { - async next() { - if (cached.length <= cur) { - cached.push(cached.iterator.next()); - } - return cached[cur++]; - } - }; - } - async touchNext(count = 1) { - let idx = 0; - while (idx++ < count) { - const last = this[this.length - 1]; - if (last && (await last).done) { - break; - } - this.push(this.iterator.next()); - } - return this[this.length - 1]; - } -} -;// ./node_modules/cached-iterable/src/index.mjs - - -;// ./node_modules/@fluent/dom/esm/localization.js - -class Localization { - constructor(resourceIds = [], generateBundles) { - this.resourceIds = resourceIds; - this.generateBundles = generateBundles; - this.onChange(true); - } - addResourceIds(resourceIds, eager = false) { - this.resourceIds.push(...resourceIds); - this.onChange(eager); - return this.resourceIds.length; - } - removeResourceIds(resourceIds) { - this.resourceIds = this.resourceIds.filter(r => !resourceIds.includes(r)); - this.onChange(); - return this.resourceIds.length; - } - async formatWithFallback(keys, method) { - const translations = []; - let hasAtLeastOneBundle = false; - for await (const bundle of this.bundles) { - hasAtLeastOneBundle = true; - const missingIds = keysFromBundle(method, bundle, keys, translations); - if (missingIds.size === 0) { - break; - } - if (typeof console !== "undefined") { - const locale = bundle.locales[0]; - const ids = Array.from(missingIds).join(", "); - console.warn(`[fluent] Missing translations in ${locale}: ${ids}`); - } - } - if (!hasAtLeastOneBundle && typeof console !== "undefined") { - console.warn(`[fluent] Request for keys failed because no resource bundles got generated. - keys: ${JSON.stringify(keys)}. - resourceIds: ${JSON.stringify(this.resourceIds)}.`); - } - return translations; - } - formatMessages(keys) { - return this.formatWithFallback(keys, messageFromBundle); - } - formatValues(keys) { - return this.formatWithFallback(keys, valueFromBundle); - } - async formatValue(id, args) { - const [val] = await this.formatValues([{ - id, - args - }]); - return val; - } - handleEvent() { - this.onChange(); - } - onChange(eager = false) { - this.bundles = CachedAsyncIterable.from(this.generateBundles(this.resourceIds)); - if (eager) { - this.bundles.touchNext(2); - } - } -} -function valueFromBundle(bundle, errors, message, args) { - if (message.value) { - return bundle.formatPattern(message.value, args, errors); - } - return null; -} -function messageFromBundle(bundle, errors, message, args) { - const formatted = { - value: null, - attributes: null - }; - if (message.value) { - formatted.value = bundle.formatPattern(message.value, args, errors); - } - let attrNames = Object.keys(message.attributes); - if (attrNames.length > 0) { - formatted.attributes = new Array(attrNames.length); - for (let [i, name] of attrNames.entries()) { - let value = bundle.formatPattern(message.attributes[name], args, errors); - formatted.attributes[i] = { - name, - value - }; - } - } - return formatted; -} -function keysFromBundle(method, bundle, keys, translations) { - const messageErrors = []; - const missingIds = new Set(); - keys.forEach(({ - id, - args - }, i) => { - if (translations[i] !== undefined) { - return; - } - let message = bundle.getMessage(id); - if (message) { - messageErrors.length = 0; - translations[i] = method(bundle, messageErrors, message, args); - if (messageErrors.length > 0 && typeof console !== "undefined") { - const locale = bundle.locales[0]; - const errors = messageErrors.join(", "); - console.warn(`[fluent][resolver] errors in ${locale}/${id}: ${errors}.`); - } - } else { - missingIds.add(id); - } - }); - return missingIds; -} -;// ./node_modules/@fluent/dom/esm/dom_localization.js - - -const L10NID_ATTR_NAME = "data-l10n-id"; -const L10NARGS_ATTR_NAME = "data-l10n-args"; -const L10N_ELEMENT_QUERY = `[${L10NID_ATTR_NAME}]`; -class DOMLocalization extends Localization { - constructor(resourceIds, generateBundles) { - super(resourceIds, generateBundles); - this.roots = new Set(); - this.pendingrAF = null; - this.pendingElements = new Set(); - this.windowElement = null; - this.mutationObserver = null; - this.observerConfig = { - attributes: true, - characterData: false, - childList: true, - subtree: true, - attributeFilter: [L10NID_ATTR_NAME, L10NARGS_ATTR_NAME] - }; - } - onChange(eager = false) { - super.onChange(eager); - if (this.roots) { - this.translateRoots(); - } - } - setAttributes(element, id, args) { - element.setAttribute(L10NID_ATTR_NAME, id); - if (args) { - element.setAttribute(L10NARGS_ATTR_NAME, JSON.stringify(args)); - } else { - element.removeAttribute(L10NARGS_ATTR_NAME); - } - return element; - } - getAttributes(element) { - return { - id: element.getAttribute(L10NID_ATTR_NAME), - args: JSON.parse(element.getAttribute(L10NARGS_ATTR_NAME) || null) - }; - } - connectRoot(newRoot) { - for (const root of this.roots) { - if (root === newRoot || root.contains(newRoot) || newRoot.contains(root)) { - throw new Error("Cannot add a root that overlaps with existing root."); - } - } - if (this.windowElement) { - if (this.windowElement !== newRoot.ownerDocument.defaultView) { - throw new Error(`Cannot connect a root: - DOMLocalization already has a root from a different window.`); - } - } else { - this.windowElement = newRoot.ownerDocument.defaultView; - this.mutationObserver = new this.windowElement.MutationObserver(mutations => this.translateMutations(mutations)); - } - this.roots.add(newRoot); - this.mutationObserver.observe(newRoot, this.observerConfig); - } - disconnectRoot(root) { - this.roots.delete(root); - this.pauseObserving(); - if (this.roots.size === 0) { - this.mutationObserver = null; - if (this.windowElement && this.pendingrAF) { - this.windowElement.cancelAnimationFrame(this.pendingrAF); - } - this.windowElement = null; - this.pendingrAF = null; - this.pendingElements.clear(); - return true; - } - this.resumeObserving(); - return false; - } - translateRoots() { - const roots = Array.from(this.roots); - return Promise.all(roots.map(root => this.translateFragment(root))); - } - pauseObserving() { - if (!this.mutationObserver) { - return; - } - this.translateMutations(this.mutationObserver.takeRecords()); - this.mutationObserver.disconnect(); - } - resumeObserving() { - if (!this.mutationObserver) { - return; - } - for (const root of this.roots) { - this.mutationObserver.observe(root, this.observerConfig); - } - } - translateMutations(mutations) { - for (const mutation of mutations) { - switch (mutation.type) { - case "attributes": - if (mutation.target.hasAttribute("data-l10n-id")) { - this.pendingElements.add(mutation.target); - } - break; - case "childList": - for (const addedNode of mutation.addedNodes) { - if (addedNode.nodeType === addedNode.ELEMENT_NODE) { - if (addedNode.childElementCount) { - for (const element of this.getTranslatables(addedNode)) { - this.pendingElements.add(element); - } - } else if (addedNode.hasAttribute(L10NID_ATTR_NAME)) { - this.pendingElements.add(addedNode); - } - } - } - break; - } - } - if (this.pendingElements.size > 0) { - if (this.pendingrAF === null) { - this.pendingrAF = this.windowElement.requestAnimationFrame(() => { - this.translateElements(Array.from(this.pendingElements)); - this.pendingElements.clear(); - this.pendingrAF = null; - }); - } - } - } - translateFragment(frag) { - return this.translateElements(this.getTranslatables(frag)); - } - async translateElements(elements) { - if (!elements.length) { - return undefined; - } - const keys = elements.map(this.getKeysForElement); - const translations = await this.formatMessages(keys); - return this.applyTranslations(elements, translations); - } - applyTranslations(elements, translations) { - this.pauseObserving(); - for (let i = 0; i < elements.length; i++) { - if (translations[i] !== undefined) { - translateElement(elements[i], translations[i]); - } - } - this.resumeObserving(); - } - getTranslatables(element) { - const nodes = Array.from(element.querySelectorAll(L10N_ELEMENT_QUERY)); - if (typeof element.hasAttribute === "function" && element.hasAttribute(L10NID_ATTR_NAME)) { - nodes.push(element); - } - return nodes; - } - getKeysForElement(element) { - return { - id: element.getAttribute(L10NID_ATTR_NAME), - args: JSON.parse(element.getAttribute(L10NARGS_ATTR_NAME) || null) - }; - } -} -;// ./node_modules/@fluent/dom/esm/index.js - - -;// ./web/l10n.js -class L10n { - #dir; - #elements; - #lang; - #l10n; - constructor({ - lang, - isRTL - }, l10n = null) { - this.#lang = L10n.#fixupLangCode(lang); - this.#l10n = l10n; - this.#dir = isRTL ?? L10n.#isRTL(this.#lang) ? "rtl" : "ltr"; - } - _setL10n(l10n) { - this.#l10n = l10n; - } - getLanguage() { - return this.#lang; - } - getDirection() { - return this.#dir; - } - async get(ids, args = null, fallback) { - if (Array.isArray(ids)) { - ids = ids.map(id => ({ - id - })); - const messages = await this.#l10n.formatMessages(ids); - return messages.map(message => message.value); - } - const messages = await this.#l10n.formatMessages([{ - id: ids, - args - }]); - return messages[0]?.value || fallback; - } - async translate(element) { - (this.#elements ||= new Set()).add(element); - try { - this.#l10n.connectRoot(element); - await this.#l10n.translateRoots(); - } catch {} - } - async translateOnce(element) { - try { - await this.#l10n.translateElements([element]); - } catch (ex) { - console.error("translateOnce:", ex); - } - } - async destroy() { - if (this.#elements) { - for (const element of this.#elements) { - this.#l10n.disconnectRoot(element); - } - this.#elements.clear(); - this.#elements = null; - } - this.#l10n.pauseObserving(); - } - pause() { - this.#l10n.pauseObserving(); - } - resume() { - this.#l10n.resumeObserving(); - } - static #fixupLangCode(langCode) { - langCode = langCode?.toLowerCase() || "en-us"; - const PARTIAL_LANG_CODES = { - en: "en-us", - es: "es-es", - fy: "fy-nl", - ga: "ga-ie", - gu: "gu-in", - hi: "hi-in", - hy: "hy-am", - nb: "nb-no", - ne: "ne-np", - nn: "nn-no", - pa: "pa-in", - pt: "pt-pt", - sv: "sv-se", - zh: "zh-cn" - }; - return PARTIAL_LANG_CODES[langCode] || langCode; - } - static #isRTL(lang) { - const shortCode = lang.split("-", 1)[0]; - return ["ar", "he", "fa", "ps", "ur"].includes(shortCode); - } -} -const GenericL10n = null; - -;// ./web/genericl10n.js - - - - -function createBundle(lang, text) { - const resource = new FluentResource(text); - const bundle = new FluentBundle(lang); - const errors = bundle.addResource(resource); - if (errors.length) { - console.error("L10n errors", errors); - } - return bundle; -} -class genericl10n_GenericL10n extends L10n { - constructor(lang) { - super({ - lang - }); - const generateBundles = !lang ? genericl10n_GenericL10n.#generateBundlesFallback.bind(genericl10n_GenericL10n, this.getLanguage()) : genericl10n_GenericL10n.#generateBundles.bind(genericl10n_GenericL10n, "en-us", this.getLanguage()); - this._setL10n(new DOMLocalization([], generateBundles)); - } - static async *#generateBundles(defaultLang, baseLang) { - const { - baseURL, - paths - } = await this.#getPaths(); - const langs = [baseLang]; - if (defaultLang !== baseLang) { - const shortLang = baseLang.split("-", 1)[0]; - if (shortLang !== baseLang) { - langs.push(shortLang); - } - langs.push(defaultLang); - } - for (const lang of langs) { - const bundle = await this.#createBundle(lang, baseURL, paths); - if (bundle) { - yield bundle; - } else if (lang === "en-us") { - yield this.#createBundleFallback(lang); - } - } - } - static async #createBundle(lang, baseURL, paths) { - const path = paths[lang]; - if (!path) { - return null; - } - const url = new URL(path, baseURL); - const text = await fetchData(url, "text"); - return createBundle(lang, text); - } - static async #getPaths() { - try { - const { - href - } = document.querySelector(`link[type="application/l10n"]`); - const paths = await fetchData(href, "json"); - return { - baseURL: href.replace(/[^/]*$/, "") || "./", - paths - }; - } catch {} - return { - baseURL: "./", - paths: Object.create(null) - }; - } - static async *#generateBundlesFallback(lang) { - yield this.#createBundleFallback(lang); - } - static async #createBundleFallback(lang) { - const text = "pdfjs-previous-button =\n .title = Previous Page\npdfjs-previous-button-label = Previous\npdfjs-next-button =\n .title = Next Page\npdfjs-next-button-label = Next\npdfjs-page-input =\n .title = Page\npdfjs-of-pages = of { $pagesCount }\npdfjs-page-of-pages = ({ $pageNumber } of { $pagesCount })\npdfjs-zoom-out-button =\n .title = Zoom Out\npdfjs-zoom-out-button-label = Zoom Out\npdfjs-zoom-in-button =\n .title = Zoom In\npdfjs-zoom-in-button-label = Zoom In\npdfjs-zoom-select =\n .title = Zoom\npdfjs-presentation-mode-button =\n .title = Switch to Presentation Mode\npdfjs-presentation-mode-button-label = Presentation Mode\npdfjs-open-file-button =\n .title = Open File\npdfjs-open-file-button-label = Open\npdfjs-print-button =\n .title = Print\npdfjs-print-button-label = Print\npdfjs-save-button =\n .title = Save\npdfjs-save-button-label = Save\npdfjs-download-button =\n .title = Download\npdfjs-download-button-label = Download\npdfjs-bookmark-button =\n .title = Current Page (View URL from Current Page)\npdfjs-bookmark-button-label = Current Page\npdfjs-tools-button =\n .title = Tools\npdfjs-tools-button-label = Tools\npdfjs-first-page-button =\n .title = Go to First Page\npdfjs-first-page-button-label = Go to First Page\npdfjs-last-page-button =\n .title = Go to Last Page\npdfjs-last-page-button-label = Go to Last Page\npdfjs-page-rotate-cw-button =\n .title = Rotate Clockwise\npdfjs-page-rotate-cw-button-label = Rotate Clockwise\npdfjs-page-rotate-ccw-button =\n .title = Rotate Counterclockwise\npdfjs-page-rotate-ccw-button-label = Rotate Counterclockwise\npdfjs-cursor-text-select-tool-button =\n .title = Enable Text Selection Tool\npdfjs-cursor-text-select-tool-button-label = Text Selection Tool\npdfjs-cursor-hand-tool-button =\n .title = Enable Hand Tool\npdfjs-cursor-hand-tool-button-label = Hand Tool\npdfjs-scroll-page-button =\n .title = Use Page Scrolling\npdfjs-scroll-page-button-label = Page Scrolling\npdfjs-scroll-vertical-button =\n .title = Use Vertical Scrolling\npdfjs-scroll-vertical-button-label = Vertical Scrolling\npdfjs-scroll-horizontal-button =\n .title = Use Horizontal Scrolling\npdfjs-scroll-horizontal-button-label = Horizontal Scrolling\npdfjs-scroll-wrapped-button =\n .title = Use Wrapped Scrolling\npdfjs-scroll-wrapped-button-label = Wrapped Scrolling\npdfjs-spread-none-button =\n .title = Do not join page spreads\npdfjs-spread-none-button-label = No Spreads\npdfjs-spread-odd-button =\n .title = Join page spreads starting with odd-numbered pages\npdfjs-spread-odd-button-label = Odd Spreads\npdfjs-spread-even-button =\n .title = Join page spreads starting with even-numbered pages\npdfjs-spread-even-button-label = Even Spreads\npdfjs-document-properties-button =\n .title = Document Properties\u2026\npdfjs-document-properties-button-label = Document Properties\u2026\npdfjs-document-properties-file-name = File name:\npdfjs-document-properties-file-size = File size:\npdfjs-document-properties-size-kb = { NUMBER($kb, maximumSignificantDigits: 3) } KB ({ $b } bytes)\npdfjs-document-properties-size-mb = { NUMBER($mb, maximumSignificantDigits: 3) } MB ({ $b } bytes)\npdfjs-document-properties-title = Title:\npdfjs-document-properties-author = Author:\npdfjs-document-properties-subject = Subject:\npdfjs-document-properties-keywords = Keywords:\npdfjs-document-properties-creation-date = Creation Date:\npdfjs-document-properties-modification-date = Modification Date:\npdfjs-document-properties-date-time-string = { DATETIME($dateObj, dateStyle: \"short\", timeStyle: \"medium\") }\npdfjs-document-properties-creator = Creator:\npdfjs-document-properties-producer = PDF Producer:\npdfjs-document-properties-version = PDF Version:\npdfjs-document-properties-page-count = Page Count:\npdfjs-document-properties-page-size = Page Size:\npdfjs-document-properties-page-size-unit-inches = in\npdfjs-document-properties-page-size-unit-millimeters = mm\npdfjs-document-properties-page-size-orientation-portrait = portrait\npdfjs-document-properties-page-size-orientation-landscape = landscape\npdfjs-document-properties-page-size-name-a-three = A3\npdfjs-document-properties-page-size-name-a-four = A4\npdfjs-document-properties-page-size-name-letter = Letter\npdfjs-document-properties-page-size-name-legal = Legal\npdfjs-document-properties-page-size-dimension-string = { $width } \xD7 { $height } { $unit } ({ $orientation })\npdfjs-document-properties-page-size-dimension-name-string = { $width } \xD7 { $height } { $unit } ({ $name }, { $orientation })\npdfjs-document-properties-linearized = Fast Web View:\npdfjs-document-properties-linearized-yes = Yes\npdfjs-document-properties-linearized-no = No\npdfjs-document-properties-close-button = Close\npdfjs-print-progress-message = Preparing document for printing\u2026\npdfjs-print-progress-percent = { $progress }%\npdfjs-print-progress-close-button = Cancel\npdfjs-printing-not-supported = Warning: Printing is not fully supported by this browser.\npdfjs-printing-not-ready = Warning: The PDF is not fully loaded for printing.\npdfjs-toggle-sidebar-button =\n .title = Toggle Sidebar\npdfjs-toggle-sidebar-notification-button =\n .title = Toggle Sidebar (document contains outline/attachments/layers)\npdfjs-toggle-sidebar-button-label = Toggle Sidebar\npdfjs-document-outline-button =\n .title = Show Document Outline (double-click to expand/collapse all items)\npdfjs-document-outline-button-label = Document Outline\npdfjs-attachments-button =\n .title = Show Attachments\npdfjs-attachments-button-label = Attachments\npdfjs-layers-button =\n .title = Show Layers (double-click to reset all layers to the default state)\npdfjs-layers-button-label = Layers\npdfjs-thumbs-button =\n .title = Show Thumbnails\npdfjs-thumbs-button-label = Thumbnails\npdfjs-current-outline-item-button =\n .title = Find Current Outline Item\npdfjs-current-outline-item-button-label = Current Outline Item\npdfjs-findbar-button =\n .title = Find in Document\npdfjs-findbar-button-label = Find\npdfjs-additional-layers = Additional Layers\npdfjs-thumb-page-title =\n .title = Page { $page }\npdfjs-thumb-page-canvas =\n .aria-label = Thumbnail of Page { $page }\npdfjs-find-input =\n .title = Find\n .placeholder = Find in document\u2026\npdfjs-find-previous-button =\n .title = Find the previous occurrence of the phrase\npdfjs-find-previous-button-label = Previous\npdfjs-find-next-button =\n .title = Find the next occurrence of the phrase\npdfjs-find-next-button-label = Next\npdfjs-find-highlight-checkbox = Highlight All\npdfjs-find-match-case-checkbox-label = Match Case\npdfjs-find-match-diacritics-checkbox-label = Match Diacritics\npdfjs-find-entire-word-checkbox-label = Whole Words\npdfjs-find-reached-top = Reached top of document, continued from bottom\npdfjs-find-reached-bottom = Reached end of document, continued from top\npdfjs-find-match-count =\n { $total ->\n [one] { $current } of { $total } match\n *[other] { $current } of { $total } matches\n }\npdfjs-find-match-count-limit =\n { $limit ->\n [one] More than { $limit } match\n *[other] More than { $limit } matches\n }\npdfjs-find-not-found = Phrase not found\npdfjs-page-scale-width = Page Width\npdfjs-page-scale-fit = Page Fit\npdfjs-page-scale-auto = Automatic Zoom\npdfjs-page-scale-actual = Actual Size\npdfjs-page-scale-percent = { $scale }%\npdfjs-page-landmark =\n .aria-label = Page { $page }\npdfjs-loading-error = An error occurred while loading the PDF.\npdfjs-invalid-file-error = Invalid or corrupted PDF file.\npdfjs-missing-file-error = Missing PDF file.\npdfjs-unexpected-response-error = Unexpected server response.\npdfjs-rendering-error = An error occurred while rendering the page.\npdfjs-annotation-date-time-string = { DATETIME($dateObj, dateStyle: \"short\", timeStyle: \"medium\") }\npdfjs-text-annotation-type =\n .alt = [{ $type } Annotation]\npdfjs-password-label = Enter the password to open this PDF file.\npdfjs-password-invalid = Invalid password. Please try again.\npdfjs-password-ok-button = OK\npdfjs-password-cancel-button = Cancel\npdfjs-web-fonts-disabled = Web fonts are disabled: unable to use embedded PDF fonts.\npdfjs-editor-free-text-button =\n .title = Text\npdfjs-editor-free-text-button-label = Text\npdfjs-editor-ink-button =\n .title = Draw\npdfjs-editor-ink-button-label = Draw\npdfjs-editor-stamp-button =\n .title = Add or edit images\npdfjs-editor-stamp-button-label = Add or edit images\npdfjs-editor-highlight-button =\n .title = Highlight\npdfjs-editor-highlight-button-label = Highlight\npdfjs-highlight-floating-button1 =\n .title = Highlight\n .aria-label = Highlight\npdfjs-highlight-floating-button-label = Highlight\npdfjs-editor-remove-ink-button =\n .title = Remove drawing\npdfjs-editor-remove-freetext-button =\n .title = Remove text\npdfjs-editor-remove-stamp-button =\n .title = Remove image\npdfjs-editor-remove-highlight-button =\n .title = Remove highlight\npdfjs-editor-free-text-color-input = Color\npdfjs-editor-free-text-size-input = Size\npdfjs-editor-ink-color-input = Color\npdfjs-editor-ink-thickness-input = Thickness\npdfjs-editor-ink-opacity-input = Opacity\npdfjs-editor-stamp-add-image-button =\n .title = Add image\npdfjs-editor-stamp-add-image-button-label = Add image\npdfjs-editor-free-highlight-thickness-input = Thickness\npdfjs-editor-free-highlight-thickness-title =\n .title = Change thickness when highlighting items other than text\npdfjs-free-text2 =\n .aria-label = Text Editor\n .default-content = Start typing\u2026\npdfjs-ink =\n .aria-label = Draw Editor\npdfjs-ink-canvas =\n .aria-label = User-created image\npdfjs-editor-alt-text-button =\n .aria-label = Alt text\npdfjs-editor-alt-text-button-label = Alt text\npdfjs-editor-alt-text-edit-button =\n .aria-label = Edit alt text\npdfjs-editor-alt-text-dialog-label = Choose an option\npdfjs-editor-alt-text-dialog-description = Alt text (alternative text) helps when people can\u2019t see the image or when it doesn\u2019t load.\npdfjs-editor-alt-text-add-description-label = Add a description\npdfjs-editor-alt-text-add-description-description = Aim for 1-2 sentences that describe the subject, setting, or actions.\npdfjs-editor-alt-text-mark-decorative-label = Mark as decorative\npdfjs-editor-alt-text-mark-decorative-description = This is used for ornamental images, like borders or watermarks.\npdfjs-editor-alt-text-cancel-button = Cancel\npdfjs-editor-alt-text-save-button = Save\npdfjs-editor-alt-text-decorative-tooltip = Marked as decorative\npdfjs-editor-alt-text-textarea =\n .placeholder = For example, \u201CA young man sits down at a table to eat a meal\u201D\npdfjs-editor-resizer-top-left =\n .aria-label = Top left corner \u2014 resize\npdfjs-editor-resizer-top-middle =\n .aria-label = Top middle \u2014 resize\npdfjs-editor-resizer-top-right =\n .aria-label = Top right corner \u2014 resize\npdfjs-editor-resizer-middle-right =\n .aria-label = Middle right \u2014 resize\npdfjs-editor-resizer-bottom-right =\n .aria-label = Bottom right corner \u2014 resize\npdfjs-editor-resizer-bottom-middle =\n .aria-label = Bottom middle \u2014 resize\npdfjs-editor-resizer-bottom-left =\n .aria-label = Bottom left corner \u2014 resize\npdfjs-editor-resizer-middle-left =\n .aria-label = Middle left \u2014 resize\npdfjs-editor-highlight-colorpicker-label = Highlight color\npdfjs-editor-colorpicker-button =\n .title = Change color\npdfjs-editor-colorpicker-dropdown =\n .aria-label = Color choices\npdfjs-editor-colorpicker-yellow =\n .title = Yellow\npdfjs-editor-colorpicker-green =\n .title = Green\npdfjs-editor-colorpicker-blue =\n .title = Blue\npdfjs-editor-colorpicker-pink =\n .title = Pink\npdfjs-editor-colorpicker-red =\n .title = Red\npdfjs-editor-highlight-show-all-button-label = Show all\npdfjs-editor-highlight-show-all-button =\n .title = Show all\npdfjs-editor-new-alt-text-dialog-edit-label = Edit alt text (image description)\npdfjs-editor-new-alt-text-dialog-add-label = Add alt text (image description)\npdfjs-editor-new-alt-text-textarea =\n .placeholder = Write your description here\u2026\npdfjs-editor-new-alt-text-description = Short description for people who can\u2019t see the image or when the image doesn\u2019t load.\npdfjs-editor-new-alt-text-disclaimer1 = This alt text was created automatically and may be inaccurate.\npdfjs-editor-new-alt-text-disclaimer-learn-more-url = Learn more\npdfjs-editor-new-alt-text-create-automatically-button-label = Create alt text automatically\npdfjs-editor-new-alt-text-not-now-button = Not now\npdfjs-editor-new-alt-text-error-title = Couldn\u2019t create alt text automatically\npdfjs-editor-new-alt-text-error-description = Please write your own alt text or try again later.\npdfjs-editor-new-alt-text-error-close-button = Close\npdfjs-editor-new-alt-text-ai-model-downloading-progress = Downloading alt text AI model ({ $downloadedSize } of { $totalSize } MB)\n .aria-valuetext = Downloading alt text AI model ({ $downloadedSize } of { $totalSize } MB)\npdfjs-editor-new-alt-text-added-button =\n .aria-label = Alt text added\npdfjs-editor-new-alt-text-added-button-label = Alt text added\npdfjs-editor-new-alt-text-missing-button =\n .aria-label = Missing alt text\npdfjs-editor-new-alt-text-missing-button-label = Missing alt text\npdfjs-editor-new-alt-text-to-review-button =\n .aria-label = Review alt text\npdfjs-editor-new-alt-text-to-review-button-label = Review alt text\npdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer = Created automatically: { $generatedAltText }\npdfjs-image-alt-text-settings-button =\n .title = Image alt text settings\npdfjs-image-alt-text-settings-button-label = Image alt text settings\npdfjs-editor-alt-text-settings-dialog-label = Image alt text settings\npdfjs-editor-alt-text-settings-automatic-title = Automatic alt text\npdfjs-editor-alt-text-settings-create-model-button-label = Create alt text automatically\npdfjs-editor-alt-text-settings-create-model-description = Suggests descriptions to help people who can\u2019t see the image or when the image doesn\u2019t load.\npdfjs-editor-alt-text-settings-download-model-label = Alt text AI model ({ $totalSize } MB)\npdfjs-editor-alt-text-settings-ai-model-description = Runs locally on your device so your data stays private. Required for automatic alt text.\npdfjs-editor-alt-text-settings-delete-model-button = Delete\npdfjs-editor-alt-text-settings-download-model-button = Download\npdfjs-editor-alt-text-settings-downloading-model-button = Downloading\u2026\npdfjs-editor-alt-text-settings-editor-title = Alt text editor\npdfjs-editor-alt-text-settings-show-dialog-button-label = Show alt text editor right away when adding an image\npdfjs-editor-alt-text-settings-show-dialog-description = Helps you make sure all your images have alt text.\npdfjs-editor-alt-text-settings-close-button = Close\npdfjs-editor-undo-bar-message-highlight = Highlight removed\npdfjs-editor-undo-bar-message-freetext = Text removed\npdfjs-editor-undo-bar-message-ink = Drawing removed\npdfjs-editor-undo-bar-message-stamp = Image removed\npdfjs-editor-undo-bar-message-multiple =\n { $count ->\n [one] { $count } annotation removed\n *[other] { $count } annotations removed\n }\npdfjs-editor-undo-bar-undo-button =\n .title = Undo\npdfjs-editor-undo-bar-undo-button-label = Undo\npdfjs-editor-undo-bar-close-button =\n .title = Close\npdfjs-editor-undo-bar-close-button-label = Close"; - return createBundle(lang, text); - } -} - -;// ./web/pdf_history.js - - -const HASH_CHANGE_TIMEOUT = 1000; -const POSITION_UPDATED_THRESHOLD = 50; -const UPDATE_VIEWAREA_TIMEOUT = 1000; -function getCurrentHash() { - return document.location.hash; -} -class PDFHistory { - #eventAbortController = null; - constructor({ - linkService, - eventBus - }) { - this.linkService = linkService; - this.eventBus = eventBus; - this._initialized = false; - this._fingerprint = ""; - this.reset(); - this.eventBus._on("pagesinit", () => { - this._isPagesLoaded = false; - this.eventBus._on("pagesloaded", evt => { - this._isPagesLoaded = !!evt.pagesCount; - }, { - once: true - }); - }); - } - initialize({ - fingerprint, - resetHistory = false, - updateUrl = false - }) { - if (!fingerprint || typeof fingerprint !== "string") { - console.error('PDFHistory.initialize: The "fingerprint" must be a non-empty string.'); - return; - } - if (this._initialized) { - this.reset(); - } - const reInitialized = this._fingerprint !== "" && this._fingerprint !== fingerprint; - this._fingerprint = fingerprint; - this._updateUrl = updateUrl === true; - this._initialized = true; - this.#bindEvents(); - const state = window.history.state; - this._popStateInProgress = false; - this._blockHashChange = 0; - this._currentHash = getCurrentHash(); - this._numPositionUpdates = 0; - this._uid = this._maxUid = 0; - this._destination = null; - this._position = null; - if (!this.#isValidState(state, true) || resetHistory) { - const { - hash, - page, - rotation - } = this.#parseCurrentHash(true); - if (!hash || reInitialized || resetHistory) { - this.#pushOrReplaceState(null, true); - return; - } - this.#pushOrReplaceState({ - hash, - page, - rotation - }, true); - return; - } - const destination = state.destination; - this.#updateInternalState(destination, state.uid, true); - if (destination.rotation !== undefined) { - this._initialRotation = destination.rotation; - } - if (destination.dest) { - this._initialBookmark = JSON.stringify(destination.dest); - this._destination.page = null; - } else if (destination.hash) { - this._initialBookmark = destination.hash; - } else if (destination.page) { - this._initialBookmark = `page=${destination.page}`; - } - } - reset() { - if (this._initialized) { - this.#pageHide(); - this._initialized = false; - this.#unbindEvents(); - } - if (this._updateViewareaTimeout) { - clearTimeout(this._updateViewareaTimeout); - this._updateViewareaTimeout = null; - } - this._initialBookmark = null; - this._initialRotation = null; - } - push({ - namedDest = null, - explicitDest, - pageNumber - }) { - if (!this._initialized) { - return; - } - if (namedDest && typeof namedDest !== "string") { - console.error("PDFHistory.push: " + `"${namedDest}" is not a valid namedDest parameter.`); - return; - } else if (!Array.isArray(explicitDest)) { - console.error("PDFHistory.push: " + `"${explicitDest}" is not a valid explicitDest parameter.`); - return; - } else if (!this.#isValidPage(pageNumber)) { - if (pageNumber !== null || this._destination) { - console.error("PDFHistory.push: " + `"${pageNumber}" is not a valid pageNumber parameter.`); - return; - } - } - const hash = namedDest || JSON.stringify(explicitDest); - if (!hash) { - return; - } - let forceReplace = false; - if (this._destination && (isDestHashesEqual(this._destination.hash, hash) || isDestArraysEqual(this._destination.dest, explicitDest))) { - if (this._destination.page) { - return; - } - forceReplace = true; - } - if (this._popStateInProgress && !forceReplace) { - return; - } - this.#pushOrReplaceState({ - dest: explicitDest, - hash, - page: pageNumber, - rotation: this.linkService.rotation - }, forceReplace); - if (!this._popStateInProgress) { - this._popStateInProgress = true; - Promise.resolve().then(() => { - this._popStateInProgress = false; - }); - } - } - pushPage(pageNumber) { - if (!this._initialized) { - return; - } - if (!this.#isValidPage(pageNumber)) { - console.error(`PDFHistory.pushPage: "${pageNumber}" is not a valid page number.`); - return; - } - if (this._destination?.page === pageNumber) { - return; - } - if (this._popStateInProgress) { - return; - } - this.#pushOrReplaceState({ - dest: null, - hash: `page=${pageNumber}`, - page: pageNumber, - rotation: this.linkService.rotation - }); - if (!this._popStateInProgress) { - this._popStateInProgress = true; - Promise.resolve().then(() => { - this._popStateInProgress = false; - }); - } - } - pushCurrentPosition() { - if (!this._initialized || this._popStateInProgress) { - return; - } - this.#tryPushCurrentPosition(); - } - back() { - if (!this._initialized || this._popStateInProgress) { - return; - } - const state = window.history.state; - if (this.#isValidState(state) && state.uid > 0) { - window.history.back(); - } - } - forward() { - if (!this._initialized || this._popStateInProgress) { - return; - } - const state = window.history.state; - if (this.#isValidState(state) && state.uid < this._maxUid) { - window.history.forward(); - } - } - get popStateInProgress() { - return this._initialized && (this._popStateInProgress || this._blockHashChange > 0); - } - get initialBookmark() { - return this._initialized ? this._initialBookmark : null; - } - get initialRotation() { - return this._initialized ? this._initialRotation : null; - } - #pushOrReplaceState(destination, forceReplace = false) { - const shouldReplace = forceReplace || !this._destination; - const newState = { - fingerprint: this._fingerprint, - uid: shouldReplace ? this._uid : this._uid + 1, - destination - }; - this.#updateInternalState(destination, newState.uid); - let newUrl; - if (this._updateUrl && destination?.hash) { - const baseUrl = document.location.href.split("#", 1)[0]; - if (!baseUrl.startsWith("file://")) { - newUrl = `${baseUrl}#${destination.hash}`; - } - } - if (shouldReplace) { - window.history.replaceState(newState, "", newUrl); - } else { - window.history.pushState(newState, "", newUrl); - } - } - #tryPushCurrentPosition(temporary = false) { - if (!this._position) { - return; - } - let position = this._position; - if (temporary) { - position = Object.assign(Object.create(null), this._position); - position.temporary = true; - } - if (!this._destination) { - this.#pushOrReplaceState(position); - return; - } - if (this._destination.temporary) { - this.#pushOrReplaceState(position, true); - return; - } - if (this._destination.hash === position.hash) { - return; - } - if (!this._destination.page && (POSITION_UPDATED_THRESHOLD <= 0 || this._numPositionUpdates <= POSITION_UPDATED_THRESHOLD)) { - return; - } - let forceReplace = false; - if (this._destination.page >= position.first && this._destination.page <= position.page) { - if (this._destination.dest !== undefined || !this._destination.first) { - return; - } - forceReplace = true; - } - this.#pushOrReplaceState(position, forceReplace); - } - #isValidPage(val) { - return Number.isInteger(val) && val > 0 && val <= this.linkService.pagesCount; - } - #isValidState(state, checkReload = false) { - if (!state) { - return false; - } - if (state.fingerprint !== this._fingerprint) { - if (checkReload) { - if (typeof state.fingerprint !== "string" || state.fingerprint.length !== this._fingerprint.length) { - return false; - } - const [perfEntry] = performance.getEntriesByType("navigation"); - if (perfEntry?.type !== "reload") { - return false; - } - } else { - return false; - } - } - if (!Number.isInteger(state.uid) || state.uid < 0) { - return false; - } - if (state.destination === null || typeof state.destination !== "object") { - return false; - } - return true; - } - #updateInternalState(destination, uid, removeTemporary = false) { - if (this._updateViewareaTimeout) { - clearTimeout(this._updateViewareaTimeout); - this._updateViewareaTimeout = null; - } - if (removeTemporary && destination?.temporary) { - delete destination.temporary; - } - this._destination = destination; - this._uid = uid; - this._maxUid = Math.max(this._maxUid, uid); - this._numPositionUpdates = 0; - } - #parseCurrentHash(checkNameddest = false) { - const hash = unescape(getCurrentHash()).substring(1); - const params = parseQueryString(hash); - const nameddest = params.get("nameddest") || ""; - let page = params.get("page") | 0; - if (!this.#isValidPage(page) || checkNameddest && nameddest.length > 0) { - page = null; - } - return { - hash, - page, - rotation: this.linkService.rotation - }; - } - #updateViewarea({ - location - }) { - if (this._updateViewareaTimeout) { - clearTimeout(this._updateViewareaTimeout); - this._updateViewareaTimeout = null; - } - this._position = { - hash: location.pdfOpenParams.substring(1), - page: this.linkService.page, - first: location.pageNumber, - rotation: location.rotation - }; - if (this._popStateInProgress) { - return; - } - if (POSITION_UPDATED_THRESHOLD > 0 && this._isPagesLoaded && this._destination && !this._destination.page) { - this._numPositionUpdates++; - } - if (UPDATE_VIEWAREA_TIMEOUT > 0) { - this._updateViewareaTimeout = setTimeout(() => { - if (!this._popStateInProgress) { - this.#tryPushCurrentPosition(true); - } - this._updateViewareaTimeout = null; - }, UPDATE_VIEWAREA_TIMEOUT); - } - } - #popState({ - state - }) { - const newHash = getCurrentHash(), - hashChanged = this._currentHash !== newHash; - this._currentHash = newHash; - if (!state) { - this._uid++; - const { - hash, - page, - rotation - } = this.#parseCurrentHash(); - this.#pushOrReplaceState({ - hash, - page, - rotation - }, true); - return; - } - if (!this.#isValidState(state)) { - return; - } - this._popStateInProgress = true; - if (hashChanged) { - this._blockHashChange++; - waitOnEventOrTimeout({ - target: window, - name: "hashchange", - delay: HASH_CHANGE_TIMEOUT - }).then(() => { - this._blockHashChange--; - }); - } - const destination = state.destination; - this.#updateInternalState(destination, state.uid, true); - if (isValidRotation(destination.rotation)) { - this.linkService.rotation = destination.rotation; - } - if (destination.dest) { - this.linkService.goToDestination(destination.dest); - } else if (destination.hash) { - this.linkService.setHash(destination.hash); - } else if (destination.page) { - this.linkService.page = destination.page; - } - Promise.resolve().then(() => { - this._popStateInProgress = false; - }); - } - #pageHide() { - if (!this._destination || this._destination.temporary) { - this.#tryPushCurrentPosition(); - } - } - #bindEvents() { - if (this.#eventAbortController) { - return; - } - this.#eventAbortController = new AbortController(); - const { - signal - } = this.#eventAbortController; - this.eventBus._on("updateviewarea", this.#updateViewarea.bind(this), { - signal - }); - window.addEventListener("popstate", this.#popState.bind(this), { - signal - }); - window.addEventListener("pagehide", this.#pageHide.bind(this), { - signal - }); - } - #unbindEvents() { - this.#eventAbortController?.abort(); - this.#eventAbortController = null; - } -} -function isDestHashesEqual(destHash, pushHash) { - if (typeof destHash !== "string" || typeof pushHash !== "string") { - return false; - } - if (destHash === pushHash) { - return true; - } - const nameddest = parseQueryString(destHash).get("nameddest"); - if (nameddest === pushHash) { - return true; - } - return false; -} -function isDestArraysEqual(firstDest, secondDest) { - function isEntryEqual(first, second) { - if (typeof first !== typeof second) { - return false; - } - if (Array.isArray(first) || Array.isArray(second)) { - return false; - } - if (first !== null && typeof first === "object" && second !== null) { - if (Object.keys(first).length !== Object.keys(second).length) { - return false; - } - for (const key in first) { - if (!isEntryEqual(first[key], second[key])) { - return false; - } - } - return true; - } - return first === second || Number.isNaN(first) && Number.isNaN(second); - } - if (!(Array.isArray(firstDest) && Array.isArray(secondDest))) { - return false; - } - if (firstDest.length !== secondDest.length) { - return false; - } - for (let i = 0, ii = firstDest.length; i < ii; i++) { - if (!isEntryEqual(firstDest[i], secondDest[i])) { - return false; - } - } - return true; -} - -;// ./web/annotation_editor_layer_builder.js - - -class AnnotationEditorLayerBuilder { - #annotationLayer = null; - #drawLayer = null; - #onAppend = null; - #structTreeLayer = null; - #textLayer = null; - #uiManager; - constructor(options) { - this.pdfPage = options.pdfPage; - this.accessibilityManager = options.accessibilityManager; - this.l10n = options.l10n; - this.l10n ||= new genericl10n_GenericL10n(); - this.annotationEditorLayer = null; - this.div = null; - this._cancelled = false; - this.#uiManager = options.uiManager; - this.#annotationLayer = options.annotationLayer || null; - this.#textLayer = options.textLayer || null; - this.#drawLayer = options.drawLayer || null; - this.#onAppend = options.onAppend || null; - this.#structTreeLayer = options.structTreeLayer || null; - } - async render(viewport, intent = "display") { - if (intent !== "display") { - return; - } - if (this._cancelled) { - return; - } - const clonedViewport = viewport.clone({ - dontFlip: true - }); - if (this.div) { - this.annotationEditorLayer.update({ - viewport: clonedViewport - }); - this.show(); - return; - } - const div = this.div = document.createElement("div"); - div.className = "annotationEditorLayer"; - div.hidden = true; - div.dir = this.#uiManager.direction; - this.#onAppend?.(div); - this.annotationEditorLayer = new AnnotationEditorLayer({ - uiManager: this.#uiManager, - div, - structTreeLayer: this.#structTreeLayer, - accessibilityManager: this.accessibilityManager, - pageIndex: this.pdfPage.pageNumber - 1, - l10n: this.l10n, - viewport: clonedViewport, - annotationLayer: this.#annotationLayer, - textLayer: this.#textLayer, - drawLayer: this.#drawLayer - }); - const parameters = { - viewport: clonedViewport, - div, - annotations: null, - intent - }; - this.annotationEditorLayer.render(parameters); - this.show(); - } - cancel() { - this._cancelled = true; - if (!this.div) { - return; - } - this.annotationEditorLayer.destroy(); - } - hide() { - if (!this.div) { - return; - } - this.annotationEditorLayer.pause(true); - this.div.hidden = true; - } - show() { - if (!this.div || this.annotationEditorLayer.isInvisible) { - return; - } - this.div.hidden = false; - this.annotationEditorLayer.pause(false); - } -} - -;// ./web/app_options.js -{ - var compatParams = new Map(); - const userAgent = navigator.userAgent || ""; - const platform = navigator.platform || ""; - const maxTouchPoints = navigator.maxTouchPoints || 1; - const isAndroid = /Android/.test(userAgent); - const isIOS = /\b(iPad|iPhone|iPod)(?=;)/.test(userAgent) || platform === "MacIntel" && maxTouchPoints > 1; - (function () { - if (isIOS || isAndroid) { - compatParams.set("maxCanvasPixels", 5242880); - } - })(); - (function () { - if (isAndroid) { - compatParams.set("useSystemFonts", false); - } - })(); -} -const OptionKind = { - BROWSER: 0x01, - VIEWER: 0x02, - API: 0x04, - WORKER: 0x08, - EVENT_DISPATCH: 0x10, - PREFERENCE: 0x80 -}; -const Type = { - BOOLEAN: 0x01, - NUMBER: 0x02, - OBJECT: 0x04, - STRING: 0x08, - UNDEFINED: 0x10 -}; -const defaultOptions = { - allowedGlobalEvents: { - value: null, - kind: OptionKind.BROWSER - }, - canvasMaxAreaInBytes: { - value: -1, - kind: OptionKind.BROWSER + OptionKind.API - }, - isInAutomation: { - value: false, - kind: OptionKind.BROWSER - }, - localeProperties: { - value: { - lang: navigator.language || "en-US" - }, - kind: OptionKind.BROWSER - }, - nimbusDataStr: { - value: "", - kind: OptionKind.BROWSER - }, - supportsCaretBrowsingMode: { - value: false, - kind: OptionKind.BROWSER - }, - supportsDocumentFonts: { - value: true, - kind: OptionKind.BROWSER - }, - supportsIntegratedFind: { - value: false, - kind: OptionKind.BROWSER - }, - supportsMouseWheelZoomCtrlKey: { - value: true, - kind: OptionKind.BROWSER - }, - supportsMouseWheelZoomMetaKey: { - value: true, - kind: OptionKind.BROWSER - }, - supportsPinchToZoom: { - value: true, - kind: OptionKind.BROWSER - }, - toolbarDensity: { - value: 0, - kind: OptionKind.BROWSER + OptionKind.EVENT_DISPATCH - }, - altTextLearnMoreUrl: { - value: "", - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - annotationEditorMode: { - value: 0, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - annotationMode: { - value: 2, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - cursorToolOnLoad: { - value: 0, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - debuggerSrc: { - value: "./debugger.mjs", - kind: OptionKind.VIEWER - }, - defaultZoomDelay: { - value: 400, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - defaultZoomValue: { - value: "", - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - disableHistory: { - value: false, - kind: OptionKind.VIEWER - }, - disablePageLabels: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enableAltText: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enableAltTextModelDownload: { - value: true, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE + OptionKind.EVENT_DISPATCH - }, - enableGuessAltText: { - value: true, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE + OptionKind.EVENT_DISPATCH - }, - enableHighlightFloatingButton: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enableNewAltTextWhenAddingImage: { - value: true, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enablePermissions: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enablePrintAutoRotate: { - value: true, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enableScripting: { - value: true, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enableUpdatedAddImage: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - externalLinkRel: { - value: "noopener noreferrer nofollow", - kind: OptionKind.VIEWER - }, - externalLinkTarget: { - value: 0, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - highlightEditorColors: { - value: "yellow=#FFFF98,green=#53FFBC,blue=#80EBFF,pink=#FFCBE6,red=#FF4F5F", - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - historyUpdateUrl: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - ignoreDestinationZoom: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - imageResourcesPath: { - value: "./images/", - kind: OptionKind.VIEWER - }, - maxCanvasPixels: { - value: 2 ** 25, - kind: OptionKind.VIEWER - }, - forcePageColors: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - pageColorsBackground: { - value: "Canvas", - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - pageColorsForeground: { - value: "CanvasText", - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - pdfBugEnabled: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - printResolution: { - value: 150, - kind: OptionKind.VIEWER - }, - sidebarViewOnLoad: { - value: -1, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - scrollModeOnLoad: { - value: -1, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - spreadModeOnLoad: { - value: -1, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - textLayerMode: { - value: 1, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - viewOnLoad: { - value: 0, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - cMapPacked: { - value: true, - kind: OptionKind.API - }, - cMapUrl: { - value: "../web/cmaps/", - kind: OptionKind.API - }, - disableAutoFetch: { - value: false, - kind: OptionKind.API + OptionKind.PREFERENCE - }, - disableFontFace: { - value: false, - kind: OptionKind.API + OptionKind.PREFERENCE - }, - disableRange: { - value: false, - kind: OptionKind.API + OptionKind.PREFERENCE - }, - disableStream: { - value: false, - kind: OptionKind.API + OptionKind.PREFERENCE - }, - docBaseUrl: { - value: "", - kind: OptionKind.API - }, - enableHWA: { - value: true, - kind: OptionKind.API + OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enableXfa: { - value: true, - kind: OptionKind.API + OptionKind.PREFERENCE - }, - fontExtraProperties: { - value: false, - kind: OptionKind.API - }, - isEvalSupported: { - value: true, - kind: OptionKind.API - }, - isOffscreenCanvasSupported: { - value: true, - kind: OptionKind.API - }, - maxImageSize: { - value: -1, - kind: OptionKind.API - }, - pdfBug: { - value: false, - kind: OptionKind.API - }, - standardFontDataUrl: { - value: "../web/standard_fonts/", - kind: OptionKind.API - }, - useSystemFonts: { - value: undefined, - kind: OptionKind.API, - type: Type.BOOLEAN + Type.UNDEFINED - }, - verbosity: { - value: 1, - kind: OptionKind.API - }, - workerPort: { - value: null, - kind: OptionKind.WORKER - }, - workerSrc: { - value: "../build/pdf.worker.mjs", - kind: OptionKind.WORKER - } -}; -{ - defaultOptions.defaultUrl = { - value: "compressed.tracemonkey-pldi-09.pdf", - kind: OptionKind.VIEWER - }; - defaultOptions.sandboxBundleSrc = { - value: "../build/pdf.sandbox.mjs", - kind: OptionKind.VIEWER - }; - defaultOptions.viewerCssTheme = { - value: 0, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }; - defaultOptions.enableFakeMLManager = { - value: true, - kind: OptionKind.VIEWER - }; -} -{ - defaultOptions.disablePreferences = { - value: false, - kind: OptionKind.VIEWER - }; -} -class AppOptions { - static eventBus; - static #opts = new Map(); - static { - for (const name in defaultOptions) { - this.#opts.set(name, defaultOptions[name].value); - } - for (const [name, value] of compatParams) { - this.#opts.set(name, value); - } - this._hasInvokedSet = false; - this._checkDisablePreferences = () => { - if (this.get("disablePreferences")) { - return true; - } - if (this._hasInvokedSet) { - console.warn("The Preferences may override manually set AppOptions; " + 'please use the "disablePreferences"-option to prevent that.'); - } - return false; - }; - } - static get(name) { - return this.#opts.get(name); - } - static getAll(kind = null, defaultOnly = false) { - const options = Object.create(null); - for (const name in defaultOptions) { - const defaultOpt = defaultOptions[name]; - if (kind && !(kind & defaultOpt.kind)) { - continue; - } - options[name] = !defaultOnly ? this.#opts.get(name) : defaultOpt.value; - } - return options; - } - static set(name, value) { - this.setAll({ - [name]: value - }); - } - static setAll(options, prefs = false) { - this._hasInvokedSet ||= true; - let events; - for (const name in options) { - const defaultOpt = defaultOptions[name], - userOpt = options[name]; - if (!defaultOpt || !(typeof userOpt === typeof defaultOpt.value || Type[(typeof userOpt).toUpperCase()] & defaultOpt.type)) { - continue; - } - const { - kind - } = defaultOpt; - if (prefs && !(kind & OptionKind.BROWSER || kind & OptionKind.PREFERENCE)) { - continue; - } - if (this.eventBus && kind & OptionKind.EVENT_DISPATCH) { - (events ||= new Map()).set(name, userOpt); - } - this.#opts.set(name, userOpt); - } - if (events) { - for (const [name, value] of events) { - this.eventBus.dispatch(name.toLowerCase(), { - source: this, - value - }); - } - } - } -} - -;// ./web/draw_layer_builder.js - -class DrawLayerBuilder { - #drawLayer = null; - constructor(options) { - this.pageIndex = options.pageIndex; - } - async render(intent = "display") { - if (intent !== "display" || this.#drawLayer || this._cancelled) { - return; - } - this.#drawLayer = new DrawLayer({ - pageIndex: this.pageIndex - }); - } - cancel() { - this._cancelled = true; - if (!this.#drawLayer) { - return; - } - this.#drawLayer.destroy(); - this.#drawLayer = null; - } - setParent(parent) { - this.#drawLayer?.setParent(parent); - } - getDrawLayer() { - return this.#drawLayer; - } -} - -;// ./web/struct_tree_layer_builder.js - -const PDF_ROLE_TO_HTML_ROLE = { - Document: null, - DocumentFragment: null, - Part: "group", - Sect: "group", - Div: "group", - Aside: "note", - NonStruct: "none", - P: null, - H: "heading", - Title: null, - FENote: "note", - Sub: "group", - Lbl: null, - Span: null, - Em: null, - Strong: null, - Link: "link", - Annot: "note", - Form: "form", - Ruby: null, - RB: null, - RT: null, - RP: null, - Warichu: null, - WT: null, - WP: null, - L: "list", - LI: "listitem", - LBody: null, - Table: "table", - TR: "row", - TH: "columnheader", - TD: "cell", - THead: "columnheader", - TBody: null, - TFoot: null, - Caption: null, - Figure: "figure", - Formula: null, - Artifact: null -}; -const HEADING_PATTERN = /^H(\d+)$/; -class StructTreeLayerBuilder { - #promise; - #treeDom = null; - #treePromise; - #elementAttributes = new Map(); - #rawDims; - #elementsToAddToTextLayer = null; - constructor(pdfPage, rawDims) { - this.#promise = pdfPage.getStructTree(); - this.#rawDims = rawDims; - } - async render() { - if (this.#treePromise) { - return this.#treePromise; - } - const { - promise, - resolve, - reject - } = Promise.withResolvers(); - this.#treePromise = promise; - try { - this.#treeDom = this.#walk(await this.#promise); - } catch (ex) { - reject(ex); - } - this.#promise = null; - this.#treeDom?.classList.add("structTree"); - resolve(this.#treeDom); - return promise; - } - async getAriaAttributes(annotationId) { - try { - await this.render(); - return this.#elementAttributes.get(annotationId); - } catch {} - return null; - } - hide() { - if (this.#treeDom && !this.#treeDom.hidden) { - this.#treeDom.hidden = true; - } - } - show() { - if (this.#treeDom?.hidden) { - this.#treeDom.hidden = false; - } - } - #setAttributes(structElement, htmlElement) { - const { - alt, - id, - lang - } = structElement; - if (alt !== undefined) { - let added = false; - const label = removeNullCharacters(alt); - for (const child of structElement.children) { - if (child.type === "annotation") { - let attrs = this.#elementAttributes.get(child.id); - if (!attrs) { - attrs = new Map(); - this.#elementAttributes.set(child.id, attrs); - } - attrs.set("aria-label", label); - added = true; - } - } - if (!added) { - htmlElement.setAttribute("aria-label", label); - } - } - if (id !== undefined) { - htmlElement.setAttribute("aria-owns", id); - } - if (lang !== undefined) { - htmlElement.setAttribute("lang", removeNullCharacters(lang, true)); - } - } - #addImageInTextLayer(node, element) { - const { - alt, - bbox, - children - } = node; - const child = children?.[0]; - if (!this.#rawDims || !alt || !bbox || child?.type !== "content") { - return false; - } - const { - id - } = child; - if (!id) { - return false; - } - element.setAttribute("aria-owns", id); - const img = document.createElement("span"); - (this.#elementsToAddToTextLayer ||= new Map()).set(id, img); - img.setAttribute("role", "img"); - img.setAttribute("aria-label", removeNullCharacters(alt)); - const { - pageHeight, - pageX, - pageY - } = this.#rawDims; - const calc = "calc(var(--scale-factor)*"; - const { - style - } = img; - style.width = `${calc}${bbox[2] - bbox[0]}px)`; - style.height = `${calc}${bbox[3] - bbox[1]}px)`; - style.left = `${calc}${bbox[0] - pageX}px)`; - style.top = `${calc}${pageHeight - bbox[3] + pageY}px)`; - return true; - } - addElementsToTextLayer() { - if (!this.#elementsToAddToTextLayer) { - return; - } - for (const [id, img] of this.#elementsToAddToTextLayer) { - document.getElementById(id)?.append(img); - } - this.#elementsToAddToTextLayer.clear(); - this.#elementsToAddToTextLayer = null; - } - #walk(node) { - if (!node) { - return null; - } - const element = document.createElement("span"); - if ("role" in node) { - const { - role - } = node; - const match = role.match(HEADING_PATTERN); - if (match) { - element.setAttribute("role", "heading"); - element.setAttribute("aria-level", match[1]); - } else if (PDF_ROLE_TO_HTML_ROLE[role]) { - element.setAttribute("role", PDF_ROLE_TO_HTML_ROLE[role]); - } - if (role === "Figure" && this.#addImageInTextLayer(node, element)) { - return element; - } - } - this.#setAttributes(node, element); - if (node.children) { - if (node.children.length === 1 && "id" in node.children[0]) { - this.#setAttributes(node.children[0], element); - } else { - for (const kid of node.children) { - element.append(this.#walk(kid)); - } - } - } - return element; - } -} - -;// ./web/text_accessibility.js - -class TextAccessibilityManager { - #enabled = false; - #textChildren = null; - #textNodes = new Map(); - #waitingElements = new Map(); - setTextMapping(textDivs) { - this.#textChildren = textDivs; - } - static #compareElementPositions(e1, e2) { - const rect1 = e1.getBoundingClientRect(); - const rect2 = e2.getBoundingClientRect(); - if (rect1.width === 0 && rect1.height === 0) { - return +1; - } - if (rect2.width === 0 && rect2.height === 0) { - return -1; - } - const top1 = rect1.y; - const bot1 = rect1.y + rect1.height; - const mid1 = rect1.y + rect1.height / 2; - const top2 = rect2.y; - const bot2 = rect2.y + rect2.height; - const mid2 = rect2.y + rect2.height / 2; - if (mid1 <= top2 && mid2 >= bot1) { - return -1; - } - if (mid2 <= top1 && mid1 >= bot2) { - return +1; - } - const centerX1 = rect1.x + rect1.width / 2; - const centerX2 = rect2.x + rect2.width / 2; - return centerX1 - centerX2; - } - enable() { - if (this.#enabled) { - throw new Error("TextAccessibilityManager is already enabled."); - } - if (!this.#textChildren) { - throw new Error("Text divs and strings have not been set."); - } - this.#enabled = true; - this.#textChildren = this.#textChildren.slice(); - this.#textChildren.sort(TextAccessibilityManager.#compareElementPositions); - if (this.#textNodes.size > 0) { - const textChildren = this.#textChildren; - for (const [id, nodeIndex] of this.#textNodes) { - const element = document.getElementById(id); - if (!element) { - this.#textNodes.delete(id); - continue; - } - this.#addIdToAriaOwns(id, textChildren[nodeIndex]); - } - } - for (const [element, isRemovable] of this.#waitingElements) { - this.addPointerInTextLayer(element, isRemovable); - } - this.#waitingElements.clear(); - } - disable() { - if (!this.#enabled) { - return; - } - this.#waitingElements.clear(); - this.#textChildren = null; - this.#enabled = false; - } - removePointerInTextLayer(element) { - if (!this.#enabled) { - this.#waitingElements.delete(element); - return; - } - const children = this.#textChildren; - if (!children || children.length === 0) { - return; - } - const { - id - } = element; - const nodeIndex = this.#textNodes.get(id); - if (nodeIndex === undefined) { - return; - } - const node = children[nodeIndex]; - this.#textNodes.delete(id); - let owns = node.getAttribute("aria-owns"); - if (owns?.includes(id)) { - owns = owns.split(" ").filter(x => x !== id).join(" "); - if (owns) { - node.setAttribute("aria-owns", owns); - } else { - node.removeAttribute("aria-owns"); - node.setAttribute("role", "presentation"); - } - } - } - #addIdToAriaOwns(id, node) { - const owns = node.getAttribute("aria-owns"); - if (!owns?.includes(id)) { - node.setAttribute("aria-owns", owns ? `${owns} ${id}` : id); - } - node.removeAttribute("role"); - } - addPointerInTextLayer(element, isRemovable) { - const { - id - } = element; - if (!id) { - return null; - } - if (!this.#enabled) { - this.#waitingElements.set(element, isRemovable); - return null; - } - if (isRemovable) { - this.removePointerInTextLayer(element); - } - const children = this.#textChildren; - if (!children || children.length === 0) { - return null; - } - const index = binarySearchFirstItem(children, node => TextAccessibilityManager.#compareElementPositions(element, node) < 0); - const nodeIndex = Math.max(0, index - 1); - const child = children[nodeIndex]; - this.#addIdToAriaOwns(id, child); - this.#textNodes.set(id, nodeIndex); - const parent = child.parentNode; - return parent?.classList.contains("markedContent") ? parent.id : null; - } - moveElementInDOM(container, element, contentElement, isRemovable) { - const id = this.addPointerInTextLayer(contentElement, isRemovable); - if (!container.hasChildNodes()) { - container.append(element); - return id; - } - const children = Array.from(container.childNodes).filter(node => node !== element); - if (children.length === 0) { - return id; - } - const elementToCompare = contentElement || element; - const index = binarySearchFirstItem(children, node => TextAccessibilityManager.#compareElementPositions(elementToCompare, node) < 0); - if (index === 0) { - children[0].before(element); - } else { - children[index - 1].after(element); - } - return id; - } -} - -;// ./web/text_highlighter.js -class TextHighlighter { - #eventAbortController = null; - constructor({ - findController, - eventBus, - pageIndex - }) { - this.findController = findController; - this.matches = []; - this.eventBus = eventBus; - this.pageIdx = pageIndex; - this.textDivs = null; - this.textContentItemsStr = null; - this.enabled = false; - } - setTextMapping(divs, texts) { - this.textDivs = divs; - this.textContentItemsStr = texts; - } - enable() { - if (!this.textDivs || !this.textContentItemsStr) { - throw new Error("Text divs and strings have not been set."); - } - if (this.enabled) { - throw new Error("TextHighlighter is already enabled."); - } - this.enabled = true; - if (!this.#eventAbortController) { - this.#eventAbortController = new AbortController(); - this.eventBus._on("updatetextlayermatches", evt => { - if (evt.pageIndex === this.pageIdx || evt.pageIndex === -1) { - this._updateMatches(); - } - }, { - signal: this.#eventAbortController.signal - }); - } - this._updateMatches(); - } - disable() { - if (!this.enabled) { - return; - } - this.enabled = false; - this.#eventAbortController?.abort(); - this.#eventAbortController = null; - this._updateMatches(true); - } - _convertMatches(matches, matchesLength) { - if (!matches) { - return []; - } - const { - textContentItemsStr - } = this; - let i = 0, - iIndex = 0; - const end = textContentItemsStr.length - 1; - const result = []; - for (let m = 0, mm = matches.length; m < mm; m++) { - let matchIdx = matches[m]; - while (i !== end && matchIdx >= iIndex + textContentItemsStr[i].length) { - iIndex += textContentItemsStr[i].length; - i++; - } - if (i === textContentItemsStr.length) { - console.error("Could not find a matching mapping"); - } - const match = { - begin: { - divIdx: i, - offset: matchIdx - iIndex - } - }; - matchIdx += matchesLength[m]; - while (i !== end && matchIdx > iIndex + textContentItemsStr[i].length) { - iIndex += textContentItemsStr[i].length; - i++; - } - match.end = { - divIdx: i, - offset: matchIdx - iIndex - }; - result.push(match); - } - return result; - } - _renderMatches(matches) { - if (matches.length === 0) { - return; - } - const { - findController, - pageIdx - } = this; - const { - textContentItemsStr, - textDivs - } = this; - const isSelectedPage = pageIdx === findController.selected.pageIdx; - const selectedMatchIdx = findController.selected.matchIdx; - const highlightAll = findController.state.highlightAll; - let prevEnd = null; - const infinity = { - divIdx: -1, - offset: undefined - }; - function beginText(begin, className) { - const divIdx = begin.divIdx; - textDivs[divIdx].textContent = ""; - return appendTextToDiv(divIdx, 0, begin.offset, className); - } - function appendTextToDiv(divIdx, fromOffset, toOffset, className) { - let div = textDivs[divIdx]; - if (div.nodeType === Node.TEXT_NODE) { - const span = document.createElement("span"); - div.before(span); - span.append(div); - textDivs[divIdx] = span; - div = span; - } - const content = textContentItemsStr[divIdx].substring(fromOffset, toOffset); - const node = document.createTextNode(content); - if (className) { - const span = document.createElement("span"); - span.className = `${className} appended`; - span.append(node); - div.append(span); - if (className.includes("selected")) { - const { - left - } = span.getClientRects()[0]; - const parentLeft = div.getBoundingClientRect().left; - return left - parentLeft; - } - return 0; - } - div.append(node); - return 0; - } - let i0 = selectedMatchIdx, - i1 = i0 + 1; - if (highlightAll) { - i0 = 0; - i1 = matches.length; - } else if (!isSelectedPage) { - return; - } - let lastDivIdx = -1; - let lastOffset = -1; - for (let i = i0; i < i1; i++) { - const match = matches[i]; - const begin = match.begin; - if (begin.divIdx === lastDivIdx && begin.offset === lastOffset) { - continue; - } - lastDivIdx = begin.divIdx; - lastOffset = begin.offset; - const end = match.end; - const isSelected = isSelectedPage && i === selectedMatchIdx; - const highlightSuffix = isSelected ? " selected" : ""; - let selectedLeft = 0; - if (!prevEnd || begin.divIdx !== prevEnd.divIdx) { - if (prevEnd !== null) { - appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset); - } - beginText(begin); - } else { - appendTextToDiv(prevEnd.divIdx, prevEnd.offset, begin.offset); - } - if (begin.divIdx === end.divIdx) { - selectedLeft = appendTextToDiv(begin.divIdx, begin.offset, end.offset, "highlight" + highlightSuffix); - } else { - selectedLeft = appendTextToDiv(begin.divIdx, begin.offset, infinity.offset, "highlight begin" + highlightSuffix); - for (let n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) { - textDivs[n0].className = "highlight middle" + highlightSuffix; - } - beginText(end, "highlight end" + highlightSuffix); - } - prevEnd = end; - if (isSelected) { - findController.scrollMatchIntoView({ - element: textDivs[begin.divIdx], - selectedLeft, - pageIndex: pageIdx, - matchIndex: selectedMatchIdx - }); - } - } - if (prevEnd) { - appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset); - } - } - _updateMatches(reset = false) { - if (!this.enabled && !reset) { - return; - } - const { - findController, - matches, - pageIdx - } = this; - const { - textContentItemsStr, - textDivs - } = this; - let clearedUntilDivIdx = -1; - for (const match of matches) { - const begin = Math.max(clearedUntilDivIdx, match.begin.divIdx); - for (let n = begin, end = match.end.divIdx; n <= end; n++) { - const div = textDivs[n]; - div.textContent = textContentItemsStr[n]; - div.className = ""; - } - clearedUntilDivIdx = match.end.divIdx + 1; - } - if (!findController?.highlightMatches || reset) { - return; - } - const pageMatches = findController.pageMatches[pageIdx] || null; - const pageMatchesLength = findController.pageMatchesLength[pageIdx] || null; - this.matches = this._convertMatches(pageMatches, pageMatchesLength); - this._renderMatches(this.matches); - } -} - -;// ./web/text_layer_builder.js - - -class TextLayerBuilder { - #enablePermissions = false; - #onAppend = null; - #renderingDone = false; - #textLayer = null; - static #textLayers = new Map(); - static #selectionChangeAbortController = null; - constructor({ - pdfPage, - highlighter = null, - accessibilityManager = null, - enablePermissions = false, - onAppend = null - }) { - this.pdfPage = pdfPage; - this.highlighter = highlighter; - this.accessibilityManager = accessibilityManager; - this.#enablePermissions = enablePermissions === true; - this.#onAppend = onAppend; - this.div = document.createElement("div"); - this.div.tabIndex = 0; - this.div.className = "textLayer"; - } - async render(viewport, textContentParams = null) { - if (this.#renderingDone && this.#textLayer) { - this.#textLayer.update({ - viewport, - onBefore: this.hide.bind(this) - }); - this.show(); - return; - } - this.cancel(); - this.#textLayer = new TextLayer({ - textContentSource: this.pdfPage.streamTextContent(textContentParams || { - includeMarkedContent: true, - disableNormalization: true - }), - container: this.div, - viewport - }); - const { - textDivs, - textContentItemsStr - } = this.#textLayer; - this.highlighter?.setTextMapping(textDivs, textContentItemsStr); - this.accessibilityManager?.setTextMapping(textDivs); - await this.#textLayer.render(); - this.#renderingDone = true; - const endOfContent = document.createElement("div"); - endOfContent.className = "endOfContent"; - this.div.append(endOfContent); - this.#bindMouse(endOfContent); - this.#onAppend?.(this.div); - this.highlighter?.enable(); - this.accessibilityManager?.enable(); - } - hide() { - if (!this.div.hidden && this.#renderingDone) { - this.highlighter?.disable(); - this.div.hidden = true; - } - } - show() { - if (this.div.hidden && this.#renderingDone) { - this.div.hidden = false; - this.highlighter?.enable(); - } - } - cancel() { - this.#textLayer?.cancel(); - this.#textLayer = null; - this.highlighter?.disable(); - this.accessibilityManager?.disable(); - TextLayerBuilder.#removeGlobalSelectionListener(this.div); - } - #bindMouse(end) { - const { - div - } = this; - div.addEventListener("mousedown", () => { - div.classList.add("selecting"); - }); - div.addEventListener("copy", event => { - if (!this.#enablePermissions) { - const selection = document.getSelection(); - event.clipboardData.setData("text/plain", removeNullCharacters(normalizeUnicode(selection.toString()))); - } - stopEvent(event); - }); - TextLayerBuilder.#textLayers.set(div, end); - TextLayerBuilder.#enableGlobalSelectionListener(); - } - static #removeGlobalSelectionListener(textLayerDiv) { - this.#textLayers.delete(textLayerDiv); - if (this.#textLayers.size === 0) { - this.#selectionChangeAbortController?.abort(); - this.#selectionChangeAbortController = null; - } - } - static #enableGlobalSelectionListener() { - if (this.#selectionChangeAbortController) { - return; - } - this.#selectionChangeAbortController = new AbortController(); - const { - signal - } = this.#selectionChangeAbortController; - const reset = (end, textLayer) => { - textLayer.append(end); - end.style.width = ""; - end.style.height = ""; - textLayer.classList.remove("selecting"); - }; - let isPointerDown = false; - document.addEventListener("pointerdown", () => { - isPointerDown = true; - }, { - signal - }); - document.addEventListener("pointerup", () => { - isPointerDown = false; - this.#textLayers.forEach(reset); - }, { - signal - }); - window.addEventListener("blur", () => { - isPointerDown = false; - this.#textLayers.forEach(reset); - }, { - signal - }); - document.addEventListener("keyup", () => { - if (!isPointerDown) { - this.#textLayers.forEach(reset); - } - }, { - signal - }); - var isFirefox, prevRange; - document.addEventListener("selectionchange", () => { - const selection = document.getSelection(); - if (selection.rangeCount === 0) { - this.#textLayers.forEach(reset); - return; - } - const activeTextLayers = new Set(); - for (let i = 0; i < selection.rangeCount; i++) { - const range = selection.getRangeAt(i); - for (const textLayerDiv of this.#textLayers.keys()) { - if (!activeTextLayers.has(textLayerDiv) && range.intersectsNode(textLayerDiv)) { - activeTextLayers.add(textLayerDiv); - } - } - } - for (const [textLayerDiv, endDiv] of this.#textLayers) { - if (activeTextLayers.has(textLayerDiv)) { - textLayerDiv.classList.add("selecting"); - } else { - reset(endDiv, textLayerDiv); - } - } - isFirefox ??= getComputedStyle(this.#textLayers.values().next().value).getPropertyValue("-moz-user-select") === "none"; - if (isFirefox) { - return; - } - const range = selection.getRangeAt(0); - const modifyStart = prevRange && (range.compareBoundaryPoints(Range.END_TO_END, prevRange) === 0 || range.compareBoundaryPoints(Range.START_TO_END, prevRange) === 0); - let anchor = modifyStart ? range.startContainer : range.endContainer; - if (anchor.nodeType === Node.TEXT_NODE) { - anchor = anchor.parentNode; - } - const parentTextLayer = anchor.parentElement?.closest(".textLayer"); - const endDiv = this.#textLayers.get(parentTextLayer); - if (endDiv) { - endDiv.style.width = parentTextLayer.style.width; - endDiv.style.height = parentTextLayer.style.height; - anchor.parentElement.insertBefore(endDiv, modifyStart ? anchor : anchor.nextSibling); - } - prevRange = range.cloneRange(); - }, { - signal - }); - } -} - -;// ./web/xfa_layer_builder.js - -class XfaLayerBuilder { - constructor({ - pdfPage, - annotationStorage = null, - linkService, - xfaHtml = null - }) { - this.pdfPage = pdfPage; - this.annotationStorage = annotationStorage; - this.linkService = linkService; - this.xfaHtml = xfaHtml; - this.div = null; - this._cancelled = false; - } - async render(viewport, intent = "display") { - if (intent === "print") { - const parameters = { - viewport: viewport.clone({ - dontFlip: true - }), - div: this.div, - xfaHtml: this.xfaHtml, - annotationStorage: this.annotationStorage, - linkService: this.linkService, - intent - }; - this.div = document.createElement("div"); - parameters.div = this.div; - return XfaLayer.render(parameters); - } - const xfaHtml = await this.pdfPage.getXfa(); - if (this._cancelled || !xfaHtml) { - return { - textDivs: [] - }; - } - const parameters = { - viewport: viewport.clone({ - dontFlip: true - }), - div: this.div, - xfaHtml, - annotationStorage: this.annotationStorage, - linkService: this.linkService, - intent - }; - if (this.div) { - return XfaLayer.update(parameters); - } - this.div = document.createElement("div"); - parameters.div = this.div; - return XfaLayer.render(parameters); - } - cancel() { - this._cancelled = true; - } - hide() { - if (!this.div) { - return; - } - this.div.hidden = true; - } -} - -;// ./web/pdf_page_view.js - - - - - - - - - - - - - -const DEFAULT_LAYER_PROPERTIES = { - annotationEditorUIManager: null, - annotationStorage: null, - downloadManager: null, - enableScripting: false, - fieldObjectsPromise: null, - findController: null, - hasJSActionsPromise: null, - get linkService() { - return new SimpleLinkService(); - } -}; -const LAYERS_ORDER = new Map([["canvasWrapper", 0], ["textLayer", 1], ["annotationLayer", 2], ["annotationEditorLayer", 3], ["xfaLayer", 3]]); -class PDFPageView { - #annotationMode = AnnotationMode.ENABLE_FORMS; - #canvasWrapper = null; - #enableHWA = false; - #hasRestrictedScaling = false; - #isEditing = false; - #layerProperties = null; - #loadingId = null; - #originalViewport = null; - #previousRotation = null; - #scaleRoundX = 1; - #scaleRoundY = 1; - #renderError = null; - #renderingState = RenderingStates.INITIAL; - #textLayerMode = TextLayerMode.ENABLE; - #useThumbnailCanvas = { - directDrawing: true, - initialOptionalContent: true, - regularAnnotations: true - }; - #layers = [null, null, null, null]; - constructor(options) { - const container = options.container; - const defaultViewport = options.defaultViewport; - this.id = options.id; - this.renderingId = "page" + this.id; - this.#layerProperties = options.layerProperties || DEFAULT_LAYER_PROPERTIES; - this.pdfPage = null; - this.pageLabel = null; - this.rotation = 0; - this.scale = options.scale || DEFAULT_SCALE; - this.viewport = defaultViewport; - this.pdfPageRotate = defaultViewport.rotation; - this._optionalContentConfigPromise = options.optionalContentConfigPromise || null; - this.#textLayerMode = options.textLayerMode ?? TextLayerMode.ENABLE; - this.#annotationMode = options.annotationMode ?? AnnotationMode.ENABLE_FORMS; - this.imageResourcesPath = options.imageResourcesPath || ""; - this.maxCanvasPixels = options.maxCanvasPixels ?? AppOptions.get("maxCanvasPixels"); - this.pageColors = options.pageColors || null; - this.#enableHWA = options.enableHWA || false; - this.eventBus = options.eventBus; - this.renderingQueue = options.renderingQueue; - this.l10n = options.l10n; - this.l10n ||= new genericl10n_GenericL10n(); - this.renderTask = null; - this.resume = null; - this._isStandalone = !this.renderingQueue?.hasViewer(); - this._container = container; - this._annotationCanvasMap = null; - this.annotationLayer = null; - this.annotationEditorLayer = null; - this.textLayer = null; - this.xfaLayer = null; - this.structTreeLayer = null; - this.drawLayer = null; - const div = document.createElement("div"); - div.className = "page"; - div.setAttribute("data-page-number", this.id); - div.setAttribute("role", "region"); - div.setAttribute("data-l10n-id", "pdfjs-page-landmark"); - div.setAttribute("data-l10n-args", JSON.stringify({ - page: this.id - })); - this.div = div; - this.#setDimensions(); - container?.append(div); - if (this._isStandalone) { - container?.style.setProperty("--scale-factor", this.scale * PixelsPerInch.PDF_TO_CSS_UNITS); - if (this.pageColors?.background) { - container?.style.setProperty("--page-bg-color", this.pageColors.background); - } - const { - optionalContentConfigPromise - } = options; - if (optionalContentConfigPromise) { - optionalContentConfigPromise.then(optionalContentConfig => { - if (optionalContentConfigPromise !== this._optionalContentConfigPromise) { - return; - } - this.#useThumbnailCanvas.initialOptionalContent = optionalContentConfig.hasInitialVisibility; - }); - } - if (!options.l10n) { - this.l10n.translate(this.div); - } - } - } - #addLayer(div, name) { - const pos = LAYERS_ORDER.get(name); - const oldDiv = this.#layers[pos]; - this.#layers[pos] = div; - if (oldDiv) { - oldDiv.replaceWith(div); - return; - } - for (let i = pos - 1; i >= 0; i--) { - const layer = this.#layers[i]; - if (layer) { - layer.after(div); - return; - } - } - this.div.prepend(div); - } - get renderingState() { - return this.#renderingState; - } - set renderingState(state) { - if (state === this.#renderingState) { - return; - } - this.#renderingState = state; - if (this.#loadingId) { - clearTimeout(this.#loadingId); - this.#loadingId = null; - } - switch (state) { - case RenderingStates.PAUSED: - this.div.classList.remove("loading"); - break; - case RenderingStates.RUNNING: - this.div.classList.add("loadingIcon"); - this.#loadingId = setTimeout(() => { - this.div.classList.add("loading"); - this.#loadingId = null; - }, 0); - break; - case RenderingStates.INITIAL: - case RenderingStates.FINISHED: - this.div.classList.remove("loadingIcon", "loading"); - break; - } - } - #setDimensions() { - const { - viewport - } = this; - if (this.pdfPage) { - if (this.#previousRotation === viewport.rotation) { - return; - } - this.#previousRotation = viewport.rotation; - } - setLayerDimensions(this.div, viewport, true, false); - } - setPdfPage(pdfPage) { - if (this._isStandalone && (this.pageColors?.foreground === "CanvasText" || this.pageColors?.background === "Canvas")) { - this._container?.style.setProperty("--hcm-highlight-filter", pdfPage.filterFactory.addHighlightHCMFilter("highlight", "CanvasText", "Canvas", "HighlightText", "Highlight")); - this._container?.style.setProperty("--hcm-highlight-selected-filter", pdfPage.filterFactory.addHighlightHCMFilter("highlight_selected", "CanvasText", "Canvas", "HighlightText", "Highlight")); - } - this.pdfPage = pdfPage; - this.pdfPageRotate = pdfPage.rotate; - const totalRotation = (this.rotation + this.pdfPageRotate) % 360; - this.viewport = pdfPage.getViewport({ - scale: this.scale * PixelsPerInch.PDF_TO_CSS_UNITS, - rotation: totalRotation - }); - this.#setDimensions(); - this.reset(); - } - destroy() { - this.reset(); - this.pdfPage?.cleanup(); - } - hasEditableAnnotations() { - return !!this.annotationLayer?.hasEditableAnnotations(); - } - get _textHighlighter() { - return shadow(this, "_textHighlighter", new TextHighlighter({ - pageIndex: this.id - 1, - eventBus: this.eventBus, - findController: this.#layerProperties.findController - })); - } - #dispatchLayerRendered(name, error) { - this.eventBus.dispatch(name, { - source: this, - pageNumber: this.id, - error - }); - } - async #renderAnnotationLayer() { - let error = null; - try { - await this.annotationLayer.render(this.viewport, { - structTreeLayer: this.structTreeLayer - }, "display"); - } catch (ex) { - console.error("#renderAnnotationLayer:", ex); - error = ex; - } finally { - this.#dispatchLayerRendered("annotationlayerrendered", error); - } - } - async #renderAnnotationEditorLayer() { - let error = null; - try { - await this.annotationEditorLayer.render(this.viewport, "display"); - } catch (ex) { - console.error("#renderAnnotationEditorLayer:", ex); - error = ex; - } finally { - this.#dispatchLayerRendered("annotationeditorlayerrendered", error); - } - } - async #renderDrawLayer() { - try { - await this.drawLayer.render("display"); - } catch (ex) { - console.error("#renderDrawLayer:", ex); - } - } - async #renderXfaLayer() { - let error = null; - try { - const result = await this.xfaLayer.render(this.viewport, "display"); - if (result?.textDivs && this._textHighlighter) { - this.#buildXfaTextContentItems(result.textDivs); - } - } catch (ex) { - console.error("#renderXfaLayer:", ex); - error = ex; - } finally { - if (this.xfaLayer?.div) { - this.l10n.pause(); - this.#addLayer(this.xfaLayer.div, "xfaLayer"); - this.l10n.resume(); - } - this.#dispatchLayerRendered("xfalayerrendered", error); - } - } - async #renderTextLayer() { - if (!this.textLayer) { - return; - } - let error = null; - try { - await this.textLayer.render(this.viewport); - } catch (ex) { - if (ex instanceof AbortException) { - return; - } - console.error("#renderTextLayer:", ex); - error = ex; - } - this.#dispatchLayerRendered("textlayerrendered", error); - this.#renderStructTreeLayer(); - } - async #renderStructTreeLayer() { - if (!this.textLayer) { - return; - } - const treeDom = await this.structTreeLayer?.render(); - if (treeDom) { - this.l10n.pause(); - this.structTreeLayer?.addElementsToTextLayer(); - if (this.canvas && treeDom.parentNode !== this.canvas) { - this.canvas.append(treeDom); - } - this.l10n.resume(); - } - this.structTreeLayer?.show(); - } - async #buildXfaTextContentItems(textDivs) { - const text = await this.pdfPage.getTextContent(); - const items = []; - for (const item of text.items) { - items.push(item.str); - } - this._textHighlighter.setTextMapping(textDivs, items); - this._textHighlighter.enable(); - } - #resetCanvas() { - const { - canvas - } = this; - if (!canvas) { - return; - } - canvas.remove(); - canvas.width = canvas.height = 0; - this.canvas = null; - this.#originalViewport = null; - } - reset({ - keepAnnotationLayer = false, - keepAnnotationEditorLayer = false, - keepXfaLayer = false, - keepTextLayer = false, - keepCanvasWrapper = false - } = {}) { - this.cancelRendering({ - keepAnnotationLayer, - keepAnnotationEditorLayer, - keepXfaLayer, - keepTextLayer - }); - this.renderingState = RenderingStates.INITIAL; - const div = this.div; - const childNodes = div.childNodes, - annotationLayerNode = keepAnnotationLayer && this.annotationLayer?.div || null, - annotationEditorLayerNode = keepAnnotationEditorLayer && this.annotationEditorLayer?.div || null, - xfaLayerNode = keepXfaLayer && this.xfaLayer?.div || null, - textLayerNode = keepTextLayer && this.textLayer?.div || null, - canvasWrapperNode = keepCanvasWrapper && this.#canvasWrapper || null; - for (let i = childNodes.length - 1; i >= 0; i--) { - const node = childNodes[i]; - switch (node) { - case annotationLayerNode: - case annotationEditorLayerNode: - case xfaLayerNode: - case textLayerNode: - case canvasWrapperNode: - continue; - } - node.remove(); - const layerIndex = this.#layers.indexOf(node); - if (layerIndex >= 0) { - this.#layers[layerIndex] = null; - } - } - div.removeAttribute("data-loaded"); - if (annotationLayerNode) { - this.annotationLayer.hide(); - } - if (annotationEditorLayerNode) { - this.annotationEditorLayer.hide(); - } - if (xfaLayerNode) { - this.xfaLayer.hide(); - } - if (textLayerNode) { - this.textLayer.hide(); - } - this.structTreeLayer?.hide(); - if (!keepCanvasWrapper && this.#canvasWrapper) { - this.#canvasWrapper = null; - this.#resetCanvas(); - } - } - toggleEditingMode(isEditing) { - if (!this.hasEditableAnnotations()) { - return; - } - this.#isEditing = isEditing; - this.reset({ - keepAnnotationLayer: true, - keepAnnotationEditorLayer: true, - keepXfaLayer: true, - keepTextLayer: true, - keepCanvasWrapper: true - }); - } - update({ - scale = 0, - rotation = null, - optionalContentConfigPromise = null, - drawingDelay = -1 - }) { - this.scale = scale || this.scale; - if (typeof rotation === "number") { - this.rotation = rotation; - } - if (optionalContentConfigPromise instanceof Promise) { - this._optionalContentConfigPromise = optionalContentConfigPromise; - optionalContentConfigPromise.then(optionalContentConfig => { - if (optionalContentConfigPromise !== this._optionalContentConfigPromise) { - return; - } - this.#useThumbnailCanvas.initialOptionalContent = optionalContentConfig.hasInitialVisibility; - }); - } - this.#useThumbnailCanvas.directDrawing = true; - const totalRotation = (this.rotation + this.pdfPageRotate) % 360; - this.viewport = this.viewport.clone({ - scale: this.scale * PixelsPerInch.PDF_TO_CSS_UNITS, - rotation: totalRotation - }); - this.#setDimensions(); - if (this._isStandalone) { - this._container?.style.setProperty("--scale-factor", this.viewport.scale); - } - if (this.canvas) { - let onlyCssZoom = false; - if (this.#hasRestrictedScaling) { - if (this.maxCanvasPixels === 0) { - onlyCssZoom = true; - } else if (this.maxCanvasPixels > 0) { - const { - width, - height - } = this.viewport; - const { - sx, - sy - } = this.outputScale; - onlyCssZoom = (Math.floor(width) * sx | 0) * (Math.floor(height) * sy | 0) > this.maxCanvasPixels; - } - } - const postponeDrawing = drawingDelay >= 0 && drawingDelay < 1000; - if (postponeDrawing || onlyCssZoom) { - if (postponeDrawing && !onlyCssZoom && this.renderingState !== RenderingStates.FINISHED) { - this.cancelRendering({ - keepAnnotationLayer: true, - keepAnnotationEditorLayer: true, - keepXfaLayer: true, - keepTextLayer: true, - cancelExtraDelay: drawingDelay - }); - this.renderingState = RenderingStates.FINISHED; - this.#useThumbnailCanvas.directDrawing = false; - } - this.cssTransform({ - redrawAnnotationLayer: true, - redrawAnnotationEditorLayer: true, - redrawXfaLayer: true, - redrawTextLayer: !postponeDrawing, - hideTextLayer: postponeDrawing - }); - if (postponeDrawing) { - return; - } - this.eventBus.dispatch("pagerendered", { - source: this, - pageNumber: this.id, - cssTransform: true, - timestamp: performance.now(), - error: this.#renderError - }); - return; - } - } - this.cssTransform({}); - this.reset({ - keepAnnotationLayer: true, - keepAnnotationEditorLayer: true, - keepXfaLayer: true, - keepTextLayer: true, - keepCanvasWrapper: true - }); - } - cancelRendering({ - keepAnnotationLayer = false, - keepAnnotationEditorLayer = false, - keepXfaLayer = false, - keepTextLayer = false, - cancelExtraDelay = 0 - } = {}) { - if (this.renderTask) { - this.renderTask.cancel(cancelExtraDelay); - this.renderTask = null; - } - this.resume = null; - if (this.textLayer && (!keepTextLayer || !this.textLayer.div)) { - this.textLayer.cancel(); - this.textLayer = null; - } - if (this.annotationLayer && (!keepAnnotationLayer || !this.annotationLayer.div)) { - this.annotationLayer.cancel(); - this.annotationLayer = null; - this._annotationCanvasMap = null; - } - if (this.structTreeLayer && !this.textLayer) { - this.structTreeLayer = null; - } - if (this.annotationEditorLayer && (!keepAnnotationEditorLayer || !this.annotationEditorLayer.div)) { - if (this.drawLayer) { - this.drawLayer.cancel(); - this.drawLayer = null; - } - this.annotationEditorLayer.cancel(); - this.annotationEditorLayer = null; - } - if (this.xfaLayer && (!keepXfaLayer || !this.xfaLayer.div)) { - this.xfaLayer.cancel(); - this.xfaLayer = null; - this._textHighlighter?.disable(); - } - } - cssTransform({ - redrawAnnotationLayer = false, - redrawAnnotationEditorLayer = false, - redrawXfaLayer = false, - redrawTextLayer = false, - hideTextLayer = false - }) { - const { - canvas - } = this; - if (!canvas) { - return; - } - const originalViewport = this.#originalViewport; - if (this.viewport !== originalViewport) { - const relativeRotation = (360 + this.viewport.rotation - originalViewport.rotation) % 360; - if (relativeRotation === 90 || relativeRotation === 270) { - const { - width, - height - } = this.viewport; - const scaleX = height / width; - const scaleY = width / height; - canvas.style.transform = `rotate(${relativeRotation}deg) scale(${scaleX},${scaleY})`; - } else { - canvas.style.transform = relativeRotation === 0 ? "" : `rotate(${relativeRotation}deg)`; - } - } - if (redrawAnnotationLayer && this.annotationLayer) { - this.#renderAnnotationLayer(); - } - if (redrawAnnotationEditorLayer && this.annotationEditorLayer) { - if (this.drawLayer) { - this.#renderDrawLayer(); - } - this.#renderAnnotationEditorLayer(); - } - if (redrawXfaLayer && this.xfaLayer) { - this.#renderXfaLayer(); - } - if (this.textLayer) { - if (hideTextLayer) { - this.textLayer.hide(); - this.structTreeLayer?.hide(); - } else if (redrawTextLayer) { - this.#renderTextLayer(); - } - } - } - get width() { - return this.viewport.width; - } - get height() { - return this.viewport.height; - } - getPagePoint(x, y) { - return this.viewport.convertToPdfPoint(x, y); - } - async #finishRenderTask(renderTask, error = null) { - if (renderTask === this.renderTask) { - this.renderTask = null; - } - if (error instanceof RenderingCancelledException) { - this.#renderError = null; - return; - } - this.#renderError = error; - this.renderingState = RenderingStates.FINISHED; - this.#useThumbnailCanvas.regularAnnotations = !renderTask.separateAnnots; - this.eventBus.dispatch("pagerendered", { - source: this, - pageNumber: this.id, - cssTransform: false, - timestamp: performance.now(), - error: this.#renderError - }); - if (error) { - throw error; - } - } - async draw() { - if (this.renderingState !== RenderingStates.INITIAL) { - console.error("Must be in new state before drawing"); - this.reset(); - } - const { - div, - l10n, - pageColors, - pdfPage, - viewport - } = this; - if (!pdfPage) { - this.renderingState = RenderingStates.FINISHED; - throw new Error("pdfPage is not loaded"); - } - this.renderingState = RenderingStates.RUNNING; - let canvasWrapper = this.#canvasWrapper; - if (!canvasWrapper) { - canvasWrapper = this.#canvasWrapper = document.createElement("div"); - canvasWrapper.classList.add("canvasWrapper"); - this.#addLayer(canvasWrapper, "canvasWrapper"); - } - if (!this.textLayer && this.#textLayerMode !== TextLayerMode.DISABLE && !pdfPage.isPureXfa) { - this._accessibilityManager ||= new TextAccessibilityManager(); - this.textLayer = new TextLayerBuilder({ - pdfPage, - highlighter: this._textHighlighter, - accessibilityManager: this._accessibilityManager, - enablePermissions: this.#textLayerMode === TextLayerMode.ENABLE_PERMISSIONS, - onAppend: textLayerDiv => { - this.l10n.pause(); - this.#addLayer(textLayerDiv, "textLayer"); - this.l10n.resume(); - } - }); - } - if (!this.annotationLayer && this.#annotationMode !== AnnotationMode.DISABLE) { - const { - annotationStorage, - annotationEditorUIManager, - downloadManager, - enableScripting, - fieldObjectsPromise, - hasJSActionsPromise, - linkService - } = this.#layerProperties; - this._annotationCanvasMap ||= new Map(); - this.annotationLayer = new AnnotationLayerBuilder({ - pdfPage, - annotationStorage, - imageResourcesPath: this.imageResourcesPath, - renderForms: this.#annotationMode === AnnotationMode.ENABLE_FORMS, - linkService, - downloadManager, - enableScripting, - hasJSActionsPromise, - fieldObjectsPromise, - annotationCanvasMap: this._annotationCanvasMap, - accessibilityManager: this._accessibilityManager, - annotationEditorUIManager, - onAppend: annotationLayerDiv => { - this.#addLayer(annotationLayerDiv, "annotationLayer"); - } - }); - } - const renderContinueCallback = cont => { - showCanvas?.(false); - if (this.renderingQueue && !this.renderingQueue.isHighestPriority(this)) { - this.renderingState = RenderingStates.PAUSED; - this.resume = () => { - this.renderingState = RenderingStates.RUNNING; - cont(); - }; - return; - } - cont(); - }; - const { - width, - height - } = viewport; - const canvas = document.createElement("canvas"); - canvas.setAttribute("role", "presentation"); - const hasHCM = !!(pageColors?.background && pageColors?.foreground); - const prevCanvas = this.canvas; - const updateOnFirstShow = !prevCanvas && !hasHCM; - this.canvas = canvas; - this.#originalViewport = viewport; - let showCanvas = isLastShow => { - if (updateOnFirstShow) { - canvasWrapper.prepend(canvas); - showCanvas = null; - return; - } - if (!isLastShow) { - return; - } - if (prevCanvas) { - prevCanvas.replaceWith(canvas); - prevCanvas.width = prevCanvas.height = 0; - } else { - canvasWrapper.prepend(canvas); - } - showCanvas = null; - }; - const ctx = canvas.getContext("2d", { - alpha: false, - willReadFrequently: !this.#enableHWA - }); - const outputScale = this.outputScale = new OutputScale(); - if (this.maxCanvasPixels === 0) { - const invScale = 1 / this.scale; - outputScale.sx *= invScale; - outputScale.sy *= invScale; - this.#hasRestrictedScaling = true; - } else if (this.maxCanvasPixels > 0) { - const pixelsInViewport = width * height; - const maxScale = Math.sqrt(this.maxCanvasPixels / pixelsInViewport); - if (outputScale.sx > maxScale || outputScale.sy > maxScale) { - outputScale.sx = maxScale; - outputScale.sy = maxScale; - this.#hasRestrictedScaling = true; - } else { - this.#hasRestrictedScaling = false; - } - } - const sfx = approximateFraction(outputScale.sx); - const sfy = approximateFraction(outputScale.sy); - const canvasWidth = canvas.width = floorToDivide(calcRound(width * outputScale.sx), sfx[0]); - const canvasHeight = canvas.height = floorToDivide(calcRound(height * outputScale.sy), sfy[0]); - const pageWidth = floorToDivide(calcRound(width), sfx[1]); - const pageHeight = floorToDivide(calcRound(height), sfy[1]); - outputScale.sx = canvasWidth / pageWidth; - outputScale.sy = canvasHeight / pageHeight; - if (this.#scaleRoundX !== sfx[1]) { - div.style.setProperty("--scale-round-x", `${sfx[1]}px`); - this.#scaleRoundX = sfx[1]; - } - if (this.#scaleRoundY !== sfy[1]) { - div.style.setProperty("--scale-round-y", `${sfy[1]}px`); - this.#scaleRoundY = sfy[1]; - } - const transform = outputScale.scaled ? [outputScale.sx, 0, 0, outputScale.sy, 0, 0] : null; - const renderContext = { - canvasContext: ctx, - transform, - viewport, - annotationMode: this.#annotationMode, - optionalContentConfigPromise: this._optionalContentConfigPromise, - annotationCanvasMap: this._annotationCanvasMap, - pageColors, - isEditing: this.#isEditing - }; - const renderTask = this.renderTask = pdfPage.render(renderContext); - renderTask.onContinue = renderContinueCallback; - const resultPromise = renderTask.promise.then(async () => { - showCanvas?.(true); - await this.#finishRenderTask(renderTask); - this.structTreeLayer ||= new StructTreeLayerBuilder(pdfPage, viewport.rawDims); - this.#renderTextLayer(); - if (this.annotationLayer) { - await this.#renderAnnotationLayer(); - } - const { - annotationEditorUIManager - } = this.#layerProperties; - if (!annotationEditorUIManager) { - return; - } - this.drawLayer ||= new DrawLayerBuilder({ - pageIndex: this.id - }); - await this.#renderDrawLayer(); - this.drawLayer.setParent(canvasWrapper); - this.annotationEditorLayer ||= new AnnotationEditorLayerBuilder({ - uiManager: annotationEditorUIManager, - pdfPage, - l10n, - structTreeLayer: this.structTreeLayer, - accessibilityManager: this._accessibilityManager, - annotationLayer: this.annotationLayer?.annotationLayer, - textLayer: this.textLayer, - drawLayer: this.drawLayer.getDrawLayer(), - onAppend: annotationEditorLayerDiv => { - this.#addLayer(annotationEditorLayerDiv, "annotationEditorLayer"); - } - }); - this.#renderAnnotationEditorLayer(); - }, error => { - if (!(error instanceof RenderingCancelledException)) { - showCanvas?.(true); - } else { - prevCanvas?.remove(); - this.#resetCanvas(); - } - return this.#finishRenderTask(renderTask, error); - }); - if (pdfPage.isPureXfa) { - if (!this.xfaLayer) { - const { - annotationStorage, - linkService - } = this.#layerProperties; - this.xfaLayer = new XfaLayerBuilder({ - pdfPage, - annotationStorage, - linkService - }); - } - this.#renderXfaLayer(); - } - div.setAttribute("data-loaded", true); - this.eventBus.dispatch("pagerender", { - source: this, - pageNumber: this.id - }); - return resultPromise; - } - setPageLabel(label) { - this.pageLabel = typeof label === "string" ? label : null; - this.div.setAttribute("data-l10n-args", JSON.stringify({ - page: this.pageLabel ?? this.id - })); - if (this.pageLabel !== null) { - this.div.setAttribute("data-page-label", this.pageLabel); - } else { - this.div.removeAttribute("data-page-label"); - } - } - get thumbnailCanvas() { - const { - directDrawing, - initialOptionalContent, - regularAnnotations - } = this.#useThumbnailCanvas; - return directDrawing && initialOptionalContent && regularAnnotations ? this.canvas : null; - } -} - -;// ./web/generic_scripting.js - -async function docProperties(pdfDocument) { - const url = "", - baseUrl = url.split("#", 1)[0]; - let { - info, - metadata, - contentDispositionFilename, - contentLength - } = await pdfDocument.getMetadata(); - if (!contentLength) { - const { - length - } = await pdfDocument.getDownloadInfo(); - contentLength = length; - } - return { - ...info, - baseURL: baseUrl, - filesize: contentLength, - filename: contentDispositionFilename || getPdfFilenameFromUrl(url), - metadata: metadata?.getRaw(), - authors: metadata?.get("dc:creator"), - numPages: pdfDocument.numPages, - URL: url - }; -} -class GenericScripting { - constructor(sandboxBundleSrc) { - this._ready = new Promise((resolve, reject) => { - const sandbox = import(/*webpackIgnore: true*/sandboxBundleSrc); - sandbox.then(pdfjsSandbox => { - resolve(pdfjsSandbox.QuickJSSandbox()); - }).catch(reject); - }); - } - async createSandbox(data) { - const sandbox = await this._ready; - sandbox.create(data); - } - async dispatchEventInSandbox(event) { - const sandbox = await this._ready; - setTimeout(() => sandbox.dispatchEvent(event), 0); - } - async destroySandbox() { - const sandbox = await this._ready; - sandbox.nukeSandbox(); - } -} - -;// ./web/pdf_scripting_manager.js - - -class PDFScriptingManager { - #closeCapability = null; - #destroyCapability = null; - #docProperties = null; - #eventAbortController = null; - #eventBus = null; - #externalServices = null; - #pdfDocument = null; - #pdfViewer = null; - #ready = false; - #scripting = null; - #willPrintCapability = null; - constructor({ - eventBus, - externalServices = null, - docProperties = null - }) { - this.#eventBus = eventBus; - this.#externalServices = externalServices; - this.#docProperties = docProperties; - } - setViewer(pdfViewer) { - this.#pdfViewer = pdfViewer; - } - async setDocument(pdfDocument) { - if (this.#pdfDocument) { - await this.#destroyScripting(); - } - this.#pdfDocument = pdfDocument; - if (!pdfDocument) { - return; - } - const [objects, calculationOrder, docActions] = await Promise.all([pdfDocument.getFieldObjects(), pdfDocument.getCalculationOrderIds(), pdfDocument.getJSActions()]); - if (!objects && !docActions) { - await this.#destroyScripting(); - return; - } - if (pdfDocument !== this.#pdfDocument) { - return; - } - try { - this.#scripting = this.#initScripting(); - } catch (error) { - console.error("setDocument:", error); - await this.#destroyScripting(); - return; - } - const eventBus = this.#eventBus; - this.#eventAbortController = new AbortController(); - const { - signal - } = this.#eventAbortController; - eventBus._on("updatefromsandbox", event => { - if (event?.source === window) { - this.#updateFromSandbox(event.detail); - } - }, { - signal - }); - eventBus._on("dispatcheventinsandbox", event => { - this.#scripting?.dispatchEventInSandbox(event.detail); - }, { - signal - }); - eventBus._on("pagechanging", ({ - pageNumber, - previous - }) => { - if (pageNumber === previous) { - return; - } - this.#dispatchPageClose(previous); - this.#dispatchPageOpen(pageNumber); - }, { - signal - }); - eventBus._on("pagerendered", ({ - pageNumber - }) => { - if (!this._pageOpenPending.has(pageNumber)) { - return; - } - if (pageNumber !== this.#pdfViewer.currentPageNumber) { - return; - } - this.#dispatchPageOpen(pageNumber); - }, { - signal - }); - eventBus._on("pagesdestroy", async () => { - await this.#dispatchPageClose(this.#pdfViewer.currentPageNumber); - await this.#scripting?.dispatchEventInSandbox({ - id: "doc", - name: "WillClose" - }); - this.#closeCapability?.resolve(); - }, { - signal - }); - try { - const docProperties = await this.#docProperties(pdfDocument); - if (pdfDocument !== this.#pdfDocument) { - return; - } - await this.#scripting.createSandbox({ - objects, - calculationOrder, - appInfo: { - platform: navigator.platform, - language: navigator.language - }, - docInfo: { - ...docProperties, - actions: docActions - } - }); - eventBus.dispatch("sandboxcreated", { - source: this - }); - } catch (error) { - console.error("setDocument:", error); - await this.#destroyScripting(); - return; - } - await this.#scripting?.dispatchEventInSandbox({ - id: "doc", - name: "Open" - }); - await this.#dispatchPageOpen(this.#pdfViewer.currentPageNumber, true); - Promise.resolve().then(() => { - if (pdfDocument === this.#pdfDocument) { - this.#ready = true; - } - }); - } - async dispatchWillSave() { - return this.#scripting?.dispatchEventInSandbox({ - id: "doc", - name: "WillSave" - }); - } - async dispatchDidSave() { - return this.#scripting?.dispatchEventInSandbox({ - id: "doc", - name: "DidSave" - }); - } - async dispatchWillPrint() { - if (!this.#scripting) { - return; - } - await this.#willPrintCapability?.promise; - this.#willPrintCapability = Promise.withResolvers(); - try { - await this.#scripting.dispatchEventInSandbox({ - id: "doc", - name: "WillPrint" - }); - } catch (ex) { - this.#willPrintCapability.resolve(); - this.#willPrintCapability = null; - throw ex; - } - await this.#willPrintCapability.promise; - } - async dispatchDidPrint() { - return this.#scripting?.dispatchEventInSandbox({ - id: "doc", - name: "DidPrint" - }); - } - get destroyPromise() { - return this.#destroyCapability?.promise || null; - } - get ready() { - return this.#ready; - } - get _pageOpenPending() { - return shadow(this, "_pageOpenPending", new Set()); - } - get _visitedPages() { - return shadow(this, "_visitedPages", new Map()); - } - async #updateFromSandbox(detail) { - const pdfViewer = this.#pdfViewer; - const isInPresentationMode = pdfViewer.isInPresentationMode || pdfViewer.isChangingPresentationMode; - const { - id, - siblings, - command, - value - } = detail; - if (!id) { - switch (command) { - case "clear": - console.clear(); - break; - case "error": - console.error(value); - break; - case "layout": - if (!isInPresentationMode) { - const modes = apiPageLayoutToViewerModes(value); - pdfViewer.spreadMode = modes.spreadMode; - } - break; - case "page-num": - pdfViewer.currentPageNumber = value + 1; - break; - case "print": - await pdfViewer.pagesPromise; - this.#eventBus.dispatch("print", { - source: this - }); - break; - case "println": - console.log(value); - break; - case "zoom": - if (!isInPresentationMode) { - pdfViewer.currentScaleValue = value; - } - break; - case "SaveAs": - this.#eventBus.dispatch("download", { - source: this - }); - break; - case "FirstPage": - pdfViewer.currentPageNumber = 1; - break; - case "LastPage": - pdfViewer.currentPageNumber = pdfViewer.pagesCount; - break; - case "NextPage": - pdfViewer.nextPage(); - break; - case "PrevPage": - pdfViewer.previousPage(); - break; - case "ZoomViewIn": - if (!isInPresentationMode) { - pdfViewer.increaseScale(); - } - break; - case "ZoomViewOut": - if (!isInPresentationMode) { - pdfViewer.decreaseScale(); - } - break; - case "WillPrintFinished": - this.#willPrintCapability?.resolve(); - this.#willPrintCapability = null; - break; - } - return; - } - if (isInPresentationMode && detail.focus) { - return; - } - delete detail.id; - delete detail.siblings; - const ids = siblings ? [id, ...siblings] : [id]; - for (const elementId of ids) { - const element = document.querySelector(`[data-element-id="${elementId}"]`); - if (element) { - element.dispatchEvent(new CustomEvent("updatefromsandbox", { - detail - })); - } else { - this.#pdfDocument?.annotationStorage.setValue(elementId, detail); - } - } - } - async #dispatchPageOpen(pageNumber, initialize = false) { - const pdfDocument = this.#pdfDocument, - visitedPages = this._visitedPages; - if (initialize) { - this.#closeCapability = Promise.withResolvers(); - } - if (!this.#closeCapability) { - return; - } - const pageView = this.#pdfViewer.getPageView(pageNumber - 1); - if (pageView?.renderingState !== RenderingStates.FINISHED) { - this._pageOpenPending.add(pageNumber); - return; - } - this._pageOpenPending.delete(pageNumber); - const actionsPromise = (async () => { - const actions = await (!visitedPages.has(pageNumber) ? pageView.pdfPage?.getJSActions() : null); - if (pdfDocument !== this.#pdfDocument) { - return; - } - await this.#scripting?.dispatchEventInSandbox({ - id: "page", - name: "PageOpen", - pageNumber, - actions - }); - })(); - visitedPages.set(pageNumber, actionsPromise); - } - async #dispatchPageClose(pageNumber) { - const pdfDocument = this.#pdfDocument, - visitedPages = this._visitedPages; - if (!this.#closeCapability) { - return; - } - if (this._pageOpenPending.has(pageNumber)) { - return; - } - const actionsPromise = visitedPages.get(pageNumber); - if (!actionsPromise) { - return; - } - visitedPages.set(pageNumber, null); - await actionsPromise; - if (pdfDocument !== this.#pdfDocument) { - return; - } - await this.#scripting?.dispatchEventInSandbox({ - id: "page", - name: "PageClose", - pageNumber - }); - } - #initScripting() { - this.#destroyCapability = Promise.withResolvers(); - if (this.#scripting) { - throw new Error("#initScripting: Scripting already exists."); - } - return this.#externalServices.createScripting(); - } - async #destroyScripting() { - if (!this.#scripting) { - this.#pdfDocument = null; - this.#destroyCapability?.resolve(); - return; - } - if (this.#closeCapability) { - await Promise.race([this.#closeCapability.promise, new Promise(resolve => { - setTimeout(resolve, 1000); - })]).catch(() => {}); - this.#closeCapability = null; - } - this.#pdfDocument = null; - try { - await this.#scripting.destroySandbox(); - } catch {} - this.#willPrintCapability?.reject(new Error("Scripting destroyed.")); - this.#willPrintCapability = null; - this.#eventAbortController?.abort(); - this.#eventAbortController = null; - this._pageOpenPending.clear(); - this._visitedPages.clear(); - this.#scripting = null; - this.#ready = false; - this.#destroyCapability?.resolve(); - } -} - -;// ./web/pdf_scripting_manager.component.js - - -class PDFScriptingManagerComponents extends PDFScriptingManager { - constructor(options) { - if (!options.externalServices) { - window.addEventListener("updatefromsandbox", event => { - options.eventBus.dispatch("updatefromsandbox", { - source: window, - detail: event.detail - }); - }); - } - options.externalServices ||= { - createScripting: () => new GenericScripting(options.sandboxBundleSrc) - }; - options.docProperties ||= pdfDocument => docProperties(pdfDocument); - super(options); - } -} - -;// ./web/pdf_rendering_queue.js - - -const CLEANUP_TIMEOUT = 30000; -class PDFRenderingQueue { - constructor() { - this.pdfViewer = null; - this.pdfThumbnailViewer = null; - this.onIdle = null; - this.highestPriorityPage = null; - this.idleTimeout = null; - this.printing = false; - this.isThumbnailViewEnabled = false; - Object.defineProperty(this, "hasViewer", { - value: () => !!this.pdfViewer - }); - } - setViewer(pdfViewer) { - this.pdfViewer = pdfViewer; - } - setThumbnailViewer(pdfThumbnailViewer) { - this.pdfThumbnailViewer = pdfThumbnailViewer; - } - isHighestPriority(view) { - return this.highestPriorityPage === view.renderingId; - } - renderHighestPriority(currentlyVisiblePages) { - if (this.idleTimeout) { - clearTimeout(this.idleTimeout); - this.idleTimeout = null; - } - if (this.pdfViewer.forceRendering(currentlyVisiblePages)) { - return; - } - if (this.isThumbnailViewEnabled && this.pdfThumbnailViewer?.forceRendering()) { - return; - } - if (this.printing) { - return; - } - if (this.onIdle) { - this.idleTimeout = setTimeout(this.onIdle.bind(this), CLEANUP_TIMEOUT); - } - } - getHighestPriority(visible, views, scrolledDown, preRenderExtra = false) { - const visibleViews = visible.views, - numVisible = visibleViews.length; - if (numVisible === 0) { - return null; - } - for (let i = 0; i < numVisible; i++) { - const view = visibleViews[i].view; - if (!this.isViewFinished(view)) { - return view; - } - } - const firstId = visible.first.id, - lastId = visible.last.id; - if (lastId - firstId + 1 > numVisible) { - const visibleIds = visible.ids; - for (let i = 1, ii = lastId - firstId; i < ii; i++) { - const holeId = scrolledDown ? firstId + i : lastId - i; - if (visibleIds.has(holeId)) { - continue; - } - const holeView = views[holeId - 1]; - if (!this.isViewFinished(holeView)) { - return holeView; - } - } - } - let preRenderIndex = scrolledDown ? lastId : firstId - 2; - let preRenderView = views[preRenderIndex]; - if (preRenderView && !this.isViewFinished(preRenderView)) { - return preRenderView; - } - if (preRenderExtra) { - preRenderIndex += scrolledDown ? 1 : -1; - preRenderView = views[preRenderIndex]; - if (preRenderView && !this.isViewFinished(preRenderView)) { - return preRenderView; - } - } - return null; - } - isViewFinished(view) { - return view.renderingState === RenderingStates.FINISHED; - } - renderView(view) { - switch (view.renderingState) { - case RenderingStates.FINISHED: - return false; - case RenderingStates.PAUSED: - this.highestPriorityPage = view.renderingId; - view.resume(); - break; - case RenderingStates.RUNNING: - this.highestPriorityPage = view.renderingId; - break; - case RenderingStates.INITIAL: - this.highestPriorityPage = view.renderingId; - view.draw().finally(() => { - this.renderHighestPriority(); - }).catch(reason => { - if (reason instanceof RenderingCancelledException) { - return; - } - console.error("renderView:", reason); - }); - break; - } - return true; - } -} - -;// ./web/pdf_viewer.js - - - - - - -const DEFAULT_CACHE_SIZE = 10; -const PagesCountLimit = { - FORCE_SCROLL_MODE_PAGE: 10000, - FORCE_LAZY_PAGE_INIT: 5000, - PAUSE_EAGER_PAGE_INIT: 250 -}; -function isValidAnnotationEditorMode(mode) { - return Object.values(AnnotationEditorType).includes(mode) && mode !== AnnotationEditorType.DISABLE; -} -class PDFPageViewBuffer { - #buf = new Set(); - #size = 0; - constructor(size) { - this.#size = size; - } - push(view) { - const buf = this.#buf; - if (buf.has(view)) { - buf.delete(view); - } - buf.add(view); - if (buf.size > this.#size) { - this.#destroyFirstView(); - } - } - resize(newSize, idsToKeep = null) { - this.#size = newSize; - const buf = this.#buf; - if (idsToKeep) { - const ii = buf.size; - let i = 1; - for (const view of buf) { - if (idsToKeep.has(view.id)) { - buf.delete(view); - buf.add(view); - } - if (++i > ii) { - break; - } - } - } - while (buf.size > this.#size) { - this.#destroyFirstView(); - } - } - has(view) { - return this.#buf.has(view); - } - [Symbol.iterator]() { - return this.#buf.keys(); - } - #destroyFirstView() { - const firstView = this.#buf.keys().next().value; - firstView?.destroy(); - this.#buf.delete(firstView); - } -} -class PDFViewer { - #buffer = null; - #altTextManager = null; - #annotationEditorHighlightColors = null; - #annotationEditorMode = AnnotationEditorType.NONE; - #annotationEditorUIManager = null; - #annotationMode = AnnotationMode.ENABLE_FORMS; - #containerTopLeft = null; - #editorUndoBar = null; - #enableHWA = false; - #enableHighlightFloatingButton = false; - #enablePermissions = false; - #enableUpdatedAddImage = false; - #enableNewAltTextWhenAddingImage = false; - #eventAbortController = null; - #mlManager = null; - #switchAnnotationEditorModeAC = null; - #switchAnnotationEditorModeTimeoutId = null; - #getAllTextInProgress = false; - #hiddenCopyElement = null; - #interruptCopyCondition = false; - #previousContainerHeight = 0; - #resizeObserver = new ResizeObserver(this.#resizeObserverCallback.bind(this)); - #scrollModePageState = null; - #scaleTimeoutId = null; - #supportsPinchToZoom = true; - #textLayerMode = TextLayerMode.ENABLE; - constructor(options) { - const viewerVersion = "4.10.38"; - if (version !== viewerVersion) { - throw new Error(`The API version "${version}" does not match the Viewer version "${viewerVersion}".`); - } - this.container = options.container; - this.viewer = options.viewer || options.container.firstElementChild; - if (this.container?.tagName !== "DIV" || this.viewer?.tagName !== "DIV") { - throw new Error("Invalid `container` and/or `viewer` option."); - } - if (this.container.offsetParent && getComputedStyle(this.container).position !== "absolute") { - throw new Error("The `container` must be absolutely positioned."); - } - this.#resizeObserver.observe(this.container); - this.eventBus = options.eventBus; - this.linkService = options.linkService || new SimpleLinkService(); - this.downloadManager = options.downloadManager || null; - this.findController = options.findController || null; - this.#altTextManager = options.altTextManager || null; - this.#editorUndoBar = options.editorUndoBar || null; - if (this.findController) { - this.findController.onIsPageVisible = pageNumber => this._getVisiblePages().ids.has(pageNumber); - } - this._scriptingManager = options.scriptingManager || null; - this.#textLayerMode = options.textLayerMode ?? TextLayerMode.ENABLE; - this.#annotationMode = options.annotationMode ?? AnnotationMode.ENABLE_FORMS; - this.#annotationEditorMode = options.annotationEditorMode ?? AnnotationEditorType.NONE; - this.#annotationEditorHighlightColors = options.annotationEditorHighlightColors || null; - this.#enableHighlightFloatingButton = options.enableHighlightFloatingButton === true; - this.#enableUpdatedAddImage = options.enableUpdatedAddImage === true; - this.#enableNewAltTextWhenAddingImage = options.enableNewAltTextWhenAddingImage === true; - this.imageResourcesPath = options.imageResourcesPath || ""; - this.enablePrintAutoRotate = options.enablePrintAutoRotate || false; - this.removePageBorders = options.removePageBorders || false; - this.maxCanvasPixels = options.maxCanvasPixels; - this.l10n = options.l10n; - this.l10n ||= new genericl10n_GenericL10n(); - this.#enablePermissions = options.enablePermissions || false; - this.pageColors = options.pageColors || null; - this.#mlManager = options.mlManager || null; - this.#enableHWA = options.enableHWA || false; - this.#supportsPinchToZoom = options.supportsPinchToZoom !== false; - this.defaultRenderingQueue = !options.renderingQueue; - if (this.defaultRenderingQueue) { - this.renderingQueue = new PDFRenderingQueue(); - this.renderingQueue.setViewer(this); - } else { - this.renderingQueue = options.renderingQueue; - } - const { - abortSignal - } = options; - abortSignal?.addEventListener("abort", () => { - this.#resizeObserver.disconnect(); - this.#resizeObserver = null; - }, { - once: true - }); - this.scroll = watchScroll(this.container, this._scrollUpdate.bind(this), abortSignal); - this.presentationModeState = PresentationModeState.UNKNOWN; - this._resetView(); - if (this.removePageBorders) { - this.viewer.classList.add("removePageBorders"); - } - this.#updateContainerHeightCss(); - this.eventBus._on("thumbnailrendered", ({ - pageNumber, - pdfPage - }) => { - const pageView = this._pages[pageNumber - 1]; - if (!this.#buffer.has(pageView)) { - pdfPage?.cleanup(); - } - }); - if (!options.l10n) { - this.l10n.translate(this.container); - } - } - get pagesCount() { - return this._pages.length; - } - getPageView(index) { - return this._pages[index]; - } - getCachedPageViews() { - return new Set(this.#buffer); - } - get pageViewsReady() { - return this._pages.every(pageView => pageView?.pdfPage); - } - get renderForms() { - return this.#annotationMode === AnnotationMode.ENABLE_FORMS; - } - get enableScripting() { - return !!this._scriptingManager; - } - get currentPageNumber() { - return this._currentPageNumber; - } - set currentPageNumber(val) { - if (!Number.isInteger(val)) { - throw new Error("Invalid page number."); - } - if (!this.pdfDocument) { - return; - } - if (!this._setCurrentPageNumber(val, true)) { - console.error(`currentPageNumber: "${val}" is not a valid page.`); - } - } - _setCurrentPageNumber(val, resetCurrentPageView = false) { - if (this._currentPageNumber === val) { - if (resetCurrentPageView) { - this.#resetCurrentPageView(); - } - return true; - } - if (!(0 < val && val <= this.pagesCount)) { - return false; - } - const previous = this._currentPageNumber; - this._currentPageNumber = val; - this.eventBus.dispatch("pagechanging", { - source: this, - pageNumber: val, - pageLabel: this._pageLabels?.[val - 1] ?? null, - previous - }); - if (resetCurrentPageView) { - this.#resetCurrentPageView(); - } - return true; - } - get currentPageLabel() { - return this._pageLabels?.[this._currentPageNumber - 1] ?? null; - } - set currentPageLabel(val) { - if (!this.pdfDocument) { - return; - } - let page = val | 0; - if (this._pageLabels) { - const i = this._pageLabels.indexOf(val); - if (i >= 0) { - page = i + 1; - } - } - if (!this._setCurrentPageNumber(page, true)) { - console.error(`currentPageLabel: "${val}" is not a valid page.`); - } - } - get currentScale() { - return this._currentScale !== UNKNOWN_SCALE ? this._currentScale : DEFAULT_SCALE; - } - set currentScale(val) { - if (isNaN(val)) { - throw new Error("Invalid numeric scale."); - } - if (!this.pdfDocument) { - return; - } - this.#setScale(val, { - noScroll: false - }); - } - get currentScaleValue() { - return this._currentScaleValue; - } - set currentScaleValue(val) { - if (!this.pdfDocument) { - return; - } - this.#setScale(val, { - noScroll: false - }); - } - get pagesRotation() { - return this._pagesRotation; - } - set pagesRotation(rotation) { - if (!isValidRotation(rotation)) { - throw new Error("Invalid pages rotation angle."); - } - if (!this.pdfDocument) { - return; - } - rotation %= 360; - if (rotation < 0) { - rotation += 360; - } - if (this._pagesRotation === rotation) { - return; - } - this._pagesRotation = rotation; - const pageNumber = this._currentPageNumber; - this.refresh(true, { - rotation - }); - if (this._currentScaleValue) { - this.#setScale(this._currentScaleValue, { - noScroll: true - }); - } - this.eventBus.dispatch("rotationchanging", { - source: this, - pagesRotation: rotation, - pageNumber - }); - if (this.defaultRenderingQueue) { - this.update(); - } - } - get firstPagePromise() { - return this.pdfDocument ? this._firstPageCapability.promise : null; - } - get onePageRendered() { - return this.pdfDocument ? this._onePageRenderedCapability.promise : null; - } - get pagesPromise() { - return this.pdfDocument ? this._pagesCapability.promise : null; - } - get _layerProperties() { - const self = this; - return shadow(this, "_layerProperties", { - get annotationEditorUIManager() { - return self.#annotationEditorUIManager; - }, - get annotationStorage() { - return self.pdfDocument?.annotationStorage; - }, - get downloadManager() { - return self.downloadManager; - }, - get enableScripting() { - return !!self._scriptingManager; - }, - get fieldObjectsPromise() { - return self.pdfDocument?.getFieldObjects(); - }, - get findController() { - return self.findController; - }, - get hasJSActionsPromise() { - return self.pdfDocument?.hasJSActions(); - }, - get linkService() { - return self.linkService; - } - }); - } - #initializePermissions(permissions) { - const params = { - annotationEditorMode: this.#annotationEditorMode, - annotationMode: this.#annotationMode, - textLayerMode: this.#textLayerMode - }; - if (!permissions) { - return params; - } - if (!permissions.includes(PermissionFlag.COPY) && this.#textLayerMode === TextLayerMode.ENABLE) { - params.textLayerMode = TextLayerMode.ENABLE_PERMISSIONS; - } - if (!permissions.includes(PermissionFlag.MODIFY_CONTENTS)) { - params.annotationEditorMode = AnnotationEditorType.DISABLE; - } - if (!permissions.includes(PermissionFlag.MODIFY_ANNOTATIONS) && !permissions.includes(PermissionFlag.FILL_INTERACTIVE_FORMS) && this.#annotationMode === AnnotationMode.ENABLE_FORMS) { - params.annotationMode = AnnotationMode.ENABLE; - } - return params; - } - async #onePageRenderedOrForceFetch(signal) { - if (document.visibilityState === "hidden" || !this.container.offsetParent || this._getVisiblePages().views.length === 0) { - return; - } - const hiddenCapability = Promise.withResolvers(), - ac = new AbortController(); - document.addEventListener("visibilitychange", () => { - if (document.visibilityState === "hidden") { - hiddenCapability.resolve(); - } - }, { - signal: typeof AbortSignal.any === "function" ? AbortSignal.any([signal, ac.signal]) : signal - }); - await Promise.race([this._onePageRenderedCapability.promise, hiddenCapability.promise]); - ac.abort(); - } - async getAllText() { - const texts = []; - const buffer = []; - for (let pageNum = 1, pagesCount = this.pdfDocument.numPages; pageNum <= pagesCount; ++pageNum) { - if (this.#interruptCopyCondition) { - return null; - } - buffer.length = 0; - const page = await this.pdfDocument.getPage(pageNum); - const { - items - } = await page.getTextContent(); - for (const item of items) { - if (item.str) { - buffer.push(item.str); - } - if (item.hasEOL) { - buffer.push("\n"); - } - } - texts.push(removeNullCharacters(buffer.join(""))); - } - return texts.join("\n"); - } - #copyCallback(textLayerMode, event) { - const selection = document.getSelection(); - const { - focusNode, - anchorNode - } = selection; - if (anchorNode && focusNode && selection.containsNode(this.#hiddenCopyElement)) { - if (this.#getAllTextInProgress || textLayerMode === TextLayerMode.ENABLE_PERMISSIONS) { - stopEvent(event); - return; - } - this.#getAllTextInProgress = true; - const { - classList - } = this.viewer; - classList.add("copyAll"); - const ac = new AbortController(); - window.addEventListener("keydown", ev => this.#interruptCopyCondition = ev.key === "Escape", { - signal: ac.signal - }); - this.getAllText().then(async text => { - if (text !== null) { - await navigator.clipboard.writeText(text); - } - }).catch(reason => { - console.warn(`Something goes wrong when extracting the text: ${reason.message}`); - }).finally(() => { - this.#getAllTextInProgress = false; - this.#interruptCopyCondition = false; - ac.abort(); - classList.remove("copyAll"); - }); - stopEvent(event); - } - } - setDocument(pdfDocument) { - if (this.pdfDocument) { - this.eventBus.dispatch("pagesdestroy", { - source: this - }); - this._cancelRendering(); - this._resetView(); - this.findController?.setDocument(null); - this._scriptingManager?.setDocument(null); - this.#annotationEditorUIManager?.destroy(); - this.#annotationEditorUIManager = null; - } - this.pdfDocument = pdfDocument; - if (!pdfDocument) { - return; - } - const pagesCount = pdfDocument.numPages; - const firstPagePromise = pdfDocument.getPage(1); - const optionalContentConfigPromise = pdfDocument.getOptionalContentConfig({ - intent: "display" - }); - const permissionsPromise = this.#enablePermissions ? pdfDocument.getPermissions() : Promise.resolve(); - const { - eventBus, - pageColors, - viewer - } = this; - this.#eventAbortController = new AbortController(); - const { - signal - } = this.#eventAbortController; - if (pagesCount > PagesCountLimit.FORCE_SCROLL_MODE_PAGE) { - console.warn("Forcing PAGE-scrolling for performance reasons, given the length of the document."); - const mode = this._scrollMode = ScrollMode.PAGE; - eventBus.dispatch("scrollmodechanged", { - source: this, - mode - }); - } - this._pagesCapability.promise.then(() => { - eventBus.dispatch("pagesloaded", { - source: this, - pagesCount - }); - }, () => {}); - const onBeforeDraw = evt => { - const pageView = this._pages[evt.pageNumber - 1]; - if (!pageView) { - return; - } - this.#buffer.push(pageView); - }; - eventBus._on("pagerender", onBeforeDraw, { - signal - }); - const onAfterDraw = evt => { - if (evt.cssTransform) { - return; - } - this._onePageRenderedCapability.resolve({ - timestamp: evt.timestamp - }); - eventBus._off("pagerendered", onAfterDraw); - }; - eventBus._on("pagerendered", onAfterDraw, { - signal - }); - Promise.all([firstPagePromise, permissionsPromise]).then(([firstPdfPage, permissions]) => { - if (pdfDocument !== this.pdfDocument) { - return; - } - this._firstPageCapability.resolve(firstPdfPage); - this._optionalContentConfigPromise = optionalContentConfigPromise; - const { - annotationEditorMode, - annotationMode, - textLayerMode - } = this.#initializePermissions(permissions); - if (textLayerMode !== TextLayerMode.DISABLE) { - const element = this.#hiddenCopyElement = document.createElement("div"); - element.id = "hiddenCopyElement"; - viewer.before(element); - } - if (typeof AbortSignal.any === "function" && annotationEditorMode !== AnnotationEditorType.DISABLE) { - const mode = annotationEditorMode; - if (pdfDocument.isPureXfa) { - console.warn("Warning: XFA-editing is not implemented."); - } else if (isValidAnnotationEditorMode(mode)) { - this.#annotationEditorUIManager = new AnnotationEditorUIManager(this.container, viewer, this.#altTextManager, eventBus, pdfDocument, pageColors, this.#annotationEditorHighlightColors, this.#enableHighlightFloatingButton, this.#enableUpdatedAddImage, this.#enableNewAltTextWhenAddingImage, this.#mlManager, this.#editorUndoBar, this.#supportsPinchToZoom); - eventBus.dispatch("annotationeditoruimanager", { - source: this, - uiManager: this.#annotationEditorUIManager - }); - if (mode !== AnnotationEditorType.NONE) { - if (mode === AnnotationEditorType.STAMP) { - this.#mlManager?.loadModel("altText"); - } - this.#annotationEditorUIManager.updateMode(mode); - } - } else { - console.error(`Invalid AnnotationEditor mode: ${mode}`); - } - } - const viewerElement = this._scrollMode === ScrollMode.PAGE ? null : viewer; - const scale = this.currentScale; - const viewport = firstPdfPage.getViewport({ - scale: scale * PixelsPerInch.PDF_TO_CSS_UNITS - }); - viewer.style.setProperty("--scale-factor", viewport.scale); - if (pageColors?.background) { - viewer.style.setProperty("--page-bg-color", pageColors.background); - } - if (pageColors?.foreground === "CanvasText" || pageColors?.background === "Canvas") { - viewer.style.setProperty("--hcm-highlight-filter", pdfDocument.filterFactory.addHighlightHCMFilter("highlight", "CanvasText", "Canvas", "HighlightText", "Highlight")); - viewer.style.setProperty("--hcm-highlight-selected-filter", pdfDocument.filterFactory.addHighlightHCMFilter("highlight_selected", "CanvasText", "Canvas", "HighlightText", "ButtonText")); - } - for (let pageNum = 1; pageNum <= pagesCount; ++pageNum) { - const pageView = new PDFPageView({ - container: viewerElement, - eventBus, - id: pageNum, - scale, - defaultViewport: viewport.clone(), - optionalContentConfigPromise, - renderingQueue: this.renderingQueue, - textLayerMode, - annotationMode, - imageResourcesPath: this.imageResourcesPath, - maxCanvasPixels: this.maxCanvasPixels, - pageColors, - l10n: this.l10n, - layerProperties: this._layerProperties, - enableHWA: this.#enableHWA - }); - this._pages.push(pageView); - } - this._pages[0]?.setPdfPage(firstPdfPage); - if (this._scrollMode === ScrollMode.PAGE) { - this.#ensurePageViewVisible(); - } else if (this._spreadMode !== SpreadMode.NONE) { - this._updateSpreadMode(); - } - this.#onePageRenderedOrForceFetch(signal).then(async () => { - if (pdfDocument !== this.pdfDocument) { - return; - } - this.findController?.setDocument(pdfDocument); - this._scriptingManager?.setDocument(pdfDocument); - if (this.#hiddenCopyElement) { - document.addEventListener("copy", this.#copyCallback.bind(this, textLayerMode), { - signal - }); - } - if (this.#annotationEditorUIManager) { - eventBus.dispatch("annotationeditormodechanged", { - source: this, - mode: this.#annotationEditorMode - }); - } - if (pdfDocument.loadingParams.disableAutoFetch || pagesCount > PagesCountLimit.FORCE_LAZY_PAGE_INIT) { - this._pagesCapability.resolve(); - return; - } - let getPagesLeft = pagesCount - 1; - if (getPagesLeft <= 0) { - this._pagesCapability.resolve(); - return; - } - for (let pageNum = 2; pageNum <= pagesCount; ++pageNum) { - const promise = pdfDocument.getPage(pageNum).then(pdfPage => { - const pageView = this._pages[pageNum - 1]; - if (!pageView.pdfPage) { - pageView.setPdfPage(pdfPage); - } - if (--getPagesLeft === 0) { - this._pagesCapability.resolve(); - } - }, reason => { - console.error(`Unable to get page ${pageNum} to initialize viewer`, reason); - if (--getPagesLeft === 0) { - this._pagesCapability.resolve(); - } - }); - if (pageNum % PagesCountLimit.PAUSE_EAGER_PAGE_INIT === 0) { - await promise; - } - } - }); - eventBus.dispatch("pagesinit", { - source: this - }); - pdfDocument.getMetadata().then(({ - info - }) => { - if (pdfDocument !== this.pdfDocument) { - return; - } - if (info.Language) { - viewer.lang = info.Language; - } - }); - if (this.defaultRenderingQueue) { - this.update(); - } - }).catch(reason => { - console.error("Unable to initialize viewer", reason); - this._pagesCapability.reject(reason); - }); - } - setPageLabels(labels) { - if (!this.pdfDocument) { - return; - } - if (!labels) { - this._pageLabels = null; - } else if (!(Array.isArray(labels) && this.pdfDocument.numPages === labels.length)) { - this._pageLabels = null; - console.error(`setPageLabels: Invalid page labels.`); - } else { - this._pageLabels = labels; - } - for (let i = 0, ii = this._pages.length; i < ii; i++) { - this._pages[i].setPageLabel(this._pageLabels?.[i] ?? null); - } - } - _resetView() { - this._pages = []; - this._currentPageNumber = 1; - this._currentScale = UNKNOWN_SCALE; - this._currentScaleValue = null; - this._pageLabels = null; - this.#buffer = new PDFPageViewBuffer(DEFAULT_CACHE_SIZE); - this._location = null; - this._pagesRotation = 0; - this._optionalContentConfigPromise = null; - this._firstPageCapability = Promise.withResolvers(); - this._onePageRenderedCapability = Promise.withResolvers(); - this._pagesCapability = Promise.withResolvers(); - this._scrollMode = ScrollMode.VERTICAL; - this._previousScrollMode = ScrollMode.UNKNOWN; - this._spreadMode = SpreadMode.NONE; - this.#scrollModePageState = { - previousPageNumber: 1, - scrollDown: true, - pages: [] - }; - this.#eventAbortController?.abort(); - this.#eventAbortController = null; - this.viewer.textContent = ""; - this._updateScrollMode(); - this.viewer.removeAttribute("lang"); - this.#hiddenCopyElement?.remove(); - this.#hiddenCopyElement = null; - this.#cleanupSwitchAnnotationEditorMode(); - } - #ensurePageViewVisible() { - if (this._scrollMode !== ScrollMode.PAGE) { - throw new Error("#ensurePageViewVisible: Invalid scrollMode value."); - } - const pageNumber = this._currentPageNumber, - state = this.#scrollModePageState, - viewer = this.viewer; - viewer.textContent = ""; - state.pages.length = 0; - if (this._spreadMode === SpreadMode.NONE && !this.isInPresentationMode) { - const pageView = this._pages[pageNumber - 1]; - viewer.append(pageView.div); - state.pages.push(pageView); - } else { - const pageIndexSet = new Set(), - parity = this._spreadMode - 1; - if (parity === -1) { - pageIndexSet.add(pageNumber - 1); - } else if (pageNumber % 2 !== parity) { - pageIndexSet.add(pageNumber - 1); - pageIndexSet.add(pageNumber); - } else { - pageIndexSet.add(pageNumber - 2); - pageIndexSet.add(pageNumber - 1); - } - const spread = document.createElement("div"); - spread.className = "spread"; - if (this.isInPresentationMode) { - const dummyPage = document.createElement("div"); - dummyPage.className = "dummyPage"; - spread.append(dummyPage); - } - for (const i of pageIndexSet) { - const pageView = this._pages[i]; - if (!pageView) { - continue; - } - spread.append(pageView.div); - state.pages.push(pageView); - } - viewer.append(spread); - } - state.scrollDown = pageNumber >= state.previousPageNumber; - state.previousPageNumber = pageNumber; - } - _scrollUpdate() { - if (this.pagesCount === 0) { - return; - } - this.update(); - } - #scrollIntoView(pageView, pageSpot = null) { - const { - div, - id - } = pageView; - if (this._currentPageNumber !== id) { - this._setCurrentPageNumber(id); - } - if (this._scrollMode === ScrollMode.PAGE) { - this.#ensurePageViewVisible(); - this.update(); - } - if (!pageSpot && !this.isInPresentationMode) { - const left = div.offsetLeft + div.clientLeft, - right = left + div.clientWidth; - const { - scrollLeft, - clientWidth - } = this.container; - if (this._scrollMode === ScrollMode.HORIZONTAL || left < scrollLeft || right > scrollLeft + clientWidth) { - pageSpot = { - left: 0, - top: 0 - }; - } - } - scrollIntoView(div, pageSpot); - if (!this._currentScaleValue && this._location) { - this._location = null; - } - } - #isSameScale(newScale) { - return newScale === this._currentScale || Math.abs(newScale - this._currentScale) < 1e-15; - } - #setScaleUpdatePages(newScale, newValue, { - noScroll = false, - preset = false, - drawingDelay = -1, - origin = null - }) { - this._currentScaleValue = newValue.toString(); - if (this.#isSameScale(newScale)) { - if (preset) { - this.eventBus.dispatch("scalechanging", { - source: this, - scale: newScale, - presetValue: newValue - }); - } - return; - } - this.viewer.style.setProperty("--scale-factor", newScale * PixelsPerInch.PDF_TO_CSS_UNITS); - const postponeDrawing = drawingDelay >= 0 && drawingDelay < 1000; - this.refresh(true, { - scale: newScale, - drawingDelay: postponeDrawing ? drawingDelay : -1 - }); - if (postponeDrawing) { - this.#scaleTimeoutId = setTimeout(() => { - this.#scaleTimeoutId = null; - this.refresh(); - }, drawingDelay); - } - const previousScale = this._currentScale; - this._currentScale = newScale; - if (!noScroll) { - let page = this._currentPageNumber, - dest; - if (this._location && !(this.isInPresentationMode || this.isChangingPresentationMode)) { - page = this._location.pageNumber; - dest = [null, { - name: "XYZ" - }, this._location.left, this._location.top, null]; - } - this.scrollPageIntoView({ - pageNumber: page, - destArray: dest, - allowNegativeOffset: true - }); - if (Array.isArray(origin)) { - const scaleDiff = newScale / previousScale - 1; - const [top, left] = this.containerTopLeft; - this.container.scrollLeft += (origin[0] - left) * scaleDiff; - this.container.scrollTop += (origin[1] - top) * scaleDiff; - } - } - this.eventBus.dispatch("scalechanging", { - source: this, - scale: newScale, - presetValue: preset ? newValue : undefined - }); - if (this.defaultRenderingQueue) { - this.update(); - } - } - get #pageWidthScaleFactor() { - if (this._spreadMode !== SpreadMode.NONE && this._scrollMode !== ScrollMode.HORIZONTAL) { - return 2; - } - return 1; - } - #setScale(value, options) { - let scale = parseFloat(value); - if (scale > 0) { - options.preset = false; - this.#setScaleUpdatePages(scale, value, options); - } else { - const currentPage = this._pages[this._currentPageNumber - 1]; - if (!currentPage) { - return; - } - let hPadding = SCROLLBAR_PADDING, - vPadding = VERTICAL_PADDING; - if (this.isInPresentationMode) { - hPadding = vPadding = 4; - if (this._spreadMode !== SpreadMode.NONE) { - hPadding *= 2; - } - } else if (this.removePageBorders) { - hPadding = vPadding = 0; - } else if (this._scrollMode === ScrollMode.HORIZONTAL) { - [hPadding, vPadding] = [vPadding, hPadding]; - } - const pageWidthScale = (this.container.clientWidth - hPadding) / currentPage.width * currentPage.scale / this.#pageWidthScaleFactor; - const pageHeightScale = (this.container.clientHeight - vPadding) / currentPage.height * currentPage.scale; - switch (value) { - case "page-actual": - scale = 1; - break; - case "page-width": - scale = pageWidthScale; - break; - case "page-height": - scale = pageHeightScale; - break; - case "page-fit": - scale = Math.min(pageWidthScale, pageHeightScale); - break; - case "auto": - const horizontalScale = isPortraitOrientation(currentPage) ? pageWidthScale : Math.min(pageHeightScale, pageWidthScale); - scale = Math.min(MAX_AUTO_SCALE, horizontalScale); - break; - default: - console.error(`#setScale: "${value}" is an unknown zoom value.`); - return; - } - options.preset = true; - this.#setScaleUpdatePages(scale, value, options); - } - } - #resetCurrentPageView() { - const pageView = this._pages[this._currentPageNumber - 1]; - if (this.isInPresentationMode) { - this.#setScale(this._currentScaleValue, { - noScroll: true - }); - } - this.#scrollIntoView(pageView); - } - pageLabelToPageNumber(label) { - if (!this._pageLabels) { - return null; - } - const i = this._pageLabels.indexOf(label); - if (i < 0) { - return null; - } - return i + 1; - } - scrollPageIntoView({ - pageNumber, - destArray = null, - allowNegativeOffset = false, - ignoreDestinationZoom = false - }) { - if (!this.pdfDocument) { - return; - } - const pageView = Number.isInteger(pageNumber) && this._pages[pageNumber - 1]; - if (!pageView) { - console.error(`scrollPageIntoView: "${pageNumber}" is not a valid pageNumber parameter.`); - return; - } - if (this.isInPresentationMode || !destArray) { - this._setCurrentPageNumber(pageNumber, true); - return; - } - let x = 0, - y = 0; - let width = 0, - height = 0, - widthScale, - heightScale; - const changeOrientation = pageView.rotation % 180 !== 0; - const pageWidth = (changeOrientation ? pageView.height : pageView.width) / pageView.scale / PixelsPerInch.PDF_TO_CSS_UNITS; - const pageHeight = (changeOrientation ? pageView.width : pageView.height) / pageView.scale / PixelsPerInch.PDF_TO_CSS_UNITS; - let scale = 0; - switch (destArray[1].name) { - case "XYZ": - x = destArray[2]; - y = destArray[3]; - scale = destArray[4]; - x = x !== null ? x : 0; - y = y !== null ? y : pageHeight; - break; - case "Fit": - case "FitB": - scale = "page-fit"; - break; - case "FitH": - case "FitBH": - y = destArray[2]; - scale = "page-width"; - if (y === null && this._location) { - x = this._location.left; - y = this._location.top; - } else if (typeof y !== "number" || y < 0) { - y = pageHeight; - } - break; - case "FitV": - case "FitBV": - x = destArray[2]; - width = pageWidth; - height = pageHeight; - scale = "page-height"; - break; - case "FitR": - x = destArray[2]; - y = destArray[3]; - width = destArray[4] - x; - height = destArray[5] - y; - let hPadding = SCROLLBAR_PADDING, - vPadding = VERTICAL_PADDING; - if (this.removePageBorders) { - hPadding = vPadding = 0; - } - widthScale = (this.container.clientWidth - hPadding) / width / PixelsPerInch.PDF_TO_CSS_UNITS; - heightScale = (this.container.clientHeight - vPadding) / height / PixelsPerInch.PDF_TO_CSS_UNITS; - scale = Math.min(Math.abs(widthScale), Math.abs(heightScale)); - break; - default: - console.error(`scrollPageIntoView: "${destArray[1].name}" is not a valid destination type.`); - return; - } - if (!ignoreDestinationZoom) { - if (scale && scale !== this._currentScale) { - this.currentScaleValue = scale; - } else if (this._currentScale === UNKNOWN_SCALE) { - this.currentScaleValue = DEFAULT_SCALE_VALUE; - } - } - if (scale === "page-fit" && !destArray[4]) { - this.#scrollIntoView(pageView); - return; - } - const boundingRect = [pageView.viewport.convertToViewportPoint(x, y), pageView.viewport.convertToViewportPoint(x + width, y + height)]; - let left = Math.min(boundingRect[0][0], boundingRect[1][0]); - let top = Math.min(boundingRect[0][1], boundingRect[1][1]); - if (!allowNegativeOffset) { - left = Math.max(left, 0); - top = Math.max(top, 0); - } - this.#scrollIntoView(pageView, { - left, - top - }); - } - _updateLocation(firstPage) { - const currentScale = this._currentScale; - const currentScaleValue = this._currentScaleValue; - const normalizedScaleValue = parseFloat(currentScaleValue) === currentScale ? Math.round(currentScale * 10000) / 100 : currentScaleValue; - const pageNumber = firstPage.id; - const currentPageView = this._pages[pageNumber - 1]; - const container = this.container; - const topLeft = currentPageView.getPagePoint(container.scrollLeft - firstPage.x, container.scrollTop - firstPage.y); - const intLeft = Math.round(topLeft[0]); - const intTop = Math.round(topLeft[1]); - let pdfOpenParams = `#page=${pageNumber}`; - if (!this.isInPresentationMode) { - pdfOpenParams += `&zoom=${normalizedScaleValue},${intLeft},${intTop}`; - } - this._location = { - pageNumber, - scale: normalizedScaleValue, - top: intTop, - left: intLeft, - rotation: this._pagesRotation, - pdfOpenParams - }; - } - update() { - const visible = this._getVisiblePages(); - const visiblePages = visible.views, - numVisiblePages = visiblePages.length; - if (numVisiblePages === 0) { - return; - } - const newCacheSize = Math.max(DEFAULT_CACHE_SIZE, 2 * numVisiblePages + 1); - this.#buffer.resize(newCacheSize, visible.ids); - this.renderingQueue.renderHighestPriority(visible); - const isSimpleLayout = this._spreadMode === SpreadMode.NONE && (this._scrollMode === ScrollMode.PAGE || this._scrollMode === ScrollMode.VERTICAL); - const currentId = this._currentPageNumber; - let stillFullyVisible = false; - for (const page of visiblePages) { - if (page.percent < 100) { - break; - } - if (page.id === currentId && isSimpleLayout) { - stillFullyVisible = true; - break; - } - } - this._setCurrentPageNumber(stillFullyVisible ? currentId : visiblePages[0].id); - this._updateLocation(visible.first); - this.eventBus.dispatch("updateviewarea", { - source: this, - location: this._location - }); - } - #switchToEditAnnotationMode() { - const visible = this._getVisiblePages(); - const pagesToRefresh = []; - const { - ids, - views - } = visible; - for (const page of views) { - const { - view - } = page; - if (!view.hasEditableAnnotations()) { - ids.delete(view.id); - continue; - } - pagesToRefresh.push(page); - } - if (pagesToRefresh.length === 0) { - return null; - } - this.renderingQueue.renderHighestPriority({ - first: pagesToRefresh[0], - last: pagesToRefresh.at(-1), - views: pagesToRefresh, - ids - }); - return ids; - } - containsElement(element) { - return this.container.contains(element); - } - focus() { - this.container.focus(); - } - get _isContainerRtl() { - return getComputedStyle(this.container).direction === "rtl"; - } - get isInPresentationMode() { - return this.presentationModeState === PresentationModeState.FULLSCREEN; - } - get isChangingPresentationMode() { - return this.presentationModeState === PresentationModeState.CHANGING; - } - get isHorizontalScrollbarEnabled() { - return this.isInPresentationMode ? false : this.container.scrollWidth > this.container.clientWidth; - } - get isVerticalScrollbarEnabled() { - return this.isInPresentationMode ? false : this.container.scrollHeight > this.container.clientHeight; - } - _getVisiblePages() { - const views = this._scrollMode === ScrollMode.PAGE ? this.#scrollModePageState.pages : this._pages, - horizontal = this._scrollMode === ScrollMode.HORIZONTAL, - rtl = horizontal && this._isContainerRtl; - return getVisibleElements({ - scrollEl: this.container, - views, - sortByVisibility: true, - horizontal, - rtl - }); - } - cleanup() { - for (const pageView of this._pages) { - if (pageView.renderingState !== RenderingStates.FINISHED) { - pageView.reset(); - } - } - } - _cancelRendering() { - for (const pageView of this._pages) { - pageView.cancelRendering(); - } - } - async #ensurePdfPageLoaded(pageView) { - if (pageView.pdfPage) { - return pageView.pdfPage; - } - try { - const pdfPage = await this.pdfDocument.getPage(pageView.id); - if (!pageView.pdfPage) { - pageView.setPdfPage(pdfPage); - } - return pdfPage; - } catch (reason) { - console.error("Unable to get page for page view", reason); - return null; - } - } - #getScrollAhead(visible) { - if (visible.first?.id === 1) { - return true; - } else if (visible.last?.id === this.pagesCount) { - return false; - } - switch (this._scrollMode) { - case ScrollMode.PAGE: - return this.#scrollModePageState.scrollDown; - case ScrollMode.HORIZONTAL: - return this.scroll.right; - } - return this.scroll.down; - } - forceRendering(currentlyVisiblePages) { - const visiblePages = currentlyVisiblePages || this._getVisiblePages(); - const scrollAhead = this.#getScrollAhead(visiblePages); - const preRenderExtra = this._spreadMode !== SpreadMode.NONE && this._scrollMode !== ScrollMode.HORIZONTAL; - const pageView = this.renderingQueue.getHighestPriority(visiblePages, this._pages, scrollAhead, preRenderExtra); - if (pageView) { - this.#ensurePdfPageLoaded(pageView).then(() => { - this.renderingQueue.renderView(pageView); - }); - return true; - } - return false; - } - get hasEqualPageSizes() { - const firstPageView = this._pages[0]; - for (let i = 1, ii = this._pages.length; i < ii; ++i) { - const pageView = this._pages[i]; - if (pageView.width !== firstPageView.width || pageView.height !== firstPageView.height) { - return false; - } - } - return true; - } - getPagesOverview() { - let initialOrientation; - return this._pages.map(pageView => { - const viewport = pageView.pdfPage.getViewport({ - scale: 1 - }); - const orientation = isPortraitOrientation(viewport); - if (initialOrientation === undefined) { - initialOrientation = orientation; - } else if (this.enablePrintAutoRotate && orientation !== initialOrientation) { - return { - width: viewport.height, - height: viewport.width, - rotation: (viewport.rotation - 90) % 360 - }; - } - return { - width: viewport.width, - height: viewport.height, - rotation: viewport.rotation - }; - }); - } - get optionalContentConfigPromise() { - if (!this.pdfDocument) { - return Promise.resolve(null); - } - if (!this._optionalContentConfigPromise) { - console.error("optionalContentConfigPromise: Not initialized yet."); - return this.pdfDocument.getOptionalContentConfig({ - intent: "display" - }); - } - return this._optionalContentConfigPromise; - } - set optionalContentConfigPromise(promise) { - if (!(promise instanceof Promise)) { - throw new Error(`Invalid optionalContentConfigPromise: ${promise}`); - } - if (!this.pdfDocument) { - return; - } - if (!this._optionalContentConfigPromise) { - return; - } - this._optionalContentConfigPromise = promise; - this.refresh(false, { - optionalContentConfigPromise: promise - }); - this.eventBus.dispatch("optionalcontentconfigchanged", { - source: this, - promise - }); - } - get scrollMode() { - return this._scrollMode; - } - set scrollMode(mode) { - if (this._scrollMode === mode) { - return; - } - if (!isValidScrollMode(mode)) { - throw new Error(`Invalid scroll mode: ${mode}`); - } - if (this.pagesCount > PagesCountLimit.FORCE_SCROLL_MODE_PAGE) { - return; - } - this._previousScrollMode = this._scrollMode; - this._scrollMode = mode; - this.eventBus.dispatch("scrollmodechanged", { - source: this, - mode - }); - this._updateScrollMode(this._currentPageNumber); - } - _updateScrollMode(pageNumber = null) { - const scrollMode = this._scrollMode, - viewer = this.viewer; - viewer.classList.toggle("scrollHorizontal", scrollMode === ScrollMode.HORIZONTAL); - viewer.classList.toggle("scrollWrapped", scrollMode === ScrollMode.WRAPPED); - if (!this.pdfDocument || !pageNumber) { - return; - } - if (scrollMode === ScrollMode.PAGE) { - this.#ensurePageViewVisible(); - } else if (this._previousScrollMode === ScrollMode.PAGE) { - this._updateSpreadMode(); - } - if (this._currentScaleValue && isNaN(this._currentScaleValue)) { - this.#setScale(this._currentScaleValue, { - noScroll: true - }); - } - this._setCurrentPageNumber(pageNumber, true); - this.update(); - } - get spreadMode() { - return this._spreadMode; - } - set spreadMode(mode) { - if (this._spreadMode === mode) { - return; - } - if (!isValidSpreadMode(mode)) { - throw new Error(`Invalid spread mode: ${mode}`); - } - this._spreadMode = mode; - this.eventBus.dispatch("spreadmodechanged", { - source: this, - mode - }); - this._updateSpreadMode(this._currentPageNumber); - } - _updateSpreadMode(pageNumber = null) { - if (!this.pdfDocument) { - return; - } - const viewer = this.viewer, - pages = this._pages; - if (this._scrollMode === ScrollMode.PAGE) { - this.#ensurePageViewVisible(); - } else { - viewer.textContent = ""; - if (this._spreadMode === SpreadMode.NONE) { - for (const pageView of this._pages) { - viewer.append(pageView.div); - } - } else { - const parity = this._spreadMode - 1; - let spread = null; - for (let i = 0, ii = pages.length; i < ii; ++i) { - if (spread === null) { - spread = document.createElement("div"); - spread.className = "spread"; - viewer.append(spread); - } else if (i % 2 === parity) { - spread = spread.cloneNode(false); - viewer.append(spread); - } - spread.append(pages[i].div); - } - } - } - if (!pageNumber) { - return; - } - if (this._currentScaleValue && isNaN(this._currentScaleValue)) { - this.#setScale(this._currentScaleValue, { - noScroll: true - }); - } - this._setCurrentPageNumber(pageNumber, true); - this.update(); - } - _getPageAdvance(currentPageNumber, previous = false) { - switch (this._scrollMode) { - case ScrollMode.WRAPPED: - { - const { - views - } = this._getVisiblePages(), - pageLayout = new Map(); - for (const { - id, - y, - percent, - widthPercent - } of views) { - if (percent === 0 || widthPercent < 100) { - continue; - } - let yArray = pageLayout.get(y); - if (!yArray) { - pageLayout.set(y, yArray ||= []); - } - yArray.push(id); - } - for (const yArray of pageLayout.values()) { - const currentIndex = yArray.indexOf(currentPageNumber); - if (currentIndex === -1) { - continue; - } - const numPages = yArray.length; - if (numPages === 1) { - break; - } - if (previous) { - for (let i = currentIndex - 1, ii = 0; i >= ii; i--) { - const currentId = yArray[i], - expectedId = yArray[i + 1] - 1; - if (currentId < expectedId) { - return currentPageNumber - expectedId; - } - } - } else { - for (let i = currentIndex + 1, ii = numPages; i < ii; i++) { - const currentId = yArray[i], - expectedId = yArray[i - 1] + 1; - if (currentId > expectedId) { - return expectedId - currentPageNumber; - } - } - } - if (previous) { - const firstId = yArray[0]; - if (firstId < currentPageNumber) { - return currentPageNumber - firstId + 1; - } - } else { - const lastId = yArray[numPages - 1]; - if (lastId > currentPageNumber) { - return lastId - currentPageNumber + 1; - } - } - break; - } - break; - } - case ScrollMode.HORIZONTAL: - { - break; - } - case ScrollMode.PAGE: - case ScrollMode.VERTICAL: - { - if (this._spreadMode === SpreadMode.NONE) { - break; - } - const parity = this._spreadMode - 1; - if (previous && currentPageNumber % 2 !== parity) { - break; - } else if (!previous && currentPageNumber % 2 === parity) { - break; - } - const { - views - } = this._getVisiblePages(), - expectedId = previous ? currentPageNumber - 1 : currentPageNumber + 1; - for (const { - id, - percent, - widthPercent - } of views) { - if (id !== expectedId) { - continue; - } - if (percent > 0 && widthPercent === 100) { - return 2; - } - break; - } - break; - } - } - return 1; - } - nextPage() { - const currentPageNumber = this._currentPageNumber, - pagesCount = this.pagesCount; - if (currentPageNumber >= pagesCount) { - return false; - } - const advance = this._getPageAdvance(currentPageNumber, false) || 1; - this.currentPageNumber = Math.min(currentPageNumber + advance, pagesCount); - return true; - } - previousPage() { - const currentPageNumber = this._currentPageNumber; - if (currentPageNumber <= 1) { - return false; - } - const advance = this._getPageAdvance(currentPageNumber, true) || 1; - this.currentPageNumber = Math.max(currentPageNumber - advance, 1); - return true; - } - updateScale({ - drawingDelay, - scaleFactor = null, - steps = null, - origin - }) { - if (steps === null && scaleFactor === null) { - throw new Error("Invalid updateScale options: either `steps` or `scaleFactor` must be provided."); - } - if (!this.pdfDocument) { - return; - } - let newScale = this._currentScale; - if (scaleFactor > 0 && scaleFactor !== 1) { - newScale = Math.round(newScale * scaleFactor * 100) / 100; - } else if (steps) { - const delta = steps > 0 ? DEFAULT_SCALE_DELTA : 1 / DEFAULT_SCALE_DELTA; - const round = steps > 0 ? Math.ceil : Math.floor; - steps = Math.abs(steps); - do { - newScale = round((newScale * delta).toFixed(2) * 10) / 10; - } while (--steps > 0); - } - newScale = Math.max(MIN_SCALE, Math.min(MAX_SCALE, newScale)); - this.#setScale(newScale, { - noScroll: false, - drawingDelay, - origin - }); - } - increaseScale(options = {}) { - this.updateScale({ - ...options, - steps: options.steps ?? 1 - }); - } - decreaseScale(options = {}) { - this.updateScale({ - ...options, - steps: -(options.steps ?? 1) - }); - } - #updateContainerHeightCss(height = this.container.clientHeight) { - if (height !== this.#previousContainerHeight) { - this.#previousContainerHeight = height; - docStyle.setProperty("--viewer-container-height", `${height}px`); - } - } - #resizeObserverCallback(entries) { - for (const entry of entries) { - if (entry.target === this.container) { - this.#updateContainerHeightCss(Math.floor(entry.borderBoxSize[0].blockSize)); - this.#containerTopLeft = null; - break; - } - } - } - get containerTopLeft() { - return this.#containerTopLeft ||= [this.container.offsetTop, this.container.offsetLeft]; - } - #cleanupSwitchAnnotationEditorMode() { - this.#switchAnnotationEditorModeAC?.abort(); - this.#switchAnnotationEditorModeAC = null; - if (this.#switchAnnotationEditorModeTimeoutId !== null) { - clearTimeout(this.#switchAnnotationEditorModeTimeoutId); - this.#switchAnnotationEditorModeTimeoutId = null; - } - } - get annotationEditorMode() { - return this.#annotationEditorUIManager ? this.#annotationEditorMode : AnnotationEditorType.DISABLE; - } - set annotationEditorMode({ - mode, - editId = null, - isFromKeyboard = false - }) { - if (!this.#annotationEditorUIManager) { - throw new Error(`The AnnotationEditor is not enabled.`); - } - if (this.#annotationEditorMode === mode) { - return; - } - if (!isValidAnnotationEditorMode(mode)) { - throw new Error(`Invalid AnnotationEditor mode: ${mode}`); - } - if (!this.pdfDocument) { - return; - } - if (mode === AnnotationEditorType.STAMP) { - this.#mlManager?.loadModel("altText"); - } - const { - eventBus - } = this; - const updater = () => { - this.#cleanupSwitchAnnotationEditorMode(); - this.#annotationEditorMode = mode; - this.#annotationEditorUIManager.updateMode(mode, editId, isFromKeyboard); - eventBus.dispatch("annotationeditormodechanged", { - source: this, - mode - }); - }; - if (mode === AnnotationEditorType.NONE || this.#annotationEditorMode === AnnotationEditorType.NONE) { - const isEditing = mode !== AnnotationEditorType.NONE; - if (!isEditing) { - this.pdfDocument.annotationStorage.resetModifiedIds(); - } - for (const pageView of this._pages) { - pageView.toggleEditingMode(isEditing); - } - const idsToRefresh = this.#switchToEditAnnotationMode(); - if (isEditing && idsToRefresh) { - this.#cleanupSwitchAnnotationEditorMode(); - this.#switchAnnotationEditorModeAC = new AbortController(); - const signal = AbortSignal.any([this.#eventAbortController.signal, this.#switchAnnotationEditorModeAC.signal]); - eventBus._on("pagerendered", ({ - pageNumber - }) => { - idsToRefresh.delete(pageNumber); - if (idsToRefresh.size === 0) { - this.#switchAnnotationEditorModeTimeoutId = setTimeout(updater, 0); - } - }, { - signal - }); - return; - } - } - updater(); - } - refresh(noUpdate = false, updateArgs = Object.create(null)) { - if (!this.pdfDocument) { - return; - } - for (const pageView of this._pages) { - pageView.update(updateArgs); - } - if (this.#scaleTimeoutId !== null) { - clearTimeout(this.#scaleTimeoutId); - this.#scaleTimeoutId = null; - } - if (!noUpdate) { - this.update(); - } - } -} - -;// ./web/pdf_single_page_viewer.js - - -class PDFSinglePageViewer extends PDFViewer { - _resetView() { - super._resetView(); - this._scrollMode = ScrollMode.PAGE; - this._spreadMode = SpreadMode.NONE; - } - set scrollMode(mode) {} - _updateScrollMode() {} - set spreadMode(mode) {} - _updateSpreadMode() {} -} - -;// ./web/pdf_viewer.component.js - - - - - - - - - - - - - - - -const pdfjsVersion = "4.10.38"; -const pdfjsBuild = "f9bea397f"; - -var __webpack_exports__AnnotationLayerBuilder = __webpack_exports__.AnnotationLayerBuilder; -var __webpack_exports__DownloadManager = __webpack_exports__.DownloadManager; -var __webpack_exports__EventBus = __webpack_exports__.EventBus; -var __webpack_exports__FindState = __webpack_exports__.FindState; -var __webpack_exports__GenericL10n = __webpack_exports__.GenericL10n; -var __webpack_exports__LinkTarget = __webpack_exports__.LinkTarget; -var __webpack_exports__PDFFindController = __webpack_exports__.PDFFindController; -var __webpack_exports__PDFHistory = __webpack_exports__.PDFHistory; -var __webpack_exports__PDFLinkService = __webpack_exports__.PDFLinkService; -var __webpack_exports__PDFPageView = __webpack_exports__.PDFPageView; -var __webpack_exports__PDFScriptingManager = __webpack_exports__.PDFScriptingManager; -var __webpack_exports__PDFSinglePageViewer = __webpack_exports__.PDFSinglePageViewer; -var __webpack_exports__PDFViewer = __webpack_exports__.PDFViewer; -var __webpack_exports__ProgressBar = __webpack_exports__.ProgressBar; -var __webpack_exports__RenderingStates = __webpack_exports__.RenderingStates; -var __webpack_exports__ScrollMode = __webpack_exports__.ScrollMode; -var __webpack_exports__SimpleLinkService = __webpack_exports__.SimpleLinkService; -var __webpack_exports__SpreadMode = __webpack_exports__.SpreadMode; -var __webpack_exports__StructTreeLayerBuilder = __webpack_exports__.StructTreeLayerBuilder; -var __webpack_exports__TextLayerBuilder = __webpack_exports__.TextLayerBuilder; -var __webpack_exports__XfaLayerBuilder = __webpack_exports__.XfaLayerBuilder; -var __webpack_exports__parseQueryString = __webpack_exports__.parseQueryString; -export { __webpack_exports__AnnotationLayerBuilder as AnnotationLayerBuilder, __webpack_exports__DownloadManager as DownloadManager, __webpack_exports__EventBus as EventBus, __webpack_exports__FindState as FindState, __webpack_exports__GenericL10n as GenericL10n, __webpack_exports__LinkTarget as LinkTarget, __webpack_exports__PDFFindController as PDFFindController, __webpack_exports__PDFHistory as PDFHistory, __webpack_exports__PDFLinkService as PDFLinkService, __webpack_exports__PDFPageView as PDFPageView, __webpack_exports__PDFScriptingManager as PDFScriptingManager, __webpack_exports__PDFSinglePageViewer as PDFSinglePageViewer, __webpack_exports__PDFViewer as PDFViewer, __webpack_exports__ProgressBar as ProgressBar, __webpack_exports__RenderingStates as RenderingStates, __webpack_exports__ScrollMode as ScrollMode, __webpack_exports__SimpleLinkService as SimpleLinkService, __webpack_exports__SpreadMode as SpreadMode, __webpack_exports__StructTreeLayerBuilder as StructTreeLayerBuilder, __webpack_exports__TextLayerBuilder as TextLayerBuilder, __webpack_exports__XfaLayerBuilder as XfaLayerBuilder, __webpack_exports__parseQueryString as parseQueryString }; - -//# sourceMappingURL=pdf_viewer.mjs.map \ No newline at end of file diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/tailwindcss/README.md b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/tailwindcss/README.md deleted file mode 100644 index 69fb53bf322..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/tailwindcss/README.md +++ /dev/null @@ -1,7 +0,0 @@ -tailwindcss version 4.0.3 -https://github.com/tailwindlabs/tailwindcss -License: MIT - -This template uses only `preflight.css`, the CSS reset stylesheet from Tailwind. For simplicity, this template doesn't use a complete deployment of Tailwind. If you want to use the full Tailwind library, remove `preflight.css` and reference the full version of Tailwind. - -To update, replace the `preflight.css` file with the one in an updated build from https://www.npmjs.com/package/tailwindcss diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/tailwindcss/dist/preflight.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/tailwindcss/dist/preflight.css deleted file mode 100644 index 178c881dd23..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/wwwroot/lib/tailwindcss/dist/preflight.css +++ /dev/null @@ -1,383 +0,0 @@ -/* - 1. Prevent padding and border from affecting element width. (https://github.com/mozdevs/cssremedy/issues/4) - 2. Remove default margins and padding - 3. Reset all borders. -*/ - -*, -::after, -::before, -::backdrop, -::file-selector-button { - box-sizing: border-box; /* 1 */ - margin: 0; /* 2 */ - padding: 0; /* 2 */ - border: 0 solid; /* 3 */ -} - -/* - 1. Use a consistent sensible line-height in all browsers. - 2. Prevent adjustments of font size after orientation changes in iOS. - 3. Use a more readable tab size. - 4. Use the user's configured `sans` font-family by default. - 5. Use the user's configured `sans` font-feature-settings by default. - 6. Use the user's configured `sans` font-variation-settings by default. - 7. Disable tap highlights on iOS. -*/ - -html, -:host { - line-height: 1.5; /* 1 */ - -webkit-text-size-adjust: 100%; /* 2 */ - tab-size: 4; /* 3 */ - font-family: var( - --default-font-family, - ui-sans-serif, - system-ui, - sans-serif, - 'Apple Color Emoji', - 'Segoe UI Emoji', - 'Segoe UI Symbol', - 'Noto Color Emoji' - ); /* 4 */ - font-feature-settings: var(--default-font-feature-settings, normal); /* 5 */ - font-variation-settings: var(--default-font-variation-settings, normal); /* 6 */ - -webkit-tap-highlight-color: transparent; /* 7 */ -} - -/* - Inherit line-height from `html` so users can set them as a class directly on the `html` element. -*/ - -body { - line-height: inherit; -} - -/* - 1. Add the correct height in Firefox. - 2. Correct the inheritance of border color in Firefox. (https://bugzilla.mozilla.org/show_bug.cgi?id=190655) - 3. Reset the default border style to a 1px solid border. -*/ - -hr { - height: 0; /* 1 */ - color: inherit; /* 2 */ - border-top-width: 1px; /* 3 */ -} - -/* - Add the correct text decoration in Chrome, Edge, and Safari. -*/ - -abbr:where([title]) { - -webkit-text-decoration: underline dotted; - text-decoration: underline dotted; -} - -/* - Remove the default font size and weight for headings. -*/ - -h1, -h2, -h3, -h4, -h5, -h6 { - font-size: inherit; - font-weight: inherit; -} - -/* - Reset links to optimize for opt-in styling instead of opt-out. -*/ - -a { - color: inherit; - -webkit-text-decoration: inherit; - text-decoration: inherit; -} - -/* - Add the correct font weight in Edge and Safari. -*/ - -b, -strong { - font-weight: bolder; -} - -/* - 1. Use the user's configured `mono` font-family by default. - 2. Use the user's configured `mono` font-feature-settings by default. - 3. Use the user's configured `mono` font-variation-settings by default. - 4. Correct the odd `em` font sizing in all browsers. -*/ - -code, -kbd, -samp, -pre { - font-family: var( - --default-mono-font-family, - ui-monospace, - SFMono-Regular, - Menlo, - Monaco, - Consolas, - 'Liberation Mono', - 'Courier New', - monospace - ); /* 4 */ - font-feature-settings: var(--default-mono-font-feature-settings, normal); /* 5 */ - font-variation-settings: var(--default-mono-font-variation-settings, normal); /* 6 */ - font-size: 1em; /* 4 */ -} - -/* - Add the correct font size in all browsers. -*/ - -small { - font-size: 80%; -} - -/* - Prevent `sub` and `sup` elements from affecting the line height in all browsers. -*/ - -sub, -sup { - font-size: 75%; - line-height: 0; - position: relative; - vertical-align: baseline; -} - -sub { - bottom: -0.25em; -} - -sup { - top: -0.5em; -} - -/* - 1. Remove text indentation from table contents in Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=999088, https://bugs.webkit.org/show_bug.cgi?id=201297) - 2. Correct table border color inheritance in all Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=935729, https://bugs.webkit.org/show_bug.cgi?id=195016) - 3. Remove gaps between table borders by default. -*/ - -table { - text-indent: 0; /* 1 */ - border-color: inherit; /* 2 */ - border-collapse: collapse; /* 3 */ -} - -/* - Use the modern Firefox focus style for all focusable elements. -*/ - -:-moz-focusring { - outline: auto; -} - -/* - Add the correct vertical alignment in Chrome and Firefox. -*/ - -progress { - vertical-align: baseline; -} - -/* - Add the correct display in Chrome and Safari. -*/ - -summary { - display: list-item; -} - -/* - Make lists unstyled by default. -*/ - -ol, -ul, -menu { - list-style: none; -} - -/* - 1. Make replaced elements `display: block` by default. (https://github.com/mozdevs/cssremedy/issues/14) - 2. Add `vertical-align: middle` to align replaced elements more sensibly by default. (https://github.com/jensimmons/cssremedy/issues/14#issuecomment-634934210) - This can trigger a poorly considered lint error in some tools but is included by design. -*/ - -img, -svg, -video, -canvas, -audio, -iframe, -embed, -object { - display: block; /* 1 */ - vertical-align: middle; /* 2 */ -} - -/* - Constrain images and videos to the parent width and preserve their intrinsic aspect ratio. (https://github.com/mozdevs/cssremedy/issues/14) -*/ - -img, -video { - max-width: 100%; - height: auto; -} - -/* - 1. Inherit font styles in all browsers. - 2. Remove border radius in all browsers. - 3. Remove background color in all browsers. - 4. Ensure consistent opacity for disabled states in all browsers. -*/ - -button, -input, -select, -optgroup, -textarea, -::file-selector-button { - font: inherit; /* 1 */ - font-feature-settings: inherit; /* 1 */ - font-variation-settings: inherit; /* 1 */ - letter-spacing: inherit; /* 1 */ - color: inherit; /* 1 */ - border-radius: 0; /* 2 */ - background-color: transparent; /* 3 */ - opacity: 1; /* 4 */ -} - -/* - Restore default font weight. -*/ - -:where(select:is([multiple], [size])) optgroup { - font-weight: bolder; -} - -/* - Restore indentation. -*/ - -:where(select:is([multiple], [size])) optgroup option { - padding-inline-start: 20px; -} - -/* - Restore space after button. -*/ - -::file-selector-button { - margin-inline-end: 4px; -} - -/* - 1. Reset the default placeholder opacity in Firefox. (https://github.com/tailwindlabs/tailwindcss/issues/3300) - 2. Set the default placeholder color to a semi-transparent version of the current text color. -*/ - -::placeholder { - opacity: 1; /* 1 */ - color: color-mix(in oklab, currentColor 50%, transparent); /* 2 */ -} - -/* - Prevent resizing textareas horizontally by default. -*/ - -textarea { - resize: vertical; -} - -/* - Remove the inner padding in Chrome and Safari on macOS. -*/ - -::-webkit-search-decoration { - -webkit-appearance: none; -} - -/* - 1. Ensure date/time inputs have the same height when empty in iOS Safari. - 2. Ensure text alignment can be changed on date/time inputs in iOS Safari. -*/ - -::-webkit-date-and-time-value { - min-height: 1lh; /* 1 */ - text-align: inherit; /* 2 */ -} - -/* - Prevent height from changing on date/time inputs in macOS Safari when the input is set to `display: block`. -*/ - -::-webkit-datetime-edit { - display: inline-flex; -} - -/* - Remove excess padding from pseudo-elements in date/time inputs to ensure consistent height across browsers. -*/ - -::-webkit-datetime-edit-fields-wrapper { - padding: 0; -} - -::-webkit-datetime-edit, -::-webkit-datetime-edit-year-field, -::-webkit-datetime-edit-month-field, -::-webkit-datetime-edit-day-field, -::-webkit-datetime-edit-hour-field, -::-webkit-datetime-edit-minute-field, -::-webkit-datetime-edit-second-field, -::-webkit-datetime-edit-millisecond-field, -::-webkit-datetime-edit-meridiem-field { - padding-block: 0; -} - -/* - Remove the additional `:invalid` styles in Firefox. (https://github.com/mozilla/gecko-dev/blob/2f9eacd9d3d995c937b4251a5557d95d494c9be1/layout/style/res/forms.css#L728-L737) -*/ - -:-moz-ui-invalid { - box-shadow: none; -} - -/* - Correct the inability to style the border radius in iOS Safari. -*/ - -button, -input:where([type='button'], [type='reset'], [type='submit']), -::file-selector-button { - appearance: button; -} - -/* - Correct the cursor style of increment and decrement buttons in Safari. -*/ - -::-webkit-inner-spin-button, -::-webkit-outer-spin-button { - height: auto; -} - -/* - Make elements with the HTML hidden attribute stay hidden by default. -*/ - -[hidden]:where(:not([hidden='until-found'])) { - display: none !important; -} diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/Data/Example_Emergency_Survival_Kit.pdf b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/Data/Example_Emergency_Survival_Kit.pdf deleted file mode 100644 index 94625f0e0e0617c1324cf5243b06d0e8a2da6177..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 153539 zcmdSC1yohr8aBM?5a|YC(;b^`knZlTO-OeONJ|MQAt`Cl-61W~og#uD4GM_Vzd?`U zIh;H0_nkAof7~&2Y!>^S^Q}3b`K~$FdZ1Dkmt+Dlb0AZVZhU%=3<9zO9Zc^b3ka~N zTf5qVfwU5KU}sCPy_pwK&CS`}+TFw!C}-_Ths+}83^s9fa0b#UICxvz+M2L%GP45p zX|=5F%^f^kfQsrs5Gyk)KM?W@E)IU6Cl`l49q_KBqb*nqYzpaug_E6|nVk#LL{3^= zL7ow4Yi$DtN`cL693X-P$HvOW!O8{V1%W_Z?3@g&tTd2+5IF@0 z^ZzU&B!moxI0Xp{`>*hrnE*k^ETRfP7DWeVI}_VqLR`OuB&}^-A*QiN+Cpp)2b(#V zgOOR}!S#1MEt zph%PqZtFr!hHGMqyk9i=ts~7*#%;pBT~_>4V(QFkj^(#uF#}_0?^@WeQ2Cy!(qLoibpY)-mdT5&(<(|eM(b*q!b^7Zq2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ZteVOx33 zjQ^i7DCVmO0QR5df#K-R3S;~~6I7t&|1J-?`h2eKIut)%s6pEpEqy`pcHi+57=RRP zZ8(0-OL8bh_Dn>kCEmL>RB@X^NLjA(p{{W!zUzMTPO@kIoR<5M`84LJVbeNU0P1zq z4^O(t7vkAuH@G=26!_ToGp8Xef3sV;1$v=+Rg=q 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - return apply(func, thisArg, args); - }; -} -/** - * Creates a new function that constructs an instance of the given constructor function with the provided arguments. - * - * @param func - The constructor function to be wrapped and called. - * @returns A new function that constructs an instance of the given constructor function with the provided arguments. - */ -function unconstruct(func) { - return function () { - for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - args[_key2] = arguments[_key2]; - } - return construct(func, args); - }; -} -/** - * Add properties to a lookup table - * - * @param set - The set to which elements will be added. - * @param array - The array containing elements to be added to the set. - * @param transformCaseFunc - An optional function to transform the case of each element before adding to the set. - * @returns The modified set with added elements. - */ -function addToSet(set, array) { - let transformCaseFunc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : stringToLowerCase; - if (setPrototypeOf) { - // Make 'in' and truthy checks like Boolean(set.constructor) - // independent of any properties defined on Object.prototype. - // Prevent prototype setters from intercepting set as a this value. - setPrototypeOf(set, null); - } - let l = array.length; - while (l--) { - let element = array[l]; - if (typeof element === 'string') { - const lcElement = transformCaseFunc(element); - if (lcElement !== element) { - // Config presets (e.g. tags.js, attrs.js) are immutable. - if (!isFrozen(array)) { - array[l] = lcElement; - } - element = lcElement; - } - } - set[element] = true; - } - return set; -} -/** - * Clean up an array to harden against CSPP - * - * @param array - The array to be cleaned. - * @returns The cleaned version of the array - */ -function cleanArray(array) { - for (let index = 0; index < array.length; index++) { - const isPropertyExist = objectHasOwnProperty(array, index); - if (!isPropertyExist) { - array[index] = null; - } - } - return array; -} -/** - * Shallow clone an object - * - * @param object - The object to be cloned. - * @returns A new object that copies the original. - */ -function clone(object) { - const newObject = create(null); - for (const [property, value] of entries(object)) { - const isPropertyExist = objectHasOwnProperty(object, property); - if (isPropertyExist) { - if (Array.isArray(value)) { - newObject[property] = cleanArray(value); - } else if (value && typeof value === 'object' && value.constructor === Object) { - newObject[property] = clone(value); - } else { - newObject[property] = value; - } - } - } - return newObject; -} -/** - * This method automatically checks if the prop is function or getter and behaves accordingly. - * - * @param object - The object to look up the getter function in its prototype chain. - * @param prop - The property name for which to find the getter function. - * @returns The getter function found in the prototype chain or a fallback function. - */ -function lookupGetter(object, prop) { - while (object !== null) { - const desc = getOwnPropertyDescriptor(object, prop); - if (desc) { - if (desc.get) { - return unapply(desc.get); - } - if (typeof desc.value === 'function') { - return unapply(desc.value); - } - } - object = getPrototypeOf(object); - } - function fallbackValue() { - return null; - } - return fallbackValue; -} - -const html$1 = freeze(['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'content', 'data', 'datalist', 'dd', 'decorator', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meter', 'nav', 'nobr', 'ol', 'optgroup', 'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'section', 'select', 'shadow', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr']); -const svg$1 = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']); -const svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feDropShadow', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']); -// List of SVG elements that are disallowed by default. -// We still need to know them so that we can do namespace -// checks properly in case one wants to add them to -// allow-list. -const svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignobject', 'hatch', 'hatchpath', 'mesh', 'meshgradient', 'meshpatch', 'meshrow', 'missing-glyph', 'script', 'set', 'solidcolor', 'unknown', 'use']); -const mathMl$1 = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover', 'mprescripts']); -// Similarly to SVG, we want to know all MathML elements, -// even those that we disallow by default. -const mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']); -const text = freeze(['#text']); - -const html = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'nonce', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'pattern', 'placeholder', 'playsinline', 'popover', 'popovertarget', 'popovertargetaction', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'wrap', 'xmlns', 'slot']); -const svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'amplitude', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dur', 'edgemode', 'elevation', 'end', 'exponent', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'intercept', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'slope', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'tablevalues', 'targetx', 'targety', 'transform', 'transform-origin', 'text-anchor', 'text-decoration', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']); -const mathMl = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnsalign', 'columnlines', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lspace', 'lquote', 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset', 'width', 'xmlns']); -const xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']); - -// eslint-disable-next-line unicorn/better-regex -const MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode -const ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm); -const TMPLIT_EXPR = seal(/\$\{[\w\W]*/gm); // eslint-disable-line unicorn/better-regex -const DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]+$/); // eslint-disable-line no-useless-escape -const ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape -const IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i // eslint-disable-line no-useless-escape -); -const IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i); -const ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex -); -const DOCTYPE_NAME = seal(/^html$/i); -const CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i); - -var EXPRESSIONS = /*#__PURE__*/Object.freeze({ - __proto__: null, - ARIA_ATTR: ARIA_ATTR, - ATTR_WHITESPACE: ATTR_WHITESPACE, - CUSTOM_ELEMENT: CUSTOM_ELEMENT, - DATA_ATTR: DATA_ATTR, - DOCTYPE_NAME: DOCTYPE_NAME, - ERB_EXPR: ERB_EXPR, - IS_ALLOWED_URI: IS_ALLOWED_URI, - IS_SCRIPT_OR_DATA: IS_SCRIPT_OR_DATA, - MUSTACHE_EXPR: MUSTACHE_EXPR, - TMPLIT_EXPR: TMPLIT_EXPR -}); - -/* eslint-disable @typescript-eslint/indent */ -// https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType -const NODE_TYPE = { - element: 1, - attribute: 2, - text: 3, - cdataSection: 4, - entityReference: 5, - // Deprecated - entityNode: 6, - // Deprecated - progressingInstruction: 7, - comment: 8, - document: 9, - documentType: 10, - documentFragment: 11, - notation: 12 // Deprecated -}; -const getGlobal = function getGlobal() { - return typeof window === 'undefined' ? null : window; -}; -/** - * Creates a no-op policy for internal use only. - * Don't export this function outside this module! - * @param trustedTypes The policy factory. - * @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix). - * @return The policy created (or null, if Trusted Types - * are not supported or creating the policy failed). - */ -const _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, purifyHostElement) { - if (typeof trustedTypes !== 'object' || typeof trustedTypes.createPolicy !== 'function') { - return null; - } - // Allow the callers to control the unique policy name - // by adding a data-tt-policy-suffix to the script element with the DOMPurify. - // Policy creation with duplicate names throws in Trusted Types. - let suffix = null; - const ATTR_NAME = 'data-tt-policy-suffix'; - if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) { - suffix = purifyHostElement.getAttribute(ATTR_NAME); - } - const policyName = 'dompurify' + (suffix ? '#' + suffix : ''); - try { - return trustedTypes.createPolicy(policyName, { - createHTML(html) { - return html; - }, - createScriptURL(scriptUrl) { - return scriptUrl; - } - }); - } catch (_) { - // Policy creation failed (most likely another DOMPurify script has - // already run). Skip creating the policy, as this will only cause errors - // if TT are enforced. - console.warn('TrustedTypes policy ' + policyName + ' could not be created.'); - return null; - } -}; -const _createHooksMap = function _createHooksMap() { - return { - afterSanitizeAttributes: [], - afterSanitizeElements: [], - afterSanitizeShadowDOM: [], - beforeSanitizeAttributes: [], - beforeSanitizeElements: [], - beforeSanitizeShadowDOM: [], - uponSanitizeAttribute: [], - uponSanitizeElement: [], - uponSanitizeShadowNode: [] - }; -}; -function createDOMPurify() { - let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal(); - const DOMPurify = root => createDOMPurify(root); - DOMPurify.version = '3.2.4'; - DOMPurify.removed = []; - if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) { - // Not running in a browser, provide a factory function - // so that you can pass your own Window - DOMPurify.isSupported = false; - return DOMPurify; - } - let { - document - } = window; - const originalDocument = document; - const currentScript = originalDocument.currentScript; - const { - DocumentFragment, - HTMLTemplateElement, - Node, - Element, - NodeFilter, - NamedNodeMap = window.NamedNodeMap || window.MozNamedAttrMap, - HTMLFormElement, - DOMParser, - trustedTypes - } = window; - const ElementPrototype = Element.prototype; - const cloneNode = lookupGetter(ElementPrototype, 'cloneNode'); - const remove = lookupGetter(ElementPrototype, 'remove'); - const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling'); - const getChildNodes = lookupGetter(ElementPrototype, 'childNodes'); - const getParentNode = lookupGetter(ElementPrototype, 'parentNode'); - // As per issue #47, the web-components registry is inherited by a - // new document created via createHTMLDocument. As per the spec - // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries) - // a new empty registry is used when creating a template contents owner - // document, so we use that as our parent document to ensure nothing - // is inherited. - if (typeof HTMLTemplateElement === 'function') { - const template = document.createElement('template'); - if (template.content && template.content.ownerDocument) { - document = template.content.ownerDocument; - } - } - let trustedTypesPolicy; - let emptyHTML = ''; - const { - implementation, - createNodeIterator, - createDocumentFragment, - getElementsByTagName - } = document; - const { - importNode - } = originalDocument; - let hooks = _createHooksMap(); - /** - * Expose whether this browser supports running the full DOMPurify. - */ - DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined; - const { - MUSTACHE_EXPR, - ERB_EXPR, - TMPLIT_EXPR, - DATA_ATTR, - ARIA_ATTR, - IS_SCRIPT_OR_DATA, - ATTR_WHITESPACE, - CUSTOM_ELEMENT - } = EXPRESSIONS; - let { - IS_ALLOWED_URI: IS_ALLOWED_URI$1 - } = EXPRESSIONS; - /** - * We consider the elements and attributes below to be safe. Ideally - * don't add any new ones but feel free to remove unwanted ones. - */ - /* allowed element names */ - let ALLOWED_TAGS = null; - const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]); - /* Allowed attribute names */ - let ALLOWED_ATTR = null; - const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]); - /* - * Configure how DOMPurify should handle custom elements and their attributes as well as customized built-in elements. - * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements) - * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list) - * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`. - */ - let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, { - tagNameCheck: { - writable: true, - configurable: false, - enumerable: true, - value: null - }, - attributeNameCheck: { - writable: true, - configurable: false, - enumerable: true, - value: null - }, - allowCustomizedBuiltInElements: { - writable: true, - configurable: false, - enumerable: true, - value: false - } - })); - /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */ - let FORBID_TAGS = null; - /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */ - let FORBID_ATTR = null; - /* Decide if ARIA attributes are okay */ - let ALLOW_ARIA_ATTR = true; - /* Decide if custom data attributes are okay */ - let ALLOW_DATA_ATTR = true; - /* Decide if unknown protocols are okay */ - let ALLOW_UNKNOWN_PROTOCOLS = false; - /* Decide if self-closing tags in attributes are allowed. - * Usually removed due to a mXSS issue in jQuery 3.0 */ - let ALLOW_SELF_CLOSE_IN_ATTR = true; - /* Output should be safe for common template engines. - * This means, DOMPurify removes data attributes, mustaches and ERB - */ - let SAFE_FOR_TEMPLATES = false; - /* Output should be safe even for XML used within HTML and alike. - * This means, DOMPurify removes comments when containing risky content. - */ - let SAFE_FOR_XML = true; - /* Decide if document with ... should be returned */ - let WHOLE_DOCUMENT = false; - /* Track whether config is already set on this instance of DOMPurify. */ - let SET_CONFIG = false; - /* Decide if all elements (e.g. style, script) must be children of - * document.body. By default, browsers might move them to document.head */ - let FORCE_BODY = false; - /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html - * string (or a TrustedHTML object if Trusted Types are supported). - * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead - */ - let RETURN_DOM = false; - /* Decide if a DOM `DocumentFragment` should be returned, instead of a html - * string (or a TrustedHTML object if Trusted Types are supported) */ - let RETURN_DOM_FRAGMENT = false; - /* Try to return a Trusted Type object instead of a string, return a string in - * case Trusted Types are not supported */ - let RETURN_TRUSTED_TYPE = false; - /* Output should be free from DOM clobbering attacks? - * This sanitizes markups named with colliding, clobberable built-in DOM APIs. - */ - let SANITIZE_DOM = true; - /* Achieve full DOM Clobbering protection by isolating the namespace of named - * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules. - * - * HTML/DOM spec rules that enable DOM Clobbering: - * - Named Access on Window (§7.3.3) - * - DOM Tree Accessors (§3.1.5) - * - Form Element Parent-Child Relations (§4.10.3) - * - Iframe srcdoc / Nested WindowProxies (§4.8.5) - * - HTMLCollection (§4.2.10.2) - * - * Namespace isolation is implemented by prefixing `id` and `name` attributes - * with a constant string, i.e., `user-content-` - */ - let SANITIZE_NAMED_PROPS = false; - const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-'; - /* Keep element content when removing element? */ - let KEEP_CONTENT = true; - /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead - * of importing it into a new Document and returning a sanitized copy */ - let IN_PLACE = false; - /* Allow usage of profiles like html, svg and mathMl */ - let USE_PROFILES = {}; - /* Tags to ignore content of when KEEP_CONTENT is true */ - let FORBID_CONTENTS = null; - const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']); - /* Tags that are safe for data: URIs */ - let DATA_URI_TAGS = null; - const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']); - /* Attributes safe for values like "javascript:" */ - let URI_SAFE_ATTRIBUTES = null; - const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']); - const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML'; - const SVG_NAMESPACE = 'http://www.w3.org/2000/svg'; - const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml'; - /* Document namespace */ - let NAMESPACE = HTML_NAMESPACE; - let IS_EMPTY_INPUT = false; - /* Allowed XHTML+XML namespaces */ - let ALLOWED_NAMESPACES = null; - const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString); - let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']); - let HTML_INTEGRATION_POINTS = addToSet({}, ['annotation-xml']); - // Certain elements are allowed in both SVG and HTML - // namespace. We need to specify them explicitly - // so that they don't get erroneously deleted from - // HTML namespace. - const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']); - /* Parsing of strict XHTML documents */ - let PARSER_MEDIA_TYPE = null; - const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html']; - const DEFAULT_PARSER_MEDIA_TYPE = 'text/html'; - let transformCaseFunc = null; - /* Keep a reference to config to pass to hooks */ - let CONFIG = null; - /* Ideally, do not touch anything below this line */ - /* ______________________________________________ */ - const formElement = document.createElement('form'); - const isRegexOrFunction = function isRegexOrFunction(testValue) { - return testValue instanceof RegExp || testValue instanceof Function; - }; - /** - * _parseConfig - * - * @param cfg optional config literal - */ - // eslint-disable-next-line complexity - const _parseConfig = function _parseConfig() { - let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - if (CONFIG && CONFIG === cfg) { - return; - } - /* Shield configuration object from tampering */ - if (!cfg || typeof cfg !== 'object') { - cfg = {}; - } - /* Shield configuration object from prototype pollution */ - cfg = clone(cfg); - PARSER_MEDIA_TYPE = - // eslint-disable-next-line unicorn/prefer-includes - SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE; - // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is. - transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase; - /* Set configuration parameters */ - ALLOWED_TAGS = objectHasOwnProperty(cfg, 'ALLOWED_TAGS') ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS; - ALLOWED_ATTR = objectHasOwnProperty(cfg, 'ALLOWED_ATTR') ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR; - ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, 'ALLOWED_NAMESPACES') ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES; - URI_SAFE_ATTRIBUTES = objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR, transformCaseFunc) : DEFAULT_URI_SAFE_ATTRIBUTES; - DATA_URI_TAGS = objectHasOwnProperty(cfg, 'ADD_DATA_URI_TAGS') ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS, transformCaseFunc) : DEFAULT_DATA_URI_TAGS; - FORBID_CONTENTS = objectHasOwnProperty(cfg, 'FORBID_CONTENTS') ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS; - FORBID_TAGS = objectHasOwnProperty(cfg, 'FORBID_TAGS') ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : {}; - FORBID_ATTR = objectHasOwnProperty(cfg, 'FORBID_ATTR') ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : {}; - USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES : false; - ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true - ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true - ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false - ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true - SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false - SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true - WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false - RETURN_DOM = cfg.RETURN_DOM || false; // Default false - RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false - RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false - FORCE_BODY = cfg.FORCE_BODY || false; // Default false - SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true - SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false - KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true - IN_PLACE = cfg.IN_PLACE || false; // Default false - IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI; - NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE; - MATHML_TEXT_INTEGRATION_POINTS = cfg.MATHML_TEXT_INTEGRATION_POINTS || MATHML_TEXT_INTEGRATION_POINTS; - HTML_INTEGRATION_POINTS = cfg.HTML_INTEGRATION_POINTS || HTML_INTEGRATION_POINTS; - CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || {}; - if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) { - CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck; - } - if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) { - CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck; - } - if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === 'boolean') { - CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements; - } - if (SAFE_FOR_TEMPLATES) { - ALLOW_DATA_ATTR = false; - } - if (RETURN_DOM_FRAGMENT) { - RETURN_DOM = true; - } - /* Parse profile info */ - if (USE_PROFILES) { - ALLOWED_TAGS = addToSet({}, text); - ALLOWED_ATTR = []; - if (USE_PROFILES.html === true) { - addToSet(ALLOWED_TAGS, html$1); - addToSet(ALLOWED_ATTR, html); - } - if (USE_PROFILES.svg === true) { - addToSet(ALLOWED_TAGS, svg$1); - addToSet(ALLOWED_ATTR, svg); - addToSet(ALLOWED_ATTR, xml); - } - if (USE_PROFILES.svgFilters === true) { - addToSet(ALLOWED_TAGS, svgFilters); - addToSet(ALLOWED_ATTR, svg); - addToSet(ALLOWED_ATTR, xml); - } - if (USE_PROFILES.mathMl === true) { - addToSet(ALLOWED_TAGS, mathMl$1); - addToSet(ALLOWED_ATTR, mathMl); - addToSet(ALLOWED_ATTR, xml); - } - } - /* Merge configuration parameters */ - if (cfg.ADD_TAGS) { - if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) { - ALLOWED_TAGS = clone(ALLOWED_TAGS); - } - addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc); - } - if (cfg.ADD_ATTR) { - if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) { - ALLOWED_ATTR = clone(ALLOWED_ATTR); - } - addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc); - } - if (cfg.ADD_URI_SAFE_ATTR) { - addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc); - } - if (cfg.FORBID_CONTENTS) { - if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) { - FORBID_CONTENTS = clone(FORBID_CONTENTS); - } - addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc); - } - /* Add #text in case KEEP_CONTENT is set to true */ - if (KEEP_CONTENT) { - ALLOWED_TAGS['#text'] = true; - } - /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */ - if (WHOLE_DOCUMENT) { - addToSet(ALLOWED_TAGS, ['html', 'head', 'body']); - } - /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */ - if (ALLOWED_TAGS.table) { - addToSet(ALLOWED_TAGS, ['tbody']); - delete FORBID_TAGS.tbody; - } - if (cfg.TRUSTED_TYPES_POLICY) { - if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') { - throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.'); - } - if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') { - throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.'); - } - // Overwrite existing TrustedTypes policy. - trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY; - // Sign local variables required by `sanitize`. - emptyHTML = trustedTypesPolicy.createHTML(''); - } else { - // Uninitialized policy, attempt to initialize the internal dompurify policy. - if (trustedTypesPolicy === undefined) { - trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript); - } - // If creating the internal policy succeeded sign internal variables. - if (trustedTypesPolicy !== null && typeof emptyHTML === 'string') { - emptyHTML = trustedTypesPolicy.createHTML(''); - } - } - // Prevent further manipulation of configuration. - // Not available in IE8, Safari 5, etc. - if (freeze) { - freeze(cfg); - } - CONFIG = cfg; - }; - /* Keep track of all possible SVG and MathML tags - * so that we can perform the namespace checks - * correctly. */ - const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]); - const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]); - /** - * @param element a DOM element whose namespace is being checked - * @returns Return false if the element has a - * namespace that a spec-compliant parser would never - * return. Return true otherwise. - */ - const _checkValidNamespace = function _checkValidNamespace(element) { - let parent = getParentNode(element); - // In JSDOM, if we're inside shadow DOM, then parentNode - // can be null. We just simulate parent in this case. - if (!parent || !parent.tagName) { - parent = { - namespaceURI: NAMESPACE, - tagName: 'template' - }; - } - const tagName = stringToLowerCase(element.tagName); - const parentTagName = stringToLowerCase(parent.tagName); - if (!ALLOWED_NAMESPACES[element.namespaceURI]) { - return false; - } - if (element.namespaceURI === SVG_NAMESPACE) { - // The only way to switch from HTML namespace to SVG - // is via . If it happens via any other tag, then - // it should be killed. - if (parent.namespaceURI === HTML_NAMESPACE) { - return tagName === 'svg'; - } - // The only way to switch from MathML to SVG is via` - // svg if parent is either or MathML - // text integration points. - if (parent.namespaceURI === MATHML_NAMESPACE) { - return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]); - } - // We only allow elements that are defined in SVG - // spec. All others are disallowed in SVG namespace. - return Boolean(ALL_SVG_TAGS[tagName]); - } - if (element.namespaceURI === MATHML_NAMESPACE) { - // The only way to switch from HTML namespace to MathML - // is via . If it happens via any other tag, then - // it should be killed. - if (parent.namespaceURI === HTML_NAMESPACE) { - return tagName === 'math'; - } - // The only way to switch from SVG to MathML is via - // and HTML integration points - if (parent.namespaceURI === SVG_NAMESPACE) { - return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName]; - } - // We only allow elements that are defined in MathML - // spec. All others are disallowed in MathML namespace. - return Boolean(ALL_MATHML_TAGS[tagName]); - } - if (element.namespaceURI === HTML_NAMESPACE) { - // The only way to switch from SVG to HTML is via - // HTML integration points, and from MathML to HTML - // is via MathML text integration points - if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) { - return false; - } - if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) { - return false; - } - // We disallow tags that are specific for MathML - // or SVG and should never appear in HTML namespace - return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]); - } - // For XHTML and XML documents that support custom namespaces - if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) { - return true; - } - // The code should never reach this place (this means - // that the element somehow got namespace that is not - // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES). - // Return false just in case. - return false; - }; - /** - * _forceRemove - * - * @param node a DOM node - */ - const _forceRemove = function _forceRemove(node) { - arrayPush(DOMPurify.removed, { - element: node - }); - try { - // eslint-disable-next-line unicorn/prefer-dom-node-remove - getParentNode(node).removeChild(node); - } catch (_) { - remove(node); - } - }; - /** - * _removeAttribute - * - * @param name an Attribute name - * @param element a DOM node - */ - const _removeAttribute = function _removeAttribute(name, element) { - try { - arrayPush(DOMPurify.removed, { - attribute: element.getAttributeNode(name), - from: element - }); - } catch (_) { - arrayPush(DOMPurify.removed, { - attribute: null, - from: element - }); - } - element.removeAttribute(name); - // We void attribute values for unremovable "is" attributes - if (name === 'is') { - if (RETURN_DOM || RETURN_DOM_FRAGMENT) { - try { - _forceRemove(element); - } catch (_) {} - } else { - try { - element.setAttribute(name, ''); - } catch (_) {} - } - } - }; - /** - * _initDocument - * - * @param dirty - a string of dirty markup - * @return a DOM, filled with the dirty markup - */ - const _initDocument = function _initDocument(dirty) { - /* Create a HTML document */ - let doc = null; - let leadingWhitespace = null; - if (FORCE_BODY) { - dirty = '' + dirty; - } else { - /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */ - const matches = stringMatch(dirty, /^[\r\n\t ]+/); - leadingWhitespace = matches && matches[0]; - } - if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) { - // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict) - dirty = '' + dirty + ''; - } - const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty; - /* - * Use the DOMParser API by default, fallback later if needs be - * DOMParser not work for svg when has multiple root element. - */ - if (NAMESPACE === HTML_NAMESPACE) { - try { - doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE); - } catch (_) {} - } - /* Use createHTMLDocument in case DOMParser is not available */ - if (!doc || !doc.documentElement) { - doc = implementation.createDocument(NAMESPACE, 'template', null); - try { - doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload; - } catch (_) { - // Syntax error if dirtyPayload is invalid xml - } - } - const body = doc.body || doc.documentElement; - if (dirty && leadingWhitespace) { - body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null); - } - /* Work on whole document or just its body */ - if (NAMESPACE === HTML_NAMESPACE) { - return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0]; - } - return WHOLE_DOCUMENT ? doc.documentElement : body; - }; - /** - * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. - * - * @param root The root element or node to start traversing on. - * @return The created NodeIterator - */ - const _createNodeIterator = function _createNodeIterator(root) { - return createNodeIterator.call(root.ownerDocument || root, root, - // eslint-disable-next-line no-bitwise - NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null); - }; - /** - * _isClobbered - * - * @param element element to check for clobbering attacks - * @return true if clobbered, false if safe - */ - const _isClobbered = function _isClobbered(element) { - return element instanceof HTMLFormElement && (typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' || !(element.attributes instanceof NamedNodeMap) || typeof element.removeAttribute !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function'); - }; - /** - * Checks whether the given object is a DOM node. - * - * @param value object to check whether it's a DOM node - * @return true is object is a DOM node - */ - const _isNode = function _isNode(value) { - return typeof Node === 'function' && value instanceof Node; - }; - function _executeHooks(hooks, currentNode, data) { - arrayForEach(hooks, hook => { - hook.call(DOMPurify, currentNode, data, CONFIG); - }); - } - /** - * _sanitizeElements - * - * @protect nodeName - * @protect textContent - * @protect removeChild - * @param currentNode to check for permission to exist - * @return true if node was killed, false if left alive - */ - const _sanitizeElements = function _sanitizeElements(currentNode) { - let content = null; - /* Execute a hook if present */ - _executeHooks(hooks.beforeSanitizeElements, currentNode, null); - /* Check if element is clobbered or can clobber */ - if (_isClobbered(currentNode)) { - _forceRemove(currentNode); - return true; - } - /* Now let's check the element's type and name */ - const tagName = transformCaseFunc(currentNode.nodeName); - /* Execute a hook if present */ - _executeHooks(hooks.uponSanitizeElement, currentNode, { - tagName, - allowedTags: ALLOWED_TAGS - }); - /* Detect mXSS attempts abusing namespace confusion */ - if (currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\w]/g, currentNode.innerHTML) && regExpTest(/<[/\w]/g, currentNode.textContent)) { - _forceRemove(currentNode); - return true; - } - /* Remove any occurrence of processing instructions */ - if (currentNode.nodeType === NODE_TYPE.progressingInstruction) { - _forceRemove(currentNode); - return true; - } - /* Remove any kind of possibly harmful comments */ - if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(/<[/\w]/g, currentNode.data)) { - _forceRemove(currentNode); - return true; - } - /* Remove element if anything forbids its presence */ - if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) { - /* Check if we have a custom element to handle */ - if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) { - if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) { - return false; - } - if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) { - return false; - } - } - /* Keep content except for bad-listed elements */ - if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) { - const parentNode = getParentNode(currentNode) || currentNode.parentNode; - const childNodes = getChildNodes(currentNode) || currentNode.childNodes; - if (childNodes && parentNode) { - const childCount = childNodes.length; - for (let i = childCount - 1; i >= 0; --i) { - const childClone = cloneNode(childNodes[i], true); - childClone.__removalCount = (currentNode.__removalCount || 0) + 1; - parentNode.insertBefore(childClone, getNextSibling(currentNode)); - } - } - } - _forceRemove(currentNode); - return true; - } - /* Check whether element has a valid namespace */ - if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) { - _forceRemove(currentNode); - return true; - } - /* Make sure that older browsers don't get fallback-tag mXSS */ - if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)) { - _forceRemove(currentNode); - return true; - } - /* Sanitize element content to be template-safe */ - if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) { - /* Get the element's text content */ - content = currentNode.textContent; - arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => { - content = stringReplace(content, expr, ' '); - }); - if (currentNode.textContent !== content) { - arrayPush(DOMPurify.removed, { - element: currentNode.cloneNode() - }); - currentNode.textContent = content; - } - } - /* Execute a hook if present */ - _executeHooks(hooks.afterSanitizeElements, currentNode, null); - return false; - }; - /** - * _isValidAttribute - * - * @param lcTag Lowercase tag name of containing element. - * @param lcName Lowercase attribute name. - * @param value Attribute value. - * @return Returns true if `value` is valid, otherwise false. - */ - // eslint-disable-next-line complexity - const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) { - /* Make sure attribute cannot clobber */ - if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) { - return false; - } - /* Allow valid data-* attributes: At least one character after "-" - (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes) - XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804) - We don't need to check the value; it's always URI safe. */ - if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR, lcName)) ; else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) { - if ( - // First condition does a very basic check if a) it's basically a valid custom element tagname AND - // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck - // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck - _isBasicCustomElement(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName)) || - // Alternative, second condition checks if it's an `is`-attribute, AND - // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck - lcName === 'is' && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))) ; else { - return false; - } - /* Check value is safe. First, is attr inert? If so, is safe */ - } else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) ; else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if (value) { - return false; - } else ; - return true; - }; - /** - * _isBasicCustomElement - * checks if at least one dash is included in tagName, and it's not the first char - * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name - * - * @param tagName name of the tag of the node to sanitize - * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false. - */ - const _isBasicCustomElement = function _isBasicCustomElement(tagName) { - return tagName !== 'annotation-xml' && stringMatch(tagName, CUSTOM_ELEMENT); - }; - /** - * _sanitizeAttributes - * - * @protect attributes - * @protect nodeName - * @protect removeAttribute - * @protect setAttribute - * - * @param currentNode to sanitize - */ - const _sanitizeAttributes = function _sanitizeAttributes(currentNode) { - /* Execute a hook if present */ - _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null); - const { - attributes - } = currentNode; - /* Check if we have attributes; if not we might have a text node */ - if (!attributes || _isClobbered(currentNode)) { - return; - } - const hookEvent = { - attrName: '', - attrValue: '', - keepAttr: true, - allowedAttributes: ALLOWED_ATTR, - forceKeepAttr: undefined - }; - let l = attributes.length; - /* Go backwards over all attributes; safely remove bad ones */ - while (l--) { - const attr = attributes[l]; - const { - name, - namespaceURI, - value: attrValue - } = attr; - const lcName = transformCaseFunc(name); - let value = name === 'value' ? attrValue : stringTrim(attrValue); - /* Execute a hook if present */ - hookEvent.attrName = lcName; - hookEvent.attrValue = value; - hookEvent.keepAttr = true; - hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set - _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent); - value = hookEvent.attrValue; - /* Full DOM Clobbering protection via namespace isolation, - * Prefix id and name attributes with `user-content-` - */ - if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name')) { - // Remove the attribute with this value - _removeAttribute(name, currentNode); - // Prefix the value and later re-create the attribute with the sanitized value - value = SANITIZE_NAMED_PROPS_PREFIX + value; - } - /* Work around a security issue with comments inside attributes */ - if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|title)/i, value)) { - _removeAttribute(name, currentNode); - continue; - } - /* Did the hooks approve of the attribute? */ - if (hookEvent.forceKeepAttr) { - continue; - } - /* Remove attribute */ - _removeAttribute(name, currentNode); - /* Did the hooks approve of the attribute? */ - if (!hookEvent.keepAttr) { - continue; - } - /* Work around a security issue in jQuery 3.0 */ - if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) { - _removeAttribute(name, currentNode); - continue; - } - /* Sanitize attribute content to be template-safe */ - if (SAFE_FOR_TEMPLATES) { - arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => { - value = stringReplace(value, expr, ' '); - }); - } - /* Is `value` valid for this attribute? */ - const lcTag = transformCaseFunc(currentNode.nodeName); - if (!_isValidAttribute(lcTag, lcName, value)) { - continue; - } - /* Handle attributes that require Trusted Types */ - if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function') { - if (namespaceURI) ; else { - switch (trustedTypes.getAttributeType(lcTag, lcName)) { - case 'TrustedHTML': - { - value = trustedTypesPolicy.createHTML(value); - break; - } - case 'TrustedScriptURL': - { - value = trustedTypesPolicy.createScriptURL(value); - break; - } - } - } - } - /* Handle invalid data-* attribute set by try-catching it */ - try { - if (namespaceURI) { - currentNode.setAttributeNS(namespaceURI, name, value); - } else { - /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */ - currentNode.setAttribute(name, value); - } - if (_isClobbered(currentNode)) { - _forceRemove(currentNode); - } else { - arrayPop(DOMPurify.removed); - } - } catch (_) {} - } - /* Execute a hook if present */ - _executeHooks(hooks.afterSanitizeAttributes, currentNode, null); - }; - /** - * _sanitizeShadowDOM - * - * @param fragment to iterate over recursively - */ - const _sanitizeShadowDOM = function _sanitizeShadowDOM(fragment) { - let shadowNode = null; - const shadowIterator = _createNodeIterator(fragment); - /* Execute a hook if present */ - _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null); - while (shadowNode = shadowIterator.nextNode()) { - /* Execute a hook if present */ - _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null); - /* Sanitize tags and elements */ - _sanitizeElements(shadowNode); - /* Check attributes next */ - _sanitizeAttributes(shadowNode); - /* Deep shadow DOM detected */ - if (shadowNode.content instanceof DocumentFragment) { - _sanitizeShadowDOM(shadowNode.content); - } - } - /* Execute a hook if present */ - _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null); - }; - // eslint-disable-next-line complexity - DOMPurify.sanitize = function (dirty) { - let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - let body = null; - let importedNode = null; - let currentNode = null; - let returnNode = null; - /* Make sure we have a string to sanitize. - DO NOT return early, as this will return the wrong type if - the user has requested a DOM object rather than a string */ - IS_EMPTY_INPUT = !dirty; - if (IS_EMPTY_INPUT) { - dirty = ''; - } - /* Stringify, in case dirty is an object */ - if (typeof dirty !== 'string' && !_isNode(dirty)) { - if (typeof dirty.toString === 'function') { - dirty = dirty.toString(); - if (typeof dirty !== 'string') { - throw typeErrorCreate('dirty is not a string, aborting'); - } - } else { - throw typeErrorCreate('toString is not a function'); - } - } - /* Return dirty HTML if DOMPurify cannot run */ - if (!DOMPurify.isSupported) { - return dirty; - } - /* Assign config vars */ - if (!SET_CONFIG) { - _parseConfig(cfg); - } - /* Clean up removed elements */ - DOMPurify.removed = []; - /* Check if dirty is correctly typed for IN_PLACE */ - if (typeof dirty === 'string') { - IN_PLACE = false; - } - if (IN_PLACE) { - /* Do some early pre-sanitization to avoid unsafe root nodes */ - if (dirty.nodeName) { - const tagName = transformCaseFunc(dirty.nodeName); - if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) { - throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place'); - } - } - } else if (dirty instanceof Node) { - /* If dirty is a DOM element, append to an empty document to avoid - elements being stripped by the parser */ - body = _initDocument(''); - importedNode = body.ownerDocument.importNode(dirty, true); - if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === 'BODY') { - /* Node is already a body, use as is */ - body = importedNode; - } else if (importedNode.nodeName === 'HTML') { - body = importedNode; - } else { - // eslint-disable-next-line unicorn/prefer-dom-node-append - body.appendChild(importedNode); - } - } else { - /* Exit directly if we have nothing to do */ - if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT && - // eslint-disable-next-line unicorn/prefer-includes - dirty.indexOf('<') === -1) { - return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty; - } - /* Initialize the document to work on */ - body = _initDocument(dirty); - /* Check we have a DOM node from the data */ - if (!body) { - return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : ''; - } - } - /* Remove first element node (ours) if FORCE_BODY is set */ - if (body && FORCE_BODY) { - _forceRemove(body.firstChild); - } - /* Get node iterator */ - const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body); - /* Now start iterating over the created document */ - while (currentNode = nodeIterator.nextNode()) { - /* Sanitize tags and elements */ - _sanitizeElements(currentNode); - /* Check attributes next */ - _sanitizeAttributes(currentNode); - /* Shadow DOM detected, sanitize it */ - if (currentNode.content instanceof DocumentFragment) { - _sanitizeShadowDOM(currentNode.content); - } - } - /* If we sanitized `dirty` in-place, return it. */ - if (IN_PLACE) { - return dirty; - } - /* Return sanitized string or DOM */ - if (RETURN_DOM) { - if (RETURN_DOM_FRAGMENT) { - returnNode = createDocumentFragment.call(body.ownerDocument); - while (body.firstChild) { - // eslint-disable-next-line unicorn/prefer-dom-node-append - returnNode.appendChild(body.firstChild); - } - } else { - returnNode = body; - } - if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) { - /* - AdoptNode() is not used because internal state is not reset - (e.g. the past names map of a HTMLFormElement), this is safe - in theory but we would rather not risk another attack vector. - The state that is cloned by importNode() is explicitly defined - by the specs. - */ - returnNode = importNode.call(originalDocument, returnNode, true); - } - return returnNode; - } - let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML; - /* Serialize doctype if allowed */ - if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) { - serializedHTML = '\n' + serializedHTML; - } - /* Sanitize final string template-safe */ - if (SAFE_FOR_TEMPLATES) { - arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => { - serializedHTML = stringReplace(serializedHTML, expr, ' '); - }); - } - return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML; - }; - DOMPurify.setConfig = function () { - let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - _parseConfig(cfg); - SET_CONFIG = true; - }; - DOMPurify.clearConfig = function () { - CONFIG = null; - SET_CONFIG = false; - }; - DOMPurify.isValidAttribute = function (tag, attr, value) { - /* Initialize shared config vars if necessary. */ - if (!CONFIG) { - _parseConfig({}); - } - const lcTag = transformCaseFunc(tag); - const lcName = transformCaseFunc(attr); - return _isValidAttribute(lcTag, lcName, value); - }; - DOMPurify.addHook = function (entryPoint, hookFunction) { - if (typeof hookFunction !== 'function') { - return; - } - arrayPush(hooks[entryPoint], hookFunction); - }; - DOMPurify.removeHook = function (entryPoint, hookFunction) { - if (hookFunction !== undefined) { - const index = arrayLastIndexOf(hooks[entryPoint], hookFunction); - return index === -1 ? undefined : arraySplice(hooks[entryPoint], index, 1)[0]; - } - return arrayPop(hooks[entryPoint]); - }; - DOMPurify.removeHooks = function (entryPoint) { - hooks[entryPoint] = []; - }; - DOMPurify.removeAllHooks = function () { - hooks = _createHooksMap(); - }; - return DOMPurify; -} -var purify = createDOMPurify(); - -export { purify as default }; -//# sourceMappingURL=purify.es.mjs.map diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/markdown_viewer/viewer.html b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/markdown_viewer/viewer.html deleted file mode 100644 index 94447ffc47e..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/markdown_viewer/viewer.html +++ /dev/null @@ -1,32 +0,0 @@ - - - - - Markdown viewer - - - - -

    - - - diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/markdown_viewer/viewer.mjs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/markdown_viewer/viewer.mjs deleted file mode 100644 index 78eb819c9a8..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/markdown_viewer/viewer.mjs +++ /dev/null @@ -1,13 +0,0 @@ -import { parse } from '../marked/dist/marked.esm.js'; -import purify from '../dompurify/dist/purify.es.mjs'; - -const url = new URL(window.location); -const fileUrl = url.searchParams.get('file'); -if (!fileUrl) { - throw new Error('File not specified in the URL query string'); -} - -var response = await fetch(fileUrl); -var text = await response.text(); - -document.getElementById('content').innerHTML = purify.sanitize(parse(text)); diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/marked/README.md b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/marked/README.md deleted file mode 100644 index 352b52d5503..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/marked/README.md +++ /dev/null @@ -1,5 +0,0 @@ -marked version 15.0.6 -https://github.com/markedjs/marked -License: MIT - -To update, replace the `dist/marked.esm.js` file with with an updated version from https://www.npmjs.com/package/marked. diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/marked/dist/marked.esm.js b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/marked/dist/marked.esm.js deleted file mode 100644 index a32cd778363..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/marked/dist/marked.esm.js +++ /dev/null @@ -1,2568 +0,0 @@ -/** - * marked v15.0.6 - a markdown parser - * Copyright (c) 2011-2025, Christopher Jeffrey. (MIT Licensed) - * https://github.com/markedjs/marked - */ - -/** - * DO NOT EDIT THIS FILE - * The code in this file is generated from files in ./src/ - */ - -/** - * Gets the original marked default options. - */ -function _getDefaults() { - return { - async: false, - breaks: false, - extensions: null, - gfm: true, - hooks: null, - pedantic: false, - renderer: null, - silent: false, - tokenizer: null, - walkTokens: null, - }; -} -let _defaults = _getDefaults(); -function changeDefaults(newDefaults) { - _defaults = newDefaults; -} - -const noopTest = { exec: () => null }; -function edit(regex, opt = '') { - let source = typeof regex === 'string' ? regex : regex.source; - const obj = { - replace: (name, val) => { - let valSource = typeof val === 'string' ? val : val.source; - valSource = valSource.replace(other.caret, '$1'); - source = source.replace(name, valSource); - return obj; - }, - getRegex: () => { - return new RegExp(source, opt); - }, - }; - return obj; -} -const other = { - codeRemoveIndent: /^(?: {1,4}| {0,3}\t)/gm, - outputLinkReplace: /\\([\[\]])/g, - indentCodeCompensation: /^(\s+)(?:```)/, - beginningSpace: /^\s+/, - endingHash: /#$/, - startingSpaceChar: /^ /, - endingSpaceChar: / $/, - nonSpaceChar: /[^ ]/, - newLineCharGlobal: /\n/g, - tabCharGlobal: /\t/g, - multipleSpaceGlobal: /\s+/g, - blankLine: /^[ \t]*$/, - doubleBlankLine: /\n[ \t]*\n[ \t]*$/, - blockquoteStart: /^ {0,3}>/, - blockquoteSetextReplace: /\n {0,3}((?:=+|-+) *)(?=\n|$)/g, - blockquoteSetextReplace2: /^ {0,3}>[ \t]?/gm, - listReplaceTabs: /^\t+/, - listReplaceNesting: /^ {1,4}(?=( {4})*[^ ])/g, - listIsTask: /^\[[ xX]\] /, - listReplaceTask: /^\[[ xX]\] +/, - anyLine: /\n.*\n/, - hrefBrackets: /^<(.*)>$/, - tableDelimiter: /[:|]/, - tableAlignChars: /^\||\| *$/g, - tableRowBlankLine: /\n[ \t]*$/, - tableAlignRight: /^ *-+: *$/, - tableAlignCenter: /^ *:-+: *$/, - tableAlignLeft: /^ *:-+ *$/, - startATag: /^
    /i, - startPreScriptTag: /^<(pre|code|kbd|script)(\s|>)/i, - endPreScriptTag: /^<\/(pre|code|kbd|script)(\s|>)/i, - startAngleBracket: /^$/, - pedanticHrefTitle: /^([^'"]*[^\s])\s+(['"])(.*)\2/, - unicodeAlphaNumeric: /[\p{L}\p{N}]/u, - escapeTest: /[&<>"']/, - escapeReplace: /[&<>"']/g, - escapeTestNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/, - escapeReplaceNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g, - unescapeTest: /&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig, - caret: /(^|[^\[])\^/g, - percentDecode: /%25/g, - findPipe: /\|/g, - splitPipe: / \|/, - slashPipe: /\\\|/g, - carriageReturn: /\r\n|\r/g, - spaceLine: /^ +$/gm, - notSpaceStart: /^\S*/, - endingNewline: /\n$/, - listItemRegex: (bull) => new RegExp(`^( {0,3}${bull})((?:[\t ][^\\n]*)?(?:\\n|$))`), - nextBulletRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ \t][^\\n]*)?(?:\\n|$))`), - hrRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`), - fencesBeginRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\`\`\`|~~~)`), - headingBeginRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`), - htmlBeginRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}<(?:[a-z].*>|!--)`, 'i'), -}; -/** - * Block-Level Grammar - */ -const newline = /^(?:[ \t]*(?:\n|$))+/; -const blockCode = /^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/; -const fences = /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/; -const hr = /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/; -const heading = /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/; -const bullet = /(?:[*+-]|\d{1,9}[.)])/; -const lheading = edit(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/) - .replace(/bull/g, bullet) // lists can interrupt - .replace(/blockCode/g, /(?: {4}| {0,3}\t)/) // indented code blocks can interrupt - .replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/) // fenced code blocks can interrupt - .replace(/blockquote/g, / {0,3}>/) // blockquote can interrupt - .replace(/heading/g, / {0,3}#{1,6}/) // ATX heading can interrupt - .replace(/html/g, / {0,3}<[^\n>]+>\n/) // block html can interrupt - .getRegex(); -const _paragraph = /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/; -const blockText = /^[^\n]+/; -const _blockLabel = /(?!\s*\])(?:\\.|[^\[\]\\])+/; -const def = edit(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/) - .replace('label', _blockLabel) - .replace('title', /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/) - .getRegex(); -const list = edit(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/) - .replace(/bull/g, bullet) - .getRegex(); -const _tag = 'address|article|aside|base|basefont|blockquote|body|caption' - + '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption' - + '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe' - + '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option' - + '|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title' - + '|tr|track|ul'; -const _comment = /|$))/; -const html = edit('^ {0,3}(?:' // optional indentation - + '<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)' // (1) - + '|comment[^\\n]*(\\n+|$)' // (2) - + '|<\\?[\\s\\S]*?(?:\\?>\\n*|$)' // (3) - + '|\\n*|$)' // (4) - + '|\\n*|$)' // (5) - + '|)[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)' // (6) - + '|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)' // (7) open tag - + '|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)' // (7) closing tag - + ')', 'i') - .replace('comment', _comment) - .replace('tag', _tag) - .replace('attribute', / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/) - .getRegex(); -const paragraph = edit(_paragraph) - .replace('hr', hr) - .replace('heading', ' {0,3}#{1,6}(?:\\s|$)') - .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs - .replace('|table', '') - .replace('blockquote', ' {0,3}>') - .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n') - .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt - .replace('html', ')|<(?:script|pre|style|textarea|!--)') - .replace('tag', _tag) // pars can be interrupted by type (6) html blocks - .getRegex(); -const blockquote = edit(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/) - .replace('paragraph', paragraph) - .getRegex(); -/** - * Normal Block Grammar - */ -const blockNormal = { - blockquote, - code: blockCode, - def, - fences, - heading, - hr, - html, - lheading, - list, - newline, - paragraph, - table: noopTest, - text: blockText, -}; -/** - * GFM Block Grammar - */ -const gfmTable = edit('^ *([^\\n ].*)\\n' // Header - + ' {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)' // Align - + '(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)') // Cells - .replace('hr', hr) - .replace('heading', ' {0,3}#{1,6}(?:\\s|$)') - .replace('blockquote', ' {0,3}>') - .replace('code', '(?: {4}| {0,3}\t)[^\\n]') - .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n') - .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt - .replace('html', ')|<(?:script|pre|style|textarea|!--)') - .replace('tag', _tag) // tables can be interrupted by type (6) html blocks - .getRegex(); -const blockGfm = { - ...blockNormal, - table: gfmTable, - paragraph: edit(_paragraph) - .replace('hr', hr) - .replace('heading', ' {0,3}#{1,6}(?:\\s|$)') - .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs - .replace('table', gfmTable) // interrupt paragraphs with table - .replace('blockquote', ' {0,3}>') - .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n') - .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt - .replace('html', ')|<(?:script|pre|style|textarea|!--)') - .replace('tag', _tag) // pars can be interrupted by type (6) html blocks - .getRegex(), -}; -/** - * Pedantic grammar (original John Gruber's loose markdown specification) - */ -const blockPedantic = { - ...blockNormal, - html: edit('^ *(?:comment *(?:\\n|\\s*$)' - + '|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)' // closed tag - + '|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))') - .replace('comment', _comment) - .replace(/tag/g, '(?!(?:' - + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub' - + '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)' - + '\\b)\\w+(?!:|[^\\w\\s@]*@)\\b') - .getRegex(), - def: /^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/, - heading: /^(#{1,6})(.*)(?:\n+|$)/, - fences: noopTest, // fences not supported - lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/, - paragraph: edit(_paragraph) - .replace('hr', hr) - .replace('heading', ' *#{1,6} *[^\n]') - .replace('lheading', lheading) - .replace('|table', '') - .replace('blockquote', ' {0,3}>') - .replace('|fences', '') - .replace('|list', '') - .replace('|html', '') - .replace('|tag', '') - .getRegex(), -}; -/** - * Inline-Level Grammar - */ -const escape$1 = /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/; -const inlineCode = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/; -const br = /^( {2,}|\\)\n(?!\s*$)/; -const inlineText = /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\ -const blockSkip = /\[[^[\]]*?\]\((?:\\.|[^\\\(\)]|\((?:\\.|[^\\\(\)])*\))*\)|`[^`]*?`|<[^<>]*?>/g; -const emStrongLDelimCore = /^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/; -const emStrongLDelim = edit(emStrongLDelimCore, 'u') - .replace(/punct/g, _punctuation) - .getRegex(); -const emStrongLDelimGfm = edit(emStrongLDelimCore, 'u') - .replace(/punct/g, _punctuationGfmStrongEm) - .getRegex(); -const emStrongRDelimAstCore = '^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)' // Skip orphan inside strong - + '|[^*]+(?=[^*])' // Consume to delim - + '|(?!\\*)punct(\\*+)(?=[\\s]|$)' // (1) #*** can only be a Right Delimiter - + '|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)' // (2) a***#, a*** can only be a Right Delimiter - + '|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)' // (3) #***a, ***a can only be Left Delimiter - + '|[\\s](\\*+)(?!\\*)(?=punct)' // (4) ***# can only be Left Delimiter - + '|(?!\\*)punct(\\*+)(?!\\*)(?=punct)' // (5) #***# can be either Left or Right Delimiter - + '|notPunctSpace(\\*+)(?=notPunctSpace)'; // (6) a***a can be either Left or Right Delimiter -const emStrongRDelimAst = edit(emStrongRDelimAstCore, 'gu') - .replace(/notPunctSpace/g, _notPunctuationOrSpace) - .replace(/punctSpace/g, _punctuationOrSpace) - .replace(/punct/g, _punctuation) - .getRegex(); -const emStrongRDelimAstGfm = edit(emStrongRDelimAstCore, 'gu') - .replace(/notPunctSpace/g, _notPunctuationOrSpaceGfmStrongEm) - .replace(/punctSpace/g, _punctuationOrSpaceGfmStrongEm) - .replace(/punct/g, _punctuationGfmStrongEm) - .getRegex(); -// (6) Not allowed for _ -const emStrongRDelimUnd = edit('^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)' // Skip orphan inside strong - + '|[^_]+(?=[^_])' // Consume to delim - + '|(?!_)punct(_+)(?=[\\s]|$)' // (1) #___ can only be a Right Delimiter - + '|notPunctSpace(_+)(?!_)(?=punctSpace|$)' // (2) a___#, a___ can only be a Right Delimiter - + '|(?!_)punctSpace(_+)(?=notPunctSpace)' // (3) #___a, ___a can only be Left Delimiter - + '|[\\s](_+)(?!_)(?=punct)' // (4) ___# can only be Left Delimiter - + '|(?!_)punct(_+)(?!_)(?=punct)', 'gu') // (5) #___# can be either Left or Right Delimiter - .replace(/notPunctSpace/g, _notPunctuationOrSpace) - .replace(/punctSpace/g, _punctuationOrSpace) - .replace(/punct/g, _punctuation) - .getRegex(); -const anyPunctuation = edit(/\\(punct)/, 'gu') - .replace(/punct/g, _punctuation) - .getRegex(); -const autolink = edit(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/) - .replace('scheme', /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/) - .replace('email', /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/) - .getRegex(); -const _inlineComment = edit(_comment).replace('(?:-->|$)', '-->').getRegex(); -const tag = edit('^comment' - + '|^' // self-closing tag - + '|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>' // open tag - + '|^<\\?[\\s\\S]*?\\?>' // processing instruction, e.g. - + '|^' // declaration, e.g. - + '|^') // CDATA section - .replace('comment', _inlineComment) - .replace('attribute', /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/) - .getRegex(); -const _inlineLabel = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/; -const link = edit(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/) - .replace('label', _inlineLabel) - .replace('href', /<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/) - .replace('title', /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/) - .getRegex(); -const reflink = edit(/^!?\[(label)\]\[(ref)\]/) - .replace('label', _inlineLabel) - .replace('ref', _blockLabel) - .getRegex(); -const nolink = edit(/^!?\[(ref)\](?:\[\])?/) - .replace('ref', _blockLabel) - .getRegex(); -const reflinkSearch = edit('reflink|nolink(?!\\()', 'g') - .replace('reflink', reflink) - .replace('nolink', nolink) - .getRegex(); -/** - * Normal Inline Grammar - */ -const inlineNormal = { - _backpedal: noopTest, // only used for GFM url - anyPunctuation, - autolink, - blockSkip, - br, - code: inlineCode, - del: noopTest, - emStrongLDelim, - emStrongRDelimAst, - emStrongRDelimUnd, - escape: escape$1, - link, - nolink, - punctuation, - reflink, - reflinkSearch, - tag, - text: inlineText, - url: noopTest, -}; -/** - * Pedantic Inline Grammar - */ -const inlinePedantic = { - ...inlineNormal, - link: edit(/^!?\[(label)\]\((.*?)\)/) - .replace('label', _inlineLabel) - .getRegex(), - reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/) - .replace('label', _inlineLabel) - .getRegex(), -}; -/** - * GFM Inline Grammar - */ -const inlineGfm = { - ...inlineNormal, - emStrongRDelimAst: emStrongRDelimAstGfm, - emStrongLDelim: emStrongLDelimGfm, - url: edit(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/, 'i') - .replace('email', /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/) - .getRegex(), - _backpedal: /(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/, - del: /^(~~?)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/, - text: /^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\': '>', - '"': '"', - "'": ''', -}; -const getEscapeReplacement = (ch) => escapeReplacements[ch]; -function escape(html, encode) { - if (encode) { - if (other.escapeTest.test(html)) { - return html.replace(other.escapeReplace, getEscapeReplacement); - } - } - else { - if (other.escapeTestNoEncode.test(html)) { - return html.replace(other.escapeReplaceNoEncode, getEscapeReplacement); - } - } - return html; -} -function cleanUrl(href) { - try { - href = encodeURI(href).replace(other.percentDecode, '%'); - } - catch { - return null; - } - return href; -} -function splitCells(tableRow, count) { - // ensure that every cell-delimiting pipe has a space - // before it to distinguish it from an escaped pipe - const row = tableRow.replace(other.findPipe, (match, offset, str) => { - let escaped = false; - let curr = offset; - while (--curr >= 0 && str[curr] === '\\') - escaped = !escaped; - if (escaped) { - // odd number of slashes means | is escaped - // so we leave it alone - return '|'; - } - else { - // add space before unescaped | - return ' |'; - } - }), cells = row.split(other.splitPipe); - let i = 0; - // First/last cell in a row cannot be empty if it has no leading/trailing pipe - if (!cells[0].trim()) { - cells.shift(); - } - if (cells.length > 0 && !cells.at(-1)?.trim()) { - cells.pop(); - } - if (count) { - if (cells.length > count) { - cells.splice(count); - } - else { - while (cells.length < count) - cells.push(''); - } - } - for (; i < cells.length; i++) { - // leading or trailing whitespace is ignored per the gfm spec - cells[i] = cells[i].trim().replace(other.slashPipe, '|'); - } - return cells; -} -/** - * Remove trailing 'c's. Equivalent to str.replace(/c*$/, ''). - * /c*$/ is vulnerable to REDOS. - * - * @param str - * @param c - * @param invert Remove suffix of non-c chars instead. Default falsey. - */ -function rtrim(str, c, invert) { - const l = str.length; - if (l === 0) { - return ''; - } - // Length of suffix matching the invert condition. - let suffLen = 0; - // Step left until we fail to match the invert condition. - while (suffLen < l) { - const currChar = str.charAt(l - suffLen - 1); - if (currChar === c && true) { - suffLen++; - } - else { - break; - } - } - return str.slice(0, l - suffLen); -} -function findClosingBracket(str, b) { - if (str.indexOf(b[1]) === -1) { - return -1; - } - let level = 0; - for (let i = 0; i < str.length; i++) { - if (str[i] === '\\') { - i++; - } - else if (str[i] === b[0]) { - level++; - } - else if (str[i] === b[1]) { - level--; - if (level < 0) { - return i; - } - } - } - return -1; -} - -function outputLink(cap, link, raw, lexer, rules) { - const href = link.href; - const title = link.title || null; - const text = cap[1].replace(rules.other.outputLinkReplace, '$1'); - if (cap[0].charAt(0) !== '!') { - lexer.state.inLink = true; - const token = { - type: 'link', - raw, - href, - title, - text, - tokens: lexer.inlineTokens(text), - }; - lexer.state.inLink = false; - return token; - } - return { - type: 'image', - raw, - href, - title, - text, - }; -} -function indentCodeCompensation(raw, text, rules) { - const matchIndentToCode = raw.match(rules.other.indentCodeCompensation); - if (matchIndentToCode === null) { - return text; - } - const indentToCode = matchIndentToCode[1]; - return text - .split('\n') - .map(node => { - const matchIndentInNode = node.match(rules.other.beginningSpace); - if (matchIndentInNode === null) { - return node; - } - const [indentInNode] = matchIndentInNode; - if (indentInNode.length >= indentToCode.length) { - return node.slice(indentToCode.length); - } - return node; - }) - .join('\n'); -} -/** - * Tokenizer - */ -class _Tokenizer { - options; - rules; // set by the lexer - lexer; // set by the lexer - constructor(options) { - this.options = options || _defaults; - } - space(src) { - const cap = this.rules.block.newline.exec(src); - if (cap && cap[0].length > 0) { - return { - type: 'space', - raw: cap[0], - }; - } - } - code(src) { - const cap = this.rules.block.code.exec(src); - if (cap) { - const text = cap[0].replace(this.rules.other.codeRemoveIndent, ''); - return { - type: 'code', - raw: cap[0], - codeBlockStyle: 'indented', - text: !this.options.pedantic - ? rtrim(text, '\n') - : text, - }; - } - } - fences(src) { - const cap = this.rules.block.fences.exec(src); - if (cap) { - const raw = cap[0]; - const text = indentCodeCompensation(raw, cap[3] || '', this.rules); - return { - type: 'code', - raw, - lang: cap[2] ? cap[2].trim().replace(this.rules.inline.anyPunctuation, '$1') : cap[2], - text, - }; - } - } - heading(src) { - const cap = this.rules.block.heading.exec(src); - if (cap) { - let text = cap[2].trim(); - // remove trailing #s - if (this.rules.other.endingHash.test(text)) { - const trimmed = rtrim(text, '#'); - if (this.options.pedantic) { - text = trimmed.trim(); - } - else if (!trimmed || this.rules.other.endingSpaceChar.test(trimmed)) { - // CommonMark requires space before trailing #s - text = trimmed.trim(); - } - } - return { - type: 'heading', - raw: cap[0], - depth: cap[1].length, - text, - tokens: this.lexer.inline(text), - }; - } - } - hr(src) { - const cap = this.rules.block.hr.exec(src); - if (cap) { - return { - type: 'hr', - raw: rtrim(cap[0], '\n'), - }; - } - } - blockquote(src) { - const cap = this.rules.block.blockquote.exec(src); - if (cap) { - let lines = rtrim(cap[0], '\n').split('\n'); - let raw = ''; - let text = ''; - const tokens = []; - while (lines.length > 0) { - let inBlockquote = false; - const currentLines = []; - let i; - for (i = 0; i < lines.length; i++) { - // get lines up to a continuation - if (this.rules.other.blockquoteStart.test(lines[i])) { - currentLines.push(lines[i]); - inBlockquote = true; - } - else if (!inBlockquote) { - currentLines.push(lines[i]); - } - else { - break; - } - } - lines = lines.slice(i); - const currentRaw = currentLines.join('\n'); - const currentText = currentRaw - // precede setext continuation with 4 spaces so it isn't a setext - .replace(this.rules.other.blockquoteSetextReplace, '\n $1') - .replace(this.rules.other.blockquoteSetextReplace2, ''); - raw = raw ? `${raw}\n${currentRaw}` : currentRaw; - text = text ? `${text}\n${currentText}` : currentText; - // parse blockquote lines as top level tokens - // merge paragraphs if this is a continuation - const top = this.lexer.state.top; - this.lexer.state.top = true; - this.lexer.blockTokens(currentText, tokens, true); - this.lexer.state.top = top; - // if there is no continuation then we are done - if (lines.length === 0) { - break; - } - const lastToken = tokens.at(-1); - if (lastToken?.type === 'code') { - // blockquote continuation cannot be preceded by a code block - break; - } - else if (lastToken?.type === 'blockquote') { - // include continuation in nested blockquote - const oldToken = lastToken; - const newText = oldToken.raw + '\n' + lines.join('\n'); - const newToken = this.blockquote(newText); - tokens[tokens.length - 1] = newToken; - raw = raw.substring(0, raw.length - oldToken.raw.length) + newToken.raw; - text = text.substring(0, text.length - oldToken.text.length) + newToken.text; - break; - } - else if (lastToken?.type === 'list') { - // include continuation in nested list - const oldToken = lastToken; - const newText = oldToken.raw + '\n' + lines.join('\n'); - const newToken = this.list(newText); - tokens[tokens.length - 1] = newToken; - raw = raw.substring(0, raw.length - lastToken.raw.length) + newToken.raw; - text = text.substring(0, text.length - oldToken.raw.length) + newToken.raw; - lines = newText.substring(tokens.at(-1).raw.length).split('\n'); - continue; - } - } - return { - type: 'blockquote', - raw, - tokens, - text, - }; - } - } - list(src) { - let cap = this.rules.block.list.exec(src); - if (cap) { - let bull = cap[1].trim(); - const isordered = bull.length > 1; - const list = { - type: 'list', - raw: '', - ordered: isordered, - start: isordered ? +bull.slice(0, -1) : '', - loose: false, - items: [], - }; - bull = isordered ? `\\d{1,9}\\${bull.slice(-1)}` : `\\${bull}`; - if (this.options.pedantic) { - bull = isordered ? bull : '[*+-]'; - } - // Get next list item - const itemRegex = this.rules.other.listItemRegex(bull); - let endsWithBlankLine = false; - // Check if current bullet point can start a new List Item - while (src) { - let endEarly = false; - let raw = ''; - let itemContents = ''; - if (!(cap = itemRegex.exec(src))) { - break; - } - if (this.rules.block.hr.test(src)) { // End list if bullet was actually HR (possibly move into itemRegex?) - break; - } - raw = cap[0]; - src = src.substring(raw.length); - let line = cap[2].split('\n', 1)[0].replace(this.rules.other.listReplaceTabs, (t) => ' '.repeat(3 * t.length)); - let nextLine = src.split('\n', 1)[0]; - let blankLine = !line.trim(); - let indent = 0; - if (this.options.pedantic) { - indent = 2; - itemContents = line.trimStart(); - } - else if (blankLine) { - indent = cap[1].length + 1; - } - else { - indent = cap[2].search(this.rules.other.nonSpaceChar); // Find first non-space char - indent = indent > 4 ? 1 : indent; // Treat indented code blocks (> 4 spaces) as having only 1 indent - itemContents = line.slice(indent); - indent += cap[1].length; - } - if (blankLine && this.rules.other.blankLine.test(nextLine)) { // Items begin with at most one blank line - raw += nextLine + '\n'; - src = src.substring(nextLine.length + 1); - endEarly = true; - } - if (!endEarly) { - const nextBulletRegex = this.rules.other.nextBulletRegex(indent); - const hrRegex = this.rules.other.hrRegex(indent); - const fencesBeginRegex = this.rules.other.fencesBeginRegex(indent); - const headingBeginRegex = this.rules.other.headingBeginRegex(indent); - const htmlBeginRegex = this.rules.other.htmlBeginRegex(indent); - // Check if following lines should be included in List Item - while (src) { - const rawLine = src.split('\n', 1)[0]; - let nextLineWithoutTabs; - nextLine = rawLine; - // Re-align to follow commonmark nesting rules - if (this.options.pedantic) { - nextLine = nextLine.replace(this.rules.other.listReplaceNesting, ' '); - nextLineWithoutTabs = nextLine; - } - else { - nextLineWithoutTabs = nextLine.replace(this.rules.other.tabCharGlobal, ' '); - } - // End list item if found code fences - if (fencesBeginRegex.test(nextLine)) { - break; - } - // End list item if found start of new heading - if (headingBeginRegex.test(nextLine)) { - break; - } - // End list item if found start of html block - if (htmlBeginRegex.test(nextLine)) { - break; - } - // End list item if found start of new bullet - if (nextBulletRegex.test(nextLine)) { - break; - } - // Horizontal rule found - if (hrRegex.test(nextLine)) { - break; - } - if (nextLineWithoutTabs.search(this.rules.other.nonSpaceChar) >= indent || !nextLine.trim()) { // Dedent if possible - itemContents += '\n' + nextLineWithoutTabs.slice(indent); - } - else { - // not enough indentation - if (blankLine) { - break; - } - // paragraph continuation unless last line was a different block level element - if (line.replace(this.rules.other.tabCharGlobal, ' ').search(this.rules.other.nonSpaceChar) >= 4) { // indented code block - break; - } - if (fencesBeginRegex.test(line)) { - break; - } - if (headingBeginRegex.test(line)) { - break; - } - if (hrRegex.test(line)) { - break; - } - itemContents += '\n' + nextLine; - } - if (!blankLine && !nextLine.trim()) { // Check if current line is blank - blankLine = true; - } - raw += rawLine + '\n'; - src = src.substring(rawLine.length + 1); - line = nextLineWithoutTabs.slice(indent); - } - } - if (!list.loose) { - // If the previous item ended with a blank line, the list is loose - if (endsWithBlankLine) { - list.loose = true; - } - else if (this.rules.other.doubleBlankLine.test(raw)) { - endsWithBlankLine = true; - } - } - let istask = null; - let ischecked; - // Check for task list items - if (this.options.gfm) { - istask = this.rules.other.listIsTask.exec(itemContents); - if (istask) { - ischecked = istask[0] !== '[ ] '; - itemContents = itemContents.replace(this.rules.other.listReplaceTask, ''); - } - } - list.items.push({ - type: 'list_item', - raw, - task: !!istask, - checked: ischecked, - loose: false, - text: itemContents, - tokens: [], - }); - list.raw += raw; - } - // Do not consume newlines at end of final item. Alternatively, make itemRegex *start* with any newlines to simplify/speed up endsWithBlankLine logic - const lastItem = list.items.at(-1); - if (lastItem) { - lastItem.raw = lastItem.raw.trimEnd(); - lastItem.text = lastItem.text.trimEnd(); - } - else { - // not a list since there were no items - return; - } - list.raw = list.raw.trimEnd(); - // Item child tokens handled here at end because we needed to have the final item to trim it first - for (let i = 0; i < list.items.length; i++) { - this.lexer.state.top = false; - list.items[i].tokens = this.lexer.blockTokens(list.items[i].text, []); - if (!list.loose) { - // Check if list should be loose - const spacers = list.items[i].tokens.filter(t => t.type === 'space'); - const hasMultipleLineBreaks = spacers.length > 0 && spacers.some(t => this.rules.other.anyLine.test(t.raw)); - list.loose = hasMultipleLineBreaks; - } - } - // Set all items to loose if list is loose - if (list.loose) { - for (let i = 0; i < list.items.length; i++) { - list.items[i].loose = true; - } - } - return list; - } - } - html(src) { - const cap = this.rules.block.html.exec(src); - if (cap) { - const token = { - type: 'html', - block: true, - raw: cap[0], - pre: cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style', - text: cap[0], - }; - return token; - } - } - def(src) { - const cap = this.rules.block.def.exec(src); - if (cap) { - const tag = cap[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal, ' '); - const href = cap[2] ? cap[2].replace(this.rules.other.hrefBrackets, '$1').replace(this.rules.inline.anyPunctuation, '$1') : ''; - const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline.anyPunctuation, '$1') : cap[3]; - return { - type: 'def', - tag, - raw: cap[0], - href, - title, - }; - } - } - table(src) { - const cap = this.rules.block.table.exec(src); - if (!cap) { - return; - } - if (!this.rules.other.tableDelimiter.test(cap[2])) { - // delimiter row must have a pipe (|) or colon (:) otherwise it is a setext heading - return; - } - const headers = splitCells(cap[1]); - const aligns = cap[2].replace(this.rules.other.tableAlignChars, '').split('|'); - const rows = cap[3]?.trim() ? cap[3].replace(this.rules.other.tableRowBlankLine, '').split('\n') : []; - const item = { - type: 'table', - raw: cap[0], - header: [], - align: [], - rows: [], - }; - if (headers.length !== aligns.length) { - // header and align columns must be equal, rows can be different. - return; - } - for (const align of aligns) { - if (this.rules.other.tableAlignRight.test(align)) { - item.align.push('right'); - } - else if (this.rules.other.tableAlignCenter.test(align)) { - item.align.push('center'); - } - else if (this.rules.other.tableAlignLeft.test(align)) { - item.align.push('left'); - } - else { - item.align.push(null); - } - } - for (let i = 0; i < headers.length; i++) { - item.header.push({ - text: headers[i], - tokens: this.lexer.inline(headers[i]), - header: true, - align: item.align[i], - }); - } - for (const row of rows) { - item.rows.push(splitCells(row, item.header.length).map((cell, i) => { - return { - text: cell, - tokens: this.lexer.inline(cell), - header: false, - align: item.align[i], - }; - })); - } - return item; - } - lheading(src) { - const cap = this.rules.block.lheading.exec(src); - if (cap) { - return { - type: 'heading', - raw: cap[0], - depth: cap[2].charAt(0) === '=' ? 1 : 2, - text: cap[1], - tokens: this.lexer.inline(cap[1]), - }; - } - } - paragraph(src) { - const cap = this.rules.block.paragraph.exec(src); - if (cap) { - const text = cap[1].charAt(cap[1].length - 1) === '\n' - ? cap[1].slice(0, -1) - : cap[1]; - return { - type: 'paragraph', - raw: cap[0], - text, - tokens: this.lexer.inline(text), - }; - } - } - text(src) { - const cap = this.rules.block.text.exec(src); - if (cap) { - return { - type: 'text', - raw: cap[0], - text: cap[0], - tokens: this.lexer.inline(cap[0]), - }; - } - } - escape(src) { - const cap = this.rules.inline.escape.exec(src); - if (cap) { - return { - type: 'escape', - raw: cap[0], - text: cap[1], - }; - } - } - tag(src) { - const cap = this.rules.inline.tag.exec(src); - if (cap) { - if (!this.lexer.state.inLink && this.rules.other.startATag.test(cap[0])) { - this.lexer.state.inLink = true; - } - else if (this.lexer.state.inLink && this.rules.other.endATag.test(cap[0])) { - this.lexer.state.inLink = false; - } - if (!this.lexer.state.inRawBlock && this.rules.other.startPreScriptTag.test(cap[0])) { - this.lexer.state.inRawBlock = true; - } - else if (this.lexer.state.inRawBlock && this.rules.other.endPreScriptTag.test(cap[0])) { - this.lexer.state.inRawBlock = false; - } - return { - type: 'html', - raw: cap[0], - inLink: this.lexer.state.inLink, - inRawBlock: this.lexer.state.inRawBlock, - block: false, - text: cap[0], - }; - } - } - link(src) { - const cap = this.rules.inline.link.exec(src); - if (cap) { - const trimmedUrl = cap[2].trim(); - if (!this.options.pedantic && this.rules.other.startAngleBracket.test(trimmedUrl)) { - // commonmark requires matching angle brackets - if (!(this.rules.other.endAngleBracket.test(trimmedUrl))) { - return; - } - // ending angle bracket cannot be escaped - const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), '\\'); - if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) { - return; - } - } - else { - // find closing parenthesis - const lastParenIndex = findClosingBracket(cap[2], '()'); - if (lastParenIndex > -1) { - const start = cap[0].indexOf('!') === 0 ? 5 : 4; - const linkLen = start + cap[1].length + lastParenIndex; - cap[2] = cap[2].substring(0, lastParenIndex); - cap[0] = cap[0].substring(0, linkLen).trim(); - cap[3] = ''; - } - } - let href = cap[2]; - let title = ''; - if (this.options.pedantic) { - // split pedantic href and title - const link = this.rules.other.pedanticHrefTitle.exec(href); - if (link) { - href = link[1]; - title = link[3]; - } - } - else { - title = cap[3] ? cap[3].slice(1, -1) : ''; - } - href = href.trim(); - if (this.rules.other.startAngleBracket.test(href)) { - if (this.options.pedantic && !(this.rules.other.endAngleBracket.test(trimmedUrl))) { - // pedantic allows starting angle bracket without ending angle bracket - href = href.slice(1); - } - else { - href = href.slice(1, -1); - } - } - return outputLink(cap, { - href: href ? href.replace(this.rules.inline.anyPunctuation, '$1') : href, - title: title ? title.replace(this.rules.inline.anyPunctuation, '$1') : title, - }, cap[0], this.lexer, this.rules); - } - } - reflink(src, links) { - let cap; - if ((cap = this.rules.inline.reflink.exec(src)) - || (cap = this.rules.inline.nolink.exec(src))) { - const linkString = (cap[2] || cap[1]).replace(this.rules.other.multipleSpaceGlobal, ' '); - const link = links[linkString.toLowerCase()]; - if (!link) { - const text = cap[0].charAt(0); - return { - type: 'text', - raw: text, - text, - }; - } - return outputLink(cap, link, cap[0], this.lexer, this.rules); - } - } - emStrong(src, maskedSrc, prevChar = '') { - let match = this.rules.inline.emStrongLDelim.exec(src); - if (!match) - return; - // _ can't be between two alphanumerics. \p{L}\p{N} includes non-english alphabet/numbers as well - if (match[3] && prevChar.match(this.rules.other.unicodeAlphaNumeric)) - return; - const nextChar = match[1] || match[2] || ''; - if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) { - // unicode Regex counts emoji as 1 char; spread into array for proper count (used multiple times below) - const lLength = [...match[0]].length - 1; - let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0; - const endReg = match[0][0] === '*' ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd; - endReg.lastIndex = 0; - // Clip maskedSrc to same section of string as src (move to lexer?) - maskedSrc = maskedSrc.slice(-1 * src.length + lLength); - while ((match = endReg.exec(maskedSrc)) != null) { - rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6]; - if (!rDelim) - continue; // skip single * in __abc*abc__ - rLength = [...rDelim].length; - if (match[3] || match[4]) { // found another Left Delim - delimTotal += rLength; - continue; - } - else if (match[5] || match[6]) { // either Left or Right Delim - if (lLength % 3 && !((lLength + rLength) % 3)) { - midDelimTotal += rLength; - continue; // CommonMark Emphasis Rules 9-10 - } - } - delimTotal -= rLength; - if (delimTotal > 0) - continue; // Haven't found enough closing delimiters - // Remove extra characters. *a*** -> *a* - rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal); - // char length can be >1 for unicode characters; - const lastCharLength = [...match[0]][0].length; - const raw = src.slice(0, lLength + match.index + lastCharLength + rLength); - // Create `em` if smallest delimiter has odd char count. *a*** - if (Math.min(lLength, rLength) % 2) { - const text = raw.slice(1, -1); - return { - type: 'em', - raw, - text, - tokens: this.lexer.inlineTokens(text), - }; - } - // Create 'strong' if smallest delimiter has even char count. **a*** - const text = raw.slice(2, -2); - return { - type: 'strong', - raw, - text, - tokens: this.lexer.inlineTokens(text), - }; - } - } - } - codespan(src) { - const cap = this.rules.inline.code.exec(src); - if (cap) { - let text = cap[2].replace(this.rules.other.newLineCharGlobal, ' '); - const hasNonSpaceChars = this.rules.other.nonSpaceChar.test(text); - const hasSpaceCharsOnBothEnds = this.rules.other.startingSpaceChar.test(text) && this.rules.other.endingSpaceChar.test(text); - if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) { - text = text.substring(1, text.length - 1); - } - return { - type: 'codespan', - raw: cap[0], - text, - }; - } - } - br(src) { - const cap = this.rules.inline.br.exec(src); - if (cap) { - return { - type: 'br', - raw: cap[0], - }; - } - } - del(src) { - const cap = this.rules.inline.del.exec(src); - if (cap) { - return { - type: 'del', - raw: cap[0], - text: cap[2], - tokens: this.lexer.inlineTokens(cap[2]), - }; - } - } - autolink(src) { - const cap = this.rules.inline.autolink.exec(src); - if (cap) { - let text, href; - if (cap[2] === '@') { - text = cap[1]; - href = 'mailto:' + text; - } - else { - text = cap[1]; - href = text; - } - return { - type: 'link', - raw: cap[0], - text, - href, - tokens: [ - { - type: 'text', - raw: text, - text, - }, - ], - }; - } - } - url(src) { - let cap; - if (cap = this.rules.inline.url.exec(src)) { - let text, href; - if (cap[2] === '@') { - text = cap[0]; - href = 'mailto:' + text; - } - else { - // do extended autolink path validation - let prevCapZero; - do { - prevCapZero = cap[0]; - cap[0] = this.rules.inline._backpedal.exec(cap[0])?.[0] ?? ''; - } while (prevCapZero !== cap[0]); - text = cap[0]; - if (cap[1] === 'www.') { - href = 'http://' + cap[0]; - } - else { - href = cap[0]; - } - } - return { - type: 'link', - raw: cap[0], - text, - href, - tokens: [ - { - type: 'text', - raw: text, - text, - }, - ], - }; - } - } - inlineText(src) { - const cap = this.rules.inline.text.exec(src); - if (cap) { - const escaped = this.lexer.state.inRawBlock; - return { - type: 'text', - raw: cap[0], - text: cap[0], - escaped, - }; - } - } -} - -/** - * Block Lexer - */ -class _Lexer { - tokens; - options; - state; - tokenizer; - inlineQueue; - constructor(options) { - // TokenList cannot be created in one go - this.tokens = []; - this.tokens.links = Object.create(null); - this.options = options || _defaults; - this.options.tokenizer = this.options.tokenizer || new _Tokenizer(); - this.tokenizer = this.options.tokenizer; - this.tokenizer.options = this.options; - this.tokenizer.lexer = this; - this.inlineQueue = []; - this.state = { - inLink: false, - inRawBlock: false, - top: true, - }; - const rules = { - other, - block: block.normal, - inline: inline.normal, - }; - if (this.options.pedantic) { - rules.block = block.pedantic; - rules.inline = inline.pedantic; - } - else if (this.options.gfm) { - rules.block = block.gfm; - if (this.options.breaks) { - rules.inline = inline.breaks; - } - else { - rules.inline = inline.gfm; - } - } - this.tokenizer.rules = rules; - } - /** - * Expose Rules - */ - static get rules() { - return { - block, - inline, - }; - } - /** - * Static Lex Method - */ - static lex(src, options) { - const lexer = new _Lexer(options); - return lexer.lex(src); - } - /** - * Static Lex Inline Method - */ - static lexInline(src, options) { - const lexer = new _Lexer(options); - return lexer.inlineTokens(src); - } - /** - * Preprocessing - */ - lex(src) { - src = src.replace(other.carriageReturn, '\n'); - this.blockTokens(src, this.tokens); - for (let i = 0; i < this.inlineQueue.length; i++) { - const next = this.inlineQueue[i]; - this.inlineTokens(next.src, next.tokens); - } - this.inlineQueue = []; - return this.tokens; - } - blockTokens(src, tokens = [], lastParagraphClipped = false) { - if (this.options.pedantic) { - src = src.replace(other.tabCharGlobal, ' ').replace(other.spaceLine, ''); - } - while (src) { - let token; - if (this.options.extensions?.block?.some((extTokenizer) => { - if (token = extTokenizer.call({ lexer: this }, src, tokens)) { - src = src.substring(token.raw.length); - tokens.push(token); - return true; - } - return false; - })) { - continue; - } - // newline - if (token = this.tokenizer.space(src)) { - src = src.substring(token.raw.length); - const lastToken = tokens.at(-1); - if (token.raw.length === 1 && lastToken !== undefined) { - // if there's a single \n as a spacer, it's terminating the last line, - // so move it there so that we don't get unnecessary paragraph tags - lastToken.raw += '\n'; - } - else { - tokens.push(token); - } - continue; - } - // code - if (token = this.tokenizer.code(src)) { - src = src.substring(token.raw.length); - const lastToken = tokens.at(-1); - // An indented code block cannot interrupt a paragraph. - if (lastToken?.type === 'paragraph' || lastToken?.type === 'text') { - lastToken.raw += '\n' + token.raw; - lastToken.text += '\n' + token.text; - this.inlineQueue.at(-1).src = lastToken.text; - } - else { - tokens.push(token); - } - continue; - } - // fences - if (token = this.tokenizer.fences(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // heading - if (token = this.tokenizer.heading(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // hr - if (token = this.tokenizer.hr(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // blockquote - if (token = this.tokenizer.blockquote(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // list - if (token = this.tokenizer.list(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // html - if (token = this.tokenizer.html(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // def - if (token = this.tokenizer.def(src)) { - src = src.substring(token.raw.length); - const lastToken = tokens.at(-1); - if (lastToken?.type === 'paragraph' || lastToken?.type === 'text') { - lastToken.raw += '\n' + token.raw; - lastToken.text += '\n' + token.raw; - this.inlineQueue.at(-1).src = lastToken.text; - } - else if (!this.tokens.links[token.tag]) { - this.tokens.links[token.tag] = { - href: token.href, - title: token.title, - }; - } - continue; - } - // table (gfm) - if (token = this.tokenizer.table(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // lheading - if (token = this.tokenizer.lheading(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // top-level paragraph - // prevent paragraph consuming extensions by clipping 'src' to extension start - let cutSrc = src; - if (this.options.extensions?.startBlock) { - let startIndex = Infinity; - const tempSrc = src.slice(1); - let tempStart; - this.options.extensions.startBlock.forEach((getStartIndex) => { - tempStart = getStartIndex.call({ lexer: this }, tempSrc); - if (typeof tempStart === 'number' && tempStart >= 0) { - startIndex = Math.min(startIndex, tempStart); - } - }); - if (startIndex < Infinity && startIndex >= 0) { - cutSrc = src.substring(0, startIndex + 1); - } - } - if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) { - const lastToken = tokens.at(-1); - if (lastParagraphClipped && lastToken?.type === 'paragraph') { - lastToken.raw += '\n' + token.raw; - lastToken.text += '\n' + token.text; - this.inlineQueue.pop(); - this.inlineQueue.at(-1).src = lastToken.text; - } - else { - tokens.push(token); - } - lastParagraphClipped = cutSrc.length !== src.length; - src = src.substring(token.raw.length); - continue; - } - // text - if (token = this.tokenizer.text(src)) { - src = src.substring(token.raw.length); - const lastToken = tokens.at(-1); - if (lastToken?.type === 'text') { - lastToken.raw += '\n' + token.raw; - lastToken.text += '\n' + token.text; - this.inlineQueue.pop(); - this.inlineQueue.at(-1).src = lastToken.text; - } - else { - tokens.push(token); - } - continue; - } - if (src) { - const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0); - if (this.options.silent) { - console.error(errMsg); - break; - } - else { - throw new Error(errMsg); - } - } - } - this.state.top = true; - return tokens; - } - inline(src, tokens = []) { - this.inlineQueue.push({ src, tokens }); - return tokens; - } - /** - * Lexing/Compiling - */ - inlineTokens(src, tokens = []) { - // String with links masked to avoid interference with em and strong - let maskedSrc = src; - let match = null; - // Mask out reflinks - if (this.tokens.links) { - const links = Object.keys(this.tokens.links); - if (links.length > 0) { - while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) { - if (links.includes(match[0].slice(match[0].lastIndexOf('[') + 1, -1))) { - maskedSrc = maskedSrc.slice(0, match.index) - + '[' + 'a'.repeat(match[0].length - 2) + ']' - + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex); - } - } - } - } - // Mask out other blocks - while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) { - maskedSrc = maskedSrc.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex); - } - // Mask out escaped characters - while ((match = this.tokenizer.rules.inline.anyPunctuation.exec(maskedSrc)) != null) { - maskedSrc = maskedSrc.slice(0, match.index) + '++' + maskedSrc.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex); - } - let keepPrevChar = false; - let prevChar = ''; - while (src) { - if (!keepPrevChar) { - prevChar = ''; - } - keepPrevChar = false; - let token; - // extensions - if (this.options.extensions?.inline?.some((extTokenizer) => { - if (token = extTokenizer.call({ lexer: this }, src, tokens)) { - src = src.substring(token.raw.length); - tokens.push(token); - return true; - } - return false; - })) { - continue; - } - // escape - if (token = this.tokenizer.escape(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // tag - if (token = this.tokenizer.tag(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // link - if (token = this.tokenizer.link(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // reflink, nolink - if (token = this.tokenizer.reflink(src, this.tokens.links)) { - src = src.substring(token.raw.length); - const lastToken = tokens.at(-1); - if (token.type === 'text' && lastToken?.type === 'text') { - lastToken.raw += token.raw; - lastToken.text += token.text; - } - else { - tokens.push(token); - } - continue; - } - // em & strong - if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // code - if (token = this.tokenizer.codespan(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // br - if (token = this.tokenizer.br(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // del (gfm) - if (token = this.tokenizer.del(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // autolink - if (token = this.tokenizer.autolink(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // url (gfm) - if (!this.state.inLink && (token = this.tokenizer.url(src))) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // text - // prevent inlineText consuming extensions by clipping 'src' to extension start - let cutSrc = src; - if (this.options.extensions?.startInline) { - let startIndex = Infinity; - const tempSrc = src.slice(1); - let tempStart; - this.options.extensions.startInline.forEach((getStartIndex) => { - tempStart = getStartIndex.call({ lexer: this }, tempSrc); - if (typeof tempStart === 'number' && tempStart >= 0) { - startIndex = Math.min(startIndex, tempStart); - } - }); - if (startIndex < Infinity && startIndex >= 0) { - cutSrc = src.substring(0, startIndex + 1); - } - } - if (token = this.tokenizer.inlineText(cutSrc)) { - src = src.substring(token.raw.length); - if (token.raw.slice(-1) !== '_') { // Track prevChar before string of ____ started - prevChar = token.raw.slice(-1); - } - keepPrevChar = true; - const lastToken = tokens.at(-1); - if (lastToken?.type === 'text') { - lastToken.raw += token.raw; - lastToken.text += token.text; - } - else { - tokens.push(token); - } - continue; - } - if (src) { - const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0); - if (this.options.silent) { - console.error(errMsg); - break; - } - else { - throw new Error(errMsg); - } - } - } - return tokens; - } -} - -/** - * Renderer - */ -class _Renderer { - options; - parser; // set by the parser - constructor(options) { - this.options = options || _defaults; - } - space(token) { - return ''; - } - code({ text, lang, escaped }) { - const langString = (lang || '').match(other.notSpaceStart)?.[0]; - const code = text.replace(other.endingNewline, '') + '\n'; - if (!langString) { - return '
    '
    -                + (escaped ? code : escape(code, true))
    -                + '
    \n'; - } - return '
    '
    -            + (escaped ? code : escape(code, true))
    -            + '
    \n'; - } - blockquote({ tokens }) { - const body = this.parser.parse(tokens); - return `
    \n${body}
    \n`; - } - html({ text }) { - return text; - } - heading({ tokens, depth }) { - return `${this.parser.parseInline(tokens)}\n`; - } - hr(token) { - return '
    \n'; - } - list(token) { - const ordered = token.ordered; - const start = token.start; - let body = ''; - for (let j = 0; j < token.items.length; j++) { - const item = token.items[j]; - body += this.listitem(item); - } - const type = ordered ? 'ol' : 'ul'; - const startAttr = (ordered && start !== 1) ? (' start="' + start + '"') : ''; - return '<' + type + startAttr + '>\n' + body + '\n'; - } - listitem(item) { - let itemBody = ''; - if (item.task) { - const checkbox = this.checkbox({ checked: !!item.checked }); - if (item.loose) { - if (item.tokens[0]?.type === 'paragraph') { - item.tokens[0].text = checkbox + ' ' + item.tokens[0].text; - if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') { - item.tokens[0].tokens[0].text = checkbox + ' ' + escape(item.tokens[0].tokens[0].text); - item.tokens[0].tokens[0].escaped = true; - } - } - else { - item.tokens.unshift({ - type: 'text', - raw: checkbox + ' ', - text: checkbox + ' ', - escaped: true, - }); - } - } - else { - itemBody += checkbox + ' '; - } - } - itemBody += this.parser.parse(item.tokens, !!item.loose); - return `
  • ${itemBody}
  • \n`; - } - checkbox({ checked }) { - return ''; - } - paragraph({ tokens }) { - return `

    ${this.parser.parseInline(tokens)}

    \n`; - } - table(token) { - let header = ''; - // header - let cell = ''; - for (let j = 0; j < token.header.length; j++) { - cell += this.tablecell(token.header[j]); - } - header += this.tablerow({ text: cell }); - let body = ''; - for (let j = 0; j < token.rows.length; j++) { - const row = token.rows[j]; - cell = ''; - for (let k = 0; k < row.length; k++) { - cell += this.tablecell(row[k]); - } - body += this.tablerow({ text: cell }); - } - if (body) - body = `${body}`; - return '\n' - + '\n' - + header - + '\n' - + body - + '
    \n'; - } - tablerow({ text }) { - return `\n${text}\n`; - } - tablecell(token) { - const content = this.parser.parseInline(token.tokens); - const type = token.header ? 'th' : 'td'; - const tag = token.align - ? `<${type} align="${token.align}">` - : `<${type}>`; - return tag + content + `\n`; - } - /** - * span level renderer - */ - strong({ tokens }) { - return `${this.parser.parseInline(tokens)}`; - } - em({ tokens }) { - return `${this.parser.parseInline(tokens)}`; - } - codespan({ text }) { - return `${escape(text, true)}`; - } - br(token) { - return '
    '; - } - del({ tokens }) { - return `${this.parser.parseInline(tokens)}`; - } - link({ href, title, tokens }) { - const text = this.parser.parseInline(tokens); - const cleanHref = cleanUrl(href); - if (cleanHref === null) { - return text; - } - href = cleanHref; - let out = '
    '; - return out; - } - image({ href, title, text }) { - const cleanHref = cleanUrl(href); - if (cleanHref === null) { - return escape(text); - } - href = cleanHref; - let out = `${text} { - const tokens = genericToken[childTokens].flat(Infinity); - values = values.concat(this.walkTokens(tokens, callback)); - }); - } - else if (genericToken.tokens) { - values = values.concat(this.walkTokens(genericToken.tokens, callback)); - } - } - } - } - return values; - } - use(...args) { - const extensions = this.defaults.extensions || { renderers: {}, childTokens: {} }; - args.forEach((pack) => { - // copy options to new object - const opts = { ...pack }; - // set async to true if it was set to true before - opts.async = this.defaults.async || opts.async || false; - // ==-- Parse "addon" extensions --== // - if (pack.extensions) { - pack.extensions.forEach((ext) => { - if (!ext.name) { - throw new Error('extension name required'); - } - if ('renderer' in ext) { // Renderer extensions - const prevRenderer = extensions.renderers[ext.name]; - if (prevRenderer) { - // Replace extension with func to run new extension but fall back if false - extensions.renderers[ext.name] = function (...args) { - let ret = ext.renderer.apply(this, args); - if (ret === false) { - ret = prevRenderer.apply(this, args); - } - return ret; - }; - } - else { - extensions.renderers[ext.name] = ext.renderer; - } - } - if ('tokenizer' in ext) { // Tokenizer Extensions - if (!ext.level || (ext.level !== 'block' && ext.level !== 'inline')) { - throw new Error("extension level must be 'block' or 'inline'"); - } - const extLevel = extensions[ext.level]; - if (extLevel) { - extLevel.unshift(ext.tokenizer); - } - else { - extensions[ext.level] = [ext.tokenizer]; - } - if (ext.start) { // Function to check for start of token - if (ext.level === 'block') { - if (extensions.startBlock) { - extensions.startBlock.push(ext.start); - } - else { - extensions.startBlock = [ext.start]; - } - } - else if (ext.level === 'inline') { - if (extensions.startInline) { - extensions.startInline.push(ext.start); - } - else { - extensions.startInline = [ext.start]; - } - } - } - } - if ('childTokens' in ext && ext.childTokens) { // Child tokens to be visited by walkTokens - extensions.childTokens[ext.name] = ext.childTokens; - } - }); - opts.extensions = extensions; - } - // ==-- Parse "overwrite" extensions --== // - if (pack.renderer) { - const renderer = this.defaults.renderer || new _Renderer(this.defaults); - for (const prop in pack.renderer) { - if (!(prop in renderer)) { - throw new Error(`renderer '${prop}' does not exist`); - } - if (['options', 'parser'].includes(prop)) { - // ignore options property - continue; - } - const rendererProp = prop; - const rendererFunc = pack.renderer[rendererProp]; - const prevRenderer = renderer[rendererProp]; - // Replace renderer with func to run extension, but fall back if false - renderer[rendererProp] = (...args) => { - let ret = rendererFunc.apply(renderer, args); - if (ret === false) { - ret = prevRenderer.apply(renderer, args); - } - return ret || ''; - }; - } - opts.renderer = renderer; - } - if (pack.tokenizer) { - const tokenizer = this.defaults.tokenizer || new _Tokenizer(this.defaults); - for (const prop in pack.tokenizer) { - if (!(prop in tokenizer)) { - throw new Error(`tokenizer '${prop}' does not exist`); - } - if (['options', 'rules', 'lexer'].includes(prop)) { - // ignore options, rules, and lexer properties - continue; - } - const tokenizerProp = prop; - const tokenizerFunc = pack.tokenizer[tokenizerProp]; - const prevTokenizer = tokenizer[tokenizerProp]; - // Replace tokenizer with func to run extension, but fall back if false - // @ts-expect-error cannot type tokenizer function dynamically - tokenizer[tokenizerProp] = (...args) => { - let ret = tokenizerFunc.apply(tokenizer, args); - if (ret === false) { - ret = prevTokenizer.apply(tokenizer, args); - } - return ret; - }; - } - opts.tokenizer = tokenizer; - } - // ==-- Parse Hooks extensions --== // - if (pack.hooks) { - const hooks = this.defaults.hooks || new _Hooks(); - for (const prop in pack.hooks) { - if (!(prop in hooks)) { - throw new Error(`hook '${prop}' does not exist`); - } - if (['options', 'block'].includes(prop)) { - // ignore options and block properties - continue; - } - const hooksProp = prop; - const hooksFunc = pack.hooks[hooksProp]; - const prevHook = hooks[hooksProp]; - if (_Hooks.passThroughHooks.has(prop)) { - // @ts-expect-error cannot type hook function dynamically - hooks[hooksProp] = (arg) => { - if (this.defaults.async) { - return Promise.resolve(hooksFunc.call(hooks, arg)).then(ret => { - return prevHook.call(hooks, ret); - }); - } - const ret = hooksFunc.call(hooks, arg); - return prevHook.call(hooks, ret); - }; - } - else { - // @ts-expect-error cannot type hook function dynamically - hooks[hooksProp] = (...args) => { - let ret = hooksFunc.apply(hooks, args); - if (ret === false) { - ret = prevHook.apply(hooks, args); - } - return ret; - }; - } - } - opts.hooks = hooks; - } - // ==-- Parse WalkTokens extensions --== // - if (pack.walkTokens) { - const walkTokens = this.defaults.walkTokens; - const packWalktokens = pack.walkTokens; - opts.walkTokens = function (token) { - let values = []; - values.push(packWalktokens.call(this, token)); - if (walkTokens) { - values = values.concat(walkTokens.call(this, token)); - } - return values; - }; - } - this.defaults = { ...this.defaults, ...opts }; - }); - return this; - } - setOptions(opt) { - this.defaults = { ...this.defaults, ...opt }; - return this; - } - lexer(src, options) { - return _Lexer.lex(src, options ?? this.defaults); - } - parser(tokens, options) { - return _Parser.parse(tokens, options ?? this.defaults); - } - parseMarkdown(blockType) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const parse = (src, options) => { - const origOpt = { ...options }; - const opt = { ...this.defaults, ...origOpt }; - const throwError = this.onError(!!opt.silent, !!opt.async); - // throw error if an extension set async to true but parse was called with async: false - if (this.defaults.async === true && origOpt.async === false) { - return throwError(new Error('marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.')); - } - // throw error in case of non string input - if (typeof src === 'undefined' || src === null) { - return throwError(new Error('marked(): input parameter is undefined or null')); - } - if (typeof src !== 'string') { - return throwError(new Error('marked(): input parameter is of type ' - + Object.prototype.toString.call(src) + ', string expected')); - } - if (opt.hooks) { - opt.hooks.options = opt; - opt.hooks.block = blockType; - } - const lexer = opt.hooks ? opt.hooks.provideLexer() : (blockType ? _Lexer.lex : _Lexer.lexInline); - const parser = opt.hooks ? opt.hooks.provideParser() : (blockType ? _Parser.parse : _Parser.parseInline); - if (opt.async) { - return Promise.resolve(opt.hooks ? opt.hooks.preprocess(src) : src) - .then(src => lexer(src, opt)) - .then(tokens => opt.hooks ? opt.hooks.processAllTokens(tokens) : tokens) - .then(tokens => opt.walkTokens ? Promise.all(this.walkTokens(tokens, opt.walkTokens)).then(() => tokens) : tokens) - .then(tokens => parser(tokens, opt)) - .then(html => opt.hooks ? opt.hooks.postprocess(html) : html) - .catch(throwError); - } - try { - if (opt.hooks) { - src = opt.hooks.preprocess(src); - } - let tokens = lexer(src, opt); - if (opt.hooks) { - tokens = opt.hooks.processAllTokens(tokens); - } - if (opt.walkTokens) { - this.walkTokens(tokens, opt.walkTokens); - } - let html = parser(tokens, opt); - if (opt.hooks) { - html = opt.hooks.postprocess(html); - } - return html; - } - catch (e) { - return throwError(e); - } - }; - return parse; - } - onError(silent, async) { - return (e) => { - e.message += '\nPlease report this to https://github.com/markedjs/marked.'; - if (silent) { - const msg = '

    An error occurred:

    '
    -                    + escape(e.message + '', true)
    -                    + '
    '; - if (async) { - return Promise.resolve(msg); - } - return msg; - } - if (async) { - return Promise.reject(e); - } - throw e; - }; - } -} - -const markedInstance = new Marked(); -function marked(src, opt) { - return markedInstance.parse(src, opt); -} -/** - * Sets the default options. - * - * @param options Hash of options - */ -marked.options = - marked.setOptions = function (options) { - markedInstance.setOptions(options); - marked.defaults = markedInstance.defaults; - changeDefaults(marked.defaults); - return marked; - }; -/** - * Gets the original marked default options. - */ -marked.getDefaults = _getDefaults; -marked.defaults = _defaults; -/** - * Use Extension - */ -marked.use = function (...args) { - markedInstance.use(...args); - marked.defaults = markedInstance.defaults; - changeDefaults(marked.defaults); - return marked; -}; -/** - * Run callback for every token - */ -marked.walkTokens = function (tokens, callback) { - return markedInstance.walkTokens(tokens, callback); -}; -/** - * Compiles markdown to HTML without enclosing `p` tag. - * - * @param src String of markdown source to be compiled - * @param options Hash of options - * @return String of compiled HTML - */ -marked.parseInline = markedInstance.parseInline; -/** - * Expose - */ -marked.Parser = _Parser; -marked.parser = _Parser.parse; -marked.Renderer = _Renderer; -marked.TextRenderer = _TextRenderer; -marked.Lexer = _Lexer; -marked.lexer = _Lexer.lex; -marked.Tokenizer = _Tokenizer; -marked.Hooks = _Hooks; -marked.parse = marked; -const options = marked.options; -const setOptions = marked.setOptions; -const use = marked.use; -const walkTokens = marked.walkTokens; -const parseInline = marked.parseInline; -const parse = marked; -const parser = _Parser.parse; -const lexer = _Lexer.lex; - -export { _Hooks as Hooks, _Lexer as Lexer, Marked, _Parser as Parser, _Renderer as Renderer, _TextRenderer as TextRenderer, _Tokenizer as Tokenizer, _defaults as defaults, _getDefaults as getDefaults, lexer, marked, options, parse, parseInline, parser, setOptions, use, walkTokens }; -//# sourceMappingURL=marked.esm.js.map diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdf_viewer/viewer.html b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdf_viewer/viewer.html deleted file mode 100644 index 32ac36286a7..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdf_viewer/viewer.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - PDF viewer - - - - - - -
    -
    -
    - - - - diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdf_viewer/viewer.mjs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdf_viewer/viewer.mjs deleted file mode 100644 index 8a4a6b76f5e..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdf_viewer/viewer.mjs +++ /dev/null @@ -1,62 +0,0 @@ -import { GlobalWorkerOptions } from '../pdfjs-dist/dist/build/pdf.min.mjs'; -import { EventBus, PDFLinkService, PDFFindController, PDFViewer } from '../pdfjs-dist/dist/web/pdf_viewer.mjs'; - -GlobalWorkerOptions.workerSrc = '../pdfjs-dist/dist/build/pdf.worker.min.mjs'; - -// Extract the file path from the URL query string. -const url = new URL(window.location); -const fileUrl = url.searchParams.get('file'); -if (!fileUrl) { - throw new Error('File not specified in the URL query string'); -} - -const container = document.getElementById('viewerContainer'); -const eventBus = new EventBus(); - -// Enable hyperlinks within PDF files. -const pdfLinkService = new PDFLinkService({ - eventBus, -}); - -// Enable the find controller. -const pdfFindController = new PDFFindController({ - eventBus, - linkService: pdfLinkService, -}); - -// Create the PDF viewer. -const pdfViewer = new PDFViewer({ - container, - eventBus, - linkService: pdfLinkService, - findController: pdfFindController, -}); -pdfLinkService.setViewer(pdfViewer); - -// Allow navigation to a citation from the URL hash. -eventBus.on('pagesinit', function () { - pdfLinkService.setHash(window.location.hash.substring(1)); -}); - -// Define how the "search" query parameter is handled. -eventBus.on('findfromurlhash', function(evt) { - eventBus.dispatch('find', { - source: evt.source, - type: '', - query: evt.query, - caseSensitive: false, - entireWord: false, - highlightAll: false, - findPrevious: false, - matchDiacritics: true, - }); -}); - -// Load and initialize the document. -const pdfDocument = await pdfjsLib.getDocument({ - url: fileUrl, - enableXfa: true, -}).promise; - -pdfViewer.setDocument(pdfDocument); -pdfLinkService.setDocument(pdfDocument, null); diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/README.md b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/README.md deleted file mode 100644 index 8e77fba7d43..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/README.md +++ /dev/null @@ -1,10 +0,0 @@ -pdfjs-dist version 4.10.38 -https://github.com/mozilla/pdf.js -License: Apache-2.0 - -To update, replace the following files with updated versions from https://www.npmjs.com/package/pdfjs-dist: -* `build/pdf.min.mjs` -* `build/pdf.worker.min.mjs` -* `web/pdf_viewer.css` -* `web/pdf_viewer.mjs` -* `web/images/loading-icon.gif` diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/build/pdf.min.mjs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/build/pdf.min.mjs deleted file mode 100644 index d7cfa914562..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/build/pdf.min.mjs +++ /dev/null @@ -1,21 +0,0 @@ -/** - * @licstart The following is the entire license notice for the - * JavaScript code in this page - * - * Copyright 2024 Mozilla Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * @licend The above is the entire license notice for the - * JavaScript code in this page - */var t={d:(e,i)=>{for(var s in i)t.o(i,s)&&!t.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:i[s]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e)},__webpack_exports__ = globalThis.pdfjsLib = {};t.d(__webpack_exports__,{AbortException:()=>AbortException,AnnotationEditorLayer:()=>AnnotationEditorLayer,AnnotationEditorParamsType:()=>m,AnnotationEditorType:()=>g,AnnotationEditorUIManager:()=>AnnotationEditorUIManager,AnnotationLayer:()=>AnnotationLayer,AnnotationMode:()=>p,ColorPicker:()=>ColorPicker,DOMSVGFactory:()=>DOMSVGFactory,DrawLayer:()=>DrawLayer,FeatureTest:()=>util_FeatureTest,GlobalWorkerOptions:()=>GlobalWorkerOptions,ImageKind:()=>_,InvalidPDFException:()=>InvalidPDFException,MissingPDFException:()=>MissingPDFException,OPS:()=>X,OutputScale:()=>OutputScale,PDFDataRangeTransport:()=>PDFDataRangeTransport,PDFDateString:()=>PDFDateString,PDFWorker:()=>PDFWorker,PasswordResponses:()=>K,PermissionFlag:()=>f,PixelsPerInch:()=>PixelsPerInch,RenderingCancelledException:()=>RenderingCancelledException,TextLayer:()=>TextLayer,TouchManager:()=>TouchManager,UnexpectedResponseException:()=>UnexpectedResponseException,Util:()=>Util,VerbosityLevel:()=>q,XfaLayer:()=>XfaLayer,build:()=>Nt,createValidAbsoluteUrl:()=>createValidAbsoluteUrl,fetchData:()=>fetchData,getDocument:()=>getDocument,getFilenameFromUrl:()=>getFilenameFromUrl,getPdfFilenameFromUrl:()=>getPdfFilenameFromUrl,getXfaPageViewport:()=>getXfaPageViewport,isDataScheme:()=>isDataScheme,isPdfFile:()=>isPdfFile,noContextMenu:()=>noContextMenu,normalizeUnicode:()=>normalizeUnicode,setLayerDimensions:()=>setLayerDimensions,shadow:()=>shadow,stopEvent:()=>stopEvent,version:()=>Ot});const e=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),i=[1,0,0,1,0,0],s=[.001,0,0,.001,0,0],n=1.35,a=1,r=2,o=4,l=16,h=32,d=64,c=128,u=256,p={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},g={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},m={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,HIGHLIGHT_COLOR:31,HIGHLIGHT_DEFAULT_COLOR:32,HIGHLIGHT_THICKNESS:33,HIGHLIGHT_FREE:34,HIGHLIGHT_SHOW_ALL:35,DRAW_STEP:41},f={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},b=0,A=1,w=2,v=3,y=3,x=4,_={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},E=1,S=2,C=3,T=4,M=5,P=6,D=7,k=8,R=9,I=10,F=11,L=12,O=13,N=14,B=15,H=16,z=17,U=20,G=1,$=2,V=3,j=4,W=5,q={ERRORS:0,WARNINGS:1,INFOS:5},X={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91,setStrokeTransparent:92,setFillTransparent:93},K={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let Y=q.WARNINGS;function setVerbosityLevel(t){Number.isInteger(t)&&(Y=t)}function getVerbosityLevel(){return Y}function info(t){Y>=q.INFOS&&console.log(`Info: ${t}`)}function warn(t){Y>=q.WARNINGS&&console.log(`Warning: ${t}`)}function unreachable(t){throw new Error(t)}function assert(t,e){t||unreachable(e)}function createValidAbsoluteUrl(t,e=null,i=null){if(!t)return null;try{if(i&&"string"==typeof t){if(i.addDefaultProtocol&&t.startsWith("www.")){const e=t.match(/\./g);e?.length>=2&&(t=`http://${t}`)}if(i.tryConvertEncoding)try{t=function stringToUTF8String(t){return decodeURIComponent(escape(t))}(t)}catch{}}const s=e?new URL(t,e):new URL(t);if(function _isValidProtocol(t){switch(t?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(s))return s}catch{}return null}function shadow(t,e,i,s=!1){Object.defineProperty(t,e,{value:i,enumerable:!s,configurable:!0,writable:!1});return i}const Q=function BaseExceptionClosure(){function BaseException(t,e){this.message=t;this.name=e}BaseException.prototype=new Error;BaseException.constructor=BaseException;return BaseException}();class PasswordException extends Q{constructor(t,e){super(t,"PasswordException");this.code=e}}class UnknownErrorException extends Q{constructor(t,e){super(t,"UnknownErrorException");this.details=e}}class InvalidPDFException extends Q{constructor(t){super(t,"InvalidPDFException")}}class MissingPDFException extends Q{constructor(t){super(t,"MissingPDFException")}}class UnexpectedResponseException extends Q{constructor(t,e){super(t,"UnexpectedResponseException");this.status=e}}class FormatError extends Q{constructor(t){super(t,"FormatError")}}class AbortException extends Q{constructor(t){super(t,"AbortException")}}function bytesToString(t){"object"==typeof t&&void 0!==t?.length||unreachable("Invalid argument for bytesToString");const e=t.length,i=8192;if(et.toString(16).padStart(2,"0")));class Util{static makeHexColor(t,e,i){return`#${J[t]}${J[e]}${J[i]}`}static scaleMinMax(t,e){let i;if(t[0]){if(t[0]<0){i=e[0];e[0]=e[2];e[2]=i}e[0]*=t[0];e[2]*=t[0];if(t[3]<0){i=e[1];e[1]=e[3];e[3]=i}e[1]*=t[3];e[3]*=t[3]}else{i=e[0];e[0]=e[1];e[1]=i;i=e[2];e[2]=e[3];e[3]=i;if(t[1]<0){i=e[1];e[1]=e[3];e[3]=i}e[1]*=t[1];e[3]*=t[1];if(t[2]<0){i=e[0];e[0]=e[2];e[2]=i}e[0]*=t[2];e[2]*=t[2]}e[0]+=t[4];e[1]+=t[5];e[2]+=t[4];e[3]+=t[5]}static transform(t,e){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],t[0]*e[4]+t[2]*e[5]+t[4],t[1]*e[4]+t[3]*e[5]+t[5]]}static applyTransform(t,e){return[t[0]*e[0]+t[1]*e[2]+e[4],t[0]*e[1]+t[1]*e[3]+e[5]]}static applyInverseTransform(t,e){const i=e[0]*e[3]-e[1]*e[2];return[(t[0]*e[3]-t[1]*e[2]+e[2]*e[5]-e[4]*e[3])/i,(-t[0]*e[1]+t[1]*e[0]+e[4]*e[1]-e[5]*e[0])/i]}static getAxialAlignedBoundingBox(t,e){const i=this.applyTransform(t,e),s=this.applyTransform(t.slice(2,4),e),n=this.applyTransform([t[0],t[3]],e),a=this.applyTransform([t[2],t[1]],e);return[Math.min(i[0],s[0],n[0],a[0]),Math.min(i[1],s[1],n[1],a[1]),Math.max(i[0],s[0],n[0],a[0]),Math.max(i[1],s[1],n[1],a[1])]}static inverseTransform(t){const e=t[0]*t[3]-t[1]*t[2];return[t[3]/e,-t[1]/e,-t[2]/e,t[0]/e,(t[2]*t[5]-t[4]*t[3])/e,(t[4]*t[1]-t[5]*t[0])/e]}static singularValueDecompose2dScale(t){const e=[t[0],t[2],t[1],t[3]],i=t[0]*e[0]+t[1]*e[2],s=t[0]*e[1]+t[1]*e[3],n=t[2]*e[0]+t[3]*e[2],a=t[2]*e[1]+t[3]*e[3],r=(i+a)/2,o=Math.sqrt((i+a)**2-4*(i*a-n*s))/2,l=r+o||1,h=r-o||1;return[Math.sqrt(l),Math.sqrt(h)]}static normalizeRect(t){const e=t.slice(0);if(t[0]>t[2]){e[0]=t[2];e[2]=t[0]}if(t[1]>t[3]){e[1]=t[3];e[3]=t[1]}return e}static intersect(t,e){const i=Math.max(Math.min(t[0],t[2]),Math.min(e[0],e[2])),s=Math.min(Math.max(t[0],t[2]),Math.max(e[0],e[2]));if(i>s)return null;const n=Math.max(Math.min(t[1],t[3]),Math.min(e[1],e[3])),a=Math.min(Math.max(t[1],t[3]),Math.max(e[1],e[3]));return n>a?null:[i,n,s,a]}static#t(t,e,i,s,n,a,r,o,l,h){if(l<=0||l>=1)return;const d=1-l,c=l*l,u=c*l,p=d*(d*(d*t+3*l*e)+3*c*i)+u*s,g=d*(d*(d*n+3*l*a)+3*c*r)+u*o;h[0]=Math.min(h[0],p);h[1]=Math.min(h[1],g);h[2]=Math.max(h[2],p);h[3]=Math.max(h[3],g)}static#e(t,e,i,s,n,a,r,o,l,h,d,c){if(Math.abs(l)<1e-12){Math.abs(h)>=1e-12&&this.#t(t,e,i,s,n,a,r,o,-d/h,c);return}const u=h**2-4*d*l;if(u<0)return;const p=Math.sqrt(u),g=2*l;this.#t(t,e,i,s,n,a,r,o,(-h+p)/g,c);this.#t(t,e,i,s,n,a,r,o,(-h-p)/g,c)}static bezierBoundingBox(t,e,i,s,n,a,r,o,l){if(l){l[0]=Math.min(l[0],t,r);l[1]=Math.min(l[1],e,o);l[2]=Math.max(l[2],t,r);l[3]=Math.max(l[3],e,o)}else l=[Math.min(t,r),Math.min(e,o),Math.max(t,r),Math.max(e,o)];this.#e(t,i,n,r,e,s,a,o,3*(3*(i-n)-t+r),6*(t-2*i+n),3*(i-t),l);this.#e(t,i,n,r,e,s,a,o,3*(3*(s-a)-e+o),6*(e-2*s+a),3*(s-e),l);return l}}let Z=null,tt=null;function normalizeUnicode(t){if(!Z){Z=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu;tt=new Map([["ſt","ſt"]])}return t.replaceAll(Z,((t,e,i)=>e?e.normalize("NFKC"):tt.get(i)))}const et="pdfjs_internal_id_";"function"!=typeof Promise.try&&(Promise.try=function(t,...e){return new Promise((i=>{i(t(...e))}))});const it="http://www.w3.org/2000/svg";class PixelsPerInch{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function fetchData(t,e="text"){if(isValidFetchUrl(t,document.baseURI)){const i=await fetch(t);if(!i.ok)throw new Error(i.statusText);switch(e){case"arraybuffer":return i.arrayBuffer();case"blob":return i.blob();case"json":return i.json()}return i.text()}return new Promise(((i,s)=>{const n=new XMLHttpRequest;n.open("GET",t,!0);n.responseType=e;n.onreadystatechange=()=>{if(n.readyState===XMLHttpRequest.DONE)if(200!==n.status&&0!==n.status)s(new Error(n.statusText));else{switch(e){case"arraybuffer":case"blob":case"json":i(n.response);return}i(n.responseText)}};n.send(null)}))}class PageViewport{constructor({viewBox:t,userUnit:e,scale:i,rotation:s,offsetX:n=0,offsetY:a=0,dontFlip:r=!1}){this.viewBox=t;this.userUnit=e;this.scale=i;this.rotation=s;this.offsetX=n;this.offsetY=a;i*=e;const o=(t[2]+t[0])/2,l=(t[3]+t[1])/2;let h,d,c,u,p,g,m,f;(s%=360)<0&&(s+=360);switch(s){case 180:h=-1;d=0;c=0;u=1;break;case 90:h=0;d=1;c=1;u=0;break;case 270:h=0;d=-1;c=-1;u=0;break;case 0:h=1;d=0;c=0;u=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}if(r){c=-c;u=-u}if(0===h){p=Math.abs(l-t[1])*i+n;g=Math.abs(o-t[0])*i+a;m=(t[3]-t[1])*i;f=(t[2]-t[0])*i}else{p=Math.abs(o-t[0])*i+n;g=Math.abs(l-t[1])*i+a;m=(t[2]-t[0])*i;f=(t[3]-t[1])*i}this.transform=[h*i,d*i,c*i,u*i,p-h*i*o-c*i*l,g-d*i*o-u*i*l];this.width=m;this.height=f}get rawDims(){const{userUnit:t,viewBox:e}=this,i=e.map((e=>e*t));return shadow(this,"rawDims",{pageWidth:i[2]-i[0],pageHeight:i[3]-i[1],pageX:i[0],pageY:i[1]})}clone({scale:t=this.scale,rotation:e=this.rotation,offsetX:i=this.offsetX,offsetY:s=this.offsetY,dontFlip:n=!1}={}){return new PageViewport({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:t,rotation:e,offsetX:i,offsetY:s,dontFlip:n})}convertToViewportPoint(t,e){return Util.applyTransform([t,e],this.transform)}convertToViewportRectangle(t){const e=Util.applyTransform([t[0],t[1]],this.transform),i=Util.applyTransform([t[2],t[3]],this.transform);return[e[0],e[1],i[0],i[1]]}convertToPdfPoint(t,e){return Util.applyInverseTransform([t,e],this.transform)}}class RenderingCancelledException extends Q{constructor(t,e=0){super(t,"RenderingCancelledException");this.extraDelay=e}}function isDataScheme(t){const e=t.length;let i=0;for(;i=1&&s<=12?s-1:0;let n=parseInt(e[3],10);n=n>=1&&n<=31?n:1;let a=parseInt(e[4],10);a=a>=0&&a<=23?a:0;let r=parseInt(e[5],10);r=r>=0&&r<=59?r:0;let o=parseInt(e[6],10);o=o>=0&&o<=59?o:0;const l=e[7]||"Z";let h=parseInt(e[8],10);h=h>=0&&h<=23?h:0;let d=parseInt(e[9],10)||0;d=d>=0&&d<=59?d:0;if("-"===l){a+=h;r+=d}else if("+"===l){a-=h;r-=d}return new Date(Date.UTC(i,s,n,a,r,o))}}function getXfaPageViewport(t,{scale:e=1,rotation:i=0}){const{width:s,height:n}=t.attributes.style,a=[0,0,parseInt(s),parseInt(n)];return new PageViewport({viewBox:a,userUnit:1,scale:e,rotation:i})}function getRGB(t){if(t.startsWith("#")){const e=parseInt(t.slice(1),16);return[(16711680&e)>>16,(65280&e)>>8,255&e]}if(t.startsWith("rgb("))return t.slice(4,-1).split(",").map((t=>parseInt(t)));if(t.startsWith("rgba("))return t.slice(5,-1).split(",").map((t=>parseInt(t))).slice(0,3);warn(`Not a valid color format: "${t}"`);return[0,0,0]}function getCurrentTransform(t){const{a:e,b:i,c:s,d:n,e:a,f:r}=t.getTransform();return[e,i,s,n,a,r]}function getCurrentTransformInverse(t){const{a:e,b:i,c:s,d:n,e:a,f:r}=t.getTransform().invertSelf();return[e,i,s,n,a,r]}function setLayerDimensions(t,e,i=!1,s=!0){if(e instanceof PageViewport){const{pageWidth:s,pageHeight:n}=e.rawDims,{style:a}=t,r=util_FeatureTest.isCSSRoundSupported,o=`var(--scale-factor) * ${s}px`,l=`var(--scale-factor) * ${n}px`,h=r?`round(down, ${o}, var(--scale-round-x, 1px))`:`calc(${o})`,d=r?`round(down, ${l}, var(--scale-round-y, 1px))`:`calc(${l})`;if(i&&e.rotation%180!=0){a.width=d;a.height=h}else{a.width=h;a.height=d}}s&&t.setAttribute("data-main-rotation",e.rotation)}class OutputScale{constructor(){const t=window.devicePixelRatio||1;this.sx=t;this.sy=t}get scaled(){return 1!==this.sx||1!==this.sy}get symmetric(){return this.sx===this.sy}}class EditorToolbar{#s=null;#n=null;#a;#r=null;#o=null;static#l=null;constructor(t){this.#a=t;EditorToolbar.#l||=Object.freeze({freetext:"pdfjs-editor-remove-freetext-button",highlight:"pdfjs-editor-remove-highlight-button",ink:"pdfjs-editor-remove-ink-button",stamp:"pdfjs-editor-remove-stamp-button"})}render(){const t=this.#s=document.createElement("div");t.classList.add("editToolbar","hidden");t.setAttribute("role","toolbar");const e=this.#a._uiManager._signal;t.addEventListener("contextmenu",noContextMenu,{signal:e});t.addEventListener("pointerdown",EditorToolbar.#h,{signal:e});const i=this.#r=document.createElement("div");i.className="buttons";t.append(i);const s=this.#a.toolbarPosition;if(s){const{style:e}=t,i="ltr"===this.#a._uiManager.direction?1-s[0]:s[0];e.insetInlineEnd=100*i+"%";e.top=`calc(${100*s[1]}% + var(--editor-toolbar-vert-offset))`}this.#d();return t}get div(){return this.#s}static#h(t){t.stopPropagation()}#c(t){this.#a._focusEventsAllowed=!1;stopEvent(t)}#u(t){this.#a._focusEventsAllowed=!0;stopEvent(t)}#p(t){const e=this.#a._uiManager._signal;t.addEventListener("focusin",this.#c.bind(this),{capture:!0,signal:e});t.addEventListener("focusout",this.#u.bind(this),{capture:!0,signal:e});t.addEventListener("contextmenu",noContextMenu,{signal:e})}hide(){this.#s.classList.add("hidden");this.#n?.hideDropdown()}show(){this.#s.classList.remove("hidden");this.#o?.shown()}#d(){const{editorType:t,_uiManager:e}=this.#a,i=document.createElement("button");i.className="delete";i.tabIndex=0;i.setAttribute("data-l10n-id",EditorToolbar.#l[t]);this.#p(i);i.addEventListener("click",(t=>{e.delete()}),{signal:e._signal});this.#r.append(i)}get#g(){const t=document.createElement("div");t.className="divider";return t}async addAltText(t){const e=await t.render();this.#p(e);this.#r.prepend(e,this.#g);this.#o=t}addColorPicker(t){this.#n=t;const e=t.renderButton();this.#p(e);this.#r.prepend(e,this.#g)}remove(){this.#s.remove();this.#n?.destroy();this.#n=null}}class HighlightToolbar{#r=null;#s=null;#m;constructor(t){this.#m=t}#f(){const t=this.#s=document.createElement("div");t.className="editToolbar";t.setAttribute("role","toolbar");t.addEventListener("contextmenu",noContextMenu,{signal:this.#m._signal});const e=this.#r=document.createElement("div");e.className="buttons";t.append(e);this.#b();return t}#A(t,e){let i=0,s=0;for(const n of t){const t=n.y+n.height;if(ti){s=a;i=t}else e?a>s&&(s=a):a{this.#m.highlightSelection("floating_button")}),{signal:i});this.#r.append(t)}}function bindEvents(t,e,i){for(const s of i)e.addEventListener(s,t[s].bind(t))}class IdManager{#w=0;get id(){return"pdfjs_internal_editor_"+this.#w++}}class ImageManager{#v=function getUuid(){if("function"==typeof crypto.randomUUID)return crypto.randomUUID();const t=new Uint8Array(32);crypto.getRandomValues(t);return bytesToString(t)}();#w=0;#y=null;static get _isSVGFittingCanvas(){const t=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),e=new Image;e.src='data:image/svg+xml;charset=UTF-8,';return shadow(this,"_isSVGFittingCanvas",e.decode().then((()=>{t.drawImage(e,0,0,1,1,0,0,1,3);return 0===new Uint32Array(t.getImageData(0,0,1,1).data.buffer)[0]})))}async#x(t,e){this.#y||=new Map;let i=this.#y.get(t);if(null===i)return null;if(i?.bitmap){i.refCounter+=1;return i}try{i||={bitmap:null,id:`image_${this.#v}_${this.#w++}`,refCounter:0,isSvg:!1};let t;if("string"==typeof e){i.url=e;t=await fetchData(e,"blob")}else e instanceof File?t=i.file=e:e instanceof Blob&&(t=e);if("image/svg+xml"===t.type){const e=ImageManager._isSVGFittingCanvas,s=new FileReader,n=new Image,a=new Promise(((t,a)=>{n.onload=()=>{i.bitmap=n;i.isSvg=!0;t()};s.onload=async()=>{const t=i.svgUrl=s.result;n.src=await e?`${t}#svgView(preserveAspectRatio(none))`:t};n.onerror=s.onerror=a}));s.readAsDataURL(t);await a}else i.bitmap=await createImageBitmap(t);i.refCounter=1}catch(t){warn(t);i=null}this.#y.set(t,i);i&&this.#y.set(i.id,i);return i}async getFromFile(t){const{lastModified:e,name:i,size:s,type:n}=t;return this.#x(`${e}_${i}_${s}_${n}`,t)}async getFromUrl(t){return this.#x(t,t)}async getFromBlob(t,e){const i=await e;return this.#x(t,i)}async getFromId(t){this.#y||=new Map;const e=this.#y.get(t);if(!e)return null;if(e.bitmap){e.refCounter+=1;return e}if(e.file)return this.getFromFile(e.file);if(e.blobPromise){const{blobPromise:t}=e;delete e.blobPromise;return this.getFromBlob(e.id,t)}return this.getFromUrl(e.url)}getFromCanvas(t,e){this.#y||=new Map;let i=this.#y.get(t);if(i?.bitmap){i.refCounter+=1;return i}const s=new OffscreenCanvas(e.width,e.height);s.getContext("2d").drawImage(e,0,0);i={bitmap:s.transferToImageBitmap(),id:`image_${this.#v}_${this.#w++}`,refCounter:1,isSvg:!1};this.#y.set(t,i);this.#y.set(i.id,i);return i}getSvgUrl(t){const e=this.#y.get(t);return e?.isSvg?e.svgUrl:null}deleteId(t){this.#y||=new Map;const e=this.#y.get(t);if(!e)return;e.refCounter-=1;if(0!==e.refCounter)return;const{bitmap:i}=e;if(!e.url&&!e.file){const t=new OffscreenCanvas(i.width,i.height);t.getContext("bitmaprenderer").transferFromImageBitmap(i);e.blobPromise=t.convertToBlob()}i.close?.();e.bitmap=null}isValidId(t){return t.startsWith(`image_${this.#v}_`)}}class CommandManager{#_=[];#E=!1;#S;#C=-1;constructor(t=128){this.#S=t}add({cmd:t,undo:e,post:i,mustExec:s,type:n=NaN,overwriteIfSameType:a=!1,keepUndo:r=!1}){s&&t();if(this.#E)return;const o={cmd:t,undo:e,post:i,type:n};if(-1===this.#C){this.#_.length>0&&(this.#_.length=0);this.#C=0;this.#_.push(o);return}if(a&&this.#_[this.#C].type===n){r&&(o.undo=this.#_[this.#C].undo);this.#_[this.#C]=o;return}const l=this.#C+1;if(l===this.#S)this.#_.splice(0,1);else{this.#C=l;l=0;e--)if(this.#_[e].type!==t){this.#_.splice(e+1,this.#C-e);this.#C=e;return}this.#_.length=0;this.#C=-1}}destroy(){this.#_=null}}class KeyboardManager{constructor(t){this.buffer=[];this.callbacks=new Map;this.allKeys=new Set;const{isMac:e}=util_FeatureTest.platform;for(const[i,s,n={}]of t)for(const t of i){const i=t.startsWith("mac+");if(e&&i){this.callbacks.set(t.slice(4),{callback:s,options:n});this.allKeys.add(t.split("+").at(-1))}else if(!e&&!i){this.callbacks.set(t,{callback:s,options:n});this.allKeys.add(t.split("+").at(-1))}}}#T(t){t.altKey&&this.buffer.push("alt");t.ctrlKey&&this.buffer.push("ctrl");t.metaKey&&this.buffer.push("meta");t.shiftKey&&this.buffer.push("shift");this.buffer.push(t.key);const e=this.buffer.join("+");this.buffer.length=0;return e}exec(t,e){if(!this.allKeys.has(e.key))return;const i=this.callbacks.get(this.#T(e));if(!i)return;const{callback:s,options:{bubbles:n=!1,args:a=[],checker:r=null}}=i;if(!r||r(t,e)){s.bind(t,...a,e)();n||stopEvent(e)}}}class ColorManager{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){const t=new Map([["CanvasText",null],["Canvas",null]]);!function getColorValues(t){const e=document.createElement("span");e.style.visibility="hidden";document.body.append(e);for(const i of t.keys()){e.style.color=i;const s=window.getComputedStyle(e).color;t.set(i,getRGB(s))}e.remove()}(t);return shadow(this,"_colors",t)}convert(t){const e=getRGB(t);if(!window.matchMedia("(forced-colors: active)").matches)return e;for(const[t,i]of this._colors)if(i.every(((t,i)=>t===e[i])))return ColorManager._colorsMapping.get(t);return e}getHexCode(t){const e=this._colors.get(t);return e?Util.makeHexColor(...e):t}}class AnnotationEditorUIManager{#M=new AbortController;#P=null;#D=new Map;#k=new Map;#R=null;#I=null;#F=null;#L=new CommandManager;#O=null;#N=null;#B=0;#H=new Set;#z=null;#U=null;#G=new Set;_editorUndoBar=null;#$=!1;#V=!1;#j=!1;#W=null;#q=null;#X=null;#K=null;#Y=!1;#Q=null;#J=new IdManager;#Z=!1;#tt=!1;#et=null;#it=null;#st=null;#nt=null;#at=g.NONE;#rt=new Set;#ot=null;#lt=null;#ht=null;#dt={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#ct=[0,0];#ut=null;#pt=null;#gt=null;#mt=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=AnnotationEditorUIManager.prototype,arrowChecker=t=>t.#pt.contains(document.activeElement)&&"BUTTON"!==document.activeElement.tagName&&t.hasSomethingToControl(),textInputChecker=(t,{target:e})=>{if(e instanceof HTMLInputElement){const{type:t}=e;return"text"!==t&&"number"!==t}return!0},e=this.TRANSLATE_SMALL,i=this.TRANSLATE_BIG;return shadow(this,"_keyboardManager",new KeyboardManager([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:textInputChecker}],[["ctrl+z","mac+meta+z"],t.undo,{checker:textInputChecker}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:textInputChecker}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],t.delete,{checker:textInputChecker}],[["Enter","mac+Enter"],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#pt.contains(e)&&!t.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#pt.contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-e,0],checker:arrowChecker}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-i,0],checker:arrowChecker}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[e,0],checker:arrowChecker}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[i,0],checker:arrowChecker}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-e],checker:arrowChecker}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-i],checker:arrowChecker}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,e],checker:arrowChecker}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,i],checker:arrowChecker}]]))}constructor(t,e,i,s,n,a,r,o,l,h,d,c,u){const p=this._signal=this.#M.signal;this.#pt=t;this.#gt=e;this.#R=i;this._eventBus=s;s._on("editingaction",this.onEditingAction.bind(this),{signal:p});s._on("pagechanging",this.onPageChanging.bind(this),{signal:p});s._on("scalechanging",this.onScaleChanging.bind(this),{signal:p});s._on("rotationchanging",this.onRotationChanging.bind(this),{signal:p});s._on("setpreference",this.onSetPreference.bind(this),{signal:p});s._on("switchannotationeditorparams",(t=>this.updateParams(t.type,t.value)),{signal:p});this.#ft();this.#bt();this.#At();this.#I=n.annotationStorage;this.#W=n.filterFactory;this.#lt=a;this.#K=r||null;this.#$=o;this.#V=l;this.#j=h;this.#nt=d||null;this.viewParameters={realScale:PixelsPerInch.PDF_TO_CSS_UNITS,rotation:0};this.isShiftKeyDown=!1;this._editorUndoBar=c||null;this._supportsPinchToZoom=!1!==u}destroy(){this.#mt?.resolve();this.#mt=null;this.#M?.abort();this.#M=null;this._signal=null;for(const t of this.#k.values())t.destroy();this.#k.clear();this.#D.clear();this.#G.clear();this.#P=null;this.#rt.clear();this.#L.destroy();this.#R?.destroy();this.#Q?.hide();this.#Q=null;if(this.#q){clearTimeout(this.#q);this.#q=null}if(this.#ut){clearTimeout(this.#ut);this.#ut=null}this._editorUndoBar?.destroy()}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return this.#nt}get useNewAltTextFlow(){return this.#V}get useNewAltTextWhenAddingImage(){return this.#j}get hcmFilter(){return shadow(this,"hcmFilter",this.#lt?this.#W.addHCMFilter(this.#lt.foreground,this.#lt.background):"none")}get direction(){return shadow(this,"direction",getComputedStyle(this.#pt).direction)}get highlightColors(){return shadow(this,"highlightColors",this.#K?new Map(this.#K.split(",").map((t=>t.split("=").map((t=>t.trim()))))):null)}get highlightColorNames(){return shadow(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,(t=>t.reverse()))):null)}setCurrentDrawingSession(t){if(t){this.unselectAll();this.disableUserSelect(!0)}else this.disableUserSelect(!1);this.#N=t}setMainHighlightColorPicker(t){this.#st=t}editAltText(t,e=!1){this.#R?.editAltText(this,t,e)}switchToMode(t,e){this._eventBus.on("annotationeditormodechanged",e,{once:!0,signal:this._signal});this._eventBus.dispatch("showannotationeditorui",{source:this,mode:t})}setPreference(t,e){this._eventBus.dispatch("setpreference",{source:this,name:t,value:e})}onSetPreference({name:t,value:e}){if("enableNewAltTextWhenAddingImage"===t)this.#j=e}onPageChanging({pageNumber:t}){this.#B=t-1}focusMainContainer(){this.#pt.focus()}findParent(t,e){for(const i of this.#k.values()){const{x:s,y:n,width:a,height:r}=i.div.getBoundingClientRect();if(t>=s&&t<=s+a&&e>=n&&e<=n+r)return i}return null}disableUserSelect(t=!1){this.#gt.classList.toggle("noUserSelect",t)}addShouldRescale(t){this.#G.add(t)}removeShouldRescale(t){this.#G.delete(t)}onScaleChanging({scale:t}){this.commitOrRemove();this.viewParameters.realScale=t*PixelsPerInch.PDF_TO_CSS_UNITS;for(const t of this.#G)t.onScaleChanging();this.#N?.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove();this.viewParameters.rotation=t}#wt({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}#vt(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const e of this.#k.values())if(e.hasTextLayer(t))return e;return null}highlightSelection(t=""){const e=document.getSelection();if(!e||e.isCollapsed)return;const{anchorNode:i,anchorOffset:s,focusNode:n,focusOffset:a}=e,r=e.toString(),o=this.#wt(e).closest(".textLayer"),l=this.getSelectionBoxes(o);if(!l)return;e.empty();const h=this.#vt(o),d=this.#at===g.NONE,callback=()=>{h?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:l,anchorNode:i,anchorOffset:s,focusNode:n,focusOffset:a,text:r});d&&this.showAllEditors("highlight",!0,!0)};d?this.switchToMode(g.HIGHLIGHT,callback):callback()}#yt(){const t=document.getSelection();if(!t||t.isCollapsed)return;const e=this.#wt(t).closest(".textLayer"),i=this.getSelectionBoxes(e);if(i){this.#Q||=new HighlightToolbar(this);this.#Q.show(e,i,"ltr"===this.direction)}}addToAnnotationStorage(t){t.isEmpty()||!this.#I||this.#I.has(t.id)||this.#I.setValue(t.id,t)}#xt(){const t=document.getSelection();if(!t||t.isCollapsed){if(this.#ot){this.#Q?.hide();this.#ot=null;this.#_t({hasSelectedText:!1})}return}const{anchorNode:e}=t;if(e===this.#ot)return;const i=this.#wt(t).closest(".textLayer");if(i){this.#Q?.hide();this.#ot=e;this.#_t({hasSelectedText:!0});if(this.#at===g.HIGHLIGHT||this.#at===g.NONE){this.#at===g.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0);this.#Y=this.isShiftKeyDown;if(!this.isShiftKeyDown){const t=this.#at===g.HIGHLIGHT?this.#vt(i):null;t?.toggleDrawing();const e=new AbortController,s=this.combinedSignal(e),pointerup=i=>{if("pointerup"!==i.type||0===i.button){e.abort();t?.toggleDrawing(!0);"pointerup"===i.type&&this.#Et("main_toolbar")}};window.addEventListener("pointerup",pointerup,{signal:s});window.addEventListener("blur",pointerup,{signal:s})}}}else if(this.#ot){this.#Q?.hide();this.#ot=null;this.#_t({hasSelectedText:!1})}}#Et(t=""){this.#at===g.HIGHLIGHT?this.highlightSelection(t):this.#$&&this.#yt()}#ft(){document.addEventListener("selectionchange",this.#xt.bind(this),{signal:this._signal})}#St(){if(this.#X)return;this.#X=new AbortController;const t=this.combinedSignal(this.#X);window.addEventListener("focus",this.focus.bind(this),{signal:t});window.addEventListener("blur",this.blur.bind(this),{signal:t})}#Ct(){this.#X?.abort();this.#X=null}blur(){this.isShiftKeyDown=!1;if(this.#Y){this.#Y=!1;this.#Et("main_toolbar")}if(!this.hasSelection)return;const{activeElement:t}=document;for(const e of this.#rt)if(e.div.contains(t)){this.#it=[e,t];e._focusEventsAllowed=!1;break}}focus(){if(!this.#it)return;const[t,e]=this.#it;this.#it=null;e.addEventListener("focusin",(()=>{t._focusEventsAllowed=!0}),{once:!0,signal:this._signal});e.focus()}#At(){if(this.#et)return;this.#et=new AbortController;const t=this.combinedSignal(this.#et);window.addEventListener("keydown",this.keydown.bind(this),{signal:t});window.addEventListener("keyup",this.keyup.bind(this),{signal:t})}#Tt(){this.#et?.abort();this.#et=null}#Mt(){if(this.#O)return;this.#O=new AbortController;const t=this.combinedSignal(this.#O);document.addEventListener("copy",this.copy.bind(this),{signal:t});document.addEventListener("cut",this.cut.bind(this),{signal:t});document.addEventListener("paste",this.paste.bind(this),{signal:t})}#Pt(){this.#O?.abort();this.#O=null}#bt(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t});document.addEventListener("drop",this.drop.bind(this),{signal:t})}addEditListeners(){this.#At();this.#Mt()}removeEditListeners(){this.#Tt();this.#Pt()}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const i of this.#U)if(i.isHandlingMimeForPasting(e)){t.dataTransfer.dropEffect="copy";t.preventDefault();return}}drop(t){for(const e of t.dataTransfer.items)for(const i of this.#U)if(i.isHandlingMimeForPasting(e.type)){i.paste(e,this.currentLayer);t.preventDefault();return}}copy(t){t.preventDefault();this.#P?.commitOrRemove();if(!this.hasSelection)return;const e=[];for(const t of this.#rt){const i=t.serialize(!0);i&&e.push(i)}0!==e.length&&t.clipboardData.setData("application/pdfjs",JSON.stringify(e))}cut(t){this.copy(t);this.delete()}async paste(t){t.preventDefault();const{clipboardData:e}=t;for(const t of e.items)for(const e of this.#U)if(e.isHandlingMimeForPasting(t.type)){e.paste(t,this.currentLayer);return}let i=e.getData("application/pdfjs");if(!i)return;try{i=JSON.parse(i)}catch(t){warn(`paste: "${t.message}".`);return}if(!Array.isArray(i))return;this.unselectAll();const s=this.currentLayer;try{const t=[];for(const e of i){const i=await s.deserialize(e);if(!i)return;t.push(i)}const cmd=()=>{for(const e of t)this.#Dt(e);this.#kt(t)},undo=()=>{for(const e of t)e.remove()};this.addCommands({cmd,undo,mustExec:!0})}catch(t){warn(`paste: "${t.message}".`)}}keydown(t){this.isShiftKeyDown||"Shift"!==t.key||(this.isShiftKeyDown=!0);this.#at===g.NONE||this.isEditorHandlingKeyboard||AnnotationEditorUIManager._keyboardManager.exec(this,t)}keyup(t){if(this.isShiftKeyDown&&"Shift"===t.key){this.isShiftKeyDown=!1;if(this.#Y){this.#Y=!1;this.#Et("main_toolbar")}}}onEditingAction({name:t}){switch(t){case"undo":case"redo":case"delete":case"selectAll":this[t]();break;case"highlightSelection":this.highlightSelection("context_menu")}}#_t(t){if(Object.entries(t).some((([t,e])=>this.#dt[t]!==e))){this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#dt,t)});this.#at===g.HIGHLIGHT&&!1===t.hasSelectedEditor&&this.#Rt([[m.HIGHLIGHT_FREE,!0]])}}#Rt(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){if(t){this.#St();this.#Mt();this.#_t({isEditing:this.#at!==g.NONE,isEmpty:this.#It(),hasSomethingToUndo:this.#L.hasSomethingToUndo(),hasSomethingToRedo:this.#L.hasSomethingToRedo(),hasSelectedEditor:!1})}else{this.#Ct();this.#Pt();this.#_t({isEditing:!1});this.disableUserSelect(!1)}}registerEditorTypes(t){if(!this.#U){this.#U=t;for(const t of this.#U)this.#Rt(t.defaultPropertiesToUpdate)}}getId(){return this.#J.id}get currentLayer(){return this.#k.get(this.#B)}getLayer(t){return this.#k.get(t)}get currentPageIndex(){return this.#B}addLayer(t){this.#k.set(t.pageIndex,t);this.#Z?t.enable():t.disable()}removeLayer(t){this.#k.delete(t.pageIndex)}async updateMode(t,e=null,i=!1){if(this.#at!==t){if(this.#mt){await this.#mt.promise;if(!this.#mt)return}this.#mt=Promise.withResolvers();this.#at=t;if(t!==g.NONE){this.setEditingState(!0);await this.#Ft();this.unselectAll();for(const e of this.#k.values())e.updateMode(t);if(e){for(const t of this.#D.values())if(t.annotationElementId===e){this.setSelected(t);t.enterInEditMode()}else t.unselect();this.#mt.resolve()}else{i&&this.addNewEditorFromKeyboard();this.#mt.resolve()}}else{this.setEditingState(!1);this.#Lt();this._editorUndoBar?.hide();this.#mt.resolve()}}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==this.#at&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,e){if(this.#U){switch(t){case m.CREATE:this.currentLayer.addNewEditor();return;case m.HIGHLIGHT_DEFAULT_COLOR:this.#st?.updateColor(e);break;case m.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}});(this.#ht||=new Map).set(t,e);this.showAllEditors("highlight",e)}for(const i of this.#rt)i.updateParams(t,e);for(const i of this.#U)i.updateDefaultParams(t,e)}}showAllEditors(t,e,i=!1){for(const i of this.#D.values())i.editorType===t&&i.show(e);(this.#ht?.get(m.HIGHLIGHT_SHOW_ALL)??!0)!==e&&this.#Rt([[m.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(this.#tt!==t){this.#tt=t;for(const e of this.#k.values()){t?e.disableClick():e.enableClick();e.div.classList.toggle("waiting",t)}}}async#Ft(){if(!this.#Z){this.#Z=!0;const t=[];for(const e of this.#k.values())t.push(e.enable());await Promise.all(t);for(const t of this.#D.values())t.enable()}}#Lt(){this.unselectAll();if(this.#Z){this.#Z=!1;for(const t of this.#k.values())t.disable();for(const t of this.#D.values())t.disable()}}getEditors(t){const e=[];for(const i of this.#D.values())i.pageIndex===t&&e.push(i);return e}getEditor(t){return this.#D.get(t)}addEditor(t){this.#D.set(t.id,t)}removeEditor(t){if(t.div.contains(document.activeElement)){this.#q&&clearTimeout(this.#q);this.#q=setTimeout((()=>{this.focusMainContainer();this.#q=null}),0)}this.#D.delete(t.id);this.unselect(t);t.annotationElementId&&this.#H.has(t.annotationElementId)||this.#I?.remove(t.id)}addDeletedAnnotationElement(t){this.#H.add(t.annotationElementId);this.addChangedExistingAnnotation(t);t.deleted=!0}isDeletedAnnotationElement(t){return this.#H.has(t)}removeDeletedAnnotationElement(t){this.#H.delete(t.annotationElementId);this.removeChangedExistingAnnotation(t);t.deleted=!1}#Dt(t){const e=this.#k.get(t.pageIndex);if(e)e.addOrRebuild(t);else{this.addEditor(t);this.addToAnnotationStorage(t)}}setActiveEditor(t){if(this.#P!==t){this.#P=t;t&&this.#Rt(t.propertiesToUpdate)}}get#Ot(){let t=null;for(t of this.#rt);return t}updateUI(t){this.#Ot===t&&this.#Rt(t.propertiesToUpdate)}updateUIForDefaultProperties(t){this.#Rt(t.defaultPropertiesToUpdate)}toggleSelected(t){if(this.#rt.has(t)){this.#rt.delete(t);t.unselect();this.#_t({hasSelectedEditor:this.hasSelection})}else{this.#rt.add(t);t.select();this.#Rt(t.propertiesToUpdate);this.#_t({hasSelectedEditor:!0})}}setSelected(t){this.#N?.commitOrRemove();for(const e of this.#rt)e!==t&&e.unselect();this.#rt.clear();this.#rt.add(t);t.select();this.#Rt(t.propertiesToUpdate);this.#_t({hasSelectedEditor:!0})}isSelected(t){return this.#rt.has(t)}get firstSelectedEditor(){return this.#rt.values().next().value}unselect(t){t.unselect();this.#rt.delete(t);this.#_t({hasSelectedEditor:this.hasSelection})}get hasSelection(){return 0!==this.#rt.size}get isEnterHandled(){return 1===this.#rt.size&&this.firstSelectedEditor.isEnterHandled}undo(){this.#L.undo();this.#_t({hasSomethingToUndo:this.#L.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#It()});this._editorUndoBar?.hide()}redo(){this.#L.redo();this.#_t({hasSomethingToUndo:!0,hasSomethingToRedo:this.#L.hasSomethingToRedo(),isEmpty:this.#It()})}addCommands(t){this.#L.add(t);this.#_t({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#It()})}cleanUndoStack(t){this.#L.cleanType(t)}#It(){if(0===this.#D.size)return!0;if(1===this.#D.size)for(const t of this.#D.values())return t.isEmpty();return!1}delete(){this.commitOrRemove();const t=this.currentLayer?.endDrawingSession(!0);if(!this.hasSelection&&!t)return;const e=t?[t]:[...this.#rt],undo=()=>{for(const t of e)this.#Dt(t)};this.addCommands({cmd:()=>{this._editorUndoBar?.show(undo,1===e.length?e[0].editorType:e.length);for(const t of e)t.remove()},undo,mustExec:!0})}commitOrRemove(){this.#P?.commitOrRemove()}hasSomethingToControl(){return this.#P||this.hasSelection}#kt(t){for(const t of this.#rt)t.unselect();this.#rt.clear();for(const e of t)if(!e.isEmpty()){this.#rt.add(e);e.select()}this.#_t({hasSelectedEditor:this.hasSelection})}selectAll(){for(const t of this.#rt)t.commit();this.#kt(this.#D.values())}unselectAll(){if(this.#P){this.#P.commitOrRemove();if(this.#at!==g.NONE)return}if(!this.#N?.commitOrRemove()&&this.hasSelection){for(const t of this.#rt)t.unselect();this.#rt.clear();this.#_t({hasSelectedEditor:!1})}}translateSelectedEditors(t,e,i=!1){i||this.commitOrRemove();if(!this.hasSelection)return;this.#ct[0]+=t;this.#ct[1]+=e;const[s,n]=this.#ct,a=[...this.#rt];this.#ut&&clearTimeout(this.#ut);this.#ut=setTimeout((()=>{this.#ut=null;this.#ct[0]=this.#ct[1]=0;this.addCommands({cmd:()=>{for(const t of a)this.#D.has(t.id)&&t.translateInPage(s,n)},undo:()=>{for(const t of a)this.#D.has(t.id)&&t.translateInPage(-s,-n)},mustExec:!1})}),1e3);for(const i of a)i.translateInPage(t,e)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0);this.#z=new Map;for(const t of this.#rt)this.#z.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#z)return!1;this.disableUserSelect(!1);const t=this.#z;this.#z=null;let e=!1;for(const[{x:i,y:s,pageIndex:n},a]of t){a.newX=i;a.newY=s;a.newPageIndex=n;e||=i!==a.savedX||s!==a.savedY||n!==a.savedPageIndex}if(!e)return!1;const move=(t,e,i,s)=>{if(this.#D.has(t.id)){const n=this.#k.get(s);if(n)t._setParentAndPosition(n,e,i);else{t.pageIndex=s;t.x=e;t.y=i}}};this.addCommands({cmd:()=>{for(const[e,{newX:i,newY:s,newPageIndex:n}]of t)move(e,i,s,n)},undo:()=>{for(const[e,{savedX:i,savedY:s,savedPageIndex:n}]of t)move(e,i,s,n)},mustExec:!0});return!0}dragSelectedEditors(t,e){if(this.#z)for(const i of this.#z.keys())i.drag(t,e)}rebuild(t){if(null===t.parent){const e=this.getLayer(t.pageIndex);if(e){e.changeParent(t);e.addOrRebuild(t)}else{this.addEditor(t);this.addToAnnotationStorage(t);t.rebuild()}}else t.parent.addOrRebuild(t)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||1===this.#rt.size&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#P===t}getActive(){return this.#P}getMode(){return this.#at}get imageManager(){return shadow(this,"imageManager",new ImageManager)}getSelectionBoxes(t){if(!t)return null;const e=document.getSelection();for(let i=0,s=e.rangeCount;i({x:(e-s)/a,y:1-(t+r-i)/n,width:o/a,height:r/n});break;case"180":r=(t,e,r,o)=>({x:1-(t+r-i)/n,y:1-(e+o-s)/a,width:r/n,height:o/a});break;case"270":r=(t,e,r,o)=>({x:1-(e+o-s)/a,y:(t-i)/n,width:o/a,height:r/n});break;default:r=(t,e,r,o)=>({x:(t-i)/n,y:(e-s)/a,width:r/n,height:o/a})}const o=[];for(let t=0,i=e.rangeCount;tt.stopPropagation()),{signal:i});const onClick=t=>{t.preventDefault();this.#a._uiManager.editAltText(this.#a);this.#Wt&&this.#a._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:this.#Xt}})};t.addEventListener("click",onClick,{capture:!0,signal:i});t.addEventListener("keydown",(e=>{if(e.target===t&&"Enter"===e.key){this.#Gt=!0;onClick(e)}}),{signal:i});await this.#Kt();return t}get#Xt(){return(this.#o?"added":null===this.#o&&this.guessedText&&"review")||"missing"}finish(){if(this.#Bt){this.#Bt.focus({focusVisible:this.#Gt});this.#Gt=!1}}isEmpty(){return this.#Wt?null===this.#o:!this.#o&&!this.#Nt}hasData(){return this.#Wt?null!==this.#o||!!this.#Vt:this.isEmpty()}get guessedText(){return this.#Vt}async setGuessedText(t){if(null===this.#o){this.#Vt=t;this.#jt=await AltText._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t});this.#Kt()}}toggleAltTextBadge(t=!1){if(this.#Wt&&!this.#o){if(!this.#$t){const t=this.#$t=document.createElement("div");t.className="noAltTextBadge";this.#a.div.append(t)}this.#$t.classList.toggle("hidden",!t)}else{this.#$t?.remove();this.#$t=null}}serialize(t){let e=this.#o;t||this.#Vt!==e||(e=this.#jt);return{altText:e,decorative:this.#Nt,guessedText:this.#Vt,textWithDisclaimer:this.#jt}}get data(){return{altText:this.#o,decorative:this.#Nt}}set data({altText:t,decorative:e,guessedText:i,textWithDisclaimer:s,cancel:n=!1}){if(i){this.#Vt=i;this.#jt=s}if(this.#o!==t||this.#Nt!==e){if(!n){this.#o=t;this.#Nt=e}this.#Kt()}}toggle(t=!1){if(this.#Bt){if(!t&&this.#Ut){clearTimeout(this.#Ut);this.#Ut=null}this.#Bt.disabled=!t}}shown(){this.#a._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:this.#Xt}})}destroy(){this.#Bt?.remove();this.#Bt=null;this.#Ht=null;this.#zt=null;this.#$t?.remove();this.#$t=null}async#Kt(){const t=this.#Bt;if(!t)return;if(this.#Wt){t.classList.toggle("done",!!this.#o);t.setAttribute("data-l10n-id",AltText.#qt[this.#Xt]);this.#Ht?.setAttribute("data-l10n-id",AltText.#qt[`${this.#Xt}-label`]);if(!this.#o){this.#zt?.remove();return}}else{if(!this.#o&&!this.#Nt){t.classList.remove("done");this.#zt?.remove();return}t.classList.add("done");t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let e=this.#zt;if(!e){this.#zt=e=document.createElement("span");e.className="tooltip";e.setAttribute("role","tooltip");e.id=`alt-text-tooltip-${this.#a.id}`;const i=100,s=this.#a._uiManager._signal;s.addEventListener("abort",(()=>{clearTimeout(this.#Ut);this.#Ut=null}),{once:!0});t.addEventListener("mouseenter",(()=>{this.#Ut=setTimeout((()=>{this.#Ut=null;this.#zt.classList.add("show");this.#a._reportTelemetry({action:"alt_text_tooltip"})}),i)}),{signal:s});t.addEventListener("mouseleave",(()=>{if(this.#Ut){clearTimeout(this.#Ut);this.#Ut=null}this.#zt?.classList.remove("show")}),{signal:s})}if(this.#Nt)e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip");else{e.removeAttribute("data-l10n-id");e.textContent=this.#o}e.parentNode||t.append(e);const i=this.#a.getImageForAltText();i?.setAttribute("aria-describedby",e.id)}}class TouchManager{#pt;#Yt=!1;#Qt=null;#Jt;#Zt;#te;#ee;#ie;#se=null;#ne;#ae=null;constructor({container:t,isPinchingDisabled:e=null,isPinchingStopped:i=null,onPinchStart:s=null,onPinching:n=null,onPinchEnd:a=null,signal:r}){this.#pt=t;this.#Qt=i;this.#Jt=e;this.#Zt=s;this.#te=n;this.#ee=a;this.#ne=new AbortController;this.#ie=AbortSignal.any([r,this.#ne.signal]);t.addEventListener("touchstart",this.#re.bind(this),{passive:!1,signal:this.#ie})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return shadow(this,"MIN_TOUCH_DISTANCE_TO_PINCH",35/(window.devicePixelRatio||1))}#re(t){if(this.#Jt?.()||t.touches.length<2)return;if(!this.#ae){this.#ae=new AbortController;const t=AbortSignal.any([this.#ie,this.#ae.signal]),e=this.#pt,i={signal:t,passive:!1};e.addEventListener("touchmove",this.#oe.bind(this),i);e.addEventListener("touchend",this.#le.bind(this),i);e.addEventListener("touchcancel",this.#le.bind(this),i);this.#Zt?.()}stopEvent(t);if(2!==t.touches.length||this.#Qt?.()){this.#se=null;return}let[e,i]=t.touches;e.identifier>i.identifier&&([e,i]=[i,e]);this.#se={touch0X:e.screenX,touch0Y:e.screenY,touch1X:i.screenX,touch1Y:i.screenY}}#oe(t){if(!this.#se||2!==t.touches.length)return;let[e,i]=t.touches;e.identifier>i.identifier&&([e,i]=[i,e]);const{screenX:s,screenY:n}=e,{screenX:a,screenY:r}=i,o=this.#se,{touch0X:l,touch0Y:h,touch1X:d,touch1Y:c}=o,u=d-l,p=c-h,g=a-s,m=r-n,f=Math.hypot(g,m)||1,b=Math.hypot(u,p)||1;if(!this.#Yt&&Math.abs(b-f)<=TouchManager.MIN_TOUCH_DISTANCE_TO_PINCH)return;o.touch0X=s;o.touch0Y=n;o.touch1X=a;o.touch1Y=r;t.preventDefault();if(!this.#Yt){this.#Yt=!0;return}const A=[(s+a)/2,(n+r)/2];this.#te?.(A,b,f)}#le(t){this.#ae.abort();this.#ae=null;this.#ee?.();if(this.#se){t.preventDefault();this.#se=null;this.#Yt=!1}}destroy(){this.#ne?.abort();this.#ne=null}}class AnnotationEditor{#he=null;#de=null;#o=null;#ce=!1;#ue=null;#pe="";#ge=!1;#me=null;#fe=null;#be=null;#Ae=null;#we="";#ve=!1;#ye=null;#xe=!1;#_e=!1;#Ee=!1;#Se=null;#Ce=0;#Te=0;#Me=null;#Pe=null;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nResizer=null;#De=!1;#ke=AnnotationEditor._zIndex++;static _borderLineWidth=-1;static _colorManager=new ColorManager;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){const t=AnnotationEditor.prototype._resizeWithKeyboard,e=AnnotationEditorUIManager.TRANSLATE_SMALL,i=AnnotationEditorUIManager.TRANSLATE_BIG;return shadow(this,"_resizerKeyboardManager",new KeyboardManager([[["ArrowLeft","mac+ArrowLeft"],t,{args:[-e,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-i,0]}],[["ArrowRight","mac+ArrowRight"],t,{args:[e,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[i,0]}],[["ArrowUp","mac+ArrowUp"],t,{args:[0,-e]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-i]}],[["ArrowDown","mac+ArrowDown"],t,{args:[0,e]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,i]}],[["Escape","mac+Escape"],AnnotationEditor.prototype._stopResizingWithKeyboard]]))}constructor(t){this.parent=t.parent;this.id=t.id;this.width=this.height=null;this.pageIndex=t.parent.pageIndex;this.name=t.name;this.div=null;this._uiManager=t.uiManager;this.annotationElementId=null;this._willKeepAspectRatio=!1;this._initialOptions.isCentered=t.isCentered;this._structTreeParentId=null;const{rotation:e,rawDims:{pageWidth:i,pageHeight:s,pageX:n,pageY:a}}=this.parent.viewport;this.rotation=e;this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360;this.pageDimensions=[i,s];this.pageTranslation=[n,a];const[r,o]=this.parentDimensions;this.x=t.x/r;this.y=t.y/o;this.isAttachedToDOM=!1;this.deleted=!1}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get isDrawer(){return!1}static get _defaultLineColor(){return shadow(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new FakeEditor({id:t.parent.getNextId(),parent:t.parent,uiManager:t._uiManager});e.annotationElementId=t.annotationElementId;e.deleted=!0;e._uiManager.addToAnnotationStorage(e)}static initialize(t,e){AnnotationEditor._l10n??=t;AnnotationEditor._l10nResizer||=Object.freeze({topLeft:"pdfjs-editor-resizer-top-left",topMiddle:"pdfjs-editor-resizer-top-middle",topRight:"pdfjs-editor-resizer-top-right",middleRight:"pdfjs-editor-resizer-middle-right",bottomRight:"pdfjs-editor-resizer-bottom-right",bottomMiddle:"pdfjs-editor-resizer-bottom-middle",bottomLeft:"pdfjs-editor-resizer-bottom-left",middleLeft:"pdfjs-editor-resizer-middle-left"});if(-1!==AnnotationEditor._borderLineWidth)return;const i=getComputedStyle(document.documentElement);AnnotationEditor._borderLineWidth=parseFloat(i.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){unreachable("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#De}set _isDraggable(t){this.#De=t;this.div?.classList.toggle("draggable",t)}get isEnterHandled(){return!0}center(){const[t,e]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*e/(2*t);this.y+=this.width*t/(2*e);break;case 180:this.x+=this.width/2;this.y+=this.height/2;break;case 270:this.x+=this.height*e/(2*t);this.y-=this.width*t/(2*e);break;default:this.x-=this.width/2;this.y-=this.height/2}this.fixAndSetPosition()}addCommands(t){this._uiManager.addCommands(t)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#ke}setParent(t){if(null!==t){this.pageIndex=t.pageIndex;this.pageDimensions=t.pageDimensions}else this.#Re();this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#ve?this.#ve=!1:this.parent.setSelected(this))}focusout(t){if(!this._focusEventsAllowed)return;if(!this.isAttachedToDOM)return;const e=t.relatedTarget;if(!e?.closest(`#${this.id}`)){t.preventDefault();this.parent?.isMultipleSelection||this.commitOrRemove()}}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(t,e,i,s){const[n,a]=this.parentDimensions;[i,s]=this.screenToPageTranslation(i,s);this.x=(t+i)/n;this.y=(e+s)/a;this.fixAndSetPosition()}#Ie([t,e],i,s){[i,s]=this.screenToPageTranslation(i,s);this.x+=i/t;this.y+=s/e;this._onTranslating(this.x,this.y);this.fixAndSetPosition()}translate(t,e){this.#Ie(this.parentDimensions,t,e)}translateInPage(t,e){this.#ye||=[this.x,this.y,this.width,this.height];this.#Ie(this.pageDimensions,t,e);this.div.scrollIntoView({block:"nearest"})}drag(t,e){this.#ye||=[this.x,this.y,this.width,this.height];const{div:i,parentDimensions:[s,n]}=this;this.x+=t/s;this.y+=e/n;if(this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:t,y:e}=this.div.getBoundingClientRect();if(this.parent.findNewParent(this,t,e)){this.x-=Math.floor(this.x);this.y-=Math.floor(this.y)}}let{x:a,y:r}=this;const[o,l]=this.getBaseTranslation();a+=o;r+=l;const{style:h}=i;h.left=`${(100*a).toFixed(2)}%`;h.top=`${(100*r).toFixed(2)}%`;this._onTranslating(a,r);i.scrollIntoView({block:"nearest"})}_onTranslating(t,e){}_onTranslated(t,e){}get _hasBeenMoved(){return!!this.#ye&&(this.#ye[0]!==this.x||this.#ye[1]!==this.y)}get _hasBeenResized(){return!!this.#ye&&(this.#ye[2]!==this.width||this.#ye[3]!==this.height)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:i}=AnnotationEditor,s=i/t,n=i/e;switch(this.rotation){case 90:return[-s,n];case 180:return[s,n];case 270:return[s,-n];default:return[-s,-n]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const{div:{style:e},pageDimensions:[i,s]}=this;let{x:n,y:a,width:r,height:o}=this;r*=i;o*=s;n*=i;a*=s;if(this._mustFixPosition)switch(t){case 0:n=Math.max(0,Math.min(i-r,n));a=Math.max(0,Math.min(s-o,a));break;case 90:n=Math.max(0,Math.min(i-o,n));a=Math.min(s,Math.max(r,a));break;case 180:n=Math.min(i,Math.max(r,n));a=Math.min(s,Math.max(o,a));break;case 270:n=Math.min(i,Math.max(o,n));a=Math.max(0,Math.min(s-r,a))}this.x=n/=i;this.y=a/=s;const[l,h]=this.getBaseTranslation();n+=l;a+=h;e.left=`${(100*n).toFixed(2)}%`;e.top=`${(100*a).toFixed(2)}%`;this.moveInDOM()}static#Fe(t,e,i){switch(i){case 90:return[e,-t];case 180:return[-t,-e];case 270:return[-e,t];default:return[t,e]}}screenToPageTranslation(t,e){return AnnotationEditor.#Fe(t,e,this.parentRotation)}pageTranslationToScreen(t,e){return AnnotationEditor.#Fe(t,e,360-this.parentRotation)}#Le(t){switch(t){case 90:{const[t,e]=this.pageDimensions;return[0,-t/e,e/t,0]}case 180:return[-1,0,0,-1];case 270:{const[t,e]=this.pageDimensions;return[0,t/e,-e/t,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:t,pageDimensions:[e,i]}=this;return[e*t,i*t]}setDims(t,e){const[i,s]=this.parentDimensions,{style:n}=this.div;n.width=`${(100*t/i).toFixed(2)}%`;this.#ge||(n.height=`${(100*e/s).toFixed(2)}%`)}fixDims(){const{style:t}=this.div,{height:e,width:i}=t,s=i.endsWith("%"),n=!this.#ge&&e.endsWith("%");if(s&&n)return;const[a,r]=this.parentDimensions;s||(t.width=`${(100*parseFloat(i)/a).toFixed(2)}%`);this.#ge||n||(t.height=`${(100*parseFloat(e)/r).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}#Oe(){if(this.#me)return;this.#me=document.createElement("div");this.#me.classList.add("resizers");const t=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],e=this._uiManager._signal;for(const i of t){const t=document.createElement("div");this.#me.append(t);t.classList.add("resizer",i);t.setAttribute("data-resizer-name",i);t.addEventListener("pointerdown",this.#Ne.bind(this,i),{signal:e});t.addEventListener("contextmenu",noContextMenu,{signal:e});t.tabIndex=-1}this.div.prepend(this.#me)}#Ne(t,e){e.preventDefault();const{isMac:i}=util_FeatureTest.platform;if(0!==e.button||e.ctrlKey&&i)return;this.#o?.toggle(!1);const s=this._isDraggable;this._isDraggable=!1;this.#fe=[e.screenX,e.screenY];const n=new AbortController,a=this._uiManager.combinedSignal(n);this.parent.togglePointerEvents(!1);window.addEventListener("pointermove",this.#Be.bind(this,t),{passive:!0,capture:!0,signal:a});window.addEventListener("touchmove",stopEvent,{passive:!1,signal:a});window.addEventListener("contextmenu",noContextMenu,{signal:a});this.#be={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const r=this.parent.div.style.cursor,o=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const pointerUpCallback=()=>{n.abort();this.parent.togglePointerEvents(!0);this.#o?.toggle(!0);this._isDraggable=s;this.parent.div.style.cursor=r;this.div.style.cursor=o;this.#He()};window.addEventListener("pointerup",pointerUpCallback,{signal:a});window.addEventListener("blur",pointerUpCallback,{signal:a})}#ze(t,e,i,s){this.width=i;this.height=s;this.x=t;this.y=e;const[n,a]=this.parentDimensions;this.setDims(n*i,a*s);this.fixAndSetPosition();this._onResized()}_onResized(){}#He(){if(!this.#be)return;const{savedX:t,savedY:e,savedWidth:i,savedHeight:s}=this.#be;this.#be=null;const n=this.x,a=this.y,r=this.width,o=this.height;n===t&&a===e&&r===i&&o===s||this.addCommands({cmd:this.#ze.bind(this,n,a,r,o),undo:this.#ze.bind(this,t,e,i,s),mustExec:!0})}static _round(t){return Math.round(1e4*t)/1e4}#Be(t,e){const[i,s]=this.parentDimensions,n=this.x,a=this.y,r=this.width,o=this.height,l=AnnotationEditor.MIN_SIZE/i,h=AnnotationEditor.MIN_SIZE/s,d=this.#Le(this.rotation),transf=(t,e)=>[d[0]*t+d[2]*e,d[1]*t+d[3]*e],c=this.#Le(360-this.rotation);let u,p,g=!1,m=!1;switch(t){case"topLeft":g=!0;u=(t,e)=>[0,0];p=(t,e)=>[t,e];break;case"topMiddle":u=(t,e)=>[t/2,0];p=(t,e)=>[t/2,e];break;case"topRight":g=!0;u=(t,e)=>[t,0];p=(t,e)=>[0,e];break;case"middleRight":m=!0;u=(t,e)=>[t,e/2];p=(t,e)=>[0,e/2];break;case"bottomRight":g=!0;u=(t,e)=>[t,e];p=(t,e)=>[0,0];break;case"bottomMiddle":u=(t,e)=>[t/2,e];p=(t,e)=>[t/2,0];break;case"bottomLeft":g=!0;u=(t,e)=>[0,e];p=(t,e)=>[t,0];break;case"middleLeft":m=!0;u=(t,e)=>[0,e/2];p=(t,e)=>[t,e/2]}const f=u(r,o),b=p(r,o);let A=transf(...b);const w=AnnotationEditor._round(n+A[0]),v=AnnotationEditor._round(a+A[1]);let y,x,_=1,E=1;if(e.fromKeyboard)({deltaX:y,deltaY:x}=e);else{const{screenX:t,screenY:i}=e,[s,n]=this.#fe;[y,x]=this.screenToPageTranslation(t-s,i-n);this.#fe[0]=t;this.#fe[1]=i}[y,x]=(S=y/i,C=x/s,[c[0]*S+c[2]*C,c[1]*S+c[3]*C]);var S,C;if(g){const t=Math.hypot(r,o);_=E=Math.max(Math.min(Math.hypot(b[0]-f[0]-y,b[1]-f[1]-x)/t,1/r,1/o),l/r,h/o)}else m?_=Math.max(l,Math.min(1,Math.abs(b[0]-f[0]-y)))/r:E=Math.max(h,Math.min(1,Math.abs(b[1]-f[1]-x)))/o;const T=AnnotationEditor._round(r*_),M=AnnotationEditor._round(o*E);A=transf(...p(T,M));const P=w-A[0],D=v-A[1];this.#ye||=[this.x,this.y,this.width,this.height];this.width=T;this.height=M;this.x=P;this.y=D;this.setDims(i*T,s*M);this.fixAndSetPosition();this._onResizing()}_onResizing(){}altTextFinish(){this.#o?.finish()}async addEditToolbar(){if(this._editToolbar||this.#_e)return this._editToolbar;this._editToolbar=new EditorToolbar(this);this.div.append(this._editToolbar.render());this.#o&&await this._editToolbar.addAltText(this.#o);return this._editToolbar}removeEditToolbar(){if(this._editToolbar){this._editToolbar.remove();this._editToolbar=null;this.#o?.destroy()}}addContainer(t){const e=this._editToolbar?.div;e?e.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){if(!this.#o){AltText.initialize(AnnotationEditor._l10n);this.#o=new AltText(this);if(this.#he){this.#o.data=this.#he;this.#he=null}await this.addEditToolbar()}}get altTextData(){return this.#o?.data}set altTextData(t){this.#o&&(this.#o.data=t)}get guessedAltText(){return this.#o?.guessedText}async setGuessedAltText(t){await(this.#o?.setGuessedText(t))}serializeAltText(t){return this.#o?.serialize(t)}hasAltText(){return!!this.#o&&!this.#o.isEmpty()}hasAltTextData(){return this.#o?.hasData()??!1}render(){this.div=document.createElement("div");this.div.setAttribute("data-editor-rotation",(360-this.rotation)%360);this.div.className=this.name;this.div.setAttribute("id",this.id);this.div.tabIndex=this.#ce?-1:0;this._isVisible||this.div.classList.add("hidden");this.setInForeground();this.#Ue();const[t,e]=this.parentDimensions;if(this.parentRotation%180!=0){this.div.style.maxWidth=`${(100*e/t).toFixed(2)}%`;this.div.style.maxHeight=`${(100*t/e).toFixed(2)}%`}const[i,s]=this.getInitialTranslation();this.translate(i,s);bindEvents(this,this.div,["pointerdown"]);this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#Pe||=new TouchManager({container:this.div,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#Ge.bind(this),onPinching:this.#$e.bind(this),onPinchEnd:this.#Ve.bind(this),signal:this._uiManager._signal}));this._uiManager._editorUndoBar?.hide();return this.div}#Ge(){this.#be={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};this.#o?.toggle(!1);this.parent.togglePointerEvents(!1)}#$e(t,e,i){let s=i/e*.7+1-.7;if(1===s)return;const n=this.#Le(this.rotation),transf=(t,e)=>[n[0]*t+n[2]*e,n[1]*t+n[3]*e],[a,r]=this.parentDimensions,o=this.x,l=this.y,h=this.width,d=this.height,c=AnnotationEditor.MIN_SIZE/a,u=AnnotationEditor.MIN_SIZE/r;s=Math.max(Math.min(s,1/h,1/d),c/h,u/d);const p=AnnotationEditor._round(h*s),g=AnnotationEditor._round(d*s);if(p===h&&g===d)return;this.#ye||=[o,l,h,d];const m=transf(h/2,d/2),f=AnnotationEditor._round(o+m[0]),b=AnnotationEditor._round(l+m[1]),A=transf(p/2,g/2);this.x=f-A[0];this.y=b-A[1];this.width=p;this.height=g;this.setDims(a*p,r*g);this.fixAndSetPosition();this._onResizing()}#Ve(){this.#o?.toggle(!0);this.parent.togglePointerEvents(!0);this.#He()}pointerdown(t){const{isMac:e}=util_FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)t.preventDefault();else{this.#ve=!0;this._isDraggable?this.#je(t):this.#We(t)}}get isSelected(){return this._uiManager.isSelected(this)}#We(t){const{isMac:e}=util_FeatureTest.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)}#je(t){const{isSelected:e}=this;this._uiManager.setUpDragSession();let i=!1;const s=new AbortController,n=this._uiManager.combinedSignal(s),a={capture:!0,passive:!1,signal:n},cancelDrag=t=>{s.abort();this.#ue=null;this.#ve=!1;this._uiManager.endDragSession()||this.#We(t);i&&this._onStopDragging()};if(e){this.#Ce=t.clientX;this.#Te=t.clientY;this.#ue=t.pointerId;this.#pe=t.pointerType;window.addEventListener("pointermove",(t=>{if(!i){i=!0;this._onStartDragging()}const{clientX:e,clientY:s,pointerId:n}=t;if(n!==this.#ue){stopEvent(t);return}const[a,r]=this.screenToPageTranslation(e-this.#Ce,s-this.#Te);this.#Ce=e;this.#Te=s;this._uiManager.dragSelectedEditors(a,r)}),a);window.addEventListener("touchmove",stopEvent,a);window.addEventListener("pointerdown",(t=>{t.pointerType===this.#pe&&(this.#Pe||t.isPrimary)&&cancelDrag(t);stopEvent(t)}),a)}const pointerUpCallback=t=>{this.#ue&&this.#ue!==t.pointerId?stopEvent(t):cancelDrag(t)};window.addEventListener("pointerup",pointerUpCallback,{signal:n});window.addEventListener("blur",pointerUpCallback,{signal:n})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#Se&&clearTimeout(this.#Se);this.#Se=setTimeout((()=>{this.#Se=null;this.parent?.moveEditorInDOM(this)}),0)}_setParentAndPosition(t,e,i){t.changeParent(this);this.x=e;this.y=i;this.fixAndSetPosition();this._onTranslated()}getRect(t,e,i=this.rotation){const s=this.parentScale,[n,a]=this.pageDimensions,[r,o]=this.pageTranslation,l=t/s,h=e/s,d=this.x*n,c=this.y*a,u=this.width*n,p=this.height*a;switch(i){case 0:return[d+l+r,a-c-h-p+o,d+l+u+r,a-c-h+o];case 90:return[d+h+r,a-c+l+o,d+h+p+r,a-c+l+u+o];case 180:return[d-l-u+r,a-c+h+o,d-l+r,a-c+h+p+o];case 270:return[d-h-p+r,a-c-l-u+o,d-h+r,a-c-l+o];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,e){const[i,s,n,a]=t,r=n-i,o=a-s;switch(this.rotation){case 0:return[i,e-a,r,o];case 90:return[i,e-s,o,r];case 180:return[n,e-s,r,o];case 270:return[n,e-a,o,r];default:throw new Error("Invalid rotation")}}onceAdded(t){}isEmpty(){return!1}enableEditMode(){this.#_e=!0}disableEditMode(){this.#_e=!1}isInEditMode(){return this.#_e}shouldGetKeyboardEvents(){return this.#Ee}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){const{top:t,left:e,bottom:i,right:s}=this.getClientDimensions(),{innerHeight:n,innerWidth:a}=window;return e0&&t0}#Ue(){if(this.#Ae||!this.div)return;this.#Ae=new AbortController;const t=this._uiManager.combinedSignal(this.#Ae);this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t});this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})}rebuild(){this.#Ue()}rotate(t){}resize(){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||""}}serialize(t=!1,e=null){unreachable("An editor must be serializable")}static async deserialize(t,e,i){const s=new this.prototype.constructor({parent:e,id:e.getNextId(),uiManager:i});s.rotation=t.rotation;s.#he=t.accessibilityData;const[n,a]=s.pageDimensions,[r,o,l,h]=s.getRectInCurrentCoords(t.rect,a);s.x=r/n;s.y=o/a;s.width=l/n;s.height=h/a;return s}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||null!==this.serialize())}remove(){this.#Ae?.abort();this.#Ae=null;this.isEmpty()||this.commit();this.parent?this.parent.remove(this):this._uiManager.removeEditor(this);if(this.#Se){clearTimeout(this.#Se);this.#Se=null}this.#Re();this.removeEditToolbar();if(this.#Me){for(const t of this.#Me.values())clearTimeout(t);this.#Me=null}this.parent=null;this.#Pe?.destroy();this.#Pe=null}get isResizable(){return!1}makeResizable(){if(this.isResizable){this.#Oe();this.#me.classList.remove("hidden");bindEvents(this,this.div,["keydown"])}}get toolbarPosition(){return null}keydown(t){if(!this.isResizable||t.target!==this.div||"Enter"!==t.key)return;this._uiManager.setSelected(this);this.#be={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const e=this.#me.children;if(!this.#de){this.#de=Array.from(e);const t=this.#qe.bind(this),i=this.#Xe.bind(this),s=this._uiManager._signal;for(const e of this.#de){const n=e.getAttribute("data-resizer-name");e.setAttribute("role","spinbutton");e.addEventListener("keydown",t,{signal:s});e.addEventListener("blur",i,{signal:s});e.addEventListener("focus",this.#Ke.bind(this,n),{signal:s});e.setAttribute("data-l10n-id",AnnotationEditor._l10nResizer[n])}}const i=this.#de[0];let s=0;for(const t of e){if(t===i)break;s++}const n=(360-this.rotation+this.parentRotation)%360/90*(this.#de.length/4);if(n!==s){if(ns)for(let t=0;t{this.div?.classList.contains("selectedEditor")&&this._editToolbar?.show()}))}unselect(){this.#me?.classList.add("hidden");this.div?.classList.remove("selectedEditor");this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0});this._editToolbar?.hide();this.#o?.toggleAltTextBadge(!0)}updateParams(t,e){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return this.#xe}set isEditing(t){this.#xe=t;if(this.parent)if(t){this.parent.setSelected(this);this.parent.setActiveEditor(this)}else this.parent.setActiveEditor(null)}setAspectRatio(t,e){this.#ge=!0;const i=t/e,{style:s}=this.div;s.aspectRatio=i;s.height="auto"}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(t,e=!1){if(e){this.#Me||=new Map;const{action:e}=t;let i=this.#Me.get(e);i&&clearTimeout(i);i=setTimeout((()=>{this._reportTelemetry(t);this.#Me.delete(e);0===this.#Me.size&&(this.#Me=null)}),AnnotationEditor._telemetryTimeout);this.#Me.set(e,i)}else{t.type||=this.editorType;this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:t}})}}show(t=this._isVisible){this.div.classList.toggle("hidden",!t);this._isVisible=t}enable(){this.div&&(this.div.tabIndex=0);this.#ce=!1}disable(){this.div&&(this.div.tabIndex=-1);this.#ce=!0}renderAnnotationElement(t){let e=t.container.querySelector(".annotationContent");if(e){if("CANVAS"===e.nodeName){const t=e;e=document.createElement("div");e.classList.add("annotationContent",this.editorType);t.before(e)}}else{e=document.createElement("div");e.classList.add("annotationContent",this.editorType);t.container.prepend(e)}return e}resetAnnotationElement(t){const{firstChild:e}=t.container;"DIV"===e?.nodeName&&e.classList.contains("annotationContent")&&e.remove()}}class FakeEditor extends AnnotationEditor{constructor(t){super(t);this.annotationElementId=t.annotationElementId;this.deleted=!0}serialize(){return this.serializeDeleted()}}const st=3285377520,nt=4294901760,at=65535;class MurmurHash3_64{constructor(t){this.h1=t?4294967295&t:st;this.h2=t?4294967295&t:st}update(t){let e,i;if("string"==typeof t){e=new Uint8Array(2*t.length);i=0;for(let s=0,n=t.length;s>>8;e[i++]=255&n}}}else{if(!ArrayBuffer.isView(t))throw new Error("Invalid data format, must be a string or TypedArray.");e=t.slice();i=e.byteLength}const s=i>>2,n=i-4*s,a=new Uint32Array(e.buffer,0,s);let r=0,o=0,l=this.h1,h=this.h2;const d=3432918353,c=461845907,u=11601,p=13715;for(let t=0;t>>17;r=r*c&nt|r*p&at;l^=r;l=l<<13|l>>>19;l=5*l+3864292196}else{o=a[t];o=o*d&nt|o*u&at;o=o<<15|o>>>17;o=o*c&nt|o*p&at;h^=o;h=h<<13|h>>>19;h=5*h+3864292196}r=0;switch(n){case 3:r^=e[4*s+2]<<16;case 2:r^=e[4*s+1]<<8;case 1:r^=e[4*s];r=r*d&nt|r*u&at;r=r<<15|r>>>17;r=r*c&nt|r*p&at;1&s?l^=r:h^=r}this.h1=l;this.h2=h}hexdigest(){let t=this.h1,e=this.h2;t^=e>>>1;t=3981806797*t&nt|36045*t&at;e=4283543511*e&nt|(2950163797*(e<<16|t>>>16)&nt)>>>16;t^=e>>>1;t=444984403*t&nt|60499*t&at;e=3301882366*e&nt|(3120437893*(e<<16|t>>>16)&nt)>>>16;t^=e>>>1;return(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const rt=Object.freeze({map:null,hash:"",transfer:void 0});class AnnotationStorage{#Qe=!1;#Je=null;#Ze=new Map;constructor(){this.onSetModified=null;this.onResetModified=null;this.onAnnotationEditor=null}getValue(t,e){const i=this.#Ze.get(t);return void 0===i?e:Object.assign(e,i)}getRawValue(t){return this.#Ze.get(t)}remove(t){this.#Ze.delete(t);0===this.#Ze.size&&this.resetModified();if("function"==typeof this.onAnnotationEditor){for(const t of this.#Ze.values())if(t instanceof AnnotationEditor)return;this.onAnnotationEditor(null)}}setValue(t,e){const i=this.#Ze.get(t);let s=!1;if(void 0!==i){for(const[t,n]of Object.entries(e))if(i[t]!==n){s=!0;i[t]=n}}else{s=!0;this.#Ze.set(t,e)}s&&this.#ti();e instanceof AnnotationEditor&&"function"==typeof this.onAnnotationEditor&&this.onAnnotationEditor(e.constructor._type)}has(t){return this.#Ze.has(t)}getAll(){return this.#Ze.size>0?objectFromMap(this.#Ze):null}setAll(t){for(const[e,i]of Object.entries(t))this.setValue(e,i)}get size(){return this.#Ze.size}#ti(){if(!this.#Qe){this.#Qe=!0;"function"==typeof this.onSetModified&&this.onSetModified()}}resetModified(){if(this.#Qe){this.#Qe=!1;"function"==typeof this.onResetModified&&this.onResetModified()}}get print(){return new PrintAnnotationStorage(this)}get serializable(){if(0===this.#Ze.size)return rt;const t=new Map,e=new MurmurHash3_64,i=[],s=Object.create(null);let n=!1;for(const[i,a]of this.#Ze){const r=a instanceof AnnotationEditor?a.serialize(!1,s):a;if(r){t.set(i,r);e.update(`${i}:${JSON.stringify(r)}`);n||=!!r.bitmap}}if(n)for(const e of t.values())e.bitmap&&i.push(e.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:i}:rt}get editorStats(){let t=null;const e=new Map;for(const i of this.#Ze.values()){if(!(i instanceof AnnotationEditor))continue;const s=i.telemetryFinalData;if(!s)continue;const{type:n}=s;e.has(n)||e.set(n,Object.getPrototypeOf(i).constructor);t||=Object.create(null);const a=t[n]||=new Map;for(const[t,e]of Object.entries(s)){if("type"===t)continue;let i=a.get(t);if(!i){i=new Map;a.set(t,i)}const s=i.get(e)??0;i.set(e,s+1)}}for(const[i,s]of e)t[i]=s.computeTelemetryFinalData(t[i]);return t}resetModifiedIds(){this.#Je=null}get modifiedIds(){if(this.#Je)return this.#Je;const t=[];for(const e of this.#Ze.values())e instanceof AnnotationEditor&&e.annotationElementId&&e.serialize()&&t.push(e.annotationElementId);return this.#Je={ids:new Set(t),hash:t.join(",")}}}class PrintAnnotationStorage extends AnnotationStorage{#ei;constructor(t){super();const{map:e,hash:i,transfer:s}=t.serializable,n=structuredClone(e,s?{transfer:s}:null);this.#ei={map:n,hash:i,transfer:s}}get print(){unreachable("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#ei}get modifiedIds(){return shadow(this,"modifiedIds",{ids:new Set,hash:""})}}class FontLoader{#ii=new Set;constructor({ownerDocument:t=globalThis.document,styleElement:e=null}){this._document=t;this.nativeFontFaces=new Set;this.styleElement=null;this.loadingRequests=[];this.loadTestFontId=0}addNativeFontFace(t){this.nativeFontFaces.add(t);this._document.fonts.add(t)}removeNativeFontFace(t){this.nativeFontFaces.delete(t);this._document.fonts.delete(t)}insertRule(t){if(!this.styleElement){this.styleElement=this._document.createElement("style");this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement)}const e=this.styleElement.sheet;e.insertRule(t,e.cssRules.length)}clear(){for(const t of this.nativeFontFaces)this._document.fonts.delete(t);this.nativeFontFaces.clear();this.#ii.clear();if(this.styleElement){this.styleElement.remove();this.styleElement=null}}async loadSystemFont({systemFontInfo:t,_inspectFont:e}){if(t&&!this.#ii.has(t.loadedName)){assert(!this.disableFontFace,"loadSystemFont shouldn't be called when `disableFontFace` is set.");if(this.isFontLoadingAPISupported){const{loadedName:i,src:s,style:n}=t,a=new FontFace(i,s,n);this.addNativeFontFace(a);try{await a.load();this.#ii.add(i);e?.(t)}catch{warn(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`);this.removeNativeFontFace(a)}}else unreachable("Not implemented: loadSystemFont without the Font Loading API.")}}async bind(t){if(t.attached||t.missingFile&&!t.systemFontInfo)return;t.attached=!0;if(t.systemFontInfo){await this.loadSystemFont(t);return}if(this.isFontLoadingAPISupported){const e=t.createNativeFontFace();if(e){this.addNativeFontFace(e);try{await e.loaded}catch(i){warn(`Failed to load font '${e.family}': '${i}'.`);t.disableFontFace=!0;throw i}}return}const e=t.createFontFaceRule();if(e){this.insertRule(e);if(this.isSyncFontLoadingSupported)return;await new Promise((e=>{const i=this._queueLoadingCallback(e);this._prepareFontLoadEvent(t,i)}))}}get isFontLoadingAPISupported(){return shadow(this,"isFontLoadingAPISupported",!!this._document?.fonts)}get isSyncFontLoadingSupported(){let t=!1;(e||"undefined"!=typeof navigator&&"string"==typeof navigator?.userAgent&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(t=!0);return shadow(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){const{loadingRequests:e}=this,i={done:!1,complete:function completeRequest(){assert(!i.done,"completeRequest() cannot be called twice.");i.done=!0;for(;e.length>0&&e[0].done;){const t=e.shift();setTimeout(t.callback,0)}},callback:t};e.push(i);return i}get _loadTestFont(){return shadow(this,"_loadTestFont",atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA=="))}_prepareFontLoadEvent(t,e){function int32(t,e){return t.charCodeAt(e)<<24|t.charCodeAt(e+1)<<16|t.charCodeAt(e+2)<<8|255&t.charCodeAt(e+3)}function spliceString(t,e,i,s){return t.substring(0,e)+s+t.substring(e+i)}let i,s;const n=this._document.createElement("canvas");n.width=1;n.height=1;const a=n.getContext("2d");let r=0;const o=`lt${Date.now()}${this.loadTestFontId++}`;let l=this._loadTestFont;l=spliceString(l,976,o.length,o);const h=1482184792;let d=int32(l,16);for(i=0,s=o.length-3;i>24&255,t>>16&255,t>>8&255,255&t)}(d));const c=`@font-face {font-family:"${o}";src:${`url(data:font/opentype;base64,${btoa(l)});`}}`;this.insertRule(c);const u=this._document.createElement("div");u.style.visibility="hidden";u.style.width=u.style.height="10px";u.style.position="absolute";u.style.top=u.style.left="0px";for(const e of[t.loadedName,o]){const t=this._document.createElement("span");t.textContent="Hi";t.style.fontFamily=e;u.append(t)}this._document.body.append(u);!function isFontReady(t,e){if(++r>30){warn("Load test font never loaded.");e();return}a.font="30px "+t;a.fillText(".",0,20);a.getImageData(0,0,1,1).data[3]>0?e():setTimeout(isFontReady.bind(null,t,e))}(o,(()=>{u.remove();e.complete()}))}}class FontFaceObject{constructor(t,{disableFontFace:e=!1,fontExtraProperties:i=!1,inspectFont:s=null}){this.compiledGlyphs=Object.create(null);for(const e in t)this[e]=t[e];this.disableFontFace=!0===e;this.fontExtraProperties=!0===i;this._inspectFont=s}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let t;if(this.cssFontInfo){const e={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(e.style=`oblique ${this.cssFontInfo.italicAngle}deg`);t=new FontFace(this.cssFontInfo.fontFamily,this.data,e)}else t=new FontFace(this.loadedName,this.data,{});this._inspectFont?.(this);return t}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;const t=`url(data:${this.mimetype};base64,${function toBase64Util(t){return Uint8Array.prototype.toBase64?t.toBase64():btoa(bytesToString(t))}(this.data)});`;let e;if(this.cssFontInfo){let i=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(i+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`);e=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${i}src:${t}}`}else e=`@font-face {font-family:"${this.loadedName}";src:${t}}`;this._inspectFont?.(this,t);return e}getPathGenerator(t,e){if(void 0!==this.compiledGlyphs[e])return this.compiledGlyphs[e];const i=this.loadedName+"_path_"+e;let s;try{s=t.get(i)}catch(t){warn(`getPathGenerator - ignoring character: "${t}".`)}const n=new Path2D(s||"");this.fontExtraProperties||t.delete(i);return this.compiledGlyphs[e]=n}}const ot=1,lt=2,ht=1,dt=2,ct=3,ut=4,pt=5,gt=6,mt=7,ft=8;function onFn(){}function wrapReason(t){if(t instanceof AbortException||t instanceof InvalidPDFException||t instanceof MissingPDFException||t instanceof PasswordException||t instanceof UnexpectedResponseException||t instanceof UnknownErrorException)return t;t instanceof Error||"object"==typeof t&&null!==t||unreachable('wrapReason: Expected "reason" to be a (possibly cloned) Error.');switch(t.name){case"AbortException":return new AbortException(t.message);case"InvalidPDFException":return new InvalidPDFException(t.message);case"MissingPDFException":return new MissingPDFException(t.message);case"PasswordException":return new PasswordException(t.message,t.code);case"UnexpectedResponseException":return new UnexpectedResponseException(t.message,t.status);case"UnknownErrorException":return new UnknownErrorException(t.message,t.details)}return new UnknownErrorException(t.message,t.toString())}class MessageHandler{#si=new AbortController;constructor(t,e,i){this.sourceName=t;this.targetName=e;this.comObj=i;this.callbackId=1;this.streamId=1;this.streamSinks=Object.create(null);this.streamControllers=Object.create(null);this.callbackCapabilities=Object.create(null);this.actionHandler=Object.create(null);i.addEventListener("message",this.#ni.bind(this),{signal:this.#si.signal})}#ni({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream){this.#ai(t);return}if(t.callback){const e=t.callbackId,i=this.callbackCapabilities[e];if(!i)throw new Error(`Cannot resolve callback ${e}`);delete this.callbackCapabilities[e];if(t.callback===ot)i.resolve(t.data);else{if(t.callback!==lt)throw new Error("Unexpected callback case");i.reject(wrapReason(t.reason))}return}const e=this.actionHandler[t.action];if(!e)throw new Error(`Unknown action from worker: ${t.action}`);if(t.callbackId){const i=this.sourceName,s=t.sourceName,n=this.comObj;Promise.try(e,t.data).then((function(e){n.postMessage({sourceName:i,targetName:s,callback:ot,callbackId:t.callbackId,data:e})}),(function(e){n.postMessage({sourceName:i,targetName:s,callback:lt,callbackId:t.callbackId,reason:wrapReason(e)})}))}else t.streamId?this.#ri(t):e(t.data)}on(t,e){const i=this.actionHandler;if(i[t])throw new Error(`There is already an actionName called "${t}"`);i[t]=e}send(t,e,i){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,data:e},i)}sendWithPromise(t,e,i){const s=this.callbackId++,n=Promise.withResolvers();this.callbackCapabilities[s]=n;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:s,data:e},i)}catch(t){n.reject(t)}return n.promise}sendWithStream(t,e,i,s){const n=this.streamId++,a=this.sourceName,r=this.targetName,o=this.comObj;return new ReadableStream({start:i=>{const l=Promise.withResolvers();this.streamControllers[n]={controller:i,startCall:l,pullCall:null,cancelCall:null,isClosed:!1};o.postMessage({sourceName:a,targetName:r,action:t,streamId:n,data:e,desiredSize:i.desiredSize},s);return l.promise},pull:t=>{const e=Promise.withResolvers();this.streamControllers[n].pullCall=e;o.postMessage({sourceName:a,targetName:r,stream:gt,streamId:n,desiredSize:t.desiredSize});return e.promise},cancel:t=>{assert(t instanceof Error,"cancel must have a valid reason");const e=Promise.withResolvers();this.streamControllers[n].cancelCall=e;this.streamControllers[n].isClosed=!0;o.postMessage({sourceName:a,targetName:r,stream:ht,streamId:n,reason:wrapReason(t)});return e.promise}},i)}#ri(t){const e=t.streamId,i=this.sourceName,s=t.sourceName,n=this.comObj,a=this,r=this.actionHandler[t.action],o={enqueue(t,a=1,r){if(this.isCancelled)return;const o=this.desiredSize;this.desiredSize-=a;if(o>0&&this.desiredSize<=0){this.sinkCapability=Promise.withResolvers();this.ready=this.sinkCapability.promise}n.postMessage({sourceName:i,targetName:s,stream:ut,streamId:e,chunk:t},r)},close(){if(!this.isCancelled){this.isCancelled=!0;n.postMessage({sourceName:i,targetName:s,stream:ct,streamId:e});delete a.streamSinks[e]}},error(t){assert(t instanceof Error,"error must have a valid reason");if(!this.isCancelled){this.isCancelled=!0;n.postMessage({sourceName:i,targetName:s,stream:pt,streamId:e,reason:wrapReason(t)})}},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};o.sinkCapability.resolve();o.ready=o.sinkCapability.promise;this.streamSinks[e]=o;Promise.try(r,t.data,o).then((function(){n.postMessage({sourceName:i,targetName:s,stream:ft,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:i,targetName:s,stream:ft,streamId:e,reason:wrapReason(t)})}))}#ai(t){const e=t.streamId,i=this.sourceName,s=t.sourceName,n=this.comObj,a=this.streamControllers[e],r=this.streamSinks[e];switch(t.stream){case ft:t.success?a.startCall.resolve():a.startCall.reject(wrapReason(t.reason));break;case mt:t.success?a.pullCall.resolve():a.pullCall.reject(wrapReason(t.reason));break;case gt:if(!r){n.postMessage({sourceName:i,targetName:s,stream:mt,streamId:e,success:!0});break}r.desiredSize<=0&&t.desiredSize>0&&r.sinkCapability.resolve();r.desiredSize=t.desiredSize;Promise.try(r.onPull||onFn).then((function(){n.postMessage({sourceName:i,targetName:s,stream:mt,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:i,targetName:s,stream:mt,streamId:e,reason:wrapReason(t)})}));break;case ut:assert(a,"enqueue should have stream controller");if(a.isClosed)break;a.controller.enqueue(t.chunk);break;case ct:assert(a,"close should have stream controller");if(a.isClosed)break;a.isClosed=!0;a.controller.close();this.#oi(a,e);break;case pt:assert(a,"error should have stream controller");a.controller.error(wrapReason(t.reason));this.#oi(a,e);break;case dt:t.success?a.cancelCall.resolve():a.cancelCall.reject(wrapReason(t.reason));this.#oi(a,e);break;case ht:if(!r)break;const o=wrapReason(t.reason);Promise.try(r.onCancel||onFn,o).then((function(){n.postMessage({sourceName:i,targetName:s,stream:dt,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:i,targetName:s,stream:dt,streamId:e,reason:wrapReason(t)})}));r.sinkCapability.reject(o);r.isCancelled=!0;delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}}async#oi(t,e){await Promise.allSettled([t.startCall?.promise,t.pullCall?.promise,t.cancelCall?.promise]);delete this.streamControllers[e]}destroy(){this.#si?.abort();this.#si=null}}class BaseCanvasFactory{#li=!1;constructor({enableHWA:t=!1}){this.#li=t}create(t,e){if(t<=0||e<=0)throw new Error("Invalid canvas size");const i=this._createCanvas(t,e);return{canvas:i,context:i.getContext("2d",{willReadFrequently:!this.#li})}}reset(t,e,i){if(!t.canvas)throw new Error("Canvas is not specified");if(e<=0||i<=0)throw new Error("Invalid canvas size");t.canvas.width=e;t.canvas.height=i}destroy(t){if(!t.canvas)throw new Error("Canvas is not specified");t.canvas.width=0;t.canvas.height=0;t.canvas=null;t.context=null}_createCanvas(t,e){unreachable("Abstract method `_createCanvas` called.")}}class BaseCMapReaderFactory{constructor({baseUrl:t=null,isCompressed:e=!0}){this.baseUrl=t;this.isCompressed=e}async fetch({name:t}){if(!this.baseUrl)throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.");if(!t)throw new Error("CMap name must be specified.");const e=this.baseUrl+t+(this.isCompressed?".bcmap":"");return this._fetch(e).then((t=>({cMapData:t,isCompressed:this.isCompressed}))).catch((t=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${e}`)}))}async _fetch(t){unreachable("Abstract method `_fetch` called.")}}class DOMCMapReaderFactory extends BaseCMapReaderFactory{async _fetch(t){const e=await fetchData(t,this.isCompressed?"arraybuffer":"text");return e instanceof ArrayBuffer?new Uint8Array(e):stringToBytes(e)}}class BaseFilterFactory{addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addHighlightHCMFilter(t,e,i,s,n){return"none"}destroy(t=!1){}}class BaseStandardFontDataFactory{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");if(!t)throw new Error("Font filename must be specified.");const e=`${this.baseUrl}${t}`;return this._fetch(e).catch((t=>{throw new Error(`Unable to load font data at: ${e}`)}))}async _fetch(t){unreachable("Abstract method `_fetch` called.")}}class DOMStandardFontDataFactory extends BaseStandardFontDataFactory{async _fetch(t){const e=await fetchData(t,"arraybuffer");return new Uint8Array(e)}}e&&warn("Please use the `legacy` build in Node.js environments.");async function node_utils_fetchData(t){const e=process.getBuiltinModule("fs"),i=await e.promises.readFile(t);return new Uint8Array(i)}const bt="Fill",At="Stroke",wt="Shading";function applyBoundingBox(t,e){if(!e)return;const i=e[2]-e[0],s=e[3]-e[1],n=new Path2D;n.rect(e[0],e[1],i,s);t.clip(n)}class BaseShadingPattern{getPattern(){unreachable("Abstract method `getPattern` called.")}}class RadialAxialShadingPattern extends BaseShadingPattern{constructor(t){super();this._type=t[1];this._bbox=t[2];this._colorStops=t[3];this._p0=t[4];this._p1=t[5];this._r0=t[6];this._r1=t[7];this.matrix=null}_createGradient(t){let e;"axial"===this._type?e=t.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):"radial"===this._type&&(e=t.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(const t of this._colorStops)e.addColorStop(t[0],t[1]);return e}getPattern(t,e,i,s){let n;if(s===At||s===bt){const a=e.current.getClippedPathBoundingBox(s,getCurrentTransform(t))||[0,0,0,0],r=Math.ceil(a[2]-a[0])||1,o=Math.ceil(a[3]-a[1])||1,l=e.cachedCanvases.getCanvas("pattern",r,o),h=l.context;h.clearRect(0,0,h.canvas.width,h.canvas.height);h.beginPath();h.rect(0,0,h.canvas.width,h.canvas.height);h.translate(-a[0],-a[1]);i=Util.transform(i,[1,0,0,1,a[0],a[1]]);h.transform(...e.baseTransform);this.matrix&&h.transform(...this.matrix);applyBoundingBox(h,this._bbox);h.fillStyle=this._createGradient(h);h.fill();n=t.createPattern(l.canvas,"no-repeat");const d=new DOMMatrix(i);n.setTransform(d)}else{applyBoundingBox(t,this._bbox);n=this._createGradient(t)}return n}}function drawTriangle(t,e,i,s,n,a,r,o){const l=e.coords,h=e.colors,d=t.data,c=4*t.width;let u;if(l[i+1]>l[s+1]){u=i;i=s;s=u;u=a;a=r;r=u}if(l[s+1]>l[n+1]){u=s;s=n;n=u;u=r;r=o;o=u}if(l[i+1]>l[s+1]){u=i;i=s;s=u;u=a;a=r;r=u}const p=(l[i]+e.offsetX)*e.scaleX,g=(l[i+1]+e.offsetY)*e.scaleY,m=(l[s]+e.offsetX)*e.scaleX,f=(l[s+1]+e.offsetY)*e.scaleY,b=(l[n]+e.offsetX)*e.scaleX,A=(l[n+1]+e.offsetY)*e.scaleY;if(g>=A)return;const w=h[a],v=h[a+1],y=h[a+2],x=h[r],_=h[r+1],E=h[r+2],S=h[o],C=h[o+1],T=h[o+2],M=Math.round(g),P=Math.round(A);let D,k,R,I,F,L,O,N;for(let t=M;t<=P;t++){if(tA?1:f===A?0:(f-t)/(f-A);D=m-(m-b)*e;k=x-(x-S)*e;R=_-(_-C)*e;I=E-(E-T)*e}let e;e=tA?1:(g-t)/(g-A);F=p-(p-b)*e;L=w-(w-S)*e;O=v-(v-C)*e;N=y-(y-T)*e;const i=Math.round(Math.min(D,F)),s=Math.round(Math.max(D,F));let n=c*t+4*i;for(let t=i;t<=s;t++){e=(D-t)/(D-F);e<0?e=0:e>1&&(e=1);d[n++]=k-(k-L)*e|0;d[n++]=R-(R-O)*e|0;d[n++]=I-(I-N)*e|0;d[n++]=255}}}function drawFigure(t,e,i){const s=e.coords,n=e.colors;let a,r;switch(e.type){case"lattice":const o=e.verticesPerRow,l=Math.floor(s.length/o)-1,h=o-1;for(a=0;a=Math.ceil(p*b)?w=o:y=!0;E>=Math.ceil(g*A)?v=l:x=!0;const S=this.getSizeAndScale(w,this.ctx.canvas.width,b),C=this.getSizeAndScale(v,this.ctx.canvas.height,A),T=t.cachedCanvases.getCanvas("pattern",S.size,C.size),M=T.context,P=r.createCanvasGraphics(M);P.groupLevel=t.groupLevel;this.setFillAndStrokeStyleToContext(P,s,a);M.translate(-S.scale*h,-C.scale*d);P.transform(S.scale,0,0,C.scale,0,0);M.save();this.clipBbox(P,h,d,c,u);P.baseTransform=getCurrentTransform(P.ctx);P.executeOperatorList(i);P.endDrawing();M.restore();if(y||x){const e=T.canvas;y&&(w=o);x&&(v=l);const i=this.getSizeAndScale(w,this.ctx.canvas.width,b),s=this.getSizeAndScale(v,this.ctx.canvas.height,A),n=i.size,a=s.size,r=t.cachedCanvases.getCanvas("pattern-workaround",n,a),c=r.context,u=y?Math.floor(p/o):0,m=x?Math.floor(g/l):0;for(let t=0;t<=u;t++)for(let i=0;i<=m;i++)c.drawImage(e,n*t,a*i,n,a,0,0,n,a);return{canvas:r.canvas,scaleX:i.scale,scaleY:s.scale,offsetX:h,offsetY:d}}return{canvas:T.canvas,scaleX:S.scale,scaleY:C.scale,offsetX:h,offsetY:d}}getSizeAndScale(t,e,i){const s=Math.max(TilingPattern.MAX_PATTERN_SIZE,e);let n=Math.ceil(t*i);n>=s?n=s:i=n/t;return{scale:i,size:n}}clipBbox(t,e,i,s,n){const a=s-e,r=n-i;t.ctx.rect(e,i,a,r);t.current.updateRectMinMax(getCurrentTransform(t.ctx),[e,i,s,n]);t.clip();t.endPath()}setFillAndStrokeStyleToContext(t,e,i){const s=t.ctx,n=t.current;switch(e){case vt:const t=this.ctx;s.fillStyle=t.fillStyle;s.strokeStyle=t.strokeStyle;n.fillColor=t.fillStyle;n.strokeColor=t.strokeStyle;break;case yt:const a=Util.makeHexColor(i[0],i[1],i[2]);s.fillStyle=a;s.strokeStyle=a;n.fillColor=a;n.strokeColor=a;break;default:throw new FormatError(`Unsupported paint type: ${e}`)}}getPattern(t,e,i,s){let n=i;if(s!==wt){n=Util.transform(n,e.baseTransform);this.matrix&&(n=Util.transform(n,this.matrix))}const a=this.createPatternCanvas(e);let r=new DOMMatrix(n);r=r.translate(a.offsetX,a.offsetY);r=r.scale(1/a.scaleX,1/a.scaleY);const o=t.createPattern(a.canvas,"repeat");o.setTransform(r);return o}}function convertBlackAndWhiteToRGBA({src:t,srcPos:e=0,dest:i,width:s,height:n,nonBlackColor:a=4294967295,inverseDecode:r=!1}){const o=util_FeatureTest.isLittleEndian?4278190080:255,[l,h]=r?[a,o]:[o,a],d=s>>3,c=7&s,u=t.length;i=new Uint32Array(i.buffer);let p=0;for(let s=0;s>2),m=i.length,f=s+7>>3,b=4294967295,A=util_FeatureTest.isLittleEndian?4278190080:255;for(u=0;uf?s:8*t-7,r=-8&a;let o=0,c=0;for(;n>=1}}for(;l=a){g=n;m=s*g}l=0;for(p=m;p--;){c[l++]=d[h++];c[l++]=d[h++];c[l++]=d[h++];c[l++]=255}t.putImageData(o,0,u*xt)}}}function putBinaryImageMask(t,e){if(e.bitmap){t.drawImage(e.bitmap,0,0);return}const i=e.height,s=e.width,n=i%xt,a=(i-n)/xt,r=0===n?a:a+1,o=t.createImageData(s,xt);let l=0;const h=e.data,d=o.data;for(let e=0;e10&&"function"==typeof i,h=l?Date.now()+15:0;let d=0;const c=this.commonObjs,u=this.objs;let p;for(;;){if(void 0!==s&&r===s.nextBreakPoint){s.breakIt(r,i);return r}p=a[r];if(p!==X.dependency)this[p].apply(this,n[r]);else for(const t of n[r]){const e=t.startsWith("g_")?c:u;if(!e.has(t)){e.get(t,i);return r}}r++;if(r===o)return r;if(l&&++d>10){if(Date.now()>h){i();return r}d=0}}}#hi(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null;this.ctx.restore();if(this.transparentCanvas){this.ctx=this.compositeCtx;this.ctx.save();this.ctx.setTransform(1,0,0,1,0,0);this.ctx.drawImage(this.transparentCanvas,0,0);this.ctx.restore();this.transparentCanvas=null}}endDrawing(){this.#hi();this.cachedCanvases.clear();this.cachedPatterns.clear();for(const t of this._cachedBitmapsMap.values()){for(const e of t.values())"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement&&(e.width=e.height=0);t.clear()}this._cachedBitmapsMap.clear();this.#di()}#di(){if(this.pageColors){const t=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if("none"!==t){const e=this.ctx.filter;this.ctx.filter=t;this.ctx.drawImage(this.ctx.canvas,0,0);this.ctx.filter=e}}}_scaleImage(t,e){const i=t.width??t.displayWidth,s=t.height??t.displayHeight;let n,a,r=Math.max(Math.hypot(e[0],e[1]),1),o=Math.max(Math.hypot(e[2],e[3]),1),l=i,h=s,d="prescale1";for(;r>2&&l>1||o>2&&h>1;){let e=l,i=h;if(r>2&&l>1){e=l>=16384?Math.floor(l/2)-1||1:Math.ceil(l/2);r/=l/e}if(o>2&&h>1){i=h>=16384?Math.floor(h/2)-1||1:Math.ceil(h)/2;o/=h/i}n=this.cachedCanvases.getCanvas(d,e,i);a=n.context;a.clearRect(0,0,e,i);a.drawImage(t,0,0,l,h,0,0,e,i);t=n.canvas;l=e;h=i;d="prescale1"===d?"prescale2":"prescale1"}return{img:t,paintWidth:l,paintHeight:h}}_createMaskCanvas(t){const e=this.ctx,{width:i,height:s}=t,n=this.current.fillColor,a=this.current.patternFill,r=getCurrentTransform(e);let o,l,h,d;if((t.bitmap||t.data)&&t.count>1){const e=t.bitmap||t.data.buffer;l=JSON.stringify(a?r:[r.slice(0,4),n]);o=this._cachedBitmapsMap.get(e);if(!o){o=new Map;this._cachedBitmapsMap.set(e,o)}const i=o.get(l);if(i&&!a){return{canvas:i,offsetX:Math.round(Math.min(r[0],r[2])+r[4]),offsetY:Math.round(Math.min(r[1],r[3])+r[5])}}h=i}if(!h){d=this.cachedCanvases.getCanvas("maskCanvas",i,s);putBinaryImageMask(d.context,t)}let c=Util.transform(r,[1/i,0,0,-1/s,0,0]);c=Util.transform(c,[1,0,0,1,0,-s]);const[u,p,g,m]=Util.getAxialAlignedBoundingBox([0,0,i,s],c),f=Math.round(g-u)||1,b=Math.round(m-p)||1,A=this.cachedCanvases.getCanvas("fillCanvas",f,b),w=A.context,v=u,y=p;w.translate(-v,-y);w.transform(...c);if(!h){h=this._scaleImage(d.canvas,getCurrentTransformInverse(w));h=h.img;o&&a&&o.set(l,h)}w.imageSmoothingEnabled=getImageSmoothingEnabled(getCurrentTransform(w),t.interpolate);drawImageAtIntegerCoords(w,h,0,0,h.width,h.height,0,0,i,s);w.globalCompositeOperation="source-in";const x=Util.transform(getCurrentTransformInverse(w),[1,0,0,1,-v,-y]);w.fillStyle=a?n.getPattern(e,this,x,bt):n;w.fillRect(0,0,i,s);if(o&&!a){this.cachedCanvases.delete("fillCanvas");o.set(l,A.canvas)}return{canvas:A.canvas,offsetX:Math.round(v),offsetY:Math.round(y)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1);this.current.lineWidth=t;this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=_t[t]}setLineJoin(t){this.ctx.lineJoin=Et[t]}setMiterLimit(t){this.ctx.miterLimit=t}setDash(t,e){const i=this.ctx;if(void 0!==i.setLineDash){i.setLineDash(t);i.lineDashOffset=e}}setRenderingIntent(t){}setFlatness(t){}setGState(t){for(const[e,i]of t)switch(e){case"LW":this.setLineWidth(i);break;case"LC":this.setLineCap(i);break;case"LJ":this.setLineJoin(i);break;case"ML":this.setMiterLimit(i);break;case"D":this.setDash(i[0],i[1]);break;case"RI":this.setRenderingIntent(i);break;case"FL":this.setFlatness(i);break;case"Font":this.setFont(i[0],i[1]);break;case"CA":this.current.strokeAlpha=i;break;case"ca":this.current.fillAlpha=i;this.ctx.globalAlpha=i;break;case"BM":this.ctx.globalCompositeOperation=i;break;case"SMask":this.current.activeSMask=i?this.tempSMask:null;this.tempSMask=null;this.checkSMaskState();break;case"TR":this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(i)}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){const t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode():!this.current.activeSMask&&t&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const t=this.ctx.canvas.width,e=this.ctx.canvas.height,i="smaskGroupAt"+this.groupLevel,s=this.cachedCanvases.getCanvas(i,t,e);this.suspendedCtx=this.ctx;this.ctx=s.context;const n=this.ctx;n.setTransform(...getCurrentTransform(this.suspendedCtx));copyCtxState(this.suspendedCtx,n);!function mirrorContextOperations(t,e){if(t._removeMirroring)throw new Error("Context is already forwarding operations.");t.__originalSave=t.save;t.__originalRestore=t.restore;t.__originalRotate=t.rotate;t.__originalScale=t.scale;t.__originalTranslate=t.translate;t.__originalTransform=t.transform;t.__originalSetTransform=t.setTransform;t.__originalResetTransform=t.resetTransform;t.__originalClip=t.clip;t.__originalMoveTo=t.moveTo;t.__originalLineTo=t.lineTo;t.__originalBezierCurveTo=t.bezierCurveTo;t.__originalRect=t.rect;t.__originalClosePath=t.closePath;t.__originalBeginPath=t.beginPath;t._removeMirroring=()=>{t.save=t.__originalSave;t.restore=t.__originalRestore;t.rotate=t.__originalRotate;t.scale=t.__originalScale;t.translate=t.__originalTranslate;t.transform=t.__originalTransform;t.setTransform=t.__originalSetTransform;t.resetTransform=t.__originalResetTransform;t.clip=t.__originalClip;t.moveTo=t.__originalMoveTo;t.lineTo=t.__originalLineTo;t.bezierCurveTo=t.__originalBezierCurveTo;t.rect=t.__originalRect;t.closePath=t.__originalClosePath;t.beginPath=t.__originalBeginPath;delete t._removeMirroring};t.save=function ctxSave(){e.save();this.__originalSave()};t.restore=function ctxRestore(){e.restore();this.__originalRestore()};t.translate=function ctxTranslate(t,i){e.translate(t,i);this.__originalTranslate(t,i)};t.scale=function ctxScale(t,i){e.scale(t,i);this.__originalScale(t,i)};t.transform=function ctxTransform(t,i,s,n,a,r){e.transform(t,i,s,n,a,r);this.__originalTransform(t,i,s,n,a,r)};t.setTransform=function ctxSetTransform(t,i,s,n,a,r){e.setTransform(t,i,s,n,a,r);this.__originalSetTransform(t,i,s,n,a,r)};t.resetTransform=function ctxResetTransform(){e.resetTransform();this.__originalResetTransform()};t.rotate=function ctxRotate(t){e.rotate(t);this.__originalRotate(t)};t.clip=function ctxRotate(t){e.clip(t);this.__originalClip(t)};t.moveTo=function(t,i){e.moveTo(t,i);this.__originalMoveTo(t,i)};t.lineTo=function(t,i){e.lineTo(t,i);this.__originalLineTo(t,i)};t.bezierCurveTo=function(t,i,s,n,a,r){e.bezierCurveTo(t,i,s,n,a,r);this.__originalBezierCurveTo(t,i,s,n,a,r)};t.rect=function(t,i,s,n){e.rect(t,i,s,n);this.__originalRect(t,i,s,n)};t.closePath=function(){e.closePath();this.__originalClosePath()};t.beginPath=function(){e.beginPath();this.__originalBeginPath()}}(n,this.suspendedCtx);this.setGState([["BM","source-over"],["ca",1],["CA",1]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring();copyCtxState(this.ctx,this.suspendedCtx);this.ctx=this.suspendedCtx;this.suspendedCtx=null}compose(t){if(!this.current.activeSMask)return;if(t){t[0]=Math.floor(t[0]);t[1]=Math.floor(t[1]);t[2]=Math.ceil(t[2]);t[3]=Math.ceil(t[3])}else t=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const e=this.current.activeSMask,i=this.suspendedCtx;this.composeSMask(i,e,this.ctx,t);this.ctx.save();this.ctx.setTransform(1,0,0,1,0,0);this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height);this.ctx.restore()}composeSMask(t,e,i,s){const n=s[0],a=s[1],r=s[2]-n,o=s[3]-a;if(0!==r&&0!==o){this.genericComposeSMask(e.context,i,r,o,e.subtype,e.backdrop,e.transferMap,n,a,e.offsetX,e.offsetY);t.save();t.globalAlpha=1;t.globalCompositeOperation="source-over";t.setTransform(1,0,0,1,0,0);t.drawImage(i.canvas,0,0);t.restore()}}genericComposeSMask(t,e,i,s,n,a,r,o,l,h,d){let c=t.canvas,u=o-h,p=l-d;if(a){const e=Util.makeHexColor(...a);if(u<0||p<0||u+i>c.width||p+s>c.height){const t=this.cachedCanvases.getCanvas("maskExtension",i,s),n=t.context;n.drawImage(c,-u,-p);n.globalCompositeOperation="destination-atop";n.fillStyle=e;n.fillRect(0,0,i,s);n.globalCompositeOperation="source-over";c=t.canvas;u=p=0}else{t.save();t.globalAlpha=1;t.setTransform(1,0,0,1,0,0);const n=new Path2D;n.rect(u,p,i,s);t.clip(n);t.globalCompositeOperation="destination-atop";t.fillStyle=e;t.fillRect(u,p,i,s);t.restore()}}e.save();e.globalAlpha=1;e.setTransform(1,0,0,1,0,0);"Alpha"===n&&r?e.filter=this.filterFactory.addAlphaFilter(r):"Luminosity"===n&&(e.filter=this.filterFactory.addLuminosityFilter(r));const g=new Path2D;g.rect(o,l,i,s);e.clip(g);e.globalCompositeOperation="destination-in";e.drawImage(c,u,p,i,s,o,l,i,s);e.restore()}save(){if(this.inSMaskMode){copyCtxState(this.ctx,this.suspendedCtx);this.suspendedCtx.save()}else this.ctx.save();const t=this.current;this.stateStack.push(t);this.current=t.clone()}restore(){0===this.stateStack.length&&this.inSMaskMode&&this.endSMaskMode();if(0!==this.stateStack.length){this.current=this.stateStack.pop();if(this.inSMaskMode){this.suspendedCtx.restore();copyCtxState(this.suspendedCtx,this.ctx)}else this.ctx.restore();this.checkSMaskState();this.pendingClip=null;this._cachedScaleForStroking[0]=-1;this._cachedGetSinglePixelWidth=null}}transform(t,e,i,s,n,a){this.ctx.transform(t,e,i,s,n,a);this._cachedScaleForStroking[0]=-1;this._cachedGetSinglePixelWidth=null}constructPath(t,e,i){const s=this.ctx,n=this.current;let a,r,o=n.x,l=n.y;const h=getCurrentTransform(s),d=0===h[0]&&0===h[3]||0===h[1]&&0===h[2],c=d?i.slice(0):null;for(let i=0,u=0,p=t.length;i100&&(h=100);this.current.fontSizeScale=e/h;this.ctx.font=`${l} ${o} ${h}px ${r}`}setTextRenderingMode(t){this.current.textRenderingMode=t}setTextRise(t){this.current.textRise=t}moveText(t,e){this.current.x=this.current.lineX+=t;this.current.y=this.current.lineY+=e}setLeadingMoveText(t,e){this.setLeading(-e);this.moveText(t,e)}setTextMatrix(t,e,i,s,n,a){this.current.textMatrix=[t,e,i,s,n,a];this.current.textMatrixScale=Math.hypot(t,e);this.current.x=this.current.lineX=0;this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}#ci(t,e,i){const s=new Path2D;s.addPath(t,new DOMMatrix(i).invertSelf().multiplySelf(e));return s}paintChar(t,e,i,s,n){const a=this.ctx,r=this.current,o=r.font,l=r.textRenderingMode,h=r.fontSize/r.fontSizeScale,d=l&y,c=!!(l&x),u=r.patternFill&&!o.missingFile,p=r.patternStroke&&!o.missingFile;let g;(o.disableFontFace||c||u||p)&&(g=o.getPathGenerator(this.commonObjs,t));if(o.disableFontFace||u||p){a.save();a.translate(e,i);a.scale(h,-h);if(d===b||d===w)if(s){const t=a.getTransform();a.setTransform(...s);a.fill(this.#ci(g,t,s))}else a.fill(g);if(d===A||d===w)if(n){const t=a.getTransform();a.setTransform(...n);a.stroke(this.#ci(g,t,n))}else{a.lineWidth/=h;a.stroke(g)}a.restore()}else{d!==b&&d!==w||a.fillText(t,e,i);d!==A&&d!==w||a.strokeText(t,e,i)}if(c){(this.pendingTextPaths||=[]).push({transform:getCurrentTransform(a),x:e,y:i,fontSize:h,path:g})}}get isFontSubpixelAAEnabled(){const{context:t}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);t.scale(1.5,1);t.fillText("I",0,10);const e=t.getImageData(0,0,10,10).data;let i=!1;for(let t=3;t0&&e[t]<255){i=!0;break}return shadow(this,"isFontSubpixelAAEnabled",i)}showText(t){const e=this.current,i=e.font;if(i.isType3Font)return this.showType3Text(t);const s=e.fontSize;if(0===s)return;const n=this.ctx,a=e.fontSizeScale,r=e.charSpacing,o=e.wordSpacing,l=e.fontDirection,h=e.textHScale*l,d=t.length,c=i.vertical,u=c?1:-1,p=i.defaultVMetrics,g=s*e.fontMatrix[0],m=e.textRenderingMode===b&&!i.disableFontFace&&!e.patternFill;n.save();n.transform(...e.textMatrix);n.translate(e.x,e.y+e.textRise);l>0?n.scale(h,-1):n.scale(h,1);let f,v;if(e.patternFill){n.save();const t=e.fillColor.getPattern(n,this,getCurrentTransformInverse(n),bt);f=getCurrentTransform(n);n.restore();n.fillStyle=t}if(e.patternStroke){n.save();const t=e.strokeColor.getPattern(n,this,getCurrentTransformInverse(n),At);v=getCurrentTransform(n);n.restore();n.strokeStyle=t}let x=e.lineWidth;const _=e.textMatrixScale;if(0===_||0===x){const t=e.textRenderingMode&y;t!==A&&t!==w||(x=this.getSinglePixelWidth())}else x/=_;if(1!==a){n.scale(a,a);x/=a}n.lineWidth=x;if(i.isInvalidPDFjsFont){const i=[];let s=0;for(const e of t){i.push(e.unicode);s+=e.width}n.fillText(i.join(""),0,0);e.x+=s*g*h;n.restore();this.compose();return}let E,S=0;for(E=0;E0){const t=1e3*n.measureText(b).width/s*a;if(xnew CanvasGraphics(t,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};e=new TilingPattern(t,i,this.ctx,n,s)}else e=this._getPattern(t[1],t[2]);return e}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments);this.current.patternStroke=!0}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments);this.current.patternFill=!0}setStrokeRGBColor(t,e,i){this.ctx.strokeStyle=this.current.strokeColor=Util.makeHexColor(t,e,i);this.current.patternStroke=!1}setStrokeTransparent(){this.ctx.strokeStyle=this.current.strokeColor="transparent";this.current.patternStroke=!1}setFillRGBColor(t,e,i){this.ctx.fillStyle=this.current.fillColor=Util.makeHexColor(t,e,i);this.current.patternFill=!1}setFillTransparent(){this.ctx.fillStyle=this.current.fillColor="transparent";this.current.patternFill=!1}_getPattern(t,e=null){let i;if(this.cachedPatterns.has(t))i=this.cachedPatterns.get(t);else{i=function getShadingPattern(t){switch(t[0]){case"RadialAxial":return new RadialAxialShadingPattern(t);case"Mesh":return new MeshShadingPattern(t);case"Dummy":return new DummyShadingPattern}throw new Error(`Unknown IR type: ${t[0]}`)}(this.getObject(t));this.cachedPatterns.set(t,i)}e&&(i.matrix=e);return i}shadingFill(t){if(!this.contentVisible)return;const e=this.ctx;this.save();const i=this._getPattern(t);e.fillStyle=i.getPattern(e,this,getCurrentTransformInverse(e),wt);const s=getCurrentTransformInverse(e);if(s){const{width:t,height:i}=e.canvas,[n,a,r,o]=Util.getAxialAlignedBoundingBox([0,0,t,i],s);this.ctx.fillRect(n,a,r-n,o-a)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox());this.restore()}beginInlineImage(){unreachable("Should not call beginInlineImage")}beginImageData(){unreachable("Should not call beginImageData")}paintFormXObjectBegin(t,e){if(this.contentVisible){this.save();this.baseTransformStack.push(this.baseTransform);t&&this.transform(...t);this.baseTransform=getCurrentTransform(this.ctx);if(e){const t=e[2]-e[0],i=e[3]-e[1];this.ctx.rect(e[0],e[1],t,i);this.current.updateRectMinMax(getCurrentTransform(this.ctx),e);this.clip();this.endPath()}}}paintFormXObjectEnd(){if(this.contentVisible){this.restore();this.baseTransform=this.baseTransformStack.pop()}}beginGroup(t){if(!this.contentVisible)return;this.save();if(this.inSMaskMode){this.endSMaskMode();this.current.activeSMask=null}const e=this.ctx;t.isolated||info("TODO: Support non-isolated groups.");t.knockout&&warn("Knockout groups not supported.");const i=getCurrentTransform(e);t.matrix&&e.transform(...t.matrix);if(!t.bbox)throw new Error("Bounding box is required.");let s=Util.getAxialAlignedBoundingBox(t.bbox,getCurrentTransform(e));const n=[0,0,e.canvas.width,e.canvas.height];s=Util.intersect(s,n)||[0,0,0,0];const a=Math.floor(s[0]),r=Math.floor(s[1]),o=Math.max(Math.ceil(s[2])-a,1),l=Math.max(Math.ceil(s[3])-r,1);this.current.startNewPathAndClipBox([0,0,o,l]);let h="groupAt"+this.groupLevel;t.smask&&(h+="_smask_"+this.smaskCounter++%2);const d=this.cachedCanvases.getCanvas(h,o,l),c=d.context;c.translate(-a,-r);c.transform(...i);if(t.smask)this.smaskStack.push({canvas:d.canvas,context:c,offsetX:a,offsetY:r,subtype:t.smask.subtype,backdrop:t.smask.backdrop,transferMap:t.smask.transferMap||null,startTransformInverse:null});else{e.setTransform(1,0,0,1,0,0);e.translate(a,r);e.save()}copyCtxState(e,c);this.ctx=c;this.setGState([["BM","source-over"],["ca",1],["CA",1]]);this.groupStack.push(e);this.groupLevel++}endGroup(t){if(!this.contentVisible)return;this.groupLevel--;const e=this.ctx,i=this.groupStack.pop();this.ctx=i;this.ctx.imageSmoothingEnabled=!1;if(t.smask){this.tempSMask=this.smaskStack.pop();this.restore()}else{this.ctx.restore();const t=getCurrentTransform(this.ctx);this.restore();this.ctx.save();this.ctx.setTransform(...t);const i=Util.getAxialAlignedBoundingBox([0,0,e.canvas.width,e.canvas.height],t);this.ctx.drawImage(e.canvas,0,0);this.ctx.restore();this.compose(i)}}beginAnnotation(t,e,i,s,n){this.#hi();resetCtxToDefault(this.ctx);this.ctx.save();this.save();this.baseTransform&&this.ctx.setTransform(...this.baseTransform);if(e){const s=e[2]-e[0],a=e[3]-e[1];if(n&&this.annotationCanvasMap){(i=i.slice())[4]-=e[0];i[5]-=e[1];(e=e.slice())[0]=e[1]=0;e[2]=s;e[3]=a;const[n,r]=Util.singularValueDecompose2dScale(getCurrentTransform(this.ctx)),{viewportScale:o}=this,l=Math.ceil(s*this.outputScaleX*o),h=Math.ceil(a*this.outputScaleY*o);this.annotationCanvas=this.canvasFactory.create(l,h);const{canvas:d,context:c}=this.annotationCanvas;this.annotationCanvasMap.set(t,d);this.annotationCanvas.savedCtx=this.ctx;this.ctx=c;this.ctx.save();this.ctx.setTransform(n,0,0,-r,0,a*r);resetCtxToDefault(this.ctx)}else{resetCtxToDefault(this.ctx);this.endPath();this.ctx.rect(e[0],e[1],s,a);this.ctx.clip();this.ctx.beginPath()}}this.current=new CanvasExtraState(this.ctx.canvas.width,this.ctx.canvas.height);this.transform(...i);this.transform(...s)}endAnnotation(){if(this.annotationCanvas){this.ctx.restore();this.#di();this.ctx=this.annotationCanvas.savedCtx;delete this.annotationCanvas.savedCtx;delete this.annotationCanvas}}paintImageMaskXObject(t){if(!this.contentVisible)return;const e=t.count;(t=this.getObject(t.data,t)).count=e;const i=this.ctx,s=this.processingType3;if(s){void 0===s.compiled&&(s.compiled=function compileType3Glyph(t){const{width:e,height:i}=t;if(e>1e3||i>1e3)return null;const s=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),n=e+1;let a,r,o,l=new Uint8Array(n*(i+1));const h=e+7&-8;let d=new Uint8Array(h*i),c=0;for(const e of t.data){let t=128;for(;t>0;){d[c++]=e&t?0:255;t>>=1}}let u=0;c=0;if(0!==d[c]){l[0]=1;++u}for(r=1;r>2)+(d[c+1]?4:0)+(d[c-h+1]?8:0);if(s[t]){l[o+r]=s[t];++u}c++}if(d[c-h]!==d[c]){l[o+r]=d[c]?2:4;++u}if(u>1e3)return null}c=h*(i-1);o=a*n;if(0!==d[c]){l[o]=8;++u}for(r=1;r1e3)return null;const p=new Int32Array([0,n,-1,0,-n,0,0,0,1]),g=new Path2D;for(a=0;u&&a<=i;a++){let t=a*n;const i=t+e;for(;t>4;l[t]&=r>>2|r<<2}g.lineTo(t%n,t/n|0);l[t]||--u}while(s!==t);--a}d=null;l=null;return function(t){t.save();t.scale(1/e,-1/i);t.translate(0,-i);t.fill(g);t.beginPath();t.restore()}}(t));if(s.compiled){s.compiled(i);return}}const n=this._createMaskCanvas(t),a=n.canvas;i.save();i.setTransform(1,0,0,1,0,0);i.drawImage(a,n.offsetX,n.offsetY);i.restore();this.compose()}paintImageMaskXObjectRepeat(t,e,i=0,s=0,n,a){if(!this.contentVisible)return;t=this.getObject(t.data,t);const r=this.ctx;r.save();const o=getCurrentTransform(r);r.transform(e,i,s,n,0,0);const l=this._createMaskCanvas(t);r.setTransform(1,0,0,1,l.offsetX-o[4],l.offsetY-o[5]);for(let t=0,h=a.length;te?h/e:1;r=l>e?l/e:1}}this._cachedScaleForStroking[0]=a;this._cachedScaleForStroking[1]=r}return this._cachedScaleForStroking}rescaleAndStroke(t){const{ctx:e}=this,{lineWidth:i}=this.current,[s,n]=this.getScaleForStroking();e.lineWidth=i||1;if(1===s&&1===n){e.stroke();return}const a=e.getLineDash();t&&e.save();e.scale(s,n);if(a.length>0){const t=Math.max(s,n);e.setLineDash(a.map((e=>e/t)));e.lineDashOffset/=t}e.stroke();t&&e.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}}for(const t in X)void 0!==CanvasGraphics.prototype[t]&&(CanvasGraphics.prototype[X[t]]=CanvasGraphics.prototype[t]);class GlobalWorkerOptions{static#ui=null;static#pi="";static get workerPort(){return this.#ui}static set workerPort(t){if(!("undefined"!=typeof Worker&&t instanceof Worker)&&null!==t)throw new Error("Invalid `workerPort` type.");this.#ui=t}static get workerSrc(){return this.#pi}static set workerSrc(t){if("string"!=typeof t)throw new Error("Invalid `workerSrc` type.");this.#pi=t}}class Metadata{#gi;#mi;constructor({parsedData:t,rawData:e}){this.#gi=t;this.#mi=e}getRaw(){return this.#mi}get(t){return this.#gi.get(t)??null}getAll(){return objectFromMap(this.#gi)}has(t){return this.#gi.has(t)}}const Tt=Symbol("INTERNAL");class OptionalContentGroup{#fi=!1;#bi=!1;#Ai=!1;#wi=!0;constructor(t,{name:e,intent:i,usage:s,rbGroups:n}){this.#fi=!!(t&r);this.#bi=!!(t&o);this.name=e;this.intent=i;this.usage=s;this.rbGroups=n}get visible(){if(this.#Ai)return this.#wi;if(!this.#wi)return!1;const{print:t,view:e}=this.usage;return this.#fi?"OFF"!==e?.viewState:!this.#bi||"OFF"!==t?.printState}_setVisible(t,e,i=!1){t!==Tt&&unreachable("Internal method `_setVisible` called.");this.#Ai=i;this.#wi=e}}class OptionalContentConfig{#vi=null;#yi=new Map;#xi=null;#_i=null;constructor(t,e=r){this.renderingIntent=e;this.name=null;this.creator=null;if(null!==t){this.name=t.name;this.creator=t.creator;this.#_i=t.order;for(const i of t.groups)this.#yi.set(i.id,new OptionalContentGroup(e,i));if("OFF"===t.baseState)for(const t of this.#yi.values())t._setVisible(Tt,!1);for(const e of t.on)this.#yi.get(e)._setVisible(Tt,!0);for(const e of t.off)this.#yi.get(e)._setVisible(Tt,!1);this.#xi=this.getHash()}}#Ei(t){const e=t.length;if(e<2)return!0;const i=t[0];for(let s=1;s0?objectFromMap(this.#yi):null}getGroup(t){return this.#yi.get(t)||null}getHash(){if(null!==this.#vi)return this.#vi;const t=new MurmurHash3_64;for(const[e,i]of this.#yi)t.update(`${e}:${i.visible}`);return this.#vi=t.hexdigest()}}class PDFDataTransportStream{constructor(t,{disableRange:e=!1,disableStream:i=!1}){assert(t,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');const{length:s,initialData:n,progressiveDone:a,contentDispositionFilename:r}=t;this._queuedChunks=[];this._progressiveDone=a;this._contentDispositionFilename=r;if(n?.length>0){const t=n instanceof Uint8Array&&n.byteLength===n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer;this._queuedChunks.push(t)}this._pdfDataRangeTransport=t;this._isStreamingSupported=!i;this._isRangeSupported=!e;this._contentLength=s;this._fullRequestReader=null;this._rangeReaders=[];t.addRangeListener(((t,e)=>{this._onReceiveData({begin:t,chunk:e})}));t.addProgressListener(((t,e)=>{this._onProgress({loaded:t,total:e})}));t.addProgressiveReadListener((t=>{this._onReceiveData({chunk:t})}));t.addProgressiveDoneListener((()=>{this._onProgressiveDone()}));t.transportReady()}_onReceiveData({begin:t,chunk:e}){const i=e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer;if(void 0===t)this._fullRequestReader?this._fullRequestReader._enqueue(i):this._queuedChunks.push(i);else{assert(this._rangeReaders.some((function(e){if(e._begin!==t)return!1;e._enqueue(i);return!0})),"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}_onProgress(t){void 0===t.total?this._rangeReaders[0]?.onProgress?.({loaded:t.loaded}):this._fullRequestReader?.onProgress?.({loaded:t.loaded,total:t.total})}_onProgressiveDone(){this._fullRequestReader?.progressiveDone();this._progressiveDone=!0}_removeRangeReader(t){const e=this._rangeReaders.indexOf(t);e>=0&&this._rangeReaders.splice(e,1)}getFullReader(){assert(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;this._queuedChunks=null;return new PDFDataTransportStreamReader(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new PDFDataTransportStreamRangeReader(this,t,e);this._pdfDataRangeTransport.requestDataRange(t,e);this._rangeReaders.push(i);return i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeReaders.slice(0))e.cancel(t);this._pdfDataRangeTransport.abort()}}class PDFDataTransportStreamReader{constructor(t,e,i=!1,s=null){this._stream=t;this._done=i||!1;this._filename=isPdfFile(s)?s:null;this._queuedChunks=e||[];this._loaded=0;for(const t of this._queuedChunks)this._loaded+=t.byteLength;this._requests=[];this._headersReady=Promise.resolve();t._fullRequestReader=this;this.onProgress=null}_enqueue(t){if(!this._done){if(this._requests.length>0){this._requests.shift().resolve({value:t,done:!1})}else this._queuedChunks.push(t);this._loaded+=t.byteLength}}get headersReady(){return this._headersReady}get filename(){return this._filename}get isRangeSupported(){return this._stream._isRangeSupported}get isStreamingSupported(){return this._stream._isStreamingSupported}get contentLength(){return this._stream._contentLength}async read(){if(this._queuedChunks.length>0){return{value:this._queuedChunks.shift(),done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||(this._done=!0)}}class PDFDataTransportStreamRangeReader{constructor(t,e,i){this._stream=t;this._begin=e;this._end=i;this._queuedChunk=null;this._requests=[];this._done=!1;this.onProgress=null}_enqueue(t){if(!this._done){if(0===this._requests.length)this._queuedChunk=t;else{this._requests.shift().resolve({value:t,done:!1});for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}this._done=!0;this._stream._removeRangeReader(this)}}get isStreamingSupported(){return!1}async read(){if(this._queuedChunk){const t=this._queuedChunk;this._queuedChunk=null;return{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0;this._stream._removeRangeReader(this)}}function createHeaders(t,e){const i=new Headers;if(!t||!e||"object"!=typeof e)return i;for(const t in e){const s=e[t];void 0!==s&&i.append(t,s)}return i}function getResponseOrigin(t){try{return new URL(t).origin}catch{}return null}function validateRangeRequestCapabilities({responseHeaders:t,isHttp:e,rangeChunkSize:i,disableRange:s}){const n={allowRangeRequests:!1,suggestedLength:void 0},a=parseInt(t.get("Content-Length"),10);if(!Number.isInteger(a))return n;n.suggestedLength=a;if(a<=2*i)return n;if(s||!e)return n;if("bytes"!==t.get("Accept-Ranges"))return n;if("identity"!==(t.get("Content-Encoding")||"identity"))return n;n.allowRangeRequests=!0;return n}function extractFilenameFromHeader(t){const e=t.get("Content-Disposition");if(e){let t=function getFilenameFromContentDispositionHeader(t){let e=!0,i=toParamRegExp("filename\\*","i").exec(t);if(i){i=i[1];let t=rfc2616unquote(i);t=unescape(t);t=rfc5987decode(t);t=rfc2047decode(t);return fixupEncoding(t)}i=function rfc2231getparam(t){const e=[];let i;const s=toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;null!==(i=s.exec(t));){let[,t,s,n]=i;t=parseInt(t,10);if(t in e){if(0===t)break}else e[t]=[s,n]}const n=[];for(let t=0;t{t._responseOrigin=getResponseOrigin(e.url);if(!validateResponseStatus(e.status))throw createResponseStatusError(e.status,s);this._reader=e.body.getReader();this._headersCapability.resolve();const i=e.headers,{allowRangeRequests:n,suggestedLength:a}=validateRangeRequestCapabilities({responseHeaders:i,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=n;this._contentLength=a||this._contentLength;this._filename=extractFilenameFromHeader(i);!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new AbortException("Streaming is disabled."))})).catch(this._headersCapability.reject);this.onProgress=null}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._headersCapability.promise;const{value:t,done:e}=await this._reader.read();if(e)return{value:t,done:e};this._loaded+=t.byteLength;this.onProgress?.({loaded:this._loaded,total:this._contentLength});return{value:getArrayBuffer(t),done:!1}}cancel(t){this._reader?.cancel(t);this._abortController.abort()}}class PDFFetchStreamRangeReader{constructor(t,e,i){this._stream=t;this._reader=null;this._loaded=0;const s=t.source;this._withCredentials=s.withCredentials||!1;this._readCapability=Promise.withResolvers();this._isStreamingSupported=!s.disableStream;this._abortController=new AbortController;const n=new Headers(t.headers);n.append("Range",`bytes=${e}-${i-1}`);const a=s.url;fetch(a,createFetchOptions(n,this._withCredentials,this._abortController)).then((e=>{const i=getResponseOrigin(e.url);if(i!==t._responseOrigin)throw new Error(`Expected range response-origin "${i}" to match "${t._responseOrigin}".`);if(!validateResponseStatus(e.status))throw createResponseStatusError(e.status,a);this._readCapability.resolve();this._reader=e.body.getReader()})).catch(this._readCapability.reject);this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();if(e)return{value:t,done:e};this._loaded+=t.byteLength;this.onProgress?.({loaded:this._loaded});return{value:getArrayBuffer(t),done:!1}}cancel(t){this._reader?.cancel(t);this._abortController.abort()}}class NetworkManager{_responseOrigin=null;constructor({url:t,httpHeaders:e,withCredentials:i}){this.url=t;this.isHttp=/^https?:/i.test(t);this.headers=createHeaders(this.isHttp,e);this.withCredentials=i||!1;this.currXhrId=0;this.pendingRequests=Object.create(null)}request(t){const e=new XMLHttpRequest,i=this.currXhrId++,s=this.pendingRequests[i]={xhr:e};e.open("GET",this.url);e.withCredentials=this.withCredentials;for(const[t,i]of this.headers)e.setRequestHeader(t,i);if(this.isHttp&&"begin"in t&&"end"in t){e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`);s.expectedStatus=206}else s.expectedStatus=200;e.responseType="arraybuffer";assert(t.onError,"Expected `onError` callback to be provided.");e.onerror=()=>{t.onError(e.status)};e.onreadystatechange=this.onStateChange.bind(this,i);e.onprogress=this.onProgress.bind(this,i);s.onHeadersReceived=t.onHeadersReceived;s.onDone=t.onDone;s.onError=t.onError;s.onProgress=t.onProgress;e.send(null);return i}onProgress(t,e){const i=this.pendingRequests[t];i&&i.onProgress?.(e)}onStateChange(t,e){const i=this.pendingRequests[t];if(!i)return;const s=i.xhr;if(s.readyState>=2&&i.onHeadersReceived){i.onHeadersReceived();delete i.onHeadersReceived}if(4!==s.readyState)return;if(!(t in this.pendingRequests))return;delete this.pendingRequests[t];if(0===s.status&&this.isHttp){i.onError(s.status);return}const n=s.status||200;if(!(200===n&&206===i.expectedStatus)&&n!==i.expectedStatus){i.onError(s.status);return}const a=function network_getArrayBuffer(t){const e=t.response;return"string"!=typeof e?e:stringToBytes(e).buffer}(s);if(206===n){const t=s.getResponseHeader("Content-Range"),e=/bytes (\d+)-(\d+)\/(\d+)/.exec(t);if(e)i.onDone({begin:parseInt(e[1],10),chunk:a});else{warn('Missing or invalid "Content-Range" header.');i.onError(0)}}else a?i.onDone({begin:0,chunk:a}):i.onError(s.status)}getRequestXhr(t){return this.pendingRequests[t].xhr}isPendingRequest(t){return t in this.pendingRequests}abortRequest(t){const e=this.pendingRequests[t].xhr;delete this.pendingRequests[t];e.abort()}}class PDFNetworkStream{constructor(t){this._source=t;this._manager=new NetworkManager(t);this._rangeChunkSize=t.rangeChunkSize;this._fullRequestReader=null;this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(t){const e=this._rangeRequestReaders.indexOf(t);e>=0&&this._rangeRequestReaders.splice(e,1)}getFullReader(){assert(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once.");this._fullRequestReader=new PDFNetworkStreamFullRequestReader(this._manager,this._source);return this._fullRequestReader}getRangeReader(t,e){const i=new PDFNetworkStreamRangeRequestReader(this._manager,t,e);i.onClosed=this._onRangeRequestReaderClosed.bind(this);this._rangeRequestReaders.push(i);return i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class PDFNetworkStreamFullRequestReader{constructor(t,e){this._manager=t;this._url=e.url;this._fullRequestId=t.request({onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)});this._headersCapability=Promise.withResolvers();this._disableRange=e.disableRange||!1;this._contentLength=e.length;this._rangeChunkSize=e.rangeChunkSize;this._rangeChunkSize||this._disableRange||(this._disableRange=!0);this._isStreamingSupported=!1;this._isRangeSupported=!1;this._cachedChunks=[];this._requests=[];this._done=!1;this._storedError=void 0;this._filename=null;this.onProgress=null}_onHeadersReceived(){const t=this._fullRequestId,e=this._manager.getRequestXhr(t);this._manager._responseOrigin=getResponseOrigin(e.responseURL);const i=e.getAllResponseHeaders(),s=new Headers(i?i.trimStart().replace(/[^\S ]+$/,"").split(/[\r\n]+/).map((t=>{const[e,...i]=t.split(": ");return[e,i.join(": ")]})):[]),{allowRangeRequests:n,suggestedLength:a}=validateRangeRequestCapabilities({responseHeaders:s,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});n&&(this._isRangeSupported=!0);this._contentLength=a||this._contentLength;this._filename=extractFilenameFromHeader(s);this._isRangeSupported&&this._manager.abortRequest(t);this._headersCapability.resolve()}_onDone(t){if(t)if(this._requests.length>0){this._requests.shift().resolve({value:t.chunk,done:!1})}else this._cachedChunks.push(t.chunk);this._done=!0;if(!(this._cachedChunks.length>0)){for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(t){this._storedError=createResponseStatusError(t,this._url);this._headersCapability.reject(this._storedError);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0;this._cachedChunks.length=0}_onProgress(t){this.onProgress?.({loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})}get filename(){return this._filename}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}get contentLength(){return this._contentLength}get headersReady(){return this._headersCapability.promise}async read(){await this._headersCapability.promise;if(this._storedError)throw this._storedError;if(this._cachedChunks.length>0){return{value:this._cachedChunks.shift(),done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;this._headersCapability.reject(t);for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0;this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId);this._fullRequestReader=null}}class PDFNetworkStreamRangeRequestReader{constructor(t,e,i){this._manager=t;this._url=t.url;this._requestId=t.request({begin:e,end:i,onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)});this._requests=[];this._queuedChunk=null;this._done=!1;this._storedError=void 0;this.onProgress=null;this.onClosed=null}_onHeadersReceived(){const t=getResponseOrigin(this._manager.getRequestXhr(this._requestId)?.responseURL);if(t!==this._manager._responseOrigin){this._storedError=new Error(`Expected range response-origin "${t}" to match "${this._manager._responseOrigin}".`);this._onError(0)}}_close(){this.onClosed?.(this)}_onDone(t){const e=t.chunk;if(this._requests.length>0){this._requests.shift().resolve({value:e,done:!1})}else this._queuedChunk=e;this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0;this._close()}_onError(t){this._storedError??=createResponseStatusError(t,this._url);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0;this._queuedChunk=null}_onProgress(t){this.isStreamingSupported||this.onProgress?.({loaded:t.loaded})}get isStreamingSupported(){return!1}async read(){if(this._storedError)throw this._storedError;if(null!==this._queuedChunk){const t=this._queuedChunk;this._queuedChunk=null;return{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0;this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId);this._close()}}const Mt=/^[a-z][a-z0-9\-+.]+:/i;class PDFNodeStream{constructor(t){this.source=t;this.url=function parseUrlOrPath(t){if(Mt.test(t))return new URL(t);const e=process.getBuiltinModule("url");return new URL(e.pathToFileURL(t))}(t.url);assert("file:"===this.url.protocol,"PDFNodeStream only supports file:// URLs.");this._fullRequestReader=null;this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){assert(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once.");this._fullRequestReader=new PDFNodeStreamFsFullReader(this);return this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new PDFNodeStreamFsRangeReader(this,t,e);this._rangeRequestReaders.push(i);return i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class PDFNodeStreamFsFullReader{constructor(t){this._url=t.url;this._done=!1;this._storedError=null;this.onProgress=null;const e=t.source;this._contentLength=e.length;this._loaded=0;this._filename=null;this._disableRange=e.disableRange||!1;this._rangeChunkSize=e.rangeChunkSize;this._rangeChunkSize||this._disableRange||(this._disableRange=!0);this._isStreamingSupported=!e.disableStream;this._isRangeSupported=!e.disableRange;this._readableStream=null;this._readCapability=Promise.withResolvers();this._headersCapability=Promise.withResolvers();const i=process.getBuiltinModule("fs");i.promises.lstat(this._url).then((t=>{this._contentLength=t.size;this._setReadableStream(i.createReadStream(this._url));this._headersCapability.resolve()}),(t=>{"ENOENT"===t.code&&(t=new MissingPDFException(`Missing PDF "${this._url}".`));this._storedError=t;this._headersCapability.reject(t)}))}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;if(this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();if(null===t){this._readCapability=Promise.withResolvers();return this.read()}this._loaded+=t.length;this.onProgress?.({loaded:this._loaded,total:this._contentLength});return{value:new Uint8Array(t).buffer,done:!1}}cancel(t){this._readableStream?this._readableStream.destroy(t):this._error(t)}_error(t){this._storedError=t;this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t;t.on("readable",(()=>{this._readCapability.resolve()}));t.on("end",(()=>{t.destroy();this._done=!0;this._readCapability.resolve()}));t.on("error",(t=>{this._error(t)}));!this._isStreamingSupported&&this._isRangeSupported&&this._error(new AbortException("streaming is disabled"));this._storedError&&this._readableStream.destroy(this._storedError)}}class PDFNodeStreamFsRangeReader{constructor(t,e,i){this._url=t.url;this._done=!1;this._storedError=null;this.onProgress=null;this._loaded=0;this._readableStream=null;this._readCapability=Promise.withResolvers();const s=t.source;this._isStreamingSupported=!s.disableStream;const n=process.getBuiltinModule("fs");this._setReadableStream(n.createReadStream(this._url,{start:e,end:i-1}))}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;if(this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();if(null===t){this._readCapability=Promise.withResolvers();return this.read()}this._loaded+=t.length;this.onProgress?.({loaded:this._loaded});return{value:new Uint8Array(t).buffer,done:!1}}cancel(t){this._readableStream?this._readableStream.destroy(t):this._error(t)}_error(t){this._storedError=t;this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t;t.on("readable",(()=>{this._readCapability.resolve()}));t.on("end",(()=>{t.destroy();this._done=!0;this._readCapability.resolve()}));t.on("error",(t=>{this._error(t)}));this._storedError&&this._readableStream.destroy(this._storedError)}}const Pt=30;class TextLayer{#Si=Promise.withResolvers();#pt=null;#Ci=!1;#Ti=!!globalThis.FontInspector?.enabled;#Mi=null;#Pi=null;#Di=0;#ki=0;#Ri=null;#Ii=null;#Fi=0;#Li=0;#Oi=Object.create(null);#Ni=[];#Bi=null;#Hi=[];#zi=new WeakMap;#Ui=null;static#Gi=new Map;static#$i=new Map;static#Vi=new WeakMap;static#ji=null;static#Wi=new Set;constructor({textContentSource:t,container:e,viewport:i}){if(t instanceof ReadableStream)this.#Bi=t;else{if("object"!=typeof t)throw new Error('No "textContentSource" parameter specified.');this.#Bi=new ReadableStream({start(e){e.enqueue(t);e.close()}})}this.#pt=this.#Ii=e;this.#Li=i.scale*(globalThis.devicePixelRatio||1);this.#Fi=i.rotation;this.#Pi={div:null,properties:null,ctx:null};const{pageWidth:s,pageHeight:n,pageX:a,pageY:r}=i.rawDims;this.#Ui=[1,0,0,-1,-a,r+n];this.#ki=s;this.#Di=n;TextLayer.#qi();setLayerDimensions(e,i);this.#Si.promise.finally((()=>{TextLayer.#Wi.delete(this);this.#Pi=null;this.#Oi=null})).catch((()=>{}))}static get fontFamilyMap(){const{isWindows:t,isFirefox:e}=util_FeatureTest.platform;return shadow(this,"fontFamilyMap",new Map([["sans-serif",(t&&e?"Calibri, ":"")+"sans-serif"],["monospace",(t&&e?"Lucida Console, ":"")+"monospace"]]))}render(){const pump=()=>{this.#Ri.read().then((({value:t,done:e})=>{if(e)this.#Si.resolve();else{this.#Mi??=t.lang;Object.assign(this.#Oi,t.styles);this.#Xi(t.items);pump()}}),this.#Si.reject)};this.#Ri=this.#Bi.getReader();TextLayer.#Wi.add(this);pump();return this.#Si.promise}update({viewport:t,onBefore:e=null}){const i=t.scale*(globalThis.devicePixelRatio||1),s=t.rotation;if(s!==this.#Fi){e?.();this.#Fi=s;setLayerDimensions(this.#Ii,{rotation:s})}if(i!==this.#Li){e?.();this.#Li=i;const t={div:null,properties:null,ctx:TextLayer.#Ki(this.#Mi)};for(const e of this.#Hi){t.properties=this.#zi.get(e);t.div=e;this.#Yi(t)}}}cancel(){const t=new AbortException("TextLayer task cancelled.");this.#Ri?.cancel(t).catch((()=>{}));this.#Ri=null;this.#Si.reject(t)}get textDivs(){return this.#Hi}get textContentItemsStr(){return this.#Ni}#Xi(t){if(this.#Ci)return;this.#Pi.ctx??=TextLayer.#Ki(this.#Mi);const e=this.#Hi,i=this.#Ni;for(const s of t){if(e.length>1e5){warn("Ignoring additional textDivs for performance reasons.");this.#Ci=!0;return}if(void 0!==s.str){i.push(s.str);this.#Qi(s)}else if("beginMarkedContentProps"===s.type||"beginMarkedContent"===s.type){const t=this.#pt;this.#pt=document.createElement("span");this.#pt.classList.add("markedContent");null!==s.id&&this.#pt.setAttribute("id",`${s.id}`);t.append(this.#pt)}else"endMarkedContent"===s.type&&(this.#pt=this.#pt.parentNode)}}#Qi(t){const e=document.createElement("span"),i={angle:0,canvasWidth:0,hasText:""!==t.str,hasEOL:t.hasEOL,fontSize:0};this.#Hi.push(e);const s=Util.transform(this.#Ui,t.transform);let n=Math.atan2(s[1],s[0]);const a=this.#Oi[t.fontName];a.vertical&&(n+=Math.PI/2);let r=this.#Ti&&a.fontSubstitution||a.fontFamily;r=TextLayer.fontFamilyMap.get(r)||r;const o=Math.hypot(s[2],s[3]),l=o*TextLayer.#Ji(r,this.#Mi);let h,d;if(0===n){h=s[4];d=s[5]-l}else{h=s[4]+l*Math.sin(n);d=s[5]-l*Math.cos(n)}const c="calc(var(--scale-factor)*",u=e.style;if(this.#pt===this.#Ii){u.left=`${(100*h/this.#ki).toFixed(2)}%`;u.top=`${(100*d/this.#Di).toFixed(2)}%`}else{u.left=`${c}${h.toFixed(2)}px)`;u.top=`${c}${d.toFixed(2)}px)`}u.fontSize=`${c}${(TextLayer.#ji*o).toFixed(2)}px)`;u.fontFamily=r;i.fontSize=o;e.setAttribute("role","presentation");e.textContent=t.str;e.dir=t.dir;this.#Ti&&(e.dataset.fontName=a.fontSubstitutionLoadedName||t.fontName);0!==n&&(i.angle=n*(180/Math.PI));let p=!1;if(t.str.length>1)p=!0;else if(" "!==t.str&&t.transform[0]!==t.transform[3]){const e=Math.abs(t.transform[0]),i=Math.abs(t.transform[3]);e!==i&&Math.max(e,i)/Math.min(e,i)>1.5&&(p=!0)}p&&(i.canvasWidth=a.vertical?t.height:t.width);this.#zi.set(e,i);this.#Pi.div=e;this.#Pi.properties=i;this.#Yi(this.#Pi);i.hasText&&this.#pt.append(e);if(i.hasEOL){const t=document.createElement("br");t.setAttribute("role","presentation");this.#pt.append(t)}}#Yi(t){const{div:e,properties:i,ctx:s}=t,{style:n}=e;let a="";TextLayer.#ji>1&&(a=`scale(${1/TextLayer.#ji})`);if(0!==i.canvasWidth&&i.hasText){const{fontFamily:t}=n,{canvasWidth:r,fontSize:o}=i;TextLayer.#Zi(s,o*this.#Li,t);const{width:l}=s.measureText(e.textContent);l>0&&(a=`scaleX(${r*this.#Li/l}) ${a}`)}0!==i.angle&&(a=`rotate(${i.angle}deg) ${a}`);a.length>0&&(n.transform=a)}static cleanup(){if(!(this.#Wi.size>0)){this.#Gi.clear();for(const{canvas:t}of this.#$i.values())t.remove();this.#$i.clear()}}static#Ki(t=null){let e=this.#$i.get(t||="");if(!e){const i=document.createElement("canvas");i.className="hiddenCanvasElement";i.lang=t;document.body.append(i);e=i.getContext("2d",{alpha:!1,willReadFrequently:!0});this.#$i.set(t,e);this.#Vi.set(e,{size:0,family:""})}return e}static#Zi(t,e,i){const s=this.#Vi.get(t);if(e!==s.size||i!==s.family){t.font=`${e}px ${i}`;s.size=e;s.family=i}}static#qi(){if(null!==this.#ji)return;const t=document.createElement("div");t.style.opacity=0;t.style.lineHeight=1;t.style.fontSize="1px";t.style.position="absolute";t.textContent="X";document.body.append(t);this.#ji=t.getBoundingClientRect().height;t.remove()}static#Ji(t,e){const i=this.#Gi.get(t);if(i)return i;const s=this.#Ki(e);s.canvas.width=s.canvas.height=Pt;this.#Zi(s,Pt,t);const n=s.measureText("");let a=n.fontBoundingBoxAscent,r=Math.abs(n.fontBoundingBoxDescent);if(a){const e=a/(a+r);this.#Gi.set(t,e);s.canvas.width=s.canvas.height=0;return e}s.strokeStyle="red";s.clearRect(0,0,Pt,Pt);s.strokeText("g",0,0);let o=s.getImageData(0,0,Pt,Pt).data;r=0;for(let t=o.length-1-3;t>=0;t-=4)if(o[t]>0){r=Math.ceil(t/4/Pt);break}s.clearRect(0,0,Pt,Pt);s.strokeText("A",0,Pt);o=s.getImageData(0,0,Pt,Pt).data;a=0;for(let t=0,e=o.length;t0){a=Pt-Math.floor(t/4/Pt);break}s.canvas.width=s.canvas.height=0;const l=a?a/(a+r):.8;this.#Gi.set(t,l);return l}}class XfaText{static textContent(t){const e=[],i={items:e,styles:Object.create(null)};!function walk(t){if(!t)return;let i=null;const s=t.name;if("#text"===s)i=t.value;else{if(!XfaText.shouldBuildText(s))return;t?.attributes?.textContent?i=t.attributes.textContent:t.value&&(i=t.value)}null!==i&&e.push({str:i});if(t.children)for(const e of t.children)walk(e)}(t);return i}static shouldBuildText(t){return!("textarea"===t||"input"===t||"option"===t||"select"===t)}}const Dt=65536,kt=e?class NodeCanvasFactory extends BaseCanvasFactory{_createCanvas(t,e){return process.getBuiltinModule("module").createRequire(import.meta.url)("@napi-rs/canvas").createCanvas(t,e)}}:class DOMCanvasFactory extends BaseCanvasFactory{constructor({ownerDocument:t=globalThis.document,enableHWA:e=!1}){super({enableHWA:e});this._document=t}_createCanvas(t,e){const i=this._document.createElement("canvas");i.width=t;i.height=e;return i}},Rt=e?class NodeCMapReaderFactory extends BaseCMapReaderFactory{async _fetch(t){return node_utils_fetchData(t)}}:DOMCMapReaderFactory,It=e?class NodeFilterFactory extends BaseFilterFactory{}:class DOMFilterFactory extends BaseFilterFactory{#ts;#es;#is;#ss;#ns;#as;#w=0;constructor({docId:t,ownerDocument:e=globalThis.document}){super();this.#ss=t;this.#ns=e}get#y(){return this.#es||=new Map}get#rs(){return this.#as||=new Map}get#os(){if(!this.#is){const t=this.#ns.createElement("div"),{style:e}=t;e.visibility="hidden";e.contain="strict";e.width=e.height=0;e.position="absolute";e.top=e.left=0;e.zIndex=-1;const i=this.#ns.createElementNS(it,"svg");i.setAttribute("width",0);i.setAttribute("height",0);this.#is=this.#ns.createElementNS(it,"defs");t.append(i);i.append(this.#is);this.#ns.body.append(t)}return this.#is}#ls(t){if(1===t.length){const e=t[0],i=new Array(256);for(let t=0;t<256;t++)i[t]=e[t]/255;const s=i.join(",");return[s,s,s]}const[e,i,s]=t,n=new Array(256),a=new Array(256),r=new Array(256);for(let t=0;t<256;t++){n[t]=e[t]/255;a[t]=i[t]/255;r[t]=s[t]/255}return[n.join(","),a.join(","),r.join(",")]}#hs(t){if(void 0===this.#ts){this.#ts="";const t=this.#ns.URL;t!==this.#ns.baseURI&&(isDataScheme(t)?warn('#createUrl: ignore "data:"-URL for performance reasons.'):this.#ts=t.split("#",1)[0])}return`url(${this.#ts}#${t})`}addFilter(t){if(!t)return"none";let e=this.#y.get(t);if(e)return e;const[i,s,n]=this.#ls(t),a=1===t.length?i:`${i}${s}${n}`;e=this.#y.get(a);if(e){this.#y.set(t,e);return e}const r=`g_${this.#ss}_transfer_map_${this.#w++}`,o=this.#hs(r);this.#y.set(t,o);this.#y.set(a,o);const l=this.#ds(r);this.#cs(i,s,n,l);return o}addHCMFilter(t,e){const i=`${t}-${e}`,s="base";let n=this.#rs.get(s);if(n?.key===i)return n.url;if(n){n.filter?.remove();n.key=i;n.url="none";n.filter=null}else{n={key:i,url:"none",filter:null};this.#rs.set(s,n)}if(!t||!e)return n.url;const a=this.#us(t);t=Util.makeHexColor(...a);const r=this.#us(e);e=Util.makeHexColor(...r);this.#os.style.color="";if("#000000"===t&&"#ffffff"===e||t===e)return n.url;const o=new Array(256);for(let t=0;t<=255;t++){const e=t/255;o[t]=e<=.03928?e/12.92:((e+.055)/1.055)**2.4}const l=o.join(","),h=`g_${this.#ss}_hcm_filter`,d=n.filter=this.#ds(h);this.#cs(l,l,l,d);this.#ps(d);const getSteps=(t,e)=>{const i=a[t]/255,s=r[t]/255,n=new Array(e+1);for(let t=0;t<=e;t++)n[t]=i+t/e*(s-i);return n.join(",")};this.#cs(getSteps(0,5),getSteps(1,5),getSteps(2,5),d);n.url=this.#hs(h);return n.url}addAlphaFilter(t){let e=this.#y.get(t);if(e)return e;const[i]=this.#ls([t]),s=`alpha_${i}`;e=this.#y.get(s);if(e){this.#y.set(t,e);return e}const n=`g_${this.#ss}_alpha_map_${this.#w++}`,a=this.#hs(n);this.#y.set(t,a);this.#y.set(s,a);const r=this.#ds(n);this.#gs(i,r);return a}addLuminosityFilter(t){let e,i,s=this.#y.get(t||"luminosity");if(s)return s;if(t){[e]=this.#ls([t]);i=`luminosity_${e}`}else i="luminosity";s=this.#y.get(i);if(s){this.#y.set(t,s);return s}const n=`g_${this.#ss}_luminosity_map_${this.#w++}`,a=this.#hs(n);this.#y.set(t,a);this.#y.set(i,a);const r=this.#ds(n);this.#ms(r);t&&this.#gs(e,r);return a}addHighlightHCMFilter(t,e,i,s,n){const a=`${e}-${i}-${s}-${n}`;let r=this.#rs.get(t);if(r?.key===a)return r.url;if(r){r.filter?.remove();r.key=a;r.url="none";r.filter=null}else{r={key:a,url:"none",filter:null};this.#rs.set(t,r)}if(!e||!i)return r.url;const[o,l]=[e,i].map(this.#us.bind(this));let h=Math.round(.2126*o[0]+.7152*o[1]+.0722*o[2]),d=Math.round(.2126*l[0]+.7152*l[1]+.0722*l[2]),[c,u]=[s,n].map(this.#us.bind(this));d{const s=new Array(256),n=(d-h)/i,a=t/255,r=(e-t)/(255*i);let o=0;for(let t=0;t<=i;t++){const e=Math.round(h+t*n),i=a+t*r;for(let t=o;t<=e;t++)s[t]=i;o=e+1}for(let t=o;t<256;t++)s[t]=s[o-1];return s.join(",")},p=`g_${this.#ss}_hcm_${t}_filter`,g=r.filter=this.#ds(p);this.#ps(g);this.#cs(getSteps(c[0],u[0],5),getSteps(c[1],u[1],5),getSteps(c[2],u[2],5),g);r.url=this.#hs(p);return r.url}destroy(t=!1){if(!t||!this.#as?.size){this.#is?.parentNode.parentNode.remove();this.#is=null;this.#es?.clear();this.#es=null;this.#as?.clear();this.#as=null;this.#w=0}}#ms(t){const e=this.#ns.createElementNS(it,"feColorMatrix");e.setAttribute("type","matrix");e.setAttribute("values","0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0");t.append(e)}#ps(t){const e=this.#ns.createElementNS(it,"feColorMatrix");e.setAttribute("type","matrix");e.setAttribute("values","0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0");t.append(e)}#ds(t){const e=this.#ns.createElementNS(it,"filter");e.setAttribute("color-interpolation-filters","sRGB");e.setAttribute("id",t);this.#os.append(e);return e}#fs(t,e,i){const s=this.#ns.createElementNS(it,e);s.setAttribute("type","discrete");s.setAttribute("tableValues",i);t.append(s)}#cs(t,e,i,s){const n=this.#ns.createElementNS(it,"feComponentTransfer");s.append(n);this.#fs(n,"feFuncR",t);this.#fs(n,"feFuncG",e);this.#fs(n,"feFuncB",i)}#gs(t,e){const i=this.#ns.createElementNS(it,"feComponentTransfer");e.append(i);this.#fs(i,"feFuncA",t)}#us(t){this.#os.style.color=t;return getRGB(getComputedStyle(this.#os).getPropertyValue("color"))}},Ft=e?class NodeStandardFontDataFactory extends BaseStandardFontDataFactory{async _fetch(t){return node_utils_fetchData(t)}}:DOMStandardFontDataFactory;function getDocument(t={}){"string"==typeof t||t instanceof URL?t={url:t}:(t instanceof ArrayBuffer||ArrayBuffer.isView(t))&&(t={data:t});const i=new PDFDocumentLoadingTask,{docId:s}=i,n=t.url?function getUrlProp(t){if(t instanceof URL)return t.href;try{return new URL(t,window.location).href}catch{if(e&&"string"==typeof t)return t}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}(t.url):null,a=t.data?function getDataProp(t){if(e&&"undefined"!=typeof Buffer&&t instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(t instanceof Uint8Array&&t.byteLength===t.buffer.byteLength)return t;if("string"==typeof t)return stringToBytes(t);if(t instanceof ArrayBuffer||ArrayBuffer.isView(t)||"object"==typeof t&&!isNaN(t?.length))return new Uint8Array(t);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}(t.data):null,r=t.httpHeaders||null,o=!0===t.withCredentials,l=t.password??null,h=t.range instanceof PDFDataRangeTransport?t.range:null,d=Number.isInteger(t.rangeChunkSize)&&t.rangeChunkSize>0?t.rangeChunkSize:Dt;let c=t.worker instanceof PDFWorker?t.worker:null;const u=t.verbosity,p="string"!=typeof t.docBaseUrl||isDataScheme(t.docBaseUrl)?null:t.docBaseUrl,g="string"==typeof t.cMapUrl?t.cMapUrl:null,m=!1!==t.cMapPacked,f=t.CMapReaderFactory||Rt,b="string"==typeof t.standardFontDataUrl?t.standardFontDataUrl:null,A=t.StandardFontDataFactory||Ft,w=!0!==t.stopAtErrors,v=Number.isInteger(t.maxImageSize)&&t.maxImageSize>-1?t.maxImageSize:-1,y=!1!==t.isEvalSupported,x="boolean"==typeof t.isOffscreenCanvasSupported?t.isOffscreenCanvasSupported:!e,_="boolean"==typeof t.isImageDecoderSupported?t.isImageDecoderSupported:!e&&(util_FeatureTest.platform.isFirefox||!globalThis.chrome),E=Number.isInteger(t.canvasMaxAreaInBytes)?t.canvasMaxAreaInBytes:-1,S="boolean"==typeof t.disableFontFace?t.disableFontFace:e,C=!0===t.fontExtraProperties,T=!0===t.enableXfa,M=t.ownerDocument||globalThis.document,P=!0===t.disableRange,D=!0===t.disableStream,k=!0===t.disableAutoFetch,R=!0===t.pdfBug,I=t.CanvasFactory||kt,F=t.FilterFactory||It,L=!0===t.enableHWA,O=h?h.length:t.length??NaN,N="boolean"==typeof t.useSystemFonts?t.useSystemFonts:!e&&!S,B="boolean"==typeof t.useWorkerFetch?t.useWorkerFetch:f===DOMCMapReaderFactory&&A===DOMStandardFontDataFactory&&g&&b&&isValidFetchUrl(g,document.baseURI)&&isValidFetchUrl(b,document.baseURI);setVerbosityLevel(u);const H={canvasFactory:new I({ownerDocument:M,enableHWA:L}),filterFactory:new F({docId:s,ownerDocument:M}),cMapReaderFactory:B?null:new f({baseUrl:g,isCompressed:m}),standardFontDataFactory:B?null:new A({baseUrl:b})};if(!c){const t={verbosity:u,port:GlobalWorkerOptions.workerPort};c=t.port?PDFWorker.fromPort(t):new PDFWorker(t);i._worker=c}const z={docId:s,apiVersion:"4.10.38",data:a,password:l,disableAutoFetch:k,rangeChunkSize:d,length:O,docBaseUrl:p,enableXfa:T,evaluatorOptions:{maxImageSize:v,disableFontFace:S,ignoreErrors:w,isEvalSupported:y,isOffscreenCanvasSupported:x,isImageDecoderSupported:_,canvasMaxAreaInBytes:E,fontExtraProperties:C,useSystemFonts:N,cMapUrl:B?g:null,standardFontDataUrl:B?b:null}},U={disableFontFace:S,fontExtraProperties:C,ownerDocument:M,pdfBug:R,styleElement:null,loadingParams:{disableAutoFetch:k,enableXfa:T}};c.promise.then((function(){if(i.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const t=c.messageHandler.sendWithPromise("GetDocRequest",z,a?[a.buffer]:null);let l;if(h)l=new PDFDataTransportStream(h,{disableRange:P,disableStream:D});else if(!a){if(!n)throw new Error("getDocument - no `url` parameter provided.");let t;if(e)if(isValidFetchUrl(n)){if("undefined"==typeof fetch||"undefined"==typeof Response||!("body"in Response.prototype))throw new Error("getDocument - the Fetch API was disabled in Node.js, see `--no-experimental-fetch`.");t=PDFFetchStream}else t=PDFNodeStream;else t=isValidFetchUrl(n)?PDFFetchStream:PDFNetworkStream;l=new t({url:n,length:O,httpHeaders:r,withCredentials:o,rangeChunkSize:d,disableRange:P,disableStream:D})}return t.then((t=>{if(i.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const e=new MessageHandler(s,t,c.port),n=new WorkerTransport(e,i,l,U,H);i._transport=n;e.send("Ready",null)}))})).catch(i._capability.reject);return i}function isRefProxy(t){return"object"==typeof t&&Number.isInteger(t?.num)&&t.num>=0&&Number.isInteger(t?.gen)&&t.gen>=0}class PDFDocumentLoadingTask{static#ss=0;constructor(){this._capability=Promise.withResolvers();this._transport=null;this._worker=null;this.docId="d"+PDFDocumentLoadingTask.#ss++;this.destroyed=!1;this.onPassword=null;this.onProgress=null}get promise(){return this._capability.promise}async destroy(){this.destroyed=!0;try{this._worker?.port&&(this._worker._pendingDestroy=!0);await(this._transport?.destroy())}catch(t){this._worker?.port&&delete this._worker._pendingDestroy;throw t}this._transport=null;this._worker?.destroy();this._worker=null}}class PDFDataRangeTransport{constructor(t,e,i=!1,s=null){this.length=t;this.initialData=e;this.progressiveDone=i;this.contentDispositionFilename=s;this._rangeListeners=[];this._progressListeners=[];this._progressiveReadListeners=[];this._progressiveDoneListeners=[];this._readyCapability=Promise.withResolvers()}addRangeListener(t){this._rangeListeners.push(t)}addProgressListener(t){this._progressListeners.push(t)}addProgressiveReadListener(t){this._progressiveReadListeners.push(t)}addProgressiveDoneListener(t){this._progressiveDoneListeners.push(t)}onDataRange(t,e){for(const i of this._rangeListeners)i(t,e)}onDataProgress(t,e){this._readyCapability.promise.then((()=>{for(const i of this._progressListeners)i(t,e)}))}onDataProgressiveRead(t){this._readyCapability.promise.then((()=>{for(const e of this._progressiveReadListeners)e(t)}))}onDataProgressiveDone(){this._readyCapability.promise.then((()=>{for(const t of this._progressiveDoneListeners)t()}))}transportReady(){this._readyCapability.resolve()}requestDataRange(t,e){unreachable("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class PDFDocumentProxy{constructor(t,e){this._pdfInfo=t;this._transport=e}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return shadow(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(t){return this._transport.getPage(t)}getPageIndex(t){return this._transport.getPageIndex(t)}getDestinations(){return this._transport.getDestinations()}getDestination(t){return this._transport.getDestination(t)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getOptionalContentConfig(e)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(t=!1){return this._transport.startCleanup(t||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}cachedPageNumber(t){return this._transport.cachedPageNumber(t)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}class PDFPageProxy{#bs=null;#As=!1;constructor(t,e,i,s=!1){this._pageIndex=t;this._pageInfo=e;this._transport=i;this._stats=s?new StatTimer:null;this._pdfBug=s;this.commonObjs=i.commonObjs;this.objs=new PDFObjects;this._maybeCleanupAfterRender=!1;this._intentStates=new Map;this.destroyed=!1}get pageNumber(){return this._pageIndex+1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:t,rotation:e=this.rotate,offsetX:i=0,offsetY:s=0,dontFlip:n=!1}={}){return new PageViewport({viewBox:this.view,userUnit:this.userUnit,scale:t,rotation:e,offsetX:i,offsetY:s,dontFlip:n})}getAnnotations({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getAnnotations(this._pageIndex,e)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return shadow(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:t,viewport:e,intent:i="display",annotationMode:s=p.ENABLE,transform:n=null,background:a=null,optionalContentConfigPromise:r=null,annotationCanvasMap:l=null,pageColors:h=null,printAnnotationStorage:d=null,isEditing:c=!1}){this._stats?.time("Overall");const u=this._transport.getRenderingIntent(i,s,d,c),{renderingIntent:g,cacheKey:m}=u;this.#As=!1;this.#ws();r||=this._transport.getOptionalContentConfig(g);let f=this._intentStates.get(m);if(!f){f=Object.create(null);this._intentStates.set(m,f)}if(f.streamReaderCancelTimeout){clearTimeout(f.streamReaderCancelTimeout);f.streamReaderCancelTimeout=null}const b=!!(g&o);if(!f.displayReadyCapability){f.displayReadyCapability=Promise.withResolvers();f.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null};this._stats?.time("Page Request");this._pumpOperatorList(u)}const complete=t=>{f.renderTasks.delete(A);(this._maybeCleanupAfterRender||b)&&(this.#As=!0);this.#vs(!b);if(t){A.capability.reject(t);this._abortOperatorList({intentState:f,reason:t instanceof Error?t:new Error(t)})}else A.capability.resolve();if(this._stats){this._stats.timeEnd("Rendering");this._stats.timeEnd("Overall");globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats)}},A=new InternalRenderTask({callback:complete,params:{canvasContext:t,viewport:e,transform:n,background:a},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:l,operatorList:f.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!b,pdfBug:this._pdfBug,pageColors:h});(f.renderTasks||=new Set).add(A);const w=A.task;Promise.all([f.displayReadyCapability.promise,r]).then((([t,e])=>{if(this.destroyed)complete();else{this._stats?.time("Rendering");if(!(e.renderingIntent&g))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");A.initializeGraphics({transparency:t,optionalContentConfig:e});A.operatorListChanged()}})).catch(complete);return w}getOperatorList({intent:t="display",annotationMode:e=p.ENABLE,printAnnotationStorage:i=null,isEditing:s=!1}={}){const n=this._transport.getRenderingIntent(t,e,i,s,!0);let a,r=this._intentStates.get(n.cacheKey);if(!r){r=Object.create(null);this._intentStates.set(n.cacheKey,r)}if(!r.opListReadCapability){a=Object.create(null);a.operatorListChanged=function operatorListChanged(){if(r.operatorList.lastChunk){r.opListReadCapability.resolve(r.operatorList);r.renderTasks.delete(a)}};r.opListReadCapability=Promise.withResolvers();(r.renderTasks||=new Set).add(a);r.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null};this._stats?.time("Page Request");this._pumpOperatorList(n)}return r.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=!1,disableNormalization:e=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,includeMarkedContent:!0===t,disableNormalization:!0===e},{highWaterMark:100,size:t=>t.items.length})}getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then((t=>XfaText.textContent(t)));const e=this.streamTextContent(t);return new Promise((function(t,i){const s=e.getReader(),n={items:[],styles:Object.create(null),lang:null};!function pump(){s.read().then((function({value:e,done:i}){if(i)t(n);else{n.lang??=e.lang;Object.assign(n.styles,e.styles);n.items.push(...e.items);pump()}}),i)}()}))}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const t=[];for(const e of this._intentStates.values()){this._abortOperatorList({intentState:e,reason:new Error("Page was destroyed."),force:!0});if(!e.opListReadCapability)for(const i of e.renderTasks){t.push(i.completed);i.cancel()}}this.objs.clear();this.#As=!1;this.#ws();return Promise.all(t)}cleanup(t=!1){this.#As=!0;const e=this.#vs(!1);t&&e&&(this._stats&&=new StatTimer);return e}#vs(t=!1){this.#ws();if(!this.#As||this.destroyed)return!1;if(t){this.#bs=setTimeout((()=>{this.#bs=null;this.#vs(!1)}),5e3);return!1}for(const{renderTasks:t,operatorList:e}of this._intentStates.values())if(t.size>0||!e.lastChunk)return!1;this._intentStates.clear();this.objs.clear();this.#As=!1;return!0}#ws(){if(this.#bs){clearTimeout(this.#bs);this.#bs=null}}_startRenderPage(t,e){const i=this._intentStates.get(e);if(i){this._stats?.timeEnd("Page Request");i.displayReadyCapability?.resolve(t)}}_renderPageChunk(t,e){for(let i=0,s=t.length;i{r.read().then((({value:t,done:e})=>{if(e)o.streamReader=null;else if(!this._transport.destroyed){this._renderPageChunk(t,o);pump()}}),(t=>{o.streamReader=null;if(!this._transport.destroyed){if(o.operatorList){o.operatorList.lastChunk=!0;for(const t of o.renderTasks)t.operatorListChanged();this.#vs(!0)}if(o.displayReadyCapability)o.displayReadyCapability.reject(t);else{if(!o.opListReadCapability)throw t;o.opListReadCapability.reject(t)}}}))};pump()}_abortOperatorList({intentState:t,reason:e,force:i=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout){clearTimeout(t.streamReaderCancelTimeout);t.streamReaderCancelTimeout=null}if(!i){if(t.renderTasks.size>0)return;if(e instanceof RenderingCancelledException){let i=100;e.extraDelay>0&&e.extraDelay<1e3&&(i+=e.extraDelay);t.streamReaderCancelTimeout=setTimeout((()=>{t.streamReaderCancelTimeout=null;this._abortOperatorList({intentState:t,reason:e,force:!0})}),i);return}}t.streamReader.cancel(new AbortException(e.message)).catch((()=>{}));t.streamReader=null;if(!this._transport.destroyed){for(const[e,i]of this._intentStates)if(i===t){this._intentStates.delete(e);break}this.cleanup()}}}get stats(){return this._stats}}class LoopbackPort{#ys=new Map;#xs=Promise.resolve();postMessage(t,e){const i={data:structuredClone(t,e?{transfer:e}:null)};this.#xs.then((()=>{for(const[t]of this.#ys)t.call(this,i)}))}addEventListener(t,e,i=null){let s=null;if(i?.signal instanceof AbortSignal){const{signal:n}=i;if(n.aborted){warn("LoopbackPort - cannot use an `aborted` signal.");return}const onAbort=()=>this.removeEventListener(t,e);s=()=>n.removeEventListener("abort",onAbort);n.addEventListener("abort",onAbort)}this.#ys.set(e,s)}removeEventListener(t,e){const i=this.#ys.get(e);i?.();this.#ys.delete(e)}terminate(){for(const[,t]of this.#ys)t?.();this.#ys.clear()}}class PDFWorker{static#_s=0;static#Es=!1;static#Ss;static{if(e){this.#Es=!0;GlobalWorkerOptions.workerSrc||="./pdf.worker.mjs"}this._isSameOrigin=(t,e)=>{let i;try{i=new URL(t);if(!i.origin||"null"===i.origin)return!1}catch{return!1}const s=new URL(e,i);return i.origin===s.origin};this._createCDNWrapper=t=>{const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))}}constructor({name:t=null,port:e=null,verbosity:i=getVerbosityLevel()}={}){this.name=t;this.destroyed=!1;this.verbosity=i;this._readyCapability=Promise.withResolvers();this._port=null;this._webWorker=null;this._messageHandler=null;if(e){if(PDFWorker.#Ss?.has(e))throw new Error("Cannot use more than one PDFWorker per port.");(PDFWorker.#Ss||=new WeakMap).set(e,this);this._initializeFromPort(e)}else this._initialize()}get promise(){return this._readyCapability.promise}#Cs(){this._readyCapability.resolve();this._messageHandler.send("configure",{verbosity:this.verbosity})}get port(){return this._port}get messageHandler(){return this._messageHandler}_initializeFromPort(t){this._port=t;this._messageHandler=new MessageHandler("main","worker",t);this._messageHandler.on("ready",(function(){}));this.#Cs()}_initialize(){if(PDFWorker.#Es||PDFWorker.#Ts){this._setupFakeWorker();return}let{workerSrc:t}=PDFWorker;try{PDFWorker._isSameOrigin(window.location.href,t)||(t=PDFWorker._createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),i=new MessageHandler("main","worker",e),terminateEarly=()=>{s.abort();i.destroy();e.terminate();this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()},s=new AbortController;e.addEventListener("error",(()=>{this._webWorker||terminateEarly()}),{signal:s.signal});i.on("test",(t=>{s.abort();if(!this.destroyed&&t){this._messageHandler=i;this._port=e;this._webWorker=e;this.#Cs()}else terminateEarly()}));i.on("ready",(t=>{s.abort();if(this.destroyed)terminateEarly();else try{sendTest()}catch{this._setupFakeWorker()}}));const sendTest=()=>{const t=new Uint8Array;i.send("test",t,[t.buffer])};sendTest();return}catch{info("The worker has been disabled.")}this._setupFakeWorker()}_setupFakeWorker(){if(!PDFWorker.#Es){warn("Setting up fake worker.");PDFWorker.#Es=!0}PDFWorker._setupFakeWorkerGlobal.then((t=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}const e=new LoopbackPort;this._port=e;const i="fake"+PDFWorker.#_s++,s=new MessageHandler(i+"_worker",i,e);t.setup(s,e);this._messageHandler=new MessageHandler(i,i+"_worker",e);this.#Cs()})).catch((t=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${t.message}".`))}))}destroy(){this.destroyed=!0;this._webWorker?.terminate();this._webWorker=null;PDFWorker.#Ss?.delete(this._port);this._port=null;this._messageHandler?.destroy();this._messageHandler=null}static fromPort(t){if(!t?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");const e=this.#Ss?.get(t.port);if(e){if(e._pendingDestroy)throw new Error("PDFWorker.fromPort - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return e}return new PDFWorker(t)}static get workerSrc(){if(GlobalWorkerOptions.workerSrc)return GlobalWorkerOptions.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get#Ts(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return shadow(this,"_setupFakeWorkerGlobal",(async()=>{if(this.#Ts)return this.#Ts;return(await import(this.workerSrc)).WorkerMessageHandler})())}}class WorkerTransport{#Ms=new Map;#Ps=new Map;#Ds=new Map;#ks=new Map;#Rs=null;constructor(t,e,i,s,n){this.messageHandler=t;this.loadingTask=e;this.commonObjs=new PDFObjects;this.fontLoader=new FontLoader({ownerDocument:s.ownerDocument,styleElement:s.styleElement});this.loadingParams=s.loadingParams;this._params=s;this.canvasFactory=n.canvasFactory;this.filterFactory=n.filterFactory;this.cMapReaderFactory=n.cMapReaderFactory;this.standardFontDataFactory=n.standardFontDataFactory;this.destroyed=!1;this.destroyCapability=null;this._networkStream=i;this._fullReader=null;this._lastProgress=null;this.downloadInfoCapability=Promise.withResolvers();this.setupMessageHandler()}#Is(t,e=null){const i=this.#Ms.get(t);if(i)return i;const s=this.messageHandler.sendWithPromise(t,e);this.#Ms.set(t,s);return s}get annotationStorage(){return shadow(this,"annotationStorage",new AnnotationStorage)}getRenderingIntent(t,e=p.ENABLE,i=null,s=!1,n=!1){let g=r,m=rt;switch(t){case"any":g=a;break;case"display":break;case"print":g=o;break;default:warn(`getRenderingIntent - invalid intent: ${t}`)}const f=g&o&&i instanceof PrintAnnotationStorage?i:this.annotationStorage;switch(e){case p.DISABLE:g+=d;break;case p.ENABLE:break;case p.ENABLE_FORMS:g+=l;break;case p.ENABLE_STORAGE:g+=h;m=f.serializable;break;default:warn(`getRenderingIntent - invalid annotationMode: ${e}`)}s&&(g+=c);n&&(g+=u);const{ids:b,hash:A}=f.modifiedIds;return{renderingIntent:g,cacheKey:[g,m.hash,A].join("_"),annotationStorageSerializable:m,modifiedIds:b}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0;this.destroyCapability=Promise.withResolvers();this.#Rs?.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const e of this.#Ps.values())t.push(e._destroy());this.#Ps.clear();this.#Ds.clear();this.#ks.clear();this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();const e=this.messageHandler.sendWithPromise("Terminate",null);t.push(e);Promise.all(t).then((()=>{this.commonObjs.clear();this.fontLoader.clear();this.#Ms.clear();this.filterFactory.destroy();TextLayer.cleanup();this._networkStream?.cancelAllRequests(new AbortException("Worker was terminated."));this.messageHandler?.destroy();this.messageHandler=null;this.destroyCapability.resolve()}),this.destroyCapability.reject);return this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:t,loadingTask:e}=this;t.on("GetReader",((t,e)=>{assert(this._networkStream,"GetReader - no `IPDFStream` instance available.");this._fullReader=this._networkStream.getFullReader();this._fullReader.onProgress=t=>{this._lastProgress={loaded:t.loaded,total:t.total}};e.onPull=()=>{this._fullReader.read().then((function({value:t,done:i}){if(i)e.close();else{assert(t instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer.");e.enqueue(new Uint8Array(t),1,[t])}})).catch((t=>{e.error(t)}))};e.onCancel=t=>{this._fullReader.cancel(t);e.ready.catch((t=>{if(!this.destroyed)throw t}))}}));t.on("ReaderHeadersReady",(async t=>{await this._fullReader.headersReady;const{isStreamingSupported:i,isRangeSupported:s,contentLength:n}=this._fullReader;if(!i||!s){this._lastProgress&&e.onProgress?.(this._lastProgress);this._fullReader.onProgress=t=>{e.onProgress?.({loaded:t.loaded,total:t.total})}}return{isStreamingSupported:i,isRangeSupported:s,contentLength:n}}));t.on("GetRangeReader",((t,e)=>{assert(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");const i=this._networkStream.getRangeReader(t.begin,t.end);if(i){e.onPull=()=>{i.read().then((function({value:t,done:i}){if(i)e.close();else{assert(t instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer.");e.enqueue(new Uint8Array(t),1,[t])}})).catch((t=>{e.error(t)}))};e.onCancel=t=>{i.cancel(t);e.ready.catch((t=>{if(!this.destroyed)throw t}))}}else e.close()}));t.on("GetDoc",(({pdfInfo:t})=>{this._numPages=t.numPages;this._htmlForXfa=t.htmlForXfa;delete t.htmlForXfa;e._capability.resolve(new PDFDocumentProxy(t,this))}));t.on("DocException",(t=>{e._capability.reject(wrapReason(t))}));t.on("PasswordRequest",(t=>{this.#Rs=Promise.withResolvers();try{if(!e.onPassword)throw wrapReason(t);const updatePassword=t=>{t instanceof Error?this.#Rs.reject(t):this.#Rs.resolve({password:t})};e.onPassword(updatePassword,t.code)}catch(t){this.#Rs.reject(t)}return this.#Rs.promise}));t.on("DataLoaded",(t=>{e.onProgress?.({loaded:t.length,total:t.length});this.downloadInfoCapability.resolve(t)}));t.on("StartRenderPage",(t=>{if(this.destroyed)return;this.#Ps.get(t.pageIndex)._startRenderPage(t.transparency,t.cacheKey)}));t.on("commonobj",(([e,i,s])=>{if(this.destroyed)return null;if(this.commonObjs.has(e))return null;switch(i){case"Font":const{disableFontFace:n,fontExtraProperties:a,pdfBug:r}=this._params;if("error"in s){const t=s.error;warn(`Error during font loading: ${t}`);this.commonObjs.resolve(e,t);break}const o=r&&globalThis.FontInspector?.enabled?(t,e)=>globalThis.FontInspector.fontAdded(t,e):null,l=new FontFaceObject(s,{disableFontFace:n,fontExtraProperties:a,inspectFont:o});this.fontLoader.bind(l).catch((()=>t.sendWithPromise("FontFallback",{id:e}))).finally((()=>{!a&&l.data&&(l.data=null);this.commonObjs.resolve(e,l)}));break;case"CopyLocalImage":const{imageRef:h}=s;assert(h,"The imageRef must be defined.");for(const t of this.#Ps.values())for(const[,i]of t.objs)if(i?.ref===h){if(!i.dataLen)return null;this.commonObjs.resolve(e,structuredClone(i));return i.dataLen}break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(e,s);break;default:throw new Error(`Got unknown common object type ${i}`)}return null}));t.on("obj",(([t,e,i,s])=>{if(this.destroyed)return;const n=this.#Ps.get(e);if(!n.objs.has(t))if(0!==n._intentStates.size)switch(i){case"Image":n.objs.resolve(t,s);s?.dataLen>1e7&&(n._maybeCleanupAfterRender=!0);break;case"Pattern":n.objs.resolve(t,s);break;default:throw new Error(`Got unknown object type ${i}`)}else s?.bitmap?.close()}));t.on("DocProgress",(t=>{this.destroyed||e.onProgress?.({loaded:t.loaded,total:t.total})}));t.on("FetchBuiltInCMap",(async t=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.cMapReaderFactory)throw new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter.");return this.cMapReaderFactory.fetch(t)}));t.on("FetchStandardFontData",(async t=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.standardFontDataFactory)throw new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter.");return this.standardFontDataFactory.fetch(t)}))}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&warn("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:t,transfer:e}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:this._fullReader?.filename??null},e).finally((()=>{this.annotationStorage.resetModified()}))}getPage(t){if(!Number.isInteger(t)||t<=0||t>this._numPages)return Promise.reject(new Error("Invalid page request."));const e=t-1,i=this.#Ds.get(e);if(i)return i;const s=this.messageHandler.sendWithPromise("GetPage",{pageIndex:e}).then((i=>{if(this.destroyed)throw new Error("Transport destroyed");i.refStr&&this.#ks.set(i.refStr,t);const s=new PDFPageProxy(e,i,this,this._params.pdfBug);this.#Ps.set(e,s);return s}));this.#Ds.set(e,s);return s}getPageIndex(t){return isRefProxy(t)?this.messageHandler.sendWithPromise("GetPageIndex",{num:t.num,gen:t.gen}):Promise.reject(new Error("Invalid pageIndex request."))}getAnnotations(t,e){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:t,intent:e})}getFieldObjects(){return this.#Is("GetFieldObjects")}hasJSActions(){return this.#Is("HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(t){return"string"!=typeof t?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:t})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getDocJSActions(){return this.#Is("GetDocJSActions")}getPageJSActions(t){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:t})}getStructTree(t){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:t})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(t){return this.#Is("GetOptionalContentConfig").then((e=>new OptionalContentConfig(e,t)))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",e=this.#Ms.get(t);if(e)return e;const i=this.messageHandler.sendWithPromise(t,null).then((t=>({info:t[0],metadata:t[1]?new Metadata(t[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null})));this.#Ms.set(t,i);return i}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(t=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const t of this.#Ps.values()){if(!t.cleanup())throw new Error(`startCleanup: Page ${t.pageNumber} is currently rendering.`)}this.commonObjs.clear();t||this.fontLoader.clear();this.#Ms.clear();this.filterFactory.destroy(!0);TextLayer.cleanup()}}cachedPageNumber(t){if(!isRefProxy(t))return null;const e=0===t.gen?`${t.num}R`:`${t.num}R${t.gen}`;return this.#ks.get(e)??null}}const Lt=Symbol("INITIAL_DATA");class PDFObjects{#Fs=Object.create(null);#Ls(t){return this.#Fs[t]||={...Promise.withResolvers(),data:Lt}}get(t,e=null){if(e){const i=this.#Ls(t);i.promise.then((()=>e(i.data)));return null}const i=this.#Fs[t];if(!i||i.data===Lt)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return i.data}has(t){const e=this.#Fs[t];return!!e&&e.data!==Lt}delete(t){const e=this.#Fs[t];if(!e||e.data===Lt)return!1;delete this.#Fs[t];return!0}resolve(t,e=null){const i=this.#Ls(t);i.data=e;i.resolve()}clear(){for(const t in this.#Fs){const{data:e}=this.#Fs[t];e?.bitmap?.close()}this.#Fs=Object.create(null)}*[Symbol.iterator](){for(const t in this.#Fs){const{data:e}=this.#Fs[t];e!==Lt&&(yield[t,e])}}}class RenderTask{#Os=null;constructor(t){this.#Os=t;this.onContinue=null}get promise(){return this.#Os.capability.promise}cancel(t=0){this.#Os.cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=this.#Os.operatorList;if(!t)return!1;const{annotationCanvasMap:e}=this.#Os;return t.form||t.canvas&&e?.size>0}}class InternalRenderTask{#Ns=null;static#Bs=new WeakSet;constructor({callback:t,params:e,objs:i,commonObjs:s,annotationCanvasMap:n,operatorList:a,pageIndex:r,canvasFactory:o,filterFactory:l,useRequestAnimationFrame:h=!1,pdfBug:d=!1,pageColors:c=null}){this.callback=t;this.params=e;this.objs=i;this.commonObjs=s;this.annotationCanvasMap=n;this.operatorListIdx=null;this.operatorList=a;this._pageIndex=r;this.canvasFactory=o;this.filterFactory=l;this._pdfBug=d;this.pageColors=c;this.running=!1;this.graphicsReadyCallback=null;this.graphicsReady=!1;this._useRequestAnimationFrame=!0===h&&"undefined"!=typeof window;this.cancelled=!1;this.capability=Promise.withResolvers();this.task=new RenderTask(this);this._cancelBound=this.cancel.bind(this);this._continueBound=this._continue.bind(this);this._scheduleNextBound=this._scheduleNext.bind(this);this._nextBound=this._next.bind(this);this._canvas=e.canvasContext.canvas}get completed(){return this.capability.promise.catch((function(){}))}initializeGraphics({transparency:t=!1,optionalContentConfig:e}){if(this.cancelled)return;if(this._canvas){if(InternalRenderTask.#Bs.has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");InternalRenderTask.#Bs.add(this._canvas)}if(this._pdfBug&&globalThis.StepperManager?.enabled){this.stepper=globalThis.StepperManager.create(this._pageIndex);this.stepper.init(this.operatorList);this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint()}const{canvasContext:i,viewport:s,transform:n,background:a}=this.params;this.gfx=new CanvasGraphics(i,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:e},this.annotationCanvasMap,this.pageColors);this.gfx.beginDrawing({transform:n,viewport:s,transparency:t,background:a});this.operatorListIdx=0;this.graphicsReady=!0;this.graphicsReadyCallback?.()}cancel(t=null,e=0){this.running=!1;this.cancelled=!0;this.gfx?.endDrawing();if(this.#Ns){window.cancelAnimationFrame(this.#Ns);this.#Ns=null}InternalRenderTask.#Bs.delete(this._canvas);this.callback(t||new RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex+1}`,e))}operatorListChanged(){if(this.graphicsReady){this.stepper?.updateOperatorList(this.operatorList);this.running||this._continue()}else this.graphicsReadyCallback||=this._continueBound}_continue(){this.running=!0;this.cancelled||(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?this.#Ns=window.requestAnimationFrame((()=>{this.#Ns=null;this._nextBound().catch(this._cancelBound)})):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){if(!this.cancelled){this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper);if(this.operatorListIdx===this.operatorList.argsArray.length){this.running=!1;if(this.operatorList.lastChunk){this.gfx.endDrawing();InternalRenderTask.#Bs.delete(this._canvas);this.callback()}}}}}const Ot="4.10.38",Nt="f9bea397f";function makeColorComp(t){return Math.floor(255*Math.max(0,Math.min(1,t))).toString(16).padStart(2,"0")}function scaleAndClamp(t){return Math.max(0,Math.min(255,255*t))}class ColorConverters{static CMYK_G([t,e,i,s]){return["G",1-Math.min(1,.3*t+.59*i+.11*e+s)]}static G_CMYK([t]){return["CMYK",0,0,0,1-t]}static G_RGB([t]){return["RGB",t,t,t]}static G_rgb([t]){return[t=scaleAndClamp(t),t,t]}static G_HTML([t]){const e=makeColorComp(t);return`#${e}${e}${e}`}static RGB_G([t,e,i]){return["G",.3*t+.59*e+.11*i]}static RGB_rgb(t){return t.map(scaleAndClamp)}static RGB_HTML(t){return`#${t.map(makeColorComp).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([t,e,i,s]){return["RGB",1-Math.min(1,t+s),1-Math.min(1,i+s),1-Math.min(1,e+s)]}static CMYK_rgb([t,e,i,s]){return[scaleAndClamp(1-Math.min(1,t+s)),scaleAndClamp(1-Math.min(1,i+s)),scaleAndClamp(1-Math.min(1,e+s))]}static CMYK_HTML(t){const e=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(e)}static RGB_CMYK([t,e,i]){const s=1-t,n=1-e,a=1-i;return["CMYK",s,n,a,Math.min(s,n,a)]}}class BaseSVGFactory{create(t,e,i=!1){if(t<=0||e<=0)throw new Error("Invalid SVG dimensions");const s=this._createSVG("svg:svg");s.setAttribute("version","1.1");if(!i){s.setAttribute("width",`${t}px`);s.setAttribute("height",`${e}px`)}s.setAttribute("preserveAspectRatio","none");s.setAttribute("viewBox",`0 0 ${t} ${e}`);return s}createElement(t){if("string"!=typeof t)throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){unreachable("Abstract method `_createSVG` called.")}}class DOMSVGFactory extends BaseSVGFactory{_createSVG(t){return document.createElementNS(it,t)}}class XfaLayer{static setupStorage(t,e,i,s,n){const a=s.getValue(e,{value:null});switch(i.name){case"textarea":null!==a.value&&(t.textContent=a.value);if("print"===n)break;t.addEventListener("input",(t=>{s.setValue(e,{value:t.target.value})}));break;case"input":if("radio"===i.attributes.type||"checkbox"===i.attributes.type){a.value===i.attributes.xfaOn?t.setAttribute("checked",!0):a.value===i.attributes.xfaOff&&t.removeAttribute("checked");if("print"===n)break;t.addEventListener("change",(t=>{s.setValue(e,{value:t.target.checked?t.target.getAttribute("xfaOn"):t.target.getAttribute("xfaOff")})}))}else{null!==a.value&&t.setAttribute("value",a.value);if("print"===n)break;t.addEventListener("input",(t=>{s.setValue(e,{value:t.target.value})}))}break;case"select":if(null!==a.value){t.setAttribute("value",a.value);for(const t of i.children)t.attributes.value===a.value?t.attributes.selected=!0:t.attributes.hasOwnProperty("selected")&&delete t.attributes.selected}t.addEventListener("input",(t=>{const i=t.target.options,n=-1===i.selectedIndex?"":i[i.selectedIndex].value;s.setValue(e,{value:n})}))}}static setAttributes({html:t,element:e,storage:i=null,intent:s,linkService:n}){const{attributes:a}=e,r=t instanceof HTMLAnchorElement;"radio"===a.type&&(a.name=`${a.name}-${s}`);for(const[e,i]of Object.entries(a))if(null!=i)switch(e){case"class":i.length&&t.setAttribute(e,i.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",i);break;case"style":Object.assign(t.style,i);break;case"textContent":t.textContent=i;break;default:(!r||"href"!==e&&"newWindow"!==e)&&t.setAttribute(e,i)}r&&n.addLinkAttributes(t,a.href,a.newWindow);i&&a.dataId&&this.setupStorage(t,a.dataId,e,i)}static render(t){const e=t.annotationStorage,i=t.linkService,s=t.xfaHtml,n=t.intent||"display",a=document.createElement(s.name);s.attributes&&this.setAttributes({html:a,element:s,intent:n,linkService:i});const r="richText"!==n,o=t.div;o.append(a);if(t.viewport){const e=`matrix(${t.viewport.transform.join(",")})`;o.style.transform=e}r&&o.setAttribute("class","xfaLayer xfaFont");const l=[];if(0===s.children.length){if(s.value){const t=document.createTextNode(s.value);a.append(t);r&&XfaText.shouldBuildText(s.name)&&l.push(t)}return{textDivs:l}}const h=[[s,-1,a]];for(;h.length>0;){const[t,s,a]=h.at(-1);if(s+1===t.children.length){h.pop();continue}const o=t.children[++h.at(-1)[1]];if(null===o)continue;const{name:d}=o;if("#text"===d){const t=document.createTextNode(o.value);l.push(t);a.append(t);continue}const c=o?.attributes?.xmlns?document.createElementNS(o.attributes.xmlns,d):document.createElement(d);a.append(c);o.attributes&&this.setAttributes({html:c,element:o,storage:e,intent:n,linkService:i});if(o.children?.length>0)h.push([o,-1,c]);else if(o.value){const t=document.createTextNode(o.value);r&&XfaText.shouldBuildText(d)&&l.push(t);c.append(t)}}for(const t of o.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))t.setAttribute("readOnly",!0);return{textDivs:l}}static update(t){const e=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=e;t.div.hidden=!1}}const Bt=1e3,Ht=new WeakSet;function getRectDims(t){return{width:t[2]-t[0],height:t[3]-t[1]}}class AnnotationElementFactory{static create(t){switch(t.data.annotationType){case S:return new LinkAnnotationElement(t);case E:return new TextAnnotationElement(t);case U:switch(t.data.fieldType){case"Tx":return new TextWidgetAnnotationElement(t);case"Btn":return t.data.radioButton?new RadioButtonWidgetAnnotationElement(t):t.data.checkBox?new CheckboxWidgetAnnotationElement(t):new PushButtonWidgetAnnotationElement(t);case"Ch":return new ChoiceWidgetAnnotationElement(t);case"Sig":return new SignatureWidgetAnnotationElement(t)}return new WidgetAnnotationElement(t);case H:return new PopupAnnotationElement(t);case C:return new FreeTextAnnotationElement(t);case T:return new LineAnnotationElement(t);case M:return new SquareAnnotationElement(t);case P:return new CircleAnnotationElement(t);case k:return new PolylineAnnotationElement(t);case N:return new CaretAnnotationElement(t);case B:return new InkAnnotationElement(t);case D:return new PolygonAnnotationElement(t);case R:return new HighlightAnnotationElement(t);case I:return new UnderlineAnnotationElement(t);case F:return new SquigglyAnnotationElement(t);case L:return new StrikeOutAnnotationElement(t);case O:return new StampAnnotationElement(t);case z:return new FileAttachmentAnnotationElement(t);default:return new AnnotationElement(t)}}}class AnnotationElement{#Hs=null;#zs=!1;#Us=null;constructor(t,{isRenderable:e=!1,ignoreBorder:i=!1,createQuadrilaterals:s=!1}={}){this.isRenderable=e;this.data=t.data;this.layer=t.layer;this.linkService=t.linkService;this.downloadManager=t.downloadManager;this.imageResourcesPath=t.imageResourcesPath;this.renderForms=t.renderForms;this.svgFactory=t.svgFactory;this.annotationStorage=t.annotationStorage;this.enableScripting=t.enableScripting;this.hasJSActions=t.hasJSActions;this._fieldObjects=t.fieldObjects;this.parent=t.parent;e&&(this.container=this._createContainer(i));s&&this._createQuadrilaterals()}static _hasPopupData({titleObj:t,contentsObj:e,richText:i}){return!!(t?.str||e?.str||i?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return AnnotationElement._hasPopupData(this.data)}updateEdited(t){if(!this.container)return;this.#Hs||={rect:this.data.rect.slice(0)};const{rect:e}=t;e&&this.#Gs(e);this.#Us?.popup.updateEdited(t)}resetEdited(){if(this.#Hs){this.#Gs(this.#Hs.rect);this.#Us?.popup.resetEdited();this.#Hs=null}}#Gs(t){const{container:{style:e},data:{rect:i,rotation:s},parent:{viewport:{rawDims:{pageWidth:n,pageHeight:a,pageX:r,pageY:o}}}}=this;i?.splice(0,4,...t);const{width:l,height:h}=getRectDims(t);e.left=100*(t[0]-r)/n+"%";e.top=100*(a-t[3]+o)/a+"%";if(0===s){e.width=100*l/n+"%";e.height=100*h/a+"%"}else this.setRotation(s)}_createContainer(t){const{data:e,parent:{page:i,viewport:s}}=this,n=document.createElement("section");n.setAttribute("data-annotation-id",e.id);this instanceof WidgetAnnotationElement||(n.tabIndex=Bt);const{style:a}=n;a.zIndex=this.parent.zIndex++;e.alternativeText&&(n.title=e.alternativeText);e.noRotate&&n.classList.add("norotate");if(!e.rect||this instanceof PopupAnnotationElement){const{rotation:t}=e;e.hasOwnCanvas||0===t||this.setRotation(t,n);return n}const{width:r,height:o}=getRectDims(e.rect);if(!t&&e.borderStyle.width>0){a.borderWidth=`${e.borderStyle.width}px`;const t=e.borderStyle.horizontalCornerRadius,i=e.borderStyle.verticalCornerRadius;if(t>0||i>0){const e=`calc(${t}px * var(--scale-factor)) / calc(${i}px * var(--scale-factor))`;a.borderRadius=e}else if(this instanceof RadioButtonWidgetAnnotationElement){const t=`calc(${r}px * var(--scale-factor)) / calc(${o}px * var(--scale-factor))`;a.borderRadius=t}switch(e.borderStyle.style){case G:a.borderStyle="solid";break;case $:a.borderStyle="dashed";break;case V:warn("Unimplemented border style: beveled");break;case j:warn("Unimplemented border style: inset");break;case W:a.borderBottomStyle="solid"}const s=e.borderColor||null;if(s){this.#zs=!0;a.borderColor=Util.makeHexColor(0|s[0],0|s[1],0|s[2])}else a.borderWidth=0}const l=Util.normalizeRect([e.rect[0],i.view[3]-e.rect[1]+i.view[1],e.rect[2],i.view[3]-e.rect[3]+i.view[1]]),{pageWidth:h,pageHeight:d,pageX:c,pageY:u}=s.rawDims;a.left=100*(l[0]-c)/h+"%";a.top=100*(l[1]-u)/d+"%";const{rotation:p}=e;if(e.hasOwnCanvas||0===p){a.width=100*r/h+"%";a.height=100*o/d+"%"}else this.setRotation(p,n);return n}setRotation(t,e=this.container){if(!this.data.rect)return;const{pageWidth:i,pageHeight:s}=this.parent.viewport.rawDims,{width:n,height:a}=getRectDims(this.data.rect);let r,o;if(t%180==0){r=100*n/i;o=100*a/s}else{r=100*a/i;o=100*n/s}e.style.width=`${r}%`;e.style.height=`${o}%`;e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const setColor=(t,e,i)=>{const s=i.detail[t],n=s[0],a=s.slice(1);i.target.style[e]=ColorConverters[`${n}_HTML`](a);this.annotationStorage.setValue(this.data.id,{[e]:ColorConverters[`${n}_rgb`](a)})};return shadow(this,"_commonActions",{display:t=>{const{display:e}=t.detail,i=e%2==1;this.container.style.visibility=i?"hidden":"visible";this.annotationStorage.setValue(this.data.id,{noView:i,noPrint:1===e||2===e})},print:t=>{this.annotationStorage.setValue(this.data.id,{noPrint:!t.detail.print})},hidden:t=>{const{hidden:e}=t.detail;this.container.style.visibility=e?"hidden":"visible";this.annotationStorage.setValue(this.data.id,{noPrint:e,noView:e})},focus:t=>{setTimeout((()=>t.target.focus({preventScroll:!1})),0)},userName:t=>{t.target.title=t.detail.userName},readonly:t=>{t.target.disabled=t.detail.readonly},required:t=>{this._setRequired(t.target,t.detail.required)},bgColor:t=>{setColor("bgColor","backgroundColor",t)},fillColor:t=>{setColor("fillColor","backgroundColor",t)},fgColor:t=>{setColor("fgColor","color",t)},textColor:t=>{setColor("textColor","color",t)},borderColor:t=>{setColor("borderColor","borderColor",t)},strokeColor:t=>{setColor("strokeColor","borderColor",t)},rotation:t=>{const e=t.detail.rotation;this.setRotation(e);this.annotationStorage.setValue(this.data.id,{rotation:e})}})}_dispatchEventFromSandbox(t,e){const i=this._commonActions;for(const s of Object.keys(e.detail)){const n=t[s]||i[s];n?.(e)}}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;const e=this.annotationStorage.getRawValue(this.data.id);if(!e)return;const i=this._commonActions;for(const[s,n]of Object.entries(e)){const a=i[s];if(a){a({detail:{[s]:n},target:t});delete e[s]}}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:t}=this.data;if(!t)return;const[e,i,s,n]=this.data.rect.map((t=>Math.fround(t)));if(8===t.length){const[a,r,o,l]=t.subarray(2,6);if(s===a&&n===r&&e===o&&i===l)return}const{style:a}=this.container;let r;if(this.#zs){const{borderColor:t,borderWidth:e}=a;a.borderWidth=0;r=["url('data:image/svg+xml;utf8,",'',``];this.container.classList.add("hasBorder")}const o=s-e,l=n-i,{svgFactory:h}=this,d=h.createElement("svg");d.classList.add("quadrilateralsContainer");d.setAttribute("width",0);d.setAttribute("height",0);const c=h.createElement("defs");d.append(c);const u=h.createElement("clipPath"),p=`clippath_${this.data.id}`;u.setAttribute("id",p);u.setAttribute("clipPathUnits","objectBoundingBox");c.append(u);for(let i=2,s=t.length;i`)}if(this.#zs){r.push("')");a.backgroundImage=r.join("")}this.container.append(d);this.container.style.clipPath=`url(#${p})`}_createPopup(){const{data:t}=this,e=this.#Us=new PopupAnnotationElement({data:{color:t.color,titleObj:t.titleObj,modificationDate:t.modificationDate,contentsObj:t.contentsObj,richText:t.richText,parentRect:t.rect,borderStyle:0,id:`popup_${t.id}`,rotation:t.rotation},parent:this.parent,elements:[this]});this.parent.div.append(e.render())}render(){unreachable("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){const i=[];if(this._fieldObjects){const s=this._fieldObjects[t];if(s)for(const{page:t,id:n,exportValues:a}of s){if(-1===t)continue;if(n===e)continue;const s="string"==typeof a?a:null,r=document.querySelector(`[data-element-id="${n}"]`);!r||Ht.has(r)?i.push({id:n,exportValue:s,domElement:r}):warn(`_getElementsByName - element not allowed: ${n}`)}return i}for(const s of document.getElementsByName(t)){const{exportValue:t}=s,n=s.getAttribute("data-element-id");n!==e&&(Ht.has(s)&&i.push({id:n,exportValue:t,domElement:s}))}return i}show(){this.container&&(this.container.hidden=!1);this.popup?.maybeShow()}hide(){this.container&&(this.container.hidden=!0);this.popup?.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){const t=this.getElementsToTriggerPopup();if(Array.isArray(t))for(const e of t)e.classList.add("highlightArea");else t.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;const{annotationEditorType:t,data:{id:e}}=this;this.container.addEventListener("dblclick",(()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:t,editId:e})}))}}class LinkAnnotationElement extends AnnotationElement{constructor(t,e=null){super(t,{isRenderable:!0,ignoreBorder:!!e?.ignoreBorder,createQuadrilaterals:!0});this.isTooltipOnly=t.data.isTooltipOnly}render(){const{data:t,linkService:e}=this,i=document.createElement("a");i.setAttribute("data-element-id",t.id);let s=!1;if(t.url){e.addLinkAttributes(i,t.url,t.newWindow);s=!0}else if(t.action){this._bindNamedAction(i,t.action);s=!0}else if(t.attachment){this.#$s(i,t.attachment,t.attachmentDest);s=!0}else if(t.setOCGState){this.#Vs(i,t.setOCGState);s=!0}else if(t.dest){this._bindLink(i,t.dest);s=!0}else{if(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions){this._bindJSAction(i,t);s=!0}if(t.resetForm){this._bindResetFormAction(i,t.resetForm);s=!0}else if(this.isTooltipOnly&&!s){this._bindLink(i,"");s=!0}}this.container.classList.add("linkAnnotation");s&&this.container.append(i);return this.container}#js(){this.container.setAttribute("data-internal-link","")}_bindLink(t,e){t.href=this.linkService.getDestinationHash(e);t.onclick=()=>{e&&this.linkService.goToDestination(e);return!1};(e||""===e)&&this.#js()}_bindNamedAction(t,e){t.href=this.linkService.getAnchorUrl("");t.onclick=()=>{this.linkService.executeNamedAction(e);return!1};this.#js()}#$s(t,e,i=null){t.href=this.linkService.getAnchorUrl("");e.description&&(t.title=e.description);t.onclick=()=>{this.downloadManager?.openOrDownloadData(e.content,e.filename,i);return!1};this.#js()}#Vs(t,e){t.href=this.linkService.getAnchorUrl("");t.onclick=()=>{this.linkService.executeSetOCGState(e);return!1};this.#js()}_bindJSAction(t,e){t.href=this.linkService.getAnchorUrl("");const i=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const s of Object.keys(e.actions)){const n=i.get(s);n&&(t[n]=()=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e.id,name:s}});return!1})}t.onclick||(t.onclick=()=>!1);this.#js()}_bindResetFormAction(t,e){const i=t.onclick;i||(t.href=this.linkService.getAnchorUrl(""));this.#js();if(this._fieldObjects)t.onclick=()=>{i?.();const{fields:t,refs:s,include:n}=e,a=[];if(0!==t.length||0!==s.length){const e=new Set(s);for(const i of t){const t=this._fieldObjects[i]||[];for(const{id:i}of t)e.add(i)}for(const t of Object.values(this._fieldObjects))for(const i of t)e.has(i.id)===n&&a.push(i)}else for(const t of Object.values(this._fieldObjects))a.push(...t);const r=this.annotationStorage,o=[];for(const t of a){const{id:e}=t;o.push(e);switch(t.type){case"text":{const i=t.defaultValue||"";r.setValue(e,{value:i});break}case"checkbox":case"radiobutton":{const i=t.defaultValue===t.exportValues;r.setValue(e,{value:i});break}case"combobox":case"listbox":{const i=t.defaultValue||"";r.setValue(e,{value:i});break}default:continue}const i=document.querySelector(`[data-element-id="${e}"]`);i&&(Ht.has(i)?i.dispatchEvent(new Event("resetform")):warn(`_bindResetFormAction - element not allowed: ${e}`))}this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:o,name:"ResetForm"}});return!1};else{warn('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.');i||(t.onclick=()=>!1)}}}class TextAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");const t=document.createElement("img");t.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg";t.setAttribute("data-l10n-id","pdfjs-text-annotation-type");t.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name}));!this.data.popupRef&&this.hasPopupData&&this._createPopup();this.container.append(t);return this.container}}class WidgetAnnotationElement extends AnnotationElement{render(){return this.container}showElementAndHideCanvas(t){if(this.data.hasOwnCanvas){"CANVAS"===t.previousSibling?.nodeName&&(t.previousSibling.hidden=!0);t.hidden=!1}}_getKeyModifier(t){return util_FeatureTest.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,e,i,s,n){i.includes("mouse")?t.addEventListener(i,(t=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:s,value:n(t),shift:t.shiftKey,modifier:this._getKeyModifier(t)}})})):t.addEventListener(i,(t=>{if("blur"===i){if(!e.focused||!t.relatedTarget)return;e.focused=!1}else if("focus"===i){if(e.focused)return;e.focused=!0}n&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:s,value:n(t)}})}))}_setEventListeners(t,e,i,s){for(const[n,a]of i)if("Action"===a||this.data.actions?.[a]){"Focus"!==a&&"Blur"!==a||(e||={focused:!1});this._setEventListener(t,e,n,a,s);"Focus"!==a||this.data.actions?.Blur?"Blur"!==a||this.data.actions?.Focus||this._setEventListener(t,e,"focus","Focus",null):this._setEventListener(t,e,"blur","Blur",null)}}_setBackgroundColor(t){const e=this.data.backgroundColor||null;t.style.backgroundColor=null===e?"transparent":Util.makeHexColor(e[0],e[1],e[2])}_setTextStyle(t){const e=["left","center","right"],{fontColor:i}=this.data.defaultAppearanceData,s=this.data.defaultAppearanceData.fontSize||9,a=t.style;let r;const roundToOneDecimal=t=>Math.round(10*t)/10;if(this.data.multiLine){const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2),e=t/(Math.round(t/(n*s))||1);r=Math.min(s,roundToOneDecimal(e/n))}else{const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2);r=Math.min(s,roundToOneDecimal(t/n))}a.fontSize=`calc(${r}px * var(--scale-factor))`;a.color=Util.makeHexColor(i[0],i[1],i[2]);null!==this.data.textAlignment&&(a.textAlign=e[this.data.textAlignment])}_setRequired(t,e){e?t.setAttribute("required",!0):t.removeAttribute("required");t.setAttribute("aria-required",e)}}class TextWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms||t.data.hasOwnCanvas||!t.data.hasAppearance&&!!t.data.fieldValue})}setPropertyOnSiblings(t,e,i,s){const n=this.annotationStorage;for(const a of this._getElementsByName(t.name,t.id)){a.domElement&&(a.domElement[e]=i);n.setValue(a.id,{[s]:i})}}render(){const t=this.annotationStorage,e=this.data.id;this.container.classList.add("textWidgetAnnotation");let i=null;if(this.renderForms){const s=t.getValue(e,{value:this.data.fieldValue});let n=s.value||"";const a=t.getValue(e,{charLimit:this.data.maxLen}).charLimit;a&&n.length>a&&(n=n.slice(0,a));let r=s.formattedValue||this.data.textContent?.join("\n")||null;r&&this.data.comb&&(r=r.replaceAll(/\s+/g,""));const o={userValue:n,formattedValue:r,lastCommittedValue:null,commitKey:1,focused:!1};if(this.data.multiLine){i=document.createElement("textarea");i.textContent=r??n;this.data.doNotScroll&&(i.style.overflowY="hidden")}else{i=document.createElement("input");i.type="text";i.setAttribute("value",r??n);this.data.doNotScroll&&(i.style.overflowX="hidden")}this.data.hasOwnCanvas&&(i.hidden=!0);Ht.add(i);i.setAttribute("data-element-id",e);i.disabled=this.data.readOnly;i.name=this.data.fieldName;i.tabIndex=Bt;this._setRequired(i,this.data.required);a&&(i.maxLength=a);i.addEventListener("input",(s=>{t.setValue(e,{value:s.target.value});this.setPropertyOnSiblings(i,"value",s.target.value,"value");o.formattedValue=null}));i.addEventListener("resetform",(t=>{const e=this.data.defaultFieldValue??"";i.value=o.userValue=e;o.formattedValue=null}));let blurListener=t=>{const{formattedValue:e}=o;null!=e&&(t.target.value=e);t.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){i.addEventListener("focus",(t=>{if(o.focused)return;const{target:e}=t;o.userValue&&(e.value=o.userValue);o.lastCommittedValue=e.value;o.commitKey=1;this.data.actions?.Focus||(o.focused=!0)}));i.addEventListener("updatefromsandbox",(i=>{this.showElementAndHideCanvas(i.target);const s={value(i){o.userValue=i.detail.value??"";t.setValue(e,{value:o.userValue.toString()});i.target.value=o.userValue},formattedValue(i){const{formattedValue:s}=i.detail;o.formattedValue=s;null!=s&&i.target!==document.activeElement&&(i.target.value=s);t.setValue(e,{formattedValue:s})},selRange(t){t.target.setSelectionRange(...t.detail.selRange)},charLimit:i=>{const{charLimit:s}=i.detail,{target:n}=i;if(0===s){n.removeAttribute("maxLength");return}n.setAttribute("maxLength",s);let a=o.userValue;if(a&&!(a.length<=s)){a=a.slice(0,s);n.value=o.userValue=a;t.setValue(e,{value:a});this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:a,willCommit:!0,commitKey:1,selStart:n.selectionStart,selEnd:n.selectionEnd}})}}};this._dispatchEventFromSandbox(s,i)}));i.addEventListener("keydown",(t=>{o.commitKey=1;let i=-1;"Escape"===t.key?i=0:"Enter"!==t.key||this.data.multiLine?"Tab"===t.key&&(o.commitKey=3):i=2;if(-1===i)return;const{value:s}=t.target;if(o.lastCommittedValue!==s){o.lastCommittedValue=s;o.userValue=s;this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:s,willCommit:!0,commitKey:i,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}})}}));const s=blurListener;blurListener=null;i.addEventListener("blur",(t=>{if(!o.focused||!t.relatedTarget)return;this.data.actions?.Blur||(o.focused=!1);const{value:i}=t.target;o.userValue=i;o.lastCommittedValue!==i&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:i,willCommit:!0,commitKey:o.commitKey,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}});s(t)}));this.data.actions?.Keystroke&&i.addEventListener("beforeinput",(t=>{o.lastCommittedValue=null;const{data:i,target:s}=t,{value:n,selectionStart:a,selectionEnd:r}=s;let l=a,h=r;switch(t.inputType){case"deleteWordBackward":{const t=n.substring(0,a).match(/\w*[^\w]*$/);t&&(l-=t[0].length);break}case"deleteWordForward":{const t=n.substring(a).match(/^[^\w]*\w*/);t&&(h+=t[0].length);break}case"deleteContentBackward":a===r&&(l-=1);break;case"deleteContentForward":a===r&&(h+=1)}t.preventDefault();this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:n,change:i||"",willCommit:!1,selStart:l,selEnd:h}})}));this._setEventListeners(i,o,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.value))}blurListener&&i.addEventListener("blur",blurListener);if(this.data.comb){const t=(this.data.rect[2]-this.data.rect[0])/a;i.classList.add("comb");i.style.letterSpacing=`calc(${t}px * var(--scale-factor) - 1ch)`}}else{i=document.createElement("div");i.textContent=this.data.fieldValue;i.style.verticalAlign="middle";i.style.display="table-cell";this.data.hasOwnCanvas&&(i.hidden=!0)}this._setTextStyle(i);this._setBackgroundColor(i);this._setDefaultPropertiesFromJS(i);this.container.append(i);return this.container}}class SignatureWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){const t=this.annotationStorage,e=this.data,i=e.id;let s=t.getValue(i,{value:e.exportValue===e.fieldValue}).value;if("string"==typeof s){s="Off"!==s;t.setValue(i,{value:s})}this.container.classList.add("buttonWidgetAnnotation","checkBox");const n=document.createElement("input");Ht.add(n);n.setAttribute("data-element-id",i);n.disabled=e.readOnly;this._setRequired(n,this.data.required);n.type="checkbox";n.name=e.fieldName;s&&n.setAttribute("checked",!0);n.setAttribute("exportValue",e.exportValue);n.tabIndex=Bt;n.addEventListener("change",(s=>{const{name:n,checked:a}=s.target;for(const s of this._getElementsByName(n,i)){const i=a&&s.exportValue===e.exportValue;s.domElement&&(s.domElement.checked=i);t.setValue(s.id,{value:i})}t.setValue(i,{value:a})}));n.addEventListener("resetform",(t=>{const i=e.defaultFieldValue||"Off";t.target.checked=i===e.exportValue}));if(this.enableScripting&&this.hasJSActions){n.addEventListener("updatefromsandbox",(e=>{const s={value(e){e.target.checked="Off"!==e.detail.value;t.setValue(i,{value:e.target.checked})}};this._dispatchEventFromSandbox(s,e)}));this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.checked))}this._setBackgroundColor(n);this._setDefaultPropertiesFromJS(n);this.container.append(n);return this.container}}class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const t=this.annotationStorage,e=this.data,i=e.id;let s=t.getValue(i,{value:e.fieldValue===e.buttonValue}).value;if("string"==typeof s){s=s!==e.buttonValue;t.setValue(i,{value:s})}if(s)for(const s of this._getElementsByName(e.fieldName,i))t.setValue(s.id,{value:!1});const n=document.createElement("input");Ht.add(n);n.setAttribute("data-element-id",i);n.disabled=e.readOnly;this._setRequired(n,this.data.required);n.type="radio";n.name=e.fieldName;s&&n.setAttribute("checked",!0);n.tabIndex=Bt;n.addEventListener("change",(e=>{const{name:s,checked:n}=e.target;for(const e of this._getElementsByName(s,i))t.setValue(e.id,{value:!1});t.setValue(i,{value:n})}));n.addEventListener("resetform",(t=>{const i=e.defaultFieldValue;t.target.checked=null!=i&&i===e.buttonValue}));if(this.enableScripting&&this.hasJSActions){const s=e.buttonValue;n.addEventListener("updatefromsandbox",(e=>{const n={value:e=>{const n=s===e.detail.value;for(const s of this._getElementsByName(e.target.name)){const e=n&&s.id===i;s.domElement&&(s.domElement.checked=e);t.setValue(s.id,{value:e})}}};this._dispatchEventFromSandbox(n,e)}));this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.checked))}this._setBackgroundColor(n);this._setDefaultPropertiesFromJS(n);this.container.append(n);return this.container}}class PushButtonWidgetAnnotationElement extends LinkAnnotationElement{constructor(t){super(t,{ignoreBorder:t.data.hasAppearance})}render(){const t=super.render();t.classList.add("buttonWidgetAnnotation","pushButton");const e=t.lastChild;if(this.enableScripting&&this.hasJSActions&&e){this._setDefaultPropertiesFromJS(e);e.addEventListener("updatefromsandbox",(t=>{this._dispatchEventFromSandbox({},t)}))}return t}}class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");const t=this.annotationStorage,e=this.data.id,i=t.getValue(e,{value:this.data.fieldValue}),s=document.createElement("select");Ht.add(s);s.setAttribute("data-element-id",e);s.disabled=this.data.readOnly;this._setRequired(s,this.data.required);s.name=this.data.fieldName;s.tabIndex=Bt;let n=this.data.combo&&this.data.options.length>0;if(!this.data.combo){s.size=this.data.options.length;this.data.multiSelect&&(s.multiple=!0)}s.addEventListener("resetform",(t=>{const e=this.data.defaultFieldValue;for(const t of s.options)t.selected=t.value===e}));for(const t of this.data.options){const e=document.createElement("option");e.textContent=t.displayValue;e.value=t.exportValue;if(i.value.includes(t.exportValue)){e.setAttribute("selected",!0);n=!1}s.append(e)}let a=null;if(n){const t=document.createElement("option");t.value=" ";t.setAttribute("hidden",!0);t.setAttribute("selected",!0);s.prepend(t);a=()=>{t.remove();s.removeEventListener("input",a);a=null};s.addEventListener("input",a)}const getValue=t=>{const e=t?"value":"textContent",{options:i,multiple:n}=s;return n?Array.prototype.filter.call(i,(t=>t.selected)).map((t=>t[e])):-1===i.selectedIndex?null:i[i.selectedIndex][e]};let r=getValue(!1);const getItems=t=>{const e=t.target.options;return Array.prototype.map.call(e,(t=>({displayValue:t.textContent,exportValue:t.value})))};if(this.enableScripting&&this.hasJSActions){s.addEventListener("updatefromsandbox",(i=>{const n={value(i){a?.();const n=i.detail.value,o=new Set(Array.isArray(n)?n:[n]);for(const t of s.options)t.selected=o.has(t.value);t.setValue(e,{value:getValue(!0)});r=getValue(!1)},multipleSelection(t){s.multiple=!0},remove(i){const n=s.options,a=i.detail.remove;n[a].selected=!1;s.remove(a);if(n.length>0){-1===Array.prototype.findIndex.call(n,(t=>t.selected))&&(n[0].selected=!0)}t.setValue(e,{value:getValue(!0),items:getItems(i)});r=getValue(!1)},clear(i){for(;0!==s.length;)s.remove(0);t.setValue(e,{value:null,items:[]});r=getValue(!1)},insert(i){const{index:n,displayValue:a,exportValue:o}=i.detail.insert,l=s.children[n],h=document.createElement("option");h.textContent=a;h.value=o;l?l.before(h):s.append(h);t.setValue(e,{value:getValue(!0),items:getItems(i)});r=getValue(!1)},items(i){const{items:n}=i.detail;for(;0!==s.length;)s.remove(0);for(const t of n){const{displayValue:e,exportValue:i}=t,n=document.createElement("option");n.textContent=e;n.value=i;s.append(n)}s.options.length>0&&(s.options[0].selected=!0);t.setValue(e,{value:getValue(!0),items:getItems(i)});r=getValue(!1)},indices(i){const s=new Set(i.detail.indices);for(const t of i.target.options)t.selected=s.has(t.index);t.setValue(e,{value:getValue(!0)});r=getValue(!1)},editable(t){t.target.disabled=!t.detail.editable}};this._dispatchEventFromSandbox(n,i)}));s.addEventListener("input",(i=>{const s=getValue(!0),n=getValue(!1);t.setValue(e,{value:s});i.preventDefault();this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:r,change:n,changeEx:s,willCommit:!1,commitKey:1,keyDown:!1}})}));this._setEventListeners(s,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],(t=>t.target.value))}else s.addEventListener("input",(function(i){t.setValue(e,{value:getValue(!0)})}));this.data.combo&&this._setTextStyle(s);this._setBackgroundColor(s);this._setDefaultPropertiesFromJS(s);this.container.append(s);return this.container}}class PopupAnnotationElement extends AnnotationElement{constructor(t){const{data:e,elements:i}=t;super(t,{isRenderable:AnnotationElement._hasPopupData(e)});this.elements=i;this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new PopupElement({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate,contentsObj:this.data.contentsObj,richText:this.data.richText,rect:this.data.rect,parentRect:this.data.parentRect||null,parent:this.parent,elements:this.elements,open:this.data.open}),e=[];for(const i of this.elements){i.popup=t;i.container.ariaHasPopup="dialog";e.push(i.data.id);i.addHighlightArea()}this.container.setAttribute("aria-controls",e.map((t=>`${et}${t}`)).join(","));return this.container}}class PopupElement{#Ws=this.#qs.bind(this);#Xs=this.#Ks.bind(this);#Ys=this.#Qs.bind(this);#Js=this.#Zs.bind(this);#tn=null;#pt=null;#en=null;#in=null;#sn=null;#nn=null;#an=null;#rn=!1;#on=null;#C=null;#ln=null;#hn=null;#dn=null;#Hs=null;#cn=!1;constructor({container:t,color:e,elements:i,titleObj:s,modificationDate:n,contentsObj:a,richText:r,parent:o,rect:l,parentRect:h,open:d}){this.#pt=t;this.#dn=s;this.#en=a;this.#hn=r;this.#nn=o;this.#tn=e;this.#ln=l;this.#an=h;this.#sn=i;this.#in=PDFDateString.toDateObject(n);this.trigger=i.flatMap((t=>t.getElementsToTriggerPopup()));for(const t of this.trigger){t.addEventListener("click",this.#Js);t.addEventListener("mouseenter",this.#Ys);t.addEventListener("mouseleave",this.#Xs);t.classList.add("popupTriggerArea")}for(const t of i)t.container?.addEventListener("keydown",this.#Ws);this.#pt.hidden=!0;d&&this.#Zs()}render(){if(this.#on)return;const t=this.#on=document.createElement("div");t.className="popup";if(this.#tn){const e=t.style.outlineColor=Util.makeHexColor(...this.#tn);if(CSS.supports("background-color","color-mix(in srgb, red 30%, white)"))t.style.backgroundColor=`color-mix(in srgb, ${e} 30%, white)`;else{const e=.7;t.style.backgroundColor=Util.makeHexColor(...this.#tn.map((t=>Math.floor(e*(255-t)+t))))}}const e=document.createElement("span");e.className="header";const i=document.createElement("h1");e.append(i);({dir:i.dir,str:i.textContent}=this.#dn);t.append(e);if(this.#in){const t=document.createElement("span");t.classList.add("popupDate");t.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string");t.setAttribute("data-l10n-args",JSON.stringify({dateObj:this.#in.valueOf()}));e.append(t)}const s=this.#un;if(s){XfaLayer.render({xfaHtml:s,intent:"richText",div:t});t.lastChild.classList.add("richText","popupContent")}else{const e=this._formatContents(this.#en);t.append(e)}this.#pt.append(t)}get#un(){const t=this.#hn,e=this.#en;return!t?.str||e?.str&&e.str!==t.str?null:this.#hn.html||null}get#pn(){return this.#un?.attributes?.style?.fontSize||0}get#gn(){return this.#un?.attributes?.style?.color||null}#mn(t){const e=[],i={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},s={style:{color:this.#gn,fontSize:this.#pn?`calc(${this.#pn}px * var(--scale-factor))`:""}};for(const i of t.split("\n"))e.push({name:"span",value:i,attributes:s});return i}_formatContents({str:t,dir:e}){const i=document.createElement("p");i.classList.add("popupContent");i.dir=e;const s=t.split(/(?:\r\n?|\n)/);for(let t=0,e=s.length;t=0&&n.setAttribute("stroke-width",e||1);if(i)for(let t=0,e=this.#xn.length;t{"Enter"===t.key&&(s?t.metaKey:t.ctrlKey)&&this.#Sn()}));!e.popupRef&&this.hasPopupData?this._createPopup():i.classList.add("popupTriggerArea");t.append(i);return t}getElementsToTriggerPopup(){return this.#En}addHighlightArea(){this.container.classList.add("highlightArea")}#Sn(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}}class AnnotationLayer{#Cn=null;#Tn=null;#Mn=new Map;#Pn=null;constructor({div:t,accessibilityManager:e,annotationCanvasMap:i,annotationEditorUIManager:s,page:n,viewport:a,structTreeLayer:r}){this.div=t;this.#Cn=e;this.#Tn=i;this.#Pn=r||null;this.page=n;this.viewport=a;this.zIndex=0;this._annotationEditorUIManager=s}hasEditableAnnotations(){return this.#Mn.size>0}async#Dn(t,e){const i=t.firstChild||t,s=i.id=`${et}${e}`,n=await(this.#Pn?.getAriaAttributes(s));if(n)for(const[t,e]of n)i.setAttribute(t,e);this.div.append(t);this.#Cn?.moveElementInDOM(this.div,t,i,!1)}async render(t){const{annotations:e}=t,i=this.div;setLayerDimensions(i,this.viewport);const s=new Map,n={data:null,layer:i,linkService:t.linkService,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:!1!==t.renderForms,svgFactory:new DOMSVGFactory,annotationStorage:t.annotationStorage||new AnnotationStorage,enableScripting:!0===t.enableScripting,hasJSActions:t.hasJSActions,fieldObjects:t.fieldObjects,parent:this,elements:null};for(const t of e){if(t.noHTML)continue;const e=t.annotationType===H;if(e){const e=s.get(t.id);if(!e)continue;n.elements=e}else{const{width:e,height:i}=getRectDims(t.rect);if(e<=0||i<=0)continue}n.data=t;const i=AnnotationElementFactory.create(n);if(!i.isRenderable)continue;if(!e&&t.popupRef){const e=s.get(t.popupRef);e?e.push(i):s.set(t.popupRef,[i])}const a=i.render();t.hidden&&(a.style.visibility="hidden");await this.#Dn(a,t.id);if(i._isEditable){this.#Mn.set(i.data.id,i);this._annotationEditorUIManager?.renderAnnotationElement(i)}}this.#kn()}update({viewport:t}){const e=this.div;this.viewport=t;setLayerDimensions(e,{rotation:t.rotation});this.#kn();e.hidden=!1}#kn(){if(!this.#Tn)return;const t=this.div;for(const[e,i]of this.#Tn){const s=t.querySelector(`[data-annotation-id="${e}"]`);if(!s)continue;i.className="annotationContent";const{firstChild:n}=s;n?"CANVAS"===n.nodeName?n.replaceWith(i):n.classList.contains("annotationContent")?n.after(i):n.before(i):s.append(i)}this.#Tn.clear()}getEditableAnnotations(){return Array.from(this.#Mn.values())}getEditableAnnotation(t){return this.#Mn.get(t)}}const zt=/\r\n?|\n/g;class FreeTextEditor extends AnnotationEditor{#tn;#Rn="";#In=`${this.id}-editor`;#Fn=null;#pn;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){const t=FreeTextEditor.prototype,arrowChecker=t=>t.isEmpty(),e=AnnotationEditorUIManager.TRANSLATE_SMALL,i=AnnotationEditorUIManager.TRANSLATE_BIG;return shadow(this,"_keyboardManager",new KeyboardManager([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],t.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],t.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],t._translateEmpty,{args:[-e,0],checker:arrowChecker}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t._translateEmpty,{args:[-i,0],checker:arrowChecker}],[["ArrowRight","mac+ArrowRight"],t._translateEmpty,{args:[e,0],checker:arrowChecker}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t._translateEmpty,{args:[i,0],checker:arrowChecker}],[["ArrowUp","mac+ArrowUp"],t._translateEmpty,{args:[0,-e],checker:arrowChecker}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t._translateEmpty,{args:[0,-i],checker:arrowChecker}],[["ArrowDown","mac+ArrowDown"],t._translateEmpty,{args:[0,e],checker:arrowChecker}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t._translateEmpty,{args:[0,i],checker:arrowChecker}]]))}static _type="freetext";static _editorType=g.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"});this.#tn=t.color||FreeTextEditor._defaultColor||AnnotationEditor._defaultLineColor;this.#pn=t.fontSize||FreeTextEditor._defaultFontSize}static initialize(t,e){AnnotationEditor.initialize(t,e);const i=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(i.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,e){switch(t){case m.FREETEXT_SIZE:FreeTextEditor._defaultFontSize=e;break;case m.FREETEXT_COLOR:FreeTextEditor._defaultColor=e}}updateParams(t,e){switch(t){case m.FREETEXT_SIZE:this.#Ln(e);break;case m.FREETEXT_COLOR:this.#On(e)}}static get defaultPropertiesToUpdate(){return[[m.FREETEXT_SIZE,FreeTextEditor._defaultFontSize],[m.FREETEXT_COLOR,FreeTextEditor._defaultColor||AnnotationEditor._defaultLineColor]]}get propertiesToUpdate(){return[[m.FREETEXT_SIZE,this.#pn],[m.FREETEXT_COLOR,this.#tn]]}#Ln(t){const setFontsize=t=>{this.editorDiv.style.fontSize=`calc(${t}px * var(--scale-factor))`;this.translate(0,-(t-this.#pn)*this.parentScale);this.#pn=t;this.#Nn()},e=this.#pn;this.addCommands({cmd:setFontsize.bind(this,t),undo:setFontsize.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:m.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}#On(t){const setColor=t=>{this.#tn=this.editorDiv.style.color=t},e=this.#tn;this.addCommands({cmd:setColor.bind(this,t),undo:setColor.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:m.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(t,e){this._uiManager.translateSelectedEditors(t,e,!0)}getInitialTranslation(){const t=this.parentScale;return[-FreeTextEditor._internalPadding*t,-(FreeTextEditor._internalPadding+this.#pn)*t]}rebuild(){if(this.parent){super.rebuild();null!==this.div&&(this.isAttachedToDOM||this.parent.add(this))}}enableEditMode(){if(this.isInEditMode())return;this.parent.setEditingState(!1);this.parent.updateToolbar(g.FREETEXT);super.enableEditMode();this.overlayDiv.classList.remove("enabled");this.editorDiv.contentEditable=!0;this._isDraggable=!1;this.div.removeAttribute("aria-activedescendant");this.#Fn=new AbortController;const t=this._uiManager.combinedSignal(this.#Fn);this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:t});this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:t});this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:t});this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:t});this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:t})}disableEditMode(){if(this.isInEditMode()){this.parent.setEditingState(!0);super.disableEditMode();this.overlayDiv.classList.add("enabled");this.editorDiv.contentEditable=!1;this.div.setAttribute("aria-activedescendant",this.#In);this._isDraggable=!0;this.#Fn?.abort();this.#Fn=null;this.div.focus({preventScroll:!0});this.isEditing=!1;this.parent.div.classList.add("freetextEditing")}}focusin(t){if(this._focusEventsAllowed){super.focusin(t);t.target!==this.editorDiv&&this.editorDiv.focus()}}onceAdded(t){if(!this.width){this.enableEditMode();t&&this.editorDiv.focus();this._initialOptions?.isCentered&&this.center();this._initialOptions=null}}isEmpty(){return!this.editorDiv||""===this.editorDiv.innerText.trim()}remove(){this.isEditing=!1;if(this.parent){this.parent.setEditingState(!0);this.parent.div.classList.add("freetextEditing")}super.remove()}#Bn(){const t=[];this.editorDiv.normalize();let e=null;for(const i of this.editorDiv.childNodes)if(e?.nodeType!==Node.TEXT_NODE||"BR"!==i.nodeName){t.push(FreeTextEditor.#Hn(i));e=i}return t.join("\n")}#Nn(){const[t,e]=this.parentDimensions;let i;if(this.isAttachedToDOM)i=this.div.getBoundingClientRect();else{const{currentLayer:t,div:e}=this,s=e.style.display,n=e.classList.contains("hidden");e.classList.remove("hidden");e.style.display="hidden";t.div.append(this.div);i=e.getBoundingClientRect();e.remove();e.style.display=s;e.classList.toggle("hidden",n)}if(this.rotation%180==this.parentRotation%180){this.width=i.width/t;this.height=i.height/e}else{this.width=i.height/t;this.height=i.width/e}this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit();this.disableEditMode();const t=this.#Rn,e=this.#Rn=this.#Bn().trimEnd();if(t===e)return;const setText=t=>{this.#Rn=t;if(t){this.#zn();this._uiManager.rebuild(this);this.#Nn()}else this.remove()};this.addCommands({cmd:()=>{setText(e)},undo:()=>{setText(t)},mustExec:!1});this.#Nn()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode();this.editorDiv.focus()}dblclick(t){this.enterInEditMode()}keydown(t){if(t.target===this.div&&"Enter"===t.key){this.enterInEditMode();t.preventDefault()}}editorDivKeydown(t){FreeTextEditor._keyboardManager.exec(this,t)}editorDivFocus(t){this.isEditing=!0}editorDivBlur(t){this.isEditing=!1}editorDivInput(t){this.parent.div.classList.toggle("freetextEditing",this.isEmpty())}disableEditing(){this.editorDiv.setAttribute("role","comment");this.editorDiv.removeAttribute("aria-multiline")}enableEditing(){this.editorDiv.setAttribute("role","textbox");this.editorDiv.setAttribute("aria-multiline",!0)}render(){if(this.div)return this.div;let t,e;if(this.width){t=this.x;e=this.y}super.render();this.editorDiv=document.createElement("div");this.editorDiv.className="internal";this.editorDiv.setAttribute("id",this.#In);this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text2");this.editorDiv.setAttribute("data-l10n-attrs","default-content");this.enableEditing();this.editorDiv.contentEditable=!0;const{style:i}=this.editorDiv;i.fontSize=`calc(${this.#pn}px * var(--scale-factor))`;i.color=this.#tn;this.div.append(this.editorDiv);this.overlayDiv=document.createElement("div");this.overlayDiv.classList.add("overlay","enabled");this.div.append(this.overlayDiv);bindEvents(this,this.div,["dblclick","keydown"]);if(this.width){const[i,s]=this.parentDimensions;if(this.annotationElementId){const{position:n}=this._initialData;let[a,r]=this.getInitialTranslation();[a,r]=this.pageTranslationToScreen(a,r);const[o,l]=this.pageDimensions,[h,d]=this.pageTranslation;let c,u;switch(this.rotation){case 0:c=t+(n[0]-h)/o;u=e+this.height-(n[1]-d)/l;break;case 90:c=t+(n[0]-h)/o;u=e-(n[1]-d)/l;[a,r]=[r,-a];break;case 180:c=t-this.width+(n[0]-h)/o;u=e-(n[1]-d)/l;[a,r]=[-a,-r];break;case 270:c=t+(n[0]-h-this.height*l)/o;u=e+(n[1]-d-this.width*o)/l;[a,r]=[-r,a]}this.setAt(c*i,u*s,a,r)}else this.setAt(t*i,e*s,this.width*i,this.height*s);this.#zn();this._isDraggable=!0;this.editorDiv.contentEditable=!1}else{this._isDraggable=!1;this.editorDiv.contentEditable=!0}return this.div}static#Hn(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(zt,"")}editorDivPaste(t){const e=t.clipboardData||window.clipboardData,{types:i}=e;if(1===i.length&&"text/plain"===i[0])return;t.preventDefault();const s=FreeTextEditor.#Un(e.getData("text")||"").replaceAll(zt,"\n");if(!s)return;const n=window.getSelection();if(!n.rangeCount)return;this.editorDiv.normalize();n.deleteFromDocument();const a=n.getRangeAt(0);if(!s.includes("\n")){a.insertNode(document.createTextNode(s));this.editorDiv.normalize();n.collapseToStart();return}const{startContainer:r,startOffset:o}=a,l=[],h=[];if(r.nodeType===Node.TEXT_NODE){const t=r.parentElement;h.push(r.nodeValue.slice(o).replaceAll(zt,""));if(t!==this.editorDiv){let e=l;for(const i of this.editorDiv.childNodes)i!==t?e.push(FreeTextEditor.#Hn(i)):e=h}l.push(r.nodeValue.slice(0,o).replaceAll(zt,""))}else if(r===this.editorDiv){let t=l,e=0;for(const i of this.editorDiv.childNodes){e++===o&&(t=h);t.push(FreeTextEditor.#Hn(i))}}this.#Rn=`${l.join("\n")}${s}${h.join("\n")}`;this.#zn();const d=new Range;let c=l.reduce(((t,e)=>t+e.length),0);for(const{firstChild:t}of this.editorDiv.childNodes)if(t.nodeType===Node.TEXT_NODE){const e=t.nodeValue.length;if(c<=e){d.setStart(t,c);d.setEnd(t,c);break}c-=e}n.removeAllRanges();n.addRange(d)}#zn(){this.editorDiv.replaceChildren();if(this.#Rn)for(const t of this.#Rn.split("\n")){const e=document.createElement("div");e.append(t?document.createTextNode(t):document.createElement("br"));this.editorDiv.append(e)}}#Gn(){return this.#Rn.replaceAll(" "," ")}static#Un(t){return t.replaceAll(" "," ")}get contentDiv(){return this.editorDiv}static async deserialize(t,e,i){let s=null;if(t instanceof FreeTextAnnotationElement){const{data:{defaultAppearanceData:{fontSize:e,fontColor:i},rect:n,rotation:a,id:r,popupRef:o},textContent:l,textPosition:h,parent:{page:{pageNumber:d}}}=t;if(!l||0===l.length)return null;s=t={annotationType:g.FREETEXT,color:Array.from(i),fontSize:e,value:l.join("\n"),position:h,pageIndex:d-1,rect:n.slice(0),rotation:a,id:r,deleted:!1,popupRef:o}}const n=await super.deserialize(t,e,i);n.#pn=t.fontSize;n.#tn=Util.makeHexColor(...t.color);n.#Rn=FreeTextEditor.#Un(t.value);n.annotationElementId=t.id||null;n._initialData=s;return n}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const e=FreeTextEditor._internalPadding*this.parentScale,i=this.getRect(e,e),s=AnnotationEditor._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.#tn),n={annotationType:g.FREETEXT,color:s,fontSize:this.#pn,value:this.#Gn(),pageIndex:this.pageIndex,rect:i,rotation:this.rotation,structTreeParentId:this._structTreeParentId};if(t)return n;if(this.annotationElementId&&!this.#$n(n))return null;n.id=this.annotationElementId;return n}#$n(t){const{value:e,fontSize:i,color:s,pageIndex:n}=this._initialData;return this._hasBeenMoved||t.value!==e||t.fontSize!==i||t.color.some(((t,e)=>t!==s[e]))||t.pageIndex!==n}renderAnnotationElement(t){const e=super.renderAnnotationElement(t);if(this.deleted)return e;const{style:i}=e;i.fontSize=`calc(${this.#pn}px * var(--scale-factor))`;i.color=this.#tn;e.replaceChildren();for(const t of this.#Rn.split("\n")){const i=document.createElement("div");i.append(t?document.createTextNode(t):document.createElement("br"));e.append(i)}const s=FreeTextEditor._internalPadding*this.parentScale;t.updateEdited({rect:this.getRect(s,s),popupContent:this.#Rn});return e}resetAnnotationElement(t){super.resetAnnotationElement(t);t.resetEdited()}}class Outline{static PRECISION=1e-4;toSVGPath(){unreachable("Abstract method `toSVGPath` must be implemented.")}get box(){unreachable("Abstract getter `box` must be implemented.")}serialize(t,e){unreachable("Abstract method `serialize` must be implemented.")}static _rescale(t,e,i,s,n,a){a||=new Float32Array(t.length);for(let r=0,o=t.length;r=6;t-=6)isNaN(e[t])?i.push(`L${e[t+4]} ${e[t+5]}`):i.push(`C${e[t]} ${e[t+1]} ${e[t+2]} ${e[t+3]} ${e[t+4]} ${e[t+5]}`);this.#ha(i);return i.join(" ")}#oa(){const[t,e,i,s]=this.#Vn,[n,a,r,o]=this.#ra();return`M${(this.#Kn[2]-t)/i} ${(this.#Kn[3]-e)/s} L${(this.#Kn[4]-t)/i} ${(this.#Kn[5]-e)/s} L${n} ${a} L${r} ${o} L${(this.#Kn[16]-t)/i} ${(this.#Kn[17]-e)/s} L${(this.#Kn[14]-t)/i} ${(this.#Kn[15]-e)/s} Z`}#ha(t){const e=this.#jn;t.push(`L${e[4]} ${e[5]} Z`)}#la(t){const[e,i,s,n]=this.#Vn,a=this.#Kn.subarray(4,6),r=this.#Kn.subarray(16,18),[o,l,h,d]=this.#ra();t.push(`L${(a[0]-e)/s} ${(a[1]-i)/n} L${o} ${l} L${h} ${d} L${(r[0]-e)/s} ${(r[1]-i)/n}`)}newFreeDrawOutline(t,e,i,s,n,a){return new FreeDrawOutline(t,e,i,s,n,a)}getOutlines(){const t=this.#Xn,e=this.#jn,i=this.#Kn,[s,n,a,r]=this.#Vn,o=new Float32Array((this.#ia?.length??0)+2);for(let t=0,e=o.length-2;t=6;t-=6)for(let i=0;i<6;i+=2)if(isNaN(e[t+i])){l[h]=l[h+1]=NaN;h+=2}else{l[h]=e[t+i];l[h+1]=e[t+i+1];h+=2}this.#ua(l,h);return this.newFreeDrawOutline(l,o,this.#Vn,this.#ta,this.#Wn,this.#qn)}#da(t){const e=this.#Kn,[i,s,n,a]=this.#Vn,[r,o,l,h]=this.#ra(),d=new Float32Array(36);d.set([NaN,NaN,NaN,NaN,(e[2]-i)/n,(e[3]-s)/a,NaN,NaN,NaN,NaN,(e[4]-i)/n,(e[5]-s)/a,NaN,NaN,NaN,NaN,r,o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,(e[16]-i)/n,(e[17]-s)/a,NaN,NaN,NaN,NaN,(e[14]-i)/n,(e[15]-s)/a],0);return this.newFreeDrawOutline(d,t,this.#Vn,this.#ta,this.#Wn,this.#qn)}#ua(t,e){const i=this.#jn;t.set([NaN,NaN,NaN,NaN,i[4],i[5]],e);return e+6}#ca(t,e){const i=this.#Kn.subarray(4,6),s=this.#Kn.subarray(16,18),[n,a,r,o]=this.#Vn,[l,h,d,c]=this.#ra();t.set([NaN,NaN,NaN,NaN,(i[0]-n)/r,(i[1]-a)/o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,d,c,NaN,NaN,NaN,NaN,(s[0]-n)/r,(s[1]-a)/o],e);return e+24}}class FreeDrawOutline extends Outline{#Vn;#pa=new Float32Array(4);#Wn;#qn;#ia;#ta;#ga;constructor(t,e,i,s,n,a){super();this.#ga=t;this.#ia=e;this.#Vn=i;this.#ta=s;this.#Wn=n;this.#qn=a;this.lastPoint=[NaN,NaN];this.#ma(a);const[r,o,l,h]=this.#pa;for(let e=0,i=t.length;et[0]-e[0]||t[1]-e[1]||t[2]-e[2]));const t=[];for(const e of this.#ba)if(e[3]){t.push(...this.#wa(e));this.#va(e)}else{this.#ya(e);t.push(...this.#wa(e))}return this.#xa(t)}#xa(t){const e=[],i=new Set;for(const i of t){const[t,s,n]=i;e.push([t,s,i],[t,n,i])}e.sort(((t,e)=>t[1]-e[1]||t[0]-e[0]));for(let t=0,s=e.length;t0;){const t=i.values().next().value;let[e,a,r,o,l]=t;i.delete(t);let h=e,d=a;n=[e,r];s.push(n);for(;;){let t;if(i.has(o))t=o;else{if(!i.has(l))break;t=l}i.delete(t);[e,a,r,o,l]=t;if(h!==e){n.push(h,d,e,d===a?a:r);h=e}d=d===a?r:a}n.push(h,d)}return new HighlightOutline(s,this.#Vn,this.#fa)}#_a(t){const e=this.#Aa;let i=0,s=e.length-1;for(;i<=s;){const n=i+s>>1,a=e[n][0];if(a===t)return n;a=0;s--){const[i,n]=this.#Aa[s];if(i!==t)break;if(i===t&&n===e){this.#Aa.splice(s,1);return}}}#wa(t){const[e,i,s]=t,n=[[e,i,s]],a=this.#_a(s);for(let t=0;t=i)if(o>s)n[t][1]=s;else{if(1===a)return[];n.splice(t,1);t--;a--}else{n[t][2]=i;o>s&&n.push([e,s,o])}}}return n}}class HighlightOutline extends Outline{#Vn;#Ea;constructor(t,e,i){super();this.#Ea=t;this.#Vn=e;this.lastPoint=i}toSVGPath(){const t=[];for(const e of this.#Ea){let[i,s]=e;t.push(`M${i} ${s}`);for(let n=2;n-1){this.#Xa=!0;this.#Za(t);this.#tr()}else if(this.#Ua){this.#Ha=t.anchorNode;this.#za=t.anchorOffset;this.#Va=t.focusNode;this.#ja=t.focusOffset;this.#er();this.#tr();this.rotate(this.rotation)}}get telemetryInitialData(){return{action:"added",type:this.#Xa?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:this.#ea,methodOfCreation:this.#Ja}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#er(){const t=new HighlightOutliner(this.#Ua,.001);this.#qa=t.getOutlines();[this.x,this.y,this.width,this.height]=this.#qa.box;const e=new HighlightOutliner(this.#Ua,.0025,.001,"ltr"===this._uiManager.direction);this.#$a=e.getOutlines();const{lastPoint:i}=this.#$a;this.#fa=[(i[0]-this.x)/this.width,(i[1]-this.y)/this.height]}#Za({highlightOutlines:t,highlightId:e,clipPathId:i}){this.#qa=t;this.#$a=t.getNewOutline(this.#ea/2+1.5,.0025);if(e>=0){this.#w=e;this.#Ga=i;this.parent.drawLayer.finalizeDraw(e,{bbox:t.box,path:{d:t.toSVGPath()}});this.#Ya=this.parent.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:!0},bbox:this.#$a.box,path:{d:this.#$a.toSVGPath()}},!0)}else if(this.parent){const e=this.parent.viewport.rotation;this.parent.drawLayer.updateProperties(this.#w,{bbox:HighlightEditor.#ir(this.#qa.box,(e-this.rotation+360)%360),path:{d:t.toSVGPath()}});this.parent.drawLayer.updateProperties(this.#Ya,{bbox:HighlightEditor.#ir(this.#$a.box,e),path:{d:this.#$a.toSVGPath()}})}const[s,n,a,r]=t.box;switch(this.rotation){case 0:this.x=s;this.y=n;this.width=a;this.height=r;break;case 90:{const[t,e]=this.parentDimensions;this.x=n;this.y=1-s;this.width=a*e/t;this.height=r*t/e;break}case 180:this.x=1-s;this.y=1-n;this.width=a;this.height=r;break;case 270:{const[t,e]=this.parentDimensions;this.x=1-n;this.y=s;this.width=a*e/t;this.height=r*t/e;break}}const{lastPoint:o}=this.#$a;this.#fa=[(o[0]-s)/a,(o[1]-n)/r]}static initialize(t,e){AnnotationEditor.initialize(t,e);HighlightEditor._defaultColor||=e.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,e){switch(t){case m.HIGHLIGHT_DEFAULT_COLOR:HighlightEditor._defaultColor=e;break;case m.HIGHLIGHT_THICKNESS:HighlightEditor._defaultThickness=e}}translateInPage(t,e){}get toolbarPosition(){return this.#fa}updateParams(t,e){switch(t){case m.HIGHLIGHT_COLOR:this.#On(e);break;case m.HIGHLIGHT_THICKNESS:this.#sr(e)}}static get defaultPropertiesToUpdate(){return[[m.HIGHLIGHT_DEFAULT_COLOR,HighlightEditor._defaultColor],[m.HIGHLIGHT_THICKNESS,HighlightEditor._defaultThickness]]}get propertiesToUpdate(){return[[m.HIGHLIGHT_COLOR,this.color||HighlightEditor._defaultColor],[m.HIGHLIGHT_THICKNESS,this.#ea||HighlightEditor._defaultThickness],[m.HIGHLIGHT_FREE,this.#Xa]]}#On(t){const setColorAndOpacity=(t,e)=>{this.color=t;this.#Ka=e;this.parent?.drawLayer.updateProperties(this.#w,{root:{fill:t,"fill-opacity":e}});this.#n?.updateColor(t)},e=this.color,i=this.#Ka;this.addCommands({cmd:setColorAndOpacity.bind(this,t,HighlightEditor._defaultOpacity),undo:setColorAndOpacity.bind(this,e,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:m.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0});this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(t)},!0)}#sr(t){const e=this.#ea,setThickness=t=>{this.#ea=t;this.#nr(t)};this.addCommands({cmd:setThickness.bind(this,t),undo:setThickness.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:m.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0});this._reportTelemetry({action:"thickness_changed",thickness:t},!0)}async addEditToolbar(){const t=await super.addEditToolbar();if(!t)return null;if(this._uiManager.highlightColors){this.#n=new ColorPicker({editor:this});t.addColorPicker(this.#n)}return t}disableEditing(){super.disableEditing();this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing();this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#ar())}getBaseTranslation(){return[0,0]}getRect(t,e){return super.getRect(t,e,this.#ar())}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this);t&&this.div.focus()}remove(){this.#rr();this._reportTelemetry({action:"deleted"});super.remove()}rebuild(){if(this.parent){super.rebuild();if(null!==this.div){this.#tr();this.isAttachedToDOM||this.parent.add(this)}}}setParent(t){let e=!1;if(this.parent&&!t)this.#rr();else if(t){this.#tr(t);e=!this.parent&&this.div?.classList.contains("selectedEditor")}super.setParent(t);this.show(this._isVisible);e&&this.select()}#nr(t){if(!this.#Xa)return;this.#Za({highlightOutlines:this.#qa.getNewOutline(t/2)});this.fixAndSetPosition();const[e,i]=this.parentDimensions;this.setDims(this.width*e,this.height*i)}#rr(){if(null!==this.#w&&this.parent){this.parent.drawLayer.remove(this.#w);this.#w=null;this.parent.drawLayer.remove(this.#Ya);this.#Ya=null}}#tr(t=this.parent){if(null===this.#w){({id:this.#w,clipPathId:this.#Ga}=t.drawLayer.draw({bbox:this.#qa.box,root:{viewBox:"0 0 1 1",fill:this.color,"fill-opacity":this.#Ka},rootClass:{highlight:!0,free:this.#Xa},path:{d:this.#qa.toSVGPath()}},!1,!0));this.#Ya=t.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:this.#Xa},bbox:this.#$a.box,path:{d:this.#$a.toSVGPath()}},this.#Xa);this.#Wa&&(this.#Wa.style.clipPath=this.#Ga)}}static#ir([t,e,i,s],n){switch(n){case 90:return[1-e-s,t,s,i];case 180:return[1-t-i,1-e-s,i,s];case 270:return[e,1-t-i,s,i]}return[t,e,i,s]}rotate(t){const{drawLayer:e}=this.parent;let i;if(this.#Xa){t=(t-this.rotation+360)%360;i=HighlightEditor.#ir(this.#qa.box,t)}else i=HighlightEditor.#ir([this.x,this.y,this.width,this.height],t);e.updateProperties(this.#w,{bbox:i,root:{"data-main-rotation":t}});e.updateProperties(this.#Ya,{bbox:HighlightEditor.#ir(this.#$a.box,t),root:{"data-main-rotation":t}})}render(){if(this.div)return this.div;const t=super.render();if(this.#Qa){t.setAttribute("aria-label",this.#Qa);t.setAttribute("role","mark")}this.#Xa?t.classList.add("free"):this.div.addEventListener("keydown",this.#or.bind(this),{signal:this._uiManager._signal});const e=this.#Wa=document.createElement("div");t.append(e);e.setAttribute("aria-hidden","true");e.className="internal";e.style.clipPath=this.#Ga;const[i,s]=this.parentDimensions;this.setDims(this.width*i,this.height*s);bindEvents(this,this.#Wa,["pointerover","pointerleave"]);this.enableEditing();return t}pointerover(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#Ya,{rootClass:{hovered:!0}})}pointerleave(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#Ya,{rootClass:{hovered:!1}})}#or(t){HighlightEditor._keyboardManager.exec(this,t)}_moveCaret(t){this.parent.unselect(this);switch(t){case 0:case 2:this.#lr(!0);break;case 1:case 3:this.#lr(!1)}}#lr(t){if(!this.#Ha)return;const e=window.getSelection();t?e.setPosition(this.#Ha,this.#za):e.setPosition(this.#Va,this.#ja)}select(){super.select();this.#Ya&&this.parent?.drawLayer.updateProperties(this.#Ya,{rootClass:{hovered:!1,selected:!0}})}unselect(){super.unselect();if(this.#Ya){this.parent?.drawLayer.updateProperties(this.#Ya,{rootClass:{selected:!1}});this.#Xa||this.#lr(!1)}}get _mustFixPosition(){return!this.#Xa}show(t=this._isVisible){super.show(t);if(this.parent){this.parent.drawLayer.updateProperties(this.#w,{rootClass:{hidden:!t}});this.parent.drawLayer.updateProperties(this.#Ya,{rootClass:{hidden:!t}})}}#ar(){return this.#Xa?this.rotation:0}#hr(){if(this.#Xa)return null;const[t,e]=this.pageDimensions,[i,s]=this.pageTranslation,n=this.#Ua,a=new Float32Array(8*n.length);let r=0;for(const{x:o,y:l,width:h,height:d}of n){const n=o*t+i,c=(1-l)*e+s;a[r]=a[r+4]=n;a[r+1]=a[r+3]=c;a[r+2]=a[r+6]=n+h*t;a[r+5]=a[r+7]=c-d*e;r+=8}return a}#dr(t){return this.#qa.serialize(t,this.#ar())}static startHighlighting(t,e,{target:i,x:s,y:n}){const{x:a,y:r,width:o,height:l}=i.getBoundingClientRect(),h=new AbortController,d=t.combinedSignal(h),pointerUpCallback=e=>{h.abort();this.#cr(t,e)};window.addEventListener("blur",pointerUpCallback,{signal:d});window.addEventListener("pointerup",pointerUpCallback,{signal:d});window.addEventListener("pointerdown",stopEvent,{capture:!0,passive:!1,signal:d});window.addEventListener("contextmenu",noContextMenu,{signal:d});i.addEventListener("pointermove",this.#ur.bind(this,t),{signal:d});this._freeHighlight=new FreeHighlightOutliner({x:s,y:n},[a,r,o,l],t.scale,this._defaultThickness/2,e,.001);({id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=t.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:this._defaultColor,"fill-opacity":this._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:this._freeHighlight.toSVGPath()}},!0,!0))}static#ur(t,e){this._freeHighlight.add(e)&&t.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})}static#cr(t,e){this._freeHighlight.isEmpty()?t.drawLayer.remove(this._freeHighlightId):t.createAndAddNewEditor(e,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"});this._freeHighlightId=-1;this._freeHighlight=null;this._freeHighlightClipId=""}static async deserialize(t,e,i){let s=null;if(t instanceof HighlightAnnotationElement){const{data:{quadPoints:e,rect:i,rotation:n,id:a,color:r,opacity:o,popupRef:l},parent:{page:{pageNumber:h}}}=t;s=t={annotationType:g.HIGHLIGHT,color:Array.from(r),opacity:o,quadPoints:e,boxes:null,pageIndex:h-1,rect:i.slice(0),rotation:n,id:a,deleted:!1,popupRef:l}}else if(t instanceof InkAnnotationElement){const{data:{inkLists:e,rect:i,rotation:n,id:a,color:r,borderStyle:{rawWidth:o},popupRef:l},parent:{page:{pageNumber:h}}}=t;s=t={annotationType:g.HIGHLIGHT,color:Array.from(r),thickness:o,inkLists:e,boxes:null,pageIndex:h-1,rect:i.slice(0),rotation:n,id:a,deleted:!1,popupRef:l}}const{color:n,quadPoints:a,inkLists:r,opacity:o}=t,l=await super.deserialize(t,e,i);l.color=Util.makeHexColor(...n);l.#Ka=o||1;r&&(l.#ea=t.thickness);l.annotationElementId=t.id||null;l._initialData=s;const[h,d]=l.pageDimensions,[c,u]=l.pageTranslation;if(a){const t=l.#Ua=[];for(let e=0;et!==e[i]))}renderAnnotationElement(t){t.updateEdited({rect:this.getRect(0,0)});return null}static canCreateNewEmptyEditor(){return!1}}class DrawingOptions{#pr=Object.create(null);updateProperty(t,e){this[t]=e;this.updateSVGProperty(t,e)}updateProperties(t){if(t)for(const[e,i]of Object.entries(t))this.updateProperty(e,i)}updateSVGProperty(t,e){this.#pr[t]=e}toSVGProperties(){const t=this.#pr;this.#pr=Object.create(null);return{root:t}}reset(){this.#pr=Object.create(null)}updateAll(t=this){this.updateProperties(t)}clone(){unreachable("Not implemented")}}class DrawingEditor extends AnnotationEditor{#gr=null;#mr;_drawId=null;static _currentDrawId=-1;static _currentParent=null;static#fr=null;static#br=null;static#Ar=null;static#wr=NaN;static#vr=null;static#yr=null;static#xr=NaN;static _INNER_MARGIN=3;constructor(t){super(t);this.#mr=t.mustBeCommitted||!1;if(t.drawOutlines){this.#_r(t);this.#tr()}}#_r({drawOutlines:t,drawId:e,drawingOptions:i}){this.#gr=t;this._drawingOptions||=i;if(e>=0){this._drawId=e;this.parent.drawLayer.finalizeDraw(e,t.defaultProperties)}else this._drawId=this.#Er(t,this.parent);this.#Sr(t.box)}#Er(t,e){const{id:i}=e.drawLayer.draw(DrawingEditor._mergeSVGProperties(this._drawingOptions.toSVGProperties(),t.defaultSVGProperties),!1,!1);return i}static _mergeSVGProperties(t,e){const i=new Set(Object.keys(t));for(const[s,n]of Object.entries(e))i.has(s)?Object.assign(t[s],n):t[s]=n;return t}static getDefaultDrawingOptions(t){unreachable("Not implemented")}static get typesMap(){unreachable("Not implemented")}static get isDrawer(){return!0}static get supportMultipleDrawings(){return!1}static updateDefaultParams(t,e){const i=this.typesMap.get(t);i&&this._defaultDrawingOptions.updateProperty(i,e);if(this._currentParent){DrawingEditor.#fr.updateProperty(i,e);this._currentParent.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties())}}updateParams(t,e){const i=this.constructor.typesMap.get(t);i&&this._updateProperty(t,i,e)}static get defaultPropertiesToUpdate(){const t=[],e=this._defaultDrawingOptions;for(const[i,s]of this.typesMap)t.push([i,e[s]]);return t}get propertiesToUpdate(){const t=[],{_drawingOptions:e}=this;for(const[i,s]of this.constructor.typesMap)t.push([i,e[s]]);return t}_updateProperty(t,e,i){const s=this._drawingOptions,n=s[e],setter=t=>{s.updateProperty(e,t);const i=this.#gr.updateProperty(e,t);i&&this.#Sr(i);this.parent?.drawLayer.updateProperties(this._drawId,s.toSVGProperties())};this.addCommands({cmd:setter.bind(this,i),undo:setter.bind(this,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:t,overwriteIfSameType:!0,keepUndo:!0})}_onResizing(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#gr.getPathResizingSVGProperties(this.#Cr()),{bbox:this.#Tr()}))}_onResized(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#gr.getPathResizedSVGProperties(this.#Cr()),{bbox:this.#Tr()}))}_onTranslating(t,e){this.parent?.drawLayer.updateProperties(this._drawId,{bbox:this.#Tr(t,e)})}_onTranslated(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#gr.getPathTranslatedSVGProperties(this.#Cr(),this.parentDimensions),{bbox:this.#Tr()}))}_onStartDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!0}})}_onStopDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!1}})}commit(){super.commit();this.disableEditMode();this.disableEditing()}disableEditing(){super.disableEditing();this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing();this.div.classList.toggle("disabled",!1)}getBaseTranslation(){return[0,0]}get isResizable(){return!0}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this);this._isDraggable=!0;if(this.#mr){this.#mr=!1;this.commit();this.parent.setSelected(this);t&&this.isOnScreen&&this.div.focus()}}remove(){this.#rr();super.remove()}rebuild(){if(this.parent){super.rebuild();if(null!==this.div){this.#tr();this.#Sr(this.#gr.box);this.isAttachedToDOM||this.parent.add(this)}}}setParent(t){let e=!1;if(this.parent&&!t){this._uiManager.removeShouldRescale(this);this.#rr()}else if(t){this._uiManager.addShouldRescale(this);this.#tr(t);e=!this.parent&&this.div?.classList.contains("selectedEditor")}super.setParent(t);e&&this.select()}#rr(){if(null!==this._drawId&&this.parent){this.parent.drawLayer.remove(this._drawId);this._drawId=null;this._drawingOptions.reset()}}#tr(t=this.parent){if(null===this._drawId||this.parent!==t)if(null===this._drawId){this._drawingOptions.updateAll();this._drawId=this.#Er(this.#gr,t)}else this.parent.drawLayer.updateParent(this._drawId,t.drawLayer)}#Mr([t,e,i,s]){const{parentDimensions:[n,a],rotation:r}=this;switch(r){case 90:return[e,1-t,i*(a/n),s*(n/a)];case 180:return[1-t,1-e,i,s];case 270:return[1-e,t,i*(a/n),s*(n/a)];default:return[t,e,i,s]}}#Cr(){const{x:t,y:e,width:i,height:s,parentDimensions:[n,a],rotation:r}=this;switch(r){case 90:return[1-e,t,i*(n/a),s*(a/n)];case 180:return[1-t,1-e,i,s];case 270:return[e,1-t,i*(n/a),s*(a/n)];default:return[t,e,i,s]}}#Sr(t){[this.x,this.y,this.width,this.height]=this.#Mr(t);if(this.div){this.fixAndSetPosition();const[t,e]=this.parentDimensions;this.setDims(this.width*t,this.height*e)}this._onResized()}#Tr(){const{x:t,y:e,width:i,height:s,rotation:n,parentRotation:a,parentDimensions:[r,o]}=this;switch((4*n+a)/90){case 1:return[1-e-s,t,s,i];case 2:return[1-t-i,1-e-s,i,s];case 3:return[e,1-t-i,s,i];case 4:return[t,e-i*(r/o),s*(o/r),i*(r/o)];case 5:return[1-e,t,i*(r/o),s*(o/r)];case 6:return[1-t-s*(o/r),1-e,s*(o/r),i*(r/o)];case 7:return[e-i*(r/o),1-t-s*(o/r),i*(r/o),s*(o/r)];case 8:return[t-i,e-s,i,s];case 9:return[1-e,t-i,s,i];case 10:return[1-t,1-e,i,s];case 11:return[e-s,1-t,s,i];case 12:return[t-s*(o/r),e,s*(o/r),i*(r/o)];case 13:return[1-e-i*(r/o),t-s*(o/r),i*(r/o),s*(o/r)];case 14:return[1-t,1-e-i*(r/o),s*(o/r),i*(r/o)];case 15:return[e,1-t,i*(r/o),s*(o/r)];default:return[t,e,i,s]}}rotate(){this.parent&&this.parent.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties({bbox:this.#Tr()},this.#gr.updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&this.#Sr(this.#gr.updateParentDimensions(this.parentDimensions,this.parent.scale))}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;const t=super.render();t.classList.add("draw");const e=document.createElement("div");t.append(e);e.setAttribute("aria-hidden","true");e.className="internal";const[i,s]=this.parentDimensions;this.setDims(this.width*i,this.height*s);this._uiManager.addShouldRescale(this);this.disableEditing();return t}static createDrawerInstance(t,e,i,s,n){unreachable("Not implemented")}static startDrawing(t,e,i,s){const{target:n,offsetX:a,offsetY:r,pointerId:o,pointerType:l}=s;if(DrawingEditor.#vr&&DrawingEditor.#vr!==l)return;const{viewport:{rotation:h}}=t,{width:d,height:c}=n.getBoundingClientRect(),u=DrawingEditor.#br=new AbortController,p=t.combinedSignal(u);DrawingEditor.#wr||=o;DrawingEditor.#vr??=l;window.addEventListener("pointerup",(t=>{DrawingEditor.#wr===t.pointerId?this._endDraw(t):DrawingEditor.#yr?.delete(t.pointerId)}),{signal:p});window.addEventListener("pointercancel",(t=>{DrawingEditor.#wr===t.pointerId?this._currentParent.endDrawingSession():DrawingEditor.#yr?.delete(t.pointerId)}),{signal:p});window.addEventListener("pointerdown",(t=>{if(DrawingEditor.#vr===t.pointerType){(DrawingEditor.#yr||=new Set).add(t.pointerId);if(DrawingEditor.#fr.isCancellable()){DrawingEditor.#fr.removeLastElement();DrawingEditor.#fr.isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)}}}),{capture:!0,passive:!1,signal:p});window.addEventListener("contextmenu",noContextMenu,{signal:p});n.addEventListener("pointermove",this._drawMove.bind(this),{signal:p});n.addEventListener("touchmove",(t=>{t.timeStamp===DrawingEditor.#xr&&stopEvent(t)}),{signal:p});t.toggleDrawing();e._editorUndoBar?.hide();if(DrawingEditor.#fr)t.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#fr.startNew(a,r,d,c,h));else{e.updateUIForDefaultProperties(this);DrawingEditor.#fr=this.createDrawerInstance(a,r,d,c,h);DrawingEditor.#Ar=this.getDefaultDrawingOptions();this._currentParent=t;({id:this._currentDrawId}=t.drawLayer.draw(this._mergeSVGProperties(DrawingEditor.#Ar.toSVGProperties(),DrawingEditor.#fr.defaultSVGProperties),!0,!1))}}static _drawMove(t){DrawingEditor.#xr=-1;if(!DrawingEditor.#fr)return;const{offsetX:e,offsetY:i,pointerId:s}=t;if(DrawingEditor.#wr===s)if(DrawingEditor.#yr?.size>=1)this._endDraw(t);else{this._currentParent.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#fr.add(e,i));DrawingEditor.#xr=t.timeStamp;stopEvent(t)}}static _cleanup(t){if(t){this._currentDrawId=-1;this._currentParent=null;DrawingEditor.#fr=null;DrawingEditor.#Ar=null;DrawingEditor.#vr=null;DrawingEditor.#xr=NaN}if(DrawingEditor.#br){DrawingEditor.#br.abort();DrawingEditor.#br=null;DrawingEditor.#wr=NaN;DrawingEditor.#yr=null}}static _endDraw(t){const e=this._currentParent;if(e){e.toggleDrawing(!0);this._cleanup(!1);t&&e.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#fr.end(t.offsetX,t.offsetY));if(this.supportMultipleDrawings){const t=DrawingEditor.#fr,i=this._currentDrawId,s=t.getLastElement();e.addCommands({cmd:()=>{e.drawLayer.updateProperties(i,t.setLastElement(s))},undo:()=>{e.drawLayer.updateProperties(i,t.removeLastElement())},mustExec:!1,type:m.DRAW_STEP})}else this.endDrawing(!1)}}static endDrawing(t){const e=this._currentParent;if(!e)return null;e.toggleDrawing(!0);e.cleanUndoStack(m.DRAW_STEP);if(!DrawingEditor.#fr.isEmpty()){const{pageDimensions:[i,s],scale:n}=e,a=e.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:DrawingEditor.#fr.getOutlines(i*n,s*n,n,this._INNER_MARGIN),drawingOptions:DrawingEditor.#Ar,mustBeCommitted:!t});this._cleanup(!0);return a}e.drawLayer.remove(this._currentDrawId);this._cleanup(!0);return null}createDrawingOptions(t){}static deserializeDraw(t,e,i,s,n,a){unreachable("Not implemented")}static async deserialize(t,e,i){const{rawDims:{pageWidth:s,pageHeight:n,pageX:a,pageY:r}}=e.viewport,o=this.deserializeDraw(a,r,s,n,this._INNER_MARGIN,t),l=await super.deserialize(t,e,i);l.createDrawingOptions(t);l.#_r({drawOutlines:o});l.#tr();l.onScaleChanging();l.rotate();return l}serializeDraw(t){const[e,i]=this.pageTranslation,[s,n]=this.pageDimensions;return this.#gr.serialize([e,i,s,n],t)}renderAnnotationElement(t){t.updateEdited({rect:this.getRect(0,0)});return null}static canCreateNewEmptyEditor(){return!1}}class InkDrawOutliner{#Kn=new Float64Array(6);#bn;#Pr;#Fi;#ea;#ia;#Dr="";#kr=0;#Ea=new InkDrawOutline;#Rr;#Ir;constructor(t,e,i,s,n,a){this.#Rr=i;this.#Ir=s;this.#Fi=n;this.#ea=a;[t,e]=this.#Fr(t,e);const r=this.#bn=[NaN,NaN,NaN,NaN,t,e];this.#ia=[t,e];this.#Pr=[{line:r,points:this.#ia}];this.#Kn.set(r,0)}updateProperty(t,e){"stroke-width"===t&&(this.#ea=e)}#Fr(t,e){return Outline._normalizePoint(t,e,this.#Rr,this.#Ir,this.#Fi)}isEmpty(){return!this.#Pr||0===this.#Pr.length}isCancellable(){return this.#ia.length<=10}add(t,e){[t,e]=this.#Fr(t,e);const[i,s,n,a]=this.#Kn.subarray(2,6),r=t-n,o=e-a;if(Math.hypot(this.#Rr*r,this.#Ir*o)<=2)return null;this.#ia.push(t,e);if(isNaN(i)){this.#Kn.set([n,a,t,e],2);this.#bn.push(NaN,NaN,NaN,NaN,t,e);return{path:{d:this.toSVGPath()}}}isNaN(this.#Kn[0])&&this.#bn.splice(6,6);this.#Kn.set([i,s,n,a,t,e],0);this.#bn.push(...Outline.createBezierPoints(i,s,n,a,t,e));return{path:{d:this.toSVGPath()}}}end(t,e){const i=this.add(t,e);return i||(2===this.#ia.length?{path:{d:this.toSVGPath()}}:null)}startNew(t,e,i,s,n){this.#Rr=i;this.#Ir=s;this.#Fi=n;[t,e]=this.#Fr(t,e);const a=this.#bn=[NaN,NaN,NaN,NaN,t,e];this.#ia=[t,e];const r=this.#Pr.at(-1);if(r){r.line=new Float32Array(r.line);r.points=new Float32Array(r.points)}this.#Pr.push({line:a,points:this.#ia});this.#Kn.set(a,0);this.#kr=0;this.toSVGPath();return null}getLastElement(){return this.#Pr.at(-1)}setLastElement(t){if(!this.#Pr)return this.#Ea.setLastElement(t);this.#Pr.push(t);this.#bn=t.line;this.#ia=t.points;this.#kr=0;return{path:{d:this.toSVGPath()}}}removeLastElement(){if(!this.#Pr)return this.#Ea.removeLastElement();this.#Pr.pop();this.#Dr="";for(let t=0,e=this.#Pr.length;tt??NaN)),d,c,u,p),points:g(r[t].map((t=>t??NaN)),d,c,u,p)});const m=new InkDrawOutline;m.build(h,i,s,1,o,l,n);return m}#Hr(t=this.#ea){const e=this.#Wn+t/2*this.#Or;return this.#Fi%180==0?[e/this.#Rr,e/this.#Ir]:[e/this.#Ir,e/this.#Rr]}#Br(){const[t,e,i,s]=this.#pa,[n,a]=this.#Hr(0);return[t+n,e+a,i-2*n,s-2*a]}#Nr(){const t=this.#pa=new Float32Array([1/0,1/0,-1/0,-1/0]);for(const{line:e}of this.#Pr){if(e.length<=12){for(let i=4,s=e.length;it!==e[i]))||t.thickness!==i||t.opacity!==s||t.pageIndex!==n}renderAnnotationElement(t){const{points:e,rect:i}=this.serializeDraw(!1);t.updateEdited({rect:i,thickness:this._drawingOptions["stroke-width"],points:e});return null}}class StampEditor extends AnnotationEditor{#Ur=null;#Gr=null;#$r=null;#Vr=null;#jr=null;#Wr="";#qr=null;#Xr=null;#Kr=!1;#Yr=!1;static _type="stamp";static _editorType=g.STAMP;constructor(t){super({...t,name:"stampEditor"});this.#Vr=t.bitmapUrl;this.#jr=t.bitmapFile}static initialize(t,e){AnnotationEditor.initialize(t,e)}static get supportedTypes(){return shadow(this,"supportedTypes",["apng","avif","bmp","gif","jpeg","png","svg+xml","webp","x-icon"].map((t=>`image/${t}`)))}static get supportedTypesStr(){return shadow(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(t){return this.supportedTypes.includes(t)}static paste(t,e){e.pasteEditor(g.STAMP,{bitmapFile:t.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1);super.altTextFinish()}get telemetryFinalData(){return{type:"stamp",hasAltText:!!this.altTextData?.altText}}static computeTelemetryFinalData(t){const e=t.get("hasAltText");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}#Qr(t,e=!1){if(t){this.#Ur=t.bitmap;if(!e){this.#Gr=t.id;this.#Kr=t.isSvg}t.file&&(this.#Wr=t.file.name);this.#Jr()}else this.remove()}#Zr(){this.#$r=null;this._uiManager.enableWaiting(!1);if(this.#qr)if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#Ur){this._editToolbar.hide();this._uiManager.editAltText(this,!0)}else{if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#Ur){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}}async mlGuessAltText(t=null,e=!0){if(this.hasAltTextData())return null;const{mlManager:i}=this._uiManager;if(!i)throw new Error("No ML.");if(!await i.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:s,width:n,height:a}=t||this.copyCanvas(null,null,!0).imageData,r=await i.guess({name:"altText",request:{data:s,width:n,height:a,channels:s.length/(n*a)}});if(!r)throw new Error("No response from the AI service.");if(r.error)throw new Error("Error from the AI service.");if(r.cancel)return null;if(!r.output)throw new Error("No valid response from the AI service.");const o=r.output;await this.setGuessedAltText(o);e&&!this.hasAltTextData()&&(this.altTextData={alt:o,decorative:!1});return o}#to(){if(this.#Gr){this._uiManager.enableWaiting(!0);this._uiManager.imageManager.getFromId(this.#Gr).then((t=>this.#Qr(t,!0))).finally((()=>this.#Zr()));return}if(this.#Vr){const t=this.#Vr;this.#Vr=null;this._uiManager.enableWaiting(!0);this.#$r=this._uiManager.imageManager.getFromUrl(t).then((t=>this.#Qr(t))).finally((()=>this.#Zr()));return}if(this.#jr){const t=this.#jr;this.#jr=null;this._uiManager.enableWaiting(!0);this.#$r=this._uiManager.imageManager.getFromFile(t).then((t=>this.#Qr(t))).finally((()=>this.#Zr()));return}const t=document.createElement("input");t.type="file";t.accept=StampEditor.supportedTypesStr;const e=this._uiManager._signal;this.#$r=new Promise((i=>{t.addEventListener("change",(async()=>{if(t.files&&0!==t.files.length){this._uiManager.enableWaiting(!0);const e=await this._uiManager.imageManager.getFromFile(t.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}});this.#Qr(e)}else this.remove();i()}),{signal:e});t.addEventListener("cancel",(()=>{this.remove();i()}),{signal:e})})).finally((()=>this.#Zr()));t.click()}remove(){if(this.#Gr){this.#Ur=null;this._uiManager.imageManager.deleteId(this.#Gr);this.#qr?.remove();this.#qr=null;if(this.#Xr){clearTimeout(this.#Xr);this.#Xr=null}}super.remove()}rebuild(){if(this.parent){super.rebuild();if(null!==this.div){this.#Gr&&null===this.#qr&&this.#to();this.isAttachedToDOM||this.parent.add(this)}}else this.#Gr&&this.#to()}onceAdded(t){this._isDraggable=!0;t&&this.div.focus()}isEmpty(){return!(this.#$r||this.#Ur||this.#Vr||this.#jr||this.#Gr)}get isResizable(){return!0}render(){if(this.div)return this.div;let t,e;if(this.width){t=this.x;e=this.y}super.render();this.div.hidden=!0;this.div.setAttribute("role","figure");this.addAltTextButton();this.#Ur?this.#Jr():this.#to();if(this.width&&!this.annotationElementId){const[i,s]=this.parentDimensions;this.setAt(t*i,e*s,this.width*i,this.height*s)}this._uiManager.addShouldRescale(this);return this.div}_onResized(){this.onScaleChanging()}onScaleChanging(){if(!this.parent)return;null!==this.#Xr&&clearTimeout(this.#Xr);this.#Xr=setTimeout((()=>{this.#Xr=null;this.#eo()}),200)}#Jr(){const{div:t}=this;let{width:e,height:i}=this.#Ur;const[s,n]=this.pageDimensions,a=.75;if(this.width){e=this.width*s;i=this.height*n}else if(e>a*s||i>a*n){const t=Math.min(a*s/e,a*n/i);e*=t;i*=t}const[r,o]=this.parentDimensions;this.setDims(e*r/s,i*o/n);this._uiManager.enableWaiting(!1);const l=this.#qr=document.createElement("canvas");l.setAttribute("role","img");this.addContainer(l);this.width=e/s;this.height=i/n;this._initialOptions?.isCentered?this.center():this.fixAndSetPosition();this._initialOptions=null;this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&!this.annotationElementId||(t.hidden=!1);this.#eo();if(!this.#Yr){this.parent.addUndoableEditor(this);this.#Yr=!0}this._reportTelemetry({action:"inserted_image"});this.#Wr&&l.setAttribute("aria-label",this.#Wr)}copyCanvas(t,e,i=!1){t||(t=224);const{width:s,height:n}=this.#Ur,a=new OutputScale;let r=this.#Ur,o=s,l=n,h=null;if(e){if(s>e||n>e){const t=Math.min(e/s,e/n);o=Math.floor(s*t);l=Math.floor(n*t)}h=document.createElement("canvas");const t=h.width=Math.ceil(o*a.sx),i=h.height=Math.ceil(l*a.sy);this.#Kr||(r=this.#io(t,i));const d=h.getContext("2d");d.filter=this._uiManager.hcmFilter;let c="white",u="#cfcfd8";if("none"!==this._uiManager.hcmFilter)u="black";else if(window.matchMedia?.("(prefers-color-scheme: dark)").matches){c="#8f8f9d";u="#42414d"}const p=15,g=p*a.sx,m=p*a.sy,f=new OffscreenCanvas(2*g,2*m),b=f.getContext("2d");b.fillStyle=c;b.fillRect(0,0,2*g,2*m);b.fillStyle=u;b.fillRect(0,0,g,m);b.fillRect(g,m,g,m);d.fillStyle=d.createPattern(f,"repeat");d.fillRect(0,0,t,i);d.drawImage(r,0,0,r.width,r.height,0,0,t,i)}let d=null;if(i){let e,i;if(a.symmetric&&r.widtht||n>t){const a=Math.min(t/s,t/n);e=Math.floor(s*a);i=Math.floor(n*a);this.#Kr||(r=this.#io(e,i))}}const o=new OffscreenCanvas(e,i).getContext("2d",{willReadFrequently:!0});o.drawImage(r,0,0,r.width,r.height,0,0,e,i);d={width:e,height:i,data:o.getImageData(0,0,e,i).data}}return{canvas:h,width:o,height:l,imageData:d}}#io(t,e){const{width:i,height:s}=this.#Ur;let n=i,a=s,r=this.#Ur;for(;n>2*t||a>2*e;){const i=n,s=a;n>2*t&&(n=n>=16384?Math.floor(n/2)-1:Math.ceil(n/2));a>2*e&&(a=a>=16384?Math.floor(a/2)-1:Math.ceil(a/2));const o=new OffscreenCanvas(n,a);o.getContext("2d").drawImage(r,0,0,i,s,0,0,n,a);r=o.transferToImageBitmap()}return r}#eo(){const[t,e]=this.parentDimensions,{width:i,height:s}=this,n=new OutputScale,a=Math.ceil(i*t*n.sx),r=Math.ceil(s*e*n.sy),o=this.#qr;if(!o||o.width===a&&o.height===r)return;o.width=a;o.height=r;const l=this.#Kr?this.#Ur:this.#io(a,r),h=o.getContext("2d");h.filter=this._uiManager.hcmFilter;h.drawImage(l,0,0,l.width,l.height,0,0,a,r)}getImageForAltText(){return this.#qr}#so(t){if(t){if(this.#Kr){const t=this._uiManager.imageManager.getSvgUrl(this.#Gr);if(t)return t}const t=document.createElement("canvas");({width:t.width,height:t.height}=this.#Ur);t.getContext("2d").drawImage(this.#Ur,0,0);return t.toDataURL()}if(this.#Kr){const[t,e]=this.pageDimensions,i=Math.round(this.width*t*PixelsPerInch.PDF_TO_CSS_UNITS),s=Math.round(this.height*e*PixelsPerInch.PDF_TO_CSS_UNITS),n=new OffscreenCanvas(i,s);n.getContext("2d").drawImage(this.#Ur,0,0,this.#Ur.width,this.#Ur.height,0,0,i,s);return n.transferToImageBitmap()}return structuredClone(this.#Ur)}static async deserialize(t,e,i){let s=null;if(t instanceof StampAnnotationElement){const{data:{rect:n,rotation:a,id:r,structParent:o,popupRef:l},container:h,parent:{page:{pageNumber:d}}}=t,c=h.querySelector("canvas"),u=i.imageManager.getFromCanvas(h.id,c);c.remove();const p=(await e._structTree.getAriaAttributes(`${et}${r}`))?.get("aria-label")||"";s=t={annotationType:g.STAMP,bitmapId:u.id,bitmap:u.bitmap,pageIndex:d-1,rect:n.slice(0),rotation:a,id:r,deleted:!1,accessibilityData:{decorative:!1,altText:p},isSvg:!1,structParent:o,popupRef:l}}const n=await super.deserialize(t,e,i),{rect:a,bitmap:r,bitmapUrl:o,bitmapId:l,isSvg:h,accessibilityData:d}=t;if(l&&i.imageManager.isValidId(l)){n.#Gr=l;r&&(n.#Ur=r)}else n.#Vr=o;n.#Kr=h;const[c,u]=n.pageDimensions;n.width=(a[2]-a[0])/c;n.height=(a[3]-a[1])/u;n.annotationElementId=t.id||null;d&&(n.altTextData=d);n._initialData=s;n.#Yr=!!s;return n}serialize(t=!1,e=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const i={annotationType:g.STAMP,bitmapId:this.#Gr,pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:this.#Kr,structTreeParentId:this._structTreeParentId};if(t){i.bitmapUrl=this.#so(!0);i.accessibilityData=this.serializeAltText(!0);return i}const{decorative:s,altText:n}=this.serializeAltText(!1);!s&&n&&(i.accessibilityData={type:"Figure",alt:n});if(this.annotationElementId){const t=this.#$n(i);if(t.isSame)return null;t.isSameAltText?delete i.accessibilityData:i.accessibilityData.structParent=this._initialData.structParent??-1}i.id=this.annotationElementId;if(null===e)return i;e.stamps||=new Map;const a=this.#Kr?(i.rect[2]-i.rect[0])*(i.rect[3]-i.rect[1]):null;if(e.stamps.has(this.#Gr)){if(this.#Kr){const t=e.stamps.get(this.#Gr);if(a>t.area){t.area=a;t.serialized.bitmap.close();t.serialized.bitmap=this.#so(!1)}}}else{e.stamps.set(this.#Gr,{area:a,serialized:i});i.bitmap=this.#so(!1)}return i}#$n(t){const{pageIndex:e,accessibilityData:{altText:i}}=this._initialData,s=t.pageIndex===e,n=(t.accessibilityData?.alt||"")===i;return{isSame:!this._hasBeenMoved&&!this._hasBeenResized&&s&&n,isSameAltText:n}}renderAnnotationElement(t){t.updateEdited({rect:this.getRect(0,0)});return null}}class AnnotationEditorLayer{#Cn;#no=!1;#ao=null;#ro=null;#oo=null;#lo=new Map;#ho=!1;#do=!1;#co=!1;#uo=null;#po=null;#go=null;#mo=null;#m;static _initialized=!1;static#U=new Map([FreeTextEditor,InkEditor,StampEditor,HighlightEditor].map((t=>[t._editorType,t])));constructor({uiManager:t,pageIndex:e,div:i,structTreeLayer:s,accessibilityManager:n,annotationLayer:a,drawLayer:r,textLayer:o,viewport:l,l10n:h}){const d=[...AnnotationEditorLayer.#U.values()];if(!AnnotationEditorLayer._initialized){AnnotationEditorLayer._initialized=!0;for(const e of d)e.initialize(h,t)}t.registerEditorTypes(d);this.#m=t;this.pageIndex=e;this.div=i;this.#Cn=n;this.#ao=a;this.viewport=l;this.#go=o;this.drawLayer=r;this._structTree=s;this.#m.addLayer(this)}get isEmpty(){return 0===this.#lo.size}get isInvisible(){return this.isEmpty&&this.#m.getMode()===g.NONE}updateToolbar(t){this.#m.updateToolbar(t)}updateMode(t=this.#m.getMode()){this.#fo();switch(t){case g.NONE:this.disableTextSelection();this.togglePointerEvents(!1);this.toggleAnnotationLayerPointerEvents(!0);this.disableClick();return;case g.INK:this.disableTextSelection();this.togglePointerEvents(!0);this.enableClick();break;case g.HIGHLIGHT:this.enableTextSelection();this.togglePointerEvents(!1);this.disableClick();break;default:this.disableTextSelection();this.togglePointerEvents(!0);this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);const{classList:e}=this.div;for(const i of AnnotationEditorLayer.#U.values())e.toggle(`${i._type}Editing`,t===i._editorType);this.div.hidden=!1}hasTextLayer(t){return t===this.#go?.div}setEditingState(t){this.#m.setEditingState(t)}addCommands(t){this.#m.addCommands(t)}cleanUndoStack(t){this.#m.cleanUndoStack(t)}toggleDrawing(t=!1){this.div.classList.toggle("drawing",!t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){this.#ao?.div.classList.toggle("disabled",!t)}async enable(){this.#co=!0;this.div.tabIndex=0;this.togglePointerEvents(!0);const t=new Set;for(const e of this.#lo.values()){e.enableEditing();e.show(!0);if(e.annotationElementId){this.#m.removeChangedExistingAnnotation(e);t.add(e.annotationElementId)}}if(!this.#ao){this.#co=!1;return}const e=this.#ao.getEditableAnnotations();for(const i of e){i.hide();if(this.#m.isDeletedAnnotationElement(i.data.id))continue;if(t.has(i.data.id))continue;const e=await this.deserialize(i);if(e){this.addOrRebuild(e);e.enableEditing()}}this.#co=!1}disable(){this.#do=!0;this.div.tabIndex=-1;this.togglePointerEvents(!1);const t=new Map,e=new Map;for(const i of this.#lo.values()){i.disableEditing();if(i.annotationElementId)if(null===i.serialize()){e.set(i.annotationElementId,i);this.getEditableAnnotation(i.annotationElementId)?.show();i.remove()}else t.set(i.annotationElementId,i)}if(this.#ao){const i=this.#ao.getEditableAnnotations();for(const s of i){const{id:i}=s.data;if(this.#m.isDeletedAnnotationElement(i))continue;let n=e.get(i);if(n){n.resetAnnotationElement(s);n.show(!1);s.show()}else{n=t.get(i);if(n){this.#m.addChangedExistingAnnotation(n);n.renderAnnotationElement(s)&&n.show(!1)}s.show()}}}this.#fo();this.isEmpty&&(this.div.hidden=!0);const{classList:i}=this.div;for(const t of AnnotationEditorLayer.#U.values())i.remove(`${t._type}Editing`);this.disableTextSelection();this.toggleAnnotationLayerPointerEvents(!0);this.#do=!1}getEditableAnnotation(t){return this.#ao?.getEditableAnnotation(t)||null}setActiveEditor(t){this.#m.getActive()!==t&&this.#m.setActiveEditor(t)}enableTextSelection(){this.div.tabIndex=-1;if(this.#go?.div&&!this.#mo){this.#mo=new AbortController;const t=this.#m.combinedSignal(this.#mo);this.#go.div.addEventListener("pointerdown",this.#bo.bind(this),{signal:t});this.#go.div.classList.add("highlighting")}}disableTextSelection(){this.div.tabIndex=0;if(this.#go?.div&&this.#mo){this.#mo.abort();this.#mo=null;this.#go.div.classList.remove("highlighting")}}#bo(t){this.#m.unselectAll();const{target:e}=t;if(e===this.#go.div||("img"===e.getAttribute("role")||e.classList.contains("endOfContent"))&&this.#go.div.contains(e)){const{isMac:e}=util_FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)return;this.#m.showAllEditors("highlight",!0,!0);this.#go.div.classList.add("free");this.toggleDrawing();HighlightEditor.startHighlighting(this,"ltr"===this.#m.direction,{target:this.#go.div,x:t.x,y:t.y});this.#go.div.addEventListener("pointerup",(()=>{this.#go.div.classList.remove("free");this.toggleDrawing(!0)}),{once:!0,signal:this.#m._signal});t.preventDefault()}}enableClick(){if(this.#ro)return;this.#ro=new AbortController;const t=this.#m.combinedSignal(this.#ro);this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t});const e=this.pointerup.bind(this);this.div.addEventListener("pointerup",e,{signal:t});this.div.addEventListener("pointercancel",e,{signal:t})}disableClick(){this.#ro?.abort();this.#ro=null}attach(t){this.#lo.set(t.id,t);const{annotationElementId:e}=t;e&&this.#m.isDeletedAnnotationElement(e)&&this.#m.removeDeletedAnnotationElement(t)}detach(t){this.#lo.delete(t.id);this.#Cn?.removePointerInTextLayer(t.contentDiv);!this.#do&&t.annotationElementId&&this.#m.addDeletedAnnotationElement(t)}remove(t){this.detach(t);this.#m.removeEditor(t);t.div.remove();t.isAttachedToDOM=!1}changeParent(t){if(t.parent!==this){if(t.parent&&t.annotationElementId){this.#m.addDeletedAnnotationElement(t.annotationElementId);AnnotationEditor.deleteAnnotationElement(t);t.annotationElementId=null}this.attach(t);t.parent?.detach(t);t.setParent(this);if(t.div&&t.isAttachedToDOM){t.div.remove();this.div.append(t.div)}}}add(t){if(t.parent!==this||!t.isAttachedToDOM){this.changeParent(t);this.#m.addEditor(t);this.attach(t);if(!t.isAttachedToDOM){const e=t.render();this.div.append(e);t.isAttachedToDOM=!0}t.fixAndSetPosition();t.onceAdded(!this.#co);this.#m.addToAnnotationStorage(t);t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){if(!t.isAttachedToDOM)return;const{activeElement:e}=document;if(t.div.contains(e)&&!this.#oo){t._focusEventsAllowed=!1;this.#oo=setTimeout((()=>{this.#oo=null;if(t.div.contains(document.activeElement))t._focusEventsAllowed=!0;else{t.div.addEventListener("focusin",(()=>{t._focusEventsAllowed=!0}),{once:!0,signal:this.#m._signal});e.focus()}}),0)}t._structTreeParentId=this.#Cn?.moveElementInDOM(this.div,t.div,t.contentDiv,!0)}addOrRebuild(t){if(t.needsToBeRebuilt()){t.parent||=this;t.rebuild();t.show()}else this.add(t)}addUndoableEditor(t){this.addCommands({cmd:()=>t._uiManager.rebuild(t),undo:()=>{t.remove()},mustExec:!1})}getNextId(){return this.#m.getId()}get#Ao(){return AnnotationEditorLayer.#U.get(this.#m.getMode())}combinedSignal(t){return this.#m.combinedSignal(t)}#wo(t){const e=this.#Ao;return e?new e.prototype.constructor(t):null}canCreateNewEmptyEditor(){return this.#Ao?.canCreateNewEmptyEditor()}pasteEditor(t,e){this.#m.updateToolbar(t);this.#m.updateMode(t);const{offsetX:i,offsetY:s}=this.#vo(),n=this.getNextId(),a=this.#wo({parent:this,id:n,x:i,y:s,uiManager:this.#m,isCentered:!0,...e});a&&this.add(a)}async deserialize(t){return await(AnnotationEditorLayer.#U.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#m))||null}createAndAddNewEditor(t,e,i={}){const s=this.getNextId(),n=this.#wo({parent:this,id:s,x:t.offsetX,y:t.offsetY,uiManager:this.#m,isCentered:e,...i});n&&this.add(n);return n}#vo(){const{x:t,y:e,width:i,height:s}=this.div.getBoundingClientRect(),n=Math.max(0,t),a=Math.max(0,e),r=(n+Math.min(window.innerWidth,t+i))/2-t,o=(a+Math.min(window.innerHeight,e+s))/2-e,[l,h]=this.viewport.rotation%180==0?[r,o]:[o,r];return{offsetX:l,offsetY:h}}addNewEditor(){this.createAndAddNewEditor(this.#vo(),!0)}setSelected(t){this.#m.setSelected(t)}toggleSelected(t){this.#m.toggleSelected(t)}unselect(t){this.#m.unselect(t)}pointerup(t){const{isMac:e}=util_FeatureTest.platform;if(!(0!==t.button||t.ctrlKey&&e)&&t.target===this.div&&this.#ho){this.#ho=!1;this.#Ao?.isDrawer&&this.#Ao.supportMultipleDrawings||(this.#no?this.#m.getMode()!==g.STAMP?this.createAndAddNewEditor(t,!1):this.#m.unselectAll():this.#no=!0)}}pointerdown(t){this.#m.getMode()===g.HIGHLIGHT&&this.enableTextSelection();if(this.#ho){this.#ho=!1;return}const{isMac:e}=util_FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)return;if(t.target!==this.div)return;this.#ho=!0;if(this.#Ao?.isDrawer){this.startDrawingSession(t);return}const i=this.#m.getActive();this.#no=!i||i.isEmpty()}startDrawingSession(t){this.div.focus();if(this.#uo){this.#Ao.startDrawing(this,this.#m,!1,t);return}this.#m.setCurrentDrawingSession(this);this.#uo=new AbortController;const e=this.#m.combinedSignal(this.#uo);this.div.addEventListener("blur",(({relatedTarget:t})=>{if(t&&!this.div.contains(t)){this.#po=null;this.commitOrRemove()}}),{signal:e});this.#Ao.startDrawing(this,this.#m,!1,t)}pause(t){if(t){const{activeElement:t}=document;this.div.contains(t)&&(this.#po=t)}else this.#po&&setTimeout((()=>{this.#po?.focus();this.#po=null}),0)}endDrawingSession(t=!1){if(!this.#uo)return null;this.#m.setCurrentDrawingSession(null);this.#uo.abort();this.#uo=null;this.#po=null;return this.#Ao.endDrawing(t)}findNewParent(t,e,i){const s=this.#m.findParent(e,i);if(null===s||s===this)return!1;s.changeParent(t);return!0}commitOrRemove(){if(this.#uo){this.endDrawingSession();return!0}return!1}onScaleChanging(){this.#uo&&this.#Ao.onScaleChangingWhenDrawing(this)}destroy(){this.commitOrRemove();if(this.#m.getActive()?.parent===this){this.#m.commitOrRemove();this.#m.setActiveEditor(null)}if(this.#oo){clearTimeout(this.#oo);this.#oo=null}for(const t of this.#lo.values()){this.#Cn?.removePointerInTextLayer(t.contentDiv);t.setParent(null);t.isAttachedToDOM=!1;t.div.remove()}this.div=null;this.#lo.clear();this.#m.removeLayer(this)}#fo(){for(const t of this.#lo.values())t.isEmpty()&&t.remove()}render({viewport:t}){this.viewport=t;setLayerDimensions(this.div,t);for(const t of this.#m.getEditors(this.pageIndex)){this.add(t);t.rebuild()}this.updateMode()}update({viewport:t}){this.#m.commitOrRemove();this.#fo();const e=this.viewport.rotation,i=t.rotation;this.viewport=t;setLayerDimensions(this.div,{rotation:i});if(e!==i)for(const t of this.#lo.values())t.rotate(i)}get pageDimensions(){const{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return this.#m.viewParameters.realScale}}class DrawLayer{#nn=null;#w=0;#yo=new Map;#xo=new Map;constructor({pageIndex:t}){this.pageIndex=t}setParent(t){if(this.#nn){if(this.#nn!==t){if(this.#yo.size>0)for(const e of this.#yo.values()){e.remove();t.append(e)}this.#nn=t}}else this.#nn=t}static get _svgFactory(){return shadow(this,"_svgFactory",new DOMSVGFactory)}static#_o(t,[e,i,s,n]){const{style:a}=t;a.top=100*i+"%";a.left=100*e+"%";a.width=100*s+"%";a.height=100*n+"%"}#Eo(){const t=DrawLayer._svgFactory.create(1,1,!0);this.#nn.append(t);t.setAttribute("aria-hidden",!0);return t}#So(t,e){const i=DrawLayer._svgFactory.createElement("clipPath");t.append(i);const s=`clip_${e}`;i.setAttribute("id",s);i.setAttribute("clipPathUnits","objectBoundingBox");const n=DrawLayer._svgFactory.createElement("use");i.append(n);n.setAttribute("href",`#${e}`);n.classList.add("clip");return s}#Co(t,e){for(const[i,s]of Object.entries(e))null===s?t.removeAttribute(i):t.setAttribute(i,s)}draw(t,e=!1,i=!1){const s=this.#w++,n=this.#Eo(),a=DrawLayer._svgFactory.createElement("defs");n.append(a);const r=DrawLayer._svgFactory.createElement("path");a.append(r);const o=`path_p${this.pageIndex}_${s}`;r.setAttribute("id",o);r.setAttribute("vector-effect","non-scaling-stroke");e&&this.#xo.set(s,r);const l=i?this.#So(a,o):null,h=DrawLayer._svgFactory.createElement("use");n.append(h);h.setAttribute("href",`#${o}`);this.updateProperties(n,t);this.#yo.set(s,n);return{id:s,clipPathId:`url(#${l})`}}drawOutline(t,e){const i=this.#w++,s=this.#Eo(),n=DrawLayer._svgFactory.createElement("defs");s.append(n);const a=DrawLayer._svgFactory.createElement("path");n.append(a);const r=`path_p${this.pageIndex}_${i}`;a.setAttribute("id",r);a.setAttribute("vector-effect","non-scaling-stroke");let o;if(e){const t=DrawLayer._svgFactory.createElement("mask");n.append(t);o=`mask_p${this.pageIndex}_${i}`;t.setAttribute("id",o);t.setAttribute("maskUnits","objectBoundingBox");const e=DrawLayer._svgFactory.createElement("rect");t.append(e);e.setAttribute("width","1");e.setAttribute("height","1");e.setAttribute("fill","white");const s=DrawLayer._svgFactory.createElement("use");t.append(s);s.setAttribute("href",`#${r}`);s.setAttribute("stroke","none");s.setAttribute("fill","black");s.setAttribute("fill-rule","nonzero");s.classList.add("mask")}const l=DrawLayer._svgFactory.createElement("use");s.append(l);l.setAttribute("href",`#${r}`);o&&l.setAttribute("mask",`url(#${o})`);const h=l.cloneNode();s.append(h);l.classList.add("mainOutline");h.classList.add("secondaryOutline");this.updateProperties(s,t);this.#yo.set(i,s);return i}finalizeDraw(t,e){this.#xo.delete(t);this.updateProperties(t,e)}updateProperties(t,e){if(!e)return;const{root:i,bbox:s,rootClass:n,path:a}=e,r="number"==typeof t?this.#yo.get(t):t;if(r){i&&this.#Co(r,i);s&&DrawLayer.#_o(r,s);if(n){const{classList:t}=r;for(const[e,i]of Object.entries(n))t.toggle(e,i)}if(a){const t=r.firstChild.firstChild;this.#Co(t,a)}}}updateParent(t,e){if(e===this)return;const i=this.#yo.get(t);if(i){e.#nn.append(i);this.#yo.delete(t);e.#yo.set(t,i)}}remove(t){this.#xo.delete(t);if(null!==this.#nn){this.#yo.get(t).remove();this.#yo.delete(t)}}destroy(){this.#nn=null;for(const t of this.#yo.values())t.remove();this.#yo.clear();this.#xo.clear()}}globalThis.pdfjsTestingUtils={HighlightOutliner};var Ut=__webpack_exports__.AbortException,Gt=__webpack_exports__.AnnotationEditorLayer,$t=__webpack_exports__.AnnotationEditorParamsType,Vt=__webpack_exports__.AnnotationEditorType,jt=__webpack_exports__.AnnotationEditorUIManager,Wt=__webpack_exports__.AnnotationLayer,qt=__webpack_exports__.AnnotationMode,Xt=__webpack_exports__.ColorPicker,Kt=__webpack_exports__.DOMSVGFactory,Yt=__webpack_exports__.DrawLayer,Qt=__webpack_exports__.FeatureTest,Jt=__webpack_exports__.GlobalWorkerOptions,Zt=__webpack_exports__.ImageKind,te=__webpack_exports__.InvalidPDFException,ee=__webpack_exports__.MissingPDFException,ie=__webpack_exports__.OPS,se=__webpack_exports__.OutputScale,ne=__webpack_exports__.PDFDataRangeTransport,ae=__webpack_exports__.PDFDateString,re=__webpack_exports__.PDFWorker,oe=__webpack_exports__.PasswordResponses,le=__webpack_exports__.PermissionFlag,he=__webpack_exports__.PixelsPerInch,de=__webpack_exports__.RenderingCancelledException,ce=__webpack_exports__.TextLayer,ue=__webpack_exports__.TouchManager,pe=__webpack_exports__.UnexpectedResponseException,ge=__webpack_exports__.Util,me=__webpack_exports__.VerbosityLevel,fe=__webpack_exports__.XfaLayer,be=__webpack_exports__.build,Ae=__webpack_exports__.createValidAbsoluteUrl,we=__webpack_exports__.fetchData,ve=__webpack_exports__.getDocument,ye=__webpack_exports__.getFilenameFromUrl,xe=__webpack_exports__.getPdfFilenameFromUrl,_e=__webpack_exports__.getXfaPageViewport,Ee=__webpack_exports__.isDataScheme,Se=__webpack_exports__.isPdfFile,Ce=__webpack_exports__.noContextMenu,Te=__webpack_exports__.normalizeUnicode,Me=__webpack_exports__.setLayerDimensions,Pe=__webpack_exports__.shadow,De=__webpack_exports__.stopEvent,ke=__webpack_exports__.version;export{Ut as AbortException,Gt as AnnotationEditorLayer,$t as AnnotationEditorParamsType,Vt as AnnotationEditorType,jt as AnnotationEditorUIManager,Wt as AnnotationLayer,qt as AnnotationMode,Xt as ColorPicker,Kt as DOMSVGFactory,Yt as DrawLayer,Qt as FeatureTest,Jt as GlobalWorkerOptions,Zt as ImageKind,te as InvalidPDFException,ee as MissingPDFException,ie as OPS,se as OutputScale,ne as PDFDataRangeTransport,ae as PDFDateString,re as PDFWorker,oe as PasswordResponses,le as PermissionFlag,he as PixelsPerInch,de as RenderingCancelledException,ce as TextLayer,ue as TouchManager,pe as UnexpectedResponseException,ge as Util,me as VerbosityLevel,fe as XfaLayer,be as build,Ae as createValidAbsoluteUrl,we as fetchData,ve as getDocument,ye as getFilenameFromUrl,xe as getPdfFilenameFromUrl,_e as getXfaPageViewport,Ee as isDataScheme,Se as isPdfFile,Ce as noContextMenu,Te as normalizeUnicode,Me as setLayerDimensions,Pe as shadow,De as stopEvent,ke as version}; \ No newline at end of file diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/build/pdf.worker.min.mjs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/build/pdf.worker.min.mjs deleted file mode 100644 index ee4038504a6..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/build/pdf.worker.min.mjs +++ /dev/null @@ -1,21 +0,0 @@ -/** - * @licstart The following is the entire license notice for the - * JavaScript code in this page - * - * Copyright 2024 Mozilla Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * @licend The above is the entire license notice for the - * JavaScript code in this page - */var e={d:(t,i)=>{for(var a in i)e.o(i,a)&&!e.o(t,a)&&Object.defineProperty(t,a,{enumerable:!0,get:i[a]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},__webpack_exports__ = globalThis.pdfjsWorker = {};e.d(__webpack_exports__,{WorkerMessageHandler:()=>WorkerMessageHandler});const t=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),i=[1,0,0,1,0,0],a=[.001,0,0,.001,0,0],s=1.35,r=.35,n=.25925925925925924,g=1,o=2,c=4,C=8,h=16,l=64,Q=128,E=256,u="pdfjs_internal_editor_",d=3,f=9,p=13,m=15,y={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},w=0,D=4,b=1,F=2,S=3,k=1,R=2,N=3,G=4,M=5,U=6,x=7,L=8,H=9,J=10,Y=11,v=12,K=13,T=14,q=15,O=16,W=17,j=20,X="Group",Z="R",V=1,z=2,_=4,$=16,AA=32,eA=128,tA=512,iA=1,aA=2,sA=4096,rA=8192,nA=32768,gA=65536,oA=131072,IA=1048576,cA=2097152,CA=8388608,hA=16777216,lA=1,BA=2,QA=3,EA=4,uA=5,dA={E:"Mouse Enter",X:"Mouse Exit",D:"Mouse Down",U:"Mouse Up",Fo:"Focus",Bl:"Blur",PO:"PageOpen",PC:"PageClose",PV:"PageVisible",PI:"PageInvisible",K:"Keystroke",F:"Format",V:"Validate",C:"Calculate"},fA={WC:"WillClose",WS:"WillSave",DS:"DidSave",WP:"WillPrint",DP:"DidPrint"},pA={O:"PageOpen",C:"PageClose"},mA=1,yA=5,wA=1,DA=2,bA=3,FA=4,SA=5,kA=6,RA=7,NA=8,GA=9,MA=10,UA=11,xA=12,LA=13,HA=14,JA=15,YA=16,vA=17,KA=18,TA=19,qA=20,OA=21,PA=22,WA=23,jA=24,XA=25,ZA=26,VA=27,zA=28,_A=29,$A=30,Ae=31,ee=32,te=33,ie=34,ae=35,se=36,re=37,ne=38,ge=39,oe=40,Ie=41,ce=42,Ce=43,he=44,le=45,Be=46,Qe=47,Ee=48,ue=49,de=50,fe=51,pe=52,me=53,ye=54,we=55,De=56,be=57,Fe=58,Se=59,ke=60,Re=61,Ne=62,Ge=63,Me=64,Ue=65,xe=66,Le=67,He=68,Je=69,Ye=70,ve=71,Ke=72,Te=73,qe=74,Oe=75,Pe=76,We=77,je=80,Xe=81,Ze=83,Ve=84,ze=85,_e=86,$e=87,At=88,et=89,tt=90,it=91,at=92,st=93,rt=1,nt=2;let gt=mA;function getVerbosityLevel(){return gt}function info(e){gt>=yA&&console.log(`Info: ${e}`)}function warn(e){gt>=mA&&console.log(`Warning: ${e}`)}function unreachable(e){throw new Error(e)}function assert(e,t){e||unreachable(t)}function createValidAbsoluteUrl(e,t=null,i=null){if(!e)return null;try{if(i&&"string"==typeof e){if(i.addDefaultProtocol&&e.startsWith("www.")){const t=e.match(/\./g);t?.length>=2&&(e=`http://${e}`)}if(i.tryConvertEncoding)try{e=stringToUTF8String(e)}catch{}}const a=t?new URL(e,t):new URL(e);if(function _isValidProtocol(e){switch(e?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(a))return a}catch{}return null}function shadow(e,t,i,a=!1){Object.defineProperty(e,t,{value:i,enumerable:!a,configurable:!0,writable:!1});return i}const ot=function BaseExceptionClosure(){function BaseException(e,t){this.message=e;this.name=t}BaseException.prototype=new Error;BaseException.constructor=BaseException;return BaseException}();class PasswordException extends ot{constructor(e,t){super(e,"PasswordException");this.code=t}}class UnknownErrorException extends ot{constructor(e,t){super(e,"UnknownErrorException");this.details=t}}class InvalidPDFException extends ot{constructor(e){super(e,"InvalidPDFException")}}class MissingPDFException extends ot{constructor(e){super(e,"MissingPDFException")}}class UnexpectedResponseException extends ot{constructor(e,t){super(e,"UnexpectedResponseException");this.status=t}}class FormatError extends ot{constructor(e){super(e,"FormatError")}}class AbortException extends ot{constructor(e){super(e,"AbortException")}}function bytesToString(e){"object"==typeof e&&void 0!==e?.length||unreachable("Invalid argument for bytesToString");const t=e.length,i=8192;if(t>24&255,e>>16&255,e>>8&255,255&e)}function objectSize(e){return Object.keys(e).length}class FeatureTest{static get isLittleEndian(){return shadow(this,"isLittleEndian",function isLittleEndian(){const e=new Uint8Array(4);e[0]=1;return 1===new Uint32Array(e.buffer,0,1)[0]}())}static get isEvalSupported(){return shadow(this,"isEvalSupported",function isEvalSupported(){try{new Function("");return!0}catch{return!1}}())}static get isOffscreenCanvasSupported(){return shadow(this,"isOffscreenCanvasSupported","undefined"!=typeof OffscreenCanvas)}static get isImageDecoderSupported(){return shadow(this,"isImageDecoderSupported","undefined"!=typeof ImageDecoder)}static get platform(){return"undefined"!=typeof navigator&&"string"==typeof navigator?.platform?shadow(this,"platform",{isMac:navigator.platform.includes("Mac"),isWindows:navigator.platform.includes("Win"),isFirefox:"string"==typeof navigator?.userAgent&&navigator.userAgent.includes("Firefox")}):shadow(this,"platform",{isMac:!1,isWindows:!1,isFirefox:!1})}static get isCSSRoundSupported(){return shadow(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}const It=Array.from(Array(256).keys(),(e=>e.toString(16).padStart(2,"0")));class Util{static makeHexColor(e,t,i){return`#${It[e]}${It[t]}${It[i]}`}static scaleMinMax(e,t){let i;if(e[0]){if(e[0]<0){i=t[0];t[0]=t[2];t[2]=i}t[0]*=e[0];t[2]*=e[0];if(e[3]<0){i=t[1];t[1]=t[3];t[3]=i}t[1]*=e[3];t[3]*=e[3]}else{i=t[0];t[0]=t[1];t[1]=i;i=t[2];t[2]=t[3];t[3]=i;if(e[1]<0){i=t[1];t[1]=t[3];t[3]=i}t[1]*=e[1];t[3]*=e[1];if(e[2]<0){i=t[0];t[0]=t[2];t[2]=i}t[0]*=e[2];t[2]*=e[2]}t[0]+=e[4];t[1]+=e[5];t[2]+=e[4];t[3]+=e[5]}static transform(e,t){return[e[0]*t[0]+e[2]*t[1],e[1]*t[0]+e[3]*t[1],e[0]*t[2]+e[2]*t[3],e[1]*t[2]+e[3]*t[3],e[0]*t[4]+e[2]*t[5]+e[4],e[1]*t[4]+e[3]*t[5]+e[5]]}static applyTransform(e,t){return[e[0]*t[0]+e[1]*t[2]+t[4],e[0]*t[1]+e[1]*t[3]+t[5]]}static applyInverseTransform(e,t){const i=t[0]*t[3]-t[1]*t[2];return[(e[0]*t[3]-e[1]*t[2]+t[2]*t[5]-t[4]*t[3])/i,(-e[0]*t[1]+e[1]*t[0]+t[4]*t[1]-t[5]*t[0])/i]}static getAxialAlignedBoundingBox(e,t){const i=this.applyTransform(e,t),a=this.applyTransform(e.slice(2,4),t),s=this.applyTransform([e[0],e[3]],t),r=this.applyTransform([e[2],e[1]],t);return[Math.min(i[0],a[0],s[0],r[0]),Math.min(i[1],a[1],s[1],r[1]),Math.max(i[0],a[0],s[0],r[0]),Math.max(i[1],a[1],s[1],r[1])]}static inverseTransform(e){const t=e[0]*e[3]-e[1]*e[2];return[e[3]/t,-e[1]/t,-e[2]/t,e[0]/t,(e[2]*e[5]-e[4]*e[3])/t,(e[4]*e[1]-e[5]*e[0])/t]}static singularValueDecompose2dScale(e){const t=[e[0],e[2],e[1],e[3]],i=e[0]*t[0]+e[1]*t[2],a=e[0]*t[1]+e[1]*t[3],s=e[2]*t[0]+e[3]*t[2],r=e[2]*t[1]+e[3]*t[3],n=(i+r)/2,g=Math.sqrt((i+r)**2-4*(i*r-s*a))/2,o=n+g||1,c=n-g||1;return[Math.sqrt(o),Math.sqrt(c)]}static normalizeRect(e){const t=e.slice(0);if(e[0]>e[2]){t[0]=e[2];t[2]=e[0]}if(e[1]>e[3]){t[1]=e[3];t[3]=e[1]}return t}static intersect(e,t){const i=Math.max(Math.min(e[0],e[2]),Math.min(t[0],t[2])),a=Math.min(Math.max(e[0],e[2]),Math.max(t[0],t[2]));if(i>a)return null;const s=Math.max(Math.min(e[1],e[3]),Math.min(t[1],t[3])),r=Math.min(Math.max(e[1],e[3]),Math.max(t[1],t[3]));return s>r?null:[i,s,a,r]}static#A(e,t,i,a,s,r,n,g,o,c){if(o<=0||o>=1)return;const C=1-o,h=o*o,l=h*o,Q=C*(C*(C*e+3*o*t)+3*h*i)+l*a,E=C*(C*(C*s+3*o*r)+3*h*n)+l*g;c[0]=Math.min(c[0],Q);c[1]=Math.min(c[1],E);c[2]=Math.max(c[2],Q);c[3]=Math.max(c[3],E)}static#e(e,t,i,a,s,r,n,g,o,c,C,h){if(Math.abs(o)<1e-12){Math.abs(c)>=1e-12&&this.#A(e,t,i,a,s,r,n,g,-C/c,h);return}const l=c**2-4*C*o;if(l<0)return;const Q=Math.sqrt(l),E=2*o;this.#A(e,t,i,a,s,r,n,g,(-c+Q)/E,h);this.#A(e,t,i,a,s,r,n,g,(-c-Q)/E,h)}static bezierBoundingBox(e,t,i,a,s,r,n,g,o){if(o){o[0]=Math.min(o[0],e,n);o[1]=Math.min(o[1],t,g);o[2]=Math.max(o[2],e,n);o[3]=Math.max(o[3],t,g)}else o=[Math.min(e,n),Math.min(t,g),Math.max(e,n),Math.max(t,g)];this.#e(e,i,s,n,t,a,r,g,3*(3*(i-s)-e+n),6*(e-2*i+s),3*(i-e),o);this.#e(e,i,s,n,t,a,r,g,3*(3*(a-r)-t+g),6*(t-2*a+r),3*(a-t),o);return o}}const ct=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,728,711,710,729,733,731,730,732,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8226,8224,8225,8230,8212,8211,402,8260,8249,8250,8722,8240,8222,8220,8221,8216,8217,8218,8482,64257,64258,321,338,352,376,381,305,322,339,353,382,0,8364];function stringToPDFString(e){if(e[0]>="ï"){let t;if("þ"===e[0]&&"ÿ"===e[1]){t="utf-16be";e.length%2==1&&(e=e.slice(0,-1))}else if("ÿ"===e[0]&&"þ"===e[1]){t="utf-16le";e.length%2==1&&(e=e.slice(0,-1))}else"ï"===e[0]&&"»"===e[1]&&"¿"===e[2]&&(t="utf-8");if(t)try{const i=new TextDecoder(t,{fatal:!0}),a=stringToBytes(e),s=i.decode(a);return s.includes("")?s.replaceAll(/\x1b[^\x1b]*(?:\x1b|$)/g,""):s}catch(e){warn(`stringToPDFString: "${e}".`)}}const t=[];for(let i=0,a=e.length;iIt[e])).join("")}"function"!=typeof Promise.try&&(Promise.try=function(e,...t){return new Promise((i=>{i(e(...t))}))});const lt=Symbol("CIRCULAR_REF"),Bt=Symbol("EOF");let Qt=Object.create(null),Et=Object.create(null),ut=Object.create(null);class Name{constructor(e){this.name=e}static get(e){return Et[e]||=new Name(e)}}class Cmd{constructor(e){this.cmd=e}static get(e){return Qt[e]||=new Cmd(e)}}const dt=function nonSerializableClosure(){return dt};class Dict{constructor(e=null){this._map=new Map;this.xref=e;this.objId=null;this.suppressEncryption=!1;this.__nonSerializable__=dt}assignXref(e){this.xref=e}get size(){return this._map.size}get(e,t,i){let a=this._map.get(e);if(void 0===a&&void 0!==t){a=this._map.get(t);void 0===a&&void 0!==i&&(a=this._map.get(i))}return a instanceof Ref&&this.xref?this.xref.fetch(a,this.suppressEncryption):a}async getAsync(e,t,i){let a=this._map.get(e);if(void 0===a&&void 0!==t){a=this._map.get(t);void 0===a&&void 0!==i&&(a=this._map.get(i))}return a instanceof Ref&&this.xref?this.xref.fetchAsync(a,this.suppressEncryption):a}getArray(e,t,i){let a=this._map.get(e);if(void 0===a&&void 0!==t){a=this._map.get(t);void 0===a&&void 0!==i&&(a=this._map.get(i))}a instanceof Ref&&this.xref&&(a=this.xref.fetch(a,this.suppressEncryption));if(Array.isArray(a)){a=a.slice();for(let e=0,t=a.length;e{unreachable("Should not call `set` on the empty dictionary.")};return shadow(this,"empty",e)}static merge({xref:e,dictArray:t,mergeSubDicts:i=!1}){const a=new Dict(e),s=new Map;for(const e of t)if(e instanceof Dict)for(const[t,a]of e._map){let e=s.get(t);if(void 0===e){e=[];s.set(t,e)}else if(!(i&&a instanceof Dict))continue;e.push(a)}for(const[t,i]of s){if(1===i.length||!(i[0]instanceof Dict)){a._map.set(t,i[0]);continue}const s=new Dict(e);for(const e of i)for(const[t,i]of e._map)s._map.has(t)||s._map.set(t,i);s.size>0&&a._map.set(t,s)}s.clear();return a.size>0?a:Dict.empty}clone(){const e=new Dict(this.xref);for(const t of this.getKeys())e.set(t,this.getRaw(t));return e}delete(e){delete this._map[e]}}class Ref{constructor(e,t){this.num=e;this.gen=t}toString(){return 0===this.gen?`${this.num}R`:`${this.num}R${this.gen}`}static fromString(e){const t=ut[e];if(t)return t;const i=/^(\d+)R(\d*)$/.exec(e);return i&&"0"!==i[1]?ut[e]=new Ref(parseInt(i[1]),i[2]?parseInt(i[2]):0):null}static get(e,t){const i=0===t?`${e}R`:`${e}R${t}`;return ut[i]||=new Ref(e,t)}}class RefSet{constructor(e=null){this._set=new Set(e?._set)}has(e){return this._set.has(e.toString())}put(e){this._set.add(e.toString())}remove(e){this._set.delete(e.toString())}[Symbol.iterator](){return this._set.values()}clear(){this._set.clear()}}class RefSetCache{constructor(){this._map=new Map}get size(){return this._map.size}get(e){return this._map.get(e.toString())}has(e){return this._map.has(e.toString())}put(e,t){this._map.set(e.toString(),t)}putAlias(e,t){this._map.set(e.toString(),this.get(t))}[Symbol.iterator](){return this._map.values()}clear(){this._map.clear()}*values(){yield*this._map.values()}*items(){for(const[e,t]of this._map)yield[Ref.fromString(e),t]}}function isName(e,t){return e instanceof Name&&(void 0===t||e.name===t)}function isCmd(e,t){return e instanceof Cmd&&(void 0===t||e.cmd===t)}function isDict(e,t){return e instanceof Dict&&(void 0===t||isName(e.get("Type"),t))}function isRefsEqual(e,t){return e.num===t.num&&e.gen===t.gen}class BaseStream{get length(){unreachable("Abstract getter `length` accessed")}get isEmpty(){unreachable("Abstract getter `isEmpty` accessed")}get isDataLoaded(){return shadow(this,"isDataLoaded",!0)}getByte(){unreachable("Abstract method `getByte` called")}getBytes(e){unreachable("Abstract method `getBytes` called")}async getImageData(e,t){return this.getBytes(e,t)}async asyncGetBytes(){unreachable("Abstract method `asyncGetBytes` called")}get isAsync(){return!1}get canAsyncDecodeImageFromBuffer(){return!1}async getTransferableImage(){return null}peekByte(){const e=this.getByte();-1!==e&&this.pos--;return e}peekBytes(e){const t=this.getBytes(e);this.pos-=t.length;return t}getUint16(){const e=this.getByte(),t=this.getByte();return-1===e||-1===t?-1:(e<<8)+t}getInt32(){return(this.getByte()<<24)+(this.getByte()<<16)+(this.getByte()<<8)+this.getByte()}getByteRange(e,t){unreachable("Abstract method `getByteRange` called")}getString(e){return bytesToString(this.getBytes(e))}skip(e){this.pos+=e||1}reset(){unreachable("Abstract method `reset` called")}moveStart(){unreachable("Abstract method `moveStart` called")}makeSubStream(e,t,i=null){unreachable("Abstract method `makeSubStream` called")}getBaseStreams(){return null}}const ft=/^[1-9]\.\d$/,pt=2**31-1;function getLookupTableFactory(e){let t;return function(){if(e){t=Object.create(null);e(t);e=null}return t}}class MissingDataException extends ot{constructor(e,t){super(`Missing data [${e}, ${t})`,"MissingDataException");this.begin=e;this.end=t}}class ParserEOFException extends ot{constructor(e){super(e,"ParserEOFException")}}class XRefEntryException extends ot{constructor(e){super(e,"XRefEntryException")}}class XRefParseException extends ot{constructor(e){super(e,"XRefParseException")}}function arrayBuffersToBytes(e){const t=e.length;if(0===t)return new Uint8Array(0);if(1===t)return new Uint8Array(e[0]);let i=0;for(let a=0;a0,"The number should be a positive integer.");const i="M".repeat(e/1e3|0)+mt[e%1e3/100|0]+mt[10+(e%100/10|0)]+mt[20+e%10];return t?i.toLowerCase():i}function log2(e){return e>0?Math.ceil(Math.log2(e)):0}function readInt8(e,t){return e[t]<<24>>24}function readUint16(e,t){return e[t]<<8|e[t+1]}function readUint32(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}function isWhiteSpace(e){return 32===e||9===e||13===e||10===e}function isNumberArray(e,t){return Array.isArray(e)?(null===t||e.length===t)&&e.every((e=>"number"==typeof e)):ArrayBuffer.isView(e)&&(0===e.length||"number"==typeof e[0])&&(null===t||e.length===t)}function lookupMatrix(e,t){return isNumberArray(e,6)?e:t}function lookupRect(e,t){return isNumberArray(e,4)?e:t}function lookupNormalRect(e,t){return isNumberArray(e,4)?Util.normalizeRect(e):t}function parseXFAPath(e){const t=/(.+)\[(\d+)\]$/;return e.split(".").map((e=>{const i=e.match(t);return i?{name:i[1],pos:parseInt(i[2],10)}:{name:e,pos:0}}))}function escapePDFName(e){const t=[];let i=0;for(let a=0,s=e.length;a126||35===s||40===s||41===s||60===s||62===s||91===s||93===s||123===s||125===s||47===s||37===s){i"\n"===e?"\\n":"\r"===e?"\\r":`\\${e}`))}function _collectJS(e,t,i,a){if(!e)return;let s=null;if(e instanceof Ref){if(a.has(e))return;s=e;a.put(s);e=t.fetch(e)}if(Array.isArray(e))for(const s of e)_collectJS(s,t,i,a);else if(e instanceof Dict){if(isName(e.get("S"),"JavaScript")){const t=e.get("JS");let a;t instanceof BaseStream?a=t.getString():"string"==typeof t&&(a=t);a&&=stringToPDFString(a).replaceAll("\0","");a&&i.push(a)}_collectJS(e.getRaw("Next"),t,i,a)}s&&a.remove(s)}function collectActions(e,t,i){const a=Object.create(null),s=getInheritableProperty({dict:t,key:"AA",stopWhenFound:!1});if(s)for(let t=s.length-1;t>=0;t--){const r=s[t];if(r instanceof Dict)for(const t of r.getKeys()){const s=i[t];if(!s)continue;const n=[];_collectJS(r.getRaw(t),e,n,new RefSet);n.length>0&&(a[s]=n)}}if(t.has("A")){const i=[];_collectJS(t.get("A"),e,i,new RefSet);i.length>0&&(a.Action=i)}return objectSize(a)>0?a:null}const yt={60:"<",62:">",38:"&",34:""",39:"'"};function*codePointIter(e){for(let t=0,i=e.length;t55295&&(i<57344||i>65533)&&t++;yield i}}function encodeToXmlString(e){const t=[];let i=0;for(let a=0,s=e.length;a55295&&(s<57344||s>65533)&&a++;i=a+1}}if(0===t.length)return e;i: ${e}.`);return!1}return!0}function validateCSSFont(e){const t=new Set(["100","200","300","400","500","600","700","800","900","1000","normal","bold","bolder","lighter"]),{fontFamily:i,fontWeight:a,italicAngle:s}=e;if(!validateFontName(i,!0))return!1;const r=a?a.toString():"";e.fontWeight=t.has(r)?r:"400";const n=parseFloat(s);e.italicAngle=isNaN(n)||n<-90||n>90?"14":s.toString();return!0}function recoverJsURL(e){const t=new RegExp("^\\s*("+["app.launchURL","window.open","xfa.host.gotoURL"].join("|").replaceAll(".","\\.")+")\\((?:'|\")([^'\"]*)(?:'|\")(?:,\\s*(\\w+)\\)|\\))","i").exec(e);return t?.[2]?{url:t[2],newWindow:"app.launchURL"===t[1]&&"true"===t[3]}:null}function numberToString(e){if(Number.isInteger(e))return e.toString();const t=Math.round(100*e);return t%100==0?(t/100).toString():t%10==0?e.toFixed(1):e.toFixed(2)}function getNewAnnotationsMap(e){if(!e)return null;const t=new Map;for(const[i,a]of e){if(!i.startsWith(u))continue;let e=t.get(a.pageIndex);if(!e){e=[];t.set(a.pageIndex,e)}e.push(a)}return t.size>0?t:null}function stringToAsciiOrUTF16BE(e){return function isAscii(e){return/^[\x00-\x7F]*$/.test(e)}(e)?e:stringToUTF16String(e,!0)}function stringToUTF16HexString(e){const t=[];for(let i=0,a=e.length;i>8&255],It[255&a])}return t.join("")}function stringToUTF16String(e,t=!1){const i=[];t&&i.push("þÿ");for(let t=0,a=e.length;t>8&255),String.fromCharCode(255&a))}return i.join("")}function getRotationMatrix(e,t,i){switch(e){case 90:return[0,1,-1,0,t,0];case 180:return[-1,0,0,-1,t,i];case 270:return[0,-1,1,0,0,i];default:throw new Error("Invalid rotation")}}function getSizeInBytes(e){return Math.ceil(Math.ceil(Math.log2(1+e))/8)}class Stream extends BaseStream{constructor(e,t,i,a){super();this.bytes=e instanceof Uint8Array?e:new Uint8Array(e);this.start=t||0;this.pos=this.start;this.end=t+i||this.bytes.length;this.dict=a}get length(){return this.end-this.start}get isEmpty(){return 0===this.length}getByte(){return this.pos>=this.end?-1:this.bytes[this.pos++]}getBytes(e){const t=this.bytes,i=this.pos,a=this.end;if(!e)return t.subarray(i,a);let s=i+e;s>a&&(s=a);this.pos=s;return t.subarray(i,s)}getByteRange(e,t){e<0&&(e=0);t>this.end&&(t=this.end);return this.bytes.subarray(e,t)}reset(){this.pos=this.start}moveStart(){this.start=this.pos}makeSubStream(e,t,i=null){return new Stream(this.bytes.buffer,e,t,i)}}class StringStream extends Stream{constructor(e){super(stringToBytes(e))}}class NullStream extends Stream{constructor(){super(new Uint8Array(0))}}class ChunkedStream extends Stream{constructor(e,t,i){super(new Uint8Array(e),0,e,null);this.chunkSize=t;this._loadedChunks=new Set;this.numChunks=Math.ceil(e/t);this.manager=i;this.progressiveDataLength=0;this.lastSuccessfulEnsureByteChunk=-1}getMissingChunks(){const e=[];for(let t=0,i=this.numChunks;t=this.end?this.numChunks:Math.floor(t/this.chunkSize);for(let e=i;ethis.numChunks)&&t!==this.lastSuccessfulEnsureByteChunk){if(!this._loadedChunks.has(t))throw new MissingDataException(e,e+1);this.lastSuccessfulEnsureByteChunk=t}}ensureRange(e,t){if(e>=t)return;if(t<=this.progressiveDataLength)return;const i=Math.floor(e/this.chunkSize);if(i>this.numChunks)return;const a=Math.min(Math.floor((t-1)/this.chunkSize)+1,this.numChunks);for(let s=i;s=this.end)return-1;e>=this.progressiveDataLength&&this.ensureByte(e);return this.bytes[this.pos++]}getBytes(e){const t=this.bytes,i=this.pos,a=this.end;if(!e){a>this.progressiveDataLength&&this.ensureRange(i,a);return t.subarray(i,a)}let s=i+e;s>a&&(s=a);s>this.progressiveDataLength&&this.ensureRange(i,s);this.pos=s;return t.subarray(i,s)}getByteRange(e,t){e<0&&(e=0);t>this.end&&(t=this.end);t>this.progressiveDataLength&&this.ensureRange(e,t);return this.bytes.subarray(e,t)}makeSubStream(e,t,i=null){t?e+t>this.progressiveDataLength&&this.ensureRange(e,e+t):e>=this.progressiveDataLength&&this.ensureByte(e);function ChunkedStreamSubstream(){}ChunkedStreamSubstream.prototype=Object.create(this);ChunkedStreamSubstream.prototype.getMissingChunks=function(){const e=this.chunkSize,t=Math.floor(this.start/e),i=Math.floor((this.end-1)/e)+1,a=[];for(let e=t;e{const readChunk=({value:r,done:n})=>{try{if(n){const t=arrayBuffersToBytes(a);a=null;e(t);return}s+=r.byteLength;i.isStreamingSupported&&this.onProgress({loaded:s});a.push(r);i.read().then(readChunk,t)}catch(e){t(e)}};i.read().then(readChunk,t)})).then((t=>{this.aborted||this.onReceiveData({chunk:t,begin:e})}))}requestAllChunks(e=!1){if(!e){const e=this.stream.getMissingChunks();this._requestChunks(e)}return this._loadedStreamCapability.promise}_requestChunks(e){const t=this.currRequestId++,i=new Set;this._chunksNeededByRequest.set(t,i);for(const t of e)this.stream.hasChunk(t)||i.add(t);if(0===i.size)return Promise.resolve();const a=Promise.withResolvers();this._promisesByRequest.set(t,a);const s=[];for(const e of i){let i=this._requestsByChunk.get(e);if(!i){i=[];this._requestsByChunk.set(e,i);s.push(e)}i.push(t)}if(s.length>0){const e=this.groupChunks(s);for(const t of e){const e=t.beginChunk*this.chunkSize,i=Math.min(t.endChunk*this.chunkSize,this.length);this.sendRequest(e,i).catch(a.reject)}}return a.promise.catch((e=>{if(!this.aborted)throw e}))}getStream(){return this.stream}requestRange(e,t){t=Math.min(t,this.length);const i=this.getBeginChunk(e),a=this.getEndChunk(t),s=[];for(let e=i;e=0&&a+1!==r){t.push({beginChunk:i,endChunk:a+1});i=r}s+1===e.length&&t.push({beginChunk:i,endChunk:r+1});a=r}return t}onProgress(e){this.msgHandler.send("DocProgress",{loaded:this.stream.numChunksLoaded*this.chunkSize+e.loaded,total:this.length})}onReceiveData(e){const t=e.chunk,i=void 0===e.begin,a=i?this.progressiveDataLength:e.begin,s=a+t.byteLength,r=Math.floor(a/this.chunkSize),n=s0||g.push(i)}}}if(!this.disableAutoFetch&&0===this._requestsByChunk.size){let e;if(1===this.stream.numChunksLoaded){const t=this.stream.numChunks-1;this.stream.hasChunk(t)||(e=t)}else e=this.stream.nextEmptyChunk(n);Number.isInteger(e)&&this._requestChunks([e])}for(const e of g){const t=this._promisesByRequest.get(e);this._promisesByRequest.delete(e);t.resolve()}this.msgHandler.send("DocProgress",{loaded:this.stream.numChunksLoaded*this.chunkSize,total:this.length})}onError(e){this._loadedStreamCapability.reject(e)}getBeginChunk(e){return Math.floor(e/this.chunkSize)}getEndChunk(e){return Math.floor((e-1)/this.chunkSize)+1}abort(e){this.aborted=!0;this.pdfNetworkStream?.cancelAllRequests(e);for(const t of this._promisesByRequest.values())t.reject(e)}}class ColorSpace{constructor(e,t){this.name=e;this.numComps=t}getRgb(e,t){const i=new Uint8ClampedArray(3);this.getRgbItem(e,t,i,0);return i}getRgbItem(e,t,i,a){unreachable("Should not call ColorSpace.getRgbItem")}getRgbBuffer(e,t,i,a,s,r,n){unreachable("Should not call ColorSpace.getRgbBuffer")}getOutputLength(e,t){unreachable("Should not call ColorSpace.getOutputLength")}isPassthrough(e){return!1}isDefaultDecode(e,t){return ColorSpace.isDefaultDecode(e,this.numComps)}fillRgb(e,t,i,a,s,r,n,g,o){const c=t*i;let C=null;const h=1<h&&"DeviceGray"!==this.name&&"DeviceRGB"!==this.name){const t=n<=8?new Uint8Array(h):new Uint16Array(h);for(let e=0;e=.99554525?1:this.#B(0,1,1.055*e**(1/2.4)-.055)}#B(e,t,i){return Math.max(e,Math.min(t,i))}#Q(e){return e<0?-this.#Q(-e):e>8?((e+16)/116)**3:e*CalRGBCS.#I}#E(e,t,i){if(0===e[0]&&0===e[1]&&0===e[2]){i[0]=t[0];i[1]=t[1];i[2]=t[2];return}const a=this.#Q(0),s=(1-a)/(1-this.#Q(e[0])),r=1-s,n=(1-a)/(1-this.#Q(e[1])),g=1-n,o=(1-a)/(1-this.#Q(e[2])),c=1-o;i[0]=t[0]*s+r;i[1]=t[1]*n+g;i[2]=t[2]*o+c}#u(e,t,i){if(1===e[0]&&1===e[2]){i[0]=t[0];i[1]=t[1];i[2]=t[2];return}const a=i;this.#c(CalRGBCS.#i,t,a);const s=CalRGBCS.#n;this.#C(e,a,s);this.#c(CalRGBCS.#a,s,i)}#d(e,t,i){const a=i;this.#c(CalRGBCS.#i,t,a);const s=CalRGBCS.#n;this.#h(e,a,s);this.#c(CalRGBCS.#a,s,i)}#t(e,t,i,a,s){const r=this.#B(0,1,e[t]*s),n=this.#B(0,1,e[t+1]*s),g=this.#B(0,1,e[t+2]*s),o=1===r?1:r**this.GR,c=1===n?1:n**this.GG,C=1===g?1:g**this.GB,h=this.MXA*o+this.MXB*c+this.MXC*C,l=this.MYA*o+this.MYB*c+this.MYC*C,Q=this.MZA*o+this.MZB*c+this.MZC*C,E=CalRGBCS.#g;E[0]=h;E[1]=l;E[2]=Q;const u=CalRGBCS.#o;this.#u(this.whitePoint,E,u);const d=CalRGBCS.#g;this.#E(this.blackPoint,u,d);const f=CalRGBCS.#o;this.#d(CalRGBCS.#r,d,f);const p=CalRGBCS.#g;this.#c(CalRGBCS.#s,f,p);i[a]=255*this.#l(p[0]);i[a+1]=255*this.#l(p[1]);i[a+2]=255*this.#l(p[2])}getRgbItem(e,t,i,a){this.#t(e,t,i,a,1)}getRgbBuffer(e,t,i,a,s,r,n){const g=1/((1<this.amax||this.bmin>this.bmax){info("Invalid Range, falling back to defaults");this.amin=-100;this.amax=100;this.bmin=-100;this.bmax=100}}#f(e){return e>=6/29?e**3:108/841*(e-4/29)}#p(e,t,i,a){return i+e*(a-i)/t}#t(e,t,i,a,s){let r=e[t],n=e[t+1],g=e[t+2];if(!1!==i){r=this.#p(r,i,0,100);n=this.#p(n,i,this.amin,this.amax);g=this.#p(g,i,this.bmin,this.bmax)}n>this.amax?n=this.amax:nthis.bmax?g=this.bmax:g>>0}function hexToStr(e,t){return 1===t?String.fromCharCode(e[0],e[1]):3===t?String.fromCharCode(e[0],e[1],e[2],e[3]):String.fromCharCode(...e.subarray(0,t+1))}function addHex(e,t,i){let a=0;for(let s=i;s>=0;s--){a+=e[s]+t[s];e[s]=255&a;a>>=8}}function incHex(e,t){let i=1;for(let a=t;a>=0&&i>0;a--){i+=e[a];e[a]=255&i;i>>=8}}const wt=16;class BinaryCMapStream{constructor(e){this.buffer=e;this.pos=0;this.end=e.length;this.tmpBuf=new Uint8Array(19)}readByte(){return this.pos>=this.end?-1:this.buffer[this.pos++]}readNumber(){let e,t=0;do{const i=this.readByte();if(i<0)throw new FormatError("unexpected EOF in bcmap");e=!(128&i);t=t<<7|127&i}while(!e);return t}readSigned(){const e=this.readNumber();return 1&e?~(e>>>1):e>>>1}readHex(e,t){e.set(this.buffer.subarray(this.pos,this.pos+t+1));this.pos+=t+1}readHexNumber(e,t){let i;const a=this.tmpBuf;let s=0;do{const e=this.readByte();if(e<0)throw new FormatError("unexpected EOF in bcmap");i=!(128&e);a[s++]=127&e}while(!i);let r=t,n=0,g=0;for(;r>=0;){for(;g<8&&a.length>0;){n|=a[--s]<>=8;g-=8}}readHexSigned(e,t){this.readHexNumber(e,t);const i=1&e[t]?255:0;let a=0;for(let s=0;s<=t;s++){a=(1&a)<<8|e[s];e[s]=a>>1^i}}readString(){const e=this.readNumber(),t=new Array(e);for(let i=0;i=0;){const e=l>>5;if(7===e){switch(31&l){case 0:a.readString();break;case 1:r=a.readString()}continue}const i=!!(16&l),s=15&l;if(s+1>wt)throw new Error("BinaryCMapReader.process: Invalid dataSize.");const Q=1,E=a.readNumber();switch(e){case 0:a.readHex(n,s);a.readHexNumber(g,s);addHex(g,n,s);t.addCodespaceRange(s+1,hexToInt(n,s),hexToInt(g,s));for(let e=1;es&&(a=s)}else{for(;!this.eof;)this.readBlock(t);a=this.bufferLength}this.pos=a;return this.buffer.subarray(i,a)}async getImageData(e,t=null){if(!this.canAsyncDecodeImageFromBuffer)return this.getBytes(e,t);const i=await this.stream.asyncGetBytes();return this.decodeImage(i,t)}reset(){this.pos=0}makeSubStream(e,t,i=null){if(void 0===t)for(;!this.eof;)this.readBlock();else{const i=e+t;for(;this.bufferLength<=i&&!this.eof;)this.readBlock()}return new Stream(this.buffer,e,t,i)}getBaseStreams(){return this.str?this.str.getBaseStreams():null}}class StreamsSequenceStream extends DecodeStream{constructor(e,t=null){e=e.filter((e=>e instanceof BaseStream));let i=0;for(const t of e)i+=t instanceof DecodeStream?t._rawMinBufferLength:t.length;super(i);this.streams=e;this._onError=t}readBlock(){const e=this.streams;if(0===e.length){this.eof=!0;return}const t=e.shift();let i;try{i=t.getBytes()}catch(e){if(this._onError){this._onError(e,t.dict?.objId);return}throw e}const a=this.bufferLength,s=a+i.length;this.ensureBuffer(s).set(i,a);this.bufferLength=s}getBaseStreams(){const e=[];for(const t of this.streams){const i=t.getBaseStreams();i&&e.push(...i)}return e.length>0?e:null}}class Ascii85Stream extends DecodeStream{constructor(e,t){t&&(t*=.8);super(t);this.str=e;this.dict=e.dict;this.input=new Uint8Array(5)}readBlock(){const e=this.str;let t=e.getByte();for(;isWhiteSpace(t);)t=e.getByte();if(-1===t||126===t){this.eof=!0;return}const i=this.bufferLength;let a,s;if(122===t){a=this.ensureBuffer(i+4);for(s=0;s<4;++s)a[i+s]=0;this.bufferLength+=4}else{const r=this.input;r[0]=t;for(s=1;s<5;++s){t=e.getByte();for(;isWhiteSpace(t);)t=e.getByte();r[s]=t;if(-1===t||126===t)break}a=this.ensureBuffer(i+s-1);this.bufferLength+=s-1;if(s<5){for(;s<5;++s)r[s]=117;this.eof=!0}let n=0;for(s=0;s<5;++s)n=85*n+(r[s]-33);for(s=3;s>=0;--s){a[i+s]=255&n;n>>=8}}}}class AsciiHexStream extends DecodeStream{constructor(e,t){t&&(t*=.5);super(t);this.str=e;this.dict=e.dict;this.firstDigit=-1}readBlock(){const e=this.str.getBytes(8e3);if(!e.length){this.eof=!0;return}const t=e.length+1>>1,i=this.ensureBuffer(this.bufferLength+t);let a=this.bufferLength,s=this.firstDigit;for(const t of e){let e;if(t>=48&&t<=57)e=15&t;else{if(!(t>=65&&t<=70||t>=97&&t<=102)){if(62===t){this.eof=!0;break}continue}e=9+(15&t)}if(s<0)s=e;else{i[a++]=s<<4|e;s=-1}}if(s>=0&&this.eof){i[a++]=s<<4;s=-1}this.firstDigit=s;this.bufferLength=a}}const bt=-1,Ft=[[-1,-1],[-1,-1],[7,8],[7,7],[6,6],[6,6],[6,5],[6,5],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2]],St=[[-1,-1],[12,-2],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[11,1792],[11,1792],[12,1984],[12,2048],[12,2112],[12,2176],[12,2240],[12,2304],[11,1856],[11,1856],[11,1920],[11,1920],[12,2368],[12,2432],[12,2496],[12,2560]],kt=[[-1,-1],[-1,-1],[-1,-1],[-1,-1],[8,29],[8,29],[8,30],[8,30],[8,45],[8,45],[8,46],[8,46],[7,22],[7,22],[7,22],[7,22],[7,23],[7,23],[7,23],[7,23],[8,47],[8,47],[8,48],[8,48],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[7,20],[7,20],[7,20],[7,20],[8,33],[8,33],[8,34],[8,34],[8,35],[8,35],[8,36],[8,36],[8,37],[8,37],[8,38],[8,38],[7,19],[7,19],[7,19],[7,19],[8,31],[8,31],[8,32],[8,32],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[8,53],[8,53],[8,54],[8,54],[7,26],[7,26],[7,26],[7,26],[8,39],[8,39],[8,40],[8,40],[8,41],[8,41],[8,42],[8,42],[8,43],[8,43],[8,44],[8,44],[7,21],[7,21],[7,21],[7,21],[7,28],[7,28],[7,28],[7,28],[8,61],[8,61],[8,62],[8,62],[8,63],[8,63],[8,0],[8,0],[8,320],[8,320],[8,384],[8,384],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[7,27],[7,27],[7,27],[7,27],[8,59],[8,59],[8,60],[8,60],[9,1472],[9,1536],[9,1600],[9,1728],[7,18],[7,18],[7,18],[7,18],[7,24],[7,24],[7,24],[7,24],[8,49],[8,49],[8,50],[8,50],[8,51],[8,51],[8,52],[8,52],[7,25],[7,25],[7,25],[7,25],[8,55],[8,55],[8,56],[8,56],[8,57],[8,57],[8,58],[8,58],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[8,448],[8,448],[8,512],[8,512],[9,704],[9,768],[8,640],[8,640],[8,576],[8,576],[9,832],[9,896],[9,960],[9,1024],[9,1088],[9,1152],[9,1216],[9,1280],[9,1344],[9,1408],[7,256],[7,256],[7,256],[7,256],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7]],Rt=[[-1,-1],[-1,-1],[12,-2],[12,-2],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[11,1792],[11,1792],[11,1792],[11,1792],[12,1984],[12,1984],[12,2048],[12,2048],[12,2112],[12,2112],[12,2176],[12,2176],[12,2240],[12,2240],[12,2304],[12,2304],[11,1856],[11,1856],[11,1856],[11,1856],[11,1920],[11,1920],[11,1920],[11,1920],[12,2368],[12,2368],[12,2432],[12,2432],[12,2496],[12,2496],[12,2560],[12,2560],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[12,52],[12,52],[13,640],[13,704],[13,768],[13,832],[12,55],[12,55],[12,56],[12,56],[13,1280],[13,1344],[13,1408],[13,1472],[12,59],[12,59],[12,60],[12,60],[13,1536],[13,1600],[11,24],[11,24],[11,24],[11,24],[11,25],[11,25],[11,25],[11,25],[13,1664],[13,1728],[12,320],[12,320],[12,384],[12,384],[12,448],[12,448],[13,512],[13,576],[12,53],[12,53],[12,54],[12,54],[13,896],[13,960],[13,1024],[13,1088],[13,1152],[13,1216],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64]],Nt=[[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[11,23],[11,23],[12,50],[12,51],[12,44],[12,45],[12,46],[12,47],[12,57],[12,58],[12,61],[12,256],[10,16],[10,16],[10,16],[10,16],[10,17],[10,17],[10,17],[10,17],[12,48],[12,49],[12,62],[12,63],[12,30],[12,31],[12,32],[12,33],[12,40],[12,41],[11,22],[11,22],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[12,128],[12,192],[12,26],[12,27],[12,28],[12,29],[11,19],[11,19],[11,20],[11,20],[12,34],[12,35],[12,36],[12,37],[12,38],[12,39],[11,21],[11,21],[12,42],[12,43],[10,0],[10,0],[10,0],[10,0],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12]],Gt=[[-1,-1],[-1,-1],[-1,-1],[-1,-1],[6,9],[6,8],[5,7],[5,7],[4,6],[4,6],[4,6],[4,6],[4,5],[4,5],[4,5],[4,5],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2]];class CCITTFaxDecoder{constructor(e,t={}){if("function"!=typeof e?.next)throw new Error('CCITTFaxDecoder - invalid "source" parameter.');this.source=e;this.eof=!1;this.encoding=t.K||0;this.eoline=t.EndOfLine||!1;this.byteAlign=t.EncodedByteAlign||!1;this.columns=t.Columns||1728;this.rows=t.Rows||0;this.eoblock=t.EndOfBlock??!0;this.black=t.BlackIs1||!1;this.codingLine=new Uint32Array(this.columns+1);this.refLine=new Uint32Array(this.columns+2);this.codingLine[0]=this.columns;this.codingPos=0;this.row=0;this.nextLine2D=this.encoding<0;this.inputBits=0;this.inputBuf=0;this.outputBits=0;this.rowsDone=!1;let i;for(;0===(i=this._lookBits(12));)this._eatBits(1);1===i&&this._eatBits(12);if(this.encoding>0){this.nextLine2D=!this._lookBits(1);this._eatBits(1)}}readNextChar(){if(this.eof)return-1;const e=this.refLine,t=this.codingLine,i=this.columns;let a,s,r,n,g;if(0===this.outputBits){this.rowsDone&&(this.eof=!0);if(this.eof)return-1;this.err=!1;let r,g,o;if(this.nextLine2D){for(n=0;t[n]=64);do{g+=o=this._getWhiteCode()}while(o>=64)}else{do{r+=o=this._getWhiteCode()}while(o>=64);do{g+=o=this._getBlackCode()}while(o>=64)}this._addPixels(t[this.codingPos]+r,s);t[this.codingPos]0?--a:++a;for(;e[a]<=t[this.codingPos]&&e[a]0?--a:++a;for(;e[a]<=t[this.codingPos]&&e[a]0?--a:++a;for(;e[a]<=t[this.codingPos]&&e[a]=64);else do{r+=o=this._getWhiteCode()}while(o>=64);this._addPixels(t[this.codingPos]+r,s);s^=1}}let c=!1;this.byteAlign&&(this.inputBits&=-8);if(this.eoblock||this.row!==this.rows-1){r=this._lookBits(12);if(this.eoline)for(;r!==bt&&1!==r;){this._eatBits(1);r=this._lookBits(12)}else for(;0===r;){this._eatBits(1);r=this._lookBits(12)}if(1===r){this._eatBits(12);c=!0}else r===bt&&(this.eof=!0)}else this.rowsDone=!0;if(!this.eof&&this.encoding>0&&!this.rowsDone){this.nextLine2D=!this._lookBits(1);this._eatBits(1)}if(this.eoblock&&c&&this.byteAlign){r=this._lookBits(12);if(1===r){this._eatBits(12);if(this.encoding>0){this._lookBits(1);this._eatBits(1)}if(this.encoding>=0)for(n=0;n<4;++n){r=this._lookBits(12);1!==r&&info("bad rtc code: "+r);this._eatBits(12);if(this.encoding>0){this._lookBits(1);this._eatBits(1)}}this.eof=!0}}else if(this.err&&this.eoline){for(;;){r=this._lookBits(13);if(r===bt){this.eof=!0;return-1}if(r>>1==1)break;this._eatBits(1)}this._eatBits(12);if(this.encoding>0){this._eatBits(1);this.nextLine2D=!(1&r)}}this.outputBits=t[0]>0?t[this.codingPos=0]:t[this.codingPos=1];this.row++}if(this.outputBits>=8){g=1&this.codingPos?0:255;this.outputBits-=8;if(0===this.outputBits&&t[this.codingPos]r){g<<=r;1&this.codingPos||(g|=255>>8-r);this.outputBits-=r;r=0}else{g<<=this.outputBits;1&this.codingPos||(g|=255>>8-this.outputBits);r-=this.outputBits;this.outputBits=0;if(t[this.codingPos]0){g<<=r;r=0}}}while(r)}this.black&&(g^=255);return g}_addPixels(e,t){const i=this.codingLine;let a=this.codingPos;if(e>i[a]){if(e>this.columns){info("row is wrong length");this.err=!0;e=this.columns}1&a^t&&++a;i[a]=e}this.codingPos=a}_addPixelsNeg(e,t){const i=this.codingLine;let a=this.codingPos;if(e>i[a]){if(e>this.columns){info("row is wrong length");this.err=!0;e=this.columns}1&a^t&&++a;i[a]=e}else if(e0&&e=s){const t=i[e-s];if(t[0]===a){this._eatBits(a);return[!0,t[1],!0]}}}return[!1,0,!1]}_getTwoDimCode(){let e,t=0;if(this.eoblock){t=this._lookBits(7);e=Ft[t];if(e?.[0]>0){this._eatBits(e[0]);return e[1]}}else{const e=this._findTableCode(1,7,Ft);if(e[0]&&e[2])return e[1]}info("Bad two dim code");return bt}_getWhiteCode(){let e,t=0;if(this.eoblock){t=this._lookBits(12);if(t===bt)return 1;e=t>>5?kt[t>>3]:St[t];if(e[0]>0){this._eatBits(e[0]);return e[1]}}else{let e=this._findTableCode(1,9,kt);if(e[0])return e[1];e=this._findTableCode(11,12,St);if(e[0])return e[1]}info("bad white code");this._eatBits(1);return 1}_getBlackCode(){let e,t;if(this.eoblock){e=this._lookBits(13);if(e===bt)return 1;t=e>>7?!(e>>9)&&e>>7?Nt[(e>>1)-64]:Gt[e>>7]:Rt[e];if(t[0]>0){this._eatBits(t[0]);return t[1]}}else{let e=this._findTableCode(2,6,Gt);if(e[0])return e[1];e=this._findTableCode(7,12,Nt,64);if(e[0])return e[1];e=this._findTableCode(10,13,Rt);if(e[0])return e[1]}info("bad black code");this._eatBits(1);return 1}_lookBits(e){let t;for(;this.inputBits>16-e;this.inputBuf=this.inputBuf<<8|t;this.inputBits+=8}return this.inputBuf>>this.inputBits-e&65535>>16-e}_eatBits(e){(this.inputBits-=e)<0&&(this.inputBits=0)}}class CCITTFaxStream extends DecodeStream{constructor(e,t,i){super(t);this.str=e;this.dict=e.dict;i instanceof Dict||(i=Dict.empty);const a={next:()=>e.getByte()};this.ccittFaxDecoder=new CCITTFaxDecoder(a,{K:i.get("K"),EndOfLine:i.get("EndOfLine"),EncodedByteAlign:i.get("EncodedByteAlign"),Columns:i.get("Columns"),Rows:i.get("Rows"),EndOfBlock:i.get("EndOfBlock"),BlackIs1:i.get("BlackIs1")})}readBlock(){for(;!this.eof;){const e=this.ccittFaxDecoder.readNextChar();if(-1===e){this.eof=!0;return}this.ensureBuffer(this.bufferLength+1);this.buffer[this.bufferLength++]=e}}}const Mt=new Int32Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ut=new Int32Array([3,4,5,6,7,8,9,10,65547,65549,65551,65553,131091,131095,131099,131103,196643,196651,196659,196667,262211,262227,262243,262259,327811,327843,327875,327907,258,258,258]),xt=new Int32Array([1,2,3,4,65541,65543,131081,131085,196625,196633,262177,262193,327745,327777,393345,393409,459009,459137,524801,525057,590849,591361,657409,658433,724993,727041,794625,798721,868353,876545]),Lt=[new Int32Array([459008,524368,524304,524568,459024,524400,524336,590016,459016,524384,524320,589984,524288,524416,524352,590048,459012,524376,524312,589968,459028,524408,524344,590032,459020,524392,524328,59e4,524296,524424,524360,590064,459010,524372,524308,524572,459026,524404,524340,590024,459018,524388,524324,589992,524292,524420,524356,590056,459014,524380,524316,589976,459030,524412,524348,590040,459022,524396,524332,590008,524300,524428,524364,590072,459009,524370,524306,524570,459025,524402,524338,590020,459017,524386,524322,589988,524290,524418,524354,590052,459013,524378,524314,589972,459029,524410,524346,590036,459021,524394,524330,590004,524298,524426,524362,590068,459011,524374,524310,524574,459027,524406,524342,590028,459019,524390,524326,589996,524294,524422,524358,590060,459015,524382,524318,589980,459031,524414,524350,590044,459023,524398,524334,590012,524302,524430,524366,590076,459008,524369,524305,524569,459024,524401,524337,590018,459016,524385,524321,589986,524289,524417,524353,590050,459012,524377,524313,589970,459028,524409,524345,590034,459020,524393,524329,590002,524297,524425,524361,590066,459010,524373,524309,524573,459026,524405,524341,590026,459018,524389,524325,589994,524293,524421,524357,590058,459014,524381,524317,589978,459030,524413,524349,590042,459022,524397,524333,590010,524301,524429,524365,590074,459009,524371,524307,524571,459025,524403,524339,590022,459017,524387,524323,589990,524291,524419,524355,590054,459013,524379,524315,589974,459029,524411,524347,590038,459021,524395,524331,590006,524299,524427,524363,590070,459011,524375,524311,524575,459027,524407,524343,590030,459019,524391,524327,589998,524295,524423,524359,590062,459015,524383,524319,589982,459031,524415,524351,590046,459023,524399,524335,590014,524303,524431,524367,590078,459008,524368,524304,524568,459024,524400,524336,590017,459016,524384,524320,589985,524288,524416,524352,590049,459012,524376,524312,589969,459028,524408,524344,590033,459020,524392,524328,590001,524296,524424,524360,590065,459010,524372,524308,524572,459026,524404,524340,590025,459018,524388,524324,589993,524292,524420,524356,590057,459014,524380,524316,589977,459030,524412,524348,590041,459022,524396,524332,590009,524300,524428,524364,590073,459009,524370,524306,524570,459025,524402,524338,590021,459017,524386,524322,589989,524290,524418,524354,590053,459013,524378,524314,589973,459029,524410,524346,590037,459021,524394,524330,590005,524298,524426,524362,590069,459011,524374,524310,524574,459027,524406,524342,590029,459019,524390,524326,589997,524294,524422,524358,590061,459015,524382,524318,589981,459031,524414,524350,590045,459023,524398,524334,590013,524302,524430,524366,590077,459008,524369,524305,524569,459024,524401,524337,590019,459016,524385,524321,589987,524289,524417,524353,590051,459012,524377,524313,589971,459028,524409,524345,590035,459020,524393,524329,590003,524297,524425,524361,590067,459010,524373,524309,524573,459026,524405,524341,590027,459018,524389,524325,589995,524293,524421,524357,590059,459014,524381,524317,589979,459030,524413,524349,590043,459022,524397,524333,590011,524301,524429,524365,590075,459009,524371,524307,524571,459025,524403,524339,590023,459017,524387,524323,589991,524291,524419,524355,590055,459013,524379,524315,589975,459029,524411,524347,590039,459021,524395,524331,590007,524299,524427,524363,590071,459011,524375,524311,524575,459027,524407,524343,590031,459019,524391,524327,589999,524295,524423,524359,590063,459015,524383,524319,589983,459031,524415,524351,590047,459023,524399,524335,590015,524303,524431,524367,590079]),9],Ht=[new Int32Array([327680,327696,327688,327704,327684,327700,327692,327708,327682,327698,327690,327706,327686,327702,327694,0,327681,327697,327689,327705,327685,327701,327693,327709,327683,327699,327691,327707,327687,327703,327695,0]),5];class FlateStream extends DecodeStream{constructor(e,t){super(t);this.str=e;this.dict=e.dict;const i=e.getByte(),a=e.getByte();if(-1===i||-1===a)throw new FormatError(`Invalid header in flate stream: ${i}, ${a}`);if(8!=(15&i))throw new FormatError(`Unknown compression method in flate stream: ${i}, ${a}`);if(((i<<8)+a)%31!=0)throw new FormatError(`Bad FCHECK in flate stream: ${i}, ${a}`);if(32&a)throw new FormatError(`FDICT bit set in flate stream: ${i}, ${a}`);this.codeSize=0;this.codeBuf=0}async getImageData(e,t){const i=await this.asyncGetBytes();return i?.subarray(0,e)||this.getBytes(e)}async asyncGetBytes(){this.str.reset();const e=this.str.getBytes();try{const{readable:t,writable:i}=new DecompressionStream("deflate"),a=i.getWriter();await a.ready;a.write(e).then((async()=>{await a.ready;await a.close()})).catch((()=>{}));const s=[];let r=0;for await(const e of t){s.push(e);r+=e.byteLength}const n=new Uint8Array(r);let g=0;for(const e of s){n.set(e,g);g+=e.byteLength}return n}catch{this.str=new Stream(e,2,e.length,this.str.dict);this.reset();return null}}get isAsync(){return!0}getBits(e){const t=this.str;let i,a=this.codeSize,s=this.codeBuf;for(;a>e;this.codeSize=a-=e;return i}getCode(e){const t=this.str,i=e[0],a=e[1];let s,r=this.codeSize,n=this.codeBuf;for(;r>16,c=65535&g;if(o<1||r>o;this.codeSize=r-o;return c}generateHuffmanTable(e){const t=e.length;let i,a=0;for(i=0;ia&&(a=e[i]);const s=1<>=1}for(i=e;i>=1;if(0===t){let t;if(-1===(t=a.getByte())){this.#m("Bad block header in flate stream");return}let i=t;if(-1===(t=a.getByte())){this.#m("Bad block header in flate stream");return}i|=t<<8;if(-1===(t=a.getByte())){this.#m("Bad block header in flate stream");return}let s=t;if(-1===(t=a.getByte())){this.#m("Bad block header in flate stream");return}s|=t<<8;if(s!==(65535&~i)&&(0!==i||0!==s))throw new FormatError("Bad uncompressed block length in flate stream");this.codeBuf=0;this.codeSize=0;const r=this.bufferLength,n=r+i;e=this.ensureBuffer(n);this.bufferLength=n;if(0===i)-1===a.peekByte()&&(this.eof=!0);else{const t=a.getBytes(i);e.set(t,r);t.length0;)C[g++]=Q}s=this.generateHuffmanTable(C.subarray(0,e));r=this.generateHuffmanTable(C.subarray(e,c))}}e=this.buffer;let n=e?e.length:0,g=this.bufferLength;for(;;){let t=this.getCode(s);if(t<256){if(g+1>=n){e=this.ensureBuffer(g+1);n=e.length}e[g++]=t;continue}if(256===t){this.bufferLength=g;return}t-=257;t=Ut[t];let a=t>>16;a>0&&(a=this.getBits(a));i=(65535&t)+a;t=this.getCode(r);t=xt[t];a=t>>16;a>0&&(a=this.getBits(a));const o=(65535&t)+a;if(g+i>=n){e=this.ensureBuffer(g+i);n=e.length}for(let t=0;t>9&127;this.clow=this.clow<<7&65535;this.ct-=7;this.a=32768}byteIn(){const e=this.data;let t=this.bp;if(255===e[t])if(e[t+1]>143){this.clow+=65280;this.ct=8}else{t++;this.clow+=e[t]<<9;this.ct=7;this.bp=t}else{t++;this.clow+=t65535){this.chigh+=this.clow>>16;this.clow&=65535}}readBit(e,t){let i=e[t]>>1,a=1&e[t];const s=Jt[i],r=s.qe;let n,g=this.a-r;if(this.chigh>15&1;this.clow=this.clow<<1&65535;this.ct--}while(!(32768&g));this.a=g;e[t]=i<<1|a;return n}}class Jbig2Error extends ot{constructor(e){super(e,"Jbig2Error")}}class ContextCache{getContexts(e){return e in this?this[e]:this[e]=new Int8Array(65536)}}class DecodingContext{constructor(e,t,i){this.data=e;this.start=t;this.end=i}get decoder(){return shadow(this,"decoder",new ArithmeticDecoder(this.data,this.start,this.end))}get contextCache(){return shadow(this,"contextCache",new ContextCache)}}function decodeInteger(e,t,i){const a=e.getContexts(t);let s=1;function readBits(e){let t=0;for(let r=0;r>>0}const r=readBits(1),n=readBits(1)?readBits(1)?readBits(1)?readBits(1)?readBits(1)?readBits(32)+4436:readBits(12)+340:readBits(8)+84:readBits(6)+20:readBits(4)+4:readBits(2);let g;0===r?g=n:n>0&&(g=-n);return g>=-2147483648&&g<=pt?g:null}function decodeIAID(e,t,i){const a=e.getContexts("IAID");let s=1;for(let e=0;e=F&&x=S){K=K<<1&d;for(u=0;u=0&&H=0){J=G[L][H];J&&(K|=J<=e?c<<=1:c=c<<1|w[g][o]}for(Q=0;Q=m||o<0||o>=p?c<<=1:c=c<<1|a[g][o]}const E=D.readBit(b,c);t[n]=E}}return w}function decodeTextRegion(e,t,i,a,s,r,n,g,o,c,C,h,l,Q,E,u,d,f,p){if(e&&t)throw new Jbig2Error("refinement with Huffman is not supported");const m=[];let y,w;for(y=0;y1&&(s=e?p.readBits(f):decodeInteger(b,"IAIT",D));const r=n*F+s,S=e?Q.symbolIDTable.decode(p):decodeIAID(b,D,o),k=t&&(e?p.readBit():decodeInteger(b,"IARI",D));let R=g[S],N=R[0].length,G=R.length;if(k){const e=decodeInteger(b,"IARDW",D),t=decodeInteger(b,"IARDH",D);N+=e;G+=t;R=decodeRefinement(N,G,E,R,(e>>1)+decodeInteger(b,"IARDX",D),(t>>1)+decodeInteger(b,"IARDY",D),!1,u,d)}let M=0;c?1&h?M=G-1:a+=G-1:h>1?a+=N-1:M=N-1;const U=r-(1&h?0:G-1),x=a-(2&h?N-1:0);let L,H,J;if(c)for(L=0;L>5&7;const o=[31&n];let c=t+6;if(7===n){g=536870911&readUint32(e,c-1);c+=3;let t=g+7>>3;o[0]=e[c++];for(;--t>0;)o.push(e[c++])}else if(5===n||6===n)throw new Jbig2Error("invalid referred-to flags");i.retainBits=o;let C=4;i.number<=256?C=1:i.number<=65536&&(C=2);const h=[];let l,Q;for(l=0;l>>24&255;r[3]=t.height>>16&255;r[4]=t.height>>8&255;r[5]=255&t.height;for(l=c,Q=e.length;l>2&3;e.huffmanDWSelector=t>>4&3;e.bitmapSizeSelector=t>>6&1;e.aggregationInstancesSelector=t>>7&1;e.bitmapCodingContextUsed=!!(256&t);e.bitmapCodingContextRetained=!!(512&t);e.template=t>>10&3;e.refinementTemplate=t>>12&1;c+=2;if(!e.huffman){o=0===e.template?4:1;n=[];for(g=0;g>2&3;C.stripSize=1<>4&3;C.transposed=!!(64&h);C.combinationOperator=h>>7&3;C.defaultPixelValue=h>>9&1;C.dsOffset=h<<17>>27;C.refinementTemplate=h>>15&1;if(C.huffman){const e=readUint16(a,c);c+=2;C.huffmanFS=3&e;C.huffmanDS=e>>2&3;C.huffmanDT=e>>4&3;C.huffmanRefinementDW=e>>6&3;C.huffmanRefinementDH=e>>8&3;C.huffmanRefinementDX=e>>10&3;C.huffmanRefinementDY=e>>12&3;C.huffmanRefinementSizeSelector=!!(16384&e)}if(C.refinement&&!C.refinementTemplate){n=[];for(g=0;g<2;g++){n.push({x:readInt8(a,c),y:readInt8(a,c+1)});c+=2}C.refinementAt=n}C.numberOfSymbolInstances=readUint32(a,c);c+=4;r=[C,i.referredTo,a,c,s];break;case 16:const l={},Q=a[c++];l.mmr=!!(1&Q);l.template=Q>>1&3;l.patternWidth=a[c++];l.patternHeight=a[c++];l.maxPatternIndex=readUint32(a,c);c+=4;r=[l,i.number,a,c,s];break;case 22:case 23:const E={};E.info=readRegionSegmentInformation(a,c);c+=Ot;const u=a[c++];E.mmr=!!(1&u);E.template=u>>1&3;E.enableSkip=!!(8&u);E.combinationOperator=u>>4&7;E.defaultPixelValue=u>>7&1;E.gridWidth=readUint32(a,c);c+=4;E.gridHeight=readUint32(a,c);c+=4;E.gridOffsetX=4294967295&readUint32(a,c);c+=4;E.gridOffsetY=4294967295&readUint32(a,c);c+=4;E.gridVectorX=readUint16(a,c);c+=2;E.gridVectorY=readUint16(a,c);c+=2;r=[E,i.referredTo,a,c,s];break;case 38:case 39:const d={};d.info=readRegionSegmentInformation(a,c);c+=Ot;const f=a[c++];d.mmr=!!(1&f);d.template=f>>1&3;d.prediction=!!(8&f);if(!d.mmr){o=0===d.template?4:1;n=[];for(g=0;g>2&1;p.combinationOperator=m>>3&3;p.requiresBuffer=!!(32&m);p.combinationOperatorOverride=!!(64&m);r=[p];break;case 49:case 50:case 51:case 62:break;case 53:r=[i.number,a,c,s];break;default:throw new Jbig2Error(`segment type ${i.typeName}(${i.type}) is not implemented`)}const C="on"+i.typeName;C in t&&t[C].apply(t,r)}function processSegments(e,t){for(let i=0,a=e.length;i>3,i=new Uint8ClampedArray(t*e.height);e.defaultPixelValue&&i.fill(255);this.buffer=i}drawBitmap(e,t){const i=this.currentPageInfo,a=e.width,s=e.height,r=i.width+7>>3,n=i.combinationOperatorOverride?e.combinationOperator:i.combinationOperator,g=this.buffer,o=128>>(7&e.x);let c,C,h,l,Q=e.y*r+(e.x>>3);switch(n){case 0:for(c=0;c>=1;if(!h){h=128;l++}}Q+=r}break;case 2:for(c=0;c>=1;if(!h){h=128;l++}}Q+=r}break;default:throw new Jbig2Error(`operator ${n} is not supported`)}}onImmediateGenericRegion(e,t,i,a){const s=e.info,r=new DecodingContext(t,i,a),n=decodeBitmap(e.mmr,s.width,s.height,e.template,e.prediction,null,e.at,r);this.drawBitmap(s,n)}onImmediateLosslessGenericRegion(){this.onImmediateGenericRegion(...arguments)}onSymbolDictionary(e,t,i,a,s,r){let n,g;if(e.huffman){n=function getSymbolDictionaryHuffmanTables(e,t,i){let a,s,r,n,g=0;switch(e.huffmanDHSelector){case 0:case 1:a=getStandardTable(e.huffmanDHSelector+4);break;case 3:a=getCustomHuffmanTable(g,t,i);g++;break;default:throw new Jbig2Error("invalid Huffman DH selector")}switch(e.huffmanDWSelector){case 0:case 1:s=getStandardTable(e.huffmanDWSelector+2);break;case 3:s=getCustomHuffmanTable(g,t,i);g++;break;default:throw new Jbig2Error("invalid Huffman DW selector")}if(e.bitmapSizeSelector){r=getCustomHuffmanTable(g,t,i);g++}else r=getStandardTable(1);n=e.aggregationInstancesSelector?getCustomHuffmanTable(g,t,i):getStandardTable(1);return{tableDeltaHeight:a,tableDeltaWidth:s,tableBitmapSize:r,tableAggregateInstances:n}}(e,i,this.customTables);g=new Reader(a,s,r)}let o=this.symbols;o||(this.symbols=o={});const c=[];for(const e of i){const t=o[e];t&&c.push(...t)}const C=new DecodingContext(a,s,r);o[t]=function decodeSymbolDictionary(e,t,i,a,s,r,n,g,o,c,C,h){if(e&&t)throw new Jbig2Error("symbol refinement with Huffman is not supported");const l=[];let Q=0,E=log2(i.length+a);const u=C.decoder,d=C.contextCache;let f,p;if(e){f=getStandardTable(1);p=[];E=Math.max(E,1)}for(;l.length1)m=decodeTextRegion(e,t,a,Q,0,s,1,i.concat(l),E,0,0,1,0,r,o,c,C,0,h);else{const e=decodeIAID(d,u,E),t=decodeInteger(d,"IARDX",u),s=decodeInteger(d,"IARDY",u);m=decodeRefinement(a,Q,o,e=32){let i,a,n;switch(t){case 32:if(0===e)throw new Jbig2Error("no previous value in symbol ID table");a=s.readBits(2)+3;i=r[e-1].prefixLength;break;case 33:a=s.readBits(3)+3;i=0;break;case 34:a=s.readBits(7)+11;i=0;break;default:throw new Jbig2Error("invalid code length in symbol ID table")}for(n=0;n=0;d--){R=e?decodeMMRBitmap(k,o,c,!0):decodeBitmap(!1,o,c,i,!1,null,F,E);S[d]=R}for(N=0;N=0;f--){M^=S[f][N][G];U|=M<>8;H=h+N*l-G*Q>>8;if(L>=0&&L+w<=a&&H>=0&&H+D<=s)for(d=0;d=s)){Y=u[t];J=x[d];for(f=0;f=0&&e>1&7),o=1+(a>>4&7),c=[];let C,h,l=s;do{C=n.readBits(g);h=n.readBits(o);c.push(new HuffmanLine([l,C,h,0]));l+=1<>t&1;if(t<=0)this.children[i]=new HuffmanTreeNode(e);else{let a=this.children[i];a||(this.children[i]=a=new HuffmanTreeNode(null));a.buildTree(e,t-1)}}decodeNode(e){if(this.isLeaf){if(this.isOOB)return null;const t=e.readBits(this.rangeLength);return this.rangeLow+(this.isLowerRange?-t:t)}const t=this.children[e.readBit()];if(!t)throw new Jbig2Error("invalid Huffman data");return t.decodeNode(e)}}class HuffmanTable{constructor(e,t){t||this.assignPrefixCodes(e);this.rootNode=new HuffmanTreeNode(null);for(let t=0,i=e.length;t0&&this.rootNode.buildTree(i,i.prefixLength-1)}}decode(e){return this.rootNode.decodeNode(e)}assignPrefixCodes(e){const t=e.length;let i=0;for(let a=0;a=this.end)throw new Jbig2Error("end of data while reading bit");this.currentByte=this.data[this.position++];this.shift=7}const e=this.currentByte>>this.shift&1;this.shift--;return e}readBits(e){let t,i=0;for(t=e-1;t>=0;t--)i|=this.readBit()<=this.end?-1:this.data[this.position++]}}function getCustomHuffmanTable(e,t,i){let a=0;for(let s=0,r=t.length;s>i&1;i--}}if(a&&!g){const e=5;for(let t=0;t>2,c=new Uint32Array(e.buffer,t,o);if(FeatureTest.isLittleEndian){for(;n>>24|t<<8|4278190080;i[a+2]=t>>>16|s<<16|4278190080;i[a+3]=s>>>8|4278190080}for(let s=4*n,r=t+g;s>>8|255;i[a+2]=t<<16|s>>>16|255;i[a+3]=s<<8|255}for(let s=4*n,r=t+g;s>3,h=7&a,l=e.length;i=new Uint32Array(i.buffer);let Q=0;for(let a=0;a0&&!e[r-1];)r--;const n=[{children:[],index:0}];let g,o=n[0];for(i=0;i0;)o=n.pop();o.index++;n.push(o);for(;n.length<=i;){n.push(g={children:[],index:0});o.children[o.index]=g.children;o=g}s++}if(i+10){E--;return Q>>E&1}Q=e[t++];if(255===Q){const a=e[t++];if(a){if(220===a&&c){const a=readUint16(e,t+=2);t+=2;if(a>0&&a!==i.scanLines)throw new DNLMarkerError("Found DNL marker (0xFFDC) while parsing scan data",a)}else if(217===a){if(c){const e=p*(8===i.precision?8:0);if(e>0&&Math.round(i.scanLines/e)>=5)throw new DNLMarkerError("Found EOI marker (0xFFD9) while parsing scan data, possibly caused by incorrect `scanLines` parameter",e)}throw new EOIMarkerError("Found EOI marker (0xFFD9) while parsing scan data")}throw new JpegError(`unexpected marker ${(Q<<8|a).toString(16)}`)}}E=7;return Q>>>7}function decodeHuffman(e){let t=e;for(;;){t=t[readBit()];switch(typeof t){case"number":return t;case"object":continue}throw new JpegError("invalid huffman sequence")}}function receive(e){let t=0;for(;e>0;){t=t<<1|readBit();e--}return t}function receiveAndExtend(e){if(1===e)return 1===readBit()?1:-1;const t=receive(e);return t>=1<0){u--;return}let i=r;const a=n;for(;i<=a;){const a=decodeHuffman(e.huffmanTableAC),s=15&a,r=a>>4;if(0===s){if(r<15){u=receive(r)+(1<>4;if(0===s)if(c<15){u=receive(c)+(1<>4;if(0===a){if(r<15)break;s+=16;continue}s+=r;const n=Wt[s];e.blockData[t+n]=receiveAndExtend(a);s++}};let k,R=0;const N=1===m?a[0].blocksPerLine*a[0].blocksPerColumn:C*i.mcusPerColumn;let G,M;for(;R<=N;){const i=s?Math.min(N-R,s):N;if(i>0){for(w=0;w0?"unexpected":"excessive"} MCU data, current marker is: ${k.invalid}`);t=k.offset}if(!(k.marker>=65488&&k.marker<=65495))break;t+=2}return t-l}function quantizeAndInverse(e,t,i){const a=e.quantizationTable,s=e.blockData;let r,n,g,o,c,C,h,l,Q,E,u,d,f,p,m,y,w;if(!a)throw new JpegError("missing required Quantization Table.");for(let e=0;e<64;e+=8){Q=s[t+e];E=s[t+e+1];u=s[t+e+2];d=s[t+e+3];f=s[t+e+4];p=s[t+e+5];m=s[t+e+6];y=s[t+e+7];Q*=a[e];if(E|u|d|f|p|m|y){E*=a[e+1];u*=a[e+2];d*=a[e+3];f*=a[e+4];p*=a[e+5];m*=a[e+6];y*=a[e+7];r=$t*Q+128>>8;n=$t*f+128>>8;g=u;o=m;c=Ai*(E-y)+128>>8;l=Ai*(E+y)+128>>8;C=d<<4;h=p<<4;r=r+n+1>>1;n=r-n;w=g*_t+o*zt+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]=d;s[t+e+32]=f;s[t+e+40]=p;s[t+e+48]=m;s[t+e+56]=y}else{w=$t*Q+8192>>14;w=w<-2040?0:w>=2024?255:w+2056>>4;s[t+e]=w;s[t+e+8]=w;s[t+e+16]=w;s[t+e+24]=w;s[t+e+32]=w;s[t+e+40]=w;s[t+e+48]=w;s[t+e+56]=w}}}function buildComponentData(e,t){const i=t.blocksPerLine,a=t.blocksPerColumn,s=new Int16Array(64);for(let e=0;e=a)return null;const r=readUint16(e,t);if(r>=65472&&r<=65534)return{invalid:null,marker:r,offset:t};let n=readUint16(e,s);for(;!(n>=65472&&n<=65534);){if(++s>=a)return null;n=readUint16(e,s)}return{invalid:r.toString(16),marker:n,offset:s}}function prepareComponents(e){const t=Math.ceil(e.samplesPerLine/8/e.maxH),i=Math.ceil(e.scanLines/8/e.maxV);for(const a of e.components){const s=Math.ceil(Math.ceil(e.samplesPerLine/8)*a.h/e.maxH),r=Math.ceil(Math.ceil(e.scanLines/8)*a.v/e.maxV),n=t*a.h,g=64*(i*a.v)*(n+1);a.blockData=new Int16Array(g);a.blocksPerLine=s;a.blocksPerColumn=r}e.mcusPerLine=t;e.mcusPerColumn=i}function readDataBlock(e,t){const i=readUint16(e,t);let a=(t+=2)+i-2;const s=findNextFileMarker(e,a,t);if(s?.invalid){warn("readDataBlock - incorrect length, current marker is: "+s.invalid);a=s.offset}const r=e.subarray(t,a);return{appData:r,newOffset:t+=r.length}}function skipData(e,t){const i=readUint16(e,t),a=(t+=2)+i-2,s=findNextFileMarker(e,a,t);return s?.invalid?s.offset:a}class JpegImage{constructor({decodeTransform:e=null,colorTransform:t=-1}={}){this._decodeTransform=e;this._colorTransform=t}static canUseImageDecoder(e,t=-1){let i=0,a=null,s=readUint16(e,i);i+=2;if(65496!==s)throw new JpegError("SOI not found");s=readUint16(e,i);i+=2;A:for(;65497!==s;){switch(s){case 65472:case 65473:case 65474:a=e[i+7];break A;case 65535:255!==e[i]&&i--}i=skipData(e,i);s=readUint16(e,i);i+=2}return 4!==a&&(3!==a||0!==t)}parse(e,{dnlScanLines:t=null}={}){let i,a,s=0,r=null,n=null,g=0;const o=[],c=[],C=[];let h=readUint16(e,s);s+=2;if(65496!==h)throw new JpegError("SOI not found");h=readUint16(e,s);s+=2;A:for(;65497!==h;){let l,Q,E;switch(h){case 65504:case 65505:case 65506:case 65507:case 65508:case 65509:case 65510:case 65511:case 65512:case 65513:case 65514:case 65515:case 65516:case 65517:case 65518:case 65519:case 65534:const{appData:u,newOffset:d}=readDataBlock(e,s);s=d;65504===h&&74===u[0]&&70===u[1]&&73===u[2]&&70===u[3]&&0===u[4]&&(r={version:{major:u[5],minor:u[6]},densityUnits:u[7],xDensity:u[8]<<8|u[9],yDensity:u[10]<<8|u[11],thumbWidth:u[12],thumbHeight:u[13],thumbData:u.subarray(14,14+3*u[12]*u[13])});65518===h&&65===u[0]&&100===u[1]&&111===u[2]&&98===u[3]&&101===u[4]&&(n={version:u[5]<<8|u[6],flags0:u[7]<<8|u[8],flags1:u[9]<<8|u[10],transformCode:u[11]});break;case 65499:const f=readUint16(e,s);s+=2;const p=f+s-2;let m;for(;s>4){if(t>>4!=1)throw new JpegError("DQT - invalid table spec");for(Q=0;Q<64;Q++){m=Wt[Q];i[m]=readUint16(e,s);s+=2}}else for(Q=0;Q<64;Q++){m=Wt[Q];i[m]=e[s++]}o[15&t]=i}break;case 65472:case 65473:case 65474:if(i)throw new JpegError("Only single frame JPEGs supported");s+=2;i={};i.extended=65473===h;i.progressive=65474===h;i.precision=e[s++];const y=readUint16(e,s);s+=2;i.scanLines=t||y;i.samplesPerLine=readUint16(e,s);s+=2;i.components=[];i.componentIds={};const w=e[s++];let D=0,b=0;for(l=0;l>4,r=15&e[s+1];D>4?c:C)[15&t]=buildHuffmanTable(i,r)}break;case 65501:s+=2;a=readUint16(e,s);s+=2;break;case 65498:const S=1==++g&&!t;s+=2;const k=e[s++],R=[];for(l=0;l>4];r.huffmanTableAC=c[15&n];R.push(r)}const N=e[s++],G=e[s++],M=e[s++];try{s+=decodeScan(e,s,i,R,a,N,G,M>>4,15&M,S)}catch(t){if(t instanceof DNLMarkerError){warn(`${t.message} -- attempting to re-parse the JPEG image.`);return this.parse(e,{dnlScanLines:t.scanLines})}if(t instanceof EOIMarkerError){warn(`${t.message} -- ignoring the rest of the image data.`);break A}throw t}break;case 65500:s+=4;break;case 65535:255!==e[s]&&s--;break;default:const U=findNextFileMarker(e,s-2,s-3);if(U?.invalid){warn("JpegImage.parse - unexpected data, current marker is: "+U.invalid);s=U.offset;break}if(!U||s>=e.length-1){warn("JpegImage.parse - reached the end of the image data without finding an EOI marker (0xFFD9).");break A}throw new JpegError("JpegImage.parse - unknown marker: "+h.toString(16))}h=readUint16(e,s);s+=2}if(!i)throw new JpegError("JpegImage.parse - no frame data found.");this.width=i.samplesPerLine;this.height=i.scanLines;this.jfif=r;this.adobe=n;this.components=[];for(const e of i.components){const t=o[e.quantizationId];t&&(e.quantizationTable=t);this.components.push({index:e.index,output:buildComponentData(0,e),scaleX:e.h/i.maxH,scaleY:e.v/i.maxV,blocksPerLine:e.blocksPerLine,blocksPerColumn:e.blocksPerColumn})}this.numComponents=this.components.length}_getLinearizedBlockData(e,t,i=!1){const a=this.width/e,s=this.height/t;let r,n,g,o,c,C,h,l,Q,E,u,d=0;const f=this.components.length,p=e*t*f,m=new Uint8ClampedArray(p),y=new Uint32Array(e),w=4294967288;let D;for(h=0;h>8)+b[Q+1];return m}get _isColorConversionNeeded(){return this.adobe?!!this.adobe.transformCode:3===this.numComponents?0!==this._colorTransform&&(82!==this.components[0].index||71!==this.components[1].index||66!==this.components[2].index):1===this._colorTransform}_convertYccToRgb(e){let t,i,a;for(let s=0,r=e.length;s4)throw new JpegError("Unsupported color mode");const r=this._getLinearizedBlockData(e,t,s);if(1===this.numComponents&&(i||a)){const e=r.length*(i?4:3),t=new Uint8ClampedArray(e);let a=0;if(i)!function grayToRGBA(e,t){if(FeatureTest.isLittleEndian)for(let i=0,a=e.length;i0&&(e=e.subarray(t));break}return e}decodeImage(e){if(this.eof)return this.buffer;e=this.#w(e||this.bytes);const t=new JpegImage(this.jpegOptions);t.parse(e);const i=t.getData({width:this.drawWidth,height:this.drawHeight,forceRGBA:this.forceRGBA,forceRGB:this.forceRGB,isSourcePDF:!0});this.buffer=i;this.bufferLength=i.length;this.eof=!0;return this.buffer}get canAsyncDecodeImageFromBuffer(){return this.stream.isAsync}async getTransferableImage(){if(!await JpegStream.canUseImageDecoder)return null;const e=this.jpegOptions;if(e.decodeTransform)return null;let t;try{const i=this.canAsyncDecodeImageFromBuffer&&await this.stream.asyncGetBytes()||this.bytes;if(!i)return null;const a=this.#w(i);if(!JpegImage.canUseImageDecoder(a,e.colorTransform))return null;t=new ImageDecoder({data:a,type:"image/jpeg",preferAnimation:!1});return(await t.decode()).image}catch(e){warn(`getTransferableImage - failed: "${e}".`);return null}finally{t?.close()}}}var ei,ti=(ei="undefined"!=typeof document?document.currentScript?.src:void 0,function(e={}){var t,i,a=e;new Promise(((e,a)=>{t=e;i=a}));a.decode=function(e,{numComponents:t=4,isIndexedColormap:i=!1,smaskInData:s=!1}){const r=e.length,n=a._malloc(r);a.HEAPU8.set(e,n);const g=a._jp2_decode(n,r,t>0?t:0,!!i,!!s);a._free(n);if(g){const{errorMessages:e}=a;if(e){delete a.errorMessages;return e}return"Unknown error"}const{imageData:o}=a;a.imageData=null;return o};var s=Object.assign({},a),r="./this.program",quit_=(e,t)=>{throw t},n="";"undefined"!=typeof document&&document.currentScript&&(n=document.currentScript.src);ei&&(n=ei);n=n.startsWith("blob:")?"":n.substr(0,n.replace(/[?#].*/,"").lastIndexOf("/")+1);var g=a.print||console.log.bind(console),o=a.printErr||console.error.bind(console);Object.assign(a,s);s=null;a.arguments&&a.arguments;a.thisProgram&&(r=a.thisProgram);var c,C=a.wasmBinary;function tryParseAsDataURI(e){if(isDataURI(e))return function intArrayFromBase64(e){for(var t=atob(e),i=new Uint8Array(t.length),a=0;ae.startsWith(b);function instantiateSync(e,t){var i,a=function getBinarySync(e){if(e==d&&C)return new Uint8Array(C);var t=tryParseAsDataURI(e);if(t)return t;throw'sync fetching of the wasm failed: you can preload it to Module["wasmBinary"] manually, or emcc.py will do that for you when generating HTML (but not JS)'}(e);i=new WebAssembly.Module(a);return[new WebAssembly.Instance(i,t),i]}class ExitStatus{name="ExitStatus";constructor(e){this.message=`Program terminated with exit(${e})`;this.status=e}}var F,callRuntimeCallbacks=e=>{for(;e.length>0;)e.shift()(a)},S=a.noExitRuntime||!0,k=0,R={},handleException=e=>{if(e instanceof ExitStatus||"unwind"==e)return h;quit_(0,e)},keepRuntimeAlive=()=>S||k>0,_proc_exit=e=>{h=e;if(!keepRuntimeAlive()){a.onExit?.(e);u=!0}quit_(0,new ExitStatus(e))},_exit=(e,t)=>{h=e;_proc_exit(e)},callUserCallback=e=>{if(!u)try{e();(()=>{if(!keepRuntimeAlive())try{_exit(h)}catch(e){handleException(e)}})()}catch(e){handleException(e)}},growMemory=e=>{var t=(e-c.buffer.byteLength+65535)/65536|0;try{c.grow(t);updateMemoryViews();return 1}catch(e){}},N={},getEnvStrings=()=>{if(!getEnvStrings.strings){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:r||"./this.program"};for(var t in N)void 0===N[t]?delete e[t]:e[t]=N[t];var i=[];for(var t in e)i.push(`${t}=${e[t]}`);getEnvStrings.strings=i}return getEnvStrings.strings},G=[null,[],[]],M="undefined"!=typeof TextDecoder?new TextDecoder:void 0,UTF8ArrayToString=(e,t=0,i=NaN)=>{for(var a=t+i,s=t;e[s]&&!(s>=a);)++s;if(s-t>16&&e.buffer&&M)return M.decode(e.subarray(t,s));for(var r="";t>10,56320|1023&c)}}else r+=String.fromCharCode((31&n)<<6|g)}else r+=String.fromCharCode(n)}return r},printChar=(e,t)=>{var i=G[e];if(0===t||10===t){(1===e?g:o)(UTF8ArrayToString(i));i.length=0}else i.push(t)},UTF8ToString=(e,t)=>e?UTF8ArrayToString(Q,e,t):"",U={m:()=>function abort(e){a.onAbort?.(e);o(e="Aborted("+e+")");u=!0;e+=". Build with -sASSERTIONS for more info.";var t=new WebAssembly.RuntimeError(e);i(t);throw t}(""),c:(e,t,i)=>Q.copyWithin(e,t,t+i),l:()=>{S=!1;k=0},n:(e,t)=>{if(R[e]){clearTimeout(R[e].id);delete R[e]}if(!t)return 0;var i=setTimeout((()=>{delete R[e];callUserCallback((()=>L(e,performance.now())))}),t);R[e]={id:i,timeout_ms:t};return 0},g:function _copy_pixels_1(e,t){e>>=2;const i=a.imageData=new Uint8ClampedArray(t),s=a.HEAP32.subarray(e,e+t);i.set(s)},f:function _copy_pixels_3(e,t,i,s){e>>=2;t>>=2;i>>=2;const r=a.imageData=new Uint8ClampedArray(3*s),n=a.HEAP32.subarray(e,e+s),g=a.HEAP32.subarray(t,t+s),o=a.HEAP32.subarray(i,i+s);for(let e=0;e>=2;t>>=2;i>>=2;s>>=2;const n=a.imageData=new Uint8ClampedArray(4*r),g=a.HEAP32.subarray(e,e+r),o=a.HEAP32.subarray(t,t+r),c=a.HEAP32.subarray(i,i+r),C=a.HEAP32.subarray(s,s+r);for(let e=0;e{var t,i,a=Q.length,s=2147483648;if((e>>>=0)>s)return!1;for(var r=1;r<=4;r*=2){var n=a*(1+.2/r);n=Math.min(n,e+100663296);var g=Math.min(s,(t=Math.max(e,n),i=65536,Math.ceil(t/i)*i));if(growMemory(g))return!0}return!1},p:(e,t)=>{var i=0;getEnvStrings().forEach(((a,s)=>{var r=t+i;E[e+4*s>>2]=r;((e,t)=>{for(var i=0;i{var i=getEnvStrings();E[e>>2]=i.length;var a=0;i.forEach((e=>a+=e.length+1));E[t>>2]=a;return 0},r:e=>52,j:function _fd_seek(e,t,i,a,s){return 70},b:(e,t,i,a)=>{for(var s=0,r=0;r>2],g=E[t+4>>2];t+=8;for(var o=0;o>2]=s;return 0},s:function _gray_to_rgba(e,t){e>>=2;const i=a.imageData=new Uint8ClampedArray(4*t),s=a.HEAP32.subarray(e,e+t);for(let e=0;e>=2;t>>=2;const s=a.imageData=new Uint8ClampedArray(4*i),r=a.HEAP32.subarray(e,e+i),n=a.HEAP32.subarray(t,t+i);for(let e=0;e>=2;t>>=2;i>>=2;const r=a.imageData=new Uint8ClampedArray(4*s),n=a.HEAP32.subarray(e,e+s),g=a.HEAP32.subarray(t,t+s),o=a.HEAP32.subarray(i,i+s);for(let e=0;e0)){!function preRun(){if(a.preRun){"function"==typeof a.preRun&&(a.preRun=[a.preRun]);for(;a.preRun.length;)e=a.preRun.shift(),f.unshift(e)}var e;callRuntimeCallbacks(f)}();if(!(y>0))if(a.setStatus){a.setStatus("Running...");setTimeout((()=>{setTimeout((()=>a.setStatus("")),1);doRun()}),1)}else doRun()}function doRun(){if(!F){F=!0;a.calledRun=!0;if(!u){!function initRuntime(){callRuntimeCallbacks(p)}();t(a);a.onRuntimeInitialized?.();!function postRun(){if(a.postRun){"function"==typeof a.postRun&&(a.postRun=[a.postRun]);for(;a.postRun.length;)e=a.postRun.shift(),m.unshift(e)}var e;callRuntimeCallbacks(m)}()}}}}if(a.preInit){"function"==typeof a.preInit&&(a.preInit=[a.preInit]);for(;a.preInit.length>0;)a.preInit.pop()()}run();return a});const ii=ti;class JpxError extends ot{constructor(e){super(e,"JpxError")}}class JpxImage{static#D=null;static decode(e,t){t||={};this.#D||=ii({warn});const i=this.#D.decode(e,t);if("string"==typeof i)throw new JpxError(i);return i}static cleanup(){this.#D=null}static parseImageProperties(e){let t=e.getByte();for(;t>=0;){const i=t;t=e.getByte();if(65361===(i<<8|t)){e.skip(4);const t=e.getInt32()>>>0,i=e.getInt32()>>>0,a=e.getInt32()>>>0,s=e.getInt32()>>>0;e.skip(16);return{width:t-a,height:i-s,bitsPerComponent:8,componentsCount:e.getUint16()}}}throw new JpxError("No size marker found in JPX stream")}}class JpxStream extends DecodeStream{constructor(e,t,i){super(t);this.stream=e;this.dict=e.dict;this.maybeLength=t;this.params=i}get bytes(){return shadow(this,"bytes",this.stream.getBytes(this.maybeLength))}ensureBuffer(e){}readBlock(e){this.decodeImage(null,e)}decodeImage(e,t){if(this.eof)return this.buffer;e||=this.bytes;this.buffer=JpxImage.decode(e,t);this.bufferLength=this.buffer.length;this.eof=!0;return this.buffer}get canAsyncDecodeImageFromBuffer(){return this.stream.isAsync}}class LZWStream extends DecodeStream{constructor(e,t,i){super(t);this.str=e;this.dict=e.dict;this.cachedData=0;this.bitsCached=0;const a=4096,s={earlyChange:i,codeLength:9,nextCode:258,dictionaryValues:new Uint8Array(a),dictionaryLengths:new Uint16Array(a),dictionaryPrevCodes:new Uint16Array(a),currentSequence:new Uint8Array(a),currentSequenceLength:0};for(let e=0;e<256;++e){s.dictionaryValues[e]=e;s.dictionaryLengths[e]=1}this.lzwState=s}readBits(e){let t=this.bitsCached,i=this.cachedData;for(;t>>t&(1<0;if(e<256){l[0]=e;Q=1}else{if(!(e>=258)){if(256===e){C=9;n=258;Q=0;continue}this.eof=!0;delete this.lzwState;break}if(e=0;t--){l[t]=g[i];i=c[i]}}else l[Q++]=l[0]}if(s){c[n]=h;o[n]=o[h]+1;g[n]=l[0];n++;C=n+r&n+r-1?C:0|Math.min(Math.log(n+r)/.6931471805599453+1,12)}h=e;E+=Q;if(a15))throw new FormatError(`Unsupported predictor: ${a}`);this.readBlock=2===a?this.readBlockTiff:this.readBlockPng;this.str=e;this.dict=e.dict;const s=this.colors=i.get("Colors")||1,r=this.bits=i.get("BPC","BitsPerComponent")||8,n=this.columns=i.get("Columns")||1;this.pixBytes=s*r+7>>3;this.rowBytes=n*s*r+7>>3;return this}readBlockTiff(){const e=this.rowBytes,t=this.bufferLength,i=this.ensureBuffer(t+e),a=this.bits,s=this.colors,r=this.str.getBytes(e);this.eof=!r.length;if(this.eof)return;let n,g=0,o=0,c=0,C=0,h=t;if(1===a&&1===s)for(n=0;n>1;e^=e>>2;e^=e>>4;g=(1&e)<<7;i[h++]=e}else if(8===a){for(n=0;n>8&255;i[h++]=255&e}}else{const e=new Uint8Array(s+1),h=(1<>c-a)&h;c-=a;o=o<=8){i[Q++]=o>>C-8&255;C-=8}}C>0&&(i[Q++]=(o<<8-C)+(g&(1<<8-C)-1))}this.bufferLength+=e}readBlockPng(){const e=this.rowBytes,t=this.pixBytes,i=this.str.getByte(),a=this.str.getBytes(e);this.eof=!a.length;if(this.eof)return;const s=this.bufferLength,r=this.ensureBuffer(s+e);let n=r.subarray(s-e,s);0===n.length&&(n=new Uint8Array(e));let g,o,c,C=s;switch(i){case 0:for(g=0;g>1)+a[g];for(;g>1)+a[g]&255;C++}break;case 4:for(g=0;g0){const e=this.str.getBytes(a);t.set(e,i);i+=a}}else{a=257-a;const s=e[1];t=this.ensureBuffer(i+a+1);for(let e=0;e>")&&this.buf1!==Bt;){if(!(this.buf1 instanceof Name)){info("Malformed dictionary: key must be a name object");this.shift();continue}const t=this.buf1.name;this.shift();if(this.buf1===Bt)break;a.set(t,this.getObj(e))}if(this.buf1===Bt){if(this.recoveryMode)return a;throw new ParserEOFException("End of file inside dictionary.")}if(isCmd(this.buf2,"stream"))return this.allowStreams?this.makeStream(a,e):a;this.shift();return a;default:return t}if(Number.isInteger(t)){if(Number.isInteger(this.buf1)&&isCmd(this.buf2,"R")){const e=Ref.get(t,this.buf1);this.shift();this.shift();return e}return t}return"string"==typeof t&&e?e.decryptString(t):t}findDefaultInlineStreamEnd(e){const{knownCommands:t}=this.lexer,i=e.pos;let a,s,r=0;for(;-1!==(a=e.getByte());)if(0===r)r=69===a?1:0;else if(1===r)r=73===a?2:0;else if(32===a||10===a||13===a){s=e.pos;const i=e.peekBytes(15),n=i.length;if(0===n)break;for(let e=0;e127))){r=0;break}}if(2!==r)continue;if(!t){warn("findDefaultInlineStreamEnd - `lexer.knownCommands` is undefined.");continue}const g=new Lexer(new Stream(i.slice()),t);g._hexStringWarn=()=>{};let o=0;for(;;){const e=g.getObj();if(e===Bt){r=0;break}if(e instanceof Cmd){const i=t[e.cmd];if(!i){r=0;break}if(i.variableArgs?o<=i.numArgs:o===i.numArgs)break;o=0}else o++}if(2===r)break}else r=0;if(-1===a){warn("findDefaultInlineStreamEnd: Reached the end of the stream without finding a valid EI marker");if(s){warn('... trying to recover by using the last "EI" occurrence.');e.skip(-(e.pos-s))}}let n=4;e.skip(-n);a=e.peekByte();e.skip(n);isWhiteSpace(a)||n--;return e.pos-n-i}findDCTDecodeInlineStreamEnd(e){const t=e.pos;let i,a,s=!1;for(;-1!==(i=e.getByte());)if(255===i){switch(e.getByte()){case 0:break;case 255:e.skip(-1);break;case 217:s=!0;break;case 192:case 193:case 194:case 195:case 197:case 198:case 199:case 201:case 202:case 203:case 205:case 206:case 207:case 196:case 204:case 218:case 219:case 220:case 221:case 222:case 223:case 224:case 225:case 226:case 227:case 228:case 229:case 230:case 231:case 232:case 233:case 234:case 235:case 236:case 237:case 238:case 239:case 254:a=e.getUint16();a>2?e.skip(a-2):e.skip(-2)}if(s)break}const r=e.pos-t;if(-1===i){warn("Inline DCTDecode image stream: EOI marker not found, searching for /EI/ instead.");e.skip(-r);return this.findDefaultInlineStreamEnd(e)}this.inlineStreamSkipEI(e);return r}findASCII85DecodeInlineStreamEnd(e){const t=e.pos;let i;for(;-1!==(i=e.getByte());)if(126===i){const t=e.pos;i=e.peekByte();for(;isWhiteSpace(i);){e.skip();i=e.peekByte()}if(62===i){e.skip();break}if(e.pos>t){const t=e.peekBytes(2);if(69===t[0]&&73===t[1])break}}const a=e.pos-t;if(-1===i){warn("Inline ASCII85Decode image stream: EOD marker not found, searching for /EI/ instead.");e.skip(-a);return this.findDefaultInlineStreamEnd(e)}this.inlineStreamSkipEI(e);return a}findASCIIHexDecodeInlineStreamEnd(e){const t=e.pos;let i;for(;-1!==(i=e.getByte())&&62!==i;);const a=e.pos-t;if(-1===i){warn("Inline ASCIIHexDecode image stream: EOD marker not found, searching for /EI/ instead.");e.skip(-a);return this.findDefaultInlineStreamEnd(e)}this.inlineStreamSkipEI(e);return a}inlineStreamSkipEI(e){let t,i=0;for(;-1!==(t=e.getByte());)if(0===i)i=69===t?1:0;else if(1===i)i=73===t?2:0;else if(2===i)break}makeInlineImage(e){const t=this.lexer,i=t.stream,a=Object.create(null);let s;for(;!isCmd(this.buf1,"ID")&&this.buf1!==Bt;){if(!(this.buf1 instanceof Name))throw new FormatError("Dictionary key must be a name object");const t=this.buf1.name;this.shift();if(this.buf1===Bt)break;a[t]=this.getObj(e)}-1!==t.beginInlineImagePos&&(s=i.pos-t.beginInlineImagePos);const r=this.xref.fetchIfRef(a.F||a.Filter);let n;if(r instanceof Name)n=r.name;else if(Array.isArray(r)){const e=this.xref.fetchIfRef(r[0]);e instanceof Name&&(n=e.name)}const g=i.pos;let o,c;switch(n){case"DCT":case"DCTDecode":o=this.findDCTDecodeInlineStreamEnd(i);break;case"A85":case"ASCII85Decode":o=this.findASCII85DecodeInlineStreamEnd(i);break;case"AHx":case"ASCIIHexDecode":o=this.findASCIIHexDecodeInlineStreamEnd(i);break;default:o=this.findDefaultInlineStreamEnd(i)}if(o<1e3&&s>0){const e=i.pos;i.pos=t.beginInlineImagePos;c=function getInlineImageCacheKey(e){const t=[],i=e.length;let a=0;for(;a=a){let a=!1;for(const e of s){const t=e.length;let s=0;for(;s=r){a=!0;break}if(s>=t){if(isWhiteSpace(n[o+g+s])){info(`Found "${bytesToString([...i,...e])}" when searching for endstream command.`);a=!0}break}}if(a){t.pos+=o;return t.pos-e}}o++}t.pos+=g}return-1}makeStream(e,t){const i=this.lexer;let a=i.stream;i.skipToNextLine();const s=a.pos-1;let r=e.get("Length");if(!Number.isInteger(r)){info(`Bad length "${r&&r.toString()}" in stream.`);r=0}a.pos=s+r;i.nextChar();if(this.tryShift()&&isCmd(this.buf2,"endstream"))this.shift();else{r=this.#b(s);if(r<0)throw new FormatError("Missing endstream command.");i.nextChar();this.shift();this.shift()}this.shift();a=a.makeSubStream(s,r,e);t&&(a=t.createStream(a,r));a=this.filter(a,e,r);a.dict=e;return a}filter(e,t,i){let a=t.get("F","Filter"),s=t.get("DP","DecodeParms");if(a instanceof Name){Array.isArray(s)&&warn("/DecodeParms should not be an Array, when /Filter is a Name.");return this.makeFilter(e,a.name,i,s)}let r=i;if(Array.isArray(a)){const t=a,i=s;for(let n=0,g=t.length;n=48&&e<=57?15&e:e>=65&&e<=70||e>=97&&e<=102?9+(15&e):-1}class Lexer{constructor(e,t=null){this.stream=e;this.nextChar();this.strBuf=[];this.knownCommands=t;this._hexStringNumWarn=0;this.beginInlineImagePos=-1}nextChar(){return this.currentChar=this.stream.getByte()}peekChar(){return this.stream.peekByte()}getNumber(){let e=this.currentChar,t=!1,i=0,a=1;if(45===e){a=-1;e=this.nextChar();45===e&&(e=this.nextChar())}else 43===e&&(e=this.nextChar());if(10===e||13===e)do{e=this.nextChar()}while(10===e||13===e);if(46===e){i=10;e=this.nextChar()}if(e<48||e>57){const t=`Invalid number: ${String.fromCharCode(e)} (charCode ${e})`;if(isWhiteSpace(e)||-1===e){info(`Lexer.getNumber - "${t}".`);return 0}throw new FormatError(t)}let s=e-48,r=0,n=1;for(;(e=this.nextChar())>=0;)if(e>=48&&e<=57){const a=e-48;if(t)r=10*r+a;else{0!==i&&(i*=10);s=10*s+a}}else if(46===e){if(0!==i)break;i=1}else if(45===e)warn("Badly formatted number: minus sign in the middle");else{if(69!==e&&101!==e)break;e=this.peekChar();if(43===e||45===e){n=45===e?-1:1;this.nextChar()}else if(e<48||e>57)break;t=!0}0!==i&&(s/=i);t&&(s*=10**(n*r));return a*s}getString(){let e=1,t=!1;const i=this.strBuf;i.length=0;let a=this.nextChar();for(;;){let s=!1;switch(0|a){case-1:warn("Unterminated string");t=!0;break;case 40:++e;i.push("(");break;case 41:if(0==--e){this.nextChar();t=!0}else i.push(")");break;case 92:a=this.nextChar();switch(a){case-1:warn("Unterminated string");t=!0;break;case 110:i.push("\n");break;case 114:i.push("\r");break;case 116:i.push("\t");break;case 98:i.push("\b");break;case 102:i.push("\f");break;case 92:case 40:case 41:i.push(String.fromCharCode(a));break;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:let e=15&a;a=this.nextChar();s=!0;if(a>=48&&a<=55){e=(e<<3)+(15&a);a=this.nextChar();if(a>=48&&a<=55){s=!1;e=(e<<3)+(15&a)}}i.push(String.fromCharCode(e));break;case 13:10===this.peekChar()&&this.nextChar();break;case 10:break;default:i.push(String.fromCharCode(a))}break;default:i.push(String.fromCharCode(a))}if(t)break;s||(a=this.nextChar())}return i.join("")}getName(){let e,t;const i=this.strBuf;i.length=0;for(;(e=this.nextChar())>=0&&!ai[e];)if(35===e){e=this.nextChar();if(ai[e]){warn("Lexer_getName: NUMBER SIGN (#) should be followed by a hexadecimal number.");i.push("#");break}const a=toHexDigit(e);if(-1!==a){t=e;e=this.nextChar();const s=toHexDigit(e);if(-1===s){warn(`Lexer_getName: Illegal digit (${String.fromCharCode(e)}) in hexadecimal number.`);i.push("#",String.fromCharCode(t));if(ai[e])break;i.push(String.fromCharCode(e));continue}i.push(String.fromCharCode(a<<4|s))}else i.push("#",String.fromCharCode(e))}else i.push(String.fromCharCode(e));i.length>127&&warn(`Name token is longer than allowed by the spec: ${i.length}`);return Name.get(i.join(""))}_hexStringWarn(e){5!=this._hexStringNumWarn++?this._hexStringNumWarn>5||warn(`getHexString - ignoring invalid character: ${e}`):warn("getHexString - ignoring additional invalid characters.")}getHexString(){const e=this.strBuf;e.length=0;let t=this.currentChar,i=-1,a=-1;this._hexStringNumWarn=0;for(;;){if(t<0){warn("Unterminated hex string");break}if(62===t){this.nextChar();break}if(1!==ai[t]){a=toHexDigit(t);if(-1===a)this._hexStringWarn(t);else if(-1===i)i=a;else{e.push(String.fromCharCode(i<<4|a));i=-1}t=this.nextChar()}else t=this.nextChar()}-1!==i&&e.push(String.fromCharCode(i<<4));return e.join("")}getObj(){let e=!1,t=this.currentChar;for(;;){if(t<0)return Bt;if(e)10!==t&&13!==t||(e=!1);else if(37===t)e=!0;else if(1!==ai[t])break;t=this.nextChar()}switch(0|t){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 43:case 45:case 46:return this.getNumber();case 40:return this.getString();case 47:return this.getName();case 91:this.nextChar();return Cmd.get("[");case 93:this.nextChar();return Cmd.get("]");case 60:t=this.nextChar();if(60===t){this.nextChar();return Cmd.get("<<")}return this.getHexString();case 62:t=this.nextChar();if(62===t){this.nextChar();return Cmd.get(">>")}return Cmd.get(">");case 123:this.nextChar();return Cmd.get("{");case 125:this.nextChar();return Cmd.get("}");case 41:this.nextChar();throw new FormatError(`Illegal character: ${t}`)}let i=String.fromCharCode(t);if(t<32||t>127){const e=this.peekChar();if(e>=32&&e<=127){this.nextChar();return Cmd.get(i)}}const a=this.knownCommands;let s=void 0!==a?.[i];for(;(t=this.nextChar())>=0&&!ai[t];){const e=i+String.fromCharCode(t);if(s&&void 0===a[e])break;if(128===i.length)throw new FormatError(`Command token too long: ${i.length}`);i=e;s=void 0!==a?.[i]}if("true"===i)return!0;if("false"===i)return!1;if("null"===i)return null;"BI"===i&&(this.beginInlineImagePos=this.stream.pos);return Cmd.get(i)}skipToNextLine(){let e=this.currentChar;for(;e>=0;){if(13===e){e=this.nextChar();10===e&&this.nextChar();break}if(10===e){this.nextChar();break}e=this.nextChar()}}}class Linearization{static create(e){function getInt(e,t,i=!1){const a=e.get(t);if(Number.isInteger(a)&&(i?a>=0:a>0))return a;throw new Error(`The "${t}" parameter in the linearization dictionary is invalid.`)}const t=new Parser({lexer:new Lexer(e),xref:null}),i=t.getObj(),a=t.getObj(),s=t.getObj(),r=t.getObj();let n,g;if(!(Number.isInteger(i)&&Number.isInteger(a)&&isCmd(s,"obj")&&r instanceof Dict&&"number"==typeof(n=r.get("Linearized"))&&n>0))return null;if((g=getInt(r,"L"))!==e.length)throw new Error('The "L" parameter in the linearization dictionary does not equal the stream length.');return{length:g,hints:function getHints(e){const t=e.get("H");let i;if(Array.isArray(t)&&(2===(i=t.length)||4===i)){for(let e=0;e0))throw new Error(`Hint (${e}) in the linearization dictionary is invalid.`)}return t}throw new Error("Hint array in the linearization dictionary is invalid.")}(r),objectNumberFirst:getInt(r,"O"),endFirst:getInt(r,"E"),numPages:getInt(r,"N"),mainXRefEntriesOffset:getInt(r,"T"),pageFirst:r.has("P")?getInt(r,"P",!0):0}}}const si=["Adobe-GB1-UCS2","Adobe-CNS1-UCS2","Adobe-Japan1-UCS2","Adobe-Korea1-UCS2","78-EUC-H","78-EUC-V","78-H","78-RKSJ-H","78-RKSJ-V","78-V","78ms-RKSJ-H","78ms-RKSJ-V","83pv-RKSJ-H","90ms-RKSJ-H","90ms-RKSJ-V","90msp-RKSJ-H","90msp-RKSJ-V","90pv-RKSJ-H","90pv-RKSJ-V","Add-H","Add-RKSJ-H","Add-RKSJ-V","Add-V","Adobe-CNS1-0","Adobe-CNS1-1","Adobe-CNS1-2","Adobe-CNS1-3","Adobe-CNS1-4","Adobe-CNS1-5","Adobe-CNS1-6","Adobe-GB1-0","Adobe-GB1-1","Adobe-GB1-2","Adobe-GB1-3","Adobe-GB1-4","Adobe-GB1-5","Adobe-Japan1-0","Adobe-Japan1-1","Adobe-Japan1-2","Adobe-Japan1-3","Adobe-Japan1-4","Adobe-Japan1-5","Adobe-Japan1-6","Adobe-Korea1-0","Adobe-Korea1-1","Adobe-Korea1-2","B5-H","B5-V","B5pc-H","B5pc-V","CNS-EUC-H","CNS-EUC-V","CNS1-H","CNS1-V","CNS2-H","CNS2-V","ETHK-B5-H","ETHK-B5-V","ETen-B5-H","ETen-B5-V","ETenms-B5-H","ETenms-B5-V","EUC-H","EUC-V","Ext-H","Ext-RKSJ-H","Ext-RKSJ-V","Ext-V","GB-EUC-H","GB-EUC-V","GB-H","GB-V","GBK-EUC-H","GBK-EUC-V","GBK2K-H","GBK2K-V","GBKp-EUC-H","GBKp-EUC-V","GBT-EUC-H","GBT-EUC-V","GBT-H","GBT-V","GBTpc-EUC-H","GBTpc-EUC-V","GBpc-EUC-H","GBpc-EUC-V","H","HKdla-B5-H","HKdla-B5-V","HKdlb-B5-H","HKdlb-B5-V","HKgccs-B5-H","HKgccs-B5-V","HKm314-B5-H","HKm314-B5-V","HKm471-B5-H","HKm471-B5-V","HKscs-B5-H","HKscs-B5-V","Hankaku","Hiragana","KSC-EUC-H","KSC-EUC-V","KSC-H","KSC-Johab-H","KSC-Johab-V","KSC-V","KSCms-UHC-H","KSCms-UHC-HW-H","KSCms-UHC-HW-V","KSCms-UHC-V","KSCpc-EUC-H","KSCpc-EUC-V","Katakana","NWP-H","NWP-V","RKSJ-H","RKSJ-V","Roman","UniCNS-UCS2-H","UniCNS-UCS2-V","UniCNS-UTF16-H","UniCNS-UTF16-V","UniCNS-UTF32-H","UniCNS-UTF32-V","UniCNS-UTF8-H","UniCNS-UTF8-V","UniGB-UCS2-H","UniGB-UCS2-V","UniGB-UTF16-H","UniGB-UTF16-V","UniGB-UTF32-H","UniGB-UTF32-V","UniGB-UTF8-H","UniGB-UTF8-V","UniJIS-UCS2-H","UniJIS-UCS2-HW-H","UniJIS-UCS2-HW-V","UniJIS-UCS2-V","UniJIS-UTF16-H","UniJIS-UTF16-V","UniJIS-UTF32-H","UniJIS-UTF32-V","UniJIS-UTF8-H","UniJIS-UTF8-V","UniJIS2004-UTF16-H","UniJIS2004-UTF16-V","UniJIS2004-UTF32-H","UniJIS2004-UTF32-V","UniJIS2004-UTF8-H","UniJIS2004-UTF8-V","UniJISPro-UCS2-HW-V","UniJISPro-UCS2-V","UniJISPro-UTF8-V","UniJISX0213-UTF32-H","UniJISX0213-UTF32-V","UniJISX02132004-UTF32-H","UniJISX02132004-UTF32-V","UniKS-UCS2-H","UniKS-UCS2-V","UniKS-UTF16-H","UniKS-UTF16-V","UniKS-UTF32-H","UniKS-UTF32-V","UniKS-UTF8-H","UniKS-UTF8-V","V","WP-Symbol"],ri=2**24-1;class CMap{constructor(e=!1){this.codespaceRanges=[[],[],[],[]];this.numCodespaceRanges=0;this._map=[];this.name="";this.vertical=!1;this.useCMap=null;this.builtInCMap=e}addCodespaceRange(e,t,i){this.codespaceRanges[e-1].push(t,i);this.numCodespaceRanges++}mapCidRange(e,t,i){if(t-e>ri)throw new Error("mapCidRange - ignoring data above MAX_MAP_RANGE.");for(;e<=t;)this._map[e++]=i++}mapBfRange(e,t,i){if(t-e>ri)throw new Error("mapBfRange - ignoring data above MAX_MAP_RANGE.");const a=i.length-1;for(;e<=t;){this._map[e++]=i;const t=i.charCodeAt(a)+1;t>255?i=i.substring(0,a-1)+String.fromCharCode(i.charCodeAt(a-1)+1)+"\0":i=i.substring(0,a)+String.fromCharCode(t)}}mapBfRangeToArray(e,t,i){if(t-e>ri)throw new Error("mapBfRangeToArray - ignoring data above MAX_MAP_RANGE.");const a=i.length;let s=0;for(;e<=t&&s>>0;const n=s[r];for(let e=0,t=n.length;e=t&&a<=s){i.charcode=a;i.length=r+1;return}}}i.charcode=0;i.length=1}getCharCodeLength(e){const t=this.codespaceRanges;for(let i=0,a=t.length;i=s&&e<=r)return i+1}}return 1}get length(){return this._map.length}get isIdentityCMap(){if("Identity-H"!==this.name&&"Identity-V"!==this.name)return!1;if(65536!==this._map.length)return!1;for(let e=0;e<65536;e++)if(this._map[e]!==e)return!1;return!0}}class IdentityCMap extends CMap{constructor(e,t){super();this.vertical=e;this.addCodespaceRange(t,0,65535)}mapCidRange(e,t,i){unreachable("should not call mapCidRange")}mapBfRange(e,t,i){unreachable("should not call mapBfRange")}mapBfRangeToArray(e,t,i){unreachable("should not call mapBfRangeToArray")}mapOne(e,t){unreachable("should not call mapCidOne")}lookup(e){return Number.isInteger(e)&&e<=65535?e:void 0}contains(e){return Number.isInteger(e)&&e<=65535}forEach(e){for(let t=0;t<=65535;t++)e(t,t)}charCodeOf(e){return Number.isInteger(e)&&e<=65535?e:-1}getMap(){const e=new Array(65536);for(let t=0;t<=65535;t++)e[t]=t;return e}get length(){return 65536}get isIdentityCMap(){unreachable("should not access .isIdentityCMap")}}function strToInt(e){let t=0;for(let i=0;i>>0}function expectString(e){if("string"!=typeof e)throw new FormatError("Malformed CMap: expected string.")}function expectInt(e){if(!Number.isInteger(e))throw new FormatError("Malformed CMap: expected int.")}function parseBfChar(e,t){for(;;){let i=t.getObj();if(i===Bt)break;if(isCmd(i,"endbfchar"))return;expectString(i);const a=strToInt(i);i=t.getObj();expectString(i);const s=i;e.mapOne(a,s)}}function parseBfRange(e,t){for(;;){let i=t.getObj();if(i===Bt)break;if(isCmd(i,"endbfrange"))return;expectString(i);const a=strToInt(i);i=t.getObj();expectString(i);const s=strToInt(i);i=t.getObj();if(Number.isInteger(i)||"string"==typeof i){const t=Number.isInteger(i)?String.fromCharCode(i):i;e.mapBfRange(a,s,t)}else{if(!isCmd(i,"["))break;{i=t.getObj();const r=[];for(;!isCmd(i,"]")&&i!==Bt;){r.push(i);i=t.getObj()}e.mapBfRangeToArray(a,s,r)}}}throw new FormatError("Invalid bf range.")}function parseCidChar(e,t){for(;;){let i=t.getObj();if(i===Bt)break;if(isCmd(i,"endcidchar"))return;expectString(i);const a=strToInt(i);i=t.getObj();expectInt(i);const s=i;e.mapOne(a,s)}}function parseCidRange(e,t){for(;;){let i=t.getObj();if(i===Bt)break;if(isCmd(i,"endcidrange"))return;expectString(i);const a=strToInt(i);i=t.getObj();expectString(i);const s=strToInt(i);i=t.getObj();expectInt(i);const r=i;e.mapCidRange(a,s,r)}}function parseCodespaceRange(e,t){for(;;){let i=t.getObj();if(i===Bt)break;if(isCmd(i,"endcodespacerange"))return;if("string"!=typeof i)break;const a=strToInt(i);i=t.getObj();if("string"!=typeof i)break;const s=strToInt(i);e.addCodespaceRange(i.length,a,s)}throw new FormatError("Invalid codespace range.")}function parseWMode(e,t){const i=t.getObj();Number.isInteger(i)&&(e.vertical=!!i)}function parseCMapName(e,t){const i=t.getObj();i instanceof Name&&(e.name=i.name)}async function parseCMap(e,t,i,a){let s,r;A:for(;;)try{const i=t.getObj();if(i===Bt)break;if(i instanceof Name){"WMode"===i.name?parseWMode(e,t):"CMapName"===i.name&&parseCMapName(e,t);s=i}else if(i instanceof Cmd)switch(i.cmd){case"endcmap":break A;case"usecmap":s instanceof Name&&(r=s.name);break;case"begincodespacerange":parseCodespaceRange(e,t);break;case"beginbfchar":parseBfChar(e,t);break;case"begincidchar":parseCidChar(e,t);break;case"beginbfrange":parseBfRange(e,t);break;case"begincidrange":parseCidRange(e,t)}}catch(e){if(e instanceof MissingDataException)throw e;warn("Invalid cMap data: "+e);continue}!a&&r&&(a=r);return a?extendCMap(e,i,a):e}async function extendCMap(e,t,i){e.useCMap=await createBuiltInCMap(i,t);if(0===e.numCodespaceRanges){const t=e.useCMap.codespaceRanges;for(let i=0;iextendCMap(s,t,e)));const r=new Lexer(new Stream(i));return parseCMap(s,r,t,null)}class CMapFactory{static async create({encoding:e,fetchBuiltInCMap:t,useCMap:i}){if(e instanceof Name)return createBuiltInCMap(e.name,t);if(e instanceof BaseStream){const a=await parseCMap(new CMap,new Lexer(e),t,i);return a.isIdentityCMap?createBuiltInCMap(a.name,t):a}throw new Error("Encoding required.")}}const ni=[".notdef","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","endash","dagger","daggerdbl","periodcentered","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","questiondown","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","ring","cedilla","hungarumlaut","ogonek","caron","emdash","AE","ordfeminine","Lslash","Oslash","OE","ordmasculine","ae","dotlessi","lslash","oslash","oe","germandbls","onesuperior","logicalnot","mu","trademark","Eth","onehalf","plusminus","Thorn","onequarter","divide","brokenbar","degree","thorn","threequarters","twosuperior","registered","minus","eth","multiply","threesuperior","copyright","Aacute","Acircumflex","Adieresis","Agrave","Aring","Atilde","Ccedilla","Eacute","Ecircumflex","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Ntilde","Oacute","Ocircumflex","Odieresis","Ograve","Otilde","Scaron","Uacute","Ucircumflex","Udieresis","Ugrave","Yacute","Ydieresis","Zcaron","aacute","acircumflex","adieresis","agrave","aring","atilde","ccedilla","eacute","ecircumflex","edieresis","egrave","iacute","icircumflex","idieresis","igrave","ntilde","oacute","ocircumflex","odieresis","ograve","otilde","scaron","uacute","ucircumflex","udieresis","ugrave","yacute","ydieresis","zcaron"],gi=[".notdef","space","exclamsmall","Hungarumlautsmall","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","questionsmall","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","fi","fl","ffi","ffl","parenleftinferior","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","exclamdownsmall","centoldstyle","Lslashsmall","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","Dotaccentsmall","Macronsmall","figuredash","hypheninferior","Ogoneksmall","Ringsmall","Cedillasmall","onequarter","onehalf","threequarters","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall"],oi=[".notdef","space","dollaroldstyle","dollarsuperior","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","fi","fl","ffi","ffl","parenleftinferior","parenrightinferior","hyphensuperior","colonmonetary","onefitted","rupiah","centoldstyle","figuredash","hypheninferior","onequarter","onehalf","threequarters","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior"],Ii=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclamsmall","Hungarumlautsmall","","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","questionsmall","","asuperior","bsuperior","centsuperior","dsuperior","esuperior","","","","isuperior","","","lsuperior","msuperior","nsuperior","osuperior","","","rsuperior","ssuperior","tsuperior","","ff","fi","fl","ffi","ffl","parenleftinferior","","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","exclamdownsmall","centoldstyle","Lslashsmall","","","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","","Dotaccentsmall","","","Macronsmall","","","figuredash","hypheninferior","","","Ogoneksmall","Ringsmall","Cedillasmall","","","","onequarter","onehalf","threequarters","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","","","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall"],ci=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclamsmall","Hungarumlautsmall","centoldstyle","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","","threequartersemdash","","questionsmall","","","","","Ethsmall","","","onequarter","onehalf","threequarters","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","","","","","","","ff","fi","fl","ffi","ffl","parenleftinferior","","parenrightinferior","Circumflexsmall","hypheninferior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","","","asuperior","centsuperior","","","","","Aacutesmall","Agravesmall","Acircumflexsmall","Adieresissmall","Atildesmall","Aringsmall","Ccedillasmall","Eacutesmall","Egravesmall","Ecircumflexsmall","Edieresissmall","Iacutesmall","Igravesmall","Icircumflexsmall","Idieresissmall","Ntildesmall","Oacutesmall","Ogravesmall","Ocircumflexsmall","Odieresissmall","Otildesmall","Uacutesmall","Ugravesmall","Ucircumflexsmall","Udieresissmall","","eightsuperior","fourinferior","threeinferior","sixinferior","eightinferior","seveninferior","Scaronsmall","","centinferior","twoinferior","","Dieresissmall","","Caronsmall","osuperior","fiveinferior","","commainferior","periodinferior","Yacutesmall","","dollarinferior","","","Thornsmall","","nineinferior","zeroinferior","Zcaronsmall","AEsmall","Oslashsmall","questiondownsmall","oneinferior","Lslashsmall","","","","","","","Cedillasmall","","","","","","OEsmall","figuredash","hyphensuperior","","","","","exclamdownsmall","","Ydieresissmall","","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","ninesuperior","zerosuperior","","esuperior","rsuperior","tsuperior","","","isuperior","ssuperior","dsuperior","","","","","","lsuperior","Ogoneksmall","Brevesmall","Macronsmall","bsuperior","nsuperior","msuperior","commasuperior","periodsuperior","Dotaccentsmall","Ringsmall","","","",""],Ci=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","","Adieresis","Aring","Ccedilla","Eacute","Ntilde","Odieresis","Udieresis","aacute","agrave","acircumflex","adieresis","atilde","aring","ccedilla","eacute","egrave","ecircumflex","edieresis","iacute","igrave","icircumflex","idieresis","ntilde","oacute","ograve","ocircumflex","odieresis","otilde","uacute","ugrave","ucircumflex","udieresis","dagger","degree","cent","sterling","section","bullet","paragraph","germandbls","registered","copyright","trademark","acute","dieresis","notequal","AE","Oslash","infinity","plusminus","lessequal","greaterequal","yen","mu","partialdiff","summation","product","pi","integral","ordfeminine","ordmasculine","Omega","ae","oslash","questiondown","exclamdown","logicalnot","radical","florin","approxequal","Delta","guillemotleft","guillemotright","ellipsis","space","Agrave","Atilde","Otilde","OE","oe","endash","emdash","quotedblleft","quotedblright","quoteleft","quoteright","divide","lozenge","ydieresis","Ydieresis","fraction","currency","guilsinglleft","guilsinglright","fi","fl","daggerdbl","periodcentered","quotesinglbase","quotedblbase","perthousand","Acircumflex","Ecircumflex","Aacute","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Oacute","Ocircumflex","apple","Ograve","Uacute","Ucircumflex","Ugrave","dotlessi","circumflex","tilde","macron","breve","dotaccent","ring","cedilla","hungarumlaut","ogonek","caron"],hi=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","","endash","dagger","daggerdbl","periodcentered","","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","","questiondown","","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","","ring","cedilla","","hungarumlaut","ogonek","caron","emdash","","","","","","","","","","","","","","","","","AE","","ordfeminine","","","","","Lslash","Oslash","OE","ordmasculine","","","","","","ae","","","","dotlessi","","","lslash","oslash","oe","germandbls","","","",""],li=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","bullet","Euro","bullet","quotesinglbase","florin","quotedblbase","ellipsis","dagger","daggerdbl","circumflex","perthousand","Scaron","guilsinglleft","OE","bullet","Zcaron","bullet","bullet","quoteleft","quoteright","quotedblleft","quotedblright","bullet","endash","emdash","tilde","trademark","scaron","guilsinglright","oe","bullet","zcaron","Ydieresis","space","exclamdown","cent","sterling","currency","yen","brokenbar","section","dieresis","copyright","ordfeminine","guillemotleft","logicalnot","hyphen","registered","macron","degree","plusminus","twosuperior","threesuperior","acute","mu","paragraph","periodcentered","cedilla","onesuperior","ordmasculine","guillemotright","onequarter","onehalf","threequarters","questiondown","Agrave","Aacute","Acircumflex","Atilde","Adieresis","Aring","AE","Ccedilla","Egrave","Eacute","Ecircumflex","Edieresis","Igrave","Iacute","Icircumflex","Idieresis","Eth","Ntilde","Ograve","Oacute","Ocircumflex","Otilde","Odieresis","multiply","Oslash","Ugrave","Uacute","Ucircumflex","Udieresis","Yacute","Thorn","germandbls","agrave","aacute","acircumflex","atilde","adieresis","aring","ae","ccedilla","egrave","eacute","ecircumflex","edieresis","igrave","iacute","icircumflex","idieresis","eth","ntilde","ograve","oacute","ocircumflex","otilde","odieresis","divide","oslash","ugrave","uacute","ucircumflex","udieresis","yacute","thorn","ydieresis"],Bi=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","universal","numbersign","existential","percent","ampersand","suchthat","parenleft","parenright","asteriskmath","plus","comma","minus","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","congruent","Alpha","Beta","Chi","Delta","Epsilon","Phi","Gamma","Eta","Iota","theta1","Kappa","Lambda","Mu","Nu","Omicron","Pi","Theta","Rho","Sigma","Tau","Upsilon","sigma1","Omega","Xi","Psi","Zeta","bracketleft","therefore","bracketright","perpendicular","underscore","radicalex","alpha","beta","chi","delta","epsilon","phi","gamma","eta","iota","phi1","kappa","lambda","mu","nu","omicron","pi","theta","rho","sigma","tau","upsilon","omega1","omega","xi","psi","zeta","braceleft","bar","braceright","similar","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","Euro","Upsilon1","minute","lessequal","fraction","infinity","florin","club","diamond","heart","spade","arrowboth","arrowleft","arrowup","arrowright","arrowdown","degree","plusminus","second","greaterequal","multiply","proportional","partialdiff","bullet","divide","notequal","equivalence","approxequal","ellipsis","arrowvertex","arrowhorizex","carriagereturn","aleph","Ifraktur","Rfraktur","weierstrass","circlemultiply","circleplus","emptyset","intersection","union","propersuperset","reflexsuperset","notsubset","propersubset","reflexsubset","element","notelement","angle","gradient","registerserif","copyrightserif","trademarkserif","product","radical","dotmath","logicalnot","logicaland","logicalor","arrowdblboth","arrowdblleft","arrowdblup","arrowdblright","arrowdbldown","lozenge","angleleft","registersans","copyrightsans","trademarksans","summation","parenlefttp","parenleftex","parenleftbt","bracketlefttp","bracketleftex","bracketleftbt","bracelefttp","braceleftmid","braceleftbt","braceex","","angleright","integral","integraltp","integralex","integralbt","parenrighttp","parenrightex","parenrightbt","bracketrighttp","bracketrightex","bracketrightbt","bracerighttp","bracerightmid","bracerightbt",""],Qi=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","a1","a2","a202","a3","a4","a5","a119","a118","a117","a11","a12","a13","a14","a15","a16","a105","a17","a18","a19","a20","a21","a22","a23","a24","a25","a26","a27","a28","a6","a7","a8","a9","a10","a29","a30","a31","a32","a33","a34","a35","a36","a37","a38","a39","a40","a41","a42","a43","a44","a45","a46","a47","a48","a49","a50","a51","a52","a53","a54","a55","a56","a57","a58","a59","a60","a61","a62","a63","a64","a65","a66","a67","a68","a69","a70","a71","a72","a73","a74","a203","a75","a204","a76","a77","a78","a79","a81","a82","a83","a84","a97","a98","a99","a100","","a89","a90","a93","a94","a91","a92","a205","a85","a206","a86","a87","a88","a95","a96","","","","","","","","","","","","","","","","","","","","a101","a102","a103","a104","a106","a107","a108","a112","a111","a110","a109","a120","a121","a122","a123","a124","a125","a126","a127","a128","a129","a130","a131","a132","a133","a134","a135","a136","a137","a138","a139","a140","a141","a142","a143","a144","a145","a146","a147","a148","a149","a150","a151","a152","a153","a154","a155","a156","a157","a158","a159","a160","a161","a163","a164","a196","a165","a192","a166","a167","a168","a169","a170","a171","a172","a173","a162","a174","a175","a176","a177","a178","a179","a193","a180","a199","a181","a200","a182","","a201","a183","a184","a197","a185","a194","a198","a186","a195","a187","a188","a189","a190","a191",""];function getEncoding(e){switch(e){case"WinAnsiEncoding":return li;case"StandardEncoding":return hi;case"MacRomanEncoding":return Ci;case"SymbolSetEncoding":return Bi;case"ZapfDingbatsEncoding":return Qi;case"ExpertEncoding":return Ii;case"MacExpertEncoding":return ci;default:return null}}const Ei=[".notdef","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","endash","dagger","daggerdbl","periodcentered","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","questiondown","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","ring","cedilla","hungarumlaut","ogonek","caron","emdash","AE","ordfeminine","Lslash","Oslash","OE","ordmasculine","ae","dotlessi","lslash","oslash","oe","germandbls","onesuperior","logicalnot","mu","trademark","Eth","onehalf","plusminus","Thorn","onequarter","divide","brokenbar","degree","thorn","threequarters","twosuperior","registered","minus","eth","multiply","threesuperior","copyright","Aacute","Acircumflex","Adieresis","Agrave","Aring","Atilde","Ccedilla","Eacute","Ecircumflex","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Ntilde","Oacute","Ocircumflex","Odieresis","Ograve","Otilde","Scaron","Uacute","Ucircumflex","Udieresis","Ugrave","Yacute","Ydieresis","Zcaron","aacute","acircumflex","adieresis","agrave","aring","atilde","ccedilla","eacute","ecircumflex","edieresis","egrave","iacute","icircumflex","idieresis","igrave","ntilde","oacute","ocircumflex","odieresis","ograve","otilde","scaron","uacute","ucircumflex","udieresis","ugrave","yacute","ydieresis","zcaron","exclamsmall","Hungarumlautsmall","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","commasuperior","threequartersemdash","periodsuperior","questionsmall","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","ffi","ffl","parenleftinferior","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","exclamdownsmall","centoldstyle","Lslashsmall","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","Dotaccentsmall","Macronsmall","figuredash","hypheninferior","Ogoneksmall","Ringsmall","Cedillasmall","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall","001.000","001.001","001.002","001.003","Black","Bold","Book","Light","Medium","Regular","Roman","Semibold"],ui=391,di=[null,{id:"hstem",min:2,stackClearing:!0,stem:!0},null,{id:"vstem",min:2,stackClearing:!0,stem:!0},{id:"vmoveto",min:1,stackClearing:!0},{id:"rlineto",min:2,resetStack:!0},{id:"hlineto",min:1,resetStack:!0},{id:"vlineto",min:1,resetStack:!0},{id:"rrcurveto",min:6,resetStack:!0},null,{id:"callsubr",min:1,undefStack:!0},{id:"return",min:0,undefStack:!0},null,null,{id:"endchar",min:0,stackClearing:!0},null,null,null,{id:"hstemhm",min:2,stackClearing:!0,stem:!0},{id:"hintmask",min:0,stackClearing:!0},{id:"cntrmask",min:0,stackClearing:!0},{id:"rmoveto",min:2,stackClearing:!0},{id:"hmoveto",min:1,stackClearing:!0},{id:"vstemhm",min:2,stackClearing:!0,stem:!0},{id:"rcurveline",min:8,resetStack:!0},{id:"rlinecurve",min:8,resetStack:!0},{id:"vvcurveto",min:4,resetStack:!0},{id:"hhcurveto",min:4,resetStack:!0},null,{id:"callgsubr",min:1,undefStack:!0},{id:"vhcurveto",min:4,resetStack:!0},{id:"hvcurveto",min:4,resetStack:!0}],fi=[null,null,null,{id:"and",min:2,stackDelta:-1},{id:"or",min:2,stackDelta:-1},{id:"not",min:1,stackDelta:0},null,null,null,{id:"abs",min:1,stackDelta:0},{id:"add",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]+e[t-1]}},{id:"sub",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]-e[t-1]}},{id:"div",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]/e[t-1]}},null,{id:"neg",min:1,stackDelta:0,stackFn(e,t){e[t-1]=-e[t-1]}},{id:"eq",min:2,stackDelta:-1},null,null,{id:"drop",min:1,stackDelta:-1},null,{id:"put",min:2,stackDelta:-2},{id:"get",min:1,stackDelta:0},{id:"ifelse",min:4,stackDelta:-3},{id:"random",min:0,stackDelta:1},{id:"mul",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]*e[t-1]}},null,{id:"sqrt",min:1,stackDelta:0},{id:"dup",min:1,stackDelta:1},{id:"exch",min:2,stackDelta:0},{id:"index",min:2,stackDelta:0},{id:"roll",min:3,stackDelta:-2},null,null,null,{id:"hflex",min:7,resetStack:!0},{id:"flex",min:13,resetStack:!0},{id:"hflex1",min:9,resetStack:!0},{id:"flex1",min:11,resetStack:!0}];class CFFParser{constructor(e,t,i){this.bytes=e.getBytes();this.properties=t;this.seacAnalysisEnabled=!!i}parse(){const e=this.properties,t=new CFF;this.cff=t;const i=this.parseHeader(),a=this.parseIndex(i.endPos),s=this.parseIndex(a.endPos),r=this.parseIndex(s.endPos),n=this.parseIndex(r.endPos),g=this.parseDict(s.obj.get(0)),o=this.createDict(CFFTopDict,g,t.strings);t.header=i.obj;t.names=this.parseNameIndex(a.obj);t.strings=this.parseStringIndex(r.obj);t.topDict=o;t.globalSubrIndex=n.obj;this.parsePrivateDict(t.topDict);t.isCIDFont=o.hasName("ROS");const c=o.getByName("CharStrings"),C=this.parseIndex(c).obj,h=o.getByName("FontMatrix");h&&(e.fontMatrix=h);const l=o.getByName("FontBBox");if(l){e.ascent=Math.max(l[3],l[1]);e.descent=Math.min(l[1],l[3]);e.ascentScaled=!0}let Q,E;if(t.isCIDFont){const e=this.parseIndex(o.getByName("FDArray")).obj;for(let i=0,a=e.count;i=t)throw new FormatError("Invalid CFF header");if(0!==i){info("cff data is shifted");e=e.subarray(i);this.bytes=e}const a=e[0],s=e[1],r=e[2],n=e[3];return{obj:new CFFHeader(a,s,r,n),endPos:r}}parseDict(e){let t=0;function parseOperand(){let i=e[t++];if(30===i)return function parseFloatOperand(){let i="";const a=15,s=["0","1","2","3","4","5","6","7","8","9",".","E","E-",null,"-"],r=e.length;for(;t>4,g=15&r;if(n===a)break;i+=s[n];if(g===a)break;i+=s[g]}return parseFloat(i)}();if(28===i){i=e[t++];i=(i<<24|e[t++]<<16)>>16;return i}if(29===i){i=e[t++];i=i<<8|e[t++];i=i<<8|e[t++];i=i<<8|e[t++];return i}if(i>=32&&i<=246)return i-139;if(i>=247&&i<=250)return 256*(i-247)+e[t++]+108;if(i>=251&&i<=254)return-256*(i-251)-e[t++]-108;warn('CFFParser_parseDict: "'+i+'" is a reserved command.');return NaN}let i=[];const a=[];t=0;const s=e.length;for(;t10)return!1;let s=e.stackSize;const r=e.stack;let n=t.length;for(let g=0;g>16;g+=2;s++}else if(14===o){if(s>=4){s-=4;if(this.seacAnalysisEnabled){e.seac=r.slice(s,s+4);return!1}}c=di[o]}else if(o>=32&&o<=246){r[s]=o-139;s++}else if(o>=247&&o<=254){r[s]=o<251?(o-247<<8)+t[g]+108:-(o-251<<8)-t[g]-108;g++;s++}else if(255===o){r[s]=(t[g]<<24|t[g+1]<<16|t[g+2]<<8|t[g+3])/65536;g+=4;s++}else if(19===o||20===o){e.hints+=s>>1;if(0===e.hints){t.copyWithin(g-1,g,-1);g-=1;n-=1;continue}g+=e.hints+7>>3;s%=2;c=di[o]}else{if(10===o||29===o){const t=10===o?i:a;if(!t){c=di[o];warn("Missing subrsIndex for "+c.id);return!1}let n=32768;t.count<1240?n=107:t.count<33900&&(n=1131);const g=r[--s]+n;if(g<0||g>=t.count||isNaN(g)){c=di[o];warn("Out of bounds subrIndex for "+c.id);return!1}e.stackSize=s;e.callDepth++;if(!this.parseCharString(e,t.get(g),i,a))return!1;e.callDepth--;s=e.stackSize;continue}if(11===o){e.stackSize=s;return!0}if(0===o&&g===t.length){t[g-1]=14;c=di[14]}else{if(9===o){t.copyWithin(g-1,g,-1);g-=1;n-=1;continue}c=di[o]}}if(c){if(c.stem){e.hints+=s>>1;if(3===o||23===o)e.hasVStems=!0;else if(e.hasVStems&&(1===o||18===o)){warn("CFF stem hints are in wrong order");t[g-1]=1===o?3:23}}if("min"in c&&!e.undefStack&&s=2&&c.stem?s%=2:s>1&&warn("Found too many parameters for stack-clearing command");s>0&&(e.width=r[s-1])}if("stackDelta"in c){"stackFn"in c&&c.stackFn(r,s);s+=c.stackDelta}else if(c.stackClearing)s=0;else if(c.resetStack){s=0;e.undefStack=!1}else if(c.undefStack){s=0;e.undefStack=!0;e.firstStackClearing=!1}}}n=s.length){warn("Invalid fd index for glyph index.");h=!1}if(h){Q=s[e].privateDict;l=Q.subrsIndex}}else t&&(l=t);h&&(h=this.parseCharString(C,o,l,i));if(null!==C.width){const e=Q.getByName("nominalWidthX");g[c]=e+C.width}else{const e=Q.getByName("defaultWidthX");g[c]=e}null!==C.seac&&(n[c]=C.seac);h||e.set(c,new Uint8Array([14]))}return{charStrings:e,seacs:n,widths:g}}emptyPrivateDictionary(e){const t=this.createDict(CFFPrivateDict,[],e.strings);e.setByKey(18,[0,0]);e.privateDict=t}parsePrivateDict(e){if(!e.hasName("Private")){this.emptyPrivateDictionary(e);return}const t=e.getByName("Private");if(!Array.isArray(t)||2!==t.length){e.removeByName("Private");return}const i=t[0],a=t[1];if(0===i||a>=this.bytes.length){this.emptyPrivateDictionary(e);return}const s=a+i,r=this.bytes.subarray(a,s),n=this.parseDict(r),g=this.createDict(CFFPrivateDict,n,e.strings);e.privateDict=g;0===g.getByName("ExpansionFactor")&&g.setByName("ExpansionFactor",.06);if(!g.getByName("Subrs"))return;const o=g.getByName("Subrs"),c=a+o;if(0===o||c>=this.bytes.length){this.emptyPrivateDictionary(e);return}const C=this.parseIndex(c);g.subrsIndex=C.obj}parseCharsets(e,t,i,a){if(0===e)return new CFFCharset(!0,yi.ISO_ADOBE,ni);if(1===e)return new CFFCharset(!0,yi.EXPERT,gi);if(2===e)return new CFFCharset(!0,yi.EXPERT_SUBSET,oi);const s=this.bytes,r=e,n=s[e++],g=[a?0:".notdef"];let o,c,C;t-=1;switch(n){case 0:for(C=0;C=65535){warn("Not enough space in charstrings to duplicate first glyph.");return}const e=this.charStrings.get(0);this.charStrings.add(e);this.isCIDFont&&this.fdSelect.fdSelect.push(this.fdSelect.fdSelect[0])}hasGlyphId(e){if(e<0||e>=this.charStrings.count)return!1;return this.charStrings.get(e).length>0}}class CFFHeader{constructor(e,t,i,a){this.major=e;this.minor=t;this.hdrSize=i;this.offSize=a}}class CFFStrings{constructor(){this.strings=[]}get(e){return e>=0&&e<=390?Ei[e]:e-ui<=this.strings.length?this.strings[e-ui]:Ei[0]}getSID(e){let t=Ei.indexOf(e);if(-1!==t)return t;t=this.strings.indexOf(e);return-1!==t?t+ui:-1}add(e){this.strings.push(e)}get count(){return this.strings.length}}class CFFIndex{constructor(){this.objects=[];this.length=0}add(e){this.length+=e.length;this.objects.push(e)}set(e,t){this.length+=t.length-this.objects[e].length;this.objects[e]=t}get(e){return this.objects[e]}get count(){return this.objects.length}}class CFFDict{constructor(e,t){this.keyToNameMap=e.keyToNameMap;this.nameToKeyMap=e.nameToKeyMap;this.defaults=e.defaults;this.types=e.types;this.opcodes=e.opcodes;this.order=e.order;this.strings=t;this.values=Object.create(null)}setByKey(e,t){if(!(e in this.keyToNameMap))return!1;if(0===t.length)return!0;for(const i of t)if(isNaN(i)){warn(`Invalid CFFDict value: "${t}" for key "${e}".`);return!0}const i=this.types[e];"num"!==i&&"sid"!==i&&"offset"!==i||(t=t[0]);this.values[e]=t;return!0}setByName(e,t){if(!(e in this.nameToKeyMap))throw new FormatError(`Invalid dictionary name "${e}"`);this.values[this.nameToKeyMap[e]]=t}hasName(e){return this.nameToKeyMap[e]in this.values}getByName(e){if(!(e in this.nameToKeyMap))throw new FormatError(`Invalid dictionary name ${e}"`);const t=this.nameToKeyMap[e];return t in this.values?this.values[t]:this.defaults[t]}removeByName(e){delete this.values[this.nameToKeyMap[e]]}static createTables(e){const t={keyToNameMap:{},nameToKeyMap:{},defaults:{},types:{},opcodes:{},order:[]};for(const i of e){const e=Array.isArray(i[0])?(i[0][0]<<8)+i[0][1]:i[0];t.keyToNameMap[e]=i[1];t.nameToKeyMap[i[1]]=e;t.types[e]=i[2];t.defaults[e]=i[3];t.opcodes[e]=Array.isArray(i[0])?i[0]:[i[0]];t.order.push(e)}return t}}const pi=[[[12,30],"ROS",["sid","sid","num"],null],[[12,20],"SyntheticBase","num",null],[0,"version","sid",null],[1,"Notice","sid",null],[[12,0],"Copyright","sid",null],[2,"FullName","sid",null],[3,"FamilyName","sid",null],[4,"Weight","sid",null],[[12,1],"isFixedPitch","num",0],[[12,2],"ItalicAngle","num",0],[[12,3],"UnderlinePosition","num",-100],[[12,4],"UnderlineThickness","num",50],[[12,5],"PaintType","num",0],[[12,6],"CharstringType","num",2],[[12,7],"FontMatrix",["num","num","num","num","num","num"],[.001,0,0,.001,0,0]],[13,"UniqueID","num",null],[5,"FontBBox",["num","num","num","num"],[0,0,0,0]],[[12,8],"StrokeWidth","num",0],[14,"XUID","array",null],[15,"charset","offset",0],[16,"Encoding","offset",0],[17,"CharStrings","offset",0],[18,"Private",["offset","offset"],null],[[12,21],"PostScript","sid",null],[[12,22],"BaseFontName","sid",null],[[12,23],"BaseFontBlend","delta",null],[[12,31],"CIDFontVersion","num",0],[[12,32],"CIDFontRevision","num",0],[[12,33],"CIDFontType","num",0],[[12,34],"CIDCount","num",8720],[[12,35],"UIDBase","num",null],[[12,37],"FDSelect","offset",null],[[12,36],"FDArray","offset",null],[[12,38],"FontName","sid",null]];class CFFTopDict extends CFFDict{static get tables(){return shadow(this,"tables",this.createTables(pi))}constructor(e){super(CFFTopDict.tables,e);this.privateDict=null}}const mi=[[6,"BlueValues","delta",null],[7,"OtherBlues","delta",null],[8,"FamilyBlues","delta",null],[9,"FamilyOtherBlues","delta",null],[[12,9],"BlueScale","num",.039625],[[12,10],"BlueShift","num",7],[[12,11],"BlueFuzz","num",1],[10,"StdHW","num",null],[11,"StdVW","num",null],[[12,12],"StemSnapH","delta",null],[[12,13],"StemSnapV","delta",null],[[12,14],"ForceBold","num",0],[[12,17],"LanguageGroup","num",0],[[12,18],"ExpansionFactor","num",.06],[[12,19],"initialRandomSeed","num",0],[20,"defaultWidthX","num",0],[21,"nominalWidthX","num",0],[19,"Subrs","offset",null]];class CFFPrivateDict extends CFFDict{static get tables(){return shadow(this,"tables",this.createTables(mi))}constructor(e){super(CFFPrivateDict.tables,e);this.subrsIndex=null}}const yi={ISO_ADOBE:0,EXPERT:1,EXPERT_SUBSET:2};class CFFCharset{constructor(e,t,i,a){this.predefined=e;this.format=t;this.charset=i;this.raw=a}}class CFFEncoding{constructor(e,t,i,a){this.predefined=e;this.format=t;this.encoding=i;this.raw=a}}class CFFFDSelect{constructor(e,t){this.format=e;this.fdSelect=t}getFDIndex(e){return e<0||e>=this.fdSelect.length?-1:this.fdSelect[e]}}class CFFOffsetTracker{constructor(){this.offsets=Object.create(null)}isTracking(e){return e in this.offsets}track(e,t){if(e in this.offsets)throw new FormatError(`Already tracking location of ${e}`);this.offsets[e]=t}offset(e){for(const t in this.offsets)this.offsets[t]+=e}setEntryLocation(e,t,i){if(!(e in this.offsets))throw new FormatError(`Not tracking location of ${e}`);const a=i.data,s=this.offsets[e];for(let e=0,i=t.length;e>24&255;a[n]=c>>16&255;a[g]=c>>8&255;a[o]=255&c}}}class CFFCompiler{constructor(e){this.cff=e}compile(){const e=this.cff,t={data:[],length:0,add(e){try{this.data.push(...e)}catch{this.data=this.data.concat(e)}this.length=this.data.length}},i=this.compileHeader(e.header);t.add(i);const a=this.compileNameIndex(e.names);t.add(a);if(e.isCIDFont&&e.topDict.hasName("FontMatrix")){const t=e.topDict.getByName("FontMatrix");e.topDict.removeByName("FontMatrix");for(const i of e.fdArray){let e=t.slice(0);i.hasName("FontMatrix")&&(e=Util.transform(e,i.getByName("FontMatrix")));i.setByName("FontMatrix",e)}}const s=e.topDict.getByName("XUID");s?.length>16&&e.topDict.removeByName("XUID");e.topDict.setByName("charset",0);let r=this.compileTopDicts([e.topDict],t.length,e.isCIDFont);t.add(r.output);const n=r.trackers[0],g=this.compileStringIndex(e.strings.strings);t.add(g);const o=this.compileIndex(e.globalSubrIndex);t.add(o);if(e.encoding&&e.topDict.hasName("Encoding"))if(e.encoding.predefined)n.setEntryLocation("Encoding",[e.encoding.format],t);else{const i=this.compileEncoding(e.encoding);n.setEntryLocation("Encoding",[t.length],t);t.add(i)}const c=this.compileCharset(e.charset,e.charStrings.count,e.strings,e.isCIDFont);n.setEntryLocation("charset",[t.length],t);t.add(c);const C=this.compileCharStrings(e.charStrings);n.setEntryLocation("CharStrings",[t.length],t);t.add(C);if(e.isCIDFont){n.setEntryLocation("FDSelect",[t.length],t);const i=this.compileFDSelect(e.fdSelect);t.add(i);r=this.compileTopDicts(e.fdArray,t.length,!0);n.setEntryLocation("FDArray",[t.length],t);t.add(r.output);const a=r.trackers;this.compilePrivateDicts(e.fdArray,a,t)}this.compilePrivateDicts([e.topDict],[n],t);t.add([0]);return t.data}encodeNumber(e){return Number.isInteger(e)?this.encodeInteger(e):this.encodeFloat(e)}static get EncodeFloatRegExp(){return shadow(this,"EncodeFloatRegExp",/\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/)}encodeFloat(e){let t=e.toString();const i=CFFCompiler.EncodeFloatRegExp.exec(t);if(i){const a=parseFloat("1e"+((i[2]?+i[2]:0)+i[1].length));t=(Math.round(e*a)/a).toString()}let a,s,r="";for(a=0,s=t.length;a=-107&&e<=107?[e+139]:e>=108&&e<=1131?[247+((e-=108)>>8),255&e]:e>=-1131&&e<=-108?[251+((e=-e-108)>>8),255&e]:e>=-32768&&e<=32767?[28,e>>8&255,255&e]:[29,e>>24&255,e>>16&255,e>>8&255,255&e];return t}compileHeader(e){return[e.major,e.minor,4,e.offSize]}compileNameIndex(e){const t=new CFFIndex;for(const i of e){const e=Math.min(i.length,127);let a=new Array(e);for(let t=0;t"~"||"["===e||"]"===e||"("===e||")"===e||"{"===e||"}"===e||"<"===e||">"===e||"/"===e||"%"===e)&&(e="_");a[t]=e}a=a.join("");""===a&&(a="Bad_Font_Name");t.add(stringToBytes(a))}return this.compileIndex(t)}compileTopDicts(e,t,i){const a=[];let s=new CFFIndex;for(const r of e){if(i){r.removeByName("CIDFontVersion");r.removeByName("CIDFontRevision");r.removeByName("CIDFontType");r.removeByName("CIDCount");r.removeByName("UIDBase")}const e=new CFFOffsetTracker,n=this.compileDict(r,e);a.push(e);s.add(n);e.offset(t)}s=this.compileIndex(s,a);return{trackers:a,output:s}}compilePrivateDicts(e,t,i){for(let a=0,s=e.length;a>8&255,255&r]);else{s=new Uint8Array(1+2*r);s[0]=0;let t=0;const a=e.charset.length;let n=!1;for(let r=1;r>8&255;s[r+1]=255&g}}return this.compileTypedArray(s)}compileEncoding(e){return this.compileTypedArray(e.raw)}compileFDSelect(e){const t=e.format;let i,a;switch(t){case 0:i=new Uint8Array(1+e.fdSelect.length);i[0]=t;for(a=0;a>8&255,255&s,r];for(a=1;a>8&255,255&a,t);r=t}}const g=(n.length-3)/3;n[1]=g>>8&255;n[2]=255&g;n.push(a>>8&255,255&a);i=new Uint8Array(n)}return this.compileTypedArray(i)}compileTypedArray(e){return Array.from(e)}compileIndex(e,t=[]){const i=e.objects,a=i.length;if(0===a)return[0,0];const s=[a>>8&255,255&a];let r,n,g=1;for(r=0;r>8&255,255&o):3===n?s.push(o>>16&255,o>>8&255,255&o):s.push(o>>>24&255,o>>16&255,o>>8&255,255&o);i[r]&&(o+=i[r].length)}for(r=0;r=5&&t<=7))return-1;a=e.substring(1)}if(a===a.toUpperCase()){i=parseInt(a,16);if(i>=0)return i}}return-1}const Fi=[[0,127],[128,255],[256,383],[384,591],[592,687,7424,7551,7552,7615],[688,767,42752,42783],[768,879,7616,7679],[880,1023],[11392,11519],[1024,1279,1280,1327,11744,11775,42560,42655],[1328,1423],[1424,1535],[42240,42559],[1536,1791,1872,1919],[1984,2047],[2304,2431],[2432,2559],[2560,2687],[2688,2815],[2816,2943],[2944,3071],[3072,3199],[3200,3327],[3328,3455],[3584,3711],[3712,3839],[4256,4351,11520,11567],[6912,7039],[4352,4607],[7680,7935,11360,11391,42784,43007],[7936,8191],[8192,8303,11776,11903],[8304,8351],[8352,8399],[8400,8447],[8448,8527],[8528,8591],[8592,8703,10224,10239,10496,10623,11008,11263],[8704,8959,10752,11007,10176,10223,10624,10751],[8960,9215],[9216,9279],[9280,9311],[9312,9471],[9472,9599],[9600,9631],[9632,9727],[9728,9983],[9984,10175],[12288,12351],[12352,12447],[12448,12543,12784,12799],[12544,12591,12704,12735],[12592,12687],[43072,43135],[12800,13055],[13056,13311],[44032,55215],[55296,57343],[67840,67871],[19968,40959,11904,12031,12032,12255,12272,12287,13312,19903,131072,173791,12688,12703],[57344,63743],[12736,12783,63744,64255,194560,195103],[64256,64335],[64336,65023],[65056,65071],[65040,65055],[65104,65135],[65136,65279],[65280,65519],[65520,65535],[3840,4095],[1792,1871],[1920,1983],[3456,3583],[4096,4255],[4608,4991,4992,5023,11648,11743],[5024,5119],[5120,5759],[5760,5791],[5792,5887],[6016,6143],[6144,6319],[10240,10495],[40960,42127],[5888,5919,5920,5951,5952,5983,5984,6015],[66304,66351],[66352,66383],[66560,66639],[118784,119039,119040,119295,119296,119375],[119808,120831],[1044480,1048573],[65024,65039,917760,917999],[917504,917631],[6400,6479],[6480,6527],[6528,6623],[6656,6687],[11264,11359],[11568,11647],[19904,19967],[43008,43055],[65536,65663,65664,65791,65792,65855],[65856,65935],[66432,66463],[66464,66527],[66640,66687],[66688,66735],[67584,67647],[68096,68191],[119552,119647],[73728,74751,74752,74879],[119648,119679],[7040,7103],[7168,7247],[7248,7295],[43136,43231],[43264,43311],[43312,43359],[43520,43615],[65936,65999],[66e3,66047],[66208,66271,66176,66207,67872,67903],[127024,127135,126976,127023]];function getUnicodeRangeFor(e,t=-1){if(-1!==t){const i=Fi[t];for(let a=0,s=i.length;a=i[a]&&e<=i[a+1])return t}for(let t=0,i=Fi.length;t=i[a]&&e<=i[a+1])return t}return-1}const Si=new RegExp("^(\\s)|(\\p{Mn})|(\\p{Cf})$","u"),ki=new Map;const Ri=!0,Ni=1,Gi=2,Mi=4,xi=32,Hi=[".notdef",".null","nonmarkingreturn","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","Adieresis","Aring","Ccedilla","Eacute","Ntilde","Odieresis","Udieresis","aacute","agrave","acircumflex","adieresis","atilde","aring","ccedilla","eacute","egrave","ecircumflex","edieresis","iacute","igrave","icircumflex","idieresis","ntilde","oacute","ograve","ocircumflex","odieresis","otilde","uacute","ugrave","ucircumflex","udieresis","dagger","degree","cent","sterling","section","bullet","paragraph","germandbls","registered","copyright","trademark","acute","dieresis","notequal","AE","Oslash","infinity","plusminus","lessequal","greaterequal","yen","mu","partialdiff","summation","product","pi","integral","ordfeminine","ordmasculine","Omega","ae","oslash","questiondown","exclamdown","logicalnot","radical","florin","approxequal","Delta","guillemotleft","guillemotright","ellipsis","nonbreakingspace","Agrave","Atilde","Otilde","OE","oe","endash","emdash","quotedblleft","quotedblright","quoteleft","quoteright","divide","lozenge","ydieresis","Ydieresis","fraction","currency","guilsinglleft","guilsinglright","fi","fl","daggerdbl","periodcentered","quotesinglbase","quotedblbase","perthousand","Acircumflex","Ecircumflex","Aacute","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Oacute","Ocircumflex","apple","Ograve","Uacute","Ucircumflex","Ugrave","dotlessi","circumflex","tilde","macron","breve","dotaccent","ring","cedilla","hungarumlaut","ogonek","caron","Lslash","lslash","Scaron","scaron","Zcaron","zcaron","brokenbar","Eth","eth","Yacute","yacute","Thorn","thorn","minus","multiply","onesuperior","twosuperior","threesuperior","onehalf","onequarter","threequarters","franc","Gbreve","gbreve","Idotaccent","Scedilla","scedilla","Cacute","cacute","Ccaron","ccaron","dcroat"];function recoverGlyphName(e,t){if(void 0!==t[e])return e;const i=getUnicodeForGlyph(e,t);if(-1!==i)for(const e in t)if(t[e]===i)return e;info("Unable to recover a standard glyph name for: "+e);return e}function type1FontGlyphMapping(e,t,i){const a=Object.create(null);let s,r,n;const g=!!(e.flags&Mi);if(e.isInternalFont){n=t;for(r=0;r=0?s:0}}else if(e.baseEncodingName){n=getEncoding(e.baseEncodingName);for(r=0;r=0?s:0}}else if(g)for(r in t)a[r]=t[r];else{n=hi;for(r=0;r=0?s:0}}const o=e.differences;let c;if(o)for(r in o){const e=o[r];s=i.indexOf(e);if(-1===s){c||(c=wi());const t=recoverGlyphName(e,c);t!==e&&(s=i.indexOf(t))}a[r]=s>=0?s:0}return a}function normalizeFontName(e){return e.replaceAll(/[,_]/g,"-").replaceAll(/\s/g,"")}const Ji=getLookupTableFactory((e=>{e[8211]=65074;e[8212]=65073;e[8229]=65072;e[8230]=65049;e[12289]=65041;e[12290]=65042;e[12296]=65087;e[12297]=65088;e[12298]=65085;e[12299]=65086;e[12300]=65089;e[12301]=65090;e[12302]=65091;e[12303]=65092;e[12304]=65083;e[12305]=65084;e[12308]=65081;e[12309]=65082;e[12310]=65047;e[12311]=65048;e[65103]=65076;e[65281]=65045;e[65288]=65077;e[65289]=65078;e[65292]=65040;e[65306]=65043;e[65307]=65044;e[65311]=65046;e[65339]=65095;e[65341]=65096;e[65343]=65075;e[65371]=65079;e[65373]=65080})),Yi=getLookupTableFactory((function(e){e["Times-Roman"]="Times-Roman";e.Helvetica="Helvetica";e.Courier="Courier";e.Symbol="Symbol";e["Times-Bold"]="Times-Bold";e["Helvetica-Bold"]="Helvetica-Bold";e["Courier-Bold"]="Courier-Bold";e.ZapfDingbats="ZapfDingbats";e["Times-Italic"]="Times-Italic";e["Helvetica-Oblique"]="Helvetica-Oblique";e["Courier-Oblique"]="Courier-Oblique";e["Times-BoldItalic"]="Times-BoldItalic";e["Helvetica-BoldOblique"]="Helvetica-BoldOblique";e["Courier-BoldOblique"]="Courier-BoldOblique";e.ArialNarrow="Helvetica";e["ArialNarrow-Bold"]="Helvetica-Bold";e["ArialNarrow-BoldItalic"]="Helvetica-BoldOblique";e["ArialNarrow-Italic"]="Helvetica-Oblique";e.ArialBlack="Helvetica";e["ArialBlack-Bold"]="Helvetica-Bold";e["ArialBlack-BoldItalic"]="Helvetica-BoldOblique";e["ArialBlack-Italic"]="Helvetica-Oblique";e["Arial-Black"]="Helvetica";e["Arial-Black-Bold"]="Helvetica-Bold";e["Arial-Black-BoldItalic"]="Helvetica-BoldOblique";e["Arial-Black-Italic"]="Helvetica-Oblique";e.Arial="Helvetica";e["Arial-Bold"]="Helvetica-Bold";e["Arial-BoldItalic"]="Helvetica-BoldOblique";e["Arial-Italic"]="Helvetica-Oblique";e.ArialMT="Helvetica";e["Arial-BoldItalicMT"]="Helvetica-BoldOblique";e["Arial-BoldMT"]="Helvetica-Bold";e["Arial-ItalicMT"]="Helvetica-Oblique";e["Arial-BoldItalicMT-BoldItalic"]="Helvetica-BoldOblique";e["Arial-BoldMT-Bold"]="Helvetica-Bold";e["Arial-ItalicMT-Italic"]="Helvetica-Oblique";e.ArialUnicodeMS="Helvetica";e["ArialUnicodeMS-Bold"]="Helvetica-Bold";e["ArialUnicodeMS-BoldItalic"]="Helvetica-BoldOblique";e["ArialUnicodeMS-Italic"]="Helvetica-Oblique";e["Courier-BoldItalic"]="Courier-BoldOblique";e["Courier-Italic"]="Courier-Oblique";e.CourierNew="Courier";e["CourierNew-Bold"]="Courier-Bold";e["CourierNew-BoldItalic"]="Courier-BoldOblique";e["CourierNew-Italic"]="Courier-Oblique";e["CourierNewPS-BoldItalicMT"]="Courier-BoldOblique";e["CourierNewPS-BoldMT"]="Courier-Bold";e["CourierNewPS-ItalicMT"]="Courier-Oblique";e.CourierNewPSMT="Courier";e["Helvetica-BoldItalic"]="Helvetica-BoldOblique";e["Helvetica-Italic"]="Helvetica-Oblique";e["HelveticaLTStd-Bold"]="Helvetica-Bold";e["Symbol-Bold"]="Symbol";e["Symbol-BoldItalic"]="Symbol";e["Symbol-Italic"]="Symbol";e.TimesNewRoman="Times-Roman";e["TimesNewRoman-Bold"]="Times-Bold";e["TimesNewRoman-BoldItalic"]="Times-BoldItalic";e["TimesNewRoman-Italic"]="Times-Italic";e.TimesNewRomanPS="Times-Roman";e["TimesNewRomanPS-Bold"]="Times-Bold";e["TimesNewRomanPS-BoldItalic"]="Times-BoldItalic";e["TimesNewRomanPS-BoldItalicMT"]="Times-BoldItalic";e["TimesNewRomanPS-BoldMT"]="Times-Bold";e["TimesNewRomanPS-Italic"]="Times-Italic";e["TimesNewRomanPS-ItalicMT"]="Times-Italic";e.TimesNewRomanPSMT="Times-Roman";e["TimesNewRomanPSMT-Bold"]="Times-Bold";e["TimesNewRomanPSMT-BoldItalic"]="Times-BoldItalic";e["TimesNewRomanPSMT-Italic"]="Times-Italic"})),vi=getLookupTableFactory((function(e){e.Courier="FoxitFixed.pfb";e["Courier-Bold"]="FoxitFixedBold.pfb";e["Courier-BoldOblique"]="FoxitFixedBoldItalic.pfb";e["Courier-Oblique"]="FoxitFixedItalic.pfb";e.Helvetica="LiberationSans-Regular.ttf";e["Helvetica-Bold"]="LiberationSans-Bold.ttf";e["Helvetica-BoldOblique"]="LiberationSans-BoldItalic.ttf";e["Helvetica-Oblique"]="LiberationSans-Italic.ttf";e["Times-Roman"]="FoxitSerif.pfb";e["Times-Bold"]="FoxitSerifBold.pfb";e["Times-BoldItalic"]="FoxitSerifBoldItalic.pfb";e["Times-Italic"]="FoxitSerifItalic.pfb";e.Symbol="FoxitSymbol.pfb";e.ZapfDingbats="FoxitDingbats.pfb";e["LiberationSans-Regular"]="LiberationSans-Regular.ttf";e["LiberationSans-Bold"]="LiberationSans-Bold.ttf";e["LiberationSans-Italic"]="LiberationSans-Italic.ttf";e["LiberationSans-BoldItalic"]="LiberationSans-BoldItalic.ttf"})),Ki=getLookupTableFactory((function(e){e.Calibri="Helvetica";e["Calibri-Bold"]="Helvetica-Bold";e["Calibri-BoldItalic"]="Helvetica-BoldOblique";e["Calibri-Italic"]="Helvetica-Oblique";e.CenturyGothic="Helvetica";e["CenturyGothic-Bold"]="Helvetica-Bold";e["CenturyGothic-BoldItalic"]="Helvetica-BoldOblique";e["CenturyGothic-Italic"]="Helvetica-Oblique";e.ComicSansMS="Comic Sans MS";e["ComicSansMS-Bold"]="Comic Sans MS-Bold";e["ComicSansMS-BoldItalic"]="Comic Sans MS-BoldItalic";e["ComicSansMS-Italic"]="Comic Sans MS-Italic";e.GillSansMT="Helvetica";e["GillSansMT-Bold"]="Helvetica-Bold";e["GillSansMT-BoldItalic"]="Helvetica-BoldOblique";e["GillSansMT-Italic"]="Helvetica-Oblique";e.Impact="Helvetica";e["ItcSymbol-Bold"]="Helvetica-Bold";e["ItcSymbol-BoldItalic"]="Helvetica-BoldOblique";e["ItcSymbol-Book"]="Helvetica";e["ItcSymbol-BookItalic"]="Helvetica-Oblique";e["ItcSymbol-Medium"]="Helvetica";e["ItcSymbol-MediumItalic"]="Helvetica-Oblique";e.LucidaConsole="Courier";e["LucidaConsole-Bold"]="Courier-Bold";e["LucidaConsole-BoldItalic"]="Courier-BoldOblique";e["LucidaConsole-Italic"]="Courier-Oblique";e["LucidaSans-Demi"]="Helvetica-Bold";e["MS-Gothic"]="MS Gothic";e["MS-Gothic-Bold"]="MS Gothic-Bold";e["MS-Gothic-BoldItalic"]="MS Gothic-BoldItalic";e["MS-Gothic-Italic"]="MS Gothic-Italic";e["MS-Mincho"]="MS Mincho";e["MS-Mincho-Bold"]="MS Mincho-Bold";e["MS-Mincho-BoldItalic"]="MS Mincho-BoldItalic";e["MS-Mincho-Italic"]="MS Mincho-Italic";e["MS-PGothic"]="MS PGothic";e["MS-PGothic-Bold"]="MS PGothic-Bold";e["MS-PGothic-BoldItalic"]="MS PGothic-BoldItalic";e["MS-PGothic-Italic"]="MS PGothic-Italic";e["MS-PMincho"]="MS PMincho";e["MS-PMincho-Bold"]="MS PMincho-Bold";e["MS-PMincho-BoldItalic"]="MS PMincho-BoldItalic";e["MS-PMincho-Italic"]="MS PMincho-Italic";e.NuptialScript="Times-Italic";e.SegoeUISymbol="Helvetica"})),Ti=getLookupTableFactory((function(e){e["Adobe Jenson"]=!0;e["Adobe Text"]=!0;e.Albertus=!0;e.Aldus=!0;e.Alexandria=!0;e.Algerian=!0;e["American Typewriter"]=!0;e.Antiqua=!0;e.Apex=!0;e.Arno=!0;e.Aster=!0;e.Aurora=!0;e.Baskerville=!0;e.Bell=!0;e.Bembo=!0;e["Bembo Schoolbook"]=!0;e.Benguiat=!0;e["Berkeley Old Style"]=!0;e["Bernhard Modern"]=!0;e["Berthold City"]=!0;e.Bodoni=!0;e["Bauer Bodoni"]=!0;e["Book Antiqua"]=!0;e.Bookman=!0;e["Bordeaux Roman"]=!0;e["Californian FB"]=!0;e.Calisto=!0;e.Calvert=!0;e.Capitals=!0;e.Cambria=!0;e.Cartier=!0;e.Caslon=!0;e.Catull=!0;e.Centaur=!0;e["Century Old Style"]=!0;e["Century Schoolbook"]=!0;e.Chaparral=!0;e["Charis SIL"]=!0;e.Cheltenham=!0;e["Cholla Slab"]=!0;e.Clarendon=!0;e.Clearface=!0;e.Cochin=!0;e.Colonna=!0;e["Computer Modern"]=!0;e["Concrete Roman"]=!0;e.Constantia=!0;e["Cooper Black"]=!0;e.Corona=!0;e.Ecotype=!0;e.Egyptienne=!0;e.Elephant=!0;e.Excelsior=!0;e.Fairfield=!0;e["FF Scala"]=!0;e.Folkard=!0;e.Footlight=!0;e.FreeSerif=!0;e["Friz Quadrata"]=!0;e.Garamond=!0;e.Gentium=!0;e.Georgia=!0;e.Gloucester=!0;e["Goudy Old Style"]=!0;e["Goudy Schoolbook"]=!0;e["Goudy Pro Font"]=!0;e.Granjon=!0;e["Guardian Egyptian"]=!0;e.Heather=!0;e.Hercules=!0;e["High Tower Text"]=!0;e.Hiroshige=!0;e["Hoefler Text"]=!0;e["Humana Serif"]=!0;e.Imprint=!0;e["Ionic No. 5"]=!0;e.Janson=!0;e.Joanna=!0;e.Korinna=!0;e.Lexicon=!0;e.LiberationSerif=!0;e["Liberation Serif"]=!0;e["Linux Libertine"]=!0;e.Literaturnaya=!0;e.Lucida=!0;e["Lucida Bright"]=!0;e.Melior=!0;e.Memphis=!0;e.Miller=!0;e.Minion=!0;e.Modern=!0;e["Mona Lisa"]=!0;e["Mrs Eaves"]=!0;e["MS Serif"]=!0;e["Museo Slab"]=!0;e["New York"]=!0;e["Nimbus Roman"]=!0;e["NPS Rawlinson Roadway"]=!0;e.NuptialScript=!0;e.Palatino=!0;e.Perpetua=!0;e.Plantin=!0;e["Plantin Schoolbook"]=!0;e.Playbill=!0;e["Poor Richard"]=!0;e["Rawlinson Roadway"]=!0;e.Renault=!0;e.Requiem=!0;e.Rockwell=!0;e.Roman=!0;e["Rotis Serif"]=!0;e.Sabon=!0;e.Scala=!0;e.Seagull=!0;e.Sistina=!0;e.Souvenir=!0;e.STIX=!0;e["Stone Informal"]=!0;e["Stone Serif"]=!0;e.Sylfaen=!0;e.Times=!0;e.Trajan=!0;e["Trinité"]=!0;e["Trump Mediaeval"]=!0;e.Utopia=!0;e["Vale Type"]=!0;e["Bitstream Vera"]=!0;e["Vera Serif"]=!0;e.Versailles=!0;e.Wanted=!0;e.Weiss=!0;e["Wide Latin"]=!0;e.Windsor=!0;e.XITS=!0})),qi=getLookupTableFactory((function(e){e.Dingbats=!0;e.Symbol=!0;e.ZapfDingbats=!0;e.Wingdings=!0;e["Wingdings-Bold"]=!0;e["Wingdings-Regular"]=!0})),Oi=getLookupTableFactory((function(e){e[2]=10;e[3]=32;e[4]=33;e[5]=34;e[6]=35;e[7]=36;e[8]=37;e[9]=38;e[10]=39;e[11]=40;e[12]=41;e[13]=42;e[14]=43;e[15]=44;e[16]=45;e[17]=46;e[18]=47;e[19]=48;e[20]=49;e[21]=50;e[22]=51;e[23]=52;e[24]=53;e[25]=54;e[26]=55;e[27]=56;e[28]=57;e[29]=58;e[30]=894;e[31]=60;e[32]=61;e[33]=62;e[34]=63;e[35]=64;e[36]=65;e[37]=66;e[38]=67;e[39]=68;e[40]=69;e[41]=70;e[42]=71;e[43]=72;e[44]=73;e[45]=74;e[46]=75;e[47]=76;e[48]=77;e[49]=78;e[50]=79;e[51]=80;e[52]=81;e[53]=82;e[54]=83;e[55]=84;e[56]=85;e[57]=86;e[58]=87;e[59]=88;e[60]=89;e[61]=90;e[62]=91;e[63]=92;e[64]=93;e[65]=94;e[66]=95;e[67]=96;e[68]=97;e[69]=98;e[70]=99;e[71]=100;e[72]=101;e[73]=102;e[74]=103;e[75]=104;e[76]=105;e[77]=106;e[78]=107;e[79]=108;e[80]=109;e[81]=110;e[82]=111;e[83]=112;e[84]=113;e[85]=114;e[86]=115;e[87]=116;e[88]=117;e[89]=118;e[90]=119;e[91]=120;e[92]=121;e[93]=122;e[94]=123;e[95]=124;e[96]=125;e[97]=126;e[98]=196;e[99]=197;e[100]=199;e[101]=201;e[102]=209;e[103]=214;e[104]=220;e[105]=225;e[106]=224;e[107]=226;e[108]=228;e[109]=227;e[110]=229;e[111]=231;e[112]=233;e[113]=232;e[114]=234;e[115]=235;e[116]=237;e[117]=236;e[118]=238;e[119]=239;e[120]=241;e[121]=243;e[122]=242;e[123]=244;e[124]=246;e[125]=245;e[126]=250;e[127]=249;e[128]=251;e[129]=252;e[130]=8224;e[131]=176;e[132]=162;e[133]=163;e[134]=167;e[135]=8226;e[136]=182;e[137]=223;e[138]=174;e[139]=169;e[140]=8482;e[141]=180;e[142]=168;e[143]=8800;e[144]=198;e[145]=216;e[146]=8734;e[147]=177;e[148]=8804;e[149]=8805;e[150]=165;e[151]=181;e[152]=8706;e[153]=8721;e[154]=8719;e[156]=8747;e[157]=170;e[158]=186;e[159]=8486;e[160]=230;e[161]=248;e[162]=191;e[163]=161;e[164]=172;e[165]=8730;e[166]=402;e[167]=8776;e[168]=8710;e[169]=171;e[170]=187;e[171]=8230;e[179]=8220;e[180]=8221;e[181]=8216;e[182]=8217;e[200]=193;e[203]=205;e[207]=211;e[210]=218;e[223]=711;e[224]=321;e[225]=322;e[226]=352;e[227]=353;e[228]=381;e[229]=382;e[233]=221;e[234]=253;e[252]=263;e[253]=268;e[254]=269;e[258]=258;e[260]=260;e[261]=261;e[265]=280;e[266]=281;e[267]=282;e[268]=283;e[269]=313;e[275]=323;e[276]=324;e[278]=328;e[283]=344;e[284]=345;e[285]=346;e[286]=347;e[292]=367;e[295]=377;e[296]=378;e[298]=380;e[305]=963;e[306]=964;e[307]=966;e[308]=8215;e[309]=8252;e[310]=8319;e[311]=8359;e[312]=8592;e[313]=8593;e[337]=9552;e[493]=1039;e[494]=1040;e[672]=1488;e[673]=1489;e[674]=1490;e[675]=1491;e[676]=1492;e[677]=1493;e[678]=1494;e[679]=1495;e[680]=1496;e[681]=1497;e[682]=1498;e[683]=1499;e[684]=1500;e[685]=1501;e[686]=1502;e[687]=1503;e[688]=1504;e[689]=1505;e[690]=1506;e[691]=1507;e[692]=1508;e[693]=1509;e[694]=1510;e[695]=1511;e[696]=1512;e[697]=1513;e[698]=1514;e[705]=1524;e[706]=8362;e[710]=64288;e[711]=64298;e[759]=1617;e[761]=1776;e[763]=1778;e[775]=1652;e[777]=1764;e[778]=1780;e[779]=1781;e[780]=1782;e[782]=771;e[783]=64726;e[786]=8363;e[788]=8532;e[790]=768;e[791]=769;e[792]=768;e[795]=803;e[797]=64336;e[798]=64337;e[799]=64342;e[800]=64343;e[801]=64344;e[802]=64345;e[803]=64362;e[804]=64363;e[805]=64364;e[2424]=7821;e[2425]=7822;e[2426]=7823;e[2427]=7824;e[2428]=7825;e[2429]=7826;e[2430]=7827;e[2433]=7682;e[2678]=8045;e[2679]=8046;e[2830]=1552;e[2838]=686;e[2840]=751;e[2842]=753;e[2843]=754;e[2844]=755;e[2846]=757;e[2856]=767;e[2857]=848;e[2858]=849;e[2862]=853;e[2863]=854;e[2864]=855;e[2865]=861;e[2866]=862;e[2906]=7460;e[2908]=7462;e[2909]=7463;e[2910]=7464;e[2912]=7466;e[2913]=7467;e[2914]=7468;e[2916]=7470;e[2917]=7471;e[2918]=7472;e[2920]=7474;e[2921]=7475;e[2922]=7476;e[2924]=7478;e[2925]=7479;e[2926]=7480;e[2928]=7482;e[2929]=7483;e[2930]=7484;e[2932]=7486;e[2933]=7487;e[2934]=7488;e[2936]=7490;e[2937]=7491;e[2938]=7492;e[2940]=7494;e[2941]=7495;e[2942]=7496;e[2944]=7498;e[2946]=7500;e[2948]=7502;e[2950]=7504;e[2951]=7505;e[2952]=7506;e[2954]=7508;e[2955]=7509;e[2956]=7510;e[2958]=7512;e[2959]=7513;e[2960]=7514;e[2962]=7516;e[2963]=7517;e[2964]=7518;e[2966]=7520;e[2967]=7521;e[2968]=7522;e[2970]=7524;e[2971]=7525;e[2972]=7526;e[2974]=7528;e[2975]=7529;e[2976]=7530;e[2978]=1537;e[2979]=1538;e[2980]=1539;e[2982]=1549;e[2983]=1551;e[2984]=1552;e[2986]=1554;e[2987]=1555;e[2988]=1556;e[2990]=1623;e[2991]=1624;e[2995]=1775;e[2999]=1791;e[3002]=64290;e[3003]=64291;e[3004]=64292;e[3006]=64294;e[3007]=64295;e[3008]=64296;e[3011]=1900;e[3014]=8223;e[3015]=8244;e[3017]=7532;e[3018]=7533;e[3019]=7534;e[3075]=7590;e[3076]=7591;e[3079]=7594;e[3080]=7595;e[3083]=7598;e[3084]=7599;e[3087]=7602;e[3088]=7603;e[3091]=7606;e[3092]=7607;e[3095]=7610;e[3096]=7611;e[3099]=7614;e[3100]=7615;e[3103]=7618;e[3104]=7619;e[3107]=8337;e[3108]=8338;e[3116]=1884;e[3119]=1885;e[3120]=1885;e[3123]=1886;e[3124]=1886;e[3127]=1887;e[3128]=1887;e[3131]=1888;e[3132]=1888;e[3135]=1889;e[3136]=1889;e[3139]=1890;e[3140]=1890;e[3143]=1891;e[3144]=1891;e[3147]=1892;e[3148]=1892;e[3153]=580;e[3154]=581;e[3157]=584;e[3158]=585;e[3161]=588;e[3162]=589;e[3165]=891;e[3166]=892;e[3169]=1274;e[3170]=1275;e[3173]=1278;e[3174]=1279;e[3181]=7622;e[3182]=7623;e[3282]=11799;e[3316]=578;e[3379]=42785;e[3393]=1159;e[3416]=8377})),Pi=getLookupTableFactory((function(e){e[227]=322;e[264]=261;e[291]=346})),Wi=getLookupTableFactory((function(e){e[1]=32;e[4]=65;e[5]=192;e[6]=193;e[9]=196;e[17]=66;e[18]=67;e[21]=268;e[24]=68;e[28]=69;e[29]=200;e[30]=201;e[32]=282;e[38]=70;e[39]=71;e[44]=72;e[47]=73;e[48]=204;e[49]=205;e[58]=74;e[60]=75;e[62]=76;e[68]=77;e[69]=78;e[75]=79;e[76]=210;e[80]=214;e[87]=80;e[89]=81;e[90]=82;e[92]=344;e[94]=83;e[97]=352;e[100]=84;e[104]=85;e[109]=220;e[115]=86;e[116]=87;e[121]=88;e[122]=89;e[124]=221;e[127]=90;e[129]=381;e[258]=97;e[259]=224;e[260]=225;e[263]=228;e[268]=261;e[271]=98;e[272]=99;e[273]=263;e[275]=269;e[282]=100;e[286]=101;e[287]=232;e[288]=233;e[290]=283;e[295]=281;e[296]=102;e[336]=103;e[346]=104;e[349]=105;e[350]=236;e[351]=237;e[361]=106;e[364]=107;e[367]=108;e[371]=322;e[373]=109;e[374]=110;e[381]=111;e[382]=242;e[383]=243;e[386]=246;e[393]=112;e[395]=113;e[396]=114;e[398]=345;e[400]=115;e[401]=347;e[403]=353;e[410]=116;e[437]=117;e[442]=252;e[448]=118;e[449]=119;e[454]=120;e[455]=121;e[457]=253;e[460]=122;e[462]=382;e[463]=380;e[853]=44;e[855]=58;e[856]=46;e[876]=47;e[878]=45;e[882]=45;e[894]=40;e[895]=41;e[896]=91;e[897]=93;e[923]=64;e[1004]=48;e[1005]=49;e[1006]=50;e[1007]=51;e[1008]=52;e[1009]=53;e[1010]=54;e[1011]=55;e[1012]=56;e[1013]=57;e[1081]=37;e[1085]=43;e[1086]=45}));function getStandardFontName(e){const t=normalizeFontName(e);return Yi()[t]}function isKnownFontName(e){const t=normalizeFontName(e);return!!(Yi()[t]||Ki()[t]||Ti()[t]||qi()[t])}class ToUnicodeMap{constructor(e=[]){this._map=e}get length(){return this._map.length}forEach(e){for(const t in this._map)e(t,this._map[t].codePointAt(0))}has(e){return void 0!==this._map[e]}get(e){return this._map[e]}charCodeOf(e){const t=this._map;if(t.length<=65536)return t.indexOf(e);for(const i in t)if(t[i]===e)return 0|i;return-1}amend(e){for(const t in e)this._map[t]=e[t]}}class IdentityToUnicodeMap{constructor(e,t){this.firstChar=e;this.lastChar=t}get length(){return this.lastChar+1-this.firstChar}forEach(e){for(let t=this.firstChar,i=this.lastChar;t<=i;t++)e(t,t)}has(e){return this.firstChar<=e&&e<=this.lastChar}get(e){if(this.firstChar<=e&&e<=this.lastChar)return String.fromCharCode(e)}charCodeOf(e){return Number.isInteger(e)&&e>=this.firstChar&&e<=this.lastChar?e:-1}amend(e){unreachable("Should not call amend()")}}class CFFFont{constructor(e,t){this.properties=t;const i=new CFFParser(e,t,Ri);this.cff=i.parse();this.cff.duplicateFirstGlyph();const a=new CFFCompiler(this.cff);this.seacs=this.cff.seacs;try{this.data=a.compile()}catch{warn("Failed to compile font "+t.loadedName);this.data=e}this._createBuiltInEncoding()}get numGlyphs(){return this.cff.charStrings.count}getCharset(){return this.cff.charset.charset}getGlyphMapping(){const e=this.cff,t=this.properties,{cidToGidMap:i,cMap:a}=t,s=e.charset.charset;let r,n;if(t.composite){let t,g;if(i?.length>0){t=Object.create(null);for(let e=0,a=i.length;e=0){const a=i[t];a&&(s[e]=a)}}s.length>0&&(this.properties.builtInEncoding=s)}}function getUint32(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}function getUint16(e,t){return e[t]<<8|e[t+1]}function getInt16(e,t){return(e[t]<<24|e[t+1]<<16)>>16}function getInt8(e,t){return e[t]<<24>>24}function getFloat214(e,t){return getInt16(e,t)/16384}function getSubroutineBias(e){const t=e.length;let i=32768;t<1240?i=107:t<33900&&(i=1131);return i}function parseCmap(e,t,i){const a=1===getUint16(e,t+2)?getUint32(e,t+8):getUint32(e,t+16),s=getUint16(e,t+a);let r,n,g;if(4===s){getUint16(e,t+a+2);const i=getUint16(e,t+a+6)>>1;n=t+a+14;r=[];for(g=0;g>1;i0;)C.push({flags:r})}for(i=0;i>1;p=!0;break;case 4:n+=s.pop();moveTo(r,n);p=!0;break;case 5:for(;s.length>0;){r+=s.shift();n+=s.shift();lineTo(r,n)}break;case 6:for(;s.length>0;){r+=s.shift();lineTo(r,n);if(0===s.length)break;n+=s.shift();lineTo(r,n)}break;case 7:for(;s.length>0;){n+=s.shift();lineTo(r,n);if(0===s.length)break;r+=s.shift();lineTo(r,n)}break;case 8:for(;s.length>0;){c=r+s.shift();h=n+s.shift();C=c+s.shift();l=h+s.shift();r=C+s.shift();n=l+s.shift();bezierCurveTo(c,h,C,l,r,n)}break;case 10:d=s.pop();f=null;if(i.isCFFCIDFont){const e=i.fdSelect.getFDIndex(a);if(e>=0&&eMath.abs(n-t)?r+=s.shift():n+=s.shift();bezierCurveTo(c,h,C,l,r,n);break;default:throw new FormatError(`unknown operator: 12 ${m}`)}break;case 14:if(s.length>=4){const e=s.pop(),a=s.pop();n=s.pop();r=s.pop();t.save();t.translate(r,n);let g=lookupCmap(i.cmap,String.fromCharCode(i.glyphNameMap[hi[e]]));compileCharString(i.glyphs[g.glyphId],t,i,g.glyphId);t.restore();g=lookupCmap(i.cmap,String.fromCharCode(i.glyphNameMap[hi[a]]));compileCharString(i.glyphs[g.glyphId],t,i,g.glyphId)}return;case 19:case 20:g+=s.length>>1;o+=g+7>>3;p=!0;break;case 21:n+=s.pop();r+=s.pop();moveTo(r,n);p=!0;break;case 22:r+=s.pop();moveTo(r,n);p=!0;break;case 24:for(;s.length>2;){c=r+s.shift();h=n+s.shift();C=c+s.shift();l=h+s.shift();r=C+s.shift();n=l+s.shift();bezierCurveTo(c,h,C,l,r,n)}r+=s.shift();n+=s.shift();lineTo(r,n);break;case 25:for(;s.length>6;){r+=s.shift();n+=s.shift();lineTo(r,n)}c=r+s.shift();h=n+s.shift();C=c+s.shift();l=h+s.shift();r=C+s.shift();n=l+s.shift();bezierCurveTo(c,h,C,l,r,n);break;case 26:s.length%2&&(r+=s.shift());for(;s.length>0;){c=r;h=n+s.shift();C=c+s.shift();l=h+s.shift();r=C;n=l+s.shift();bezierCurveTo(c,h,C,l,r,n)}break;case 27:s.length%2&&(n+=s.shift());for(;s.length>0;){c=r+s.shift();h=n;C=c+s.shift();l=h+s.shift();r=C+s.shift();n=l;bezierCurveTo(c,h,C,l,r,n)}break;case 28:s.push((e[o]<<24|e[o+1]<<16)>>16);o+=2;break;case 29:d=s.pop()+i.gsubrsBias;f=i.gsubrs[d];f&&parse(f);break;case 30:for(;s.length>0;){c=r;h=n+s.shift();C=c+s.shift();l=h+s.shift();r=C+s.shift();n=l+(1===s.length?s.shift():0);bezierCurveTo(c,h,C,l,r,n);if(0===s.length)break;c=r+s.shift();h=n;C=c+s.shift();l=h+s.shift();n=l+s.shift();r=C+(1===s.length?s.shift():0);bezierCurveTo(c,h,C,l,r,n)}break;case 31:for(;s.length>0;){c=r+s.shift();h=n;C=c+s.shift();l=h+s.shift();n=l+s.shift();r=C+(1===s.length?s.shift():0);bezierCurveTo(c,h,C,l,r,n);if(0===s.length)break;c=r;h=n+s.shift();C=c+s.shift();l=h+s.shift();r=C+s.shift();n=l+(1===s.length?s.shift():0);bezierCurveTo(c,h,C,l,r,n)}break;default:if(m<32)throw new FormatError(`unknown operator: ${m}`);if(m<247)s.push(m-139);else if(m<251)s.push(256*(m-247)+e[o++]+108);else if(m<255)s.push(256*-(m-251)-e[o++]-108);else{s.push((e[o]<<24|e[o+1]<<16|e[o+2]<<8|e[o+3])/65536);o+=4}}p&&(s.length=0)}}(e)}class Commands{cmds=[];transformStack=[];currentTransform=[1,0,0,1,0,0];add(e,t){if(t){const[i,a,s,r,n,g]=this.currentTransform;for(let e=0,o=t.length;e=0&&e2*getUint16(e,t)}const r=[];let n=s(t,0);for(let i=a;ie+(t.getSize()+3&-4)),0)}write(){const e=this.getSize(),t=new DataView(new ArrayBuffer(e)),i=e>131070,a=i?4:2,s=new DataView(new ArrayBuffer((this.glyphs.length+1)*a));i?s.setUint32(0,0):s.setUint16(0,0);let r=0,n=0;for(const e of this.glyphs){r+=e.write(r,t);r=r+3&-4;n+=a;i?s.setUint32(n,r):s.setUint16(n,r>>1)}return{isLocationLong:i,loca:new Uint8Array(s.buffer),glyf:new Uint8Array(t.buffer)}}scale(e){for(let t=0,i=this.glyphs.length;te+t.getSize()),0);return this.header.getSize()+e}write(e,t){if(!this.header)return 0;const i=e;e+=this.header.write(e,t);if(this.simple)e+=this.simple.write(e,t);else for(const i of this.composites)e+=i.write(e,t);return e-i}scale(e){if(!this.header)return;const t=(this.header.xMin+this.header.xMax)/2;this.header.scale(t,e);if(this.simple)this.simple.scale(t,e);else for(const i of this.composites)i.scale(t,e)}}class GlyphHeader{constructor({numberOfContours:e,xMin:t,yMin:i,xMax:a,yMax:s}){this.numberOfContours=e;this.xMin=t;this.yMin=i;this.xMax=a;this.yMax=s}static parse(e,t){return[10,new GlyphHeader({numberOfContours:t.getInt16(e),xMin:t.getInt16(e+2),yMin:t.getInt16(e+4),xMax:t.getInt16(e+6),yMax:t.getInt16(e+8)})]}getSize(){return 10}write(e,t){t.setInt16(e,this.numberOfContours);t.setInt16(e+2,this.xMin);t.setInt16(e+4,this.yMin);t.setInt16(e+6,this.xMax);t.setInt16(e+8,this.yMax);return 10}scale(e,t){this.xMin=Math.round(e+(this.xMin-e)*t);this.xMax=Math.round(e+(this.xMax-e)*t)}}class Contour{constructor({flags:e,xCoordinates:t,yCoordinates:i}){this.xCoordinates=t;this.yCoordinates=i;this.flags=e}}class SimpleGlyph{constructor({contours:e,instructions:t}){this.contours=e;this.instructions=t}static parse(e,t,i){const a=[];for(let s=0;s255?e+=2:g>0&&(e+=1);t=r;g=Math.abs(n-i);g>255?e+=2:g>0&&(e+=1);i=n}}return e}write(e,t){const i=e,a=[],s=[],r=[];let n=0,g=0;for(const i of this.contours){for(let e=0,t=i.xCoordinates.length;e=0?18:2;a.push(e)}else a.push(c)}n=o;const C=i.yCoordinates[e];c=C-g;if(0===c){t|=32;s.push(0)}else{const e=Math.abs(c);if(e<=255){t|=c>=0?36:4;s.push(e)}else s.push(c)}g=C;r.push(t)}t.setUint16(e,a.length-1);e+=2}t.setUint16(e,this.instructions.length);e+=2;if(this.instructions.length){new Uint8Array(t.buffer,0,t.buffer.byteLength).set(this.instructions,e);e+=this.instructions.length}for(const i of r)t.setUint8(e++,i);for(let i=0,s=a.length;i=-128&&this.argument1<=127&&this.argument2>=-128&&this.argument2<=127||(e+=2):this.argument1>=0&&this.argument1<=255&&this.argument2>=0&&this.argument2<=255||(e+=2);return e}write(e,t){const i=e;2&this.flags?this.argument1>=-128&&this.argument1<=127&&this.argument2>=-128&&this.argument2<=127||(this.flags|=1):this.argument1>=0&&this.argument1<=255&&this.argument2>=0&&this.argument2<=255||(this.flags|=1);t.setUint16(e,this.flags);t.setUint16(e+2,this.glyphIndex);e+=4;if(1&this.flags){if(2&this.flags){t.setInt16(e,this.argument1);t.setInt16(e+2,this.argument2)}else{t.setUint16(e,this.argument1);t.setUint16(e+2,this.argument2)}e+=4}else{t.setUint8(e,this.argument1);t.setUint8(e+1,this.argument2);e+=2}if(256&this.flags){t.setUint16(e,this.instructions.length);e+=2;if(this.instructions.length){new Uint8Array(t.buffer,0,t.buffer.byteLength).set(this.instructions,e);e+=this.instructions.length}}return e-i}scale(e,t){}}function writeInt16(e,t,i){e[t]=i>>8&255;e[t+1]=255&i}function writeInt32(e,t,i){e[t]=i>>24&255;e[t+1]=i>>16&255;e[t+2]=i>>8&255;e[t+3]=255&i}function writeData(e,t,i){if(i instanceof Uint8Array)e.set(i,t);else if("string"==typeof i)for(let a=0,s=i.length;ai;){i<<=1;a++}const s=i*t;return{range:s,entry:a,rangeShift:t*e-s}}toArray(){let e=this.sfnt;const t=this.tables,i=Object.keys(t);i.sort();const a=i.length;let s,r,n,g,o,c=12+16*a;const C=[c];for(s=0;s>>0;C.push(c)}const h=new Uint8Array(c);for(s=0;s>>0}writeInt32(h,c+4,e);writeInt32(h,c+8,C[s]);writeInt32(h,c+12,t[o].length);c+=16}return h}addTable(e,t){if(e in this.tables)throw new Error("Table "+e+" already exists");this.tables[e]=t}}const Zi=[4],Vi=[5],zi=[6],_i=[7],$i=[8],Aa=[12,35],ea=[14],ta=[21],ia=[22],aa=[30],sa=[31];class Type1CharString{constructor(){this.width=0;this.lsb=0;this.flexing=!1;this.output=[];this.stack=[]}convert(e,t,i){const a=e.length;let s,r,n,g=!1;for(let o=0;oa)return!0;const s=a-e;for(let e=s;e>8&255,255&t);else{t=65536*t|0;this.output.push(255,t>>24&255,t>>16&255,t>>8&255,255&t)}}this.output.push(...t);i?this.stack.splice(s,e):this.stack.length=0;return!1}}function isHexDigit(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function decrypt(e,t,i){if(i>=e.length)return new Uint8Array(0);let a,s,r=0|t;for(a=0;a>8;r=52845*(t+r)+22719&65535}return g}function isSpecial(e){return 47===e||91===e||93===e||123===e||125===e||40===e||41===e}class Type1Parser{constructor(e,t,i){if(t){const t=e.getBytes(),i=!((isHexDigit(t[0])||isWhiteSpace(t[0]))&&isHexDigit(t[1])&&isHexDigit(t[2])&&isHexDigit(t[3])&&isHexDigit(t[4])&&isHexDigit(t[5])&&isHexDigit(t[6])&&isHexDigit(t[7]));e=new Stream(i?decrypt(t,55665,4):function decryptAscii(e,t,i){let a=0|t;const s=e.length,r=new Uint8Array(s>>>1);let n,g;for(n=0,g=0;n>8;a=52845*(e+a)+22719&65535}}return r.slice(i,g)}(t,55665,4))}this.seacAnalysisEnabled=!!i;this.stream=e;this.nextChar()}readNumberArray(){this.getToken();const e=[];for(;;){const t=this.getToken();if(null===t||"]"===t||"}"===t)break;e.push(parseFloat(t||0))}return e}readNumber(){const e=this.getToken();return parseFloat(e||0)}readInt(){const e=this.getToken();return 0|parseInt(e||0,10)}readBoolean(){return"true"===this.getToken()?1:0}nextChar(){return this.currentChar=this.stream.getByte()}prevChar(){this.stream.skip(-2);return this.currentChar=this.stream.getByte()}getToken(){let e=!1,t=this.currentChar;for(;;){if(-1===t)return null;if(e)10!==t&&13!==t||(e=!1);else if(37===t)e=!0;else if(!isWhiteSpace(t))break;t=this.nextChar()}if(isSpecial(t)){this.nextChar();return String.fromCharCode(t)}let i="";do{i+=String.fromCharCode(t);t=this.nextChar()}while(t>=0&&!isWhiteSpace(t)&&!isSpecial(t));return i}readCharStrings(e,t){return-1===t?e:decrypt(e,4330,t)}extractFontProgram(e){const t=this.stream,i=[],a=[],s=Object.create(null);s.lenIV=4;const r={subrs:[],charstrings:[],properties:{privateData:s}};let n,g,o,c;for(;null!==(n=this.getToken());)if("/"===n){n=this.getToken();switch(n){case"CharStrings":this.getToken();this.getToken();this.getToken();this.getToken();for(;;){n=this.getToken();if(null===n||"end"===n)break;if("/"!==n)continue;const e=this.getToken();g=this.readInt();this.getToken();o=g>0?t.getBytes(g):new Uint8Array(0);c=r.properties.privateData.lenIV;const i=this.readCharStrings(o,c);this.nextChar();n=this.getToken();"noaccess"===n?this.getToken():"/"===n&&this.prevChar();a.push({glyph:e,encoded:i})}break;case"Subrs":this.readInt();this.getToken();for(;"dup"===this.getToken();){const e=this.readInt();g=this.readInt();this.getToken();o=g>0?t.getBytes(g):new Uint8Array(0);c=r.properties.privateData.lenIV;const a=this.readCharStrings(o,c);this.nextChar();n=this.getToken();"noaccess"===n&&this.getToken();i[e]=a}break;case"BlueValues":case"OtherBlues":case"FamilyBlues":case"FamilyOtherBlues":const e=this.readNumberArray();e.length>0&&e.length,0;break;case"StemSnapH":case"StemSnapV":r.properties.privateData[n]=this.readNumberArray();break;case"StdHW":case"StdVW":r.properties.privateData[n]=this.readNumberArray()[0];break;case"BlueShift":case"lenIV":case"BlueFuzz":case"BlueScale":case"LanguageGroup":r.properties.privateData[n]=this.readNumber();break;case"ExpansionFactor":r.properties.privateData[n]=this.readNumber()||.06;break;case"ForceBold":r.properties.privateData[n]=this.readBoolean()}}for(const{encoded:t,glyph:s}of a){const a=new Type1CharString,n=a.convert(t,i,this.seacAnalysisEnabled);let g=a.output;n&&(g=[14]);const o={glyphName:s,charstring:g,width:a.width,lsb:a.lsb,seac:a.seac};".notdef"===s?r.charstrings.unshift(o):r.charstrings.push(o);if(e.builtInEncoding){const t=e.builtInEncoding.indexOf(s);t>-1&&void 0===e.widths[t]&&t>=e.firstChar&&t<=e.lastChar&&(e.widths[t]=a.width)}}return r}extractFontHeader(e){let t;for(;null!==(t=this.getToken());)if("/"===t){t=this.getToken();switch(t){case"FontMatrix":const i=this.readNumberArray();e.fontMatrix=i;break;case"Encoding":const a=this.getToken();let s;if(/^\d+$/.test(a)){s=[];const e=0|parseInt(a,10);this.getToken();for(let i=0;i=s){n+=i;for(;n=0&&(a[e]=s)}}return type1FontGlyphMapping(e,a,i)}hasGlyphId(e){if(e<0||e>=this.numGlyphs)return!1;if(0===e)return!0;return this.charstrings[e-1].charstring.length>0}getSeacs(e){const t=[];for(let i=0,a=e.length;i0;e--)t[e]-=t[e-1];Q.setByName(e,t)}r.topDict.privateDict=Q;const u=new CFFIndex;for(C=0,h=a.length;C0&&e.toUnicode.amend(t)}class fonts_Glyph{constructor(e,t,i,a,s,r,n,g,o){this.originalCharCode=e;this.fontChar=t;this.unicode=i;this.accent=a;this.width=s;this.vmetric=r;this.operatorListId=n;this.isSpace=g;this.isInFont=o}get category(){return shadow(this,"category",function getCharUnicodeCategory(e){const t=ki.get(e);if(t)return t;const i=e.match(Si),a={isWhitespace:!!i?.[1],isZeroWidthDiacritic:!!i?.[2],isInvisibleFormatMark:!!i?.[3]};ki.set(e,a);return a}(this.unicode),!0)}}function int16(e,t){return(e<<8)+t}function writeSignedInt16(e,t,i){e[t+1]=i;e[t]=i>>>8}function signedInt16(e,t){const i=(e<<8)+t;return 32768&i?i-65536:i}function string16(e){return String.fromCharCode(e>>8&255,255&e)}function safeString16(e){e>32767?e=32767:e<-32768&&(e=-32768);return String.fromCharCode(e>>8&255,255&e)}function isTrueTypeCollectionFile(e){return"ttcf"===bytesToString(e.peekBytes(4))}function getFontFileType(e,{type:t,subtype:i,composite:a}){let s,r;if(function isTrueTypeFile(e){const t=e.peekBytes(4);return 65536===readUint32(t,0)||"true"===bytesToString(t)}(e)||isTrueTypeCollectionFile(e))s=a?"CIDFontType2":"TrueType";else if(function isOpenTypeFile(e){return"OTTO"===bytesToString(e.peekBytes(4))}(e))s=a?"CIDFontType2":"OpenType";else if(function isType1File(e){const t=e.peekBytes(2);return 37===t[0]&&33===t[1]||128===t[0]&&1===t[1]}(e))s=a?"CIDFontType0":"MMType1"===t?"MMType1":"Type1";else if(function isCFFFile(e){const t=e.peekBytes(4);return t[0]>=1&&t[3]>=1&&t[3]<=4}(e))if(a){s="CIDFontType0";r="CIDFontType0C"}else{s="MMType1"===t?"MMType1":"Type1";r="Type1C"}else{warn("getFontFileType: Unable to detect correct font file Type/Subtype.");s=t;r=i}return[s,r]}function applyStandardFontGlyphMap(e,t){for(const i in t)e[+i]=t[i]}function buildToFontChar(e,t,i){const a=[];let s;for(let i=0,r=e.length;iC){o++;if(o>=ra.length){warn("Ran out of space in font private use area.");break}c=ra[o][0];C=ra[o][1]}const E=c++;0===Q&&(Q=i);let u=a.get(l);"string"==typeof u&&(u=u.codePointAt(0));if(u&&!(h=u,ra[0][0]<=h&&h<=ra[0][1]||ra[1][0]<=h&&h<=ra[1][1])&&!g.has(Q)){r.set(u,Q);g.add(Q)}s[E]=Q;n[l]=E}var h;return{toFontChar:n,charCodeToGlyphId:s,toUnicodeExtraMap:r,nextAvailableFontCharCode:c}}function createCmapTable(e,t,i){const a=function getRanges(e,t,i){const a=[];for(const t in e)e[t]>=i||a.push({fontCharCode:0|t,glyphId:e[t]});if(t)for(const[e,s]of t)s>=i||a.push({fontCharCode:e,glyphId:s});0===a.length&&a.push({fontCharCode:0,glyphId:0});a.sort((function fontGetRangesSort(e,t){return e.fontCharCode-t.fontCharCode}));const s=[],r=a.length;for(let e=0;e65535?2:1;let r,n,g,o,c="\0\0"+string16(s)+"\0\0"+string32(4+8*s);for(r=a.length-1;r>=0&&!(a[r][0]<=65535);--r);const C=r+1;a[r][0]<65535&&65535===a[r][1]&&(a[r][1]=65534);const h=a[r][1]<65535?1:0,l=C+h,Q=OpenTypeFileBuilder.getSearchParams(l,2);let E,u,d,f,p="",m="",y="",w="",D="",b=0;for(r=0,n=C;r0){m+="ÿÿ";p+="ÿÿ";y+="\0";w+="\0\0"}const F="\0\0"+string16(2*l)+string16(Q.range)+string16(Q.entry)+string16(Q.rangeShift)+m+"\0\0"+p+y+w+D;let S="",k="";if(s>1){c+="\0\0\n"+string32(4+8*s+4+F.length);S="";for(r=0,n=a.length;re||!g)&&(g=e);o 123 are reserved for internal usage");n|=1<65535&&(o=65535)}else{g=0;o=255}const C=e.bbox||[0,0,0,0],h=i.unitsPerEm||(e.fontMatrix?1/Math.max(...e.fontMatrix.slice(0,4).map(Math.abs)):1e3),l=e.ascentScaled?1:h/na,Q=i.ascent||Math.round(l*(e.ascent||C[3]));let E=i.descent||Math.round(l*(e.descent||C[1]));E>0&&e.descent>0&&C[1]<0&&(E=-E);const u=i.yMax||Q,d=-i.yMin||-E;return"\0$ô\0\0\0Š»\0\0\0ŒŠ»\0\0ß\x001\0\0\0\0"+String.fromCharCode(e.fixedPitch?9:0)+"\0\0\0\0\0\0"+string32(a)+string32(s)+string32(r)+string32(n)+"*21*"+string16(e.italicAngle?1:0)+string16(g||e.firstChar)+string16(o||e.lastChar)+string16(Q)+string16(E)+"\0d"+string16(u)+string16(d)+"\0\0\0\0\0\0\0\0"+string16(e.xHeight)+string16(e.capHeight)+string16(0)+string16(g||e.firstChar)+"\0"}function createPostTable(e){return"\0\0\0"+string32(Math.floor(65536*e.italicAngle))+"\0\0\0\0"+string32(e.fixedPitch?1:0)+"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"}function createPostscriptName(e){return e.replaceAll(/[^\x21-\x7E]|[[\](){}<>/%]/g,"").slice(0,63)}function createNameTable(e,t){t||(t=[[],[]]);const i=[t[0][0]||"Original licence",t[0][1]||e,t[0][2]||"Unknown",t[0][3]||"uniqueID",t[0][4]||e,t[0][5]||"Version 0.11",t[0][6]||createPostscriptName(e),t[0][7]||"Unknown",t[0][8]||"Unknown",t[0][9]||"Unknown"],a=[];let s,r,n,g,o;for(s=0,r=i.length;s0;if((n||g)&&"CIDFontType2"===i&&this.cidEncoding.startsWith("Identity-")){const i=e.cidToGidMap,a=[];applyStandardFontGlyphMap(a,Oi());/Arial-?Black/i.test(t)?applyStandardFontGlyphMap(a,Pi()):/Calibri/i.test(t)&&applyStandardFontGlyphMap(a,Wi());if(i){for(const e in a){const t=a[e];void 0!==i[t]&&(a[+e]=i[t])}i.length!==this.toUnicode.length&&e.hasIncludedToUnicodeMap&&this.toUnicode instanceof IdentityToUnicodeMap&&this.toUnicode.forEach((function(e,t){const s=a[e];void 0===i[s]&&(a[+e]=t)}))}this.toUnicode instanceof IdentityToUnicodeMap||this.toUnicode.forEach((function(e,t){a[+e]=t}));this.toFontChar=a;this.toUnicode=new ToUnicodeMap(a)}else if(/Symbol/i.test(a))this.toFontChar=buildToFontChar(Bi,wi(),this.differences);else if(/Dingbats/i.test(a))this.toFontChar=buildToFontChar(Qi,Di(),this.differences);else if(n||g){const e=buildToFontChar(this.defaultEncoding,wi(),this.differences);"CIDFontType2"!==i||this.cidEncoding.startsWith("Identity-")||this.toUnicode instanceof IdentityToUnicodeMap||this.toUnicode.forEach((function(t,i){e[+t]=i}));this.toFontChar=e}else{const e=wi(),i=[];this.toUnicode.forEach(((t,a)=>{if(!this.composite){const i=getUnicodeForGlyph(this.differences[t]||this.defaultEncoding[t],e);-1!==i&&(a=i)}i[+t]=a}));this.composite&&this.toUnicode instanceof IdentityToUnicodeMap&&/Tahoma|Verdana/i.test(t)&&applyStandardFontGlyphMap(i,Oi());this.toFontChar=i}amendFallbackToUnicode(e);this.loadedName=a.split("-",1)[0]}checkAndRepair(e,t,i){const a=["OS/2","cmap","head","hhea","hmtx","maxp","name","post","loca","glyf","fpgm","prep","cvt ","CFF "];function readTables(e,t){const i=Object.create(null);i["OS/2"]=null;i.cmap=null;i.head=null;i.hhea=null;i.hmtx=null;i.maxp=null;i.name=null;i.post=null;for(let s=0;s>>0,a=e.getInt32()>>>0,s=e.getInt32()>>>0,r=e.pos;e.pos=e.start||0;e.skip(a);const n=e.getBytes(s);e.pos=r;if("head"===t){n[8]=n[9]=n[10]=n[11]=0;n[17]|=32}return{tag:t,checksum:i,length:s,offset:a,data:n}}function readOpenTypeHeader(e){return{version:e.getString(4),numTables:e.getUint16(),searchRange:e.getUint16(),entrySelector:e.getUint16(),rangeShift:e.getUint16()}}function sanitizeGlyph(e,t,i,a,s,r){const n={length:0,sizeOfInstructions:0};if(t<0||t>=e.length||i>e.length||i-t<=12)return n;const g=e.subarray(t,i),o=signedInt16(g[2],g[3]),c=signedInt16(g[4],g[5]),C=signedInt16(g[6],g[7]),h=signedInt16(g[8],g[9]);if(o>C){writeSignedInt16(g,2,C);writeSignedInt16(g,6,o)}if(c>h){writeSignedInt16(g,4,h);writeSignedInt16(g,8,c)}const l=signedInt16(g[0],g[1]);if(l<0){if(l<-1)return n;a.set(g,s);n.length=g.length;return n}let Q,E=10,u=0;for(Q=0;Qg.length)return n;if(!r&&f>0){a.set(g.subarray(0,d),s);a.set([0,0],s+d);a.set(g.subarray(p,y),s+d+2);y-=f;g.length-y>3&&(y=y+3&-4);n.length=y;return n}if(g.length-y>3){y=y+3&-4;a.set(g.subarray(0,y),s);n.length=y;return n}a.set(g,s);n.length=g.length;return n}function readNameTable(e){const i=(t.start||0)+e.offset;t.pos=i;const a=[[],[]],s=[],r=e.length,n=i+r;if(0!==t.getUint16()||r<6)return[a,s];const g=t.getUint16(),o=t.getUint16();let c,C;for(c=0;cn)continue;t.pos=r;const g=e.name;if(e.encoding){let i="";for(let a=0,s=e.length;a0&&(c+=e-1)}}else{if(d||p){warn("TT: nested FDEFs not allowed");u=!0}d=!0;h=c;n=l.pop();t.functionsDefined[n]={data:o,i:c}}else if(!d&&!p){n=l.at(-1);if(isNaN(n))info("TT: CALL empty stack (or invalid entry).");else{t.functionsUsed[n]=!0;if(n in t.functionsStackDeltas){const e=l.length+t.functionsStackDeltas[n];if(e<0){warn("TT: CALL invalid functions stack delta.");t.hintsValid=!1;return}l.length=e}else if(n in t.functionsDefined&&!E.includes(n)){Q.push({data:o,i:c,stackTop:l.length-1});E.push(n);g=t.functionsDefined[n];if(!g){warn("TT: CALL non-existent function");t.hintsValid=!1;return}o=g.data;c=g.i}}}if(!d&&!p){let t=0;e<=142?t=s[e]:e>=192&&e<=223?t=-1:e>=224&&(t=-2);if(e>=113&&e<=117){a=l.pop();isNaN(a)||(t=2*-a)}for(;t<0&&l.length>0;){l.pop();t++}for(;t>0;){l.push(NaN);t--}}}t.tooComplexToFollowFunctions=u;const m=[o];c>o.length&&m.push(new Uint8Array(c-o.length));if(h>C){warn("TT: complementing a missing function tail");m.push(new Uint8Array([34,45]))}!function foldTTTable(e,t){if(t.length>1){let i,a,s=0;for(i=0,a=t.length;i>>0,r=[];for(let t=0;t>>0);const n={ttcTag:t,majorVersion:i,minorVersion:a,numFonts:s,offsetTable:r};switch(i){case 1:return n;case 2:n.dsigTag=e.getInt32()>>>0;n.dsigLength=e.getInt32()>>>0;n.dsigOffset=e.getInt32()>>>0;return n}throw new FormatError(`Invalid TrueType Collection majorVersion: ${i}.`)}(e),s=t.split("+");let r;for(let n=0;n0||!(i.cMap instanceof IdentityCMap));if("OTTO"===r.version&&!t||!n.head||!n.hhea||!n.maxp||!n.post){o=new Stream(n["CFF "].data);g=new CFFFont(o,i);adjustWidths(i);return this.convert(e,g,i)}delete n.glyf;delete n.loca;delete n.fpgm;delete n.prep;delete n["cvt "];this.isOpenType=!0}if(!n.maxp)throw new FormatError('Required "maxp" table is not found');t.pos=(t.start||0)+n.maxp.offset;let C=t.getInt32();const h=t.getUint16();if(65536!==C&&20480!==C){if(6===n.maxp.length)C=20480;else{if(!(n.maxp.length>=32))throw new FormatError('"maxp" table has a wrong version number');C=65536}!function writeUint32(e,t,i){e[t+3]=255&i;e[t+2]=i>>>8;e[t+1]=i>>>16;e[t]=i>>>24}(n.maxp.data,0,C)}if(i.scaleFactors?.length===h&&c){const{scaleFactors:e}=i,t=int16(n.head.data[50],n.head.data[51]),a=new GlyfTable({glyfTable:n.glyf.data,isGlyphLocationsLong:t,locaTable:n.loca.data,numGlyphs:h});a.scale(e);const{glyf:s,loca:r,isLocationLong:g}=a.write();n.glyf.data=s;n.loca.data=r;if(g!==!!t){n.head.data[50]=0;n.head.data[51]=g?1:0}const o=n.hmtx.data;for(let t=0;t>8&255;o[i+1]=255&a;writeSignedInt16(o,i+2,Math.round(e[t]*signedInt16(o[i+2],o[i+3])))}}let l=h+1,Q=!0;if(l>65535){Q=!1;l=h;warn("Not enough space in glyfs to duplicate first glyph.")}let E=0,u=0;if(C>=65536&&n.maxp.length>=32){t.pos+=8;if(t.getUint16()>2){n.maxp.data[14]=0;n.maxp.data[15]=2}t.pos+=4;E=t.getUint16();t.pos+=4;u=t.getUint16()}n.maxp.data[4]=l>>8;n.maxp.data[5]=255&l;const d=function sanitizeTTPrograms(e,t,i,a){const s={functionsDefined:[],functionsUsed:[],functionsStackDeltas:[],tooComplexToFollowFunctions:!1,hintsValid:!0};e&&sanitizeTTProgram(e,s);t&&sanitizeTTProgram(t,s);e&&function checkInvalidFunctions(e,t){if(!e.tooComplexToFollowFunctions)if(e.functionsDefined.length>t){warn("TT: more functions defined than expected");e.hintsValid=!1}else for(let i=0,a=e.functionsUsed.length;it){warn("TT: invalid function id: "+i);e.hintsValid=!1;return}if(e.functionsUsed[i]&&!e.functionsDefined[i]){warn("TT: undefined function: "+i);e.hintsValid=!1;return}}}(s,a);if(i&&1&i.length){const e=new Uint8Array(i.length+1);e.set(i.data);i.data=e}return s.hintsValid}(n.fpgm,n.prep,n["cvt "],E);if(!d){delete n.fpgm;delete n.prep;delete n["cvt "]}!function sanitizeMetrics(e,t,i,a,s,r){if(!t){i&&(i.data=null);return}e.pos=(e.start||0)+t.offset;e.pos+=4;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;const n=e.getUint16();e.pos+=8;e.pos+=2;let g=e.getUint16();if(0!==n){if(!(2&int16(a.data[44],a.data[45]))){t.data[22]=0;t.data[23]=0}}if(g>s){info(`The numOfMetrics (${g}) should not be greater than the numGlyphs (${s}).`);g=s;t.data[34]=(65280&g)>>8;t.data[35]=255&g}const o=s-g-(i.length-4*g>>1);if(o>0){const e=new Uint8Array(i.length+2*o);e.set(i.data);if(r){e[i.length]=i.data[2];e[i.length+1]=i.data[3]}i.data=e}}(t,n.hhea,n.hmtx,n.head,l,Q);if(!n.head)throw new FormatError('Required "head" table is not found');!function sanitizeHead(e,t,i){const a=e.data,s=function int32(e,t,i,a){return(e<<24)+(t<<16)+(i<<8)+a}(a[0],a[1],a[2],a[3]);if(s>>16!=1){info("Attempting to fix invalid version in head table: "+s);a[0]=0;a[1]=1;a[2]=0;a[3]=0}const r=int16(a[50],a[51]);if(r<0||r>1){info("Attempting to fix invalid indexToLocFormat in head table: "+r);const e=t+1;if(i===e<<1){a[50]=0;a[51]=0}else{if(i!==e<<2)throw new FormatError("Could not fix indexToLocFormat: "+r);a[50]=0;a[51]=1}}}(n.head,h,c?n.loca.length:0);let f=Object.create(null);if(c){const e=int16(n.head.data[50],n.head.data[51]),t=function sanitizeGlyphLocations(e,t,i,a,s,r,n){let g,o,c;if(a){g=4;o=function fontItemDecodeLong(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]};c=function fontItemEncodeLong(e,t,i){e[t]=i>>>24&255;e[t+1]=i>>16&255;e[t+2]=i>>8&255;e[t+3]=255&i}}else{g=2;o=function fontItemDecode(e,t){return e[t]<<9|e[t+1]<<1};c=function fontItemEncode(e,t,i){e[t]=i>>9&255;e[t+1]=i>>1&255}}const C=r?i+1:i,h=g*(1+C),l=new Uint8Array(h);l.set(e.data.subarray(0,h));e.data=l;const Q=t.data,E=Q.length,u=new Uint8Array(E);let d,f;const p=[];for(d=0,f=0;dE&&(e=E);p.push({index:d,offset:e,endOffset:0})}p.sort(((e,t)=>e.offset-t.offset));for(d=0;de.index-t.index));for(d=0;dn&&(n=e.sizeOfInstructions);w+=t;c(l,f,w)}if(0===w){const e=new Uint8Array([0,1,0,0,0,0,0,0,0,0,0,0,0,0,49,0]);for(d=0,f=g;di+w)t.data=u.subarray(0,i+w);else{t.data=new Uint8Array(i+w);t.data.set(u.subarray(0,w))}t.data.set(u.subarray(0,i),w);c(e.data,l.length-g,w+i)}else t.data=u.subarray(0,w);return{missingGlyphs:y,maxSizeOfInstructions:n}}(n.loca,n.glyf,h,e,d,Q,u);f=t.missingGlyphs;if(C>=65536&&n.maxp.length>=32){n.maxp.data[26]=t.maxSizeOfInstructions>>8;n.maxp.data[27]=255&t.maxSizeOfInstructions}}if(!n.hhea)throw new FormatError('Required "hhea" table is not found');if(0===n.hhea.data[10]&&0===n.hhea.data[11]){n.hhea.data[10]=255;n.hhea.data[11]=255}const p={unitsPerEm:int16(n.head.data[18],n.head.data[19]),yMax:signedInt16(n.head.data[42],n.head.data[43]),yMin:signedInt16(n.head.data[38],n.head.data[39]),ascent:signedInt16(n.hhea.data[4],n.hhea.data[5]),descent:signedInt16(n.hhea.data[6],n.hhea.data[7]),lineGap:signedInt16(n.hhea.data[8],n.hhea.data[9])};this.ascent=p.ascent/p.unitsPerEm;this.descent=p.descent/p.unitsPerEm;this.lineGap=p.lineGap/p.unitsPerEm;if(this.cssFontInfo?.lineHeight){this.lineHeight=this.cssFontInfo.metrics.lineHeight;this.lineGap=this.cssFontInfo.metrics.lineGap}else this.lineHeight=this.ascent-this.descent+this.lineGap;n.post&&function readPostScriptTable(e,i,a){const s=(t.start||0)+e.offset;t.pos=s;const r=s+e.length,n=t.getInt32();t.skip(28);let g,o,c=!0;switch(n){case 65536:g=Hi;break;case 131072:const e=t.getUint16();if(e!==a){c=!1;break}const s=[];for(o=0;o=32768){c=!1;break}s.push(e)}if(!c)break;const C=[],h=[];for(;t.pos65535)throw new FormatError("Max size of CID is 65,535");let s=-1;t?s=a:void 0!==e[a]&&(s=e[a]);s>=0&&s>>0;let C=!1;if(g?.platformId!==s||g?.encodingId!==r){if(0!==s||0!==r&&1!==r&&3!==r)if(1===s&&0===r)C=!0;else if(3!==s||1!==r||!a&&g){if(i&&3===s&&0===r){C=!0;let i=!0;if(e>3;e.push(a);i=Math.max(a,i)}const a=[];for(let e=0;e<=i;e++)a.push({firstCode:t.getUint16(),entryCount:t.getUint16(),idDelta:signedInt16(t.getByte(),t.getByte()),idRangePos:t.pos+t.getUint16()});for(let i=0;i<256;i++)if(0===e[i]){t.pos=a[0].idRangePos+2*i;Q=t.getUint16();h.push({charCode:i,glyphId:Q})}else{const s=a[e[i]];for(l=0;l>1;t.skip(6);const i=[];let a;for(a=0;a>1)-(e-a);s.offsetIndex=n;g=Math.max(g,n+s.end-s.start+1)}else s.offsetIndex=-1}const o=[];for(l=0;l>>0;for(l=0;l>>0,i=t.getInt32()>>>0;let a=t.getInt32()>>>0;for(let t=e;t<=i;t++)h.push({charCode:t,glyphId:a++})}}}h.sort((function(e,t){return e.charCode-t.charCode}));for(let e=1;e=61440&&t<=61695&&(t&=255);m[t]=e.glyphId}else for(const e of r)m[e.charCode]=e.glyphId;if(i.glyphNames&&(g.length||this.differences.length))for(let e=0;e<256;++e){if(!o&&void 0!==m[e])continue;const t=this.differences[e]||g[e];if(!t)continue;const a=i.glyphNames.indexOf(t);a>0&&hasGlyph(a)&&(m[e]=a)}}0===m.length&&(m[0]=0);let y=l-1;Q||(y=0);if(!i.cssFontInfo){const e=adjustMapping(m,hasGlyph,y,this.toUnicode);this.toFontChar=e.toFontChar;n.cmap={tag:"cmap",data:createCmapTable(e.charCodeToGlyphId,e.toUnicodeExtraMap,l)};n["OS/2"]&&function validateOS2Table(e,t){t.pos=(t.start||0)+e.offset;const i=t.getUint16();t.skip(60);const a=t.getUint16();if(i<4&&768&a)return!1;if(t.getUint16()>t.getUint16())return!1;t.skip(6);if(0===t.getUint16())return!1;e.data[8]=e.data[9]=0;return!0}(n["OS/2"],t)||(n["OS/2"]={tag:"OS/2",data:createOS2Table(i,e.charCodeToGlyphId,p)})}if(!c)try{o=new Stream(n["CFF "].data);g=new CFFParser(o,i,Ri).parse();g.duplicateFirstGlyph();const e=new CFFCompiler(g);n["CFF "].data=e.compile()}catch{warn("Failed to compile font "+i.loadedName)}if(n.name){const[t,a]=readNameTable(n.name);n.name.data=createNameTable(e,t);this.psName=t[0][6]||null;i.composite||function adjustTrueTypeToUnicode(e,t,i){if(e.isInternalFont)return;if(e.hasIncludedToUnicodeMap)return;if(e.hasEncoding)return;if(e.toUnicode instanceof IdentityToUnicodeMap)return;if(!t)return;if(0===i.length)return;if(e.defaultEncoding===li)return;for(const e of i)if(!isWinNameRecord(e))return;const a=li,s=[],r=wi();for(const e in a){const t=a[e];if(""===t)continue;const i=r[t];void 0!==i&&(s[e]=String.fromCharCode(i))}s.length>0&&e.toUnicode.amend(s)}(i,this.isSymbolicFont,a)}else n.name={tag:"name",data:createNameTable(this.name)};const w=new OpenTypeFileBuilder(r.version);for(const e in n)w.addTable(e,n[e].data);return w.toArray()}convert(e,t,i){i.fixedPitch=!1;i.builtInEncoding&&function adjustType1ToUnicode(e,t){if(e.isInternalFont)return;if(e.hasIncludedToUnicodeMap)return;if(t===e.defaultEncoding)return;if(e.toUnicode instanceof IdentityToUnicodeMap)return;const i=[],a=wi();for(const s in t){if(e.hasEncoding&&(e.baseEncodingName||void 0!==e.differences[s]))continue;const r=getUnicodeForGlyph(t[s],a);-1!==r&&(i[s]=String.fromCharCode(r))}i.length>0&&e.toUnicode.amend(i)}(i,i.builtInEncoding);let s=1;t instanceof CFFFont&&(s=t.numGlyphs-1);const r=t.getGlyphMapping(i);let n=null,g=r,o=null;if(!i.cssFontInfo){n=adjustMapping(r,t.hasGlyphId.bind(t),s,this.toUnicode);this.toFontChar=n.toFontChar;g=n.charCodeToGlyphId;o=n.toUnicodeExtraMap}const c=t.numGlyphs;function getCharCodes(e,t){let i=null;for(const a in e)t===e[a]&&(i||=[]).push(0|a);return i}function createCharCode(e,t){for(const i in e)if(t===e[i])return 0|i;n.charCodeToGlyphId[n.nextAvailableFontCharCode]=t;return n.nextAvailableFontCharCode++}const C=t.seacs;if(n&&C?.length){const e=i.fontMatrix||a,s=t.getCharset(),g=Object.create(null);for(let t in C){t|=0;const i=C[t],a=hi[i[2]],o=hi[i[3]],c=s.indexOf(a),h=s.indexOf(o);if(c<0||h<0)continue;const l={x:i[0]*e[0]+i[1]*e[2]+e[4],y:i[0]*e[1]+i[1]*e[3]+e[5]},Q=getCharCodes(r,t);if(Q)for(const e of Q){const t=n.charCodeToGlyphId,i=createCharCode(t,c),a=createCharCode(t,h);g[e]={baseFontCharCode:i,accentFontCharCode:a,accentOffset:l}}}i.seacMap=g}const h=i.fontMatrix?1/Math.max(...i.fontMatrix.slice(0,4).map(Math.abs)):1e3,l=new OpenTypeFileBuilder("OTTO");l.addTable("CFF ",t.data);l.addTable("OS/2",createOS2Table(i,g));l.addTable("cmap",createCmapTable(g,o,c));l.addTable("head","\0\0\0\0\0\0\0\0\0\0_<õ\0\0"+safeString16(h)+"\0\0\0\0ž\v~'\0\0\0\0ž\v~'\0\0"+safeString16(i.descent)+"ÿ"+safeString16(i.ascent)+string16(i.italicAngle?2:0)+"\0\0\0\0\0\0\0");l.addTable("hhea","\0\0\0"+safeString16(i.ascent)+safeString16(i.descent)+"\0\0ÿÿ\0\0\0\0\0\0"+safeString16(i.capHeight)+safeString16(Math.tan(i.italicAngle)*i.xHeight)+"\0\0\0\0\0\0\0\0\0\0\0\0"+string16(c));l.addTable("hmtx",function fontFieldsHmtx(){const e=t.charstrings,i=t.cff?t.cff.widths:null;let a="\0\0\0\0";for(let t=1,s=c;t=65520&&e<=65535?0:e>=62976&&e<=63743?bi()[e]||e:173===e?45:e}(i)}this.isType3Font&&(s=i);let C=null;if(this.seacMap?.[e]){c=!0;const t=this.seacMap[e];i=t.baseFontCharCode;C={fontChar:String.fromCodePoint(t.accentFontCharCode),offset:t.accentOffset}}let h="";"number"==typeof i&&(i<=1114111?h=String.fromCodePoint(i):warn(`charToGlyph - invalid fontCharCode: ${i}`));if(this.missingFile&&this.vertical&&1===h.length){const e=Ji()[h.charCodeAt(0)];e&&(h=o=String.fromCharCode(e))}r=new fonts_Glyph(e,h,o,C,a,g,s,t,c);return this._glyphCache[e]=r}charsToGlyphs(e){let t=this._charsCache[e];if(t)return t;t=[];if(this.cMap){const i=Object.create(null),a=e.length;let s=0;for(;st.length%2==1,a=this.toUnicode instanceof IdentityToUnicodeMap?e=>this.toUnicode.charCodeOf(e):e=>this.toUnicode.charCodeOf(String.fromCodePoint(e));for(let s=0,r=e.length;s55295&&(r<57344||r>65533)&&s++;if(this.toUnicode){const e=a(r);if(-1!==e){if(hasCurrentBufErrors()){t.push(i.join(""));i.length=0}for(let t=(this.cMap?this.cMap.getCharCodeLength(e):1)-1;t>=0;t--)i.push(String.fromCharCode(e>>8*t&255));continue}}if(!hasCurrentBufErrors()){t.push(i.join(""));i.length=0}i.push(String.fromCodePoint(r))}t.push(i.join(""));return t}}class ErrorFont{constructor(e){this.error=e;this.loadedName="g_font_error";this.missingFile=!0}charsToGlyphs(){return[]}encodeString(e){return[e]}exportData(e=!1){return{error:this.error}}}const Ia=2,ca=3,Ca=4,ha=5,la=6,Ba=7;class Pattern{constructor(){unreachable("Cannot initialize Pattern.")}static parseShading(e,t,i,a,s){const r=e instanceof BaseStream?e.dict:e,n=r.get("ShadingType");try{switch(n){case Ia:case ca:return new RadialAxialShading(r,t,i,a,s);case Ca:case ha:case la:case Ba:return new MeshShading(e,t,i,a,s);default:throw new FormatError("Unsupported ShadingType: "+n)}}catch(e){if(e instanceof MissingDataException)throw e;warn(e);return new DummyShading}}}class BaseShading{static SMALL_NUMBER=1e-6;getIR(){unreachable("Abstract method `getIR` called.")}}class RadialAxialShading extends BaseShading{constructor(e,t,i,a,s){super();this.shadingType=e.get("ShadingType");let r=0;this.shadingType===Ia?r=4:this.shadingType===ca&&(r=6);this.coordsArr=e.getArray("Coords");if(!isNumberArray(this.coordsArr,r))throw new FormatError("RadialAxialShading: Invalid /Coords array.");const n=ColorSpace.parse({cs:e.getRaw("CS")||e.getRaw("ColorSpace"),xref:t,resources:i,pdfFunctionFactory:a,localColorSpaceCache:s});this.bbox=lookupNormalRect(e.getArray("BBox"),null);let g=0,o=1;const c=e.getArray("Domain");isNumberArray(c,2)&&([g,o]=c);let C=!1,h=!1;const l=e.getArray("Extend");(function isBooleanArray(e,t){return Array.isArray(e)&&(null===t||e.length===t)&&e.every((e=>"boolean"==typeof e))})(l,2)&&([C,h]=l);if(!(this.shadingType!==ca||C&&h)){const[e,t,i,a,s,r]=this.coordsArr,n=Math.hypot(e-a,t-s);i<=r+n&&r<=i+n&&warn("Unsupported radial gradient.")}this.extendStart=C;this.extendEnd=h;const Q=e.getRaw("Function"),E=a.createFromArray(Q),u=(o-g)/840,d=this.colorStops=[];if(g>=o||u<=0){info("Bad shading domain.");return}const f=new Float32Array(n.numComps),p=new Float32Array(1);let m,y=0;p[0]=g;E(p,0,f,0);let w=n.getRgb(f,0);const D=Util.makeHexColor(w[0],w[1],w[2]);d.push([0,D]);let b=1;p[0]=g+u;E(p,0,f,0);let F=n.getRgb(f,0),S=F[0]-w[0]+1,k=F[1]-w[1]+1,R=F[2]-w[2]+1,N=F[0]-w[0]-1,G=F[1]-w[1]-1,M=F[2]-w[2]-1;for(let e=2;e<840;e++){p[0]=g+e*u;E(p,0,f,0);m=n.getRgb(f,0);const t=e-y;S=Math.min(S,(m[0]-w[0]+1)/t);k=Math.min(k,(m[1]-w[1]+1)/t);R=Math.min(R,(m[2]-w[2]+1)/t);N=Math.max(N,(m[0]-w[0]-1)/t);G=Math.max(G,(m[1]-w[1]-1)/t);M=Math.max(M,(m[2]-w[2]-1)/t);if(!(N<=S&&G<=k&&M<=R)){const e=Util.makeHexColor(F[0],F[1],F[2]);d.push([b/840,e]);S=m[0]-F[0]+1;k=m[1]-F[1]+1;R=m[2]-F[2]+1;N=m[0]-F[0]-1;G=m[1]-F[1]-1;M=m[2]-F[2]-1;y=b;w=F}b=e;F=m}const U=Util.makeHexColor(F[0],F[1],F[2]);d.push([1,U]);let x="transparent";if(e.has("Background")){m=n.getRgb(e.get("Background"),0);x=Util.makeHexColor(m[0],m[1],m[2])}if(!C){d.unshift([0,x]);d[1][0]+=BaseShading.SMALL_NUMBER}if(!h){d.at(-1)[0]-=BaseShading.SMALL_NUMBER;d.push([1,x])}this.colorStops=d}getIR(){const{coordsArr:e,shadingType:t}=this;let i,a,s,r,n;if(t===Ia){a=[e[0],e[1]];s=[e[2],e[3]];r=null;n=null;i="axial"}else if(t===ca){a=[e[0],e[1]];s=[e[3],e[4]];r=e[2];n=e[5];i="radial"}else unreachable(`getPattern type unknown: ${t}`);return["RadialAxial",i,this.bbox,this.colorStops,a,s,r,n]}}class MeshStreamReader{constructor(e,t){this.stream=e;this.context=t;this.buffer=0;this.bufferLength=0;const i=t.numComps;this.tmpCompsBuf=new Float32Array(i);const a=t.colorSpace.numComps;this.tmpCsCompsBuf=t.colorFn?new Float32Array(a):this.tmpCompsBuf}get hasData(){if(this.stream.end)return this.stream.pos0)return!0;const e=this.stream.getByte();if(e<0)return!1;this.buffer=e;this.bufferLength=8;return!0}readBits(e){let t=this.buffer,i=this.bufferLength;if(32===e){if(0===i)return(this.stream.getByte()<<24|this.stream.getByte()<<16|this.stream.getByte()<<8|this.stream.getByte())>>>0;t=t<<24|this.stream.getByte()<<16|this.stream.getByte()<<8|this.stream.getByte();const e=this.stream.getByte();this.buffer=e&(1<>i)>>>0}if(8===e&&0===i)return this.stream.getByte();for(;i>i}align(){this.buffer=0;this.bufferLength=0}readFlag(){return this.readBits(this.context.bitsPerFlag)}readCoordinate(){const e=this.context.bitsPerCoordinate,t=this.readBits(e),i=this.readBits(e),a=this.context.decode,s=e<32?1/((1<r?r:e;t=t>n?n:t;i=ie*s[t])):i;let n,g=-2;const o=[];for(const[e,t]of a.map(((e,t)=>[e,t])).sort((([e],[t])=>e-t)))if(-1!==e)if(e===g+1){n.push(r[t]);g+=1}else{g=e;n=[r[t]];o.push(e,n)}return o}(e),i=new Dict(null);i.set("BaseFont",Name.get(e));i.set("Type",Name.get("Font"));i.set("Subtype",Name.get("CIDFontType2"));i.set("Encoding",Name.get("Identity-H"));i.set("CIDToGIDMap",Name.get("Identity"));i.set("W",t);i.set("FirstChar",t[0]);i.set("LastChar",t.at(-2)+t.at(-1).length-1);const a=new Dict(null);i.set("FontDescriptor",a);const s=new Dict(null);s.set("Ordering","Identity");s.set("Registry","Adobe");s.set("Supplement",0);i.set("CIDSystemInfo",s);return i}class PostScriptParser{constructor(e){this.lexer=e;this.operators=[];this.token=null;this.prev=null}nextToken(){this.prev=this.token;this.token=this.lexer.getToken()}accept(e){if(this.token.type===e){this.nextToken();return!0}return!1}expect(e){if(this.accept(e))return!0;throw new FormatError(`Unexpected symbol: found ${this.token.type} expected ${e}.`)}parse(){this.nextToken();this.expect(as.LBRACE);this.parseBlock();this.expect(as.RBRACE);return this.operators}parseBlock(){for(;;)if(this.accept(as.NUMBER))this.operators.push(this.prev.value);else if(this.accept(as.OPERATOR))this.operators.push(this.prev.value);else{if(!this.accept(as.LBRACE))return;this.parseCondition()}}parseCondition(){const e=this.operators.length;this.operators.push(null,null);this.parseBlock();this.expect(as.RBRACE);if(this.accept(as.IF)){this.operators[e]=this.operators.length;this.operators[e+1]="jz"}else{if(!this.accept(as.LBRACE))throw new FormatError("PS Function: error parsing conditional.");{const t=this.operators.length;this.operators.push(null,null);const i=this.operators.length;this.parseBlock();this.expect(as.RBRACE);this.expect(as.IFELSE);this.operators[t]=this.operators.length;this.operators[t+1]="j";this.operators[e]=i;this.operators[e+1]="jz"}}}}const as={LBRACE:0,RBRACE:1,NUMBER:2,OPERATOR:3,IF:4,IFELSE:5};class PostScriptToken{static get opCache(){return shadow(this,"opCache",Object.create(null))}constructor(e,t){this.type=e;this.value=t}static getOperator(e){return PostScriptToken.opCache[e]||=new PostScriptToken(as.OPERATOR,e)}static get LBRACE(){return shadow(this,"LBRACE",new PostScriptToken(as.LBRACE,"{"))}static get RBRACE(){return shadow(this,"RBRACE",new PostScriptToken(as.RBRACE,"}"))}static get IF(){return shadow(this,"IF",new PostScriptToken(as.IF,"IF"))}static get IFELSE(){return shadow(this,"IFELSE",new PostScriptToken(as.IFELSE,"IFELSE"))}}class PostScriptLexer{constructor(e){this.stream=e;this.nextChar();this.strBuf=[]}nextChar(){return this.currentChar=this.stream.getByte()}getToken(){let e=!1,t=this.currentChar;for(;;){if(t<0)return Bt;if(e)10!==t&&13!==t||(e=!1);else if(37===t)e=!0;else if(!isWhiteSpace(t))break;t=this.nextChar()}switch(0|t){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 43:case 45:case 46:return new PostScriptToken(as.NUMBER,this.getNumber());case 123:this.nextChar();return PostScriptToken.LBRACE;case 125:this.nextChar();return PostScriptToken.RBRACE}const i=this.strBuf;i.length=0;i[0]=String.fromCharCode(t);for(;(t=this.nextChar())>=0&&(t>=65&&t<=90||t>=97&&t<=122);)i.push(String.fromCharCode(t));const a=i.join("");switch(a.toLowerCase()){case"if":return PostScriptToken.IF;case"ifelse":return PostScriptToken.IFELSE;default:return PostScriptToken.getOperator(a)}}getNumber(){let e=this.currentChar;const t=this.strBuf;t.length=0;t[0]=String.fromCharCode(e);for(;(e=this.nextChar())>=0&&(e>=48&&e<=57||45===e||46===e);)t.push(String.fromCharCode(e));const i=parseFloat(t.join(""));if(isNaN(i))throw new FormatError(`Invalid floating point number: ${i}`);return i}}class BaseLocalCache{constructor(e){this._onlyRefs=!0===e?.onlyRefs;if(!this._onlyRefs){this._nameRefMap=new Map;this._imageMap=new Map}this._imageCache=new RefSetCache}getByName(e){this._onlyRefs&&unreachable("Should not call `getByName` method.");const t=this._nameRefMap.get(e);return t?this.getByRef(t):this._imageMap.get(e)||null}getByRef(e){return this._imageCache.get(e)||null}set(e,t,i){unreachable("Abstract method `set` called.")}}class LocalImageCache extends BaseLocalCache{set(e,t=null,i){if("string"!=typeof e)throw new Error('LocalImageCache.set - expected "name" argument.');if(t){if(this._imageCache.has(t))return;this._nameRefMap.set(e,t);this._imageCache.put(t,i)}else this._imageMap.has(e)||this._imageMap.set(e,i)}}class LocalColorSpaceCache extends BaseLocalCache{set(e=null,t=null,i){if("string"!=typeof e&&!t)throw new Error('LocalColorSpaceCache.set - expected "name" and/or "ref" argument.');if(t){if(this._imageCache.has(t))return;null!==e&&this._nameRefMap.set(e,t);this._imageCache.put(t,i)}else this._imageMap.has(e)||this._imageMap.set(e,i)}}class LocalFunctionCache extends BaseLocalCache{constructor(e){super({onlyRefs:!0})}set(e=null,t,i){if(!t)throw new Error('LocalFunctionCache.set - expected "ref" argument.');this._imageCache.has(t)||this._imageCache.put(t,i)}}class LocalGStateCache extends BaseLocalCache{set(e,t=null,i){if("string"!=typeof e)throw new Error('LocalGStateCache.set - expected "name" argument.');if(t){if(this._imageCache.has(t))return;this._nameRefMap.set(e,t);this._imageCache.put(t,i)}else this._imageMap.has(e)||this._imageMap.set(e,i)}}class LocalTilingPatternCache extends BaseLocalCache{constructor(e){super({onlyRefs:!0})}set(e=null,t,i){if(!t)throw new Error('LocalTilingPatternCache.set - expected "ref" argument.');this._imageCache.has(t)||this._imageCache.put(t,i)}}class RegionalImageCache extends BaseLocalCache{constructor(e){super({onlyRefs:!0})}set(e=null,t,i){if(!t)throw new Error('RegionalImageCache.set - expected "ref" argument.');this._imageCache.has(t)||this._imageCache.put(t,i)}}class GlobalImageCache{static NUM_PAGES_THRESHOLD=2;static MIN_IMAGES_TO_CACHE=10;static MAX_BYTE_SIZE=5e7;#F=new RefSet;constructor(){this._refCache=new RefSetCache;this._imageCache=new RefSetCache}get#S(){let e=0;for(const t of this._imageCache)e+=t.byteSize;return e}get#k(){return!(this._imageCache.size+e)):null}class PDFFunction{static getSampleArray(e,t,i,a){let s,r,n=1;for(s=0,r=e.length;s>o)*C;c&=(1<i?e=i:e0&&(l=r[h-1]);let Q=a[1];h>1,c=s.length>>1,C=new PostScriptEvaluator(g),h=Object.create(null);let l=8192;const Q=new Float32Array(c);return function constructPostScriptFn(e,t,i,a){let s,n,g="";const E=Q;for(s=0;se&&(n=e)}d[s]=n}if(l>0){l--;h[g]=d}i.set(d,a)}}}function isPDFFunction(e){let t;if(e instanceof Dict)t=e;else{if(!(e instanceof BaseStream))return!1;t=e.dict}return t.has("FunctionType")}class PostScriptStack{static MAX_STACK_SIZE=100;constructor(e){this.stack=e?Array.from(e):[]}push(e){if(this.stack.length>=PostScriptStack.MAX_STACK_SIZE)throw new Error("PostScript function stack overflow.");this.stack.push(e)}pop(){if(this.stack.length<=0)throw new Error("PostScript function stack underflow.");return this.stack.pop()}copy(e){if(this.stack.length+e>=PostScriptStack.MAX_STACK_SIZE)throw new Error("PostScript function stack overflow.");const t=this.stack;for(let i=t.length-e,a=e-1;a>=0;a--,i++)t.push(t[i])}index(e){this.push(this.stack[this.stack.length-e-1])}roll(e,t){const i=this.stack,a=i.length-e,s=i.length-1,r=a+(t-Math.floor(t/e)*e);for(let e=a,t=s;e0?t.push(n<>g);break;case"ceiling":n=t.pop();t.push(Math.ceil(n));break;case"copy":n=t.pop();t.copy(n);break;case"cos":n=t.pop();t.push(Math.cos(n%360/180*Math.PI));break;case"cvi":n=0|t.pop();t.push(n);break;case"cvr":break;case"div":g=t.pop();n=t.pop();t.push(n/g);break;case"dup":t.copy(1);break;case"eq":g=t.pop();n=t.pop();t.push(n===g);break;case"exch":t.roll(2,1);break;case"exp":g=t.pop();n=t.pop();t.push(n**g);break;case"false":t.push(!1);break;case"floor":n=t.pop();t.push(Math.floor(n));break;case"ge":g=t.pop();n=t.pop();t.push(n>=g);break;case"gt":g=t.pop();n=t.pop();t.push(n>g);break;case"idiv":g=t.pop();n=t.pop();t.push(n/g|0);break;case"index":n=t.pop();t.index(n);break;case"le":g=t.pop();n=t.pop();t.push(n<=g);break;case"ln":n=t.pop();t.push(Math.log(n));break;case"log":n=t.pop();t.push(Math.log10(n));break;case"lt":g=t.pop();n=t.pop();t.push(n=t?new AstLiteral(t):e.max<=t?e:new AstMin(e,t)}class PostScriptCompiler{compile(e,t,i){const a=[],s=[],r=t.length>>1,n=i.length>>1;let g,o,c,C,h,l,Q,E,u=0;for(let e=0;et.min){g.unshift("Math.max(",r,", ");g.push(")")}if(n4){a=!0;t=0}else{a=!1;t=1}const o=[];for(r=0;r=0&&"ET"===gs[e];--e)gs[e]="EN";for(let e=r+1;e0&&(t=gs[r-1]);let i=h;e+1E&&isOdd(E)&&(d=E)}for(E=u;E>=d;--E){let e=-1;for(r=0,n=o.length;r=0){reverseValues(ns,e,r);e=-1}}else e<0&&(e=r);e>=0&&reverseValues(ns,e,o.length)}for(r=0,n=ns.length;r"!==e||(ns[r]="")}return createBidiText(ns.join(""),a)}const os={style:"normal",weight:"normal"},Is={style:"normal",weight:"bold"},cs={style:"italic",weight:"normal"},Cs={style:"italic",weight:"bold"},hs=new Map([["Times-Roman",{local:["Times New Roman","Times-Roman","Times","Liberation Serif","Nimbus Roman","Nimbus Roman L","Tinos","Thorndale","TeX Gyre Termes","FreeSerif","Linux Libertine O","Libertinus Serif","DejaVu Serif","Bitstream Vera Serif","Ubuntu"],style:os,ultimate:"serif"}],["Times-Bold",{alias:"Times-Roman",style:Is,ultimate:"serif"}],["Times-Italic",{alias:"Times-Roman",style:cs,ultimate:"serif"}],["Times-BoldItalic",{alias:"Times-Roman",style:Cs,ultimate:"serif"}],["Helvetica",{local:["Helvetica","Helvetica Neue","Arial","Arial Nova","Liberation Sans","Arimo","Nimbus Sans","Nimbus Sans L","A030","TeX Gyre Heros","FreeSans","DejaVu Sans","Albany","Bitstream Vera Sans","Arial Unicode MS","Microsoft Sans Serif","Apple Symbols","Cantarell"],path:"LiberationSans-Regular.ttf",style:os,ultimate:"sans-serif"}],["Helvetica-Bold",{alias:"Helvetica",path:"LiberationSans-Bold.ttf",style:Is,ultimate:"sans-serif"}],["Helvetica-Oblique",{alias:"Helvetica",path:"LiberationSans-Italic.ttf",style:cs,ultimate:"sans-serif"}],["Helvetica-BoldOblique",{alias:"Helvetica",path:"LiberationSans-BoldItalic.ttf",style:Cs,ultimate:"sans-serif"}],["Courier",{local:["Courier","Courier New","Liberation Mono","Nimbus Mono","Nimbus Mono L","Cousine","Cumberland","TeX Gyre Cursor","FreeMono","Linux Libertine Mono O","Libertinus Mono"],style:os,ultimate:"monospace"}],["Courier-Bold",{alias:"Courier",style:Is,ultimate:"monospace"}],["Courier-Oblique",{alias:"Courier",style:cs,ultimate:"monospace"}],["Courier-BoldOblique",{alias:"Courier",style:Cs,ultimate:"monospace"}],["ArialBlack",{local:["Arial Black"],style:{style:"normal",weight:"900"},fallback:"Helvetica-Bold"}],["ArialBlack-Bold",{alias:"ArialBlack"}],["ArialBlack-Italic",{alias:"ArialBlack",style:{style:"italic",weight:"900"},fallback:"Helvetica-BoldOblique"}],["ArialBlack-BoldItalic",{alias:"ArialBlack-Italic"}],["ArialNarrow",{local:["Arial Narrow","Liberation Sans Narrow","Helvetica Condensed","Nimbus Sans Narrow","TeX Gyre Heros Cn"],style:os,fallback:"Helvetica"}],["ArialNarrow-Bold",{alias:"ArialNarrow",style:Is,fallback:"Helvetica-Bold"}],["ArialNarrow-Italic",{alias:"ArialNarrow",style:cs,fallback:"Helvetica-Oblique"}],["ArialNarrow-BoldItalic",{alias:"ArialNarrow",style:Cs,fallback:"Helvetica-BoldOblique"}],["Calibri",{local:["Calibri","Carlito"],style:os,fallback:"Helvetica"}],["Calibri-Bold",{alias:"Calibri",style:Is,fallback:"Helvetica-Bold"}],["Calibri-Italic",{alias:"Calibri",style:cs,fallback:"Helvetica-Oblique"}],["Calibri-BoldItalic",{alias:"Calibri",style:Cs,fallback:"Helvetica-BoldOblique"}],["Wingdings",{local:["Wingdings","URW Dingbats"],style:os}],["Wingdings-Regular",{alias:"Wingdings"}],["Wingdings-Bold",{alias:"Wingdings"}]]),ls=new Map([["Arial-Black","ArialBlack"]]);function getFamilyName(e){const t=new Set(["thin","extralight","ultralight","demilight","semilight","light","book","regular","normal","medium","demibold","semibold","bold","extrabold","ultrabold","black","heavy","extrablack","ultrablack","roman","italic","oblique","ultracondensed","extracondensed","condensed","semicondensed","normal","semiexpanded","expanded","extraexpanded","ultraexpanded","bolditalic"]);return e.split(/[- ,+]+/g).filter((e=>!t.has(e.toLowerCase()))).join(" ")}function generateFont({alias:e,local:t,path:i,fallback:a,style:s,ultimate:r},n,g,o=!0,c=!0,C=""){const h={style:null,ultimate:null};if(t){const e=C?` ${C}`:"";for(const i of t)n.push(`local(${i}${e})`)}if(e){const t=hs.get(e),r=C||function getStyleToAppend(e){switch(e){case Is:return"Bold";case cs:return"Italic";case Cs:return"Bold Italic";default:if("bold"===e?.weight)return"Bold";if("italic"===e?.style)return"Italic"}return""}(s);Object.assign(h,generateFont(t,n,g,o&&!a,c&&!i,r))}s&&(h.style=s);r&&(h.ultimate=r);if(o&&a){const e=hs.get(a),{ultimate:t}=generateFont(e,n,g,o,c&&!i,C);h.ultimate||=t}c&&i&&g&&n.push(`url(${g}${i})`);return h}function getFontSubstitution(e,t,i,a,s,r){if(a.startsWith("InvalidPDFjsFont_"))return null;"TrueType"!==r&&"Type1"!==r||!/^[A-Z]{6}\+/.test(a)||(a=a.slice(7));const n=a=normalizeFontName(a);let g=e.get(n);if(g)return g;let o=hs.get(a);if(!o)for(const[e,t]of ls)if(a.startsWith(e)){a=`${t}${a.substring(e.length)}`;o=hs.get(a);break}let c=!1;if(!o){o=hs.get(s);c=!0}const C=`${t.getDocId()}_s${t.createFontId()}`;if(!o){if(!validateFontName(a)){warn(`Cannot substitute the font because of its name: ${a}`);e.set(n,null);return null}const t=/bold/gi.test(a),i=/oblique|italic/gi.test(a),s=t&&i&&Cs||t&&Is||i&&cs||os;g={css:`"${getFamilyName(a)}",${C}`,guessFallback:!0,loadedName:C,baseFontName:a,src:`local(${a})`,style:s};e.set(n,g);return g}const h=[];c&&validateFontName(a)&&h.push(`local(${a})`);const{style:l,ultimate:Q}=generateFont(o,h,i),E=null===Q,u=E?"":`,${Q}`;g={css:`"${getFamilyName(a)}",${C}${u}`,guessFallback:E,loadedName:C,baseFontName:a,src:h.join(","),style:l};e.set(n,g);return g}class ImageResizer{static#R=2048;static#y=FeatureTest.isImageDecoderSupported;constructor(e,t){this._imgData=e;this._isMask=t}static get canUseImageDecoder(){return shadow(this,"canUseImageDecoder",this.#y?ImageDecoder.isTypeSupported("image/bmp"):Promise.resolve(!1))}static needsToBeResized(e,t){if(e<=this.#R&&t<=this.#R)return!1;const{MAX_DIM:i}=this;if(e>i||t>i)return!0;const a=e*t;if(this._hasMaxArea)return a>this.MAX_AREA;if(a(this.MAX_AREA=this.#R**2)}static get MAX_DIM(){return shadow(this,"MAX_DIM",this._guessMax(2048,65537,0,1))}static get MAX_AREA(){this._hasMaxArea=!0;return shadow(this,"MAX_AREA",this._guessMax(this.#R,this.MAX_DIM,128,0)**2)}static set MAX_AREA(e){if(e>=0){this._hasMaxArea=!0;shadow(this,"MAX_AREA",e)}}static setOptions({canvasMaxAreaInBytes:e=-1,isImageDecoderSupported:t=!1}){this._hasMaxArea||(this.MAX_AREA=e>>2);this.#y=t}static _areGoodDims(e,t){try{const i=new OffscreenCanvas(e,t),a=i.getContext("2d");a.fillRect(0,0,1,1);const s=a.getImageData(0,0,1,1).data[3];i.width=i.height=1;return 0!==s}catch{return!1}}static _guessMax(e,t,i,a){for(;e+i+1pt){const e=this.#N();if(e)return e}const a=this._encodeBMP();let s,r;if(await ImageResizer.canUseImageDecoder){s=new ImageDecoder({data:a,type:"image/bmp",preferAnimation:!1,transfer:[a.buffer]});r=s.decode().catch((e=>{warn(`BMP image decoding failed: ${e}`);return createImageBitmap(new Blob([this._encodeBMP().buffer],{type:"image/bmp"}))})).finally((()=>{s.close()}))}else r=createImageBitmap(new Blob([a.buffer],{type:"image/bmp"}));const{MAX_AREA:n,MAX_DIM:g}=ImageResizer,o=Math.max(t/g,i/g,Math.sqrt(t*i/n)),c=Math.max(o,2),C=Math.round(10*(o+1.25))/10/c,h=Math.floor(Math.log2(C)),l=new Array(h+2).fill(2);l[0]=c;l.splice(-1,1,C/(1<>n,o=a>>n;let c,C=a;try{c=new Uint8Array(r)}catch{let e=Math.floor(Math.log2(r+1));for(;;)try{c=new Uint8Array(2**e-1);break}catch{e-=1}C=Math.floor((2**e-1)/(4*i));const t=i*C*4;t>n;e>3,n=i+3&-4;if(i!==n){const e=new Uint8Array(n*t);let a=0;for(let r=0,g=t*i;r>>8;t[i++]=255&s}}}else{if(!ArrayBuffer.isView(e))throw new Error("Invalid data format, must be a string or TypedArray.");t=e.slice();i=t.byteLength}const a=i>>2,s=i-4*a,r=new Uint32Array(t.buffer,0,a);let n=0,g=0,o=this.h1,c=this.h2;const C=3432918353,h=461845907,l=11601,Q=13715;for(let e=0;e>>17;n=n*h&Qs|n*Q&Es;o^=n;o=o<<13|o>>>19;o=5*o+3864292196}else{g=r[e];g=g*C&Qs|g*l&Es;g=g<<15|g>>>17;g=g*h&Qs|g*Q&Es;c^=g;c=c<<13|c>>>19;c=5*c+3864292196}n=0;switch(s){case 3:n^=t[4*a+2]<<16;case 2:n^=t[4*a+1]<<8;case 1:n^=t[4*a];n=n*C&Qs|n*l&Es;n=n<<15|n>>>17;n=n*h&Qs|n*Q&Es;1&a?o^=n:c^=n}this.h1=o;this.h2=c}hexdigest(){let e=this.h1,t=this.h2;e^=t>>>1;e=3981806797*e&Qs|36045*e&Es;t=4283543511*t&Qs|(2950163797*(t<<16|e>>>16)&Qs)>>>16;e^=t>>>1;e=444984403*e&Qs|60499*e&Es;t=3301882366*t&Qs|(3120437893*(t<<16|e>>>16)&Qs)>>>16;e^=t>>>1;return(e>>>0).toString(16).padStart(8,"0")+(t>>>0).toString(16).padStart(8,"0")}}function addState(e,t,i,a,s){let r=e;for(let e=0,i=t.length-1;e1e3){c=Math.max(c,l);Q+=h+2;l=0;h=0}C.push({transform:t,x:l,y:Q,w:i.width,h:i.height});l+=i.width+2;h=Math.max(h,i.height)}const E=Math.max(c,l)+1,u=Q+h+1,d=new Uint8Array(E*u*4),f=E<<2;for(let e=0;e=0;){t[r-4]=t[r];t[r-3]=t[r+1];t[r-2]=t[r+2];t[r-1]=t[r+3];t[r+i]=t[r+i-4];t[r+i+1]=t[r+i-3];t[r+i+2]=t[r+i-2];t[r+i+3]=t[r+i-1];r-=f}}const p={width:E,height:u};if(e.isOffscreenCanvasSupported){const e=new OffscreenCanvas(E,u);e.getContext("2d").putImageData(new ImageData(new Uint8ClampedArray(d.buffer),E,u),0,0);p.bitmap=e.transferToImageBitmap();p.data=null}else{p.kind=S;p.data=d}i.splice(r,4*o,$e);a.splice(r,4*o,[p,C]);return r+1}));addState(us,[MA,xA,Ze,UA],null,(function iterateImageMaskGroup(e,t){const i=e.fnArray,a=(t-(e.iCurr-3))%4;switch(a){case 0:return i[t]===MA;case 1:return i[t]===xA;case 2:return i[t]===Ze;case 3:return i[t]===UA}throw new Error(`iterateImageMaskGroup - invalid pos: ${a}`)}),(function foundImageMaskGroup(e,t){const i=e.fnArray,a=e.argsArray,s=e.iCurr,r=s-3,n=s-2,g=s-1;let o=Math.floor((t-r)/4);if(o<10)return t-(t-r)%4;let c,C,h=!1;const l=a[g][0],Q=a[n][0],E=a[n][1],u=a[n][2],d=a[n][3];if(E===u){h=!0;c=n+4;let e=g+4;for(let t=1;t=4&&i[r-4]===i[n]&&i[r-3]===i[g]&&i[r-2]===i[o]&&i[r-1]===i[c]&&a[r-4][0]===C&&a[r-4][1]===h){l++;Q-=5}let E=Q+4;for(let e=1;e=i)break}a=(a||us)[e[t]];if(a&&!Array.isArray(a)){r.iCurr=t;t++;if(!a.checkFn||(0,a.checkFn)(r)){s=a;a=null}else a=null}else t++}this.state=a;this.match=s;this.lastProcessed=t}flush(){for(;this.match;){const e=this.queue.fnArray.length;this.lastProcessed=(0,this.match.processFn)(this.context,e);this.match=null;this.state=null;this._optimize()}}reset(){this.state=null;this.match=null;this.lastProcessed=0}}class OperatorList{static CHUNK_SIZE=1e3;static CHUNK_SIZE_ABOUT=this.CHUNK_SIZE-5;constructor(e=0,t){this._streamSink=t;this.fnArray=[];this.argsArray=[];this.optimizer=!t||e&E?new NullOptimizer(this):new QueueOptimizer(this);this.dependencies=new Set;this._totalLength=0;this.weight=0;this._resolved=t?null:Promise.resolve()}set isOffscreenCanvasSupported(e){this.optimizer.isOffscreenCanvasSupported=e}get length(){return this.argsArray.length}get ready(){return this._resolved||this._streamSink.ready}get totalLength(){return this._totalLength+this.length}addOp(e,t){this.optimizer.push(e,t);this.weight++;this._streamSink&&(this.weight>=OperatorList.CHUNK_SIZE||this.weight>=OperatorList.CHUNK_SIZE_ABOUT&&(e===UA||e===ee))&&this.flush()}addImageOps(e,t,i,a=!1){if(a){this.addOp(MA);this.addOp(GA,[[["SMask",!1]]])}void 0!==i&&this.addOp(Ye,["OC",i]);this.addOp(e,t);void 0!==i&&this.addOp(ve,[]);a&&this.addOp(UA)}addDependency(e){if(!this.dependencies.has(e)){this.dependencies.add(e);this.addOp(wA,[e])}}addDependencies(e){for(const t of e)this.addDependency(t)}addOpList(e){if(e instanceof OperatorList){for(const t of e.dependencies)this.dependencies.add(t);for(let t=0,i=e.length;ta&&(e=a);return e}function resizeImageMask(e,t,i,a,s,r){const n=s*r;let g;g=t<=8?new Uint8Array(n):t<=16?new Uint16Array(n):new Uint32Array(n);const o=i/s,c=a/r;let C,h,l,Q,E=0;const u=new Uint16Array(s),d=i;for(C=0;C0&&Number.isInteger(i.height)&&i.height>0&&(i.width!==l||i.height!==Q)){warn("PDFImage - using the Width/Height of the image data, rather than the image dictionary.");l=i.width;Q=i.height}if(l<1||Q<1)throw new FormatError(`Invalid image width: ${l} or height: ${Q}`);this.width=l;this.height=Q;this.interpolate=c.get("I","Interpolate");this.imageMask=c.get("IM","ImageMask")||!1;this.matte=c.get("Matte")||!1;let E=i.bitsPerComponent;if(!E){E=c.get("BPC","BitsPerComponent");if(!E){if(!this.imageMask)throw new FormatError(`Bits per component missing in image: ${this.imageMask}`);E=1}}this.bpc=E;if(!this.imageMask){let s=c.getRaw("CS")||c.getRaw("ColorSpace");const r=!!s;if(r)this.jpxDecoderOptions?.smaskInData&&(s=Name.get("DeviceRGBA"));else if(this.jpxDecoderOptions)s=Name.get("DeviceRGBA");else switch(i.numComps){case 1:s=Name.get("DeviceGray");break;case 3:s=Name.get("DeviceRGB");break;case 4:s=Name.get("DeviceCMYK");break;default:throw new Error(`Images with ${i.numComps} color components not supported.`)}this.colorSpace=ColorSpace.parse({cs:s,xref:e,resources:a?t:null,pdfFunctionFactory:g,localColorSpaceCache:o});this.numComps=this.colorSpace.numComps;if(this.jpxDecoderOptions){this.jpxDecoderOptions.numComponents=r?this.numComp:0;this.jpxDecoderOptions.isIndexedColormap="Indexed"===this.colorSpace.name}}this.decode=c.getArray("D","Decode");this.needsDecode=!1;if(this.decode&&(this.colorSpace&&!this.colorSpace.isDefaultDecode(this.decode,E)||n&&!ColorSpace.isDefaultDecode(this.decode,1))){this.needsDecode=!0;const e=(1<>3)*i,g=e.byteLength;let o,c;if(!a||s&&!(n===g))if(s){o=new Uint8Array(n);o.set(e);o.fill(255,g)}else o=new Uint8Array(e);else o=e;if(s)for(c=0;c>7&1;n[l+1]=h>>6&1;n[l+2]=h>>5&1;n[l+3]=h>>4&1;n[l+4]=h>>3&1;n[l+5]=h>>2&1;n[l+6]=h>>1&1;n[l+7]=1&h;l+=8}if(l>=1}}}}else{let i=0;h=0;for(l=0,C=r;l>a;s<0?s=0:s>c&&(s=c);n[l]=s;h&=(1<n[a+1]){t=255;break}}g[C]=t}}}if(g)for(C=0,l=3,h=t*a;C>3,C=t&&ImageResizer.needsToBeResized(i,a);if(!this.smask&&!this.mask&&"DeviceRGBA"===this.colorSpace.name){s.kind=S;const e=s.data=await this.getImageBytes(g*n*4,{});return t?C?ImageResizer.createImage(s,!1):this.createBitmap(S,i,a,e):s}if(!e){let e;"DeviceGray"===this.colorSpace.name&&1===o?e=b:"DeviceRGB"!==this.colorSpace.name||8!==o||this.needsDecode||(e=F);if(e&&!this.smask&&!this.mask&&i===n&&a===g){const r=await this.#G(n,g);if(r)return r;const o=await this.getImageBytes(g*c,{});if(t)return C?ImageResizer.createImage({data:o,kind:e,width:i,height:a,interpolate:this.interpolate},this.needsDecode):this.createBitmap(e,n,g,o);s.kind=e;s.data=o;if(this.needsDecode){assert(e===b,"PDFImage.createImageData: The image must be grayscale.");const t=s.data;for(let e=0,i=t.length;e>3,n=await this.getImageBytes(a*r,{internal:!0}),g=this.getComponents(n);let o,c;if(1===s){c=i*a;if(this.needsDecode)for(o=0;o0&&t.args[0].count++}class TimeSlotManager{static TIME_SLOT_DURATION_MS=20;static CHECK_TIME_EVERY=100;constructor(){this.reset()}check(){if(++this.checkedh){const e="Image exceeded maximum allowed size and was removed.";if(this.options.ignoreErrors){warn(e);return}throw new Error(e)}let l;g.has("OC")&&(l=await this.parseMarkedContentProps(g.get("OC"),e));let Q,E;if(g.get("IM","ImageMask")||!1){const e=g.get("I","Interpolate"),i=c+7>>3,n=t.getBytes(i*C),h=g.getArray("D","Decode");if(this.parsingType3Font){Q=PDFImage.createRawMask({imgArray:n,width:c,height:C,imageIsFromDecodeStream:t instanceof DecodeStream,inverseDecode:h?.[0]>0,interpolate:e});Q.cached=!!s;E=[Q];a.addImageOps(Ze,E,l);if(s){const e={fn:Ze,args:E,optionalContent:l};r.set(s,o,e);o&&this._regionalImageCache.set(null,o,e)}return}Q=await PDFImage.createMask({imgArray:n,width:c,height:C,imageIsFromDecodeStream:t instanceof DecodeStream,inverseDecode:h?.[0]>0,interpolate:e,isOffscreenCanvasSupported:this.options.isOffscreenCanvasSupported});if(Q.isSingleOpaquePixel){a.addImageOps(tt,[],l);if(s){const e={fn:tt,args:[],optionalContent:l};r.set(s,o,e);o&&this._regionalImageCache.set(null,o,e)}return}const u=`mask_${this.idFactory.createObjId()}`;a.addDependency(u);Q.dataLen=Q.bitmap?Q.width*Q.height*4:Q.data.length;this._sendImgData(u,Q);E=[{data:u,width:Q.width,height:Q.height,interpolate:Q.interpolate,count:1}];a.addImageOps(Ze,E,l);if(s){const e={objId:u,fn:Ze,args:E,optionalContent:l};r.set(s,o,e);o&&this._regionalImageCache.set(null,o,e)}return}const u=g.has("SMask")||g.has("Mask");if(i&&c+C<200&&!u){try{const s=new PDFImage({xref:this.xref,res:e,image:t,isInline:i,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:n});Q=await s.createImageData(!0,!1);a.isOffscreenCanvasSupported=this.options.isOffscreenCanvasSupported;a.addImageOps(_e,[Q],l)}catch(e){const t=`Unable to decode inline image: "${e}".`;if(!this.options.ignoreErrors)throw new Error(t);warn(t)}return}let d=`img_${this.idFactory.createObjId()}`,f=!1;if(this.parsingType3Font)d=`${this.idFactory.getDocId()}_type3_${d}`;else if(s&&o){f=this.globalImageCache.shouldCache(o,this.pageIndex);if(f){assert(!i,"Cannot cache an inline image globally.");d=`${this.idFactory.getDocId()}_${d}`}}a.addDependency(d);E=[d,c,C];a.addImageOps(ze,E,l,u);if(f){if(this.globalImageCache.hasDecodeFailed(o)){this.globalImageCache.setData(o,{objId:d,fn:ze,args:E,optionalContent:l,hasMask:u,byteSize:0});this._sendImgData(d,null,f);return}if(c*C>25e4||u){const e=await this.handler.sendWithPromise("commonobj",[d,"CopyLocalImage",{imageRef:o}]);if(e){this.globalImageCache.setData(o,{objId:d,fn:ze,args:E,optionalContent:l,hasMask:u,byteSize:0});this.globalImageCache.addByteSize(o,e);return}}}PDFImage.buildImage({xref:this.xref,res:e,image:t,isInline:i,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:n}).then((async e=>{Q=await e.createImageData(!1,this.options.isOffscreenCanvasSupported);Q.dataLen=Q.bitmap?Q.width*Q.height*4:Q.data.length;Q.ref=o;f&&this.globalImageCache.addByteSize(o,Q.dataLen);return this._sendImgData(d,Q,f)})).catch((e=>{warn(`Unable to decode image "${d}": "${e}".`);o&&this.globalImageCache.addDecodeFailed(o);return this._sendImgData(d,null,f)}));if(s){const e={objId:d,fn:ze,args:E,optionalContent:l,hasMask:u};r.set(s,o,e);if(o){this._regionalImageCache.set(null,o,e);f&&this.globalImageCache.setData(o,{objId:d,fn:ze,args:E,optionalContent:l,hasMask:u,byteSize:0})}}}handleSMask(e,t,i,a,s,r){const n=e.get("G"),g={subtype:e.get("S").name,backdrop:e.get("BC")},o=e.get("TR");if(isPDFFunction(o)){const e=this._pdfFunctionFactory.create(o),t=new Uint8Array(256),i=new Float32Array(1);for(let a=0;a<256;a++){i[0]=a/255;e(i,0,i,0);t[a]=255*i[0]|0}g.transferMap=t}return this.buildFormXObject(t,n,g,i,a,s.state.clone(),r)}handleTransferFunction(e){let t;if(Array.isArray(e))t=e;else{if(!isPDFFunction(e))return null;t=[e]}const i=[];let a=0,s=0;for(const e of t){const t=this.xref.fetchIfRef(e);a++;if(isName(t,"Identity")){i.push(null);continue}if(!isPDFFunction(t))return null;const r=this._pdfFunctionFactory.create(t),n=new Uint8Array(256),g=new Float32Array(1);for(let e=0;e<256;e++){g[0]=e/255;r(g,0,g,0);n[e]=255*g[0]|0}i.push(n);s++}return 1!==a&&4!==a||0===s?null:i}handleTilingType(e,t,i,a,s,r,n,g){const o=new OperatorList,c=Dict.merge({xref:this.xref,dictArray:[s.get("Resources"),i]});return this.getOperatorList({stream:a,task:n,resources:c,operatorList:o}).then((function(){const i=o.getIR(),a=getTilingPatternIR(i,s,t);r.addDependencies(o.dependencies);r.addOp(e,a);s.objId&&g.set(null,s.objId,{operatorListIR:i,dict:s})})).catch((e=>{if(!(e instanceof AbortException)){if(!this.options.ignoreErrors)throw e;warn(`handleTilingType - ignoring pattern: "${e}".`)}}))}async handleSetFont(e,t,i,a,s,r,n=null,g=null){const o=t?.[0]instanceof Name?t[0].name:null;let c=await this.loadFont(o,i,e,n,g);if(c.font.isType3Font)try{await c.loadType3Data(this,e,s);a.addDependencies(c.type3Dependencies)}catch(e){c=new TranslatedFont({loadedName:"g_font_error",font:new ErrorFont(`Type3 font load error: ${e}`),dict:c.font,evaluatorOptions:this.options})}r.font=c.font;c.send(this.handler);return c.loadedName}handleText(e,t){const i=t.font,a=i.charsToGlyphs(e);if(i.data){(!!(t.textRenderingMode&D)||"Pattern"===t.fillColorSpace.name||i.disableFontFace||this.options.disableFontFace)&&PartialEvaluator.buildFontPaths(i,a,this.handler,this.options)}return a}ensureStateFont(e){if(e.font)return;const t=new FormatError("Missing setFont (Tf) operator before text rendering operator.");if(!this.options.ignoreErrors)throw t;warn(`ensureStateFont: "${t}".`)}async setGState({resources:e,gState:t,operatorList:i,cacheKey:a,task:s,stateManager:r,localGStateCache:n,localColorSpaceCache:g}){const o=t.objId;let c=!0;const C=[];let h=Promise.resolve();for(const a of t.getKeys()){const n=t.get(a);switch(a){case"Type":break;case"LW":case"LC":case"LJ":case"ML":case"D":case"RI":case"FL":case"CA":case"ca":C.push([a,n]);break;case"Font":c=!1;h=h.then((()=>this.handleSetFont(e,null,n[0],i,s,r.state).then((function(e){i.addDependency(e);C.push([a,[e,n[1]]])}))));break;case"BM":C.push([a,normalizeBlendMode(n)]);break;case"SMask":if(isName(n,"None")){C.push([a,!1]);break}if(n instanceof Dict){c=!1;h=h.then((()=>this.handleSMask(n,e,i,s,r,g)));C.push([a,!0])}else warn("Unsupported SMask type");break;case"TR":const t=this.handleTransferFunction(n);C.push([a,t]);break;case"OP":case"op":case"OPM":case"BG":case"BG2":case"UCR":case"UCR2":case"TR2":case"HT":case"SM":case"SA":case"AIS":case"TK":info("graphic state operator "+a);break;default:info("Unknown graphic state operator "+a)}}await h;C.length>0&&i.addOp(GA,[C]);c&&n.set(a,o,C)}loadFont(e,t,i,a=null,s=null){const errorFont=async()=>new TranslatedFont({loadedName:"g_font_error",font:new ErrorFont(`Font "${e}" is not available.`),dict:t,evaluatorOptions:this.options});let r;if(t)t instanceof Ref&&(r=t);else{const t=i.get("Font");t&&(r=t.getRaw(e))}if(r){if(this.type3FontRefs?.has(r))return errorFont();if(this.fontCache.has(r))return this.fontCache.get(r);try{t=this.xref.fetchIfRef(r)}catch(e){warn(`loadFont - lookup failed: "${e}".`)}}if(!(t instanceof Dict)){if(!this.options.ignoreErrors&&!this.parsingType3Font){warn(`Font "${e}" is not available.`);return errorFont()}warn(`Font "${e}" is not available -- attempting to fallback to a default font.`);t=a||PartialEvaluator.fallbackFontDict}if(t.cacheKey&&this.fontCache.has(t.cacheKey))return this.fontCache.get(t.cacheKey);const{promise:n,resolve:g}=Promise.withResolvers();let o;try{o=this.preEvaluateFont(t);o.cssFontInfo=s}catch(e){warn(`loadFont - preEvaluateFont failed: "${e}".`);return errorFont()}const{descriptor:c,hash:C}=o,h=r instanceof Ref;let l;if(C&&c instanceof Dict){const e=c.fontAliases||=Object.create(null);if(e[C]){const t=e[C].aliasRef;if(h&&t&&this.fontCache.has(t)){this.fontCache.putAlias(r,t);return this.fontCache.get(r)}}else e[C]={fontID:this.idFactory.createFontId()};h&&(e[C].aliasRef=r);l=e[C].fontID}else l=this.idFactory.createFontId();assert(l?.startsWith("f"),'The "fontID" must be (correctly) defined.');if(h)this.fontCache.put(r,n);else{t.cacheKey=`cacheKey_${l}`;this.fontCache.put(t.cacheKey,n)}t.loadedName=`${this.idFactory.getDocId()}_${l}`;this.translateFont(o).then((e=>{g(new TranslatedFont({loadedName:t.loadedName,font:e,dict:t,evaluatorOptions:this.options}))})).catch((e=>{warn(`loadFont - translateFont failed: "${e}".`);g(new TranslatedFont({loadedName:t.loadedName,font:new ErrorFont(e instanceof Error?e.message:e),dict:t,evaluatorOptions:this.options}))}));return n}buildPath(e,t,i,a=!1){const s=e.length-1;i||(i=[]);if(s<0||e.fnArray[s]!==it){if(a){warn(`Encountered path operator "${t}" inside of a text object.`);e.addOp(MA,null)}let s;switch(t){case TA:const e=i[0]+i[2],t=i[1]+i[3];s=[Math.min(i[0],e),Math.min(i[1],t),Math.max(i[0],e),Math.max(i[1],t)];break;case LA:case HA:s=[i[0],i[1],i[0],i[1]];break;default:s=[1/0,1/0,-1/0,-1/0]}e.addOp(it,[[t],i,s]);a&&e.addOp(UA,null)}else{const a=e.argsArray[s];a[0].push(t);a[1].push(...i);const r=a[2];switch(t){case TA:const e=i[0]+i[2],t=i[1]+i[3];r[0]=Math.min(r[0],i[0],e);r[1]=Math.min(r[1],i[1],t);r[2]=Math.max(r[2],i[0],e);r[3]=Math.max(r[3],i[1],t);break;case LA:case HA:r[0]=Math.min(r[0],i[0]);r[1]=Math.min(r[1],i[1]);r[2]=Math.max(r[2],i[0]);r[3]=Math.max(r[3],i[1])}}}parseColorSpace({cs:e,resources:t,localColorSpaceCache:i}){return ColorSpace.parseAsync({cs:e,xref:this.xref,resources:t,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:i}).catch((e=>{if(e instanceof AbortException)return null;if(this.options.ignoreErrors){warn(`parseColorSpace - ignoring ColorSpace: "${e}".`);return null}throw e}))}parseShading({shading:e,resources:t,localColorSpaceCache:i,localShadingPatternCache:a}){let s,r=a.get(e);if(r)return r;try{s=Pattern.parseShading(e,this.xref,t,this._pdfFunctionFactory,i).getIR()}catch(t){if(t instanceof AbortException)return null;if(this.options.ignoreErrors){warn(`parseShading - ignoring shading: "${t}".`);a.set(e,null);return null}throw t}r=`pattern_${this.idFactory.createObjId()}`;this.parsingType3Font&&(r=`${this.idFactory.getDocId()}_type3_${r}`);a.set(e,r);this.parsingType3Font?this.handler.send("commonobj",[r,"Pattern",s]):this.handler.send("obj",[r,this.pageIndex,"Pattern",s]);return r}handleColorN(e,t,i,a,s,r,n,g,o,c){const C=i.pop();if(C instanceof Name){const h=s.getRaw(C.name),l=h instanceof Ref&&o.getByRef(h);if(l)try{const s=a.base?a.base.getRgb(i,0):null,r=getTilingPatternIR(l.operatorListIR,l.dict,s);e.addOp(t,r);return}catch{}const Q=this.xref.fetchIfRef(h);if(Q){const s=Q instanceof BaseStream?Q.dict:Q,C=s.get("PatternType");if(C===fs){const g=a.base?a.base.getRgb(i,0):null;return this.handleTilingType(t,g,r,Q,s,e,n,o)}if(C===ps){const i=s.get("Shading"),a=this.parseShading({shading:i,resources:r,localColorSpaceCache:g,localShadingPatternCache:c});if(a){const i=lookupMatrix(s.getArray("Matrix"),null);e.addOp(t,["Shading",a,i])}return}throw new FormatError(`Unknown PatternType: ${C}`)}}throw new FormatError(`Unknown PatternName: ${C}`)}_parseVisibilityExpression(e,t,i){if(++t>10){warn("Visibility expression is too deeply nested");return}const a=e.length,s=this.xref.fetchIfRef(e[0]);if(!(a<2)&&s instanceof Name){switch(s.name){case"And":case"Or":case"Not":i.push(s.name);break;default:warn(`Invalid operator ${s.name} in visibility expression`);return}for(let s=1;s0)return{type:"OCMD",expression:t}}const t=i.get("OCGs");if(Array.isArray(t)||t instanceof Dict){const e=[];if(Array.isArray(t))for(const i of t)e.push(i.toString());else e.push(t.objId);return{type:a,ids:e,policy:i.get("P")instanceof Name?i.get("P").name:null,expression:null}}if(t instanceof Ref)return{type:a,id:t.toString()}}return null}getOperatorList({stream:e,task:t,resources:i,operatorList:a,initialState:s=null,fallbackFontDict:r=null}){i||=Dict.empty;s||=new EvalState;if(!a)throw new Error('getOperatorList: missing "operatorList" parameter');const n=this,g=this.xref;let o=!1;const c=new LocalImageCache,C=new LocalColorSpaceCache,h=new LocalGStateCache,l=new LocalTilingPatternCache,Q=new Map,E=i.get("XObject")||Dict.empty,u=i.get("Pattern")||Dict.empty,d=new StateManager(s),f=new EvaluatorPreprocessor(e,g,d),p=new TimeSlotManager;function closePendingRestoreOPS(e){for(let e=0,t=f.savedStatesDepth;e0&&a.addOp(GA,[t]);e=null;continue}}next(new Promise((function(e,s){if(!S)throw new FormatError("GState must be referred to by name.");const r=i.get("ExtGState");if(!(r instanceof Dict))throw new FormatError("ExtGState should be a dictionary.");const g=r.get(F);if(!(g instanceof Dict))throw new FormatError("GState should be a dictionary.");n.setGState({resources:i,gState:g,operatorList:a,cacheKey:F,task:t,stateManager:d,localGStateCache:h,localColorSpaceCache:C}).then(e,s)})).catch((function(e){if(!(e instanceof AbortException)){if(!n.options.ignoreErrors)throw e;warn(`getOperatorList - ignoring ExtGState: "${e}".`)}})));return;case LA:case HA:case JA:case YA:case vA:case KA:case TA:n.buildPath(a,s,e,o);continue;case Le:case He:case Ke:case Te:continue;case Ye:if(!(e[0]instanceof Name)){warn(`Expected name for beginMarkedContentProps arg0=${e[0]}`);a.addOp(Ye,["OC",null]);continue}if("OC"===e[0].name){next(n.parseMarkedContentProps(e[1],i).then((e=>{a.addOp(Ye,["OC",e])})).catch((e=>{if(!(e instanceof AbortException)){if(!n.options.ignoreErrors)throw e;warn(`getOperatorList - ignoring beginMarkedContentProps: "${e}".`);a.addOp(Ye,["OC",null])}})));return}e=[e[0].name,e[1]instanceof Dict?e[1].get("MCID"):null];break;default:if(null!==e){for(w=0,D=e.length;w{if(!(e instanceof AbortException)){if(!this.options.ignoreErrors)throw e;warn(`getOperatorList - ignoring errors during "${t.name}" task: "${e}".`);closePendingRestoreOPS()}}))}getTextContent({stream:e,task:t,resources:s,stateManager:r=null,includeMarkedContent:n=!1,sink:g,seenStyles:o=new Set,viewBox:c,lang:C=null,markedContentData:h=null,disableNormalization:l=!1,keepWhiteSpace:Q=!1}){s||=Dict.empty;r||=new StateManager(new TextState);n&&(h||={level:0});const E={items:[],styles:Object.create(null),lang:C},u={initialized:!1,str:[],totalWidth:0,totalHeight:0,width:0,height:0,vertical:!1,prevTransform:null,textAdvanceScale:0,spaceInFlowMin:0,spaceInFlowMax:0,trackingSpaceMin:1/0,negativeSpaceMax:-1/0,notASpace:-1/0,transform:null,fontName:null,hasEOL:!1},d=[" "," "];let f=0;function saveLastChar(e){const t=(f+1)%2,i=" "!==d[f]&&" "===d[t];d[f]=e;f=t;return!Q&&i}function shouldAddWhitepsace(){return!Q&&" "!==d[f]&&" "===d[(f+1)%2]}function resetLastChars(){d[0]=d[1]=" ";f=0}const p=this,m=this.xref,y=[];let w=null;const D=new LocalImageCache,b=new LocalGStateCache,F=new EvaluatorPreprocessor(e,m,r);let S;function pushWhitespace({width:e=0,height:t=0,transform:i=u.prevTransform,fontName:a=u.fontName}){E.items.push({str:" ",dir:"ltr",width:e,height:t,transform:i,fontName:a,hasEOL:!1})}function getCurrentTextTransform(){const e=S.font,t=[S.fontSize*S.textHScale,0,0,S.fontSize,0,S.textRise];if(e.isType3Font&&(S.fontSize<=1||e.isCharBBox)&&!isArrayEqual(S.fontMatrix,a)){const i=e.bbox[3]-e.bbox[1];i>0&&(t[3]*=i*S.fontMatrix[3])}return Util.transform(S.ctm,Util.transform(S.textMatrix,t))}function ensureTextContentItem(){if(u.initialized)return u;const{font:e,loadedName:t}=S;if(!o.has(t)){o.add(t);E.styles[t]={fontFamily:e.fallbackName,ascent:e.ascent,descent:e.descent,vertical:e.vertical};if(p.options.fontExtraProperties&&e.systemFontInfo){const i=E.styles[t];i.fontSubstitution=e.systemFontInfo.css;i.fontSubstitutionLoadedName=e.systemFontInfo.loadedName}}u.fontName=t;const i=u.transform=getCurrentTextTransform();if(e.vertical){u.width=u.totalWidth=Math.hypot(i[0],i[1]);u.height=u.totalHeight=0;u.vertical=!0}else{u.width=u.totalWidth=0;u.height=u.totalHeight=Math.hypot(i[2],i[3]);u.vertical=!1}const a=Math.hypot(S.textLineMatrix[0],S.textLineMatrix[1]),s=Math.hypot(S.ctm[0],S.ctm[1]);u.textAdvanceScale=s*a;const{fontSize:r}=S;u.trackingSpaceMin=.102*r;u.notASpace=.03*r;u.negativeSpaceMax=-.2*r;u.spaceInFlowMin=.102*r;u.spaceInFlowMax=.6*r;u.hasEOL=!1;u.initialized=!0;return u}function updateAdvanceScale(){if(!u.initialized)return;const e=Math.hypot(S.textLineMatrix[0],S.textLineMatrix[1]),t=Math.hypot(S.ctm[0],S.ctm[1])*e;if(t!==u.textAdvanceScale){if(u.vertical){u.totalHeight+=u.height*u.textAdvanceScale;u.height=0}else{u.totalWidth+=u.width*u.textAdvanceScale;u.width=0}u.textAdvanceScale=t}}function runBidiTransform(e){let t=e.str.join("");l||(t=function normalizeUnicode(e){if(!Ct){Ct=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu;ht=new Map([["ſt","ſt"]])}return e.replaceAll(Ct,((e,t,i)=>t?t.normalize("NFKC"):ht.get(i)))}(t));const i=bidi(t,-1,e.vertical);return{str:i.str,dir:i.dir,width:Math.abs(e.totalWidth),height:Math.abs(e.totalHeight),transform:e.transform,fontName:e.fontName,hasEOL:e.hasEOL}}async function handleSetFont(e,i){const r=await p.loadFont(e,i,s);if(r.font.isType3Font)try{await r.loadType3Data(p,s,t)}catch{}S.loadedName=r.loadedName;S.font=r.font;S.fontMatrix=r.font.fontMatrix||a}function applyInverseRotation(e,t,i){const a=Math.hypot(i[0],i[1]);return[(i[0]*e+i[1]*t)/a,(i[2]*e+i[3]*t)/a]}function compareWithLastPosition(e){const t=getCurrentTextTransform();let i=t[4],a=t[5];if(S.font?.vertical){if(ic[2]||a+ec[3])return!1}else if(i+ec[2]||ac[3])return!1;if(!S.font||!u.prevTransform)return!0;let s=u.prevTransform[4],r=u.prevTransform[5];if(s===i&&r===a)return!0;let n=-1;t[0]&&0===t[1]&&0===t[2]?n=t[0]>0?0:180:t[1]&&0===t[0]&&0===t[3]&&(n=t[1]>0?90:270);switch(n){case 0:break;case 90:[i,a]=[a,i];[s,r]=[r,s];break;case 180:[i,a,s,r]=[-i,-a,-s,-r];break;case 270:[i,a]=[-a,-i];[s,r]=[-r,-s];break;default:[i,a]=applyInverseRotation(i,a,t);[s,r]=applyInverseRotation(s,r,u.prevTransform)}if(S.font.vertical){const e=(r-a)/u.textAdvanceScale,t=i-s,n=Math.sign(u.height);if(e.5*u.width){appendEOL();return!0}resetLastChars();flushTextContentItem();return!0}if(Math.abs(t)>u.width){appendEOL();return!0}e<=n*u.notASpace&&resetLastChars();if(e<=n*u.trackingSpaceMin)if(shouldAddWhitepsace()){resetLastChars();flushTextContentItem();pushWhitespace({height:Math.abs(e)})}else u.height+=e;else if(!addFakeSpaces(e,u.prevTransform,n))if(0===u.str.length){resetLastChars();pushWhitespace({height:Math.abs(e)})}else u.height+=e;Math.abs(t)>.25*u.width&&flushTextContentItem();return!0}const g=(i-s)/u.textAdvanceScale,o=a-r,C=Math.sign(u.width);if(g.5*u.height){appendEOL();return!0}resetLastChars();flushTextContentItem();return!0}if(Math.abs(o)>u.height){appendEOL();return!0}g<=C*u.notASpace&&resetLastChars();if(g<=C*u.trackingSpaceMin)if(shouldAddWhitepsace()){resetLastChars();flushTextContentItem();pushWhitespace({width:Math.abs(g)})}else u.width+=g;else if(!addFakeSpaces(g,u.prevTransform,C))if(0===u.str.length){resetLastChars();pushWhitespace({width:Math.abs(g)})}else u.width+=g;Math.abs(o)>.25*u.height&&flushTextContentItem();return!0}function buildTextContentItem({chars:e,extraSpacing:t}){const i=S.font;if(!e){const e=S.charSpacing+t;e&&(i.vertical?S.translateTextMatrix(0,-e):S.translateTextMatrix(e*S.textHScale,0));Q&&compareWithLastPosition(0);return}const a=i.charsToGlyphs(e),s=S.fontMatrix[0]*S.fontSize;for(let e=0,r=a.length;e0){const e=y.join("");y.length=0;buildTextContentItem({chars:e,extraSpacing:0})}break;case he:if(!r.state.font){p.ensureStateFont(r.state);continue}buildTextContentItem({chars:N[0],extraSpacing:0});break;case Be:if(!r.state.font){p.ensureStateFont(r.state);continue}S.carriageReturn();buildTextContentItem({chars:N[0],extraSpacing:0});break;case Qe:if(!r.state.font){p.ensureStateFont(r.state);continue}S.wordSpacing=N[0];S.charSpacing=N[1];S.carriageReturn();buildTextContentItem({chars:N[2],extraSpacing:0});break;case xe:flushTextContentItem();w??=s.get("XObject")||Dict.empty;R=N[0]instanceof Name;f=N[0].name;if(R&&D.getByName(f))break;next(new Promise((function(e,i){if(!R)throw new FormatError("XObject must be referred to by name.");let a=w.getRaw(f);if(a instanceof Ref){if(D.getByRef(a)){e();return}if(p.globalImageCache.getData(a,p.pageIndex)){e();return}a=m.fetch(a)}if(!(a instanceof BaseStream))throw new FormatError("XObject should be a stream");const E=a.dict.get("Subtype");if(!(E instanceof Name))throw new FormatError("XObject should have a Name subtype");if("Form"!==E.name){D.set(f,a.dict.objId,!0);e();return}const u=r.state.clone(),d=new StateManager(u),y=lookupMatrix(a.dict.getArray("Matrix"),null);y&&d.transform(y);enqueueChunk();const b={enqueueInvoked:!1,enqueue(e,t){this.enqueueInvoked=!0;g.enqueue(e,t)},get desiredSize(){return g.desiredSize},get ready(){return g.ready}};p.getTextContent({stream:a,task:t,resources:a.dict.get("Resources")||s,stateManager:d,includeMarkedContent:n,sink:b,seenStyles:o,viewBox:c,lang:C,markedContentData:h,disableNormalization:l,keepWhiteSpace:Q}).then((function(){b.enqueueInvoked||D.set(f,a.dict.objId,!0);e()}),i)})).catch((function(e){if(!(e instanceof AbortException)){if(!p.options.ignoreErrors)throw e;warn(`getTextContent - ignoring XObject: "${e}".`)}})));return;case GA:R=N[0]instanceof Name;f=N[0].name;if(R&&b.getByName(f))break;next(new Promise((function(e,t){if(!R)throw new FormatError("GState must be referred to by name.");const i=s.get("ExtGState");if(!(i instanceof Dict))throw new FormatError("ExtGState should be a dictionary.");const a=i.get(f);if(!(a instanceof Dict))throw new FormatError("GState should be a dictionary.");const r=a.get("Font");if(r){flushTextContentItem();S.fontName=null;S.fontSize=r[1];handleSetFont(null,r[0]).then(e,t)}else{b.set(f,a.objId,!0);e()}})).catch((function(e){if(!(e instanceof AbortException)){if(!p.options.ignoreErrors)throw e;warn(`getTextContent - ignoring ExtGState: "${e}".`)}})));return;case Je:flushTextContentItem();if(n){h.level++;E.items.push({type:"beginMarkedContent",tag:N[0]instanceof Name?N[0].name:null})}break;case Ye:flushTextContentItem();if(n){h.level++;let e=null;N[1]instanceof Dict&&(e=N[1].get("MCID"));E.items.push({type:"beginMarkedContentProps",id:Number.isInteger(e)?`${p.idFactory.getPageObjId()}_mc${e}`:null,tag:N[0]instanceof Name?N[0].name:null})}break;case ve:flushTextContentItem();if(n){if(0===h.level)break;h.level--;E.items.push({type:"endMarkedContent"})}break;case UA:!e||e.font===S.font&&e.fontSize===S.fontSize&&e.fontName===S.fontName||flushTextContentItem()}if(E.items.length>=g.desiredSize){d=!0;break}}if(d)next(ms);else{flushTextContentItem();enqueueChunk();e()}})).catch((e=>{if(!(e instanceof AbortException)){if(!this.options.ignoreErrors)throw e;warn(`getTextContent - ignoring errors during "${t.name}" task: "${e}".`);flushTextContentItem();enqueueChunk()}}))}async extractDataStructures(e,t){const i=this.xref;let a;const s=this.readToUnicode(t.toUnicode);if(t.composite){const i=e.get("CIDSystemInfo");i instanceof Dict&&(t.cidSystemInfo={registry:stringToPDFString(i.get("Registry")),ordering:stringToPDFString(i.get("Ordering")),supplement:i.get("Supplement")});try{const t=e.get("CIDToGIDMap");t instanceof BaseStream&&(a=t.getBytes())}catch(e){if(!this.options.ignoreErrors)throw e;warn(`extractDataStructures - ignoring CIDToGIDMap data: "${e}".`)}}const r=[];let n,g=null;if(e.has("Encoding")){n=e.get("Encoding");if(n instanceof Dict){g=n.get("BaseEncoding");g=g instanceof Name?g.name:null;if(n.has("Differences")){const e=n.get("Differences");let t=0;for(const a of e){const e=i.fetchIfRef(a);if("number"==typeof e)t=e;else{if(!(e instanceof Name))throw new FormatError(`Invalid entry in 'Differences' array: ${e}`);r[t++]=e.name}}}}else if(n instanceof Name)g=n.name;else{const e="Encoding is not a Name nor a Dict";if(!this.options.ignoreErrors)throw new FormatError(e);warn(e)}"MacRomanEncoding"!==g&&"MacExpertEncoding"!==g&&"WinAnsiEncoding"!==g&&(g=null)}const o=!t.file||t.isInternalFont,c=qi()[t.name];g&&o&&c&&(g=null);if(g)t.defaultEncoding=getEncoding(g);else{const e=!!(t.flags&Mi),i=!!(t.flags&xi);n=hi;"TrueType"!==t.type||i||(n=li);if(e||c){n=Ci;o&&(/Symbol/i.test(t.name)?n=Bi:/Dingbats/i.test(t.name)?n=Qi:/Wingdings/i.test(t.name)&&(n=li))}t.defaultEncoding=n}t.differences=r;t.baseEncodingName=g;t.hasEncoding=!!g||r.length>0;t.dict=e;t.toUnicode=await s;const C=await this.buildToUnicode(t);t.toUnicode=C;a&&(t.cidToGidMap=this.readCidToGidMap(a,C));return t}_simpleFontToUnicode(e,t=!1){assert(!e.composite,"Must be a simple font.");const i=[],a=e.defaultEncoding.slice(),s=e.baseEncodingName,r=e.differences;for(const e in r){const t=r[e];".notdef"!==t&&(a[e]=t)}const n=wi();for(const r in a){let g=a[r];if(""===g)continue;let o=n[g];if(void 0!==o){i[r]=String.fromCharCode(o);continue}let c=0;switch(g[0]){case"G":3===g.length&&(c=parseInt(g.substring(1),16));break;case"g":5===g.length&&(c=parseInt(g.substring(1),16));break;case"C":case"c":if(g.length>=3&&g.length<=4){const i=g.substring(1);if(t){c=parseInt(i,16);break}c=+i;if(Number.isNaN(c)&&Number.isInteger(parseInt(i,16)))return this._simpleFontToUnicode(e,!0)}break;case"u":o=getUnicodeForGlyph(g,n);-1!==o&&(c=o);break;default:switch(g){case"f_h":case"f_t":case"T_h":i[r]=g.replaceAll("_","");continue}}if(c>0&&c<=1114111&&Number.isInteger(c)){if(s&&c===+r){const e=getEncoding(s);if(e&&(g=e[r])){i[r]=String.fromCharCode(n[g]);continue}}i[r]=String.fromCodePoint(c)}}return i}async buildToUnicode(e){e.hasIncludedToUnicodeMap=e.toUnicode?.length>0;if(e.hasIncludedToUnicodeMap){!e.composite&&e.hasEncoding&&(e.fallbackToUnicode=this._simpleFontToUnicode(e));return e.toUnicode}if(!e.composite)return new ToUnicodeMap(this._simpleFontToUnicode(e));if(e.composite&&(e.cMap.builtInCMap&&!(e.cMap instanceof IdentityCMap)||"Adobe"===e.cidSystemInfo?.registry&&("GB1"===e.cidSystemInfo.ordering||"CNS1"===e.cidSystemInfo.ordering||"Japan1"===e.cidSystemInfo.ordering||"Korea1"===e.cidSystemInfo.ordering))){const{registry:t,ordering:i}=e.cidSystemInfo,a=Name.get(`${t}-${i}-UCS2`),s=await CMapFactory.create({encoding:a,fetchBuiltInCMap:this._fetchBuiltInCMapBound,useCMap:null}),r=[],n=[];e.cMap.forEach((function(e,t){if(t>65535)throw new FormatError("Max size of CID is 65,535");const i=s.lookup(t);if(i){n.length=0;for(let e=0,t=i.length;e>1;(0!==s||t.has(r))&&(i[r]=s)}return i}extractWidths(e,t,i){const a=this.xref;let s=[],r=0;const n=[];let g;if(i.composite){const t=e.get("DW");r="number"==typeof t?Math.ceil(t):1e3;const o=e.get("W");if(Array.isArray(o))for(let e=0,t=o.length;e{const t=o.get(e),s=new OperatorList;return a.getOperatorList({stream:t,task:i,resources:c,operatorList:s}).then((()=>{s.fnArray[0]===ue&&this._removeType3ColorOperators(s,E);C[e]=s.getIR();for(const e of s.dependencies)n.add(e)})).catch((function(t){warn(`Type3 font resource "${e}" is not available.`);const i=new OperatorList;C[e]=i.getIR()}))}));this.type3Loaded=g.then((()=>{r.charProcOperatorList=C;if(this._bbox){r.isCharBBox=!0;r.bbox=this._bbox}}));return this.type3Loaded}_removeType3ColorOperators(e,t=NaN){const i=Util.normalizeRect(e.argsArray[0].slice(2)),a=i[2]-i[0],s=i[3]-i[1],r=Math.hypot(a,s);if(0===a||0===s){e.fnArray.splice(0,1);e.argsArray.splice(0,1)}else if(0===t||Math.round(r/t)>=10){this._bbox||(this._bbox=[1/0,1/0,-1/0,-1/0]);this._bbox[0]=Math.min(this._bbox[0],i[0]);this._bbox[1]=Math.min(this._bbox[1],i[1]);this._bbox[2]=Math.max(this._bbox[2],i[2]);this._bbox[3]=Math.max(this._bbox[3],i[3])}let n=0,g=e.length;for(;n=LA&&r<=zA;if(s.variableArgs)g>n&&info(`Command ${a}: expected [0, ${n}] args, but received ${g} args.`);else{if(g!==n){const e=this.nonProcessedArgs;for(;g>n;){e.push(t.shift());g--}for(;gEvaluatorPreprocessor.MAX_INVALID_PATH_OPS)throw new FormatError(`Invalid ${e}`);warn(`Skipping ${e}`);null!==t&&(t.length=0);continue}}this.preprocessCommand(r,t);e.fn=r;e.args=t;return!0}if(i===Bt)return!1;if(null!==i){null===t&&(t=[]);t.push(i);if(t.length>33)throw new FormatError("Too many arguments")}}}preprocessCommand(e,t){switch(0|e){case MA:this.stateManager.save();break;case UA:this.stateManager.restore();break;case xA:this.stateManager.transform(t)}}}class DefaultAppearanceEvaluator extends EvaluatorPreprocessor{constructor(e){super(new StringStream(e))}parse(){const e={fn:0,args:[]},t={fontSize:0,fontName:"",fontColor:new Uint8ClampedArray(3)};try{for(;;){e.args.length=0;if(!this.read(e))break;if(0!==this.savedStatesDepth)continue;const{fn:i,args:a}=e;switch(0|i){case re:const[e,i]=a;e instanceof Name&&(t.fontName=e.name);"number"==typeof i&&i>0&&(t.fontSize=i);break;case Se:ColorSpace.singletons.rgb.getRgbItem(a,0,t.fontColor,0);break;case be:ColorSpace.singletons.gray.getRgbItem(a,0,t.fontColor,0);break;case Re:ColorSpace.singletons.cmyk.getRgbItem(a,0,t.fontColor,0)}}}catch(e){warn(`parseDefaultAppearance - ignoring errors: "${e}".`)}return t}}function parseDefaultAppearance(e){return new DefaultAppearanceEvaluator(e).parse()}class AppearanceStreamEvaluator extends EvaluatorPreprocessor{constructor(e,t,i){super(e);this.stream=e;this.evaluatorOptions=t;this.xref=i;this.resources=e.dict?.get("Resources")}parse(){const e={fn:0,args:[]};let t={scaleFactor:1,fontSize:0,fontName:"",fontColor:new Uint8ClampedArray(3),fillColorSpace:ColorSpace.singletons.gray},i=!1;const a=[];try{for(;;){e.args.length=0;if(i||!this.read(e))break;const{fn:s,args:r}=e;switch(0|s){case MA:a.push({scaleFactor:t.scaleFactor,fontSize:t.fontSize,fontName:t.fontName,fontColor:t.fontColor.slice(),fillColorSpace:t.fillColorSpace});break;case UA:t=a.pop()||t;break;case ce:t.scaleFactor*=Math.hypot(r[0],r[1]);break;case re:const[e,s]=r;e instanceof Name&&(t.fontName=e.name);"number"==typeof s&&s>0&&(t.fontSize=s*t.scaleFactor);break;case fe:t.fillColorSpace=ColorSpace.parse({cs:r[0],xref:this.xref,resources:this.resources,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:this._localColorSpaceCache});break;case ye:t.fillColorSpace.getRgbItem(r,0,t.fontColor,0);break;case Se:ColorSpace.singletons.rgb.getRgbItem(r,0,t.fontColor,0);break;case be:ColorSpace.singletons.gray.getRgbItem(r,0,t.fontColor,0);break;case Re:ColorSpace.singletons.cmyk.getRgbItem(r,0,t.fontColor,0);break;case he:case le:case Be:case Qe:i=!0}}}catch(e){warn(`parseAppearanceStream - ignoring errors: "${e}".`)}this.stream.reset();delete t.scaleFactor;delete t.fillColorSpace;return t}get _localColorSpaceCache(){return shadow(this,"_localColorSpaceCache",new LocalColorSpaceCache)}get _pdfFunctionFactory(){return shadow(this,"_pdfFunctionFactory",new PDFFunctionFactory({xref:this.xref,isEvalSupported:this.evaluatorOptions.isEvalSupported}))}}function getPdfColor(e,t){if(e[0]===e[1]&&e[1]===e[2]){return`${numberToString(e[0]/255)} ${t?"g":"G"}`}return Array.from(e,(e=>numberToString(e/255))).join(" ")+" "+(t?"rg":"RG")}class FakeUnicodeFont{constructor(e,t){this.xref=e;this.widths=null;this.firstChar=1/0;this.lastChar=-1/0;this.fontFamily=t;const i=new OffscreenCanvas(1,1);this.ctxMeasure=i.getContext("2d",{willReadFrequently:!0});FakeUnicodeFont._fontNameId||(FakeUnicodeFont._fontNameId=1);this.fontName=Name.get(`InvalidPDFjsFont_${t}_${FakeUnicodeFont._fontNameId++}`)}get fontDescriptorRef(){if(!FakeUnicodeFont._fontDescriptorRef){const e=new Dict(this.xref);e.set("Type",Name.get("FontDescriptor"));e.set("FontName",this.fontName);e.set("FontFamily","MyriadPro Regular");e.set("FontBBox",[0,0,0,0]);e.set("FontStretch",Name.get("Normal"));e.set("FontWeight",400);e.set("ItalicAngle",0);FakeUnicodeFont._fontDescriptorRef=this.xref.getNewPersistentRef(e)}return FakeUnicodeFont._fontDescriptorRef}get descendantFontRef(){const e=new Dict(this.xref);e.set("BaseFont",this.fontName);e.set("Type",Name.get("Font"));e.set("Subtype",Name.get("CIDFontType0"));e.set("CIDToGIDMap",Name.get("Identity"));e.set("FirstChar",this.firstChar);e.set("LastChar",this.lastChar);e.set("FontDescriptor",this.fontDescriptorRef);e.set("DW",1e3);const t=[],i=[...this.widths.entries()].sort();let a=null,s=null;for(const[e,r]of i)if(a)if(e===a+s.length)s.push(r);else{t.push(a,s);a=e;s=[r]}else{a=e;s=[r]}a&&t.push(a,s);e.set("W",t);const r=new Dict(this.xref);r.set("Ordering","Identity");r.set("Registry","Adobe");r.set("Supplement",0);e.set("CIDSystemInfo",r);return this.xref.getNewPersistentRef(e)}get baseFontRef(){const e=new Dict(this.xref);e.set("BaseFont",this.fontName);e.set("Type",Name.get("Font"));e.set("Subtype",Name.get("Type0"));e.set("Encoding",Name.get("Identity-H"));e.set("DescendantFonts",[this.descendantFontRef]);e.set("ToUnicode",Name.get("Identity-H"));return this.xref.getNewPersistentRef(e)}get resources(){const e=new Dict(this.xref),t=new Dict(this.xref);t.set(this.fontName.name,this.baseFontRef);e.set("Font",t);return e}_createContext(){this.widths=new Map;this.ctxMeasure.font=`1000px ${this.fontFamily}`;return this.ctxMeasure}createFontResources(e){const t=this._createContext();for(const i of e.split(/\r\n?|\n/))for(const e of i.split("")){const i=e.charCodeAt(0);if(this.widths.has(i))continue;const a=t.measureText(e),s=Math.ceil(a.width);this.widths.set(i,s);this.firstChar=Math.min(i,this.firstChar);this.lastChar=Math.max(i,this.lastChar)}return this.resources}static getFirstPositionInfo(e,t,i){const[a,n,g,o]=e;let c=g-a,C=o-n;t%180!=0&&([c,C]=[C,c]);const h=s*i;return{coords:[0,C+r*i-h],bbox:[0,0,c,C],matrix:0!==t?getRotationMatrix(t,C,h):void 0}}createAppearance(e,t,i,a,n,g){const o=this._createContext(),c=[];let C=-1/0;for(const t of e.split(/\r\n?|\n/)){c.push(t);const e=o.measureText(t).width;C=Math.max(C,e);for(const e of codePointIter(t)){const t=String.fromCodePoint(e);let i=this.widths.get(e);if(void 0===i){const a=o.measureText(t);i=Math.ceil(a.width);this.widths.set(e,i);this.firstChar=Math.min(e,this.firstChar);this.lastChar=Math.max(e,this.lastChar)}}}C*=a/1e3;const[h,l,Q,E]=t;let u=Q-h,d=E-l;i%180!=0&&([u,d]=[d,u]);let f=1;C>u&&(f=u/C);let p=1;const m=s*a,y=r*a,w=m*c.length;w>d&&(p=d/w);const D=a*Math.min(f,p),b=["q",`0 0 ${numberToString(u)} ${numberToString(d)} re W n`,"BT",`1 0 0 1 0 ${numberToString(d+y)} Tm 0 Tc ${getPdfColor(n,!0)}`,`/${this.fontName.name} ${numberToString(D)} Tf`],{resources:F}=this;if(1!==(g="number"==typeof g&&g>=0&&g<=1?g:1)){b.push("/R0 gs");const e=new Dict(this.xref),t=new Dict(this.xref);t.set("ca",g);t.set("CA",g);t.set("Type",Name.get("ExtGState"));e.set("R0",t);F.set("ExtGState",e)}const S=numberToString(m);for(const e of c)b.push(`0 -${S} Td <${stringToUTF16HexString(e)}> Tj`);b.push("ET","Q");const k=b.join("\n"),R=new Dict(this.xref);R.set("Subtype",Name.get("Form"));R.set("Type",Name.get("XObject"));R.set("BBox",[0,0,u,d]);R.set("Length",k.length);R.set("Resources",F);if(i){const e=getRotationMatrix(i,u,d);R.set("Matrix",e)}const N=new StringStream(k);N.dict=R;return N}}class NameOrNumberTree{constructor(e,t,i){this.root=e;this.xref=t;this._type=i}getAll(){const e=new Map;if(!this.root)return e;const t=this.xref,i=new RefSet;i.put(this.root);const a=[this.root];for(;a.length>0;){const s=t.fetchIfRef(a.shift());if(!(s instanceof Dict))continue;if(s.has("Kids")){const e=s.get("Kids");if(!Array.isArray(e))continue;for(const t of e){if(i.has(t))throw new FormatError(`Duplicate entry in "${this._type}" tree.`);a.push(t);i.put(t)}continue}const r=s.get(this._type);if(Array.isArray(r))for(let i=0,a=r.length;i10){warn(`Search depth limit reached for "${this._type}" tree.`);return null}const s=i.get("Kids");if(!Array.isArray(s))return null;let r=0,n=s.length-1;for(;r<=n;){const a=r+n>>1,g=t.fetchIfRef(s[a]),o=g.get("Limits");if(et.fetchIfRef(o[1]))){i=g;break}r=a+1}}if(r>n)return null}const s=i.get(this._type);if(Array.isArray(s)){let i=0,a=s.length-2;for(;i<=a;){const r=i+a>>1,n=r+(1&r),g=t.fetchIfRef(s[n]);if(eg))return s[n+1];i=n+2}}}return null}get(e){return this.xref.fetchIfRef(this.getRaw(e))}}class NameTree extends NameOrNumberTree{constructor(e,t){super(e,t,"Names")}}class NumberTree extends NameOrNumberTree{constructor(e,t){super(e,t,"Nums")}}function clearGlobalCaches(){!function clearPatternCaches(){Qa=Object.create(null)}();!function clearPrimitiveCaches(){Qt=Object.create(null);Et=Object.create(null);ut=Object.create(null)}();!function clearUnicodeCaches(){ki.clear()}();JpxImage.cleanup()}function pickPlatformItem(e){return e instanceof Dict?e.has("UF")?e.get("UF"):e.has("F")?e.get("F"):e.has("Unix")?e.get("Unix"):e.has("Mac")?e.get("Mac"):e.has("DOS")?e.get("DOS"):null:null}class FileSpec{#U=!1;constructor(e,t,i=!1){if(e instanceof Dict){this.xref=t;this.root=e;e.has("FS")&&(this.fs=e.get("FS"));e.has("RF")&&warn("Related file specifications are not supported");i||(e.has("EF")?this.#U=!0:warn("Non-embedded file specifications are not supported"))}}get filename(){let e="";const t=pickPlatformItem(this.root);t&&"string"==typeof t&&(e=stringToPDFString(t).replaceAll("\\\\","\\").replaceAll("\\/","/").replaceAll("\\","/"));return shadow(this,"filename",e||"unnamed")}get content(){if(!this.#U)return null;this._contentRef||=pickPlatformItem(this.root?.get("EF"));let e=null;if(this._contentRef){const t=this.xref.fetchIfRef(this._contentRef);t instanceof BaseStream?e=t.getBytes():warn("Embedded file specification points to non-existing/invalid content")}else warn("Embedded file specification does not have any content");return e}get description(){let e="";const t=this.root?.get("Desc");t&&"string"==typeof t&&(e=stringToPDFString(t));return shadow(this,"description",e)}get serializable(){return{rawFilename:this.filename,filename:(e=this.filename,e.substring(e.lastIndexOf("/")+1)),content:this.content,description:this.description};var e}}const ys=0,ws=-2,Ds=-3,bs=-4,Fs=-5,Ss=-6,ks=-9;function isWhitespace(e,t){const i=e[t];return" "===i||"\n"===i||"\r"===i||"\t"===i}class XMLParserBase{_resolveEntities(e){return e.replaceAll(/&([^;]+);/g,((e,t)=>{if("#x"===t.substring(0,2))return String.fromCodePoint(parseInt(t.substring(2),16));if("#"===t.substring(0,1))return String.fromCodePoint(parseInt(t.substring(1),10));switch(t){case"lt":return"<";case"gt":return">";case"amp":return"&";case"quot":return'"';case"apos":return"'"}return this.onResolveEntity(t)}))}_parseContent(e,t){const i=[];let a=t;function skipWs(){for(;a"!==e[a]&&"/"!==e[a];)++a;const s=e.substring(t,a);skipWs();for(;a"!==e[a]&&"/"!==e[a]&&"?"!==e[a];){skipWs();let t="",s="";for(;a"!==e[i]&&"?"!==e[i]&&"/"!==e[i];)++i;const a=e.substring(t,i);!function skipWs(){for(;i"!==e[i+1]);)++i;return{name:a,value:e.substring(s,i),parsed:i-t}}parseXml(e){let t=0;for(;t",i);if(t<0){this.onError(ks);return}this.onEndElement(e.substring(i,t));i=t+1;break;case"?":++i;const a=this._parseProcessingInstruction(e,i);if("?>"!==e.substring(i+a.parsed,i+a.parsed+2)){this.onError(Ds);return}this.onPi(a.name,a.value);i+=a.parsed+2;break;case"!":if("--"===e.substring(i+1,i+3)){t=e.indexOf("--\x3e",i+3);if(t<0){this.onError(Fs);return}this.onComment(e.substring(i+3,t));i=t+3}else if("[CDATA["===e.substring(i+1,i+8)){t=e.indexOf("]]>",i+8);if(t<0){this.onError(ws);return}this.onCdata(e.substring(i+8,t));i=t+3}else{if("DOCTYPE"!==e.substring(i+1,i+8)){this.onError(Ss);return}{const a=e.indexOf("[",i+8);let s=!1;t=e.indexOf(">",i+8);if(t<0){this.onError(bs);return}if(a>0&&t>a){t=e.indexOf("]>",i+8);if(t<0){this.onError(bs);return}s=!0}const r=e.substring(i+8,t+(s?1:0));this.onDoctype(r);i=t+(s?2:1)}}break;default:const s=this._parseContent(e,i);if(null===s){this.onError(Ss);return}let r=!1;if("/>"===e.substring(i+s.parsed,i+s.parsed+2))r=!0;else if(">"!==e.substring(i+s.parsed,i+s.parsed+1)){this.onError(ks);return}this.onBeginElement(s.name,s.attributes,r);i+=s.parsed+(r?2:1)}}else{for(;i0}searchNode(e,t){if(t>=e.length)return this;const i=e[t];if(i.name.startsWith("#")&&t0){a.push([s,0]);s=s.childNodes[0]}else{if(0===a.length)return null;for(;0!==a.length;){const[e,t]=a.pop(),i=t+1;if(i");for(const t of this.childNodes)t.dump(e);e.push(``)}else this.nodeValue?e.push(`>${encodeToXmlString(this.nodeValue)}`):e.push("/>")}else e.push(encodeToXmlString(this.nodeValue))}}class SimpleXMLParser extends XMLParserBase{constructor({hasAttributes:e=!1,lowerCaseName:t=!1}){super();this._currentFragment=null;this._stack=null;this._errorCode=ys;this._hasAttributes=e;this._lowerCaseName=t}parseFromString(e){this._currentFragment=[];this._stack=[];this._errorCode=ys;this.parseXml(e);if(this._errorCode!==ys)return;const[t]=this._currentFragment;return t?{documentElement:t}:void 0}onText(e){if(function isWhitespaceString(e){for(let t=0,i=e.length;t\\376\\377([^<]+)/g,(function(e,t){const i=t.replaceAll(/\\([0-3])([0-7])([0-7])/g,(function(e,t,i,a){return String.fromCharCode(64*t+8*i+1*a)})).replaceAll(/&(amp|apos|gt|lt|quot);/g,(function(e,t){switch(t){case"amp":return"&";case"apos":return"'";case"gt":return">";case"lt":return"<";case"quot":return'"'}throw new Error(`_repair: ${t} isn't defined.`)})),a=[">"];for(let e=0,t=i.length;e=32&&t<127&&60!==t&&62!==t&&38!==t?a.push(String.fromCharCode(t)):a.push("&#x"+(65536+t).toString(16).substring(1)+";")}return a.join("")}))}_getSequence(e){const t=e.nodeName;return"rdf:bag"!==t&&"rdf:seq"!==t&&"rdf:alt"!==t?null:e.childNodes.filter((e=>"rdf:li"===e.nodeName))}_parseArray(e){if(!e.hasChildNodes())return;const[t]=e.childNodes,i=this._getSequence(t)||[];this._metadataMap.set(e.nodeName,i.map((e=>e.textContent.trim())))}_parse(e){let t=e.documentElement;if("rdf:rdf"!==t.nodeName){t=t.firstChild;for(;t&&"rdf:rdf"!==t.nodeName;)t=t.nextSibling}if(t&&"rdf:rdf"===t.nodeName&&t.hasChildNodes())for(const e of t.childNodes)if("rdf:description"===e.nodeName)for(const t of e.childNodes){const e=t.nodeName;switch(e){case"#text":continue;case"dc:creator":case"dc:subject":this._parseArray(t);continue}this._metadataMap.set(e,t.textContent.trim())}}get serializable(){return{parsedData:this._metadataMap,rawData:this._data}}}const Rs=1,Ns=2,Gs=3,Ms=4,Us=5;class StructTreeRoot{constructor(e,t){this.dict=e;this.ref=t instanceof Ref?t:null;this.roleMap=new Map;this.structParentIds=null}init(){this.readRoleMap()}#x(e,t,i){if(!(e instanceof Ref)||t<0)return;this.structParentIds||=new RefSetCache;let a=this.structParentIds.get(e);if(!a){a=[];this.structParentIds.put(e,a)}a.push([t,i])}addAnnotationIdToPage(e,t){this.#x(e,t,Ms)}readRoleMap(){const e=this.dict.get("RoleMap");if(e instanceof Dict)for(const[t,i]of e)i instanceof Name&&this.roleMap.set(t,i.name)}static async canCreateStructureTree({catalogRef:e,pdfManager:t,newAnnotationsByPage:i}){if(!(e instanceof Ref)){warn("Cannot save the struct tree: no catalog reference.");return!1}let a=0,s=!0;for(const[e,r]of i){const{ref:i}=await t.getPage(e);if(!(i instanceof Ref)){warn(`Cannot save the struct tree: page ${e} has no ref.`);s=!0;break}for(const e of r)if(e.accessibilityData?.type){e.parentTreeId=a++;s=!1}}if(s){for(const e of i.values())for(const t of e)delete t.parentTreeId;return!1}return!0}static async createStructureTree({newAnnotationsByPage:e,xref:t,catalogRef:i,pdfManager:a,changes:s}){const r=a.catalog.cloneDict(),n=new RefSetCache;n.put(i,r);const g=t.getNewTemporaryRef();r.set("StructTreeRoot",g);const o=new Dict(t);o.set("Type",Name.get("StructTreeRoot"));const c=t.getNewTemporaryRef();o.set("ParentTree",c);const C=[];o.set("K",C);n.put(g,o);const h=new Dict(t),l=[];h.set("Nums",l);const Q=await this.#L({newAnnotationsByPage:e,structTreeRootRef:g,structTreeRoot:null,kids:C,nums:l,xref:t,pdfManager:a,changes:s,cache:n});o.set("ParentTreeNextKey",Q);n.put(c,h);for(const[e,t]of n.items())s.put(e,{data:t})}async canUpdateStructTree({pdfManager:e,xref:t,newAnnotationsByPage:i}){if(!this.ref){warn("Cannot update the struct tree: no root reference.");return!1}let a=this.dict.get("ParentTreeNextKey");if(!Number.isInteger(a)||a<0){warn("Cannot update the struct tree: invalid next key.");return!1}const s=this.dict.get("ParentTree");if(!(s instanceof Dict)){warn("Cannot update the struct tree: ParentTree isn't a dict.");return!1}const r=s.get("Nums");if(!Array.isArray(r)){warn("Cannot update the struct tree: nums isn't an array.");return!1}const n=new NumberTree(s,t);for(const t of i.keys()){const{pageDict:i}=await e.getPage(t);if(!i.has("StructParents"))continue;const a=i.get("StructParents");if(!Number.isInteger(a)||!Array.isArray(n.get(a))){warn(`Cannot save the struct tree: page ${t} has a wrong id.`);return!1}}let g=!0;for(const[t,s]of i){const{pageDict:i}=await e.getPage(t);StructTreeRoot.#H({elements:s,xref:this.dict.xref,pageDict:i,numberTree:n});for(const e of s)if(e.accessibilityData?.type){e.accessibilityData.structParent>=0||(e.parentTreeId=a++);g=!1}}if(g){for(const e of i.values())for(const t of e){delete t.parentTreeId;delete t.structTreeParent}return!1}return!0}async updateStructureTree({newAnnotationsByPage:e,pdfManager:t,changes:i}){const a=this.dict.xref,s=this.dict.clone(),r=this.ref,n=new RefSetCache;n.put(r,s);let g,o=s.getRaw("ParentTree");if(o instanceof Ref)g=a.fetch(o);else{g=o;o=a.getNewTemporaryRef();s.set("ParentTree",o)}g=g.clone();n.put(o,g);let c=g.getRaw("Nums"),C=null;if(c instanceof Ref){C=c;c=a.fetch(C)}c=c.slice();C||g.set("Nums",c);const h=await StructTreeRoot.#L({newAnnotationsByPage:e,structTreeRootRef:r,structTreeRoot:this,kids:null,nums:c,xref:a,pdfManager:t,changes:i,cache:n});if(-1!==h){s.set("ParentTreeNextKey",h);C&&n.put(C,c);for(const[e,t]of n.items())i.put(e,{data:t})}}static async#L({newAnnotationsByPage:e,structTreeRootRef:t,structTreeRoot:i,kids:a,nums:s,xref:r,pdfManager:n,changes:g,cache:o}){const c=Name.get("OBJR");let C,h=-1;for(const[l,Q]of e){const e=await n.getPage(l),{ref:E}=e,u=E instanceof Ref;for(const{accessibilityData:n,ref:d,parentTreeId:f,structTreeParent:p}of Q){if(!n?.type)continue;const{structParent:Q}=n;if(i&&Number.isInteger(Q)&&Q>=0){let t=(C||=new Map).get(l);if(void 0===t){t=new StructTreePage(i,e.pageDict).collectObjects(E);C.set(l,t)}const a=t?.get(Q);if(a){const e=r.fetch(a).clone();StructTreeRoot.#J(e,n);g.put(a,{data:e});continue}}h=Math.max(h,f);const m=r.getNewTemporaryRef(),y=new Dict(r);StructTreeRoot.#J(y,n);await this.#Y({structTreeParent:p,tagDict:y,newTagRef:m,structTreeRootRef:t,fallbackKids:a,xref:r,cache:o});const w=new Dict(r);y.set("K",w);w.set("Type",c);u&&w.set("Pg",E);w.set("Obj",d);o.put(m,y);s.push(f,m)}}return h+1}static#J(e,{type:t,title:i,lang:a,alt:s,expanded:r,actualText:n}){e.set("S",Name.get(t));i&&e.set("T",stringToAsciiOrUTF16BE(i));a&&e.set("Lang",stringToAsciiOrUTF16BE(a));s&&e.set("Alt",stringToAsciiOrUTF16BE(s));r&&e.set("E",stringToAsciiOrUTF16BE(r));n&&e.set("ActualText",stringToAsciiOrUTF16BE(n))}static#H({elements:e,xref:t,pageDict:i,numberTree:a}){const s=new Map;for(const t of e)if(t.structTreeParentId){const e=parseInt(t.structTreeParentId.split("_mc")[1],10);let i=s.get(e);if(!i){i=[];s.set(e,i)}i.push(t)}const r=i.get("StructParents");if(!Number.isInteger(r))return;const n=a.get(r),updateElement=(e,i,a)=>{const r=s.get(e);if(r){const e=i.getRaw("P"),s=t.fetchIfRef(e);if(e instanceof Ref&&s instanceof Dict){const e={ref:a,dict:i};for(const t of r)t.structTreeParent=e}return!0}return!1};for(const e of n){if(!(e instanceof Ref))continue;const i=t.fetch(e),a=i.get("K");if(Number.isInteger(a))updateElement(a,i,e);else if(Array.isArray(a))for(let s of a){s=t.fetchIfRef(s);if(Number.isInteger(s)&&updateElement(s,i,e))break;if(!(s instanceof Dict))continue;if(!isName(s.get("Type"),"MCR"))break;const a=s.get("MCID");if(Number.isInteger(a)&&updateElement(a,i,e))break}}}static async#Y({structTreeParent:e,tagDict:t,newTagRef:i,structTreeRootRef:a,fallbackKids:s,xref:r,cache:n}){let g,o=null;if(e){({ref:o}=e);g=e.dict.getRaw("P")||a}else g=a;t.set("P",g);const c=r.fetchIfRef(g);if(!c){s.push(i);return}let C=n.get(g);if(!C){C=c.clone();n.put(g,C)}const h=C.getRaw("K");let l=h instanceof Ref?n.get(h):null;if(!l){l=r.fetchIfRef(h);l=Array.isArray(l)?l.slice():[h];const e=r.getNewTemporaryRef();C.set("K",e);n.put(e,l)}const Q=l.indexOf(o);l.splice(Q>=0?Q+1:l.length,0,i)}}class StructElementNode{constructor(e,t){this.tree=e;this.dict=t;this.kids=[];this.parseKids()}get role(){const e=this.dict.get("S"),t=e instanceof Name?e.name:"",{root:i}=this.tree;return i.roleMap.has(t)?i.roleMap.get(t):t}parseKids(){let e=null;const t=this.dict.getRaw("Pg");t instanceof Ref&&(e=t.toString());const i=this.dict.get("K");if(Array.isArray(i))for(const t of i){const i=this.parseKid(e,t);i&&this.kids.push(i)}else{const t=this.parseKid(e,i);t&&this.kids.push(t)}}parseKid(e,t){if(Number.isInteger(t))return this.tree.pageDict.objId!==e?null:new StructElement({type:Rs,mcid:t,pageObjId:e});let i=null;t instanceof Ref?i=this.dict.xref.fetch(t):t instanceof Dict&&(i=t);if(!i)return null;const a=i.getRaw("Pg");a instanceof Ref&&(e=a.toString());const s=i.get("Type")instanceof Name?i.get("Type").name:null;if("MCR"===s){if(this.tree.pageDict.objId!==e)return null;const t=i.getRaw("Stm");return new StructElement({type:Ns,refObjId:t instanceof Ref?t.toString():null,pageObjId:e,mcid:i.get("MCID")})}if("OBJR"===s){if(this.tree.pageDict.objId!==e)return null;const t=i.getRaw("Obj");return new StructElement({type:Gs,refObjId:t instanceof Ref?t.toString():null,pageObjId:e})}return new StructElement({type:Us,dict:i})}}class StructElement{constructor({type:e,dict:t=null,mcid:i=null,pageObjId:a=null,refObjId:s=null}){this.type=e;this.dict=t;this.mcid=i;this.pageObjId=a;this.refObjId=s;this.parentNode=null}}class StructTreePage{constructor(e,t){this.root=e;this.rootDict=e?e.dict:null;this.pageDict=t;this.nodes=[]}collectObjects(e){if(!(this.root&&this.rootDict&&e instanceof Ref))return null;const t=this.rootDict.get("ParentTree");if(!t)return null;const i=this.root.structParentIds?.get(e);if(!i)return null;const a=new Map,s=new NumberTree(t,this.rootDict.xref);for(const[e]of i){const t=s.getRaw(e);t instanceof Ref&&a.set(e,t)}return a}parse(e){if(!(this.root&&this.rootDict&&e instanceof Ref))return;const t=this.rootDict.get("ParentTree");if(!t)return;const i=this.pageDict.get("StructParents"),a=this.root.structParentIds?.get(e);if(!Number.isInteger(i)&&!a)return;const s=new Map,r=new NumberTree(t,this.rootDict.xref);if(Number.isInteger(i)){const e=r.get(i);if(Array.isArray(e))for(const t of e)t instanceof Ref&&this.addNode(this.rootDict.xref.fetch(t),s)}if(a)for(const[e,t]of a){const i=r.get(e);if(i){const e=this.addNode(this.rootDict.xref.fetchIfRef(i),s);1===e?.kids?.length&&e.kids[0].type===Gs&&(e.kids[0].type=t)}}}addNode(e,t,i=0){if(i>40){warn("StructTree MAX_DEPTH reached.");return null}if(!(e instanceof Dict))return null;if(t.has(e))return t.get(e);const a=new StructElementNode(this,e);t.set(e,a);const s=e.get("P");if(!s||isName(s.get("Type"),"StructTreeRoot")){this.addTopLevelNode(e,a)||t.delete(e);return a}const r=this.addNode(s,t,i+1);if(!r)return a;let n=!1;for(const t of r.kids)if(t.type===Us&&t.dict===e){t.parentNode=a;n=!0}n||t.delete(e);return a}addTopLevelNode(e,t){const i=this.rootDict.get("K");if(!i)return!1;if(i instanceof Dict){if(i.objId!==e.objId)return!1;this.nodes[0]=t;return!0}if(!Array.isArray(i))return!0;let a=!1;for(let s=0;s40){warn("StructTree too deep to be fully serialized.");return}const a=Object.create(null);a.role=e.role;a.children=[];t.children.push(a);let s=e.dict.get("Alt");"string"!=typeof s&&(s=e.dict.get("ActualText"));"string"==typeof s&&(a.alt=stringToPDFString(s));const r=e.dict.get("A");if(r instanceof Dict){const e=lookupNormalRect(r.getArray("BBox"),null);if(e)a.bbox=e;else{const e=r.get("Width"),t=r.get("Height");"number"==typeof e&&e>0&&"number"==typeof t&&t>0&&(a.bbox=[0,0,e,t])}}const n=e.dict.get("Lang");"string"==typeof n&&(a.lang=stringToPDFString(n));for(const t of e.kids){const e=t.type===Us?t.parentNode:null;e?nodeToSerializable(e,a,i+1):t.type===Rs||t.type===Ns?a.children.push({type:"content",id:`p${t.pageObjId}_mc${t.mcid}`}):t.type===Gs?a.children.push({type:"object",id:t.refObjId}):t.type===Ms&&a.children.push({type:"annotation",id:`pdfjs_internal_id_${t.refObjId}`})}}const e=Object.create(null);e.children=[];e.role="Root";for(const t of this.nodes)t&&nodeToSerializable(t,e);return e}}function isValidExplicitDest(e){if(!Array.isArray(e)||e.length<2)return!1;const[t,i,...a]=e;if(!(t instanceof Ref||Number.isInteger(t)))return!1;if(!(i instanceof Name))return!1;const s=a.length;let r=!0;switch(i.name){case"XYZ":if(s<2||s>3)return!1;break;case"Fit":case"FitB":return 0===s;case"FitH":case"FitBH":case"FitV":case"FitBV":if(s>1)return!1;break;case"FitR":if(4!==s)return!1;r=!1;break;default:return!1}for(const e of a)if(!("number"==typeof e||r&&null===e))return!1;return!0}function fetchDest(e){e instanceof Dict&&(e=e.get("D"));return isValidExplicitDest(e)?e:null}function fetchRemoteDest(e){let t=e.get("D");if(t){t instanceof Name&&(t=t.name);if("string"==typeof t)return stringToPDFString(t);if(isValidExplicitDest(t))return JSON.stringify(t)}return null}class Catalog{constructor(e,t){this.pdfManager=e;this.xref=t;this._catDict=t.getCatalogObj();if(!(this._catDict instanceof Dict))throw new FormatError("Catalog object is not a dictionary.");this.toplevelPagesDict;this._actualNumPages=null;this.fontCache=new RefSetCache;this.builtInCMapCache=new Map;this.standardFontDataCache=new Map;this.globalImageCache=new GlobalImageCache;this.pageKidsCountCache=new RefSetCache;this.pageIndexCache=new RefSetCache;this.pageDictCache=new RefSetCache;this.nonBlendModesSet=new RefSet;this.systemFontCache=new Map}cloneDict(){return this._catDict.clone()}get version(){const e=this._catDict.get("Version");if(e instanceof Name){if(ft.test(e.name))return shadow(this,"version",e.name);warn(`Invalid PDF catalog version: ${e.name}`)}return shadow(this,"version",null)}get lang(){const e=this._catDict.get("Lang");return shadow(this,"lang",e&&"string"==typeof e?stringToPDFString(e):null)}get needsRendering(){const e=this._catDict.get("NeedsRendering");return shadow(this,"needsRendering","boolean"==typeof e&&e)}get collection(){let e=null;try{const t=this._catDict.get("Collection");t instanceof Dict&&t.size>0&&(e=t)}catch(e){if(e instanceof MissingDataException)throw e;info("Cannot fetch Collection entry; assuming no collection is present.")}return shadow(this,"collection",e)}get acroForm(){let e=null;try{const t=this._catDict.get("AcroForm");t instanceof Dict&&t.size>0&&(e=t)}catch(e){if(e instanceof MissingDataException)throw e;info("Cannot fetch AcroForm entry; assuming no forms are present.")}return shadow(this,"acroForm",e)}get acroFormRef(){const e=this._catDict.getRaw("AcroForm");return shadow(this,"acroFormRef",e instanceof Ref?e:null)}get metadata(){const e=this._catDict.getRaw("Metadata");if(!(e instanceof Ref))return shadow(this,"metadata",null);let t=null;try{const i=this.xref.fetch(e,!this.xref.encrypt?.encryptMetadata);if(i instanceof BaseStream&&i.dict instanceof Dict){const e=i.dict.get("Type"),a=i.dict.get("Subtype");if(isName(e,"Metadata")&&isName(a,"XML")){const e=stringToUTF8String(i.getString());e&&(t=new MetadataParser(e).serializable)}}}catch(e){if(e instanceof MissingDataException)throw e;info(`Skipping invalid Metadata: "${e}".`)}return shadow(this,"metadata",t)}get markInfo(){let e=null;try{e=this._readMarkInfo()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read mark info.")}return shadow(this,"markInfo",e)}_readMarkInfo(){const e=this._catDict.get("MarkInfo");if(!(e instanceof Dict))return null;const t={Marked:!1,UserProperties:!1,Suspects:!1};for(const i in t){const a=e.get(i);"boolean"==typeof a&&(t[i]=a)}return t}get structTreeRoot(){let e=null;try{e=this._readStructTreeRoot()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable read to structTreeRoot info.")}return shadow(this,"structTreeRoot",e)}_readStructTreeRoot(){const e=this._catDict.getRaw("StructTreeRoot"),t=this.xref.fetchIfRef(e);if(!(t instanceof Dict))return null;const i=new StructTreeRoot(t,e);i.init();return i}get toplevelPagesDict(){const e=this._catDict.get("Pages");if(!(e instanceof Dict))throw new FormatError("Invalid top-level pages dictionary.");return shadow(this,"toplevelPagesDict",e)}get documentOutline(){let e=null;try{e=this._readDocumentOutline()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read document outline.")}return shadow(this,"documentOutline",e)}_readDocumentOutline(){let e=this._catDict.get("Outlines");if(!(e instanceof Dict))return null;e=e.getRaw("First");if(!(e instanceof Ref))return null;const t={items:[]},i=[{obj:e,parent:t}],a=new RefSet;a.put(e);const s=this.xref,r=new Uint8ClampedArray(3);for(;i.length>0;){const t=i.shift(),n=s.fetchIfRef(t.obj);if(null===n)continue;n.has("Title")||warn("Invalid outline item encountered.");const g={url:null,dest:null,action:null};Catalog.parseDestDictionary({destDict:n,resultObj:g,docBaseUrl:this.baseUrl,docAttachments:this.attachments});const o=n.get("Title"),c=n.get("F")||0,C=n.getArray("C"),h=n.get("Count");let l=r;!isNumberArray(C,3)||0===C[0]&&0===C[1]&&0===C[2]||(l=ColorSpace.singletons.rgb.getRgb(C,0));const Q={action:g.action,attachment:g.attachment,dest:g.dest,url:g.url,unsafeUrl:g.unsafeUrl,newWindow:g.newWindow,setOCGState:g.setOCGState,title:"string"==typeof o?stringToPDFString(o):"",color:l,count:Number.isInteger(h)?h:void 0,bold:!!(2&c),italic:!!(1&c),items:[]};t.parent.items.push(Q);e=n.getRaw("First");if(e instanceof Ref&&!a.has(e)){i.push({obj:e,parent:Q});a.put(e)}e=n.getRaw("Next");if(e instanceof Ref&&!a.has(e)){i.push({obj:e,parent:t.parent});a.put(e)}}return t.items.length>0?t.items:null}get permissions(){let e=null;try{e=this._readPermissions()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read permissions.")}return shadow(this,"permissions",e)}_readPermissions(){const e=this.xref.trailer.get("Encrypt");if(!(e instanceof Dict))return null;let t=e.get("P");if("number"!=typeof t)return null;t+=2**32;const i=[];for(const e in y){const a=y[e];t&a&&i.push(a)}return i}get optionalContentConfig(){let e=null;try{const t=this._catDict.get("OCProperties");if(!t)return shadow(this,"optionalContentConfig",null);const i=t.get("D");if(!i)return shadow(this,"optionalContentConfig",null);const a=t.get("OCGs");if(!Array.isArray(a))return shadow(this,"optionalContentConfig",null);const s=new RefSetCache;for(const e of a)e instanceof Ref&&!s.has(e)&&s.put(e,this.#v(e));e=this.#K(i,s)}catch(e){if(e instanceof MissingDataException)throw e;warn(`Unable to read optional content config: ${e}`)}return shadow(this,"optionalContentConfig",e)}#v(e){const t=this.xref.fetch(e),i={id:e.toString(),name:null,intent:null,usage:{print:null,view:null},rbGroups:[]},a=t.get("Name");"string"==typeof a&&(i.name=stringToPDFString(a));let s=t.getArray("Intent");Array.isArray(s)||(s=[s]);s.every((e=>e instanceof Name))&&(i.intent=s.map((e=>e.name)));const r=t.get("Usage");if(!(r instanceof Dict))return i;const n=i.usage,g=r.get("Print");if(g instanceof Dict){const e=g.get("PrintState");if(e instanceof Name)switch(e.name){case"ON":case"OFF":n.print={printState:e.name}}}const o=r.get("View");if(o instanceof Dict){const e=o.get("ViewState");if(e instanceof Name)switch(e.name){case"ON":case"OFF":n.view={viewState:e.name}}}return i}#K(e,t){function parseOnOff(e){const i=[];if(Array.isArray(e))for(const a of e)a instanceof Ref&&t.has(a)&&i.push(a.toString());return i}function parseOrder(e,i=0){if(!Array.isArray(e))return null;const s=[];for(const r of e){if(r instanceof Ref&&t.has(r)){a.put(r);s.push(r.toString());continue}const e=parseNestedOrder(r,i);e&&s.push(e)}if(i>0)return s;const r=[];for(const[e]of t.items())a.has(e)||r.push(e.toString());r.length&&s.push({name:null,order:r});return s}function parseNestedOrder(e,t){if(++t>s){warn("parseNestedOrder - reached MAX_NESTED_LEVELS.");return null}const a=i.fetchIfRef(e);if(!Array.isArray(a))return null;const r=i.fetchIfRef(a[0]);if("string"!=typeof r)return null;const n=parseOrder(a.slice(1),t);return n?.length?{name:stringToPDFString(r),order:n}:null}const i=this.xref,a=new RefSet,s=10;!function parseRBGroups(e){if(Array.isArray(e))for(const a of e){const e=i.fetchIfRef(a);if(!Array.isArray(e)||!e.length)continue;const s=new Set;for(const i of e)if(i instanceof Ref&&t.has(i)&&!s.has(i.toString())){s.add(i.toString());t.get(i).rbGroups.push(s)}}}(e.get("RBGroups"));return{name:"string"==typeof e.get("Name")?stringToPDFString(e.get("Name")):null,creator:"string"==typeof e.get("Creator")?stringToPDFString(e.get("Creator")):null,baseState:e.get("BaseState")instanceof Name?e.get("BaseState").name:null,on:parseOnOff(e.get("ON")),off:parseOnOff(e.get("OFF")),order:parseOrder(e.get("Order")),groups:[...t]}}setActualNumPages(e=null){this._actualNumPages=e}get hasActualNumPages(){return null!==this._actualNumPages}get _pagesCount(){const e=this.toplevelPagesDict.get("Count");if(!Number.isInteger(e))throw new FormatError("Page count in top-level pages dictionary is not an integer.");return shadow(this,"_pagesCount",e)}get numPages(){return this.hasActualNumPages?this._actualNumPages:this._pagesCount}get destinations(){const e=this._readDests(),t=Object.create(null);if(e instanceof NameTree)for(const[i,a]of e.getAll()){const e=fetchDest(a);e&&(t[stringToPDFString(i)]=e)}else if(e instanceof Dict)for(const[i,a]of e){const e=fetchDest(a);e&&(t[i]=e)}return shadow(this,"destinations",t)}getDestination(e){const t=this._readDests();if(t instanceof NameTree){const i=fetchDest(t.get(e));if(i)return i;const a=this.destinations[e];if(a){warn(`Found "${e}" at an incorrect position in the NameTree.`);return a}}else if(t instanceof Dict){const i=fetchDest(t.get(e));if(i)return i}return null}_readDests(){const e=this._catDict.get("Names");return e?.has("Dests")?new NameTree(e.getRaw("Dests"),this.xref):this._catDict.has("Dests")?this._catDict.get("Dests"):void 0}get pageLabels(){let e=null;try{e=this._readPageLabels()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read page labels.")}return shadow(this,"pageLabels",e)}_readPageLabels(){const e=this._catDict.getRaw("PageLabels");if(!e)return null;const t=new Array(this.numPages);let i=null,a="";const s=new NumberTree(e,this.xref).getAll();let r="",n=1;for(let e=0,g=this.numPages;e=1))throw new FormatError("Invalid start in PageLabel dictionary.");n=e}else n=1}switch(i){case"D":r=n;break;case"R":case"r":r=toRomanNumerals(n,"r"===i);break;case"A":case"a":const e=26,t="a"===i?97:65,a=n-1;r=String.fromCharCode(t+a%e).repeat(Math.floor(a/e)+1);break;default:if(i)throw new FormatError(`Invalid style "${i}" in PageLabel dictionary.`);r=""}t[e]=a+r;n++}return t}get pageLayout(){const e=this._catDict.get("PageLayout");let t="";if(e instanceof Name)switch(e.name){case"SinglePage":case"OneColumn":case"TwoColumnLeft":case"TwoColumnRight":case"TwoPageLeft":case"TwoPageRight":t=e.name}return shadow(this,"pageLayout",t)}get pageMode(){const e=this._catDict.get("PageMode");let t="UseNone";if(e instanceof Name)switch(e.name){case"UseNone":case"UseOutlines":case"UseThumbs":case"FullScreen":case"UseOC":case"UseAttachments":t=e.name}return shadow(this,"pageMode",t)}get viewerPreferences(){const e=this._catDict.get("ViewerPreferences");if(!(e instanceof Dict))return shadow(this,"viewerPreferences",null);let t=null;for(const i of e.getKeys()){const a=e.get(i);let s;switch(i){case"HideToolbar":case"HideMenubar":case"HideWindowUI":case"FitWindow":case"CenterWindow":case"DisplayDocTitle":case"PickTrayByPDFSize":"boolean"==typeof a&&(s=a);break;case"NonFullScreenPageMode":if(a instanceof Name)switch(a.name){case"UseNone":case"UseOutlines":case"UseThumbs":case"UseOC":s=a.name;break;default:s="UseNone"}break;case"Direction":if(a instanceof Name)switch(a.name){case"L2R":case"R2L":s=a.name;break;default:s="L2R"}break;case"ViewArea":case"ViewClip":case"PrintArea":case"PrintClip":if(a instanceof Name)switch(a.name){case"MediaBox":case"CropBox":case"BleedBox":case"TrimBox":case"ArtBox":s=a.name;break;default:s="CropBox"}break;case"PrintScaling":if(a instanceof Name)switch(a.name){case"None":case"AppDefault":s=a.name;break;default:s="AppDefault"}break;case"Duplex":if(a instanceof Name)switch(a.name){case"Simplex":case"DuplexFlipShortEdge":case"DuplexFlipLongEdge":s=a.name;break;default:s="None"}break;case"PrintPageRange":if(Array.isArray(a)&&a.length%2==0){a.every(((e,t,i)=>Number.isInteger(e)&&e>0&&(0===t||e>=i[t-1])&&e<=this.numPages))&&(s=a)}break;case"NumCopies":Number.isInteger(a)&&a>0&&(s=a);break;default:warn(`Ignoring non-standard key in ViewerPreferences: ${i}.`);continue}if(void 0!==s){t||(t=Object.create(null));t[i]=s}else warn(`Bad value, for key "${i}", in ViewerPreferences: ${a}.`)}return shadow(this,"viewerPreferences",t)}get openAction(){const e=this._catDict.get("OpenAction"),t=Object.create(null);if(e instanceof Dict){const i=new Dict(this.xref);i.set("A",e);const a={url:null,dest:null,action:null};Catalog.parseDestDictionary({destDict:i,resultObj:a});Array.isArray(a.dest)?t.dest=a.dest:a.action&&(t.action=a.action)}else Array.isArray(e)&&(t.dest=e);return shadow(this,"openAction",objectSize(t)>0?t:null)}get attachments(){const e=this._catDict.get("Names");let t=null;if(e instanceof Dict&&e.has("EmbeddedFiles")){const i=new NameTree(e.getRaw("EmbeddedFiles"),this.xref);for(const[e,a]of i.getAll()){const i=new FileSpec(a,this.xref);t||(t=Object.create(null));t[stringToPDFString(e)]=i.serializable}}return shadow(this,"attachments",t)}get xfaImages(){const e=this._catDict.get("Names");let t=null;if(e instanceof Dict&&e.has("XFAImages")){const i=new NameTree(e.getRaw("XFAImages"),this.xref);for(const[e,a]of i.getAll()){t||(t=new Dict(this.xref));t.set(stringToPDFString(e),a)}}return shadow(this,"xfaImages",t)}_collectJavaScript(){const e=this._catDict.get("Names");let t=null;function appendIfJavaScriptDict(e,i){if(!(i instanceof Dict))return;if(!isName(i.get("S"),"JavaScript"))return;let a=i.get("JS");if(a instanceof BaseStream)a=a.getString();else if("string"!=typeof a)return;a=stringToPDFString(a).replaceAll("\0","");a&&(t||=new Map).set(e,a)}if(e instanceof Dict&&e.has("JavaScript")){const t=new NameTree(e.getRaw("JavaScript"),this.xref);for(const[e,i]of t.getAll())appendIfJavaScriptDict(stringToPDFString(e),i)}const i=this._catDict.get("OpenAction");i&&appendIfJavaScriptDict("OpenAction",i);return t}get jsActions(){const e=this._collectJavaScript();let t=collectActions(this.xref,this._catDict,fA);if(e){t||=Object.create(null);for(const[i,a]of e)i in t?t[i].push(a):t[i]=[a]}return shadow(this,"jsActions",t)}async fontFallback(e,t){const i=await Promise.all(this.fontCache);for(const a of i)if(a.loadedName===e){a.fallback(t);return}}async cleanup(e=!1){clearGlobalCaches();this.globalImageCache.clear(e);this.pageKidsCountCache.clear();this.pageIndexCache.clear();this.pageDictCache.clear();this.nonBlendModesSet.clear();const t=await Promise.all(this.fontCache);for(const{dict:e}of t)delete e.cacheKey;this.fontCache.clear();this.builtInCMapCache.clear();this.standardFontDataCache.clear();this.systemFontCache.clear()}async getPageDict(e){const t=[this.toplevelPagesDict],i=new RefSet,a=this._catDict.getRaw("Pages");a instanceof Ref&&i.put(a);const s=this.xref,r=this.pageKidsCountCache,n=this.pageIndexCache,g=this.pageDictCache;let o=0;for(;t.length;){const a=t.pop();if(a instanceof Ref){const c=r.get(a);if(c>=0&&o+c<=e){o+=c;continue}if(i.has(a))throw new FormatError("Pages tree contains circular reference.");i.put(a);const C=await(g.get(a)||s.fetchAsync(a));if(C instanceof Dict){let t=C.getRaw("Type");t instanceof Ref&&(t=await s.fetchAsync(t));if(isName(t,"Page")||!C.has("Kids")){r.has(a)||r.put(a,1);n.has(a)||n.put(a,o);if(o===e)return[C,a];o++;continue}}t.push(C);continue}if(!(a instanceof Dict))throw new FormatError("Page dictionary kid reference points to wrong type of object.");const{objId:c}=a;let C=a.getRaw("Count");C instanceof Ref&&(C=await s.fetchAsync(C));if(Number.isInteger(C)&&C>=0){c&&!r.has(c)&&r.put(c,C);if(o+C<=e){o+=C;continue}}let h=a.getRaw("Kids");h instanceof Ref&&(h=await s.fetchAsync(h));if(!Array.isArray(h)){let t=a.getRaw("Type");t instanceof Ref&&(t=await s.fetchAsync(t));if(isName(t,"Page")||!a.has("Kids")){if(o===e)return[a,null];o++;continue}throw new FormatError("Page dictionary kids object is not an array.")}for(let e=h.length-1;e>=0;e--){const i=h[e];t.push(i);a===this.toplevelPagesDict&&i instanceof Ref&&!g.has(i)&&g.put(i,s.fetchAsync(i))}}throw new Error(`Page index ${e} not found.`)}async getAllPageDicts(e=!1){const{ignoreErrors:t}=this.pdfManager.evaluatorOptions,i=[{currentNode:this.toplevelPagesDict,posInKids:0}],a=new RefSet,s=this._catDict.getRaw("Pages");s instanceof Ref&&a.put(s);const r=new Map,n=this.xref,g=this.pageIndexCache;let o=0;function addPageDict(e,t){t&&!g.has(t)&&g.put(t,o);r.set(o++,[e,t])}function addPageError(i){if(i instanceof XRefEntryException&&!e)throw i;if(e&&t&&0===o){warn(`getAllPageDicts - Skipping invalid first page: "${i}".`);i=Dict.empty}r.set(o++,[i,null])}for(;i.length>0;){const e=i.at(-1),{currentNode:t,posInKids:s}=e;let r=t.getRaw("Kids");if(r instanceof Ref)try{r=await n.fetchAsync(r)}catch(e){addPageError(e);break}if(!Array.isArray(r)){addPageError(new FormatError("Page dictionary kids object is not an array."));break}if(s>=r.length){i.pop();continue}const g=r[s];let o;if(g instanceof Ref){if(a.has(g)){addPageError(new FormatError("Pages tree contains circular reference."));break}a.put(g);try{o=await n.fetchAsync(g)}catch(e){addPageError(e);break}}else o=g;if(!(o instanceof Dict)){addPageError(new FormatError("Page dictionary kid reference points to wrong type of object."));break}let c=o.getRaw("Type");if(c instanceof Ref)try{c=await n.fetchAsync(c)}catch(e){addPageError(e);break}isName(c,"Page")||!o.has("Kids")?addPageDict(o,g instanceof Ref?g:null):i.push({currentNode:o,posInKids:0});e.posInKids++}return r}getPageIndex(e){const t=this.pageIndexCache.get(e);if(void 0!==t)return Promise.resolve(t);const i=this.xref;let a=0;const next=t=>function pagesBeforeRef(t){let a,s=0;return i.fetchAsync(t).then((function(i){if(isRefsEqual(t,e)&&!isDict(i,"Page")&&!(i instanceof Dict&&!i.has("Type")&&i.has("Contents")))throw new FormatError("The reference does not point to a /Page dictionary.");if(!i)return null;if(!(i instanceof Dict))throw new FormatError("Node must be a dictionary.");a=i.getRaw("Parent");return i.getAsync("Parent")})).then((function(e){if(!e)return null;if(!(e instanceof Dict))throw new FormatError("Parent must be a dictionary.");return e.getAsync("Kids")})).then((function(e){if(!e)return null;const r=[];let n=!1;for(const a of e){if(!(a instanceof Ref))throw new FormatError("Kid must be a reference.");if(isRefsEqual(a,t)){n=!0;break}r.push(i.fetchAsync(a).then((function(e){if(!(e instanceof Dict))throw new FormatError("Kid node must be a dictionary.");e.has("Count")?s+=e.get("Count"):s++})))}if(!n)throw new FormatError("Kid reference not found in parent's kids.");return Promise.all(r).then((function(){return[s,a]}))}))}(t).then((t=>{if(!t){this.pageIndexCache.put(e,a);return a}const[i,s]=t;a+=i;return next(s)}));return next(e)}get baseUrl(){const e=this._catDict.get("URI");if(e instanceof Dict){const t=e.get("Base");if("string"==typeof t){const e=createValidAbsoluteUrl(t,null,{tryConvertEncoding:!0});if(e)return shadow(this,"baseUrl",e.href)}}return shadow(this,"baseUrl",this.pdfManager.docBaseUrl)}static parseDestDictionary({destDict:e,resultObj:t,docBaseUrl:i=null,docAttachments:a=null}){if(!(e instanceof Dict)){warn("parseDestDictionary: `destDict` must be a dictionary.");return}let s,r,n=e.get("A");if(!(n instanceof Dict))if(e.has("Dest"))n=e.get("Dest");else{n=e.get("AA");n instanceof Dict&&(n.has("D")?n=n.get("D"):n.has("U")&&(n=n.get("U")))}if(n instanceof Dict){const e=n.get("S");if(!(e instanceof Name)){warn("parseDestDictionary: Invalid type in Action dictionary.");return}const i=e.name;switch(i){case"ResetForm":const e=n.get("Flags"),g=!(1&("number"==typeof e?e:0)),o=[],c=[];for(const e of n.get("Fields")||[])e instanceof Ref?c.push(e.toString()):"string"==typeof e&&o.push(stringToPDFString(e));t.resetForm={fields:o,refs:c,include:g};break;case"URI":s=n.get("URI");s instanceof Name&&(s="/"+s.name);break;case"GoTo":r=n.get("D");break;case"Launch":case"GoToR":const C=n.get("F");if(C instanceof Dict){const e=new FileSpec(C,null,!0),{rawFilename:t}=e.serializable;s=t}else"string"==typeof C&&(s=C);const h=fetchRemoteDest(n);h&&"string"==typeof s&&(s=s.split("#",1)[0]+"#"+h);const l=n.get("NewWindow");"boolean"==typeof l&&(t.newWindow=l);break;case"GoToE":const Q=n.get("T");let E;if(a&&Q instanceof Dict){const e=Q.get("R"),t=Q.get("N");isName(e,"C")&&"string"==typeof t&&(E=a[stringToPDFString(t)])}if(E){t.attachment=E;const e=fetchRemoteDest(n);e&&(t.attachmentDest=e)}else warn('parseDestDictionary - unimplemented "GoToE" action.');break;case"Named":const u=n.get("N");u instanceof Name&&(t.action=u.name);break;case"SetOCGState":const d=n.get("State"),f=n.get("PreserveRB");if(!Array.isArray(d)||0===d.length)break;const p=[];for(const e of d)if(e instanceof Name)switch(e.name){case"ON":case"OFF":case"Toggle":p.push(e.name)}else e instanceof Ref&&p.push(e.toString());if(p.length!==d.length)break;t.setOCGState={state:p,preserveRB:"boolean"!=typeof f||f};break;case"JavaScript":const m=n.get("JS");let y;m instanceof BaseStream?y=m.getString():"string"==typeof m&&(y=m);const w=y&&recoverJsURL(stringToPDFString(y));if(w){s=w.url;t.newWindow=w.newWindow;break}default:if("JavaScript"===i||"SubmitForm"===i)break;warn(`parseDestDictionary - unsupported action: "${i}".`)}}else e.has("Dest")&&(r=e.get("Dest"));if("string"==typeof s){const e=createValidAbsoluteUrl(s,i,{addDefaultProtocol:!0,tryConvertEncoding:!0});e&&(t.url=e.href);t.unsafeUrl=s}if(r){r instanceof Name&&(r=r.name);"string"==typeof r?t.dest=stringToPDFString(r):isValidExplicitDest(r)&&(t.dest=r)}}}function addChildren(e,t){if(e instanceof Dict)e=e.getRawValues();else if(e instanceof BaseStream)e=e.dict.getRawValues();else if(!Array.isArray(e))return;for(const a of e)((i=a)instanceof Ref||i instanceof Dict||i instanceof BaseStream||Array.isArray(i))&&t.push(a);var i}class ObjectLoader{constructor(e,t,i){this.dict=e;this.keys=t;this.xref=i;this.refSet=null}async load(){if(this.xref.stream.isDataLoaded)return;const{keys:e,dict:t}=this;this.refSet=new RefSet;const i=[];for(const a of e){const e=t.getRaw(a);void 0!==e&&i.push(e)}return this._walk(i)}async _walk(e){const t=[],i=[];for(;e.length;){let a=e.pop();if(a instanceof Ref){if(this.refSet.has(a))continue;try{this.refSet.put(a);a=this.xref.fetch(a)}catch(e){if(!(e instanceof MissingDataException)){warn(`ObjectLoader._walk - requesting all data: "${e}".`);this.refSet=null;const{manager:t}=this.xref.stream;return t.requestAllChunks()}t.push(a);i.push({begin:e.begin,end:e.end})}}if(a instanceof BaseStream){const e=a.getBaseStreams();if(e){let s=!1;for(const t of e)if(!t.isDataLoaded){s=!0;i.push({begin:t.start,end:t.end})}s&&t.push(a)}}addChildren(a,e)}if(i.length){await this.xref.stream.manager.requestRanges(i);for(const e of t)e instanceof Ref&&this.refSet.remove(e);return this._walk(t)}this.refSet=null}}const xs=Symbol(),Ls=Symbol(),Hs=Symbol(),Js=Symbol(),Ys=Symbol(),vs=Symbol(),Ks=Symbol(),Ts=Symbol(),qs=Symbol(),Os=Symbol("content"),Ws=Symbol("data"),js=Symbol(),Xs=Symbol("extra"),Zs=Symbol(),Vs=Symbol(),zs=Symbol(),_s=Symbol(),$s=Symbol(),Ar=Symbol(),er=Symbol(),tr=Symbol(),ir=Symbol(),ar=Symbol(),sr=Symbol(),rr=Symbol(),nr=Symbol(),gr=Symbol(),or=Symbol(),Ir=Symbol(),cr=Symbol(),Cr=Symbol(),hr=Symbol(),lr=Symbol(),Qr=Symbol(),Er=Symbol(),ur=Symbol(),dr=Symbol(),fr=Symbol(),pr=Symbol(),mr=Symbol(),yr=Symbol(),wr=Symbol(),Dr=Symbol(),br=Symbol(),Fr=Symbol(),Sr=Symbol("namespaceId"),kr=Symbol("nodeName"),Rr=Symbol(),Nr=Symbol(),Gr=Symbol(),Mr=Symbol(),Ur=Symbol(),xr=Symbol(),Lr=Symbol(),Hr=Symbol(),Jr=Symbol("root"),Yr=Symbol(),vr=Symbol(),Kr=Symbol(),Tr=Symbol(),qr=Symbol(),Or=Symbol(),Pr=Symbol(),Wr=Symbol(),jr=Symbol(),Xr=Symbol(),Zr=Symbol(),Vr=Symbol("uid"),zr=Symbol(),_r={config:{id:0,check:e=>e.startsWith("http://www.xfa.org/schema/xci/")},connectionSet:{id:1,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-connection-set/")},datasets:{id:2,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-data/")},form:{id:3,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-form/")},localeSet:{id:4,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-locale-set/")},pdf:{id:5,check:e=>"http://ns.adobe.com/xdp/pdf/"===e},signature:{id:6,check:e=>"http://www.w3.org/2000/09/xmldsig#"===e},sourceSet:{id:7,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-source-set/")},stylesheet:{id:8,check:e=>"http://www.w3.org/1999/XSL/Transform"===e},template:{id:9,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-template/")},xdc:{id:10,check:e=>e.startsWith("http://www.xfa.org/schema/xdc/")},xdp:{id:11,check:e=>"http://ns.adobe.com/xdp/"===e},xfdf:{id:12,check:e=>"http://ns.adobe.com/xfdf/"===e},xhtml:{id:13,check:e=>"http://www.w3.org/1999/xhtml"===e},xmpmeta:{id:14,check:e=>"http://ns.adobe.com/xmpmeta/"===e}},$r={pt:e=>e,cm:e=>e/2.54*72,mm:e=>e/25.4*72,in:e=>72*e,px:e=>e},An=/([+-]?\d+\.?\d*)(.*)/;function stripQuotes(e){return e.startsWith("'")||e.startsWith('"')?e.slice(1,-1):e}function getInteger({data:e,defaultValue:t,validate:i}){if(!e)return t;e=e.trim();const a=parseInt(e,10);return!isNaN(a)&&i(a)?a:t}function getFloat({data:e,defaultValue:t,validate:i}){if(!e)return t;e=e.trim();const a=parseFloat(e);return!isNaN(a)&&i(a)?a:t}function getKeyword({data:e,defaultValue:t,validate:i}){return e&&i(e=e.trim())?e:t}function getStringOption(e,t){return getKeyword({data:e,defaultValue:t[0],validate:e=>t.includes(e)})}function getMeasurement(e,t="0"){t||="0";if(!e)return getMeasurement(t);const i=e.trim().match(An);if(!i)return getMeasurement(t);const[,a,s]=i,r=parseFloat(a);if(isNaN(r))return getMeasurement(t);if(0===r)return 0;const n=$r[s];return n?n(r):r}function getRatio(e){if(!e)return{num:1,den:1};const t=e.trim().split(/\s*:\s*/).map((e=>parseFloat(e))).filter((e=>!isNaN(e)));1===t.length&&t.push(1);if(0===t.length)return{num:1,den:1};const[i,a]=t;return{num:i,den:a}}function getRelevant(e){return e?e.trim().split(/\s+/).map((e=>({excluded:"-"===e[0],viewname:e.substring(1)}))):[]}class HTMLResult{static get FAILURE(){return shadow(this,"FAILURE",new HTMLResult(!1,null,null,null))}static get EMPTY(){return shadow(this,"EMPTY",new HTMLResult(!0,null,null,null))}constructor(e,t,i,a){this.success=e;this.html=t;this.bbox=i;this.breakNode=a}isBreak(){return!!this.breakNode}static breakNode(e){return new HTMLResult(!1,null,null,e)}static success(e,t=null){return new HTMLResult(!0,e,t,null)}}class FontFinder{constructor(e){this.fonts=new Map;this.cache=new Map;this.warned=new Set;this.defaultFont=null;this.add(e)}add(e,t=null){for(const t of e)this.addPdfFont(t);for(const e of this.fonts.values())e.regular||(e.regular=e.italic||e.bold||e.bolditalic);if(!t||0===t.size)return;const i=this.fonts.get("PdfJS-Fallback-PdfJS-XFA");for(const e of t)this.fonts.set(e,i)}addPdfFont(e){const t=e.cssFontInfo,i=t.fontFamily;let a=this.fonts.get(i);if(!a){a=Object.create(null);this.fonts.set(i,a);this.defaultFont||(this.defaultFont=a)}let s="";const r=parseFloat(t.fontWeight);0!==parseFloat(t.italicAngle)?s=r>=700?"bolditalic":"italic":r>=700&&(s="bold");if(!s){(e.name.includes("Bold")||e.psName?.includes("Bold"))&&(s="bold");(e.name.includes("Italic")||e.name.endsWith("It")||e.psName?.includes("Italic")||e.psName?.endsWith("It"))&&(s+="italic")}s||(s="regular");a[s]=e}getDefault(){return this.defaultFont}find(e,t=!0){let i=this.fonts.get(e)||this.cache.get(e);if(i)return i;const a=/,|-|_| |bolditalic|bold|italic|regular|it/gi;let s=e.replaceAll(a,"");i=this.fonts.get(s);if(i){this.cache.set(e,i);return i}s=s.toLowerCase();const r=[];for(const[e,t]of this.fonts.entries())e.replaceAll(a,"").toLowerCase().startsWith(s)&&r.push(t);if(0===r.length)for(const[,e]of this.fonts.entries())e.regular.name?.replaceAll(a,"").toLowerCase().startsWith(s)&&r.push(e);if(0===r.length){s=s.replaceAll(/psmt|mt/gi,"");for(const[e,t]of this.fonts.entries())e.replaceAll(a,"").toLowerCase().startsWith(s)&&r.push(t)}if(0===r.length)for(const e of this.fonts.values())e.regular.name?.replaceAll(a,"").toLowerCase().startsWith(s)&&r.push(e);if(r.length>=1){1!==r.length&&t&&warn(`XFA - Too many choices to guess the correct font: ${e}`);this.cache.set(e,r[0]);return r[0]}if(t&&!this.warned.has(e)){this.warned.add(e);warn(`XFA - Cannot find the font: ${e}`)}return null}}function selectFont(e,t){return"italic"===e.posture?"bold"===e.weight?t.bolditalic:t.italic:"bold"===e.weight?t.bold:t.regular}class FontInfo{constructor(e,t,i,a){this.lineHeight=i;this.paraMargin=t||{top:0,bottom:0,left:0,right:0};if(!e){[this.pdfFont,this.xfaFont]=this.defaultFont(a);return}this.xfaFont={typeface:e.typeface,posture:e.posture,weight:e.weight,size:e.size,letterSpacing:e.letterSpacing};const s=a.find(e.typeface);if(s){this.pdfFont=selectFont(e,s);this.pdfFont||([this.pdfFont,this.xfaFont]=this.defaultFont(a))}else[this.pdfFont,this.xfaFont]=this.defaultFont(a)}defaultFont(e){const t=e.find("Helvetica",!1)||e.find("Myriad Pro",!1)||e.find("Arial",!1)||e.getDefault();if(t?.regular){const e=t.regular;return[e,{typeface:e.cssFontInfo.fontFamily,posture:"normal",weight:"normal",size:10,letterSpacing:0}]}return[null,{typeface:"Courier",posture:"normal",weight:"normal",size:10,letterSpacing:0}]}}class FontSelector{constructor(e,t,i,a){this.fontFinder=a;this.stack=[new FontInfo(e,t,i,a)]}pushData(e,t,i){const a=this.stack.at(-1);for(const t of["typeface","posture","weight","size","letterSpacing"])e[t]||(e[t]=a.xfaFont[t]);for(const e of["top","bottom","left","right"])isNaN(t[e])&&(t[e]=a.paraMargin[e]);const s=new FontInfo(e,t,i||a.lineHeight,this.fontFinder);s.pdfFont||(s.pdfFont=a.pdfFont);this.stack.push(s)}popFont(){this.stack.pop()}topFont(){return this.stack.at(-1)}}class TextMeasure{constructor(e,t,i,a){this.glyphs=[];this.fontSelector=new FontSelector(e,t,i,a);this.extraHeight=0}pushData(e,t,i){this.fontSelector.pushData(e,t,i)}popFont(e){return this.fontSelector.popFont()}addPara(){const e=this.fontSelector.topFont();this.extraHeight+=e.paraMargin.top+e.paraMargin.bottom}addString(e){if(!e)return;const t=this.fontSelector.topFont(),i=t.xfaFont.size;if(t.pdfFont){const a=t.xfaFont.letterSpacing,s=t.pdfFont,r=s.lineHeight||1.2,n=t.lineHeight||Math.max(1.2,r)*i,g=r-(void 0===s.lineGap?.2:s.lineGap),o=Math.max(1,g)*i,c=i/1e3,C=s.defaultWidth||s.charsToGlyphs(" ")[0].width;for(const t of e.split(/[\u2029\n]/)){const e=s.encodeString(t).join(""),i=s.charsToGlyphs(e);for(const e of i){const t=e.width||C;this.glyphs.push([t*c+a,n,o,e.unicode,!1])}this.glyphs.push([0,0,0,"\n",!0])}this.glyphs.pop()}else{for(const t of e.split(/[\u2029\n]/)){for(const e of t.split(""))this.glyphs.push([i,1.2*i,i,e,!1]);this.glyphs.push([0,0,0,"\n",!0])}this.glyphs.pop()}}compute(e){let t=-1,i=0,a=0,s=0,r=0,n=0,g=!1,o=!0;for(let c=0,C=this.glyphs.length;ce){a=Math.max(a,r);r=0;s+=n;n=d;t=-1;i=0;g=!0;o=!1}else{n=Math.max(d,n);i=r;r+=C;t=c}else if(r+C>e){s+=n;n=d;if(-1!==t){c=t;a=Math.max(a,i);r=0;t=-1;i=0}else{a=Math.max(a,r);r=C}g=!0;o=!1}else{r+=C;n=Math.max(d,n)}}a=Math.max(a,r);s+=n+this.extraHeight;return{width:1.02*a,height:s,isBroken:g}}}const en=/^[^.[]+/,tn=/^[^\]]+/,an=0,sn=1,rn=2,nn=3,gn=4,on=new Map([["$data",(e,t)=>e.datasets?e.datasets.data:e],["$record",(e,t)=>(e.datasets?e.datasets.data:e)[rr]()[0]],["$template",(e,t)=>e.template],["$connectionSet",(e,t)=>e.connectionSet],["$form",(e,t)=>e.form],["$layout",(e,t)=>e.layout],["$host",(e,t)=>e.host],["$dataWindow",(e,t)=>e.dataWindow],["$event",(e,t)=>e.event],["!",(e,t)=>e.datasets],["$xfa",(e,t)=>e],["xfa",(e,t)=>e],["$",(e,t)=>t]]),In=new WeakMap;function parseExpression(e,t,i=!0){let a=e.match(en);if(!a)return null;let[s]=a;const r=[{name:s,cacheName:"."+s,index:0,js:null,formCalc:null,operator:an}];let n=s.length;for(;n0&&C.push(e)}if(0!==C.length||g||0!==o)e=isFinite(c)?C.filter((e=>ce[c])):C.flat();else{const i=t[Ir]();if(!(t=i))return null;o=-1;e=[t]}}return 0===e.length?null:e}function createDataNode(e,t,i){const a=parseExpression(i);if(!a)return null;if(a.some((e=>e.operator===sn)))return null;const s=on.get(a[0].name);let r=0;if(s){e=s(e,t);r=1}else e=t||e;for(let t=a.length;re[Pr]())).join("")}get[hn](){const e=Object.getPrototypeOf(this);if(!e._attributes){const t=e._attributes=new Set;for(const e of Object.getOwnPropertyNames(this)){if(null===this[e]||this[e]instanceof XFAObject||this[e]instanceof XFAObjectArray)break;t.add(e)}}return shadow(this,hn,e._attributes)}[pr](e){let t=this;for(;t;){if(t===e)return!0;t=t[Ir]()}return!1}[Ir](){return this[wn]}[or](){return this[Ir]()}[rr](e=null){return e?this[e]:this[ln]}[js](){const e=Object.create(null);this[Os]&&(e.$content=this[Os]);for(const t of Object.getOwnPropertyNames(this)){const i=this[t];null!==i&&(i instanceof XFAObject?e[t]=i[js]():i instanceof XFAObjectArray?i.isEmpty()||(e[t]=i.dump()):e[t]=i)}return e}[Zr](){return null}[jr](){return HTMLResult.EMPTY}*[nr](){for(const e of this[rr]())yield e}*[un](e,t){for(const i of this[nr]())if(!e||t===e.has(i[kr])){const e=this[$s](),t=i[jr](e);t.success||(this[Xs].failingNode=i);yield t}}[Vs](){return null}[Ls](e,t){this[Xs].children.push(e)}[$s](){}[Js]({filter:e=null,include:t=!0}){if(this[Xs].generator){const e=this[$s](),t=this[Xs].failingNode[jr](e);if(!t.success)return t;t.html&&this[Ls](t.html,t.bbox);delete this[Xs].failingNode}else this[Xs].generator=this[un](e,t);for(;;){const e=this[Xs].generator.next();if(e.done)break;const t=e.value;if(!t.success)return t;t.html&&this[Ls](t.html,t.bbox)}this[Xs].generator=null;return HTMLResult.EMPTY}[Tr](e){this[bn]=new Set(Object.keys(e))}[fn](e){const t=this[hn],i=this[bn];return[...e].filter((e=>t.has(e)&&!i.has(e)))}[Yr](e,t=new Set){for(const i of this[ln])i[Dn](e,t)}[Dn](e,t){const i=this[dn](e,t);i?this[cn](i,e,t):this[Yr](e,t)}[dn](e,t){const{use:i,usehref:a}=this;if(!i&&!a)return null;let s=null,r=null,n=null,g=i;if(a){g=a;a.startsWith("#som(")&&a.endsWith(")")?r=a.slice(5,-1):a.startsWith(".#som(")&&a.endsWith(")")?r=a.slice(6,-1):a.startsWith("#")?n=a.slice(1):a.startsWith(".#")&&(n=a.slice(2))}else i.startsWith("#")?n=i.slice(1):r=i;this.use=this.usehref="";if(n)s=e.get(n);else{s=searchNode(e.get(Jr),this,r,!0,!1);s&&(s=s[0])}if(!s){warn(`XFA - Invalid prototype reference: ${g}.`);return null}if(s[kr]!==this[kr]){warn(`XFA - Incompatible prototype: ${s[kr]} !== ${this[kr]}.`);return null}if(t.has(s)){warn("XFA - Cycle detected in prototypes use.");return null}t.add(s);const o=s[dn](e,t);o&&s[cn](o,e,t);s[Yr](e,t);t.delete(s);return s}[cn](e,t,i){if(i.has(e)){warn("XFA - Cycle detected in prototypes use.");return}!this[Os]&&e[Os]&&(this[Os]=e[Os]);new Set(i).add(e);for(const t of this[fn](e[bn])){this[t]=e[t];this[bn]&&this[bn].add(t)}for(const a of Object.getOwnPropertyNames(this)){if(this[hn].has(a))continue;const s=this[a],r=e[a];if(s instanceof XFAObjectArray){for(const e of s[ln])e[Dn](t,i);for(let a=s[ln].length,n=r[ln].length;aXFAObject[Bn](e))):"object"==typeof e&&null!==e?Object.assign({},e):e}[Ts](){const e=Object.create(Object.getPrototypeOf(this));for(const t of Object.getOwnPropertySymbols(this))try{e[t]=this[t]}catch{shadow(e,t,this[t])}e[Vr]=`${e[kr]}${Sn++}`;e[ln]=[];for(const t of Object.getOwnPropertyNames(this)){if(this[hn].has(t)){e[t]=XFAObject[Bn](this[t]);continue}const i=this[t];e[t]=i instanceof XFAObjectArray?new XFAObjectArray(i[mn]):null}for(const t of this[ln]){const i=t[kr],a=t[Ts]();e[ln].push(a);a[wn]=e;null===e[i]?e[i]=a:e[i][ln].push(a)}return e}[rr](e=null){return e?this[ln].filter((t=>t[kr]===e)):this[ln]}[Ar](e){return this[e]}[er](e,t,i=!0){return Array.from(this[tr](e,t,i))}*[tr](e,t,i=!0){if("parent"!==e){for(const i of this[ln]){i[kr]===e&&(yield i);i.name===e&&(yield i);(t||i[Dr]())&&(yield*i[tr](e,t,!1))}i&&this[hn].has(e)&&(yield new XFAAttribute(this,e,this[e]))}else yield this[wn]}}class XFAObjectArray{constructor(e=1/0){this[mn]=e;this[ln]=[]}get isXFAObject(){return!1}get isXFAObjectArray(){return!0}push(e){if(this[ln].length<=this[mn]){this[ln].push(e);return!0}warn(`XFA - node "${e[kr]}" accepts no more than ${this[mn]} children`);return!1}isEmpty(){return 0===this[ln].length}dump(){return 1===this[ln].length?this[ln][0][js]():this[ln].map((e=>e[js]()))}[Ts](){const e=new XFAObjectArray(this[mn]);e[ln]=this[ln].map((e=>e[Ts]()));return e}get children(){return this[ln]}clear(){this[ln].length=0}}class XFAAttribute{constructor(e,t,i){this[wn]=e;this[kr]=t;this[Os]=i;this[qs]=!1;this[Vr]="attribute"+Sn++}[Ir](){return this[wn]}[fr](){return!0}[ir](){return this[Os].trim()}[qr](e){e=e.value||"";this[Os]=e.toString()}[Pr](){return this[Os]}[pr](e){return this[wn]===e||this[wn][pr](e)}}class XmlObject extends XFAObject{constructor(e,t,i={}){super(e,t);this[Os]="";this[Qn]=null;if("#text"!==t){const e=new Map;this[Cn]=e;for(const[t,a]of Object.entries(i))e.set(t,new XFAAttribute(this,t,a));if(i.hasOwnProperty(Rr)){const e=i[Rr].xfa.dataNode;void 0!==e&&("dataGroup"===e?this[Qn]=!1:"dataValue"===e&&(this[Qn]=!0))}}this[qs]=!1}[Xr](e){const t=this[kr];if("#text"===t){e.push(encodeToXmlString(this[Os]));return}const i=utf8StringToString(t),a=this[Sr]===kn?"xfa:":"";e.push(`<${a}${i}`);for(const[t,i]of this[Cn].entries()){const a=utf8StringToString(t);e.push(` ${a}="${encodeToXmlString(i[Os])}"`)}null!==this[Qn]&&(this[Qn]?e.push(' xfa:dataNode="dataValue"'):e.push(' xfa:dataNode="dataGroup"'));if(this[Os]||0!==this[ln].length){e.push(">");if(this[Os])"string"==typeof this[Os]?e.push(encodeToXmlString(this[Os])):this[Os][Xr](e);else for(const t of this[ln])t[Xr](e);e.push(``)}else e.push("/>")}[Nr](e){if(this[Os]){const e=new XmlObject(this[Sr],"#text");this[Hs](e);e[Os]=this[Os];this[Os]=""}this[Hs](e);return!0}[Mr](e){this[Os]+=e}[Zs](){if(this[Os]&&this[ln].length>0){const e=new XmlObject(this[Sr],"#text");this[Hs](e);e[Os]=this[Os];delete this[Os]}}[jr](){return"#text"===this[kr]?HTMLResult.success({name:"#text",value:this[Os]}):HTMLResult.EMPTY}[rr](e=null){return e?this[ln].filter((t=>t[kr]===e)):this[ln]}[_s](){return this[Cn]}[Ar](e){const t=this[Cn].get(e);return void 0!==t?t:this[rr](e)}*[tr](e,t){const i=this[Cn].get(e);i&&(yield i);for(const i of this[ln]){i[kr]===e&&(yield i);t&&(yield*i[tr](e,t))}}*[zs](e,t){const i=this[Cn].get(e);!i||t&&i[qs]||(yield i);for(const i of this[ln])yield*i[zs](e,t)}*[sr](e,t,i){for(const a of this[ln]){a[kr]!==e||i&&a[qs]||(yield a);t&&(yield*a[sr](e,t,i))}}[fr](){return null===this[Qn]?0===this[ln].length||this[ln][0][Sr]===_r.xhtml.id:this[Qn]}[ir](){return null===this[Qn]?0===this[ln].length?this[Os].trim():this[ln][0][Sr]===_r.xhtml.id?this[ln][0][Pr]().trim():null:this[Os].trim()}[qr](e){e=e.value||"";this[Os]=e.toString()}[js](e=!1){const t=Object.create(null);e&&(t.$ns=this[Sr]);this[Os]&&(t.$content=this[Os]);t.$name=this[kr];t.children=[];for(const i of this[ln])t.children.push(i[js](e));t.attributes=Object.create(null);for(const[e,i]of this[Cn])t.attributes[e]=i[Os];return t}}class ContentObject extends XFAObject{constructor(e,t){super(e,t);this[Os]=""}[Mr](e){this[Os]+=e}[Zs](){}}class OptionObject extends ContentObject{constructor(e,t,i){super(e,t);this[yn]=i}[Zs](){this[Os]=getKeyword({data:this[Os],defaultValue:this[yn][0],validate:e=>this[yn].includes(e)})}[Ys](e){super[Ys](e);delete this[yn]}}class StringObject extends ContentObject{[Zs](){this[Os]=this[Os].trim()}}class IntegerObject extends ContentObject{constructor(e,t,i,a){super(e,t);this[En]=i;this[Fn]=a}[Zs](){this[Os]=getInteger({data:this[Os],defaultValue:this[En],validate:this[Fn]})}[Ys](e){super[Ys](e);delete this[En];delete this[Fn]}}class Option01 extends IntegerObject{constructor(e,t){super(e,t,0,(e=>1===e))}}class Option10 extends IntegerObject{constructor(e,t){super(e,t,1,(e=>0===e))}}function measureToString(e){return"string"==typeof e?"0px":Number.isInteger(e)?`${e}px`:`${e.toFixed(2)}px`}const Rn={anchorType(e,t){const i=e[or]();if(i&&(!i.layout||"position"===i.layout)){"transform"in t||(t.transform="");switch(e.anchorType){case"bottomCenter":t.transform+="translate(-50%, -100%)";break;case"bottomLeft":t.transform+="translate(0,-100%)";break;case"bottomRight":t.transform+="translate(-100%,-100%)";break;case"middleCenter":t.transform+="translate(-50%,-50%)";break;case"middleLeft":t.transform+="translate(0,-50%)";break;case"middleRight":t.transform+="translate(-100%,-50%)";break;case"topCenter":t.transform+="translate(-50%,0)";break;case"topRight":t.transform+="translate(-100%,0)"}}},dimensions(e,t){const i=e[or]();let a=e.w;const s=e.h;if(i.layout?.includes("row")){const t=i[Xs],s=e.colSpan;let r;if(-1===s){r=t.columnWidths.slice(t.currentColumn).reduce(((e,t)=>e+t),0);t.currentColumn=0}else{r=t.columnWidths.slice(t.currentColumn,t.currentColumn+s).reduce(((e,t)=>e+t),0);t.currentColumn=(t.currentColumn+e.colSpan)%t.columnWidths.length}isNaN(r)||(a=e.w=r)}t.width=""!==a?measureToString(a):"auto";t.height=""!==s?measureToString(s):"auto"},position(e,t){const i=e[or]();if(!i?.layout||"position"===i.layout){t.position="absolute";t.left=measureToString(e.x);t.top=measureToString(e.y)}},rotate(e,t){if(e.rotate){"transform"in t||(t.transform="");t.transform+=`rotate(-${e.rotate}deg)`;t.transformOrigin="top left"}},presence(e,t){switch(e.presence){case"invisible":t.visibility="hidden";break;case"hidden":case"inactive":t.display="none"}},hAlign(e,t){if("para"===e[kr])switch(e.hAlign){case"justifyAll":t.textAlign="justify-all";break;case"radix":t.textAlign="left";break;default:t.textAlign=e.hAlign}else switch(e.hAlign){case"left":t.alignSelf="start";break;case"center":t.alignSelf="center";break;case"right":t.alignSelf="end"}},margin(e,t){e.margin&&(t.margin=e.margin[Zr]().margin)}};function setMinMaxDimensions(e,t){if("position"===e[or]().layout){e.minW>0&&(t.minWidth=measureToString(e.minW));e.maxW>0&&(t.maxWidth=measureToString(e.maxW));e.minH>0&&(t.minHeight=measureToString(e.minH));e.maxH>0&&(t.maxHeight=measureToString(e.maxH))}}function layoutText(e,t,i,a,s,r){const n=new TextMeasure(t,i,a,s);"string"==typeof e?n.addString(e):e[Ur](n);return n.compute(r)}function layoutNode(e,t){let i=null,a=null,s=!1;if((!e.w||!e.h)&&e.value){let r=0,n=0;if(e.margin){r=e.margin.leftInset+e.margin.rightInset;n=e.margin.topInset+e.margin.bottomInset}let g=null,o=null;if(e.para){o=Object.create(null);g=""===e.para.lineHeight?null:e.para.lineHeight;o.top=""===e.para.spaceAbove?0:e.para.spaceAbove;o.bottom=""===e.para.spaceBelow?0:e.para.spaceBelow;o.left=""===e.para.marginLeft?0:e.para.marginLeft;o.right=""===e.para.marginRight?0:e.para.marginRight}let c=e.font;if(!c){const t=e[cr]();let i=e[Ir]();for(;i&&i!==t;){if(i.font){c=i.font;break}i=i[Ir]()}}const C=(e.w||t.width)-r,h=e[Cr].fontFinder;if(e.value.exData&&e.value.exData[Os]&&"text/html"===e.value.exData.contentType){const t=layoutText(e.value.exData[Os],c,o,g,h,C);a=t.width;i=t.height;s=t.isBroken}else{const t=e.value[Pr]();if(t){const e=layoutText(t,c,o,g,h,C);a=e.width;i=e.height;s=e.isBroken}}null===a||e.w||(a+=r);null===i||e.h||(i+=n)}return{w:a,h:i,isBroken:s}}function computeBbox(e,t,i){let a;if(""!==e.w&&""!==e.h)a=[e.x,e.y,e.w,e.h];else{if(!i)return null;let s=e.w;if(""===s){if(0===e.maxW){const t=e[or]();s="position"===t.layout&&""!==t.w?0:e.minW}else s=Math.min(e.maxW,i.width);t.attributes.style.width=measureToString(s)}let r=e.h;if(""===r){if(0===e.maxH){const t=e[or]();r="position"===t.layout&&""!==t.h?0:e.minH}else r=Math.min(e.maxH,i.height);t.attributes.style.height=measureToString(r)}a=[e.x,e.y,s,r]}return a}function fixDimensions(e){const t=e[or]();if(t.layout?.includes("row")){const i=t[Xs],a=e.colSpan;let s;s=-1===a?i.columnWidths.slice(i.currentColumn).reduce(((e,t)=>e+t),0):i.columnWidths.slice(i.currentColumn,i.currentColumn+a).reduce(((e,t)=>e+t),0);isNaN(s)||(e.w=s)}t.layout&&"position"!==t.layout&&(e.x=e.y=0);"table"===e.layout&&""===e.w&&Array.isArray(e.columnWidths)&&(e.w=e.columnWidths.reduce(((e,t)=>e+t),0))}function layoutClass(e){switch(e.layout){case"position":default:return"xfaPosition";case"lr-tb":return"xfaLrTb";case"rl-row":return"xfaRlRow";case"rl-tb":return"xfaRlTb";case"row":return"xfaRow";case"table":return"xfaTable";case"tb":return"xfaTb"}}function toStyle(e,...t){const i=Object.create(null);for(const a of t){const t=e[a];if(null!==t)if(Rn.hasOwnProperty(a))Rn[a](e,i);else if(t instanceof XFAObject){const e=t[Zr]();e?Object.assign(i,e):warn(`(DEBUG) - XFA - style for ${a} not implemented yet`)}}return i}function createWrapper(e,t){const{attributes:i}=t,{style:a}=i,s={name:"div",attributes:{class:["xfaWrapper"],style:Object.create(null)},children:[]};i.class.push("xfaWrapped");if(e.border){const{widths:i,insets:r}=e.border[Xs];let n,g,o=r[0],c=r[3];const C=r[0]+r[2],h=r[1]+r[3];switch(e.border.hand){case"even":o-=i[0]/2;c-=i[3]/2;n=`calc(100% + ${(i[1]+i[3])/2-h}px)`;g=`calc(100% + ${(i[0]+i[2])/2-C}px)`;break;case"left":o-=i[0];c-=i[3];n=`calc(100% + ${i[1]+i[3]-h}px)`;g=`calc(100% + ${i[0]+i[2]-C}px)`;break;case"right":n=h?`calc(100% - ${h}px)`:"100%";g=C?`calc(100% - ${C}px)`:"100%"}const l=["xfaBorder"];isPrintOnly(e.border)&&l.push("xfaPrintOnly");const Q={name:"div",attributes:{class:l,style:{top:`${o}px`,left:`${c}px`,width:n,height:g}},children:[]};for(const e of["border","borderWidth","borderColor","borderRadius","borderStyle"])if(void 0!==a[e]){Q.attributes.style[e]=a[e];delete a[e]}s.children.push(Q,t)}else s.children.push(t);for(const e of["background","backgroundClip","top","left","width","height","minWidth","minHeight","maxWidth","maxHeight","transform","transformOrigin","visibility"])if(void 0!==a[e]){s.attributes.style[e]=a[e];delete a[e]}s.attributes.style.position="absolute"===a.position?"absolute":"relative";delete a.position;if(a.alignSelf){s.attributes.style.alignSelf=a.alignSelf;delete a.alignSelf}return s}function fixTextIndent(e){const t=getMeasurement(e.textIndent,"0px");if(t>=0)return;const i="padding"+("left"===("right"===e.textAlign?"right":"left")?"Left":"Right"),a=getMeasurement(e[i],"0px");e[i]=a-t+"px"}function setAccess(e,t){switch(e.access){case"nonInteractive":t.push("xfaNonInteractive");break;case"readOnly":t.push("xfaReadOnly");break;case"protected":t.push("xfaDisabled")}}function isPrintOnly(e){return e.relevant.length>0&&!e.relevant[0].excluded&&"print"===e.relevant[0].viewname}function getCurrentPara(e){const t=e[cr]()[Xs].paraStack;return t.length?t.at(-1):null}function setPara(e,t,i){if(i.attributes.class?.includes("xfaRich")){if(t){""===e.h&&(t.height="auto");""===e.w&&(t.width="auto")}const a=getCurrentPara(e);if(a){const e=i.attributes.style;e.display="flex";e.flexDirection="column";switch(a.vAlign){case"top":e.justifyContent="start";break;case"bottom":e.justifyContent="end";break;case"middle":e.justifyContent="center"}const t=a[Zr]();for(const[i,a]of Object.entries(t))i in e||(e[i]=a)}}}function setFontFamily(e,t,i,a){if(!i){delete a.fontFamily;return}const s=stripQuotes(e.typeface);a.fontFamily=`"${s}"`;const r=i.find(s);if(r){const{fontFamily:i}=r.regular.cssFontInfo;i!==s&&(a.fontFamily=`"${i}"`);const n=getCurrentPara(t);if(n&&""!==n.lineHeight)return;if(a.lineHeight)return;const g=selectFont(e,r);g&&(a.lineHeight=Math.max(1.2,g.lineHeight))}}function fixURL(e){const t=createValidAbsoluteUrl(e,null,{addDefaultProtocol:!0,tryConvertEncoding:!0});return t?t.href:null}function createLine(e,t){return{name:"div",attributes:{class:["lr-tb"===e.layout?"xfaLr":"xfaRl"]},children:t}}function flushHTML(e){if(!e[Xs])return null;const t={name:"div",attributes:e[Xs].attributes,children:e[Xs].children};if(e[Xs].failingNode){const i=e[Xs].failingNode[Vs]();i&&(e.layout.endsWith("-tb")?t.children.push(createLine(e,[i])):t.children.push(i))}return 0===t.children.length?null:t}function addHTML(e,t,i){const a=e[Xs],s=a.availableSpace,[r,n,g,o]=i;switch(e.layout){case"position":a.width=Math.max(a.width,r+g);a.height=Math.max(a.height,n+o);a.children.push(t);break;case"lr-tb":case"rl-tb":if(!a.line||1===a.attempt){a.line=createLine(e,[]);a.children.push(a.line);a.numberInLine=0}a.numberInLine+=1;a.line.children.push(t);if(0===a.attempt){a.currentWidth+=g;a.height=Math.max(a.height,a.prevHeight+o)}else{a.currentWidth=g;a.prevHeight=a.height;a.height+=o;a.attempt=0}a.width=Math.max(a.width,a.currentWidth);break;case"rl-row":case"row":{a.children.push(t);a.width+=g;a.height=Math.max(a.height,o);const e=measureToString(a.height);for(const t of a.children)t.attributes.style.height=e;break}case"table":case"tb":a.width=Math.min(s.width,Math.max(a.width,g));a.height+=o;a.children.push(t)}}function getAvailableSpace(e){const t=e[Xs].availableSpace,i=e.margin?e.margin.topInset+e.margin.bottomInset:0,a=e.margin?e.margin.leftInset+e.margin.rightInset:0;switch(e.layout){case"lr-tb":case"rl-tb":return 0===e[Xs].attempt?{width:t.width-a-e[Xs].currentWidth,height:t.height-i-e[Xs].prevHeight}:{width:t.width-a,height:t.height-i-e[Xs].height};case"rl-row":case"row":return{width:e[Xs].columnWidths.slice(e[Xs].currentColumn).reduce(((e,t)=>e+t)),height:t.height-a};case"table":case"tb":return{width:t.width-a,height:t.height-i-e[Xs].height};default:return t}}function checkDimensions(e,t){if(null===e[cr]()[Xs].firstUnsplittable)return!0;if(0===e.w||0===e.h)return!0;const i=e[or](),a=i[Xs]?.attempt||0,[,s,r,n]=function getTransformedBBox(e){let t,i,a=""===e.w?NaN:e.w,s=""===e.h?NaN:e.h,[r,n]=[0,0];switch(e.anchorType||""){case"bottomCenter":[r,n]=[a/2,s];break;case"bottomLeft":[r,n]=[0,s];break;case"bottomRight":[r,n]=[a,s];break;case"middleCenter":[r,n]=[a/2,s/2];break;case"middleLeft":[r,n]=[0,s/2];break;case"middleRight":[r,n]=[a,s/2];break;case"topCenter":[r,n]=[a/2,0];break;case"topRight":[r,n]=[a,0]}switch(e.rotate||0){case 0:[t,i]=[-r,-n];break;case 90:[t,i]=[-n,r];[a,s]=[s,-a];break;case 180:[t,i]=[r,n];[a,s]=[-a,-s];break;case 270:[t,i]=[n,-r];[a,s]=[-s,a]}return[e.x+t+Math.min(0,a),e.y+i+Math.min(0,s),Math.abs(a),Math.abs(s)]}(e);switch(i.layout){case"lr-tb":case"rl-tb":return 0===a?e[cr]()[Xs].noLayoutFailure?""!==e.w?Math.round(r-t.width)<=2:t.width>2:!(""!==e.h&&Math.round(n-t.height)>2)&&(""!==e.w?Math.round(r-t.width)<=2||0===i[Xs].numberInLine&&t.height>2:t.width>2):!!e[cr]()[Xs].noLayoutFailure||!(""!==e.h&&Math.round(n-t.height)>2)&&((""===e.w||Math.round(r-t.width)<=2||!i[wr]())&&t.height>2);case"table":case"tb":return!!e[cr]()[Xs].noLayoutFailure||(""===e.h||e[yr]()?(""===e.w||Math.round(r-t.width)<=2||!i[wr]())&&t.height>2:Math.round(n-t.height)<=2);case"position":if(e[cr]()[Xs].noLayoutFailure)return!0;if(""===e.h||Math.round(n+s-t.height)<=2)return!0;return n+s>e[cr]()[Xs].currentContentArea.h;case"rl-row":case"row":return!!e[cr]()[Xs].noLayoutFailure||(""===e.h||Math.round(n-t.height)<=2);default:return!0}}const Nn=_r.template.id,Gn="http://www.w3.org/2000/svg",Mn=/^H(\d+)$/,Un=new Set(["image/gif","image/jpeg","image/jpg","image/pjpeg","image/png","image/apng","image/x-png","image/bmp","image/x-ms-bmp","image/tiff","image/tif","application/octet-stream"]),xn=[[[66,77],"image/bmp"],[[255,216,255],"image/jpeg"],[[73,73,42,0],"image/tiff"],[[77,77,0,42],"image/tiff"],[[71,73,70,56,57,97],"image/gif"],[[137,80,78,71,13,10,26,10],"image/png"]];function getBorderDims(e){if(!e||!e.border)return{w:0,h:0};const t=e.border[ar]();return t?{w:t.widths[0]+t.widths[2]+t.insets[0]+t.insets[2],h:t.widths[1]+t.widths[3]+t.insets[1]+t.insets[3]}:{w:0,h:0}}function hasMargin(e){return e.margin&&(e.margin.topInset||e.margin.rightInset||e.margin.bottomInset||e.margin.leftInset)}function _setValue(e,t){if(!e.value){const t=new Value({});e[Hs](t);e.value=t}e.value[qr](t)}function*getContainedChildren(e){for(const t of e[rr]())t instanceof SubformSet?yield*t[nr]():yield t}function isRequired(e){return"error"===e.validate?.nullTest}function setTabIndex(e){for(;e;){if(!e.traversal){e[Or]=e[Ir]()[Or];return}if(e[Or])return;let t=null;for(const i of e.traversal[rr]())if("next"===i.operation){t=i;break}if(!t||!t.ref){e[Or]=e[Ir]()[Or];return}const i=e[cr]();e[Or]=++i[Or];const a=i[vr](t.ref,e);if(!a)return;e=a[0]}}function applyAssist(e,t){const i=e.assist;if(i){const e=i[jr]();e&&(t.title=e);const a=i.role.match(Mn);if(a){const e="heading",i=a[1];t.role=e;t["aria-level"]=i}}if("table"===e.layout)t.role="table";else if("row"===e.layout)t.role="row";else{const i=e[Ir]();"row"===i.layout&&(t.role="TH"===i.assist?.role?"columnheader":"cell")}}function ariaLabel(e){if(!e.assist)return null;const t=e.assist;return t.speak&&""!==t.speak[Os]?t.speak[Os]:t.toolTip?t.toolTip[Os]:null}function valueToHtml(e){return HTMLResult.success({name:"div",attributes:{class:["xfaRich"],style:Object.create(null)},children:[{name:"span",attributes:{style:Object.create(null)},value:e}]})}function setFirstUnsplittable(e){const t=e[cr]();if(null===t[Xs].firstUnsplittable){t[Xs].firstUnsplittable=e;t[Xs].noLayoutFailure=!0}}function unsetFirstUnsplittable(e){const t=e[cr]();t[Xs].firstUnsplittable===e&&(t[Xs].noLayoutFailure=!1)}function handleBreak(e){if(e[Xs])return!1;e[Xs]=Object.create(null);if("auto"===e.targetType)return!1;const t=e[cr]();let i=null;if(e.target){i=t[vr](e.target,e[Ir]());if(!i)return!1;i=i[0]}const{currentPageArea:a,currentContentArea:s}=t[Xs];if("pageArea"===e.targetType){i instanceof PageArea||(i=null);if(e.startNew){e[Xs].target=i||a;return!0}if(i&&i!==a){e[Xs].target=i;return!0}return!1}i instanceof ContentArea||(i=null);const r=i&&i[Ir]();let n,g=r;if(e.startNew)if(i){const e=r.contentArea.children,t=e.indexOf(s),a=e.indexOf(i);-1!==t&&te;a[Xs].noLayoutFailure=!0;const n=t[jr](i);e[Ls](n.html,n.bbox);a[Xs].noLayoutFailure=s;t[or]=r}class AppearanceFilter extends StringObject{constructor(e){super(Nn,"appearanceFilter");this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Arc extends XFAObject{constructor(e){super(Nn,"arc",!0);this.circular=getInteger({data:e.circular,defaultValue:0,validate:e=>1===e});this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.startAngle=getFloat({data:e.startAngle,defaultValue:0,validate:e=>!0});this.sweepAngle=getFloat({data:e.sweepAngle,defaultValue:360,validate:e=>!0});this.use=e.use||"";this.usehref=e.usehref||"";this.edge=null;this.fill=null}[jr](){const e=this.edge||new Edge({}),t=e[Zr](),i=Object.create(null);"visible"===this.fill?.presence?Object.assign(i,this.fill[Zr]()):i.fill="transparent";i.strokeWidth=measureToString("visible"===e.presence?e.thickness:0);i.stroke=t.color;let a;const s={xmlns:Gn,style:{width:"100%",height:"100%",overflow:"visible"}};if(360===this.sweepAngle)a={name:"ellipse",attributes:{xmlns:Gn,cx:"50%",cy:"50%",rx:"50%",ry:"50%",style:i}};else{const e=this.startAngle*Math.PI/180,t=this.sweepAngle*Math.PI/180,r=this.sweepAngle>180?1:0,[n,g,o,c]=[50*(1+Math.cos(e)),50*(1-Math.sin(e)),50*(1+Math.cos(e+t)),50*(1-Math.sin(e+t))];a={name:"path",attributes:{xmlns:Gn,d:`M ${n} ${g} A 50 50 0 ${r} 0 ${o} ${c}`,vectorEffect:"non-scaling-stroke",style:i}};Object.assign(s,{viewBox:"0 0 100 100",preserveAspectRatio:"none"})}const r={name:"svg",children:[a],attributes:s};if(hasMargin(this[Ir]()[Ir]()))return HTMLResult.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[r]});r.attributes.style.position="absolute";return HTMLResult.success(r)}}class Area extends XFAObject{constructor(e){super(Nn,"area",!0);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.id=e.id||"";this.name=e.name||"";this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.desc=null;this.extras=null;this.area=new XFAObjectArray;this.draw=new XFAObjectArray;this.exObject=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.field=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray}*[nr](){yield*getContainedChildren(this)}[Dr](){return!0}[dr](){return!0}[Ls](e,t){const[i,a,s,r]=t;this[Xs].width=Math.max(this[Xs].width,i+s);this[Xs].height=Math.max(this[Xs].height,a+r);this[Xs].children.push(e)}[$s](){return this[Xs].availableSpace}[jr](e){const t=toStyle(this,"position"),i={style:t,id:this[Vr],class:["xfaArea"]};isPrintOnly(this)&&i.class.push("xfaPrintOnly");this.name&&(i.xfaName=this.name);const a=[];this[Xs]={children:a,width:0,height:0,availableSpace:e};const s=this[Js]({filter:new Set(["area","draw","field","exclGroup","subform","subformSet"]),include:!0});if(!s.success){if(s.isBreak())return s;delete this[Xs];return HTMLResult.FAILURE}t.width=measureToString(this[Xs].width);t.height=measureToString(this[Xs].height);const r={name:"div",attributes:i,children:a},n=[this.x,this.y,this[Xs].width,this[Xs].height];delete this[Xs];return HTMLResult.success(r,n)}}class Assist extends XFAObject{constructor(e){super(Nn,"assist",!0);this.id=e.id||"";this.role=e.role||"";this.use=e.use||"";this.usehref=e.usehref||"";this.speak=null;this.toolTip=null}[jr](){return this.toolTip?.[Os]||null}}class Barcode extends XFAObject{constructor(e){super(Nn,"barcode",!0);this.charEncoding=getKeyword({data:e.charEncoding?e.charEncoding.toLowerCase():"",defaultValue:"",validate:e=>["utf-8","big-five","fontspecific","gbk","gb-18030","gb-2312","ksc-5601","none","shift-jis","ucs-2","utf-16"].includes(e)||e.match(/iso-8859-\d{2}/)});this.checksum=getStringOption(e.checksum,["none","1mod10","1mod10_1mod11","2mod10","auto"]);this.dataColumnCount=getInteger({data:e.dataColumnCount,defaultValue:-1,validate:e=>e>=0});this.dataLength=getInteger({data:e.dataLength,defaultValue:-1,validate:e=>e>=0});this.dataPrep=getStringOption(e.dataPrep,["none","flateCompress"]);this.dataRowCount=getInteger({data:e.dataRowCount,defaultValue:-1,validate:e=>e>=0});this.endChar=e.endChar||"";this.errorCorrectionLevel=getInteger({data:e.errorCorrectionLevel,defaultValue:-1,validate:e=>e>=0&&e<=8});this.id=e.id||"";this.moduleHeight=getMeasurement(e.moduleHeight,"5mm");this.moduleWidth=getMeasurement(e.moduleWidth,"0.25mm");this.printCheckDigit=getInteger({data:e.printCheckDigit,defaultValue:0,validate:e=>1===e});this.rowColumnRatio=getRatio(e.rowColumnRatio);this.startChar=e.startChar||"";this.textLocation=getStringOption(e.textLocation,["below","above","aboveEmbedded","belowEmbedded","none"]);this.truncate=getInteger({data:e.truncate,defaultValue:0,validate:e=>1===e});this.type=getStringOption(e.type?e.type.toLowerCase():"",["aztec","codabar","code2of5industrial","code2of5interleaved","code2of5matrix","code2of5standard","code3of9","code3of9extended","code11","code49","code93","code128","code128a","code128b","code128c","code128sscc","datamatrix","ean8","ean8add2","ean8add5","ean13","ean13add2","ean13add5","ean13pwcd","fim","logmars","maxicode","msi","pdf417","pdf417macro","plessey","postauscust2","postauscust3","postausreplypaid","postausstandard","postukrm4scc","postusdpbc","postusimb","postusstandard","postus5zip","qrcode","rfid","rss14","rss14expanded","rss14limited","rss14stacked","rss14stackedomni","rss14truncated","telepen","ucc128","ucc128random","ucc128sscc","upca","upcaadd2","upcaadd5","upcapwcd","upce","upceadd2","upceadd5","upcean2","upcean5","upsmaxicode"]);this.upsMode=getStringOption(e.upsMode,["usCarrier","internationalCarrier","secureSymbol","standardSymbol"]);this.use=e.use||"";this.usehref=e.usehref||"";this.wideNarrowRatio=getRatio(e.wideNarrowRatio);this.encrypt=null;this.extras=null}}class Bind extends XFAObject{constructor(e){super(Nn,"bind",!0);this.match=getStringOption(e.match,["once","dataRef","global","none"]);this.ref=e.ref||"";this.picture=null}}class BindItems extends XFAObject{constructor(e){super(Nn,"bindItems");this.connection=e.connection||"";this.labelRef=e.labelRef||"";this.ref=e.ref||"";this.valueRef=e.valueRef||""}}class Bookend extends XFAObject{constructor(e){super(Nn,"bookend");this.id=e.id||"";this.leader=e.leader||"";this.trailer=e.trailer||"";this.use=e.use||"";this.usehref=e.usehref||""}}class BooleanElement extends Option01{constructor(e){super(Nn,"boolean");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[jr](e){return valueToHtml(1===this[Os]?"1":"0")}}class Border extends XFAObject{constructor(e){super(Nn,"border",!0);this.break=getStringOption(e.break,["close","open"]);this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.corner=new XFAObjectArray(4);this.edge=new XFAObjectArray(4);this.extras=null;this.fill=null;this.margin=null}[ar](){if(!this[Xs]){const e=this.edge.children.slice();if(e.length<4){const t=e.at(-1)||new Edge({});for(let i=e.length;i<4;i++)e.push(t)}const t=e.map((e=>e.thickness)),i=[0,0,0,0];if(this.margin){i[0]=this.margin.topInset;i[1]=this.margin.rightInset;i[2]=this.margin.bottomInset;i[3]=this.margin.leftInset}this[Xs]={widths:t,insets:i,edges:e}}return this[Xs]}[Zr](){const{edges:e}=this[ar](),t=e.map((e=>{const t=e[Zr]();t.color||="#000000";return t})),i=Object.create(null);this.margin&&Object.assign(i,this.margin[Zr]());"visible"===this.fill?.presence&&Object.assign(i,this.fill[Zr]());if(this.corner.children.some((e=>0!==e.radius))){const e=this.corner.children.map((e=>e[Zr]()));if(2===e.length||3===e.length){const t=e.at(-1);for(let i=e.length;i<4;i++)e.push(t)}i.borderRadius=e.map((e=>e.radius)).join(" ")}switch(this.presence){case"invisible":case"hidden":i.borderStyle="";break;case"inactive":i.borderStyle="none";break;default:i.borderStyle=t.map((e=>e.style)).join(" ")}i.borderWidth=t.map((e=>e.width)).join(" ");i.borderColor=t.map((e=>e.color)).join(" ");return i}}class Break extends XFAObject{constructor(e){super(Nn,"break",!0);this.after=getStringOption(e.after,["auto","contentArea","pageArea","pageEven","pageOdd"]);this.afterTarget=e.afterTarget||"";this.before=getStringOption(e.before,["auto","contentArea","pageArea","pageEven","pageOdd"]);this.beforeTarget=e.beforeTarget||"";this.bookendLeader=e.bookendLeader||"";this.bookendTrailer=e.bookendTrailer||"";this.id=e.id||"";this.overflowLeader=e.overflowLeader||"";this.overflowTarget=e.overflowTarget||"";this.overflowTrailer=e.overflowTrailer||"";this.startNew=getInteger({data:e.startNew,defaultValue:0,validate:e=>1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}}class BreakAfter extends XFAObject{constructor(e){super(Nn,"breakAfter",!0);this.id=e.id||"";this.leader=e.leader||"";this.startNew=getInteger({data:e.startNew,defaultValue:0,validate:e=>1===e});this.target=e.target||"";this.targetType=getStringOption(e.targetType,["auto","contentArea","pageArea"]);this.trailer=e.trailer||"";this.use=e.use||"";this.usehref=e.usehref||"";this.script=null}}class BreakBefore extends XFAObject{constructor(e){super(Nn,"breakBefore",!0);this.id=e.id||"";this.leader=e.leader||"";this.startNew=getInteger({data:e.startNew,defaultValue:0,validate:e=>1===e});this.target=e.target||"";this.targetType=getStringOption(e.targetType,["auto","contentArea","pageArea"]);this.trailer=e.trailer||"";this.use=e.use||"";this.usehref=e.usehref||"";this.script=null}[jr](e){this[Xs]={};return HTMLResult.FAILURE}}class Button extends XFAObject{constructor(e){super(Nn,"button",!0);this.highlight=getStringOption(e.highlight,["inverted","none","outline","push"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[jr](e){const t=this[Ir]()[Ir](),i={name:"button",attributes:{id:this[Vr],class:["xfaButton"],style:{}},children:[]};for(const e of t.event.children){if("click"!==e.activity||!e.script)continue;const t=recoverJsURL(e.script[Os]);if(!t)continue;const a=fixURL(t.url);a&&i.children.push({name:"a",attributes:{id:"link"+this[Vr],href:a,newWindow:t.newWindow,class:["xfaLink"],style:{}},children:[]})}return HTMLResult.success(i)}}class Calculate extends XFAObject{constructor(e){super(Nn,"calculate",!0);this.id=e.id||"";this.override=getStringOption(e.override,["disabled","error","ignore","warning"]);this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.message=null;this.script=null}}class Caption extends XFAObject{constructor(e){super(Nn,"caption",!0);this.id=e.id||"";this.placement=getStringOption(e.placement,["left","bottom","inline","right","top"]);this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.reserve=Math.ceil(getMeasurement(e.reserve));this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.font=null;this.margin=null;this.para=null;this.value=null}[qr](e){_setValue(this,e)}[ar](e){if(!this[Xs]){let{width:t,height:i}=e;switch(this.placement){case"left":case"right":case"inline":t=this.reserve<=0?t:this.reserve;break;case"top":case"bottom":i=this.reserve<=0?i:this.reserve}this[Xs]=layoutNode(this,{width:t,height:i})}return this[Xs]}[jr](e){if(!this.value)return HTMLResult.EMPTY;this[Lr]();const t=this.value[jr](e).html;if(!t){this[xr]();return HTMLResult.EMPTY}const i=this.reserve;if(this.reserve<=0){const{w:t,h:i}=this[ar](e);switch(this.placement){case"left":case"right":case"inline":this.reserve=t;break;case"top":case"bottom":this.reserve=i}}const a=[];"string"==typeof t?a.push({name:"#text",value:t}):a.push(t);const s=toStyle(this,"font","margin","visibility");switch(this.placement){case"left":case"right":this.reserve>0&&(s.width=measureToString(this.reserve));break;case"top":case"bottom":this.reserve>0&&(s.height=measureToString(this.reserve))}setPara(this,null,t);this[xr]();this.reserve=i;return HTMLResult.success({name:"div",attributes:{style:s,class:["xfaCaption"]},children:a})}}class Certificate extends StringObject{constructor(e){super(Nn,"certificate");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Certificates extends XFAObject{constructor(e){super(Nn,"certificates",!0);this.credentialServerPolicy=getStringOption(e.credentialServerPolicy,["optional","required"]);this.id=e.id||"";this.url=e.url||"";this.urlPolicy=e.urlPolicy||"";this.use=e.use||"";this.usehref=e.usehref||"";this.encryption=null;this.issuers=null;this.keyUsage=null;this.oids=null;this.signing=null;this.subjectDNs=null}}class CheckButton extends XFAObject{constructor(e){super(Nn,"checkButton",!0);this.id=e.id||"";this.mark=getStringOption(e.mark,["default","check","circle","cross","diamond","square","star"]);this.shape=getStringOption(e.shape,["square","round"]);this.size=getMeasurement(e.size,"10pt");this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}[jr](e){const t=toStyle("margin"),i=measureToString(this.size);t.width=t.height=i;let a,s,r;const n=this[Ir]()[Ir](),g=n.items.children.length&&n.items.children[0][jr]().html||[],o={on:(void 0!==g[0]?g[0]:"on").toString(),off:(void 0!==g[1]?g[1]:"off").toString()},c=(n.value?.[Pr]()||"off")===o.on||void 0,C=n[or](),h=n[Vr];let l;if(C instanceof ExclGroup){r=C[Vr];a="radio";s="xfaRadio";l=C[Ws]?.[Vr]||C[Vr]}else{a="checkbox";s="xfaCheckbox";l=n[Ws]?.[Vr]||n[Vr]}const Q={name:"input",attributes:{class:[s],style:t,fieldId:h,dataId:l,type:a,checked:c,xfaOn:o.on,xfaOff:o.off,"aria-label":ariaLabel(n),"aria-required":!1}};r&&(Q.attributes.name=r);if(isRequired(n)){Q.attributes["aria-required"]=!0;Q.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[Q]})}}class ChoiceList extends XFAObject{constructor(e){super(Nn,"choiceList",!0);this.commitOn=getStringOption(e.commitOn,["select","exit"]);this.id=e.id||"";this.open=getStringOption(e.open,["userControl","always","multiSelect","onEntry"]);this.textEntry=getInteger({data:e.textEntry,defaultValue:0,validate:e=>1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}[jr](e){const t=toStyle(this,"border","margin"),i=this[Ir]()[Ir](),a={fontSize:`calc(${i.font?.size||10}px * var(--scale-factor))`},s=[];if(i.items.children.length>0){const e=i.items;let t=0,r=0;if(2===e.children.length){t=e.children[0].save;r=1-t}const n=e.children[t][jr]().html,g=e.children[r][jr]().html;let o=!1;const c=i.value?.[Pr]()||"";for(let e=0,t=n.length;eMath.min(Math.max(0,parseInt(e.trim(),10)),255))).map((e=>isNaN(e)?0:e));if(r.length<3)return{r:i,g:a,b:s};[i,a,s]=r;return{r:i,g:a,b:s}}(e.value):"";this.extras=null}[hr](){return!1}[Zr](){return this.value?Util.makeHexColor(this.value.r,this.value.g,this.value.b):null}}class Comb extends XFAObject{constructor(e){super(Nn,"comb");this.id=e.id||"";this.numberOfCells=getInteger({data:e.numberOfCells,defaultValue:0,validate:e=>e>=0});this.use=e.use||"";this.usehref=e.usehref||""}}class Connect extends XFAObject{constructor(e){super(Nn,"connect",!0);this.connection=e.connection||"";this.id=e.id||"";this.ref=e.ref||"";this.usage=getStringOption(e.usage,["exportAndImport","exportOnly","importOnly"]);this.use=e.use||"";this.usehref=e.usehref||"";this.picture=null}}class ContentArea extends XFAObject{constructor(e){super(Nn,"contentArea",!0);this.h=getMeasurement(e.h);this.id=e.id||"";this.name=e.name||"";this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.w=getMeasurement(e.w);this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.desc=null;this.extras=null}[jr](e){const t={left:measureToString(this.x),top:measureToString(this.y),width:measureToString(this.w),height:measureToString(this.h)},i=["xfaContentarea"];isPrintOnly(this)&&i.push("xfaPrintOnly");return HTMLResult.success({name:"div",children:[],attributes:{style:t,class:i,id:this[Vr]}})}}class Corner extends XFAObject{constructor(e){super(Nn,"corner",!0);this.id=e.id||"";this.inverted=getInteger({data:e.inverted,defaultValue:0,validate:e=>1===e});this.join=getStringOption(e.join,["square","round"]);this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.radius=getMeasurement(e.radius);this.stroke=getStringOption(e.stroke,["solid","dashDot","dashDotDot","dashed","dotted","embossed","etched","lowered","raised"]);this.thickness=getMeasurement(e.thickness,"0.5pt");this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zr](){const e=toStyle(this,"visibility");e.radius=measureToString("square"===this.join?0:this.radius);return e}}class DateElement extends ContentObject{constructor(e){super(Nn,"date");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){const e=this[Os].trim();this[Os]=e?new Date(e):null}[jr](e){return valueToHtml(this[Os]?this[Os].toString():"")}}class DateTime extends ContentObject{constructor(e){super(Nn,"dateTime");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){const e=this[Os].trim();this[Os]=e?new Date(e):null}[jr](e){return valueToHtml(this[Os]?this[Os].toString():"")}}class DateTimeEdit extends XFAObject{constructor(e){super(Nn,"dateTimeEdit",!0);this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.picker=getStringOption(e.picker,["host","none"]);this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.comb=null;this.extras=null;this.margin=null}[jr](e){const t=toStyle(this,"border","font","margin"),i=this[Ir]()[Ir](),a={name:"input",attributes:{type:"text",fieldId:i[Vr],dataId:i[Ws]?.[Vr]||i[Vr],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(i),"aria-required":!1}};if(isRequired(i)){a.attributes["aria-required"]=!0;a.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[a]})}}class Decimal extends ContentObject{constructor(e){super(Nn,"decimal");this.fracDigits=getInteger({data:e.fracDigits,defaultValue:2,validate:e=>!0});this.id=e.id||"";this.leadDigits=getInteger({data:e.leadDigits,defaultValue:-1,validate:e=>!0});this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){const e=parseFloat(this[Os].trim());this[Os]=isNaN(e)?null:e}[jr](e){return valueToHtml(null!==this[Os]?this[Os].toString():"")}}class DefaultUi extends XFAObject{constructor(e){super(Nn,"defaultUi",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}}class Desc extends XFAObject{constructor(e){super(Nn,"desc",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}}class DigestMethod extends OptionObject{constructor(e){super(Nn,"digestMethod",["","SHA1","SHA256","SHA512","RIPEMD160"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class DigestMethods extends XFAObject{constructor(e){super(Nn,"digestMethods",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.digestMethod=new XFAObjectArray}}class Draw extends XFAObject{constructor(e){super(Nn,"draw",!0);this.anchorType=getStringOption(e.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.locale=e.locale||"";this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.rotate=getInteger({data:e.rotate,defaultValue:0,validate:e=>e%90==0});this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.border=null;this.caption=null;this.desc=null;this.extras=null;this.font=null;this.keep=null;this.margin=null;this.para=null;this.traversal=null;this.ui=null;this.value=null;this.setProperty=new XFAObjectArray}[qr](e){_setValue(this,e)}[jr](e){setTabIndex(this);if("hidden"===this.presence||"inactive"===this.presence)return HTMLResult.EMPTY;fixDimensions(this);this[Lr]();const t=this.w,i=this.h,{w:a,h:s,isBroken:r}=layoutNode(this,e);if(a&&""===this.w){if(r&&this[or]()[wr]()){this[xr]();return HTMLResult.FAILURE}this.w=a}s&&""===this.h&&(this.h=s);setFirstUnsplittable(this);if(!checkDimensions(this,e)){this.w=t;this.h=i;this[xr]();return HTMLResult.FAILURE}unsetFirstUnsplittable(this);const n=toStyle(this,"font","hAlign","dimensions","position","presence","rotate","anchorType","border","margin");setMinMaxDimensions(this,n);if(n.margin){n.padding=n.margin;delete n.margin}const g=["xfaDraw"];this.font&&g.push("xfaFont");isPrintOnly(this)&&g.push("xfaPrintOnly");const o={style:n,id:this[Vr],class:g};this.name&&(o.xfaName=this.name);const c={name:"div",attributes:o,children:[]};applyAssist(this,o);const C=computeBbox(this,c,e),h=this.value?this.value[jr](e).html:null;if(null===h){this.w=t;this.h=i;this[xr]();return HTMLResult.success(createWrapper(this,c),C)}c.children.push(h);setPara(this,n,h);this.w=t;this.h=i;this[xr]();return HTMLResult.success(createWrapper(this,c),C)}}class Edge extends XFAObject{constructor(e){super(Nn,"edge",!0);this.cap=getStringOption(e.cap,["square","butt","round"]);this.id=e.id||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.stroke=getStringOption(e.stroke,["solid","dashDot","dashDotDot","dashed","dotted","embossed","etched","lowered","raised"]);this.thickness=getMeasurement(e.thickness,"0.5pt");this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zr](){const e=toStyle(this,"visibility");Object.assign(e,{linecap:this.cap,width:measureToString(this.thickness),color:this.color?this.color[Zr]():"#000000",style:""});if("visible"!==this.presence)e.style="none";else switch(this.stroke){case"solid":e.style="solid";break;case"dashDot":case"dashDotDot":case"dashed":e.style="dashed";break;case"dotted":e.style="dotted";break;case"embossed":e.style="ridge";break;case"etched":e.style="groove";break;case"lowered":e.style="inset";break;case"raised":e.style="outset"}return e}}class Encoding extends OptionObject{constructor(e){super(Nn,"encoding",["adbe.x509.rsa_sha1","adbe.pkcs7.detached","adbe.pkcs7.sha1"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Encodings extends XFAObject{constructor(e){super(Nn,"encodings",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.encoding=new XFAObjectArray}}class Encrypt extends XFAObject{constructor(e){super(Nn,"encrypt",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=null}}class EncryptData extends XFAObject{constructor(e){super(Nn,"encryptData",!0);this.id=e.id||"";this.operation=getStringOption(e.operation,["encrypt","decrypt"]);this.target=e.target||"";this.use=e.use||"";this.usehref=e.usehref||"";this.filter=null;this.manifest=null}}class Encryption extends XFAObject{constructor(e){super(Nn,"encryption",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=new XFAObjectArray}}class EncryptionMethod extends OptionObject{constructor(e){super(Nn,"encryptionMethod",["","AES256-CBC","TRIPLEDES-CBC","AES128-CBC","AES192-CBC"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class EncryptionMethods extends XFAObject{constructor(e){super(Nn,"encryptionMethods",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.encryptionMethod=new XFAObjectArray}}class Event extends XFAObject{constructor(e){super(Nn,"event",!0);this.activity=getStringOption(e.activity,["click","change","docClose","docReady","enter","exit","full","indexChange","initialize","mouseDown","mouseEnter","mouseExit","mouseUp","postExecute","postOpen","postPrint","postSave","postSign","postSubmit","preExecute","preOpen","prePrint","preSave","preSign","preSubmit","ready","validationState"]);this.id=e.id||"";this.listen=getStringOption(e.listen,["refOnly","refAndDescendents"]);this.name=e.name||"";this.ref=e.ref||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.encryptData=null;this.execute=null;this.script=null;this.signData=null;this.submit=null}}class ExData extends ContentObject{constructor(e){super(Nn,"exData");this.contentType=e.contentType||"";this.href=e.href||"";this.id=e.id||"";this.maxLength=getInteger({data:e.maxLength,defaultValue:-1,validate:e=>e>=-1});this.name=e.name||"";this.rid=e.rid||"";this.transferEncoding=getStringOption(e.transferEncoding,["none","base64","package"]);this.use=e.use||"";this.usehref=e.usehref||""}[ur](){return"text/html"===this.contentType}[Nr](e){if("text/html"===this.contentType&&e[Sr]===_r.xhtml.id){this[Os]=e;return!0}if("text/xml"===this.contentType){this[Os]=e;return!0}return!1}[jr](e){return"text/html"===this.contentType&&this[Os]?this[Os][jr](e):HTMLResult.EMPTY}}class ExObject extends XFAObject{constructor(e){super(Nn,"exObject",!0);this.archive=e.archive||"";this.classId=e.classId||"";this.codeBase=e.codeBase||"";this.codeType=e.codeType||"";this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.exObject=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}}class ExclGroup extends XFAObject{constructor(e){super(Nn,"exclGroup",!0);this.access=getStringOption(e.access,["open","nonInteractive","protected","readOnly"]);this.accessKey=e.accessKey||"";this.anchorType=getStringOption(e.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.layout=getStringOption(e.layout,["position","lr-tb","rl-row","rl-tb","row","table","tb"]);this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.bind=null;this.border=null;this.calculate=null;this.caption=null;this.desc=null;this.extras=null;this.margin=null;this.para=null;this.traversal=null;this.validate=null;this.connect=new XFAObjectArray;this.event=new XFAObjectArray;this.field=new XFAObjectArray;this.setProperty=new XFAObjectArray}[dr](){return!0}[hr](){return!0}[qr](e){for(const t of this.field.children){if(!t.value){const e=new Value({});t[Hs](e);t.value=e}t.value[qr](e)}}[wr](){return this.layout.endsWith("-tb")&&0===this[Xs].attempt&&this[Xs].numberInLine>0||this[Ir]()[wr]()}[yr](){const e=this[or]();if(!e[yr]())return!1;if(void 0!==this[Xs]._isSplittable)return this[Xs]._isSplittable;if("position"===this.layout||this.layout.includes("row")){this[Xs]._isSplittable=!1;return!1}if(e.layout?.endsWith("-tb")&&0!==e[Xs].numberInLine)return!1;this[Xs]._isSplittable=!0;return!0}[Vs](){return flushHTML(this)}[Ls](e,t){addHTML(this,e,t)}[$s](){return getAvailableSpace(this)}[jr](e){setTabIndex(this);if("hidden"===this.presence||"inactive"===this.presence||0===this.h||0===this.w)return HTMLResult.EMPTY;fixDimensions(this);const t=[],i={id:this[Vr],class:[]};setAccess(this,i.class);this[Xs]||(this[Xs]=Object.create(null));Object.assign(this[Xs],{children:t,attributes:i,attempt:0,line:null,numberInLine:0,availableSpace:{width:Math.min(this.w||1/0,e.width),height:Math.min(this.h||1/0,e.height)},width:0,height:0,prevHeight:0,currentWidth:0});const a=this[yr]();a||setFirstUnsplittable(this);if(!checkDimensions(this,e))return HTMLResult.FAILURE;const s=new Set(["field"]);if(this.layout.includes("row")){const e=this[or]().columnWidths;if(Array.isArray(e)&&e.length>0){this[Xs].columnWidths=e;this[Xs].currentColumn=0}}const r=toStyle(this,"anchorType","dimensions","position","presence","border","margin","hAlign"),n=["xfaExclgroup"],g=layoutClass(this);g&&n.push(g);isPrintOnly(this)&&n.push("xfaPrintOnly");i.style=r;i.class=n;this.name&&(i.xfaName=this.name);this[Lr]();const o="lr-tb"===this.layout||"rl-tb"===this.layout,c=o?2:1;for(;this[Xs].attempte>=1||-1===e});this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.locale=e.locale||"";this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.rotate=getInteger({data:e.rotate,defaultValue:0,validate:e=>e%90==0});this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.bind=null;this.border=null;this.calculate=null;this.caption=null;this.desc=null;this.extras=null;this.font=null;this.format=null;this.items=new XFAObjectArray(2);this.keep=null;this.margin=null;this.para=null;this.traversal=null;this.ui=null;this.validate=null;this.value=null;this.bindItems=new XFAObjectArray;this.connect=new XFAObjectArray;this.event=new XFAObjectArray;this.setProperty=new XFAObjectArray}[dr](){return!0}[qr](e){_setValue(this,e)}[jr](e){setTabIndex(this);if(!this.ui){this.ui=new Ui({});this.ui[Cr]=this[Cr];this[Hs](this.ui);let e;switch(this.items.children.length){case 0:e=new TextEdit({});this.ui.textEdit=e;break;case 1:e=new CheckButton({});this.ui.checkButton=e;break;case 2:e=new ChoiceList({});this.ui.choiceList=e}this.ui[Hs](e)}if(!this.ui||"hidden"===this.presence||"inactive"===this.presence||0===this.h||0===this.w)return HTMLResult.EMPTY;this.caption&&delete this.caption[Xs];this[Lr]();const t=this.caption?this.caption[jr](e).html:null,i=this.w,a=this.h;let s=0,r=0;if(this.margin){s=this.margin.leftInset+this.margin.rightInset;r=this.margin.topInset+this.margin.bottomInset}let n=null;if(""===this.w||""===this.h){let t=null,i=null,a=0,g=0;if(this.ui.checkButton)a=g=this.ui.checkButton.size;else{const{w:t,h:i}=layoutNode(this,e);if(null!==t){a=t;g=i}else g=function fonts_getMetrics(e,t=!1){let i=null;if(e){const t=stripQuotes(e.typeface),a=e[Cr].fontFinder.find(t);i=selectFont(e,a)}if(!i)return{lineHeight:12,lineGap:2,lineNoGap:10};const a=e.size||10,s=i.lineHeight?Math.max(t?0:1.2,i.lineHeight):1.2,r=void 0===i.lineGap?.2:i.lineGap;return{lineHeight:s*a,lineGap:r*a,lineNoGap:Math.max(1,s-r)*a}}(this.font,!0).lineNoGap}n=getBorderDims(this.ui[ar]());a+=n.w;g+=n.h;if(this.caption){const{w:s,h:r,isBroken:n}=this.caption[ar](e);if(n&&this[or]()[wr]()){this[xr]();return HTMLResult.FAILURE}t=s;i=r;switch(this.caption.placement){case"left":case"right":case"inline":t+=a;break;case"top":case"bottom":i+=g}}else{t=a;i=g}if(t&&""===this.w){t+=s;this.w=Math.min(this.maxW<=0?1/0:this.maxW,this.minW+1e>=1&&e<=5});this.appearanceFilter=null;this.certificates=null;this.digestMethods=null;this.encodings=null;this.encryptionMethods=null;this.handler=null;this.lockDocument=null;this.mdp=null;this.reasons=null;this.timeStamp=null}}class Float extends ContentObject{constructor(e){super(Nn,"float");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){const e=parseFloat(this[Os].trim());this[Os]=isNaN(e)?null:e}[jr](e){return valueToHtml(null!==this[Os]?this[Os].toString():"")}}class template_Font extends XFAObject{constructor(e){super(Nn,"font",!0);this.baselineShift=getMeasurement(e.baselineShift);this.fontHorizontalScale=getFloat({data:e.fontHorizontalScale,defaultValue:100,validate:e=>e>=0});this.fontVerticalScale=getFloat({data:e.fontVerticalScale,defaultValue:100,validate:e=>e>=0});this.id=e.id||"";this.kerningMode=getStringOption(e.kerningMode,["none","pair"]);this.letterSpacing=getMeasurement(e.letterSpacing,"0");this.lineThrough=getInteger({data:e.lineThrough,defaultValue:0,validate:e=>1===e||2===e});this.lineThroughPeriod=getStringOption(e.lineThroughPeriod,["all","word"]);this.overline=getInteger({data:e.overline,defaultValue:0,validate:e=>1===e||2===e});this.overlinePeriod=getStringOption(e.overlinePeriod,["all","word"]);this.posture=getStringOption(e.posture,["normal","italic"]);this.size=getMeasurement(e.size,"10pt");this.typeface=e.typeface||"Courier";this.underline=getInteger({data:e.underline,defaultValue:0,validate:e=>1===e||2===e});this.underlinePeriod=getStringOption(e.underlinePeriod,["all","word"]);this.use=e.use||"";this.usehref=e.usehref||"";this.weight=getStringOption(e.weight,["normal","bold"]);this.extras=null;this.fill=null}[Ys](e){super[Ys](e);this[Cr].usedTypefaces.add(this.typeface)}[Zr](){const e=toStyle(this,"fill"),t=e.color;if(t)if("#000000"===t)delete e.color;else if(!t.startsWith("#")){e.background=t;e.backgroundClip="text";e.color="transparent"}this.baselineShift&&(e.verticalAlign=measureToString(this.baselineShift));e.fontKerning="none"===this.kerningMode?"none":"normal";e.letterSpacing=measureToString(this.letterSpacing);if(0!==this.lineThrough){e.textDecoration="line-through";2===this.lineThrough&&(e.textDecorationStyle="double")}if(0!==this.overline){e.textDecoration="overline";2===this.overline&&(e.textDecorationStyle="double")}e.fontStyle=this.posture;e.fontSize=measureToString(.99*this.size);setFontFamily(this,this,this[Cr].fontFinder,e);if(0!==this.underline){e.textDecoration="underline";2===this.underline&&(e.textDecorationStyle="double")}e.fontWeight=this.weight;return e}}class Format extends XFAObject{constructor(e){super(Nn,"format",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.picture=null}}class Handler extends StringObject{constructor(e){super(Nn,"handler");this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Hyphenation extends XFAObject{constructor(e){super(Nn,"hyphenation");this.excludeAllCaps=getInteger({data:e.excludeAllCaps,defaultValue:0,validate:e=>1===e});this.excludeInitialCap=getInteger({data:e.excludeInitialCap,defaultValue:0,validate:e=>1===e});this.hyphenate=getInteger({data:e.hyphenate,defaultValue:0,validate:e=>1===e});this.id=e.id||"";this.pushCharacterCount=getInteger({data:e.pushCharacterCount,defaultValue:3,validate:e=>e>=0});this.remainCharacterCount=getInteger({data:e.remainCharacterCount,defaultValue:3,validate:e=>e>=0});this.use=e.use||"";this.usehref=e.usehref||"";this.wordCharacterCount=getInteger({data:e.wordCharacterCount,defaultValue:7,validate:e=>e>=0})}}class Image extends StringObject{constructor(e){super(Nn,"image");this.aspect=getStringOption(e.aspect,["fit","actual","height","none","width"]);this.contentType=e.contentType||"";this.href=e.href||"";this.id=e.id||"";this.name=e.name||"";this.transferEncoding=getStringOption(e.transferEncoding,["base64","none","package"]);this.use=e.use||"";this.usehref=e.usehref||""}[jr](){if(this.contentType&&!Un.has(this.contentType.toLowerCase()))return HTMLResult.EMPTY;let e=this[Cr].images&&this[Cr].images.get(this.href);if(!e&&(this.href||!this[Os]))return HTMLResult.EMPTY;e||"base64"!==this.transferEncoding||(e=function fromBase64Util(e){return Uint8Array.fromBase64?Uint8Array.fromBase64(e):stringToBytes(atob(e))}(this[Os]));if(!e)return HTMLResult.EMPTY;if(!this.contentType){for(const[t,i]of xn)if(e.length>t.length&&t.every(((t,i)=>t===e[i]))){this.contentType=i;break}if(!this.contentType)return HTMLResult.EMPTY}const t=new Blob([e],{type:this.contentType});let i;switch(this.aspect){case"fit":case"actual":break;case"height":i={height:"100%",objectFit:"fill"};break;case"none":i={width:"100%",height:"100%",objectFit:"fill"};break;case"width":i={width:"100%",objectFit:"fill"}}const a=this[Ir]();return HTMLResult.success({name:"img",attributes:{class:["xfaImage"],style:i,src:URL.createObjectURL(t),alt:a?ariaLabel(a[Ir]()):null}})}}class ImageEdit extends XFAObject{constructor(e){super(Nn,"imageEdit",!0);this.data=getStringOption(e.data,["link","embed"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}[jr](e){return"embed"===this.data?HTMLResult.success({name:"div",children:[],attributes:{}}):HTMLResult.EMPTY}}class Integer extends ContentObject{constructor(e){super(Nn,"integer");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){const e=parseInt(this[Os].trim(),10);this[Os]=isNaN(e)?null:e}[jr](e){return valueToHtml(null!==this[Os]?this[Os].toString():"")}}class Issuers extends XFAObject{constructor(e){super(Nn,"issuers",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=new XFAObjectArray}}class Items extends XFAObject{constructor(e){super(Nn,"items",!0);this.id=e.id||"";this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.ref=e.ref||"";this.save=getInteger({data:e.save,defaultValue:0,validate:e=>1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}[jr](){const e=[];for(const t of this[rr]())e.push(t[Pr]());return HTMLResult.success(e)}}class Keep extends XFAObject{constructor(e){super(Nn,"keep",!0);this.id=e.id||"";const t=["none","contentArea","pageArea"];this.intact=getStringOption(e.intact,t);this.next=getStringOption(e.next,t);this.previous=getStringOption(e.previous,t);this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}}class KeyUsage extends XFAObject{constructor(e){super(Nn,"keyUsage");const t=["","yes","no"];this.crlSign=getStringOption(e.crlSign,t);this.dataEncipherment=getStringOption(e.dataEncipherment,t);this.decipherOnly=getStringOption(e.decipherOnly,t);this.digitalSignature=getStringOption(e.digitalSignature,t);this.encipherOnly=getStringOption(e.encipherOnly,t);this.id=e.id||"";this.keyAgreement=getStringOption(e.keyAgreement,t);this.keyCertSign=getStringOption(e.keyCertSign,t);this.keyEncipherment=getStringOption(e.keyEncipherment,t);this.nonRepudiation=getStringOption(e.nonRepudiation,t);this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Line extends XFAObject{constructor(e){super(Nn,"line",!0);this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.slope=getStringOption(e.slope,["\\","/"]);this.use=e.use||"";this.usehref=e.usehref||"";this.edge=null}[jr](){const e=this[Ir]()[Ir](),t=this.edge||new Edge({}),i=t[Zr](),a=Object.create(null),s="visible"===t.presence?t.thickness:0;a.strokeWidth=measureToString(s);a.stroke=i.color;let r,n,g,o,c="100%",C="100%";if(e.w<=s){[r,n,g,o]=["50%",0,"50%","100%"];c=a.strokeWidth}else if(e.h<=s){[r,n,g,o]=[0,"50%","100%","50%"];C=a.strokeWidth}else"\\"===this.slope?[r,n,g,o]=[0,0,"100%","100%"]:[r,n,g,o]=[0,"100%","100%",0];const h={name:"svg",children:[{name:"line",attributes:{xmlns:Gn,x1:r,y1:n,x2:g,y2:o,style:a}}],attributes:{xmlns:Gn,width:c,height:C,style:{overflow:"visible"}}};if(hasMargin(e))return HTMLResult.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[h]});h.attributes.style.position="absolute";return HTMLResult.success(h)}}class Linear extends XFAObject{constructor(e){super(Nn,"linear",!0);this.id=e.id||"";this.type=getStringOption(e.type,["toRight","toBottom","toLeft","toTop"]);this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zr](e){e=e?e[Zr]():"#FFFFFF";return`linear-gradient(${this.type.replace(/([RBLT])/," $1").toLowerCase()}, ${e}, ${this.color?this.color[Zr]():"#000000"})`}}class LockDocument extends ContentObject{constructor(e){super(Nn,"lockDocument");this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){this[Os]=getStringOption(this[Os],["auto","0","1"])}}class Manifest extends XFAObject{constructor(e){super(Nn,"manifest",!0);this.action=getStringOption(e.action,["include","all","exclude"]);this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.ref=new XFAObjectArray}}class Margin extends XFAObject{constructor(e){super(Nn,"margin",!0);this.bottomInset=getMeasurement(e.bottomInset,"0");this.id=e.id||"";this.leftInset=getMeasurement(e.leftInset,"0");this.rightInset=getMeasurement(e.rightInset,"0");this.topInset=getMeasurement(e.topInset,"0");this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[Zr](){return{margin:measureToString(this.topInset)+" "+measureToString(this.rightInset)+" "+measureToString(this.bottomInset)+" "+measureToString(this.leftInset)}}}class Mdp extends XFAObject{constructor(e){super(Nn,"mdp");this.id=e.id||"";this.permissions=getInteger({data:e.permissions,defaultValue:2,validate:e=>1===e||3===e});this.signatureType=getStringOption(e.signatureType,["filler","author"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Medium extends XFAObject{constructor(e){super(Nn,"medium");this.id=e.id||"";this.imagingBBox=function getBBox(e){const t=-1;if(!e)return{x:t,y:t,width:t,height:t};const i=e.trim().split(/\s*,\s*/).map((e=>getMeasurement(e,"-1")));if(i.length<4||i[2]<0||i[3]<0)return{x:t,y:t,width:t,height:t};const[a,s,r,n]=i;return{x:a,y:s,width:r,height:n}}(e.imagingBBox);this.long=getMeasurement(e.long);this.orientation=getStringOption(e.orientation,["portrait","landscape"]);this.short=getMeasurement(e.short);this.stock=e.stock||"";this.trayIn=getStringOption(e.trayIn,["auto","delegate","pageFront"]);this.trayOut=getStringOption(e.trayOut,["auto","delegate"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Message extends XFAObject{constructor(e){super(Nn,"message",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.text=new XFAObjectArray}}class NumericEdit extends XFAObject{constructor(e){super(Nn,"numericEdit",!0);this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.comb=null;this.extras=null;this.margin=null}[jr](e){const t=toStyle(this,"border","font","margin"),i=this[Ir]()[Ir](),a={name:"input",attributes:{type:"text",fieldId:i[Vr],dataId:i[Ws]?.[Vr]||i[Vr],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(i),"aria-required":!1}};if(isRequired(i)){a.attributes["aria-required"]=!0;a.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[a]})}}class Occur extends XFAObject{constructor(e){super(Nn,"occur",!0);this.id=e.id||"";this.initial=""!==e.initial?getInteger({data:e.initial,defaultValue:"",validate:e=>!0}):"";this.max=""!==e.max?getInteger({data:e.max,defaultValue:1,validate:e=>!0}):"";this.min=""!==e.min?getInteger({data:e.min,defaultValue:1,validate:e=>!0}):"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[Ys](){const e=this[Ir](),t=this.min;""===this.min&&(this.min=e instanceof PageArea||e instanceof PageSet?0:1);""===this.max&&(this.max=""===t?e instanceof PageArea||e instanceof PageSet?-1:1:this.min);-1!==this.max&&this.max!0});this.name=e.name||"";this.numbered=getInteger({data:e.numbered,defaultValue:1,validate:e=>!0});this.oddOrEven=getStringOption(e.oddOrEven,["any","even","odd"]);this.pagePosition=getStringOption(e.pagePosition,["any","first","last","only","rest"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.desc=null;this.extras=null;this.medium=null;this.occur=null;this.area=new XFAObjectArray;this.contentArea=new XFAObjectArray;this.draw=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.field=new XFAObjectArray;this.subform=new XFAObjectArray}[br](){if(!this[Xs]){this[Xs]={numberOfUse:0};return!0}return!this.occur||-1===this.occur.max||this[Xs].numberOfUsee.oddOrEven===t&&e.pagePosition===i));if(a)return a;a=this.pageArea.children.find((e=>"any"===e.oddOrEven&&e.pagePosition===i));if(a)return a;a=this.pageArea.children.find((e=>"any"===e.oddOrEven&&"any"===e.pagePosition));return a||this.pageArea.children[0]}}class Para extends XFAObject{constructor(e){super(Nn,"para",!0);this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.lineHeight=e.lineHeight?getMeasurement(e.lineHeight,"0pt"):"";this.marginLeft=e.marginLeft?getMeasurement(e.marginLeft,"0pt"):"";this.marginRight=e.marginRight?getMeasurement(e.marginRight,"0pt"):"";this.orphans=getInteger({data:e.orphans,defaultValue:0,validate:e=>e>=0});this.preserve=e.preserve||"";this.radixOffset=e.radixOffset?getMeasurement(e.radixOffset,"0pt"):"";this.spaceAbove=e.spaceAbove?getMeasurement(e.spaceAbove,"0pt"):"";this.spaceBelow=e.spaceBelow?getMeasurement(e.spaceBelow,"0pt"):"";this.tabDefault=e.tabDefault?getMeasurement(this.tabDefault):"";this.tabStops=(e.tabStops||"").trim().split(/\s+/).map(((e,t)=>t%2==1?getMeasurement(e):e));this.textIndent=e.textIndent?getMeasurement(e.textIndent,"0pt"):"";this.use=e.use||"";this.usehref=e.usehref||"";this.vAlign=getStringOption(e.vAlign,["top","bottom","middle"]);this.widows=getInteger({data:e.widows,defaultValue:0,validate:e=>e>=0});this.hyphenation=null}[Zr](){const e=toStyle(this,"hAlign");""!==this.marginLeft&&(e.paddingLeft=measureToString(this.marginLeft));""!==this.marginRight&&(e.paddingRight=measureToString(this.marginRight));""!==this.spaceAbove&&(e.paddingTop=measureToString(this.spaceAbove));""!==this.spaceBelow&&(e.paddingBottom=measureToString(this.spaceBelow));if(""!==this.textIndent){e.textIndent=measureToString(this.textIndent);fixTextIndent(e)}this.lineHeight>0&&(e.lineHeight=measureToString(this.lineHeight));""!==this.tabDefault&&(e.tabSize=measureToString(this.tabDefault));this.tabStops.length;this.hyphenatation&&Object.assign(e,this.hyphenatation[Zr]());return e}}class PasswordEdit extends XFAObject{constructor(e){super(Nn,"passwordEdit",!0);this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.passwordChar=e.passwordChar||"*";this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}}class template_Pattern extends XFAObject{constructor(e){super(Nn,"pattern",!0);this.id=e.id||"";this.type=getStringOption(e.type,["crossHatch","crossDiagonal","diagonalLeft","diagonalRight","horizontal","vertical"]);this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zr](e){e=e?e[Zr]():"#FFFFFF";const t=this.color?this.color[Zr]():"#000000",i="repeating-linear-gradient",a=`${e},${e} 5px,${t} 5px,${t} 10px`;switch(this.type){case"crossHatch":return`${i}(to top,${a}) ${i}(to right,${a})`;case"crossDiagonal":return`${i}(45deg,${a}) ${i}(-45deg,${a})`;case"diagonalLeft":return`${i}(45deg,${a})`;case"diagonalRight":return`${i}(-45deg,${a})`;case"horizontal":return`${i}(to top,${a})`;case"vertical":return`${i}(to right,${a})`}return""}}class Picture extends StringObject{constructor(e){super(Nn,"picture");this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Proto extends XFAObject{constructor(e){super(Nn,"proto",!0);this.appearanceFilter=new XFAObjectArray;this.arc=new XFAObjectArray;this.area=new XFAObjectArray;this.assist=new XFAObjectArray;this.barcode=new XFAObjectArray;this.bindItems=new XFAObjectArray;this.bookend=new XFAObjectArray;this.boolean=new XFAObjectArray;this.border=new XFAObjectArray;this.break=new XFAObjectArray;this.breakAfter=new XFAObjectArray;this.breakBefore=new XFAObjectArray;this.button=new XFAObjectArray;this.calculate=new XFAObjectArray;this.caption=new XFAObjectArray;this.certificate=new XFAObjectArray;this.certificates=new XFAObjectArray;this.checkButton=new XFAObjectArray;this.choiceList=new XFAObjectArray;this.color=new XFAObjectArray;this.comb=new XFAObjectArray;this.connect=new XFAObjectArray;this.contentArea=new XFAObjectArray;this.corner=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.dateTimeEdit=new XFAObjectArray;this.decimal=new XFAObjectArray;this.defaultUi=new XFAObjectArray;this.desc=new XFAObjectArray;this.digestMethod=new XFAObjectArray;this.digestMethods=new XFAObjectArray;this.draw=new XFAObjectArray;this.edge=new XFAObjectArray;this.encoding=new XFAObjectArray;this.encodings=new XFAObjectArray;this.encrypt=new XFAObjectArray;this.encryptData=new XFAObjectArray;this.encryption=new XFAObjectArray;this.encryptionMethod=new XFAObjectArray;this.encryptionMethods=new XFAObjectArray;this.event=new XFAObjectArray;this.exData=new XFAObjectArray;this.exObject=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.execute=new XFAObjectArray;this.extras=new XFAObjectArray;this.field=new XFAObjectArray;this.fill=new XFAObjectArray;this.filter=new XFAObjectArray;this.float=new XFAObjectArray;this.font=new XFAObjectArray;this.format=new XFAObjectArray;this.handler=new XFAObjectArray;this.hyphenation=new XFAObjectArray;this.image=new XFAObjectArray;this.imageEdit=new XFAObjectArray;this.integer=new XFAObjectArray;this.issuers=new XFAObjectArray;this.items=new XFAObjectArray;this.keep=new XFAObjectArray;this.keyUsage=new XFAObjectArray;this.line=new XFAObjectArray;this.linear=new XFAObjectArray;this.lockDocument=new XFAObjectArray;this.manifest=new XFAObjectArray;this.margin=new XFAObjectArray;this.mdp=new XFAObjectArray;this.medium=new XFAObjectArray;this.message=new XFAObjectArray;this.numericEdit=new XFAObjectArray;this.occur=new XFAObjectArray;this.oid=new XFAObjectArray;this.oids=new XFAObjectArray;this.overflow=new XFAObjectArray;this.pageArea=new XFAObjectArray;this.pageSet=new XFAObjectArray;this.para=new XFAObjectArray;this.passwordEdit=new XFAObjectArray;this.pattern=new XFAObjectArray;this.picture=new XFAObjectArray;this.radial=new XFAObjectArray;this.reason=new XFAObjectArray;this.reasons=new XFAObjectArray;this.rectangle=new XFAObjectArray;this.ref=new XFAObjectArray;this.script=new XFAObjectArray;this.setProperty=new XFAObjectArray;this.signData=new XFAObjectArray;this.signature=new XFAObjectArray;this.signing=new XFAObjectArray;this.solid=new XFAObjectArray;this.speak=new XFAObjectArray;this.stipple=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray;this.subjectDN=new XFAObjectArray;this.subjectDNs=new XFAObjectArray;this.submit=new XFAObjectArray;this.text=new XFAObjectArray;this.textEdit=new XFAObjectArray;this.time=new XFAObjectArray;this.timeStamp=new XFAObjectArray;this.toolTip=new XFAObjectArray;this.traversal=new XFAObjectArray;this.traverse=new XFAObjectArray;this.ui=new XFAObjectArray;this.validate=new XFAObjectArray;this.value=new XFAObjectArray;this.variables=new XFAObjectArray}}class Radial extends XFAObject{constructor(e){super(Nn,"radial",!0);this.id=e.id||"";this.type=getStringOption(e.type,["toEdge","toCenter"]);this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zr](e){e=e?e[Zr]():"#FFFFFF";const t=this.color?this.color[Zr]():"#000000";return`radial-gradient(circle at center, ${"toEdge"===this.type?`${e},${t}`:`${t},${e}`})`}}class Reason extends StringObject{constructor(e){super(Nn,"reason");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Reasons extends XFAObject{constructor(e){super(Nn,"reasons",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.reason=new XFAObjectArray}}class Rectangle extends XFAObject{constructor(e){super(Nn,"rectangle",!0);this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.corner=new XFAObjectArray(4);this.edge=new XFAObjectArray(4);this.fill=null}[jr](){const e=this.edge.children.length?this.edge.children[0]:new Edge({}),t=e[Zr](),i=Object.create(null);"visible"===this.fill?.presence?Object.assign(i,this.fill[Zr]()):i.fill="transparent";i.strokeWidth=measureToString("visible"===e.presence?e.thickness:0);i.stroke=t.color;const a=(this.corner.children.length?this.corner.children[0]:new Corner({}))[Zr](),s={name:"svg",children:[{name:"rect",attributes:{xmlns:Gn,width:"100%",height:"100%",x:0,y:0,rx:a.radius,ry:a.radius,style:i}}],attributes:{xmlns:Gn,style:{overflow:"visible"},width:"100%",height:"100%"}};if(hasMargin(this[Ir]()[Ir]()))return HTMLResult.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[s]});s.attributes.style.position="absolute";return HTMLResult.success(s)}}class RefElement extends StringObject{constructor(e){super(Nn,"ref");this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Script extends StringObject{constructor(e){super(Nn,"script");this.binding=e.binding||"";this.contentType=e.contentType||"";this.id=e.id||"";this.name=e.name||"";this.runAt=getStringOption(e.runAt,["client","both","server"]);this.use=e.use||"";this.usehref=e.usehref||""}}class SetProperty extends XFAObject{constructor(e){super(Nn,"setProperty");this.connection=e.connection||"";this.ref=e.ref||"";this.target=e.target||""}}class SignData extends XFAObject{constructor(e){super(Nn,"signData",!0);this.id=e.id||"";this.operation=getStringOption(e.operation,["sign","clear","verify"]);this.ref=e.ref||"";this.target=e.target||"";this.use=e.use||"";this.usehref=e.usehref||"";this.filter=null;this.manifest=null}}class Signature extends XFAObject{constructor(e){super(Nn,"signature",!0);this.id=e.id||"";this.type=getStringOption(e.type,["PDF1.3","PDF1.6"]);this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.filter=null;this.manifest=null;this.margin=null}}class Signing extends XFAObject{constructor(e){super(Nn,"signing",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=new XFAObjectArray}}class Solid extends XFAObject{constructor(e){super(Nn,"solid",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[Zr](e){return e?e[Zr]():"#FFFFFF"}}class Speak extends StringObject{constructor(e){super(Nn,"speak");this.disable=getInteger({data:e.disable,defaultValue:0,validate:e=>1===e});this.id=e.id||"";this.priority=getStringOption(e.priority,["custom","caption","name","toolTip"]);this.rid=e.rid||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Stipple extends XFAObject{constructor(e){super(Nn,"stipple",!0);this.id=e.id||"";this.rate=getInteger({data:e.rate,defaultValue:50,validate:e=>e>=0&&e<=100});this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zr](e){const t=this.rate/100;return Util.makeHexColor(Math.round(e.value.r*(1-t)+this.value.r*t),Math.round(e.value.g*(1-t)+this.value.g*t),Math.round(e.value.b*(1-t)+this.value.b*t))}}class Subform extends XFAObject{constructor(e){super(Nn,"subform",!0);this.access=getStringOption(e.access,["open","nonInteractive","protected","readOnly"]);this.allowMacro=getInteger({data:e.allowMacro,defaultValue:0,validate:e=>1===e});this.anchorType=getStringOption(e.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.columnWidths=(e.columnWidths||"").trim().split(/\s+/).map((e=>"-1"===e?-1:getMeasurement(e)));this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.layout=getStringOption(e.layout,["position","lr-tb","rl-row","rl-tb","row","table","tb"]);this.locale=e.locale||"";this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.mergeMode=getStringOption(e.mergeMode,["consumeData","matchTemplate"]);this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.restoreState=getStringOption(e.restoreState,["manual","auto"]);this.scope=getStringOption(e.scope,["name","none"]);this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.bind=null;this.bookend=null;this.border=null;this.break=null;this.calculate=null;this.desc=null;this.extras=null;this.keep=null;this.margin=null;this.occur=null;this.overflow=null;this.pageSet=null;this.para=null;this.traversal=null;this.validate=null;this.variables=null;this.area=new XFAObjectArray;this.breakAfter=new XFAObjectArray;this.breakBefore=new XFAObjectArray;this.connect=new XFAObjectArray;this.draw=new XFAObjectArray;this.event=new XFAObjectArray;this.exObject=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.field=new XFAObjectArray;this.proto=new XFAObjectArray;this.setProperty=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray}[or](){const e=this[Ir]();return e instanceof SubformSet?e[or]():e}[dr](){return!0}[wr](){return this.layout.endsWith("-tb")&&0===this[Xs].attempt&&this[Xs].numberInLine>0||this[Ir]()[wr]()}*[nr](){yield*getContainedChildren(this)}[Vs](){return flushHTML(this)}[Ls](e,t){addHTML(this,e,t)}[$s](){return getAvailableSpace(this)}[yr](){const e=this[or]();if(!e[yr]())return!1;if(void 0!==this[Xs]._isSplittable)return this[Xs]._isSplittable;if("position"===this.layout||this.layout.includes("row")){this[Xs]._isSplittable=!1;return!1}if(this.keep&&"none"!==this.keep.intact){this[Xs]._isSplittable=!1;return!1}if(e.layout?.endsWith("-tb")&&0!==e[Xs].numberInLine)return!1;this[Xs]._isSplittable=!0;return!0}[jr](e){setTabIndex(this);if(this.break){if("auto"!==this.break.after||""!==this.break.afterTarget){const e=new BreakAfter({targetType:this.break.after,target:this.break.afterTarget,startNew:this.break.startNew.toString()});e[Cr]=this[Cr];this[Hs](e);this.breakAfter.push(e)}if("auto"!==this.break.before||""!==this.break.beforeTarget){const e=new BreakBefore({targetType:this.break.before,target:this.break.beforeTarget,startNew:this.break.startNew.toString()});e[Cr]=this[Cr];this[Hs](e);this.breakBefore.push(e)}if(""!==this.break.overflowTarget){const e=new Overflow({target:this.break.overflowTarget,leader:this.break.overflowLeader,trailer:this.break.overflowTrailer});e[Cr]=this[Cr];this[Hs](e);this.overflow.push(e)}this[Hr](this.break);this.break=null}if("hidden"===this.presence||"inactive"===this.presence)return HTMLResult.EMPTY;(this.breakBefore.children.length>1||this.breakAfter.children.length>1)&&warn("XFA - Several breakBefore or breakAfter in subforms: please file a bug.");if(this.breakBefore.children.length>=1){const e=this.breakBefore.children[0];if(handleBreak(e))return HTMLResult.breakNode(e)}if(this[Xs]?.afterBreakAfter)return HTMLResult.EMPTY;fixDimensions(this);const t=[],i={id:this[Vr],class:[]};setAccess(this,i.class);this[Xs]||(this[Xs]=Object.create(null));Object.assign(this[Xs],{children:t,line:null,attributes:i,attempt:0,numberInLine:0,availableSpace:{width:Math.min(this.w||1/0,e.width),height:Math.min(this.h||1/0,e.height)},width:0,height:0,prevHeight:0,currentWidth:0});const a=this[cr](),s=a[Xs].noLayoutFailure,r=this[yr]();r||setFirstUnsplittable(this);if(!checkDimensions(this,e))return HTMLResult.FAILURE;const n=new Set(["area","draw","exclGroup","field","subform","subformSet"]);if(this.layout.includes("row")){const e=this[or]().columnWidths;if(Array.isArray(e)&&e.length>0){this[Xs].columnWidths=e;this[Xs].currentColumn=0}}const g=toStyle(this,"anchorType","dimensions","position","presence","border","margin","hAlign"),o=["xfaSubform"],c=layoutClass(this);c&&o.push(c);i.style=g;i.class=o;this.name&&(i.xfaName=this.name);if(this.overflow){const t=this.overflow[ar]();if(t.addLeader){t.addLeader=!1;handleOverflow(this,t.leader,e)}}this[Lr]();const C="lr-tb"===this.layout||"rl-tb"===this.layout,h=C?2:1;for(;this[Xs].attempt=1){const e=this.breakAfter.children[0];if(handleBreak(e)){this[Xs].afterBreakAfter=p;return HTMLResult.breakNode(e)}}delete this[Xs];return p}}class SubformSet extends XFAObject{constructor(e){super(Nn,"subformSet",!0);this.id=e.id||"";this.name=e.name||"";this.relation=getStringOption(e.relation,["ordered","choice","unordered"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.bookend=null;this.break=null;this.desc=null;this.extras=null;this.occur=null;this.overflow=null;this.breakAfter=new XFAObjectArray;this.breakBefore=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray}*[nr](){yield*getContainedChildren(this)}[or](){let e=this[Ir]();for(;!(e instanceof Subform);)e=e[Ir]();return e}[dr](){return!0}}class SubjectDN extends ContentObject{constructor(e){super(Nn,"subjectDN");this.delimiter=e.delimiter||",";this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){this[Os]=new Map(this[Os].split(this.delimiter).map((e=>{(e=e.split("=",2))[0]=e[0].trim();return e})))}}class SubjectDNs extends XFAObject{constructor(e){super(Nn,"subjectDNs",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.subjectDN=new XFAObjectArray}}class Submit extends XFAObject{constructor(e){super(Nn,"submit",!0);this.embedPDF=getInteger({data:e.embedPDF,defaultValue:0,validate:e=>1===e});this.format=getStringOption(e.format,["xdp","formdata","pdf","urlencoded","xfd","xml"]);this.id=e.id||"";this.target=e.target||"";this.textEncoding=getKeyword({data:e.textEncoding?e.textEncoding.toLowerCase():"",defaultValue:"",validate:e=>["utf-8","big-five","fontspecific","gbk","gb-18030","gb-2312","ksc-5601","none","shift-jis","ucs-2","utf-16"].includes(e)||e.match(/iso-8859-\d{2}/)});this.use=e.use||"";this.usehref=e.usehref||"";this.xdpContent=e.xdpContent||"";this.encrypt=null;this.encryptData=new XFAObjectArray;this.signData=new XFAObjectArray}}class Template extends XFAObject{constructor(e){super(Nn,"template",!0);this.baseProfile=getStringOption(e.baseProfile,["full","interactiveForms"]);this.extras=null;this.subform=new XFAObjectArray}[Zs](){0===this.subform.children.length&&warn("XFA - No subforms in template node.");this.subform.children.length>=2&&warn("XFA - Several subforms in template node: please file a bug.");this[Or]=5e3}[yr](){return!0}[vr](e,t){return e.startsWith("#")?[this[lr].get(e.slice(1))]:searchNode(this,t,e,!0,!0)}*[Wr](){if(!this.subform.children.length)return HTMLResult.success({name:"div",children:[]});this[Xs]={overflowNode:null,firstUnsplittable:null,currentContentArea:null,currentPageArea:null,noLayoutFailure:!1,pageNumber:1,pagePosition:"first",oddOrEven:"odd",blankOrNotBlank:"nonBlank",paraStack:[]};const e=this.subform.children[0];e.pageSet[vs]();const t=e.pageSet.pageArea.children,i={name:"div",children:[]};let a=null,s=null,r=null;if(e.breakBefore.children.length>=1){s=e.breakBefore.children[0];r=s.target}else if(e.subform.children.length>=1&&e.subform.children[0].breakBefore.children.length>=1){s=e.subform.children[0].breakBefore.children[0];r=s.target}else if(e.break?.beforeTarget){s=e.break;r=s.beforeTarget}else if(e.subform.children.length>=1&&e.subform.children[0].break?.beforeTarget){s=e.subform.children[0].break;r=s.beforeTarget}if(s){const e=this[vr](r,s[Ir]());if(e instanceof PageArea){a=e;s[Xs]={}}}a||(a=t[0]);a[Xs]={numberOfUse:1};const n=a[Ir]();n[Xs]={numberOfUse:1,pageIndex:n.pageArea.children.indexOf(a),pageSetIndex:0};let g,o=null,c=null,C=!0,h=0,l=0;for(;;){if(C)h=0;else{i.children.pop();if(3==++h){warn("XFA - Something goes wrong: please file a bug.");return i}}g=null;this[Xs].currentPageArea=a;const t=a[jr]().html;i.children.push(t);if(o){this[Xs].noLayoutFailure=!0;t.children.push(o[jr](a[Xs].space).html);o=null}if(c){this[Xs].noLayoutFailure=!0;t.children.push(c[jr](a[Xs].space).html);c=null}const s=a.contentArea.children,r=t.children.filter((e=>e.attributes.class.includes("xfaContentarea")));C=!1;this[Xs].firstUnsplittable=null;this[Xs].noLayoutFailure=!1;const flush=t=>{const i=e[Vs]();if(i){C||=i.children?.length>0;r[t].children.push(i)}};for(let t=l,a=s.length;t0;r[t].children.push(h.html)}else!C&&i.children.length>1&&i.children.pop();return i}if(h.isBreak()){const e=h.breakNode;flush(t);if("auto"===e.targetType)continue;if(e.leader){o=this[vr](e.leader,e[Ir]());o=o?o[0]:null}if(e.trailer){c=this[vr](e.trailer,e[Ir]());c=c?c[0]:null}if("pageArea"===e.targetType){g=e[Xs].target;t=1/0}else if(e[Xs].target){g=e[Xs].target;l=e[Xs].index+1;t=1/0}else t=e[Xs].index}else if(this[Xs].overflowNode){const e=this[Xs].overflowNode;this[Xs].overflowNode=null;const i=e[ar](),a=i.target;i.addLeader=null!==i.leader;i.addTrailer=null!==i.trailer;flush(t);const r=t;t=1/0;if(a instanceof PageArea)g=a;else if(a instanceof ContentArea){const e=s.indexOf(a);if(-1!==e)e>r?t=e-1:l=e;else{g=a[Ir]();l=g.contentArea.children.indexOf(a)}}}else flush(t)}this[Xs].pageNumber+=1;g&&(g[br]()?g[Xs].numberOfUse+=1:g=null);a=g||a[gr]();yield null}}}class Text extends ContentObject{constructor(e){super(Nn,"text");this.id=e.id||"";this.maxChars=getInteger({data:e.maxChars,defaultValue:0,validate:e=>e>=0});this.name=e.name||"";this.rid=e.rid||"";this.use=e.use||"";this.usehref=e.usehref||""}[xs](){return!0}[Nr](e){if(e[Sr]===_r.xhtml.id){this[Os]=e;return!0}warn(`XFA - Invalid content in Text: ${e[kr]}.`);return!1}[Mr](e){this[Os]instanceof XFAObject||super[Mr](e)}[Zs](){"string"==typeof this[Os]&&(this[Os]=this[Os].replaceAll("\r\n","\n"))}[ar](){return"string"==typeof this[Os]?this[Os].split(/[\u2029\u2028\n]/).reduce(((e,t)=>{t&&e.push(t);return e}),[]).join("\n"):this[Os][Pr]()}[jr](e){if("string"==typeof this[Os]){const e=valueToHtml(this[Os]).html;if(this[Os].includes("\u2029")){e.name="div";e.children=[];this[Os].split("\u2029").map((e=>e.split(/[\u2028\n]/).reduce(((e,t)=>{e.push({name:"span",value:t},{name:"br"});return e}),[]))).forEach((t=>{e.children.push({name:"p",children:t})}))}else if(/[\u2028\n]/.test(this[Os])){e.name="div";e.children=[];this[Os].split(/[\u2028\n]/).forEach((t=>{e.children.push({name:"span",value:t},{name:"br"})}))}return HTMLResult.success(e)}return this[Os][jr](e)}}class TextEdit extends XFAObject{constructor(e){super(Nn,"textEdit",!0);this.allowRichText=getInteger({data:e.allowRichText,defaultValue:0,validate:e=>1===e});this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.multiLine=getInteger({data:e.multiLine,defaultValue:"",validate:e=>0===e||1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.vScrollPolicy=getStringOption(e.vScrollPolicy,["auto","off","on"]);this.border=null;this.comb=null;this.extras=null;this.margin=null}[jr](e){const t=toStyle(this,"border","font","margin");let i;const a=this[Ir]()[Ir]();""===this.multiLine&&(this.multiLine=a instanceof Draw?1:0);i=1===this.multiLine?{name:"textarea",attributes:{dataId:a[Ws]?.[Vr]||a[Vr],fieldId:a[Vr],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(a),"aria-required":!1}}:{name:"input",attributes:{type:"text",dataId:a[Ws]?.[Vr]||a[Vr],fieldId:a[Vr],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(a),"aria-required":!1}};if(isRequired(a)){i.attributes["aria-required"]=!0;i.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[i]})}}class Time extends StringObject{constructor(e){super(Nn,"time");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){const e=this[Os].trim();this[Os]=e?new Date(e):null}[jr](e){return valueToHtml(this[Os]?this[Os].toString():"")}}class TimeStamp extends XFAObject{constructor(e){super(Nn,"timeStamp");this.id=e.id||"";this.server=e.server||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class ToolTip extends StringObject{constructor(e){super(Nn,"toolTip");this.id=e.id||"";this.rid=e.rid||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Traversal extends XFAObject{constructor(e){super(Nn,"traversal",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.traverse=new XFAObjectArray}}class Traverse extends XFAObject{constructor(e){super(Nn,"traverse",!0);this.id=e.id||"";this.operation=getStringOption(e.operation,["next","back","down","first","left","right","up"]);this.ref=e.ref||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.script=null}get name(){return this.operation}[Dr](){return!1}}class Ui extends XFAObject{constructor(e){super(Nn,"ui",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.picture=null;this.barcode=null;this.button=null;this.checkButton=null;this.choiceList=null;this.dateTimeEdit=null;this.defaultUi=null;this.imageEdit=null;this.numericEdit=null;this.passwordEdit=null;this.signature=null;this.textEdit=null}[ar](){if(void 0===this[Xs]){for(const e of Object.getOwnPropertyNames(this)){if("extras"===e||"picture"===e)continue;const t=this[e];if(t instanceof XFAObject){this[Xs]=t;return t}}this[Xs]=null}return this[Xs]}[jr](e){const t=this[ar]();return t?t[jr](e):HTMLResult.EMPTY}}class Validate extends XFAObject{constructor(e){super(Nn,"validate",!0);this.formatTest=getStringOption(e.formatTest,["warning","disabled","error"]);this.id=e.id||"";this.nullTest=getStringOption(e.nullTest,["disabled","error","warning"]);this.scriptTest=getStringOption(e.scriptTest,["error","disabled","warning"]);this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.message=null;this.picture=null;this.script=null}}class Value extends XFAObject{constructor(e){super(Nn,"value",!0);this.id=e.id||"";this.override=getInteger({data:e.override,defaultValue:0,validate:e=>1===e});this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.arc=null;this.boolean=null;this.date=null;this.dateTime=null;this.decimal=null;this.exData=null;this.float=null;this.image=null;this.integer=null;this.line=null;this.rectangle=null;this.text=null;this.time=null}[qr](e){const t=this[Ir]();if(t instanceof Field&&t.ui?.imageEdit){if(!this.image){this.image=new Image({});this[Hs](this.image)}this.image[Os]=e[Os];return}const i=e[kr];if(null===this[i]){for(const e of Object.getOwnPropertyNames(this)){const t=this[e];if(t instanceof XFAObject){this[e]=null;this[Hr](t)}}this[e[kr]]=e;this[Hs](e)}else this[i][Os]=e[Os]}[Pr](){if(this.exData)return"string"==typeof this.exData[Os]?this.exData[Os].trim():this.exData[Os][Pr]().trim();for(const e of Object.getOwnPropertyNames(this)){if("image"===e)continue;const t=this[e];if(t instanceof XFAObject)return(t[Os]||"").toString().trim()}return null}[jr](e){for(const t of Object.getOwnPropertyNames(this)){const i=this[t];if(i instanceof XFAObject)return i[jr](e)}return HTMLResult.EMPTY}}class Variables extends XFAObject{constructor(e){super(Nn,"variables",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.manifest=new XFAObjectArray;this.script=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}[Dr](){return!0}}class TemplateNamespace{static[zr](e,t){if(TemplateNamespace.hasOwnProperty(e)){const i=TemplateNamespace[e](t);i[Tr](t);return i}}static appearanceFilter(e){return new AppearanceFilter(e)}static arc(e){return new Arc(e)}static area(e){return new Area(e)}static assist(e){return new Assist(e)}static barcode(e){return new Barcode(e)}static bind(e){return new Bind(e)}static bindItems(e){return new BindItems(e)}static bookend(e){return new Bookend(e)}static boolean(e){return new BooleanElement(e)}static border(e){return new Border(e)}static break(e){return new Break(e)}static breakAfter(e){return new BreakAfter(e)}static breakBefore(e){return new BreakBefore(e)}static button(e){return new Button(e)}static calculate(e){return new Calculate(e)}static caption(e){return new Caption(e)}static certificate(e){return new Certificate(e)}static certificates(e){return new Certificates(e)}static checkButton(e){return new CheckButton(e)}static choiceList(e){return new ChoiceList(e)}static color(e){return new Color(e)}static comb(e){return new Comb(e)}static connect(e){return new Connect(e)}static contentArea(e){return new ContentArea(e)}static corner(e){return new Corner(e)}static date(e){return new DateElement(e)}static dateTime(e){return new DateTime(e)}static dateTimeEdit(e){return new DateTimeEdit(e)}static decimal(e){return new Decimal(e)}static defaultUi(e){return new DefaultUi(e)}static desc(e){return new Desc(e)}static digestMethod(e){return new DigestMethod(e)}static digestMethods(e){return new DigestMethods(e)}static draw(e){return new Draw(e)}static edge(e){return new Edge(e)}static encoding(e){return new Encoding(e)}static encodings(e){return new Encodings(e)}static encrypt(e){return new Encrypt(e)}static encryptData(e){return new EncryptData(e)}static encryption(e){return new Encryption(e)}static encryptionMethod(e){return new EncryptionMethod(e)}static encryptionMethods(e){return new EncryptionMethods(e)}static event(e){return new Event(e)}static exData(e){return new ExData(e)}static exObject(e){return new ExObject(e)}static exclGroup(e){return new ExclGroup(e)}static execute(e){return new Execute(e)}static extras(e){return new Extras(e)}static field(e){return new Field(e)}static fill(e){return new Fill(e)}static filter(e){return new Filter(e)}static float(e){return new Float(e)}static font(e){return new template_Font(e)}static format(e){return new Format(e)}static handler(e){return new Handler(e)}static hyphenation(e){return new Hyphenation(e)}static image(e){return new Image(e)}static imageEdit(e){return new ImageEdit(e)}static integer(e){return new Integer(e)}static issuers(e){return new Issuers(e)}static items(e){return new Items(e)}static keep(e){return new Keep(e)}static keyUsage(e){return new KeyUsage(e)}static line(e){return new Line(e)}static linear(e){return new Linear(e)}static lockDocument(e){return new LockDocument(e)}static manifest(e){return new Manifest(e)}static margin(e){return new Margin(e)}static mdp(e){return new Mdp(e)}static medium(e){return new Medium(e)}static message(e){return new Message(e)}static numericEdit(e){return new NumericEdit(e)}static occur(e){return new Occur(e)}static oid(e){return new Oid(e)}static oids(e){return new Oids(e)}static overflow(e){return new Overflow(e)}static pageArea(e){return new PageArea(e)}static pageSet(e){return new PageSet(e)}static para(e){return new Para(e)}static passwordEdit(e){return new PasswordEdit(e)}static pattern(e){return new template_Pattern(e)}static picture(e){return new Picture(e)}static proto(e){return new Proto(e)}static radial(e){return new Radial(e)}static reason(e){return new Reason(e)}static reasons(e){return new Reasons(e)}static rectangle(e){return new Rectangle(e)}static ref(e){return new RefElement(e)}static script(e){return new Script(e)}static setProperty(e){return new SetProperty(e)}static signData(e){return new SignData(e)}static signature(e){return new Signature(e)}static signing(e){return new Signing(e)}static solid(e){return new Solid(e)}static speak(e){return new Speak(e)}static stipple(e){return new Stipple(e)}static subform(e){return new Subform(e)}static subformSet(e){return new SubformSet(e)}static subjectDN(e){return new SubjectDN(e)}static subjectDNs(e){return new SubjectDNs(e)}static submit(e){return new Submit(e)}static template(e){return new Template(e)}static text(e){return new Text(e)}static textEdit(e){return new TextEdit(e)}static time(e){return new Time(e)}static timeStamp(e){return new TimeStamp(e)}static toolTip(e){return new ToolTip(e)}static traversal(e){return new Traversal(e)}static traverse(e){return new Traverse(e)}static ui(e){return new Ui(e)}static validate(e){return new Validate(e)}static value(e){return new Value(e)}static variables(e){return new Variables(e)}}const Ln=_r.datasets.id;function createText(e){const t=new Text({});t[Os]=e;return t}class Binder{constructor(e){this.root=e;this.datasets=e.datasets;this.data=e.datasets?.data||new XmlObject(_r.datasets.id,"data");this.emptyMerge=0===this.data[rr]().length;this.root.form=this.form=e.template[Ts]()}_isConsumeData(){return!this.emptyMerge&&this._mergeMode}_isMatchTemplate(){return!this._isConsumeData()}bind(){this._bindElement(this.form,this.data);return this.form}getData(){return this.data}_bindValue(e,t,i){e[Ws]=t;if(e[hr]())if(t[fr]()){const i=t[ir]();e[qr](createText(i))}else if(e instanceof Field&&"multiSelect"===e.ui?.choiceList?.open){const i=t[rr]().map((e=>e[Os].trim())).join("\n");e[qr](createText(i))}else this._isConsumeData()&&warn("XFA - Nodes haven't the same type.");else!t[fr]()||this._isMatchTemplate()?this._bindElement(e,t):warn("XFA - Nodes haven't the same type.")}_findDataByNameToConsume(e,t,i,a){if(!e)return null;let s,r;for(let a=0;a<3;a++){s=i[sr](e,!1,!0);for(;;){r=s.next().value;if(!r)break;if(t===r[fr]())return r}if(i[Sr]===_r.datasets.id&&"data"===i[kr])break;i=i[Ir]()}if(!a)return null;s=this.data[sr](e,!0,!1);r=s.next().value;if(r)return r;s=this.data[zs](e,!0);r=s.next().value;return r?.[fr]()?r:null}_setProperties(e,t){if(e.hasOwnProperty("setProperty"))for(const{ref:i,target:a,connection:s}of e.setProperty.children){if(s)continue;if(!i)continue;const r=searchNode(this.root,t,i,!1,!1);if(!r){warn(`XFA - Invalid reference: ${i}.`);continue}const[n]=r;if(!n[pr](this.data)){warn("XFA - Invalid node: must be a data node.");continue}const g=searchNode(this.root,e,a,!1,!1);if(!g){warn(`XFA - Invalid target: ${a}.`);continue}const[o]=g;if(!o[pr](e)){warn("XFA - Invalid target: must be a property or subproperty.");continue}const c=o[Ir]();if(o instanceof SetProperty||c instanceof SetProperty){warn("XFA - Invalid target: cannot be a setProperty or one of its properties.");continue}if(o instanceof BindItems||c instanceof BindItems){warn("XFA - Invalid target: cannot be a bindItems or one of its properties.");continue}const C=n[Pr](),h=o[kr];if(o instanceof XFAAttribute){const e=Object.create(null);e[h]=C;const t=Reflect.construct(Object.getPrototypeOf(c).constructor,[e]);c[h]=t[h]}else if(o.hasOwnProperty(Os)){o[Ws]=n;o[Os]=C;o[Zs]()}else warn("XFA - Invalid node to use in setProperty")}}_bindItems(e,t){if(!e.hasOwnProperty("items")||!e.hasOwnProperty("bindItems")||e.bindItems.isEmpty())return;for(const t of e.items.children)e[Hr](t);e.items.clear();const i=new Items({}),a=new Items({});e[Hs](i);e.items.push(i);e[Hs](a);e.items.push(a);for(const{ref:s,labelRef:r,valueRef:n,connection:g}of e.bindItems.children){if(g)continue;if(!s)continue;const e=searchNode(this.root,t,s,!1,!1);if(e)for(const t of e){if(!t[pr](this.datasets)){warn(`XFA - Invalid ref (${s}): must be a datasets child.`);continue}const e=searchNode(this.root,t,r,!0,!1);if(!e){warn(`XFA - Invalid label: ${r}.`);continue}const[g]=e;if(!g[pr](this.datasets)){warn("XFA - Invalid label: must be a datasets child.");continue}const o=searchNode(this.root,t,n,!0,!1);if(!o){warn(`XFA - Invalid value: ${n}.`);continue}const[c]=o;if(!c[pr](this.datasets)){warn("XFA - Invalid value: must be a datasets child.");continue}const C=createText(g[Pr]()),h=createText(c[Pr]());i[Hs](C);i.text.push(C);a[Hs](h);a.text.push(h)}else warn(`XFA - Invalid reference: ${s}.`)}}_bindOccurrences(e,t,i){let a;if(t.length>1){a=e[Ts]();a[Hr](a.occur);a.occur=null}this._bindValue(e,t[0],i);this._setProperties(e,t[0]);this._bindItems(e,t[0]);if(1===t.length)return;const s=e[Ir](),r=e[kr],n=s[Qr](e);for(let e=1,g=t.length;et.name===e.name)).length:i[a].children.length;const r=i[Qr](e)+1,n=t.initial-s;if(n){const t=e[Ts]();t[Hr](t.occur);t.occur=null;i[a].push(t);i[Er](r,t);for(let e=1;e0)this._bindOccurrences(a,[e[0]],null);else if(this.emptyMerge){const e=t[Sr]===Ln?-1:t[Sr],i=a[Ws]=new XmlObject(e,a.name||"root");t[Hs](i);this._bindElement(a,i)}continue}if(!a[dr]())continue;let e=!1,s=null,r=null,n=null;if(a.bind){switch(a.bind.match){case"none":this._setAndBind(a,t);continue;case"global":e=!0;break;case"dataRef":if(!a.bind.ref){warn(`XFA - ref is empty in node ${a[kr]}.`);this._setAndBind(a,t);continue}r=a.bind.ref}a.bind.picture&&(s=a.bind.picture[Os])}const[g,o]=this._getOccurInfo(a);if(r){n=searchNode(this.root,t,r,!0,!1);if(null===n){n=createDataNode(this.data,t,r);if(!n)continue;this._isConsumeData()&&(n[qs]=!0);this._setAndBind(a,n);continue}this._isConsumeData()&&(n=n.filter((e=>!e[qs])));n.length>o?n=n.slice(0,o):0===n.length&&(n=null);n&&this._isConsumeData()&&n.forEach((e=>{e[qs]=!0}))}else{if(!a.name){this._setAndBind(a,t);continue}if(this._isConsumeData()){const i=[];for(;i.length0?i:null}else{n=t[sr](a.name,!1,this.emptyMerge).next().value;if(!n){if(0===g){i.push(a);continue}const e=t[Sr]===Ln?-1:t[Sr];n=a[Ws]=new XmlObject(e,a.name);this.emptyMerge&&(n[qs]=!0);t[Hs](n);this._setAndBind(a,n);continue}this.emptyMerge&&(n[qs]=!0);n=[n]}}n?this._bindOccurrences(a,n,s):g>0?this._setAndBind(a,t):i.push(a)}i.forEach((e=>e[Ir]()[Hr](e)))}}class DataHandler{constructor(e,t){this.data=t;this.dataset=e.datasets||null}serialize(e){const t=[[-1,this.data[rr]()]];for(;t.length>0;){const i=t.at(-1),[a,s]=i;if(a+1===s.length){t.pop();continue}const r=s[++i[0]],n=e.get(r[Vr]);if(n)r[qr](n);else{const t=r[_s]();for(const i of t.values()){const t=e.get(i[Vr]);if(t){i[qr](t);break}}}const g=r[rr]();g.length>0&&t.push([-1,g])}const i=[''];if(this.dataset)for(const e of this.dataset[rr]())"data"!==e[kr]&&e[Xr](i);this.data[Xr](i);i.push("");return i.join("")}}const Hn=_r.config.id;class Acrobat extends XFAObject{constructor(e){super(Hn,"acrobat",!0);this.acrobat7=null;this.autoSave=null;this.common=null;this.validate=null;this.validateApprovalSignatures=null;this.submitUrl=new XFAObjectArray}}class Acrobat7 extends XFAObject{constructor(e){super(Hn,"acrobat7",!0);this.dynamicRender=null}}class ADBE_JSConsole extends OptionObject{constructor(e){super(Hn,"ADBE_JSConsole",["delegate","Enable","Disable"])}}class ADBE_JSDebugger extends OptionObject{constructor(e){super(Hn,"ADBE_JSDebugger",["delegate","Enable","Disable"])}}class AddSilentPrint extends Option01{constructor(e){super(Hn,"addSilentPrint")}}class AddViewerPreferences extends Option01{constructor(e){super(Hn,"addViewerPreferences")}}class AdjustData extends Option10{constructor(e){super(Hn,"adjustData")}}class AdobeExtensionLevel extends IntegerObject{constructor(e){super(Hn,"adobeExtensionLevel",0,(e=>e>=1&&e<=8))}}class Agent extends XFAObject{constructor(e){super(Hn,"agent",!0);this.name=e.name?e.name.trim():"";this.common=new XFAObjectArray}}class AlwaysEmbed extends ContentObject{constructor(e){super(Hn,"alwaysEmbed")}}class Amd extends StringObject{constructor(e){super(Hn,"amd")}}class config_Area extends XFAObject{constructor(e){super(Hn,"area");this.level=getInteger({data:e.level,defaultValue:0,validate:e=>e>=1&&e<=3});this.name=getStringOption(e.name,["","barcode","coreinit","deviceDriver","font","general","layout","merge","script","signature","sourceSet","templateCache"])}}class Attributes extends OptionObject{constructor(e){super(Hn,"attributes",["preserve","delegate","ignore"])}}class AutoSave extends OptionObject{constructor(e){super(Hn,"autoSave",["disabled","enabled"])}}class Base extends StringObject{constructor(e){super(Hn,"base")}}class BatchOutput extends XFAObject{constructor(e){super(Hn,"batchOutput");this.format=getStringOption(e.format,["none","concat","zip","zipCompress"])}}class BehaviorOverride extends ContentObject{constructor(e){super(Hn,"behaviorOverride")}[Zs](){this[Os]=new Map(this[Os].trim().split(/\s+/).filter((e=>e.includes(":"))).map((e=>e.split(":",2))))}}class Cache extends XFAObject{constructor(e){super(Hn,"cache",!0);this.templateCache=null}}class Change extends Option01{constructor(e){super(Hn,"change")}}class Common extends XFAObject{constructor(e){super(Hn,"common",!0);this.data=null;this.locale=null;this.localeSet=null;this.messaging=null;this.suppressBanner=null;this.template=null;this.validationMessaging=null;this.versionControl=null;this.log=new XFAObjectArray}}class Compress extends XFAObject{constructor(e){super(Hn,"compress");this.scope=getStringOption(e.scope,["imageOnly","document"])}}class CompressLogicalStructure extends Option01{constructor(e){super(Hn,"compressLogicalStructure")}}class CompressObjectStream extends Option10{constructor(e){super(Hn,"compressObjectStream")}}class Compression extends XFAObject{constructor(e){super(Hn,"compression",!0);this.compressLogicalStructure=null;this.compressObjectStream=null;this.level=null;this.type=null}}class Config extends XFAObject{constructor(e){super(Hn,"config",!0);this.acrobat=null;this.present=null;this.trace=null;this.agent=new XFAObjectArray}}class Conformance extends OptionObject{constructor(e){super(Hn,"conformance",["A","B"])}}class ContentCopy extends Option01{constructor(e){super(Hn,"contentCopy")}}class Copies extends IntegerObject{constructor(e){super(Hn,"copies",1,(e=>e>=1))}}class Creator extends StringObject{constructor(e){super(Hn,"creator")}}class CurrentPage extends IntegerObject{constructor(e){super(Hn,"currentPage",0,(e=>e>=0))}}class Data extends XFAObject{constructor(e){super(Hn,"data",!0);this.adjustData=null;this.attributes=null;this.incrementalLoad=null;this.outputXSL=null;this.range=null;this.record=null;this.startNode=null;this.uri=null;this.window=null;this.xsl=null;this.excludeNS=new XFAObjectArray;this.transform=new XFAObjectArray}}class Debug extends XFAObject{constructor(e){super(Hn,"debug",!0);this.uri=null}}class DefaultTypeface extends ContentObject{constructor(e){super(Hn,"defaultTypeface");this.writingScript=getStringOption(e.writingScript,["*","Arabic","Cyrillic","EastEuropeanRoman","Greek","Hebrew","Japanese","Korean","Roman","SimplifiedChinese","Thai","TraditionalChinese","Vietnamese"])}}class Destination extends OptionObject{constructor(e){super(Hn,"destination",["pdf","pcl","ps","webClient","zpl"])}}class DocumentAssembly extends Option01{constructor(e){super(Hn,"documentAssembly")}}class Driver extends XFAObject{constructor(e){super(Hn,"driver",!0);this.name=e.name?e.name.trim():"";this.fontInfo=null;this.xdc=null}}class DuplexOption extends OptionObject{constructor(e){super(Hn,"duplexOption",["simplex","duplexFlipLongEdge","duplexFlipShortEdge"])}}class DynamicRender extends OptionObject{constructor(e){super(Hn,"dynamicRender",["forbidden","required"])}}class Embed extends Option01{constructor(e){super(Hn,"embed")}}class config_Encrypt extends Option01{constructor(e){super(Hn,"encrypt")}}class config_Encryption extends XFAObject{constructor(e){super(Hn,"encryption",!0);this.encrypt=null;this.encryptionLevel=null;this.permissions=null}}class EncryptionLevel extends OptionObject{constructor(e){super(Hn,"encryptionLevel",["40bit","128bit"])}}class Enforce extends StringObject{constructor(e){super(Hn,"enforce")}}class Equate extends XFAObject{constructor(e){super(Hn,"equate");this.force=getInteger({data:e.force,defaultValue:1,validate:e=>0===e});this.from=e.from||"";this.to=e.to||""}}class EquateRange extends XFAObject{constructor(e){super(Hn,"equateRange");this.from=e.from||"";this.to=e.to||"";this._unicodeRange=e.unicodeRange||""}get unicodeRange(){const e=[],t=/U\+([0-9a-fA-F]+)/,i=this._unicodeRange;for(let a of i.split(",").map((e=>e.trim())).filter((e=>!!e))){a=a.split("-",2).map((e=>{const i=e.match(t);return i?parseInt(i[1],16):0}));1===a.length&&a.push(a[0]);e.push(a)}return shadow(this,"unicodeRange",e)}}class Exclude extends ContentObject{constructor(e){super(Hn,"exclude")}[Zs](){this[Os]=this[Os].trim().split(/\s+/).filter((e=>e&&["calculate","close","enter","exit","initialize","ready","validate"].includes(e)))}}class ExcludeNS extends StringObject{constructor(e){super(Hn,"excludeNS")}}class FlipLabel extends OptionObject{constructor(e){super(Hn,"flipLabel",["usePrinterSetting","on","off"])}}class config_FontInfo extends XFAObject{constructor(e){super(Hn,"fontInfo",!0);this.embed=null;this.map=null;this.subsetBelow=null;this.alwaysEmbed=new XFAObjectArray;this.defaultTypeface=new XFAObjectArray;this.neverEmbed=new XFAObjectArray}}class FormFieldFilling extends Option01{constructor(e){super(Hn,"formFieldFilling")}}class GroupParent extends StringObject{constructor(e){super(Hn,"groupParent")}}class IfEmpty extends OptionObject{constructor(e){super(Hn,"ifEmpty",["dataValue","dataGroup","ignore","remove"])}}class IncludeXDPContent extends StringObject{constructor(e){super(Hn,"includeXDPContent")}}class IncrementalLoad extends OptionObject{constructor(e){super(Hn,"incrementalLoad",["none","forwardOnly"])}}class IncrementalMerge extends Option01{constructor(e){super(Hn,"incrementalMerge")}}class Interactive extends Option01{constructor(e){super(Hn,"interactive")}}class Jog extends OptionObject{constructor(e){super(Hn,"jog",["usePrinterSetting","none","pageSet"])}}class LabelPrinter extends XFAObject{constructor(e){super(Hn,"labelPrinter",!0);this.name=getStringOption(e.name,["zpl","dpl","ipl","tcpl"]);this.batchOutput=null;this.flipLabel=null;this.fontInfo=null;this.xdc=null}}class Layout extends OptionObject{constructor(e){super(Hn,"layout",["paginate","panel"])}}class Level extends IntegerObject{constructor(e){super(Hn,"level",0,(e=>e>0))}}class Linearized extends Option01{constructor(e){super(Hn,"linearized")}}class Locale extends StringObject{constructor(e){super(Hn,"locale")}}class LocaleSet extends StringObject{constructor(e){super(Hn,"localeSet")}}class Log extends XFAObject{constructor(e){super(Hn,"log",!0);this.mode=null;this.threshold=null;this.to=null;this.uri=null}}class MapElement extends XFAObject{constructor(e){super(Hn,"map",!0);this.equate=new XFAObjectArray;this.equateRange=new XFAObjectArray}}class MediumInfo extends XFAObject{constructor(e){super(Hn,"mediumInfo",!0);this.map=null}}class config_Message extends XFAObject{constructor(e){super(Hn,"message",!0);this.msgId=null;this.severity=null}}class Messaging extends XFAObject{constructor(e){super(Hn,"messaging",!0);this.message=new XFAObjectArray}}class Mode extends OptionObject{constructor(e){super(Hn,"mode",["append","overwrite"])}}class ModifyAnnots extends Option01{constructor(e){super(Hn,"modifyAnnots")}}class MsgId extends IntegerObject{constructor(e){super(Hn,"msgId",1,(e=>e>=1))}}class NameAttr extends StringObject{constructor(e){super(Hn,"nameAttr")}}class NeverEmbed extends ContentObject{constructor(e){super(Hn,"neverEmbed")}}class NumberOfCopies extends IntegerObject{constructor(e){super(Hn,"numberOfCopies",null,(e=>e>=2&&e<=5))}}class OpenAction extends XFAObject{constructor(e){super(Hn,"openAction",!0);this.destination=null}}class Output extends XFAObject{constructor(e){super(Hn,"output",!0);this.to=null;this.type=null;this.uri=null}}class OutputBin extends StringObject{constructor(e){super(Hn,"outputBin")}}class OutputXSL extends XFAObject{constructor(e){super(Hn,"outputXSL",!0);this.uri=null}}class Overprint extends OptionObject{constructor(e){super(Hn,"overprint",["none","both","draw","field"])}}class Packets extends StringObject{constructor(e){super(Hn,"packets")}[Zs](){"*"!==this[Os]&&(this[Os]=this[Os].trim().split(/\s+/).filter((e=>["config","datasets","template","xfdf","xslt"].includes(e))))}}class PageOffset extends XFAObject{constructor(e){super(Hn,"pageOffset");this.x=getInteger({data:e.x,defaultValue:"useXDCSetting",validate:e=>!0});this.y=getInteger({data:e.y,defaultValue:"useXDCSetting",validate:e=>!0})}}class PageRange extends StringObject{constructor(e){super(Hn,"pageRange")}[Zs](){const e=this[Os].trim().split(/\s+/).map((e=>parseInt(e,10))),t=[];for(let i=0,a=e.length;i!1))}}class Pcl extends XFAObject{constructor(e){super(Hn,"pcl",!0);this.name=e.name||"";this.batchOutput=null;this.fontInfo=null;this.jog=null;this.mediumInfo=null;this.outputBin=null;this.pageOffset=null;this.staple=null;this.xdc=null}}class Pdf extends XFAObject{constructor(e){super(Hn,"pdf",!0);this.name=e.name||"";this.adobeExtensionLevel=null;this.batchOutput=null;this.compression=null;this.creator=null;this.encryption=null;this.fontInfo=null;this.interactive=null;this.linearized=null;this.openAction=null;this.pdfa=null;this.producer=null;this.renderPolicy=null;this.scriptModel=null;this.silentPrint=null;this.submitFormat=null;this.tagged=null;this.version=null;this.viewerPreferences=null;this.xdc=null}}class Pdfa extends XFAObject{constructor(e){super(Hn,"pdfa",!0);this.amd=null;this.conformance=null;this.includeXDPContent=null;this.part=null}}class Permissions extends XFAObject{constructor(e){super(Hn,"permissions",!0);this.accessibleContent=null;this.change=null;this.contentCopy=null;this.documentAssembly=null;this.formFieldFilling=null;this.modifyAnnots=null;this.plaintextMetadata=null;this.print=null;this.printHighQuality=null}}class PickTrayByPDFSize extends Option01{constructor(e){super(Hn,"pickTrayByPDFSize")}}class config_Picture extends StringObject{constructor(e){super(Hn,"picture")}}class PlaintextMetadata extends Option01{constructor(e){super(Hn,"plaintextMetadata")}}class Presence extends OptionObject{constructor(e){super(Hn,"presence",["preserve","dissolve","dissolveStructure","ignore","remove"])}}class Present extends XFAObject{constructor(e){super(Hn,"present",!0);this.behaviorOverride=null;this.cache=null;this.common=null;this.copies=null;this.destination=null;this.incrementalMerge=null;this.layout=null;this.output=null;this.overprint=null;this.pagination=null;this.paginationOverride=null;this.script=null;this.validate=null;this.xdp=null;this.driver=new XFAObjectArray;this.labelPrinter=new XFAObjectArray;this.pcl=new XFAObjectArray;this.pdf=new XFAObjectArray;this.ps=new XFAObjectArray;this.submitUrl=new XFAObjectArray;this.webClient=new XFAObjectArray;this.zpl=new XFAObjectArray}}class Print extends Option01{constructor(e){super(Hn,"print")}}class PrintHighQuality extends Option01{constructor(e){super(Hn,"printHighQuality")}}class PrintScaling extends OptionObject{constructor(e){super(Hn,"printScaling",["appdefault","noScaling"])}}class PrinterName extends StringObject{constructor(e){super(Hn,"printerName")}}class Producer extends StringObject{constructor(e){super(Hn,"producer")}}class Ps extends XFAObject{constructor(e){super(Hn,"ps",!0);this.name=e.name||"";this.batchOutput=null;this.fontInfo=null;this.jog=null;this.mediumInfo=null;this.outputBin=null;this.staple=null;this.xdc=null}}class Range extends ContentObject{constructor(e){super(Hn,"range")}[Zs](){this[Os]=this[Os].trim().split(/\s*,\s*/,2).map((e=>e.split("-").map((e=>parseInt(e.trim(),10))))).filter((e=>e.every((e=>!isNaN(e))))).map((e=>{1===e.length&&e.push(e[0]);return e}))}}class Record extends ContentObject{constructor(e){super(Hn,"record")}[Zs](){this[Os]=this[Os].trim();const e=parseInt(this[Os],10);!isNaN(e)&&e>=0&&(this[Os]=e)}}class Relevant extends ContentObject{constructor(e){super(Hn,"relevant")}[Zs](){this[Os]=this[Os].trim().split(/\s+/)}}class Rename extends ContentObject{constructor(e){super(Hn,"rename")}[Zs](){this[Os]=this[Os].trim();(this[Os].toLowerCase().startsWith("xml")||new RegExp("[\\p{L}_][\\p{L}\\d._\\p{M}-]*","u").test(this[Os]))&&warn("XFA - Rename: invalid XFA name")}}class RenderPolicy extends OptionObject{constructor(e){super(Hn,"renderPolicy",["server","client"])}}class RunScripts extends OptionObject{constructor(e){super(Hn,"runScripts",["both","client","none","server"])}}class config_Script extends XFAObject{constructor(e){super(Hn,"script",!0);this.currentPage=null;this.exclude=null;this.runScripts=null}}class ScriptModel extends OptionObject{constructor(e){super(Hn,"scriptModel",["XFA","none"])}}class Severity extends OptionObject{constructor(e){super(Hn,"severity",["ignore","error","information","trace","warning"])}}class SilentPrint extends XFAObject{constructor(e){super(Hn,"silentPrint",!0);this.addSilentPrint=null;this.printerName=null}}class Staple extends XFAObject{constructor(e){super(Hn,"staple");this.mode=getStringOption(e.mode,["usePrinterSetting","on","off"])}}class StartNode extends StringObject{constructor(e){super(Hn,"startNode")}}class StartPage extends IntegerObject{constructor(e){super(Hn,"startPage",0,(e=>!0))}}class SubmitFormat extends OptionObject{constructor(e){super(Hn,"submitFormat",["html","delegate","fdf","xml","pdf"])}}class SubmitUrl extends StringObject{constructor(e){super(Hn,"submitUrl")}}class SubsetBelow extends IntegerObject{constructor(e){super(Hn,"subsetBelow",100,(e=>e>=0&&e<=100))}}class SuppressBanner extends Option01{constructor(e){super(Hn,"suppressBanner")}}class Tagged extends Option01{constructor(e){super(Hn,"tagged")}}class config_Template extends XFAObject{constructor(e){super(Hn,"template",!0);this.base=null;this.relevant=null;this.startPage=null;this.uri=null;this.xsl=null}}class Threshold extends OptionObject{constructor(e){super(Hn,"threshold",["trace","error","information","warning"])}}class To extends OptionObject{constructor(e){super(Hn,"to",["null","memory","stderr","stdout","system","uri"])}}class TemplateCache extends XFAObject{constructor(e){super(Hn,"templateCache");this.maxEntries=getInteger({data:e.maxEntries,defaultValue:5,validate:e=>e>=0})}}class Trace extends XFAObject{constructor(e){super(Hn,"trace",!0);this.area=new XFAObjectArray}}class Transform extends XFAObject{constructor(e){super(Hn,"transform",!0);this.groupParent=null;this.ifEmpty=null;this.nameAttr=null;this.picture=null;this.presence=null;this.rename=null;this.whitespace=null}}class Type extends OptionObject{constructor(e){super(Hn,"type",["none","ascii85","asciiHex","ccittfax","flate","lzw","runLength","native","xdp","mergedXDP"])}}class Uri extends StringObject{constructor(e){super(Hn,"uri")}}class config_Validate extends OptionObject{constructor(e){super(Hn,"validate",["preSubmit","prePrint","preExecute","preSave"])}}class ValidateApprovalSignatures extends ContentObject{constructor(e){super(Hn,"validateApprovalSignatures")}[Zs](){this[Os]=this[Os].trim().split(/\s+/).filter((e=>["docReady","postSign"].includes(e)))}}class ValidationMessaging extends OptionObject{constructor(e){super(Hn,"validationMessaging",["allMessagesIndividually","allMessagesTogether","firstMessageOnly","noMessages"])}}class Version extends OptionObject{constructor(e){super(Hn,"version",["1.7","1.6","1.5","1.4","1.3","1.2"])}}class VersionControl extends XFAObject{constructor(e){super(Hn,"VersionControl");this.outputBelow=getStringOption(e.outputBelow,["warn","error","update"]);this.sourceAbove=getStringOption(e.sourceAbove,["warn","error"]);this.sourceBelow=getStringOption(e.sourceBelow,["update","maintain"])}}class ViewerPreferences extends XFAObject{constructor(e){super(Hn,"viewerPreferences",!0);this.ADBE_JSConsole=null;this.ADBE_JSDebugger=null;this.addViewerPreferences=null;this.duplexOption=null;this.enforce=null;this.numberOfCopies=null;this.pageRange=null;this.pickTrayByPDFSize=null;this.printScaling=null}}class WebClient extends XFAObject{constructor(e){super(Hn,"webClient",!0);this.name=e.name?e.name.trim():"";this.fontInfo=null;this.xdc=null}}class Whitespace extends OptionObject{constructor(e){super(Hn,"whitespace",["preserve","ltrim","normalize","rtrim","trim"])}}class Window extends ContentObject{constructor(e){super(Hn,"window")}[Zs](){const e=this[Os].trim().split(/\s*,\s*/,2).map((e=>parseInt(e,10)));if(e.some((e=>isNaN(e))))this[Os]=[0,0];else{1===e.length&&e.push(e[0]);this[Os]=e}}}class Xdc extends XFAObject{constructor(e){super(Hn,"xdc",!0);this.uri=new XFAObjectArray;this.xsl=new XFAObjectArray}}class Xdp extends XFAObject{constructor(e){super(Hn,"xdp",!0);this.packets=null}}class Xsl extends XFAObject{constructor(e){super(Hn,"xsl",!0);this.debug=null;this.uri=null}}class Zpl extends XFAObject{constructor(e){super(Hn,"zpl",!0);this.name=e.name?e.name.trim():"";this.batchOutput=null;this.flipLabel=null;this.fontInfo=null;this.xdc=null}}class ConfigNamespace{static[zr](e,t){if(ConfigNamespace.hasOwnProperty(e))return ConfigNamespace[e](t)}static acrobat(e){return new Acrobat(e)}static acrobat7(e){return new Acrobat7(e)}static ADBE_JSConsole(e){return new ADBE_JSConsole(e)}static ADBE_JSDebugger(e){return new ADBE_JSDebugger(e)}static addSilentPrint(e){return new AddSilentPrint(e)}static addViewerPreferences(e){return new AddViewerPreferences(e)}static adjustData(e){return new AdjustData(e)}static adobeExtensionLevel(e){return new AdobeExtensionLevel(e)}static agent(e){return new Agent(e)}static alwaysEmbed(e){return new AlwaysEmbed(e)}static amd(e){return new Amd(e)}static area(e){return new config_Area(e)}static attributes(e){return new Attributes(e)}static autoSave(e){return new AutoSave(e)}static base(e){return new Base(e)}static batchOutput(e){return new BatchOutput(e)}static behaviorOverride(e){return new BehaviorOverride(e)}static cache(e){return new Cache(e)}static change(e){return new Change(e)}static common(e){return new Common(e)}static compress(e){return new Compress(e)}static compressLogicalStructure(e){return new CompressLogicalStructure(e)}static compressObjectStream(e){return new CompressObjectStream(e)}static compression(e){return new Compression(e)}static config(e){return new Config(e)}static conformance(e){return new Conformance(e)}static contentCopy(e){return new ContentCopy(e)}static copies(e){return new Copies(e)}static creator(e){return new Creator(e)}static currentPage(e){return new CurrentPage(e)}static data(e){return new Data(e)}static debug(e){return new Debug(e)}static defaultTypeface(e){return new DefaultTypeface(e)}static destination(e){return new Destination(e)}static documentAssembly(e){return new DocumentAssembly(e)}static driver(e){return new Driver(e)}static duplexOption(e){return new DuplexOption(e)}static dynamicRender(e){return new DynamicRender(e)}static embed(e){return new Embed(e)}static encrypt(e){return new config_Encrypt(e)}static encryption(e){return new config_Encryption(e)}static encryptionLevel(e){return new EncryptionLevel(e)}static enforce(e){return new Enforce(e)}static equate(e){return new Equate(e)}static equateRange(e){return new EquateRange(e)}static exclude(e){return new Exclude(e)}static excludeNS(e){return new ExcludeNS(e)}static flipLabel(e){return new FlipLabel(e)}static fontInfo(e){return new config_FontInfo(e)}static formFieldFilling(e){return new FormFieldFilling(e)}static groupParent(e){return new GroupParent(e)}static ifEmpty(e){return new IfEmpty(e)}static includeXDPContent(e){return new IncludeXDPContent(e)}static incrementalLoad(e){return new IncrementalLoad(e)}static incrementalMerge(e){return new IncrementalMerge(e)}static interactive(e){return new Interactive(e)}static jog(e){return new Jog(e)}static labelPrinter(e){return new LabelPrinter(e)}static layout(e){return new Layout(e)}static level(e){return new Level(e)}static linearized(e){return new Linearized(e)}static locale(e){return new Locale(e)}static localeSet(e){return new LocaleSet(e)}static log(e){return new Log(e)}static map(e){return new MapElement(e)}static mediumInfo(e){return new MediumInfo(e)}static message(e){return new config_Message(e)}static messaging(e){return new Messaging(e)}static mode(e){return new Mode(e)}static modifyAnnots(e){return new ModifyAnnots(e)}static msgId(e){return new MsgId(e)}static nameAttr(e){return new NameAttr(e)}static neverEmbed(e){return new NeverEmbed(e)}static numberOfCopies(e){return new NumberOfCopies(e)}static openAction(e){return new OpenAction(e)}static output(e){return new Output(e)}static outputBin(e){return new OutputBin(e)}static outputXSL(e){return new OutputXSL(e)}static overprint(e){return new Overprint(e)}static packets(e){return new Packets(e)}static pageOffset(e){return new PageOffset(e)}static pageRange(e){return new PageRange(e)}static pagination(e){return new Pagination(e)}static paginationOverride(e){return new PaginationOverride(e)}static part(e){return new Part(e)}static pcl(e){return new Pcl(e)}static pdf(e){return new Pdf(e)}static pdfa(e){return new Pdfa(e)}static permissions(e){return new Permissions(e)}static pickTrayByPDFSize(e){return new PickTrayByPDFSize(e)}static picture(e){return new config_Picture(e)}static plaintextMetadata(e){return new PlaintextMetadata(e)}static presence(e){return new Presence(e)}static present(e){return new Present(e)}static print(e){return new Print(e)}static printHighQuality(e){return new PrintHighQuality(e)}static printScaling(e){return new PrintScaling(e)}static printerName(e){return new PrinterName(e)}static producer(e){return new Producer(e)}static ps(e){return new Ps(e)}static range(e){return new Range(e)}static record(e){return new Record(e)}static relevant(e){return new Relevant(e)}static rename(e){return new Rename(e)}static renderPolicy(e){return new RenderPolicy(e)}static runScripts(e){return new RunScripts(e)}static script(e){return new config_Script(e)}static scriptModel(e){return new ScriptModel(e)}static severity(e){return new Severity(e)}static silentPrint(e){return new SilentPrint(e)}static staple(e){return new Staple(e)}static startNode(e){return new StartNode(e)}static startPage(e){return new StartPage(e)}static submitFormat(e){return new SubmitFormat(e)}static submitUrl(e){return new SubmitUrl(e)}static subsetBelow(e){return new SubsetBelow(e)}static suppressBanner(e){return new SuppressBanner(e)}static tagged(e){return new Tagged(e)}static template(e){return new config_Template(e)}static templateCache(e){return new TemplateCache(e)}static threshold(e){return new Threshold(e)}static to(e){return new To(e)}static trace(e){return new Trace(e)}static transform(e){return new Transform(e)}static type(e){return new Type(e)}static uri(e){return new Uri(e)}static validate(e){return new config_Validate(e)}static validateApprovalSignatures(e){return new ValidateApprovalSignatures(e)}static validationMessaging(e){return new ValidationMessaging(e)}static version(e){return new Version(e)}static versionControl(e){return new VersionControl(e)}static viewerPreferences(e){return new ViewerPreferences(e)}static webClient(e){return new WebClient(e)}static whitespace(e){return new Whitespace(e)}static window(e){return new Window(e)}static xdc(e){return new Xdc(e)}static xdp(e){return new Xdp(e)}static xsl(e){return new Xsl(e)}static zpl(e){return new Zpl(e)}}const Jn=_r.connectionSet.id;class ConnectionSet extends XFAObject{constructor(e){super(Jn,"connectionSet",!0);this.wsdlConnection=new XFAObjectArray;this.xmlConnection=new XFAObjectArray;this.xsdConnection=new XFAObjectArray}}class EffectiveInputPolicy extends XFAObject{constructor(e){super(Jn,"effectiveInputPolicy");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class EffectiveOutputPolicy extends XFAObject{constructor(e){super(Jn,"effectiveOutputPolicy");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Operation extends StringObject{constructor(e){super(Jn,"operation");this.id=e.id||"";this.input=e.input||"";this.name=e.name||"";this.output=e.output||"";this.use=e.use||"";this.usehref=e.usehref||""}}class RootElement extends StringObject{constructor(e){super(Jn,"rootElement");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class SoapAction extends StringObject{constructor(e){super(Jn,"soapAction");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class SoapAddress extends StringObject{constructor(e){super(Jn,"soapAddress");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class connection_set_Uri extends StringObject{constructor(e){super(Jn,"uri");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class WsdlAddress extends StringObject{constructor(e){super(Jn,"wsdlAddress");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class WsdlConnection extends XFAObject{constructor(e){super(Jn,"wsdlConnection",!0);this.dataDescription=e.dataDescription||"";this.name=e.name||"";this.effectiveInputPolicy=null;this.effectiveOutputPolicy=null;this.operation=null;this.soapAction=null;this.soapAddress=null;this.wsdlAddress=null}}class XmlConnection extends XFAObject{constructor(e){super(Jn,"xmlConnection",!0);this.dataDescription=e.dataDescription||"";this.name=e.name||"";this.uri=null}}class XsdConnection extends XFAObject{constructor(e){super(Jn,"xsdConnection",!0);this.dataDescription=e.dataDescription||"";this.name=e.name||"";this.rootElement=null;this.uri=null}}class ConnectionSetNamespace{static[zr](e,t){if(ConnectionSetNamespace.hasOwnProperty(e))return ConnectionSetNamespace[e](t)}static connectionSet(e){return new ConnectionSet(e)}static effectiveInputPolicy(e){return new EffectiveInputPolicy(e)}static effectiveOutputPolicy(e){return new EffectiveOutputPolicy(e)}static operation(e){return new Operation(e)}static rootElement(e){return new RootElement(e)}static soapAction(e){return new SoapAction(e)}static soapAddress(e){return new SoapAddress(e)}static uri(e){return new connection_set_Uri(e)}static wsdlAddress(e){return new WsdlAddress(e)}static wsdlConnection(e){return new WsdlConnection(e)}static xmlConnection(e){return new XmlConnection(e)}static xsdConnection(e){return new XsdConnection(e)}}const Yn=_r.datasets.id;class datasets_Data extends XmlObject{constructor(e){super(Yn,"data",e)}[mr](){return!0}}class Datasets extends XFAObject{constructor(e){super(Yn,"datasets",!0);this.data=null;this.Signature=null}[Nr](e){const t=e[kr];("data"===t&&e[Sr]===Yn||"Signature"===t&&e[Sr]===_r.signature.id)&&(this[t]=e);this[Hs](e)}}class DatasetsNamespace{static[zr](e,t){if(DatasetsNamespace.hasOwnProperty(e))return DatasetsNamespace[e](t)}static datasets(e){return new Datasets(e)}static data(e){return new datasets_Data(e)}}const vn=_r.localeSet.id;class CalendarSymbols extends XFAObject{constructor(e){super(vn,"calendarSymbols",!0);this.name="gregorian";this.dayNames=new XFAObjectArray(2);this.eraNames=null;this.meridiemNames=null;this.monthNames=new XFAObjectArray(2)}}class CurrencySymbol extends StringObject{constructor(e){super(vn,"currencySymbol");this.name=getStringOption(e.name,["symbol","isoname","decimal"])}}class CurrencySymbols extends XFAObject{constructor(e){super(vn,"currencySymbols",!0);this.currencySymbol=new XFAObjectArray(3)}}class DatePattern extends StringObject{constructor(e){super(vn,"datePattern");this.name=getStringOption(e.name,["full","long","med","short"])}}class DatePatterns extends XFAObject{constructor(e){super(vn,"datePatterns",!0);this.datePattern=new XFAObjectArray(4)}}class DateTimeSymbols extends ContentObject{constructor(e){super(vn,"dateTimeSymbols")}}class Day extends StringObject{constructor(e){super(vn,"day")}}class DayNames extends XFAObject{constructor(e){super(vn,"dayNames",!0);this.abbr=getInteger({data:e.abbr,defaultValue:0,validate:e=>1===e});this.day=new XFAObjectArray(7)}}class Era extends StringObject{constructor(e){super(vn,"era")}}class EraNames extends XFAObject{constructor(e){super(vn,"eraNames",!0);this.era=new XFAObjectArray(2)}}class locale_set_Locale extends XFAObject{constructor(e){super(vn,"locale",!0);this.desc=e.desc||"";this.name="isoname";this.calendarSymbols=null;this.currencySymbols=null;this.datePatterns=null;this.dateTimeSymbols=null;this.numberPatterns=null;this.numberSymbols=null;this.timePatterns=null;this.typeFaces=null}}class locale_set_LocaleSet extends XFAObject{constructor(e){super(vn,"localeSet",!0);this.locale=new XFAObjectArray}}class Meridiem extends StringObject{constructor(e){super(vn,"meridiem")}}class MeridiemNames extends XFAObject{constructor(e){super(vn,"meridiemNames",!0);this.meridiem=new XFAObjectArray(2)}}class Month extends StringObject{constructor(e){super(vn,"month")}}class MonthNames extends XFAObject{constructor(e){super(vn,"monthNames",!0);this.abbr=getInteger({data:e.abbr,defaultValue:0,validate:e=>1===e});this.month=new XFAObjectArray(12)}}class NumberPattern extends StringObject{constructor(e){super(vn,"numberPattern");this.name=getStringOption(e.name,["full","long","med","short"])}}class NumberPatterns extends XFAObject{constructor(e){super(vn,"numberPatterns",!0);this.numberPattern=new XFAObjectArray(4)}}class NumberSymbol extends StringObject{constructor(e){super(vn,"numberSymbol");this.name=getStringOption(e.name,["decimal","grouping","percent","minus","zero"])}}class NumberSymbols extends XFAObject{constructor(e){super(vn,"numberSymbols",!0);this.numberSymbol=new XFAObjectArray(5)}}class TimePattern extends StringObject{constructor(e){super(vn,"timePattern");this.name=getStringOption(e.name,["full","long","med","short"])}}class TimePatterns extends XFAObject{constructor(e){super(vn,"timePatterns",!0);this.timePattern=new XFAObjectArray(4)}}class TypeFace extends XFAObject{constructor(e){super(vn,"typeFace",!0);this.name=""|e.name}}class TypeFaces extends XFAObject{constructor(e){super(vn,"typeFaces",!0);this.typeFace=new XFAObjectArray}}class LocaleSetNamespace{static[zr](e,t){if(LocaleSetNamespace.hasOwnProperty(e))return LocaleSetNamespace[e](t)}static calendarSymbols(e){return new CalendarSymbols(e)}static currencySymbol(e){return new CurrencySymbol(e)}static currencySymbols(e){return new CurrencySymbols(e)}static datePattern(e){return new DatePattern(e)}static datePatterns(e){return new DatePatterns(e)}static dateTimeSymbols(e){return new DateTimeSymbols(e)}static day(e){return new Day(e)}static dayNames(e){return new DayNames(e)}static era(e){return new Era(e)}static eraNames(e){return new EraNames(e)}static locale(e){return new locale_set_Locale(e)}static localeSet(e){return new locale_set_LocaleSet(e)}static meridiem(e){return new Meridiem(e)}static meridiemNames(e){return new MeridiemNames(e)}static month(e){return new Month(e)}static monthNames(e){return new MonthNames(e)}static numberPattern(e){return new NumberPattern(e)}static numberPatterns(e){return new NumberPatterns(e)}static numberSymbol(e){return new NumberSymbol(e)}static numberSymbols(e){return new NumberSymbols(e)}static timePattern(e){return new TimePattern(e)}static timePatterns(e){return new TimePatterns(e)}static typeFace(e){return new TypeFace(e)}static typeFaces(e){return new TypeFaces(e)}}const Kn=_r.signature.id;class signature_Signature extends XFAObject{constructor(e){super(Kn,"signature",!0)}}class SignatureNamespace{static[zr](e,t){if(SignatureNamespace.hasOwnProperty(e))return SignatureNamespace[e](t)}static signature(e){return new signature_Signature(e)}}const Tn=_r.stylesheet.id;class Stylesheet extends XFAObject{constructor(e){super(Tn,"stylesheet",!0)}}class StylesheetNamespace{static[zr](e,t){if(StylesheetNamespace.hasOwnProperty(e))return StylesheetNamespace[e](t)}static stylesheet(e){return new Stylesheet(e)}}const qn=_r.xdp.id;class xdp_Xdp extends XFAObject{constructor(e){super(qn,"xdp",!0);this.uuid=e.uuid||"";this.timeStamp=e.timeStamp||"";this.config=null;this.connectionSet=null;this.datasets=null;this.localeSet=null;this.stylesheet=new XFAObjectArray;this.template=null}[Gr](e){const t=_r[e[kr]];return t&&e[Sr]===t.id}}class XdpNamespace{static[zr](e,t){if(XdpNamespace.hasOwnProperty(e))return XdpNamespace[e](t)}static xdp(e){return new xdp_Xdp(e)}}const On=_r.xhtml.id,Pn=Symbol(),Wn=new Set(["color","font","font-family","font-size","font-stretch","font-style","font-weight","margin","margin-bottom","margin-left","margin-right","margin-top","letter-spacing","line-height","orphans","page-break-after","page-break-before","page-break-inside","tab-interval","tab-stop","text-align","text-decoration","text-indent","vertical-align","widows","kerning-mode","xfa-font-horizontal-scale","xfa-font-vertical-scale","xfa-spacerun","xfa-tab-stops"]),jn=new Map([["page-break-after","breakAfter"],["page-break-before","breakBefore"],["page-break-inside","breakInside"],["kerning-mode",e=>"none"===e?"none":"normal"],["xfa-font-horizontal-scale",e=>`scaleX(${Math.max(0,Math.min(parseInt(e)/100)).toFixed(2)})`],["xfa-font-vertical-scale",e=>`scaleY(${Math.max(0,Math.min(parseInt(e)/100)).toFixed(2)})`],["xfa-spacerun",""],["xfa-tab-stops",""],["font-size",(e,t)=>measureToString(.99*(e=t.fontSize=Math.abs(getMeasurement(e))))],["letter-spacing",e=>measureToString(getMeasurement(e))],["line-height",e=>measureToString(getMeasurement(e))],["margin",e=>measureToString(getMeasurement(e))],["margin-bottom",e=>measureToString(getMeasurement(e))],["margin-left",e=>measureToString(getMeasurement(e))],["margin-right",e=>measureToString(getMeasurement(e))],["margin-top",e=>measureToString(getMeasurement(e))],["text-indent",e=>measureToString(getMeasurement(e))],["font-family",e=>e],["vertical-align",e=>measureToString(getMeasurement(e))]]),Xn=/\s+/g,Zn=/[\r\n]+/g,Vn=/\r\n?/g;function mapStyle(e,t,i){const a=Object.create(null);if(!e)return a;const s=Object.create(null);for(const[t,i]of e.split(";").map((e=>e.split(":",2)))){const e=jn.get(t);if(""===e)continue;let r=i;e&&(r="string"==typeof e?e:e(i,s));t.endsWith("scale")?a.transform=a.transform?`${a[t]} ${r}`:r:a[t.replaceAll(/-([a-zA-Z])/g,((e,t)=>t.toUpperCase()))]=r}a.fontFamily&&setFontFamily({typeface:a.fontFamily,weight:a.fontWeight||"normal",posture:a.fontStyle||"normal",size:s.fontSize||0},t,t[Cr].fontFinder,a);if(i&&a.verticalAlign&&"0px"!==a.verticalAlign&&a.fontSize){const e=.583,t=.333,i=getMeasurement(a.fontSize);a.fontSize=measureToString(i*e);a.verticalAlign=measureToString(Math.sign(getMeasurement(a.verticalAlign))*i*t)}i&&a.fontSize&&(a.fontSize=`calc(${a.fontSize} * var(--scale-factor))`);fixTextIndent(a);return a}const zn=new Set(["body","html"]);class XhtmlObject extends XmlObject{constructor(e,t){super(On,t);this[Pn]=!1;this.style=e.style||""}[Ys](e){super[Ys](e);this.style=function checkStyle(e){return e.style?e.style.trim().split(/\s*;\s*/).filter((e=>!!e)).map((e=>e.split(/\s*:\s*/,2))).filter((([t,i])=>{"font-family"===t&&e[Cr].usedTypefaces.add(i);return Wn.has(t)})).map((e=>e.join(":"))).join(";"):""}(this)}[xs](){return!zn.has(this[kr])}[Mr](e,t=!1){if(t)this[Pn]=!0;else{e=e.replaceAll(Zn,"");this.style.includes("xfa-spacerun:yes")||(e=e.replaceAll(Xn," "))}e&&(this[Os]+=e)}[Ur](e,t=!0){const i=Object.create(null),a={top:NaN,bottom:NaN,left:NaN,right:NaN};let s=null;for(const[e,t]of this.style.split(";").map((e=>e.split(":",2))))switch(e){case"font-family":i.typeface=stripQuotes(t);break;case"font-size":i.size=getMeasurement(t);break;case"font-weight":i.weight=t;break;case"font-style":i.posture=t;break;case"letter-spacing":i.letterSpacing=getMeasurement(t);break;case"margin":const e=t.split(/ \t/).map((e=>getMeasurement(e)));switch(e.length){case 1:a.top=a.bottom=a.left=a.right=e[0];break;case 2:a.top=a.bottom=e[0];a.left=a.right=e[1];break;case 3:a.top=e[0];a.bottom=e[2];a.left=a.right=e[1];break;case 4:a.top=e[0];a.left=e[1];a.bottom=e[2];a.right=e[3]}break;case"margin-top":a.top=getMeasurement(t);break;case"margin-bottom":a.bottom=getMeasurement(t);break;case"margin-left":a.left=getMeasurement(t);break;case"margin-right":a.right=getMeasurement(t);break;case"line-height":s=getMeasurement(t)}e.pushData(i,a,s);if(this[Os])e.addString(this[Os]);else for(const t of this[rr]())"#text"!==t[kr]?t[Ur](e):e.addString(t[Os]);t&&e.popFont()}[jr](e){const t=[];this[Xs]={children:t};this[Js]({});if(0===t.length&&!this[Os])return HTMLResult.EMPTY;let i;i=this[Pn]?this[Os]?this[Os].replaceAll(Vn,"\n"):void 0:this[Os]||void 0;return HTMLResult.success({name:this[kr],attributes:{href:this.href,style:mapStyle(this.style,this,this[Pn])},children:t,value:i})}}class A extends XhtmlObject{constructor(e){super(e,"a");this.href=fixURL(e.href)||""}}class B extends XhtmlObject{constructor(e){super(e,"b")}[Ur](e){e.pushFont({weight:"bold"});super[Ur](e);e.popFont()}}class Body extends XhtmlObject{constructor(e){super(e,"body")}[jr](e){const t=super[jr](e),{html:i}=t;if(!i)return HTMLResult.EMPTY;i.name="div";i.attributes.class=["xfaRich"];return t}}class Br extends XhtmlObject{constructor(e){super(e,"br")}[Pr](){return"\n"}[Ur](e){e.addString("\n")}[jr](e){return HTMLResult.success({name:"br"})}}class Html extends XhtmlObject{constructor(e){super(e,"html")}[jr](e){const t=[];this[Xs]={children:t};this[Js]({});if(0===t.length)return HTMLResult.success({name:"div",attributes:{class:["xfaRich"],style:{}},value:this[Os]||""});if(1===t.length){const e=t[0];if(e.attributes?.class.includes("xfaRich"))return HTMLResult.success(e)}return HTMLResult.success({name:"div",attributes:{class:["xfaRich"],style:{}},children:t})}}class I extends XhtmlObject{constructor(e){super(e,"i")}[Ur](e){e.pushFont({posture:"italic"});super[Ur](e);e.popFont()}}class Li extends XhtmlObject{constructor(e){super(e,"li")}}class Ol extends XhtmlObject{constructor(e){super(e,"ol")}}class P extends XhtmlObject{constructor(e){super(e,"p")}[Ur](e){super[Ur](e,!1);e.addString("\n");e.addPara();e.popFont()}[Pr](){return this[Ir]()[rr]().at(-1)===this?super[Pr]():super[Pr]()+"\n"}}class Span extends XhtmlObject{constructor(e){super(e,"span")}}class Sub extends XhtmlObject{constructor(e){super(e,"sub")}}class Sup extends XhtmlObject{constructor(e){super(e,"sup")}}class Ul extends XhtmlObject{constructor(e){super(e,"ul")}}class XhtmlNamespace{static[zr](e,t){if(XhtmlNamespace.hasOwnProperty(e))return XhtmlNamespace[e](t)}static a(e){return new A(e)}static b(e){return new B(e)}static body(e){return new Body(e)}static br(e){return new Br(e)}static html(e){return new Html(e)}static i(e){return new I(e)}static li(e){return new Li(e)}static ol(e){return new Ol(e)}static p(e){return new P(e)}static span(e){return new Span(e)}static sub(e){return new Sub(e)}static sup(e){return new Sup(e)}static ul(e){return new Ul(e)}}const _n={config:ConfigNamespace,connection:ConnectionSetNamespace,datasets:DatasetsNamespace,localeSet:LocaleSetNamespace,signature:SignatureNamespace,stylesheet:StylesheetNamespace,template:TemplateNamespace,xdp:XdpNamespace,xhtml:XhtmlNamespace};class UnknownNamespace{constructor(e){this.namespaceId=e}[zr](e,t){return new XmlObject(this.namespaceId,e,t)}}class Root extends XFAObject{constructor(e){super(-1,"root",Object.create(null));this.element=null;this[lr]=e}[Nr](e){this.element=e;return!0}[Zs](){super[Zs]();if(this.element.template instanceof Template){this[lr].set(Jr,this.element);this.element.template[Yr](this[lr]);this.element.template[lr]=this[lr]}}}class Empty extends XFAObject{constructor(){super(-1,"",Object.create(null))}[Nr](e){return!1}}class Builder{constructor(e=null){this._namespaceStack=[];this._nsAgnosticLevel=0;this._namespacePrefixes=new Map;this._namespaces=new Map;this._nextNsId=Math.max(...Object.values(_r).map((({id:e})=>e)));this._currentNamespace=e||new UnknownNamespace(++this._nextNsId)}buildRoot(e){return new Root(e)}build({nsPrefix:e,name:t,attributes:i,namespace:a,prefixes:s}){const r=null!==a;if(r){this._namespaceStack.push(this._currentNamespace);this._currentNamespace=this._searchNamespace(a)}s&&this._addNamespacePrefix(s);if(i.hasOwnProperty(Rr)){const e=_n.datasets,t=i[Rr];let a=null;for(const[i,s]of Object.entries(t)){if(this._getNamespaceToUse(i)===e){a={xfa:s};break}}a?i[Rr]=a:delete i[Rr]}const n=this._getNamespaceToUse(e),g=n?.[zr](t,i)||new Empty;g[mr]()&&this._nsAgnosticLevel++;(r||s||g[mr]())&&(g[Ks]={hasNamespace:r,prefixes:s,nsAgnostic:g[mr]()});return g}isNsAgnostic(){return this._nsAgnosticLevel>0}_searchNamespace(e){let t=this._namespaces.get(e);if(t)return t;for(const[i,{check:a}]of Object.entries(_r))if(a(e)){t=_n[i];if(t){this._namespaces.set(e,t);return t}break}t=new UnknownNamespace(++this._nextNsId);this._namespaces.set(e,t);return t}_addNamespacePrefix(e){for(const{prefix:t,value:i}of e){const e=this._searchNamespace(i);let a=this._namespacePrefixes.get(t);if(!a){a=[];this._namespacePrefixes.set(t,a)}a.push(e)}}_getNamespaceToUse(e){if(!e)return this._currentNamespace;const t=this._namespacePrefixes.get(e);if(t?.length>0)return t.at(-1);warn(`Unknown namespace prefix: ${e}.`);return null}clean(e){const{hasNamespace:t,prefixes:i,nsAgnostic:a}=e;t&&(this._currentNamespace=this._namespaceStack.pop());i&&i.forEach((({prefix:e})=>{this._namespacePrefixes.get(e).pop()}));a&&this._nsAgnosticLevel--}}class XFAParser extends XMLParserBase{constructor(e=null,t=!1){super();this._builder=new Builder(e);this._stack=[];this._globalData={usedTypefaces:new Set};this._ids=new Map;this._current=this._builder.buildRoot(this._ids);this._errorCode=ys;this._whiteRegex=/^\s+$/;this._nbsps=/\xa0+/g;this._richText=t}parse(e){this.parseXml(e);if(this._errorCode===ys){this._current[Zs]();return this._current.element}}onText(e){e=e.replace(this._nbsps,(e=>e.slice(1)+" "));this._richText||this._current[xs]()?this._current[Mr](e,this._richText):this._whiteRegex.test(e)||this._current[Mr](e.trim())}onCdata(e){this._current[Mr](e)}_mkAttributes(e,t){let i=null,a=null;const s=Object.create({});for(const{name:r,value:n}of e)if("xmlns"===r)i?warn(`XFA - multiple namespace definition in <${t}>`):i=n;else if(r.startsWith("xmlns:")){const e=r.substring(6);a||(a=[]);a.push({prefix:e,value:n})}else{const e=r.indexOf(":");if(-1===e)s[r]=n;else{let t=s[Rr];t||(t=s[Rr]=Object.create(null));const[i,a]=[r.slice(0,e),r.slice(e+1)];(t[i]||=Object.create(null))[a]=n}}return[i,a,s]}_getNameAndPrefix(e,t){const i=e.indexOf(":");return-1===i?[e,null]:[e.substring(i+1),t?"":e.substring(0,i)]}onBeginElement(e,t,i){const[a,s,r]=this._mkAttributes(t,e),[n,g]=this._getNameAndPrefix(e,this._builder.isNsAgnostic()),o=this._builder.build({nsPrefix:g,name:n,attributes:r,namespace:a,prefixes:s});o[Cr]=this._globalData;if(i){o[Zs]();this._current[Nr](o)&&o[Kr](this._ids);o[Ys](this._builder)}else{this._stack.push(this._current);this._current=o}}onEndElement(e){const t=this._current;if(t[ur]()&&"string"==typeof t[Os]){const e=new XFAParser;e._globalData=this._globalData;const i=e.parse(t[Os]);t[Os]=null;t[Nr](i)}t[Zs]();this._current=this._stack.pop();this._current[Nr](t)&&t[Kr](this._ids);t[Ys](this._builder)}onError(e){this._errorCode=e}}class XFAFactory{constructor(e){try{this.root=(new XFAParser).parse(XFAFactory._createDocument(e));const t=new Binder(this.root);this.form=t.bind();this.dataHandler=new DataHandler(this.root,t.getData());this.form[Cr].template=this.form}catch(e){warn(`XFA - an error occurred during parsing and binding: ${e}`)}}isValid(){return this.root&&this.form}_createPagesHelper(){const e=this.form[Wr]();return new Promise(((t,i)=>{const nextIteration=()=>{try{const i=e.next();i.done?t(i.value):setTimeout(nextIteration,0)}catch(e){i(e)}};setTimeout(nextIteration,0)}))}async _createPages(){try{this.pages=await this._createPagesHelper();this.dims=this.pages.children.map((e=>{const{width:t,height:i}=e.attributes.style;return[0,0,parseInt(t),parseInt(i)]}))}catch(e){warn(`XFA - an error occurred during layout: ${e}`)}}getBoundingBox(e){return this.dims[e]}async getNumPages(){this.pages||await this._createPages();return this.dims.length}setImages(e){this.form[Cr].images=e}setFonts(e){this.form[Cr].fontFinder=new FontFinder(e);const t=[];for(let e of this.form[Cr].usedTypefaces){e=stripQuotes(e);this.form[Cr].fontFinder.find(e)||t.push(e)}return t.length>0?t:null}appendFonts(e,t){this.form[Cr].fontFinder.add(e,t)}async getPages(){this.pages||await this._createPages();const e=this.pages;this.pages=null;return e}serializeData(e){return this.dataHandler.serialize(e)}static _createDocument(e){return e["/xdp:xdp"]?Object.values(e).join(""):e["xdp:xdp"]}static getRichTextAsHtml(e){if(!e||"string"!=typeof e)return null;try{let t=new XFAParser(XhtmlNamespace,!0).parse(e);if(!["body","xhtml"].includes(t[kr])){const e=XhtmlNamespace.body({});e[Hs](t);t=e}const i=t[jr]();if(!i.success)return null;const{html:a}=i,{attributes:s}=a;if(s){s.class&&(s.class=s.class.filter((e=>!e.startsWith("xfa"))));s.dir="auto"}return{html:a,str:t[Pr]()}}catch(e){warn(`XFA - an error occurred during parsing of rich text: ${e}`)}return null}}class AnnotationFactory{static createGlobals(e){return Promise.all([e.ensureCatalog("acroForm"),e.ensureDoc("xfaDatasets"),e.ensureCatalog("structTreeRoot"),e.ensureCatalog("baseUrl"),e.ensureCatalog("attachments")]).then((([t,i,a,s,r])=>({pdfManager:e,acroForm:t instanceof Dict?t:Dict.empty,xfaDatasets:i,structTreeRoot:a,baseUrl:s,attachments:r})),(e=>{warn(`createGlobals: "${e}".`);return null}))}static async create(e,t,i,a,s,r,n){const g=s?await this._getPageIndex(e,t,i.pdfManager):null;return i.pdfManager.ensure(this,"_create",[e,t,i,a,s,r,g,n])}static _create(e,t,i,a,s=!1,r=null,n=null,g=null){const o=e.fetchIfRef(t);if(!(o instanceof Dict))return;const{acroForm:c,pdfManager:C}=i,h=t instanceof Ref?t.toString():`annot_${a.createObjId()}`;let l=o.get("Subtype");l=l instanceof Name?l.name:null;const Q={xref:e,ref:t,dict:o,subtype:l,id:h,annotationGlobals:i,collectFields:s,orphanFields:r,needAppearances:!s&&!0===c.get("NeedAppearances"),pageIndex:n,evaluatorOptions:C.evaluatorOptions,pageRef:g};switch(l){case"Link":return new LinkAnnotation(Q);case"Text":return new TextAnnotation(Q);case"Widget":let e=getInheritableProperty({dict:o,key:"FT"});e=e instanceof Name?e.name:null;switch(e){case"Tx":return new TextWidgetAnnotation(Q);case"Btn":return new ButtonWidgetAnnotation(Q);case"Ch":return new ChoiceWidgetAnnotation(Q);case"Sig":return new SignatureWidgetAnnotation(Q)}warn(`Unimplemented widget field type "${e}", falling back to base field type.`);return new WidgetAnnotation(Q);case"Popup":return new PopupAnnotation(Q);case"FreeText":return new FreeTextAnnotation(Q);case"Line":return new LineAnnotation(Q);case"Square":return new SquareAnnotation(Q);case"Circle":return new CircleAnnotation(Q);case"PolyLine":return new PolylineAnnotation(Q);case"Polygon":return new PolygonAnnotation(Q);case"Caret":return new CaretAnnotation(Q);case"Ink":return new InkAnnotation(Q);case"Highlight":return new HighlightAnnotation(Q);case"Underline":return new UnderlineAnnotation(Q);case"Squiggly":return new SquigglyAnnotation(Q);case"StrikeOut":return new StrikeOutAnnotation(Q);case"Stamp":return new StampAnnotation(Q);case"FileAttachment":return new FileAttachmentAnnotation(Q);default:s||warn(l?`Unimplemented annotation type "${l}", falling back to base annotation.`:"Annotation is missing the required /Subtype.");return new Annotation(Q)}}static async _getPageIndex(e,t,i){try{const a=await e.fetchIfRefAsync(t);if(!(a instanceof Dict))return-1;const s=a.getRaw("P");if(s instanceof Ref)try{return await i.ensureCatalog("getPageIndex",[s])}catch(e){info(`_getPageIndex -- not a valid page reference: "${e}".`)}if(a.has("Kids"))return-1;const r=await i.ensureDoc("numPages");for(let e=0;ee/255))}function getQuadPoints(e,t){const i=e.getArray("QuadPoints");if(!isNumberArray(i,null)||0===i.length||i.length%8>0)return null;const a=new Float32Array(i.length);for(let e=0,s=i.length;et[2]||Et[3]))return null;a.set([l,u,Q,u,l,E,Q,E],e)}return a}function getTransformMatrix(e,t,i){const[a,s,r,n]=Util.getAxialAlignedBoundingBox(t,i);if(a===r||s===n)return[1,0,0,1,e[0],e[1]];const g=(e[2]-e[0])/(r-a),o=(e[3]-e[1])/(n-s);return[g,0,0,o,e[0]-a*g,e[1]-s*o]}class Annotation{constructor(e){const{dict:t,xref:i,annotationGlobals:a,ref:s,orphanFields:r}=e,n=r?.get(s);n&&t.set("Parent",n);this.setTitle(t.get("T"));this.setContents(t.get("Contents"));this.setModificationDate(t.get("M"));this.setFlags(t.get("F"));this.setRectangle(t.getArray("Rect"));this.setColor(t.getArray("C"));this.setBorderStyle(t);this.setAppearance(t);this.setOptionalContent(t);const g=t.get("MK");this.setBorderAndBackgroundColors(g);this.setRotation(g,t);this.ref=e.ref instanceof Ref?e.ref:null;this._streams=[];this.appearance&&this._streams.push(this.appearance);const o=!!(this.flags&eA),c=!!(this.flags&tA);this.data={annotationFlags:this.flags,borderStyle:this.borderStyle,color:this.color,backgroundColor:this.backgroundColor,borderColor:this.borderColor,rotation:this.rotation,contentsObj:this._contents,hasAppearance:!!this.appearance,id:e.id,modificationDate:this.modificationDate,rect:this.rectangle,subtype:e.subtype,hasOwnCanvas:!1,noRotate:!!(this.flags&$),noHTML:o&&c,isEditable:!1,structParent:-1};if(a.structTreeRoot){let i=t.get("StructParent");this.data.structParent=i=Number.isInteger(i)&&i>=0?i:-1;a.structTreeRoot.addAnnotationIdToPage(e.pageRef,i)}if(e.collectFields){const a=t.get("Kids");if(Array.isArray(a)){const e=[];for(const t of a)t instanceof Ref&&e.push(t.toString());0!==e.length&&(this.data.kidIds=e)}this.data.actions=collectActions(i,t,dA);this.data.fieldName=this._constructFieldName(t);this.data.pageIndex=e.pageIndex}const C=t.get("IT");C instanceof Name&&(this.data.it=C.name);this._isOffscreenCanvasSupported=e.evaluatorOptions.isOffscreenCanvasSupported;this._fallbackFontDict=null;this._needAppearances=!1}_hasFlag(e,t){return!!(e&t)}_buildFlags(e,t){let{flags:i}=this;if(void 0===e){if(void 0===t)return;return t?i&~_:i&~z|_}if(e){i|=_;return t?i&~AA|z:i&~z|AA}i&=~(z|AA);return t?i&~_:i|_}_isViewable(e){return!this._hasFlag(e,V)&&!this._hasFlag(e,AA)}_isPrintable(e){return this._hasFlag(e,_)&&!this._hasFlag(e,z)&&!this._hasFlag(e,V)}mustBeViewed(e,t){const i=e?.get(this.data.id)?.noView;return void 0!==i?!i:this.viewable&&!this._hasFlag(this.flags,z)}mustBePrinted(e){const t=e?.get(this.data.id)?.noPrint;return void 0!==t?!t:this.printable}mustBeViewedWhenEditing(e,t=null){return e?!this.data.isEditable:!t?.has(this.data.id)}get viewable(){return null!==this.data.quadPoints&&(0===this.flags||this._isViewable(this.flags))}get printable(){return null!==this.data.quadPoints&&(0!==this.flags&&this._isPrintable(this.flags))}_parseStringHelper(e){const t="string"==typeof e?stringToPDFString(e):"";return{str:t,dir:t&&"rtl"===bidi(t).dir?"rtl":"ltr"}}setDefaultAppearance(e){const{dict:t,annotationGlobals:i}=e,a=getInheritableProperty({dict:t,key:"DA"})||i.acroForm.get("DA");this._defaultAppearance="string"==typeof a?a:"";this.data.defaultAppearanceData=parseDefaultAppearance(this._defaultAppearance)}setTitle(e){this._title=this._parseStringHelper(e)}setContents(e){this._contents=this._parseStringHelper(e)}setModificationDate(e){this.modificationDate="string"==typeof e?e:null}setFlags(e){this.flags=Number.isInteger(e)&&e>0?e:0;this.flags&V&&"Annotation"!==this.constructor.name&&(this.flags^=V)}hasFlag(e){return this._hasFlag(this.flags,e)}setRectangle(e){this.rectangle=lookupNormalRect(e,[0,0,0,0])}setColor(e){this.color=getRgbColor(e)}setLineEndings(e){this.lineEndings=["None","None"];if(Array.isArray(e)&&2===e.length)for(let t=0;t<2;t++){const i=e[t];if(i instanceof Name)switch(i.name){case"None":continue;case"Square":case"Circle":case"Diamond":case"OpenArrow":case"ClosedArrow":case"Butt":case"ROpenArrow":case"RClosedArrow":case"Slash":this.lineEndings[t]=i.name;continue}warn(`Ignoring invalid lineEnding: ${i}`)}}setRotation(e,t){this.rotation=0;let i=e instanceof Dict?e.get("R")||0:t.get("Rotate")||0;if(Number.isInteger(i)&&0!==i){i%=360;i<0&&(i+=360);i%90==0&&(this.rotation=i)}}setBorderAndBackgroundColors(e){if(e instanceof Dict){this.borderColor=getRgbColor(e.getArray("BC"),null);this.backgroundColor=getRgbColor(e.getArray("BG"),null)}else this.borderColor=this.backgroundColor=null}setBorderStyle(e){this.borderStyle=new AnnotationBorderStyle;if(e instanceof Dict)if(e.has("BS")){const t=e.get("BS");if(t instanceof Dict){const e=t.get("Type");if(!e||isName(e,"Border")){this.borderStyle.setWidth(t.get("W"),this.rectangle);this.borderStyle.setStyle(t.get("S"));this.borderStyle.setDashArray(t.getArray("D"))}}}else if(e.has("Border")){const t=e.getArray("Border");if(Array.isArray(t)&&t.length>=3){this.borderStyle.setHorizontalCornerRadius(t[0]);this.borderStyle.setVerticalCornerRadius(t[1]);this.borderStyle.setWidth(t[2],this.rectangle);4===t.length&&this.borderStyle.setDashArray(t[3],!0)}}else this.borderStyle.setWidth(0)}setAppearance(e){this.appearance=null;const t=e.get("AP");if(!(t instanceof Dict))return;const i=t.get("N");if(i instanceof BaseStream){this.appearance=i;return}if(!(i instanceof Dict))return;const a=e.get("AS");if(!(a instanceof Name&&i.has(a.name)))return;const s=i.get(a.name);s instanceof BaseStream&&(this.appearance=s)}setOptionalContent(e){this.oc=null;const t=e.get("OC");t instanceof Name?warn("setOptionalContent: Support for /Name-entry is not implemented."):t instanceof Dict&&(this.oc=t)}loadResources(e,t){return t.dict.getAsync("Resources").then((t=>{if(!t)return;return new ObjectLoader(t,e,t.xref).load().then((function(){return t}))}))}async getOperatorList(e,t,a,s){const{hasOwnCanvas:r,id:n,rect:g}=this.data;let c=this.appearance;const C=!!(r&&a&o);if(C&&(g[0]===g[2]||g[1]===g[3])){this.data.hasOwnCanvas=!1;return{opList:new OperatorList,separateForm:!1,separateCanvas:!1}}if(!c){if(!C)return{opList:new OperatorList,separateForm:!1,separateCanvas:!1};c=new StringStream("");c.dict=new Dict}const h=c.dict,l=await this.loadResources(["ExtGState","ColorSpace","Pattern","Shading","XObject","Font"],c),Q=lookupRect(h.getArray("BBox"),[0,0,1,1]),E=lookupMatrix(h.getArray("Matrix"),i),u=getTransformMatrix(g,Q,E),d=new OperatorList;let f;this.oc&&(f=await e.parseMarkedContentProps(this.oc,null));void 0!==f&&d.addOp(Ye,["OC",f]);d.addOp(je,[n,g,u,E,C]);await e.getOperatorList({stream:c,task:t,resources:l,operatorList:d,fallbackFontDict:this._fallbackFontDict});d.addOp(Xe,[]);void 0!==f&&d.addOp(ve,[]);this.reset();return{opList:d,separateForm:!1,separateCanvas:C}}async save(e,t,i,a){return null}get hasTextContent(){return!1}async extractTextContent(e,t,i){if(!this.appearance)return;const a=await this.loadResources(["ExtGState","Font","Properties","XObject"],this.appearance),s=[],r=[];let n=null;const g={desiredSize:Math.Infinity,ready:!0,enqueue(e,t){for(const t of e.items)if(void 0!==t.str){n||=t.transform.slice(-2);r.push(t.str);if(t.hasEOL){s.push(r.join("").trimEnd());r.length=0}}}};await e.getTextContent({stream:this.appearance,task:t,resources:a,includeMarkedContent:!0,keepWhiteSpace:!0,sink:g,viewBox:i});this.reset();r.length&&s.push(r.join("").trimEnd());if(s.length>1||s[0]){const e=this.appearance.dict,t=lookupRect(e.getArray("BBox"),null),i=lookupMatrix(e.getArray("Matrix"),null);this.data.textPosition=this._transformPoint(n,t,i);this.data.textContent=s}}_transformPoint(e,t,i){const{rect:a}=this.data;t||=[0,0,1,1];i||=[1,0,0,1,0,0];const s=getTransformMatrix(a,t,i);s[4]-=a[0];s[5]-=a[1];e=Util.applyTransform(e,s);return Util.applyTransform(e,i)}getFieldObject(){return this.data.kidIds?{id:this.data.id,actions:this.data.actions,name:this.data.fieldName,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,type:"",kidIds:this.data.kidIds,page:this.data.pageIndex,rotation:this.rotation}:null}reset(){for(const e of this._streams)e.reset()}_constructFieldName(e){if(!e.has("T")&&!e.has("Parent")){warn("Unknown field name, falling back to empty field name.");return""}if(!e.has("Parent"))return stringToPDFString(e.get("T"));const t=[];e.has("T")&&t.unshift(stringToPDFString(e.get("T")));let i=e;const a=new RefSet;e.objId&&a.put(e.objId);for(;i.has("Parent");){i=i.get("Parent");if(!(i instanceof Dict)||i.objId&&a.has(i.objId))break;i.objId&&a.put(i.objId);i.has("T")&&t.unshift(stringToPDFString(i.get("T")))}return t.join(".")}}class AnnotationBorderStyle{constructor(){this.width=1;this.rawWidth=1;this.style=lA;this.dashArray=[3];this.horizontalCornerRadius=0;this.verticalCornerRadius=0}setWidth(e,t=[0,0,0,0]){if(e instanceof Name)this.width=0;else if("number"==typeof e){if(e>0){this.rawWidth=e;const i=(t[2]-t[0])/2,a=(t[3]-t[1])/2;if(i>0&&a>0&&(e>i||e>a)){warn(`AnnotationBorderStyle.setWidth - ignoring width: ${e}`);e=1}}this.width=e}}setStyle(e){if(e instanceof Name)switch(e.name){case"S":this.style=lA;break;case"D":this.style=BA;break;case"B":this.style=QA;break;case"I":this.style=EA;break;case"U":this.style=uA}}setDashArray(e,t=!1){if(Array.isArray(e)){let i=!0,a=!0;for(const t of e){if(!(+t>=0)){i=!1;break}t>0&&(a=!1)}if(0===e.length||i&&!a){this.dashArray=e;t&&this.setStyle(Name.get("D"))}else this.width=0}else e&&(this.width=0)}setHorizontalCornerRadius(e){Number.isInteger(e)&&(this.horizontalCornerRadius=e)}setVerticalCornerRadius(e){Number.isInteger(e)&&(this.verticalCornerRadius=e)}}class MarkupAnnotation extends Annotation{constructor(e){super(e);const{dict:t}=e;if(t.has("IRT")){const e=t.getRaw("IRT");this.data.inReplyTo=e instanceof Ref?e.toString():null;const i=t.get("RT");this.data.replyType=i instanceof Name?i.name:Z}let i=null;if(this.data.replyType===X){const e=t.get("IRT");this.setTitle(e.get("T"));this.data.titleObj=this._title;this.setContents(e.get("Contents"));this.data.contentsObj=this._contents;if(e.has("CreationDate")){this.setCreationDate(e.get("CreationDate"));this.data.creationDate=this.creationDate}else this.data.creationDate=null;if(e.has("M")){this.setModificationDate(e.get("M"));this.data.modificationDate=this.modificationDate}else this.data.modificationDate=null;i=e.getRaw("Popup");if(e.has("C")){this.setColor(e.getArray("C"));this.data.color=this.color}else this.data.color=null}else{this.data.titleObj=this._title;this.setCreationDate(t.get("CreationDate"));this.data.creationDate=this.creationDate;i=t.getRaw("Popup");t.has("C")||(this.data.color=null)}this.data.popupRef=i instanceof Ref?i.toString():null;t.has("RC")&&(this.data.richText=XFAFactory.getRichTextAsHtml(t.get("RC")))}setCreationDate(e){this.creationDate="string"==typeof e?e:null}_setDefaultAppearance({xref:e,extra:t,strokeColor:i,fillColor:a,blendMode:s,strokeAlpha:r,fillAlpha:n,pointsCallback:g}){let o=Number.MAX_VALUE,c=Number.MAX_VALUE,C=Number.MIN_VALUE,h=Number.MIN_VALUE;const l=["q"];t&&l.push(t);i&&l.push(`${i[0]} ${i[1]} ${i[2]} RG`);a&&l.push(`${a[0]} ${a[1]} ${a[2]} rg`);const Q=this.data.quadPoints||Float32Array.from([this.rectangle[0],this.rectangle[3],this.rectangle[2],this.rectangle[3],this.rectangle[0],this.rectangle[1],this.rectangle[2],this.rectangle[1]]);for(let e=0,t=Q.length;e"string"==typeof e)).map((e=>stringToPDFString(e))):e instanceof Name?stringToPDFString(e.name):"string"==typeof e?stringToPDFString(e):null}hasFieldFlag(e){return!!(this.data.fieldFlags&e)}_isViewable(e){return!0}mustBeViewed(e,t){return t?this.viewable:super.mustBeViewed(e,t)&&!this._hasFlag(this.flags,AA)}getRotationMatrix(e){let t=e?.get(this.data.id)?.rotation;void 0===t&&(t=this.rotation);if(0===t)return i;return getRotationMatrix(t,this.data.rect[2]-this.data.rect[0],this.data.rect[3]-this.data.rect[1])}getBorderAndBackgroundAppearances(e){let t=e?.get(this.data.id)?.rotation;void 0===t&&(t=this.rotation);if(!this.backgroundColor&&!this.borderColor)return"";const i=this.data.rect[2]-this.data.rect[0],a=this.data.rect[3]-this.data.rect[1],s=0===t||180===t?`0 0 ${i} ${a} re`:`0 0 ${a} ${i} re`;let r="";this.backgroundColor&&(r=`${getPdfColor(this.backgroundColor,!0)} ${s} f `);if(this.borderColor){r+=`${this.borderStyle.width||1} w ${getPdfColor(this.borderColor,!1)} ${s} S `}return r}async getOperatorList(e,t,i,a){if(i&h&&!(this instanceof SignatureWidgetAnnotation)&&!this.data.noHTML&&!this.data.hasOwnCanvas)return{opList:new OperatorList,separateForm:!0,separateCanvas:!1};if(!this._hasText)return super.getOperatorList(e,t,i,a);const s=await this._getAppearance(e,t,i,a);if(this.appearance&&null===s)return super.getOperatorList(e,t,i,a);const r=new OperatorList;if(!this._defaultAppearance||null===s)return{opList:r,separateForm:!1,separateCanvas:!1};const n=!!(this.data.hasOwnCanvas&&i&o),g=[0,0,this.data.rect[2]-this.data.rect[0],this.data.rect[3]-this.data.rect[1]],c=getTransformMatrix(this.data.rect,g,[1,0,0,1,0,0]);let C;this.oc&&(C=await e.parseMarkedContentProps(this.oc,null));void 0!==C&&r.addOp(Ye,["OC",C]);r.addOp(je,[this.data.id,this.data.rect,c,this.getRotationMatrix(a),n]);const l=new StringStream(s);await e.getOperatorList({stream:l,task:t,resources:this._fieldResources.mergedResources,operatorList:r});r.addOp(Xe,[]);void 0!==C&&r.addOp(ve,[]);return{opList:r,separateForm:!1,separateCanvas:n}}_getMKDict(e){const t=new Dict(null);e&&t.set("R",e);this.borderColor&&t.set("BC",getPdfColorArray(this.borderColor));this.backgroundColor&&t.set("BG",getPdfColorArray(this.backgroundColor));return t.size>0?t:null}amendSavedDict(e,t){}setValue(e,t,i,a){const{dict:s,ref:r}=function getParentToUpdate(e,t,i){const a=new RefSet,s=e,r={dict:null,ref:null};for(;e instanceof Dict&&!a.has(t);){a.put(t);if(e.has("T"))break;if(!((t=e.getRaw("Parent"))instanceof Ref))return r;e=i.fetch(t)}if(e instanceof Dict&&e!==s){r.dict=e;r.ref=t}return r}(e,this.ref,i);if(s){if(!a.has(r)){const e=s.clone();e.set("V",t);a.put(r,{data:e});return e}}else e.set("V",t);return null}async save(e,t,a,s){const r=a?.get(this.data.id),n=this._buildFlags(r?.noView,r?.noPrint);let g=r?.value,o=r?.rotation;if(g===this.data.fieldValue||void 0===g){if(!this._hasValueFromXFA&&void 0===o&&void 0===n)return;g||=this.data.fieldValue}if(void 0===o&&!this._hasValueFromXFA&&Array.isArray(g)&&Array.isArray(this.data.fieldValue)&&isArrayEqual(g,this.data.fieldValue)&&void 0===n)return;void 0===o&&(o=this.rotation);let c=null;if(!this._needAppearances){c=await this._getAppearance(e,t,C,a);if(null===c&&void 0===n)return}let h=!1;if(c?.needAppearances){h=!0;c=null}const{xref:l}=e,Q=l.fetchIfRef(this.ref);if(!(Q instanceof Dict))return;const E=new Dict(l);for(const e of Q.getKeys())"AP"!==e&&E.set(e,Q.getRaw(e));if(void 0!==n){E.set("F",n);if(null===c&&!h){const e=Q.getRaw("AP");e&&E.set("AP",e)}}const u={path:this.data.fieldName,value:g},d=this.setValue(E,Array.isArray(g)?g.map(stringToAsciiOrUTF16BE):stringToAsciiOrUTF16BE(g),l,s);this.amendSavedDict(a,d||E);const f=this._getMKDict(o);f&&E.set("MK",f);s.put(this.ref,{data:E,xfa:u,needAppearances:h});if(null!==c){const e=l.getNewTemporaryRef(),t=new Dict(l);E.set("AP",t);t.set("N",e);const r=this._getSaveFieldResources(l),n=new StringStream(c),g=n.dict=new Dict(l);g.set("Subtype",Name.get("Form"));g.set("Resources",r);g.set("BBox",[0,0,this.data.rect[2]-this.data.rect[0],this.data.rect[3]-this.data.rect[1]]);const o=this.getRotationMatrix(a);o!==i&&g.set("Matrix",o);s.put(e,{data:n,xfa:null,needAppearances:!1})}E.set("M",`D:${getModificationDate()}`)}async _getAppearance(e,t,i,a){if(this.hasFieldFlag(rA))return null;const s=a?.get(this.data.id);let r,g;if(s){r=s.formattedValue||s.value;g=s.rotation}if(void 0===g&&void 0===r&&!this._needAppearances&&(!this._hasValueFromXFA||this.appearance))return null;const o=this.getBorderAndBackgroundAppearances(a);if(void 0===r){r=this.data.fieldValue;if(!r)return`/Tx BMC q ${o}Q EMC`}Array.isArray(r)&&1===r.length&&(r=r[0]);assert("string"==typeof r,"Expected `value` to be a string.");r=r.trimEnd();if(this.data.combo){const e=this.data.options.find((({exportValue:e})=>r===e));r=e?.displayValue||r}if(""===r)return`/Tx BMC q ${o}Q EMC`;void 0===g&&(g=this.rotation);let c,h=-1;if(this.data.multiLine){c=r.split(/\r\n?|\n/).map((e=>e.normalize("NFC")));h=c.length}else c=[r.replace(/\r\n?|\n/,"").normalize("NFC")];let l=this.data.rect[3]-this.data.rect[1],Q=this.data.rect[2]-this.data.rect[0];90!==g&&270!==g||([Q,l]=[l,Q]);this._defaultAppearance||(this.data.defaultAppearanceData=parseDefaultAppearance(this._defaultAppearance="/Helvetica 0 Tf 0 g"));let E,u,d,f=await WidgetAnnotation._getFontData(e,t,this.data.defaultAppearanceData,this._fieldResources.mergedResources);const p=[];let m=!1;for(const e of c){const t=f.encodeString(e);t.length>1&&(m=!0);p.push(t.join(""))}if(m&&i&C)return{needAppearances:!0};if(m&&this._isOffscreenCanvasSupported){const i=this.data.comb?"monospace":"sans-serif",a=new FakeUnicodeFont(e.xref,i),s=a.createFontResources(c.join("")),n=s.getRaw("Font");if(this._fieldResources.mergedResources.has("Font")){const e=this._fieldResources.mergedResources.get("Font");for(const t of n.getKeys())e.set(t,n.getRaw(t))}else this._fieldResources.mergedResources.set("Font",n);const g=a.fontName.name;f=await WidgetAnnotation._getFontData(e,t,{fontName:g,fontSize:0},s);for(let e=0,t=p.length;e2)return`/Tx BMC q ${o}BT `+E+` 1 0 0 1 ${numberToString(2)} ${numberToString(b)} Tm (${escapeString(p[0])}) Tj ET Q EMC`;return`/Tx BMC q ${o}BT `+E+` 1 0 0 1 0 0 Tm ${this._renderText(p[0],f,u,Q,D,{shift:0},2,b)} ET Q EMC`}static async _getFontData(e,t,i,a){const s=new OperatorList,r={font:null,clone(){return this}},{fontName:n,fontSize:g}=i;await e.handleSetFont(a,[n&&Name.get(n),g],null,s,t,r,null);return r.font}_getTextWidth(e,t){return t.charsToGlyphs(e).reduce(((e,t)=>e+t.width),0)/1e3}_computeFontSize(e,t,i,a,r){let{fontSize:n}=this.data.defaultAppearanceData,g=(n||12)*s,o=Math.round(e/g);if(!n){const roundWithTwoDigits=e=>Math.floor(100*e)/100;if(-1===r){const r=this._getTextWidth(i,a);n=roundWithTwoDigits(Math.min(e/s,t/r));o=1}else{const c=i.split(/\r\n?|\n/),C=[];for(const e of c){const t=a.encodeString(e).join(""),i=a.charsToGlyphs(t),s=a.getCharPositions(t);C.push({line:t,glyphs:i,positions:s})}const isTooBig=i=>{let s=0;for(const r of C){s+=this._splitLine(null,a,i,t,r).length*i;if(s>e)return!0}return!1};o=Math.max(o,r);for(;;){g=e/o;n=roundWithTwoDigits(g/s);if(!isTooBig(n))break;o++}}const{fontName:c,fontColor:C}=this.data.defaultAppearanceData;this._defaultAppearance=function createDefaultAppearance({fontSize:e,fontName:t,fontColor:i}){return`/${escapePDFName(t)} ${e} Tf ${getPdfColor(i,!0)}`}({fontSize:n,fontName:c,fontColor:C})}return[this._defaultAppearance,n,e/o]}_renderText(e,t,i,a,s,r,n,g){let o;if(1===s){o=(a-this._getTextWidth(e,t)*i)/2}else if(2===s){o=a-this._getTextWidth(e,t)*i-n}else o=n;const c=numberToString(o-r.shift);r.shift=o;return`${c} ${g=numberToString(g)} Td (${escapeString(e)}) Tj`}_getSaveFieldResources(e){const{localResources:t,appearanceResources:i,acroFormResources:a}=this._fieldResources,s=this.data.defaultAppearanceData?.fontName;if(!s)return t||Dict.empty;for(const e of[t,i])if(e instanceof Dict){const t=e.get("Font");if(t instanceof Dict&&t.has(s))return e}if(a instanceof Dict){const i=a.get("Font");if(i instanceof Dict&&i.has(s)){const a=new Dict(e);a.set(s,i.getRaw(s));const r=new Dict(e);r.set("Font",a);return Dict.merge({xref:e,dictArray:[r,t],mergeSubDicts:!0})}}return t||Dict.empty}getFieldObject(){return null}}class TextWidgetAnnotation extends WidgetAnnotation{constructor(e){super(e);const{dict:t}=e;if(t.has("PMD")){this.flags|=z;this.data.hidden=!0;warn("Barcodes are not supported")}this.data.hasOwnCanvas=this.data.readOnly&&!this.data.noHTML;this._hasText=!0;"string"!=typeof this.data.fieldValue&&(this.data.fieldValue="");let i=getInheritableProperty({dict:t,key:"Q"});(!Number.isInteger(i)||i<0||i>2)&&(i=null);this.data.textAlignment=i;let a=getInheritableProperty({dict:t,key:"MaxLen"});(!Number.isInteger(a)||a<0)&&(a=0);this.data.maxLen=a;this.data.multiLine=this.hasFieldFlag(sA);this.data.comb=this.hasFieldFlag(hA)&&!this.hasFieldFlag(sA)&&!this.hasFieldFlag(rA)&&!this.hasFieldFlag(IA)&&0!==this.data.maxLen;this.data.doNotScroll=this.hasFieldFlag(CA)}get hasTextContent(){return!!this.appearance&&!this._needAppearances}_getCombAppearance(e,t,i,a,s,r,n,g,o,c,C){const h=s/this.data.maxLen,l=this.getBorderAndBackgroundAppearances(C),Q=[],E=t.getCharPositions(i);for(const[e,t]of E)Q.push(`(${escapeString(i.substring(e,t))}) Tj`);const u=Q.join(` ${numberToString(h)} 0 Td `);return`/Tx BMC q ${l}BT `+e+` 1 0 0 1 ${numberToString(n)} ${numberToString(g+o)} Tm ${u} ET Q EMC`}_getMultilineAppearance(e,t,i,a,s,r,n,g,o,c,C,h){const l=[],Q=s-2*g,E={shift:0};for(let e=0,r=t.length;ea){o.push(e.substring(l,i));l=i;Q=u;c=-1;h=-1}else{Q+=u;c=i;C=s;h=t}else if(Q+u>a)if(-1!==c){o.push(e.substring(l,C));l=C;t=h+1;c=-1;Q=0}else{o.push(e.substring(l,i));l=i;Q=u}else Q+=u}lt?`\\${t}`:"\\s+"));new RegExp(`^\\s*${r}\\s*$`).test(this.data.fieldValue)&&(this.data.textContent=this.data.fieldValue.split("\n"))}getFieldObject(){return{id:this.data.id,value:this.data.fieldValue,defaultValue:this.data.defaultFieldValue||"",multiline:this.data.multiLine,password:this.hasFieldFlag(rA),charLimit:this.data.maxLen,comb:this.data.comb,editable:!this.data.readOnly,hidden:this.data.hidden,name:this.data.fieldName,rect:this.data.rect,actions:this.data.actions,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,type:"text"}}}class ButtonWidgetAnnotation extends WidgetAnnotation{constructor(e){super(e);this.checkedAppearance=null;this.uncheckedAppearance=null;this.data.checkBox=!this.hasFieldFlag(nA)&&!this.hasFieldFlag(gA);this.data.radioButton=this.hasFieldFlag(nA)&&!this.hasFieldFlag(gA);this.data.pushButton=this.hasFieldFlag(gA);this.data.isTooltipOnly=!1;if(this.data.checkBox)this._processCheckBox(e);else if(this.data.radioButton)this._processRadioButton(e);else if(this.data.pushButton){this.data.hasOwnCanvas=!0;this.data.noHTML=!1;this._processPushButton(e)}else warn("Invalid field flags for button widget annotation")}async getOperatorList(e,t,a,s){if(this.data.pushButton)return super.getOperatorList(e,t,a,!1,s);let r=null,n=null;if(s){const e=s.get(this.data.id);r=e?e.value:null;n=e?e.rotation:null}if(null===r&&this.appearance)return super.getOperatorList(e,t,a,s);null==r&&(r=this.data.checkBox?this.data.fieldValue===this.data.exportValue:this.data.fieldValue===this.data.buttonValue);const g=r?this.checkedAppearance:this.uncheckedAppearance;if(g){const r=this.appearance,o=lookupMatrix(g.dict.getArray("Matrix"),i);n&&g.dict.set("Matrix",this.getRotationMatrix(s));this.appearance=g;const c=super.getOperatorList(e,t,a,s);this.appearance=r;g.dict.set("Matrix",o);return c}return{opList:new OperatorList,separateForm:!1,separateCanvas:!1}}async save(e,t,i,a){this.data.checkBox?this._saveCheckbox(e,t,i,a):this.data.radioButton&&this._saveRadioButton(e,t,i,a)}async _saveCheckbox(e,t,i,a){if(!i)return;const s=i.get(this.data.id),r=this._buildFlags(s?.noView,s?.noPrint);let n=s?.rotation,g=s?.value;if(void 0===n&&void 0===r){if(void 0===g)return;if(this.data.fieldValue===this.data.exportValue===g)return}let o=e.xref.fetchIfRef(this.ref);if(!(o instanceof Dict))return;o=o.clone();void 0===n&&(n=this.rotation);void 0===g&&(g=this.data.fieldValue===this.data.exportValue);const c={path:this.data.fieldName,value:g?this.data.exportValue:""},C=Name.get(g?this.data.exportValue:"Off");this.setValue(o,C,e.xref,a);o.set("AS",C);o.set("M",`D:${getModificationDate()}`);void 0!==r&&o.set("F",r);const h=this._getMKDict(n);h&&o.set("MK",h);a.put(this.ref,{data:o,xfa:c,needAppearances:!1})}async _saveRadioButton(e,t,i,a){if(!i)return;const s=i.get(this.data.id),r=this._buildFlags(s?.noView,s?.noPrint);let n=s?.rotation,g=s?.value;if(void 0===n&&void 0===r){if(void 0===g)return;if(this.data.fieldValue===this.data.buttonValue===g)return}let o=e.xref.fetchIfRef(this.ref);if(!(o instanceof Dict))return;o=o.clone();void 0===g&&(g=this.data.fieldValue===this.data.buttonValue);void 0===n&&(n=this.rotation);const c={path:this.data.fieldName,value:g?this.data.buttonValue:""},C=Name.get(g?this.data.buttonValue:"Off");g&&this.setValue(o,C,e.xref,a);o.set("AS",C);o.set("M",`D:${getModificationDate()}`);void 0!==r&&o.set("F",r);const h=this._getMKDict(n);h&&o.set("MK",h);a.put(this.ref,{data:o,xfa:c,needAppearances:!1})}_getDefaultCheckedAppearance(e,t){const i=this.data.rect[2]-this.data.rect[0],a=this.data.rect[3]-this.data.rect[1],s=[0,0,i,a],r=.8*Math.min(i,a);let n,g;if("check"===t){n={width:.755*r,height:.705*r};g="3"}else if("disc"===t){n={width:.791*r,height:.705*r};g="l"}else unreachable(`_getDefaultCheckedAppearance - unsupported type: ${t}`);const o=`q BT /PdfJsZaDb ${r} Tf 0 g ${numberToString((i-n.width)/2)} ${numberToString((a-n.height)/2)} Td (${g}) Tj ET Q`,c=new Dict(e.xref);c.set("FormType",1);c.set("Subtype",Name.get("Form"));c.set("Type",Name.get("XObject"));c.set("BBox",s);c.set("Matrix",[1,0,0,1,0,0]);c.set("Length",o.length);const C=new Dict(e.xref),h=new Dict(e.xref);h.set("PdfJsZaDb",this.fallbackFontDict);C.set("Font",h);c.set("Resources",C);this.checkedAppearance=new StringStream(o);this.checkedAppearance.dict=c;this._streams.push(this.checkedAppearance)}_processCheckBox(e){const t=e.dict.get("AP");if(!(t instanceof Dict))return;const i=t.get("N");if(!(i instanceof Dict))return;const a=this._decodeFormValue(e.dict.get("AS"));"string"==typeof a&&(this.data.fieldValue=a);const s=null!==this.data.fieldValue&&"Off"!==this.data.fieldValue?this.data.fieldValue:"Yes",r=i.getKeys();if(0===r.length)r.push("Off",s);else if(1===r.length)"Off"===r[0]?r.push(s):r.unshift("Off");else if(r.includes(s)){r.length=0;r.push("Off",s)}else{const e=r.find((e=>"Off"!==e));r.length=0;r.push("Off",e)}r.includes(this.data.fieldValue)||(this.data.fieldValue="Off");this.data.exportValue=r[1];const n=i.get(this.data.exportValue);this.checkedAppearance=n instanceof BaseStream?n:null;const g=i.get("Off");this.uncheckedAppearance=g instanceof BaseStream?g:null;this.checkedAppearance?this._streams.push(this.checkedAppearance):this._getDefaultCheckedAppearance(e,"check");this.uncheckedAppearance&&this._streams.push(this.uncheckedAppearance);this._fallbackFontDict=this.fallbackFontDict;null===this.data.defaultFieldValue&&(this.data.defaultFieldValue="Off")}_processRadioButton(e){this.data.buttonValue=null;const t=e.dict.get("Parent");if(t instanceof Dict){this.parent=e.dict.getRaw("Parent");const i=t.get("V");i instanceof Name&&(this.data.fieldValue=this._decodeFormValue(i))}const i=e.dict.get("AP");if(!(i instanceof Dict))return;const a=i.get("N");if(!(a instanceof Dict))return;for(const e of a.getKeys())if("Off"!==e){this.data.buttonValue=this._decodeFormValue(e);break}const s=a.get(this.data.buttonValue);this.checkedAppearance=s instanceof BaseStream?s:null;const r=a.get("Off");this.uncheckedAppearance=r instanceof BaseStream?r:null;this.checkedAppearance?this._streams.push(this.checkedAppearance):this._getDefaultCheckedAppearance(e,"disc");this.uncheckedAppearance&&this._streams.push(this.uncheckedAppearance);this._fallbackFontDict=this.fallbackFontDict;null===this.data.defaultFieldValue&&(this.data.defaultFieldValue="Off")}_processPushButton(e){const{dict:t,annotationGlobals:i}=e;if(t.has("A")||t.has("AA")||this.data.alternativeText){this.data.isTooltipOnly=!t.has("A")&&!t.has("AA");Catalog.parseDestDictionary({destDict:t,resultObj:this.data,docBaseUrl:i.baseUrl,docAttachments:i.attachments})}else warn("Push buttons without action dictionaries are not supported")}getFieldObject(){let e,t="button";if(this.data.checkBox){t="checkbox";e=this.data.exportValue}else if(this.data.radioButton){t="radiobutton";e=this.data.buttonValue}return{id:this.data.id,value:this.data.fieldValue||"Off",defaultValue:this.data.defaultFieldValue,exportValues:e,editable:!this.data.readOnly,name:this.data.fieldName,rect:this.data.rect,hidden:this.data.hidden,actions:this.data.actions,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,type:t}}get fallbackFontDict(){const e=new Dict;e.set("BaseFont",Name.get("ZapfDingbats"));e.set("Type",Name.get("FallbackType"));e.set("Subtype",Name.get("FallbackType"));e.set("Encoding",Name.get("ZapfDingbatsEncoding"));return shadow(this,"fallbackFontDict",e)}}class ChoiceWidgetAnnotation extends WidgetAnnotation{constructor(e){super(e);const{dict:t,xref:i}=e;this.indices=t.getArray("I");this.hasIndices=Array.isArray(this.indices)&&this.indices.length>0;this.data.options=[];const a=getInheritableProperty({dict:t,key:"Opt"});if(Array.isArray(a))for(let e=0,t=a.length;e=0&&t0&&(this.data.options=this.data.fieldValue.map((e=>({exportValue:e,displayValue:e}))));this.data.combo=this.hasFieldFlag(oA);this.data.multiSelect=this.hasFieldFlag(cA);this._hasText=!0}getFieldObject(){const e=this.data.combo?"combobox":"listbox",t=this.data.fieldValue.length>0?this.data.fieldValue[0]:null;return{id:this.data.id,value:t,defaultValue:this.data.defaultFieldValue,editable:!this.data.readOnly,name:this.data.fieldName,rect:this.data.rect,numItems:this.data.fieldValue.length,multipleSelection:this.data.multiSelect,hidden:this.data.hidden,actions:this.data.actions,items:this.data.options,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,type:e}}amendSavedDict(e,t){if(!this.hasIndices)return;let i=e?.get(this.data.id)?.value;Array.isArray(i)||(i=[i]);const a=[],{options:s}=this.data;for(let e=0,t=0,r=s.length;ei){i=a;t=e}}[Q,E]=this._computeFontSize(e,c-4,t,l,-1)}const u=E*s,d=(u-E)/2,f=Math.floor(o/u);let p=0;if(h.length>0){const e=Math.min(...h),t=Math.max(...h);p=Math.max(0,t-f+1);p>e&&(p=e)}const m=Math.min(p+f+1,C),y=["/Tx BMC q",`1 1 ${c} ${o} re W n`];if(h.length){y.push("0.600006 0.756866 0.854904 rg");for(const e of h)p<=e&&ee.trimEnd()));const{coords:e,bbox:t,matrix:i}=FakeUnicodeFont.getFirstPositionInfo(this.rectangle,this.rotation,a);this.data.textPosition=this._transformPoint(e,t,i)}if(this._isOffscreenCanvasSupported){const s=e.dict.get("CA"),r=new FakeUnicodeFont(i,"sans-serif");this.appearance=r.createAppearance(this._contents.str,this.rectangle,this.rotation,a,t,s);this._streams.push(this.appearance)}else warn("FreeTextAnnotation: OffscreenCanvas is not supported, annotation may not render correctly.")}}get hasTextContent(){return this._hasAppearance}static createNewDict(e,t,{apRef:i,ap:a}){const{color:s,fontSize:r,oldAnnotation:n,rect:g,rotation:o,user:c,value:C}=e,h=n||new Dict(t);h.set("Type",Name.get("Annot"));h.set("Subtype",Name.get("FreeText"));if(n){h.set("M",`D:${getModificationDate()}`);h.delete("RC")}else h.set("CreationDate",`D:${getModificationDate()}`);h.set("Rect",g);const l=`/Helv ${r} Tf ${getPdfColor(s,!0)}`;h.set("DA",l);h.set("Contents",stringToAsciiOrUTF16BE(C));h.set("F",4);h.set("Border",[0,0,0]);h.set("Rotate",o);c&&h.set("T",stringToAsciiOrUTF16BE(c));if(i||a){const e=new Dict(t);h.set("AP",e);i?e.set("N",i):e.set("N",a)}return h}static async createNewAppearanceStream(e,t,i){const{baseFontRef:a,evaluator:r,task:n}=i,{color:g,fontSize:o,rect:c,rotation:C,value:h}=e,l=new Dict(t),Q=new Dict(t);if(a)Q.set("Helv",a);else{const e=new Dict(t);e.set("BaseFont",Name.get("Helvetica"));e.set("Type",Name.get("Font"));e.set("Subtype",Name.get("Type1"));e.set("Encoding",Name.get("WinAnsiEncoding"));Q.set("Helv",e)}l.set("Font",Q);const E=await WidgetAnnotation._getFontData(r,n,{fontName:"Helv",fontSize:o},l),[u,d,f,p]=c;let m=f-u,y=p-d;C%180!=0&&([m,y]=[y,m]);const w=h.split("\n"),D=o/1e3;let b=-1/0;const F=[];for(let e of w){const t=E.encodeString(e);if(t.length>1)return null;e=t.join("");F.push(e);let i=0;const a=E.charsToGlyphs(e);for(const e of a)i+=e.width*D;b=Math.max(b,i)}let S=1;b>m&&(S=m/b);let k=1;const R=s*o,N=1*o,G=R*w.length;G>y&&(k=y/G);const M=o*Math.min(S,k);let U,x,L;switch(C){case 0:L=[1,0,0,1];x=[c[0],c[1],m,y];U=[c[0],c[3]-N];break;case 90:L=[0,1,-1,0];x=[c[1],-c[2],m,y];U=[c[1],-c[0]-N];break;case 180:L=[-1,0,0,-1];x=[-c[2],-c[3],m,y];U=[-c[2],-c[1]-N];break;case 270:L=[0,-1,1,0];x=[-c[3],c[0],m,y];U=[-c[3],c[2]-N]}const H=["q",`${L.join(" ")} 0 0 cm`,`${x.join(" ")} re W n`,"BT",`${getPdfColor(g,!0)}`,`0 Tc /Helv ${numberToString(M)} Tf`];H.push(`${U.join(" ")} Td (${escapeString(F[0])}) Tj`);const J=numberToString(R);for(let e=1,t=F.length;e{e.push(`${a[0]} ${a[1]} m`,`${a[2]} ${a[3]} l`,"S");return[t[0]-o,t[2]+o,t[7]-o,t[3]+o]}})}}}class SquareAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:i}=e;this.data.annotationType=M;this.data.hasOwnCanvas=this.data.noRotate;this.data.noHTML=!1;if(!this.appearance){const e=this.color?getPdfColorArray(this.color):[0,0,0],a=t.get("CA"),s=getRgbColor(t.getArray("IC"),null),r=s?getPdfColorArray(s):null,n=r?a:null;if(0===this.borderStyle.width&&!r)return;this._setDefaultAppearance({xref:i,extra:`${this.borderStyle.width} w`,strokeColor:e,fillColor:r,strokeAlpha:a,fillAlpha:n,pointsCallback:(e,t)=>{const i=t[4]+this.borderStyle.width/2,a=t[5]+this.borderStyle.width/2,s=t[6]-t[4]-this.borderStyle.width,n=t[3]-t[7]-this.borderStyle.width;e.push(`${i} ${a} ${s} ${n} re`);r?e.push("B"):e.push("S");return[t[0],t[2],t[7],t[3]]}})}}}class CircleAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:i}=e;this.data.annotationType=U;if(!this.appearance){const e=this.color?getPdfColorArray(this.color):[0,0,0],a=t.get("CA"),s=getRgbColor(t.getArray("IC"),null),r=s?getPdfColorArray(s):null,n=r?a:null;if(0===this.borderStyle.width&&!r)return;const g=4/3*Math.tan(Math.PI/8);this._setDefaultAppearance({xref:i,extra:`${this.borderStyle.width} w`,strokeColor:e,fillColor:r,strokeAlpha:a,fillAlpha:n,pointsCallback:(e,t)=>{const i=t[0]+this.borderStyle.width/2,a=t[1]-this.borderStyle.width/2,s=t[6]-this.borderStyle.width/2,n=t[7]+this.borderStyle.width/2,o=i+(s-i)/2,c=a+(n-a)/2,C=(s-i)/2*g,h=(n-a)/2*g;e.push(`${o} ${n} m`,`${o+C} ${n} ${s} ${c+h} ${s} ${c} c`,`${s} ${c-h} ${o+C} ${a} ${o} ${a} c`,`${o-C} ${a} ${i} ${c-h} ${i} ${c} c`,`${i} ${c+h} ${o-C} ${n} ${o} ${n} c`,"h");r?e.push("B"):e.push("S");return[t[0],t[2],t[7],t[3]]}})}}}class PolylineAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:i}=e;this.data.annotationType=L;this.data.hasOwnCanvas=this.data.noRotate;this.data.noHTML=!1;this.data.vertices=null;if(!(this instanceof PolygonAnnotation)){this.setLineEndings(t.getArray("LE"));this.data.lineEndings=this.lineEndings}const a=t.getArray("Vertices");if(!isNumberArray(a,null))return;const s=this.data.vertices=Float32Array.from(a);if(!this.appearance){const e=this.color?getPdfColorArray(this.color):[0,0,0],a=t.get("CA"),r=this.borderStyle.width||1,n=2*r,g=[1/0,1/0,-1/0,-1/0];for(let e=0,t=s.length;e{for(let t=0,i=s.length;t{for(const t of this.data.inkLists){for(let i=0,a=t.length;ie/255)));Q.set("CA",n);const u=new Dict(t);Q.set("AP",u);i?u.set("N",i):u.set("N",a);return Q}static async createNewAppearanceStream(e,t,i){if(e.outlines)return this.createNewAppearanceStreamForHighlight(e,t,i);const{color:a,rect:s,paths:r,thickness:n,opacity:g}=e,o=[`${n} w 1 J 1 j`,`${getPdfColor(a,!1)}`];1!==g&&o.push("/R0 gs");for(const e of r.lines){o.push(`${numberToString(e[4])} ${numberToString(e[5])} m`);for(let t=6,i=e.length;t{e.push(`${t[0]} ${t[1]} m`,`${t[2]} ${t[3]} l`,`${t[6]} ${t[7]} l`,`${t[4]} ${t[5]} l`,"f");return[t[0],t[2],t[7],t[3]]}})}}else this.data.popupRef=null}static createNewDict(e,t,{apRef:i,ap:a}){const{color:s,oldAnnotation:r,opacity:n,rect:g,rotation:o,user:c,quadPoints:C}=e,h=r||new Dict(t);h.set("Type",Name.get("Annot"));h.set("Subtype",Name.get("Highlight"));h.set(r?"M":"CreationDate",`D:${getModificationDate()}`);h.set("CreationDate",`D:${getModificationDate()}`);h.set("Rect",g);h.set("F",4);h.set("Border",[0,0,0]);h.set("Rotate",o);h.set("QuadPoints",C);h.set("C",Array.from(s,(e=>e/255)));h.set("CA",n);c&&h.set("T",stringToAsciiOrUTF16BE(c));if(i||a){const e=new Dict(t);h.set("AP",e);e.set("N",i||a)}return h}static async createNewAppearanceStream(e,t,i){const{color:a,rect:s,outlines:r,opacity:n}=e,g=[`${getPdfColor(a,!0)}`,"/R0 gs"],o=[];for(const e of r){o.length=0;o.push(`${numberToString(e[0])} ${numberToString(e[1])} m`);for(let t=2,i=e.length;t{e.push(`${t[4]} ${t[5]+1.3} m`,`${t[6]} ${t[7]+1.3} l`,"S");return[t[0],t[2],t[7],t[3]]}})}}else this.data.popupRef=null}}class SquigglyAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:i}=e;this.data.annotationType=Y;if(this.data.quadPoints=getQuadPoints(t,null)){if(!this.appearance){const e=this.color?getPdfColorArray(this.color):[0,0,0],a=t.get("CA");this._setDefaultAppearance({xref:i,extra:"[] 0 d 1 w",strokeColor:e,strokeAlpha:a,pointsCallback:(e,t)=>{const i=(t[1]-t[5])/6;let a=i,s=t[4];const r=t[5],n=t[6];e.push(`${s} ${r+a} m`);do{s+=2;a=0===a?i:0;e.push(`${s} ${r+a} l`)}while(s{e.push((t[0]+t[4])/2+" "+(t[1]+t[5])/2+" m",(t[2]+t[6])/2+" "+(t[3]+t[7])/2+" l","S");return[t[0],t[2],t[7],t[3]]}})}}else this.data.popupRef=null}}class StampAnnotation extends MarkupAnnotation{#T;constructor(e){super(e);this.data.annotationType=K;this.#T=this.data.hasOwnCanvas=this.data.noRotate;this.data.isEditable=!this.data.noHTML;this.data.noHTML=!1}mustBeViewedWhenEditing(e,t=null){if(e){if(!this.data.isEditable)return!1;this.#T=this.data.hasOwnCanvas;this.data.hasOwnCanvas=!0;return!0}this.data.hasOwnCanvas=this.#T;return!t?.has(this.data.id)}static async createImage(e,t){const{width:i,height:a}=e,s=new OffscreenCanvas(i,a),r=s.getContext("2d",{alpha:!0});r.drawImage(e,0,0);const n=r.getImageData(0,0,i,a).data,g=new Uint32Array(n.buffer),o=g.some(FeatureTest.isLittleEndian?e=>e>>>24!=255:e=>!!(255&~e));if(o){r.fillStyle="white";r.fillRect(0,0,i,a);r.drawImage(e,0,0)}const c=s.convertToBlob({type:"image/jpeg",quality:1}).then((e=>e.arrayBuffer())),C=Name.get("XObject"),h=Name.get("Image"),l=new Dict(t);l.set("Type",C);l.set("Subtype",h);l.set("BitsPerComponent",8);l.set("ColorSpace",Name.get("DeviceRGB"));l.set("Filter",Name.get("DCTDecode"));l.set("BBox",[0,0,i,a]);l.set("Width",i);l.set("Height",a);let Q=null;if(o){const e=new Uint8Array(g.length);if(FeatureTest.isLittleEndian)for(let t=0,i=g.length;t>>24;else for(let t=0,i=g.length;t=0&&r<=1?r:null}}class DecryptStream extends DecodeStream{constructor(e,t,i){super(t);this.str=e;this.dict=e.dict;this.decrypt=i;this.nextChunk=null;this.initialized=!1}readBlock(){let e;if(this.initialized)e=this.nextChunk;else{e=this.str.getBytes(512);this.initialized=!0}if(!e?.length){this.eof=!0;return}this.nextChunk=this.str.getBytes(512);const t=this.nextChunk?.length>0;e=(0,this.decrypt)(e,!t);const i=this.bufferLength,a=i+e.length;this.ensureBuffer(a).set(e,i);this.bufferLength=a}}class ARCFourCipher{constructor(e){this.a=0;this.b=0;const t=new Uint8Array(256),i=e.length;for(let e=0;e<256;++e)t[e]=e;for(let a=0,s=0;a<256;++a){const r=t[a];s=s+r+e[a%i]&255;t[a]=t[s];t[s]=r}this.s=t}encryptBlock(e){let t=this.a,i=this.b;const a=this.s,s=e.length,r=new Uint8Array(s);for(let n=0;n>5&255;C[h++]=s>>13&255;C[h++]=s>>21&255;C[h++]=s>>>29&255;C[h++]=0;C[h++]=0;C[h++]=0;const E=new Int32Array(16);for(h=0;h>>32-g)|0;s=r}r=r+s|0;n=n+c|0;g=g+Q|0;o=o+u|0}return new Uint8Array([255&r,r>>8&255,r>>16&255,r>>>24&255,255&n,n>>8&255,n>>16&255,n>>>24&255,255&g,g>>8&255,g>>16&255,g>>>24&255,255&o,o>>8&255,o>>16&255,o>>>24&255])}}();class Word64{constructor(e,t){this.high=0|e;this.low=0|t}and(e){this.high&=e.high;this.low&=e.low}xor(e){this.high^=e.high;this.low^=e.low}or(e){this.high|=e.high;this.low|=e.low}shiftRight(e){if(e>=32){this.low=this.high>>>e-32|0;this.high=0}else{this.low=this.low>>>e|this.high<<32-e;this.high=this.high>>>e|0}}shiftLeft(e){if(e>=32){this.high=this.low<>>32-e;this.low<<=e}}rotateRight(e){let t,i;if(32&e){i=this.low;t=this.high}else{t=this.low;i=this.high}e&=31;this.low=t>>>e|i<<32-e;this.high=i>>>e|t<<32-e}not(){this.high=~this.high;this.low=~this.low}add(e){const t=(this.low>>>0)+(e.low>>>0);let i=(this.high>>>0)+(e.high>>>0);t>4294967295&&(i+=1);this.low=0|t;this.high=0|i}copyTo(e,t){e[t]=this.high>>>24&255;e[t+1]=this.high>>16&255;e[t+2]=this.high>>8&255;e[t+3]=255&this.high;e[t+4]=this.low>>>24&255;e[t+5]=this.low>>16&255;e[t+6]=this.low>>8&255;e[t+7]=255&this.low}assign(e){this.high=e.high;this.low=e.low}}const Ag=function calculateSHA256Closure(){function rotr(e,t){return e>>>t|e<<32-t}function ch(e,t,i){return e&t^~e&i}function maj(e,t,i){return e&t^e&i^t&i}function sigma(e){return rotr(e,2)^rotr(e,13)^rotr(e,22)}function sigmaPrime(e){return rotr(e,6)^rotr(e,11)^rotr(e,25)}function littleSigma(e){return rotr(e,7)^rotr(e,18)^e>>>3}const e=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];return function hash(t,i,a){let s=1779033703,r=3144134277,n=1013904242,g=2773480762,o=1359893119,c=2600822924,C=528734635,h=1541459225;const l=64*Math.ceil((a+9)/64),Q=new Uint8Array(l);let E,u;for(E=0;E>>29&255;Q[E++]=a>>21&255;Q[E++]=a>>13&255;Q[E++]=a>>5&255;Q[E++]=a<<3&255;const f=new Uint32Array(64);for(E=0;E>>10)+f[u-7]+littleSigma(f[u-15])+f[u-16]|0;let t,i,a=s,l=r,d=n,m=g,y=o,w=c,D=C,b=h;for(u=0;u<64;++u){t=b+sigmaPrime(y)+ch(y,w,D)+e[u]+f[u];i=sigma(a)+maj(a,l,d);b=D;D=w;w=y;y=m+t|0;m=d;d=l;l=a;a=t+i|0}s=s+a|0;r=r+l|0;n=n+d|0;g=g+m|0;o=o+y|0;c=c+w|0;C=C+D|0;h=h+b|0}var p;return new Uint8Array([s>>24&255,s>>16&255,s>>8&255,255&s,r>>24&255,r>>16&255,r>>8&255,255&r,n>>24&255,n>>16&255,n>>8&255,255&n,g>>24&255,g>>16&255,g>>8&255,255&g,o>>24&255,o>>16&255,o>>8&255,255&o,c>>24&255,c>>16&255,c>>8&255,255&c,C>>24&255,C>>16&255,C>>8&255,255&C,h>>24&255,h>>16&255,h>>8&255,255&h])}}(),eg=function calculateSHA512Closure(){function ch(e,t,i,a,s){e.assign(t);e.and(i);s.assign(t);s.not();s.and(a);e.xor(s)}function maj(e,t,i,a,s){e.assign(t);e.and(i);s.assign(t);s.and(a);e.xor(s);s.assign(i);s.and(a);e.xor(s)}function sigma(e,t,i){e.assign(t);e.rotateRight(28);i.assign(t);i.rotateRight(34);e.xor(i);i.assign(t);i.rotateRight(39);e.xor(i)}function sigmaPrime(e,t,i){e.assign(t);e.rotateRight(14);i.assign(t);i.rotateRight(18);e.xor(i);i.assign(t);i.rotateRight(41);e.xor(i)}function littleSigma(e,t,i){e.assign(t);e.rotateRight(1);i.assign(t);i.rotateRight(8);e.xor(i);i.assign(t);i.shiftRight(7);e.xor(i)}function littleSigmaPrime(e,t,i){e.assign(t);e.rotateRight(19);i.assign(t);i.rotateRight(61);e.xor(i);i.assign(t);i.shiftRight(6);e.xor(i)}const e=[new Word64(1116352408,3609767458),new Word64(1899447441,602891725),new Word64(3049323471,3964484399),new Word64(3921009573,2173295548),new Word64(961987163,4081628472),new Word64(1508970993,3053834265),new Word64(2453635748,2937671579),new Word64(2870763221,3664609560),new Word64(3624381080,2734883394),new Word64(310598401,1164996542),new Word64(607225278,1323610764),new Word64(1426881987,3590304994),new Word64(1925078388,4068182383),new Word64(2162078206,991336113),new Word64(2614888103,633803317),new Word64(3248222580,3479774868),new Word64(3835390401,2666613458),new Word64(4022224774,944711139),new Word64(264347078,2341262773),new Word64(604807628,2007800933),new Word64(770255983,1495990901),new Word64(1249150122,1856431235),new Word64(1555081692,3175218132),new Word64(1996064986,2198950837),new Word64(2554220882,3999719339),new Word64(2821834349,766784016),new Word64(2952996808,2566594879),new Word64(3210313671,3203337956),new Word64(3336571891,1034457026),new Word64(3584528711,2466948901),new Word64(113926993,3758326383),new Word64(338241895,168717936),new Word64(666307205,1188179964),new Word64(773529912,1546045734),new Word64(1294757372,1522805485),new Word64(1396182291,2643833823),new Word64(1695183700,2343527390),new Word64(1986661051,1014477480),new Word64(2177026350,1206759142),new Word64(2456956037,344077627),new Word64(2730485921,1290863460),new Word64(2820302411,3158454273),new Word64(3259730800,3505952657),new Word64(3345764771,106217008),new Word64(3516065817,3606008344),new Word64(3600352804,1432725776),new Word64(4094571909,1467031594),new Word64(275423344,851169720),new Word64(430227734,3100823752),new Word64(506948616,1363258195),new Word64(659060556,3750685593),new Word64(883997877,3785050280),new Word64(958139571,3318307427),new Word64(1322822218,3812723403),new Word64(1537002063,2003034995),new Word64(1747873779,3602036899),new Word64(1955562222,1575990012),new Word64(2024104815,1125592928),new Word64(2227730452,2716904306),new Word64(2361852424,442776044),new Word64(2428436474,593698344),new Word64(2756734187,3733110249),new Word64(3204031479,2999351573),new Word64(3329325298,3815920427),new Word64(3391569614,3928383900),new Word64(3515267271,566280711),new Word64(3940187606,3454069534),new Word64(4118630271,4000239992),new Word64(116418474,1914138554),new Word64(174292421,2731055270),new Word64(289380356,3203993006),new Word64(460393269,320620315),new Word64(685471733,587496836),new Word64(852142971,1086792851),new Word64(1017036298,365543100),new Word64(1126000580,2618297676),new Word64(1288033470,3409855158),new Word64(1501505948,4234509866),new Word64(1607167915,987167468),new Word64(1816402316,1246189591)];return function hash(t,i,a,s=!1){let r,n,g,o,c,C,h,l;if(s){r=new Word64(3418070365,3238371032);n=new Word64(1654270250,914150663);g=new Word64(2438529370,812702999);o=new Word64(355462360,4144912697);c=new Word64(1731405415,4290775857);C=new Word64(2394180231,1750603025);h=new Word64(3675008525,1694076839);l=new Word64(1203062813,3204075428)}else{r=new Word64(1779033703,4089235720);n=new Word64(3144134277,2227873595);g=new Word64(1013904242,4271175723);o=new Word64(2773480762,1595750129);c=new Word64(1359893119,2917565137);C=new Word64(2600822924,725511199);h=new Word64(528734635,4215389547);l=new Word64(1541459225,327033209)}const Q=128*Math.ceil((a+17)/128),E=new Uint8Array(Q);let u,d;for(u=0;u>>29&255;E[u++]=a>>21&255;E[u++]=a>>13&255;E[u++]=a>>5&255;E[u++]=a<<3&255;const p=new Array(80);for(u=0;u<80;u++)p[u]=new Word64(0,0);let m=new Word64(0,0),y=new Word64(0,0),w=new Word64(0,0),D=new Word64(0,0),b=new Word64(0,0),F=new Word64(0,0),S=new Word64(0,0),k=new Word64(0,0);const R=new Word64(0,0),N=new Word64(0,0),G=new Word64(0,0),M=new Word64(0,0);let U,x;for(u=0;u=1;--e){i=r[13];r[13]=r[9];r[9]=r[5];r[5]=r[1];r[1]=i;i=r[14];a=r[10];r[14]=r[6];r[10]=r[2];r[6]=i;r[2]=a;i=r[15];a=r[11];s=r[7];r[15]=r[3];r[11]=i;r[7]=a;r[3]=s;for(let e=0;e<16;++e)r[e]=this._inv_s[r[e]];for(let i=0,a=16*e;i<16;++i,++a)r[i]^=t[a];for(let e=0;e<16;e+=4){const t=this._mix[r[e]],a=this._mix[r[e+1]],s=this._mix[r[e+2]],n=this._mix[r[e+3]];i=t^a>>>8^a<<24^s>>>16^s<<16^n>>>24^n<<8;r[e]=i>>>24&255;r[e+1]=i>>16&255;r[e+2]=i>>8&255;r[e+3]=255&i}}i=r[13];r[13]=r[9];r[9]=r[5];r[5]=r[1];r[1]=i;i=r[14];a=r[10];r[14]=r[6];r[10]=r[2];r[6]=i;r[2]=a;i=r[15];a=r[11];s=r[7];r[15]=r[3];r[11]=i;r[7]=a;r[3]=s;for(let e=0;e<16;++e){r[e]=this._inv_s[r[e]];r[e]^=t[e]}return r}_encrypt(e,t){const i=this._s;let a,s,r;const n=new Uint8Array(16);n.set(e);for(let e=0;e<16;++e)n[e]^=t[e];for(let e=1;e=a;--i)if(e[i]!==t){t=0;break}g-=t;r[r.length-1]=e.subarray(0,16-t)}}const o=new Uint8Array(g);for(let e=0,t=0,i=r.length;e=256&&(g=255&(27^g))}for(let t=0;t<4;++t){i[e]=a^=i[e-32];e++;i[e]=s^=i[e-32];e++;i[e]=r^=i[e-32];e++;i[e]=n^=i[e-32];e++}}return i}}class PDF17{checkOwnerPassword(e,t,i,a){const s=new Uint8Array(e.length+56);s.set(e,0);s.set(t,e.length);s.set(i,e.length+t.length);return isArrayEqual(Ag(s,0,s.length),a)}checkUserPassword(e,t,i){const a=new Uint8Array(e.length+8);a.set(e,0);a.set(t,e.length);return isArrayEqual(Ag(a,0,a.length),i)}getOwnerKey(e,t,i,a){const s=new Uint8Array(e.length+56);s.set(e,0);s.set(t,e.length);s.set(i,e.length+t.length);const r=Ag(s,0,s.length);return new AES256Cipher(r).decryptBlock(a,!1,new Uint8Array(16))}getUserKey(e,t,i){const a=new Uint8Array(e.length+8);a.set(e,0);a.set(t,e.length);const s=Ag(a,0,a.length);return new AES256Cipher(s).decryptBlock(i,!1,new Uint8Array(16))}}class PDF20{_hash(e,t,i){let a=Ag(t,0,t.length).subarray(0,32),s=[0],r=0;for(;r<64||s.at(-1)>r-32;){const t=e.length+a.length+i.length,c=new Uint8Array(t);let C=0;c.set(e,C);C+=e.length;c.set(a,C);C+=a.length;c.set(i,C);const h=new Uint8Array(64*t);for(let e=0,i=0;e<64;e++,i+=t)h.set(c,i);s=new AES128Cipher(a.subarray(0,16)).encrypt(h,a.subarray(16,32));const l=s.slice(0,16).reduce(((e,t)=>e+t),0)%3;0===l?a=Ag(s,0,s.length):1===l?a=(n=s,g=0,o=s.length,eg(n,g,o,!0)):2===l&&(a=eg(s,0,s.length));r++}var n,g,o;return a.subarray(0,32)}checkOwnerPassword(e,t,i,a){const s=new Uint8Array(e.length+56);s.set(e,0);s.set(t,e.length);s.set(i,e.length+t.length);return isArrayEqual(this._hash(e,s,i),a)}checkUserPassword(e,t,i){const a=new Uint8Array(e.length+8);a.set(e,0);a.set(t,e.length);return isArrayEqual(this._hash(e,a,[]),i)}getOwnerKey(e,t,i,a){const s=new Uint8Array(e.length+56);s.set(e,0);s.set(t,e.length);s.set(i,e.length+t.length);const r=this._hash(e,s,i);return new AES256Cipher(r).decryptBlock(a,!1,new Uint8Array(16))}getUserKey(e,t,i){const a=new Uint8Array(e.length+8);a.set(e,0);a.set(t,e.length);const s=this._hash(e,a,[]);return new AES256Cipher(s).decryptBlock(i,!1,new Uint8Array(16))}}class CipherTransform{constructor(e,t){this.StringCipherConstructor=e;this.StreamCipherConstructor=t}createStream(e,t){const i=new this.StreamCipherConstructor;return new DecryptStream(e,t,(function cipherTransformDecryptStream(e,t){return i.decryptBlock(e,t)}))}decryptString(e){const t=new this.StringCipherConstructor;let i=stringToBytes(e);i=t.decryptBlock(i,!0);return bytesToString(i)}encryptString(e){const t=new this.StringCipherConstructor;if(t instanceof AESBaseCipher){const i=16-e.length%16;e+=String.fromCharCode(i).repeat(i);const a=new Uint8Array(16);if("undefined"!=typeof crypto)crypto.getRandomValues(a);else for(let e=0;e<16;e++)a[e]=Math.floor(256*Math.random());let s=stringToBytes(e);s=t.encrypt(s,a);const r=new Uint8Array(16+s.length);r.set(a);r.set(s,16);return bytesToString(r)}let i=stringToBytes(e);i=t.encrypt(i);return bytesToString(i)}}class CipherTransformFactory{static#q=new Uint8Array([40,191,78,94,78,117,138,65,100,0,78,86,255,250,1,8,46,46,0,182,208,104,62,128,47,12,169,254,100,83,105,122]);#O(e,t,i,a,s,r,n,g,o,c,C,h){if(t){const e=Math.min(127,t.length);t=t.subarray(0,e)}else t=[];const l=6===e?new PDF20:new PDF17;return l.checkUserPassword(t,g,n)?l.getUserKey(t,o,C):t.length&&l.checkOwnerPassword(t,a,r,i)?l.getOwnerKey(t,s,r,c):null}#P(e,t,i,a,s,r,n,g){const o=40+i.length+e.length,c=new Uint8Array(o);let C,h,l=0;if(t){h=Math.min(32,t.length);for(;l>8&255;c[l++]=s>>16&255;c[l++]=s>>>24&255;for(C=0,h=e.length;C=4&&!g){c[l++]=255;c[l++]=255;c[l++]=255;c[l++]=255}let Q=$n(c,0,l);const E=n>>3;if(r>=3)for(C=0;C<50;++C)Q=$n(Q,0,E);const u=Q.subarray(0,E);let d,f;if(r>=3){for(l=0;l<32;++l)c[l]=CipherTransformFactory.#q[l];for(C=0,h=e.length;C>3;if(i>=3)for(g=0;g<50;++g)o=$n(o,0,o.length);let C,h;if(i>=3){h=t;const e=new Uint8Array(c);for(g=19;g>=0;g--){for(let t=0;t>8&255;s[n++]=e>>16&255;s[n++]=255&t;s[n++]=t>>8&255;if(a){s[n++]=115;s[n++]=65;s[n++]=108;s[n++]=84}return $n(s,0,n).subarray(0,Math.min(i.length+5,16))}#X(e,t,i,a,s){if(!(t instanceof Name))throw new FormatError("Invalid crypt filter name.");const r=this,n=e.get(t.name),g=n?.get("CFM");if(!g||"None"===g.name)return function(){return new NullCipher};if("V2"===g.name)return function(){return new ARCFourCipher(r.#j(i,a,s,!1))};if("AESV2"===g.name)return function(){return new AES128Cipher(r.#j(i,a,s,!0))};if("AESV3"===g.name)return function(){return new AES256Cipher(s)};throw new FormatError("Unknown crypto method")}constructor(e,t,i){const a=e.get("Filter");if(!isName(a,"Standard"))throw new FormatError("unknown encryption method");this.filterName=a.name;this.dict=e;const s=e.get("V");if(!Number.isInteger(s)||1!==s&&2!==s&&4!==s&&5!==s)throw new FormatError("unsupported encryption algorithm");this.algorithm=s;let r=e.get("Length");if(!r)if(s<=3)r=40;else{const t=e.get("CF"),i=e.get("StmF");if(t instanceof Dict&&i instanceof Name){t.suppressEncryption=!0;const e=t.get(i.name);r=e?.get("Length")||128;r<40&&(r<<=3)}}if(!Number.isInteger(r)||r<40||r%8!=0)throw new FormatError("invalid key length");const n=stringToBytes(e.get("O")),g=stringToBytes(e.get("U")),o=n.subarray(0,32),c=g.subarray(0,32),C=e.get("P"),h=e.get("R"),l=(4===s||5===s)&&!1!==e.get("EncryptMetadata");this.encryptMetadata=l;const Q=stringToBytes(t);let E,u;if(i){if(6===h)try{i=utf8StringToString(i)}catch{warn("CipherTransformFactory: Unable to convert UTF8 encoded password.")}E=stringToBytes(i)}if(5!==s)u=this.#P(Q,E,o,c,C,h,r,l);else{const t=n.subarray(32,40),i=n.subarray(40,48),a=g.subarray(0,48),s=g.subarray(32,40),r=g.subarray(40,48),C=stringToBytes(e.get("OE")),l=stringToBytes(e.get("UE")),Q=stringToBytes(e.get("Perms"));u=this.#O(h,E,o,t,i,a,c,s,r,C,l,Q)}if(!u&&!i)throw new PasswordException("No password given",rt);if(!u&&i){const e=this.#W(E,o,h,r);u=this.#P(Q,e,o,c,C,h,r,l)}if(!u)throw new PasswordException("Incorrect Password",nt);this.encryptionKey=u;if(s>=4){const t=e.get("CF");t instanceof Dict&&(t.suppressEncryption=!0);this.cf=t;this.stmf=e.get("StmF")||Name.get("Identity");this.strf=e.get("StrF")||Name.get("Identity");this.eff=e.get("EFF")||this.stmf}}createCipherTransform(e,t){if(4===this.algorithm||5===this.algorithm)return new CipherTransform(this.#X(this.cf,this.strf,e,t,this.encryptionKey),this.#X(this.cf,this.stmf,e,t,this.encryptionKey));const i=this.#j(e,t,this.encryptionKey,!1),cipherConstructor=function(){return new ARCFourCipher(i)};return new CipherTransform(cipherConstructor,cipherConstructor)}}function decodeString(e){try{return stringToUTF8String(e)}catch(t){warn(`UTF-8 decoding failed: "${t}".`);return e}}class DatasetXMLParser extends SimpleXMLParser{constructor(e){super(e);this.node=null}onEndElement(e){const t=super.onEndElement(e);if(t&&"xfa:datasets"===e){this.node=t;throw new Error("Aborting DatasetXMLParser.")}}}class DatasetReader{constructor(e){if(e.datasets)this.node=new SimpleXMLParser({hasAttributes:!0}).parseFromString(e.datasets).documentElement;else{const t=new DatasetXMLParser({hasAttributes:!0});try{t.parseFromString(e["xdp:xdp"])}catch{}this.node=t.node}}getValue(e){if(!this.node||!e)return"";const t=this.node.searchNode(parseXFAPath(e),0);if(!t)return"";const i=t.firstChild;return"value"===i?.nodeName?t.children.map((e=>decodeString(e.textContent))):decodeString(t.textContent)}}class XRef{#Z=null;constructor(e,t){this.stream=e;this.pdfManager=t;this.entries=[];this._xrefStms=new Set;this._cacheMap=new Map;this._pendingRefs=new RefSet;this._newPersistentRefNum=null;this._newTemporaryRefNum=null;this._persistentRefsCache=null}getNewPersistentRef(e){null===this._newPersistentRefNum&&(this._newPersistentRefNum=this.entries.length||1);const t=this._newPersistentRefNum++;this._cacheMap.set(t,e);return Ref.get(t,0)}getNewTemporaryRef(){if(null===this._newTemporaryRefNum){this._newTemporaryRefNum=this.entries.length||1;if(this._newPersistentRefNum){this._persistentRefsCache=new Map;for(let e=this._newTemporaryRefNum;e0;){const[n,g]=r;if(!Number.isInteger(n)||!Number.isInteger(g))throw new FormatError(`Invalid XRef range fields: ${n}, ${g}`);if(!Number.isInteger(i)||!Number.isInteger(a)||!Number.isInteger(s))throw new FormatError(`Invalid XRef entry fields length: ${n}, ${g}`);for(let r=t.entryNum;r=e.length);){i+=String.fromCharCode(a);a=e[t]}return i}function skipUntil(e,t,i){const a=i.length,s=e.length;let r=0;for(;t=a)break;t++;r++}return r}const e=/\b(endobj|\d+\s+\d+\s+obj|xref|trailer\s*<<)\b/g,t=/\b(startxref|\d+\s+\d+\s+obj)\b/g,i=/^(\d+)\s+(\d+)\s+obj\b/,a=new Uint8Array([116,114,97,105,108,101,114]),s=new Uint8Array([115,116,97,114,116,120,114,101,102]),r=new Uint8Array([47,88,82,101,102]);this.entries.length=0;this._cacheMap.clear();const n=this.stream;n.pos=0;const g=n.getBytes(),o=bytesToString(g),c=g.length;let C=n.start;const h=[],l=[];for(;C=c)break;Q=g[C]}while(10!==Q&&13!==Q);continue}const E=readToken(g,C);let u;if(E.startsWith("xref")&&(4===E.length||/\s/.test(E[4]))){C+=skipUntil(g,C,a);h.push(C);C+=skipUntil(g,C,s)}else if(u=i.exec(E)){const t=0|u[1],i=0|u[2],a=C+E.length;let s,h=!1;if(this.entries[t]){if(this.entries[t].gen===i)try{new Parser({lexer:new Lexer(n.makeSubStream(a))}).getObj();h=!0}catch(e){e instanceof ParserEOFException?warn(`indexObjects -- checking object (${E}): "${e}".`):h=!0}}else h=!0;h&&(this.entries[t]={offset:C-n.start,gen:i,uncompressed:!0});e.lastIndex=a;const Q=e.exec(o);if(Q){s=e.lastIndex+1-C;if("endobj"!==Q[1]){warn(`indexObjects: Found "${Q[1]}" inside of another "obj", caused by missing "endobj" -- trying to recover.`);s-=Q[1].length+1}}else s=c-C;const d=g.subarray(C,C+s),f=skipUntil(d,0,r);if(f0?Math.max(...this._xrefStms):null)}getEntry(e){const t=this.entries[e];return t&&!t.free&&t.offset?t:null}fetchIfRef(e,t=!1){return e instanceof Ref?this.fetch(e,t):e}fetch(e,t=!1){if(!(e instanceof Ref))throw new Error("ref object is not a reference");const i=e.num,a=this._cacheMap.get(i);if(void 0!==a){a instanceof Dict&&!a.objId&&(a.objId=e.toString());return a}let s=this.getEntry(i);if(null===s){this._cacheMap.set(i,s);return s}if(this._pendingRefs.has(e)){this._pendingRefs.remove(e);warn(`Ignoring circular reference: ${e}.`);return lt}this._pendingRefs.put(e);try{s=s.uncompressed?this.fetchUncompressed(e,s,t):this.fetchCompressed(e,s,t);this._pendingRefs.remove(e)}catch(t){this._pendingRefs.remove(e);throw t}s instanceof Dict?s.objId=e.toString():s instanceof BaseStream&&(s.dict.objId=e.toString());return s}fetchUncompressed(e,t,i=!1){const a=e.gen;let s=e.num;if(t.gen!==a){const r=`Inconsistent generation in XRef: ${e}`;if(this._generationFallback&&t.gen0&&t[3]-t[1]>0)return t;warn(`Empty, or invalid, /${e} entry.`)}return null}get mediaBox(){return shadow(this,"mediaBox",this._getBoundingBox("MediaBox")||tg)}get cropBox(){return shadow(this,"cropBox",this._getBoundingBox("CropBox")||this.mediaBox)}get userUnit(){const e=this.pageDict.get("UserUnit");return shadow(this,"userUnit","number"==typeof e&&e>0?e:1)}get view(){const{cropBox:e,mediaBox:t}=this;if(e!==t&&!isArrayEqual(e,t)){const i=Util.intersect(e,t);if(i&&i[2]-i[0]>0&&i[3]-i[1]>0)return shadow(this,"view",i);warn("Empty /CropBox and /MediaBox intersection.")}return shadow(this,"view",t)}get rotate(){let e=this._getInheritableProperty("Rotate")||0;e%90!=0?e=0:e>=360?e%=360:e<0&&(e=(e%360+360)%360);return shadow(this,"rotate",e)}_onSubStreamError(e,t){if(!this.evaluatorOptions.ignoreErrors)throw e;warn(`getContentStream - ignoring sub-stream (${t}): "${e}".`)}getContentStream(){return this.pdfManager.ensure(this,"content").then((e=>e instanceof BaseStream?e:Array.isArray(e)?new StreamsSequenceStream(e,this._onSubStreamError.bind(this)):new NullStream))}get xfaData(){return shadow(this,"xfaData",this.xfaFactory?{bbox:this.xfaFactory.getBoundingBox(this.pageIndex)}:null)}async#V(e,t,i){const a=[];for(const s of e)if(s.id){const e=Ref.fromString(s.id);if(!e){warn(`A non-linked annotation cannot be modified: ${s.id}`);continue}if(s.deleted){t.put(e,e);if(s.popupRef){const e=Ref.fromString(s.popupRef);e&&t.put(e,e)}continue}i?.put(e);s.ref=e;a.push(this.xref.fetchAsync(e).then((e=>{e instanceof Dict&&(s.oldAnnotation=e.clone())}),(()=>{warn(`Cannot fetch \`oldAnnotation\` for: ${e}.`)})));delete s.id}await Promise.all(a)}async saveNewAnnotations(e,t,i,a,s){if(this.xfaFactory)throw new Error("XFA: Cannot save new annotations.");const r=new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions}),n=new RefSetCache,g=new RefSet;await this.#V(i,n,g);const o=this.pageDict,c=this.annotations.filter((e=>!(e instanceof Ref&&n.has(e)))),C=await AnnotationFactory.saveNewAnnotations(r,t,i,a,s);for(const{ref:e}of C.annotations)e instanceof Ref&&!g.has(e)&&c.push(e);const h=o.clone();h.set("Annots",c);s.put(this.ref,{data:h});for(const e of n)s.put(e,{data:null})}save(e,t,i,a){const s=new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions});return this._parsedAnnotations.then((function(e){const r=[];for(const n of e)r.push(n.save(s,t,i,a).catch((function(e){warn(`save - ignoring annotation data during "${t.name}" task: "${e}".`);return null})));return Promise.all(r)}))}loadResources(e){this.resourcesPromise||=this.pdfManager.ensure(this,"resources");return this.resourcesPromise.then((()=>new ObjectLoader(this.resources,e,this.xref).load()))}getOperatorList({handler:e,sink:t,task:i,intent:a,cacheKey:s,annotationStorage:r=null,modifiedIds:n=null}){const C=this.getContentStream(),E=this.loadResources(["ColorSpace","ExtGState","Font","Pattern","Properties","Shading","XObject"]),d=new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions}),f=this.xfaFactory?null:getNewAnnotationsMap(r),p=f?.get(this.pageIndex);let m=Promise.resolve(null),y=null;if(p){const e=this.pdfManager.ensureDoc("annotationGlobals");let t;const a=new Set;for(const{bitmapId:e,bitmap:t}of p)!e||t||a.has(e)||a.add(e);const{isOffscreenCanvasSupported:s}=this.evaluatorOptions;if(a.size>0){const e=p.slice();for(const[t,i]of r)t.startsWith(u)&&i.bitmap&&a.has(i.bitmapId)&&e.push(i);t=AnnotationFactory.generateImages(e,this.xref,s)}else t=AnnotationFactory.generateImages(p,this.xref,s);y=new RefSet;m=Promise.all([e,this.#V(p,y,null)]).then((([e])=>e?AnnotationFactory.printNewAnnotations(e,d,i,p,t):null))}const w=Promise.all([C,E]).then((([r])=>{const n=new OperatorList(a,t);e.send("StartRenderPage",{transparency:d.hasBlendModes(this.resources,this.nonBlendModesSet),pageIndex:this.pageIndex,cacheKey:s});return d.getOperatorList({stream:r,task:i,resources:this.resources,operatorList:n}).then((function(){return n}))}));return Promise.all([w,this._parsedAnnotations,m]).then((function([e,t,s]){if(s){t=t.filter((e=>!(e.ref&&y.has(e.ref))));for(let e=0,i=s.length;ee.ref&&isRefsEqual(e.ref,a.refToReplace)));if(r>=0){t.splice(r,1,a);s.splice(e--,1);i--}}}t=t.concat(s)}if(0===t.length||a&l){e.flush(!0);return{length:e.totalLength}}const C=!!(a&h),E=!!(a&Q),u=!!(a&g),f=!!(a&o),p=!!(a&c),m=[];for(const e of t)(u||f&&e.mustBeViewed(r,C)&&e.mustBeViewedWhenEditing(E,n)||p&&e.mustBePrinted(r))&&m.push(e.getOperatorList(d,i,a,r).catch((function(e){warn(`getOperatorList - ignoring annotation data during "${i.name}" task: "${e}".`);return{opList:null,separateForm:!1,separateCanvas:!1}})));return Promise.all(m).then((function(t){let i=!1,a=!1;for(const{opList:s,separateForm:r,separateCanvas:n}of t){e.addOpList(s);i||=r;a||=n}e.flush(!0,{form:i,canvas:a});return{length:e.totalLength}}))}))}async extractTextContent({handler:e,task:t,includeMarkedContent:i,disableNormalization:a,sink:s}){const r=this.getContentStream(),n=this.loadResources(["ExtGState","Font","Properties","XObject"]),g=this.pdfManager.ensureCatalog("lang"),[o,,c]=await Promise.all([r,n,g]);return new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions}).getTextContent({stream:o,task:t,resources:this.resources,includeMarkedContent:i,disableNormalization:a,sink:s,viewBox:this.view,lang:c})}async getStructTree(){const e=await this.pdfManager.ensureCatalog("structTreeRoot");if(!e)return null;await this._parsedAnnotations;const t=await this.pdfManager.ensure(this,"_parseStructTree",[e]);return this.pdfManager.ensure(t,"serializable")}_parseStructTree(e){const t=new StructTreePage(e,this.pageDict);t.parse(this.ref);return t}async getAnnotationsData(e,t,i){const a=await this._parsedAnnotations;if(0===a.length)return a;const s=[],r=[];let n;const C=!!(i&g),h=!!(i&o),l=!!(i&c);for(const i of a){const a=C||h&&i.viewable;(a||l&&i.printable)&&s.push(i.data);if(i.hasTextContent&&a){n||=new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions});r.push(i.extractTextContent(n,t,[-1/0,-1/0,1/0,1/0]).catch((function(e){warn(`getAnnotationsData - ignoring textContent during "${t.name}" task: "${e}".`)})))}}await Promise.all(r);return s}get annotations(){const e=this._getInheritableProperty("Annots");return shadow(this,"annotations",Array.isArray(e)?e:[])}get _parsedAnnotations(){return shadow(this,"_parsedAnnotations",this.pdfManager.ensure(this,"annotations").then((async e=>{if(0===e.length)return e;const[t,i]=await Promise.all([this.pdfManager.ensureDoc("annotationGlobals"),this.pdfManager.ensureDoc("fieldObjects")]);if(!t)return[];const a=i?.orphanFields,s=[];for(const i of e)s.push(AnnotationFactory.create(this.xref,i,t,this._localIdFactory,!1,a,this.ref).catch((function(e){warn(`_parsedAnnotations: "${e}".`);return null})));const r=[];let n,g;for(const e of await Promise.all(s))e&&(e instanceof WidgetAnnotation?(g||=[]).push(e):e instanceof PopupAnnotation?(n||=[]).push(e):r.push(e));g&&r.push(...g);n&&r.push(...n);return r})))}get jsActions(){return shadow(this,"jsActions",collectActions(this.xref,this.pageDict,pA))}}const ig=new Uint8Array([37,80,68,70,45]),ag=new Uint8Array([115,116,97,114,116,120,114,101,102]),sg=new Uint8Array([101,110,100,111,98,106]);function find(e,t,i=1024,a=!1){const s=t.length,r=e.peekBytes(i),n=r.length-s;if(n<=0)return!1;if(a){const i=s-1;let a=r.length-1;for(;a>=i;){let n=0;for(;n=s){e.pos+=a-i;return!0}a--}}else{let i=0;for(;i<=n;){let a=0;for(;a=s){e.pos+=i;return!0}i++}}return!1}class PDFDocument{constructor(e,t){if(t.length<=0)throw new InvalidPDFException("The PDF file is empty, i.e. its size is zero bytes.");this.pdfManager=e;this.stream=t;this.xref=new XRef(t,e);this._pagePromises=new Map;this._version=null;const i={font:0};this._globalIdFactory=class{static getDocId(){return`g_${e.docId}`}static createFontId(){return"f"+ ++i.font}static createObjId(){unreachable("Abstract method `createObjId` called.")}static getPageObjId(){unreachable("Abstract method `getPageObjId` called.")}}}parse(e){this.xref.parse(e);this.catalog=new Catalog(this.pdfManager,this.xref)}get linearization(){let e=null;try{e=Linearization.create(this.stream)}catch(e){if(e instanceof MissingDataException)throw e;info(e)}return shadow(this,"linearization",e)}get startXRef(){const e=this.stream;let t=0;if(this.linearization){e.reset();if(find(e,sg)){e.skip(6);let i=e.peekByte();for(;isWhiteSpace(i);){e.pos++;i=e.peekByte()}t=e.pos-e.start}}else{const i=1024,a=ag.length;let s=!1,r=e.end;for(;!s&&r>0;){r-=i-a;r<0&&(r=0);e.pos=r;s=find(e,ag,i,!0)}if(s){e.skip(9);let i;do{i=e.getByte()}while(isWhiteSpace(i));let a="";for(;i>=32&&i<=57;){a+=String.fromCharCode(i);i=e.getByte()}t=parseInt(a,10);isNaN(t)&&(t=0)}}return shadow(this,"startXRef",t)}checkHeader(){const e=this.stream;e.reset();if(!find(e,ig))return;e.moveStart();e.skip(ig.length);let t,i="";for(;(t=e.getByte())>32&&i.length<7;)i+=String.fromCharCode(t);ft.test(i)?this._version=i:warn(`Invalid PDF header version: ${i}`)}parseStartXRef(){this.xref.setStartXRef(this.startXRef)}get numPages(){let e=0;e=this.catalog.hasActualNumPages?this.catalog.numPages:this.xfaFactory?this.xfaFactory.getNumPages():this.linearization?this.linearization.numPages:this.catalog.numPages;return shadow(this,"numPages",e)}_hasOnlyDocumentSignatures(e,t=0){return!!Array.isArray(e)&&e.every((e=>{if(!((e=this.xref.fetchIfRef(e))instanceof Dict))return!1;if(e.has("Kids")){if(++t>10){warn("_hasOnlyDocumentSignatures: maximum recursion depth reached");return!1}return this._hasOnlyDocumentSignatures(e.get("Kids"),t)}const i=isName(e.get("FT"),"Sig"),a=e.get("Rect"),s=Array.isArray(a)&&a.every((e=>0===e));return i&&s}))}get _xfaStreams(){const e=this.catalog.acroForm;if(!e)return null;const t=e.get("XFA"),i={"xdp:xdp":"",template:"",datasets:"",config:"",connectionSet:"",localeSet:"",stylesheet:"","/xdp:xdp":""};if(t instanceof BaseStream&&!t.isEmpty){i["xdp:xdp"]=t;return i}if(!Array.isArray(t)||0===t.length)return null;for(let e=0,a=t.length;e0;e.hasFields=a;const s=t.get("XFA");e.hasXfa=Array.isArray(s)&&s.length>0||s instanceof BaseStream&&!s.isEmpty;const r=!!(1&t.get("SigFlags")),n=r&&this._hasOnlyDocumentSignatures(i);e.hasAcroForm=a&&!n;e.hasSignatures=r}catch(e){if(e instanceof MissingDataException)throw e;warn(`Cannot fetch form information: "${e}".`)}return shadow(this,"formInfo",e)}get documentInfo(){const e={PDFFormatVersion:this.version,Language:this.catalog.lang,EncryptFilterName:this.xref.encrypt?this.xref.encrypt.filterName:null,IsLinearized:!!this.linearization,IsAcroFormPresent:this.formInfo.hasAcroForm,IsXFAPresent:this.formInfo.hasXfa,IsCollectionPresent:!!this.catalog.collection,IsSignaturesPresent:this.formInfo.hasSignatures};let t;try{t=this.xref.trailer.get("Info")}catch(e){if(e instanceof MissingDataException)throw e;info("The document information dictionary is invalid.")}if(!(t instanceof Dict))return shadow(this,"documentInfo",e);for(const i of t.getKeys()){const a=t.get(i);switch(i){case"Title":case"Author":case"Subject":case"Keywords":case"Creator":case"Producer":case"CreationDate":case"ModDate":if("string"==typeof a){e[i]=stringToPDFString(a);continue}break;case"Trapped":if(a instanceof Name){e[i]=a;continue}break;default:let t;switch(typeof a){case"string":t=stringToPDFString(a);break;case"number":case"boolean":t=a;break;default:a instanceof Name&&(t=a)}if(void 0===t){warn(`Bad value, for custom key "${i}", in Info: ${a}.`);continue}e.Custom||(e.Custom=Object.create(null));e.Custom[i]=t;continue}warn(`Bad value, for key "${i}", in Info: ${a}.`)}return shadow(this,"documentInfo",e)}get fingerprints(){const e="\0".repeat(16);function validate(t){return"string"==typeof t&&16===t.length&&t!==e}const t=this.xref.trailer.get("ID");let i,a;if(Array.isArray(t)&&validate(t[0])){i=stringToBytes(t[0]);t[1]!==t[0]&&validate(t[1])&&(a=stringToBytes(t[1]))}else i=$n(this.stream.getByteRange(0,1024),0,1024);return shadow(this,"fingerprints",[toHexUtil(i),a?toHexUtil(a):null])}async _getLinearizationPage(e){const{catalog:t,linearization:i,xref:a}=this,s=Ref.get(i.objectNumberFirst,0);try{const e=await a.fetchAsync(s);if(e instanceof Dict){let i=e.getRaw("Type");i instanceof Ref&&(i=await a.fetchAsync(i));if(isName(i,"Page")||!e.has("Type")&&!e.has("Kids")&&e.has("Contents")){t.pageKidsCountCache.has(s)||t.pageKidsCountCache.put(s,1);t.pageIndexCache.has(s)||t.pageIndexCache.put(s,0);return[e,s]}}throw new FormatError("The Linearization dictionary doesn't point to a valid Page dictionary.")}catch(i){warn(`_getLinearizationPage: "${i.message}".`);return t.getPageDict(e)}}getPage(e){const t=this._pagePromises.get(e);if(t)return t;const{catalog:i,linearization:a,xfaFactory:s}=this;let r;r=s?Promise.resolve([Dict.empty,null]):a?.pageFirst===e?this._getLinearizationPage(e):i.getPageDict(e);r=r.then((([t,a])=>new Page({pdfManager:this.pdfManager,xref:this.xref,pageIndex:e,pageDict:t,ref:a,globalIdFactory:this._globalIdFactory,fontCache:i.fontCache,builtInCMapCache:i.builtInCMapCache,standardFontDataCache:i.standardFontDataCache,globalImageCache:i.globalImageCache,systemFontCache:i.systemFontCache,nonBlendModesSet:i.nonBlendModesSet,xfaFactory:s})));this._pagePromises.set(e,r);return r}async checkFirstPage(e=!1){if(!e)try{await this.getPage(0)}catch(e){if(e instanceof XRefEntryException){this._pagePromises.delete(0);await this.cleanup();throw new XRefParseException}}}async checkLastPage(e=!1){const{catalog:t,pdfManager:i}=this;t.setActualNumPages();let a;try{await Promise.all([i.ensureDoc("xfaFactory"),i.ensureDoc("linearization"),i.ensureCatalog("numPages")]);if(this.xfaFactory)return;a=this.linearization?this.linearization.numPages:t.numPages;if(!Number.isInteger(a))throw new FormatError("Page count is not an integer.");if(a<=1)return;await this.getPage(a-1)}catch(s){this._pagePromises.delete(a-1);await this.cleanup();if(s instanceof XRefEntryException&&!e)throw new XRefParseException;warn(`checkLastPage - invalid /Pages tree /Count: ${a}.`);let r;try{r=await t.getAllPageDicts(e)}catch(i){if(i instanceof XRefEntryException&&!e)throw new XRefParseException;t.setActualNumPages(1);return}for(const[e,[a,s]]of r){let r;if(a instanceof Error){r=Promise.reject(a);r.catch((()=>{}))}else r=Promise.resolve(new Page({pdfManager:i,xref:this.xref,pageIndex:e,pageDict:a,ref:s,globalIdFactory:this._globalIdFactory,fontCache:t.fontCache,builtInCMapCache:t.builtInCMapCache,standardFontDataCache:t.standardFontDataCache,globalImageCache:t.globalImageCache,systemFontCache:t.systemFontCache,nonBlendModesSet:t.nonBlendModesSet,xfaFactory:null}));this._pagePromises.set(e,r)}t.setActualNumPages(r.size)}}fontFallback(e,t){return this.catalog.fontFallback(e,t)}async cleanup(e=!1){return this.catalog?this.catalog.cleanup(e):clearGlobalCaches()}async#z(e,t,i,a,s,r,n){const{xref:g}=this;if(!(i instanceof Ref)||r.has(i))return;r.put(i);const o=await g.fetchAsync(i);if(!(o instanceof Dict))return;if(o.has("T")){const t=stringToPDFString(await o.getAsync("T"));e=""===e?t:`${e}.${t}`}else{let i=o;for(;;){i=i.getRaw("Parent")||t;if(i instanceof Ref){if(r.has(i))break;i=await g.fetchAsync(i)}if(!(i instanceof Dict))break;if(i.has("T")){const t=stringToPDFString(await i.getAsync("T"));e=""===e?t:`${e}.${t}`;break}}}t&&!o.has("Parent")&&isName(o.get("Subtype"),"Widget")&&n.put(i,t);a.has(e)||a.set(e,[]);a.get(e).push(AnnotationFactory.create(g,i,s,null,!0,n,null).then((e=>e?.getFieldObject())).catch((function(e){warn(`#collectFieldObjects: "${e}".`);return null})));if(!o.has("Kids"))return;const c=await o.getAsync("Kids");if(Array.isArray(c))for(const t of c)await this.#z(e,i,t,a,s,r,n)}get fieldObjects(){return shadow(this,"fieldObjects",this.pdfManager.ensureDoc("formInfo").then((async e=>{if(!e.hasFields)return null;const[t,i]=await Promise.all([this.pdfManager.ensureDoc("annotationGlobals"),this.pdfManager.ensureCatalog("acroForm")]);if(!t)return null;const a=new RefSet,s=Object.create(null),r=new Map,n=new RefSetCache;for(const e of await i.getAsync("Fields"))await this.#z("",null,e,r,t,a,n);const g=[];for(const[e,t]of r)g.push(Promise.all(t).then((t=>{(t=t.filter((e=>!!e))).length>0&&(s[e]=t)})));await Promise.all(g);return{allFields:s,orphanFields:n}})))}get hasJSActions(){return shadow(this,"hasJSActions",this.pdfManager.ensureDoc("_parseHasJSActions"))}async _parseHasJSActions(){const[e,t]=await Promise.all([this.pdfManager.ensureCatalog("jsActions"),this.pdfManager.ensureDoc("fieldObjects")]);return!!e||!!t&&Object.values(t.allFields).some((e=>e.some((e=>null!==e.actions))))}get calculationOrderIds(){const e=this.catalog.acroForm?.get("CO");if(!Array.isArray(e)||0===e.length)return shadow(this,"calculationOrderIds",null);const t=[];for(const i of e)i instanceof Ref&&t.push(i.toString());return shadow(this,"calculationOrderIds",t.length?t:null)}get annotationGlobals(){return shadow(this,"annotationGlobals",AnnotationFactory.createGlobals(this.pdfManager))}}class BasePdfManager{constructor(e){this._docBaseUrl=function parseDocBaseUrl(e){if(e){const t=createValidAbsoluteUrl(e);if(t)return t.href;warn(`Invalid absolute docBaseUrl: "${e}".`)}return null}(e.docBaseUrl);this._docId=e.docId;this._password=e.password;this.enableXfa=e.enableXfa;e.evaluatorOptions.isOffscreenCanvasSupported&&=FeatureTest.isOffscreenCanvasSupported;e.evaluatorOptions.isImageDecoderSupported&&=FeatureTest.isImageDecoderSupported;this.evaluatorOptions=Object.freeze(e.evaluatorOptions)}get docId(){return this._docId}get password(){return this._password}get docBaseUrl(){return this._docBaseUrl}get catalog(){return this.pdfDocument.catalog}ensureDoc(e,t){return this.ensure(this.pdfDocument,e,t)}ensureXRef(e,t){return this.ensure(this.pdfDocument.xref,e,t)}ensureCatalog(e,t){return this.ensure(this.pdfDocument.catalog,e,t)}getPage(e){return this.pdfDocument.getPage(e)}fontFallback(e,t){return this.pdfDocument.fontFallback(e,t)}loadXfaFonts(e,t){return this.pdfDocument.loadXfaFonts(e,t)}loadXfaImages(){return this.pdfDocument.loadXfaImages()}serializeXfaData(e){return this.pdfDocument.serializeXfaData(e)}cleanup(e=!1){return this.pdfDocument.cleanup(e)}async ensure(e,t,i){unreachable("Abstract method `ensure` called")}requestRange(e,t){unreachable("Abstract method `requestRange` called")}requestLoadedStream(e=!1){unreachable("Abstract method `requestLoadedStream` called")}sendProgressiveData(e){unreachable("Abstract method `sendProgressiveData` called")}updatePassword(e){this._password=e}terminate(e){unreachable("Abstract method `terminate` called")}}class LocalPdfManager extends BasePdfManager{constructor(e){super(e);const t=new Stream(e.source);this.pdfDocument=new PDFDocument(this,t);this._loadedStreamPromise=Promise.resolve(t)}async ensure(e,t,i){const a=e[t];return"function"==typeof a?a.apply(e,i):a}requestRange(e,t){return Promise.resolve()}requestLoadedStream(e=!1){return this._loadedStreamPromise}terminate(e){}}class NetworkPdfManager extends BasePdfManager{constructor(e){super(e);this.streamManager=new ChunkedStreamManager(e.source,{msgHandler:e.handler,length:e.length,disableAutoFetch:e.disableAutoFetch,rangeChunkSize:e.rangeChunkSize});this.pdfDocument=new PDFDocument(this,this.streamManager.getStream())}async ensure(e,t,i){try{const a=e[t];return"function"==typeof a?a.apply(e,i):a}catch(a){if(!(a instanceof MissingDataException))throw a;await this.requestRange(a.begin,a.end);return this.ensure(e,t,i)}}requestRange(e,t){return this.streamManager.requestRange(e,t)}requestLoadedStream(e=!1){return this.streamManager.requestAllChunks(e)}sendProgressiveData(e){this.streamManager.onReceiveData({chunk:e})}terminate(e){this.streamManager.abort(e)}}const rg=1,ng=2,gg=1,og=2,Ig=3,cg=4,Cg=5,hg=6,lg=7,Bg=8;function onFn(){}function wrapReason(e){if(e instanceof AbortException||e instanceof InvalidPDFException||e instanceof MissingPDFException||e instanceof PasswordException||e instanceof UnexpectedResponseException||e instanceof UnknownErrorException)return e;e instanceof Error||"object"==typeof e&&null!==e||unreachable('wrapReason: Expected "reason" to be a (possibly cloned) Error.');switch(e.name){case"AbortException":return new AbortException(e.message);case"InvalidPDFException":return new InvalidPDFException(e.message);case"MissingPDFException":return new MissingPDFException(e.message);case"PasswordException":return new PasswordException(e.message,e.code);case"UnexpectedResponseException":return new UnexpectedResponseException(e.message,e.status);case"UnknownErrorException":return new UnknownErrorException(e.message,e.details)}return new UnknownErrorException(e.message,e.toString())}class MessageHandler{#_=new AbortController;constructor(e,t,i){this.sourceName=e;this.targetName=t;this.comObj=i;this.callbackId=1;this.streamId=1;this.streamSinks=Object.create(null);this.streamControllers=Object.create(null);this.callbackCapabilities=Object.create(null);this.actionHandler=Object.create(null);i.addEventListener("message",this.#$.bind(this),{signal:this.#_.signal})}#$({data:e}){if(e.targetName!==this.sourceName)return;if(e.stream){this.#AA(e);return}if(e.callback){const t=e.callbackId,i=this.callbackCapabilities[t];if(!i)throw new Error(`Cannot resolve callback ${t}`);delete this.callbackCapabilities[t];if(e.callback===rg)i.resolve(e.data);else{if(e.callback!==ng)throw new Error("Unexpected callback case");i.reject(wrapReason(e.reason))}return}const t=this.actionHandler[e.action];if(!t)throw new Error(`Unknown action from worker: ${e.action}`);if(e.callbackId){const i=this.sourceName,a=e.sourceName,s=this.comObj;Promise.try(t,e.data).then((function(t){s.postMessage({sourceName:i,targetName:a,callback:rg,callbackId:e.callbackId,data:t})}),(function(t){s.postMessage({sourceName:i,targetName:a,callback:ng,callbackId:e.callbackId,reason:wrapReason(t)})}))}else e.streamId?this.#eA(e):t(e.data)}on(e,t){const i=this.actionHandler;if(i[e])throw new Error(`There is already an actionName called "${e}"`);i[e]=t}send(e,t,i){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,data:t},i)}sendWithPromise(e,t,i){const a=this.callbackId++,s=Promise.withResolvers();this.callbackCapabilities[a]=s;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,callbackId:a,data:t},i)}catch(e){s.reject(e)}return s.promise}sendWithStream(e,t,i,a){const s=this.streamId++,r=this.sourceName,n=this.targetName,g=this.comObj;return new ReadableStream({start:i=>{const o=Promise.withResolvers();this.streamControllers[s]={controller:i,startCall:o,pullCall:null,cancelCall:null,isClosed:!1};g.postMessage({sourceName:r,targetName:n,action:e,streamId:s,data:t,desiredSize:i.desiredSize},a);return o.promise},pull:e=>{const t=Promise.withResolvers();this.streamControllers[s].pullCall=t;g.postMessage({sourceName:r,targetName:n,stream:hg,streamId:s,desiredSize:e.desiredSize});return t.promise},cancel:e=>{assert(e instanceof Error,"cancel must have a valid reason");const t=Promise.withResolvers();this.streamControllers[s].cancelCall=t;this.streamControllers[s].isClosed=!0;g.postMessage({sourceName:r,targetName:n,stream:gg,streamId:s,reason:wrapReason(e)});return t.promise}},i)}#eA(e){const t=e.streamId,i=this.sourceName,a=e.sourceName,s=this.comObj,r=this,n=this.actionHandler[e.action],g={enqueue(e,r=1,n){if(this.isCancelled)return;const g=this.desiredSize;this.desiredSize-=r;if(g>0&&this.desiredSize<=0){this.sinkCapability=Promise.withResolvers();this.ready=this.sinkCapability.promise}s.postMessage({sourceName:i,targetName:a,stream:cg,streamId:t,chunk:e},n)},close(){if(!this.isCancelled){this.isCancelled=!0;s.postMessage({sourceName:i,targetName:a,stream:Ig,streamId:t});delete r.streamSinks[t]}},error(e){assert(e instanceof Error,"error must have a valid reason");if(!this.isCancelled){this.isCancelled=!0;s.postMessage({sourceName:i,targetName:a,stream:Cg,streamId:t,reason:wrapReason(e)})}},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:e.desiredSize,ready:null};g.sinkCapability.resolve();g.ready=g.sinkCapability.promise;this.streamSinks[t]=g;Promise.try(n,e.data,g).then((function(){s.postMessage({sourceName:i,targetName:a,stream:Bg,streamId:t,success:!0})}),(function(e){s.postMessage({sourceName:i,targetName:a,stream:Bg,streamId:t,reason:wrapReason(e)})}))}#AA(e){const t=e.streamId,i=this.sourceName,a=e.sourceName,s=this.comObj,r=this.streamControllers[t],n=this.streamSinks[t];switch(e.stream){case Bg:e.success?r.startCall.resolve():r.startCall.reject(wrapReason(e.reason));break;case lg:e.success?r.pullCall.resolve():r.pullCall.reject(wrapReason(e.reason));break;case hg:if(!n){s.postMessage({sourceName:i,targetName:a,stream:lg,streamId:t,success:!0});break}n.desiredSize<=0&&e.desiredSize>0&&n.sinkCapability.resolve();n.desiredSize=e.desiredSize;Promise.try(n.onPull||onFn).then((function(){s.postMessage({sourceName:i,targetName:a,stream:lg,streamId:t,success:!0})}),(function(e){s.postMessage({sourceName:i,targetName:a,stream:lg,streamId:t,reason:wrapReason(e)})}));break;case cg:assert(r,"enqueue should have stream controller");if(r.isClosed)break;r.controller.enqueue(e.chunk);break;case Ig:assert(r,"close should have stream controller");if(r.isClosed)break;r.isClosed=!0;r.controller.close();this.#tA(r,t);break;case Cg:assert(r,"error should have stream controller");r.controller.error(wrapReason(e.reason));this.#tA(r,t);break;case og:e.success?r.cancelCall.resolve():r.cancelCall.reject(wrapReason(e.reason));this.#tA(r,t);break;case gg:if(!n)break;const g=wrapReason(e.reason);Promise.try(n.onCancel||onFn,g).then((function(){s.postMessage({sourceName:i,targetName:a,stream:og,streamId:t,success:!0})}),(function(e){s.postMessage({sourceName:i,targetName:a,stream:og,streamId:t,reason:wrapReason(e)})}));n.sinkCapability.reject(g);n.isCancelled=!0;delete this.streamSinks[t];break;default:throw new Error("Unexpected stream case")}}async#tA(e,t){await Promise.allSettled([e.startCall?.promise,e.pullCall?.promise,e.cancelCall?.promise]);delete this.streamControllers[t]}destroy(){this.#_?.abort();this.#_=null}}async function writeObject(e,t,i,{encrypt:a=null}){const s=a?.createCipherTransform(e.num,e.gen);i.push(`${e.num} ${e.gen} obj\n`);t instanceof Dict?await writeDict(t,i,s):t instanceof BaseStream?await writeStream(t,i,s):(Array.isArray(t)||ArrayBuffer.isView(t))&&await writeArray(t,i,s);i.push("\nendobj\n")}async function writeDict(e,t,i){t.push("<<");for(const a of e.getKeys()){t.push(` /${escapePDFName(a)} `);await writeValue(e.getRaw(a),t,i)}t.push(">>")}async function writeStream(e,t,i){let a=e.getBytes();const{dict:s}=e,[r,n]=await Promise.all([s.getAsync("Filter"),s.getAsync("DecodeParms")]),g=isName(Array.isArray(r)?await s.xref.fetchIfRefAsync(r[0]):r,"FlateDecode");if(a.length>=256||g)try{const e=new CompressionStream("deflate"),t=e.writable.getWriter();await t.ready;t.write(a).then((async()=>{await t.ready;await t.close()})).catch((()=>{}));const i=await new Response(e.readable).arrayBuffer();a=new Uint8Array(i);let o,c;if(r){if(!g){o=Array.isArray(r)?[Name.get("FlateDecode"),...r]:[Name.get("FlateDecode"),r];n&&(c=Array.isArray(n)?[null,...n]:[null,n])}}else o=Name.get("FlateDecode");o&&s.set("Filter",o);c&&s.set("DecodeParms",c)}catch(e){info(`writeStream - cannot compress data: "${e}".`)}let o=bytesToString(a);i&&(o=i.encryptString(o));s.set("Length",o.length);await writeDict(s,t,i);t.push(" stream\n",o,"\nendstream")}async function writeArray(e,t,i){t.push("[");let a=!0;for(const s of e){a?a=!1:t.push(" ");await writeValue(s,t,i)}t.push("]")}async function writeValue(e,t,i){if(e instanceof Name)t.push(`/${escapePDFName(e.name)}`);else if(e instanceof Ref)t.push(`${e.num} ${e.gen} R`);else if(Array.isArray(e)||ArrayBuffer.isView(e))await writeArray(e,t,i);else if("string"==typeof e){i&&(e=i.encryptString(e));t.push(`(${escapeString(e)})`)}else"number"==typeof e?t.push(numberToString(e)):"boolean"==typeof e?t.push(e.toString()):e instanceof Dict?await writeDict(e,t,i):e instanceof BaseStream?await writeStream(e,t,i):null===e?t.push("null"):warn(`Unhandled value in writer: ${typeof e}, please file a bug.`)}function writeInt(e,t,i,a){for(let s=t+i-1;s>i-1;s--){a[s]=255&e;e>>=8}return i+t}function writeString(e,t,i){for(let a=0,s=e.length;a1&&(r=i.documentElement.searchNode([s.at(-1)],0));r?r.childNodes=Array.isArray(a)?a.map((e=>new SimpleDOMNode("value",e))):[new SimpleDOMNode("#text",a)]:warn(`Node not found for path: ${t}`)}const a=[];i.documentElement.dump(a);return a.join("")}(a.fetchIfRef(t).getString(),i)}const s=new StringStream(e);s.dict=new Dict(a);s.dict.set("Type",Name.get("EmbeddedFile"));i.put(t,{data:s})}function getIndexes(e){const t=[];for(const{ref:i}of e)i.num===t.at(-2)+t.at(-1)?t[t.length-1]+=1:t.push(i.num,1);return t}function computeIDs(e,t,i){if(Array.isArray(t.fileIds)&&t.fileIds.length>0){const a=function computeMD5(e,t){const i=Math.floor(Date.now()/1e3),a=t.filename||"",s=[i.toString(),a,e.toString()];let r=s.reduce(((e,t)=>e+t.length),0);for(const e of Object.values(t.info)){s.push(e);r+=e.length}const n=new Uint8Array(r);let g=0;for(const e of s){writeString(e,g,n);g+=e.length}return bytesToString($n(n))}(e,t);i.set("ID",[t.fileIds[0],a])}}async function incrementalUpdate({originalData:e,xrefInfo:t,changes:i,xref:a=null,hasXfa:s=!1,xfaDatasetsRef:r=null,hasXfaDatasetsEntry:n=!1,needAppearances:g,acroFormRef:o=null,acroForm:c=null,xfaData:C=null,useXrefStream:h=!1}){await async function updateAcroform({xref:e,acroForm:t,acroFormRef:i,hasXfa:a,hasXfaDatasetsEntry:s,xfaDatasetsRef:r,needAppearances:n,changes:g}){!a||s||r||warn("XFA - Cannot save it");if(!n&&(!a||!r||s))return;const o=t.clone();if(a&&!s){const e=t.get("XFA").slice();e.splice(2,0,"datasets");e.splice(3,0,r);o.set("XFA",e)}n&&o.set("NeedAppearances",!0);g.put(i,{data:o})}({xref:a,acroForm:c,acroFormRef:o,hasXfa:s,hasXfaDatasetsEntry:n,xfaDatasetsRef:r,needAppearances:g,changes:i});s&&updateXFA({xfaData:C,xfaDatasetsRef:r,changes:i,xref:a});const l=function getTrailerDict(e,t,i){const a=new Dict(null);a.set("Prev",e.startXRef);const s=e.newRef;if(i){t.put(s,{data:""});a.set("Size",s.num+1);a.set("Type",Name.get("XRef"))}else a.set("Size",s.num);null!==e.rootRef&&a.set("Root",e.rootRef);null!==e.infoRef&&a.set("Info",e.infoRef);null!==e.encryptRef&&a.set("Encrypt",e.encryptRef);return a}(t,i,h),Q=[],E=await async function writeChanges(e,t,i=[]){const a=[];for(const[s,{data:r}]of e.items())if(null!==r&&"string"!=typeof r){await writeObject(s,r,i,t);a.push({ref:s,data:i.join("")});i.length=0}else a.push({ref:s,data:r});return a.sort(((e,t)=>e.ref.num-t.ref.num))}(i,a,Q);let u=e.length;const d=e.at(-1);if(10!==d&&13!==d){Q.push("\n");u+=1}for(const{data:e}of E)null!==e&&Q.push(e);await(h?async function getXRefStreamTable(e,t,i,a,s){const r=[];let n=0,g=0;for(const{ref:e,data:a}of i){let i;n=Math.max(n,t);if(null!==a){i=Math.min(e.gen,65535);r.push([1,t,i]);t+=a.length}else{i=Math.min(e.gen+1,65535);r.push([0,0,i])}g=Math.max(g,i)}a.set("Index",getIndexes(i));const o=[1,getSizeInBytes(n),getSizeInBytes(g)];a.set("W",o);computeIDs(t,e,a);const c=o.reduce(((e,t)=>e+t),0),C=new Uint8Array(c*r.length),h=new Stream(C);h.dict=a;let l=0;for(const[e,t,i]of r){l=writeInt(e,o[0],l,C);l=writeInt(t,o[1],l,C);l=writeInt(i,o[2],l,C)}await writeObject(e.newRef,h,s,{});s.push("startxref\n",t.toString(),"\n%%EOF\n")}(t,u,E,l,Q):async function getXRefTable(e,t,i,a,s){s.push("xref\n");const r=getIndexes(i);let n=0;for(const{ref:e,data:a}of i){if(e.num===r[n]){s.push(`${r[n]} ${r[n+1]}\n`);n+=2}if(null!==a){s.push(`${t.toString().padStart(10,"0")} ${Math.min(e.gen,65535).toString().padStart(5,"0")} n\r\n`);t+=a.length}else s.push(`0000000000 ${Math.min(e.gen+1,65535).toString().padStart(5,"0")} f\r\n`)}computeIDs(t,e,a);s.push("trailer\n");await writeDict(a,s);s.push("\nstartxref\n",t.toString(),"\n%%EOF\n")}(t,u,E,l,Q));const f=Q.reduce(((e,t)=>e+t.length),e.length),p=new Uint8Array(f);p.set(e);let m=e.length;for(const e of Q){writeString(e,m,p);m+=e.length}return p}class PDFWorkerStream{constructor(e){this._msgHandler=e;this._contentLength=null;this._fullRequestReader=null;this._rangeRequestReaders=[]}getFullReader(){assert(!this._fullRequestReader,"PDFWorkerStream.getFullReader can only be called once.");this._fullRequestReader=new PDFWorkerStreamReader(this._msgHandler);return this._fullRequestReader}getRangeReader(e,t){const i=new PDFWorkerStreamRangeReader(e,t,this._msgHandler);this._rangeRequestReaders.push(i);return i}cancelAllRequests(e){this._fullRequestReader?.cancel(e);for(const t of this._rangeRequestReaders.slice(0))t.cancel(e)}}class PDFWorkerStreamReader{constructor(e){this._msgHandler=e;this.onProgress=null;this._contentLength=null;this._isRangeSupported=!1;this._isStreamingSupported=!1;const t=this._msgHandler.sendWithStream("GetReader");this._reader=t.getReader();this._headersReady=this._msgHandler.sendWithPromise("ReaderHeadersReady").then((e=>{this._isStreamingSupported=e.isStreamingSupported;this._isRangeSupported=e.isRangeSupported;this._contentLength=e.contentLength}))}get headersReady(){return this._headersReady}get contentLength(){return this._contentLength}get isStreamingSupported(){return this._isStreamingSupported}get isRangeSupported(){return this._isRangeSupported}async read(){const{value:e,done:t}=await this._reader.read();return t?{value:void 0,done:!0}:{value:e.buffer,done:!1}}cancel(e){this._reader.cancel(e)}}class PDFWorkerStreamRangeReader{constructor(e,t,i){this._msgHandler=i;this.onProgress=null;const a=this._msgHandler.sendWithStream("GetRangeReader",{begin:e,end:t});this._reader=a.getReader()}get isStreamingSupported(){return!1}async read(){const{value:e,done:t}=await this._reader.read();return t?{value:void 0,done:!0}:{value:e.buffer,done:!1}}cancel(e){this._reader.cancel(e)}}class WorkerTask{constructor(e){this.name=e;this.terminated=!1;this._capability=Promise.withResolvers()}get finished(){return this._capability.promise}finish(){this._capability.resolve()}terminate(){this.terminated=!0}ensureNotTerminated(){if(this.terminated)throw new Error("Worker task was terminated")}}class WorkerMessageHandler{static{"undefined"==typeof window&&!t&&"undefined"!=typeof self&&"function"==typeof self.postMessage&&"onmessage"in self&&this.initializeFromPort(self)}static setup(e,t){let i=!1;e.on("test",(t=>{if(!i){i=!0;e.send("test",t instanceof Uint8Array)}}));e.on("configure",(e=>{!function setVerbosityLevel(e){Number.isInteger(e)&&(gt=e)}(e.verbosity)}));e.on("GetDocRequest",(e=>this.createDocumentHandler(e,t)))}static createDocumentHandler(e,t){let i,a=!1,s=null;const r=new Set,n=getVerbosityLevel(),{docId:g,apiVersion:o}=e,c="4.10.38";if(o!==c)throw new Error(`The API version "${o}" does not match the Worker version "${c}".`);const C=[];for(const e in[])C.push(e);if(C.length)throw new Error("The `Array.prototype` contains unexpected enumerable properties: "+C.join(", ")+"; thus breaking e.g. `for...in` iteration of `Array`s.");const h=g+"_worker";let l=new MessageHandler(h,g,t);function ensureNotTerminated(){if(a)throw new Error("Worker was terminated")}function startWorkerTask(e){r.add(e)}function finishWorkerTask(e){e.finish();r.delete(e)}async function loadDocument(e){await i.ensureDoc("checkHeader");await i.ensureDoc("parseStartXRef");await i.ensureDoc("parse",[e]);await i.ensureDoc("checkFirstPage",[e]);await i.ensureDoc("checkLastPage",[e]);const t=await i.ensureDoc("isPureXfa");if(t){const e=new WorkerTask("loadXfaFonts");startWorkerTask(e);await Promise.all([i.loadXfaFonts(l,e).catch((e=>{})).then((()=>finishWorkerTask(e))),i.loadXfaImages()])}const[a,s]=await Promise.all([i.ensureDoc("numPages"),i.ensureDoc("fingerprints")]);return{numPages:a,fingerprints:s,htmlForXfa:t?await i.ensureDoc("htmlForXfa"):null}}function setupDoc(e){function onSuccess(e){ensureNotTerminated();l.send("GetDoc",{pdfInfo:e})}function onFailure(e){ensureNotTerminated();if(e instanceof PasswordException){const t=new WorkerTask(`PasswordException: response ${e.code}`);startWorkerTask(t);l.sendWithPromise("PasswordRequest",e).then((function({password:e}){finishWorkerTask(t);i.updatePassword(e);pdfManagerReady()})).catch((function(){finishWorkerTask(t);l.send("DocException",e)}))}else l.send("DocException",wrapReason(e))}function pdfManagerReady(){ensureNotTerminated();loadDocument(!1).then(onSuccess,(function(e){ensureNotTerminated();e instanceof XRefParseException?i.requestLoadedStream().then((function(){ensureNotTerminated();loadDocument(!0).then(onSuccess,onFailure)})):onFailure(e)}))}ensureNotTerminated();(async function getPdfManager({data:e,password:t,disableAutoFetch:i,rangeChunkSize:a,length:r,docBaseUrl:n,enableXfa:o,evaluatorOptions:c}){const C={source:null,disableAutoFetch:i,docBaseUrl:n,docId:g,enableXfa:o,evaluatorOptions:c,handler:l,length:r,password:t,rangeChunkSize:a};if(e){C.source=e;return new LocalPdfManager(C)}const h=new PDFWorkerStream(l),Q=h.getFullReader(),E=Promise.withResolvers();let u,d=[],f=0;Q.headersReady.then((function(){if(Q.isRangeSupported){C.source=h;C.length=Q.contentLength;C.disableAutoFetch||=Q.isStreamingSupported;u=new NetworkPdfManager(C);for(const e of d)u.sendProgressiveData(e);d=[];E.resolve(u);s=null}})).catch((function(e){E.reject(e);s=null}));new Promise((function(e,t){const readChunk=function({value:e,done:i}){try{ensureNotTerminated();if(i){if(!u){const e=arrayBuffersToBytes(d);d=[];r&&e.length!==r&&warn("reported HTTP length is different from actual");C.source=e;u=new LocalPdfManager(C);E.resolve(u)}s=null;return}f+=e.byteLength;Q.isStreamingSupported||l.send("DocProgress",{loaded:f,total:Math.max(f,Q.contentLength||0)});u?u.sendProgressiveData(e):d.push(e);Q.read().then(readChunk,t)}catch(e){t(e)}};Q.read().then(readChunk,t)})).catch((function(e){E.reject(e);s=null}));s=e=>{h.cancelAllRequests(e)};return E.promise})(e).then((function(e){if(a){e.terminate(new AbortException("Worker was terminated."));throw new Error("Worker was terminated")}i=e;i.requestLoadedStream(!0).then((e=>{l.send("DataLoaded",{length:e.bytes.byteLength})}))})).then(pdfManagerReady,onFailure)}l.on("GetPage",(function(e){return i.getPage(e.pageIndex).then((function(e){return Promise.all([i.ensure(e,"rotate"),i.ensure(e,"ref"),i.ensure(e,"userUnit"),i.ensure(e,"view")]).then((function([e,t,i,a]){return{rotate:e,ref:t,refStr:t?.toString()??null,userUnit:i,view:a}}))}))}));l.on("GetPageIndex",(function(e){const t=Ref.get(e.num,e.gen);return i.ensureCatalog("getPageIndex",[t])}));l.on("GetDestinations",(function(e){return i.ensureCatalog("destinations")}));l.on("GetDestination",(function(e){return i.ensureCatalog("getDestination",[e.id])}));l.on("GetPageLabels",(function(e){return i.ensureCatalog("pageLabels")}));l.on("GetPageLayout",(function(e){return i.ensureCatalog("pageLayout")}));l.on("GetPageMode",(function(e){return i.ensureCatalog("pageMode")}));l.on("GetViewerPreferences",(function(e){return i.ensureCatalog("viewerPreferences")}));l.on("GetOpenAction",(function(e){return i.ensureCatalog("openAction")}));l.on("GetAttachments",(function(e){return i.ensureCatalog("attachments")}));l.on("GetDocJSActions",(function(e){return i.ensureCatalog("jsActions")}));l.on("GetPageJSActions",(function({pageIndex:e}){return i.getPage(e).then((function(e){return i.ensure(e,"jsActions")}))}));l.on("GetOutline",(function(e){return i.ensureCatalog("documentOutline")}));l.on("GetOptionalContentConfig",(function(e){return i.ensureCatalog("optionalContentConfig")}));l.on("GetPermissions",(function(e){return i.ensureCatalog("permissions")}));l.on("GetMetadata",(function(e){return Promise.all([i.ensureDoc("documentInfo"),i.ensureCatalog("metadata")])}));l.on("GetMarkInfo",(function(e){return i.ensureCatalog("markInfo")}));l.on("GetData",(function(e){return i.requestLoadedStream().then((function(e){return e.bytes}))}));l.on("GetAnnotations",(function({pageIndex:e,intent:t}){return i.getPage(e).then((function(i){const a=new WorkerTask(`GetAnnotations: page ${e}`);startWorkerTask(a);return i.getAnnotationsData(l,a,t).then((e=>{finishWorkerTask(a);return e}),(e=>{finishWorkerTask(a);throw e}))}))}));l.on("GetFieldObjects",(function(e){return i.ensureDoc("fieldObjects").then((e=>e?.allFields||null))}));l.on("HasJSActions",(function(e){return i.ensureDoc("hasJSActions")}));l.on("GetCalculationOrderIds",(function(e){return i.ensureDoc("calculationOrderIds")}));l.on("SaveDocument",(async function({isPureXfa:e,numPages:t,annotationStorage:a,filename:s}){const r=[i.requestLoadedStream(),i.ensureCatalog("acroForm"),i.ensureCatalog("acroFormRef"),i.ensureDoc("startXRef"),i.ensureDoc("xref"),i.ensureDoc("linearization"),i.ensureCatalog("structTreeRoot")],n=new RefSetCache,g=[],o=e?null:getNewAnnotationsMap(a),[c,C,h,Q,E,u,d]=await Promise.all(r),f=E.trailer.getRaw("Root")||null;let p;if(o){d?await d.canUpdateStructTree({pdfManager:i,xref:E,newAnnotationsByPage:o})&&(p=d):await StructTreeRoot.canCreateStructureTree({catalogRef:f,pdfManager:i,newAnnotationsByPage:o})&&(p=null);const e=AnnotationFactory.generateImages(a.values(),E,i.evaluatorOptions.isOffscreenCanvasSupported),t=void 0===p?g:[];for(const[a,s]of o)t.push(i.getPage(a).then((t=>{const i=new WorkerTask(`Save (editor): page ${a}`);startWorkerTask(i);return t.saveNewAnnotations(l,i,s,e,n).finally((function(){finishWorkerTask(i)}))})));null===p?g.push(Promise.all(t).then((async()=>{await StructTreeRoot.createStructureTree({newAnnotationsByPage:o,xref:E,catalogRef:f,pdfManager:i,changes:n})}))):p&&g.push(Promise.all(t).then((async()=>{await p.updateStructureTree({newAnnotationsByPage:o,pdfManager:i,changes:n})})))}if(e)g.push(i.serializeXfaData(a));else for(let e=0;ee.needAppearances)),D=C instanceof Dict&&C.get("XFA")||null;let b=null,F=!1;if(Array.isArray(D)){for(let e=0,t=D.length;e{E.resetNewTemporaryRef()}))}));l.on("GetOperatorList",(function(e,t){const a=e.pageIndex;i.getPage(a).then((function(i){const s=new WorkerTask(`GetOperatorList: page ${a}`);startWorkerTask(s);const r=n>=yA?Date.now():0;i.getOperatorList({handler:l,sink:t,task:s,intent:e.intent,cacheKey:e.cacheKey,annotationStorage:e.annotationStorage,modifiedIds:e.modifiedIds}).then((function(e){finishWorkerTask(s);r&&info(`page=${a+1} - getOperatorList: time=${Date.now()-r}ms, len=${e.length}`);t.close()}),(function(e){finishWorkerTask(s);s.terminated||t.error(e)}))}))}));l.on("GetTextContent",(function(e,t){const{pageIndex:a,includeMarkedContent:s,disableNormalization:r}=e;i.getPage(a).then((function(e){const i=new WorkerTask("GetTextContent: page "+a);startWorkerTask(i);const g=n>=yA?Date.now():0;e.extractTextContent({handler:l,task:i,sink:t,includeMarkedContent:s,disableNormalization:r}).then((function(){finishWorkerTask(i);g&&info(`page=${a+1} - getTextContent: time=`+(Date.now()-g)+"ms");t.close()}),(function(e){finishWorkerTask(i);i.terminated||t.error(e)}))}))}));l.on("GetStructTree",(function(e){return i.getPage(e.pageIndex).then((function(e){return i.ensure(e,"getStructTree")}))}));l.on("FontFallback",(function(e){return i.fontFallback(e.id,l)}));l.on("Cleanup",(function(e){return i.cleanup(!0)}));l.on("Terminate",(function(e){a=!0;const t=[];if(i){i.terminate(new AbortException("Worker was terminated."));const e=i.cleanup();t.push(e);i=null}else clearGlobalCaches();s?.(new AbortException("Worker was terminated."));for(const e of r){t.push(e.finished);e.terminate()}return Promise.all(t).then((function(){l.destroy();l=null}))}));l.on("Ready",(function(t){setupDoc(e);e=null}));return h}static initializeFromPort(e){const t=new MessageHandler("worker","main",e);this.setup(t,e);t.send("ready",null)}}var Qg=__webpack_exports__.WorkerMessageHandler;export{Qg as WorkerMessageHandler}; \ No newline at end of file diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/web/images/loading-icon.gif b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/web/images/loading-icon.gif deleted file mode 100644 index 1c72ebb554be018511ae972c3f2361dff02dce02..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2545 zcma*pX;2es8VB%~zPr=ibVMCx-JQ^BhLDAsK)^**h(ZDp9YGuzZ%~j!}+w%FI;|aC7){7CdVvG)P{bng1y9Te*f}~*`1kQl$jwb z$tlW~rRS!X?#xfm_&6tTdp_`cjgYwbRFLNdoJCN$S-yhg`ZnC-yvedRSmOh%;Y`Gl6bY$Z-}#C=#F4%9!I1b zWQ~f+9P?;vhCxWwlwl=lrWG|7IYo;{jjmzJ5R9?f>n%-d@>kLINUc z4wM5dAO;kq<$}Dk{2-u0$I6@2N}&cUx9nmV1dYc8jfC}%=F9WCg^OQK9C6poh#2!A z3^EU*UFZvS^)?bu3T?J;@Ahb~%I?+@4!l5!*TjC}GIslNan-RCrrd~PdHYnNLJk+m&`$Y+NV(e>CCu%R#_8GqY4cv#j`#uRWdsg9DxWy(?oOvgCU}&@jy%c!H&-Q zqXJxajAtmQRoRa9V-RFXXh-bK*;Fum{BjpkYQGX~i@OZ^Dx0n&H}kv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vraLLWA;&tRhIKOvhW|HC|L-dLvAUF(MG0(Nl?4tB{RzN7I(}Cb%hwN{crFC8 zji#aJElKvDFV+&VI1V?oUMA>*kto0^;3W8FQBSZ|{ z$v~TqE=(8DZa^i$^oht&h};P1N&wMXorKh*Z68gPV&ouy>%f36Oqkwemyeas$Qbz# zV?7Jy%o7KY6^I=P@eCji%W`o5sf(5hySYo9$l4e2`(hIV_?=H-#R6}0$WVA|*(K@3 z=5?@RlcLh(meW%A4)hGzcvEpm(_w?>zhL*i&s9$2>r zAtk{8Cia|+Y+V!uX9BtpXoF%lswuRKsM!pSs!?yhlCy!269K0|b M?FSZn2B>%I-}ej|s{jB1 diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.css deleted file mode 100644 index 86a3716c501..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.css +++ /dev/null @@ -1,3274 +0,0 @@ -/* Copyright 2014 Mozilla Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -.messageBar{ - --closing-button-icon:url(images/messageBar_closingButton.svg); - --message-bar-close-button-color:var(--text-primary-color); - --message-bar-close-button-color-hover:var(--text-primary-color); - --message-bar-close-button-border-radius:4px; - --message-bar-close-button-border:none; - --message-bar-close-button-hover-bg-color:rgb(21 20 26 / 0.14); - --message-bar-close-button-active-bg-color:rgb(21 20 26 / 0.21); - --message-bar-close-button-focus-bg-color:rgb(21 20 26 / 0.07); -} - -@media (prefers-color-scheme: dark){ - -.messageBar{ - --message-bar-close-button-hover-bg-color:rgb(251 251 254 / 0.14); - --message-bar-close-button-active-bg-color:rgb(251 251 254 / 0.21); - --message-bar-close-button-focus-bg-color:rgb(251 251 254 / 0.07); -} - } - -@media screen and (forced-colors: active){ - -.messageBar{ - --message-bar-close-button-color:ButtonText; - --message-bar-close-button-border:1px solid ButtonText; - --message-bar-close-button-hover-bg-color:ButtonText; - --message-bar-close-button-active-bg-color:ButtonText; - --message-bar-close-button-focus-bg-color:ButtonText; - --message-bar-close-button-color-hover:HighlightText; -} - } - -.messageBar{ - - display:flex; - position:relative; - padding:8px 8px 8px 16px; - flex-direction:column; - justify-content:center; - align-items:center; - gap:8px; - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; - - border-radius:4px; - - border:1px solid var(--message-bar-border-color); - background:var(--message-bar-bg-color); - color:var(--message-bar-fg-color); -} - -.messageBar > div{ - display:flex; - align-items:flex-start; - gap:8px; - align-self:stretch; - } - -:is(.messageBar > div)::before{ - content:""; - display:inline-block; - width:16px; - height:16px; - -webkit-mask-image:var(--message-bar-icon); - mask-image:var(--message-bar-icon); - -webkit-mask-size:cover; - mask-size:cover; - background-color:var(--message-bar-icon-color); - flex-shrink:0; - } - -.messageBar button{ - cursor:pointer; - } - -:is(.messageBar button):focus-visible{ - outline:var(--focus-ring-outline); - outline-offset:2px; - } - -.messageBar .closeButton{ - width:32px; - height:32px; - background:none; - border-radius:var(--message-bar-close-button-border-radius); - border:var(--message-bar-close-button-border); - - display:flex; - align-items:center; - justify-content:center; - } - -:is(.messageBar .closeButton)::before{ - content:""; - display:inline-block; - width:16px; - height:16px; - -webkit-mask-image:var(--closing-button-icon); - mask-image:var(--closing-button-icon); - -webkit-mask-size:cover; - mask-size:cover; - background-color:var(--message-bar-close-button-color); - } - -:is(.messageBar .closeButton):is(:hover,:active,:focus)::before{ - background-color:var(--message-bar-close-button-color-hover); - } - -:is(.messageBar .closeButton):hover{ - background-color:var(--message-bar-close-button-hover-bg-color); - } - -:is(.messageBar .closeButton):active{ - background-color:var(--message-bar-close-button-active-bg-color); - } - -:is(.messageBar .closeButton):focus{ - background-color:var(--message-bar-close-button-focus-bg-color); - } - -:is(.messageBar .closeButton) > span{ - display:inline-block; - width:0; - height:0; - overflow:hidden; - } - -#editorUndoBar{ - --text-primary-color:#15141a; - - --message-bar-icon:url(images/secondaryToolbarButton-documentProperties.svg); - --message-bar-icon-color:#0060df; - --message-bar-bg-color:#deeafc; - --message-bar-fg-color:var(--text-primary-color); - --message-bar-border-color:rgb(0 0 0 / 0.08); - - --undo-button-bg-color:rgb(21 20 26 / 0.07); - --undo-button-bg-color-hover:rgb(21 20 26 / 0.14); - --undo-button-bg-color-active:rgb(21 20 26 / 0.21); - - --undo-button-fg-color:var(--message-bar-fg-color); - --undo-button-fg-color-hover:var(--undo-button-fg-color); - --undo-button-fg-color-active:var(--undo-button-fg-color); - - --focus-ring-color:#0060df; - --focus-ring-outline:2px solid var(--focus-ring-color); -} - -@media (prefers-color-scheme: dark){ - -#editorUndoBar{ - --text-primary-color:#fbfbfe; - - --message-bar-icon-color:#73a7f3; - --message-bar-bg-color:#003070; - --message-bar-border-color:rgb(255 255 255 / 0.08); - - --undo-button-bg-color:rgb(255 255 255 / 0.08); - --undo-button-bg-color-hover:rgb(255 255 255 / 0.14); - --undo-button-bg-color-active:rgb(255 255 255 / 0.21); -} - } - -@media screen and (forced-colors: active){ - -#editorUndoBar{ - --text-primary-color:CanvasText; - - --message-bar-icon-color:CanvasText; - --message-bar-bg-color:Canvas; - --message-bar-border-color:CanvasText; - - --undo-button-bg-color:ButtonText; - --undo-button-bg-color-hover:SelectedItem; - --undo-button-bg-color-active:SelectedItem; - - --undo-button-fg-color:ButtonFace; - --undo-button-fg-color-hover:SelectedItemText; - --undo-button-fg-color-active:SelectedItemText; - - --focus-ring-color:CanvasText; -} - } - -#editorUndoBar{ - - position:fixed; - top:50px; - left:50%; - transform:translateX(-50%); - z-index:10; - - padding-block:8px; - padding-inline:16px 8px; - - font:menu; - font-size:15px; - - cursor:default; -} - -#editorUndoBar button{ - cursor:pointer; - } - -#editorUndoBar #editorUndoBarUndoButton{ - border-radius:4px; - font-weight:590; - line-height:19.5px; - color:var(--undo-button-fg-color); - border:none; - padding:4px 16px; - margin-inline-start:8px; - height:32px; - - background-color:var(--undo-button-bg-color); - } - -:is(#editorUndoBar #editorUndoBarUndoButton):hover{ - background-color:var(--undo-button-bg-color-hover); - color:var(--undo-button-fg-color-hover); - } - -:is(#editorUndoBar #editorUndoBarUndoButton):active{ - background-color:var(--undo-button-bg-color-active); - color:var(--undo-button-fg-color-active); - } - -#editorUndoBar > div{ - align-items:center; - } - -.dialog{ - --dialog-bg-color:white; - --dialog-border-color:white; - --dialog-shadow:0 2px 14px 0 rgb(58 57 68 / 0.2); - --text-primary-color:#15141a; - --text-secondary-color:#5b5b66; - --hover-filter:brightness(0.9); - --focus-ring-color:#0060df; - --focus-ring-outline:2px solid var(--focus-ring-color); - --link-fg-color:#0060df; - --link-hover-fg-color:#0250bb; - --separator-color:#f0f0f4; - - --textarea-border-color:#8f8f9d; - --textarea-bg-color:white; - --textarea-fg-color:var(--text-secondary-color); - - --radio-bg-color:#f0f0f4; - --radio-checked-bg-color:#fbfbfe; - --radio-border-color:#8f8f9d; - --radio-checked-border-color:#0060df; - - --button-secondary-bg-color:#f0f0f4; - --button-secondary-fg-color:var(--text-primary-color); - --button-secondary-border-color:var(--button-secondary-bg-color); - --button-secondary-hover-bg-color:var(--button-secondary-bg-color); - --button-secondary-hover-fg-color:var(--button-secondary-fg-color); - --button-secondary-hover-border-color:var(--button-secondary-hover-bg-color); - - --button-primary-bg-color:#0060df; - --button-primary-fg-color:#fbfbfe; - --button-primary-border-color:var(--button-primary-bg-color); - --button-primary-hover-bg-color:var(--button-primary-bg-color); - --button-primary-hover-fg-color:var(--button-primary-fg-color); - --button-primary-hover-border-color:var(--button-primary-hover-bg-color); -} - -@media (prefers-color-scheme: dark){ - -.dialog{ - --dialog-bg-color:#1c1b22; - --dialog-border-color:#1c1b22; - --dialog-shadow:0 2px 14px 0 #15141a; - --text-primary-color:#fbfbfe; - --text-secondary-color:#cfcfd8; - --focus-ring-color:#0df; - --hover-filter:brightness(1.4); - --link-fg-color:#0df; - --link-hover-fg-color:#80ebff; - --separator-color:#52525e; - - --textarea-bg-color:#42414d; - - --radio-bg-color:#2b2a33; - --radio-checked-bg-color:#15141a; - --radio-checked-border-color:#0df; - - --button-secondary-bg-color:#2b2a33; - --button-primary-bg-color:#0df; - --button-primary-fg-color:#15141a; -} - } - -@media screen and (forced-colors: active){ - -.dialog{ - --dialog-bg-color:Canvas; - --dialog-border-color:CanvasText; - --dialog-shadow:none; - --text-primary-color:CanvasText; - --text-secondary-color:CanvasText; - --hover-filter:none; - --focus-ring-color:ButtonBorder; - --link-fg-color:LinkText; - --link-hover-fg-color:LinkText; - --separator-color:CanvasText; - - --textarea-border-color:ButtonBorder; - --textarea-bg-color:Field; - --textarea-fg-color:ButtonText; - - --radio-bg-color:ButtonFace; - --radio-checked-bg-color:ButtonFace; - --radio-border-color:ButtonText; - --radio-checked-border-color:ButtonText; - - --button-secondary-bg-color:ButtonFace; - --button-secondary-fg-color:ButtonText; - --button-secondary-border-color:ButtonText; - --button-secondary-hover-bg-color:AccentColor; - --button-secondary-hover-fg-color:AccentColorText; - - --button-primary-bg-color:ButtonText; - --button-primary-fg-color:ButtonFace; - --button-primary-hover-bg-color:AccentColor; - --button-primary-hover-fg-color:AccentColorText; -} - } - -.dialog{ - - font:message-box; - font-size:13px; - font-weight:400; - line-height:150%; - border-radius:4px; - padding:12px 16px; - border:1px solid var(--dialog-border-color); - background:var(--dialog-bg-color); - color:var(--text-primary-color); - box-shadow:var(--dialog-shadow); -} - -:is(.dialog .mainContainer) *:focus-visible{ - outline:var(--focus-ring-outline); - outline-offset:2px; - } - -:is(.dialog .mainContainer) .title{ - display:flex; - width:auto; - flex-direction:column; - justify-content:flex-end; - align-items:flex-start; - gap:12px; - } - -:is(:is(.dialog .mainContainer) .title) > span{ - font-size:13px; - font-style:normal; - font-weight:590; - line-height:150%; - } - -:is(.dialog .mainContainer) .dialogSeparator{ - width:100%; - height:0; - margin-block:4px; - border-top:1px solid var(--separator-color); - border-bottom:none; - } - -:is(.dialog .mainContainer) .dialogButtonsGroup{ - display:flex; - gap:12px; - align-self:flex-end; - } - -:is(.dialog .mainContainer) .radio{ - display:flex; - flex-direction:column; - align-items:flex-start; - gap:4px; - } - -:is(:is(.dialog .mainContainer) .radio) > .radioButton{ - display:flex; - gap:8px; - align-self:stretch; - align-items:center; - } - -:is(:is(:is(.dialog .mainContainer) .radio) > .radioButton) input{ - -webkit-appearance:none; - -moz-appearance:none; - appearance:none; - box-sizing:border-box; - width:16px; - height:16px; - border-radius:50%; - background-color:var(--radio-bg-color); - border:1px solid var(--radio-border-color); - } - -:is(:is(:is(:is(.dialog .mainContainer) .radio) > .radioButton) input):hover{ - filter:var(--hover-filter); - } - -:is(:is(:is(:is(.dialog .mainContainer) .radio) > .radioButton) input):checked{ - background-color:var(--radio-checked-bg-color); - border:4px solid var(--radio-checked-border-color); - } - -:is(:is(.dialog .mainContainer) .radio) > .radioLabel{ - display:flex; - padding-inline-start:24px; - align-items:flex-start; - gap:10px; - align-self:stretch; - } - -:is(:is(:is(.dialog .mainContainer) .radio) > .radioLabel) > span{ - flex:1 0 0; - font-size:11px; - color:var(--text-secondary-color); - } - -:is(.dialog .mainContainer) button:not(:is(.toggle-button,.closeButton)){ - border-radius:4px; - border:1px solid; - font:menu; - font-weight:600; - padding:4px 16px; - width:auto; - height:32px; - } - -:is(:is(.dialog .mainContainer) button:not(:is(.toggle-button,.closeButton))):hover{ - cursor:pointer; - filter:var(--hover-filter); - } - -.secondaryButton:is(:is(.dialog .mainContainer) button:not(:is(.toggle-button,.closeButton))){ - color:var(--button-secondary-fg-color); - background-color:var(--button-secondary-bg-color); - border-color:var(--button-secondary-border-color); - } - -.secondaryButton:is(:is(.dialog .mainContainer) button:not(:is(.toggle-button,.closeButton))):hover{ - color:var(--button-secondary-hover-fg-color); - background-color:var(--button-secondary-hover-bg-color); - border-color:var(--button-secondary-hover-border-color); - } - -.primaryButton:is(:is(.dialog .mainContainer) button:not(:is(.toggle-button,.closeButton))){ - color:var(--button-primary-fg-color); - background-color:var(--button-primary-bg-color); - border-color:var(--button-primary-border-color); - opacity:1; - } - -.primaryButton:is(:is(.dialog .mainContainer) button:not(:is(.toggle-button,.closeButton))):hover{ - color:var(--button-primary-hover-fg-color); - background-color:var(--button-primary-hover-bg-color); - border-color:var(--button-primary-hover-border-color); - } - -:is(.dialog .mainContainer) a{ - color:var(--link-fg-color); - } - -:is(:is(.dialog .mainContainer) a):hover{ - color:var(--link-hover-fg-color); - } - -:is(.dialog .mainContainer) textarea{ - font:inherit; - padding:8px; - resize:none; - margin:0; - box-sizing:border-box; - border-radius:4px; - border:1px solid var(--textarea-border-color); - background:var(--textarea-bg-color); - color:var(--textarea-fg-color); - } - -:is(:is(.dialog .mainContainer) textarea):focus{ - outline-offset:0; - border-color:transparent; - } - -:is(:is(.dialog .mainContainer) textarea):disabled{ - pointer-events:none; - opacity:0.4; - } - -:is(.dialog .mainContainer) .messageBar{ - --message-bar-bg-color:#ffebcd; - --message-bar-fg-color:#15141a; - --message-bar-border-color:rgb(0 0 0 / 0.08); - --message-bar-icon:url(images/messageBar_warning.svg); - --message-bar-icon-color:#cd411e; - } - -@media (prefers-color-scheme: dark){ - -:is(.dialog .mainContainer) .messageBar{ - --message-bar-bg-color:#5a3100; - --message-bar-fg-color:#fbfbfe; - --message-bar-border-color:rgb(255 255 255 / 0.08); - --message-bar-icon-color:#e49c49; - } - } - -@media screen and (forced-colors: active){ - -:is(.dialog .mainContainer) .messageBar{ - --message-bar-bg-color:HighlightText; - --message-bar-fg-color:CanvasText; - --message-bar-border-color:CanvasText; - --message-bar-icon-color:CanvasText; - } - } - -:is(.dialog .mainContainer) .messageBar{ - - align-self:stretch; - } - -:is(:is(:is(.dialog .mainContainer) .messageBar) > div)::before,:is(:is(:is(.dialog .mainContainer) .messageBar) > div) > div{ - margin-block:4px; - } - -:is(:is(:is(.dialog .mainContainer) .messageBar) > div) > div{ - display:flex; - flex-direction:column; - align-items:flex-start; - gap:8px; - flex:1 0 0; - } - -:is(:is(:is(:is(.dialog .mainContainer) .messageBar) > div) > div) .title{ - font-size:13px; - font-weight:590; - } - -:is(:is(:is(:is(.dialog .mainContainer) .messageBar) > div) > div) .description{ - font-size:13px; - } - -:is(.dialog .mainContainer) .toggler{ - display:flex; - align-items:center; - gap:8px; - align-self:stretch; - } - -:is(:is(.dialog .mainContainer) .toggler) > .togglerLabel{ - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; - } - -.textLayer{ - position:absolute; - text-align:initial; - inset:0; - overflow:clip; - opacity:1; - line-height:1; - -webkit-text-size-adjust:none; - -moz-text-size-adjust:none; - text-size-adjust:none; - forced-color-adjust:none; - transform-origin:0 0; - caret-color:CanvasText; - z-index:0; -} - -.textLayer.highlighting{ - touch-action:none; - } - -.textLayer :is(span,br){ - color:transparent; - position:absolute; - white-space:pre; - cursor:text; - transform-origin:0% 0%; - } - -.textLayer > :not(.markedContent),.textLayer .markedContent span:not(.markedContent){ - z-index:1; - } - -.textLayer span.markedContent{ - top:0; - height:0; - } - -.textLayer span[role="img"]{ - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; - cursor:default; - } - -.textLayer .highlight{ - --highlight-bg-color:rgb(180 0 170 / 0.25); - --highlight-selected-bg-color:rgb(0 100 0 / 0.25); - --highlight-backdrop-filter:none; - --highlight-selected-backdrop-filter:none; - } - -@media screen and (forced-colors: active){ - -.textLayer .highlight{ - --highlight-bg-color:transparent; - --highlight-selected-bg-color:transparent; - --highlight-backdrop-filter:var(--hcm-highlight-filter); - --highlight-selected-backdrop-filter:var( - --hcm-highlight-selected-filter - ); - } - } - -.textLayer .highlight{ - - margin:-1px; - padding:1px; - background-color:var(--highlight-bg-color); - -webkit-backdrop-filter:var(--highlight-backdrop-filter); - backdrop-filter:var(--highlight-backdrop-filter); - border-radius:4px; - } - -.appended:is(.textLayer .highlight){ - position:initial; - } - -.begin:is(.textLayer .highlight){ - border-radius:4px 0 0 4px; - } - -.end:is(.textLayer .highlight){ - border-radius:0 4px 4px 0; - } - -.middle:is(.textLayer .highlight){ - border-radius:0; - } - -.selected:is(.textLayer .highlight){ - background-color:var(--highlight-selected-bg-color); - -webkit-backdrop-filter:var(--highlight-selected-backdrop-filter); - backdrop-filter:var(--highlight-selected-backdrop-filter); - } - -.textLayer ::-moz-selection{ - background:rgba(0 0 255 / 0.25); - background:color-mix(in srgb, AccentColor, transparent 75%); - } - -.textLayer ::selection{ - background:rgba(0 0 255 / 0.25); - background:color-mix(in srgb, AccentColor, transparent 75%); - } - -.textLayer br::-moz-selection{ - background:transparent; - } - -.textLayer br::selection{ - background:transparent; - } - -.textLayer .endOfContent{ - display:block; - position:absolute; - inset:100% 0 0; - z-index:0; - cursor:default; - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; - } - -.textLayer.selecting .endOfContent{ - top:0; - } - -.annotationLayer{ - --annotation-unfocused-field-background:url("data:image/svg+xml;charset=UTF-8,"); - --input-focus-border-color:Highlight; - --input-focus-outline:1px solid Canvas; - --input-unfocused-border-color:transparent; - --input-disabled-border-color:transparent; - --input-hover-border-color:black; - --link-outline:none; -} - -@media screen and (forced-colors: active){ - -.annotationLayer{ - --input-focus-border-color:CanvasText; - --input-unfocused-border-color:ActiveText; - --input-disabled-border-color:GrayText; - --input-hover-border-color:Highlight; - --link-outline:1.5px solid LinkText; -} - - .annotationLayer .textWidgetAnnotation :is(input,textarea):required,.annotationLayer .choiceWidgetAnnotation select:required,.annotationLayer .buttonWidgetAnnotation:is(.checkBox,.radioButton) input:required{ - outline:1.5px solid selectedItem; - } - - .annotationLayer .linkAnnotation{ - outline:var(--link-outline); - } - - :is(.annotationLayer .linkAnnotation):hover{ - -webkit-backdrop-filter:var(--hcm-highlight-filter); - backdrop-filter:var(--hcm-highlight-filter); - } - - :is(.annotationLayer .linkAnnotation) > a:hover{ - opacity:0 !important; - background:none !important; - box-shadow:none; - } - - .annotationLayer .popupAnnotation .popup{ - outline:calc(1.5px * var(--scale-factor)) solid CanvasText !important; - background-color:ButtonFace !important; - color:ButtonText !important; - } - - .annotationLayer .highlightArea:hover::after{ - position:absolute; - top:0; - left:0; - width:100%; - height:100%; - -webkit-backdrop-filter:var(--hcm-highlight-filter); - backdrop-filter:var(--hcm-highlight-filter); - content:""; - pointer-events:none; - } - - .annotationLayer .popupAnnotation.focused .popup{ - outline:calc(3px * var(--scale-factor)) solid Highlight !important; - } - } - -.annotationLayer{ - - position:absolute; - top:0; - left:0; - pointer-events:none; - transform-origin:0 0; -} - -.annotationLayer[data-main-rotation="90"] .norotate{ - transform:rotate(270deg) translateX(-100%); - } - -.annotationLayer[data-main-rotation="180"] .norotate{ - transform:rotate(180deg) translate(-100%, -100%); - } - -.annotationLayer[data-main-rotation="270"] .norotate{ - transform:rotate(90deg) translateY(-100%); - } - -.annotationLayer.disabled section,.annotationLayer.disabled .popup{ - pointer-events:none; - } - -.annotationLayer .annotationContent{ - position:absolute; - width:100%; - height:100%; - pointer-events:none; - } - -.freetext:is(.annotationLayer .annotationContent){ - background:transparent; - border:none; - inset:0; - overflow:visible; - white-space:nowrap; - font:10px sans-serif; - line-height:1.35; - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; - } - -.annotationLayer section{ - position:absolute; - text-align:initial; - pointer-events:auto; - box-sizing:border-box; - transform-origin:0 0; - } - -:is(.annotationLayer section):has(div.annotationContent) canvas.annotationContent{ - display:none; - } - -.textLayer.selecting ~ .annotationLayer section{ - pointer-events:none; - } - -.annotationLayer :is(.linkAnnotation,.buttonWidgetAnnotation.pushButton) > a{ - position:absolute; - font-size:1em; - top:0; - left:0; - width:100%; - height:100%; - } - -.annotationLayer :is(.linkAnnotation,.buttonWidgetAnnotation.pushButton):not(.hasBorder) > a:hover{ - opacity:0.2; - background-color:rgb(255 255 0); - box-shadow:0 2px 10px rgb(255 255 0); - } - -.annotationLayer .linkAnnotation.hasBorder:hover{ - background-color:rgb(255 255 0 / 0.2); - } - -.annotationLayer .hasBorder{ - background-size:100% 100%; - } - -.annotationLayer .textAnnotation img{ - position:absolute; - cursor:pointer; - width:100%; - height:100%; - top:0; - left:0; - } - -.annotationLayer .textWidgetAnnotation :is(input,textarea),.annotationLayer .choiceWidgetAnnotation select,.annotationLayer .buttonWidgetAnnotation:is(.checkBox,.radioButton) input{ - background-image:var(--annotation-unfocused-field-background); - border:2px solid var(--input-unfocused-border-color); - box-sizing:border-box; - font:calc(9px * var(--scale-factor)) sans-serif; - height:100%; - margin:0; - vertical-align:top; - width:100%; - } - -.annotationLayer .textWidgetAnnotation :is(input,textarea):required,.annotationLayer .choiceWidgetAnnotation select:required,.annotationLayer .buttonWidgetAnnotation:is(.checkBox,.radioButton) input:required{ - outline:1.5px solid red; - } - -.annotationLayer .choiceWidgetAnnotation select option{ - padding:0; - } - -.annotationLayer .buttonWidgetAnnotation.radioButton input{ - border-radius:50%; - } - -.annotationLayer .textWidgetAnnotation textarea{ - resize:none; - } - -.annotationLayer .textWidgetAnnotation [disabled]:is(input,textarea),.annotationLayer .choiceWidgetAnnotation select[disabled],.annotationLayer .buttonWidgetAnnotation:is(.checkBox,.radioButton) input[disabled]{ - background:none; - border:2px solid var(--input-disabled-border-color); - cursor:not-allowed; - } - -.annotationLayer .textWidgetAnnotation :is(input,textarea):hover,.annotationLayer .choiceWidgetAnnotation select:hover,.annotationLayer .buttonWidgetAnnotation:is(.checkBox,.radioButton) input:hover{ - border:2px solid var(--input-hover-border-color); - } - -.annotationLayer .textWidgetAnnotation :is(input,textarea):hover,.annotationLayer .choiceWidgetAnnotation select:hover,.annotationLayer .buttonWidgetAnnotation.checkBox input:hover{ - border-radius:2px; - } - -.annotationLayer .textWidgetAnnotation :is(input,textarea):focus,.annotationLayer .choiceWidgetAnnotation select:focus{ - background:none; - border:2px solid var(--input-focus-border-color); - border-radius:2px; - outline:var(--input-focus-outline); - } - -.annotationLayer .buttonWidgetAnnotation:is(.checkBox,.radioButton) :focus{ - background-image:none; - background-color:transparent; - } - -.annotationLayer .buttonWidgetAnnotation.checkBox :focus{ - border:2px solid var(--input-focus-border-color); - border-radius:2px; - outline:var(--input-focus-outline); - } - -.annotationLayer .buttonWidgetAnnotation.radioButton :focus{ - border:2px solid var(--input-focus-border-color); - outline:var(--input-focus-outline); - } - -.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::before,.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::after,.annotationLayer .buttonWidgetAnnotation.radioButton input:checked::before{ - background-color:CanvasText; - content:""; - display:block; - position:absolute; - } - -.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::before,.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::after{ - height:80%; - left:45%; - width:1px; - } - -.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::before{ - transform:rotate(45deg); - } - -.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::after{ - transform:rotate(-45deg); - } - -.annotationLayer .buttonWidgetAnnotation.radioButton input:checked::before{ - border-radius:50%; - height:50%; - left:25%; - top:25%; - width:50%; - } - -.annotationLayer .textWidgetAnnotation input.comb{ - font-family:monospace; - padding-left:2px; - padding-right:0; - } - -.annotationLayer .textWidgetAnnotation input.comb:focus{ - width:103%; - } - -.annotationLayer .buttonWidgetAnnotation:is(.checkBox,.radioButton) input{ - -webkit-appearance:none; - -moz-appearance:none; - appearance:none; - } - -.annotationLayer .fileAttachmentAnnotation .popupTriggerArea{ - height:100%; - width:100%; - } - -.annotationLayer .popupAnnotation{ - position:absolute; - font-size:calc(9px * var(--scale-factor)); - pointer-events:none; - width:-moz-max-content; - width:max-content; - max-width:45%; - height:auto; - } - -.annotationLayer .popup{ - background-color:rgb(255 255 153); - box-shadow:0 calc(2px * var(--scale-factor)) calc(5px * var(--scale-factor)) rgb(136 136 136); - border-radius:calc(2px * var(--scale-factor)); - outline:1.5px solid rgb(255 255 74); - padding:calc(6px * var(--scale-factor)); - cursor:pointer; - font:message-box; - white-space:normal; - word-wrap:break-word; - pointer-events:auto; - } - -.annotationLayer .popupAnnotation.focused .popup{ - outline-width:3px; - } - -.annotationLayer .popup *{ - font-size:calc(9px * var(--scale-factor)); - } - -.annotationLayer .popup > .header{ - display:inline-block; - } - -.annotationLayer .popup > .header h1{ - display:inline; - } - -.annotationLayer .popup > .header .popupDate{ - display:inline-block; - margin-left:calc(5px * var(--scale-factor)); - width:-moz-fit-content; - width:fit-content; - } - -.annotationLayer .popupContent{ - border-top:1px solid rgb(51 51 51); - margin-top:calc(2px * var(--scale-factor)); - padding-top:calc(2px * var(--scale-factor)); - } - -.annotationLayer .richText > *{ - white-space:pre-wrap; - font-size:calc(9px * var(--scale-factor)); - } - -.annotationLayer .popupTriggerArea{ - cursor:pointer; - } - -.annotationLayer section svg{ - position:absolute; - width:100%; - height:100%; - top:0; - left:0; - } - -.annotationLayer .annotationTextContent{ - position:absolute; - width:100%; - height:100%; - opacity:0; - color:transparent; - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; - pointer-events:none; - } - -:is(.annotationLayer .annotationTextContent) span{ - width:100%; - display:inline-block; - } - -.annotationLayer svg.quadrilateralsContainer{ - contain:strict; - width:0; - height:0; - position:absolute; - top:0; - left:0; - z-index:-1; - } - -:root{ - --xfa-unfocused-field-background:url("data:image/svg+xml;charset=UTF-8,"); - --xfa-focus-outline:auto; -} - -@media screen and (forced-colors: active){ - :root{ - --xfa-focus-outline:2px solid CanvasText; - } - .xfaLayer *:required{ - outline:1.5px solid selectedItem; - } -} - -.xfaLayer{ - background-color:transparent; -} - -.xfaLayer .highlight{ - margin:-1px; - padding:1px; - background-color:rgb(239 203 237); - border-radius:4px; -} - -.xfaLayer .highlight.appended{ - position:initial; -} - -.xfaLayer .highlight.begin{ - border-radius:4px 0 0 4px; -} - -.xfaLayer .highlight.end{ - border-radius:0 4px 4px 0; -} - -.xfaLayer .highlight.middle{ - border-radius:0; -} - -.xfaLayer .highlight.selected{ - background-color:rgb(203 223 203); -} - -.xfaPage{ - overflow:hidden; - position:relative; -} - -.xfaContentarea{ - position:absolute; -} - -.xfaPrintOnly{ - display:none; -} - -.xfaLayer{ - position:absolute; - text-align:initial; - top:0; - left:0; - transform-origin:0 0; - line-height:1.2; -} - -.xfaLayer *{ - color:inherit; - font:inherit; - font-style:inherit; - font-weight:inherit; - font-kerning:inherit; - letter-spacing:-0.01px; - text-align:inherit; - text-decoration:inherit; - box-sizing:border-box; - background-color:transparent; - padding:0; - margin:0; - pointer-events:auto; - line-height:inherit; -} - -.xfaLayer *:required{ - outline:1.5px solid red; -} - -.xfaLayer div, -.xfaLayer svg, -.xfaLayer svg *{ - pointer-events:none; -} - -.xfaLayer a{ - color:blue; -} - -.xfaRich li{ - margin-left:3em; -} - -.xfaFont{ - color:black; - font-weight:normal; - font-kerning:none; - font-size:10px; - font-style:normal; - letter-spacing:0; - text-decoration:none; - vertical-align:0; -} - -.xfaCaption{ - overflow:hidden; - flex:0 0 auto; -} - -.xfaCaptionForCheckButton{ - overflow:hidden; - flex:1 1 auto; -} - -.xfaLabel{ - height:100%; - width:100%; -} - -.xfaLeft{ - display:flex; - flex-direction:row; - align-items:center; -} - -.xfaRight{ - display:flex; - flex-direction:row-reverse; - align-items:center; -} - -:is(.xfaLeft, .xfaRight) > :is(.xfaCaption, .xfaCaptionForCheckButton){ - max-height:100%; -} - -.xfaTop{ - display:flex; - flex-direction:column; - align-items:flex-start; -} - -.xfaBottom{ - display:flex; - flex-direction:column-reverse; - align-items:flex-start; -} - -:is(.xfaTop, .xfaBottom) > :is(.xfaCaption, .xfaCaptionForCheckButton){ - width:100%; -} - -.xfaBorder{ - background-color:transparent; - position:absolute; - pointer-events:none; -} - -.xfaWrapped{ - width:100%; - height:100%; -} - -:is(.xfaTextfield, .xfaSelect):focus{ - background-image:none; - background-color:transparent; - outline:var(--xfa-focus-outline); - outline-offset:-1px; -} - -:is(.xfaCheckbox, .xfaRadio):focus{ - outline:var(--xfa-focus-outline); -} - -.xfaTextfield, -.xfaSelect{ - height:100%; - width:100%; - flex:1 1 auto; - border:none; - resize:none; - background-image:var(--xfa-unfocused-field-background); -} - -.xfaSelect{ - padding-inline:2px; -} - -:is(.xfaTop, .xfaBottom) > :is(.xfaTextfield, .xfaSelect){ - flex:0 1 auto; -} - -.xfaButton{ - cursor:pointer; - width:100%; - height:100%; - border:none; - text-align:center; -} - -.xfaLink{ - width:100%; - height:100%; - position:absolute; - top:0; - left:0; -} - -.xfaCheckbox, -.xfaRadio{ - width:100%; - height:100%; - flex:0 0 auto; - border:none; -} - -.xfaRich{ - white-space:pre-wrap; - width:100%; - height:100%; -} - -.xfaImage{ - -o-object-position:left top; - object-position:left top; - -o-object-fit:contain; - object-fit:contain; - width:100%; - height:100%; -} - -.xfaLrTb, -.xfaRlTb, -.xfaTb{ - display:flex; - flex-direction:column; - align-items:stretch; -} - -.xfaLr{ - display:flex; - flex-direction:row; - align-items:stretch; -} - -.xfaRl{ - display:flex; - flex-direction:row-reverse; - align-items:stretch; -} - -.xfaTb > div{ - justify-content:left; -} - -.xfaPosition{ - position:relative; -} - -.xfaArea{ - position:relative; -} - -.xfaValignMiddle{ - display:flex; - align-items:center; -} - -.xfaTable{ - display:flex; - flex-direction:column; - align-items:stretch; -} - -.xfaTable .xfaRow{ - display:flex; - flex-direction:row; - align-items:stretch; -} - -.xfaTable .xfaRlRow{ - display:flex; - flex-direction:row-reverse; - align-items:stretch; - flex:1; -} - -.xfaTable .xfaRlRow > div{ - flex:1; -} - -:is(.xfaNonInteractive, .xfaDisabled, .xfaReadOnly) :is(input, textarea){ - background:initial; -} - -@media print{ - .xfaTextfield, - .xfaSelect{ - background:transparent; - } - - .xfaSelect{ - -webkit-appearance:none; - -moz-appearance:none; - appearance:none; - text-indent:1px; - text-overflow:""; - } -} - -.canvasWrapper svg{ - transform:none; - } - -.moving:is(.canvasWrapper svg){ - z-index:100000; - } - -[data-main-rotation="90"]:is(.highlight:is(.canvasWrapper svg),.highlightOutline:is(.canvasWrapper svg)) mask,[data-main-rotation="90"]:is(.highlight:is(.canvasWrapper svg),.highlightOutline:is(.canvasWrapper svg)) use:not(.clip,.mask){ - transform:matrix(0, 1, -1, 0, 1, 0); - } - -[data-main-rotation="180"]:is(.highlight:is(.canvasWrapper svg),.highlightOutline:is(.canvasWrapper svg)) mask,[data-main-rotation="180"]:is(.highlight:is(.canvasWrapper svg),.highlightOutline:is(.canvasWrapper svg)) use:not(.clip,.mask){ - transform:matrix(-1, 0, 0, -1, 1, 1); - } - -[data-main-rotation="270"]:is(.highlight:is(.canvasWrapper svg),.highlightOutline:is(.canvasWrapper svg)) mask,[data-main-rotation="270"]:is(.highlight:is(.canvasWrapper svg),.highlightOutline:is(.canvasWrapper svg)) use:not(.clip,.mask){ - transform:matrix(0, -1, 1, 0, 0, 1); - } - -.draw:is(.canvasWrapper svg){ - position:absolute; - mix-blend-mode:normal; - } - -.draw[data-draw-rotation="90"]:is(.canvasWrapper svg){ - transform:rotate(90deg); - } - -.draw[data-draw-rotation="180"]:is(.canvasWrapper svg){ - transform:rotate(180deg); - } - -.draw[data-draw-rotation="270"]:is(.canvasWrapper svg){ - transform:rotate(270deg); - } - -.highlight:is(.canvasWrapper svg){ - --blend-mode:multiply; - } - -@media screen and (forced-colors: active){ - -.highlight:is(.canvasWrapper svg){ - --blend-mode:difference; - } - } - -.highlight:is(.canvasWrapper svg){ - - position:absolute; - mix-blend-mode:var(--blend-mode); - } - -.highlight:is(.canvasWrapper svg):not(.free){ - fill-rule:evenodd; - } - -.highlightOutline:is(.canvasWrapper svg){ - position:absolute; - mix-blend-mode:normal; - fill-rule:evenodd; - fill:none; - } - -.highlightOutline.hovered:is(.canvasWrapper svg):not(.free):not(.selected){ - stroke:var(--hover-outline-color); - stroke-width:var(--outline-width); - } - -.highlightOutline.selected:is(.canvasWrapper svg):not(.free) .mainOutline{ - stroke:var(--outline-around-color); - stroke-width:calc( - var(--outline-width) + 2 * var(--outline-around-width) - ); - } - -.highlightOutline.selected:is(.canvasWrapper svg):not(.free) .secondaryOutline{ - stroke:var(--outline-color); - stroke-width:var(--outline-width); - } - -.highlightOutline.free.hovered:is(.canvasWrapper svg):not(.selected){ - stroke:var(--hover-outline-color); - stroke-width:calc(2 * var(--outline-width)); - } - -.highlightOutline.free.selected:is(.canvasWrapper svg) .mainOutline{ - stroke:var(--outline-around-color); - stroke-width:calc( - 2 * (var(--outline-width) + var(--outline-around-width)) - ); - } - -.highlightOutline.free.selected:is(.canvasWrapper svg) .secondaryOutline{ - stroke:var(--outline-color); - stroke-width:calc(2 * var(--outline-width)); - } - -.toggle-button{ - --button-background-color:#f0f0f4; - --button-background-color-hover:#e0e0e6; - --button-background-color-active:#cfcfd8; - --color-accent-primary:#0060df; - --color-accent-primary-hover:#0250bb; - --color-accent-primary-active:#054096; - --border-interactive-color:#8f8f9d; - --border-radius-circle:9999px; - --border-width:1px; - --size-item-small:16px; - --size-item-large:32px; - --color-canvas:white; -} - -@media (prefers-color-scheme: dark){ - -.toggle-button{ - --button-background-color:color-mix(in srgb, currentColor 7%, transparent); - --button-background-color-hover:color-mix( - in srgb, - currentColor 14%, - transparent - ); - --button-background-color-active:color-mix( - in srgb, - currentColor 21%, - transparent - ); - --color-accent-primary:#0df; - --color-accent-primary-hover:#80ebff; - --color-accent-primary-active:#aaf2ff; - --border-interactive-color:#bfbfc9; - --color-canvas:#1c1b22; -} - } - -@media (forced-colors: active){ - -.toggle-button{ - --color-accent-primary:ButtonText; - --color-accent-primary-hover:SelectedItem; - --color-accent-primary-active:SelectedItem; - --border-interactive-color:ButtonText; - --button-background-color:ButtonFace; - --border-interactive-color-hover:SelectedItem; - --border-interactive-color-active:SelectedItem; - --border-interactive-color-disabled:GrayText; - --color-canvas:ButtonText; -} - } - -.toggle-button{ - - --toggle-background-color:var(--button-background-color); - --toggle-background-color-hover:var(--button-background-color-hover); - --toggle-background-color-active:var(--button-background-color-active); - --toggle-background-color-pressed:var(--color-accent-primary); - --toggle-background-color-pressed-hover:var(--color-accent-primary-hover); - --toggle-background-color-pressed-active:var(--color-accent-primary-active); - --toggle-border-color:var(--border-interactive-color); - --toggle-border-color-hover:var(--toggle-border-color); - --toggle-border-color-active:var(--toggle-border-color); - --toggle-border-radius:var(--border-radius-circle); - --toggle-border-width:var(--border-width); - --toggle-height:var(--size-item-small); - --toggle-width:var(--size-item-large); - --toggle-dot-background-color:var(--toggle-border-color); - --toggle-dot-background-color-hover:var(--toggle-dot-background-color); - --toggle-dot-background-color-active:var(--toggle-dot-background-color); - --toggle-dot-background-color-on-pressed:var(--color-canvas); - --toggle-dot-margin:1px; - --toggle-dot-height:calc( - var(--toggle-height) - 2 * var(--toggle-dot-margin) - 2 * - var(--toggle-border-width) - ); - --toggle-dot-width:var(--toggle-dot-height); - --toggle-dot-transform-x:calc( - var(--toggle-width) - 4 * var(--toggle-dot-margin) - var(--toggle-dot-width) - ); - - -webkit-appearance:none; - - -moz-appearance:none; - - appearance:none; - padding:0; - margin:0; - border:var(--toggle-border-width) solid var(--toggle-border-color); - height:var(--toggle-height); - width:var(--toggle-width); - border-radius:var(--toggle-border-radius); - background:var(--toggle-background-color); - box-sizing:border-box; - flex-shrink:0; -} - -.toggle-button:focus-visible{ - outline:var(--focus-outline); - outline-offset:var(--focus-outline-offset); - } - -.toggle-button:enabled:hover{ - background:var(--toggle-background-color-hover); - border-color:var(--toggle-border-color); - } - -.toggle-button:enabled:active{ - background:var(--toggle-background-color-active); - border-color:var(--toggle-border-color); - } - -.toggle-button[aria-pressed="true"]{ - background:var(--toggle-background-color-pressed); - border-color:transparent; - } - -.toggle-button[aria-pressed="true"]:enabled:hover{ - background:var(--toggle-background-color-pressed-hover); - border-color:transparent; - } - -.toggle-button[aria-pressed="true"]:enabled:active{ - background:var(--toggle-background-color-pressed-active); - border-color:transparent; - } - -.toggle-button::before{ - display:block; - content:""; - background-color:var(--toggle-dot-background-color); - height:var(--toggle-dot-height); - width:var(--toggle-dot-width); - margin:var(--toggle-dot-margin); - border-radius:var(--toggle-border-radius); - translate:0; - } - -.toggle-button[aria-pressed="true"]::before{ - translate:var(--toggle-dot-transform-x); - background-color:var(--toggle-dot-background-color-on-pressed); - } - -.toggle-button[aria-pressed="true"]:enabled:hover::before,.toggle-button[aria-pressed="true"]:enabled:active::before{ - background-color:var(--toggle-dot-background-color-on-pressed); - } - -[dir="rtl"] .toggle-button[aria-pressed="true"]::before{ - translate:calc(-1 * var(--toggle-dot-transform-x)); - } - -@media (prefers-reduced-motion: no-preference){ - .toggle-button::before{ - transition:translate 100ms; - } - } - -@media (prefers-contrast){ - .toggle-button:enabled:hover{ - border-color:var(--toggle-border-color-hover); - } - - .toggle-button:enabled:active{ - border-color:var(--toggle-border-color-active); - } - - .toggle-button[aria-pressed="true"]:enabled{ - border-color:var(--toggle-border-color); - position:relative; - } - - .toggle-button[aria-pressed="true"]:enabled:hover,.toggle-button[aria-pressed="true"]:enabled:hover:active{ - border-color:var(--toggle-border-color-hover); - } - - .toggle-button[aria-pressed="true"]:enabled:active{ - background-color:var(--toggle-dot-background-color-active); - border-color:var(--toggle-dot-background-color-hover); - } - - .toggle-button:hover::before,.toggle-button:active::before{ - background-color:var(--toggle-dot-background-color-hover); - } - } - -@media (forced-colors){ - -.toggle-button{ - --toggle-dot-background-color:var(--color-accent-primary); - --toggle-dot-background-color-hover:var(--color-accent-primary-hover); - --toggle-dot-background-color-active:var(--color-accent-primary-active); - --toggle-dot-background-color-on-pressed:var(--button-background-color); - --toggle-background-color-disabled:var(--button-background-color-disabled); - --toggle-border-color-hover:var(--border-interactive-color-hover); - --toggle-border-color-active:var(--border-interactive-color-active); - --toggle-border-color-disabled:var(--border-interactive-color-disabled); -} - - .toggle-button[aria-pressed="true"]:enabled::after{ - border:1px solid var(--button-background-color); - content:""; - position:absolute; - height:var(--toggle-height); - width:var(--toggle-width); - display:block; - border-radius:var(--toggle-border-radius); - inset:-2px; - } - - .toggle-button[aria-pressed="true"]:enabled:active::after{ - border-color:var(--toggle-border-color-active); - } - } - -:root{ - --outline-width:2px; - --outline-color:#0060df; - --outline-around-width:1px; - --outline-around-color:#f0f0f4; - --hover-outline-around-color:var(--outline-around-color); - --focus-outline:solid var(--outline-width) var(--outline-color); - --unfocus-outline:solid var(--outline-width) transparent; - --focus-outline-around:solid var(--outline-around-width) var(--outline-around-color); - --hover-outline-color:#8f8f9d; - --hover-outline:solid var(--outline-width) var(--hover-outline-color); - --hover-outline-around:solid var(--outline-around-width) var(--hover-outline-around-color); - --freetext-line-height:1.35; - --freetext-padding:2px; - --resizer-bg-color:var(--outline-color); - --resizer-size:6px; - --resizer-shift:calc( - 0px - (var(--outline-width) + var(--resizer-size)) / 2 - - var(--outline-around-width) - ); - --editorFreeText-editing-cursor:text; - --editorInk-editing-cursor:url(images/cursor-editorInk.svg) 0 16, pointer; - --editorHighlight-editing-cursor:url(images/cursor-editorTextHighlight.svg) 24 24, text; - --editorFreeHighlight-editing-cursor:url(images/cursor-editorFreeHighlight.svg) 1 18, pointer; - - --new-alt-text-warning-image:url(images/altText_warning.svg); -} -.visuallyHidden{ - position:absolute; - top:0; - left:0; - border:0; - margin:0; - padding:0; - width:0; - height:0; - overflow:hidden; - white-space:nowrap; - font-size:0; -} - -.textLayer.highlighting{ - cursor:var(--editorFreeHighlight-editing-cursor); - } - -.textLayer.highlighting:not(.free) span{ - cursor:var(--editorHighlight-editing-cursor); - } - -[role="img"]:is(.textLayer.highlighting:not(.free) span){ - cursor:var(--editorFreeHighlight-editing-cursor); - } - -.textLayer.highlighting.free span{ - cursor:var(--editorFreeHighlight-editing-cursor); - } - -:is(#viewerContainer.pdfPresentationMode:fullscreen,.annotationEditorLayer.disabled) .noAltTextBadge{ - display:none !important; - } - -@media (min-resolution: 1.1dppx){ - :root{ - --editorFreeText-editing-cursor:url(images/cursor-editorFreeText.svg) 0 16, text; - } -} - -@media screen and (forced-colors: active){ - :root{ - --outline-color:CanvasText; - --outline-around-color:ButtonFace; - --resizer-bg-color:ButtonText; - --hover-outline-color:Highlight; - --hover-outline-around-color:SelectedItemText; - } -} - -[data-editor-rotation="90"]{ - transform:rotate(90deg); -} - -[data-editor-rotation="180"]{ - transform:rotate(180deg); -} - -[data-editor-rotation="270"]{ - transform:rotate(270deg); -} - -.annotationEditorLayer{ - background:transparent; - position:absolute; - inset:0; - font-size:calc(100px * var(--scale-factor)); - transform-origin:0 0; - cursor:auto; -} - -.annotationEditorLayer .selectedEditor{ - z-index:100000 !important; - } - -.annotationEditorLayer.drawing *{ - pointer-events:none !important; - } - -.annotationEditorLayer.waiting{ - content:""; - cursor:wait; - position:absolute; - inset:0; - width:100%; - height:100%; -} - -.annotationEditorLayer.disabled{ - pointer-events:none; -} - -.annotationEditorLayer.freetextEditing{ - cursor:var(--editorFreeText-editing-cursor); -} - -.annotationEditorLayer.inkEditing{ - cursor:var(--editorInk-editing-cursor); -} - -.annotationEditorLayer .draw{ - box-sizing:border-box; -} - -.annotationEditorLayer :is(.freeTextEditor, .inkEditor, .stampEditor){ - position:absolute; - background:transparent; - z-index:1; - transform-origin:0 0; - cursor:auto; - max-width:100%; - max-height:100%; - border:var(--unfocus-outline); -} - -.draggable.selectedEditor:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)){ - cursor:move; - } - -.selectedEditor:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)){ - border:var(--focus-outline); - outline:var(--focus-outline-around); - } - -.selectedEditor:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor))::before{ - content:""; - position:absolute; - inset:0; - border:var(--focus-outline-around); - pointer-events:none; - } - -:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)):hover:not(.selectedEditor){ - border:var(--hover-outline); - outline:var(--hover-outline-around); - } - -:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)):hover:not(.selectedEditor)::before{ - content:""; - position:absolute; - inset:0; - border:var(--focus-outline-around); - } - -:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar{ - --editor-toolbar-delete-image:url(images/editor-toolbar-delete.svg); - --editor-toolbar-bg-color:#f0f0f4; - --editor-toolbar-highlight-image:url(images/toolbarButton-editorHighlight.svg); - --editor-toolbar-fg-color:#2e2e56; - --editor-toolbar-border-color:#8f8f9d; - --editor-toolbar-hover-border-color:var(--editor-toolbar-border-color); - --editor-toolbar-hover-bg-color:#e0e0e6; - --editor-toolbar-hover-fg-color:var(--editor-toolbar-fg-color); - --editor-toolbar-hover-outline:none; - --editor-toolbar-focus-outline-color:#0060df; - --editor-toolbar-shadow:0 2px 6px 0 rgb(58 57 68 / 0.2); - --editor-toolbar-vert-offset:6px; - --editor-toolbar-height:28px; - --editor-toolbar-padding:2px; - --alt-text-done-color:#2ac3a2; - --alt-text-warning-color:#0090ed; - --alt-text-hover-done-color:var(--alt-text-done-color); - --alt-text-hover-warning-color:var(--alt-text-warning-color); - } - -@media (prefers-color-scheme: dark){ - -:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar{ - --editor-toolbar-bg-color:#2b2a33; - --editor-toolbar-fg-color:#fbfbfe; - --editor-toolbar-hover-bg-color:#52525e; - --editor-toolbar-focus-outline-color:#0df; - --alt-text-done-color:#54ffbd; - --alt-text-warning-color:#80ebff; - } - } - -@media screen and (forced-colors: active){ - -:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar{ - --editor-toolbar-bg-color:ButtonFace; - --editor-toolbar-fg-color:ButtonText; - --editor-toolbar-border-color:ButtonText; - --editor-toolbar-hover-border-color:AccentColor; - --editor-toolbar-hover-bg-color:ButtonFace; - --editor-toolbar-hover-fg-color:AccentColor; - --editor-toolbar-hover-outline:2px solid var(--editor-toolbar-hover-border-color); - --editor-toolbar-focus-outline-color:ButtonBorder; - --editor-toolbar-shadow:none; - --alt-text-done-color:var(--editor-toolbar-fg-color); - --alt-text-warning-color:var(--editor-toolbar-fg-color); - --alt-text-hover-done-color:var(--editor-toolbar-hover-fg-color); - --alt-text-hover-warning-color:var(--editor-toolbar-hover-fg-color); - } - } - -:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar{ - - display:flex; - width:-moz-fit-content; - width:fit-content; - height:var(--editor-toolbar-height); - flex-direction:column; - justify-content:center; - align-items:center; - cursor:default; - pointer-events:auto; - box-sizing:content-box; - padding:var(--editor-toolbar-padding); - - position:absolute; - inset-inline-end:0; - inset-block-start:calc(100% + var(--editor-toolbar-vert-offset)); - - border-radius:6px; - background-color:var(--editor-toolbar-bg-color); - border:1px solid var(--editor-toolbar-border-color); - box-shadow:var(--editor-toolbar-shadow); - } - -.hidden:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar){ - display:none; - } - -:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar):has(:focus-visible){ - border-color:transparent; - } - -[dir="ltr"] :is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar){ - transform-origin:100% 0; - } - -[dir="rtl"] :is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar){ - transform-origin:0 0; - } - -:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons{ - display:flex; - justify-content:center; - align-items:center; - gap:0; - height:100%; - } - -:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) button{ - padding:0; - } - -:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .divider{ - width:0; - height:calc( - 2 * var(--editor-toolbar-padding) + var(--editor-toolbar-height) - ); - border-left:1px solid var(--editor-toolbar-border-color); - border-right:none; - display:inline-block; - margin-inline:2px; - } - -:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .highlightButton{ - width:var(--editor-toolbar-height); - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .highlightButton)::before{ - content:""; - -webkit-mask-image:var(--editor-toolbar-highlight-image); - mask-image:var(--editor-toolbar-highlight-image); - -webkit-mask-repeat:no-repeat; - mask-repeat:no-repeat; - -webkit-mask-position:center; - mask-position:center; - display:inline-block; - background-color:var(--editor-toolbar-fg-color); - width:100%; - height:100%; - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .highlightButton):hover::before{ - background-color:var(--editor-toolbar-hover-fg-color); - } - -:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .delete{ - width:var(--editor-toolbar-height); - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .delete)::before{ - content:""; - -webkit-mask-image:var(--editor-toolbar-delete-image); - mask-image:var(--editor-toolbar-delete-image); - -webkit-mask-repeat:no-repeat; - mask-repeat:no-repeat; - -webkit-mask-position:center; - mask-position:center; - display:inline-block; - background-color:var(--editor-toolbar-fg-color); - width:100%; - height:100%; - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .delete):hover::before{ - background-color:var(--editor-toolbar-hover-fg-color); - } - -:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) > *{ - height:var(--editor-toolbar-height); - } - -:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) > :not(.divider){ - border:none; - background-color:transparent; - cursor:pointer; - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) > :not(.divider)):hover{ - border-radius:2px; - background-color:var(--editor-toolbar-hover-bg-color); - color:var(--editor-toolbar-hover-fg-color); - outline:var(--editor-toolbar-hover-outline); - outline-offset:1px; - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) > :not(.divider)):hover:active{ - outline:none; - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) > :not(.divider)):focus-visible{ - border-radius:2px; - outline:2px solid var(--editor-toolbar-focus-outline-color); - } - -:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText{ - --alt-text-add-image:url(images/altText_add.svg); - --alt-text-done-image:url(images/altText_done.svg); - - display:flex; - align-items:center; - justify-content:center; - width:-moz-max-content; - width:max-content; - padding-inline:8px; - pointer-events:all; - font:menu; - font-weight:590; - font-size:12px; - color:var(--editor-toolbar-fg-color); - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText):disabled{ - pointer-events:none; - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText)::before{ - content:""; - -webkit-mask-image:var(--alt-text-add-image); - mask-image:var(--alt-text-add-image); - -webkit-mask-repeat:no-repeat; - mask-repeat:no-repeat; - -webkit-mask-position:center; - mask-position:center; - display:inline-block; - width:12px; - height:13px; - background-color:var(--editor-toolbar-fg-color); - margin-inline-end:4px; - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText):hover::before{ - background-color:var(--editor-toolbar-hover-fg-color); - } - -.done:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText)::before{ - -webkit-mask-image:var(--alt-text-done-image); - mask-image:var(--alt-text-done-image); - } - -.new:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText)::before{ - width:16px; - height:16px; - -webkit-mask-image:var(--new-alt-text-warning-image); - mask-image:var(--new-alt-text-warning-image); - background-color:var(--alt-text-warning-color); - -webkit-mask-size:cover; - mask-size:cover; - } - -.new:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText):hover::before{ - background-color:var(--alt-text-hover-warning-color); - } - -.new.done:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText)::before{ - -webkit-mask-image:var(--alt-text-done-image); - mask-image:var(--alt-text-done-image); - background-color:var(--alt-text-done-color); - } - -.new.done:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText):hover::before{ - background-color:var(--alt-text-hover-done-color); - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText) .tooltip{ - display:none; - word-wrap:anywhere; - } - -.show:is(:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText) .tooltip){ - --alt-text-tooltip-bg:#f0f0f4; - --alt-text-tooltip-fg:#15141a; - --alt-text-tooltip-border:#8f8f9d; - --alt-text-tooltip-shadow:0px 2px 6px 0px rgb(58 57 68 / 0.2); - } - -@media (prefers-color-scheme: dark){ - -.show:is(:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText) .tooltip){ - --alt-text-tooltip-bg:#1c1b22; - --alt-text-tooltip-fg:#fbfbfe; - --alt-text-tooltip-shadow:0px 2px 6px 0px #15141a; - } - } - -@media screen and (forced-colors: active){ - -.show:is(:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText) .tooltip){ - --alt-text-tooltip-bg:Canvas; - --alt-text-tooltip-fg:CanvasText; - --alt-text-tooltip-border:CanvasText; - --alt-text-tooltip-shadow:none; - } - } - -.show:is(:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText) .tooltip){ - - display:inline-flex; - flex-direction:column; - align-items:center; - justify-content:center; - position:absolute; - top:calc(100% + 2px); - inset-inline-start:0; - padding-block:2px 3px; - padding-inline:3px; - max-width:300px; - width:-moz-max-content; - width:max-content; - height:auto; - font-size:12px; - - border:0.5px solid var(--alt-text-tooltip-border); - background:var(--alt-text-tooltip-bg); - box-shadow:var(--alt-text-tooltip-shadow); - color:var(--alt-text-tooltip-fg); - - pointer-events:none; - } - -.annotationEditorLayer .freeTextEditor{ - padding:calc(var(--freetext-padding) * var(--scale-factor)); - width:auto; - height:auto; - touch-action:none; -} - -.annotationEditorLayer .freeTextEditor .internal{ - background:transparent; - border:none; - inset:0; - overflow:visible; - white-space:nowrap; - font:10px sans-serif; - line-height:var(--freetext-line-height); - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; -} - -.annotationEditorLayer .freeTextEditor .overlay{ - position:absolute; - display:none; - background:transparent; - inset:0; - width:100%; - height:100%; -} - -.annotationEditorLayer freeTextEditor .overlay.enabled{ - display:block; -} - -.annotationEditorLayer .freeTextEditor .internal:empty::before{ - content:attr(default-content); - color:gray; -} - -.annotationEditorLayer .freeTextEditor .internal:focus{ - outline:none; - -webkit-user-select:auto; - -moz-user-select:auto; - user-select:auto; -} - -.annotationEditorLayer .inkEditor{ - width:100%; - height:100%; -} - -.annotationEditorLayer .inkEditor.editing{ - cursor:inherit; -} - -.annotationEditorLayer .inkEditor .inkEditorCanvas{ - position:absolute; - inset:0; - width:100%; - height:100%; - touch-action:none; -} - -.annotationEditorLayer .stampEditor{ - width:auto; - height:auto; -} - -:is(.annotationEditorLayer .stampEditor) canvas{ - position:absolute; - width:100%; - height:100%; - margin:0; - top:0; - left:0; - } - -:is(.annotationEditorLayer .stampEditor) .noAltTextBadge{ - --no-alt-text-badge-border-color:#f0f0f4; - --no-alt-text-badge-bg-color:#cfcfd8; - --no-alt-text-badge-fg-color:#5b5b66; - } - -@media (prefers-color-scheme: dark){ - -:is(.annotationEditorLayer .stampEditor) .noAltTextBadge{ - --no-alt-text-badge-border-color:#52525e; - --no-alt-text-badge-bg-color:#fbfbfe; - --no-alt-text-badge-fg-color:#15141a; - } - } - -@media screen and (forced-colors: active){ - -:is(.annotationEditorLayer .stampEditor) .noAltTextBadge{ - --no-alt-text-badge-border-color:ButtonText; - --no-alt-text-badge-bg-color:ButtonFace; - --no-alt-text-badge-fg-color:ButtonText; - } - } - -:is(.annotationEditorLayer .stampEditor) .noAltTextBadge{ - - position:absolute; - inset-inline-end:5px; - inset-block-end:5px; - display:inline-flex; - width:32px; - height:32px; - padding:3px; - justify-content:center; - align-items:center; - pointer-events:none; - z-index:1; - - border-radius:2px; - border:1px solid var(--no-alt-text-badge-border-color); - background:var(--no-alt-text-badge-bg-color); - } - -:is(:is(.annotationEditorLayer .stampEditor) .noAltTextBadge)::before{ - content:""; - display:inline-block; - width:16px; - height:16px; - -webkit-mask-image:var(--new-alt-text-warning-image); - mask-image:var(--new-alt-text-warning-image); - -webkit-mask-size:cover; - mask-size:cover; - background-color:var(--no-alt-text-badge-fg-color); - } - -:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers{ - position:absolute; - inset:0; - } - -.hidden:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers){ - display:none; - } - -:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer{ - width:var(--resizer-size); - height:var(--resizer-size); - background:content-box var(--resizer-bg-color); - border:var(--focus-outline-around); - border-radius:2px; - position:absolute; - } - -.topLeft:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer){ - top:var(--resizer-shift); - left:var(--resizer-shift); - } - -.topMiddle:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer){ - top:var(--resizer-shift); - left:calc(50% + var(--resizer-shift)); - } - -.topRight:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer){ - top:var(--resizer-shift); - right:var(--resizer-shift); - } - -.middleRight:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer){ - top:calc(50% + var(--resizer-shift)); - right:var(--resizer-shift); - } - -.bottomRight:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer){ - bottom:var(--resizer-shift); - right:var(--resizer-shift); - } - -.bottomMiddle:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer){ - bottom:var(--resizer-shift); - left:calc(50% + var(--resizer-shift)); - } - -.bottomLeft:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer){ - bottom:var(--resizer-shift); - left:var(--resizer-shift); - } - -.middleLeft:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer){ - top:calc(50% + var(--resizer-shift)); - left:var(--resizer-shift); - } - -.topLeft:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="180"],[data-editor-rotation="0"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="90"],[data-editor-rotation="270"])) > .resizers > .resizer),.bottomRight:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="180"],[data-editor-rotation="0"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="90"],[data-editor-rotation="270"])) > .resizers > .resizer){ - cursor:nwse-resize; - } - -.topMiddle:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="180"],[data-editor-rotation="0"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="90"],[data-editor-rotation="270"])) > .resizers > .resizer),.bottomMiddle:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="180"],[data-editor-rotation="0"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="90"],[data-editor-rotation="270"])) > .resizers > .resizer){ - cursor:ns-resize; - } - -.topRight:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="180"],[data-editor-rotation="0"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="90"],[data-editor-rotation="270"])) > .resizers > .resizer),.bottomLeft:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="180"],[data-editor-rotation="0"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="90"],[data-editor-rotation="270"])) > .resizers > .resizer){ - cursor:nesw-resize; - } - -.middleRight:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="180"],[data-editor-rotation="0"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="90"],[data-editor-rotation="270"])) > .resizers > .resizer),.middleLeft:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="180"],[data-editor-rotation="0"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="90"],[data-editor-rotation="270"])) > .resizers > .resizer){ - cursor:ew-resize; - } - -.topLeft:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="90"],[data-editor-rotation="270"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="180"],[data-editor-rotation="0"])) > .resizers > .resizer),.bottomRight:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="90"],[data-editor-rotation="270"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="180"],[data-editor-rotation="0"])) > .resizers > .resizer){ - cursor:nesw-resize; - } - -.topMiddle:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="90"],[data-editor-rotation="270"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="180"],[data-editor-rotation="0"])) > .resizers > .resizer),.bottomMiddle:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="90"],[data-editor-rotation="270"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="180"],[data-editor-rotation="0"])) > .resizers > .resizer){ - cursor:ew-resize; - } - -.topRight:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="90"],[data-editor-rotation="270"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="180"],[data-editor-rotation="0"])) > .resizers > .resizer),.bottomLeft:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="90"],[data-editor-rotation="270"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="180"],[data-editor-rotation="0"])) > .resizers > .resizer){ - cursor:nwse-resize; - } - -.middleRight:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="90"],[data-editor-rotation="270"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="180"],[data-editor-rotation="0"])) > .resizers > .resizer),.middleLeft:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="90"],[data-editor-rotation="270"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="180"],[data-editor-rotation="0"])) > .resizers > .resizer){ - cursor:ns-resize; - } - -:is(.annotationEditorLayer :is([data-main-rotation="0"] [data-editor-rotation="90"],[data-main-rotation="90"] [data-editor-rotation="0"],[data-main-rotation="180"] [data-editor-rotation="270"],[data-main-rotation="270"] [data-editor-rotation="180"])) .editToolbar{ - rotate:270deg; - } - -[dir="ltr"] :is(:is(.annotationEditorLayer :is([data-main-rotation="0"] [data-editor-rotation="90"],[data-main-rotation="90"] [data-editor-rotation="0"],[data-main-rotation="180"] [data-editor-rotation="270"],[data-main-rotation="270"] [data-editor-rotation="180"])) .editToolbar){ - inset-inline-end:calc(0px - var(--editor-toolbar-vert-offset)); - inset-block-start:0; - } - -[dir="rtl"] :is(:is(.annotationEditorLayer :is([data-main-rotation="0"] [data-editor-rotation="90"],[data-main-rotation="90"] [data-editor-rotation="0"],[data-main-rotation="180"] [data-editor-rotation="270"],[data-main-rotation="270"] [data-editor-rotation="180"])) .editToolbar){ - inset-inline-end:calc(100% + var(--editor-toolbar-vert-offset)); - inset-block-start:0; - } - -:is(.annotationEditorLayer :is([data-main-rotation="0"] [data-editor-rotation="180"],[data-main-rotation="90"] [data-editor-rotation="90"],[data-main-rotation="180"] [data-editor-rotation="0"],[data-main-rotation="270"] [data-editor-rotation="270"])) .editToolbar{ - rotate:180deg; - inset-inline-end:100%; - inset-block-start:calc(0pc - var(--editor-toolbar-vert-offset)); - } - -:is(.annotationEditorLayer :is([data-main-rotation="0"] [data-editor-rotation="270"],[data-main-rotation="90"] [data-editor-rotation="180"],[data-main-rotation="180"] [data-editor-rotation="90"],[data-main-rotation="270"] [data-editor-rotation="0"])) .editToolbar{ - rotate:90deg; - } - -[dir="ltr"] :is(:is(.annotationEditorLayer :is([data-main-rotation="0"] [data-editor-rotation="270"],[data-main-rotation="90"] [data-editor-rotation="180"],[data-main-rotation="180"] [data-editor-rotation="90"],[data-main-rotation="270"] [data-editor-rotation="0"])) .editToolbar){ - inset-inline-end:calc(100% + var(--editor-toolbar-vert-offset)); - inset-block-start:100%; - } - -[dir="rtl"] :is(:is(.annotationEditorLayer :is([data-main-rotation="0"] [data-editor-rotation="270"],[data-main-rotation="90"] [data-editor-rotation="180"],[data-main-rotation="180"] [data-editor-rotation="90"],[data-main-rotation="270"] [data-editor-rotation="0"])) .editToolbar){ - inset-inline-start:calc(0px - var(--editor-toolbar-vert-offset)); - inset-block-start:0; - } - -.dialog.altText::backdrop{ - -webkit-mask:url(#alttext-manager-mask); - mask:url(#alttext-manager-mask); - } - -.dialog.altText.positioned{ - margin:0; - } - -.dialog.altText #altTextContainer{ - width:300px; - height:-moz-fit-content; - height:fit-content; - display:inline-flex; - flex-direction:column; - align-items:flex-start; - gap:16px; - } - -:is(.dialog.altText #altTextContainer) #overallDescription{ - display:flex; - flex-direction:column; - align-items:flex-start; - gap:4px; - align-self:stretch; - } - -:is(:is(.dialog.altText #altTextContainer) #overallDescription) span{ - align-self:stretch; - } - -:is(:is(.dialog.altText #altTextContainer) #overallDescription) .title{ - font-size:13px; - font-style:normal; - font-weight:590; - } - -:is(.dialog.altText #altTextContainer) #addDescription{ - display:flex; - flex-direction:column; - align-items:stretch; - gap:8px; - } - -:is(:is(.dialog.altText #altTextContainer) #addDescription) .descriptionArea{ - flex:1; - padding-inline:24px 10px; - } - -:is(:is(:is(.dialog.altText #altTextContainer) #addDescription) .descriptionArea) textarea{ - width:100%; - min-height:75px; - } - -:is(.dialog.altText #altTextContainer) #buttons{ - display:flex; - justify-content:flex-end; - align-items:flex-start; - gap:8px; - align-self:stretch; - } - -.dialog.newAltText{ - --new-alt-text-ai-disclaimer-icon:url(images/altText_disclaimer.svg); - --new-alt-text-spinner-icon:url(images/altText_spinner.svg); - --preview-image-bg-color:#f0f0f4; - --preview-image-border:none; -} - -@media (prefers-color-scheme: dark){ - -.dialog.newAltText{ - --preview-image-bg-color:#2b2a33; -} - } - -@media screen and (forced-colors: active){ - -.dialog.newAltText{ - --preview-image-bg-color:ButtonFace; - --preview-image-border:1px solid ButtonText; -} - } - -.dialog.newAltText{ - - width:80%; - max-width:570px; - min-width:300px; - padding:0; -} - -.dialog.newAltText.noAi #newAltTextDisclaimer,.dialog.newAltText.noAi #newAltTextCreateAutomatically{ - display:none !important; - } - -.dialog.newAltText.aiInstalling #newAltTextCreateAutomatically{ - display:none !important; - } - -.dialog.newAltText.aiInstalling #newAltTextDownloadModel{ - display:flex !important; - } - -.dialog.newAltText.error #newAltTextNotNow{ - display:none !important; - } - -.dialog.newAltText.error #newAltTextCancel{ - display:inline-block !important; - } - -.dialog.newAltText:not(.error) #newAltTextError{ - display:none !important; - } - -.dialog.newAltText #newAltTextContainer{ - display:flex; - width:auto; - padding:16px; - flex-direction:column; - justify-content:flex-end; - align-items:flex-start; - gap:12px; - flex:0 1 auto; - line-height:normal; - } - -:is(.dialog.newAltText #newAltTextContainer) #mainContent{ - display:flex; - justify-content:flex-end; - align-items:flex-start; - gap:12px; - align-self:stretch; - flex:1 1 auto; - } - -:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionAndSettings{ - display:flex; - flex-direction:column; - align-items:flex-start; - gap:16px; - flex:1 0 0; - align-self:stretch; - } - -:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction{ - display:flex; - flex-direction:column; - align-items:flex-start; - gap:8px; - align-self:stretch; - flex:1 1 auto; - } - -:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescriptionContainer{ - width:100%; - height:70px; - position:relative; - } - -:is(:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescriptionContainer) textarea{ - width:100%; - height:100%; - padding:8px; - } - -:is(:is(:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescriptionContainer) textarea)::-moz-placeholder{ - color:var(--text-secondary-color); - } - -:is(:is(:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescriptionContainer) textarea)::placeholder{ - color:var(--text-secondary-color); - } - -:is(:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescriptionContainer) .altTextSpinner{ - display:none; - position:absolute; - width:16px; - height:16px; - inset-inline-start:8px; - inset-block-start:8px; - -webkit-mask-size:cover; - mask-size:cover; - background-color:var(--text-secondary-color); - pointer-events:none; - } - -.loading:is(:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescriptionContainer) textarea::-moz-placeholder{ - color:transparent; - } - -.loading:is(:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescriptionContainer) textarea::placeholder{ - color:transparent; - } - -.loading:is(:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescriptionContainer) .altTextSpinner{ - display:inline-block; - -webkit-mask-image:var(--new-alt-text-spinner-icon); - mask-image:var(--new-alt-text-spinner-icon); - } - -:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescription{ - font-size:11px; - } - -:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDisclaimer{ - display:flex; - flex-direction:row; - align-items:flex-start; - gap:4px; - font-size:11px; - } - -:is(:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDisclaimer)::before{ - content:""; - display:inline-block; - width:17px; - height:16px; - -webkit-mask-image:var(--new-alt-text-ai-disclaimer-icon); - mask-image:var(--new-alt-text-ai-disclaimer-icon); - -webkit-mask-size:cover; - mask-size:cover; - background-color:var(--text-secondary-color); - flex:1 0 auto; - } - -:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #newAltTextDownloadModel{ - display:flex; - align-items:center; - gap:4px; - align-self:stretch; - } - -:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #newAltTextDownloadModel)::before{ - content:""; - display:inline-block; - width:16px; - height:16px; - -webkit-mask-image:var(--new-alt-text-spinner-icon); - mask-image:var(--new-alt-text-spinner-icon); - -webkit-mask-size:cover; - mask-size:cover; - background-color:var(--text-secondary-color); - } - -:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #newAltTextImagePreview{ - width:180px; - aspect-ratio:1; - display:flex; - justify-content:center; - align-items:center; - flex:0 0 auto; - background-color:var(--preview-image-bg-color); - border:var(--preview-image-border); - } - -:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #newAltTextImagePreview) > canvas{ - max-width:100%; - max-height:100%; - } - -.colorPicker{ - --hover-outline-color:#0250bb; - --selected-outline-color:#0060df; - --swatch-border-color:#cfcfd8; -} - -@media (prefers-color-scheme: dark){ - -.colorPicker{ - --hover-outline-color:#80ebff; - --selected-outline-color:#aaf2ff; - --swatch-border-color:#52525e; -} - } - -@media screen and (forced-colors: active){ - -.colorPicker{ - --hover-outline-color:Highlight; - --selected-outline-color:var(--hover-outline-color); - --swatch-border-color:ButtonText; -} - } - -.colorPicker .swatch{ - width:16px; - height:16px; - border:1px solid var(--swatch-border-color); - border-radius:100%; - outline-offset:2px; - box-sizing:border-box; - forced-color-adjust:none; - } - -.colorPicker button:is(:hover,.selected) > .swatch{ - border:none; - } - -.annotationEditorLayer[data-main-rotation="0"] .highlightEditor:not(.free) > .editToolbar{ - rotate:0deg; - } - -.annotationEditorLayer[data-main-rotation="90"] .highlightEditor:not(.free) > .editToolbar{ - rotate:270deg; - } - -.annotationEditorLayer[data-main-rotation="180"] .highlightEditor:not(.free) > .editToolbar{ - rotate:180deg; - } - -.annotationEditorLayer[data-main-rotation="270"] .highlightEditor:not(.free) > .editToolbar{ - rotate:90deg; - } - -.annotationEditorLayer .highlightEditor{ - position:absolute; - background:transparent; - z-index:1; - cursor:auto; - max-width:100%; - max-height:100%; - border:none; - outline:none; - pointer-events:none; - transform-origin:0 0; - } - -:is(.annotationEditorLayer .highlightEditor):not(.free){ - transform:none; - } - -:is(.annotationEditorLayer .highlightEditor) .internal{ - position:absolute; - top:0; - left:0; - width:100%; - height:100%; - pointer-events:auto; - } - -.disabled:is(.annotationEditorLayer .highlightEditor) .internal{ - pointer-events:none; - } - -.selectedEditor:is(.annotationEditorLayer .highlightEditor) .internal{ - cursor:pointer; - } - -:is(.annotationEditorLayer .highlightEditor) .editToolbar{ - --editor-toolbar-colorpicker-arrow-image:url(images/toolbarButton-menuArrow.svg); - - transform-origin:center !important; - } - -:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker{ - position:relative; - width:auto; - display:flex; - justify-content:center; - align-items:center; - gap:4px; - padding:4px; - } - -:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker)::after{ - content:""; - -webkit-mask-image:var(--editor-toolbar-colorpicker-arrow-image); - mask-image:var(--editor-toolbar-colorpicker-arrow-image); - -webkit-mask-repeat:no-repeat; - mask-repeat:no-repeat; - -webkit-mask-position:center; - mask-position:center; - display:inline-block; - background-color:var(--editor-toolbar-fg-color); - width:12px; - height:12px; - } - -:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker):hover::after{ - background-color:var(--editor-toolbar-hover-fg-color); - } - -:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker):has(.dropdown:not(.hidden)){ - background-color:var(--editor-toolbar-hover-bg-color); - } - -:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker):has(.dropdown:not(.hidden))::after{ - scale:-1; - } - -:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker) .dropdown{ - position:absolute; - display:flex; - justify-content:center; - align-items:center; - flex-direction:column; - gap:11px; - padding-block:8px; - border-radius:6px; - background-color:var(--editor-toolbar-bg-color); - border:1px solid var(--editor-toolbar-border-color); - box-shadow:var(--editor-toolbar-shadow); - inset-block-start:calc(100% + 4px); - width:calc(100% + 2 * var(--editor-toolbar-padding)); - } - -:is(:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker) .dropdown) button{ - width:100%; - height:auto; - border:none; - cursor:pointer; - display:flex; - justify-content:center; - align-items:center; - background:none; - } - -:is(:is(:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker) .dropdown) button):is(:active,:focus-visible){ - outline:none; - } - -:is(:is(:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker) .dropdown) button) > .swatch{ - outline-offset:2px; - } - -[aria-selected="true"]:is(:is(:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker) .dropdown) button) > .swatch{ - outline:2px solid var(--selected-outline-color); - } - -:is(:is(:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker) .dropdown) button):is(:hover,:active,:focus-visible) > .swatch{ - outline:2px solid var(--hover-outline-color); - } - -.editorParamsToolbar:has(#highlightParamsToolbarContainer){ - padding:unset; -} - -#highlightParamsToolbarContainer{ - gap:16px; - padding-inline:10px; - padding-block-end:12px; -} - -#highlightParamsToolbarContainer .colorPicker{ - display:flex; - flex-direction:column; - gap:8px; - } - -:is(#highlightParamsToolbarContainer .colorPicker) .dropdown{ - display:flex; - justify-content:space-between; - align-items:center; - flex-direction:row; - height:auto; - } - -:is(:is(#highlightParamsToolbarContainer .colorPicker) .dropdown) button{ - width:auto; - height:auto; - border:none; - cursor:pointer; - display:flex; - justify-content:center; - align-items:center; - background:none; - flex:0 0 auto; - padding:0; - } - -:is(:is(:is(#highlightParamsToolbarContainer .colorPicker) .dropdown) button) .swatch{ - width:24px; - height:24px; - } - -:is(:is(:is(#highlightParamsToolbarContainer .colorPicker) .dropdown) button):is(:active,:focus-visible){ - outline:none; - } - -[aria-selected="true"]:is(:is(:is(#highlightParamsToolbarContainer .colorPicker) .dropdown) button) > .swatch{ - outline:2px solid var(--selected-outline-color); - } - -:is(:is(:is(#highlightParamsToolbarContainer .colorPicker) .dropdown) button):is(:hover,:active,:focus-visible) > .swatch{ - outline:2px solid var(--hover-outline-color); - } - -#highlightParamsToolbarContainer #editorHighlightThickness{ - display:flex; - flex-direction:column; - align-items:center; - gap:4px; - align-self:stretch; - } - -:is(#highlightParamsToolbarContainer #editorHighlightThickness) .editorParamsLabel{ - height:auto; - align-self:stretch; - } - -:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker{ - display:flex; - justify-content:space-between; - align-items:center; - align-self:stretch; - - --example-color:#bfbfc9; - } - -@media (prefers-color-scheme: dark){ - -:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker{ - --example-color:#80808e; - } - } - -@media screen and (forced-colors: active){ - -:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker{ - --example-color:CanvasText; - } - } - -:is(:is(:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker) > .editorParamsSlider[disabled]){ - opacity:0.4; - } - -:is(:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker)::before,:is(:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker)::after{ - content:""; - width:8px; - aspect-ratio:1; - display:block; - border-radius:100%; - background-color:var(--example-color); - } - -:is(:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker)::after{ - width:24px; - } - -:is(:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker) .editorParamsSlider{ - width:unset; - height:14px; - } - -#highlightParamsToolbarContainer #editorHighlightVisibility{ - display:flex; - flex-direction:column; - align-items:flex-start; - gap:8px; - align-self:stretch; - } - -:is(#highlightParamsToolbarContainer #editorHighlightVisibility) .divider{ - --divider-color:#d7d7db; - } - -@media (prefers-color-scheme: dark){ - -:is(#highlightParamsToolbarContainer #editorHighlightVisibility) .divider{ - --divider-color:#8f8f9d; - } - } - -@media screen and (forced-colors: active){ - -:is(#highlightParamsToolbarContainer #editorHighlightVisibility) .divider{ - --divider-color:CanvasText; - } - } - -:is(#highlightParamsToolbarContainer #editorHighlightVisibility) .divider{ - - margin-block:4px; - width:100%; - height:1px; - background-color:var(--divider-color); - } - -:is(#highlightParamsToolbarContainer #editorHighlightVisibility) .toggler{ - display:flex; - justify-content:space-between; - align-items:center; - align-self:stretch; - } - -#altTextSettingsDialog{ - padding:16px; -} - -#altTextSettingsDialog #altTextSettingsContainer{ - display:flex; - width:573px; - flex-direction:column; - gap:16px; - } - -:is(#altTextSettingsDialog #altTextSettingsContainer) .mainContainer{ - gap:16px; - } - -:is(#altTextSettingsDialog #altTextSettingsContainer) .description{ - color:var(--text-secondary-color); - } - -:is(#altTextSettingsDialog #altTextSettingsContainer) #aiModelSettings{ - display:flex; - flex-direction:column; - gap:12px; - } - -:is(:is(#altTextSettingsDialog #altTextSettingsContainer) #aiModelSettings) button{ - width:-moz-fit-content; - width:fit-content; - } - -.download:is(:is(#altTextSettingsDialog #altTextSettingsContainer) #aiModelSettings) #deleteModelButton{ - display:none; - } - -:is(:is(#altTextSettingsDialog #altTextSettingsContainer) #aiModelSettings):not(.download) #downloadModelButton{ - display:none; - } - -:is(#altTextSettingsDialog #altTextSettingsContainer) #automaticAltText,:is(#altTextSettingsDialog #altTextSettingsContainer) #altTextEditor{ - display:flex; - flex-direction:column; - gap:8px; - } - -:is(#altTextSettingsDialog #altTextSettingsContainer) #createModelDescription,:is(#altTextSettingsDialog #altTextSettingsContainer) #aiModelSettings,:is(#altTextSettingsDialog #altTextSettingsContainer) #showAltTextDialogDescription{ - padding-inline-start:40px; - } - -:is(#altTextSettingsDialog #altTextSettingsContainer) #automaticSettings{ - display:flex; - flex-direction:column; - gap:16px; - } - -:root{ - --viewer-container-height:0; - --pdfViewer-padding-bottom:0; - --page-margin:1px auto -8px; - --page-border:9px solid transparent; - --spreadHorizontalWrapped-margin-LR:-3.5px; - --loading-icon-delay:400ms; -} - -@media screen and (forced-colors: active){ - :root{ - --pdfViewer-padding-bottom:9px; - --page-margin:8px auto -1px; - --page-border:1px solid CanvasText; - --spreadHorizontalWrapped-margin-LR:3.5px; - } -} - -[data-main-rotation="90"]{ - transform:rotate(90deg) translateY(-100%); -} -[data-main-rotation="180"]{ - transform:rotate(180deg) translate(-100%, -100%); -} -[data-main-rotation="270"]{ - transform:rotate(270deg) translateX(-100%); -} - -#hiddenCopyElement, -.hiddenCanvasElement{ - position:absolute; - top:0; - left:0; - width:0; - height:0; - display:none; -} - -.pdfViewer{ - --scale-factor:1; - --page-bg-color:unset; - - padding-bottom:var(--pdfViewer-padding-bottom); - - --hcm-highlight-filter:none; - --hcm-highlight-selected-filter:none; -} - -@media screen and (forced-colors: active){ - -.pdfViewer{ - --hcm-highlight-filter:invert(100%); -} - } - -.pdfViewer.copyAll{ - cursor:wait; - } - -.pdfViewer .canvasWrapper{ - overflow:hidden; - width:100%; - height:100%; - } - -:is(.pdfViewer .canvasWrapper) canvas{ - position:absolute; - top:0; - left:0; - margin:0; - display:block; - width:100%; - height:100%; - contain:content; - } - -:is(:is(.pdfViewer .canvasWrapper) canvas) .structTree{ - contain:strict; - } - -.pdfViewer .page{ - --scale-round-x:1px; - --scale-round-y:1px; - - direction:ltr; - width:816px; - height:1056px; - margin:var(--page-margin); - position:relative; - overflow:visible; - border:var(--page-border); - background-clip:content-box; - background-color:var(--page-bg-color, rgb(255 255 255)); -} - -.pdfViewer .dummyPage{ - position:relative; - width:0; - height:var(--viewer-container-height); -} - -.pdfViewer.noUserSelect{ - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; -} - -.pdfViewer.removePageBorders .page{ - margin:0 auto 10px; - border:none; -} - -.pdfViewer.singlePageView{ - display:inline-block; -} - -.pdfViewer.singlePageView .page{ - margin:0; - border:none; -} - -.pdfViewer:is(.scrollHorizontal, .scrollWrapped), -.spread{ - margin-inline:3.5px; - text-align:center; -} - -.pdfViewer.scrollHorizontal, -.spread{ - white-space:nowrap; -} - -.pdfViewer.removePageBorders, -.pdfViewer:is(.scrollHorizontal, .scrollWrapped) .spread{ - margin-inline:0; -} - -.spread :is(.page, .dummyPage), -.pdfViewer:is(.scrollHorizontal, .scrollWrapped) :is(.page, .spread){ - display:inline-block; - vertical-align:middle; -} - -.spread .page, -.pdfViewer:is(.scrollHorizontal, .scrollWrapped) .page{ - margin-inline:var(--spreadHorizontalWrapped-margin-LR); -} - -.pdfViewer.removePageBorders .spread .page, -.pdfViewer.removePageBorders:is(.scrollHorizontal, .scrollWrapped) .page{ - margin-inline:5px; -} - -.pdfViewer .page.loadingIcon::after{ - position:absolute; - top:0; - left:0; - content:""; - width:100%; - height:100%; - background:url("images/loading-icon.gif") center no-repeat; - display:none; - transition-property:display; - transition-delay:var(--loading-icon-delay); - z-index:5; - contain:strict; -} - -.pdfViewer .page.loading::after{ - display:block; -} - -.pdfViewer .page:not(.loading)::after{ - transition-property:none; - display:none; -} - -.pdfPresentationMode .pdfViewer{ - padding-bottom:0; -} - -.pdfPresentationMode .spread{ - margin:0; -} - -.pdfPresentationMode .pdfViewer .page{ - margin:0 auto; - border:2px solid transparent; -} diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.mjs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.mjs deleted file mode 100644 index 9b2c200c99e..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.mjs +++ /dev/null @@ -1,8435 +0,0 @@ -/** - * @licstart The following is the entire license notice for the - * JavaScript code in this page - * - * Copyright 2024 Mozilla Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * @licend The above is the entire license notice for the - * JavaScript code in this page - */ - -/******/ // The require scope -/******/ var __webpack_require__ = {}; -/******/ -/************************************************************************/ -/******/ /* webpack/runtime/define property getters */ -/******/ (() => { -/******/ // define getter functions for harmony exports -/******/ __webpack_require__.d = (exports, definition) => { -/******/ for(var key in definition) { -/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { -/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); -/******/ } -/******/ } -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/hasOwnProperty shorthand */ -/******/ (() => { -/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) -/******/ })(); -/******/ -/************************************************************************/ -var __webpack_exports__ = globalThis.pdfjsViewer = {}; - -// EXPORTS -__webpack_require__.d(__webpack_exports__, { - AnnotationLayerBuilder: () => (/* reexport */ AnnotationLayerBuilder), - DownloadManager: () => (/* reexport */ DownloadManager), - EventBus: () => (/* reexport */ EventBus), - FindState: () => (/* reexport */ FindState), - GenericL10n: () => (/* reexport */ genericl10n_GenericL10n), - LinkTarget: () => (/* reexport */ LinkTarget), - PDFFindController: () => (/* reexport */ PDFFindController), - PDFHistory: () => (/* reexport */ PDFHistory), - PDFLinkService: () => (/* reexport */ PDFLinkService), - PDFPageView: () => (/* reexport */ PDFPageView), - PDFScriptingManager: () => (/* reexport */ PDFScriptingManagerComponents), - PDFSinglePageViewer: () => (/* reexport */ PDFSinglePageViewer), - PDFViewer: () => (/* reexport */ PDFViewer), - ProgressBar: () => (/* reexport */ ProgressBar), - RenderingStates: () => (/* reexport */ RenderingStates), - ScrollMode: () => (/* reexport */ ScrollMode), - SimpleLinkService: () => (/* reexport */ SimpleLinkService), - SpreadMode: () => (/* reexport */ SpreadMode), - StructTreeLayerBuilder: () => (/* reexport */ StructTreeLayerBuilder), - TextLayerBuilder: () => (/* reexport */ TextLayerBuilder), - XfaLayerBuilder: () => (/* reexport */ XfaLayerBuilder), - parseQueryString: () => (/* reexport */ parseQueryString) -}); - -;// ./web/ui_utils.js -const DEFAULT_SCALE_VALUE = "auto"; -const DEFAULT_SCALE = 1.0; -const DEFAULT_SCALE_DELTA = 1.1; -const MIN_SCALE = 0.1; -const MAX_SCALE = 10.0; -const UNKNOWN_SCALE = 0; -const MAX_AUTO_SCALE = 1.25; -const SCROLLBAR_PADDING = 40; -const VERTICAL_PADDING = 5; -const RenderingStates = { - INITIAL: 0, - RUNNING: 1, - PAUSED: 2, - FINISHED: 3 -}; -const PresentationModeState = { - UNKNOWN: 0, - NORMAL: 1, - CHANGING: 2, - FULLSCREEN: 3 -}; -const SidebarView = { - UNKNOWN: -1, - NONE: 0, - THUMBS: 1, - OUTLINE: 2, - ATTACHMENTS: 3, - LAYERS: 4 -}; -const TextLayerMode = { - DISABLE: 0, - ENABLE: 1, - ENABLE_PERMISSIONS: 2 -}; -const ScrollMode = { - UNKNOWN: -1, - VERTICAL: 0, - HORIZONTAL: 1, - WRAPPED: 2, - PAGE: 3 -}; -const SpreadMode = { - UNKNOWN: -1, - NONE: 0, - ODD: 1, - EVEN: 2 -}; -const CursorTool = { - SELECT: 0, - HAND: 1, - ZOOM: 2 -}; -const AutoPrintRegExp = /\bprint\s*\(/; -function scrollIntoView(element, spot, scrollMatches = false) { - let parent = element.offsetParent; - if (!parent) { - console.error("offsetParent is not set -- cannot scroll"); - return; - } - let offsetY = element.offsetTop + element.clientTop; - let offsetX = element.offsetLeft + element.clientLeft; - while (parent.clientHeight === parent.scrollHeight && parent.clientWidth === parent.scrollWidth || scrollMatches && (parent.classList.contains("markedContent") || getComputedStyle(parent).overflow === "hidden")) { - offsetY += parent.offsetTop; - offsetX += parent.offsetLeft; - parent = parent.offsetParent; - if (!parent) { - return; - } - } - if (spot) { - if (spot.top !== undefined) { - offsetY += spot.top; - } - if (spot.left !== undefined) { - offsetX += spot.left; - parent.scrollLeft = offsetX; - } - } - parent.scrollTop = offsetY; -} -function watchScroll(viewAreaElement, callback, abortSignal = undefined) { - const debounceScroll = function (evt) { - if (rAF) { - return; - } - rAF = window.requestAnimationFrame(function viewAreaElementScrolled() { - rAF = null; - const currentX = viewAreaElement.scrollLeft; - const lastX = state.lastX; - if (currentX !== lastX) { - state.right = currentX > lastX; - } - state.lastX = currentX; - const currentY = viewAreaElement.scrollTop; - const lastY = state.lastY; - if (currentY !== lastY) { - state.down = currentY > lastY; - } - state.lastY = currentY; - callback(state); - }); - }; - const state = { - right: true, - down: true, - lastX: viewAreaElement.scrollLeft, - lastY: viewAreaElement.scrollTop, - _eventHandler: debounceScroll - }; - let rAF = null; - viewAreaElement.addEventListener("scroll", debounceScroll, { - useCapture: true, - signal: abortSignal - }); - abortSignal?.addEventListener("abort", () => window.cancelAnimationFrame(rAF), { - once: true - }); - return state; -} -function parseQueryString(query) { - const params = new Map(); - for (const [key, value] of new URLSearchParams(query)) { - params.set(key.toLowerCase(), value); - } - return params; -} -const InvisibleCharsRegExp = /[\x00-\x1F]/g; -function removeNullCharacters(str, replaceInvisible = false) { - if (!InvisibleCharsRegExp.test(str)) { - return str; - } - if (replaceInvisible) { - return str.replaceAll(InvisibleCharsRegExp, m => m === "\x00" ? "" : " "); - } - return str.replaceAll("\x00", ""); -} -function binarySearchFirstItem(items, condition, start = 0) { - let minIndex = start; - let maxIndex = items.length - 1; - if (maxIndex < 0 || !condition(items[maxIndex])) { - return items.length; - } - if (condition(items[minIndex])) { - return minIndex; - } - while (minIndex < maxIndex) { - const currentIndex = minIndex + maxIndex >> 1; - const currentItem = items[currentIndex]; - if (condition(currentItem)) { - maxIndex = currentIndex; - } else { - minIndex = currentIndex + 1; - } - } - return minIndex; -} -function approximateFraction(x) { - if (Math.floor(x) === x) { - return [x, 1]; - } - const xinv = 1 / x; - const limit = 8; - if (xinv > limit) { - return [1, limit]; - } else if (Math.floor(xinv) === xinv) { - return [1, xinv]; - } - const x_ = x > 1 ? xinv : x; - let a = 0, - b = 1, - c = 1, - d = 1; - while (true) { - const p = a + c, - q = b + d; - if (q > limit) { - break; - } - if (x_ <= p / q) { - c = p; - d = q; - } else { - a = p; - b = q; - } - } - let result; - if (x_ - a / b < c / d - x_) { - result = x_ === x ? [a, b] : [b, a]; - } else { - result = x_ === x ? [c, d] : [d, c]; - } - return result; -} -function floorToDivide(x, div) { - return x - x % div; -} -function getPageSizeInches({ - view, - userUnit, - rotate -}) { - const [x1, y1, x2, y2] = view; - const changeOrientation = rotate % 180 !== 0; - const width = (x2 - x1) / 72 * userUnit; - const height = (y2 - y1) / 72 * userUnit; - return { - width: changeOrientation ? height : width, - height: changeOrientation ? width : height - }; -} -function backtrackBeforeAllVisibleElements(index, views, top) { - if (index < 2) { - return index; - } - let elt = views[index].div; - let pageTop = elt.offsetTop + elt.clientTop; - if (pageTop >= top) { - elt = views[index - 1].div; - pageTop = elt.offsetTop + elt.clientTop; - } - for (let i = index - 2; i >= 0; --i) { - elt = views[i].div; - if (elt.offsetTop + elt.clientTop + elt.clientHeight <= pageTop) { - break; - } - index = i; - } - return index; -} -function getVisibleElements({ - scrollEl, - views, - sortByVisibility = false, - horizontal = false, - rtl = false -}) { - const top = scrollEl.scrollTop, - bottom = top + scrollEl.clientHeight; - const left = scrollEl.scrollLeft, - right = left + scrollEl.clientWidth; - function isElementBottomAfterViewTop(view) { - const element = view.div; - const elementBottom = element.offsetTop + element.clientTop + element.clientHeight; - return elementBottom > top; - } - function isElementNextAfterViewHorizontally(view) { - const element = view.div; - const elementLeft = element.offsetLeft + element.clientLeft; - const elementRight = elementLeft + element.clientWidth; - return rtl ? elementLeft < right : elementRight > left; - } - const visible = [], - ids = new Set(), - numViews = views.length; - let firstVisibleElementInd = binarySearchFirstItem(views, horizontal ? isElementNextAfterViewHorizontally : isElementBottomAfterViewTop); - if (firstVisibleElementInd > 0 && firstVisibleElementInd < numViews && !horizontal) { - firstVisibleElementInd = backtrackBeforeAllVisibleElements(firstVisibleElementInd, views, top); - } - let lastEdge = horizontal ? right : -1; - for (let i = firstVisibleElementInd; i < numViews; i++) { - const view = views[i], - element = view.div; - const currentWidth = element.offsetLeft + element.clientLeft; - const currentHeight = element.offsetTop + element.clientTop; - const viewWidth = element.clientWidth, - viewHeight = element.clientHeight; - const viewRight = currentWidth + viewWidth; - const viewBottom = currentHeight + viewHeight; - if (lastEdge === -1) { - if (viewBottom >= bottom) { - lastEdge = viewBottom; - } - } else if ((horizontal ? currentWidth : currentHeight) > lastEdge) { - break; - } - if (viewBottom <= top || currentHeight >= bottom || viewRight <= left || currentWidth >= right) { - continue; - } - const hiddenHeight = Math.max(0, top - currentHeight) + Math.max(0, viewBottom - bottom); - const hiddenWidth = Math.max(0, left - currentWidth) + Math.max(0, viewRight - right); - const fractionHeight = (viewHeight - hiddenHeight) / viewHeight, - fractionWidth = (viewWidth - hiddenWidth) / viewWidth; - const percent = fractionHeight * fractionWidth * 100 | 0; - visible.push({ - id: view.id, - x: currentWidth, - y: currentHeight, - view, - percent, - widthPercent: fractionWidth * 100 | 0 - }); - ids.add(view.id); - } - const first = visible[0], - last = visible.at(-1); - if (sortByVisibility) { - visible.sort(function (a, b) { - const pc = a.percent - b.percent; - if (Math.abs(pc) > 0.001) { - return -pc; - } - return a.id - b.id; - }); - } - return { - first, - last, - views: visible, - ids - }; -} -function normalizeWheelEventDirection(evt) { - let delta = Math.hypot(evt.deltaX, evt.deltaY); - const angle = Math.atan2(evt.deltaY, evt.deltaX); - if (-0.25 * Math.PI < angle && angle < 0.75 * Math.PI) { - delta = -delta; - } - return delta; -} -function normalizeWheelEventDelta(evt) { - const deltaMode = evt.deltaMode; - let delta = normalizeWheelEventDirection(evt); - const MOUSE_PIXELS_PER_LINE = 30; - const MOUSE_LINES_PER_PAGE = 30; - if (deltaMode === WheelEvent.DOM_DELTA_PIXEL) { - delta /= MOUSE_PIXELS_PER_LINE * MOUSE_LINES_PER_PAGE; - } else if (deltaMode === WheelEvent.DOM_DELTA_LINE) { - delta /= MOUSE_LINES_PER_PAGE; - } - return delta; -} -function isValidRotation(angle) { - return Number.isInteger(angle) && angle % 90 === 0; -} -function isValidScrollMode(mode) { - return Number.isInteger(mode) && Object.values(ScrollMode).includes(mode) && mode !== ScrollMode.UNKNOWN; -} -function isValidSpreadMode(mode) { - return Number.isInteger(mode) && Object.values(SpreadMode).includes(mode) && mode !== SpreadMode.UNKNOWN; -} -function isPortraitOrientation(size) { - return size.width <= size.height; -} -const animationStarted = new Promise(function (resolve) { - window.requestAnimationFrame(resolve); -}); -const docStyle = document.documentElement.style; -function clamp(v, min, max) { - return Math.min(Math.max(v, min), max); -} -class ProgressBar { - #classList = null; - #disableAutoFetchTimeout = null; - #percent = 0; - #style = null; - #visible = true; - constructor(bar) { - this.#classList = bar.classList; - this.#style = bar.style; - } - get percent() { - return this.#percent; - } - set percent(val) { - this.#percent = clamp(val, 0, 100); - if (isNaN(val)) { - this.#classList.add("indeterminate"); - return; - } - this.#classList.remove("indeterminate"); - this.#style.setProperty("--progressBar-percent", `${this.#percent}%`); - } - setWidth(viewer) { - if (!viewer) { - return; - } - const container = viewer.parentNode; - const scrollbarWidth = container.offsetWidth - viewer.offsetWidth; - if (scrollbarWidth > 0) { - this.#style.setProperty("--progressBar-end-offset", `${scrollbarWidth}px`); - } - } - setDisableAutoFetch(delay = 5000) { - if (this.#percent === 100 || isNaN(this.#percent)) { - return; - } - if (this.#disableAutoFetchTimeout) { - clearTimeout(this.#disableAutoFetchTimeout); - } - this.show(); - this.#disableAutoFetchTimeout = setTimeout(() => { - this.#disableAutoFetchTimeout = null; - this.hide(); - }, delay); - } - hide() { - if (!this.#visible) { - return; - } - this.#visible = false; - this.#classList.add("hidden"); - } - show() { - if (this.#visible) { - return; - } - this.#visible = true; - this.#classList.remove("hidden"); - } -} -function getActiveOrFocusedElement() { - let curRoot = document; - let curActiveOrFocused = curRoot.activeElement || curRoot.querySelector(":focus"); - while (curActiveOrFocused?.shadowRoot) { - curRoot = curActiveOrFocused.shadowRoot; - curActiveOrFocused = curRoot.activeElement || curRoot.querySelector(":focus"); - } - return curActiveOrFocused; -} -function apiPageLayoutToViewerModes(layout) { - let scrollMode = ScrollMode.VERTICAL, - spreadMode = SpreadMode.NONE; - switch (layout) { - case "SinglePage": - scrollMode = ScrollMode.PAGE; - break; - case "OneColumn": - break; - case "TwoPageLeft": - scrollMode = ScrollMode.PAGE; - case "TwoColumnLeft": - spreadMode = SpreadMode.ODD; - break; - case "TwoPageRight": - scrollMode = ScrollMode.PAGE; - case "TwoColumnRight": - spreadMode = SpreadMode.EVEN; - break; - } - return { - scrollMode, - spreadMode - }; -} -function apiPageModeToSidebarView(mode) { - switch (mode) { - case "UseNone": - return SidebarView.NONE; - case "UseThumbs": - return SidebarView.THUMBS; - case "UseOutlines": - return SidebarView.OUTLINE; - case "UseAttachments": - return SidebarView.ATTACHMENTS; - case "UseOC": - return SidebarView.LAYERS; - } - return SidebarView.NONE; -} -function toggleCheckedBtn(button, toggle, view = null) { - button.classList.toggle("toggled", toggle); - button.setAttribute("aria-checked", toggle); - view?.classList.toggle("hidden", !toggle); -} -function toggleExpandedBtn(button, toggle, view = null) { - button.classList.toggle("toggled", toggle); - button.setAttribute("aria-expanded", toggle); - view?.classList.toggle("hidden", !toggle); -} -const calcRound = function () { - const e = document.createElement("div"); - e.style.width = "round(down, calc(1.6666666666666665 * 792px), 1px)"; - return e.style.width === "calc(1320px)" ? Math.fround : x => x; -}(); - -;// ./web/pdf_find_utils.js -const CharacterType = { - SPACE: 0, - ALPHA_LETTER: 1, - PUNCT: 2, - HAN_LETTER: 3, - KATAKANA_LETTER: 4, - HIRAGANA_LETTER: 5, - HALFWIDTH_KATAKANA_LETTER: 6, - THAI_LETTER: 7 -}; -function isAlphabeticalScript(charCode) { - return charCode < 0x2e80; -} -function isAscii(charCode) { - return (charCode & 0xff80) === 0; -} -function isAsciiAlpha(charCode) { - return charCode >= 0x61 && charCode <= 0x7a || charCode >= 0x41 && charCode <= 0x5a; -} -function isAsciiDigit(charCode) { - return charCode >= 0x30 && charCode <= 0x39; -} -function isAsciiSpace(charCode) { - return charCode === 0x20 || charCode === 0x09 || charCode === 0x0d || charCode === 0x0a; -} -function isHan(charCode) { - return charCode >= 0x3400 && charCode <= 0x9fff || charCode >= 0xf900 && charCode <= 0xfaff; -} -function isKatakana(charCode) { - return charCode >= 0x30a0 && charCode <= 0x30ff; -} -function isHiragana(charCode) { - return charCode >= 0x3040 && charCode <= 0x309f; -} -function isHalfwidthKatakana(charCode) { - return charCode >= 0xff60 && charCode <= 0xff9f; -} -function isThai(charCode) { - return (charCode & 0xff80) === 0x0e00; -} -function getCharacterType(charCode) { - if (isAlphabeticalScript(charCode)) { - if (isAscii(charCode)) { - if (isAsciiSpace(charCode)) { - return CharacterType.SPACE; - } else if (isAsciiAlpha(charCode) || isAsciiDigit(charCode) || charCode === 0x5f) { - return CharacterType.ALPHA_LETTER; - } - return CharacterType.PUNCT; - } else if (isThai(charCode)) { - return CharacterType.THAI_LETTER; - } else if (charCode === 0xa0) { - return CharacterType.SPACE; - } - return CharacterType.ALPHA_LETTER; - } - if (isHan(charCode)) { - return CharacterType.HAN_LETTER; - } else if (isKatakana(charCode)) { - return CharacterType.KATAKANA_LETTER; - } else if (isHiragana(charCode)) { - return CharacterType.HIRAGANA_LETTER; - } else if (isHalfwidthKatakana(charCode)) { - return CharacterType.HALFWIDTH_KATAKANA_LETTER; - } - return CharacterType.ALPHA_LETTER; -} -let NormalizeWithNFKC; -function getNormalizeWithNFKC() { - NormalizeWithNFKC ||= ` ¨ª¯²-µ¸-º¼-¾IJ-ijĿ-ŀʼnſDŽ-njDZ-dzʰ-ʸ˘-˝ˠ-ˤʹͺ;΄-΅·ϐ-ϖϰ-ϲϴ-ϵϹևٵ-ٸक़-य़ড়-ঢ়য়ਲ਼ਸ਼ਖ਼-ਜ਼ਫ਼ଡ଼-ଢ଼ำຳໜ-ໝ༌གྷཌྷདྷབྷཛྷཀྵჼᴬ-ᴮᴰ-ᴺᴼ-ᵍᵏ-ᵪᵸᶛ-ᶿẚ-ẛάέήίόύώΆ᾽-῁ΈΉ῍-῏ΐΊ῝-῟ΰΎ῭-`ΌΏ´-῾ - ‑‗․-… ″-‴‶-‷‼‾⁇-⁉⁗ ⁰-ⁱ⁴-₎ₐ-ₜ₨℀-℃℅-ℇ℉-ℓℕ-№ℙ-ℝ℠-™ℤΩℨK-ℭℯ-ℱℳ-ℹ℻-⅀ⅅ-ⅉ⅐-ⅿ↉∬-∭∯-∰〈-〉①-⓪⨌⩴-⩶⫝̸ⱼ-ⱽⵯ⺟⻳⼀-⿕ 〶〸-〺゛-゜ゟヿㄱ-ㆎ㆒-㆟㈀-㈞㈠-㉇㉐-㉾㊀-㏿ꚜ-ꚝꝰꟲ-ꟴꟸ-ꟹꭜ-ꭟꭩ豈-嗀塚晴凞-羽蘒諸逸-都飯-舘並-龎ff-stﬓ-ﬗיִײַ-זּטּ-לּמּנּ-סּףּ-פּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-﷼︐-︙︰-﹄﹇-﹒﹔-﹦﹨-﹫ﹰ-ﹲﹴﹶ-ﻼ!-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ¢-₩`; - return NormalizeWithNFKC; -} - -;// ./web/pdf_find_controller.js - - -const FindState = { - FOUND: 0, - NOT_FOUND: 1, - WRAPPED: 2, - PENDING: 3 -}; -const FIND_TIMEOUT = 250; -const MATCH_SCROLL_OFFSET_TOP = -50; -const MATCH_SCROLL_OFFSET_LEFT = -400; -const CHARACTERS_TO_NORMALIZE = { - "\u2010": "-", - "\u2018": "'", - "\u2019": "'", - "\u201A": "'", - "\u201B": "'", - "\u201C": '"', - "\u201D": '"', - "\u201E": '"', - "\u201F": '"', - "\u00BC": "1/4", - "\u00BD": "1/2", - "\u00BE": "3/4" -}; -const DIACRITICS_EXCEPTION = new Set([0x3099, 0x309a, 0x094d, 0x09cd, 0x0a4d, 0x0acd, 0x0b4d, 0x0bcd, 0x0c4d, 0x0ccd, 0x0d3b, 0x0d3c, 0x0d4d, 0x0dca, 0x0e3a, 0x0eba, 0x0f84, 0x1039, 0x103a, 0x1714, 0x1734, 0x17d2, 0x1a60, 0x1b44, 0x1baa, 0x1bab, 0x1bf2, 0x1bf3, 0x2d7f, 0xa806, 0xa82c, 0xa8c4, 0xa953, 0xa9c0, 0xaaf6, 0xabed, 0x0c56, 0x0f71, 0x0f72, 0x0f7a, 0x0f7b, 0x0f7c, 0x0f7d, 0x0f80, 0x0f74]); -let DIACRITICS_EXCEPTION_STR; -const DIACRITICS_REG_EXP = /\p{M}+/gu; -const SPECIAL_CHARS_REG_EXP = /([.*+?^${}()|[\]\\])|(\p{P})|(\s+)|(\p{M})|(\p{L})/gu; -const NOT_DIACRITIC_FROM_END_REG_EXP = /([^\p{M}])\p{M}*$/u; -const NOT_DIACRITIC_FROM_START_REG_EXP = /^\p{M}*([^\p{M}])/u; -const SYLLABLES_REG_EXP = /[\uAC00-\uD7AF\uFA6C\uFACF-\uFAD1\uFAD5-\uFAD7]+/g; -const SYLLABLES_LENGTHS = new Map(); -const FIRST_CHAR_SYLLABLES_REG_EXP = "[\\u1100-\\u1112\\ud7a4-\\ud7af\\ud84a\\ud84c\\ud850\\ud854\\ud857\\ud85f]"; -const NFKC_CHARS_TO_NORMALIZE = new Map(); -let noSyllablesRegExp = null; -let withSyllablesRegExp = null; -function normalize(text) { - const syllablePositions = []; - let m; - while ((m = SYLLABLES_REG_EXP.exec(text)) !== null) { - let { - index - } = m; - for (const char of m[0]) { - let len = SYLLABLES_LENGTHS.get(char); - if (!len) { - len = char.normalize("NFD").length; - SYLLABLES_LENGTHS.set(char, len); - } - syllablePositions.push([len, index++]); - } - } - let normalizationRegex; - if (syllablePositions.length === 0 && noSyllablesRegExp) { - normalizationRegex = noSyllablesRegExp; - } else if (syllablePositions.length > 0 && withSyllablesRegExp) { - normalizationRegex = withSyllablesRegExp; - } else { - const replace = Object.keys(CHARACTERS_TO_NORMALIZE).join(""); - const toNormalizeWithNFKC = getNormalizeWithNFKC(); - const CJK = "(?:\\p{Ideographic}|[\u3040-\u30FF])"; - const HKDiacritics = "(?:\u3099|\u309A)"; - const CompoundWord = "\\p{Ll}-\\n\\p{Lu}"; - const regexp = `([${replace}])|([${toNormalizeWithNFKC}])|(${HKDiacritics}\\n)|(\\p{M}+(?:-\\n)?)|(${CompoundWord})|(\\S-\\n)|(${CJK}\\n)|(\\n)`; - if (syllablePositions.length === 0) { - normalizationRegex = noSyllablesRegExp = new RegExp(regexp + "|(\\u0000)", "gum"); - } else { - normalizationRegex = withSyllablesRegExp = new RegExp(regexp + `|(${FIRST_CHAR_SYLLABLES_REG_EXP})`, "gum"); - } - } - const rawDiacriticsPositions = []; - while ((m = DIACRITICS_REG_EXP.exec(text)) !== null) { - rawDiacriticsPositions.push([m[0].length, m.index]); - } - let normalized = text.normalize("NFD"); - const positions = [0, 0]; - let rawDiacriticsIndex = 0; - let syllableIndex = 0; - let shift = 0; - let shiftOrigin = 0; - let eol = 0; - let hasDiacritics = false; - normalized = normalized.replace(normalizationRegex, (match, p1, p2, p3, p4, p5, p6, p7, p8, p9, i) => { - i -= shiftOrigin; - if (p1) { - const replacement = CHARACTERS_TO_NORMALIZE[p1]; - const jj = replacement.length; - for (let j = 1; j < jj; j++) { - positions.push(i - shift + j, shift - j); - } - shift -= jj - 1; - return replacement; - } - if (p2) { - let replacement = NFKC_CHARS_TO_NORMALIZE.get(p2); - if (!replacement) { - replacement = p2.normalize("NFKC"); - NFKC_CHARS_TO_NORMALIZE.set(p2, replacement); - } - const jj = replacement.length; - for (let j = 1; j < jj; j++) { - positions.push(i - shift + j, shift - j); - } - shift -= jj - 1; - return replacement; - } - if (p3) { - hasDiacritics = true; - if (i + eol === rawDiacriticsPositions[rawDiacriticsIndex]?.[1]) { - ++rawDiacriticsIndex; - } else { - positions.push(i - 1 - shift + 1, shift - 1); - shift -= 1; - shiftOrigin += 1; - } - positions.push(i - shift + 1, shift); - shiftOrigin += 1; - eol += 1; - return p3.charAt(0); - } - if (p4) { - const hasTrailingDashEOL = p4.endsWith("\n"); - const len = hasTrailingDashEOL ? p4.length - 2 : p4.length; - hasDiacritics = true; - let jj = len; - if (i + eol === rawDiacriticsPositions[rawDiacriticsIndex]?.[1]) { - jj -= rawDiacriticsPositions[rawDiacriticsIndex][0]; - ++rawDiacriticsIndex; - } - for (let j = 1; j <= jj; j++) { - positions.push(i - 1 - shift + j, shift - j); - } - shift -= jj; - shiftOrigin += jj; - if (hasTrailingDashEOL) { - i += len - 1; - positions.push(i - shift + 1, 1 + shift); - shift += 1; - shiftOrigin += 1; - eol += 1; - return p4.slice(0, len); - } - return p4; - } - if (p5) { - shiftOrigin += 1; - eol += 1; - return p5.replace("\n", ""); - } - if (p6) { - const len = p6.length - 2; - positions.push(i - shift + len, 1 + shift); - shift += 1; - shiftOrigin += 1; - eol += 1; - return p6.slice(0, -2); - } - if (p7) { - const len = p7.length - 1; - positions.push(i - shift + len, shift); - shiftOrigin += 1; - eol += 1; - return p7.slice(0, -1); - } - if (p8) { - positions.push(i - shift + 1, shift - 1); - shift -= 1; - shiftOrigin += 1; - eol += 1; - return " "; - } - if (i + eol === syllablePositions[syllableIndex]?.[1]) { - const newCharLen = syllablePositions[syllableIndex][0] - 1; - ++syllableIndex; - for (let j = 1; j <= newCharLen; j++) { - positions.push(i - (shift - j), shift - j); - } - shift -= newCharLen; - shiftOrigin += newCharLen; - } - return p9; - }); - positions.push(normalized.length, shift); - const starts = new Uint32Array(positions.length >> 1); - const shifts = new Int32Array(positions.length >> 1); - for (let i = 0, ii = positions.length; i < ii; i += 2) { - starts[i >> 1] = positions[i]; - shifts[i >> 1] = positions[i + 1]; - } - return [normalized, [starts, shifts], hasDiacritics]; -} -function getOriginalIndex(diffs, pos, len) { - if (!diffs) { - return [pos, len]; - } - const [starts, shifts] = diffs; - const start = pos; - const end = pos + len - 1; - let i = binarySearchFirstItem(starts, x => x >= start); - if (starts[i] > start) { - --i; - } - let j = binarySearchFirstItem(starts, x => x >= end, i); - if (starts[j] > end) { - --j; - } - const oldStart = start + shifts[i]; - const oldEnd = end + shifts[j]; - const oldLen = oldEnd + 1 - oldStart; - return [oldStart, oldLen]; -} -class PDFFindController { - #state = null; - #updateMatchesCountOnProgress = true; - #visitedPagesCount = 0; - constructor({ - linkService, - eventBus, - updateMatchesCountOnProgress = true - }) { - this._linkService = linkService; - this._eventBus = eventBus; - this.#updateMatchesCountOnProgress = updateMatchesCountOnProgress; - this.onIsPageVisible = null; - this.#reset(); - eventBus._on("find", this.#onFind.bind(this)); - eventBus._on("findbarclose", this.#onFindBarClose.bind(this)); - } - get highlightMatches() { - return this._highlightMatches; - } - get pageMatches() { - return this._pageMatches; - } - get pageMatchesLength() { - return this._pageMatchesLength; - } - get selected() { - return this._selected; - } - get state() { - return this.#state; - } - setDocument(pdfDocument) { - if (this._pdfDocument) { - this.#reset(); - } - if (!pdfDocument) { - return; - } - this._pdfDocument = pdfDocument; - this._firstPageCapability.resolve(); - } - #onFind(state) { - if (!state) { - return; - } - const pdfDocument = this._pdfDocument; - const { - type - } = state; - if (this.#state === null || this.#shouldDirtyMatch(state)) { - this._dirtyMatch = true; - } - this.#state = state; - if (type !== "highlightallchange") { - this.#updateUIState(FindState.PENDING); - } - this._firstPageCapability.promise.then(() => { - if (!this._pdfDocument || pdfDocument && this._pdfDocument !== pdfDocument) { - return; - } - this.#extractText(); - const findbarClosed = !this._highlightMatches; - const pendingTimeout = !!this._findTimeout; - if (this._findTimeout) { - clearTimeout(this._findTimeout); - this._findTimeout = null; - } - if (!type) { - this._findTimeout = setTimeout(() => { - this.#nextMatch(); - this._findTimeout = null; - }, FIND_TIMEOUT); - } else if (this._dirtyMatch) { - this.#nextMatch(); - } else if (type === "again") { - this.#nextMatch(); - if (findbarClosed && this.#state.highlightAll) { - this.#updateAllPages(); - } - } else if (type === "highlightallchange") { - if (pendingTimeout) { - this.#nextMatch(); - } else { - this._highlightMatches = true; - } - this.#updateAllPages(); - } else { - this.#nextMatch(); - } - }); - } - scrollMatchIntoView({ - element = null, - selectedLeft = 0, - pageIndex = -1, - matchIndex = -1 - }) { - if (!this._scrollMatches || !element) { - return; - } else if (matchIndex === -1 || matchIndex !== this._selected.matchIdx) { - return; - } else if (pageIndex === -1 || pageIndex !== this._selected.pageIdx) { - return; - } - this._scrollMatches = false; - const spot = { - top: MATCH_SCROLL_OFFSET_TOP, - left: selectedLeft + MATCH_SCROLL_OFFSET_LEFT - }; - scrollIntoView(element, spot, true); - } - #reset() { - this._highlightMatches = false; - this._scrollMatches = false; - this._pdfDocument = null; - this._pageMatches = []; - this._pageMatchesLength = []; - this.#visitedPagesCount = 0; - this.#state = null; - this._selected = { - pageIdx: -1, - matchIdx: -1 - }; - this._offset = { - pageIdx: null, - matchIdx: null, - wrapped: false - }; - this._extractTextPromises = []; - this._pageContents = []; - this._pageDiffs = []; - this._hasDiacritics = []; - this._matchesCountTotal = 0; - this._pagesToSearch = null; - this._pendingFindMatches = new Set(); - this._resumePageIdx = null; - this._dirtyMatch = false; - clearTimeout(this._findTimeout); - this._findTimeout = null; - this._firstPageCapability = Promise.withResolvers(); - } - get #query() { - const { - query - } = this.#state; - if (typeof query === "string") { - if (query !== this._rawQuery) { - this._rawQuery = query; - [this._normalizedQuery] = normalize(query); - } - return this._normalizedQuery; - } - return (query || []).filter(q => !!q).map(q => normalize(q)[0]); - } - #shouldDirtyMatch(state) { - const newQuery = state.query, - prevQuery = this.#state.query; - const newType = typeof newQuery, - prevType = typeof prevQuery; - if (newType !== prevType) { - return true; - } - if (newType === "string") { - if (newQuery !== prevQuery) { - return true; - } - } else if (JSON.stringify(newQuery) !== JSON.stringify(prevQuery)) { - return true; - } - switch (state.type) { - case "again": - const pageNumber = this._selected.pageIdx + 1; - const linkService = this._linkService; - return pageNumber >= 1 && pageNumber <= linkService.pagesCount && pageNumber !== linkService.page && !(this.onIsPageVisible?.(pageNumber) ?? true); - case "highlightallchange": - return false; - } - return true; - } - #isEntireWord(content, startIdx, length) { - let match = content.slice(0, startIdx).match(NOT_DIACRITIC_FROM_END_REG_EXP); - if (match) { - const first = content.charCodeAt(startIdx); - const limit = match[1].charCodeAt(0); - if (getCharacterType(first) === getCharacterType(limit)) { - return false; - } - } - match = content.slice(startIdx + length).match(NOT_DIACRITIC_FROM_START_REG_EXP); - if (match) { - const last = content.charCodeAt(startIdx + length - 1); - const limit = match[1].charCodeAt(0); - if (getCharacterType(last) === getCharacterType(limit)) { - return false; - } - } - return true; - } - #convertToRegExpString(query, hasDiacritics) { - const { - matchDiacritics - } = this.#state; - let isUnicode = false; - query = query.replaceAll(SPECIAL_CHARS_REG_EXP, (match, p1, p2, p3, p4, p5) => { - if (p1) { - return `[ ]*\\${p1}[ ]*`; - } - if (p2) { - return `[ ]*${p2}[ ]*`; - } - if (p3) { - return "[ ]+"; - } - if (matchDiacritics) { - return p4 || p5; - } - if (p4) { - return DIACRITICS_EXCEPTION.has(p4.charCodeAt(0)) ? p4 : ""; - } - if (hasDiacritics) { - isUnicode = true; - return `${p5}\\p{M}*`; - } - return p5; - }); - const trailingSpaces = "[ ]*"; - if (query.endsWith(trailingSpaces)) { - query = query.slice(0, query.length - trailingSpaces.length); - } - if (matchDiacritics) { - if (hasDiacritics) { - DIACRITICS_EXCEPTION_STR ||= String.fromCharCode(...DIACRITICS_EXCEPTION); - isUnicode = true; - query = `${query}(?=[${DIACRITICS_EXCEPTION_STR}]|[^\\p{M}]|$)`; - } - } - return [isUnicode, query]; - } - #calculateMatch(pageIndex) { - const query = this.#query; - if (query.length === 0) { - return; - } - const pageContent = this._pageContents[pageIndex]; - const matcherResult = this.match(query, pageContent, pageIndex); - const matches = this._pageMatches[pageIndex] = []; - const matchesLength = this._pageMatchesLength[pageIndex] = []; - const diffs = this._pageDiffs[pageIndex]; - matcherResult?.forEach(({ - index, - length - }) => { - const [matchPos, matchLen] = getOriginalIndex(diffs, index, length); - if (matchLen) { - matches.push(matchPos); - matchesLength.push(matchLen); - } - }); - if (this.#state.highlightAll) { - this.#updatePage(pageIndex); - } - if (this._resumePageIdx === pageIndex) { - this._resumePageIdx = null; - this.#nextPageMatch(); - } - const pageMatchesCount = matches.length; - this._matchesCountTotal += pageMatchesCount; - if (this.#updateMatchesCountOnProgress) { - if (pageMatchesCount > 0) { - this.#updateUIResultsCount(); - } - } else if (++this.#visitedPagesCount === this._linkService.pagesCount) { - this.#updateUIResultsCount(); - } - } - match(query, pageContent, pageIndex) { - const hasDiacritics = this._hasDiacritics[pageIndex]; - let isUnicode = false; - if (typeof query === "string") { - [isUnicode, query] = this.#convertToRegExpString(query, hasDiacritics); - } else { - query = query.sort().reverse().map(q => { - const [isUnicodePart, queryPart] = this.#convertToRegExpString(q, hasDiacritics); - isUnicode ||= isUnicodePart; - return `(${queryPart})`; - }).join("|"); - } - if (!query) { - return undefined; - } - const { - caseSensitive, - entireWord - } = this.#state; - const flags = `g${isUnicode ? "u" : ""}${caseSensitive ? "" : "i"}`; - query = new RegExp(query, flags); - const matches = []; - let match; - while ((match = query.exec(pageContent)) !== null) { - if (entireWord && !this.#isEntireWord(pageContent, match.index, match[0].length)) { - continue; - } - matches.push({ - index: match.index, - length: match[0].length - }); - } - return matches; - } - #extractText() { - if (this._extractTextPromises.length > 0) { - return; - } - let deferred = Promise.resolve(); - const textOptions = { - disableNormalization: true - }; - for (let i = 0, ii = this._linkService.pagesCount; i < ii; i++) { - const { - promise, - resolve - } = Promise.withResolvers(); - this._extractTextPromises[i] = promise; - deferred = deferred.then(() => { - return this._pdfDocument.getPage(i + 1).then(pdfPage => pdfPage.getTextContent(textOptions)).then(textContent => { - const strBuf = []; - for (const textItem of textContent.items) { - strBuf.push(textItem.str); - if (textItem.hasEOL) { - strBuf.push("\n"); - } - } - [this._pageContents[i], this._pageDiffs[i], this._hasDiacritics[i]] = normalize(strBuf.join("")); - resolve(); - }, reason => { - console.error(`Unable to get text content for page ${i + 1}`, reason); - this._pageContents[i] = ""; - this._pageDiffs[i] = null; - this._hasDiacritics[i] = false; - resolve(); - }); - }); - } - } - #updatePage(index) { - if (this._scrollMatches && this._selected.pageIdx === index) { - this._linkService.page = index + 1; - } - this._eventBus.dispatch("updatetextlayermatches", { - source: this, - pageIndex: index - }); - } - #updateAllPages() { - this._eventBus.dispatch("updatetextlayermatches", { - source: this, - pageIndex: -1 - }); - } - #nextMatch() { - const previous = this.#state.findPrevious; - const currentPageIndex = this._linkService.page - 1; - const numPages = this._linkService.pagesCount; - this._highlightMatches = true; - if (this._dirtyMatch) { - this._dirtyMatch = false; - this._selected.pageIdx = this._selected.matchIdx = -1; - this._offset.pageIdx = currentPageIndex; - this._offset.matchIdx = null; - this._offset.wrapped = false; - this._resumePageIdx = null; - this._pageMatches.length = 0; - this._pageMatchesLength.length = 0; - this.#visitedPagesCount = 0; - this._matchesCountTotal = 0; - this.#updateAllPages(); - for (let i = 0; i < numPages; i++) { - if (this._pendingFindMatches.has(i)) { - continue; - } - this._pendingFindMatches.add(i); - this._extractTextPromises[i].then(() => { - this._pendingFindMatches.delete(i); - this.#calculateMatch(i); - }); - } - } - const query = this.#query; - if (query.length === 0) { - this.#updateUIState(FindState.FOUND); - return; - } - if (this._resumePageIdx) { - return; - } - const offset = this._offset; - this._pagesToSearch = numPages; - if (offset.matchIdx !== null) { - const numPageMatches = this._pageMatches[offset.pageIdx].length; - if (!previous && offset.matchIdx + 1 < numPageMatches || previous && offset.matchIdx > 0) { - offset.matchIdx = previous ? offset.matchIdx - 1 : offset.matchIdx + 1; - this.#updateMatch(true); - return; - } - this.#advanceOffsetPage(previous); - } - this.#nextPageMatch(); - } - #matchesReady(matches) { - const offset = this._offset; - const numMatches = matches.length; - const previous = this.#state.findPrevious; - if (numMatches) { - offset.matchIdx = previous ? numMatches - 1 : 0; - this.#updateMatch(true); - return true; - } - this.#advanceOffsetPage(previous); - if (offset.wrapped) { - offset.matchIdx = null; - if (this._pagesToSearch < 0) { - this.#updateMatch(false); - return true; - } - } - return false; - } - #nextPageMatch() { - if (this._resumePageIdx !== null) { - console.error("There can only be one pending page."); - } - let matches = null; - do { - const pageIdx = this._offset.pageIdx; - matches = this._pageMatches[pageIdx]; - if (!matches) { - this._resumePageIdx = pageIdx; - break; - } - } while (!this.#matchesReady(matches)); - } - #advanceOffsetPage(previous) { - const offset = this._offset; - const numPages = this._linkService.pagesCount; - offset.pageIdx = previous ? offset.pageIdx - 1 : offset.pageIdx + 1; - offset.matchIdx = null; - this._pagesToSearch--; - if (offset.pageIdx >= numPages || offset.pageIdx < 0) { - offset.pageIdx = previous ? numPages - 1 : 0; - offset.wrapped = true; - } - } - #updateMatch(found = false) { - let state = FindState.NOT_FOUND; - const wrapped = this._offset.wrapped; - this._offset.wrapped = false; - if (found) { - const previousPage = this._selected.pageIdx; - this._selected.pageIdx = this._offset.pageIdx; - this._selected.matchIdx = this._offset.matchIdx; - state = wrapped ? FindState.WRAPPED : FindState.FOUND; - if (previousPage !== -1 && previousPage !== this._selected.pageIdx) { - this.#updatePage(previousPage); - } - } - this.#updateUIState(state, this.#state.findPrevious); - if (this._selected.pageIdx !== -1) { - this._scrollMatches = true; - this.#updatePage(this._selected.pageIdx); - } - } - #onFindBarClose(evt) { - const pdfDocument = this._pdfDocument; - this._firstPageCapability.promise.then(() => { - if (!this._pdfDocument || pdfDocument && this._pdfDocument !== pdfDocument) { - return; - } - if (this._findTimeout) { - clearTimeout(this._findTimeout); - this._findTimeout = null; - } - if (this._resumePageIdx) { - this._resumePageIdx = null; - this._dirtyMatch = true; - } - this.#updateUIState(FindState.FOUND); - this._highlightMatches = false; - this.#updateAllPages(); - }); - } - #requestMatchesCount() { - const { - pageIdx, - matchIdx - } = this._selected; - let current = 0, - total = this._matchesCountTotal; - if (matchIdx !== -1) { - for (let i = 0; i < pageIdx; i++) { - current += this._pageMatches[i]?.length || 0; - } - current += matchIdx + 1; - } - if (current < 1 || current > total) { - current = total = 0; - } - return { - current, - total - }; - } - #updateUIResultsCount() { - this._eventBus.dispatch("updatefindmatchescount", { - source: this, - matchesCount: this.#requestMatchesCount() - }); - } - #updateUIState(state, previous = false) { - if (!this.#updateMatchesCountOnProgress && (this.#visitedPagesCount !== this._linkService.pagesCount || state === FindState.PENDING)) { - return; - } - this._eventBus.dispatch("updatefindcontrolstate", { - source: this, - state, - previous, - entireWord: this.#state?.entireWord ?? null, - matchesCount: this.#requestMatchesCount(), - rawQuery: this.#state?.query ?? null - }); - } -} - -;// ./web/pdf_link_service.js - -const DEFAULT_LINK_REL = "noopener noreferrer nofollow"; -const LinkTarget = { - NONE: 0, - SELF: 1, - BLANK: 2, - PARENT: 3, - TOP: 4 -}; -class PDFLinkService { - externalLinkEnabled = true; - constructor({ - eventBus, - externalLinkTarget = null, - externalLinkRel = null, - ignoreDestinationZoom = false - } = {}) { - this.eventBus = eventBus; - this.externalLinkTarget = externalLinkTarget; - this.externalLinkRel = externalLinkRel; - this._ignoreDestinationZoom = ignoreDestinationZoom; - this.baseUrl = null; - this.pdfDocument = null; - this.pdfViewer = null; - this.pdfHistory = null; - } - setDocument(pdfDocument, baseUrl = null) { - this.baseUrl = baseUrl; - this.pdfDocument = pdfDocument; - } - setViewer(pdfViewer) { - this.pdfViewer = pdfViewer; - } - setHistory(pdfHistory) { - this.pdfHistory = pdfHistory; - } - get pagesCount() { - return this.pdfDocument ? this.pdfDocument.numPages : 0; - } - get page() { - return this.pdfDocument ? this.pdfViewer.currentPageNumber : 1; - } - set page(value) { - if (this.pdfDocument) { - this.pdfViewer.currentPageNumber = value; - } - } - get rotation() { - return this.pdfDocument ? this.pdfViewer.pagesRotation : 0; - } - set rotation(value) { - if (this.pdfDocument) { - this.pdfViewer.pagesRotation = value; - } - } - get isInPresentationMode() { - return this.pdfDocument ? this.pdfViewer.isInPresentationMode : false; - } - async goToDestination(dest) { - if (!this.pdfDocument) { - return; - } - let namedDest, explicitDest, pageNumber; - if (typeof dest === "string") { - namedDest = dest; - explicitDest = await this.pdfDocument.getDestination(dest); - } else { - namedDest = null; - explicitDest = await dest; - } - if (!Array.isArray(explicitDest)) { - console.error(`goToDestination: "${explicitDest}" is not a valid destination array, for dest="${dest}".`); - return; - } - const [destRef] = explicitDest; - if (destRef && typeof destRef === "object") { - pageNumber = this.pdfDocument.cachedPageNumber(destRef); - if (!pageNumber) { - try { - pageNumber = (await this.pdfDocument.getPageIndex(destRef)) + 1; - } catch { - console.error(`goToDestination: "${destRef}" is not a valid page reference, for dest="${dest}".`); - return; - } - } - } else if (Number.isInteger(destRef)) { - pageNumber = destRef + 1; - } - if (!pageNumber || pageNumber < 1 || pageNumber > this.pagesCount) { - console.error(`goToDestination: "${pageNumber}" is not a valid page number, for dest="${dest}".`); - return; - } - if (this.pdfHistory) { - this.pdfHistory.pushCurrentPosition(); - this.pdfHistory.push({ - namedDest, - explicitDest, - pageNumber - }); - } - this.pdfViewer.scrollPageIntoView({ - pageNumber, - destArray: explicitDest, - ignoreDestinationZoom: this._ignoreDestinationZoom - }); - } - goToPage(val) { - if (!this.pdfDocument) { - return; - } - const pageNumber = typeof val === "string" && this.pdfViewer.pageLabelToPageNumber(val) || val | 0; - if (!(Number.isInteger(pageNumber) && pageNumber > 0 && pageNumber <= this.pagesCount)) { - console.error(`PDFLinkService.goToPage: "${val}" is not a valid page.`); - return; - } - if (this.pdfHistory) { - this.pdfHistory.pushCurrentPosition(); - this.pdfHistory.pushPage(pageNumber); - } - this.pdfViewer.scrollPageIntoView({ - pageNumber - }); - } - addLinkAttributes(link, url, newWindow = false) { - if (!url || typeof url !== "string") { - throw new Error('A valid "url" parameter must provided.'); - } - const target = newWindow ? LinkTarget.BLANK : this.externalLinkTarget, - rel = this.externalLinkRel; - if (this.externalLinkEnabled) { - link.href = link.title = url; - } else { - link.href = ""; - link.title = `Disabled: ${url}`; - link.onclick = () => false; - } - let targetStr = ""; - switch (target) { - case LinkTarget.NONE: - break; - case LinkTarget.SELF: - targetStr = "_self"; - break; - case LinkTarget.BLANK: - targetStr = "_blank"; - break; - case LinkTarget.PARENT: - targetStr = "_parent"; - break; - case LinkTarget.TOP: - targetStr = "_top"; - break; - } - link.target = targetStr; - link.rel = typeof rel === "string" ? rel : DEFAULT_LINK_REL; - } - getDestinationHash(dest) { - if (typeof dest === "string") { - if (dest.length > 0) { - return this.getAnchorUrl("#" + escape(dest)); - } - } else if (Array.isArray(dest)) { - const str = JSON.stringify(dest); - if (str.length > 0) { - return this.getAnchorUrl("#" + escape(str)); - } - } - return this.getAnchorUrl(""); - } - getAnchorUrl(anchor) { - return this.baseUrl ? this.baseUrl + anchor : anchor; - } - setHash(hash) { - if (!this.pdfDocument) { - return; - } - let pageNumber, dest; - if (hash.includes("=")) { - const params = parseQueryString(hash); - if (params.has("search")) { - const query = params.get("search").replaceAll('"', ""), - phrase = params.get("phrase") === "true"; - this.eventBus.dispatch("findfromurlhash", { - source: this, - query: phrase ? query : query.match(/\S+/g) - }); - } - if (params.has("page")) { - pageNumber = params.get("page") | 0 || 1; - } - if (params.has("zoom")) { - const zoomArgs = params.get("zoom").split(","); - const zoomArg = zoomArgs[0]; - const zoomArgNumber = parseFloat(zoomArg); - if (!zoomArg.includes("Fit")) { - dest = [null, { - name: "XYZ" - }, zoomArgs.length > 1 ? zoomArgs[1] | 0 : null, zoomArgs.length > 2 ? zoomArgs[2] | 0 : null, zoomArgNumber ? zoomArgNumber / 100 : zoomArg]; - } else if (zoomArg === "Fit" || zoomArg === "FitB") { - dest = [null, { - name: zoomArg - }]; - } else if (zoomArg === "FitH" || zoomArg === "FitBH" || zoomArg === "FitV" || zoomArg === "FitBV") { - dest = [null, { - name: zoomArg - }, zoomArgs.length > 1 ? zoomArgs[1] | 0 : null]; - } else if (zoomArg === "FitR") { - if (zoomArgs.length !== 5) { - console.error('PDFLinkService.setHash: Not enough parameters for "FitR".'); - } else { - dest = [null, { - name: zoomArg - }, zoomArgs[1] | 0, zoomArgs[2] | 0, zoomArgs[3] | 0, zoomArgs[4] | 0]; - } - } else { - console.error(`PDFLinkService.setHash: "${zoomArg}" is not a valid zoom value.`); - } - } - if (dest) { - this.pdfViewer.scrollPageIntoView({ - pageNumber: pageNumber || this.page, - destArray: dest, - allowNegativeOffset: true - }); - } else if (pageNumber) { - this.page = pageNumber; - } - if (params.has("pagemode")) { - this.eventBus.dispatch("pagemode", { - source: this, - mode: params.get("pagemode") - }); - } - if (params.has("nameddest")) { - this.goToDestination(params.get("nameddest")); - } - return; - } - dest = unescape(hash); - try { - dest = JSON.parse(dest); - if (!Array.isArray(dest)) { - dest = dest.toString(); - } - } catch {} - if (typeof dest === "string" || PDFLinkService.#isValidExplicitDest(dest)) { - this.goToDestination(dest); - return; - } - console.error(`PDFLinkService.setHash: "${unescape(hash)}" is not a valid destination.`); - } - executeNamedAction(action) { - if (!this.pdfDocument) { - return; - } - switch (action) { - case "GoBack": - this.pdfHistory?.back(); - break; - case "GoForward": - this.pdfHistory?.forward(); - break; - case "NextPage": - this.pdfViewer.nextPage(); - break; - case "PrevPage": - this.pdfViewer.previousPage(); - break; - case "LastPage": - this.page = this.pagesCount; - break; - case "FirstPage": - this.page = 1; - break; - default: - break; - } - this.eventBus.dispatch("namedaction", { - source: this, - action - }); - } - async executeSetOCGState(action) { - if (!this.pdfDocument) { - return; - } - const pdfDocument = this.pdfDocument, - optionalContentConfig = await this.pdfViewer.optionalContentConfigPromise; - if (pdfDocument !== this.pdfDocument) { - return; - } - optionalContentConfig.setOCGState(action); - this.pdfViewer.optionalContentConfigPromise = Promise.resolve(optionalContentConfig); - } - static #isValidExplicitDest(dest) { - if (!Array.isArray(dest) || dest.length < 2) { - return false; - } - const [page, zoom, ...args] = dest; - if (!(typeof page === "object" && Number.isInteger(page?.num) && Number.isInteger(page?.gen)) && !Number.isInteger(page)) { - return false; - } - if (!(typeof zoom === "object" && typeof zoom?.name === "string")) { - return false; - } - const argsLen = args.length; - let allowNull = true; - switch (zoom.name) { - case "XYZ": - if (argsLen < 2 || argsLen > 3) { - return false; - } - break; - case "Fit": - case "FitB": - return argsLen === 0; - case "FitH": - case "FitBH": - case "FitV": - case "FitBV": - if (argsLen > 1) { - return false; - } - break; - case "FitR": - if (argsLen !== 4) { - return false; - } - allowNull = false; - break; - default: - return false; - } - for (const arg of args) { - if (!(typeof arg === "number" || allowNull && arg === null)) { - return false; - } - } - return true; - } -} -class SimpleLinkService extends PDFLinkService { - setDocument(pdfDocument, baseUrl = null) {} -} - -;// ./web/pdfjs.js -const { - AbortException, - AnnotationEditorLayer, - AnnotationEditorParamsType, - AnnotationEditorType, - AnnotationEditorUIManager, - AnnotationLayer, - AnnotationMode, - build, - ColorPicker, - createValidAbsoluteUrl, - DOMSVGFactory, - DrawLayer, - FeatureTest, - fetchData, - getDocument, - getFilenameFromUrl, - getPdfFilenameFromUrl, - getXfaPageViewport, - GlobalWorkerOptions, - ImageKind, - InvalidPDFException, - isDataScheme, - isPdfFile, - MissingPDFException, - noContextMenu, - normalizeUnicode, - OPS, - OutputScale, - PasswordResponses, - PDFDataRangeTransport, - PDFDateString, - PDFWorker, - PermissionFlag, - PixelsPerInch, - RenderingCancelledException, - setLayerDimensions, - shadow, - stopEvent, - TextLayer, - TouchManager, - UnexpectedResponseException, - Util, - VerbosityLevel, - version, - XfaLayer -} = globalThis.pdfjsLib; - -;// ./web/annotation_layer_builder.js - - -class AnnotationLayerBuilder { - #onAppend = null; - #eventAbortController = null; - constructor({ - pdfPage, - linkService, - downloadManager, - annotationStorage = null, - imageResourcesPath = "", - renderForms = true, - enableScripting = false, - hasJSActionsPromise = null, - fieldObjectsPromise = null, - annotationCanvasMap = null, - accessibilityManager = null, - annotationEditorUIManager = null, - onAppend = null - }) { - this.pdfPage = pdfPage; - this.linkService = linkService; - this.downloadManager = downloadManager; - this.imageResourcesPath = imageResourcesPath; - this.renderForms = renderForms; - this.annotationStorage = annotationStorage; - this.enableScripting = enableScripting; - this._hasJSActionsPromise = hasJSActionsPromise || Promise.resolve(false); - this._fieldObjectsPromise = fieldObjectsPromise || Promise.resolve(null); - this._annotationCanvasMap = annotationCanvasMap; - this._accessibilityManager = accessibilityManager; - this._annotationEditorUIManager = annotationEditorUIManager; - this.#onAppend = onAppend; - this.annotationLayer = null; - this.div = null; - this._cancelled = false; - this._eventBus = linkService.eventBus; - } - async render(viewport, options, intent = "display") { - if (this.div) { - if (this._cancelled || !this.annotationLayer) { - return; - } - this.annotationLayer.update({ - viewport: viewport.clone({ - dontFlip: true - }) - }); - return; - } - const [annotations, hasJSActions, fieldObjects] = await Promise.all([this.pdfPage.getAnnotations({ - intent - }), this._hasJSActionsPromise, this._fieldObjectsPromise]); - if (this._cancelled) { - return; - } - const div = this.div = document.createElement("div"); - div.className = "annotationLayer"; - this.#onAppend?.(div); - if (annotations.length === 0) { - this.hide(); - return; - } - this.annotationLayer = new AnnotationLayer({ - div, - accessibilityManager: this._accessibilityManager, - annotationCanvasMap: this._annotationCanvasMap, - annotationEditorUIManager: this._annotationEditorUIManager, - page: this.pdfPage, - viewport: viewport.clone({ - dontFlip: true - }), - structTreeLayer: options?.structTreeLayer || null - }); - await this.annotationLayer.render({ - annotations, - imageResourcesPath: this.imageResourcesPath, - renderForms: this.renderForms, - linkService: this.linkService, - downloadManager: this.downloadManager, - annotationStorage: this.annotationStorage, - enableScripting: this.enableScripting, - hasJSActions, - fieldObjects - }); - if (this.linkService.isInPresentationMode) { - this.#updatePresentationModeState(PresentationModeState.FULLSCREEN); - } - if (!this.#eventAbortController) { - this.#eventAbortController = new AbortController(); - this._eventBus?._on("presentationmodechanged", evt => { - this.#updatePresentationModeState(evt.state); - }, { - signal: this.#eventAbortController.signal - }); - } - } - cancel() { - this._cancelled = true; - this.#eventAbortController?.abort(); - this.#eventAbortController = null; - } - hide() { - if (!this.div) { - return; - } - this.div.hidden = true; - } - hasEditableAnnotations() { - return !!this.annotationLayer?.hasEditableAnnotations(); - } - #updatePresentationModeState(state) { - if (!this.div) { - return; - } - let disableFormElements = false; - switch (state) { - case PresentationModeState.FULLSCREEN: - disableFormElements = true; - break; - case PresentationModeState.NORMAL: - break; - default: - return; - } - for (const section of this.div.childNodes) { - if (section.hasAttribute("data-internal-link")) { - continue; - } - section.inert = disableFormElements; - } - } -} - -;// ./web/download_manager.js - -function download(blobUrl, filename) { - const a = document.createElement("a"); - if (!a.click) { - throw new Error('DownloadManager: "a.click()" is not supported.'); - } - a.href = blobUrl; - a.target = "_parent"; - if ("download" in a) { - a.download = filename; - } - (document.body || document.documentElement).append(a); - a.click(); - a.remove(); -} -class DownloadManager { - #openBlobUrls = new WeakMap(); - downloadData(data, filename, contentType) { - const blobUrl = URL.createObjectURL(new Blob([data], { - type: contentType - })); - download(blobUrl, filename); - } - openOrDownloadData(data, filename, dest = null) { - const isPdfData = isPdfFile(filename); - const contentType = isPdfData ? "application/pdf" : ""; - this.downloadData(data, filename, contentType); - return false; - } - download(data, url, filename) { - let blobUrl; - if (data) { - blobUrl = URL.createObjectURL(new Blob([data], { - type: "application/pdf" - })); - } else { - if (!createValidAbsoluteUrl(url, "http://example.com")) { - console.error(`download - not a valid URL: ${url}`); - return; - } - blobUrl = url + "#pdfjs.action=download"; - } - download(blobUrl, filename); - } -} - -;// ./web/event_utils.js -const WaitOnType = { - EVENT: "event", - TIMEOUT: "timeout" -}; -async function waitOnEventOrTimeout({ - target, - name, - delay = 0 -}) { - if (typeof target !== "object" || !(name && typeof name === "string") || !(Number.isInteger(delay) && delay >= 0)) { - throw new Error("waitOnEventOrTimeout - invalid parameters."); - } - const { - promise, - resolve - } = Promise.withResolvers(); - const ac = new AbortController(); - function handler(type) { - ac.abort(); - clearTimeout(timeout); - resolve(type); - } - const evtMethod = target instanceof EventBus ? "_on" : "addEventListener"; - target[evtMethod](name, handler.bind(null, WaitOnType.EVENT), { - signal: ac.signal - }); - const timeout = setTimeout(handler.bind(null, WaitOnType.TIMEOUT), delay); - return promise; -} -class EventBus { - #listeners = Object.create(null); - on(eventName, listener, options = null) { - this._on(eventName, listener, { - external: true, - once: options?.once, - signal: options?.signal - }); - } - off(eventName, listener, options = null) { - this._off(eventName, listener); - } - dispatch(eventName, data) { - const eventListeners = this.#listeners[eventName]; - if (!eventListeners || eventListeners.length === 0) { - return; - } - let externalListeners; - for (const { - listener, - external, - once - } of eventListeners.slice(0)) { - if (once) { - this._off(eventName, listener); - } - if (external) { - (externalListeners ||= []).push(listener); - continue; - } - listener(data); - } - if (externalListeners) { - for (const listener of externalListeners) { - listener(data); - } - externalListeners = null; - } - } - _on(eventName, listener, options = null) { - let rmAbort = null; - if (options?.signal instanceof AbortSignal) { - const { - signal - } = options; - if (signal.aborted) { - console.error("Cannot use an `aborted` signal."); - return; - } - const onAbort = () => this._off(eventName, listener); - rmAbort = () => signal.removeEventListener("abort", onAbort); - signal.addEventListener("abort", onAbort); - } - const eventListeners = this.#listeners[eventName] ||= []; - eventListeners.push({ - listener, - external: options?.external === true, - once: options?.once === true, - rmAbort - }); - } - _off(eventName, listener, options = null) { - const eventListeners = this.#listeners[eventName]; - if (!eventListeners) { - return; - } - for (let i = 0, ii = eventListeners.length; i < ii; i++) { - const evt = eventListeners[i]; - if (evt.listener === listener) { - evt.rmAbort?.(); - eventListeners.splice(i, 1); - return; - } - } - } -} -class FirefoxEventBus extends EventBus { - #externalServices; - #globalEventNames; - #isInAutomation; - constructor(globalEventNames, externalServices, isInAutomation) { - super(); - this.#globalEventNames = globalEventNames; - this.#externalServices = externalServices; - this.#isInAutomation = isInAutomation; - } - dispatch(eventName, data) { - throw new Error("Not implemented: FirefoxEventBus.dispatch"); - } -} - -;// ./node_modules/@fluent/bundle/esm/types.js -class FluentType { - constructor(value) { - this.value = value; - } - valueOf() { - return this.value; - } -} -class FluentNone extends FluentType { - constructor(value = "???") { - super(value); - } - toString(scope) { - return `{${this.value}}`; - } -} -class FluentNumber extends FluentType { - constructor(value, opts = {}) { - super(value); - this.opts = opts; - } - toString(scope) { - try { - const nf = scope.memoizeIntlObject(Intl.NumberFormat, this.opts); - return nf.format(this.value); - } catch (err) { - scope.reportError(err); - return this.value.toString(10); - } - } -} -class FluentDateTime extends FluentType { - constructor(value, opts = {}) { - super(value); - this.opts = opts; - } - toString(scope) { - try { - const dtf = scope.memoizeIntlObject(Intl.DateTimeFormat, this.opts); - return dtf.format(this.value); - } catch (err) { - scope.reportError(err); - return new Date(this.value).toISOString(); - } - } -} -;// ./node_modules/@fluent/bundle/esm/resolver.js - -const MAX_PLACEABLES = 100; -const FSI = "\u2068"; -const PDI = "\u2069"; -function match(scope, selector, key) { - if (key === selector) { - return true; - } - if (key instanceof FluentNumber && selector instanceof FluentNumber && key.value === selector.value) { - return true; - } - if (selector instanceof FluentNumber && typeof key === "string") { - let category = scope.memoizeIntlObject(Intl.PluralRules, selector.opts).select(selector.value); - if (key === category) { - return true; - } - } - return false; -} -function getDefault(scope, variants, star) { - if (variants[star]) { - return resolvePattern(scope, variants[star].value); - } - scope.reportError(new RangeError("No default")); - return new FluentNone(); -} -function getArguments(scope, args) { - const positional = []; - const named = Object.create(null); - for (const arg of args) { - if (arg.type === "narg") { - named[arg.name] = resolveExpression(scope, arg.value); - } else { - positional.push(resolveExpression(scope, arg)); - } - } - return { - positional, - named - }; -} -function resolveExpression(scope, expr) { - switch (expr.type) { - case "str": - return expr.value; - case "num": - return new FluentNumber(expr.value, { - minimumFractionDigits: expr.precision - }); - case "var": - return resolveVariableReference(scope, expr); - case "mesg": - return resolveMessageReference(scope, expr); - case "term": - return resolveTermReference(scope, expr); - case "func": - return resolveFunctionReference(scope, expr); - case "select": - return resolveSelectExpression(scope, expr); - default: - return new FluentNone(); - } -} -function resolveVariableReference(scope, { - name -}) { - let arg; - if (scope.params) { - if (Object.prototype.hasOwnProperty.call(scope.params, name)) { - arg = scope.params[name]; - } else { - return new FluentNone(`$${name}`); - } - } else if (scope.args && Object.prototype.hasOwnProperty.call(scope.args, name)) { - arg = scope.args[name]; - } else { - scope.reportError(new ReferenceError(`Unknown variable: $${name}`)); - return new FluentNone(`$${name}`); - } - if (arg instanceof FluentType) { - return arg; - } - switch (typeof arg) { - case "string": - return arg; - case "number": - return new FluentNumber(arg); - case "object": - if (arg instanceof Date) { - return new FluentDateTime(arg.getTime()); - } - default: - scope.reportError(new TypeError(`Variable type not supported: $${name}, ${typeof arg}`)); - return new FluentNone(`$${name}`); - } -} -function resolveMessageReference(scope, { - name, - attr -}) { - const message = scope.bundle._messages.get(name); - if (!message) { - scope.reportError(new ReferenceError(`Unknown message: ${name}`)); - return new FluentNone(name); - } - if (attr) { - const attribute = message.attributes[attr]; - if (attribute) { - return resolvePattern(scope, attribute); - } - scope.reportError(new ReferenceError(`Unknown attribute: ${attr}`)); - return new FluentNone(`${name}.${attr}`); - } - if (message.value) { - return resolvePattern(scope, message.value); - } - scope.reportError(new ReferenceError(`No value: ${name}`)); - return new FluentNone(name); -} -function resolveTermReference(scope, { - name, - attr, - args -}) { - const id = `-${name}`; - const term = scope.bundle._terms.get(id); - if (!term) { - scope.reportError(new ReferenceError(`Unknown term: ${id}`)); - return new FluentNone(id); - } - if (attr) { - const attribute = term.attributes[attr]; - if (attribute) { - scope.params = getArguments(scope, args).named; - const resolved = resolvePattern(scope, attribute); - scope.params = null; - return resolved; - } - scope.reportError(new ReferenceError(`Unknown attribute: ${attr}`)); - return new FluentNone(`${id}.${attr}`); - } - scope.params = getArguments(scope, args).named; - const resolved = resolvePattern(scope, term.value); - scope.params = null; - return resolved; -} -function resolveFunctionReference(scope, { - name, - args -}) { - let func = scope.bundle._functions[name]; - if (!func) { - scope.reportError(new ReferenceError(`Unknown function: ${name}()`)); - return new FluentNone(`${name}()`); - } - if (typeof func !== "function") { - scope.reportError(new TypeError(`Function ${name}() is not callable`)); - return new FluentNone(`${name}()`); - } - try { - let resolved = getArguments(scope, args); - return func(resolved.positional, resolved.named); - } catch (err) { - scope.reportError(err); - return new FluentNone(`${name}()`); - } -} -function resolveSelectExpression(scope, { - selector, - variants, - star -}) { - let sel = resolveExpression(scope, selector); - if (sel instanceof FluentNone) { - return getDefault(scope, variants, star); - } - for (const variant of variants) { - const key = resolveExpression(scope, variant.key); - if (match(scope, sel, key)) { - return resolvePattern(scope, variant.value); - } - } - return getDefault(scope, variants, star); -} -function resolveComplexPattern(scope, ptn) { - if (scope.dirty.has(ptn)) { - scope.reportError(new RangeError("Cyclic reference")); - return new FluentNone(); - } - scope.dirty.add(ptn); - const result = []; - const useIsolating = scope.bundle._useIsolating && ptn.length > 1; - for (const elem of ptn) { - if (typeof elem === "string") { - result.push(scope.bundle._transform(elem)); - continue; - } - scope.placeables++; - if (scope.placeables > MAX_PLACEABLES) { - scope.dirty.delete(ptn); - throw new RangeError(`Too many placeables expanded: ${scope.placeables}, ` + `max allowed is ${MAX_PLACEABLES}`); - } - if (useIsolating) { - result.push(FSI); - } - result.push(resolveExpression(scope, elem).toString(scope)); - if (useIsolating) { - result.push(PDI); - } - } - scope.dirty.delete(ptn); - return result.join(""); -} -function resolvePattern(scope, value) { - if (typeof value === "string") { - return scope.bundle._transform(value); - } - return resolveComplexPattern(scope, value); -} -;// ./node_modules/@fluent/bundle/esm/scope.js -class Scope { - constructor(bundle, errors, args) { - this.dirty = new WeakSet(); - this.params = null; - this.placeables = 0; - this.bundle = bundle; - this.errors = errors; - this.args = args; - } - reportError(error) { - if (!this.errors || !(error instanceof Error)) { - throw error; - } - this.errors.push(error); - } - memoizeIntlObject(ctor, opts) { - let cache = this.bundle._intls.get(ctor); - if (!cache) { - cache = {}; - this.bundle._intls.set(ctor, cache); - } - let id = JSON.stringify(opts); - if (!cache[id]) { - cache[id] = new ctor(this.bundle.locales, opts); - } - return cache[id]; - } -} -;// ./node_modules/@fluent/bundle/esm/builtins.js - -function values(opts, allowed) { - const unwrapped = Object.create(null); - for (const [name, opt] of Object.entries(opts)) { - if (allowed.includes(name)) { - unwrapped[name] = opt.valueOf(); - } - } - return unwrapped; -} -const NUMBER_ALLOWED = ["unitDisplay", "currencyDisplay", "useGrouping", "minimumIntegerDigits", "minimumFractionDigits", "maximumFractionDigits", "minimumSignificantDigits", "maximumSignificantDigits"]; -function NUMBER(args, opts) { - let arg = args[0]; - if (arg instanceof FluentNone) { - return new FluentNone(`NUMBER(${arg.valueOf()})`); - } - if (arg instanceof FluentNumber) { - return new FluentNumber(arg.valueOf(), { - ...arg.opts, - ...values(opts, NUMBER_ALLOWED) - }); - } - if (arg instanceof FluentDateTime) { - return new FluentNumber(arg.valueOf(), { - ...values(opts, NUMBER_ALLOWED) - }); - } - throw new TypeError("Invalid argument to NUMBER"); -} -const DATETIME_ALLOWED = ["dateStyle", "timeStyle", "fractionalSecondDigits", "dayPeriod", "hour12", "weekday", "era", "year", "month", "day", "hour", "minute", "second", "timeZoneName"]; -function DATETIME(args, opts) { - let arg = args[0]; - if (arg instanceof FluentNone) { - return new FluentNone(`DATETIME(${arg.valueOf()})`); - } - if (arg instanceof FluentDateTime) { - return new FluentDateTime(arg.valueOf(), { - ...arg.opts, - ...values(opts, DATETIME_ALLOWED) - }); - } - if (arg instanceof FluentNumber) { - return new FluentDateTime(arg.valueOf(), { - ...values(opts, DATETIME_ALLOWED) - }); - } - throw new TypeError("Invalid argument to DATETIME"); -} -;// ./node_modules/@fluent/bundle/esm/memoizer.js -const cache = new Map(); -function getMemoizerForLocale(locales) { - const stringLocale = Array.isArray(locales) ? locales.join(" ") : locales; - let memoizer = cache.get(stringLocale); - if (memoizer === undefined) { - memoizer = new Map(); - cache.set(stringLocale, memoizer); - } - return memoizer; -} -;// ./node_modules/@fluent/bundle/esm/bundle.js - - - - - -class FluentBundle { - constructor(locales, { - functions, - useIsolating = true, - transform = v => v - } = {}) { - this._terms = new Map(); - this._messages = new Map(); - this.locales = Array.isArray(locales) ? locales : [locales]; - this._functions = { - NUMBER: NUMBER, - DATETIME: DATETIME, - ...functions - }; - this._useIsolating = useIsolating; - this._transform = transform; - this._intls = getMemoizerForLocale(locales); - } - hasMessage(id) { - return this._messages.has(id); - } - getMessage(id) { - return this._messages.get(id); - } - addResource(res, { - allowOverrides = false - } = {}) { - const errors = []; - for (let i = 0; i < res.body.length; i++) { - let entry = res.body[i]; - if (entry.id.startsWith("-")) { - if (allowOverrides === false && this._terms.has(entry.id)) { - errors.push(new Error(`Attempt to override an existing term: "${entry.id}"`)); - continue; - } - this._terms.set(entry.id, entry); - } else { - if (allowOverrides === false && this._messages.has(entry.id)) { - errors.push(new Error(`Attempt to override an existing message: "${entry.id}"`)); - continue; - } - this._messages.set(entry.id, entry); - } - } - return errors; - } - formatPattern(pattern, args = null, errors = null) { - if (typeof pattern === "string") { - return this._transform(pattern); - } - let scope = new Scope(this, errors, args); - try { - let value = resolveComplexPattern(scope, pattern); - return value.toString(scope); - } catch (err) { - if (scope.errors && err instanceof Error) { - scope.errors.push(err); - return new FluentNone().toString(scope); - } - throw err; - } - } -} -;// ./node_modules/@fluent/bundle/esm/resource.js -const RE_MESSAGE_START = /^(-?[a-zA-Z][\w-]*) *= */gm; -const RE_ATTRIBUTE_START = /\.([a-zA-Z][\w-]*) *= */y; -const RE_VARIANT_START = /\*?\[/y; -const RE_NUMBER_LITERAL = /(-?[0-9]+(?:\.([0-9]+))?)/y; -const RE_IDENTIFIER = /([a-zA-Z][\w-]*)/y; -const RE_REFERENCE = /([$-])?([a-zA-Z][\w-]*)(?:\.([a-zA-Z][\w-]*))?/y; -const RE_FUNCTION_NAME = /^[A-Z][A-Z0-9_-]*$/; -const RE_TEXT_RUN = /([^{}\n\r]+)/y; -const RE_STRING_RUN = /([^\\"\n\r]*)/y; -const RE_STRING_ESCAPE = /\\([\\"])/y; -const RE_UNICODE_ESCAPE = /\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{6})/y; -const RE_LEADING_NEWLINES = /^\n+/; -const RE_TRAILING_SPACES = / +$/; -const RE_BLANK_LINES = / *\r?\n/g; -const RE_INDENT = /( *)$/; -const TOKEN_BRACE_OPEN = /{\s*/y; -const TOKEN_BRACE_CLOSE = /\s*}/y; -const TOKEN_BRACKET_OPEN = /\[\s*/y; -const TOKEN_BRACKET_CLOSE = /\s*] */y; -const TOKEN_PAREN_OPEN = /\s*\(\s*/y; -const TOKEN_ARROW = /\s*->\s*/y; -const TOKEN_COLON = /\s*:\s*/y; -const TOKEN_COMMA = /\s*,?\s*/y; -const TOKEN_BLANK = /\s+/y; -class FluentResource { - constructor(source) { - this.body = []; - RE_MESSAGE_START.lastIndex = 0; - let cursor = 0; - while (true) { - let next = RE_MESSAGE_START.exec(source); - if (next === null) { - break; - } - cursor = RE_MESSAGE_START.lastIndex; - try { - this.body.push(parseMessage(next[1])); - } catch (err) { - if (err instanceof SyntaxError) { - continue; - } - throw err; - } - } - function test(re) { - re.lastIndex = cursor; - return re.test(source); - } - function consumeChar(char, errorClass) { - if (source[cursor] === char) { - cursor++; - return true; - } - if (errorClass) { - throw new errorClass(`Expected ${char}`); - } - return false; - } - function consumeToken(re, errorClass) { - if (test(re)) { - cursor = re.lastIndex; - return true; - } - if (errorClass) { - throw new errorClass(`Expected ${re.toString()}`); - } - return false; - } - function match(re) { - re.lastIndex = cursor; - let result = re.exec(source); - if (result === null) { - throw new SyntaxError(`Expected ${re.toString()}`); - } - cursor = re.lastIndex; - return result; - } - function match1(re) { - return match(re)[1]; - } - function parseMessage(id) { - let value = parsePattern(); - let attributes = parseAttributes(); - if (value === null && Object.keys(attributes).length === 0) { - throw new SyntaxError("Expected message value or attributes"); - } - return { - id, - value, - attributes - }; - } - function parseAttributes() { - let attrs = Object.create(null); - while (test(RE_ATTRIBUTE_START)) { - let name = match1(RE_ATTRIBUTE_START); - let value = parsePattern(); - if (value === null) { - throw new SyntaxError("Expected attribute value"); - } - attrs[name] = value; - } - return attrs; - } - function parsePattern() { - let first; - if (test(RE_TEXT_RUN)) { - first = match1(RE_TEXT_RUN); - } - if (source[cursor] === "{" || source[cursor] === "}") { - return parsePatternElements(first ? [first] : [], Infinity); - } - let indent = parseIndent(); - if (indent) { - if (first) { - return parsePatternElements([first, indent], indent.length); - } - indent.value = trim(indent.value, RE_LEADING_NEWLINES); - return parsePatternElements([indent], indent.length); - } - if (first) { - return trim(first, RE_TRAILING_SPACES); - } - return null; - } - function parsePatternElements(elements = [], commonIndent) { - while (true) { - if (test(RE_TEXT_RUN)) { - elements.push(match1(RE_TEXT_RUN)); - continue; - } - if (source[cursor] === "{") { - elements.push(parsePlaceable()); - continue; - } - if (source[cursor] === "}") { - throw new SyntaxError("Unbalanced closing brace"); - } - let indent = parseIndent(); - if (indent) { - elements.push(indent); - commonIndent = Math.min(commonIndent, indent.length); - continue; - } - break; - } - let lastIndex = elements.length - 1; - let lastElement = elements[lastIndex]; - if (typeof lastElement === "string") { - elements[lastIndex] = trim(lastElement, RE_TRAILING_SPACES); - } - let baked = []; - for (let element of elements) { - if (element instanceof Indent) { - element = element.value.slice(0, element.value.length - commonIndent); - } - if (element) { - baked.push(element); - } - } - return baked; - } - function parsePlaceable() { - consumeToken(TOKEN_BRACE_OPEN, SyntaxError); - let selector = parseInlineExpression(); - if (consumeToken(TOKEN_BRACE_CLOSE)) { - return selector; - } - if (consumeToken(TOKEN_ARROW)) { - let variants = parseVariants(); - consumeToken(TOKEN_BRACE_CLOSE, SyntaxError); - return { - type: "select", - selector, - ...variants - }; - } - throw new SyntaxError("Unclosed placeable"); - } - function parseInlineExpression() { - if (source[cursor] === "{") { - return parsePlaceable(); - } - if (test(RE_REFERENCE)) { - let [, sigil, name, attr = null] = match(RE_REFERENCE); - if (sigil === "$") { - return { - type: "var", - name - }; - } - if (consumeToken(TOKEN_PAREN_OPEN)) { - let args = parseArguments(); - if (sigil === "-") { - return { - type: "term", - name, - attr, - args - }; - } - if (RE_FUNCTION_NAME.test(name)) { - return { - type: "func", - name, - args - }; - } - throw new SyntaxError("Function names must be all upper-case"); - } - if (sigil === "-") { - return { - type: "term", - name, - attr, - args: [] - }; - } - return { - type: "mesg", - name, - attr - }; - } - return parseLiteral(); - } - function parseArguments() { - let args = []; - while (true) { - switch (source[cursor]) { - case ")": - cursor++; - return args; - case undefined: - throw new SyntaxError("Unclosed argument list"); - } - args.push(parseArgument()); - consumeToken(TOKEN_COMMA); - } - } - function parseArgument() { - let expr = parseInlineExpression(); - if (expr.type !== "mesg") { - return expr; - } - if (consumeToken(TOKEN_COLON)) { - return { - type: "narg", - name: expr.name, - value: parseLiteral() - }; - } - return expr; - } - function parseVariants() { - let variants = []; - let count = 0; - let star; - while (test(RE_VARIANT_START)) { - if (consumeChar("*")) { - star = count; - } - let key = parseVariantKey(); - let value = parsePattern(); - if (value === null) { - throw new SyntaxError("Expected variant value"); - } - variants[count++] = { - key, - value - }; - } - if (count === 0) { - return null; - } - if (star === undefined) { - throw new SyntaxError("Expected default variant"); - } - return { - variants, - star - }; - } - function parseVariantKey() { - consumeToken(TOKEN_BRACKET_OPEN, SyntaxError); - let key; - if (test(RE_NUMBER_LITERAL)) { - key = parseNumberLiteral(); - } else { - key = { - type: "str", - value: match1(RE_IDENTIFIER) - }; - } - consumeToken(TOKEN_BRACKET_CLOSE, SyntaxError); - return key; - } - function parseLiteral() { - if (test(RE_NUMBER_LITERAL)) { - return parseNumberLiteral(); - } - if (source[cursor] === '"') { - return parseStringLiteral(); - } - throw new SyntaxError("Invalid expression"); - } - function parseNumberLiteral() { - let [, value, fraction = ""] = match(RE_NUMBER_LITERAL); - let precision = fraction.length; - return { - type: "num", - value: parseFloat(value), - precision - }; - } - function parseStringLiteral() { - consumeChar('"', SyntaxError); - let value = ""; - while (true) { - value += match1(RE_STRING_RUN); - if (source[cursor] === "\\") { - value += parseEscapeSequence(); - continue; - } - if (consumeChar('"')) { - return { - type: "str", - value - }; - } - throw new SyntaxError("Unclosed string literal"); - } - } - function parseEscapeSequence() { - if (test(RE_STRING_ESCAPE)) { - return match1(RE_STRING_ESCAPE); - } - if (test(RE_UNICODE_ESCAPE)) { - let [, codepoint4, codepoint6] = match(RE_UNICODE_ESCAPE); - let codepoint = parseInt(codepoint4 || codepoint6, 16); - return codepoint <= 0xd7ff || 0xe000 <= codepoint ? String.fromCodePoint(codepoint) : "�"; - } - throw new SyntaxError("Unknown escape sequence"); - } - function parseIndent() { - let start = cursor; - consumeToken(TOKEN_BLANK); - switch (source[cursor]) { - case ".": - case "[": - case "*": - case "}": - case undefined: - return false; - case "{": - return makeIndent(source.slice(start, cursor)); - } - if (source[cursor - 1] === " ") { - return makeIndent(source.slice(start, cursor)); - } - return false; - } - function trim(text, re) { - return text.replace(re, ""); - } - function makeIndent(blank) { - let value = blank.replace(RE_BLANK_LINES, "\n"); - let length = RE_INDENT.exec(blank)[1].length; - return new Indent(value, length); - } - } -} -class Indent { - constructor(value, length) { - this.value = value; - this.length = length; - } -} -;// ./node_modules/@fluent/bundle/esm/index.js - - - -;// ./node_modules/@fluent/dom/esm/overlay.js -const reOverlay = /<|&#?\w+;/; -const TEXT_LEVEL_ELEMENTS = { - "http://www.w3.org/1999/xhtml": ["em", "strong", "small", "s", "cite", "q", "dfn", "abbr", "data", "time", "code", "var", "samp", "kbd", "sub", "sup", "i", "b", "u", "mark", "bdi", "bdo", "span", "br", "wbr"] -}; -const LOCALIZABLE_ATTRIBUTES = { - "http://www.w3.org/1999/xhtml": { - global: ["title", "aria-label", "aria-valuetext"], - a: ["download"], - area: ["download", "alt"], - input: ["alt", "placeholder"], - menuitem: ["label"], - menu: ["label"], - optgroup: ["label"], - option: ["label"], - track: ["label"], - img: ["alt"], - textarea: ["placeholder"], - th: ["abbr"] - }, - "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul": { - global: ["accesskey", "aria-label", "aria-valuetext", "label", "title", "tooltiptext"], - description: ["value"], - key: ["key", "keycode"], - label: ["value"], - textbox: ["placeholder", "value"] - } -}; -function translateElement(element, translation) { - const { - value - } = translation; - if (typeof value === "string") { - if (element.localName === "title" && element.namespaceURI === "http://www.w3.org/1999/xhtml") { - element.textContent = value; - } else if (!reOverlay.test(value)) { - element.textContent = value; - } else { - const templateElement = element.ownerDocument.createElementNS("http://www.w3.org/1999/xhtml", "template"); - templateElement.innerHTML = value; - overlayChildNodes(templateElement.content, element); - } - } - overlayAttributes(translation, element); -} -function overlayChildNodes(fromFragment, toElement) { - for (const childNode of fromFragment.childNodes) { - if (childNode.nodeType === childNode.TEXT_NODE) { - continue; - } - if (childNode.hasAttribute("data-l10n-name")) { - const sanitized = getNodeForNamedElement(toElement, childNode); - fromFragment.replaceChild(sanitized, childNode); - continue; - } - if (isElementAllowed(childNode)) { - const sanitized = createSanitizedElement(childNode); - fromFragment.replaceChild(sanitized, childNode); - continue; - } - console.warn(`An element of forbidden type "${childNode.localName}" was found in ` + "the translation. Only safe text-level elements and elements with " + "data-l10n-name are allowed."); - fromFragment.replaceChild(createTextNodeFromTextContent(childNode), childNode); - } - toElement.textContent = ""; - toElement.appendChild(fromFragment); -} -function hasAttribute(attributes, name) { - if (!attributes) { - return false; - } - for (let attr of attributes) { - if (attr.name === name) { - return true; - } - } - return false; -} -function overlayAttributes(fromElement, toElement) { - const explicitlyAllowed = toElement.hasAttribute("data-l10n-attrs") ? toElement.getAttribute("data-l10n-attrs").split(",").map(i => i.trim()) : null; - for (const attr of Array.from(toElement.attributes)) { - if (isAttrNameLocalizable(attr.name, toElement, explicitlyAllowed) && !hasAttribute(fromElement.attributes, attr.name)) { - toElement.removeAttribute(attr.name); - } - } - if (!fromElement.attributes) { - return; - } - for (const attr of Array.from(fromElement.attributes)) { - if (isAttrNameLocalizable(attr.name, toElement, explicitlyAllowed) && toElement.getAttribute(attr.name) !== attr.value) { - toElement.setAttribute(attr.name, attr.value); - } - } -} -function getNodeForNamedElement(sourceElement, translatedChild) { - const childName = translatedChild.getAttribute("data-l10n-name"); - const sourceChild = sourceElement.querySelector(`[data-l10n-name="${childName}"]`); - if (!sourceChild) { - console.warn(`An element named "${childName}" wasn't found in the source.`); - return createTextNodeFromTextContent(translatedChild); - } - if (sourceChild.localName !== translatedChild.localName) { - console.warn(`An element named "${childName}" was found in the translation ` + `but its type ${translatedChild.localName} didn't match the ` + `element found in the source (${sourceChild.localName}).`); - return createTextNodeFromTextContent(translatedChild); - } - sourceElement.removeChild(sourceChild); - const clone = sourceChild.cloneNode(false); - return shallowPopulateUsing(translatedChild, clone); -} -function createSanitizedElement(element) { - const clone = element.ownerDocument.createElement(element.localName); - return shallowPopulateUsing(element, clone); -} -function createTextNodeFromTextContent(element) { - return element.ownerDocument.createTextNode(element.textContent); -} -function isElementAllowed(element) { - const allowed = TEXT_LEVEL_ELEMENTS[element.namespaceURI]; - return allowed && allowed.includes(element.localName); -} -function isAttrNameLocalizable(name, element, explicitlyAllowed = null) { - if (explicitlyAllowed && explicitlyAllowed.includes(name)) { - return true; - } - const allowed = LOCALIZABLE_ATTRIBUTES[element.namespaceURI]; - if (!allowed) { - return false; - } - const attrName = name.toLowerCase(); - const elemName = element.localName; - if (allowed.global.includes(attrName)) { - return true; - } - if (!allowed[elemName]) { - return false; - } - if (allowed[elemName].includes(attrName)) { - return true; - } - if (element.namespaceURI === "http://www.w3.org/1999/xhtml" && elemName === "input" && attrName === "value") { - const type = element.type.toLowerCase(); - if (type === "submit" || type === "button" || type === "reset") { - return true; - } - } - return false; -} -function shallowPopulateUsing(fromElement, toElement) { - toElement.textContent = fromElement.textContent; - overlayAttributes(fromElement, toElement); - return toElement; -} -;// ./node_modules/cached-iterable/src/cached_iterable.mjs -class CachedIterable extends Array { - static from(iterable) { - if (iterable instanceof this) { - return iterable; - } - return new this(iterable); - } -} -;// ./node_modules/cached-iterable/src/cached_sync_iterable.mjs - -class CachedSyncIterable extends CachedIterable { - constructor(iterable) { - super(); - if (Symbol.iterator in Object(iterable)) { - this.iterator = iterable[Symbol.iterator](); - } else { - throw new TypeError("Argument must implement the iteration protocol."); - } - } - [Symbol.iterator]() { - const cached = this; - let cur = 0; - return { - next() { - if (cached.length <= cur) { - cached.push(cached.iterator.next()); - } - return cached[cur++]; - } - }; - } - touchNext(count = 1) { - let idx = 0; - while (idx++ < count) { - const last = this[this.length - 1]; - if (last && last.done) { - break; - } - this.push(this.iterator.next()); - } - return this[this.length - 1]; - } -} -;// ./node_modules/cached-iterable/src/cached_async_iterable.mjs - -class CachedAsyncIterable extends CachedIterable { - constructor(iterable) { - super(); - if (Symbol.asyncIterator in Object(iterable)) { - this.iterator = iterable[Symbol.asyncIterator](); - } else if (Symbol.iterator in Object(iterable)) { - this.iterator = iterable[Symbol.iterator](); - } else { - throw new TypeError("Argument must implement the iteration protocol."); - } - } - [Symbol.asyncIterator]() { - const cached = this; - let cur = 0; - return { - async next() { - if (cached.length <= cur) { - cached.push(cached.iterator.next()); - } - return cached[cur++]; - } - }; - } - async touchNext(count = 1) { - let idx = 0; - while (idx++ < count) { - const last = this[this.length - 1]; - if (last && (await last).done) { - break; - } - this.push(this.iterator.next()); - } - return this[this.length - 1]; - } -} -;// ./node_modules/cached-iterable/src/index.mjs - - -;// ./node_modules/@fluent/dom/esm/localization.js - -class Localization { - constructor(resourceIds = [], generateBundles) { - this.resourceIds = resourceIds; - this.generateBundles = generateBundles; - this.onChange(true); - } - addResourceIds(resourceIds, eager = false) { - this.resourceIds.push(...resourceIds); - this.onChange(eager); - return this.resourceIds.length; - } - removeResourceIds(resourceIds) { - this.resourceIds = this.resourceIds.filter(r => !resourceIds.includes(r)); - this.onChange(); - return this.resourceIds.length; - } - async formatWithFallback(keys, method) { - const translations = []; - let hasAtLeastOneBundle = false; - for await (const bundle of this.bundles) { - hasAtLeastOneBundle = true; - const missingIds = keysFromBundle(method, bundle, keys, translations); - if (missingIds.size === 0) { - break; - } - if (typeof console !== "undefined") { - const locale = bundle.locales[0]; - const ids = Array.from(missingIds).join(", "); - console.warn(`[fluent] Missing translations in ${locale}: ${ids}`); - } - } - if (!hasAtLeastOneBundle && typeof console !== "undefined") { - console.warn(`[fluent] Request for keys failed because no resource bundles got generated. - keys: ${JSON.stringify(keys)}. - resourceIds: ${JSON.stringify(this.resourceIds)}.`); - } - return translations; - } - formatMessages(keys) { - return this.formatWithFallback(keys, messageFromBundle); - } - formatValues(keys) { - return this.formatWithFallback(keys, valueFromBundle); - } - async formatValue(id, args) { - const [val] = await this.formatValues([{ - id, - args - }]); - return val; - } - handleEvent() { - this.onChange(); - } - onChange(eager = false) { - this.bundles = CachedAsyncIterable.from(this.generateBundles(this.resourceIds)); - if (eager) { - this.bundles.touchNext(2); - } - } -} -function valueFromBundle(bundle, errors, message, args) { - if (message.value) { - return bundle.formatPattern(message.value, args, errors); - } - return null; -} -function messageFromBundle(bundle, errors, message, args) { - const formatted = { - value: null, - attributes: null - }; - if (message.value) { - formatted.value = bundle.formatPattern(message.value, args, errors); - } - let attrNames = Object.keys(message.attributes); - if (attrNames.length > 0) { - formatted.attributes = new Array(attrNames.length); - for (let [i, name] of attrNames.entries()) { - let value = bundle.formatPattern(message.attributes[name], args, errors); - formatted.attributes[i] = { - name, - value - }; - } - } - return formatted; -} -function keysFromBundle(method, bundle, keys, translations) { - const messageErrors = []; - const missingIds = new Set(); - keys.forEach(({ - id, - args - }, i) => { - if (translations[i] !== undefined) { - return; - } - let message = bundle.getMessage(id); - if (message) { - messageErrors.length = 0; - translations[i] = method(bundle, messageErrors, message, args); - if (messageErrors.length > 0 && typeof console !== "undefined") { - const locale = bundle.locales[0]; - const errors = messageErrors.join(", "); - console.warn(`[fluent][resolver] errors in ${locale}/${id}: ${errors}.`); - } - } else { - missingIds.add(id); - } - }); - return missingIds; -} -;// ./node_modules/@fluent/dom/esm/dom_localization.js - - -const L10NID_ATTR_NAME = "data-l10n-id"; -const L10NARGS_ATTR_NAME = "data-l10n-args"; -const L10N_ELEMENT_QUERY = `[${L10NID_ATTR_NAME}]`; -class DOMLocalization extends Localization { - constructor(resourceIds, generateBundles) { - super(resourceIds, generateBundles); - this.roots = new Set(); - this.pendingrAF = null; - this.pendingElements = new Set(); - this.windowElement = null; - this.mutationObserver = null; - this.observerConfig = { - attributes: true, - characterData: false, - childList: true, - subtree: true, - attributeFilter: [L10NID_ATTR_NAME, L10NARGS_ATTR_NAME] - }; - } - onChange(eager = false) { - super.onChange(eager); - if (this.roots) { - this.translateRoots(); - } - } - setAttributes(element, id, args) { - element.setAttribute(L10NID_ATTR_NAME, id); - if (args) { - element.setAttribute(L10NARGS_ATTR_NAME, JSON.stringify(args)); - } else { - element.removeAttribute(L10NARGS_ATTR_NAME); - } - return element; - } - getAttributes(element) { - return { - id: element.getAttribute(L10NID_ATTR_NAME), - args: JSON.parse(element.getAttribute(L10NARGS_ATTR_NAME) || null) - }; - } - connectRoot(newRoot) { - for (const root of this.roots) { - if (root === newRoot || root.contains(newRoot) || newRoot.contains(root)) { - throw new Error("Cannot add a root that overlaps with existing root."); - } - } - if (this.windowElement) { - if (this.windowElement !== newRoot.ownerDocument.defaultView) { - throw new Error(`Cannot connect a root: - DOMLocalization already has a root from a different window.`); - } - } else { - this.windowElement = newRoot.ownerDocument.defaultView; - this.mutationObserver = new this.windowElement.MutationObserver(mutations => this.translateMutations(mutations)); - } - this.roots.add(newRoot); - this.mutationObserver.observe(newRoot, this.observerConfig); - } - disconnectRoot(root) { - this.roots.delete(root); - this.pauseObserving(); - if (this.roots.size === 0) { - this.mutationObserver = null; - if (this.windowElement && this.pendingrAF) { - this.windowElement.cancelAnimationFrame(this.pendingrAF); - } - this.windowElement = null; - this.pendingrAF = null; - this.pendingElements.clear(); - return true; - } - this.resumeObserving(); - return false; - } - translateRoots() { - const roots = Array.from(this.roots); - return Promise.all(roots.map(root => this.translateFragment(root))); - } - pauseObserving() { - if (!this.mutationObserver) { - return; - } - this.translateMutations(this.mutationObserver.takeRecords()); - this.mutationObserver.disconnect(); - } - resumeObserving() { - if (!this.mutationObserver) { - return; - } - for (const root of this.roots) { - this.mutationObserver.observe(root, this.observerConfig); - } - } - translateMutations(mutations) { - for (const mutation of mutations) { - switch (mutation.type) { - case "attributes": - if (mutation.target.hasAttribute("data-l10n-id")) { - this.pendingElements.add(mutation.target); - } - break; - case "childList": - for (const addedNode of mutation.addedNodes) { - if (addedNode.nodeType === addedNode.ELEMENT_NODE) { - if (addedNode.childElementCount) { - for (const element of this.getTranslatables(addedNode)) { - this.pendingElements.add(element); - } - } else if (addedNode.hasAttribute(L10NID_ATTR_NAME)) { - this.pendingElements.add(addedNode); - } - } - } - break; - } - } - if (this.pendingElements.size > 0) { - if (this.pendingrAF === null) { - this.pendingrAF = this.windowElement.requestAnimationFrame(() => { - this.translateElements(Array.from(this.pendingElements)); - this.pendingElements.clear(); - this.pendingrAF = null; - }); - } - } - } - translateFragment(frag) { - return this.translateElements(this.getTranslatables(frag)); - } - async translateElements(elements) { - if (!elements.length) { - return undefined; - } - const keys = elements.map(this.getKeysForElement); - const translations = await this.formatMessages(keys); - return this.applyTranslations(elements, translations); - } - applyTranslations(elements, translations) { - this.pauseObserving(); - for (let i = 0; i < elements.length; i++) { - if (translations[i] !== undefined) { - translateElement(elements[i], translations[i]); - } - } - this.resumeObserving(); - } - getTranslatables(element) { - const nodes = Array.from(element.querySelectorAll(L10N_ELEMENT_QUERY)); - if (typeof element.hasAttribute === "function" && element.hasAttribute(L10NID_ATTR_NAME)) { - nodes.push(element); - } - return nodes; - } - getKeysForElement(element) { - return { - id: element.getAttribute(L10NID_ATTR_NAME), - args: JSON.parse(element.getAttribute(L10NARGS_ATTR_NAME) || null) - }; - } -} -;// ./node_modules/@fluent/dom/esm/index.js - - -;// ./web/l10n.js -class L10n { - #dir; - #elements; - #lang; - #l10n; - constructor({ - lang, - isRTL - }, l10n = null) { - this.#lang = L10n.#fixupLangCode(lang); - this.#l10n = l10n; - this.#dir = isRTL ?? L10n.#isRTL(this.#lang) ? "rtl" : "ltr"; - } - _setL10n(l10n) { - this.#l10n = l10n; - } - getLanguage() { - return this.#lang; - } - getDirection() { - return this.#dir; - } - async get(ids, args = null, fallback) { - if (Array.isArray(ids)) { - ids = ids.map(id => ({ - id - })); - const messages = await this.#l10n.formatMessages(ids); - return messages.map(message => message.value); - } - const messages = await this.#l10n.formatMessages([{ - id: ids, - args - }]); - return messages[0]?.value || fallback; - } - async translate(element) { - (this.#elements ||= new Set()).add(element); - try { - this.#l10n.connectRoot(element); - await this.#l10n.translateRoots(); - } catch {} - } - async translateOnce(element) { - try { - await this.#l10n.translateElements([element]); - } catch (ex) { - console.error("translateOnce:", ex); - } - } - async destroy() { - if (this.#elements) { - for (const element of this.#elements) { - this.#l10n.disconnectRoot(element); - } - this.#elements.clear(); - this.#elements = null; - } - this.#l10n.pauseObserving(); - } - pause() { - this.#l10n.pauseObserving(); - } - resume() { - this.#l10n.resumeObserving(); - } - static #fixupLangCode(langCode) { - langCode = langCode?.toLowerCase() || "en-us"; - const PARTIAL_LANG_CODES = { - en: "en-us", - es: "es-es", - fy: "fy-nl", - ga: "ga-ie", - gu: "gu-in", - hi: "hi-in", - hy: "hy-am", - nb: "nb-no", - ne: "ne-np", - nn: "nn-no", - pa: "pa-in", - pt: "pt-pt", - sv: "sv-se", - zh: "zh-cn" - }; - return PARTIAL_LANG_CODES[langCode] || langCode; - } - static #isRTL(lang) { - const shortCode = lang.split("-", 1)[0]; - return ["ar", "he", "fa", "ps", "ur"].includes(shortCode); - } -} -const GenericL10n = null; - -;// ./web/genericl10n.js - - - - -function createBundle(lang, text) { - const resource = new FluentResource(text); - const bundle = new FluentBundle(lang); - const errors = bundle.addResource(resource); - if (errors.length) { - console.error("L10n errors", errors); - } - return bundle; -} -class genericl10n_GenericL10n extends L10n { - constructor(lang) { - super({ - lang - }); - const generateBundles = !lang ? genericl10n_GenericL10n.#generateBundlesFallback.bind(genericl10n_GenericL10n, this.getLanguage()) : genericl10n_GenericL10n.#generateBundles.bind(genericl10n_GenericL10n, "en-us", this.getLanguage()); - this._setL10n(new DOMLocalization([], generateBundles)); - } - static async *#generateBundles(defaultLang, baseLang) { - const { - baseURL, - paths - } = await this.#getPaths(); - const langs = [baseLang]; - if (defaultLang !== baseLang) { - const shortLang = baseLang.split("-", 1)[0]; - if (shortLang !== baseLang) { - langs.push(shortLang); - } - langs.push(defaultLang); - } - for (const lang of langs) { - const bundle = await this.#createBundle(lang, baseURL, paths); - if (bundle) { - yield bundle; - } else if (lang === "en-us") { - yield this.#createBundleFallback(lang); - } - } - } - static async #createBundle(lang, baseURL, paths) { - const path = paths[lang]; - if (!path) { - return null; - } - const url = new URL(path, baseURL); - const text = await fetchData(url, "text"); - return createBundle(lang, text); - } - static async #getPaths() { - try { - const { - href - } = document.querySelector(`link[type="application/l10n"]`); - const paths = await fetchData(href, "json"); - return { - baseURL: href.replace(/[^/]*$/, "") || "./", - paths - }; - } catch {} - return { - baseURL: "./", - paths: Object.create(null) - }; - } - static async *#generateBundlesFallback(lang) { - yield this.#createBundleFallback(lang); - } - static async #createBundleFallback(lang) { - const text = "pdfjs-previous-button =\n .title = Previous Page\npdfjs-previous-button-label = Previous\npdfjs-next-button =\n .title = Next Page\npdfjs-next-button-label = Next\npdfjs-page-input =\n .title = Page\npdfjs-of-pages = of { $pagesCount }\npdfjs-page-of-pages = ({ $pageNumber } of { $pagesCount })\npdfjs-zoom-out-button =\n .title = Zoom Out\npdfjs-zoom-out-button-label = Zoom Out\npdfjs-zoom-in-button =\n .title = Zoom In\npdfjs-zoom-in-button-label = Zoom In\npdfjs-zoom-select =\n .title = Zoom\npdfjs-presentation-mode-button =\n .title = Switch to Presentation Mode\npdfjs-presentation-mode-button-label = Presentation Mode\npdfjs-open-file-button =\n .title = Open File\npdfjs-open-file-button-label = Open\npdfjs-print-button =\n .title = Print\npdfjs-print-button-label = Print\npdfjs-save-button =\n .title = Save\npdfjs-save-button-label = Save\npdfjs-download-button =\n .title = Download\npdfjs-download-button-label = Download\npdfjs-bookmark-button =\n .title = Current Page (View URL from Current Page)\npdfjs-bookmark-button-label = Current Page\npdfjs-tools-button =\n .title = Tools\npdfjs-tools-button-label = Tools\npdfjs-first-page-button =\n .title = Go to First Page\npdfjs-first-page-button-label = Go to First Page\npdfjs-last-page-button =\n .title = Go to Last Page\npdfjs-last-page-button-label = Go to Last Page\npdfjs-page-rotate-cw-button =\n .title = Rotate Clockwise\npdfjs-page-rotate-cw-button-label = Rotate Clockwise\npdfjs-page-rotate-ccw-button =\n .title = Rotate Counterclockwise\npdfjs-page-rotate-ccw-button-label = Rotate Counterclockwise\npdfjs-cursor-text-select-tool-button =\n .title = Enable Text Selection Tool\npdfjs-cursor-text-select-tool-button-label = Text Selection Tool\npdfjs-cursor-hand-tool-button =\n .title = Enable Hand Tool\npdfjs-cursor-hand-tool-button-label = Hand Tool\npdfjs-scroll-page-button =\n .title = Use Page Scrolling\npdfjs-scroll-page-button-label = Page Scrolling\npdfjs-scroll-vertical-button =\n .title = Use Vertical Scrolling\npdfjs-scroll-vertical-button-label = Vertical Scrolling\npdfjs-scroll-horizontal-button =\n .title = Use Horizontal Scrolling\npdfjs-scroll-horizontal-button-label = Horizontal Scrolling\npdfjs-scroll-wrapped-button =\n .title = Use Wrapped Scrolling\npdfjs-scroll-wrapped-button-label = Wrapped Scrolling\npdfjs-spread-none-button =\n .title = Do not join page spreads\npdfjs-spread-none-button-label = No Spreads\npdfjs-spread-odd-button =\n .title = Join page spreads starting with odd-numbered pages\npdfjs-spread-odd-button-label = Odd Spreads\npdfjs-spread-even-button =\n .title = Join page spreads starting with even-numbered pages\npdfjs-spread-even-button-label = Even Spreads\npdfjs-document-properties-button =\n .title = Document Properties\u2026\npdfjs-document-properties-button-label = Document Properties\u2026\npdfjs-document-properties-file-name = File name:\npdfjs-document-properties-file-size = File size:\npdfjs-document-properties-size-kb = { NUMBER($kb, maximumSignificantDigits: 3) } KB ({ $b } bytes)\npdfjs-document-properties-size-mb = { NUMBER($mb, maximumSignificantDigits: 3) } MB ({ $b } bytes)\npdfjs-document-properties-title = Title:\npdfjs-document-properties-author = Author:\npdfjs-document-properties-subject = Subject:\npdfjs-document-properties-keywords = Keywords:\npdfjs-document-properties-creation-date = Creation Date:\npdfjs-document-properties-modification-date = Modification Date:\npdfjs-document-properties-date-time-string = { DATETIME($dateObj, dateStyle: \"short\", timeStyle: \"medium\") }\npdfjs-document-properties-creator = Creator:\npdfjs-document-properties-producer = PDF Producer:\npdfjs-document-properties-version = PDF Version:\npdfjs-document-properties-page-count = Page Count:\npdfjs-document-properties-page-size = Page Size:\npdfjs-document-properties-page-size-unit-inches = in\npdfjs-document-properties-page-size-unit-millimeters = mm\npdfjs-document-properties-page-size-orientation-portrait = portrait\npdfjs-document-properties-page-size-orientation-landscape = landscape\npdfjs-document-properties-page-size-name-a-three = A3\npdfjs-document-properties-page-size-name-a-four = A4\npdfjs-document-properties-page-size-name-letter = Letter\npdfjs-document-properties-page-size-name-legal = Legal\npdfjs-document-properties-page-size-dimension-string = { $width } \xD7 { $height } { $unit } ({ $orientation })\npdfjs-document-properties-page-size-dimension-name-string = { $width } \xD7 { $height } { $unit } ({ $name }, { $orientation })\npdfjs-document-properties-linearized = Fast Web View:\npdfjs-document-properties-linearized-yes = Yes\npdfjs-document-properties-linearized-no = No\npdfjs-document-properties-close-button = Close\npdfjs-print-progress-message = Preparing document for printing\u2026\npdfjs-print-progress-percent = { $progress }%\npdfjs-print-progress-close-button = Cancel\npdfjs-printing-not-supported = Warning: Printing is not fully supported by this browser.\npdfjs-printing-not-ready = Warning: The PDF is not fully loaded for printing.\npdfjs-toggle-sidebar-button =\n .title = Toggle Sidebar\npdfjs-toggle-sidebar-notification-button =\n .title = Toggle Sidebar (document contains outline/attachments/layers)\npdfjs-toggle-sidebar-button-label = Toggle Sidebar\npdfjs-document-outline-button =\n .title = Show Document Outline (double-click to expand/collapse all items)\npdfjs-document-outline-button-label = Document Outline\npdfjs-attachments-button =\n .title = Show Attachments\npdfjs-attachments-button-label = Attachments\npdfjs-layers-button =\n .title = Show Layers (double-click to reset all layers to the default state)\npdfjs-layers-button-label = Layers\npdfjs-thumbs-button =\n .title = Show Thumbnails\npdfjs-thumbs-button-label = Thumbnails\npdfjs-current-outline-item-button =\n .title = Find Current Outline Item\npdfjs-current-outline-item-button-label = Current Outline Item\npdfjs-findbar-button =\n .title = Find in Document\npdfjs-findbar-button-label = Find\npdfjs-additional-layers = Additional Layers\npdfjs-thumb-page-title =\n .title = Page { $page }\npdfjs-thumb-page-canvas =\n .aria-label = Thumbnail of Page { $page }\npdfjs-find-input =\n .title = Find\n .placeholder = Find in document\u2026\npdfjs-find-previous-button =\n .title = Find the previous occurrence of the phrase\npdfjs-find-previous-button-label = Previous\npdfjs-find-next-button =\n .title = Find the next occurrence of the phrase\npdfjs-find-next-button-label = Next\npdfjs-find-highlight-checkbox = Highlight All\npdfjs-find-match-case-checkbox-label = Match Case\npdfjs-find-match-diacritics-checkbox-label = Match Diacritics\npdfjs-find-entire-word-checkbox-label = Whole Words\npdfjs-find-reached-top = Reached top of document, continued from bottom\npdfjs-find-reached-bottom = Reached end of document, continued from top\npdfjs-find-match-count =\n { $total ->\n [one] { $current } of { $total } match\n *[other] { $current } of { $total } matches\n }\npdfjs-find-match-count-limit =\n { $limit ->\n [one] More than { $limit } match\n *[other] More than { $limit } matches\n }\npdfjs-find-not-found = Phrase not found\npdfjs-page-scale-width = Page Width\npdfjs-page-scale-fit = Page Fit\npdfjs-page-scale-auto = Automatic Zoom\npdfjs-page-scale-actual = Actual Size\npdfjs-page-scale-percent = { $scale }%\npdfjs-page-landmark =\n .aria-label = Page { $page }\npdfjs-loading-error = An error occurred while loading the PDF.\npdfjs-invalid-file-error = Invalid or corrupted PDF file.\npdfjs-missing-file-error = Missing PDF file.\npdfjs-unexpected-response-error = Unexpected server response.\npdfjs-rendering-error = An error occurred while rendering the page.\npdfjs-annotation-date-time-string = { DATETIME($dateObj, dateStyle: \"short\", timeStyle: \"medium\") }\npdfjs-text-annotation-type =\n .alt = [{ $type } Annotation]\npdfjs-password-label = Enter the password to open this PDF file.\npdfjs-password-invalid = Invalid password. Please try again.\npdfjs-password-ok-button = OK\npdfjs-password-cancel-button = Cancel\npdfjs-web-fonts-disabled = Web fonts are disabled: unable to use embedded PDF fonts.\npdfjs-editor-free-text-button =\n .title = Text\npdfjs-editor-free-text-button-label = Text\npdfjs-editor-ink-button =\n .title = Draw\npdfjs-editor-ink-button-label = Draw\npdfjs-editor-stamp-button =\n .title = Add or edit images\npdfjs-editor-stamp-button-label = Add or edit images\npdfjs-editor-highlight-button =\n .title = Highlight\npdfjs-editor-highlight-button-label = Highlight\npdfjs-highlight-floating-button1 =\n .title = Highlight\n .aria-label = Highlight\npdfjs-highlight-floating-button-label = Highlight\npdfjs-editor-remove-ink-button =\n .title = Remove drawing\npdfjs-editor-remove-freetext-button =\n .title = Remove text\npdfjs-editor-remove-stamp-button =\n .title = Remove image\npdfjs-editor-remove-highlight-button =\n .title = Remove highlight\npdfjs-editor-free-text-color-input = Color\npdfjs-editor-free-text-size-input = Size\npdfjs-editor-ink-color-input = Color\npdfjs-editor-ink-thickness-input = Thickness\npdfjs-editor-ink-opacity-input = Opacity\npdfjs-editor-stamp-add-image-button =\n .title = Add image\npdfjs-editor-stamp-add-image-button-label = Add image\npdfjs-editor-free-highlight-thickness-input = Thickness\npdfjs-editor-free-highlight-thickness-title =\n .title = Change thickness when highlighting items other than text\npdfjs-free-text2 =\n .aria-label = Text Editor\n .default-content = Start typing\u2026\npdfjs-ink =\n .aria-label = Draw Editor\npdfjs-ink-canvas =\n .aria-label = User-created image\npdfjs-editor-alt-text-button =\n .aria-label = Alt text\npdfjs-editor-alt-text-button-label = Alt text\npdfjs-editor-alt-text-edit-button =\n .aria-label = Edit alt text\npdfjs-editor-alt-text-dialog-label = Choose an option\npdfjs-editor-alt-text-dialog-description = Alt text (alternative text) helps when people can\u2019t see the image or when it doesn\u2019t load.\npdfjs-editor-alt-text-add-description-label = Add a description\npdfjs-editor-alt-text-add-description-description = Aim for 1-2 sentences that describe the subject, setting, or actions.\npdfjs-editor-alt-text-mark-decorative-label = Mark as decorative\npdfjs-editor-alt-text-mark-decorative-description = This is used for ornamental images, like borders or watermarks.\npdfjs-editor-alt-text-cancel-button = Cancel\npdfjs-editor-alt-text-save-button = Save\npdfjs-editor-alt-text-decorative-tooltip = Marked as decorative\npdfjs-editor-alt-text-textarea =\n .placeholder = For example, \u201CA young man sits down at a table to eat a meal\u201D\npdfjs-editor-resizer-top-left =\n .aria-label = Top left corner \u2014 resize\npdfjs-editor-resizer-top-middle =\n .aria-label = Top middle \u2014 resize\npdfjs-editor-resizer-top-right =\n .aria-label = Top right corner \u2014 resize\npdfjs-editor-resizer-middle-right =\n .aria-label = Middle right \u2014 resize\npdfjs-editor-resizer-bottom-right =\n .aria-label = Bottom right corner \u2014 resize\npdfjs-editor-resizer-bottom-middle =\n .aria-label = Bottom middle \u2014 resize\npdfjs-editor-resizer-bottom-left =\n .aria-label = Bottom left corner \u2014 resize\npdfjs-editor-resizer-middle-left =\n .aria-label = Middle left \u2014 resize\npdfjs-editor-highlight-colorpicker-label = Highlight color\npdfjs-editor-colorpicker-button =\n .title = Change color\npdfjs-editor-colorpicker-dropdown =\n .aria-label = Color choices\npdfjs-editor-colorpicker-yellow =\n .title = Yellow\npdfjs-editor-colorpicker-green =\n .title = Green\npdfjs-editor-colorpicker-blue =\n .title = Blue\npdfjs-editor-colorpicker-pink =\n .title = Pink\npdfjs-editor-colorpicker-red =\n .title = Red\npdfjs-editor-highlight-show-all-button-label = Show all\npdfjs-editor-highlight-show-all-button =\n .title = Show all\npdfjs-editor-new-alt-text-dialog-edit-label = Edit alt text (image description)\npdfjs-editor-new-alt-text-dialog-add-label = Add alt text (image description)\npdfjs-editor-new-alt-text-textarea =\n .placeholder = Write your description here\u2026\npdfjs-editor-new-alt-text-description = Short description for people who can\u2019t see the image or when the image doesn\u2019t load.\npdfjs-editor-new-alt-text-disclaimer1 = This alt text was created automatically and may be inaccurate.\npdfjs-editor-new-alt-text-disclaimer-learn-more-url = Learn more\npdfjs-editor-new-alt-text-create-automatically-button-label = Create alt text automatically\npdfjs-editor-new-alt-text-not-now-button = Not now\npdfjs-editor-new-alt-text-error-title = Couldn\u2019t create alt text automatically\npdfjs-editor-new-alt-text-error-description = Please write your own alt text or try again later.\npdfjs-editor-new-alt-text-error-close-button = Close\npdfjs-editor-new-alt-text-ai-model-downloading-progress = Downloading alt text AI model ({ $downloadedSize } of { $totalSize } MB)\n .aria-valuetext = Downloading alt text AI model ({ $downloadedSize } of { $totalSize } MB)\npdfjs-editor-new-alt-text-added-button =\n .aria-label = Alt text added\npdfjs-editor-new-alt-text-added-button-label = Alt text added\npdfjs-editor-new-alt-text-missing-button =\n .aria-label = Missing alt text\npdfjs-editor-new-alt-text-missing-button-label = Missing alt text\npdfjs-editor-new-alt-text-to-review-button =\n .aria-label = Review alt text\npdfjs-editor-new-alt-text-to-review-button-label = Review alt text\npdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer = Created automatically: { $generatedAltText }\npdfjs-image-alt-text-settings-button =\n .title = Image alt text settings\npdfjs-image-alt-text-settings-button-label = Image alt text settings\npdfjs-editor-alt-text-settings-dialog-label = Image alt text settings\npdfjs-editor-alt-text-settings-automatic-title = Automatic alt text\npdfjs-editor-alt-text-settings-create-model-button-label = Create alt text automatically\npdfjs-editor-alt-text-settings-create-model-description = Suggests descriptions to help people who can\u2019t see the image or when the image doesn\u2019t load.\npdfjs-editor-alt-text-settings-download-model-label = Alt text AI model ({ $totalSize } MB)\npdfjs-editor-alt-text-settings-ai-model-description = Runs locally on your device so your data stays private. Required for automatic alt text.\npdfjs-editor-alt-text-settings-delete-model-button = Delete\npdfjs-editor-alt-text-settings-download-model-button = Download\npdfjs-editor-alt-text-settings-downloading-model-button = Downloading\u2026\npdfjs-editor-alt-text-settings-editor-title = Alt text editor\npdfjs-editor-alt-text-settings-show-dialog-button-label = Show alt text editor right away when adding an image\npdfjs-editor-alt-text-settings-show-dialog-description = Helps you make sure all your images have alt text.\npdfjs-editor-alt-text-settings-close-button = Close\npdfjs-editor-undo-bar-message-highlight = Highlight removed\npdfjs-editor-undo-bar-message-freetext = Text removed\npdfjs-editor-undo-bar-message-ink = Drawing removed\npdfjs-editor-undo-bar-message-stamp = Image removed\npdfjs-editor-undo-bar-message-multiple =\n { $count ->\n [one] { $count } annotation removed\n *[other] { $count } annotations removed\n }\npdfjs-editor-undo-bar-undo-button =\n .title = Undo\npdfjs-editor-undo-bar-undo-button-label = Undo\npdfjs-editor-undo-bar-close-button =\n .title = Close\npdfjs-editor-undo-bar-close-button-label = Close"; - return createBundle(lang, text); - } -} - -;// ./web/pdf_history.js - - -const HASH_CHANGE_TIMEOUT = 1000; -const POSITION_UPDATED_THRESHOLD = 50; -const UPDATE_VIEWAREA_TIMEOUT = 1000; -function getCurrentHash() { - return document.location.hash; -} -class PDFHistory { - #eventAbortController = null; - constructor({ - linkService, - eventBus - }) { - this.linkService = linkService; - this.eventBus = eventBus; - this._initialized = false; - this._fingerprint = ""; - this.reset(); - this.eventBus._on("pagesinit", () => { - this._isPagesLoaded = false; - this.eventBus._on("pagesloaded", evt => { - this._isPagesLoaded = !!evt.pagesCount; - }, { - once: true - }); - }); - } - initialize({ - fingerprint, - resetHistory = false, - updateUrl = false - }) { - if (!fingerprint || typeof fingerprint !== "string") { - console.error('PDFHistory.initialize: The "fingerprint" must be a non-empty string.'); - return; - } - if (this._initialized) { - this.reset(); - } - const reInitialized = this._fingerprint !== "" && this._fingerprint !== fingerprint; - this._fingerprint = fingerprint; - this._updateUrl = updateUrl === true; - this._initialized = true; - this.#bindEvents(); - const state = window.history.state; - this._popStateInProgress = false; - this._blockHashChange = 0; - this._currentHash = getCurrentHash(); - this._numPositionUpdates = 0; - this._uid = this._maxUid = 0; - this._destination = null; - this._position = null; - if (!this.#isValidState(state, true) || resetHistory) { - const { - hash, - page, - rotation - } = this.#parseCurrentHash(true); - if (!hash || reInitialized || resetHistory) { - this.#pushOrReplaceState(null, true); - return; - } - this.#pushOrReplaceState({ - hash, - page, - rotation - }, true); - return; - } - const destination = state.destination; - this.#updateInternalState(destination, state.uid, true); - if (destination.rotation !== undefined) { - this._initialRotation = destination.rotation; - } - if (destination.dest) { - this._initialBookmark = JSON.stringify(destination.dest); - this._destination.page = null; - } else if (destination.hash) { - this._initialBookmark = destination.hash; - } else if (destination.page) { - this._initialBookmark = `page=${destination.page}`; - } - } - reset() { - if (this._initialized) { - this.#pageHide(); - this._initialized = false; - this.#unbindEvents(); - } - if (this._updateViewareaTimeout) { - clearTimeout(this._updateViewareaTimeout); - this._updateViewareaTimeout = null; - } - this._initialBookmark = null; - this._initialRotation = null; - } - push({ - namedDest = null, - explicitDest, - pageNumber - }) { - if (!this._initialized) { - return; - } - if (namedDest && typeof namedDest !== "string") { - console.error("PDFHistory.push: " + `"${namedDest}" is not a valid namedDest parameter.`); - return; - } else if (!Array.isArray(explicitDest)) { - console.error("PDFHistory.push: " + `"${explicitDest}" is not a valid explicitDest parameter.`); - return; - } else if (!this.#isValidPage(pageNumber)) { - if (pageNumber !== null || this._destination) { - console.error("PDFHistory.push: " + `"${pageNumber}" is not a valid pageNumber parameter.`); - return; - } - } - const hash = namedDest || JSON.stringify(explicitDest); - if (!hash) { - return; - } - let forceReplace = false; - if (this._destination && (isDestHashesEqual(this._destination.hash, hash) || isDestArraysEqual(this._destination.dest, explicitDest))) { - if (this._destination.page) { - return; - } - forceReplace = true; - } - if (this._popStateInProgress && !forceReplace) { - return; - } - this.#pushOrReplaceState({ - dest: explicitDest, - hash, - page: pageNumber, - rotation: this.linkService.rotation - }, forceReplace); - if (!this._popStateInProgress) { - this._popStateInProgress = true; - Promise.resolve().then(() => { - this._popStateInProgress = false; - }); - } - } - pushPage(pageNumber) { - if (!this._initialized) { - return; - } - if (!this.#isValidPage(pageNumber)) { - console.error(`PDFHistory.pushPage: "${pageNumber}" is not a valid page number.`); - return; - } - if (this._destination?.page === pageNumber) { - return; - } - if (this._popStateInProgress) { - return; - } - this.#pushOrReplaceState({ - dest: null, - hash: `page=${pageNumber}`, - page: pageNumber, - rotation: this.linkService.rotation - }); - if (!this._popStateInProgress) { - this._popStateInProgress = true; - Promise.resolve().then(() => { - this._popStateInProgress = false; - }); - } - } - pushCurrentPosition() { - if (!this._initialized || this._popStateInProgress) { - return; - } - this.#tryPushCurrentPosition(); - } - back() { - if (!this._initialized || this._popStateInProgress) { - return; - } - const state = window.history.state; - if (this.#isValidState(state) && state.uid > 0) { - window.history.back(); - } - } - forward() { - if (!this._initialized || this._popStateInProgress) { - return; - } - const state = window.history.state; - if (this.#isValidState(state) && state.uid < this._maxUid) { - window.history.forward(); - } - } - get popStateInProgress() { - return this._initialized && (this._popStateInProgress || this._blockHashChange > 0); - } - get initialBookmark() { - return this._initialized ? this._initialBookmark : null; - } - get initialRotation() { - return this._initialized ? this._initialRotation : null; - } - #pushOrReplaceState(destination, forceReplace = false) { - const shouldReplace = forceReplace || !this._destination; - const newState = { - fingerprint: this._fingerprint, - uid: shouldReplace ? this._uid : this._uid + 1, - destination - }; - this.#updateInternalState(destination, newState.uid); - let newUrl; - if (this._updateUrl && destination?.hash) { - const baseUrl = document.location.href.split("#", 1)[0]; - if (!baseUrl.startsWith("file://")) { - newUrl = `${baseUrl}#${destination.hash}`; - } - } - if (shouldReplace) { - window.history.replaceState(newState, "", newUrl); - } else { - window.history.pushState(newState, "", newUrl); - } - } - #tryPushCurrentPosition(temporary = false) { - if (!this._position) { - return; - } - let position = this._position; - if (temporary) { - position = Object.assign(Object.create(null), this._position); - position.temporary = true; - } - if (!this._destination) { - this.#pushOrReplaceState(position); - return; - } - if (this._destination.temporary) { - this.#pushOrReplaceState(position, true); - return; - } - if (this._destination.hash === position.hash) { - return; - } - if (!this._destination.page && (POSITION_UPDATED_THRESHOLD <= 0 || this._numPositionUpdates <= POSITION_UPDATED_THRESHOLD)) { - return; - } - let forceReplace = false; - if (this._destination.page >= position.first && this._destination.page <= position.page) { - if (this._destination.dest !== undefined || !this._destination.first) { - return; - } - forceReplace = true; - } - this.#pushOrReplaceState(position, forceReplace); - } - #isValidPage(val) { - return Number.isInteger(val) && val > 0 && val <= this.linkService.pagesCount; - } - #isValidState(state, checkReload = false) { - if (!state) { - return false; - } - if (state.fingerprint !== this._fingerprint) { - if (checkReload) { - if (typeof state.fingerprint !== "string" || state.fingerprint.length !== this._fingerprint.length) { - return false; - } - const [perfEntry] = performance.getEntriesByType("navigation"); - if (perfEntry?.type !== "reload") { - return false; - } - } else { - return false; - } - } - if (!Number.isInteger(state.uid) || state.uid < 0) { - return false; - } - if (state.destination === null || typeof state.destination !== "object") { - return false; - } - return true; - } - #updateInternalState(destination, uid, removeTemporary = false) { - if (this._updateViewareaTimeout) { - clearTimeout(this._updateViewareaTimeout); - this._updateViewareaTimeout = null; - } - if (removeTemporary && destination?.temporary) { - delete destination.temporary; - } - this._destination = destination; - this._uid = uid; - this._maxUid = Math.max(this._maxUid, uid); - this._numPositionUpdates = 0; - } - #parseCurrentHash(checkNameddest = false) { - const hash = unescape(getCurrentHash()).substring(1); - const params = parseQueryString(hash); - const nameddest = params.get("nameddest") || ""; - let page = params.get("page") | 0; - if (!this.#isValidPage(page) || checkNameddest && nameddest.length > 0) { - page = null; - } - return { - hash, - page, - rotation: this.linkService.rotation - }; - } - #updateViewarea({ - location - }) { - if (this._updateViewareaTimeout) { - clearTimeout(this._updateViewareaTimeout); - this._updateViewareaTimeout = null; - } - this._position = { - hash: location.pdfOpenParams.substring(1), - page: this.linkService.page, - first: location.pageNumber, - rotation: location.rotation - }; - if (this._popStateInProgress) { - return; - } - if (POSITION_UPDATED_THRESHOLD > 0 && this._isPagesLoaded && this._destination && !this._destination.page) { - this._numPositionUpdates++; - } - if (UPDATE_VIEWAREA_TIMEOUT > 0) { - this._updateViewareaTimeout = setTimeout(() => { - if (!this._popStateInProgress) { - this.#tryPushCurrentPosition(true); - } - this._updateViewareaTimeout = null; - }, UPDATE_VIEWAREA_TIMEOUT); - } - } - #popState({ - state - }) { - const newHash = getCurrentHash(), - hashChanged = this._currentHash !== newHash; - this._currentHash = newHash; - if (!state) { - this._uid++; - const { - hash, - page, - rotation - } = this.#parseCurrentHash(); - this.#pushOrReplaceState({ - hash, - page, - rotation - }, true); - return; - } - if (!this.#isValidState(state)) { - return; - } - this._popStateInProgress = true; - if (hashChanged) { - this._blockHashChange++; - waitOnEventOrTimeout({ - target: window, - name: "hashchange", - delay: HASH_CHANGE_TIMEOUT - }).then(() => { - this._blockHashChange--; - }); - } - const destination = state.destination; - this.#updateInternalState(destination, state.uid, true); - if (isValidRotation(destination.rotation)) { - this.linkService.rotation = destination.rotation; - } - if (destination.dest) { - this.linkService.goToDestination(destination.dest); - } else if (destination.hash) { - this.linkService.setHash(destination.hash); - } else if (destination.page) { - this.linkService.page = destination.page; - } - Promise.resolve().then(() => { - this._popStateInProgress = false; - }); - } - #pageHide() { - if (!this._destination || this._destination.temporary) { - this.#tryPushCurrentPosition(); - } - } - #bindEvents() { - if (this.#eventAbortController) { - return; - } - this.#eventAbortController = new AbortController(); - const { - signal - } = this.#eventAbortController; - this.eventBus._on("updateviewarea", this.#updateViewarea.bind(this), { - signal - }); - window.addEventListener("popstate", this.#popState.bind(this), { - signal - }); - window.addEventListener("pagehide", this.#pageHide.bind(this), { - signal - }); - } - #unbindEvents() { - this.#eventAbortController?.abort(); - this.#eventAbortController = null; - } -} -function isDestHashesEqual(destHash, pushHash) { - if (typeof destHash !== "string" || typeof pushHash !== "string") { - return false; - } - if (destHash === pushHash) { - return true; - } - const nameddest = parseQueryString(destHash).get("nameddest"); - if (nameddest === pushHash) { - return true; - } - return false; -} -function isDestArraysEqual(firstDest, secondDest) { - function isEntryEqual(first, second) { - if (typeof first !== typeof second) { - return false; - } - if (Array.isArray(first) || Array.isArray(second)) { - return false; - } - if (first !== null && typeof first === "object" && second !== null) { - if (Object.keys(first).length !== Object.keys(second).length) { - return false; - } - for (const key in first) { - if (!isEntryEqual(first[key], second[key])) { - return false; - } - } - return true; - } - return first === second || Number.isNaN(first) && Number.isNaN(second); - } - if (!(Array.isArray(firstDest) && Array.isArray(secondDest))) { - return false; - } - if (firstDest.length !== secondDest.length) { - return false; - } - for (let i = 0, ii = firstDest.length; i < ii; i++) { - if (!isEntryEqual(firstDest[i], secondDest[i])) { - return false; - } - } - return true; -} - -;// ./web/annotation_editor_layer_builder.js - - -class AnnotationEditorLayerBuilder { - #annotationLayer = null; - #drawLayer = null; - #onAppend = null; - #structTreeLayer = null; - #textLayer = null; - #uiManager; - constructor(options) { - this.pdfPage = options.pdfPage; - this.accessibilityManager = options.accessibilityManager; - this.l10n = options.l10n; - this.l10n ||= new genericl10n_GenericL10n(); - this.annotationEditorLayer = null; - this.div = null; - this._cancelled = false; - this.#uiManager = options.uiManager; - this.#annotationLayer = options.annotationLayer || null; - this.#textLayer = options.textLayer || null; - this.#drawLayer = options.drawLayer || null; - this.#onAppend = options.onAppend || null; - this.#structTreeLayer = options.structTreeLayer || null; - } - async render(viewport, intent = "display") { - if (intent !== "display") { - return; - } - if (this._cancelled) { - return; - } - const clonedViewport = viewport.clone({ - dontFlip: true - }); - if (this.div) { - this.annotationEditorLayer.update({ - viewport: clonedViewport - }); - this.show(); - return; - } - const div = this.div = document.createElement("div"); - div.className = "annotationEditorLayer"; - div.hidden = true; - div.dir = this.#uiManager.direction; - this.#onAppend?.(div); - this.annotationEditorLayer = new AnnotationEditorLayer({ - uiManager: this.#uiManager, - div, - structTreeLayer: this.#structTreeLayer, - accessibilityManager: this.accessibilityManager, - pageIndex: this.pdfPage.pageNumber - 1, - l10n: this.l10n, - viewport: clonedViewport, - annotationLayer: this.#annotationLayer, - textLayer: this.#textLayer, - drawLayer: this.#drawLayer - }); - const parameters = { - viewport: clonedViewport, - div, - annotations: null, - intent - }; - this.annotationEditorLayer.render(parameters); - this.show(); - } - cancel() { - this._cancelled = true; - if (!this.div) { - return; - } - this.annotationEditorLayer.destroy(); - } - hide() { - if (!this.div) { - return; - } - this.annotationEditorLayer.pause(true); - this.div.hidden = true; - } - show() { - if (!this.div || this.annotationEditorLayer.isInvisible) { - return; - } - this.div.hidden = false; - this.annotationEditorLayer.pause(false); - } -} - -;// ./web/app_options.js -{ - var compatParams = new Map(); - const userAgent = navigator.userAgent || ""; - const platform = navigator.platform || ""; - const maxTouchPoints = navigator.maxTouchPoints || 1; - const isAndroid = /Android/.test(userAgent); - const isIOS = /\b(iPad|iPhone|iPod)(?=;)/.test(userAgent) || platform === "MacIntel" && maxTouchPoints > 1; - (function () { - if (isIOS || isAndroid) { - compatParams.set("maxCanvasPixels", 5242880); - } - })(); - (function () { - if (isAndroid) { - compatParams.set("useSystemFonts", false); - } - })(); -} -const OptionKind = { - BROWSER: 0x01, - VIEWER: 0x02, - API: 0x04, - WORKER: 0x08, - EVENT_DISPATCH: 0x10, - PREFERENCE: 0x80 -}; -const Type = { - BOOLEAN: 0x01, - NUMBER: 0x02, - OBJECT: 0x04, - STRING: 0x08, - UNDEFINED: 0x10 -}; -const defaultOptions = { - allowedGlobalEvents: { - value: null, - kind: OptionKind.BROWSER - }, - canvasMaxAreaInBytes: { - value: -1, - kind: OptionKind.BROWSER + OptionKind.API - }, - isInAutomation: { - value: false, - kind: OptionKind.BROWSER - }, - localeProperties: { - value: { - lang: navigator.language || "en-US" - }, - kind: OptionKind.BROWSER - }, - nimbusDataStr: { - value: "", - kind: OptionKind.BROWSER - }, - supportsCaretBrowsingMode: { - value: false, - kind: OptionKind.BROWSER - }, - supportsDocumentFonts: { - value: true, - kind: OptionKind.BROWSER - }, - supportsIntegratedFind: { - value: false, - kind: OptionKind.BROWSER - }, - supportsMouseWheelZoomCtrlKey: { - value: true, - kind: OptionKind.BROWSER - }, - supportsMouseWheelZoomMetaKey: { - value: true, - kind: OptionKind.BROWSER - }, - supportsPinchToZoom: { - value: true, - kind: OptionKind.BROWSER - }, - toolbarDensity: { - value: 0, - kind: OptionKind.BROWSER + OptionKind.EVENT_DISPATCH - }, - altTextLearnMoreUrl: { - value: "", - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - annotationEditorMode: { - value: 0, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - annotationMode: { - value: 2, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - cursorToolOnLoad: { - value: 0, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - debuggerSrc: { - value: "./debugger.mjs", - kind: OptionKind.VIEWER - }, - defaultZoomDelay: { - value: 400, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - defaultZoomValue: { - value: "", - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - disableHistory: { - value: false, - kind: OptionKind.VIEWER - }, - disablePageLabels: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enableAltText: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enableAltTextModelDownload: { - value: true, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE + OptionKind.EVENT_DISPATCH - }, - enableGuessAltText: { - value: true, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE + OptionKind.EVENT_DISPATCH - }, - enableHighlightFloatingButton: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enableNewAltTextWhenAddingImage: { - value: true, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enablePermissions: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enablePrintAutoRotate: { - value: true, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enableScripting: { - value: true, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enableUpdatedAddImage: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - externalLinkRel: { - value: "noopener noreferrer nofollow", - kind: OptionKind.VIEWER - }, - externalLinkTarget: { - value: 0, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - highlightEditorColors: { - value: "yellow=#FFFF98,green=#53FFBC,blue=#80EBFF,pink=#FFCBE6,red=#FF4F5F", - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - historyUpdateUrl: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - ignoreDestinationZoom: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - imageResourcesPath: { - value: "./images/", - kind: OptionKind.VIEWER - }, - maxCanvasPixels: { - value: 2 ** 25, - kind: OptionKind.VIEWER - }, - forcePageColors: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - pageColorsBackground: { - value: "Canvas", - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - pageColorsForeground: { - value: "CanvasText", - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - pdfBugEnabled: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - printResolution: { - value: 150, - kind: OptionKind.VIEWER - }, - sidebarViewOnLoad: { - value: -1, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - scrollModeOnLoad: { - value: -1, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - spreadModeOnLoad: { - value: -1, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - textLayerMode: { - value: 1, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - viewOnLoad: { - value: 0, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - cMapPacked: { - value: true, - kind: OptionKind.API - }, - cMapUrl: { - value: "../web/cmaps/", - kind: OptionKind.API - }, - disableAutoFetch: { - value: false, - kind: OptionKind.API + OptionKind.PREFERENCE - }, - disableFontFace: { - value: false, - kind: OptionKind.API + OptionKind.PREFERENCE - }, - disableRange: { - value: false, - kind: OptionKind.API + OptionKind.PREFERENCE - }, - disableStream: { - value: false, - kind: OptionKind.API + OptionKind.PREFERENCE - }, - docBaseUrl: { - value: "", - kind: OptionKind.API - }, - enableHWA: { - value: true, - kind: OptionKind.API + OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enableXfa: { - value: true, - kind: OptionKind.API + OptionKind.PREFERENCE - }, - fontExtraProperties: { - value: false, - kind: OptionKind.API - }, - isEvalSupported: { - value: true, - kind: OptionKind.API - }, - isOffscreenCanvasSupported: { - value: true, - kind: OptionKind.API - }, - maxImageSize: { - value: -1, - kind: OptionKind.API - }, - pdfBug: { - value: false, - kind: OptionKind.API - }, - standardFontDataUrl: { - value: "../web/standard_fonts/", - kind: OptionKind.API - }, - useSystemFonts: { - value: undefined, - kind: OptionKind.API, - type: Type.BOOLEAN + Type.UNDEFINED - }, - verbosity: { - value: 1, - kind: OptionKind.API - }, - workerPort: { - value: null, - kind: OptionKind.WORKER - }, - workerSrc: { - value: "../build/pdf.worker.mjs", - kind: OptionKind.WORKER - } -}; -{ - defaultOptions.defaultUrl = { - value: "compressed.tracemonkey-pldi-09.pdf", - kind: OptionKind.VIEWER - }; - defaultOptions.sandboxBundleSrc = { - value: "../build/pdf.sandbox.mjs", - kind: OptionKind.VIEWER - }; - defaultOptions.viewerCssTheme = { - value: 0, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }; - defaultOptions.enableFakeMLManager = { - value: true, - kind: OptionKind.VIEWER - }; -} -{ - defaultOptions.disablePreferences = { - value: false, - kind: OptionKind.VIEWER - }; -} -class AppOptions { - static eventBus; - static #opts = new Map(); - static { - for (const name in defaultOptions) { - this.#opts.set(name, defaultOptions[name].value); - } - for (const [name, value] of compatParams) { - this.#opts.set(name, value); - } - this._hasInvokedSet = false; - this._checkDisablePreferences = () => { - if (this.get("disablePreferences")) { - return true; - } - if (this._hasInvokedSet) { - console.warn("The Preferences may override manually set AppOptions; " + 'please use the "disablePreferences"-option to prevent that.'); - } - return false; - }; - } - static get(name) { - return this.#opts.get(name); - } - static getAll(kind = null, defaultOnly = false) { - const options = Object.create(null); - for (const name in defaultOptions) { - const defaultOpt = defaultOptions[name]; - if (kind && !(kind & defaultOpt.kind)) { - continue; - } - options[name] = !defaultOnly ? this.#opts.get(name) : defaultOpt.value; - } - return options; - } - static set(name, value) { - this.setAll({ - [name]: value - }); - } - static setAll(options, prefs = false) { - this._hasInvokedSet ||= true; - let events; - for (const name in options) { - const defaultOpt = defaultOptions[name], - userOpt = options[name]; - if (!defaultOpt || !(typeof userOpt === typeof defaultOpt.value || Type[(typeof userOpt).toUpperCase()] & defaultOpt.type)) { - continue; - } - const { - kind - } = defaultOpt; - if (prefs && !(kind & OptionKind.BROWSER || kind & OptionKind.PREFERENCE)) { - continue; - } - if (this.eventBus && kind & OptionKind.EVENT_DISPATCH) { - (events ||= new Map()).set(name, userOpt); - } - this.#opts.set(name, userOpt); - } - if (events) { - for (const [name, value] of events) { - this.eventBus.dispatch(name.toLowerCase(), { - source: this, - value - }); - } - } - } -} - -;// ./web/draw_layer_builder.js - -class DrawLayerBuilder { - #drawLayer = null; - constructor(options) { - this.pageIndex = options.pageIndex; - } - async render(intent = "display") { - if (intent !== "display" || this.#drawLayer || this._cancelled) { - return; - } - this.#drawLayer = new DrawLayer({ - pageIndex: this.pageIndex - }); - } - cancel() { - this._cancelled = true; - if (!this.#drawLayer) { - return; - } - this.#drawLayer.destroy(); - this.#drawLayer = null; - } - setParent(parent) { - this.#drawLayer?.setParent(parent); - } - getDrawLayer() { - return this.#drawLayer; - } -} - -;// ./web/struct_tree_layer_builder.js - -const PDF_ROLE_TO_HTML_ROLE = { - Document: null, - DocumentFragment: null, - Part: "group", - Sect: "group", - Div: "group", - Aside: "note", - NonStruct: "none", - P: null, - H: "heading", - Title: null, - FENote: "note", - Sub: "group", - Lbl: null, - Span: null, - Em: null, - Strong: null, - Link: "link", - Annot: "note", - Form: "form", - Ruby: null, - RB: null, - RT: null, - RP: null, - Warichu: null, - WT: null, - WP: null, - L: "list", - LI: "listitem", - LBody: null, - Table: "table", - TR: "row", - TH: "columnheader", - TD: "cell", - THead: "columnheader", - TBody: null, - TFoot: null, - Caption: null, - Figure: "figure", - Formula: null, - Artifact: null -}; -const HEADING_PATTERN = /^H(\d+)$/; -class StructTreeLayerBuilder { - #promise; - #treeDom = null; - #treePromise; - #elementAttributes = new Map(); - #rawDims; - #elementsToAddToTextLayer = null; - constructor(pdfPage, rawDims) { - this.#promise = pdfPage.getStructTree(); - this.#rawDims = rawDims; - } - async render() { - if (this.#treePromise) { - return this.#treePromise; - } - const { - promise, - resolve, - reject - } = Promise.withResolvers(); - this.#treePromise = promise; - try { - this.#treeDom = this.#walk(await this.#promise); - } catch (ex) { - reject(ex); - } - this.#promise = null; - this.#treeDom?.classList.add("structTree"); - resolve(this.#treeDom); - return promise; - } - async getAriaAttributes(annotationId) { - try { - await this.render(); - return this.#elementAttributes.get(annotationId); - } catch {} - return null; - } - hide() { - if (this.#treeDom && !this.#treeDom.hidden) { - this.#treeDom.hidden = true; - } - } - show() { - if (this.#treeDom?.hidden) { - this.#treeDom.hidden = false; - } - } - #setAttributes(structElement, htmlElement) { - const { - alt, - id, - lang - } = structElement; - if (alt !== undefined) { - let added = false; - const label = removeNullCharacters(alt); - for (const child of structElement.children) { - if (child.type === "annotation") { - let attrs = this.#elementAttributes.get(child.id); - if (!attrs) { - attrs = new Map(); - this.#elementAttributes.set(child.id, attrs); - } - attrs.set("aria-label", label); - added = true; - } - } - if (!added) { - htmlElement.setAttribute("aria-label", label); - } - } - if (id !== undefined) { - htmlElement.setAttribute("aria-owns", id); - } - if (lang !== undefined) { - htmlElement.setAttribute("lang", removeNullCharacters(lang, true)); - } - } - #addImageInTextLayer(node, element) { - const { - alt, - bbox, - children - } = node; - const child = children?.[0]; - if (!this.#rawDims || !alt || !bbox || child?.type !== "content") { - return false; - } - const { - id - } = child; - if (!id) { - return false; - } - element.setAttribute("aria-owns", id); - const img = document.createElement("span"); - (this.#elementsToAddToTextLayer ||= new Map()).set(id, img); - img.setAttribute("role", "img"); - img.setAttribute("aria-label", removeNullCharacters(alt)); - const { - pageHeight, - pageX, - pageY - } = this.#rawDims; - const calc = "calc(var(--scale-factor)*"; - const { - style - } = img; - style.width = `${calc}${bbox[2] - bbox[0]}px)`; - style.height = `${calc}${bbox[3] - bbox[1]}px)`; - style.left = `${calc}${bbox[0] - pageX}px)`; - style.top = `${calc}${pageHeight - bbox[3] + pageY}px)`; - return true; - } - addElementsToTextLayer() { - if (!this.#elementsToAddToTextLayer) { - return; - } - for (const [id, img] of this.#elementsToAddToTextLayer) { - document.getElementById(id)?.append(img); - } - this.#elementsToAddToTextLayer.clear(); - this.#elementsToAddToTextLayer = null; - } - #walk(node) { - if (!node) { - return null; - } - const element = document.createElement("span"); - if ("role" in node) { - const { - role - } = node; - const match = role.match(HEADING_PATTERN); - if (match) { - element.setAttribute("role", "heading"); - element.setAttribute("aria-level", match[1]); - } else if (PDF_ROLE_TO_HTML_ROLE[role]) { - element.setAttribute("role", PDF_ROLE_TO_HTML_ROLE[role]); - } - if (role === "Figure" && this.#addImageInTextLayer(node, element)) { - return element; - } - } - this.#setAttributes(node, element); - if (node.children) { - if (node.children.length === 1 && "id" in node.children[0]) { - this.#setAttributes(node.children[0], element); - } else { - for (const kid of node.children) { - element.append(this.#walk(kid)); - } - } - } - return element; - } -} - -;// ./web/text_accessibility.js - -class TextAccessibilityManager { - #enabled = false; - #textChildren = null; - #textNodes = new Map(); - #waitingElements = new Map(); - setTextMapping(textDivs) { - this.#textChildren = textDivs; - } - static #compareElementPositions(e1, e2) { - const rect1 = e1.getBoundingClientRect(); - const rect2 = e2.getBoundingClientRect(); - if (rect1.width === 0 && rect1.height === 0) { - return +1; - } - if (rect2.width === 0 && rect2.height === 0) { - return -1; - } - const top1 = rect1.y; - const bot1 = rect1.y + rect1.height; - const mid1 = rect1.y + rect1.height / 2; - const top2 = rect2.y; - const bot2 = rect2.y + rect2.height; - const mid2 = rect2.y + rect2.height / 2; - if (mid1 <= top2 && mid2 >= bot1) { - return -1; - } - if (mid2 <= top1 && mid1 >= bot2) { - return +1; - } - const centerX1 = rect1.x + rect1.width / 2; - const centerX2 = rect2.x + rect2.width / 2; - return centerX1 - centerX2; - } - enable() { - if (this.#enabled) { - throw new Error("TextAccessibilityManager is already enabled."); - } - if (!this.#textChildren) { - throw new Error("Text divs and strings have not been set."); - } - this.#enabled = true; - this.#textChildren = this.#textChildren.slice(); - this.#textChildren.sort(TextAccessibilityManager.#compareElementPositions); - if (this.#textNodes.size > 0) { - const textChildren = this.#textChildren; - for (const [id, nodeIndex] of this.#textNodes) { - const element = document.getElementById(id); - if (!element) { - this.#textNodes.delete(id); - continue; - } - this.#addIdToAriaOwns(id, textChildren[nodeIndex]); - } - } - for (const [element, isRemovable] of this.#waitingElements) { - this.addPointerInTextLayer(element, isRemovable); - } - this.#waitingElements.clear(); - } - disable() { - if (!this.#enabled) { - return; - } - this.#waitingElements.clear(); - this.#textChildren = null; - this.#enabled = false; - } - removePointerInTextLayer(element) { - if (!this.#enabled) { - this.#waitingElements.delete(element); - return; - } - const children = this.#textChildren; - if (!children || children.length === 0) { - return; - } - const { - id - } = element; - const nodeIndex = this.#textNodes.get(id); - if (nodeIndex === undefined) { - return; - } - const node = children[nodeIndex]; - this.#textNodes.delete(id); - let owns = node.getAttribute("aria-owns"); - if (owns?.includes(id)) { - owns = owns.split(" ").filter(x => x !== id).join(" "); - if (owns) { - node.setAttribute("aria-owns", owns); - } else { - node.removeAttribute("aria-owns"); - node.setAttribute("role", "presentation"); - } - } - } - #addIdToAriaOwns(id, node) { - const owns = node.getAttribute("aria-owns"); - if (!owns?.includes(id)) { - node.setAttribute("aria-owns", owns ? `${owns} ${id}` : id); - } - node.removeAttribute("role"); - } - addPointerInTextLayer(element, isRemovable) { - const { - id - } = element; - if (!id) { - return null; - } - if (!this.#enabled) { - this.#waitingElements.set(element, isRemovable); - return null; - } - if (isRemovable) { - this.removePointerInTextLayer(element); - } - const children = this.#textChildren; - if (!children || children.length === 0) { - return null; - } - const index = binarySearchFirstItem(children, node => TextAccessibilityManager.#compareElementPositions(element, node) < 0); - const nodeIndex = Math.max(0, index - 1); - const child = children[nodeIndex]; - this.#addIdToAriaOwns(id, child); - this.#textNodes.set(id, nodeIndex); - const parent = child.parentNode; - return parent?.classList.contains("markedContent") ? parent.id : null; - } - moveElementInDOM(container, element, contentElement, isRemovable) { - const id = this.addPointerInTextLayer(contentElement, isRemovable); - if (!container.hasChildNodes()) { - container.append(element); - return id; - } - const children = Array.from(container.childNodes).filter(node => node !== element); - if (children.length === 0) { - return id; - } - const elementToCompare = contentElement || element; - const index = binarySearchFirstItem(children, node => TextAccessibilityManager.#compareElementPositions(elementToCompare, node) < 0); - if (index === 0) { - children[0].before(element); - } else { - children[index - 1].after(element); - } - return id; - } -} - -;// ./web/text_highlighter.js -class TextHighlighter { - #eventAbortController = null; - constructor({ - findController, - eventBus, - pageIndex - }) { - this.findController = findController; - this.matches = []; - this.eventBus = eventBus; - this.pageIdx = pageIndex; - this.textDivs = null; - this.textContentItemsStr = null; - this.enabled = false; - } - setTextMapping(divs, texts) { - this.textDivs = divs; - this.textContentItemsStr = texts; - } - enable() { - if (!this.textDivs || !this.textContentItemsStr) { - throw new Error("Text divs and strings have not been set."); - } - if (this.enabled) { - throw new Error("TextHighlighter is already enabled."); - } - this.enabled = true; - if (!this.#eventAbortController) { - this.#eventAbortController = new AbortController(); - this.eventBus._on("updatetextlayermatches", evt => { - if (evt.pageIndex === this.pageIdx || evt.pageIndex === -1) { - this._updateMatches(); - } - }, { - signal: this.#eventAbortController.signal - }); - } - this._updateMatches(); - } - disable() { - if (!this.enabled) { - return; - } - this.enabled = false; - this.#eventAbortController?.abort(); - this.#eventAbortController = null; - this._updateMatches(true); - } - _convertMatches(matches, matchesLength) { - if (!matches) { - return []; - } - const { - textContentItemsStr - } = this; - let i = 0, - iIndex = 0; - const end = textContentItemsStr.length - 1; - const result = []; - for (let m = 0, mm = matches.length; m < mm; m++) { - let matchIdx = matches[m]; - while (i !== end && matchIdx >= iIndex + textContentItemsStr[i].length) { - iIndex += textContentItemsStr[i].length; - i++; - } - if (i === textContentItemsStr.length) { - console.error("Could not find a matching mapping"); - } - const match = { - begin: { - divIdx: i, - offset: matchIdx - iIndex - } - }; - matchIdx += matchesLength[m]; - while (i !== end && matchIdx > iIndex + textContentItemsStr[i].length) { - iIndex += textContentItemsStr[i].length; - i++; - } - match.end = { - divIdx: i, - offset: matchIdx - iIndex - }; - result.push(match); - } - return result; - } - _renderMatches(matches) { - if (matches.length === 0) { - return; - } - const { - findController, - pageIdx - } = this; - const { - textContentItemsStr, - textDivs - } = this; - const isSelectedPage = pageIdx === findController.selected.pageIdx; - const selectedMatchIdx = findController.selected.matchIdx; - const highlightAll = findController.state.highlightAll; - let prevEnd = null; - const infinity = { - divIdx: -1, - offset: undefined - }; - function beginText(begin, className) { - const divIdx = begin.divIdx; - textDivs[divIdx].textContent = ""; - return appendTextToDiv(divIdx, 0, begin.offset, className); - } - function appendTextToDiv(divIdx, fromOffset, toOffset, className) { - let div = textDivs[divIdx]; - if (div.nodeType === Node.TEXT_NODE) { - const span = document.createElement("span"); - div.before(span); - span.append(div); - textDivs[divIdx] = span; - div = span; - } - const content = textContentItemsStr[divIdx].substring(fromOffset, toOffset); - const node = document.createTextNode(content); - if (className) { - const span = document.createElement("span"); - span.className = `${className} appended`; - span.append(node); - div.append(span); - if (className.includes("selected")) { - const { - left - } = span.getClientRects()[0]; - const parentLeft = div.getBoundingClientRect().left; - return left - parentLeft; - } - return 0; - } - div.append(node); - return 0; - } - let i0 = selectedMatchIdx, - i1 = i0 + 1; - if (highlightAll) { - i0 = 0; - i1 = matches.length; - } else if (!isSelectedPage) { - return; - } - let lastDivIdx = -1; - let lastOffset = -1; - for (let i = i0; i < i1; i++) { - const match = matches[i]; - const begin = match.begin; - if (begin.divIdx === lastDivIdx && begin.offset === lastOffset) { - continue; - } - lastDivIdx = begin.divIdx; - lastOffset = begin.offset; - const end = match.end; - const isSelected = isSelectedPage && i === selectedMatchIdx; - const highlightSuffix = isSelected ? " selected" : ""; - let selectedLeft = 0; - if (!prevEnd || begin.divIdx !== prevEnd.divIdx) { - if (prevEnd !== null) { - appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset); - } - beginText(begin); - } else { - appendTextToDiv(prevEnd.divIdx, prevEnd.offset, begin.offset); - } - if (begin.divIdx === end.divIdx) { - selectedLeft = appendTextToDiv(begin.divIdx, begin.offset, end.offset, "highlight" + highlightSuffix); - } else { - selectedLeft = appendTextToDiv(begin.divIdx, begin.offset, infinity.offset, "highlight begin" + highlightSuffix); - for (let n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) { - textDivs[n0].className = "highlight middle" + highlightSuffix; - } - beginText(end, "highlight end" + highlightSuffix); - } - prevEnd = end; - if (isSelected) { - findController.scrollMatchIntoView({ - element: textDivs[begin.divIdx], - selectedLeft, - pageIndex: pageIdx, - matchIndex: selectedMatchIdx - }); - } - } - if (prevEnd) { - appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset); - } - } - _updateMatches(reset = false) { - if (!this.enabled && !reset) { - return; - } - const { - findController, - matches, - pageIdx - } = this; - const { - textContentItemsStr, - textDivs - } = this; - let clearedUntilDivIdx = -1; - for (const match of matches) { - const begin = Math.max(clearedUntilDivIdx, match.begin.divIdx); - for (let n = begin, end = match.end.divIdx; n <= end; n++) { - const div = textDivs[n]; - div.textContent = textContentItemsStr[n]; - div.className = ""; - } - clearedUntilDivIdx = match.end.divIdx + 1; - } - if (!findController?.highlightMatches || reset) { - return; - } - const pageMatches = findController.pageMatches[pageIdx] || null; - const pageMatchesLength = findController.pageMatchesLength[pageIdx] || null; - this.matches = this._convertMatches(pageMatches, pageMatchesLength); - this._renderMatches(this.matches); - } -} - -;// ./web/text_layer_builder.js - - -class TextLayerBuilder { - #enablePermissions = false; - #onAppend = null; - #renderingDone = false; - #textLayer = null; - static #textLayers = new Map(); - static #selectionChangeAbortController = null; - constructor({ - pdfPage, - highlighter = null, - accessibilityManager = null, - enablePermissions = false, - onAppend = null - }) { - this.pdfPage = pdfPage; - this.highlighter = highlighter; - this.accessibilityManager = accessibilityManager; - this.#enablePermissions = enablePermissions === true; - this.#onAppend = onAppend; - this.div = document.createElement("div"); - this.div.tabIndex = 0; - this.div.className = "textLayer"; - } - async render(viewport, textContentParams = null) { - if (this.#renderingDone && this.#textLayer) { - this.#textLayer.update({ - viewport, - onBefore: this.hide.bind(this) - }); - this.show(); - return; - } - this.cancel(); - this.#textLayer = new TextLayer({ - textContentSource: this.pdfPage.streamTextContent(textContentParams || { - includeMarkedContent: true, - disableNormalization: true - }), - container: this.div, - viewport - }); - const { - textDivs, - textContentItemsStr - } = this.#textLayer; - this.highlighter?.setTextMapping(textDivs, textContentItemsStr); - this.accessibilityManager?.setTextMapping(textDivs); - await this.#textLayer.render(); - this.#renderingDone = true; - const endOfContent = document.createElement("div"); - endOfContent.className = "endOfContent"; - this.div.append(endOfContent); - this.#bindMouse(endOfContent); - this.#onAppend?.(this.div); - this.highlighter?.enable(); - this.accessibilityManager?.enable(); - } - hide() { - if (!this.div.hidden && this.#renderingDone) { - this.highlighter?.disable(); - this.div.hidden = true; - } - } - show() { - if (this.div.hidden && this.#renderingDone) { - this.div.hidden = false; - this.highlighter?.enable(); - } - } - cancel() { - this.#textLayer?.cancel(); - this.#textLayer = null; - this.highlighter?.disable(); - this.accessibilityManager?.disable(); - TextLayerBuilder.#removeGlobalSelectionListener(this.div); - } - #bindMouse(end) { - const { - div - } = this; - div.addEventListener("mousedown", () => { - div.classList.add("selecting"); - }); - div.addEventListener("copy", event => { - if (!this.#enablePermissions) { - const selection = document.getSelection(); - event.clipboardData.setData("text/plain", removeNullCharacters(normalizeUnicode(selection.toString()))); - } - stopEvent(event); - }); - TextLayerBuilder.#textLayers.set(div, end); - TextLayerBuilder.#enableGlobalSelectionListener(); - } - static #removeGlobalSelectionListener(textLayerDiv) { - this.#textLayers.delete(textLayerDiv); - if (this.#textLayers.size === 0) { - this.#selectionChangeAbortController?.abort(); - this.#selectionChangeAbortController = null; - } - } - static #enableGlobalSelectionListener() { - if (this.#selectionChangeAbortController) { - return; - } - this.#selectionChangeAbortController = new AbortController(); - const { - signal - } = this.#selectionChangeAbortController; - const reset = (end, textLayer) => { - textLayer.append(end); - end.style.width = ""; - end.style.height = ""; - textLayer.classList.remove("selecting"); - }; - let isPointerDown = false; - document.addEventListener("pointerdown", () => { - isPointerDown = true; - }, { - signal - }); - document.addEventListener("pointerup", () => { - isPointerDown = false; - this.#textLayers.forEach(reset); - }, { - signal - }); - window.addEventListener("blur", () => { - isPointerDown = false; - this.#textLayers.forEach(reset); - }, { - signal - }); - document.addEventListener("keyup", () => { - if (!isPointerDown) { - this.#textLayers.forEach(reset); - } - }, { - signal - }); - var isFirefox, prevRange; - document.addEventListener("selectionchange", () => { - const selection = document.getSelection(); - if (selection.rangeCount === 0) { - this.#textLayers.forEach(reset); - return; - } - const activeTextLayers = new Set(); - for (let i = 0; i < selection.rangeCount; i++) { - const range = selection.getRangeAt(i); - for (const textLayerDiv of this.#textLayers.keys()) { - if (!activeTextLayers.has(textLayerDiv) && range.intersectsNode(textLayerDiv)) { - activeTextLayers.add(textLayerDiv); - } - } - } - for (const [textLayerDiv, endDiv] of this.#textLayers) { - if (activeTextLayers.has(textLayerDiv)) { - textLayerDiv.classList.add("selecting"); - } else { - reset(endDiv, textLayerDiv); - } - } - isFirefox ??= getComputedStyle(this.#textLayers.values().next().value).getPropertyValue("-moz-user-select") === "none"; - if (isFirefox) { - return; - } - const range = selection.getRangeAt(0); - const modifyStart = prevRange && (range.compareBoundaryPoints(Range.END_TO_END, prevRange) === 0 || range.compareBoundaryPoints(Range.START_TO_END, prevRange) === 0); - let anchor = modifyStart ? range.startContainer : range.endContainer; - if (anchor.nodeType === Node.TEXT_NODE) { - anchor = anchor.parentNode; - } - const parentTextLayer = anchor.parentElement?.closest(".textLayer"); - const endDiv = this.#textLayers.get(parentTextLayer); - if (endDiv) { - endDiv.style.width = parentTextLayer.style.width; - endDiv.style.height = parentTextLayer.style.height; - anchor.parentElement.insertBefore(endDiv, modifyStart ? anchor : anchor.nextSibling); - } - prevRange = range.cloneRange(); - }, { - signal - }); - } -} - -;// ./web/xfa_layer_builder.js - -class XfaLayerBuilder { - constructor({ - pdfPage, - annotationStorage = null, - linkService, - xfaHtml = null - }) { - this.pdfPage = pdfPage; - this.annotationStorage = annotationStorage; - this.linkService = linkService; - this.xfaHtml = xfaHtml; - this.div = null; - this._cancelled = false; - } - async render(viewport, intent = "display") { - if (intent === "print") { - const parameters = { - viewport: viewport.clone({ - dontFlip: true - }), - div: this.div, - xfaHtml: this.xfaHtml, - annotationStorage: this.annotationStorage, - linkService: this.linkService, - intent - }; - this.div = document.createElement("div"); - parameters.div = this.div; - return XfaLayer.render(parameters); - } - const xfaHtml = await this.pdfPage.getXfa(); - if (this._cancelled || !xfaHtml) { - return { - textDivs: [] - }; - } - const parameters = { - viewport: viewport.clone({ - dontFlip: true - }), - div: this.div, - xfaHtml, - annotationStorage: this.annotationStorage, - linkService: this.linkService, - intent - }; - if (this.div) { - return XfaLayer.update(parameters); - } - this.div = document.createElement("div"); - parameters.div = this.div; - return XfaLayer.render(parameters); - } - cancel() { - this._cancelled = true; - } - hide() { - if (!this.div) { - return; - } - this.div.hidden = true; - } -} - -;// ./web/pdf_page_view.js - - - - - - - - - - - - - -const DEFAULT_LAYER_PROPERTIES = { - annotationEditorUIManager: null, - annotationStorage: null, - downloadManager: null, - enableScripting: false, - fieldObjectsPromise: null, - findController: null, - hasJSActionsPromise: null, - get linkService() { - return new SimpleLinkService(); - } -}; -const LAYERS_ORDER = new Map([["canvasWrapper", 0], ["textLayer", 1], ["annotationLayer", 2], ["annotationEditorLayer", 3], ["xfaLayer", 3]]); -class PDFPageView { - #annotationMode = AnnotationMode.ENABLE_FORMS; - #canvasWrapper = null; - #enableHWA = false; - #hasRestrictedScaling = false; - #isEditing = false; - #layerProperties = null; - #loadingId = null; - #originalViewport = null; - #previousRotation = null; - #scaleRoundX = 1; - #scaleRoundY = 1; - #renderError = null; - #renderingState = RenderingStates.INITIAL; - #textLayerMode = TextLayerMode.ENABLE; - #useThumbnailCanvas = { - directDrawing: true, - initialOptionalContent: true, - regularAnnotations: true - }; - #layers = [null, null, null, null]; - constructor(options) { - const container = options.container; - const defaultViewport = options.defaultViewport; - this.id = options.id; - this.renderingId = "page" + this.id; - this.#layerProperties = options.layerProperties || DEFAULT_LAYER_PROPERTIES; - this.pdfPage = null; - this.pageLabel = null; - this.rotation = 0; - this.scale = options.scale || DEFAULT_SCALE; - this.viewport = defaultViewport; - this.pdfPageRotate = defaultViewport.rotation; - this._optionalContentConfigPromise = options.optionalContentConfigPromise || null; - this.#textLayerMode = options.textLayerMode ?? TextLayerMode.ENABLE; - this.#annotationMode = options.annotationMode ?? AnnotationMode.ENABLE_FORMS; - this.imageResourcesPath = options.imageResourcesPath || ""; - this.maxCanvasPixels = options.maxCanvasPixels ?? AppOptions.get("maxCanvasPixels"); - this.pageColors = options.pageColors || null; - this.#enableHWA = options.enableHWA || false; - this.eventBus = options.eventBus; - this.renderingQueue = options.renderingQueue; - this.l10n = options.l10n; - this.l10n ||= new genericl10n_GenericL10n(); - this.renderTask = null; - this.resume = null; - this._isStandalone = !this.renderingQueue?.hasViewer(); - this._container = container; - this._annotationCanvasMap = null; - this.annotationLayer = null; - this.annotationEditorLayer = null; - this.textLayer = null; - this.xfaLayer = null; - this.structTreeLayer = null; - this.drawLayer = null; - const div = document.createElement("div"); - div.className = "page"; - div.setAttribute("data-page-number", this.id); - div.setAttribute("role", "region"); - div.setAttribute("data-l10n-id", "pdfjs-page-landmark"); - div.setAttribute("data-l10n-args", JSON.stringify({ - page: this.id - })); - this.div = div; - this.#setDimensions(); - container?.append(div); - if (this._isStandalone) { - container?.style.setProperty("--scale-factor", this.scale * PixelsPerInch.PDF_TO_CSS_UNITS); - if (this.pageColors?.background) { - container?.style.setProperty("--page-bg-color", this.pageColors.background); - } - const { - optionalContentConfigPromise - } = options; - if (optionalContentConfigPromise) { - optionalContentConfigPromise.then(optionalContentConfig => { - if (optionalContentConfigPromise !== this._optionalContentConfigPromise) { - return; - } - this.#useThumbnailCanvas.initialOptionalContent = optionalContentConfig.hasInitialVisibility; - }); - } - if (!options.l10n) { - this.l10n.translate(this.div); - } - } - } - #addLayer(div, name) { - const pos = LAYERS_ORDER.get(name); - const oldDiv = this.#layers[pos]; - this.#layers[pos] = div; - if (oldDiv) { - oldDiv.replaceWith(div); - return; - } - for (let i = pos - 1; i >= 0; i--) { - const layer = this.#layers[i]; - if (layer) { - layer.after(div); - return; - } - } - this.div.prepend(div); - } - get renderingState() { - return this.#renderingState; - } - set renderingState(state) { - if (state === this.#renderingState) { - return; - } - this.#renderingState = state; - if (this.#loadingId) { - clearTimeout(this.#loadingId); - this.#loadingId = null; - } - switch (state) { - case RenderingStates.PAUSED: - this.div.classList.remove("loading"); - break; - case RenderingStates.RUNNING: - this.div.classList.add("loadingIcon"); - this.#loadingId = setTimeout(() => { - this.div.classList.add("loading"); - this.#loadingId = null; - }, 0); - break; - case RenderingStates.INITIAL: - case RenderingStates.FINISHED: - this.div.classList.remove("loadingIcon", "loading"); - break; - } - } - #setDimensions() { - const { - viewport - } = this; - if (this.pdfPage) { - if (this.#previousRotation === viewport.rotation) { - return; - } - this.#previousRotation = viewport.rotation; - } - setLayerDimensions(this.div, viewport, true, false); - } - setPdfPage(pdfPage) { - if (this._isStandalone && (this.pageColors?.foreground === "CanvasText" || this.pageColors?.background === "Canvas")) { - this._container?.style.setProperty("--hcm-highlight-filter", pdfPage.filterFactory.addHighlightHCMFilter("highlight", "CanvasText", "Canvas", "HighlightText", "Highlight")); - this._container?.style.setProperty("--hcm-highlight-selected-filter", pdfPage.filterFactory.addHighlightHCMFilter("highlight_selected", "CanvasText", "Canvas", "HighlightText", "Highlight")); - } - this.pdfPage = pdfPage; - this.pdfPageRotate = pdfPage.rotate; - const totalRotation = (this.rotation + this.pdfPageRotate) % 360; - this.viewport = pdfPage.getViewport({ - scale: this.scale * PixelsPerInch.PDF_TO_CSS_UNITS, - rotation: totalRotation - }); - this.#setDimensions(); - this.reset(); - } - destroy() { - this.reset(); - this.pdfPage?.cleanup(); - } - hasEditableAnnotations() { - return !!this.annotationLayer?.hasEditableAnnotations(); - } - get _textHighlighter() { - return shadow(this, "_textHighlighter", new TextHighlighter({ - pageIndex: this.id - 1, - eventBus: this.eventBus, - findController: this.#layerProperties.findController - })); - } - #dispatchLayerRendered(name, error) { - this.eventBus.dispatch(name, { - source: this, - pageNumber: this.id, - error - }); - } - async #renderAnnotationLayer() { - let error = null; - try { - await this.annotationLayer.render(this.viewport, { - structTreeLayer: this.structTreeLayer - }, "display"); - } catch (ex) { - console.error("#renderAnnotationLayer:", ex); - error = ex; - } finally { - this.#dispatchLayerRendered("annotationlayerrendered", error); - } - } - async #renderAnnotationEditorLayer() { - let error = null; - try { - await this.annotationEditorLayer.render(this.viewport, "display"); - } catch (ex) { - console.error("#renderAnnotationEditorLayer:", ex); - error = ex; - } finally { - this.#dispatchLayerRendered("annotationeditorlayerrendered", error); - } - } - async #renderDrawLayer() { - try { - await this.drawLayer.render("display"); - } catch (ex) { - console.error("#renderDrawLayer:", ex); - } - } - async #renderXfaLayer() { - let error = null; - try { - const result = await this.xfaLayer.render(this.viewport, "display"); - if (result?.textDivs && this._textHighlighter) { - this.#buildXfaTextContentItems(result.textDivs); - } - } catch (ex) { - console.error("#renderXfaLayer:", ex); - error = ex; - } finally { - if (this.xfaLayer?.div) { - this.l10n.pause(); - this.#addLayer(this.xfaLayer.div, "xfaLayer"); - this.l10n.resume(); - } - this.#dispatchLayerRendered("xfalayerrendered", error); - } - } - async #renderTextLayer() { - if (!this.textLayer) { - return; - } - let error = null; - try { - await this.textLayer.render(this.viewport); - } catch (ex) { - if (ex instanceof AbortException) { - return; - } - console.error("#renderTextLayer:", ex); - error = ex; - } - this.#dispatchLayerRendered("textlayerrendered", error); - this.#renderStructTreeLayer(); - } - async #renderStructTreeLayer() { - if (!this.textLayer) { - return; - } - const treeDom = await this.structTreeLayer?.render(); - if (treeDom) { - this.l10n.pause(); - this.structTreeLayer?.addElementsToTextLayer(); - if (this.canvas && treeDom.parentNode !== this.canvas) { - this.canvas.append(treeDom); - } - this.l10n.resume(); - } - this.structTreeLayer?.show(); - } - async #buildXfaTextContentItems(textDivs) { - const text = await this.pdfPage.getTextContent(); - const items = []; - for (const item of text.items) { - items.push(item.str); - } - this._textHighlighter.setTextMapping(textDivs, items); - this._textHighlighter.enable(); - } - #resetCanvas() { - const { - canvas - } = this; - if (!canvas) { - return; - } - canvas.remove(); - canvas.width = canvas.height = 0; - this.canvas = null; - this.#originalViewport = null; - } - reset({ - keepAnnotationLayer = false, - keepAnnotationEditorLayer = false, - keepXfaLayer = false, - keepTextLayer = false, - keepCanvasWrapper = false - } = {}) { - this.cancelRendering({ - keepAnnotationLayer, - keepAnnotationEditorLayer, - keepXfaLayer, - keepTextLayer - }); - this.renderingState = RenderingStates.INITIAL; - const div = this.div; - const childNodes = div.childNodes, - annotationLayerNode = keepAnnotationLayer && this.annotationLayer?.div || null, - annotationEditorLayerNode = keepAnnotationEditorLayer && this.annotationEditorLayer?.div || null, - xfaLayerNode = keepXfaLayer && this.xfaLayer?.div || null, - textLayerNode = keepTextLayer && this.textLayer?.div || null, - canvasWrapperNode = keepCanvasWrapper && this.#canvasWrapper || null; - for (let i = childNodes.length - 1; i >= 0; i--) { - const node = childNodes[i]; - switch (node) { - case annotationLayerNode: - case annotationEditorLayerNode: - case xfaLayerNode: - case textLayerNode: - case canvasWrapperNode: - continue; - } - node.remove(); - const layerIndex = this.#layers.indexOf(node); - if (layerIndex >= 0) { - this.#layers[layerIndex] = null; - } - } - div.removeAttribute("data-loaded"); - if (annotationLayerNode) { - this.annotationLayer.hide(); - } - if (annotationEditorLayerNode) { - this.annotationEditorLayer.hide(); - } - if (xfaLayerNode) { - this.xfaLayer.hide(); - } - if (textLayerNode) { - this.textLayer.hide(); - } - this.structTreeLayer?.hide(); - if (!keepCanvasWrapper && this.#canvasWrapper) { - this.#canvasWrapper = null; - this.#resetCanvas(); - } - } - toggleEditingMode(isEditing) { - if (!this.hasEditableAnnotations()) { - return; - } - this.#isEditing = isEditing; - this.reset({ - keepAnnotationLayer: true, - keepAnnotationEditorLayer: true, - keepXfaLayer: true, - keepTextLayer: true, - keepCanvasWrapper: true - }); - } - update({ - scale = 0, - rotation = null, - optionalContentConfigPromise = null, - drawingDelay = -1 - }) { - this.scale = scale || this.scale; - if (typeof rotation === "number") { - this.rotation = rotation; - } - if (optionalContentConfigPromise instanceof Promise) { - this._optionalContentConfigPromise = optionalContentConfigPromise; - optionalContentConfigPromise.then(optionalContentConfig => { - if (optionalContentConfigPromise !== this._optionalContentConfigPromise) { - return; - } - this.#useThumbnailCanvas.initialOptionalContent = optionalContentConfig.hasInitialVisibility; - }); - } - this.#useThumbnailCanvas.directDrawing = true; - const totalRotation = (this.rotation + this.pdfPageRotate) % 360; - this.viewport = this.viewport.clone({ - scale: this.scale * PixelsPerInch.PDF_TO_CSS_UNITS, - rotation: totalRotation - }); - this.#setDimensions(); - if (this._isStandalone) { - this._container?.style.setProperty("--scale-factor", this.viewport.scale); - } - if (this.canvas) { - let onlyCssZoom = false; - if (this.#hasRestrictedScaling) { - if (this.maxCanvasPixels === 0) { - onlyCssZoom = true; - } else if (this.maxCanvasPixels > 0) { - const { - width, - height - } = this.viewport; - const { - sx, - sy - } = this.outputScale; - onlyCssZoom = (Math.floor(width) * sx | 0) * (Math.floor(height) * sy | 0) > this.maxCanvasPixels; - } - } - const postponeDrawing = drawingDelay >= 0 && drawingDelay < 1000; - if (postponeDrawing || onlyCssZoom) { - if (postponeDrawing && !onlyCssZoom && this.renderingState !== RenderingStates.FINISHED) { - this.cancelRendering({ - keepAnnotationLayer: true, - keepAnnotationEditorLayer: true, - keepXfaLayer: true, - keepTextLayer: true, - cancelExtraDelay: drawingDelay - }); - this.renderingState = RenderingStates.FINISHED; - this.#useThumbnailCanvas.directDrawing = false; - } - this.cssTransform({ - redrawAnnotationLayer: true, - redrawAnnotationEditorLayer: true, - redrawXfaLayer: true, - redrawTextLayer: !postponeDrawing, - hideTextLayer: postponeDrawing - }); - if (postponeDrawing) { - return; - } - this.eventBus.dispatch("pagerendered", { - source: this, - pageNumber: this.id, - cssTransform: true, - timestamp: performance.now(), - error: this.#renderError - }); - return; - } - } - this.cssTransform({}); - this.reset({ - keepAnnotationLayer: true, - keepAnnotationEditorLayer: true, - keepXfaLayer: true, - keepTextLayer: true, - keepCanvasWrapper: true - }); - } - cancelRendering({ - keepAnnotationLayer = false, - keepAnnotationEditorLayer = false, - keepXfaLayer = false, - keepTextLayer = false, - cancelExtraDelay = 0 - } = {}) { - if (this.renderTask) { - this.renderTask.cancel(cancelExtraDelay); - this.renderTask = null; - } - this.resume = null; - if (this.textLayer && (!keepTextLayer || !this.textLayer.div)) { - this.textLayer.cancel(); - this.textLayer = null; - } - if (this.annotationLayer && (!keepAnnotationLayer || !this.annotationLayer.div)) { - this.annotationLayer.cancel(); - this.annotationLayer = null; - this._annotationCanvasMap = null; - } - if (this.structTreeLayer && !this.textLayer) { - this.structTreeLayer = null; - } - if (this.annotationEditorLayer && (!keepAnnotationEditorLayer || !this.annotationEditorLayer.div)) { - if (this.drawLayer) { - this.drawLayer.cancel(); - this.drawLayer = null; - } - this.annotationEditorLayer.cancel(); - this.annotationEditorLayer = null; - } - if (this.xfaLayer && (!keepXfaLayer || !this.xfaLayer.div)) { - this.xfaLayer.cancel(); - this.xfaLayer = null; - this._textHighlighter?.disable(); - } - } - cssTransform({ - redrawAnnotationLayer = false, - redrawAnnotationEditorLayer = false, - redrawXfaLayer = false, - redrawTextLayer = false, - hideTextLayer = false - }) { - const { - canvas - } = this; - if (!canvas) { - return; - } - const originalViewport = this.#originalViewport; - if (this.viewport !== originalViewport) { - const relativeRotation = (360 + this.viewport.rotation - originalViewport.rotation) % 360; - if (relativeRotation === 90 || relativeRotation === 270) { - const { - width, - height - } = this.viewport; - const scaleX = height / width; - const scaleY = width / height; - canvas.style.transform = `rotate(${relativeRotation}deg) scale(${scaleX},${scaleY})`; - } else { - canvas.style.transform = relativeRotation === 0 ? "" : `rotate(${relativeRotation}deg)`; - } - } - if (redrawAnnotationLayer && this.annotationLayer) { - this.#renderAnnotationLayer(); - } - if (redrawAnnotationEditorLayer && this.annotationEditorLayer) { - if (this.drawLayer) { - this.#renderDrawLayer(); - } - this.#renderAnnotationEditorLayer(); - } - if (redrawXfaLayer && this.xfaLayer) { - this.#renderXfaLayer(); - } - if (this.textLayer) { - if (hideTextLayer) { - this.textLayer.hide(); - this.structTreeLayer?.hide(); - } else if (redrawTextLayer) { - this.#renderTextLayer(); - } - } - } - get width() { - return this.viewport.width; - } - get height() { - return this.viewport.height; - } - getPagePoint(x, y) { - return this.viewport.convertToPdfPoint(x, y); - } - async #finishRenderTask(renderTask, error = null) { - if (renderTask === this.renderTask) { - this.renderTask = null; - } - if (error instanceof RenderingCancelledException) { - this.#renderError = null; - return; - } - this.#renderError = error; - this.renderingState = RenderingStates.FINISHED; - this.#useThumbnailCanvas.regularAnnotations = !renderTask.separateAnnots; - this.eventBus.dispatch("pagerendered", { - source: this, - pageNumber: this.id, - cssTransform: false, - timestamp: performance.now(), - error: this.#renderError - }); - if (error) { - throw error; - } - } - async draw() { - if (this.renderingState !== RenderingStates.INITIAL) { - console.error("Must be in new state before drawing"); - this.reset(); - } - const { - div, - l10n, - pageColors, - pdfPage, - viewport - } = this; - if (!pdfPage) { - this.renderingState = RenderingStates.FINISHED; - throw new Error("pdfPage is not loaded"); - } - this.renderingState = RenderingStates.RUNNING; - let canvasWrapper = this.#canvasWrapper; - if (!canvasWrapper) { - canvasWrapper = this.#canvasWrapper = document.createElement("div"); - canvasWrapper.classList.add("canvasWrapper"); - this.#addLayer(canvasWrapper, "canvasWrapper"); - } - if (!this.textLayer && this.#textLayerMode !== TextLayerMode.DISABLE && !pdfPage.isPureXfa) { - this._accessibilityManager ||= new TextAccessibilityManager(); - this.textLayer = new TextLayerBuilder({ - pdfPage, - highlighter: this._textHighlighter, - accessibilityManager: this._accessibilityManager, - enablePermissions: this.#textLayerMode === TextLayerMode.ENABLE_PERMISSIONS, - onAppend: textLayerDiv => { - this.l10n.pause(); - this.#addLayer(textLayerDiv, "textLayer"); - this.l10n.resume(); - } - }); - } - if (!this.annotationLayer && this.#annotationMode !== AnnotationMode.DISABLE) { - const { - annotationStorage, - annotationEditorUIManager, - downloadManager, - enableScripting, - fieldObjectsPromise, - hasJSActionsPromise, - linkService - } = this.#layerProperties; - this._annotationCanvasMap ||= new Map(); - this.annotationLayer = new AnnotationLayerBuilder({ - pdfPage, - annotationStorage, - imageResourcesPath: this.imageResourcesPath, - renderForms: this.#annotationMode === AnnotationMode.ENABLE_FORMS, - linkService, - downloadManager, - enableScripting, - hasJSActionsPromise, - fieldObjectsPromise, - annotationCanvasMap: this._annotationCanvasMap, - accessibilityManager: this._accessibilityManager, - annotationEditorUIManager, - onAppend: annotationLayerDiv => { - this.#addLayer(annotationLayerDiv, "annotationLayer"); - } - }); - } - const renderContinueCallback = cont => { - showCanvas?.(false); - if (this.renderingQueue && !this.renderingQueue.isHighestPriority(this)) { - this.renderingState = RenderingStates.PAUSED; - this.resume = () => { - this.renderingState = RenderingStates.RUNNING; - cont(); - }; - return; - } - cont(); - }; - const { - width, - height - } = viewport; - const canvas = document.createElement("canvas"); - canvas.setAttribute("role", "presentation"); - const hasHCM = !!(pageColors?.background && pageColors?.foreground); - const prevCanvas = this.canvas; - const updateOnFirstShow = !prevCanvas && !hasHCM; - this.canvas = canvas; - this.#originalViewport = viewport; - let showCanvas = isLastShow => { - if (updateOnFirstShow) { - canvasWrapper.prepend(canvas); - showCanvas = null; - return; - } - if (!isLastShow) { - return; - } - if (prevCanvas) { - prevCanvas.replaceWith(canvas); - prevCanvas.width = prevCanvas.height = 0; - } else { - canvasWrapper.prepend(canvas); - } - showCanvas = null; - }; - const ctx = canvas.getContext("2d", { - alpha: false, - willReadFrequently: !this.#enableHWA - }); - const outputScale = this.outputScale = new OutputScale(); - if (this.maxCanvasPixels === 0) { - const invScale = 1 / this.scale; - outputScale.sx *= invScale; - outputScale.sy *= invScale; - this.#hasRestrictedScaling = true; - } else if (this.maxCanvasPixels > 0) { - const pixelsInViewport = width * height; - const maxScale = Math.sqrt(this.maxCanvasPixels / pixelsInViewport); - if (outputScale.sx > maxScale || outputScale.sy > maxScale) { - outputScale.sx = maxScale; - outputScale.sy = maxScale; - this.#hasRestrictedScaling = true; - } else { - this.#hasRestrictedScaling = false; - } - } - const sfx = approximateFraction(outputScale.sx); - const sfy = approximateFraction(outputScale.sy); - const canvasWidth = canvas.width = floorToDivide(calcRound(width * outputScale.sx), sfx[0]); - const canvasHeight = canvas.height = floorToDivide(calcRound(height * outputScale.sy), sfy[0]); - const pageWidth = floorToDivide(calcRound(width), sfx[1]); - const pageHeight = floorToDivide(calcRound(height), sfy[1]); - outputScale.sx = canvasWidth / pageWidth; - outputScale.sy = canvasHeight / pageHeight; - if (this.#scaleRoundX !== sfx[1]) { - div.style.setProperty("--scale-round-x", `${sfx[1]}px`); - this.#scaleRoundX = sfx[1]; - } - if (this.#scaleRoundY !== sfy[1]) { - div.style.setProperty("--scale-round-y", `${sfy[1]}px`); - this.#scaleRoundY = sfy[1]; - } - const transform = outputScale.scaled ? [outputScale.sx, 0, 0, outputScale.sy, 0, 0] : null; - const renderContext = { - canvasContext: ctx, - transform, - viewport, - annotationMode: this.#annotationMode, - optionalContentConfigPromise: this._optionalContentConfigPromise, - annotationCanvasMap: this._annotationCanvasMap, - pageColors, - isEditing: this.#isEditing - }; - const renderTask = this.renderTask = pdfPage.render(renderContext); - renderTask.onContinue = renderContinueCallback; - const resultPromise = renderTask.promise.then(async () => { - showCanvas?.(true); - await this.#finishRenderTask(renderTask); - this.structTreeLayer ||= new StructTreeLayerBuilder(pdfPage, viewport.rawDims); - this.#renderTextLayer(); - if (this.annotationLayer) { - await this.#renderAnnotationLayer(); - } - const { - annotationEditorUIManager - } = this.#layerProperties; - if (!annotationEditorUIManager) { - return; - } - this.drawLayer ||= new DrawLayerBuilder({ - pageIndex: this.id - }); - await this.#renderDrawLayer(); - this.drawLayer.setParent(canvasWrapper); - this.annotationEditorLayer ||= new AnnotationEditorLayerBuilder({ - uiManager: annotationEditorUIManager, - pdfPage, - l10n, - structTreeLayer: this.structTreeLayer, - accessibilityManager: this._accessibilityManager, - annotationLayer: this.annotationLayer?.annotationLayer, - textLayer: this.textLayer, - drawLayer: this.drawLayer.getDrawLayer(), - onAppend: annotationEditorLayerDiv => { - this.#addLayer(annotationEditorLayerDiv, "annotationEditorLayer"); - } - }); - this.#renderAnnotationEditorLayer(); - }, error => { - if (!(error instanceof RenderingCancelledException)) { - showCanvas?.(true); - } else { - prevCanvas?.remove(); - this.#resetCanvas(); - } - return this.#finishRenderTask(renderTask, error); - }); - if (pdfPage.isPureXfa) { - if (!this.xfaLayer) { - const { - annotationStorage, - linkService - } = this.#layerProperties; - this.xfaLayer = new XfaLayerBuilder({ - pdfPage, - annotationStorage, - linkService - }); - } - this.#renderXfaLayer(); - } - div.setAttribute("data-loaded", true); - this.eventBus.dispatch("pagerender", { - source: this, - pageNumber: this.id - }); - return resultPromise; - } - setPageLabel(label) { - this.pageLabel = typeof label === "string" ? label : null; - this.div.setAttribute("data-l10n-args", JSON.stringify({ - page: this.pageLabel ?? this.id - })); - if (this.pageLabel !== null) { - this.div.setAttribute("data-page-label", this.pageLabel); - } else { - this.div.removeAttribute("data-page-label"); - } - } - get thumbnailCanvas() { - const { - directDrawing, - initialOptionalContent, - regularAnnotations - } = this.#useThumbnailCanvas; - return directDrawing && initialOptionalContent && regularAnnotations ? this.canvas : null; - } -} - -;// ./web/generic_scripting.js - -async function docProperties(pdfDocument) { - const url = "", - baseUrl = url.split("#", 1)[0]; - let { - info, - metadata, - contentDispositionFilename, - contentLength - } = await pdfDocument.getMetadata(); - if (!contentLength) { - const { - length - } = await pdfDocument.getDownloadInfo(); - contentLength = length; - } - return { - ...info, - baseURL: baseUrl, - filesize: contentLength, - filename: contentDispositionFilename || getPdfFilenameFromUrl(url), - metadata: metadata?.getRaw(), - authors: metadata?.get("dc:creator"), - numPages: pdfDocument.numPages, - URL: url - }; -} -class GenericScripting { - constructor(sandboxBundleSrc) { - this._ready = new Promise((resolve, reject) => { - const sandbox = import(/*webpackIgnore: true*/sandboxBundleSrc); - sandbox.then(pdfjsSandbox => { - resolve(pdfjsSandbox.QuickJSSandbox()); - }).catch(reject); - }); - } - async createSandbox(data) { - const sandbox = await this._ready; - sandbox.create(data); - } - async dispatchEventInSandbox(event) { - const sandbox = await this._ready; - setTimeout(() => sandbox.dispatchEvent(event), 0); - } - async destroySandbox() { - const sandbox = await this._ready; - sandbox.nukeSandbox(); - } -} - -;// ./web/pdf_scripting_manager.js - - -class PDFScriptingManager { - #closeCapability = null; - #destroyCapability = null; - #docProperties = null; - #eventAbortController = null; - #eventBus = null; - #externalServices = null; - #pdfDocument = null; - #pdfViewer = null; - #ready = false; - #scripting = null; - #willPrintCapability = null; - constructor({ - eventBus, - externalServices = null, - docProperties = null - }) { - this.#eventBus = eventBus; - this.#externalServices = externalServices; - this.#docProperties = docProperties; - } - setViewer(pdfViewer) { - this.#pdfViewer = pdfViewer; - } - async setDocument(pdfDocument) { - if (this.#pdfDocument) { - await this.#destroyScripting(); - } - this.#pdfDocument = pdfDocument; - if (!pdfDocument) { - return; - } - const [objects, calculationOrder, docActions] = await Promise.all([pdfDocument.getFieldObjects(), pdfDocument.getCalculationOrderIds(), pdfDocument.getJSActions()]); - if (!objects && !docActions) { - await this.#destroyScripting(); - return; - } - if (pdfDocument !== this.#pdfDocument) { - return; - } - try { - this.#scripting = this.#initScripting(); - } catch (error) { - console.error("setDocument:", error); - await this.#destroyScripting(); - return; - } - const eventBus = this.#eventBus; - this.#eventAbortController = new AbortController(); - const { - signal - } = this.#eventAbortController; - eventBus._on("updatefromsandbox", event => { - if (event?.source === window) { - this.#updateFromSandbox(event.detail); - } - }, { - signal - }); - eventBus._on("dispatcheventinsandbox", event => { - this.#scripting?.dispatchEventInSandbox(event.detail); - }, { - signal - }); - eventBus._on("pagechanging", ({ - pageNumber, - previous - }) => { - if (pageNumber === previous) { - return; - } - this.#dispatchPageClose(previous); - this.#dispatchPageOpen(pageNumber); - }, { - signal - }); - eventBus._on("pagerendered", ({ - pageNumber - }) => { - if (!this._pageOpenPending.has(pageNumber)) { - return; - } - if (pageNumber !== this.#pdfViewer.currentPageNumber) { - return; - } - this.#dispatchPageOpen(pageNumber); - }, { - signal - }); - eventBus._on("pagesdestroy", async () => { - await this.#dispatchPageClose(this.#pdfViewer.currentPageNumber); - await this.#scripting?.dispatchEventInSandbox({ - id: "doc", - name: "WillClose" - }); - this.#closeCapability?.resolve(); - }, { - signal - }); - try { - const docProperties = await this.#docProperties(pdfDocument); - if (pdfDocument !== this.#pdfDocument) { - return; - } - await this.#scripting.createSandbox({ - objects, - calculationOrder, - appInfo: { - platform: navigator.platform, - language: navigator.language - }, - docInfo: { - ...docProperties, - actions: docActions - } - }); - eventBus.dispatch("sandboxcreated", { - source: this - }); - } catch (error) { - console.error("setDocument:", error); - await this.#destroyScripting(); - return; - } - await this.#scripting?.dispatchEventInSandbox({ - id: "doc", - name: "Open" - }); - await this.#dispatchPageOpen(this.#pdfViewer.currentPageNumber, true); - Promise.resolve().then(() => { - if (pdfDocument === this.#pdfDocument) { - this.#ready = true; - } - }); - } - async dispatchWillSave() { - return this.#scripting?.dispatchEventInSandbox({ - id: "doc", - name: "WillSave" - }); - } - async dispatchDidSave() { - return this.#scripting?.dispatchEventInSandbox({ - id: "doc", - name: "DidSave" - }); - } - async dispatchWillPrint() { - if (!this.#scripting) { - return; - } - await this.#willPrintCapability?.promise; - this.#willPrintCapability = Promise.withResolvers(); - try { - await this.#scripting.dispatchEventInSandbox({ - id: "doc", - name: "WillPrint" - }); - } catch (ex) { - this.#willPrintCapability.resolve(); - this.#willPrintCapability = null; - throw ex; - } - await this.#willPrintCapability.promise; - } - async dispatchDidPrint() { - return this.#scripting?.dispatchEventInSandbox({ - id: "doc", - name: "DidPrint" - }); - } - get destroyPromise() { - return this.#destroyCapability?.promise || null; - } - get ready() { - return this.#ready; - } - get _pageOpenPending() { - return shadow(this, "_pageOpenPending", new Set()); - } - get _visitedPages() { - return shadow(this, "_visitedPages", new Map()); - } - async #updateFromSandbox(detail) { - const pdfViewer = this.#pdfViewer; - const isInPresentationMode = pdfViewer.isInPresentationMode || pdfViewer.isChangingPresentationMode; - const { - id, - siblings, - command, - value - } = detail; - if (!id) { - switch (command) { - case "clear": - console.clear(); - break; - case "error": - console.error(value); - break; - case "layout": - if (!isInPresentationMode) { - const modes = apiPageLayoutToViewerModes(value); - pdfViewer.spreadMode = modes.spreadMode; - } - break; - case "page-num": - pdfViewer.currentPageNumber = value + 1; - break; - case "print": - await pdfViewer.pagesPromise; - this.#eventBus.dispatch("print", { - source: this - }); - break; - case "println": - console.log(value); - break; - case "zoom": - if (!isInPresentationMode) { - pdfViewer.currentScaleValue = value; - } - break; - case "SaveAs": - this.#eventBus.dispatch("download", { - source: this - }); - break; - case "FirstPage": - pdfViewer.currentPageNumber = 1; - break; - case "LastPage": - pdfViewer.currentPageNumber = pdfViewer.pagesCount; - break; - case "NextPage": - pdfViewer.nextPage(); - break; - case "PrevPage": - pdfViewer.previousPage(); - break; - case "ZoomViewIn": - if (!isInPresentationMode) { - pdfViewer.increaseScale(); - } - break; - case "ZoomViewOut": - if (!isInPresentationMode) { - pdfViewer.decreaseScale(); - } - break; - case "WillPrintFinished": - this.#willPrintCapability?.resolve(); - this.#willPrintCapability = null; - break; - } - return; - } - if (isInPresentationMode && detail.focus) { - return; - } - delete detail.id; - delete detail.siblings; - const ids = siblings ? [id, ...siblings] : [id]; - for (const elementId of ids) { - const element = document.querySelector(`[data-element-id="${elementId}"]`); - if (element) { - element.dispatchEvent(new CustomEvent("updatefromsandbox", { - detail - })); - } else { - this.#pdfDocument?.annotationStorage.setValue(elementId, detail); - } - } - } - async #dispatchPageOpen(pageNumber, initialize = false) { - const pdfDocument = this.#pdfDocument, - visitedPages = this._visitedPages; - if (initialize) { - this.#closeCapability = Promise.withResolvers(); - } - if (!this.#closeCapability) { - return; - } - const pageView = this.#pdfViewer.getPageView(pageNumber - 1); - if (pageView?.renderingState !== RenderingStates.FINISHED) { - this._pageOpenPending.add(pageNumber); - return; - } - this._pageOpenPending.delete(pageNumber); - const actionsPromise = (async () => { - const actions = await (!visitedPages.has(pageNumber) ? pageView.pdfPage?.getJSActions() : null); - if (pdfDocument !== this.#pdfDocument) { - return; - } - await this.#scripting?.dispatchEventInSandbox({ - id: "page", - name: "PageOpen", - pageNumber, - actions - }); - })(); - visitedPages.set(pageNumber, actionsPromise); - } - async #dispatchPageClose(pageNumber) { - const pdfDocument = this.#pdfDocument, - visitedPages = this._visitedPages; - if (!this.#closeCapability) { - return; - } - if (this._pageOpenPending.has(pageNumber)) { - return; - } - const actionsPromise = visitedPages.get(pageNumber); - if (!actionsPromise) { - return; - } - visitedPages.set(pageNumber, null); - await actionsPromise; - if (pdfDocument !== this.#pdfDocument) { - return; - } - await this.#scripting?.dispatchEventInSandbox({ - id: "page", - name: "PageClose", - pageNumber - }); - } - #initScripting() { - this.#destroyCapability = Promise.withResolvers(); - if (this.#scripting) { - throw new Error("#initScripting: Scripting already exists."); - } - return this.#externalServices.createScripting(); - } - async #destroyScripting() { - if (!this.#scripting) { - this.#pdfDocument = null; - this.#destroyCapability?.resolve(); - return; - } - if (this.#closeCapability) { - await Promise.race([this.#closeCapability.promise, new Promise(resolve => { - setTimeout(resolve, 1000); - })]).catch(() => {}); - this.#closeCapability = null; - } - this.#pdfDocument = null; - try { - await this.#scripting.destroySandbox(); - } catch {} - this.#willPrintCapability?.reject(new Error("Scripting destroyed.")); - this.#willPrintCapability = null; - this.#eventAbortController?.abort(); - this.#eventAbortController = null; - this._pageOpenPending.clear(); - this._visitedPages.clear(); - this.#scripting = null; - this.#ready = false; - this.#destroyCapability?.resolve(); - } -} - -;// ./web/pdf_scripting_manager.component.js - - -class PDFScriptingManagerComponents extends PDFScriptingManager { - constructor(options) { - if (!options.externalServices) { - window.addEventListener("updatefromsandbox", event => { - options.eventBus.dispatch("updatefromsandbox", { - source: window, - detail: event.detail - }); - }); - } - options.externalServices ||= { - createScripting: () => new GenericScripting(options.sandboxBundleSrc) - }; - options.docProperties ||= pdfDocument => docProperties(pdfDocument); - super(options); - } -} - -;// ./web/pdf_rendering_queue.js - - -const CLEANUP_TIMEOUT = 30000; -class PDFRenderingQueue { - constructor() { - this.pdfViewer = null; - this.pdfThumbnailViewer = null; - this.onIdle = null; - this.highestPriorityPage = null; - this.idleTimeout = null; - this.printing = false; - this.isThumbnailViewEnabled = false; - Object.defineProperty(this, "hasViewer", { - value: () => !!this.pdfViewer - }); - } - setViewer(pdfViewer) { - this.pdfViewer = pdfViewer; - } - setThumbnailViewer(pdfThumbnailViewer) { - this.pdfThumbnailViewer = pdfThumbnailViewer; - } - isHighestPriority(view) { - return this.highestPriorityPage === view.renderingId; - } - renderHighestPriority(currentlyVisiblePages) { - if (this.idleTimeout) { - clearTimeout(this.idleTimeout); - this.idleTimeout = null; - } - if (this.pdfViewer.forceRendering(currentlyVisiblePages)) { - return; - } - if (this.isThumbnailViewEnabled && this.pdfThumbnailViewer?.forceRendering()) { - return; - } - if (this.printing) { - return; - } - if (this.onIdle) { - this.idleTimeout = setTimeout(this.onIdle.bind(this), CLEANUP_TIMEOUT); - } - } - getHighestPriority(visible, views, scrolledDown, preRenderExtra = false) { - const visibleViews = visible.views, - numVisible = visibleViews.length; - if (numVisible === 0) { - return null; - } - for (let i = 0; i < numVisible; i++) { - const view = visibleViews[i].view; - if (!this.isViewFinished(view)) { - return view; - } - } - const firstId = visible.first.id, - lastId = visible.last.id; - if (lastId - firstId + 1 > numVisible) { - const visibleIds = visible.ids; - for (let i = 1, ii = lastId - firstId; i < ii; i++) { - const holeId = scrolledDown ? firstId + i : lastId - i; - if (visibleIds.has(holeId)) { - continue; - } - const holeView = views[holeId - 1]; - if (!this.isViewFinished(holeView)) { - return holeView; - } - } - } - let preRenderIndex = scrolledDown ? lastId : firstId - 2; - let preRenderView = views[preRenderIndex]; - if (preRenderView && !this.isViewFinished(preRenderView)) { - return preRenderView; - } - if (preRenderExtra) { - preRenderIndex += scrolledDown ? 1 : -1; - preRenderView = views[preRenderIndex]; - if (preRenderView && !this.isViewFinished(preRenderView)) { - return preRenderView; - } - } - return null; - } - isViewFinished(view) { - return view.renderingState === RenderingStates.FINISHED; - } - renderView(view) { - switch (view.renderingState) { - case RenderingStates.FINISHED: - return false; - case RenderingStates.PAUSED: - this.highestPriorityPage = view.renderingId; - view.resume(); - break; - case RenderingStates.RUNNING: - this.highestPriorityPage = view.renderingId; - break; - case RenderingStates.INITIAL: - this.highestPriorityPage = view.renderingId; - view.draw().finally(() => { - this.renderHighestPriority(); - }).catch(reason => { - if (reason instanceof RenderingCancelledException) { - return; - } - console.error("renderView:", reason); - }); - break; - } - return true; - } -} - -;// ./web/pdf_viewer.js - - - - - - -const DEFAULT_CACHE_SIZE = 10; -const PagesCountLimit = { - FORCE_SCROLL_MODE_PAGE: 10000, - FORCE_LAZY_PAGE_INIT: 5000, - PAUSE_EAGER_PAGE_INIT: 250 -}; -function isValidAnnotationEditorMode(mode) { - return Object.values(AnnotationEditorType).includes(mode) && mode !== AnnotationEditorType.DISABLE; -} -class PDFPageViewBuffer { - #buf = new Set(); - #size = 0; - constructor(size) { - this.#size = size; - } - push(view) { - const buf = this.#buf; - if (buf.has(view)) { - buf.delete(view); - } - buf.add(view); - if (buf.size > this.#size) { - this.#destroyFirstView(); - } - } - resize(newSize, idsToKeep = null) { - this.#size = newSize; - const buf = this.#buf; - if (idsToKeep) { - const ii = buf.size; - let i = 1; - for (const view of buf) { - if (idsToKeep.has(view.id)) { - buf.delete(view); - buf.add(view); - } - if (++i > ii) { - break; - } - } - } - while (buf.size > this.#size) { - this.#destroyFirstView(); - } - } - has(view) { - return this.#buf.has(view); - } - [Symbol.iterator]() { - return this.#buf.keys(); - } - #destroyFirstView() { - const firstView = this.#buf.keys().next().value; - firstView?.destroy(); - this.#buf.delete(firstView); - } -} -class PDFViewer { - #buffer = null; - #altTextManager = null; - #annotationEditorHighlightColors = null; - #annotationEditorMode = AnnotationEditorType.NONE; - #annotationEditorUIManager = null; - #annotationMode = AnnotationMode.ENABLE_FORMS; - #containerTopLeft = null; - #editorUndoBar = null; - #enableHWA = false; - #enableHighlightFloatingButton = false; - #enablePermissions = false; - #enableUpdatedAddImage = false; - #enableNewAltTextWhenAddingImage = false; - #eventAbortController = null; - #mlManager = null; - #switchAnnotationEditorModeAC = null; - #switchAnnotationEditorModeTimeoutId = null; - #getAllTextInProgress = false; - #hiddenCopyElement = null; - #interruptCopyCondition = false; - #previousContainerHeight = 0; - #resizeObserver = new ResizeObserver(this.#resizeObserverCallback.bind(this)); - #scrollModePageState = null; - #scaleTimeoutId = null; - #supportsPinchToZoom = true; - #textLayerMode = TextLayerMode.ENABLE; - constructor(options) { - const viewerVersion = "4.10.38"; - if (version !== viewerVersion) { - throw new Error(`The API version "${version}" does not match the Viewer version "${viewerVersion}".`); - } - this.container = options.container; - this.viewer = options.viewer || options.container.firstElementChild; - if (this.container?.tagName !== "DIV" || this.viewer?.tagName !== "DIV") { - throw new Error("Invalid `container` and/or `viewer` option."); - } - if (this.container.offsetParent && getComputedStyle(this.container).position !== "absolute") { - throw new Error("The `container` must be absolutely positioned."); - } - this.#resizeObserver.observe(this.container); - this.eventBus = options.eventBus; - this.linkService = options.linkService || new SimpleLinkService(); - this.downloadManager = options.downloadManager || null; - this.findController = options.findController || null; - this.#altTextManager = options.altTextManager || null; - this.#editorUndoBar = options.editorUndoBar || null; - if (this.findController) { - this.findController.onIsPageVisible = pageNumber => this._getVisiblePages().ids.has(pageNumber); - } - this._scriptingManager = options.scriptingManager || null; - this.#textLayerMode = options.textLayerMode ?? TextLayerMode.ENABLE; - this.#annotationMode = options.annotationMode ?? AnnotationMode.ENABLE_FORMS; - this.#annotationEditorMode = options.annotationEditorMode ?? AnnotationEditorType.NONE; - this.#annotationEditorHighlightColors = options.annotationEditorHighlightColors || null; - this.#enableHighlightFloatingButton = options.enableHighlightFloatingButton === true; - this.#enableUpdatedAddImage = options.enableUpdatedAddImage === true; - this.#enableNewAltTextWhenAddingImage = options.enableNewAltTextWhenAddingImage === true; - this.imageResourcesPath = options.imageResourcesPath || ""; - this.enablePrintAutoRotate = options.enablePrintAutoRotate || false; - this.removePageBorders = options.removePageBorders || false; - this.maxCanvasPixels = options.maxCanvasPixels; - this.l10n = options.l10n; - this.l10n ||= new genericl10n_GenericL10n(); - this.#enablePermissions = options.enablePermissions || false; - this.pageColors = options.pageColors || null; - this.#mlManager = options.mlManager || null; - this.#enableHWA = options.enableHWA || false; - this.#supportsPinchToZoom = options.supportsPinchToZoom !== false; - this.defaultRenderingQueue = !options.renderingQueue; - if (this.defaultRenderingQueue) { - this.renderingQueue = new PDFRenderingQueue(); - this.renderingQueue.setViewer(this); - } else { - this.renderingQueue = options.renderingQueue; - } - const { - abortSignal - } = options; - abortSignal?.addEventListener("abort", () => { - this.#resizeObserver.disconnect(); - this.#resizeObserver = null; - }, { - once: true - }); - this.scroll = watchScroll(this.container, this._scrollUpdate.bind(this), abortSignal); - this.presentationModeState = PresentationModeState.UNKNOWN; - this._resetView(); - if (this.removePageBorders) { - this.viewer.classList.add("removePageBorders"); - } - this.#updateContainerHeightCss(); - this.eventBus._on("thumbnailrendered", ({ - pageNumber, - pdfPage - }) => { - const pageView = this._pages[pageNumber - 1]; - if (!this.#buffer.has(pageView)) { - pdfPage?.cleanup(); - } - }); - if (!options.l10n) { - this.l10n.translate(this.container); - } - } - get pagesCount() { - return this._pages.length; - } - getPageView(index) { - return this._pages[index]; - } - getCachedPageViews() { - return new Set(this.#buffer); - } - get pageViewsReady() { - return this._pages.every(pageView => pageView?.pdfPage); - } - get renderForms() { - return this.#annotationMode === AnnotationMode.ENABLE_FORMS; - } - get enableScripting() { - return !!this._scriptingManager; - } - get currentPageNumber() { - return this._currentPageNumber; - } - set currentPageNumber(val) { - if (!Number.isInteger(val)) { - throw new Error("Invalid page number."); - } - if (!this.pdfDocument) { - return; - } - if (!this._setCurrentPageNumber(val, true)) { - console.error(`currentPageNumber: "${val}" is not a valid page.`); - } - } - _setCurrentPageNumber(val, resetCurrentPageView = false) { - if (this._currentPageNumber === val) { - if (resetCurrentPageView) { - this.#resetCurrentPageView(); - } - return true; - } - if (!(0 < val && val <= this.pagesCount)) { - return false; - } - const previous = this._currentPageNumber; - this._currentPageNumber = val; - this.eventBus.dispatch("pagechanging", { - source: this, - pageNumber: val, - pageLabel: this._pageLabels?.[val - 1] ?? null, - previous - }); - if (resetCurrentPageView) { - this.#resetCurrentPageView(); - } - return true; - } - get currentPageLabel() { - return this._pageLabels?.[this._currentPageNumber - 1] ?? null; - } - set currentPageLabel(val) { - if (!this.pdfDocument) { - return; - } - let page = val | 0; - if (this._pageLabels) { - const i = this._pageLabels.indexOf(val); - if (i >= 0) { - page = i + 1; - } - } - if (!this._setCurrentPageNumber(page, true)) { - console.error(`currentPageLabel: "${val}" is not a valid page.`); - } - } - get currentScale() { - return this._currentScale !== UNKNOWN_SCALE ? this._currentScale : DEFAULT_SCALE; - } - set currentScale(val) { - if (isNaN(val)) { - throw new Error("Invalid numeric scale."); - } - if (!this.pdfDocument) { - return; - } - this.#setScale(val, { - noScroll: false - }); - } - get currentScaleValue() { - return this._currentScaleValue; - } - set currentScaleValue(val) { - if (!this.pdfDocument) { - return; - } - this.#setScale(val, { - noScroll: false - }); - } - get pagesRotation() { - return this._pagesRotation; - } - set pagesRotation(rotation) { - if (!isValidRotation(rotation)) { - throw new Error("Invalid pages rotation angle."); - } - if (!this.pdfDocument) { - return; - } - rotation %= 360; - if (rotation < 0) { - rotation += 360; - } - if (this._pagesRotation === rotation) { - return; - } - this._pagesRotation = rotation; - const pageNumber = this._currentPageNumber; - this.refresh(true, { - rotation - }); - if (this._currentScaleValue) { - this.#setScale(this._currentScaleValue, { - noScroll: true - }); - } - this.eventBus.dispatch("rotationchanging", { - source: this, - pagesRotation: rotation, - pageNumber - }); - if (this.defaultRenderingQueue) { - this.update(); - } - } - get firstPagePromise() { - return this.pdfDocument ? this._firstPageCapability.promise : null; - } - get onePageRendered() { - return this.pdfDocument ? this._onePageRenderedCapability.promise : null; - } - get pagesPromise() { - return this.pdfDocument ? this._pagesCapability.promise : null; - } - get _layerProperties() { - const self = this; - return shadow(this, "_layerProperties", { - get annotationEditorUIManager() { - return self.#annotationEditorUIManager; - }, - get annotationStorage() { - return self.pdfDocument?.annotationStorage; - }, - get downloadManager() { - return self.downloadManager; - }, - get enableScripting() { - return !!self._scriptingManager; - }, - get fieldObjectsPromise() { - return self.pdfDocument?.getFieldObjects(); - }, - get findController() { - return self.findController; - }, - get hasJSActionsPromise() { - return self.pdfDocument?.hasJSActions(); - }, - get linkService() { - return self.linkService; - } - }); - } - #initializePermissions(permissions) { - const params = { - annotationEditorMode: this.#annotationEditorMode, - annotationMode: this.#annotationMode, - textLayerMode: this.#textLayerMode - }; - if (!permissions) { - return params; - } - if (!permissions.includes(PermissionFlag.COPY) && this.#textLayerMode === TextLayerMode.ENABLE) { - params.textLayerMode = TextLayerMode.ENABLE_PERMISSIONS; - } - if (!permissions.includes(PermissionFlag.MODIFY_CONTENTS)) { - params.annotationEditorMode = AnnotationEditorType.DISABLE; - } - if (!permissions.includes(PermissionFlag.MODIFY_ANNOTATIONS) && !permissions.includes(PermissionFlag.FILL_INTERACTIVE_FORMS) && this.#annotationMode === AnnotationMode.ENABLE_FORMS) { - params.annotationMode = AnnotationMode.ENABLE; - } - return params; - } - async #onePageRenderedOrForceFetch(signal) { - if (document.visibilityState === "hidden" || !this.container.offsetParent || this._getVisiblePages().views.length === 0) { - return; - } - const hiddenCapability = Promise.withResolvers(), - ac = new AbortController(); - document.addEventListener("visibilitychange", () => { - if (document.visibilityState === "hidden") { - hiddenCapability.resolve(); - } - }, { - signal: typeof AbortSignal.any === "function" ? AbortSignal.any([signal, ac.signal]) : signal - }); - await Promise.race([this._onePageRenderedCapability.promise, hiddenCapability.promise]); - ac.abort(); - } - async getAllText() { - const texts = []; - const buffer = []; - for (let pageNum = 1, pagesCount = this.pdfDocument.numPages; pageNum <= pagesCount; ++pageNum) { - if (this.#interruptCopyCondition) { - return null; - } - buffer.length = 0; - const page = await this.pdfDocument.getPage(pageNum); - const { - items - } = await page.getTextContent(); - for (const item of items) { - if (item.str) { - buffer.push(item.str); - } - if (item.hasEOL) { - buffer.push("\n"); - } - } - texts.push(removeNullCharacters(buffer.join(""))); - } - return texts.join("\n"); - } - #copyCallback(textLayerMode, event) { - const selection = document.getSelection(); - const { - focusNode, - anchorNode - } = selection; - if (anchorNode && focusNode && selection.containsNode(this.#hiddenCopyElement)) { - if (this.#getAllTextInProgress || textLayerMode === TextLayerMode.ENABLE_PERMISSIONS) { - stopEvent(event); - return; - } - this.#getAllTextInProgress = true; - const { - classList - } = this.viewer; - classList.add("copyAll"); - const ac = new AbortController(); - window.addEventListener("keydown", ev => this.#interruptCopyCondition = ev.key === "Escape", { - signal: ac.signal - }); - this.getAllText().then(async text => { - if (text !== null) { - await navigator.clipboard.writeText(text); - } - }).catch(reason => { - console.warn(`Something goes wrong when extracting the text: ${reason.message}`); - }).finally(() => { - this.#getAllTextInProgress = false; - this.#interruptCopyCondition = false; - ac.abort(); - classList.remove("copyAll"); - }); - stopEvent(event); - } - } - setDocument(pdfDocument) { - if (this.pdfDocument) { - this.eventBus.dispatch("pagesdestroy", { - source: this - }); - this._cancelRendering(); - this._resetView(); - this.findController?.setDocument(null); - this._scriptingManager?.setDocument(null); - this.#annotationEditorUIManager?.destroy(); - this.#annotationEditorUIManager = null; - } - this.pdfDocument = pdfDocument; - if (!pdfDocument) { - return; - } - const pagesCount = pdfDocument.numPages; - const firstPagePromise = pdfDocument.getPage(1); - const optionalContentConfigPromise = pdfDocument.getOptionalContentConfig({ - intent: "display" - }); - const permissionsPromise = this.#enablePermissions ? pdfDocument.getPermissions() : Promise.resolve(); - const { - eventBus, - pageColors, - viewer - } = this; - this.#eventAbortController = new AbortController(); - const { - signal - } = this.#eventAbortController; - if (pagesCount > PagesCountLimit.FORCE_SCROLL_MODE_PAGE) { - console.warn("Forcing PAGE-scrolling for performance reasons, given the length of the document."); - const mode = this._scrollMode = ScrollMode.PAGE; - eventBus.dispatch("scrollmodechanged", { - source: this, - mode - }); - } - this._pagesCapability.promise.then(() => { - eventBus.dispatch("pagesloaded", { - source: this, - pagesCount - }); - }, () => {}); - const onBeforeDraw = evt => { - const pageView = this._pages[evt.pageNumber - 1]; - if (!pageView) { - return; - } - this.#buffer.push(pageView); - }; - eventBus._on("pagerender", onBeforeDraw, { - signal - }); - const onAfterDraw = evt => { - if (evt.cssTransform) { - return; - } - this._onePageRenderedCapability.resolve({ - timestamp: evt.timestamp - }); - eventBus._off("pagerendered", onAfterDraw); - }; - eventBus._on("pagerendered", onAfterDraw, { - signal - }); - Promise.all([firstPagePromise, permissionsPromise]).then(([firstPdfPage, permissions]) => { - if (pdfDocument !== this.pdfDocument) { - return; - } - this._firstPageCapability.resolve(firstPdfPage); - this._optionalContentConfigPromise = optionalContentConfigPromise; - const { - annotationEditorMode, - annotationMode, - textLayerMode - } = this.#initializePermissions(permissions); - if (textLayerMode !== TextLayerMode.DISABLE) { - const element = this.#hiddenCopyElement = document.createElement("div"); - element.id = "hiddenCopyElement"; - viewer.before(element); - } - if (typeof AbortSignal.any === "function" && annotationEditorMode !== AnnotationEditorType.DISABLE) { - const mode = annotationEditorMode; - if (pdfDocument.isPureXfa) { - console.warn("Warning: XFA-editing is not implemented."); - } else if (isValidAnnotationEditorMode(mode)) { - this.#annotationEditorUIManager = new AnnotationEditorUIManager(this.container, viewer, this.#altTextManager, eventBus, pdfDocument, pageColors, this.#annotationEditorHighlightColors, this.#enableHighlightFloatingButton, this.#enableUpdatedAddImage, this.#enableNewAltTextWhenAddingImage, this.#mlManager, this.#editorUndoBar, this.#supportsPinchToZoom); - eventBus.dispatch("annotationeditoruimanager", { - source: this, - uiManager: this.#annotationEditorUIManager - }); - if (mode !== AnnotationEditorType.NONE) { - if (mode === AnnotationEditorType.STAMP) { - this.#mlManager?.loadModel("altText"); - } - this.#annotationEditorUIManager.updateMode(mode); - } - } else { - console.error(`Invalid AnnotationEditor mode: ${mode}`); - } - } - const viewerElement = this._scrollMode === ScrollMode.PAGE ? null : viewer; - const scale = this.currentScale; - const viewport = firstPdfPage.getViewport({ - scale: scale * PixelsPerInch.PDF_TO_CSS_UNITS - }); - viewer.style.setProperty("--scale-factor", viewport.scale); - if (pageColors?.background) { - viewer.style.setProperty("--page-bg-color", pageColors.background); - } - if (pageColors?.foreground === "CanvasText" || pageColors?.background === "Canvas") { - viewer.style.setProperty("--hcm-highlight-filter", pdfDocument.filterFactory.addHighlightHCMFilter("highlight", "CanvasText", "Canvas", "HighlightText", "Highlight")); - viewer.style.setProperty("--hcm-highlight-selected-filter", pdfDocument.filterFactory.addHighlightHCMFilter("highlight_selected", "CanvasText", "Canvas", "HighlightText", "ButtonText")); - } - for (let pageNum = 1; pageNum <= pagesCount; ++pageNum) { - const pageView = new PDFPageView({ - container: viewerElement, - eventBus, - id: pageNum, - scale, - defaultViewport: viewport.clone(), - optionalContentConfigPromise, - renderingQueue: this.renderingQueue, - textLayerMode, - annotationMode, - imageResourcesPath: this.imageResourcesPath, - maxCanvasPixels: this.maxCanvasPixels, - pageColors, - l10n: this.l10n, - layerProperties: this._layerProperties, - enableHWA: this.#enableHWA - }); - this._pages.push(pageView); - } - this._pages[0]?.setPdfPage(firstPdfPage); - if (this._scrollMode === ScrollMode.PAGE) { - this.#ensurePageViewVisible(); - } else if (this._spreadMode !== SpreadMode.NONE) { - this._updateSpreadMode(); - } - this.#onePageRenderedOrForceFetch(signal).then(async () => { - if (pdfDocument !== this.pdfDocument) { - return; - } - this.findController?.setDocument(pdfDocument); - this._scriptingManager?.setDocument(pdfDocument); - if (this.#hiddenCopyElement) { - document.addEventListener("copy", this.#copyCallback.bind(this, textLayerMode), { - signal - }); - } - if (this.#annotationEditorUIManager) { - eventBus.dispatch("annotationeditormodechanged", { - source: this, - mode: this.#annotationEditorMode - }); - } - if (pdfDocument.loadingParams.disableAutoFetch || pagesCount > PagesCountLimit.FORCE_LAZY_PAGE_INIT) { - this._pagesCapability.resolve(); - return; - } - let getPagesLeft = pagesCount - 1; - if (getPagesLeft <= 0) { - this._pagesCapability.resolve(); - return; - } - for (let pageNum = 2; pageNum <= pagesCount; ++pageNum) { - const promise = pdfDocument.getPage(pageNum).then(pdfPage => { - const pageView = this._pages[pageNum - 1]; - if (!pageView.pdfPage) { - pageView.setPdfPage(pdfPage); - } - if (--getPagesLeft === 0) { - this._pagesCapability.resolve(); - } - }, reason => { - console.error(`Unable to get page ${pageNum} to initialize viewer`, reason); - if (--getPagesLeft === 0) { - this._pagesCapability.resolve(); - } - }); - if (pageNum % PagesCountLimit.PAUSE_EAGER_PAGE_INIT === 0) { - await promise; - } - } - }); - eventBus.dispatch("pagesinit", { - source: this - }); - pdfDocument.getMetadata().then(({ - info - }) => { - if (pdfDocument !== this.pdfDocument) { - return; - } - if (info.Language) { - viewer.lang = info.Language; - } - }); - if (this.defaultRenderingQueue) { - this.update(); - } - }).catch(reason => { - console.error("Unable to initialize viewer", reason); - this._pagesCapability.reject(reason); - }); - } - setPageLabels(labels) { - if (!this.pdfDocument) { - return; - } - if (!labels) { - this._pageLabels = null; - } else if (!(Array.isArray(labels) && this.pdfDocument.numPages === labels.length)) { - this._pageLabels = null; - console.error(`setPageLabels: Invalid page labels.`); - } else { - this._pageLabels = labels; - } - for (let i = 0, ii = this._pages.length; i < ii; i++) { - this._pages[i].setPageLabel(this._pageLabels?.[i] ?? null); - } - } - _resetView() { - this._pages = []; - this._currentPageNumber = 1; - this._currentScale = UNKNOWN_SCALE; - this._currentScaleValue = null; - this._pageLabels = null; - this.#buffer = new PDFPageViewBuffer(DEFAULT_CACHE_SIZE); - this._location = null; - this._pagesRotation = 0; - this._optionalContentConfigPromise = null; - this._firstPageCapability = Promise.withResolvers(); - this._onePageRenderedCapability = Promise.withResolvers(); - this._pagesCapability = Promise.withResolvers(); - this._scrollMode = ScrollMode.VERTICAL; - this._previousScrollMode = ScrollMode.UNKNOWN; - this._spreadMode = SpreadMode.NONE; - this.#scrollModePageState = { - previousPageNumber: 1, - scrollDown: true, - pages: [] - }; - this.#eventAbortController?.abort(); - this.#eventAbortController = null; - this.viewer.textContent = ""; - this._updateScrollMode(); - this.viewer.removeAttribute("lang"); - this.#hiddenCopyElement?.remove(); - this.#hiddenCopyElement = null; - this.#cleanupSwitchAnnotationEditorMode(); - } - #ensurePageViewVisible() { - if (this._scrollMode !== ScrollMode.PAGE) { - throw new Error("#ensurePageViewVisible: Invalid scrollMode value."); - } - const pageNumber = this._currentPageNumber, - state = this.#scrollModePageState, - viewer = this.viewer; - viewer.textContent = ""; - state.pages.length = 0; - if (this._spreadMode === SpreadMode.NONE && !this.isInPresentationMode) { - const pageView = this._pages[pageNumber - 1]; - viewer.append(pageView.div); - state.pages.push(pageView); - } else { - const pageIndexSet = new Set(), - parity = this._spreadMode - 1; - if (parity === -1) { - pageIndexSet.add(pageNumber - 1); - } else if (pageNumber % 2 !== parity) { - pageIndexSet.add(pageNumber - 1); - pageIndexSet.add(pageNumber); - } else { - pageIndexSet.add(pageNumber - 2); - pageIndexSet.add(pageNumber - 1); - } - const spread = document.createElement("div"); - spread.className = "spread"; - if (this.isInPresentationMode) { - const dummyPage = document.createElement("div"); - dummyPage.className = "dummyPage"; - spread.append(dummyPage); - } - for (const i of pageIndexSet) { - const pageView = this._pages[i]; - if (!pageView) { - continue; - } - spread.append(pageView.div); - state.pages.push(pageView); - } - viewer.append(spread); - } - state.scrollDown = pageNumber >= state.previousPageNumber; - state.previousPageNumber = pageNumber; - } - _scrollUpdate() { - if (this.pagesCount === 0) { - return; - } - this.update(); - } - #scrollIntoView(pageView, pageSpot = null) { - const { - div, - id - } = pageView; - if (this._currentPageNumber !== id) { - this._setCurrentPageNumber(id); - } - if (this._scrollMode === ScrollMode.PAGE) { - this.#ensurePageViewVisible(); - this.update(); - } - if (!pageSpot && !this.isInPresentationMode) { - const left = div.offsetLeft + div.clientLeft, - right = left + div.clientWidth; - const { - scrollLeft, - clientWidth - } = this.container; - if (this._scrollMode === ScrollMode.HORIZONTAL || left < scrollLeft || right > scrollLeft + clientWidth) { - pageSpot = { - left: 0, - top: 0 - }; - } - } - scrollIntoView(div, pageSpot); - if (!this._currentScaleValue && this._location) { - this._location = null; - } - } - #isSameScale(newScale) { - return newScale === this._currentScale || Math.abs(newScale - this._currentScale) < 1e-15; - } - #setScaleUpdatePages(newScale, newValue, { - noScroll = false, - preset = false, - drawingDelay = -1, - origin = null - }) { - this._currentScaleValue = newValue.toString(); - if (this.#isSameScale(newScale)) { - if (preset) { - this.eventBus.dispatch("scalechanging", { - source: this, - scale: newScale, - presetValue: newValue - }); - } - return; - } - this.viewer.style.setProperty("--scale-factor", newScale * PixelsPerInch.PDF_TO_CSS_UNITS); - const postponeDrawing = drawingDelay >= 0 && drawingDelay < 1000; - this.refresh(true, { - scale: newScale, - drawingDelay: postponeDrawing ? drawingDelay : -1 - }); - if (postponeDrawing) { - this.#scaleTimeoutId = setTimeout(() => { - this.#scaleTimeoutId = null; - this.refresh(); - }, drawingDelay); - } - const previousScale = this._currentScale; - this._currentScale = newScale; - if (!noScroll) { - let page = this._currentPageNumber, - dest; - if (this._location && !(this.isInPresentationMode || this.isChangingPresentationMode)) { - page = this._location.pageNumber; - dest = [null, { - name: "XYZ" - }, this._location.left, this._location.top, null]; - } - this.scrollPageIntoView({ - pageNumber: page, - destArray: dest, - allowNegativeOffset: true - }); - if (Array.isArray(origin)) { - const scaleDiff = newScale / previousScale - 1; - const [top, left] = this.containerTopLeft; - this.container.scrollLeft += (origin[0] - left) * scaleDiff; - this.container.scrollTop += (origin[1] - top) * scaleDiff; - } - } - this.eventBus.dispatch("scalechanging", { - source: this, - scale: newScale, - presetValue: preset ? newValue : undefined - }); - if (this.defaultRenderingQueue) { - this.update(); - } - } - get #pageWidthScaleFactor() { - if (this._spreadMode !== SpreadMode.NONE && this._scrollMode !== ScrollMode.HORIZONTAL) { - return 2; - } - return 1; - } - #setScale(value, options) { - let scale = parseFloat(value); - if (scale > 0) { - options.preset = false; - this.#setScaleUpdatePages(scale, value, options); - } else { - const currentPage = this._pages[this._currentPageNumber - 1]; - if (!currentPage) { - return; - } - let hPadding = SCROLLBAR_PADDING, - vPadding = VERTICAL_PADDING; - if (this.isInPresentationMode) { - hPadding = vPadding = 4; - if (this._spreadMode !== SpreadMode.NONE) { - hPadding *= 2; - } - } else if (this.removePageBorders) { - hPadding = vPadding = 0; - } else if (this._scrollMode === ScrollMode.HORIZONTAL) { - [hPadding, vPadding] = [vPadding, hPadding]; - } - const pageWidthScale = (this.container.clientWidth - hPadding) / currentPage.width * currentPage.scale / this.#pageWidthScaleFactor; - const pageHeightScale = (this.container.clientHeight - vPadding) / currentPage.height * currentPage.scale; - switch (value) { - case "page-actual": - scale = 1; - break; - case "page-width": - scale = pageWidthScale; - break; - case "page-height": - scale = pageHeightScale; - break; - case "page-fit": - scale = Math.min(pageWidthScale, pageHeightScale); - break; - case "auto": - const horizontalScale = isPortraitOrientation(currentPage) ? pageWidthScale : Math.min(pageHeightScale, pageWidthScale); - scale = Math.min(MAX_AUTO_SCALE, horizontalScale); - break; - default: - console.error(`#setScale: "${value}" is an unknown zoom value.`); - return; - } - options.preset = true; - this.#setScaleUpdatePages(scale, value, options); - } - } - #resetCurrentPageView() { - const pageView = this._pages[this._currentPageNumber - 1]; - if (this.isInPresentationMode) { - this.#setScale(this._currentScaleValue, { - noScroll: true - }); - } - this.#scrollIntoView(pageView); - } - pageLabelToPageNumber(label) { - if (!this._pageLabels) { - return null; - } - const i = this._pageLabels.indexOf(label); - if (i < 0) { - return null; - } - return i + 1; - } - scrollPageIntoView({ - pageNumber, - destArray = null, - allowNegativeOffset = false, - ignoreDestinationZoom = false - }) { - if (!this.pdfDocument) { - return; - } - const pageView = Number.isInteger(pageNumber) && this._pages[pageNumber - 1]; - if (!pageView) { - console.error(`scrollPageIntoView: "${pageNumber}" is not a valid pageNumber parameter.`); - return; - } - if (this.isInPresentationMode || !destArray) { - this._setCurrentPageNumber(pageNumber, true); - return; - } - let x = 0, - y = 0; - let width = 0, - height = 0, - widthScale, - heightScale; - const changeOrientation = pageView.rotation % 180 !== 0; - const pageWidth = (changeOrientation ? pageView.height : pageView.width) / pageView.scale / PixelsPerInch.PDF_TO_CSS_UNITS; - const pageHeight = (changeOrientation ? pageView.width : pageView.height) / pageView.scale / PixelsPerInch.PDF_TO_CSS_UNITS; - let scale = 0; - switch (destArray[1].name) { - case "XYZ": - x = destArray[2]; - y = destArray[3]; - scale = destArray[4]; - x = x !== null ? x : 0; - y = y !== null ? y : pageHeight; - break; - case "Fit": - case "FitB": - scale = "page-fit"; - break; - case "FitH": - case "FitBH": - y = destArray[2]; - scale = "page-width"; - if (y === null && this._location) { - x = this._location.left; - y = this._location.top; - } else if (typeof y !== "number" || y < 0) { - y = pageHeight; - } - break; - case "FitV": - case "FitBV": - x = destArray[2]; - width = pageWidth; - height = pageHeight; - scale = "page-height"; - break; - case "FitR": - x = destArray[2]; - y = destArray[3]; - width = destArray[4] - x; - height = destArray[5] - y; - let hPadding = SCROLLBAR_PADDING, - vPadding = VERTICAL_PADDING; - if (this.removePageBorders) { - hPadding = vPadding = 0; - } - widthScale = (this.container.clientWidth - hPadding) / width / PixelsPerInch.PDF_TO_CSS_UNITS; - heightScale = (this.container.clientHeight - vPadding) / height / PixelsPerInch.PDF_TO_CSS_UNITS; - scale = Math.min(Math.abs(widthScale), Math.abs(heightScale)); - break; - default: - console.error(`scrollPageIntoView: "${destArray[1].name}" is not a valid destination type.`); - return; - } - if (!ignoreDestinationZoom) { - if (scale && scale !== this._currentScale) { - this.currentScaleValue = scale; - } else if (this._currentScale === UNKNOWN_SCALE) { - this.currentScaleValue = DEFAULT_SCALE_VALUE; - } - } - if (scale === "page-fit" && !destArray[4]) { - this.#scrollIntoView(pageView); - return; - } - const boundingRect = [pageView.viewport.convertToViewportPoint(x, y), pageView.viewport.convertToViewportPoint(x + width, y + height)]; - let left = Math.min(boundingRect[0][0], boundingRect[1][0]); - let top = Math.min(boundingRect[0][1], boundingRect[1][1]); - if (!allowNegativeOffset) { - left = Math.max(left, 0); - top = Math.max(top, 0); - } - this.#scrollIntoView(pageView, { - left, - top - }); - } - _updateLocation(firstPage) { - const currentScale = this._currentScale; - const currentScaleValue = this._currentScaleValue; - const normalizedScaleValue = parseFloat(currentScaleValue) === currentScale ? Math.round(currentScale * 10000) / 100 : currentScaleValue; - const pageNumber = firstPage.id; - const currentPageView = this._pages[pageNumber - 1]; - const container = this.container; - const topLeft = currentPageView.getPagePoint(container.scrollLeft - firstPage.x, container.scrollTop - firstPage.y); - const intLeft = Math.round(topLeft[0]); - const intTop = Math.round(topLeft[1]); - let pdfOpenParams = `#page=${pageNumber}`; - if (!this.isInPresentationMode) { - pdfOpenParams += `&zoom=${normalizedScaleValue},${intLeft},${intTop}`; - } - this._location = { - pageNumber, - scale: normalizedScaleValue, - top: intTop, - left: intLeft, - rotation: this._pagesRotation, - pdfOpenParams - }; - } - update() { - const visible = this._getVisiblePages(); - const visiblePages = visible.views, - numVisiblePages = visiblePages.length; - if (numVisiblePages === 0) { - return; - } - const newCacheSize = Math.max(DEFAULT_CACHE_SIZE, 2 * numVisiblePages + 1); - this.#buffer.resize(newCacheSize, visible.ids); - this.renderingQueue.renderHighestPriority(visible); - const isSimpleLayout = this._spreadMode === SpreadMode.NONE && (this._scrollMode === ScrollMode.PAGE || this._scrollMode === ScrollMode.VERTICAL); - const currentId = this._currentPageNumber; - let stillFullyVisible = false; - for (const page of visiblePages) { - if (page.percent < 100) { - break; - } - if (page.id === currentId && isSimpleLayout) { - stillFullyVisible = true; - break; - } - } - this._setCurrentPageNumber(stillFullyVisible ? currentId : visiblePages[0].id); - this._updateLocation(visible.first); - this.eventBus.dispatch("updateviewarea", { - source: this, - location: this._location - }); - } - #switchToEditAnnotationMode() { - const visible = this._getVisiblePages(); - const pagesToRefresh = []; - const { - ids, - views - } = visible; - for (const page of views) { - const { - view - } = page; - if (!view.hasEditableAnnotations()) { - ids.delete(view.id); - continue; - } - pagesToRefresh.push(page); - } - if (pagesToRefresh.length === 0) { - return null; - } - this.renderingQueue.renderHighestPriority({ - first: pagesToRefresh[0], - last: pagesToRefresh.at(-1), - views: pagesToRefresh, - ids - }); - return ids; - } - containsElement(element) { - return this.container.contains(element); - } - focus() { - this.container.focus(); - } - get _isContainerRtl() { - return getComputedStyle(this.container).direction === "rtl"; - } - get isInPresentationMode() { - return this.presentationModeState === PresentationModeState.FULLSCREEN; - } - get isChangingPresentationMode() { - return this.presentationModeState === PresentationModeState.CHANGING; - } - get isHorizontalScrollbarEnabled() { - return this.isInPresentationMode ? false : this.container.scrollWidth > this.container.clientWidth; - } - get isVerticalScrollbarEnabled() { - return this.isInPresentationMode ? false : this.container.scrollHeight > this.container.clientHeight; - } - _getVisiblePages() { - const views = this._scrollMode === ScrollMode.PAGE ? this.#scrollModePageState.pages : this._pages, - horizontal = this._scrollMode === ScrollMode.HORIZONTAL, - rtl = horizontal && this._isContainerRtl; - return getVisibleElements({ - scrollEl: this.container, - views, - sortByVisibility: true, - horizontal, - rtl - }); - } - cleanup() { - for (const pageView of this._pages) { - if (pageView.renderingState !== RenderingStates.FINISHED) { - pageView.reset(); - } - } - } - _cancelRendering() { - for (const pageView of this._pages) { - pageView.cancelRendering(); - } - } - async #ensurePdfPageLoaded(pageView) { - if (pageView.pdfPage) { - return pageView.pdfPage; - } - try { - const pdfPage = await this.pdfDocument.getPage(pageView.id); - if (!pageView.pdfPage) { - pageView.setPdfPage(pdfPage); - } - return pdfPage; - } catch (reason) { - console.error("Unable to get page for page view", reason); - return null; - } - } - #getScrollAhead(visible) { - if (visible.first?.id === 1) { - return true; - } else if (visible.last?.id === this.pagesCount) { - return false; - } - switch (this._scrollMode) { - case ScrollMode.PAGE: - return this.#scrollModePageState.scrollDown; - case ScrollMode.HORIZONTAL: - return this.scroll.right; - } - return this.scroll.down; - } - forceRendering(currentlyVisiblePages) { - const visiblePages = currentlyVisiblePages || this._getVisiblePages(); - const scrollAhead = this.#getScrollAhead(visiblePages); - const preRenderExtra = this._spreadMode !== SpreadMode.NONE && this._scrollMode !== ScrollMode.HORIZONTAL; - const pageView = this.renderingQueue.getHighestPriority(visiblePages, this._pages, scrollAhead, preRenderExtra); - if (pageView) { - this.#ensurePdfPageLoaded(pageView).then(() => { - this.renderingQueue.renderView(pageView); - }); - return true; - } - return false; - } - get hasEqualPageSizes() { - const firstPageView = this._pages[0]; - for (let i = 1, ii = this._pages.length; i < ii; ++i) { - const pageView = this._pages[i]; - if (pageView.width !== firstPageView.width || pageView.height !== firstPageView.height) { - return false; - } - } - return true; - } - getPagesOverview() { - let initialOrientation; - return this._pages.map(pageView => { - const viewport = pageView.pdfPage.getViewport({ - scale: 1 - }); - const orientation = isPortraitOrientation(viewport); - if (initialOrientation === undefined) { - initialOrientation = orientation; - } else if (this.enablePrintAutoRotate && orientation !== initialOrientation) { - return { - width: viewport.height, - height: viewport.width, - rotation: (viewport.rotation - 90) % 360 - }; - } - return { - width: viewport.width, - height: viewport.height, - rotation: viewport.rotation - }; - }); - } - get optionalContentConfigPromise() { - if (!this.pdfDocument) { - return Promise.resolve(null); - } - if (!this._optionalContentConfigPromise) { - console.error("optionalContentConfigPromise: Not initialized yet."); - return this.pdfDocument.getOptionalContentConfig({ - intent: "display" - }); - } - return this._optionalContentConfigPromise; - } - set optionalContentConfigPromise(promise) { - if (!(promise instanceof Promise)) { - throw new Error(`Invalid optionalContentConfigPromise: ${promise}`); - } - if (!this.pdfDocument) { - return; - } - if (!this._optionalContentConfigPromise) { - return; - } - this._optionalContentConfigPromise = promise; - this.refresh(false, { - optionalContentConfigPromise: promise - }); - this.eventBus.dispatch("optionalcontentconfigchanged", { - source: this, - promise - }); - } - get scrollMode() { - return this._scrollMode; - } - set scrollMode(mode) { - if (this._scrollMode === mode) { - return; - } - if (!isValidScrollMode(mode)) { - throw new Error(`Invalid scroll mode: ${mode}`); - } - if (this.pagesCount > PagesCountLimit.FORCE_SCROLL_MODE_PAGE) { - return; - } - this._previousScrollMode = this._scrollMode; - this._scrollMode = mode; - this.eventBus.dispatch("scrollmodechanged", { - source: this, - mode - }); - this._updateScrollMode(this._currentPageNumber); - } - _updateScrollMode(pageNumber = null) { - const scrollMode = this._scrollMode, - viewer = this.viewer; - viewer.classList.toggle("scrollHorizontal", scrollMode === ScrollMode.HORIZONTAL); - viewer.classList.toggle("scrollWrapped", scrollMode === ScrollMode.WRAPPED); - if (!this.pdfDocument || !pageNumber) { - return; - } - if (scrollMode === ScrollMode.PAGE) { - this.#ensurePageViewVisible(); - } else if (this._previousScrollMode === ScrollMode.PAGE) { - this._updateSpreadMode(); - } - if (this._currentScaleValue && isNaN(this._currentScaleValue)) { - this.#setScale(this._currentScaleValue, { - noScroll: true - }); - } - this._setCurrentPageNumber(pageNumber, true); - this.update(); - } - get spreadMode() { - return this._spreadMode; - } - set spreadMode(mode) { - if (this._spreadMode === mode) { - return; - } - if (!isValidSpreadMode(mode)) { - throw new Error(`Invalid spread mode: ${mode}`); - } - this._spreadMode = mode; - this.eventBus.dispatch("spreadmodechanged", { - source: this, - mode - }); - this._updateSpreadMode(this._currentPageNumber); - } - _updateSpreadMode(pageNumber = null) { - if (!this.pdfDocument) { - return; - } - const viewer = this.viewer, - pages = this._pages; - if (this._scrollMode === ScrollMode.PAGE) { - this.#ensurePageViewVisible(); - } else { - viewer.textContent = ""; - if (this._spreadMode === SpreadMode.NONE) { - for (const pageView of this._pages) { - viewer.append(pageView.div); - } - } else { - const parity = this._spreadMode - 1; - let spread = null; - for (let i = 0, ii = pages.length; i < ii; ++i) { - if (spread === null) { - spread = document.createElement("div"); - spread.className = "spread"; - viewer.append(spread); - } else if (i % 2 === parity) { - spread = spread.cloneNode(false); - viewer.append(spread); - } - spread.append(pages[i].div); - } - } - } - if (!pageNumber) { - return; - } - if (this._currentScaleValue && isNaN(this._currentScaleValue)) { - this.#setScale(this._currentScaleValue, { - noScroll: true - }); - } - this._setCurrentPageNumber(pageNumber, true); - this.update(); - } - _getPageAdvance(currentPageNumber, previous = false) { - switch (this._scrollMode) { - case ScrollMode.WRAPPED: - { - const { - views - } = this._getVisiblePages(), - pageLayout = new Map(); - for (const { - id, - y, - percent, - widthPercent - } of views) { - if (percent === 0 || widthPercent < 100) { - continue; - } - let yArray = pageLayout.get(y); - if (!yArray) { - pageLayout.set(y, yArray ||= []); - } - yArray.push(id); - } - for (const yArray of pageLayout.values()) { - const currentIndex = yArray.indexOf(currentPageNumber); - if (currentIndex === -1) { - continue; - } - const numPages = yArray.length; - if (numPages === 1) { - break; - } - if (previous) { - for (let i = currentIndex - 1, ii = 0; i >= ii; i--) { - const currentId = yArray[i], - expectedId = yArray[i + 1] - 1; - if (currentId < expectedId) { - return currentPageNumber - expectedId; - } - } - } else { - for (let i = currentIndex + 1, ii = numPages; i < ii; i++) { - const currentId = yArray[i], - expectedId = yArray[i - 1] + 1; - if (currentId > expectedId) { - return expectedId - currentPageNumber; - } - } - } - if (previous) { - const firstId = yArray[0]; - if (firstId < currentPageNumber) { - return currentPageNumber - firstId + 1; - } - } else { - const lastId = yArray[numPages - 1]; - if (lastId > currentPageNumber) { - return lastId - currentPageNumber + 1; - } - } - break; - } - break; - } - case ScrollMode.HORIZONTAL: - { - break; - } - case ScrollMode.PAGE: - case ScrollMode.VERTICAL: - { - if (this._spreadMode === SpreadMode.NONE) { - break; - } - const parity = this._spreadMode - 1; - if (previous && currentPageNumber % 2 !== parity) { - break; - } else if (!previous && currentPageNumber % 2 === parity) { - break; - } - const { - views - } = this._getVisiblePages(), - expectedId = previous ? currentPageNumber - 1 : currentPageNumber + 1; - for (const { - id, - percent, - widthPercent - } of views) { - if (id !== expectedId) { - continue; - } - if (percent > 0 && widthPercent === 100) { - return 2; - } - break; - } - break; - } - } - return 1; - } - nextPage() { - const currentPageNumber = this._currentPageNumber, - pagesCount = this.pagesCount; - if (currentPageNumber >= pagesCount) { - return false; - } - const advance = this._getPageAdvance(currentPageNumber, false) || 1; - this.currentPageNumber = Math.min(currentPageNumber + advance, pagesCount); - return true; - } - previousPage() { - const currentPageNumber = this._currentPageNumber; - if (currentPageNumber <= 1) { - return false; - } - const advance = this._getPageAdvance(currentPageNumber, true) || 1; - this.currentPageNumber = Math.max(currentPageNumber - advance, 1); - return true; - } - updateScale({ - drawingDelay, - scaleFactor = null, - steps = null, - origin - }) { - if (steps === null && scaleFactor === null) { - throw new Error("Invalid updateScale options: either `steps` or `scaleFactor` must be provided."); - } - if (!this.pdfDocument) { - return; - } - let newScale = this._currentScale; - if (scaleFactor > 0 && scaleFactor !== 1) { - newScale = Math.round(newScale * scaleFactor * 100) / 100; - } else if (steps) { - const delta = steps > 0 ? DEFAULT_SCALE_DELTA : 1 / DEFAULT_SCALE_DELTA; - const round = steps > 0 ? Math.ceil : Math.floor; - steps = Math.abs(steps); - do { - newScale = round((newScale * delta).toFixed(2) * 10) / 10; - } while (--steps > 0); - } - newScale = Math.max(MIN_SCALE, Math.min(MAX_SCALE, newScale)); - this.#setScale(newScale, { - noScroll: false, - drawingDelay, - origin - }); - } - increaseScale(options = {}) { - this.updateScale({ - ...options, - steps: options.steps ?? 1 - }); - } - decreaseScale(options = {}) { - this.updateScale({ - ...options, - steps: -(options.steps ?? 1) - }); - } - #updateContainerHeightCss(height = this.container.clientHeight) { - if (height !== this.#previousContainerHeight) { - this.#previousContainerHeight = height; - docStyle.setProperty("--viewer-container-height", `${height}px`); - } - } - #resizeObserverCallback(entries) { - for (const entry of entries) { - if (entry.target === this.container) { - this.#updateContainerHeightCss(Math.floor(entry.borderBoxSize[0].blockSize)); - this.#containerTopLeft = null; - break; - } - } - } - get containerTopLeft() { - return this.#containerTopLeft ||= [this.container.offsetTop, this.container.offsetLeft]; - } - #cleanupSwitchAnnotationEditorMode() { - this.#switchAnnotationEditorModeAC?.abort(); - this.#switchAnnotationEditorModeAC = null; - if (this.#switchAnnotationEditorModeTimeoutId !== null) { - clearTimeout(this.#switchAnnotationEditorModeTimeoutId); - this.#switchAnnotationEditorModeTimeoutId = null; - } - } - get annotationEditorMode() { - return this.#annotationEditorUIManager ? this.#annotationEditorMode : AnnotationEditorType.DISABLE; - } - set annotationEditorMode({ - mode, - editId = null, - isFromKeyboard = false - }) { - if (!this.#annotationEditorUIManager) { - throw new Error(`The AnnotationEditor is not enabled.`); - } - if (this.#annotationEditorMode === mode) { - return; - } - if (!isValidAnnotationEditorMode(mode)) { - throw new Error(`Invalid AnnotationEditor mode: ${mode}`); - } - if (!this.pdfDocument) { - return; - } - if (mode === AnnotationEditorType.STAMP) { - this.#mlManager?.loadModel("altText"); - } - const { - eventBus - } = this; - const updater = () => { - this.#cleanupSwitchAnnotationEditorMode(); - this.#annotationEditorMode = mode; - this.#annotationEditorUIManager.updateMode(mode, editId, isFromKeyboard); - eventBus.dispatch("annotationeditormodechanged", { - source: this, - mode - }); - }; - if (mode === AnnotationEditorType.NONE || this.#annotationEditorMode === AnnotationEditorType.NONE) { - const isEditing = mode !== AnnotationEditorType.NONE; - if (!isEditing) { - this.pdfDocument.annotationStorage.resetModifiedIds(); - } - for (const pageView of this._pages) { - pageView.toggleEditingMode(isEditing); - } - const idsToRefresh = this.#switchToEditAnnotationMode(); - if (isEditing && idsToRefresh) { - this.#cleanupSwitchAnnotationEditorMode(); - this.#switchAnnotationEditorModeAC = new AbortController(); - const signal = AbortSignal.any([this.#eventAbortController.signal, this.#switchAnnotationEditorModeAC.signal]); - eventBus._on("pagerendered", ({ - pageNumber - }) => { - idsToRefresh.delete(pageNumber); - if (idsToRefresh.size === 0) { - this.#switchAnnotationEditorModeTimeoutId = setTimeout(updater, 0); - } - }, { - signal - }); - return; - } - } - updater(); - } - refresh(noUpdate = false, updateArgs = Object.create(null)) { - if (!this.pdfDocument) { - return; - } - for (const pageView of this._pages) { - pageView.update(updateArgs); - } - if (this.#scaleTimeoutId !== null) { - clearTimeout(this.#scaleTimeoutId); - this.#scaleTimeoutId = null; - } - if (!noUpdate) { - this.update(); - } - } -} - -;// ./web/pdf_single_page_viewer.js - - -class PDFSinglePageViewer extends PDFViewer { - _resetView() { - super._resetView(); - this._scrollMode = ScrollMode.PAGE; - this._spreadMode = SpreadMode.NONE; - } - set scrollMode(mode) {} - _updateScrollMode() {} - set spreadMode(mode) {} - _updateSpreadMode() {} -} - -;// ./web/pdf_viewer.component.js - - - - - - - - - - - - - - - -const pdfjsVersion = "4.10.38"; -const pdfjsBuild = "f9bea397f"; - -var __webpack_exports__AnnotationLayerBuilder = __webpack_exports__.AnnotationLayerBuilder; -var __webpack_exports__DownloadManager = __webpack_exports__.DownloadManager; -var __webpack_exports__EventBus = __webpack_exports__.EventBus; -var __webpack_exports__FindState = __webpack_exports__.FindState; -var __webpack_exports__GenericL10n = __webpack_exports__.GenericL10n; -var __webpack_exports__LinkTarget = __webpack_exports__.LinkTarget; -var __webpack_exports__PDFFindController = __webpack_exports__.PDFFindController; -var __webpack_exports__PDFHistory = __webpack_exports__.PDFHistory; -var __webpack_exports__PDFLinkService = __webpack_exports__.PDFLinkService; -var __webpack_exports__PDFPageView = __webpack_exports__.PDFPageView; -var __webpack_exports__PDFScriptingManager = __webpack_exports__.PDFScriptingManager; -var __webpack_exports__PDFSinglePageViewer = __webpack_exports__.PDFSinglePageViewer; -var __webpack_exports__PDFViewer = __webpack_exports__.PDFViewer; -var __webpack_exports__ProgressBar = __webpack_exports__.ProgressBar; -var __webpack_exports__RenderingStates = __webpack_exports__.RenderingStates; -var __webpack_exports__ScrollMode = __webpack_exports__.ScrollMode; -var __webpack_exports__SimpleLinkService = __webpack_exports__.SimpleLinkService; -var __webpack_exports__SpreadMode = __webpack_exports__.SpreadMode; -var __webpack_exports__StructTreeLayerBuilder = __webpack_exports__.StructTreeLayerBuilder; -var __webpack_exports__TextLayerBuilder = __webpack_exports__.TextLayerBuilder; -var __webpack_exports__XfaLayerBuilder = __webpack_exports__.XfaLayerBuilder; -var __webpack_exports__parseQueryString = __webpack_exports__.parseQueryString; -export { __webpack_exports__AnnotationLayerBuilder as AnnotationLayerBuilder, __webpack_exports__DownloadManager as DownloadManager, __webpack_exports__EventBus as EventBus, __webpack_exports__FindState as FindState, __webpack_exports__GenericL10n as GenericL10n, __webpack_exports__LinkTarget as LinkTarget, __webpack_exports__PDFFindController as PDFFindController, __webpack_exports__PDFHistory as PDFHistory, __webpack_exports__PDFLinkService as PDFLinkService, __webpack_exports__PDFPageView as PDFPageView, __webpack_exports__PDFScriptingManager as PDFScriptingManager, __webpack_exports__PDFSinglePageViewer as PDFSinglePageViewer, __webpack_exports__PDFViewer as PDFViewer, __webpack_exports__ProgressBar as ProgressBar, __webpack_exports__RenderingStates as RenderingStates, __webpack_exports__ScrollMode as ScrollMode, __webpack_exports__SimpleLinkService as SimpleLinkService, __webpack_exports__SpreadMode as SpreadMode, __webpack_exports__StructTreeLayerBuilder as StructTreeLayerBuilder, __webpack_exports__TextLayerBuilder as TextLayerBuilder, __webpack_exports__XfaLayerBuilder as XfaLayerBuilder, __webpack_exports__parseQueryString as parseQueryString }; - -//# sourceMappingURL=pdf_viewer.mjs.map \ No newline at end of file diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/tailwindcss/README.md b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/tailwindcss/README.md deleted file mode 100644 index 69fb53bf322..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/tailwindcss/README.md +++ /dev/null @@ -1,7 +0,0 @@ -tailwindcss version 4.0.3 -https://github.com/tailwindlabs/tailwindcss -License: MIT - -This template uses only `preflight.css`, the CSS reset stylesheet from Tailwind. For simplicity, this template doesn't use a complete deployment of Tailwind. If you want to use the full Tailwind library, remove `preflight.css` and reference the full version of Tailwind. - -To update, replace the `preflight.css` file with the one in an updated build from https://www.npmjs.com/package/tailwindcss diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/tailwindcss/dist/preflight.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/tailwindcss/dist/preflight.css deleted file mode 100644 index 178c881dd23..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/wwwroot/lib/tailwindcss/dist/preflight.css +++ /dev/null @@ -1,383 +0,0 @@ -/* - 1. Prevent padding and border from affecting element width. (https://github.com/mozdevs/cssremedy/issues/4) - 2. Remove default margins and padding - 3. Reset all borders. -*/ - -*, -::after, -::before, -::backdrop, -::file-selector-button { - box-sizing: border-box; /* 1 */ - margin: 0; /* 2 */ - padding: 0; /* 2 */ - border: 0 solid; /* 3 */ -} - -/* - 1. Use a consistent sensible line-height in all browsers. - 2. Prevent adjustments of font size after orientation changes in iOS. - 3. Use a more readable tab size. - 4. Use the user's configured `sans` font-family by default. - 5. Use the user's configured `sans` font-feature-settings by default. - 6. Use the user's configured `sans` font-variation-settings by default. - 7. Disable tap highlights on iOS. -*/ - -html, -:host { - line-height: 1.5; /* 1 */ - -webkit-text-size-adjust: 100%; /* 2 */ - tab-size: 4; /* 3 */ - font-family: var( - --default-font-family, - ui-sans-serif, - system-ui, - sans-serif, - 'Apple Color Emoji', - 'Segoe UI Emoji', - 'Segoe UI Symbol', - 'Noto Color Emoji' - ); /* 4 */ - font-feature-settings: var(--default-font-feature-settings, normal); /* 5 */ - font-variation-settings: var(--default-font-variation-settings, normal); /* 6 */ - -webkit-tap-highlight-color: transparent; /* 7 */ -} - -/* - Inherit line-height from `html` so users can set them as a class directly on the `html` element. -*/ - -body { - line-height: inherit; -} - -/* - 1. Add the correct height in Firefox. - 2. Correct the inheritance of border color in Firefox. (https://bugzilla.mozilla.org/show_bug.cgi?id=190655) - 3. Reset the default border style to a 1px solid border. -*/ - -hr { - height: 0; /* 1 */ - color: inherit; /* 2 */ - border-top-width: 1px; /* 3 */ -} - -/* - Add the correct text decoration in Chrome, Edge, and Safari. -*/ - -abbr:where([title]) { - -webkit-text-decoration: underline dotted; - text-decoration: underline dotted; -} - -/* - Remove the default font size and weight for headings. -*/ - -h1, -h2, -h3, -h4, -h5, -h6 { - font-size: inherit; - font-weight: inherit; -} - -/* - Reset links to optimize for opt-in styling instead of opt-out. -*/ - -a { - color: inherit; - -webkit-text-decoration: inherit; - text-decoration: inherit; -} - -/* - Add the correct font weight in Edge and Safari. -*/ - -b, -strong { - font-weight: bolder; -} - -/* - 1. Use the user's configured `mono` font-family by default. - 2. Use the user's configured `mono` font-feature-settings by default. - 3. Use the user's configured `mono` font-variation-settings by default. - 4. Correct the odd `em` font sizing in all browsers. -*/ - -code, -kbd, -samp, -pre { - font-family: var( - --default-mono-font-family, - ui-monospace, - SFMono-Regular, - Menlo, - Monaco, - Consolas, - 'Liberation Mono', - 'Courier New', - monospace - ); /* 4 */ - font-feature-settings: var(--default-mono-font-feature-settings, normal); /* 5 */ - font-variation-settings: var(--default-mono-font-variation-settings, normal); /* 6 */ - font-size: 1em; /* 4 */ -} - -/* - Add the correct font size in all browsers. -*/ - -small { - font-size: 80%; -} - -/* - Prevent `sub` and `sup` elements from affecting the line height in all browsers. -*/ - -sub, -sup { - font-size: 75%; - line-height: 0; - position: relative; - vertical-align: baseline; -} - -sub { - bottom: -0.25em; -} - -sup { - top: -0.5em; -} - -/* - 1. Remove text indentation from table contents in Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=999088, https://bugs.webkit.org/show_bug.cgi?id=201297) - 2. Correct table border color inheritance in all Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=935729, https://bugs.webkit.org/show_bug.cgi?id=195016) - 3. Remove gaps between table borders by default. -*/ - -table { - text-indent: 0; /* 1 */ - border-color: inherit; /* 2 */ - border-collapse: collapse; /* 3 */ -} - -/* - Use the modern Firefox focus style for all focusable elements. -*/ - -:-moz-focusring { - outline: auto; -} - -/* - Add the correct vertical alignment in Chrome and Firefox. -*/ - -progress { - vertical-align: baseline; -} - -/* - Add the correct display in Chrome and Safari. -*/ - -summary { - display: list-item; -} - -/* - Make lists unstyled by default. -*/ - -ol, -ul, -menu { - list-style: none; -} - -/* - 1. Make replaced elements `display: block` by default. (https://github.com/mozdevs/cssremedy/issues/14) - 2. Add `vertical-align: middle` to align replaced elements more sensibly by default. (https://github.com/jensimmons/cssremedy/issues/14#issuecomment-634934210) - This can trigger a poorly considered lint error in some tools but is included by design. -*/ - -img, -svg, -video, -canvas, -audio, -iframe, -embed, -object { - display: block; /* 1 */ - vertical-align: middle; /* 2 */ -} - -/* - Constrain images and videos to the parent width and preserve their intrinsic aspect ratio. (https://github.com/mozdevs/cssremedy/issues/14) -*/ - -img, -video { - max-width: 100%; - height: auto; -} - -/* - 1. Inherit font styles in all browsers. - 2. Remove border radius in all browsers. - 3. Remove background color in all browsers. - 4. Ensure consistent opacity for disabled states in all browsers. -*/ - -button, -input, -select, -optgroup, -textarea, -::file-selector-button { - font: inherit; /* 1 */ - font-feature-settings: inherit; /* 1 */ - font-variation-settings: inherit; /* 1 */ - letter-spacing: inherit; /* 1 */ - color: inherit; /* 1 */ - border-radius: 0; /* 2 */ - background-color: transparent; /* 3 */ - opacity: 1; /* 4 */ -} - -/* - Restore default font weight. -*/ - -:where(select:is([multiple], [size])) optgroup { - font-weight: bolder; -} - -/* - Restore indentation. -*/ - -:where(select:is([multiple], [size])) optgroup option { - padding-inline-start: 20px; -} - -/* - Restore space after button. -*/ - -::file-selector-button { - margin-inline-end: 4px; -} - -/* - 1. Reset the default placeholder opacity in Firefox. (https://github.com/tailwindlabs/tailwindcss/issues/3300) - 2. Set the default placeholder color to a semi-transparent version of the current text color. -*/ - -::placeholder { - opacity: 1; /* 1 */ - color: color-mix(in oklab, currentColor 50%, transparent); /* 2 */ -} - -/* - Prevent resizing textareas horizontally by default. -*/ - -textarea { - resize: vertical; -} - -/* - Remove the inner padding in Chrome and Safari on macOS. -*/ - -::-webkit-search-decoration { - -webkit-appearance: none; -} - -/* - 1. Ensure date/time inputs have the same height when empty in iOS Safari. - 2. Ensure text alignment can be changed on date/time inputs in iOS Safari. -*/ - -::-webkit-date-and-time-value { - min-height: 1lh; /* 1 */ - text-align: inherit; /* 2 */ -} - -/* - Prevent height from changing on date/time inputs in macOS Safari when the input is set to `display: block`. -*/ - -::-webkit-datetime-edit { - display: inline-flex; -} - -/* - Remove excess padding from pseudo-elements in date/time inputs to ensure consistent height across browsers. -*/ - -::-webkit-datetime-edit-fields-wrapper { - padding: 0; -} - -::-webkit-datetime-edit, -::-webkit-datetime-edit-year-field, -::-webkit-datetime-edit-month-field, -::-webkit-datetime-edit-day-field, -::-webkit-datetime-edit-hour-field, -::-webkit-datetime-edit-minute-field, -::-webkit-datetime-edit-second-field, -::-webkit-datetime-edit-millisecond-field, -::-webkit-datetime-edit-meridiem-field { - padding-block: 0; -} - -/* - Remove the additional `:invalid` styles in Firefox. (https://github.com/mozilla/gecko-dev/blob/2f9eacd9d3d995c937b4251a5557d95d494c9be1/layout/style/res/forms.css#L728-L737) -*/ - -:-moz-ui-invalid { - box-shadow: none; -} - -/* - Correct the inability to style the border radius in iOS Safari. -*/ - -button, -input:where([type='button'], [type='reset'], [type='submit']), -::file-selector-button { - appearance: button; -} - -/* - Correct the cursor style of increment and decrement buttons in Safari. -*/ - -::-webkit-inner-spin-button, -::-webkit-outer-spin-button { - height: auto; -} - -/* - Make elements with the HTML hidden attribute stay hidden by default. -*/ - -[hidden]:where(:not([hidden='until-found'])) { - display: none !important; -} diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/Data/Example_Emergency_Survival_Kit.pdf b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/Data/Example_Emergency_Survival_Kit.pdf deleted file mode 100644 index 94625f0e0e0617c1324cf5243b06d0e8a2da6177..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 153539 zcmdSC1yohr8aBM?5a|YC(;b^`knZlTO-OeONJ|MQAt`Cl-61W~og#uD4GM_Vzd?`U zIh;H0_nkAof7~&2Y!>^S^Q}3b`K~$FdZ1Dkmt+Dlb0AZVZhU%=3<9zO9Zc^b3ka~N zTf5qVfwU5KU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q zr&h>m>wd=P2y>+DYj1fj6*3#sAYm=Bm655wjBs9lrZrvOuD$vap0=$m{L;kHCq(YG zMpuui&}rmh{+i!cQe=9-pR7O$OkWtEd$Tcmbjt^nxQLs)CQ31S_AG-vL-;qC_h3`H z{t-2c(BWg#e&b&kg@sIW*;IhfPQa5h7~G3qs)VdSs=hHjJ>5%2{sFd{h9Hr^H2Sn@ zR%OVrx6n+?9U@h`c4GmRLTBMx((b(%?2c61^lO|$opC-95fRZ73H%%Ms<@?umXtM7 zjg_qSNUX4@fdw4_aeI0*koC)Vu4*fT)IY+!q9}=_AdK!!Q(4j^q@|j!gUHX%kDDyI zd~wlA_HKjV`ZteVOx33 zjQ^i7DCVmO0QR5df#K-R3S;~~6I7t&|1J-?`h2eKIut)%s6pEpEqy`pcHi+57=RRP zZ8(0-OL8bh_Dn>kCEmL>RB@X^NLjA(p{{W!zUzMTPO@kIoR<5M`84LJVbeNU0P1zq z4^O(t7vkAuH@G=26!_ToGp8Xef3sV;1$v=+Rg=q 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - return apply(func, thisArg, args); - }; -} -/** - * Creates a new function that constructs an instance of the given constructor function with the provided arguments. - * - * @param func - The constructor function to be wrapped and called. - * @returns A new function that constructs an instance of the given constructor function with the provided arguments. - */ -function unconstruct(func) { - return function () { - for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - args[_key2] = arguments[_key2]; - } - return construct(func, args); - }; -} -/** - * Add properties to a lookup table - * - * @param set - The set to which elements will be added. - * @param array - The array containing elements to be added to the set. - * @param transformCaseFunc - An optional function to transform the case of each element before adding to the set. - * @returns The modified set with added elements. - */ -function addToSet(set, array) { - let transformCaseFunc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : stringToLowerCase; - if (setPrototypeOf) { - // Make 'in' and truthy checks like Boolean(set.constructor) - // independent of any properties defined on Object.prototype. - // Prevent prototype setters from intercepting set as a this value. - setPrototypeOf(set, null); - } - let l = array.length; - while (l--) { - let element = array[l]; - if (typeof element === 'string') { - const lcElement = transformCaseFunc(element); - if (lcElement !== element) { - // Config presets (e.g. tags.js, attrs.js) are immutable. - if (!isFrozen(array)) { - array[l] = lcElement; - } - element = lcElement; - } - } - set[element] = true; - } - return set; -} -/** - * Clean up an array to harden against CSPP - * - * @param array - The array to be cleaned. - * @returns The cleaned version of the array - */ -function cleanArray(array) { - for (let index = 0; index < array.length; index++) { - const isPropertyExist = objectHasOwnProperty(array, index); - if (!isPropertyExist) { - array[index] = null; - } - } - return array; -} -/** - * Shallow clone an object - * - * @param object - The object to be cloned. - * @returns A new object that copies the original. - */ -function clone(object) { - const newObject = create(null); - for (const [property, value] of entries(object)) { - const isPropertyExist = objectHasOwnProperty(object, property); - if (isPropertyExist) { - if (Array.isArray(value)) { - newObject[property] = cleanArray(value); - } else if (value && typeof value === 'object' && value.constructor === Object) { - newObject[property] = clone(value); - } else { - newObject[property] = value; - } - } - } - return newObject; -} -/** - * This method automatically checks if the prop is function or getter and behaves accordingly. - * - * @param object - The object to look up the getter function in its prototype chain. - * @param prop - The property name for which to find the getter function. - * @returns The getter function found in the prototype chain or a fallback function. - */ -function lookupGetter(object, prop) { - while (object !== null) { - const desc = getOwnPropertyDescriptor(object, prop); - if (desc) { - if (desc.get) { - return unapply(desc.get); - } - if (typeof desc.value === 'function') { - return unapply(desc.value); - } - } - object = getPrototypeOf(object); - } - function fallbackValue() { - return null; - } - return fallbackValue; -} - -const html$1 = freeze(['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'content', 'data', 'datalist', 'dd', 'decorator', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meter', 'nav', 'nobr', 'ol', 'optgroup', 'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'section', 'select', 'shadow', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr']); -const svg$1 = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']); -const svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feDropShadow', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']); -// List of SVG elements that are disallowed by default. -// We still need to know them so that we can do namespace -// checks properly in case one wants to add them to -// allow-list. -const svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignobject', 'hatch', 'hatchpath', 'mesh', 'meshgradient', 'meshpatch', 'meshrow', 'missing-glyph', 'script', 'set', 'solidcolor', 'unknown', 'use']); -const mathMl$1 = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover', 'mprescripts']); -// Similarly to SVG, we want to know all MathML elements, -// even those that we disallow by default. -const mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']); -const text = freeze(['#text']); - -const html = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'nonce', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'pattern', 'placeholder', 'playsinline', 'popover', 'popovertarget', 'popovertargetaction', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'wrap', 'xmlns', 'slot']); -const svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'amplitude', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dur', 'edgemode', 'elevation', 'end', 'exponent', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'intercept', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'slope', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'tablevalues', 'targetx', 'targety', 'transform', 'transform-origin', 'text-anchor', 'text-decoration', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']); -const mathMl = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnsalign', 'columnlines', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lspace', 'lquote', 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset', 'width', 'xmlns']); -const xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']); - -// eslint-disable-next-line unicorn/better-regex -const MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode -const ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm); -const TMPLIT_EXPR = seal(/\$\{[\w\W]*/gm); // eslint-disable-line unicorn/better-regex -const DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]+$/); // eslint-disable-line no-useless-escape -const ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape -const IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i // eslint-disable-line no-useless-escape -); -const IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i); -const ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex -); -const DOCTYPE_NAME = seal(/^html$/i); -const CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i); - -var EXPRESSIONS = /*#__PURE__*/Object.freeze({ - __proto__: null, - ARIA_ATTR: ARIA_ATTR, - ATTR_WHITESPACE: ATTR_WHITESPACE, - CUSTOM_ELEMENT: CUSTOM_ELEMENT, - DATA_ATTR: DATA_ATTR, - DOCTYPE_NAME: DOCTYPE_NAME, - ERB_EXPR: ERB_EXPR, - IS_ALLOWED_URI: IS_ALLOWED_URI, - IS_SCRIPT_OR_DATA: IS_SCRIPT_OR_DATA, - MUSTACHE_EXPR: MUSTACHE_EXPR, - TMPLIT_EXPR: TMPLIT_EXPR -}); - -/* eslint-disable @typescript-eslint/indent */ -// https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType -const NODE_TYPE = { - element: 1, - attribute: 2, - text: 3, - cdataSection: 4, - entityReference: 5, - // Deprecated - entityNode: 6, - // Deprecated - progressingInstruction: 7, - comment: 8, - document: 9, - documentType: 10, - documentFragment: 11, - notation: 12 // Deprecated -}; -const getGlobal = function getGlobal() { - return typeof window === 'undefined' ? null : window; -}; -/** - * Creates a no-op policy for internal use only. - * Don't export this function outside this module! - * @param trustedTypes The policy factory. - * @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix). - * @return The policy created (or null, if Trusted Types - * are not supported or creating the policy failed). - */ -const _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, purifyHostElement) { - if (typeof trustedTypes !== 'object' || typeof trustedTypes.createPolicy !== 'function') { - return null; - } - // Allow the callers to control the unique policy name - // by adding a data-tt-policy-suffix to the script element with the DOMPurify. - // Policy creation with duplicate names throws in Trusted Types. - let suffix = null; - const ATTR_NAME = 'data-tt-policy-suffix'; - if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) { - suffix = purifyHostElement.getAttribute(ATTR_NAME); - } - const policyName = 'dompurify' + (suffix ? '#' + suffix : ''); - try { - return trustedTypes.createPolicy(policyName, { - createHTML(html) { - return html; - }, - createScriptURL(scriptUrl) { - return scriptUrl; - } - }); - } catch (_) { - // Policy creation failed (most likely another DOMPurify script has - // already run). Skip creating the policy, as this will only cause errors - // if TT are enforced. - console.warn('TrustedTypes policy ' + policyName + ' could not be created.'); - return null; - } -}; -const _createHooksMap = function _createHooksMap() { - return { - afterSanitizeAttributes: [], - afterSanitizeElements: [], - afterSanitizeShadowDOM: [], - beforeSanitizeAttributes: [], - beforeSanitizeElements: [], - beforeSanitizeShadowDOM: [], - uponSanitizeAttribute: [], - uponSanitizeElement: [], - uponSanitizeShadowNode: [] - }; -}; -function createDOMPurify() { - let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal(); - const DOMPurify = root => createDOMPurify(root); - DOMPurify.version = '3.2.4'; - DOMPurify.removed = []; - if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) { - // Not running in a browser, provide a factory function - // so that you can pass your own Window - DOMPurify.isSupported = false; - return DOMPurify; - } - let { - document - } = window; - const originalDocument = document; - const currentScript = originalDocument.currentScript; - const { - DocumentFragment, - HTMLTemplateElement, - Node, - Element, - NodeFilter, - NamedNodeMap = window.NamedNodeMap || window.MozNamedAttrMap, - HTMLFormElement, - DOMParser, - trustedTypes - } = window; - const ElementPrototype = Element.prototype; - const cloneNode = lookupGetter(ElementPrototype, 'cloneNode'); - const remove = lookupGetter(ElementPrototype, 'remove'); - const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling'); - const getChildNodes = lookupGetter(ElementPrototype, 'childNodes'); - const getParentNode = lookupGetter(ElementPrototype, 'parentNode'); - // As per issue #47, the web-components registry is inherited by a - // new document created via createHTMLDocument. As per the spec - // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries) - // a new empty registry is used when creating a template contents owner - // document, so we use that as our parent document to ensure nothing - // is inherited. - if (typeof HTMLTemplateElement === 'function') { - const template = document.createElement('template'); - if (template.content && template.content.ownerDocument) { - document = template.content.ownerDocument; - } - } - let trustedTypesPolicy; - let emptyHTML = ''; - const { - implementation, - createNodeIterator, - createDocumentFragment, - getElementsByTagName - } = document; - const { - importNode - } = originalDocument; - let hooks = _createHooksMap(); - /** - * Expose whether this browser supports running the full DOMPurify. - */ - DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined; - const { - MUSTACHE_EXPR, - ERB_EXPR, - TMPLIT_EXPR, - DATA_ATTR, - ARIA_ATTR, - IS_SCRIPT_OR_DATA, - ATTR_WHITESPACE, - CUSTOM_ELEMENT - } = EXPRESSIONS; - let { - IS_ALLOWED_URI: IS_ALLOWED_URI$1 - } = EXPRESSIONS; - /** - * We consider the elements and attributes below to be safe. Ideally - * don't add any new ones but feel free to remove unwanted ones. - */ - /* allowed element names */ - let ALLOWED_TAGS = null; - const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]); - /* Allowed attribute names */ - let ALLOWED_ATTR = null; - const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]); - /* - * Configure how DOMPurify should handle custom elements and their attributes as well as customized built-in elements. - * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements) - * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list) - * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`. - */ - let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, { - tagNameCheck: { - writable: true, - configurable: false, - enumerable: true, - value: null - }, - attributeNameCheck: { - writable: true, - configurable: false, - enumerable: true, - value: null - }, - allowCustomizedBuiltInElements: { - writable: true, - configurable: false, - enumerable: true, - value: false - } - })); - /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */ - let FORBID_TAGS = null; - /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */ - let FORBID_ATTR = null; - /* Decide if ARIA attributes are okay */ - let ALLOW_ARIA_ATTR = true; - /* Decide if custom data attributes are okay */ - let ALLOW_DATA_ATTR = true; - /* Decide if unknown protocols are okay */ - let ALLOW_UNKNOWN_PROTOCOLS = false; - /* Decide if self-closing tags in attributes are allowed. - * Usually removed due to a mXSS issue in jQuery 3.0 */ - let ALLOW_SELF_CLOSE_IN_ATTR = true; - /* Output should be safe for common template engines. - * This means, DOMPurify removes data attributes, mustaches and ERB - */ - let SAFE_FOR_TEMPLATES = false; - /* Output should be safe even for XML used within HTML and alike. - * This means, DOMPurify removes comments when containing risky content. - */ - let SAFE_FOR_XML = true; - /* Decide if document with ... should be returned */ - let WHOLE_DOCUMENT = false; - /* Track whether config is already set on this instance of DOMPurify. */ - let SET_CONFIG = false; - /* Decide if all elements (e.g. style, script) must be children of - * document.body. By default, browsers might move them to document.head */ - let FORCE_BODY = false; - /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html - * string (or a TrustedHTML object if Trusted Types are supported). - * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead - */ - let RETURN_DOM = false; - /* Decide if a DOM `DocumentFragment` should be returned, instead of a html - * string (or a TrustedHTML object if Trusted Types are supported) */ - let RETURN_DOM_FRAGMENT = false; - /* Try to return a Trusted Type object instead of a string, return a string in - * case Trusted Types are not supported */ - let RETURN_TRUSTED_TYPE = false; - /* Output should be free from DOM clobbering attacks? - * This sanitizes markups named with colliding, clobberable built-in DOM APIs. - */ - let SANITIZE_DOM = true; - /* Achieve full DOM Clobbering protection by isolating the namespace of named - * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules. - * - * HTML/DOM spec rules that enable DOM Clobbering: - * - Named Access on Window (§7.3.3) - * - DOM Tree Accessors (§3.1.5) - * - Form Element Parent-Child Relations (§4.10.3) - * - Iframe srcdoc / Nested WindowProxies (§4.8.5) - * - HTMLCollection (§4.2.10.2) - * - * Namespace isolation is implemented by prefixing `id` and `name` attributes - * with a constant string, i.e., `user-content-` - */ - let SANITIZE_NAMED_PROPS = false; - const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-'; - /* Keep element content when removing element? */ - let KEEP_CONTENT = true; - /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead - * of importing it into a new Document and returning a sanitized copy */ - let IN_PLACE = false; - /* Allow usage of profiles like html, svg and mathMl */ - let USE_PROFILES = {}; - /* Tags to ignore content of when KEEP_CONTENT is true */ - let FORBID_CONTENTS = null; - const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']); - /* Tags that are safe for data: URIs */ - let DATA_URI_TAGS = null; - const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']); - /* Attributes safe for values like "javascript:" */ - let URI_SAFE_ATTRIBUTES = null; - const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']); - const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML'; - const SVG_NAMESPACE = 'http://www.w3.org/2000/svg'; - const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml'; - /* Document namespace */ - let NAMESPACE = HTML_NAMESPACE; - let IS_EMPTY_INPUT = false; - /* Allowed XHTML+XML namespaces */ - let ALLOWED_NAMESPACES = null; - const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString); - let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']); - let HTML_INTEGRATION_POINTS = addToSet({}, ['annotation-xml']); - // Certain elements are allowed in both SVG and HTML - // namespace. We need to specify them explicitly - // so that they don't get erroneously deleted from - // HTML namespace. - const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']); - /* Parsing of strict XHTML documents */ - let PARSER_MEDIA_TYPE = null; - const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html']; - const DEFAULT_PARSER_MEDIA_TYPE = 'text/html'; - let transformCaseFunc = null; - /* Keep a reference to config to pass to hooks */ - let CONFIG = null; - /* Ideally, do not touch anything below this line */ - /* ______________________________________________ */ - const formElement = document.createElement('form'); - const isRegexOrFunction = function isRegexOrFunction(testValue) { - return testValue instanceof RegExp || testValue instanceof Function; - }; - /** - * _parseConfig - * - * @param cfg optional config literal - */ - // eslint-disable-next-line complexity - const _parseConfig = function _parseConfig() { - let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - if (CONFIG && CONFIG === cfg) { - return; - } - /* Shield configuration object from tampering */ - if (!cfg || typeof cfg !== 'object') { - cfg = {}; - } - /* Shield configuration object from prototype pollution */ - cfg = clone(cfg); - PARSER_MEDIA_TYPE = - // eslint-disable-next-line unicorn/prefer-includes - SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE; - // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is. - transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase; - /* Set configuration parameters */ - ALLOWED_TAGS = objectHasOwnProperty(cfg, 'ALLOWED_TAGS') ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS; - ALLOWED_ATTR = objectHasOwnProperty(cfg, 'ALLOWED_ATTR') ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR; - ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, 'ALLOWED_NAMESPACES') ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES; - URI_SAFE_ATTRIBUTES = objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR, transformCaseFunc) : DEFAULT_URI_SAFE_ATTRIBUTES; - DATA_URI_TAGS = objectHasOwnProperty(cfg, 'ADD_DATA_URI_TAGS') ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS, transformCaseFunc) : DEFAULT_DATA_URI_TAGS; - FORBID_CONTENTS = objectHasOwnProperty(cfg, 'FORBID_CONTENTS') ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS; - FORBID_TAGS = objectHasOwnProperty(cfg, 'FORBID_TAGS') ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : {}; - FORBID_ATTR = objectHasOwnProperty(cfg, 'FORBID_ATTR') ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : {}; - USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES : false; - ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true - ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true - ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false - ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true - SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false - SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true - WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false - RETURN_DOM = cfg.RETURN_DOM || false; // Default false - RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false - RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false - FORCE_BODY = cfg.FORCE_BODY || false; // Default false - SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true - SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false - KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true - IN_PLACE = cfg.IN_PLACE || false; // Default false - IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI; - NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE; - MATHML_TEXT_INTEGRATION_POINTS = cfg.MATHML_TEXT_INTEGRATION_POINTS || MATHML_TEXT_INTEGRATION_POINTS; - HTML_INTEGRATION_POINTS = cfg.HTML_INTEGRATION_POINTS || HTML_INTEGRATION_POINTS; - CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || {}; - if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) { - CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck; - } - if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) { - CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck; - } - if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === 'boolean') { - CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements; - } - if (SAFE_FOR_TEMPLATES) { - ALLOW_DATA_ATTR = false; - } - if (RETURN_DOM_FRAGMENT) { - RETURN_DOM = true; - } - /* Parse profile info */ - if (USE_PROFILES) { - ALLOWED_TAGS = addToSet({}, text); - ALLOWED_ATTR = []; - if (USE_PROFILES.html === true) { - addToSet(ALLOWED_TAGS, html$1); - addToSet(ALLOWED_ATTR, html); - } - if (USE_PROFILES.svg === true) { - addToSet(ALLOWED_TAGS, svg$1); - addToSet(ALLOWED_ATTR, svg); - addToSet(ALLOWED_ATTR, xml); - } - if (USE_PROFILES.svgFilters === true) { - addToSet(ALLOWED_TAGS, svgFilters); - addToSet(ALLOWED_ATTR, svg); - addToSet(ALLOWED_ATTR, xml); - } - if (USE_PROFILES.mathMl === true) { - addToSet(ALLOWED_TAGS, mathMl$1); - addToSet(ALLOWED_ATTR, mathMl); - addToSet(ALLOWED_ATTR, xml); - } - } - /* Merge configuration parameters */ - if (cfg.ADD_TAGS) { - if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) { - ALLOWED_TAGS = clone(ALLOWED_TAGS); - } - addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc); - } - if (cfg.ADD_ATTR) { - if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) { - ALLOWED_ATTR = clone(ALLOWED_ATTR); - } - addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc); - } - if (cfg.ADD_URI_SAFE_ATTR) { - addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc); - } - if (cfg.FORBID_CONTENTS) { - if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) { - FORBID_CONTENTS = clone(FORBID_CONTENTS); - } - addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc); - } - /* Add #text in case KEEP_CONTENT is set to true */ - if (KEEP_CONTENT) { - ALLOWED_TAGS['#text'] = true; - } - /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */ - if (WHOLE_DOCUMENT) { - addToSet(ALLOWED_TAGS, ['html', 'head', 'body']); - } - /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */ - if (ALLOWED_TAGS.table) { - addToSet(ALLOWED_TAGS, ['tbody']); - delete FORBID_TAGS.tbody; - } - if (cfg.TRUSTED_TYPES_POLICY) { - if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') { - throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.'); - } - if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') { - throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.'); - } - // Overwrite existing TrustedTypes policy. - trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY; - // Sign local variables required by `sanitize`. - emptyHTML = trustedTypesPolicy.createHTML(''); - } else { - // Uninitialized policy, attempt to initialize the internal dompurify policy. - if (trustedTypesPolicy === undefined) { - trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript); - } - // If creating the internal policy succeeded sign internal variables. - if (trustedTypesPolicy !== null && typeof emptyHTML === 'string') { - emptyHTML = trustedTypesPolicy.createHTML(''); - } - } - // Prevent further manipulation of configuration. - // Not available in IE8, Safari 5, etc. - if (freeze) { - freeze(cfg); - } - CONFIG = cfg; - }; - /* Keep track of all possible SVG and MathML tags - * so that we can perform the namespace checks - * correctly. */ - const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]); - const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]); - /** - * @param element a DOM element whose namespace is being checked - * @returns Return false if the element has a - * namespace that a spec-compliant parser would never - * return. Return true otherwise. - */ - const _checkValidNamespace = function _checkValidNamespace(element) { - let parent = getParentNode(element); - // In JSDOM, if we're inside shadow DOM, then parentNode - // can be null. We just simulate parent in this case. - if (!parent || !parent.tagName) { - parent = { - namespaceURI: NAMESPACE, - tagName: 'template' - }; - } - const tagName = stringToLowerCase(element.tagName); - const parentTagName = stringToLowerCase(parent.tagName); - if (!ALLOWED_NAMESPACES[element.namespaceURI]) { - return false; - } - if (element.namespaceURI === SVG_NAMESPACE) { - // The only way to switch from HTML namespace to SVG - // is via . If it happens via any other tag, then - // it should be killed. - if (parent.namespaceURI === HTML_NAMESPACE) { - return tagName === 'svg'; - } - // The only way to switch from MathML to SVG is via` - // svg if parent is either or MathML - // text integration points. - if (parent.namespaceURI === MATHML_NAMESPACE) { - return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]); - } - // We only allow elements that are defined in SVG - // spec. All others are disallowed in SVG namespace. - return Boolean(ALL_SVG_TAGS[tagName]); - } - if (element.namespaceURI === MATHML_NAMESPACE) { - // The only way to switch from HTML namespace to MathML - // is via . If it happens via any other tag, then - // it should be killed. - if (parent.namespaceURI === HTML_NAMESPACE) { - return tagName === 'math'; - } - // The only way to switch from SVG to MathML is via - // and HTML integration points - if (parent.namespaceURI === SVG_NAMESPACE) { - return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName]; - } - // We only allow elements that are defined in MathML - // spec. All others are disallowed in MathML namespace. - return Boolean(ALL_MATHML_TAGS[tagName]); - } - if (element.namespaceURI === HTML_NAMESPACE) { - // The only way to switch from SVG to HTML is via - // HTML integration points, and from MathML to HTML - // is via MathML text integration points - if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) { - return false; - } - if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) { - return false; - } - // We disallow tags that are specific for MathML - // or SVG and should never appear in HTML namespace - return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]); - } - // For XHTML and XML documents that support custom namespaces - if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) { - return true; - } - // The code should never reach this place (this means - // that the element somehow got namespace that is not - // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES). - // Return false just in case. - return false; - }; - /** - * _forceRemove - * - * @param node a DOM node - */ - const _forceRemove = function _forceRemove(node) { - arrayPush(DOMPurify.removed, { - element: node - }); - try { - // eslint-disable-next-line unicorn/prefer-dom-node-remove - getParentNode(node).removeChild(node); - } catch (_) { - remove(node); - } - }; - /** - * _removeAttribute - * - * @param name an Attribute name - * @param element a DOM node - */ - const _removeAttribute = function _removeAttribute(name, element) { - try { - arrayPush(DOMPurify.removed, { - attribute: element.getAttributeNode(name), - from: element - }); - } catch (_) { - arrayPush(DOMPurify.removed, { - attribute: null, - from: element - }); - } - element.removeAttribute(name); - // We void attribute values for unremovable "is" attributes - if (name === 'is') { - if (RETURN_DOM || RETURN_DOM_FRAGMENT) { - try { - _forceRemove(element); - } catch (_) {} - } else { - try { - element.setAttribute(name, ''); - } catch (_) {} - } - } - }; - /** - * _initDocument - * - * @param dirty - a string of dirty markup - * @return a DOM, filled with the dirty markup - */ - const _initDocument = function _initDocument(dirty) { - /* Create a HTML document */ - let doc = null; - let leadingWhitespace = null; - if (FORCE_BODY) { - dirty = '' + dirty; - } else { - /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */ - const matches = stringMatch(dirty, /^[\r\n\t ]+/); - leadingWhitespace = matches && matches[0]; - } - if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) { - // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict) - dirty = '' + dirty + ''; - } - const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty; - /* - * Use the DOMParser API by default, fallback later if needs be - * DOMParser not work for svg when has multiple root element. - */ - if (NAMESPACE === HTML_NAMESPACE) { - try { - doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE); - } catch (_) {} - } - /* Use createHTMLDocument in case DOMParser is not available */ - if (!doc || !doc.documentElement) { - doc = implementation.createDocument(NAMESPACE, 'template', null); - try { - doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload; - } catch (_) { - // Syntax error if dirtyPayload is invalid xml - } - } - const body = doc.body || doc.documentElement; - if (dirty && leadingWhitespace) { - body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null); - } - /* Work on whole document or just its body */ - if (NAMESPACE === HTML_NAMESPACE) { - return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0]; - } - return WHOLE_DOCUMENT ? doc.documentElement : body; - }; - /** - * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. - * - * @param root The root element or node to start traversing on. - * @return The created NodeIterator - */ - const _createNodeIterator = function _createNodeIterator(root) { - return createNodeIterator.call(root.ownerDocument || root, root, - // eslint-disable-next-line no-bitwise - NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null); - }; - /** - * _isClobbered - * - * @param element element to check for clobbering attacks - * @return true if clobbered, false if safe - */ - const _isClobbered = function _isClobbered(element) { - return element instanceof HTMLFormElement && (typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' || !(element.attributes instanceof NamedNodeMap) || typeof element.removeAttribute !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function'); - }; - /** - * Checks whether the given object is a DOM node. - * - * @param value object to check whether it's a DOM node - * @return true is object is a DOM node - */ - const _isNode = function _isNode(value) { - return typeof Node === 'function' && value instanceof Node; - }; - function _executeHooks(hooks, currentNode, data) { - arrayForEach(hooks, hook => { - hook.call(DOMPurify, currentNode, data, CONFIG); - }); - } - /** - * _sanitizeElements - * - * @protect nodeName - * @protect textContent - * @protect removeChild - * @param currentNode to check for permission to exist - * @return true if node was killed, false if left alive - */ - const _sanitizeElements = function _sanitizeElements(currentNode) { - let content = null; - /* Execute a hook if present */ - _executeHooks(hooks.beforeSanitizeElements, currentNode, null); - /* Check if element is clobbered or can clobber */ - if (_isClobbered(currentNode)) { - _forceRemove(currentNode); - return true; - } - /* Now let's check the element's type and name */ - const tagName = transformCaseFunc(currentNode.nodeName); - /* Execute a hook if present */ - _executeHooks(hooks.uponSanitizeElement, currentNode, { - tagName, - allowedTags: ALLOWED_TAGS - }); - /* Detect mXSS attempts abusing namespace confusion */ - if (currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\w]/g, currentNode.innerHTML) && regExpTest(/<[/\w]/g, currentNode.textContent)) { - _forceRemove(currentNode); - return true; - } - /* Remove any occurrence of processing instructions */ - if (currentNode.nodeType === NODE_TYPE.progressingInstruction) { - _forceRemove(currentNode); - return true; - } - /* Remove any kind of possibly harmful comments */ - if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(/<[/\w]/g, currentNode.data)) { - _forceRemove(currentNode); - return true; - } - /* Remove element if anything forbids its presence */ - if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) { - /* Check if we have a custom element to handle */ - if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) { - if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) { - return false; - } - if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) { - return false; - } - } - /* Keep content except for bad-listed elements */ - if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) { - const parentNode = getParentNode(currentNode) || currentNode.parentNode; - const childNodes = getChildNodes(currentNode) || currentNode.childNodes; - if (childNodes && parentNode) { - const childCount = childNodes.length; - for (let i = childCount - 1; i >= 0; --i) { - const childClone = cloneNode(childNodes[i], true); - childClone.__removalCount = (currentNode.__removalCount || 0) + 1; - parentNode.insertBefore(childClone, getNextSibling(currentNode)); - } - } - } - _forceRemove(currentNode); - return true; - } - /* Check whether element has a valid namespace */ - if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) { - _forceRemove(currentNode); - return true; - } - /* Make sure that older browsers don't get fallback-tag mXSS */ - if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)) { - _forceRemove(currentNode); - return true; - } - /* Sanitize element content to be template-safe */ - if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) { - /* Get the element's text content */ - content = currentNode.textContent; - arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => { - content = stringReplace(content, expr, ' '); - }); - if (currentNode.textContent !== content) { - arrayPush(DOMPurify.removed, { - element: currentNode.cloneNode() - }); - currentNode.textContent = content; - } - } - /* Execute a hook if present */ - _executeHooks(hooks.afterSanitizeElements, currentNode, null); - return false; - }; - /** - * _isValidAttribute - * - * @param lcTag Lowercase tag name of containing element. - * @param lcName Lowercase attribute name. - * @param value Attribute value. - * @return Returns true if `value` is valid, otherwise false. - */ - // eslint-disable-next-line complexity - const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) { - /* Make sure attribute cannot clobber */ - if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) { - return false; - } - /* Allow valid data-* attributes: At least one character after "-" - (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes) - XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804) - We don't need to check the value; it's always URI safe. */ - if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR, lcName)) ; else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) { - if ( - // First condition does a very basic check if a) it's basically a valid custom element tagname AND - // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck - // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck - _isBasicCustomElement(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName)) || - // Alternative, second condition checks if it's an `is`-attribute, AND - // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck - lcName === 'is' && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))) ; else { - return false; - } - /* Check value is safe. First, is attr inert? If so, is safe */ - } else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) ; else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if (value) { - return false; - } else ; - return true; - }; - /** - * _isBasicCustomElement - * checks if at least one dash is included in tagName, and it's not the first char - * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name - * - * @param tagName name of the tag of the node to sanitize - * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false. - */ - const _isBasicCustomElement = function _isBasicCustomElement(tagName) { - return tagName !== 'annotation-xml' && stringMatch(tagName, CUSTOM_ELEMENT); - }; - /** - * _sanitizeAttributes - * - * @protect attributes - * @protect nodeName - * @protect removeAttribute - * @protect setAttribute - * - * @param currentNode to sanitize - */ - const _sanitizeAttributes = function _sanitizeAttributes(currentNode) { - /* Execute a hook if present */ - _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null); - const { - attributes - } = currentNode; - /* Check if we have attributes; if not we might have a text node */ - if (!attributes || _isClobbered(currentNode)) { - return; - } - const hookEvent = { - attrName: '', - attrValue: '', - keepAttr: true, - allowedAttributes: ALLOWED_ATTR, - forceKeepAttr: undefined - }; - let l = attributes.length; - /* Go backwards over all attributes; safely remove bad ones */ - while (l--) { - const attr = attributes[l]; - const { - name, - namespaceURI, - value: attrValue - } = attr; - const lcName = transformCaseFunc(name); - let value = name === 'value' ? attrValue : stringTrim(attrValue); - /* Execute a hook if present */ - hookEvent.attrName = lcName; - hookEvent.attrValue = value; - hookEvent.keepAttr = true; - hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set - _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent); - value = hookEvent.attrValue; - /* Full DOM Clobbering protection via namespace isolation, - * Prefix id and name attributes with `user-content-` - */ - if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name')) { - // Remove the attribute with this value - _removeAttribute(name, currentNode); - // Prefix the value and later re-create the attribute with the sanitized value - value = SANITIZE_NAMED_PROPS_PREFIX + value; - } - /* Work around a security issue with comments inside attributes */ - if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|title)/i, value)) { - _removeAttribute(name, currentNode); - continue; - } - /* Did the hooks approve of the attribute? */ - if (hookEvent.forceKeepAttr) { - continue; - } - /* Remove attribute */ - _removeAttribute(name, currentNode); - /* Did the hooks approve of the attribute? */ - if (!hookEvent.keepAttr) { - continue; - } - /* Work around a security issue in jQuery 3.0 */ - if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) { - _removeAttribute(name, currentNode); - continue; - } - /* Sanitize attribute content to be template-safe */ - if (SAFE_FOR_TEMPLATES) { - arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => { - value = stringReplace(value, expr, ' '); - }); - } - /* Is `value` valid for this attribute? */ - const lcTag = transformCaseFunc(currentNode.nodeName); - if (!_isValidAttribute(lcTag, lcName, value)) { - continue; - } - /* Handle attributes that require Trusted Types */ - if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function') { - if (namespaceURI) ; else { - switch (trustedTypes.getAttributeType(lcTag, lcName)) { - case 'TrustedHTML': - { - value = trustedTypesPolicy.createHTML(value); - break; - } - case 'TrustedScriptURL': - { - value = trustedTypesPolicy.createScriptURL(value); - break; - } - } - } - } - /* Handle invalid data-* attribute set by try-catching it */ - try { - if (namespaceURI) { - currentNode.setAttributeNS(namespaceURI, name, value); - } else { - /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */ - currentNode.setAttribute(name, value); - } - if (_isClobbered(currentNode)) { - _forceRemove(currentNode); - } else { - arrayPop(DOMPurify.removed); - } - } catch (_) {} - } - /* Execute a hook if present */ - _executeHooks(hooks.afterSanitizeAttributes, currentNode, null); - }; - /** - * _sanitizeShadowDOM - * - * @param fragment to iterate over recursively - */ - const _sanitizeShadowDOM = function _sanitizeShadowDOM(fragment) { - let shadowNode = null; - const shadowIterator = _createNodeIterator(fragment); - /* Execute a hook if present */ - _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null); - while (shadowNode = shadowIterator.nextNode()) { - /* Execute a hook if present */ - _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null); - /* Sanitize tags and elements */ - _sanitizeElements(shadowNode); - /* Check attributes next */ - _sanitizeAttributes(shadowNode); - /* Deep shadow DOM detected */ - if (shadowNode.content instanceof DocumentFragment) { - _sanitizeShadowDOM(shadowNode.content); - } - } - /* Execute a hook if present */ - _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null); - }; - // eslint-disable-next-line complexity - DOMPurify.sanitize = function (dirty) { - let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - let body = null; - let importedNode = null; - let currentNode = null; - let returnNode = null; - /* Make sure we have a string to sanitize. - DO NOT return early, as this will return the wrong type if - the user has requested a DOM object rather than a string */ - IS_EMPTY_INPUT = !dirty; - if (IS_EMPTY_INPUT) { - dirty = ''; - } - /* Stringify, in case dirty is an object */ - if (typeof dirty !== 'string' && !_isNode(dirty)) { - if (typeof dirty.toString === 'function') { - dirty = dirty.toString(); - if (typeof dirty !== 'string') { - throw typeErrorCreate('dirty is not a string, aborting'); - } - } else { - throw typeErrorCreate('toString is not a function'); - } - } - /* Return dirty HTML if DOMPurify cannot run */ - if (!DOMPurify.isSupported) { - return dirty; - } - /* Assign config vars */ - if (!SET_CONFIG) { - _parseConfig(cfg); - } - /* Clean up removed elements */ - DOMPurify.removed = []; - /* Check if dirty is correctly typed for IN_PLACE */ - if (typeof dirty === 'string') { - IN_PLACE = false; - } - if (IN_PLACE) { - /* Do some early pre-sanitization to avoid unsafe root nodes */ - if (dirty.nodeName) { - const tagName = transformCaseFunc(dirty.nodeName); - if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) { - throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place'); - } - } - } else if (dirty instanceof Node) { - /* If dirty is a DOM element, append to an empty document to avoid - elements being stripped by the parser */ - body = _initDocument(''); - importedNode = body.ownerDocument.importNode(dirty, true); - if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === 'BODY') { - /* Node is already a body, use as is */ - body = importedNode; - } else if (importedNode.nodeName === 'HTML') { - body = importedNode; - } else { - // eslint-disable-next-line unicorn/prefer-dom-node-append - body.appendChild(importedNode); - } - } else { - /* Exit directly if we have nothing to do */ - if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT && - // eslint-disable-next-line unicorn/prefer-includes - dirty.indexOf('<') === -1) { - return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty; - } - /* Initialize the document to work on */ - body = _initDocument(dirty); - /* Check we have a DOM node from the data */ - if (!body) { - return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : ''; - } - } - /* Remove first element node (ours) if FORCE_BODY is set */ - if (body && FORCE_BODY) { - _forceRemove(body.firstChild); - } - /* Get node iterator */ - const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body); - /* Now start iterating over the created document */ - while (currentNode = nodeIterator.nextNode()) { - /* Sanitize tags and elements */ - _sanitizeElements(currentNode); - /* Check attributes next */ - _sanitizeAttributes(currentNode); - /* Shadow DOM detected, sanitize it */ - if (currentNode.content instanceof DocumentFragment) { - _sanitizeShadowDOM(currentNode.content); - } - } - /* If we sanitized `dirty` in-place, return it. */ - if (IN_PLACE) { - return dirty; - } - /* Return sanitized string or DOM */ - if (RETURN_DOM) { - if (RETURN_DOM_FRAGMENT) { - returnNode = createDocumentFragment.call(body.ownerDocument); - while (body.firstChild) { - // eslint-disable-next-line unicorn/prefer-dom-node-append - returnNode.appendChild(body.firstChild); - } - } else { - returnNode = body; - } - if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) { - /* - AdoptNode() is not used because internal state is not reset - (e.g. the past names map of a HTMLFormElement), this is safe - in theory but we would rather not risk another attack vector. - The state that is cloned by importNode() is explicitly defined - by the specs. - */ - returnNode = importNode.call(originalDocument, returnNode, true); - } - return returnNode; - } - let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML; - /* Serialize doctype if allowed */ - if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) { - serializedHTML = '\n' + serializedHTML; - } - /* Sanitize final string template-safe */ - if (SAFE_FOR_TEMPLATES) { - arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => { - serializedHTML = stringReplace(serializedHTML, expr, ' '); - }); - } - return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML; - }; - DOMPurify.setConfig = function () { - let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - _parseConfig(cfg); - SET_CONFIG = true; - }; - DOMPurify.clearConfig = function () { - CONFIG = null; - SET_CONFIG = false; - }; - DOMPurify.isValidAttribute = function (tag, attr, value) { - /* Initialize shared config vars if necessary. */ - if (!CONFIG) { - _parseConfig({}); - } - const lcTag = transformCaseFunc(tag); - const lcName = transformCaseFunc(attr); - return _isValidAttribute(lcTag, lcName, value); - }; - DOMPurify.addHook = function (entryPoint, hookFunction) { - if (typeof hookFunction !== 'function') { - return; - } - arrayPush(hooks[entryPoint], hookFunction); - }; - DOMPurify.removeHook = function (entryPoint, hookFunction) { - if (hookFunction !== undefined) { - const index = arrayLastIndexOf(hooks[entryPoint], hookFunction); - return index === -1 ? undefined : arraySplice(hooks[entryPoint], index, 1)[0]; - } - return arrayPop(hooks[entryPoint]); - }; - DOMPurify.removeHooks = function (entryPoint) { - hooks[entryPoint] = []; - }; - DOMPurify.removeAllHooks = function () { - hooks = _createHooksMap(); - }; - return DOMPurify; -} -var purify = createDOMPurify(); - -export { purify as default }; -//# sourceMappingURL=purify.es.mjs.map diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/markdown_viewer/viewer.html b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/markdown_viewer/viewer.html deleted file mode 100644 index 94447ffc47e..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/markdown_viewer/viewer.html +++ /dev/null @@ -1,32 +0,0 @@ - - - - - Markdown viewer - - - - -

    - - - diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/markdown_viewer/viewer.mjs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/markdown_viewer/viewer.mjs deleted file mode 100644 index 78eb819c9a8..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/markdown_viewer/viewer.mjs +++ /dev/null @@ -1,13 +0,0 @@ -import { parse } from '../marked/dist/marked.esm.js'; -import purify from '../dompurify/dist/purify.es.mjs'; - -const url = new URL(window.location); -const fileUrl = url.searchParams.get('file'); -if (!fileUrl) { - throw new Error('File not specified in the URL query string'); -} - -var response = await fetch(fileUrl); -var text = await response.text(); - -document.getElementById('content').innerHTML = purify.sanitize(parse(text)); diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/marked/README.md b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/marked/README.md deleted file mode 100644 index 352b52d5503..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/marked/README.md +++ /dev/null @@ -1,5 +0,0 @@ -marked version 15.0.6 -https://github.com/markedjs/marked -License: MIT - -To update, replace the `dist/marked.esm.js` file with with an updated version from https://www.npmjs.com/package/marked. diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/marked/dist/marked.esm.js b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/marked/dist/marked.esm.js deleted file mode 100644 index a32cd778363..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/marked/dist/marked.esm.js +++ /dev/null @@ -1,2568 +0,0 @@ -/** - * marked v15.0.6 - a markdown parser - * Copyright (c) 2011-2025, Christopher Jeffrey. (MIT Licensed) - * https://github.com/markedjs/marked - */ - -/** - * DO NOT EDIT THIS FILE - * The code in this file is generated from files in ./src/ - */ - -/** - * Gets the original marked default options. - */ -function _getDefaults() { - return { - async: false, - breaks: false, - extensions: null, - gfm: true, - hooks: null, - pedantic: false, - renderer: null, - silent: false, - tokenizer: null, - walkTokens: null, - }; -} -let _defaults = _getDefaults(); -function changeDefaults(newDefaults) { - _defaults = newDefaults; -} - -const noopTest = { exec: () => null }; -function edit(regex, opt = '') { - let source = typeof regex === 'string' ? regex : regex.source; - const obj = { - replace: (name, val) => { - let valSource = typeof val === 'string' ? val : val.source; - valSource = valSource.replace(other.caret, '$1'); - source = source.replace(name, valSource); - return obj; - }, - getRegex: () => { - return new RegExp(source, opt); - }, - }; - return obj; -} -const other = { - codeRemoveIndent: /^(?: {1,4}| {0,3}\t)/gm, - outputLinkReplace: /\\([\[\]])/g, - indentCodeCompensation: /^(\s+)(?:```)/, - beginningSpace: /^\s+/, - endingHash: /#$/, - startingSpaceChar: /^ /, - endingSpaceChar: / $/, - nonSpaceChar: /[^ ]/, - newLineCharGlobal: /\n/g, - tabCharGlobal: /\t/g, - multipleSpaceGlobal: /\s+/g, - blankLine: /^[ \t]*$/, - doubleBlankLine: /\n[ \t]*\n[ \t]*$/, - blockquoteStart: /^ {0,3}>/, - blockquoteSetextReplace: /\n {0,3}((?:=+|-+) *)(?=\n|$)/g, - blockquoteSetextReplace2: /^ {0,3}>[ \t]?/gm, - listReplaceTabs: /^\t+/, - listReplaceNesting: /^ {1,4}(?=( {4})*[^ ])/g, - listIsTask: /^\[[ xX]\] /, - listReplaceTask: /^\[[ xX]\] +/, - anyLine: /\n.*\n/, - hrefBrackets: /^<(.*)>$/, - tableDelimiter: /[:|]/, - tableAlignChars: /^\||\| *$/g, - tableRowBlankLine: /\n[ \t]*$/, - tableAlignRight: /^ *-+: *$/, - tableAlignCenter: /^ *:-+: *$/, - tableAlignLeft: /^ *:-+ *$/, - startATag: /^
    /i, - startPreScriptTag: /^<(pre|code|kbd|script)(\s|>)/i, - endPreScriptTag: /^<\/(pre|code|kbd|script)(\s|>)/i, - startAngleBracket: /^$/, - pedanticHrefTitle: /^([^'"]*[^\s])\s+(['"])(.*)\2/, - unicodeAlphaNumeric: /[\p{L}\p{N}]/u, - escapeTest: /[&<>"']/, - escapeReplace: /[&<>"']/g, - escapeTestNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/, - escapeReplaceNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g, - unescapeTest: /&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig, - caret: /(^|[^\[])\^/g, - percentDecode: /%25/g, - findPipe: /\|/g, - splitPipe: / \|/, - slashPipe: /\\\|/g, - carriageReturn: /\r\n|\r/g, - spaceLine: /^ +$/gm, - notSpaceStart: /^\S*/, - endingNewline: /\n$/, - listItemRegex: (bull) => new RegExp(`^( {0,3}${bull})((?:[\t ][^\\n]*)?(?:\\n|$))`), - nextBulletRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ \t][^\\n]*)?(?:\\n|$))`), - hrRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`), - fencesBeginRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\`\`\`|~~~)`), - headingBeginRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`), - htmlBeginRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}<(?:[a-z].*>|!--)`, 'i'), -}; -/** - * Block-Level Grammar - */ -const newline = /^(?:[ \t]*(?:\n|$))+/; -const blockCode = /^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/; -const fences = /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/; -const hr = /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/; -const heading = /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/; -const bullet = /(?:[*+-]|\d{1,9}[.)])/; -const lheading = edit(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/) - .replace(/bull/g, bullet) // lists can interrupt - .replace(/blockCode/g, /(?: {4}| {0,3}\t)/) // indented code blocks can interrupt - .replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/) // fenced code blocks can interrupt - .replace(/blockquote/g, / {0,3}>/) // blockquote can interrupt - .replace(/heading/g, / {0,3}#{1,6}/) // ATX heading can interrupt - .replace(/html/g, / {0,3}<[^\n>]+>\n/) // block html can interrupt - .getRegex(); -const _paragraph = /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/; -const blockText = /^[^\n]+/; -const _blockLabel = /(?!\s*\])(?:\\.|[^\[\]\\])+/; -const def = edit(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/) - .replace('label', _blockLabel) - .replace('title', /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/) - .getRegex(); -const list = edit(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/) - .replace(/bull/g, bullet) - .getRegex(); -const _tag = 'address|article|aside|base|basefont|blockquote|body|caption' - + '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption' - + '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe' - + '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option' - + '|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title' - + '|tr|track|ul'; -const _comment = /|$))/; -const html = edit('^ {0,3}(?:' // optional indentation - + '<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)' // (1) - + '|comment[^\\n]*(\\n+|$)' // (2) - + '|<\\?[\\s\\S]*?(?:\\?>\\n*|$)' // (3) - + '|\\n*|$)' // (4) - + '|\\n*|$)' // (5) - + '|)[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)' // (6) - + '|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)' // (7) open tag - + '|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)' // (7) closing tag - + ')', 'i') - .replace('comment', _comment) - .replace('tag', _tag) - .replace('attribute', / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/) - .getRegex(); -const paragraph = edit(_paragraph) - .replace('hr', hr) - .replace('heading', ' {0,3}#{1,6}(?:\\s|$)') - .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs - .replace('|table', '') - .replace('blockquote', ' {0,3}>') - .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n') - .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt - .replace('html', ')|<(?:script|pre|style|textarea|!--)') - .replace('tag', _tag) // pars can be interrupted by type (6) html blocks - .getRegex(); -const blockquote = edit(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/) - .replace('paragraph', paragraph) - .getRegex(); -/** - * Normal Block Grammar - */ -const blockNormal = { - blockquote, - code: blockCode, - def, - fences, - heading, - hr, - html, - lheading, - list, - newline, - paragraph, - table: noopTest, - text: blockText, -}; -/** - * GFM Block Grammar - */ -const gfmTable = edit('^ *([^\\n ].*)\\n' // Header - + ' {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)' // Align - + '(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)') // Cells - .replace('hr', hr) - .replace('heading', ' {0,3}#{1,6}(?:\\s|$)') - .replace('blockquote', ' {0,3}>') - .replace('code', '(?: {4}| {0,3}\t)[^\\n]') - .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n') - .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt - .replace('html', ')|<(?:script|pre|style|textarea|!--)') - .replace('tag', _tag) // tables can be interrupted by type (6) html blocks - .getRegex(); -const blockGfm = { - ...blockNormal, - table: gfmTable, - paragraph: edit(_paragraph) - .replace('hr', hr) - .replace('heading', ' {0,3}#{1,6}(?:\\s|$)') - .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs - .replace('table', gfmTable) // interrupt paragraphs with table - .replace('blockquote', ' {0,3}>') - .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n') - .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt - .replace('html', ')|<(?:script|pre|style|textarea|!--)') - .replace('tag', _tag) // pars can be interrupted by type (6) html blocks - .getRegex(), -}; -/** - * Pedantic grammar (original John Gruber's loose markdown specification) - */ -const blockPedantic = { - ...blockNormal, - html: edit('^ *(?:comment *(?:\\n|\\s*$)' - + '|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)' // closed tag - + '|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))') - .replace('comment', _comment) - .replace(/tag/g, '(?!(?:' - + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub' - + '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)' - + '\\b)\\w+(?!:|[^\\w\\s@]*@)\\b') - .getRegex(), - def: /^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/, - heading: /^(#{1,6})(.*)(?:\n+|$)/, - fences: noopTest, // fences not supported - lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/, - paragraph: edit(_paragraph) - .replace('hr', hr) - .replace('heading', ' *#{1,6} *[^\n]') - .replace('lheading', lheading) - .replace('|table', '') - .replace('blockquote', ' {0,3}>') - .replace('|fences', '') - .replace('|list', '') - .replace('|html', '') - .replace('|tag', '') - .getRegex(), -}; -/** - * Inline-Level Grammar - */ -const escape$1 = /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/; -const inlineCode = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/; -const br = /^( {2,}|\\)\n(?!\s*$)/; -const inlineText = /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\ -const blockSkip = /\[[^[\]]*?\]\((?:\\.|[^\\\(\)]|\((?:\\.|[^\\\(\)])*\))*\)|`[^`]*?`|<[^<>]*?>/g; -const emStrongLDelimCore = /^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/; -const emStrongLDelim = edit(emStrongLDelimCore, 'u') - .replace(/punct/g, _punctuation) - .getRegex(); -const emStrongLDelimGfm = edit(emStrongLDelimCore, 'u') - .replace(/punct/g, _punctuationGfmStrongEm) - .getRegex(); -const emStrongRDelimAstCore = '^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)' // Skip orphan inside strong - + '|[^*]+(?=[^*])' // Consume to delim - + '|(?!\\*)punct(\\*+)(?=[\\s]|$)' // (1) #*** can only be a Right Delimiter - + '|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)' // (2) a***#, a*** can only be a Right Delimiter - + '|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)' // (3) #***a, ***a can only be Left Delimiter - + '|[\\s](\\*+)(?!\\*)(?=punct)' // (4) ***# can only be Left Delimiter - + '|(?!\\*)punct(\\*+)(?!\\*)(?=punct)' // (5) #***# can be either Left or Right Delimiter - + '|notPunctSpace(\\*+)(?=notPunctSpace)'; // (6) a***a can be either Left or Right Delimiter -const emStrongRDelimAst = edit(emStrongRDelimAstCore, 'gu') - .replace(/notPunctSpace/g, _notPunctuationOrSpace) - .replace(/punctSpace/g, _punctuationOrSpace) - .replace(/punct/g, _punctuation) - .getRegex(); -const emStrongRDelimAstGfm = edit(emStrongRDelimAstCore, 'gu') - .replace(/notPunctSpace/g, _notPunctuationOrSpaceGfmStrongEm) - .replace(/punctSpace/g, _punctuationOrSpaceGfmStrongEm) - .replace(/punct/g, _punctuationGfmStrongEm) - .getRegex(); -// (6) Not allowed for _ -const emStrongRDelimUnd = edit('^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)' // Skip orphan inside strong - + '|[^_]+(?=[^_])' // Consume to delim - + '|(?!_)punct(_+)(?=[\\s]|$)' // (1) #___ can only be a Right Delimiter - + '|notPunctSpace(_+)(?!_)(?=punctSpace|$)' // (2) a___#, a___ can only be a Right Delimiter - + '|(?!_)punctSpace(_+)(?=notPunctSpace)' // (3) #___a, ___a can only be Left Delimiter - + '|[\\s](_+)(?!_)(?=punct)' // (4) ___# can only be Left Delimiter - + '|(?!_)punct(_+)(?!_)(?=punct)', 'gu') // (5) #___# can be either Left or Right Delimiter - .replace(/notPunctSpace/g, _notPunctuationOrSpace) - .replace(/punctSpace/g, _punctuationOrSpace) - .replace(/punct/g, _punctuation) - .getRegex(); -const anyPunctuation = edit(/\\(punct)/, 'gu') - .replace(/punct/g, _punctuation) - .getRegex(); -const autolink = edit(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/) - .replace('scheme', /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/) - .replace('email', /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/) - .getRegex(); -const _inlineComment = edit(_comment).replace('(?:-->|$)', '-->').getRegex(); -const tag = edit('^comment' - + '|^' // self-closing tag - + '|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>' // open tag - + '|^<\\?[\\s\\S]*?\\?>' // processing instruction, e.g. - + '|^' // declaration, e.g. - + '|^') // CDATA section - .replace('comment', _inlineComment) - .replace('attribute', /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/) - .getRegex(); -const _inlineLabel = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/; -const link = edit(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/) - .replace('label', _inlineLabel) - .replace('href', /<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/) - .replace('title', /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/) - .getRegex(); -const reflink = edit(/^!?\[(label)\]\[(ref)\]/) - .replace('label', _inlineLabel) - .replace('ref', _blockLabel) - .getRegex(); -const nolink = edit(/^!?\[(ref)\](?:\[\])?/) - .replace('ref', _blockLabel) - .getRegex(); -const reflinkSearch = edit('reflink|nolink(?!\\()', 'g') - .replace('reflink', reflink) - .replace('nolink', nolink) - .getRegex(); -/** - * Normal Inline Grammar - */ -const inlineNormal = { - _backpedal: noopTest, // only used for GFM url - anyPunctuation, - autolink, - blockSkip, - br, - code: inlineCode, - del: noopTest, - emStrongLDelim, - emStrongRDelimAst, - emStrongRDelimUnd, - escape: escape$1, - link, - nolink, - punctuation, - reflink, - reflinkSearch, - tag, - text: inlineText, - url: noopTest, -}; -/** - * Pedantic Inline Grammar - */ -const inlinePedantic = { - ...inlineNormal, - link: edit(/^!?\[(label)\]\((.*?)\)/) - .replace('label', _inlineLabel) - .getRegex(), - reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/) - .replace('label', _inlineLabel) - .getRegex(), -}; -/** - * GFM Inline Grammar - */ -const inlineGfm = { - ...inlineNormal, - emStrongRDelimAst: emStrongRDelimAstGfm, - emStrongLDelim: emStrongLDelimGfm, - url: edit(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/, 'i') - .replace('email', /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/) - .getRegex(), - _backpedal: /(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/, - del: /^(~~?)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/, - text: /^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\': '>', - '"': '"', - "'": ''', -}; -const getEscapeReplacement = (ch) => escapeReplacements[ch]; -function escape(html, encode) { - if (encode) { - if (other.escapeTest.test(html)) { - return html.replace(other.escapeReplace, getEscapeReplacement); - } - } - else { - if (other.escapeTestNoEncode.test(html)) { - return html.replace(other.escapeReplaceNoEncode, getEscapeReplacement); - } - } - return html; -} -function cleanUrl(href) { - try { - href = encodeURI(href).replace(other.percentDecode, '%'); - } - catch { - return null; - } - return href; -} -function splitCells(tableRow, count) { - // ensure that every cell-delimiting pipe has a space - // before it to distinguish it from an escaped pipe - const row = tableRow.replace(other.findPipe, (match, offset, str) => { - let escaped = false; - let curr = offset; - while (--curr >= 0 && str[curr] === '\\') - escaped = !escaped; - if (escaped) { - // odd number of slashes means | is escaped - // so we leave it alone - return '|'; - } - else { - // add space before unescaped | - return ' |'; - } - }), cells = row.split(other.splitPipe); - let i = 0; - // First/last cell in a row cannot be empty if it has no leading/trailing pipe - if (!cells[0].trim()) { - cells.shift(); - } - if (cells.length > 0 && !cells.at(-1)?.trim()) { - cells.pop(); - } - if (count) { - if (cells.length > count) { - cells.splice(count); - } - else { - while (cells.length < count) - cells.push(''); - } - } - for (; i < cells.length; i++) { - // leading or trailing whitespace is ignored per the gfm spec - cells[i] = cells[i].trim().replace(other.slashPipe, '|'); - } - return cells; -} -/** - * Remove trailing 'c's. Equivalent to str.replace(/c*$/, ''). - * /c*$/ is vulnerable to REDOS. - * - * @param str - * @param c - * @param invert Remove suffix of non-c chars instead. Default falsey. - */ -function rtrim(str, c, invert) { - const l = str.length; - if (l === 0) { - return ''; - } - // Length of suffix matching the invert condition. - let suffLen = 0; - // Step left until we fail to match the invert condition. - while (suffLen < l) { - const currChar = str.charAt(l - suffLen - 1); - if (currChar === c && true) { - suffLen++; - } - else { - break; - } - } - return str.slice(0, l - suffLen); -} -function findClosingBracket(str, b) { - if (str.indexOf(b[1]) === -1) { - return -1; - } - let level = 0; - for (let i = 0; i < str.length; i++) { - if (str[i] === '\\') { - i++; - } - else if (str[i] === b[0]) { - level++; - } - else if (str[i] === b[1]) { - level--; - if (level < 0) { - return i; - } - } - } - return -1; -} - -function outputLink(cap, link, raw, lexer, rules) { - const href = link.href; - const title = link.title || null; - const text = cap[1].replace(rules.other.outputLinkReplace, '$1'); - if (cap[0].charAt(0) !== '!') { - lexer.state.inLink = true; - const token = { - type: 'link', - raw, - href, - title, - text, - tokens: lexer.inlineTokens(text), - }; - lexer.state.inLink = false; - return token; - } - return { - type: 'image', - raw, - href, - title, - text, - }; -} -function indentCodeCompensation(raw, text, rules) { - const matchIndentToCode = raw.match(rules.other.indentCodeCompensation); - if (matchIndentToCode === null) { - return text; - } - const indentToCode = matchIndentToCode[1]; - return text - .split('\n') - .map(node => { - const matchIndentInNode = node.match(rules.other.beginningSpace); - if (matchIndentInNode === null) { - return node; - } - const [indentInNode] = matchIndentInNode; - if (indentInNode.length >= indentToCode.length) { - return node.slice(indentToCode.length); - } - return node; - }) - .join('\n'); -} -/** - * Tokenizer - */ -class _Tokenizer { - options; - rules; // set by the lexer - lexer; // set by the lexer - constructor(options) { - this.options = options || _defaults; - } - space(src) { - const cap = this.rules.block.newline.exec(src); - if (cap && cap[0].length > 0) { - return { - type: 'space', - raw: cap[0], - }; - } - } - code(src) { - const cap = this.rules.block.code.exec(src); - if (cap) { - const text = cap[0].replace(this.rules.other.codeRemoveIndent, ''); - return { - type: 'code', - raw: cap[0], - codeBlockStyle: 'indented', - text: !this.options.pedantic - ? rtrim(text, '\n') - : text, - }; - } - } - fences(src) { - const cap = this.rules.block.fences.exec(src); - if (cap) { - const raw = cap[0]; - const text = indentCodeCompensation(raw, cap[3] || '', this.rules); - return { - type: 'code', - raw, - lang: cap[2] ? cap[2].trim().replace(this.rules.inline.anyPunctuation, '$1') : cap[2], - text, - }; - } - } - heading(src) { - const cap = this.rules.block.heading.exec(src); - if (cap) { - let text = cap[2].trim(); - // remove trailing #s - if (this.rules.other.endingHash.test(text)) { - const trimmed = rtrim(text, '#'); - if (this.options.pedantic) { - text = trimmed.trim(); - } - else if (!trimmed || this.rules.other.endingSpaceChar.test(trimmed)) { - // CommonMark requires space before trailing #s - text = trimmed.trim(); - } - } - return { - type: 'heading', - raw: cap[0], - depth: cap[1].length, - text, - tokens: this.lexer.inline(text), - }; - } - } - hr(src) { - const cap = this.rules.block.hr.exec(src); - if (cap) { - return { - type: 'hr', - raw: rtrim(cap[0], '\n'), - }; - } - } - blockquote(src) { - const cap = this.rules.block.blockquote.exec(src); - if (cap) { - let lines = rtrim(cap[0], '\n').split('\n'); - let raw = ''; - let text = ''; - const tokens = []; - while (lines.length > 0) { - let inBlockquote = false; - const currentLines = []; - let i; - for (i = 0; i < lines.length; i++) { - // get lines up to a continuation - if (this.rules.other.blockquoteStart.test(lines[i])) { - currentLines.push(lines[i]); - inBlockquote = true; - } - else if (!inBlockquote) { - currentLines.push(lines[i]); - } - else { - break; - } - } - lines = lines.slice(i); - const currentRaw = currentLines.join('\n'); - const currentText = currentRaw - // precede setext continuation with 4 spaces so it isn't a setext - .replace(this.rules.other.blockquoteSetextReplace, '\n $1') - .replace(this.rules.other.blockquoteSetextReplace2, ''); - raw = raw ? `${raw}\n${currentRaw}` : currentRaw; - text = text ? `${text}\n${currentText}` : currentText; - // parse blockquote lines as top level tokens - // merge paragraphs if this is a continuation - const top = this.lexer.state.top; - this.lexer.state.top = true; - this.lexer.blockTokens(currentText, tokens, true); - this.lexer.state.top = top; - // if there is no continuation then we are done - if (lines.length === 0) { - break; - } - const lastToken = tokens.at(-1); - if (lastToken?.type === 'code') { - // blockquote continuation cannot be preceded by a code block - break; - } - else if (lastToken?.type === 'blockquote') { - // include continuation in nested blockquote - const oldToken = lastToken; - const newText = oldToken.raw + '\n' + lines.join('\n'); - const newToken = this.blockquote(newText); - tokens[tokens.length - 1] = newToken; - raw = raw.substring(0, raw.length - oldToken.raw.length) + newToken.raw; - text = text.substring(0, text.length - oldToken.text.length) + newToken.text; - break; - } - else if (lastToken?.type === 'list') { - // include continuation in nested list - const oldToken = lastToken; - const newText = oldToken.raw + '\n' + lines.join('\n'); - const newToken = this.list(newText); - tokens[tokens.length - 1] = newToken; - raw = raw.substring(0, raw.length - lastToken.raw.length) + newToken.raw; - text = text.substring(0, text.length - oldToken.raw.length) + newToken.raw; - lines = newText.substring(tokens.at(-1).raw.length).split('\n'); - continue; - } - } - return { - type: 'blockquote', - raw, - tokens, - text, - }; - } - } - list(src) { - let cap = this.rules.block.list.exec(src); - if (cap) { - let bull = cap[1].trim(); - const isordered = bull.length > 1; - const list = { - type: 'list', - raw: '', - ordered: isordered, - start: isordered ? +bull.slice(0, -1) : '', - loose: false, - items: [], - }; - bull = isordered ? `\\d{1,9}\\${bull.slice(-1)}` : `\\${bull}`; - if (this.options.pedantic) { - bull = isordered ? bull : '[*+-]'; - } - // Get next list item - const itemRegex = this.rules.other.listItemRegex(bull); - let endsWithBlankLine = false; - // Check if current bullet point can start a new List Item - while (src) { - let endEarly = false; - let raw = ''; - let itemContents = ''; - if (!(cap = itemRegex.exec(src))) { - break; - } - if (this.rules.block.hr.test(src)) { // End list if bullet was actually HR (possibly move into itemRegex?) - break; - } - raw = cap[0]; - src = src.substring(raw.length); - let line = cap[2].split('\n', 1)[0].replace(this.rules.other.listReplaceTabs, (t) => ' '.repeat(3 * t.length)); - let nextLine = src.split('\n', 1)[0]; - let blankLine = !line.trim(); - let indent = 0; - if (this.options.pedantic) { - indent = 2; - itemContents = line.trimStart(); - } - else if (blankLine) { - indent = cap[1].length + 1; - } - else { - indent = cap[2].search(this.rules.other.nonSpaceChar); // Find first non-space char - indent = indent > 4 ? 1 : indent; // Treat indented code blocks (> 4 spaces) as having only 1 indent - itemContents = line.slice(indent); - indent += cap[1].length; - } - if (blankLine && this.rules.other.blankLine.test(nextLine)) { // Items begin with at most one blank line - raw += nextLine + '\n'; - src = src.substring(nextLine.length + 1); - endEarly = true; - } - if (!endEarly) { - const nextBulletRegex = this.rules.other.nextBulletRegex(indent); - const hrRegex = this.rules.other.hrRegex(indent); - const fencesBeginRegex = this.rules.other.fencesBeginRegex(indent); - const headingBeginRegex = this.rules.other.headingBeginRegex(indent); - const htmlBeginRegex = this.rules.other.htmlBeginRegex(indent); - // Check if following lines should be included in List Item - while (src) { - const rawLine = src.split('\n', 1)[0]; - let nextLineWithoutTabs; - nextLine = rawLine; - // Re-align to follow commonmark nesting rules - if (this.options.pedantic) { - nextLine = nextLine.replace(this.rules.other.listReplaceNesting, ' '); - nextLineWithoutTabs = nextLine; - } - else { - nextLineWithoutTabs = nextLine.replace(this.rules.other.tabCharGlobal, ' '); - } - // End list item if found code fences - if (fencesBeginRegex.test(nextLine)) { - break; - } - // End list item if found start of new heading - if (headingBeginRegex.test(nextLine)) { - break; - } - // End list item if found start of html block - if (htmlBeginRegex.test(nextLine)) { - break; - } - // End list item if found start of new bullet - if (nextBulletRegex.test(nextLine)) { - break; - } - // Horizontal rule found - if (hrRegex.test(nextLine)) { - break; - } - if (nextLineWithoutTabs.search(this.rules.other.nonSpaceChar) >= indent || !nextLine.trim()) { // Dedent if possible - itemContents += '\n' + nextLineWithoutTabs.slice(indent); - } - else { - // not enough indentation - if (blankLine) { - break; - } - // paragraph continuation unless last line was a different block level element - if (line.replace(this.rules.other.tabCharGlobal, ' ').search(this.rules.other.nonSpaceChar) >= 4) { // indented code block - break; - } - if (fencesBeginRegex.test(line)) { - break; - } - if (headingBeginRegex.test(line)) { - break; - } - if (hrRegex.test(line)) { - break; - } - itemContents += '\n' + nextLine; - } - if (!blankLine && !nextLine.trim()) { // Check if current line is blank - blankLine = true; - } - raw += rawLine + '\n'; - src = src.substring(rawLine.length + 1); - line = nextLineWithoutTabs.slice(indent); - } - } - if (!list.loose) { - // If the previous item ended with a blank line, the list is loose - if (endsWithBlankLine) { - list.loose = true; - } - else if (this.rules.other.doubleBlankLine.test(raw)) { - endsWithBlankLine = true; - } - } - let istask = null; - let ischecked; - // Check for task list items - if (this.options.gfm) { - istask = this.rules.other.listIsTask.exec(itemContents); - if (istask) { - ischecked = istask[0] !== '[ ] '; - itemContents = itemContents.replace(this.rules.other.listReplaceTask, ''); - } - } - list.items.push({ - type: 'list_item', - raw, - task: !!istask, - checked: ischecked, - loose: false, - text: itemContents, - tokens: [], - }); - list.raw += raw; - } - // Do not consume newlines at end of final item. Alternatively, make itemRegex *start* with any newlines to simplify/speed up endsWithBlankLine logic - const lastItem = list.items.at(-1); - if (lastItem) { - lastItem.raw = lastItem.raw.trimEnd(); - lastItem.text = lastItem.text.trimEnd(); - } - else { - // not a list since there were no items - return; - } - list.raw = list.raw.trimEnd(); - // Item child tokens handled here at end because we needed to have the final item to trim it first - for (let i = 0; i < list.items.length; i++) { - this.lexer.state.top = false; - list.items[i].tokens = this.lexer.blockTokens(list.items[i].text, []); - if (!list.loose) { - // Check if list should be loose - const spacers = list.items[i].tokens.filter(t => t.type === 'space'); - const hasMultipleLineBreaks = spacers.length > 0 && spacers.some(t => this.rules.other.anyLine.test(t.raw)); - list.loose = hasMultipleLineBreaks; - } - } - // Set all items to loose if list is loose - if (list.loose) { - for (let i = 0; i < list.items.length; i++) { - list.items[i].loose = true; - } - } - return list; - } - } - html(src) { - const cap = this.rules.block.html.exec(src); - if (cap) { - const token = { - type: 'html', - block: true, - raw: cap[0], - pre: cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style', - text: cap[0], - }; - return token; - } - } - def(src) { - const cap = this.rules.block.def.exec(src); - if (cap) { - const tag = cap[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal, ' '); - const href = cap[2] ? cap[2].replace(this.rules.other.hrefBrackets, '$1').replace(this.rules.inline.anyPunctuation, '$1') : ''; - const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline.anyPunctuation, '$1') : cap[3]; - return { - type: 'def', - tag, - raw: cap[0], - href, - title, - }; - } - } - table(src) { - const cap = this.rules.block.table.exec(src); - if (!cap) { - return; - } - if (!this.rules.other.tableDelimiter.test(cap[2])) { - // delimiter row must have a pipe (|) or colon (:) otherwise it is a setext heading - return; - } - const headers = splitCells(cap[1]); - const aligns = cap[2].replace(this.rules.other.tableAlignChars, '').split('|'); - const rows = cap[3]?.trim() ? cap[3].replace(this.rules.other.tableRowBlankLine, '').split('\n') : []; - const item = { - type: 'table', - raw: cap[0], - header: [], - align: [], - rows: [], - }; - if (headers.length !== aligns.length) { - // header and align columns must be equal, rows can be different. - return; - } - for (const align of aligns) { - if (this.rules.other.tableAlignRight.test(align)) { - item.align.push('right'); - } - else if (this.rules.other.tableAlignCenter.test(align)) { - item.align.push('center'); - } - else if (this.rules.other.tableAlignLeft.test(align)) { - item.align.push('left'); - } - else { - item.align.push(null); - } - } - for (let i = 0; i < headers.length; i++) { - item.header.push({ - text: headers[i], - tokens: this.lexer.inline(headers[i]), - header: true, - align: item.align[i], - }); - } - for (const row of rows) { - item.rows.push(splitCells(row, item.header.length).map((cell, i) => { - return { - text: cell, - tokens: this.lexer.inline(cell), - header: false, - align: item.align[i], - }; - })); - } - return item; - } - lheading(src) { - const cap = this.rules.block.lheading.exec(src); - if (cap) { - return { - type: 'heading', - raw: cap[0], - depth: cap[2].charAt(0) === '=' ? 1 : 2, - text: cap[1], - tokens: this.lexer.inline(cap[1]), - }; - } - } - paragraph(src) { - const cap = this.rules.block.paragraph.exec(src); - if (cap) { - const text = cap[1].charAt(cap[1].length - 1) === '\n' - ? cap[1].slice(0, -1) - : cap[1]; - return { - type: 'paragraph', - raw: cap[0], - text, - tokens: this.lexer.inline(text), - }; - } - } - text(src) { - const cap = this.rules.block.text.exec(src); - if (cap) { - return { - type: 'text', - raw: cap[0], - text: cap[0], - tokens: this.lexer.inline(cap[0]), - }; - } - } - escape(src) { - const cap = this.rules.inline.escape.exec(src); - if (cap) { - return { - type: 'escape', - raw: cap[0], - text: cap[1], - }; - } - } - tag(src) { - const cap = this.rules.inline.tag.exec(src); - if (cap) { - if (!this.lexer.state.inLink && this.rules.other.startATag.test(cap[0])) { - this.lexer.state.inLink = true; - } - else if (this.lexer.state.inLink && this.rules.other.endATag.test(cap[0])) { - this.lexer.state.inLink = false; - } - if (!this.lexer.state.inRawBlock && this.rules.other.startPreScriptTag.test(cap[0])) { - this.lexer.state.inRawBlock = true; - } - else if (this.lexer.state.inRawBlock && this.rules.other.endPreScriptTag.test(cap[0])) { - this.lexer.state.inRawBlock = false; - } - return { - type: 'html', - raw: cap[0], - inLink: this.lexer.state.inLink, - inRawBlock: this.lexer.state.inRawBlock, - block: false, - text: cap[0], - }; - } - } - link(src) { - const cap = this.rules.inline.link.exec(src); - if (cap) { - const trimmedUrl = cap[2].trim(); - if (!this.options.pedantic && this.rules.other.startAngleBracket.test(trimmedUrl)) { - // commonmark requires matching angle brackets - if (!(this.rules.other.endAngleBracket.test(trimmedUrl))) { - return; - } - // ending angle bracket cannot be escaped - const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), '\\'); - if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) { - return; - } - } - else { - // find closing parenthesis - const lastParenIndex = findClosingBracket(cap[2], '()'); - if (lastParenIndex > -1) { - const start = cap[0].indexOf('!') === 0 ? 5 : 4; - const linkLen = start + cap[1].length + lastParenIndex; - cap[2] = cap[2].substring(0, lastParenIndex); - cap[0] = cap[0].substring(0, linkLen).trim(); - cap[3] = ''; - } - } - let href = cap[2]; - let title = ''; - if (this.options.pedantic) { - // split pedantic href and title - const link = this.rules.other.pedanticHrefTitle.exec(href); - if (link) { - href = link[1]; - title = link[3]; - } - } - else { - title = cap[3] ? cap[3].slice(1, -1) : ''; - } - href = href.trim(); - if (this.rules.other.startAngleBracket.test(href)) { - if (this.options.pedantic && !(this.rules.other.endAngleBracket.test(trimmedUrl))) { - // pedantic allows starting angle bracket without ending angle bracket - href = href.slice(1); - } - else { - href = href.slice(1, -1); - } - } - return outputLink(cap, { - href: href ? href.replace(this.rules.inline.anyPunctuation, '$1') : href, - title: title ? title.replace(this.rules.inline.anyPunctuation, '$1') : title, - }, cap[0], this.lexer, this.rules); - } - } - reflink(src, links) { - let cap; - if ((cap = this.rules.inline.reflink.exec(src)) - || (cap = this.rules.inline.nolink.exec(src))) { - const linkString = (cap[2] || cap[1]).replace(this.rules.other.multipleSpaceGlobal, ' '); - const link = links[linkString.toLowerCase()]; - if (!link) { - const text = cap[0].charAt(0); - return { - type: 'text', - raw: text, - text, - }; - } - return outputLink(cap, link, cap[0], this.lexer, this.rules); - } - } - emStrong(src, maskedSrc, prevChar = '') { - let match = this.rules.inline.emStrongLDelim.exec(src); - if (!match) - return; - // _ can't be between two alphanumerics. \p{L}\p{N} includes non-english alphabet/numbers as well - if (match[3] && prevChar.match(this.rules.other.unicodeAlphaNumeric)) - return; - const nextChar = match[1] || match[2] || ''; - if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) { - // unicode Regex counts emoji as 1 char; spread into array for proper count (used multiple times below) - const lLength = [...match[0]].length - 1; - let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0; - const endReg = match[0][0] === '*' ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd; - endReg.lastIndex = 0; - // Clip maskedSrc to same section of string as src (move to lexer?) - maskedSrc = maskedSrc.slice(-1 * src.length + lLength); - while ((match = endReg.exec(maskedSrc)) != null) { - rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6]; - if (!rDelim) - continue; // skip single * in __abc*abc__ - rLength = [...rDelim].length; - if (match[3] || match[4]) { // found another Left Delim - delimTotal += rLength; - continue; - } - else if (match[5] || match[6]) { // either Left or Right Delim - if (lLength % 3 && !((lLength + rLength) % 3)) { - midDelimTotal += rLength; - continue; // CommonMark Emphasis Rules 9-10 - } - } - delimTotal -= rLength; - if (delimTotal > 0) - continue; // Haven't found enough closing delimiters - // Remove extra characters. *a*** -> *a* - rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal); - // char length can be >1 for unicode characters; - const lastCharLength = [...match[0]][0].length; - const raw = src.slice(0, lLength + match.index + lastCharLength + rLength); - // Create `em` if smallest delimiter has odd char count. *a*** - if (Math.min(lLength, rLength) % 2) { - const text = raw.slice(1, -1); - return { - type: 'em', - raw, - text, - tokens: this.lexer.inlineTokens(text), - }; - } - // Create 'strong' if smallest delimiter has even char count. **a*** - const text = raw.slice(2, -2); - return { - type: 'strong', - raw, - text, - tokens: this.lexer.inlineTokens(text), - }; - } - } - } - codespan(src) { - const cap = this.rules.inline.code.exec(src); - if (cap) { - let text = cap[2].replace(this.rules.other.newLineCharGlobal, ' '); - const hasNonSpaceChars = this.rules.other.nonSpaceChar.test(text); - const hasSpaceCharsOnBothEnds = this.rules.other.startingSpaceChar.test(text) && this.rules.other.endingSpaceChar.test(text); - if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) { - text = text.substring(1, text.length - 1); - } - return { - type: 'codespan', - raw: cap[0], - text, - }; - } - } - br(src) { - const cap = this.rules.inline.br.exec(src); - if (cap) { - return { - type: 'br', - raw: cap[0], - }; - } - } - del(src) { - const cap = this.rules.inline.del.exec(src); - if (cap) { - return { - type: 'del', - raw: cap[0], - text: cap[2], - tokens: this.lexer.inlineTokens(cap[2]), - }; - } - } - autolink(src) { - const cap = this.rules.inline.autolink.exec(src); - if (cap) { - let text, href; - if (cap[2] === '@') { - text = cap[1]; - href = 'mailto:' + text; - } - else { - text = cap[1]; - href = text; - } - return { - type: 'link', - raw: cap[0], - text, - href, - tokens: [ - { - type: 'text', - raw: text, - text, - }, - ], - }; - } - } - url(src) { - let cap; - if (cap = this.rules.inline.url.exec(src)) { - let text, href; - if (cap[2] === '@') { - text = cap[0]; - href = 'mailto:' + text; - } - else { - // do extended autolink path validation - let prevCapZero; - do { - prevCapZero = cap[0]; - cap[0] = this.rules.inline._backpedal.exec(cap[0])?.[0] ?? ''; - } while (prevCapZero !== cap[0]); - text = cap[0]; - if (cap[1] === 'www.') { - href = 'http://' + cap[0]; - } - else { - href = cap[0]; - } - } - return { - type: 'link', - raw: cap[0], - text, - href, - tokens: [ - { - type: 'text', - raw: text, - text, - }, - ], - }; - } - } - inlineText(src) { - const cap = this.rules.inline.text.exec(src); - if (cap) { - const escaped = this.lexer.state.inRawBlock; - return { - type: 'text', - raw: cap[0], - text: cap[0], - escaped, - }; - } - } -} - -/** - * Block Lexer - */ -class _Lexer { - tokens; - options; - state; - tokenizer; - inlineQueue; - constructor(options) { - // TokenList cannot be created in one go - this.tokens = []; - this.tokens.links = Object.create(null); - this.options = options || _defaults; - this.options.tokenizer = this.options.tokenizer || new _Tokenizer(); - this.tokenizer = this.options.tokenizer; - this.tokenizer.options = this.options; - this.tokenizer.lexer = this; - this.inlineQueue = []; - this.state = { - inLink: false, - inRawBlock: false, - top: true, - }; - const rules = { - other, - block: block.normal, - inline: inline.normal, - }; - if (this.options.pedantic) { - rules.block = block.pedantic; - rules.inline = inline.pedantic; - } - else if (this.options.gfm) { - rules.block = block.gfm; - if (this.options.breaks) { - rules.inline = inline.breaks; - } - else { - rules.inline = inline.gfm; - } - } - this.tokenizer.rules = rules; - } - /** - * Expose Rules - */ - static get rules() { - return { - block, - inline, - }; - } - /** - * Static Lex Method - */ - static lex(src, options) { - const lexer = new _Lexer(options); - return lexer.lex(src); - } - /** - * Static Lex Inline Method - */ - static lexInline(src, options) { - const lexer = new _Lexer(options); - return lexer.inlineTokens(src); - } - /** - * Preprocessing - */ - lex(src) { - src = src.replace(other.carriageReturn, '\n'); - this.blockTokens(src, this.tokens); - for (let i = 0; i < this.inlineQueue.length; i++) { - const next = this.inlineQueue[i]; - this.inlineTokens(next.src, next.tokens); - } - this.inlineQueue = []; - return this.tokens; - } - blockTokens(src, tokens = [], lastParagraphClipped = false) { - if (this.options.pedantic) { - src = src.replace(other.tabCharGlobal, ' ').replace(other.spaceLine, ''); - } - while (src) { - let token; - if (this.options.extensions?.block?.some((extTokenizer) => { - if (token = extTokenizer.call({ lexer: this }, src, tokens)) { - src = src.substring(token.raw.length); - tokens.push(token); - return true; - } - return false; - })) { - continue; - } - // newline - if (token = this.tokenizer.space(src)) { - src = src.substring(token.raw.length); - const lastToken = tokens.at(-1); - if (token.raw.length === 1 && lastToken !== undefined) { - // if there's a single \n as a spacer, it's terminating the last line, - // so move it there so that we don't get unnecessary paragraph tags - lastToken.raw += '\n'; - } - else { - tokens.push(token); - } - continue; - } - // code - if (token = this.tokenizer.code(src)) { - src = src.substring(token.raw.length); - const lastToken = tokens.at(-1); - // An indented code block cannot interrupt a paragraph. - if (lastToken?.type === 'paragraph' || lastToken?.type === 'text') { - lastToken.raw += '\n' + token.raw; - lastToken.text += '\n' + token.text; - this.inlineQueue.at(-1).src = lastToken.text; - } - else { - tokens.push(token); - } - continue; - } - // fences - if (token = this.tokenizer.fences(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // heading - if (token = this.tokenizer.heading(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // hr - if (token = this.tokenizer.hr(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // blockquote - if (token = this.tokenizer.blockquote(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // list - if (token = this.tokenizer.list(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // html - if (token = this.tokenizer.html(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // def - if (token = this.tokenizer.def(src)) { - src = src.substring(token.raw.length); - const lastToken = tokens.at(-1); - if (lastToken?.type === 'paragraph' || lastToken?.type === 'text') { - lastToken.raw += '\n' + token.raw; - lastToken.text += '\n' + token.raw; - this.inlineQueue.at(-1).src = lastToken.text; - } - else if (!this.tokens.links[token.tag]) { - this.tokens.links[token.tag] = { - href: token.href, - title: token.title, - }; - } - continue; - } - // table (gfm) - if (token = this.tokenizer.table(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // lheading - if (token = this.tokenizer.lheading(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // top-level paragraph - // prevent paragraph consuming extensions by clipping 'src' to extension start - let cutSrc = src; - if (this.options.extensions?.startBlock) { - let startIndex = Infinity; - const tempSrc = src.slice(1); - let tempStart; - this.options.extensions.startBlock.forEach((getStartIndex) => { - tempStart = getStartIndex.call({ lexer: this }, tempSrc); - if (typeof tempStart === 'number' && tempStart >= 0) { - startIndex = Math.min(startIndex, tempStart); - } - }); - if (startIndex < Infinity && startIndex >= 0) { - cutSrc = src.substring(0, startIndex + 1); - } - } - if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) { - const lastToken = tokens.at(-1); - if (lastParagraphClipped && lastToken?.type === 'paragraph') { - lastToken.raw += '\n' + token.raw; - lastToken.text += '\n' + token.text; - this.inlineQueue.pop(); - this.inlineQueue.at(-1).src = lastToken.text; - } - else { - tokens.push(token); - } - lastParagraphClipped = cutSrc.length !== src.length; - src = src.substring(token.raw.length); - continue; - } - // text - if (token = this.tokenizer.text(src)) { - src = src.substring(token.raw.length); - const lastToken = tokens.at(-1); - if (lastToken?.type === 'text') { - lastToken.raw += '\n' + token.raw; - lastToken.text += '\n' + token.text; - this.inlineQueue.pop(); - this.inlineQueue.at(-1).src = lastToken.text; - } - else { - tokens.push(token); - } - continue; - } - if (src) { - const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0); - if (this.options.silent) { - console.error(errMsg); - break; - } - else { - throw new Error(errMsg); - } - } - } - this.state.top = true; - return tokens; - } - inline(src, tokens = []) { - this.inlineQueue.push({ src, tokens }); - return tokens; - } - /** - * Lexing/Compiling - */ - inlineTokens(src, tokens = []) { - // String with links masked to avoid interference with em and strong - let maskedSrc = src; - let match = null; - // Mask out reflinks - if (this.tokens.links) { - const links = Object.keys(this.tokens.links); - if (links.length > 0) { - while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) { - if (links.includes(match[0].slice(match[0].lastIndexOf('[') + 1, -1))) { - maskedSrc = maskedSrc.slice(0, match.index) - + '[' + 'a'.repeat(match[0].length - 2) + ']' - + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex); - } - } - } - } - // Mask out other blocks - while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) { - maskedSrc = maskedSrc.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex); - } - // Mask out escaped characters - while ((match = this.tokenizer.rules.inline.anyPunctuation.exec(maskedSrc)) != null) { - maskedSrc = maskedSrc.slice(0, match.index) + '++' + maskedSrc.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex); - } - let keepPrevChar = false; - let prevChar = ''; - while (src) { - if (!keepPrevChar) { - prevChar = ''; - } - keepPrevChar = false; - let token; - // extensions - if (this.options.extensions?.inline?.some((extTokenizer) => { - if (token = extTokenizer.call({ lexer: this }, src, tokens)) { - src = src.substring(token.raw.length); - tokens.push(token); - return true; - } - return false; - })) { - continue; - } - // escape - if (token = this.tokenizer.escape(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // tag - if (token = this.tokenizer.tag(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // link - if (token = this.tokenizer.link(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // reflink, nolink - if (token = this.tokenizer.reflink(src, this.tokens.links)) { - src = src.substring(token.raw.length); - const lastToken = tokens.at(-1); - if (token.type === 'text' && lastToken?.type === 'text') { - lastToken.raw += token.raw; - lastToken.text += token.text; - } - else { - tokens.push(token); - } - continue; - } - // em & strong - if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // code - if (token = this.tokenizer.codespan(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // br - if (token = this.tokenizer.br(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // del (gfm) - if (token = this.tokenizer.del(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // autolink - if (token = this.tokenizer.autolink(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // url (gfm) - if (!this.state.inLink && (token = this.tokenizer.url(src))) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // text - // prevent inlineText consuming extensions by clipping 'src' to extension start - let cutSrc = src; - if (this.options.extensions?.startInline) { - let startIndex = Infinity; - const tempSrc = src.slice(1); - let tempStart; - this.options.extensions.startInline.forEach((getStartIndex) => { - tempStart = getStartIndex.call({ lexer: this }, tempSrc); - if (typeof tempStart === 'number' && tempStart >= 0) { - startIndex = Math.min(startIndex, tempStart); - } - }); - if (startIndex < Infinity && startIndex >= 0) { - cutSrc = src.substring(0, startIndex + 1); - } - } - if (token = this.tokenizer.inlineText(cutSrc)) { - src = src.substring(token.raw.length); - if (token.raw.slice(-1) !== '_') { // Track prevChar before string of ____ started - prevChar = token.raw.slice(-1); - } - keepPrevChar = true; - const lastToken = tokens.at(-1); - if (lastToken?.type === 'text') { - lastToken.raw += token.raw; - lastToken.text += token.text; - } - else { - tokens.push(token); - } - continue; - } - if (src) { - const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0); - if (this.options.silent) { - console.error(errMsg); - break; - } - else { - throw new Error(errMsg); - } - } - } - return tokens; - } -} - -/** - * Renderer - */ -class _Renderer { - options; - parser; // set by the parser - constructor(options) { - this.options = options || _defaults; - } - space(token) { - return ''; - } - code({ text, lang, escaped }) { - const langString = (lang || '').match(other.notSpaceStart)?.[0]; - const code = text.replace(other.endingNewline, '') + '\n'; - if (!langString) { - return '
    '
    -                + (escaped ? code : escape(code, true))
    -                + '
    \n'; - } - return '
    '
    -            + (escaped ? code : escape(code, true))
    -            + '
    \n'; - } - blockquote({ tokens }) { - const body = this.parser.parse(tokens); - return `
    \n${body}
    \n`; - } - html({ text }) { - return text; - } - heading({ tokens, depth }) { - return `${this.parser.parseInline(tokens)}\n`; - } - hr(token) { - return '
    \n'; - } - list(token) { - const ordered = token.ordered; - const start = token.start; - let body = ''; - for (let j = 0; j < token.items.length; j++) { - const item = token.items[j]; - body += this.listitem(item); - } - const type = ordered ? 'ol' : 'ul'; - const startAttr = (ordered && start !== 1) ? (' start="' + start + '"') : ''; - return '<' + type + startAttr + '>\n' + body + '\n'; - } - listitem(item) { - let itemBody = ''; - if (item.task) { - const checkbox = this.checkbox({ checked: !!item.checked }); - if (item.loose) { - if (item.tokens[0]?.type === 'paragraph') { - item.tokens[0].text = checkbox + ' ' + item.tokens[0].text; - if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') { - item.tokens[0].tokens[0].text = checkbox + ' ' + escape(item.tokens[0].tokens[0].text); - item.tokens[0].tokens[0].escaped = true; - } - } - else { - item.tokens.unshift({ - type: 'text', - raw: checkbox + ' ', - text: checkbox + ' ', - escaped: true, - }); - } - } - else { - itemBody += checkbox + ' '; - } - } - itemBody += this.parser.parse(item.tokens, !!item.loose); - return `
  • ${itemBody}
  • \n`; - } - checkbox({ checked }) { - return ''; - } - paragraph({ tokens }) { - return `

    ${this.parser.parseInline(tokens)}

    \n`; - } - table(token) { - let header = ''; - // header - let cell = ''; - for (let j = 0; j < token.header.length; j++) { - cell += this.tablecell(token.header[j]); - } - header += this.tablerow({ text: cell }); - let body = ''; - for (let j = 0; j < token.rows.length; j++) { - const row = token.rows[j]; - cell = ''; - for (let k = 0; k < row.length; k++) { - cell += this.tablecell(row[k]); - } - body += this.tablerow({ text: cell }); - } - if (body) - body = `${body}`; - return '\n' - + '\n' - + header - + '\n' - + body - + '
    \n'; - } - tablerow({ text }) { - return `\n${text}\n`; - } - tablecell(token) { - const content = this.parser.parseInline(token.tokens); - const type = token.header ? 'th' : 'td'; - const tag = token.align - ? `<${type} align="${token.align}">` - : `<${type}>`; - return tag + content + `\n`; - } - /** - * span level renderer - */ - strong({ tokens }) { - return `${this.parser.parseInline(tokens)}`; - } - em({ tokens }) { - return `${this.parser.parseInline(tokens)}`; - } - codespan({ text }) { - return `${escape(text, true)}`; - } - br(token) { - return '
    '; - } - del({ tokens }) { - return `${this.parser.parseInline(tokens)}`; - } - link({ href, title, tokens }) { - const text = this.parser.parseInline(tokens); - const cleanHref = cleanUrl(href); - if (cleanHref === null) { - return text; - } - href = cleanHref; - let out = '
    '; - return out; - } - image({ href, title, text }) { - const cleanHref = cleanUrl(href); - if (cleanHref === null) { - return escape(text); - } - href = cleanHref; - let out = `${text} { - const tokens = genericToken[childTokens].flat(Infinity); - values = values.concat(this.walkTokens(tokens, callback)); - }); - } - else if (genericToken.tokens) { - values = values.concat(this.walkTokens(genericToken.tokens, callback)); - } - } - } - } - return values; - } - use(...args) { - const extensions = this.defaults.extensions || { renderers: {}, childTokens: {} }; - args.forEach((pack) => { - // copy options to new object - const opts = { ...pack }; - // set async to true if it was set to true before - opts.async = this.defaults.async || opts.async || false; - // ==-- Parse "addon" extensions --== // - if (pack.extensions) { - pack.extensions.forEach((ext) => { - if (!ext.name) { - throw new Error('extension name required'); - } - if ('renderer' in ext) { // Renderer extensions - const prevRenderer = extensions.renderers[ext.name]; - if (prevRenderer) { - // Replace extension with func to run new extension but fall back if false - extensions.renderers[ext.name] = function (...args) { - let ret = ext.renderer.apply(this, args); - if (ret === false) { - ret = prevRenderer.apply(this, args); - } - return ret; - }; - } - else { - extensions.renderers[ext.name] = ext.renderer; - } - } - if ('tokenizer' in ext) { // Tokenizer Extensions - if (!ext.level || (ext.level !== 'block' && ext.level !== 'inline')) { - throw new Error("extension level must be 'block' or 'inline'"); - } - const extLevel = extensions[ext.level]; - if (extLevel) { - extLevel.unshift(ext.tokenizer); - } - else { - extensions[ext.level] = [ext.tokenizer]; - } - if (ext.start) { // Function to check for start of token - if (ext.level === 'block') { - if (extensions.startBlock) { - extensions.startBlock.push(ext.start); - } - else { - extensions.startBlock = [ext.start]; - } - } - else if (ext.level === 'inline') { - if (extensions.startInline) { - extensions.startInline.push(ext.start); - } - else { - extensions.startInline = [ext.start]; - } - } - } - } - if ('childTokens' in ext && ext.childTokens) { // Child tokens to be visited by walkTokens - extensions.childTokens[ext.name] = ext.childTokens; - } - }); - opts.extensions = extensions; - } - // ==-- Parse "overwrite" extensions --== // - if (pack.renderer) { - const renderer = this.defaults.renderer || new _Renderer(this.defaults); - for (const prop in pack.renderer) { - if (!(prop in renderer)) { - throw new Error(`renderer '${prop}' does not exist`); - } - if (['options', 'parser'].includes(prop)) { - // ignore options property - continue; - } - const rendererProp = prop; - const rendererFunc = pack.renderer[rendererProp]; - const prevRenderer = renderer[rendererProp]; - // Replace renderer with func to run extension, but fall back if false - renderer[rendererProp] = (...args) => { - let ret = rendererFunc.apply(renderer, args); - if (ret === false) { - ret = prevRenderer.apply(renderer, args); - } - return ret || ''; - }; - } - opts.renderer = renderer; - } - if (pack.tokenizer) { - const tokenizer = this.defaults.tokenizer || new _Tokenizer(this.defaults); - for (const prop in pack.tokenizer) { - if (!(prop in tokenizer)) { - throw new Error(`tokenizer '${prop}' does not exist`); - } - if (['options', 'rules', 'lexer'].includes(prop)) { - // ignore options, rules, and lexer properties - continue; - } - const tokenizerProp = prop; - const tokenizerFunc = pack.tokenizer[tokenizerProp]; - const prevTokenizer = tokenizer[tokenizerProp]; - // Replace tokenizer with func to run extension, but fall back if false - // @ts-expect-error cannot type tokenizer function dynamically - tokenizer[tokenizerProp] = (...args) => { - let ret = tokenizerFunc.apply(tokenizer, args); - if (ret === false) { - ret = prevTokenizer.apply(tokenizer, args); - } - return ret; - }; - } - opts.tokenizer = tokenizer; - } - // ==-- Parse Hooks extensions --== // - if (pack.hooks) { - const hooks = this.defaults.hooks || new _Hooks(); - for (const prop in pack.hooks) { - if (!(prop in hooks)) { - throw new Error(`hook '${prop}' does not exist`); - } - if (['options', 'block'].includes(prop)) { - // ignore options and block properties - continue; - } - const hooksProp = prop; - const hooksFunc = pack.hooks[hooksProp]; - const prevHook = hooks[hooksProp]; - if (_Hooks.passThroughHooks.has(prop)) { - // @ts-expect-error cannot type hook function dynamically - hooks[hooksProp] = (arg) => { - if (this.defaults.async) { - return Promise.resolve(hooksFunc.call(hooks, arg)).then(ret => { - return prevHook.call(hooks, ret); - }); - } - const ret = hooksFunc.call(hooks, arg); - return prevHook.call(hooks, ret); - }; - } - else { - // @ts-expect-error cannot type hook function dynamically - hooks[hooksProp] = (...args) => { - let ret = hooksFunc.apply(hooks, args); - if (ret === false) { - ret = prevHook.apply(hooks, args); - } - return ret; - }; - } - } - opts.hooks = hooks; - } - // ==-- Parse WalkTokens extensions --== // - if (pack.walkTokens) { - const walkTokens = this.defaults.walkTokens; - const packWalktokens = pack.walkTokens; - opts.walkTokens = function (token) { - let values = []; - values.push(packWalktokens.call(this, token)); - if (walkTokens) { - values = values.concat(walkTokens.call(this, token)); - } - return values; - }; - } - this.defaults = { ...this.defaults, ...opts }; - }); - return this; - } - setOptions(opt) { - this.defaults = { ...this.defaults, ...opt }; - return this; - } - lexer(src, options) { - return _Lexer.lex(src, options ?? this.defaults); - } - parser(tokens, options) { - return _Parser.parse(tokens, options ?? this.defaults); - } - parseMarkdown(blockType) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const parse = (src, options) => { - const origOpt = { ...options }; - const opt = { ...this.defaults, ...origOpt }; - const throwError = this.onError(!!opt.silent, !!opt.async); - // throw error if an extension set async to true but parse was called with async: false - if (this.defaults.async === true && origOpt.async === false) { - return throwError(new Error('marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.')); - } - // throw error in case of non string input - if (typeof src === 'undefined' || src === null) { - return throwError(new Error('marked(): input parameter is undefined or null')); - } - if (typeof src !== 'string') { - return throwError(new Error('marked(): input parameter is of type ' - + Object.prototype.toString.call(src) + ', string expected')); - } - if (opt.hooks) { - opt.hooks.options = opt; - opt.hooks.block = blockType; - } - const lexer = opt.hooks ? opt.hooks.provideLexer() : (blockType ? _Lexer.lex : _Lexer.lexInline); - const parser = opt.hooks ? opt.hooks.provideParser() : (blockType ? _Parser.parse : _Parser.parseInline); - if (opt.async) { - return Promise.resolve(opt.hooks ? opt.hooks.preprocess(src) : src) - .then(src => lexer(src, opt)) - .then(tokens => opt.hooks ? opt.hooks.processAllTokens(tokens) : tokens) - .then(tokens => opt.walkTokens ? Promise.all(this.walkTokens(tokens, opt.walkTokens)).then(() => tokens) : tokens) - .then(tokens => parser(tokens, opt)) - .then(html => opt.hooks ? opt.hooks.postprocess(html) : html) - .catch(throwError); - } - try { - if (opt.hooks) { - src = opt.hooks.preprocess(src); - } - let tokens = lexer(src, opt); - if (opt.hooks) { - tokens = opt.hooks.processAllTokens(tokens); - } - if (opt.walkTokens) { - this.walkTokens(tokens, opt.walkTokens); - } - let html = parser(tokens, opt); - if (opt.hooks) { - html = opt.hooks.postprocess(html); - } - return html; - } - catch (e) { - return throwError(e); - } - }; - return parse; - } - onError(silent, async) { - return (e) => { - e.message += '\nPlease report this to https://github.com/markedjs/marked.'; - if (silent) { - const msg = '

    An error occurred:

    '
    -                    + escape(e.message + '', true)
    -                    + '
    '; - if (async) { - return Promise.resolve(msg); - } - return msg; - } - if (async) { - return Promise.reject(e); - } - throw e; - }; - } -} - -const markedInstance = new Marked(); -function marked(src, opt) { - return markedInstance.parse(src, opt); -} -/** - * Sets the default options. - * - * @param options Hash of options - */ -marked.options = - marked.setOptions = function (options) { - markedInstance.setOptions(options); - marked.defaults = markedInstance.defaults; - changeDefaults(marked.defaults); - return marked; - }; -/** - * Gets the original marked default options. - */ -marked.getDefaults = _getDefaults; -marked.defaults = _defaults; -/** - * Use Extension - */ -marked.use = function (...args) { - markedInstance.use(...args); - marked.defaults = markedInstance.defaults; - changeDefaults(marked.defaults); - return marked; -}; -/** - * Run callback for every token - */ -marked.walkTokens = function (tokens, callback) { - return markedInstance.walkTokens(tokens, callback); -}; -/** - * Compiles markdown to HTML without enclosing `p` tag. - * - * @param src String of markdown source to be compiled - * @param options Hash of options - * @return String of compiled HTML - */ -marked.parseInline = markedInstance.parseInline; -/** - * Expose - */ -marked.Parser = _Parser; -marked.parser = _Parser.parse; -marked.Renderer = _Renderer; -marked.TextRenderer = _TextRenderer; -marked.Lexer = _Lexer; -marked.lexer = _Lexer.lex; -marked.Tokenizer = _Tokenizer; -marked.Hooks = _Hooks; -marked.parse = marked; -const options = marked.options; -const setOptions = marked.setOptions; -const use = marked.use; -const walkTokens = marked.walkTokens; -const parseInline = marked.parseInline; -const parse = marked; -const parser = _Parser.parse; -const lexer = _Lexer.lex; - -export { _Hooks as Hooks, _Lexer as Lexer, Marked, _Parser as Parser, _Renderer as Renderer, _TextRenderer as TextRenderer, _Tokenizer as Tokenizer, _defaults as defaults, _getDefaults as getDefaults, lexer, marked, options, parse, parseInline, parser, setOptions, use, walkTokens }; -//# sourceMappingURL=marked.esm.js.map diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdf_viewer/viewer.html b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdf_viewer/viewer.html deleted file mode 100644 index 32ac36286a7..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdf_viewer/viewer.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - PDF viewer - - - - - - -
    -
    -
    - - - - diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdf_viewer/viewer.mjs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdf_viewer/viewer.mjs deleted file mode 100644 index 8a4a6b76f5e..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdf_viewer/viewer.mjs +++ /dev/null @@ -1,62 +0,0 @@ -import { GlobalWorkerOptions } from '../pdfjs-dist/dist/build/pdf.min.mjs'; -import { EventBus, PDFLinkService, PDFFindController, PDFViewer } from '../pdfjs-dist/dist/web/pdf_viewer.mjs'; - -GlobalWorkerOptions.workerSrc = '../pdfjs-dist/dist/build/pdf.worker.min.mjs'; - -// Extract the file path from the URL query string. -const url = new URL(window.location); -const fileUrl = url.searchParams.get('file'); -if (!fileUrl) { - throw new Error('File not specified in the URL query string'); -} - -const container = document.getElementById('viewerContainer'); -const eventBus = new EventBus(); - -// Enable hyperlinks within PDF files. -const pdfLinkService = new PDFLinkService({ - eventBus, -}); - -// Enable the find controller. -const pdfFindController = new PDFFindController({ - eventBus, - linkService: pdfLinkService, -}); - -// Create the PDF viewer. -const pdfViewer = new PDFViewer({ - container, - eventBus, - linkService: pdfLinkService, - findController: pdfFindController, -}); -pdfLinkService.setViewer(pdfViewer); - -// Allow navigation to a citation from the URL hash. -eventBus.on('pagesinit', function () { - pdfLinkService.setHash(window.location.hash.substring(1)); -}); - -// Define how the "search" query parameter is handled. -eventBus.on('findfromurlhash', function(evt) { - eventBus.dispatch('find', { - source: evt.source, - type: '', - query: evt.query, - caseSensitive: false, - entireWord: false, - highlightAll: false, - findPrevious: false, - matchDiacritics: true, - }); -}); - -// Load and initialize the document. -const pdfDocument = await pdfjsLib.getDocument({ - url: fileUrl, - enableXfa: true, -}).promise; - -pdfViewer.setDocument(pdfDocument); -pdfLinkService.setDocument(pdfDocument, null); diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/README.md b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/README.md deleted file mode 100644 index 8e77fba7d43..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/README.md +++ /dev/null @@ -1,10 +0,0 @@ -pdfjs-dist version 4.10.38 -https://github.com/mozilla/pdf.js -License: Apache-2.0 - -To update, replace the following files with updated versions from https://www.npmjs.com/package/pdfjs-dist: -* `build/pdf.min.mjs` -* `build/pdf.worker.min.mjs` -* `web/pdf_viewer.css` -* `web/pdf_viewer.mjs` -* `web/images/loading-icon.gif` diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/build/pdf.min.mjs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/build/pdf.min.mjs deleted file mode 100644 index d7cfa914562..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/build/pdf.min.mjs +++ /dev/null @@ -1,21 +0,0 @@ -/** - * @licstart The following is the entire license notice for the - * JavaScript code in this page - * - * Copyright 2024 Mozilla Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * @licend The above is the entire license notice for the - * JavaScript code in this page - */var t={d:(e,i)=>{for(var s in i)t.o(i,s)&&!t.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:i[s]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e)},__webpack_exports__ = globalThis.pdfjsLib = {};t.d(__webpack_exports__,{AbortException:()=>AbortException,AnnotationEditorLayer:()=>AnnotationEditorLayer,AnnotationEditorParamsType:()=>m,AnnotationEditorType:()=>g,AnnotationEditorUIManager:()=>AnnotationEditorUIManager,AnnotationLayer:()=>AnnotationLayer,AnnotationMode:()=>p,ColorPicker:()=>ColorPicker,DOMSVGFactory:()=>DOMSVGFactory,DrawLayer:()=>DrawLayer,FeatureTest:()=>util_FeatureTest,GlobalWorkerOptions:()=>GlobalWorkerOptions,ImageKind:()=>_,InvalidPDFException:()=>InvalidPDFException,MissingPDFException:()=>MissingPDFException,OPS:()=>X,OutputScale:()=>OutputScale,PDFDataRangeTransport:()=>PDFDataRangeTransport,PDFDateString:()=>PDFDateString,PDFWorker:()=>PDFWorker,PasswordResponses:()=>K,PermissionFlag:()=>f,PixelsPerInch:()=>PixelsPerInch,RenderingCancelledException:()=>RenderingCancelledException,TextLayer:()=>TextLayer,TouchManager:()=>TouchManager,UnexpectedResponseException:()=>UnexpectedResponseException,Util:()=>Util,VerbosityLevel:()=>q,XfaLayer:()=>XfaLayer,build:()=>Nt,createValidAbsoluteUrl:()=>createValidAbsoluteUrl,fetchData:()=>fetchData,getDocument:()=>getDocument,getFilenameFromUrl:()=>getFilenameFromUrl,getPdfFilenameFromUrl:()=>getPdfFilenameFromUrl,getXfaPageViewport:()=>getXfaPageViewport,isDataScheme:()=>isDataScheme,isPdfFile:()=>isPdfFile,noContextMenu:()=>noContextMenu,normalizeUnicode:()=>normalizeUnicode,setLayerDimensions:()=>setLayerDimensions,shadow:()=>shadow,stopEvent:()=>stopEvent,version:()=>Ot});const e=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),i=[1,0,0,1,0,0],s=[.001,0,0,.001,0,0],n=1.35,a=1,r=2,o=4,l=16,h=32,d=64,c=128,u=256,p={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},g={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},m={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,HIGHLIGHT_COLOR:31,HIGHLIGHT_DEFAULT_COLOR:32,HIGHLIGHT_THICKNESS:33,HIGHLIGHT_FREE:34,HIGHLIGHT_SHOW_ALL:35,DRAW_STEP:41},f={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},b=0,A=1,w=2,v=3,y=3,x=4,_={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},E=1,S=2,C=3,T=4,M=5,P=6,D=7,k=8,R=9,I=10,F=11,L=12,O=13,N=14,B=15,H=16,z=17,U=20,G=1,$=2,V=3,j=4,W=5,q={ERRORS:0,WARNINGS:1,INFOS:5},X={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91,setStrokeTransparent:92,setFillTransparent:93},K={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let Y=q.WARNINGS;function setVerbosityLevel(t){Number.isInteger(t)&&(Y=t)}function getVerbosityLevel(){return Y}function info(t){Y>=q.INFOS&&console.log(`Info: ${t}`)}function warn(t){Y>=q.WARNINGS&&console.log(`Warning: ${t}`)}function unreachable(t){throw new Error(t)}function assert(t,e){t||unreachable(e)}function createValidAbsoluteUrl(t,e=null,i=null){if(!t)return null;try{if(i&&"string"==typeof t){if(i.addDefaultProtocol&&t.startsWith("www.")){const e=t.match(/\./g);e?.length>=2&&(t=`http://${t}`)}if(i.tryConvertEncoding)try{t=function stringToUTF8String(t){return decodeURIComponent(escape(t))}(t)}catch{}}const s=e?new URL(t,e):new URL(t);if(function _isValidProtocol(t){switch(t?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(s))return s}catch{}return null}function shadow(t,e,i,s=!1){Object.defineProperty(t,e,{value:i,enumerable:!s,configurable:!0,writable:!1});return i}const Q=function BaseExceptionClosure(){function BaseException(t,e){this.message=t;this.name=e}BaseException.prototype=new Error;BaseException.constructor=BaseException;return BaseException}();class PasswordException extends Q{constructor(t,e){super(t,"PasswordException");this.code=e}}class UnknownErrorException extends Q{constructor(t,e){super(t,"UnknownErrorException");this.details=e}}class InvalidPDFException extends Q{constructor(t){super(t,"InvalidPDFException")}}class MissingPDFException extends Q{constructor(t){super(t,"MissingPDFException")}}class UnexpectedResponseException extends Q{constructor(t,e){super(t,"UnexpectedResponseException");this.status=e}}class FormatError extends Q{constructor(t){super(t,"FormatError")}}class AbortException extends Q{constructor(t){super(t,"AbortException")}}function bytesToString(t){"object"==typeof t&&void 0!==t?.length||unreachable("Invalid argument for bytesToString");const e=t.length,i=8192;if(et.toString(16).padStart(2,"0")));class Util{static makeHexColor(t,e,i){return`#${J[t]}${J[e]}${J[i]}`}static scaleMinMax(t,e){let i;if(t[0]){if(t[0]<0){i=e[0];e[0]=e[2];e[2]=i}e[0]*=t[0];e[2]*=t[0];if(t[3]<0){i=e[1];e[1]=e[3];e[3]=i}e[1]*=t[3];e[3]*=t[3]}else{i=e[0];e[0]=e[1];e[1]=i;i=e[2];e[2]=e[3];e[3]=i;if(t[1]<0){i=e[1];e[1]=e[3];e[3]=i}e[1]*=t[1];e[3]*=t[1];if(t[2]<0){i=e[0];e[0]=e[2];e[2]=i}e[0]*=t[2];e[2]*=t[2]}e[0]+=t[4];e[1]+=t[5];e[2]+=t[4];e[3]+=t[5]}static transform(t,e){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],t[0]*e[4]+t[2]*e[5]+t[4],t[1]*e[4]+t[3]*e[5]+t[5]]}static applyTransform(t,e){return[t[0]*e[0]+t[1]*e[2]+e[4],t[0]*e[1]+t[1]*e[3]+e[5]]}static applyInverseTransform(t,e){const i=e[0]*e[3]-e[1]*e[2];return[(t[0]*e[3]-t[1]*e[2]+e[2]*e[5]-e[4]*e[3])/i,(-t[0]*e[1]+t[1]*e[0]+e[4]*e[1]-e[5]*e[0])/i]}static getAxialAlignedBoundingBox(t,e){const i=this.applyTransform(t,e),s=this.applyTransform(t.slice(2,4),e),n=this.applyTransform([t[0],t[3]],e),a=this.applyTransform([t[2],t[1]],e);return[Math.min(i[0],s[0],n[0],a[0]),Math.min(i[1],s[1],n[1],a[1]),Math.max(i[0],s[0],n[0],a[0]),Math.max(i[1],s[1],n[1],a[1])]}static inverseTransform(t){const e=t[0]*t[3]-t[1]*t[2];return[t[3]/e,-t[1]/e,-t[2]/e,t[0]/e,(t[2]*t[5]-t[4]*t[3])/e,(t[4]*t[1]-t[5]*t[0])/e]}static singularValueDecompose2dScale(t){const e=[t[0],t[2],t[1],t[3]],i=t[0]*e[0]+t[1]*e[2],s=t[0]*e[1]+t[1]*e[3],n=t[2]*e[0]+t[3]*e[2],a=t[2]*e[1]+t[3]*e[3],r=(i+a)/2,o=Math.sqrt((i+a)**2-4*(i*a-n*s))/2,l=r+o||1,h=r-o||1;return[Math.sqrt(l),Math.sqrt(h)]}static normalizeRect(t){const e=t.slice(0);if(t[0]>t[2]){e[0]=t[2];e[2]=t[0]}if(t[1]>t[3]){e[1]=t[3];e[3]=t[1]}return e}static intersect(t,e){const i=Math.max(Math.min(t[0],t[2]),Math.min(e[0],e[2])),s=Math.min(Math.max(t[0],t[2]),Math.max(e[0],e[2]));if(i>s)return null;const n=Math.max(Math.min(t[1],t[3]),Math.min(e[1],e[3])),a=Math.min(Math.max(t[1],t[3]),Math.max(e[1],e[3]));return n>a?null:[i,n,s,a]}static#t(t,e,i,s,n,a,r,o,l,h){if(l<=0||l>=1)return;const d=1-l,c=l*l,u=c*l,p=d*(d*(d*t+3*l*e)+3*c*i)+u*s,g=d*(d*(d*n+3*l*a)+3*c*r)+u*o;h[0]=Math.min(h[0],p);h[1]=Math.min(h[1],g);h[2]=Math.max(h[2],p);h[3]=Math.max(h[3],g)}static#e(t,e,i,s,n,a,r,o,l,h,d,c){if(Math.abs(l)<1e-12){Math.abs(h)>=1e-12&&this.#t(t,e,i,s,n,a,r,o,-d/h,c);return}const u=h**2-4*d*l;if(u<0)return;const p=Math.sqrt(u),g=2*l;this.#t(t,e,i,s,n,a,r,o,(-h+p)/g,c);this.#t(t,e,i,s,n,a,r,o,(-h-p)/g,c)}static bezierBoundingBox(t,e,i,s,n,a,r,o,l){if(l){l[0]=Math.min(l[0],t,r);l[1]=Math.min(l[1],e,o);l[2]=Math.max(l[2],t,r);l[3]=Math.max(l[3],e,o)}else l=[Math.min(t,r),Math.min(e,o),Math.max(t,r),Math.max(e,o)];this.#e(t,i,n,r,e,s,a,o,3*(3*(i-n)-t+r),6*(t-2*i+n),3*(i-t),l);this.#e(t,i,n,r,e,s,a,o,3*(3*(s-a)-e+o),6*(e-2*s+a),3*(s-e),l);return l}}let Z=null,tt=null;function normalizeUnicode(t){if(!Z){Z=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu;tt=new Map([["ſt","ſt"]])}return t.replaceAll(Z,((t,e,i)=>e?e.normalize("NFKC"):tt.get(i)))}const et="pdfjs_internal_id_";"function"!=typeof Promise.try&&(Promise.try=function(t,...e){return new Promise((i=>{i(t(...e))}))});const it="http://www.w3.org/2000/svg";class PixelsPerInch{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function fetchData(t,e="text"){if(isValidFetchUrl(t,document.baseURI)){const i=await fetch(t);if(!i.ok)throw new Error(i.statusText);switch(e){case"arraybuffer":return i.arrayBuffer();case"blob":return i.blob();case"json":return i.json()}return i.text()}return new Promise(((i,s)=>{const n=new XMLHttpRequest;n.open("GET",t,!0);n.responseType=e;n.onreadystatechange=()=>{if(n.readyState===XMLHttpRequest.DONE)if(200!==n.status&&0!==n.status)s(new Error(n.statusText));else{switch(e){case"arraybuffer":case"blob":case"json":i(n.response);return}i(n.responseText)}};n.send(null)}))}class PageViewport{constructor({viewBox:t,userUnit:e,scale:i,rotation:s,offsetX:n=0,offsetY:a=0,dontFlip:r=!1}){this.viewBox=t;this.userUnit=e;this.scale=i;this.rotation=s;this.offsetX=n;this.offsetY=a;i*=e;const o=(t[2]+t[0])/2,l=(t[3]+t[1])/2;let h,d,c,u,p,g,m,f;(s%=360)<0&&(s+=360);switch(s){case 180:h=-1;d=0;c=0;u=1;break;case 90:h=0;d=1;c=1;u=0;break;case 270:h=0;d=-1;c=-1;u=0;break;case 0:h=1;d=0;c=0;u=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}if(r){c=-c;u=-u}if(0===h){p=Math.abs(l-t[1])*i+n;g=Math.abs(o-t[0])*i+a;m=(t[3]-t[1])*i;f=(t[2]-t[0])*i}else{p=Math.abs(o-t[0])*i+n;g=Math.abs(l-t[1])*i+a;m=(t[2]-t[0])*i;f=(t[3]-t[1])*i}this.transform=[h*i,d*i,c*i,u*i,p-h*i*o-c*i*l,g-d*i*o-u*i*l];this.width=m;this.height=f}get rawDims(){const{userUnit:t,viewBox:e}=this,i=e.map((e=>e*t));return shadow(this,"rawDims",{pageWidth:i[2]-i[0],pageHeight:i[3]-i[1],pageX:i[0],pageY:i[1]})}clone({scale:t=this.scale,rotation:e=this.rotation,offsetX:i=this.offsetX,offsetY:s=this.offsetY,dontFlip:n=!1}={}){return new PageViewport({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:t,rotation:e,offsetX:i,offsetY:s,dontFlip:n})}convertToViewportPoint(t,e){return Util.applyTransform([t,e],this.transform)}convertToViewportRectangle(t){const e=Util.applyTransform([t[0],t[1]],this.transform),i=Util.applyTransform([t[2],t[3]],this.transform);return[e[0],e[1],i[0],i[1]]}convertToPdfPoint(t,e){return Util.applyInverseTransform([t,e],this.transform)}}class RenderingCancelledException extends Q{constructor(t,e=0){super(t,"RenderingCancelledException");this.extraDelay=e}}function isDataScheme(t){const e=t.length;let i=0;for(;i=1&&s<=12?s-1:0;let n=parseInt(e[3],10);n=n>=1&&n<=31?n:1;let a=parseInt(e[4],10);a=a>=0&&a<=23?a:0;let r=parseInt(e[5],10);r=r>=0&&r<=59?r:0;let o=parseInt(e[6],10);o=o>=0&&o<=59?o:0;const l=e[7]||"Z";let h=parseInt(e[8],10);h=h>=0&&h<=23?h:0;let d=parseInt(e[9],10)||0;d=d>=0&&d<=59?d:0;if("-"===l){a+=h;r+=d}else if("+"===l){a-=h;r-=d}return new Date(Date.UTC(i,s,n,a,r,o))}}function getXfaPageViewport(t,{scale:e=1,rotation:i=0}){const{width:s,height:n}=t.attributes.style,a=[0,0,parseInt(s),parseInt(n)];return new PageViewport({viewBox:a,userUnit:1,scale:e,rotation:i})}function getRGB(t){if(t.startsWith("#")){const e=parseInt(t.slice(1),16);return[(16711680&e)>>16,(65280&e)>>8,255&e]}if(t.startsWith("rgb("))return t.slice(4,-1).split(",").map((t=>parseInt(t)));if(t.startsWith("rgba("))return t.slice(5,-1).split(",").map((t=>parseInt(t))).slice(0,3);warn(`Not a valid color format: "${t}"`);return[0,0,0]}function getCurrentTransform(t){const{a:e,b:i,c:s,d:n,e:a,f:r}=t.getTransform();return[e,i,s,n,a,r]}function getCurrentTransformInverse(t){const{a:e,b:i,c:s,d:n,e:a,f:r}=t.getTransform().invertSelf();return[e,i,s,n,a,r]}function setLayerDimensions(t,e,i=!1,s=!0){if(e instanceof PageViewport){const{pageWidth:s,pageHeight:n}=e.rawDims,{style:a}=t,r=util_FeatureTest.isCSSRoundSupported,o=`var(--scale-factor) * ${s}px`,l=`var(--scale-factor) * ${n}px`,h=r?`round(down, ${o}, var(--scale-round-x, 1px))`:`calc(${o})`,d=r?`round(down, ${l}, var(--scale-round-y, 1px))`:`calc(${l})`;if(i&&e.rotation%180!=0){a.width=d;a.height=h}else{a.width=h;a.height=d}}s&&t.setAttribute("data-main-rotation",e.rotation)}class OutputScale{constructor(){const t=window.devicePixelRatio||1;this.sx=t;this.sy=t}get scaled(){return 1!==this.sx||1!==this.sy}get symmetric(){return this.sx===this.sy}}class EditorToolbar{#s=null;#n=null;#a;#r=null;#o=null;static#l=null;constructor(t){this.#a=t;EditorToolbar.#l||=Object.freeze({freetext:"pdfjs-editor-remove-freetext-button",highlight:"pdfjs-editor-remove-highlight-button",ink:"pdfjs-editor-remove-ink-button",stamp:"pdfjs-editor-remove-stamp-button"})}render(){const t=this.#s=document.createElement("div");t.classList.add("editToolbar","hidden");t.setAttribute("role","toolbar");const e=this.#a._uiManager._signal;t.addEventListener("contextmenu",noContextMenu,{signal:e});t.addEventListener("pointerdown",EditorToolbar.#h,{signal:e});const i=this.#r=document.createElement("div");i.className="buttons";t.append(i);const s=this.#a.toolbarPosition;if(s){const{style:e}=t,i="ltr"===this.#a._uiManager.direction?1-s[0]:s[0];e.insetInlineEnd=100*i+"%";e.top=`calc(${100*s[1]}% + var(--editor-toolbar-vert-offset))`}this.#d();return t}get div(){return this.#s}static#h(t){t.stopPropagation()}#c(t){this.#a._focusEventsAllowed=!1;stopEvent(t)}#u(t){this.#a._focusEventsAllowed=!0;stopEvent(t)}#p(t){const e=this.#a._uiManager._signal;t.addEventListener("focusin",this.#c.bind(this),{capture:!0,signal:e});t.addEventListener("focusout",this.#u.bind(this),{capture:!0,signal:e});t.addEventListener("contextmenu",noContextMenu,{signal:e})}hide(){this.#s.classList.add("hidden");this.#n?.hideDropdown()}show(){this.#s.classList.remove("hidden");this.#o?.shown()}#d(){const{editorType:t,_uiManager:e}=this.#a,i=document.createElement("button");i.className="delete";i.tabIndex=0;i.setAttribute("data-l10n-id",EditorToolbar.#l[t]);this.#p(i);i.addEventListener("click",(t=>{e.delete()}),{signal:e._signal});this.#r.append(i)}get#g(){const t=document.createElement("div");t.className="divider";return t}async addAltText(t){const e=await t.render();this.#p(e);this.#r.prepend(e,this.#g);this.#o=t}addColorPicker(t){this.#n=t;const e=t.renderButton();this.#p(e);this.#r.prepend(e,this.#g)}remove(){this.#s.remove();this.#n?.destroy();this.#n=null}}class HighlightToolbar{#r=null;#s=null;#m;constructor(t){this.#m=t}#f(){const t=this.#s=document.createElement("div");t.className="editToolbar";t.setAttribute("role","toolbar");t.addEventListener("contextmenu",noContextMenu,{signal:this.#m._signal});const e=this.#r=document.createElement("div");e.className="buttons";t.append(e);this.#b();return t}#A(t,e){let i=0,s=0;for(const n of t){const t=n.y+n.height;if(ti){s=a;i=t}else e?a>s&&(s=a):a{this.#m.highlightSelection("floating_button")}),{signal:i});this.#r.append(t)}}function bindEvents(t,e,i){for(const s of i)e.addEventListener(s,t[s].bind(t))}class IdManager{#w=0;get id(){return"pdfjs_internal_editor_"+this.#w++}}class ImageManager{#v=function getUuid(){if("function"==typeof crypto.randomUUID)return crypto.randomUUID();const t=new Uint8Array(32);crypto.getRandomValues(t);return bytesToString(t)}();#w=0;#y=null;static get _isSVGFittingCanvas(){const t=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),e=new Image;e.src='data:image/svg+xml;charset=UTF-8,';return shadow(this,"_isSVGFittingCanvas",e.decode().then((()=>{t.drawImage(e,0,0,1,1,0,0,1,3);return 0===new Uint32Array(t.getImageData(0,0,1,1).data.buffer)[0]})))}async#x(t,e){this.#y||=new Map;let i=this.#y.get(t);if(null===i)return null;if(i?.bitmap){i.refCounter+=1;return i}try{i||={bitmap:null,id:`image_${this.#v}_${this.#w++}`,refCounter:0,isSvg:!1};let t;if("string"==typeof e){i.url=e;t=await fetchData(e,"blob")}else e instanceof File?t=i.file=e:e instanceof Blob&&(t=e);if("image/svg+xml"===t.type){const e=ImageManager._isSVGFittingCanvas,s=new FileReader,n=new Image,a=new Promise(((t,a)=>{n.onload=()=>{i.bitmap=n;i.isSvg=!0;t()};s.onload=async()=>{const t=i.svgUrl=s.result;n.src=await e?`${t}#svgView(preserveAspectRatio(none))`:t};n.onerror=s.onerror=a}));s.readAsDataURL(t);await a}else i.bitmap=await createImageBitmap(t);i.refCounter=1}catch(t){warn(t);i=null}this.#y.set(t,i);i&&this.#y.set(i.id,i);return i}async getFromFile(t){const{lastModified:e,name:i,size:s,type:n}=t;return this.#x(`${e}_${i}_${s}_${n}`,t)}async getFromUrl(t){return this.#x(t,t)}async getFromBlob(t,e){const i=await e;return this.#x(t,i)}async getFromId(t){this.#y||=new Map;const e=this.#y.get(t);if(!e)return null;if(e.bitmap){e.refCounter+=1;return e}if(e.file)return this.getFromFile(e.file);if(e.blobPromise){const{blobPromise:t}=e;delete e.blobPromise;return this.getFromBlob(e.id,t)}return this.getFromUrl(e.url)}getFromCanvas(t,e){this.#y||=new Map;let i=this.#y.get(t);if(i?.bitmap){i.refCounter+=1;return i}const s=new OffscreenCanvas(e.width,e.height);s.getContext("2d").drawImage(e,0,0);i={bitmap:s.transferToImageBitmap(),id:`image_${this.#v}_${this.#w++}`,refCounter:1,isSvg:!1};this.#y.set(t,i);this.#y.set(i.id,i);return i}getSvgUrl(t){const e=this.#y.get(t);return e?.isSvg?e.svgUrl:null}deleteId(t){this.#y||=new Map;const e=this.#y.get(t);if(!e)return;e.refCounter-=1;if(0!==e.refCounter)return;const{bitmap:i}=e;if(!e.url&&!e.file){const t=new OffscreenCanvas(i.width,i.height);t.getContext("bitmaprenderer").transferFromImageBitmap(i);e.blobPromise=t.convertToBlob()}i.close?.();e.bitmap=null}isValidId(t){return t.startsWith(`image_${this.#v}_`)}}class CommandManager{#_=[];#E=!1;#S;#C=-1;constructor(t=128){this.#S=t}add({cmd:t,undo:e,post:i,mustExec:s,type:n=NaN,overwriteIfSameType:a=!1,keepUndo:r=!1}){s&&t();if(this.#E)return;const o={cmd:t,undo:e,post:i,type:n};if(-1===this.#C){this.#_.length>0&&(this.#_.length=0);this.#C=0;this.#_.push(o);return}if(a&&this.#_[this.#C].type===n){r&&(o.undo=this.#_[this.#C].undo);this.#_[this.#C]=o;return}const l=this.#C+1;if(l===this.#S)this.#_.splice(0,1);else{this.#C=l;l=0;e--)if(this.#_[e].type!==t){this.#_.splice(e+1,this.#C-e);this.#C=e;return}this.#_.length=0;this.#C=-1}}destroy(){this.#_=null}}class KeyboardManager{constructor(t){this.buffer=[];this.callbacks=new Map;this.allKeys=new Set;const{isMac:e}=util_FeatureTest.platform;for(const[i,s,n={}]of t)for(const t of i){const i=t.startsWith("mac+");if(e&&i){this.callbacks.set(t.slice(4),{callback:s,options:n});this.allKeys.add(t.split("+").at(-1))}else if(!e&&!i){this.callbacks.set(t,{callback:s,options:n});this.allKeys.add(t.split("+").at(-1))}}}#T(t){t.altKey&&this.buffer.push("alt");t.ctrlKey&&this.buffer.push("ctrl");t.metaKey&&this.buffer.push("meta");t.shiftKey&&this.buffer.push("shift");this.buffer.push(t.key);const e=this.buffer.join("+");this.buffer.length=0;return e}exec(t,e){if(!this.allKeys.has(e.key))return;const i=this.callbacks.get(this.#T(e));if(!i)return;const{callback:s,options:{bubbles:n=!1,args:a=[],checker:r=null}}=i;if(!r||r(t,e)){s.bind(t,...a,e)();n||stopEvent(e)}}}class ColorManager{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){const t=new Map([["CanvasText",null],["Canvas",null]]);!function getColorValues(t){const e=document.createElement("span");e.style.visibility="hidden";document.body.append(e);for(const i of t.keys()){e.style.color=i;const s=window.getComputedStyle(e).color;t.set(i,getRGB(s))}e.remove()}(t);return shadow(this,"_colors",t)}convert(t){const e=getRGB(t);if(!window.matchMedia("(forced-colors: active)").matches)return e;for(const[t,i]of this._colors)if(i.every(((t,i)=>t===e[i])))return ColorManager._colorsMapping.get(t);return e}getHexCode(t){const e=this._colors.get(t);return e?Util.makeHexColor(...e):t}}class AnnotationEditorUIManager{#M=new AbortController;#P=null;#D=new Map;#k=new Map;#R=null;#I=null;#F=null;#L=new CommandManager;#O=null;#N=null;#B=0;#H=new Set;#z=null;#U=null;#G=new Set;_editorUndoBar=null;#$=!1;#V=!1;#j=!1;#W=null;#q=null;#X=null;#K=null;#Y=!1;#Q=null;#J=new IdManager;#Z=!1;#tt=!1;#et=null;#it=null;#st=null;#nt=null;#at=g.NONE;#rt=new Set;#ot=null;#lt=null;#ht=null;#dt={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#ct=[0,0];#ut=null;#pt=null;#gt=null;#mt=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=AnnotationEditorUIManager.prototype,arrowChecker=t=>t.#pt.contains(document.activeElement)&&"BUTTON"!==document.activeElement.tagName&&t.hasSomethingToControl(),textInputChecker=(t,{target:e})=>{if(e instanceof HTMLInputElement){const{type:t}=e;return"text"!==t&&"number"!==t}return!0},e=this.TRANSLATE_SMALL,i=this.TRANSLATE_BIG;return shadow(this,"_keyboardManager",new KeyboardManager([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:textInputChecker}],[["ctrl+z","mac+meta+z"],t.undo,{checker:textInputChecker}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:textInputChecker}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],t.delete,{checker:textInputChecker}],[["Enter","mac+Enter"],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#pt.contains(e)&&!t.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#pt.contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-e,0],checker:arrowChecker}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-i,0],checker:arrowChecker}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[e,0],checker:arrowChecker}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[i,0],checker:arrowChecker}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-e],checker:arrowChecker}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-i],checker:arrowChecker}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,e],checker:arrowChecker}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,i],checker:arrowChecker}]]))}constructor(t,e,i,s,n,a,r,o,l,h,d,c,u){const p=this._signal=this.#M.signal;this.#pt=t;this.#gt=e;this.#R=i;this._eventBus=s;s._on("editingaction",this.onEditingAction.bind(this),{signal:p});s._on("pagechanging",this.onPageChanging.bind(this),{signal:p});s._on("scalechanging",this.onScaleChanging.bind(this),{signal:p});s._on("rotationchanging",this.onRotationChanging.bind(this),{signal:p});s._on("setpreference",this.onSetPreference.bind(this),{signal:p});s._on("switchannotationeditorparams",(t=>this.updateParams(t.type,t.value)),{signal:p});this.#ft();this.#bt();this.#At();this.#I=n.annotationStorage;this.#W=n.filterFactory;this.#lt=a;this.#K=r||null;this.#$=o;this.#V=l;this.#j=h;this.#nt=d||null;this.viewParameters={realScale:PixelsPerInch.PDF_TO_CSS_UNITS,rotation:0};this.isShiftKeyDown=!1;this._editorUndoBar=c||null;this._supportsPinchToZoom=!1!==u}destroy(){this.#mt?.resolve();this.#mt=null;this.#M?.abort();this.#M=null;this._signal=null;for(const t of this.#k.values())t.destroy();this.#k.clear();this.#D.clear();this.#G.clear();this.#P=null;this.#rt.clear();this.#L.destroy();this.#R?.destroy();this.#Q?.hide();this.#Q=null;if(this.#q){clearTimeout(this.#q);this.#q=null}if(this.#ut){clearTimeout(this.#ut);this.#ut=null}this._editorUndoBar?.destroy()}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return this.#nt}get useNewAltTextFlow(){return this.#V}get useNewAltTextWhenAddingImage(){return this.#j}get hcmFilter(){return shadow(this,"hcmFilter",this.#lt?this.#W.addHCMFilter(this.#lt.foreground,this.#lt.background):"none")}get direction(){return shadow(this,"direction",getComputedStyle(this.#pt).direction)}get highlightColors(){return shadow(this,"highlightColors",this.#K?new Map(this.#K.split(",").map((t=>t.split("=").map((t=>t.trim()))))):null)}get highlightColorNames(){return shadow(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,(t=>t.reverse()))):null)}setCurrentDrawingSession(t){if(t){this.unselectAll();this.disableUserSelect(!0)}else this.disableUserSelect(!1);this.#N=t}setMainHighlightColorPicker(t){this.#st=t}editAltText(t,e=!1){this.#R?.editAltText(this,t,e)}switchToMode(t,e){this._eventBus.on("annotationeditormodechanged",e,{once:!0,signal:this._signal});this._eventBus.dispatch("showannotationeditorui",{source:this,mode:t})}setPreference(t,e){this._eventBus.dispatch("setpreference",{source:this,name:t,value:e})}onSetPreference({name:t,value:e}){if("enableNewAltTextWhenAddingImage"===t)this.#j=e}onPageChanging({pageNumber:t}){this.#B=t-1}focusMainContainer(){this.#pt.focus()}findParent(t,e){for(const i of this.#k.values()){const{x:s,y:n,width:a,height:r}=i.div.getBoundingClientRect();if(t>=s&&t<=s+a&&e>=n&&e<=n+r)return i}return null}disableUserSelect(t=!1){this.#gt.classList.toggle("noUserSelect",t)}addShouldRescale(t){this.#G.add(t)}removeShouldRescale(t){this.#G.delete(t)}onScaleChanging({scale:t}){this.commitOrRemove();this.viewParameters.realScale=t*PixelsPerInch.PDF_TO_CSS_UNITS;for(const t of this.#G)t.onScaleChanging();this.#N?.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove();this.viewParameters.rotation=t}#wt({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}#vt(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const e of this.#k.values())if(e.hasTextLayer(t))return e;return null}highlightSelection(t=""){const e=document.getSelection();if(!e||e.isCollapsed)return;const{anchorNode:i,anchorOffset:s,focusNode:n,focusOffset:a}=e,r=e.toString(),o=this.#wt(e).closest(".textLayer"),l=this.getSelectionBoxes(o);if(!l)return;e.empty();const h=this.#vt(o),d=this.#at===g.NONE,callback=()=>{h?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:l,anchorNode:i,anchorOffset:s,focusNode:n,focusOffset:a,text:r});d&&this.showAllEditors("highlight",!0,!0)};d?this.switchToMode(g.HIGHLIGHT,callback):callback()}#yt(){const t=document.getSelection();if(!t||t.isCollapsed)return;const e=this.#wt(t).closest(".textLayer"),i=this.getSelectionBoxes(e);if(i){this.#Q||=new HighlightToolbar(this);this.#Q.show(e,i,"ltr"===this.direction)}}addToAnnotationStorage(t){t.isEmpty()||!this.#I||this.#I.has(t.id)||this.#I.setValue(t.id,t)}#xt(){const t=document.getSelection();if(!t||t.isCollapsed){if(this.#ot){this.#Q?.hide();this.#ot=null;this.#_t({hasSelectedText:!1})}return}const{anchorNode:e}=t;if(e===this.#ot)return;const i=this.#wt(t).closest(".textLayer");if(i){this.#Q?.hide();this.#ot=e;this.#_t({hasSelectedText:!0});if(this.#at===g.HIGHLIGHT||this.#at===g.NONE){this.#at===g.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0);this.#Y=this.isShiftKeyDown;if(!this.isShiftKeyDown){const t=this.#at===g.HIGHLIGHT?this.#vt(i):null;t?.toggleDrawing();const e=new AbortController,s=this.combinedSignal(e),pointerup=i=>{if("pointerup"!==i.type||0===i.button){e.abort();t?.toggleDrawing(!0);"pointerup"===i.type&&this.#Et("main_toolbar")}};window.addEventListener("pointerup",pointerup,{signal:s});window.addEventListener("blur",pointerup,{signal:s})}}}else if(this.#ot){this.#Q?.hide();this.#ot=null;this.#_t({hasSelectedText:!1})}}#Et(t=""){this.#at===g.HIGHLIGHT?this.highlightSelection(t):this.#$&&this.#yt()}#ft(){document.addEventListener("selectionchange",this.#xt.bind(this),{signal:this._signal})}#St(){if(this.#X)return;this.#X=new AbortController;const t=this.combinedSignal(this.#X);window.addEventListener("focus",this.focus.bind(this),{signal:t});window.addEventListener("blur",this.blur.bind(this),{signal:t})}#Ct(){this.#X?.abort();this.#X=null}blur(){this.isShiftKeyDown=!1;if(this.#Y){this.#Y=!1;this.#Et("main_toolbar")}if(!this.hasSelection)return;const{activeElement:t}=document;for(const e of this.#rt)if(e.div.contains(t)){this.#it=[e,t];e._focusEventsAllowed=!1;break}}focus(){if(!this.#it)return;const[t,e]=this.#it;this.#it=null;e.addEventListener("focusin",(()=>{t._focusEventsAllowed=!0}),{once:!0,signal:this._signal});e.focus()}#At(){if(this.#et)return;this.#et=new AbortController;const t=this.combinedSignal(this.#et);window.addEventListener("keydown",this.keydown.bind(this),{signal:t});window.addEventListener("keyup",this.keyup.bind(this),{signal:t})}#Tt(){this.#et?.abort();this.#et=null}#Mt(){if(this.#O)return;this.#O=new AbortController;const t=this.combinedSignal(this.#O);document.addEventListener("copy",this.copy.bind(this),{signal:t});document.addEventListener("cut",this.cut.bind(this),{signal:t});document.addEventListener("paste",this.paste.bind(this),{signal:t})}#Pt(){this.#O?.abort();this.#O=null}#bt(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t});document.addEventListener("drop",this.drop.bind(this),{signal:t})}addEditListeners(){this.#At();this.#Mt()}removeEditListeners(){this.#Tt();this.#Pt()}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const i of this.#U)if(i.isHandlingMimeForPasting(e)){t.dataTransfer.dropEffect="copy";t.preventDefault();return}}drop(t){for(const e of t.dataTransfer.items)for(const i of this.#U)if(i.isHandlingMimeForPasting(e.type)){i.paste(e,this.currentLayer);t.preventDefault();return}}copy(t){t.preventDefault();this.#P?.commitOrRemove();if(!this.hasSelection)return;const e=[];for(const t of this.#rt){const i=t.serialize(!0);i&&e.push(i)}0!==e.length&&t.clipboardData.setData("application/pdfjs",JSON.stringify(e))}cut(t){this.copy(t);this.delete()}async paste(t){t.preventDefault();const{clipboardData:e}=t;for(const t of e.items)for(const e of this.#U)if(e.isHandlingMimeForPasting(t.type)){e.paste(t,this.currentLayer);return}let i=e.getData("application/pdfjs");if(!i)return;try{i=JSON.parse(i)}catch(t){warn(`paste: "${t.message}".`);return}if(!Array.isArray(i))return;this.unselectAll();const s=this.currentLayer;try{const t=[];for(const e of i){const i=await s.deserialize(e);if(!i)return;t.push(i)}const cmd=()=>{for(const e of t)this.#Dt(e);this.#kt(t)},undo=()=>{for(const e of t)e.remove()};this.addCommands({cmd,undo,mustExec:!0})}catch(t){warn(`paste: "${t.message}".`)}}keydown(t){this.isShiftKeyDown||"Shift"!==t.key||(this.isShiftKeyDown=!0);this.#at===g.NONE||this.isEditorHandlingKeyboard||AnnotationEditorUIManager._keyboardManager.exec(this,t)}keyup(t){if(this.isShiftKeyDown&&"Shift"===t.key){this.isShiftKeyDown=!1;if(this.#Y){this.#Y=!1;this.#Et("main_toolbar")}}}onEditingAction({name:t}){switch(t){case"undo":case"redo":case"delete":case"selectAll":this[t]();break;case"highlightSelection":this.highlightSelection("context_menu")}}#_t(t){if(Object.entries(t).some((([t,e])=>this.#dt[t]!==e))){this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#dt,t)});this.#at===g.HIGHLIGHT&&!1===t.hasSelectedEditor&&this.#Rt([[m.HIGHLIGHT_FREE,!0]])}}#Rt(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){if(t){this.#St();this.#Mt();this.#_t({isEditing:this.#at!==g.NONE,isEmpty:this.#It(),hasSomethingToUndo:this.#L.hasSomethingToUndo(),hasSomethingToRedo:this.#L.hasSomethingToRedo(),hasSelectedEditor:!1})}else{this.#Ct();this.#Pt();this.#_t({isEditing:!1});this.disableUserSelect(!1)}}registerEditorTypes(t){if(!this.#U){this.#U=t;for(const t of this.#U)this.#Rt(t.defaultPropertiesToUpdate)}}getId(){return this.#J.id}get currentLayer(){return this.#k.get(this.#B)}getLayer(t){return this.#k.get(t)}get currentPageIndex(){return this.#B}addLayer(t){this.#k.set(t.pageIndex,t);this.#Z?t.enable():t.disable()}removeLayer(t){this.#k.delete(t.pageIndex)}async updateMode(t,e=null,i=!1){if(this.#at!==t){if(this.#mt){await this.#mt.promise;if(!this.#mt)return}this.#mt=Promise.withResolvers();this.#at=t;if(t!==g.NONE){this.setEditingState(!0);await this.#Ft();this.unselectAll();for(const e of this.#k.values())e.updateMode(t);if(e){for(const t of this.#D.values())if(t.annotationElementId===e){this.setSelected(t);t.enterInEditMode()}else t.unselect();this.#mt.resolve()}else{i&&this.addNewEditorFromKeyboard();this.#mt.resolve()}}else{this.setEditingState(!1);this.#Lt();this._editorUndoBar?.hide();this.#mt.resolve()}}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==this.#at&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,e){if(this.#U){switch(t){case m.CREATE:this.currentLayer.addNewEditor();return;case m.HIGHLIGHT_DEFAULT_COLOR:this.#st?.updateColor(e);break;case m.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}});(this.#ht||=new Map).set(t,e);this.showAllEditors("highlight",e)}for(const i of this.#rt)i.updateParams(t,e);for(const i of this.#U)i.updateDefaultParams(t,e)}}showAllEditors(t,e,i=!1){for(const i of this.#D.values())i.editorType===t&&i.show(e);(this.#ht?.get(m.HIGHLIGHT_SHOW_ALL)??!0)!==e&&this.#Rt([[m.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(this.#tt!==t){this.#tt=t;for(const e of this.#k.values()){t?e.disableClick():e.enableClick();e.div.classList.toggle("waiting",t)}}}async#Ft(){if(!this.#Z){this.#Z=!0;const t=[];for(const e of this.#k.values())t.push(e.enable());await Promise.all(t);for(const t of this.#D.values())t.enable()}}#Lt(){this.unselectAll();if(this.#Z){this.#Z=!1;for(const t of this.#k.values())t.disable();for(const t of this.#D.values())t.disable()}}getEditors(t){const e=[];for(const i of this.#D.values())i.pageIndex===t&&e.push(i);return e}getEditor(t){return this.#D.get(t)}addEditor(t){this.#D.set(t.id,t)}removeEditor(t){if(t.div.contains(document.activeElement)){this.#q&&clearTimeout(this.#q);this.#q=setTimeout((()=>{this.focusMainContainer();this.#q=null}),0)}this.#D.delete(t.id);this.unselect(t);t.annotationElementId&&this.#H.has(t.annotationElementId)||this.#I?.remove(t.id)}addDeletedAnnotationElement(t){this.#H.add(t.annotationElementId);this.addChangedExistingAnnotation(t);t.deleted=!0}isDeletedAnnotationElement(t){return this.#H.has(t)}removeDeletedAnnotationElement(t){this.#H.delete(t.annotationElementId);this.removeChangedExistingAnnotation(t);t.deleted=!1}#Dt(t){const e=this.#k.get(t.pageIndex);if(e)e.addOrRebuild(t);else{this.addEditor(t);this.addToAnnotationStorage(t)}}setActiveEditor(t){if(this.#P!==t){this.#P=t;t&&this.#Rt(t.propertiesToUpdate)}}get#Ot(){let t=null;for(t of this.#rt);return t}updateUI(t){this.#Ot===t&&this.#Rt(t.propertiesToUpdate)}updateUIForDefaultProperties(t){this.#Rt(t.defaultPropertiesToUpdate)}toggleSelected(t){if(this.#rt.has(t)){this.#rt.delete(t);t.unselect();this.#_t({hasSelectedEditor:this.hasSelection})}else{this.#rt.add(t);t.select();this.#Rt(t.propertiesToUpdate);this.#_t({hasSelectedEditor:!0})}}setSelected(t){this.#N?.commitOrRemove();for(const e of this.#rt)e!==t&&e.unselect();this.#rt.clear();this.#rt.add(t);t.select();this.#Rt(t.propertiesToUpdate);this.#_t({hasSelectedEditor:!0})}isSelected(t){return this.#rt.has(t)}get firstSelectedEditor(){return this.#rt.values().next().value}unselect(t){t.unselect();this.#rt.delete(t);this.#_t({hasSelectedEditor:this.hasSelection})}get hasSelection(){return 0!==this.#rt.size}get isEnterHandled(){return 1===this.#rt.size&&this.firstSelectedEditor.isEnterHandled}undo(){this.#L.undo();this.#_t({hasSomethingToUndo:this.#L.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#It()});this._editorUndoBar?.hide()}redo(){this.#L.redo();this.#_t({hasSomethingToUndo:!0,hasSomethingToRedo:this.#L.hasSomethingToRedo(),isEmpty:this.#It()})}addCommands(t){this.#L.add(t);this.#_t({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#It()})}cleanUndoStack(t){this.#L.cleanType(t)}#It(){if(0===this.#D.size)return!0;if(1===this.#D.size)for(const t of this.#D.values())return t.isEmpty();return!1}delete(){this.commitOrRemove();const t=this.currentLayer?.endDrawingSession(!0);if(!this.hasSelection&&!t)return;const e=t?[t]:[...this.#rt],undo=()=>{for(const t of e)this.#Dt(t)};this.addCommands({cmd:()=>{this._editorUndoBar?.show(undo,1===e.length?e[0].editorType:e.length);for(const t of e)t.remove()},undo,mustExec:!0})}commitOrRemove(){this.#P?.commitOrRemove()}hasSomethingToControl(){return this.#P||this.hasSelection}#kt(t){for(const t of this.#rt)t.unselect();this.#rt.clear();for(const e of t)if(!e.isEmpty()){this.#rt.add(e);e.select()}this.#_t({hasSelectedEditor:this.hasSelection})}selectAll(){for(const t of this.#rt)t.commit();this.#kt(this.#D.values())}unselectAll(){if(this.#P){this.#P.commitOrRemove();if(this.#at!==g.NONE)return}if(!this.#N?.commitOrRemove()&&this.hasSelection){for(const t of this.#rt)t.unselect();this.#rt.clear();this.#_t({hasSelectedEditor:!1})}}translateSelectedEditors(t,e,i=!1){i||this.commitOrRemove();if(!this.hasSelection)return;this.#ct[0]+=t;this.#ct[1]+=e;const[s,n]=this.#ct,a=[...this.#rt];this.#ut&&clearTimeout(this.#ut);this.#ut=setTimeout((()=>{this.#ut=null;this.#ct[0]=this.#ct[1]=0;this.addCommands({cmd:()=>{for(const t of a)this.#D.has(t.id)&&t.translateInPage(s,n)},undo:()=>{for(const t of a)this.#D.has(t.id)&&t.translateInPage(-s,-n)},mustExec:!1})}),1e3);for(const i of a)i.translateInPage(t,e)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0);this.#z=new Map;for(const t of this.#rt)this.#z.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#z)return!1;this.disableUserSelect(!1);const t=this.#z;this.#z=null;let e=!1;for(const[{x:i,y:s,pageIndex:n},a]of t){a.newX=i;a.newY=s;a.newPageIndex=n;e||=i!==a.savedX||s!==a.savedY||n!==a.savedPageIndex}if(!e)return!1;const move=(t,e,i,s)=>{if(this.#D.has(t.id)){const n=this.#k.get(s);if(n)t._setParentAndPosition(n,e,i);else{t.pageIndex=s;t.x=e;t.y=i}}};this.addCommands({cmd:()=>{for(const[e,{newX:i,newY:s,newPageIndex:n}]of t)move(e,i,s,n)},undo:()=>{for(const[e,{savedX:i,savedY:s,savedPageIndex:n}]of t)move(e,i,s,n)},mustExec:!0});return!0}dragSelectedEditors(t,e){if(this.#z)for(const i of this.#z.keys())i.drag(t,e)}rebuild(t){if(null===t.parent){const e=this.getLayer(t.pageIndex);if(e){e.changeParent(t);e.addOrRebuild(t)}else{this.addEditor(t);this.addToAnnotationStorage(t);t.rebuild()}}else t.parent.addOrRebuild(t)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||1===this.#rt.size&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#P===t}getActive(){return this.#P}getMode(){return this.#at}get imageManager(){return shadow(this,"imageManager",new ImageManager)}getSelectionBoxes(t){if(!t)return null;const e=document.getSelection();for(let i=0,s=e.rangeCount;i({x:(e-s)/a,y:1-(t+r-i)/n,width:o/a,height:r/n});break;case"180":r=(t,e,r,o)=>({x:1-(t+r-i)/n,y:1-(e+o-s)/a,width:r/n,height:o/a});break;case"270":r=(t,e,r,o)=>({x:1-(e+o-s)/a,y:(t-i)/n,width:o/a,height:r/n});break;default:r=(t,e,r,o)=>({x:(t-i)/n,y:(e-s)/a,width:r/n,height:o/a})}const o=[];for(let t=0,i=e.rangeCount;tt.stopPropagation()),{signal:i});const onClick=t=>{t.preventDefault();this.#a._uiManager.editAltText(this.#a);this.#Wt&&this.#a._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:this.#Xt}})};t.addEventListener("click",onClick,{capture:!0,signal:i});t.addEventListener("keydown",(e=>{if(e.target===t&&"Enter"===e.key){this.#Gt=!0;onClick(e)}}),{signal:i});await this.#Kt();return t}get#Xt(){return(this.#o?"added":null===this.#o&&this.guessedText&&"review")||"missing"}finish(){if(this.#Bt){this.#Bt.focus({focusVisible:this.#Gt});this.#Gt=!1}}isEmpty(){return this.#Wt?null===this.#o:!this.#o&&!this.#Nt}hasData(){return this.#Wt?null!==this.#o||!!this.#Vt:this.isEmpty()}get guessedText(){return this.#Vt}async setGuessedText(t){if(null===this.#o){this.#Vt=t;this.#jt=await AltText._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t});this.#Kt()}}toggleAltTextBadge(t=!1){if(this.#Wt&&!this.#o){if(!this.#$t){const t=this.#$t=document.createElement("div");t.className="noAltTextBadge";this.#a.div.append(t)}this.#$t.classList.toggle("hidden",!t)}else{this.#$t?.remove();this.#$t=null}}serialize(t){let e=this.#o;t||this.#Vt!==e||(e=this.#jt);return{altText:e,decorative:this.#Nt,guessedText:this.#Vt,textWithDisclaimer:this.#jt}}get data(){return{altText:this.#o,decorative:this.#Nt}}set data({altText:t,decorative:e,guessedText:i,textWithDisclaimer:s,cancel:n=!1}){if(i){this.#Vt=i;this.#jt=s}if(this.#o!==t||this.#Nt!==e){if(!n){this.#o=t;this.#Nt=e}this.#Kt()}}toggle(t=!1){if(this.#Bt){if(!t&&this.#Ut){clearTimeout(this.#Ut);this.#Ut=null}this.#Bt.disabled=!t}}shown(){this.#a._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:this.#Xt}})}destroy(){this.#Bt?.remove();this.#Bt=null;this.#Ht=null;this.#zt=null;this.#$t?.remove();this.#$t=null}async#Kt(){const t=this.#Bt;if(!t)return;if(this.#Wt){t.classList.toggle("done",!!this.#o);t.setAttribute("data-l10n-id",AltText.#qt[this.#Xt]);this.#Ht?.setAttribute("data-l10n-id",AltText.#qt[`${this.#Xt}-label`]);if(!this.#o){this.#zt?.remove();return}}else{if(!this.#o&&!this.#Nt){t.classList.remove("done");this.#zt?.remove();return}t.classList.add("done");t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let e=this.#zt;if(!e){this.#zt=e=document.createElement("span");e.className="tooltip";e.setAttribute("role","tooltip");e.id=`alt-text-tooltip-${this.#a.id}`;const i=100,s=this.#a._uiManager._signal;s.addEventListener("abort",(()=>{clearTimeout(this.#Ut);this.#Ut=null}),{once:!0});t.addEventListener("mouseenter",(()=>{this.#Ut=setTimeout((()=>{this.#Ut=null;this.#zt.classList.add("show");this.#a._reportTelemetry({action:"alt_text_tooltip"})}),i)}),{signal:s});t.addEventListener("mouseleave",(()=>{if(this.#Ut){clearTimeout(this.#Ut);this.#Ut=null}this.#zt?.classList.remove("show")}),{signal:s})}if(this.#Nt)e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip");else{e.removeAttribute("data-l10n-id");e.textContent=this.#o}e.parentNode||t.append(e);const i=this.#a.getImageForAltText();i?.setAttribute("aria-describedby",e.id)}}class TouchManager{#pt;#Yt=!1;#Qt=null;#Jt;#Zt;#te;#ee;#ie;#se=null;#ne;#ae=null;constructor({container:t,isPinchingDisabled:e=null,isPinchingStopped:i=null,onPinchStart:s=null,onPinching:n=null,onPinchEnd:a=null,signal:r}){this.#pt=t;this.#Qt=i;this.#Jt=e;this.#Zt=s;this.#te=n;this.#ee=a;this.#ne=new AbortController;this.#ie=AbortSignal.any([r,this.#ne.signal]);t.addEventListener("touchstart",this.#re.bind(this),{passive:!1,signal:this.#ie})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return shadow(this,"MIN_TOUCH_DISTANCE_TO_PINCH",35/(window.devicePixelRatio||1))}#re(t){if(this.#Jt?.()||t.touches.length<2)return;if(!this.#ae){this.#ae=new AbortController;const t=AbortSignal.any([this.#ie,this.#ae.signal]),e=this.#pt,i={signal:t,passive:!1};e.addEventListener("touchmove",this.#oe.bind(this),i);e.addEventListener("touchend",this.#le.bind(this),i);e.addEventListener("touchcancel",this.#le.bind(this),i);this.#Zt?.()}stopEvent(t);if(2!==t.touches.length||this.#Qt?.()){this.#se=null;return}let[e,i]=t.touches;e.identifier>i.identifier&&([e,i]=[i,e]);this.#se={touch0X:e.screenX,touch0Y:e.screenY,touch1X:i.screenX,touch1Y:i.screenY}}#oe(t){if(!this.#se||2!==t.touches.length)return;let[e,i]=t.touches;e.identifier>i.identifier&&([e,i]=[i,e]);const{screenX:s,screenY:n}=e,{screenX:a,screenY:r}=i,o=this.#se,{touch0X:l,touch0Y:h,touch1X:d,touch1Y:c}=o,u=d-l,p=c-h,g=a-s,m=r-n,f=Math.hypot(g,m)||1,b=Math.hypot(u,p)||1;if(!this.#Yt&&Math.abs(b-f)<=TouchManager.MIN_TOUCH_DISTANCE_TO_PINCH)return;o.touch0X=s;o.touch0Y=n;o.touch1X=a;o.touch1Y=r;t.preventDefault();if(!this.#Yt){this.#Yt=!0;return}const A=[(s+a)/2,(n+r)/2];this.#te?.(A,b,f)}#le(t){this.#ae.abort();this.#ae=null;this.#ee?.();if(this.#se){t.preventDefault();this.#se=null;this.#Yt=!1}}destroy(){this.#ne?.abort();this.#ne=null}}class AnnotationEditor{#he=null;#de=null;#o=null;#ce=!1;#ue=null;#pe="";#ge=!1;#me=null;#fe=null;#be=null;#Ae=null;#we="";#ve=!1;#ye=null;#xe=!1;#_e=!1;#Ee=!1;#Se=null;#Ce=0;#Te=0;#Me=null;#Pe=null;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nResizer=null;#De=!1;#ke=AnnotationEditor._zIndex++;static _borderLineWidth=-1;static _colorManager=new ColorManager;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){const t=AnnotationEditor.prototype._resizeWithKeyboard,e=AnnotationEditorUIManager.TRANSLATE_SMALL,i=AnnotationEditorUIManager.TRANSLATE_BIG;return shadow(this,"_resizerKeyboardManager",new KeyboardManager([[["ArrowLeft","mac+ArrowLeft"],t,{args:[-e,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-i,0]}],[["ArrowRight","mac+ArrowRight"],t,{args:[e,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[i,0]}],[["ArrowUp","mac+ArrowUp"],t,{args:[0,-e]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-i]}],[["ArrowDown","mac+ArrowDown"],t,{args:[0,e]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,i]}],[["Escape","mac+Escape"],AnnotationEditor.prototype._stopResizingWithKeyboard]]))}constructor(t){this.parent=t.parent;this.id=t.id;this.width=this.height=null;this.pageIndex=t.parent.pageIndex;this.name=t.name;this.div=null;this._uiManager=t.uiManager;this.annotationElementId=null;this._willKeepAspectRatio=!1;this._initialOptions.isCentered=t.isCentered;this._structTreeParentId=null;const{rotation:e,rawDims:{pageWidth:i,pageHeight:s,pageX:n,pageY:a}}=this.parent.viewport;this.rotation=e;this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360;this.pageDimensions=[i,s];this.pageTranslation=[n,a];const[r,o]=this.parentDimensions;this.x=t.x/r;this.y=t.y/o;this.isAttachedToDOM=!1;this.deleted=!1}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get isDrawer(){return!1}static get _defaultLineColor(){return shadow(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new FakeEditor({id:t.parent.getNextId(),parent:t.parent,uiManager:t._uiManager});e.annotationElementId=t.annotationElementId;e.deleted=!0;e._uiManager.addToAnnotationStorage(e)}static initialize(t,e){AnnotationEditor._l10n??=t;AnnotationEditor._l10nResizer||=Object.freeze({topLeft:"pdfjs-editor-resizer-top-left",topMiddle:"pdfjs-editor-resizer-top-middle",topRight:"pdfjs-editor-resizer-top-right",middleRight:"pdfjs-editor-resizer-middle-right",bottomRight:"pdfjs-editor-resizer-bottom-right",bottomMiddle:"pdfjs-editor-resizer-bottom-middle",bottomLeft:"pdfjs-editor-resizer-bottom-left",middleLeft:"pdfjs-editor-resizer-middle-left"});if(-1!==AnnotationEditor._borderLineWidth)return;const i=getComputedStyle(document.documentElement);AnnotationEditor._borderLineWidth=parseFloat(i.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){unreachable("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#De}set _isDraggable(t){this.#De=t;this.div?.classList.toggle("draggable",t)}get isEnterHandled(){return!0}center(){const[t,e]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*e/(2*t);this.y+=this.width*t/(2*e);break;case 180:this.x+=this.width/2;this.y+=this.height/2;break;case 270:this.x+=this.height*e/(2*t);this.y-=this.width*t/(2*e);break;default:this.x-=this.width/2;this.y-=this.height/2}this.fixAndSetPosition()}addCommands(t){this._uiManager.addCommands(t)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#ke}setParent(t){if(null!==t){this.pageIndex=t.pageIndex;this.pageDimensions=t.pageDimensions}else this.#Re();this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#ve?this.#ve=!1:this.parent.setSelected(this))}focusout(t){if(!this._focusEventsAllowed)return;if(!this.isAttachedToDOM)return;const e=t.relatedTarget;if(!e?.closest(`#${this.id}`)){t.preventDefault();this.parent?.isMultipleSelection||this.commitOrRemove()}}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(t,e,i,s){const[n,a]=this.parentDimensions;[i,s]=this.screenToPageTranslation(i,s);this.x=(t+i)/n;this.y=(e+s)/a;this.fixAndSetPosition()}#Ie([t,e],i,s){[i,s]=this.screenToPageTranslation(i,s);this.x+=i/t;this.y+=s/e;this._onTranslating(this.x,this.y);this.fixAndSetPosition()}translate(t,e){this.#Ie(this.parentDimensions,t,e)}translateInPage(t,e){this.#ye||=[this.x,this.y,this.width,this.height];this.#Ie(this.pageDimensions,t,e);this.div.scrollIntoView({block:"nearest"})}drag(t,e){this.#ye||=[this.x,this.y,this.width,this.height];const{div:i,parentDimensions:[s,n]}=this;this.x+=t/s;this.y+=e/n;if(this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:t,y:e}=this.div.getBoundingClientRect();if(this.parent.findNewParent(this,t,e)){this.x-=Math.floor(this.x);this.y-=Math.floor(this.y)}}let{x:a,y:r}=this;const[o,l]=this.getBaseTranslation();a+=o;r+=l;const{style:h}=i;h.left=`${(100*a).toFixed(2)}%`;h.top=`${(100*r).toFixed(2)}%`;this._onTranslating(a,r);i.scrollIntoView({block:"nearest"})}_onTranslating(t,e){}_onTranslated(t,e){}get _hasBeenMoved(){return!!this.#ye&&(this.#ye[0]!==this.x||this.#ye[1]!==this.y)}get _hasBeenResized(){return!!this.#ye&&(this.#ye[2]!==this.width||this.#ye[3]!==this.height)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:i}=AnnotationEditor,s=i/t,n=i/e;switch(this.rotation){case 90:return[-s,n];case 180:return[s,n];case 270:return[s,-n];default:return[-s,-n]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const{div:{style:e},pageDimensions:[i,s]}=this;let{x:n,y:a,width:r,height:o}=this;r*=i;o*=s;n*=i;a*=s;if(this._mustFixPosition)switch(t){case 0:n=Math.max(0,Math.min(i-r,n));a=Math.max(0,Math.min(s-o,a));break;case 90:n=Math.max(0,Math.min(i-o,n));a=Math.min(s,Math.max(r,a));break;case 180:n=Math.min(i,Math.max(r,n));a=Math.min(s,Math.max(o,a));break;case 270:n=Math.min(i,Math.max(o,n));a=Math.max(0,Math.min(s-r,a))}this.x=n/=i;this.y=a/=s;const[l,h]=this.getBaseTranslation();n+=l;a+=h;e.left=`${(100*n).toFixed(2)}%`;e.top=`${(100*a).toFixed(2)}%`;this.moveInDOM()}static#Fe(t,e,i){switch(i){case 90:return[e,-t];case 180:return[-t,-e];case 270:return[-e,t];default:return[t,e]}}screenToPageTranslation(t,e){return AnnotationEditor.#Fe(t,e,this.parentRotation)}pageTranslationToScreen(t,e){return AnnotationEditor.#Fe(t,e,360-this.parentRotation)}#Le(t){switch(t){case 90:{const[t,e]=this.pageDimensions;return[0,-t/e,e/t,0]}case 180:return[-1,0,0,-1];case 270:{const[t,e]=this.pageDimensions;return[0,t/e,-e/t,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:t,pageDimensions:[e,i]}=this;return[e*t,i*t]}setDims(t,e){const[i,s]=this.parentDimensions,{style:n}=this.div;n.width=`${(100*t/i).toFixed(2)}%`;this.#ge||(n.height=`${(100*e/s).toFixed(2)}%`)}fixDims(){const{style:t}=this.div,{height:e,width:i}=t,s=i.endsWith("%"),n=!this.#ge&&e.endsWith("%");if(s&&n)return;const[a,r]=this.parentDimensions;s||(t.width=`${(100*parseFloat(i)/a).toFixed(2)}%`);this.#ge||n||(t.height=`${(100*parseFloat(e)/r).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}#Oe(){if(this.#me)return;this.#me=document.createElement("div");this.#me.classList.add("resizers");const t=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],e=this._uiManager._signal;for(const i of t){const t=document.createElement("div");this.#me.append(t);t.classList.add("resizer",i);t.setAttribute("data-resizer-name",i);t.addEventListener("pointerdown",this.#Ne.bind(this,i),{signal:e});t.addEventListener("contextmenu",noContextMenu,{signal:e});t.tabIndex=-1}this.div.prepend(this.#me)}#Ne(t,e){e.preventDefault();const{isMac:i}=util_FeatureTest.platform;if(0!==e.button||e.ctrlKey&&i)return;this.#o?.toggle(!1);const s=this._isDraggable;this._isDraggable=!1;this.#fe=[e.screenX,e.screenY];const n=new AbortController,a=this._uiManager.combinedSignal(n);this.parent.togglePointerEvents(!1);window.addEventListener("pointermove",this.#Be.bind(this,t),{passive:!0,capture:!0,signal:a});window.addEventListener("touchmove",stopEvent,{passive:!1,signal:a});window.addEventListener("contextmenu",noContextMenu,{signal:a});this.#be={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const r=this.parent.div.style.cursor,o=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const pointerUpCallback=()=>{n.abort();this.parent.togglePointerEvents(!0);this.#o?.toggle(!0);this._isDraggable=s;this.parent.div.style.cursor=r;this.div.style.cursor=o;this.#He()};window.addEventListener("pointerup",pointerUpCallback,{signal:a});window.addEventListener("blur",pointerUpCallback,{signal:a})}#ze(t,e,i,s){this.width=i;this.height=s;this.x=t;this.y=e;const[n,a]=this.parentDimensions;this.setDims(n*i,a*s);this.fixAndSetPosition();this._onResized()}_onResized(){}#He(){if(!this.#be)return;const{savedX:t,savedY:e,savedWidth:i,savedHeight:s}=this.#be;this.#be=null;const n=this.x,a=this.y,r=this.width,o=this.height;n===t&&a===e&&r===i&&o===s||this.addCommands({cmd:this.#ze.bind(this,n,a,r,o),undo:this.#ze.bind(this,t,e,i,s),mustExec:!0})}static _round(t){return Math.round(1e4*t)/1e4}#Be(t,e){const[i,s]=this.parentDimensions,n=this.x,a=this.y,r=this.width,o=this.height,l=AnnotationEditor.MIN_SIZE/i,h=AnnotationEditor.MIN_SIZE/s,d=this.#Le(this.rotation),transf=(t,e)=>[d[0]*t+d[2]*e,d[1]*t+d[3]*e],c=this.#Le(360-this.rotation);let u,p,g=!1,m=!1;switch(t){case"topLeft":g=!0;u=(t,e)=>[0,0];p=(t,e)=>[t,e];break;case"topMiddle":u=(t,e)=>[t/2,0];p=(t,e)=>[t/2,e];break;case"topRight":g=!0;u=(t,e)=>[t,0];p=(t,e)=>[0,e];break;case"middleRight":m=!0;u=(t,e)=>[t,e/2];p=(t,e)=>[0,e/2];break;case"bottomRight":g=!0;u=(t,e)=>[t,e];p=(t,e)=>[0,0];break;case"bottomMiddle":u=(t,e)=>[t/2,e];p=(t,e)=>[t/2,0];break;case"bottomLeft":g=!0;u=(t,e)=>[0,e];p=(t,e)=>[t,0];break;case"middleLeft":m=!0;u=(t,e)=>[0,e/2];p=(t,e)=>[t,e/2]}const f=u(r,o),b=p(r,o);let A=transf(...b);const w=AnnotationEditor._round(n+A[0]),v=AnnotationEditor._round(a+A[1]);let y,x,_=1,E=1;if(e.fromKeyboard)({deltaX:y,deltaY:x}=e);else{const{screenX:t,screenY:i}=e,[s,n]=this.#fe;[y,x]=this.screenToPageTranslation(t-s,i-n);this.#fe[0]=t;this.#fe[1]=i}[y,x]=(S=y/i,C=x/s,[c[0]*S+c[2]*C,c[1]*S+c[3]*C]);var S,C;if(g){const t=Math.hypot(r,o);_=E=Math.max(Math.min(Math.hypot(b[0]-f[0]-y,b[1]-f[1]-x)/t,1/r,1/o),l/r,h/o)}else m?_=Math.max(l,Math.min(1,Math.abs(b[0]-f[0]-y)))/r:E=Math.max(h,Math.min(1,Math.abs(b[1]-f[1]-x)))/o;const T=AnnotationEditor._round(r*_),M=AnnotationEditor._round(o*E);A=transf(...p(T,M));const P=w-A[0],D=v-A[1];this.#ye||=[this.x,this.y,this.width,this.height];this.width=T;this.height=M;this.x=P;this.y=D;this.setDims(i*T,s*M);this.fixAndSetPosition();this._onResizing()}_onResizing(){}altTextFinish(){this.#o?.finish()}async addEditToolbar(){if(this._editToolbar||this.#_e)return this._editToolbar;this._editToolbar=new EditorToolbar(this);this.div.append(this._editToolbar.render());this.#o&&await this._editToolbar.addAltText(this.#o);return this._editToolbar}removeEditToolbar(){if(this._editToolbar){this._editToolbar.remove();this._editToolbar=null;this.#o?.destroy()}}addContainer(t){const e=this._editToolbar?.div;e?e.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){if(!this.#o){AltText.initialize(AnnotationEditor._l10n);this.#o=new AltText(this);if(this.#he){this.#o.data=this.#he;this.#he=null}await this.addEditToolbar()}}get altTextData(){return this.#o?.data}set altTextData(t){this.#o&&(this.#o.data=t)}get guessedAltText(){return this.#o?.guessedText}async setGuessedAltText(t){await(this.#o?.setGuessedText(t))}serializeAltText(t){return this.#o?.serialize(t)}hasAltText(){return!!this.#o&&!this.#o.isEmpty()}hasAltTextData(){return this.#o?.hasData()??!1}render(){this.div=document.createElement("div");this.div.setAttribute("data-editor-rotation",(360-this.rotation)%360);this.div.className=this.name;this.div.setAttribute("id",this.id);this.div.tabIndex=this.#ce?-1:0;this._isVisible||this.div.classList.add("hidden");this.setInForeground();this.#Ue();const[t,e]=this.parentDimensions;if(this.parentRotation%180!=0){this.div.style.maxWidth=`${(100*e/t).toFixed(2)}%`;this.div.style.maxHeight=`${(100*t/e).toFixed(2)}%`}const[i,s]=this.getInitialTranslation();this.translate(i,s);bindEvents(this,this.div,["pointerdown"]);this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#Pe||=new TouchManager({container:this.div,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#Ge.bind(this),onPinching:this.#$e.bind(this),onPinchEnd:this.#Ve.bind(this),signal:this._uiManager._signal}));this._uiManager._editorUndoBar?.hide();return this.div}#Ge(){this.#be={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};this.#o?.toggle(!1);this.parent.togglePointerEvents(!1)}#$e(t,e,i){let s=i/e*.7+1-.7;if(1===s)return;const n=this.#Le(this.rotation),transf=(t,e)=>[n[0]*t+n[2]*e,n[1]*t+n[3]*e],[a,r]=this.parentDimensions,o=this.x,l=this.y,h=this.width,d=this.height,c=AnnotationEditor.MIN_SIZE/a,u=AnnotationEditor.MIN_SIZE/r;s=Math.max(Math.min(s,1/h,1/d),c/h,u/d);const p=AnnotationEditor._round(h*s),g=AnnotationEditor._round(d*s);if(p===h&&g===d)return;this.#ye||=[o,l,h,d];const m=transf(h/2,d/2),f=AnnotationEditor._round(o+m[0]),b=AnnotationEditor._round(l+m[1]),A=transf(p/2,g/2);this.x=f-A[0];this.y=b-A[1];this.width=p;this.height=g;this.setDims(a*p,r*g);this.fixAndSetPosition();this._onResizing()}#Ve(){this.#o?.toggle(!0);this.parent.togglePointerEvents(!0);this.#He()}pointerdown(t){const{isMac:e}=util_FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)t.preventDefault();else{this.#ve=!0;this._isDraggable?this.#je(t):this.#We(t)}}get isSelected(){return this._uiManager.isSelected(this)}#We(t){const{isMac:e}=util_FeatureTest.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)}#je(t){const{isSelected:e}=this;this._uiManager.setUpDragSession();let i=!1;const s=new AbortController,n=this._uiManager.combinedSignal(s),a={capture:!0,passive:!1,signal:n},cancelDrag=t=>{s.abort();this.#ue=null;this.#ve=!1;this._uiManager.endDragSession()||this.#We(t);i&&this._onStopDragging()};if(e){this.#Ce=t.clientX;this.#Te=t.clientY;this.#ue=t.pointerId;this.#pe=t.pointerType;window.addEventListener("pointermove",(t=>{if(!i){i=!0;this._onStartDragging()}const{clientX:e,clientY:s,pointerId:n}=t;if(n!==this.#ue){stopEvent(t);return}const[a,r]=this.screenToPageTranslation(e-this.#Ce,s-this.#Te);this.#Ce=e;this.#Te=s;this._uiManager.dragSelectedEditors(a,r)}),a);window.addEventListener("touchmove",stopEvent,a);window.addEventListener("pointerdown",(t=>{t.pointerType===this.#pe&&(this.#Pe||t.isPrimary)&&cancelDrag(t);stopEvent(t)}),a)}const pointerUpCallback=t=>{this.#ue&&this.#ue!==t.pointerId?stopEvent(t):cancelDrag(t)};window.addEventListener("pointerup",pointerUpCallback,{signal:n});window.addEventListener("blur",pointerUpCallback,{signal:n})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#Se&&clearTimeout(this.#Se);this.#Se=setTimeout((()=>{this.#Se=null;this.parent?.moveEditorInDOM(this)}),0)}_setParentAndPosition(t,e,i){t.changeParent(this);this.x=e;this.y=i;this.fixAndSetPosition();this._onTranslated()}getRect(t,e,i=this.rotation){const s=this.parentScale,[n,a]=this.pageDimensions,[r,o]=this.pageTranslation,l=t/s,h=e/s,d=this.x*n,c=this.y*a,u=this.width*n,p=this.height*a;switch(i){case 0:return[d+l+r,a-c-h-p+o,d+l+u+r,a-c-h+o];case 90:return[d+h+r,a-c+l+o,d+h+p+r,a-c+l+u+o];case 180:return[d-l-u+r,a-c+h+o,d-l+r,a-c+h+p+o];case 270:return[d-h-p+r,a-c-l-u+o,d-h+r,a-c-l+o];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,e){const[i,s,n,a]=t,r=n-i,o=a-s;switch(this.rotation){case 0:return[i,e-a,r,o];case 90:return[i,e-s,o,r];case 180:return[n,e-s,r,o];case 270:return[n,e-a,o,r];default:throw new Error("Invalid rotation")}}onceAdded(t){}isEmpty(){return!1}enableEditMode(){this.#_e=!0}disableEditMode(){this.#_e=!1}isInEditMode(){return this.#_e}shouldGetKeyboardEvents(){return this.#Ee}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){const{top:t,left:e,bottom:i,right:s}=this.getClientDimensions(),{innerHeight:n,innerWidth:a}=window;return e0&&t0}#Ue(){if(this.#Ae||!this.div)return;this.#Ae=new AbortController;const t=this._uiManager.combinedSignal(this.#Ae);this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t});this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})}rebuild(){this.#Ue()}rotate(t){}resize(){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||""}}serialize(t=!1,e=null){unreachable("An editor must be serializable")}static async deserialize(t,e,i){const s=new this.prototype.constructor({parent:e,id:e.getNextId(),uiManager:i});s.rotation=t.rotation;s.#he=t.accessibilityData;const[n,a]=s.pageDimensions,[r,o,l,h]=s.getRectInCurrentCoords(t.rect,a);s.x=r/n;s.y=o/a;s.width=l/n;s.height=h/a;return s}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||null!==this.serialize())}remove(){this.#Ae?.abort();this.#Ae=null;this.isEmpty()||this.commit();this.parent?this.parent.remove(this):this._uiManager.removeEditor(this);if(this.#Se){clearTimeout(this.#Se);this.#Se=null}this.#Re();this.removeEditToolbar();if(this.#Me){for(const t of this.#Me.values())clearTimeout(t);this.#Me=null}this.parent=null;this.#Pe?.destroy();this.#Pe=null}get isResizable(){return!1}makeResizable(){if(this.isResizable){this.#Oe();this.#me.classList.remove("hidden");bindEvents(this,this.div,["keydown"])}}get toolbarPosition(){return null}keydown(t){if(!this.isResizable||t.target!==this.div||"Enter"!==t.key)return;this._uiManager.setSelected(this);this.#be={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const e=this.#me.children;if(!this.#de){this.#de=Array.from(e);const t=this.#qe.bind(this),i=this.#Xe.bind(this),s=this._uiManager._signal;for(const e of this.#de){const n=e.getAttribute("data-resizer-name");e.setAttribute("role","spinbutton");e.addEventListener("keydown",t,{signal:s});e.addEventListener("blur",i,{signal:s});e.addEventListener("focus",this.#Ke.bind(this,n),{signal:s});e.setAttribute("data-l10n-id",AnnotationEditor._l10nResizer[n])}}const i=this.#de[0];let s=0;for(const t of e){if(t===i)break;s++}const n=(360-this.rotation+this.parentRotation)%360/90*(this.#de.length/4);if(n!==s){if(ns)for(let t=0;t{this.div?.classList.contains("selectedEditor")&&this._editToolbar?.show()}))}unselect(){this.#me?.classList.add("hidden");this.div?.classList.remove("selectedEditor");this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0});this._editToolbar?.hide();this.#o?.toggleAltTextBadge(!0)}updateParams(t,e){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return this.#xe}set isEditing(t){this.#xe=t;if(this.parent)if(t){this.parent.setSelected(this);this.parent.setActiveEditor(this)}else this.parent.setActiveEditor(null)}setAspectRatio(t,e){this.#ge=!0;const i=t/e,{style:s}=this.div;s.aspectRatio=i;s.height="auto"}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(t,e=!1){if(e){this.#Me||=new Map;const{action:e}=t;let i=this.#Me.get(e);i&&clearTimeout(i);i=setTimeout((()=>{this._reportTelemetry(t);this.#Me.delete(e);0===this.#Me.size&&(this.#Me=null)}),AnnotationEditor._telemetryTimeout);this.#Me.set(e,i)}else{t.type||=this.editorType;this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:t}})}}show(t=this._isVisible){this.div.classList.toggle("hidden",!t);this._isVisible=t}enable(){this.div&&(this.div.tabIndex=0);this.#ce=!1}disable(){this.div&&(this.div.tabIndex=-1);this.#ce=!0}renderAnnotationElement(t){let e=t.container.querySelector(".annotationContent");if(e){if("CANVAS"===e.nodeName){const t=e;e=document.createElement("div");e.classList.add("annotationContent",this.editorType);t.before(e)}}else{e=document.createElement("div");e.classList.add("annotationContent",this.editorType);t.container.prepend(e)}return e}resetAnnotationElement(t){const{firstChild:e}=t.container;"DIV"===e?.nodeName&&e.classList.contains("annotationContent")&&e.remove()}}class FakeEditor extends AnnotationEditor{constructor(t){super(t);this.annotationElementId=t.annotationElementId;this.deleted=!0}serialize(){return this.serializeDeleted()}}const st=3285377520,nt=4294901760,at=65535;class MurmurHash3_64{constructor(t){this.h1=t?4294967295&t:st;this.h2=t?4294967295&t:st}update(t){let e,i;if("string"==typeof t){e=new Uint8Array(2*t.length);i=0;for(let s=0,n=t.length;s>>8;e[i++]=255&n}}}else{if(!ArrayBuffer.isView(t))throw new Error("Invalid data format, must be a string or TypedArray.");e=t.slice();i=e.byteLength}const s=i>>2,n=i-4*s,a=new Uint32Array(e.buffer,0,s);let r=0,o=0,l=this.h1,h=this.h2;const d=3432918353,c=461845907,u=11601,p=13715;for(let t=0;t>>17;r=r*c&nt|r*p&at;l^=r;l=l<<13|l>>>19;l=5*l+3864292196}else{o=a[t];o=o*d&nt|o*u&at;o=o<<15|o>>>17;o=o*c&nt|o*p&at;h^=o;h=h<<13|h>>>19;h=5*h+3864292196}r=0;switch(n){case 3:r^=e[4*s+2]<<16;case 2:r^=e[4*s+1]<<8;case 1:r^=e[4*s];r=r*d&nt|r*u&at;r=r<<15|r>>>17;r=r*c&nt|r*p&at;1&s?l^=r:h^=r}this.h1=l;this.h2=h}hexdigest(){let t=this.h1,e=this.h2;t^=e>>>1;t=3981806797*t&nt|36045*t&at;e=4283543511*e&nt|(2950163797*(e<<16|t>>>16)&nt)>>>16;t^=e>>>1;t=444984403*t&nt|60499*t&at;e=3301882366*e&nt|(3120437893*(e<<16|t>>>16)&nt)>>>16;t^=e>>>1;return(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const rt=Object.freeze({map:null,hash:"",transfer:void 0});class AnnotationStorage{#Qe=!1;#Je=null;#Ze=new Map;constructor(){this.onSetModified=null;this.onResetModified=null;this.onAnnotationEditor=null}getValue(t,e){const i=this.#Ze.get(t);return void 0===i?e:Object.assign(e,i)}getRawValue(t){return this.#Ze.get(t)}remove(t){this.#Ze.delete(t);0===this.#Ze.size&&this.resetModified();if("function"==typeof this.onAnnotationEditor){for(const t of this.#Ze.values())if(t instanceof AnnotationEditor)return;this.onAnnotationEditor(null)}}setValue(t,e){const i=this.#Ze.get(t);let s=!1;if(void 0!==i){for(const[t,n]of Object.entries(e))if(i[t]!==n){s=!0;i[t]=n}}else{s=!0;this.#Ze.set(t,e)}s&&this.#ti();e instanceof AnnotationEditor&&"function"==typeof this.onAnnotationEditor&&this.onAnnotationEditor(e.constructor._type)}has(t){return this.#Ze.has(t)}getAll(){return this.#Ze.size>0?objectFromMap(this.#Ze):null}setAll(t){for(const[e,i]of Object.entries(t))this.setValue(e,i)}get size(){return this.#Ze.size}#ti(){if(!this.#Qe){this.#Qe=!0;"function"==typeof this.onSetModified&&this.onSetModified()}}resetModified(){if(this.#Qe){this.#Qe=!1;"function"==typeof this.onResetModified&&this.onResetModified()}}get print(){return new PrintAnnotationStorage(this)}get serializable(){if(0===this.#Ze.size)return rt;const t=new Map,e=new MurmurHash3_64,i=[],s=Object.create(null);let n=!1;for(const[i,a]of this.#Ze){const r=a instanceof AnnotationEditor?a.serialize(!1,s):a;if(r){t.set(i,r);e.update(`${i}:${JSON.stringify(r)}`);n||=!!r.bitmap}}if(n)for(const e of t.values())e.bitmap&&i.push(e.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:i}:rt}get editorStats(){let t=null;const e=new Map;for(const i of this.#Ze.values()){if(!(i instanceof AnnotationEditor))continue;const s=i.telemetryFinalData;if(!s)continue;const{type:n}=s;e.has(n)||e.set(n,Object.getPrototypeOf(i).constructor);t||=Object.create(null);const a=t[n]||=new Map;for(const[t,e]of Object.entries(s)){if("type"===t)continue;let i=a.get(t);if(!i){i=new Map;a.set(t,i)}const s=i.get(e)??0;i.set(e,s+1)}}for(const[i,s]of e)t[i]=s.computeTelemetryFinalData(t[i]);return t}resetModifiedIds(){this.#Je=null}get modifiedIds(){if(this.#Je)return this.#Je;const t=[];for(const e of this.#Ze.values())e instanceof AnnotationEditor&&e.annotationElementId&&e.serialize()&&t.push(e.annotationElementId);return this.#Je={ids:new Set(t),hash:t.join(",")}}}class PrintAnnotationStorage extends AnnotationStorage{#ei;constructor(t){super();const{map:e,hash:i,transfer:s}=t.serializable,n=structuredClone(e,s?{transfer:s}:null);this.#ei={map:n,hash:i,transfer:s}}get print(){unreachable("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#ei}get modifiedIds(){return shadow(this,"modifiedIds",{ids:new Set,hash:""})}}class FontLoader{#ii=new Set;constructor({ownerDocument:t=globalThis.document,styleElement:e=null}){this._document=t;this.nativeFontFaces=new Set;this.styleElement=null;this.loadingRequests=[];this.loadTestFontId=0}addNativeFontFace(t){this.nativeFontFaces.add(t);this._document.fonts.add(t)}removeNativeFontFace(t){this.nativeFontFaces.delete(t);this._document.fonts.delete(t)}insertRule(t){if(!this.styleElement){this.styleElement=this._document.createElement("style");this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement)}const e=this.styleElement.sheet;e.insertRule(t,e.cssRules.length)}clear(){for(const t of this.nativeFontFaces)this._document.fonts.delete(t);this.nativeFontFaces.clear();this.#ii.clear();if(this.styleElement){this.styleElement.remove();this.styleElement=null}}async loadSystemFont({systemFontInfo:t,_inspectFont:e}){if(t&&!this.#ii.has(t.loadedName)){assert(!this.disableFontFace,"loadSystemFont shouldn't be called when `disableFontFace` is set.");if(this.isFontLoadingAPISupported){const{loadedName:i,src:s,style:n}=t,a=new FontFace(i,s,n);this.addNativeFontFace(a);try{await a.load();this.#ii.add(i);e?.(t)}catch{warn(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`);this.removeNativeFontFace(a)}}else unreachable("Not implemented: loadSystemFont without the Font Loading API.")}}async bind(t){if(t.attached||t.missingFile&&!t.systemFontInfo)return;t.attached=!0;if(t.systemFontInfo){await this.loadSystemFont(t);return}if(this.isFontLoadingAPISupported){const e=t.createNativeFontFace();if(e){this.addNativeFontFace(e);try{await e.loaded}catch(i){warn(`Failed to load font '${e.family}': '${i}'.`);t.disableFontFace=!0;throw i}}return}const e=t.createFontFaceRule();if(e){this.insertRule(e);if(this.isSyncFontLoadingSupported)return;await new Promise((e=>{const i=this._queueLoadingCallback(e);this._prepareFontLoadEvent(t,i)}))}}get isFontLoadingAPISupported(){return shadow(this,"isFontLoadingAPISupported",!!this._document?.fonts)}get isSyncFontLoadingSupported(){let t=!1;(e||"undefined"!=typeof navigator&&"string"==typeof navigator?.userAgent&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(t=!0);return shadow(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){const{loadingRequests:e}=this,i={done:!1,complete:function completeRequest(){assert(!i.done,"completeRequest() cannot be called twice.");i.done=!0;for(;e.length>0&&e[0].done;){const t=e.shift();setTimeout(t.callback,0)}},callback:t};e.push(i);return i}get _loadTestFont(){return shadow(this,"_loadTestFont",atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAA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eAt(e+3)}function spliceString(t,e,i,s){return t.substring(0,e)+s+t.substring(e+i)}let i,s;const n=this._document.createElement("canvas");n.width=1;n.height=1;const a=n.getContext("2d");let r=0;const o=`lt${Date.now()}${this.loadTestFontId++}`;let l=this._loadTestFont;l=spliceString(l,976,o.length,o);const h=1482184792;let d=int32(l,16);for(i=0,s=o.length-3;i>24&255,t>>16&255,t>>8&255,255&t)}(d));const c=`@font-face {font-family:"${o}";src:${`url(data:font/opentype;base64,${btoa(l)});`}}`;this.insertRule(c);const u=this._document.createElement("div");u.style.visibility="hidden";u.style.width=u.style.height="10px";u.style.position="absolute";u.style.top=u.style.left="0px";for(const e of[t.loadedName,o]){const t=this._document.createElement("span");t.textContent="Hi";t.style.fontFamily=e;u.append(t)}this._document.body.append(u);!function isFontReady(t,e){if(++r>30){warn("Load test font never loaded.");e();return}a.font="30px "+t;a.fillText(".",0,20);a.getImageData(0,0,1,1).data[3]>0?e():setTimeout(isFontReady.bind(null,t,e))}(o,(()=>{u.remove();e.complete()}))}}class FontFaceObject{constructor(t,{disableFontFace:e=!1,fontExtraProperties:i=!1,inspectFont:s=null}){this.compiledGlyphs=Object.create(null);for(const e in t)this[e]=t[e];this.disableFontFace=!0===e;this.fontExtraProperties=!0===i;this._inspectFont=s}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let t;if(this.cssFontInfo){const e={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(e.style=`oblique ${this.cssFontInfo.italicAngle}deg`);t=new FontFace(this.cssFontInfo.fontFamily,this.data,e)}else t=new FontFace(this.loadedName,this.data,{});this._inspectFont?.(this);return t}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;const t=`url(data:${this.mimetype};base64,${function toBase64Util(t){return Uint8Array.prototype.toBase64?t.toBase64():btoa(bytesToString(t))}(this.data)});`;let e;if(this.cssFontInfo){let i=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(i+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`);e=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${i}src:${t}}`}else e=`@font-face {font-family:"${this.loadedName}";src:${t}}`;this._inspectFont?.(this,t);return e}getPathGenerator(t,e){if(void 0!==this.compiledGlyphs[e])return this.compiledGlyphs[e];const i=this.loadedName+"_path_"+e;let s;try{s=t.get(i)}catch(t){warn(`getPathGenerator - ignoring character: "${t}".`)}const n=new Path2D(s||"");this.fontExtraProperties||t.delete(i);return this.compiledGlyphs[e]=n}}const ot=1,lt=2,ht=1,dt=2,ct=3,ut=4,pt=5,gt=6,mt=7,ft=8;function onFn(){}function wrapReason(t){if(t instanceof AbortException||t instanceof InvalidPDFException||t instanceof MissingPDFException||t instanceof PasswordException||t instanceof UnexpectedResponseException||t instanceof UnknownErrorException)return t;t instanceof Error||"object"==typeof t&&null!==t||unreachable('wrapReason: Expected "reason" to be a (possibly cloned) Error.');switch(t.name){case"AbortException":return new AbortException(t.message);case"InvalidPDFException":return new InvalidPDFException(t.message);case"MissingPDFException":return new MissingPDFException(t.message);case"PasswordException":return new PasswordException(t.message,t.code);case"UnexpectedResponseException":return new UnexpectedResponseException(t.message,t.status);case"UnknownErrorException":return new UnknownErrorException(t.message,t.details)}return new UnknownErrorException(t.message,t.toString())}class MessageHandler{#si=new AbortController;constructor(t,e,i){this.sourceName=t;this.targetName=e;this.comObj=i;this.callbackId=1;this.streamId=1;this.streamSinks=Object.create(null);this.streamControllers=Object.create(null);this.callbackCapabilities=Object.create(null);this.actionHandler=Object.create(null);i.addEventListener("message",this.#ni.bind(this),{signal:this.#si.signal})}#ni({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream){this.#ai(t);return}if(t.callback){const e=t.callbackId,i=this.callbackCapabilities[e];if(!i)throw new Error(`Cannot resolve callback ${e}`);delete this.callbackCapabilities[e];if(t.callback===ot)i.resolve(t.data);else{if(t.callback!==lt)throw new Error("Unexpected callback case");i.reject(wrapReason(t.reason))}return}const e=this.actionHandler[t.action];if(!e)throw new Error(`Unknown action from worker: ${t.action}`);if(t.callbackId){const i=this.sourceName,s=t.sourceName,n=this.comObj;Promise.try(e,t.data).then((function(e){n.postMessage({sourceName:i,targetName:s,callback:ot,callbackId:t.callbackId,data:e})}),(function(e){n.postMessage({sourceName:i,targetName:s,callback:lt,callbackId:t.callbackId,reason:wrapReason(e)})}))}else t.streamId?this.#ri(t):e(t.data)}on(t,e){const i=this.actionHandler;if(i[t])throw new Error(`There is already an actionName called "${t}"`);i[t]=e}send(t,e,i){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,data:e},i)}sendWithPromise(t,e,i){const s=this.callbackId++,n=Promise.withResolvers();this.callbackCapabilities[s]=n;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:s,data:e},i)}catch(t){n.reject(t)}return n.promise}sendWithStream(t,e,i,s){const n=this.streamId++,a=this.sourceName,r=this.targetName,o=this.comObj;return new ReadableStream({start:i=>{const l=Promise.withResolvers();this.streamControllers[n]={controller:i,startCall:l,pullCall:null,cancelCall:null,isClosed:!1};o.postMessage({sourceName:a,targetName:r,action:t,streamId:n,data:e,desiredSize:i.desiredSize},s);return l.promise},pull:t=>{const e=Promise.withResolvers();this.streamControllers[n].pullCall=e;o.postMessage({sourceName:a,targetName:r,stream:gt,streamId:n,desiredSize:t.desiredSize});return e.promise},cancel:t=>{assert(t instanceof Error,"cancel must have a valid reason");const e=Promise.withResolvers();this.streamControllers[n].cancelCall=e;this.streamControllers[n].isClosed=!0;o.postMessage({sourceName:a,targetName:r,stream:ht,streamId:n,reason:wrapReason(t)});return e.promise}},i)}#ri(t){const e=t.streamId,i=this.sourceName,s=t.sourceName,n=this.comObj,a=this,r=this.actionHandler[t.action],o={enqueue(t,a=1,r){if(this.isCancelled)return;const o=this.desiredSize;this.desiredSize-=a;if(o>0&&this.desiredSize<=0){this.sinkCapability=Promise.withResolvers();this.ready=this.sinkCapability.promise}n.postMessage({sourceName:i,targetName:s,stream:ut,streamId:e,chunk:t},r)},close(){if(!this.isCancelled){this.isCancelled=!0;n.postMessage({sourceName:i,targetName:s,stream:ct,streamId:e});delete a.streamSinks[e]}},error(t){assert(t instanceof Error,"error must have a valid reason");if(!this.isCancelled){this.isCancelled=!0;n.postMessage({sourceName:i,targetName:s,stream:pt,streamId:e,reason:wrapReason(t)})}},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};o.sinkCapability.resolve();o.ready=o.sinkCapability.promise;this.streamSinks[e]=o;Promise.try(r,t.data,o).then((function(){n.postMessage({sourceName:i,targetName:s,stream:ft,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:i,targetName:s,stream:ft,streamId:e,reason:wrapReason(t)})}))}#ai(t){const e=t.streamId,i=this.sourceName,s=t.sourceName,n=this.comObj,a=this.streamControllers[e],r=this.streamSinks[e];switch(t.stream){case ft:t.success?a.startCall.resolve():a.startCall.reject(wrapReason(t.reason));break;case mt:t.success?a.pullCall.resolve():a.pullCall.reject(wrapReason(t.reason));break;case gt:if(!r){n.postMessage({sourceName:i,targetName:s,stream:mt,streamId:e,success:!0});break}r.desiredSize<=0&&t.desiredSize>0&&r.sinkCapability.resolve();r.desiredSize=t.desiredSize;Promise.try(r.onPull||onFn).then((function(){n.postMessage({sourceName:i,targetName:s,stream:mt,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:i,targetName:s,stream:mt,streamId:e,reason:wrapReason(t)})}));break;case ut:assert(a,"enqueue should have stream controller");if(a.isClosed)break;a.controller.enqueue(t.chunk);break;case ct:assert(a,"close should have stream controller");if(a.isClosed)break;a.isClosed=!0;a.controller.close();this.#oi(a,e);break;case pt:assert(a,"error should have stream controller");a.controller.error(wrapReason(t.reason));this.#oi(a,e);break;case dt:t.success?a.cancelCall.resolve():a.cancelCall.reject(wrapReason(t.reason));this.#oi(a,e);break;case ht:if(!r)break;const o=wrapReason(t.reason);Promise.try(r.onCancel||onFn,o).then((function(){n.postMessage({sourceName:i,targetName:s,stream:dt,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:i,targetName:s,stream:dt,streamId:e,reason:wrapReason(t)})}));r.sinkCapability.reject(o);r.isCancelled=!0;delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}}async#oi(t,e){await Promise.allSettled([t.startCall?.promise,t.pullCall?.promise,t.cancelCall?.promise]);delete this.streamControllers[e]}destroy(){this.#si?.abort();this.#si=null}}class BaseCanvasFactory{#li=!1;constructor({enableHWA:t=!1}){this.#li=t}create(t,e){if(t<=0||e<=0)throw new Error("Invalid canvas size");const i=this._createCanvas(t,e);return{canvas:i,context:i.getContext("2d",{willReadFrequently:!this.#li})}}reset(t,e,i){if(!t.canvas)throw new Error("Canvas is not specified");if(e<=0||i<=0)throw new Error("Invalid canvas size");t.canvas.width=e;t.canvas.height=i}destroy(t){if(!t.canvas)throw new Error("Canvas is not specified");t.canvas.width=0;t.canvas.height=0;t.canvas=null;t.context=null}_createCanvas(t,e){unreachable("Abstract method `_createCanvas` called.")}}class BaseCMapReaderFactory{constructor({baseUrl:t=null,isCompressed:e=!0}){this.baseUrl=t;this.isCompressed=e}async fetch({name:t}){if(!this.baseUrl)throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.");if(!t)throw new Error("CMap name must be specified.");const e=this.baseUrl+t+(this.isCompressed?".bcmap":"");return this._fetch(e).then((t=>({cMapData:t,isCompressed:this.isCompressed}))).catch((t=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${e}`)}))}async _fetch(t){unreachable("Abstract method `_fetch` called.")}}class DOMCMapReaderFactory extends BaseCMapReaderFactory{async _fetch(t){const e=await fetchData(t,this.isCompressed?"arraybuffer":"text");return e instanceof ArrayBuffer?new Uint8Array(e):stringToBytes(e)}}class BaseFilterFactory{addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addHighlightHCMFilter(t,e,i,s,n){return"none"}destroy(t=!1){}}class BaseStandardFontDataFactory{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");if(!t)throw new Error("Font filename must be specified.");const e=`${this.baseUrl}${t}`;return this._fetch(e).catch((t=>{throw new Error(`Unable to load font data at: ${e}`)}))}async _fetch(t){unreachable("Abstract method `_fetch` called.")}}class DOMStandardFontDataFactory extends BaseStandardFontDataFactory{async _fetch(t){const e=await fetchData(t,"arraybuffer");return new Uint8Array(e)}}e&&warn("Please use the `legacy` build in Node.js environments.");async function node_utils_fetchData(t){const e=process.getBuiltinModule("fs"),i=await e.promises.readFile(t);return new Uint8Array(i)}const bt="Fill",At="Stroke",wt="Shading";function applyBoundingBox(t,e){if(!e)return;const i=e[2]-e[0],s=e[3]-e[1],n=new Path2D;n.rect(e[0],e[1],i,s);t.clip(n)}class BaseShadingPattern{getPattern(){unreachable("Abstract method `getPattern` called.")}}class RadialAxialShadingPattern extends BaseShadingPattern{constructor(t){super();this._type=t[1];this._bbox=t[2];this._colorStops=t[3];this._p0=t[4];this._p1=t[5];this._r0=t[6];this._r1=t[7];this.matrix=null}_createGradient(t){let e;"axial"===this._type?e=t.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):"radial"===this._type&&(e=t.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(const t of this._colorStops)e.addColorStop(t[0],t[1]);return e}getPattern(t,e,i,s){let n;if(s===At||s===bt){const a=e.current.getClippedPathBoundingBox(s,getCurrentTransform(t))||[0,0,0,0],r=Math.ceil(a[2]-a[0])||1,o=Math.ceil(a[3]-a[1])||1,l=e.cachedCanvases.getCanvas("pattern",r,o),h=l.context;h.clearRect(0,0,h.canvas.width,h.canvas.height);h.beginPath();h.rect(0,0,h.canvas.width,h.canvas.height);h.translate(-a[0],-a[1]);i=Util.transform(i,[1,0,0,1,a[0],a[1]]);h.transform(...e.baseTransform);this.matrix&&h.transform(...this.matrix);applyBoundingBox(h,this._bbox);h.fillStyle=this._createGradient(h);h.fill();n=t.createPattern(l.canvas,"no-repeat");const d=new DOMMatrix(i);n.setTransform(d)}else{applyBoundingBox(t,this._bbox);n=this._createGradient(t)}return n}}function drawTriangle(t,e,i,s,n,a,r,o){const l=e.coords,h=e.colors,d=t.data,c=4*t.width;let u;if(l[i+1]>l[s+1]){u=i;i=s;s=u;u=a;a=r;r=u}if(l[s+1]>l[n+1]){u=s;s=n;n=u;u=r;r=o;o=u}if(l[i+1]>l[s+1]){u=i;i=s;s=u;u=a;a=r;r=u}const p=(l[i]+e.offsetX)*e.scaleX,g=(l[i+1]+e.offsetY)*e.scaleY,m=(l[s]+e.offsetX)*e.scaleX,f=(l[s+1]+e.offsetY)*e.scaleY,b=(l[n]+e.offsetX)*e.scaleX,A=(l[n+1]+e.offsetY)*e.scaleY;if(g>=A)return;const w=h[a],v=h[a+1],y=h[a+2],x=h[r],_=h[r+1],E=h[r+2],S=h[o],C=h[o+1],T=h[o+2],M=Math.round(g),P=Math.round(A);let D,k,R,I,F,L,O,N;for(let t=M;t<=P;t++){if(tA?1:f===A?0:(f-t)/(f-A);D=m-(m-b)*e;k=x-(x-S)*e;R=_-(_-C)*e;I=E-(E-T)*e}let e;e=tA?1:(g-t)/(g-A);F=p-(p-b)*e;L=w-(w-S)*e;O=v-(v-C)*e;N=y-(y-T)*e;const i=Math.round(Math.min(D,F)),s=Math.round(Math.max(D,F));let n=c*t+4*i;for(let t=i;t<=s;t++){e=(D-t)/(D-F);e<0?e=0:e>1&&(e=1);d[n++]=k-(k-L)*e|0;d[n++]=R-(R-O)*e|0;d[n++]=I-(I-N)*e|0;d[n++]=255}}}function drawFigure(t,e,i){const s=e.coords,n=e.colors;let a,r;switch(e.type){case"lattice":const o=e.verticesPerRow,l=Math.floor(s.length/o)-1,h=o-1;for(a=0;a=Math.ceil(p*b)?w=o:y=!0;E>=Math.ceil(g*A)?v=l:x=!0;const S=this.getSizeAndScale(w,this.ctx.canvas.width,b),C=this.getSizeAndScale(v,this.ctx.canvas.height,A),T=t.cachedCanvases.getCanvas("pattern",S.size,C.size),M=T.context,P=r.createCanvasGraphics(M);P.groupLevel=t.groupLevel;this.setFillAndStrokeStyleToContext(P,s,a);M.translate(-S.scale*h,-C.scale*d);P.transform(S.scale,0,0,C.scale,0,0);M.save();this.clipBbox(P,h,d,c,u);P.baseTransform=getCurrentTransform(P.ctx);P.executeOperatorList(i);P.endDrawing();M.restore();if(y||x){const e=T.canvas;y&&(w=o);x&&(v=l);const i=this.getSizeAndScale(w,this.ctx.canvas.width,b),s=this.getSizeAndScale(v,this.ctx.canvas.height,A),n=i.size,a=s.size,r=t.cachedCanvases.getCanvas("pattern-workaround",n,a),c=r.context,u=y?Math.floor(p/o):0,m=x?Math.floor(g/l):0;for(let t=0;t<=u;t++)for(let i=0;i<=m;i++)c.drawImage(e,n*t,a*i,n,a,0,0,n,a);return{canvas:r.canvas,scaleX:i.scale,scaleY:s.scale,offsetX:h,offsetY:d}}return{canvas:T.canvas,scaleX:S.scale,scaleY:C.scale,offsetX:h,offsetY:d}}getSizeAndScale(t,e,i){const s=Math.max(TilingPattern.MAX_PATTERN_SIZE,e);let n=Math.ceil(t*i);n>=s?n=s:i=n/t;return{scale:i,size:n}}clipBbox(t,e,i,s,n){const a=s-e,r=n-i;t.ctx.rect(e,i,a,r);t.current.updateRectMinMax(getCurrentTransform(t.ctx),[e,i,s,n]);t.clip();t.endPath()}setFillAndStrokeStyleToContext(t,e,i){const s=t.ctx,n=t.current;switch(e){case vt:const t=this.ctx;s.fillStyle=t.fillStyle;s.strokeStyle=t.strokeStyle;n.fillColor=t.fillStyle;n.strokeColor=t.strokeStyle;break;case yt:const a=Util.makeHexColor(i[0],i[1],i[2]);s.fillStyle=a;s.strokeStyle=a;n.fillColor=a;n.strokeColor=a;break;default:throw new FormatError(`Unsupported paint type: ${e}`)}}getPattern(t,e,i,s){let n=i;if(s!==wt){n=Util.transform(n,e.baseTransform);this.matrix&&(n=Util.transform(n,this.matrix))}const a=this.createPatternCanvas(e);let r=new DOMMatrix(n);r=r.translate(a.offsetX,a.offsetY);r=r.scale(1/a.scaleX,1/a.scaleY);const o=t.createPattern(a.canvas,"repeat");o.setTransform(r);return o}}function convertBlackAndWhiteToRGBA({src:t,srcPos:e=0,dest:i,width:s,height:n,nonBlackColor:a=4294967295,inverseDecode:r=!1}){const o=util_FeatureTest.isLittleEndian?4278190080:255,[l,h]=r?[a,o]:[o,a],d=s>>3,c=7&s,u=t.length;i=new Uint32Array(i.buffer);let p=0;for(let s=0;s>2),m=i.length,f=s+7>>3,b=4294967295,A=util_FeatureTest.isLittleEndian?4278190080:255;for(u=0;uf?s:8*t-7,r=-8&a;let o=0,c=0;for(;n>=1}}for(;l=a){g=n;m=s*g}l=0;for(p=m;p--;){c[l++]=d[h++];c[l++]=d[h++];c[l++]=d[h++];c[l++]=255}t.putImageData(o,0,u*xt)}}}function putBinaryImageMask(t,e){if(e.bitmap){t.drawImage(e.bitmap,0,0);return}const i=e.height,s=e.width,n=i%xt,a=(i-n)/xt,r=0===n?a:a+1,o=t.createImageData(s,xt);let l=0;const h=e.data,d=o.data;for(let e=0;e10&&"function"==typeof i,h=l?Date.now()+15:0;let d=0;const c=this.commonObjs,u=this.objs;let p;for(;;){if(void 0!==s&&r===s.nextBreakPoint){s.breakIt(r,i);return r}p=a[r];if(p!==X.dependency)this[p].apply(this,n[r]);else for(const t of n[r]){const e=t.startsWith("g_")?c:u;if(!e.has(t)){e.get(t,i);return r}}r++;if(r===o)return r;if(l&&++d>10){if(Date.now()>h){i();return r}d=0}}}#hi(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null;this.ctx.restore();if(this.transparentCanvas){this.ctx=this.compositeCtx;this.ctx.save();this.ctx.setTransform(1,0,0,1,0,0);this.ctx.drawImage(this.transparentCanvas,0,0);this.ctx.restore();this.transparentCanvas=null}}endDrawing(){this.#hi();this.cachedCanvases.clear();this.cachedPatterns.clear();for(const t of this._cachedBitmapsMap.values()){for(const e of t.values())"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement&&(e.width=e.height=0);t.clear()}this._cachedBitmapsMap.clear();this.#di()}#di(){if(this.pageColors){const t=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if("none"!==t){const e=this.ctx.filter;this.ctx.filter=t;this.ctx.drawImage(this.ctx.canvas,0,0);this.ctx.filter=e}}}_scaleImage(t,e){const i=t.width??t.displayWidth,s=t.height??t.displayHeight;let n,a,r=Math.max(Math.hypot(e[0],e[1]),1),o=Math.max(Math.hypot(e[2],e[3]),1),l=i,h=s,d="prescale1";for(;r>2&&l>1||o>2&&h>1;){let e=l,i=h;if(r>2&&l>1){e=l>=16384?Math.floor(l/2)-1||1:Math.ceil(l/2);r/=l/e}if(o>2&&h>1){i=h>=16384?Math.floor(h/2)-1||1:Math.ceil(h)/2;o/=h/i}n=this.cachedCanvases.getCanvas(d,e,i);a=n.context;a.clearRect(0,0,e,i);a.drawImage(t,0,0,l,h,0,0,e,i);t=n.canvas;l=e;h=i;d="prescale1"===d?"prescale2":"prescale1"}return{img:t,paintWidth:l,paintHeight:h}}_createMaskCanvas(t){const e=this.ctx,{width:i,height:s}=t,n=this.current.fillColor,a=this.current.patternFill,r=getCurrentTransform(e);let o,l,h,d;if((t.bitmap||t.data)&&t.count>1){const e=t.bitmap||t.data.buffer;l=JSON.stringify(a?r:[r.slice(0,4),n]);o=this._cachedBitmapsMap.get(e);if(!o){o=new Map;this._cachedBitmapsMap.set(e,o)}const i=o.get(l);if(i&&!a){return{canvas:i,offsetX:Math.round(Math.min(r[0],r[2])+r[4]),offsetY:Math.round(Math.min(r[1],r[3])+r[5])}}h=i}if(!h){d=this.cachedCanvases.getCanvas("maskCanvas",i,s);putBinaryImageMask(d.context,t)}let c=Util.transform(r,[1/i,0,0,-1/s,0,0]);c=Util.transform(c,[1,0,0,1,0,-s]);const[u,p,g,m]=Util.getAxialAlignedBoundingBox([0,0,i,s],c),f=Math.round(g-u)||1,b=Math.round(m-p)||1,A=this.cachedCanvases.getCanvas("fillCanvas",f,b),w=A.context,v=u,y=p;w.translate(-v,-y);w.transform(...c);if(!h){h=this._scaleImage(d.canvas,getCurrentTransformInverse(w));h=h.img;o&&a&&o.set(l,h)}w.imageSmoothingEnabled=getImageSmoothingEnabled(getCurrentTransform(w),t.interpolate);drawImageAtIntegerCoords(w,h,0,0,h.width,h.height,0,0,i,s);w.globalCompositeOperation="source-in";const x=Util.transform(getCurrentTransformInverse(w),[1,0,0,1,-v,-y]);w.fillStyle=a?n.getPattern(e,this,x,bt):n;w.fillRect(0,0,i,s);if(o&&!a){this.cachedCanvases.delete("fillCanvas");o.set(l,A.canvas)}return{canvas:A.canvas,offsetX:Math.round(v),offsetY:Math.round(y)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1);this.current.lineWidth=t;this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=_t[t]}setLineJoin(t){this.ctx.lineJoin=Et[t]}setMiterLimit(t){this.ctx.miterLimit=t}setDash(t,e){const i=this.ctx;if(void 0!==i.setLineDash){i.setLineDash(t);i.lineDashOffset=e}}setRenderingIntent(t){}setFlatness(t){}setGState(t){for(const[e,i]of t)switch(e){case"LW":this.setLineWidth(i);break;case"LC":this.setLineCap(i);break;case"LJ":this.setLineJoin(i);break;case"ML":this.setMiterLimit(i);break;case"D":this.setDash(i[0],i[1]);break;case"RI":this.setRenderingIntent(i);break;case"FL":this.setFlatness(i);break;case"Font":this.setFont(i[0],i[1]);break;case"CA":this.current.strokeAlpha=i;break;case"ca":this.current.fillAlpha=i;this.ctx.globalAlpha=i;break;case"BM":this.ctx.globalCompositeOperation=i;break;case"SMask":this.current.activeSMask=i?this.tempSMask:null;this.tempSMask=null;this.checkSMaskState();break;case"TR":this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(i)}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){const t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode():!this.current.activeSMask&&t&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const t=this.ctx.canvas.width,e=this.ctx.canvas.height,i="smaskGroupAt"+this.groupLevel,s=this.cachedCanvases.getCanvas(i,t,e);this.suspendedCtx=this.ctx;this.ctx=s.context;const n=this.ctx;n.setTransform(...getCurrentTransform(this.suspendedCtx));copyCtxState(this.suspendedCtx,n);!function mirrorContextOperations(t,e){if(t._removeMirroring)throw new Error("Context is already forwarding operations.");t.__originalSave=t.save;t.__originalRestore=t.restore;t.__originalRotate=t.rotate;t.__originalScale=t.scale;t.__originalTranslate=t.translate;t.__originalTransform=t.transform;t.__originalSetTransform=t.setTransform;t.__originalResetTransform=t.resetTransform;t.__originalClip=t.clip;t.__originalMoveTo=t.moveTo;t.__originalLineTo=t.lineTo;t.__originalBezierCurveTo=t.bezierCurveTo;t.__originalRect=t.rect;t.__originalClosePath=t.closePath;t.__originalBeginPath=t.beginPath;t._removeMirroring=()=>{t.save=t.__originalSave;t.restore=t.__originalRestore;t.rotate=t.__originalRotate;t.scale=t.__originalScale;t.translate=t.__originalTranslate;t.transform=t.__originalTransform;t.setTransform=t.__originalSetTransform;t.resetTransform=t.__originalResetTransform;t.clip=t.__originalClip;t.moveTo=t.__originalMoveTo;t.lineTo=t.__originalLineTo;t.bezierCurveTo=t.__originalBezierCurveTo;t.rect=t.__originalRect;t.closePath=t.__originalClosePath;t.beginPath=t.__originalBeginPath;delete t._removeMirroring};t.save=function ctxSave(){e.save();this.__originalSave()};t.restore=function ctxRestore(){e.restore();this.__originalRestore()};t.translate=function ctxTranslate(t,i){e.translate(t,i);this.__originalTranslate(t,i)};t.scale=function ctxScale(t,i){e.scale(t,i);this.__originalScale(t,i)};t.transform=function ctxTransform(t,i,s,n,a,r){e.transform(t,i,s,n,a,r);this.__originalTransform(t,i,s,n,a,r)};t.setTransform=function ctxSetTransform(t,i,s,n,a,r){e.setTransform(t,i,s,n,a,r);this.__originalSetTransform(t,i,s,n,a,r)};t.resetTransform=function ctxResetTransform(){e.resetTransform();this.__originalResetTransform()};t.rotate=function ctxRotate(t){e.rotate(t);this.__originalRotate(t)};t.clip=function ctxRotate(t){e.clip(t);this.__originalClip(t)};t.moveTo=function(t,i){e.moveTo(t,i);this.__originalMoveTo(t,i)};t.lineTo=function(t,i){e.lineTo(t,i);this.__originalLineTo(t,i)};t.bezierCurveTo=function(t,i,s,n,a,r){e.bezierCurveTo(t,i,s,n,a,r);this.__originalBezierCurveTo(t,i,s,n,a,r)};t.rect=function(t,i,s,n){e.rect(t,i,s,n);this.__originalRect(t,i,s,n)};t.closePath=function(){e.closePath();this.__originalClosePath()};t.beginPath=function(){e.beginPath();this.__originalBeginPath()}}(n,this.suspendedCtx);this.setGState([["BM","source-over"],["ca",1],["CA",1]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring();copyCtxState(this.ctx,this.suspendedCtx);this.ctx=this.suspendedCtx;this.suspendedCtx=null}compose(t){if(!this.current.activeSMask)return;if(t){t[0]=Math.floor(t[0]);t[1]=Math.floor(t[1]);t[2]=Math.ceil(t[2]);t[3]=Math.ceil(t[3])}else t=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const e=this.current.activeSMask,i=this.suspendedCtx;this.composeSMask(i,e,this.ctx,t);this.ctx.save();this.ctx.setTransform(1,0,0,1,0,0);this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height);this.ctx.restore()}composeSMask(t,e,i,s){const n=s[0],a=s[1],r=s[2]-n,o=s[3]-a;if(0!==r&&0!==o){this.genericComposeSMask(e.context,i,r,o,e.subtype,e.backdrop,e.transferMap,n,a,e.offsetX,e.offsetY);t.save();t.globalAlpha=1;t.globalCompositeOperation="source-over";t.setTransform(1,0,0,1,0,0);t.drawImage(i.canvas,0,0);t.restore()}}genericComposeSMask(t,e,i,s,n,a,r,o,l,h,d){let c=t.canvas,u=o-h,p=l-d;if(a){const e=Util.makeHexColor(...a);if(u<0||p<0||u+i>c.width||p+s>c.height){const t=this.cachedCanvases.getCanvas("maskExtension",i,s),n=t.context;n.drawImage(c,-u,-p);n.globalCompositeOperation="destination-atop";n.fillStyle=e;n.fillRect(0,0,i,s);n.globalCompositeOperation="source-over";c=t.canvas;u=p=0}else{t.save();t.globalAlpha=1;t.setTransform(1,0,0,1,0,0);const n=new Path2D;n.rect(u,p,i,s);t.clip(n);t.globalCompositeOperation="destination-atop";t.fillStyle=e;t.fillRect(u,p,i,s);t.restore()}}e.save();e.globalAlpha=1;e.setTransform(1,0,0,1,0,0);"Alpha"===n&&r?e.filter=this.filterFactory.addAlphaFilter(r):"Luminosity"===n&&(e.filter=this.filterFactory.addLuminosityFilter(r));const g=new Path2D;g.rect(o,l,i,s);e.clip(g);e.globalCompositeOperation="destination-in";e.drawImage(c,u,p,i,s,o,l,i,s);e.restore()}save(){if(this.inSMaskMode){copyCtxState(this.ctx,this.suspendedCtx);this.suspendedCtx.save()}else this.ctx.save();const t=this.current;this.stateStack.push(t);this.current=t.clone()}restore(){0===this.stateStack.length&&this.inSMaskMode&&this.endSMaskMode();if(0!==this.stateStack.length){this.current=this.stateStack.pop();if(this.inSMaskMode){this.suspendedCtx.restore();copyCtxState(this.suspendedCtx,this.ctx)}else this.ctx.restore();this.checkSMaskState();this.pendingClip=null;this._cachedScaleForStroking[0]=-1;this._cachedGetSinglePixelWidth=null}}transform(t,e,i,s,n,a){this.ctx.transform(t,e,i,s,n,a);this._cachedScaleForStroking[0]=-1;this._cachedGetSinglePixelWidth=null}constructPath(t,e,i){const s=this.ctx,n=this.current;let a,r,o=n.x,l=n.y;const h=getCurrentTransform(s),d=0===h[0]&&0===h[3]||0===h[1]&&0===h[2],c=d?i.slice(0):null;for(let i=0,u=0,p=t.length;i100&&(h=100);this.current.fontSizeScale=e/h;this.ctx.font=`${l} ${o} ${h}px ${r}`}setTextRenderingMode(t){this.current.textRenderingMode=t}setTextRise(t){this.current.textRise=t}moveText(t,e){this.current.x=this.current.lineX+=t;this.current.y=this.current.lineY+=e}setLeadingMoveText(t,e){this.setLeading(-e);this.moveText(t,e)}setTextMatrix(t,e,i,s,n,a){this.current.textMatrix=[t,e,i,s,n,a];this.current.textMatrixScale=Math.hypot(t,e);this.current.x=this.current.lineX=0;this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}#ci(t,e,i){const s=new Path2D;s.addPath(t,new DOMMatrix(i).invertSelf().multiplySelf(e));return s}paintChar(t,e,i,s,n){const a=this.ctx,r=this.current,o=r.font,l=r.textRenderingMode,h=r.fontSize/r.fontSizeScale,d=l&y,c=!!(l&x),u=r.patternFill&&!o.missingFile,p=r.patternStroke&&!o.missingFile;let g;(o.disableFontFace||c||u||p)&&(g=o.getPathGenerator(this.commonObjs,t));if(o.disableFontFace||u||p){a.save();a.translate(e,i);a.scale(h,-h);if(d===b||d===w)if(s){const t=a.getTransform();a.setTransform(...s);a.fill(this.#ci(g,t,s))}else a.fill(g);if(d===A||d===w)if(n){const t=a.getTransform();a.setTransform(...n);a.stroke(this.#ci(g,t,n))}else{a.lineWidth/=h;a.stroke(g)}a.restore()}else{d!==b&&d!==w||a.fillText(t,e,i);d!==A&&d!==w||a.strokeText(t,e,i)}if(c){(this.pendingTextPaths||=[]).push({transform:getCurrentTransform(a),x:e,y:i,fontSize:h,path:g})}}get isFontSubpixelAAEnabled(){const{context:t}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);t.scale(1.5,1);t.fillText("I",0,10);const e=t.getImageData(0,0,10,10).data;let i=!1;for(let t=3;t0&&e[t]<255){i=!0;break}return shadow(this,"isFontSubpixelAAEnabled",i)}showText(t){const e=this.current,i=e.font;if(i.isType3Font)return this.showType3Text(t);const s=e.fontSize;if(0===s)return;const n=this.ctx,a=e.fontSizeScale,r=e.charSpacing,o=e.wordSpacing,l=e.fontDirection,h=e.textHScale*l,d=t.length,c=i.vertical,u=c?1:-1,p=i.defaultVMetrics,g=s*e.fontMatrix[0],m=e.textRenderingMode===b&&!i.disableFontFace&&!e.patternFill;n.save();n.transform(...e.textMatrix);n.translate(e.x,e.y+e.textRise);l>0?n.scale(h,-1):n.scale(h,1);let f,v;if(e.patternFill){n.save();const t=e.fillColor.getPattern(n,this,getCurrentTransformInverse(n),bt);f=getCurrentTransform(n);n.restore();n.fillStyle=t}if(e.patternStroke){n.save();const t=e.strokeColor.getPattern(n,this,getCurrentTransformInverse(n),At);v=getCurrentTransform(n);n.restore();n.strokeStyle=t}let x=e.lineWidth;const _=e.textMatrixScale;if(0===_||0===x){const t=e.textRenderingMode&y;t!==A&&t!==w||(x=this.getSinglePixelWidth())}else x/=_;if(1!==a){n.scale(a,a);x/=a}n.lineWidth=x;if(i.isInvalidPDFjsFont){const i=[];let s=0;for(const e of t){i.push(e.unicode);s+=e.width}n.fillText(i.join(""),0,0);e.x+=s*g*h;n.restore();this.compose();return}let E,S=0;for(E=0;E0){const t=1e3*n.measureText(b).width/s*a;if(xnew CanvasGraphics(t,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};e=new TilingPattern(t,i,this.ctx,n,s)}else e=this._getPattern(t[1],t[2]);return e}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments);this.current.patternStroke=!0}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments);this.current.patternFill=!0}setStrokeRGBColor(t,e,i){this.ctx.strokeStyle=this.current.strokeColor=Util.makeHexColor(t,e,i);this.current.patternStroke=!1}setStrokeTransparent(){this.ctx.strokeStyle=this.current.strokeColor="transparent";this.current.patternStroke=!1}setFillRGBColor(t,e,i){this.ctx.fillStyle=this.current.fillColor=Util.makeHexColor(t,e,i);this.current.patternFill=!1}setFillTransparent(){this.ctx.fillStyle=this.current.fillColor="transparent";this.current.patternFill=!1}_getPattern(t,e=null){let i;if(this.cachedPatterns.has(t))i=this.cachedPatterns.get(t);else{i=function getShadingPattern(t){switch(t[0]){case"RadialAxial":return new RadialAxialShadingPattern(t);case"Mesh":return new MeshShadingPattern(t);case"Dummy":return new DummyShadingPattern}throw new Error(`Unknown IR type: ${t[0]}`)}(this.getObject(t));this.cachedPatterns.set(t,i)}e&&(i.matrix=e);return i}shadingFill(t){if(!this.contentVisible)return;const e=this.ctx;this.save();const i=this._getPattern(t);e.fillStyle=i.getPattern(e,this,getCurrentTransformInverse(e),wt);const s=getCurrentTransformInverse(e);if(s){const{width:t,height:i}=e.canvas,[n,a,r,o]=Util.getAxialAlignedBoundingBox([0,0,t,i],s);this.ctx.fillRect(n,a,r-n,o-a)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox());this.restore()}beginInlineImage(){unreachable("Should not call beginInlineImage")}beginImageData(){unreachable("Should not call beginImageData")}paintFormXObjectBegin(t,e){if(this.contentVisible){this.save();this.baseTransformStack.push(this.baseTransform);t&&this.transform(...t);this.baseTransform=getCurrentTransform(this.ctx);if(e){const t=e[2]-e[0],i=e[3]-e[1];this.ctx.rect(e[0],e[1],t,i);this.current.updateRectMinMax(getCurrentTransform(this.ctx),e);this.clip();this.endPath()}}}paintFormXObjectEnd(){if(this.contentVisible){this.restore();this.baseTransform=this.baseTransformStack.pop()}}beginGroup(t){if(!this.contentVisible)return;this.save();if(this.inSMaskMode){this.endSMaskMode();this.current.activeSMask=null}const e=this.ctx;t.isolated||info("TODO: Support non-isolated groups.");t.knockout&&warn("Knockout groups not supported.");const i=getCurrentTransform(e);t.matrix&&e.transform(...t.matrix);if(!t.bbox)throw new Error("Bounding box is required.");let s=Util.getAxialAlignedBoundingBox(t.bbox,getCurrentTransform(e));const n=[0,0,e.canvas.width,e.canvas.height];s=Util.intersect(s,n)||[0,0,0,0];const a=Math.floor(s[0]),r=Math.floor(s[1]),o=Math.max(Math.ceil(s[2])-a,1),l=Math.max(Math.ceil(s[3])-r,1);this.current.startNewPathAndClipBox([0,0,o,l]);let h="groupAt"+this.groupLevel;t.smask&&(h+="_smask_"+this.smaskCounter++%2);const d=this.cachedCanvases.getCanvas(h,o,l),c=d.context;c.translate(-a,-r);c.transform(...i);if(t.smask)this.smaskStack.push({canvas:d.canvas,context:c,offsetX:a,offsetY:r,subtype:t.smask.subtype,backdrop:t.smask.backdrop,transferMap:t.smask.transferMap||null,startTransformInverse:null});else{e.setTransform(1,0,0,1,0,0);e.translate(a,r);e.save()}copyCtxState(e,c);this.ctx=c;this.setGState([["BM","source-over"],["ca",1],["CA",1]]);this.groupStack.push(e);this.groupLevel++}endGroup(t){if(!this.contentVisible)return;this.groupLevel--;const e=this.ctx,i=this.groupStack.pop();this.ctx=i;this.ctx.imageSmoothingEnabled=!1;if(t.smask){this.tempSMask=this.smaskStack.pop();this.restore()}else{this.ctx.restore();const t=getCurrentTransform(this.ctx);this.restore();this.ctx.save();this.ctx.setTransform(...t);const i=Util.getAxialAlignedBoundingBox([0,0,e.canvas.width,e.canvas.height],t);this.ctx.drawImage(e.canvas,0,0);this.ctx.restore();this.compose(i)}}beginAnnotation(t,e,i,s,n){this.#hi();resetCtxToDefault(this.ctx);this.ctx.save();this.save();this.baseTransform&&this.ctx.setTransform(...this.baseTransform);if(e){const s=e[2]-e[0],a=e[3]-e[1];if(n&&this.annotationCanvasMap){(i=i.slice())[4]-=e[0];i[5]-=e[1];(e=e.slice())[0]=e[1]=0;e[2]=s;e[3]=a;const[n,r]=Util.singularValueDecompose2dScale(getCurrentTransform(this.ctx)),{viewportScale:o}=this,l=Math.ceil(s*this.outputScaleX*o),h=Math.ceil(a*this.outputScaleY*o);this.annotationCanvas=this.canvasFactory.create(l,h);const{canvas:d,context:c}=this.annotationCanvas;this.annotationCanvasMap.set(t,d);this.annotationCanvas.savedCtx=this.ctx;this.ctx=c;this.ctx.save();this.ctx.setTransform(n,0,0,-r,0,a*r);resetCtxToDefault(this.ctx)}else{resetCtxToDefault(this.ctx);this.endPath();this.ctx.rect(e[0],e[1],s,a);this.ctx.clip();this.ctx.beginPath()}}this.current=new CanvasExtraState(this.ctx.canvas.width,this.ctx.canvas.height);this.transform(...i);this.transform(...s)}endAnnotation(){if(this.annotationCanvas){this.ctx.restore();this.#di();this.ctx=this.annotationCanvas.savedCtx;delete this.annotationCanvas.savedCtx;delete this.annotationCanvas}}paintImageMaskXObject(t){if(!this.contentVisible)return;const e=t.count;(t=this.getObject(t.data,t)).count=e;const i=this.ctx,s=this.processingType3;if(s){void 0===s.compiled&&(s.compiled=function compileType3Glyph(t){const{width:e,height:i}=t;if(e>1e3||i>1e3)return null;const s=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),n=e+1;let a,r,o,l=new Uint8Array(n*(i+1));const h=e+7&-8;let d=new Uint8Array(h*i),c=0;for(const e of t.data){let t=128;for(;t>0;){d[c++]=e&t?0:255;t>>=1}}let u=0;c=0;if(0!==d[c]){l[0]=1;++u}for(r=1;r>2)+(d[c+1]?4:0)+(d[c-h+1]?8:0);if(s[t]){l[o+r]=s[t];++u}c++}if(d[c-h]!==d[c]){l[o+r]=d[c]?2:4;++u}if(u>1e3)return null}c=h*(i-1);o=a*n;if(0!==d[c]){l[o]=8;++u}for(r=1;r1e3)return null;const p=new Int32Array([0,n,-1,0,-n,0,0,0,1]),g=new Path2D;for(a=0;u&&a<=i;a++){let t=a*n;const i=t+e;for(;t>4;l[t]&=r>>2|r<<2}g.lineTo(t%n,t/n|0);l[t]||--u}while(s!==t);--a}d=null;l=null;return function(t){t.save();t.scale(1/e,-1/i);t.translate(0,-i);t.fill(g);t.beginPath();t.restore()}}(t));if(s.compiled){s.compiled(i);return}}const n=this._createMaskCanvas(t),a=n.canvas;i.save();i.setTransform(1,0,0,1,0,0);i.drawImage(a,n.offsetX,n.offsetY);i.restore();this.compose()}paintImageMaskXObjectRepeat(t,e,i=0,s=0,n,a){if(!this.contentVisible)return;t=this.getObject(t.data,t);const r=this.ctx;r.save();const o=getCurrentTransform(r);r.transform(e,i,s,n,0,0);const l=this._createMaskCanvas(t);r.setTransform(1,0,0,1,l.offsetX-o[4],l.offsetY-o[5]);for(let t=0,h=a.length;te?h/e:1;r=l>e?l/e:1}}this._cachedScaleForStroking[0]=a;this._cachedScaleForStroking[1]=r}return this._cachedScaleForStroking}rescaleAndStroke(t){const{ctx:e}=this,{lineWidth:i}=this.current,[s,n]=this.getScaleForStroking();e.lineWidth=i||1;if(1===s&&1===n){e.stroke();return}const a=e.getLineDash();t&&e.save();e.scale(s,n);if(a.length>0){const t=Math.max(s,n);e.setLineDash(a.map((e=>e/t)));e.lineDashOffset/=t}e.stroke();t&&e.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}}for(const t in X)void 0!==CanvasGraphics.prototype[t]&&(CanvasGraphics.prototype[X[t]]=CanvasGraphics.prototype[t]);class GlobalWorkerOptions{static#ui=null;static#pi="";static get workerPort(){return this.#ui}static set workerPort(t){if(!("undefined"!=typeof Worker&&t instanceof Worker)&&null!==t)throw new Error("Invalid `workerPort` type.");this.#ui=t}static get workerSrc(){return this.#pi}static set workerSrc(t){if("string"!=typeof t)throw new Error("Invalid `workerSrc` type.");this.#pi=t}}class Metadata{#gi;#mi;constructor({parsedData:t,rawData:e}){this.#gi=t;this.#mi=e}getRaw(){return this.#mi}get(t){return this.#gi.get(t)??null}getAll(){return objectFromMap(this.#gi)}has(t){return this.#gi.has(t)}}const Tt=Symbol("INTERNAL");class OptionalContentGroup{#fi=!1;#bi=!1;#Ai=!1;#wi=!0;constructor(t,{name:e,intent:i,usage:s,rbGroups:n}){this.#fi=!!(t&r);this.#bi=!!(t&o);this.name=e;this.intent=i;this.usage=s;this.rbGroups=n}get visible(){if(this.#Ai)return this.#wi;if(!this.#wi)return!1;const{print:t,view:e}=this.usage;return this.#fi?"OFF"!==e?.viewState:!this.#bi||"OFF"!==t?.printState}_setVisible(t,e,i=!1){t!==Tt&&unreachable("Internal method `_setVisible` called.");this.#Ai=i;this.#wi=e}}class OptionalContentConfig{#vi=null;#yi=new Map;#xi=null;#_i=null;constructor(t,e=r){this.renderingIntent=e;this.name=null;this.creator=null;if(null!==t){this.name=t.name;this.creator=t.creator;this.#_i=t.order;for(const i of t.groups)this.#yi.set(i.id,new OptionalContentGroup(e,i));if("OFF"===t.baseState)for(const t of this.#yi.values())t._setVisible(Tt,!1);for(const e of t.on)this.#yi.get(e)._setVisible(Tt,!0);for(const e of t.off)this.#yi.get(e)._setVisible(Tt,!1);this.#xi=this.getHash()}}#Ei(t){const e=t.length;if(e<2)return!0;const i=t[0];for(let s=1;s0?objectFromMap(this.#yi):null}getGroup(t){return this.#yi.get(t)||null}getHash(){if(null!==this.#vi)return this.#vi;const t=new MurmurHash3_64;for(const[e,i]of this.#yi)t.update(`${e}:${i.visible}`);return this.#vi=t.hexdigest()}}class PDFDataTransportStream{constructor(t,{disableRange:e=!1,disableStream:i=!1}){assert(t,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');const{length:s,initialData:n,progressiveDone:a,contentDispositionFilename:r}=t;this._queuedChunks=[];this._progressiveDone=a;this._contentDispositionFilename=r;if(n?.length>0){const t=n instanceof Uint8Array&&n.byteLength===n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer;this._queuedChunks.push(t)}this._pdfDataRangeTransport=t;this._isStreamingSupported=!i;this._isRangeSupported=!e;this._contentLength=s;this._fullRequestReader=null;this._rangeReaders=[];t.addRangeListener(((t,e)=>{this._onReceiveData({begin:t,chunk:e})}));t.addProgressListener(((t,e)=>{this._onProgress({loaded:t,total:e})}));t.addProgressiveReadListener((t=>{this._onReceiveData({chunk:t})}));t.addProgressiveDoneListener((()=>{this._onProgressiveDone()}));t.transportReady()}_onReceiveData({begin:t,chunk:e}){const i=e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer;if(void 0===t)this._fullRequestReader?this._fullRequestReader._enqueue(i):this._queuedChunks.push(i);else{assert(this._rangeReaders.some((function(e){if(e._begin!==t)return!1;e._enqueue(i);return!0})),"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}_onProgress(t){void 0===t.total?this._rangeReaders[0]?.onProgress?.({loaded:t.loaded}):this._fullRequestReader?.onProgress?.({loaded:t.loaded,total:t.total})}_onProgressiveDone(){this._fullRequestReader?.progressiveDone();this._progressiveDone=!0}_removeRangeReader(t){const e=this._rangeReaders.indexOf(t);e>=0&&this._rangeReaders.splice(e,1)}getFullReader(){assert(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;this._queuedChunks=null;return new PDFDataTransportStreamReader(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new PDFDataTransportStreamRangeReader(this,t,e);this._pdfDataRangeTransport.requestDataRange(t,e);this._rangeReaders.push(i);return i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeReaders.slice(0))e.cancel(t);this._pdfDataRangeTransport.abort()}}class PDFDataTransportStreamReader{constructor(t,e,i=!1,s=null){this._stream=t;this._done=i||!1;this._filename=isPdfFile(s)?s:null;this._queuedChunks=e||[];this._loaded=0;for(const t of this._queuedChunks)this._loaded+=t.byteLength;this._requests=[];this._headersReady=Promise.resolve();t._fullRequestReader=this;this.onProgress=null}_enqueue(t){if(!this._done){if(this._requests.length>0){this._requests.shift().resolve({value:t,done:!1})}else this._queuedChunks.push(t);this._loaded+=t.byteLength}}get headersReady(){return this._headersReady}get filename(){return this._filename}get isRangeSupported(){return this._stream._isRangeSupported}get isStreamingSupported(){return this._stream._isStreamingSupported}get contentLength(){return this._stream._contentLength}async read(){if(this._queuedChunks.length>0){return{value:this._queuedChunks.shift(),done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||(this._done=!0)}}class PDFDataTransportStreamRangeReader{constructor(t,e,i){this._stream=t;this._begin=e;this._end=i;this._queuedChunk=null;this._requests=[];this._done=!1;this.onProgress=null}_enqueue(t){if(!this._done){if(0===this._requests.length)this._queuedChunk=t;else{this._requests.shift().resolve({value:t,done:!1});for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}this._done=!0;this._stream._removeRangeReader(this)}}get isStreamingSupported(){return!1}async read(){if(this._queuedChunk){const t=this._queuedChunk;this._queuedChunk=null;return{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0;this._stream._removeRangeReader(this)}}function createHeaders(t,e){const i=new Headers;if(!t||!e||"object"!=typeof e)return i;for(const t in e){const s=e[t];void 0!==s&&i.append(t,s)}return i}function getResponseOrigin(t){try{return new URL(t).origin}catch{}return null}function validateRangeRequestCapabilities({responseHeaders:t,isHttp:e,rangeChunkSize:i,disableRange:s}){const n={allowRangeRequests:!1,suggestedLength:void 0},a=parseInt(t.get("Content-Length"),10);if(!Number.isInteger(a))return n;n.suggestedLength=a;if(a<=2*i)return n;if(s||!e)return n;if("bytes"!==t.get("Accept-Ranges"))return n;if("identity"!==(t.get("Content-Encoding")||"identity"))return n;n.allowRangeRequests=!0;return n}function extractFilenameFromHeader(t){const e=t.get("Content-Disposition");if(e){let t=function getFilenameFromContentDispositionHeader(t){let e=!0,i=toParamRegExp("filename\\*","i").exec(t);if(i){i=i[1];let t=rfc2616unquote(i);t=unescape(t);t=rfc5987decode(t);t=rfc2047decode(t);return fixupEncoding(t)}i=function rfc2231getparam(t){const e=[];let i;const s=toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;null!==(i=s.exec(t));){let[,t,s,n]=i;t=parseInt(t,10);if(t in e){if(0===t)break}else e[t]=[s,n]}const n=[];for(let t=0;t{t._responseOrigin=getResponseOrigin(e.url);if(!validateResponseStatus(e.status))throw createResponseStatusError(e.status,s);this._reader=e.body.getReader();this._headersCapability.resolve();const i=e.headers,{allowRangeRequests:n,suggestedLength:a}=validateRangeRequestCapabilities({responseHeaders:i,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=n;this._contentLength=a||this._contentLength;this._filename=extractFilenameFromHeader(i);!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new AbortException("Streaming is disabled."))})).catch(this._headersCapability.reject);this.onProgress=null}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._headersCapability.promise;const{value:t,done:e}=await this._reader.read();if(e)return{value:t,done:e};this._loaded+=t.byteLength;this.onProgress?.({loaded:this._loaded,total:this._contentLength});return{value:getArrayBuffer(t),done:!1}}cancel(t){this._reader?.cancel(t);this._abortController.abort()}}class PDFFetchStreamRangeReader{constructor(t,e,i){this._stream=t;this._reader=null;this._loaded=0;const s=t.source;this._withCredentials=s.withCredentials||!1;this._readCapability=Promise.withResolvers();this._isStreamingSupported=!s.disableStream;this._abortController=new AbortController;const n=new Headers(t.headers);n.append("Range",`bytes=${e}-${i-1}`);const a=s.url;fetch(a,createFetchOptions(n,this._withCredentials,this._abortController)).then((e=>{const i=getResponseOrigin(e.url);if(i!==t._responseOrigin)throw new Error(`Expected range response-origin "${i}" to match "${t._responseOrigin}".`);if(!validateResponseStatus(e.status))throw createResponseStatusError(e.status,a);this._readCapability.resolve();this._reader=e.body.getReader()})).catch(this._readCapability.reject);this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();if(e)return{value:t,done:e};this._loaded+=t.byteLength;this.onProgress?.({loaded:this._loaded});return{value:getArrayBuffer(t),done:!1}}cancel(t){this._reader?.cancel(t);this._abortController.abort()}}class NetworkManager{_responseOrigin=null;constructor({url:t,httpHeaders:e,withCredentials:i}){this.url=t;this.isHttp=/^https?:/i.test(t);this.headers=createHeaders(this.isHttp,e);this.withCredentials=i||!1;this.currXhrId=0;this.pendingRequests=Object.create(null)}request(t){const e=new XMLHttpRequest,i=this.currXhrId++,s=this.pendingRequests[i]={xhr:e};e.open("GET",this.url);e.withCredentials=this.withCredentials;for(const[t,i]of this.headers)e.setRequestHeader(t,i);if(this.isHttp&&"begin"in t&&"end"in t){e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`);s.expectedStatus=206}else s.expectedStatus=200;e.responseType="arraybuffer";assert(t.onError,"Expected `onError` callback to be provided.");e.onerror=()=>{t.onError(e.status)};e.onreadystatechange=this.onStateChange.bind(this,i);e.onprogress=this.onProgress.bind(this,i);s.onHeadersReceived=t.onHeadersReceived;s.onDone=t.onDone;s.onError=t.onError;s.onProgress=t.onProgress;e.send(null);return i}onProgress(t,e){const i=this.pendingRequests[t];i&&i.onProgress?.(e)}onStateChange(t,e){const i=this.pendingRequests[t];if(!i)return;const s=i.xhr;if(s.readyState>=2&&i.onHeadersReceived){i.onHeadersReceived();delete i.onHeadersReceived}if(4!==s.readyState)return;if(!(t in this.pendingRequests))return;delete this.pendingRequests[t];if(0===s.status&&this.isHttp){i.onError(s.status);return}const n=s.status||200;if(!(200===n&&206===i.expectedStatus)&&n!==i.expectedStatus){i.onError(s.status);return}const a=function network_getArrayBuffer(t){const e=t.response;return"string"!=typeof e?e:stringToBytes(e).buffer}(s);if(206===n){const t=s.getResponseHeader("Content-Range"),e=/bytes (\d+)-(\d+)\/(\d+)/.exec(t);if(e)i.onDone({begin:parseInt(e[1],10),chunk:a});else{warn('Missing or invalid "Content-Range" header.');i.onError(0)}}else a?i.onDone({begin:0,chunk:a}):i.onError(s.status)}getRequestXhr(t){return this.pendingRequests[t].xhr}isPendingRequest(t){return t in this.pendingRequests}abortRequest(t){const e=this.pendingRequests[t].xhr;delete this.pendingRequests[t];e.abort()}}class PDFNetworkStream{constructor(t){this._source=t;this._manager=new NetworkManager(t);this._rangeChunkSize=t.rangeChunkSize;this._fullRequestReader=null;this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(t){const e=this._rangeRequestReaders.indexOf(t);e>=0&&this._rangeRequestReaders.splice(e,1)}getFullReader(){assert(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once.");this._fullRequestReader=new PDFNetworkStreamFullRequestReader(this._manager,this._source);return this._fullRequestReader}getRangeReader(t,e){const i=new PDFNetworkStreamRangeRequestReader(this._manager,t,e);i.onClosed=this._onRangeRequestReaderClosed.bind(this);this._rangeRequestReaders.push(i);return i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class PDFNetworkStreamFullRequestReader{constructor(t,e){this._manager=t;this._url=e.url;this._fullRequestId=t.request({onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)});this._headersCapability=Promise.withResolvers();this._disableRange=e.disableRange||!1;this._contentLength=e.length;this._rangeChunkSize=e.rangeChunkSize;this._rangeChunkSize||this._disableRange||(this._disableRange=!0);this._isStreamingSupported=!1;this._isRangeSupported=!1;this._cachedChunks=[];this._requests=[];this._done=!1;this._storedError=void 0;this._filename=null;this.onProgress=null}_onHeadersReceived(){const t=this._fullRequestId,e=this._manager.getRequestXhr(t);this._manager._responseOrigin=getResponseOrigin(e.responseURL);const i=e.getAllResponseHeaders(),s=new Headers(i?i.trimStart().replace(/[^\S ]+$/,"").split(/[\r\n]+/).map((t=>{const[e,...i]=t.split(": ");return[e,i.join(": ")]})):[]),{allowRangeRequests:n,suggestedLength:a}=validateRangeRequestCapabilities({responseHeaders:s,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});n&&(this._isRangeSupported=!0);this._contentLength=a||this._contentLength;this._filename=extractFilenameFromHeader(s);this._isRangeSupported&&this._manager.abortRequest(t);this._headersCapability.resolve()}_onDone(t){if(t)if(this._requests.length>0){this._requests.shift().resolve({value:t.chunk,done:!1})}else this._cachedChunks.push(t.chunk);this._done=!0;if(!(this._cachedChunks.length>0)){for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(t){this._storedError=createResponseStatusError(t,this._url);this._headersCapability.reject(this._storedError);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0;this._cachedChunks.length=0}_onProgress(t){this.onProgress?.({loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})}get filename(){return this._filename}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}get contentLength(){return this._contentLength}get headersReady(){return this._headersCapability.promise}async read(){await this._headersCapability.promise;if(this._storedError)throw this._storedError;if(this._cachedChunks.length>0){return{value:this._cachedChunks.shift(),done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;this._headersCapability.reject(t);for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0;this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId);this._fullRequestReader=null}}class PDFNetworkStreamRangeRequestReader{constructor(t,e,i){this._manager=t;this._url=t.url;this._requestId=t.request({begin:e,end:i,onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)});this._requests=[];this._queuedChunk=null;this._done=!1;this._storedError=void 0;this.onProgress=null;this.onClosed=null}_onHeadersReceived(){const t=getResponseOrigin(this._manager.getRequestXhr(this._requestId)?.responseURL);if(t!==this._manager._responseOrigin){this._storedError=new Error(`Expected range response-origin "${t}" to match "${this._manager._responseOrigin}".`);this._onError(0)}}_close(){this.onClosed?.(this)}_onDone(t){const e=t.chunk;if(this._requests.length>0){this._requests.shift().resolve({value:e,done:!1})}else this._queuedChunk=e;this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0;this._close()}_onError(t){this._storedError??=createResponseStatusError(t,this._url);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0;this._queuedChunk=null}_onProgress(t){this.isStreamingSupported||this.onProgress?.({loaded:t.loaded})}get isStreamingSupported(){return!1}async read(){if(this._storedError)throw this._storedError;if(null!==this._queuedChunk){const t=this._queuedChunk;this._queuedChunk=null;return{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0;this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId);this._close()}}const Mt=/^[a-z][a-z0-9\-+.]+:/i;class PDFNodeStream{constructor(t){this.source=t;this.url=function parseUrlOrPath(t){if(Mt.test(t))return new URL(t);const e=process.getBuiltinModule("url");return new URL(e.pathToFileURL(t))}(t.url);assert("file:"===this.url.protocol,"PDFNodeStream only supports file:// URLs.");this._fullRequestReader=null;this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){assert(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once.");this._fullRequestReader=new PDFNodeStreamFsFullReader(this);return this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new PDFNodeStreamFsRangeReader(this,t,e);this._rangeRequestReaders.push(i);return i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class PDFNodeStreamFsFullReader{constructor(t){this._url=t.url;this._done=!1;this._storedError=null;this.onProgress=null;const e=t.source;this._contentLength=e.length;this._loaded=0;this._filename=null;this._disableRange=e.disableRange||!1;this._rangeChunkSize=e.rangeChunkSize;this._rangeChunkSize||this._disableRange||(this._disableRange=!0);this._isStreamingSupported=!e.disableStream;this._isRangeSupported=!e.disableRange;this._readableStream=null;this._readCapability=Promise.withResolvers();this._headersCapability=Promise.withResolvers();const i=process.getBuiltinModule("fs");i.promises.lstat(this._url).then((t=>{this._contentLength=t.size;this._setReadableStream(i.createReadStream(this._url));this._headersCapability.resolve()}),(t=>{"ENOENT"===t.code&&(t=new MissingPDFException(`Missing PDF "${this._url}".`));this._storedError=t;this._headersCapability.reject(t)}))}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;if(this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();if(null===t){this._readCapability=Promise.withResolvers();return this.read()}this._loaded+=t.length;this.onProgress?.({loaded:this._loaded,total:this._contentLength});return{value:new Uint8Array(t).buffer,done:!1}}cancel(t){this._readableStream?this._readableStream.destroy(t):this._error(t)}_error(t){this._storedError=t;this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t;t.on("readable",(()=>{this._readCapability.resolve()}));t.on("end",(()=>{t.destroy();this._done=!0;this._readCapability.resolve()}));t.on("error",(t=>{this._error(t)}));!this._isStreamingSupported&&this._isRangeSupported&&this._error(new AbortException("streaming is disabled"));this._storedError&&this._readableStream.destroy(this._storedError)}}class PDFNodeStreamFsRangeReader{constructor(t,e,i){this._url=t.url;this._done=!1;this._storedError=null;this.onProgress=null;this._loaded=0;this._readableStream=null;this._readCapability=Promise.withResolvers();const s=t.source;this._isStreamingSupported=!s.disableStream;const n=process.getBuiltinModule("fs");this._setReadableStream(n.createReadStream(this._url,{start:e,end:i-1}))}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;if(this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();if(null===t){this._readCapability=Promise.withResolvers();return this.read()}this._loaded+=t.length;this.onProgress?.({loaded:this._loaded});return{value:new Uint8Array(t).buffer,done:!1}}cancel(t){this._readableStream?this._readableStream.destroy(t):this._error(t)}_error(t){this._storedError=t;this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t;t.on("readable",(()=>{this._readCapability.resolve()}));t.on("end",(()=>{t.destroy();this._done=!0;this._readCapability.resolve()}));t.on("error",(t=>{this._error(t)}));this._storedError&&this._readableStream.destroy(this._storedError)}}const Pt=30;class TextLayer{#Si=Promise.withResolvers();#pt=null;#Ci=!1;#Ti=!!globalThis.FontInspector?.enabled;#Mi=null;#Pi=null;#Di=0;#ki=0;#Ri=null;#Ii=null;#Fi=0;#Li=0;#Oi=Object.create(null);#Ni=[];#Bi=null;#Hi=[];#zi=new WeakMap;#Ui=null;static#Gi=new Map;static#$i=new Map;static#Vi=new WeakMap;static#ji=null;static#Wi=new Set;constructor({textContentSource:t,container:e,viewport:i}){if(t instanceof ReadableStream)this.#Bi=t;else{if("object"!=typeof t)throw new Error('No "textContentSource" parameter specified.');this.#Bi=new ReadableStream({start(e){e.enqueue(t);e.close()}})}this.#pt=this.#Ii=e;this.#Li=i.scale*(globalThis.devicePixelRatio||1);this.#Fi=i.rotation;this.#Pi={div:null,properties:null,ctx:null};const{pageWidth:s,pageHeight:n,pageX:a,pageY:r}=i.rawDims;this.#Ui=[1,0,0,-1,-a,r+n];this.#ki=s;this.#Di=n;TextLayer.#qi();setLayerDimensions(e,i);this.#Si.promise.finally((()=>{TextLayer.#Wi.delete(this);this.#Pi=null;this.#Oi=null})).catch((()=>{}))}static get fontFamilyMap(){const{isWindows:t,isFirefox:e}=util_FeatureTest.platform;return shadow(this,"fontFamilyMap",new Map([["sans-serif",(t&&e?"Calibri, ":"")+"sans-serif"],["monospace",(t&&e?"Lucida Console, ":"")+"monospace"]]))}render(){const pump=()=>{this.#Ri.read().then((({value:t,done:e})=>{if(e)this.#Si.resolve();else{this.#Mi??=t.lang;Object.assign(this.#Oi,t.styles);this.#Xi(t.items);pump()}}),this.#Si.reject)};this.#Ri=this.#Bi.getReader();TextLayer.#Wi.add(this);pump();return this.#Si.promise}update({viewport:t,onBefore:e=null}){const i=t.scale*(globalThis.devicePixelRatio||1),s=t.rotation;if(s!==this.#Fi){e?.();this.#Fi=s;setLayerDimensions(this.#Ii,{rotation:s})}if(i!==this.#Li){e?.();this.#Li=i;const t={div:null,properties:null,ctx:TextLayer.#Ki(this.#Mi)};for(const e of this.#Hi){t.properties=this.#zi.get(e);t.div=e;this.#Yi(t)}}}cancel(){const t=new AbortException("TextLayer task cancelled.");this.#Ri?.cancel(t).catch((()=>{}));this.#Ri=null;this.#Si.reject(t)}get textDivs(){return this.#Hi}get textContentItemsStr(){return this.#Ni}#Xi(t){if(this.#Ci)return;this.#Pi.ctx??=TextLayer.#Ki(this.#Mi);const e=this.#Hi,i=this.#Ni;for(const s of t){if(e.length>1e5){warn("Ignoring additional textDivs for performance reasons.");this.#Ci=!0;return}if(void 0!==s.str){i.push(s.str);this.#Qi(s)}else if("beginMarkedContentProps"===s.type||"beginMarkedContent"===s.type){const t=this.#pt;this.#pt=document.createElement("span");this.#pt.classList.add("markedContent");null!==s.id&&this.#pt.setAttribute("id",`${s.id}`);t.append(this.#pt)}else"endMarkedContent"===s.type&&(this.#pt=this.#pt.parentNode)}}#Qi(t){const e=document.createElement("span"),i={angle:0,canvasWidth:0,hasText:""!==t.str,hasEOL:t.hasEOL,fontSize:0};this.#Hi.push(e);const s=Util.transform(this.#Ui,t.transform);let n=Math.atan2(s[1],s[0]);const a=this.#Oi[t.fontName];a.vertical&&(n+=Math.PI/2);let r=this.#Ti&&a.fontSubstitution||a.fontFamily;r=TextLayer.fontFamilyMap.get(r)||r;const o=Math.hypot(s[2],s[3]),l=o*TextLayer.#Ji(r,this.#Mi);let h,d;if(0===n){h=s[4];d=s[5]-l}else{h=s[4]+l*Math.sin(n);d=s[5]-l*Math.cos(n)}const c="calc(var(--scale-factor)*",u=e.style;if(this.#pt===this.#Ii){u.left=`${(100*h/this.#ki).toFixed(2)}%`;u.top=`${(100*d/this.#Di).toFixed(2)}%`}else{u.left=`${c}${h.toFixed(2)}px)`;u.top=`${c}${d.toFixed(2)}px)`}u.fontSize=`${c}${(TextLayer.#ji*o).toFixed(2)}px)`;u.fontFamily=r;i.fontSize=o;e.setAttribute("role","presentation");e.textContent=t.str;e.dir=t.dir;this.#Ti&&(e.dataset.fontName=a.fontSubstitutionLoadedName||t.fontName);0!==n&&(i.angle=n*(180/Math.PI));let p=!1;if(t.str.length>1)p=!0;else if(" "!==t.str&&t.transform[0]!==t.transform[3]){const e=Math.abs(t.transform[0]),i=Math.abs(t.transform[3]);e!==i&&Math.max(e,i)/Math.min(e,i)>1.5&&(p=!0)}p&&(i.canvasWidth=a.vertical?t.height:t.width);this.#zi.set(e,i);this.#Pi.div=e;this.#Pi.properties=i;this.#Yi(this.#Pi);i.hasText&&this.#pt.append(e);if(i.hasEOL){const t=document.createElement("br");t.setAttribute("role","presentation");this.#pt.append(t)}}#Yi(t){const{div:e,properties:i,ctx:s}=t,{style:n}=e;let a="";TextLayer.#ji>1&&(a=`scale(${1/TextLayer.#ji})`);if(0!==i.canvasWidth&&i.hasText){const{fontFamily:t}=n,{canvasWidth:r,fontSize:o}=i;TextLayer.#Zi(s,o*this.#Li,t);const{width:l}=s.measureText(e.textContent);l>0&&(a=`scaleX(${r*this.#Li/l}) ${a}`)}0!==i.angle&&(a=`rotate(${i.angle}deg) ${a}`);a.length>0&&(n.transform=a)}static cleanup(){if(!(this.#Wi.size>0)){this.#Gi.clear();for(const{canvas:t}of this.#$i.values())t.remove();this.#$i.clear()}}static#Ki(t=null){let e=this.#$i.get(t||="");if(!e){const i=document.createElement("canvas");i.className="hiddenCanvasElement";i.lang=t;document.body.append(i);e=i.getContext("2d",{alpha:!1,willReadFrequently:!0});this.#$i.set(t,e);this.#Vi.set(e,{size:0,family:""})}return e}static#Zi(t,e,i){const s=this.#Vi.get(t);if(e!==s.size||i!==s.family){t.font=`${e}px ${i}`;s.size=e;s.family=i}}static#qi(){if(null!==this.#ji)return;const t=document.createElement("div");t.style.opacity=0;t.style.lineHeight=1;t.style.fontSize="1px";t.style.position="absolute";t.textContent="X";document.body.append(t);this.#ji=t.getBoundingClientRect().height;t.remove()}static#Ji(t,e){const i=this.#Gi.get(t);if(i)return i;const s=this.#Ki(e);s.canvas.width=s.canvas.height=Pt;this.#Zi(s,Pt,t);const n=s.measureText("");let a=n.fontBoundingBoxAscent,r=Math.abs(n.fontBoundingBoxDescent);if(a){const e=a/(a+r);this.#Gi.set(t,e);s.canvas.width=s.canvas.height=0;return e}s.strokeStyle="red";s.clearRect(0,0,Pt,Pt);s.strokeText("g",0,0);let o=s.getImageData(0,0,Pt,Pt).data;r=0;for(let t=o.length-1-3;t>=0;t-=4)if(o[t]>0){r=Math.ceil(t/4/Pt);break}s.clearRect(0,0,Pt,Pt);s.strokeText("A",0,Pt);o=s.getImageData(0,0,Pt,Pt).data;a=0;for(let t=0,e=o.length;t0){a=Pt-Math.floor(t/4/Pt);break}s.canvas.width=s.canvas.height=0;const l=a?a/(a+r):.8;this.#Gi.set(t,l);return l}}class XfaText{static textContent(t){const e=[],i={items:e,styles:Object.create(null)};!function walk(t){if(!t)return;let i=null;const s=t.name;if("#text"===s)i=t.value;else{if(!XfaText.shouldBuildText(s))return;t?.attributes?.textContent?i=t.attributes.textContent:t.value&&(i=t.value)}null!==i&&e.push({str:i});if(t.children)for(const e of t.children)walk(e)}(t);return i}static shouldBuildText(t){return!("textarea"===t||"input"===t||"option"===t||"select"===t)}}const Dt=65536,kt=e?class NodeCanvasFactory extends BaseCanvasFactory{_createCanvas(t,e){return process.getBuiltinModule("module").createRequire(import.meta.url)("@napi-rs/canvas").createCanvas(t,e)}}:class DOMCanvasFactory extends BaseCanvasFactory{constructor({ownerDocument:t=globalThis.document,enableHWA:e=!1}){super({enableHWA:e});this._document=t}_createCanvas(t,e){const i=this._document.createElement("canvas");i.width=t;i.height=e;return i}},Rt=e?class NodeCMapReaderFactory extends BaseCMapReaderFactory{async _fetch(t){return node_utils_fetchData(t)}}:DOMCMapReaderFactory,It=e?class NodeFilterFactory extends BaseFilterFactory{}:class DOMFilterFactory extends BaseFilterFactory{#ts;#es;#is;#ss;#ns;#as;#w=0;constructor({docId:t,ownerDocument:e=globalThis.document}){super();this.#ss=t;this.#ns=e}get#y(){return this.#es||=new Map}get#rs(){return this.#as||=new Map}get#os(){if(!this.#is){const t=this.#ns.createElement("div"),{style:e}=t;e.visibility="hidden";e.contain="strict";e.width=e.height=0;e.position="absolute";e.top=e.left=0;e.zIndex=-1;const i=this.#ns.createElementNS(it,"svg");i.setAttribute("width",0);i.setAttribute("height",0);this.#is=this.#ns.createElementNS(it,"defs");t.append(i);i.append(this.#is);this.#ns.body.append(t)}return this.#is}#ls(t){if(1===t.length){const e=t[0],i=new Array(256);for(let t=0;t<256;t++)i[t]=e[t]/255;const s=i.join(",");return[s,s,s]}const[e,i,s]=t,n=new Array(256),a=new Array(256),r=new Array(256);for(let t=0;t<256;t++){n[t]=e[t]/255;a[t]=i[t]/255;r[t]=s[t]/255}return[n.join(","),a.join(","),r.join(",")]}#hs(t){if(void 0===this.#ts){this.#ts="";const t=this.#ns.URL;t!==this.#ns.baseURI&&(isDataScheme(t)?warn('#createUrl: ignore "data:"-URL for performance reasons.'):this.#ts=t.split("#",1)[0])}return`url(${this.#ts}#${t})`}addFilter(t){if(!t)return"none";let e=this.#y.get(t);if(e)return e;const[i,s,n]=this.#ls(t),a=1===t.length?i:`${i}${s}${n}`;e=this.#y.get(a);if(e){this.#y.set(t,e);return e}const r=`g_${this.#ss}_transfer_map_${this.#w++}`,o=this.#hs(r);this.#y.set(t,o);this.#y.set(a,o);const l=this.#ds(r);this.#cs(i,s,n,l);return o}addHCMFilter(t,e){const i=`${t}-${e}`,s="base";let n=this.#rs.get(s);if(n?.key===i)return n.url;if(n){n.filter?.remove();n.key=i;n.url="none";n.filter=null}else{n={key:i,url:"none",filter:null};this.#rs.set(s,n)}if(!t||!e)return n.url;const a=this.#us(t);t=Util.makeHexColor(...a);const r=this.#us(e);e=Util.makeHexColor(...r);this.#os.style.color="";if("#000000"===t&&"#ffffff"===e||t===e)return n.url;const o=new Array(256);for(let t=0;t<=255;t++){const e=t/255;o[t]=e<=.03928?e/12.92:((e+.055)/1.055)**2.4}const l=o.join(","),h=`g_${this.#ss}_hcm_filter`,d=n.filter=this.#ds(h);this.#cs(l,l,l,d);this.#ps(d);const getSteps=(t,e)=>{const i=a[t]/255,s=r[t]/255,n=new Array(e+1);for(let t=0;t<=e;t++)n[t]=i+t/e*(s-i);return n.join(",")};this.#cs(getSteps(0,5),getSteps(1,5),getSteps(2,5),d);n.url=this.#hs(h);return n.url}addAlphaFilter(t){let e=this.#y.get(t);if(e)return e;const[i]=this.#ls([t]),s=`alpha_${i}`;e=this.#y.get(s);if(e){this.#y.set(t,e);return e}const n=`g_${this.#ss}_alpha_map_${this.#w++}`,a=this.#hs(n);this.#y.set(t,a);this.#y.set(s,a);const r=this.#ds(n);this.#gs(i,r);return a}addLuminosityFilter(t){let e,i,s=this.#y.get(t||"luminosity");if(s)return s;if(t){[e]=this.#ls([t]);i=`luminosity_${e}`}else i="luminosity";s=this.#y.get(i);if(s){this.#y.set(t,s);return s}const n=`g_${this.#ss}_luminosity_map_${this.#w++}`,a=this.#hs(n);this.#y.set(t,a);this.#y.set(i,a);const r=this.#ds(n);this.#ms(r);t&&this.#gs(e,r);return a}addHighlightHCMFilter(t,e,i,s,n){const a=`${e}-${i}-${s}-${n}`;let r=this.#rs.get(t);if(r?.key===a)return r.url;if(r){r.filter?.remove();r.key=a;r.url="none";r.filter=null}else{r={key:a,url:"none",filter:null};this.#rs.set(t,r)}if(!e||!i)return r.url;const[o,l]=[e,i].map(this.#us.bind(this));let h=Math.round(.2126*o[0]+.7152*o[1]+.0722*o[2]),d=Math.round(.2126*l[0]+.7152*l[1]+.0722*l[2]),[c,u]=[s,n].map(this.#us.bind(this));d{const s=new Array(256),n=(d-h)/i,a=t/255,r=(e-t)/(255*i);let o=0;for(let t=0;t<=i;t++){const e=Math.round(h+t*n),i=a+t*r;for(let t=o;t<=e;t++)s[t]=i;o=e+1}for(let t=o;t<256;t++)s[t]=s[o-1];return s.join(",")},p=`g_${this.#ss}_hcm_${t}_filter`,g=r.filter=this.#ds(p);this.#ps(g);this.#cs(getSteps(c[0],u[0],5),getSteps(c[1],u[1],5),getSteps(c[2],u[2],5),g);r.url=this.#hs(p);return r.url}destroy(t=!1){if(!t||!this.#as?.size){this.#is?.parentNode.parentNode.remove();this.#is=null;this.#es?.clear();this.#es=null;this.#as?.clear();this.#as=null;this.#w=0}}#ms(t){const e=this.#ns.createElementNS(it,"feColorMatrix");e.setAttribute("type","matrix");e.setAttribute("values","0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0");t.append(e)}#ps(t){const e=this.#ns.createElementNS(it,"feColorMatrix");e.setAttribute("type","matrix");e.setAttribute("values","0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0");t.append(e)}#ds(t){const e=this.#ns.createElementNS(it,"filter");e.setAttribute("color-interpolation-filters","sRGB");e.setAttribute("id",t);this.#os.append(e);return e}#fs(t,e,i){const s=this.#ns.createElementNS(it,e);s.setAttribute("type","discrete");s.setAttribute("tableValues",i);t.append(s)}#cs(t,e,i,s){const n=this.#ns.createElementNS(it,"feComponentTransfer");s.append(n);this.#fs(n,"feFuncR",t);this.#fs(n,"feFuncG",e);this.#fs(n,"feFuncB",i)}#gs(t,e){const i=this.#ns.createElementNS(it,"feComponentTransfer");e.append(i);this.#fs(i,"feFuncA",t)}#us(t){this.#os.style.color=t;return getRGB(getComputedStyle(this.#os).getPropertyValue("color"))}},Ft=e?class NodeStandardFontDataFactory extends BaseStandardFontDataFactory{async _fetch(t){return node_utils_fetchData(t)}}:DOMStandardFontDataFactory;function getDocument(t={}){"string"==typeof t||t instanceof URL?t={url:t}:(t instanceof ArrayBuffer||ArrayBuffer.isView(t))&&(t={data:t});const i=new PDFDocumentLoadingTask,{docId:s}=i,n=t.url?function getUrlProp(t){if(t instanceof URL)return t.href;try{return new URL(t,window.location).href}catch{if(e&&"string"==typeof t)return t}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}(t.url):null,a=t.data?function getDataProp(t){if(e&&"undefined"!=typeof Buffer&&t instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(t instanceof Uint8Array&&t.byteLength===t.buffer.byteLength)return t;if("string"==typeof t)return stringToBytes(t);if(t instanceof ArrayBuffer||ArrayBuffer.isView(t)||"object"==typeof t&&!isNaN(t?.length))return new Uint8Array(t);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}(t.data):null,r=t.httpHeaders||null,o=!0===t.withCredentials,l=t.password??null,h=t.range instanceof PDFDataRangeTransport?t.range:null,d=Number.isInteger(t.rangeChunkSize)&&t.rangeChunkSize>0?t.rangeChunkSize:Dt;let c=t.worker instanceof PDFWorker?t.worker:null;const u=t.verbosity,p="string"!=typeof t.docBaseUrl||isDataScheme(t.docBaseUrl)?null:t.docBaseUrl,g="string"==typeof t.cMapUrl?t.cMapUrl:null,m=!1!==t.cMapPacked,f=t.CMapReaderFactory||Rt,b="string"==typeof t.standardFontDataUrl?t.standardFontDataUrl:null,A=t.StandardFontDataFactory||Ft,w=!0!==t.stopAtErrors,v=Number.isInteger(t.maxImageSize)&&t.maxImageSize>-1?t.maxImageSize:-1,y=!1!==t.isEvalSupported,x="boolean"==typeof t.isOffscreenCanvasSupported?t.isOffscreenCanvasSupported:!e,_="boolean"==typeof t.isImageDecoderSupported?t.isImageDecoderSupported:!e&&(util_FeatureTest.platform.isFirefox||!globalThis.chrome),E=Number.isInteger(t.canvasMaxAreaInBytes)?t.canvasMaxAreaInBytes:-1,S="boolean"==typeof t.disableFontFace?t.disableFontFace:e,C=!0===t.fontExtraProperties,T=!0===t.enableXfa,M=t.ownerDocument||globalThis.document,P=!0===t.disableRange,D=!0===t.disableStream,k=!0===t.disableAutoFetch,R=!0===t.pdfBug,I=t.CanvasFactory||kt,F=t.FilterFactory||It,L=!0===t.enableHWA,O=h?h.length:t.length??NaN,N="boolean"==typeof t.useSystemFonts?t.useSystemFonts:!e&&!S,B="boolean"==typeof t.useWorkerFetch?t.useWorkerFetch:f===DOMCMapReaderFactory&&A===DOMStandardFontDataFactory&&g&&b&&isValidFetchUrl(g,document.baseURI)&&isValidFetchUrl(b,document.baseURI);setVerbosityLevel(u);const H={canvasFactory:new I({ownerDocument:M,enableHWA:L}),filterFactory:new F({docId:s,ownerDocument:M}),cMapReaderFactory:B?null:new f({baseUrl:g,isCompressed:m}),standardFontDataFactory:B?null:new A({baseUrl:b})};if(!c){const t={verbosity:u,port:GlobalWorkerOptions.workerPort};c=t.port?PDFWorker.fromPort(t):new PDFWorker(t);i._worker=c}const z={docId:s,apiVersion:"4.10.38",data:a,password:l,disableAutoFetch:k,rangeChunkSize:d,length:O,docBaseUrl:p,enableXfa:T,evaluatorOptions:{maxImageSize:v,disableFontFace:S,ignoreErrors:w,isEvalSupported:y,isOffscreenCanvasSupported:x,isImageDecoderSupported:_,canvasMaxAreaInBytes:E,fontExtraProperties:C,useSystemFonts:N,cMapUrl:B?g:null,standardFontDataUrl:B?b:null}},U={disableFontFace:S,fontExtraProperties:C,ownerDocument:M,pdfBug:R,styleElement:null,loadingParams:{disableAutoFetch:k,enableXfa:T}};c.promise.then((function(){if(i.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const t=c.messageHandler.sendWithPromise("GetDocRequest",z,a?[a.buffer]:null);let l;if(h)l=new PDFDataTransportStream(h,{disableRange:P,disableStream:D});else if(!a){if(!n)throw new Error("getDocument - no `url` parameter provided.");let t;if(e)if(isValidFetchUrl(n)){if("undefined"==typeof fetch||"undefined"==typeof Response||!("body"in Response.prototype))throw new Error("getDocument - the Fetch API was disabled in Node.js, see `--no-experimental-fetch`.");t=PDFFetchStream}else t=PDFNodeStream;else t=isValidFetchUrl(n)?PDFFetchStream:PDFNetworkStream;l=new t({url:n,length:O,httpHeaders:r,withCredentials:o,rangeChunkSize:d,disableRange:P,disableStream:D})}return t.then((t=>{if(i.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const e=new MessageHandler(s,t,c.port),n=new WorkerTransport(e,i,l,U,H);i._transport=n;e.send("Ready",null)}))})).catch(i._capability.reject);return i}function isRefProxy(t){return"object"==typeof t&&Number.isInteger(t?.num)&&t.num>=0&&Number.isInteger(t?.gen)&&t.gen>=0}class PDFDocumentLoadingTask{static#ss=0;constructor(){this._capability=Promise.withResolvers();this._transport=null;this._worker=null;this.docId="d"+PDFDocumentLoadingTask.#ss++;this.destroyed=!1;this.onPassword=null;this.onProgress=null}get promise(){return this._capability.promise}async destroy(){this.destroyed=!0;try{this._worker?.port&&(this._worker._pendingDestroy=!0);await(this._transport?.destroy())}catch(t){this._worker?.port&&delete this._worker._pendingDestroy;throw t}this._transport=null;this._worker?.destroy();this._worker=null}}class PDFDataRangeTransport{constructor(t,e,i=!1,s=null){this.length=t;this.initialData=e;this.progressiveDone=i;this.contentDispositionFilename=s;this._rangeListeners=[];this._progressListeners=[];this._progressiveReadListeners=[];this._progressiveDoneListeners=[];this._readyCapability=Promise.withResolvers()}addRangeListener(t){this._rangeListeners.push(t)}addProgressListener(t){this._progressListeners.push(t)}addProgressiveReadListener(t){this._progressiveReadListeners.push(t)}addProgressiveDoneListener(t){this._progressiveDoneListeners.push(t)}onDataRange(t,e){for(const i of this._rangeListeners)i(t,e)}onDataProgress(t,e){this._readyCapability.promise.then((()=>{for(const i of this._progressListeners)i(t,e)}))}onDataProgressiveRead(t){this._readyCapability.promise.then((()=>{for(const e of this._progressiveReadListeners)e(t)}))}onDataProgressiveDone(){this._readyCapability.promise.then((()=>{for(const t of this._progressiveDoneListeners)t()}))}transportReady(){this._readyCapability.resolve()}requestDataRange(t,e){unreachable("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class PDFDocumentProxy{constructor(t,e){this._pdfInfo=t;this._transport=e}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return shadow(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(t){return this._transport.getPage(t)}getPageIndex(t){return this._transport.getPageIndex(t)}getDestinations(){return this._transport.getDestinations()}getDestination(t){return this._transport.getDestination(t)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getOptionalContentConfig(e)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(t=!1){return this._transport.startCleanup(t||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}cachedPageNumber(t){return this._transport.cachedPageNumber(t)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}class PDFPageProxy{#bs=null;#As=!1;constructor(t,e,i,s=!1){this._pageIndex=t;this._pageInfo=e;this._transport=i;this._stats=s?new StatTimer:null;this._pdfBug=s;this.commonObjs=i.commonObjs;this.objs=new PDFObjects;this._maybeCleanupAfterRender=!1;this._intentStates=new Map;this.destroyed=!1}get pageNumber(){return this._pageIndex+1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:t,rotation:e=this.rotate,offsetX:i=0,offsetY:s=0,dontFlip:n=!1}={}){return new PageViewport({viewBox:this.view,userUnit:this.userUnit,scale:t,rotation:e,offsetX:i,offsetY:s,dontFlip:n})}getAnnotations({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getAnnotations(this._pageIndex,e)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return shadow(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:t,viewport:e,intent:i="display",annotationMode:s=p.ENABLE,transform:n=null,background:a=null,optionalContentConfigPromise:r=null,annotationCanvasMap:l=null,pageColors:h=null,printAnnotationStorage:d=null,isEditing:c=!1}){this._stats?.time("Overall");const u=this._transport.getRenderingIntent(i,s,d,c),{renderingIntent:g,cacheKey:m}=u;this.#As=!1;this.#ws();r||=this._transport.getOptionalContentConfig(g);let f=this._intentStates.get(m);if(!f){f=Object.create(null);this._intentStates.set(m,f)}if(f.streamReaderCancelTimeout){clearTimeout(f.streamReaderCancelTimeout);f.streamReaderCancelTimeout=null}const b=!!(g&o);if(!f.displayReadyCapability){f.displayReadyCapability=Promise.withResolvers();f.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null};this._stats?.time("Page Request");this._pumpOperatorList(u)}const complete=t=>{f.renderTasks.delete(A);(this._maybeCleanupAfterRender||b)&&(this.#As=!0);this.#vs(!b);if(t){A.capability.reject(t);this._abortOperatorList({intentState:f,reason:t instanceof Error?t:new Error(t)})}else A.capability.resolve();if(this._stats){this._stats.timeEnd("Rendering");this._stats.timeEnd("Overall");globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats)}},A=new InternalRenderTask({callback:complete,params:{canvasContext:t,viewport:e,transform:n,background:a},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:l,operatorList:f.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!b,pdfBug:this._pdfBug,pageColors:h});(f.renderTasks||=new Set).add(A);const w=A.task;Promise.all([f.displayReadyCapability.promise,r]).then((([t,e])=>{if(this.destroyed)complete();else{this._stats?.time("Rendering");if(!(e.renderingIntent&g))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");A.initializeGraphics({transparency:t,optionalContentConfig:e});A.operatorListChanged()}})).catch(complete);return w}getOperatorList({intent:t="display",annotationMode:e=p.ENABLE,printAnnotationStorage:i=null,isEditing:s=!1}={}){const n=this._transport.getRenderingIntent(t,e,i,s,!0);let a,r=this._intentStates.get(n.cacheKey);if(!r){r=Object.create(null);this._intentStates.set(n.cacheKey,r)}if(!r.opListReadCapability){a=Object.create(null);a.operatorListChanged=function operatorListChanged(){if(r.operatorList.lastChunk){r.opListReadCapability.resolve(r.operatorList);r.renderTasks.delete(a)}};r.opListReadCapability=Promise.withResolvers();(r.renderTasks||=new Set).add(a);r.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null};this._stats?.time("Page Request");this._pumpOperatorList(n)}return r.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=!1,disableNormalization:e=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,includeMarkedContent:!0===t,disableNormalization:!0===e},{highWaterMark:100,size:t=>t.items.length})}getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then((t=>XfaText.textContent(t)));const e=this.streamTextContent(t);return new Promise((function(t,i){const s=e.getReader(),n={items:[],styles:Object.create(null),lang:null};!function pump(){s.read().then((function({value:e,done:i}){if(i)t(n);else{n.lang??=e.lang;Object.assign(n.styles,e.styles);n.items.push(...e.items);pump()}}),i)}()}))}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const t=[];for(const e of this._intentStates.values()){this._abortOperatorList({intentState:e,reason:new Error("Page was destroyed."),force:!0});if(!e.opListReadCapability)for(const i of e.renderTasks){t.push(i.completed);i.cancel()}}this.objs.clear();this.#As=!1;this.#ws();return Promise.all(t)}cleanup(t=!1){this.#As=!0;const e=this.#vs(!1);t&&e&&(this._stats&&=new StatTimer);return e}#vs(t=!1){this.#ws();if(!this.#As||this.destroyed)return!1;if(t){this.#bs=setTimeout((()=>{this.#bs=null;this.#vs(!1)}),5e3);return!1}for(const{renderTasks:t,operatorList:e}of this._intentStates.values())if(t.size>0||!e.lastChunk)return!1;this._intentStates.clear();this.objs.clear();this.#As=!1;return!0}#ws(){if(this.#bs){clearTimeout(this.#bs);this.#bs=null}}_startRenderPage(t,e){const i=this._intentStates.get(e);if(i){this._stats?.timeEnd("Page Request");i.displayReadyCapability?.resolve(t)}}_renderPageChunk(t,e){for(let i=0,s=t.length;i{r.read().then((({value:t,done:e})=>{if(e)o.streamReader=null;else if(!this._transport.destroyed){this._renderPageChunk(t,o);pump()}}),(t=>{o.streamReader=null;if(!this._transport.destroyed){if(o.operatorList){o.operatorList.lastChunk=!0;for(const t of o.renderTasks)t.operatorListChanged();this.#vs(!0)}if(o.displayReadyCapability)o.displayReadyCapability.reject(t);else{if(!o.opListReadCapability)throw t;o.opListReadCapability.reject(t)}}}))};pump()}_abortOperatorList({intentState:t,reason:e,force:i=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout){clearTimeout(t.streamReaderCancelTimeout);t.streamReaderCancelTimeout=null}if(!i){if(t.renderTasks.size>0)return;if(e instanceof RenderingCancelledException){let i=100;e.extraDelay>0&&e.extraDelay<1e3&&(i+=e.extraDelay);t.streamReaderCancelTimeout=setTimeout((()=>{t.streamReaderCancelTimeout=null;this._abortOperatorList({intentState:t,reason:e,force:!0})}),i);return}}t.streamReader.cancel(new AbortException(e.message)).catch((()=>{}));t.streamReader=null;if(!this._transport.destroyed){for(const[e,i]of this._intentStates)if(i===t){this._intentStates.delete(e);break}this.cleanup()}}}get stats(){return this._stats}}class LoopbackPort{#ys=new Map;#xs=Promise.resolve();postMessage(t,e){const i={data:structuredClone(t,e?{transfer:e}:null)};this.#xs.then((()=>{for(const[t]of this.#ys)t.call(this,i)}))}addEventListener(t,e,i=null){let s=null;if(i?.signal instanceof AbortSignal){const{signal:n}=i;if(n.aborted){warn("LoopbackPort - cannot use an `aborted` signal.");return}const onAbort=()=>this.removeEventListener(t,e);s=()=>n.removeEventListener("abort",onAbort);n.addEventListener("abort",onAbort)}this.#ys.set(e,s)}removeEventListener(t,e){const i=this.#ys.get(e);i?.();this.#ys.delete(e)}terminate(){for(const[,t]of this.#ys)t?.();this.#ys.clear()}}class PDFWorker{static#_s=0;static#Es=!1;static#Ss;static{if(e){this.#Es=!0;GlobalWorkerOptions.workerSrc||="./pdf.worker.mjs"}this._isSameOrigin=(t,e)=>{let i;try{i=new URL(t);if(!i.origin||"null"===i.origin)return!1}catch{return!1}const s=new URL(e,i);return i.origin===s.origin};this._createCDNWrapper=t=>{const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))}}constructor({name:t=null,port:e=null,verbosity:i=getVerbosityLevel()}={}){this.name=t;this.destroyed=!1;this.verbosity=i;this._readyCapability=Promise.withResolvers();this._port=null;this._webWorker=null;this._messageHandler=null;if(e){if(PDFWorker.#Ss?.has(e))throw new Error("Cannot use more than one PDFWorker per port.");(PDFWorker.#Ss||=new WeakMap).set(e,this);this._initializeFromPort(e)}else this._initialize()}get promise(){return this._readyCapability.promise}#Cs(){this._readyCapability.resolve();this._messageHandler.send("configure",{verbosity:this.verbosity})}get port(){return this._port}get messageHandler(){return this._messageHandler}_initializeFromPort(t){this._port=t;this._messageHandler=new MessageHandler("main","worker",t);this._messageHandler.on("ready",(function(){}));this.#Cs()}_initialize(){if(PDFWorker.#Es||PDFWorker.#Ts){this._setupFakeWorker();return}let{workerSrc:t}=PDFWorker;try{PDFWorker._isSameOrigin(window.location.href,t)||(t=PDFWorker._createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),i=new MessageHandler("main","worker",e),terminateEarly=()=>{s.abort();i.destroy();e.terminate();this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()},s=new AbortController;e.addEventListener("error",(()=>{this._webWorker||terminateEarly()}),{signal:s.signal});i.on("test",(t=>{s.abort();if(!this.destroyed&&t){this._messageHandler=i;this._port=e;this._webWorker=e;this.#Cs()}else terminateEarly()}));i.on("ready",(t=>{s.abort();if(this.destroyed)terminateEarly();else try{sendTest()}catch{this._setupFakeWorker()}}));const sendTest=()=>{const t=new Uint8Array;i.send("test",t,[t.buffer])};sendTest();return}catch{info("The worker has been disabled.")}this._setupFakeWorker()}_setupFakeWorker(){if(!PDFWorker.#Es){warn("Setting up fake worker.");PDFWorker.#Es=!0}PDFWorker._setupFakeWorkerGlobal.then((t=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}const e=new LoopbackPort;this._port=e;const i="fake"+PDFWorker.#_s++,s=new MessageHandler(i+"_worker",i,e);t.setup(s,e);this._messageHandler=new MessageHandler(i,i+"_worker",e);this.#Cs()})).catch((t=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${t.message}".`))}))}destroy(){this.destroyed=!0;this._webWorker?.terminate();this._webWorker=null;PDFWorker.#Ss?.delete(this._port);this._port=null;this._messageHandler?.destroy();this._messageHandler=null}static fromPort(t){if(!t?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");const e=this.#Ss?.get(t.port);if(e){if(e._pendingDestroy)throw new Error("PDFWorker.fromPort - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return e}return new PDFWorker(t)}static get workerSrc(){if(GlobalWorkerOptions.workerSrc)return GlobalWorkerOptions.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get#Ts(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return shadow(this,"_setupFakeWorkerGlobal",(async()=>{if(this.#Ts)return this.#Ts;return(await import(this.workerSrc)).WorkerMessageHandler})())}}class WorkerTransport{#Ms=new Map;#Ps=new Map;#Ds=new Map;#ks=new Map;#Rs=null;constructor(t,e,i,s,n){this.messageHandler=t;this.loadingTask=e;this.commonObjs=new PDFObjects;this.fontLoader=new FontLoader({ownerDocument:s.ownerDocument,styleElement:s.styleElement});this.loadingParams=s.loadingParams;this._params=s;this.canvasFactory=n.canvasFactory;this.filterFactory=n.filterFactory;this.cMapReaderFactory=n.cMapReaderFactory;this.standardFontDataFactory=n.standardFontDataFactory;this.destroyed=!1;this.destroyCapability=null;this._networkStream=i;this._fullReader=null;this._lastProgress=null;this.downloadInfoCapability=Promise.withResolvers();this.setupMessageHandler()}#Is(t,e=null){const i=this.#Ms.get(t);if(i)return i;const s=this.messageHandler.sendWithPromise(t,e);this.#Ms.set(t,s);return s}get annotationStorage(){return shadow(this,"annotationStorage",new AnnotationStorage)}getRenderingIntent(t,e=p.ENABLE,i=null,s=!1,n=!1){let g=r,m=rt;switch(t){case"any":g=a;break;case"display":break;case"print":g=o;break;default:warn(`getRenderingIntent - invalid intent: ${t}`)}const f=g&o&&i instanceof PrintAnnotationStorage?i:this.annotationStorage;switch(e){case p.DISABLE:g+=d;break;case p.ENABLE:break;case p.ENABLE_FORMS:g+=l;break;case p.ENABLE_STORAGE:g+=h;m=f.serializable;break;default:warn(`getRenderingIntent - invalid annotationMode: ${e}`)}s&&(g+=c);n&&(g+=u);const{ids:b,hash:A}=f.modifiedIds;return{renderingIntent:g,cacheKey:[g,m.hash,A].join("_"),annotationStorageSerializable:m,modifiedIds:b}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0;this.destroyCapability=Promise.withResolvers();this.#Rs?.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const e of this.#Ps.values())t.push(e._destroy());this.#Ps.clear();this.#Ds.clear();this.#ks.clear();this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();const e=this.messageHandler.sendWithPromise("Terminate",null);t.push(e);Promise.all(t).then((()=>{this.commonObjs.clear();this.fontLoader.clear();this.#Ms.clear();this.filterFactory.destroy();TextLayer.cleanup();this._networkStream?.cancelAllRequests(new AbortException("Worker was terminated."));this.messageHandler?.destroy();this.messageHandler=null;this.destroyCapability.resolve()}),this.destroyCapability.reject);return this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:t,loadingTask:e}=this;t.on("GetReader",((t,e)=>{assert(this._networkStream,"GetReader - no `IPDFStream` instance available.");this._fullReader=this._networkStream.getFullReader();this._fullReader.onProgress=t=>{this._lastProgress={loaded:t.loaded,total:t.total}};e.onPull=()=>{this._fullReader.read().then((function({value:t,done:i}){if(i)e.close();else{assert(t instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer.");e.enqueue(new Uint8Array(t),1,[t])}})).catch((t=>{e.error(t)}))};e.onCancel=t=>{this._fullReader.cancel(t);e.ready.catch((t=>{if(!this.destroyed)throw t}))}}));t.on("ReaderHeadersReady",(async t=>{await this._fullReader.headersReady;const{isStreamingSupported:i,isRangeSupported:s,contentLength:n}=this._fullReader;if(!i||!s){this._lastProgress&&e.onProgress?.(this._lastProgress);this._fullReader.onProgress=t=>{e.onProgress?.({loaded:t.loaded,total:t.total})}}return{isStreamingSupported:i,isRangeSupported:s,contentLength:n}}));t.on("GetRangeReader",((t,e)=>{assert(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");const i=this._networkStream.getRangeReader(t.begin,t.end);if(i){e.onPull=()=>{i.read().then((function({value:t,done:i}){if(i)e.close();else{assert(t instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer.");e.enqueue(new Uint8Array(t),1,[t])}})).catch((t=>{e.error(t)}))};e.onCancel=t=>{i.cancel(t);e.ready.catch((t=>{if(!this.destroyed)throw t}))}}else e.close()}));t.on("GetDoc",(({pdfInfo:t})=>{this._numPages=t.numPages;this._htmlForXfa=t.htmlForXfa;delete t.htmlForXfa;e._capability.resolve(new PDFDocumentProxy(t,this))}));t.on("DocException",(t=>{e._capability.reject(wrapReason(t))}));t.on("PasswordRequest",(t=>{this.#Rs=Promise.withResolvers();try{if(!e.onPassword)throw wrapReason(t);const updatePassword=t=>{t instanceof Error?this.#Rs.reject(t):this.#Rs.resolve({password:t})};e.onPassword(updatePassword,t.code)}catch(t){this.#Rs.reject(t)}return this.#Rs.promise}));t.on("DataLoaded",(t=>{e.onProgress?.({loaded:t.length,total:t.length});this.downloadInfoCapability.resolve(t)}));t.on("StartRenderPage",(t=>{if(this.destroyed)return;this.#Ps.get(t.pageIndex)._startRenderPage(t.transparency,t.cacheKey)}));t.on("commonobj",(([e,i,s])=>{if(this.destroyed)return null;if(this.commonObjs.has(e))return null;switch(i){case"Font":const{disableFontFace:n,fontExtraProperties:a,pdfBug:r}=this._params;if("error"in s){const t=s.error;warn(`Error during font loading: ${t}`);this.commonObjs.resolve(e,t);break}const o=r&&globalThis.FontInspector?.enabled?(t,e)=>globalThis.FontInspector.fontAdded(t,e):null,l=new FontFaceObject(s,{disableFontFace:n,fontExtraProperties:a,inspectFont:o});this.fontLoader.bind(l).catch((()=>t.sendWithPromise("FontFallback",{id:e}))).finally((()=>{!a&&l.data&&(l.data=null);this.commonObjs.resolve(e,l)}));break;case"CopyLocalImage":const{imageRef:h}=s;assert(h,"The imageRef must be defined.");for(const t of this.#Ps.values())for(const[,i]of t.objs)if(i?.ref===h){if(!i.dataLen)return null;this.commonObjs.resolve(e,structuredClone(i));return i.dataLen}break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(e,s);break;default:throw new Error(`Got unknown common object type ${i}`)}return null}));t.on("obj",(([t,e,i,s])=>{if(this.destroyed)return;const n=this.#Ps.get(e);if(!n.objs.has(t))if(0!==n._intentStates.size)switch(i){case"Image":n.objs.resolve(t,s);s?.dataLen>1e7&&(n._maybeCleanupAfterRender=!0);break;case"Pattern":n.objs.resolve(t,s);break;default:throw new Error(`Got unknown object type ${i}`)}else s?.bitmap?.close()}));t.on("DocProgress",(t=>{this.destroyed||e.onProgress?.({loaded:t.loaded,total:t.total})}));t.on("FetchBuiltInCMap",(async t=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.cMapReaderFactory)throw new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter.");return this.cMapReaderFactory.fetch(t)}));t.on("FetchStandardFontData",(async t=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.standardFontDataFactory)throw new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter.");return this.standardFontDataFactory.fetch(t)}))}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&warn("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:t,transfer:e}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:this._fullReader?.filename??null},e).finally((()=>{this.annotationStorage.resetModified()}))}getPage(t){if(!Number.isInteger(t)||t<=0||t>this._numPages)return Promise.reject(new Error("Invalid page request."));const e=t-1,i=this.#Ds.get(e);if(i)return i;const s=this.messageHandler.sendWithPromise("GetPage",{pageIndex:e}).then((i=>{if(this.destroyed)throw new Error("Transport destroyed");i.refStr&&this.#ks.set(i.refStr,t);const s=new PDFPageProxy(e,i,this,this._params.pdfBug);this.#Ps.set(e,s);return s}));this.#Ds.set(e,s);return s}getPageIndex(t){return isRefProxy(t)?this.messageHandler.sendWithPromise("GetPageIndex",{num:t.num,gen:t.gen}):Promise.reject(new Error("Invalid pageIndex request."))}getAnnotations(t,e){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:t,intent:e})}getFieldObjects(){return this.#Is("GetFieldObjects")}hasJSActions(){return this.#Is("HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(t){return"string"!=typeof t?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:t})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getDocJSActions(){return this.#Is("GetDocJSActions")}getPageJSActions(t){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:t})}getStructTree(t){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:t})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(t){return this.#Is("GetOptionalContentConfig").then((e=>new OptionalContentConfig(e,t)))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",e=this.#Ms.get(t);if(e)return e;const i=this.messageHandler.sendWithPromise(t,null).then((t=>({info:t[0],metadata:t[1]?new Metadata(t[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null})));this.#Ms.set(t,i);return i}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(t=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const t of this.#Ps.values()){if(!t.cleanup())throw new Error(`startCleanup: Page ${t.pageNumber} is currently rendering.`)}this.commonObjs.clear();t||this.fontLoader.clear();this.#Ms.clear();this.filterFactory.destroy(!0);TextLayer.cleanup()}}cachedPageNumber(t){if(!isRefProxy(t))return null;const e=0===t.gen?`${t.num}R`:`${t.num}R${t.gen}`;return this.#ks.get(e)??null}}const Lt=Symbol("INITIAL_DATA");class PDFObjects{#Fs=Object.create(null);#Ls(t){return this.#Fs[t]||={...Promise.withResolvers(),data:Lt}}get(t,e=null){if(e){const i=this.#Ls(t);i.promise.then((()=>e(i.data)));return null}const i=this.#Fs[t];if(!i||i.data===Lt)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return i.data}has(t){const e=this.#Fs[t];return!!e&&e.data!==Lt}delete(t){const e=this.#Fs[t];if(!e||e.data===Lt)return!1;delete this.#Fs[t];return!0}resolve(t,e=null){const i=this.#Ls(t);i.data=e;i.resolve()}clear(){for(const t in this.#Fs){const{data:e}=this.#Fs[t];e?.bitmap?.close()}this.#Fs=Object.create(null)}*[Symbol.iterator](){for(const t in this.#Fs){const{data:e}=this.#Fs[t];e!==Lt&&(yield[t,e])}}}class RenderTask{#Os=null;constructor(t){this.#Os=t;this.onContinue=null}get promise(){return this.#Os.capability.promise}cancel(t=0){this.#Os.cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=this.#Os.operatorList;if(!t)return!1;const{annotationCanvasMap:e}=this.#Os;return t.form||t.canvas&&e?.size>0}}class InternalRenderTask{#Ns=null;static#Bs=new WeakSet;constructor({callback:t,params:e,objs:i,commonObjs:s,annotationCanvasMap:n,operatorList:a,pageIndex:r,canvasFactory:o,filterFactory:l,useRequestAnimationFrame:h=!1,pdfBug:d=!1,pageColors:c=null}){this.callback=t;this.params=e;this.objs=i;this.commonObjs=s;this.annotationCanvasMap=n;this.operatorListIdx=null;this.operatorList=a;this._pageIndex=r;this.canvasFactory=o;this.filterFactory=l;this._pdfBug=d;this.pageColors=c;this.running=!1;this.graphicsReadyCallback=null;this.graphicsReady=!1;this._useRequestAnimationFrame=!0===h&&"undefined"!=typeof window;this.cancelled=!1;this.capability=Promise.withResolvers();this.task=new RenderTask(this);this._cancelBound=this.cancel.bind(this);this._continueBound=this._continue.bind(this);this._scheduleNextBound=this._scheduleNext.bind(this);this._nextBound=this._next.bind(this);this._canvas=e.canvasContext.canvas}get completed(){return this.capability.promise.catch((function(){}))}initializeGraphics({transparency:t=!1,optionalContentConfig:e}){if(this.cancelled)return;if(this._canvas){if(InternalRenderTask.#Bs.has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");InternalRenderTask.#Bs.add(this._canvas)}if(this._pdfBug&&globalThis.StepperManager?.enabled){this.stepper=globalThis.StepperManager.create(this._pageIndex);this.stepper.init(this.operatorList);this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint()}const{canvasContext:i,viewport:s,transform:n,background:a}=this.params;this.gfx=new CanvasGraphics(i,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:e},this.annotationCanvasMap,this.pageColors);this.gfx.beginDrawing({transform:n,viewport:s,transparency:t,background:a});this.operatorListIdx=0;this.graphicsReady=!0;this.graphicsReadyCallback?.()}cancel(t=null,e=0){this.running=!1;this.cancelled=!0;this.gfx?.endDrawing();if(this.#Ns){window.cancelAnimationFrame(this.#Ns);this.#Ns=null}InternalRenderTask.#Bs.delete(this._canvas);this.callback(t||new RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex+1}`,e))}operatorListChanged(){if(this.graphicsReady){this.stepper?.updateOperatorList(this.operatorList);this.running||this._continue()}else this.graphicsReadyCallback||=this._continueBound}_continue(){this.running=!0;this.cancelled||(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?this.#Ns=window.requestAnimationFrame((()=>{this.#Ns=null;this._nextBound().catch(this._cancelBound)})):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){if(!this.cancelled){this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper);if(this.operatorListIdx===this.operatorList.argsArray.length){this.running=!1;if(this.operatorList.lastChunk){this.gfx.endDrawing();InternalRenderTask.#Bs.delete(this._canvas);this.callback()}}}}}const Ot="4.10.38",Nt="f9bea397f";function makeColorComp(t){return Math.floor(255*Math.max(0,Math.min(1,t))).toString(16).padStart(2,"0")}function scaleAndClamp(t){return Math.max(0,Math.min(255,255*t))}class ColorConverters{static CMYK_G([t,e,i,s]){return["G",1-Math.min(1,.3*t+.59*i+.11*e+s)]}static G_CMYK([t]){return["CMYK",0,0,0,1-t]}static G_RGB([t]){return["RGB",t,t,t]}static G_rgb([t]){return[t=scaleAndClamp(t),t,t]}static G_HTML([t]){const e=makeColorComp(t);return`#${e}${e}${e}`}static RGB_G([t,e,i]){return["G",.3*t+.59*e+.11*i]}static RGB_rgb(t){return t.map(scaleAndClamp)}static RGB_HTML(t){return`#${t.map(makeColorComp).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([t,e,i,s]){return["RGB",1-Math.min(1,t+s),1-Math.min(1,i+s),1-Math.min(1,e+s)]}static CMYK_rgb([t,e,i,s]){return[scaleAndClamp(1-Math.min(1,t+s)),scaleAndClamp(1-Math.min(1,i+s)),scaleAndClamp(1-Math.min(1,e+s))]}static CMYK_HTML(t){const e=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(e)}static RGB_CMYK([t,e,i]){const s=1-t,n=1-e,a=1-i;return["CMYK",s,n,a,Math.min(s,n,a)]}}class BaseSVGFactory{create(t,e,i=!1){if(t<=0||e<=0)throw new Error("Invalid SVG dimensions");const s=this._createSVG("svg:svg");s.setAttribute("version","1.1");if(!i){s.setAttribute("width",`${t}px`);s.setAttribute("height",`${e}px`)}s.setAttribute("preserveAspectRatio","none");s.setAttribute("viewBox",`0 0 ${t} ${e}`);return s}createElement(t){if("string"!=typeof t)throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){unreachable("Abstract method `_createSVG` called.")}}class DOMSVGFactory extends BaseSVGFactory{_createSVG(t){return document.createElementNS(it,t)}}class XfaLayer{static setupStorage(t,e,i,s,n){const a=s.getValue(e,{value:null});switch(i.name){case"textarea":null!==a.value&&(t.textContent=a.value);if("print"===n)break;t.addEventListener("input",(t=>{s.setValue(e,{value:t.target.value})}));break;case"input":if("radio"===i.attributes.type||"checkbox"===i.attributes.type){a.value===i.attributes.xfaOn?t.setAttribute("checked",!0):a.value===i.attributes.xfaOff&&t.removeAttribute("checked");if("print"===n)break;t.addEventListener("change",(t=>{s.setValue(e,{value:t.target.checked?t.target.getAttribute("xfaOn"):t.target.getAttribute("xfaOff")})}))}else{null!==a.value&&t.setAttribute("value",a.value);if("print"===n)break;t.addEventListener("input",(t=>{s.setValue(e,{value:t.target.value})}))}break;case"select":if(null!==a.value){t.setAttribute("value",a.value);for(const t of i.children)t.attributes.value===a.value?t.attributes.selected=!0:t.attributes.hasOwnProperty("selected")&&delete t.attributes.selected}t.addEventListener("input",(t=>{const i=t.target.options,n=-1===i.selectedIndex?"":i[i.selectedIndex].value;s.setValue(e,{value:n})}))}}static setAttributes({html:t,element:e,storage:i=null,intent:s,linkService:n}){const{attributes:a}=e,r=t instanceof HTMLAnchorElement;"radio"===a.type&&(a.name=`${a.name}-${s}`);for(const[e,i]of Object.entries(a))if(null!=i)switch(e){case"class":i.length&&t.setAttribute(e,i.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",i);break;case"style":Object.assign(t.style,i);break;case"textContent":t.textContent=i;break;default:(!r||"href"!==e&&"newWindow"!==e)&&t.setAttribute(e,i)}r&&n.addLinkAttributes(t,a.href,a.newWindow);i&&a.dataId&&this.setupStorage(t,a.dataId,e,i)}static render(t){const e=t.annotationStorage,i=t.linkService,s=t.xfaHtml,n=t.intent||"display",a=document.createElement(s.name);s.attributes&&this.setAttributes({html:a,element:s,intent:n,linkService:i});const r="richText"!==n,o=t.div;o.append(a);if(t.viewport){const e=`matrix(${t.viewport.transform.join(",")})`;o.style.transform=e}r&&o.setAttribute("class","xfaLayer xfaFont");const l=[];if(0===s.children.length){if(s.value){const t=document.createTextNode(s.value);a.append(t);r&&XfaText.shouldBuildText(s.name)&&l.push(t)}return{textDivs:l}}const h=[[s,-1,a]];for(;h.length>0;){const[t,s,a]=h.at(-1);if(s+1===t.children.length){h.pop();continue}const o=t.children[++h.at(-1)[1]];if(null===o)continue;const{name:d}=o;if("#text"===d){const t=document.createTextNode(o.value);l.push(t);a.append(t);continue}const c=o?.attributes?.xmlns?document.createElementNS(o.attributes.xmlns,d):document.createElement(d);a.append(c);o.attributes&&this.setAttributes({html:c,element:o,storage:e,intent:n,linkService:i});if(o.children?.length>0)h.push([o,-1,c]);else if(o.value){const t=document.createTextNode(o.value);r&&XfaText.shouldBuildText(d)&&l.push(t);c.append(t)}}for(const t of o.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))t.setAttribute("readOnly",!0);return{textDivs:l}}static update(t){const e=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=e;t.div.hidden=!1}}const Bt=1e3,Ht=new WeakSet;function getRectDims(t){return{width:t[2]-t[0],height:t[3]-t[1]}}class AnnotationElementFactory{static create(t){switch(t.data.annotationType){case S:return new LinkAnnotationElement(t);case E:return new TextAnnotationElement(t);case U:switch(t.data.fieldType){case"Tx":return new TextWidgetAnnotationElement(t);case"Btn":return t.data.radioButton?new RadioButtonWidgetAnnotationElement(t):t.data.checkBox?new CheckboxWidgetAnnotationElement(t):new PushButtonWidgetAnnotationElement(t);case"Ch":return new ChoiceWidgetAnnotationElement(t);case"Sig":return new SignatureWidgetAnnotationElement(t)}return new WidgetAnnotationElement(t);case H:return new PopupAnnotationElement(t);case C:return new FreeTextAnnotationElement(t);case T:return new LineAnnotationElement(t);case M:return new SquareAnnotationElement(t);case P:return new CircleAnnotationElement(t);case k:return new PolylineAnnotationElement(t);case N:return new CaretAnnotationElement(t);case B:return new InkAnnotationElement(t);case D:return new PolygonAnnotationElement(t);case R:return new HighlightAnnotationElement(t);case I:return new UnderlineAnnotationElement(t);case F:return new SquigglyAnnotationElement(t);case L:return new StrikeOutAnnotationElement(t);case O:return new StampAnnotationElement(t);case z:return new FileAttachmentAnnotationElement(t);default:return new AnnotationElement(t)}}}class AnnotationElement{#Hs=null;#zs=!1;#Us=null;constructor(t,{isRenderable:e=!1,ignoreBorder:i=!1,createQuadrilaterals:s=!1}={}){this.isRenderable=e;this.data=t.data;this.layer=t.layer;this.linkService=t.linkService;this.downloadManager=t.downloadManager;this.imageResourcesPath=t.imageResourcesPath;this.renderForms=t.renderForms;this.svgFactory=t.svgFactory;this.annotationStorage=t.annotationStorage;this.enableScripting=t.enableScripting;this.hasJSActions=t.hasJSActions;this._fieldObjects=t.fieldObjects;this.parent=t.parent;e&&(this.container=this._createContainer(i));s&&this._createQuadrilaterals()}static _hasPopupData({titleObj:t,contentsObj:e,richText:i}){return!!(t?.str||e?.str||i?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return AnnotationElement._hasPopupData(this.data)}updateEdited(t){if(!this.container)return;this.#Hs||={rect:this.data.rect.slice(0)};const{rect:e}=t;e&&this.#Gs(e);this.#Us?.popup.updateEdited(t)}resetEdited(){if(this.#Hs){this.#Gs(this.#Hs.rect);this.#Us?.popup.resetEdited();this.#Hs=null}}#Gs(t){const{container:{style:e},data:{rect:i,rotation:s},parent:{viewport:{rawDims:{pageWidth:n,pageHeight:a,pageX:r,pageY:o}}}}=this;i?.splice(0,4,...t);const{width:l,height:h}=getRectDims(t);e.left=100*(t[0]-r)/n+"%";e.top=100*(a-t[3]+o)/a+"%";if(0===s){e.width=100*l/n+"%";e.height=100*h/a+"%"}else this.setRotation(s)}_createContainer(t){const{data:e,parent:{page:i,viewport:s}}=this,n=document.createElement("section");n.setAttribute("data-annotation-id",e.id);this instanceof WidgetAnnotationElement||(n.tabIndex=Bt);const{style:a}=n;a.zIndex=this.parent.zIndex++;e.alternativeText&&(n.title=e.alternativeText);e.noRotate&&n.classList.add("norotate");if(!e.rect||this instanceof PopupAnnotationElement){const{rotation:t}=e;e.hasOwnCanvas||0===t||this.setRotation(t,n);return n}const{width:r,height:o}=getRectDims(e.rect);if(!t&&e.borderStyle.width>0){a.borderWidth=`${e.borderStyle.width}px`;const t=e.borderStyle.horizontalCornerRadius,i=e.borderStyle.verticalCornerRadius;if(t>0||i>0){const e=`calc(${t}px * var(--scale-factor)) / calc(${i}px * var(--scale-factor))`;a.borderRadius=e}else if(this instanceof RadioButtonWidgetAnnotationElement){const t=`calc(${r}px * var(--scale-factor)) / calc(${o}px * var(--scale-factor))`;a.borderRadius=t}switch(e.borderStyle.style){case G:a.borderStyle="solid";break;case $:a.borderStyle="dashed";break;case V:warn("Unimplemented border style: beveled");break;case j:warn("Unimplemented border style: inset");break;case W:a.borderBottomStyle="solid"}const s=e.borderColor||null;if(s){this.#zs=!0;a.borderColor=Util.makeHexColor(0|s[0],0|s[1],0|s[2])}else a.borderWidth=0}const l=Util.normalizeRect([e.rect[0],i.view[3]-e.rect[1]+i.view[1],e.rect[2],i.view[3]-e.rect[3]+i.view[1]]),{pageWidth:h,pageHeight:d,pageX:c,pageY:u}=s.rawDims;a.left=100*(l[0]-c)/h+"%";a.top=100*(l[1]-u)/d+"%";const{rotation:p}=e;if(e.hasOwnCanvas||0===p){a.width=100*r/h+"%";a.height=100*o/d+"%"}else this.setRotation(p,n);return n}setRotation(t,e=this.container){if(!this.data.rect)return;const{pageWidth:i,pageHeight:s}=this.parent.viewport.rawDims,{width:n,height:a}=getRectDims(this.data.rect);let r,o;if(t%180==0){r=100*n/i;o=100*a/s}else{r=100*a/i;o=100*n/s}e.style.width=`${r}%`;e.style.height=`${o}%`;e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const setColor=(t,e,i)=>{const s=i.detail[t],n=s[0],a=s.slice(1);i.target.style[e]=ColorConverters[`${n}_HTML`](a);this.annotationStorage.setValue(this.data.id,{[e]:ColorConverters[`${n}_rgb`](a)})};return shadow(this,"_commonActions",{display:t=>{const{display:e}=t.detail,i=e%2==1;this.container.style.visibility=i?"hidden":"visible";this.annotationStorage.setValue(this.data.id,{noView:i,noPrint:1===e||2===e})},print:t=>{this.annotationStorage.setValue(this.data.id,{noPrint:!t.detail.print})},hidden:t=>{const{hidden:e}=t.detail;this.container.style.visibility=e?"hidden":"visible";this.annotationStorage.setValue(this.data.id,{noPrint:e,noView:e})},focus:t=>{setTimeout((()=>t.target.focus({preventScroll:!1})),0)},userName:t=>{t.target.title=t.detail.userName},readonly:t=>{t.target.disabled=t.detail.readonly},required:t=>{this._setRequired(t.target,t.detail.required)},bgColor:t=>{setColor("bgColor","backgroundColor",t)},fillColor:t=>{setColor("fillColor","backgroundColor",t)},fgColor:t=>{setColor("fgColor","color",t)},textColor:t=>{setColor("textColor","color",t)},borderColor:t=>{setColor("borderColor","borderColor",t)},strokeColor:t=>{setColor("strokeColor","borderColor",t)},rotation:t=>{const e=t.detail.rotation;this.setRotation(e);this.annotationStorage.setValue(this.data.id,{rotation:e})}})}_dispatchEventFromSandbox(t,e){const i=this._commonActions;for(const s of Object.keys(e.detail)){const n=t[s]||i[s];n?.(e)}}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;const e=this.annotationStorage.getRawValue(this.data.id);if(!e)return;const i=this._commonActions;for(const[s,n]of Object.entries(e)){const a=i[s];if(a){a({detail:{[s]:n},target:t});delete e[s]}}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:t}=this.data;if(!t)return;const[e,i,s,n]=this.data.rect.map((t=>Math.fround(t)));if(8===t.length){const[a,r,o,l]=t.subarray(2,6);if(s===a&&n===r&&e===o&&i===l)return}const{style:a}=this.container;let r;if(this.#zs){const{borderColor:t,borderWidth:e}=a;a.borderWidth=0;r=["url('data:image/svg+xml;utf8,",'',``];this.container.classList.add("hasBorder")}const o=s-e,l=n-i,{svgFactory:h}=this,d=h.createElement("svg");d.classList.add("quadrilateralsContainer");d.setAttribute("width",0);d.setAttribute("height",0);const c=h.createElement("defs");d.append(c);const u=h.createElement("clipPath"),p=`clippath_${this.data.id}`;u.setAttribute("id",p);u.setAttribute("clipPathUnits","objectBoundingBox");c.append(u);for(let i=2,s=t.length;i`)}if(this.#zs){r.push("')");a.backgroundImage=r.join("")}this.container.append(d);this.container.style.clipPath=`url(#${p})`}_createPopup(){const{data:t}=this,e=this.#Us=new PopupAnnotationElement({data:{color:t.color,titleObj:t.titleObj,modificationDate:t.modificationDate,contentsObj:t.contentsObj,richText:t.richText,parentRect:t.rect,borderStyle:0,id:`popup_${t.id}`,rotation:t.rotation},parent:this.parent,elements:[this]});this.parent.div.append(e.render())}render(){unreachable("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){const i=[];if(this._fieldObjects){const s=this._fieldObjects[t];if(s)for(const{page:t,id:n,exportValues:a}of s){if(-1===t)continue;if(n===e)continue;const s="string"==typeof a?a:null,r=document.querySelector(`[data-element-id="${n}"]`);!r||Ht.has(r)?i.push({id:n,exportValue:s,domElement:r}):warn(`_getElementsByName - element not allowed: ${n}`)}return i}for(const s of document.getElementsByName(t)){const{exportValue:t}=s,n=s.getAttribute("data-element-id");n!==e&&(Ht.has(s)&&i.push({id:n,exportValue:t,domElement:s}))}return i}show(){this.container&&(this.container.hidden=!1);this.popup?.maybeShow()}hide(){this.container&&(this.container.hidden=!0);this.popup?.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){const t=this.getElementsToTriggerPopup();if(Array.isArray(t))for(const e of t)e.classList.add("highlightArea");else t.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;const{annotationEditorType:t,data:{id:e}}=this;this.container.addEventListener("dblclick",(()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:t,editId:e})}))}}class LinkAnnotationElement extends AnnotationElement{constructor(t,e=null){super(t,{isRenderable:!0,ignoreBorder:!!e?.ignoreBorder,createQuadrilaterals:!0});this.isTooltipOnly=t.data.isTooltipOnly}render(){const{data:t,linkService:e}=this,i=document.createElement("a");i.setAttribute("data-element-id",t.id);let s=!1;if(t.url){e.addLinkAttributes(i,t.url,t.newWindow);s=!0}else if(t.action){this._bindNamedAction(i,t.action);s=!0}else if(t.attachment){this.#$s(i,t.attachment,t.attachmentDest);s=!0}else if(t.setOCGState){this.#Vs(i,t.setOCGState);s=!0}else if(t.dest){this._bindLink(i,t.dest);s=!0}else{if(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions){this._bindJSAction(i,t);s=!0}if(t.resetForm){this._bindResetFormAction(i,t.resetForm);s=!0}else if(this.isTooltipOnly&&!s){this._bindLink(i,"");s=!0}}this.container.classList.add("linkAnnotation");s&&this.container.append(i);return this.container}#js(){this.container.setAttribute("data-internal-link","")}_bindLink(t,e){t.href=this.linkService.getDestinationHash(e);t.onclick=()=>{e&&this.linkService.goToDestination(e);return!1};(e||""===e)&&this.#js()}_bindNamedAction(t,e){t.href=this.linkService.getAnchorUrl("");t.onclick=()=>{this.linkService.executeNamedAction(e);return!1};this.#js()}#$s(t,e,i=null){t.href=this.linkService.getAnchorUrl("");e.description&&(t.title=e.description);t.onclick=()=>{this.downloadManager?.openOrDownloadData(e.content,e.filename,i);return!1};this.#js()}#Vs(t,e){t.href=this.linkService.getAnchorUrl("");t.onclick=()=>{this.linkService.executeSetOCGState(e);return!1};this.#js()}_bindJSAction(t,e){t.href=this.linkService.getAnchorUrl("");const i=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const s of Object.keys(e.actions)){const n=i.get(s);n&&(t[n]=()=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e.id,name:s}});return!1})}t.onclick||(t.onclick=()=>!1);this.#js()}_bindResetFormAction(t,e){const i=t.onclick;i||(t.href=this.linkService.getAnchorUrl(""));this.#js();if(this._fieldObjects)t.onclick=()=>{i?.();const{fields:t,refs:s,include:n}=e,a=[];if(0!==t.length||0!==s.length){const e=new Set(s);for(const i of t){const t=this._fieldObjects[i]||[];for(const{id:i}of t)e.add(i)}for(const t of Object.values(this._fieldObjects))for(const i of t)e.has(i.id)===n&&a.push(i)}else for(const t of Object.values(this._fieldObjects))a.push(...t);const r=this.annotationStorage,o=[];for(const t of a){const{id:e}=t;o.push(e);switch(t.type){case"text":{const i=t.defaultValue||"";r.setValue(e,{value:i});break}case"checkbox":case"radiobutton":{const i=t.defaultValue===t.exportValues;r.setValue(e,{value:i});break}case"combobox":case"listbox":{const i=t.defaultValue||"";r.setValue(e,{value:i});break}default:continue}const i=document.querySelector(`[data-element-id="${e}"]`);i&&(Ht.has(i)?i.dispatchEvent(new Event("resetform")):warn(`_bindResetFormAction - element not allowed: ${e}`))}this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:o,name:"ResetForm"}});return!1};else{warn('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.');i||(t.onclick=()=>!1)}}}class TextAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");const t=document.createElement("img");t.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg";t.setAttribute("data-l10n-id","pdfjs-text-annotation-type");t.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name}));!this.data.popupRef&&this.hasPopupData&&this._createPopup();this.container.append(t);return this.container}}class WidgetAnnotationElement extends AnnotationElement{render(){return this.container}showElementAndHideCanvas(t){if(this.data.hasOwnCanvas){"CANVAS"===t.previousSibling?.nodeName&&(t.previousSibling.hidden=!0);t.hidden=!1}}_getKeyModifier(t){return util_FeatureTest.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,e,i,s,n){i.includes("mouse")?t.addEventListener(i,(t=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:s,value:n(t),shift:t.shiftKey,modifier:this._getKeyModifier(t)}})})):t.addEventListener(i,(t=>{if("blur"===i){if(!e.focused||!t.relatedTarget)return;e.focused=!1}else if("focus"===i){if(e.focused)return;e.focused=!0}n&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:s,value:n(t)}})}))}_setEventListeners(t,e,i,s){for(const[n,a]of i)if("Action"===a||this.data.actions?.[a]){"Focus"!==a&&"Blur"!==a||(e||={focused:!1});this._setEventListener(t,e,n,a,s);"Focus"!==a||this.data.actions?.Blur?"Blur"!==a||this.data.actions?.Focus||this._setEventListener(t,e,"focus","Focus",null):this._setEventListener(t,e,"blur","Blur",null)}}_setBackgroundColor(t){const e=this.data.backgroundColor||null;t.style.backgroundColor=null===e?"transparent":Util.makeHexColor(e[0],e[1],e[2])}_setTextStyle(t){const e=["left","center","right"],{fontColor:i}=this.data.defaultAppearanceData,s=this.data.defaultAppearanceData.fontSize||9,a=t.style;let r;const roundToOneDecimal=t=>Math.round(10*t)/10;if(this.data.multiLine){const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2),e=t/(Math.round(t/(n*s))||1);r=Math.min(s,roundToOneDecimal(e/n))}else{const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2);r=Math.min(s,roundToOneDecimal(t/n))}a.fontSize=`calc(${r}px * var(--scale-factor))`;a.color=Util.makeHexColor(i[0],i[1],i[2]);null!==this.data.textAlignment&&(a.textAlign=e[this.data.textAlignment])}_setRequired(t,e){e?t.setAttribute("required",!0):t.removeAttribute("required");t.setAttribute("aria-required",e)}}class TextWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms||t.data.hasOwnCanvas||!t.data.hasAppearance&&!!t.data.fieldValue})}setPropertyOnSiblings(t,e,i,s){const n=this.annotationStorage;for(const a of this._getElementsByName(t.name,t.id)){a.domElement&&(a.domElement[e]=i);n.setValue(a.id,{[s]:i})}}render(){const t=this.annotationStorage,e=this.data.id;this.container.classList.add("textWidgetAnnotation");let i=null;if(this.renderForms){const s=t.getValue(e,{value:this.data.fieldValue});let n=s.value||"";const a=t.getValue(e,{charLimit:this.data.maxLen}).charLimit;a&&n.length>a&&(n=n.slice(0,a));let r=s.formattedValue||this.data.textContent?.join("\n")||null;r&&this.data.comb&&(r=r.replaceAll(/\s+/g,""));const o={userValue:n,formattedValue:r,lastCommittedValue:null,commitKey:1,focused:!1};if(this.data.multiLine){i=document.createElement("textarea");i.textContent=r??n;this.data.doNotScroll&&(i.style.overflowY="hidden")}else{i=document.createElement("input");i.type="text";i.setAttribute("value",r??n);this.data.doNotScroll&&(i.style.overflowX="hidden")}this.data.hasOwnCanvas&&(i.hidden=!0);Ht.add(i);i.setAttribute("data-element-id",e);i.disabled=this.data.readOnly;i.name=this.data.fieldName;i.tabIndex=Bt;this._setRequired(i,this.data.required);a&&(i.maxLength=a);i.addEventListener("input",(s=>{t.setValue(e,{value:s.target.value});this.setPropertyOnSiblings(i,"value",s.target.value,"value");o.formattedValue=null}));i.addEventListener("resetform",(t=>{const e=this.data.defaultFieldValue??"";i.value=o.userValue=e;o.formattedValue=null}));let blurListener=t=>{const{formattedValue:e}=o;null!=e&&(t.target.value=e);t.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){i.addEventListener("focus",(t=>{if(o.focused)return;const{target:e}=t;o.userValue&&(e.value=o.userValue);o.lastCommittedValue=e.value;o.commitKey=1;this.data.actions?.Focus||(o.focused=!0)}));i.addEventListener("updatefromsandbox",(i=>{this.showElementAndHideCanvas(i.target);const s={value(i){o.userValue=i.detail.value??"";t.setValue(e,{value:o.userValue.toString()});i.target.value=o.userValue},formattedValue(i){const{formattedValue:s}=i.detail;o.formattedValue=s;null!=s&&i.target!==document.activeElement&&(i.target.value=s);t.setValue(e,{formattedValue:s})},selRange(t){t.target.setSelectionRange(...t.detail.selRange)},charLimit:i=>{const{charLimit:s}=i.detail,{target:n}=i;if(0===s){n.removeAttribute("maxLength");return}n.setAttribute("maxLength",s);let a=o.userValue;if(a&&!(a.length<=s)){a=a.slice(0,s);n.value=o.userValue=a;t.setValue(e,{value:a});this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:a,willCommit:!0,commitKey:1,selStart:n.selectionStart,selEnd:n.selectionEnd}})}}};this._dispatchEventFromSandbox(s,i)}));i.addEventListener("keydown",(t=>{o.commitKey=1;let i=-1;"Escape"===t.key?i=0:"Enter"!==t.key||this.data.multiLine?"Tab"===t.key&&(o.commitKey=3):i=2;if(-1===i)return;const{value:s}=t.target;if(o.lastCommittedValue!==s){o.lastCommittedValue=s;o.userValue=s;this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:s,willCommit:!0,commitKey:i,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}})}}));const s=blurListener;blurListener=null;i.addEventListener("blur",(t=>{if(!o.focused||!t.relatedTarget)return;this.data.actions?.Blur||(o.focused=!1);const{value:i}=t.target;o.userValue=i;o.lastCommittedValue!==i&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:i,willCommit:!0,commitKey:o.commitKey,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}});s(t)}));this.data.actions?.Keystroke&&i.addEventListener("beforeinput",(t=>{o.lastCommittedValue=null;const{data:i,target:s}=t,{value:n,selectionStart:a,selectionEnd:r}=s;let l=a,h=r;switch(t.inputType){case"deleteWordBackward":{const t=n.substring(0,a).match(/\w*[^\w]*$/);t&&(l-=t[0].length);break}case"deleteWordForward":{const t=n.substring(a).match(/^[^\w]*\w*/);t&&(h+=t[0].length);break}case"deleteContentBackward":a===r&&(l-=1);break;case"deleteContentForward":a===r&&(h+=1)}t.preventDefault();this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:n,change:i||"",willCommit:!1,selStart:l,selEnd:h}})}));this._setEventListeners(i,o,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.value))}blurListener&&i.addEventListener("blur",blurListener);if(this.data.comb){const t=(this.data.rect[2]-this.data.rect[0])/a;i.classList.add("comb");i.style.letterSpacing=`calc(${t}px * var(--scale-factor) - 1ch)`}}else{i=document.createElement("div");i.textContent=this.data.fieldValue;i.style.verticalAlign="middle";i.style.display="table-cell";this.data.hasOwnCanvas&&(i.hidden=!0)}this._setTextStyle(i);this._setBackgroundColor(i);this._setDefaultPropertiesFromJS(i);this.container.append(i);return this.container}}class SignatureWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){const t=this.annotationStorage,e=this.data,i=e.id;let s=t.getValue(i,{value:e.exportValue===e.fieldValue}).value;if("string"==typeof s){s="Off"!==s;t.setValue(i,{value:s})}this.container.classList.add("buttonWidgetAnnotation","checkBox");const n=document.createElement("input");Ht.add(n);n.setAttribute("data-element-id",i);n.disabled=e.readOnly;this._setRequired(n,this.data.required);n.type="checkbox";n.name=e.fieldName;s&&n.setAttribute("checked",!0);n.setAttribute("exportValue",e.exportValue);n.tabIndex=Bt;n.addEventListener("change",(s=>{const{name:n,checked:a}=s.target;for(const s of this._getElementsByName(n,i)){const i=a&&s.exportValue===e.exportValue;s.domElement&&(s.domElement.checked=i);t.setValue(s.id,{value:i})}t.setValue(i,{value:a})}));n.addEventListener("resetform",(t=>{const i=e.defaultFieldValue||"Off";t.target.checked=i===e.exportValue}));if(this.enableScripting&&this.hasJSActions){n.addEventListener("updatefromsandbox",(e=>{const s={value(e){e.target.checked="Off"!==e.detail.value;t.setValue(i,{value:e.target.checked})}};this._dispatchEventFromSandbox(s,e)}));this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.checked))}this._setBackgroundColor(n);this._setDefaultPropertiesFromJS(n);this.container.append(n);return this.container}}class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const t=this.annotationStorage,e=this.data,i=e.id;let s=t.getValue(i,{value:e.fieldValue===e.buttonValue}).value;if("string"==typeof s){s=s!==e.buttonValue;t.setValue(i,{value:s})}if(s)for(const s of this._getElementsByName(e.fieldName,i))t.setValue(s.id,{value:!1});const n=document.createElement("input");Ht.add(n);n.setAttribute("data-element-id",i);n.disabled=e.readOnly;this._setRequired(n,this.data.required);n.type="radio";n.name=e.fieldName;s&&n.setAttribute("checked",!0);n.tabIndex=Bt;n.addEventListener("change",(e=>{const{name:s,checked:n}=e.target;for(const e of this._getElementsByName(s,i))t.setValue(e.id,{value:!1});t.setValue(i,{value:n})}));n.addEventListener("resetform",(t=>{const i=e.defaultFieldValue;t.target.checked=null!=i&&i===e.buttonValue}));if(this.enableScripting&&this.hasJSActions){const s=e.buttonValue;n.addEventListener("updatefromsandbox",(e=>{const n={value:e=>{const n=s===e.detail.value;for(const s of this._getElementsByName(e.target.name)){const e=n&&s.id===i;s.domElement&&(s.domElement.checked=e);t.setValue(s.id,{value:e})}}};this._dispatchEventFromSandbox(n,e)}));this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.checked))}this._setBackgroundColor(n);this._setDefaultPropertiesFromJS(n);this.container.append(n);return this.container}}class PushButtonWidgetAnnotationElement extends LinkAnnotationElement{constructor(t){super(t,{ignoreBorder:t.data.hasAppearance})}render(){const t=super.render();t.classList.add("buttonWidgetAnnotation","pushButton");const e=t.lastChild;if(this.enableScripting&&this.hasJSActions&&e){this._setDefaultPropertiesFromJS(e);e.addEventListener("updatefromsandbox",(t=>{this._dispatchEventFromSandbox({},t)}))}return t}}class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");const t=this.annotationStorage,e=this.data.id,i=t.getValue(e,{value:this.data.fieldValue}),s=document.createElement("select");Ht.add(s);s.setAttribute("data-element-id",e);s.disabled=this.data.readOnly;this._setRequired(s,this.data.required);s.name=this.data.fieldName;s.tabIndex=Bt;let n=this.data.combo&&this.data.options.length>0;if(!this.data.combo){s.size=this.data.options.length;this.data.multiSelect&&(s.multiple=!0)}s.addEventListener("resetform",(t=>{const e=this.data.defaultFieldValue;for(const t of s.options)t.selected=t.value===e}));for(const t of this.data.options){const e=document.createElement("option");e.textContent=t.displayValue;e.value=t.exportValue;if(i.value.includes(t.exportValue)){e.setAttribute("selected",!0);n=!1}s.append(e)}let a=null;if(n){const t=document.createElement("option");t.value=" ";t.setAttribute("hidden",!0);t.setAttribute("selected",!0);s.prepend(t);a=()=>{t.remove();s.removeEventListener("input",a);a=null};s.addEventListener("input",a)}const getValue=t=>{const e=t?"value":"textContent",{options:i,multiple:n}=s;return n?Array.prototype.filter.call(i,(t=>t.selected)).map((t=>t[e])):-1===i.selectedIndex?null:i[i.selectedIndex][e]};let r=getValue(!1);const getItems=t=>{const e=t.target.options;return Array.prototype.map.call(e,(t=>({displayValue:t.textContent,exportValue:t.value})))};if(this.enableScripting&&this.hasJSActions){s.addEventListener("updatefromsandbox",(i=>{const n={value(i){a?.();const n=i.detail.value,o=new Set(Array.isArray(n)?n:[n]);for(const t of s.options)t.selected=o.has(t.value);t.setValue(e,{value:getValue(!0)});r=getValue(!1)},multipleSelection(t){s.multiple=!0},remove(i){const n=s.options,a=i.detail.remove;n[a].selected=!1;s.remove(a);if(n.length>0){-1===Array.prototype.findIndex.call(n,(t=>t.selected))&&(n[0].selected=!0)}t.setValue(e,{value:getValue(!0),items:getItems(i)});r=getValue(!1)},clear(i){for(;0!==s.length;)s.remove(0);t.setValue(e,{value:null,items:[]});r=getValue(!1)},insert(i){const{index:n,displayValue:a,exportValue:o}=i.detail.insert,l=s.children[n],h=document.createElement("option");h.textContent=a;h.value=o;l?l.before(h):s.append(h);t.setValue(e,{value:getValue(!0),items:getItems(i)});r=getValue(!1)},items(i){const{items:n}=i.detail;for(;0!==s.length;)s.remove(0);for(const t of n){const{displayValue:e,exportValue:i}=t,n=document.createElement("option");n.textContent=e;n.value=i;s.append(n)}s.options.length>0&&(s.options[0].selected=!0);t.setValue(e,{value:getValue(!0),items:getItems(i)});r=getValue(!1)},indices(i){const s=new Set(i.detail.indices);for(const t of i.target.options)t.selected=s.has(t.index);t.setValue(e,{value:getValue(!0)});r=getValue(!1)},editable(t){t.target.disabled=!t.detail.editable}};this._dispatchEventFromSandbox(n,i)}));s.addEventListener("input",(i=>{const s=getValue(!0),n=getValue(!1);t.setValue(e,{value:s});i.preventDefault();this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:r,change:n,changeEx:s,willCommit:!1,commitKey:1,keyDown:!1}})}));this._setEventListeners(s,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],(t=>t.target.value))}else s.addEventListener("input",(function(i){t.setValue(e,{value:getValue(!0)})}));this.data.combo&&this._setTextStyle(s);this._setBackgroundColor(s);this._setDefaultPropertiesFromJS(s);this.container.append(s);return this.container}}class PopupAnnotationElement extends AnnotationElement{constructor(t){const{data:e,elements:i}=t;super(t,{isRenderable:AnnotationElement._hasPopupData(e)});this.elements=i;this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new PopupElement({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate,contentsObj:this.data.contentsObj,richText:this.data.richText,rect:this.data.rect,parentRect:this.data.parentRect||null,parent:this.parent,elements:this.elements,open:this.data.open}),e=[];for(const i of this.elements){i.popup=t;i.container.ariaHasPopup="dialog";e.push(i.data.id);i.addHighlightArea()}this.container.setAttribute("aria-controls",e.map((t=>`${et}${t}`)).join(","));return this.container}}class PopupElement{#Ws=this.#qs.bind(this);#Xs=this.#Ks.bind(this);#Ys=this.#Qs.bind(this);#Js=this.#Zs.bind(this);#tn=null;#pt=null;#en=null;#in=null;#sn=null;#nn=null;#an=null;#rn=!1;#on=null;#C=null;#ln=null;#hn=null;#dn=null;#Hs=null;#cn=!1;constructor({container:t,color:e,elements:i,titleObj:s,modificationDate:n,contentsObj:a,richText:r,parent:o,rect:l,parentRect:h,open:d}){this.#pt=t;this.#dn=s;this.#en=a;this.#hn=r;this.#nn=o;this.#tn=e;this.#ln=l;this.#an=h;this.#sn=i;this.#in=PDFDateString.toDateObject(n);this.trigger=i.flatMap((t=>t.getElementsToTriggerPopup()));for(const t of this.trigger){t.addEventListener("click",this.#Js);t.addEventListener("mouseenter",this.#Ys);t.addEventListener("mouseleave",this.#Xs);t.classList.add("popupTriggerArea")}for(const t of i)t.container?.addEventListener("keydown",this.#Ws);this.#pt.hidden=!0;d&&this.#Zs()}render(){if(this.#on)return;const t=this.#on=document.createElement("div");t.className="popup";if(this.#tn){const e=t.style.outlineColor=Util.makeHexColor(...this.#tn);if(CSS.supports("background-color","color-mix(in srgb, red 30%, white)"))t.style.backgroundColor=`color-mix(in srgb, ${e} 30%, white)`;else{const e=.7;t.style.backgroundColor=Util.makeHexColor(...this.#tn.map((t=>Math.floor(e*(255-t)+t))))}}const e=document.createElement("span");e.className="header";const i=document.createElement("h1");e.append(i);({dir:i.dir,str:i.textContent}=this.#dn);t.append(e);if(this.#in){const t=document.createElement("span");t.classList.add("popupDate");t.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string");t.setAttribute("data-l10n-args",JSON.stringify({dateObj:this.#in.valueOf()}));e.append(t)}const s=this.#un;if(s){XfaLayer.render({xfaHtml:s,intent:"richText",div:t});t.lastChild.classList.add("richText","popupContent")}else{const e=this._formatContents(this.#en);t.append(e)}this.#pt.append(t)}get#un(){const t=this.#hn,e=this.#en;return!t?.str||e?.str&&e.str!==t.str?null:this.#hn.html||null}get#pn(){return this.#un?.attributes?.style?.fontSize||0}get#gn(){return this.#un?.attributes?.style?.color||null}#mn(t){const e=[],i={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},s={style:{color:this.#gn,fontSize:this.#pn?`calc(${this.#pn}px * var(--scale-factor))`:""}};for(const i of t.split("\n"))e.push({name:"span",value:i,attributes:s});return i}_formatContents({str:t,dir:e}){const i=document.createElement("p");i.classList.add("popupContent");i.dir=e;const s=t.split(/(?:\r\n?|\n)/);for(let t=0,e=s.length;t=0&&n.setAttribute("stroke-width",e||1);if(i)for(let t=0,e=this.#xn.length;t{"Enter"===t.key&&(s?t.metaKey:t.ctrlKey)&&this.#Sn()}));!e.popupRef&&this.hasPopupData?this._createPopup():i.classList.add("popupTriggerArea");t.append(i);return t}getElementsToTriggerPopup(){return this.#En}addHighlightArea(){this.container.classList.add("highlightArea")}#Sn(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}}class AnnotationLayer{#Cn=null;#Tn=null;#Mn=new Map;#Pn=null;constructor({div:t,accessibilityManager:e,annotationCanvasMap:i,annotationEditorUIManager:s,page:n,viewport:a,structTreeLayer:r}){this.div=t;this.#Cn=e;this.#Tn=i;this.#Pn=r||null;this.page=n;this.viewport=a;this.zIndex=0;this._annotationEditorUIManager=s}hasEditableAnnotations(){return this.#Mn.size>0}async#Dn(t,e){const i=t.firstChild||t,s=i.id=`${et}${e}`,n=await(this.#Pn?.getAriaAttributes(s));if(n)for(const[t,e]of n)i.setAttribute(t,e);this.div.append(t);this.#Cn?.moveElementInDOM(this.div,t,i,!1)}async render(t){const{annotations:e}=t,i=this.div;setLayerDimensions(i,this.viewport);const s=new Map,n={data:null,layer:i,linkService:t.linkService,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:!1!==t.renderForms,svgFactory:new DOMSVGFactory,annotationStorage:t.annotationStorage||new AnnotationStorage,enableScripting:!0===t.enableScripting,hasJSActions:t.hasJSActions,fieldObjects:t.fieldObjects,parent:this,elements:null};for(const t of e){if(t.noHTML)continue;const e=t.annotationType===H;if(e){const e=s.get(t.id);if(!e)continue;n.elements=e}else{const{width:e,height:i}=getRectDims(t.rect);if(e<=0||i<=0)continue}n.data=t;const i=AnnotationElementFactory.create(n);if(!i.isRenderable)continue;if(!e&&t.popupRef){const e=s.get(t.popupRef);e?e.push(i):s.set(t.popupRef,[i])}const a=i.render();t.hidden&&(a.style.visibility="hidden");await this.#Dn(a,t.id);if(i._isEditable){this.#Mn.set(i.data.id,i);this._annotationEditorUIManager?.renderAnnotationElement(i)}}this.#kn()}update({viewport:t}){const e=this.div;this.viewport=t;setLayerDimensions(e,{rotation:t.rotation});this.#kn();e.hidden=!1}#kn(){if(!this.#Tn)return;const t=this.div;for(const[e,i]of this.#Tn){const s=t.querySelector(`[data-annotation-id="${e}"]`);if(!s)continue;i.className="annotationContent";const{firstChild:n}=s;n?"CANVAS"===n.nodeName?n.replaceWith(i):n.classList.contains("annotationContent")?n.after(i):n.before(i):s.append(i)}this.#Tn.clear()}getEditableAnnotations(){return Array.from(this.#Mn.values())}getEditableAnnotation(t){return this.#Mn.get(t)}}const zt=/\r\n?|\n/g;class FreeTextEditor extends AnnotationEditor{#tn;#Rn="";#In=`${this.id}-editor`;#Fn=null;#pn;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){const t=FreeTextEditor.prototype,arrowChecker=t=>t.isEmpty(),e=AnnotationEditorUIManager.TRANSLATE_SMALL,i=AnnotationEditorUIManager.TRANSLATE_BIG;return shadow(this,"_keyboardManager",new KeyboardManager([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],t.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],t.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],t._translateEmpty,{args:[-e,0],checker:arrowChecker}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t._translateEmpty,{args:[-i,0],checker:arrowChecker}],[["ArrowRight","mac+ArrowRight"],t._translateEmpty,{args:[e,0],checker:arrowChecker}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t._translateEmpty,{args:[i,0],checker:arrowChecker}],[["ArrowUp","mac+ArrowUp"],t._translateEmpty,{args:[0,-e],checker:arrowChecker}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t._translateEmpty,{args:[0,-i],checker:arrowChecker}],[["ArrowDown","mac+ArrowDown"],t._translateEmpty,{args:[0,e],checker:arrowChecker}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t._translateEmpty,{args:[0,i],checker:arrowChecker}]]))}static _type="freetext";static _editorType=g.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"});this.#tn=t.color||FreeTextEditor._defaultColor||AnnotationEditor._defaultLineColor;this.#pn=t.fontSize||FreeTextEditor._defaultFontSize}static initialize(t,e){AnnotationEditor.initialize(t,e);const i=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(i.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,e){switch(t){case m.FREETEXT_SIZE:FreeTextEditor._defaultFontSize=e;break;case m.FREETEXT_COLOR:FreeTextEditor._defaultColor=e}}updateParams(t,e){switch(t){case m.FREETEXT_SIZE:this.#Ln(e);break;case m.FREETEXT_COLOR:this.#On(e)}}static get defaultPropertiesToUpdate(){return[[m.FREETEXT_SIZE,FreeTextEditor._defaultFontSize],[m.FREETEXT_COLOR,FreeTextEditor._defaultColor||AnnotationEditor._defaultLineColor]]}get propertiesToUpdate(){return[[m.FREETEXT_SIZE,this.#pn],[m.FREETEXT_COLOR,this.#tn]]}#Ln(t){const setFontsize=t=>{this.editorDiv.style.fontSize=`calc(${t}px * var(--scale-factor))`;this.translate(0,-(t-this.#pn)*this.parentScale);this.#pn=t;this.#Nn()},e=this.#pn;this.addCommands({cmd:setFontsize.bind(this,t),undo:setFontsize.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:m.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}#On(t){const setColor=t=>{this.#tn=this.editorDiv.style.color=t},e=this.#tn;this.addCommands({cmd:setColor.bind(this,t),undo:setColor.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:m.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(t,e){this._uiManager.translateSelectedEditors(t,e,!0)}getInitialTranslation(){const t=this.parentScale;return[-FreeTextEditor._internalPadding*t,-(FreeTextEditor._internalPadding+this.#pn)*t]}rebuild(){if(this.parent){super.rebuild();null!==this.div&&(this.isAttachedToDOM||this.parent.add(this))}}enableEditMode(){if(this.isInEditMode())return;this.parent.setEditingState(!1);this.parent.updateToolbar(g.FREETEXT);super.enableEditMode();this.overlayDiv.classList.remove("enabled");this.editorDiv.contentEditable=!0;this._isDraggable=!1;this.div.removeAttribute("aria-activedescendant");this.#Fn=new AbortController;const t=this._uiManager.combinedSignal(this.#Fn);this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:t});this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:t});this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:t});this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:t});this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:t})}disableEditMode(){if(this.isInEditMode()){this.parent.setEditingState(!0);super.disableEditMode();this.overlayDiv.classList.add("enabled");this.editorDiv.contentEditable=!1;this.div.setAttribute("aria-activedescendant",this.#In);this._isDraggable=!0;this.#Fn?.abort();this.#Fn=null;this.div.focus({preventScroll:!0});this.isEditing=!1;this.parent.div.classList.add("freetextEditing")}}focusin(t){if(this._focusEventsAllowed){super.focusin(t);t.target!==this.editorDiv&&this.editorDiv.focus()}}onceAdded(t){if(!this.width){this.enableEditMode();t&&this.editorDiv.focus();this._initialOptions?.isCentered&&this.center();this._initialOptions=null}}isEmpty(){return!this.editorDiv||""===this.editorDiv.innerText.trim()}remove(){this.isEditing=!1;if(this.parent){this.parent.setEditingState(!0);this.parent.div.classList.add("freetextEditing")}super.remove()}#Bn(){const t=[];this.editorDiv.normalize();let e=null;for(const i of this.editorDiv.childNodes)if(e?.nodeType!==Node.TEXT_NODE||"BR"!==i.nodeName){t.push(FreeTextEditor.#Hn(i));e=i}return t.join("\n")}#Nn(){const[t,e]=this.parentDimensions;let i;if(this.isAttachedToDOM)i=this.div.getBoundingClientRect();else{const{currentLayer:t,div:e}=this,s=e.style.display,n=e.classList.contains("hidden");e.classList.remove("hidden");e.style.display="hidden";t.div.append(this.div);i=e.getBoundingClientRect();e.remove();e.style.display=s;e.classList.toggle("hidden",n)}if(this.rotation%180==this.parentRotation%180){this.width=i.width/t;this.height=i.height/e}else{this.width=i.height/t;this.height=i.width/e}this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit();this.disableEditMode();const t=this.#Rn,e=this.#Rn=this.#Bn().trimEnd();if(t===e)return;const setText=t=>{this.#Rn=t;if(t){this.#zn();this._uiManager.rebuild(this);this.#Nn()}else this.remove()};this.addCommands({cmd:()=>{setText(e)},undo:()=>{setText(t)},mustExec:!1});this.#Nn()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode();this.editorDiv.focus()}dblclick(t){this.enterInEditMode()}keydown(t){if(t.target===this.div&&"Enter"===t.key){this.enterInEditMode();t.preventDefault()}}editorDivKeydown(t){FreeTextEditor._keyboardManager.exec(this,t)}editorDivFocus(t){this.isEditing=!0}editorDivBlur(t){this.isEditing=!1}editorDivInput(t){this.parent.div.classList.toggle("freetextEditing",this.isEmpty())}disableEditing(){this.editorDiv.setAttribute("role","comment");this.editorDiv.removeAttribute("aria-multiline")}enableEditing(){this.editorDiv.setAttribute("role","textbox");this.editorDiv.setAttribute("aria-multiline",!0)}render(){if(this.div)return this.div;let t,e;if(this.width){t=this.x;e=this.y}super.render();this.editorDiv=document.createElement("div");this.editorDiv.className="internal";this.editorDiv.setAttribute("id",this.#In);this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text2");this.editorDiv.setAttribute("data-l10n-attrs","default-content");this.enableEditing();this.editorDiv.contentEditable=!0;const{style:i}=this.editorDiv;i.fontSize=`calc(${this.#pn}px * var(--scale-factor))`;i.color=this.#tn;this.div.append(this.editorDiv);this.overlayDiv=document.createElement("div");this.overlayDiv.classList.add("overlay","enabled");this.div.append(this.overlayDiv);bindEvents(this,this.div,["dblclick","keydown"]);if(this.width){const[i,s]=this.parentDimensions;if(this.annotationElementId){const{position:n}=this._initialData;let[a,r]=this.getInitialTranslation();[a,r]=this.pageTranslationToScreen(a,r);const[o,l]=this.pageDimensions,[h,d]=this.pageTranslation;let c,u;switch(this.rotation){case 0:c=t+(n[0]-h)/o;u=e+this.height-(n[1]-d)/l;break;case 90:c=t+(n[0]-h)/o;u=e-(n[1]-d)/l;[a,r]=[r,-a];break;case 180:c=t-this.width+(n[0]-h)/o;u=e-(n[1]-d)/l;[a,r]=[-a,-r];break;case 270:c=t+(n[0]-h-this.height*l)/o;u=e+(n[1]-d-this.width*o)/l;[a,r]=[-r,a]}this.setAt(c*i,u*s,a,r)}else this.setAt(t*i,e*s,this.width*i,this.height*s);this.#zn();this._isDraggable=!0;this.editorDiv.contentEditable=!1}else{this._isDraggable=!1;this.editorDiv.contentEditable=!0}return this.div}static#Hn(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(zt,"")}editorDivPaste(t){const e=t.clipboardData||window.clipboardData,{types:i}=e;if(1===i.length&&"text/plain"===i[0])return;t.preventDefault();const s=FreeTextEditor.#Un(e.getData("text")||"").replaceAll(zt,"\n");if(!s)return;const n=window.getSelection();if(!n.rangeCount)return;this.editorDiv.normalize();n.deleteFromDocument();const a=n.getRangeAt(0);if(!s.includes("\n")){a.insertNode(document.createTextNode(s));this.editorDiv.normalize();n.collapseToStart();return}const{startContainer:r,startOffset:o}=a,l=[],h=[];if(r.nodeType===Node.TEXT_NODE){const t=r.parentElement;h.push(r.nodeValue.slice(o).replaceAll(zt,""));if(t!==this.editorDiv){let e=l;for(const i of this.editorDiv.childNodes)i!==t?e.push(FreeTextEditor.#Hn(i)):e=h}l.push(r.nodeValue.slice(0,o).replaceAll(zt,""))}else if(r===this.editorDiv){let t=l,e=0;for(const i of this.editorDiv.childNodes){e++===o&&(t=h);t.push(FreeTextEditor.#Hn(i))}}this.#Rn=`${l.join("\n")}${s}${h.join("\n")}`;this.#zn();const d=new Range;let c=l.reduce(((t,e)=>t+e.length),0);for(const{firstChild:t}of this.editorDiv.childNodes)if(t.nodeType===Node.TEXT_NODE){const e=t.nodeValue.length;if(c<=e){d.setStart(t,c);d.setEnd(t,c);break}c-=e}n.removeAllRanges();n.addRange(d)}#zn(){this.editorDiv.replaceChildren();if(this.#Rn)for(const t of this.#Rn.split("\n")){const e=document.createElement("div");e.append(t?document.createTextNode(t):document.createElement("br"));this.editorDiv.append(e)}}#Gn(){return this.#Rn.replaceAll(" "," ")}static#Un(t){return t.replaceAll(" "," ")}get contentDiv(){return this.editorDiv}static async deserialize(t,e,i){let s=null;if(t instanceof FreeTextAnnotationElement){const{data:{defaultAppearanceData:{fontSize:e,fontColor:i},rect:n,rotation:a,id:r,popupRef:o},textContent:l,textPosition:h,parent:{page:{pageNumber:d}}}=t;if(!l||0===l.length)return null;s=t={annotationType:g.FREETEXT,color:Array.from(i),fontSize:e,value:l.join("\n"),position:h,pageIndex:d-1,rect:n.slice(0),rotation:a,id:r,deleted:!1,popupRef:o}}const n=await super.deserialize(t,e,i);n.#pn=t.fontSize;n.#tn=Util.makeHexColor(...t.color);n.#Rn=FreeTextEditor.#Un(t.value);n.annotationElementId=t.id||null;n._initialData=s;return n}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const e=FreeTextEditor._internalPadding*this.parentScale,i=this.getRect(e,e),s=AnnotationEditor._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.#tn),n={annotationType:g.FREETEXT,color:s,fontSize:this.#pn,value:this.#Gn(),pageIndex:this.pageIndex,rect:i,rotation:this.rotation,structTreeParentId:this._structTreeParentId};if(t)return n;if(this.annotationElementId&&!this.#$n(n))return null;n.id=this.annotationElementId;return n}#$n(t){const{value:e,fontSize:i,color:s,pageIndex:n}=this._initialData;return this._hasBeenMoved||t.value!==e||t.fontSize!==i||t.color.some(((t,e)=>t!==s[e]))||t.pageIndex!==n}renderAnnotationElement(t){const e=super.renderAnnotationElement(t);if(this.deleted)return e;const{style:i}=e;i.fontSize=`calc(${this.#pn}px * var(--scale-factor))`;i.color=this.#tn;e.replaceChildren();for(const t of this.#Rn.split("\n")){const i=document.createElement("div");i.append(t?document.createTextNode(t):document.createElement("br"));e.append(i)}const s=FreeTextEditor._internalPadding*this.parentScale;t.updateEdited({rect:this.getRect(s,s),popupContent:this.#Rn});return e}resetAnnotationElement(t){super.resetAnnotationElement(t);t.resetEdited()}}class Outline{static PRECISION=1e-4;toSVGPath(){unreachable("Abstract method `toSVGPath` must be implemented.")}get box(){unreachable("Abstract getter `box` must be implemented.")}serialize(t,e){unreachable("Abstract method `serialize` must be implemented.")}static _rescale(t,e,i,s,n,a){a||=new Float32Array(t.length);for(let r=0,o=t.length;r=6;t-=6)isNaN(e[t])?i.push(`L${e[t+4]} ${e[t+5]}`):i.push(`C${e[t]} ${e[t+1]} ${e[t+2]} ${e[t+3]} ${e[t+4]} ${e[t+5]}`);this.#ha(i);return i.join(" ")}#oa(){const[t,e,i,s]=this.#Vn,[n,a,r,o]=this.#ra();return`M${(this.#Kn[2]-t)/i} ${(this.#Kn[3]-e)/s} L${(this.#Kn[4]-t)/i} ${(this.#Kn[5]-e)/s} L${n} ${a} L${r} ${o} L${(this.#Kn[16]-t)/i} ${(this.#Kn[17]-e)/s} L${(this.#Kn[14]-t)/i} ${(this.#Kn[15]-e)/s} Z`}#ha(t){const e=this.#jn;t.push(`L${e[4]} ${e[5]} Z`)}#la(t){const[e,i,s,n]=this.#Vn,a=this.#Kn.subarray(4,6),r=this.#Kn.subarray(16,18),[o,l,h,d]=this.#ra();t.push(`L${(a[0]-e)/s} ${(a[1]-i)/n} L${o} ${l} L${h} ${d} L${(r[0]-e)/s} ${(r[1]-i)/n}`)}newFreeDrawOutline(t,e,i,s,n,a){return new FreeDrawOutline(t,e,i,s,n,a)}getOutlines(){const t=this.#Xn,e=this.#jn,i=this.#Kn,[s,n,a,r]=this.#Vn,o=new Float32Array((this.#ia?.length??0)+2);for(let t=0,e=o.length-2;t=6;t-=6)for(let i=0;i<6;i+=2)if(isNaN(e[t+i])){l[h]=l[h+1]=NaN;h+=2}else{l[h]=e[t+i];l[h+1]=e[t+i+1];h+=2}this.#ua(l,h);return this.newFreeDrawOutline(l,o,this.#Vn,this.#ta,this.#Wn,this.#qn)}#da(t){const e=this.#Kn,[i,s,n,a]=this.#Vn,[r,o,l,h]=this.#ra(),d=new Float32Array(36);d.set([NaN,NaN,NaN,NaN,(e[2]-i)/n,(e[3]-s)/a,NaN,NaN,NaN,NaN,(e[4]-i)/n,(e[5]-s)/a,NaN,NaN,NaN,NaN,r,o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,(e[16]-i)/n,(e[17]-s)/a,NaN,NaN,NaN,NaN,(e[14]-i)/n,(e[15]-s)/a],0);return this.newFreeDrawOutline(d,t,this.#Vn,this.#ta,this.#Wn,this.#qn)}#ua(t,e){const i=this.#jn;t.set([NaN,NaN,NaN,NaN,i[4],i[5]],e);return e+6}#ca(t,e){const i=this.#Kn.subarray(4,6),s=this.#Kn.subarray(16,18),[n,a,r,o]=this.#Vn,[l,h,d,c]=this.#ra();t.set([NaN,NaN,NaN,NaN,(i[0]-n)/r,(i[1]-a)/o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,d,c,NaN,NaN,NaN,NaN,(s[0]-n)/r,(s[1]-a)/o],e);return e+24}}class FreeDrawOutline extends Outline{#Vn;#pa=new Float32Array(4);#Wn;#qn;#ia;#ta;#ga;constructor(t,e,i,s,n,a){super();this.#ga=t;this.#ia=e;this.#Vn=i;this.#ta=s;this.#Wn=n;this.#qn=a;this.lastPoint=[NaN,NaN];this.#ma(a);const[r,o,l,h]=this.#pa;for(let e=0,i=t.length;et[0]-e[0]||t[1]-e[1]||t[2]-e[2]));const t=[];for(const e of this.#ba)if(e[3]){t.push(...this.#wa(e));this.#va(e)}else{this.#ya(e);t.push(...this.#wa(e))}return this.#xa(t)}#xa(t){const e=[],i=new Set;for(const i of t){const[t,s,n]=i;e.push([t,s,i],[t,n,i])}e.sort(((t,e)=>t[1]-e[1]||t[0]-e[0]));for(let t=0,s=e.length;t0;){const t=i.values().next().value;let[e,a,r,o,l]=t;i.delete(t);let h=e,d=a;n=[e,r];s.push(n);for(;;){let t;if(i.has(o))t=o;else{if(!i.has(l))break;t=l}i.delete(t);[e,a,r,o,l]=t;if(h!==e){n.push(h,d,e,d===a?a:r);h=e}d=d===a?r:a}n.push(h,d)}return new HighlightOutline(s,this.#Vn,this.#fa)}#_a(t){const e=this.#Aa;let i=0,s=e.length-1;for(;i<=s;){const n=i+s>>1,a=e[n][0];if(a===t)return n;a=0;s--){const[i,n]=this.#Aa[s];if(i!==t)break;if(i===t&&n===e){this.#Aa.splice(s,1);return}}}#wa(t){const[e,i,s]=t,n=[[e,i,s]],a=this.#_a(s);for(let t=0;t=i)if(o>s)n[t][1]=s;else{if(1===a)return[];n.splice(t,1);t--;a--}else{n[t][2]=i;o>s&&n.push([e,s,o])}}}return n}}class HighlightOutline extends Outline{#Vn;#Ea;constructor(t,e,i){super();this.#Ea=t;this.#Vn=e;this.lastPoint=i}toSVGPath(){const t=[];for(const e of this.#Ea){let[i,s]=e;t.push(`M${i} ${s}`);for(let n=2;n-1){this.#Xa=!0;this.#Za(t);this.#tr()}else if(this.#Ua){this.#Ha=t.anchorNode;this.#za=t.anchorOffset;this.#Va=t.focusNode;this.#ja=t.focusOffset;this.#er();this.#tr();this.rotate(this.rotation)}}get telemetryInitialData(){return{action:"added",type:this.#Xa?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:this.#ea,methodOfCreation:this.#Ja}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#er(){const t=new HighlightOutliner(this.#Ua,.001);this.#qa=t.getOutlines();[this.x,this.y,this.width,this.height]=this.#qa.box;const e=new HighlightOutliner(this.#Ua,.0025,.001,"ltr"===this._uiManager.direction);this.#$a=e.getOutlines();const{lastPoint:i}=this.#$a;this.#fa=[(i[0]-this.x)/this.width,(i[1]-this.y)/this.height]}#Za({highlightOutlines:t,highlightId:e,clipPathId:i}){this.#qa=t;this.#$a=t.getNewOutline(this.#ea/2+1.5,.0025);if(e>=0){this.#w=e;this.#Ga=i;this.parent.drawLayer.finalizeDraw(e,{bbox:t.box,path:{d:t.toSVGPath()}});this.#Ya=this.parent.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:!0},bbox:this.#$a.box,path:{d:this.#$a.toSVGPath()}},!0)}else if(this.parent){const e=this.parent.viewport.rotation;this.parent.drawLayer.updateProperties(this.#w,{bbox:HighlightEditor.#ir(this.#qa.box,(e-this.rotation+360)%360),path:{d:t.toSVGPath()}});this.parent.drawLayer.updateProperties(this.#Ya,{bbox:HighlightEditor.#ir(this.#$a.box,e),path:{d:this.#$a.toSVGPath()}})}const[s,n,a,r]=t.box;switch(this.rotation){case 0:this.x=s;this.y=n;this.width=a;this.height=r;break;case 90:{const[t,e]=this.parentDimensions;this.x=n;this.y=1-s;this.width=a*e/t;this.height=r*t/e;break}case 180:this.x=1-s;this.y=1-n;this.width=a;this.height=r;break;case 270:{const[t,e]=this.parentDimensions;this.x=1-n;this.y=s;this.width=a*e/t;this.height=r*t/e;break}}const{lastPoint:o}=this.#$a;this.#fa=[(o[0]-s)/a,(o[1]-n)/r]}static initialize(t,e){AnnotationEditor.initialize(t,e);HighlightEditor._defaultColor||=e.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,e){switch(t){case m.HIGHLIGHT_DEFAULT_COLOR:HighlightEditor._defaultColor=e;break;case m.HIGHLIGHT_THICKNESS:HighlightEditor._defaultThickness=e}}translateInPage(t,e){}get toolbarPosition(){return this.#fa}updateParams(t,e){switch(t){case m.HIGHLIGHT_COLOR:this.#On(e);break;case m.HIGHLIGHT_THICKNESS:this.#sr(e)}}static get defaultPropertiesToUpdate(){return[[m.HIGHLIGHT_DEFAULT_COLOR,HighlightEditor._defaultColor],[m.HIGHLIGHT_THICKNESS,HighlightEditor._defaultThickness]]}get propertiesToUpdate(){return[[m.HIGHLIGHT_COLOR,this.color||HighlightEditor._defaultColor],[m.HIGHLIGHT_THICKNESS,this.#ea||HighlightEditor._defaultThickness],[m.HIGHLIGHT_FREE,this.#Xa]]}#On(t){const setColorAndOpacity=(t,e)=>{this.color=t;this.#Ka=e;this.parent?.drawLayer.updateProperties(this.#w,{root:{fill:t,"fill-opacity":e}});this.#n?.updateColor(t)},e=this.color,i=this.#Ka;this.addCommands({cmd:setColorAndOpacity.bind(this,t,HighlightEditor._defaultOpacity),undo:setColorAndOpacity.bind(this,e,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:m.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0});this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(t)},!0)}#sr(t){const e=this.#ea,setThickness=t=>{this.#ea=t;this.#nr(t)};this.addCommands({cmd:setThickness.bind(this,t),undo:setThickness.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:m.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0});this._reportTelemetry({action:"thickness_changed",thickness:t},!0)}async addEditToolbar(){const t=await super.addEditToolbar();if(!t)return null;if(this._uiManager.highlightColors){this.#n=new ColorPicker({editor:this});t.addColorPicker(this.#n)}return t}disableEditing(){super.disableEditing();this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing();this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#ar())}getBaseTranslation(){return[0,0]}getRect(t,e){return super.getRect(t,e,this.#ar())}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this);t&&this.div.focus()}remove(){this.#rr();this._reportTelemetry({action:"deleted"});super.remove()}rebuild(){if(this.parent){super.rebuild();if(null!==this.div){this.#tr();this.isAttachedToDOM||this.parent.add(this)}}}setParent(t){let e=!1;if(this.parent&&!t)this.#rr();else if(t){this.#tr(t);e=!this.parent&&this.div?.classList.contains("selectedEditor")}super.setParent(t);this.show(this._isVisible);e&&this.select()}#nr(t){if(!this.#Xa)return;this.#Za({highlightOutlines:this.#qa.getNewOutline(t/2)});this.fixAndSetPosition();const[e,i]=this.parentDimensions;this.setDims(this.width*e,this.height*i)}#rr(){if(null!==this.#w&&this.parent){this.parent.drawLayer.remove(this.#w);this.#w=null;this.parent.drawLayer.remove(this.#Ya);this.#Ya=null}}#tr(t=this.parent){if(null===this.#w){({id:this.#w,clipPathId:this.#Ga}=t.drawLayer.draw({bbox:this.#qa.box,root:{viewBox:"0 0 1 1",fill:this.color,"fill-opacity":this.#Ka},rootClass:{highlight:!0,free:this.#Xa},path:{d:this.#qa.toSVGPath()}},!1,!0));this.#Ya=t.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:this.#Xa},bbox:this.#$a.box,path:{d:this.#$a.toSVGPath()}},this.#Xa);this.#Wa&&(this.#Wa.style.clipPath=this.#Ga)}}static#ir([t,e,i,s],n){switch(n){case 90:return[1-e-s,t,s,i];case 180:return[1-t-i,1-e-s,i,s];case 270:return[e,1-t-i,s,i]}return[t,e,i,s]}rotate(t){const{drawLayer:e}=this.parent;let i;if(this.#Xa){t=(t-this.rotation+360)%360;i=HighlightEditor.#ir(this.#qa.box,t)}else i=HighlightEditor.#ir([this.x,this.y,this.width,this.height],t);e.updateProperties(this.#w,{bbox:i,root:{"data-main-rotation":t}});e.updateProperties(this.#Ya,{bbox:HighlightEditor.#ir(this.#$a.box,t),root:{"data-main-rotation":t}})}render(){if(this.div)return this.div;const t=super.render();if(this.#Qa){t.setAttribute("aria-label",this.#Qa);t.setAttribute("role","mark")}this.#Xa?t.classList.add("free"):this.div.addEventListener("keydown",this.#or.bind(this),{signal:this._uiManager._signal});const e=this.#Wa=document.createElement("div");t.append(e);e.setAttribute("aria-hidden","true");e.className="internal";e.style.clipPath=this.#Ga;const[i,s]=this.parentDimensions;this.setDims(this.width*i,this.height*s);bindEvents(this,this.#Wa,["pointerover","pointerleave"]);this.enableEditing();return t}pointerover(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#Ya,{rootClass:{hovered:!0}})}pointerleave(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#Ya,{rootClass:{hovered:!1}})}#or(t){HighlightEditor._keyboardManager.exec(this,t)}_moveCaret(t){this.parent.unselect(this);switch(t){case 0:case 2:this.#lr(!0);break;case 1:case 3:this.#lr(!1)}}#lr(t){if(!this.#Ha)return;const e=window.getSelection();t?e.setPosition(this.#Ha,this.#za):e.setPosition(this.#Va,this.#ja)}select(){super.select();this.#Ya&&this.parent?.drawLayer.updateProperties(this.#Ya,{rootClass:{hovered:!1,selected:!0}})}unselect(){super.unselect();if(this.#Ya){this.parent?.drawLayer.updateProperties(this.#Ya,{rootClass:{selected:!1}});this.#Xa||this.#lr(!1)}}get _mustFixPosition(){return!this.#Xa}show(t=this._isVisible){super.show(t);if(this.parent){this.parent.drawLayer.updateProperties(this.#w,{rootClass:{hidden:!t}});this.parent.drawLayer.updateProperties(this.#Ya,{rootClass:{hidden:!t}})}}#ar(){return this.#Xa?this.rotation:0}#hr(){if(this.#Xa)return null;const[t,e]=this.pageDimensions,[i,s]=this.pageTranslation,n=this.#Ua,a=new Float32Array(8*n.length);let r=0;for(const{x:o,y:l,width:h,height:d}of n){const n=o*t+i,c=(1-l)*e+s;a[r]=a[r+4]=n;a[r+1]=a[r+3]=c;a[r+2]=a[r+6]=n+h*t;a[r+5]=a[r+7]=c-d*e;r+=8}return a}#dr(t){return this.#qa.serialize(t,this.#ar())}static startHighlighting(t,e,{target:i,x:s,y:n}){const{x:a,y:r,width:o,height:l}=i.getBoundingClientRect(),h=new AbortController,d=t.combinedSignal(h),pointerUpCallback=e=>{h.abort();this.#cr(t,e)};window.addEventListener("blur",pointerUpCallback,{signal:d});window.addEventListener("pointerup",pointerUpCallback,{signal:d});window.addEventListener("pointerdown",stopEvent,{capture:!0,passive:!1,signal:d});window.addEventListener("contextmenu",noContextMenu,{signal:d});i.addEventListener("pointermove",this.#ur.bind(this,t),{signal:d});this._freeHighlight=new FreeHighlightOutliner({x:s,y:n},[a,r,o,l],t.scale,this._defaultThickness/2,e,.001);({id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=t.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:this._defaultColor,"fill-opacity":this._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:this._freeHighlight.toSVGPath()}},!0,!0))}static#ur(t,e){this._freeHighlight.add(e)&&t.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})}static#cr(t,e){this._freeHighlight.isEmpty()?t.drawLayer.remove(this._freeHighlightId):t.createAndAddNewEditor(e,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"});this._freeHighlightId=-1;this._freeHighlight=null;this._freeHighlightClipId=""}static async deserialize(t,e,i){let s=null;if(t instanceof HighlightAnnotationElement){const{data:{quadPoints:e,rect:i,rotation:n,id:a,color:r,opacity:o,popupRef:l},parent:{page:{pageNumber:h}}}=t;s=t={annotationType:g.HIGHLIGHT,color:Array.from(r),opacity:o,quadPoints:e,boxes:null,pageIndex:h-1,rect:i.slice(0),rotation:n,id:a,deleted:!1,popupRef:l}}else if(t instanceof InkAnnotationElement){const{data:{inkLists:e,rect:i,rotation:n,id:a,color:r,borderStyle:{rawWidth:o},popupRef:l},parent:{page:{pageNumber:h}}}=t;s=t={annotationType:g.HIGHLIGHT,color:Array.from(r),thickness:o,inkLists:e,boxes:null,pageIndex:h-1,rect:i.slice(0),rotation:n,id:a,deleted:!1,popupRef:l}}const{color:n,quadPoints:a,inkLists:r,opacity:o}=t,l=await super.deserialize(t,e,i);l.color=Util.makeHexColor(...n);l.#Ka=o||1;r&&(l.#ea=t.thickness);l.annotationElementId=t.id||null;l._initialData=s;const[h,d]=l.pageDimensions,[c,u]=l.pageTranslation;if(a){const t=l.#Ua=[];for(let e=0;et!==e[i]))}renderAnnotationElement(t){t.updateEdited({rect:this.getRect(0,0)});return null}static canCreateNewEmptyEditor(){return!1}}class DrawingOptions{#pr=Object.create(null);updateProperty(t,e){this[t]=e;this.updateSVGProperty(t,e)}updateProperties(t){if(t)for(const[e,i]of Object.entries(t))this.updateProperty(e,i)}updateSVGProperty(t,e){this.#pr[t]=e}toSVGProperties(){const t=this.#pr;this.#pr=Object.create(null);return{root:t}}reset(){this.#pr=Object.create(null)}updateAll(t=this){this.updateProperties(t)}clone(){unreachable("Not implemented")}}class DrawingEditor extends AnnotationEditor{#gr=null;#mr;_drawId=null;static _currentDrawId=-1;static _currentParent=null;static#fr=null;static#br=null;static#Ar=null;static#wr=NaN;static#vr=null;static#yr=null;static#xr=NaN;static _INNER_MARGIN=3;constructor(t){super(t);this.#mr=t.mustBeCommitted||!1;if(t.drawOutlines){this.#_r(t);this.#tr()}}#_r({drawOutlines:t,drawId:e,drawingOptions:i}){this.#gr=t;this._drawingOptions||=i;if(e>=0){this._drawId=e;this.parent.drawLayer.finalizeDraw(e,t.defaultProperties)}else this._drawId=this.#Er(t,this.parent);this.#Sr(t.box)}#Er(t,e){const{id:i}=e.drawLayer.draw(DrawingEditor._mergeSVGProperties(this._drawingOptions.toSVGProperties(),t.defaultSVGProperties),!1,!1);return i}static _mergeSVGProperties(t,e){const i=new Set(Object.keys(t));for(const[s,n]of Object.entries(e))i.has(s)?Object.assign(t[s],n):t[s]=n;return t}static getDefaultDrawingOptions(t){unreachable("Not implemented")}static get typesMap(){unreachable("Not implemented")}static get isDrawer(){return!0}static get supportMultipleDrawings(){return!1}static updateDefaultParams(t,e){const i=this.typesMap.get(t);i&&this._defaultDrawingOptions.updateProperty(i,e);if(this._currentParent){DrawingEditor.#fr.updateProperty(i,e);this._currentParent.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties())}}updateParams(t,e){const i=this.constructor.typesMap.get(t);i&&this._updateProperty(t,i,e)}static get defaultPropertiesToUpdate(){const t=[],e=this._defaultDrawingOptions;for(const[i,s]of this.typesMap)t.push([i,e[s]]);return t}get propertiesToUpdate(){const t=[],{_drawingOptions:e}=this;for(const[i,s]of this.constructor.typesMap)t.push([i,e[s]]);return t}_updateProperty(t,e,i){const s=this._drawingOptions,n=s[e],setter=t=>{s.updateProperty(e,t);const i=this.#gr.updateProperty(e,t);i&&this.#Sr(i);this.parent?.drawLayer.updateProperties(this._drawId,s.toSVGProperties())};this.addCommands({cmd:setter.bind(this,i),undo:setter.bind(this,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:t,overwriteIfSameType:!0,keepUndo:!0})}_onResizing(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#gr.getPathResizingSVGProperties(this.#Cr()),{bbox:this.#Tr()}))}_onResized(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#gr.getPathResizedSVGProperties(this.#Cr()),{bbox:this.#Tr()}))}_onTranslating(t,e){this.parent?.drawLayer.updateProperties(this._drawId,{bbox:this.#Tr(t,e)})}_onTranslated(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#gr.getPathTranslatedSVGProperties(this.#Cr(),this.parentDimensions),{bbox:this.#Tr()}))}_onStartDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!0}})}_onStopDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!1}})}commit(){super.commit();this.disableEditMode();this.disableEditing()}disableEditing(){super.disableEditing();this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing();this.div.classList.toggle("disabled",!1)}getBaseTranslation(){return[0,0]}get isResizable(){return!0}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this);this._isDraggable=!0;if(this.#mr){this.#mr=!1;this.commit();this.parent.setSelected(this);t&&this.isOnScreen&&this.div.focus()}}remove(){this.#rr();super.remove()}rebuild(){if(this.parent){super.rebuild();if(null!==this.div){this.#tr();this.#Sr(this.#gr.box);this.isAttachedToDOM||this.parent.add(this)}}}setParent(t){let e=!1;if(this.parent&&!t){this._uiManager.removeShouldRescale(this);this.#rr()}else if(t){this._uiManager.addShouldRescale(this);this.#tr(t);e=!this.parent&&this.div?.classList.contains("selectedEditor")}super.setParent(t);e&&this.select()}#rr(){if(null!==this._drawId&&this.parent){this.parent.drawLayer.remove(this._drawId);this._drawId=null;this._drawingOptions.reset()}}#tr(t=this.parent){if(null===this._drawId||this.parent!==t)if(null===this._drawId){this._drawingOptions.updateAll();this._drawId=this.#Er(this.#gr,t)}else this.parent.drawLayer.updateParent(this._drawId,t.drawLayer)}#Mr([t,e,i,s]){const{parentDimensions:[n,a],rotation:r}=this;switch(r){case 90:return[e,1-t,i*(a/n),s*(n/a)];case 180:return[1-t,1-e,i,s];case 270:return[1-e,t,i*(a/n),s*(n/a)];default:return[t,e,i,s]}}#Cr(){const{x:t,y:e,width:i,height:s,parentDimensions:[n,a],rotation:r}=this;switch(r){case 90:return[1-e,t,i*(n/a),s*(a/n)];case 180:return[1-t,1-e,i,s];case 270:return[e,1-t,i*(n/a),s*(a/n)];default:return[t,e,i,s]}}#Sr(t){[this.x,this.y,this.width,this.height]=this.#Mr(t);if(this.div){this.fixAndSetPosition();const[t,e]=this.parentDimensions;this.setDims(this.width*t,this.height*e)}this._onResized()}#Tr(){const{x:t,y:e,width:i,height:s,rotation:n,parentRotation:a,parentDimensions:[r,o]}=this;switch((4*n+a)/90){case 1:return[1-e-s,t,s,i];case 2:return[1-t-i,1-e-s,i,s];case 3:return[e,1-t-i,s,i];case 4:return[t,e-i*(r/o),s*(o/r),i*(r/o)];case 5:return[1-e,t,i*(r/o),s*(o/r)];case 6:return[1-t-s*(o/r),1-e,s*(o/r),i*(r/o)];case 7:return[e-i*(r/o),1-t-s*(o/r),i*(r/o),s*(o/r)];case 8:return[t-i,e-s,i,s];case 9:return[1-e,t-i,s,i];case 10:return[1-t,1-e,i,s];case 11:return[e-s,1-t,s,i];case 12:return[t-s*(o/r),e,s*(o/r),i*(r/o)];case 13:return[1-e-i*(r/o),t-s*(o/r),i*(r/o),s*(o/r)];case 14:return[1-t,1-e-i*(r/o),s*(o/r),i*(r/o)];case 15:return[e,1-t,i*(r/o),s*(o/r)];default:return[t,e,i,s]}}rotate(){this.parent&&this.parent.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties({bbox:this.#Tr()},this.#gr.updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&this.#Sr(this.#gr.updateParentDimensions(this.parentDimensions,this.parent.scale))}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;const t=super.render();t.classList.add("draw");const e=document.createElement("div");t.append(e);e.setAttribute("aria-hidden","true");e.className="internal";const[i,s]=this.parentDimensions;this.setDims(this.width*i,this.height*s);this._uiManager.addShouldRescale(this);this.disableEditing();return t}static createDrawerInstance(t,e,i,s,n){unreachable("Not implemented")}static startDrawing(t,e,i,s){const{target:n,offsetX:a,offsetY:r,pointerId:o,pointerType:l}=s;if(DrawingEditor.#vr&&DrawingEditor.#vr!==l)return;const{viewport:{rotation:h}}=t,{width:d,height:c}=n.getBoundingClientRect(),u=DrawingEditor.#br=new AbortController,p=t.combinedSignal(u);DrawingEditor.#wr||=o;DrawingEditor.#vr??=l;window.addEventListener("pointerup",(t=>{DrawingEditor.#wr===t.pointerId?this._endDraw(t):DrawingEditor.#yr?.delete(t.pointerId)}),{signal:p});window.addEventListener("pointercancel",(t=>{DrawingEditor.#wr===t.pointerId?this._currentParent.endDrawingSession():DrawingEditor.#yr?.delete(t.pointerId)}),{signal:p});window.addEventListener("pointerdown",(t=>{if(DrawingEditor.#vr===t.pointerType){(DrawingEditor.#yr||=new Set).add(t.pointerId);if(DrawingEditor.#fr.isCancellable()){DrawingEditor.#fr.removeLastElement();DrawingEditor.#fr.isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)}}}),{capture:!0,passive:!1,signal:p});window.addEventListener("contextmenu",noContextMenu,{signal:p});n.addEventListener("pointermove",this._drawMove.bind(this),{signal:p});n.addEventListener("touchmove",(t=>{t.timeStamp===DrawingEditor.#xr&&stopEvent(t)}),{signal:p});t.toggleDrawing();e._editorUndoBar?.hide();if(DrawingEditor.#fr)t.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#fr.startNew(a,r,d,c,h));else{e.updateUIForDefaultProperties(this);DrawingEditor.#fr=this.createDrawerInstance(a,r,d,c,h);DrawingEditor.#Ar=this.getDefaultDrawingOptions();this._currentParent=t;({id:this._currentDrawId}=t.drawLayer.draw(this._mergeSVGProperties(DrawingEditor.#Ar.toSVGProperties(),DrawingEditor.#fr.defaultSVGProperties),!0,!1))}}static _drawMove(t){DrawingEditor.#xr=-1;if(!DrawingEditor.#fr)return;const{offsetX:e,offsetY:i,pointerId:s}=t;if(DrawingEditor.#wr===s)if(DrawingEditor.#yr?.size>=1)this._endDraw(t);else{this._currentParent.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#fr.add(e,i));DrawingEditor.#xr=t.timeStamp;stopEvent(t)}}static _cleanup(t){if(t){this._currentDrawId=-1;this._currentParent=null;DrawingEditor.#fr=null;DrawingEditor.#Ar=null;DrawingEditor.#vr=null;DrawingEditor.#xr=NaN}if(DrawingEditor.#br){DrawingEditor.#br.abort();DrawingEditor.#br=null;DrawingEditor.#wr=NaN;DrawingEditor.#yr=null}}static _endDraw(t){const e=this._currentParent;if(e){e.toggleDrawing(!0);this._cleanup(!1);t&&e.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#fr.end(t.offsetX,t.offsetY));if(this.supportMultipleDrawings){const t=DrawingEditor.#fr,i=this._currentDrawId,s=t.getLastElement();e.addCommands({cmd:()=>{e.drawLayer.updateProperties(i,t.setLastElement(s))},undo:()=>{e.drawLayer.updateProperties(i,t.removeLastElement())},mustExec:!1,type:m.DRAW_STEP})}else this.endDrawing(!1)}}static endDrawing(t){const e=this._currentParent;if(!e)return null;e.toggleDrawing(!0);e.cleanUndoStack(m.DRAW_STEP);if(!DrawingEditor.#fr.isEmpty()){const{pageDimensions:[i,s],scale:n}=e,a=e.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:DrawingEditor.#fr.getOutlines(i*n,s*n,n,this._INNER_MARGIN),drawingOptions:DrawingEditor.#Ar,mustBeCommitted:!t});this._cleanup(!0);return a}e.drawLayer.remove(this._currentDrawId);this._cleanup(!0);return null}createDrawingOptions(t){}static deserializeDraw(t,e,i,s,n,a){unreachable("Not implemented")}static async deserialize(t,e,i){const{rawDims:{pageWidth:s,pageHeight:n,pageX:a,pageY:r}}=e.viewport,o=this.deserializeDraw(a,r,s,n,this._INNER_MARGIN,t),l=await super.deserialize(t,e,i);l.createDrawingOptions(t);l.#_r({drawOutlines:o});l.#tr();l.onScaleChanging();l.rotate();return l}serializeDraw(t){const[e,i]=this.pageTranslation,[s,n]=this.pageDimensions;return this.#gr.serialize([e,i,s,n],t)}renderAnnotationElement(t){t.updateEdited({rect:this.getRect(0,0)});return null}static canCreateNewEmptyEditor(){return!1}}class InkDrawOutliner{#Kn=new Float64Array(6);#bn;#Pr;#Fi;#ea;#ia;#Dr="";#kr=0;#Ea=new InkDrawOutline;#Rr;#Ir;constructor(t,e,i,s,n,a){this.#Rr=i;this.#Ir=s;this.#Fi=n;this.#ea=a;[t,e]=this.#Fr(t,e);const r=this.#bn=[NaN,NaN,NaN,NaN,t,e];this.#ia=[t,e];this.#Pr=[{line:r,points:this.#ia}];this.#Kn.set(r,0)}updateProperty(t,e){"stroke-width"===t&&(this.#ea=e)}#Fr(t,e){return Outline._normalizePoint(t,e,this.#Rr,this.#Ir,this.#Fi)}isEmpty(){return!this.#Pr||0===this.#Pr.length}isCancellable(){return this.#ia.length<=10}add(t,e){[t,e]=this.#Fr(t,e);const[i,s,n,a]=this.#Kn.subarray(2,6),r=t-n,o=e-a;if(Math.hypot(this.#Rr*r,this.#Ir*o)<=2)return null;this.#ia.push(t,e);if(isNaN(i)){this.#Kn.set([n,a,t,e],2);this.#bn.push(NaN,NaN,NaN,NaN,t,e);return{path:{d:this.toSVGPath()}}}isNaN(this.#Kn[0])&&this.#bn.splice(6,6);this.#Kn.set([i,s,n,a,t,e],0);this.#bn.push(...Outline.createBezierPoints(i,s,n,a,t,e));return{path:{d:this.toSVGPath()}}}end(t,e){const i=this.add(t,e);return i||(2===this.#ia.length?{path:{d:this.toSVGPath()}}:null)}startNew(t,e,i,s,n){this.#Rr=i;this.#Ir=s;this.#Fi=n;[t,e]=this.#Fr(t,e);const a=this.#bn=[NaN,NaN,NaN,NaN,t,e];this.#ia=[t,e];const r=this.#Pr.at(-1);if(r){r.line=new Float32Array(r.line);r.points=new Float32Array(r.points)}this.#Pr.push({line:a,points:this.#ia});this.#Kn.set(a,0);this.#kr=0;this.toSVGPath();return null}getLastElement(){return this.#Pr.at(-1)}setLastElement(t){if(!this.#Pr)return this.#Ea.setLastElement(t);this.#Pr.push(t);this.#bn=t.line;this.#ia=t.points;this.#kr=0;return{path:{d:this.toSVGPath()}}}removeLastElement(){if(!this.#Pr)return this.#Ea.removeLastElement();this.#Pr.pop();this.#Dr="";for(let t=0,e=this.#Pr.length;tt??NaN)),d,c,u,p),points:g(r[t].map((t=>t??NaN)),d,c,u,p)});const m=new InkDrawOutline;m.build(h,i,s,1,o,l,n);return m}#Hr(t=this.#ea){const e=this.#Wn+t/2*this.#Or;return this.#Fi%180==0?[e/this.#Rr,e/this.#Ir]:[e/this.#Ir,e/this.#Rr]}#Br(){const[t,e,i,s]=this.#pa,[n,a]=this.#Hr(0);return[t+n,e+a,i-2*n,s-2*a]}#Nr(){const t=this.#pa=new Float32Array([1/0,1/0,-1/0,-1/0]);for(const{line:e}of this.#Pr){if(e.length<=12){for(let i=4,s=e.length;it!==e[i]))||t.thickness!==i||t.opacity!==s||t.pageIndex!==n}renderAnnotationElement(t){const{points:e,rect:i}=this.serializeDraw(!1);t.updateEdited({rect:i,thickness:this._drawingOptions["stroke-width"],points:e});return null}}class StampEditor extends AnnotationEditor{#Ur=null;#Gr=null;#$r=null;#Vr=null;#jr=null;#Wr="";#qr=null;#Xr=null;#Kr=!1;#Yr=!1;static _type="stamp";static _editorType=g.STAMP;constructor(t){super({...t,name:"stampEditor"});this.#Vr=t.bitmapUrl;this.#jr=t.bitmapFile}static initialize(t,e){AnnotationEditor.initialize(t,e)}static get supportedTypes(){return shadow(this,"supportedTypes",["apng","avif","bmp","gif","jpeg","png","svg+xml","webp","x-icon"].map((t=>`image/${t}`)))}static get supportedTypesStr(){return shadow(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(t){return this.supportedTypes.includes(t)}static paste(t,e){e.pasteEditor(g.STAMP,{bitmapFile:t.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1);super.altTextFinish()}get telemetryFinalData(){return{type:"stamp",hasAltText:!!this.altTextData?.altText}}static computeTelemetryFinalData(t){const e=t.get("hasAltText");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}#Qr(t,e=!1){if(t){this.#Ur=t.bitmap;if(!e){this.#Gr=t.id;this.#Kr=t.isSvg}t.file&&(this.#Wr=t.file.name);this.#Jr()}else this.remove()}#Zr(){this.#$r=null;this._uiManager.enableWaiting(!1);if(this.#qr)if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#Ur){this._editToolbar.hide();this._uiManager.editAltText(this,!0)}else{if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#Ur){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}}async mlGuessAltText(t=null,e=!0){if(this.hasAltTextData())return null;const{mlManager:i}=this._uiManager;if(!i)throw new Error("No ML.");if(!await i.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:s,width:n,height:a}=t||this.copyCanvas(null,null,!0).imageData,r=await i.guess({name:"altText",request:{data:s,width:n,height:a,channels:s.length/(n*a)}});if(!r)throw new Error("No response from the AI service.");if(r.error)throw new Error("Error from the AI service.");if(r.cancel)return null;if(!r.output)throw new Error("No valid response from the AI service.");const o=r.output;await this.setGuessedAltText(o);e&&!this.hasAltTextData()&&(this.altTextData={alt:o,decorative:!1});return o}#to(){if(this.#Gr){this._uiManager.enableWaiting(!0);this._uiManager.imageManager.getFromId(this.#Gr).then((t=>this.#Qr(t,!0))).finally((()=>this.#Zr()));return}if(this.#Vr){const t=this.#Vr;this.#Vr=null;this._uiManager.enableWaiting(!0);this.#$r=this._uiManager.imageManager.getFromUrl(t).then((t=>this.#Qr(t))).finally((()=>this.#Zr()));return}if(this.#jr){const t=this.#jr;this.#jr=null;this._uiManager.enableWaiting(!0);this.#$r=this._uiManager.imageManager.getFromFile(t).then((t=>this.#Qr(t))).finally((()=>this.#Zr()));return}const t=document.createElement("input");t.type="file";t.accept=StampEditor.supportedTypesStr;const e=this._uiManager._signal;this.#$r=new Promise((i=>{t.addEventListener("change",(async()=>{if(t.files&&0!==t.files.length){this._uiManager.enableWaiting(!0);const e=await this._uiManager.imageManager.getFromFile(t.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}});this.#Qr(e)}else this.remove();i()}),{signal:e});t.addEventListener("cancel",(()=>{this.remove();i()}),{signal:e})})).finally((()=>this.#Zr()));t.click()}remove(){if(this.#Gr){this.#Ur=null;this._uiManager.imageManager.deleteId(this.#Gr);this.#qr?.remove();this.#qr=null;if(this.#Xr){clearTimeout(this.#Xr);this.#Xr=null}}super.remove()}rebuild(){if(this.parent){super.rebuild();if(null!==this.div){this.#Gr&&null===this.#qr&&this.#to();this.isAttachedToDOM||this.parent.add(this)}}else this.#Gr&&this.#to()}onceAdded(t){this._isDraggable=!0;t&&this.div.focus()}isEmpty(){return!(this.#$r||this.#Ur||this.#Vr||this.#jr||this.#Gr)}get isResizable(){return!0}render(){if(this.div)return this.div;let t,e;if(this.width){t=this.x;e=this.y}super.render();this.div.hidden=!0;this.div.setAttribute("role","figure");this.addAltTextButton();this.#Ur?this.#Jr():this.#to();if(this.width&&!this.annotationElementId){const[i,s]=this.parentDimensions;this.setAt(t*i,e*s,this.width*i,this.height*s)}this._uiManager.addShouldRescale(this);return this.div}_onResized(){this.onScaleChanging()}onScaleChanging(){if(!this.parent)return;null!==this.#Xr&&clearTimeout(this.#Xr);this.#Xr=setTimeout((()=>{this.#Xr=null;this.#eo()}),200)}#Jr(){const{div:t}=this;let{width:e,height:i}=this.#Ur;const[s,n]=this.pageDimensions,a=.75;if(this.width){e=this.width*s;i=this.height*n}else if(e>a*s||i>a*n){const t=Math.min(a*s/e,a*n/i);e*=t;i*=t}const[r,o]=this.parentDimensions;this.setDims(e*r/s,i*o/n);this._uiManager.enableWaiting(!1);const l=this.#qr=document.createElement("canvas");l.setAttribute("role","img");this.addContainer(l);this.width=e/s;this.height=i/n;this._initialOptions?.isCentered?this.center():this.fixAndSetPosition();this._initialOptions=null;this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&!this.annotationElementId||(t.hidden=!1);this.#eo();if(!this.#Yr){this.parent.addUndoableEditor(this);this.#Yr=!0}this._reportTelemetry({action:"inserted_image"});this.#Wr&&l.setAttribute("aria-label",this.#Wr)}copyCanvas(t,e,i=!1){t||(t=224);const{width:s,height:n}=this.#Ur,a=new OutputScale;let r=this.#Ur,o=s,l=n,h=null;if(e){if(s>e||n>e){const t=Math.min(e/s,e/n);o=Math.floor(s*t);l=Math.floor(n*t)}h=document.createElement("canvas");const t=h.width=Math.ceil(o*a.sx),i=h.height=Math.ceil(l*a.sy);this.#Kr||(r=this.#io(t,i));const d=h.getContext("2d");d.filter=this._uiManager.hcmFilter;let c="white",u="#cfcfd8";if("none"!==this._uiManager.hcmFilter)u="black";else if(window.matchMedia?.("(prefers-color-scheme: dark)").matches){c="#8f8f9d";u="#42414d"}const p=15,g=p*a.sx,m=p*a.sy,f=new OffscreenCanvas(2*g,2*m),b=f.getContext("2d");b.fillStyle=c;b.fillRect(0,0,2*g,2*m);b.fillStyle=u;b.fillRect(0,0,g,m);b.fillRect(g,m,g,m);d.fillStyle=d.createPattern(f,"repeat");d.fillRect(0,0,t,i);d.drawImage(r,0,0,r.width,r.height,0,0,t,i)}let d=null;if(i){let e,i;if(a.symmetric&&r.widtht||n>t){const a=Math.min(t/s,t/n);e=Math.floor(s*a);i=Math.floor(n*a);this.#Kr||(r=this.#io(e,i))}}const o=new OffscreenCanvas(e,i).getContext("2d",{willReadFrequently:!0});o.drawImage(r,0,0,r.width,r.height,0,0,e,i);d={width:e,height:i,data:o.getImageData(0,0,e,i).data}}return{canvas:h,width:o,height:l,imageData:d}}#io(t,e){const{width:i,height:s}=this.#Ur;let n=i,a=s,r=this.#Ur;for(;n>2*t||a>2*e;){const i=n,s=a;n>2*t&&(n=n>=16384?Math.floor(n/2)-1:Math.ceil(n/2));a>2*e&&(a=a>=16384?Math.floor(a/2)-1:Math.ceil(a/2));const o=new OffscreenCanvas(n,a);o.getContext("2d").drawImage(r,0,0,i,s,0,0,n,a);r=o.transferToImageBitmap()}return r}#eo(){const[t,e]=this.parentDimensions,{width:i,height:s}=this,n=new OutputScale,a=Math.ceil(i*t*n.sx),r=Math.ceil(s*e*n.sy),o=this.#qr;if(!o||o.width===a&&o.height===r)return;o.width=a;o.height=r;const l=this.#Kr?this.#Ur:this.#io(a,r),h=o.getContext("2d");h.filter=this._uiManager.hcmFilter;h.drawImage(l,0,0,l.width,l.height,0,0,a,r)}getImageForAltText(){return this.#qr}#so(t){if(t){if(this.#Kr){const t=this._uiManager.imageManager.getSvgUrl(this.#Gr);if(t)return t}const t=document.createElement("canvas");({width:t.width,height:t.height}=this.#Ur);t.getContext("2d").drawImage(this.#Ur,0,0);return t.toDataURL()}if(this.#Kr){const[t,e]=this.pageDimensions,i=Math.round(this.width*t*PixelsPerInch.PDF_TO_CSS_UNITS),s=Math.round(this.height*e*PixelsPerInch.PDF_TO_CSS_UNITS),n=new OffscreenCanvas(i,s);n.getContext("2d").drawImage(this.#Ur,0,0,this.#Ur.width,this.#Ur.height,0,0,i,s);return n.transferToImageBitmap()}return structuredClone(this.#Ur)}static async deserialize(t,e,i){let s=null;if(t instanceof StampAnnotationElement){const{data:{rect:n,rotation:a,id:r,structParent:o,popupRef:l},container:h,parent:{page:{pageNumber:d}}}=t,c=h.querySelector("canvas"),u=i.imageManager.getFromCanvas(h.id,c);c.remove();const p=(await e._structTree.getAriaAttributes(`${et}${r}`))?.get("aria-label")||"";s=t={annotationType:g.STAMP,bitmapId:u.id,bitmap:u.bitmap,pageIndex:d-1,rect:n.slice(0),rotation:a,id:r,deleted:!1,accessibilityData:{decorative:!1,altText:p},isSvg:!1,structParent:o,popupRef:l}}const n=await super.deserialize(t,e,i),{rect:a,bitmap:r,bitmapUrl:o,bitmapId:l,isSvg:h,accessibilityData:d}=t;if(l&&i.imageManager.isValidId(l)){n.#Gr=l;r&&(n.#Ur=r)}else n.#Vr=o;n.#Kr=h;const[c,u]=n.pageDimensions;n.width=(a[2]-a[0])/c;n.height=(a[3]-a[1])/u;n.annotationElementId=t.id||null;d&&(n.altTextData=d);n._initialData=s;n.#Yr=!!s;return n}serialize(t=!1,e=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const i={annotationType:g.STAMP,bitmapId:this.#Gr,pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:this.#Kr,structTreeParentId:this._structTreeParentId};if(t){i.bitmapUrl=this.#so(!0);i.accessibilityData=this.serializeAltText(!0);return i}const{decorative:s,altText:n}=this.serializeAltText(!1);!s&&n&&(i.accessibilityData={type:"Figure",alt:n});if(this.annotationElementId){const t=this.#$n(i);if(t.isSame)return null;t.isSameAltText?delete i.accessibilityData:i.accessibilityData.structParent=this._initialData.structParent??-1}i.id=this.annotationElementId;if(null===e)return i;e.stamps||=new Map;const a=this.#Kr?(i.rect[2]-i.rect[0])*(i.rect[3]-i.rect[1]):null;if(e.stamps.has(this.#Gr)){if(this.#Kr){const t=e.stamps.get(this.#Gr);if(a>t.area){t.area=a;t.serialized.bitmap.close();t.serialized.bitmap=this.#so(!1)}}}else{e.stamps.set(this.#Gr,{area:a,serialized:i});i.bitmap=this.#so(!1)}return i}#$n(t){const{pageIndex:e,accessibilityData:{altText:i}}=this._initialData,s=t.pageIndex===e,n=(t.accessibilityData?.alt||"")===i;return{isSame:!this._hasBeenMoved&&!this._hasBeenResized&&s&&n,isSameAltText:n}}renderAnnotationElement(t){t.updateEdited({rect:this.getRect(0,0)});return null}}class AnnotationEditorLayer{#Cn;#no=!1;#ao=null;#ro=null;#oo=null;#lo=new Map;#ho=!1;#do=!1;#co=!1;#uo=null;#po=null;#go=null;#mo=null;#m;static _initialized=!1;static#U=new Map([FreeTextEditor,InkEditor,StampEditor,HighlightEditor].map((t=>[t._editorType,t])));constructor({uiManager:t,pageIndex:e,div:i,structTreeLayer:s,accessibilityManager:n,annotationLayer:a,drawLayer:r,textLayer:o,viewport:l,l10n:h}){const d=[...AnnotationEditorLayer.#U.values()];if(!AnnotationEditorLayer._initialized){AnnotationEditorLayer._initialized=!0;for(const e of d)e.initialize(h,t)}t.registerEditorTypes(d);this.#m=t;this.pageIndex=e;this.div=i;this.#Cn=n;this.#ao=a;this.viewport=l;this.#go=o;this.drawLayer=r;this._structTree=s;this.#m.addLayer(this)}get isEmpty(){return 0===this.#lo.size}get isInvisible(){return this.isEmpty&&this.#m.getMode()===g.NONE}updateToolbar(t){this.#m.updateToolbar(t)}updateMode(t=this.#m.getMode()){this.#fo();switch(t){case g.NONE:this.disableTextSelection();this.togglePointerEvents(!1);this.toggleAnnotationLayerPointerEvents(!0);this.disableClick();return;case g.INK:this.disableTextSelection();this.togglePointerEvents(!0);this.enableClick();break;case g.HIGHLIGHT:this.enableTextSelection();this.togglePointerEvents(!1);this.disableClick();break;default:this.disableTextSelection();this.togglePointerEvents(!0);this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);const{classList:e}=this.div;for(const i of AnnotationEditorLayer.#U.values())e.toggle(`${i._type}Editing`,t===i._editorType);this.div.hidden=!1}hasTextLayer(t){return t===this.#go?.div}setEditingState(t){this.#m.setEditingState(t)}addCommands(t){this.#m.addCommands(t)}cleanUndoStack(t){this.#m.cleanUndoStack(t)}toggleDrawing(t=!1){this.div.classList.toggle("drawing",!t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){this.#ao?.div.classList.toggle("disabled",!t)}async enable(){this.#co=!0;this.div.tabIndex=0;this.togglePointerEvents(!0);const t=new Set;for(const e of this.#lo.values()){e.enableEditing();e.show(!0);if(e.annotationElementId){this.#m.removeChangedExistingAnnotation(e);t.add(e.annotationElementId)}}if(!this.#ao){this.#co=!1;return}const e=this.#ao.getEditableAnnotations();for(const i of e){i.hide();if(this.#m.isDeletedAnnotationElement(i.data.id))continue;if(t.has(i.data.id))continue;const e=await this.deserialize(i);if(e){this.addOrRebuild(e);e.enableEditing()}}this.#co=!1}disable(){this.#do=!0;this.div.tabIndex=-1;this.togglePointerEvents(!1);const t=new Map,e=new Map;for(const i of this.#lo.values()){i.disableEditing();if(i.annotationElementId)if(null===i.serialize()){e.set(i.annotationElementId,i);this.getEditableAnnotation(i.annotationElementId)?.show();i.remove()}else t.set(i.annotationElementId,i)}if(this.#ao){const i=this.#ao.getEditableAnnotations();for(const s of i){const{id:i}=s.data;if(this.#m.isDeletedAnnotationElement(i))continue;let n=e.get(i);if(n){n.resetAnnotationElement(s);n.show(!1);s.show()}else{n=t.get(i);if(n){this.#m.addChangedExistingAnnotation(n);n.renderAnnotationElement(s)&&n.show(!1)}s.show()}}}this.#fo();this.isEmpty&&(this.div.hidden=!0);const{classList:i}=this.div;for(const t of AnnotationEditorLayer.#U.values())i.remove(`${t._type}Editing`);this.disableTextSelection();this.toggleAnnotationLayerPointerEvents(!0);this.#do=!1}getEditableAnnotation(t){return this.#ao?.getEditableAnnotation(t)||null}setActiveEditor(t){this.#m.getActive()!==t&&this.#m.setActiveEditor(t)}enableTextSelection(){this.div.tabIndex=-1;if(this.#go?.div&&!this.#mo){this.#mo=new AbortController;const t=this.#m.combinedSignal(this.#mo);this.#go.div.addEventListener("pointerdown",this.#bo.bind(this),{signal:t});this.#go.div.classList.add("highlighting")}}disableTextSelection(){this.div.tabIndex=0;if(this.#go?.div&&this.#mo){this.#mo.abort();this.#mo=null;this.#go.div.classList.remove("highlighting")}}#bo(t){this.#m.unselectAll();const{target:e}=t;if(e===this.#go.div||("img"===e.getAttribute("role")||e.classList.contains("endOfContent"))&&this.#go.div.contains(e)){const{isMac:e}=util_FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)return;this.#m.showAllEditors("highlight",!0,!0);this.#go.div.classList.add("free");this.toggleDrawing();HighlightEditor.startHighlighting(this,"ltr"===this.#m.direction,{target:this.#go.div,x:t.x,y:t.y});this.#go.div.addEventListener("pointerup",(()=>{this.#go.div.classList.remove("free");this.toggleDrawing(!0)}),{once:!0,signal:this.#m._signal});t.preventDefault()}}enableClick(){if(this.#ro)return;this.#ro=new AbortController;const t=this.#m.combinedSignal(this.#ro);this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t});const e=this.pointerup.bind(this);this.div.addEventListener("pointerup",e,{signal:t});this.div.addEventListener("pointercancel",e,{signal:t})}disableClick(){this.#ro?.abort();this.#ro=null}attach(t){this.#lo.set(t.id,t);const{annotationElementId:e}=t;e&&this.#m.isDeletedAnnotationElement(e)&&this.#m.removeDeletedAnnotationElement(t)}detach(t){this.#lo.delete(t.id);this.#Cn?.removePointerInTextLayer(t.contentDiv);!this.#do&&t.annotationElementId&&this.#m.addDeletedAnnotationElement(t)}remove(t){this.detach(t);this.#m.removeEditor(t);t.div.remove();t.isAttachedToDOM=!1}changeParent(t){if(t.parent!==this){if(t.parent&&t.annotationElementId){this.#m.addDeletedAnnotationElement(t.annotationElementId);AnnotationEditor.deleteAnnotationElement(t);t.annotationElementId=null}this.attach(t);t.parent?.detach(t);t.setParent(this);if(t.div&&t.isAttachedToDOM){t.div.remove();this.div.append(t.div)}}}add(t){if(t.parent!==this||!t.isAttachedToDOM){this.changeParent(t);this.#m.addEditor(t);this.attach(t);if(!t.isAttachedToDOM){const e=t.render();this.div.append(e);t.isAttachedToDOM=!0}t.fixAndSetPosition();t.onceAdded(!this.#co);this.#m.addToAnnotationStorage(t);t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){if(!t.isAttachedToDOM)return;const{activeElement:e}=document;if(t.div.contains(e)&&!this.#oo){t._focusEventsAllowed=!1;this.#oo=setTimeout((()=>{this.#oo=null;if(t.div.contains(document.activeElement))t._focusEventsAllowed=!0;else{t.div.addEventListener("focusin",(()=>{t._focusEventsAllowed=!0}),{once:!0,signal:this.#m._signal});e.focus()}}),0)}t._structTreeParentId=this.#Cn?.moveElementInDOM(this.div,t.div,t.contentDiv,!0)}addOrRebuild(t){if(t.needsToBeRebuilt()){t.parent||=this;t.rebuild();t.show()}else this.add(t)}addUndoableEditor(t){this.addCommands({cmd:()=>t._uiManager.rebuild(t),undo:()=>{t.remove()},mustExec:!1})}getNextId(){return this.#m.getId()}get#Ao(){return AnnotationEditorLayer.#U.get(this.#m.getMode())}combinedSignal(t){return this.#m.combinedSignal(t)}#wo(t){const e=this.#Ao;return e?new e.prototype.constructor(t):null}canCreateNewEmptyEditor(){return this.#Ao?.canCreateNewEmptyEditor()}pasteEditor(t,e){this.#m.updateToolbar(t);this.#m.updateMode(t);const{offsetX:i,offsetY:s}=this.#vo(),n=this.getNextId(),a=this.#wo({parent:this,id:n,x:i,y:s,uiManager:this.#m,isCentered:!0,...e});a&&this.add(a)}async deserialize(t){return await(AnnotationEditorLayer.#U.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#m))||null}createAndAddNewEditor(t,e,i={}){const s=this.getNextId(),n=this.#wo({parent:this,id:s,x:t.offsetX,y:t.offsetY,uiManager:this.#m,isCentered:e,...i});n&&this.add(n);return n}#vo(){const{x:t,y:e,width:i,height:s}=this.div.getBoundingClientRect(),n=Math.max(0,t),a=Math.max(0,e),r=(n+Math.min(window.innerWidth,t+i))/2-t,o=(a+Math.min(window.innerHeight,e+s))/2-e,[l,h]=this.viewport.rotation%180==0?[r,o]:[o,r];return{offsetX:l,offsetY:h}}addNewEditor(){this.createAndAddNewEditor(this.#vo(),!0)}setSelected(t){this.#m.setSelected(t)}toggleSelected(t){this.#m.toggleSelected(t)}unselect(t){this.#m.unselect(t)}pointerup(t){const{isMac:e}=util_FeatureTest.platform;if(!(0!==t.button||t.ctrlKey&&e)&&t.target===this.div&&this.#ho){this.#ho=!1;this.#Ao?.isDrawer&&this.#Ao.supportMultipleDrawings||(this.#no?this.#m.getMode()!==g.STAMP?this.createAndAddNewEditor(t,!1):this.#m.unselectAll():this.#no=!0)}}pointerdown(t){this.#m.getMode()===g.HIGHLIGHT&&this.enableTextSelection();if(this.#ho){this.#ho=!1;return}const{isMac:e}=util_FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)return;if(t.target!==this.div)return;this.#ho=!0;if(this.#Ao?.isDrawer){this.startDrawingSession(t);return}const i=this.#m.getActive();this.#no=!i||i.isEmpty()}startDrawingSession(t){this.div.focus();if(this.#uo){this.#Ao.startDrawing(this,this.#m,!1,t);return}this.#m.setCurrentDrawingSession(this);this.#uo=new AbortController;const e=this.#m.combinedSignal(this.#uo);this.div.addEventListener("blur",(({relatedTarget:t})=>{if(t&&!this.div.contains(t)){this.#po=null;this.commitOrRemove()}}),{signal:e});this.#Ao.startDrawing(this,this.#m,!1,t)}pause(t){if(t){const{activeElement:t}=document;this.div.contains(t)&&(this.#po=t)}else this.#po&&setTimeout((()=>{this.#po?.focus();this.#po=null}),0)}endDrawingSession(t=!1){if(!this.#uo)return null;this.#m.setCurrentDrawingSession(null);this.#uo.abort();this.#uo=null;this.#po=null;return this.#Ao.endDrawing(t)}findNewParent(t,e,i){const s=this.#m.findParent(e,i);if(null===s||s===this)return!1;s.changeParent(t);return!0}commitOrRemove(){if(this.#uo){this.endDrawingSession();return!0}return!1}onScaleChanging(){this.#uo&&this.#Ao.onScaleChangingWhenDrawing(this)}destroy(){this.commitOrRemove();if(this.#m.getActive()?.parent===this){this.#m.commitOrRemove();this.#m.setActiveEditor(null)}if(this.#oo){clearTimeout(this.#oo);this.#oo=null}for(const t of this.#lo.values()){this.#Cn?.removePointerInTextLayer(t.contentDiv);t.setParent(null);t.isAttachedToDOM=!1;t.div.remove()}this.div=null;this.#lo.clear();this.#m.removeLayer(this)}#fo(){for(const t of this.#lo.values())t.isEmpty()&&t.remove()}render({viewport:t}){this.viewport=t;setLayerDimensions(this.div,t);for(const t of this.#m.getEditors(this.pageIndex)){this.add(t);t.rebuild()}this.updateMode()}update({viewport:t}){this.#m.commitOrRemove();this.#fo();const e=this.viewport.rotation,i=t.rotation;this.viewport=t;setLayerDimensions(this.div,{rotation:i});if(e!==i)for(const t of this.#lo.values())t.rotate(i)}get pageDimensions(){const{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return this.#m.viewParameters.realScale}}class DrawLayer{#nn=null;#w=0;#yo=new Map;#xo=new Map;constructor({pageIndex:t}){this.pageIndex=t}setParent(t){if(this.#nn){if(this.#nn!==t){if(this.#yo.size>0)for(const e of this.#yo.values()){e.remove();t.append(e)}this.#nn=t}}else this.#nn=t}static get _svgFactory(){return shadow(this,"_svgFactory",new DOMSVGFactory)}static#_o(t,[e,i,s,n]){const{style:a}=t;a.top=100*i+"%";a.left=100*e+"%";a.width=100*s+"%";a.height=100*n+"%"}#Eo(){const t=DrawLayer._svgFactory.create(1,1,!0);this.#nn.append(t);t.setAttribute("aria-hidden",!0);return t}#So(t,e){const i=DrawLayer._svgFactory.createElement("clipPath");t.append(i);const s=`clip_${e}`;i.setAttribute("id",s);i.setAttribute("clipPathUnits","objectBoundingBox");const n=DrawLayer._svgFactory.createElement("use");i.append(n);n.setAttribute("href",`#${e}`);n.classList.add("clip");return s}#Co(t,e){for(const[i,s]of Object.entries(e))null===s?t.removeAttribute(i):t.setAttribute(i,s)}draw(t,e=!1,i=!1){const s=this.#w++,n=this.#Eo(),a=DrawLayer._svgFactory.createElement("defs");n.append(a);const r=DrawLayer._svgFactory.createElement("path");a.append(r);const o=`path_p${this.pageIndex}_${s}`;r.setAttribute("id",o);r.setAttribute("vector-effect","non-scaling-stroke");e&&this.#xo.set(s,r);const l=i?this.#So(a,o):null,h=DrawLayer._svgFactory.createElement("use");n.append(h);h.setAttribute("href",`#${o}`);this.updateProperties(n,t);this.#yo.set(s,n);return{id:s,clipPathId:`url(#${l})`}}drawOutline(t,e){const i=this.#w++,s=this.#Eo(),n=DrawLayer._svgFactory.createElement("defs");s.append(n);const a=DrawLayer._svgFactory.createElement("path");n.append(a);const r=`path_p${this.pageIndex}_${i}`;a.setAttribute("id",r);a.setAttribute("vector-effect","non-scaling-stroke");let o;if(e){const t=DrawLayer._svgFactory.createElement("mask");n.append(t);o=`mask_p${this.pageIndex}_${i}`;t.setAttribute("id",o);t.setAttribute("maskUnits","objectBoundingBox");const e=DrawLayer._svgFactory.createElement("rect");t.append(e);e.setAttribute("width","1");e.setAttribute("height","1");e.setAttribute("fill","white");const s=DrawLayer._svgFactory.createElement("use");t.append(s);s.setAttribute("href",`#${r}`);s.setAttribute("stroke","none");s.setAttribute("fill","black");s.setAttribute("fill-rule","nonzero");s.classList.add("mask")}const l=DrawLayer._svgFactory.createElement("use");s.append(l);l.setAttribute("href",`#${r}`);o&&l.setAttribute("mask",`url(#${o})`);const h=l.cloneNode();s.append(h);l.classList.add("mainOutline");h.classList.add("secondaryOutline");this.updateProperties(s,t);this.#yo.set(i,s);return i}finalizeDraw(t,e){this.#xo.delete(t);this.updateProperties(t,e)}updateProperties(t,e){if(!e)return;const{root:i,bbox:s,rootClass:n,path:a}=e,r="number"==typeof t?this.#yo.get(t):t;if(r){i&&this.#Co(r,i);s&&DrawLayer.#_o(r,s);if(n){const{classList:t}=r;for(const[e,i]of Object.entries(n))t.toggle(e,i)}if(a){const t=r.firstChild.firstChild;this.#Co(t,a)}}}updateParent(t,e){if(e===this)return;const i=this.#yo.get(t);if(i){e.#nn.append(i);this.#yo.delete(t);e.#yo.set(t,i)}}remove(t){this.#xo.delete(t);if(null!==this.#nn){this.#yo.get(t).remove();this.#yo.delete(t)}}destroy(){this.#nn=null;for(const t of this.#yo.values())t.remove();this.#yo.clear();this.#xo.clear()}}globalThis.pdfjsTestingUtils={HighlightOutliner};var Ut=__webpack_exports__.AbortException,Gt=__webpack_exports__.AnnotationEditorLayer,$t=__webpack_exports__.AnnotationEditorParamsType,Vt=__webpack_exports__.AnnotationEditorType,jt=__webpack_exports__.AnnotationEditorUIManager,Wt=__webpack_exports__.AnnotationLayer,qt=__webpack_exports__.AnnotationMode,Xt=__webpack_exports__.ColorPicker,Kt=__webpack_exports__.DOMSVGFactory,Yt=__webpack_exports__.DrawLayer,Qt=__webpack_exports__.FeatureTest,Jt=__webpack_exports__.GlobalWorkerOptions,Zt=__webpack_exports__.ImageKind,te=__webpack_exports__.InvalidPDFException,ee=__webpack_exports__.MissingPDFException,ie=__webpack_exports__.OPS,se=__webpack_exports__.OutputScale,ne=__webpack_exports__.PDFDataRangeTransport,ae=__webpack_exports__.PDFDateString,re=__webpack_exports__.PDFWorker,oe=__webpack_exports__.PasswordResponses,le=__webpack_exports__.PermissionFlag,he=__webpack_exports__.PixelsPerInch,de=__webpack_exports__.RenderingCancelledException,ce=__webpack_exports__.TextLayer,ue=__webpack_exports__.TouchManager,pe=__webpack_exports__.UnexpectedResponseException,ge=__webpack_exports__.Util,me=__webpack_exports__.VerbosityLevel,fe=__webpack_exports__.XfaLayer,be=__webpack_exports__.build,Ae=__webpack_exports__.createValidAbsoluteUrl,we=__webpack_exports__.fetchData,ve=__webpack_exports__.getDocument,ye=__webpack_exports__.getFilenameFromUrl,xe=__webpack_exports__.getPdfFilenameFromUrl,_e=__webpack_exports__.getXfaPageViewport,Ee=__webpack_exports__.isDataScheme,Se=__webpack_exports__.isPdfFile,Ce=__webpack_exports__.noContextMenu,Te=__webpack_exports__.normalizeUnicode,Me=__webpack_exports__.setLayerDimensions,Pe=__webpack_exports__.shadow,De=__webpack_exports__.stopEvent,ke=__webpack_exports__.version;export{Ut as AbortException,Gt as AnnotationEditorLayer,$t as AnnotationEditorParamsType,Vt as AnnotationEditorType,jt as AnnotationEditorUIManager,Wt as AnnotationLayer,qt as AnnotationMode,Xt as ColorPicker,Kt as DOMSVGFactory,Yt as DrawLayer,Qt as FeatureTest,Jt as GlobalWorkerOptions,Zt as ImageKind,te as InvalidPDFException,ee as MissingPDFException,ie as OPS,se as OutputScale,ne as PDFDataRangeTransport,ae as PDFDateString,re as PDFWorker,oe as PasswordResponses,le as PermissionFlag,he as PixelsPerInch,de as RenderingCancelledException,ce as TextLayer,ue as TouchManager,pe as UnexpectedResponseException,ge as Util,me as VerbosityLevel,fe as XfaLayer,be as build,Ae as createValidAbsoluteUrl,we as fetchData,ve as getDocument,ye as getFilenameFromUrl,xe as getPdfFilenameFromUrl,_e as getXfaPageViewport,Ee as isDataScheme,Se as isPdfFile,Ce as noContextMenu,Te as normalizeUnicode,Me as setLayerDimensions,Pe as shadow,De as stopEvent,ke as version}; \ No newline at end of file diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/build/pdf.worker.min.mjs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/build/pdf.worker.min.mjs deleted file mode 100644 index ee4038504a6..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/build/pdf.worker.min.mjs +++ /dev/null @@ -1,21 +0,0 @@ -/** - * @licstart The following is the entire license notice for the - * JavaScript code in this page - * - * Copyright 2024 Mozilla Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * @licend The above is the entire license notice for the - * JavaScript code in this page - */var e={d:(t,i)=>{for(var a in i)e.o(i,a)&&!e.o(t,a)&&Object.defineProperty(t,a,{enumerable:!0,get:i[a]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},__webpack_exports__ = globalThis.pdfjsWorker = {};e.d(__webpack_exports__,{WorkerMessageHandler:()=>WorkerMessageHandler});const t=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),i=[1,0,0,1,0,0],a=[.001,0,0,.001,0,0],s=1.35,r=.35,n=.25925925925925924,g=1,o=2,c=4,C=8,h=16,l=64,Q=128,E=256,u="pdfjs_internal_editor_",d=3,f=9,p=13,m=15,y={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},w=0,D=4,b=1,F=2,S=3,k=1,R=2,N=3,G=4,M=5,U=6,x=7,L=8,H=9,J=10,Y=11,v=12,K=13,T=14,q=15,O=16,W=17,j=20,X="Group",Z="R",V=1,z=2,_=4,$=16,AA=32,eA=128,tA=512,iA=1,aA=2,sA=4096,rA=8192,nA=32768,gA=65536,oA=131072,IA=1048576,cA=2097152,CA=8388608,hA=16777216,lA=1,BA=2,QA=3,EA=4,uA=5,dA={E:"Mouse Enter",X:"Mouse Exit",D:"Mouse Down",U:"Mouse Up",Fo:"Focus",Bl:"Blur",PO:"PageOpen",PC:"PageClose",PV:"PageVisible",PI:"PageInvisible",K:"Keystroke",F:"Format",V:"Validate",C:"Calculate"},fA={WC:"WillClose",WS:"WillSave",DS:"DidSave",WP:"WillPrint",DP:"DidPrint"},pA={O:"PageOpen",C:"PageClose"},mA=1,yA=5,wA=1,DA=2,bA=3,FA=4,SA=5,kA=6,RA=7,NA=8,GA=9,MA=10,UA=11,xA=12,LA=13,HA=14,JA=15,YA=16,vA=17,KA=18,TA=19,qA=20,OA=21,PA=22,WA=23,jA=24,XA=25,ZA=26,VA=27,zA=28,_A=29,$A=30,Ae=31,ee=32,te=33,ie=34,ae=35,se=36,re=37,ne=38,ge=39,oe=40,Ie=41,ce=42,Ce=43,he=44,le=45,Be=46,Qe=47,Ee=48,ue=49,de=50,fe=51,pe=52,me=53,ye=54,we=55,De=56,be=57,Fe=58,Se=59,ke=60,Re=61,Ne=62,Ge=63,Me=64,Ue=65,xe=66,Le=67,He=68,Je=69,Ye=70,ve=71,Ke=72,Te=73,qe=74,Oe=75,Pe=76,We=77,je=80,Xe=81,Ze=83,Ve=84,ze=85,_e=86,$e=87,At=88,et=89,tt=90,it=91,at=92,st=93,rt=1,nt=2;let gt=mA;function getVerbosityLevel(){return gt}function info(e){gt>=yA&&console.log(`Info: ${e}`)}function warn(e){gt>=mA&&console.log(`Warning: ${e}`)}function unreachable(e){throw new Error(e)}function assert(e,t){e||unreachable(t)}function createValidAbsoluteUrl(e,t=null,i=null){if(!e)return null;try{if(i&&"string"==typeof e){if(i.addDefaultProtocol&&e.startsWith("www.")){const t=e.match(/\./g);t?.length>=2&&(e=`http://${e}`)}if(i.tryConvertEncoding)try{e=stringToUTF8String(e)}catch{}}const a=t?new URL(e,t):new URL(e);if(function _isValidProtocol(e){switch(e?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(a))return a}catch{}return null}function shadow(e,t,i,a=!1){Object.defineProperty(e,t,{value:i,enumerable:!a,configurable:!0,writable:!1});return i}const ot=function BaseExceptionClosure(){function BaseException(e,t){this.message=e;this.name=t}BaseException.prototype=new Error;BaseException.constructor=BaseException;return BaseException}();class PasswordException extends ot{constructor(e,t){super(e,"PasswordException");this.code=t}}class UnknownErrorException extends ot{constructor(e,t){super(e,"UnknownErrorException");this.details=t}}class InvalidPDFException extends ot{constructor(e){super(e,"InvalidPDFException")}}class MissingPDFException extends ot{constructor(e){super(e,"MissingPDFException")}}class UnexpectedResponseException extends ot{constructor(e,t){super(e,"UnexpectedResponseException");this.status=t}}class FormatError extends ot{constructor(e){super(e,"FormatError")}}class AbortException extends ot{constructor(e){super(e,"AbortException")}}function bytesToString(e){"object"==typeof e&&void 0!==e?.length||unreachable("Invalid argument for bytesToString");const t=e.length,i=8192;if(t>24&255,e>>16&255,e>>8&255,255&e)}function objectSize(e){return Object.keys(e).length}class FeatureTest{static get isLittleEndian(){return shadow(this,"isLittleEndian",function isLittleEndian(){const e=new Uint8Array(4);e[0]=1;return 1===new Uint32Array(e.buffer,0,1)[0]}())}static get isEvalSupported(){return shadow(this,"isEvalSupported",function isEvalSupported(){try{new Function("");return!0}catch{return!1}}())}static get isOffscreenCanvasSupported(){return shadow(this,"isOffscreenCanvasSupported","undefined"!=typeof OffscreenCanvas)}static get isImageDecoderSupported(){return shadow(this,"isImageDecoderSupported","undefined"!=typeof ImageDecoder)}static get platform(){return"undefined"!=typeof navigator&&"string"==typeof navigator?.platform?shadow(this,"platform",{isMac:navigator.platform.includes("Mac"),isWindows:navigator.platform.includes("Win"),isFirefox:"string"==typeof navigator?.userAgent&&navigator.userAgent.includes("Firefox")}):shadow(this,"platform",{isMac:!1,isWindows:!1,isFirefox:!1})}static get isCSSRoundSupported(){return shadow(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}const It=Array.from(Array(256).keys(),(e=>e.toString(16).padStart(2,"0")));class Util{static makeHexColor(e,t,i){return`#${It[e]}${It[t]}${It[i]}`}static scaleMinMax(e,t){let i;if(e[0]){if(e[0]<0){i=t[0];t[0]=t[2];t[2]=i}t[0]*=e[0];t[2]*=e[0];if(e[3]<0){i=t[1];t[1]=t[3];t[3]=i}t[1]*=e[3];t[3]*=e[3]}else{i=t[0];t[0]=t[1];t[1]=i;i=t[2];t[2]=t[3];t[3]=i;if(e[1]<0){i=t[1];t[1]=t[3];t[3]=i}t[1]*=e[1];t[3]*=e[1];if(e[2]<0){i=t[0];t[0]=t[2];t[2]=i}t[0]*=e[2];t[2]*=e[2]}t[0]+=e[4];t[1]+=e[5];t[2]+=e[4];t[3]+=e[5]}static transform(e,t){return[e[0]*t[0]+e[2]*t[1],e[1]*t[0]+e[3]*t[1],e[0]*t[2]+e[2]*t[3],e[1]*t[2]+e[3]*t[3],e[0]*t[4]+e[2]*t[5]+e[4],e[1]*t[4]+e[3]*t[5]+e[5]]}static applyTransform(e,t){return[e[0]*t[0]+e[1]*t[2]+t[4],e[0]*t[1]+e[1]*t[3]+t[5]]}static applyInverseTransform(e,t){const i=t[0]*t[3]-t[1]*t[2];return[(e[0]*t[3]-e[1]*t[2]+t[2]*t[5]-t[4]*t[3])/i,(-e[0]*t[1]+e[1]*t[0]+t[4]*t[1]-t[5]*t[0])/i]}static getAxialAlignedBoundingBox(e,t){const i=this.applyTransform(e,t),a=this.applyTransform(e.slice(2,4),t),s=this.applyTransform([e[0],e[3]],t),r=this.applyTransform([e[2],e[1]],t);return[Math.min(i[0],a[0],s[0],r[0]),Math.min(i[1],a[1],s[1],r[1]),Math.max(i[0],a[0],s[0],r[0]),Math.max(i[1],a[1],s[1],r[1])]}static inverseTransform(e){const t=e[0]*e[3]-e[1]*e[2];return[e[3]/t,-e[1]/t,-e[2]/t,e[0]/t,(e[2]*e[5]-e[4]*e[3])/t,(e[4]*e[1]-e[5]*e[0])/t]}static singularValueDecompose2dScale(e){const t=[e[0],e[2],e[1],e[3]],i=e[0]*t[0]+e[1]*t[2],a=e[0]*t[1]+e[1]*t[3],s=e[2]*t[0]+e[3]*t[2],r=e[2]*t[1]+e[3]*t[3],n=(i+r)/2,g=Math.sqrt((i+r)**2-4*(i*r-s*a))/2,o=n+g||1,c=n-g||1;return[Math.sqrt(o),Math.sqrt(c)]}static normalizeRect(e){const t=e.slice(0);if(e[0]>e[2]){t[0]=e[2];t[2]=e[0]}if(e[1]>e[3]){t[1]=e[3];t[3]=e[1]}return t}static intersect(e,t){const i=Math.max(Math.min(e[0],e[2]),Math.min(t[0],t[2])),a=Math.min(Math.max(e[0],e[2]),Math.max(t[0],t[2]));if(i>a)return null;const s=Math.max(Math.min(e[1],e[3]),Math.min(t[1],t[3])),r=Math.min(Math.max(e[1],e[3]),Math.max(t[1],t[3]));return s>r?null:[i,s,a,r]}static#A(e,t,i,a,s,r,n,g,o,c){if(o<=0||o>=1)return;const C=1-o,h=o*o,l=h*o,Q=C*(C*(C*e+3*o*t)+3*h*i)+l*a,E=C*(C*(C*s+3*o*r)+3*h*n)+l*g;c[0]=Math.min(c[0],Q);c[1]=Math.min(c[1],E);c[2]=Math.max(c[2],Q);c[3]=Math.max(c[3],E)}static#e(e,t,i,a,s,r,n,g,o,c,C,h){if(Math.abs(o)<1e-12){Math.abs(c)>=1e-12&&this.#A(e,t,i,a,s,r,n,g,-C/c,h);return}const l=c**2-4*C*o;if(l<0)return;const Q=Math.sqrt(l),E=2*o;this.#A(e,t,i,a,s,r,n,g,(-c+Q)/E,h);this.#A(e,t,i,a,s,r,n,g,(-c-Q)/E,h)}static bezierBoundingBox(e,t,i,a,s,r,n,g,o){if(o){o[0]=Math.min(o[0],e,n);o[1]=Math.min(o[1],t,g);o[2]=Math.max(o[2],e,n);o[3]=Math.max(o[3],t,g)}else o=[Math.min(e,n),Math.min(t,g),Math.max(e,n),Math.max(t,g)];this.#e(e,i,s,n,t,a,r,g,3*(3*(i-s)-e+n),6*(e-2*i+s),3*(i-e),o);this.#e(e,i,s,n,t,a,r,g,3*(3*(a-r)-t+g),6*(t-2*a+r),3*(a-t),o);return o}}const ct=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,728,711,710,729,733,731,730,732,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8226,8224,8225,8230,8212,8211,402,8260,8249,8250,8722,8240,8222,8220,8221,8216,8217,8218,8482,64257,64258,321,338,352,376,381,305,322,339,353,382,0,8364];function stringToPDFString(e){if(e[0]>="ï"){let t;if("þ"===e[0]&&"ÿ"===e[1]){t="utf-16be";e.length%2==1&&(e=e.slice(0,-1))}else if("ÿ"===e[0]&&"þ"===e[1]){t="utf-16le";e.length%2==1&&(e=e.slice(0,-1))}else"ï"===e[0]&&"»"===e[1]&&"¿"===e[2]&&(t="utf-8");if(t)try{const i=new TextDecoder(t,{fatal:!0}),a=stringToBytes(e),s=i.decode(a);return s.includes("")?s.replaceAll(/\x1b[^\x1b]*(?:\x1b|$)/g,""):s}catch(e){warn(`stringToPDFString: "${e}".`)}}const t=[];for(let i=0,a=e.length;iIt[e])).join("")}"function"!=typeof Promise.try&&(Promise.try=function(e,...t){return new Promise((i=>{i(e(...t))}))});const lt=Symbol("CIRCULAR_REF"),Bt=Symbol("EOF");let Qt=Object.create(null),Et=Object.create(null),ut=Object.create(null);class Name{constructor(e){this.name=e}static get(e){return Et[e]||=new Name(e)}}class Cmd{constructor(e){this.cmd=e}static get(e){return Qt[e]||=new Cmd(e)}}const dt=function nonSerializableClosure(){return dt};class Dict{constructor(e=null){this._map=new Map;this.xref=e;this.objId=null;this.suppressEncryption=!1;this.__nonSerializable__=dt}assignXref(e){this.xref=e}get size(){return this._map.size}get(e,t,i){let a=this._map.get(e);if(void 0===a&&void 0!==t){a=this._map.get(t);void 0===a&&void 0!==i&&(a=this._map.get(i))}return a instanceof Ref&&this.xref?this.xref.fetch(a,this.suppressEncryption):a}async getAsync(e,t,i){let a=this._map.get(e);if(void 0===a&&void 0!==t){a=this._map.get(t);void 0===a&&void 0!==i&&(a=this._map.get(i))}return a instanceof Ref&&this.xref?this.xref.fetchAsync(a,this.suppressEncryption):a}getArray(e,t,i){let a=this._map.get(e);if(void 0===a&&void 0!==t){a=this._map.get(t);void 0===a&&void 0!==i&&(a=this._map.get(i))}a instanceof Ref&&this.xref&&(a=this.xref.fetch(a,this.suppressEncryption));if(Array.isArray(a)){a=a.slice();for(let e=0,t=a.length;e{unreachable("Should not call `set` on the empty dictionary.")};return shadow(this,"empty",e)}static merge({xref:e,dictArray:t,mergeSubDicts:i=!1}){const a=new Dict(e),s=new Map;for(const e of t)if(e instanceof Dict)for(const[t,a]of e._map){let e=s.get(t);if(void 0===e){e=[];s.set(t,e)}else if(!(i&&a instanceof Dict))continue;e.push(a)}for(const[t,i]of s){if(1===i.length||!(i[0]instanceof Dict)){a._map.set(t,i[0]);continue}const s=new Dict(e);for(const e of i)for(const[t,i]of e._map)s._map.has(t)||s._map.set(t,i);s.size>0&&a._map.set(t,s)}s.clear();return a.size>0?a:Dict.empty}clone(){const e=new Dict(this.xref);for(const t of this.getKeys())e.set(t,this.getRaw(t));return e}delete(e){delete this._map[e]}}class Ref{constructor(e,t){this.num=e;this.gen=t}toString(){return 0===this.gen?`${this.num}R`:`${this.num}R${this.gen}`}static fromString(e){const t=ut[e];if(t)return t;const i=/^(\d+)R(\d*)$/.exec(e);return i&&"0"!==i[1]?ut[e]=new Ref(parseInt(i[1]),i[2]?parseInt(i[2]):0):null}static get(e,t){const i=0===t?`${e}R`:`${e}R${t}`;return ut[i]||=new Ref(e,t)}}class RefSet{constructor(e=null){this._set=new Set(e?._set)}has(e){return this._set.has(e.toString())}put(e){this._set.add(e.toString())}remove(e){this._set.delete(e.toString())}[Symbol.iterator](){return this._set.values()}clear(){this._set.clear()}}class RefSetCache{constructor(){this._map=new Map}get size(){return this._map.size}get(e){return this._map.get(e.toString())}has(e){return this._map.has(e.toString())}put(e,t){this._map.set(e.toString(),t)}putAlias(e,t){this._map.set(e.toString(),this.get(t))}[Symbol.iterator](){return this._map.values()}clear(){this._map.clear()}*values(){yield*this._map.values()}*items(){for(const[e,t]of this._map)yield[Ref.fromString(e),t]}}function isName(e,t){return e instanceof Name&&(void 0===t||e.name===t)}function isCmd(e,t){return e instanceof Cmd&&(void 0===t||e.cmd===t)}function isDict(e,t){return e instanceof Dict&&(void 0===t||isName(e.get("Type"),t))}function isRefsEqual(e,t){return e.num===t.num&&e.gen===t.gen}class BaseStream{get length(){unreachable("Abstract getter `length` accessed")}get isEmpty(){unreachable("Abstract getter `isEmpty` accessed")}get isDataLoaded(){return shadow(this,"isDataLoaded",!0)}getByte(){unreachable("Abstract method `getByte` called")}getBytes(e){unreachable("Abstract method `getBytes` called")}async getImageData(e,t){return this.getBytes(e,t)}async asyncGetBytes(){unreachable("Abstract method `asyncGetBytes` called")}get isAsync(){return!1}get canAsyncDecodeImageFromBuffer(){return!1}async getTransferableImage(){return null}peekByte(){const e=this.getByte();-1!==e&&this.pos--;return e}peekBytes(e){const t=this.getBytes(e);this.pos-=t.length;return t}getUint16(){const e=this.getByte(),t=this.getByte();return-1===e||-1===t?-1:(e<<8)+t}getInt32(){return(this.getByte()<<24)+(this.getByte()<<16)+(this.getByte()<<8)+this.getByte()}getByteRange(e,t){unreachable("Abstract method `getByteRange` called")}getString(e){return bytesToString(this.getBytes(e))}skip(e){this.pos+=e||1}reset(){unreachable("Abstract method `reset` called")}moveStart(){unreachable("Abstract method `moveStart` called")}makeSubStream(e,t,i=null){unreachable("Abstract method `makeSubStream` called")}getBaseStreams(){return null}}const ft=/^[1-9]\.\d$/,pt=2**31-1;function getLookupTableFactory(e){let t;return function(){if(e){t=Object.create(null);e(t);e=null}return t}}class MissingDataException extends ot{constructor(e,t){super(`Missing data [${e}, ${t})`,"MissingDataException");this.begin=e;this.end=t}}class ParserEOFException extends ot{constructor(e){super(e,"ParserEOFException")}}class XRefEntryException extends ot{constructor(e){super(e,"XRefEntryException")}}class XRefParseException extends ot{constructor(e){super(e,"XRefParseException")}}function arrayBuffersToBytes(e){const t=e.length;if(0===t)return new Uint8Array(0);if(1===t)return new Uint8Array(e[0]);let i=0;for(let a=0;a0,"The number should be a positive integer.");const i="M".repeat(e/1e3|0)+mt[e%1e3/100|0]+mt[10+(e%100/10|0)]+mt[20+e%10];return t?i.toLowerCase():i}function log2(e){return e>0?Math.ceil(Math.log2(e)):0}function readInt8(e,t){return e[t]<<24>>24}function readUint16(e,t){return e[t]<<8|e[t+1]}function readUint32(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}function isWhiteSpace(e){return 32===e||9===e||13===e||10===e}function isNumberArray(e,t){return Array.isArray(e)?(null===t||e.length===t)&&e.every((e=>"number"==typeof e)):ArrayBuffer.isView(e)&&(0===e.length||"number"==typeof e[0])&&(null===t||e.length===t)}function lookupMatrix(e,t){return isNumberArray(e,6)?e:t}function lookupRect(e,t){return isNumberArray(e,4)?e:t}function lookupNormalRect(e,t){return isNumberArray(e,4)?Util.normalizeRect(e):t}function parseXFAPath(e){const t=/(.+)\[(\d+)\]$/;return e.split(".").map((e=>{const i=e.match(t);return i?{name:i[1],pos:parseInt(i[2],10)}:{name:e,pos:0}}))}function escapePDFName(e){const t=[];let i=0;for(let a=0,s=e.length;a126||35===s||40===s||41===s||60===s||62===s||91===s||93===s||123===s||125===s||47===s||37===s){i"\n"===e?"\\n":"\r"===e?"\\r":`\\${e}`))}function _collectJS(e,t,i,a){if(!e)return;let s=null;if(e instanceof Ref){if(a.has(e))return;s=e;a.put(s);e=t.fetch(e)}if(Array.isArray(e))for(const s of e)_collectJS(s,t,i,a);else if(e instanceof Dict){if(isName(e.get("S"),"JavaScript")){const t=e.get("JS");let a;t instanceof BaseStream?a=t.getString():"string"==typeof t&&(a=t);a&&=stringToPDFString(a).replaceAll("\0","");a&&i.push(a)}_collectJS(e.getRaw("Next"),t,i,a)}s&&a.remove(s)}function collectActions(e,t,i){const a=Object.create(null),s=getInheritableProperty({dict:t,key:"AA",stopWhenFound:!1});if(s)for(let t=s.length-1;t>=0;t--){const r=s[t];if(r instanceof Dict)for(const t of r.getKeys()){const s=i[t];if(!s)continue;const n=[];_collectJS(r.getRaw(t),e,n,new RefSet);n.length>0&&(a[s]=n)}}if(t.has("A")){const i=[];_collectJS(t.get("A"),e,i,new RefSet);i.length>0&&(a.Action=i)}return objectSize(a)>0?a:null}const yt={60:"<",62:">",38:"&",34:""",39:"'"};function*codePointIter(e){for(let t=0,i=e.length;t55295&&(i<57344||i>65533)&&t++;yield i}}function encodeToXmlString(e){const t=[];let i=0;for(let a=0,s=e.length;a55295&&(s<57344||s>65533)&&a++;i=a+1}}if(0===t.length)return e;i: ${e}.`);return!1}return!0}function validateCSSFont(e){const t=new Set(["100","200","300","400","500","600","700","800","900","1000","normal","bold","bolder","lighter"]),{fontFamily:i,fontWeight:a,italicAngle:s}=e;if(!validateFontName(i,!0))return!1;const r=a?a.toString():"";e.fontWeight=t.has(r)?r:"400";const n=parseFloat(s);e.italicAngle=isNaN(n)||n<-90||n>90?"14":s.toString();return!0}function recoverJsURL(e){const t=new RegExp("^\\s*("+["app.launchURL","window.open","xfa.host.gotoURL"].join("|").replaceAll(".","\\.")+")\\((?:'|\")([^'\"]*)(?:'|\")(?:,\\s*(\\w+)\\)|\\))","i").exec(e);return t?.[2]?{url:t[2],newWindow:"app.launchURL"===t[1]&&"true"===t[3]}:null}function numberToString(e){if(Number.isInteger(e))return e.toString();const t=Math.round(100*e);return t%100==0?(t/100).toString():t%10==0?e.toFixed(1):e.toFixed(2)}function getNewAnnotationsMap(e){if(!e)return null;const t=new Map;for(const[i,a]of e){if(!i.startsWith(u))continue;let e=t.get(a.pageIndex);if(!e){e=[];t.set(a.pageIndex,e)}e.push(a)}return t.size>0?t:null}function stringToAsciiOrUTF16BE(e){return function isAscii(e){return/^[\x00-\x7F]*$/.test(e)}(e)?e:stringToUTF16String(e,!0)}function stringToUTF16HexString(e){const t=[];for(let i=0,a=e.length;i>8&255],It[255&a])}return t.join("")}function stringToUTF16String(e,t=!1){const i=[];t&&i.push("þÿ");for(let t=0,a=e.length;t>8&255),String.fromCharCode(255&a))}return i.join("")}function getRotationMatrix(e,t,i){switch(e){case 90:return[0,1,-1,0,t,0];case 180:return[-1,0,0,-1,t,i];case 270:return[0,-1,1,0,0,i];default:throw new Error("Invalid rotation")}}function getSizeInBytes(e){return Math.ceil(Math.ceil(Math.log2(1+e))/8)}class Stream extends BaseStream{constructor(e,t,i,a){super();this.bytes=e instanceof Uint8Array?e:new Uint8Array(e);this.start=t||0;this.pos=this.start;this.end=t+i||this.bytes.length;this.dict=a}get length(){return this.end-this.start}get isEmpty(){return 0===this.length}getByte(){return this.pos>=this.end?-1:this.bytes[this.pos++]}getBytes(e){const t=this.bytes,i=this.pos,a=this.end;if(!e)return t.subarray(i,a);let s=i+e;s>a&&(s=a);this.pos=s;return t.subarray(i,s)}getByteRange(e,t){e<0&&(e=0);t>this.end&&(t=this.end);return this.bytes.subarray(e,t)}reset(){this.pos=this.start}moveStart(){this.start=this.pos}makeSubStream(e,t,i=null){return new Stream(this.bytes.buffer,e,t,i)}}class StringStream extends Stream{constructor(e){super(stringToBytes(e))}}class NullStream extends Stream{constructor(){super(new Uint8Array(0))}}class ChunkedStream extends Stream{constructor(e,t,i){super(new Uint8Array(e),0,e,null);this.chunkSize=t;this._loadedChunks=new Set;this.numChunks=Math.ceil(e/t);this.manager=i;this.progressiveDataLength=0;this.lastSuccessfulEnsureByteChunk=-1}getMissingChunks(){const e=[];for(let t=0,i=this.numChunks;t=this.end?this.numChunks:Math.floor(t/this.chunkSize);for(let e=i;ethis.numChunks)&&t!==this.lastSuccessfulEnsureByteChunk){if(!this._loadedChunks.has(t))throw new MissingDataException(e,e+1);this.lastSuccessfulEnsureByteChunk=t}}ensureRange(e,t){if(e>=t)return;if(t<=this.progressiveDataLength)return;const i=Math.floor(e/this.chunkSize);if(i>this.numChunks)return;const a=Math.min(Math.floor((t-1)/this.chunkSize)+1,this.numChunks);for(let s=i;s=this.end)return-1;e>=this.progressiveDataLength&&this.ensureByte(e);return this.bytes[this.pos++]}getBytes(e){const t=this.bytes,i=this.pos,a=this.end;if(!e){a>this.progressiveDataLength&&this.ensureRange(i,a);return t.subarray(i,a)}let s=i+e;s>a&&(s=a);s>this.progressiveDataLength&&this.ensureRange(i,s);this.pos=s;return t.subarray(i,s)}getByteRange(e,t){e<0&&(e=0);t>this.end&&(t=this.end);t>this.progressiveDataLength&&this.ensureRange(e,t);return this.bytes.subarray(e,t)}makeSubStream(e,t,i=null){t?e+t>this.progressiveDataLength&&this.ensureRange(e,e+t):e>=this.progressiveDataLength&&this.ensureByte(e);function ChunkedStreamSubstream(){}ChunkedStreamSubstream.prototype=Object.create(this);ChunkedStreamSubstream.prototype.getMissingChunks=function(){const e=this.chunkSize,t=Math.floor(this.start/e),i=Math.floor((this.end-1)/e)+1,a=[];for(let e=t;e{const readChunk=({value:r,done:n})=>{try{if(n){const t=arrayBuffersToBytes(a);a=null;e(t);return}s+=r.byteLength;i.isStreamingSupported&&this.onProgress({loaded:s});a.push(r);i.read().then(readChunk,t)}catch(e){t(e)}};i.read().then(readChunk,t)})).then((t=>{this.aborted||this.onReceiveData({chunk:t,begin:e})}))}requestAllChunks(e=!1){if(!e){const e=this.stream.getMissingChunks();this._requestChunks(e)}return this._loadedStreamCapability.promise}_requestChunks(e){const t=this.currRequestId++,i=new Set;this._chunksNeededByRequest.set(t,i);for(const t of e)this.stream.hasChunk(t)||i.add(t);if(0===i.size)return Promise.resolve();const a=Promise.withResolvers();this._promisesByRequest.set(t,a);const s=[];for(const e of i){let i=this._requestsByChunk.get(e);if(!i){i=[];this._requestsByChunk.set(e,i);s.push(e)}i.push(t)}if(s.length>0){const e=this.groupChunks(s);for(const t of e){const e=t.beginChunk*this.chunkSize,i=Math.min(t.endChunk*this.chunkSize,this.length);this.sendRequest(e,i).catch(a.reject)}}return a.promise.catch((e=>{if(!this.aborted)throw e}))}getStream(){return this.stream}requestRange(e,t){t=Math.min(t,this.length);const i=this.getBeginChunk(e),a=this.getEndChunk(t),s=[];for(let e=i;e=0&&a+1!==r){t.push({beginChunk:i,endChunk:a+1});i=r}s+1===e.length&&t.push({beginChunk:i,endChunk:r+1});a=r}return t}onProgress(e){this.msgHandler.send("DocProgress",{loaded:this.stream.numChunksLoaded*this.chunkSize+e.loaded,total:this.length})}onReceiveData(e){const t=e.chunk,i=void 0===e.begin,a=i?this.progressiveDataLength:e.begin,s=a+t.byteLength,r=Math.floor(a/this.chunkSize),n=s0||g.push(i)}}}if(!this.disableAutoFetch&&0===this._requestsByChunk.size){let e;if(1===this.stream.numChunksLoaded){const t=this.stream.numChunks-1;this.stream.hasChunk(t)||(e=t)}else e=this.stream.nextEmptyChunk(n);Number.isInteger(e)&&this._requestChunks([e])}for(const e of g){const t=this._promisesByRequest.get(e);this._promisesByRequest.delete(e);t.resolve()}this.msgHandler.send("DocProgress",{loaded:this.stream.numChunksLoaded*this.chunkSize,total:this.length})}onError(e){this._loadedStreamCapability.reject(e)}getBeginChunk(e){return Math.floor(e/this.chunkSize)}getEndChunk(e){return Math.floor((e-1)/this.chunkSize)+1}abort(e){this.aborted=!0;this.pdfNetworkStream?.cancelAllRequests(e);for(const t of this._promisesByRequest.values())t.reject(e)}}class ColorSpace{constructor(e,t){this.name=e;this.numComps=t}getRgb(e,t){const i=new Uint8ClampedArray(3);this.getRgbItem(e,t,i,0);return i}getRgbItem(e,t,i,a){unreachable("Should not call ColorSpace.getRgbItem")}getRgbBuffer(e,t,i,a,s,r,n){unreachable("Should not call ColorSpace.getRgbBuffer")}getOutputLength(e,t){unreachable("Should not call ColorSpace.getOutputLength")}isPassthrough(e){return!1}isDefaultDecode(e,t){return ColorSpace.isDefaultDecode(e,this.numComps)}fillRgb(e,t,i,a,s,r,n,g,o){const c=t*i;let C=null;const h=1<h&&"DeviceGray"!==this.name&&"DeviceRGB"!==this.name){const t=n<=8?new Uint8Array(h):new Uint16Array(h);for(let e=0;e=.99554525?1:this.#B(0,1,1.055*e**(1/2.4)-.055)}#B(e,t,i){return Math.max(e,Math.min(t,i))}#Q(e){return e<0?-this.#Q(-e):e>8?((e+16)/116)**3:e*CalRGBCS.#I}#E(e,t,i){if(0===e[0]&&0===e[1]&&0===e[2]){i[0]=t[0];i[1]=t[1];i[2]=t[2];return}const a=this.#Q(0),s=(1-a)/(1-this.#Q(e[0])),r=1-s,n=(1-a)/(1-this.#Q(e[1])),g=1-n,o=(1-a)/(1-this.#Q(e[2])),c=1-o;i[0]=t[0]*s+r;i[1]=t[1]*n+g;i[2]=t[2]*o+c}#u(e,t,i){if(1===e[0]&&1===e[2]){i[0]=t[0];i[1]=t[1];i[2]=t[2];return}const a=i;this.#c(CalRGBCS.#i,t,a);const s=CalRGBCS.#n;this.#C(e,a,s);this.#c(CalRGBCS.#a,s,i)}#d(e,t,i){const a=i;this.#c(CalRGBCS.#i,t,a);const s=CalRGBCS.#n;this.#h(e,a,s);this.#c(CalRGBCS.#a,s,i)}#t(e,t,i,a,s){const r=this.#B(0,1,e[t]*s),n=this.#B(0,1,e[t+1]*s),g=this.#B(0,1,e[t+2]*s),o=1===r?1:r**this.GR,c=1===n?1:n**this.GG,C=1===g?1:g**this.GB,h=this.MXA*o+this.MXB*c+this.MXC*C,l=this.MYA*o+this.MYB*c+this.MYC*C,Q=this.MZA*o+this.MZB*c+this.MZC*C,E=CalRGBCS.#g;E[0]=h;E[1]=l;E[2]=Q;const u=CalRGBCS.#o;this.#u(this.whitePoint,E,u);const d=CalRGBCS.#g;this.#E(this.blackPoint,u,d);const f=CalRGBCS.#o;this.#d(CalRGBCS.#r,d,f);const p=CalRGBCS.#g;this.#c(CalRGBCS.#s,f,p);i[a]=255*this.#l(p[0]);i[a+1]=255*this.#l(p[1]);i[a+2]=255*this.#l(p[2])}getRgbItem(e,t,i,a){this.#t(e,t,i,a,1)}getRgbBuffer(e,t,i,a,s,r,n){const g=1/((1<this.amax||this.bmin>this.bmax){info("Invalid Range, falling back to defaults");this.amin=-100;this.amax=100;this.bmin=-100;this.bmax=100}}#f(e){return e>=6/29?e**3:108/841*(e-4/29)}#p(e,t,i,a){return i+e*(a-i)/t}#t(e,t,i,a,s){let r=e[t],n=e[t+1],g=e[t+2];if(!1!==i){r=this.#p(r,i,0,100);n=this.#p(n,i,this.amin,this.amax);g=this.#p(g,i,this.bmin,this.bmax)}n>this.amax?n=this.amax:nthis.bmax?g=this.bmax:g>>0}function hexToStr(e,t){return 1===t?String.fromCharCode(e[0],e[1]):3===t?String.fromCharCode(e[0],e[1],e[2],e[3]):String.fromCharCode(...e.subarray(0,t+1))}function addHex(e,t,i){let a=0;for(let s=i;s>=0;s--){a+=e[s]+t[s];e[s]=255&a;a>>=8}}function incHex(e,t){let i=1;for(let a=t;a>=0&&i>0;a--){i+=e[a];e[a]=255&i;i>>=8}}const wt=16;class BinaryCMapStream{constructor(e){this.buffer=e;this.pos=0;this.end=e.length;this.tmpBuf=new Uint8Array(19)}readByte(){return this.pos>=this.end?-1:this.buffer[this.pos++]}readNumber(){let e,t=0;do{const i=this.readByte();if(i<0)throw new FormatError("unexpected EOF in bcmap");e=!(128&i);t=t<<7|127&i}while(!e);return t}readSigned(){const e=this.readNumber();return 1&e?~(e>>>1):e>>>1}readHex(e,t){e.set(this.buffer.subarray(this.pos,this.pos+t+1));this.pos+=t+1}readHexNumber(e,t){let i;const a=this.tmpBuf;let s=0;do{const e=this.readByte();if(e<0)throw new FormatError("unexpected EOF in bcmap");i=!(128&e);a[s++]=127&e}while(!i);let r=t,n=0,g=0;for(;r>=0;){for(;g<8&&a.length>0;){n|=a[--s]<>=8;g-=8}}readHexSigned(e,t){this.readHexNumber(e,t);const i=1&e[t]?255:0;let a=0;for(let s=0;s<=t;s++){a=(1&a)<<8|e[s];e[s]=a>>1^i}}readString(){const e=this.readNumber(),t=new Array(e);for(let i=0;i=0;){const e=l>>5;if(7===e){switch(31&l){case 0:a.readString();break;case 1:r=a.readString()}continue}const i=!!(16&l),s=15&l;if(s+1>wt)throw new Error("BinaryCMapReader.process: Invalid dataSize.");const Q=1,E=a.readNumber();switch(e){case 0:a.readHex(n,s);a.readHexNumber(g,s);addHex(g,n,s);t.addCodespaceRange(s+1,hexToInt(n,s),hexToInt(g,s));for(let e=1;es&&(a=s)}else{for(;!this.eof;)this.readBlock(t);a=this.bufferLength}this.pos=a;return this.buffer.subarray(i,a)}async getImageData(e,t=null){if(!this.canAsyncDecodeImageFromBuffer)return this.getBytes(e,t);const i=await this.stream.asyncGetBytes();return this.decodeImage(i,t)}reset(){this.pos=0}makeSubStream(e,t,i=null){if(void 0===t)for(;!this.eof;)this.readBlock();else{const i=e+t;for(;this.bufferLength<=i&&!this.eof;)this.readBlock()}return new Stream(this.buffer,e,t,i)}getBaseStreams(){return this.str?this.str.getBaseStreams():null}}class StreamsSequenceStream extends DecodeStream{constructor(e,t=null){e=e.filter((e=>e instanceof BaseStream));let i=0;for(const t of e)i+=t instanceof DecodeStream?t._rawMinBufferLength:t.length;super(i);this.streams=e;this._onError=t}readBlock(){const e=this.streams;if(0===e.length){this.eof=!0;return}const t=e.shift();let i;try{i=t.getBytes()}catch(e){if(this._onError){this._onError(e,t.dict?.objId);return}throw e}const a=this.bufferLength,s=a+i.length;this.ensureBuffer(s).set(i,a);this.bufferLength=s}getBaseStreams(){const e=[];for(const t of this.streams){const i=t.getBaseStreams();i&&e.push(...i)}return e.length>0?e:null}}class Ascii85Stream extends DecodeStream{constructor(e,t){t&&(t*=.8);super(t);this.str=e;this.dict=e.dict;this.input=new Uint8Array(5)}readBlock(){const e=this.str;let t=e.getByte();for(;isWhiteSpace(t);)t=e.getByte();if(-1===t||126===t){this.eof=!0;return}const i=this.bufferLength;let a,s;if(122===t){a=this.ensureBuffer(i+4);for(s=0;s<4;++s)a[i+s]=0;this.bufferLength+=4}else{const r=this.input;r[0]=t;for(s=1;s<5;++s){t=e.getByte();for(;isWhiteSpace(t);)t=e.getByte();r[s]=t;if(-1===t||126===t)break}a=this.ensureBuffer(i+s-1);this.bufferLength+=s-1;if(s<5){for(;s<5;++s)r[s]=117;this.eof=!0}let n=0;for(s=0;s<5;++s)n=85*n+(r[s]-33);for(s=3;s>=0;--s){a[i+s]=255&n;n>>=8}}}}class AsciiHexStream extends DecodeStream{constructor(e,t){t&&(t*=.5);super(t);this.str=e;this.dict=e.dict;this.firstDigit=-1}readBlock(){const e=this.str.getBytes(8e3);if(!e.length){this.eof=!0;return}const t=e.length+1>>1,i=this.ensureBuffer(this.bufferLength+t);let a=this.bufferLength,s=this.firstDigit;for(const t of e){let e;if(t>=48&&t<=57)e=15&t;else{if(!(t>=65&&t<=70||t>=97&&t<=102)){if(62===t){this.eof=!0;break}continue}e=9+(15&t)}if(s<0)s=e;else{i[a++]=s<<4|e;s=-1}}if(s>=0&&this.eof){i[a++]=s<<4;s=-1}this.firstDigit=s;this.bufferLength=a}}const bt=-1,Ft=[[-1,-1],[-1,-1],[7,8],[7,7],[6,6],[6,6],[6,5],[6,5],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2]],St=[[-1,-1],[12,-2],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[11,1792],[11,1792],[12,1984],[12,2048],[12,2112],[12,2176],[12,2240],[12,2304],[11,1856],[11,1856],[11,1920],[11,1920],[12,2368],[12,2432],[12,2496],[12,2560]],kt=[[-1,-1],[-1,-1],[-1,-1],[-1,-1],[8,29],[8,29],[8,30],[8,30],[8,45],[8,45],[8,46],[8,46],[7,22],[7,22],[7,22],[7,22],[7,23],[7,23],[7,23],[7,23],[8,47],[8,47],[8,48],[8,48],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[7,20],[7,20],[7,20],[7,20],[8,33],[8,33],[8,34],[8,34],[8,35],[8,35],[8,36],[8,36],[8,37],[8,37],[8,38],[8,38],[7,19],[7,19],[7,19],[7,19],[8,31],[8,31],[8,32],[8,32],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[8,53],[8,53],[8,54],[8,54],[7,26],[7,26],[7,26],[7,26],[8,39],[8,39],[8,40],[8,40],[8,41],[8,41],[8,42],[8,42],[8,43],[8,43],[8,44],[8,44],[7,21],[7,21],[7,21],[7,21],[7,28],[7,28],[7,28],[7,28],[8,61],[8,61],[8,62],[8,62],[8,63],[8,63],[8,0],[8,0],[8,320],[8,320],[8,384],[8,384],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[7,27],[7,27],[7,27],[7,27],[8,59],[8,59],[8,60],[8,60],[9,1472],[9,1536],[9,1600],[9,1728],[7,18],[7,18],[7,18],[7,18],[7,24],[7,24],[7,24],[7,24],[8,49],[8,49],[8,50],[8,50],[8,51],[8,51],[8,52],[8,52],[7,25],[7,25],[7,25],[7,25],[8,55],[8,55],[8,56],[8,56],[8,57],[8,57],[8,58],[8,58],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[8,448],[8,448],[8,512],[8,512],[9,704],[9,768],[8,640],[8,640],[8,576],[8,576],[9,832],[9,896],[9,960],[9,1024],[9,1088],[9,1152],[9,1216],[9,1280],[9,1344],[9,1408],[7,256],[7,256],[7,256],[7,256],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7]],Rt=[[-1,-1],[-1,-1],[12,-2],[12,-2],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[11,1792],[11,1792],[11,1792],[11,1792],[12,1984],[12,1984],[12,2048],[12,2048],[12,2112],[12,2112],[12,2176],[12,2176],[12,2240],[12,2240],[12,2304],[12,2304],[11,1856],[11,1856],[11,1856],[11,1856],[11,1920],[11,1920],[11,1920],[11,1920],[12,2368],[12,2368],[12,2432],[12,2432],[12,2496],[12,2496],[12,2560],[12,2560],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[12,52],[12,52],[13,640],[13,704],[13,768],[13,832],[12,55],[12,55],[12,56],[12,56],[13,1280],[13,1344],[13,1408],[13,1472],[12,59],[12,59],[12,60],[12,60],[13,1536],[13,1600],[11,24],[11,24],[11,24],[11,24],[11,25],[11,25],[11,25],[11,25],[13,1664],[13,1728],[12,320],[12,320],[12,384],[12,384],[12,448],[12,448],[13,512],[13,576],[12,53],[12,53],[12,54],[12,54],[13,896],[13,960],[13,1024],[13,1088],[13,1152],[13,1216],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64]],Nt=[[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[11,23],[11,23],[12,50],[12,51],[12,44],[12,45],[12,46],[12,47],[12,57],[12,58],[12,61],[12,256],[10,16],[10,16],[10,16],[10,16],[10,17],[10,17],[10,17],[10,17],[12,48],[12,49],[12,62],[12,63],[12,30],[12,31],[12,32],[12,33],[12,40],[12,41],[11,22],[11,22],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[12,128],[12,192],[12,26],[12,27],[12,28],[12,29],[11,19],[11,19],[11,20],[11,20],[12,34],[12,35],[12,36],[12,37],[12,38],[12,39],[11,21],[11,21],[12,42],[12,43],[10,0],[10,0],[10,0],[10,0],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12]],Gt=[[-1,-1],[-1,-1],[-1,-1],[-1,-1],[6,9],[6,8],[5,7],[5,7],[4,6],[4,6],[4,6],[4,6],[4,5],[4,5],[4,5],[4,5],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2]];class CCITTFaxDecoder{constructor(e,t={}){if("function"!=typeof e?.next)throw new Error('CCITTFaxDecoder - invalid "source" parameter.');this.source=e;this.eof=!1;this.encoding=t.K||0;this.eoline=t.EndOfLine||!1;this.byteAlign=t.EncodedByteAlign||!1;this.columns=t.Columns||1728;this.rows=t.Rows||0;this.eoblock=t.EndOfBlock??!0;this.black=t.BlackIs1||!1;this.codingLine=new Uint32Array(this.columns+1);this.refLine=new Uint32Array(this.columns+2);this.codingLine[0]=this.columns;this.codingPos=0;this.row=0;this.nextLine2D=this.encoding<0;this.inputBits=0;this.inputBuf=0;this.outputBits=0;this.rowsDone=!1;let i;for(;0===(i=this._lookBits(12));)this._eatBits(1);1===i&&this._eatBits(12);if(this.encoding>0){this.nextLine2D=!this._lookBits(1);this._eatBits(1)}}readNextChar(){if(this.eof)return-1;const e=this.refLine,t=this.codingLine,i=this.columns;let a,s,r,n,g;if(0===this.outputBits){this.rowsDone&&(this.eof=!0);if(this.eof)return-1;this.err=!1;let r,g,o;if(this.nextLine2D){for(n=0;t[n]=64);do{g+=o=this._getWhiteCode()}while(o>=64)}else{do{r+=o=this._getWhiteCode()}while(o>=64);do{g+=o=this._getBlackCode()}while(o>=64)}this._addPixels(t[this.codingPos]+r,s);t[this.codingPos]0?--a:++a;for(;e[a]<=t[this.codingPos]&&e[a]0?--a:++a;for(;e[a]<=t[this.codingPos]&&e[a]0?--a:++a;for(;e[a]<=t[this.codingPos]&&e[a]=64);else do{r+=o=this._getWhiteCode()}while(o>=64);this._addPixels(t[this.codingPos]+r,s);s^=1}}let c=!1;this.byteAlign&&(this.inputBits&=-8);if(this.eoblock||this.row!==this.rows-1){r=this._lookBits(12);if(this.eoline)for(;r!==bt&&1!==r;){this._eatBits(1);r=this._lookBits(12)}else for(;0===r;){this._eatBits(1);r=this._lookBits(12)}if(1===r){this._eatBits(12);c=!0}else r===bt&&(this.eof=!0)}else this.rowsDone=!0;if(!this.eof&&this.encoding>0&&!this.rowsDone){this.nextLine2D=!this._lookBits(1);this._eatBits(1)}if(this.eoblock&&c&&this.byteAlign){r=this._lookBits(12);if(1===r){this._eatBits(12);if(this.encoding>0){this._lookBits(1);this._eatBits(1)}if(this.encoding>=0)for(n=0;n<4;++n){r=this._lookBits(12);1!==r&&info("bad rtc code: "+r);this._eatBits(12);if(this.encoding>0){this._lookBits(1);this._eatBits(1)}}this.eof=!0}}else if(this.err&&this.eoline){for(;;){r=this._lookBits(13);if(r===bt){this.eof=!0;return-1}if(r>>1==1)break;this._eatBits(1)}this._eatBits(12);if(this.encoding>0){this._eatBits(1);this.nextLine2D=!(1&r)}}this.outputBits=t[0]>0?t[this.codingPos=0]:t[this.codingPos=1];this.row++}if(this.outputBits>=8){g=1&this.codingPos?0:255;this.outputBits-=8;if(0===this.outputBits&&t[this.codingPos]r){g<<=r;1&this.codingPos||(g|=255>>8-r);this.outputBits-=r;r=0}else{g<<=this.outputBits;1&this.codingPos||(g|=255>>8-this.outputBits);r-=this.outputBits;this.outputBits=0;if(t[this.codingPos]0){g<<=r;r=0}}}while(r)}this.black&&(g^=255);return g}_addPixels(e,t){const i=this.codingLine;let a=this.codingPos;if(e>i[a]){if(e>this.columns){info("row is wrong length");this.err=!0;e=this.columns}1&a^t&&++a;i[a]=e}this.codingPos=a}_addPixelsNeg(e,t){const i=this.codingLine;let a=this.codingPos;if(e>i[a]){if(e>this.columns){info("row is wrong length");this.err=!0;e=this.columns}1&a^t&&++a;i[a]=e}else if(e0&&e=s){const t=i[e-s];if(t[0]===a){this._eatBits(a);return[!0,t[1],!0]}}}return[!1,0,!1]}_getTwoDimCode(){let e,t=0;if(this.eoblock){t=this._lookBits(7);e=Ft[t];if(e?.[0]>0){this._eatBits(e[0]);return e[1]}}else{const e=this._findTableCode(1,7,Ft);if(e[0]&&e[2])return e[1]}info("Bad two dim code");return bt}_getWhiteCode(){let e,t=0;if(this.eoblock){t=this._lookBits(12);if(t===bt)return 1;e=t>>5?kt[t>>3]:St[t];if(e[0]>0){this._eatBits(e[0]);return e[1]}}else{let e=this._findTableCode(1,9,kt);if(e[0])return e[1];e=this._findTableCode(11,12,St);if(e[0])return e[1]}info("bad white code");this._eatBits(1);return 1}_getBlackCode(){let e,t;if(this.eoblock){e=this._lookBits(13);if(e===bt)return 1;t=e>>7?!(e>>9)&&e>>7?Nt[(e>>1)-64]:Gt[e>>7]:Rt[e];if(t[0]>0){this._eatBits(t[0]);return t[1]}}else{let e=this._findTableCode(2,6,Gt);if(e[0])return e[1];e=this._findTableCode(7,12,Nt,64);if(e[0])return e[1];e=this._findTableCode(10,13,Rt);if(e[0])return e[1]}info("bad black code");this._eatBits(1);return 1}_lookBits(e){let t;for(;this.inputBits>16-e;this.inputBuf=this.inputBuf<<8|t;this.inputBits+=8}return this.inputBuf>>this.inputBits-e&65535>>16-e}_eatBits(e){(this.inputBits-=e)<0&&(this.inputBits=0)}}class CCITTFaxStream extends DecodeStream{constructor(e,t,i){super(t);this.str=e;this.dict=e.dict;i instanceof Dict||(i=Dict.empty);const a={next:()=>e.getByte()};this.ccittFaxDecoder=new CCITTFaxDecoder(a,{K:i.get("K"),EndOfLine:i.get("EndOfLine"),EncodedByteAlign:i.get("EncodedByteAlign"),Columns:i.get("Columns"),Rows:i.get("Rows"),EndOfBlock:i.get("EndOfBlock"),BlackIs1:i.get("BlackIs1")})}readBlock(){for(;!this.eof;){const e=this.ccittFaxDecoder.readNextChar();if(-1===e){this.eof=!0;return}this.ensureBuffer(this.bufferLength+1);this.buffer[this.bufferLength++]=e}}}const Mt=new Int32Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ut=new Int32Array([3,4,5,6,7,8,9,10,65547,65549,65551,65553,131091,131095,131099,131103,196643,196651,196659,196667,262211,262227,262243,262259,327811,327843,327875,327907,258,258,258]),xt=new Int32Array([1,2,3,4,65541,65543,131081,131085,196625,196633,262177,262193,327745,327777,393345,393409,459009,459137,524801,525057,590849,591361,657409,658433,724993,727041,794625,798721,868353,876545]),Lt=[new Int32Array([459008,524368,524304,524568,459024,524400,524336,590016,459016,524384,524320,589984,524288,524416,524352,590048,459012,524376,524312,589968,459028,524408,524344,590032,459020,524392,524328,59e4,524296,524424,524360,590064,459010,524372,524308,524572,459026,524404,524340,590024,459018,524388,524324,589992,524292,524420,524356,590056,459014,524380,524316,589976,459030,524412,524348,590040,459022,524396,524332,590008,524300,524428,524364,590072,459009,524370,524306,524570,459025,524402,524338,590020,459017,524386,524322,589988,524290,524418,524354,590052,459013,524378,524314,589972,459029,524410,524346,590036,459021,524394,524330,590004,524298,524426,524362,590068,459011,524374,524310,524574,459027,524406,524342,590028,459019,524390,524326,589996,524294,524422,524358,590060,459015,524382,524318,589980,459031,524414,524350,590044,459023,524398,524334,590012,524302,524430,524366,590076,459008,524369,524305,524569,459024,524401,524337,590018,459016,524385,524321,589986,524289,524417,524353,590050,459012,524377,524313,589970,459028,524409,524345,590034,459020,524393,524329,590002,524297,524425,524361,590066,459010,524373,524309,524573,459026,524405,524341,590026,459018,524389,524325,589994,524293,524421,524357,590058,459014,524381,524317,589978,459030,524413,524349,590042,459022,524397,524333,590010,524301,524429,524365,590074,459009,524371,524307,524571,459025,524403,524339,590022,459017,524387,524323,589990,524291,524419,524355,590054,459013,524379,524315,589974,459029,524411,524347,590038,459021,524395,524331,590006,524299,524427,524363,590070,459011,524375,524311,524575,459027,524407,524343,590030,459019,524391,524327,589998,524295,524423,524359,590062,459015,524383,524319,589982,459031,524415,524351,590046,459023,524399,524335,590014,524303,524431,524367,590078,459008,524368,524304,524568,459024,524400,524336,590017,459016,524384,524320,589985,524288,524416,524352,590049,459012,524376,524312,589969,459028,524408,524344,590033,459020,524392,524328,590001,524296,524424,524360,590065,459010,524372,524308,524572,459026,524404,524340,590025,459018,524388,524324,589993,524292,524420,524356,590057,459014,524380,524316,589977,459030,524412,524348,590041,459022,524396,524332,590009,524300,524428,524364,590073,459009,524370,524306,524570,459025,524402,524338,590021,459017,524386,524322,589989,524290,524418,524354,590053,459013,524378,524314,589973,459029,524410,524346,590037,459021,524394,524330,590005,524298,524426,524362,590069,459011,524374,524310,524574,459027,524406,524342,590029,459019,524390,524326,589997,524294,524422,524358,590061,459015,524382,524318,589981,459031,524414,524350,590045,459023,524398,524334,590013,524302,524430,524366,590077,459008,524369,524305,524569,459024,524401,524337,590019,459016,524385,524321,589987,524289,524417,524353,590051,459012,524377,524313,589971,459028,524409,524345,590035,459020,524393,524329,590003,524297,524425,524361,590067,459010,524373,524309,524573,459026,524405,524341,590027,459018,524389,524325,589995,524293,524421,524357,590059,459014,524381,524317,589979,459030,524413,524349,590043,459022,524397,524333,590011,524301,524429,524365,590075,459009,524371,524307,524571,459025,524403,524339,590023,459017,524387,524323,589991,524291,524419,524355,590055,459013,524379,524315,589975,459029,524411,524347,590039,459021,524395,524331,590007,524299,524427,524363,590071,459011,524375,524311,524575,459027,524407,524343,590031,459019,524391,524327,589999,524295,524423,524359,590063,459015,524383,524319,589983,459031,524415,524351,590047,459023,524399,524335,590015,524303,524431,524367,590079]),9],Ht=[new Int32Array([327680,327696,327688,327704,327684,327700,327692,327708,327682,327698,327690,327706,327686,327702,327694,0,327681,327697,327689,327705,327685,327701,327693,327709,327683,327699,327691,327707,327687,327703,327695,0]),5];class FlateStream extends DecodeStream{constructor(e,t){super(t);this.str=e;this.dict=e.dict;const i=e.getByte(),a=e.getByte();if(-1===i||-1===a)throw new FormatError(`Invalid header in flate stream: ${i}, ${a}`);if(8!=(15&i))throw new FormatError(`Unknown compression method in flate stream: ${i}, ${a}`);if(((i<<8)+a)%31!=0)throw new FormatError(`Bad FCHECK in flate stream: ${i}, ${a}`);if(32&a)throw new FormatError(`FDICT bit set in flate stream: ${i}, ${a}`);this.codeSize=0;this.codeBuf=0}async getImageData(e,t){const i=await this.asyncGetBytes();return i?.subarray(0,e)||this.getBytes(e)}async asyncGetBytes(){this.str.reset();const e=this.str.getBytes();try{const{readable:t,writable:i}=new DecompressionStream("deflate"),a=i.getWriter();await a.ready;a.write(e).then((async()=>{await a.ready;await a.close()})).catch((()=>{}));const s=[];let r=0;for await(const e of t){s.push(e);r+=e.byteLength}const n=new Uint8Array(r);let g=0;for(const e of s){n.set(e,g);g+=e.byteLength}return n}catch{this.str=new Stream(e,2,e.length,this.str.dict);this.reset();return null}}get isAsync(){return!0}getBits(e){const t=this.str;let i,a=this.codeSize,s=this.codeBuf;for(;a>e;this.codeSize=a-=e;return i}getCode(e){const t=this.str,i=e[0],a=e[1];let s,r=this.codeSize,n=this.codeBuf;for(;r>16,c=65535&g;if(o<1||r>o;this.codeSize=r-o;return c}generateHuffmanTable(e){const t=e.length;let i,a=0;for(i=0;ia&&(a=e[i]);const s=1<>=1}for(i=e;i>=1;if(0===t){let t;if(-1===(t=a.getByte())){this.#m("Bad block header in flate stream");return}let i=t;if(-1===(t=a.getByte())){this.#m("Bad block header in flate stream");return}i|=t<<8;if(-1===(t=a.getByte())){this.#m("Bad block header in flate stream");return}let s=t;if(-1===(t=a.getByte())){this.#m("Bad block header in flate stream");return}s|=t<<8;if(s!==(65535&~i)&&(0!==i||0!==s))throw new FormatError("Bad uncompressed block length in flate stream");this.codeBuf=0;this.codeSize=0;const r=this.bufferLength,n=r+i;e=this.ensureBuffer(n);this.bufferLength=n;if(0===i)-1===a.peekByte()&&(this.eof=!0);else{const t=a.getBytes(i);e.set(t,r);t.length0;)C[g++]=Q}s=this.generateHuffmanTable(C.subarray(0,e));r=this.generateHuffmanTable(C.subarray(e,c))}}e=this.buffer;let n=e?e.length:0,g=this.bufferLength;for(;;){let t=this.getCode(s);if(t<256){if(g+1>=n){e=this.ensureBuffer(g+1);n=e.length}e[g++]=t;continue}if(256===t){this.bufferLength=g;return}t-=257;t=Ut[t];let a=t>>16;a>0&&(a=this.getBits(a));i=(65535&t)+a;t=this.getCode(r);t=xt[t];a=t>>16;a>0&&(a=this.getBits(a));const o=(65535&t)+a;if(g+i>=n){e=this.ensureBuffer(g+i);n=e.length}for(let t=0;t>9&127;this.clow=this.clow<<7&65535;this.ct-=7;this.a=32768}byteIn(){const e=this.data;let t=this.bp;if(255===e[t])if(e[t+1]>143){this.clow+=65280;this.ct=8}else{t++;this.clow+=e[t]<<9;this.ct=7;this.bp=t}else{t++;this.clow+=t65535){this.chigh+=this.clow>>16;this.clow&=65535}}readBit(e,t){let i=e[t]>>1,a=1&e[t];const s=Jt[i],r=s.qe;let n,g=this.a-r;if(this.chigh>15&1;this.clow=this.clow<<1&65535;this.ct--}while(!(32768&g));this.a=g;e[t]=i<<1|a;return n}}class Jbig2Error extends ot{constructor(e){super(e,"Jbig2Error")}}class ContextCache{getContexts(e){return e in this?this[e]:this[e]=new Int8Array(65536)}}class DecodingContext{constructor(e,t,i){this.data=e;this.start=t;this.end=i}get decoder(){return shadow(this,"decoder",new ArithmeticDecoder(this.data,this.start,this.end))}get contextCache(){return shadow(this,"contextCache",new ContextCache)}}function decodeInteger(e,t,i){const a=e.getContexts(t);let s=1;function readBits(e){let t=0;for(let r=0;r>>0}const r=readBits(1),n=readBits(1)?readBits(1)?readBits(1)?readBits(1)?readBits(1)?readBits(32)+4436:readBits(12)+340:readBits(8)+84:readBits(6)+20:readBits(4)+4:readBits(2);let g;0===r?g=n:n>0&&(g=-n);return g>=-2147483648&&g<=pt?g:null}function decodeIAID(e,t,i){const a=e.getContexts("IAID");let s=1;for(let e=0;e=F&&x=S){K=K<<1&d;for(u=0;u=0&&H=0){J=G[L][H];J&&(K|=J<=e?c<<=1:c=c<<1|w[g][o]}for(Q=0;Q=m||o<0||o>=p?c<<=1:c=c<<1|a[g][o]}const E=D.readBit(b,c);t[n]=E}}return w}function decodeTextRegion(e,t,i,a,s,r,n,g,o,c,C,h,l,Q,E,u,d,f,p){if(e&&t)throw new Jbig2Error("refinement with Huffman is not supported");const m=[];let y,w;for(y=0;y1&&(s=e?p.readBits(f):decodeInteger(b,"IAIT",D));const r=n*F+s,S=e?Q.symbolIDTable.decode(p):decodeIAID(b,D,o),k=t&&(e?p.readBit():decodeInteger(b,"IARI",D));let R=g[S],N=R[0].length,G=R.length;if(k){const e=decodeInteger(b,"IARDW",D),t=decodeInteger(b,"IARDH",D);N+=e;G+=t;R=decodeRefinement(N,G,E,R,(e>>1)+decodeInteger(b,"IARDX",D),(t>>1)+decodeInteger(b,"IARDY",D),!1,u,d)}let M=0;c?1&h?M=G-1:a+=G-1:h>1?a+=N-1:M=N-1;const U=r-(1&h?0:G-1),x=a-(2&h?N-1:0);let L,H,J;if(c)for(L=0;L>5&7;const o=[31&n];let c=t+6;if(7===n){g=536870911&readUint32(e,c-1);c+=3;let t=g+7>>3;o[0]=e[c++];for(;--t>0;)o.push(e[c++])}else if(5===n||6===n)throw new Jbig2Error("invalid referred-to flags");i.retainBits=o;let C=4;i.number<=256?C=1:i.number<=65536&&(C=2);const h=[];let l,Q;for(l=0;l>>24&255;r[3]=t.height>>16&255;r[4]=t.height>>8&255;r[5]=255&t.height;for(l=c,Q=e.length;l>2&3;e.huffmanDWSelector=t>>4&3;e.bitmapSizeSelector=t>>6&1;e.aggregationInstancesSelector=t>>7&1;e.bitmapCodingContextUsed=!!(256&t);e.bitmapCodingContextRetained=!!(512&t);e.template=t>>10&3;e.refinementTemplate=t>>12&1;c+=2;if(!e.huffman){o=0===e.template?4:1;n=[];for(g=0;g>2&3;C.stripSize=1<>4&3;C.transposed=!!(64&h);C.combinationOperator=h>>7&3;C.defaultPixelValue=h>>9&1;C.dsOffset=h<<17>>27;C.refinementTemplate=h>>15&1;if(C.huffman){const e=readUint16(a,c);c+=2;C.huffmanFS=3&e;C.huffmanDS=e>>2&3;C.huffmanDT=e>>4&3;C.huffmanRefinementDW=e>>6&3;C.huffmanRefinementDH=e>>8&3;C.huffmanRefinementDX=e>>10&3;C.huffmanRefinementDY=e>>12&3;C.huffmanRefinementSizeSelector=!!(16384&e)}if(C.refinement&&!C.refinementTemplate){n=[];for(g=0;g<2;g++){n.push({x:readInt8(a,c),y:readInt8(a,c+1)});c+=2}C.refinementAt=n}C.numberOfSymbolInstances=readUint32(a,c);c+=4;r=[C,i.referredTo,a,c,s];break;case 16:const l={},Q=a[c++];l.mmr=!!(1&Q);l.template=Q>>1&3;l.patternWidth=a[c++];l.patternHeight=a[c++];l.maxPatternIndex=readUint32(a,c);c+=4;r=[l,i.number,a,c,s];break;case 22:case 23:const E={};E.info=readRegionSegmentInformation(a,c);c+=Ot;const u=a[c++];E.mmr=!!(1&u);E.template=u>>1&3;E.enableSkip=!!(8&u);E.combinationOperator=u>>4&7;E.defaultPixelValue=u>>7&1;E.gridWidth=readUint32(a,c);c+=4;E.gridHeight=readUint32(a,c);c+=4;E.gridOffsetX=4294967295&readUint32(a,c);c+=4;E.gridOffsetY=4294967295&readUint32(a,c);c+=4;E.gridVectorX=readUint16(a,c);c+=2;E.gridVectorY=readUint16(a,c);c+=2;r=[E,i.referredTo,a,c,s];break;case 38:case 39:const d={};d.info=readRegionSegmentInformation(a,c);c+=Ot;const f=a[c++];d.mmr=!!(1&f);d.template=f>>1&3;d.prediction=!!(8&f);if(!d.mmr){o=0===d.template?4:1;n=[];for(g=0;g>2&1;p.combinationOperator=m>>3&3;p.requiresBuffer=!!(32&m);p.combinationOperatorOverride=!!(64&m);r=[p];break;case 49:case 50:case 51:case 62:break;case 53:r=[i.number,a,c,s];break;default:throw new Jbig2Error(`segment type ${i.typeName}(${i.type}) is not implemented`)}const C="on"+i.typeName;C in t&&t[C].apply(t,r)}function processSegments(e,t){for(let i=0,a=e.length;i>3,i=new Uint8ClampedArray(t*e.height);e.defaultPixelValue&&i.fill(255);this.buffer=i}drawBitmap(e,t){const i=this.currentPageInfo,a=e.width,s=e.height,r=i.width+7>>3,n=i.combinationOperatorOverride?e.combinationOperator:i.combinationOperator,g=this.buffer,o=128>>(7&e.x);let c,C,h,l,Q=e.y*r+(e.x>>3);switch(n){case 0:for(c=0;c>=1;if(!h){h=128;l++}}Q+=r}break;case 2:for(c=0;c>=1;if(!h){h=128;l++}}Q+=r}break;default:throw new Jbig2Error(`operator ${n} is not supported`)}}onImmediateGenericRegion(e,t,i,a){const s=e.info,r=new DecodingContext(t,i,a),n=decodeBitmap(e.mmr,s.width,s.height,e.template,e.prediction,null,e.at,r);this.drawBitmap(s,n)}onImmediateLosslessGenericRegion(){this.onImmediateGenericRegion(...arguments)}onSymbolDictionary(e,t,i,a,s,r){let n,g;if(e.huffman){n=function getSymbolDictionaryHuffmanTables(e,t,i){let a,s,r,n,g=0;switch(e.huffmanDHSelector){case 0:case 1:a=getStandardTable(e.huffmanDHSelector+4);break;case 3:a=getCustomHuffmanTable(g,t,i);g++;break;default:throw new Jbig2Error("invalid Huffman DH selector")}switch(e.huffmanDWSelector){case 0:case 1:s=getStandardTable(e.huffmanDWSelector+2);break;case 3:s=getCustomHuffmanTable(g,t,i);g++;break;default:throw new Jbig2Error("invalid Huffman DW selector")}if(e.bitmapSizeSelector){r=getCustomHuffmanTable(g,t,i);g++}else r=getStandardTable(1);n=e.aggregationInstancesSelector?getCustomHuffmanTable(g,t,i):getStandardTable(1);return{tableDeltaHeight:a,tableDeltaWidth:s,tableBitmapSize:r,tableAggregateInstances:n}}(e,i,this.customTables);g=new Reader(a,s,r)}let o=this.symbols;o||(this.symbols=o={});const c=[];for(const e of i){const t=o[e];t&&c.push(...t)}const C=new DecodingContext(a,s,r);o[t]=function decodeSymbolDictionary(e,t,i,a,s,r,n,g,o,c,C,h){if(e&&t)throw new Jbig2Error("symbol refinement with Huffman is not supported");const l=[];let Q=0,E=log2(i.length+a);const u=C.decoder,d=C.contextCache;let f,p;if(e){f=getStandardTable(1);p=[];E=Math.max(E,1)}for(;l.length1)m=decodeTextRegion(e,t,a,Q,0,s,1,i.concat(l),E,0,0,1,0,r,o,c,C,0,h);else{const e=decodeIAID(d,u,E),t=decodeInteger(d,"IARDX",u),s=decodeInteger(d,"IARDY",u);m=decodeRefinement(a,Q,o,e=32){let i,a,n;switch(t){case 32:if(0===e)throw new Jbig2Error("no previous value in symbol ID table");a=s.readBits(2)+3;i=r[e-1].prefixLength;break;case 33:a=s.readBits(3)+3;i=0;break;case 34:a=s.readBits(7)+11;i=0;break;default:throw new Jbig2Error("invalid code length in symbol ID table")}for(n=0;n=0;d--){R=e?decodeMMRBitmap(k,o,c,!0):decodeBitmap(!1,o,c,i,!1,null,F,E);S[d]=R}for(N=0;N=0;f--){M^=S[f][N][G];U|=M<>8;H=h+N*l-G*Q>>8;if(L>=0&&L+w<=a&&H>=0&&H+D<=s)for(d=0;d=s)){Y=u[t];J=x[d];for(f=0;f=0&&e>1&7),o=1+(a>>4&7),c=[];let C,h,l=s;do{C=n.readBits(g);h=n.readBits(o);c.push(new HuffmanLine([l,C,h,0]));l+=1<>t&1;if(t<=0)this.children[i]=new HuffmanTreeNode(e);else{let a=this.children[i];a||(this.children[i]=a=new HuffmanTreeNode(null));a.buildTree(e,t-1)}}decodeNode(e){if(this.isLeaf){if(this.isOOB)return null;const t=e.readBits(this.rangeLength);return this.rangeLow+(this.isLowerRange?-t:t)}const t=this.children[e.readBit()];if(!t)throw new Jbig2Error("invalid Huffman data");return t.decodeNode(e)}}class HuffmanTable{constructor(e,t){t||this.assignPrefixCodes(e);this.rootNode=new HuffmanTreeNode(null);for(let t=0,i=e.length;t0&&this.rootNode.buildTree(i,i.prefixLength-1)}}decode(e){return this.rootNode.decodeNode(e)}assignPrefixCodes(e){const t=e.length;let i=0;for(let a=0;a=this.end)throw new Jbig2Error("end of data while reading bit");this.currentByte=this.data[this.position++];this.shift=7}const e=this.currentByte>>this.shift&1;this.shift--;return e}readBits(e){let t,i=0;for(t=e-1;t>=0;t--)i|=this.readBit()<=this.end?-1:this.data[this.position++]}}function getCustomHuffmanTable(e,t,i){let a=0;for(let s=0,r=t.length;s>i&1;i--}}if(a&&!g){const e=5;for(let t=0;t>2,c=new Uint32Array(e.buffer,t,o);if(FeatureTest.isLittleEndian){for(;n>>24|t<<8|4278190080;i[a+2]=t>>>16|s<<16|4278190080;i[a+3]=s>>>8|4278190080}for(let s=4*n,r=t+g;s>>8|255;i[a+2]=t<<16|s>>>16|255;i[a+3]=s<<8|255}for(let s=4*n,r=t+g;s>3,h=7&a,l=e.length;i=new Uint32Array(i.buffer);let Q=0;for(let a=0;a0&&!e[r-1];)r--;const n=[{children:[],index:0}];let g,o=n[0];for(i=0;i0;)o=n.pop();o.index++;n.push(o);for(;n.length<=i;){n.push(g={children:[],index:0});o.children[o.index]=g.children;o=g}s++}if(i+10){E--;return Q>>E&1}Q=e[t++];if(255===Q){const a=e[t++];if(a){if(220===a&&c){const a=readUint16(e,t+=2);t+=2;if(a>0&&a!==i.scanLines)throw new DNLMarkerError("Found DNL marker (0xFFDC) while parsing scan data",a)}else if(217===a){if(c){const e=p*(8===i.precision?8:0);if(e>0&&Math.round(i.scanLines/e)>=5)throw new DNLMarkerError("Found EOI marker (0xFFD9) while parsing scan data, possibly caused by incorrect `scanLines` parameter",e)}throw new EOIMarkerError("Found EOI marker (0xFFD9) while parsing scan data")}throw new JpegError(`unexpected marker ${(Q<<8|a).toString(16)}`)}}E=7;return Q>>>7}function decodeHuffman(e){let t=e;for(;;){t=t[readBit()];switch(typeof t){case"number":return t;case"object":continue}throw new JpegError("invalid huffman sequence")}}function receive(e){let t=0;for(;e>0;){t=t<<1|readBit();e--}return t}function receiveAndExtend(e){if(1===e)return 1===readBit()?1:-1;const t=receive(e);return t>=1<0){u--;return}let i=r;const a=n;for(;i<=a;){const a=decodeHuffman(e.huffmanTableAC),s=15&a,r=a>>4;if(0===s){if(r<15){u=receive(r)+(1<>4;if(0===s)if(c<15){u=receive(c)+(1<>4;if(0===a){if(r<15)break;s+=16;continue}s+=r;const n=Wt[s];e.blockData[t+n]=receiveAndExtend(a);s++}};let k,R=0;const N=1===m?a[0].blocksPerLine*a[0].blocksPerColumn:C*i.mcusPerColumn;let G,M;for(;R<=N;){const i=s?Math.min(N-R,s):N;if(i>0){for(w=0;w0?"unexpected":"excessive"} MCU data, current marker is: ${k.invalid}`);t=k.offset}if(!(k.marker>=65488&&k.marker<=65495))break;t+=2}return t-l}function quantizeAndInverse(e,t,i){const a=e.quantizationTable,s=e.blockData;let r,n,g,o,c,C,h,l,Q,E,u,d,f,p,m,y,w;if(!a)throw new JpegError("missing required Quantization Table.");for(let e=0;e<64;e+=8){Q=s[t+e];E=s[t+e+1];u=s[t+e+2];d=s[t+e+3];f=s[t+e+4];p=s[t+e+5];m=s[t+e+6];y=s[t+e+7];Q*=a[e];if(E|u|d|f|p|m|y){E*=a[e+1];u*=a[e+2];d*=a[e+3];f*=a[e+4];p*=a[e+5];m*=a[e+6];y*=a[e+7];r=$t*Q+128>>8;n=$t*f+128>>8;g=u;o=m;c=Ai*(E-y)+128>>8;l=Ai*(E+y)+128>>8;C=d<<4;h=p<<4;r=r+n+1>>1;n=r-n;w=g*_t+o*zt+128>>8;g=g*zt-o*_t+128>>8;o=w;c=c+h+1>>1;h=c-h;l=l+C+1>>1;C=l-C;r=r+o+1>>1;o=r-o;n=n+g+1>>1;g=n-g;w=c*Vt+l*Zt+2048>>12;c=c*Zt-l*Vt+2048>>12;l=w;w=C*Xt+h*jt+2048>>12;C=C*jt-h*Xt+2048>>12;h=w;i[e]=r+l;i[e+7]=r-l;i[e+1]=n+h;i[e+6]=n-h;i[e+2]=g+C;i[e+5]=g-C;i[e+3]=o+c;i[e+4]=o-c}else{w=$t*Q+512>>10;i[e]=w;i[e+1]=w;i[e+2]=w;i[e+3]=w;i[e+4]=w;i[e+5]=w;i[e+6]=w;i[e+7]=w}}for(let e=0;e<8;++e){Q=i[e];E=i[e+8];u=i[e+16];d=i[e+24];f=i[e+32];p=i[e+40];m=i[e+48];y=i[e+56];if(E|u|d|f|p|m|y){r=$t*Q+2048>>12;n=$t*f+2048>>12;g=u;o=m;c=Ai*(E-y)+2048>>12;l=Ai*(E+y)+2048>>12;C=d;h=p;r=4112+(r+n+1>>1);n=r-n;w=g*_t+o*zt+2048>>12;g=g*zt-o*_t+2048>>12;o=w;c=c+h+1>>1;h=c-h;l=l+C+1>>1;C=l-C;r=r+o+1>>1;o=r-o;n=n+g+1>>1;g=n-g;w=c*Vt+l*Zt+2048>>12;c=c*Zt-l*Vt+2048>>12;l=w;w=C*Xt+h*jt+2048>>12;C=C*jt-h*Xt+2048>>12;h=w;Q=r+l;y=r-l;E=n+h;m=n-h;u=g+C;p=g-C;d=o+c;f=o-c;Q<16?Q=0:Q>=4080?Q=255:Q>>=4;E<16?E=0:E>=4080?E=255:E>>=4;u<16?u=0:u>=4080?u=255:u>>=4;d<16?d=0:d>=4080?d=255:d>>=4;f<16?f=0:f>=4080?f=255:f>>=4;p<16?p=0:p>=4080?p=255:p>>=4;m<16?m=0:m>=4080?m=255:m>>=4;y<16?y=0:y>=4080?y=255:y>>=4;s[t+e]=Q;s[t+e+8]=E;s[t+e+16]=u;s[t+e+24]=d;s[t+e+32]=f;s[t+e+40]=p;s[t+e+48]=m;s[t+e+56]=y}else{w=$t*Q+8192>>14;w=w<-2040?0:w>=2024?255:w+2056>>4;s[t+e]=w;s[t+e+8]=w;s[t+e+16]=w;s[t+e+24]=w;s[t+e+32]=w;s[t+e+40]=w;s[t+e+48]=w;s[t+e+56]=w}}}function buildComponentData(e,t){const i=t.blocksPerLine,a=t.blocksPerColumn,s=new Int16Array(64);for(let e=0;e=a)return null;const r=readUint16(e,t);if(r>=65472&&r<=65534)return{invalid:null,marker:r,offset:t};let n=readUint16(e,s);for(;!(n>=65472&&n<=65534);){if(++s>=a)return null;n=readUint16(e,s)}return{invalid:r.toString(16),marker:n,offset:s}}function prepareComponents(e){const t=Math.ceil(e.samplesPerLine/8/e.maxH),i=Math.ceil(e.scanLines/8/e.maxV);for(const a of e.components){const s=Math.ceil(Math.ceil(e.samplesPerLine/8)*a.h/e.maxH),r=Math.ceil(Math.ceil(e.scanLines/8)*a.v/e.maxV),n=t*a.h,g=64*(i*a.v)*(n+1);a.blockData=new Int16Array(g);a.blocksPerLine=s;a.blocksPerColumn=r}e.mcusPerLine=t;e.mcusPerColumn=i}function readDataBlock(e,t){const i=readUint16(e,t);let a=(t+=2)+i-2;const s=findNextFileMarker(e,a,t);if(s?.invalid){warn("readDataBlock - incorrect length, current marker is: "+s.invalid);a=s.offset}const r=e.subarray(t,a);return{appData:r,newOffset:t+=r.length}}function skipData(e,t){const i=readUint16(e,t),a=(t+=2)+i-2,s=findNextFileMarker(e,a,t);return s?.invalid?s.offset:a}class JpegImage{constructor({decodeTransform:e=null,colorTransform:t=-1}={}){this._decodeTransform=e;this._colorTransform=t}static canUseImageDecoder(e,t=-1){let i=0,a=null,s=readUint16(e,i);i+=2;if(65496!==s)throw new JpegError("SOI not found");s=readUint16(e,i);i+=2;A:for(;65497!==s;){switch(s){case 65472:case 65473:case 65474:a=e[i+7];break A;case 65535:255!==e[i]&&i--}i=skipData(e,i);s=readUint16(e,i);i+=2}return 4!==a&&(3!==a||0!==t)}parse(e,{dnlScanLines:t=null}={}){let i,a,s=0,r=null,n=null,g=0;const o=[],c=[],C=[];let h=readUint16(e,s);s+=2;if(65496!==h)throw new JpegError("SOI not found");h=readUint16(e,s);s+=2;A:for(;65497!==h;){let l,Q,E;switch(h){case 65504:case 65505:case 65506:case 65507:case 65508:case 65509:case 65510:case 65511:case 65512:case 65513:case 65514:case 65515:case 65516:case 65517:case 65518:case 65519:case 65534:const{appData:u,newOffset:d}=readDataBlock(e,s);s=d;65504===h&&74===u[0]&&70===u[1]&&73===u[2]&&70===u[3]&&0===u[4]&&(r={version:{major:u[5],minor:u[6]},densityUnits:u[7],xDensity:u[8]<<8|u[9],yDensity:u[10]<<8|u[11],thumbWidth:u[12],thumbHeight:u[13],thumbData:u.subarray(14,14+3*u[12]*u[13])});65518===h&&65===u[0]&&100===u[1]&&111===u[2]&&98===u[3]&&101===u[4]&&(n={version:u[5]<<8|u[6],flags0:u[7]<<8|u[8],flags1:u[9]<<8|u[10],transformCode:u[11]});break;case 65499:const f=readUint16(e,s);s+=2;const p=f+s-2;let m;for(;s>4){if(t>>4!=1)throw new JpegError("DQT - invalid table spec");for(Q=0;Q<64;Q++){m=Wt[Q];i[m]=readUint16(e,s);s+=2}}else for(Q=0;Q<64;Q++){m=Wt[Q];i[m]=e[s++]}o[15&t]=i}break;case 65472:case 65473:case 65474:if(i)throw new JpegError("Only single frame JPEGs supported");s+=2;i={};i.extended=65473===h;i.progressive=65474===h;i.precision=e[s++];const y=readUint16(e,s);s+=2;i.scanLines=t||y;i.samplesPerLine=readUint16(e,s);s+=2;i.components=[];i.componentIds={};const w=e[s++];let D=0,b=0;for(l=0;l>4,r=15&e[s+1];D>4?c:C)[15&t]=buildHuffmanTable(i,r)}break;case 65501:s+=2;a=readUint16(e,s);s+=2;break;case 65498:const S=1==++g&&!t;s+=2;const k=e[s++],R=[];for(l=0;l>4];r.huffmanTableAC=c[15&n];R.push(r)}const N=e[s++],G=e[s++],M=e[s++];try{s+=decodeScan(e,s,i,R,a,N,G,M>>4,15&M,S)}catch(t){if(t instanceof DNLMarkerError){warn(`${t.message} -- attempting to re-parse the JPEG image.`);return this.parse(e,{dnlScanLines:t.scanLines})}if(t instanceof EOIMarkerError){warn(`${t.message} -- ignoring the rest of the image data.`);break A}throw t}break;case 65500:s+=4;break;case 65535:255!==e[s]&&s--;break;default:const U=findNextFileMarker(e,s-2,s-3);if(U?.invalid){warn("JpegImage.parse - unexpected data, current marker is: "+U.invalid);s=U.offset;break}if(!U||s>=e.length-1){warn("JpegImage.parse - reached the end of the image data without finding an EOI marker (0xFFD9).");break A}throw new JpegError("JpegImage.parse - unknown marker: "+h.toString(16))}h=readUint16(e,s);s+=2}if(!i)throw new JpegError("JpegImage.parse - no frame data found.");this.width=i.samplesPerLine;this.height=i.scanLines;this.jfif=r;this.adobe=n;this.components=[];for(const e of i.components){const t=o[e.quantizationId];t&&(e.quantizationTable=t);this.components.push({index:e.index,output:buildComponentData(0,e),scaleX:e.h/i.maxH,scaleY:e.v/i.maxV,blocksPerLine:e.blocksPerLine,blocksPerColumn:e.blocksPerColumn})}this.numComponents=this.components.length}_getLinearizedBlockData(e,t,i=!1){const a=this.width/e,s=this.height/t;let r,n,g,o,c,C,h,l,Q,E,u,d=0;const f=this.components.length,p=e*t*f,m=new Uint8ClampedArray(p),y=new Uint32Array(e),w=4294967288;let D;for(h=0;h>8)+b[Q+1];return m}get _isColorConversionNeeded(){return this.adobe?!!this.adobe.transformCode:3===this.numComponents?0!==this._colorTransform&&(82!==this.components[0].index||71!==this.components[1].index||66!==this.components[2].index):1===this._colorTransform}_convertYccToRgb(e){let t,i,a;for(let s=0,r=e.length;s4)throw new JpegError("Unsupported color mode");const r=this._getLinearizedBlockData(e,t,s);if(1===this.numComponents&&(i||a)){const e=r.length*(i?4:3),t=new Uint8ClampedArray(e);let a=0;if(i)!function grayToRGBA(e,t){if(FeatureTest.isLittleEndian)for(let i=0,a=e.length;i0&&(e=e.subarray(t));break}return e}decodeImage(e){if(this.eof)return this.buffer;e=this.#w(e||this.bytes);const t=new JpegImage(this.jpegOptions);t.parse(e);const i=t.getData({width:this.drawWidth,height:this.drawHeight,forceRGBA:this.forceRGBA,forceRGB:this.forceRGB,isSourcePDF:!0});this.buffer=i;this.bufferLength=i.length;this.eof=!0;return this.buffer}get canAsyncDecodeImageFromBuffer(){return this.stream.isAsync}async getTransferableImage(){if(!await JpegStream.canUseImageDecoder)return null;const e=this.jpegOptions;if(e.decodeTransform)return null;let t;try{const i=this.canAsyncDecodeImageFromBuffer&&await this.stream.asyncGetBytes()||this.bytes;if(!i)return null;const a=this.#w(i);if(!JpegImage.canUseImageDecoder(a,e.colorTransform))return null;t=new ImageDecoder({data:a,type:"image/jpeg",preferAnimation:!1});return(await t.decode()).image}catch(e){warn(`getTransferableImage - failed: "${e}".`);return null}finally{t?.close()}}}var ei,ti=(ei="undefined"!=typeof document?document.currentScript?.src:void 0,function(e={}){var t,i,a=e;new Promise(((e,a)=>{t=e;i=a}));a.decode=function(e,{numComponents:t=4,isIndexedColormap:i=!1,smaskInData:s=!1}){const r=e.length,n=a._malloc(r);a.HEAPU8.set(e,n);const g=a._jp2_decode(n,r,t>0?t:0,!!i,!!s);a._free(n);if(g){const{errorMessages:e}=a;if(e){delete a.errorMessages;return e}return"Unknown error"}const{imageData:o}=a;a.imageData=null;return o};var s=Object.assign({},a),r="./this.program",quit_=(e,t)=>{throw t},n="";"undefined"!=typeof document&&document.currentScript&&(n=document.currentScript.src);ei&&(n=ei);n=n.startsWith("blob:")?"":n.substr(0,n.replace(/[?#].*/,"").lastIndexOf("/")+1);var g=a.print||console.log.bind(console),o=a.printErr||console.error.bind(console);Object.assign(a,s);s=null;a.arguments&&a.arguments;a.thisProgram&&(r=a.thisProgram);var c,C=a.wasmBinary;function tryParseAsDataURI(e){if(isDataURI(e))return function intArrayFromBase64(e){for(var t=atob(e),i=new Uint8Array(t.length),a=0;ae.startsWith(b);function instantiateSync(e,t){var i,a=function getBinarySync(e){if(e==d&&C)return new Uint8Array(C);var t=tryParseAsDataURI(e);if(t)return t;throw'sync fetching of the wasm failed: you can preload it to Module["wasmBinary"] manually, or emcc.py will do that for you when generating HTML (but not JS)'}(e);i=new WebAssembly.Module(a);return[new WebAssembly.Instance(i,t),i]}class ExitStatus{name="ExitStatus";constructor(e){this.message=`Program terminated with exit(${e})`;this.status=e}}var F,callRuntimeCallbacks=e=>{for(;e.length>0;)e.shift()(a)},S=a.noExitRuntime||!0,k=0,R={},handleException=e=>{if(e instanceof ExitStatus||"unwind"==e)return h;quit_(0,e)},keepRuntimeAlive=()=>S||k>0,_proc_exit=e=>{h=e;if(!keepRuntimeAlive()){a.onExit?.(e);u=!0}quit_(0,new ExitStatus(e))},_exit=(e,t)=>{h=e;_proc_exit(e)},callUserCallback=e=>{if(!u)try{e();(()=>{if(!keepRuntimeAlive())try{_exit(h)}catch(e){handleException(e)}})()}catch(e){handleException(e)}},growMemory=e=>{var t=(e-c.buffer.byteLength+65535)/65536|0;try{c.grow(t);updateMemoryViews();return 1}catch(e){}},N={},getEnvStrings=()=>{if(!getEnvStrings.strings){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:r||"./this.program"};for(var t in N)void 0===N[t]?delete e[t]:e[t]=N[t];var i=[];for(var t in e)i.push(`${t}=${e[t]}`);getEnvStrings.strings=i}return getEnvStrings.strings},G=[null,[],[]],M="undefined"!=typeof TextDecoder?new TextDecoder:void 0,UTF8ArrayToString=(e,t=0,i=NaN)=>{for(var a=t+i,s=t;e[s]&&!(s>=a);)++s;if(s-t>16&&e.buffer&&M)return M.decode(e.subarray(t,s));for(var r="";t>10,56320|1023&c)}}else r+=String.fromCharCode((31&n)<<6|g)}else r+=String.fromCharCode(n)}return r},printChar=(e,t)=>{var i=G[e];if(0===t||10===t){(1===e?g:o)(UTF8ArrayToString(i));i.length=0}else i.push(t)},UTF8ToString=(e,t)=>e?UTF8ArrayToString(Q,e,t):"",U={m:()=>function abort(e){a.onAbort?.(e);o(e="Aborted("+e+")");u=!0;e+=". Build with -sASSERTIONS for more info.";var t=new WebAssembly.RuntimeError(e);i(t);throw t}(""),c:(e,t,i)=>Q.copyWithin(e,t,t+i),l:()=>{S=!1;k=0},n:(e,t)=>{if(R[e]){clearTimeout(R[e].id);delete R[e]}if(!t)return 0;var i=setTimeout((()=>{delete R[e];callUserCallback((()=>L(e,performance.now())))}),t);R[e]={id:i,timeout_ms:t};return 0},g:function _copy_pixels_1(e,t){e>>=2;const i=a.imageData=new Uint8ClampedArray(t),s=a.HEAP32.subarray(e,e+t);i.set(s)},f:function _copy_pixels_3(e,t,i,s){e>>=2;t>>=2;i>>=2;const r=a.imageData=new Uint8ClampedArray(3*s),n=a.HEAP32.subarray(e,e+s),g=a.HEAP32.subarray(t,t+s),o=a.HEAP32.subarray(i,i+s);for(let e=0;e>=2;t>>=2;i>>=2;s>>=2;const n=a.imageData=new Uint8ClampedArray(4*r),g=a.HEAP32.subarray(e,e+r),o=a.HEAP32.subarray(t,t+r),c=a.HEAP32.subarray(i,i+r),C=a.HEAP32.subarray(s,s+r);for(let e=0;e{var t,i,a=Q.length,s=2147483648;if((e>>>=0)>s)return!1;for(var r=1;r<=4;r*=2){var n=a*(1+.2/r);n=Math.min(n,e+100663296);var g=Math.min(s,(t=Math.max(e,n),i=65536,Math.ceil(t/i)*i));if(growMemory(g))return!0}return!1},p:(e,t)=>{var i=0;getEnvStrings().forEach(((a,s)=>{var r=t+i;E[e+4*s>>2]=r;((e,t)=>{for(var i=0;i{var i=getEnvStrings();E[e>>2]=i.length;var a=0;i.forEach((e=>a+=e.length+1));E[t>>2]=a;return 0},r:e=>52,j:function _fd_seek(e,t,i,a,s){return 70},b:(e,t,i,a)=>{for(var s=0,r=0;r>2],g=E[t+4>>2];t+=8;for(var o=0;o>2]=s;return 0},s:function _gray_to_rgba(e,t){e>>=2;const i=a.imageData=new Uint8ClampedArray(4*t),s=a.HEAP32.subarray(e,e+t);for(let e=0;e>=2;t>>=2;const s=a.imageData=new Uint8ClampedArray(4*i),r=a.HEAP32.subarray(e,e+i),n=a.HEAP32.subarray(t,t+i);for(let e=0;e>=2;t>>=2;i>>=2;const r=a.imageData=new Uint8ClampedArray(4*s),n=a.HEAP32.subarray(e,e+s),g=a.HEAP32.subarray(t,t+s),o=a.HEAP32.subarray(i,i+s);for(let e=0;e0)){!function preRun(){if(a.preRun){"function"==typeof a.preRun&&(a.preRun=[a.preRun]);for(;a.preRun.length;)e=a.preRun.shift(),f.unshift(e)}var e;callRuntimeCallbacks(f)}();if(!(y>0))if(a.setStatus){a.setStatus("Running...");setTimeout((()=>{setTimeout((()=>a.setStatus("")),1);doRun()}),1)}else doRun()}function doRun(){if(!F){F=!0;a.calledRun=!0;if(!u){!function initRuntime(){callRuntimeCallbacks(p)}();t(a);a.onRuntimeInitialized?.();!function postRun(){if(a.postRun){"function"==typeof a.postRun&&(a.postRun=[a.postRun]);for(;a.postRun.length;)e=a.postRun.shift(),m.unshift(e)}var e;callRuntimeCallbacks(m)}()}}}}if(a.preInit){"function"==typeof a.preInit&&(a.preInit=[a.preInit]);for(;a.preInit.length>0;)a.preInit.pop()()}run();return a});const ii=ti;class JpxError extends ot{constructor(e){super(e,"JpxError")}}class JpxImage{static#D=null;static decode(e,t){t||={};this.#D||=ii({warn});const i=this.#D.decode(e,t);if("string"==typeof i)throw new JpxError(i);return i}static cleanup(){this.#D=null}static parseImageProperties(e){let t=e.getByte();for(;t>=0;){const i=t;t=e.getByte();if(65361===(i<<8|t)){e.skip(4);const t=e.getInt32()>>>0,i=e.getInt32()>>>0,a=e.getInt32()>>>0,s=e.getInt32()>>>0;e.skip(16);return{width:t-a,height:i-s,bitsPerComponent:8,componentsCount:e.getUint16()}}}throw new JpxError("No size marker found in JPX stream")}}class JpxStream extends DecodeStream{constructor(e,t,i){super(t);this.stream=e;this.dict=e.dict;this.maybeLength=t;this.params=i}get bytes(){return shadow(this,"bytes",this.stream.getBytes(this.maybeLength))}ensureBuffer(e){}readBlock(e){this.decodeImage(null,e)}decodeImage(e,t){if(this.eof)return this.buffer;e||=this.bytes;this.buffer=JpxImage.decode(e,t);this.bufferLength=this.buffer.length;this.eof=!0;return this.buffer}get canAsyncDecodeImageFromBuffer(){return this.stream.isAsync}}class LZWStream extends DecodeStream{constructor(e,t,i){super(t);this.str=e;this.dict=e.dict;this.cachedData=0;this.bitsCached=0;const a=4096,s={earlyChange:i,codeLength:9,nextCode:258,dictionaryValues:new Uint8Array(a),dictionaryLengths:new Uint16Array(a),dictionaryPrevCodes:new Uint16Array(a),currentSequence:new Uint8Array(a),currentSequenceLength:0};for(let e=0;e<256;++e){s.dictionaryValues[e]=e;s.dictionaryLengths[e]=1}this.lzwState=s}readBits(e){let t=this.bitsCached,i=this.cachedData;for(;t>>t&(1<0;if(e<256){l[0]=e;Q=1}else{if(!(e>=258)){if(256===e){C=9;n=258;Q=0;continue}this.eof=!0;delete this.lzwState;break}if(e=0;t--){l[t]=g[i];i=c[i]}}else l[Q++]=l[0]}if(s){c[n]=h;o[n]=o[h]+1;g[n]=l[0];n++;C=n+r&n+r-1?C:0|Math.min(Math.log(n+r)/.6931471805599453+1,12)}h=e;E+=Q;if(a15))throw new FormatError(`Unsupported predictor: ${a}`);this.readBlock=2===a?this.readBlockTiff:this.readBlockPng;this.str=e;this.dict=e.dict;const s=this.colors=i.get("Colors")||1,r=this.bits=i.get("BPC","BitsPerComponent")||8,n=this.columns=i.get("Columns")||1;this.pixBytes=s*r+7>>3;this.rowBytes=n*s*r+7>>3;return this}readBlockTiff(){const e=this.rowBytes,t=this.bufferLength,i=this.ensureBuffer(t+e),a=this.bits,s=this.colors,r=this.str.getBytes(e);this.eof=!r.length;if(this.eof)return;let n,g=0,o=0,c=0,C=0,h=t;if(1===a&&1===s)for(n=0;n>1;e^=e>>2;e^=e>>4;g=(1&e)<<7;i[h++]=e}else if(8===a){for(n=0;n>8&255;i[h++]=255&e}}else{const e=new Uint8Array(s+1),h=(1<>c-a)&h;c-=a;o=o<=8){i[Q++]=o>>C-8&255;C-=8}}C>0&&(i[Q++]=(o<<8-C)+(g&(1<<8-C)-1))}this.bufferLength+=e}readBlockPng(){const e=this.rowBytes,t=this.pixBytes,i=this.str.getByte(),a=this.str.getBytes(e);this.eof=!a.length;if(this.eof)return;const s=this.bufferLength,r=this.ensureBuffer(s+e);let n=r.subarray(s-e,s);0===n.length&&(n=new Uint8Array(e));let g,o,c,C=s;switch(i){case 0:for(g=0;g>1)+a[g];for(;g>1)+a[g]&255;C++}break;case 4:for(g=0;g0){const e=this.str.getBytes(a);t.set(e,i);i+=a}}else{a=257-a;const s=e[1];t=this.ensureBuffer(i+a+1);for(let e=0;e>")&&this.buf1!==Bt;){if(!(this.buf1 instanceof Name)){info("Malformed dictionary: key must be a name object");this.shift();continue}const t=this.buf1.name;this.shift();if(this.buf1===Bt)break;a.set(t,this.getObj(e))}if(this.buf1===Bt){if(this.recoveryMode)return a;throw new ParserEOFException("End of file inside dictionary.")}if(isCmd(this.buf2,"stream"))return this.allowStreams?this.makeStream(a,e):a;this.shift();return a;default:return t}if(Number.isInteger(t)){if(Number.isInteger(this.buf1)&&isCmd(this.buf2,"R")){const e=Ref.get(t,this.buf1);this.shift();this.shift();return e}return t}return"string"==typeof t&&e?e.decryptString(t):t}findDefaultInlineStreamEnd(e){const{knownCommands:t}=this.lexer,i=e.pos;let a,s,r=0;for(;-1!==(a=e.getByte());)if(0===r)r=69===a?1:0;else if(1===r)r=73===a?2:0;else if(32===a||10===a||13===a){s=e.pos;const i=e.peekBytes(15),n=i.length;if(0===n)break;for(let e=0;e127))){r=0;break}}if(2!==r)continue;if(!t){warn("findDefaultInlineStreamEnd - `lexer.knownCommands` is undefined.");continue}const g=new Lexer(new Stream(i.slice()),t);g._hexStringWarn=()=>{};let o=0;for(;;){const e=g.getObj();if(e===Bt){r=0;break}if(e instanceof Cmd){const i=t[e.cmd];if(!i){r=0;break}if(i.variableArgs?o<=i.numArgs:o===i.numArgs)break;o=0}else o++}if(2===r)break}else r=0;if(-1===a){warn("findDefaultInlineStreamEnd: Reached the end of the stream without finding a valid EI marker");if(s){warn('... trying to recover by using the last "EI" occurrence.');e.skip(-(e.pos-s))}}let n=4;e.skip(-n);a=e.peekByte();e.skip(n);isWhiteSpace(a)||n--;return e.pos-n-i}findDCTDecodeInlineStreamEnd(e){const t=e.pos;let i,a,s=!1;for(;-1!==(i=e.getByte());)if(255===i){switch(e.getByte()){case 0:break;case 255:e.skip(-1);break;case 217:s=!0;break;case 192:case 193:case 194:case 195:case 197:case 198:case 199:case 201:case 202:case 203:case 205:case 206:case 207:case 196:case 204:case 218:case 219:case 220:case 221:case 222:case 223:case 224:case 225:case 226:case 227:case 228:case 229:case 230:case 231:case 232:case 233:case 234:case 235:case 236:case 237:case 238:case 239:case 254:a=e.getUint16();a>2?e.skip(a-2):e.skip(-2)}if(s)break}const r=e.pos-t;if(-1===i){warn("Inline DCTDecode image stream: EOI marker not found, searching for /EI/ instead.");e.skip(-r);return this.findDefaultInlineStreamEnd(e)}this.inlineStreamSkipEI(e);return r}findASCII85DecodeInlineStreamEnd(e){const t=e.pos;let i;for(;-1!==(i=e.getByte());)if(126===i){const t=e.pos;i=e.peekByte();for(;isWhiteSpace(i);){e.skip();i=e.peekByte()}if(62===i){e.skip();break}if(e.pos>t){const t=e.peekBytes(2);if(69===t[0]&&73===t[1])break}}const a=e.pos-t;if(-1===i){warn("Inline ASCII85Decode image stream: EOD marker not found, searching for /EI/ instead.");e.skip(-a);return this.findDefaultInlineStreamEnd(e)}this.inlineStreamSkipEI(e);return a}findASCIIHexDecodeInlineStreamEnd(e){const t=e.pos;let i;for(;-1!==(i=e.getByte())&&62!==i;);const a=e.pos-t;if(-1===i){warn("Inline ASCIIHexDecode image stream: EOD marker not found, searching for /EI/ instead.");e.skip(-a);return this.findDefaultInlineStreamEnd(e)}this.inlineStreamSkipEI(e);return a}inlineStreamSkipEI(e){let t,i=0;for(;-1!==(t=e.getByte());)if(0===i)i=69===t?1:0;else if(1===i)i=73===t?2:0;else if(2===i)break}makeInlineImage(e){const t=this.lexer,i=t.stream,a=Object.create(null);let s;for(;!isCmd(this.buf1,"ID")&&this.buf1!==Bt;){if(!(this.buf1 instanceof Name))throw new FormatError("Dictionary key must be a name object");const t=this.buf1.name;this.shift();if(this.buf1===Bt)break;a[t]=this.getObj(e)}-1!==t.beginInlineImagePos&&(s=i.pos-t.beginInlineImagePos);const r=this.xref.fetchIfRef(a.F||a.Filter);let n;if(r instanceof Name)n=r.name;else if(Array.isArray(r)){const e=this.xref.fetchIfRef(r[0]);e instanceof Name&&(n=e.name)}const g=i.pos;let o,c;switch(n){case"DCT":case"DCTDecode":o=this.findDCTDecodeInlineStreamEnd(i);break;case"A85":case"ASCII85Decode":o=this.findASCII85DecodeInlineStreamEnd(i);break;case"AHx":case"ASCIIHexDecode":o=this.findASCIIHexDecodeInlineStreamEnd(i);break;default:o=this.findDefaultInlineStreamEnd(i)}if(o<1e3&&s>0){const e=i.pos;i.pos=t.beginInlineImagePos;c=function getInlineImageCacheKey(e){const t=[],i=e.length;let a=0;for(;a=a){let a=!1;for(const e of s){const t=e.length;let s=0;for(;s=r){a=!0;break}if(s>=t){if(isWhiteSpace(n[o+g+s])){info(`Found "${bytesToString([...i,...e])}" when searching for endstream command.`);a=!0}break}}if(a){t.pos+=o;return t.pos-e}}o++}t.pos+=g}return-1}makeStream(e,t){const i=this.lexer;let a=i.stream;i.skipToNextLine();const s=a.pos-1;let r=e.get("Length");if(!Number.isInteger(r)){info(`Bad length "${r&&r.toString()}" in stream.`);r=0}a.pos=s+r;i.nextChar();if(this.tryShift()&&isCmd(this.buf2,"endstream"))this.shift();else{r=this.#b(s);if(r<0)throw new FormatError("Missing endstream command.");i.nextChar();this.shift();this.shift()}this.shift();a=a.makeSubStream(s,r,e);t&&(a=t.createStream(a,r));a=this.filter(a,e,r);a.dict=e;return a}filter(e,t,i){let a=t.get("F","Filter"),s=t.get("DP","DecodeParms");if(a instanceof Name){Array.isArray(s)&&warn("/DecodeParms should not be an Array, when /Filter is a Name.");return this.makeFilter(e,a.name,i,s)}let r=i;if(Array.isArray(a)){const t=a,i=s;for(let n=0,g=t.length;n=48&&e<=57?15&e:e>=65&&e<=70||e>=97&&e<=102?9+(15&e):-1}class Lexer{constructor(e,t=null){this.stream=e;this.nextChar();this.strBuf=[];this.knownCommands=t;this._hexStringNumWarn=0;this.beginInlineImagePos=-1}nextChar(){return this.currentChar=this.stream.getByte()}peekChar(){return this.stream.peekByte()}getNumber(){let e=this.currentChar,t=!1,i=0,a=1;if(45===e){a=-1;e=this.nextChar();45===e&&(e=this.nextChar())}else 43===e&&(e=this.nextChar());if(10===e||13===e)do{e=this.nextChar()}while(10===e||13===e);if(46===e){i=10;e=this.nextChar()}if(e<48||e>57){const t=`Invalid number: ${String.fromCharCode(e)} (charCode ${e})`;if(isWhiteSpace(e)||-1===e){info(`Lexer.getNumber - "${t}".`);return 0}throw new FormatError(t)}let s=e-48,r=0,n=1;for(;(e=this.nextChar())>=0;)if(e>=48&&e<=57){const a=e-48;if(t)r=10*r+a;else{0!==i&&(i*=10);s=10*s+a}}else if(46===e){if(0!==i)break;i=1}else if(45===e)warn("Badly formatted number: minus sign in the middle");else{if(69!==e&&101!==e)break;e=this.peekChar();if(43===e||45===e){n=45===e?-1:1;this.nextChar()}else if(e<48||e>57)break;t=!0}0!==i&&(s/=i);t&&(s*=10**(n*r));return a*s}getString(){let e=1,t=!1;const i=this.strBuf;i.length=0;let a=this.nextChar();for(;;){let s=!1;switch(0|a){case-1:warn("Unterminated string");t=!0;break;case 40:++e;i.push("(");break;case 41:if(0==--e){this.nextChar();t=!0}else i.push(")");break;case 92:a=this.nextChar();switch(a){case-1:warn("Unterminated string");t=!0;break;case 110:i.push("\n");break;case 114:i.push("\r");break;case 116:i.push("\t");break;case 98:i.push("\b");break;case 102:i.push("\f");break;case 92:case 40:case 41:i.push(String.fromCharCode(a));break;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:let e=15&a;a=this.nextChar();s=!0;if(a>=48&&a<=55){e=(e<<3)+(15&a);a=this.nextChar();if(a>=48&&a<=55){s=!1;e=(e<<3)+(15&a)}}i.push(String.fromCharCode(e));break;case 13:10===this.peekChar()&&this.nextChar();break;case 10:break;default:i.push(String.fromCharCode(a))}break;default:i.push(String.fromCharCode(a))}if(t)break;s||(a=this.nextChar())}return i.join("")}getName(){let e,t;const i=this.strBuf;i.length=0;for(;(e=this.nextChar())>=0&&!ai[e];)if(35===e){e=this.nextChar();if(ai[e]){warn("Lexer_getName: NUMBER SIGN (#) should be followed by a hexadecimal number.");i.push("#");break}const a=toHexDigit(e);if(-1!==a){t=e;e=this.nextChar();const s=toHexDigit(e);if(-1===s){warn(`Lexer_getName: Illegal digit (${String.fromCharCode(e)}) in hexadecimal number.`);i.push("#",String.fromCharCode(t));if(ai[e])break;i.push(String.fromCharCode(e));continue}i.push(String.fromCharCode(a<<4|s))}else i.push("#",String.fromCharCode(e))}else i.push(String.fromCharCode(e));i.length>127&&warn(`Name token is longer than allowed by the spec: ${i.length}`);return Name.get(i.join(""))}_hexStringWarn(e){5!=this._hexStringNumWarn++?this._hexStringNumWarn>5||warn(`getHexString - ignoring invalid character: ${e}`):warn("getHexString - ignoring additional invalid characters.")}getHexString(){const e=this.strBuf;e.length=0;let t=this.currentChar,i=-1,a=-1;this._hexStringNumWarn=0;for(;;){if(t<0){warn("Unterminated hex string");break}if(62===t){this.nextChar();break}if(1!==ai[t]){a=toHexDigit(t);if(-1===a)this._hexStringWarn(t);else if(-1===i)i=a;else{e.push(String.fromCharCode(i<<4|a));i=-1}t=this.nextChar()}else t=this.nextChar()}-1!==i&&e.push(String.fromCharCode(i<<4));return e.join("")}getObj(){let e=!1,t=this.currentChar;for(;;){if(t<0)return Bt;if(e)10!==t&&13!==t||(e=!1);else if(37===t)e=!0;else if(1!==ai[t])break;t=this.nextChar()}switch(0|t){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 43:case 45:case 46:return this.getNumber();case 40:return this.getString();case 47:return this.getName();case 91:this.nextChar();return Cmd.get("[");case 93:this.nextChar();return Cmd.get("]");case 60:t=this.nextChar();if(60===t){this.nextChar();return Cmd.get("<<")}return this.getHexString();case 62:t=this.nextChar();if(62===t){this.nextChar();return Cmd.get(">>")}return Cmd.get(">");case 123:this.nextChar();return Cmd.get("{");case 125:this.nextChar();return Cmd.get("}");case 41:this.nextChar();throw new FormatError(`Illegal character: ${t}`)}let i=String.fromCharCode(t);if(t<32||t>127){const e=this.peekChar();if(e>=32&&e<=127){this.nextChar();return Cmd.get(i)}}const a=this.knownCommands;let s=void 0!==a?.[i];for(;(t=this.nextChar())>=0&&!ai[t];){const e=i+String.fromCharCode(t);if(s&&void 0===a[e])break;if(128===i.length)throw new FormatError(`Command token too long: ${i.length}`);i=e;s=void 0!==a?.[i]}if("true"===i)return!0;if("false"===i)return!1;if("null"===i)return null;"BI"===i&&(this.beginInlineImagePos=this.stream.pos);return Cmd.get(i)}skipToNextLine(){let e=this.currentChar;for(;e>=0;){if(13===e){e=this.nextChar();10===e&&this.nextChar();break}if(10===e){this.nextChar();break}e=this.nextChar()}}}class Linearization{static create(e){function getInt(e,t,i=!1){const a=e.get(t);if(Number.isInteger(a)&&(i?a>=0:a>0))return a;throw new Error(`The "${t}" parameter in the linearization dictionary is invalid.`)}const t=new Parser({lexer:new Lexer(e),xref:null}),i=t.getObj(),a=t.getObj(),s=t.getObj(),r=t.getObj();let n,g;if(!(Number.isInteger(i)&&Number.isInteger(a)&&isCmd(s,"obj")&&r instanceof Dict&&"number"==typeof(n=r.get("Linearized"))&&n>0))return null;if((g=getInt(r,"L"))!==e.length)throw new Error('The "L" parameter in the linearization dictionary does not equal the stream length.');return{length:g,hints:function getHints(e){const t=e.get("H");let i;if(Array.isArray(t)&&(2===(i=t.length)||4===i)){for(let e=0;e0))throw new Error(`Hint (${e}) in the linearization dictionary is invalid.`)}return t}throw new Error("Hint array in the linearization dictionary is invalid.")}(r),objectNumberFirst:getInt(r,"O"),endFirst:getInt(r,"E"),numPages:getInt(r,"N"),mainXRefEntriesOffset:getInt(r,"T"),pageFirst:r.has("P")?getInt(r,"P",!0):0}}}const si=["Adobe-GB1-UCS2","Adobe-CNS1-UCS2","Adobe-Japan1-UCS2","Adobe-Korea1-UCS2","78-EUC-H","78-EUC-V","78-H","78-RKSJ-H","78-RKSJ-V","78-V","78ms-RKSJ-H","78ms-RKSJ-V","83pv-RKSJ-H","90ms-RKSJ-H","90ms-RKSJ-V","90msp-RKSJ-H","90msp-RKSJ-V","90pv-RKSJ-H","90pv-RKSJ-V","Add-H","Add-RKSJ-H","Add-RKSJ-V","Add-V","Adobe-CNS1-0","Adobe-CNS1-1","Adobe-CNS1-2","Adobe-CNS1-3","Adobe-CNS1-4","Adobe-CNS1-5","Adobe-CNS1-6","Adobe-GB1-0","Adobe-GB1-1","Adobe-GB1-2","Adobe-GB1-3","Adobe-GB1-4","Adobe-GB1-5","Adobe-Japan1-0","Adobe-Japan1-1","Adobe-Japan1-2","Adobe-Japan1-3","Adobe-Japan1-4","Adobe-Japan1-5","Adobe-Japan1-6","Adobe-Korea1-0","Adobe-Korea1-1","Adobe-Korea1-2","B5-H","B5-V","B5pc-H","B5pc-V","CNS-EUC-H","CNS-EUC-V","CNS1-H","CNS1-V","CNS2-H","CNS2-V","ETHK-B5-H","ETHK-B5-V","ETen-B5-H","ETen-B5-V","ETenms-B5-H","ETenms-B5-V","EUC-H","EUC-V","Ext-H","Ext-RKSJ-H","Ext-RKSJ-V","Ext-V","GB-EUC-H","GB-EUC-V","GB-H","GB-V","GBK-EUC-H","GBK-EUC-V","GBK2K-H","GBK2K-V","GBKp-EUC-H","GBKp-EUC-V","GBT-EUC-H","GBT-EUC-V","GBT-H","GBT-V","GBTpc-EUC-H","GBTpc-EUC-V","GBpc-EUC-H","GBpc-EUC-V","H","HKdla-B5-H","HKdla-B5-V","HKdlb-B5-H","HKdlb-B5-V","HKgccs-B5-H","HKgccs-B5-V","HKm314-B5-H","HKm314-B5-V","HKm471-B5-H","HKm471-B5-V","HKscs-B5-H","HKscs-B5-V","Hankaku","Hiragana","KSC-EUC-H","KSC-EUC-V","KSC-H","KSC-Johab-H","KSC-Johab-V","KSC-V","KSCms-UHC-H","KSCms-UHC-HW-H","KSCms-UHC-HW-V","KSCms-UHC-V","KSCpc-EUC-H","KSCpc-EUC-V","Katakana","NWP-H","NWP-V","RKSJ-H","RKSJ-V","Roman","UniCNS-UCS2-H","UniCNS-UCS2-V","UniCNS-UTF16-H","UniCNS-UTF16-V","UniCNS-UTF32-H","UniCNS-UTF32-V","UniCNS-UTF8-H","UniCNS-UTF8-V","UniGB-UCS2-H","UniGB-UCS2-V","UniGB-UTF16-H","UniGB-UTF16-V","UniGB-UTF32-H","UniGB-UTF32-V","UniGB-UTF8-H","UniGB-UTF8-V","UniJIS-UCS2-H","UniJIS-UCS2-HW-H","UniJIS-UCS2-HW-V","UniJIS-UCS2-V","UniJIS-UTF16-H","UniJIS-UTF16-V","UniJIS-UTF32-H","UniJIS-UTF32-V","UniJIS-UTF8-H","UniJIS-UTF8-V","UniJIS2004-UTF16-H","UniJIS2004-UTF16-V","UniJIS2004-UTF32-H","UniJIS2004-UTF32-V","UniJIS2004-UTF8-H","UniJIS2004-UTF8-V","UniJISPro-UCS2-HW-V","UniJISPro-UCS2-V","UniJISPro-UTF8-V","UniJISX0213-UTF32-H","UniJISX0213-UTF32-V","UniJISX02132004-UTF32-H","UniJISX02132004-UTF32-V","UniKS-UCS2-H","UniKS-UCS2-V","UniKS-UTF16-H","UniKS-UTF16-V","UniKS-UTF32-H","UniKS-UTF32-V","UniKS-UTF8-H","UniKS-UTF8-V","V","WP-Symbol"],ri=2**24-1;class CMap{constructor(e=!1){this.codespaceRanges=[[],[],[],[]];this.numCodespaceRanges=0;this._map=[];this.name="";this.vertical=!1;this.useCMap=null;this.builtInCMap=e}addCodespaceRange(e,t,i){this.codespaceRanges[e-1].push(t,i);this.numCodespaceRanges++}mapCidRange(e,t,i){if(t-e>ri)throw new Error("mapCidRange - ignoring data above MAX_MAP_RANGE.");for(;e<=t;)this._map[e++]=i++}mapBfRange(e,t,i){if(t-e>ri)throw new Error("mapBfRange - ignoring data above MAX_MAP_RANGE.");const a=i.length-1;for(;e<=t;){this._map[e++]=i;const t=i.charCodeAt(a)+1;t>255?i=i.substring(0,a-1)+String.fromCharCode(i.charCodeAt(a-1)+1)+"\0":i=i.substring(0,a)+String.fromCharCode(t)}}mapBfRangeToArray(e,t,i){if(t-e>ri)throw new Error("mapBfRangeToArray - ignoring data above MAX_MAP_RANGE.");const a=i.length;let s=0;for(;e<=t&&s>>0;const n=s[r];for(let e=0,t=n.length;e=t&&a<=s){i.charcode=a;i.length=r+1;return}}}i.charcode=0;i.length=1}getCharCodeLength(e){const t=this.codespaceRanges;for(let i=0,a=t.length;i=s&&e<=r)return i+1}}return 1}get length(){return this._map.length}get isIdentityCMap(){if("Identity-H"!==this.name&&"Identity-V"!==this.name)return!1;if(65536!==this._map.length)return!1;for(let e=0;e<65536;e++)if(this._map[e]!==e)return!1;return!0}}class IdentityCMap extends CMap{constructor(e,t){super();this.vertical=e;this.addCodespaceRange(t,0,65535)}mapCidRange(e,t,i){unreachable("should not call mapCidRange")}mapBfRange(e,t,i){unreachable("should not call mapBfRange")}mapBfRangeToArray(e,t,i){unreachable("should not call mapBfRangeToArray")}mapOne(e,t){unreachable("should not call mapCidOne")}lookup(e){return Number.isInteger(e)&&e<=65535?e:void 0}contains(e){return Number.isInteger(e)&&e<=65535}forEach(e){for(let t=0;t<=65535;t++)e(t,t)}charCodeOf(e){return Number.isInteger(e)&&e<=65535?e:-1}getMap(){const e=new Array(65536);for(let t=0;t<=65535;t++)e[t]=t;return e}get length(){return 65536}get isIdentityCMap(){unreachable("should not access .isIdentityCMap")}}function strToInt(e){let t=0;for(let i=0;i>>0}function expectString(e){if("string"!=typeof e)throw new FormatError("Malformed CMap: expected string.")}function expectInt(e){if(!Number.isInteger(e))throw new FormatError("Malformed CMap: expected int.")}function parseBfChar(e,t){for(;;){let i=t.getObj();if(i===Bt)break;if(isCmd(i,"endbfchar"))return;expectString(i);const a=strToInt(i);i=t.getObj();expectString(i);const s=i;e.mapOne(a,s)}}function parseBfRange(e,t){for(;;){let i=t.getObj();if(i===Bt)break;if(isCmd(i,"endbfrange"))return;expectString(i);const a=strToInt(i);i=t.getObj();expectString(i);const s=strToInt(i);i=t.getObj();if(Number.isInteger(i)||"string"==typeof i){const t=Number.isInteger(i)?String.fromCharCode(i):i;e.mapBfRange(a,s,t)}else{if(!isCmd(i,"["))break;{i=t.getObj();const r=[];for(;!isCmd(i,"]")&&i!==Bt;){r.push(i);i=t.getObj()}e.mapBfRangeToArray(a,s,r)}}}throw new FormatError("Invalid bf range.")}function parseCidChar(e,t){for(;;){let i=t.getObj();if(i===Bt)break;if(isCmd(i,"endcidchar"))return;expectString(i);const a=strToInt(i);i=t.getObj();expectInt(i);const s=i;e.mapOne(a,s)}}function parseCidRange(e,t){for(;;){let i=t.getObj();if(i===Bt)break;if(isCmd(i,"endcidrange"))return;expectString(i);const a=strToInt(i);i=t.getObj();expectString(i);const s=strToInt(i);i=t.getObj();expectInt(i);const r=i;e.mapCidRange(a,s,r)}}function parseCodespaceRange(e,t){for(;;){let i=t.getObj();if(i===Bt)break;if(isCmd(i,"endcodespacerange"))return;if("string"!=typeof i)break;const a=strToInt(i);i=t.getObj();if("string"!=typeof i)break;const s=strToInt(i);e.addCodespaceRange(i.length,a,s)}throw new FormatError("Invalid codespace range.")}function parseWMode(e,t){const i=t.getObj();Number.isInteger(i)&&(e.vertical=!!i)}function parseCMapName(e,t){const i=t.getObj();i instanceof Name&&(e.name=i.name)}async function parseCMap(e,t,i,a){let s,r;A:for(;;)try{const i=t.getObj();if(i===Bt)break;if(i instanceof Name){"WMode"===i.name?parseWMode(e,t):"CMapName"===i.name&&parseCMapName(e,t);s=i}else if(i instanceof Cmd)switch(i.cmd){case"endcmap":break A;case"usecmap":s instanceof Name&&(r=s.name);break;case"begincodespacerange":parseCodespaceRange(e,t);break;case"beginbfchar":parseBfChar(e,t);break;case"begincidchar":parseCidChar(e,t);break;case"beginbfrange":parseBfRange(e,t);break;case"begincidrange":parseCidRange(e,t)}}catch(e){if(e instanceof MissingDataException)throw e;warn("Invalid cMap data: "+e);continue}!a&&r&&(a=r);return a?extendCMap(e,i,a):e}async function extendCMap(e,t,i){e.useCMap=await createBuiltInCMap(i,t);if(0===e.numCodespaceRanges){const t=e.useCMap.codespaceRanges;for(let i=0;iextendCMap(s,t,e)));const r=new Lexer(new Stream(i));return parseCMap(s,r,t,null)}class CMapFactory{static async create({encoding:e,fetchBuiltInCMap:t,useCMap:i}){if(e instanceof Name)return createBuiltInCMap(e.name,t);if(e instanceof BaseStream){const a=await parseCMap(new CMap,new Lexer(e),t,i);return a.isIdentityCMap?createBuiltInCMap(a.name,t):a}throw new Error("Encoding required.")}}const ni=[".notdef","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","endash","dagger","daggerdbl","periodcentered","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","questiondown","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","ring","cedilla","hungarumlaut","ogonek","caron","emdash","AE","ordfeminine","Lslash","Oslash","OE","ordmasculine","ae","dotlessi","lslash","oslash","oe","germandbls","onesuperior","logicalnot","mu","trademark","Eth","onehalf","plusminus","Thorn","onequarter","divide","brokenbar","degree","thorn","threequarters","twosuperior","registered","minus","eth","multiply","threesuperior","copyright","Aacute","Acircumflex","Adieresis","Agrave","Aring","Atilde","Ccedilla","Eacute","Ecircumflex","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Ntilde","Oacute","Ocircumflex","Odieresis","Ograve","Otilde","Scaron","Uacute","Ucircumflex","Udieresis","Ugrave","Yacute","Ydieresis","Zcaron","aacute","acircumflex","adieresis","agrave","aring","atilde","ccedilla","eacute","ecircumflex","edieresis","egrave","iacute","icircumflex","idieresis","igrave","ntilde","oacute","ocircumflex","odieresis","ograve","otilde","scaron","uacute","ucircumflex","udieresis","ugrave","yacute","ydieresis","zcaron"],gi=[".notdef","space","exclamsmall","Hungarumlautsmall","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","questionsmall","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","fi","fl","ffi","ffl","parenleftinferior","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","exclamdownsmall","centoldstyle","Lslashsmall","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","Dotaccentsmall","Macronsmall","figuredash","hypheninferior","Ogoneksmall","Ringsmall","Cedillasmall","onequarter","onehalf","threequarters","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall"],oi=[".notdef","space","dollaroldstyle","dollarsuperior","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","fi","fl","ffi","ffl","parenleftinferior","parenrightinferior","hyphensuperior","colonmonetary","onefitted","rupiah","centoldstyle","figuredash","hypheninferior","onequarter","onehalf","threequarters","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior"],Ii=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclamsmall","Hungarumlautsmall","","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","questionsmall","","asuperior","bsuperior","centsuperior","dsuperior","esuperior","","","","isuperior","","","lsuperior","msuperior","nsuperior","osuperior","","","rsuperior","ssuperior","tsuperior","","ff","fi","fl","ffi","ffl","parenleftinferior","","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","exclamdownsmall","centoldstyle","Lslashsmall","","","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","","Dotaccentsmall","","","Macronsmall","","","figuredash","hypheninferior","","","Ogoneksmall","Ringsmall","Cedillasmall","","","","onequarter","onehalf","threequarters","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","","","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall"],ci=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclamsmall","Hungarumlautsmall","centoldstyle","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","","threequartersemdash","","questionsmall","","","","","Ethsmall","","","onequarter","onehalf","threequarters","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","","","","","","","ff","fi","fl","ffi","ffl","parenleftinferior","","parenrightinferior","Circumflexsmall","hypheninferior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","","","asuperior","centsuperior","","","","","Aacutesmall","Agravesmall","Acircumflexsmall","Adieresissmall","Atildesmall","Aringsmall","Ccedillasmall","Eacutesmall","Egravesmall","Ecircumflexsmall","Edieresissmall","Iacutesmall","Igravesmall","Icircumflexsmall","Idieresissmall","Ntildesmall","Oacutesmall","Ogravesmall","Ocircumflexsmall","Odieresissmall","Otildesmall","Uacutesmall","Ugravesmall","Ucircumflexsmall","Udieresissmall","","eightsuperior","fourinferior","threeinferior","sixinferior","eightinferior","seveninferior","Scaronsmall","","centinferior","twoinferior","","Dieresissmall","","Caronsmall","osuperior","fiveinferior","","commainferior","periodinferior","Yacutesmall","","dollarinferior","","","Thornsmall","","nineinferior","zeroinferior","Zcaronsmall","AEsmall","Oslashsmall","questiondownsmall","oneinferior","Lslashsmall","","","","","","","Cedillasmall","","","","","","OEsmall","figuredash","hyphensuperior","","","","","exclamdownsmall","","Ydieresissmall","","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","ninesuperior","zerosuperior","","esuperior","rsuperior","tsuperior","","","isuperior","ssuperior","dsuperior","","","","","","lsuperior","Ogoneksmall","Brevesmall","Macronsmall","bsuperior","nsuperior","msuperior","commasuperior","periodsuperior","Dotaccentsmall","Ringsmall","","","",""],Ci=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","","Adieresis","Aring","Ccedilla","Eacute","Ntilde","Odieresis","Udieresis","aacute","agrave","acircumflex","adieresis","atilde","aring","ccedilla","eacute","egrave","ecircumflex","edieresis","iacute","igrave","icircumflex","idieresis","ntilde","oacute","ograve","ocircumflex","odieresis","otilde","uacute","ugrave","ucircumflex","udieresis","dagger","degree","cent","sterling","section","bullet","paragraph","germandbls","registered","copyright","trademark","acute","dieresis","notequal","AE","Oslash","infinity","plusminus","lessequal","greaterequal","yen","mu","partialdiff","summation","product","pi","integral","ordfeminine","ordmasculine","Omega","ae","oslash","questiondown","exclamdown","logicalnot","radical","florin","approxequal","Delta","guillemotleft","guillemotright","ellipsis","space","Agrave","Atilde","Otilde","OE","oe","endash","emdash","quotedblleft","quotedblright","quoteleft","quoteright","divide","lozenge","ydieresis","Ydieresis","fraction","currency","guilsinglleft","guilsinglright","fi","fl","daggerdbl","periodcentered","quotesinglbase","quotedblbase","perthousand","Acircumflex","Ecircumflex","Aacute","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Oacute","Ocircumflex","apple","Ograve","Uacute","Ucircumflex","Ugrave","dotlessi","circumflex","tilde","macron","breve","dotaccent","ring","cedilla","hungarumlaut","ogonek","caron"],hi=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","","endash","dagger","daggerdbl","periodcentered","","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","","questiondown","","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","","ring","cedilla","","hungarumlaut","ogonek","caron","emdash","","","","","","","","","","","","","","","","","AE","","ordfeminine","","","","","Lslash","Oslash","OE","ordmasculine","","","","","","ae","","","","dotlessi","","","lslash","oslash","oe","germandbls","","","",""],li=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","bullet","Euro","bullet","quotesinglbase","florin","quotedblbase","ellipsis","dagger","daggerdbl","circumflex","perthousand","Scaron","guilsinglleft","OE","bullet","Zcaron","bullet","bullet","quoteleft","quoteright","quotedblleft","quotedblright","bullet","endash","emdash","tilde","trademark","scaron","guilsinglright","oe","bullet","zcaron","Ydieresis","space","exclamdown","cent","sterling","currency","yen","brokenbar","section","dieresis","copyright","ordfeminine","guillemotleft","logicalnot","hyphen","registered","macron","degree","plusminus","twosuperior","threesuperior","acute","mu","paragraph","periodcentered","cedilla","onesuperior","ordmasculine","guillemotright","onequarter","onehalf","threequarters","questiondown","Agrave","Aacute","Acircumflex","Atilde","Adieresis","Aring","AE","Ccedilla","Egrave","Eacute","Ecircumflex","Edieresis","Igrave","Iacute","Icircumflex","Idieresis","Eth","Ntilde","Ograve","Oacute","Ocircumflex","Otilde","Odieresis","multiply","Oslash","Ugrave","Uacute","Ucircumflex","Udieresis","Yacute","Thorn","germandbls","agrave","aacute","acircumflex","atilde","adieresis","aring","ae","ccedilla","egrave","eacute","ecircumflex","edieresis","igrave","iacute","icircumflex","idieresis","eth","ntilde","ograve","oacute","ocircumflex","otilde","odieresis","divide","oslash","ugrave","uacute","ucircumflex","udieresis","yacute","thorn","ydieresis"],Bi=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","universal","numbersign","existential","percent","ampersand","suchthat","parenleft","parenright","asteriskmath","plus","comma","minus","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","congruent","Alpha","Beta","Chi","Delta","Epsilon","Phi","Gamma","Eta","Iota","theta1","Kappa","Lambda","Mu","Nu","Omicron","Pi","Theta","Rho","Sigma","Tau","Upsilon","sigma1","Omega","Xi","Psi","Zeta","bracketleft","therefore","bracketright","perpendicular","underscore","radicalex","alpha","beta","chi","delta","epsilon","phi","gamma","eta","iota","phi1","kappa","lambda","mu","nu","omicron","pi","theta","rho","sigma","tau","upsilon","omega1","omega","xi","psi","zeta","braceleft","bar","braceright","similar","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","Euro","Upsilon1","minute","lessequal","fraction","infinity","florin","club","diamond","heart","spade","arrowboth","arrowleft","arrowup","arrowright","arrowdown","degree","plusminus","second","greaterequal","multiply","proportional","partialdiff","bullet","divide","notequal","equivalence","approxequal","ellipsis","arrowvertex","arrowhorizex","carriagereturn","aleph","Ifraktur","Rfraktur","weierstrass","circlemultiply","circleplus","emptyset","intersection","union","propersuperset","reflexsuperset","notsubset","propersubset","reflexsubset","element","notelement","angle","gradient","registerserif","copyrightserif","trademarkserif","product","radical","dotmath","logicalnot","logicaland","logicalor","arrowdblboth","arrowdblleft","arrowdblup","arrowdblright","arrowdbldown","lozenge","angleleft","registersans","copyrightsans","trademarksans","summation","parenlefttp","parenleftex","parenleftbt","bracketlefttp","bracketleftex","bracketleftbt","bracelefttp","braceleftmid","braceleftbt","braceex","","angleright","integral","integraltp","integralex","integralbt","parenrighttp","parenrightex","parenrightbt","bracketrighttp","bracketrightex","bracketrightbt","bracerighttp","bracerightmid","bracerightbt",""],Qi=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","a1","a2","a202","a3","a4","a5","a119","a118","a117","a11","a12","a13","a14","a15","a16","a105","a17","a18","a19","a20","a21","a22","a23","a24","a25","a26","a27","a28","a6","a7","a8","a9","a10","a29","a30","a31","a32","a33","a34","a35","a36","a37","a38","a39","a40","a41","a42","a43","a44","a45","a46","a47","a48","a49","a50","a51","a52","a53","a54","a55","a56","a57","a58","a59","a60","a61","a62","a63","a64","a65","a66","a67","a68","a69","a70","a71","a72","a73","a74","a203","a75","a204","a76","a77","a78","a79","a81","a82","a83","a84","a97","a98","a99","a100","","a89","a90","a93","a94","a91","a92","a205","a85","a206","a86","a87","a88","a95","a96","","","","","","","","","","","","","","","","","","","","a101","a102","a103","a104","a106","a107","a108","a112","a111","a110","a109","a120","a121","a122","a123","a124","a125","a126","a127","a128","a129","a130","a131","a132","a133","a134","a135","a136","a137","a138","a139","a140","a141","a142","a143","a144","a145","a146","a147","a148","a149","a150","a151","a152","a153","a154","a155","a156","a157","a158","a159","a160","a161","a163","a164","a196","a165","a192","a166","a167","a168","a169","a170","a171","a172","a173","a162","a174","a175","a176","a177","a178","a179","a193","a180","a199","a181","a200","a182","","a201","a183","a184","a197","a185","a194","a198","a186","a195","a187","a188","a189","a190","a191",""];function getEncoding(e){switch(e){case"WinAnsiEncoding":return li;case"StandardEncoding":return hi;case"MacRomanEncoding":return Ci;case"SymbolSetEncoding":return Bi;case"ZapfDingbatsEncoding":return Qi;case"ExpertEncoding":return Ii;case"MacExpertEncoding":return ci;default:return null}}const Ei=[".notdef","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","endash","dagger","daggerdbl","periodcentered","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","questiondown","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","ring","cedilla","hungarumlaut","ogonek","caron","emdash","AE","ordfeminine","Lslash","Oslash","OE","ordmasculine","ae","dotlessi","lslash","oslash","oe","germandbls","onesuperior","logicalnot","mu","trademark","Eth","onehalf","plusminus","Thorn","onequarter","divide","brokenbar","degree","thorn","threequarters","twosuperior","registered","minus","eth","multiply","threesuperior","copyright","Aacute","Acircumflex","Adieresis","Agrave","Aring","Atilde","Ccedilla","Eacute","Ecircumflex","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Ntilde","Oacute","Ocircumflex","Odieresis","Ograve","Otilde","Scaron","Uacute","Ucircumflex","Udieresis","Ugrave","Yacute","Ydieresis","Zcaron","aacute","acircumflex","adieresis","agrave","aring","atilde","ccedilla","eacute","ecircumflex","edieresis","egrave","iacute","icircumflex","idieresis","igrave","ntilde","oacute","ocircumflex","odieresis","ograve","otilde","scaron","uacute","ucircumflex","udieresis","ugrave","yacute","ydieresis","zcaron","exclamsmall","Hungarumlautsmall","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","commasuperior","threequartersemdash","periodsuperior","questionsmall","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","ffi","ffl","parenleftinferior","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","exclamdownsmall","centoldstyle","Lslashsmall","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","Dotaccentsmall","Macronsmall","figuredash","hypheninferior","Ogoneksmall","Ringsmall","Cedillasmall","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall","001.000","001.001","001.002","001.003","Black","Bold","Book","Light","Medium","Regular","Roman","Semibold"],ui=391,di=[null,{id:"hstem",min:2,stackClearing:!0,stem:!0},null,{id:"vstem",min:2,stackClearing:!0,stem:!0},{id:"vmoveto",min:1,stackClearing:!0},{id:"rlineto",min:2,resetStack:!0},{id:"hlineto",min:1,resetStack:!0},{id:"vlineto",min:1,resetStack:!0},{id:"rrcurveto",min:6,resetStack:!0},null,{id:"callsubr",min:1,undefStack:!0},{id:"return",min:0,undefStack:!0},null,null,{id:"endchar",min:0,stackClearing:!0},null,null,null,{id:"hstemhm",min:2,stackClearing:!0,stem:!0},{id:"hintmask",min:0,stackClearing:!0},{id:"cntrmask",min:0,stackClearing:!0},{id:"rmoveto",min:2,stackClearing:!0},{id:"hmoveto",min:1,stackClearing:!0},{id:"vstemhm",min:2,stackClearing:!0,stem:!0},{id:"rcurveline",min:8,resetStack:!0},{id:"rlinecurve",min:8,resetStack:!0},{id:"vvcurveto",min:4,resetStack:!0},{id:"hhcurveto",min:4,resetStack:!0},null,{id:"callgsubr",min:1,undefStack:!0},{id:"vhcurveto",min:4,resetStack:!0},{id:"hvcurveto",min:4,resetStack:!0}],fi=[null,null,null,{id:"and",min:2,stackDelta:-1},{id:"or",min:2,stackDelta:-1},{id:"not",min:1,stackDelta:0},null,null,null,{id:"abs",min:1,stackDelta:0},{id:"add",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]+e[t-1]}},{id:"sub",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]-e[t-1]}},{id:"div",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]/e[t-1]}},null,{id:"neg",min:1,stackDelta:0,stackFn(e,t){e[t-1]=-e[t-1]}},{id:"eq",min:2,stackDelta:-1},null,null,{id:"drop",min:1,stackDelta:-1},null,{id:"put",min:2,stackDelta:-2},{id:"get",min:1,stackDelta:0},{id:"ifelse",min:4,stackDelta:-3},{id:"random",min:0,stackDelta:1},{id:"mul",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]*e[t-1]}},null,{id:"sqrt",min:1,stackDelta:0},{id:"dup",min:1,stackDelta:1},{id:"exch",min:2,stackDelta:0},{id:"index",min:2,stackDelta:0},{id:"roll",min:3,stackDelta:-2},null,null,null,{id:"hflex",min:7,resetStack:!0},{id:"flex",min:13,resetStack:!0},{id:"hflex1",min:9,resetStack:!0},{id:"flex1",min:11,resetStack:!0}];class CFFParser{constructor(e,t,i){this.bytes=e.getBytes();this.properties=t;this.seacAnalysisEnabled=!!i}parse(){const e=this.properties,t=new CFF;this.cff=t;const i=this.parseHeader(),a=this.parseIndex(i.endPos),s=this.parseIndex(a.endPos),r=this.parseIndex(s.endPos),n=this.parseIndex(r.endPos),g=this.parseDict(s.obj.get(0)),o=this.createDict(CFFTopDict,g,t.strings);t.header=i.obj;t.names=this.parseNameIndex(a.obj);t.strings=this.parseStringIndex(r.obj);t.topDict=o;t.globalSubrIndex=n.obj;this.parsePrivateDict(t.topDict);t.isCIDFont=o.hasName("ROS");const c=o.getByName("CharStrings"),C=this.parseIndex(c).obj,h=o.getByName("FontMatrix");h&&(e.fontMatrix=h);const l=o.getByName("FontBBox");if(l){e.ascent=Math.max(l[3],l[1]);e.descent=Math.min(l[1],l[3]);e.ascentScaled=!0}let Q,E;if(t.isCIDFont){const e=this.parseIndex(o.getByName("FDArray")).obj;for(let i=0,a=e.count;i=t)throw new FormatError("Invalid CFF header");if(0!==i){info("cff data is shifted");e=e.subarray(i);this.bytes=e}const a=e[0],s=e[1],r=e[2],n=e[3];return{obj:new CFFHeader(a,s,r,n),endPos:r}}parseDict(e){let t=0;function parseOperand(){let i=e[t++];if(30===i)return function parseFloatOperand(){let i="";const a=15,s=["0","1","2","3","4","5","6","7","8","9",".","E","E-",null,"-"],r=e.length;for(;t>4,g=15&r;if(n===a)break;i+=s[n];if(g===a)break;i+=s[g]}return parseFloat(i)}();if(28===i){i=e[t++];i=(i<<24|e[t++]<<16)>>16;return i}if(29===i){i=e[t++];i=i<<8|e[t++];i=i<<8|e[t++];i=i<<8|e[t++];return i}if(i>=32&&i<=246)return i-139;if(i>=247&&i<=250)return 256*(i-247)+e[t++]+108;if(i>=251&&i<=254)return-256*(i-251)-e[t++]-108;warn('CFFParser_parseDict: "'+i+'" is a reserved command.');return NaN}let i=[];const a=[];t=0;const s=e.length;for(;t10)return!1;let s=e.stackSize;const r=e.stack;let n=t.length;for(let g=0;g>16;g+=2;s++}else if(14===o){if(s>=4){s-=4;if(this.seacAnalysisEnabled){e.seac=r.slice(s,s+4);return!1}}c=di[o]}else if(o>=32&&o<=246){r[s]=o-139;s++}else if(o>=247&&o<=254){r[s]=o<251?(o-247<<8)+t[g]+108:-(o-251<<8)-t[g]-108;g++;s++}else if(255===o){r[s]=(t[g]<<24|t[g+1]<<16|t[g+2]<<8|t[g+3])/65536;g+=4;s++}else if(19===o||20===o){e.hints+=s>>1;if(0===e.hints){t.copyWithin(g-1,g,-1);g-=1;n-=1;continue}g+=e.hints+7>>3;s%=2;c=di[o]}else{if(10===o||29===o){const t=10===o?i:a;if(!t){c=di[o];warn("Missing subrsIndex for "+c.id);return!1}let n=32768;t.count<1240?n=107:t.count<33900&&(n=1131);const g=r[--s]+n;if(g<0||g>=t.count||isNaN(g)){c=di[o];warn("Out of bounds subrIndex for "+c.id);return!1}e.stackSize=s;e.callDepth++;if(!this.parseCharString(e,t.get(g),i,a))return!1;e.callDepth--;s=e.stackSize;continue}if(11===o){e.stackSize=s;return!0}if(0===o&&g===t.length){t[g-1]=14;c=di[14]}else{if(9===o){t.copyWithin(g-1,g,-1);g-=1;n-=1;continue}c=di[o]}}if(c){if(c.stem){e.hints+=s>>1;if(3===o||23===o)e.hasVStems=!0;else if(e.hasVStems&&(1===o||18===o)){warn("CFF stem hints are in wrong order");t[g-1]=1===o?3:23}}if("min"in c&&!e.undefStack&&s=2&&c.stem?s%=2:s>1&&warn("Found too many parameters for stack-clearing command");s>0&&(e.width=r[s-1])}if("stackDelta"in c){"stackFn"in c&&c.stackFn(r,s);s+=c.stackDelta}else if(c.stackClearing)s=0;else if(c.resetStack){s=0;e.undefStack=!1}else if(c.undefStack){s=0;e.undefStack=!0;e.firstStackClearing=!1}}}n=s.length){warn("Invalid fd index for glyph index.");h=!1}if(h){Q=s[e].privateDict;l=Q.subrsIndex}}else t&&(l=t);h&&(h=this.parseCharString(C,o,l,i));if(null!==C.width){const e=Q.getByName("nominalWidthX");g[c]=e+C.width}else{const e=Q.getByName("defaultWidthX");g[c]=e}null!==C.seac&&(n[c]=C.seac);h||e.set(c,new Uint8Array([14]))}return{charStrings:e,seacs:n,widths:g}}emptyPrivateDictionary(e){const t=this.createDict(CFFPrivateDict,[],e.strings);e.setByKey(18,[0,0]);e.privateDict=t}parsePrivateDict(e){if(!e.hasName("Private")){this.emptyPrivateDictionary(e);return}const t=e.getByName("Private");if(!Array.isArray(t)||2!==t.length){e.removeByName("Private");return}const i=t[0],a=t[1];if(0===i||a>=this.bytes.length){this.emptyPrivateDictionary(e);return}const s=a+i,r=this.bytes.subarray(a,s),n=this.parseDict(r),g=this.createDict(CFFPrivateDict,n,e.strings);e.privateDict=g;0===g.getByName("ExpansionFactor")&&g.setByName("ExpansionFactor",.06);if(!g.getByName("Subrs"))return;const o=g.getByName("Subrs"),c=a+o;if(0===o||c>=this.bytes.length){this.emptyPrivateDictionary(e);return}const C=this.parseIndex(c);g.subrsIndex=C.obj}parseCharsets(e,t,i,a){if(0===e)return new CFFCharset(!0,yi.ISO_ADOBE,ni);if(1===e)return new CFFCharset(!0,yi.EXPERT,gi);if(2===e)return new CFFCharset(!0,yi.EXPERT_SUBSET,oi);const s=this.bytes,r=e,n=s[e++],g=[a?0:".notdef"];let o,c,C;t-=1;switch(n){case 0:for(C=0;C=65535){warn("Not enough space in charstrings to duplicate first glyph.");return}const e=this.charStrings.get(0);this.charStrings.add(e);this.isCIDFont&&this.fdSelect.fdSelect.push(this.fdSelect.fdSelect[0])}hasGlyphId(e){if(e<0||e>=this.charStrings.count)return!1;return this.charStrings.get(e).length>0}}class CFFHeader{constructor(e,t,i,a){this.major=e;this.minor=t;this.hdrSize=i;this.offSize=a}}class CFFStrings{constructor(){this.strings=[]}get(e){return e>=0&&e<=390?Ei[e]:e-ui<=this.strings.length?this.strings[e-ui]:Ei[0]}getSID(e){let t=Ei.indexOf(e);if(-1!==t)return t;t=this.strings.indexOf(e);return-1!==t?t+ui:-1}add(e){this.strings.push(e)}get count(){return this.strings.length}}class CFFIndex{constructor(){this.objects=[];this.length=0}add(e){this.length+=e.length;this.objects.push(e)}set(e,t){this.length+=t.length-this.objects[e].length;this.objects[e]=t}get(e){return this.objects[e]}get count(){return this.objects.length}}class CFFDict{constructor(e,t){this.keyToNameMap=e.keyToNameMap;this.nameToKeyMap=e.nameToKeyMap;this.defaults=e.defaults;this.types=e.types;this.opcodes=e.opcodes;this.order=e.order;this.strings=t;this.values=Object.create(null)}setByKey(e,t){if(!(e in this.keyToNameMap))return!1;if(0===t.length)return!0;for(const i of t)if(isNaN(i)){warn(`Invalid CFFDict value: "${t}" for key "${e}".`);return!0}const i=this.types[e];"num"!==i&&"sid"!==i&&"offset"!==i||(t=t[0]);this.values[e]=t;return!0}setByName(e,t){if(!(e in this.nameToKeyMap))throw new FormatError(`Invalid dictionary name "${e}"`);this.values[this.nameToKeyMap[e]]=t}hasName(e){return this.nameToKeyMap[e]in this.values}getByName(e){if(!(e in this.nameToKeyMap))throw new FormatError(`Invalid dictionary name ${e}"`);const t=this.nameToKeyMap[e];return t in this.values?this.values[t]:this.defaults[t]}removeByName(e){delete this.values[this.nameToKeyMap[e]]}static createTables(e){const t={keyToNameMap:{},nameToKeyMap:{},defaults:{},types:{},opcodes:{},order:[]};for(const i of e){const e=Array.isArray(i[0])?(i[0][0]<<8)+i[0][1]:i[0];t.keyToNameMap[e]=i[1];t.nameToKeyMap[i[1]]=e;t.types[e]=i[2];t.defaults[e]=i[3];t.opcodes[e]=Array.isArray(i[0])?i[0]:[i[0]];t.order.push(e)}return t}}const pi=[[[12,30],"ROS",["sid","sid","num"],null],[[12,20],"SyntheticBase","num",null],[0,"version","sid",null],[1,"Notice","sid",null],[[12,0],"Copyright","sid",null],[2,"FullName","sid",null],[3,"FamilyName","sid",null],[4,"Weight","sid",null],[[12,1],"isFixedPitch","num",0],[[12,2],"ItalicAngle","num",0],[[12,3],"UnderlinePosition","num",-100],[[12,4],"UnderlineThickness","num",50],[[12,5],"PaintType","num",0],[[12,6],"CharstringType","num",2],[[12,7],"FontMatrix",["num","num","num","num","num","num"],[.001,0,0,.001,0,0]],[13,"UniqueID","num",null],[5,"FontBBox",["num","num","num","num"],[0,0,0,0]],[[12,8],"StrokeWidth","num",0],[14,"XUID","array",null],[15,"charset","offset",0],[16,"Encoding","offset",0],[17,"CharStrings","offset",0],[18,"Private",["offset","offset"],null],[[12,21],"PostScript","sid",null],[[12,22],"BaseFontName","sid",null],[[12,23],"BaseFontBlend","delta",null],[[12,31],"CIDFontVersion","num",0],[[12,32],"CIDFontRevision","num",0],[[12,33],"CIDFontType","num",0],[[12,34],"CIDCount","num",8720],[[12,35],"UIDBase","num",null],[[12,37],"FDSelect","offset",null],[[12,36],"FDArray","offset",null],[[12,38],"FontName","sid",null]];class CFFTopDict extends CFFDict{static get tables(){return shadow(this,"tables",this.createTables(pi))}constructor(e){super(CFFTopDict.tables,e);this.privateDict=null}}const mi=[[6,"BlueValues","delta",null],[7,"OtherBlues","delta",null],[8,"FamilyBlues","delta",null],[9,"FamilyOtherBlues","delta",null],[[12,9],"BlueScale","num",.039625],[[12,10],"BlueShift","num",7],[[12,11],"BlueFuzz","num",1],[10,"StdHW","num",null],[11,"StdVW","num",null],[[12,12],"StemSnapH","delta",null],[[12,13],"StemSnapV","delta",null],[[12,14],"ForceBold","num",0],[[12,17],"LanguageGroup","num",0],[[12,18],"ExpansionFactor","num",.06],[[12,19],"initialRandomSeed","num",0],[20,"defaultWidthX","num",0],[21,"nominalWidthX","num",0],[19,"Subrs","offset",null]];class CFFPrivateDict extends CFFDict{static get tables(){return shadow(this,"tables",this.createTables(mi))}constructor(e){super(CFFPrivateDict.tables,e);this.subrsIndex=null}}const yi={ISO_ADOBE:0,EXPERT:1,EXPERT_SUBSET:2};class CFFCharset{constructor(e,t,i,a){this.predefined=e;this.format=t;this.charset=i;this.raw=a}}class CFFEncoding{constructor(e,t,i,a){this.predefined=e;this.format=t;this.encoding=i;this.raw=a}}class CFFFDSelect{constructor(e,t){this.format=e;this.fdSelect=t}getFDIndex(e){return e<0||e>=this.fdSelect.length?-1:this.fdSelect[e]}}class CFFOffsetTracker{constructor(){this.offsets=Object.create(null)}isTracking(e){return e in this.offsets}track(e,t){if(e in this.offsets)throw new FormatError(`Already tracking location of ${e}`);this.offsets[e]=t}offset(e){for(const t in this.offsets)this.offsets[t]+=e}setEntryLocation(e,t,i){if(!(e in this.offsets))throw new FormatError(`Not tracking location of ${e}`);const a=i.data,s=this.offsets[e];for(let e=0,i=t.length;e>24&255;a[n]=c>>16&255;a[g]=c>>8&255;a[o]=255&c}}}class CFFCompiler{constructor(e){this.cff=e}compile(){const e=this.cff,t={data:[],length:0,add(e){try{this.data.push(...e)}catch{this.data=this.data.concat(e)}this.length=this.data.length}},i=this.compileHeader(e.header);t.add(i);const a=this.compileNameIndex(e.names);t.add(a);if(e.isCIDFont&&e.topDict.hasName("FontMatrix")){const t=e.topDict.getByName("FontMatrix");e.topDict.removeByName("FontMatrix");for(const i of e.fdArray){let e=t.slice(0);i.hasName("FontMatrix")&&(e=Util.transform(e,i.getByName("FontMatrix")));i.setByName("FontMatrix",e)}}const s=e.topDict.getByName("XUID");s?.length>16&&e.topDict.removeByName("XUID");e.topDict.setByName("charset",0);let r=this.compileTopDicts([e.topDict],t.length,e.isCIDFont);t.add(r.output);const n=r.trackers[0],g=this.compileStringIndex(e.strings.strings);t.add(g);const o=this.compileIndex(e.globalSubrIndex);t.add(o);if(e.encoding&&e.topDict.hasName("Encoding"))if(e.encoding.predefined)n.setEntryLocation("Encoding",[e.encoding.format],t);else{const i=this.compileEncoding(e.encoding);n.setEntryLocation("Encoding",[t.length],t);t.add(i)}const c=this.compileCharset(e.charset,e.charStrings.count,e.strings,e.isCIDFont);n.setEntryLocation("charset",[t.length],t);t.add(c);const C=this.compileCharStrings(e.charStrings);n.setEntryLocation("CharStrings",[t.length],t);t.add(C);if(e.isCIDFont){n.setEntryLocation("FDSelect",[t.length],t);const i=this.compileFDSelect(e.fdSelect);t.add(i);r=this.compileTopDicts(e.fdArray,t.length,!0);n.setEntryLocation("FDArray",[t.length],t);t.add(r.output);const a=r.trackers;this.compilePrivateDicts(e.fdArray,a,t)}this.compilePrivateDicts([e.topDict],[n],t);t.add([0]);return t.data}encodeNumber(e){return Number.isInteger(e)?this.encodeInteger(e):this.encodeFloat(e)}static get EncodeFloatRegExp(){return shadow(this,"EncodeFloatRegExp",/\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/)}encodeFloat(e){let t=e.toString();const i=CFFCompiler.EncodeFloatRegExp.exec(t);if(i){const a=parseFloat("1e"+((i[2]?+i[2]:0)+i[1].length));t=(Math.round(e*a)/a).toString()}let a,s,r="";for(a=0,s=t.length;a=-107&&e<=107?[e+139]:e>=108&&e<=1131?[247+((e-=108)>>8),255&e]:e>=-1131&&e<=-108?[251+((e=-e-108)>>8),255&e]:e>=-32768&&e<=32767?[28,e>>8&255,255&e]:[29,e>>24&255,e>>16&255,e>>8&255,255&e];return t}compileHeader(e){return[e.major,e.minor,4,e.offSize]}compileNameIndex(e){const t=new CFFIndex;for(const i of e){const e=Math.min(i.length,127);let a=new Array(e);for(let t=0;t"~"||"["===e||"]"===e||"("===e||")"===e||"{"===e||"}"===e||"<"===e||">"===e||"/"===e||"%"===e)&&(e="_");a[t]=e}a=a.join("");""===a&&(a="Bad_Font_Name");t.add(stringToBytes(a))}return this.compileIndex(t)}compileTopDicts(e,t,i){const a=[];let s=new CFFIndex;for(const r of e){if(i){r.removeByName("CIDFontVersion");r.removeByName("CIDFontRevision");r.removeByName("CIDFontType");r.removeByName("CIDCount");r.removeByName("UIDBase")}const e=new CFFOffsetTracker,n=this.compileDict(r,e);a.push(e);s.add(n);e.offset(t)}s=this.compileIndex(s,a);return{trackers:a,output:s}}compilePrivateDicts(e,t,i){for(let a=0,s=e.length;a>8&255,255&r]);else{s=new Uint8Array(1+2*r);s[0]=0;let t=0;const a=e.charset.length;let n=!1;for(let r=1;r>8&255;s[r+1]=255&g}}return this.compileTypedArray(s)}compileEncoding(e){return this.compileTypedArray(e.raw)}compileFDSelect(e){const t=e.format;let i,a;switch(t){case 0:i=new Uint8Array(1+e.fdSelect.length);i[0]=t;for(a=0;a>8&255,255&s,r];for(a=1;a>8&255,255&a,t);r=t}}const g=(n.length-3)/3;n[1]=g>>8&255;n[2]=255&g;n.push(a>>8&255,255&a);i=new Uint8Array(n)}return this.compileTypedArray(i)}compileTypedArray(e){return Array.from(e)}compileIndex(e,t=[]){const i=e.objects,a=i.length;if(0===a)return[0,0];const s=[a>>8&255,255&a];let r,n,g=1;for(r=0;r>8&255,255&o):3===n?s.push(o>>16&255,o>>8&255,255&o):s.push(o>>>24&255,o>>16&255,o>>8&255,255&o);i[r]&&(o+=i[r].length)}for(r=0;r=5&&t<=7))return-1;a=e.substring(1)}if(a===a.toUpperCase()){i=parseInt(a,16);if(i>=0)return i}}return-1}const Fi=[[0,127],[128,255],[256,383],[384,591],[592,687,7424,7551,7552,7615],[688,767,42752,42783],[768,879,7616,7679],[880,1023],[11392,11519],[1024,1279,1280,1327,11744,11775,42560,42655],[1328,1423],[1424,1535],[42240,42559],[1536,1791,1872,1919],[1984,2047],[2304,2431],[2432,2559],[2560,2687],[2688,2815],[2816,2943],[2944,3071],[3072,3199],[3200,3327],[3328,3455],[3584,3711],[3712,3839],[4256,4351,11520,11567],[6912,7039],[4352,4607],[7680,7935,11360,11391,42784,43007],[7936,8191],[8192,8303,11776,11903],[8304,8351],[8352,8399],[8400,8447],[8448,8527],[8528,8591],[8592,8703,10224,10239,10496,10623,11008,11263],[8704,8959,10752,11007,10176,10223,10624,10751],[8960,9215],[9216,9279],[9280,9311],[9312,9471],[9472,9599],[9600,9631],[9632,9727],[9728,9983],[9984,10175],[12288,12351],[12352,12447],[12448,12543,12784,12799],[12544,12591,12704,12735],[12592,12687],[43072,43135],[12800,13055],[13056,13311],[44032,55215],[55296,57343],[67840,67871],[19968,40959,11904,12031,12032,12255,12272,12287,13312,19903,131072,173791,12688,12703],[57344,63743],[12736,12783,63744,64255,194560,195103],[64256,64335],[64336,65023],[65056,65071],[65040,65055],[65104,65135],[65136,65279],[65280,65519],[65520,65535],[3840,4095],[1792,1871],[1920,1983],[3456,3583],[4096,4255],[4608,4991,4992,5023,11648,11743],[5024,5119],[5120,5759],[5760,5791],[5792,5887],[6016,6143],[6144,6319],[10240,10495],[40960,42127],[5888,5919,5920,5951,5952,5983,5984,6015],[66304,66351],[66352,66383],[66560,66639],[118784,119039,119040,119295,119296,119375],[119808,120831],[1044480,1048573],[65024,65039,917760,917999],[917504,917631],[6400,6479],[6480,6527],[6528,6623],[6656,6687],[11264,11359],[11568,11647],[19904,19967],[43008,43055],[65536,65663,65664,65791,65792,65855],[65856,65935],[66432,66463],[66464,66527],[66640,66687],[66688,66735],[67584,67647],[68096,68191],[119552,119647],[73728,74751,74752,74879],[119648,119679],[7040,7103],[7168,7247],[7248,7295],[43136,43231],[43264,43311],[43312,43359],[43520,43615],[65936,65999],[66e3,66047],[66208,66271,66176,66207,67872,67903],[127024,127135,126976,127023]];function getUnicodeRangeFor(e,t=-1){if(-1!==t){const i=Fi[t];for(let a=0,s=i.length;a=i[a]&&e<=i[a+1])return t}for(let t=0,i=Fi.length;t=i[a]&&e<=i[a+1])return t}return-1}const Si=new RegExp("^(\\s)|(\\p{Mn})|(\\p{Cf})$","u"),ki=new Map;const Ri=!0,Ni=1,Gi=2,Mi=4,xi=32,Hi=[".notdef",".null","nonmarkingreturn","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","Adieresis","Aring","Ccedilla","Eacute","Ntilde","Odieresis","Udieresis","aacute","agrave","acircumflex","adieresis","atilde","aring","ccedilla","eacute","egrave","ecircumflex","edieresis","iacute","igrave","icircumflex","idieresis","ntilde","oacute","ograve","ocircumflex","odieresis","otilde","uacute","ugrave","ucircumflex","udieresis","dagger","degree","cent","sterling","section","bullet","paragraph","germandbls","registered","copyright","trademark","acute","dieresis","notequal","AE","Oslash","infinity","plusminus","lessequal","greaterequal","yen","mu","partialdiff","summation","product","pi","integral","ordfeminine","ordmasculine","Omega","ae","oslash","questiondown","exclamdown","logicalnot","radical","florin","approxequal","Delta","guillemotleft","guillemotright","ellipsis","nonbreakingspace","Agrave","Atilde","Otilde","OE","oe","endash","emdash","quotedblleft","quotedblright","quoteleft","quoteright","divide","lozenge","ydieresis","Ydieresis","fraction","currency","guilsinglleft","guilsinglright","fi","fl","daggerdbl","periodcentered","quotesinglbase","quotedblbase","perthousand","Acircumflex","Ecircumflex","Aacute","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Oacute","Ocircumflex","apple","Ograve","Uacute","Ucircumflex","Ugrave","dotlessi","circumflex","tilde","macron","breve","dotaccent","ring","cedilla","hungarumlaut","ogonek","caron","Lslash","lslash","Scaron","scaron","Zcaron","zcaron","brokenbar","Eth","eth","Yacute","yacute","Thorn","thorn","minus","multiply","onesuperior","twosuperior","threesuperior","onehalf","onequarter","threequarters","franc","Gbreve","gbreve","Idotaccent","Scedilla","scedilla","Cacute","cacute","Ccaron","ccaron","dcroat"];function recoverGlyphName(e,t){if(void 0!==t[e])return e;const i=getUnicodeForGlyph(e,t);if(-1!==i)for(const e in t)if(t[e]===i)return e;info("Unable to recover a standard glyph name for: "+e);return e}function type1FontGlyphMapping(e,t,i){const a=Object.create(null);let s,r,n;const g=!!(e.flags&Mi);if(e.isInternalFont){n=t;for(r=0;r=0?s:0}}else if(e.baseEncodingName){n=getEncoding(e.baseEncodingName);for(r=0;r=0?s:0}}else if(g)for(r in t)a[r]=t[r];else{n=hi;for(r=0;r=0?s:0}}const o=e.differences;let c;if(o)for(r in o){const e=o[r];s=i.indexOf(e);if(-1===s){c||(c=wi());const t=recoverGlyphName(e,c);t!==e&&(s=i.indexOf(t))}a[r]=s>=0?s:0}return a}function normalizeFontName(e){return e.replaceAll(/[,_]/g,"-").replaceAll(/\s/g,"")}const Ji=getLookupTableFactory((e=>{e[8211]=65074;e[8212]=65073;e[8229]=65072;e[8230]=65049;e[12289]=65041;e[12290]=65042;e[12296]=65087;e[12297]=65088;e[12298]=65085;e[12299]=65086;e[12300]=65089;e[12301]=65090;e[12302]=65091;e[12303]=65092;e[12304]=65083;e[12305]=65084;e[12308]=65081;e[12309]=65082;e[12310]=65047;e[12311]=65048;e[65103]=65076;e[65281]=65045;e[65288]=65077;e[65289]=65078;e[65292]=65040;e[65306]=65043;e[65307]=65044;e[65311]=65046;e[65339]=65095;e[65341]=65096;e[65343]=65075;e[65371]=65079;e[65373]=65080})),Yi=getLookupTableFactory((function(e){e["Times-Roman"]="Times-Roman";e.Helvetica="Helvetica";e.Courier="Courier";e.Symbol="Symbol";e["Times-Bold"]="Times-Bold";e["Helvetica-Bold"]="Helvetica-Bold";e["Courier-Bold"]="Courier-Bold";e.ZapfDingbats="ZapfDingbats";e["Times-Italic"]="Times-Italic";e["Helvetica-Oblique"]="Helvetica-Oblique";e["Courier-Oblique"]="Courier-Oblique";e["Times-BoldItalic"]="Times-BoldItalic";e["Helvetica-BoldOblique"]="Helvetica-BoldOblique";e["Courier-BoldOblique"]="Courier-BoldOblique";e.ArialNarrow="Helvetica";e["ArialNarrow-Bold"]="Helvetica-Bold";e["ArialNarrow-BoldItalic"]="Helvetica-BoldOblique";e["ArialNarrow-Italic"]="Helvetica-Oblique";e.ArialBlack="Helvetica";e["ArialBlack-Bold"]="Helvetica-Bold";e["ArialBlack-BoldItalic"]="Helvetica-BoldOblique";e["ArialBlack-Italic"]="Helvetica-Oblique";e["Arial-Black"]="Helvetica";e["Arial-Black-Bold"]="Helvetica-Bold";e["Arial-Black-BoldItalic"]="Helvetica-BoldOblique";e["Arial-Black-Italic"]="Helvetica-Oblique";e.Arial="Helvetica";e["Arial-Bold"]="Helvetica-Bold";e["Arial-BoldItalic"]="Helvetica-BoldOblique";e["Arial-Italic"]="Helvetica-Oblique";e.ArialMT="Helvetica";e["Arial-BoldItalicMT"]="Helvetica-BoldOblique";e["Arial-BoldMT"]="Helvetica-Bold";e["Arial-ItalicMT"]="Helvetica-Oblique";e["Arial-BoldItalicMT-BoldItalic"]="Helvetica-BoldOblique";e["Arial-BoldMT-Bold"]="Helvetica-Bold";e["Arial-ItalicMT-Italic"]="Helvetica-Oblique";e.ArialUnicodeMS="Helvetica";e["ArialUnicodeMS-Bold"]="Helvetica-Bold";e["ArialUnicodeMS-BoldItalic"]="Helvetica-BoldOblique";e["ArialUnicodeMS-Italic"]="Helvetica-Oblique";e["Courier-BoldItalic"]="Courier-BoldOblique";e["Courier-Italic"]="Courier-Oblique";e.CourierNew="Courier";e["CourierNew-Bold"]="Courier-Bold";e["CourierNew-BoldItalic"]="Courier-BoldOblique";e["CourierNew-Italic"]="Courier-Oblique";e["CourierNewPS-BoldItalicMT"]="Courier-BoldOblique";e["CourierNewPS-BoldMT"]="Courier-Bold";e["CourierNewPS-ItalicMT"]="Courier-Oblique";e.CourierNewPSMT="Courier";e["Helvetica-BoldItalic"]="Helvetica-BoldOblique";e["Helvetica-Italic"]="Helvetica-Oblique";e["HelveticaLTStd-Bold"]="Helvetica-Bold";e["Symbol-Bold"]="Symbol";e["Symbol-BoldItalic"]="Symbol";e["Symbol-Italic"]="Symbol";e.TimesNewRoman="Times-Roman";e["TimesNewRoman-Bold"]="Times-Bold";e["TimesNewRoman-BoldItalic"]="Times-BoldItalic";e["TimesNewRoman-Italic"]="Times-Italic";e.TimesNewRomanPS="Times-Roman";e["TimesNewRomanPS-Bold"]="Times-Bold";e["TimesNewRomanPS-BoldItalic"]="Times-BoldItalic";e["TimesNewRomanPS-BoldItalicMT"]="Times-BoldItalic";e["TimesNewRomanPS-BoldMT"]="Times-Bold";e["TimesNewRomanPS-Italic"]="Times-Italic";e["TimesNewRomanPS-ItalicMT"]="Times-Italic";e.TimesNewRomanPSMT="Times-Roman";e["TimesNewRomanPSMT-Bold"]="Times-Bold";e["TimesNewRomanPSMT-BoldItalic"]="Times-BoldItalic";e["TimesNewRomanPSMT-Italic"]="Times-Italic"})),vi=getLookupTableFactory((function(e){e.Courier="FoxitFixed.pfb";e["Courier-Bold"]="FoxitFixedBold.pfb";e["Courier-BoldOblique"]="FoxitFixedBoldItalic.pfb";e["Courier-Oblique"]="FoxitFixedItalic.pfb";e.Helvetica="LiberationSans-Regular.ttf";e["Helvetica-Bold"]="LiberationSans-Bold.ttf";e["Helvetica-BoldOblique"]="LiberationSans-BoldItalic.ttf";e["Helvetica-Oblique"]="LiberationSans-Italic.ttf";e["Times-Roman"]="FoxitSerif.pfb";e["Times-Bold"]="FoxitSerifBold.pfb";e["Times-BoldItalic"]="FoxitSerifBoldItalic.pfb";e["Times-Italic"]="FoxitSerifItalic.pfb";e.Symbol="FoxitSymbol.pfb";e.ZapfDingbats="FoxitDingbats.pfb";e["LiberationSans-Regular"]="LiberationSans-Regular.ttf";e["LiberationSans-Bold"]="LiberationSans-Bold.ttf";e["LiberationSans-Italic"]="LiberationSans-Italic.ttf";e["LiberationSans-BoldItalic"]="LiberationSans-BoldItalic.ttf"})),Ki=getLookupTableFactory((function(e){e.Calibri="Helvetica";e["Calibri-Bold"]="Helvetica-Bold";e["Calibri-BoldItalic"]="Helvetica-BoldOblique";e["Calibri-Italic"]="Helvetica-Oblique";e.CenturyGothic="Helvetica";e["CenturyGothic-Bold"]="Helvetica-Bold";e["CenturyGothic-BoldItalic"]="Helvetica-BoldOblique";e["CenturyGothic-Italic"]="Helvetica-Oblique";e.ComicSansMS="Comic Sans MS";e["ComicSansMS-Bold"]="Comic Sans MS-Bold";e["ComicSansMS-BoldItalic"]="Comic Sans MS-BoldItalic";e["ComicSansMS-Italic"]="Comic Sans MS-Italic";e.GillSansMT="Helvetica";e["GillSansMT-Bold"]="Helvetica-Bold";e["GillSansMT-BoldItalic"]="Helvetica-BoldOblique";e["GillSansMT-Italic"]="Helvetica-Oblique";e.Impact="Helvetica";e["ItcSymbol-Bold"]="Helvetica-Bold";e["ItcSymbol-BoldItalic"]="Helvetica-BoldOblique";e["ItcSymbol-Book"]="Helvetica";e["ItcSymbol-BookItalic"]="Helvetica-Oblique";e["ItcSymbol-Medium"]="Helvetica";e["ItcSymbol-MediumItalic"]="Helvetica-Oblique";e.LucidaConsole="Courier";e["LucidaConsole-Bold"]="Courier-Bold";e["LucidaConsole-BoldItalic"]="Courier-BoldOblique";e["LucidaConsole-Italic"]="Courier-Oblique";e["LucidaSans-Demi"]="Helvetica-Bold";e["MS-Gothic"]="MS Gothic";e["MS-Gothic-Bold"]="MS Gothic-Bold";e["MS-Gothic-BoldItalic"]="MS Gothic-BoldItalic";e["MS-Gothic-Italic"]="MS Gothic-Italic";e["MS-Mincho"]="MS Mincho";e["MS-Mincho-Bold"]="MS Mincho-Bold";e["MS-Mincho-BoldItalic"]="MS Mincho-BoldItalic";e["MS-Mincho-Italic"]="MS Mincho-Italic";e["MS-PGothic"]="MS PGothic";e["MS-PGothic-Bold"]="MS PGothic-Bold";e["MS-PGothic-BoldItalic"]="MS PGothic-BoldItalic";e["MS-PGothic-Italic"]="MS PGothic-Italic";e["MS-PMincho"]="MS PMincho";e["MS-PMincho-Bold"]="MS PMincho-Bold";e["MS-PMincho-BoldItalic"]="MS PMincho-BoldItalic";e["MS-PMincho-Italic"]="MS PMincho-Italic";e.NuptialScript="Times-Italic";e.SegoeUISymbol="Helvetica"})),Ti=getLookupTableFactory((function(e){e["Adobe Jenson"]=!0;e["Adobe Text"]=!0;e.Albertus=!0;e.Aldus=!0;e.Alexandria=!0;e.Algerian=!0;e["American Typewriter"]=!0;e.Antiqua=!0;e.Apex=!0;e.Arno=!0;e.Aster=!0;e.Aurora=!0;e.Baskerville=!0;e.Bell=!0;e.Bembo=!0;e["Bembo Schoolbook"]=!0;e.Benguiat=!0;e["Berkeley Old Style"]=!0;e["Bernhard Modern"]=!0;e["Berthold City"]=!0;e.Bodoni=!0;e["Bauer Bodoni"]=!0;e["Book Antiqua"]=!0;e.Bookman=!0;e["Bordeaux Roman"]=!0;e["Californian FB"]=!0;e.Calisto=!0;e.Calvert=!0;e.Capitals=!0;e.Cambria=!0;e.Cartier=!0;e.Caslon=!0;e.Catull=!0;e.Centaur=!0;e["Century Old Style"]=!0;e["Century Schoolbook"]=!0;e.Chaparral=!0;e["Charis SIL"]=!0;e.Cheltenham=!0;e["Cholla Slab"]=!0;e.Clarendon=!0;e.Clearface=!0;e.Cochin=!0;e.Colonna=!0;e["Computer Modern"]=!0;e["Concrete Roman"]=!0;e.Constantia=!0;e["Cooper Black"]=!0;e.Corona=!0;e.Ecotype=!0;e.Egyptienne=!0;e.Elephant=!0;e.Excelsior=!0;e.Fairfield=!0;e["FF Scala"]=!0;e.Folkard=!0;e.Footlight=!0;e.FreeSerif=!0;e["Friz Quadrata"]=!0;e.Garamond=!0;e.Gentium=!0;e.Georgia=!0;e.Gloucester=!0;e["Goudy Old Style"]=!0;e["Goudy Schoolbook"]=!0;e["Goudy Pro Font"]=!0;e.Granjon=!0;e["Guardian Egyptian"]=!0;e.Heather=!0;e.Hercules=!0;e["High Tower Text"]=!0;e.Hiroshige=!0;e["Hoefler Text"]=!0;e["Humana Serif"]=!0;e.Imprint=!0;e["Ionic No. 5"]=!0;e.Janson=!0;e.Joanna=!0;e.Korinna=!0;e.Lexicon=!0;e.LiberationSerif=!0;e["Liberation Serif"]=!0;e["Linux Libertine"]=!0;e.Literaturnaya=!0;e.Lucida=!0;e["Lucida Bright"]=!0;e.Melior=!0;e.Memphis=!0;e.Miller=!0;e.Minion=!0;e.Modern=!0;e["Mona Lisa"]=!0;e["Mrs Eaves"]=!0;e["MS Serif"]=!0;e["Museo Slab"]=!0;e["New York"]=!0;e["Nimbus Roman"]=!0;e["NPS Rawlinson Roadway"]=!0;e.NuptialScript=!0;e.Palatino=!0;e.Perpetua=!0;e.Plantin=!0;e["Plantin Schoolbook"]=!0;e.Playbill=!0;e["Poor Richard"]=!0;e["Rawlinson Roadway"]=!0;e.Renault=!0;e.Requiem=!0;e.Rockwell=!0;e.Roman=!0;e["Rotis Serif"]=!0;e.Sabon=!0;e.Scala=!0;e.Seagull=!0;e.Sistina=!0;e.Souvenir=!0;e.STIX=!0;e["Stone Informal"]=!0;e["Stone Serif"]=!0;e.Sylfaen=!0;e.Times=!0;e.Trajan=!0;e["Trinité"]=!0;e["Trump Mediaeval"]=!0;e.Utopia=!0;e["Vale Type"]=!0;e["Bitstream Vera"]=!0;e["Vera Serif"]=!0;e.Versailles=!0;e.Wanted=!0;e.Weiss=!0;e["Wide Latin"]=!0;e.Windsor=!0;e.XITS=!0})),qi=getLookupTableFactory((function(e){e.Dingbats=!0;e.Symbol=!0;e.ZapfDingbats=!0;e.Wingdings=!0;e["Wingdings-Bold"]=!0;e["Wingdings-Regular"]=!0})),Oi=getLookupTableFactory((function(e){e[2]=10;e[3]=32;e[4]=33;e[5]=34;e[6]=35;e[7]=36;e[8]=37;e[9]=38;e[10]=39;e[11]=40;e[12]=41;e[13]=42;e[14]=43;e[15]=44;e[16]=45;e[17]=46;e[18]=47;e[19]=48;e[20]=49;e[21]=50;e[22]=51;e[23]=52;e[24]=53;e[25]=54;e[26]=55;e[27]=56;e[28]=57;e[29]=58;e[30]=894;e[31]=60;e[32]=61;e[33]=62;e[34]=63;e[35]=64;e[36]=65;e[37]=66;e[38]=67;e[39]=68;e[40]=69;e[41]=70;e[42]=71;e[43]=72;e[44]=73;e[45]=74;e[46]=75;e[47]=76;e[48]=77;e[49]=78;e[50]=79;e[51]=80;e[52]=81;e[53]=82;e[54]=83;e[55]=84;e[56]=85;e[57]=86;e[58]=87;e[59]=88;e[60]=89;e[61]=90;e[62]=91;e[63]=92;e[64]=93;e[65]=94;e[66]=95;e[67]=96;e[68]=97;e[69]=98;e[70]=99;e[71]=100;e[72]=101;e[73]=102;e[74]=103;e[75]=104;e[76]=105;e[77]=106;e[78]=107;e[79]=108;e[80]=109;e[81]=110;e[82]=111;e[83]=112;e[84]=113;e[85]=114;e[86]=115;e[87]=116;e[88]=117;e[89]=118;e[90]=119;e[91]=120;e[92]=121;e[93]=122;e[94]=123;e[95]=124;e[96]=125;e[97]=126;e[98]=196;e[99]=197;e[100]=199;e[101]=201;e[102]=209;e[103]=214;e[104]=220;e[105]=225;e[106]=224;e[107]=226;e[108]=228;e[109]=227;e[110]=229;e[111]=231;e[112]=233;e[113]=232;e[114]=234;e[115]=235;e[116]=237;e[117]=236;e[118]=238;e[119]=239;e[120]=241;e[121]=243;e[122]=242;e[123]=244;e[124]=246;e[125]=245;e[126]=250;e[127]=249;e[128]=251;e[129]=252;e[130]=8224;e[131]=176;e[132]=162;e[133]=163;e[134]=167;e[135]=8226;e[136]=182;e[137]=223;e[138]=174;e[139]=169;e[140]=8482;e[141]=180;e[142]=168;e[143]=8800;e[144]=198;e[145]=216;e[146]=8734;e[147]=177;e[148]=8804;e[149]=8805;e[150]=165;e[151]=181;e[152]=8706;e[153]=8721;e[154]=8719;e[156]=8747;e[157]=170;e[158]=186;e[159]=8486;e[160]=230;e[161]=248;e[162]=191;e[163]=161;e[164]=172;e[165]=8730;e[166]=402;e[167]=8776;e[168]=8710;e[169]=171;e[170]=187;e[171]=8230;e[179]=8220;e[180]=8221;e[181]=8216;e[182]=8217;e[200]=193;e[203]=205;e[207]=211;e[210]=218;e[223]=711;e[224]=321;e[225]=322;e[226]=352;e[227]=353;e[228]=381;e[229]=382;e[233]=221;e[234]=253;e[252]=263;e[253]=268;e[254]=269;e[258]=258;e[260]=260;e[261]=261;e[265]=280;e[266]=281;e[267]=282;e[268]=283;e[269]=313;e[275]=323;e[276]=324;e[278]=328;e[283]=344;e[284]=345;e[285]=346;e[286]=347;e[292]=367;e[295]=377;e[296]=378;e[298]=380;e[305]=963;e[306]=964;e[307]=966;e[308]=8215;e[309]=8252;e[310]=8319;e[311]=8359;e[312]=8592;e[313]=8593;e[337]=9552;e[493]=1039;e[494]=1040;e[672]=1488;e[673]=1489;e[674]=1490;e[675]=1491;e[676]=1492;e[677]=1493;e[678]=1494;e[679]=1495;e[680]=1496;e[681]=1497;e[682]=1498;e[683]=1499;e[684]=1500;e[685]=1501;e[686]=1502;e[687]=1503;e[688]=1504;e[689]=1505;e[690]=1506;e[691]=1507;e[692]=1508;e[693]=1509;e[694]=1510;e[695]=1511;e[696]=1512;e[697]=1513;e[698]=1514;e[705]=1524;e[706]=8362;e[710]=64288;e[711]=64298;e[759]=1617;e[761]=1776;e[763]=1778;e[775]=1652;e[777]=1764;e[778]=1780;e[779]=1781;e[780]=1782;e[782]=771;e[783]=64726;e[786]=8363;e[788]=8532;e[790]=768;e[791]=769;e[792]=768;e[795]=803;e[797]=64336;e[798]=64337;e[799]=64342;e[800]=64343;e[801]=64344;e[802]=64345;e[803]=64362;e[804]=64363;e[805]=64364;e[2424]=7821;e[2425]=7822;e[2426]=7823;e[2427]=7824;e[2428]=7825;e[2429]=7826;e[2430]=7827;e[2433]=7682;e[2678]=8045;e[2679]=8046;e[2830]=1552;e[2838]=686;e[2840]=751;e[2842]=753;e[2843]=754;e[2844]=755;e[2846]=757;e[2856]=767;e[2857]=848;e[2858]=849;e[2862]=853;e[2863]=854;e[2864]=855;e[2865]=861;e[2866]=862;e[2906]=7460;e[2908]=7462;e[2909]=7463;e[2910]=7464;e[2912]=7466;e[2913]=7467;e[2914]=7468;e[2916]=7470;e[2917]=7471;e[2918]=7472;e[2920]=7474;e[2921]=7475;e[2922]=7476;e[2924]=7478;e[2925]=7479;e[2926]=7480;e[2928]=7482;e[2929]=7483;e[2930]=7484;e[2932]=7486;e[2933]=7487;e[2934]=7488;e[2936]=7490;e[2937]=7491;e[2938]=7492;e[2940]=7494;e[2941]=7495;e[2942]=7496;e[2944]=7498;e[2946]=7500;e[2948]=7502;e[2950]=7504;e[2951]=7505;e[2952]=7506;e[2954]=7508;e[2955]=7509;e[2956]=7510;e[2958]=7512;e[2959]=7513;e[2960]=7514;e[2962]=7516;e[2963]=7517;e[2964]=7518;e[2966]=7520;e[2967]=7521;e[2968]=7522;e[2970]=7524;e[2971]=7525;e[2972]=7526;e[2974]=7528;e[2975]=7529;e[2976]=7530;e[2978]=1537;e[2979]=1538;e[2980]=1539;e[2982]=1549;e[2983]=1551;e[2984]=1552;e[2986]=1554;e[2987]=1555;e[2988]=1556;e[2990]=1623;e[2991]=1624;e[2995]=1775;e[2999]=1791;e[3002]=64290;e[3003]=64291;e[3004]=64292;e[3006]=64294;e[3007]=64295;e[3008]=64296;e[3011]=1900;e[3014]=8223;e[3015]=8244;e[3017]=7532;e[3018]=7533;e[3019]=7534;e[3075]=7590;e[3076]=7591;e[3079]=7594;e[3080]=7595;e[3083]=7598;e[3084]=7599;e[3087]=7602;e[3088]=7603;e[3091]=7606;e[3092]=7607;e[3095]=7610;e[3096]=7611;e[3099]=7614;e[3100]=7615;e[3103]=7618;e[3104]=7619;e[3107]=8337;e[3108]=8338;e[3116]=1884;e[3119]=1885;e[3120]=1885;e[3123]=1886;e[3124]=1886;e[3127]=1887;e[3128]=1887;e[3131]=1888;e[3132]=1888;e[3135]=1889;e[3136]=1889;e[3139]=1890;e[3140]=1890;e[3143]=1891;e[3144]=1891;e[3147]=1892;e[3148]=1892;e[3153]=580;e[3154]=581;e[3157]=584;e[3158]=585;e[3161]=588;e[3162]=589;e[3165]=891;e[3166]=892;e[3169]=1274;e[3170]=1275;e[3173]=1278;e[3174]=1279;e[3181]=7622;e[3182]=7623;e[3282]=11799;e[3316]=578;e[3379]=42785;e[3393]=1159;e[3416]=8377})),Pi=getLookupTableFactory((function(e){e[227]=322;e[264]=261;e[291]=346})),Wi=getLookupTableFactory((function(e){e[1]=32;e[4]=65;e[5]=192;e[6]=193;e[9]=196;e[17]=66;e[18]=67;e[21]=268;e[24]=68;e[28]=69;e[29]=200;e[30]=201;e[32]=282;e[38]=70;e[39]=71;e[44]=72;e[47]=73;e[48]=204;e[49]=205;e[58]=74;e[60]=75;e[62]=76;e[68]=77;e[69]=78;e[75]=79;e[76]=210;e[80]=214;e[87]=80;e[89]=81;e[90]=82;e[92]=344;e[94]=83;e[97]=352;e[100]=84;e[104]=85;e[109]=220;e[115]=86;e[116]=87;e[121]=88;e[122]=89;e[124]=221;e[127]=90;e[129]=381;e[258]=97;e[259]=224;e[260]=225;e[263]=228;e[268]=261;e[271]=98;e[272]=99;e[273]=263;e[275]=269;e[282]=100;e[286]=101;e[287]=232;e[288]=233;e[290]=283;e[295]=281;e[296]=102;e[336]=103;e[346]=104;e[349]=105;e[350]=236;e[351]=237;e[361]=106;e[364]=107;e[367]=108;e[371]=322;e[373]=109;e[374]=110;e[381]=111;e[382]=242;e[383]=243;e[386]=246;e[393]=112;e[395]=113;e[396]=114;e[398]=345;e[400]=115;e[401]=347;e[403]=353;e[410]=116;e[437]=117;e[442]=252;e[448]=118;e[449]=119;e[454]=120;e[455]=121;e[457]=253;e[460]=122;e[462]=382;e[463]=380;e[853]=44;e[855]=58;e[856]=46;e[876]=47;e[878]=45;e[882]=45;e[894]=40;e[895]=41;e[896]=91;e[897]=93;e[923]=64;e[1004]=48;e[1005]=49;e[1006]=50;e[1007]=51;e[1008]=52;e[1009]=53;e[1010]=54;e[1011]=55;e[1012]=56;e[1013]=57;e[1081]=37;e[1085]=43;e[1086]=45}));function getStandardFontName(e){const t=normalizeFontName(e);return Yi()[t]}function isKnownFontName(e){const t=normalizeFontName(e);return!!(Yi()[t]||Ki()[t]||Ti()[t]||qi()[t])}class ToUnicodeMap{constructor(e=[]){this._map=e}get length(){return this._map.length}forEach(e){for(const t in this._map)e(t,this._map[t].codePointAt(0))}has(e){return void 0!==this._map[e]}get(e){return this._map[e]}charCodeOf(e){const t=this._map;if(t.length<=65536)return t.indexOf(e);for(const i in t)if(t[i]===e)return 0|i;return-1}amend(e){for(const t in e)this._map[t]=e[t]}}class IdentityToUnicodeMap{constructor(e,t){this.firstChar=e;this.lastChar=t}get length(){return this.lastChar+1-this.firstChar}forEach(e){for(let t=this.firstChar,i=this.lastChar;t<=i;t++)e(t,t)}has(e){return this.firstChar<=e&&e<=this.lastChar}get(e){if(this.firstChar<=e&&e<=this.lastChar)return String.fromCharCode(e)}charCodeOf(e){return Number.isInteger(e)&&e>=this.firstChar&&e<=this.lastChar?e:-1}amend(e){unreachable("Should not call amend()")}}class CFFFont{constructor(e,t){this.properties=t;const i=new CFFParser(e,t,Ri);this.cff=i.parse();this.cff.duplicateFirstGlyph();const a=new CFFCompiler(this.cff);this.seacs=this.cff.seacs;try{this.data=a.compile()}catch{warn("Failed to compile font "+t.loadedName);this.data=e}this._createBuiltInEncoding()}get numGlyphs(){return this.cff.charStrings.count}getCharset(){return this.cff.charset.charset}getGlyphMapping(){const e=this.cff,t=this.properties,{cidToGidMap:i,cMap:a}=t,s=e.charset.charset;let r,n;if(t.composite){let t,g;if(i?.length>0){t=Object.create(null);for(let e=0,a=i.length;e=0){const a=i[t];a&&(s[e]=a)}}s.length>0&&(this.properties.builtInEncoding=s)}}function getUint32(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}function getUint16(e,t){return e[t]<<8|e[t+1]}function getInt16(e,t){return(e[t]<<24|e[t+1]<<16)>>16}function getInt8(e,t){return e[t]<<24>>24}function getFloat214(e,t){return getInt16(e,t)/16384}function getSubroutineBias(e){const t=e.length;let i=32768;t<1240?i=107:t<33900&&(i=1131);return i}function parseCmap(e,t,i){const a=1===getUint16(e,t+2)?getUint32(e,t+8):getUint32(e,t+16),s=getUint16(e,t+a);let r,n,g;if(4===s){getUint16(e,t+a+2);const i=getUint16(e,t+a+6)>>1;n=t+a+14;r=[];for(g=0;g>1;i0;)C.push({flags:r})}for(i=0;i>1;p=!0;break;case 4:n+=s.pop();moveTo(r,n);p=!0;break;case 5:for(;s.length>0;){r+=s.shift();n+=s.shift();lineTo(r,n)}break;case 6:for(;s.length>0;){r+=s.shift();lineTo(r,n);if(0===s.length)break;n+=s.shift();lineTo(r,n)}break;case 7:for(;s.length>0;){n+=s.shift();lineTo(r,n);if(0===s.length)break;r+=s.shift();lineTo(r,n)}break;case 8:for(;s.length>0;){c=r+s.shift();h=n+s.shift();C=c+s.shift();l=h+s.shift();r=C+s.shift();n=l+s.shift();bezierCurveTo(c,h,C,l,r,n)}break;case 10:d=s.pop();f=null;if(i.isCFFCIDFont){const e=i.fdSelect.getFDIndex(a);if(e>=0&&eMath.abs(n-t)?r+=s.shift():n+=s.shift();bezierCurveTo(c,h,C,l,r,n);break;default:throw new FormatError(`unknown operator: 12 ${m}`)}break;case 14:if(s.length>=4){const e=s.pop(),a=s.pop();n=s.pop();r=s.pop();t.save();t.translate(r,n);let g=lookupCmap(i.cmap,String.fromCharCode(i.glyphNameMap[hi[e]]));compileCharString(i.glyphs[g.glyphId],t,i,g.glyphId);t.restore();g=lookupCmap(i.cmap,String.fromCharCode(i.glyphNameMap[hi[a]]));compileCharString(i.glyphs[g.glyphId],t,i,g.glyphId)}return;case 19:case 20:g+=s.length>>1;o+=g+7>>3;p=!0;break;case 21:n+=s.pop();r+=s.pop();moveTo(r,n);p=!0;break;case 22:r+=s.pop();moveTo(r,n);p=!0;break;case 24:for(;s.length>2;){c=r+s.shift();h=n+s.shift();C=c+s.shift();l=h+s.shift();r=C+s.shift();n=l+s.shift();bezierCurveTo(c,h,C,l,r,n)}r+=s.shift();n+=s.shift();lineTo(r,n);break;case 25:for(;s.length>6;){r+=s.shift();n+=s.shift();lineTo(r,n)}c=r+s.shift();h=n+s.shift();C=c+s.shift();l=h+s.shift();r=C+s.shift();n=l+s.shift();bezierCurveTo(c,h,C,l,r,n);break;case 26:s.length%2&&(r+=s.shift());for(;s.length>0;){c=r;h=n+s.shift();C=c+s.shift();l=h+s.shift();r=C;n=l+s.shift();bezierCurveTo(c,h,C,l,r,n)}break;case 27:s.length%2&&(n+=s.shift());for(;s.length>0;){c=r+s.shift();h=n;C=c+s.shift();l=h+s.shift();r=C+s.shift();n=l;bezierCurveTo(c,h,C,l,r,n)}break;case 28:s.push((e[o]<<24|e[o+1]<<16)>>16);o+=2;break;case 29:d=s.pop()+i.gsubrsBias;f=i.gsubrs[d];f&&parse(f);break;case 30:for(;s.length>0;){c=r;h=n+s.shift();C=c+s.shift();l=h+s.shift();r=C+s.shift();n=l+(1===s.length?s.shift():0);bezierCurveTo(c,h,C,l,r,n);if(0===s.length)break;c=r+s.shift();h=n;C=c+s.shift();l=h+s.shift();n=l+s.shift();r=C+(1===s.length?s.shift():0);bezierCurveTo(c,h,C,l,r,n)}break;case 31:for(;s.length>0;){c=r+s.shift();h=n;C=c+s.shift();l=h+s.shift();n=l+s.shift();r=C+(1===s.length?s.shift():0);bezierCurveTo(c,h,C,l,r,n);if(0===s.length)break;c=r;h=n+s.shift();C=c+s.shift();l=h+s.shift();r=C+s.shift();n=l+(1===s.length?s.shift():0);bezierCurveTo(c,h,C,l,r,n)}break;default:if(m<32)throw new FormatError(`unknown operator: ${m}`);if(m<247)s.push(m-139);else if(m<251)s.push(256*(m-247)+e[o++]+108);else if(m<255)s.push(256*-(m-251)-e[o++]-108);else{s.push((e[o]<<24|e[o+1]<<16|e[o+2]<<8|e[o+3])/65536);o+=4}}p&&(s.length=0)}}(e)}class Commands{cmds=[];transformStack=[];currentTransform=[1,0,0,1,0,0];add(e,t){if(t){const[i,a,s,r,n,g]=this.currentTransform;for(let e=0,o=t.length;e=0&&e2*getUint16(e,t)}const r=[];let n=s(t,0);for(let i=a;ie+(t.getSize()+3&-4)),0)}write(){const e=this.getSize(),t=new DataView(new ArrayBuffer(e)),i=e>131070,a=i?4:2,s=new DataView(new ArrayBuffer((this.glyphs.length+1)*a));i?s.setUint32(0,0):s.setUint16(0,0);let r=0,n=0;for(const e of this.glyphs){r+=e.write(r,t);r=r+3&-4;n+=a;i?s.setUint32(n,r):s.setUint16(n,r>>1)}return{isLocationLong:i,loca:new Uint8Array(s.buffer),glyf:new Uint8Array(t.buffer)}}scale(e){for(let t=0,i=this.glyphs.length;te+t.getSize()),0);return this.header.getSize()+e}write(e,t){if(!this.header)return 0;const i=e;e+=this.header.write(e,t);if(this.simple)e+=this.simple.write(e,t);else for(const i of this.composites)e+=i.write(e,t);return e-i}scale(e){if(!this.header)return;const t=(this.header.xMin+this.header.xMax)/2;this.header.scale(t,e);if(this.simple)this.simple.scale(t,e);else for(const i of this.composites)i.scale(t,e)}}class GlyphHeader{constructor({numberOfContours:e,xMin:t,yMin:i,xMax:a,yMax:s}){this.numberOfContours=e;this.xMin=t;this.yMin=i;this.xMax=a;this.yMax=s}static parse(e,t){return[10,new GlyphHeader({numberOfContours:t.getInt16(e),xMin:t.getInt16(e+2),yMin:t.getInt16(e+4),xMax:t.getInt16(e+6),yMax:t.getInt16(e+8)})]}getSize(){return 10}write(e,t){t.setInt16(e,this.numberOfContours);t.setInt16(e+2,this.xMin);t.setInt16(e+4,this.yMin);t.setInt16(e+6,this.xMax);t.setInt16(e+8,this.yMax);return 10}scale(e,t){this.xMin=Math.round(e+(this.xMin-e)*t);this.xMax=Math.round(e+(this.xMax-e)*t)}}class Contour{constructor({flags:e,xCoordinates:t,yCoordinates:i}){this.xCoordinates=t;this.yCoordinates=i;this.flags=e}}class SimpleGlyph{constructor({contours:e,instructions:t}){this.contours=e;this.instructions=t}static parse(e,t,i){const a=[];for(let s=0;s255?e+=2:g>0&&(e+=1);t=r;g=Math.abs(n-i);g>255?e+=2:g>0&&(e+=1);i=n}}return e}write(e,t){const i=e,a=[],s=[],r=[];let n=0,g=0;for(const i of this.contours){for(let e=0,t=i.xCoordinates.length;e=0?18:2;a.push(e)}else a.push(c)}n=o;const C=i.yCoordinates[e];c=C-g;if(0===c){t|=32;s.push(0)}else{const e=Math.abs(c);if(e<=255){t|=c>=0?36:4;s.push(e)}else s.push(c)}g=C;r.push(t)}t.setUint16(e,a.length-1);e+=2}t.setUint16(e,this.instructions.length);e+=2;if(this.instructions.length){new Uint8Array(t.buffer,0,t.buffer.byteLength).set(this.instructions,e);e+=this.instructions.length}for(const i of r)t.setUint8(e++,i);for(let i=0,s=a.length;i=-128&&this.argument1<=127&&this.argument2>=-128&&this.argument2<=127||(e+=2):this.argument1>=0&&this.argument1<=255&&this.argument2>=0&&this.argument2<=255||(e+=2);return e}write(e,t){const i=e;2&this.flags?this.argument1>=-128&&this.argument1<=127&&this.argument2>=-128&&this.argument2<=127||(this.flags|=1):this.argument1>=0&&this.argument1<=255&&this.argument2>=0&&this.argument2<=255||(this.flags|=1);t.setUint16(e,this.flags);t.setUint16(e+2,this.glyphIndex);e+=4;if(1&this.flags){if(2&this.flags){t.setInt16(e,this.argument1);t.setInt16(e+2,this.argument2)}else{t.setUint16(e,this.argument1);t.setUint16(e+2,this.argument2)}e+=4}else{t.setUint8(e,this.argument1);t.setUint8(e+1,this.argument2);e+=2}if(256&this.flags){t.setUint16(e,this.instructions.length);e+=2;if(this.instructions.length){new Uint8Array(t.buffer,0,t.buffer.byteLength).set(this.instructions,e);e+=this.instructions.length}}return e-i}scale(e,t){}}function writeInt16(e,t,i){e[t]=i>>8&255;e[t+1]=255&i}function writeInt32(e,t,i){e[t]=i>>24&255;e[t+1]=i>>16&255;e[t+2]=i>>8&255;e[t+3]=255&i}function writeData(e,t,i){if(i instanceof Uint8Array)e.set(i,t);else if("string"==typeof i)for(let a=0,s=i.length;ai;){i<<=1;a++}const s=i*t;return{range:s,entry:a,rangeShift:t*e-s}}toArray(){let e=this.sfnt;const t=this.tables,i=Object.keys(t);i.sort();const a=i.length;let s,r,n,g,o,c=12+16*a;const C=[c];for(s=0;s>>0;C.push(c)}const h=new Uint8Array(c);for(s=0;s>>0}writeInt32(h,c+4,e);writeInt32(h,c+8,C[s]);writeInt32(h,c+12,t[o].length);c+=16}return h}addTable(e,t){if(e in this.tables)throw new Error("Table "+e+" already exists");this.tables[e]=t}}const Zi=[4],Vi=[5],zi=[6],_i=[7],$i=[8],Aa=[12,35],ea=[14],ta=[21],ia=[22],aa=[30],sa=[31];class Type1CharString{constructor(){this.width=0;this.lsb=0;this.flexing=!1;this.output=[];this.stack=[]}convert(e,t,i){const a=e.length;let s,r,n,g=!1;for(let o=0;oa)return!0;const s=a-e;for(let e=s;e>8&255,255&t);else{t=65536*t|0;this.output.push(255,t>>24&255,t>>16&255,t>>8&255,255&t)}}this.output.push(...t);i?this.stack.splice(s,e):this.stack.length=0;return!1}}function isHexDigit(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function decrypt(e,t,i){if(i>=e.length)return new Uint8Array(0);let a,s,r=0|t;for(a=0;a>8;r=52845*(t+r)+22719&65535}return g}function isSpecial(e){return 47===e||91===e||93===e||123===e||125===e||40===e||41===e}class Type1Parser{constructor(e,t,i){if(t){const t=e.getBytes(),i=!((isHexDigit(t[0])||isWhiteSpace(t[0]))&&isHexDigit(t[1])&&isHexDigit(t[2])&&isHexDigit(t[3])&&isHexDigit(t[4])&&isHexDigit(t[5])&&isHexDigit(t[6])&&isHexDigit(t[7]));e=new Stream(i?decrypt(t,55665,4):function decryptAscii(e,t,i){let a=0|t;const s=e.length,r=new Uint8Array(s>>>1);let n,g;for(n=0,g=0;n>8;a=52845*(e+a)+22719&65535}}return r.slice(i,g)}(t,55665,4))}this.seacAnalysisEnabled=!!i;this.stream=e;this.nextChar()}readNumberArray(){this.getToken();const e=[];for(;;){const t=this.getToken();if(null===t||"]"===t||"}"===t)break;e.push(parseFloat(t||0))}return e}readNumber(){const e=this.getToken();return parseFloat(e||0)}readInt(){const e=this.getToken();return 0|parseInt(e||0,10)}readBoolean(){return"true"===this.getToken()?1:0}nextChar(){return this.currentChar=this.stream.getByte()}prevChar(){this.stream.skip(-2);return this.currentChar=this.stream.getByte()}getToken(){let e=!1,t=this.currentChar;for(;;){if(-1===t)return null;if(e)10!==t&&13!==t||(e=!1);else if(37===t)e=!0;else if(!isWhiteSpace(t))break;t=this.nextChar()}if(isSpecial(t)){this.nextChar();return String.fromCharCode(t)}let i="";do{i+=String.fromCharCode(t);t=this.nextChar()}while(t>=0&&!isWhiteSpace(t)&&!isSpecial(t));return i}readCharStrings(e,t){return-1===t?e:decrypt(e,4330,t)}extractFontProgram(e){const t=this.stream,i=[],a=[],s=Object.create(null);s.lenIV=4;const r={subrs:[],charstrings:[],properties:{privateData:s}};let n,g,o,c;for(;null!==(n=this.getToken());)if("/"===n){n=this.getToken();switch(n){case"CharStrings":this.getToken();this.getToken();this.getToken();this.getToken();for(;;){n=this.getToken();if(null===n||"end"===n)break;if("/"!==n)continue;const e=this.getToken();g=this.readInt();this.getToken();o=g>0?t.getBytes(g):new Uint8Array(0);c=r.properties.privateData.lenIV;const i=this.readCharStrings(o,c);this.nextChar();n=this.getToken();"noaccess"===n?this.getToken():"/"===n&&this.prevChar();a.push({glyph:e,encoded:i})}break;case"Subrs":this.readInt();this.getToken();for(;"dup"===this.getToken();){const e=this.readInt();g=this.readInt();this.getToken();o=g>0?t.getBytes(g):new Uint8Array(0);c=r.properties.privateData.lenIV;const a=this.readCharStrings(o,c);this.nextChar();n=this.getToken();"noaccess"===n&&this.getToken();i[e]=a}break;case"BlueValues":case"OtherBlues":case"FamilyBlues":case"FamilyOtherBlues":const e=this.readNumberArray();e.length>0&&e.length,0;break;case"StemSnapH":case"StemSnapV":r.properties.privateData[n]=this.readNumberArray();break;case"StdHW":case"StdVW":r.properties.privateData[n]=this.readNumberArray()[0];break;case"BlueShift":case"lenIV":case"BlueFuzz":case"BlueScale":case"LanguageGroup":r.properties.privateData[n]=this.readNumber();break;case"ExpansionFactor":r.properties.privateData[n]=this.readNumber()||.06;break;case"ForceBold":r.properties.privateData[n]=this.readBoolean()}}for(const{encoded:t,glyph:s}of a){const a=new Type1CharString,n=a.convert(t,i,this.seacAnalysisEnabled);let g=a.output;n&&(g=[14]);const o={glyphName:s,charstring:g,width:a.width,lsb:a.lsb,seac:a.seac};".notdef"===s?r.charstrings.unshift(o):r.charstrings.push(o);if(e.builtInEncoding){const t=e.builtInEncoding.indexOf(s);t>-1&&void 0===e.widths[t]&&t>=e.firstChar&&t<=e.lastChar&&(e.widths[t]=a.width)}}return r}extractFontHeader(e){let t;for(;null!==(t=this.getToken());)if("/"===t){t=this.getToken();switch(t){case"FontMatrix":const i=this.readNumberArray();e.fontMatrix=i;break;case"Encoding":const a=this.getToken();let s;if(/^\d+$/.test(a)){s=[];const e=0|parseInt(a,10);this.getToken();for(let i=0;i=s){n+=i;for(;n=0&&(a[e]=s)}}return type1FontGlyphMapping(e,a,i)}hasGlyphId(e){if(e<0||e>=this.numGlyphs)return!1;if(0===e)return!0;return this.charstrings[e-1].charstring.length>0}getSeacs(e){const t=[];for(let i=0,a=e.length;i0;e--)t[e]-=t[e-1];Q.setByName(e,t)}r.topDict.privateDict=Q;const u=new CFFIndex;for(C=0,h=a.length;C0&&e.toUnicode.amend(t)}class fonts_Glyph{constructor(e,t,i,a,s,r,n,g,o){this.originalCharCode=e;this.fontChar=t;this.unicode=i;this.accent=a;this.width=s;this.vmetric=r;this.operatorListId=n;this.isSpace=g;this.isInFont=o}get category(){return shadow(this,"category",function getCharUnicodeCategory(e){const t=ki.get(e);if(t)return t;const i=e.match(Si),a={isWhitespace:!!i?.[1],isZeroWidthDiacritic:!!i?.[2],isInvisibleFormatMark:!!i?.[3]};ki.set(e,a);return a}(this.unicode),!0)}}function int16(e,t){return(e<<8)+t}function writeSignedInt16(e,t,i){e[t+1]=i;e[t]=i>>>8}function signedInt16(e,t){const i=(e<<8)+t;return 32768&i?i-65536:i}function string16(e){return String.fromCharCode(e>>8&255,255&e)}function safeString16(e){e>32767?e=32767:e<-32768&&(e=-32768);return String.fromCharCode(e>>8&255,255&e)}function isTrueTypeCollectionFile(e){return"ttcf"===bytesToString(e.peekBytes(4))}function getFontFileType(e,{type:t,subtype:i,composite:a}){let s,r;if(function isTrueTypeFile(e){const t=e.peekBytes(4);return 65536===readUint32(t,0)||"true"===bytesToString(t)}(e)||isTrueTypeCollectionFile(e))s=a?"CIDFontType2":"TrueType";else if(function isOpenTypeFile(e){return"OTTO"===bytesToString(e.peekBytes(4))}(e))s=a?"CIDFontType2":"OpenType";else if(function isType1File(e){const t=e.peekBytes(2);return 37===t[0]&&33===t[1]||128===t[0]&&1===t[1]}(e))s=a?"CIDFontType0":"MMType1"===t?"MMType1":"Type1";else if(function isCFFFile(e){const t=e.peekBytes(4);return t[0]>=1&&t[3]>=1&&t[3]<=4}(e))if(a){s="CIDFontType0";r="CIDFontType0C"}else{s="MMType1"===t?"MMType1":"Type1";r="Type1C"}else{warn("getFontFileType: Unable to detect correct font file Type/Subtype.");s=t;r=i}return[s,r]}function applyStandardFontGlyphMap(e,t){for(const i in t)e[+i]=t[i]}function buildToFontChar(e,t,i){const a=[];let s;for(let i=0,r=e.length;iC){o++;if(o>=ra.length){warn("Ran out of space in font private use area.");break}c=ra[o][0];C=ra[o][1]}const E=c++;0===Q&&(Q=i);let u=a.get(l);"string"==typeof u&&(u=u.codePointAt(0));if(u&&!(h=u,ra[0][0]<=h&&h<=ra[0][1]||ra[1][0]<=h&&h<=ra[1][1])&&!g.has(Q)){r.set(u,Q);g.add(Q)}s[E]=Q;n[l]=E}var h;return{toFontChar:n,charCodeToGlyphId:s,toUnicodeExtraMap:r,nextAvailableFontCharCode:c}}function createCmapTable(e,t,i){const a=function getRanges(e,t,i){const a=[];for(const t in e)e[t]>=i||a.push({fontCharCode:0|t,glyphId:e[t]});if(t)for(const[e,s]of t)s>=i||a.push({fontCharCode:e,glyphId:s});0===a.length&&a.push({fontCharCode:0,glyphId:0});a.sort((function fontGetRangesSort(e,t){return e.fontCharCode-t.fontCharCode}));const s=[],r=a.length;for(let e=0;e65535?2:1;let r,n,g,o,c="\0\0"+string16(s)+"\0\0"+string32(4+8*s);for(r=a.length-1;r>=0&&!(a[r][0]<=65535);--r);const C=r+1;a[r][0]<65535&&65535===a[r][1]&&(a[r][1]=65534);const h=a[r][1]<65535?1:0,l=C+h,Q=OpenTypeFileBuilder.getSearchParams(l,2);let E,u,d,f,p="",m="",y="",w="",D="",b=0;for(r=0,n=C;r0){m+="ÿÿ";p+="ÿÿ";y+="\0";w+="\0\0"}const F="\0\0"+string16(2*l)+string16(Q.range)+string16(Q.entry)+string16(Q.rangeShift)+m+"\0\0"+p+y+w+D;let S="",k="";if(s>1){c+="\0\0\n"+string32(4+8*s+4+F.length);S="";for(r=0,n=a.length;re||!g)&&(g=e);o 123 are reserved for internal usage");n|=1<65535&&(o=65535)}else{g=0;o=255}const C=e.bbox||[0,0,0,0],h=i.unitsPerEm||(e.fontMatrix?1/Math.max(...e.fontMatrix.slice(0,4).map(Math.abs)):1e3),l=e.ascentScaled?1:h/na,Q=i.ascent||Math.round(l*(e.ascent||C[3]));let E=i.descent||Math.round(l*(e.descent||C[1]));E>0&&e.descent>0&&C[1]<0&&(E=-E);const u=i.yMax||Q,d=-i.yMin||-E;return"\0$ô\0\0\0Š»\0\0\0ŒŠ»\0\0ß\x001\0\0\0\0"+String.fromCharCode(e.fixedPitch?9:0)+"\0\0\0\0\0\0"+string32(a)+string32(s)+string32(r)+string32(n)+"*21*"+string16(e.italicAngle?1:0)+string16(g||e.firstChar)+string16(o||e.lastChar)+string16(Q)+string16(E)+"\0d"+string16(u)+string16(d)+"\0\0\0\0\0\0\0\0"+string16(e.xHeight)+string16(e.capHeight)+string16(0)+string16(g||e.firstChar)+"\0"}function createPostTable(e){return"\0\0\0"+string32(Math.floor(65536*e.italicAngle))+"\0\0\0\0"+string32(e.fixedPitch?1:0)+"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"}function createPostscriptName(e){return e.replaceAll(/[^\x21-\x7E]|[[\](){}<>/%]/g,"").slice(0,63)}function createNameTable(e,t){t||(t=[[],[]]);const i=[t[0][0]||"Original licence",t[0][1]||e,t[0][2]||"Unknown",t[0][3]||"uniqueID",t[0][4]||e,t[0][5]||"Version 0.11",t[0][6]||createPostscriptName(e),t[0][7]||"Unknown",t[0][8]||"Unknown",t[0][9]||"Unknown"],a=[];let s,r,n,g,o;for(s=0,r=i.length;s0;if((n||g)&&"CIDFontType2"===i&&this.cidEncoding.startsWith("Identity-")){const i=e.cidToGidMap,a=[];applyStandardFontGlyphMap(a,Oi());/Arial-?Black/i.test(t)?applyStandardFontGlyphMap(a,Pi()):/Calibri/i.test(t)&&applyStandardFontGlyphMap(a,Wi());if(i){for(const e in a){const t=a[e];void 0!==i[t]&&(a[+e]=i[t])}i.length!==this.toUnicode.length&&e.hasIncludedToUnicodeMap&&this.toUnicode instanceof IdentityToUnicodeMap&&this.toUnicode.forEach((function(e,t){const s=a[e];void 0===i[s]&&(a[+e]=t)}))}this.toUnicode instanceof IdentityToUnicodeMap||this.toUnicode.forEach((function(e,t){a[+e]=t}));this.toFontChar=a;this.toUnicode=new ToUnicodeMap(a)}else if(/Symbol/i.test(a))this.toFontChar=buildToFontChar(Bi,wi(),this.differences);else if(/Dingbats/i.test(a))this.toFontChar=buildToFontChar(Qi,Di(),this.differences);else if(n||g){const e=buildToFontChar(this.defaultEncoding,wi(),this.differences);"CIDFontType2"!==i||this.cidEncoding.startsWith("Identity-")||this.toUnicode instanceof IdentityToUnicodeMap||this.toUnicode.forEach((function(t,i){e[+t]=i}));this.toFontChar=e}else{const e=wi(),i=[];this.toUnicode.forEach(((t,a)=>{if(!this.composite){const i=getUnicodeForGlyph(this.differences[t]||this.defaultEncoding[t],e);-1!==i&&(a=i)}i[+t]=a}));this.composite&&this.toUnicode instanceof IdentityToUnicodeMap&&/Tahoma|Verdana/i.test(t)&&applyStandardFontGlyphMap(i,Oi());this.toFontChar=i}amendFallbackToUnicode(e);this.loadedName=a.split("-",1)[0]}checkAndRepair(e,t,i){const a=["OS/2","cmap","head","hhea","hmtx","maxp","name","post","loca","glyf","fpgm","prep","cvt ","CFF "];function readTables(e,t){const i=Object.create(null);i["OS/2"]=null;i.cmap=null;i.head=null;i.hhea=null;i.hmtx=null;i.maxp=null;i.name=null;i.post=null;for(let s=0;s>>0,a=e.getInt32()>>>0,s=e.getInt32()>>>0,r=e.pos;e.pos=e.start||0;e.skip(a);const n=e.getBytes(s);e.pos=r;if("head"===t){n[8]=n[9]=n[10]=n[11]=0;n[17]|=32}return{tag:t,checksum:i,length:s,offset:a,data:n}}function readOpenTypeHeader(e){return{version:e.getString(4),numTables:e.getUint16(),searchRange:e.getUint16(),entrySelector:e.getUint16(),rangeShift:e.getUint16()}}function sanitizeGlyph(e,t,i,a,s,r){const n={length:0,sizeOfInstructions:0};if(t<0||t>=e.length||i>e.length||i-t<=12)return n;const g=e.subarray(t,i),o=signedInt16(g[2],g[3]),c=signedInt16(g[4],g[5]),C=signedInt16(g[6],g[7]),h=signedInt16(g[8],g[9]);if(o>C){writeSignedInt16(g,2,C);writeSignedInt16(g,6,o)}if(c>h){writeSignedInt16(g,4,h);writeSignedInt16(g,8,c)}const l=signedInt16(g[0],g[1]);if(l<0){if(l<-1)return n;a.set(g,s);n.length=g.length;return n}let Q,E=10,u=0;for(Q=0;Qg.length)return n;if(!r&&f>0){a.set(g.subarray(0,d),s);a.set([0,0],s+d);a.set(g.subarray(p,y),s+d+2);y-=f;g.length-y>3&&(y=y+3&-4);n.length=y;return n}if(g.length-y>3){y=y+3&-4;a.set(g.subarray(0,y),s);n.length=y;return n}a.set(g,s);n.length=g.length;return n}function readNameTable(e){const i=(t.start||0)+e.offset;t.pos=i;const a=[[],[]],s=[],r=e.length,n=i+r;if(0!==t.getUint16()||r<6)return[a,s];const g=t.getUint16(),o=t.getUint16();let c,C;for(c=0;cn)continue;t.pos=r;const g=e.name;if(e.encoding){let i="";for(let a=0,s=e.length;a0&&(c+=e-1)}}else{if(d||p){warn("TT: nested FDEFs not allowed");u=!0}d=!0;h=c;n=l.pop();t.functionsDefined[n]={data:o,i:c}}else if(!d&&!p){n=l.at(-1);if(isNaN(n))info("TT: CALL empty stack (or invalid entry).");else{t.functionsUsed[n]=!0;if(n in t.functionsStackDeltas){const e=l.length+t.functionsStackDeltas[n];if(e<0){warn("TT: CALL invalid functions stack delta.");t.hintsValid=!1;return}l.length=e}else if(n in t.functionsDefined&&!E.includes(n)){Q.push({data:o,i:c,stackTop:l.length-1});E.push(n);g=t.functionsDefined[n];if(!g){warn("TT: CALL non-existent function");t.hintsValid=!1;return}o=g.data;c=g.i}}}if(!d&&!p){let t=0;e<=142?t=s[e]:e>=192&&e<=223?t=-1:e>=224&&(t=-2);if(e>=113&&e<=117){a=l.pop();isNaN(a)||(t=2*-a)}for(;t<0&&l.length>0;){l.pop();t++}for(;t>0;){l.push(NaN);t--}}}t.tooComplexToFollowFunctions=u;const m=[o];c>o.length&&m.push(new Uint8Array(c-o.length));if(h>C){warn("TT: complementing a missing function tail");m.push(new Uint8Array([34,45]))}!function foldTTTable(e,t){if(t.length>1){let i,a,s=0;for(i=0,a=t.length;i>>0,r=[];for(let t=0;t>>0);const n={ttcTag:t,majorVersion:i,minorVersion:a,numFonts:s,offsetTable:r};switch(i){case 1:return n;case 2:n.dsigTag=e.getInt32()>>>0;n.dsigLength=e.getInt32()>>>0;n.dsigOffset=e.getInt32()>>>0;return n}throw new FormatError(`Invalid TrueType Collection majorVersion: ${i}.`)}(e),s=t.split("+");let r;for(let n=0;n0||!(i.cMap instanceof IdentityCMap));if("OTTO"===r.version&&!t||!n.head||!n.hhea||!n.maxp||!n.post){o=new Stream(n["CFF "].data);g=new CFFFont(o,i);adjustWidths(i);return this.convert(e,g,i)}delete n.glyf;delete n.loca;delete n.fpgm;delete n.prep;delete n["cvt "];this.isOpenType=!0}if(!n.maxp)throw new FormatError('Required "maxp" table is not found');t.pos=(t.start||0)+n.maxp.offset;let C=t.getInt32();const h=t.getUint16();if(65536!==C&&20480!==C){if(6===n.maxp.length)C=20480;else{if(!(n.maxp.length>=32))throw new FormatError('"maxp" table has a wrong version number');C=65536}!function writeUint32(e,t,i){e[t+3]=255&i;e[t+2]=i>>>8;e[t+1]=i>>>16;e[t]=i>>>24}(n.maxp.data,0,C)}if(i.scaleFactors?.length===h&&c){const{scaleFactors:e}=i,t=int16(n.head.data[50],n.head.data[51]),a=new GlyfTable({glyfTable:n.glyf.data,isGlyphLocationsLong:t,locaTable:n.loca.data,numGlyphs:h});a.scale(e);const{glyf:s,loca:r,isLocationLong:g}=a.write();n.glyf.data=s;n.loca.data=r;if(g!==!!t){n.head.data[50]=0;n.head.data[51]=g?1:0}const o=n.hmtx.data;for(let t=0;t>8&255;o[i+1]=255&a;writeSignedInt16(o,i+2,Math.round(e[t]*signedInt16(o[i+2],o[i+3])))}}let l=h+1,Q=!0;if(l>65535){Q=!1;l=h;warn("Not enough space in glyfs to duplicate first glyph.")}let E=0,u=0;if(C>=65536&&n.maxp.length>=32){t.pos+=8;if(t.getUint16()>2){n.maxp.data[14]=0;n.maxp.data[15]=2}t.pos+=4;E=t.getUint16();t.pos+=4;u=t.getUint16()}n.maxp.data[4]=l>>8;n.maxp.data[5]=255&l;const d=function sanitizeTTPrograms(e,t,i,a){const s={functionsDefined:[],functionsUsed:[],functionsStackDeltas:[],tooComplexToFollowFunctions:!1,hintsValid:!0};e&&sanitizeTTProgram(e,s);t&&sanitizeTTProgram(t,s);e&&function checkInvalidFunctions(e,t){if(!e.tooComplexToFollowFunctions)if(e.functionsDefined.length>t){warn("TT: more functions defined than expected");e.hintsValid=!1}else for(let i=0,a=e.functionsUsed.length;it){warn("TT: invalid function id: "+i);e.hintsValid=!1;return}if(e.functionsUsed[i]&&!e.functionsDefined[i]){warn("TT: undefined function: "+i);e.hintsValid=!1;return}}}(s,a);if(i&&1&i.length){const e=new Uint8Array(i.length+1);e.set(i.data);i.data=e}return s.hintsValid}(n.fpgm,n.prep,n["cvt "],E);if(!d){delete n.fpgm;delete n.prep;delete n["cvt "]}!function sanitizeMetrics(e,t,i,a,s,r){if(!t){i&&(i.data=null);return}e.pos=(e.start||0)+t.offset;e.pos+=4;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;const n=e.getUint16();e.pos+=8;e.pos+=2;let g=e.getUint16();if(0!==n){if(!(2&int16(a.data[44],a.data[45]))){t.data[22]=0;t.data[23]=0}}if(g>s){info(`The numOfMetrics (${g}) should not be greater than the numGlyphs (${s}).`);g=s;t.data[34]=(65280&g)>>8;t.data[35]=255&g}const o=s-g-(i.length-4*g>>1);if(o>0){const e=new Uint8Array(i.length+2*o);e.set(i.data);if(r){e[i.length]=i.data[2];e[i.length+1]=i.data[3]}i.data=e}}(t,n.hhea,n.hmtx,n.head,l,Q);if(!n.head)throw new FormatError('Required "head" table is not found');!function sanitizeHead(e,t,i){const a=e.data,s=function int32(e,t,i,a){return(e<<24)+(t<<16)+(i<<8)+a}(a[0],a[1],a[2],a[3]);if(s>>16!=1){info("Attempting to fix invalid version in head table: "+s);a[0]=0;a[1]=1;a[2]=0;a[3]=0}const r=int16(a[50],a[51]);if(r<0||r>1){info("Attempting to fix invalid indexToLocFormat in head table: "+r);const e=t+1;if(i===e<<1){a[50]=0;a[51]=0}else{if(i!==e<<2)throw new FormatError("Could not fix indexToLocFormat: "+r);a[50]=0;a[51]=1}}}(n.head,h,c?n.loca.length:0);let f=Object.create(null);if(c){const e=int16(n.head.data[50],n.head.data[51]),t=function sanitizeGlyphLocations(e,t,i,a,s,r,n){let g,o,c;if(a){g=4;o=function fontItemDecodeLong(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]};c=function fontItemEncodeLong(e,t,i){e[t]=i>>>24&255;e[t+1]=i>>16&255;e[t+2]=i>>8&255;e[t+3]=255&i}}else{g=2;o=function fontItemDecode(e,t){return e[t]<<9|e[t+1]<<1};c=function fontItemEncode(e,t,i){e[t]=i>>9&255;e[t+1]=i>>1&255}}const C=r?i+1:i,h=g*(1+C),l=new Uint8Array(h);l.set(e.data.subarray(0,h));e.data=l;const Q=t.data,E=Q.length,u=new Uint8Array(E);let d,f;const p=[];for(d=0,f=0;dE&&(e=E);p.push({index:d,offset:e,endOffset:0})}p.sort(((e,t)=>e.offset-t.offset));for(d=0;de.index-t.index));for(d=0;dn&&(n=e.sizeOfInstructions);w+=t;c(l,f,w)}if(0===w){const e=new Uint8Array([0,1,0,0,0,0,0,0,0,0,0,0,0,0,49,0]);for(d=0,f=g;di+w)t.data=u.subarray(0,i+w);else{t.data=new Uint8Array(i+w);t.data.set(u.subarray(0,w))}t.data.set(u.subarray(0,i),w);c(e.data,l.length-g,w+i)}else t.data=u.subarray(0,w);return{missingGlyphs:y,maxSizeOfInstructions:n}}(n.loca,n.glyf,h,e,d,Q,u);f=t.missingGlyphs;if(C>=65536&&n.maxp.length>=32){n.maxp.data[26]=t.maxSizeOfInstructions>>8;n.maxp.data[27]=255&t.maxSizeOfInstructions}}if(!n.hhea)throw new FormatError('Required "hhea" table is not found');if(0===n.hhea.data[10]&&0===n.hhea.data[11]){n.hhea.data[10]=255;n.hhea.data[11]=255}const p={unitsPerEm:int16(n.head.data[18],n.head.data[19]),yMax:signedInt16(n.head.data[42],n.head.data[43]),yMin:signedInt16(n.head.data[38],n.head.data[39]),ascent:signedInt16(n.hhea.data[4],n.hhea.data[5]),descent:signedInt16(n.hhea.data[6],n.hhea.data[7]),lineGap:signedInt16(n.hhea.data[8],n.hhea.data[9])};this.ascent=p.ascent/p.unitsPerEm;this.descent=p.descent/p.unitsPerEm;this.lineGap=p.lineGap/p.unitsPerEm;if(this.cssFontInfo?.lineHeight){this.lineHeight=this.cssFontInfo.metrics.lineHeight;this.lineGap=this.cssFontInfo.metrics.lineGap}else this.lineHeight=this.ascent-this.descent+this.lineGap;n.post&&function readPostScriptTable(e,i,a){const s=(t.start||0)+e.offset;t.pos=s;const r=s+e.length,n=t.getInt32();t.skip(28);let g,o,c=!0;switch(n){case 65536:g=Hi;break;case 131072:const e=t.getUint16();if(e!==a){c=!1;break}const s=[];for(o=0;o=32768){c=!1;break}s.push(e)}if(!c)break;const C=[],h=[];for(;t.pos65535)throw new FormatError("Max size of CID is 65,535");let s=-1;t?s=a:void 0!==e[a]&&(s=e[a]);s>=0&&s>>0;let C=!1;if(g?.platformId!==s||g?.encodingId!==r){if(0!==s||0!==r&&1!==r&&3!==r)if(1===s&&0===r)C=!0;else if(3!==s||1!==r||!a&&g){if(i&&3===s&&0===r){C=!0;let i=!0;if(e>3;e.push(a);i=Math.max(a,i)}const a=[];for(let e=0;e<=i;e++)a.push({firstCode:t.getUint16(),entryCount:t.getUint16(),idDelta:signedInt16(t.getByte(),t.getByte()),idRangePos:t.pos+t.getUint16()});for(let i=0;i<256;i++)if(0===e[i]){t.pos=a[0].idRangePos+2*i;Q=t.getUint16();h.push({charCode:i,glyphId:Q})}else{const s=a[e[i]];for(l=0;l>1;t.skip(6);const i=[];let a;for(a=0;a>1)-(e-a);s.offsetIndex=n;g=Math.max(g,n+s.end-s.start+1)}else s.offsetIndex=-1}const o=[];for(l=0;l>>0;for(l=0;l>>0,i=t.getInt32()>>>0;let a=t.getInt32()>>>0;for(let t=e;t<=i;t++)h.push({charCode:t,glyphId:a++})}}}h.sort((function(e,t){return e.charCode-t.charCode}));for(let e=1;e=61440&&t<=61695&&(t&=255);m[t]=e.glyphId}else for(const e of r)m[e.charCode]=e.glyphId;if(i.glyphNames&&(g.length||this.differences.length))for(let e=0;e<256;++e){if(!o&&void 0!==m[e])continue;const t=this.differences[e]||g[e];if(!t)continue;const a=i.glyphNames.indexOf(t);a>0&&hasGlyph(a)&&(m[e]=a)}}0===m.length&&(m[0]=0);let y=l-1;Q||(y=0);if(!i.cssFontInfo){const e=adjustMapping(m,hasGlyph,y,this.toUnicode);this.toFontChar=e.toFontChar;n.cmap={tag:"cmap",data:createCmapTable(e.charCodeToGlyphId,e.toUnicodeExtraMap,l)};n["OS/2"]&&function validateOS2Table(e,t){t.pos=(t.start||0)+e.offset;const i=t.getUint16();t.skip(60);const a=t.getUint16();if(i<4&&768&a)return!1;if(t.getUint16()>t.getUint16())return!1;t.skip(6);if(0===t.getUint16())return!1;e.data[8]=e.data[9]=0;return!0}(n["OS/2"],t)||(n["OS/2"]={tag:"OS/2",data:createOS2Table(i,e.charCodeToGlyphId,p)})}if(!c)try{o=new Stream(n["CFF "].data);g=new CFFParser(o,i,Ri).parse();g.duplicateFirstGlyph();const e=new CFFCompiler(g);n["CFF "].data=e.compile()}catch{warn("Failed to compile font "+i.loadedName)}if(n.name){const[t,a]=readNameTable(n.name);n.name.data=createNameTable(e,t);this.psName=t[0][6]||null;i.composite||function adjustTrueTypeToUnicode(e,t,i){if(e.isInternalFont)return;if(e.hasIncludedToUnicodeMap)return;if(e.hasEncoding)return;if(e.toUnicode instanceof IdentityToUnicodeMap)return;if(!t)return;if(0===i.length)return;if(e.defaultEncoding===li)return;for(const e of i)if(!isWinNameRecord(e))return;const a=li,s=[],r=wi();for(const e in a){const t=a[e];if(""===t)continue;const i=r[t];void 0!==i&&(s[e]=String.fromCharCode(i))}s.length>0&&e.toUnicode.amend(s)}(i,this.isSymbolicFont,a)}else n.name={tag:"name",data:createNameTable(this.name)};const w=new OpenTypeFileBuilder(r.version);for(const e in n)w.addTable(e,n[e].data);return w.toArray()}convert(e,t,i){i.fixedPitch=!1;i.builtInEncoding&&function adjustType1ToUnicode(e,t){if(e.isInternalFont)return;if(e.hasIncludedToUnicodeMap)return;if(t===e.defaultEncoding)return;if(e.toUnicode instanceof IdentityToUnicodeMap)return;const i=[],a=wi();for(const s in t){if(e.hasEncoding&&(e.baseEncodingName||void 0!==e.differences[s]))continue;const r=getUnicodeForGlyph(t[s],a);-1!==r&&(i[s]=String.fromCharCode(r))}i.length>0&&e.toUnicode.amend(i)}(i,i.builtInEncoding);let s=1;t instanceof CFFFont&&(s=t.numGlyphs-1);const r=t.getGlyphMapping(i);let n=null,g=r,o=null;if(!i.cssFontInfo){n=adjustMapping(r,t.hasGlyphId.bind(t),s,this.toUnicode);this.toFontChar=n.toFontChar;g=n.charCodeToGlyphId;o=n.toUnicodeExtraMap}const c=t.numGlyphs;function getCharCodes(e,t){let i=null;for(const a in e)t===e[a]&&(i||=[]).push(0|a);return i}function createCharCode(e,t){for(const i in e)if(t===e[i])return 0|i;n.charCodeToGlyphId[n.nextAvailableFontCharCode]=t;return n.nextAvailableFontCharCode++}const C=t.seacs;if(n&&C?.length){const e=i.fontMatrix||a,s=t.getCharset(),g=Object.create(null);for(let t in C){t|=0;const i=C[t],a=hi[i[2]],o=hi[i[3]],c=s.indexOf(a),h=s.indexOf(o);if(c<0||h<0)continue;const l={x:i[0]*e[0]+i[1]*e[2]+e[4],y:i[0]*e[1]+i[1]*e[3]+e[5]},Q=getCharCodes(r,t);if(Q)for(const e of Q){const t=n.charCodeToGlyphId,i=createCharCode(t,c),a=createCharCode(t,h);g[e]={baseFontCharCode:i,accentFontCharCode:a,accentOffset:l}}}i.seacMap=g}const h=i.fontMatrix?1/Math.max(...i.fontMatrix.slice(0,4).map(Math.abs)):1e3,l=new OpenTypeFileBuilder("OTTO");l.addTable("CFF ",t.data);l.addTable("OS/2",createOS2Table(i,g));l.addTable("cmap",createCmapTable(g,o,c));l.addTable("head","\0\0\0\0\0\0\0\0\0\0_<õ\0\0"+safeString16(h)+"\0\0\0\0ž\v~'\0\0\0\0ž\v~'\0\0"+safeString16(i.descent)+"ÿ"+safeString16(i.ascent)+string16(i.italicAngle?2:0)+"\0\0\0\0\0\0\0");l.addTable("hhea","\0\0\0"+safeString16(i.ascent)+safeString16(i.descent)+"\0\0ÿÿ\0\0\0\0\0\0"+safeString16(i.capHeight)+safeString16(Math.tan(i.italicAngle)*i.xHeight)+"\0\0\0\0\0\0\0\0\0\0\0\0"+string16(c));l.addTable("hmtx",function fontFieldsHmtx(){const e=t.charstrings,i=t.cff?t.cff.widths:null;let a="\0\0\0\0";for(let t=1,s=c;t=65520&&e<=65535?0:e>=62976&&e<=63743?bi()[e]||e:173===e?45:e}(i)}this.isType3Font&&(s=i);let C=null;if(this.seacMap?.[e]){c=!0;const t=this.seacMap[e];i=t.baseFontCharCode;C={fontChar:String.fromCodePoint(t.accentFontCharCode),offset:t.accentOffset}}let h="";"number"==typeof i&&(i<=1114111?h=String.fromCodePoint(i):warn(`charToGlyph - invalid fontCharCode: ${i}`));if(this.missingFile&&this.vertical&&1===h.length){const e=Ji()[h.charCodeAt(0)];e&&(h=o=String.fromCharCode(e))}r=new fonts_Glyph(e,h,o,C,a,g,s,t,c);return this._glyphCache[e]=r}charsToGlyphs(e){let t=this._charsCache[e];if(t)return t;t=[];if(this.cMap){const i=Object.create(null),a=e.length;let s=0;for(;st.length%2==1,a=this.toUnicode instanceof IdentityToUnicodeMap?e=>this.toUnicode.charCodeOf(e):e=>this.toUnicode.charCodeOf(String.fromCodePoint(e));for(let s=0,r=e.length;s55295&&(r<57344||r>65533)&&s++;if(this.toUnicode){const e=a(r);if(-1!==e){if(hasCurrentBufErrors()){t.push(i.join(""));i.length=0}for(let t=(this.cMap?this.cMap.getCharCodeLength(e):1)-1;t>=0;t--)i.push(String.fromCharCode(e>>8*t&255));continue}}if(!hasCurrentBufErrors()){t.push(i.join(""));i.length=0}i.push(String.fromCodePoint(r))}t.push(i.join(""));return t}}class ErrorFont{constructor(e){this.error=e;this.loadedName="g_font_error";this.missingFile=!0}charsToGlyphs(){return[]}encodeString(e){return[e]}exportData(e=!1){return{error:this.error}}}const Ia=2,ca=3,Ca=4,ha=5,la=6,Ba=7;class Pattern{constructor(){unreachable("Cannot initialize Pattern.")}static parseShading(e,t,i,a,s){const r=e instanceof BaseStream?e.dict:e,n=r.get("ShadingType");try{switch(n){case Ia:case ca:return new RadialAxialShading(r,t,i,a,s);case Ca:case ha:case la:case Ba:return new MeshShading(e,t,i,a,s);default:throw new FormatError("Unsupported ShadingType: "+n)}}catch(e){if(e instanceof MissingDataException)throw e;warn(e);return new DummyShading}}}class BaseShading{static SMALL_NUMBER=1e-6;getIR(){unreachable("Abstract method `getIR` called.")}}class RadialAxialShading extends BaseShading{constructor(e,t,i,a,s){super();this.shadingType=e.get("ShadingType");let r=0;this.shadingType===Ia?r=4:this.shadingType===ca&&(r=6);this.coordsArr=e.getArray("Coords");if(!isNumberArray(this.coordsArr,r))throw new FormatError("RadialAxialShading: Invalid /Coords array.");const n=ColorSpace.parse({cs:e.getRaw("CS")||e.getRaw("ColorSpace"),xref:t,resources:i,pdfFunctionFactory:a,localColorSpaceCache:s});this.bbox=lookupNormalRect(e.getArray("BBox"),null);let g=0,o=1;const c=e.getArray("Domain");isNumberArray(c,2)&&([g,o]=c);let C=!1,h=!1;const l=e.getArray("Extend");(function isBooleanArray(e,t){return Array.isArray(e)&&(null===t||e.length===t)&&e.every((e=>"boolean"==typeof e))})(l,2)&&([C,h]=l);if(!(this.shadingType!==ca||C&&h)){const[e,t,i,a,s,r]=this.coordsArr,n=Math.hypot(e-a,t-s);i<=r+n&&r<=i+n&&warn("Unsupported radial gradient.")}this.extendStart=C;this.extendEnd=h;const Q=e.getRaw("Function"),E=a.createFromArray(Q),u=(o-g)/840,d=this.colorStops=[];if(g>=o||u<=0){info("Bad shading domain.");return}const f=new Float32Array(n.numComps),p=new Float32Array(1);let m,y=0;p[0]=g;E(p,0,f,0);let w=n.getRgb(f,0);const D=Util.makeHexColor(w[0],w[1],w[2]);d.push([0,D]);let b=1;p[0]=g+u;E(p,0,f,0);let F=n.getRgb(f,0),S=F[0]-w[0]+1,k=F[1]-w[1]+1,R=F[2]-w[2]+1,N=F[0]-w[0]-1,G=F[1]-w[1]-1,M=F[2]-w[2]-1;for(let e=2;e<840;e++){p[0]=g+e*u;E(p,0,f,0);m=n.getRgb(f,0);const t=e-y;S=Math.min(S,(m[0]-w[0]+1)/t);k=Math.min(k,(m[1]-w[1]+1)/t);R=Math.min(R,(m[2]-w[2]+1)/t);N=Math.max(N,(m[0]-w[0]-1)/t);G=Math.max(G,(m[1]-w[1]-1)/t);M=Math.max(M,(m[2]-w[2]-1)/t);if(!(N<=S&&G<=k&&M<=R)){const e=Util.makeHexColor(F[0],F[1],F[2]);d.push([b/840,e]);S=m[0]-F[0]+1;k=m[1]-F[1]+1;R=m[2]-F[2]+1;N=m[0]-F[0]-1;G=m[1]-F[1]-1;M=m[2]-F[2]-1;y=b;w=F}b=e;F=m}const U=Util.makeHexColor(F[0],F[1],F[2]);d.push([1,U]);let x="transparent";if(e.has("Background")){m=n.getRgb(e.get("Background"),0);x=Util.makeHexColor(m[0],m[1],m[2])}if(!C){d.unshift([0,x]);d[1][0]+=BaseShading.SMALL_NUMBER}if(!h){d.at(-1)[0]-=BaseShading.SMALL_NUMBER;d.push([1,x])}this.colorStops=d}getIR(){const{coordsArr:e,shadingType:t}=this;let i,a,s,r,n;if(t===Ia){a=[e[0],e[1]];s=[e[2],e[3]];r=null;n=null;i="axial"}else if(t===ca){a=[e[0],e[1]];s=[e[3],e[4]];r=e[2];n=e[5];i="radial"}else unreachable(`getPattern type unknown: ${t}`);return["RadialAxial",i,this.bbox,this.colorStops,a,s,r,n]}}class MeshStreamReader{constructor(e,t){this.stream=e;this.context=t;this.buffer=0;this.bufferLength=0;const i=t.numComps;this.tmpCompsBuf=new Float32Array(i);const a=t.colorSpace.numComps;this.tmpCsCompsBuf=t.colorFn?new Float32Array(a):this.tmpCompsBuf}get hasData(){if(this.stream.end)return this.stream.pos0)return!0;const e=this.stream.getByte();if(e<0)return!1;this.buffer=e;this.bufferLength=8;return!0}readBits(e){let t=this.buffer,i=this.bufferLength;if(32===e){if(0===i)return(this.stream.getByte()<<24|this.stream.getByte()<<16|this.stream.getByte()<<8|this.stream.getByte())>>>0;t=t<<24|this.stream.getByte()<<16|this.stream.getByte()<<8|this.stream.getByte();const e=this.stream.getByte();this.buffer=e&(1<>i)>>>0}if(8===e&&0===i)return this.stream.getByte();for(;i>i}align(){this.buffer=0;this.bufferLength=0}readFlag(){return this.readBits(this.context.bitsPerFlag)}readCoordinate(){const e=this.context.bitsPerCoordinate,t=this.readBits(e),i=this.readBits(e),a=this.context.decode,s=e<32?1/((1<r?r:e;t=t>n?n:t;i=ie*s[t])):i;let n,g=-2;const o=[];for(const[e,t]of a.map(((e,t)=>[e,t])).sort((([e],[t])=>e-t)))if(-1!==e)if(e===g+1){n.push(r[t]);g+=1}else{g=e;n=[r[t]];o.push(e,n)}return o}(e),i=new Dict(null);i.set("BaseFont",Name.get(e));i.set("Type",Name.get("Font"));i.set("Subtype",Name.get("CIDFontType2"));i.set("Encoding",Name.get("Identity-H"));i.set("CIDToGIDMap",Name.get("Identity"));i.set("W",t);i.set("FirstChar",t[0]);i.set("LastChar",t.at(-2)+t.at(-1).length-1);const a=new Dict(null);i.set("FontDescriptor",a);const s=new Dict(null);s.set("Ordering","Identity");s.set("Registry","Adobe");s.set("Supplement",0);i.set("CIDSystemInfo",s);return i}class PostScriptParser{constructor(e){this.lexer=e;this.operators=[];this.token=null;this.prev=null}nextToken(){this.prev=this.token;this.token=this.lexer.getToken()}accept(e){if(this.token.type===e){this.nextToken();return!0}return!1}expect(e){if(this.accept(e))return!0;throw new FormatError(`Unexpected symbol: found ${this.token.type} expected ${e}.`)}parse(){this.nextToken();this.expect(as.LBRACE);this.parseBlock();this.expect(as.RBRACE);return this.operators}parseBlock(){for(;;)if(this.accept(as.NUMBER))this.operators.push(this.prev.value);else if(this.accept(as.OPERATOR))this.operators.push(this.prev.value);else{if(!this.accept(as.LBRACE))return;this.parseCondition()}}parseCondition(){const e=this.operators.length;this.operators.push(null,null);this.parseBlock();this.expect(as.RBRACE);if(this.accept(as.IF)){this.operators[e]=this.operators.length;this.operators[e+1]="jz"}else{if(!this.accept(as.LBRACE))throw new FormatError("PS Function: error parsing conditional.");{const t=this.operators.length;this.operators.push(null,null);const i=this.operators.length;this.parseBlock();this.expect(as.RBRACE);this.expect(as.IFELSE);this.operators[t]=this.operators.length;this.operators[t+1]="j";this.operators[e]=i;this.operators[e+1]="jz"}}}}const as={LBRACE:0,RBRACE:1,NUMBER:2,OPERATOR:3,IF:4,IFELSE:5};class PostScriptToken{static get opCache(){return shadow(this,"opCache",Object.create(null))}constructor(e,t){this.type=e;this.value=t}static getOperator(e){return PostScriptToken.opCache[e]||=new PostScriptToken(as.OPERATOR,e)}static get LBRACE(){return shadow(this,"LBRACE",new PostScriptToken(as.LBRACE,"{"))}static get RBRACE(){return shadow(this,"RBRACE",new PostScriptToken(as.RBRACE,"}"))}static get IF(){return shadow(this,"IF",new PostScriptToken(as.IF,"IF"))}static get IFELSE(){return shadow(this,"IFELSE",new PostScriptToken(as.IFELSE,"IFELSE"))}}class PostScriptLexer{constructor(e){this.stream=e;this.nextChar();this.strBuf=[]}nextChar(){return this.currentChar=this.stream.getByte()}getToken(){let e=!1,t=this.currentChar;for(;;){if(t<0)return Bt;if(e)10!==t&&13!==t||(e=!1);else if(37===t)e=!0;else if(!isWhiteSpace(t))break;t=this.nextChar()}switch(0|t){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 43:case 45:case 46:return new PostScriptToken(as.NUMBER,this.getNumber());case 123:this.nextChar();return PostScriptToken.LBRACE;case 125:this.nextChar();return PostScriptToken.RBRACE}const i=this.strBuf;i.length=0;i[0]=String.fromCharCode(t);for(;(t=this.nextChar())>=0&&(t>=65&&t<=90||t>=97&&t<=122);)i.push(String.fromCharCode(t));const a=i.join("");switch(a.toLowerCase()){case"if":return PostScriptToken.IF;case"ifelse":return PostScriptToken.IFELSE;default:return PostScriptToken.getOperator(a)}}getNumber(){let e=this.currentChar;const t=this.strBuf;t.length=0;t[0]=String.fromCharCode(e);for(;(e=this.nextChar())>=0&&(e>=48&&e<=57||45===e||46===e);)t.push(String.fromCharCode(e));const i=parseFloat(t.join(""));if(isNaN(i))throw new FormatError(`Invalid floating point number: ${i}`);return i}}class BaseLocalCache{constructor(e){this._onlyRefs=!0===e?.onlyRefs;if(!this._onlyRefs){this._nameRefMap=new Map;this._imageMap=new Map}this._imageCache=new RefSetCache}getByName(e){this._onlyRefs&&unreachable("Should not call `getByName` method.");const t=this._nameRefMap.get(e);return t?this.getByRef(t):this._imageMap.get(e)||null}getByRef(e){return this._imageCache.get(e)||null}set(e,t,i){unreachable("Abstract method `set` called.")}}class LocalImageCache extends BaseLocalCache{set(e,t=null,i){if("string"!=typeof e)throw new Error('LocalImageCache.set - expected "name" argument.');if(t){if(this._imageCache.has(t))return;this._nameRefMap.set(e,t);this._imageCache.put(t,i)}else this._imageMap.has(e)||this._imageMap.set(e,i)}}class LocalColorSpaceCache extends BaseLocalCache{set(e=null,t=null,i){if("string"!=typeof e&&!t)throw new Error('LocalColorSpaceCache.set - expected "name" and/or "ref" argument.');if(t){if(this._imageCache.has(t))return;null!==e&&this._nameRefMap.set(e,t);this._imageCache.put(t,i)}else this._imageMap.has(e)||this._imageMap.set(e,i)}}class LocalFunctionCache extends BaseLocalCache{constructor(e){super({onlyRefs:!0})}set(e=null,t,i){if(!t)throw new Error('LocalFunctionCache.set - expected "ref" argument.');this._imageCache.has(t)||this._imageCache.put(t,i)}}class LocalGStateCache extends BaseLocalCache{set(e,t=null,i){if("string"!=typeof e)throw new Error('LocalGStateCache.set - expected "name" argument.');if(t){if(this._imageCache.has(t))return;this._nameRefMap.set(e,t);this._imageCache.put(t,i)}else this._imageMap.has(e)||this._imageMap.set(e,i)}}class LocalTilingPatternCache extends BaseLocalCache{constructor(e){super({onlyRefs:!0})}set(e=null,t,i){if(!t)throw new Error('LocalTilingPatternCache.set - expected "ref" argument.');this._imageCache.has(t)||this._imageCache.put(t,i)}}class RegionalImageCache extends BaseLocalCache{constructor(e){super({onlyRefs:!0})}set(e=null,t,i){if(!t)throw new Error('RegionalImageCache.set - expected "ref" argument.');this._imageCache.has(t)||this._imageCache.put(t,i)}}class GlobalImageCache{static NUM_PAGES_THRESHOLD=2;static MIN_IMAGES_TO_CACHE=10;static MAX_BYTE_SIZE=5e7;#F=new RefSet;constructor(){this._refCache=new RefSetCache;this._imageCache=new RefSetCache}get#S(){let e=0;for(const t of this._imageCache)e+=t.byteSize;return e}get#k(){return!(this._imageCache.size+e)):null}class PDFFunction{static getSampleArray(e,t,i,a){let s,r,n=1;for(s=0,r=e.length;s>o)*C;c&=(1<i?e=i:e0&&(l=r[h-1]);let Q=a[1];h>1,c=s.length>>1,C=new PostScriptEvaluator(g),h=Object.create(null);let l=8192;const Q=new Float32Array(c);return function constructPostScriptFn(e,t,i,a){let s,n,g="";const E=Q;for(s=0;se&&(n=e)}d[s]=n}if(l>0){l--;h[g]=d}i.set(d,a)}}}function isPDFFunction(e){let t;if(e instanceof Dict)t=e;else{if(!(e instanceof BaseStream))return!1;t=e.dict}return t.has("FunctionType")}class PostScriptStack{static MAX_STACK_SIZE=100;constructor(e){this.stack=e?Array.from(e):[]}push(e){if(this.stack.length>=PostScriptStack.MAX_STACK_SIZE)throw new Error("PostScript function stack overflow.");this.stack.push(e)}pop(){if(this.stack.length<=0)throw new Error("PostScript function stack underflow.");return this.stack.pop()}copy(e){if(this.stack.length+e>=PostScriptStack.MAX_STACK_SIZE)throw new Error("PostScript function stack overflow.");const t=this.stack;for(let i=t.length-e,a=e-1;a>=0;a--,i++)t.push(t[i])}index(e){this.push(this.stack[this.stack.length-e-1])}roll(e,t){const i=this.stack,a=i.length-e,s=i.length-1,r=a+(t-Math.floor(t/e)*e);for(let e=a,t=s;e0?t.push(n<>g);break;case"ceiling":n=t.pop();t.push(Math.ceil(n));break;case"copy":n=t.pop();t.copy(n);break;case"cos":n=t.pop();t.push(Math.cos(n%360/180*Math.PI));break;case"cvi":n=0|t.pop();t.push(n);break;case"cvr":break;case"div":g=t.pop();n=t.pop();t.push(n/g);break;case"dup":t.copy(1);break;case"eq":g=t.pop();n=t.pop();t.push(n===g);break;case"exch":t.roll(2,1);break;case"exp":g=t.pop();n=t.pop();t.push(n**g);break;case"false":t.push(!1);break;case"floor":n=t.pop();t.push(Math.floor(n));break;case"ge":g=t.pop();n=t.pop();t.push(n>=g);break;case"gt":g=t.pop();n=t.pop();t.push(n>g);break;case"idiv":g=t.pop();n=t.pop();t.push(n/g|0);break;case"index":n=t.pop();t.index(n);break;case"le":g=t.pop();n=t.pop();t.push(n<=g);break;case"ln":n=t.pop();t.push(Math.log(n));break;case"log":n=t.pop();t.push(Math.log10(n));break;case"lt":g=t.pop();n=t.pop();t.push(n=t?new AstLiteral(t):e.max<=t?e:new AstMin(e,t)}class PostScriptCompiler{compile(e,t,i){const a=[],s=[],r=t.length>>1,n=i.length>>1;let g,o,c,C,h,l,Q,E,u=0;for(let e=0;et.min){g.unshift("Math.max(",r,", ");g.push(")")}if(n4){a=!0;t=0}else{a=!1;t=1}const o=[];for(r=0;r=0&&"ET"===gs[e];--e)gs[e]="EN";for(let e=r+1;e0&&(t=gs[r-1]);let i=h;e+1E&&isOdd(E)&&(d=E)}for(E=u;E>=d;--E){let e=-1;for(r=0,n=o.length;r=0){reverseValues(ns,e,r);e=-1}}else e<0&&(e=r);e>=0&&reverseValues(ns,e,o.length)}for(r=0,n=ns.length;r"!==e||(ns[r]="")}return createBidiText(ns.join(""),a)}const os={style:"normal",weight:"normal"},Is={style:"normal",weight:"bold"},cs={style:"italic",weight:"normal"},Cs={style:"italic",weight:"bold"},hs=new Map([["Times-Roman",{local:["Times New Roman","Times-Roman","Times","Liberation Serif","Nimbus Roman","Nimbus Roman L","Tinos","Thorndale","TeX Gyre Termes","FreeSerif","Linux Libertine O","Libertinus Serif","DejaVu Serif","Bitstream Vera Serif","Ubuntu"],style:os,ultimate:"serif"}],["Times-Bold",{alias:"Times-Roman",style:Is,ultimate:"serif"}],["Times-Italic",{alias:"Times-Roman",style:cs,ultimate:"serif"}],["Times-BoldItalic",{alias:"Times-Roman",style:Cs,ultimate:"serif"}],["Helvetica",{local:["Helvetica","Helvetica Neue","Arial","Arial Nova","Liberation Sans","Arimo","Nimbus Sans","Nimbus Sans L","A030","TeX Gyre Heros","FreeSans","DejaVu Sans","Albany","Bitstream Vera Sans","Arial Unicode MS","Microsoft Sans Serif","Apple Symbols","Cantarell"],path:"LiberationSans-Regular.ttf",style:os,ultimate:"sans-serif"}],["Helvetica-Bold",{alias:"Helvetica",path:"LiberationSans-Bold.ttf",style:Is,ultimate:"sans-serif"}],["Helvetica-Oblique",{alias:"Helvetica",path:"LiberationSans-Italic.ttf",style:cs,ultimate:"sans-serif"}],["Helvetica-BoldOblique",{alias:"Helvetica",path:"LiberationSans-BoldItalic.ttf",style:Cs,ultimate:"sans-serif"}],["Courier",{local:["Courier","Courier New","Liberation Mono","Nimbus Mono","Nimbus Mono L","Cousine","Cumberland","TeX Gyre Cursor","FreeMono","Linux Libertine Mono O","Libertinus Mono"],style:os,ultimate:"monospace"}],["Courier-Bold",{alias:"Courier",style:Is,ultimate:"monospace"}],["Courier-Oblique",{alias:"Courier",style:cs,ultimate:"monospace"}],["Courier-BoldOblique",{alias:"Courier",style:Cs,ultimate:"monospace"}],["ArialBlack",{local:["Arial Black"],style:{style:"normal",weight:"900"},fallback:"Helvetica-Bold"}],["ArialBlack-Bold",{alias:"ArialBlack"}],["ArialBlack-Italic",{alias:"ArialBlack",style:{style:"italic",weight:"900"},fallback:"Helvetica-BoldOblique"}],["ArialBlack-BoldItalic",{alias:"ArialBlack-Italic"}],["ArialNarrow",{local:["Arial Narrow","Liberation Sans Narrow","Helvetica Condensed","Nimbus Sans Narrow","TeX Gyre Heros Cn"],style:os,fallback:"Helvetica"}],["ArialNarrow-Bold",{alias:"ArialNarrow",style:Is,fallback:"Helvetica-Bold"}],["ArialNarrow-Italic",{alias:"ArialNarrow",style:cs,fallback:"Helvetica-Oblique"}],["ArialNarrow-BoldItalic",{alias:"ArialNarrow",style:Cs,fallback:"Helvetica-BoldOblique"}],["Calibri",{local:["Calibri","Carlito"],style:os,fallback:"Helvetica"}],["Calibri-Bold",{alias:"Calibri",style:Is,fallback:"Helvetica-Bold"}],["Calibri-Italic",{alias:"Calibri",style:cs,fallback:"Helvetica-Oblique"}],["Calibri-BoldItalic",{alias:"Calibri",style:Cs,fallback:"Helvetica-BoldOblique"}],["Wingdings",{local:["Wingdings","URW Dingbats"],style:os}],["Wingdings-Regular",{alias:"Wingdings"}],["Wingdings-Bold",{alias:"Wingdings"}]]),ls=new Map([["Arial-Black","ArialBlack"]]);function getFamilyName(e){const t=new Set(["thin","extralight","ultralight","demilight","semilight","light","book","regular","normal","medium","demibold","semibold","bold","extrabold","ultrabold","black","heavy","extrablack","ultrablack","roman","italic","oblique","ultracondensed","extracondensed","condensed","semicondensed","normal","semiexpanded","expanded","extraexpanded","ultraexpanded","bolditalic"]);return e.split(/[- ,+]+/g).filter((e=>!t.has(e.toLowerCase()))).join(" ")}function generateFont({alias:e,local:t,path:i,fallback:a,style:s,ultimate:r},n,g,o=!0,c=!0,C=""){const h={style:null,ultimate:null};if(t){const e=C?` ${C}`:"";for(const i of t)n.push(`local(${i}${e})`)}if(e){const t=hs.get(e),r=C||function getStyleToAppend(e){switch(e){case Is:return"Bold";case cs:return"Italic";case Cs:return"Bold Italic";default:if("bold"===e?.weight)return"Bold";if("italic"===e?.style)return"Italic"}return""}(s);Object.assign(h,generateFont(t,n,g,o&&!a,c&&!i,r))}s&&(h.style=s);r&&(h.ultimate=r);if(o&&a){const e=hs.get(a),{ultimate:t}=generateFont(e,n,g,o,c&&!i,C);h.ultimate||=t}c&&i&&g&&n.push(`url(${g}${i})`);return h}function getFontSubstitution(e,t,i,a,s,r){if(a.startsWith("InvalidPDFjsFont_"))return null;"TrueType"!==r&&"Type1"!==r||!/^[A-Z]{6}\+/.test(a)||(a=a.slice(7));const n=a=normalizeFontName(a);let g=e.get(n);if(g)return g;let o=hs.get(a);if(!o)for(const[e,t]of ls)if(a.startsWith(e)){a=`${t}${a.substring(e.length)}`;o=hs.get(a);break}let c=!1;if(!o){o=hs.get(s);c=!0}const C=`${t.getDocId()}_s${t.createFontId()}`;if(!o){if(!validateFontName(a)){warn(`Cannot substitute the font because of its name: ${a}`);e.set(n,null);return null}const t=/bold/gi.test(a),i=/oblique|italic/gi.test(a),s=t&&i&&Cs||t&&Is||i&&cs||os;g={css:`"${getFamilyName(a)}",${C}`,guessFallback:!0,loadedName:C,baseFontName:a,src:`local(${a})`,style:s};e.set(n,g);return g}const h=[];c&&validateFontName(a)&&h.push(`local(${a})`);const{style:l,ultimate:Q}=generateFont(o,h,i),E=null===Q,u=E?"":`,${Q}`;g={css:`"${getFamilyName(a)}",${C}${u}`,guessFallback:E,loadedName:C,baseFontName:a,src:h.join(","),style:l};e.set(n,g);return g}class ImageResizer{static#R=2048;static#y=FeatureTest.isImageDecoderSupported;constructor(e,t){this._imgData=e;this._isMask=t}static get canUseImageDecoder(){return shadow(this,"canUseImageDecoder",this.#y?ImageDecoder.isTypeSupported("image/bmp"):Promise.resolve(!1))}static needsToBeResized(e,t){if(e<=this.#R&&t<=this.#R)return!1;const{MAX_DIM:i}=this;if(e>i||t>i)return!0;const a=e*t;if(this._hasMaxArea)return a>this.MAX_AREA;if(a(this.MAX_AREA=this.#R**2)}static get MAX_DIM(){return shadow(this,"MAX_DIM",this._guessMax(2048,65537,0,1))}static get MAX_AREA(){this._hasMaxArea=!0;return shadow(this,"MAX_AREA",this._guessMax(this.#R,this.MAX_DIM,128,0)**2)}static set MAX_AREA(e){if(e>=0){this._hasMaxArea=!0;shadow(this,"MAX_AREA",e)}}static setOptions({canvasMaxAreaInBytes:e=-1,isImageDecoderSupported:t=!1}){this._hasMaxArea||(this.MAX_AREA=e>>2);this.#y=t}static _areGoodDims(e,t){try{const i=new OffscreenCanvas(e,t),a=i.getContext("2d");a.fillRect(0,0,1,1);const s=a.getImageData(0,0,1,1).data[3];i.width=i.height=1;return 0!==s}catch{return!1}}static _guessMax(e,t,i,a){for(;e+i+1pt){const e=this.#N();if(e)return e}const a=this._encodeBMP();let s,r;if(await ImageResizer.canUseImageDecoder){s=new ImageDecoder({data:a,type:"image/bmp",preferAnimation:!1,transfer:[a.buffer]});r=s.decode().catch((e=>{warn(`BMP image decoding failed: ${e}`);return createImageBitmap(new Blob([this._encodeBMP().buffer],{type:"image/bmp"}))})).finally((()=>{s.close()}))}else r=createImageBitmap(new Blob([a.buffer],{type:"image/bmp"}));const{MAX_AREA:n,MAX_DIM:g}=ImageResizer,o=Math.max(t/g,i/g,Math.sqrt(t*i/n)),c=Math.max(o,2),C=Math.round(10*(o+1.25))/10/c,h=Math.floor(Math.log2(C)),l=new Array(h+2).fill(2);l[0]=c;l.splice(-1,1,C/(1<>n,o=a>>n;let c,C=a;try{c=new Uint8Array(r)}catch{let e=Math.floor(Math.log2(r+1));for(;;)try{c=new Uint8Array(2**e-1);break}catch{e-=1}C=Math.floor((2**e-1)/(4*i));const t=i*C*4;t>n;e>3,n=i+3&-4;if(i!==n){const e=new Uint8Array(n*t);let a=0;for(let r=0,g=t*i;r>>8;t[i++]=255&s}}}else{if(!ArrayBuffer.isView(e))throw new Error("Invalid data format, must be a string or TypedArray.");t=e.slice();i=t.byteLength}const a=i>>2,s=i-4*a,r=new Uint32Array(t.buffer,0,a);let n=0,g=0,o=this.h1,c=this.h2;const C=3432918353,h=461845907,l=11601,Q=13715;for(let e=0;e>>17;n=n*h&Qs|n*Q&Es;o^=n;o=o<<13|o>>>19;o=5*o+3864292196}else{g=r[e];g=g*C&Qs|g*l&Es;g=g<<15|g>>>17;g=g*h&Qs|g*Q&Es;c^=g;c=c<<13|c>>>19;c=5*c+3864292196}n=0;switch(s){case 3:n^=t[4*a+2]<<16;case 2:n^=t[4*a+1]<<8;case 1:n^=t[4*a];n=n*C&Qs|n*l&Es;n=n<<15|n>>>17;n=n*h&Qs|n*Q&Es;1&a?o^=n:c^=n}this.h1=o;this.h2=c}hexdigest(){let e=this.h1,t=this.h2;e^=t>>>1;e=3981806797*e&Qs|36045*e&Es;t=4283543511*t&Qs|(2950163797*(t<<16|e>>>16)&Qs)>>>16;e^=t>>>1;e=444984403*e&Qs|60499*e&Es;t=3301882366*t&Qs|(3120437893*(t<<16|e>>>16)&Qs)>>>16;e^=t>>>1;return(e>>>0).toString(16).padStart(8,"0")+(t>>>0).toString(16).padStart(8,"0")}}function addState(e,t,i,a,s){let r=e;for(let e=0,i=t.length-1;e1e3){c=Math.max(c,l);Q+=h+2;l=0;h=0}C.push({transform:t,x:l,y:Q,w:i.width,h:i.height});l+=i.width+2;h=Math.max(h,i.height)}const E=Math.max(c,l)+1,u=Q+h+1,d=new Uint8Array(E*u*4),f=E<<2;for(let e=0;e=0;){t[r-4]=t[r];t[r-3]=t[r+1];t[r-2]=t[r+2];t[r-1]=t[r+3];t[r+i]=t[r+i-4];t[r+i+1]=t[r+i-3];t[r+i+2]=t[r+i-2];t[r+i+3]=t[r+i-1];r-=f}}const p={width:E,height:u};if(e.isOffscreenCanvasSupported){const e=new OffscreenCanvas(E,u);e.getContext("2d").putImageData(new ImageData(new Uint8ClampedArray(d.buffer),E,u),0,0);p.bitmap=e.transferToImageBitmap();p.data=null}else{p.kind=S;p.data=d}i.splice(r,4*o,$e);a.splice(r,4*o,[p,C]);return r+1}));addState(us,[MA,xA,Ze,UA],null,(function iterateImageMaskGroup(e,t){const i=e.fnArray,a=(t-(e.iCurr-3))%4;switch(a){case 0:return i[t]===MA;case 1:return i[t]===xA;case 2:return i[t]===Ze;case 3:return i[t]===UA}throw new Error(`iterateImageMaskGroup - invalid pos: ${a}`)}),(function foundImageMaskGroup(e,t){const i=e.fnArray,a=e.argsArray,s=e.iCurr,r=s-3,n=s-2,g=s-1;let o=Math.floor((t-r)/4);if(o<10)return t-(t-r)%4;let c,C,h=!1;const l=a[g][0],Q=a[n][0],E=a[n][1],u=a[n][2],d=a[n][3];if(E===u){h=!0;c=n+4;let e=g+4;for(let t=1;t=4&&i[r-4]===i[n]&&i[r-3]===i[g]&&i[r-2]===i[o]&&i[r-1]===i[c]&&a[r-4][0]===C&&a[r-4][1]===h){l++;Q-=5}let E=Q+4;for(let e=1;e=i)break}a=(a||us)[e[t]];if(a&&!Array.isArray(a)){r.iCurr=t;t++;if(!a.checkFn||(0,a.checkFn)(r)){s=a;a=null}else a=null}else t++}this.state=a;this.match=s;this.lastProcessed=t}flush(){for(;this.match;){const e=this.queue.fnArray.length;this.lastProcessed=(0,this.match.processFn)(this.context,e);this.match=null;this.state=null;this._optimize()}}reset(){this.state=null;this.match=null;this.lastProcessed=0}}class OperatorList{static CHUNK_SIZE=1e3;static CHUNK_SIZE_ABOUT=this.CHUNK_SIZE-5;constructor(e=0,t){this._streamSink=t;this.fnArray=[];this.argsArray=[];this.optimizer=!t||e&E?new NullOptimizer(this):new QueueOptimizer(this);this.dependencies=new Set;this._totalLength=0;this.weight=0;this._resolved=t?null:Promise.resolve()}set isOffscreenCanvasSupported(e){this.optimizer.isOffscreenCanvasSupported=e}get length(){return this.argsArray.length}get ready(){return this._resolved||this._streamSink.ready}get totalLength(){return this._totalLength+this.length}addOp(e,t){this.optimizer.push(e,t);this.weight++;this._streamSink&&(this.weight>=OperatorList.CHUNK_SIZE||this.weight>=OperatorList.CHUNK_SIZE_ABOUT&&(e===UA||e===ee))&&this.flush()}addImageOps(e,t,i,a=!1){if(a){this.addOp(MA);this.addOp(GA,[[["SMask",!1]]])}void 0!==i&&this.addOp(Ye,["OC",i]);this.addOp(e,t);void 0!==i&&this.addOp(ve,[]);a&&this.addOp(UA)}addDependency(e){if(!this.dependencies.has(e)){this.dependencies.add(e);this.addOp(wA,[e])}}addDependencies(e){for(const t of e)this.addDependency(t)}addOpList(e){if(e instanceof OperatorList){for(const t of e.dependencies)this.dependencies.add(t);for(let t=0,i=e.length;ta&&(e=a);return e}function resizeImageMask(e,t,i,a,s,r){const n=s*r;let g;g=t<=8?new Uint8Array(n):t<=16?new Uint16Array(n):new Uint32Array(n);const o=i/s,c=a/r;let C,h,l,Q,E=0;const u=new Uint16Array(s),d=i;for(C=0;C0&&Number.isInteger(i.height)&&i.height>0&&(i.width!==l||i.height!==Q)){warn("PDFImage - using the Width/Height of the image data, rather than the image dictionary.");l=i.width;Q=i.height}if(l<1||Q<1)throw new FormatError(`Invalid image width: ${l} or height: ${Q}`);this.width=l;this.height=Q;this.interpolate=c.get("I","Interpolate");this.imageMask=c.get("IM","ImageMask")||!1;this.matte=c.get("Matte")||!1;let E=i.bitsPerComponent;if(!E){E=c.get("BPC","BitsPerComponent");if(!E){if(!this.imageMask)throw new FormatError(`Bits per component missing in image: ${this.imageMask}`);E=1}}this.bpc=E;if(!this.imageMask){let s=c.getRaw("CS")||c.getRaw("ColorSpace");const r=!!s;if(r)this.jpxDecoderOptions?.smaskInData&&(s=Name.get("DeviceRGBA"));else if(this.jpxDecoderOptions)s=Name.get("DeviceRGBA");else switch(i.numComps){case 1:s=Name.get("DeviceGray");break;case 3:s=Name.get("DeviceRGB");break;case 4:s=Name.get("DeviceCMYK");break;default:throw new Error(`Images with ${i.numComps} color components not supported.`)}this.colorSpace=ColorSpace.parse({cs:s,xref:e,resources:a?t:null,pdfFunctionFactory:g,localColorSpaceCache:o});this.numComps=this.colorSpace.numComps;if(this.jpxDecoderOptions){this.jpxDecoderOptions.numComponents=r?this.numComp:0;this.jpxDecoderOptions.isIndexedColormap="Indexed"===this.colorSpace.name}}this.decode=c.getArray("D","Decode");this.needsDecode=!1;if(this.decode&&(this.colorSpace&&!this.colorSpace.isDefaultDecode(this.decode,E)||n&&!ColorSpace.isDefaultDecode(this.decode,1))){this.needsDecode=!0;const e=(1<>3)*i,g=e.byteLength;let o,c;if(!a||s&&!(n===g))if(s){o=new Uint8Array(n);o.set(e);o.fill(255,g)}else o=new Uint8Array(e);else o=e;if(s)for(c=0;c>7&1;n[l+1]=h>>6&1;n[l+2]=h>>5&1;n[l+3]=h>>4&1;n[l+4]=h>>3&1;n[l+5]=h>>2&1;n[l+6]=h>>1&1;n[l+7]=1&h;l+=8}if(l>=1}}}}else{let i=0;h=0;for(l=0,C=r;l>a;s<0?s=0:s>c&&(s=c);n[l]=s;h&=(1<n[a+1]){t=255;break}}g[C]=t}}}if(g)for(C=0,l=3,h=t*a;C>3,C=t&&ImageResizer.needsToBeResized(i,a);if(!this.smask&&!this.mask&&"DeviceRGBA"===this.colorSpace.name){s.kind=S;const e=s.data=await this.getImageBytes(g*n*4,{});return t?C?ImageResizer.createImage(s,!1):this.createBitmap(S,i,a,e):s}if(!e){let e;"DeviceGray"===this.colorSpace.name&&1===o?e=b:"DeviceRGB"!==this.colorSpace.name||8!==o||this.needsDecode||(e=F);if(e&&!this.smask&&!this.mask&&i===n&&a===g){const r=await this.#G(n,g);if(r)return r;const o=await this.getImageBytes(g*c,{});if(t)return C?ImageResizer.createImage({data:o,kind:e,width:i,height:a,interpolate:this.interpolate},this.needsDecode):this.createBitmap(e,n,g,o);s.kind=e;s.data=o;if(this.needsDecode){assert(e===b,"PDFImage.createImageData: The image must be grayscale.");const t=s.data;for(let e=0,i=t.length;e>3,n=await this.getImageBytes(a*r,{internal:!0}),g=this.getComponents(n);let o,c;if(1===s){c=i*a;if(this.needsDecode)for(o=0;o0&&t.args[0].count++}class TimeSlotManager{static TIME_SLOT_DURATION_MS=20;static CHECK_TIME_EVERY=100;constructor(){this.reset()}check(){if(++this.checkedh){const e="Image exceeded maximum allowed size and was removed.";if(this.options.ignoreErrors){warn(e);return}throw new Error(e)}let l;g.has("OC")&&(l=await this.parseMarkedContentProps(g.get("OC"),e));let Q,E;if(g.get("IM","ImageMask")||!1){const e=g.get("I","Interpolate"),i=c+7>>3,n=t.getBytes(i*C),h=g.getArray("D","Decode");if(this.parsingType3Font){Q=PDFImage.createRawMask({imgArray:n,width:c,height:C,imageIsFromDecodeStream:t instanceof DecodeStream,inverseDecode:h?.[0]>0,interpolate:e});Q.cached=!!s;E=[Q];a.addImageOps(Ze,E,l);if(s){const e={fn:Ze,args:E,optionalContent:l};r.set(s,o,e);o&&this._regionalImageCache.set(null,o,e)}return}Q=await PDFImage.createMask({imgArray:n,width:c,height:C,imageIsFromDecodeStream:t instanceof DecodeStream,inverseDecode:h?.[0]>0,interpolate:e,isOffscreenCanvasSupported:this.options.isOffscreenCanvasSupported});if(Q.isSingleOpaquePixel){a.addImageOps(tt,[],l);if(s){const e={fn:tt,args:[],optionalContent:l};r.set(s,o,e);o&&this._regionalImageCache.set(null,o,e)}return}const u=`mask_${this.idFactory.createObjId()}`;a.addDependency(u);Q.dataLen=Q.bitmap?Q.width*Q.height*4:Q.data.length;this._sendImgData(u,Q);E=[{data:u,width:Q.width,height:Q.height,interpolate:Q.interpolate,count:1}];a.addImageOps(Ze,E,l);if(s){const e={objId:u,fn:Ze,args:E,optionalContent:l};r.set(s,o,e);o&&this._regionalImageCache.set(null,o,e)}return}const u=g.has("SMask")||g.has("Mask");if(i&&c+C<200&&!u){try{const s=new PDFImage({xref:this.xref,res:e,image:t,isInline:i,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:n});Q=await s.createImageData(!0,!1);a.isOffscreenCanvasSupported=this.options.isOffscreenCanvasSupported;a.addImageOps(_e,[Q],l)}catch(e){const t=`Unable to decode inline image: "${e}".`;if(!this.options.ignoreErrors)throw new Error(t);warn(t)}return}let d=`img_${this.idFactory.createObjId()}`,f=!1;if(this.parsingType3Font)d=`${this.idFactory.getDocId()}_type3_${d}`;else if(s&&o){f=this.globalImageCache.shouldCache(o,this.pageIndex);if(f){assert(!i,"Cannot cache an inline image globally.");d=`${this.idFactory.getDocId()}_${d}`}}a.addDependency(d);E=[d,c,C];a.addImageOps(ze,E,l,u);if(f){if(this.globalImageCache.hasDecodeFailed(o)){this.globalImageCache.setData(o,{objId:d,fn:ze,args:E,optionalContent:l,hasMask:u,byteSize:0});this._sendImgData(d,null,f);return}if(c*C>25e4||u){const e=await this.handler.sendWithPromise("commonobj",[d,"CopyLocalImage",{imageRef:o}]);if(e){this.globalImageCache.setData(o,{objId:d,fn:ze,args:E,optionalContent:l,hasMask:u,byteSize:0});this.globalImageCache.addByteSize(o,e);return}}}PDFImage.buildImage({xref:this.xref,res:e,image:t,isInline:i,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:n}).then((async e=>{Q=await e.createImageData(!1,this.options.isOffscreenCanvasSupported);Q.dataLen=Q.bitmap?Q.width*Q.height*4:Q.data.length;Q.ref=o;f&&this.globalImageCache.addByteSize(o,Q.dataLen);return this._sendImgData(d,Q,f)})).catch((e=>{warn(`Unable to decode image "${d}": "${e}".`);o&&this.globalImageCache.addDecodeFailed(o);return this._sendImgData(d,null,f)}));if(s){const e={objId:d,fn:ze,args:E,optionalContent:l,hasMask:u};r.set(s,o,e);if(o){this._regionalImageCache.set(null,o,e);f&&this.globalImageCache.setData(o,{objId:d,fn:ze,args:E,optionalContent:l,hasMask:u,byteSize:0})}}}handleSMask(e,t,i,a,s,r){const n=e.get("G"),g={subtype:e.get("S").name,backdrop:e.get("BC")},o=e.get("TR");if(isPDFFunction(o)){const e=this._pdfFunctionFactory.create(o),t=new Uint8Array(256),i=new Float32Array(1);for(let a=0;a<256;a++){i[0]=a/255;e(i,0,i,0);t[a]=255*i[0]|0}g.transferMap=t}return this.buildFormXObject(t,n,g,i,a,s.state.clone(),r)}handleTransferFunction(e){let t;if(Array.isArray(e))t=e;else{if(!isPDFFunction(e))return null;t=[e]}const i=[];let a=0,s=0;for(const e of t){const t=this.xref.fetchIfRef(e);a++;if(isName(t,"Identity")){i.push(null);continue}if(!isPDFFunction(t))return null;const r=this._pdfFunctionFactory.create(t),n=new Uint8Array(256),g=new Float32Array(1);for(let e=0;e<256;e++){g[0]=e/255;r(g,0,g,0);n[e]=255*g[0]|0}i.push(n);s++}return 1!==a&&4!==a||0===s?null:i}handleTilingType(e,t,i,a,s,r,n,g){const o=new OperatorList,c=Dict.merge({xref:this.xref,dictArray:[s.get("Resources"),i]});return this.getOperatorList({stream:a,task:n,resources:c,operatorList:o}).then((function(){const i=o.getIR(),a=getTilingPatternIR(i,s,t);r.addDependencies(o.dependencies);r.addOp(e,a);s.objId&&g.set(null,s.objId,{operatorListIR:i,dict:s})})).catch((e=>{if(!(e instanceof AbortException)){if(!this.options.ignoreErrors)throw e;warn(`handleTilingType - ignoring pattern: "${e}".`)}}))}async handleSetFont(e,t,i,a,s,r,n=null,g=null){const o=t?.[0]instanceof Name?t[0].name:null;let c=await this.loadFont(o,i,e,n,g);if(c.font.isType3Font)try{await c.loadType3Data(this,e,s);a.addDependencies(c.type3Dependencies)}catch(e){c=new TranslatedFont({loadedName:"g_font_error",font:new ErrorFont(`Type3 font load error: ${e}`),dict:c.font,evaluatorOptions:this.options})}r.font=c.font;c.send(this.handler);return c.loadedName}handleText(e,t){const i=t.font,a=i.charsToGlyphs(e);if(i.data){(!!(t.textRenderingMode&D)||"Pattern"===t.fillColorSpace.name||i.disableFontFace||this.options.disableFontFace)&&PartialEvaluator.buildFontPaths(i,a,this.handler,this.options)}return a}ensureStateFont(e){if(e.font)return;const t=new FormatError("Missing setFont (Tf) operator before text rendering operator.");if(!this.options.ignoreErrors)throw t;warn(`ensureStateFont: "${t}".`)}async setGState({resources:e,gState:t,operatorList:i,cacheKey:a,task:s,stateManager:r,localGStateCache:n,localColorSpaceCache:g}){const o=t.objId;let c=!0;const C=[];let h=Promise.resolve();for(const a of t.getKeys()){const n=t.get(a);switch(a){case"Type":break;case"LW":case"LC":case"LJ":case"ML":case"D":case"RI":case"FL":case"CA":case"ca":C.push([a,n]);break;case"Font":c=!1;h=h.then((()=>this.handleSetFont(e,null,n[0],i,s,r.state).then((function(e){i.addDependency(e);C.push([a,[e,n[1]]])}))));break;case"BM":C.push([a,normalizeBlendMode(n)]);break;case"SMask":if(isName(n,"None")){C.push([a,!1]);break}if(n instanceof Dict){c=!1;h=h.then((()=>this.handleSMask(n,e,i,s,r,g)));C.push([a,!0])}else warn("Unsupported SMask type");break;case"TR":const t=this.handleTransferFunction(n);C.push([a,t]);break;case"OP":case"op":case"OPM":case"BG":case"BG2":case"UCR":case"UCR2":case"TR2":case"HT":case"SM":case"SA":case"AIS":case"TK":info("graphic state operator "+a);break;default:info("Unknown graphic state operator "+a)}}await h;C.length>0&&i.addOp(GA,[C]);c&&n.set(a,o,C)}loadFont(e,t,i,a=null,s=null){const errorFont=async()=>new TranslatedFont({loadedName:"g_font_error",font:new ErrorFont(`Font "${e}" is not available.`),dict:t,evaluatorOptions:this.options});let r;if(t)t instanceof Ref&&(r=t);else{const t=i.get("Font");t&&(r=t.getRaw(e))}if(r){if(this.type3FontRefs?.has(r))return errorFont();if(this.fontCache.has(r))return this.fontCache.get(r);try{t=this.xref.fetchIfRef(r)}catch(e){warn(`loadFont - lookup failed: "${e}".`)}}if(!(t instanceof Dict)){if(!this.options.ignoreErrors&&!this.parsingType3Font){warn(`Font "${e}" is not available.`);return errorFont()}warn(`Font "${e}" is not available -- attempting to fallback to a default font.`);t=a||PartialEvaluator.fallbackFontDict}if(t.cacheKey&&this.fontCache.has(t.cacheKey))return this.fontCache.get(t.cacheKey);const{promise:n,resolve:g}=Promise.withResolvers();let o;try{o=this.preEvaluateFont(t);o.cssFontInfo=s}catch(e){warn(`loadFont - preEvaluateFont failed: "${e}".`);return errorFont()}const{descriptor:c,hash:C}=o,h=r instanceof Ref;let l;if(C&&c instanceof Dict){const e=c.fontAliases||=Object.create(null);if(e[C]){const t=e[C].aliasRef;if(h&&t&&this.fontCache.has(t)){this.fontCache.putAlias(r,t);return this.fontCache.get(r)}}else e[C]={fontID:this.idFactory.createFontId()};h&&(e[C].aliasRef=r);l=e[C].fontID}else l=this.idFactory.createFontId();assert(l?.startsWith("f"),'The "fontID" must be (correctly) defined.');if(h)this.fontCache.put(r,n);else{t.cacheKey=`cacheKey_${l}`;this.fontCache.put(t.cacheKey,n)}t.loadedName=`${this.idFactory.getDocId()}_${l}`;this.translateFont(o).then((e=>{g(new TranslatedFont({loadedName:t.loadedName,font:e,dict:t,evaluatorOptions:this.options}))})).catch((e=>{warn(`loadFont - translateFont failed: "${e}".`);g(new TranslatedFont({loadedName:t.loadedName,font:new ErrorFont(e instanceof Error?e.message:e),dict:t,evaluatorOptions:this.options}))}));return n}buildPath(e,t,i,a=!1){const s=e.length-1;i||(i=[]);if(s<0||e.fnArray[s]!==it){if(a){warn(`Encountered path operator "${t}" inside of a text object.`);e.addOp(MA,null)}let s;switch(t){case TA:const e=i[0]+i[2],t=i[1]+i[3];s=[Math.min(i[0],e),Math.min(i[1],t),Math.max(i[0],e),Math.max(i[1],t)];break;case LA:case HA:s=[i[0],i[1],i[0],i[1]];break;default:s=[1/0,1/0,-1/0,-1/0]}e.addOp(it,[[t],i,s]);a&&e.addOp(UA,null)}else{const a=e.argsArray[s];a[0].push(t);a[1].push(...i);const r=a[2];switch(t){case TA:const e=i[0]+i[2],t=i[1]+i[3];r[0]=Math.min(r[0],i[0],e);r[1]=Math.min(r[1],i[1],t);r[2]=Math.max(r[2],i[0],e);r[3]=Math.max(r[3],i[1],t);break;case LA:case HA:r[0]=Math.min(r[0],i[0]);r[1]=Math.min(r[1],i[1]);r[2]=Math.max(r[2],i[0]);r[3]=Math.max(r[3],i[1])}}}parseColorSpace({cs:e,resources:t,localColorSpaceCache:i}){return ColorSpace.parseAsync({cs:e,xref:this.xref,resources:t,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:i}).catch((e=>{if(e instanceof AbortException)return null;if(this.options.ignoreErrors){warn(`parseColorSpace - ignoring ColorSpace: "${e}".`);return null}throw e}))}parseShading({shading:e,resources:t,localColorSpaceCache:i,localShadingPatternCache:a}){let s,r=a.get(e);if(r)return r;try{s=Pattern.parseShading(e,this.xref,t,this._pdfFunctionFactory,i).getIR()}catch(t){if(t instanceof AbortException)return null;if(this.options.ignoreErrors){warn(`parseShading - ignoring shading: "${t}".`);a.set(e,null);return null}throw t}r=`pattern_${this.idFactory.createObjId()}`;this.parsingType3Font&&(r=`${this.idFactory.getDocId()}_type3_${r}`);a.set(e,r);this.parsingType3Font?this.handler.send("commonobj",[r,"Pattern",s]):this.handler.send("obj",[r,this.pageIndex,"Pattern",s]);return r}handleColorN(e,t,i,a,s,r,n,g,o,c){const C=i.pop();if(C instanceof Name){const h=s.getRaw(C.name),l=h instanceof Ref&&o.getByRef(h);if(l)try{const s=a.base?a.base.getRgb(i,0):null,r=getTilingPatternIR(l.operatorListIR,l.dict,s);e.addOp(t,r);return}catch{}const Q=this.xref.fetchIfRef(h);if(Q){const s=Q instanceof BaseStream?Q.dict:Q,C=s.get("PatternType");if(C===fs){const g=a.base?a.base.getRgb(i,0):null;return this.handleTilingType(t,g,r,Q,s,e,n,o)}if(C===ps){const i=s.get("Shading"),a=this.parseShading({shading:i,resources:r,localColorSpaceCache:g,localShadingPatternCache:c});if(a){const i=lookupMatrix(s.getArray("Matrix"),null);e.addOp(t,["Shading",a,i])}return}throw new FormatError(`Unknown PatternType: ${C}`)}}throw new FormatError(`Unknown PatternName: ${C}`)}_parseVisibilityExpression(e,t,i){if(++t>10){warn("Visibility expression is too deeply nested");return}const a=e.length,s=this.xref.fetchIfRef(e[0]);if(!(a<2)&&s instanceof Name){switch(s.name){case"And":case"Or":case"Not":i.push(s.name);break;default:warn(`Invalid operator ${s.name} in visibility expression`);return}for(let s=1;s0)return{type:"OCMD",expression:t}}const t=i.get("OCGs");if(Array.isArray(t)||t instanceof Dict){const e=[];if(Array.isArray(t))for(const i of t)e.push(i.toString());else e.push(t.objId);return{type:a,ids:e,policy:i.get("P")instanceof Name?i.get("P").name:null,expression:null}}if(t instanceof Ref)return{type:a,id:t.toString()}}return null}getOperatorList({stream:e,task:t,resources:i,operatorList:a,initialState:s=null,fallbackFontDict:r=null}){i||=Dict.empty;s||=new EvalState;if(!a)throw new Error('getOperatorList: missing "operatorList" parameter');const n=this,g=this.xref;let o=!1;const c=new LocalImageCache,C=new LocalColorSpaceCache,h=new LocalGStateCache,l=new LocalTilingPatternCache,Q=new Map,E=i.get("XObject")||Dict.empty,u=i.get("Pattern")||Dict.empty,d=new StateManager(s),f=new EvaluatorPreprocessor(e,g,d),p=new TimeSlotManager;function closePendingRestoreOPS(e){for(let e=0,t=f.savedStatesDepth;e0&&a.addOp(GA,[t]);e=null;continue}}next(new Promise((function(e,s){if(!S)throw new FormatError("GState must be referred to by name.");const r=i.get("ExtGState");if(!(r instanceof Dict))throw new FormatError("ExtGState should be a dictionary.");const g=r.get(F);if(!(g instanceof Dict))throw new FormatError("GState should be a dictionary.");n.setGState({resources:i,gState:g,operatorList:a,cacheKey:F,task:t,stateManager:d,localGStateCache:h,localColorSpaceCache:C}).then(e,s)})).catch((function(e){if(!(e instanceof AbortException)){if(!n.options.ignoreErrors)throw e;warn(`getOperatorList - ignoring ExtGState: "${e}".`)}})));return;case LA:case HA:case JA:case YA:case vA:case KA:case TA:n.buildPath(a,s,e,o);continue;case Le:case He:case Ke:case Te:continue;case Ye:if(!(e[0]instanceof Name)){warn(`Expected name for beginMarkedContentProps arg0=${e[0]}`);a.addOp(Ye,["OC",null]);continue}if("OC"===e[0].name){next(n.parseMarkedContentProps(e[1],i).then((e=>{a.addOp(Ye,["OC",e])})).catch((e=>{if(!(e instanceof AbortException)){if(!n.options.ignoreErrors)throw e;warn(`getOperatorList - ignoring beginMarkedContentProps: "${e}".`);a.addOp(Ye,["OC",null])}})));return}e=[e[0].name,e[1]instanceof Dict?e[1].get("MCID"):null];break;default:if(null!==e){for(w=0,D=e.length;w{if(!(e instanceof AbortException)){if(!this.options.ignoreErrors)throw e;warn(`getOperatorList - ignoring errors during "${t.name}" task: "${e}".`);closePendingRestoreOPS()}}))}getTextContent({stream:e,task:t,resources:s,stateManager:r=null,includeMarkedContent:n=!1,sink:g,seenStyles:o=new Set,viewBox:c,lang:C=null,markedContentData:h=null,disableNormalization:l=!1,keepWhiteSpace:Q=!1}){s||=Dict.empty;r||=new StateManager(new TextState);n&&(h||={level:0});const E={items:[],styles:Object.create(null),lang:C},u={initialized:!1,str:[],totalWidth:0,totalHeight:0,width:0,height:0,vertical:!1,prevTransform:null,textAdvanceScale:0,spaceInFlowMin:0,spaceInFlowMax:0,trackingSpaceMin:1/0,negativeSpaceMax:-1/0,notASpace:-1/0,transform:null,fontName:null,hasEOL:!1},d=[" "," "];let f=0;function saveLastChar(e){const t=(f+1)%2,i=" "!==d[f]&&" "===d[t];d[f]=e;f=t;return!Q&&i}function shouldAddWhitepsace(){return!Q&&" "!==d[f]&&" "===d[(f+1)%2]}function resetLastChars(){d[0]=d[1]=" ";f=0}const p=this,m=this.xref,y=[];let w=null;const D=new LocalImageCache,b=new LocalGStateCache,F=new EvaluatorPreprocessor(e,m,r);let S;function pushWhitespace({width:e=0,height:t=0,transform:i=u.prevTransform,fontName:a=u.fontName}){E.items.push({str:" ",dir:"ltr",width:e,height:t,transform:i,fontName:a,hasEOL:!1})}function getCurrentTextTransform(){const e=S.font,t=[S.fontSize*S.textHScale,0,0,S.fontSize,0,S.textRise];if(e.isType3Font&&(S.fontSize<=1||e.isCharBBox)&&!isArrayEqual(S.fontMatrix,a)){const i=e.bbox[3]-e.bbox[1];i>0&&(t[3]*=i*S.fontMatrix[3])}return Util.transform(S.ctm,Util.transform(S.textMatrix,t))}function ensureTextContentItem(){if(u.initialized)return u;const{font:e,loadedName:t}=S;if(!o.has(t)){o.add(t);E.styles[t]={fontFamily:e.fallbackName,ascent:e.ascent,descent:e.descent,vertical:e.vertical};if(p.options.fontExtraProperties&&e.systemFontInfo){const i=E.styles[t];i.fontSubstitution=e.systemFontInfo.css;i.fontSubstitutionLoadedName=e.systemFontInfo.loadedName}}u.fontName=t;const i=u.transform=getCurrentTextTransform();if(e.vertical){u.width=u.totalWidth=Math.hypot(i[0],i[1]);u.height=u.totalHeight=0;u.vertical=!0}else{u.width=u.totalWidth=0;u.height=u.totalHeight=Math.hypot(i[2],i[3]);u.vertical=!1}const a=Math.hypot(S.textLineMatrix[0],S.textLineMatrix[1]),s=Math.hypot(S.ctm[0],S.ctm[1]);u.textAdvanceScale=s*a;const{fontSize:r}=S;u.trackingSpaceMin=.102*r;u.notASpace=.03*r;u.negativeSpaceMax=-.2*r;u.spaceInFlowMin=.102*r;u.spaceInFlowMax=.6*r;u.hasEOL=!1;u.initialized=!0;return u}function updateAdvanceScale(){if(!u.initialized)return;const e=Math.hypot(S.textLineMatrix[0],S.textLineMatrix[1]),t=Math.hypot(S.ctm[0],S.ctm[1])*e;if(t!==u.textAdvanceScale){if(u.vertical){u.totalHeight+=u.height*u.textAdvanceScale;u.height=0}else{u.totalWidth+=u.width*u.textAdvanceScale;u.width=0}u.textAdvanceScale=t}}function runBidiTransform(e){let t=e.str.join("");l||(t=function normalizeUnicode(e){if(!Ct){Ct=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu;ht=new Map([["ſt","ſt"]])}return e.replaceAll(Ct,((e,t,i)=>t?t.normalize("NFKC"):ht.get(i)))}(t));const i=bidi(t,-1,e.vertical);return{str:i.str,dir:i.dir,width:Math.abs(e.totalWidth),height:Math.abs(e.totalHeight),transform:e.transform,fontName:e.fontName,hasEOL:e.hasEOL}}async function handleSetFont(e,i){const r=await p.loadFont(e,i,s);if(r.font.isType3Font)try{await r.loadType3Data(p,s,t)}catch{}S.loadedName=r.loadedName;S.font=r.font;S.fontMatrix=r.font.fontMatrix||a}function applyInverseRotation(e,t,i){const a=Math.hypot(i[0],i[1]);return[(i[0]*e+i[1]*t)/a,(i[2]*e+i[3]*t)/a]}function compareWithLastPosition(e){const t=getCurrentTextTransform();let i=t[4],a=t[5];if(S.font?.vertical){if(ic[2]||a+ec[3])return!1}else if(i+ec[2]||ac[3])return!1;if(!S.font||!u.prevTransform)return!0;let s=u.prevTransform[4],r=u.prevTransform[5];if(s===i&&r===a)return!0;let n=-1;t[0]&&0===t[1]&&0===t[2]?n=t[0]>0?0:180:t[1]&&0===t[0]&&0===t[3]&&(n=t[1]>0?90:270);switch(n){case 0:break;case 90:[i,a]=[a,i];[s,r]=[r,s];break;case 180:[i,a,s,r]=[-i,-a,-s,-r];break;case 270:[i,a]=[-a,-i];[s,r]=[-r,-s];break;default:[i,a]=applyInverseRotation(i,a,t);[s,r]=applyInverseRotation(s,r,u.prevTransform)}if(S.font.vertical){const e=(r-a)/u.textAdvanceScale,t=i-s,n=Math.sign(u.height);if(e.5*u.width){appendEOL();return!0}resetLastChars();flushTextContentItem();return!0}if(Math.abs(t)>u.width){appendEOL();return!0}e<=n*u.notASpace&&resetLastChars();if(e<=n*u.trackingSpaceMin)if(shouldAddWhitepsace()){resetLastChars();flushTextContentItem();pushWhitespace({height:Math.abs(e)})}else u.height+=e;else if(!addFakeSpaces(e,u.prevTransform,n))if(0===u.str.length){resetLastChars();pushWhitespace({height:Math.abs(e)})}else u.height+=e;Math.abs(t)>.25*u.width&&flushTextContentItem();return!0}const g=(i-s)/u.textAdvanceScale,o=a-r,C=Math.sign(u.width);if(g.5*u.height){appendEOL();return!0}resetLastChars();flushTextContentItem();return!0}if(Math.abs(o)>u.height){appendEOL();return!0}g<=C*u.notASpace&&resetLastChars();if(g<=C*u.trackingSpaceMin)if(shouldAddWhitepsace()){resetLastChars();flushTextContentItem();pushWhitespace({width:Math.abs(g)})}else u.width+=g;else if(!addFakeSpaces(g,u.prevTransform,C))if(0===u.str.length){resetLastChars();pushWhitespace({width:Math.abs(g)})}else u.width+=g;Math.abs(o)>.25*u.height&&flushTextContentItem();return!0}function buildTextContentItem({chars:e,extraSpacing:t}){const i=S.font;if(!e){const e=S.charSpacing+t;e&&(i.vertical?S.translateTextMatrix(0,-e):S.translateTextMatrix(e*S.textHScale,0));Q&&compareWithLastPosition(0);return}const a=i.charsToGlyphs(e),s=S.fontMatrix[0]*S.fontSize;for(let e=0,r=a.length;e0){const e=y.join("");y.length=0;buildTextContentItem({chars:e,extraSpacing:0})}break;case he:if(!r.state.font){p.ensureStateFont(r.state);continue}buildTextContentItem({chars:N[0],extraSpacing:0});break;case Be:if(!r.state.font){p.ensureStateFont(r.state);continue}S.carriageReturn();buildTextContentItem({chars:N[0],extraSpacing:0});break;case Qe:if(!r.state.font){p.ensureStateFont(r.state);continue}S.wordSpacing=N[0];S.charSpacing=N[1];S.carriageReturn();buildTextContentItem({chars:N[2],extraSpacing:0});break;case xe:flushTextContentItem();w??=s.get("XObject")||Dict.empty;R=N[0]instanceof Name;f=N[0].name;if(R&&D.getByName(f))break;next(new Promise((function(e,i){if(!R)throw new FormatError("XObject must be referred to by name.");let a=w.getRaw(f);if(a instanceof Ref){if(D.getByRef(a)){e();return}if(p.globalImageCache.getData(a,p.pageIndex)){e();return}a=m.fetch(a)}if(!(a instanceof BaseStream))throw new FormatError("XObject should be a stream");const E=a.dict.get("Subtype");if(!(E instanceof Name))throw new FormatError("XObject should have a Name subtype");if("Form"!==E.name){D.set(f,a.dict.objId,!0);e();return}const u=r.state.clone(),d=new StateManager(u),y=lookupMatrix(a.dict.getArray("Matrix"),null);y&&d.transform(y);enqueueChunk();const b={enqueueInvoked:!1,enqueue(e,t){this.enqueueInvoked=!0;g.enqueue(e,t)},get desiredSize(){return g.desiredSize},get ready(){return g.ready}};p.getTextContent({stream:a,task:t,resources:a.dict.get("Resources")||s,stateManager:d,includeMarkedContent:n,sink:b,seenStyles:o,viewBox:c,lang:C,markedContentData:h,disableNormalization:l,keepWhiteSpace:Q}).then((function(){b.enqueueInvoked||D.set(f,a.dict.objId,!0);e()}),i)})).catch((function(e){if(!(e instanceof AbortException)){if(!p.options.ignoreErrors)throw e;warn(`getTextContent - ignoring XObject: "${e}".`)}})));return;case GA:R=N[0]instanceof Name;f=N[0].name;if(R&&b.getByName(f))break;next(new Promise((function(e,t){if(!R)throw new FormatError("GState must be referred to by name.");const i=s.get("ExtGState");if(!(i instanceof Dict))throw new FormatError("ExtGState should be a dictionary.");const a=i.get(f);if(!(a instanceof Dict))throw new FormatError("GState should be a dictionary.");const r=a.get("Font");if(r){flushTextContentItem();S.fontName=null;S.fontSize=r[1];handleSetFont(null,r[0]).then(e,t)}else{b.set(f,a.objId,!0);e()}})).catch((function(e){if(!(e instanceof AbortException)){if(!p.options.ignoreErrors)throw e;warn(`getTextContent - ignoring ExtGState: "${e}".`)}})));return;case Je:flushTextContentItem();if(n){h.level++;E.items.push({type:"beginMarkedContent",tag:N[0]instanceof Name?N[0].name:null})}break;case Ye:flushTextContentItem();if(n){h.level++;let e=null;N[1]instanceof Dict&&(e=N[1].get("MCID"));E.items.push({type:"beginMarkedContentProps",id:Number.isInteger(e)?`${p.idFactory.getPageObjId()}_mc${e}`:null,tag:N[0]instanceof Name?N[0].name:null})}break;case ve:flushTextContentItem();if(n){if(0===h.level)break;h.level--;E.items.push({type:"endMarkedContent"})}break;case UA:!e||e.font===S.font&&e.fontSize===S.fontSize&&e.fontName===S.fontName||flushTextContentItem()}if(E.items.length>=g.desiredSize){d=!0;break}}if(d)next(ms);else{flushTextContentItem();enqueueChunk();e()}})).catch((e=>{if(!(e instanceof AbortException)){if(!this.options.ignoreErrors)throw e;warn(`getTextContent - ignoring errors during "${t.name}" task: "${e}".`);flushTextContentItem();enqueueChunk()}}))}async extractDataStructures(e,t){const i=this.xref;let a;const s=this.readToUnicode(t.toUnicode);if(t.composite){const i=e.get("CIDSystemInfo");i instanceof Dict&&(t.cidSystemInfo={registry:stringToPDFString(i.get("Registry")),ordering:stringToPDFString(i.get("Ordering")),supplement:i.get("Supplement")});try{const t=e.get("CIDToGIDMap");t instanceof BaseStream&&(a=t.getBytes())}catch(e){if(!this.options.ignoreErrors)throw e;warn(`extractDataStructures - ignoring CIDToGIDMap data: "${e}".`)}}const r=[];let n,g=null;if(e.has("Encoding")){n=e.get("Encoding");if(n instanceof Dict){g=n.get("BaseEncoding");g=g instanceof Name?g.name:null;if(n.has("Differences")){const e=n.get("Differences");let t=0;for(const a of e){const e=i.fetchIfRef(a);if("number"==typeof e)t=e;else{if(!(e instanceof Name))throw new FormatError(`Invalid entry in 'Differences' array: ${e}`);r[t++]=e.name}}}}else if(n instanceof Name)g=n.name;else{const e="Encoding is not a Name nor a Dict";if(!this.options.ignoreErrors)throw new FormatError(e);warn(e)}"MacRomanEncoding"!==g&&"MacExpertEncoding"!==g&&"WinAnsiEncoding"!==g&&(g=null)}const o=!t.file||t.isInternalFont,c=qi()[t.name];g&&o&&c&&(g=null);if(g)t.defaultEncoding=getEncoding(g);else{const e=!!(t.flags&Mi),i=!!(t.flags&xi);n=hi;"TrueType"!==t.type||i||(n=li);if(e||c){n=Ci;o&&(/Symbol/i.test(t.name)?n=Bi:/Dingbats/i.test(t.name)?n=Qi:/Wingdings/i.test(t.name)&&(n=li))}t.defaultEncoding=n}t.differences=r;t.baseEncodingName=g;t.hasEncoding=!!g||r.length>0;t.dict=e;t.toUnicode=await s;const C=await this.buildToUnicode(t);t.toUnicode=C;a&&(t.cidToGidMap=this.readCidToGidMap(a,C));return t}_simpleFontToUnicode(e,t=!1){assert(!e.composite,"Must be a simple font.");const i=[],a=e.defaultEncoding.slice(),s=e.baseEncodingName,r=e.differences;for(const e in r){const t=r[e];".notdef"!==t&&(a[e]=t)}const n=wi();for(const r in a){let g=a[r];if(""===g)continue;let o=n[g];if(void 0!==o){i[r]=String.fromCharCode(o);continue}let c=0;switch(g[0]){case"G":3===g.length&&(c=parseInt(g.substring(1),16));break;case"g":5===g.length&&(c=parseInt(g.substring(1),16));break;case"C":case"c":if(g.length>=3&&g.length<=4){const i=g.substring(1);if(t){c=parseInt(i,16);break}c=+i;if(Number.isNaN(c)&&Number.isInteger(parseInt(i,16)))return this._simpleFontToUnicode(e,!0)}break;case"u":o=getUnicodeForGlyph(g,n);-1!==o&&(c=o);break;default:switch(g){case"f_h":case"f_t":case"T_h":i[r]=g.replaceAll("_","");continue}}if(c>0&&c<=1114111&&Number.isInteger(c)){if(s&&c===+r){const e=getEncoding(s);if(e&&(g=e[r])){i[r]=String.fromCharCode(n[g]);continue}}i[r]=String.fromCodePoint(c)}}return i}async buildToUnicode(e){e.hasIncludedToUnicodeMap=e.toUnicode?.length>0;if(e.hasIncludedToUnicodeMap){!e.composite&&e.hasEncoding&&(e.fallbackToUnicode=this._simpleFontToUnicode(e));return e.toUnicode}if(!e.composite)return new ToUnicodeMap(this._simpleFontToUnicode(e));if(e.composite&&(e.cMap.builtInCMap&&!(e.cMap instanceof IdentityCMap)||"Adobe"===e.cidSystemInfo?.registry&&("GB1"===e.cidSystemInfo.ordering||"CNS1"===e.cidSystemInfo.ordering||"Japan1"===e.cidSystemInfo.ordering||"Korea1"===e.cidSystemInfo.ordering))){const{registry:t,ordering:i}=e.cidSystemInfo,a=Name.get(`${t}-${i}-UCS2`),s=await CMapFactory.create({encoding:a,fetchBuiltInCMap:this._fetchBuiltInCMapBound,useCMap:null}),r=[],n=[];e.cMap.forEach((function(e,t){if(t>65535)throw new FormatError("Max size of CID is 65,535");const i=s.lookup(t);if(i){n.length=0;for(let e=0,t=i.length;e>1;(0!==s||t.has(r))&&(i[r]=s)}return i}extractWidths(e,t,i){const a=this.xref;let s=[],r=0;const n=[];let g;if(i.composite){const t=e.get("DW");r="number"==typeof t?Math.ceil(t):1e3;const o=e.get("W");if(Array.isArray(o))for(let e=0,t=o.length;e{const t=o.get(e),s=new OperatorList;return a.getOperatorList({stream:t,task:i,resources:c,operatorList:s}).then((()=>{s.fnArray[0]===ue&&this._removeType3ColorOperators(s,E);C[e]=s.getIR();for(const e of s.dependencies)n.add(e)})).catch((function(t){warn(`Type3 font resource "${e}" is not available.`);const i=new OperatorList;C[e]=i.getIR()}))}));this.type3Loaded=g.then((()=>{r.charProcOperatorList=C;if(this._bbox){r.isCharBBox=!0;r.bbox=this._bbox}}));return this.type3Loaded}_removeType3ColorOperators(e,t=NaN){const i=Util.normalizeRect(e.argsArray[0].slice(2)),a=i[2]-i[0],s=i[3]-i[1],r=Math.hypot(a,s);if(0===a||0===s){e.fnArray.splice(0,1);e.argsArray.splice(0,1)}else if(0===t||Math.round(r/t)>=10){this._bbox||(this._bbox=[1/0,1/0,-1/0,-1/0]);this._bbox[0]=Math.min(this._bbox[0],i[0]);this._bbox[1]=Math.min(this._bbox[1],i[1]);this._bbox[2]=Math.max(this._bbox[2],i[2]);this._bbox[3]=Math.max(this._bbox[3],i[3])}let n=0,g=e.length;for(;n=LA&&r<=zA;if(s.variableArgs)g>n&&info(`Command ${a}: expected [0, ${n}] args, but received ${g} args.`);else{if(g!==n){const e=this.nonProcessedArgs;for(;g>n;){e.push(t.shift());g--}for(;gEvaluatorPreprocessor.MAX_INVALID_PATH_OPS)throw new FormatError(`Invalid ${e}`);warn(`Skipping ${e}`);null!==t&&(t.length=0);continue}}this.preprocessCommand(r,t);e.fn=r;e.args=t;return!0}if(i===Bt)return!1;if(null!==i){null===t&&(t=[]);t.push(i);if(t.length>33)throw new FormatError("Too many arguments")}}}preprocessCommand(e,t){switch(0|e){case MA:this.stateManager.save();break;case UA:this.stateManager.restore();break;case xA:this.stateManager.transform(t)}}}class DefaultAppearanceEvaluator extends EvaluatorPreprocessor{constructor(e){super(new StringStream(e))}parse(){const e={fn:0,args:[]},t={fontSize:0,fontName:"",fontColor:new Uint8ClampedArray(3)};try{for(;;){e.args.length=0;if(!this.read(e))break;if(0!==this.savedStatesDepth)continue;const{fn:i,args:a}=e;switch(0|i){case re:const[e,i]=a;e instanceof Name&&(t.fontName=e.name);"number"==typeof i&&i>0&&(t.fontSize=i);break;case Se:ColorSpace.singletons.rgb.getRgbItem(a,0,t.fontColor,0);break;case be:ColorSpace.singletons.gray.getRgbItem(a,0,t.fontColor,0);break;case Re:ColorSpace.singletons.cmyk.getRgbItem(a,0,t.fontColor,0)}}}catch(e){warn(`parseDefaultAppearance - ignoring errors: "${e}".`)}return t}}function parseDefaultAppearance(e){return new DefaultAppearanceEvaluator(e).parse()}class AppearanceStreamEvaluator extends EvaluatorPreprocessor{constructor(e,t,i){super(e);this.stream=e;this.evaluatorOptions=t;this.xref=i;this.resources=e.dict?.get("Resources")}parse(){const e={fn:0,args:[]};let t={scaleFactor:1,fontSize:0,fontName:"",fontColor:new Uint8ClampedArray(3),fillColorSpace:ColorSpace.singletons.gray},i=!1;const a=[];try{for(;;){e.args.length=0;if(i||!this.read(e))break;const{fn:s,args:r}=e;switch(0|s){case MA:a.push({scaleFactor:t.scaleFactor,fontSize:t.fontSize,fontName:t.fontName,fontColor:t.fontColor.slice(),fillColorSpace:t.fillColorSpace});break;case UA:t=a.pop()||t;break;case ce:t.scaleFactor*=Math.hypot(r[0],r[1]);break;case re:const[e,s]=r;e instanceof Name&&(t.fontName=e.name);"number"==typeof s&&s>0&&(t.fontSize=s*t.scaleFactor);break;case fe:t.fillColorSpace=ColorSpace.parse({cs:r[0],xref:this.xref,resources:this.resources,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:this._localColorSpaceCache});break;case ye:t.fillColorSpace.getRgbItem(r,0,t.fontColor,0);break;case Se:ColorSpace.singletons.rgb.getRgbItem(r,0,t.fontColor,0);break;case be:ColorSpace.singletons.gray.getRgbItem(r,0,t.fontColor,0);break;case Re:ColorSpace.singletons.cmyk.getRgbItem(r,0,t.fontColor,0);break;case he:case le:case Be:case Qe:i=!0}}}catch(e){warn(`parseAppearanceStream - ignoring errors: "${e}".`)}this.stream.reset();delete t.scaleFactor;delete t.fillColorSpace;return t}get _localColorSpaceCache(){return shadow(this,"_localColorSpaceCache",new LocalColorSpaceCache)}get _pdfFunctionFactory(){return shadow(this,"_pdfFunctionFactory",new PDFFunctionFactory({xref:this.xref,isEvalSupported:this.evaluatorOptions.isEvalSupported}))}}function getPdfColor(e,t){if(e[0]===e[1]&&e[1]===e[2]){return`${numberToString(e[0]/255)} ${t?"g":"G"}`}return Array.from(e,(e=>numberToString(e/255))).join(" ")+" "+(t?"rg":"RG")}class FakeUnicodeFont{constructor(e,t){this.xref=e;this.widths=null;this.firstChar=1/0;this.lastChar=-1/0;this.fontFamily=t;const i=new OffscreenCanvas(1,1);this.ctxMeasure=i.getContext("2d",{willReadFrequently:!0});FakeUnicodeFont._fontNameId||(FakeUnicodeFont._fontNameId=1);this.fontName=Name.get(`InvalidPDFjsFont_${t}_${FakeUnicodeFont._fontNameId++}`)}get fontDescriptorRef(){if(!FakeUnicodeFont._fontDescriptorRef){const e=new Dict(this.xref);e.set("Type",Name.get("FontDescriptor"));e.set("FontName",this.fontName);e.set("FontFamily","MyriadPro Regular");e.set("FontBBox",[0,0,0,0]);e.set("FontStretch",Name.get("Normal"));e.set("FontWeight",400);e.set("ItalicAngle",0);FakeUnicodeFont._fontDescriptorRef=this.xref.getNewPersistentRef(e)}return FakeUnicodeFont._fontDescriptorRef}get descendantFontRef(){const e=new Dict(this.xref);e.set("BaseFont",this.fontName);e.set("Type",Name.get("Font"));e.set("Subtype",Name.get("CIDFontType0"));e.set("CIDToGIDMap",Name.get("Identity"));e.set("FirstChar",this.firstChar);e.set("LastChar",this.lastChar);e.set("FontDescriptor",this.fontDescriptorRef);e.set("DW",1e3);const t=[],i=[...this.widths.entries()].sort();let a=null,s=null;for(const[e,r]of i)if(a)if(e===a+s.length)s.push(r);else{t.push(a,s);a=e;s=[r]}else{a=e;s=[r]}a&&t.push(a,s);e.set("W",t);const r=new Dict(this.xref);r.set("Ordering","Identity");r.set("Registry","Adobe");r.set("Supplement",0);e.set("CIDSystemInfo",r);return this.xref.getNewPersistentRef(e)}get baseFontRef(){const e=new Dict(this.xref);e.set("BaseFont",this.fontName);e.set("Type",Name.get("Font"));e.set("Subtype",Name.get("Type0"));e.set("Encoding",Name.get("Identity-H"));e.set("DescendantFonts",[this.descendantFontRef]);e.set("ToUnicode",Name.get("Identity-H"));return this.xref.getNewPersistentRef(e)}get resources(){const e=new Dict(this.xref),t=new Dict(this.xref);t.set(this.fontName.name,this.baseFontRef);e.set("Font",t);return e}_createContext(){this.widths=new Map;this.ctxMeasure.font=`1000px ${this.fontFamily}`;return this.ctxMeasure}createFontResources(e){const t=this._createContext();for(const i of e.split(/\r\n?|\n/))for(const e of i.split("")){const i=e.charCodeAt(0);if(this.widths.has(i))continue;const a=t.measureText(e),s=Math.ceil(a.width);this.widths.set(i,s);this.firstChar=Math.min(i,this.firstChar);this.lastChar=Math.max(i,this.lastChar)}return this.resources}static getFirstPositionInfo(e,t,i){const[a,n,g,o]=e;let c=g-a,C=o-n;t%180!=0&&([c,C]=[C,c]);const h=s*i;return{coords:[0,C+r*i-h],bbox:[0,0,c,C],matrix:0!==t?getRotationMatrix(t,C,h):void 0}}createAppearance(e,t,i,a,n,g){const o=this._createContext(),c=[];let C=-1/0;for(const t of e.split(/\r\n?|\n/)){c.push(t);const e=o.measureText(t).width;C=Math.max(C,e);for(const e of codePointIter(t)){const t=String.fromCodePoint(e);let i=this.widths.get(e);if(void 0===i){const a=o.measureText(t);i=Math.ceil(a.width);this.widths.set(e,i);this.firstChar=Math.min(e,this.firstChar);this.lastChar=Math.max(e,this.lastChar)}}}C*=a/1e3;const[h,l,Q,E]=t;let u=Q-h,d=E-l;i%180!=0&&([u,d]=[d,u]);let f=1;C>u&&(f=u/C);let p=1;const m=s*a,y=r*a,w=m*c.length;w>d&&(p=d/w);const D=a*Math.min(f,p),b=["q",`0 0 ${numberToString(u)} ${numberToString(d)} re W n`,"BT",`1 0 0 1 0 ${numberToString(d+y)} Tm 0 Tc ${getPdfColor(n,!0)}`,`/${this.fontName.name} ${numberToString(D)} Tf`],{resources:F}=this;if(1!==(g="number"==typeof g&&g>=0&&g<=1?g:1)){b.push("/R0 gs");const e=new Dict(this.xref),t=new Dict(this.xref);t.set("ca",g);t.set("CA",g);t.set("Type",Name.get("ExtGState"));e.set("R0",t);F.set("ExtGState",e)}const S=numberToString(m);for(const e of c)b.push(`0 -${S} Td <${stringToUTF16HexString(e)}> Tj`);b.push("ET","Q");const k=b.join("\n"),R=new Dict(this.xref);R.set("Subtype",Name.get("Form"));R.set("Type",Name.get("XObject"));R.set("BBox",[0,0,u,d]);R.set("Length",k.length);R.set("Resources",F);if(i){const e=getRotationMatrix(i,u,d);R.set("Matrix",e)}const N=new StringStream(k);N.dict=R;return N}}class NameOrNumberTree{constructor(e,t,i){this.root=e;this.xref=t;this._type=i}getAll(){const e=new Map;if(!this.root)return e;const t=this.xref,i=new RefSet;i.put(this.root);const a=[this.root];for(;a.length>0;){const s=t.fetchIfRef(a.shift());if(!(s instanceof Dict))continue;if(s.has("Kids")){const e=s.get("Kids");if(!Array.isArray(e))continue;for(const t of e){if(i.has(t))throw new FormatError(`Duplicate entry in "${this._type}" tree.`);a.push(t);i.put(t)}continue}const r=s.get(this._type);if(Array.isArray(r))for(let i=0,a=r.length;i10){warn(`Search depth limit reached for "${this._type}" tree.`);return null}const s=i.get("Kids");if(!Array.isArray(s))return null;let r=0,n=s.length-1;for(;r<=n;){const a=r+n>>1,g=t.fetchIfRef(s[a]),o=g.get("Limits");if(et.fetchIfRef(o[1]))){i=g;break}r=a+1}}if(r>n)return null}const s=i.get(this._type);if(Array.isArray(s)){let i=0,a=s.length-2;for(;i<=a;){const r=i+a>>1,n=r+(1&r),g=t.fetchIfRef(s[n]);if(eg))return s[n+1];i=n+2}}}return null}get(e){return this.xref.fetchIfRef(this.getRaw(e))}}class NameTree extends NameOrNumberTree{constructor(e,t){super(e,t,"Names")}}class NumberTree extends NameOrNumberTree{constructor(e,t){super(e,t,"Nums")}}function clearGlobalCaches(){!function clearPatternCaches(){Qa=Object.create(null)}();!function clearPrimitiveCaches(){Qt=Object.create(null);Et=Object.create(null);ut=Object.create(null)}();!function clearUnicodeCaches(){ki.clear()}();JpxImage.cleanup()}function pickPlatformItem(e){return e instanceof Dict?e.has("UF")?e.get("UF"):e.has("F")?e.get("F"):e.has("Unix")?e.get("Unix"):e.has("Mac")?e.get("Mac"):e.has("DOS")?e.get("DOS"):null:null}class FileSpec{#U=!1;constructor(e,t,i=!1){if(e instanceof Dict){this.xref=t;this.root=e;e.has("FS")&&(this.fs=e.get("FS"));e.has("RF")&&warn("Related file specifications are not supported");i||(e.has("EF")?this.#U=!0:warn("Non-embedded file specifications are not supported"))}}get filename(){let e="";const t=pickPlatformItem(this.root);t&&"string"==typeof t&&(e=stringToPDFString(t).replaceAll("\\\\","\\").replaceAll("\\/","/").replaceAll("\\","/"));return shadow(this,"filename",e||"unnamed")}get content(){if(!this.#U)return null;this._contentRef||=pickPlatformItem(this.root?.get("EF"));let e=null;if(this._contentRef){const t=this.xref.fetchIfRef(this._contentRef);t instanceof BaseStream?e=t.getBytes():warn("Embedded file specification points to non-existing/invalid content")}else warn("Embedded file specification does not have any content");return e}get description(){let e="";const t=this.root?.get("Desc");t&&"string"==typeof t&&(e=stringToPDFString(t));return shadow(this,"description",e)}get serializable(){return{rawFilename:this.filename,filename:(e=this.filename,e.substring(e.lastIndexOf("/")+1)),content:this.content,description:this.description};var e}}const ys=0,ws=-2,Ds=-3,bs=-4,Fs=-5,Ss=-6,ks=-9;function isWhitespace(e,t){const i=e[t];return" "===i||"\n"===i||"\r"===i||"\t"===i}class XMLParserBase{_resolveEntities(e){return e.replaceAll(/&([^;]+);/g,((e,t)=>{if("#x"===t.substring(0,2))return String.fromCodePoint(parseInt(t.substring(2),16));if("#"===t.substring(0,1))return String.fromCodePoint(parseInt(t.substring(1),10));switch(t){case"lt":return"<";case"gt":return">";case"amp":return"&";case"quot":return'"';case"apos":return"'"}return this.onResolveEntity(t)}))}_parseContent(e,t){const i=[];let a=t;function skipWs(){for(;a"!==e[a]&&"/"!==e[a];)++a;const s=e.substring(t,a);skipWs();for(;a"!==e[a]&&"/"!==e[a]&&"?"!==e[a];){skipWs();let t="",s="";for(;a"!==e[i]&&"?"!==e[i]&&"/"!==e[i];)++i;const a=e.substring(t,i);!function skipWs(){for(;i"!==e[i+1]);)++i;return{name:a,value:e.substring(s,i),parsed:i-t}}parseXml(e){let t=0;for(;t",i);if(t<0){this.onError(ks);return}this.onEndElement(e.substring(i,t));i=t+1;break;case"?":++i;const a=this._parseProcessingInstruction(e,i);if("?>"!==e.substring(i+a.parsed,i+a.parsed+2)){this.onError(Ds);return}this.onPi(a.name,a.value);i+=a.parsed+2;break;case"!":if("--"===e.substring(i+1,i+3)){t=e.indexOf("--\x3e",i+3);if(t<0){this.onError(Fs);return}this.onComment(e.substring(i+3,t));i=t+3}else if("[CDATA["===e.substring(i+1,i+8)){t=e.indexOf("]]>",i+8);if(t<0){this.onError(ws);return}this.onCdata(e.substring(i+8,t));i=t+3}else{if("DOCTYPE"!==e.substring(i+1,i+8)){this.onError(Ss);return}{const a=e.indexOf("[",i+8);let s=!1;t=e.indexOf(">",i+8);if(t<0){this.onError(bs);return}if(a>0&&t>a){t=e.indexOf("]>",i+8);if(t<0){this.onError(bs);return}s=!0}const r=e.substring(i+8,t+(s?1:0));this.onDoctype(r);i=t+(s?2:1)}}break;default:const s=this._parseContent(e,i);if(null===s){this.onError(Ss);return}let r=!1;if("/>"===e.substring(i+s.parsed,i+s.parsed+2))r=!0;else if(">"!==e.substring(i+s.parsed,i+s.parsed+1)){this.onError(ks);return}this.onBeginElement(s.name,s.attributes,r);i+=s.parsed+(r?2:1)}}else{for(;i0}searchNode(e,t){if(t>=e.length)return this;const i=e[t];if(i.name.startsWith("#")&&t0){a.push([s,0]);s=s.childNodes[0]}else{if(0===a.length)return null;for(;0!==a.length;){const[e,t]=a.pop(),i=t+1;if(i");for(const t of this.childNodes)t.dump(e);e.push(``)}else this.nodeValue?e.push(`>${encodeToXmlString(this.nodeValue)}`):e.push("/>")}else e.push(encodeToXmlString(this.nodeValue))}}class SimpleXMLParser extends XMLParserBase{constructor({hasAttributes:e=!1,lowerCaseName:t=!1}){super();this._currentFragment=null;this._stack=null;this._errorCode=ys;this._hasAttributes=e;this._lowerCaseName=t}parseFromString(e){this._currentFragment=[];this._stack=[];this._errorCode=ys;this.parseXml(e);if(this._errorCode!==ys)return;const[t]=this._currentFragment;return t?{documentElement:t}:void 0}onText(e){if(function isWhitespaceString(e){for(let t=0,i=e.length;t\\376\\377([^<]+)/g,(function(e,t){const i=t.replaceAll(/\\([0-3])([0-7])([0-7])/g,(function(e,t,i,a){return String.fromCharCode(64*t+8*i+1*a)})).replaceAll(/&(amp|apos|gt|lt|quot);/g,(function(e,t){switch(t){case"amp":return"&";case"apos":return"'";case"gt":return">";case"lt":return"<";case"quot":return'"'}throw new Error(`_repair: ${t} isn't defined.`)})),a=[">"];for(let e=0,t=i.length;e=32&&t<127&&60!==t&&62!==t&&38!==t?a.push(String.fromCharCode(t)):a.push("&#x"+(65536+t).toString(16).substring(1)+";")}return a.join("")}))}_getSequence(e){const t=e.nodeName;return"rdf:bag"!==t&&"rdf:seq"!==t&&"rdf:alt"!==t?null:e.childNodes.filter((e=>"rdf:li"===e.nodeName))}_parseArray(e){if(!e.hasChildNodes())return;const[t]=e.childNodes,i=this._getSequence(t)||[];this._metadataMap.set(e.nodeName,i.map((e=>e.textContent.trim())))}_parse(e){let t=e.documentElement;if("rdf:rdf"!==t.nodeName){t=t.firstChild;for(;t&&"rdf:rdf"!==t.nodeName;)t=t.nextSibling}if(t&&"rdf:rdf"===t.nodeName&&t.hasChildNodes())for(const e of t.childNodes)if("rdf:description"===e.nodeName)for(const t of e.childNodes){const e=t.nodeName;switch(e){case"#text":continue;case"dc:creator":case"dc:subject":this._parseArray(t);continue}this._metadataMap.set(e,t.textContent.trim())}}get serializable(){return{parsedData:this._metadataMap,rawData:this._data}}}const Rs=1,Ns=2,Gs=3,Ms=4,Us=5;class StructTreeRoot{constructor(e,t){this.dict=e;this.ref=t instanceof Ref?t:null;this.roleMap=new Map;this.structParentIds=null}init(){this.readRoleMap()}#x(e,t,i){if(!(e instanceof Ref)||t<0)return;this.structParentIds||=new RefSetCache;let a=this.structParentIds.get(e);if(!a){a=[];this.structParentIds.put(e,a)}a.push([t,i])}addAnnotationIdToPage(e,t){this.#x(e,t,Ms)}readRoleMap(){const e=this.dict.get("RoleMap");if(e instanceof Dict)for(const[t,i]of e)i instanceof Name&&this.roleMap.set(t,i.name)}static async canCreateStructureTree({catalogRef:e,pdfManager:t,newAnnotationsByPage:i}){if(!(e instanceof Ref)){warn("Cannot save the struct tree: no catalog reference.");return!1}let a=0,s=!0;for(const[e,r]of i){const{ref:i}=await t.getPage(e);if(!(i instanceof Ref)){warn(`Cannot save the struct tree: page ${e} has no ref.`);s=!0;break}for(const e of r)if(e.accessibilityData?.type){e.parentTreeId=a++;s=!1}}if(s){for(const e of i.values())for(const t of e)delete t.parentTreeId;return!1}return!0}static async createStructureTree({newAnnotationsByPage:e,xref:t,catalogRef:i,pdfManager:a,changes:s}){const r=a.catalog.cloneDict(),n=new RefSetCache;n.put(i,r);const g=t.getNewTemporaryRef();r.set("StructTreeRoot",g);const o=new Dict(t);o.set("Type",Name.get("StructTreeRoot"));const c=t.getNewTemporaryRef();o.set("ParentTree",c);const C=[];o.set("K",C);n.put(g,o);const h=new Dict(t),l=[];h.set("Nums",l);const Q=await this.#L({newAnnotationsByPage:e,structTreeRootRef:g,structTreeRoot:null,kids:C,nums:l,xref:t,pdfManager:a,changes:s,cache:n});o.set("ParentTreeNextKey",Q);n.put(c,h);for(const[e,t]of n.items())s.put(e,{data:t})}async canUpdateStructTree({pdfManager:e,xref:t,newAnnotationsByPage:i}){if(!this.ref){warn("Cannot update the struct tree: no root reference.");return!1}let a=this.dict.get("ParentTreeNextKey");if(!Number.isInteger(a)||a<0){warn("Cannot update the struct tree: invalid next key.");return!1}const s=this.dict.get("ParentTree");if(!(s instanceof Dict)){warn("Cannot update the struct tree: ParentTree isn't a dict.");return!1}const r=s.get("Nums");if(!Array.isArray(r)){warn("Cannot update the struct tree: nums isn't an array.");return!1}const n=new NumberTree(s,t);for(const t of i.keys()){const{pageDict:i}=await e.getPage(t);if(!i.has("StructParents"))continue;const a=i.get("StructParents");if(!Number.isInteger(a)||!Array.isArray(n.get(a))){warn(`Cannot save the struct tree: page ${t} has a wrong id.`);return!1}}let g=!0;for(const[t,s]of i){const{pageDict:i}=await e.getPage(t);StructTreeRoot.#H({elements:s,xref:this.dict.xref,pageDict:i,numberTree:n});for(const e of s)if(e.accessibilityData?.type){e.accessibilityData.structParent>=0||(e.parentTreeId=a++);g=!1}}if(g){for(const e of i.values())for(const t of e){delete t.parentTreeId;delete t.structTreeParent}return!1}return!0}async updateStructureTree({newAnnotationsByPage:e,pdfManager:t,changes:i}){const a=this.dict.xref,s=this.dict.clone(),r=this.ref,n=new RefSetCache;n.put(r,s);let g,o=s.getRaw("ParentTree");if(o instanceof Ref)g=a.fetch(o);else{g=o;o=a.getNewTemporaryRef();s.set("ParentTree",o)}g=g.clone();n.put(o,g);let c=g.getRaw("Nums"),C=null;if(c instanceof Ref){C=c;c=a.fetch(C)}c=c.slice();C||g.set("Nums",c);const h=await StructTreeRoot.#L({newAnnotationsByPage:e,structTreeRootRef:r,structTreeRoot:this,kids:null,nums:c,xref:a,pdfManager:t,changes:i,cache:n});if(-1!==h){s.set("ParentTreeNextKey",h);C&&n.put(C,c);for(const[e,t]of n.items())i.put(e,{data:t})}}static async#L({newAnnotationsByPage:e,structTreeRootRef:t,structTreeRoot:i,kids:a,nums:s,xref:r,pdfManager:n,changes:g,cache:o}){const c=Name.get("OBJR");let C,h=-1;for(const[l,Q]of e){const e=await n.getPage(l),{ref:E}=e,u=E instanceof Ref;for(const{accessibilityData:n,ref:d,parentTreeId:f,structTreeParent:p}of Q){if(!n?.type)continue;const{structParent:Q}=n;if(i&&Number.isInteger(Q)&&Q>=0){let t=(C||=new Map).get(l);if(void 0===t){t=new StructTreePage(i,e.pageDict).collectObjects(E);C.set(l,t)}const a=t?.get(Q);if(a){const e=r.fetch(a).clone();StructTreeRoot.#J(e,n);g.put(a,{data:e});continue}}h=Math.max(h,f);const m=r.getNewTemporaryRef(),y=new Dict(r);StructTreeRoot.#J(y,n);await this.#Y({structTreeParent:p,tagDict:y,newTagRef:m,structTreeRootRef:t,fallbackKids:a,xref:r,cache:o});const w=new Dict(r);y.set("K",w);w.set("Type",c);u&&w.set("Pg",E);w.set("Obj",d);o.put(m,y);s.push(f,m)}}return h+1}static#J(e,{type:t,title:i,lang:a,alt:s,expanded:r,actualText:n}){e.set("S",Name.get(t));i&&e.set("T",stringToAsciiOrUTF16BE(i));a&&e.set("Lang",stringToAsciiOrUTF16BE(a));s&&e.set("Alt",stringToAsciiOrUTF16BE(s));r&&e.set("E",stringToAsciiOrUTF16BE(r));n&&e.set("ActualText",stringToAsciiOrUTF16BE(n))}static#H({elements:e,xref:t,pageDict:i,numberTree:a}){const s=new Map;for(const t of e)if(t.structTreeParentId){const e=parseInt(t.structTreeParentId.split("_mc")[1],10);let i=s.get(e);if(!i){i=[];s.set(e,i)}i.push(t)}const r=i.get("StructParents");if(!Number.isInteger(r))return;const n=a.get(r),updateElement=(e,i,a)=>{const r=s.get(e);if(r){const e=i.getRaw("P"),s=t.fetchIfRef(e);if(e instanceof Ref&&s instanceof Dict){const e={ref:a,dict:i};for(const t of r)t.structTreeParent=e}return!0}return!1};for(const e of n){if(!(e instanceof Ref))continue;const i=t.fetch(e),a=i.get("K");if(Number.isInteger(a))updateElement(a,i,e);else if(Array.isArray(a))for(let s of a){s=t.fetchIfRef(s);if(Number.isInteger(s)&&updateElement(s,i,e))break;if(!(s instanceof Dict))continue;if(!isName(s.get("Type"),"MCR"))break;const a=s.get("MCID");if(Number.isInteger(a)&&updateElement(a,i,e))break}}}static async#Y({structTreeParent:e,tagDict:t,newTagRef:i,structTreeRootRef:a,fallbackKids:s,xref:r,cache:n}){let g,o=null;if(e){({ref:o}=e);g=e.dict.getRaw("P")||a}else g=a;t.set("P",g);const c=r.fetchIfRef(g);if(!c){s.push(i);return}let C=n.get(g);if(!C){C=c.clone();n.put(g,C)}const h=C.getRaw("K");let l=h instanceof Ref?n.get(h):null;if(!l){l=r.fetchIfRef(h);l=Array.isArray(l)?l.slice():[h];const e=r.getNewTemporaryRef();C.set("K",e);n.put(e,l)}const Q=l.indexOf(o);l.splice(Q>=0?Q+1:l.length,0,i)}}class StructElementNode{constructor(e,t){this.tree=e;this.dict=t;this.kids=[];this.parseKids()}get role(){const e=this.dict.get("S"),t=e instanceof Name?e.name:"",{root:i}=this.tree;return i.roleMap.has(t)?i.roleMap.get(t):t}parseKids(){let e=null;const t=this.dict.getRaw("Pg");t instanceof Ref&&(e=t.toString());const i=this.dict.get("K");if(Array.isArray(i))for(const t of i){const i=this.parseKid(e,t);i&&this.kids.push(i)}else{const t=this.parseKid(e,i);t&&this.kids.push(t)}}parseKid(e,t){if(Number.isInteger(t))return this.tree.pageDict.objId!==e?null:new StructElement({type:Rs,mcid:t,pageObjId:e});let i=null;t instanceof Ref?i=this.dict.xref.fetch(t):t instanceof Dict&&(i=t);if(!i)return null;const a=i.getRaw("Pg");a instanceof Ref&&(e=a.toString());const s=i.get("Type")instanceof Name?i.get("Type").name:null;if("MCR"===s){if(this.tree.pageDict.objId!==e)return null;const t=i.getRaw("Stm");return new StructElement({type:Ns,refObjId:t instanceof Ref?t.toString():null,pageObjId:e,mcid:i.get("MCID")})}if("OBJR"===s){if(this.tree.pageDict.objId!==e)return null;const t=i.getRaw("Obj");return new StructElement({type:Gs,refObjId:t instanceof Ref?t.toString():null,pageObjId:e})}return new StructElement({type:Us,dict:i})}}class StructElement{constructor({type:e,dict:t=null,mcid:i=null,pageObjId:a=null,refObjId:s=null}){this.type=e;this.dict=t;this.mcid=i;this.pageObjId=a;this.refObjId=s;this.parentNode=null}}class StructTreePage{constructor(e,t){this.root=e;this.rootDict=e?e.dict:null;this.pageDict=t;this.nodes=[]}collectObjects(e){if(!(this.root&&this.rootDict&&e instanceof Ref))return null;const t=this.rootDict.get("ParentTree");if(!t)return null;const i=this.root.structParentIds?.get(e);if(!i)return null;const a=new Map,s=new NumberTree(t,this.rootDict.xref);for(const[e]of i){const t=s.getRaw(e);t instanceof Ref&&a.set(e,t)}return a}parse(e){if(!(this.root&&this.rootDict&&e instanceof Ref))return;const t=this.rootDict.get("ParentTree");if(!t)return;const i=this.pageDict.get("StructParents"),a=this.root.structParentIds?.get(e);if(!Number.isInteger(i)&&!a)return;const s=new Map,r=new NumberTree(t,this.rootDict.xref);if(Number.isInteger(i)){const e=r.get(i);if(Array.isArray(e))for(const t of e)t instanceof Ref&&this.addNode(this.rootDict.xref.fetch(t),s)}if(a)for(const[e,t]of a){const i=r.get(e);if(i){const e=this.addNode(this.rootDict.xref.fetchIfRef(i),s);1===e?.kids?.length&&e.kids[0].type===Gs&&(e.kids[0].type=t)}}}addNode(e,t,i=0){if(i>40){warn("StructTree MAX_DEPTH reached.");return null}if(!(e instanceof Dict))return null;if(t.has(e))return t.get(e);const a=new StructElementNode(this,e);t.set(e,a);const s=e.get("P");if(!s||isName(s.get("Type"),"StructTreeRoot")){this.addTopLevelNode(e,a)||t.delete(e);return a}const r=this.addNode(s,t,i+1);if(!r)return a;let n=!1;for(const t of r.kids)if(t.type===Us&&t.dict===e){t.parentNode=a;n=!0}n||t.delete(e);return a}addTopLevelNode(e,t){const i=this.rootDict.get("K");if(!i)return!1;if(i instanceof Dict){if(i.objId!==e.objId)return!1;this.nodes[0]=t;return!0}if(!Array.isArray(i))return!0;let a=!1;for(let s=0;s40){warn("StructTree too deep to be fully serialized.");return}const a=Object.create(null);a.role=e.role;a.children=[];t.children.push(a);let s=e.dict.get("Alt");"string"!=typeof s&&(s=e.dict.get("ActualText"));"string"==typeof s&&(a.alt=stringToPDFString(s));const r=e.dict.get("A");if(r instanceof Dict){const e=lookupNormalRect(r.getArray("BBox"),null);if(e)a.bbox=e;else{const e=r.get("Width"),t=r.get("Height");"number"==typeof e&&e>0&&"number"==typeof t&&t>0&&(a.bbox=[0,0,e,t])}}const n=e.dict.get("Lang");"string"==typeof n&&(a.lang=stringToPDFString(n));for(const t of e.kids){const e=t.type===Us?t.parentNode:null;e?nodeToSerializable(e,a,i+1):t.type===Rs||t.type===Ns?a.children.push({type:"content",id:`p${t.pageObjId}_mc${t.mcid}`}):t.type===Gs?a.children.push({type:"object",id:t.refObjId}):t.type===Ms&&a.children.push({type:"annotation",id:`pdfjs_internal_id_${t.refObjId}`})}}const e=Object.create(null);e.children=[];e.role="Root";for(const t of this.nodes)t&&nodeToSerializable(t,e);return e}}function isValidExplicitDest(e){if(!Array.isArray(e)||e.length<2)return!1;const[t,i,...a]=e;if(!(t instanceof Ref||Number.isInteger(t)))return!1;if(!(i instanceof Name))return!1;const s=a.length;let r=!0;switch(i.name){case"XYZ":if(s<2||s>3)return!1;break;case"Fit":case"FitB":return 0===s;case"FitH":case"FitBH":case"FitV":case"FitBV":if(s>1)return!1;break;case"FitR":if(4!==s)return!1;r=!1;break;default:return!1}for(const e of a)if(!("number"==typeof e||r&&null===e))return!1;return!0}function fetchDest(e){e instanceof Dict&&(e=e.get("D"));return isValidExplicitDest(e)?e:null}function fetchRemoteDest(e){let t=e.get("D");if(t){t instanceof Name&&(t=t.name);if("string"==typeof t)return stringToPDFString(t);if(isValidExplicitDest(t))return JSON.stringify(t)}return null}class Catalog{constructor(e,t){this.pdfManager=e;this.xref=t;this._catDict=t.getCatalogObj();if(!(this._catDict instanceof Dict))throw new FormatError("Catalog object is not a dictionary.");this.toplevelPagesDict;this._actualNumPages=null;this.fontCache=new RefSetCache;this.builtInCMapCache=new Map;this.standardFontDataCache=new Map;this.globalImageCache=new GlobalImageCache;this.pageKidsCountCache=new RefSetCache;this.pageIndexCache=new RefSetCache;this.pageDictCache=new RefSetCache;this.nonBlendModesSet=new RefSet;this.systemFontCache=new Map}cloneDict(){return this._catDict.clone()}get version(){const e=this._catDict.get("Version");if(e instanceof Name){if(ft.test(e.name))return shadow(this,"version",e.name);warn(`Invalid PDF catalog version: ${e.name}`)}return shadow(this,"version",null)}get lang(){const e=this._catDict.get("Lang");return shadow(this,"lang",e&&"string"==typeof e?stringToPDFString(e):null)}get needsRendering(){const e=this._catDict.get("NeedsRendering");return shadow(this,"needsRendering","boolean"==typeof e&&e)}get collection(){let e=null;try{const t=this._catDict.get("Collection");t instanceof Dict&&t.size>0&&(e=t)}catch(e){if(e instanceof MissingDataException)throw e;info("Cannot fetch Collection entry; assuming no collection is present.")}return shadow(this,"collection",e)}get acroForm(){let e=null;try{const t=this._catDict.get("AcroForm");t instanceof Dict&&t.size>0&&(e=t)}catch(e){if(e instanceof MissingDataException)throw e;info("Cannot fetch AcroForm entry; assuming no forms are present.")}return shadow(this,"acroForm",e)}get acroFormRef(){const e=this._catDict.getRaw("AcroForm");return shadow(this,"acroFormRef",e instanceof Ref?e:null)}get metadata(){const e=this._catDict.getRaw("Metadata");if(!(e instanceof Ref))return shadow(this,"metadata",null);let t=null;try{const i=this.xref.fetch(e,!this.xref.encrypt?.encryptMetadata);if(i instanceof BaseStream&&i.dict instanceof Dict){const e=i.dict.get("Type"),a=i.dict.get("Subtype");if(isName(e,"Metadata")&&isName(a,"XML")){const e=stringToUTF8String(i.getString());e&&(t=new MetadataParser(e).serializable)}}}catch(e){if(e instanceof MissingDataException)throw e;info(`Skipping invalid Metadata: "${e}".`)}return shadow(this,"metadata",t)}get markInfo(){let e=null;try{e=this._readMarkInfo()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read mark info.")}return shadow(this,"markInfo",e)}_readMarkInfo(){const e=this._catDict.get("MarkInfo");if(!(e instanceof Dict))return null;const t={Marked:!1,UserProperties:!1,Suspects:!1};for(const i in t){const a=e.get(i);"boolean"==typeof a&&(t[i]=a)}return t}get structTreeRoot(){let e=null;try{e=this._readStructTreeRoot()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable read to structTreeRoot info.")}return shadow(this,"structTreeRoot",e)}_readStructTreeRoot(){const e=this._catDict.getRaw("StructTreeRoot"),t=this.xref.fetchIfRef(e);if(!(t instanceof Dict))return null;const i=new StructTreeRoot(t,e);i.init();return i}get toplevelPagesDict(){const e=this._catDict.get("Pages");if(!(e instanceof Dict))throw new FormatError("Invalid top-level pages dictionary.");return shadow(this,"toplevelPagesDict",e)}get documentOutline(){let e=null;try{e=this._readDocumentOutline()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read document outline.")}return shadow(this,"documentOutline",e)}_readDocumentOutline(){let e=this._catDict.get("Outlines");if(!(e instanceof Dict))return null;e=e.getRaw("First");if(!(e instanceof Ref))return null;const t={items:[]},i=[{obj:e,parent:t}],a=new RefSet;a.put(e);const s=this.xref,r=new Uint8ClampedArray(3);for(;i.length>0;){const t=i.shift(),n=s.fetchIfRef(t.obj);if(null===n)continue;n.has("Title")||warn("Invalid outline item encountered.");const g={url:null,dest:null,action:null};Catalog.parseDestDictionary({destDict:n,resultObj:g,docBaseUrl:this.baseUrl,docAttachments:this.attachments});const o=n.get("Title"),c=n.get("F")||0,C=n.getArray("C"),h=n.get("Count");let l=r;!isNumberArray(C,3)||0===C[0]&&0===C[1]&&0===C[2]||(l=ColorSpace.singletons.rgb.getRgb(C,0));const Q={action:g.action,attachment:g.attachment,dest:g.dest,url:g.url,unsafeUrl:g.unsafeUrl,newWindow:g.newWindow,setOCGState:g.setOCGState,title:"string"==typeof o?stringToPDFString(o):"",color:l,count:Number.isInteger(h)?h:void 0,bold:!!(2&c),italic:!!(1&c),items:[]};t.parent.items.push(Q);e=n.getRaw("First");if(e instanceof Ref&&!a.has(e)){i.push({obj:e,parent:Q});a.put(e)}e=n.getRaw("Next");if(e instanceof Ref&&!a.has(e)){i.push({obj:e,parent:t.parent});a.put(e)}}return t.items.length>0?t.items:null}get permissions(){let e=null;try{e=this._readPermissions()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read permissions.")}return shadow(this,"permissions",e)}_readPermissions(){const e=this.xref.trailer.get("Encrypt");if(!(e instanceof Dict))return null;let t=e.get("P");if("number"!=typeof t)return null;t+=2**32;const i=[];for(const e in y){const a=y[e];t&a&&i.push(a)}return i}get optionalContentConfig(){let e=null;try{const t=this._catDict.get("OCProperties");if(!t)return shadow(this,"optionalContentConfig",null);const i=t.get("D");if(!i)return shadow(this,"optionalContentConfig",null);const a=t.get("OCGs");if(!Array.isArray(a))return shadow(this,"optionalContentConfig",null);const s=new RefSetCache;for(const e of a)e instanceof Ref&&!s.has(e)&&s.put(e,this.#v(e));e=this.#K(i,s)}catch(e){if(e instanceof MissingDataException)throw e;warn(`Unable to read optional content config: ${e}`)}return shadow(this,"optionalContentConfig",e)}#v(e){const t=this.xref.fetch(e),i={id:e.toString(),name:null,intent:null,usage:{print:null,view:null},rbGroups:[]},a=t.get("Name");"string"==typeof a&&(i.name=stringToPDFString(a));let s=t.getArray("Intent");Array.isArray(s)||(s=[s]);s.every((e=>e instanceof Name))&&(i.intent=s.map((e=>e.name)));const r=t.get("Usage");if(!(r instanceof Dict))return i;const n=i.usage,g=r.get("Print");if(g instanceof Dict){const e=g.get("PrintState");if(e instanceof Name)switch(e.name){case"ON":case"OFF":n.print={printState:e.name}}}const o=r.get("View");if(o instanceof Dict){const e=o.get("ViewState");if(e instanceof Name)switch(e.name){case"ON":case"OFF":n.view={viewState:e.name}}}return i}#K(e,t){function parseOnOff(e){const i=[];if(Array.isArray(e))for(const a of e)a instanceof Ref&&t.has(a)&&i.push(a.toString());return i}function parseOrder(e,i=0){if(!Array.isArray(e))return null;const s=[];for(const r of e){if(r instanceof Ref&&t.has(r)){a.put(r);s.push(r.toString());continue}const e=parseNestedOrder(r,i);e&&s.push(e)}if(i>0)return s;const r=[];for(const[e]of t.items())a.has(e)||r.push(e.toString());r.length&&s.push({name:null,order:r});return s}function parseNestedOrder(e,t){if(++t>s){warn("parseNestedOrder - reached MAX_NESTED_LEVELS.");return null}const a=i.fetchIfRef(e);if(!Array.isArray(a))return null;const r=i.fetchIfRef(a[0]);if("string"!=typeof r)return null;const n=parseOrder(a.slice(1),t);return n?.length?{name:stringToPDFString(r),order:n}:null}const i=this.xref,a=new RefSet,s=10;!function parseRBGroups(e){if(Array.isArray(e))for(const a of e){const e=i.fetchIfRef(a);if(!Array.isArray(e)||!e.length)continue;const s=new Set;for(const i of e)if(i instanceof Ref&&t.has(i)&&!s.has(i.toString())){s.add(i.toString());t.get(i).rbGroups.push(s)}}}(e.get("RBGroups"));return{name:"string"==typeof e.get("Name")?stringToPDFString(e.get("Name")):null,creator:"string"==typeof e.get("Creator")?stringToPDFString(e.get("Creator")):null,baseState:e.get("BaseState")instanceof Name?e.get("BaseState").name:null,on:parseOnOff(e.get("ON")),off:parseOnOff(e.get("OFF")),order:parseOrder(e.get("Order")),groups:[...t]}}setActualNumPages(e=null){this._actualNumPages=e}get hasActualNumPages(){return null!==this._actualNumPages}get _pagesCount(){const e=this.toplevelPagesDict.get("Count");if(!Number.isInteger(e))throw new FormatError("Page count in top-level pages dictionary is not an integer.");return shadow(this,"_pagesCount",e)}get numPages(){return this.hasActualNumPages?this._actualNumPages:this._pagesCount}get destinations(){const e=this._readDests(),t=Object.create(null);if(e instanceof NameTree)for(const[i,a]of e.getAll()){const e=fetchDest(a);e&&(t[stringToPDFString(i)]=e)}else if(e instanceof Dict)for(const[i,a]of e){const e=fetchDest(a);e&&(t[i]=e)}return shadow(this,"destinations",t)}getDestination(e){const t=this._readDests();if(t instanceof NameTree){const i=fetchDest(t.get(e));if(i)return i;const a=this.destinations[e];if(a){warn(`Found "${e}" at an incorrect position in the NameTree.`);return a}}else if(t instanceof Dict){const i=fetchDest(t.get(e));if(i)return i}return null}_readDests(){const e=this._catDict.get("Names");return e?.has("Dests")?new NameTree(e.getRaw("Dests"),this.xref):this._catDict.has("Dests")?this._catDict.get("Dests"):void 0}get pageLabels(){let e=null;try{e=this._readPageLabels()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read page labels.")}return shadow(this,"pageLabels",e)}_readPageLabels(){const e=this._catDict.getRaw("PageLabels");if(!e)return null;const t=new Array(this.numPages);let i=null,a="";const s=new NumberTree(e,this.xref).getAll();let r="",n=1;for(let e=0,g=this.numPages;e=1))throw new FormatError("Invalid start in PageLabel dictionary.");n=e}else n=1}switch(i){case"D":r=n;break;case"R":case"r":r=toRomanNumerals(n,"r"===i);break;case"A":case"a":const e=26,t="a"===i?97:65,a=n-1;r=String.fromCharCode(t+a%e).repeat(Math.floor(a/e)+1);break;default:if(i)throw new FormatError(`Invalid style "${i}" in PageLabel dictionary.`);r=""}t[e]=a+r;n++}return t}get pageLayout(){const e=this._catDict.get("PageLayout");let t="";if(e instanceof Name)switch(e.name){case"SinglePage":case"OneColumn":case"TwoColumnLeft":case"TwoColumnRight":case"TwoPageLeft":case"TwoPageRight":t=e.name}return shadow(this,"pageLayout",t)}get pageMode(){const e=this._catDict.get("PageMode");let t="UseNone";if(e instanceof Name)switch(e.name){case"UseNone":case"UseOutlines":case"UseThumbs":case"FullScreen":case"UseOC":case"UseAttachments":t=e.name}return shadow(this,"pageMode",t)}get viewerPreferences(){const e=this._catDict.get("ViewerPreferences");if(!(e instanceof Dict))return shadow(this,"viewerPreferences",null);let t=null;for(const i of e.getKeys()){const a=e.get(i);let s;switch(i){case"HideToolbar":case"HideMenubar":case"HideWindowUI":case"FitWindow":case"CenterWindow":case"DisplayDocTitle":case"PickTrayByPDFSize":"boolean"==typeof a&&(s=a);break;case"NonFullScreenPageMode":if(a instanceof Name)switch(a.name){case"UseNone":case"UseOutlines":case"UseThumbs":case"UseOC":s=a.name;break;default:s="UseNone"}break;case"Direction":if(a instanceof Name)switch(a.name){case"L2R":case"R2L":s=a.name;break;default:s="L2R"}break;case"ViewArea":case"ViewClip":case"PrintArea":case"PrintClip":if(a instanceof Name)switch(a.name){case"MediaBox":case"CropBox":case"BleedBox":case"TrimBox":case"ArtBox":s=a.name;break;default:s="CropBox"}break;case"PrintScaling":if(a instanceof Name)switch(a.name){case"None":case"AppDefault":s=a.name;break;default:s="AppDefault"}break;case"Duplex":if(a instanceof Name)switch(a.name){case"Simplex":case"DuplexFlipShortEdge":case"DuplexFlipLongEdge":s=a.name;break;default:s="None"}break;case"PrintPageRange":if(Array.isArray(a)&&a.length%2==0){a.every(((e,t,i)=>Number.isInteger(e)&&e>0&&(0===t||e>=i[t-1])&&e<=this.numPages))&&(s=a)}break;case"NumCopies":Number.isInteger(a)&&a>0&&(s=a);break;default:warn(`Ignoring non-standard key in ViewerPreferences: ${i}.`);continue}if(void 0!==s){t||(t=Object.create(null));t[i]=s}else warn(`Bad value, for key "${i}", in ViewerPreferences: ${a}.`)}return shadow(this,"viewerPreferences",t)}get openAction(){const e=this._catDict.get("OpenAction"),t=Object.create(null);if(e instanceof Dict){const i=new Dict(this.xref);i.set("A",e);const a={url:null,dest:null,action:null};Catalog.parseDestDictionary({destDict:i,resultObj:a});Array.isArray(a.dest)?t.dest=a.dest:a.action&&(t.action=a.action)}else Array.isArray(e)&&(t.dest=e);return shadow(this,"openAction",objectSize(t)>0?t:null)}get attachments(){const e=this._catDict.get("Names");let t=null;if(e instanceof Dict&&e.has("EmbeddedFiles")){const i=new NameTree(e.getRaw("EmbeddedFiles"),this.xref);for(const[e,a]of i.getAll()){const i=new FileSpec(a,this.xref);t||(t=Object.create(null));t[stringToPDFString(e)]=i.serializable}}return shadow(this,"attachments",t)}get xfaImages(){const e=this._catDict.get("Names");let t=null;if(e instanceof Dict&&e.has("XFAImages")){const i=new NameTree(e.getRaw("XFAImages"),this.xref);for(const[e,a]of i.getAll()){t||(t=new Dict(this.xref));t.set(stringToPDFString(e),a)}}return shadow(this,"xfaImages",t)}_collectJavaScript(){const e=this._catDict.get("Names");let t=null;function appendIfJavaScriptDict(e,i){if(!(i instanceof Dict))return;if(!isName(i.get("S"),"JavaScript"))return;let a=i.get("JS");if(a instanceof BaseStream)a=a.getString();else if("string"!=typeof a)return;a=stringToPDFString(a).replaceAll("\0","");a&&(t||=new Map).set(e,a)}if(e instanceof Dict&&e.has("JavaScript")){const t=new NameTree(e.getRaw("JavaScript"),this.xref);for(const[e,i]of t.getAll())appendIfJavaScriptDict(stringToPDFString(e),i)}const i=this._catDict.get("OpenAction");i&&appendIfJavaScriptDict("OpenAction",i);return t}get jsActions(){const e=this._collectJavaScript();let t=collectActions(this.xref,this._catDict,fA);if(e){t||=Object.create(null);for(const[i,a]of e)i in t?t[i].push(a):t[i]=[a]}return shadow(this,"jsActions",t)}async fontFallback(e,t){const i=await Promise.all(this.fontCache);for(const a of i)if(a.loadedName===e){a.fallback(t);return}}async cleanup(e=!1){clearGlobalCaches();this.globalImageCache.clear(e);this.pageKidsCountCache.clear();this.pageIndexCache.clear();this.pageDictCache.clear();this.nonBlendModesSet.clear();const t=await Promise.all(this.fontCache);for(const{dict:e}of t)delete e.cacheKey;this.fontCache.clear();this.builtInCMapCache.clear();this.standardFontDataCache.clear();this.systemFontCache.clear()}async getPageDict(e){const t=[this.toplevelPagesDict],i=new RefSet,a=this._catDict.getRaw("Pages");a instanceof Ref&&i.put(a);const s=this.xref,r=this.pageKidsCountCache,n=this.pageIndexCache,g=this.pageDictCache;let o=0;for(;t.length;){const a=t.pop();if(a instanceof Ref){const c=r.get(a);if(c>=0&&o+c<=e){o+=c;continue}if(i.has(a))throw new FormatError("Pages tree contains circular reference.");i.put(a);const C=await(g.get(a)||s.fetchAsync(a));if(C instanceof Dict){let t=C.getRaw("Type");t instanceof Ref&&(t=await s.fetchAsync(t));if(isName(t,"Page")||!C.has("Kids")){r.has(a)||r.put(a,1);n.has(a)||n.put(a,o);if(o===e)return[C,a];o++;continue}}t.push(C);continue}if(!(a instanceof Dict))throw new FormatError("Page dictionary kid reference points to wrong type of object.");const{objId:c}=a;let C=a.getRaw("Count");C instanceof Ref&&(C=await s.fetchAsync(C));if(Number.isInteger(C)&&C>=0){c&&!r.has(c)&&r.put(c,C);if(o+C<=e){o+=C;continue}}let h=a.getRaw("Kids");h instanceof Ref&&(h=await s.fetchAsync(h));if(!Array.isArray(h)){let t=a.getRaw("Type");t instanceof Ref&&(t=await s.fetchAsync(t));if(isName(t,"Page")||!a.has("Kids")){if(o===e)return[a,null];o++;continue}throw new FormatError("Page dictionary kids object is not an array.")}for(let e=h.length-1;e>=0;e--){const i=h[e];t.push(i);a===this.toplevelPagesDict&&i instanceof Ref&&!g.has(i)&&g.put(i,s.fetchAsync(i))}}throw new Error(`Page index ${e} not found.`)}async getAllPageDicts(e=!1){const{ignoreErrors:t}=this.pdfManager.evaluatorOptions,i=[{currentNode:this.toplevelPagesDict,posInKids:0}],a=new RefSet,s=this._catDict.getRaw("Pages");s instanceof Ref&&a.put(s);const r=new Map,n=this.xref,g=this.pageIndexCache;let o=0;function addPageDict(e,t){t&&!g.has(t)&&g.put(t,o);r.set(o++,[e,t])}function addPageError(i){if(i instanceof XRefEntryException&&!e)throw i;if(e&&t&&0===o){warn(`getAllPageDicts - Skipping invalid first page: "${i}".`);i=Dict.empty}r.set(o++,[i,null])}for(;i.length>0;){const e=i.at(-1),{currentNode:t,posInKids:s}=e;let r=t.getRaw("Kids");if(r instanceof Ref)try{r=await n.fetchAsync(r)}catch(e){addPageError(e);break}if(!Array.isArray(r)){addPageError(new FormatError("Page dictionary kids object is not an array."));break}if(s>=r.length){i.pop();continue}const g=r[s];let o;if(g instanceof Ref){if(a.has(g)){addPageError(new FormatError("Pages tree contains circular reference."));break}a.put(g);try{o=await n.fetchAsync(g)}catch(e){addPageError(e);break}}else o=g;if(!(o instanceof Dict)){addPageError(new FormatError("Page dictionary kid reference points to wrong type of object."));break}let c=o.getRaw("Type");if(c instanceof Ref)try{c=await n.fetchAsync(c)}catch(e){addPageError(e);break}isName(c,"Page")||!o.has("Kids")?addPageDict(o,g instanceof Ref?g:null):i.push({currentNode:o,posInKids:0});e.posInKids++}return r}getPageIndex(e){const t=this.pageIndexCache.get(e);if(void 0!==t)return Promise.resolve(t);const i=this.xref;let a=0;const next=t=>function pagesBeforeRef(t){let a,s=0;return i.fetchAsync(t).then((function(i){if(isRefsEqual(t,e)&&!isDict(i,"Page")&&!(i instanceof Dict&&!i.has("Type")&&i.has("Contents")))throw new FormatError("The reference does not point to a /Page dictionary.");if(!i)return null;if(!(i instanceof Dict))throw new FormatError("Node must be a dictionary.");a=i.getRaw("Parent");return i.getAsync("Parent")})).then((function(e){if(!e)return null;if(!(e instanceof Dict))throw new FormatError("Parent must be a dictionary.");return e.getAsync("Kids")})).then((function(e){if(!e)return null;const r=[];let n=!1;for(const a of e){if(!(a instanceof Ref))throw new FormatError("Kid must be a reference.");if(isRefsEqual(a,t)){n=!0;break}r.push(i.fetchAsync(a).then((function(e){if(!(e instanceof Dict))throw new FormatError("Kid node must be a dictionary.");e.has("Count")?s+=e.get("Count"):s++})))}if(!n)throw new FormatError("Kid reference not found in parent's kids.");return Promise.all(r).then((function(){return[s,a]}))}))}(t).then((t=>{if(!t){this.pageIndexCache.put(e,a);return a}const[i,s]=t;a+=i;return next(s)}));return next(e)}get baseUrl(){const e=this._catDict.get("URI");if(e instanceof Dict){const t=e.get("Base");if("string"==typeof t){const e=createValidAbsoluteUrl(t,null,{tryConvertEncoding:!0});if(e)return shadow(this,"baseUrl",e.href)}}return shadow(this,"baseUrl",this.pdfManager.docBaseUrl)}static parseDestDictionary({destDict:e,resultObj:t,docBaseUrl:i=null,docAttachments:a=null}){if(!(e instanceof Dict)){warn("parseDestDictionary: `destDict` must be a dictionary.");return}let s,r,n=e.get("A");if(!(n instanceof Dict))if(e.has("Dest"))n=e.get("Dest");else{n=e.get("AA");n instanceof Dict&&(n.has("D")?n=n.get("D"):n.has("U")&&(n=n.get("U")))}if(n instanceof Dict){const e=n.get("S");if(!(e instanceof Name)){warn("parseDestDictionary: Invalid type in Action dictionary.");return}const i=e.name;switch(i){case"ResetForm":const e=n.get("Flags"),g=!(1&("number"==typeof e?e:0)),o=[],c=[];for(const e of n.get("Fields")||[])e instanceof Ref?c.push(e.toString()):"string"==typeof e&&o.push(stringToPDFString(e));t.resetForm={fields:o,refs:c,include:g};break;case"URI":s=n.get("URI");s instanceof Name&&(s="/"+s.name);break;case"GoTo":r=n.get("D");break;case"Launch":case"GoToR":const C=n.get("F");if(C instanceof Dict){const e=new FileSpec(C,null,!0),{rawFilename:t}=e.serializable;s=t}else"string"==typeof C&&(s=C);const h=fetchRemoteDest(n);h&&"string"==typeof s&&(s=s.split("#",1)[0]+"#"+h);const l=n.get("NewWindow");"boolean"==typeof l&&(t.newWindow=l);break;case"GoToE":const Q=n.get("T");let E;if(a&&Q instanceof Dict){const e=Q.get("R"),t=Q.get("N");isName(e,"C")&&"string"==typeof t&&(E=a[stringToPDFString(t)])}if(E){t.attachment=E;const e=fetchRemoteDest(n);e&&(t.attachmentDest=e)}else warn('parseDestDictionary - unimplemented "GoToE" action.');break;case"Named":const u=n.get("N");u instanceof Name&&(t.action=u.name);break;case"SetOCGState":const d=n.get("State"),f=n.get("PreserveRB");if(!Array.isArray(d)||0===d.length)break;const p=[];for(const e of d)if(e instanceof Name)switch(e.name){case"ON":case"OFF":case"Toggle":p.push(e.name)}else e instanceof Ref&&p.push(e.toString());if(p.length!==d.length)break;t.setOCGState={state:p,preserveRB:"boolean"!=typeof f||f};break;case"JavaScript":const m=n.get("JS");let y;m instanceof BaseStream?y=m.getString():"string"==typeof m&&(y=m);const w=y&&recoverJsURL(stringToPDFString(y));if(w){s=w.url;t.newWindow=w.newWindow;break}default:if("JavaScript"===i||"SubmitForm"===i)break;warn(`parseDestDictionary - unsupported action: "${i}".`)}}else e.has("Dest")&&(r=e.get("Dest"));if("string"==typeof s){const e=createValidAbsoluteUrl(s,i,{addDefaultProtocol:!0,tryConvertEncoding:!0});e&&(t.url=e.href);t.unsafeUrl=s}if(r){r instanceof Name&&(r=r.name);"string"==typeof r?t.dest=stringToPDFString(r):isValidExplicitDest(r)&&(t.dest=r)}}}function addChildren(e,t){if(e instanceof Dict)e=e.getRawValues();else if(e instanceof BaseStream)e=e.dict.getRawValues();else if(!Array.isArray(e))return;for(const a of e)((i=a)instanceof Ref||i instanceof Dict||i instanceof BaseStream||Array.isArray(i))&&t.push(a);var i}class ObjectLoader{constructor(e,t,i){this.dict=e;this.keys=t;this.xref=i;this.refSet=null}async load(){if(this.xref.stream.isDataLoaded)return;const{keys:e,dict:t}=this;this.refSet=new RefSet;const i=[];for(const a of e){const e=t.getRaw(a);void 0!==e&&i.push(e)}return this._walk(i)}async _walk(e){const t=[],i=[];for(;e.length;){let a=e.pop();if(a instanceof Ref){if(this.refSet.has(a))continue;try{this.refSet.put(a);a=this.xref.fetch(a)}catch(e){if(!(e instanceof MissingDataException)){warn(`ObjectLoader._walk - requesting all data: "${e}".`);this.refSet=null;const{manager:t}=this.xref.stream;return t.requestAllChunks()}t.push(a);i.push({begin:e.begin,end:e.end})}}if(a instanceof BaseStream){const e=a.getBaseStreams();if(e){let s=!1;for(const t of e)if(!t.isDataLoaded){s=!0;i.push({begin:t.start,end:t.end})}s&&t.push(a)}}addChildren(a,e)}if(i.length){await this.xref.stream.manager.requestRanges(i);for(const e of t)e instanceof Ref&&this.refSet.remove(e);return this._walk(t)}this.refSet=null}}const xs=Symbol(),Ls=Symbol(),Hs=Symbol(),Js=Symbol(),Ys=Symbol(),vs=Symbol(),Ks=Symbol(),Ts=Symbol(),qs=Symbol(),Os=Symbol("content"),Ws=Symbol("data"),js=Symbol(),Xs=Symbol("extra"),Zs=Symbol(),Vs=Symbol(),zs=Symbol(),_s=Symbol(),$s=Symbol(),Ar=Symbol(),er=Symbol(),tr=Symbol(),ir=Symbol(),ar=Symbol(),sr=Symbol(),rr=Symbol(),nr=Symbol(),gr=Symbol(),or=Symbol(),Ir=Symbol(),cr=Symbol(),Cr=Symbol(),hr=Symbol(),lr=Symbol(),Qr=Symbol(),Er=Symbol(),ur=Symbol(),dr=Symbol(),fr=Symbol(),pr=Symbol(),mr=Symbol(),yr=Symbol(),wr=Symbol(),Dr=Symbol(),br=Symbol(),Fr=Symbol(),Sr=Symbol("namespaceId"),kr=Symbol("nodeName"),Rr=Symbol(),Nr=Symbol(),Gr=Symbol(),Mr=Symbol(),Ur=Symbol(),xr=Symbol(),Lr=Symbol(),Hr=Symbol(),Jr=Symbol("root"),Yr=Symbol(),vr=Symbol(),Kr=Symbol(),Tr=Symbol(),qr=Symbol(),Or=Symbol(),Pr=Symbol(),Wr=Symbol(),jr=Symbol(),Xr=Symbol(),Zr=Symbol(),Vr=Symbol("uid"),zr=Symbol(),_r={config:{id:0,check:e=>e.startsWith("http://www.xfa.org/schema/xci/")},connectionSet:{id:1,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-connection-set/")},datasets:{id:2,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-data/")},form:{id:3,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-form/")},localeSet:{id:4,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-locale-set/")},pdf:{id:5,check:e=>"http://ns.adobe.com/xdp/pdf/"===e},signature:{id:6,check:e=>"http://www.w3.org/2000/09/xmldsig#"===e},sourceSet:{id:7,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-source-set/")},stylesheet:{id:8,check:e=>"http://www.w3.org/1999/XSL/Transform"===e},template:{id:9,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-template/")},xdc:{id:10,check:e=>e.startsWith("http://www.xfa.org/schema/xdc/")},xdp:{id:11,check:e=>"http://ns.adobe.com/xdp/"===e},xfdf:{id:12,check:e=>"http://ns.adobe.com/xfdf/"===e},xhtml:{id:13,check:e=>"http://www.w3.org/1999/xhtml"===e},xmpmeta:{id:14,check:e=>"http://ns.adobe.com/xmpmeta/"===e}},$r={pt:e=>e,cm:e=>e/2.54*72,mm:e=>e/25.4*72,in:e=>72*e,px:e=>e},An=/([+-]?\d+\.?\d*)(.*)/;function stripQuotes(e){return e.startsWith("'")||e.startsWith('"')?e.slice(1,-1):e}function getInteger({data:e,defaultValue:t,validate:i}){if(!e)return t;e=e.trim();const a=parseInt(e,10);return!isNaN(a)&&i(a)?a:t}function getFloat({data:e,defaultValue:t,validate:i}){if(!e)return t;e=e.trim();const a=parseFloat(e);return!isNaN(a)&&i(a)?a:t}function getKeyword({data:e,defaultValue:t,validate:i}){return e&&i(e=e.trim())?e:t}function getStringOption(e,t){return getKeyword({data:e,defaultValue:t[0],validate:e=>t.includes(e)})}function getMeasurement(e,t="0"){t||="0";if(!e)return getMeasurement(t);const i=e.trim().match(An);if(!i)return getMeasurement(t);const[,a,s]=i,r=parseFloat(a);if(isNaN(r))return getMeasurement(t);if(0===r)return 0;const n=$r[s];return n?n(r):r}function getRatio(e){if(!e)return{num:1,den:1};const t=e.trim().split(/\s*:\s*/).map((e=>parseFloat(e))).filter((e=>!isNaN(e)));1===t.length&&t.push(1);if(0===t.length)return{num:1,den:1};const[i,a]=t;return{num:i,den:a}}function getRelevant(e){return e?e.trim().split(/\s+/).map((e=>({excluded:"-"===e[0],viewname:e.substring(1)}))):[]}class HTMLResult{static get FAILURE(){return shadow(this,"FAILURE",new HTMLResult(!1,null,null,null))}static get EMPTY(){return shadow(this,"EMPTY",new HTMLResult(!0,null,null,null))}constructor(e,t,i,a){this.success=e;this.html=t;this.bbox=i;this.breakNode=a}isBreak(){return!!this.breakNode}static breakNode(e){return new HTMLResult(!1,null,null,e)}static success(e,t=null){return new HTMLResult(!0,e,t,null)}}class FontFinder{constructor(e){this.fonts=new Map;this.cache=new Map;this.warned=new Set;this.defaultFont=null;this.add(e)}add(e,t=null){for(const t of e)this.addPdfFont(t);for(const e of this.fonts.values())e.regular||(e.regular=e.italic||e.bold||e.bolditalic);if(!t||0===t.size)return;const i=this.fonts.get("PdfJS-Fallback-PdfJS-XFA");for(const e of t)this.fonts.set(e,i)}addPdfFont(e){const t=e.cssFontInfo,i=t.fontFamily;let a=this.fonts.get(i);if(!a){a=Object.create(null);this.fonts.set(i,a);this.defaultFont||(this.defaultFont=a)}let s="";const r=parseFloat(t.fontWeight);0!==parseFloat(t.italicAngle)?s=r>=700?"bolditalic":"italic":r>=700&&(s="bold");if(!s){(e.name.includes("Bold")||e.psName?.includes("Bold"))&&(s="bold");(e.name.includes("Italic")||e.name.endsWith("It")||e.psName?.includes("Italic")||e.psName?.endsWith("It"))&&(s+="italic")}s||(s="regular");a[s]=e}getDefault(){return this.defaultFont}find(e,t=!0){let i=this.fonts.get(e)||this.cache.get(e);if(i)return i;const a=/,|-|_| |bolditalic|bold|italic|regular|it/gi;let s=e.replaceAll(a,"");i=this.fonts.get(s);if(i){this.cache.set(e,i);return i}s=s.toLowerCase();const r=[];for(const[e,t]of this.fonts.entries())e.replaceAll(a,"").toLowerCase().startsWith(s)&&r.push(t);if(0===r.length)for(const[,e]of this.fonts.entries())e.regular.name?.replaceAll(a,"").toLowerCase().startsWith(s)&&r.push(e);if(0===r.length){s=s.replaceAll(/psmt|mt/gi,"");for(const[e,t]of this.fonts.entries())e.replaceAll(a,"").toLowerCase().startsWith(s)&&r.push(t)}if(0===r.length)for(const e of this.fonts.values())e.regular.name?.replaceAll(a,"").toLowerCase().startsWith(s)&&r.push(e);if(r.length>=1){1!==r.length&&t&&warn(`XFA - Too many choices to guess the correct font: ${e}`);this.cache.set(e,r[0]);return r[0]}if(t&&!this.warned.has(e)){this.warned.add(e);warn(`XFA - Cannot find the font: ${e}`)}return null}}function selectFont(e,t){return"italic"===e.posture?"bold"===e.weight?t.bolditalic:t.italic:"bold"===e.weight?t.bold:t.regular}class FontInfo{constructor(e,t,i,a){this.lineHeight=i;this.paraMargin=t||{top:0,bottom:0,left:0,right:0};if(!e){[this.pdfFont,this.xfaFont]=this.defaultFont(a);return}this.xfaFont={typeface:e.typeface,posture:e.posture,weight:e.weight,size:e.size,letterSpacing:e.letterSpacing};const s=a.find(e.typeface);if(s){this.pdfFont=selectFont(e,s);this.pdfFont||([this.pdfFont,this.xfaFont]=this.defaultFont(a))}else[this.pdfFont,this.xfaFont]=this.defaultFont(a)}defaultFont(e){const t=e.find("Helvetica",!1)||e.find("Myriad Pro",!1)||e.find("Arial",!1)||e.getDefault();if(t?.regular){const e=t.regular;return[e,{typeface:e.cssFontInfo.fontFamily,posture:"normal",weight:"normal",size:10,letterSpacing:0}]}return[null,{typeface:"Courier",posture:"normal",weight:"normal",size:10,letterSpacing:0}]}}class FontSelector{constructor(e,t,i,a){this.fontFinder=a;this.stack=[new FontInfo(e,t,i,a)]}pushData(e,t,i){const a=this.stack.at(-1);for(const t of["typeface","posture","weight","size","letterSpacing"])e[t]||(e[t]=a.xfaFont[t]);for(const e of["top","bottom","left","right"])isNaN(t[e])&&(t[e]=a.paraMargin[e]);const s=new FontInfo(e,t,i||a.lineHeight,this.fontFinder);s.pdfFont||(s.pdfFont=a.pdfFont);this.stack.push(s)}popFont(){this.stack.pop()}topFont(){return this.stack.at(-1)}}class TextMeasure{constructor(e,t,i,a){this.glyphs=[];this.fontSelector=new FontSelector(e,t,i,a);this.extraHeight=0}pushData(e,t,i){this.fontSelector.pushData(e,t,i)}popFont(e){return this.fontSelector.popFont()}addPara(){const e=this.fontSelector.topFont();this.extraHeight+=e.paraMargin.top+e.paraMargin.bottom}addString(e){if(!e)return;const t=this.fontSelector.topFont(),i=t.xfaFont.size;if(t.pdfFont){const a=t.xfaFont.letterSpacing,s=t.pdfFont,r=s.lineHeight||1.2,n=t.lineHeight||Math.max(1.2,r)*i,g=r-(void 0===s.lineGap?.2:s.lineGap),o=Math.max(1,g)*i,c=i/1e3,C=s.defaultWidth||s.charsToGlyphs(" ")[0].width;for(const t of e.split(/[\u2029\n]/)){const e=s.encodeString(t).join(""),i=s.charsToGlyphs(e);for(const e of i){const t=e.width||C;this.glyphs.push([t*c+a,n,o,e.unicode,!1])}this.glyphs.push([0,0,0,"\n",!0])}this.glyphs.pop()}else{for(const t of e.split(/[\u2029\n]/)){for(const e of t.split(""))this.glyphs.push([i,1.2*i,i,e,!1]);this.glyphs.push([0,0,0,"\n",!0])}this.glyphs.pop()}}compute(e){let t=-1,i=0,a=0,s=0,r=0,n=0,g=!1,o=!0;for(let c=0,C=this.glyphs.length;ce){a=Math.max(a,r);r=0;s+=n;n=d;t=-1;i=0;g=!0;o=!1}else{n=Math.max(d,n);i=r;r+=C;t=c}else if(r+C>e){s+=n;n=d;if(-1!==t){c=t;a=Math.max(a,i);r=0;t=-1;i=0}else{a=Math.max(a,r);r=C}g=!0;o=!1}else{r+=C;n=Math.max(d,n)}}a=Math.max(a,r);s+=n+this.extraHeight;return{width:1.02*a,height:s,isBroken:g}}}const en=/^[^.[]+/,tn=/^[^\]]+/,an=0,sn=1,rn=2,nn=3,gn=4,on=new Map([["$data",(e,t)=>e.datasets?e.datasets.data:e],["$record",(e,t)=>(e.datasets?e.datasets.data:e)[rr]()[0]],["$template",(e,t)=>e.template],["$connectionSet",(e,t)=>e.connectionSet],["$form",(e,t)=>e.form],["$layout",(e,t)=>e.layout],["$host",(e,t)=>e.host],["$dataWindow",(e,t)=>e.dataWindow],["$event",(e,t)=>e.event],["!",(e,t)=>e.datasets],["$xfa",(e,t)=>e],["xfa",(e,t)=>e],["$",(e,t)=>t]]),In=new WeakMap;function parseExpression(e,t,i=!0){let a=e.match(en);if(!a)return null;let[s]=a;const r=[{name:s,cacheName:"."+s,index:0,js:null,formCalc:null,operator:an}];let n=s.length;for(;n0&&C.push(e)}if(0!==C.length||g||0!==o)e=isFinite(c)?C.filter((e=>ce[c])):C.flat();else{const i=t[Ir]();if(!(t=i))return null;o=-1;e=[t]}}return 0===e.length?null:e}function createDataNode(e,t,i){const a=parseExpression(i);if(!a)return null;if(a.some((e=>e.operator===sn)))return null;const s=on.get(a[0].name);let r=0;if(s){e=s(e,t);r=1}else e=t||e;for(let t=a.length;re[Pr]())).join("")}get[hn](){const e=Object.getPrototypeOf(this);if(!e._attributes){const t=e._attributes=new Set;for(const e of Object.getOwnPropertyNames(this)){if(null===this[e]||this[e]instanceof XFAObject||this[e]instanceof XFAObjectArray)break;t.add(e)}}return shadow(this,hn,e._attributes)}[pr](e){let t=this;for(;t;){if(t===e)return!0;t=t[Ir]()}return!1}[Ir](){return this[wn]}[or](){return this[Ir]()}[rr](e=null){return e?this[e]:this[ln]}[js](){const e=Object.create(null);this[Os]&&(e.$content=this[Os]);for(const t of Object.getOwnPropertyNames(this)){const i=this[t];null!==i&&(i instanceof XFAObject?e[t]=i[js]():i instanceof XFAObjectArray?i.isEmpty()||(e[t]=i.dump()):e[t]=i)}return e}[Zr](){return null}[jr](){return HTMLResult.EMPTY}*[nr](){for(const e of this[rr]())yield e}*[un](e,t){for(const i of this[nr]())if(!e||t===e.has(i[kr])){const e=this[$s](),t=i[jr](e);t.success||(this[Xs].failingNode=i);yield t}}[Vs](){return null}[Ls](e,t){this[Xs].children.push(e)}[$s](){}[Js]({filter:e=null,include:t=!0}){if(this[Xs].generator){const e=this[$s](),t=this[Xs].failingNode[jr](e);if(!t.success)return t;t.html&&this[Ls](t.html,t.bbox);delete this[Xs].failingNode}else this[Xs].generator=this[un](e,t);for(;;){const e=this[Xs].generator.next();if(e.done)break;const t=e.value;if(!t.success)return t;t.html&&this[Ls](t.html,t.bbox)}this[Xs].generator=null;return HTMLResult.EMPTY}[Tr](e){this[bn]=new Set(Object.keys(e))}[fn](e){const t=this[hn],i=this[bn];return[...e].filter((e=>t.has(e)&&!i.has(e)))}[Yr](e,t=new Set){for(const i of this[ln])i[Dn](e,t)}[Dn](e,t){const i=this[dn](e,t);i?this[cn](i,e,t):this[Yr](e,t)}[dn](e,t){const{use:i,usehref:a}=this;if(!i&&!a)return null;let s=null,r=null,n=null,g=i;if(a){g=a;a.startsWith("#som(")&&a.endsWith(")")?r=a.slice(5,-1):a.startsWith(".#som(")&&a.endsWith(")")?r=a.slice(6,-1):a.startsWith("#")?n=a.slice(1):a.startsWith(".#")&&(n=a.slice(2))}else i.startsWith("#")?n=i.slice(1):r=i;this.use=this.usehref="";if(n)s=e.get(n);else{s=searchNode(e.get(Jr),this,r,!0,!1);s&&(s=s[0])}if(!s){warn(`XFA - Invalid prototype reference: ${g}.`);return null}if(s[kr]!==this[kr]){warn(`XFA - Incompatible prototype: ${s[kr]} !== ${this[kr]}.`);return null}if(t.has(s)){warn("XFA - Cycle detected in prototypes use.");return null}t.add(s);const o=s[dn](e,t);o&&s[cn](o,e,t);s[Yr](e,t);t.delete(s);return s}[cn](e,t,i){if(i.has(e)){warn("XFA - Cycle detected in prototypes use.");return}!this[Os]&&e[Os]&&(this[Os]=e[Os]);new Set(i).add(e);for(const t of this[fn](e[bn])){this[t]=e[t];this[bn]&&this[bn].add(t)}for(const a of Object.getOwnPropertyNames(this)){if(this[hn].has(a))continue;const s=this[a],r=e[a];if(s instanceof XFAObjectArray){for(const e of s[ln])e[Dn](t,i);for(let a=s[ln].length,n=r[ln].length;aXFAObject[Bn](e))):"object"==typeof e&&null!==e?Object.assign({},e):e}[Ts](){const e=Object.create(Object.getPrototypeOf(this));for(const t of Object.getOwnPropertySymbols(this))try{e[t]=this[t]}catch{shadow(e,t,this[t])}e[Vr]=`${e[kr]}${Sn++}`;e[ln]=[];for(const t of Object.getOwnPropertyNames(this)){if(this[hn].has(t)){e[t]=XFAObject[Bn](this[t]);continue}const i=this[t];e[t]=i instanceof XFAObjectArray?new XFAObjectArray(i[mn]):null}for(const t of this[ln]){const i=t[kr],a=t[Ts]();e[ln].push(a);a[wn]=e;null===e[i]?e[i]=a:e[i][ln].push(a)}return e}[rr](e=null){return e?this[ln].filter((t=>t[kr]===e)):this[ln]}[Ar](e){return this[e]}[er](e,t,i=!0){return Array.from(this[tr](e,t,i))}*[tr](e,t,i=!0){if("parent"!==e){for(const i of this[ln]){i[kr]===e&&(yield i);i.name===e&&(yield i);(t||i[Dr]())&&(yield*i[tr](e,t,!1))}i&&this[hn].has(e)&&(yield new XFAAttribute(this,e,this[e]))}else yield this[wn]}}class XFAObjectArray{constructor(e=1/0){this[mn]=e;this[ln]=[]}get isXFAObject(){return!1}get isXFAObjectArray(){return!0}push(e){if(this[ln].length<=this[mn]){this[ln].push(e);return!0}warn(`XFA - node "${e[kr]}" accepts no more than ${this[mn]} children`);return!1}isEmpty(){return 0===this[ln].length}dump(){return 1===this[ln].length?this[ln][0][js]():this[ln].map((e=>e[js]()))}[Ts](){const e=new XFAObjectArray(this[mn]);e[ln]=this[ln].map((e=>e[Ts]()));return e}get children(){return this[ln]}clear(){this[ln].length=0}}class XFAAttribute{constructor(e,t,i){this[wn]=e;this[kr]=t;this[Os]=i;this[qs]=!1;this[Vr]="attribute"+Sn++}[Ir](){return this[wn]}[fr](){return!0}[ir](){return this[Os].trim()}[qr](e){e=e.value||"";this[Os]=e.toString()}[Pr](){return this[Os]}[pr](e){return this[wn]===e||this[wn][pr](e)}}class XmlObject extends XFAObject{constructor(e,t,i={}){super(e,t);this[Os]="";this[Qn]=null;if("#text"!==t){const e=new Map;this[Cn]=e;for(const[t,a]of Object.entries(i))e.set(t,new XFAAttribute(this,t,a));if(i.hasOwnProperty(Rr)){const e=i[Rr].xfa.dataNode;void 0!==e&&("dataGroup"===e?this[Qn]=!1:"dataValue"===e&&(this[Qn]=!0))}}this[qs]=!1}[Xr](e){const t=this[kr];if("#text"===t){e.push(encodeToXmlString(this[Os]));return}const i=utf8StringToString(t),a=this[Sr]===kn?"xfa:":"";e.push(`<${a}${i}`);for(const[t,i]of this[Cn].entries()){const a=utf8StringToString(t);e.push(` ${a}="${encodeToXmlString(i[Os])}"`)}null!==this[Qn]&&(this[Qn]?e.push(' xfa:dataNode="dataValue"'):e.push(' xfa:dataNode="dataGroup"'));if(this[Os]||0!==this[ln].length){e.push(">");if(this[Os])"string"==typeof this[Os]?e.push(encodeToXmlString(this[Os])):this[Os][Xr](e);else for(const t of this[ln])t[Xr](e);e.push(``)}else e.push("/>")}[Nr](e){if(this[Os]){const e=new XmlObject(this[Sr],"#text");this[Hs](e);e[Os]=this[Os];this[Os]=""}this[Hs](e);return!0}[Mr](e){this[Os]+=e}[Zs](){if(this[Os]&&this[ln].length>0){const e=new XmlObject(this[Sr],"#text");this[Hs](e);e[Os]=this[Os];delete this[Os]}}[jr](){return"#text"===this[kr]?HTMLResult.success({name:"#text",value:this[Os]}):HTMLResult.EMPTY}[rr](e=null){return e?this[ln].filter((t=>t[kr]===e)):this[ln]}[_s](){return this[Cn]}[Ar](e){const t=this[Cn].get(e);return void 0!==t?t:this[rr](e)}*[tr](e,t){const i=this[Cn].get(e);i&&(yield i);for(const i of this[ln]){i[kr]===e&&(yield i);t&&(yield*i[tr](e,t))}}*[zs](e,t){const i=this[Cn].get(e);!i||t&&i[qs]||(yield i);for(const i of this[ln])yield*i[zs](e,t)}*[sr](e,t,i){for(const a of this[ln]){a[kr]!==e||i&&a[qs]||(yield a);t&&(yield*a[sr](e,t,i))}}[fr](){return null===this[Qn]?0===this[ln].length||this[ln][0][Sr]===_r.xhtml.id:this[Qn]}[ir](){return null===this[Qn]?0===this[ln].length?this[Os].trim():this[ln][0][Sr]===_r.xhtml.id?this[ln][0][Pr]().trim():null:this[Os].trim()}[qr](e){e=e.value||"";this[Os]=e.toString()}[js](e=!1){const t=Object.create(null);e&&(t.$ns=this[Sr]);this[Os]&&(t.$content=this[Os]);t.$name=this[kr];t.children=[];for(const i of this[ln])t.children.push(i[js](e));t.attributes=Object.create(null);for(const[e,i]of this[Cn])t.attributes[e]=i[Os];return t}}class ContentObject extends XFAObject{constructor(e,t){super(e,t);this[Os]=""}[Mr](e){this[Os]+=e}[Zs](){}}class OptionObject extends ContentObject{constructor(e,t,i){super(e,t);this[yn]=i}[Zs](){this[Os]=getKeyword({data:this[Os],defaultValue:this[yn][0],validate:e=>this[yn].includes(e)})}[Ys](e){super[Ys](e);delete this[yn]}}class StringObject extends ContentObject{[Zs](){this[Os]=this[Os].trim()}}class IntegerObject extends ContentObject{constructor(e,t,i,a){super(e,t);this[En]=i;this[Fn]=a}[Zs](){this[Os]=getInteger({data:this[Os],defaultValue:this[En],validate:this[Fn]})}[Ys](e){super[Ys](e);delete this[En];delete this[Fn]}}class Option01 extends IntegerObject{constructor(e,t){super(e,t,0,(e=>1===e))}}class Option10 extends IntegerObject{constructor(e,t){super(e,t,1,(e=>0===e))}}function measureToString(e){return"string"==typeof e?"0px":Number.isInteger(e)?`${e}px`:`${e.toFixed(2)}px`}const Rn={anchorType(e,t){const i=e[or]();if(i&&(!i.layout||"position"===i.layout)){"transform"in t||(t.transform="");switch(e.anchorType){case"bottomCenter":t.transform+="translate(-50%, -100%)";break;case"bottomLeft":t.transform+="translate(0,-100%)";break;case"bottomRight":t.transform+="translate(-100%,-100%)";break;case"middleCenter":t.transform+="translate(-50%,-50%)";break;case"middleLeft":t.transform+="translate(0,-50%)";break;case"middleRight":t.transform+="translate(-100%,-50%)";break;case"topCenter":t.transform+="translate(-50%,0)";break;case"topRight":t.transform+="translate(-100%,0)"}}},dimensions(e,t){const i=e[or]();let a=e.w;const s=e.h;if(i.layout?.includes("row")){const t=i[Xs],s=e.colSpan;let r;if(-1===s){r=t.columnWidths.slice(t.currentColumn).reduce(((e,t)=>e+t),0);t.currentColumn=0}else{r=t.columnWidths.slice(t.currentColumn,t.currentColumn+s).reduce(((e,t)=>e+t),0);t.currentColumn=(t.currentColumn+e.colSpan)%t.columnWidths.length}isNaN(r)||(a=e.w=r)}t.width=""!==a?measureToString(a):"auto";t.height=""!==s?measureToString(s):"auto"},position(e,t){const i=e[or]();if(!i?.layout||"position"===i.layout){t.position="absolute";t.left=measureToString(e.x);t.top=measureToString(e.y)}},rotate(e,t){if(e.rotate){"transform"in t||(t.transform="");t.transform+=`rotate(-${e.rotate}deg)`;t.transformOrigin="top left"}},presence(e,t){switch(e.presence){case"invisible":t.visibility="hidden";break;case"hidden":case"inactive":t.display="none"}},hAlign(e,t){if("para"===e[kr])switch(e.hAlign){case"justifyAll":t.textAlign="justify-all";break;case"radix":t.textAlign="left";break;default:t.textAlign=e.hAlign}else switch(e.hAlign){case"left":t.alignSelf="start";break;case"center":t.alignSelf="center";break;case"right":t.alignSelf="end"}},margin(e,t){e.margin&&(t.margin=e.margin[Zr]().margin)}};function setMinMaxDimensions(e,t){if("position"===e[or]().layout){e.minW>0&&(t.minWidth=measureToString(e.minW));e.maxW>0&&(t.maxWidth=measureToString(e.maxW));e.minH>0&&(t.minHeight=measureToString(e.minH));e.maxH>0&&(t.maxHeight=measureToString(e.maxH))}}function layoutText(e,t,i,a,s,r){const n=new TextMeasure(t,i,a,s);"string"==typeof e?n.addString(e):e[Ur](n);return n.compute(r)}function layoutNode(e,t){let i=null,a=null,s=!1;if((!e.w||!e.h)&&e.value){let r=0,n=0;if(e.margin){r=e.margin.leftInset+e.margin.rightInset;n=e.margin.topInset+e.margin.bottomInset}let g=null,o=null;if(e.para){o=Object.create(null);g=""===e.para.lineHeight?null:e.para.lineHeight;o.top=""===e.para.spaceAbove?0:e.para.spaceAbove;o.bottom=""===e.para.spaceBelow?0:e.para.spaceBelow;o.left=""===e.para.marginLeft?0:e.para.marginLeft;o.right=""===e.para.marginRight?0:e.para.marginRight}let c=e.font;if(!c){const t=e[cr]();let i=e[Ir]();for(;i&&i!==t;){if(i.font){c=i.font;break}i=i[Ir]()}}const C=(e.w||t.width)-r,h=e[Cr].fontFinder;if(e.value.exData&&e.value.exData[Os]&&"text/html"===e.value.exData.contentType){const t=layoutText(e.value.exData[Os],c,o,g,h,C);a=t.width;i=t.height;s=t.isBroken}else{const t=e.value[Pr]();if(t){const e=layoutText(t,c,o,g,h,C);a=e.width;i=e.height;s=e.isBroken}}null===a||e.w||(a+=r);null===i||e.h||(i+=n)}return{w:a,h:i,isBroken:s}}function computeBbox(e,t,i){let a;if(""!==e.w&&""!==e.h)a=[e.x,e.y,e.w,e.h];else{if(!i)return null;let s=e.w;if(""===s){if(0===e.maxW){const t=e[or]();s="position"===t.layout&&""!==t.w?0:e.minW}else s=Math.min(e.maxW,i.width);t.attributes.style.width=measureToString(s)}let r=e.h;if(""===r){if(0===e.maxH){const t=e[or]();r="position"===t.layout&&""!==t.h?0:e.minH}else r=Math.min(e.maxH,i.height);t.attributes.style.height=measureToString(r)}a=[e.x,e.y,s,r]}return a}function fixDimensions(e){const t=e[or]();if(t.layout?.includes("row")){const i=t[Xs],a=e.colSpan;let s;s=-1===a?i.columnWidths.slice(i.currentColumn).reduce(((e,t)=>e+t),0):i.columnWidths.slice(i.currentColumn,i.currentColumn+a).reduce(((e,t)=>e+t),0);isNaN(s)||(e.w=s)}t.layout&&"position"!==t.layout&&(e.x=e.y=0);"table"===e.layout&&""===e.w&&Array.isArray(e.columnWidths)&&(e.w=e.columnWidths.reduce(((e,t)=>e+t),0))}function layoutClass(e){switch(e.layout){case"position":default:return"xfaPosition";case"lr-tb":return"xfaLrTb";case"rl-row":return"xfaRlRow";case"rl-tb":return"xfaRlTb";case"row":return"xfaRow";case"table":return"xfaTable";case"tb":return"xfaTb"}}function toStyle(e,...t){const i=Object.create(null);for(const a of t){const t=e[a];if(null!==t)if(Rn.hasOwnProperty(a))Rn[a](e,i);else if(t instanceof XFAObject){const e=t[Zr]();e?Object.assign(i,e):warn(`(DEBUG) - XFA - style for ${a} not implemented yet`)}}return i}function createWrapper(e,t){const{attributes:i}=t,{style:a}=i,s={name:"div",attributes:{class:["xfaWrapper"],style:Object.create(null)},children:[]};i.class.push("xfaWrapped");if(e.border){const{widths:i,insets:r}=e.border[Xs];let n,g,o=r[0],c=r[3];const C=r[0]+r[2],h=r[1]+r[3];switch(e.border.hand){case"even":o-=i[0]/2;c-=i[3]/2;n=`calc(100% + ${(i[1]+i[3])/2-h}px)`;g=`calc(100% + ${(i[0]+i[2])/2-C}px)`;break;case"left":o-=i[0];c-=i[3];n=`calc(100% + ${i[1]+i[3]-h}px)`;g=`calc(100% + ${i[0]+i[2]-C}px)`;break;case"right":n=h?`calc(100% - ${h}px)`:"100%";g=C?`calc(100% - ${C}px)`:"100%"}const l=["xfaBorder"];isPrintOnly(e.border)&&l.push("xfaPrintOnly");const Q={name:"div",attributes:{class:l,style:{top:`${o}px`,left:`${c}px`,width:n,height:g}},children:[]};for(const e of["border","borderWidth","borderColor","borderRadius","borderStyle"])if(void 0!==a[e]){Q.attributes.style[e]=a[e];delete a[e]}s.children.push(Q,t)}else s.children.push(t);for(const e of["background","backgroundClip","top","left","width","height","minWidth","minHeight","maxWidth","maxHeight","transform","transformOrigin","visibility"])if(void 0!==a[e]){s.attributes.style[e]=a[e];delete a[e]}s.attributes.style.position="absolute"===a.position?"absolute":"relative";delete a.position;if(a.alignSelf){s.attributes.style.alignSelf=a.alignSelf;delete a.alignSelf}return s}function fixTextIndent(e){const t=getMeasurement(e.textIndent,"0px");if(t>=0)return;const i="padding"+("left"===("right"===e.textAlign?"right":"left")?"Left":"Right"),a=getMeasurement(e[i],"0px");e[i]=a-t+"px"}function setAccess(e,t){switch(e.access){case"nonInteractive":t.push("xfaNonInteractive");break;case"readOnly":t.push("xfaReadOnly");break;case"protected":t.push("xfaDisabled")}}function isPrintOnly(e){return e.relevant.length>0&&!e.relevant[0].excluded&&"print"===e.relevant[0].viewname}function getCurrentPara(e){const t=e[cr]()[Xs].paraStack;return t.length?t.at(-1):null}function setPara(e,t,i){if(i.attributes.class?.includes("xfaRich")){if(t){""===e.h&&(t.height="auto");""===e.w&&(t.width="auto")}const a=getCurrentPara(e);if(a){const e=i.attributes.style;e.display="flex";e.flexDirection="column";switch(a.vAlign){case"top":e.justifyContent="start";break;case"bottom":e.justifyContent="end";break;case"middle":e.justifyContent="center"}const t=a[Zr]();for(const[i,a]of Object.entries(t))i in e||(e[i]=a)}}}function setFontFamily(e,t,i,a){if(!i){delete a.fontFamily;return}const s=stripQuotes(e.typeface);a.fontFamily=`"${s}"`;const r=i.find(s);if(r){const{fontFamily:i}=r.regular.cssFontInfo;i!==s&&(a.fontFamily=`"${i}"`);const n=getCurrentPara(t);if(n&&""!==n.lineHeight)return;if(a.lineHeight)return;const g=selectFont(e,r);g&&(a.lineHeight=Math.max(1.2,g.lineHeight))}}function fixURL(e){const t=createValidAbsoluteUrl(e,null,{addDefaultProtocol:!0,tryConvertEncoding:!0});return t?t.href:null}function createLine(e,t){return{name:"div",attributes:{class:["lr-tb"===e.layout?"xfaLr":"xfaRl"]},children:t}}function flushHTML(e){if(!e[Xs])return null;const t={name:"div",attributes:e[Xs].attributes,children:e[Xs].children};if(e[Xs].failingNode){const i=e[Xs].failingNode[Vs]();i&&(e.layout.endsWith("-tb")?t.children.push(createLine(e,[i])):t.children.push(i))}return 0===t.children.length?null:t}function addHTML(e,t,i){const a=e[Xs],s=a.availableSpace,[r,n,g,o]=i;switch(e.layout){case"position":a.width=Math.max(a.width,r+g);a.height=Math.max(a.height,n+o);a.children.push(t);break;case"lr-tb":case"rl-tb":if(!a.line||1===a.attempt){a.line=createLine(e,[]);a.children.push(a.line);a.numberInLine=0}a.numberInLine+=1;a.line.children.push(t);if(0===a.attempt){a.currentWidth+=g;a.height=Math.max(a.height,a.prevHeight+o)}else{a.currentWidth=g;a.prevHeight=a.height;a.height+=o;a.attempt=0}a.width=Math.max(a.width,a.currentWidth);break;case"rl-row":case"row":{a.children.push(t);a.width+=g;a.height=Math.max(a.height,o);const e=measureToString(a.height);for(const t of a.children)t.attributes.style.height=e;break}case"table":case"tb":a.width=Math.min(s.width,Math.max(a.width,g));a.height+=o;a.children.push(t)}}function getAvailableSpace(e){const t=e[Xs].availableSpace,i=e.margin?e.margin.topInset+e.margin.bottomInset:0,a=e.margin?e.margin.leftInset+e.margin.rightInset:0;switch(e.layout){case"lr-tb":case"rl-tb":return 0===e[Xs].attempt?{width:t.width-a-e[Xs].currentWidth,height:t.height-i-e[Xs].prevHeight}:{width:t.width-a,height:t.height-i-e[Xs].height};case"rl-row":case"row":return{width:e[Xs].columnWidths.slice(e[Xs].currentColumn).reduce(((e,t)=>e+t)),height:t.height-a};case"table":case"tb":return{width:t.width-a,height:t.height-i-e[Xs].height};default:return t}}function checkDimensions(e,t){if(null===e[cr]()[Xs].firstUnsplittable)return!0;if(0===e.w||0===e.h)return!0;const i=e[or](),a=i[Xs]?.attempt||0,[,s,r,n]=function getTransformedBBox(e){let t,i,a=""===e.w?NaN:e.w,s=""===e.h?NaN:e.h,[r,n]=[0,0];switch(e.anchorType||""){case"bottomCenter":[r,n]=[a/2,s];break;case"bottomLeft":[r,n]=[0,s];break;case"bottomRight":[r,n]=[a,s];break;case"middleCenter":[r,n]=[a/2,s/2];break;case"middleLeft":[r,n]=[0,s/2];break;case"middleRight":[r,n]=[a,s/2];break;case"topCenter":[r,n]=[a/2,0];break;case"topRight":[r,n]=[a,0]}switch(e.rotate||0){case 0:[t,i]=[-r,-n];break;case 90:[t,i]=[-n,r];[a,s]=[s,-a];break;case 180:[t,i]=[r,n];[a,s]=[-a,-s];break;case 270:[t,i]=[n,-r];[a,s]=[-s,a]}return[e.x+t+Math.min(0,a),e.y+i+Math.min(0,s),Math.abs(a),Math.abs(s)]}(e);switch(i.layout){case"lr-tb":case"rl-tb":return 0===a?e[cr]()[Xs].noLayoutFailure?""!==e.w?Math.round(r-t.width)<=2:t.width>2:!(""!==e.h&&Math.round(n-t.height)>2)&&(""!==e.w?Math.round(r-t.width)<=2||0===i[Xs].numberInLine&&t.height>2:t.width>2):!!e[cr]()[Xs].noLayoutFailure||!(""!==e.h&&Math.round(n-t.height)>2)&&((""===e.w||Math.round(r-t.width)<=2||!i[wr]())&&t.height>2);case"table":case"tb":return!!e[cr]()[Xs].noLayoutFailure||(""===e.h||e[yr]()?(""===e.w||Math.round(r-t.width)<=2||!i[wr]())&&t.height>2:Math.round(n-t.height)<=2);case"position":if(e[cr]()[Xs].noLayoutFailure)return!0;if(""===e.h||Math.round(n+s-t.height)<=2)return!0;return n+s>e[cr]()[Xs].currentContentArea.h;case"rl-row":case"row":return!!e[cr]()[Xs].noLayoutFailure||(""===e.h||Math.round(n-t.height)<=2);default:return!0}}const Nn=_r.template.id,Gn="http://www.w3.org/2000/svg",Mn=/^H(\d+)$/,Un=new Set(["image/gif","image/jpeg","image/jpg","image/pjpeg","image/png","image/apng","image/x-png","image/bmp","image/x-ms-bmp","image/tiff","image/tif","application/octet-stream"]),xn=[[[66,77],"image/bmp"],[[255,216,255],"image/jpeg"],[[73,73,42,0],"image/tiff"],[[77,77,0,42],"image/tiff"],[[71,73,70,56,57,97],"image/gif"],[[137,80,78,71,13,10,26,10],"image/png"]];function getBorderDims(e){if(!e||!e.border)return{w:0,h:0};const t=e.border[ar]();return t?{w:t.widths[0]+t.widths[2]+t.insets[0]+t.insets[2],h:t.widths[1]+t.widths[3]+t.insets[1]+t.insets[3]}:{w:0,h:0}}function hasMargin(e){return e.margin&&(e.margin.topInset||e.margin.rightInset||e.margin.bottomInset||e.margin.leftInset)}function _setValue(e,t){if(!e.value){const t=new Value({});e[Hs](t);e.value=t}e.value[qr](t)}function*getContainedChildren(e){for(const t of e[rr]())t instanceof SubformSet?yield*t[nr]():yield t}function isRequired(e){return"error"===e.validate?.nullTest}function setTabIndex(e){for(;e;){if(!e.traversal){e[Or]=e[Ir]()[Or];return}if(e[Or])return;let t=null;for(const i of e.traversal[rr]())if("next"===i.operation){t=i;break}if(!t||!t.ref){e[Or]=e[Ir]()[Or];return}const i=e[cr]();e[Or]=++i[Or];const a=i[vr](t.ref,e);if(!a)return;e=a[0]}}function applyAssist(e,t){const i=e.assist;if(i){const e=i[jr]();e&&(t.title=e);const a=i.role.match(Mn);if(a){const e="heading",i=a[1];t.role=e;t["aria-level"]=i}}if("table"===e.layout)t.role="table";else if("row"===e.layout)t.role="row";else{const i=e[Ir]();"row"===i.layout&&(t.role="TH"===i.assist?.role?"columnheader":"cell")}}function ariaLabel(e){if(!e.assist)return null;const t=e.assist;return t.speak&&""!==t.speak[Os]?t.speak[Os]:t.toolTip?t.toolTip[Os]:null}function valueToHtml(e){return HTMLResult.success({name:"div",attributes:{class:["xfaRich"],style:Object.create(null)},children:[{name:"span",attributes:{style:Object.create(null)},value:e}]})}function setFirstUnsplittable(e){const t=e[cr]();if(null===t[Xs].firstUnsplittable){t[Xs].firstUnsplittable=e;t[Xs].noLayoutFailure=!0}}function unsetFirstUnsplittable(e){const t=e[cr]();t[Xs].firstUnsplittable===e&&(t[Xs].noLayoutFailure=!1)}function handleBreak(e){if(e[Xs])return!1;e[Xs]=Object.create(null);if("auto"===e.targetType)return!1;const t=e[cr]();let i=null;if(e.target){i=t[vr](e.target,e[Ir]());if(!i)return!1;i=i[0]}const{currentPageArea:a,currentContentArea:s}=t[Xs];if("pageArea"===e.targetType){i instanceof PageArea||(i=null);if(e.startNew){e[Xs].target=i||a;return!0}if(i&&i!==a){e[Xs].target=i;return!0}return!1}i instanceof ContentArea||(i=null);const r=i&&i[Ir]();let n,g=r;if(e.startNew)if(i){const e=r.contentArea.children,t=e.indexOf(s),a=e.indexOf(i);-1!==t&&te;a[Xs].noLayoutFailure=!0;const n=t[jr](i);e[Ls](n.html,n.bbox);a[Xs].noLayoutFailure=s;t[or]=r}class AppearanceFilter extends StringObject{constructor(e){super(Nn,"appearanceFilter");this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Arc extends XFAObject{constructor(e){super(Nn,"arc",!0);this.circular=getInteger({data:e.circular,defaultValue:0,validate:e=>1===e});this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.startAngle=getFloat({data:e.startAngle,defaultValue:0,validate:e=>!0});this.sweepAngle=getFloat({data:e.sweepAngle,defaultValue:360,validate:e=>!0});this.use=e.use||"";this.usehref=e.usehref||"";this.edge=null;this.fill=null}[jr](){const e=this.edge||new Edge({}),t=e[Zr](),i=Object.create(null);"visible"===this.fill?.presence?Object.assign(i,this.fill[Zr]()):i.fill="transparent";i.strokeWidth=measureToString("visible"===e.presence?e.thickness:0);i.stroke=t.color;let a;const s={xmlns:Gn,style:{width:"100%",height:"100%",overflow:"visible"}};if(360===this.sweepAngle)a={name:"ellipse",attributes:{xmlns:Gn,cx:"50%",cy:"50%",rx:"50%",ry:"50%",style:i}};else{const e=this.startAngle*Math.PI/180,t=this.sweepAngle*Math.PI/180,r=this.sweepAngle>180?1:0,[n,g,o,c]=[50*(1+Math.cos(e)),50*(1-Math.sin(e)),50*(1+Math.cos(e+t)),50*(1-Math.sin(e+t))];a={name:"path",attributes:{xmlns:Gn,d:`M ${n} ${g} A 50 50 0 ${r} 0 ${o} ${c}`,vectorEffect:"non-scaling-stroke",style:i}};Object.assign(s,{viewBox:"0 0 100 100",preserveAspectRatio:"none"})}const r={name:"svg",children:[a],attributes:s};if(hasMargin(this[Ir]()[Ir]()))return HTMLResult.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[r]});r.attributes.style.position="absolute";return HTMLResult.success(r)}}class Area extends XFAObject{constructor(e){super(Nn,"area",!0);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.id=e.id||"";this.name=e.name||"";this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.desc=null;this.extras=null;this.area=new XFAObjectArray;this.draw=new XFAObjectArray;this.exObject=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.field=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray}*[nr](){yield*getContainedChildren(this)}[Dr](){return!0}[dr](){return!0}[Ls](e,t){const[i,a,s,r]=t;this[Xs].width=Math.max(this[Xs].width,i+s);this[Xs].height=Math.max(this[Xs].height,a+r);this[Xs].children.push(e)}[$s](){return this[Xs].availableSpace}[jr](e){const t=toStyle(this,"position"),i={style:t,id:this[Vr],class:["xfaArea"]};isPrintOnly(this)&&i.class.push("xfaPrintOnly");this.name&&(i.xfaName=this.name);const a=[];this[Xs]={children:a,width:0,height:0,availableSpace:e};const s=this[Js]({filter:new Set(["area","draw","field","exclGroup","subform","subformSet"]),include:!0});if(!s.success){if(s.isBreak())return s;delete this[Xs];return HTMLResult.FAILURE}t.width=measureToString(this[Xs].width);t.height=measureToString(this[Xs].height);const r={name:"div",attributes:i,children:a},n=[this.x,this.y,this[Xs].width,this[Xs].height];delete this[Xs];return HTMLResult.success(r,n)}}class Assist extends XFAObject{constructor(e){super(Nn,"assist",!0);this.id=e.id||"";this.role=e.role||"";this.use=e.use||"";this.usehref=e.usehref||"";this.speak=null;this.toolTip=null}[jr](){return this.toolTip?.[Os]||null}}class Barcode extends XFAObject{constructor(e){super(Nn,"barcode",!0);this.charEncoding=getKeyword({data:e.charEncoding?e.charEncoding.toLowerCase():"",defaultValue:"",validate:e=>["utf-8","big-five","fontspecific","gbk","gb-18030","gb-2312","ksc-5601","none","shift-jis","ucs-2","utf-16"].includes(e)||e.match(/iso-8859-\d{2}/)});this.checksum=getStringOption(e.checksum,["none","1mod10","1mod10_1mod11","2mod10","auto"]);this.dataColumnCount=getInteger({data:e.dataColumnCount,defaultValue:-1,validate:e=>e>=0});this.dataLength=getInteger({data:e.dataLength,defaultValue:-1,validate:e=>e>=0});this.dataPrep=getStringOption(e.dataPrep,["none","flateCompress"]);this.dataRowCount=getInteger({data:e.dataRowCount,defaultValue:-1,validate:e=>e>=0});this.endChar=e.endChar||"";this.errorCorrectionLevel=getInteger({data:e.errorCorrectionLevel,defaultValue:-1,validate:e=>e>=0&&e<=8});this.id=e.id||"";this.moduleHeight=getMeasurement(e.moduleHeight,"5mm");this.moduleWidth=getMeasurement(e.moduleWidth,"0.25mm");this.printCheckDigit=getInteger({data:e.printCheckDigit,defaultValue:0,validate:e=>1===e});this.rowColumnRatio=getRatio(e.rowColumnRatio);this.startChar=e.startChar||"";this.textLocation=getStringOption(e.textLocation,["below","above","aboveEmbedded","belowEmbedded","none"]);this.truncate=getInteger({data:e.truncate,defaultValue:0,validate:e=>1===e});this.type=getStringOption(e.type?e.type.toLowerCase():"",["aztec","codabar","code2of5industrial","code2of5interleaved","code2of5matrix","code2of5standard","code3of9","code3of9extended","code11","code49","code93","code128","code128a","code128b","code128c","code128sscc","datamatrix","ean8","ean8add2","ean8add5","ean13","ean13add2","ean13add5","ean13pwcd","fim","logmars","maxicode","msi","pdf417","pdf417macro","plessey","postauscust2","postauscust3","postausreplypaid","postausstandard","postukrm4scc","postusdpbc","postusimb","postusstandard","postus5zip","qrcode","rfid","rss14","rss14expanded","rss14limited","rss14stacked","rss14stackedomni","rss14truncated","telepen","ucc128","ucc128random","ucc128sscc","upca","upcaadd2","upcaadd5","upcapwcd","upce","upceadd2","upceadd5","upcean2","upcean5","upsmaxicode"]);this.upsMode=getStringOption(e.upsMode,["usCarrier","internationalCarrier","secureSymbol","standardSymbol"]);this.use=e.use||"";this.usehref=e.usehref||"";this.wideNarrowRatio=getRatio(e.wideNarrowRatio);this.encrypt=null;this.extras=null}}class Bind extends XFAObject{constructor(e){super(Nn,"bind",!0);this.match=getStringOption(e.match,["once","dataRef","global","none"]);this.ref=e.ref||"";this.picture=null}}class BindItems extends XFAObject{constructor(e){super(Nn,"bindItems");this.connection=e.connection||"";this.labelRef=e.labelRef||"";this.ref=e.ref||"";this.valueRef=e.valueRef||""}}class Bookend extends XFAObject{constructor(e){super(Nn,"bookend");this.id=e.id||"";this.leader=e.leader||"";this.trailer=e.trailer||"";this.use=e.use||"";this.usehref=e.usehref||""}}class BooleanElement extends Option01{constructor(e){super(Nn,"boolean");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[jr](e){return valueToHtml(1===this[Os]?"1":"0")}}class Border extends XFAObject{constructor(e){super(Nn,"border",!0);this.break=getStringOption(e.break,["close","open"]);this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.corner=new XFAObjectArray(4);this.edge=new XFAObjectArray(4);this.extras=null;this.fill=null;this.margin=null}[ar](){if(!this[Xs]){const e=this.edge.children.slice();if(e.length<4){const t=e.at(-1)||new Edge({});for(let i=e.length;i<4;i++)e.push(t)}const t=e.map((e=>e.thickness)),i=[0,0,0,0];if(this.margin){i[0]=this.margin.topInset;i[1]=this.margin.rightInset;i[2]=this.margin.bottomInset;i[3]=this.margin.leftInset}this[Xs]={widths:t,insets:i,edges:e}}return this[Xs]}[Zr](){const{edges:e}=this[ar](),t=e.map((e=>{const t=e[Zr]();t.color||="#000000";return t})),i=Object.create(null);this.margin&&Object.assign(i,this.margin[Zr]());"visible"===this.fill?.presence&&Object.assign(i,this.fill[Zr]());if(this.corner.children.some((e=>0!==e.radius))){const e=this.corner.children.map((e=>e[Zr]()));if(2===e.length||3===e.length){const t=e.at(-1);for(let i=e.length;i<4;i++)e.push(t)}i.borderRadius=e.map((e=>e.radius)).join(" ")}switch(this.presence){case"invisible":case"hidden":i.borderStyle="";break;case"inactive":i.borderStyle="none";break;default:i.borderStyle=t.map((e=>e.style)).join(" ")}i.borderWidth=t.map((e=>e.width)).join(" ");i.borderColor=t.map((e=>e.color)).join(" ");return i}}class Break extends XFAObject{constructor(e){super(Nn,"break",!0);this.after=getStringOption(e.after,["auto","contentArea","pageArea","pageEven","pageOdd"]);this.afterTarget=e.afterTarget||"";this.before=getStringOption(e.before,["auto","contentArea","pageArea","pageEven","pageOdd"]);this.beforeTarget=e.beforeTarget||"";this.bookendLeader=e.bookendLeader||"";this.bookendTrailer=e.bookendTrailer||"";this.id=e.id||"";this.overflowLeader=e.overflowLeader||"";this.overflowTarget=e.overflowTarget||"";this.overflowTrailer=e.overflowTrailer||"";this.startNew=getInteger({data:e.startNew,defaultValue:0,validate:e=>1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}}class BreakAfter extends XFAObject{constructor(e){super(Nn,"breakAfter",!0);this.id=e.id||"";this.leader=e.leader||"";this.startNew=getInteger({data:e.startNew,defaultValue:0,validate:e=>1===e});this.target=e.target||"";this.targetType=getStringOption(e.targetType,["auto","contentArea","pageArea"]);this.trailer=e.trailer||"";this.use=e.use||"";this.usehref=e.usehref||"";this.script=null}}class BreakBefore extends XFAObject{constructor(e){super(Nn,"breakBefore",!0);this.id=e.id||"";this.leader=e.leader||"";this.startNew=getInteger({data:e.startNew,defaultValue:0,validate:e=>1===e});this.target=e.target||"";this.targetType=getStringOption(e.targetType,["auto","contentArea","pageArea"]);this.trailer=e.trailer||"";this.use=e.use||"";this.usehref=e.usehref||"";this.script=null}[jr](e){this[Xs]={};return HTMLResult.FAILURE}}class Button extends XFAObject{constructor(e){super(Nn,"button",!0);this.highlight=getStringOption(e.highlight,["inverted","none","outline","push"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[jr](e){const t=this[Ir]()[Ir](),i={name:"button",attributes:{id:this[Vr],class:["xfaButton"],style:{}},children:[]};for(const e of t.event.children){if("click"!==e.activity||!e.script)continue;const t=recoverJsURL(e.script[Os]);if(!t)continue;const a=fixURL(t.url);a&&i.children.push({name:"a",attributes:{id:"link"+this[Vr],href:a,newWindow:t.newWindow,class:["xfaLink"],style:{}},children:[]})}return HTMLResult.success(i)}}class Calculate extends XFAObject{constructor(e){super(Nn,"calculate",!0);this.id=e.id||"";this.override=getStringOption(e.override,["disabled","error","ignore","warning"]);this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.message=null;this.script=null}}class Caption extends XFAObject{constructor(e){super(Nn,"caption",!0);this.id=e.id||"";this.placement=getStringOption(e.placement,["left","bottom","inline","right","top"]);this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.reserve=Math.ceil(getMeasurement(e.reserve));this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.font=null;this.margin=null;this.para=null;this.value=null}[qr](e){_setValue(this,e)}[ar](e){if(!this[Xs]){let{width:t,height:i}=e;switch(this.placement){case"left":case"right":case"inline":t=this.reserve<=0?t:this.reserve;break;case"top":case"bottom":i=this.reserve<=0?i:this.reserve}this[Xs]=layoutNode(this,{width:t,height:i})}return this[Xs]}[jr](e){if(!this.value)return HTMLResult.EMPTY;this[Lr]();const t=this.value[jr](e).html;if(!t){this[xr]();return HTMLResult.EMPTY}const i=this.reserve;if(this.reserve<=0){const{w:t,h:i}=this[ar](e);switch(this.placement){case"left":case"right":case"inline":this.reserve=t;break;case"top":case"bottom":this.reserve=i}}const a=[];"string"==typeof t?a.push({name:"#text",value:t}):a.push(t);const s=toStyle(this,"font","margin","visibility");switch(this.placement){case"left":case"right":this.reserve>0&&(s.width=measureToString(this.reserve));break;case"top":case"bottom":this.reserve>0&&(s.height=measureToString(this.reserve))}setPara(this,null,t);this[xr]();this.reserve=i;return HTMLResult.success({name:"div",attributes:{style:s,class:["xfaCaption"]},children:a})}}class Certificate extends StringObject{constructor(e){super(Nn,"certificate");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Certificates extends XFAObject{constructor(e){super(Nn,"certificates",!0);this.credentialServerPolicy=getStringOption(e.credentialServerPolicy,["optional","required"]);this.id=e.id||"";this.url=e.url||"";this.urlPolicy=e.urlPolicy||"";this.use=e.use||"";this.usehref=e.usehref||"";this.encryption=null;this.issuers=null;this.keyUsage=null;this.oids=null;this.signing=null;this.subjectDNs=null}}class CheckButton extends XFAObject{constructor(e){super(Nn,"checkButton",!0);this.id=e.id||"";this.mark=getStringOption(e.mark,["default","check","circle","cross","diamond","square","star"]);this.shape=getStringOption(e.shape,["square","round"]);this.size=getMeasurement(e.size,"10pt");this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}[jr](e){const t=toStyle("margin"),i=measureToString(this.size);t.width=t.height=i;let a,s,r;const n=this[Ir]()[Ir](),g=n.items.children.length&&n.items.children[0][jr]().html||[],o={on:(void 0!==g[0]?g[0]:"on").toString(),off:(void 0!==g[1]?g[1]:"off").toString()},c=(n.value?.[Pr]()||"off")===o.on||void 0,C=n[or](),h=n[Vr];let l;if(C instanceof ExclGroup){r=C[Vr];a="radio";s="xfaRadio";l=C[Ws]?.[Vr]||C[Vr]}else{a="checkbox";s="xfaCheckbox";l=n[Ws]?.[Vr]||n[Vr]}const Q={name:"input",attributes:{class:[s],style:t,fieldId:h,dataId:l,type:a,checked:c,xfaOn:o.on,xfaOff:o.off,"aria-label":ariaLabel(n),"aria-required":!1}};r&&(Q.attributes.name=r);if(isRequired(n)){Q.attributes["aria-required"]=!0;Q.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[Q]})}}class ChoiceList extends XFAObject{constructor(e){super(Nn,"choiceList",!0);this.commitOn=getStringOption(e.commitOn,["select","exit"]);this.id=e.id||"";this.open=getStringOption(e.open,["userControl","always","multiSelect","onEntry"]);this.textEntry=getInteger({data:e.textEntry,defaultValue:0,validate:e=>1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}[jr](e){const t=toStyle(this,"border","margin"),i=this[Ir]()[Ir](),a={fontSize:`calc(${i.font?.size||10}px * var(--scale-factor))`},s=[];if(i.items.children.length>0){const e=i.items;let t=0,r=0;if(2===e.children.length){t=e.children[0].save;r=1-t}const n=e.children[t][jr]().html,g=e.children[r][jr]().html;let o=!1;const c=i.value?.[Pr]()||"";for(let e=0,t=n.length;eMath.min(Math.max(0,parseInt(e.trim(),10)),255))).map((e=>isNaN(e)?0:e));if(r.length<3)return{r:i,g:a,b:s};[i,a,s]=r;return{r:i,g:a,b:s}}(e.value):"";this.extras=null}[hr](){return!1}[Zr](){return this.value?Util.makeHexColor(this.value.r,this.value.g,this.value.b):null}}class Comb extends XFAObject{constructor(e){super(Nn,"comb");this.id=e.id||"";this.numberOfCells=getInteger({data:e.numberOfCells,defaultValue:0,validate:e=>e>=0});this.use=e.use||"";this.usehref=e.usehref||""}}class Connect extends XFAObject{constructor(e){super(Nn,"connect",!0);this.connection=e.connection||"";this.id=e.id||"";this.ref=e.ref||"";this.usage=getStringOption(e.usage,["exportAndImport","exportOnly","importOnly"]);this.use=e.use||"";this.usehref=e.usehref||"";this.picture=null}}class ContentArea extends XFAObject{constructor(e){super(Nn,"contentArea",!0);this.h=getMeasurement(e.h);this.id=e.id||"";this.name=e.name||"";this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.w=getMeasurement(e.w);this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.desc=null;this.extras=null}[jr](e){const t={left:measureToString(this.x),top:measureToString(this.y),width:measureToString(this.w),height:measureToString(this.h)},i=["xfaContentarea"];isPrintOnly(this)&&i.push("xfaPrintOnly");return HTMLResult.success({name:"div",children:[],attributes:{style:t,class:i,id:this[Vr]}})}}class Corner extends XFAObject{constructor(e){super(Nn,"corner",!0);this.id=e.id||"";this.inverted=getInteger({data:e.inverted,defaultValue:0,validate:e=>1===e});this.join=getStringOption(e.join,["square","round"]);this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.radius=getMeasurement(e.radius);this.stroke=getStringOption(e.stroke,["solid","dashDot","dashDotDot","dashed","dotted","embossed","etched","lowered","raised"]);this.thickness=getMeasurement(e.thickness,"0.5pt");this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zr](){const e=toStyle(this,"visibility");e.radius=measureToString("square"===this.join?0:this.radius);return e}}class DateElement extends ContentObject{constructor(e){super(Nn,"date");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){const e=this[Os].trim();this[Os]=e?new Date(e):null}[jr](e){return valueToHtml(this[Os]?this[Os].toString():"")}}class DateTime extends ContentObject{constructor(e){super(Nn,"dateTime");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){const e=this[Os].trim();this[Os]=e?new Date(e):null}[jr](e){return valueToHtml(this[Os]?this[Os].toString():"")}}class DateTimeEdit extends XFAObject{constructor(e){super(Nn,"dateTimeEdit",!0);this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.picker=getStringOption(e.picker,["host","none"]);this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.comb=null;this.extras=null;this.margin=null}[jr](e){const t=toStyle(this,"border","font","margin"),i=this[Ir]()[Ir](),a={name:"input",attributes:{type:"text",fieldId:i[Vr],dataId:i[Ws]?.[Vr]||i[Vr],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(i),"aria-required":!1}};if(isRequired(i)){a.attributes["aria-required"]=!0;a.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[a]})}}class Decimal extends ContentObject{constructor(e){super(Nn,"decimal");this.fracDigits=getInteger({data:e.fracDigits,defaultValue:2,validate:e=>!0});this.id=e.id||"";this.leadDigits=getInteger({data:e.leadDigits,defaultValue:-1,validate:e=>!0});this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){const e=parseFloat(this[Os].trim());this[Os]=isNaN(e)?null:e}[jr](e){return valueToHtml(null!==this[Os]?this[Os].toString():"")}}class DefaultUi extends XFAObject{constructor(e){super(Nn,"defaultUi",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}}class Desc extends XFAObject{constructor(e){super(Nn,"desc",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}}class DigestMethod extends OptionObject{constructor(e){super(Nn,"digestMethod",["","SHA1","SHA256","SHA512","RIPEMD160"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class DigestMethods extends XFAObject{constructor(e){super(Nn,"digestMethods",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.digestMethod=new XFAObjectArray}}class Draw extends XFAObject{constructor(e){super(Nn,"draw",!0);this.anchorType=getStringOption(e.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.locale=e.locale||"";this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.rotate=getInteger({data:e.rotate,defaultValue:0,validate:e=>e%90==0});this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.border=null;this.caption=null;this.desc=null;this.extras=null;this.font=null;this.keep=null;this.margin=null;this.para=null;this.traversal=null;this.ui=null;this.value=null;this.setProperty=new XFAObjectArray}[qr](e){_setValue(this,e)}[jr](e){setTabIndex(this);if("hidden"===this.presence||"inactive"===this.presence)return HTMLResult.EMPTY;fixDimensions(this);this[Lr]();const t=this.w,i=this.h,{w:a,h:s,isBroken:r}=layoutNode(this,e);if(a&&""===this.w){if(r&&this[or]()[wr]()){this[xr]();return HTMLResult.FAILURE}this.w=a}s&&""===this.h&&(this.h=s);setFirstUnsplittable(this);if(!checkDimensions(this,e)){this.w=t;this.h=i;this[xr]();return HTMLResult.FAILURE}unsetFirstUnsplittable(this);const n=toStyle(this,"font","hAlign","dimensions","position","presence","rotate","anchorType","border","margin");setMinMaxDimensions(this,n);if(n.margin){n.padding=n.margin;delete n.margin}const g=["xfaDraw"];this.font&&g.push("xfaFont");isPrintOnly(this)&&g.push("xfaPrintOnly");const o={style:n,id:this[Vr],class:g};this.name&&(o.xfaName=this.name);const c={name:"div",attributes:o,children:[]};applyAssist(this,o);const C=computeBbox(this,c,e),h=this.value?this.value[jr](e).html:null;if(null===h){this.w=t;this.h=i;this[xr]();return HTMLResult.success(createWrapper(this,c),C)}c.children.push(h);setPara(this,n,h);this.w=t;this.h=i;this[xr]();return HTMLResult.success(createWrapper(this,c),C)}}class Edge extends XFAObject{constructor(e){super(Nn,"edge",!0);this.cap=getStringOption(e.cap,["square","butt","round"]);this.id=e.id||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.stroke=getStringOption(e.stroke,["solid","dashDot","dashDotDot","dashed","dotted","embossed","etched","lowered","raised"]);this.thickness=getMeasurement(e.thickness,"0.5pt");this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zr](){const e=toStyle(this,"visibility");Object.assign(e,{linecap:this.cap,width:measureToString(this.thickness),color:this.color?this.color[Zr]():"#000000",style:""});if("visible"!==this.presence)e.style="none";else switch(this.stroke){case"solid":e.style="solid";break;case"dashDot":case"dashDotDot":case"dashed":e.style="dashed";break;case"dotted":e.style="dotted";break;case"embossed":e.style="ridge";break;case"etched":e.style="groove";break;case"lowered":e.style="inset";break;case"raised":e.style="outset"}return e}}class Encoding extends OptionObject{constructor(e){super(Nn,"encoding",["adbe.x509.rsa_sha1","adbe.pkcs7.detached","adbe.pkcs7.sha1"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Encodings extends XFAObject{constructor(e){super(Nn,"encodings",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.encoding=new XFAObjectArray}}class Encrypt extends XFAObject{constructor(e){super(Nn,"encrypt",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=null}}class EncryptData extends XFAObject{constructor(e){super(Nn,"encryptData",!0);this.id=e.id||"";this.operation=getStringOption(e.operation,["encrypt","decrypt"]);this.target=e.target||"";this.use=e.use||"";this.usehref=e.usehref||"";this.filter=null;this.manifest=null}}class Encryption extends XFAObject{constructor(e){super(Nn,"encryption",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=new XFAObjectArray}}class EncryptionMethod extends OptionObject{constructor(e){super(Nn,"encryptionMethod",["","AES256-CBC","TRIPLEDES-CBC","AES128-CBC","AES192-CBC"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class EncryptionMethods extends XFAObject{constructor(e){super(Nn,"encryptionMethods",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.encryptionMethod=new XFAObjectArray}}class Event extends XFAObject{constructor(e){super(Nn,"event",!0);this.activity=getStringOption(e.activity,["click","change","docClose","docReady","enter","exit","full","indexChange","initialize","mouseDown","mouseEnter","mouseExit","mouseUp","postExecute","postOpen","postPrint","postSave","postSign","postSubmit","preExecute","preOpen","prePrint","preSave","preSign","preSubmit","ready","validationState"]);this.id=e.id||"";this.listen=getStringOption(e.listen,["refOnly","refAndDescendents"]);this.name=e.name||"";this.ref=e.ref||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.encryptData=null;this.execute=null;this.script=null;this.signData=null;this.submit=null}}class ExData extends ContentObject{constructor(e){super(Nn,"exData");this.contentType=e.contentType||"";this.href=e.href||"";this.id=e.id||"";this.maxLength=getInteger({data:e.maxLength,defaultValue:-1,validate:e=>e>=-1});this.name=e.name||"";this.rid=e.rid||"";this.transferEncoding=getStringOption(e.transferEncoding,["none","base64","package"]);this.use=e.use||"";this.usehref=e.usehref||""}[ur](){return"text/html"===this.contentType}[Nr](e){if("text/html"===this.contentType&&e[Sr]===_r.xhtml.id){this[Os]=e;return!0}if("text/xml"===this.contentType){this[Os]=e;return!0}return!1}[jr](e){return"text/html"===this.contentType&&this[Os]?this[Os][jr](e):HTMLResult.EMPTY}}class ExObject extends XFAObject{constructor(e){super(Nn,"exObject",!0);this.archive=e.archive||"";this.classId=e.classId||"";this.codeBase=e.codeBase||"";this.codeType=e.codeType||"";this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.exObject=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}}class ExclGroup extends XFAObject{constructor(e){super(Nn,"exclGroup",!0);this.access=getStringOption(e.access,["open","nonInteractive","protected","readOnly"]);this.accessKey=e.accessKey||"";this.anchorType=getStringOption(e.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.layout=getStringOption(e.layout,["position","lr-tb","rl-row","rl-tb","row","table","tb"]);this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.bind=null;this.border=null;this.calculate=null;this.caption=null;this.desc=null;this.extras=null;this.margin=null;this.para=null;this.traversal=null;this.validate=null;this.connect=new XFAObjectArray;this.event=new XFAObjectArray;this.field=new XFAObjectArray;this.setProperty=new XFAObjectArray}[dr](){return!0}[hr](){return!0}[qr](e){for(const t of this.field.children){if(!t.value){const e=new Value({});t[Hs](e);t.value=e}t.value[qr](e)}}[wr](){return this.layout.endsWith("-tb")&&0===this[Xs].attempt&&this[Xs].numberInLine>0||this[Ir]()[wr]()}[yr](){const e=this[or]();if(!e[yr]())return!1;if(void 0!==this[Xs]._isSplittable)return this[Xs]._isSplittable;if("position"===this.layout||this.layout.includes("row")){this[Xs]._isSplittable=!1;return!1}if(e.layout?.endsWith("-tb")&&0!==e[Xs].numberInLine)return!1;this[Xs]._isSplittable=!0;return!0}[Vs](){return flushHTML(this)}[Ls](e,t){addHTML(this,e,t)}[$s](){return getAvailableSpace(this)}[jr](e){setTabIndex(this);if("hidden"===this.presence||"inactive"===this.presence||0===this.h||0===this.w)return HTMLResult.EMPTY;fixDimensions(this);const t=[],i={id:this[Vr],class:[]};setAccess(this,i.class);this[Xs]||(this[Xs]=Object.create(null));Object.assign(this[Xs],{children:t,attributes:i,attempt:0,line:null,numberInLine:0,availableSpace:{width:Math.min(this.w||1/0,e.width),height:Math.min(this.h||1/0,e.height)},width:0,height:0,prevHeight:0,currentWidth:0});const a=this[yr]();a||setFirstUnsplittable(this);if(!checkDimensions(this,e))return HTMLResult.FAILURE;const s=new Set(["field"]);if(this.layout.includes("row")){const e=this[or]().columnWidths;if(Array.isArray(e)&&e.length>0){this[Xs].columnWidths=e;this[Xs].currentColumn=0}}const r=toStyle(this,"anchorType","dimensions","position","presence","border","margin","hAlign"),n=["xfaExclgroup"],g=layoutClass(this);g&&n.push(g);isPrintOnly(this)&&n.push("xfaPrintOnly");i.style=r;i.class=n;this.name&&(i.xfaName=this.name);this[Lr]();const o="lr-tb"===this.layout||"rl-tb"===this.layout,c=o?2:1;for(;this[Xs].attempte>=1||-1===e});this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.locale=e.locale||"";this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.rotate=getInteger({data:e.rotate,defaultValue:0,validate:e=>e%90==0});this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.bind=null;this.border=null;this.calculate=null;this.caption=null;this.desc=null;this.extras=null;this.font=null;this.format=null;this.items=new XFAObjectArray(2);this.keep=null;this.margin=null;this.para=null;this.traversal=null;this.ui=null;this.validate=null;this.value=null;this.bindItems=new XFAObjectArray;this.connect=new XFAObjectArray;this.event=new XFAObjectArray;this.setProperty=new XFAObjectArray}[dr](){return!0}[qr](e){_setValue(this,e)}[jr](e){setTabIndex(this);if(!this.ui){this.ui=new Ui({});this.ui[Cr]=this[Cr];this[Hs](this.ui);let e;switch(this.items.children.length){case 0:e=new TextEdit({});this.ui.textEdit=e;break;case 1:e=new CheckButton({});this.ui.checkButton=e;break;case 2:e=new ChoiceList({});this.ui.choiceList=e}this.ui[Hs](e)}if(!this.ui||"hidden"===this.presence||"inactive"===this.presence||0===this.h||0===this.w)return HTMLResult.EMPTY;this.caption&&delete this.caption[Xs];this[Lr]();const t=this.caption?this.caption[jr](e).html:null,i=this.w,a=this.h;let s=0,r=0;if(this.margin){s=this.margin.leftInset+this.margin.rightInset;r=this.margin.topInset+this.margin.bottomInset}let n=null;if(""===this.w||""===this.h){let t=null,i=null,a=0,g=0;if(this.ui.checkButton)a=g=this.ui.checkButton.size;else{const{w:t,h:i}=layoutNode(this,e);if(null!==t){a=t;g=i}else g=function fonts_getMetrics(e,t=!1){let i=null;if(e){const t=stripQuotes(e.typeface),a=e[Cr].fontFinder.find(t);i=selectFont(e,a)}if(!i)return{lineHeight:12,lineGap:2,lineNoGap:10};const a=e.size||10,s=i.lineHeight?Math.max(t?0:1.2,i.lineHeight):1.2,r=void 0===i.lineGap?.2:i.lineGap;return{lineHeight:s*a,lineGap:r*a,lineNoGap:Math.max(1,s-r)*a}}(this.font,!0).lineNoGap}n=getBorderDims(this.ui[ar]());a+=n.w;g+=n.h;if(this.caption){const{w:s,h:r,isBroken:n}=this.caption[ar](e);if(n&&this[or]()[wr]()){this[xr]();return HTMLResult.FAILURE}t=s;i=r;switch(this.caption.placement){case"left":case"right":case"inline":t+=a;break;case"top":case"bottom":i+=g}}else{t=a;i=g}if(t&&""===this.w){t+=s;this.w=Math.min(this.maxW<=0?1/0:this.maxW,this.minW+1e>=1&&e<=5});this.appearanceFilter=null;this.certificates=null;this.digestMethods=null;this.encodings=null;this.encryptionMethods=null;this.handler=null;this.lockDocument=null;this.mdp=null;this.reasons=null;this.timeStamp=null}}class Float extends ContentObject{constructor(e){super(Nn,"float");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){const e=parseFloat(this[Os].trim());this[Os]=isNaN(e)?null:e}[jr](e){return valueToHtml(null!==this[Os]?this[Os].toString():"")}}class template_Font extends XFAObject{constructor(e){super(Nn,"font",!0);this.baselineShift=getMeasurement(e.baselineShift);this.fontHorizontalScale=getFloat({data:e.fontHorizontalScale,defaultValue:100,validate:e=>e>=0});this.fontVerticalScale=getFloat({data:e.fontVerticalScale,defaultValue:100,validate:e=>e>=0});this.id=e.id||"";this.kerningMode=getStringOption(e.kerningMode,["none","pair"]);this.letterSpacing=getMeasurement(e.letterSpacing,"0");this.lineThrough=getInteger({data:e.lineThrough,defaultValue:0,validate:e=>1===e||2===e});this.lineThroughPeriod=getStringOption(e.lineThroughPeriod,["all","word"]);this.overline=getInteger({data:e.overline,defaultValue:0,validate:e=>1===e||2===e});this.overlinePeriod=getStringOption(e.overlinePeriod,["all","word"]);this.posture=getStringOption(e.posture,["normal","italic"]);this.size=getMeasurement(e.size,"10pt");this.typeface=e.typeface||"Courier";this.underline=getInteger({data:e.underline,defaultValue:0,validate:e=>1===e||2===e});this.underlinePeriod=getStringOption(e.underlinePeriod,["all","word"]);this.use=e.use||"";this.usehref=e.usehref||"";this.weight=getStringOption(e.weight,["normal","bold"]);this.extras=null;this.fill=null}[Ys](e){super[Ys](e);this[Cr].usedTypefaces.add(this.typeface)}[Zr](){const e=toStyle(this,"fill"),t=e.color;if(t)if("#000000"===t)delete e.color;else if(!t.startsWith("#")){e.background=t;e.backgroundClip="text";e.color="transparent"}this.baselineShift&&(e.verticalAlign=measureToString(this.baselineShift));e.fontKerning="none"===this.kerningMode?"none":"normal";e.letterSpacing=measureToString(this.letterSpacing);if(0!==this.lineThrough){e.textDecoration="line-through";2===this.lineThrough&&(e.textDecorationStyle="double")}if(0!==this.overline){e.textDecoration="overline";2===this.overline&&(e.textDecorationStyle="double")}e.fontStyle=this.posture;e.fontSize=measureToString(.99*this.size);setFontFamily(this,this,this[Cr].fontFinder,e);if(0!==this.underline){e.textDecoration="underline";2===this.underline&&(e.textDecorationStyle="double")}e.fontWeight=this.weight;return e}}class Format extends XFAObject{constructor(e){super(Nn,"format",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.picture=null}}class Handler extends StringObject{constructor(e){super(Nn,"handler");this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Hyphenation extends XFAObject{constructor(e){super(Nn,"hyphenation");this.excludeAllCaps=getInteger({data:e.excludeAllCaps,defaultValue:0,validate:e=>1===e});this.excludeInitialCap=getInteger({data:e.excludeInitialCap,defaultValue:0,validate:e=>1===e});this.hyphenate=getInteger({data:e.hyphenate,defaultValue:0,validate:e=>1===e});this.id=e.id||"";this.pushCharacterCount=getInteger({data:e.pushCharacterCount,defaultValue:3,validate:e=>e>=0});this.remainCharacterCount=getInteger({data:e.remainCharacterCount,defaultValue:3,validate:e=>e>=0});this.use=e.use||"";this.usehref=e.usehref||"";this.wordCharacterCount=getInteger({data:e.wordCharacterCount,defaultValue:7,validate:e=>e>=0})}}class Image extends StringObject{constructor(e){super(Nn,"image");this.aspect=getStringOption(e.aspect,["fit","actual","height","none","width"]);this.contentType=e.contentType||"";this.href=e.href||"";this.id=e.id||"";this.name=e.name||"";this.transferEncoding=getStringOption(e.transferEncoding,["base64","none","package"]);this.use=e.use||"";this.usehref=e.usehref||""}[jr](){if(this.contentType&&!Un.has(this.contentType.toLowerCase()))return HTMLResult.EMPTY;let e=this[Cr].images&&this[Cr].images.get(this.href);if(!e&&(this.href||!this[Os]))return HTMLResult.EMPTY;e||"base64"!==this.transferEncoding||(e=function fromBase64Util(e){return Uint8Array.fromBase64?Uint8Array.fromBase64(e):stringToBytes(atob(e))}(this[Os]));if(!e)return HTMLResult.EMPTY;if(!this.contentType){for(const[t,i]of xn)if(e.length>t.length&&t.every(((t,i)=>t===e[i]))){this.contentType=i;break}if(!this.contentType)return HTMLResult.EMPTY}const t=new Blob([e],{type:this.contentType});let i;switch(this.aspect){case"fit":case"actual":break;case"height":i={height:"100%",objectFit:"fill"};break;case"none":i={width:"100%",height:"100%",objectFit:"fill"};break;case"width":i={width:"100%",objectFit:"fill"}}const a=this[Ir]();return HTMLResult.success({name:"img",attributes:{class:["xfaImage"],style:i,src:URL.createObjectURL(t),alt:a?ariaLabel(a[Ir]()):null}})}}class ImageEdit extends XFAObject{constructor(e){super(Nn,"imageEdit",!0);this.data=getStringOption(e.data,["link","embed"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}[jr](e){return"embed"===this.data?HTMLResult.success({name:"div",children:[],attributes:{}}):HTMLResult.EMPTY}}class Integer extends ContentObject{constructor(e){super(Nn,"integer");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){const e=parseInt(this[Os].trim(),10);this[Os]=isNaN(e)?null:e}[jr](e){return valueToHtml(null!==this[Os]?this[Os].toString():"")}}class Issuers extends XFAObject{constructor(e){super(Nn,"issuers",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=new XFAObjectArray}}class Items extends XFAObject{constructor(e){super(Nn,"items",!0);this.id=e.id||"";this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.ref=e.ref||"";this.save=getInteger({data:e.save,defaultValue:0,validate:e=>1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}[jr](){const e=[];for(const t of this[rr]())e.push(t[Pr]());return HTMLResult.success(e)}}class Keep extends XFAObject{constructor(e){super(Nn,"keep",!0);this.id=e.id||"";const t=["none","contentArea","pageArea"];this.intact=getStringOption(e.intact,t);this.next=getStringOption(e.next,t);this.previous=getStringOption(e.previous,t);this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}}class KeyUsage extends XFAObject{constructor(e){super(Nn,"keyUsage");const t=["","yes","no"];this.crlSign=getStringOption(e.crlSign,t);this.dataEncipherment=getStringOption(e.dataEncipherment,t);this.decipherOnly=getStringOption(e.decipherOnly,t);this.digitalSignature=getStringOption(e.digitalSignature,t);this.encipherOnly=getStringOption(e.encipherOnly,t);this.id=e.id||"";this.keyAgreement=getStringOption(e.keyAgreement,t);this.keyCertSign=getStringOption(e.keyCertSign,t);this.keyEncipherment=getStringOption(e.keyEncipherment,t);this.nonRepudiation=getStringOption(e.nonRepudiation,t);this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Line extends XFAObject{constructor(e){super(Nn,"line",!0);this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.slope=getStringOption(e.slope,["\\","/"]);this.use=e.use||"";this.usehref=e.usehref||"";this.edge=null}[jr](){const e=this[Ir]()[Ir](),t=this.edge||new Edge({}),i=t[Zr](),a=Object.create(null),s="visible"===t.presence?t.thickness:0;a.strokeWidth=measureToString(s);a.stroke=i.color;let r,n,g,o,c="100%",C="100%";if(e.w<=s){[r,n,g,o]=["50%",0,"50%","100%"];c=a.strokeWidth}else if(e.h<=s){[r,n,g,o]=[0,"50%","100%","50%"];C=a.strokeWidth}else"\\"===this.slope?[r,n,g,o]=[0,0,"100%","100%"]:[r,n,g,o]=[0,"100%","100%",0];const h={name:"svg",children:[{name:"line",attributes:{xmlns:Gn,x1:r,y1:n,x2:g,y2:o,style:a}}],attributes:{xmlns:Gn,width:c,height:C,style:{overflow:"visible"}}};if(hasMargin(e))return HTMLResult.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[h]});h.attributes.style.position="absolute";return HTMLResult.success(h)}}class Linear extends XFAObject{constructor(e){super(Nn,"linear",!0);this.id=e.id||"";this.type=getStringOption(e.type,["toRight","toBottom","toLeft","toTop"]);this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zr](e){e=e?e[Zr]():"#FFFFFF";return`linear-gradient(${this.type.replace(/([RBLT])/," $1").toLowerCase()}, ${e}, ${this.color?this.color[Zr]():"#000000"})`}}class LockDocument extends ContentObject{constructor(e){super(Nn,"lockDocument");this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){this[Os]=getStringOption(this[Os],["auto","0","1"])}}class Manifest extends XFAObject{constructor(e){super(Nn,"manifest",!0);this.action=getStringOption(e.action,["include","all","exclude"]);this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.ref=new XFAObjectArray}}class Margin extends XFAObject{constructor(e){super(Nn,"margin",!0);this.bottomInset=getMeasurement(e.bottomInset,"0");this.id=e.id||"";this.leftInset=getMeasurement(e.leftInset,"0");this.rightInset=getMeasurement(e.rightInset,"0");this.topInset=getMeasurement(e.topInset,"0");this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[Zr](){return{margin:measureToString(this.topInset)+" "+measureToString(this.rightInset)+" "+measureToString(this.bottomInset)+" "+measureToString(this.leftInset)}}}class Mdp extends XFAObject{constructor(e){super(Nn,"mdp");this.id=e.id||"";this.permissions=getInteger({data:e.permissions,defaultValue:2,validate:e=>1===e||3===e});this.signatureType=getStringOption(e.signatureType,["filler","author"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Medium extends XFAObject{constructor(e){super(Nn,"medium");this.id=e.id||"";this.imagingBBox=function getBBox(e){const t=-1;if(!e)return{x:t,y:t,width:t,height:t};const i=e.trim().split(/\s*,\s*/).map((e=>getMeasurement(e,"-1")));if(i.length<4||i[2]<0||i[3]<0)return{x:t,y:t,width:t,height:t};const[a,s,r,n]=i;return{x:a,y:s,width:r,height:n}}(e.imagingBBox);this.long=getMeasurement(e.long);this.orientation=getStringOption(e.orientation,["portrait","landscape"]);this.short=getMeasurement(e.short);this.stock=e.stock||"";this.trayIn=getStringOption(e.trayIn,["auto","delegate","pageFront"]);this.trayOut=getStringOption(e.trayOut,["auto","delegate"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Message extends XFAObject{constructor(e){super(Nn,"message",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.text=new XFAObjectArray}}class NumericEdit extends XFAObject{constructor(e){super(Nn,"numericEdit",!0);this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.comb=null;this.extras=null;this.margin=null}[jr](e){const t=toStyle(this,"border","font","margin"),i=this[Ir]()[Ir](),a={name:"input",attributes:{type:"text",fieldId:i[Vr],dataId:i[Ws]?.[Vr]||i[Vr],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(i),"aria-required":!1}};if(isRequired(i)){a.attributes["aria-required"]=!0;a.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[a]})}}class Occur extends XFAObject{constructor(e){super(Nn,"occur",!0);this.id=e.id||"";this.initial=""!==e.initial?getInteger({data:e.initial,defaultValue:"",validate:e=>!0}):"";this.max=""!==e.max?getInteger({data:e.max,defaultValue:1,validate:e=>!0}):"";this.min=""!==e.min?getInteger({data:e.min,defaultValue:1,validate:e=>!0}):"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[Ys](){const e=this[Ir](),t=this.min;""===this.min&&(this.min=e instanceof PageArea||e instanceof PageSet?0:1);""===this.max&&(this.max=""===t?e instanceof PageArea||e instanceof PageSet?-1:1:this.min);-1!==this.max&&this.max!0});this.name=e.name||"";this.numbered=getInteger({data:e.numbered,defaultValue:1,validate:e=>!0});this.oddOrEven=getStringOption(e.oddOrEven,["any","even","odd"]);this.pagePosition=getStringOption(e.pagePosition,["any","first","last","only","rest"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.desc=null;this.extras=null;this.medium=null;this.occur=null;this.area=new XFAObjectArray;this.contentArea=new XFAObjectArray;this.draw=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.field=new XFAObjectArray;this.subform=new XFAObjectArray}[br](){if(!this[Xs]){this[Xs]={numberOfUse:0};return!0}return!this.occur||-1===this.occur.max||this[Xs].numberOfUsee.oddOrEven===t&&e.pagePosition===i));if(a)return a;a=this.pageArea.children.find((e=>"any"===e.oddOrEven&&e.pagePosition===i));if(a)return a;a=this.pageArea.children.find((e=>"any"===e.oddOrEven&&"any"===e.pagePosition));return a||this.pageArea.children[0]}}class Para extends XFAObject{constructor(e){super(Nn,"para",!0);this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.lineHeight=e.lineHeight?getMeasurement(e.lineHeight,"0pt"):"";this.marginLeft=e.marginLeft?getMeasurement(e.marginLeft,"0pt"):"";this.marginRight=e.marginRight?getMeasurement(e.marginRight,"0pt"):"";this.orphans=getInteger({data:e.orphans,defaultValue:0,validate:e=>e>=0});this.preserve=e.preserve||"";this.radixOffset=e.radixOffset?getMeasurement(e.radixOffset,"0pt"):"";this.spaceAbove=e.spaceAbove?getMeasurement(e.spaceAbove,"0pt"):"";this.spaceBelow=e.spaceBelow?getMeasurement(e.spaceBelow,"0pt"):"";this.tabDefault=e.tabDefault?getMeasurement(this.tabDefault):"";this.tabStops=(e.tabStops||"").trim().split(/\s+/).map(((e,t)=>t%2==1?getMeasurement(e):e));this.textIndent=e.textIndent?getMeasurement(e.textIndent,"0pt"):"";this.use=e.use||"";this.usehref=e.usehref||"";this.vAlign=getStringOption(e.vAlign,["top","bottom","middle"]);this.widows=getInteger({data:e.widows,defaultValue:0,validate:e=>e>=0});this.hyphenation=null}[Zr](){const e=toStyle(this,"hAlign");""!==this.marginLeft&&(e.paddingLeft=measureToString(this.marginLeft));""!==this.marginRight&&(e.paddingRight=measureToString(this.marginRight));""!==this.spaceAbove&&(e.paddingTop=measureToString(this.spaceAbove));""!==this.spaceBelow&&(e.paddingBottom=measureToString(this.spaceBelow));if(""!==this.textIndent){e.textIndent=measureToString(this.textIndent);fixTextIndent(e)}this.lineHeight>0&&(e.lineHeight=measureToString(this.lineHeight));""!==this.tabDefault&&(e.tabSize=measureToString(this.tabDefault));this.tabStops.length;this.hyphenatation&&Object.assign(e,this.hyphenatation[Zr]());return e}}class PasswordEdit extends XFAObject{constructor(e){super(Nn,"passwordEdit",!0);this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.passwordChar=e.passwordChar||"*";this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}}class template_Pattern extends XFAObject{constructor(e){super(Nn,"pattern",!0);this.id=e.id||"";this.type=getStringOption(e.type,["crossHatch","crossDiagonal","diagonalLeft","diagonalRight","horizontal","vertical"]);this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zr](e){e=e?e[Zr]():"#FFFFFF";const t=this.color?this.color[Zr]():"#000000",i="repeating-linear-gradient",a=`${e},${e} 5px,${t} 5px,${t} 10px`;switch(this.type){case"crossHatch":return`${i}(to top,${a}) ${i}(to right,${a})`;case"crossDiagonal":return`${i}(45deg,${a}) ${i}(-45deg,${a})`;case"diagonalLeft":return`${i}(45deg,${a})`;case"diagonalRight":return`${i}(-45deg,${a})`;case"horizontal":return`${i}(to top,${a})`;case"vertical":return`${i}(to right,${a})`}return""}}class Picture extends StringObject{constructor(e){super(Nn,"picture");this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Proto extends XFAObject{constructor(e){super(Nn,"proto",!0);this.appearanceFilter=new XFAObjectArray;this.arc=new XFAObjectArray;this.area=new XFAObjectArray;this.assist=new XFAObjectArray;this.barcode=new XFAObjectArray;this.bindItems=new XFAObjectArray;this.bookend=new XFAObjectArray;this.boolean=new XFAObjectArray;this.border=new XFAObjectArray;this.break=new XFAObjectArray;this.breakAfter=new XFAObjectArray;this.breakBefore=new XFAObjectArray;this.button=new XFAObjectArray;this.calculate=new XFAObjectArray;this.caption=new XFAObjectArray;this.certificate=new XFAObjectArray;this.certificates=new XFAObjectArray;this.checkButton=new XFAObjectArray;this.choiceList=new XFAObjectArray;this.color=new XFAObjectArray;this.comb=new XFAObjectArray;this.connect=new XFAObjectArray;this.contentArea=new XFAObjectArray;this.corner=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.dateTimeEdit=new XFAObjectArray;this.decimal=new XFAObjectArray;this.defaultUi=new XFAObjectArray;this.desc=new XFAObjectArray;this.digestMethod=new XFAObjectArray;this.digestMethods=new XFAObjectArray;this.draw=new XFAObjectArray;this.edge=new XFAObjectArray;this.encoding=new XFAObjectArray;this.encodings=new XFAObjectArray;this.encrypt=new XFAObjectArray;this.encryptData=new XFAObjectArray;this.encryption=new XFAObjectArray;this.encryptionMethod=new XFAObjectArray;this.encryptionMethods=new XFAObjectArray;this.event=new XFAObjectArray;this.exData=new XFAObjectArray;this.exObject=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.execute=new XFAObjectArray;this.extras=new XFAObjectArray;this.field=new XFAObjectArray;this.fill=new XFAObjectArray;this.filter=new XFAObjectArray;this.float=new XFAObjectArray;this.font=new XFAObjectArray;this.format=new XFAObjectArray;this.handler=new XFAObjectArray;this.hyphenation=new XFAObjectArray;this.image=new XFAObjectArray;this.imageEdit=new XFAObjectArray;this.integer=new XFAObjectArray;this.issuers=new XFAObjectArray;this.items=new XFAObjectArray;this.keep=new XFAObjectArray;this.keyUsage=new XFAObjectArray;this.line=new XFAObjectArray;this.linear=new XFAObjectArray;this.lockDocument=new XFAObjectArray;this.manifest=new XFAObjectArray;this.margin=new XFAObjectArray;this.mdp=new XFAObjectArray;this.medium=new XFAObjectArray;this.message=new XFAObjectArray;this.numericEdit=new XFAObjectArray;this.occur=new XFAObjectArray;this.oid=new XFAObjectArray;this.oids=new XFAObjectArray;this.overflow=new XFAObjectArray;this.pageArea=new XFAObjectArray;this.pageSet=new XFAObjectArray;this.para=new XFAObjectArray;this.passwordEdit=new XFAObjectArray;this.pattern=new XFAObjectArray;this.picture=new XFAObjectArray;this.radial=new XFAObjectArray;this.reason=new XFAObjectArray;this.reasons=new XFAObjectArray;this.rectangle=new XFAObjectArray;this.ref=new XFAObjectArray;this.script=new XFAObjectArray;this.setProperty=new XFAObjectArray;this.signData=new XFAObjectArray;this.signature=new XFAObjectArray;this.signing=new XFAObjectArray;this.solid=new XFAObjectArray;this.speak=new XFAObjectArray;this.stipple=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray;this.subjectDN=new XFAObjectArray;this.subjectDNs=new XFAObjectArray;this.submit=new XFAObjectArray;this.text=new XFAObjectArray;this.textEdit=new XFAObjectArray;this.time=new XFAObjectArray;this.timeStamp=new XFAObjectArray;this.toolTip=new XFAObjectArray;this.traversal=new XFAObjectArray;this.traverse=new XFAObjectArray;this.ui=new XFAObjectArray;this.validate=new XFAObjectArray;this.value=new XFAObjectArray;this.variables=new XFAObjectArray}}class Radial extends XFAObject{constructor(e){super(Nn,"radial",!0);this.id=e.id||"";this.type=getStringOption(e.type,["toEdge","toCenter"]);this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zr](e){e=e?e[Zr]():"#FFFFFF";const t=this.color?this.color[Zr]():"#000000";return`radial-gradient(circle at center, ${"toEdge"===this.type?`${e},${t}`:`${t},${e}`})`}}class Reason extends StringObject{constructor(e){super(Nn,"reason");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Reasons extends XFAObject{constructor(e){super(Nn,"reasons",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.reason=new XFAObjectArray}}class Rectangle extends XFAObject{constructor(e){super(Nn,"rectangle",!0);this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.corner=new XFAObjectArray(4);this.edge=new XFAObjectArray(4);this.fill=null}[jr](){const e=this.edge.children.length?this.edge.children[0]:new Edge({}),t=e[Zr](),i=Object.create(null);"visible"===this.fill?.presence?Object.assign(i,this.fill[Zr]()):i.fill="transparent";i.strokeWidth=measureToString("visible"===e.presence?e.thickness:0);i.stroke=t.color;const a=(this.corner.children.length?this.corner.children[0]:new Corner({}))[Zr](),s={name:"svg",children:[{name:"rect",attributes:{xmlns:Gn,width:"100%",height:"100%",x:0,y:0,rx:a.radius,ry:a.radius,style:i}}],attributes:{xmlns:Gn,style:{overflow:"visible"},width:"100%",height:"100%"}};if(hasMargin(this[Ir]()[Ir]()))return HTMLResult.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[s]});s.attributes.style.position="absolute";return HTMLResult.success(s)}}class RefElement extends StringObject{constructor(e){super(Nn,"ref");this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Script extends StringObject{constructor(e){super(Nn,"script");this.binding=e.binding||"";this.contentType=e.contentType||"";this.id=e.id||"";this.name=e.name||"";this.runAt=getStringOption(e.runAt,["client","both","server"]);this.use=e.use||"";this.usehref=e.usehref||""}}class SetProperty extends XFAObject{constructor(e){super(Nn,"setProperty");this.connection=e.connection||"";this.ref=e.ref||"";this.target=e.target||""}}class SignData extends XFAObject{constructor(e){super(Nn,"signData",!0);this.id=e.id||"";this.operation=getStringOption(e.operation,["sign","clear","verify"]);this.ref=e.ref||"";this.target=e.target||"";this.use=e.use||"";this.usehref=e.usehref||"";this.filter=null;this.manifest=null}}class Signature extends XFAObject{constructor(e){super(Nn,"signature",!0);this.id=e.id||"";this.type=getStringOption(e.type,["PDF1.3","PDF1.6"]);this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.filter=null;this.manifest=null;this.margin=null}}class Signing extends XFAObject{constructor(e){super(Nn,"signing",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=new XFAObjectArray}}class Solid extends XFAObject{constructor(e){super(Nn,"solid",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[Zr](e){return e?e[Zr]():"#FFFFFF"}}class Speak extends StringObject{constructor(e){super(Nn,"speak");this.disable=getInteger({data:e.disable,defaultValue:0,validate:e=>1===e});this.id=e.id||"";this.priority=getStringOption(e.priority,["custom","caption","name","toolTip"]);this.rid=e.rid||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Stipple extends XFAObject{constructor(e){super(Nn,"stipple",!0);this.id=e.id||"";this.rate=getInteger({data:e.rate,defaultValue:50,validate:e=>e>=0&&e<=100});this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zr](e){const t=this.rate/100;return Util.makeHexColor(Math.round(e.value.r*(1-t)+this.value.r*t),Math.round(e.value.g*(1-t)+this.value.g*t),Math.round(e.value.b*(1-t)+this.value.b*t))}}class Subform extends XFAObject{constructor(e){super(Nn,"subform",!0);this.access=getStringOption(e.access,["open","nonInteractive","protected","readOnly"]);this.allowMacro=getInteger({data:e.allowMacro,defaultValue:0,validate:e=>1===e});this.anchorType=getStringOption(e.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.columnWidths=(e.columnWidths||"").trim().split(/\s+/).map((e=>"-1"===e?-1:getMeasurement(e)));this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.layout=getStringOption(e.layout,["position","lr-tb","rl-row","rl-tb","row","table","tb"]);this.locale=e.locale||"";this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.mergeMode=getStringOption(e.mergeMode,["consumeData","matchTemplate"]);this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.restoreState=getStringOption(e.restoreState,["manual","auto"]);this.scope=getStringOption(e.scope,["name","none"]);this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.bind=null;this.bookend=null;this.border=null;this.break=null;this.calculate=null;this.desc=null;this.extras=null;this.keep=null;this.margin=null;this.occur=null;this.overflow=null;this.pageSet=null;this.para=null;this.traversal=null;this.validate=null;this.variables=null;this.area=new XFAObjectArray;this.breakAfter=new XFAObjectArray;this.breakBefore=new XFAObjectArray;this.connect=new XFAObjectArray;this.draw=new XFAObjectArray;this.event=new XFAObjectArray;this.exObject=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.field=new XFAObjectArray;this.proto=new XFAObjectArray;this.setProperty=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray}[or](){const e=this[Ir]();return e instanceof SubformSet?e[or]():e}[dr](){return!0}[wr](){return this.layout.endsWith("-tb")&&0===this[Xs].attempt&&this[Xs].numberInLine>0||this[Ir]()[wr]()}*[nr](){yield*getContainedChildren(this)}[Vs](){return flushHTML(this)}[Ls](e,t){addHTML(this,e,t)}[$s](){return getAvailableSpace(this)}[yr](){const e=this[or]();if(!e[yr]())return!1;if(void 0!==this[Xs]._isSplittable)return this[Xs]._isSplittable;if("position"===this.layout||this.layout.includes("row")){this[Xs]._isSplittable=!1;return!1}if(this.keep&&"none"!==this.keep.intact){this[Xs]._isSplittable=!1;return!1}if(e.layout?.endsWith("-tb")&&0!==e[Xs].numberInLine)return!1;this[Xs]._isSplittable=!0;return!0}[jr](e){setTabIndex(this);if(this.break){if("auto"!==this.break.after||""!==this.break.afterTarget){const e=new BreakAfter({targetType:this.break.after,target:this.break.afterTarget,startNew:this.break.startNew.toString()});e[Cr]=this[Cr];this[Hs](e);this.breakAfter.push(e)}if("auto"!==this.break.before||""!==this.break.beforeTarget){const e=new BreakBefore({targetType:this.break.before,target:this.break.beforeTarget,startNew:this.break.startNew.toString()});e[Cr]=this[Cr];this[Hs](e);this.breakBefore.push(e)}if(""!==this.break.overflowTarget){const e=new Overflow({target:this.break.overflowTarget,leader:this.break.overflowLeader,trailer:this.break.overflowTrailer});e[Cr]=this[Cr];this[Hs](e);this.overflow.push(e)}this[Hr](this.break);this.break=null}if("hidden"===this.presence||"inactive"===this.presence)return HTMLResult.EMPTY;(this.breakBefore.children.length>1||this.breakAfter.children.length>1)&&warn("XFA - Several breakBefore or breakAfter in subforms: please file a bug.");if(this.breakBefore.children.length>=1){const e=this.breakBefore.children[0];if(handleBreak(e))return HTMLResult.breakNode(e)}if(this[Xs]?.afterBreakAfter)return HTMLResult.EMPTY;fixDimensions(this);const t=[],i={id:this[Vr],class:[]};setAccess(this,i.class);this[Xs]||(this[Xs]=Object.create(null));Object.assign(this[Xs],{children:t,line:null,attributes:i,attempt:0,numberInLine:0,availableSpace:{width:Math.min(this.w||1/0,e.width),height:Math.min(this.h||1/0,e.height)},width:0,height:0,prevHeight:0,currentWidth:0});const a=this[cr](),s=a[Xs].noLayoutFailure,r=this[yr]();r||setFirstUnsplittable(this);if(!checkDimensions(this,e))return HTMLResult.FAILURE;const n=new Set(["area","draw","exclGroup","field","subform","subformSet"]);if(this.layout.includes("row")){const e=this[or]().columnWidths;if(Array.isArray(e)&&e.length>0){this[Xs].columnWidths=e;this[Xs].currentColumn=0}}const g=toStyle(this,"anchorType","dimensions","position","presence","border","margin","hAlign"),o=["xfaSubform"],c=layoutClass(this);c&&o.push(c);i.style=g;i.class=o;this.name&&(i.xfaName=this.name);if(this.overflow){const t=this.overflow[ar]();if(t.addLeader){t.addLeader=!1;handleOverflow(this,t.leader,e)}}this[Lr]();const C="lr-tb"===this.layout||"rl-tb"===this.layout,h=C?2:1;for(;this[Xs].attempt=1){const e=this.breakAfter.children[0];if(handleBreak(e)){this[Xs].afterBreakAfter=p;return HTMLResult.breakNode(e)}}delete this[Xs];return p}}class SubformSet extends XFAObject{constructor(e){super(Nn,"subformSet",!0);this.id=e.id||"";this.name=e.name||"";this.relation=getStringOption(e.relation,["ordered","choice","unordered"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.bookend=null;this.break=null;this.desc=null;this.extras=null;this.occur=null;this.overflow=null;this.breakAfter=new XFAObjectArray;this.breakBefore=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray}*[nr](){yield*getContainedChildren(this)}[or](){let e=this[Ir]();for(;!(e instanceof Subform);)e=e[Ir]();return e}[dr](){return!0}}class SubjectDN extends ContentObject{constructor(e){super(Nn,"subjectDN");this.delimiter=e.delimiter||",";this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){this[Os]=new Map(this[Os].split(this.delimiter).map((e=>{(e=e.split("=",2))[0]=e[0].trim();return e})))}}class SubjectDNs extends XFAObject{constructor(e){super(Nn,"subjectDNs",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.subjectDN=new XFAObjectArray}}class Submit extends XFAObject{constructor(e){super(Nn,"submit",!0);this.embedPDF=getInteger({data:e.embedPDF,defaultValue:0,validate:e=>1===e});this.format=getStringOption(e.format,["xdp","formdata","pdf","urlencoded","xfd","xml"]);this.id=e.id||"";this.target=e.target||"";this.textEncoding=getKeyword({data:e.textEncoding?e.textEncoding.toLowerCase():"",defaultValue:"",validate:e=>["utf-8","big-five","fontspecific","gbk","gb-18030","gb-2312","ksc-5601","none","shift-jis","ucs-2","utf-16"].includes(e)||e.match(/iso-8859-\d{2}/)});this.use=e.use||"";this.usehref=e.usehref||"";this.xdpContent=e.xdpContent||"";this.encrypt=null;this.encryptData=new XFAObjectArray;this.signData=new XFAObjectArray}}class Template extends XFAObject{constructor(e){super(Nn,"template",!0);this.baseProfile=getStringOption(e.baseProfile,["full","interactiveForms"]);this.extras=null;this.subform=new XFAObjectArray}[Zs](){0===this.subform.children.length&&warn("XFA - No subforms in template node.");this.subform.children.length>=2&&warn("XFA - Several subforms in template node: please file a bug.");this[Or]=5e3}[yr](){return!0}[vr](e,t){return e.startsWith("#")?[this[lr].get(e.slice(1))]:searchNode(this,t,e,!0,!0)}*[Wr](){if(!this.subform.children.length)return HTMLResult.success({name:"div",children:[]});this[Xs]={overflowNode:null,firstUnsplittable:null,currentContentArea:null,currentPageArea:null,noLayoutFailure:!1,pageNumber:1,pagePosition:"first",oddOrEven:"odd",blankOrNotBlank:"nonBlank",paraStack:[]};const e=this.subform.children[0];e.pageSet[vs]();const t=e.pageSet.pageArea.children,i={name:"div",children:[]};let a=null,s=null,r=null;if(e.breakBefore.children.length>=1){s=e.breakBefore.children[0];r=s.target}else if(e.subform.children.length>=1&&e.subform.children[0].breakBefore.children.length>=1){s=e.subform.children[0].breakBefore.children[0];r=s.target}else if(e.break?.beforeTarget){s=e.break;r=s.beforeTarget}else if(e.subform.children.length>=1&&e.subform.children[0].break?.beforeTarget){s=e.subform.children[0].break;r=s.beforeTarget}if(s){const e=this[vr](r,s[Ir]());if(e instanceof PageArea){a=e;s[Xs]={}}}a||(a=t[0]);a[Xs]={numberOfUse:1};const n=a[Ir]();n[Xs]={numberOfUse:1,pageIndex:n.pageArea.children.indexOf(a),pageSetIndex:0};let g,o=null,c=null,C=!0,h=0,l=0;for(;;){if(C)h=0;else{i.children.pop();if(3==++h){warn("XFA - Something goes wrong: please file a bug.");return i}}g=null;this[Xs].currentPageArea=a;const t=a[jr]().html;i.children.push(t);if(o){this[Xs].noLayoutFailure=!0;t.children.push(o[jr](a[Xs].space).html);o=null}if(c){this[Xs].noLayoutFailure=!0;t.children.push(c[jr](a[Xs].space).html);c=null}const s=a.contentArea.children,r=t.children.filter((e=>e.attributes.class.includes("xfaContentarea")));C=!1;this[Xs].firstUnsplittable=null;this[Xs].noLayoutFailure=!1;const flush=t=>{const i=e[Vs]();if(i){C||=i.children?.length>0;r[t].children.push(i)}};for(let t=l,a=s.length;t0;r[t].children.push(h.html)}else!C&&i.children.length>1&&i.children.pop();return i}if(h.isBreak()){const e=h.breakNode;flush(t);if("auto"===e.targetType)continue;if(e.leader){o=this[vr](e.leader,e[Ir]());o=o?o[0]:null}if(e.trailer){c=this[vr](e.trailer,e[Ir]());c=c?c[0]:null}if("pageArea"===e.targetType){g=e[Xs].target;t=1/0}else if(e[Xs].target){g=e[Xs].target;l=e[Xs].index+1;t=1/0}else t=e[Xs].index}else if(this[Xs].overflowNode){const e=this[Xs].overflowNode;this[Xs].overflowNode=null;const i=e[ar](),a=i.target;i.addLeader=null!==i.leader;i.addTrailer=null!==i.trailer;flush(t);const r=t;t=1/0;if(a instanceof PageArea)g=a;else if(a instanceof ContentArea){const e=s.indexOf(a);if(-1!==e)e>r?t=e-1:l=e;else{g=a[Ir]();l=g.contentArea.children.indexOf(a)}}}else flush(t)}this[Xs].pageNumber+=1;g&&(g[br]()?g[Xs].numberOfUse+=1:g=null);a=g||a[gr]();yield null}}}class Text extends ContentObject{constructor(e){super(Nn,"text");this.id=e.id||"";this.maxChars=getInteger({data:e.maxChars,defaultValue:0,validate:e=>e>=0});this.name=e.name||"";this.rid=e.rid||"";this.use=e.use||"";this.usehref=e.usehref||""}[xs](){return!0}[Nr](e){if(e[Sr]===_r.xhtml.id){this[Os]=e;return!0}warn(`XFA - Invalid content in Text: ${e[kr]}.`);return!1}[Mr](e){this[Os]instanceof XFAObject||super[Mr](e)}[Zs](){"string"==typeof this[Os]&&(this[Os]=this[Os].replaceAll("\r\n","\n"))}[ar](){return"string"==typeof this[Os]?this[Os].split(/[\u2029\u2028\n]/).reduce(((e,t)=>{t&&e.push(t);return e}),[]).join("\n"):this[Os][Pr]()}[jr](e){if("string"==typeof this[Os]){const e=valueToHtml(this[Os]).html;if(this[Os].includes("\u2029")){e.name="div";e.children=[];this[Os].split("\u2029").map((e=>e.split(/[\u2028\n]/).reduce(((e,t)=>{e.push({name:"span",value:t},{name:"br"});return e}),[]))).forEach((t=>{e.children.push({name:"p",children:t})}))}else if(/[\u2028\n]/.test(this[Os])){e.name="div";e.children=[];this[Os].split(/[\u2028\n]/).forEach((t=>{e.children.push({name:"span",value:t},{name:"br"})}))}return HTMLResult.success(e)}return this[Os][jr](e)}}class TextEdit extends XFAObject{constructor(e){super(Nn,"textEdit",!0);this.allowRichText=getInteger({data:e.allowRichText,defaultValue:0,validate:e=>1===e});this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.multiLine=getInteger({data:e.multiLine,defaultValue:"",validate:e=>0===e||1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.vScrollPolicy=getStringOption(e.vScrollPolicy,["auto","off","on"]);this.border=null;this.comb=null;this.extras=null;this.margin=null}[jr](e){const t=toStyle(this,"border","font","margin");let i;const a=this[Ir]()[Ir]();""===this.multiLine&&(this.multiLine=a instanceof Draw?1:0);i=1===this.multiLine?{name:"textarea",attributes:{dataId:a[Ws]?.[Vr]||a[Vr],fieldId:a[Vr],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(a),"aria-required":!1}}:{name:"input",attributes:{type:"text",dataId:a[Ws]?.[Vr]||a[Vr],fieldId:a[Vr],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(a),"aria-required":!1}};if(isRequired(a)){i.attributes["aria-required"]=!0;i.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[i]})}}class Time extends StringObject{constructor(e){super(Nn,"time");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){const e=this[Os].trim();this[Os]=e?new Date(e):null}[jr](e){return valueToHtml(this[Os]?this[Os].toString():"")}}class TimeStamp extends XFAObject{constructor(e){super(Nn,"timeStamp");this.id=e.id||"";this.server=e.server||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class ToolTip extends StringObject{constructor(e){super(Nn,"toolTip");this.id=e.id||"";this.rid=e.rid||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Traversal extends XFAObject{constructor(e){super(Nn,"traversal",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.traverse=new XFAObjectArray}}class Traverse extends XFAObject{constructor(e){super(Nn,"traverse",!0);this.id=e.id||"";this.operation=getStringOption(e.operation,["next","back","down","first","left","right","up"]);this.ref=e.ref||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.script=null}get name(){return this.operation}[Dr](){return!1}}class Ui extends XFAObject{constructor(e){super(Nn,"ui",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.picture=null;this.barcode=null;this.button=null;this.checkButton=null;this.choiceList=null;this.dateTimeEdit=null;this.defaultUi=null;this.imageEdit=null;this.numericEdit=null;this.passwordEdit=null;this.signature=null;this.textEdit=null}[ar](){if(void 0===this[Xs]){for(const e of Object.getOwnPropertyNames(this)){if("extras"===e||"picture"===e)continue;const t=this[e];if(t instanceof XFAObject){this[Xs]=t;return t}}this[Xs]=null}return this[Xs]}[jr](e){const t=this[ar]();return t?t[jr](e):HTMLResult.EMPTY}}class Validate extends XFAObject{constructor(e){super(Nn,"validate",!0);this.formatTest=getStringOption(e.formatTest,["warning","disabled","error"]);this.id=e.id||"";this.nullTest=getStringOption(e.nullTest,["disabled","error","warning"]);this.scriptTest=getStringOption(e.scriptTest,["error","disabled","warning"]);this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.message=null;this.picture=null;this.script=null}}class Value extends XFAObject{constructor(e){super(Nn,"value",!0);this.id=e.id||"";this.override=getInteger({data:e.override,defaultValue:0,validate:e=>1===e});this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.arc=null;this.boolean=null;this.date=null;this.dateTime=null;this.decimal=null;this.exData=null;this.float=null;this.image=null;this.integer=null;this.line=null;this.rectangle=null;this.text=null;this.time=null}[qr](e){const t=this[Ir]();if(t instanceof Field&&t.ui?.imageEdit){if(!this.image){this.image=new Image({});this[Hs](this.image)}this.image[Os]=e[Os];return}const i=e[kr];if(null===this[i]){for(const e of Object.getOwnPropertyNames(this)){const t=this[e];if(t instanceof XFAObject){this[e]=null;this[Hr](t)}}this[e[kr]]=e;this[Hs](e)}else this[i][Os]=e[Os]}[Pr](){if(this.exData)return"string"==typeof this.exData[Os]?this.exData[Os].trim():this.exData[Os][Pr]().trim();for(const e of Object.getOwnPropertyNames(this)){if("image"===e)continue;const t=this[e];if(t instanceof XFAObject)return(t[Os]||"").toString().trim()}return null}[jr](e){for(const t of Object.getOwnPropertyNames(this)){const i=this[t];if(i instanceof XFAObject)return i[jr](e)}return HTMLResult.EMPTY}}class Variables extends XFAObject{constructor(e){super(Nn,"variables",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.manifest=new XFAObjectArray;this.script=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}[Dr](){return!0}}class TemplateNamespace{static[zr](e,t){if(TemplateNamespace.hasOwnProperty(e)){const i=TemplateNamespace[e](t);i[Tr](t);return i}}static appearanceFilter(e){return new AppearanceFilter(e)}static arc(e){return new Arc(e)}static area(e){return new Area(e)}static assist(e){return new Assist(e)}static barcode(e){return new Barcode(e)}static bind(e){return new Bind(e)}static bindItems(e){return new BindItems(e)}static bookend(e){return new Bookend(e)}static boolean(e){return new BooleanElement(e)}static border(e){return new Border(e)}static break(e){return new Break(e)}static breakAfter(e){return new BreakAfter(e)}static breakBefore(e){return new BreakBefore(e)}static button(e){return new Button(e)}static calculate(e){return new Calculate(e)}static caption(e){return new Caption(e)}static certificate(e){return new Certificate(e)}static certificates(e){return new Certificates(e)}static checkButton(e){return new CheckButton(e)}static choiceList(e){return new ChoiceList(e)}static color(e){return new Color(e)}static comb(e){return new Comb(e)}static connect(e){return new Connect(e)}static contentArea(e){return new ContentArea(e)}static corner(e){return new Corner(e)}static date(e){return new DateElement(e)}static dateTime(e){return new DateTime(e)}static dateTimeEdit(e){return new DateTimeEdit(e)}static decimal(e){return new Decimal(e)}static defaultUi(e){return new DefaultUi(e)}static desc(e){return new Desc(e)}static digestMethod(e){return new DigestMethod(e)}static digestMethods(e){return new DigestMethods(e)}static draw(e){return new Draw(e)}static edge(e){return new Edge(e)}static encoding(e){return new Encoding(e)}static encodings(e){return new Encodings(e)}static encrypt(e){return new Encrypt(e)}static encryptData(e){return new EncryptData(e)}static encryption(e){return new Encryption(e)}static encryptionMethod(e){return new EncryptionMethod(e)}static encryptionMethods(e){return new EncryptionMethods(e)}static event(e){return new Event(e)}static exData(e){return new ExData(e)}static exObject(e){return new ExObject(e)}static exclGroup(e){return new ExclGroup(e)}static execute(e){return new Execute(e)}static extras(e){return new Extras(e)}static field(e){return new Field(e)}static fill(e){return new Fill(e)}static filter(e){return new Filter(e)}static float(e){return new Float(e)}static font(e){return new template_Font(e)}static format(e){return new Format(e)}static handler(e){return new Handler(e)}static hyphenation(e){return new Hyphenation(e)}static image(e){return new Image(e)}static imageEdit(e){return new ImageEdit(e)}static integer(e){return new Integer(e)}static issuers(e){return new Issuers(e)}static items(e){return new Items(e)}static keep(e){return new Keep(e)}static keyUsage(e){return new KeyUsage(e)}static line(e){return new Line(e)}static linear(e){return new Linear(e)}static lockDocument(e){return new LockDocument(e)}static manifest(e){return new Manifest(e)}static margin(e){return new Margin(e)}static mdp(e){return new Mdp(e)}static medium(e){return new Medium(e)}static message(e){return new Message(e)}static numericEdit(e){return new NumericEdit(e)}static occur(e){return new Occur(e)}static oid(e){return new Oid(e)}static oids(e){return new Oids(e)}static overflow(e){return new Overflow(e)}static pageArea(e){return new PageArea(e)}static pageSet(e){return new PageSet(e)}static para(e){return new Para(e)}static passwordEdit(e){return new PasswordEdit(e)}static pattern(e){return new template_Pattern(e)}static picture(e){return new Picture(e)}static proto(e){return new Proto(e)}static radial(e){return new Radial(e)}static reason(e){return new Reason(e)}static reasons(e){return new Reasons(e)}static rectangle(e){return new Rectangle(e)}static ref(e){return new RefElement(e)}static script(e){return new Script(e)}static setProperty(e){return new SetProperty(e)}static signData(e){return new SignData(e)}static signature(e){return new Signature(e)}static signing(e){return new Signing(e)}static solid(e){return new Solid(e)}static speak(e){return new Speak(e)}static stipple(e){return new Stipple(e)}static subform(e){return new Subform(e)}static subformSet(e){return new SubformSet(e)}static subjectDN(e){return new SubjectDN(e)}static subjectDNs(e){return new SubjectDNs(e)}static submit(e){return new Submit(e)}static template(e){return new Template(e)}static text(e){return new Text(e)}static textEdit(e){return new TextEdit(e)}static time(e){return new Time(e)}static timeStamp(e){return new TimeStamp(e)}static toolTip(e){return new ToolTip(e)}static traversal(e){return new Traversal(e)}static traverse(e){return new Traverse(e)}static ui(e){return new Ui(e)}static validate(e){return new Validate(e)}static value(e){return new Value(e)}static variables(e){return new Variables(e)}}const Ln=_r.datasets.id;function createText(e){const t=new Text({});t[Os]=e;return t}class Binder{constructor(e){this.root=e;this.datasets=e.datasets;this.data=e.datasets?.data||new XmlObject(_r.datasets.id,"data");this.emptyMerge=0===this.data[rr]().length;this.root.form=this.form=e.template[Ts]()}_isConsumeData(){return!this.emptyMerge&&this._mergeMode}_isMatchTemplate(){return!this._isConsumeData()}bind(){this._bindElement(this.form,this.data);return this.form}getData(){return this.data}_bindValue(e,t,i){e[Ws]=t;if(e[hr]())if(t[fr]()){const i=t[ir]();e[qr](createText(i))}else if(e instanceof Field&&"multiSelect"===e.ui?.choiceList?.open){const i=t[rr]().map((e=>e[Os].trim())).join("\n");e[qr](createText(i))}else this._isConsumeData()&&warn("XFA - Nodes haven't the same type.");else!t[fr]()||this._isMatchTemplate()?this._bindElement(e,t):warn("XFA - Nodes haven't the same type.")}_findDataByNameToConsume(e,t,i,a){if(!e)return null;let s,r;for(let a=0;a<3;a++){s=i[sr](e,!1,!0);for(;;){r=s.next().value;if(!r)break;if(t===r[fr]())return r}if(i[Sr]===_r.datasets.id&&"data"===i[kr])break;i=i[Ir]()}if(!a)return null;s=this.data[sr](e,!0,!1);r=s.next().value;if(r)return r;s=this.data[zs](e,!0);r=s.next().value;return r?.[fr]()?r:null}_setProperties(e,t){if(e.hasOwnProperty("setProperty"))for(const{ref:i,target:a,connection:s}of e.setProperty.children){if(s)continue;if(!i)continue;const r=searchNode(this.root,t,i,!1,!1);if(!r){warn(`XFA - Invalid reference: ${i}.`);continue}const[n]=r;if(!n[pr](this.data)){warn("XFA - Invalid node: must be a data node.");continue}const g=searchNode(this.root,e,a,!1,!1);if(!g){warn(`XFA - Invalid target: ${a}.`);continue}const[o]=g;if(!o[pr](e)){warn("XFA - Invalid target: must be a property or subproperty.");continue}const c=o[Ir]();if(o instanceof SetProperty||c instanceof SetProperty){warn("XFA - Invalid target: cannot be a setProperty or one of its properties.");continue}if(o instanceof BindItems||c instanceof BindItems){warn("XFA - Invalid target: cannot be a bindItems or one of its properties.");continue}const C=n[Pr](),h=o[kr];if(o instanceof XFAAttribute){const e=Object.create(null);e[h]=C;const t=Reflect.construct(Object.getPrototypeOf(c).constructor,[e]);c[h]=t[h]}else if(o.hasOwnProperty(Os)){o[Ws]=n;o[Os]=C;o[Zs]()}else warn("XFA - Invalid node to use in setProperty")}}_bindItems(e,t){if(!e.hasOwnProperty("items")||!e.hasOwnProperty("bindItems")||e.bindItems.isEmpty())return;for(const t of e.items.children)e[Hr](t);e.items.clear();const i=new Items({}),a=new Items({});e[Hs](i);e.items.push(i);e[Hs](a);e.items.push(a);for(const{ref:s,labelRef:r,valueRef:n,connection:g}of e.bindItems.children){if(g)continue;if(!s)continue;const e=searchNode(this.root,t,s,!1,!1);if(e)for(const t of e){if(!t[pr](this.datasets)){warn(`XFA - Invalid ref (${s}): must be a datasets child.`);continue}const e=searchNode(this.root,t,r,!0,!1);if(!e){warn(`XFA - Invalid label: ${r}.`);continue}const[g]=e;if(!g[pr](this.datasets)){warn("XFA - Invalid label: must be a datasets child.");continue}const o=searchNode(this.root,t,n,!0,!1);if(!o){warn(`XFA - Invalid value: ${n}.`);continue}const[c]=o;if(!c[pr](this.datasets)){warn("XFA - Invalid value: must be a datasets child.");continue}const C=createText(g[Pr]()),h=createText(c[Pr]());i[Hs](C);i.text.push(C);a[Hs](h);a.text.push(h)}else warn(`XFA - Invalid reference: ${s}.`)}}_bindOccurrences(e,t,i){let a;if(t.length>1){a=e[Ts]();a[Hr](a.occur);a.occur=null}this._bindValue(e,t[0],i);this._setProperties(e,t[0]);this._bindItems(e,t[0]);if(1===t.length)return;const s=e[Ir](),r=e[kr],n=s[Qr](e);for(let e=1,g=t.length;et.name===e.name)).length:i[a].children.length;const r=i[Qr](e)+1,n=t.initial-s;if(n){const t=e[Ts]();t[Hr](t.occur);t.occur=null;i[a].push(t);i[Er](r,t);for(let e=1;e0)this._bindOccurrences(a,[e[0]],null);else if(this.emptyMerge){const e=t[Sr]===Ln?-1:t[Sr],i=a[Ws]=new XmlObject(e,a.name||"root");t[Hs](i);this._bindElement(a,i)}continue}if(!a[dr]())continue;let e=!1,s=null,r=null,n=null;if(a.bind){switch(a.bind.match){case"none":this._setAndBind(a,t);continue;case"global":e=!0;break;case"dataRef":if(!a.bind.ref){warn(`XFA - ref is empty in node ${a[kr]}.`);this._setAndBind(a,t);continue}r=a.bind.ref}a.bind.picture&&(s=a.bind.picture[Os])}const[g,o]=this._getOccurInfo(a);if(r){n=searchNode(this.root,t,r,!0,!1);if(null===n){n=createDataNode(this.data,t,r);if(!n)continue;this._isConsumeData()&&(n[qs]=!0);this._setAndBind(a,n);continue}this._isConsumeData()&&(n=n.filter((e=>!e[qs])));n.length>o?n=n.slice(0,o):0===n.length&&(n=null);n&&this._isConsumeData()&&n.forEach((e=>{e[qs]=!0}))}else{if(!a.name){this._setAndBind(a,t);continue}if(this._isConsumeData()){const i=[];for(;i.length0?i:null}else{n=t[sr](a.name,!1,this.emptyMerge).next().value;if(!n){if(0===g){i.push(a);continue}const e=t[Sr]===Ln?-1:t[Sr];n=a[Ws]=new XmlObject(e,a.name);this.emptyMerge&&(n[qs]=!0);t[Hs](n);this._setAndBind(a,n);continue}this.emptyMerge&&(n[qs]=!0);n=[n]}}n?this._bindOccurrences(a,n,s):g>0?this._setAndBind(a,t):i.push(a)}i.forEach((e=>e[Ir]()[Hr](e)))}}class DataHandler{constructor(e,t){this.data=t;this.dataset=e.datasets||null}serialize(e){const t=[[-1,this.data[rr]()]];for(;t.length>0;){const i=t.at(-1),[a,s]=i;if(a+1===s.length){t.pop();continue}const r=s[++i[0]],n=e.get(r[Vr]);if(n)r[qr](n);else{const t=r[_s]();for(const i of t.values()){const t=e.get(i[Vr]);if(t){i[qr](t);break}}}const g=r[rr]();g.length>0&&t.push([-1,g])}const i=[''];if(this.dataset)for(const e of this.dataset[rr]())"data"!==e[kr]&&e[Xr](i);this.data[Xr](i);i.push("");return i.join("")}}const Hn=_r.config.id;class Acrobat extends XFAObject{constructor(e){super(Hn,"acrobat",!0);this.acrobat7=null;this.autoSave=null;this.common=null;this.validate=null;this.validateApprovalSignatures=null;this.submitUrl=new XFAObjectArray}}class Acrobat7 extends XFAObject{constructor(e){super(Hn,"acrobat7",!0);this.dynamicRender=null}}class ADBE_JSConsole extends OptionObject{constructor(e){super(Hn,"ADBE_JSConsole",["delegate","Enable","Disable"])}}class ADBE_JSDebugger extends OptionObject{constructor(e){super(Hn,"ADBE_JSDebugger",["delegate","Enable","Disable"])}}class AddSilentPrint extends Option01{constructor(e){super(Hn,"addSilentPrint")}}class AddViewerPreferences extends Option01{constructor(e){super(Hn,"addViewerPreferences")}}class AdjustData extends Option10{constructor(e){super(Hn,"adjustData")}}class AdobeExtensionLevel extends IntegerObject{constructor(e){super(Hn,"adobeExtensionLevel",0,(e=>e>=1&&e<=8))}}class Agent extends XFAObject{constructor(e){super(Hn,"agent",!0);this.name=e.name?e.name.trim():"";this.common=new XFAObjectArray}}class AlwaysEmbed extends ContentObject{constructor(e){super(Hn,"alwaysEmbed")}}class Amd extends StringObject{constructor(e){super(Hn,"amd")}}class config_Area extends XFAObject{constructor(e){super(Hn,"area");this.level=getInteger({data:e.level,defaultValue:0,validate:e=>e>=1&&e<=3});this.name=getStringOption(e.name,["","barcode","coreinit","deviceDriver","font","general","layout","merge","script","signature","sourceSet","templateCache"])}}class Attributes extends OptionObject{constructor(e){super(Hn,"attributes",["preserve","delegate","ignore"])}}class AutoSave extends OptionObject{constructor(e){super(Hn,"autoSave",["disabled","enabled"])}}class Base extends StringObject{constructor(e){super(Hn,"base")}}class BatchOutput extends XFAObject{constructor(e){super(Hn,"batchOutput");this.format=getStringOption(e.format,["none","concat","zip","zipCompress"])}}class BehaviorOverride extends ContentObject{constructor(e){super(Hn,"behaviorOverride")}[Zs](){this[Os]=new Map(this[Os].trim().split(/\s+/).filter((e=>e.includes(":"))).map((e=>e.split(":",2))))}}class Cache extends XFAObject{constructor(e){super(Hn,"cache",!0);this.templateCache=null}}class Change extends Option01{constructor(e){super(Hn,"change")}}class Common extends XFAObject{constructor(e){super(Hn,"common",!0);this.data=null;this.locale=null;this.localeSet=null;this.messaging=null;this.suppressBanner=null;this.template=null;this.validationMessaging=null;this.versionControl=null;this.log=new XFAObjectArray}}class Compress extends XFAObject{constructor(e){super(Hn,"compress");this.scope=getStringOption(e.scope,["imageOnly","document"])}}class CompressLogicalStructure extends Option01{constructor(e){super(Hn,"compressLogicalStructure")}}class CompressObjectStream extends Option10{constructor(e){super(Hn,"compressObjectStream")}}class Compression extends XFAObject{constructor(e){super(Hn,"compression",!0);this.compressLogicalStructure=null;this.compressObjectStream=null;this.level=null;this.type=null}}class Config extends XFAObject{constructor(e){super(Hn,"config",!0);this.acrobat=null;this.present=null;this.trace=null;this.agent=new XFAObjectArray}}class Conformance extends OptionObject{constructor(e){super(Hn,"conformance",["A","B"])}}class ContentCopy extends Option01{constructor(e){super(Hn,"contentCopy")}}class Copies extends IntegerObject{constructor(e){super(Hn,"copies",1,(e=>e>=1))}}class Creator extends StringObject{constructor(e){super(Hn,"creator")}}class CurrentPage extends IntegerObject{constructor(e){super(Hn,"currentPage",0,(e=>e>=0))}}class Data extends XFAObject{constructor(e){super(Hn,"data",!0);this.adjustData=null;this.attributes=null;this.incrementalLoad=null;this.outputXSL=null;this.range=null;this.record=null;this.startNode=null;this.uri=null;this.window=null;this.xsl=null;this.excludeNS=new XFAObjectArray;this.transform=new XFAObjectArray}}class Debug extends XFAObject{constructor(e){super(Hn,"debug",!0);this.uri=null}}class DefaultTypeface extends ContentObject{constructor(e){super(Hn,"defaultTypeface");this.writingScript=getStringOption(e.writingScript,["*","Arabic","Cyrillic","EastEuropeanRoman","Greek","Hebrew","Japanese","Korean","Roman","SimplifiedChinese","Thai","TraditionalChinese","Vietnamese"])}}class Destination extends OptionObject{constructor(e){super(Hn,"destination",["pdf","pcl","ps","webClient","zpl"])}}class DocumentAssembly extends Option01{constructor(e){super(Hn,"documentAssembly")}}class Driver extends XFAObject{constructor(e){super(Hn,"driver",!0);this.name=e.name?e.name.trim():"";this.fontInfo=null;this.xdc=null}}class DuplexOption extends OptionObject{constructor(e){super(Hn,"duplexOption",["simplex","duplexFlipLongEdge","duplexFlipShortEdge"])}}class DynamicRender extends OptionObject{constructor(e){super(Hn,"dynamicRender",["forbidden","required"])}}class Embed extends Option01{constructor(e){super(Hn,"embed")}}class config_Encrypt extends Option01{constructor(e){super(Hn,"encrypt")}}class config_Encryption extends XFAObject{constructor(e){super(Hn,"encryption",!0);this.encrypt=null;this.encryptionLevel=null;this.permissions=null}}class EncryptionLevel extends OptionObject{constructor(e){super(Hn,"encryptionLevel",["40bit","128bit"])}}class Enforce extends StringObject{constructor(e){super(Hn,"enforce")}}class Equate extends XFAObject{constructor(e){super(Hn,"equate");this.force=getInteger({data:e.force,defaultValue:1,validate:e=>0===e});this.from=e.from||"";this.to=e.to||""}}class EquateRange extends XFAObject{constructor(e){super(Hn,"equateRange");this.from=e.from||"";this.to=e.to||"";this._unicodeRange=e.unicodeRange||""}get unicodeRange(){const e=[],t=/U\+([0-9a-fA-F]+)/,i=this._unicodeRange;for(let a of i.split(",").map((e=>e.trim())).filter((e=>!!e))){a=a.split("-",2).map((e=>{const i=e.match(t);return i?parseInt(i[1],16):0}));1===a.length&&a.push(a[0]);e.push(a)}return shadow(this,"unicodeRange",e)}}class Exclude extends ContentObject{constructor(e){super(Hn,"exclude")}[Zs](){this[Os]=this[Os].trim().split(/\s+/).filter((e=>e&&["calculate","close","enter","exit","initialize","ready","validate"].includes(e)))}}class ExcludeNS extends StringObject{constructor(e){super(Hn,"excludeNS")}}class FlipLabel extends OptionObject{constructor(e){super(Hn,"flipLabel",["usePrinterSetting","on","off"])}}class config_FontInfo extends XFAObject{constructor(e){super(Hn,"fontInfo",!0);this.embed=null;this.map=null;this.subsetBelow=null;this.alwaysEmbed=new XFAObjectArray;this.defaultTypeface=new XFAObjectArray;this.neverEmbed=new XFAObjectArray}}class FormFieldFilling extends Option01{constructor(e){super(Hn,"formFieldFilling")}}class GroupParent extends StringObject{constructor(e){super(Hn,"groupParent")}}class IfEmpty extends OptionObject{constructor(e){super(Hn,"ifEmpty",["dataValue","dataGroup","ignore","remove"])}}class IncludeXDPContent extends StringObject{constructor(e){super(Hn,"includeXDPContent")}}class IncrementalLoad extends OptionObject{constructor(e){super(Hn,"incrementalLoad",["none","forwardOnly"])}}class IncrementalMerge extends Option01{constructor(e){super(Hn,"incrementalMerge")}}class Interactive extends Option01{constructor(e){super(Hn,"interactive")}}class Jog extends OptionObject{constructor(e){super(Hn,"jog",["usePrinterSetting","none","pageSet"])}}class LabelPrinter extends XFAObject{constructor(e){super(Hn,"labelPrinter",!0);this.name=getStringOption(e.name,["zpl","dpl","ipl","tcpl"]);this.batchOutput=null;this.flipLabel=null;this.fontInfo=null;this.xdc=null}}class Layout extends OptionObject{constructor(e){super(Hn,"layout",["paginate","panel"])}}class Level extends IntegerObject{constructor(e){super(Hn,"level",0,(e=>e>0))}}class Linearized extends Option01{constructor(e){super(Hn,"linearized")}}class Locale extends StringObject{constructor(e){super(Hn,"locale")}}class LocaleSet extends StringObject{constructor(e){super(Hn,"localeSet")}}class Log extends XFAObject{constructor(e){super(Hn,"log",!0);this.mode=null;this.threshold=null;this.to=null;this.uri=null}}class MapElement extends XFAObject{constructor(e){super(Hn,"map",!0);this.equate=new XFAObjectArray;this.equateRange=new XFAObjectArray}}class MediumInfo extends XFAObject{constructor(e){super(Hn,"mediumInfo",!0);this.map=null}}class config_Message extends XFAObject{constructor(e){super(Hn,"message",!0);this.msgId=null;this.severity=null}}class Messaging extends XFAObject{constructor(e){super(Hn,"messaging",!0);this.message=new XFAObjectArray}}class Mode extends OptionObject{constructor(e){super(Hn,"mode",["append","overwrite"])}}class ModifyAnnots extends Option01{constructor(e){super(Hn,"modifyAnnots")}}class MsgId extends IntegerObject{constructor(e){super(Hn,"msgId",1,(e=>e>=1))}}class NameAttr extends StringObject{constructor(e){super(Hn,"nameAttr")}}class NeverEmbed extends ContentObject{constructor(e){super(Hn,"neverEmbed")}}class NumberOfCopies extends IntegerObject{constructor(e){super(Hn,"numberOfCopies",null,(e=>e>=2&&e<=5))}}class OpenAction extends XFAObject{constructor(e){super(Hn,"openAction",!0);this.destination=null}}class Output extends XFAObject{constructor(e){super(Hn,"output",!0);this.to=null;this.type=null;this.uri=null}}class OutputBin extends StringObject{constructor(e){super(Hn,"outputBin")}}class OutputXSL extends XFAObject{constructor(e){super(Hn,"outputXSL",!0);this.uri=null}}class Overprint extends OptionObject{constructor(e){super(Hn,"overprint",["none","both","draw","field"])}}class Packets extends StringObject{constructor(e){super(Hn,"packets")}[Zs](){"*"!==this[Os]&&(this[Os]=this[Os].trim().split(/\s+/).filter((e=>["config","datasets","template","xfdf","xslt"].includes(e))))}}class PageOffset extends XFAObject{constructor(e){super(Hn,"pageOffset");this.x=getInteger({data:e.x,defaultValue:"useXDCSetting",validate:e=>!0});this.y=getInteger({data:e.y,defaultValue:"useXDCSetting",validate:e=>!0})}}class PageRange extends StringObject{constructor(e){super(Hn,"pageRange")}[Zs](){const e=this[Os].trim().split(/\s+/).map((e=>parseInt(e,10))),t=[];for(let i=0,a=e.length;i!1))}}class Pcl extends XFAObject{constructor(e){super(Hn,"pcl",!0);this.name=e.name||"";this.batchOutput=null;this.fontInfo=null;this.jog=null;this.mediumInfo=null;this.outputBin=null;this.pageOffset=null;this.staple=null;this.xdc=null}}class Pdf extends XFAObject{constructor(e){super(Hn,"pdf",!0);this.name=e.name||"";this.adobeExtensionLevel=null;this.batchOutput=null;this.compression=null;this.creator=null;this.encryption=null;this.fontInfo=null;this.interactive=null;this.linearized=null;this.openAction=null;this.pdfa=null;this.producer=null;this.renderPolicy=null;this.scriptModel=null;this.silentPrint=null;this.submitFormat=null;this.tagged=null;this.version=null;this.viewerPreferences=null;this.xdc=null}}class Pdfa extends XFAObject{constructor(e){super(Hn,"pdfa",!0);this.amd=null;this.conformance=null;this.includeXDPContent=null;this.part=null}}class Permissions extends XFAObject{constructor(e){super(Hn,"permissions",!0);this.accessibleContent=null;this.change=null;this.contentCopy=null;this.documentAssembly=null;this.formFieldFilling=null;this.modifyAnnots=null;this.plaintextMetadata=null;this.print=null;this.printHighQuality=null}}class PickTrayByPDFSize extends Option01{constructor(e){super(Hn,"pickTrayByPDFSize")}}class config_Picture extends StringObject{constructor(e){super(Hn,"picture")}}class PlaintextMetadata extends Option01{constructor(e){super(Hn,"plaintextMetadata")}}class Presence extends OptionObject{constructor(e){super(Hn,"presence",["preserve","dissolve","dissolveStructure","ignore","remove"])}}class Present extends XFAObject{constructor(e){super(Hn,"present",!0);this.behaviorOverride=null;this.cache=null;this.common=null;this.copies=null;this.destination=null;this.incrementalMerge=null;this.layout=null;this.output=null;this.overprint=null;this.pagination=null;this.paginationOverride=null;this.script=null;this.validate=null;this.xdp=null;this.driver=new XFAObjectArray;this.labelPrinter=new XFAObjectArray;this.pcl=new XFAObjectArray;this.pdf=new XFAObjectArray;this.ps=new XFAObjectArray;this.submitUrl=new XFAObjectArray;this.webClient=new XFAObjectArray;this.zpl=new XFAObjectArray}}class Print extends Option01{constructor(e){super(Hn,"print")}}class PrintHighQuality extends Option01{constructor(e){super(Hn,"printHighQuality")}}class PrintScaling extends OptionObject{constructor(e){super(Hn,"printScaling",["appdefault","noScaling"])}}class PrinterName extends StringObject{constructor(e){super(Hn,"printerName")}}class Producer extends StringObject{constructor(e){super(Hn,"producer")}}class Ps extends XFAObject{constructor(e){super(Hn,"ps",!0);this.name=e.name||"";this.batchOutput=null;this.fontInfo=null;this.jog=null;this.mediumInfo=null;this.outputBin=null;this.staple=null;this.xdc=null}}class Range extends ContentObject{constructor(e){super(Hn,"range")}[Zs](){this[Os]=this[Os].trim().split(/\s*,\s*/,2).map((e=>e.split("-").map((e=>parseInt(e.trim(),10))))).filter((e=>e.every((e=>!isNaN(e))))).map((e=>{1===e.length&&e.push(e[0]);return e}))}}class Record extends ContentObject{constructor(e){super(Hn,"record")}[Zs](){this[Os]=this[Os].trim();const e=parseInt(this[Os],10);!isNaN(e)&&e>=0&&(this[Os]=e)}}class Relevant extends ContentObject{constructor(e){super(Hn,"relevant")}[Zs](){this[Os]=this[Os].trim().split(/\s+/)}}class Rename extends ContentObject{constructor(e){super(Hn,"rename")}[Zs](){this[Os]=this[Os].trim();(this[Os].toLowerCase().startsWith("xml")||new RegExp("[\\p{L}_][\\p{L}\\d._\\p{M}-]*","u").test(this[Os]))&&warn("XFA - Rename: invalid XFA name")}}class RenderPolicy extends OptionObject{constructor(e){super(Hn,"renderPolicy",["server","client"])}}class RunScripts extends OptionObject{constructor(e){super(Hn,"runScripts",["both","client","none","server"])}}class config_Script extends XFAObject{constructor(e){super(Hn,"script",!0);this.currentPage=null;this.exclude=null;this.runScripts=null}}class ScriptModel extends OptionObject{constructor(e){super(Hn,"scriptModel",["XFA","none"])}}class Severity extends OptionObject{constructor(e){super(Hn,"severity",["ignore","error","information","trace","warning"])}}class SilentPrint extends XFAObject{constructor(e){super(Hn,"silentPrint",!0);this.addSilentPrint=null;this.printerName=null}}class Staple extends XFAObject{constructor(e){super(Hn,"staple");this.mode=getStringOption(e.mode,["usePrinterSetting","on","off"])}}class StartNode extends StringObject{constructor(e){super(Hn,"startNode")}}class StartPage extends IntegerObject{constructor(e){super(Hn,"startPage",0,(e=>!0))}}class SubmitFormat extends OptionObject{constructor(e){super(Hn,"submitFormat",["html","delegate","fdf","xml","pdf"])}}class SubmitUrl extends StringObject{constructor(e){super(Hn,"submitUrl")}}class SubsetBelow extends IntegerObject{constructor(e){super(Hn,"subsetBelow",100,(e=>e>=0&&e<=100))}}class SuppressBanner extends Option01{constructor(e){super(Hn,"suppressBanner")}}class Tagged extends Option01{constructor(e){super(Hn,"tagged")}}class config_Template extends XFAObject{constructor(e){super(Hn,"template",!0);this.base=null;this.relevant=null;this.startPage=null;this.uri=null;this.xsl=null}}class Threshold extends OptionObject{constructor(e){super(Hn,"threshold",["trace","error","information","warning"])}}class To extends OptionObject{constructor(e){super(Hn,"to",["null","memory","stderr","stdout","system","uri"])}}class TemplateCache extends XFAObject{constructor(e){super(Hn,"templateCache");this.maxEntries=getInteger({data:e.maxEntries,defaultValue:5,validate:e=>e>=0})}}class Trace extends XFAObject{constructor(e){super(Hn,"trace",!0);this.area=new XFAObjectArray}}class Transform extends XFAObject{constructor(e){super(Hn,"transform",!0);this.groupParent=null;this.ifEmpty=null;this.nameAttr=null;this.picture=null;this.presence=null;this.rename=null;this.whitespace=null}}class Type extends OptionObject{constructor(e){super(Hn,"type",["none","ascii85","asciiHex","ccittfax","flate","lzw","runLength","native","xdp","mergedXDP"])}}class Uri extends StringObject{constructor(e){super(Hn,"uri")}}class config_Validate extends OptionObject{constructor(e){super(Hn,"validate",["preSubmit","prePrint","preExecute","preSave"])}}class ValidateApprovalSignatures extends ContentObject{constructor(e){super(Hn,"validateApprovalSignatures")}[Zs](){this[Os]=this[Os].trim().split(/\s+/).filter((e=>["docReady","postSign"].includes(e)))}}class ValidationMessaging extends OptionObject{constructor(e){super(Hn,"validationMessaging",["allMessagesIndividually","allMessagesTogether","firstMessageOnly","noMessages"])}}class Version extends OptionObject{constructor(e){super(Hn,"version",["1.7","1.6","1.5","1.4","1.3","1.2"])}}class VersionControl extends XFAObject{constructor(e){super(Hn,"VersionControl");this.outputBelow=getStringOption(e.outputBelow,["warn","error","update"]);this.sourceAbove=getStringOption(e.sourceAbove,["warn","error"]);this.sourceBelow=getStringOption(e.sourceBelow,["update","maintain"])}}class ViewerPreferences extends XFAObject{constructor(e){super(Hn,"viewerPreferences",!0);this.ADBE_JSConsole=null;this.ADBE_JSDebugger=null;this.addViewerPreferences=null;this.duplexOption=null;this.enforce=null;this.numberOfCopies=null;this.pageRange=null;this.pickTrayByPDFSize=null;this.printScaling=null}}class WebClient extends XFAObject{constructor(e){super(Hn,"webClient",!0);this.name=e.name?e.name.trim():"";this.fontInfo=null;this.xdc=null}}class Whitespace extends OptionObject{constructor(e){super(Hn,"whitespace",["preserve","ltrim","normalize","rtrim","trim"])}}class Window extends ContentObject{constructor(e){super(Hn,"window")}[Zs](){const e=this[Os].trim().split(/\s*,\s*/,2).map((e=>parseInt(e,10)));if(e.some((e=>isNaN(e))))this[Os]=[0,0];else{1===e.length&&e.push(e[0]);this[Os]=e}}}class Xdc extends XFAObject{constructor(e){super(Hn,"xdc",!0);this.uri=new XFAObjectArray;this.xsl=new XFAObjectArray}}class Xdp extends XFAObject{constructor(e){super(Hn,"xdp",!0);this.packets=null}}class Xsl extends XFAObject{constructor(e){super(Hn,"xsl",!0);this.debug=null;this.uri=null}}class Zpl extends XFAObject{constructor(e){super(Hn,"zpl",!0);this.name=e.name?e.name.trim():"";this.batchOutput=null;this.flipLabel=null;this.fontInfo=null;this.xdc=null}}class ConfigNamespace{static[zr](e,t){if(ConfigNamespace.hasOwnProperty(e))return ConfigNamespace[e](t)}static acrobat(e){return new Acrobat(e)}static acrobat7(e){return new Acrobat7(e)}static ADBE_JSConsole(e){return new ADBE_JSConsole(e)}static ADBE_JSDebugger(e){return new ADBE_JSDebugger(e)}static addSilentPrint(e){return new AddSilentPrint(e)}static addViewerPreferences(e){return new AddViewerPreferences(e)}static adjustData(e){return new AdjustData(e)}static adobeExtensionLevel(e){return new AdobeExtensionLevel(e)}static agent(e){return new Agent(e)}static alwaysEmbed(e){return new AlwaysEmbed(e)}static amd(e){return new Amd(e)}static area(e){return new config_Area(e)}static attributes(e){return new Attributes(e)}static autoSave(e){return new AutoSave(e)}static base(e){return new Base(e)}static batchOutput(e){return new BatchOutput(e)}static behaviorOverride(e){return new BehaviorOverride(e)}static cache(e){return new Cache(e)}static change(e){return new Change(e)}static common(e){return new Common(e)}static compress(e){return new Compress(e)}static compressLogicalStructure(e){return new CompressLogicalStructure(e)}static compressObjectStream(e){return new CompressObjectStream(e)}static compression(e){return new Compression(e)}static config(e){return new Config(e)}static conformance(e){return new Conformance(e)}static contentCopy(e){return new ContentCopy(e)}static copies(e){return new Copies(e)}static creator(e){return new Creator(e)}static currentPage(e){return new CurrentPage(e)}static data(e){return new Data(e)}static debug(e){return new Debug(e)}static defaultTypeface(e){return new DefaultTypeface(e)}static destination(e){return new Destination(e)}static documentAssembly(e){return new DocumentAssembly(e)}static driver(e){return new Driver(e)}static duplexOption(e){return new DuplexOption(e)}static dynamicRender(e){return new DynamicRender(e)}static embed(e){return new Embed(e)}static encrypt(e){return new config_Encrypt(e)}static encryption(e){return new config_Encryption(e)}static encryptionLevel(e){return new EncryptionLevel(e)}static enforce(e){return new Enforce(e)}static equate(e){return new Equate(e)}static equateRange(e){return new EquateRange(e)}static exclude(e){return new Exclude(e)}static excludeNS(e){return new ExcludeNS(e)}static flipLabel(e){return new FlipLabel(e)}static fontInfo(e){return new config_FontInfo(e)}static formFieldFilling(e){return new FormFieldFilling(e)}static groupParent(e){return new GroupParent(e)}static ifEmpty(e){return new IfEmpty(e)}static includeXDPContent(e){return new IncludeXDPContent(e)}static incrementalLoad(e){return new IncrementalLoad(e)}static incrementalMerge(e){return new IncrementalMerge(e)}static interactive(e){return new Interactive(e)}static jog(e){return new Jog(e)}static labelPrinter(e){return new LabelPrinter(e)}static layout(e){return new Layout(e)}static level(e){return new Level(e)}static linearized(e){return new Linearized(e)}static locale(e){return new Locale(e)}static localeSet(e){return new LocaleSet(e)}static log(e){return new Log(e)}static map(e){return new MapElement(e)}static mediumInfo(e){return new MediumInfo(e)}static message(e){return new config_Message(e)}static messaging(e){return new Messaging(e)}static mode(e){return new Mode(e)}static modifyAnnots(e){return new ModifyAnnots(e)}static msgId(e){return new MsgId(e)}static nameAttr(e){return new NameAttr(e)}static neverEmbed(e){return new NeverEmbed(e)}static numberOfCopies(e){return new NumberOfCopies(e)}static openAction(e){return new OpenAction(e)}static output(e){return new Output(e)}static outputBin(e){return new OutputBin(e)}static outputXSL(e){return new OutputXSL(e)}static overprint(e){return new Overprint(e)}static packets(e){return new Packets(e)}static pageOffset(e){return new PageOffset(e)}static pageRange(e){return new PageRange(e)}static pagination(e){return new Pagination(e)}static paginationOverride(e){return new PaginationOverride(e)}static part(e){return new Part(e)}static pcl(e){return new Pcl(e)}static pdf(e){return new Pdf(e)}static pdfa(e){return new Pdfa(e)}static permissions(e){return new Permissions(e)}static pickTrayByPDFSize(e){return new PickTrayByPDFSize(e)}static picture(e){return new config_Picture(e)}static plaintextMetadata(e){return new PlaintextMetadata(e)}static presence(e){return new Presence(e)}static present(e){return new Present(e)}static print(e){return new Print(e)}static printHighQuality(e){return new PrintHighQuality(e)}static printScaling(e){return new PrintScaling(e)}static printerName(e){return new PrinterName(e)}static producer(e){return new Producer(e)}static ps(e){return new Ps(e)}static range(e){return new Range(e)}static record(e){return new Record(e)}static relevant(e){return new Relevant(e)}static rename(e){return new Rename(e)}static renderPolicy(e){return new RenderPolicy(e)}static runScripts(e){return new RunScripts(e)}static script(e){return new config_Script(e)}static scriptModel(e){return new ScriptModel(e)}static severity(e){return new Severity(e)}static silentPrint(e){return new SilentPrint(e)}static staple(e){return new Staple(e)}static startNode(e){return new StartNode(e)}static startPage(e){return new StartPage(e)}static submitFormat(e){return new SubmitFormat(e)}static submitUrl(e){return new SubmitUrl(e)}static subsetBelow(e){return new SubsetBelow(e)}static suppressBanner(e){return new SuppressBanner(e)}static tagged(e){return new Tagged(e)}static template(e){return new config_Template(e)}static templateCache(e){return new TemplateCache(e)}static threshold(e){return new Threshold(e)}static to(e){return new To(e)}static trace(e){return new Trace(e)}static transform(e){return new Transform(e)}static type(e){return new Type(e)}static uri(e){return new Uri(e)}static validate(e){return new config_Validate(e)}static validateApprovalSignatures(e){return new ValidateApprovalSignatures(e)}static validationMessaging(e){return new ValidationMessaging(e)}static version(e){return new Version(e)}static versionControl(e){return new VersionControl(e)}static viewerPreferences(e){return new ViewerPreferences(e)}static webClient(e){return new WebClient(e)}static whitespace(e){return new Whitespace(e)}static window(e){return new Window(e)}static xdc(e){return new Xdc(e)}static xdp(e){return new Xdp(e)}static xsl(e){return new Xsl(e)}static zpl(e){return new Zpl(e)}}const Jn=_r.connectionSet.id;class ConnectionSet extends XFAObject{constructor(e){super(Jn,"connectionSet",!0);this.wsdlConnection=new XFAObjectArray;this.xmlConnection=new XFAObjectArray;this.xsdConnection=new XFAObjectArray}}class EffectiveInputPolicy extends XFAObject{constructor(e){super(Jn,"effectiveInputPolicy");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class EffectiveOutputPolicy extends XFAObject{constructor(e){super(Jn,"effectiveOutputPolicy");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Operation extends StringObject{constructor(e){super(Jn,"operation");this.id=e.id||"";this.input=e.input||"";this.name=e.name||"";this.output=e.output||"";this.use=e.use||"";this.usehref=e.usehref||""}}class RootElement extends StringObject{constructor(e){super(Jn,"rootElement");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class SoapAction extends StringObject{constructor(e){super(Jn,"soapAction");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class SoapAddress extends StringObject{constructor(e){super(Jn,"soapAddress");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class connection_set_Uri extends StringObject{constructor(e){super(Jn,"uri");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class WsdlAddress extends StringObject{constructor(e){super(Jn,"wsdlAddress");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class WsdlConnection extends XFAObject{constructor(e){super(Jn,"wsdlConnection",!0);this.dataDescription=e.dataDescription||"";this.name=e.name||"";this.effectiveInputPolicy=null;this.effectiveOutputPolicy=null;this.operation=null;this.soapAction=null;this.soapAddress=null;this.wsdlAddress=null}}class XmlConnection extends XFAObject{constructor(e){super(Jn,"xmlConnection",!0);this.dataDescription=e.dataDescription||"";this.name=e.name||"";this.uri=null}}class XsdConnection extends XFAObject{constructor(e){super(Jn,"xsdConnection",!0);this.dataDescription=e.dataDescription||"";this.name=e.name||"";this.rootElement=null;this.uri=null}}class ConnectionSetNamespace{static[zr](e,t){if(ConnectionSetNamespace.hasOwnProperty(e))return ConnectionSetNamespace[e](t)}static connectionSet(e){return new ConnectionSet(e)}static effectiveInputPolicy(e){return new EffectiveInputPolicy(e)}static effectiveOutputPolicy(e){return new EffectiveOutputPolicy(e)}static operation(e){return new Operation(e)}static rootElement(e){return new RootElement(e)}static soapAction(e){return new SoapAction(e)}static soapAddress(e){return new SoapAddress(e)}static uri(e){return new connection_set_Uri(e)}static wsdlAddress(e){return new WsdlAddress(e)}static wsdlConnection(e){return new WsdlConnection(e)}static xmlConnection(e){return new XmlConnection(e)}static xsdConnection(e){return new XsdConnection(e)}}const Yn=_r.datasets.id;class datasets_Data extends XmlObject{constructor(e){super(Yn,"data",e)}[mr](){return!0}}class Datasets extends XFAObject{constructor(e){super(Yn,"datasets",!0);this.data=null;this.Signature=null}[Nr](e){const t=e[kr];("data"===t&&e[Sr]===Yn||"Signature"===t&&e[Sr]===_r.signature.id)&&(this[t]=e);this[Hs](e)}}class DatasetsNamespace{static[zr](e,t){if(DatasetsNamespace.hasOwnProperty(e))return DatasetsNamespace[e](t)}static datasets(e){return new Datasets(e)}static data(e){return new datasets_Data(e)}}const vn=_r.localeSet.id;class CalendarSymbols extends XFAObject{constructor(e){super(vn,"calendarSymbols",!0);this.name="gregorian";this.dayNames=new XFAObjectArray(2);this.eraNames=null;this.meridiemNames=null;this.monthNames=new XFAObjectArray(2)}}class CurrencySymbol extends StringObject{constructor(e){super(vn,"currencySymbol");this.name=getStringOption(e.name,["symbol","isoname","decimal"])}}class CurrencySymbols extends XFAObject{constructor(e){super(vn,"currencySymbols",!0);this.currencySymbol=new XFAObjectArray(3)}}class DatePattern extends StringObject{constructor(e){super(vn,"datePattern");this.name=getStringOption(e.name,["full","long","med","short"])}}class DatePatterns extends XFAObject{constructor(e){super(vn,"datePatterns",!0);this.datePattern=new XFAObjectArray(4)}}class DateTimeSymbols extends ContentObject{constructor(e){super(vn,"dateTimeSymbols")}}class Day extends StringObject{constructor(e){super(vn,"day")}}class DayNames extends XFAObject{constructor(e){super(vn,"dayNames",!0);this.abbr=getInteger({data:e.abbr,defaultValue:0,validate:e=>1===e});this.day=new XFAObjectArray(7)}}class Era extends StringObject{constructor(e){super(vn,"era")}}class EraNames extends XFAObject{constructor(e){super(vn,"eraNames",!0);this.era=new XFAObjectArray(2)}}class locale_set_Locale extends XFAObject{constructor(e){super(vn,"locale",!0);this.desc=e.desc||"";this.name="isoname";this.calendarSymbols=null;this.currencySymbols=null;this.datePatterns=null;this.dateTimeSymbols=null;this.numberPatterns=null;this.numberSymbols=null;this.timePatterns=null;this.typeFaces=null}}class locale_set_LocaleSet extends XFAObject{constructor(e){super(vn,"localeSet",!0);this.locale=new XFAObjectArray}}class Meridiem extends StringObject{constructor(e){super(vn,"meridiem")}}class MeridiemNames extends XFAObject{constructor(e){super(vn,"meridiemNames",!0);this.meridiem=new XFAObjectArray(2)}}class Month extends StringObject{constructor(e){super(vn,"month")}}class MonthNames extends XFAObject{constructor(e){super(vn,"monthNames",!0);this.abbr=getInteger({data:e.abbr,defaultValue:0,validate:e=>1===e});this.month=new XFAObjectArray(12)}}class NumberPattern extends StringObject{constructor(e){super(vn,"numberPattern");this.name=getStringOption(e.name,["full","long","med","short"])}}class NumberPatterns extends XFAObject{constructor(e){super(vn,"numberPatterns",!0);this.numberPattern=new XFAObjectArray(4)}}class NumberSymbol extends StringObject{constructor(e){super(vn,"numberSymbol");this.name=getStringOption(e.name,["decimal","grouping","percent","minus","zero"])}}class NumberSymbols extends XFAObject{constructor(e){super(vn,"numberSymbols",!0);this.numberSymbol=new XFAObjectArray(5)}}class TimePattern extends StringObject{constructor(e){super(vn,"timePattern");this.name=getStringOption(e.name,["full","long","med","short"])}}class TimePatterns extends XFAObject{constructor(e){super(vn,"timePatterns",!0);this.timePattern=new XFAObjectArray(4)}}class TypeFace extends XFAObject{constructor(e){super(vn,"typeFace",!0);this.name=""|e.name}}class TypeFaces extends XFAObject{constructor(e){super(vn,"typeFaces",!0);this.typeFace=new XFAObjectArray}}class LocaleSetNamespace{static[zr](e,t){if(LocaleSetNamespace.hasOwnProperty(e))return LocaleSetNamespace[e](t)}static calendarSymbols(e){return new CalendarSymbols(e)}static currencySymbol(e){return new CurrencySymbol(e)}static currencySymbols(e){return new CurrencySymbols(e)}static datePattern(e){return new DatePattern(e)}static datePatterns(e){return new DatePatterns(e)}static dateTimeSymbols(e){return new DateTimeSymbols(e)}static day(e){return new Day(e)}static dayNames(e){return new DayNames(e)}static era(e){return new Era(e)}static eraNames(e){return new EraNames(e)}static locale(e){return new locale_set_Locale(e)}static localeSet(e){return new locale_set_LocaleSet(e)}static meridiem(e){return new Meridiem(e)}static meridiemNames(e){return new MeridiemNames(e)}static month(e){return new Month(e)}static monthNames(e){return new MonthNames(e)}static numberPattern(e){return new NumberPattern(e)}static numberPatterns(e){return new NumberPatterns(e)}static numberSymbol(e){return new NumberSymbol(e)}static numberSymbols(e){return new NumberSymbols(e)}static timePattern(e){return new TimePattern(e)}static timePatterns(e){return new TimePatterns(e)}static typeFace(e){return new TypeFace(e)}static typeFaces(e){return new TypeFaces(e)}}const Kn=_r.signature.id;class signature_Signature extends XFAObject{constructor(e){super(Kn,"signature",!0)}}class SignatureNamespace{static[zr](e,t){if(SignatureNamespace.hasOwnProperty(e))return SignatureNamespace[e](t)}static signature(e){return new signature_Signature(e)}}const Tn=_r.stylesheet.id;class Stylesheet extends XFAObject{constructor(e){super(Tn,"stylesheet",!0)}}class StylesheetNamespace{static[zr](e,t){if(StylesheetNamespace.hasOwnProperty(e))return StylesheetNamespace[e](t)}static stylesheet(e){return new Stylesheet(e)}}const qn=_r.xdp.id;class xdp_Xdp extends XFAObject{constructor(e){super(qn,"xdp",!0);this.uuid=e.uuid||"";this.timeStamp=e.timeStamp||"";this.config=null;this.connectionSet=null;this.datasets=null;this.localeSet=null;this.stylesheet=new XFAObjectArray;this.template=null}[Gr](e){const t=_r[e[kr]];return t&&e[Sr]===t.id}}class XdpNamespace{static[zr](e,t){if(XdpNamespace.hasOwnProperty(e))return XdpNamespace[e](t)}static xdp(e){return new xdp_Xdp(e)}}const On=_r.xhtml.id,Pn=Symbol(),Wn=new Set(["color","font","font-family","font-size","font-stretch","font-style","font-weight","margin","margin-bottom","margin-left","margin-right","margin-top","letter-spacing","line-height","orphans","page-break-after","page-break-before","page-break-inside","tab-interval","tab-stop","text-align","text-decoration","text-indent","vertical-align","widows","kerning-mode","xfa-font-horizontal-scale","xfa-font-vertical-scale","xfa-spacerun","xfa-tab-stops"]),jn=new Map([["page-break-after","breakAfter"],["page-break-before","breakBefore"],["page-break-inside","breakInside"],["kerning-mode",e=>"none"===e?"none":"normal"],["xfa-font-horizontal-scale",e=>`scaleX(${Math.max(0,Math.min(parseInt(e)/100)).toFixed(2)})`],["xfa-font-vertical-scale",e=>`scaleY(${Math.max(0,Math.min(parseInt(e)/100)).toFixed(2)})`],["xfa-spacerun",""],["xfa-tab-stops",""],["font-size",(e,t)=>measureToString(.99*(e=t.fontSize=Math.abs(getMeasurement(e))))],["letter-spacing",e=>measureToString(getMeasurement(e))],["line-height",e=>measureToString(getMeasurement(e))],["margin",e=>measureToString(getMeasurement(e))],["margin-bottom",e=>measureToString(getMeasurement(e))],["margin-left",e=>measureToString(getMeasurement(e))],["margin-right",e=>measureToString(getMeasurement(e))],["margin-top",e=>measureToString(getMeasurement(e))],["text-indent",e=>measureToString(getMeasurement(e))],["font-family",e=>e],["vertical-align",e=>measureToString(getMeasurement(e))]]),Xn=/\s+/g,Zn=/[\r\n]+/g,Vn=/\r\n?/g;function mapStyle(e,t,i){const a=Object.create(null);if(!e)return a;const s=Object.create(null);for(const[t,i]of e.split(";").map((e=>e.split(":",2)))){const e=jn.get(t);if(""===e)continue;let r=i;e&&(r="string"==typeof e?e:e(i,s));t.endsWith("scale")?a.transform=a.transform?`${a[t]} ${r}`:r:a[t.replaceAll(/-([a-zA-Z])/g,((e,t)=>t.toUpperCase()))]=r}a.fontFamily&&setFontFamily({typeface:a.fontFamily,weight:a.fontWeight||"normal",posture:a.fontStyle||"normal",size:s.fontSize||0},t,t[Cr].fontFinder,a);if(i&&a.verticalAlign&&"0px"!==a.verticalAlign&&a.fontSize){const e=.583,t=.333,i=getMeasurement(a.fontSize);a.fontSize=measureToString(i*e);a.verticalAlign=measureToString(Math.sign(getMeasurement(a.verticalAlign))*i*t)}i&&a.fontSize&&(a.fontSize=`calc(${a.fontSize} * var(--scale-factor))`);fixTextIndent(a);return a}const zn=new Set(["body","html"]);class XhtmlObject extends XmlObject{constructor(e,t){super(On,t);this[Pn]=!1;this.style=e.style||""}[Ys](e){super[Ys](e);this.style=function checkStyle(e){return e.style?e.style.trim().split(/\s*;\s*/).filter((e=>!!e)).map((e=>e.split(/\s*:\s*/,2))).filter((([t,i])=>{"font-family"===t&&e[Cr].usedTypefaces.add(i);return Wn.has(t)})).map((e=>e.join(":"))).join(";"):""}(this)}[xs](){return!zn.has(this[kr])}[Mr](e,t=!1){if(t)this[Pn]=!0;else{e=e.replaceAll(Zn,"");this.style.includes("xfa-spacerun:yes")||(e=e.replaceAll(Xn," "))}e&&(this[Os]+=e)}[Ur](e,t=!0){const i=Object.create(null),a={top:NaN,bottom:NaN,left:NaN,right:NaN};let s=null;for(const[e,t]of this.style.split(";").map((e=>e.split(":",2))))switch(e){case"font-family":i.typeface=stripQuotes(t);break;case"font-size":i.size=getMeasurement(t);break;case"font-weight":i.weight=t;break;case"font-style":i.posture=t;break;case"letter-spacing":i.letterSpacing=getMeasurement(t);break;case"margin":const e=t.split(/ \t/).map((e=>getMeasurement(e)));switch(e.length){case 1:a.top=a.bottom=a.left=a.right=e[0];break;case 2:a.top=a.bottom=e[0];a.left=a.right=e[1];break;case 3:a.top=e[0];a.bottom=e[2];a.left=a.right=e[1];break;case 4:a.top=e[0];a.left=e[1];a.bottom=e[2];a.right=e[3]}break;case"margin-top":a.top=getMeasurement(t);break;case"margin-bottom":a.bottom=getMeasurement(t);break;case"margin-left":a.left=getMeasurement(t);break;case"margin-right":a.right=getMeasurement(t);break;case"line-height":s=getMeasurement(t)}e.pushData(i,a,s);if(this[Os])e.addString(this[Os]);else for(const t of this[rr]())"#text"!==t[kr]?t[Ur](e):e.addString(t[Os]);t&&e.popFont()}[jr](e){const t=[];this[Xs]={children:t};this[Js]({});if(0===t.length&&!this[Os])return HTMLResult.EMPTY;let i;i=this[Pn]?this[Os]?this[Os].replaceAll(Vn,"\n"):void 0:this[Os]||void 0;return HTMLResult.success({name:this[kr],attributes:{href:this.href,style:mapStyle(this.style,this,this[Pn])},children:t,value:i})}}class A extends XhtmlObject{constructor(e){super(e,"a");this.href=fixURL(e.href)||""}}class B extends XhtmlObject{constructor(e){super(e,"b")}[Ur](e){e.pushFont({weight:"bold"});super[Ur](e);e.popFont()}}class Body extends XhtmlObject{constructor(e){super(e,"body")}[jr](e){const t=super[jr](e),{html:i}=t;if(!i)return HTMLResult.EMPTY;i.name="div";i.attributes.class=["xfaRich"];return t}}class Br extends XhtmlObject{constructor(e){super(e,"br")}[Pr](){return"\n"}[Ur](e){e.addString("\n")}[jr](e){return HTMLResult.success({name:"br"})}}class Html extends XhtmlObject{constructor(e){super(e,"html")}[jr](e){const t=[];this[Xs]={children:t};this[Js]({});if(0===t.length)return HTMLResult.success({name:"div",attributes:{class:["xfaRich"],style:{}},value:this[Os]||""});if(1===t.length){const e=t[0];if(e.attributes?.class.includes("xfaRich"))return HTMLResult.success(e)}return HTMLResult.success({name:"div",attributes:{class:["xfaRich"],style:{}},children:t})}}class I extends XhtmlObject{constructor(e){super(e,"i")}[Ur](e){e.pushFont({posture:"italic"});super[Ur](e);e.popFont()}}class Li extends XhtmlObject{constructor(e){super(e,"li")}}class Ol extends XhtmlObject{constructor(e){super(e,"ol")}}class P extends XhtmlObject{constructor(e){super(e,"p")}[Ur](e){super[Ur](e,!1);e.addString("\n");e.addPara();e.popFont()}[Pr](){return this[Ir]()[rr]().at(-1)===this?super[Pr]():super[Pr]()+"\n"}}class Span extends XhtmlObject{constructor(e){super(e,"span")}}class Sub extends XhtmlObject{constructor(e){super(e,"sub")}}class Sup extends XhtmlObject{constructor(e){super(e,"sup")}}class Ul extends XhtmlObject{constructor(e){super(e,"ul")}}class XhtmlNamespace{static[zr](e,t){if(XhtmlNamespace.hasOwnProperty(e))return XhtmlNamespace[e](t)}static a(e){return new A(e)}static b(e){return new B(e)}static body(e){return new Body(e)}static br(e){return new Br(e)}static html(e){return new Html(e)}static i(e){return new I(e)}static li(e){return new Li(e)}static ol(e){return new Ol(e)}static p(e){return new P(e)}static span(e){return new Span(e)}static sub(e){return new Sub(e)}static sup(e){return new Sup(e)}static ul(e){return new Ul(e)}}const _n={config:ConfigNamespace,connection:ConnectionSetNamespace,datasets:DatasetsNamespace,localeSet:LocaleSetNamespace,signature:SignatureNamespace,stylesheet:StylesheetNamespace,template:TemplateNamespace,xdp:XdpNamespace,xhtml:XhtmlNamespace};class UnknownNamespace{constructor(e){this.namespaceId=e}[zr](e,t){return new XmlObject(this.namespaceId,e,t)}}class Root extends XFAObject{constructor(e){super(-1,"root",Object.create(null));this.element=null;this[lr]=e}[Nr](e){this.element=e;return!0}[Zs](){super[Zs]();if(this.element.template instanceof Template){this[lr].set(Jr,this.element);this.element.template[Yr](this[lr]);this.element.template[lr]=this[lr]}}}class Empty extends XFAObject{constructor(){super(-1,"",Object.create(null))}[Nr](e){return!1}}class Builder{constructor(e=null){this._namespaceStack=[];this._nsAgnosticLevel=0;this._namespacePrefixes=new Map;this._namespaces=new Map;this._nextNsId=Math.max(...Object.values(_r).map((({id:e})=>e)));this._currentNamespace=e||new UnknownNamespace(++this._nextNsId)}buildRoot(e){return new Root(e)}build({nsPrefix:e,name:t,attributes:i,namespace:a,prefixes:s}){const r=null!==a;if(r){this._namespaceStack.push(this._currentNamespace);this._currentNamespace=this._searchNamespace(a)}s&&this._addNamespacePrefix(s);if(i.hasOwnProperty(Rr)){const e=_n.datasets,t=i[Rr];let a=null;for(const[i,s]of Object.entries(t)){if(this._getNamespaceToUse(i)===e){a={xfa:s};break}}a?i[Rr]=a:delete i[Rr]}const n=this._getNamespaceToUse(e),g=n?.[zr](t,i)||new Empty;g[mr]()&&this._nsAgnosticLevel++;(r||s||g[mr]())&&(g[Ks]={hasNamespace:r,prefixes:s,nsAgnostic:g[mr]()});return g}isNsAgnostic(){return this._nsAgnosticLevel>0}_searchNamespace(e){let t=this._namespaces.get(e);if(t)return t;for(const[i,{check:a}]of Object.entries(_r))if(a(e)){t=_n[i];if(t){this._namespaces.set(e,t);return t}break}t=new UnknownNamespace(++this._nextNsId);this._namespaces.set(e,t);return t}_addNamespacePrefix(e){for(const{prefix:t,value:i}of e){const e=this._searchNamespace(i);let a=this._namespacePrefixes.get(t);if(!a){a=[];this._namespacePrefixes.set(t,a)}a.push(e)}}_getNamespaceToUse(e){if(!e)return this._currentNamespace;const t=this._namespacePrefixes.get(e);if(t?.length>0)return t.at(-1);warn(`Unknown namespace prefix: ${e}.`);return null}clean(e){const{hasNamespace:t,prefixes:i,nsAgnostic:a}=e;t&&(this._currentNamespace=this._namespaceStack.pop());i&&i.forEach((({prefix:e})=>{this._namespacePrefixes.get(e).pop()}));a&&this._nsAgnosticLevel--}}class XFAParser extends XMLParserBase{constructor(e=null,t=!1){super();this._builder=new Builder(e);this._stack=[];this._globalData={usedTypefaces:new Set};this._ids=new Map;this._current=this._builder.buildRoot(this._ids);this._errorCode=ys;this._whiteRegex=/^\s+$/;this._nbsps=/\xa0+/g;this._richText=t}parse(e){this.parseXml(e);if(this._errorCode===ys){this._current[Zs]();return this._current.element}}onText(e){e=e.replace(this._nbsps,(e=>e.slice(1)+" "));this._richText||this._current[xs]()?this._current[Mr](e,this._richText):this._whiteRegex.test(e)||this._current[Mr](e.trim())}onCdata(e){this._current[Mr](e)}_mkAttributes(e,t){let i=null,a=null;const s=Object.create({});for(const{name:r,value:n}of e)if("xmlns"===r)i?warn(`XFA - multiple namespace definition in <${t}>`):i=n;else if(r.startsWith("xmlns:")){const e=r.substring(6);a||(a=[]);a.push({prefix:e,value:n})}else{const e=r.indexOf(":");if(-1===e)s[r]=n;else{let t=s[Rr];t||(t=s[Rr]=Object.create(null));const[i,a]=[r.slice(0,e),r.slice(e+1)];(t[i]||=Object.create(null))[a]=n}}return[i,a,s]}_getNameAndPrefix(e,t){const i=e.indexOf(":");return-1===i?[e,null]:[e.substring(i+1),t?"":e.substring(0,i)]}onBeginElement(e,t,i){const[a,s,r]=this._mkAttributes(t,e),[n,g]=this._getNameAndPrefix(e,this._builder.isNsAgnostic()),o=this._builder.build({nsPrefix:g,name:n,attributes:r,namespace:a,prefixes:s});o[Cr]=this._globalData;if(i){o[Zs]();this._current[Nr](o)&&o[Kr](this._ids);o[Ys](this._builder)}else{this._stack.push(this._current);this._current=o}}onEndElement(e){const t=this._current;if(t[ur]()&&"string"==typeof t[Os]){const e=new XFAParser;e._globalData=this._globalData;const i=e.parse(t[Os]);t[Os]=null;t[Nr](i)}t[Zs]();this._current=this._stack.pop();this._current[Nr](t)&&t[Kr](this._ids);t[Ys](this._builder)}onError(e){this._errorCode=e}}class XFAFactory{constructor(e){try{this.root=(new XFAParser).parse(XFAFactory._createDocument(e));const t=new Binder(this.root);this.form=t.bind();this.dataHandler=new DataHandler(this.root,t.getData());this.form[Cr].template=this.form}catch(e){warn(`XFA - an error occurred during parsing and binding: ${e}`)}}isValid(){return this.root&&this.form}_createPagesHelper(){const e=this.form[Wr]();return new Promise(((t,i)=>{const nextIteration=()=>{try{const i=e.next();i.done?t(i.value):setTimeout(nextIteration,0)}catch(e){i(e)}};setTimeout(nextIteration,0)}))}async _createPages(){try{this.pages=await this._createPagesHelper();this.dims=this.pages.children.map((e=>{const{width:t,height:i}=e.attributes.style;return[0,0,parseInt(t),parseInt(i)]}))}catch(e){warn(`XFA - an error occurred during layout: ${e}`)}}getBoundingBox(e){return this.dims[e]}async getNumPages(){this.pages||await this._createPages();return this.dims.length}setImages(e){this.form[Cr].images=e}setFonts(e){this.form[Cr].fontFinder=new FontFinder(e);const t=[];for(let e of this.form[Cr].usedTypefaces){e=stripQuotes(e);this.form[Cr].fontFinder.find(e)||t.push(e)}return t.length>0?t:null}appendFonts(e,t){this.form[Cr].fontFinder.add(e,t)}async getPages(){this.pages||await this._createPages();const e=this.pages;this.pages=null;return e}serializeData(e){return this.dataHandler.serialize(e)}static _createDocument(e){return e["/xdp:xdp"]?Object.values(e).join(""):e["xdp:xdp"]}static getRichTextAsHtml(e){if(!e||"string"!=typeof e)return null;try{let t=new XFAParser(XhtmlNamespace,!0).parse(e);if(!["body","xhtml"].includes(t[kr])){const e=XhtmlNamespace.body({});e[Hs](t);t=e}const i=t[jr]();if(!i.success)return null;const{html:a}=i,{attributes:s}=a;if(s){s.class&&(s.class=s.class.filter((e=>!e.startsWith("xfa"))));s.dir="auto"}return{html:a,str:t[Pr]()}}catch(e){warn(`XFA - an error occurred during parsing of rich text: ${e}`)}return null}}class AnnotationFactory{static createGlobals(e){return Promise.all([e.ensureCatalog("acroForm"),e.ensureDoc("xfaDatasets"),e.ensureCatalog("structTreeRoot"),e.ensureCatalog("baseUrl"),e.ensureCatalog("attachments")]).then((([t,i,a,s,r])=>({pdfManager:e,acroForm:t instanceof Dict?t:Dict.empty,xfaDatasets:i,structTreeRoot:a,baseUrl:s,attachments:r})),(e=>{warn(`createGlobals: "${e}".`);return null}))}static async create(e,t,i,a,s,r,n){const g=s?await this._getPageIndex(e,t,i.pdfManager):null;return i.pdfManager.ensure(this,"_create",[e,t,i,a,s,r,g,n])}static _create(e,t,i,a,s=!1,r=null,n=null,g=null){const o=e.fetchIfRef(t);if(!(o instanceof Dict))return;const{acroForm:c,pdfManager:C}=i,h=t instanceof Ref?t.toString():`annot_${a.createObjId()}`;let l=o.get("Subtype");l=l instanceof Name?l.name:null;const Q={xref:e,ref:t,dict:o,subtype:l,id:h,annotationGlobals:i,collectFields:s,orphanFields:r,needAppearances:!s&&!0===c.get("NeedAppearances"),pageIndex:n,evaluatorOptions:C.evaluatorOptions,pageRef:g};switch(l){case"Link":return new LinkAnnotation(Q);case"Text":return new TextAnnotation(Q);case"Widget":let e=getInheritableProperty({dict:o,key:"FT"});e=e instanceof Name?e.name:null;switch(e){case"Tx":return new TextWidgetAnnotation(Q);case"Btn":return new ButtonWidgetAnnotation(Q);case"Ch":return new ChoiceWidgetAnnotation(Q);case"Sig":return new SignatureWidgetAnnotation(Q)}warn(`Unimplemented widget field type "${e}", falling back to base field type.`);return new WidgetAnnotation(Q);case"Popup":return new PopupAnnotation(Q);case"FreeText":return new FreeTextAnnotation(Q);case"Line":return new LineAnnotation(Q);case"Square":return new SquareAnnotation(Q);case"Circle":return new CircleAnnotation(Q);case"PolyLine":return new PolylineAnnotation(Q);case"Polygon":return new PolygonAnnotation(Q);case"Caret":return new CaretAnnotation(Q);case"Ink":return new InkAnnotation(Q);case"Highlight":return new HighlightAnnotation(Q);case"Underline":return new UnderlineAnnotation(Q);case"Squiggly":return new SquigglyAnnotation(Q);case"StrikeOut":return new StrikeOutAnnotation(Q);case"Stamp":return new StampAnnotation(Q);case"FileAttachment":return new FileAttachmentAnnotation(Q);default:s||warn(l?`Unimplemented annotation type "${l}", falling back to base annotation.`:"Annotation is missing the required /Subtype.");return new Annotation(Q)}}static async _getPageIndex(e,t,i){try{const a=await e.fetchIfRefAsync(t);if(!(a instanceof Dict))return-1;const s=a.getRaw("P");if(s instanceof Ref)try{return await i.ensureCatalog("getPageIndex",[s])}catch(e){info(`_getPageIndex -- not a valid page reference: "${e}".`)}if(a.has("Kids"))return-1;const r=await i.ensureDoc("numPages");for(let e=0;ee/255))}function getQuadPoints(e,t){const i=e.getArray("QuadPoints");if(!isNumberArray(i,null)||0===i.length||i.length%8>0)return null;const a=new Float32Array(i.length);for(let e=0,s=i.length;et[2]||Et[3]))return null;a.set([l,u,Q,u,l,E,Q,E],e)}return a}function getTransformMatrix(e,t,i){const[a,s,r,n]=Util.getAxialAlignedBoundingBox(t,i);if(a===r||s===n)return[1,0,0,1,e[0],e[1]];const g=(e[2]-e[0])/(r-a),o=(e[3]-e[1])/(n-s);return[g,0,0,o,e[0]-a*g,e[1]-s*o]}class Annotation{constructor(e){const{dict:t,xref:i,annotationGlobals:a,ref:s,orphanFields:r}=e,n=r?.get(s);n&&t.set("Parent",n);this.setTitle(t.get("T"));this.setContents(t.get("Contents"));this.setModificationDate(t.get("M"));this.setFlags(t.get("F"));this.setRectangle(t.getArray("Rect"));this.setColor(t.getArray("C"));this.setBorderStyle(t);this.setAppearance(t);this.setOptionalContent(t);const g=t.get("MK");this.setBorderAndBackgroundColors(g);this.setRotation(g,t);this.ref=e.ref instanceof Ref?e.ref:null;this._streams=[];this.appearance&&this._streams.push(this.appearance);const o=!!(this.flags&eA),c=!!(this.flags&tA);this.data={annotationFlags:this.flags,borderStyle:this.borderStyle,color:this.color,backgroundColor:this.backgroundColor,borderColor:this.borderColor,rotation:this.rotation,contentsObj:this._contents,hasAppearance:!!this.appearance,id:e.id,modificationDate:this.modificationDate,rect:this.rectangle,subtype:e.subtype,hasOwnCanvas:!1,noRotate:!!(this.flags&$),noHTML:o&&c,isEditable:!1,structParent:-1};if(a.structTreeRoot){let i=t.get("StructParent");this.data.structParent=i=Number.isInteger(i)&&i>=0?i:-1;a.structTreeRoot.addAnnotationIdToPage(e.pageRef,i)}if(e.collectFields){const a=t.get("Kids");if(Array.isArray(a)){const e=[];for(const t of a)t instanceof Ref&&e.push(t.toString());0!==e.length&&(this.data.kidIds=e)}this.data.actions=collectActions(i,t,dA);this.data.fieldName=this._constructFieldName(t);this.data.pageIndex=e.pageIndex}const C=t.get("IT");C instanceof Name&&(this.data.it=C.name);this._isOffscreenCanvasSupported=e.evaluatorOptions.isOffscreenCanvasSupported;this._fallbackFontDict=null;this._needAppearances=!1}_hasFlag(e,t){return!!(e&t)}_buildFlags(e,t){let{flags:i}=this;if(void 0===e){if(void 0===t)return;return t?i&~_:i&~z|_}if(e){i|=_;return t?i&~AA|z:i&~z|AA}i&=~(z|AA);return t?i&~_:i|_}_isViewable(e){return!this._hasFlag(e,V)&&!this._hasFlag(e,AA)}_isPrintable(e){return this._hasFlag(e,_)&&!this._hasFlag(e,z)&&!this._hasFlag(e,V)}mustBeViewed(e,t){const i=e?.get(this.data.id)?.noView;return void 0!==i?!i:this.viewable&&!this._hasFlag(this.flags,z)}mustBePrinted(e){const t=e?.get(this.data.id)?.noPrint;return void 0!==t?!t:this.printable}mustBeViewedWhenEditing(e,t=null){return e?!this.data.isEditable:!t?.has(this.data.id)}get viewable(){return null!==this.data.quadPoints&&(0===this.flags||this._isViewable(this.flags))}get printable(){return null!==this.data.quadPoints&&(0!==this.flags&&this._isPrintable(this.flags))}_parseStringHelper(e){const t="string"==typeof e?stringToPDFString(e):"";return{str:t,dir:t&&"rtl"===bidi(t).dir?"rtl":"ltr"}}setDefaultAppearance(e){const{dict:t,annotationGlobals:i}=e,a=getInheritableProperty({dict:t,key:"DA"})||i.acroForm.get("DA");this._defaultAppearance="string"==typeof a?a:"";this.data.defaultAppearanceData=parseDefaultAppearance(this._defaultAppearance)}setTitle(e){this._title=this._parseStringHelper(e)}setContents(e){this._contents=this._parseStringHelper(e)}setModificationDate(e){this.modificationDate="string"==typeof e?e:null}setFlags(e){this.flags=Number.isInteger(e)&&e>0?e:0;this.flags&V&&"Annotation"!==this.constructor.name&&(this.flags^=V)}hasFlag(e){return this._hasFlag(this.flags,e)}setRectangle(e){this.rectangle=lookupNormalRect(e,[0,0,0,0])}setColor(e){this.color=getRgbColor(e)}setLineEndings(e){this.lineEndings=["None","None"];if(Array.isArray(e)&&2===e.length)for(let t=0;t<2;t++){const i=e[t];if(i instanceof Name)switch(i.name){case"None":continue;case"Square":case"Circle":case"Diamond":case"OpenArrow":case"ClosedArrow":case"Butt":case"ROpenArrow":case"RClosedArrow":case"Slash":this.lineEndings[t]=i.name;continue}warn(`Ignoring invalid lineEnding: ${i}`)}}setRotation(e,t){this.rotation=0;let i=e instanceof Dict?e.get("R")||0:t.get("Rotate")||0;if(Number.isInteger(i)&&0!==i){i%=360;i<0&&(i+=360);i%90==0&&(this.rotation=i)}}setBorderAndBackgroundColors(e){if(e instanceof Dict){this.borderColor=getRgbColor(e.getArray("BC"),null);this.backgroundColor=getRgbColor(e.getArray("BG"),null)}else this.borderColor=this.backgroundColor=null}setBorderStyle(e){this.borderStyle=new AnnotationBorderStyle;if(e instanceof Dict)if(e.has("BS")){const t=e.get("BS");if(t instanceof Dict){const e=t.get("Type");if(!e||isName(e,"Border")){this.borderStyle.setWidth(t.get("W"),this.rectangle);this.borderStyle.setStyle(t.get("S"));this.borderStyle.setDashArray(t.getArray("D"))}}}else if(e.has("Border")){const t=e.getArray("Border");if(Array.isArray(t)&&t.length>=3){this.borderStyle.setHorizontalCornerRadius(t[0]);this.borderStyle.setVerticalCornerRadius(t[1]);this.borderStyle.setWidth(t[2],this.rectangle);4===t.length&&this.borderStyle.setDashArray(t[3],!0)}}else this.borderStyle.setWidth(0)}setAppearance(e){this.appearance=null;const t=e.get("AP");if(!(t instanceof Dict))return;const i=t.get("N");if(i instanceof BaseStream){this.appearance=i;return}if(!(i instanceof Dict))return;const a=e.get("AS");if(!(a instanceof Name&&i.has(a.name)))return;const s=i.get(a.name);s instanceof BaseStream&&(this.appearance=s)}setOptionalContent(e){this.oc=null;const t=e.get("OC");t instanceof Name?warn("setOptionalContent: Support for /Name-entry is not implemented."):t instanceof Dict&&(this.oc=t)}loadResources(e,t){return t.dict.getAsync("Resources").then((t=>{if(!t)return;return new ObjectLoader(t,e,t.xref).load().then((function(){return t}))}))}async getOperatorList(e,t,a,s){const{hasOwnCanvas:r,id:n,rect:g}=this.data;let c=this.appearance;const C=!!(r&&a&o);if(C&&(g[0]===g[2]||g[1]===g[3])){this.data.hasOwnCanvas=!1;return{opList:new OperatorList,separateForm:!1,separateCanvas:!1}}if(!c){if(!C)return{opList:new OperatorList,separateForm:!1,separateCanvas:!1};c=new StringStream("");c.dict=new Dict}const h=c.dict,l=await this.loadResources(["ExtGState","ColorSpace","Pattern","Shading","XObject","Font"],c),Q=lookupRect(h.getArray("BBox"),[0,0,1,1]),E=lookupMatrix(h.getArray("Matrix"),i),u=getTransformMatrix(g,Q,E),d=new OperatorList;let f;this.oc&&(f=await e.parseMarkedContentProps(this.oc,null));void 0!==f&&d.addOp(Ye,["OC",f]);d.addOp(je,[n,g,u,E,C]);await e.getOperatorList({stream:c,task:t,resources:l,operatorList:d,fallbackFontDict:this._fallbackFontDict});d.addOp(Xe,[]);void 0!==f&&d.addOp(ve,[]);this.reset();return{opList:d,separateForm:!1,separateCanvas:C}}async save(e,t,i,a){return null}get hasTextContent(){return!1}async extractTextContent(e,t,i){if(!this.appearance)return;const a=await this.loadResources(["ExtGState","Font","Properties","XObject"],this.appearance),s=[],r=[];let n=null;const g={desiredSize:Math.Infinity,ready:!0,enqueue(e,t){for(const t of e.items)if(void 0!==t.str){n||=t.transform.slice(-2);r.push(t.str);if(t.hasEOL){s.push(r.join("").trimEnd());r.length=0}}}};await e.getTextContent({stream:this.appearance,task:t,resources:a,includeMarkedContent:!0,keepWhiteSpace:!0,sink:g,viewBox:i});this.reset();r.length&&s.push(r.join("").trimEnd());if(s.length>1||s[0]){const e=this.appearance.dict,t=lookupRect(e.getArray("BBox"),null),i=lookupMatrix(e.getArray("Matrix"),null);this.data.textPosition=this._transformPoint(n,t,i);this.data.textContent=s}}_transformPoint(e,t,i){const{rect:a}=this.data;t||=[0,0,1,1];i||=[1,0,0,1,0,0];const s=getTransformMatrix(a,t,i);s[4]-=a[0];s[5]-=a[1];e=Util.applyTransform(e,s);return Util.applyTransform(e,i)}getFieldObject(){return this.data.kidIds?{id:this.data.id,actions:this.data.actions,name:this.data.fieldName,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,type:"",kidIds:this.data.kidIds,page:this.data.pageIndex,rotation:this.rotation}:null}reset(){for(const e of this._streams)e.reset()}_constructFieldName(e){if(!e.has("T")&&!e.has("Parent")){warn("Unknown field name, falling back to empty field name.");return""}if(!e.has("Parent"))return stringToPDFString(e.get("T"));const t=[];e.has("T")&&t.unshift(stringToPDFString(e.get("T")));let i=e;const a=new RefSet;e.objId&&a.put(e.objId);for(;i.has("Parent");){i=i.get("Parent");if(!(i instanceof Dict)||i.objId&&a.has(i.objId))break;i.objId&&a.put(i.objId);i.has("T")&&t.unshift(stringToPDFString(i.get("T")))}return t.join(".")}}class AnnotationBorderStyle{constructor(){this.width=1;this.rawWidth=1;this.style=lA;this.dashArray=[3];this.horizontalCornerRadius=0;this.verticalCornerRadius=0}setWidth(e,t=[0,0,0,0]){if(e instanceof Name)this.width=0;else if("number"==typeof e){if(e>0){this.rawWidth=e;const i=(t[2]-t[0])/2,a=(t[3]-t[1])/2;if(i>0&&a>0&&(e>i||e>a)){warn(`AnnotationBorderStyle.setWidth - ignoring width: ${e}`);e=1}}this.width=e}}setStyle(e){if(e instanceof Name)switch(e.name){case"S":this.style=lA;break;case"D":this.style=BA;break;case"B":this.style=QA;break;case"I":this.style=EA;break;case"U":this.style=uA}}setDashArray(e,t=!1){if(Array.isArray(e)){let i=!0,a=!0;for(const t of e){if(!(+t>=0)){i=!1;break}t>0&&(a=!1)}if(0===e.length||i&&!a){this.dashArray=e;t&&this.setStyle(Name.get("D"))}else this.width=0}else e&&(this.width=0)}setHorizontalCornerRadius(e){Number.isInteger(e)&&(this.horizontalCornerRadius=e)}setVerticalCornerRadius(e){Number.isInteger(e)&&(this.verticalCornerRadius=e)}}class MarkupAnnotation extends Annotation{constructor(e){super(e);const{dict:t}=e;if(t.has("IRT")){const e=t.getRaw("IRT");this.data.inReplyTo=e instanceof Ref?e.toString():null;const i=t.get("RT");this.data.replyType=i instanceof Name?i.name:Z}let i=null;if(this.data.replyType===X){const e=t.get("IRT");this.setTitle(e.get("T"));this.data.titleObj=this._title;this.setContents(e.get("Contents"));this.data.contentsObj=this._contents;if(e.has("CreationDate")){this.setCreationDate(e.get("CreationDate"));this.data.creationDate=this.creationDate}else this.data.creationDate=null;if(e.has("M")){this.setModificationDate(e.get("M"));this.data.modificationDate=this.modificationDate}else this.data.modificationDate=null;i=e.getRaw("Popup");if(e.has("C")){this.setColor(e.getArray("C"));this.data.color=this.color}else this.data.color=null}else{this.data.titleObj=this._title;this.setCreationDate(t.get("CreationDate"));this.data.creationDate=this.creationDate;i=t.getRaw("Popup");t.has("C")||(this.data.color=null)}this.data.popupRef=i instanceof Ref?i.toString():null;t.has("RC")&&(this.data.richText=XFAFactory.getRichTextAsHtml(t.get("RC")))}setCreationDate(e){this.creationDate="string"==typeof e?e:null}_setDefaultAppearance({xref:e,extra:t,strokeColor:i,fillColor:a,blendMode:s,strokeAlpha:r,fillAlpha:n,pointsCallback:g}){let o=Number.MAX_VALUE,c=Number.MAX_VALUE,C=Number.MIN_VALUE,h=Number.MIN_VALUE;const l=["q"];t&&l.push(t);i&&l.push(`${i[0]} ${i[1]} ${i[2]} RG`);a&&l.push(`${a[0]} ${a[1]} ${a[2]} rg`);const Q=this.data.quadPoints||Float32Array.from([this.rectangle[0],this.rectangle[3],this.rectangle[2],this.rectangle[3],this.rectangle[0],this.rectangle[1],this.rectangle[2],this.rectangle[1]]);for(let e=0,t=Q.length;e"string"==typeof e)).map((e=>stringToPDFString(e))):e instanceof Name?stringToPDFString(e.name):"string"==typeof e?stringToPDFString(e):null}hasFieldFlag(e){return!!(this.data.fieldFlags&e)}_isViewable(e){return!0}mustBeViewed(e,t){return t?this.viewable:super.mustBeViewed(e,t)&&!this._hasFlag(this.flags,AA)}getRotationMatrix(e){let t=e?.get(this.data.id)?.rotation;void 0===t&&(t=this.rotation);if(0===t)return i;return getRotationMatrix(t,this.data.rect[2]-this.data.rect[0],this.data.rect[3]-this.data.rect[1])}getBorderAndBackgroundAppearances(e){let t=e?.get(this.data.id)?.rotation;void 0===t&&(t=this.rotation);if(!this.backgroundColor&&!this.borderColor)return"";const i=this.data.rect[2]-this.data.rect[0],a=this.data.rect[3]-this.data.rect[1],s=0===t||180===t?`0 0 ${i} ${a} re`:`0 0 ${a} ${i} re`;let r="";this.backgroundColor&&(r=`${getPdfColor(this.backgroundColor,!0)} ${s} f `);if(this.borderColor){r+=`${this.borderStyle.width||1} w ${getPdfColor(this.borderColor,!1)} ${s} S `}return r}async getOperatorList(e,t,i,a){if(i&h&&!(this instanceof SignatureWidgetAnnotation)&&!this.data.noHTML&&!this.data.hasOwnCanvas)return{opList:new OperatorList,separateForm:!0,separateCanvas:!1};if(!this._hasText)return super.getOperatorList(e,t,i,a);const s=await this._getAppearance(e,t,i,a);if(this.appearance&&null===s)return super.getOperatorList(e,t,i,a);const r=new OperatorList;if(!this._defaultAppearance||null===s)return{opList:r,separateForm:!1,separateCanvas:!1};const n=!!(this.data.hasOwnCanvas&&i&o),g=[0,0,this.data.rect[2]-this.data.rect[0],this.data.rect[3]-this.data.rect[1]],c=getTransformMatrix(this.data.rect,g,[1,0,0,1,0,0]);let C;this.oc&&(C=await e.parseMarkedContentProps(this.oc,null));void 0!==C&&r.addOp(Ye,["OC",C]);r.addOp(je,[this.data.id,this.data.rect,c,this.getRotationMatrix(a),n]);const l=new StringStream(s);await e.getOperatorList({stream:l,task:t,resources:this._fieldResources.mergedResources,operatorList:r});r.addOp(Xe,[]);void 0!==C&&r.addOp(ve,[]);return{opList:r,separateForm:!1,separateCanvas:n}}_getMKDict(e){const t=new Dict(null);e&&t.set("R",e);this.borderColor&&t.set("BC",getPdfColorArray(this.borderColor));this.backgroundColor&&t.set("BG",getPdfColorArray(this.backgroundColor));return t.size>0?t:null}amendSavedDict(e,t){}setValue(e,t,i,a){const{dict:s,ref:r}=function getParentToUpdate(e,t,i){const a=new RefSet,s=e,r={dict:null,ref:null};for(;e instanceof Dict&&!a.has(t);){a.put(t);if(e.has("T"))break;if(!((t=e.getRaw("Parent"))instanceof Ref))return r;e=i.fetch(t)}if(e instanceof Dict&&e!==s){r.dict=e;r.ref=t}return r}(e,this.ref,i);if(s){if(!a.has(r)){const e=s.clone();e.set("V",t);a.put(r,{data:e});return e}}else e.set("V",t);return null}async save(e,t,a,s){const r=a?.get(this.data.id),n=this._buildFlags(r?.noView,r?.noPrint);let g=r?.value,o=r?.rotation;if(g===this.data.fieldValue||void 0===g){if(!this._hasValueFromXFA&&void 0===o&&void 0===n)return;g||=this.data.fieldValue}if(void 0===o&&!this._hasValueFromXFA&&Array.isArray(g)&&Array.isArray(this.data.fieldValue)&&isArrayEqual(g,this.data.fieldValue)&&void 0===n)return;void 0===o&&(o=this.rotation);let c=null;if(!this._needAppearances){c=await this._getAppearance(e,t,C,a);if(null===c&&void 0===n)return}let h=!1;if(c?.needAppearances){h=!0;c=null}const{xref:l}=e,Q=l.fetchIfRef(this.ref);if(!(Q instanceof Dict))return;const E=new Dict(l);for(const e of Q.getKeys())"AP"!==e&&E.set(e,Q.getRaw(e));if(void 0!==n){E.set("F",n);if(null===c&&!h){const e=Q.getRaw("AP");e&&E.set("AP",e)}}const u={path:this.data.fieldName,value:g},d=this.setValue(E,Array.isArray(g)?g.map(stringToAsciiOrUTF16BE):stringToAsciiOrUTF16BE(g),l,s);this.amendSavedDict(a,d||E);const f=this._getMKDict(o);f&&E.set("MK",f);s.put(this.ref,{data:E,xfa:u,needAppearances:h});if(null!==c){const e=l.getNewTemporaryRef(),t=new Dict(l);E.set("AP",t);t.set("N",e);const r=this._getSaveFieldResources(l),n=new StringStream(c),g=n.dict=new Dict(l);g.set("Subtype",Name.get("Form"));g.set("Resources",r);g.set("BBox",[0,0,this.data.rect[2]-this.data.rect[0],this.data.rect[3]-this.data.rect[1]]);const o=this.getRotationMatrix(a);o!==i&&g.set("Matrix",o);s.put(e,{data:n,xfa:null,needAppearances:!1})}E.set("M",`D:${getModificationDate()}`)}async _getAppearance(e,t,i,a){if(this.hasFieldFlag(rA))return null;const s=a?.get(this.data.id);let r,g;if(s){r=s.formattedValue||s.value;g=s.rotation}if(void 0===g&&void 0===r&&!this._needAppearances&&(!this._hasValueFromXFA||this.appearance))return null;const o=this.getBorderAndBackgroundAppearances(a);if(void 0===r){r=this.data.fieldValue;if(!r)return`/Tx BMC q ${o}Q EMC`}Array.isArray(r)&&1===r.length&&(r=r[0]);assert("string"==typeof r,"Expected `value` to be a string.");r=r.trimEnd();if(this.data.combo){const e=this.data.options.find((({exportValue:e})=>r===e));r=e?.displayValue||r}if(""===r)return`/Tx BMC q ${o}Q EMC`;void 0===g&&(g=this.rotation);let c,h=-1;if(this.data.multiLine){c=r.split(/\r\n?|\n/).map((e=>e.normalize("NFC")));h=c.length}else c=[r.replace(/\r\n?|\n/,"").normalize("NFC")];let l=this.data.rect[3]-this.data.rect[1],Q=this.data.rect[2]-this.data.rect[0];90!==g&&270!==g||([Q,l]=[l,Q]);this._defaultAppearance||(this.data.defaultAppearanceData=parseDefaultAppearance(this._defaultAppearance="/Helvetica 0 Tf 0 g"));let E,u,d,f=await WidgetAnnotation._getFontData(e,t,this.data.defaultAppearanceData,this._fieldResources.mergedResources);const p=[];let m=!1;for(const e of c){const t=f.encodeString(e);t.length>1&&(m=!0);p.push(t.join(""))}if(m&&i&C)return{needAppearances:!0};if(m&&this._isOffscreenCanvasSupported){const i=this.data.comb?"monospace":"sans-serif",a=new FakeUnicodeFont(e.xref,i),s=a.createFontResources(c.join("")),n=s.getRaw("Font");if(this._fieldResources.mergedResources.has("Font")){const e=this._fieldResources.mergedResources.get("Font");for(const t of n.getKeys())e.set(t,n.getRaw(t))}else this._fieldResources.mergedResources.set("Font",n);const g=a.fontName.name;f=await WidgetAnnotation._getFontData(e,t,{fontName:g,fontSize:0},s);for(let e=0,t=p.length;e2)return`/Tx BMC q ${o}BT `+E+` 1 0 0 1 ${numberToString(2)} ${numberToString(b)} Tm (${escapeString(p[0])}) Tj ET Q EMC`;return`/Tx BMC q ${o}BT `+E+` 1 0 0 1 0 0 Tm ${this._renderText(p[0],f,u,Q,D,{shift:0},2,b)} ET Q EMC`}static async _getFontData(e,t,i,a){const s=new OperatorList,r={font:null,clone(){return this}},{fontName:n,fontSize:g}=i;await e.handleSetFont(a,[n&&Name.get(n),g],null,s,t,r,null);return r.font}_getTextWidth(e,t){return t.charsToGlyphs(e).reduce(((e,t)=>e+t.width),0)/1e3}_computeFontSize(e,t,i,a,r){let{fontSize:n}=this.data.defaultAppearanceData,g=(n||12)*s,o=Math.round(e/g);if(!n){const roundWithTwoDigits=e=>Math.floor(100*e)/100;if(-1===r){const r=this._getTextWidth(i,a);n=roundWithTwoDigits(Math.min(e/s,t/r));o=1}else{const c=i.split(/\r\n?|\n/),C=[];for(const e of c){const t=a.encodeString(e).join(""),i=a.charsToGlyphs(t),s=a.getCharPositions(t);C.push({line:t,glyphs:i,positions:s})}const isTooBig=i=>{let s=0;for(const r of C){s+=this._splitLine(null,a,i,t,r).length*i;if(s>e)return!0}return!1};o=Math.max(o,r);for(;;){g=e/o;n=roundWithTwoDigits(g/s);if(!isTooBig(n))break;o++}}const{fontName:c,fontColor:C}=this.data.defaultAppearanceData;this._defaultAppearance=function createDefaultAppearance({fontSize:e,fontName:t,fontColor:i}){return`/${escapePDFName(t)} ${e} Tf ${getPdfColor(i,!0)}`}({fontSize:n,fontName:c,fontColor:C})}return[this._defaultAppearance,n,e/o]}_renderText(e,t,i,a,s,r,n,g){let o;if(1===s){o=(a-this._getTextWidth(e,t)*i)/2}else if(2===s){o=a-this._getTextWidth(e,t)*i-n}else o=n;const c=numberToString(o-r.shift);r.shift=o;return`${c} ${g=numberToString(g)} Td (${escapeString(e)}) Tj`}_getSaveFieldResources(e){const{localResources:t,appearanceResources:i,acroFormResources:a}=this._fieldResources,s=this.data.defaultAppearanceData?.fontName;if(!s)return t||Dict.empty;for(const e of[t,i])if(e instanceof Dict){const t=e.get("Font");if(t instanceof Dict&&t.has(s))return e}if(a instanceof Dict){const i=a.get("Font");if(i instanceof Dict&&i.has(s)){const a=new Dict(e);a.set(s,i.getRaw(s));const r=new Dict(e);r.set("Font",a);return Dict.merge({xref:e,dictArray:[r,t],mergeSubDicts:!0})}}return t||Dict.empty}getFieldObject(){return null}}class TextWidgetAnnotation extends WidgetAnnotation{constructor(e){super(e);const{dict:t}=e;if(t.has("PMD")){this.flags|=z;this.data.hidden=!0;warn("Barcodes are not supported")}this.data.hasOwnCanvas=this.data.readOnly&&!this.data.noHTML;this._hasText=!0;"string"!=typeof this.data.fieldValue&&(this.data.fieldValue="");let i=getInheritableProperty({dict:t,key:"Q"});(!Number.isInteger(i)||i<0||i>2)&&(i=null);this.data.textAlignment=i;let a=getInheritableProperty({dict:t,key:"MaxLen"});(!Number.isInteger(a)||a<0)&&(a=0);this.data.maxLen=a;this.data.multiLine=this.hasFieldFlag(sA);this.data.comb=this.hasFieldFlag(hA)&&!this.hasFieldFlag(sA)&&!this.hasFieldFlag(rA)&&!this.hasFieldFlag(IA)&&0!==this.data.maxLen;this.data.doNotScroll=this.hasFieldFlag(CA)}get hasTextContent(){return!!this.appearance&&!this._needAppearances}_getCombAppearance(e,t,i,a,s,r,n,g,o,c,C){const h=s/this.data.maxLen,l=this.getBorderAndBackgroundAppearances(C),Q=[],E=t.getCharPositions(i);for(const[e,t]of E)Q.push(`(${escapeString(i.substring(e,t))}) Tj`);const u=Q.join(` ${numberToString(h)} 0 Td `);return`/Tx BMC q ${l}BT `+e+` 1 0 0 1 ${numberToString(n)} ${numberToString(g+o)} Tm ${u} ET Q EMC`}_getMultilineAppearance(e,t,i,a,s,r,n,g,o,c,C,h){const l=[],Q=s-2*g,E={shift:0};for(let e=0,r=t.length;ea){o.push(e.substring(l,i));l=i;Q=u;c=-1;h=-1}else{Q+=u;c=i;C=s;h=t}else if(Q+u>a)if(-1!==c){o.push(e.substring(l,C));l=C;t=h+1;c=-1;Q=0}else{o.push(e.substring(l,i));l=i;Q=u}else Q+=u}lt?`\\${t}`:"\\s+"));new RegExp(`^\\s*${r}\\s*$`).test(this.data.fieldValue)&&(this.data.textContent=this.data.fieldValue.split("\n"))}getFieldObject(){return{id:this.data.id,value:this.data.fieldValue,defaultValue:this.data.defaultFieldValue||"",multiline:this.data.multiLine,password:this.hasFieldFlag(rA),charLimit:this.data.maxLen,comb:this.data.comb,editable:!this.data.readOnly,hidden:this.data.hidden,name:this.data.fieldName,rect:this.data.rect,actions:this.data.actions,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,type:"text"}}}class ButtonWidgetAnnotation extends WidgetAnnotation{constructor(e){super(e);this.checkedAppearance=null;this.uncheckedAppearance=null;this.data.checkBox=!this.hasFieldFlag(nA)&&!this.hasFieldFlag(gA);this.data.radioButton=this.hasFieldFlag(nA)&&!this.hasFieldFlag(gA);this.data.pushButton=this.hasFieldFlag(gA);this.data.isTooltipOnly=!1;if(this.data.checkBox)this._processCheckBox(e);else if(this.data.radioButton)this._processRadioButton(e);else if(this.data.pushButton){this.data.hasOwnCanvas=!0;this.data.noHTML=!1;this._processPushButton(e)}else warn("Invalid field flags for button widget annotation")}async getOperatorList(e,t,a,s){if(this.data.pushButton)return super.getOperatorList(e,t,a,!1,s);let r=null,n=null;if(s){const e=s.get(this.data.id);r=e?e.value:null;n=e?e.rotation:null}if(null===r&&this.appearance)return super.getOperatorList(e,t,a,s);null==r&&(r=this.data.checkBox?this.data.fieldValue===this.data.exportValue:this.data.fieldValue===this.data.buttonValue);const g=r?this.checkedAppearance:this.uncheckedAppearance;if(g){const r=this.appearance,o=lookupMatrix(g.dict.getArray("Matrix"),i);n&&g.dict.set("Matrix",this.getRotationMatrix(s));this.appearance=g;const c=super.getOperatorList(e,t,a,s);this.appearance=r;g.dict.set("Matrix",o);return c}return{opList:new OperatorList,separateForm:!1,separateCanvas:!1}}async save(e,t,i,a){this.data.checkBox?this._saveCheckbox(e,t,i,a):this.data.radioButton&&this._saveRadioButton(e,t,i,a)}async _saveCheckbox(e,t,i,a){if(!i)return;const s=i.get(this.data.id),r=this._buildFlags(s?.noView,s?.noPrint);let n=s?.rotation,g=s?.value;if(void 0===n&&void 0===r){if(void 0===g)return;if(this.data.fieldValue===this.data.exportValue===g)return}let o=e.xref.fetchIfRef(this.ref);if(!(o instanceof Dict))return;o=o.clone();void 0===n&&(n=this.rotation);void 0===g&&(g=this.data.fieldValue===this.data.exportValue);const c={path:this.data.fieldName,value:g?this.data.exportValue:""},C=Name.get(g?this.data.exportValue:"Off");this.setValue(o,C,e.xref,a);o.set("AS",C);o.set("M",`D:${getModificationDate()}`);void 0!==r&&o.set("F",r);const h=this._getMKDict(n);h&&o.set("MK",h);a.put(this.ref,{data:o,xfa:c,needAppearances:!1})}async _saveRadioButton(e,t,i,a){if(!i)return;const s=i.get(this.data.id),r=this._buildFlags(s?.noView,s?.noPrint);let n=s?.rotation,g=s?.value;if(void 0===n&&void 0===r){if(void 0===g)return;if(this.data.fieldValue===this.data.buttonValue===g)return}let o=e.xref.fetchIfRef(this.ref);if(!(o instanceof Dict))return;o=o.clone();void 0===g&&(g=this.data.fieldValue===this.data.buttonValue);void 0===n&&(n=this.rotation);const c={path:this.data.fieldName,value:g?this.data.buttonValue:""},C=Name.get(g?this.data.buttonValue:"Off");g&&this.setValue(o,C,e.xref,a);o.set("AS",C);o.set("M",`D:${getModificationDate()}`);void 0!==r&&o.set("F",r);const h=this._getMKDict(n);h&&o.set("MK",h);a.put(this.ref,{data:o,xfa:c,needAppearances:!1})}_getDefaultCheckedAppearance(e,t){const i=this.data.rect[2]-this.data.rect[0],a=this.data.rect[3]-this.data.rect[1],s=[0,0,i,a],r=.8*Math.min(i,a);let n,g;if("check"===t){n={width:.755*r,height:.705*r};g="3"}else if("disc"===t){n={width:.791*r,height:.705*r};g="l"}else unreachable(`_getDefaultCheckedAppearance - unsupported type: ${t}`);const o=`q BT /PdfJsZaDb ${r} Tf 0 g ${numberToString((i-n.width)/2)} ${numberToString((a-n.height)/2)} Td (${g}) Tj ET Q`,c=new Dict(e.xref);c.set("FormType",1);c.set("Subtype",Name.get("Form"));c.set("Type",Name.get("XObject"));c.set("BBox",s);c.set("Matrix",[1,0,0,1,0,0]);c.set("Length",o.length);const C=new Dict(e.xref),h=new Dict(e.xref);h.set("PdfJsZaDb",this.fallbackFontDict);C.set("Font",h);c.set("Resources",C);this.checkedAppearance=new StringStream(o);this.checkedAppearance.dict=c;this._streams.push(this.checkedAppearance)}_processCheckBox(e){const t=e.dict.get("AP");if(!(t instanceof Dict))return;const i=t.get("N");if(!(i instanceof Dict))return;const a=this._decodeFormValue(e.dict.get("AS"));"string"==typeof a&&(this.data.fieldValue=a);const s=null!==this.data.fieldValue&&"Off"!==this.data.fieldValue?this.data.fieldValue:"Yes",r=i.getKeys();if(0===r.length)r.push("Off",s);else if(1===r.length)"Off"===r[0]?r.push(s):r.unshift("Off");else if(r.includes(s)){r.length=0;r.push("Off",s)}else{const e=r.find((e=>"Off"!==e));r.length=0;r.push("Off",e)}r.includes(this.data.fieldValue)||(this.data.fieldValue="Off");this.data.exportValue=r[1];const n=i.get(this.data.exportValue);this.checkedAppearance=n instanceof BaseStream?n:null;const g=i.get("Off");this.uncheckedAppearance=g instanceof BaseStream?g:null;this.checkedAppearance?this._streams.push(this.checkedAppearance):this._getDefaultCheckedAppearance(e,"check");this.uncheckedAppearance&&this._streams.push(this.uncheckedAppearance);this._fallbackFontDict=this.fallbackFontDict;null===this.data.defaultFieldValue&&(this.data.defaultFieldValue="Off")}_processRadioButton(e){this.data.buttonValue=null;const t=e.dict.get("Parent");if(t instanceof Dict){this.parent=e.dict.getRaw("Parent");const i=t.get("V");i instanceof Name&&(this.data.fieldValue=this._decodeFormValue(i))}const i=e.dict.get("AP");if(!(i instanceof Dict))return;const a=i.get("N");if(!(a instanceof Dict))return;for(const e of a.getKeys())if("Off"!==e){this.data.buttonValue=this._decodeFormValue(e);break}const s=a.get(this.data.buttonValue);this.checkedAppearance=s instanceof BaseStream?s:null;const r=a.get("Off");this.uncheckedAppearance=r instanceof BaseStream?r:null;this.checkedAppearance?this._streams.push(this.checkedAppearance):this._getDefaultCheckedAppearance(e,"disc");this.uncheckedAppearance&&this._streams.push(this.uncheckedAppearance);this._fallbackFontDict=this.fallbackFontDict;null===this.data.defaultFieldValue&&(this.data.defaultFieldValue="Off")}_processPushButton(e){const{dict:t,annotationGlobals:i}=e;if(t.has("A")||t.has("AA")||this.data.alternativeText){this.data.isTooltipOnly=!t.has("A")&&!t.has("AA");Catalog.parseDestDictionary({destDict:t,resultObj:this.data,docBaseUrl:i.baseUrl,docAttachments:i.attachments})}else warn("Push buttons without action dictionaries are not supported")}getFieldObject(){let e,t="button";if(this.data.checkBox){t="checkbox";e=this.data.exportValue}else if(this.data.radioButton){t="radiobutton";e=this.data.buttonValue}return{id:this.data.id,value:this.data.fieldValue||"Off",defaultValue:this.data.defaultFieldValue,exportValues:e,editable:!this.data.readOnly,name:this.data.fieldName,rect:this.data.rect,hidden:this.data.hidden,actions:this.data.actions,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,type:t}}get fallbackFontDict(){const e=new Dict;e.set("BaseFont",Name.get("ZapfDingbats"));e.set("Type",Name.get("FallbackType"));e.set("Subtype",Name.get("FallbackType"));e.set("Encoding",Name.get("ZapfDingbatsEncoding"));return shadow(this,"fallbackFontDict",e)}}class ChoiceWidgetAnnotation extends WidgetAnnotation{constructor(e){super(e);const{dict:t,xref:i}=e;this.indices=t.getArray("I");this.hasIndices=Array.isArray(this.indices)&&this.indices.length>0;this.data.options=[];const a=getInheritableProperty({dict:t,key:"Opt"});if(Array.isArray(a))for(let e=0,t=a.length;e=0&&t0&&(this.data.options=this.data.fieldValue.map((e=>({exportValue:e,displayValue:e}))));this.data.combo=this.hasFieldFlag(oA);this.data.multiSelect=this.hasFieldFlag(cA);this._hasText=!0}getFieldObject(){const e=this.data.combo?"combobox":"listbox",t=this.data.fieldValue.length>0?this.data.fieldValue[0]:null;return{id:this.data.id,value:t,defaultValue:this.data.defaultFieldValue,editable:!this.data.readOnly,name:this.data.fieldName,rect:this.data.rect,numItems:this.data.fieldValue.length,multipleSelection:this.data.multiSelect,hidden:this.data.hidden,actions:this.data.actions,items:this.data.options,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,type:e}}amendSavedDict(e,t){if(!this.hasIndices)return;let i=e?.get(this.data.id)?.value;Array.isArray(i)||(i=[i]);const a=[],{options:s}=this.data;for(let e=0,t=0,r=s.length;ei){i=a;t=e}}[Q,E]=this._computeFontSize(e,c-4,t,l,-1)}const u=E*s,d=(u-E)/2,f=Math.floor(o/u);let p=0;if(h.length>0){const e=Math.min(...h),t=Math.max(...h);p=Math.max(0,t-f+1);p>e&&(p=e)}const m=Math.min(p+f+1,C),y=["/Tx BMC q",`1 1 ${c} ${o} re W n`];if(h.length){y.push("0.600006 0.756866 0.854904 rg");for(const e of h)p<=e&&ee.trimEnd()));const{coords:e,bbox:t,matrix:i}=FakeUnicodeFont.getFirstPositionInfo(this.rectangle,this.rotation,a);this.data.textPosition=this._transformPoint(e,t,i)}if(this._isOffscreenCanvasSupported){const s=e.dict.get("CA"),r=new FakeUnicodeFont(i,"sans-serif");this.appearance=r.createAppearance(this._contents.str,this.rectangle,this.rotation,a,t,s);this._streams.push(this.appearance)}else warn("FreeTextAnnotation: OffscreenCanvas is not supported, annotation may not render correctly.")}}get hasTextContent(){return this._hasAppearance}static createNewDict(e,t,{apRef:i,ap:a}){const{color:s,fontSize:r,oldAnnotation:n,rect:g,rotation:o,user:c,value:C}=e,h=n||new Dict(t);h.set("Type",Name.get("Annot"));h.set("Subtype",Name.get("FreeText"));if(n){h.set("M",`D:${getModificationDate()}`);h.delete("RC")}else h.set("CreationDate",`D:${getModificationDate()}`);h.set("Rect",g);const l=`/Helv ${r} Tf ${getPdfColor(s,!0)}`;h.set("DA",l);h.set("Contents",stringToAsciiOrUTF16BE(C));h.set("F",4);h.set("Border",[0,0,0]);h.set("Rotate",o);c&&h.set("T",stringToAsciiOrUTF16BE(c));if(i||a){const e=new Dict(t);h.set("AP",e);i?e.set("N",i):e.set("N",a)}return h}static async createNewAppearanceStream(e,t,i){const{baseFontRef:a,evaluator:r,task:n}=i,{color:g,fontSize:o,rect:c,rotation:C,value:h}=e,l=new Dict(t),Q=new Dict(t);if(a)Q.set("Helv",a);else{const e=new Dict(t);e.set("BaseFont",Name.get("Helvetica"));e.set("Type",Name.get("Font"));e.set("Subtype",Name.get("Type1"));e.set("Encoding",Name.get("WinAnsiEncoding"));Q.set("Helv",e)}l.set("Font",Q);const E=await WidgetAnnotation._getFontData(r,n,{fontName:"Helv",fontSize:o},l),[u,d,f,p]=c;let m=f-u,y=p-d;C%180!=0&&([m,y]=[y,m]);const w=h.split("\n"),D=o/1e3;let b=-1/0;const F=[];for(let e of w){const t=E.encodeString(e);if(t.length>1)return null;e=t.join("");F.push(e);let i=0;const a=E.charsToGlyphs(e);for(const e of a)i+=e.width*D;b=Math.max(b,i)}let S=1;b>m&&(S=m/b);let k=1;const R=s*o,N=1*o,G=R*w.length;G>y&&(k=y/G);const M=o*Math.min(S,k);let U,x,L;switch(C){case 0:L=[1,0,0,1];x=[c[0],c[1],m,y];U=[c[0],c[3]-N];break;case 90:L=[0,1,-1,0];x=[c[1],-c[2],m,y];U=[c[1],-c[0]-N];break;case 180:L=[-1,0,0,-1];x=[-c[2],-c[3],m,y];U=[-c[2],-c[1]-N];break;case 270:L=[0,-1,1,0];x=[-c[3],c[0],m,y];U=[-c[3],c[2]-N]}const H=["q",`${L.join(" ")} 0 0 cm`,`${x.join(" ")} re W n`,"BT",`${getPdfColor(g,!0)}`,`0 Tc /Helv ${numberToString(M)} Tf`];H.push(`${U.join(" ")} Td (${escapeString(F[0])}) Tj`);const J=numberToString(R);for(let e=1,t=F.length;e{e.push(`${a[0]} ${a[1]} m`,`${a[2]} ${a[3]} l`,"S");return[t[0]-o,t[2]+o,t[7]-o,t[3]+o]}})}}}class SquareAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:i}=e;this.data.annotationType=M;this.data.hasOwnCanvas=this.data.noRotate;this.data.noHTML=!1;if(!this.appearance){const e=this.color?getPdfColorArray(this.color):[0,0,0],a=t.get("CA"),s=getRgbColor(t.getArray("IC"),null),r=s?getPdfColorArray(s):null,n=r?a:null;if(0===this.borderStyle.width&&!r)return;this._setDefaultAppearance({xref:i,extra:`${this.borderStyle.width} w`,strokeColor:e,fillColor:r,strokeAlpha:a,fillAlpha:n,pointsCallback:(e,t)=>{const i=t[4]+this.borderStyle.width/2,a=t[5]+this.borderStyle.width/2,s=t[6]-t[4]-this.borderStyle.width,n=t[3]-t[7]-this.borderStyle.width;e.push(`${i} ${a} ${s} ${n} re`);r?e.push("B"):e.push("S");return[t[0],t[2],t[7],t[3]]}})}}}class CircleAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:i}=e;this.data.annotationType=U;if(!this.appearance){const e=this.color?getPdfColorArray(this.color):[0,0,0],a=t.get("CA"),s=getRgbColor(t.getArray("IC"),null),r=s?getPdfColorArray(s):null,n=r?a:null;if(0===this.borderStyle.width&&!r)return;const g=4/3*Math.tan(Math.PI/8);this._setDefaultAppearance({xref:i,extra:`${this.borderStyle.width} w`,strokeColor:e,fillColor:r,strokeAlpha:a,fillAlpha:n,pointsCallback:(e,t)=>{const i=t[0]+this.borderStyle.width/2,a=t[1]-this.borderStyle.width/2,s=t[6]-this.borderStyle.width/2,n=t[7]+this.borderStyle.width/2,o=i+(s-i)/2,c=a+(n-a)/2,C=(s-i)/2*g,h=(n-a)/2*g;e.push(`${o} ${n} m`,`${o+C} ${n} ${s} ${c+h} ${s} ${c} c`,`${s} ${c-h} ${o+C} ${a} ${o} ${a} c`,`${o-C} ${a} ${i} ${c-h} ${i} ${c} c`,`${i} ${c+h} ${o-C} ${n} ${o} ${n} c`,"h");r?e.push("B"):e.push("S");return[t[0],t[2],t[7],t[3]]}})}}}class PolylineAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:i}=e;this.data.annotationType=L;this.data.hasOwnCanvas=this.data.noRotate;this.data.noHTML=!1;this.data.vertices=null;if(!(this instanceof PolygonAnnotation)){this.setLineEndings(t.getArray("LE"));this.data.lineEndings=this.lineEndings}const a=t.getArray("Vertices");if(!isNumberArray(a,null))return;const s=this.data.vertices=Float32Array.from(a);if(!this.appearance){const e=this.color?getPdfColorArray(this.color):[0,0,0],a=t.get("CA"),r=this.borderStyle.width||1,n=2*r,g=[1/0,1/0,-1/0,-1/0];for(let e=0,t=s.length;e{for(let t=0,i=s.length;t{for(const t of this.data.inkLists){for(let i=0,a=t.length;ie/255)));Q.set("CA",n);const u=new Dict(t);Q.set("AP",u);i?u.set("N",i):u.set("N",a);return Q}static async createNewAppearanceStream(e,t,i){if(e.outlines)return this.createNewAppearanceStreamForHighlight(e,t,i);const{color:a,rect:s,paths:r,thickness:n,opacity:g}=e,o=[`${n} w 1 J 1 j`,`${getPdfColor(a,!1)}`];1!==g&&o.push("/R0 gs");for(const e of r.lines){o.push(`${numberToString(e[4])} ${numberToString(e[5])} m`);for(let t=6,i=e.length;t{e.push(`${t[0]} ${t[1]} m`,`${t[2]} ${t[3]} l`,`${t[6]} ${t[7]} l`,`${t[4]} ${t[5]} l`,"f");return[t[0],t[2],t[7],t[3]]}})}}else this.data.popupRef=null}static createNewDict(e,t,{apRef:i,ap:a}){const{color:s,oldAnnotation:r,opacity:n,rect:g,rotation:o,user:c,quadPoints:C}=e,h=r||new Dict(t);h.set("Type",Name.get("Annot"));h.set("Subtype",Name.get("Highlight"));h.set(r?"M":"CreationDate",`D:${getModificationDate()}`);h.set("CreationDate",`D:${getModificationDate()}`);h.set("Rect",g);h.set("F",4);h.set("Border",[0,0,0]);h.set("Rotate",o);h.set("QuadPoints",C);h.set("C",Array.from(s,(e=>e/255)));h.set("CA",n);c&&h.set("T",stringToAsciiOrUTF16BE(c));if(i||a){const e=new Dict(t);h.set("AP",e);e.set("N",i||a)}return h}static async createNewAppearanceStream(e,t,i){const{color:a,rect:s,outlines:r,opacity:n}=e,g=[`${getPdfColor(a,!0)}`,"/R0 gs"],o=[];for(const e of r){o.length=0;o.push(`${numberToString(e[0])} ${numberToString(e[1])} m`);for(let t=2,i=e.length;t{e.push(`${t[4]} ${t[5]+1.3} m`,`${t[6]} ${t[7]+1.3} l`,"S");return[t[0],t[2],t[7],t[3]]}})}}else this.data.popupRef=null}}class SquigglyAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:i}=e;this.data.annotationType=Y;if(this.data.quadPoints=getQuadPoints(t,null)){if(!this.appearance){const e=this.color?getPdfColorArray(this.color):[0,0,0],a=t.get("CA");this._setDefaultAppearance({xref:i,extra:"[] 0 d 1 w",strokeColor:e,strokeAlpha:a,pointsCallback:(e,t)=>{const i=(t[1]-t[5])/6;let a=i,s=t[4];const r=t[5],n=t[6];e.push(`${s} ${r+a} m`);do{s+=2;a=0===a?i:0;e.push(`${s} ${r+a} l`)}while(s{e.push((t[0]+t[4])/2+" "+(t[1]+t[5])/2+" m",(t[2]+t[6])/2+" "+(t[3]+t[7])/2+" l","S");return[t[0],t[2],t[7],t[3]]}})}}else this.data.popupRef=null}}class StampAnnotation extends MarkupAnnotation{#T;constructor(e){super(e);this.data.annotationType=K;this.#T=this.data.hasOwnCanvas=this.data.noRotate;this.data.isEditable=!this.data.noHTML;this.data.noHTML=!1}mustBeViewedWhenEditing(e,t=null){if(e){if(!this.data.isEditable)return!1;this.#T=this.data.hasOwnCanvas;this.data.hasOwnCanvas=!0;return!0}this.data.hasOwnCanvas=this.#T;return!t?.has(this.data.id)}static async createImage(e,t){const{width:i,height:a}=e,s=new OffscreenCanvas(i,a),r=s.getContext("2d",{alpha:!0});r.drawImage(e,0,0);const n=r.getImageData(0,0,i,a).data,g=new Uint32Array(n.buffer),o=g.some(FeatureTest.isLittleEndian?e=>e>>>24!=255:e=>!!(255&~e));if(o){r.fillStyle="white";r.fillRect(0,0,i,a);r.drawImage(e,0,0)}const c=s.convertToBlob({type:"image/jpeg",quality:1}).then((e=>e.arrayBuffer())),C=Name.get("XObject"),h=Name.get("Image"),l=new Dict(t);l.set("Type",C);l.set("Subtype",h);l.set("BitsPerComponent",8);l.set("ColorSpace",Name.get("DeviceRGB"));l.set("Filter",Name.get("DCTDecode"));l.set("BBox",[0,0,i,a]);l.set("Width",i);l.set("Height",a);let Q=null;if(o){const e=new Uint8Array(g.length);if(FeatureTest.isLittleEndian)for(let t=0,i=g.length;t>>24;else for(let t=0,i=g.length;t=0&&r<=1?r:null}}class DecryptStream extends DecodeStream{constructor(e,t,i){super(t);this.str=e;this.dict=e.dict;this.decrypt=i;this.nextChunk=null;this.initialized=!1}readBlock(){let e;if(this.initialized)e=this.nextChunk;else{e=this.str.getBytes(512);this.initialized=!0}if(!e?.length){this.eof=!0;return}this.nextChunk=this.str.getBytes(512);const t=this.nextChunk?.length>0;e=(0,this.decrypt)(e,!t);const i=this.bufferLength,a=i+e.length;this.ensureBuffer(a).set(e,i);this.bufferLength=a}}class ARCFourCipher{constructor(e){this.a=0;this.b=0;const t=new Uint8Array(256),i=e.length;for(let e=0;e<256;++e)t[e]=e;for(let a=0,s=0;a<256;++a){const r=t[a];s=s+r+e[a%i]&255;t[a]=t[s];t[s]=r}this.s=t}encryptBlock(e){let t=this.a,i=this.b;const a=this.s,s=e.length,r=new Uint8Array(s);for(let n=0;n>5&255;C[h++]=s>>13&255;C[h++]=s>>21&255;C[h++]=s>>>29&255;C[h++]=0;C[h++]=0;C[h++]=0;const E=new Int32Array(16);for(h=0;h>>32-g)|0;s=r}r=r+s|0;n=n+c|0;g=g+Q|0;o=o+u|0}return new Uint8Array([255&r,r>>8&255,r>>16&255,r>>>24&255,255&n,n>>8&255,n>>16&255,n>>>24&255,255&g,g>>8&255,g>>16&255,g>>>24&255,255&o,o>>8&255,o>>16&255,o>>>24&255])}}();class Word64{constructor(e,t){this.high=0|e;this.low=0|t}and(e){this.high&=e.high;this.low&=e.low}xor(e){this.high^=e.high;this.low^=e.low}or(e){this.high|=e.high;this.low|=e.low}shiftRight(e){if(e>=32){this.low=this.high>>>e-32|0;this.high=0}else{this.low=this.low>>>e|this.high<<32-e;this.high=this.high>>>e|0}}shiftLeft(e){if(e>=32){this.high=this.low<>>32-e;this.low<<=e}}rotateRight(e){let t,i;if(32&e){i=this.low;t=this.high}else{t=this.low;i=this.high}e&=31;this.low=t>>>e|i<<32-e;this.high=i>>>e|t<<32-e}not(){this.high=~this.high;this.low=~this.low}add(e){const t=(this.low>>>0)+(e.low>>>0);let i=(this.high>>>0)+(e.high>>>0);t>4294967295&&(i+=1);this.low=0|t;this.high=0|i}copyTo(e,t){e[t]=this.high>>>24&255;e[t+1]=this.high>>16&255;e[t+2]=this.high>>8&255;e[t+3]=255&this.high;e[t+4]=this.low>>>24&255;e[t+5]=this.low>>16&255;e[t+6]=this.low>>8&255;e[t+7]=255&this.low}assign(e){this.high=e.high;this.low=e.low}}const Ag=function calculateSHA256Closure(){function rotr(e,t){return e>>>t|e<<32-t}function ch(e,t,i){return e&t^~e&i}function maj(e,t,i){return e&t^e&i^t&i}function sigma(e){return rotr(e,2)^rotr(e,13)^rotr(e,22)}function sigmaPrime(e){return rotr(e,6)^rotr(e,11)^rotr(e,25)}function littleSigma(e){return rotr(e,7)^rotr(e,18)^e>>>3}const e=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];return function hash(t,i,a){let s=1779033703,r=3144134277,n=1013904242,g=2773480762,o=1359893119,c=2600822924,C=528734635,h=1541459225;const l=64*Math.ceil((a+9)/64),Q=new Uint8Array(l);let E,u;for(E=0;E>>29&255;Q[E++]=a>>21&255;Q[E++]=a>>13&255;Q[E++]=a>>5&255;Q[E++]=a<<3&255;const f=new Uint32Array(64);for(E=0;E>>10)+f[u-7]+littleSigma(f[u-15])+f[u-16]|0;let t,i,a=s,l=r,d=n,m=g,y=o,w=c,D=C,b=h;for(u=0;u<64;++u){t=b+sigmaPrime(y)+ch(y,w,D)+e[u]+f[u];i=sigma(a)+maj(a,l,d);b=D;D=w;w=y;y=m+t|0;m=d;d=l;l=a;a=t+i|0}s=s+a|0;r=r+l|0;n=n+d|0;g=g+m|0;o=o+y|0;c=c+w|0;C=C+D|0;h=h+b|0}var p;return new Uint8Array([s>>24&255,s>>16&255,s>>8&255,255&s,r>>24&255,r>>16&255,r>>8&255,255&r,n>>24&255,n>>16&255,n>>8&255,255&n,g>>24&255,g>>16&255,g>>8&255,255&g,o>>24&255,o>>16&255,o>>8&255,255&o,c>>24&255,c>>16&255,c>>8&255,255&c,C>>24&255,C>>16&255,C>>8&255,255&C,h>>24&255,h>>16&255,h>>8&255,255&h])}}(),eg=function calculateSHA512Closure(){function ch(e,t,i,a,s){e.assign(t);e.and(i);s.assign(t);s.not();s.and(a);e.xor(s)}function maj(e,t,i,a,s){e.assign(t);e.and(i);s.assign(t);s.and(a);e.xor(s);s.assign(i);s.and(a);e.xor(s)}function sigma(e,t,i){e.assign(t);e.rotateRight(28);i.assign(t);i.rotateRight(34);e.xor(i);i.assign(t);i.rotateRight(39);e.xor(i)}function sigmaPrime(e,t,i){e.assign(t);e.rotateRight(14);i.assign(t);i.rotateRight(18);e.xor(i);i.assign(t);i.rotateRight(41);e.xor(i)}function littleSigma(e,t,i){e.assign(t);e.rotateRight(1);i.assign(t);i.rotateRight(8);e.xor(i);i.assign(t);i.shiftRight(7);e.xor(i)}function littleSigmaPrime(e,t,i){e.assign(t);e.rotateRight(19);i.assign(t);i.rotateRight(61);e.xor(i);i.assign(t);i.shiftRight(6);e.xor(i)}const e=[new Word64(1116352408,3609767458),new Word64(1899447441,602891725),new Word64(3049323471,3964484399),new Word64(3921009573,2173295548),new Word64(961987163,4081628472),new Word64(1508970993,3053834265),new Word64(2453635748,2937671579),new Word64(2870763221,3664609560),new Word64(3624381080,2734883394),new Word64(310598401,1164996542),new Word64(607225278,1323610764),new Word64(1426881987,3590304994),new Word64(1925078388,4068182383),new Word64(2162078206,991336113),new Word64(2614888103,633803317),new Word64(3248222580,3479774868),new Word64(3835390401,2666613458),new Word64(4022224774,944711139),new Word64(264347078,2341262773),new Word64(604807628,2007800933),new Word64(770255983,1495990901),new Word64(1249150122,1856431235),new Word64(1555081692,3175218132),new Word64(1996064986,2198950837),new Word64(2554220882,3999719339),new Word64(2821834349,766784016),new Word64(2952996808,2566594879),new Word64(3210313671,3203337956),new Word64(3336571891,1034457026),new Word64(3584528711,2466948901),new Word64(113926993,3758326383),new Word64(338241895,168717936),new Word64(666307205,1188179964),new Word64(773529912,1546045734),new Word64(1294757372,1522805485),new Word64(1396182291,2643833823),new Word64(1695183700,2343527390),new Word64(1986661051,1014477480),new Word64(2177026350,1206759142),new Word64(2456956037,344077627),new Word64(2730485921,1290863460),new Word64(2820302411,3158454273),new Word64(3259730800,3505952657),new Word64(3345764771,106217008),new Word64(3516065817,3606008344),new Word64(3600352804,1432725776),new Word64(4094571909,1467031594),new Word64(275423344,851169720),new Word64(430227734,3100823752),new Word64(506948616,1363258195),new Word64(659060556,3750685593),new Word64(883997877,3785050280),new Word64(958139571,3318307427),new Word64(1322822218,3812723403),new Word64(1537002063,2003034995),new Word64(1747873779,3602036899),new Word64(1955562222,1575990012),new Word64(2024104815,1125592928),new Word64(2227730452,2716904306),new Word64(2361852424,442776044),new Word64(2428436474,593698344),new Word64(2756734187,3733110249),new Word64(3204031479,2999351573),new Word64(3329325298,3815920427),new Word64(3391569614,3928383900),new Word64(3515267271,566280711),new Word64(3940187606,3454069534),new Word64(4118630271,4000239992),new Word64(116418474,1914138554),new Word64(174292421,2731055270),new Word64(289380356,3203993006),new Word64(460393269,320620315),new Word64(685471733,587496836),new Word64(852142971,1086792851),new Word64(1017036298,365543100),new Word64(1126000580,2618297676),new Word64(1288033470,3409855158),new Word64(1501505948,4234509866),new Word64(1607167915,987167468),new Word64(1816402316,1246189591)];return function hash(t,i,a,s=!1){let r,n,g,o,c,C,h,l;if(s){r=new Word64(3418070365,3238371032);n=new Word64(1654270250,914150663);g=new Word64(2438529370,812702999);o=new Word64(355462360,4144912697);c=new Word64(1731405415,4290775857);C=new Word64(2394180231,1750603025);h=new Word64(3675008525,1694076839);l=new Word64(1203062813,3204075428)}else{r=new Word64(1779033703,4089235720);n=new Word64(3144134277,2227873595);g=new Word64(1013904242,4271175723);o=new Word64(2773480762,1595750129);c=new Word64(1359893119,2917565137);C=new Word64(2600822924,725511199);h=new Word64(528734635,4215389547);l=new Word64(1541459225,327033209)}const Q=128*Math.ceil((a+17)/128),E=new Uint8Array(Q);let u,d;for(u=0;u>>29&255;E[u++]=a>>21&255;E[u++]=a>>13&255;E[u++]=a>>5&255;E[u++]=a<<3&255;const p=new Array(80);for(u=0;u<80;u++)p[u]=new Word64(0,0);let m=new Word64(0,0),y=new Word64(0,0),w=new Word64(0,0),D=new Word64(0,0),b=new Word64(0,0),F=new Word64(0,0),S=new Word64(0,0),k=new Word64(0,0);const R=new Word64(0,0),N=new Word64(0,0),G=new Word64(0,0),M=new Word64(0,0);let U,x;for(u=0;u=1;--e){i=r[13];r[13]=r[9];r[9]=r[5];r[5]=r[1];r[1]=i;i=r[14];a=r[10];r[14]=r[6];r[10]=r[2];r[6]=i;r[2]=a;i=r[15];a=r[11];s=r[7];r[15]=r[3];r[11]=i;r[7]=a;r[3]=s;for(let e=0;e<16;++e)r[e]=this._inv_s[r[e]];for(let i=0,a=16*e;i<16;++i,++a)r[i]^=t[a];for(let e=0;e<16;e+=4){const t=this._mix[r[e]],a=this._mix[r[e+1]],s=this._mix[r[e+2]],n=this._mix[r[e+3]];i=t^a>>>8^a<<24^s>>>16^s<<16^n>>>24^n<<8;r[e]=i>>>24&255;r[e+1]=i>>16&255;r[e+2]=i>>8&255;r[e+3]=255&i}}i=r[13];r[13]=r[9];r[9]=r[5];r[5]=r[1];r[1]=i;i=r[14];a=r[10];r[14]=r[6];r[10]=r[2];r[6]=i;r[2]=a;i=r[15];a=r[11];s=r[7];r[15]=r[3];r[11]=i;r[7]=a;r[3]=s;for(let e=0;e<16;++e){r[e]=this._inv_s[r[e]];r[e]^=t[e]}return r}_encrypt(e,t){const i=this._s;let a,s,r;const n=new Uint8Array(16);n.set(e);for(let e=0;e<16;++e)n[e]^=t[e];for(let e=1;e=a;--i)if(e[i]!==t){t=0;break}g-=t;r[r.length-1]=e.subarray(0,16-t)}}const o=new Uint8Array(g);for(let e=0,t=0,i=r.length;e=256&&(g=255&(27^g))}for(let t=0;t<4;++t){i[e]=a^=i[e-32];e++;i[e]=s^=i[e-32];e++;i[e]=r^=i[e-32];e++;i[e]=n^=i[e-32];e++}}return i}}class PDF17{checkOwnerPassword(e,t,i,a){const s=new Uint8Array(e.length+56);s.set(e,0);s.set(t,e.length);s.set(i,e.length+t.length);return isArrayEqual(Ag(s,0,s.length),a)}checkUserPassword(e,t,i){const a=new Uint8Array(e.length+8);a.set(e,0);a.set(t,e.length);return isArrayEqual(Ag(a,0,a.length),i)}getOwnerKey(e,t,i,a){const s=new Uint8Array(e.length+56);s.set(e,0);s.set(t,e.length);s.set(i,e.length+t.length);const r=Ag(s,0,s.length);return new AES256Cipher(r).decryptBlock(a,!1,new Uint8Array(16))}getUserKey(e,t,i){const a=new Uint8Array(e.length+8);a.set(e,0);a.set(t,e.length);const s=Ag(a,0,a.length);return new AES256Cipher(s).decryptBlock(i,!1,new Uint8Array(16))}}class PDF20{_hash(e,t,i){let a=Ag(t,0,t.length).subarray(0,32),s=[0],r=0;for(;r<64||s.at(-1)>r-32;){const t=e.length+a.length+i.length,c=new Uint8Array(t);let C=0;c.set(e,C);C+=e.length;c.set(a,C);C+=a.length;c.set(i,C);const h=new Uint8Array(64*t);for(let e=0,i=0;e<64;e++,i+=t)h.set(c,i);s=new AES128Cipher(a.subarray(0,16)).encrypt(h,a.subarray(16,32));const l=s.slice(0,16).reduce(((e,t)=>e+t),0)%3;0===l?a=Ag(s,0,s.length):1===l?a=(n=s,g=0,o=s.length,eg(n,g,o,!0)):2===l&&(a=eg(s,0,s.length));r++}var n,g,o;return a.subarray(0,32)}checkOwnerPassword(e,t,i,a){const s=new Uint8Array(e.length+56);s.set(e,0);s.set(t,e.length);s.set(i,e.length+t.length);return isArrayEqual(this._hash(e,s,i),a)}checkUserPassword(e,t,i){const a=new Uint8Array(e.length+8);a.set(e,0);a.set(t,e.length);return isArrayEqual(this._hash(e,a,[]),i)}getOwnerKey(e,t,i,a){const s=new Uint8Array(e.length+56);s.set(e,0);s.set(t,e.length);s.set(i,e.length+t.length);const r=this._hash(e,s,i);return new AES256Cipher(r).decryptBlock(a,!1,new Uint8Array(16))}getUserKey(e,t,i){const a=new Uint8Array(e.length+8);a.set(e,0);a.set(t,e.length);const s=this._hash(e,a,[]);return new AES256Cipher(s).decryptBlock(i,!1,new Uint8Array(16))}}class CipherTransform{constructor(e,t){this.StringCipherConstructor=e;this.StreamCipherConstructor=t}createStream(e,t){const i=new this.StreamCipherConstructor;return new DecryptStream(e,t,(function cipherTransformDecryptStream(e,t){return i.decryptBlock(e,t)}))}decryptString(e){const t=new this.StringCipherConstructor;let i=stringToBytes(e);i=t.decryptBlock(i,!0);return bytesToString(i)}encryptString(e){const t=new this.StringCipherConstructor;if(t instanceof AESBaseCipher){const i=16-e.length%16;e+=String.fromCharCode(i).repeat(i);const a=new Uint8Array(16);if("undefined"!=typeof crypto)crypto.getRandomValues(a);else for(let e=0;e<16;e++)a[e]=Math.floor(256*Math.random());let s=stringToBytes(e);s=t.encrypt(s,a);const r=new Uint8Array(16+s.length);r.set(a);r.set(s,16);return bytesToString(r)}let i=stringToBytes(e);i=t.encrypt(i);return bytesToString(i)}}class CipherTransformFactory{static#q=new Uint8Array([40,191,78,94,78,117,138,65,100,0,78,86,255,250,1,8,46,46,0,182,208,104,62,128,47,12,169,254,100,83,105,122]);#O(e,t,i,a,s,r,n,g,o,c,C,h){if(t){const e=Math.min(127,t.length);t=t.subarray(0,e)}else t=[];const l=6===e?new PDF20:new PDF17;return l.checkUserPassword(t,g,n)?l.getUserKey(t,o,C):t.length&&l.checkOwnerPassword(t,a,r,i)?l.getOwnerKey(t,s,r,c):null}#P(e,t,i,a,s,r,n,g){const o=40+i.length+e.length,c=new Uint8Array(o);let C,h,l=0;if(t){h=Math.min(32,t.length);for(;l>8&255;c[l++]=s>>16&255;c[l++]=s>>>24&255;for(C=0,h=e.length;C=4&&!g){c[l++]=255;c[l++]=255;c[l++]=255;c[l++]=255}let Q=$n(c,0,l);const E=n>>3;if(r>=3)for(C=0;C<50;++C)Q=$n(Q,0,E);const u=Q.subarray(0,E);let d,f;if(r>=3){for(l=0;l<32;++l)c[l]=CipherTransformFactory.#q[l];for(C=0,h=e.length;C>3;if(i>=3)for(g=0;g<50;++g)o=$n(o,0,o.length);let C,h;if(i>=3){h=t;const e=new Uint8Array(c);for(g=19;g>=0;g--){for(let t=0;t>8&255;s[n++]=e>>16&255;s[n++]=255&t;s[n++]=t>>8&255;if(a){s[n++]=115;s[n++]=65;s[n++]=108;s[n++]=84}return $n(s,0,n).subarray(0,Math.min(i.length+5,16))}#X(e,t,i,a,s){if(!(t instanceof Name))throw new FormatError("Invalid crypt filter name.");const r=this,n=e.get(t.name),g=n?.get("CFM");if(!g||"None"===g.name)return function(){return new NullCipher};if("V2"===g.name)return function(){return new ARCFourCipher(r.#j(i,a,s,!1))};if("AESV2"===g.name)return function(){return new AES128Cipher(r.#j(i,a,s,!0))};if("AESV3"===g.name)return function(){return new AES256Cipher(s)};throw new FormatError("Unknown crypto method")}constructor(e,t,i){const a=e.get("Filter");if(!isName(a,"Standard"))throw new FormatError("unknown encryption method");this.filterName=a.name;this.dict=e;const s=e.get("V");if(!Number.isInteger(s)||1!==s&&2!==s&&4!==s&&5!==s)throw new FormatError("unsupported encryption algorithm");this.algorithm=s;let r=e.get("Length");if(!r)if(s<=3)r=40;else{const t=e.get("CF"),i=e.get("StmF");if(t instanceof Dict&&i instanceof Name){t.suppressEncryption=!0;const e=t.get(i.name);r=e?.get("Length")||128;r<40&&(r<<=3)}}if(!Number.isInteger(r)||r<40||r%8!=0)throw new FormatError("invalid key length");const n=stringToBytes(e.get("O")),g=stringToBytes(e.get("U")),o=n.subarray(0,32),c=g.subarray(0,32),C=e.get("P"),h=e.get("R"),l=(4===s||5===s)&&!1!==e.get("EncryptMetadata");this.encryptMetadata=l;const Q=stringToBytes(t);let E,u;if(i){if(6===h)try{i=utf8StringToString(i)}catch{warn("CipherTransformFactory: Unable to convert UTF8 encoded password.")}E=stringToBytes(i)}if(5!==s)u=this.#P(Q,E,o,c,C,h,r,l);else{const t=n.subarray(32,40),i=n.subarray(40,48),a=g.subarray(0,48),s=g.subarray(32,40),r=g.subarray(40,48),C=stringToBytes(e.get("OE")),l=stringToBytes(e.get("UE")),Q=stringToBytes(e.get("Perms"));u=this.#O(h,E,o,t,i,a,c,s,r,C,l,Q)}if(!u&&!i)throw new PasswordException("No password given",rt);if(!u&&i){const e=this.#W(E,o,h,r);u=this.#P(Q,e,o,c,C,h,r,l)}if(!u)throw new PasswordException("Incorrect Password",nt);this.encryptionKey=u;if(s>=4){const t=e.get("CF");t instanceof Dict&&(t.suppressEncryption=!0);this.cf=t;this.stmf=e.get("StmF")||Name.get("Identity");this.strf=e.get("StrF")||Name.get("Identity");this.eff=e.get("EFF")||this.stmf}}createCipherTransform(e,t){if(4===this.algorithm||5===this.algorithm)return new CipherTransform(this.#X(this.cf,this.strf,e,t,this.encryptionKey),this.#X(this.cf,this.stmf,e,t,this.encryptionKey));const i=this.#j(e,t,this.encryptionKey,!1),cipherConstructor=function(){return new ARCFourCipher(i)};return new CipherTransform(cipherConstructor,cipherConstructor)}}function decodeString(e){try{return stringToUTF8String(e)}catch(t){warn(`UTF-8 decoding failed: "${t}".`);return e}}class DatasetXMLParser extends SimpleXMLParser{constructor(e){super(e);this.node=null}onEndElement(e){const t=super.onEndElement(e);if(t&&"xfa:datasets"===e){this.node=t;throw new Error("Aborting DatasetXMLParser.")}}}class DatasetReader{constructor(e){if(e.datasets)this.node=new SimpleXMLParser({hasAttributes:!0}).parseFromString(e.datasets).documentElement;else{const t=new DatasetXMLParser({hasAttributes:!0});try{t.parseFromString(e["xdp:xdp"])}catch{}this.node=t.node}}getValue(e){if(!this.node||!e)return"";const t=this.node.searchNode(parseXFAPath(e),0);if(!t)return"";const i=t.firstChild;return"value"===i?.nodeName?t.children.map((e=>decodeString(e.textContent))):decodeString(t.textContent)}}class XRef{#Z=null;constructor(e,t){this.stream=e;this.pdfManager=t;this.entries=[];this._xrefStms=new Set;this._cacheMap=new Map;this._pendingRefs=new RefSet;this._newPersistentRefNum=null;this._newTemporaryRefNum=null;this._persistentRefsCache=null}getNewPersistentRef(e){null===this._newPersistentRefNum&&(this._newPersistentRefNum=this.entries.length||1);const t=this._newPersistentRefNum++;this._cacheMap.set(t,e);return Ref.get(t,0)}getNewTemporaryRef(){if(null===this._newTemporaryRefNum){this._newTemporaryRefNum=this.entries.length||1;if(this._newPersistentRefNum){this._persistentRefsCache=new Map;for(let e=this._newTemporaryRefNum;e0;){const[n,g]=r;if(!Number.isInteger(n)||!Number.isInteger(g))throw new FormatError(`Invalid XRef range fields: ${n}, ${g}`);if(!Number.isInteger(i)||!Number.isInteger(a)||!Number.isInteger(s))throw new FormatError(`Invalid XRef entry fields length: ${n}, ${g}`);for(let r=t.entryNum;r=e.length);){i+=String.fromCharCode(a);a=e[t]}return i}function skipUntil(e,t,i){const a=i.length,s=e.length;let r=0;for(;t=a)break;t++;r++}return r}const e=/\b(endobj|\d+\s+\d+\s+obj|xref|trailer\s*<<)\b/g,t=/\b(startxref|\d+\s+\d+\s+obj)\b/g,i=/^(\d+)\s+(\d+)\s+obj\b/,a=new Uint8Array([116,114,97,105,108,101,114]),s=new Uint8Array([115,116,97,114,116,120,114,101,102]),r=new Uint8Array([47,88,82,101,102]);this.entries.length=0;this._cacheMap.clear();const n=this.stream;n.pos=0;const g=n.getBytes(),o=bytesToString(g),c=g.length;let C=n.start;const h=[],l=[];for(;C=c)break;Q=g[C]}while(10!==Q&&13!==Q);continue}const E=readToken(g,C);let u;if(E.startsWith("xref")&&(4===E.length||/\s/.test(E[4]))){C+=skipUntil(g,C,a);h.push(C);C+=skipUntil(g,C,s)}else if(u=i.exec(E)){const t=0|u[1],i=0|u[2],a=C+E.length;let s,h=!1;if(this.entries[t]){if(this.entries[t].gen===i)try{new Parser({lexer:new Lexer(n.makeSubStream(a))}).getObj();h=!0}catch(e){e instanceof ParserEOFException?warn(`indexObjects -- checking object (${E}): "${e}".`):h=!0}}else h=!0;h&&(this.entries[t]={offset:C-n.start,gen:i,uncompressed:!0});e.lastIndex=a;const Q=e.exec(o);if(Q){s=e.lastIndex+1-C;if("endobj"!==Q[1]){warn(`indexObjects: Found "${Q[1]}" inside of another "obj", caused by missing "endobj" -- trying to recover.`);s-=Q[1].length+1}}else s=c-C;const d=g.subarray(C,C+s),f=skipUntil(d,0,r);if(f0?Math.max(...this._xrefStms):null)}getEntry(e){const t=this.entries[e];return t&&!t.free&&t.offset?t:null}fetchIfRef(e,t=!1){return e instanceof Ref?this.fetch(e,t):e}fetch(e,t=!1){if(!(e instanceof Ref))throw new Error("ref object is not a reference");const i=e.num,a=this._cacheMap.get(i);if(void 0!==a){a instanceof Dict&&!a.objId&&(a.objId=e.toString());return a}let s=this.getEntry(i);if(null===s){this._cacheMap.set(i,s);return s}if(this._pendingRefs.has(e)){this._pendingRefs.remove(e);warn(`Ignoring circular reference: ${e}.`);return lt}this._pendingRefs.put(e);try{s=s.uncompressed?this.fetchUncompressed(e,s,t):this.fetchCompressed(e,s,t);this._pendingRefs.remove(e)}catch(t){this._pendingRefs.remove(e);throw t}s instanceof Dict?s.objId=e.toString():s instanceof BaseStream&&(s.dict.objId=e.toString());return s}fetchUncompressed(e,t,i=!1){const a=e.gen;let s=e.num;if(t.gen!==a){const r=`Inconsistent generation in XRef: ${e}`;if(this._generationFallback&&t.gen0&&t[3]-t[1]>0)return t;warn(`Empty, or invalid, /${e} entry.`)}return null}get mediaBox(){return shadow(this,"mediaBox",this._getBoundingBox("MediaBox")||tg)}get cropBox(){return shadow(this,"cropBox",this._getBoundingBox("CropBox")||this.mediaBox)}get userUnit(){const e=this.pageDict.get("UserUnit");return shadow(this,"userUnit","number"==typeof e&&e>0?e:1)}get view(){const{cropBox:e,mediaBox:t}=this;if(e!==t&&!isArrayEqual(e,t)){const i=Util.intersect(e,t);if(i&&i[2]-i[0]>0&&i[3]-i[1]>0)return shadow(this,"view",i);warn("Empty /CropBox and /MediaBox intersection.")}return shadow(this,"view",t)}get rotate(){let e=this._getInheritableProperty("Rotate")||0;e%90!=0?e=0:e>=360?e%=360:e<0&&(e=(e%360+360)%360);return shadow(this,"rotate",e)}_onSubStreamError(e,t){if(!this.evaluatorOptions.ignoreErrors)throw e;warn(`getContentStream - ignoring sub-stream (${t}): "${e}".`)}getContentStream(){return this.pdfManager.ensure(this,"content").then((e=>e instanceof BaseStream?e:Array.isArray(e)?new StreamsSequenceStream(e,this._onSubStreamError.bind(this)):new NullStream))}get xfaData(){return shadow(this,"xfaData",this.xfaFactory?{bbox:this.xfaFactory.getBoundingBox(this.pageIndex)}:null)}async#V(e,t,i){const a=[];for(const s of e)if(s.id){const e=Ref.fromString(s.id);if(!e){warn(`A non-linked annotation cannot be modified: ${s.id}`);continue}if(s.deleted){t.put(e,e);if(s.popupRef){const e=Ref.fromString(s.popupRef);e&&t.put(e,e)}continue}i?.put(e);s.ref=e;a.push(this.xref.fetchAsync(e).then((e=>{e instanceof Dict&&(s.oldAnnotation=e.clone())}),(()=>{warn(`Cannot fetch \`oldAnnotation\` for: ${e}.`)})));delete s.id}await Promise.all(a)}async saveNewAnnotations(e,t,i,a,s){if(this.xfaFactory)throw new Error("XFA: Cannot save new annotations.");const r=new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions}),n=new RefSetCache,g=new RefSet;await this.#V(i,n,g);const o=this.pageDict,c=this.annotations.filter((e=>!(e instanceof Ref&&n.has(e)))),C=await AnnotationFactory.saveNewAnnotations(r,t,i,a,s);for(const{ref:e}of C.annotations)e instanceof Ref&&!g.has(e)&&c.push(e);const h=o.clone();h.set("Annots",c);s.put(this.ref,{data:h});for(const e of n)s.put(e,{data:null})}save(e,t,i,a){const s=new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions});return this._parsedAnnotations.then((function(e){const r=[];for(const n of e)r.push(n.save(s,t,i,a).catch((function(e){warn(`save - ignoring annotation data during "${t.name}" task: "${e}".`);return null})));return Promise.all(r)}))}loadResources(e){this.resourcesPromise||=this.pdfManager.ensure(this,"resources");return this.resourcesPromise.then((()=>new ObjectLoader(this.resources,e,this.xref).load()))}getOperatorList({handler:e,sink:t,task:i,intent:a,cacheKey:s,annotationStorage:r=null,modifiedIds:n=null}){const C=this.getContentStream(),E=this.loadResources(["ColorSpace","ExtGState","Font","Pattern","Properties","Shading","XObject"]),d=new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions}),f=this.xfaFactory?null:getNewAnnotationsMap(r),p=f?.get(this.pageIndex);let m=Promise.resolve(null),y=null;if(p){const e=this.pdfManager.ensureDoc("annotationGlobals");let t;const a=new Set;for(const{bitmapId:e,bitmap:t}of p)!e||t||a.has(e)||a.add(e);const{isOffscreenCanvasSupported:s}=this.evaluatorOptions;if(a.size>0){const e=p.slice();for(const[t,i]of r)t.startsWith(u)&&i.bitmap&&a.has(i.bitmapId)&&e.push(i);t=AnnotationFactory.generateImages(e,this.xref,s)}else t=AnnotationFactory.generateImages(p,this.xref,s);y=new RefSet;m=Promise.all([e,this.#V(p,y,null)]).then((([e])=>e?AnnotationFactory.printNewAnnotations(e,d,i,p,t):null))}const w=Promise.all([C,E]).then((([r])=>{const n=new OperatorList(a,t);e.send("StartRenderPage",{transparency:d.hasBlendModes(this.resources,this.nonBlendModesSet),pageIndex:this.pageIndex,cacheKey:s});return d.getOperatorList({stream:r,task:i,resources:this.resources,operatorList:n}).then((function(){return n}))}));return Promise.all([w,this._parsedAnnotations,m]).then((function([e,t,s]){if(s){t=t.filter((e=>!(e.ref&&y.has(e.ref))));for(let e=0,i=s.length;ee.ref&&isRefsEqual(e.ref,a.refToReplace)));if(r>=0){t.splice(r,1,a);s.splice(e--,1);i--}}}t=t.concat(s)}if(0===t.length||a&l){e.flush(!0);return{length:e.totalLength}}const C=!!(a&h),E=!!(a&Q),u=!!(a&g),f=!!(a&o),p=!!(a&c),m=[];for(const e of t)(u||f&&e.mustBeViewed(r,C)&&e.mustBeViewedWhenEditing(E,n)||p&&e.mustBePrinted(r))&&m.push(e.getOperatorList(d,i,a,r).catch((function(e){warn(`getOperatorList - ignoring annotation data during "${i.name}" task: "${e}".`);return{opList:null,separateForm:!1,separateCanvas:!1}})));return Promise.all(m).then((function(t){let i=!1,a=!1;for(const{opList:s,separateForm:r,separateCanvas:n}of t){e.addOpList(s);i||=r;a||=n}e.flush(!0,{form:i,canvas:a});return{length:e.totalLength}}))}))}async extractTextContent({handler:e,task:t,includeMarkedContent:i,disableNormalization:a,sink:s}){const r=this.getContentStream(),n=this.loadResources(["ExtGState","Font","Properties","XObject"]),g=this.pdfManager.ensureCatalog("lang"),[o,,c]=await Promise.all([r,n,g]);return new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions}).getTextContent({stream:o,task:t,resources:this.resources,includeMarkedContent:i,disableNormalization:a,sink:s,viewBox:this.view,lang:c})}async getStructTree(){const e=await this.pdfManager.ensureCatalog("structTreeRoot");if(!e)return null;await this._parsedAnnotations;const t=await this.pdfManager.ensure(this,"_parseStructTree",[e]);return this.pdfManager.ensure(t,"serializable")}_parseStructTree(e){const t=new StructTreePage(e,this.pageDict);t.parse(this.ref);return t}async getAnnotationsData(e,t,i){const a=await this._parsedAnnotations;if(0===a.length)return a;const s=[],r=[];let n;const C=!!(i&g),h=!!(i&o),l=!!(i&c);for(const i of a){const a=C||h&&i.viewable;(a||l&&i.printable)&&s.push(i.data);if(i.hasTextContent&&a){n||=new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions});r.push(i.extractTextContent(n,t,[-1/0,-1/0,1/0,1/0]).catch((function(e){warn(`getAnnotationsData - ignoring textContent during "${t.name}" task: "${e}".`)})))}}await Promise.all(r);return s}get annotations(){const e=this._getInheritableProperty("Annots");return shadow(this,"annotations",Array.isArray(e)?e:[])}get _parsedAnnotations(){return shadow(this,"_parsedAnnotations",this.pdfManager.ensure(this,"annotations").then((async e=>{if(0===e.length)return e;const[t,i]=await Promise.all([this.pdfManager.ensureDoc("annotationGlobals"),this.pdfManager.ensureDoc("fieldObjects")]);if(!t)return[];const a=i?.orphanFields,s=[];for(const i of e)s.push(AnnotationFactory.create(this.xref,i,t,this._localIdFactory,!1,a,this.ref).catch((function(e){warn(`_parsedAnnotations: "${e}".`);return null})));const r=[];let n,g;for(const e of await Promise.all(s))e&&(e instanceof WidgetAnnotation?(g||=[]).push(e):e instanceof PopupAnnotation?(n||=[]).push(e):r.push(e));g&&r.push(...g);n&&r.push(...n);return r})))}get jsActions(){return shadow(this,"jsActions",collectActions(this.xref,this.pageDict,pA))}}const ig=new Uint8Array([37,80,68,70,45]),ag=new Uint8Array([115,116,97,114,116,120,114,101,102]),sg=new Uint8Array([101,110,100,111,98,106]);function find(e,t,i=1024,a=!1){const s=t.length,r=e.peekBytes(i),n=r.length-s;if(n<=0)return!1;if(a){const i=s-1;let a=r.length-1;for(;a>=i;){let n=0;for(;n=s){e.pos+=a-i;return!0}a--}}else{let i=0;for(;i<=n;){let a=0;for(;a=s){e.pos+=i;return!0}i++}}return!1}class PDFDocument{constructor(e,t){if(t.length<=0)throw new InvalidPDFException("The PDF file is empty, i.e. its size is zero bytes.");this.pdfManager=e;this.stream=t;this.xref=new XRef(t,e);this._pagePromises=new Map;this._version=null;const i={font:0};this._globalIdFactory=class{static getDocId(){return`g_${e.docId}`}static createFontId(){return"f"+ ++i.font}static createObjId(){unreachable("Abstract method `createObjId` called.")}static getPageObjId(){unreachable("Abstract method `getPageObjId` called.")}}}parse(e){this.xref.parse(e);this.catalog=new Catalog(this.pdfManager,this.xref)}get linearization(){let e=null;try{e=Linearization.create(this.stream)}catch(e){if(e instanceof MissingDataException)throw e;info(e)}return shadow(this,"linearization",e)}get startXRef(){const e=this.stream;let t=0;if(this.linearization){e.reset();if(find(e,sg)){e.skip(6);let i=e.peekByte();for(;isWhiteSpace(i);){e.pos++;i=e.peekByte()}t=e.pos-e.start}}else{const i=1024,a=ag.length;let s=!1,r=e.end;for(;!s&&r>0;){r-=i-a;r<0&&(r=0);e.pos=r;s=find(e,ag,i,!0)}if(s){e.skip(9);let i;do{i=e.getByte()}while(isWhiteSpace(i));let a="";for(;i>=32&&i<=57;){a+=String.fromCharCode(i);i=e.getByte()}t=parseInt(a,10);isNaN(t)&&(t=0)}}return shadow(this,"startXRef",t)}checkHeader(){const e=this.stream;e.reset();if(!find(e,ig))return;e.moveStart();e.skip(ig.length);let t,i="";for(;(t=e.getByte())>32&&i.length<7;)i+=String.fromCharCode(t);ft.test(i)?this._version=i:warn(`Invalid PDF header version: ${i}`)}parseStartXRef(){this.xref.setStartXRef(this.startXRef)}get numPages(){let e=0;e=this.catalog.hasActualNumPages?this.catalog.numPages:this.xfaFactory?this.xfaFactory.getNumPages():this.linearization?this.linearization.numPages:this.catalog.numPages;return shadow(this,"numPages",e)}_hasOnlyDocumentSignatures(e,t=0){return!!Array.isArray(e)&&e.every((e=>{if(!((e=this.xref.fetchIfRef(e))instanceof Dict))return!1;if(e.has("Kids")){if(++t>10){warn("_hasOnlyDocumentSignatures: maximum recursion depth reached");return!1}return this._hasOnlyDocumentSignatures(e.get("Kids"),t)}const i=isName(e.get("FT"),"Sig"),a=e.get("Rect"),s=Array.isArray(a)&&a.every((e=>0===e));return i&&s}))}get _xfaStreams(){const e=this.catalog.acroForm;if(!e)return null;const t=e.get("XFA"),i={"xdp:xdp":"",template:"",datasets:"",config:"",connectionSet:"",localeSet:"",stylesheet:"","/xdp:xdp":""};if(t instanceof BaseStream&&!t.isEmpty){i["xdp:xdp"]=t;return i}if(!Array.isArray(t)||0===t.length)return null;for(let e=0,a=t.length;e0;e.hasFields=a;const s=t.get("XFA");e.hasXfa=Array.isArray(s)&&s.length>0||s instanceof BaseStream&&!s.isEmpty;const r=!!(1&t.get("SigFlags")),n=r&&this._hasOnlyDocumentSignatures(i);e.hasAcroForm=a&&!n;e.hasSignatures=r}catch(e){if(e instanceof MissingDataException)throw e;warn(`Cannot fetch form information: "${e}".`)}return shadow(this,"formInfo",e)}get documentInfo(){const e={PDFFormatVersion:this.version,Language:this.catalog.lang,EncryptFilterName:this.xref.encrypt?this.xref.encrypt.filterName:null,IsLinearized:!!this.linearization,IsAcroFormPresent:this.formInfo.hasAcroForm,IsXFAPresent:this.formInfo.hasXfa,IsCollectionPresent:!!this.catalog.collection,IsSignaturesPresent:this.formInfo.hasSignatures};let t;try{t=this.xref.trailer.get("Info")}catch(e){if(e instanceof MissingDataException)throw e;info("The document information dictionary is invalid.")}if(!(t instanceof Dict))return shadow(this,"documentInfo",e);for(const i of t.getKeys()){const a=t.get(i);switch(i){case"Title":case"Author":case"Subject":case"Keywords":case"Creator":case"Producer":case"CreationDate":case"ModDate":if("string"==typeof a){e[i]=stringToPDFString(a);continue}break;case"Trapped":if(a instanceof Name){e[i]=a;continue}break;default:let t;switch(typeof a){case"string":t=stringToPDFString(a);break;case"number":case"boolean":t=a;break;default:a instanceof Name&&(t=a)}if(void 0===t){warn(`Bad value, for custom key "${i}", in Info: ${a}.`);continue}e.Custom||(e.Custom=Object.create(null));e.Custom[i]=t;continue}warn(`Bad value, for key "${i}", in Info: ${a}.`)}return shadow(this,"documentInfo",e)}get fingerprints(){const e="\0".repeat(16);function validate(t){return"string"==typeof t&&16===t.length&&t!==e}const t=this.xref.trailer.get("ID");let i,a;if(Array.isArray(t)&&validate(t[0])){i=stringToBytes(t[0]);t[1]!==t[0]&&validate(t[1])&&(a=stringToBytes(t[1]))}else i=$n(this.stream.getByteRange(0,1024),0,1024);return shadow(this,"fingerprints",[toHexUtil(i),a?toHexUtil(a):null])}async _getLinearizationPage(e){const{catalog:t,linearization:i,xref:a}=this,s=Ref.get(i.objectNumberFirst,0);try{const e=await a.fetchAsync(s);if(e instanceof Dict){let i=e.getRaw("Type");i instanceof Ref&&(i=await a.fetchAsync(i));if(isName(i,"Page")||!e.has("Type")&&!e.has("Kids")&&e.has("Contents")){t.pageKidsCountCache.has(s)||t.pageKidsCountCache.put(s,1);t.pageIndexCache.has(s)||t.pageIndexCache.put(s,0);return[e,s]}}throw new FormatError("The Linearization dictionary doesn't point to a valid Page dictionary.")}catch(i){warn(`_getLinearizationPage: "${i.message}".`);return t.getPageDict(e)}}getPage(e){const t=this._pagePromises.get(e);if(t)return t;const{catalog:i,linearization:a,xfaFactory:s}=this;let r;r=s?Promise.resolve([Dict.empty,null]):a?.pageFirst===e?this._getLinearizationPage(e):i.getPageDict(e);r=r.then((([t,a])=>new Page({pdfManager:this.pdfManager,xref:this.xref,pageIndex:e,pageDict:t,ref:a,globalIdFactory:this._globalIdFactory,fontCache:i.fontCache,builtInCMapCache:i.builtInCMapCache,standardFontDataCache:i.standardFontDataCache,globalImageCache:i.globalImageCache,systemFontCache:i.systemFontCache,nonBlendModesSet:i.nonBlendModesSet,xfaFactory:s})));this._pagePromises.set(e,r);return r}async checkFirstPage(e=!1){if(!e)try{await this.getPage(0)}catch(e){if(e instanceof XRefEntryException){this._pagePromises.delete(0);await this.cleanup();throw new XRefParseException}}}async checkLastPage(e=!1){const{catalog:t,pdfManager:i}=this;t.setActualNumPages();let a;try{await Promise.all([i.ensureDoc("xfaFactory"),i.ensureDoc("linearization"),i.ensureCatalog("numPages")]);if(this.xfaFactory)return;a=this.linearization?this.linearization.numPages:t.numPages;if(!Number.isInteger(a))throw new FormatError("Page count is not an integer.");if(a<=1)return;await this.getPage(a-1)}catch(s){this._pagePromises.delete(a-1);await this.cleanup();if(s instanceof XRefEntryException&&!e)throw new XRefParseException;warn(`checkLastPage - invalid /Pages tree /Count: ${a}.`);let r;try{r=await t.getAllPageDicts(e)}catch(i){if(i instanceof XRefEntryException&&!e)throw new XRefParseException;t.setActualNumPages(1);return}for(const[e,[a,s]]of r){let r;if(a instanceof Error){r=Promise.reject(a);r.catch((()=>{}))}else r=Promise.resolve(new Page({pdfManager:i,xref:this.xref,pageIndex:e,pageDict:a,ref:s,globalIdFactory:this._globalIdFactory,fontCache:t.fontCache,builtInCMapCache:t.builtInCMapCache,standardFontDataCache:t.standardFontDataCache,globalImageCache:t.globalImageCache,systemFontCache:t.systemFontCache,nonBlendModesSet:t.nonBlendModesSet,xfaFactory:null}));this._pagePromises.set(e,r)}t.setActualNumPages(r.size)}}fontFallback(e,t){return this.catalog.fontFallback(e,t)}async cleanup(e=!1){return this.catalog?this.catalog.cleanup(e):clearGlobalCaches()}async#z(e,t,i,a,s,r,n){const{xref:g}=this;if(!(i instanceof Ref)||r.has(i))return;r.put(i);const o=await g.fetchAsync(i);if(!(o instanceof Dict))return;if(o.has("T")){const t=stringToPDFString(await o.getAsync("T"));e=""===e?t:`${e}.${t}`}else{let i=o;for(;;){i=i.getRaw("Parent")||t;if(i instanceof Ref){if(r.has(i))break;i=await g.fetchAsync(i)}if(!(i instanceof Dict))break;if(i.has("T")){const t=stringToPDFString(await i.getAsync("T"));e=""===e?t:`${e}.${t}`;break}}}t&&!o.has("Parent")&&isName(o.get("Subtype"),"Widget")&&n.put(i,t);a.has(e)||a.set(e,[]);a.get(e).push(AnnotationFactory.create(g,i,s,null,!0,n,null).then((e=>e?.getFieldObject())).catch((function(e){warn(`#collectFieldObjects: "${e}".`);return null})));if(!o.has("Kids"))return;const c=await o.getAsync("Kids");if(Array.isArray(c))for(const t of c)await this.#z(e,i,t,a,s,r,n)}get fieldObjects(){return shadow(this,"fieldObjects",this.pdfManager.ensureDoc("formInfo").then((async e=>{if(!e.hasFields)return null;const[t,i]=await Promise.all([this.pdfManager.ensureDoc("annotationGlobals"),this.pdfManager.ensureCatalog("acroForm")]);if(!t)return null;const a=new RefSet,s=Object.create(null),r=new Map,n=new RefSetCache;for(const e of await i.getAsync("Fields"))await this.#z("",null,e,r,t,a,n);const g=[];for(const[e,t]of r)g.push(Promise.all(t).then((t=>{(t=t.filter((e=>!!e))).length>0&&(s[e]=t)})));await Promise.all(g);return{allFields:s,orphanFields:n}})))}get hasJSActions(){return shadow(this,"hasJSActions",this.pdfManager.ensureDoc("_parseHasJSActions"))}async _parseHasJSActions(){const[e,t]=await Promise.all([this.pdfManager.ensureCatalog("jsActions"),this.pdfManager.ensureDoc("fieldObjects")]);return!!e||!!t&&Object.values(t.allFields).some((e=>e.some((e=>null!==e.actions))))}get calculationOrderIds(){const e=this.catalog.acroForm?.get("CO");if(!Array.isArray(e)||0===e.length)return shadow(this,"calculationOrderIds",null);const t=[];for(const i of e)i instanceof Ref&&t.push(i.toString());return shadow(this,"calculationOrderIds",t.length?t:null)}get annotationGlobals(){return shadow(this,"annotationGlobals",AnnotationFactory.createGlobals(this.pdfManager))}}class BasePdfManager{constructor(e){this._docBaseUrl=function parseDocBaseUrl(e){if(e){const t=createValidAbsoluteUrl(e);if(t)return t.href;warn(`Invalid absolute docBaseUrl: "${e}".`)}return null}(e.docBaseUrl);this._docId=e.docId;this._password=e.password;this.enableXfa=e.enableXfa;e.evaluatorOptions.isOffscreenCanvasSupported&&=FeatureTest.isOffscreenCanvasSupported;e.evaluatorOptions.isImageDecoderSupported&&=FeatureTest.isImageDecoderSupported;this.evaluatorOptions=Object.freeze(e.evaluatorOptions)}get docId(){return this._docId}get password(){return this._password}get docBaseUrl(){return this._docBaseUrl}get catalog(){return this.pdfDocument.catalog}ensureDoc(e,t){return this.ensure(this.pdfDocument,e,t)}ensureXRef(e,t){return this.ensure(this.pdfDocument.xref,e,t)}ensureCatalog(e,t){return this.ensure(this.pdfDocument.catalog,e,t)}getPage(e){return this.pdfDocument.getPage(e)}fontFallback(e,t){return this.pdfDocument.fontFallback(e,t)}loadXfaFonts(e,t){return this.pdfDocument.loadXfaFonts(e,t)}loadXfaImages(){return this.pdfDocument.loadXfaImages()}serializeXfaData(e){return this.pdfDocument.serializeXfaData(e)}cleanup(e=!1){return this.pdfDocument.cleanup(e)}async ensure(e,t,i){unreachable("Abstract method `ensure` called")}requestRange(e,t){unreachable("Abstract method `requestRange` called")}requestLoadedStream(e=!1){unreachable("Abstract method `requestLoadedStream` called")}sendProgressiveData(e){unreachable("Abstract method `sendProgressiveData` called")}updatePassword(e){this._password=e}terminate(e){unreachable("Abstract method `terminate` called")}}class LocalPdfManager extends BasePdfManager{constructor(e){super(e);const t=new Stream(e.source);this.pdfDocument=new PDFDocument(this,t);this._loadedStreamPromise=Promise.resolve(t)}async ensure(e,t,i){const a=e[t];return"function"==typeof a?a.apply(e,i):a}requestRange(e,t){return Promise.resolve()}requestLoadedStream(e=!1){return this._loadedStreamPromise}terminate(e){}}class NetworkPdfManager extends BasePdfManager{constructor(e){super(e);this.streamManager=new ChunkedStreamManager(e.source,{msgHandler:e.handler,length:e.length,disableAutoFetch:e.disableAutoFetch,rangeChunkSize:e.rangeChunkSize});this.pdfDocument=new PDFDocument(this,this.streamManager.getStream())}async ensure(e,t,i){try{const a=e[t];return"function"==typeof a?a.apply(e,i):a}catch(a){if(!(a instanceof MissingDataException))throw a;await this.requestRange(a.begin,a.end);return this.ensure(e,t,i)}}requestRange(e,t){return this.streamManager.requestRange(e,t)}requestLoadedStream(e=!1){return this.streamManager.requestAllChunks(e)}sendProgressiveData(e){this.streamManager.onReceiveData({chunk:e})}terminate(e){this.streamManager.abort(e)}}const rg=1,ng=2,gg=1,og=2,Ig=3,cg=4,Cg=5,hg=6,lg=7,Bg=8;function onFn(){}function wrapReason(e){if(e instanceof AbortException||e instanceof InvalidPDFException||e instanceof MissingPDFException||e instanceof PasswordException||e instanceof UnexpectedResponseException||e instanceof UnknownErrorException)return e;e instanceof Error||"object"==typeof e&&null!==e||unreachable('wrapReason: Expected "reason" to be a (possibly cloned) Error.');switch(e.name){case"AbortException":return new AbortException(e.message);case"InvalidPDFException":return new InvalidPDFException(e.message);case"MissingPDFException":return new MissingPDFException(e.message);case"PasswordException":return new PasswordException(e.message,e.code);case"UnexpectedResponseException":return new UnexpectedResponseException(e.message,e.status);case"UnknownErrorException":return new UnknownErrorException(e.message,e.details)}return new UnknownErrorException(e.message,e.toString())}class MessageHandler{#_=new AbortController;constructor(e,t,i){this.sourceName=e;this.targetName=t;this.comObj=i;this.callbackId=1;this.streamId=1;this.streamSinks=Object.create(null);this.streamControllers=Object.create(null);this.callbackCapabilities=Object.create(null);this.actionHandler=Object.create(null);i.addEventListener("message",this.#$.bind(this),{signal:this.#_.signal})}#$({data:e}){if(e.targetName!==this.sourceName)return;if(e.stream){this.#AA(e);return}if(e.callback){const t=e.callbackId,i=this.callbackCapabilities[t];if(!i)throw new Error(`Cannot resolve callback ${t}`);delete this.callbackCapabilities[t];if(e.callback===rg)i.resolve(e.data);else{if(e.callback!==ng)throw new Error("Unexpected callback case");i.reject(wrapReason(e.reason))}return}const t=this.actionHandler[e.action];if(!t)throw new Error(`Unknown action from worker: ${e.action}`);if(e.callbackId){const i=this.sourceName,a=e.sourceName,s=this.comObj;Promise.try(t,e.data).then((function(t){s.postMessage({sourceName:i,targetName:a,callback:rg,callbackId:e.callbackId,data:t})}),(function(t){s.postMessage({sourceName:i,targetName:a,callback:ng,callbackId:e.callbackId,reason:wrapReason(t)})}))}else e.streamId?this.#eA(e):t(e.data)}on(e,t){const i=this.actionHandler;if(i[e])throw new Error(`There is already an actionName called "${e}"`);i[e]=t}send(e,t,i){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,data:t},i)}sendWithPromise(e,t,i){const a=this.callbackId++,s=Promise.withResolvers();this.callbackCapabilities[a]=s;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,callbackId:a,data:t},i)}catch(e){s.reject(e)}return s.promise}sendWithStream(e,t,i,a){const s=this.streamId++,r=this.sourceName,n=this.targetName,g=this.comObj;return new ReadableStream({start:i=>{const o=Promise.withResolvers();this.streamControllers[s]={controller:i,startCall:o,pullCall:null,cancelCall:null,isClosed:!1};g.postMessage({sourceName:r,targetName:n,action:e,streamId:s,data:t,desiredSize:i.desiredSize},a);return o.promise},pull:e=>{const t=Promise.withResolvers();this.streamControllers[s].pullCall=t;g.postMessage({sourceName:r,targetName:n,stream:hg,streamId:s,desiredSize:e.desiredSize});return t.promise},cancel:e=>{assert(e instanceof Error,"cancel must have a valid reason");const t=Promise.withResolvers();this.streamControllers[s].cancelCall=t;this.streamControllers[s].isClosed=!0;g.postMessage({sourceName:r,targetName:n,stream:gg,streamId:s,reason:wrapReason(e)});return t.promise}},i)}#eA(e){const t=e.streamId,i=this.sourceName,a=e.sourceName,s=this.comObj,r=this,n=this.actionHandler[e.action],g={enqueue(e,r=1,n){if(this.isCancelled)return;const g=this.desiredSize;this.desiredSize-=r;if(g>0&&this.desiredSize<=0){this.sinkCapability=Promise.withResolvers();this.ready=this.sinkCapability.promise}s.postMessage({sourceName:i,targetName:a,stream:cg,streamId:t,chunk:e},n)},close(){if(!this.isCancelled){this.isCancelled=!0;s.postMessage({sourceName:i,targetName:a,stream:Ig,streamId:t});delete r.streamSinks[t]}},error(e){assert(e instanceof Error,"error must have a valid reason");if(!this.isCancelled){this.isCancelled=!0;s.postMessage({sourceName:i,targetName:a,stream:Cg,streamId:t,reason:wrapReason(e)})}},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:e.desiredSize,ready:null};g.sinkCapability.resolve();g.ready=g.sinkCapability.promise;this.streamSinks[t]=g;Promise.try(n,e.data,g).then((function(){s.postMessage({sourceName:i,targetName:a,stream:Bg,streamId:t,success:!0})}),(function(e){s.postMessage({sourceName:i,targetName:a,stream:Bg,streamId:t,reason:wrapReason(e)})}))}#AA(e){const t=e.streamId,i=this.sourceName,a=e.sourceName,s=this.comObj,r=this.streamControllers[t],n=this.streamSinks[t];switch(e.stream){case Bg:e.success?r.startCall.resolve():r.startCall.reject(wrapReason(e.reason));break;case lg:e.success?r.pullCall.resolve():r.pullCall.reject(wrapReason(e.reason));break;case hg:if(!n){s.postMessage({sourceName:i,targetName:a,stream:lg,streamId:t,success:!0});break}n.desiredSize<=0&&e.desiredSize>0&&n.sinkCapability.resolve();n.desiredSize=e.desiredSize;Promise.try(n.onPull||onFn).then((function(){s.postMessage({sourceName:i,targetName:a,stream:lg,streamId:t,success:!0})}),(function(e){s.postMessage({sourceName:i,targetName:a,stream:lg,streamId:t,reason:wrapReason(e)})}));break;case cg:assert(r,"enqueue should have stream controller");if(r.isClosed)break;r.controller.enqueue(e.chunk);break;case Ig:assert(r,"close should have stream controller");if(r.isClosed)break;r.isClosed=!0;r.controller.close();this.#tA(r,t);break;case Cg:assert(r,"error should have stream controller");r.controller.error(wrapReason(e.reason));this.#tA(r,t);break;case og:e.success?r.cancelCall.resolve():r.cancelCall.reject(wrapReason(e.reason));this.#tA(r,t);break;case gg:if(!n)break;const g=wrapReason(e.reason);Promise.try(n.onCancel||onFn,g).then((function(){s.postMessage({sourceName:i,targetName:a,stream:og,streamId:t,success:!0})}),(function(e){s.postMessage({sourceName:i,targetName:a,stream:og,streamId:t,reason:wrapReason(e)})}));n.sinkCapability.reject(g);n.isCancelled=!0;delete this.streamSinks[t];break;default:throw new Error("Unexpected stream case")}}async#tA(e,t){await Promise.allSettled([e.startCall?.promise,e.pullCall?.promise,e.cancelCall?.promise]);delete this.streamControllers[t]}destroy(){this.#_?.abort();this.#_=null}}async function writeObject(e,t,i,{encrypt:a=null}){const s=a?.createCipherTransform(e.num,e.gen);i.push(`${e.num} ${e.gen} obj\n`);t instanceof Dict?await writeDict(t,i,s):t instanceof BaseStream?await writeStream(t,i,s):(Array.isArray(t)||ArrayBuffer.isView(t))&&await writeArray(t,i,s);i.push("\nendobj\n")}async function writeDict(e,t,i){t.push("<<");for(const a of e.getKeys()){t.push(` /${escapePDFName(a)} `);await writeValue(e.getRaw(a),t,i)}t.push(">>")}async function writeStream(e,t,i){let a=e.getBytes();const{dict:s}=e,[r,n]=await Promise.all([s.getAsync("Filter"),s.getAsync("DecodeParms")]),g=isName(Array.isArray(r)?await s.xref.fetchIfRefAsync(r[0]):r,"FlateDecode");if(a.length>=256||g)try{const e=new CompressionStream("deflate"),t=e.writable.getWriter();await t.ready;t.write(a).then((async()=>{await t.ready;await t.close()})).catch((()=>{}));const i=await new Response(e.readable).arrayBuffer();a=new Uint8Array(i);let o,c;if(r){if(!g){o=Array.isArray(r)?[Name.get("FlateDecode"),...r]:[Name.get("FlateDecode"),r];n&&(c=Array.isArray(n)?[null,...n]:[null,n])}}else o=Name.get("FlateDecode");o&&s.set("Filter",o);c&&s.set("DecodeParms",c)}catch(e){info(`writeStream - cannot compress data: "${e}".`)}let o=bytesToString(a);i&&(o=i.encryptString(o));s.set("Length",o.length);await writeDict(s,t,i);t.push(" stream\n",o,"\nendstream")}async function writeArray(e,t,i){t.push("[");let a=!0;for(const s of e){a?a=!1:t.push(" ");await writeValue(s,t,i)}t.push("]")}async function writeValue(e,t,i){if(e instanceof Name)t.push(`/${escapePDFName(e.name)}`);else if(e instanceof Ref)t.push(`${e.num} ${e.gen} R`);else if(Array.isArray(e)||ArrayBuffer.isView(e))await writeArray(e,t,i);else if("string"==typeof e){i&&(e=i.encryptString(e));t.push(`(${escapeString(e)})`)}else"number"==typeof e?t.push(numberToString(e)):"boolean"==typeof e?t.push(e.toString()):e instanceof Dict?await writeDict(e,t,i):e instanceof BaseStream?await writeStream(e,t,i):null===e?t.push("null"):warn(`Unhandled value in writer: ${typeof e}, please file a bug.`)}function writeInt(e,t,i,a){for(let s=t+i-1;s>i-1;s--){a[s]=255&e;e>>=8}return i+t}function writeString(e,t,i){for(let a=0,s=e.length;a1&&(r=i.documentElement.searchNode([s.at(-1)],0));r?r.childNodes=Array.isArray(a)?a.map((e=>new SimpleDOMNode("value",e))):[new SimpleDOMNode("#text",a)]:warn(`Node not found for path: ${t}`)}const a=[];i.documentElement.dump(a);return a.join("")}(a.fetchIfRef(t).getString(),i)}const s=new StringStream(e);s.dict=new Dict(a);s.dict.set("Type",Name.get("EmbeddedFile"));i.put(t,{data:s})}function getIndexes(e){const t=[];for(const{ref:i}of e)i.num===t.at(-2)+t.at(-1)?t[t.length-1]+=1:t.push(i.num,1);return t}function computeIDs(e,t,i){if(Array.isArray(t.fileIds)&&t.fileIds.length>0){const a=function computeMD5(e,t){const i=Math.floor(Date.now()/1e3),a=t.filename||"",s=[i.toString(),a,e.toString()];let r=s.reduce(((e,t)=>e+t.length),0);for(const e of Object.values(t.info)){s.push(e);r+=e.length}const n=new Uint8Array(r);let g=0;for(const e of s){writeString(e,g,n);g+=e.length}return bytesToString($n(n))}(e,t);i.set("ID",[t.fileIds[0],a])}}async function incrementalUpdate({originalData:e,xrefInfo:t,changes:i,xref:a=null,hasXfa:s=!1,xfaDatasetsRef:r=null,hasXfaDatasetsEntry:n=!1,needAppearances:g,acroFormRef:o=null,acroForm:c=null,xfaData:C=null,useXrefStream:h=!1}){await async function updateAcroform({xref:e,acroForm:t,acroFormRef:i,hasXfa:a,hasXfaDatasetsEntry:s,xfaDatasetsRef:r,needAppearances:n,changes:g}){!a||s||r||warn("XFA - Cannot save it");if(!n&&(!a||!r||s))return;const o=t.clone();if(a&&!s){const e=t.get("XFA").slice();e.splice(2,0,"datasets");e.splice(3,0,r);o.set("XFA",e)}n&&o.set("NeedAppearances",!0);g.put(i,{data:o})}({xref:a,acroForm:c,acroFormRef:o,hasXfa:s,hasXfaDatasetsEntry:n,xfaDatasetsRef:r,needAppearances:g,changes:i});s&&updateXFA({xfaData:C,xfaDatasetsRef:r,changes:i,xref:a});const l=function getTrailerDict(e,t,i){const a=new Dict(null);a.set("Prev",e.startXRef);const s=e.newRef;if(i){t.put(s,{data:""});a.set("Size",s.num+1);a.set("Type",Name.get("XRef"))}else a.set("Size",s.num);null!==e.rootRef&&a.set("Root",e.rootRef);null!==e.infoRef&&a.set("Info",e.infoRef);null!==e.encryptRef&&a.set("Encrypt",e.encryptRef);return a}(t,i,h),Q=[],E=await async function writeChanges(e,t,i=[]){const a=[];for(const[s,{data:r}]of e.items())if(null!==r&&"string"!=typeof r){await writeObject(s,r,i,t);a.push({ref:s,data:i.join("")});i.length=0}else a.push({ref:s,data:r});return a.sort(((e,t)=>e.ref.num-t.ref.num))}(i,a,Q);let u=e.length;const d=e.at(-1);if(10!==d&&13!==d){Q.push("\n");u+=1}for(const{data:e}of E)null!==e&&Q.push(e);await(h?async function getXRefStreamTable(e,t,i,a,s){const r=[];let n=0,g=0;for(const{ref:e,data:a}of i){let i;n=Math.max(n,t);if(null!==a){i=Math.min(e.gen,65535);r.push([1,t,i]);t+=a.length}else{i=Math.min(e.gen+1,65535);r.push([0,0,i])}g=Math.max(g,i)}a.set("Index",getIndexes(i));const o=[1,getSizeInBytes(n),getSizeInBytes(g)];a.set("W",o);computeIDs(t,e,a);const c=o.reduce(((e,t)=>e+t),0),C=new Uint8Array(c*r.length),h=new Stream(C);h.dict=a;let l=0;for(const[e,t,i]of r){l=writeInt(e,o[0],l,C);l=writeInt(t,o[1],l,C);l=writeInt(i,o[2],l,C)}await writeObject(e.newRef,h,s,{});s.push("startxref\n",t.toString(),"\n%%EOF\n")}(t,u,E,l,Q):async function getXRefTable(e,t,i,a,s){s.push("xref\n");const r=getIndexes(i);let n=0;for(const{ref:e,data:a}of i){if(e.num===r[n]){s.push(`${r[n]} ${r[n+1]}\n`);n+=2}if(null!==a){s.push(`${t.toString().padStart(10,"0")} ${Math.min(e.gen,65535).toString().padStart(5,"0")} n\r\n`);t+=a.length}else s.push(`0000000000 ${Math.min(e.gen+1,65535).toString().padStart(5,"0")} f\r\n`)}computeIDs(t,e,a);s.push("trailer\n");await writeDict(a,s);s.push("\nstartxref\n",t.toString(),"\n%%EOF\n")}(t,u,E,l,Q));const f=Q.reduce(((e,t)=>e+t.length),e.length),p=new Uint8Array(f);p.set(e);let m=e.length;for(const e of Q){writeString(e,m,p);m+=e.length}return p}class PDFWorkerStream{constructor(e){this._msgHandler=e;this._contentLength=null;this._fullRequestReader=null;this._rangeRequestReaders=[]}getFullReader(){assert(!this._fullRequestReader,"PDFWorkerStream.getFullReader can only be called once.");this._fullRequestReader=new PDFWorkerStreamReader(this._msgHandler);return this._fullRequestReader}getRangeReader(e,t){const i=new PDFWorkerStreamRangeReader(e,t,this._msgHandler);this._rangeRequestReaders.push(i);return i}cancelAllRequests(e){this._fullRequestReader?.cancel(e);for(const t of this._rangeRequestReaders.slice(0))t.cancel(e)}}class PDFWorkerStreamReader{constructor(e){this._msgHandler=e;this.onProgress=null;this._contentLength=null;this._isRangeSupported=!1;this._isStreamingSupported=!1;const t=this._msgHandler.sendWithStream("GetReader");this._reader=t.getReader();this._headersReady=this._msgHandler.sendWithPromise("ReaderHeadersReady").then((e=>{this._isStreamingSupported=e.isStreamingSupported;this._isRangeSupported=e.isRangeSupported;this._contentLength=e.contentLength}))}get headersReady(){return this._headersReady}get contentLength(){return this._contentLength}get isStreamingSupported(){return this._isStreamingSupported}get isRangeSupported(){return this._isRangeSupported}async read(){const{value:e,done:t}=await this._reader.read();return t?{value:void 0,done:!0}:{value:e.buffer,done:!1}}cancel(e){this._reader.cancel(e)}}class PDFWorkerStreamRangeReader{constructor(e,t,i){this._msgHandler=i;this.onProgress=null;const a=this._msgHandler.sendWithStream("GetRangeReader",{begin:e,end:t});this._reader=a.getReader()}get isStreamingSupported(){return!1}async read(){const{value:e,done:t}=await this._reader.read();return t?{value:void 0,done:!0}:{value:e.buffer,done:!1}}cancel(e){this._reader.cancel(e)}}class WorkerTask{constructor(e){this.name=e;this.terminated=!1;this._capability=Promise.withResolvers()}get finished(){return this._capability.promise}finish(){this._capability.resolve()}terminate(){this.terminated=!0}ensureNotTerminated(){if(this.terminated)throw new Error("Worker task was terminated")}}class WorkerMessageHandler{static{"undefined"==typeof window&&!t&&"undefined"!=typeof self&&"function"==typeof self.postMessage&&"onmessage"in self&&this.initializeFromPort(self)}static setup(e,t){let i=!1;e.on("test",(t=>{if(!i){i=!0;e.send("test",t instanceof Uint8Array)}}));e.on("configure",(e=>{!function setVerbosityLevel(e){Number.isInteger(e)&&(gt=e)}(e.verbosity)}));e.on("GetDocRequest",(e=>this.createDocumentHandler(e,t)))}static createDocumentHandler(e,t){let i,a=!1,s=null;const r=new Set,n=getVerbosityLevel(),{docId:g,apiVersion:o}=e,c="4.10.38";if(o!==c)throw new Error(`The API version "${o}" does not match the Worker version "${c}".`);const C=[];for(const e in[])C.push(e);if(C.length)throw new Error("The `Array.prototype` contains unexpected enumerable properties: "+C.join(", ")+"; thus breaking e.g. `for...in` iteration of `Array`s.");const h=g+"_worker";let l=new MessageHandler(h,g,t);function ensureNotTerminated(){if(a)throw new Error("Worker was terminated")}function startWorkerTask(e){r.add(e)}function finishWorkerTask(e){e.finish();r.delete(e)}async function loadDocument(e){await i.ensureDoc("checkHeader");await i.ensureDoc("parseStartXRef");await i.ensureDoc("parse",[e]);await i.ensureDoc("checkFirstPage",[e]);await i.ensureDoc("checkLastPage",[e]);const t=await i.ensureDoc("isPureXfa");if(t){const e=new WorkerTask("loadXfaFonts");startWorkerTask(e);await Promise.all([i.loadXfaFonts(l,e).catch((e=>{})).then((()=>finishWorkerTask(e))),i.loadXfaImages()])}const[a,s]=await Promise.all([i.ensureDoc("numPages"),i.ensureDoc("fingerprints")]);return{numPages:a,fingerprints:s,htmlForXfa:t?await i.ensureDoc("htmlForXfa"):null}}function setupDoc(e){function onSuccess(e){ensureNotTerminated();l.send("GetDoc",{pdfInfo:e})}function onFailure(e){ensureNotTerminated();if(e instanceof PasswordException){const t=new WorkerTask(`PasswordException: response ${e.code}`);startWorkerTask(t);l.sendWithPromise("PasswordRequest",e).then((function({password:e}){finishWorkerTask(t);i.updatePassword(e);pdfManagerReady()})).catch((function(){finishWorkerTask(t);l.send("DocException",e)}))}else l.send("DocException",wrapReason(e))}function pdfManagerReady(){ensureNotTerminated();loadDocument(!1).then(onSuccess,(function(e){ensureNotTerminated();e instanceof XRefParseException?i.requestLoadedStream().then((function(){ensureNotTerminated();loadDocument(!0).then(onSuccess,onFailure)})):onFailure(e)}))}ensureNotTerminated();(async function getPdfManager({data:e,password:t,disableAutoFetch:i,rangeChunkSize:a,length:r,docBaseUrl:n,enableXfa:o,evaluatorOptions:c}){const C={source:null,disableAutoFetch:i,docBaseUrl:n,docId:g,enableXfa:o,evaluatorOptions:c,handler:l,length:r,password:t,rangeChunkSize:a};if(e){C.source=e;return new LocalPdfManager(C)}const h=new PDFWorkerStream(l),Q=h.getFullReader(),E=Promise.withResolvers();let u,d=[],f=0;Q.headersReady.then((function(){if(Q.isRangeSupported){C.source=h;C.length=Q.contentLength;C.disableAutoFetch||=Q.isStreamingSupported;u=new NetworkPdfManager(C);for(const e of d)u.sendProgressiveData(e);d=[];E.resolve(u);s=null}})).catch((function(e){E.reject(e);s=null}));new Promise((function(e,t){const readChunk=function({value:e,done:i}){try{ensureNotTerminated();if(i){if(!u){const e=arrayBuffersToBytes(d);d=[];r&&e.length!==r&&warn("reported HTTP length is different from actual");C.source=e;u=new LocalPdfManager(C);E.resolve(u)}s=null;return}f+=e.byteLength;Q.isStreamingSupported||l.send("DocProgress",{loaded:f,total:Math.max(f,Q.contentLength||0)});u?u.sendProgressiveData(e):d.push(e);Q.read().then(readChunk,t)}catch(e){t(e)}};Q.read().then(readChunk,t)})).catch((function(e){E.reject(e);s=null}));s=e=>{h.cancelAllRequests(e)};return E.promise})(e).then((function(e){if(a){e.terminate(new AbortException("Worker was terminated."));throw new Error("Worker was terminated")}i=e;i.requestLoadedStream(!0).then((e=>{l.send("DataLoaded",{length:e.bytes.byteLength})}))})).then(pdfManagerReady,onFailure)}l.on("GetPage",(function(e){return i.getPage(e.pageIndex).then((function(e){return Promise.all([i.ensure(e,"rotate"),i.ensure(e,"ref"),i.ensure(e,"userUnit"),i.ensure(e,"view")]).then((function([e,t,i,a]){return{rotate:e,ref:t,refStr:t?.toString()??null,userUnit:i,view:a}}))}))}));l.on("GetPageIndex",(function(e){const t=Ref.get(e.num,e.gen);return i.ensureCatalog("getPageIndex",[t])}));l.on("GetDestinations",(function(e){return i.ensureCatalog("destinations")}));l.on("GetDestination",(function(e){return i.ensureCatalog("getDestination",[e.id])}));l.on("GetPageLabels",(function(e){return i.ensureCatalog("pageLabels")}));l.on("GetPageLayout",(function(e){return i.ensureCatalog("pageLayout")}));l.on("GetPageMode",(function(e){return i.ensureCatalog("pageMode")}));l.on("GetViewerPreferences",(function(e){return i.ensureCatalog("viewerPreferences")}));l.on("GetOpenAction",(function(e){return i.ensureCatalog("openAction")}));l.on("GetAttachments",(function(e){return i.ensureCatalog("attachments")}));l.on("GetDocJSActions",(function(e){return i.ensureCatalog("jsActions")}));l.on("GetPageJSActions",(function({pageIndex:e}){return i.getPage(e).then((function(e){return i.ensure(e,"jsActions")}))}));l.on("GetOutline",(function(e){return i.ensureCatalog("documentOutline")}));l.on("GetOptionalContentConfig",(function(e){return i.ensureCatalog("optionalContentConfig")}));l.on("GetPermissions",(function(e){return i.ensureCatalog("permissions")}));l.on("GetMetadata",(function(e){return Promise.all([i.ensureDoc("documentInfo"),i.ensureCatalog("metadata")])}));l.on("GetMarkInfo",(function(e){return i.ensureCatalog("markInfo")}));l.on("GetData",(function(e){return i.requestLoadedStream().then((function(e){return e.bytes}))}));l.on("GetAnnotations",(function({pageIndex:e,intent:t}){return i.getPage(e).then((function(i){const a=new WorkerTask(`GetAnnotations: page ${e}`);startWorkerTask(a);return i.getAnnotationsData(l,a,t).then((e=>{finishWorkerTask(a);return e}),(e=>{finishWorkerTask(a);throw e}))}))}));l.on("GetFieldObjects",(function(e){return i.ensureDoc("fieldObjects").then((e=>e?.allFields||null))}));l.on("HasJSActions",(function(e){return i.ensureDoc("hasJSActions")}));l.on("GetCalculationOrderIds",(function(e){return i.ensureDoc("calculationOrderIds")}));l.on("SaveDocument",(async function({isPureXfa:e,numPages:t,annotationStorage:a,filename:s}){const r=[i.requestLoadedStream(),i.ensureCatalog("acroForm"),i.ensureCatalog("acroFormRef"),i.ensureDoc("startXRef"),i.ensureDoc("xref"),i.ensureDoc("linearization"),i.ensureCatalog("structTreeRoot")],n=new RefSetCache,g=[],o=e?null:getNewAnnotationsMap(a),[c,C,h,Q,E,u,d]=await Promise.all(r),f=E.trailer.getRaw("Root")||null;let p;if(o){d?await d.canUpdateStructTree({pdfManager:i,xref:E,newAnnotationsByPage:o})&&(p=d):await StructTreeRoot.canCreateStructureTree({catalogRef:f,pdfManager:i,newAnnotationsByPage:o})&&(p=null);const e=AnnotationFactory.generateImages(a.values(),E,i.evaluatorOptions.isOffscreenCanvasSupported),t=void 0===p?g:[];for(const[a,s]of o)t.push(i.getPage(a).then((t=>{const i=new WorkerTask(`Save (editor): page ${a}`);startWorkerTask(i);return t.saveNewAnnotations(l,i,s,e,n).finally((function(){finishWorkerTask(i)}))})));null===p?g.push(Promise.all(t).then((async()=>{await StructTreeRoot.createStructureTree({newAnnotationsByPage:o,xref:E,catalogRef:f,pdfManager:i,changes:n})}))):p&&g.push(Promise.all(t).then((async()=>{await p.updateStructureTree({newAnnotationsByPage:o,pdfManager:i,changes:n})})))}if(e)g.push(i.serializeXfaData(a));else for(let e=0;ee.needAppearances)),D=C instanceof Dict&&C.get("XFA")||null;let b=null,F=!1;if(Array.isArray(D)){for(let e=0,t=D.length;e{E.resetNewTemporaryRef()}))}));l.on("GetOperatorList",(function(e,t){const a=e.pageIndex;i.getPage(a).then((function(i){const s=new WorkerTask(`GetOperatorList: page ${a}`);startWorkerTask(s);const r=n>=yA?Date.now():0;i.getOperatorList({handler:l,sink:t,task:s,intent:e.intent,cacheKey:e.cacheKey,annotationStorage:e.annotationStorage,modifiedIds:e.modifiedIds}).then((function(e){finishWorkerTask(s);r&&info(`page=${a+1} - getOperatorList: time=${Date.now()-r}ms, len=${e.length}`);t.close()}),(function(e){finishWorkerTask(s);s.terminated||t.error(e)}))}))}));l.on("GetTextContent",(function(e,t){const{pageIndex:a,includeMarkedContent:s,disableNormalization:r}=e;i.getPage(a).then((function(e){const i=new WorkerTask("GetTextContent: page "+a);startWorkerTask(i);const g=n>=yA?Date.now():0;e.extractTextContent({handler:l,task:i,sink:t,includeMarkedContent:s,disableNormalization:r}).then((function(){finishWorkerTask(i);g&&info(`page=${a+1} - getTextContent: time=`+(Date.now()-g)+"ms");t.close()}),(function(e){finishWorkerTask(i);i.terminated||t.error(e)}))}))}));l.on("GetStructTree",(function(e){return i.getPage(e.pageIndex).then((function(e){return i.ensure(e,"getStructTree")}))}));l.on("FontFallback",(function(e){return i.fontFallback(e.id,l)}));l.on("Cleanup",(function(e){return i.cleanup(!0)}));l.on("Terminate",(function(e){a=!0;const t=[];if(i){i.terminate(new AbortException("Worker was terminated."));const e=i.cleanup();t.push(e);i=null}else clearGlobalCaches();s?.(new AbortException("Worker was terminated."));for(const e of r){t.push(e.finished);e.terminate()}return Promise.all(t).then((function(){l.destroy();l=null}))}));l.on("Ready",(function(t){setupDoc(e);e=null}));return h}static initializeFromPort(e){const t=new MessageHandler("worker","main",e);this.setup(t,e);t.send("ready",null)}}var Qg=__webpack_exports__.WorkerMessageHandler;export{Qg as WorkerMessageHandler}; \ No newline at end of file diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/web/images/loading-icon.gif b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/web/images/loading-icon.gif deleted file mode 100644 index 1c72ebb554be018511ae972c3f2361dff02dce02..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2545 zcma*pX;2es8VB%~zPr=ibVMCx-JQ^BhLDAsK)^**h(ZDp9YGuzZ%~j!}+w%FI;|aC7){7CdVvG)P{bng1y9Te*f}~*`1kQl$jwb z$tlW~rRS!X?#xfm_&6tTdp_`cjgYwbRFLNdoJCN$S-yhg`ZnC-yvedRSmOh%;Y`Gl6bY$Z-}#C=#F4%9!I1b zWQ~f+9P?;vhCxWwlwl=lrWG|7IYo;{jjmzJ5R9?f>n%-d@>kLINUc z4wM5dAO;kq<$}Dk{2-u0$I6@2N}&cUx9nmV1dYc8jfC}%=F9WCg^OQK9C6poh#2!A z3^EU*UFZvS^)?bu3T?J;@Ahb~%I?+@4!l5!*TjC}GIslNan-RCrrd~PdHYnNLJk+m&`$Y+NV(e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Ds;S57nYSJxtek>^~&(7B+N5MPf2+2xx z5Dl&4X|c@f{Kd|z1r+N|$DmsoVp*3yOdxT^J^-VAk)Z@$4^XrPrFP-Co+MXZ+KJ(W z{JNYvraLLWA;&tRhIKOvhW|HC|L-dLvAUF(MG0(Nl?4tB{RzN7I(}Cb%hwN{crFC8 zji#aJElKvDFV+&VI1V?oUMA>*kto0^;3W8FQBSZ|{ z$v~TqE=(8DZa^i$^oht&h};P1N&wMXorKh*Z68gPV&ouy>%f36Oqkwemyeas$Qbz# zV?7Jy%o7KY6^I=P@eCji%W`o5sf(5hySYo9$l4e2`(hIV_?=H-#R6}0$WVA|*(K@3 z=5?@RlcLh(meW%A4)hGzcvEpm(_w?>zhL*i&s9$2>r zAtk{8Cia|+Y+V!uX9BtpXoF%lswuRKsM!pSs!?yhlCy!269K0|b M?FSZn2B>%I-}ej|s{jB1 diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.css deleted file mode 100644 index 86a3716c501..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.css +++ /dev/null @@ -1,3274 +0,0 @@ -/* Copyright 2014 Mozilla Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -.messageBar{ - --closing-button-icon:url(images/messageBar_closingButton.svg); - --message-bar-close-button-color:var(--text-primary-color); - --message-bar-close-button-color-hover:var(--text-primary-color); - --message-bar-close-button-border-radius:4px; - --message-bar-close-button-border:none; - --message-bar-close-button-hover-bg-color:rgb(21 20 26 / 0.14); - --message-bar-close-button-active-bg-color:rgb(21 20 26 / 0.21); - --message-bar-close-button-focus-bg-color:rgb(21 20 26 / 0.07); -} - -@media (prefers-color-scheme: dark){ - -.messageBar{ - --message-bar-close-button-hover-bg-color:rgb(251 251 254 / 0.14); - --message-bar-close-button-active-bg-color:rgb(251 251 254 / 0.21); - --message-bar-close-button-focus-bg-color:rgb(251 251 254 / 0.07); -} - } - -@media screen and (forced-colors: active){ - -.messageBar{ - --message-bar-close-button-color:ButtonText; - --message-bar-close-button-border:1px solid ButtonText; - --message-bar-close-button-hover-bg-color:ButtonText; - --message-bar-close-button-active-bg-color:ButtonText; - --message-bar-close-button-focus-bg-color:ButtonText; - --message-bar-close-button-color-hover:HighlightText; -} - } - -.messageBar{ - - display:flex; - position:relative; - padding:8px 8px 8px 16px; - flex-direction:column; - justify-content:center; - align-items:center; - gap:8px; - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; - - border-radius:4px; - - border:1px solid var(--message-bar-border-color); - background:var(--message-bar-bg-color); - color:var(--message-bar-fg-color); -} - -.messageBar > div{ - display:flex; - align-items:flex-start; - gap:8px; - align-self:stretch; - } - -:is(.messageBar > div)::before{ - content:""; - display:inline-block; - width:16px; - height:16px; - -webkit-mask-image:var(--message-bar-icon); - mask-image:var(--message-bar-icon); - -webkit-mask-size:cover; - mask-size:cover; - background-color:var(--message-bar-icon-color); - flex-shrink:0; - } - -.messageBar button{ - cursor:pointer; - } - -:is(.messageBar button):focus-visible{ - outline:var(--focus-ring-outline); - outline-offset:2px; - } - -.messageBar .closeButton{ - width:32px; - height:32px; - background:none; - border-radius:var(--message-bar-close-button-border-radius); - border:var(--message-bar-close-button-border); - - display:flex; - align-items:center; - justify-content:center; - } - -:is(.messageBar .closeButton)::before{ - content:""; - display:inline-block; - width:16px; - height:16px; - -webkit-mask-image:var(--closing-button-icon); - mask-image:var(--closing-button-icon); - -webkit-mask-size:cover; - mask-size:cover; - background-color:var(--message-bar-close-button-color); - } - -:is(.messageBar .closeButton):is(:hover,:active,:focus)::before{ - background-color:var(--message-bar-close-button-color-hover); - } - -:is(.messageBar .closeButton):hover{ - background-color:var(--message-bar-close-button-hover-bg-color); - } - -:is(.messageBar .closeButton):active{ - background-color:var(--message-bar-close-button-active-bg-color); - } - -:is(.messageBar .closeButton):focus{ - background-color:var(--message-bar-close-button-focus-bg-color); - } - -:is(.messageBar .closeButton) > span{ - display:inline-block; - width:0; - height:0; - overflow:hidden; - } - -#editorUndoBar{ - --text-primary-color:#15141a; - - --message-bar-icon:url(images/secondaryToolbarButton-documentProperties.svg); - --message-bar-icon-color:#0060df; - --message-bar-bg-color:#deeafc; - --message-bar-fg-color:var(--text-primary-color); - --message-bar-border-color:rgb(0 0 0 / 0.08); - - --undo-button-bg-color:rgb(21 20 26 / 0.07); - --undo-button-bg-color-hover:rgb(21 20 26 / 0.14); - --undo-button-bg-color-active:rgb(21 20 26 / 0.21); - - --undo-button-fg-color:var(--message-bar-fg-color); - --undo-button-fg-color-hover:var(--undo-button-fg-color); - --undo-button-fg-color-active:var(--undo-button-fg-color); - - --focus-ring-color:#0060df; - --focus-ring-outline:2px solid var(--focus-ring-color); -} - -@media (prefers-color-scheme: dark){ - -#editorUndoBar{ - --text-primary-color:#fbfbfe; - - --message-bar-icon-color:#73a7f3; - --message-bar-bg-color:#003070; - --message-bar-border-color:rgb(255 255 255 / 0.08); - - --undo-button-bg-color:rgb(255 255 255 / 0.08); - --undo-button-bg-color-hover:rgb(255 255 255 / 0.14); - --undo-button-bg-color-active:rgb(255 255 255 / 0.21); -} - } - -@media screen and (forced-colors: active){ - -#editorUndoBar{ - --text-primary-color:CanvasText; - - --message-bar-icon-color:CanvasText; - --message-bar-bg-color:Canvas; - --message-bar-border-color:CanvasText; - - --undo-button-bg-color:ButtonText; - --undo-button-bg-color-hover:SelectedItem; - --undo-button-bg-color-active:SelectedItem; - - --undo-button-fg-color:ButtonFace; - --undo-button-fg-color-hover:SelectedItemText; - --undo-button-fg-color-active:SelectedItemText; - - --focus-ring-color:CanvasText; -} - } - -#editorUndoBar{ - - position:fixed; - top:50px; - left:50%; - transform:translateX(-50%); - z-index:10; - - padding-block:8px; - padding-inline:16px 8px; - - font:menu; - font-size:15px; - - cursor:default; -} - -#editorUndoBar button{ - cursor:pointer; - } - -#editorUndoBar #editorUndoBarUndoButton{ - border-radius:4px; - font-weight:590; - line-height:19.5px; - color:var(--undo-button-fg-color); - border:none; - padding:4px 16px; - margin-inline-start:8px; - height:32px; - - background-color:var(--undo-button-bg-color); - } - -:is(#editorUndoBar #editorUndoBarUndoButton):hover{ - background-color:var(--undo-button-bg-color-hover); - color:var(--undo-button-fg-color-hover); - } - -:is(#editorUndoBar #editorUndoBarUndoButton):active{ - background-color:var(--undo-button-bg-color-active); - color:var(--undo-button-fg-color-active); - } - -#editorUndoBar > div{ - align-items:center; - } - -.dialog{ - --dialog-bg-color:white; - --dialog-border-color:white; - --dialog-shadow:0 2px 14px 0 rgb(58 57 68 / 0.2); - --text-primary-color:#15141a; - --text-secondary-color:#5b5b66; - --hover-filter:brightness(0.9); - --focus-ring-color:#0060df; - --focus-ring-outline:2px solid var(--focus-ring-color); - --link-fg-color:#0060df; - --link-hover-fg-color:#0250bb; - --separator-color:#f0f0f4; - - --textarea-border-color:#8f8f9d; - --textarea-bg-color:white; - --textarea-fg-color:var(--text-secondary-color); - - --radio-bg-color:#f0f0f4; - --radio-checked-bg-color:#fbfbfe; - --radio-border-color:#8f8f9d; - --radio-checked-border-color:#0060df; - - --button-secondary-bg-color:#f0f0f4; - --button-secondary-fg-color:var(--text-primary-color); - --button-secondary-border-color:var(--button-secondary-bg-color); - --button-secondary-hover-bg-color:var(--button-secondary-bg-color); - --button-secondary-hover-fg-color:var(--button-secondary-fg-color); - --button-secondary-hover-border-color:var(--button-secondary-hover-bg-color); - - --button-primary-bg-color:#0060df; - --button-primary-fg-color:#fbfbfe; - --button-primary-border-color:var(--button-primary-bg-color); - --button-primary-hover-bg-color:var(--button-primary-bg-color); - --button-primary-hover-fg-color:var(--button-primary-fg-color); - --button-primary-hover-border-color:var(--button-primary-hover-bg-color); -} - -@media (prefers-color-scheme: dark){ - -.dialog{ - --dialog-bg-color:#1c1b22; - --dialog-border-color:#1c1b22; - --dialog-shadow:0 2px 14px 0 #15141a; - --text-primary-color:#fbfbfe; - --text-secondary-color:#cfcfd8; - --focus-ring-color:#0df; - --hover-filter:brightness(1.4); - --link-fg-color:#0df; - --link-hover-fg-color:#80ebff; - --separator-color:#52525e; - - --textarea-bg-color:#42414d; - - --radio-bg-color:#2b2a33; - --radio-checked-bg-color:#15141a; - --radio-checked-border-color:#0df; - - --button-secondary-bg-color:#2b2a33; - --button-primary-bg-color:#0df; - --button-primary-fg-color:#15141a; -} - } - -@media screen and (forced-colors: active){ - -.dialog{ - --dialog-bg-color:Canvas; - --dialog-border-color:CanvasText; - --dialog-shadow:none; - --text-primary-color:CanvasText; - --text-secondary-color:CanvasText; - --hover-filter:none; - --focus-ring-color:ButtonBorder; - --link-fg-color:LinkText; - --link-hover-fg-color:LinkText; - --separator-color:CanvasText; - - --textarea-border-color:ButtonBorder; - --textarea-bg-color:Field; - --textarea-fg-color:ButtonText; - - --radio-bg-color:ButtonFace; - --radio-checked-bg-color:ButtonFace; - --radio-border-color:ButtonText; - --radio-checked-border-color:ButtonText; - - --button-secondary-bg-color:ButtonFace; - --button-secondary-fg-color:ButtonText; - --button-secondary-border-color:ButtonText; - --button-secondary-hover-bg-color:AccentColor; - --button-secondary-hover-fg-color:AccentColorText; - - --button-primary-bg-color:ButtonText; - --button-primary-fg-color:ButtonFace; - --button-primary-hover-bg-color:AccentColor; - --button-primary-hover-fg-color:AccentColorText; -} - } - -.dialog{ - - font:message-box; - font-size:13px; - font-weight:400; - line-height:150%; - border-radius:4px; - padding:12px 16px; - border:1px solid var(--dialog-border-color); - background:var(--dialog-bg-color); - color:var(--text-primary-color); - box-shadow:var(--dialog-shadow); -} - -:is(.dialog .mainContainer) *:focus-visible{ - outline:var(--focus-ring-outline); - outline-offset:2px; - } - -:is(.dialog .mainContainer) .title{ - display:flex; - width:auto; - flex-direction:column; - justify-content:flex-end; - align-items:flex-start; - gap:12px; - } - -:is(:is(.dialog .mainContainer) .title) > span{ - font-size:13px; - font-style:normal; - font-weight:590; - line-height:150%; - } - -:is(.dialog .mainContainer) .dialogSeparator{ - width:100%; - height:0; - margin-block:4px; - border-top:1px solid var(--separator-color); - border-bottom:none; - } - -:is(.dialog .mainContainer) .dialogButtonsGroup{ - display:flex; - gap:12px; - align-self:flex-end; - } - -:is(.dialog .mainContainer) .radio{ - display:flex; - flex-direction:column; - align-items:flex-start; - gap:4px; - } - -:is(:is(.dialog .mainContainer) .radio) > .radioButton{ - display:flex; - gap:8px; - align-self:stretch; - align-items:center; - } - -:is(:is(:is(.dialog .mainContainer) .radio) > .radioButton) input{ - -webkit-appearance:none; - -moz-appearance:none; - appearance:none; - box-sizing:border-box; - width:16px; - height:16px; - border-radius:50%; - background-color:var(--radio-bg-color); - border:1px solid var(--radio-border-color); - } - -:is(:is(:is(:is(.dialog .mainContainer) .radio) > .radioButton) input):hover{ - filter:var(--hover-filter); - } - -:is(:is(:is(:is(.dialog .mainContainer) .radio) > .radioButton) input):checked{ - background-color:var(--radio-checked-bg-color); - border:4px solid var(--radio-checked-border-color); - } - -:is(:is(.dialog .mainContainer) .radio) > .radioLabel{ - display:flex; - padding-inline-start:24px; - align-items:flex-start; - gap:10px; - align-self:stretch; - } - -:is(:is(:is(.dialog .mainContainer) .radio) > .radioLabel) > span{ - flex:1 0 0; - font-size:11px; - color:var(--text-secondary-color); - } - -:is(.dialog .mainContainer) button:not(:is(.toggle-button,.closeButton)){ - border-radius:4px; - border:1px solid; - font:menu; - font-weight:600; - padding:4px 16px; - width:auto; - height:32px; - } - -:is(:is(.dialog .mainContainer) button:not(:is(.toggle-button,.closeButton))):hover{ - cursor:pointer; - filter:var(--hover-filter); - } - -.secondaryButton:is(:is(.dialog .mainContainer) button:not(:is(.toggle-button,.closeButton))){ - color:var(--button-secondary-fg-color); - background-color:var(--button-secondary-bg-color); - border-color:var(--button-secondary-border-color); - } - -.secondaryButton:is(:is(.dialog .mainContainer) button:not(:is(.toggle-button,.closeButton))):hover{ - color:var(--button-secondary-hover-fg-color); - background-color:var(--button-secondary-hover-bg-color); - border-color:var(--button-secondary-hover-border-color); - } - -.primaryButton:is(:is(.dialog .mainContainer) button:not(:is(.toggle-button,.closeButton))){ - color:var(--button-primary-fg-color); - background-color:var(--button-primary-bg-color); - border-color:var(--button-primary-border-color); - opacity:1; - } - -.primaryButton:is(:is(.dialog .mainContainer) button:not(:is(.toggle-button,.closeButton))):hover{ - color:var(--button-primary-hover-fg-color); - background-color:var(--button-primary-hover-bg-color); - border-color:var(--button-primary-hover-border-color); - } - -:is(.dialog .mainContainer) a{ - color:var(--link-fg-color); - } - -:is(:is(.dialog .mainContainer) a):hover{ - color:var(--link-hover-fg-color); - } - -:is(.dialog .mainContainer) textarea{ - font:inherit; - padding:8px; - resize:none; - margin:0; - box-sizing:border-box; - border-radius:4px; - border:1px solid var(--textarea-border-color); - background:var(--textarea-bg-color); - color:var(--textarea-fg-color); - } - -:is(:is(.dialog .mainContainer) textarea):focus{ - outline-offset:0; - border-color:transparent; - } - -:is(:is(.dialog .mainContainer) textarea):disabled{ - pointer-events:none; - opacity:0.4; - } - -:is(.dialog .mainContainer) .messageBar{ - --message-bar-bg-color:#ffebcd; - --message-bar-fg-color:#15141a; - --message-bar-border-color:rgb(0 0 0 / 0.08); - --message-bar-icon:url(images/messageBar_warning.svg); - --message-bar-icon-color:#cd411e; - } - -@media (prefers-color-scheme: dark){ - -:is(.dialog .mainContainer) .messageBar{ - --message-bar-bg-color:#5a3100; - --message-bar-fg-color:#fbfbfe; - --message-bar-border-color:rgb(255 255 255 / 0.08); - --message-bar-icon-color:#e49c49; - } - } - -@media screen and (forced-colors: active){ - -:is(.dialog .mainContainer) .messageBar{ - --message-bar-bg-color:HighlightText; - --message-bar-fg-color:CanvasText; - --message-bar-border-color:CanvasText; - --message-bar-icon-color:CanvasText; - } - } - -:is(.dialog .mainContainer) .messageBar{ - - align-self:stretch; - } - -:is(:is(:is(.dialog .mainContainer) .messageBar) > div)::before,:is(:is(:is(.dialog .mainContainer) .messageBar) > div) > div{ - margin-block:4px; - } - -:is(:is(:is(.dialog .mainContainer) .messageBar) > div) > div{ - display:flex; - flex-direction:column; - align-items:flex-start; - gap:8px; - flex:1 0 0; - } - -:is(:is(:is(:is(.dialog .mainContainer) .messageBar) > div) > div) .title{ - font-size:13px; - font-weight:590; - } - -:is(:is(:is(:is(.dialog .mainContainer) .messageBar) > div) > div) .description{ - font-size:13px; - } - -:is(.dialog .mainContainer) .toggler{ - display:flex; - align-items:center; - gap:8px; - align-self:stretch; - } - -:is(:is(.dialog .mainContainer) .toggler) > .togglerLabel{ - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; - } - -.textLayer{ - position:absolute; - text-align:initial; - inset:0; - overflow:clip; - opacity:1; - line-height:1; - -webkit-text-size-adjust:none; - -moz-text-size-adjust:none; - text-size-adjust:none; - forced-color-adjust:none; - transform-origin:0 0; - caret-color:CanvasText; - z-index:0; -} - -.textLayer.highlighting{ - touch-action:none; - } - -.textLayer :is(span,br){ - color:transparent; - position:absolute; - white-space:pre; - cursor:text; - transform-origin:0% 0%; - } - -.textLayer > :not(.markedContent),.textLayer .markedContent span:not(.markedContent){ - z-index:1; - } - -.textLayer span.markedContent{ - top:0; - height:0; - } - -.textLayer span[role="img"]{ - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; - cursor:default; - } - -.textLayer .highlight{ - --highlight-bg-color:rgb(180 0 170 / 0.25); - --highlight-selected-bg-color:rgb(0 100 0 / 0.25); - --highlight-backdrop-filter:none; - --highlight-selected-backdrop-filter:none; - } - -@media screen and (forced-colors: active){ - -.textLayer .highlight{ - --highlight-bg-color:transparent; - --highlight-selected-bg-color:transparent; - --highlight-backdrop-filter:var(--hcm-highlight-filter); - --highlight-selected-backdrop-filter:var( - --hcm-highlight-selected-filter - ); - } - } - -.textLayer .highlight{ - - margin:-1px; - padding:1px; - background-color:var(--highlight-bg-color); - -webkit-backdrop-filter:var(--highlight-backdrop-filter); - backdrop-filter:var(--highlight-backdrop-filter); - border-radius:4px; - } - -.appended:is(.textLayer .highlight){ - position:initial; - } - -.begin:is(.textLayer .highlight){ - border-radius:4px 0 0 4px; - } - -.end:is(.textLayer .highlight){ - border-radius:0 4px 4px 0; - } - -.middle:is(.textLayer .highlight){ - border-radius:0; - } - -.selected:is(.textLayer .highlight){ - background-color:var(--highlight-selected-bg-color); - -webkit-backdrop-filter:var(--highlight-selected-backdrop-filter); - backdrop-filter:var(--highlight-selected-backdrop-filter); - } - -.textLayer ::-moz-selection{ - background:rgba(0 0 255 / 0.25); - background:color-mix(in srgb, AccentColor, transparent 75%); - } - -.textLayer ::selection{ - background:rgba(0 0 255 / 0.25); - background:color-mix(in srgb, AccentColor, transparent 75%); - } - -.textLayer br::-moz-selection{ - background:transparent; - } - -.textLayer br::selection{ - background:transparent; - } - -.textLayer .endOfContent{ - display:block; - position:absolute; - inset:100% 0 0; - z-index:0; - cursor:default; - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; - } - -.textLayer.selecting .endOfContent{ - top:0; - } - -.annotationLayer{ - --annotation-unfocused-field-background:url("data:image/svg+xml;charset=UTF-8,"); - --input-focus-border-color:Highlight; - --input-focus-outline:1px solid Canvas; - --input-unfocused-border-color:transparent; - --input-disabled-border-color:transparent; - --input-hover-border-color:black; - --link-outline:none; -} - -@media screen and (forced-colors: active){ - -.annotationLayer{ - --input-focus-border-color:CanvasText; - --input-unfocused-border-color:ActiveText; - --input-disabled-border-color:GrayText; - --input-hover-border-color:Highlight; - --link-outline:1.5px solid LinkText; -} - - .annotationLayer .textWidgetAnnotation :is(input,textarea):required,.annotationLayer .choiceWidgetAnnotation select:required,.annotationLayer .buttonWidgetAnnotation:is(.checkBox,.radioButton) input:required{ - outline:1.5px solid selectedItem; - } - - .annotationLayer .linkAnnotation{ - outline:var(--link-outline); - } - - :is(.annotationLayer .linkAnnotation):hover{ - -webkit-backdrop-filter:var(--hcm-highlight-filter); - backdrop-filter:var(--hcm-highlight-filter); - } - - :is(.annotationLayer .linkAnnotation) > a:hover{ - opacity:0 !important; - background:none !important; - box-shadow:none; - } - - .annotationLayer .popupAnnotation .popup{ - outline:calc(1.5px * var(--scale-factor)) solid CanvasText !important; - background-color:ButtonFace !important; - color:ButtonText !important; - } - - .annotationLayer .highlightArea:hover::after{ - position:absolute; - top:0; - left:0; - width:100%; - height:100%; - -webkit-backdrop-filter:var(--hcm-highlight-filter); - backdrop-filter:var(--hcm-highlight-filter); - content:""; - pointer-events:none; - } - - .annotationLayer .popupAnnotation.focused .popup{ - outline:calc(3px * var(--scale-factor)) solid Highlight !important; - } - } - -.annotationLayer{ - - position:absolute; - top:0; - left:0; - pointer-events:none; - transform-origin:0 0; -} - -.annotationLayer[data-main-rotation="90"] .norotate{ - transform:rotate(270deg) translateX(-100%); - } - -.annotationLayer[data-main-rotation="180"] .norotate{ - transform:rotate(180deg) translate(-100%, -100%); - } - -.annotationLayer[data-main-rotation="270"] .norotate{ - transform:rotate(90deg) translateY(-100%); - } - -.annotationLayer.disabled section,.annotationLayer.disabled .popup{ - pointer-events:none; - } - -.annotationLayer .annotationContent{ - position:absolute; - width:100%; - height:100%; - pointer-events:none; - } - -.freetext:is(.annotationLayer .annotationContent){ - background:transparent; - border:none; - inset:0; - overflow:visible; - white-space:nowrap; - font:10px sans-serif; - line-height:1.35; - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; - } - -.annotationLayer section{ - position:absolute; - text-align:initial; - pointer-events:auto; - box-sizing:border-box; - transform-origin:0 0; - } - -:is(.annotationLayer section):has(div.annotationContent) canvas.annotationContent{ - display:none; - } - -.textLayer.selecting ~ .annotationLayer section{ - pointer-events:none; - } - -.annotationLayer :is(.linkAnnotation,.buttonWidgetAnnotation.pushButton) > a{ - position:absolute; - font-size:1em; - top:0; - left:0; - width:100%; - height:100%; - } - -.annotationLayer :is(.linkAnnotation,.buttonWidgetAnnotation.pushButton):not(.hasBorder) > a:hover{ - opacity:0.2; - background-color:rgb(255 255 0); - box-shadow:0 2px 10px rgb(255 255 0); - } - -.annotationLayer .linkAnnotation.hasBorder:hover{ - background-color:rgb(255 255 0 / 0.2); - } - -.annotationLayer .hasBorder{ - background-size:100% 100%; - } - -.annotationLayer .textAnnotation img{ - position:absolute; - cursor:pointer; - width:100%; - height:100%; - top:0; - left:0; - } - -.annotationLayer .textWidgetAnnotation :is(input,textarea),.annotationLayer .choiceWidgetAnnotation select,.annotationLayer .buttonWidgetAnnotation:is(.checkBox,.radioButton) input{ - background-image:var(--annotation-unfocused-field-background); - border:2px solid var(--input-unfocused-border-color); - box-sizing:border-box; - font:calc(9px * var(--scale-factor)) sans-serif; - height:100%; - margin:0; - vertical-align:top; - width:100%; - } - -.annotationLayer .textWidgetAnnotation :is(input,textarea):required,.annotationLayer .choiceWidgetAnnotation select:required,.annotationLayer .buttonWidgetAnnotation:is(.checkBox,.radioButton) input:required{ - outline:1.5px solid red; - } - -.annotationLayer .choiceWidgetAnnotation select option{ - padding:0; - } - -.annotationLayer .buttonWidgetAnnotation.radioButton input{ - border-radius:50%; - } - -.annotationLayer .textWidgetAnnotation textarea{ - resize:none; - } - -.annotationLayer .textWidgetAnnotation [disabled]:is(input,textarea),.annotationLayer .choiceWidgetAnnotation select[disabled],.annotationLayer .buttonWidgetAnnotation:is(.checkBox,.radioButton) input[disabled]{ - background:none; - border:2px solid var(--input-disabled-border-color); - cursor:not-allowed; - } - -.annotationLayer .textWidgetAnnotation :is(input,textarea):hover,.annotationLayer .choiceWidgetAnnotation select:hover,.annotationLayer .buttonWidgetAnnotation:is(.checkBox,.radioButton) input:hover{ - border:2px solid var(--input-hover-border-color); - } - -.annotationLayer .textWidgetAnnotation :is(input,textarea):hover,.annotationLayer .choiceWidgetAnnotation select:hover,.annotationLayer .buttonWidgetAnnotation.checkBox input:hover{ - border-radius:2px; - } - -.annotationLayer .textWidgetAnnotation :is(input,textarea):focus,.annotationLayer .choiceWidgetAnnotation select:focus{ - background:none; - border:2px solid var(--input-focus-border-color); - border-radius:2px; - outline:var(--input-focus-outline); - } - -.annotationLayer .buttonWidgetAnnotation:is(.checkBox,.radioButton) :focus{ - background-image:none; - background-color:transparent; - } - -.annotationLayer .buttonWidgetAnnotation.checkBox :focus{ - border:2px solid var(--input-focus-border-color); - border-radius:2px; - outline:var(--input-focus-outline); - } - -.annotationLayer .buttonWidgetAnnotation.radioButton :focus{ - border:2px solid var(--input-focus-border-color); - outline:var(--input-focus-outline); - } - -.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::before,.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::after,.annotationLayer .buttonWidgetAnnotation.radioButton input:checked::before{ - background-color:CanvasText; - content:""; - display:block; - position:absolute; - } - -.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::before,.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::after{ - height:80%; - left:45%; - width:1px; - } - -.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::before{ - transform:rotate(45deg); - } - -.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::after{ - transform:rotate(-45deg); - } - -.annotationLayer .buttonWidgetAnnotation.radioButton input:checked::before{ - border-radius:50%; - height:50%; - left:25%; - top:25%; - width:50%; - } - -.annotationLayer .textWidgetAnnotation input.comb{ - font-family:monospace; - padding-left:2px; - padding-right:0; - } - -.annotationLayer .textWidgetAnnotation input.comb:focus{ - width:103%; - } - -.annotationLayer .buttonWidgetAnnotation:is(.checkBox,.radioButton) input{ - -webkit-appearance:none; - -moz-appearance:none; - appearance:none; - } - -.annotationLayer .fileAttachmentAnnotation .popupTriggerArea{ - height:100%; - width:100%; - } - -.annotationLayer .popupAnnotation{ - position:absolute; - font-size:calc(9px * var(--scale-factor)); - pointer-events:none; - width:-moz-max-content; - width:max-content; - max-width:45%; - height:auto; - } - -.annotationLayer .popup{ - background-color:rgb(255 255 153); - box-shadow:0 calc(2px * var(--scale-factor)) calc(5px * var(--scale-factor)) rgb(136 136 136); - border-radius:calc(2px * var(--scale-factor)); - outline:1.5px solid rgb(255 255 74); - padding:calc(6px * var(--scale-factor)); - cursor:pointer; - font:message-box; - white-space:normal; - word-wrap:break-word; - pointer-events:auto; - } - -.annotationLayer .popupAnnotation.focused .popup{ - outline-width:3px; - } - -.annotationLayer .popup *{ - font-size:calc(9px * var(--scale-factor)); - } - -.annotationLayer .popup > .header{ - display:inline-block; - } - -.annotationLayer .popup > .header h1{ - display:inline; - } - -.annotationLayer .popup > .header .popupDate{ - display:inline-block; - margin-left:calc(5px * var(--scale-factor)); - width:-moz-fit-content; - width:fit-content; - } - -.annotationLayer .popupContent{ - border-top:1px solid rgb(51 51 51); - margin-top:calc(2px * var(--scale-factor)); - padding-top:calc(2px * var(--scale-factor)); - } - -.annotationLayer .richText > *{ - white-space:pre-wrap; - font-size:calc(9px * var(--scale-factor)); - } - -.annotationLayer .popupTriggerArea{ - cursor:pointer; - } - -.annotationLayer section svg{ - position:absolute; - width:100%; - height:100%; - top:0; - left:0; - } - -.annotationLayer .annotationTextContent{ - position:absolute; - width:100%; - height:100%; - opacity:0; - color:transparent; - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; - pointer-events:none; - } - -:is(.annotationLayer .annotationTextContent) span{ - width:100%; - display:inline-block; - } - -.annotationLayer svg.quadrilateralsContainer{ - contain:strict; - width:0; - height:0; - position:absolute; - top:0; - left:0; - z-index:-1; - } - -:root{ - --xfa-unfocused-field-background:url("data:image/svg+xml;charset=UTF-8,"); - --xfa-focus-outline:auto; -} - -@media screen and (forced-colors: active){ - :root{ - --xfa-focus-outline:2px solid CanvasText; - } - .xfaLayer *:required{ - outline:1.5px solid selectedItem; - } -} - -.xfaLayer{ - background-color:transparent; -} - -.xfaLayer .highlight{ - margin:-1px; - padding:1px; - background-color:rgb(239 203 237); - border-radius:4px; -} - -.xfaLayer .highlight.appended{ - position:initial; -} - -.xfaLayer .highlight.begin{ - border-radius:4px 0 0 4px; -} - -.xfaLayer .highlight.end{ - border-radius:0 4px 4px 0; -} - -.xfaLayer .highlight.middle{ - border-radius:0; -} - -.xfaLayer .highlight.selected{ - background-color:rgb(203 223 203); -} - -.xfaPage{ - overflow:hidden; - position:relative; -} - -.xfaContentarea{ - position:absolute; -} - -.xfaPrintOnly{ - display:none; -} - -.xfaLayer{ - position:absolute; - text-align:initial; - top:0; - left:0; - transform-origin:0 0; - line-height:1.2; -} - -.xfaLayer *{ - color:inherit; - font:inherit; - font-style:inherit; - font-weight:inherit; - font-kerning:inherit; - letter-spacing:-0.01px; - text-align:inherit; - text-decoration:inherit; - box-sizing:border-box; - background-color:transparent; - padding:0; - margin:0; - pointer-events:auto; - line-height:inherit; -} - -.xfaLayer *:required{ - outline:1.5px solid red; -} - -.xfaLayer div, -.xfaLayer svg, -.xfaLayer svg *{ - pointer-events:none; -} - -.xfaLayer a{ - color:blue; -} - -.xfaRich li{ - margin-left:3em; -} - -.xfaFont{ - color:black; - font-weight:normal; - font-kerning:none; - font-size:10px; - font-style:normal; - letter-spacing:0; - text-decoration:none; - vertical-align:0; -} - -.xfaCaption{ - overflow:hidden; - flex:0 0 auto; -} - -.xfaCaptionForCheckButton{ - overflow:hidden; - flex:1 1 auto; -} - -.xfaLabel{ - height:100%; - width:100%; -} - -.xfaLeft{ - display:flex; - flex-direction:row; - align-items:center; -} - -.xfaRight{ - display:flex; - flex-direction:row-reverse; - align-items:center; -} - -:is(.xfaLeft, .xfaRight) > :is(.xfaCaption, .xfaCaptionForCheckButton){ - max-height:100%; -} - -.xfaTop{ - display:flex; - flex-direction:column; - align-items:flex-start; -} - -.xfaBottom{ - display:flex; - flex-direction:column-reverse; - align-items:flex-start; -} - -:is(.xfaTop, .xfaBottom) > :is(.xfaCaption, .xfaCaptionForCheckButton){ - width:100%; -} - -.xfaBorder{ - background-color:transparent; - position:absolute; - pointer-events:none; -} - -.xfaWrapped{ - width:100%; - height:100%; -} - -:is(.xfaTextfield, .xfaSelect):focus{ - background-image:none; - background-color:transparent; - outline:var(--xfa-focus-outline); - outline-offset:-1px; -} - -:is(.xfaCheckbox, .xfaRadio):focus{ - outline:var(--xfa-focus-outline); -} - -.xfaTextfield, -.xfaSelect{ - height:100%; - width:100%; - flex:1 1 auto; - border:none; - resize:none; - background-image:var(--xfa-unfocused-field-background); -} - -.xfaSelect{ - padding-inline:2px; -} - -:is(.xfaTop, .xfaBottom) > :is(.xfaTextfield, .xfaSelect){ - flex:0 1 auto; -} - -.xfaButton{ - cursor:pointer; - width:100%; - height:100%; - border:none; - text-align:center; -} - -.xfaLink{ - width:100%; - height:100%; - position:absolute; - top:0; - left:0; -} - -.xfaCheckbox, -.xfaRadio{ - width:100%; - height:100%; - flex:0 0 auto; - border:none; -} - -.xfaRich{ - white-space:pre-wrap; - width:100%; - height:100%; -} - -.xfaImage{ - -o-object-position:left top; - object-position:left top; - -o-object-fit:contain; - object-fit:contain; - width:100%; - height:100%; -} - -.xfaLrTb, -.xfaRlTb, -.xfaTb{ - display:flex; - flex-direction:column; - align-items:stretch; -} - -.xfaLr{ - display:flex; - flex-direction:row; - align-items:stretch; -} - -.xfaRl{ - display:flex; - flex-direction:row-reverse; - align-items:stretch; -} - -.xfaTb > div{ - justify-content:left; -} - -.xfaPosition{ - position:relative; -} - -.xfaArea{ - position:relative; -} - -.xfaValignMiddle{ - display:flex; - align-items:center; -} - -.xfaTable{ - display:flex; - flex-direction:column; - align-items:stretch; -} - -.xfaTable .xfaRow{ - display:flex; - flex-direction:row; - align-items:stretch; -} - -.xfaTable .xfaRlRow{ - display:flex; - flex-direction:row-reverse; - align-items:stretch; - flex:1; -} - -.xfaTable .xfaRlRow > div{ - flex:1; -} - -:is(.xfaNonInteractive, .xfaDisabled, .xfaReadOnly) :is(input, textarea){ - background:initial; -} - -@media print{ - .xfaTextfield, - .xfaSelect{ - background:transparent; - } - - .xfaSelect{ - -webkit-appearance:none; - -moz-appearance:none; - appearance:none; - text-indent:1px; - text-overflow:""; - } -} - -.canvasWrapper svg{ - transform:none; - } - -.moving:is(.canvasWrapper svg){ - z-index:100000; - } - -[data-main-rotation="90"]:is(.highlight:is(.canvasWrapper svg),.highlightOutline:is(.canvasWrapper svg)) mask,[data-main-rotation="90"]:is(.highlight:is(.canvasWrapper svg),.highlightOutline:is(.canvasWrapper svg)) use:not(.clip,.mask){ - transform:matrix(0, 1, -1, 0, 1, 0); - } - -[data-main-rotation="180"]:is(.highlight:is(.canvasWrapper svg),.highlightOutline:is(.canvasWrapper svg)) mask,[data-main-rotation="180"]:is(.highlight:is(.canvasWrapper svg),.highlightOutline:is(.canvasWrapper svg)) use:not(.clip,.mask){ - transform:matrix(-1, 0, 0, -1, 1, 1); - } - -[data-main-rotation="270"]:is(.highlight:is(.canvasWrapper svg),.highlightOutline:is(.canvasWrapper svg)) mask,[data-main-rotation="270"]:is(.highlight:is(.canvasWrapper svg),.highlightOutline:is(.canvasWrapper svg)) use:not(.clip,.mask){ - transform:matrix(0, -1, 1, 0, 0, 1); - } - -.draw:is(.canvasWrapper svg){ - position:absolute; - mix-blend-mode:normal; - } - -.draw[data-draw-rotation="90"]:is(.canvasWrapper svg){ - transform:rotate(90deg); - } - -.draw[data-draw-rotation="180"]:is(.canvasWrapper svg){ - transform:rotate(180deg); - } - -.draw[data-draw-rotation="270"]:is(.canvasWrapper svg){ - transform:rotate(270deg); - } - -.highlight:is(.canvasWrapper svg){ - --blend-mode:multiply; - } - -@media screen and (forced-colors: active){ - -.highlight:is(.canvasWrapper svg){ - --blend-mode:difference; - } - } - -.highlight:is(.canvasWrapper svg){ - - position:absolute; - mix-blend-mode:var(--blend-mode); - } - -.highlight:is(.canvasWrapper svg):not(.free){ - fill-rule:evenodd; - } - -.highlightOutline:is(.canvasWrapper svg){ - position:absolute; - mix-blend-mode:normal; - fill-rule:evenodd; - fill:none; - } - -.highlightOutline.hovered:is(.canvasWrapper svg):not(.free):not(.selected){ - stroke:var(--hover-outline-color); - stroke-width:var(--outline-width); - } - -.highlightOutline.selected:is(.canvasWrapper svg):not(.free) .mainOutline{ - stroke:var(--outline-around-color); - stroke-width:calc( - var(--outline-width) + 2 * var(--outline-around-width) - ); - } - -.highlightOutline.selected:is(.canvasWrapper svg):not(.free) .secondaryOutline{ - stroke:var(--outline-color); - stroke-width:var(--outline-width); - } - -.highlightOutline.free.hovered:is(.canvasWrapper svg):not(.selected){ - stroke:var(--hover-outline-color); - stroke-width:calc(2 * var(--outline-width)); - } - -.highlightOutline.free.selected:is(.canvasWrapper svg) .mainOutline{ - stroke:var(--outline-around-color); - stroke-width:calc( - 2 * (var(--outline-width) + var(--outline-around-width)) - ); - } - -.highlightOutline.free.selected:is(.canvasWrapper svg) .secondaryOutline{ - stroke:var(--outline-color); - stroke-width:calc(2 * var(--outline-width)); - } - -.toggle-button{ - --button-background-color:#f0f0f4; - --button-background-color-hover:#e0e0e6; - --button-background-color-active:#cfcfd8; - --color-accent-primary:#0060df; - --color-accent-primary-hover:#0250bb; - --color-accent-primary-active:#054096; - --border-interactive-color:#8f8f9d; - --border-radius-circle:9999px; - --border-width:1px; - --size-item-small:16px; - --size-item-large:32px; - --color-canvas:white; -} - -@media (prefers-color-scheme: dark){ - -.toggle-button{ - --button-background-color:color-mix(in srgb, currentColor 7%, transparent); - --button-background-color-hover:color-mix( - in srgb, - currentColor 14%, - transparent - ); - --button-background-color-active:color-mix( - in srgb, - currentColor 21%, - transparent - ); - --color-accent-primary:#0df; - --color-accent-primary-hover:#80ebff; - --color-accent-primary-active:#aaf2ff; - --border-interactive-color:#bfbfc9; - --color-canvas:#1c1b22; -} - } - -@media (forced-colors: active){ - -.toggle-button{ - --color-accent-primary:ButtonText; - --color-accent-primary-hover:SelectedItem; - --color-accent-primary-active:SelectedItem; - --border-interactive-color:ButtonText; - --button-background-color:ButtonFace; - --border-interactive-color-hover:SelectedItem; - --border-interactive-color-active:SelectedItem; - --border-interactive-color-disabled:GrayText; - --color-canvas:ButtonText; -} - } - -.toggle-button{ - - --toggle-background-color:var(--button-background-color); - --toggle-background-color-hover:var(--button-background-color-hover); - --toggle-background-color-active:var(--button-background-color-active); - --toggle-background-color-pressed:var(--color-accent-primary); - --toggle-background-color-pressed-hover:var(--color-accent-primary-hover); - --toggle-background-color-pressed-active:var(--color-accent-primary-active); - --toggle-border-color:var(--border-interactive-color); - --toggle-border-color-hover:var(--toggle-border-color); - --toggle-border-color-active:var(--toggle-border-color); - --toggle-border-radius:var(--border-radius-circle); - --toggle-border-width:var(--border-width); - --toggle-height:var(--size-item-small); - --toggle-width:var(--size-item-large); - --toggle-dot-background-color:var(--toggle-border-color); - --toggle-dot-background-color-hover:var(--toggle-dot-background-color); - --toggle-dot-background-color-active:var(--toggle-dot-background-color); - --toggle-dot-background-color-on-pressed:var(--color-canvas); - --toggle-dot-margin:1px; - --toggle-dot-height:calc( - var(--toggle-height) - 2 * var(--toggle-dot-margin) - 2 * - var(--toggle-border-width) - ); - --toggle-dot-width:var(--toggle-dot-height); - --toggle-dot-transform-x:calc( - var(--toggle-width) - 4 * var(--toggle-dot-margin) - var(--toggle-dot-width) - ); - - -webkit-appearance:none; - - -moz-appearance:none; - - appearance:none; - padding:0; - margin:0; - border:var(--toggle-border-width) solid var(--toggle-border-color); - height:var(--toggle-height); - width:var(--toggle-width); - border-radius:var(--toggle-border-radius); - background:var(--toggle-background-color); - box-sizing:border-box; - flex-shrink:0; -} - -.toggle-button:focus-visible{ - outline:var(--focus-outline); - outline-offset:var(--focus-outline-offset); - } - -.toggle-button:enabled:hover{ - background:var(--toggle-background-color-hover); - border-color:var(--toggle-border-color); - } - -.toggle-button:enabled:active{ - background:var(--toggle-background-color-active); - border-color:var(--toggle-border-color); - } - -.toggle-button[aria-pressed="true"]{ - background:var(--toggle-background-color-pressed); - border-color:transparent; - } - -.toggle-button[aria-pressed="true"]:enabled:hover{ - background:var(--toggle-background-color-pressed-hover); - border-color:transparent; - } - -.toggle-button[aria-pressed="true"]:enabled:active{ - background:var(--toggle-background-color-pressed-active); - border-color:transparent; - } - -.toggle-button::before{ - display:block; - content:""; - background-color:var(--toggle-dot-background-color); - height:var(--toggle-dot-height); - width:var(--toggle-dot-width); - margin:var(--toggle-dot-margin); - border-radius:var(--toggle-border-radius); - translate:0; - } - -.toggle-button[aria-pressed="true"]::before{ - translate:var(--toggle-dot-transform-x); - background-color:var(--toggle-dot-background-color-on-pressed); - } - -.toggle-button[aria-pressed="true"]:enabled:hover::before,.toggle-button[aria-pressed="true"]:enabled:active::before{ - background-color:var(--toggle-dot-background-color-on-pressed); - } - -[dir="rtl"] .toggle-button[aria-pressed="true"]::before{ - translate:calc(-1 * var(--toggle-dot-transform-x)); - } - -@media (prefers-reduced-motion: no-preference){ - .toggle-button::before{ - transition:translate 100ms; - } - } - -@media (prefers-contrast){ - .toggle-button:enabled:hover{ - border-color:var(--toggle-border-color-hover); - } - - .toggle-button:enabled:active{ - border-color:var(--toggle-border-color-active); - } - - .toggle-button[aria-pressed="true"]:enabled{ - border-color:var(--toggle-border-color); - position:relative; - } - - .toggle-button[aria-pressed="true"]:enabled:hover,.toggle-button[aria-pressed="true"]:enabled:hover:active{ - border-color:var(--toggle-border-color-hover); - } - - .toggle-button[aria-pressed="true"]:enabled:active{ - background-color:var(--toggle-dot-background-color-active); - border-color:var(--toggle-dot-background-color-hover); - } - - .toggle-button:hover::before,.toggle-button:active::before{ - background-color:var(--toggle-dot-background-color-hover); - } - } - -@media (forced-colors){ - -.toggle-button{ - --toggle-dot-background-color:var(--color-accent-primary); - --toggle-dot-background-color-hover:var(--color-accent-primary-hover); - --toggle-dot-background-color-active:var(--color-accent-primary-active); - --toggle-dot-background-color-on-pressed:var(--button-background-color); - --toggle-background-color-disabled:var(--button-background-color-disabled); - --toggle-border-color-hover:var(--border-interactive-color-hover); - --toggle-border-color-active:var(--border-interactive-color-active); - --toggle-border-color-disabled:var(--border-interactive-color-disabled); -} - - .toggle-button[aria-pressed="true"]:enabled::after{ - border:1px solid var(--button-background-color); - content:""; - position:absolute; - height:var(--toggle-height); - width:var(--toggle-width); - display:block; - border-radius:var(--toggle-border-radius); - inset:-2px; - } - - .toggle-button[aria-pressed="true"]:enabled:active::after{ - border-color:var(--toggle-border-color-active); - } - } - -:root{ - --outline-width:2px; - --outline-color:#0060df; - --outline-around-width:1px; - --outline-around-color:#f0f0f4; - --hover-outline-around-color:var(--outline-around-color); - --focus-outline:solid var(--outline-width) var(--outline-color); - --unfocus-outline:solid var(--outline-width) transparent; - --focus-outline-around:solid var(--outline-around-width) var(--outline-around-color); - --hover-outline-color:#8f8f9d; - --hover-outline:solid var(--outline-width) var(--hover-outline-color); - --hover-outline-around:solid var(--outline-around-width) var(--hover-outline-around-color); - --freetext-line-height:1.35; - --freetext-padding:2px; - --resizer-bg-color:var(--outline-color); - --resizer-size:6px; - --resizer-shift:calc( - 0px - (var(--outline-width) + var(--resizer-size)) / 2 - - var(--outline-around-width) - ); - --editorFreeText-editing-cursor:text; - --editorInk-editing-cursor:url(images/cursor-editorInk.svg) 0 16, pointer; - --editorHighlight-editing-cursor:url(images/cursor-editorTextHighlight.svg) 24 24, text; - --editorFreeHighlight-editing-cursor:url(images/cursor-editorFreeHighlight.svg) 1 18, pointer; - - --new-alt-text-warning-image:url(images/altText_warning.svg); -} -.visuallyHidden{ - position:absolute; - top:0; - left:0; - border:0; - margin:0; - padding:0; - width:0; - height:0; - overflow:hidden; - white-space:nowrap; - font-size:0; -} - -.textLayer.highlighting{ - cursor:var(--editorFreeHighlight-editing-cursor); - } - -.textLayer.highlighting:not(.free) span{ - cursor:var(--editorHighlight-editing-cursor); - } - -[role="img"]:is(.textLayer.highlighting:not(.free) span){ - cursor:var(--editorFreeHighlight-editing-cursor); - } - -.textLayer.highlighting.free span{ - cursor:var(--editorFreeHighlight-editing-cursor); - } - -:is(#viewerContainer.pdfPresentationMode:fullscreen,.annotationEditorLayer.disabled) .noAltTextBadge{ - display:none !important; - } - -@media (min-resolution: 1.1dppx){ - :root{ - --editorFreeText-editing-cursor:url(images/cursor-editorFreeText.svg) 0 16, text; - } -} - -@media screen and (forced-colors: active){ - :root{ - --outline-color:CanvasText; - --outline-around-color:ButtonFace; - --resizer-bg-color:ButtonText; - --hover-outline-color:Highlight; - --hover-outline-around-color:SelectedItemText; - } -} - -[data-editor-rotation="90"]{ - transform:rotate(90deg); -} - -[data-editor-rotation="180"]{ - transform:rotate(180deg); -} - -[data-editor-rotation="270"]{ - transform:rotate(270deg); -} - -.annotationEditorLayer{ - background:transparent; - position:absolute; - inset:0; - font-size:calc(100px * var(--scale-factor)); - transform-origin:0 0; - cursor:auto; -} - -.annotationEditorLayer .selectedEditor{ - z-index:100000 !important; - } - -.annotationEditorLayer.drawing *{ - pointer-events:none !important; - } - -.annotationEditorLayer.waiting{ - content:""; - cursor:wait; - position:absolute; - inset:0; - width:100%; - height:100%; -} - -.annotationEditorLayer.disabled{ - pointer-events:none; -} - -.annotationEditorLayer.freetextEditing{ - cursor:var(--editorFreeText-editing-cursor); -} - -.annotationEditorLayer.inkEditing{ - cursor:var(--editorInk-editing-cursor); -} - -.annotationEditorLayer .draw{ - box-sizing:border-box; -} - -.annotationEditorLayer :is(.freeTextEditor, .inkEditor, .stampEditor){ - position:absolute; - background:transparent; - z-index:1; - transform-origin:0 0; - cursor:auto; - max-width:100%; - max-height:100%; - border:var(--unfocus-outline); -} - -.draggable.selectedEditor:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)){ - cursor:move; - } - -.selectedEditor:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)){ - border:var(--focus-outline); - outline:var(--focus-outline-around); - } - -.selectedEditor:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor))::before{ - content:""; - position:absolute; - inset:0; - border:var(--focus-outline-around); - pointer-events:none; - } - -:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)):hover:not(.selectedEditor){ - border:var(--hover-outline); - outline:var(--hover-outline-around); - } - -:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)):hover:not(.selectedEditor)::before{ - content:""; - position:absolute; - inset:0; - border:var(--focus-outline-around); - } - -:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar{ - --editor-toolbar-delete-image:url(images/editor-toolbar-delete.svg); - --editor-toolbar-bg-color:#f0f0f4; - --editor-toolbar-highlight-image:url(images/toolbarButton-editorHighlight.svg); - --editor-toolbar-fg-color:#2e2e56; - --editor-toolbar-border-color:#8f8f9d; - --editor-toolbar-hover-border-color:var(--editor-toolbar-border-color); - --editor-toolbar-hover-bg-color:#e0e0e6; - --editor-toolbar-hover-fg-color:var(--editor-toolbar-fg-color); - --editor-toolbar-hover-outline:none; - --editor-toolbar-focus-outline-color:#0060df; - --editor-toolbar-shadow:0 2px 6px 0 rgb(58 57 68 / 0.2); - --editor-toolbar-vert-offset:6px; - --editor-toolbar-height:28px; - --editor-toolbar-padding:2px; - --alt-text-done-color:#2ac3a2; - --alt-text-warning-color:#0090ed; - --alt-text-hover-done-color:var(--alt-text-done-color); - --alt-text-hover-warning-color:var(--alt-text-warning-color); - } - -@media (prefers-color-scheme: dark){ - -:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar{ - --editor-toolbar-bg-color:#2b2a33; - --editor-toolbar-fg-color:#fbfbfe; - --editor-toolbar-hover-bg-color:#52525e; - --editor-toolbar-focus-outline-color:#0df; - --alt-text-done-color:#54ffbd; - --alt-text-warning-color:#80ebff; - } - } - -@media screen and (forced-colors: active){ - -:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar{ - --editor-toolbar-bg-color:ButtonFace; - --editor-toolbar-fg-color:ButtonText; - --editor-toolbar-border-color:ButtonText; - --editor-toolbar-hover-border-color:AccentColor; - --editor-toolbar-hover-bg-color:ButtonFace; - --editor-toolbar-hover-fg-color:AccentColor; - --editor-toolbar-hover-outline:2px solid var(--editor-toolbar-hover-border-color); - --editor-toolbar-focus-outline-color:ButtonBorder; - --editor-toolbar-shadow:none; - --alt-text-done-color:var(--editor-toolbar-fg-color); - --alt-text-warning-color:var(--editor-toolbar-fg-color); - --alt-text-hover-done-color:var(--editor-toolbar-hover-fg-color); - --alt-text-hover-warning-color:var(--editor-toolbar-hover-fg-color); - } - } - -:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar{ - - display:flex; - width:-moz-fit-content; - width:fit-content; - height:var(--editor-toolbar-height); - flex-direction:column; - justify-content:center; - align-items:center; - cursor:default; - pointer-events:auto; - box-sizing:content-box; - padding:var(--editor-toolbar-padding); - - position:absolute; - inset-inline-end:0; - inset-block-start:calc(100% + var(--editor-toolbar-vert-offset)); - - border-radius:6px; - background-color:var(--editor-toolbar-bg-color); - border:1px solid var(--editor-toolbar-border-color); - box-shadow:var(--editor-toolbar-shadow); - } - -.hidden:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar){ - display:none; - } - -:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar):has(:focus-visible){ - border-color:transparent; - } - -[dir="ltr"] :is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar){ - transform-origin:100% 0; - } - -[dir="rtl"] :is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar){ - transform-origin:0 0; - } - -:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons{ - display:flex; - justify-content:center; - align-items:center; - gap:0; - height:100%; - } - -:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) button{ - padding:0; - } - -:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .divider{ - width:0; - height:calc( - 2 * var(--editor-toolbar-padding) + var(--editor-toolbar-height) - ); - border-left:1px solid var(--editor-toolbar-border-color); - border-right:none; - display:inline-block; - margin-inline:2px; - } - -:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .highlightButton{ - width:var(--editor-toolbar-height); - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .highlightButton)::before{ - content:""; - -webkit-mask-image:var(--editor-toolbar-highlight-image); - mask-image:var(--editor-toolbar-highlight-image); - -webkit-mask-repeat:no-repeat; - mask-repeat:no-repeat; - -webkit-mask-position:center; - mask-position:center; - display:inline-block; - background-color:var(--editor-toolbar-fg-color); - width:100%; - height:100%; - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .highlightButton):hover::before{ - background-color:var(--editor-toolbar-hover-fg-color); - } - -:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .delete{ - width:var(--editor-toolbar-height); - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .delete)::before{ - content:""; - -webkit-mask-image:var(--editor-toolbar-delete-image); - mask-image:var(--editor-toolbar-delete-image); - -webkit-mask-repeat:no-repeat; - mask-repeat:no-repeat; - -webkit-mask-position:center; - mask-position:center; - display:inline-block; - background-color:var(--editor-toolbar-fg-color); - width:100%; - height:100%; - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .delete):hover::before{ - background-color:var(--editor-toolbar-hover-fg-color); - } - -:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) > *{ - height:var(--editor-toolbar-height); - } - -:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) > :not(.divider){ - border:none; - background-color:transparent; - cursor:pointer; - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) > :not(.divider)):hover{ - border-radius:2px; - background-color:var(--editor-toolbar-hover-bg-color); - color:var(--editor-toolbar-hover-fg-color); - outline:var(--editor-toolbar-hover-outline); - outline-offset:1px; - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) > :not(.divider)):hover:active{ - outline:none; - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) > :not(.divider)):focus-visible{ - border-radius:2px; - outline:2px solid var(--editor-toolbar-focus-outline-color); - } - -:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText{ - --alt-text-add-image:url(images/altText_add.svg); - --alt-text-done-image:url(images/altText_done.svg); - - display:flex; - align-items:center; - justify-content:center; - width:-moz-max-content; - width:max-content; - padding-inline:8px; - pointer-events:all; - font:menu; - font-weight:590; - font-size:12px; - color:var(--editor-toolbar-fg-color); - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText):disabled{ - pointer-events:none; - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText)::before{ - content:""; - -webkit-mask-image:var(--alt-text-add-image); - mask-image:var(--alt-text-add-image); - -webkit-mask-repeat:no-repeat; - mask-repeat:no-repeat; - -webkit-mask-position:center; - mask-position:center; - display:inline-block; - width:12px; - height:13px; - background-color:var(--editor-toolbar-fg-color); - margin-inline-end:4px; - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText):hover::before{ - background-color:var(--editor-toolbar-hover-fg-color); - } - -.done:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText)::before{ - -webkit-mask-image:var(--alt-text-done-image); - mask-image:var(--alt-text-done-image); - } - -.new:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText)::before{ - width:16px; - height:16px; - -webkit-mask-image:var(--new-alt-text-warning-image); - mask-image:var(--new-alt-text-warning-image); - background-color:var(--alt-text-warning-color); - -webkit-mask-size:cover; - mask-size:cover; - } - -.new:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText):hover::before{ - background-color:var(--alt-text-hover-warning-color); - } - -.new.done:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText)::before{ - -webkit-mask-image:var(--alt-text-done-image); - mask-image:var(--alt-text-done-image); - background-color:var(--alt-text-done-color); - } - -.new.done:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText):hover::before{ - background-color:var(--alt-text-hover-done-color); - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText) .tooltip{ - display:none; - word-wrap:anywhere; - } - -.show:is(:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText) .tooltip){ - --alt-text-tooltip-bg:#f0f0f4; - --alt-text-tooltip-fg:#15141a; - --alt-text-tooltip-border:#8f8f9d; - --alt-text-tooltip-shadow:0px 2px 6px 0px rgb(58 57 68 / 0.2); - } - -@media (prefers-color-scheme: dark){ - -.show:is(:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText) .tooltip){ - --alt-text-tooltip-bg:#1c1b22; - --alt-text-tooltip-fg:#fbfbfe; - --alt-text-tooltip-shadow:0px 2px 6px 0px #15141a; - } - } - -@media screen and (forced-colors: active){ - -.show:is(:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText) .tooltip){ - --alt-text-tooltip-bg:Canvas; - --alt-text-tooltip-fg:CanvasText; - --alt-text-tooltip-border:CanvasText; - --alt-text-tooltip-shadow:none; - } - } - -.show:is(:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText) .tooltip){ - - display:inline-flex; - flex-direction:column; - align-items:center; - justify-content:center; - position:absolute; - top:calc(100% + 2px); - inset-inline-start:0; - padding-block:2px 3px; - padding-inline:3px; - max-width:300px; - width:-moz-max-content; - width:max-content; - height:auto; - font-size:12px; - - border:0.5px solid var(--alt-text-tooltip-border); - background:var(--alt-text-tooltip-bg); - box-shadow:var(--alt-text-tooltip-shadow); - color:var(--alt-text-tooltip-fg); - - pointer-events:none; - } - -.annotationEditorLayer .freeTextEditor{ - padding:calc(var(--freetext-padding) * var(--scale-factor)); - width:auto; - height:auto; - touch-action:none; -} - -.annotationEditorLayer .freeTextEditor .internal{ - background:transparent; - border:none; - inset:0; - overflow:visible; - white-space:nowrap; - font:10px sans-serif; - line-height:var(--freetext-line-height); - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; -} - -.annotationEditorLayer .freeTextEditor .overlay{ - position:absolute; - display:none; - background:transparent; - inset:0; - width:100%; - height:100%; -} - -.annotationEditorLayer freeTextEditor .overlay.enabled{ - display:block; -} - -.annotationEditorLayer .freeTextEditor .internal:empty::before{ - content:attr(default-content); - color:gray; -} - -.annotationEditorLayer .freeTextEditor .internal:focus{ - outline:none; - -webkit-user-select:auto; - -moz-user-select:auto; - user-select:auto; -} - -.annotationEditorLayer .inkEditor{ - width:100%; - height:100%; -} - -.annotationEditorLayer .inkEditor.editing{ - cursor:inherit; -} - -.annotationEditorLayer .inkEditor .inkEditorCanvas{ - position:absolute; - inset:0; - width:100%; - height:100%; - touch-action:none; -} - -.annotationEditorLayer .stampEditor{ - width:auto; - height:auto; -} - -:is(.annotationEditorLayer .stampEditor) canvas{ - position:absolute; - width:100%; - height:100%; - margin:0; - top:0; - left:0; - } - -:is(.annotationEditorLayer .stampEditor) .noAltTextBadge{ - --no-alt-text-badge-border-color:#f0f0f4; - --no-alt-text-badge-bg-color:#cfcfd8; - --no-alt-text-badge-fg-color:#5b5b66; - } - -@media (prefers-color-scheme: dark){ - -:is(.annotationEditorLayer .stampEditor) .noAltTextBadge{ - --no-alt-text-badge-border-color:#52525e; - --no-alt-text-badge-bg-color:#fbfbfe; - --no-alt-text-badge-fg-color:#15141a; - } - } - -@media screen and (forced-colors: active){ - -:is(.annotationEditorLayer .stampEditor) .noAltTextBadge{ - --no-alt-text-badge-border-color:ButtonText; - --no-alt-text-badge-bg-color:ButtonFace; - --no-alt-text-badge-fg-color:ButtonText; - } - } - -:is(.annotationEditorLayer .stampEditor) .noAltTextBadge{ - - position:absolute; - inset-inline-end:5px; - inset-block-end:5px; - display:inline-flex; - width:32px; - height:32px; - padding:3px; - justify-content:center; - align-items:center; - pointer-events:none; - z-index:1; - - border-radius:2px; - border:1px solid var(--no-alt-text-badge-border-color); - background:var(--no-alt-text-badge-bg-color); - } - -:is(:is(.annotationEditorLayer .stampEditor) .noAltTextBadge)::before{ - content:""; - display:inline-block; - width:16px; - height:16px; - -webkit-mask-image:var(--new-alt-text-warning-image); - mask-image:var(--new-alt-text-warning-image); - -webkit-mask-size:cover; - mask-size:cover; - background-color:var(--no-alt-text-badge-fg-color); - } - -:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers{ - position:absolute; - inset:0; - } - -.hidden:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers){ - display:none; - } - -:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer{ - width:var(--resizer-size); - height:var(--resizer-size); - background:content-box var(--resizer-bg-color); - border:var(--focus-outline-around); - border-radius:2px; - position:absolute; - } - -.topLeft:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer){ - top:var(--resizer-shift); - left:var(--resizer-shift); - } - -.topMiddle:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer){ - top:var(--resizer-shift); - left:calc(50% + var(--resizer-shift)); - } - -.topRight:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer){ - top:var(--resizer-shift); - right:var(--resizer-shift); - } - -.middleRight:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer){ - top:calc(50% + var(--resizer-shift)); - right:var(--resizer-shift); - } - -.bottomRight:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer){ - bottom:var(--resizer-shift); - right:var(--resizer-shift); - } - -.bottomMiddle:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer){ - bottom:var(--resizer-shift); - left:calc(50% + var(--resizer-shift)); - } - -.bottomLeft:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer){ - bottom:var(--resizer-shift); - left:var(--resizer-shift); - } - -.middleLeft:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer){ - top:calc(50% + var(--resizer-shift)); - left:var(--resizer-shift); - } - -.topLeft:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="180"],[data-editor-rotation="0"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="90"],[data-editor-rotation="270"])) > .resizers > .resizer),.bottomRight:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="180"],[data-editor-rotation="0"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="90"],[data-editor-rotation="270"])) > .resizers > .resizer){ - cursor:nwse-resize; - } - -.topMiddle:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="180"],[data-editor-rotation="0"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="90"],[data-editor-rotation="270"])) > .resizers > .resizer),.bottomMiddle:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="180"],[data-editor-rotation="0"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="90"],[data-editor-rotation="270"])) > .resizers > .resizer){ - cursor:ns-resize; - } - -.topRight:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="180"],[data-editor-rotation="0"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="90"],[data-editor-rotation="270"])) > .resizers > .resizer),.bottomLeft:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="180"],[data-editor-rotation="0"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="90"],[data-editor-rotation="270"])) > .resizers > .resizer){ - cursor:nesw-resize; - } - -.middleRight:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="180"],[data-editor-rotation="0"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="90"],[data-editor-rotation="270"])) > .resizers > .resizer),.middleLeft:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="180"],[data-editor-rotation="0"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="90"],[data-editor-rotation="270"])) > .resizers > .resizer){ - cursor:ew-resize; - } - -.topLeft:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="90"],[data-editor-rotation="270"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="180"],[data-editor-rotation="0"])) > .resizers > .resizer),.bottomRight:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="90"],[data-editor-rotation="270"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="180"],[data-editor-rotation="0"])) > .resizers > .resizer){ - cursor:nesw-resize; - } - -.topMiddle:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="90"],[data-editor-rotation="270"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="180"],[data-editor-rotation="0"])) > .resizers > .resizer),.bottomMiddle:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="90"],[data-editor-rotation="270"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="180"],[data-editor-rotation="0"])) > .resizers > .resizer){ - cursor:ew-resize; - } - -.topRight:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="90"],[data-editor-rotation="270"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="180"],[data-editor-rotation="0"])) > .resizers > .resizer),.bottomLeft:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="90"],[data-editor-rotation="270"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="180"],[data-editor-rotation="0"])) > .resizers > .resizer){ - cursor:nwse-resize; - } - -.middleRight:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="90"],[data-editor-rotation="270"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="180"],[data-editor-rotation="0"])) > .resizers > .resizer),.middleLeft:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="90"],[data-editor-rotation="270"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="180"],[data-editor-rotation="0"])) > .resizers > .resizer){ - cursor:ns-resize; - } - -:is(.annotationEditorLayer :is([data-main-rotation="0"] [data-editor-rotation="90"],[data-main-rotation="90"] [data-editor-rotation="0"],[data-main-rotation="180"] [data-editor-rotation="270"],[data-main-rotation="270"] [data-editor-rotation="180"])) .editToolbar{ - rotate:270deg; - } - -[dir="ltr"] :is(:is(.annotationEditorLayer :is([data-main-rotation="0"] [data-editor-rotation="90"],[data-main-rotation="90"] [data-editor-rotation="0"],[data-main-rotation="180"] [data-editor-rotation="270"],[data-main-rotation="270"] [data-editor-rotation="180"])) .editToolbar){ - inset-inline-end:calc(0px - var(--editor-toolbar-vert-offset)); - inset-block-start:0; - } - -[dir="rtl"] :is(:is(.annotationEditorLayer :is([data-main-rotation="0"] [data-editor-rotation="90"],[data-main-rotation="90"] [data-editor-rotation="0"],[data-main-rotation="180"] [data-editor-rotation="270"],[data-main-rotation="270"] [data-editor-rotation="180"])) .editToolbar){ - inset-inline-end:calc(100% + var(--editor-toolbar-vert-offset)); - inset-block-start:0; - } - -:is(.annotationEditorLayer :is([data-main-rotation="0"] [data-editor-rotation="180"],[data-main-rotation="90"] [data-editor-rotation="90"],[data-main-rotation="180"] [data-editor-rotation="0"],[data-main-rotation="270"] [data-editor-rotation="270"])) .editToolbar{ - rotate:180deg; - inset-inline-end:100%; - inset-block-start:calc(0pc - var(--editor-toolbar-vert-offset)); - } - -:is(.annotationEditorLayer :is([data-main-rotation="0"] [data-editor-rotation="270"],[data-main-rotation="90"] [data-editor-rotation="180"],[data-main-rotation="180"] [data-editor-rotation="90"],[data-main-rotation="270"] [data-editor-rotation="0"])) .editToolbar{ - rotate:90deg; - } - -[dir="ltr"] :is(:is(.annotationEditorLayer :is([data-main-rotation="0"] [data-editor-rotation="270"],[data-main-rotation="90"] [data-editor-rotation="180"],[data-main-rotation="180"] [data-editor-rotation="90"],[data-main-rotation="270"] [data-editor-rotation="0"])) .editToolbar){ - inset-inline-end:calc(100% + var(--editor-toolbar-vert-offset)); - inset-block-start:100%; - } - -[dir="rtl"] :is(:is(.annotationEditorLayer :is([data-main-rotation="0"] [data-editor-rotation="270"],[data-main-rotation="90"] [data-editor-rotation="180"],[data-main-rotation="180"] [data-editor-rotation="90"],[data-main-rotation="270"] [data-editor-rotation="0"])) .editToolbar){ - inset-inline-start:calc(0px - var(--editor-toolbar-vert-offset)); - inset-block-start:0; - } - -.dialog.altText::backdrop{ - -webkit-mask:url(#alttext-manager-mask); - mask:url(#alttext-manager-mask); - } - -.dialog.altText.positioned{ - margin:0; - } - -.dialog.altText #altTextContainer{ - width:300px; - height:-moz-fit-content; - height:fit-content; - display:inline-flex; - flex-direction:column; - align-items:flex-start; - gap:16px; - } - -:is(.dialog.altText #altTextContainer) #overallDescription{ - display:flex; - flex-direction:column; - align-items:flex-start; - gap:4px; - align-self:stretch; - } - -:is(:is(.dialog.altText #altTextContainer) #overallDescription) span{ - align-self:stretch; - } - -:is(:is(.dialog.altText #altTextContainer) #overallDescription) .title{ - font-size:13px; - font-style:normal; - font-weight:590; - } - -:is(.dialog.altText #altTextContainer) #addDescription{ - display:flex; - flex-direction:column; - align-items:stretch; - gap:8px; - } - -:is(:is(.dialog.altText #altTextContainer) #addDescription) .descriptionArea{ - flex:1; - padding-inline:24px 10px; - } - -:is(:is(:is(.dialog.altText #altTextContainer) #addDescription) .descriptionArea) textarea{ - width:100%; - min-height:75px; - } - -:is(.dialog.altText #altTextContainer) #buttons{ - display:flex; - justify-content:flex-end; - align-items:flex-start; - gap:8px; - align-self:stretch; - } - -.dialog.newAltText{ - --new-alt-text-ai-disclaimer-icon:url(images/altText_disclaimer.svg); - --new-alt-text-spinner-icon:url(images/altText_spinner.svg); - --preview-image-bg-color:#f0f0f4; - --preview-image-border:none; -} - -@media (prefers-color-scheme: dark){ - -.dialog.newAltText{ - --preview-image-bg-color:#2b2a33; -} - } - -@media screen and (forced-colors: active){ - -.dialog.newAltText{ - --preview-image-bg-color:ButtonFace; - --preview-image-border:1px solid ButtonText; -} - } - -.dialog.newAltText{ - - width:80%; - max-width:570px; - min-width:300px; - padding:0; -} - -.dialog.newAltText.noAi #newAltTextDisclaimer,.dialog.newAltText.noAi #newAltTextCreateAutomatically{ - display:none !important; - } - -.dialog.newAltText.aiInstalling #newAltTextCreateAutomatically{ - display:none !important; - } - -.dialog.newAltText.aiInstalling #newAltTextDownloadModel{ - display:flex !important; - } - -.dialog.newAltText.error #newAltTextNotNow{ - display:none !important; - } - -.dialog.newAltText.error #newAltTextCancel{ - display:inline-block !important; - } - -.dialog.newAltText:not(.error) #newAltTextError{ - display:none !important; - } - -.dialog.newAltText #newAltTextContainer{ - display:flex; - width:auto; - padding:16px; - flex-direction:column; - justify-content:flex-end; - align-items:flex-start; - gap:12px; - flex:0 1 auto; - line-height:normal; - } - -:is(.dialog.newAltText #newAltTextContainer) #mainContent{ - display:flex; - justify-content:flex-end; - align-items:flex-start; - gap:12px; - align-self:stretch; - flex:1 1 auto; - } - -:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionAndSettings{ - display:flex; - flex-direction:column; - align-items:flex-start; - gap:16px; - flex:1 0 0; - align-self:stretch; - } - -:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction{ - display:flex; - flex-direction:column; - align-items:flex-start; - gap:8px; - align-self:stretch; - flex:1 1 auto; - } - -:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescriptionContainer{ - width:100%; - height:70px; - position:relative; - } - -:is(:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescriptionContainer) textarea{ - width:100%; - height:100%; - padding:8px; - } - -:is(:is(:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescriptionContainer) textarea)::-moz-placeholder{ - color:var(--text-secondary-color); - } - -:is(:is(:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescriptionContainer) textarea)::placeholder{ - color:var(--text-secondary-color); - } - -:is(:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescriptionContainer) .altTextSpinner{ - display:none; - position:absolute; - width:16px; - height:16px; - inset-inline-start:8px; - inset-block-start:8px; - -webkit-mask-size:cover; - mask-size:cover; - background-color:var(--text-secondary-color); - pointer-events:none; - } - -.loading:is(:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescriptionContainer) textarea::-moz-placeholder{ - color:transparent; - } - -.loading:is(:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescriptionContainer) textarea::placeholder{ - color:transparent; - } - -.loading:is(:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescriptionContainer) .altTextSpinner{ - display:inline-block; - -webkit-mask-image:var(--new-alt-text-spinner-icon); - mask-image:var(--new-alt-text-spinner-icon); - } - -:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescription{ - font-size:11px; - } - -:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDisclaimer{ - display:flex; - flex-direction:row; - align-items:flex-start; - gap:4px; - font-size:11px; - } - -:is(:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDisclaimer)::before{ - content:""; - display:inline-block; - width:17px; - height:16px; - -webkit-mask-image:var(--new-alt-text-ai-disclaimer-icon); - mask-image:var(--new-alt-text-ai-disclaimer-icon); - -webkit-mask-size:cover; - mask-size:cover; - background-color:var(--text-secondary-color); - flex:1 0 auto; - } - -:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #newAltTextDownloadModel{ - display:flex; - align-items:center; - gap:4px; - align-self:stretch; - } - -:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #newAltTextDownloadModel)::before{ - content:""; - display:inline-block; - width:16px; - height:16px; - -webkit-mask-image:var(--new-alt-text-spinner-icon); - mask-image:var(--new-alt-text-spinner-icon); - -webkit-mask-size:cover; - mask-size:cover; - background-color:var(--text-secondary-color); - } - -:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #newAltTextImagePreview{ - width:180px; - aspect-ratio:1; - display:flex; - justify-content:center; - align-items:center; - flex:0 0 auto; - background-color:var(--preview-image-bg-color); - border:var(--preview-image-border); - } - -:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #newAltTextImagePreview) > canvas{ - max-width:100%; - max-height:100%; - } - -.colorPicker{ - --hover-outline-color:#0250bb; - --selected-outline-color:#0060df; - --swatch-border-color:#cfcfd8; -} - -@media (prefers-color-scheme: dark){ - -.colorPicker{ - --hover-outline-color:#80ebff; - --selected-outline-color:#aaf2ff; - --swatch-border-color:#52525e; -} - } - -@media screen and (forced-colors: active){ - -.colorPicker{ - --hover-outline-color:Highlight; - --selected-outline-color:var(--hover-outline-color); - --swatch-border-color:ButtonText; -} - } - -.colorPicker .swatch{ - width:16px; - height:16px; - border:1px solid var(--swatch-border-color); - border-radius:100%; - outline-offset:2px; - box-sizing:border-box; - forced-color-adjust:none; - } - -.colorPicker button:is(:hover,.selected) > .swatch{ - border:none; - } - -.annotationEditorLayer[data-main-rotation="0"] .highlightEditor:not(.free) > .editToolbar{ - rotate:0deg; - } - -.annotationEditorLayer[data-main-rotation="90"] .highlightEditor:not(.free) > .editToolbar{ - rotate:270deg; - } - -.annotationEditorLayer[data-main-rotation="180"] .highlightEditor:not(.free) > .editToolbar{ - rotate:180deg; - } - -.annotationEditorLayer[data-main-rotation="270"] .highlightEditor:not(.free) > .editToolbar{ - rotate:90deg; - } - -.annotationEditorLayer .highlightEditor{ - position:absolute; - background:transparent; - z-index:1; - cursor:auto; - max-width:100%; - max-height:100%; - border:none; - outline:none; - pointer-events:none; - transform-origin:0 0; - } - -:is(.annotationEditorLayer .highlightEditor):not(.free){ - transform:none; - } - -:is(.annotationEditorLayer .highlightEditor) .internal{ - position:absolute; - top:0; - left:0; - width:100%; - height:100%; - pointer-events:auto; - } - -.disabled:is(.annotationEditorLayer .highlightEditor) .internal{ - pointer-events:none; - } - -.selectedEditor:is(.annotationEditorLayer .highlightEditor) .internal{ - cursor:pointer; - } - -:is(.annotationEditorLayer .highlightEditor) .editToolbar{ - --editor-toolbar-colorpicker-arrow-image:url(images/toolbarButton-menuArrow.svg); - - transform-origin:center !important; - } - -:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker{ - position:relative; - width:auto; - display:flex; - justify-content:center; - align-items:center; - gap:4px; - padding:4px; - } - -:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker)::after{ - content:""; - -webkit-mask-image:var(--editor-toolbar-colorpicker-arrow-image); - mask-image:var(--editor-toolbar-colorpicker-arrow-image); - -webkit-mask-repeat:no-repeat; - mask-repeat:no-repeat; - -webkit-mask-position:center; - mask-position:center; - display:inline-block; - background-color:var(--editor-toolbar-fg-color); - width:12px; - height:12px; - } - -:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker):hover::after{ - background-color:var(--editor-toolbar-hover-fg-color); - } - -:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker):has(.dropdown:not(.hidden)){ - background-color:var(--editor-toolbar-hover-bg-color); - } - -:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker):has(.dropdown:not(.hidden))::after{ - scale:-1; - } - -:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker) .dropdown{ - position:absolute; - display:flex; - justify-content:center; - align-items:center; - flex-direction:column; - gap:11px; - padding-block:8px; - border-radius:6px; - background-color:var(--editor-toolbar-bg-color); - border:1px solid var(--editor-toolbar-border-color); - box-shadow:var(--editor-toolbar-shadow); - inset-block-start:calc(100% + 4px); - width:calc(100% + 2 * var(--editor-toolbar-padding)); - } - -:is(:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker) .dropdown) button{ - width:100%; - height:auto; - border:none; - cursor:pointer; - display:flex; - justify-content:center; - align-items:center; - background:none; - } - -:is(:is(:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker) .dropdown) button):is(:active,:focus-visible){ - outline:none; - } - -:is(:is(:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker) .dropdown) button) > .swatch{ - outline-offset:2px; - } - -[aria-selected="true"]:is(:is(:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker) .dropdown) button) > .swatch{ - outline:2px solid var(--selected-outline-color); - } - -:is(:is(:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker) .dropdown) button):is(:hover,:active,:focus-visible) > .swatch{ - outline:2px solid var(--hover-outline-color); - } - -.editorParamsToolbar:has(#highlightParamsToolbarContainer){ - padding:unset; -} - -#highlightParamsToolbarContainer{ - gap:16px; - padding-inline:10px; - padding-block-end:12px; -} - -#highlightParamsToolbarContainer .colorPicker{ - display:flex; - flex-direction:column; - gap:8px; - } - -:is(#highlightParamsToolbarContainer .colorPicker) .dropdown{ - display:flex; - justify-content:space-between; - align-items:center; - flex-direction:row; - height:auto; - } - -:is(:is(#highlightParamsToolbarContainer .colorPicker) .dropdown) button{ - width:auto; - height:auto; - border:none; - cursor:pointer; - display:flex; - justify-content:center; - align-items:center; - background:none; - flex:0 0 auto; - padding:0; - } - -:is(:is(:is(#highlightParamsToolbarContainer .colorPicker) .dropdown) button) .swatch{ - width:24px; - height:24px; - } - -:is(:is(:is(#highlightParamsToolbarContainer .colorPicker) .dropdown) button):is(:active,:focus-visible){ - outline:none; - } - -[aria-selected="true"]:is(:is(:is(#highlightParamsToolbarContainer .colorPicker) .dropdown) button) > .swatch{ - outline:2px solid var(--selected-outline-color); - } - -:is(:is(:is(#highlightParamsToolbarContainer .colorPicker) .dropdown) button):is(:hover,:active,:focus-visible) > .swatch{ - outline:2px solid var(--hover-outline-color); - } - -#highlightParamsToolbarContainer #editorHighlightThickness{ - display:flex; - flex-direction:column; - align-items:center; - gap:4px; - align-self:stretch; - } - -:is(#highlightParamsToolbarContainer #editorHighlightThickness) .editorParamsLabel{ - height:auto; - align-self:stretch; - } - -:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker{ - display:flex; - justify-content:space-between; - align-items:center; - align-self:stretch; - - --example-color:#bfbfc9; - } - -@media (prefers-color-scheme: dark){ - -:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker{ - --example-color:#80808e; - } - } - -@media screen and (forced-colors: active){ - -:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker{ - --example-color:CanvasText; - } - } - -:is(:is(:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker) > .editorParamsSlider[disabled]){ - opacity:0.4; - } - -:is(:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker)::before,:is(:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker)::after{ - content:""; - width:8px; - aspect-ratio:1; - display:block; - border-radius:100%; - background-color:var(--example-color); - } - -:is(:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker)::after{ - width:24px; - } - -:is(:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker) .editorParamsSlider{ - width:unset; - height:14px; - } - -#highlightParamsToolbarContainer #editorHighlightVisibility{ - display:flex; - flex-direction:column; - align-items:flex-start; - gap:8px; - align-self:stretch; - } - -:is(#highlightParamsToolbarContainer #editorHighlightVisibility) .divider{ - --divider-color:#d7d7db; - } - -@media (prefers-color-scheme: dark){ - -:is(#highlightParamsToolbarContainer #editorHighlightVisibility) .divider{ - --divider-color:#8f8f9d; - } - } - -@media screen and (forced-colors: active){ - -:is(#highlightParamsToolbarContainer #editorHighlightVisibility) .divider{ - --divider-color:CanvasText; - } - } - -:is(#highlightParamsToolbarContainer #editorHighlightVisibility) .divider{ - - margin-block:4px; - width:100%; - height:1px; - background-color:var(--divider-color); - } - -:is(#highlightParamsToolbarContainer #editorHighlightVisibility) .toggler{ - display:flex; - justify-content:space-between; - align-items:center; - align-self:stretch; - } - -#altTextSettingsDialog{ - padding:16px; -} - -#altTextSettingsDialog #altTextSettingsContainer{ - display:flex; - width:573px; - flex-direction:column; - gap:16px; - } - -:is(#altTextSettingsDialog #altTextSettingsContainer) .mainContainer{ - gap:16px; - } - -:is(#altTextSettingsDialog #altTextSettingsContainer) .description{ - color:var(--text-secondary-color); - } - -:is(#altTextSettingsDialog #altTextSettingsContainer) #aiModelSettings{ - display:flex; - flex-direction:column; - gap:12px; - } - -:is(:is(#altTextSettingsDialog #altTextSettingsContainer) #aiModelSettings) button{ - width:-moz-fit-content; - width:fit-content; - } - -.download:is(:is(#altTextSettingsDialog #altTextSettingsContainer) #aiModelSettings) #deleteModelButton{ - display:none; - } - -:is(:is(#altTextSettingsDialog #altTextSettingsContainer) #aiModelSettings):not(.download) #downloadModelButton{ - display:none; - } - -:is(#altTextSettingsDialog #altTextSettingsContainer) #automaticAltText,:is(#altTextSettingsDialog #altTextSettingsContainer) #altTextEditor{ - display:flex; - flex-direction:column; - gap:8px; - } - -:is(#altTextSettingsDialog #altTextSettingsContainer) #createModelDescription,:is(#altTextSettingsDialog #altTextSettingsContainer) #aiModelSettings,:is(#altTextSettingsDialog #altTextSettingsContainer) #showAltTextDialogDescription{ - padding-inline-start:40px; - } - -:is(#altTextSettingsDialog #altTextSettingsContainer) #automaticSettings{ - display:flex; - flex-direction:column; - gap:16px; - } - -:root{ - --viewer-container-height:0; - --pdfViewer-padding-bottom:0; - --page-margin:1px auto -8px; - --page-border:9px solid transparent; - --spreadHorizontalWrapped-margin-LR:-3.5px; - --loading-icon-delay:400ms; -} - -@media screen and (forced-colors: active){ - :root{ - --pdfViewer-padding-bottom:9px; - --page-margin:8px auto -1px; - --page-border:1px solid CanvasText; - --spreadHorizontalWrapped-margin-LR:3.5px; - } -} - -[data-main-rotation="90"]{ - transform:rotate(90deg) translateY(-100%); -} -[data-main-rotation="180"]{ - transform:rotate(180deg) translate(-100%, -100%); -} -[data-main-rotation="270"]{ - transform:rotate(270deg) translateX(-100%); -} - -#hiddenCopyElement, -.hiddenCanvasElement{ - position:absolute; - top:0; - left:0; - width:0; - height:0; - display:none; -} - -.pdfViewer{ - --scale-factor:1; - --page-bg-color:unset; - - padding-bottom:var(--pdfViewer-padding-bottom); - - --hcm-highlight-filter:none; - --hcm-highlight-selected-filter:none; -} - -@media screen and (forced-colors: active){ - -.pdfViewer{ - --hcm-highlight-filter:invert(100%); -} - } - -.pdfViewer.copyAll{ - cursor:wait; - } - -.pdfViewer .canvasWrapper{ - overflow:hidden; - width:100%; - height:100%; - } - -:is(.pdfViewer .canvasWrapper) canvas{ - position:absolute; - top:0; - left:0; - margin:0; - display:block; - width:100%; - height:100%; - contain:content; - } - -:is(:is(.pdfViewer .canvasWrapper) canvas) .structTree{ - contain:strict; - } - -.pdfViewer .page{ - --scale-round-x:1px; - --scale-round-y:1px; - - direction:ltr; - width:816px; - height:1056px; - margin:var(--page-margin); - position:relative; - overflow:visible; - border:var(--page-border); - background-clip:content-box; - background-color:var(--page-bg-color, rgb(255 255 255)); -} - -.pdfViewer .dummyPage{ - position:relative; - width:0; - height:var(--viewer-container-height); -} - -.pdfViewer.noUserSelect{ - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; -} - -.pdfViewer.removePageBorders .page{ - margin:0 auto 10px; - border:none; -} - -.pdfViewer.singlePageView{ - display:inline-block; -} - -.pdfViewer.singlePageView .page{ - margin:0; - border:none; -} - -.pdfViewer:is(.scrollHorizontal, .scrollWrapped), -.spread{ - margin-inline:3.5px; - text-align:center; -} - -.pdfViewer.scrollHorizontal, -.spread{ - white-space:nowrap; -} - -.pdfViewer.removePageBorders, -.pdfViewer:is(.scrollHorizontal, .scrollWrapped) .spread{ - margin-inline:0; -} - -.spread :is(.page, .dummyPage), -.pdfViewer:is(.scrollHorizontal, .scrollWrapped) :is(.page, .spread){ - display:inline-block; - vertical-align:middle; -} - -.spread .page, -.pdfViewer:is(.scrollHorizontal, .scrollWrapped) .page{ - margin-inline:var(--spreadHorizontalWrapped-margin-LR); -} - -.pdfViewer.removePageBorders .spread .page, -.pdfViewer.removePageBorders:is(.scrollHorizontal, .scrollWrapped) .page{ - margin-inline:5px; -} - -.pdfViewer .page.loadingIcon::after{ - position:absolute; - top:0; - left:0; - content:""; - width:100%; - height:100%; - background:url("images/loading-icon.gif") center no-repeat; - display:none; - transition-property:display; - transition-delay:var(--loading-icon-delay); - z-index:5; - contain:strict; -} - -.pdfViewer .page.loading::after{ - display:block; -} - -.pdfViewer .page:not(.loading)::after{ - transition-property:none; - display:none; -} - -.pdfPresentationMode .pdfViewer{ - padding-bottom:0; -} - -.pdfPresentationMode .spread{ - margin:0; -} - -.pdfPresentationMode .pdfViewer .page{ - margin:0 auto; - border:2px solid transparent; -} diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.mjs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.mjs deleted file mode 100644 index 9b2c200c99e..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.mjs +++ /dev/null @@ -1,8435 +0,0 @@ -/** - * @licstart The following is the entire license notice for the - * JavaScript code in this page - * - * Copyright 2024 Mozilla Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * @licend The above is the entire license notice for the - * JavaScript code in this page - */ - -/******/ // The require scope -/******/ var __webpack_require__ = {}; -/******/ -/************************************************************************/ -/******/ /* webpack/runtime/define property getters */ -/******/ (() => { -/******/ // define getter functions for harmony exports -/******/ __webpack_require__.d = (exports, definition) => { -/******/ for(var key in definition) { -/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { -/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); -/******/ } -/******/ } -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/hasOwnProperty shorthand */ -/******/ (() => { -/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) -/******/ })(); -/******/ -/************************************************************************/ -var __webpack_exports__ = globalThis.pdfjsViewer = {}; - -// EXPORTS -__webpack_require__.d(__webpack_exports__, { - AnnotationLayerBuilder: () => (/* reexport */ AnnotationLayerBuilder), - DownloadManager: () => (/* reexport */ DownloadManager), - EventBus: () => (/* reexport */ EventBus), - FindState: () => (/* reexport */ FindState), - GenericL10n: () => (/* reexport */ genericl10n_GenericL10n), - LinkTarget: () => (/* reexport */ LinkTarget), - PDFFindController: () => (/* reexport */ PDFFindController), - PDFHistory: () => (/* reexport */ PDFHistory), - PDFLinkService: () => (/* reexport */ PDFLinkService), - PDFPageView: () => (/* reexport */ PDFPageView), - PDFScriptingManager: () => (/* reexport */ PDFScriptingManagerComponents), - PDFSinglePageViewer: () => (/* reexport */ PDFSinglePageViewer), - PDFViewer: () => (/* reexport */ PDFViewer), - ProgressBar: () => (/* reexport */ ProgressBar), - RenderingStates: () => (/* reexport */ RenderingStates), - ScrollMode: () => (/* reexport */ ScrollMode), - SimpleLinkService: () => (/* reexport */ SimpleLinkService), - SpreadMode: () => (/* reexport */ SpreadMode), - StructTreeLayerBuilder: () => (/* reexport */ StructTreeLayerBuilder), - TextLayerBuilder: () => (/* reexport */ TextLayerBuilder), - XfaLayerBuilder: () => (/* reexport */ XfaLayerBuilder), - parseQueryString: () => (/* reexport */ parseQueryString) -}); - -;// ./web/ui_utils.js -const DEFAULT_SCALE_VALUE = "auto"; -const DEFAULT_SCALE = 1.0; -const DEFAULT_SCALE_DELTA = 1.1; -const MIN_SCALE = 0.1; -const MAX_SCALE = 10.0; -const UNKNOWN_SCALE = 0; -const MAX_AUTO_SCALE = 1.25; -const SCROLLBAR_PADDING = 40; -const VERTICAL_PADDING = 5; -const RenderingStates = { - INITIAL: 0, - RUNNING: 1, - PAUSED: 2, - FINISHED: 3 -}; -const PresentationModeState = { - UNKNOWN: 0, - NORMAL: 1, - CHANGING: 2, - FULLSCREEN: 3 -}; -const SidebarView = { - UNKNOWN: -1, - NONE: 0, - THUMBS: 1, - OUTLINE: 2, - ATTACHMENTS: 3, - LAYERS: 4 -}; -const TextLayerMode = { - DISABLE: 0, - ENABLE: 1, - ENABLE_PERMISSIONS: 2 -}; -const ScrollMode = { - UNKNOWN: -1, - VERTICAL: 0, - HORIZONTAL: 1, - WRAPPED: 2, - PAGE: 3 -}; -const SpreadMode = { - UNKNOWN: -1, - NONE: 0, - ODD: 1, - EVEN: 2 -}; -const CursorTool = { - SELECT: 0, - HAND: 1, - ZOOM: 2 -}; -const AutoPrintRegExp = /\bprint\s*\(/; -function scrollIntoView(element, spot, scrollMatches = false) { - let parent = element.offsetParent; - if (!parent) { - console.error("offsetParent is not set -- cannot scroll"); - return; - } - let offsetY = element.offsetTop + element.clientTop; - let offsetX = element.offsetLeft + element.clientLeft; - while (parent.clientHeight === parent.scrollHeight && parent.clientWidth === parent.scrollWidth || scrollMatches && (parent.classList.contains("markedContent") || getComputedStyle(parent).overflow === "hidden")) { - offsetY += parent.offsetTop; - offsetX += parent.offsetLeft; - parent = parent.offsetParent; - if (!parent) { - return; - } - } - if (spot) { - if (spot.top !== undefined) { - offsetY += spot.top; - } - if (spot.left !== undefined) { - offsetX += spot.left; - parent.scrollLeft = offsetX; - } - } - parent.scrollTop = offsetY; -} -function watchScroll(viewAreaElement, callback, abortSignal = undefined) { - const debounceScroll = function (evt) { - if (rAF) { - return; - } - rAF = window.requestAnimationFrame(function viewAreaElementScrolled() { - rAF = null; - const currentX = viewAreaElement.scrollLeft; - const lastX = state.lastX; - if (currentX !== lastX) { - state.right = currentX > lastX; - } - state.lastX = currentX; - const currentY = viewAreaElement.scrollTop; - const lastY = state.lastY; - if (currentY !== lastY) { - state.down = currentY > lastY; - } - state.lastY = currentY; - callback(state); - }); - }; - const state = { - right: true, - down: true, - lastX: viewAreaElement.scrollLeft, - lastY: viewAreaElement.scrollTop, - _eventHandler: debounceScroll - }; - let rAF = null; - viewAreaElement.addEventListener("scroll", debounceScroll, { - useCapture: true, - signal: abortSignal - }); - abortSignal?.addEventListener("abort", () => window.cancelAnimationFrame(rAF), { - once: true - }); - return state; -} -function parseQueryString(query) { - const params = new Map(); - for (const [key, value] of new URLSearchParams(query)) { - params.set(key.toLowerCase(), value); - } - return params; -} -const InvisibleCharsRegExp = /[\x00-\x1F]/g; -function removeNullCharacters(str, replaceInvisible = false) { - if (!InvisibleCharsRegExp.test(str)) { - return str; - } - if (replaceInvisible) { - return str.replaceAll(InvisibleCharsRegExp, m => m === "\x00" ? "" : " "); - } - return str.replaceAll("\x00", ""); -} -function binarySearchFirstItem(items, condition, start = 0) { - let minIndex = start; - let maxIndex = items.length - 1; - if (maxIndex < 0 || !condition(items[maxIndex])) { - return items.length; - } - if (condition(items[minIndex])) { - return minIndex; - } - while (minIndex < maxIndex) { - const currentIndex = minIndex + maxIndex >> 1; - const currentItem = items[currentIndex]; - if (condition(currentItem)) { - maxIndex = currentIndex; - } else { - minIndex = currentIndex + 1; - } - } - return minIndex; -} -function approximateFraction(x) { - if (Math.floor(x) === x) { - return [x, 1]; - } - const xinv = 1 / x; - const limit = 8; - if (xinv > limit) { - return [1, limit]; - } else if (Math.floor(xinv) === xinv) { - return [1, xinv]; - } - const x_ = x > 1 ? xinv : x; - let a = 0, - b = 1, - c = 1, - d = 1; - while (true) { - const p = a + c, - q = b + d; - if (q > limit) { - break; - } - if (x_ <= p / q) { - c = p; - d = q; - } else { - a = p; - b = q; - } - } - let result; - if (x_ - a / b < c / d - x_) { - result = x_ === x ? [a, b] : [b, a]; - } else { - result = x_ === x ? [c, d] : [d, c]; - } - return result; -} -function floorToDivide(x, div) { - return x - x % div; -} -function getPageSizeInches({ - view, - userUnit, - rotate -}) { - const [x1, y1, x2, y2] = view; - const changeOrientation = rotate % 180 !== 0; - const width = (x2 - x1) / 72 * userUnit; - const height = (y2 - y1) / 72 * userUnit; - return { - width: changeOrientation ? height : width, - height: changeOrientation ? width : height - }; -} -function backtrackBeforeAllVisibleElements(index, views, top) { - if (index < 2) { - return index; - } - let elt = views[index].div; - let pageTop = elt.offsetTop + elt.clientTop; - if (pageTop >= top) { - elt = views[index - 1].div; - pageTop = elt.offsetTop + elt.clientTop; - } - for (let i = index - 2; i >= 0; --i) { - elt = views[i].div; - if (elt.offsetTop + elt.clientTop + elt.clientHeight <= pageTop) { - break; - } - index = i; - } - return index; -} -function getVisibleElements({ - scrollEl, - views, - sortByVisibility = false, - horizontal = false, - rtl = false -}) { - const top = scrollEl.scrollTop, - bottom = top + scrollEl.clientHeight; - const left = scrollEl.scrollLeft, - right = left + scrollEl.clientWidth; - function isElementBottomAfterViewTop(view) { - const element = view.div; - const elementBottom = element.offsetTop + element.clientTop + element.clientHeight; - return elementBottom > top; - } - function isElementNextAfterViewHorizontally(view) { - const element = view.div; - const elementLeft = element.offsetLeft + element.clientLeft; - const elementRight = elementLeft + element.clientWidth; - return rtl ? elementLeft < right : elementRight > left; - } - const visible = [], - ids = new Set(), - numViews = views.length; - let firstVisibleElementInd = binarySearchFirstItem(views, horizontal ? isElementNextAfterViewHorizontally : isElementBottomAfterViewTop); - if (firstVisibleElementInd > 0 && firstVisibleElementInd < numViews && !horizontal) { - firstVisibleElementInd = backtrackBeforeAllVisibleElements(firstVisibleElementInd, views, top); - } - let lastEdge = horizontal ? right : -1; - for (let i = firstVisibleElementInd; i < numViews; i++) { - const view = views[i], - element = view.div; - const currentWidth = element.offsetLeft + element.clientLeft; - const currentHeight = element.offsetTop + element.clientTop; - const viewWidth = element.clientWidth, - viewHeight = element.clientHeight; - const viewRight = currentWidth + viewWidth; - const viewBottom = currentHeight + viewHeight; - if (lastEdge === -1) { - if (viewBottom >= bottom) { - lastEdge = viewBottom; - } - } else if ((horizontal ? currentWidth : currentHeight) > lastEdge) { - break; - } - if (viewBottom <= top || currentHeight >= bottom || viewRight <= left || currentWidth >= right) { - continue; - } - const hiddenHeight = Math.max(0, top - currentHeight) + Math.max(0, viewBottom - bottom); - const hiddenWidth = Math.max(0, left - currentWidth) + Math.max(0, viewRight - right); - const fractionHeight = (viewHeight - hiddenHeight) / viewHeight, - fractionWidth = (viewWidth - hiddenWidth) / viewWidth; - const percent = fractionHeight * fractionWidth * 100 | 0; - visible.push({ - id: view.id, - x: currentWidth, - y: currentHeight, - view, - percent, - widthPercent: fractionWidth * 100 | 0 - }); - ids.add(view.id); - } - const first = visible[0], - last = visible.at(-1); - if (sortByVisibility) { - visible.sort(function (a, b) { - const pc = a.percent - b.percent; - if (Math.abs(pc) > 0.001) { - return -pc; - } - return a.id - b.id; - }); - } - return { - first, - last, - views: visible, - ids - }; -} -function normalizeWheelEventDirection(evt) { - let delta = Math.hypot(evt.deltaX, evt.deltaY); - const angle = Math.atan2(evt.deltaY, evt.deltaX); - if (-0.25 * Math.PI < angle && angle < 0.75 * Math.PI) { - delta = -delta; - } - return delta; -} -function normalizeWheelEventDelta(evt) { - const deltaMode = evt.deltaMode; - let delta = normalizeWheelEventDirection(evt); - const MOUSE_PIXELS_PER_LINE = 30; - const MOUSE_LINES_PER_PAGE = 30; - if (deltaMode === WheelEvent.DOM_DELTA_PIXEL) { - delta /= MOUSE_PIXELS_PER_LINE * MOUSE_LINES_PER_PAGE; - } else if (deltaMode === WheelEvent.DOM_DELTA_LINE) { - delta /= MOUSE_LINES_PER_PAGE; - } - return delta; -} -function isValidRotation(angle) { - return Number.isInteger(angle) && angle % 90 === 0; -} -function isValidScrollMode(mode) { - return Number.isInteger(mode) && Object.values(ScrollMode).includes(mode) && mode !== ScrollMode.UNKNOWN; -} -function isValidSpreadMode(mode) { - return Number.isInteger(mode) && Object.values(SpreadMode).includes(mode) && mode !== SpreadMode.UNKNOWN; -} -function isPortraitOrientation(size) { - return size.width <= size.height; -} -const animationStarted = new Promise(function (resolve) { - window.requestAnimationFrame(resolve); -}); -const docStyle = document.documentElement.style; -function clamp(v, min, max) { - return Math.min(Math.max(v, min), max); -} -class ProgressBar { - #classList = null; - #disableAutoFetchTimeout = null; - #percent = 0; - #style = null; - #visible = true; - constructor(bar) { - this.#classList = bar.classList; - this.#style = bar.style; - } - get percent() { - return this.#percent; - } - set percent(val) { - this.#percent = clamp(val, 0, 100); - if (isNaN(val)) { - this.#classList.add("indeterminate"); - return; - } - this.#classList.remove("indeterminate"); - this.#style.setProperty("--progressBar-percent", `${this.#percent}%`); - } - setWidth(viewer) { - if (!viewer) { - return; - } - const container = viewer.parentNode; - const scrollbarWidth = container.offsetWidth - viewer.offsetWidth; - if (scrollbarWidth > 0) { - this.#style.setProperty("--progressBar-end-offset", `${scrollbarWidth}px`); - } - } - setDisableAutoFetch(delay = 5000) { - if (this.#percent === 100 || isNaN(this.#percent)) { - return; - } - if (this.#disableAutoFetchTimeout) { - clearTimeout(this.#disableAutoFetchTimeout); - } - this.show(); - this.#disableAutoFetchTimeout = setTimeout(() => { - this.#disableAutoFetchTimeout = null; - this.hide(); - }, delay); - } - hide() { - if (!this.#visible) { - return; - } - this.#visible = false; - this.#classList.add("hidden"); - } - show() { - if (this.#visible) { - return; - } - this.#visible = true; - this.#classList.remove("hidden"); - } -} -function getActiveOrFocusedElement() { - let curRoot = document; - let curActiveOrFocused = curRoot.activeElement || curRoot.querySelector(":focus"); - while (curActiveOrFocused?.shadowRoot) { - curRoot = curActiveOrFocused.shadowRoot; - curActiveOrFocused = curRoot.activeElement || curRoot.querySelector(":focus"); - } - return curActiveOrFocused; -} -function apiPageLayoutToViewerModes(layout) { - let scrollMode = ScrollMode.VERTICAL, - spreadMode = SpreadMode.NONE; - switch (layout) { - case "SinglePage": - scrollMode = ScrollMode.PAGE; - break; - case "OneColumn": - break; - case "TwoPageLeft": - scrollMode = ScrollMode.PAGE; - case "TwoColumnLeft": - spreadMode = SpreadMode.ODD; - break; - case "TwoPageRight": - scrollMode = ScrollMode.PAGE; - case "TwoColumnRight": - spreadMode = SpreadMode.EVEN; - break; - } - return { - scrollMode, - spreadMode - }; -} -function apiPageModeToSidebarView(mode) { - switch (mode) { - case "UseNone": - return SidebarView.NONE; - case "UseThumbs": - return SidebarView.THUMBS; - case "UseOutlines": - return SidebarView.OUTLINE; - case "UseAttachments": - return SidebarView.ATTACHMENTS; - case "UseOC": - return SidebarView.LAYERS; - } - return SidebarView.NONE; -} -function toggleCheckedBtn(button, toggle, view = null) { - button.classList.toggle("toggled", toggle); - button.setAttribute("aria-checked", toggle); - view?.classList.toggle("hidden", !toggle); -} -function toggleExpandedBtn(button, toggle, view = null) { - button.classList.toggle("toggled", toggle); - button.setAttribute("aria-expanded", toggle); - view?.classList.toggle("hidden", !toggle); -} -const calcRound = function () { - const e = document.createElement("div"); - e.style.width = "round(down, calc(1.6666666666666665 * 792px), 1px)"; - return e.style.width === "calc(1320px)" ? Math.fround : x => x; -}(); - -;// ./web/pdf_find_utils.js -const CharacterType = { - SPACE: 0, - ALPHA_LETTER: 1, - PUNCT: 2, - HAN_LETTER: 3, - KATAKANA_LETTER: 4, - HIRAGANA_LETTER: 5, - HALFWIDTH_KATAKANA_LETTER: 6, - THAI_LETTER: 7 -}; -function isAlphabeticalScript(charCode) { - return charCode < 0x2e80; -} -function isAscii(charCode) { - return (charCode & 0xff80) === 0; -} -function isAsciiAlpha(charCode) { - return charCode >= 0x61 && charCode <= 0x7a || charCode >= 0x41 && charCode <= 0x5a; -} -function isAsciiDigit(charCode) { - return charCode >= 0x30 && charCode <= 0x39; -} -function isAsciiSpace(charCode) { - return charCode === 0x20 || charCode === 0x09 || charCode === 0x0d || charCode === 0x0a; -} -function isHan(charCode) { - return charCode >= 0x3400 && charCode <= 0x9fff || charCode >= 0xf900 && charCode <= 0xfaff; -} -function isKatakana(charCode) { - return charCode >= 0x30a0 && charCode <= 0x30ff; -} -function isHiragana(charCode) { - return charCode >= 0x3040 && charCode <= 0x309f; -} -function isHalfwidthKatakana(charCode) { - return charCode >= 0xff60 && charCode <= 0xff9f; -} -function isThai(charCode) { - return (charCode & 0xff80) === 0x0e00; -} -function getCharacterType(charCode) { - if (isAlphabeticalScript(charCode)) { - if (isAscii(charCode)) { - if (isAsciiSpace(charCode)) { - return CharacterType.SPACE; - } else if (isAsciiAlpha(charCode) || isAsciiDigit(charCode) || charCode === 0x5f) { - return CharacterType.ALPHA_LETTER; - } - return CharacterType.PUNCT; - } else if (isThai(charCode)) { - return CharacterType.THAI_LETTER; - } else if (charCode === 0xa0) { - return CharacterType.SPACE; - } - return CharacterType.ALPHA_LETTER; - } - if (isHan(charCode)) { - return CharacterType.HAN_LETTER; - } else if (isKatakana(charCode)) { - return CharacterType.KATAKANA_LETTER; - } else if (isHiragana(charCode)) { - return CharacterType.HIRAGANA_LETTER; - } else if (isHalfwidthKatakana(charCode)) { - return CharacterType.HALFWIDTH_KATAKANA_LETTER; - } - return CharacterType.ALPHA_LETTER; -} -let NormalizeWithNFKC; -function getNormalizeWithNFKC() { - NormalizeWithNFKC ||= ` ¨ª¯²-µ¸-º¼-¾IJ-ijĿ-ŀʼnſDŽ-njDZ-dzʰ-ʸ˘-˝ˠ-ˤʹͺ;΄-΅·ϐ-ϖϰ-ϲϴ-ϵϹևٵ-ٸक़-य़ড়-ঢ়য়ਲ਼ਸ਼ਖ਼-ਜ਼ਫ਼ଡ଼-ଢ଼ำຳໜ-ໝ༌གྷཌྷདྷབྷཛྷཀྵჼᴬ-ᴮᴰ-ᴺᴼ-ᵍᵏ-ᵪᵸᶛ-ᶿẚ-ẛάέήίόύώΆ᾽-῁ΈΉ῍-῏ΐΊ῝-῟ΰΎ῭-`ΌΏ´-῾ - ‑‗․-… ″-‴‶-‷‼‾⁇-⁉⁗ ⁰-ⁱ⁴-₎ₐ-ₜ₨℀-℃℅-ℇ℉-ℓℕ-№ℙ-ℝ℠-™ℤΩℨK-ℭℯ-ℱℳ-ℹ℻-⅀ⅅ-ⅉ⅐-ⅿ↉∬-∭∯-∰〈-〉①-⓪⨌⩴-⩶⫝̸ⱼ-ⱽⵯ⺟⻳⼀-⿕ 〶〸-〺゛-゜ゟヿㄱ-ㆎ㆒-㆟㈀-㈞㈠-㉇㉐-㉾㊀-㏿ꚜ-ꚝꝰꟲ-ꟴꟸ-ꟹꭜ-ꭟꭩ豈-嗀塚晴凞-羽蘒諸逸-都飯-舘並-龎ff-stﬓ-ﬗיִײַ-זּטּ-לּמּנּ-סּףּ-פּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-﷼︐-︙︰-﹄﹇-﹒﹔-﹦﹨-﹫ﹰ-ﹲﹴﹶ-ﻼ!-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ¢-₩`; - return NormalizeWithNFKC; -} - -;// ./web/pdf_find_controller.js - - -const FindState = { - FOUND: 0, - NOT_FOUND: 1, - WRAPPED: 2, - PENDING: 3 -}; -const FIND_TIMEOUT = 250; -const MATCH_SCROLL_OFFSET_TOP = -50; -const MATCH_SCROLL_OFFSET_LEFT = -400; -const CHARACTERS_TO_NORMALIZE = { - "\u2010": "-", - "\u2018": "'", - "\u2019": "'", - "\u201A": "'", - "\u201B": "'", - "\u201C": '"', - "\u201D": '"', - "\u201E": '"', - "\u201F": '"', - "\u00BC": "1/4", - "\u00BD": "1/2", - "\u00BE": "3/4" -}; -const DIACRITICS_EXCEPTION = new Set([0x3099, 0x309a, 0x094d, 0x09cd, 0x0a4d, 0x0acd, 0x0b4d, 0x0bcd, 0x0c4d, 0x0ccd, 0x0d3b, 0x0d3c, 0x0d4d, 0x0dca, 0x0e3a, 0x0eba, 0x0f84, 0x1039, 0x103a, 0x1714, 0x1734, 0x17d2, 0x1a60, 0x1b44, 0x1baa, 0x1bab, 0x1bf2, 0x1bf3, 0x2d7f, 0xa806, 0xa82c, 0xa8c4, 0xa953, 0xa9c0, 0xaaf6, 0xabed, 0x0c56, 0x0f71, 0x0f72, 0x0f7a, 0x0f7b, 0x0f7c, 0x0f7d, 0x0f80, 0x0f74]); -let DIACRITICS_EXCEPTION_STR; -const DIACRITICS_REG_EXP = /\p{M}+/gu; -const SPECIAL_CHARS_REG_EXP = /([.*+?^${}()|[\]\\])|(\p{P})|(\s+)|(\p{M})|(\p{L})/gu; -const NOT_DIACRITIC_FROM_END_REG_EXP = /([^\p{M}])\p{M}*$/u; -const NOT_DIACRITIC_FROM_START_REG_EXP = /^\p{M}*([^\p{M}])/u; -const SYLLABLES_REG_EXP = /[\uAC00-\uD7AF\uFA6C\uFACF-\uFAD1\uFAD5-\uFAD7]+/g; -const SYLLABLES_LENGTHS = new Map(); -const FIRST_CHAR_SYLLABLES_REG_EXP = "[\\u1100-\\u1112\\ud7a4-\\ud7af\\ud84a\\ud84c\\ud850\\ud854\\ud857\\ud85f]"; -const NFKC_CHARS_TO_NORMALIZE = new Map(); -let noSyllablesRegExp = null; -let withSyllablesRegExp = null; -function normalize(text) { - const syllablePositions = []; - let m; - while ((m = SYLLABLES_REG_EXP.exec(text)) !== null) { - let { - index - } = m; - for (const char of m[0]) { - let len = SYLLABLES_LENGTHS.get(char); - if (!len) { - len = char.normalize("NFD").length; - SYLLABLES_LENGTHS.set(char, len); - } - syllablePositions.push([len, index++]); - } - } - let normalizationRegex; - if (syllablePositions.length === 0 && noSyllablesRegExp) { - normalizationRegex = noSyllablesRegExp; - } else if (syllablePositions.length > 0 && withSyllablesRegExp) { - normalizationRegex = withSyllablesRegExp; - } else { - const replace = Object.keys(CHARACTERS_TO_NORMALIZE).join(""); - const toNormalizeWithNFKC = getNormalizeWithNFKC(); - const CJK = "(?:\\p{Ideographic}|[\u3040-\u30FF])"; - const HKDiacritics = "(?:\u3099|\u309A)"; - const CompoundWord = "\\p{Ll}-\\n\\p{Lu}"; - const regexp = `([${replace}])|([${toNormalizeWithNFKC}])|(${HKDiacritics}\\n)|(\\p{M}+(?:-\\n)?)|(${CompoundWord})|(\\S-\\n)|(${CJK}\\n)|(\\n)`; - if (syllablePositions.length === 0) { - normalizationRegex = noSyllablesRegExp = new RegExp(regexp + "|(\\u0000)", "gum"); - } else { - normalizationRegex = withSyllablesRegExp = new RegExp(regexp + `|(${FIRST_CHAR_SYLLABLES_REG_EXP})`, "gum"); - } - } - const rawDiacriticsPositions = []; - while ((m = DIACRITICS_REG_EXP.exec(text)) !== null) { - rawDiacriticsPositions.push([m[0].length, m.index]); - } - let normalized = text.normalize("NFD"); - const positions = [0, 0]; - let rawDiacriticsIndex = 0; - let syllableIndex = 0; - let shift = 0; - let shiftOrigin = 0; - let eol = 0; - let hasDiacritics = false; - normalized = normalized.replace(normalizationRegex, (match, p1, p2, p3, p4, p5, p6, p7, p8, p9, i) => { - i -= shiftOrigin; - if (p1) { - const replacement = CHARACTERS_TO_NORMALIZE[p1]; - const jj = replacement.length; - for (let j = 1; j < jj; j++) { - positions.push(i - shift + j, shift - j); - } - shift -= jj - 1; - return replacement; - } - if (p2) { - let replacement = NFKC_CHARS_TO_NORMALIZE.get(p2); - if (!replacement) { - replacement = p2.normalize("NFKC"); - NFKC_CHARS_TO_NORMALIZE.set(p2, replacement); - } - const jj = replacement.length; - for (let j = 1; j < jj; j++) { - positions.push(i - shift + j, shift - j); - } - shift -= jj - 1; - return replacement; - } - if (p3) { - hasDiacritics = true; - if (i + eol === rawDiacriticsPositions[rawDiacriticsIndex]?.[1]) { - ++rawDiacriticsIndex; - } else { - positions.push(i - 1 - shift + 1, shift - 1); - shift -= 1; - shiftOrigin += 1; - } - positions.push(i - shift + 1, shift); - shiftOrigin += 1; - eol += 1; - return p3.charAt(0); - } - if (p4) { - const hasTrailingDashEOL = p4.endsWith("\n"); - const len = hasTrailingDashEOL ? p4.length - 2 : p4.length; - hasDiacritics = true; - let jj = len; - if (i + eol === rawDiacriticsPositions[rawDiacriticsIndex]?.[1]) { - jj -= rawDiacriticsPositions[rawDiacriticsIndex][0]; - ++rawDiacriticsIndex; - } - for (let j = 1; j <= jj; j++) { - positions.push(i - 1 - shift + j, shift - j); - } - shift -= jj; - shiftOrigin += jj; - if (hasTrailingDashEOL) { - i += len - 1; - positions.push(i - shift + 1, 1 + shift); - shift += 1; - shiftOrigin += 1; - eol += 1; - return p4.slice(0, len); - } - return p4; - } - if (p5) { - shiftOrigin += 1; - eol += 1; - return p5.replace("\n", ""); - } - if (p6) { - const len = p6.length - 2; - positions.push(i - shift + len, 1 + shift); - shift += 1; - shiftOrigin += 1; - eol += 1; - return p6.slice(0, -2); - } - if (p7) { - const len = p7.length - 1; - positions.push(i - shift + len, shift); - shiftOrigin += 1; - eol += 1; - return p7.slice(0, -1); - } - if (p8) { - positions.push(i - shift + 1, shift - 1); - shift -= 1; - shiftOrigin += 1; - eol += 1; - return " "; - } - if (i + eol === syllablePositions[syllableIndex]?.[1]) { - const newCharLen = syllablePositions[syllableIndex][0] - 1; - ++syllableIndex; - for (let j = 1; j <= newCharLen; j++) { - positions.push(i - (shift - j), shift - j); - } - shift -= newCharLen; - shiftOrigin += newCharLen; - } - return p9; - }); - positions.push(normalized.length, shift); - const starts = new Uint32Array(positions.length >> 1); - const shifts = new Int32Array(positions.length >> 1); - for (let i = 0, ii = positions.length; i < ii; i += 2) { - starts[i >> 1] = positions[i]; - shifts[i >> 1] = positions[i + 1]; - } - return [normalized, [starts, shifts], hasDiacritics]; -} -function getOriginalIndex(diffs, pos, len) { - if (!diffs) { - return [pos, len]; - } - const [starts, shifts] = diffs; - const start = pos; - const end = pos + len - 1; - let i = binarySearchFirstItem(starts, x => x >= start); - if (starts[i] > start) { - --i; - } - let j = binarySearchFirstItem(starts, x => x >= end, i); - if (starts[j] > end) { - --j; - } - const oldStart = start + shifts[i]; - const oldEnd = end + shifts[j]; - const oldLen = oldEnd + 1 - oldStart; - return [oldStart, oldLen]; -} -class PDFFindController { - #state = null; - #updateMatchesCountOnProgress = true; - #visitedPagesCount = 0; - constructor({ - linkService, - eventBus, - updateMatchesCountOnProgress = true - }) { - this._linkService = linkService; - this._eventBus = eventBus; - this.#updateMatchesCountOnProgress = updateMatchesCountOnProgress; - this.onIsPageVisible = null; - this.#reset(); - eventBus._on("find", this.#onFind.bind(this)); - eventBus._on("findbarclose", this.#onFindBarClose.bind(this)); - } - get highlightMatches() { - return this._highlightMatches; - } - get pageMatches() { - return this._pageMatches; - } - get pageMatchesLength() { - return this._pageMatchesLength; - } - get selected() { - return this._selected; - } - get state() { - return this.#state; - } - setDocument(pdfDocument) { - if (this._pdfDocument) { - this.#reset(); - } - if (!pdfDocument) { - return; - } - this._pdfDocument = pdfDocument; - this._firstPageCapability.resolve(); - } - #onFind(state) { - if (!state) { - return; - } - const pdfDocument = this._pdfDocument; - const { - type - } = state; - if (this.#state === null || this.#shouldDirtyMatch(state)) { - this._dirtyMatch = true; - } - this.#state = state; - if (type !== "highlightallchange") { - this.#updateUIState(FindState.PENDING); - } - this._firstPageCapability.promise.then(() => { - if (!this._pdfDocument || pdfDocument && this._pdfDocument !== pdfDocument) { - return; - } - this.#extractText(); - const findbarClosed = !this._highlightMatches; - const pendingTimeout = !!this._findTimeout; - if (this._findTimeout) { - clearTimeout(this._findTimeout); - this._findTimeout = null; - } - if (!type) { - this._findTimeout = setTimeout(() => { - this.#nextMatch(); - this._findTimeout = null; - }, FIND_TIMEOUT); - } else if (this._dirtyMatch) { - this.#nextMatch(); - } else if (type === "again") { - this.#nextMatch(); - if (findbarClosed && this.#state.highlightAll) { - this.#updateAllPages(); - } - } else if (type === "highlightallchange") { - if (pendingTimeout) { - this.#nextMatch(); - } else { - this._highlightMatches = true; - } - this.#updateAllPages(); - } else { - this.#nextMatch(); - } - }); - } - scrollMatchIntoView({ - element = null, - selectedLeft = 0, - pageIndex = -1, - matchIndex = -1 - }) { - if (!this._scrollMatches || !element) { - return; - } else if (matchIndex === -1 || matchIndex !== this._selected.matchIdx) { - return; - } else if (pageIndex === -1 || pageIndex !== this._selected.pageIdx) { - return; - } - this._scrollMatches = false; - const spot = { - top: MATCH_SCROLL_OFFSET_TOP, - left: selectedLeft + MATCH_SCROLL_OFFSET_LEFT - }; - scrollIntoView(element, spot, true); - } - #reset() { - this._highlightMatches = false; - this._scrollMatches = false; - this._pdfDocument = null; - this._pageMatches = []; - this._pageMatchesLength = []; - this.#visitedPagesCount = 0; - this.#state = null; - this._selected = { - pageIdx: -1, - matchIdx: -1 - }; - this._offset = { - pageIdx: null, - matchIdx: null, - wrapped: false - }; - this._extractTextPromises = []; - this._pageContents = []; - this._pageDiffs = []; - this._hasDiacritics = []; - this._matchesCountTotal = 0; - this._pagesToSearch = null; - this._pendingFindMatches = new Set(); - this._resumePageIdx = null; - this._dirtyMatch = false; - clearTimeout(this._findTimeout); - this._findTimeout = null; - this._firstPageCapability = Promise.withResolvers(); - } - get #query() { - const { - query - } = this.#state; - if (typeof query === "string") { - if (query !== this._rawQuery) { - this._rawQuery = query; - [this._normalizedQuery] = normalize(query); - } - return this._normalizedQuery; - } - return (query || []).filter(q => !!q).map(q => normalize(q)[0]); - } - #shouldDirtyMatch(state) { - const newQuery = state.query, - prevQuery = this.#state.query; - const newType = typeof newQuery, - prevType = typeof prevQuery; - if (newType !== prevType) { - return true; - } - if (newType === "string") { - if (newQuery !== prevQuery) { - return true; - } - } else if (JSON.stringify(newQuery) !== JSON.stringify(prevQuery)) { - return true; - } - switch (state.type) { - case "again": - const pageNumber = this._selected.pageIdx + 1; - const linkService = this._linkService; - return pageNumber >= 1 && pageNumber <= linkService.pagesCount && pageNumber !== linkService.page && !(this.onIsPageVisible?.(pageNumber) ?? true); - case "highlightallchange": - return false; - } - return true; - } - #isEntireWord(content, startIdx, length) { - let match = content.slice(0, startIdx).match(NOT_DIACRITIC_FROM_END_REG_EXP); - if (match) { - const first = content.charCodeAt(startIdx); - const limit = match[1].charCodeAt(0); - if (getCharacterType(first) === getCharacterType(limit)) { - return false; - } - } - match = content.slice(startIdx + length).match(NOT_DIACRITIC_FROM_START_REG_EXP); - if (match) { - const last = content.charCodeAt(startIdx + length - 1); - const limit = match[1].charCodeAt(0); - if (getCharacterType(last) === getCharacterType(limit)) { - return false; - } - } - return true; - } - #convertToRegExpString(query, hasDiacritics) { - const { - matchDiacritics - } = this.#state; - let isUnicode = false; - query = query.replaceAll(SPECIAL_CHARS_REG_EXP, (match, p1, p2, p3, p4, p5) => { - if (p1) { - return `[ ]*\\${p1}[ ]*`; - } - if (p2) { - return `[ ]*${p2}[ ]*`; - } - if (p3) { - return "[ ]+"; - } - if (matchDiacritics) { - return p4 || p5; - } - if (p4) { - return DIACRITICS_EXCEPTION.has(p4.charCodeAt(0)) ? p4 : ""; - } - if (hasDiacritics) { - isUnicode = true; - return `${p5}\\p{M}*`; - } - return p5; - }); - const trailingSpaces = "[ ]*"; - if (query.endsWith(trailingSpaces)) { - query = query.slice(0, query.length - trailingSpaces.length); - } - if (matchDiacritics) { - if (hasDiacritics) { - DIACRITICS_EXCEPTION_STR ||= String.fromCharCode(...DIACRITICS_EXCEPTION); - isUnicode = true; - query = `${query}(?=[${DIACRITICS_EXCEPTION_STR}]|[^\\p{M}]|$)`; - } - } - return [isUnicode, query]; - } - #calculateMatch(pageIndex) { - const query = this.#query; - if (query.length === 0) { - return; - } - const pageContent = this._pageContents[pageIndex]; - const matcherResult = this.match(query, pageContent, pageIndex); - const matches = this._pageMatches[pageIndex] = []; - const matchesLength = this._pageMatchesLength[pageIndex] = []; - const diffs = this._pageDiffs[pageIndex]; - matcherResult?.forEach(({ - index, - length - }) => { - const [matchPos, matchLen] = getOriginalIndex(diffs, index, length); - if (matchLen) { - matches.push(matchPos); - matchesLength.push(matchLen); - } - }); - if (this.#state.highlightAll) { - this.#updatePage(pageIndex); - } - if (this._resumePageIdx === pageIndex) { - this._resumePageIdx = null; - this.#nextPageMatch(); - } - const pageMatchesCount = matches.length; - this._matchesCountTotal += pageMatchesCount; - if (this.#updateMatchesCountOnProgress) { - if (pageMatchesCount > 0) { - this.#updateUIResultsCount(); - } - } else if (++this.#visitedPagesCount === this._linkService.pagesCount) { - this.#updateUIResultsCount(); - } - } - match(query, pageContent, pageIndex) { - const hasDiacritics = this._hasDiacritics[pageIndex]; - let isUnicode = false; - if (typeof query === "string") { - [isUnicode, query] = this.#convertToRegExpString(query, hasDiacritics); - } else { - query = query.sort().reverse().map(q => { - const [isUnicodePart, queryPart] = this.#convertToRegExpString(q, hasDiacritics); - isUnicode ||= isUnicodePart; - return `(${queryPart})`; - }).join("|"); - } - if (!query) { - return undefined; - } - const { - caseSensitive, - entireWord - } = this.#state; - const flags = `g${isUnicode ? "u" : ""}${caseSensitive ? "" : "i"}`; - query = new RegExp(query, flags); - const matches = []; - let match; - while ((match = query.exec(pageContent)) !== null) { - if (entireWord && !this.#isEntireWord(pageContent, match.index, match[0].length)) { - continue; - } - matches.push({ - index: match.index, - length: match[0].length - }); - } - return matches; - } - #extractText() { - if (this._extractTextPromises.length > 0) { - return; - } - let deferred = Promise.resolve(); - const textOptions = { - disableNormalization: true - }; - for (let i = 0, ii = this._linkService.pagesCount; i < ii; i++) { - const { - promise, - resolve - } = Promise.withResolvers(); - this._extractTextPromises[i] = promise; - deferred = deferred.then(() => { - return this._pdfDocument.getPage(i + 1).then(pdfPage => pdfPage.getTextContent(textOptions)).then(textContent => { - const strBuf = []; - for (const textItem of textContent.items) { - strBuf.push(textItem.str); - if (textItem.hasEOL) { - strBuf.push("\n"); - } - } - [this._pageContents[i], this._pageDiffs[i], this._hasDiacritics[i]] = normalize(strBuf.join("")); - resolve(); - }, reason => { - console.error(`Unable to get text content for page ${i + 1}`, reason); - this._pageContents[i] = ""; - this._pageDiffs[i] = null; - this._hasDiacritics[i] = false; - resolve(); - }); - }); - } - } - #updatePage(index) { - if (this._scrollMatches && this._selected.pageIdx === index) { - this._linkService.page = index + 1; - } - this._eventBus.dispatch("updatetextlayermatches", { - source: this, - pageIndex: index - }); - } - #updateAllPages() { - this._eventBus.dispatch("updatetextlayermatches", { - source: this, - pageIndex: -1 - }); - } - #nextMatch() { - const previous = this.#state.findPrevious; - const currentPageIndex = this._linkService.page - 1; - const numPages = this._linkService.pagesCount; - this._highlightMatches = true; - if (this._dirtyMatch) { - this._dirtyMatch = false; - this._selected.pageIdx = this._selected.matchIdx = -1; - this._offset.pageIdx = currentPageIndex; - this._offset.matchIdx = null; - this._offset.wrapped = false; - this._resumePageIdx = null; - this._pageMatches.length = 0; - this._pageMatchesLength.length = 0; - this.#visitedPagesCount = 0; - this._matchesCountTotal = 0; - this.#updateAllPages(); - for (let i = 0; i < numPages; i++) { - if (this._pendingFindMatches.has(i)) { - continue; - } - this._pendingFindMatches.add(i); - this._extractTextPromises[i].then(() => { - this._pendingFindMatches.delete(i); - this.#calculateMatch(i); - }); - } - } - const query = this.#query; - if (query.length === 0) { - this.#updateUIState(FindState.FOUND); - return; - } - if (this._resumePageIdx) { - return; - } - const offset = this._offset; - this._pagesToSearch = numPages; - if (offset.matchIdx !== null) { - const numPageMatches = this._pageMatches[offset.pageIdx].length; - if (!previous && offset.matchIdx + 1 < numPageMatches || previous && offset.matchIdx > 0) { - offset.matchIdx = previous ? offset.matchIdx - 1 : offset.matchIdx + 1; - this.#updateMatch(true); - return; - } - this.#advanceOffsetPage(previous); - } - this.#nextPageMatch(); - } - #matchesReady(matches) { - const offset = this._offset; - const numMatches = matches.length; - const previous = this.#state.findPrevious; - if (numMatches) { - offset.matchIdx = previous ? numMatches - 1 : 0; - this.#updateMatch(true); - return true; - } - this.#advanceOffsetPage(previous); - if (offset.wrapped) { - offset.matchIdx = null; - if (this._pagesToSearch < 0) { - this.#updateMatch(false); - return true; - } - } - return false; - } - #nextPageMatch() { - if (this._resumePageIdx !== null) { - console.error("There can only be one pending page."); - } - let matches = null; - do { - const pageIdx = this._offset.pageIdx; - matches = this._pageMatches[pageIdx]; - if (!matches) { - this._resumePageIdx = pageIdx; - break; - } - } while (!this.#matchesReady(matches)); - } - #advanceOffsetPage(previous) { - const offset = this._offset; - const numPages = this._linkService.pagesCount; - offset.pageIdx = previous ? offset.pageIdx - 1 : offset.pageIdx + 1; - offset.matchIdx = null; - this._pagesToSearch--; - if (offset.pageIdx >= numPages || offset.pageIdx < 0) { - offset.pageIdx = previous ? numPages - 1 : 0; - offset.wrapped = true; - } - } - #updateMatch(found = false) { - let state = FindState.NOT_FOUND; - const wrapped = this._offset.wrapped; - this._offset.wrapped = false; - if (found) { - const previousPage = this._selected.pageIdx; - this._selected.pageIdx = this._offset.pageIdx; - this._selected.matchIdx = this._offset.matchIdx; - state = wrapped ? FindState.WRAPPED : FindState.FOUND; - if (previousPage !== -1 && previousPage !== this._selected.pageIdx) { - this.#updatePage(previousPage); - } - } - this.#updateUIState(state, this.#state.findPrevious); - if (this._selected.pageIdx !== -1) { - this._scrollMatches = true; - this.#updatePage(this._selected.pageIdx); - } - } - #onFindBarClose(evt) { - const pdfDocument = this._pdfDocument; - this._firstPageCapability.promise.then(() => { - if (!this._pdfDocument || pdfDocument && this._pdfDocument !== pdfDocument) { - return; - } - if (this._findTimeout) { - clearTimeout(this._findTimeout); - this._findTimeout = null; - } - if (this._resumePageIdx) { - this._resumePageIdx = null; - this._dirtyMatch = true; - } - this.#updateUIState(FindState.FOUND); - this._highlightMatches = false; - this.#updateAllPages(); - }); - } - #requestMatchesCount() { - const { - pageIdx, - matchIdx - } = this._selected; - let current = 0, - total = this._matchesCountTotal; - if (matchIdx !== -1) { - for (let i = 0; i < pageIdx; i++) { - current += this._pageMatches[i]?.length || 0; - } - current += matchIdx + 1; - } - if (current < 1 || current > total) { - current = total = 0; - } - return { - current, - total - }; - } - #updateUIResultsCount() { - this._eventBus.dispatch("updatefindmatchescount", { - source: this, - matchesCount: this.#requestMatchesCount() - }); - } - #updateUIState(state, previous = false) { - if (!this.#updateMatchesCountOnProgress && (this.#visitedPagesCount !== this._linkService.pagesCount || state === FindState.PENDING)) { - return; - } - this._eventBus.dispatch("updatefindcontrolstate", { - source: this, - state, - previous, - entireWord: this.#state?.entireWord ?? null, - matchesCount: this.#requestMatchesCount(), - rawQuery: this.#state?.query ?? null - }); - } -} - -;// ./web/pdf_link_service.js - -const DEFAULT_LINK_REL = "noopener noreferrer nofollow"; -const LinkTarget = { - NONE: 0, - SELF: 1, - BLANK: 2, - PARENT: 3, - TOP: 4 -}; -class PDFLinkService { - externalLinkEnabled = true; - constructor({ - eventBus, - externalLinkTarget = null, - externalLinkRel = null, - ignoreDestinationZoom = false - } = {}) { - this.eventBus = eventBus; - this.externalLinkTarget = externalLinkTarget; - this.externalLinkRel = externalLinkRel; - this._ignoreDestinationZoom = ignoreDestinationZoom; - this.baseUrl = null; - this.pdfDocument = null; - this.pdfViewer = null; - this.pdfHistory = null; - } - setDocument(pdfDocument, baseUrl = null) { - this.baseUrl = baseUrl; - this.pdfDocument = pdfDocument; - } - setViewer(pdfViewer) { - this.pdfViewer = pdfViewer; - } - setHistory(pdfHistory) { - this.pdfHistory = pdfHistory; - } - get pagesCount() { - return this.pdfDocument ? this.pdfDocument.numPages : 0; - } - get page() { - return this.pdfDocument ? this.pdfViewer.currentPageNumber : 1; - } - set page(value) { - if (this.pdfDocument) { - this.pdfViewer.currentPageNumber = value; - } - } - get rotation() { - return this.pdfDocument ? this.pdfViewer.pagesRotation : 0; - } - set rotation(value) { - if (this.pdfDocument) { - this.pdfViewer.pagesRotation = value; - } - } - get isInPresentationMode() { - return this.pdfDocument ? this.pdfViewer.isInPresentationMode : false; - } - async goToDestination(dest) { - if (!this.pdfDocument) { - return; - } - let namedDest, explicitDest, pageNumber; - if (typeof dest === "string") { - namedDest = dest; - explicitDest = await this.pdfDocument.getDestination(dest); - } else { - namedDest = null; - explicitDest = await dest; - } - if (!Array.isArray(explicitDest)) { - console.error(`goToDestination: "${explicitDest}" is not a valid destination array, for dest="${dest}".`); - return; - } - const [destRef] = explicitDest; - if (destRef && typeof destRef === "object") { - pageNumber = this.pdfDocument.cachedPageNumber(destRef); - if (!pageNumber) { - try { - pageNumber = (await this.pdfDocument.getPageIndex(destRef)) + 1; - } catch { - console.error(`goToDestination: "${destRef}" is not a valid page reference, for dest="${dest}".`); - return; - } - } - } else if (Number.isInteger(destRef)) { - pageNumber = destRef + 1; - } - if (!pageNumber || pageNumber < 1 || pageNumber > this.pagesCount) { - console.error(`goToDestination: "${pageNumber}" is not a valid page number, for dest="${dest}".`); - return; - } - if (this.pdfHistory) { - this.pdfHistory.pushCurrentPosition(); - this.pdfHistory.push({ - namedDest, - explicitDest, - pageNumber - }); - } - this.pdfViewer.scrollPageIntoView({ - pageNumber, - destArray: explicitDest, - ignoreDestinationZoom: this._ignoreDestinationZoom - }); - } - goToPage(val) { - if (!this.pdfDocument) { - return; - } - const pageNumber = typeof val === "string" && this.pdfViewer.pageLabelToPageNumber(val) || val | 0; - if (!(Number.isInteger(pageNumber) && pageNumber > 0 && pageNumber <= this.pagesCount)) { - console.error(`PDFLinkService.goToPage: "${val}" is not a valid page.`); - return; - } - if (this.pdfHistory) { - this.pdfHistory.pushCurrentPosition(); - this.pdfHistory.pushPage(pageNumber); - } - this.pdfViewer.scrollPageIntoView({ - pageNumber - }); - } - addLinkAttributes(link, url, newWindow = false) { - if (!url || typeof url !== "string") { - throw new Error('A valid "url" parameter must provided.'); - } - const target = newWindow ? LinkTarget.BLANK : this.externalLinkTarget, - rel = this.externalLinkRel; - if (this.externalLinkEnabled) { - link.href = link.title = url; - } else { - link.href = ""; - link.title = `Disabled: ${url}`; - link.onclick = () => false; - } - let targetStr = ""; - switch (target) { - case LinkTarget.NONE: - break; - case LinkTarget.SELF: - targetStr = "_self"; - break; - case LinkTarget.BLANK: - targetStr = "_blank"; - break; - case LinkTarget.PARENT: - targetStr = "_parent"; - break; - case LinkTarget.TOP: - targetStr = "_top"; - break; - } - link.target = targetStr; - link.rel = typeof rel === "string" ? rel : DEFAULT_LINK_REL; - } - getDestinationHash(dest) { - if (typeof dest === "string") { - if (dest.length > 0) { - return this.getAnchorUrl("#" + escape(dest)); - } - } else if (Array.isArray(dest)) { - const str = JSON.stringify(dest); - if (str.length > 0) { - return this.getAnchorUrl("#" + escape(str)); - } - } - return this.getAnchorUrl(""); - } - getAnchorUrl(anchor) { - return this.baseUrl ? this.baseUrl + anchor : anchor; - } - setHash(hash) { - if (!this.pdfDocument) { - return; - } - let pageNumber, dest; - if (hash.includes("=")) { - const params = parseQueryString(hash); - if (params.has("search")) { - const query = params.get("search").replaceAll('"', ""), - phrase = params.get("phrase") === "true"; - this.eventBus.dispatch("findfromurlhash", { - source: this, - query: phrase ? query : query.match(/\S+/g) - }); - } - if (params.has("page")) { - pageNumber = params.get("page") | 0 || 1; - } - if (params.has("zoom")) { - const zoomArgs = params.get("zoom").split(","); - const zoomArg = zoomArgs[0]; - const zoomArgNumber = parseFloat(zoomArg); - if (!zoomArg.includes("Fit")) { - dest = [null, { - name: "XYZ" - }, zoomArgs.length > 1 ? zoomArgs[1] | 0 : null, zoomArgs.length > 2 ? zoomArgs[2] | 0 : null, zoomArgNumber ? zoomArgNumber / 100 : zoomArg]; - } else if (zoomArg === "Fit" || zoomArg === "FitB") { - dest = [null, { - name: zoomArg - }]; - } else if (zoomArg === "FitH" || zoomArg === "FitBH" || zoomArg === "FitV" || zoomArg === "FitBV") { - dest = [null, { - name: zoomArg - }, zoomArgs.length > 1 ? zoomArgs[1] | 0 : null]; - } else if (zoomArg === "FitR") { - if (zoomArgs.length !== 5) { - console.error('PDFLinkService.setHash: Not enough parameters for "FitR".'); - } else { - dest = [null, { - name: zoomArg - }, zoomArgs[1] | 0, zoomArgs[2] | 0, zoomArgs[3] | 0, zoomArgs[4] | 0]; - } - } else { - console.error(`PDFLinkService.setHash: "${zoomArg}" is not a valid zoom value.`); - } - } - if (dest) { - this.pdfViewer.scrollPageIntoView({ - pageNumber: pageNumber || this.page, - destArray: dest, - allowNegativeOffset: true - }); - } else if (pageNumber) { - this.page = pageNumber; - } - if (params.has("pagemode")) { - this.eventBus.dispatch("pagemode", { - source: this, - mode: params.get("pagemode") - }); - } - if (params.has("nameddest")) { - this.goToDestination(params.get("nameddest")); - } - return; - } - dest = unescape(hash); - try { - dest = JSON.parse(dest); - if (!Array.isArray(dest)) { - dest = dest.toString(); - } - } catch {} - if (typeof dest === "string" || PDFLinkService.#isValidExplicitDest(dest)) { - this.goToDestination(dest); - return; - } - console.error(`PDFLinkService.setHash: "${unescape(hash)}" is not a valid destination.`); - } - executeNamedAction(action) { - if (!this.pdfDocument) { - return; - } - switch (action) { - case "GoBack": - this.pdfHistory?.back(); - break; - case "GoForward": - this.pdfHistory?.forward(); - break; - case "NextPage": - this.pdfViewer.nextPage(); - break; - case "PrevPage": - this.pdfViewer.previousPage(); - break; - case "LastPage": - this.page = this.pagesCount; - break; - case "FirstPage": - this.page = 1; - break; - default: - break; - } - this.eventBus.dispatch("namedaction", { - source: this, - action - }); - } - async executeSetOCGState(action) { - if (!this.pdfDocument) { - return; - } - const pdfDocument = this.pdfDocument, - optionalContentConfig = await this.pdfViewer.optionalContentConfigPromise; - if (pdfDocument !== this.pdfDocument) { - return; - } - optionalContentConfig.setOCGState(action); - this.pdfViewer.optionalContentConfigPromise = Promise.resolve(optionalContentConfig); - } - static #isValidExplicitDest(dest) { - if (!Array.isArray(dest) || dest.length < 2) { - return false; - } - const [page, zoom, ...args] = dest; - if (!(typeof page === "object" && Number.isInteger(page?.num) && Number.isInteger(page?.gen)) && !Number.isInteger(page)) { - return false; - } - if (!(typeof zoom === "object" && typeof zoom?.name === "string")) { - return false; - } - const argsLen = args.length; - let allowNull = true; - switch (zoom.name) { - case "XYZ": - if (argsLen < 2 || argsLen > 3) { - return false; - } - break; - case "Fit": - case "FitB": - return argsLen === 0; - case "FitH": - case "FitBH": - case "FitV": - case "FitBV": - if (argsLen > 1) { - return false; - } - break; - case "FitR": - if (argsLen !== 4) { - return false; - } - allowNull = false; - break; - default: - return false; - } - for (const arg of args) { - if (!(typeof arg === "number" || allowNull && arg === null)) { - return false; - } - } - return true; - } -} -class SimpleLinkService extends PDFLinkService { - setDocument(pdfDocument, baseUrl = null) {} -} - -;// ./web/pdfjs.js -const { - AbortException, - AnnotationEditorLayer, - AnnotationEditorParamsType, - AnnotationEditorType, - AnnotationEditorUIManager, - AnnotationLayer, - AnnotationMode, - build, - ColorPicker, - createValidAbsoluteUrl, - DOMSVGFactory, - DrawLayer, - FeatureTest, - fetchData, - getDocument, - getFilenameFromUrl, - getPdfFilenameFromUrl, - getXfaPageViewport, - GlobalWorkerOptions, - ImageKind, - InvalidPDFException, - isDataScheme, - isPdfFile, - MissingPDFException, - noContextMenu, - normalizeUnicode, - OPS, - OutputScale, - PasswordResponses, - PDFDataRangeTransport, - PDFDateString, - PDFWorker, - PermissionFlag, - PixelsPerInch, - RenderingCancelledException, - setLayerDimensions, - shadow, - stopEvent, - TextLayer, - TouchManager, - UnexpectedResponseException, - Util, - VerbosityLevel, - version, - XfaLayer -} = globalThis.pdfjsLib; - -;// ./web/annotation_layer_builder.js - - -class AnnotationLayerBuilder { - #onAppend = null; - #eventAbortController = null; - constructor({ - pdfPage, - linkService, - downloadManager, - annotationStorage = null, - imageResourcesPath = "", - renderForms = true, - enableScripting = false, - hasJSActionsPromise = null, - fieldObjectsPromise = null, - annotationCanvasMap = null, - accessibilityManager = null, - annotationEditorUIManager = null, - onAppend = null - }) { - this.pdfPage = pdfPage; - this.linkService = linkService; - this.downloadManager = downloadManager; - this.imageResourcesPath = imageResourcesPath; - this.renderForms = renderForms; - this.annotationStorage = annotationStorage; - this.enableScripting = enableScripting; - this._hasJSActionsPromise = hasJSActionsPromise || Promise.resolve(false); - this._fieldObjectsPromise = fieldObjectsPromise || Promise.resolve(null); - this._annotationCanvasMap = annotationCanvasMap; - this._accessibilityManager = accessibilityManager; - this._annotationEditorUIManager = annotationEditorUIManager; - this.#onAppend = onAppend; - this.annotationLayer = null; - this.div = null; - this._cancelled = false; - this._eventBus = linkService.eventBus; - } - async render(viewport, options, intent = "display") { - if (this.div) { - if (this._cancelled || !this.annotationLayer) { - return; - } - this.annotationLayer.update({ - viewport: viewport.clone({ - dontFlip: true - }) - }); - return; - } - const [annotations, hasJSActions, fieldObjects] = await Promise.all([this.pdfPage.getAnnotations({ - intent - }), this._hasJSActionsPromise, this._fieldObjectsPromise]); - if (this._cancelled) { - return; - } - const div = this.div = document.createElement("div"); - div.className = "annotationLayer"; - this.#onAppend?.(div); - if (annotations.length === 0) { - this.hide(); - return; - } - this.annotationLayer = new AnnotationLayer({ - div, - accessibilityManager: this._accessibilityManager, - annotationCanvasMap: this._annotationCanvasMap, - annotationEditorUIManager: this._annotationEditorUIManager, - page: this.pdfPage, - viewport: viewport.clone({ - dontFlip: true - }), - structTreeLayer: options?.structTreeLayer || null - }); - await this.annotationLayer.render({ - annotations, - imageResourcesPath: this.imageResourcesPath, - renderForms: this.renderForms, - linkService: this.linkService, - downloadManager: this.downloadManager, - annotationStorage: this.annotationStorage, - enableScripting: this.enableScripting, - hasJSActions, - fieldObjects - }); - if (this.linkService.isInPresentationMode) { - this.#updatePresentationModeState(PresentationModeState.FULLSCREEN); - } - if (!this.#eventAbortController) { - this.#eventAbortController = new AbortController(); - this._eventBus?._on("presentationmodechanged", evt => { - this.#updatePresentationModeState(evt.state); - }, { - signal: this.#eventAbortController.signal - }); - } - } - cancel() { - this._cancelled = true; - this.#eventAbortController?.abort(); - this.#eventAbortController = null; - } - hide() { - if (!this.div) { - return; - } - this.div.hidden = true; - } - hasEditableAnnotations() { - return !!this.annotationLayer?.hasEditableAnnotations(); - } - #updatePresentationModeState(state) { - if (!this.div) { - return; - } - let disableFormElements = false; - switch (state) { - case PresentationModeState.FULLSCREEN: - disableFormElements = true; - break; - case PresentationModeState.NORMAL: - break; - default: - return; - } - for (const section of this.div.childNodes) { - if (section.hasAttribute("data-internal-link")) { - continue; - } - section.inert = disableFormElements; - } - } -} - -;// ./web/download_manager.js - -function download(blobUrl, filename) { - const a = document.createElement("a"); - if (!a.click) { - throw new Error('DownloadManager: "a.click()" is not supported.'); - } - a.href = blobUrl; - a.target = "_parent"; - if ("download" in a) { - a.download = filename; - } - (document.body || document.documentElement).append(a); - a.click(); - a.remove(); -} -class DownloadManager { - #openBlobUrls = new WeakMap(); - downloadData(data, filename, contentType) { - const blobUrl = URL.createObjectURL(new Blob([data], { - type: contentType - })); - download(blobUrl, filename); - } - openOrDownloadData(data, filename, dest = null) { - const isPdfData = isPdfFile(filename); - const contentType = isPdfData ? "application/pdf" : ""; - this.downloadData(data, filename, contentType); - return false; - } - download(data, url, filename) { - let blobUrl; - if (data) { - blobUrl = URL.createObjectURL(new Blob([data], { - type: "application/pdf" - })); - } else { - if (!createValidAbsoluteUrl(url, "http://example.com")) { - console.error(`download - not a valid URL: ${url}`); - return; - } - blobUrl = url + "#pdfjs.action=download"; - } - download(blobUrl, filename); - } -} - -;// ./web/event_utils.js -const WaitOnType = { - EVENT: "event", - TIMEOUT: "timeout" -}; -async function waitOnEventOrTimeout({ - target, - name, - delay = 0 -}) { - if (typeof target !== "object" || !(name && typeof name === "string") || !(Number.isInteger(delay) && delay >= 0)) { - throw new Error("waitOnEventOrTimeout - invalid parameters."); - } - const { - promise, - resolve - } = Promise.withResolvers(); - const ac = new AbortController(); - function handler(type) { - ac.abort(); - clearTimeout(timeout); - resolve(type); - } - const evtMethod = target instanceof EventBus ? "_on" : "addEventListener"; - target[evtMethod](name, handler.bind(null, WaitOnType.EVENT), { - signal: ac.signal - }); - const timeout = setTimeout(handler.bind(null, WaitOnType.TIMEOUT), delay); - return promise; -} -class EventBus { - #listeners = Object.create(null); - on(eventName, listener, options = null) { - this._on(eventName, listener, { - external: true, - once: options?.once, - signal: options?.signal - }); - } - off(eventName, listener, options = null) { - this._off(eventName, listener); - } - dispatch(eventName, data) { - const eventListeners = this.#listeners[eventName]; - if (!eventListeners || eventListeners.length === 0) { - return; - } - let externalListeners; - for (const { - listener, - external, - once - } of eventListeners.slice(0)) { - if (once) { - this._off(eventName, listener); - } - if (external) { - (externalListeners ||= []).push(listener); - continue; - } - listener(data); - } - if (externalListeners) { - for (const listener of externalListeners) { - listener(data); - } - externalListeners = null; - } - } - _on(eventName, listener, options = null) { - let rmAbort = null; - if (options?.signal instanceof AbortSignal) { - const { - signal - } = options; - if (signal.aborted) { - console.error("Cannot use an `aborted` signal."); - return; - } - const onAbort = () => this._off(eventName, listener); - rmAbort = () => signal.removeEventListener("abort", onAbort); - signal.addEventListener("abort", onAbort); - } - const eventListeners = this.#listeners[eventName] ||= []; - eventListeners.push({ - listener, - external: options?.external === true, - once: options?.once === true, - rmAbort - }); - } - _off(eventName, listener, options = null) { - const eventListeners = this.#listeners[eventName]; - if (!eventListeners) { - return; - } - for (let i = 0, ii = eventListeners.length; i < ii; i++) { - const evt = eventListeners[i]; - if (evt.listener === listener) { - evt.rmAbort?.(); - eventListeners.splice(i, 1); - return; - } - } - } -} -class FirefoxEventBus extends EventBus { - #externalServices; - #globalEventNames; - #isInAutomation; - constructor(globalEventNames, externalServices, isInAutomation) { - super(); - this.#globalEventNames = globalEventNames; - this.#externalServices = externalServices; - this.#isInAutomation = isInAutomation; - } - dispatch(eventName, data) { - throw new Error("Not implemented: FirefoxEventBus.dispatch"); - } -} - -;// ./node_modules/@fluent/bundle/esm/types.js -class FluentType { - constructor(value) { - this.value = value; - } - valueOf() { - return this.value; - } -} -class FluentNone extends FluentType { - constructor(value = "???") { - super(value); - } - toString(scope) { - return `{${this.value}}`; - } -} -class FluentNumber extends FluentType { - constructor(value, opts = {}) { - super(value); - this.opts = opts; - } - toString(scope) { - try { - const nf = scope.memoizeIntlObject(Intl.NumberFormat, this.opts); - return nf.format(this.value); - } catch (err) { - scope.reportError(err); - return this.value.toString(10); - } - } -} -class FluentDateTime extends FluentType { - constructor(value, opts = {}) { - super(value); - this.opts = opts; - } - toString(scope) { - try { - const dtf = scope.memoizeIntlObject(Intl.DateTimeFormat, this.opts); - return dtf.format(this.value); - } catch (err) { - scope.reportError(err); - return new Date(this.value).toISOString(); - } - } -} -;// ./node_modules/@fluent/bundle/esm/resolver.js - -const MAX_PLACEABLES = 100; -const FSI = "\u2068"; -const PDI = "\u2069"; -function match(scope, selector, key) { - if (key === selector) { - return true; - } - if (key instanceof FluentNumber && selector instanceof FluentNumber && key.value === selector.value) { - return true; - } - if (selector instanceof FluentNumber && typeof key === "string") { - let category = scope.memoizeIntlObject(Intl.PluralRules, selector.opts).select(selector.value); - if (key === category) { - return true; - } - } - return false; -} -function getDefault(scope, variants, star) { - if (variants[star]) { - return resolvePattern(scope, variants[star].value); - } - scope.reportError(new RangeError("No default")); - return new FluentNone(); -} -function getArguments(scope, args) { - const positional = []; - const named = Object.create(null); - for (const arg of args) { - if (arg.type === "narg") { - named[arg.name] = resolveExpression(scope, arg.value); - } else { - positional.push(resolveExpression(scope, arg)); - } - } - return { - positional, - named - }; -} -function resolveExpression(scope, expr) { - switch (expr.type) { - case "str": - return expr.value; - case "num": - return new FluentNumber(expr.value, { - minimumFractionDigits: expr.precision - }); - case "var": - return resolveVariableReference(scope, expr); - case "mesg": - return resolveMessageReference(scope, expr); - case "term": - return resolveTermReference(scope, expr); - case "func": - return resolveFunctionReference(scope, expr); - case "select": - return resolveSelectExpression(scope, expr); - default: - return new FluentNone(); - } -} -function resolveVariableReference(scope, { - name -}) { - let arg; - if (scope.params) { - if (Object.prototype.hasOwnProperty.call(scope.params, name)) { - arg = scope.params[name]; - } else { - return new FluentNone(`$${name}`); - } - } else if (scope.args && Object.prototype.hasOwnProperty.call(scope.args, name)) { - arg = scope.args[name]; - } else { - scope.reportError(new ReferenceError(`Unknown variable: $${name}`)); - return new FluentNone(`$${name}`); - } - if (arg instanceof FluentType) { - return arg; - } - switch (typeof arg) { - case "string": - return arg; - case "number": - return new FluentNumber(arg); - case "object": - if (arg instanceof Date) { - return new FluentDateTime(arg.getTime()); - } - default: - scope.reportError(new TypeError(`Variable type not supported: $${name}, ${typeof arg}`)); - return new FluentNone(`$${name}`); - } -} -function resolveMessageReference(scope, { - name, - attr -}) { - const message = scope.bundle._messages.get(name); - if (!message) { - scope.reportError(new ReferenceError(`Unknown message: ${name}`)); - return new FluentNone(name); - } - if (attr) { - const attribute = message.attributes[attr]; - if (attribute) { - return resolvePattern(scope, attribute); - } - scope.reportError(new ReferenceError(`Unknown attribute: ${attr}`)); - return new FluentNone(`${name}.${attr}`); - } - if (message.value) { - return resolvePattern(scope, message.value); - } - scope.reportError(new ReferenceError(`No value: ${name}`)); - return new FluentNone(name); -} -function resolveTermReference(scope, { - name, - attr, - args -}) { - const id = `-${name}`; - const term = scope.bundle._terms.get(id); - if (!term) { - scope.reportError(new ReferenceError(`Unknown term: ${id}`)); - return new FluentNone(id); - } - if (attr) { - const attribute = term.attributes[attr]; - if (attribute) { - scope.params = getArguments(scope, args).named; - const resolved = resolvePattern(scope, attribute); - scope.params = null; - return resolved; - } - scope.reportError(new ReferenceError(`Unknown attribute: ${attr}`)); - return new FluentNone(`${id}.${attr}`); - } - scope.params = getArguments(scope, args).named; - const resolved = resolvePattern(scope, term.value); - scope.params = null; - return resolved; -} -function resolveFunctionReference(scope, { - name, - args -}) { - let func = scope.bundle._functions[name]; - if (!func) { - scope.reportError(new ReferenceError(`Unknown function: ${name}()`)); - return new FluentNone(`${name}()`); - } - if (typeof func !== "function") { - scope.reportError(new TypeError(`Function ${name}() is not callable`)); - return new FluentNone(`${name}()`); - } - try { - let resolved = getArguments(scope, args); - return func(resolved.positional, resolved.named); - } catch (err) { - scope.reportError(err); - return new FluentNone(`${name}()`); - } -} -function resolveSelectExpression(scope, { - selector, - variants, - star -}) { - let sel = resolveExpression(scope, selector); - if (sel instanceof FluentNone) { - return getDefault(scope, variants, star); - } - for (const variant of variants) { - const key = resolveExpression(scope, variant.key); - if (match(scope, sel, key)) { - return resolvePattern(scope, variant.value); - } - } - return getDefault(scope, variants, star); -} -function resolveComplexPattern(scope, ptn) { - if (scope.dirty.has(ptn)) { - scope.reportError(new RangeError("Cyclic reference")); - return new FluentNone(); - } - scope.dirty.add(ptn); - const result = []; - const useIsolating = scope.bundle._useIsolating && ptn.length > 1; - for (const elem of ptn) { - if (typeof elem === "string") { - result.push(scope.bundle._transform(elem)); - continue; - } - scope.placeables++; - if (scope.placeables > MAX_PLACEABLES) { - scope.dirty.delete(ptn); - throw new RangeError(`Too many placeables expanded: ${scope.placeables}, ` + `max allowed is ${MAX_PLACEABLES}`); - } - if (useIsolating) { - result.push(FSI); - } - result.push(resolveExpression(scope, elem).toString(scope)); - if (useIsolating) { - result.push(PDI); - } - } - scope.dirty.delete(ptn); - return result.join(""); -} -function resolvePattern(scope, value) { - if (typeof value === "string") { - return scope.bundle._transform(value); - } - return resolveComplexPattern(scope, value); -} -;// ./node_modules/@fluent/bundle/esm/scope.js -class Scope { - constructor(bundle, errors, args) { - this.dirty = new WeakSet(); - this.params = null; - this.placeables = 0; - this.bundle = bundle; - this.errors = errors; - this.args = args; - } - reportError(error) { - if (!this.errors || !(error instanceof Error)) { - throw error; - } - this.errors.push(error); - } - memoizeIntlObject(ctor, opts) { - let cache = this.bundle._intls.get(ctor); - if (!cache) { - cache = {}; - this.bundle._intls.set(ctor, cache); - } - let id = JSON.stringify(opts); - if (!cache[id]) { - cache[id] = new ctor(this.bundle.locales, opts); - } - return cache[id]; - } -} -;// ./node_modules/@fluent/bundle/esm/builtins.js - -function values(opts, allowed) { - const unwrapped = Object.create(null); - for (const [name, opt] of Object.entries(opts)) { - if (allowed.includes(name)) { - unwrapped[name] = opt.valueOf(); - } - } - return unwrapped; -} -const NUMBER_ALLOWED = ["unitDisplay", "currencyDisplay", "useGrouping", "minimumIntegerDigits", "minimumFractionDigits", "maximumFractionDigits", "minimumSignificantDigits", "maximumSignificantDigits"]; -function NUMBER(args, opts) { - let arg = args[0]; - if (arg instanceof FluentNone) { - return new FluentNone(`NUMBER(${arg.valueOf()})`); - } - if (arg instanceof FluentNumber) { - return new FluentNumber(arg.valueOf(), { - ...arg.opts, - ...values(opts, NUMBER_ALLOWED) - }); - } - if (arg instanceof FluentDateTime) { - return new FluentNumber(arg.valueOf(), { - ...values(opts, NUMBER_ALLOWED) - }); - } - throw new TypeError("Invalid argument to NUMBER"); -} -const DATETIME_ALLOWED = ["dateStyle", "timeStyle", "fractionalSecondDigits", "dayPeriod", "hour12", "weekday", "era", "year", "month", "day", "hour", "minute", "second", "timeZoneName"]; -function DATETIME(args, opts) { - let arg = args[0]; - if (arg instanceof FluentNone) { - return new FluentNone(`DATETIME(${arg.valueOf()})`); - } - if (arg instanceof FluentDateTime) { - return new FluentDateTime(arg.valueOf(), { - ...arg.opts, - ...values(opts, DATETIME_ALLOWED) - }); - } - if (arg instanceof FluentNumber) { - return new FluentDateTime(arg.valueOf(), { - ...values(opts, DATETIME_ALLOWED) - }); - } - throw new TypeError("Invalid argument to DATETIME"); -} -;// ./node_modules/@fluent/bundle/esm/memoizer.js -const cache = new Map(); -function getMemoizerForLocale(locales) { - const stringLocale = Array.isArray(locales) ? locales.join(" ") : locales; - let memoizer = cache.get(stringLocale); - if (memoizer === undefined) { - memoizer = new Map(); - cache.set(stringLocale, memoizer); - } - return memoizer; -} -;// ./node_modules/@fluent/bundle/esm/bundle.js - - - - - -class FluentBundle { - constructor(locales, { - functions, - useIsolating = true, - transform = v => v - } = {}) { - this._terms = new Map(); - this._messages = new Map(); - this.locales = Array.isArray(locales) ? locales : [locales]; - this._functions = { - NUMBER: NUMBER, - DATETIME: DATETIME, - ...functions - }; - this._useIsolating = useIsolating; - this._transform = transform; - this._intls = getMemoizerForLocale(locales); - } - hasMessage(id) { - return this._messages.has(id); - } - getMessage(id) { - return this._messages.get(id); - } - addResource(res, { - allowOverrides = false - } = {}) { - const errors = []; - for (let i = 0; i < res.body.length; i++) { - let entry = res.body[i]; - if (entry.id.startsWith("-")) { - if (allowOverrides === false && this._terms.has(entry.id)) { - errors.push(new Error(`Attempt to override an existing term: "${entry.id}"`)); - continue; - } - this._terms.set(entry.id, entry); - } else { - if (allowOverrides === false && this._messages.has(entry.id)) { - errors.push(new Error(`Attempt to override an existing message: "${entry.id}"`)); - continue; - } - this._messages.set(entry.id, entry); - } - } - return errors; - } - formatPattern(pattern, args = null, errors = null) { - if (typeof pattern === "string") { - return this._transform(pattern); - } - let scope = new Scope(this, errors, args); - try { - let value = resolveComplexPattern(scope, pattern); - return value.toString(scope); - } catch (err) { - if (scope.errors && err instanceof Error) { - scope.errors.push(err); - return new FluentNone().toString(scope); - } - throw err; - } - } -} -;// ./node_modules/@fluent/bundle/esm/resource.js -const RE_MESSAGE_START = /^(-?[a-zA-Z][\w-]*) *= */gm; -const RE_ATTRIBUTE_START = /\.([a-zA-Z][\w-]*) *= */y; -const RE_VARIANT_START = /\*?\[/y; -const RE_NUMBER_LITERAL = /(-?[0-9]+(?:\.([0-9]+))?)/y; -const RE_IDENTIFIER = /([a-zA-Z][\w-]*)/y; -const RE_REFERENCE = /([$-])?([a-zA-Z][\w-]*)(?:\.([a-zA-Z][\w-]*))?/y; -const RE_FUNCTION_NAME = /^[A-Z][A-Z0-9_-]*$/; -const RE_TEXT_RUN = /([^{}\n\r]+)/y; -const RE_STRING_RUN = /([^\\"\n\r]*)/y; -const RE_STRING_ESCAPE = /\\([\\"])/y; -const RE_UNICODE_ESCAPE = /\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{6})/y; -const RE_LEADING_NEWLINES = /^\n+/; -const RE_TRAILING_SPACES = / +$/; -const RE_BLANK_LINES = / *\r?\n/g; -const RE_INDENT = /( *)$/; -const TOKEN_BRACE_OPEN = /{\s*/y; -const TOKEN_BRACE_CLOSE = /\s*}/y; -const TOKEN_BRACKET_OPEN = /\[\s*/y; -const TOKEN_BRACKET_CLOSE = /\s*] */y; -const TOKEN_PAREN_OPEN = /\s*\(\s*/y; -const TOKEN_ARROW = /\s*->\s*/y; -const TOKEN_COLON = /\s*:\s*/y; -const TOKEN_COMMA = /\s*,?\s*/y; -const TOKEN_BLANK = /\s+/y; -class FluentResource { - constructor(source) { - this.body = []; - RE_MESSAGE_START.lastIndex = 0; - let cursor = 0; - while (true) { - let next = RE_MESSAGE_START.exec(source); - if (next === null) { - break; - } - cursor = RE_MESSAGE_START.lastIndex; - try { - this.body.push(parseMessage(next[1])); - } catch (err) { - if (err instanceof SyntaxError) { - continue; - } - throw err; - } - } - function test(re) { - re.lastIndex = cursor; - return re.test(source); - } - function consumeChar(char, errorClass) { - if (source[cursor] === char) { - cursor++; - return true; - } - if (errorClass) { - throw new errorClass(`Expected ${char}`); - } - return false; - } - function consumeToken(re, errorClass) { - if (test(re)) { - cursor = re.lastIndex; - return true; - } - if (errorClass) { - throw new errorClass(`Expected ${re.toString()}`); - } - return false; - } - function match(re) { - re.lastIndex = cursor; - let result = re.exec(source); - if (result === null) { - throw new SyntaxError(`Expected ${re.toString()}`); - } - cursor = re.lastIndex; - return result; - } - function match1(re) { - return match(re)[1]; - } - function parseMessage(id) { - let value = parsePattern(); - let attributes = parseAttributes(); - if (value === null && Object.keys(attributes).length === 0) { - throw new SyntaxError("Expected message value or attributes"); - } - return { - id, - value, - attributes - }; - } - function parseAttributes() { - let attrs = Object.create(null); - while (test(RE_ATTRIBUTE_START)) { - let name = match1(RE_ATTRIBUTE_START); - let value = parsePattern(); - if (value === null) { - throw new SyntaxError("Expected attribute value"); - } - attrs[name] = value; - } - return attrs; - } - function parsePattern() { - let first; - if (test(RE_TEXT_RUN)) { - first = match1(RE_TEXT_RUN); - } - if (source[cursor] === "{" || source[cursor] === "}") { - return parsePatternElements(first ? [first] : [], Infinity); - } - let indent = parseIndent(); - if (indent) { - if (first) { - return parsePatternElements([first, indent], indent.length); - } - indent.value = trim(indent.value, RE_LEADING_NEWLINES); - return parsePatternElements([indent], indent.length); - } - if (first) { - return trim(first, RE_TRAILING_SPACES); - } - return null; - } - function parsePatternElements(elements = [], commonIndent) { - while (true) { - if (test(RE_TEXT_RUN)) { - elements.push(match1(RE_TEXT_RUN)); - continue; - } - if (source[cursor] === "{") { - elements.push(parsePlaceable()); - continue; - } - if (source[cursor] === "}") { - throw new SyntaxError("Unbalanced closing brace"); - } - let indent = parseIndent(); - if (indent) { - elements.push(indent); - commonIndent = Math.min(commonIndent, indent.length); - continue; - } - break; - } - let lastIndex = elements.length - 1; - let lastElement = elements[lastIndex]; - if (typeof lastElement === "string") { - elements[lastIndex] = trim(lastElement, RE_TRAILING_SPACES); - } - let baked = []; - for (let element of elements) { - if (element instanceof Indent) { - element = element.value.slice(0, element.value.length - commonIndent); - } - if (element) { - baked.push(element); - } - } - return baked; - } - function parsePlaceable() { - consumeToken(TOKEN_BRACE_OPEN, SyntaxError); - let selector = parseInlineExpression(); - if (consumeToken(TOKEN_BRACE_CLOSE)) { - return selector; - } - if (consumeToken(TOKEN_ARROW)) { - let variants = parseVariants(); - consumeToken(TOKEN_BRACE_CLOSE, SyntaxError); - return { - type: "select", - selector, - ...variants - }; - } - throw new SyntaxError("Unclosed placeable"); - } - function parseInlineExpression() { - if (source[cursor] === "{") { - return parsePlaceable(); - } - if (test(RE_REFERENCE)) { - let [, sigil, name, attr = null] = match(RE_REFERENCE); - if (sigil === "$") { - return { - type: "var", - name - }; - } - if (consumeToken(TOKEN_PAREN_OPEN)) { - let args = parseArguments(); - if (sigil === "-") { - return { - type: "term", - name, - attr, - args - }; - } - if (RE_FUNCTION_NAME.test(name)) { - return { - type: "func", - name, - args - }; - } - throw new SyntaxError("Function names must be all upper-case"); - } - if (sigil === "-") { - return { - type: "term", - name, - attr, - args: [] - }; - } - return { - type: "mesg", - name, - attr - }; - } - return parseLiteral(); - } - function parseArguments() { - let args = []; - while (true) { - switch (source[cursor]) { - case ")": - cursor++; - return args; - case undefined: - throw new SyntaxError("Unclosed argument list"); - } - args.push(parseArgument()); - consumeToken(TOKEN_COMMA); - } - } - function parseArgument() { - let expr = parseInlineExpression(); - if (expr.type !== "mesg") { - return expr; - } - if (consumeToken(TOKEN_COLON)) { - return { - type: "narg", - name: expr.name, - value: parseLiteral() - }; - } - return expr; - } - function parseVariants() { - let variants = []; - let count = 0; - let star; - while (test(RE_VARIANT_START)) { - if (consumeChar("*")) { - star = count; - } - let key = parseVariantKey(); - let value = parsePattern(); - if (value === null) { - throw new SyntaxError("Expected variant value"); - } - variants[count++] = { - key, - value - }; - } - if (count === 0) { - return null; - } - if (star === undefined) { - throw new SyntaxError("Expected default variant"); - } - return { - variants, - star - }; - } - function parseVariantKey() { - consumeToken(TOKEN_BRACKET_OPEN, SyntaxError); - let key; - if (test(RE_NUMBER_LITERAL)) { - key = parseNumberLiteral(); - } else { - key = { - type: "str", - value: match1(RE_IDENTIFIER) - }; - } - consumeToken(TOKEN_BRACKET_CLOSE, SyntaxError); - return key; - } - function parseLiteral() { - if (test(RE_NUMBER_LITERAL)) { - return parseNumberLiteral(); - } - if (source[cursor] === '"') { - return parseStringLiteral(); - } - throw new SyntaxError("Invalid expression"); - } - function parseNumberLiteral() { - let [, value, fraction = ""] = match(RE_NUMBER_LITERAL); - let precision = fraction.length; - return { - type: "num", - value: parseFloat(value), - precision - }; - } - function parseStringLiteral() { - consumeChar('"', SyntaxError); - let value = ""; - while (true) { - value += match1(RE_STRING_RUN); - if (source[cursor] === "\\") { - value += parseEscapeSequence(); - continue; - } - if (consumeChar('"')) { - return { - type: "str", - value - }; - } - throw new SyntaxError("Unclosed string literal"); - } - } - function parseEscapeSequence() { - if (test(RE_STRING_ESCAPE)) { - return match1(RE_STRING_ESCAPE); - } - if (test(RE_UNICODE_ESCAPE)) { - let [, codepoint4, codepoint6] = match(RE_UNICODE_ESCAPE); - let codepoint = parseInt(codepoint4 || codepoint6, 16); - return codepoint <= 0xd7ff || 0xe000 <= codepoint ? String.fromCodePoint(codepoint) : "�"; - } - throw new SyntaxError("Unknown escape sequence"); - } - function parseIndent() { - let start = cursor; - consumeToken(TOKEN_BLANK); - switch (source[cursor]) { - case ".": - case "[": - case "*": - case "}": - case undefined: - return false; - case "{": - return makeIndent(source.slice(start, cursor)); - } - if (source[cursor - 1] === " ") { - return makeIndent(source.slice(start, cursor)); - } - return false; - } - function trim(text, re) { - return text.replace(re, ""); - } - function makeIndent(blank) { - let value = blank.replace(RE_BLANK_LINES, "\n"); - let length = RE_INDENT.exec(blank)[1].length; - return new Indent(value, length); - } - } -} -class Indent { - constructor(value, length) { - this.value = value; - this.length = length; - } -} -;// ./node_modules/@fluent/bundle/esm/index.js - - - -;// ./node_modules/@fluent/dom/esm/overlay.js -const reOverlay = /<|&#?\w+;/; -const TEXT_LEVEL_ELEMENTS = { - "http://www.w3.org/1999/xhtml": ["em", "strong", "small", "s", "cite", "q", "dfn", "abbr", "data", "time", "code", "var", "samp", "kbd", "sub", "sup", "i", "b", "u", "mark", "bdi", "bdo", "span", "br", "wbr"] -}; -const LOCALIZABLE_ATTRIBUTES = { - "http://www.w3.org/1999/xhtml": { - global: ["title", "aria-label", "aria-valuetext"], - a: ["download"], - area: ["download", "alt"], - input: ["alt", "placeholder"], - menuitem: ["label"], - menu: ["label"], - optgroup: ["label"], - option: ["label"], - track: ["label"], - img: ["alt"], - textarea: ["placeholder"], - th: ["abbr"] - }, - "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul": { - global: ["accesskey", "aria-label", "aria-valuetext", "label", "title", "tooltiptext"], - description: ["value"], - key: ["key", "keycode"], - label: ["value"], - textbox: ["placeholder", "value"] - } -}; -function translateElement(element, translation) { - const { - value - } = translation; - if (typeof value === "string") { - if (element.localName === "title" && element.namespaceURI === "http://www.w3.org/1999/xhtml") { - element.textContent = value; - } else if (!reOverlay.test(value)) { - element.textContent = value; - } else { - const templateElement = element.ownerDocument.createElementNS("http://www.w3.org/1999/xhtml", "template"); - templateElement.innerHTML = value; - overlayChildNodes(templateElement.content, element); - } - } - overlayAttributes(translation, element); -} -function overlayChildNodes(fromFragment, toElement) { - for (const childNode of fromFragment.childNodes) { - if (childNode.nodeType === childNode.TEXT_NODE) { - continue; - } - if (childNode.hasAttribute("data-l10n-name")) { - const sanitized = getNodeForNamedElement(toElement, childNode); - fromFragment.replaceChild(sanitized, childNode); - continue; - } - if (isElementAllowed(childNode)) { - const sanitized = createSanitizedElement(childNode); - fromFragment.replaceChild(sanitized, childNode); - continue; - } - console.warn(`An element of forbidden type "${childNode.localName}" was found in ` + "the translation. Only safe text-level elements and elements with " + "data-l10n-name are allowed."); - fromFragment.replaceChild(createTextNodeFromTextContent(childNode), childNode); - } - toElement.textContent = ""; - toElement.appendChild(fromFragment); -} -function hasAttribute(attributes, name) { - if (!attributes) { - return false; - } - for (let attr of attributes) { - if (attr.name === name) { - return true; - } - } - return false; -} -function overlayAttributes(fromElement, toElement) { - const explicitlyAllowed = toElement.hasAttribute("data-l10n-attrs") ? toElement.getAttribute("data-l10n-attrs").split(",").map(i => i.trim()) : null; - for (const attr of Array.from(toElement.attributes)) { - if (isAttrNameLocalizable(attr.name, toElement, explicitlyAllowed) && !hasAttribute(fromElement.attributes, attr.name)) { - toElement.removeAttribute(attr.name); - } - } - if (!fromElement.attributes) { - return; - } - for (const attr of Array.from(fromElement.attributes)) { - if (isAttrNameLocalizable(attr.name, toElement, explicitlyAllowed) && toElement.getAttribute(attr.name) !== attr.value) { - toElement.setAttribute(attr.name, attr.value); - } - } -} -function getNodeForNamedElement(sourceElement, translatedChild) { - const childName = translatedChild.getAttribute("data-l10n-name"); - const sourceChild = sourceElement.querySelector(`[data-l10n-name="${childName}"]`); - if (!sourceChild) { - console.warn(`An element named "${childName}" wasn't found in the source.`); - return createTextNodeFromTextContent(translatedChild); - } - if (sourceChild.localName !== translatedChild.localName) { - console.warn(`An element named "${childName}" was found in the translation ` + `but its type ${translatedChild.localName} didn't match the ` + `element found in the source (${sourceChild.localName}).`); - return createTextNodeFromTextContent(translatedChild); - } - sourceElement.removeChild(sourceChild); - const clone = sourceChild.cloneNode(false); - return shallowPopulateUsing(translatedChild, clone); -} -function createSanitizedElement(element) { - const clone = element.ownerDocument.createElement(element.localName); - return shallowPopulateUsing(element, clone); -} -function createTextNodeFromTextContent(element) { - return element.ownerDocument.createTextNode(element.textContent); -} -function isElementAllowed(element) { - const allowed = TEXT_LEVEL_ELEMENTS[element.namespaceURI]; - return allowed && allowed.includes(element.localName); -} -function isAttrNameLocalizable(name, element, explicitlyAllowed = null) { - if (explicitlyAllowed && explicitlyAllowed.includes(name)) { - return true; - } - const allowed = LOCALIZABLE_ATTRIBUTES[element.namespaceURI]; - if (!allowed) { - return false; - } - const attrName = name.toLowerCase(); - const elemName = element.localName; - if (allowed.global.includes(attrName)) { - return true; - } - if (!allowed[elemName]) { - return false; - } - if (allowed[elemName].includes(attrName)) { - return true; - } - if (element.namespaceURI === "http://www.w3.org/1999/xhtml" && elemName === "input" && attrName === "value") { - const type = element.type.toLowerCase(); - if (type === "submit" || type === "button" || type === "reset") { - return true; - } - } - return false; -} -function shallowPopulateUsing(fromElement, toElement) { - toElement.textContent = fromElement.textContent; - overlayAttributes(fromElement, toElement); - return toElement; -} -;// ./node_modules/cached-iterable/src/cached_iterable.mjs -class CachedIterable extends Array { - static from(iterable) { - if (iterable instanceof this) { - return iterable; - } - return new this(iterable); - } -} -;// ./node_modules/cached-iterable/src/cached_sync_iterable.mjs - -class CachedSyncIterable extends CachedIterable { - constructor(iterable) { - super(); - if (Symbol.iterator in Object(iterable)) { - this.iterator = iterable[Symbol.iterator](); - } else { - throw new TypeError("Argument must implement the iteration protocol."); - } - } - [Symbol.iterator]() { - const cached = this; - let cur = 0; - return { - next() { - if (cached.length <= cur) { - cached.push(cached.iterator.next()); - } - return cached[cur++]; - } - }; - } - touchNext(count = 1) { - let idx = 0; - while (idx++ < count) { - const last = this[this.length - 1]; - if (last && last.done) { - break; - } - this.push(this.iterator.next()); - } - return this[this.length - 1]; - } -} -;// ./node_modules/cached-iterable/src/cached_async_iterable.mjs - -class CachedAsyncIterable extends CachedIterable { - constructor(iterable) { - super(); - if (Symbol.asyncIterator in Object(iterable)) { - this.iterator = iterable[Symbol.asyncIterator](); - } else if (Symbol.iterator in Object(iterable)) { - this.iterator = iterable[Symbol.iterator](); - } else { - throw new TypeError("Argument must implement the iteration protocol."); - } - } - [Symbol.asyncIterator]() { - const cached = this; - let cur = 0; - return { - async next() { - if (cached.length <= cur) { - cached.push(cached.iterator.next()); - } - return cached[cur++]; - } - }; - } - async touchNext(count = 1) { - let idx = 0; - while (idx++ < count) { - const last = this[this.length - 1]; - if (last && (await last).done) { - break; - } - this.push(this.iterator.next()); - } - return this[this.length - 1]; - } -} -;// ./node_modules/cached-iterable/src/index.mjs - - -;// ./node_modules/@fluent/dom/esm/localization.js - -class Localization { - constructor(resourceIds = [], generateBundles) { - this.resourceIds = resourceIds; - this.generateBundles = generateBundles; - this.onChange(true); - } - addResourceIds(resourceIds, eager = false) { - this.resourceIds.push(...resourceIds); - this.onChange(eager); - return this.resourceIds.length; - } - removeResourceIds(resourceIds) { - this.resourceIds = this.resourceIds.filter(r => !resourceIds.includes(r)); - this.onChange(); - return this.resourceIds.length; - } - async formatWithFallback(keys, method) { - const translations = []; - let hasAtLeastOneBundle = false; - for await (const bundle of this.bundles) { - hasAtLeastOneBundle = true; - const missingIds = keysFromBundle(method, bundle, keys, translations); - if (missingIds.size === 0) { - break; - } - if (typeof console !== "undefined") { - const locale = bundle.locales[0]; - const ids = Array.from(missingIds).join(", "); - console.warn(`[fluent] Missing translations in ${locale}: ${ids}`); - } - } - if (!hasAtLeastOneBundle && typeof console !== "undefined") { - console.warn(`[fluent] Request for keys failed because no resource bundles got generated. - keys: ${JSON.stringify(keys)}. - resourceIds: ${JSON.stringify(this.resourceIds)}.`); - } - return translations; - } - formatMessages(keys) { - return this.formatWithFallback(keys, messageFromBundle); - } - formatValues(keys) { - return this.formatWithFallback(keys, valueFromBundle); - } - async formatValue(id, args) { - const [val] = await this.formatValues([{ - id, - args - }]); - return val; - } - handleEvent() { - this.onChange(); - } - onChange(eager = false) { - this.bundles = CachedAsyncIterable.from(this.generateBundles(this.resourceIds)); - if (eager) { - this.bundles.touchNext(2); - } - } -} -function valueFromBundle(bundle, errors, message, args) { - if (message.value) { - return bundle.formatPattern(message.value, args, errors); - } - return null; -} -function messageFromBundle(bundle, errors, message, args) { - const formatted = { - value: null, - attributes: null - }; - if (message.value) { - formatted.value = bundle.formatPattern(message.value, args, errors); - } - let attrNames = Object.keys(message.attributes); - if (attrNames.length > 0) { - formatted.attributes = new Array(attrNames.length); - for (let [i, name] of attrNames.entries()) { - let value = bundle.formatPattern(message.attributes[name], args, errors); - formatted.attributes[i] = { - name, - value - }; - } - } - return formatted; -} -function keysFromBundle(method, bundle, keys, translations) { - const messageErrors = []; - const missingIds = new Set(); - keys.forEach(({ - id, - args - }, i) => { - if (translations[i] !== undefined) { - return; - } - let message = bundle.getMessage(id); - if (message) { - messageErrors.length = 0; - translations[i] = method(bundle, messageErrors, message, args); - if (messageErrors.length > 0 && typeof console !== "undefined") { - const locale = bundle.locales[0]; - const errors = messageErrors.join(", "); - console.warn(`[fluent][resolver] errors in ${locale}/${id}: ${errors}.`); - } - } else { - missingIds.add(id); - } - }); - return missingIds; -} -;// ./node_modules/@fluent/dom/esm/dom_localization.js - - -const L10NID_ATTR_NAME = "data-l10n-id"; -const L10NARGS_ATTR_NAME = "data-l10n-args"; -const L10N_ELEMENT_QUERY = `[${L10NID_ATTR_NAME}]`; -class DOMLocalization extends Localization { - constructor(resourceIds, generateBundles) { - super(resourceIds, generateBundles); - this.roots = new Set(); - this.pendingrAF = null; - this.pendingElements = new Set(); - this.windowElement = null; - this.mutationObserver = null; - this.observerConfig = { - attributes: true, - characterData: false, - childList: true, - subtree: true, - attributeFilter: [L10NID_ATTR_NAME, L10NARGS_ATTR_NAME] - }; - } - onChange(eager = false) { - super.onChange(eager); - if (this.roots) { - this.translateRoots(); - } - } - setAttributes(element, id, args) { - element.setAttribute(L10NID_ATTR_NAME, id); - if (args) { - element.setAttribute(L10NARGS_ATTR_NAME, JSON.stringify(args)); - } else { - element.removeAttribute(L10NARGS_ATTR_NAME); - } - return element; - } - getAttributes(element) { - return { - id: element.getAttribute(L10NID_ATTR_NAME), - args: JSON.parse(element.getAttribute(L10NARGS_ATTR_NAME) || null) - }; - } - connectRoot(newRoot) { - for (const root of this.roots) { - if (root === newRoot || root.contains(newRoot) || newRoot.contains(root)) { - throw new Error("Cannot add a root that overlaps with existing root."); - } - } - if (this.windowElement) { - if (this.windowElement !== newRoot.ownerDocument.defaultView) { - throw new Error(`Cannot connect a root: - DOMLocalization already has a root from a different window.`); - } - } else { - this.windowElement = newRoot.ownerDocument.defaultView; - this.mutationObserver = new this.windowElement.MutationObserver(mutations => this.translateMutations(mutations)); - } - this.roots.add(newRoot); - this.mutationObserver.observe(newRoot, this.observerConfig); - } - disconnectRoot(root) { - this.roots.delete(root); - this.pauseObserving(); - if (this.roots.size === 0) { - this.mutationObserver = null; - if (this.windowElement && this.pendingrAF) { - this.windowElement.cancelAnimationFrame(this.pendingrAF); - } - this.windowElement = null; - this.pendingrAF = null; - this.pendingElements.clear(); - return true; - } - this.resumeObserving(); - return false; - } - translateRoots() { - const roots = Array.from(this.roots); - return Promise.all(roots.map(root => this.translateFragment(root))); - } - pauseObserving() { - if (!this.mutationObserver) { - return; - } - this.translateMutations(this.mutationObserver.takeRecords()); - this.mutationObserver.disconnect(); - } - resumeObserving() { - if (!this.mutationObserver) { - return; - } - for (const root of this.roots) { - this.mutationObserver.observe(root, this.observerConfig); - } - } - translateMutations(mutations) { - for (const mutation of mutations) { - switch (mutation.type) { - case "attributes": - if (mutation.target.hasAttribute("data-l10n-id")) { - this.pendingElements.add(mutation.target); - } - break; - case "childList": - for (const addedNode of mutation.addedNodes) { - if (addedNode.nodeType === addedNode.ELEMENT_NODE) { - if (addedNode.childElementCount) { - for (const element of this.getTranslatables(addedNode)) { - this.pendingElements.add(element); - } - } else if (addedNode.hasAttribute(L10NID_ATTR_NAME)) { - this.pendingElements.add(addedNode); - } - } - } - break; - } - } - if (this.pendingElements.size > 0) { - if (this.pendingrAF === null) { - this.pendingrAF = this.windowElement.requestAnimationFrame(() => { - this.translateElements(Array.from(this.pendingElements)); - this.pendingElements.clear(); - this.pendingrAF = null; - }); - } - } - } - translateFragment(frag) { - return this.translateElements(this.getTranslatables(frag)); - } - async translateElements(elements) { - if (!elements.length) { - return undefined; - } - const keys = elements.map(this.getKeysForElement); - const translations = await this.formatMessages(keys); - return this.applyTranslations(elements, translations); - } - applyTranslations(elements, translations) { - this.pauseObserving(); - for (let i = 0; i < elements.length; i++) { - if (translations[i] !== undefined) { - translateElement(elements[i], translations[i]); - } - } - this.resumeObserving(); - } - getTranslatables(element) { - const nodes = Array.from(element.querySelectorAll(L10N_ELEMENT_QUERY)); - if (typeof element.hasAttribute === "function" && element.hasAttribute(L10NID_ATTR_NAME)) { - nodes.push(element); - } - return nodes; - } - getKeysForElement(element) { - return { - id: element.getAttribute(L10NID_ATTR_NAME), - args: JSON.parse(element.getAttribute(L10NARGS_ATTR_NAME) || null) - }; - } -} -;// ./node_modules/@fluent/dom/esm/index.js - - -;// ./web/l10n.js -class L10n { - #dir; - #elements; - #lang; - #l10n; - constructor({ - lang, - isRTL - }, l10n = null) { - this.#lang = L10n.#fixupLangCode(lang); - this.#l10n = l10n; - this.#dir = isRTL ?? L10n.#isRTL(this.#lang) ? "rtl" : "ltr"; - } - _setL10n(l10n) { - this.#l10n = l10n; - } - getLanguage() { - return this.#lang; - } - getDirection() { - return this.#dir; - } - async get(ids, args = null, fallback) { - if (Array.isArray(ids)) { - ids = ids.map(id => ({ - id - })); - const messages = await this.#l10n.formatMessages(ids); - return messages.map(message => message.value); - } - const messages = await this.#l10n.formatMessages([{ - id: ids, - args - }]); - return messages[0]?.value || fallback; - } - async translate(element) { - (this.#elements ||= new Set()).add(element); - try { - this.#l10n.connectRoot(element); - await this.#l10n.translateRoots(); - } catch {} - } - async translateOnce(element) { - try { - await this.#l10n.translateElements([element]); - } catch (ex) { - console.error("translateOnce:", ex); - } - } - async destroy() { - if (this.#elements) { - for (const element of this.#elements) { - this.#l10n.disconnectRoot(element); - } - this.#elements.clear(); - this.#elements = null; - } - this.#l10n.pauseObserving(); - } - pause() { - this.#l10n.pauseObserving(); - } - resume() { - this.#l10n.resumeObserving(); - } - static #fixupLangCode(langCode) { - langCode = langCode?.toLowerCase() || "en-us"; - const PARTIAL_LANG_CODES = { - en: "en-us", - es: "es-es", - fy: "fy-nl", - ga: "ga-ie", - gu: "gu-in", - hi: "hi-in", - hy: "hy-am", - nb: "nb-no", - ne: "ne-np", - nn: "nn-no", - pa: "pa-in", - pt: "pt-pt", - sv: "sv-se", - zh: "zh-cn" - }; - return PARTIAL_LANG_CODES[langCode] || langCode; - } - static #isRTL(lang) { - const shortCode = lang.split("-", 1)[0]; - return ["ar", "he", "fa", "ps", "ur"].includes(shortCode); - } -} -const GenericL10n = null; - -;// ./web/genericl10n.js - - - - -function createBundle(lang, text) { - const resource = new FluentResource(text); - const bundle = new FluentBundle(lang); - const errors = bundle.addResource(resource); - if (errors.length) { - console.error("L10n errors", errors); - } - return bundle; -} -class genericl10n_GenericL10n extends L10n { - constructor(lang) { - super({ - lang - }); - const generateBundles = !lang ? genericl10n_GenericL10n.#generateBundlesFallback.bind(genericl10n_GenericL10n, this.getLanguage()) : genericl10n_GenericL10n.#generateBundles.bind(genericl10n_GenericL10n, "en-us", this.getLanguage()); - this._setL10n(new DOMLocalization([], generateBundles)); - } - static async *#generateBundles(defaultLang, baseLang) { - const { - baseURL, - paths - } = await this.#getPaths(); - const langs = [baseLang]; - if (defaultLang !== baseLang) { - const shortLang = baseLang.split("-", 1)[0]; - if (shortLang !== baseLang) { - langs.push(shortLang); - } - langs.push(defaultLang); - } - for (const lang of langs) { - const bundle = await this.#createBundle(lang, baseURL, paths); - if (bundle) { - yield bundle; - } else if (lang === "en-us") { - yield this.#createBundleFallback(lang); - } - } - } - static async #createBundle(lang, baseURL, paths) { - const path = paths[lang]; - if (!path) { - return null; - } - const url = new URL(path, baseURL); - const text = await fetchData(url, "text"); - return createBundle(lang, text); - } - static async #getPaths() { - try { - const { - href - } = document.querySelector(`link[type="application/l10n"]`); - const paths = await fetchData(href, "json"); - return { - baseURL: href.replace(/[^/]*$/, "") || "./", - paths - }; - } catch {} - return { - baseURL: "./", - paths: Object.create(null) - }; - } - static async *#generateBundlesFallback(lang) { - yield this.#createBundleFallback(lang); - } - static async #createBundleFallback(lang) { - const text = "pdfjs-previous-button =\n .title = Previous Page\npdfjs-previous-button-label = Previous\npdfjs-next-button =\n .title = Next Page\npdfjs-next-button-label = Next\npdfjs-page-input =\n .title = Page\npdfjs-of-pages = of { $pagesCount }\npdfjs-page-of-pages = ({ $pageNumber } of { $pagesCount })\npdfjs-zoom-out-button =\n .title = Zoom Out\npdfjs-zoom-out-button-label = Zoom Out\npdfjs-zoom-in-button =\n .title = Zoom In\npdfjs-zoom-in-button-label = Zoom In\npdfjs-zoom-select =\n .title = Zoom\npdfjs-presentation-mode-button =\n .title = Switch to Presentation Mode\npdfjs-presentation-mode-button-label = Presentation Mode\npdfjs-open-file-button =\n .title = Open File\npdfjs-open-file-button-label = Open\npdfjs-print-button =\n .title = Print\npdfjs-print-button-label = Print\npdfjs-save-button =\n .title = Save\npdfjs-save-button-label = Save\npdfjs-download-button =\n .title = Download\npdfjs-download-button-label = Download\npdfjs-bookmark-button =\n .title = Current Page (View URL from Current Page)\npdfjs-bookmark-button-label = Current Page\npdfjs-tools-button =\n .title = Tools\npdfjs-tools-button-label = Tools\npdfjs-first-page-button =\n .title = Go to First Page\npdfjs-first-page-button-label = Go to First Page\npdfjs-last-page-button =\n .title = Go to Last Page\npdfjs-last-page-button-label = Go to Last Page\npdfjs-page-rotate-cw-button =\n .title = Rotate Clockwise\npdfjs-page-rotate-cw-button-label = Rotate Clockwise\npdfjs-page-rotate-ccw-button =\n .title = Rotate Counterclockwise\npdfjs-page-rotate-ccw-button-label = Rotate Counterclockwise\npdfjs-cursor-text-select-tool-button =\n .title = Enable Text Selection Tool\npdfjs-cursor-text-select-tool-button-label = Text Selection Tool\npdfjs-cursor-hand-tool-button =\n .title = Enable Hand Tool\npdfjs-cursor-hand-tool-button-label = Hand Tool\npdfjs-scroll-page-button =\n .title = Use Page Scrolling\npdfjs-scroll-page-button-label = Page Scrolling\npdfjs-scroll-vertical-button =\n .title = Use Vertical Scrolling\npdfjs-scroll-vertical-button-label = Vertical Scrolling\npdfjs-scroll-horizontal-button =\n .title = Use Horizontal Scrolling\npdfjs-scroll-horizontal-button-label = Horizontal Scrolling\npdfjs-scroll-wrapped-button =\n .title = Use Wrapped Scrolling\npdfjs-scroll-wrapped-button-label = Wrapped Scrolling\npdfjs-spread-none-button =\n .title = Do not join page spreads\npdfjs-spread-none-button-label = No Spreads\npdfjs-spread-odd-button =\n .title = Join page spreads starting with odd-numbered pages\npdfjs-spread-odd-button-label = Odd Spreads\npdfjs-spread-even-button =\n .title = Join page spreads starting with even-numbered pages\npdfjs-spread-even-button-label = Even Spreads\npdfjs-document-properties-button =\n .title = Document Properties\u2026\npdfjs-document-properties-button-label = Document Properties\u2026\npdfjs-document-properties-file-name = File name:\npdfjs-document-properties-file-size = File size:\npdfjs-document-properties-size-kb = { NUMBER($kb, maximumSignificantDigits: 3) } KB ({ $b } bytes)\npdfjs-document-properties-size-mb = { NUMBER($mb, maximumSignificantDigits: 3) } MB ({ $b } bytes)\npdfjs-document-properties-title = Title:\npdfjs-document-properties-author = Author:\npdfjs-document-properties-subject = Subject:\npdfjs-document-properties-keywords = Keywords:\npdfjs-document-properties-creation-date = Creation Date:\npdfjs-document-properties-modification-date = Modification Date:\npdfjs-document-properties-date-time-string = { DATETIME($dateObj, dateStyle: \"short\", timeStyle: \"medium\") }\npdfjs-document-properties-creator = Creator:\npdfjs-document-properties-producer = PDF Producer:\npdfjs-document-properties-version = PDF Version:\npdfjs-document-properties-page-count = Page Count:\npdfjs-document-properties-page-size = Page Size:\npdfjs-document-properties-page-size-unit-inches = in\npdfjs-document-properties-page-size-unit-millimeters = mm\npdfjs-document-properties-page-size-orientation-portrait = portrait\npdfjs-document-properties-page-size-orientation-landscape = landscape\npdfjs-document-properties-page-size-name-a-three = A3\npdfjs-document-properties-page-size-name-a-four = A4\npdfjs-document-properties-page-size-name-letter = Letter\npdfjs-document-properties-page-size-name-legal = Legal\npdfjs-document-properties-page-size-dimension-string = { $width } \xD7 { $height } { $unit } ({ $orientation })\npdfjs-document-properties-page-size-dimension-name-string = { $width } \xD7 { $height } { $unit } ({ $name }, { $orientation })\npdfjs-document-properties-linearized = Fast Web View:\npdfjs-document-properties-linearized-yes = Yes\npdfjs-document-properties-linearized-no = No\npdfjs-document-properties-close-button = Close\npdfjs-print-progress-message = Preparing document for printing\u2026\npdfjs-print-progress-percent = { $progress }%\npdfjs-print-progress-close-button = Cancel\npdfjs-printing-not-supported = Warning: Printing is not fully supported by this browser.\npdfjs-printing-not-ready = Warning: The PDF is not fully loaded for printing.\npdfjs-toggle-sidebar-button =\n .title = Toggle Sidebar\npdfjs-toggle-sidebar-notification-button =\n .title = Toggle Sidebar (document contains outline/attachments/layers)\npdfjs-toggle-sidebar-button-label = Toggle Sidebar\npdfjs-document-outline-button =\n .title = Show Document Outline (double-click to expand/collapse all items)\npdfjs-document-outline-button-label = Document Outline\npdfjs-attachments-button =\n .title = Show Attachments\npdfjs-attachments-button-label = Attachments\npdfjs-layers-button =\n .title = Show Layers (double-click to reset all layers to the default state)\npdfjs-layers-button-label = Layers\npdfjs-thumbs-button =\n .title = Show Thumbnails\npdfjs-thumbs-button-label = Thumbnails\npdfjs-current-outline-item-button =\n .title = Find Current Outline Item\npdfjs-current-outline-item-button-label = Current Outline Item\npdfjs-findbar-button =\n .title = Find in Document\npdfjs-findbar-button-label = Find\npdfjs-additional-layers = Additional Layers\npdfjs-thumb-page-title =\n .title = Page { $page }\npdfjs-thumb-page-canvas =\n .aria-label = Thumbnail of Page { $page }\npdfjs-find-input =\n .title = Find\n .placeholder = Find in document\u2026\npdfjs-find-previous-button =\n .title = Find the previous occurrence of the phrase\npdfjs-find-previous-button-label = Previous\npdfjs-find-next-button =\n .title = Find the next occurrence of the phrase\npdfjs-find-next-button-label = Next\npdfjs-find-highlight-checkbox = Highlight All\npdfjs-find-match-case-checkbox-label = Match Case\npdfjs-find-match-diacritics-checkbox-label = Match Diacritics\npdfjs-find-entire-word-checkbox-label = Whole Words\npdfjs-find-reached-top = Reached top of document, continued from bottom\npdfjs-find-reached-bottom = Reached end of document, continued from top\npdfjs-find-match-count =\n { $total ->\n [one] { $current } of { $total } match\n *[other] { $current } of { $total } matches\n }\npdfjs-find-match-count-limit =\n { $limit ->\n [one] More than { $limit } match\n *[other] More than { $limit } matches\n }\npdfjs-find-not-found = Phrase not found\npdfjs-page-scale-width = Page Width\npdfjs-page-scale-fit = Page Fit\npdfjs-page-scale-auto = Automatic Zoom\npdfjs-page-scale-actual = Actual Size\npdfjs-page-scale-percent = { $scale }%\npdfjs-page-landmark =\n .aria-label = Page { $page }\npdfjs-loading-error = An error occurred while loading the PDF.\npdfjs-invalid-file-error = Invalid or corrupted PDF file.\npdfjs-missing-file-error = Missing PDF file.\npdfjs-unexpected-response-error = Unexpected server response.\npdfjs-rendering-error = An error occurred while rendering the page.\npdfjs-annotation-date-time-string = { DATETIME($dateObj, dateStyle: \"short\", timeStyle: \"medium\") }\npdfjs-text-annotation-type =\n .alt = [{ $type } Annotation]\npdfjs-password-label = Enter the password to open this PDF file.\npdfjs-password-invalid = Invalid password. Please try again.\npdfjs-password-ok-button = OK\npdfjs-password-cancel-button = Cancel\npdfjs-web-fonts-disabled = Web fonts are disabled: unable to use embedded PDF fonts.\npdfjs-editor-free-text-button =\n .title = Text\npdfjs-editor-free-text-button-label = Text\npdfjs-editor-ink-button =\n .title = Draw\npdfjs-editor-ink-button-label = Draw\npdfjs-editor-stamp-button =\n .title = Add or edit images\npdfjs-editor-stamp-button-label = Add or edit images\npdfjs-editor-highlight-button =\n .title = Highlight\npdfjs-editor-highlight-button-label = Highlight\npdfjs-highlight-floating-button1 =\n .title = Highlight\n .aria-label = Highlight\npdfjs-highlight-floating-button-label = Highlight\npdfjs-editor-remove-ink-button =\n .title = Remove drawing\npdfjs-editor-remove-freetext-button =\n .title = Remove text\npdfjs-editor-remove-stamp-button =\n .title = Remove image\npdfjs-editor-remove-highlight-button =\n .title = Remove highlight\npdfjs-editor-free-text-color-input = Color\npdfjs-editor-free-text-size-input = Size\npdfjs-editor-ink-color-input = Color\npdfjs-editor-ink-thickness-input = Thickness\npdfjs-editor-ink-opacity-input = Opacity\npdfjs-editor-stamp-add-image-button =\n .title = Add image\npdfjs-editor-stamp-add-image-button-label = Add image\npdfjs-editor-free-highlight-thickness-input = Thickness\npdfjs-editor-free-highlight-thickness-title =\n .title = Change thickness when highlighting items other than text\npdfjs-free-text2 =\n .aria-label = Text Editor\n .default-content = Start typing\u2026\npdfjs-ink =\n .aria-label = Draw Editor\npdfjs-ink-canvas =\n .aria-label = User-created image\npdfjs-editor-alt-text-button =\n .aria-label = Alt text\npdfjs-editor-alt-text-button-label = Alt text\npdfjs-editor-alt-text-edit-button =\n .aria-label = Edit alt text\npdfjs-editor-alt-text-dialog-label = Choose an option\npdfjs-editor-alt-text-dialog-description = Alt text (alternative text) helps when people can\u2019t see the image or when it doesn\u2019t load.\npdfjs-editor-alt-text-add-description-label = Add a description\npdfjs-editor-alt-text-add-description-description = Aim for 1-2 sentences that describe the subject, setting, or actions.\npdfjs-editor-alt-text-mark-decorative-label = Mark as decorative\npdfjs-editor-alt-text-mark-decorative-description = This is used for ornamental images, like borders or watermarks.\npdfjs-editor-alt-text-cancel-button = Cancel\npdfjs-editor-alt-text-save-button = Save\npdfjs-editor-alt-text-decorative-tooltip = Marked as decorative\npdfjs-editor-alt-text-textarea =\n .placeholder = For example, \u201CA young man sits down at a table to eat a meal\u201D\npdfjs-editor-resizer-top-left =\n .aria-label = Top left corner \u2014 resize\npdfjs-editor-resizer-top-middle =\n .aria-label = Top middle \u2014 resize\npdfjs-editor-resizer-top-right =\n .aria-label = Top right corner \u2014 resize\npdfjs-editor-resizer-middle-right =\n .aria-label = Middle right \u2014 resize\npdfjs-editor-resizer-bottom-right =\n .aria-label = Bottom right corner \u2014 resize\npdfjs-editor-resizer-bottom-middle =\n .aria-label = Bottom middle \u2014 resize\npdfjs-editor-resizer-bottom-left =\n .aria-label = Bottom left corner \u2014 resize\npdfjs-editor-resizer-middle-left =\n .aria-label = Middle left \u2014 resize\npdfjs-editor-highlight-colorpicker-label = Highlight color\npdfjs-editor-colorpicker-button =\n .title = Change color\npdfjs-editor-colorpicker-dropdown =\n .aria-label = Color choices\npdfjs-editor-colorpicker-yellow =\n .title = Yellow\npdfjs-editor-colorpicker-green =\n .title = Green\npdfjs-editor-colorpicker-blue =\n .title = Blue\npdfjs-editor-colorpicker-pink =\n .title = Pink\npdfjs-editor-colorpicker-red =\n .title = Red\npdfjs-editor-highlight-show-all-button-label = Show all\npdfjs-editor-highlight-show-all-button =\n .title = Show all\npdfjs-editor-new-alt-text-dialog-edit-label = Edit alt text (image description)\npdfjs-editor-new-alt-text-dialog-add-label = Add alt text (image description)\npdfjs-editor-new-alt-text-textarea =\n .placeholder = Write your description here\u2026\npdfjs-editor-new-alt-text-description = Short description for people who can\u2019t see the image or when the image doesn\u2019t load.\npdfjs-editor-new-alt-text-disclaimer1 = This alt text was created automatically and may be inaccurate.\npdfjs-editor-new-alt-text-disclaimer-learn-more-url = Learn more\npdfjs-editor-new-alt-text-create-automatically-button-label = Create alt text automatically\npdfjs-editor-new-alt-text-not-now-button = Not now\npdfjs-editor-new-alt-text-error-title = Couldn\u2019t create alt text automatically\npdfjs-editor-new-alt-text-error-description = Please write your own alt text or try again later.\npdfjs-editor-new-alt-text-error-close-button = Close\npdfjs-editor-new-alt-text-ai-model-downloading-progress = Downloading alt text AI model ({ $downloadedSize } of { $totalSize } MB)\n .aria-valuetext = Downloading alt text AI model ({ $downloadedSize } of { $totalSize } MB)\npdfjs-editor-new-alt-text-added-button =\n .aria-label = Alt text added\npdfjs-editor-new-alt-text-added-button-label = Alt text added\npdfjs-editor-new-alt-text-missing-button =\n .aria-label = Missing alt text\npdfjs-editor-new-alt-text-missing-button-label = Missing alt text\npdfjs-editor-new-alt-text-to-review-button =\n .aria-label = Review alt text\npdfjs-editor-new-alt-text-to-review-button-label = Review alt text\npdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer = Created automatically: { $generatedAltText }\npdfjs-image-alt-text-settings-button =\n .title = Image alt text settings\npdfjs-image-alt-text-settings-button-label = Image alt text settings\npdfjs-editor-alt-text-settings-dialog-label = Image alt text settings\npdfjs-editor-alt-text-settings-automatic-title = Automatic alt text\npdfjs-editor-alt-text-settings-create-model-button-label = Create alt text automatically\npdfjs-editor-alt-text-settings-create-model-description = Suggests descriptions to help people who can\u2019t see the image or when the image doesn\u2019t load.\npdfjs-editor-alt-text-settings-download-model-label = Alt text AI model ({ $totalSize } MB)\npdfjs-editor-alt-text-settings-ai-model-description = Runs locally on your device so your data stays private. Required for automatic alt text.\npdfjs-editor-alt-text-settings-delete-model-button = Delete\npdfjs-editor-alt-text-settings-download-model-button = Download\npdfjs-editor-alt-text-settings-downloading-model-button = Downloading\u2026\npdfjs-editor-alt-text-settings-editor-title = Alt text editor\npdfjs-editor-alt-text-settings-show-dialog-button-label = Show alt text editor right away when adding an image\npdfjs-editor-alt-text-settings-show-dialog-description = Helps you make sure all your images have alt text.\npdfjs-editor-alt-text-settings-close-button = Close\npdfjs-editor-undo-bar-message-highlight = Highlight removed\npdfjs-editor-undo-bar-message-freetext = Text removed\npdfjs-editor-undo-bar-message-ink = Drawing removed\npdfjs-editor-undo-bar-message-stamp = Image removed\npdfjs-editor-undo-bar-message-multiple =\n { $count ->\n [one] { $count } annotation removed\n *[other] { $count } annotations removed\n }\npdfjs-editor-undo-bar-undo-button =\n .title = Undo\npdfjs-editor-undo-bar-undo-button-label = Undo\npdfjs-editor-undo-bar-close-button =\n .title = Close\npdfjs-editor-undo-bar-close-button-label = Close"; - return createBundle(lang, text); - } -} - -;// ./web/pdf_history.js - - -const HASH_CHANGE_TIMEOUT = 1000; -const POSITION_UPDATED_THRESHOLD = 50; -const UPDATE_VIEWAREA_TIMEOUT = 1000; -function getCurrentHash() { - return document.location.hash; -} -class PDFHistory { - #eventAbortController = null; - constructor({ - linkService, - eventBus - }) { - this.linkService = linkService; - this.eventBus = eventBus; - this._initialized = false; - this._fingerprint = ""; - this.reset(); - this.eventBus._on("pagesinit", () => { - this._isPagesLoaded = false; - this.eventBus._on("pagesloaded", evt => { - this._isPagesLoaded = !!evt.pagesCount; - }, { - once: true - }); - }); - } - initialize({ - fingerprint, - resetHistory = false, - updateUrl = false - }) { - if (!fingerprint || typeof fingerprint !== "string") { - console.error('PDFHistory.initialize: The "fingerprint" must be a non-empty string.'); - return; - } - if (this._initialized) { - this.reset(); - } - const reInitialized = this._fingerprint !== "" && this._fingerprint !== fingerprint; - this._fingerprint = fingerprint; - this._updateUrl = updateUrl === true; - this._initialized = true; - this.#bindEvents(); - const state = window.history.state; - this._popStateInProgress = false; - this._blockHashChange = 0; - this._currentHash = getCurrentHash(); - this._numPositionUpdates = 0; - this._uid = this._maxUid = 0; - this._destination = null; - this._position = null; - if (!this.#isValidState(state, true) || resetHistory) { - const { - hash, - page, - rotation - } = this.#parseCurrentHash(true); - if (!hash || reInitialized || resetHistory) { - this.#pushOrReplaceState(null, true); - return; - } - this.#pushOrReplaceState({ - hash, - page, - rotation - }, true); - return; - } - const destination = state.destination; - this.#updateInternalState(destination, state.uid, true); - if (destination.rotation !== undefined) { - this._initialRotation = destination.rotation; - } - if (destination.dest) { - this._initialBookmark = JSON.stringify(destination.dest); - this._destination.page = null; - } else if (destination.hash) { - this._initialBookmark = destination.hash; - } else if (destination.page) { - this._initialBookmark = `page=${destination.page}`; - } - } - reset() { - if (this._initialized) { - this.#pageHide(); - this._initialized = false; - this.#unbindEvents(); - } - if (this._updateViewareaTimeout) { - clearTimeout(this._updateViewareaTimeout); - this._updateViewareaTimeout = null; - } - this._initialBookmark = null; - this._initialRotation = null; - } - push({ - namedDest = null, - explicitDest, - pageNumber - }) { - if (!this._initialized) { - return; - } - if (namedDest && typeof namedDest !== "string") { - console.error("PDFHistory.push: " + `"${namedDest}" is not a valid namedDest parameter.`); - return; - } else if (!Array.isArray(explicitDest)) { - console.error("PDFHistory.push: " + `"${explicitDest}" is not a valid explicitDest parameter.`); - return; - } else if (!this.#isValidPage(pageNumber)) { - if (pageNumber !== null || this._destination) { - console.error("PDFHistory.push: " + `"${pageNumber}" is not a valid pageNumber parameter.`); - return; - } - } - const hash = namedDest || JSON.stringify(explicitDest); - if (!hash) { - return; - } - let forceReplace = false; - if (this._destination && (isDestHashesEqual(this._destination.hash, hash) || isDestArraysEqual(this._destination.dest, explicitDest))) { - if (this._destination.page) { - return; - } - forceReplace = true; - } - if (this._popStateInProgress && !forceReplace) { - return; - } - this.#pushOrReplaceState({ - dest: explicitDest, - hash, - page: pageNumber, - rotation: this.linkService.rotation - }, forceReplace); - if (!this._popStateInProgress) { - this._popStateInProgress = true; - Promise.resolve().then(() => { - this._popStateInProgress = false; - }); - } - } - pushPage(pageNumber) { - if (!this._initialized) { - return; - } - if (!this.#isValidPage(pageNumber)) { - console.error(`PDFHistory.pushPage: "${pageNumber}" is not a valid page number.`); - return; - } - if (this._destination?.page === pageNumber) { - return; - } - if (this._popStateInProgress) { - return; - } - this.#pushOrReplaceState({ - dest: null, - hash: `page=${pageNumber}`, - page: pageNumber, - rotation: this.linkService.rotation - }); - if (!this._popStateInProgress) { - this._popStateInProgress = true; - Promise.resolve().then(() => { - this._popStateInProgress = false; - }); - } - } - pushCurrentPosition() { - if (!this._initialized || this._popStateInProgress) { - return; - } - this.#tryPushCurrentPosition(); - } - back() { - if (!this._initialized || this._popStateInProgress) { - return; - } - const state = window.history.state; - if (this.#isValidState(state) && state.uid > 0) { - window.history.back(); - } - } - forward() { - if (!this._initialized || this._popStateInProgress) { - return; - } - const state = window.history.state; - if (this.#isValidState(state) && state.uid < this._maxUid) { - window.history.forward(); - } - } - get popStateInProgress() { - return this._initialized && (this._popStateInProgress || this._blockHashChange > 0); - } - get initialBookmark() { - return this._initialized ? this._initialBookmark : null; - } - get initialRotation() { - return this._initialized ? this._initialRotation : null; - } - #pushOrReplaceState(destination, forceReplace = false) { - const shouldReplace = forceReplace || !this._destination; - const newState = { - fingerprint: this._fingerprint, - uid: shouldReplace ? this._uid : this._uid + 1, - destination - }; - this.#updateInternalState(destination, newState.uid); - let newUrl; - if (this._updateUrl && destination?.hash) { - const baseUrl = document.location.href.split("#", 1)[0]; - if (!baseUrl.startsWith("file://")) { - newUrl = `${baseUrl}#${destination.hash}`; - } - } - if (shouldReplace) { - window.history.replaceState(newState, "", newUrl); - } else { - window.history.pushState(newState, "", newUrl); - } - } - #tryPushCurrentPosition(temporary = false) { - if (!this._position) { - return; - } - let position = this._position; - if (temporary) { - position = Object.assign(Object.create(null), this._position); - position.temporary = true; - } - if (!this._destination) { - this.#pushOrReplaceState(position); - return; - } - if (this._destination.temporary) { - this.#pushOrReplaceState(position, true); - return; - } - if (this._destination.hash === position.hash) { - return; - } - if (!this._destination.page && (POSITION_UPDATED_THRESHOLD <= 0 || this._numPositionUpdates <= POSITION_UPDATED_THRESHOLD)) { - return; - } - let forceReplace = false; - if (this._destination.page >= position.first && this._destination.page <= position.page) { - if (this._destination.dest !== undefined || !this._destination.first) { - return; - } - forceReplace = true; - } - this.#pushOrReplaceState(position, forceReplace); - } - #isValidPage(val) { - return Number.isInteger(val) && val > 0 && val <= this.linkService.pagesCount; - } - #isValidState(state, checkReload = false) { - if (!state) { - return false; - } - if (state.fingerprint !== this._fingerprint) { - if (checkReload) { - if (typeof state.fingerprint !== "string" || state.fingerprint.length !== this._fingerprint.length) { - return false; - } - const [perfEntry] = performance.getEntriesByType("navigation"); - if (perfEntry?.type !== "reload") { - return false; - } - } else { - return false; - } - } - if (!Number.isInteger(state.uid) || state.uid < 0) { - return false; - } - if (state.destination === null || typeof state.destination !== "object") { - return false; - } - return true; - } - #updateInternalState(destination, uid, removeTemporary = false) { - if (this._updateViewareaTimeout) { - clearTimeout(this._updateViewareaTimeout); - this._updateViewareaTimeout = null; - } - if (removeTemporary && destination?.temporary) { - delete destination.temporary; - } - this._destination = destination; - this._uid = uid; - this._maxUid = Math.max(this._maxUid, uid); - this._numPositionUpdates = 0; - } - #parseCurrentHash(checkNameddest = false) { - const hash = unescape(getCurrentHash()).substring(1); - const params = parseQueryString(hash); - const nameddest = params.get("nameddest") || ""; - let page = params.get("page") | 0; - if (!this.#isValidPage(page) || checkNameddest && nameddest.length > 0) { - page = null; - } - return { - hash, - page, - rotation: this.linkService.rotation - }; - } - #updateViewarea({ - location - }) { - if (this._updateViewareaTimeout) { - clearTimeout(this._updateViewareaTimeout); - this._updateViewareaTimeout = null; - } - this._position = { - hash: location.pdfOpenParams.substring(1), - page: this.linkService.page, - first: location.pageNumber, - rotation: location.rotation - }; - if (this._popStateInProgress) { - return; - } - if (POSITION_UPDATED_THRESHOLD > 0 && this._isPagesLoaded && this._destination && !this._destination.page) { - this._numPositionUpdates++; - } - if (UPDATE_VIEWAREA_TIMEOUT > 0) { - this._updateViewareaTimeout = setTimeout(() => { - if (!this._popStateInProgress) { - this.#tryPushCurrentPosition(true); - } - this._updateViewareaTimeout = null; - }, UPDATE_VIEWAREA_TIMEOUT); - } - } - #popState({ - state - }) { - const newHash = getCurrentHash(), - hashChanged = this._currentHash !== newHash; - this._currentHash = newHash; - if (!state) { - this._uid++; - const { - hash, - page, - rotation - } = this.#parseCurrentHash(); - this.#pushOrReplaceState({ - hash, - page, - rotation - }, true); - return; - } - if (!this.#isValidState(state)) { - return; - } - this._popStateInProgress = true; - if (hashChanged) { - this._blockHashChange++; - waitOnEventOrTimeout({ - target: window, - name: "hashchange", - delay: HASH_CHANGE_TIMEOUT - }).then(() => { - this._blockHashChange--; - }); - } - const destination = state.destination; - this.#updateInternalState(destination, state.uid, true); - if (isValidRotation(destination.rotation)) { - this.linkService.rotation = destination.rotation; - } - if (destination.dest) { - this.linkService.goToDestination(destination.dest); - } else if (destination.hash) { - this.linkService.setHash(destination.hash); - } else if (destination.page) { - this.linkService.page = destination.page; - } - Promise.resolve().then(() => { - this._popStateInProgress = false; - }); - } - #pageHide() { - if (!this._destination || this._destination.temporary) { - this.#tryPushCurrentPosition(); - } - } - #bindEvents() { - if (this.#eventAbortController) { - return; - } - this.#eventAbortController = new AbortController(); - const { - signal - } = this.#eventAbortController; - this.eventBus._on("updateviewarea", this.#updateViewarea.bind(this), { - signal - }); - window.addEventListener("popstate", this.#popState.bind(this), { - signal - }); - window.addEventListener("pagehide", this.#pageHide.bind(this), { - signal - }); - } - #unbindEvents() { - this.#eventAbortController?.abort(); - this.#eventAbortController = null; - } -} -function isDestHashesEqual(destHash, pushHash) { - if (typeof destHash !== "string" || typeof pushHash !== "string") { - return false; - } - if (destHash === pushHash) { - return true; - } - const nameddest = parseQueryString(destHash).get("nameddest"); - if (nameddest === pushHash) { - return true; - } - return false; -} -function isDestArraysEqual(firstDest, secondDest) { - function isEntryEqual(first, second) { - if (typeof first !== typeof second) { - return false; - } - if (Array.isArray(first) || Array.isArray(second)) { - return false; - } - if (first !== null && typeof first === "object" && second !== null) { - if (Object.keys(first).length !== Object.keys(second).length) { - return false; - } - for (const key in first) { - if (!isEntryEqual(first[key], second[key])) { - return false; - } - } - return true; - } - return first === second || Number.isNaN(first) && Number.isNaN(second); - } - if (!(Array.isArray(firstDest) && Array.isArray(secondDest))) { - return false; - } - if (firstDest.length !== secondDest.length) { - return false; - } - for (let i = 0, ii = firstDest.length; i < ii; i++) { - if (!isEntryEqual(firstDest[i], secondDest[i])) { - return false; - } - } - return true; -} - -;// ./web/annotation_editor_layer_builder.js - - -class AnnotationEditorLayerBuilder { - #annotationLayer = null; - #drawLayer = null; - #onAppend = null; - #structTreeLayer = null; - #textLayer = null; - #uiManager; - constructor(options) { - this.pdfPage = options.pdfPage; - this.accessibilityManager = options.accessibilityManager; - this.l10n = options.l10n; - this.l10n ||= new genericl10n_GenericL10n(); - this.annotationEditorLayer = null; - this.div = null; - this._cancelled = false; - this.#uiManager = options.uiManager; - this.#annotationLayer = options.annotationLayer || null; - this.#textLayer = options.textLayer || null; - this.#drawLayer = options.drawLayer || null; - this.#onAppend = options.onAppend || null; - this.#structTreeLayer = options.structTreeLayer || null; - } - async render(viewport, intent = "display") { - if (intent !== "display") { - return; - } - if (this._cancelled) { - return; - } - const clonedViewport = viewport.clone({ - dontFlip: true - }); - if (this.div) { - this.annotationEditorLayer.update({ - viewport: clonedViewport - }); - this.show(); - return; - } - const div = this.div = document.createElement("div"); - div.className = "annotationEditorLayer"; - div.hidden = true; - div.dir = this.#uiManager.direction; - this.#onAppend?.(div); - this.annotationEditorLayer = new AnnotationEditorLayer({ - uiManager: this.#uiManager, - div, - structTreeLayer: this.#structTreeLayer, - accessibilityManager: this.accessibilityManager, - pageIndex: this.pdfPage.pageNumber - 1, - l10n: this.l10n, - viewport: clonedViewport, - annotationLayer: this.#annotationLayer, - textLayer: this.#textLayer, - drawLayer: this.#drawLayer - }); - const parameters = { - viewport: clonedViewport, - div, - annotations: null, - intent - }; - this.annotationEditorLayer.render(parameters); - this.show(); - } - cancel() { - this._cancelled = true; - if (!this.div) { - return; - } - this.annotationEditorLayer.destroy(); - } - hide() { - if (!this.div) { - return; - } - this.annotationEditorLayer.pause(true); - this.div.hidden = true; - } - show() { - if (!this.div || this.annotationEditorLayer.isInvisible) { - return; - } - this.div.hidden = false; - this.annotationEditorLayer.pause(false); - } -} - -;// ./web/app_options.js -{ - var compatParams = new Map(); - const userAgent = navigator.userAgent || ""; - const platform = navigator.platform || ""; - const maxTouchPoints = navigator.maxTouchPoints || 1; - const isAndroid = /Android/.test(userAgent); - const isIOS = /\b(iPad|iPhone|iPod)(?=;)/.test(userAgent) || platform === "MacIntel" && maxTouchPoints > 1; - (function () { - if (isIOS || isAndroid) { - compatParams.set("maxCanvasPixels", 5242880); - } - })(); - (function () { - if (isAndroid) { - compatParams.set("useSystemFonts", false); - } - })(); -} -const OptionKind = { - BROWSER: 0x01, - VIEWER: 0x02, - API: 0x04, - WORKER: 0x08, - EVENT_DISPATCH: 0x10, - PREFERENCE: 0x80 -}; -const Type = { - BOOLEAN: 0x01, - NUMBER: 0x02, - OBJECT: 0x04, - STRING: 0x08, - UNDEFINED: 0x10 -}; -const defaultOptions = { - allowedGlobalEvents: { - value: null, - kind: OptionKind.BROWSER - }, - canvasMaxAreaInBytes: { - value: -1, - kind: OptionKind.BROWSER + OptionKind.API - }, - isInAutomation: { - value: false, - kind: OptionKind.BROWSER - }, - localeProperties: { - value: { - lang: navigator.language || "en-US" - }, - kind: OptionKind.BROWSER - }, - nimbusDataStr: { - value: "", - kind: OptionKind.BROWSER - }, - supportsCaretBrowsingMode: { - value: false, - kind: OptionKind.BROWSER - }, - supportsDocumentFonts: { - value: true, - kind: OptionKind.BROWSER - }, - supportsIntegratedFind: { - value: false, - kind: OptionKind.BROWSER - }, - supportsMouseWheelZoomCtrlKey: { - value: true, - kind: OptionKind.BROWSER - }, - supportsMouseWheelZoomMetaKey: { - value: true, - kind: OptionKind.BROWSER - }, - supportsPinchToZoom: { - value: true, - kind: OptionKind.BROWSER - }, - toolbarDensity: { - value: 0, - kind: OptionKind.BROWSER + OptionKind.EVENT_DISPATCH - }, - altTextLearnMoreUrl: { - value: "", - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - annotationEditorMode: { - value: 0, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - annotationMode: { - value: 2, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - cursorToolOnLoad: { - value: 0, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - debuggerSrc: { - value: "./debugger.mjs", - kind: OptionKind.VIEWER - }, - defaultZoomDelay: { - value: 400, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - defaultZoomValue: { - value: "", - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - disableHistory: { - value: false, - kind: OptionKind.VIEWER - }, - disablePageLabels: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enableAltText: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enableAltTextModelDownload: { - value: true, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE + OptionKind.EVENT_DISPATCH - }, - enableGuessAltText: { - value: true, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE + OptionKind.EVENT_DISPATCH - }, - enableHighlightFloatingButton: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enableNewAltTextWhenAddingImage: { - value: true, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enablePermissions: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enablePrintAutoRotate: { - value: true, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enableScripting: { - value: true, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enableUpdatedAddImage: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - externalLinkRel: { - value: "noopener noreferrer nofollow", - kind: OptionKind.VIEWER - }, - externalLinkTarget: { - value: 0, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - highlightEditorColors: { - value: "yellow=#FFFF98,green=#53FFBC,blue=#80EBFF,pink=#FFCBE6,red=#FF4F5F", - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - historyUpdateUrl: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - ignoreDestinationZoom: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - imageResourcesPath: { - value: "./images/", - kind: OptionKind.VIEWER - }, - maxCanvasPixels: { - value: 2 ** 25, - kind: OptionKind.VIEWER - }, - forcePageColors: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - pageColorsBackground: { - value: "Canvas", - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - pageColorsForeground: { - value: "CanvasText", - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - pdfBugEnabled: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - printResolution: { - value: 150, - kind: OptionKind.VIEWER - }, - sidebarViewOnLoad: { - value: -1, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - scrollModeOnLoad: { - value: -1, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - spreadModeOnLoad: { - value: -1, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - textLayerMode: { - value: 1, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - viewOnLoad: { - value: 0, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - cMapPacked: { - value: true, - kind: OptionKind.API - }, - cMapUrl: { - value: "../web/cmaps/", - kind: OptionKind.API - }, - disableAutoFetch: { - value: false, - kind: OptionKind.API + OptionKind.PREFERENCE - }, - disableFontFace: { - value: false, - kind: OptionKind.API + OptionKind.PREFERENCE - }, - disableRange: { - value: false, - kind: OptionKind.API + OptionKind.PREFERENCE - }, - disableStream: { - value: false, - kind: OptionKind.API + OptionKind.PREFERENCE - }, - docBaseUrl: { - value: "", - kind: OptionKind.API - }, - enableHWA: { - value: true, - kind: OptionKind.API + OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enableXfa: { - value: true, - kind: OptionKind.API + OptionKind.PREFERENCE - }, - fontExtraProperties: { - value: false, - kind: OptionKind.API - }, - isEvalSupported: { - value: true, - kind: OptionKind.API - }, - isOffscreenCanvasSupported: { - value: true, - kind: OptionKind.API - }, - maxImageSize: { - value: -1, - kind: OptionKind.API - }, - pdfBug: { - value: false, - kind: OptionKind.API - }, - standardFontDataUrl: { - value: "../web/standard_fonts/", - kind: OptionKind.API - }, - useSystemFonts: { - value: undefined, - kind: OptionKind.API, - type: Type.BOOLEAN + Type.UNDEFINED - }, - verbosity: { - value: 1, - kind: OptionKind.API - }, - workerPort: { - value: null, - kind: OptionKind.WORKER - }, - workerSrc: { - value: "../build/pdf.worker.mjs", - kind: OptionKind.WORKER - } -}; -{ - defaultOptions.defaultUrl = { - value: "compressed.tracemonkey-pldi-09.pdf", - kind: OptionKind.VIEWER - }; - defaultOptions.sandboxBundleSrc = { - value: "../build/pdf.sandbox.mjs", - kind: OptionKind.VIEWER - }; - defaultOptions.viewerCssTheme = { - value: 0, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }; - defaultOptions.enableFakeMLManager = { - value: true, - kind: OptionKind.VIEWER - }; -} -{ - defaultOptions.disablePreferences = { - value: false, - kind: OptionKind.VIEWER - }; -} -class AppOptions { - static eventBus; - static #opts = new Map(); - static { - for (const name in defaultOptions) { - this.#opts.set(name, defaultOptions[name].value); - } - for (const [name, value] of compatParams) { - this.#opts.set(name, value); - } - this._hasInvokedSet = false; - this._checkDisablePreferences = () => { - if (this.get("disablePreferences")) { - return true; - } - if (this._hasInvokedSet) { - console.warn("The Preferences may override manually set AppOptions; " + 'please use the "disablePreferences"-option to prevent that.'); - } - return false; - }; - } - static get(name) { - return this.#opts.get(name); - } - static getAll(kind = null, defaultOnly = false) { - const options = Object.create(null); - for (const name in defaultOptions) { - const defaultOpt = defaultOptions[name]; - if (kind && !(kind & defaultOpt.kind)) { - continue; - } - options[name] = !defaultOnly ? this.#opts.get(name) : defaultOpt.value; - } - return options; - } - static set(name, value) { - this.setAll({ - [name]: value - }); - } - static setAll(options, prefs = false) { - this._hasInvokedSet ||= true; - let events; - for (const name in options) { - const defaultOpt = defaultOptions[name], - userOpt = options[name]; - if (!defaultOpt || !(typeof userOpt === typeof defaultOpt.value || Type[(typeof userOpt).toUpperCase()] & defaultOpt.type)) { - continue; - } - const { - kind - } = defaultOpt; - if (prefs && !(kind & OptionKind.BROWSER || kind & OptionKind.PREFERENCE)) { - continue; - } - if (this.eventBus && kind & OptionKind.EVENT_DISPATCH) { - (events ||= new Map()).set(name, userOpt); - } - this.#opts.set(name, userOpt); - } - if (events) { - for (const [name, value] of events) { - this.eventBus.dispatch(name.toLowerCase(), { - source: this, - value - }); - } - } - } -} - -;// ./web/draw_layer_builder.js - -class DrawLayerBuilder { - #drawLayer = null; - constructor(options) { - this.pageIndex = options.pageIndex; - } - async render(intent = "display") { - if (intent !== "display" || this.#drawLayer || this._cancelled) { - return; - } - this.#drawLayer = new DrawLayer({ - pageIndex: this.pageIndex - }); - } - cancel() { - this._cancelled = true; - if (!this.#drawLayer) { - return; - } - this.#drawLayer.destroy(); - this.#drawLayer = null; - } - setParent(parent) { - this.#drawLayer?.setParent(parent); - } - getDrawLayer() { - return this.#drawLayer; - } -} - -;// ./web/struct_tree_layer_builder.js - -const PDF_ROLE_TO_HTML_ROLE = { - Document: null, - DocumentFragment: null, - Part: "group", - Sect: "group", - Div: "group", - Aside: "note", - NonStruct: "none", - P: null, - H: "heading", - Title: null, - FENote: "note", - Sub: "group", - Lbl: null, - Span: null, - Em: null, - Strong: null, - Link: "link", - Annot: "note", - Form: "form", - Ruby: null, - RB: null, - RT: null, - RP: null, - Warichu: null, - WT: null, - WP: null, - L: "list", - LI: "listitem", - LBody: null, - Table: "table", - TR: "row", - TH: "columnheader", - TD: "cell", - THead: "columnheader", - TBody: null, - TFoot: null, - Caption: null, - Figure: "figure", - Formula: null, - Artifact: null -}; -const HEADING_PATTERN = /^H(\d+)$/; -class StructTreeLayerBuilder { - #promise; - #treeDom = null; - #treePromise; - #elementAttributes = new Map(); - #rawDims; - #elementsToAddToTextLayer = null; - constructor(pdfPage, rawDims) { - this.#promise = pdfPage.getStructTree(); - this.#rawDims = rawDims; - } - async render() { - if (this.#treePromise) { - return this.#treePromise; - } - const { - promise, - resolve, - reject - } = Promise.withResolvers(); - this.#treePromise = promise; - try { - this.#treeDom = this.#walk(await this.#promise); - } catch (ex) { - reject(ex); - } - this.#promise = null; - this.#treeDom?.classList.add("structTree"); - resolve(this.#treeDom); - return promise; - } - async getAriaAttributes(annotationId) { - try { - await this.render(); - return this.#elementAttributes.get(annotationId); - } catch {} - return null; - } - hide() { - if (this.#treeDom && !this.#treeDom.hidden) { - this.#treeDom.hidden = true; - } - } - show() { - if (this.#treeDom?.hidden) { - this.#treeDom.hidden = false; - } - } - #setAttributes(structElement, htmlElement) { - const { - alt, - id, - lang - } = structElement; - if (alt !== undefined) { - let added = false; - const label = removeNullCharacters(alt); - for (const child of structElement.children) { - if (child.type === "annotation") { - let attrs = this.#elementAttributes.get(child.id); - if (!attrs) { - attrs = new Map(); - this.#elementAttributes.set(child.id, attrs); - } - attrs.set("aria-label", label); - added = true; - } - } - if (!added) { - htmlElement.setAttribute("aria-label", label); - } - } - if (id !== undefined) { - htmlElement.setAttribute("aria-owns", id); - } - if (lang !== undefined) { - htmlElement.setAttribute("lang", removeNullCharacters(lang, true)); - } - } - #addImageInTextLayer(node, element) { - const { - alt, - bbox, - children - } = node; - const child = children?.[0]; - if (!this.#rawDims || !alt || !bbox || child?.type !== "content") { - return false; - } - const { - id - } = child; - if (!id) { - return false; - } - element.setAttribute("aria-owns", id); - const img = document.createElement("span"); - (this.#elementsToAddToTextLayer ||= new Map()).set(id, img); - img.setAttribute("role", "img"); - img.setAttribute("aria-label", removeNullCharacters(alt)); - const { - pageHeight, - pageX, - pageY - } = this.#rawDims; - const calc = "calc(var(--scale-factor)*"; - const { - style - } = img; - style.width = `${calc}${bbox[2] - bbox[0]}px)`; - style.height = `${calc}${bbox[3] - bbox[1]}px)`; - style.left = `${calc}${bbox[0] - pageX}px)`; - style.top = `${calc}${pageHeight - bbox[3] + pageY}px)`; - return true; - } - addElementsToTextLayer() { - if (!this.#elementsToAddToTextLayer) { - return; - } - for (const [id, img] of this.#elementsToAddToTextLayer) { - document.getElementById(id)?.append(img); - } - this.#elementsToAddToTextLayer.clear(); - this.#elementsToAddToTextLayer = null; - } - #walk(node) { - if (!node) { - return null; - } - const element = document.createElement("span"); - if ("role" in node) { - const { - role - } = node; - const match = role.match(HEADING_PATTERN); - if (match) { - element.setAttribute("role", "heading"); - element.setAttribute("aria-level", match[1]); - } else if (PDF_ROLE_TO_HTML_ROLE[role]) { - element.setAttribute("role", PDF_ROLE_TO_HTML_ROLE[role]); - } - if (role === "Figure" && this.#addImageInTextLayer(node, element)) { - return element; - } - } - this.#setAttributes(node, element); - if (node.children) { - if (node.children.length === 1 && "id" in node.children[0]) { - this.#setAttributes(node.children[0], element); - } else { - for (const kid of node.children) { - element.append(this.#walk(kid)); - } - } - } - return element; - } -} - -;// ./web/text_accessibility.js - -class TextAccessibilityManager { - #enabled = false; - #textChildren = null; - #textNodes = new Map(); - #waitingElements = new Map(); - setTextMapping(textDivs) { - this.#textChildren = textDivs; - } - static #compareElementPositions(e1, e2) { - const rect1 = e1.getBoundingClientRect(); - const rect2 = e2.getBoundingClientRect(); - if (rect1.width === 0 && rect1.height === 0) { - return +1; - } - if (rect2.width === 0 && rect2.height === 0) { - return -1; - } - const top1 = rect1.y; - const bot1 = rect1.y + rect1.height; - const mid1 = rect1.y + rect1.height / 2; - const top2 = rect2.y; - const bot2 = rect2.y + rect2.height; - const mid2 = rect2.y + rect2.height / 2; - if (mid1 <= top2 && mid2 >= bot1) { - return -1; - } - if (mid2 <= top1 && mid1 >= bot2) { - return +1; - } - const centerX1 = rect1.x + rect1.width / 2; - const centerX2 = rect2.x + rect2.width / 2; - return centerX1 - centerX2; - } - enable() { - if (this.#enabled) { - throw new Error("TextAccessibilityManager is already enabled."); - } - if (!this.#textChildren) { - throw new Error("Text divs and strings have not been set."); - } - this.#enabled = true; - this.#textChildren = this.#textChildren.slice(); - this.#textChildren.sort(TextAccessibilityManager.#compareElementPositions); - if (this.#textNodes.size > 0) { - const textChildren = this.#textChildren; - for (const [id, nodeIndex] of this.#textNodes) { - const element = document.getElementById(id); - if (!element) { - this.#textNodes.delete(id); - continue; - } - this.#addIdToAriaOwns(id, textChildren[nodeIndex]); - } - } - for (const [element, isRemovable] of this.#waitingElements) { - this.addPointerInTextLayer(element, isRemovable); - } - this.#waitingElements.clear(); - } - disable() { - if (!this.#enabled) { - return; - } - this.#waitingElements.clear(); - this.#textChildren = null; - this.#enabled = false; - } - removePointerInTextLayer(element) { - if (!this.#enabled) { - this.#waitingElements.delete(element); - return; - } - const children = this.#textChildren; - if (!children || children.length === 0) { - return; - } - const { - id - } = element; - const nodeIndex = this.#textNodes.get(id); - if (nodeIndex === undefined) { - return; - } - const node = children[nodeIndex]; - this.#textNodes.delete(id); - let owns = node.getAttribute("aria-owns"); - if (owns?.includes(id)) { - owns = owns.split(" ").filter(x => x !== id).join(" "); - if (owns) { - node.setAttribute("aria-owns", owns); - } else { - node.removeAttribute("aria-owns"); - node.setAttribute("role", "presentation"); - } - } - } - #addIdToAriaOwns(id, node) { - const owns = node.getAttribute("aria-owns"); - if (!owns?.includes(id)) { - node.setAttribute("aria-owns", owns ? `${owns} ${id}` : id); - } - node.removeAttribute("role"); - } - addPointerInTextLayer(element, isRemovable) { - const { - id - } = element; - if (!id) { - return null; - } - if (!this.#enabled) { - this.#waitingElements.set(element, isRemovable); - return null; - } - if (isRemovable) { - this.removePointerInTextLayer(element); - } - const children = this.#textChildren; - if (!children || children.length === 0) { - return null; - } - const index = binarySearchFirstItem(children, node => TextAccessibilityManager.#compareElementPositions(element, node) < 0); - const nodeIndex = Math.max(0, index - 1); - const child = children[nodeIndex]; - this.#addIdToAriaOwns(id, child); - this.#textNodes.set(id, nodeIndex); - const parent = child.parentNode; - return parent?.classList.contains("markedContent") ? parent.id : null; - } - moveElementInDOM(container, element, contentElement, isRemovable) { - const id = this.addPointerInTextLayer(contentElement, isRemovable); - if (!container.hasChildNodes()) { - container.append(element); - return id; - } - const children = Array.from(container.childNodes).filter(node => node !== element); - if (children.length === 0) { - return id; - } - const elementToCompare = contentElement || element; - const index = binarySearchFirstItem(children, node => TextAccessibilityManager.#compareElementPositions(elementToCompare, node) < 0); - if (index === 0) { - children[0].before(element); - } else { - children[index - 1].after(element); - } - return id; - } -} - -;// ./web/text_highlighter.js -class TextHighlighter { - #eventAbortController = null; - constructor({ - findController, - eventBus, - pageIndex - }) { - this.findController = findController; - this.matches = []; - this.eventBus = eventBus; - this.pageIdx = pageIndex; - this.textDivs = null; - this.textContentItemsStr = null; - this.enabled = false; - } - setTextMapping(divs, texts) { - this.textDivs = divs; - this.textContentItemsStr = texts; - } - enable() { - if (!this.textDivs || !this.textContentItemsStr) { - throw new Error("Text divs and strings have not been set."); - } - if (this.enabled) { - throw new Error("TextHighlighter is already enabled."); - } - this.enabled = true; - if (!this.#eventAbortController) { - this.#eventAbortController = new AbortController(); - this.eventBus._on("updatetextlayermatches", evt => { - if (evt.pageIndex === this.pageIdx || evt.pageIndex === -1) { - this._updateMatches(); - } - }, { - signal: this.#eventAbortController.signal - }); - } - this._updateMatches(); - } - disable() { - if (!this.enabled) { - return; - } - this.enabled = false; - this.#eventAbortController?.abort(); - this.#eventAbortController = null; - this._updateMatches(true); - } - _convertMatches(matches, matchesLength) { - if (!matches) { - return []; - } - const { - textContentItemsStr - } = this; - let i = 0, - iIndex = 0; - const end = textContentItemsStr.length - 1; - const result = []; - for (let m = 0, mm = matches.length; m < mm; m++) { - let matchIdx = matches[m]; - while (i !== end && matchIdx >= iIndex + textContentItemsStr[i].length) { - iIndex += textContentItemsStr[i].length; - i++; - } - if (i === textContentItemsStr.length) { - console.error("Could not find a matching mapping"); - } - const match = { - begin: { - divIdx: i, - offset: matchIdx - iIndex - } - }; - matchIdx += matchesLength[m]; - while (i !== end && matchIdx > iIndex + textContentItemsStr[i].length) { - iIndex += textContentItemsStr[i].length; - i++; - } - match.end = { - divIdx: i, - offset: matchIdx - iIndex - }; - result.push(match); - } - return result; - } - _renderMatches(matches) { - if (matches.length === 0) { - return; - } - const { - findController, - pageIdx - } = this; - const { - textContentItemsStr, - textDivs - } = this; - const isSelectedPage = pageIdx === findController.selected.pageIdx; - const selectedMatchIdx = findController.selected.matchIdx; - const highlightAll = findController.state.highlightAll; - let prevEnd = null; - const infinity = { - divIdx: -1, - offset: undefined - }; - function beginText(begin, className) { - const divIdx = begin.divIdx; - textDivs[divIdx].textContent = ""; - return appendTextToDiv(divIdx, 0, begin.offset, className); - } - function appendTextToDiv(divIdx, fromOffset, toOffset, className) { - let div = textDivs[divIdx]; - if (div.nodeType === Node.TEXT_NODE) { - const span = document.createElement("span"); - div.before(span); - span.append(div); - textDivs[divIdx] = span; - div = span; - } - const content = textContentItemsStr[divIdx].substring(fromOffset, toOffset); - const node = document.createTextNode(content); - if (className) { - const span = document.createElement("span"); - span.className = `${className} appended`; - span.append(node); - div.append(span); - if (className.includes("selected")) { - const { - left - } = span.getClientRects()[0]; - const parentLeft = div.getBoundingClientRect().left; - return left - parentLeft; - } - return 0; - } - div.append(node); - return 0; - } - let i0 = selectedMatchIdx, - i1 = i0 + 1; - if (highlightAll) { - i0 = 0; - i1 = matches.length; - } else if (!isSelectedPage) { - return; - } - let lastDivIdx = -1; - let lastOffset = -1; - for (let i = i0; i < i1; i++) { - const match = matches[i]; - const begin = match.begin; - if (begin.divIdx === lastDivIdx && begin.offset === lastOffset) { - continue; - } - lastDivIdx = begin.divIdx; - lastOffset = begin.offset; - const end = match.end; - const isSelected = isSelectedPage && i === selectedMatchIdx; - const highlightSuffix = isSelected ? " selected" : ""; - let selectedLeft = 0; - if (!prevEnd || begin.divIdx !== prevEnd.divIdx) { - if (prevEnd !== null) { - appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset); - } - beginText(begin); - } else { - appendTextToDiv(prevEnd.divIdx, prevEnd.offset, begin.offset); - } - if (begin.divIdx === end.divIdx) { - selectedLeft = appendTextToDiv(begin.divIdx, begin.offset, end.offset, "highlight" + highlightSuffix); - } else { - selectedLeft = appendTextToDiv(begin.divIdx, begin.offset, infinity.offset, "highlight begin" + highlightSuffix); - for (let n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) { - textDivs[n0].className = "highlight middle" + highlightSuffix; - } - beginText(end, "highlight end" + highlightSuffix); - } - prevEnd = end; - if (isSelected) { - findController.scrollMatchIntoView({ - element: textDivs[begin.divIdx], - selectedLeft, - pageIndex: pageIdx, - matchIndex: selectedMatchIdx - }); - } - } - if (prevEnd) { - appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset); - } - } - _updateMatches(reset = false) { - if (!this.enabled && !reset) { - return; - } - const { - findController, - matches, - pageIdx - } = this; - const { - textContentItemsStr, - textDivs - } = this; - let clearedUntilDivIdx = -1; - for (const match of matches) { - const begin = Math.max(clearedUntilDivIdx, match.begin.divIdx); - for (let n = begin, end = match.end.divIdx; n <= end; n++) { - const div = textDivs[n]; - div.textContent = textContentItemsStr[n]; - div.className = ""; - } - clearedUntilDivIdx = match.end.divIdx + 1; - } - if (!findController?.highlightMatches || reset) { - return; - } - const pageMatches = findController.pageMatches[pageIdx] || null; - const pageMatchesLength = findController.pageMatchesLength[pageIdx] || null; - this.matches = this._convertMatches(pageMatches, pageMatchesLength); - this._renderMatches(this.matches); - } -} - -;// ./web/text_layer_builder.js - - -class TextLayerBuilder { - #enablePermissions = false; - #onAppend = null; - #renderingDone = false; - #textLayer = null; - static #textLayers = new Map(); - static #selectionChangeAbortController = null; - constructor({ - pdfPage, - highlighter = null, - accessibilityManager = null, - enablePermissions = false, - onAppend = null - }) { - this.pdfPage = pdfPage; - this.highlighter = highlighter; - this.accessibilityManager = accessibilityManager; - this.#enablePermissions = enablePermissions === true; - this.#onAppend = onAppend; - this.div = document.createElement("div"); - this.div.tabIndex = 0; - this.div.className = "textLayer"; - } - async render(viewport, textContentParams = null) { - if (this.#renderingDone && this.#textLayer) { - this.#textLayer.update({ - viewport, - onBefore: this.hide.bind(this) - }); - this.show(); - return; - } - this.cancel(); - this.#textLayer = new TextLayer({ - textContentSource: this.pdfPage.streamTextContent(textContentParams || { - includeMarkedContent: true, - disableNormalization: true - }), - container: this.div, - viewport - }); - const { - textDivs, - textContentItemsStr - } = this.#textLayer; - this.highlighter?.setTextMapping(textDivs, textContentItemsStr); - this.accessibilityManager?.setTextMapping(textDivs); - await this.#textLayer.render(); - this.#renderingDone = true; - const endOfContent = document.createElement("div"); - endOfContent.className = "endOfContent"; - this.div.append(endOfContent); - this.#bindMouse(endOfContent); - this.#onAppend?.(this.div); - this.highlighter?.enable(); - this.accessibilityManager?.enable(); - } - hide() { - if (!this.div.hidden && this.#renderingDone) { - this.highlighter?.disable(); - this.div.hidden = true; - } - } - show() { - if (this.div.hidden && this.#renderingDone) { - this.div.hidden = false; - this.highlighter?.enable(); - } - } - cancel() { - this.#textLayer?.cancel(); - this.#textLayer = null; - this.highlighter?.disable(); - this.accessibilityManager?.disable(); - TextLayerBuilder.#removeGlobalSelectionListener(this.div); - } - #bindMouse(end) { - const { - div - } = this; - div.addEventListener("mousedown", () => { - div.classList.add("selecting"); - }); - div.addEventListener("copy", event => { - if (!this.#enablePermissions) { - const selection = document.getSelection(); - event.clipboardData.setData("text/plain", removeNullCharacters(normalizeUnicode(selection.toString()))); - } - stopEvent(event); - }); - TextLayerBuilder.#textLayers.set(div, end); - TextLayerBuilder.#enableGlobalSelectionListener(); - } - static #removeGlobalSelectionListener(textLayerDiv) { - this.#textLayers.delete(textLayerDiv); - if (this.#textLayers.size === 0) { - this.#selectionChangeAbortController?.abort(); - this.#selectionChangeAbortController = null; - } - } - static #enableGlobalSelectionListener() { - if (this.#selectionChangeAbortController) { - return; - } - this.#selectionChangeAbortController = new AbortController(); - const { - signal - } = this.#selectionChangeAbortController; - const reset = (end, textLayer) => { - textLayer.append(end); - end.style.width = ""; - end.style.height = ""; - textLayer.classList.remove("selecting"); - }; - let isPointerDown = false; - document.addEventListener("pointerdown", () => { - isPointerDown = true; - }, { - signal - }); - document.addEventListener("pointerup", () => { - isPointerDown = false; - this.#textLayers.forEach(reset); - }, { - signal - }); - window.addEventListener("blur", () => { - isPointerDown = false; - this.#textLayers.forEach(reset); - }, { - signal - }); - document.addEventListener("keyup", () => { - if (!isPointerDown) { - this.#textLayers.forEach(reset); - } - }, { - signal - }); - var isFirefox, prevRange; - document.addEventListener("selectionchange", () => { - const selection = document.getSelection(); - if (selection.rangeCount === 0) { - this.#textLayers.forEach(reset); - return; - } - const activeTextLayers = new Set(); - for (let i = 0; i < selection.rangeCount; i++) { - const range = selection.getRangeAt(i); - for (const textLayerDiv of this.#textLayers.keys()) { - if (!activeTextLayers.has(textLayerDiv) && range.intersectsNode(textLayerDiv)) { - activeTextLayers.add(textLayerDiv); - } - } - } - for (const [textLayerDiv, endDiv] of this.#textLayers) { - if (activeTextLayers.has(textLayerDiv)) { - textLayerDiv.classList.add("selecting"); - } else { - reset(endDiv, textLayerDiv); - } - } - isFirefox ??= getComputedStyle(this.#textLayers.values().next().value).getPropertyValue("-moz-user-select") === "none"; - if (isFirefox) { - return; - } - const range = selection.getRangeAt(0); - const modifyStart = prevRange && (range.compareBoundaryPoints(Range.END_TO_END, prevRange) === 0 || range.compareBoundaryPoints(Range.START_TO_END, prevRange) === 0); - let anchor = modifyStart ? range.startContainer : range.endContainer; - if (anchor.nodeType === Node.TEXT_NODE) { - anchor = anchor.parentNode; - } - const parentTextLayer = anchor.parentElement?.closest(".textLayer"); - const endDiv = this.#textLayers.get(parentTextLayer); - if (endDiv) { - endDiv.style.width = parentTextLayer.style.width; - endDiv.style.height = parentTextLayer.style.height; - anchor.parentElement.insertBefore(endDiv, modifyStart ? anchor : anchor.nextSibling); - } - prevRange = range.cloneRange(); - }, { - signal - }); - } -} - -;// ./web/xfa_layer_builder.js - -class XfaLayerBuilder { - constructor({ - pdfPage, - annotationStorage = null, - linkService, - xfaHtml = null - }) { - this.pdfPage = pdfPage; - this.annotationStorage = annotationStorage; - this.linkService = linkService; - this.xfaHtml = xfaHtml; - this.div = null; - this._cancelled = false; - } - async render(viewport, intent = "display") { - if (intent === "print") { - const parameters = { - viewport: viewport.clone({ - dontFlip: true - }), - div: this.div, - xfaHtml: this.xfaHtml, - annotationStorage: this.annotationStorage, - linkService: this.linkService, - intent - }; - this.div = document.createElement("div"); - parameters.div = this.div; - return XfaLayer.render(parameters); - } - const xfaHtml = await this.pdfPage.getXfa(); - if (this._cancelled || !xfaHtml) { - return { - textDivs: [] - }; - } - const parameters = { - viewport: viewport.clone({ - dontFlip: true - }), - div: this.div, - xfaHtml, - annotationStorage: this.annotationStorage, - linkService: this.linkService, - intent - }; - if (this.div) { - return XfaLayer.update(parameters); - } - this.div = document.createElement("div"); - parameters.div = this.div; - return XfaLayer.render(parameters); - } - cancel() { - this._cancelled = true; - } - hide() { - if (!this.div) { - return; - } - this.div.hidden = true; - } -} - -;// ./web/pdf_page_view.js - - - - - - - - - - - - - -const DEFAULT_LAYER_PROPERTIES = { - annotationEditorUIManager: null, - annotationStorage: null, - downloadManager: null, - enableScripting: false, - fieldObjectsPromise: null, - findController: null, - hasJSActionsPromise: null, - get linkService() { - return new SimpleLinkService(); - } -}; -const LAYERS_ORDER = new Map([["canvasWrapper", 0], ["textLayer", 1], ["annotationLayer", 2], ["annotationEditorLayer", 3], ["xfaLayer", 3]]); -class PDFPageView { - #annotationMode = AnnotationMode.ENABLE_FORMS; - #canvasWrapper = null; - #enableHWA = false; - #hasRestrictedScaling = false; - #isEditing = false; - #layerProperties = null; - #loadingId = null; - #originalViewport = null; - #previousRotation = null; - #scaleRoundX = 1; - #scaleRoundY = 1; - #renderError = null; - #renderingState = RenderingStates.INITIAL; - #textLayerMode = TextLayerMode.ENABLE; - #useThumbnailCanvas = { - directDrawing: true, - initialOptionalContent: true, - regularAnnotations: true - }; - #layers = [null, null, null, null]; - constructor(options) { - const container = options.container; - const defaultViewport = options.defaultViewport; - this.id = options.id; - this.renderingId = "page" + this.id; - this.#layerProperties = options.layerProperties || DEFAULT_LAYER_PROPERTIES; - this.pdfPage = null; - this.pageLabel = null; - this.rotation = 0; - this.scale = options.scale || DEFAULT_SCALE; - this.viewport = defaultViewport; - this.pdfPageRotate = defaultViewport.rotation; - this._optionalContentConfigPromise = options.optionalContentConfigPromise || null; - this.#textLayerMode = options.textLayerMode ?? TextLayerMode.ENABLE; - this.#annotationMode = options.annotationMode ?? AnnotationMode.ENABLE_FORMS; - this.imageResourcesPath = options.imageResourcesPath || ""; - this.maxCanvasPixels = options.maxCanvasPixels ?? AppOptions.get("maxCanvasPixels"); - this.pageColors = options.pageColors || null; - this.#enableHWA = options.enableHWA || false; - this.eventBus = options.eventBus; - this.renderingQueue = options.renderingQueue; - this.l10n = options.l10n; - this.l10n ||= new genericl10n_GenericL10n(); - this.renderTask = null; - this.resume = null; - this._isStandalone = !this.renderingQueue?.hasViewer(); - this._container = container; - this._annotationCanvasMap = null; - this.annotationLayer = null; - this.annotationEditorLayer = null; - this.textLayer = null; - this.xfaLayer = null; - this.structTreeLayer = null; - this.drawLayer = null; - const div = document.createElement("div"); - div.className = "page"; - div.setAttribute("data-page-number", this.id); - div.setAttribute("role", "region"); - div.setAttribute("data-l10n-id", "pdfjs-page-landmark"); - div.setAttribute("data-l10n-args", JSON.stringify({ - page: this.id - })); - this.div = div; - this.#setDimensions(); - container?.append(div); - if (this._isStandalone) { - container?.style.setProperty("--scale-factor", this.scale * PixelsPerInch.PDF_TO_CSS_UNITS); - if (this.pageColors?.background) { - container?.style.setProperty("--page-bg-color", this.pageColors.background); - } - const { - optionalContentConfigPromise - } = options; - if (optionalContentConfigPromise) { - optionalContentConfigPromise.then(optionalContentConfig => { - if (optionalContentConfigPromise !== this._optionalContentConfigPromise) { - return; - } - this.#useThumbnailCanvas.initialOptionalContent = optionalContentConfig.hasInitialVisibility; - }); - } - if (!options.l10n) { - this.l10n.translate(this.div); - } - } - } - #addLayer(div, name) { - const pos = LAYERS_ORDER.get(name); - const oldDiv = this.#layers[pos]; - this.#layers[pos] = div; - if (oldDiv) { - oldDiv.replaceWith(div); - return; - } - for (let i = pos - 1; i >= 0; i--) { - const layer = this.#layers[i]; - if (layer) { - layer.after(div); - return; - } - } - this.div.prepend(div); - } - get renderingState() { - return this.#renderingState; - } - set renderingState(state) { - if (state === this.#renderingState) { - return; - } - this.#renderingState = state; - if (this.#loadingId) { - clearTimeout(this.#loadingId); - this.#loadingId = null; - } - switch (state) { - case RenderingStates.PAUSED: - this.div.classList.remove("loading"); - break; - case RenderingStates.RUNNING: - this.div.classList.add("loadingIcon"); - this.#loadingId = setTimeout(() => { - this.div.classList.add("loading"); - this.#loadingId = null; - }, 0); - break; - case RenderingStates.INITIAL: - case RenderingStates.FINISHED: - this.div.classList.remove("loadingIcon", "loading"); - break; - } - } - #setDimensions() { - const { - viewport - } = this; - if (this.pdfPage) { - if (this.#previousRotation === viewport.rotation) { - return; - } - this.#previousRotation = viewport.rotation; - } - setLayerDimensions(this.div, viewport, true, false); - } - setPdfPage(pdfPage) { - if (this._isStandalone && (this.pageColors?.foreground === "CanvasText" || this.pageColors?.background === "Canvas")) { - this._container?.style.setProperty("--hcm-highlight-filter", pdfPage.filterFactory.addHighlightHCMFilter("highlight", "CanvasText", "Canvas", "HighlightText", "Highlight")); - this._container?.style.setProperty("--hcm-highlight-selected-filter", pdfPage.filterFactory.addHighlightHCMFilter("highlight_selected", "CanvasText", "Canvas", "HighlightText", "Highlight")); - } - this.pdfPage = pdfPage; - this.pdfPageRotate = pdfPage.rotate; - const totalRotation = (this.rotation + this.pdfPageRotate) % 360; - this.viewport = pdfPage.getViewport({ - scale: this.scale * PixelsPerInch.PDF_TO_CSS_UNITS, - rotation: totalRotation - }); - this.#setDimensions(); - this.reset(); - } - destroy() { - this.reset(); - this.pdfPage?.cleanup(); - } - hasEditableAnnotations() { - return !!this.annotationLayer?.hasEditableAnnotations(); - } - get _textHighlighter() { - return shadow(this, "_textHighlighter", new TextHighlighter({ - pageIndex: this.id - 1, - eventBus: this.eventBus, - findController: this.#layerProperties.findController - })); - } - #dispatchLayerRendered(name, error) { - this.eventBus.dispatch(name, { - source: this, - pageNumber: this.id, - error - }); - } - async #renderAnnotationLayer() { - let error = null; - try { - await this.annotationLayer.render(this.viewport, { - structTreeLayer: this.structTreeLayer - }, "display"); - } catch (ex) { - console.error("#renderAnnotationLayer:", ex); - error = ex; - } finally { - this.#dispatchLayerRendered("annotationlayerrendered", error); - } - } - async #renderAnnotationEditorLayer() { - let error = null; - try { - await this.annotationEditorLayer.render(this.viewport, "display"); - } catch (ex) { - console.error("#renderAnnotationEditorLayer:", ex); - error = ex; - } finally { - this.#dispatchLayerRendered("annotationeditorlayerrendered", error); - } - } - async #renderDrawLayer() { - try { - await this.drawLayer.render("display"); - } catch (ex) { - console.error("#renderDrawLayer:", ex); - } - } - async #renderXfaLayer() { - let error = null; - try { - const result = await this.xfaLayer.render(this.viewport, "display"); - if (result?.textDivs && this._textHighlighter) { - this.#buildXfaTextContentItems(result.textDivs); - } - } catch (ex) { - console.error("#renderXfaLayer:", ex); - error = ex; - } finally { - if (this.xfaLayer?.div) { - this.l10n.pause(); - this.#addLayer(this.xfaLayer.div, "xfaLayer"); - this.l10n.resume(); - } - this.#dispatchLayerRendered("xfalayerrendered", error); - } - } - async #renderTextLayer() { - if (!this.textLayer) { - return; - } - let error = null; - try { - await this.textLayer.render(this.viewport); - } catch (ex) { - if (ex instanceof AbortException) { - return; - } - console.error("#renderTextLayer:", ex); - error = ex; - } - this.#dispatchLayerRendered("textlayerrendered", error); - this.#renderStructTreeLayer(); - } - async #renderStructTreeLayer() { - if (!this.textLayer) { - return; - } - const treeDom = await this.structTreeLayer?.render(); - if (treeDom) { - this.l10n.pause(); - this.structTreeLayer?.addElementsToTextLayer(); - if (this.canvas && treeDom.parentNode !== this.canvas) { - this.canvas.append(treeDom); - } - this.l10n.resume(); - } - this.structTreeLayer?.show(); - } - async #buildXfaTextContentItems(textDivs) { - const text = await this.pdfPage.getTextContent(); - const items = []; - for (const item of text.items) { - items.push(item.str); - } - this._textHighlighter.setTextMapping(textDivs, items); - this._textHighlighter.enable(); - } - #resetCanvas() { - const { - canvas - } = this; - if (!canvas) { - return; - } - canvas.remove(); - canvas.width = canvas.height = 0; - this.canvas = null; - this.#originalViewport = null; - } - reset({ - keepAnnotationLayer = false, - keepAnnotationEditorLayer = false, - keepXfaLayer = false, - keepTextLayer = false, - keepCanvasWrapper = false - } = {}) { - this.cancelRendering({ - keepAnnotationLayer, - keepAnnotationEditorLayer, - keepXfaLayer, - keepTextLayer - }); - this.renderingState = RenderingStates.INITIAL; - const div = this.div; - const childNodes = div.childNodes, - annotationLayerNode = keepAnnotationLayer && this.annotationLayer?.div || null, - annotationEditorLayerNode = keepAnnotationEditorLayer && this.annotationEditorLayer?.div || null, - xfaLayerNode = keepXfaLayer && this.xfaLayer?.div || null, - textLayerNode = keepTextLayer && this.textLayer?.div || null, - canvasWrapperNode = keepCanvasWrapper && this.#canvasWrapper || null; - for (let i = childNodes.length - 1; i >= 0; i--) { - const node = childNodes[i]; - switch (node) { - case annotationLayerNode: - case annotationEditorLayerNode: - case xfaLayerNode: - case textLayerNode: - case canvasWrapperNode: - continue; - } - node.remove(); - const layerIndex = this.#layers.indexOf(node); - if (layerIndex >= 0) { - this.#layers[layerIndex] = null; - } - } - div.removeAttribute("data-loaded"); - if (annotationLayerNode) { - this.annotationLayer.hide(); - } - if (annotationEditorLayerNode) { - this.annotationEditorLayer.hide(); - } - if (xfaLayerNode) { - this.xfaLayer.hide(); - } - if (textLayerNode) { - this.textLayer.hide(); - } - this.structTreeLayer?.hide(); - if (!keepCanvasWrapper && this.#canvasWrapper) { - this.#canvasWrapper = null; - this.#resetCanvas(); - } - } - toggleEditingMode(isEditing) { - if (!this.hasEditableAnnotations()) { - return; - } - this.#isEditing = isEditing; - this.reset({ - keepAnnotationLayer: true, - keepAnnotationEditorLayer: true, - keepXfaLayer: true, - keepTextLayer: true, - keepCanvasWrapper: true - }); - } - update({ - scale = 0, - rotation = null, - optionalContentConfigPromise = null, - drawingDelay = -1 - }) { - this.scale = scale || this.scale; - if (typeof rotation === "number") { - this.rotation = rotation; - } - if (optionalContentConfigPromise instanceof Promise) { - this._optionalContentConfigPromise = optionalContentConfigPromise; - optionalContentConfigPromise.then(optionalContentConfig => { - if (optionalContentConfigPromise !== this._optionalContentConfigPromise) { - return; - } - this.#useThumbnailCanvas.initialOptionalContent = optionalContentConfig.hasInitialVisibility; - }); - } - this.#useThumbnailCanvas.directDrawing = true; - const totalRotation = (this.rotation + this.pdfPageRotate) % 360; - this.viewport = this.viewport.clone({ - scale: this.scale * PixelsPerInch.PDF_TO_CSS_UNITS, - rotation: totalRotation - }); - this.#setDimensions(); - if (this._isStandalone) { - this._container?.style.setProperty("--scale-factor", this.viewport.scale); - } - if (this.canvas) { - let onlyCssZoom = false; - if (this.#hasRestrictedScaling) { - if (this.maxCanvasPixels === 0) { - onlyCssZoom = true; - } else if (this.maxCanvasPixels > 0) { - const { - width, - height - } = this.viewport; - const { - sx, - sy - } = this.outputScale; - onlyCssZoom = (Math.floor(width) * sx | 0) * (Math.floor(height) * sy | 0) > this.maxCanvasPixels; - } - } - const postponeDrawing = drawingDelay >= 0 && drawingDelay < 1000; - if (postponeDrawing || onlyCssZoom) { - if (postponeDrawing && !onlyCssZoom && this.renderingState !== RenderingStates.FINISHED) { - this.cancelRendering({ - keepAnnotationLayer: true, - keepAnnotationEditorLayer: true, - keepXfaLayer: true, - keepTextLayer: true, - cancelExtraDelay: drawingDelay - }); - this.renderingState = RenderingStates.FINISHED; - this.#useThumbnailCanvas.directDrawing = false; - } - this.cssTransform({ - redrawAnnotationLayer: true, - redrawAnnotationEditorLayer: true, - redrawXfaLayer: true, - redrawTextLayer: !postponeDrawing, - hideTextLayer: postponeDrawing - }); - if (postponeDrawing) { - return; - } - this.eventBus.dispatch("pagerendered", { - source: this, - pageNumber: this.id, - cssTransform: true, - timestamp: performance.now(), - error: this.#renderError - }); - return; - } - } - this.cssTransform({}); - this.reset({ - keepAnnotationLayer: true, - keepAnnotationEditorLayer: true, - keepXfaLayer: true, - keepTextLayer: true, - keepCanvasWrapper: true - }); - } - cancelRendering({ - keepAnnotationLayer = false, - keepAnnotationEditorLayer = false, - keepXfaLayer = false, - keepTextLayer = false, - cancelExtraDelay = 0 - } = {}) { - if (this.renderTask) { - this.renderTask.cancel(cancelExtraDelay); - this.renderTask = null; - } - this.resume = null; - if (this.textLayer && (!keepTextLayer || !this.textLayer.div)) { - this.textLayer.cancel(); - this.textLayer = null; - } - if (this.annotationLayer && (!keepAnnotationLayer || !this.annotationLayer.div)) { - this.annotationLayer.cancel(); - this.annotationLayer = null; - this._annotationCanvasMap = null; - } - if (this.structTreeLayer && !this.textLayer) { - this.structTreeLayer = null; - } - if (this.annotationEditorLayer && (!keepAnnotationEditorLayer || !this.annotationEditorLayer.div)) { - if (this.drawLayer) { - this.drawLayer.cancel(); - this.drawLayer = null; - } - this.annotationEditorLayer.cancel(); - this.annotationEditorLayer = null; - } - if (this.xfaLayer && (!keepXfaLayer || !this.xfaLayer.div)) { - this.xfaLayer.cancel(); - this.xfaLayer = null; - this._textHighlighter?.disable(); - } - } - cssTransform({ - redrawAnnotationLayer = false, - redrawAnnotationEditorLayer = false, - redrawXfaLayer = false, - redrawTextLayer = false, - hideTextLayer = false - }) { - const { - canvas - } = this; - if (!canvas) { - return; - } - const originalViewport = this.#originalViewport; - if (this.viewport !== originalViewport) { - const relativeRotation = (360 + this.viewport.rotation - originalViewport.rotation) % 360; - if (relativeRotation === 90 || relativeRotation === 270) { - const { - width, - height - } = this.viewport; - const scaleX = height / width; - const scaleY = width / height; - canvas.style.transform = `rotate(${relativeRotation}deg) scale(${scaleX},${scaleY})`; - } else { - canvas.style.transform = relativeRotation === 0 ? "" : `rotate(${relativeRotation}deg)`; - } - } - if (redrawAnnotationLayer && this.annotationLayer) { - this.#renderAnnotationLayer(); - } - if (redrawAnnotationEditorLayer && this.annotationEditorLayer) { - if (this.drawLayer) { - this.#renderDrawLayer(); - } - this.#renderAnnotationEditorLayer(); - } - if (redrawXfaLayer && this.xfaLayer) { - this.#renderXfaLayer(); - } - if (this.textLayer) { - if (hideTextLayer) { - this.textLayer.hide(); - this.structTreeLayer?.hide(); - } else if (redrawTextLayer) { - this.#renderTextLayer(); - } - } - } - get width() { - return this.viewport.width; - } - get height() { - return this.viewport.height; - } - getPagePoint(x, y) { - return this.viewport.convertToPdfPoint(x, y); - } - async #finishRenderTask(renderTask, error = null) { - if (renderTask === this.renderTask) { - this.renderTask = null; - } - if (error instanceof RenderingCancelledException) { - this.#renderError = null; - return; - } - this.#renderError = error; - this.renderingState = RenderingStates.FINISHED; - this.#useThumbnailCanvas.regularAnnotations = !renderTask.separateAnnots; - this.eventBus.dispatch("pagerendered", { - source: this, - pageNumber: this.id, - cssTransform: false, - timestamp: performance.now(), - error: this.#renderError - }); - if (error) { - throw error; - } - } - async draw() { - if (this.renderingState !== RenderingStates.INITIAL) { - console.error("Must be in new state before drawing"); - this.reset(); - } - const { - div, - l10n, - pageColors, - pdfPage, - viewport - } = this; - if (!pdfPage) { - this.renderingState = RenderingStates.FINISHED; - throw new Error("pdfPage is not loaded"); - } - this.renderingState = RenderingStates.RUNNING; - let canvasWrapper = this.#canvasWrapper; - if (!canvasWrapper) { - canvasWrapper = this.#canvasWrapper = document.createElement("div"); - canvasWrapper.classList.add("canvasWrapper"); - this.#addLayer(canvasWrapper, "canvasWrapper"); - } - if (!this.textLayer && this.#textLayerMode !== TextLayerMode.DISABLE && !pdfPage.isPureXfa) { - this._accessibilityManager ||= new TextAccessibilityManager(); - this.textLayer = new TextLayerBuilder({ - pdfPage, - highlighter: this._textHighlighter, - accessibilityManager: this._accessibilityManager, - enablePermissions: this.#textLayerMode === TextLayerMode.ENABLE_PERMISSIONS, - onAppend: textLayerDiv => { - this.l10n.pause(); - this.#addLayer(textLayerDiv, "textLayer"); - this.l10n.resume(); - } - }); - } - if (!this.annotationLayer && this.#annotationMode !== AnnotationMode.DISABLE) { - const { - annotationStorage, - annotationEditorUIManager, - downloadManager, - enableScripting, - fieldObjectsPromise, - hasJSActionsPromise, - linkService - } = this.#layerProperties; - this._annotationCanvasMap ||= new Map(); - this.annotationLayer = new AnnotationLayerBuilder({ - pdfPage, - annotationStorage, - imageResourcesPath: this.imageResourcesPath, - renderForms: this.#annotationMode === AnnotationMode.ENABLE_FORMS, - linkService, - downloadManager, - enableScripting, - hasJSActionsPromise, - fieldObjectsPromise, - annotationCanvasMap: this._annotationCanvasMap, - accessibilityManager: this._accessibilityManager, - annotationEditorUIManager, - onAppend: annotationLayerDiv => { - this.#addLayer(annotationLayerDiv, "annotationLayer"); - } - }); - } - const renderContinueCallback = cont => { - showCanvas?.(false); - if (this.renderingQueue && !this.renderingQueue.isHighestPriority(this)) { - this.renderingState = RenderingStates.PAUSED; - this.resume = () => { - this.renderingState = RenderingStates.RUNNING; - cont(); - }; - return; - } - cont(); - }; - const { - width, - height - } = viewport; - const canvas = document.createElement("canvas"); - canvas.setAttribute("role", "presentation"); - const hasHCM = !!(pageColors?.background && pageColors?.foreground); - const prevCanvas = this.canvas; - const updateOnFirstShow = !prevCanvas && !hasHCM; - this.canvas = canvas; - this.#originalViewport = viewport; - let showCanvas = isLastShow => { - if (updateOnFirstShow) { - canvasWrapper.prepend(canvas); - showCanvas = null; - return; - } - if (!isLastShow) { - return; - } - if (prevCanvas) { - prevCanvas.replaceWith(canvas); - prevCanvas.width = prevCanvas.height = 0; - } else { - canvasWrapper.prepend(canvas); - } - showCanvas = null; - }; - const ctx = canvas.getContext("2d", { - alpha: false, - willReadFrequently: !this.#enableHWA - }); - const outputScale = this.outputScale = new OutputScale(); - if (this.maxCanvasPixels === 0) { - const invScale = 1 / this.scale; - outputScale.sx *= invScale; - outputScale.sy *= invScale; - this.#hasRestrictedScaling = true; - } else if (this.maxCanvasPixels > 0) { - const pixelsInViewport = width * height; - const maxScale = Math.sqrt(this.maxCanvasPixels / pixelsInViewport); - if (outputScale.sx > maxScale || outputScale.sy > maxScale) { - outputScale.sx = maxScale; - outputScale.sy = maxScale; - this.#hasRestrictedScaling = true; - } else { - this.#hasRestrictedScaling = false; - } - } - const sfx = approximateFraction(outputScale.sx); - const sfy = approximateFraction(outputScale.sy); - const canvasWidth = canvas.width = floorToDivide(calcRound(width * outputScale.sx), sfx[0]); - const canvasHeight = canvas.height = floorToDivide(calcRound(height * outputScale.sy), sfy[0]); - const pageWidth = floorToDivide(calcRound(width), sfx[1]); - const pageHeight = floorToDivide(calcRound(height), sfy[1]); - outputScale.sx = canvasWidth / pageWidth; - outputScale.sy = canvasHeight / pageHeight; - if (this.#scaleRoundX !== sfx[1]) { - div.style.setProperty("--scale-round-x", `${sfx[1]}px`); - this.#scaleRoundX = sfx[1]; - } - if (this.#scaleRoundY !== sfy[1]) { - div.style.setProperty("--scale-round-y", `${sfy[1]}px`); - this.#scaleRoundY = sfy[1]; - } - const transform = outputScale.scaled ? [outputScale.sx, 0, 0, outputScale.sy, 0, 0] : null; - const renderContext = { - canvasContext: ctx, - transform, - viewport, - annotationMode: this.#annotationMode, - optionalContentConfigPromise: this._optionalContentConfigPromise, - annotationCanvasMap: this._annotationCanvasMap, - pageColors, - isEditing: this.#isEditing - }; - const renderTask = this.renderTask = pdfPage.render(renderContext); - renderTask.onContinue = renderContinueCallback; - const resultPromise = renderTask.promise.then(async () => { - showCanvas?.(true); - await this.#finishRenderTask(renderTask); - this.structTreeLayer ||= new StructTreeLayerBuilder(pdfPage, viewport.rawDims); - this.#renderTextLayer(); - if (this.annotationLayer) { - await this.#renderAnnotationLayer(); - } - const { - annotationEditorUIManager - } = this.#layerProperties; - if (!annotationEditorUIManager) { - return; - } - this.drawLayer ||= new DrawLayerBuilder({ - pageIndex: this.id - }); - await this.#renderDrawLayer(); - this.drawLayer.setParent(canvasWrapper); - this.annotationEditorLayer ||= new AnnotationEditorLayerBuilder({ - uiManager: annotationEditorUIManager, - pdfPage, - l10n, - structTreeLayer: this.structTreeLayer, - accessibilityManager: this._accessibilityManager, - annotationLayer: this.annotationLayer?.annotationLayer, - textLayer: this.textLayer, - drawLayer: this.drawLayer.getDrawLayer(), - onAppend: annotationEditorLayerDiv => { - this.#addLayer(annotationEditorLayerDiv, "annotationEditorLayer"); - } - }); - this.#renderAnnotationEditorLayer(); - }, error => { - if (!(error instanceof RenderingCancelledException)) { - showCanvas?.(true); - } else { - prevCanvas?.remove(); - this.#resetCanvas(); - } - return this.#finishRenderTask(renderTask, error); - }); - if (pdfPage.isPureXfa) { - if (!this.xfaLayer) { - const { - annotationStorage, - linkService - } = this.#layerProperties; - this.xfaLayer = new XfaLayerBuilder({ - pdfPage, - annotationStorage, - linkService - }); - } - this.#renderXfaLayer(); - } - div.setAttribute("data-loaded", true); - this.eventBus.dispatch("pagerender", { - source: this, - pageNumber: this.id - }); - return resultPromise; - } - setPageLabel(label) { - this.pageLabel = typeof label === "string" ? label : null; - this.div.setAttribute("data-l10n-args", JSON.stringify({ - page: this.pageLabel ?? this.id - })); - if (this.pageLabel !== null) { - this.div.setAttribute("data-page-label", this.pageLabel); - } else { - this.div.removeAttribute("data-page-label"); - } - } - get thumbnailCanvas() { - const { - directDrawing, - initialOptionalContent, - regularAnnotations - } = this.#useThumbnailCanvas; - return directDrawing && initialOptionalContent && regularAnnotations ? this.canvas : null; - } -} - -;// ./web/generic_scripting.js - -async function docProperties(pdfDocument) { - const url = "", - baseUrl = url.split("#", 1)[0]; - let { - info, - metadata, - contentDispositionFilename, - contentLength - } = await pdfDocument.getMetadata(); - if (!contentLength) { - const { - length - } = await pdfDocument.getDownloadInfo(); - contentLength = length; - } - return { - ...info, - baseURL: baseUrl, - filesize: contentLength, - filename: contentDispositionFilename || getPdfFilenameFromUrl(url), - metadata: metadata?.getRaw(), - authors: metadata?.get("dc:creator"), - numPages: pdfDocument.numPages, - URL: url - }; -} -class GenericScripting { - constructor(sandboxBundleSrc) { - this._ready = new Promise((resolve, reject) => { - const sandbox = import(/*webpackIgnore: true*/sandboxBundleSrc); - sandbox.then(pdfjsSandbox => { - resolve(pdfjsSandbox.QuickJSSandbox()); - }).catch(reject); - }); - } - async createSandbox(data) { - const sandbox = await this._ready; - sandbox.create(data); - } - async dispatchEventInSandbox(event) { - const sandbox = await this._ready; - setTimeout(() => sandbox.dispatchEvent(event), 0); - } - async destroySandbox() { - const sandbox = await this._ready; - sandbox.nukeSandbox(); - } -} - -;// ./web/pdf_scripting_manager.js - - -class PDFScriptingManager { - #closeCapability = null; - #destroyCapability = null; - #docProperties = null; - #eventAbortController = null; - #eventBus = null; - #externalServices = null; - #pdfDocument = null; - #pdfViewer = null; - #ready = false; - #scripting = null; - #willPrintCapability = null; - constructor({ - eventBus, - externalServices = null, - docProperties = null - }) { - this.#eventBus = eventBus; - this.#externalServices = externalServices; - this.#docProperties = docProperties; - } - setViewer(pdfViewer) { - this.#pdfViewer = pdfViewer; - } - async setDocument(pdfDocument) { - if (this.#pdfDocument) { - await this.#destroyScripting(); - } - this.#pdfDocument = pdfDocument; - if (!pdfDocument) { - return; - } - const [objects, calculationOrder, docActions] = await Promise.all([pdfDocument.getFieldObjects(), pdfDocument.getCalculationOrderIds(), pdfDocument.getJSActions()]); - if (!objects && !docActions) { - await this.#destroyScripting(); - return; - } - if (pdfDocument !== this.#pdfDocument) { - return; - } - try { - this.#scripting = this.#initScripting(); - } catch (error) { - console.error("setDocument:", error); - await this.#destroyScripting(); - return; - } - const eventBus = this.#eventBus; - this.#eventAbortController = new AbortController(); - const { - signal - } = this.#eventAbortController; - eventBus._on("updatefromsandbox", event => { - if (event?.source === window) { - this.#updateFromSandbox(event.detail); - } - }, { - signal - }); - eventBus._on("dispatcheventinsandbox", event => { - this.#scripting?.dispatchEventInSandbox(event.detail); - }, { - signal - }); - eventBus._on("pagechanging", ({ - pageNumber, - previous - }) => { - if (pageNumber === previous) { - return; - } - this.#dispatchPageClose(previous); - this.#dispatchPageOpen(pageNumber); - }, { - signal - }); - eventBus._on("pagerendered", ({ - pageNumber - }) => { - if (!this._pageOpenPending.has(pageNumber)) { - return; - } - if (pageNumber !== this.#pdfViewer.currentPageNumber) { - return; - } - this.#dispatchPageOpen(pageNumber); - }, { - signal - }); - eventBus._on("pagesdestroy", async () => { - await this.#dispatchPageClose(this.#pdfViewer.currentPageNumber); - await this.#scripting?.dispatchEventInSandbox({ - id: "doc", - name: "WillClose" - }); - this.#closeCapability?.resolve(); - }, { - signal - }); - try { - const docProperties = await this.#docProperties(pdfDocument); - if (pdfDocument !== this.#pdfDocument) { - return; - } - await this.#scripting.createSandbox({ - objects, - calculationOrder, - appInfo: { - platform: navigator.platform, - language: navigator.language - }, - docInfo: { - ...docProperties, - actions: docActions - } - }); - eventBus.dispatch("sandboxcreated", { - source: this - }); - } catch (error) { - console.error("setDocument:", error); - await this.#destroyScripting(); - return; - } - await this.#scripting?.dispatchEventInSandbox({ - id: "doc", - name: "Open" - }); - await this.#dispatchPageOpen(this.#pdfViewer.currentPageNumber, true); - Promise.resolve().then(() => { - if (pdfDocument === this.#pdfDocument) { - this.#ready = true; - } - }); - } - async dispatchWillSave() { - return this.#scripting?.dispatchEventInSandbox({ - id: "doc", - name: "WillSave" - }); - } - async dispatchDidSave() { - return this.#scripting?.dispatchEventInSandbox({ - id: "doc", - name: "DidSave" - }); - } - async dispatchWillPrint() { - if (!this.#scripting) { - return; - } - await this.#willPrintCapability?.promise; - this.#willPrintCapability = Promise.withResolvers(); - try { - await this.#scripting.dispatchEventInSandbox({ - id: "doc", - name: "WillPrint" - }); - } catch (ex) { - this.#willPrintCapability.resolve(); - this.#willPrintCapability = null; - throw ex; - } - await this.#willPrintCapability.promise; - } - async dispatchDidPrint() { - return this.#scripting?.dispatchEventInSandbox({ - id: "doc", - name: "DidPrint" - }); - } - get destroyPromise() { - return this.#destroyCapability?.promise || null; - } - get ready() { - return this.#ready; - } - get _pageOpenPending() { - return shadow(this, "_pageOpenPending", new Set()); - } - get _visitedPages() { - return shadow(this, "_visitedPages", new Map()); - } - async #updateFromSandbox(detail) { - const pdfViewer = this.#pdfViewer; - const isInPresentationMode = pdfViewer.isInPresentationMode || pdfViewer.isChangingPresentationMode; - const { - id, - siblings, - command, - value - } = detail; - if (!id) { - switch (command) { - case "clear": - console.clear(); - break; - case "error": - console.error(value); - break; - case "layout": - if (!isInPresentationMode) { - const modes = apiPageLayoutToViewerModes(value); - pdfViewer.spreadMode = modes.spreadMode; - } - break; - case "page-num": - pdfViewer.currentPageNumber = value + 1; - break; - case "print": - await pdfViewer.pagesPromise; - this.#eventBus.dispatch("print", { - source: this - }); - break; - case "println": - console.log(value); - break; - case "zoom": - if (!isInPresentationMode) { - pdfViewer.currentScaleValue = value; - } - break; - case "SaveAs": - this.#eventBus.dispatch("download", { - source: this - }); - break; - case "FirstPage": - pdfViewer.currentPageNumber = 1; - break; - case "LastPage": - pdfViewer.currentPageNumber = pdfViewer.pagesCount; - break; - case "NextPage": - pdfViewer.nextPage(); - break; - case "PrevPage": - pdfViewer.previousPage(); - break; - case "ZoomViewIn": - if (!isInPresentationMode) { - pdfViewer.increaseScale(); - } - break; - case "ZoomViewOut": - if (!isInPresentationMode) { - pdfViewer.decreaseScale(); - } - break; - case "WillPrintFinished": - this.#willPrintCapability?.resolve(); - this.#willPrintCapability = null; - break; - } - return; - } - if (isInPresentationMode && detail.focus) { - return; - } - delete detail.id; - delete detail.siblings; - const ids = siblings ? [id, ...siblings] : [id]; - for (const elementId of ids) { - const element = document.querySelector(`[data-element-id="${elementId}"]`); - if (element) { - element.dispatchEvent(new CustomEvent("updatefromsandbox", { - detail - })); - } else { - this.#pdfDocument?.annotationStorage.setValue(elementId, detail); - } - } - } - async #dispatchPageOpen(pageNumber, initialize = false) { - const pdfDocument = this.#pdfDocument, - visitedPages = this._visitedPages; - if (initialize) { - this.#closeCapability = Promise.withResolvers(); - } - if (!this.#closeCapability) { - return; - } - const pageView = this.#pdfViewer.getPageView(pageNumber - 1); - if (pageView?.renderingState !== RenderingStates.FINISHED) { - this._pageOpenPending.add(pageNumber); - return; - } - this._pageOpenPending.delete(pageNumber); - const actionsPromise = (async () => { - const actions = await (!visitedPages.has(pageNumber) ? pageView.pdfPage?.getJSActions() : null); - if (pdfDocument !== this.#pdfDocument) { - return; - } - await this.#scripting?.dispatchEventInSandbox({ - id: "page", - name: "PageOpen", - pageNumber, - actions - }); - })(); - visitedPages.set(pageNumber, actionsPromise); - } - async #dispatchPageClose(pageNumber) { - const pdfDocument = this.#pdfDocument, - visitedPages = this._visitedPages; - if (!this.#closeCapability) { - return; - } - if (this._pageOpenPending.has(pageNumber)) { - return; - } - const actionsPromise = visitedPages.get(pageNumber); - if (!actionsPromise) { - return; - } - visitedPages.set(pageNumber, null); - await actionsPromise; - if (pdfDocument !== this.#pdfDocument) { - return; - } - await this.#scripting?.dispatchEventInSandbox({ - id: "page", - name: "PageClose", - pageNumber - }); - } - #initScripting() { - this.#destroyCapability = Promise.withResolvers(); - if (this.#scripting) { - throw new Error("#initScripting: Scripting already exists."); - } - return this.#externalServices.createScripting(); - } - async #destroyScripting() { - if (!this.#scripting) { - this.#pdfDocument = null; - this.#destroyCapability?.resolve(); - return; - } - if (this.#closeCapability) { - await Promise.race([this.#closeCapability.promise, new Promise(resolve => { - setTimeout(resolve, 1000); - })]).catch(() => {}); - this.#closeCapability = null; - } - this.#pdfDocument = null; - try { - await this.#scripting.destroySandbox(); - } catch {} - this.#willPrintCapability?.reject(new Error("Scripting destroyed.")); - this.#willPrintCapability = null; - this.#eventAbortController?.abort(); - this.#eventAbortController = null; - this._pageOpenPending.clear(); - this._visitedPages.clear(); - this.#scripting = null; - this.#ready = false; - this.#destroyCapability?.resolve(); - } -} - -;// ./web/pdf_scripting_manager.component.js - - -class PDFScriptingManagerComponents extends PDFScriptingManager { - constructor(options) { - if (!options.externalServices) { - window.addEventListener("updatefromsandbox", event => { - options.eventBus.dispatch("updatefromsandbox", { - source: window, - detail: event.detail - }); - }); - } - options.externalServices ||= { - createScripting: () => new GenericScripting(options.sandboxBundleSrc) - }; - options.docProperties ||= pdfDocument => docProperties(pdfDocument); - super(options); - } -} - -;// ./web/pdf_rendering_queue.js - - -const CLEANUP_TIMEOUT = 30000; -class PDFRenderingQueue { - constructor() { - this.pdfViewer = null; - this.pdfThumbnailViewer = null; - this.onIdle = null; - this.highestPriorityPage = null; - this.idleTimeout = null; - this.printing = false; - this.isThumbnailViewEnabled = false; - Object.defineProperty(this, "hasViewer", { - value: () => !!this.pdfViewer - }); - } - setViewer(pdfViewer) { - this.pdfViewer = pdfViewer; - } - setThumbnailViewer(pdfThumbnailViewer) { - this.pdfThumbnailViewer = pdfThumbnailViewer; - } - isHighestPriority(view) { - return this.highestPriorityPage === view.renderingId; - } - renderHighestPriority(currentlyVisiblePages) { - if (this.idleTimeout) { - clearTimeout(this.idleTimeout); - this.idleTimeout = null; - } - if (this.pdfViewer.forceRendering(currentlyVisiblePages)) { - return; - } - if (this.isThumbnailViewEnabled && this.pdfThumbnailViewer?.forceRendering()) { - return; - } - if (this.printing) { - return; - } - if (this.onIdle) { - this.idleTimeout = setTimeout(this.onIdle.bind(this), CLEANUP_TIMEOUT); - } - } - getHighestPriority(visible, views, scrolledDown, preRenderExtra = false) { - const visibleViews = visible.views, - numVisible = visibleViews.length; - if (numVisible === 0) { - return null; - } - for (let i = 0; i < numVisible; i++) { - const view = visibleViews[i].view; - if (!this.isViewFinished(view)) { - return view; - } - } - const firstId = visible.first.id, - lastId = visible.last.id; - if (lastId - firstId + 1 > numVisible) { - const visibleIds = visible.ids; - for (let i = 1, ii = lastId - firstId; i < ii; i++) { - const holeId = scrolledDown ? firstId + i : lastId - i; - if (visibleIds.has(holeId)) { - continue; - } - const holeView = views[holeId - 1]; - if (!this.isViewFinished(holeView)) { - return holeView; - } - } - } - let preRenderIndex = scrolledDown ? lastId : firstId - 2; - let preRenderView = views[preRenderIndex]; - if (preRenderView && !this.isViewFinished(preRenderView)) { - return preRenderView; - } - if (preRenderExtra) { - preRenderIndex += scrolledDown ? 1 : -1; - preRenderView = views[preRenderIndex]; - if (preRenderView && !this.isViewFinished(preRenderView)) { - return preRenderView; - } - } - return null; - } - isViewFinished(view) { - return view.renderingState === RenderingStates.FINISHED; - } - renderView(view) { - switch (view.renderingState) { - case RenderingStates.FINISHED: - return false; - case RenderingStates.PAUSED: - this.highestPriorityPage = view.renderingId; - view.resume(); - break; - case RenderingStates.RUNNING: - this.highestPriorityPage = view.renderingId; - break; - case RenderingStates.INITIAL: - this.highestPriorityPage = view.renderingId; - view.draw().finally(() => { - this.renderHighestPriority(); - }).catch(reason => { - if (reason instanceof RenderingCancelledException) { - return; - } - console.error("renderView:", reason); - }); - break; - } - return true; - } -} - -;// ./web/pdf_viewer.js - - - - - - -const DEFAULT_CACHE_SIZE = 10; -const PagesCountLimit = { - FORCE_SCROLL_MODE_PAGE: 10000, - FORCE_LAZY_PAGE_INIT: 5000, - PAUSE_EAGER_PAGE_INIT: 250 -}; -function isValidAnnotationEditorMode(mode) { - return Object.values(AnnotationEditorType).includes(mode) && mode !== AnnotationEditorType.DISABLE; -} -class PDFPageViewBuffer { - #buf = new Set(); - #size = 0; - constructor(size) { - this.#size = size; - } - push(view) { - const buf = this.#buf; - if (buf.has(view)) { - buf.delete(view); - } - buf.add(view); - if (buf.size > this.#size) { - this.#destroyFirstView(); - } - } - resize(newSize, idsToKeep = null) { - this.#size = newSize; - const buf = this.#buf; - if (idsToKeep) { - const ii = buf.size; - let i = 1; - for (const view of buf) { - if (idsToKeep.has(view.id)) { - buf.delete(view); - buf.add(view); - } - if (++i > ii) { - break; - } - } - } - while (buf.size > this.#size) { - this.#destroyFirstView(); - } - } - has(view) { - return this.#buf.has(view); - } - [Symbol.iterator]() { - return this.#buf.keys(); - } - #destroyFirstView() { - const firstView = this.#buf.keys().next().value; - firstView?.destroy(); - this.#buf.delete(firstView); - } -} -class PDFViewer { - #buffer = null; - #altTextManager = null; - #annotationEditorHighlightColors = null; - #annotationEditorMode = AnnotationEditorType.NONE; - #annotationEditorUIManager = null; - #annotationMode = AnnotationMode.ENABLE_FORMS; - #containerTopLeft = null; - #editorUndoBar = null; - #enableHWA = false; - #enableHighlightFloatingButton = false; - #enablePermissions = false; - #enableUpdatedAddImage = false; - #enableNewAltTextWhenAddingImage = false; - #eventAbortController = null; - #mlManager = null; - #switchAnnotationEditorModeAC = null; - #switchAnnotationEditorModeTimeoutId = null; - #getAllTextInProgress = false; - #hiddenCopyElement = null; - #interruptCopyCondition = false; - #previousContainerHeight = 0; - #resizeObserver = new ResizeObserver(this.#resizeObserverCallback.bind(this)); - #scrollModePageState = null; - #scaleTimeoutId = null; - #supportsPinchToZoom = true; - #textLayerMode = TextLayerMode.ENABLE; - constructor(options) { - const viewerVersion = "4.10.38"; - if (version !== viewerVersion) { - throw new Error(`The API version "${version}" does not match the Viewer version "${viewerVersion}".`); - } - this.container = options.container; - this.viewer = options.viewer || options.container.firstElementChild; - if (this.container?.tagName !== "DIV" || this.viewer?.tagName !== "DIV") { - throw new Error("Invalid `container` and/or `viewer` option."); - } - if (this.container.offsetParent && getComputedStyle(this.container).position !== "absolute") { - throw new Error("The `container` must be absolutely positioned."); - } - this.#resizeObserver.observe(this.container); - this.eventBus = options.eventBus; - this.linkService = options.linkService || new SimpleLinkService(); - this.downloadManager = options.downloadManager || null; - this.findController = options.findController || null; - this.#altTextManager = options.altTextManager || null; - this.#editorUndoBar = options.editorUndoBar || null; - if (this.findController) { - this.findController.onIsPageVisible = pageNumber => this._getVisiblePages().ids.has(pageNumber); - } - this._scriptingManager = options.scriptingManager || null; - this.#textLayerMode = options.textLayerMode ?? TextLayerMode.ENABLE; - this.#annotationMode = options.annotationMode ?? AnnotationMode.ENABLE_FORMS; - this.#annotationEditorMode = options.annotationEditorMode ?? AnnotationEditorType.NONE; - this.#annotationEditorHighlightColors = options.annotationEditorHighlightColors || null; - this.#enableHighlightFloatingButton = options.enableHighlightFloatingButton === true; - this.#enableUpdatedAddImage = options.enableUpdatedAddImage === true; - this.#enableNewAltTextWhenAddingImage = options.enableNewAltTextWhenAddingImage === true; - this.imageResourcesPath = options.imageResourcesPath || ""; - this.enablePrintAutoRotate = options.enablePrintAutoRotate || false; - this.removePageBorders = options.removePageBorders || false; - this.maxCanvasPixels = options.maxCanvasPixels; - this.l10n = options.l10n; - this.l10n ||= new genericl10n_GenericL10n(); - this.#enablePermissions = options.enablePermissions || false; - this.pageColors = options.pageColors || null; - this.#mlManager = options.mlManager || null; - this.#enableHWA = options.enableHWA || false; - this.#supportsPinchToZoom = options.supportsPinchToZoom !== false; - this.defaultRenderingQueue = !options.renderingQueue; - if (this.defaultRenderingQueue) { - this.renderingQueue = new PDFRenderingQueue(); - this.renderingQueue.setViewer(this); - } else { - this.renderingQueue = options.renderingQueue; - } - const { - abortSignal - } = options; - abortSignal?.addEventListener("abort", () => { - this.#resizeObserver.disconnect(); - this.#resizeObserver = null; - }, { - once: true - }); - this.scroll = watchScroll(this.container, this._scrollUpdate.bind(this), abortSignal); - this.presentationModeState = PresentationModeState.UNKNOWN; - this._resetView(); - if (this.removePageBorders) { - this.viewer.classList.add("removePageBorders"); - } - this.#updateContainerHeightCss(); - this.eventBus._on("thumbnailrendered", ({ - pageNumber, - pdfPage - }) => { - const pageView = this._pages[pageNumber - 1]; - if (!this.#buffer.has(pageView)) { - pdfPage?.cleanup(); - } - }); - if (!options.l10n) { - this.l10n.translate(this.container); - } - } - get pagesCount() { - return this._pages.length; - } - getPageView(index) { - return this._pages[index]; - } - getCachedPageViews() { - return new Set(this.#buffer); - } - get pageViewsReady() { - return this._pages.every(pageView => pageView?.pdfPage); - } - get renderForms() { - return this.#annotationMode === AnnotationMode.ENABLE_FORMS; - } - get enableScripting() { - return !!this._scriptingManager; - } - get currentPageNumber() { - return this._currentPageNumber; - } - set currentPageNumber(val) { - if (!Number.isInteger(val)) { - throw new Error("Invalid page number."); - } - if (!this.pdfDocument) { - return; - } - if (!this._setCurrentPageNumber(val, true)) { - console.error(`currentPageNumber: "${val}" is not a valid page.`); - } - } - _setCurrentPageNumber(val, resetCurrentPageView = false) { - if (this._currentPageNumber === val) { - if (resetCurrentPageView) { - this.#resetCurrentPageView(); - } - return true; - } - if (!(0 < val && val <= this.pagesCount)) { - return false; - } - const previous = this._currentPageNumber; - this._currentPageNumber = val; - this.eventBus.dispatch("pagechanging", { - source: this, - pageNumber: val, - pageLabel: this._pageLabels?.[val - 1] ?? null, - previous - }); - if (resetCurrentPageView) { - this.#resetCurrentPageView(); - } - return true; - } - get currentPageLabel() { - return this._pageLabels?.[this._currentPageNumber - 1] ?? null; - } - set currentPageLabel(val) { - if (!this.pdfDocument) { - return; - } - let page = val | 0; - if (this._pageLabels) { - const i = this._pageLabels.indexOf(val); - if (i >= 0) { - page = i + 1; - } - } - if (!this._setCurrentPageNumber(page, true)) { - console.error(`currentPageLabel: "${val}" is not a valid page.`); - } - } - get currentScale() { - return this._currentScale !== UNKNOWN_SCALE ? this._currentScale : DEFAULT_SCALE; - } - set currentScale(val) { - if (isNaN(val)) { - throw new Error("Invalid numeric scale."); - } - if (!this.pdfDocument) { - return; - } - this.#setScale(val, { - noScroll: false - }); - } - get currentScaleValue() { - return this._currentScaleValue; - } - set currentScaleValue(val) { - if (!this.pdfDocument) { - return; - } - this.#setScale(val, { - noScroll: false - }); - } - get pagesRotation() { - return this._pagesRotation; - } - set pagesRotation(rotation) { - if (!isValidRotation(rotation)) { - throw new Error("Invalid pages rotation angle."); - } - if (!this.pdfDocument) { - return; - } - rotation %= 360; - if (rotation < 0) { - rotation += 360; - } - if (this._pagesRotation === rotation) { - return; - } - this._pagesRotation = rotation; - const pageNumber = this._currentPageNumber; - this.refresh(true, { - rotation - }); - if (this._currentScaleValue) { - this.#setScale(this._currentScaleValue, { - noScroll: true - }); - } - this.eventBus.dispatch("rotationchanging", { - source: this, - pagesRotation: rotation, - pageNumber - }); - if (this.defaultRenderingQueue) { - this.update(); - } - } - get firstPagePromise() { - return this.pdfDocument ? this._firstPageCapability.promise : null; - } - get onePageRendered() { - return this.pdfDocument ? this._onePageRenderedCapability.promise : null; - } - get pagesPromise() { - return this.pdfDocument ? this._pagesCapability.promise : null; - } - get _layerProperties() { - const self = this; - return shadow(this, "_layerProperties", { - get annotationEditorUIManager() { - return self.#annotationEditorUIManager; - }, - get annotationStorage() { - return self.pdfDocument?.annotationStorage; - }, - get downloadManager() { - return self.downloadManager; - }, - get enableScripting() { - return !!self._scriptingManager; - }, - get fieldObjectsPromise() { - return self.pdfDocument?.getFieldObjects(); - }, - get findController() { - return self.findController; - }, - get hasJSActionsPromise() { - return self.pdfDocument?.hasJSActions(); - }, - get linkService() { - return self.linkService; - } - }); - } - #initializePermissions(permissions) { - const params = { - annotationEditorMode: this.#annotationEditorMode, - annotationMode: this.#annotationMode, - textLayerMode: this.#textLayerMode - }; - if (!permissions) { - return params; - } - if (!permissions.includes(PermissionFlag.COPY) && this.#textLayerMode === TextLayerMode.ENABLE) { - params.textLayerMode = TextLayerMode.ENABLE_PERMISSIONS; - } - if (!permissions.includes(PermissionFlag.MODIFY_CONTENTS)) { - params.annotationEditorMode = AnnotationEditorType.DISABLE; - } - if (!permissions.includes(PermissionFlag.MODIFY_ANNOTATIONS) && !permissions.includes(PermissionFlag.FILL_INTERACTIVE_FORMS) && this.#annotationMode === AnnotationMode.ENABLE_FORMS) { - params.annotationMode = AnnotationMode.ENABLE; - } - return params; - } - async #onePageRenderedOrForceFetch(signal) { - if (document.visibilityState === "hidden" || !this.container.offsetParent || this._getVisiblePages().views.length === 0) { - return; - } - const hiddenCapability = Promise.withResolvers(), - ac = new AbortController(); - document.addEventListener("visibilitychange", () => { - if (document.visibilityState === "hidden") { - hiddenCapability.resolve(); - } - }, { - signal: typeof AbortSignal.any === "function" ? AbortSignal.any([signal, ac.signal]) : signal - }); - await Promise.race([this._onePageRenderedCapability.promise, hiddenCapability.promise]); - ac.abort(); - } - async getAllText() { - const texts = []; - const buffer = []; - for (let pageNum = 1, pagesCount = this.pdfDocument.numPages; pageNum <= pagesCount; ++pageNum) { - if (this.#interruptCopyCondition) { - return null; - } - buffer.length = 0; - const page = await this.pdfDocument.getPage(pageNum); - const { - items - } = await page.getTextContent(); - for (const item of items) { - if (item.str) { - buffer.push(item.str); - } - if (item.hasEOL) { - buffer.push("\n"); - } - } - texts.push(removeNullCharacters(buffer.join(""))); - } - return texts.join("\n"); - } - #copyCallback(textLayerMode, event) { - const selection = document.getSelection(); - const { - focusNode, - anchorNode - } = selection; - if (anchorNode && focusNode && selection.containsNode(this.#hiddenCopyElement)) { - if (this.#getAllTextInProgress || textLayerMode === TextLayerMode.ENABLE_PERMISSIONS) { - stopEvent(event); - return; - } - this.#getAllTextInProgress = true; - const { - classList - } = this.viewer; - classList.add("copyAll"); - const ac = new AbortController(); - window.addEventListener("keydown", ev => this.#interruptCopyCondition = ev.key === "Escape", { - signal: ac.signal - }); - this.getAllText().then(async text => { - if (text !== null) { - await navigator.clipboard.writeText(text); - } - }).catch(reason => { - console.warn(`Something goes wrong when extracting the text: ${reason.message}`); - }).finally(() => { - this.#getAllTextInProgress = false; - this.#interruptCopyCondition = false; - ac.abort(); - classList.remove("copyAll"); - }); - stopEvent(event); - } - } - setDocument(pdfDocument) { - if (this.pdfDocument) { - this.eventBus.dispatch("pagesdestroy", { - source: this - }); - this._cancelRendering(); - this._resetView(); - this.findController?.setDocument(null); - this._scriptingManager?.setDocument(null); - this.#annotationEditorUIManager?.destroy(); - this.#annotationEditorUIManager = null; - } - this.pdfDocument = pdfDocument; - if (!pdfDocument) { - return; - } - const pagesCount = pdfDocument.numPages; - const firstPagePromise = pdfDocument.getPage(1); - const optionalContentConfigPromise = pdfDocument.getOptionalContentConfig({ - intent: "display" - }); - const permissionsPromise = this.#enablePermissions ? pdfDocument.getPermissions() : Promise.resolve(); - const { - eventBus, - pageColors, - viewer - } = this; - this.#eventAbortController = new AbortController(); - const { - signal - } = this.#eventAbortController; - if (pagesCount > PagesCountLimit.FORCE_SCROLL_MODE_PAGE) { - console.warn("Forcing PAGE-scrolling for performance reasons, given the length of the document."); - const mode = this._scrollMode = ScrollMode.PAGE; - eventBus.dispatch("scrollmodechanged", { - source: this, - mode - }); - } - this._pagesCapability.promise.then(() => { - eventBus.dispatch("pagesloaded", { - source: this, - pagesCount - }); - }, () => {}); - const onBeforeDraw = evt => { - const pageView = this._pages[evt.pageNumber - 1]; - if (!pageView) { - return; - } - this.#buffer.push(pageView); - }; - eventBus._on("pagerender", onBeforeDraw, { - signal - }); - const onAfterDraw = evt => { - if (evt.cssTransform) { - return; - } - this._onePageRenderedCapability.resolve({ - timestamp: evt.timestamp - }); - eventBus._off("pagerendered", onAfterDraw); - }; - eventBus._on("pagerendered", onAfterDraw, { - signal - }); - Promise.all([firstPagePromise, permissionsPromise]).then(([firstPdfPage, permissions]) => { - if (pdfDocument !== this.pdfDocument) { - return; - } - this._firstPageCapability.resolve(firstPdfPage); - this._optionalContentConfigPromise = optionalContentConfigPromise; - const { - annotationEditorMode, - annotationMode, - textLayerMode - } = this.#initializePermissions(permissions); - if (textLayerMode !== TextLayerMode.DISABLE) { - const element = this.#hiddenCopyElement = document.createElement("div"); - element.id = "hiddenCopyElement"; - viewer.before(element); - } - if (typeof AbortSignal.any === "function" && annotationEditorMode !== AnnotationEditorType.DISABLE) { - const mode = annotationEditorMode; - if (pdfDocument.isPureXfa) { - console.warn("Warning: XFA-editing is not implemented."); - } else if (isValidAnnotationEditorMode(mode)) { - this.#annotationEditorUIManager = new AnnotationEditorUIManager(this.container, viewer, this.#altTextManager, eventBus, pdfDocument, pageColors, this.#annotationEditorHighlightColors, this.#enableHighlightFloatingButton, this.#enableUpdatedAddImage, this.#enableNewAltTextWhenAddingImage, this.#mlManager, this.#editorUndoBar, this.#supportsPinchToZoom); - eventBus.dispatch("annotationeditoruimanager", { - source: this, - uiManager: this.#annotationEditorUIManager - }); - if (mode !== AnnotationEditorType.NONE) { - if (mode === AnnotationEditorType.STAMP) { - this.#mlManager?.loadModel("altText"); - } - this.#annotationEditorUIManager.updateMode(mode); - } - } else { - console.error(`Invalid AnnotationEditor mode: ${mode}`); - } - } - const viewerElement = this._scrollMode === ScrollMode.PAGE ? null : viewer; - const scale = this.currentScale; - const viewport = firstPdfPage.getViewport({ - scale: scale * PixelsPerInch.PDF_TO_CSS_UNITS - }); - viewer.style.setProperty("--scale-factor", viewport.scale); - if (pageColors?.background) { - viewer.style.setProperty("--page-bg-color", pageColors.background); - } - if (pageColors?.foreground === "CanvasText" || pageColors?.background === "Canvas") { - viewer.style.setProperty("--hcm-highlight-filter", pdfDocument.filterFactory.addHighlightHCMFilter("highlight", "CanvasText", "Canvas", "HighlightText", "Highlight")); - viewer.style.setProperty("--hcm-highlight-selected-filter", pdfDocument.filterFactory.addHighlightHCMFilter("highlight_selected", "CanvasText", "Canvas", "HighlightText", "ButtonText")); - } - for (let pageNum = 1; pageNum <= pagesCount; ++pageNum) { - const pageView = new PDFPageView({ - container: viewerElement, - eventBus, - id: pageNum, - scale, - defaultViewport: viewport.clone(), - optionalContentConfigPromise, - renderingQueue: this.renderingQueue, - textLayerMode, - annotationMode, - imageResourcesPath: this.imageResourcesPath, - maxCanvasPixels: this.maxCanvasPixels, - pageColors, - l10n: this.l10n, - layerProperties: this._layerProperties, - enableHWA: this.#enableHWA - }); - this._pages.push(pageView); - } - this._pages[0]?.setPdfPage(firstPdfPage); - if (this._scrollMode === ScrollMode.PAGE) { - this.#ensurePageViewVisible(); - } else if (this._spreadMode !== SpreadMode.NONE) { - this._updateSpreadMode(); - } - this.#onePageRenderedOrForceFetch(signal).then(async () => { - if (pdfDocument !== this.pdfDocument) { - return; - } - this.findController?.setDocument(pdfDocument); - this._scriptingManager?.setDocument(pdfDocument); - if (this.#hiddenCopyElement) { - document.addEventListener("copy", this.#copyCallback.bind(this, textLayerMode), { - signal - }); - } - if (this.#annotationEditorUIManager) { - eventBus.dispatch("annotationeditormodechanged", { - source: this, - mode: this.#annotationEditorMode - }); - } - if (pdfDocument.loadingParams.disableAutoFetch || pagesCount > PagesCountLimit.FORCE_LAZY_PAGE_INIT) { - this._pagesCapability.resolve(); - return; - } - let getPagesLeft = pagesCount - 1; - if (getPagesLeft <= 0) { - this._pagesCapability.resolve(); - return; - } - for (let pageNum = 2; pageNum <= pagesCount; ++pageNum) { - const promise = pdfDocument.getPage(pageNum).then(pdfPage => { - const pageView = this._pages[pageNum - 1]; - if (!pageView.pdfPage) { - pageView.setPdfPage(pdfPage); - } - if (--getPagesLeft === 0) { - this._pagesCapability.resolve(); - } - }, reason => { - console.error(`Unable to get page ${pageNum} to initialize viewer`, reason); - if (--getPagesLeft === 0) { - this._pagesCapability.resolve(); - } - }); - if (pageNum % PagesCountLimit.PAUSE_EAGER_PAGE_INIT === 0) { - await promise; - } - } - }); - eventBus.dispatch("pagesinit", { - source: this - }); - pdfDocument.getMetadata().then(({ - info - }) => { - if (pdfDocument !== this.pdfDocument) { - return; - } - if (info.Language) { - viewer.lang = info.Language; - } - }); - if (this.defaultRenderingQueue) { - this.update(); - } - }).catch(reason => { - console.error("Unable to initialize viewer", reason); - this._pagesCapability.reject(reason); - }); - } - setPageLabels(labels) { - if (!this.pdfDocument) { - return; - } - if (!labels) { - this._pageLabels = null; - } else if (!(Array.isArray(labels) && this.pdfDocument.numPages === labels.length)) { - this._pageLabels = null; - console.error(`setPageLabels: Invalid page labels.`); - } else { - this._pageLabels = labels; - } - for (let i = 0, ii = this._pages.length; i < ii; i++) { - this._pages[i].setPageLabel(this._pageLabels?.[i] ?? null); - } - } - _resetView() { - this._pages = []; - this._currentPageNumber = 1; - this._currentScale = UNKNOWN_SCALE; - this._currentScaleValue = null; - this._pageLabels = null; - this.#buffer = new PDFPageViewBuffer(DEFAULT_CACHE_SIZE); - this._location = null; - this._pagesRotation = 0; - this._optionalContentConfigPromise = null; - this._firstPageCapability = Promise.withResolvers(); - this._onePageRenderedCapability = Promise.withResolvers(); - this._pagesCapability = Promise.withResolvers(); - this._scrollMode = ScrollMode.VERTICAL; - this._previousScrollMode = ScrollMode.UNKNOWN; - this._spreadMode = SpreadMode.NONE; - this.#scrollModePageState = { - previousPageNumber: 1, - scrollDown: true, - pages: [] - }; - this.#eventAbortController?.abort(); - this.#eventAbortController = null; - this.viewer.textContent = ""; - this._updateScrollMode(); - this.viewer.removeAttribute("lang"); - this.#hiddenCopyElement?.remove(); - this.#hiddenCopyElement = null; - this.#cleanupSwitchAnnotationEditorMode(); - } - #ensurePageViewVisible() { - if (this._scrollMode !== ScrollMode.PAGE) { - throw new Error("#ensurePageViewVisible: Invalid scrollMode value."); - } - const pageNumber = this._currentPageNumber, - state = this.#scrollModePageState, - viewer = this.viewer; - viewer.textContent = ""; - state.pages.length = 0; - if (this._spreadMode === SpreadMode.NONE && !this.isInPresentationMode) { - const pageView = this._pages[pageNumber - 1]; - viewer.append(pageView.div); - state.pages.push(pageView); - } else { - const pageIndexSet = new Set(), - parity = this._spreadMode - 1; - if (parity === -1) { - pageIndexSet.add(pageNumber - 1); - } else if (pageNumber % 2 !== parity) { - pageIndexSet.add(pageNumber - 1); - pageIndexSet.add(pageNumber); - } else { - pageIndexSet.add(pageNumber - 2); - pageIndexSet.add(pageNumber - 1); - } - const spread = document.createElement("div"); - spread.className = "spread"; - if (this.isInPresentationMode) { - const dummyPage = document.createElement("div"); - dummyPage.className = "dummyPage"; - spread.append(dummyPage); - } - for (const i of pageIndexSet) { - const pageView = this._pages[i]; - if (!pageView) { - continue; - } - spread.append(pageView.div); - state.pages.push(pageView); - } - viewer.append(spread); - } - state.scrollDown = pageNumber >= state.previousPageNumber; - state.previousPageNumber = pageNumber; - } - _scrollUpdate() { - if (this.pagesCount === 0) { - return; - } - this.update(); - } - #scrollIntoView(pageView, pageSpot = null) { - const { - div, - id - } = pageView; - if (this._currentPageNumber !== id) { - this._setCurrentPageNumber(id); - } - if (this._scrollMode === ScrollMode.PAGE) { - this.#ensurePageViewVisible(); - this.update(); - } - if (!pageSpot && !this.isInPresentationMode) { - const left = div.offsetLeft + div.clientLeft, - right = left + div.clientWidth; - const { - scrollLeft, - clientWidth - } = this.container; - if (this._scrollMode === ScrollMode.HORIZONTAL || left < scrollLeft || right > scrollLeft + clientWidth) { - pageSpot = { - left: 0, - top: 0 - }; - } - } - scrollIntoView(div, pageSpot); - if (!this._currentScaleValue && this._location) { - this._location = null; - } - } - #isSameScale(newScale) { - return newScale === this._currentScale || Math.abs(newScale - this._currentScale) < 1e-15; - } - #setScaleUpdatePages(newScale, newValue, { - noScroll = false, - preset = false, - drawingDelay = -1, - origin = null - }) { - this._currentScaleValue = newValue.toString(); - if (this.#isSameScale(newScale)) { - if (preset) { - this.eventBus.dispatch("scalechanging", { - source: this, - scale: newScale, - presetValue: newValue - }); - } - return; - } - this.viewer.style.setProperty("--scale-factor", newScale * PixelsPerInch.PDF_TO_CSS_UNITS); - const postponeDrawing = drawingDelay >= 0 && drawingDelay < 1000; - this.refresh(true, { - scale: newScale, - drawingDelay: postponeDrawing ? drawingDelay : -1 - }); - if (postponeDrawing) { - this.#scaleTimeoutId = setTimeout(() => { - this.#scaleTimeoutId = null; - this.refresh(); - }, drawingDelay); - } - const previousScale = this._currentScale; - this._currentScale = newScale; - if (!noScroll) { - let page = this._currentPageNumber, - dest; - if (this._location && !(this.isInPresentationMode || this.isChangingPresentationMode)) { - page = this._location.pageNumber; - dest = [null, { - name: "XYZ" - }, this._location.left, this._location.top, null]; - } - this.scrollPageIntoView({ - pageNumber: page, - destArray: dest, - allowNegativeOffset: true - }); - if (Array.isArray(origin)) { - const scaleDiff = newScale / previousScale - 1; - const [top, left] = this.containerTopLeft; - this.container.scrollLeft += (origin[0] - left) * scaleDiff; - this.container.scrollTop += (origin[1] - top) * scaleDiff; - } - } - this.eventBus.dispatch("scalechanging", { - source: this, - scale: newScale, - presetValue: preset ? newValue : undefined - }); - if (this.defaultRenderingQueue) { - this.update(); - } - } - get #pageWidthScaleFactor() { - if (this._spreadMode !== SpreadMode.NONE && this._scrollMode !== ScrollMode.HORIZONTAL) { - return 2; - } - return 1; - } - #setScale(value, options) { - let scale = parseFloat(value); - if (scale > 0) { - options.preset = false; - this.#setScaleUpdatePages(scale, value, options); - } else { - const currentPage = this._pages[this._currentPageNumber - 1]; - if (!currentPage) { - return; - } - let hPadding = SCROLLBAR_PADDING, - vPadding = VERTICAL_PADDING; - if (this.isInPresentationMode) { - hPadding = vPadding = 4; - if (this._spreadMode !== SpreadMode.NONE) { - hPadding *= 2; - } - } else if (this.removePageBorders) { - hPadding = vPadding = 0; - } else if (this._scrollMode === ScrollMode.HORIZONTAL) { - [hPadding, vPadding] = [vPadding, hPadding]; - } - const pageWidthScale = (this.container.clientWidth - hPadding) / currentPage.width * currentPage.scale / this.#pageWidthScaleFactor; - const pageHeightScale = (this.container.clientHeight - vPadding) / currentPage.height * currentPage.scale; - switch (value) { - case "page-actual": - scale = 1; - break; - case "page-width": - scale = pageWidthScale; - break; - case "page-height": - scale = pageHeightScale; - break; - case "page-fit": - scale = Math.min(pageWidthScale, pageHeightScale); - break; - case "auto": - const horizontalScale = isPortraitOrientation(currentPage) ? pageWidthScale : Math.min(pageHeightScale, pageWidthScale); - scale = Math.min(MAX_AUTO_SCALE, horizontalScale); - break; - default: - console.error(`#setScale: "${value}" is an unknown zoom value.`); - return; - } - options.preset = true; - this.#setScaleUpdatePages(scale, value, options); - } - } - #resetCurrentPageView() { - const pageView = this._pages[this._currentPageNumber - 1]; - if (this.isInPresentationMode) { - this.#setScale(this._currentScaleValue, { - noScroll: true - }); - } - this.#scrollIntoView(pageView); - } - pageLabelToPageNumber(label) { - if (!this._pageLabels) { - return null; - } - const i = this._pageLabels.indexOf(label); - if (i < 0) { - return null; - } - return i + 1; - } - scrollPageIntoView({ - pageNumber, - destArray = null, - allowNegativeOffset = false, - ignoreDestinationZoom = false - }) { - if (!this.pdfDocument) { - return; - } - const pageView = Number.isInteger(pageNumber) && this._pages[pageNumber - 1]; - if (!pageView) { - console.error(`scrollPageIntoView: "${pageNumber}" is not a valid pageNumber parameter.`); - return; - } - if (this.isInPresentationMode || !destArray) { - this._setCurrentPageNumber(pageNumber, true); - return; - } - let x = 0, - y = 0; - let width = 0, - height = 0, - widthScale, - heightScale; - const changeOrientation = pageView.rotation % 180 !== 0; - const pageWidth = (changeOrientation ? pageView.height : pageView.width) / pageView.scale / PixelsPerInch.PDF_TO_CSS_UNITS; - const pageHeight = (changeOrientation ? pageView.width : pageView.height) / pageView.scale / PixelsPerInch.PDF_TO_CSS_UNITS; - let scale = 0; - switch (destArray[1].name) { - case "XYZ": - x = destArray[2]; - y = destArray[3]; - scale = destArray[4]; - x = x !== null ? x : 0; - y = y !== null ? y : pageHeight; - break; - case "Fit": - case "FitB": - scale = "page-fit"; - break; - case "FitH": - case "FitBH": - y = destArray[2]; - scale = "page-width"; - if (y === null && this._location) { - x = this._location.left; - y = this._location.top; - } else if (typeof y !== "number" || y < 0) { - y = pageHeight; - } - break; - case "FitV": - case "FitBV": - x = destArray[2]; - width = pageWidth; - height = pageHeight; - scale = "page-height"; - break; - case "FitR": - x = destArray[2]; - y = destArray[3]; - width = destArray[4] - x; - height = destArray[5] - y; - let hPadding = SCROLLBAR_PADDING, - vPadding = VERTICAL_PADDING; - if (this.removePageBorders) { - hPadding = vPadding = 0; - } - widthScale = (this.container.clientWidth - hPadding) / width / PixelsPerInch.PDF_TO_CSS_UNITS; - heightScale = (this.container.clientHeight - vPadding) / height / PixelsPerInch.PDF_TO_CSS_UNITS; - scale = Math.min(Math.abs(widthScale), Math.abs(heightScale)); - break; - default: - console.error(`scrollPageIntoView: "${destArray[1].name}" is not a valid destination type.`); - return; - } - if (!ignoreDestinationZoom) { - if (scale && scale !== this._currentScale) { - this.currentScaleValue = scale; - } else if (this._currentScale === UNKNOWN_SCALE) { - this.currentScaleValue = DEFAULT_SCALE_VALUE; - } - } - if (scale === "page-fit" && !destArray[4]) { - this.#scrollIntoView(pageView); - return; - } - const boundingRect = [pageView.viewport.convertToViewportPoint(x, y), pageView.viewport.convertToViewportPoint(x + width, y + height)]; - let left = Math.min(boundingRect[0][0], boundingRect[1][0]); - let top = Math.min(boundingRect[0][1], boundingRect[1][1]); - if (!allowNegativeOffset) { - left = Math.max(left, 0); - top = Math.max(top, 0); - } - this.#scrollIntoView(pageView, { - left, - top - }); - } - _updateLocation(firstPage) { - const currentScale = this._currentScale; - const currentScaleValue = this._currentScaleValue; - const normalizedScaleValue = parseFloat(currentScaleValue) === currentScale ? Math.round(currentScale * 10000) / 100 : currentScaleValue; - const pageNumber = firstPage.id; - const currentPageView = this._pages[pageNumber - 1]; - const container = this.container; - const topLeft = currentPageView.getPagePoint(container.scrollLeft - firstPage.x, container.scrollTop - firstPage.y); - const intLeft = Math.round(topLeft[0]); - const intTop = Math.round(topLeft[1]); - let pdfOpenParams = `#page=${pageNumber}`; - if (!this.isInPresentationMode) { - pdfOpenParams += `&zoom=${normalizedScaleValue},${intLeft},${intTop}`; - } - this._location = { - pageNumber, - scale: normalizedScaleValue, - top: intTop, - left: intLeft, - rotation: this._pagesRotation, - pdfOpenParams - }; - } - update() { - const visible = this._getVisiblePages(); - const visiblePages = visible.views, - numVisiblePages = visiblePages.length; - if (numVisiblePages === 0) { - return; - } - const newCacheSize = Math.max(DEFAULT_CACHE_SIZE, 2 * numVisiblePages + 1); - this.#buffer.resize(newCacheSize, visible.ids); - this.renderingQueue.renderHighestPriority(visible); - const isSimpleLayout = this._spreadMode === SpreadMode.NONE && (this._scrollMode === ScrollMode.PAGE || this._scrollMode === ScrollMode.VERTICAL); - const currentId = this._currentPageNumber; - let stillFullyVisible = false; - for (const page of visiblePages) { - if (page.percent < 100) { - break; - } - if (page.id === currentId && isSimpleLayout) { - stillFullyVisible = true; - break; - } - } - this._setCurrentPageNumber(stillFullyVisible ? currentId : visiblePages[0].id); - this._updateLocation(visible.first); - this.eventBus.dispatch("updateviewarea", { - source: this, - location: this._location - }); - } - #switchToEditAnnotationMode() { - const visible = this._getVisiblePages(); - const pagesToRefresh = []; - const { - ids, - views - } = visible; - for (const page of views) { - const { - view - } = page; - if (!view.hasEditableAnnotations()) { - ids.delete(view.id); - continue; - } - pagesToRefresh.push(page); - } - if (pagesToRefresh.length === 0) { - return null; - } - this.renderingQueue.renderHighestPriority({ - first: pagesToRefresh[0], - last: pagesToRefresh.at(-1), - views: pagesToRefresh, - ids - }); - return ids; - } - containsElement(element) { - return this.container.contains(element); - } - focus() { - this.container.focus(); - } - get _isContainerRtl() { - return getComputedStyle(this.container).direction === "rtl"; - } - get isInPresentationMode() { - return this.presentationModeState === PresentationModeState.FULLSCREEN; - } - get isChangingPresentationMode() { - return this.presentationModeState === PresentationModeState.CHANGING; - } - get isHorizontalScrollbarEnabled() { - return this.isInPresentationMode ? false : this.container.scrollWidth > this.container.clientWidth; - } - get isVerticalScrollbarEnabled() { - return this.isInPresentationMode ? false : this.container.scrollHeight > this.container.clientHeight; - } - _getVisiblePages() { - const views = this._scrollMode === ScrollMode.PAGE ? this.#scrollModePageState.pages : this._pages, - horizontal = this._scrollMode === ScrollMode.HORIZONTAL, - rtl = horizontal && this._isContainerRtl; - return getVisibleElements({ - scrollEl: this.container, - views, - sortByVisibility: true, - horizontal, - rtl - }); - } - cleanup() { - for (const pageView of this._pages) { - if (pageView.renderingState !== RenderingStates.FINISHED) { - pageView.reset(); - } - } - } - _cancelRendering() { - for (const pageView of this._pages) { - pageView.cancelRendering(); - } - } - async #ensurePdfPageLoaded(pageView) { - if (pageView.pdfPage) { - return pageView.pdfPage; - } - try { - const pdfPage = await this.pdfDocument.getPage(pageView.id); - if (!pageView.pdfPage) { - pageView.setPdfPage(pdfPage); - } - return pdfPage; - } catch (reason) { - console.error("Unable to get page for page view", reason); - return null; - } - } - #getScrollAhead(visible) { - if (visible.first?.id === 1) { - return true; - } else if (visible.last?.id === this.pagesCount) { - return false; - } - switch (this._scrollMode) { - case ScrollMode.PAGE: - return this.#scrollModePageState.scrollDown; - case ScrollMode.HORIZONTAL: - return this.scroll.right; - } - return this.scroll.down; - } - forceRendering(currentlyVisiblePages) { - const visiblePages = currentlyVisiblePages || this._getVisiblePages(); - const scrollAhead = this.#getScrollAhead(visiblePages); - const preRenderExtra = this._spreadMode !== SpreadMode.NONE && this._scrollMode !== ScrollMode.HORIZONTAL; - const pageView = this.renderingQueue.getHighestPriority(visiblePages, this._pages, scrollAhead, preRenderExtra); - if (pageView) { - this.#ensurePdfPageLoaded(pageView).then(() => { - this.renderingQueue.renderView(pageView); - }); - return true; - } - return false; - } - get hasEqualPageSizes() { - const firstPageView = this._pages[0]; - for (let i = 1, ii = this._pages.length; i < ii; ++i) { - const pageView = this._pages[i]; - if (pageView.width !== firstPageView.width || pageView.height !== firstPageView.height) { - return false; - } - } - return true; - } - getPagesOverview() { - let initialOrientation; - return this._pages.map(pageView => { - const viewport = pageView.pdfPage.getViewport({ - scale: 1 - }); - const orientation = isPortraitOrientation(viewport); - if (initialOrientation === undefined) { - initialOrientation = orientation; - } else if (this.enablePrintAutoRotate && orientation !== initialOrientation) { - return { - width: viewport.height, - height: viewport.width, - rotation: (viewport.rotation - 90) % 360 - }; - } - return { - width: viewport.width, - height: viewport.height, - rotation: viewport.rotation - }; - }); - } - get optionalContentConfigPromise() { - if (!this.pdfDocument) { - return Promise.resolve(null); - } - if (!this._optionalContentConfigPromise) { - console.error("optionalContentConfigPromise: Not initialized yet."); - return this.pdfDocument.getOptionalContentConfig({ - intent: "display" - }); - } - return this._optionalContentConfigPromise; - } - set optionalContentConfigPromise(promise) { - if (!(promise instanceof Promise)) { - throw new Error(`Invalid optionalContentConfigPromise: ${promise}`); - } - if (!this.pdfDocument) { - return; - } - if (!this._optionalContentConfigPromise) { - return; - } - this._optionalContentConfigPromise = promise; - this.refresh(false, { - optionalContentConfigPromise: promise - }); - this.eventBus.dispatch("optionalcontentconfigchanged", { - source: this, - promise - }); - } - get scrollMode() { - return this._scrollMode; - } - set scrollMode(mode) { - if (this._scrollMode === mode) { - return; - } - if (!isValidScrollMode(mode)) { - throw new Error(`Invalid scroll mode: ${mode}`); - } - if (this.pagesCount > PagesCountLimit.FORCE_SCROLL_MODE_PAGE) { - return; - } - this._previousScrollMode = this._scrollMode; - this._scrollMode = mode; - this.eventBus.dispatch("scrollmodechanged", { - source: this, - mode - }); - this._updateScrollMode(this._currentPageNumber); - } - _updateScrollMode(pageNumber = null) { - const scrollMode = this._scrollMode, - viewer = this.viewer; - viewer.classList.toggle("scrollHorizontal", scrollMode === ScrollMode.HORIZONTAL); - viewer.classList.toggle("scrollWrapped", scrollMode === ScrollMode.WRAPPED); - if (!this.pdfDocument || !pageNumber) { - return; - } - if (scrollMode === ScrollMode.PAGE) { - this.#ensurePageViewVisible(); - } else if (this._previousScrollMode === ScrollMode.PAGE) { - this._updateSpreadMode(); - } - if (this._currentScaleValue && isNaN(this._currentScaleValue)) { - this.#setScale(this._currentScaleValue, { - noScroll: true - }); - } - this._setCurrentPageNumber(pageNumber, true); - this.update(); - } - get spreadMode() { - return this._spreadMode; - } - set spreadMode(mode) { - if (this._spreadMode === mode) { - return; - } - if (!isValidSpreadMode(mode)) { - throw new Error(`Invalid spread mode: ${mode}`); - } - this._spreadMode = mode; - this.eventBus.dispatch("spreadmodechanged", { - source: this, - mode - }); - this._updateSpreadMode(this._currentPageNumber); - } - _updateSpreadMode(pageNumber = null) { - if (!this.pdfDocument) { - return; - } - const viewer = this.viewer, - pages = this._pages; - if (this._scrollMode === ScrollMode.PAGE) { - this.#ensurePageViewVisible(); - } else { - viewer.textContent = ""; - if (this._spreadMode === SpreadMode.NONE) { - for (const pageView of this._pages) { - viewer.append(pageView.div); - } - } else { - const parity = this._spreadMode - 1; - let spread = null; - for (let i = 0, ii = pages.length; i < ii; ++i) { - if (spread === null) { - spread = document.createElement("div"); - spread.className = "spread"; - viewer.append(spread); - } else if (i % 2 === parity) { - spread = spread.cloneNode(false); - viewer.append(spread); - } - spread.append(pages[i].div); - } - } - } - if (!pageNumber) { - return; - } - if (this._currentScaleValue && isNaN(this._currentScaleValue)) { - this.#setScale(this._currentScaleValue, { - noScroll: true - }); - } - this._setCurrentPageNumber(pageNumber, true); - this.update(); - } - _getPageAdvance(currentPageNumber, previous = false) { - switch (this._scrollMode) { - case ScrollMode.WRAPPED: - { - const { - views - } = this._getVisiblePages(), - pageLayout = new Map(); - for (const { - id, - y, - percent, - widthPercent - } of views) { - if (percent === 0 || widthPercent < 100) { - continue; - } - let yArray = pageLayout.get(y); - if (!yArray) { - pageLayout.set(y, yArray ||= []); - } - yArray.push(id); - } - for (const yArray of pageLayout.values()) { - const currentIndex = yArray.indexOf(currentPageNumber); - if (currentIndex === -1) { - continue; - } - const numPages = yArray.length; - if (numPages === 1) { - break; - } - if (previous) { - for (let i = currentIndex - 1, ii = 0; i >= ii; i--) { - const currentId = yArray[i], - expectedId = yArray[i + 1] - 1; - if (currentId < expectedId) { - return currentPageNumber - expectedId; - } - } - } else { - for (let i = currentIndex + 1, ii = numPages; i < ii; i++) { - const currentId = yArray[i], - expectedId = yArray[i - 1] + 1; - if (currentId > expectedId) { - return expectedId - currentPageNumber; - } - } - } - if (previous) { - const firstId = yArray[0]; - if (firstId < currentPageNumber) { - return currentPageNumber - firstId + 1; - } - } else { - const lastId = yArray[numPages - 1]; - if (lastId > currentPageNumber) { - return lastId - currentPageNumber + 1; - } - } - break; - } - break; - } - case ScrollMode.HORIZONTAL: - { - break; - } - case ScrollMode.PAGE: - case ScrollMode.VERTICAL: - { - if (this._spreadMode === SpreadMode.NONE) { - break; - } - const parity = this._spreadMode - 1; - if (previous && currentPageNumber % 2 !== parity) { - break; - } else if (!previous && currentPageNumber % 2 === parity) { - break; - } - const { - views - } = this._getVisiblePages(), - expectedId = previous ? currentPageNumber - 1 : currentPageNumber + 1; - for (const { - id, - percent, - widthPercent - } of views) { - if (id !== expectedId) { - continue; - } - if (percent > 0 && widthPercent === 100) { - return 2; - } - break; - } - break; - } - } - return 1; - } - nextPage() { - const currentPageNumber = this._currentPageNumber, - pagesCount = this.pagesCount; - if (currentPageNumber >= pagesCount) { - return false; - } - const advance = this._getPageAdvance(currentPageNumber, false) || 1; - this.currentPageNumber = Math.min(currentPageNumber + advance, pagesCount); - return true; - } - previousPage() { - const currentPageNumber = this._currentPageNumber; - if (currentPageNumber <= 1) { - return false; - } - const advance = this._getPageAdvance(currentPageNumber, true) || 1; - this.currentPageNumber = Math.max(currentPageNumber - advance, 1); - return true; - } - updateScale({ - drawingDelay, - scaleFactor = null, - steps = null, - origin - }) { - if (steps === null && scaleFactor === null) { - throw new Error("Invalid updateScale options: either `steps` or `scaleFactor` must be provided."); - } - if (!this.pdfDocument) { - return; - } - let newScale = this._currentScale; - if (scaleFactor > 0 && scaleFactor !== 1) { - newScale = Math.round(newScale * scaleFactor * 100) / 100; - } else if (steps) { - const delta = steps > 0 ? DEFAULT_SCALE_DELTA : 1 / DEFAULT_SCALE_DELTA; - const round = steps > 0 ? Math.ceil : Math.floor; - steps = Math.abs(steps); - do { - newScale = round((newScale * delta).toFixed(2) * 10) / 10; - } while (--steps > 0); - } - newScale = Math.max(MIN_SCALE, Math.min(MAX_SCALE, newScale)); - this.#setScale(newScale, { - noScroll: false, - drawingDelay, - origin - }); - } - increaseScale(options = {}) { - this.updateScale({ - ...options, - steps: options.steps ?? 1 - }); - } - decreaseScale(options = {}) { - this.updateScale({ - ...options, - steps: -(options.steps ?? 1) - }); - } - #updateContainerHeightCss(height = this.container.clientHeight) { - if (height !== this.#previousContainerHeight) { - this.#previousContainerHeight = height; - docStyle.setProperty("--viewer-container-height", `${height}px`); - } - } - #resizeObserverCallback(entries) { - for (const entry of entries) { - if (entry.target === this.container) { - this.#updateContainerHeightCss(Math.floor(entry.borderBoxSize[0].blockSize)); - this.#containerTopLeft = null; - break; - } - } - } - get containerTopLeft() { - return this.#containerTopLeft ||= [this.container.offsetTop, this.container.offsetLeft]; - } - #cleanupSwitchAnnotationEditorMode() { - this.#switchAnnotationEditorModeAC?.abort(); - this.#switchAnnotationEditorModeAC = null; - if (this.#switchAnnotationEditorModeTimeoutId !== null) { - clearTimeout(this.#switchAnnotationEditorModeTimeoutId); - this.#switchAnnotationEditorModeTimeoutId = null; - } - } - get annotationEditorMode() { - return this.#annotationEditorUIManager ? this.#annotationEditorMode : AnnotationEditorType.DISABLE; - } - set annotationEditorMode({ - mode, - editId = null, - isFromKeyboard = false - }) { - if (!this.#annotationEditorUIManager) { - throw new Error(`The AnnotationEditor is not enabled.`); - } - if (this.#annotationEditorMode === mode) { - return; - } - if (!isValidAnnotationEditorMode(mode)) { - throw new Error(`Invalid AnnotationEditor mode: ${mode}`); - } - if (!this.pdfDocument) { - return; - } - if (mode === AnnotationEditorType.STAMP) { - this.#mlManager?.loadModel("altText"); - } - const { - eventBus - } = this; - const updater = () => { - this.#cleanupSwitchAnnotationEditorMode(); - this.#annotationEditorMode = mode; - this.#annotationEditorUIManager.updateMode(mode, editId, isFromKeyboard); - eventBus.dispatch("annotationeditormodechanged", { - source: this, - mode - }); - }; - if (mode === AnnotationEditorType.NONE || this.#annotationEditorMode === AnnotationEditorType.NONE) { - const isEditing = mode !== AnnotationEditorType.NONE; - if (!isEditing) { - this.pdfDocument.annotationStorage.resetModifiedIds(); - } - for (const pageView of this._pages) { - pageView.toggleEditingMode(isEditing); - } - const idsToRefresh = this.#switchToEditAnnotationMode(); - if (isEditing && idsToRefresh) { - this.#cleanupSwitchAnnotationEditorMode(); - this.#switchAnnotationEditorModeAC = new AbortController(); - const signal = AbortSignal.any([this.#eventAbortController.signal, this.#switchAnnotationEditorModeAC.signal]); - eventBus._on("pagerendered", ({ - pageNumber - }) => { - idsToRefresh.delete(pageNumber); - if (idsToRefresh.size === 0) { - this.#switchAnnotationEditorModeTimeoutId = setTimeout(updater, 0); - } - }, { - signal - }); - return; - } - } - updater(); - } - refresh(noUpdate = false, updateArgs = Object.create(null)) { - if (!this.pdfDocument) { - return; - } - for (const pageView of this._pages) { - pageView.update(updateArgs); - } - if (this.#scaleTimeoutId !== null) { - clearTimeout(this.#scaleTimeoutId); - this.#scaleTimeoutId = null; - } - if (!noUpdate) { - this.update(); - } - } -} - -;// ./web/pdf_single_page_viewer.js - - -class PDFSinglePageViewer extends PDFViewer { - _resetView() { - super._resetView(); - this._scrollMode = ScrollMode.PAGE; - this._spreadMode = SpreadMode.NONE; - } - set scrollMode(mode) {} - _updateScrollMode() {} - set spreadMode(mode) {} - _updateSpreadMode() {} -} - -;// ./web/pdf_viewer.component.js - - - - - - - - - - - - - - - -const pdfjsVersion = "4.10.38"; -const pdfjsBuild = "f9bea397f"; - -var __webpack_exports__AnnotationLayerBuilder = __webpack_exports__.AnnotationLayerBuilder; -var __webpack_exports__DownloadManager = __webpack_exports__.DownloadManager; -var __webpack_exports__EventBus = __webpack_exports__.EventBus; -var __webpack_exports__FindState = __webpack_exports__.FindState; -var __webpack_exports__GenericL10n = __webpack_exports__.GenericL10n; -var __webpack_exports__LinkTarget = __webpack_exports__.LinkTarget; -var __webpack_exports__PDFFindController = __webpack_exports__.PDFFindController; -var __webpack_exports__PDFHistory = __webpack_exports__.PDFHistory; -var __webpack_exports__PDFLinkService = __webpack_exports__.PDFLinkService; -var __webpack_exports__PDFPageView = __webpack_exports__.PDFPageView; -var __webpack_exports__PDFScriptingManager = __webpack_exports__.PDFScriptingManager; -var __webpack_exports__PDFSinglePageViewer = __webpack_exports__.PDFSinglePageViewer; -var __webpack_exports__PDFViewer = __webpack_exports__.PDFViewer; -var __webpack_exports__ProgressBar = __webpack_exports__.ProgressBar; -var __webpack_exports__RenderingStates = __webpack_exports__.RenderingStates; -var __webpack_exports__ScrollMode = __webpack_exports__.ScrollMode; -var __webpack_exports__SimpleLinkService = __webpack_exports__.SimpleLinkService; -var __webpack_exports__SpreadMode = __webpack_exports__.SpreadMode; -var __webpack_exports__StructTreeLayerBuilder = __webpack_exports__.StructTreeLayerBuilder; -var __webpack_exports__TextLayerBuilder = __webpack_exports__.TextLayerBuilder; -var __webpack_exports__XfaLayerBuilder = __webpack_exports__.XfaLayerBuilder; -var __webpack_exports__parseQueryString = __webpack_exports__.parseQueryString; -export { __webpack_exports__AnnotationLayerBuilder as AnnotationLayerBuilder, __webpack_exports__DownloadManager as DownloadManager, __webpack_exports__EventBus as EventBus, __webpack_exports__FindState as FindState, __webpack_exports__GenericL10n as GenericL10n, __webpack_exports__LinkTarget as LinkTarget, __webpack_exports__PDFFindController as PDFFindController, __webpack_exports__PDFHistory as PDFHistory, __webpack_exports__PDFLinkService as PDFLinkService, __webpack_exports__PDFPageView as PDFPageView, __webpack_exports__PDFScriptingManager as PDFScriptingManager, __webpack_exports__PDFSinglePageViewer as PDFSinglePageViewer, __webpack_exports__PDFViewer as PDFViewer, __webpack_exports__ProgressBar as ProgressBar, __webpack_exports__RenderingStates as RenderingStates, __webpack_exports__ScrollMode as ScrollMode, __webpack_exports__SimpleLinkService as SimpleLinkService, __webpack_exports__SpreadMode as SpreadMode, __webpack_exports__StructTreeLayerBuilder as StructTreeLayerBuilder, __webpack_exports__TextLayerBuilder as TextLayerBuilder, __webpack_exports__XfaLayerBuilder as XfaLayerBuilder, __webpack_exports__parseQueryString as parseQueryString }; - -//# sourceMappingURL=pdf_viewer.mjs.map \ No newline at end of file diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/tailwindcss/README.md b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/tailwindcss/README.md deleted file mode 100644 index 69fb53bf322..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/tailwindcss/README.md +++ /dev/null @@ -1,7 +0,0 @@ -tailwindcss version 4.0.3 -https://github.com/tailwindlabs/tailwindcss -License: MIT - -This template uses only `preflight.css`, the CSS reset stylesheet from Tailwind. For simplicity, this template doesn't use a complete deployment of Tailwind. If you want to use the full Tailwind library, remove `preflight.css` and reference the full version of Tailwind. - -To update, replace the `preflight.css` file with the one in an updated build from https://www.npmjs.com/package/tailwindcss diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/tailwindcss/dist/preflight.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/tailwindcss/dist/preflight.css deleted file mode 100644 index 178c881dd23..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/wwwroot/lib/tailwindcss/dist/preflight.css +++ /dev/null @@ -1,383 +0,0 @@ -/* - 1. Prevent padding and border from affecting element width. (https://github.com/mozdevs/cssremedy/issues/4) - 2. Remove default margins and padding - 3. Reset all borders. -*/ - -*, -::after, -::before, -::backdrop, -::file-selector-button { - box-sizing: border-box; /* 1 */ - margin: 0; /* 2 */ - padding: 0; /* 2 */ - border: 0 solid; /* 3 */ -} - -/* - 1. Use a consistent sensible line-height in all browsers. - 2. Prevent adjustments of font size after orientation changes in iOS. - 3. Use a more readable tab size. - 4. Use the user's configured `sans` font-family by default. - 5. Use the user's configured `sans` font-feature-settings by default. - 6. Use the user's configured `sans` font-variation-settings by default. - 7. Disable tap highlights on iOS. -*/ - -html, -:host { - line-height: 1.5; /* 1 */ - -webkit-text-size-adjust: 100%; /* 2 */ - tab-size: 4; /* 3 */ - font-family: var( - --default-font-family, - ui-sans-serif, - system-ui, - sans-serif, - 'Apple Color Emoji', - 'Segoe UI Emoji', - 'Segoe UI Symbol', - 'Noto Color Emoji' - ); /* 4 */ - font-feature-settings: var(--default-font-feature-settings, normal); /* 5 */ - font-variation-settings: var(--default-font-variation-settings, normal); /* 6 */ - -webkit-tap-highlight-color: transparent; /* 7 */ -} - -/* - Inherit line-height from `html` so users can set them as a class directly on the `html` element. -*/ - -body { - line-height: inherit; -} - -/* - 1. Add the correct height in Firefox. - 2. Correct the inheritance of border color in Firefox. (https://bugzilla.mozilla.org/show_bug.cgi?id=190655) - 3. Reset the default border style to a 1px solid border. -*/ - -hr { - height: 0; /* 1 */ - color: inherit; /* 2 */ - border-top-width: 1px; /* 3 */ -} - -/* - Add the correct text decoration in Chrome, Edge, and Safari. -*/ - -abbr:where([title]) { - -webkit-text-decoration: underline dotted; - text-decoration: underline dotted; -} - -/* - Remove the default font size and weight for headings. -*/ - -h1, -h2, -h3, -h4, -h5, -h6 { - font-size: inherit; - font-weight: inherit; -} - -/* - Reset links to optimize for opt-in styling instead of opt-out. -*/ - -a { - color: inherit; - -webkit-text-decoration: inherit; - text-decoration: inherit; -} - -/* - Add the correct font weight in Edge and Safari. -*/ - -b, -strong { - font-weight: bolder; -} - -/* - 1. Use the user's configured `mono` font-family by default. - 2. Use the user's configured `mono` font-feature-settings by default. - 3. Use the user's configured `mono` font-variation-settings by default. - 4. Correct the odd `em` font sizing in all browsers. -*/ - -code, -kbd, -samp, -pre { - font-family: var( - --default-mono-font-family, - ui-monospace, - SFMono-Regular, - Menlo, - Monaco, - Consolas, - 'Liberation Mono', - 'Courier New', - monospace - ); /* 4 */ - font-feature-settings: var(--default-mono-font-feature-settings, normal); /* 5 */ - font-variation-settings: var(--default-mono-font-variation-settings, normal); /* 6 */ - font-size: 1em; /* 4 */ -} - -/* - Add the correct font size in all browsers. -*/ - -small { - font-size: 80%; -} - -/* - Prevent `sub` and `sup` elements from affecting the line height in all browsers. -*/ - -sub, -sup { - font-size: 75%; - line-height: 0; - position: relative; - vertical-align: baseline; -} - -sub { - bottom: -0.25em; -} - -sup { - top: -0.5em; -} - -/* - 1. Remove text indentation from table contents in Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=999088, https://bugs.webkit.org/show_bug.cgi?id=201297) - 2. Correct table border color inheritance in all Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=935729, https://bugs.webkit.org/show_bug.cgi?id=195016) - 3. Remove gaps between table borders by default. -*/ - -table { - text-indent: 0; /* 1 */ - border-color: inherit; /* 2 */ - border-collapse: collapse; /* 3 */ -} - -/* - Use the modern Firefox focus style for all focusable elements. -*/ - -:-moz-focusring { - outline: auto; -} - -/* - Add the correct vertical alignment in Chrome and Firefox. -*/ - -progress { - vertical-align: baseline; -} - -/* - Add the correct display in Chrome and Safari. -*/ - -summary { - display: list-item; -} - -/* - Make lists unstyled by default. -*/ - -ol, -ul, -menu { - list-style: none; -} - -/* - 1. Make replaced elements `display: block` by default. (https://github.com/mozdevs/cssremedy/issues/14) - 2. Add `vertical-align: middle` to align replaced elements more sensibly by default. (https://github.com/jensimmons/cssremedy/issues/14#issuecomment-634934210) - This can trigger a poorly considered lint error in some tools but is included by design. -*/ - -img, -svg, -video, -canvas, -audio, -iframe, -embed, -object { - display: block; /* 1 */ - vertical-align: middle; /* 2 */ -} - -/* - Constrain images and videos to the parent width and preserve their intrinsic aspect ratio. (https://github.com/mozdevs/cssremedy/issues/14) -*/ - -img, -video { - max-width: 100%; - height: auto; -} - -/* - 1. Inherit font styles in all browsers. - 2. Remove border radius in all browsers. - 3. Remove background color in all browsers. - 4. Ensure consistent opacity for disabled states in all browsers. -*/ - -button, -input, -select, -optgroup, -textarea, -::file-selector-button { - font: inherit; /* 1 */ - font-feature-settings: inherit; /* 1 */ - font-variation-settings: inherit; /* 1 */ - letter-spacing: inherit; /* 1 */ - color: inherit; /* 1 */ - border-radius: 0; /* 2 */ - background-color: transparent; /* 3 */ - opacity: 1; /* 4 */ -} - -/* - Restore default font weight. -*/ - -:where(select:is([multiple], [size])) optgroup { - font-weight: bolder; -} - -/* - Restore indentation. -*/ - -:where(select:is([multiple], [size])) optgroup option { - padding-inline-start: 20px; -} - -/* - Restore space after button. -*/ - -::file-selector-button { - margin-inline-end: 4px; -} - -/* - 1. Reset the default placeholder opacity in Firefox. (https://github.com/tailwindlabs/tailwindcss/issues/3300) - 2. Set the default placeholder color to a semi-transparent version of the current text color. -*/ - -::placeholder { - opacity: 1; /* 1 */ - color: color-mix(in oklab, currentColor 50%, transparent); /* 2 */ -} - -/* - Prevent resizing textareas horizontally by default. -*/ - -textarea { - resize: vertical; -} - -/* - Remove the inner padding in Chrome and Safari on macOS. -*/ - -::-webkit-search-decoration { - -webkit-appearance: none; -} - -/* - 1. Ensure date/time inputs have the same height when empty in iOS Safari. - 2. Ensure text alignment can be changed on date/time inputs in iOS Safari. -*/ - -::-webkit-date-and-time-value { - min-height: 1lh; /* 1 */ - text-align: inherit; /* 2 */ -} - -/* - Prevent height from changing on date/time inputs in macOS Safari when the input is set to `display: block`. -*/ - -::-webkit-datetime-edit { - display: inline-flex; -} - -/* - Remove excess padding from pseudo-elements in date/time inputs to ensure consistent height across browsers. -*/ - -::-webkit-datetime-edit-fields-wrapper { - padding: 0; -} - -::-webkit-datetime-edit, -::-webkit-datetime-edit-year-field, -::-webkit-datetime-edit-month-field, -::-webkit-datetime-edit-day-field, -::-webkit-datetime-edit-hour-field, -::-webkit-datetime-edit-minute-field, -::-webkit-datetime-edit-second-field, -::-webkit-datetime-edit-millisecond-field, -::-webkit-datetime-edit-meridiem-field { - padding-block: 0; -} - -/* - Remove the additional `:invalid` styles in Firefox. (https://github.com/mozilla/gecko-dev/blob/2f9eacd9d3d995c937b4251a5557d95d494c9be1/layout/style/res/forms.css#L728-L737) -*/ - -:-moz-ui-invalid { - box-shadow: none; -} - -/* - Correct the inability to style the border radius in iOS Safari. -*/ - -button, -input:where([type='button'], [type='reset'], [type='submit']), -::file-selector-button { - appearance: button; -} - -/* - Correct the cursor style of increment and decrement buttons in Safari. -*/ - -::-webkit-inner-spin-button, -::-webkit-outer-spin-button { - height: auto; -} - -/* - Make elements with the HTML hidden attribute stay hidden by default. -*/ - -[hidden]:where(:not([hidden='until-found'])) { - display: none !important; -} diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Properties/launchSettings.json b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Properties/launchSettings.json deleted file mode 100644 index e2d900a219d..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Properties/launchSettings.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "$schema": "https://json.schemastore.org/launchsettings.json", - "profiles": { - "http": { - "commandName": "Project", - "dotnetRunMessages": true, - "launchBrowser": true, - "applicationUrl": "http://localhost:9999", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - }, - "https": { - "commandName": "Project", - "dotnetRunMessages": true, - "launchBrowser": true, - "applicationUrl": "https://localhost:9999;http://localhost:9999", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - } - } -} diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/Data/Example_Emergency_Survival_Kit.pdf b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/Data/Example_Emergency_Survival_Kit.pdf deleted file mode 100644 index 94625f0e0e0617c1324cf5243b06d0e8a2da6177..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 153539 zcmdSC1yohr8aBM?5a|YC(;b^`knZlTO-OeONJ|MQAt`Cl-61W~og#uD4GM_Vzd?`U zIh;H0_nkAof7~&2Y!>^S^Q}3b`K~$FdZ1Dkmt+Dlb0AZVZhU%=3<9zO9Zc^b3ka~N zTf5qVfwU5KU}sCPy_pwK&CS`}+TFw!C}-_Ths+}83^s9fa0b#UICxvz+M2L%GP45p zX|=5F%^f^kfQsrs5Gyk)KM?W@E)IU6Cl`l49q_KBqb*nqYzpaug_E6|nVk#LL{3^= zL7ow4Yi$DtN`cL693X-P$HvOW!O8{V1%W_Z?3@g&tTd2+5IF@0 z^ZzU&B!moxI0Xp{`>*hrnE*k^ETRfP7DWeVI}_VqLR`OuB&}^-A*QiN+Cpp)2b(#V zgOOR}!S#1MEt zph%PqZtFr!hHGMqyk9i=ts~7*#%;pBT~_>4V(QFkj^(#uF#}_0?^@WeQ2Cy!(qLoibpY)-mdT5&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kDDyI zd~wlA_HKjV`ZteVOx33 zjQ^i7DCVmO0QR5df#K-R3S;~~6I7t&|1J-?`h2eKIut)%s6pEpEqy`pcHi+57=RRP zZ8(0-OL8bh_Dn>kCEmL>RB@X^NLjA(p{{W!zUzMTPO@kIoR<5M`84LJVbeNU0P1zq z4^O(t7vkAuH@G=26!_ToGp8Xef3sV;1$v=+Rg=q 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - return apply(func, thisArg, args); - }; -} -/** - * Creates a new function that constructs an instance of the given constructor function with the provided arguments. - * - * @param func - The constructor function to be wrapped and called. - * @returns A new function that constructs an instance of the given constructor function with the provided arguments. - */ -function unconstruct(func) { - return function () { - for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - args[_key2] = arguments[_key2]; - } - return construct(func, args); - }; -} -/** - * Add properties to a lookup table - * - * @param set - The set to which elements will be added. - * @param array - The array containing elements to be added to the set. - * @param transformCaseFunc - An optional function to transform the case of each element before adding to the set. - * @returns The modified set with added elements. - */ -function addToSet(set, array) { - let transformCaseFunc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : stringToLowerCase; - if (setPrototypeOf) { - // Make 'in' and truthy checks like Boolean(set.constructor) - // independent of any properties defined on Object.prototype. - // Prevent prototype setters from intercepting set as a this value. - setPrototypeOf(set, null); - } - let l = array.length; - while (l--) { - let element = array[l]; - if (typeof element === 'string') { - const lcElement = transformCaseFunc(element); - if (lcElement !== element) { - // Config presets (e.g. tags.js, attrs.js) are immutable. - if (!isFrozen(array)) { - array[l] = lcElement; - } - element = lcElement; - } - } - set[element] = true; - } - return set; -} -/** - * Clean up an array to harden against CSPP - * - * @param array - The array to be cleaned. - * @returns The cleaned version of the array - */ -function cleanArray(array) { - for (let index = 0; index < array.length; index++) { - const isPropertyExist = objectHasOwnProperty(array, index); - if (!isPropertyExist) { - array[index] = null; - } - } - return array; -} -/** - * Shallow clone an object - * - * @param object - The object to be cloned. - * @returns A new object that copies the original. - */ -function clone(object) { - const newObject = create(null); - for (const [property, value] of entries(object)) { - const isPropertyExist = objectHasOwnProperty(object, property); - if (isPropertyExist) { - if (Array.isArray(value)) { - newObject[property] = cleanArray(value); - } else if (value && typeof value === 'object' && value.constructor === Object) { - newObject[property] = clone(value); - } else { - newObject[property] = value; - } - } - } - return newObject; -} -/** - * This method automatically checks if the prop is function or getter and behaves accordingly. - * - * @param object - The object to look up the getter function in its prototype chain. - * @param prop - The property name for which to find the getter function. - * @returns The getter function found in the prototype chain or a fallback function. - */ -function lookupGetter(object, prop) { - while (object !== null) { - const desc = getOwnPropertyDescriptor(object, prop); - if (desc) { - if (desc.get) { - return unapply(desc.get); - } - if (typeof desc.value === 'function') { - return unapply(desc.value); - } - } - object = getPrototypeOf(object); - } - function fallbackValue() { - return null; - } - return fallbackValue; -} - -const html$1 = freeze(['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'content', 'data', 'datalist', 'dd', 'decorator', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meter', 'nav', 'nobr', 'ol', 'optgroup', 'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'section', 'select', 'shadow', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr']); -const svg$1 = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']); -const svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feDropShadow', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']); -// List of SVG elements that are disallowed by default. -// We still need to know them so that we can do namespace -// checks properly in case one wants to add them to -// allow-list. -const svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignobject', 'hatch', 'hatchpath', 'mesh', 'meshgradient', 'meshpatch', 'meshrow', 'missing-glyph', 'script', 'set', 'solidcolor', 'unknown', 'use']); -const mathMl$1 = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover', 'mprescripts']); -// Similarly to SVG, we want to know all MathML elements, -// even those that we disallow by default. -const mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']); -const text = freeze(['#text']); - -const html = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'nonce', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'pattern', 'placeholder', 'playsinline', 'popover', 'popovertarget', 'popovertargetaction', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'wrap', 'xmlns', 'slot']); -const svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'amplitude', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dur', 'edgemode', 'elevation', 'end', 'exponent', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'intercept', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'slope', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'tablevalues', 'targetx', 'targety', 'transform', 'transform-origin', 'text-anchor', 'text-decoration', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']); -const mathMl = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnsalign', 'columnlines', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lspace', 'lquote', 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset', 'width', 'xmlns']); -const xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']); - -// eslint-disable-next-line unicorn/better-regex -const MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode -const ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm); -const TMPLIT_EXPR = seal(/\$\{[\w\W]*/gm); // eslint-disable-line unicorn/better-regex -const DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]+$/); // eslint-disable-line no-useless-escape -const ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape -const IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i // eslint-disable-line no-useless-escape -); -const IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i); -const ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex -); -const DOCTYPE_NAME = seal(/^html$/i); -const CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i); - -var EXPRESSIONS = /*#__PURE__*/Object.freeze({ - __proto__: null, - ARIA_ATTR: ARIA_ATTR, - ATTR_WHITESPACE: ATTR_WHITESPACE, - CUSTOM_ELEMENT: CUSTOM_ELEMENT, - DATA_ATTR: DATA_ATTR, - DOCTYPE_NAME: DOCTYPE_NAME, - ERB_EXPR: ERB_EXPR, - IS_ALLOWED_URI: IS_ALLOWED_URI, - IS_SCRIPT_OR_DATA: IS_SCRIPT_OR_DATA, - MUSTACHE_EXPR: MUSTACHE_EXPR, - TMPLIT_EXPR: TMPLIT_EXPR -}); - -/* eslint-disable @typescript-eslint/indent */ -// https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType -const NODE_TYPE = { - element: 1, - attribute: 2, - text: 3, - cdataSection: 4, - entityReference: 5, - // Deprecated - entityNode: 6, - // Deprecated - progressingInstruction: 7, - comment: 8, - document: 9, - documentType: 10, - documentFragment: 11, - notation: 12 // Deprecated -}; -const getGlobal = function getGlobal() { - return typeof window === 'undefined' ? null : window; -}; -/** - * Creates a no-op policy for internal use only. - * Don't export this function outside this module! - * @param trustedTypes The policy factory. - * @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix). - * @return The policy created (or null, if Trusted Types - * are not supported or creating the policy failed). - */ -const _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, purifyHostElement) { - if (typeof trustedTypes !== 'object' || typeof trustedTypes.createPolicy !== 'function') { - return null; - } - // Allow the callers to control the unique policy name - // by adding a data-tt-policy-suffix to the script element with the DOMPurify. - // Policy creation with duplicate names throws in Trusted Types. - let suffix = null; - const ATTR_NAME = 'data-tt-policy-suffix'; - if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) { - suffix = purifyHostElement.getAttribute(ATTR_NAME); - } - const policyName = 'dompurify' + (suffix ? '#' + suffix : ''); - try { - return trustedTypes.createPolicy(policyName, { - createHTML(html) { - return html; - }, - createScriptURL(scriptUrl) { - return scriptUrl; - } - }); - } catch (_) { - // Policy creation failed (most likely another DOMPurify script has - // already run). Skip creating the policy, as this will only cause errors - // if TT are enforced. - console.warn('TrustedTypes policy ' + policyName + ' could not be created.'); - return null; - } -}; -const _createHooksMap = function _createHooksMap() { - return { - afterSanitizeAttributes: [], - afterSanitizeElements: [], - afterSanitizeShadowDOM: [], - beforeSanitizeAttributes: [], - beforeSanitizeElements: [], - beforeSanitizeShadowDOM: [], - uponSanitizeAttribute: [], - uponSanitizeElement: [], - uponSanitizeShadowNode: [] - }; -}; -function createDOMPurify() { - let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal(); - const DOMPurify = root => createDOMPurify(root); - DOMPurify.version = '3.2.4'; - DOMPurify.removed = []; - if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) { - // Not running in a browser, provide a factory function - // so that you can pass your own Window - DOMPurify.isSupported = false; - return DOMPurify; - } - let { - document - } = window; - const originalDocument = document; - const currentScript = originalDocument.currentScript; - const { - DocumentFragment, - HTMLTemplateElement, - Node, - Element, - NodeFilter, - NamedNodeMap = window.NamedNodeMap || window.MozNamedAttrMap, - HTMLFormElement, - DOMParser, - trustedTypes - } = window; - const ElementPrototype = Element.prototype; - const cloneNode = lookupGetter(ElementPrototype, 'cloneNode'); - const remove = lookupGetter(ElementPrototype, 'remove'); - const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling'); - const getChildNodes = lookupGetter(ElementPrototype, 'childNodes'); - const getParentNode = lookupGetter(ElementPrototype, 'parentNode'); - // As per issue #47, the web-components registry is inherited by a - // new document created via createHTMLDocument. As per the spec - // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries) - // a new empty registry is used when creating a template contents owner - // document, so we use that as our parent document to ensure nothing - // is inherited. - if (typeof HTMLTemplateElement === 'function') { - const template = document.createElement('template'); - if (template.content && template.content.ownerDocument) { - document = template.content.ownerDocument; - } - } - let trustedTypesPolicy; - let emptyHTML = ''; - const { - implementation, - createNodeIterator, - createDocumentFragment, - getElementsByTagName - } = document; - const { - importNode - } = originalDocument; - let hooks = _createHooksMap(); - /** - * Expose whether this browser supports running the full DOMPurify. - */ - DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined; - const { - MUSTACHE_EXPR, - ERB_EXPR, - TMPLIT_EXPR, - DATA_ATTR, - ARIA_ATTR, - IS_SCRIPT_OR_DATA, - ATTR_WHITESPACE, - CUSTOM_ELEMENT - } = EXPRESSIONS; - let { - IS_ALLOWED_URI: IS_ALLOWED_URI$1 - } = EXPRESSIONS; - /** - * We consider the elements and attributes below to be safe. Ideally - * don't add any new ones but feel free to remove unwanted ones. - */ - /* allowed element names */ - let ALLOWED_TAGS = null; - const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]); - /* Allowed attribute names */ - let ALLOWED_ATTR = null; - const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]); - /* - * Configure how DOMPurify should handle custom elements and their attributes as well as customized built-in elements. - * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements) - * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list) - * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`. - */ - let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, { - tagNameCheck: { - writable: true, - configurable: false, - enumerable: true, - value: null - }, - attributeNameCheck: { - writable: true, - configurable: false, - enumerable: true, - value: null - }, - allowCustomizedBuiltInElements: { - writable: true, - configurable: false, - enumerable: true, - value: false - } - })); - /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */ - let FORBID_TAGS = null; - /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */ - let FORBID_ATTR = null; - /* Decide if ARIA attributes are okay */ - let ALLOW_ARIA_ATTR = true; - /* Decide if custom data attributes are okay */ - let ALLOW_DATA_ATTR = true; - /* Decide if unknown protocols are okay */ - let ALLOW_UNKNOWN_PROTOCOLS = false; - /* Decide if self-closing tags in attributes are allowed. - * Usually removed due to a mXSS issue in jQuery 3.0 */ - let ALLOW_SELF_CLOSE_IN_ATTR = true; - /* Output should be safe for common template engines. - * This means, DOMPurify removes data attributes, mustaches and ERB - */ - let SAFE_FOR_TEMPLATES = false; - /* Output should be safe even for XML used within HTML and alike. - * This means, DOMPurify removes comments when containing risky content. - */ - let SAFE_FOR_XML = true; - /* Decide if document with ... should be returned */ - let WHOLE_DOCUMENT = false; - /* Track whether config is already set on this instance of DOMPurify. */ - let SET_CONFIG = false; - /* Decide if all elements (e.g. style, script) must be children of - * document.body. By default, browsers might move them to document.head */ - let FORCE_BODY = false; - /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html - * string (or a TrustedHTML object if Trusted Types are supported). - * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead - */ - let RETURN_DOM = false; - /* Decide if a DOM `DocumentFragment` should be returned, instead of a html - * string (or a TrustedHTML object if Trusted Types are supported) */ - let RETURN_DOM_FRAGMENT = false; - /* Try to return a Trusted Type object instead of a string, return a string in - * case Trusted Types are not supported */ - let RETURN_TRUSTED_TYPE = false; - /* Output should be free from DOM clobbering attacks? - * This sanitizes markups named with colliding, clobberable built-in DOM APIs. - */ - let SANITIZE_DOM = true; - /* Achieve full DOM Clobbering protection by isolating the namespace of named - * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules. - * - * HTML/DOM spec rules that enable DOM Clobbering: - * - Named Access on Window (§7.3.3) - * - DOM Tree Accessors (§3.1.5) - * - Form Element Parent-Child Relations (§4.10.3) - * - Iframe srcdoc / Nested WindowProxies (§4.8.5) - * - HTMLCollection (§4.2.10.2) - * - * Namespace isolation is implemented by prefixing `id` and `name` attributes - * with a constant string, i.e., `user-content-` - */ - let SANITIZE_NAMED_PROPS = false; - const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-'; - /* Keep element content when removing element? */ - let KEEP_CONTENT = true; - /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead - * of importing it into a new Document and returning a sanitized copy */ - let IN_PLACE = false; - /* Allow usage of profiles like html, svg and mathMl */ - let USE_PROFILES = {}; - /* Tags to ignore content of when KEEP_CONTENT is true */ - let FORBID_CONTENTS = null; - const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']); - /* Tags that are safe for data: URIs */ - let DATA_URI_TAGS = null; - const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']); - /* Attributes safe for values like "javascript:" */ - let URI_SAFE_ATTRIBUTES = null; - const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']); - const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML'; - const SVG_NAMESPACE = 'http://www.w3.org/2000/svg'; - const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml'; - /* Document namespace */ - let NAMESPACE = HTML_NAMESPACE; - let IS_EMPTY_INPUT = false; - /* Allowed XHTML+XML namespaces */ - let ALLOWED_NAMESPACES = null; - const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString); - let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']); - let HTML_INTEGRATION_POINTS = addToSet({}, ['annotation-xml']); - // Certain elements are allowed in both SVG and HTML - // namespace. We need to specify them explicitly - // so that they don't get erroneously deleted from - // HTML namespace. - const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']); - /* Parsing of strict XHTML documents */ - let PARSER_MEDIA_TYPE = null; - const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html']; - const DEFAULT_PARSER_MEDIA_TYPE = 'text/html'; - let transformCaseFunc = null; - /* Keep a reference to config to pass to hooks */ - let CONFIG = null; - /* Ideally, do not touch anything below this line */ - /* ______________________________________________ */ - const formElement = document.createElement('form'); - const isRegexOrFunction = function isRegexOrFunction(testValue) { - return testValue instanceof RegExp || testValue instanceof Function; - }; - /** - * _parseConfig - * - * @param cfg optional config literal - */ - // eslint-disable-next-line complexity - const _parseConfig = function _parseConfig() { - let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - if (CONFIG && CONFIG === cfg) { - return; - } - /* Shield configuration object from tampering */ - if (!cfg || typeof cfg !== 'object') { - cfg = {}; - } - /* Shield configuration object from prototype pollution */ - cfg = clone(cfg); - PARSER_MEDIA_TYPE = - // eslint-disable-next-line unicorn/prefer-includes - SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE; - // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is. - transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase; - /* Set configuration parameters */ - ALLOWED_TAGS = objectHasOwnProperty(cfg, 'ALLOWED_TAGS') ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS; - ALLOWED_ATTR = objectHasOwnProperty(cfg, 'ALLOWED_ATTR') ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR; - ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, 'ALLOWED_NAMESPACES') ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES; - URI_SAFE_ATTRIBUTES = objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR, transformCaseFunc) : DEFAULT_URI_SAFE_ATTRIBUTES; - DATA_URI_TAGS = objectHasOwnProperty(cfg, 'ADD_DATA_URI_TAGS') ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS, transformCaseFunc) : DEFAULT_DATA_URI_TAGS; - FORBID_CONTENTS = objectHasOwnProperty(cfg, 'FORBID_CONTENTS') ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS; - FORBID_TAGS = objectHasOwnProperty(cfg, 'FORBID_TAGS') ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : {}; - FORBID_ATTR = objectHasOwnProperty(cfg, 'FORBID_ATTR') ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : {}; - USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES : false; - ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true - ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true - ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false - ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true - SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false - SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true - WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false - RETURN_DOM = cfg.RETURN_DOM || false; // Default false - RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false - RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false - FORCE_BODY = cfg.FORCE_BODY || false; // Default false - SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true - SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false - KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true - IN_PLACE = cfg.IN_PLACE || false; // Default false - IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI; - NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE; - MATHML_TEXT_INTEGRATION_POINTS = cfg.MATHML_TEXT_INTEGRATION_POINTS || MATHML_TEXT_INTEGRATION_POINTS; - HTML_INTEGRATION_POINTS = cfg.HTML_INTEGRATION_POINTS || HTML_INTEGRATION_POINTS; - CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || {}; - if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) { - CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck; - } - if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) { - CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck; - } - if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === 'boolean') { - CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements; - } - if (SAFE_FOR_TEMPLATES) { - ALLOW_DATA_ATTR = false; - } - if (RETURN_DOM_FRAGMENT) { - RETURN_DOM = true; - } - /* Parse profile info */ - if (USE_PROFILES) { - ALLOWED_TAGS = addToSet({}, text); - ALLOWED_ATTR = []; - if (USE_PROFILES.html === true) { - addToSet(ALLOWED_TAGS, html$1); - addToSet(ALLOWED_ATTR, html); - } - if (USE_PROFILES.svg === true) { - addToSet(ALLOWED_TAGS, svg$1); - addToSet(ALLOWED_ATTR, svg); - addToSet(ALLOWED_ATTR, xml); - } - if (USE_PROFILES.svgFilters === true) { - addToSet(ALLOWED_TAGS, svgFilters); - addToSet(ALLOWED_ATTR, svg); - addToSet(ALLOWED_ATTR, xml); - } - if (USE_PROFILES.mathMl === true) { - addToSet(ALLOWED_TAGS, mathMl$1); - addToSet(ALLOWED_ATTR, mathMl); - addToSet(ALLOWED_ATTR, xml); - } - } - /* Merge configuration parameters */ - if (cfg.ADD_TAGS) { - if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) { - ALLOWED_TAGS = clone(ALLOWED_TAGS); - } - addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc); - } - if (cfg.ADD_ATTR) { - if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) { - ALLOWED_ATTR = clone(ALLOWED_ATTR); - } - addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc); - } - if (cfg.ADD_URI_SAFE_ATTR) { - addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc); - } - if (cfg.FORBID_CONTENTS) { - if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) { - FORBID_CONTENTS = clone(FORBID_CONTENTS); - } - addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc); - } - /* Add #text in case KEEP_CONTENT is set to true */ - if (KEEP_CONTENT) { - ALLOWED_TAGS['#text'] = true; - } - /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */ - if (WHOLE_DOCUMENT) { - addToSet(ALLOWED_TAGS, ['html', 'head', 'body']); - } - /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */ - if (ALLOWED_TAGS.table) { - addToSet(ALLOWED_TAGS, ['tbody']); - delete FORBID_TAGS.tbody; - } - if (cfg.TRUSTED_TYPES_POLICY) { - if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') { - throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.'); - } - if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') { - throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.'); - } - // Overwrite existing TrustedTypes policy. - trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY; - // Sign local variables required by `sanitize`. - emptyHTML = trustedTypesPolicy.createHTML(''); - } else { - // Uninitialized policy, attempt to initialize the internal dompurify policy. - if (trustedTypesPolicy === undefined) { - trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript); - } - // If creating the internal policy succeeded sign internal variables. - if (trustedTypesPolicy !== null && typeof emptyHTML === 'string') { - emptyHTML = trustedTypesPolicy.createHTML(''); - } - } - // Prevent further manipulation of configuration. - // Not available in IE8, Safari 5, etc. - if (freeze) { - freeze(cfg); - } - CONFIG = cfg; - }; - /* Keep track of all possible SVG and MathML tags - * so that we can perform the namespace checks - * correctly. */ - const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]); - const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]); - /** - * @param element a DOM element whose namespace is being checked - * @returns Return false if the element has a - * namespace that a spec-compliant parser would never - * return. Return true otherwise. - */ - const _checkValidNamespace = function _checkValidNamespace(element) { - let parent = getParentNode(element); - // In JSDOM, if we're inside shadow DOM, then parentNode - // can be null. We just simulate parent in this case. - if (!parent || !parent.tagName) { - parent = { - namespaceURI: NAMESPACE, - tagName: 'template' - }; - } - const tagName = stringToLowerCase(element.tagName); - const parentTagName = stringToLowerCase(parent.tagName); - if (!ALLOWED_NAMESPACES[element.namespaceURI]) { - return false; - } - if (element.namespaceURI === SVG_NAMESPACE) { - // The only way to switch from HTML namespace to SVG - // is via . If it happens via any other tag, then - // it should be killed. - if (parent.namespaceURI === HTML_NAMESPACE) { - return tagName === 'svg'; - } - // The only way to switch from MathML to SVG is via` - // svg if parent is either or MathML - // text integration points. - if (parent.namespaceURI === MATHML_NAMESPACE) { - return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]); - } - // We only allow elements that are defined in SVG - // spec. All others are disallowed in SVG namespace. - return Boolean(ALL_SVG_TAGS[tagName]); - } - if (element.namespaceURI === MATHML_NAMESPACE) { - // The only way to switch from HTML namespace to MathML - // is via . If it happens via any other tag, then - // it should be killed. - if (parent.namespaceURI === HTML_NAMESPACE) { - return tagName === 'math'; - } - // The only way to switch from SVG to MathML is via - // and HTML integration points - if (parent.namespaceURI === SVG_NAMESPACE) { - return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName]; - } - // We only allow elements that are defined in MathML - // spec. All others are disallowed in MathML namespace. - return Boolean(ALL_MATHML_TAGS[tagName]); - } - if (element.namespaceURI === HTML_NAMESPACE) { - // The only way to switch from SVG to HTML is via - // HTML integration points, and from MathML to HTML - // is via MathML text integration points - if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) { - return false; - } - if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) { - return false; - } - // We disallow tags that are specific for MathML - // or SVG and should never appear in HTML namespace - return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]); - } - // For XHTML and XML documents that support custom namespaces - if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) { - return true; - } - // The code should never reach this place (this means - // that the element somehow got namespace that is not - // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES). - // Return false just in case. - return false; - }; - /** - * _forceRemove - * - * @param node a DOM node - */ - const _forceRemove = function _forceRemove(node) { - arrayPush(DOMPurify.removed, { - element: node - }); - try { - // eslint-disable-next-line unicorn/prefer-dom-node-remove - getParentNode(node).removeChild(node); - } catch (_) { - remove(node); - } - }; - /** - * _removeAttribute - * - * @param name an Attribute name - * @param element a DOM node - */ - const _removeAttribute = function _removeAttribute(name, element) { - try { - arrayPush(DOMPurify.removed, { - attribute: element.getAttributeNode(name), - from: element - }); - } catch (_) { - arrayPush(DOMPurify.removed, { - attribute: null, - from: element - }); - } - element.removeAttribute(name); - // We void attribute values for unremovable "is" attributes - if (name === 'is') { - if (RETURN_DOM || RETURN_DOM_FRAGMENT) { - try { - _forceRemove(element); - } catch (_) {} - } else { - try { - element.setAttribute(name, ''); - } catch (_) {} - } - } - }; - /** - * _initDocument - * - * @param dirty - a string of dirty markup - * @return a DOM, filled with the dirty markup - */ - const _initDocument = function _initDocument(dirty) { - /* Create a HTML document */ - let doc = null; - let leadingWhitespace = null; - if (FORCE_BODY) { - dirty = '' + dirty; - } else { - /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */ - const matches = stringMatch(dirty, /^[\r\n\t ]+/); - leadingWhitespace = matches && matches[0]; - } - if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) { - // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict) - dirty = '' + dirty + ''; - } - const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty; - /* - * Use the DOMParser API by default, fallback later if needs be - * DOMParser not work for svg when has multiple root element. - */ - if (NAMESPACE === HTML_NAMESPACE) { - try { - doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE); - } catch (_) {} - } - /* Use createHTMLDocument in case DOMParser is not available */ - if (!doc || !doc.documentElement) { - doc = implementation.createDocument(NAMESPACE, 'template', null); - try { - doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload; - } catch (_) { - // Syntax error if dirtyPayload is invalid xml - } - } - const body = doc.body || doc.documentElement; - if (dirty && leadingWhitespace) { - body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null); - } - /* Work on whole document or just its body */ - if (NAMESPACE === HTML_NAMESPACE) { - return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0]; - } - return WHOLE_DOCUMENT ? doc.documentElement : body; - }; - /** - * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. - * - * @param root The root element or node to start traversing on. - * @return The created NodeIterator - */ - const _createNodeIterator = function _createNodeIterator(root) { - return createNodeIterator.call(root.ownerDocument || root, root, - // eslint-disable-next-line no-bitwise - NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null); - }; - /** - * _isClobbered - * - * @param element element to check for clobbering attacks - * @return true if clobbered, false if safe - */ - const _isClobbered = function _isClobbered(element) { - return element instanceof HTMLFormElement && (typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' || !(element.attributes instanceof NamedNodeMap) || typeof element.removeAttribute !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function'); - }; - /** - * Checks whether the given object is a DOM node. - * - * @param value object to check whether it's a DOM node - * @return true is object is a DOM node - */ - const _isNode = function _isNode(value) { - return typeof Node === 'function' && value instanceof Node; - }; - function _executeHooks(hooks, currentNode, data) { - arrayForEach(hooks, hook => { - hook.call(DOMPurify, currentNode, data, CONFIG); - }); - } - /** - * _sanitizeElements - * - * @protect nodeName - * @protect textContent - * @protect removeChild - * @param currentNode to check for permission to exist - * @return true if node was killed, false if left alive - */ - const _sanitizeElements = function _sanitizeElements(currentNode) { - let content = null; - /* Execute a hook if present */ - _executeHooks(hooks.beforeSanitizeElements, currentNode, null); - /* Check if element is clobbered or can clobber */ - if (_isClobbered(currentNode)) { - _forceRemove(currentNode); - return true; - } - /* Now let's check the element's type and name */ - const tagName = transformCaseFunc(currentNode.nodeName); - /* Execute a hook if present */ - _executeHooks(hooks.uponSanitizeElement, currentNode, { - tagName, - allowedTags: ALLOWED_TAGS - }); - /* Detect mXSS attempts abusing namespace confusion */ - if (currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\w]/g, currentNode.innerHTML) && regExpTest(/<[/\w]/g, currentNode.textContent)) { - _forceRemove(currentNode); - return true; - } - /* Remove any occurrence of processing instructions */ - if (currentNode.nodeType === NODE_TYPE.progressingInstruction) { - _forceRemove(currentNode); - return true; - } - /* Remove any kind of possibly harmful comments */ - if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(/<[/\w]/g, currentNode.data)) { - _forceRemove(currentNode); - return true; - } - /* Remove element if anything forbids its presence */ - if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) { - /* Check if we have a custom element to handle */ - if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) { - if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) { - return false; - } - if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) { - return false; - } - } - /* Keep content except for bad-listed elements */ - if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) { - const parentNode = getParentNode(currentNode) || currentNode.parentNode; - const childNodes = getChildNodes(currentNode) || currentNode.childNodes; - if (childNodes && parentNode) { - const childCount = childNodes.length; - for (let i = childCount - 1; i >= 0; --i) { - const childClone = cloneNode(childNodes[i], true); - childClone.__removalCount = (currentNode.__removalCount || 0) + 1; - parentNode.insertBefore(childClone, getNextSibling(currentNode)); - } - } - } - _forceRemove(currentNode); - return true; - } - /* Check whether element has a valid namespace */ - if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) { - _forceRemove(currentNode); - return true; - } - /* Make sure that older browsers don't get fallback-tag mXSS */ - if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)) { - _forceRemove(currentNode); - return true; - } - /* Sanitize element content to be template-safe */ - if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) { - /* Get the element's text content */ - content = currentNode.textContent; - arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => { - content = stringReplace(content, expr, ' '); - }); - if (currentNode.textContent !== content) { - arrayPush(DOMPurify.removed, { - element: currentNode.cloneNode() - }); - currentNode.textContent = content; - } - } - /* Execute a hook if present */ - _executeHooks(hooks.afterSanitizeElements, currentNode, null); - return false; - }; - /** - * _isValidAttribute - * - * @param lcTag Lowercase tag name of containing element. - * @param lcName Lowercase attribute name. - * @param value Attribute value. - * @return Returns true if `value` is valid, otherwise false. - */ - // eslint-disable-next-line complexity - const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) { - /* Make sure attribute cannot clobber */ - if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) { - return false; - } - /* Allow valid data-* attributes: At least one character after "-" - (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes) - XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804) - We don't need to check the value; it's always URI safe. */ - if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR, lcName)) ; else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) { - if ( - // First condition does a very basic check if a) it's basically a valid custom element tagname AND - // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck - // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck - _isBasicCustomElement(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName)) || - // Alternative, second condition checks if it's an `is`-attribute, AND - // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck - lcName === 'is' && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))) ; else { - return false; - } - /* Check value is safe. First, is attr inert? If so, is safe */ - } else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) ; else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if (value) { - return false; - } else ; - return true; - }; - /** - * _isBasicCustomElement - * checks if at least one dash is included in tagName, and it's not the first char - * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name - * - * @param tagName name of the tag of the node to sanitize - * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false. - */ - const _isBasicCustomElement = function _isBasicCustomElement(tagName) { - return tagName !== 'annotation-xml' && stringMatch(tagName, CUSTOM_ELEMENT); - }; - /** - * _sanitizeAttributes - * - * @protect attributes - * @protect nodeName - * @protect removeAttribute - * @protect setAttribute - * - * @param currentNode to sanitize - */ - const _sanitizeAttributes = function _sanitizeAttributes(currentNode) { - /* Execute a hook if present */ - _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null); - const { - attributes - } = currentNode; - /* Check if we have attributes; if not we might have a text node */ - if (!attributes || _isClobbered(currentNode)) { - return; - } - const hookEvent = { - attrName: '', - attrValue: '', - keepAttr: true, - allowedAttributes: ALLOWED_ATTR, - forceKeepAttr: undefined - }; - let l = attributes.length; - /* Go backwards over all attributes; safely remove bad ones */ - while (l--) { - const attr = attributes[l]; - const { - name, - namespaceURI, - value: attrValue - } = attr; - const lcName = transformCaseFunc(name); - let value = name === 'value' ? attrValue : stringTrim(attrValue); - /* Execute a hook if present */ - hookEvent.attrName = lcName; - hookEvent.attrValue = value; - hookEvent.keepAttr = true; - hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set - _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent); - value = hookEvent.attrValue; - /* Full DOM Clobbering protection via namespace isolation, - * Prefix id and name attributes with `user-content-` - */ - if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name')) { - // Remove the attribute with this value - _removeAttribute(name, currentNode); - // Prefix the value and later re-create the attribute with the sanitized value - value = SANITIZE_NAMED_PROPS_PREFIX + value; - } - /* Work around a security issue with comments inside attributes */ - if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|title)/i, value)) { - _removeAttribute(name, currentNode); - continue; - } - /* Did the hooks approve of the attribute? */ - if (hookEvent.forceKeepAttr) { - continue; - } - /* Remove attribute */ - _removeAttribute(name, currentNode); - /* Did the hooks approve of the attribute? */ - if (!hookEvent.keepAttr) { - continue; - } - /* Work around a security issue in jQuery 3.0 */ - if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) { - _removeAttribute(name, currentNode); - continue; - } - /* Sanitize attribute content to be template-safe */ - if (SAFE_FOR_TEMPLATES) { - arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => { - value = stringReplace(value, expr, ' '); - }); - } - /* Is `value` valid for this attribute? */ - const lcTag = transformCaseFunc(currentNode.nodeName); - if (!_isValidAttribute(lcTag, lcName, value)) { - continue; - } - /* Handle attributes that require Trusted Types */ - if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function') { - if (namespaceURI) ; else { - switch (trustedTypes.getAttributeType(lcTag, lcName)) { - case 'TrustedHTML': - { - value = trustedTypesPolicy.createHTML(value); - break; - } - case 'TrustedScriptURL': - { - value = trustedTypesPolicy.createScriptURL(value); - break; - } - } - } - } - /* Handle invalid data-* attribute set by try-catching it */ - try { - if (namespaceURI) { - currentNode.setAttributeNS(namespaceURI, name, value); - } else { - /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */ - currentNode.setAttribute(name, value); - } - if (_isClobbered(currentNode)) { - _forceRemove(currentNode); - } else { - arrayPop(DOMPurify.removed); - } - } catch (_) {} - } - /* Execute a hook if present */ - _executeHooks(hooks.afterSanitizeAttributes, currentNode, null); - }; - /** - * _sanitizeShadowDOM - * - * @param fragment to iterate over recursively - */ - const _sanitizeShadowDOM = function _sanitizeShadowDOM(fragment) { - let shadowNode = null; - const shadowIterator = _createNodeIterator(fragment); - /* Execute a hook if present */ - _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null); - while (shadowNode = shadowIterator.nextNode()) { - /* Execute a hook if present */ - _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null); - /* Sanitize tags and elements */ - _sanitizeElements(shadowNode); - /* Check attributes next */ - _sanitizeAttributes(shadowNode); - /* Deep shadow DOM detected */ - if (shadowNode.content instanceof DocumentFragment) { - _sanitizeShadowDOM(shadowNode.content); - } - } - /* Execute a hook if present */ - _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null); - }; - // eslint-disable-next-line complexity - DOMPurify.sanitize = function (dirty) { - let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - let body = null; - let importedNode = null; - let currentNode = null; - let returnNode = null; - /* Make sure we have a string to sanitize. - DO NOT return early, as this will return the wrong type if - the user has requested a DOM object rather than a string */ - IS_EMPTY_INPUT = !dirty; - if (IS_EMPTY_INPUT) { - dirty = ''; - } - /* Stringify, in case dirty is an object */ - if (typeof dirty !== 'string' && !_isNode(dirty)) { - if (typeof dirty.toString === 'function') { - dirty = dirty.toString(); - if (typeof dirty !== 'string') { - throw typeErrorCreate('dirty is not a string, aborting'); - } - } else { - throw typeErrorCreate('toString is not a function'); - } - } - /* Return dirty HTML if DOMPurify cannot run */ - if (!DOMPurify.isSupported) { - return dirty; - } - /* Assign config vars */ - if (!SET_CONFIG) { - _parseConfig(cfg); - } - /* Clean up removed elements */ - DOMPurify.removed = []; - /* Check if dirty is correctly typed for IN_PLACE */ - if (typeof dirty === 'string') { - IN_PLACE = false; - } - if (IN_PLACE) { - /* Do some early pre-sanitization to avoid unsafe root nodes */ - if (dirty.nodeName) { - const tagName = transformCaseFunc(dirty.nodeName); - if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) { - throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place'); - } - } - } else if (dirty instanceof Node) { - /* If dirty is a DOM element, append to an empty document to avoid - elements being stripped by the parser */ - body = _initDocument(''); - importedNode = body.ownerDocument.importNode(dirty, true); - if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === 'BODY') { - /* Node is already a body, use as is */ - body = importedNode; - } else if (importedNode.nodeName === 'HTML') { - body = importedNode; - } else { - // eslint-disable-next-line unicorn/prefer-dom-node-append - body.appendChild(importedNode); - } - } else { - /* Exit directly if we have nothing to do */ - if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT && - // eslint-disable-next-line unicorn/prefer-includes - dirty.indexOf('<') === -1) { - return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty; - } - /* Initialize the document to work on */ - body = _initDocument(dirty); - /* Check we have a DOM node from the data */ - if (!body) { - return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : ''; - } - } - /* Remove first element node (ours) if FORCE_BODY is set */ - if (body && FORCE_BODY) { - _forceRemove(body.firstChild); - } - /* Get node iterator */ - const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body); - /* Now start iterating over the created document */ - while (currentNode = nodeIterator.nextNode()) { - /* Sanitize tags and elements */ - _sanitizeElements(currentNode); - /* Check attributes next */ - _sanitizeAttributes(currentNode); - /* Shadow DOM detected, sanitize it */ - if (currentNode.content instanceof DocumentFragment) { - _sanitizeShadowDOM(currentNode.content); - } - } - /* If we sanitized `dirty` in-place, return it. */ - if (IN_PLACE) { - return dirty; - } - /* Return sanitized string or DOM */ - if (RETURN_DOM) { - if (RETURN_DOM_FRAGMENT) { - returnNode = createDocumentFragment.call(body.ownerDocument); - while (body.firstChild) { - // eslint-disable-next-line unicorn/prefer-dom-node-append - returnNode.appendChild(body.firstChild); - } - } else { - returnNode = body; - } - if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) { - /* - AdoptNode() is not used because internal state is not reset - (e.g. the past names map of a HTMLFormElement), this is safe - in theory but we would rather not risk another attack vector. - The state that is cloned by importNode() is explicitly defined - by the specs. - */ - returnNode = importNode.call(originalDocument, returnNode, true); - } - return returnNode; - } - let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML; - /* Serialize doctype if allowed */ - if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) { - serializedHTML = '\n' + serializedHTML; - } - /* Sanitize final string template-safe */ - if (SAFE_FOR_TEMPLATES) { - arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => { - serializedHTML = stringReplace(serializedHTML, expr, ' '); - }); - } - return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML; - }; - DOMPurify.setConfig = function () { - let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - _parseConfig(cfg); - SET_CONFIG = true; - }; - DOMPurify.clearConfig = function () { - CONFIG = null; - SET_CONFIG = false; - }; - DOMPurify.isValidAttribute = function (tag, attr, value) { - /* Initialize shared config vars if necessary. */ - if (!CONFIG) { - _parseConfig({}); - } - const lcTag = transformCaseFunc(tag); - const lcName = transformCaseFunc(attr); - return _isValidAttribute(lcTag, lcName, value); - }; - DOMPurify.addHook = function (entryPoint, hookFunction) { - if (typeof hookFunction !== 'function') { - return; - } - arrayPush(hooks[entryPoint], hookFunction); - }; - DOMPurify.removeHook = function (entryPoint, hookFunction) { - if (hookFunction !== undefined) { - const index = arrayLastIndexOf(hooks[entryPoint], hookFunction); - return index === -1 ? undefined : arraySplice(hooks[entryPoint], index, 1)[0]; - } - return arrayPop(hooks[entryPoint]); - }; - DOMPurify.removeHooks = function (entryPoint) { - hooks[entryPoint] = []; - }; - DOMPurify.removeAllHooks = function () { - hooks = _createHooksMap(); - }; - return DOMPurify; -} -var purify = createDOMPurify(); - -export { purify as default }; -//# sourceMappingURL=purify.es.mjs.map diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/markdown_viewer/viewer.html b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/markdown_viewer/viewer.html deleted file mode 100644 index 94447ffc47e..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/markdown_viewer/viewer.html +++ /dev/null @@ -1,32 +0,0 @@ - - - - - Markdown viewer - - - - -

    - - - diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/markdown_viewer/viewer.mjs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/markdown_viewer/viewer.mjs deleted file mode 100644 index 78eb819c9a8..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/markdown_viewer/viewer.mjs +++ /dev/null @@ -1,13 +0,0 @@ -import { parse } from '../marked/dist/marked.esm.js'; -import purify from '../dompurify/dist/purify.es.mjs'; - -const url = new URL(window.location); -const fileUrl = url.searchParams.get('file'); -if (!fileUrl) { - throw new Error('File not specified in the URL query string'); -} - -var response = await fetch(fileUrl); -var text = await response.text(); - -document.getElementById('content').innerHTML = purify.sanitize(parse(text)); diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/marked/README.md b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/marked/README.md deleted file mode 100644 index 352b52d5503..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/marked/README.md +++ /dev/null @@ -1,5 +0,0 @@ -marked version 15.0.6 -https://github.com/markedjs/marked -License: MIT - -To update, replace the `dist/marked.esm.js` file with with an updated version from https://www.npmjs.com/package/marked. diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/marked/dist/marked.esm.js b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/marked/dist/marked.esm.js deleted file mode 100644 index a32cd778363..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/marked/dist/marked.esm.js +++ /dev/null @@ -1,2568 +0,0 @@ -/** - * marked v15.0.6 - a markdown parser - * Copyright (c) 2011-2025, Christopher Jeffrey. (MIT Licensed) - * https://github.com/markedjs/marked - */ - -/** - * DO NOT EDIT THIS FILE - * The code in this file is generated from files in ./src/ - */ - -/** - * Gets the original marked default options. - */ -function _getDefaults() { - return { - async: false, - breaks: false, - extensions: null, - gfm: true, - hooks: null, - pedantic: false, - renderer: null, - silent: false, - tokenizer: null, - walkTokens: null, - }; -} -let _defaults = _getDefaults(); -function changeDefaults(newDefaults) { - _defaults = newDefaults; -} - -const noopTest = { exec: () => null }; -function edit(regex, opt = '') { - let source = typeof regex === 'string' ? regex : regex.source; - const obj = { - replace: (name, val) => { - let valSource = typeof val === 'string' ? val : val.source; - valSource = valSource.replace(other.caret, '$1'); - source = source.replace(name, valSource); - return obj; - }, - getRegex: () => { - return new RegExp(source, opt); - }, - }; - return obj; -} -const other = { - codeRemoveIndent: /^(?: {1,4}| {0,3}\t)/gm, - outputLinkReplace: /\\([\[\]])/g, - indentCodeCompensation: /^(\s+)(?:```)/, - beginningSpace: /^\s+/, - endingHash: /#$/, - startingSpaceChar: /^ /, - endingSpaceChar: / $/, - nonSpaceChar: /[^ ]/, - newLineCharGlobal: /\n/g, - tabCharGlobal: /\t/g, - multipleSpaceGlobal: /\s+/g, - blankLine: /^[ \t]*$/, - doubleBlankLine: /\n[ \t]*\n[ \t]*$/, - blockquoteStart: /^ {0,3}>/, - blockquoteSetextReplace: /\n {0,3}((?:=+|-+) *)(?=\n|$)/g, - blockquoteSetextReplace2: /^ {0,3}>[ \t]?/gm, - listReplaceTabs: /^\t+/, - listReplaceNesting: /^ {1,4}(?=( {4})*[^ ])/g, - listIsTask: /^\[[ xX]\] /, - listReplaceTask: /^\[[ xX]\] +/, - anyLine: /\n.*\n/, - hrefBrackets: /^<(.*)>$/, - tableDelimiter: /[:|]/, - tableAlignChars: /^\||\| *$/g, - tableRowBlankLine: /\n[ \t]*$/, - tableAlignRight: /^ *-+: *$/, - tableAlignCenter: /^ *:-+: *$/, - tableAlignLeft: /^ *:-+ *$/, - startATag: /^
    /i, - startPreScriptTag: /^<(pre|code|kbd|script)(\s|>)/i, - endPreScriptTag: /^<\/(pre|code|kbd|script)(\s|>)/i, - startAngleBracket: /^$/, - pedanticHrefTitle: /^([^'"]*[^\s])\s+(['"])(.*)\2/, - unicodeAlphaNumeric: /[\p{L}\p{N}]/u, - escapeTest: /[&<>"']/, - escapeReplace: /[&<>"']/g, - escapeTestNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/, - escapeReplaceNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g, - unescapeTest: /&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig, - caret: /(^|[^\[])\^/g, - percentDecode: /%25/g, - findPipe: /\|/g, - splitPipe: / \|/, - slashPipe: /\\\|/g, - carriageReturn: /\r\n|\r/g, - spaceLine: /^ +$/gm, - notSpaceStart: /^\S*/, - endingNewline: /\n$/, - listItemRegex: (bull) => new RegExp(`^( {0,3}${bull})((?:[\t ][^\\n]*)?(?:\\n|$))`), - nextBulletRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ \t][^\\n]*)?(?:\\n|$))`), - hrRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`), - fencesBeginRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\`\`\`|~~~)`), - headingBeginRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`), - htmlBeginRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}<(?:[a-z].*>|!--)`, 'i'), -}; -/** - * Block-Level Grammar - */ -const newline = /^(?:[ \t]*(?:\n|$))+/; -const blockCode = /^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/; -const fences = /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/; -const hr = /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/; -const heading = /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/; -const bullet = /(?:[*+-]|\d{1,9}[.)])/; -const lheading = edit(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/) - .replace(/bull/g, bullet) // lists can interrupt - .replace(/blockCode/g, /(?: {4}| {0,3}\t)/) // indented code blocks can interrupt - .replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/) // fenced code blocks can interrupt - .replace(/blockquote/g, / {0,3}>/) // blockquote can interrupt - .replace(/heading/g, / {0,3}#{1,6}/) // ATX heading can interrupt - .replace(/html/g, / {0,3}<[^\n>]+>\n/) // block html can interrupt - .getRegex(); -const _paragraph = /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/; -const blockText = /^[^\n]+/; -const _blockLabel = /(?!\s*\])(?:\\.|[^\[\]\\])+/; -const def = edit(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/) - .replace('label', _blockLabel) - .replace('title', /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/) - .getRegex(); -const list = edit(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/) - .replace(/bull/g, bullet) - .getRegex(); -const _tag = 'address|article|aside|base|basefont|blockquote|body|caption' - + '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption' - + '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe' - + '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option' - + '|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title' - + '|tr|track|ul'; -const _comment = /|$))/; -const html = edit('^ {0,3}(?:' // optional indentation - + '<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)' // (1) - + '|comment[^\\n]*(\\n+|$)' // (2) - + '|<\\?[\\s\\S]*?(?:\\?>\\n*|$)' // (3) - + '|\\n*|$)' // (4) - + '|\\n*|$)' // (5) - + '|)[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)' // (6) - + '|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)' // (7) open tag - + '|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)' // (7) closing tag - + ')', 'i') - .replace('comment', _comment) - .replace('tag', _tag) - .replace('attribute', / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/) - .getRegex(); -const paragraph = edit(_paragraph) - .replace('hr', hr) - .replace('heading', ' {0,3}#{1,6}(?:\\s|$)') - .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs - .replace('|table', '') - .replace('blockquote', ' {0,3}>') - .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n') - .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt - .replace('html', ')|<(?:script|pre|style|textarea|!--)') - .replace('tag', _tag) // pars can be interrupted by type (6) html blocks - .getRegex(); -const blockquote = edit(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/) - .replace('paragraph', paragraph) - .getRegex(); -/** - * Normal Block Grammar - */ -const blockNormal = { - blockquote, - code: blockCode, - def, - fences, - heading, - hr, - html, - lheading, - list, - newline, - paragraph, - table: noopTest, - text: blockText, -}; -/** - * GFM Block Grammar - */ -const gfmTable = edit('^ *([^\\n ].*)\\n' // Header - + ' {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)' // Align - + '(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)') // Cells - .replace('hr', hr) - .replace('heading', ' {0,3}#{1,6}(?:\\s|$)') - .replace('blockquote', ' {0,3}>') - .replace('code', '(?: {4}| {0,3}\t)[^\\n]') - .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n') - .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt - .replace('html', ')|<(?:script|pre|style|textarea|!--)') - .replace('tag', _tag) // tables can be interrupted by type (6) html blocks - .getRegex(); -const blockGfm = { - ...blockNormal, - table: gfmTable, - paragraph: edit(_paragraph) - .replace('hr', hr) - .replace('heading', ' {0,3}#{1,6}(?:\\s|$)') - .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs - .replace('table', gfmTable) // interrupt paragraphs with table - .replace('blockquote', ' {0,3}>') - .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n') - .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt - .replace('html', ')|<(?:script|pre|style|textarea|!--)') - .replace('tag', _tag) // pars can be interrupted by type (6) html blocks - .getRegex(), -}; -/** - * Pedantic grammar (original John Gruber's loose markdown specification) - */ -const blockPedantic = { - ...blockNormal, - html: edit('^ *(?:comment *(?:\\n|\\s*$)' - + '|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)' // closed tag - + '|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))') - .replace('comment', _comment) - .replace(/tag/g, '(?!(?:' - + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub' - + '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)' - + '\\b)\\w+(?!:|[^\\w\\s@]*@)\\b') - .getRegex(), - def: /^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/, - heading: /^(#{1,6})(.*)(?:\n+|$)/, - fences: noopTest, // fences not supported - lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/, - paragraph: edit(_paragraph) - .replace('hr', hr) - .replace('heading', ' *#{1,6} *[^\n]') - .replace('lheading', lheading) - .replace('|table', '') - .replace('blockquote', ' {0,3}>') - .replace('|fences', '') - .replace('|list', '') - .replace('|html', '') - .replace('|tag', '') - .getRegex(), -}; -/** - * Inline-Level Grammar - */ -const escape$1 = /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/; -const inlineCode = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/; -const br = /^( {2,}|\\)\n(?!\s*$)/; -const inlineText = /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\ -const blockSkip = /\[[^[\]]*?\]\((?:\\.|[^\\\(\)]|\((?:\\.|[^\\\(\)])*\))*\)|`[^`]*?`|<[^<>]*?>/g; -const emStrongLDelimCore = /^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/; -const emStrongLDelim = edit(emStrongLDelimCore, 'u') - .replace(/punct/g, _punctuation) - .getRegex(); -const emStrongLDelimGfm = edit(emStrongLDelimCore, 'u') - .replace(/punct/g, _punctuationGfmStrongEm) - .getRegex(); -const emStrongRDelimAstCore = '^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)' // Skip orphan inside strong - + '|[^*]+(?=[^*])' // Consume to delim - + '|(?!\\*)punct(\\*+)(?=[\\s]|$)' // (1) #*** can only be a Right Delimiter - + '|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)' // (2) a***#, a*** can only be a Right Delimiter - + '|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)' // (3) #***a, ***a can only be Left Delimiter - + '|[\\s](\\*+)(?!\\*)(?=punct)' // (4) ***# can only be Left Delimiter - + '|(?!\\*)punct(\\*+)(?!\\*)(?=punct)' // (5) #***# can be either Left or Right Delimiter - + '|notPunctSpace(\\*+)(?=notPunctSpace)'; // (6) a***a can be either Left or Right Delimiter -const emStrongRDelimAst = edit(emStrongRDelimAstCore, 'gu') - .replace(/notPunctSpace/g, _notPunctuationOrSpace) - .replace(/punctSpace/g, _punctuationOrSpace) - .replace(/punct/g, _punctuation) - .getRegex(); -const emStrongRDelimAstGfm = edit(emStrongRDelimAstCore, 'gu') - .replace(/notPunctSpace/g, _notPunctuationOrSpaceGfmStrongEm) - .replace(/punctSpace/g, _punctuationOrSpaceGfmStrongEm) - .replace(/punct/g, _punctuationGfmStrongEm) - .getRegex(); -// (6) Not allowed for _ -const emStrongRDelimUnd = edit('^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)' // Skip orphan inside strong - + '|[^_]+(?=[^_])' // Consume to delim - + '|(?!_)punct(_+)(?=[\\s]|$)' // (1) #___ can only be a Right Delimiter - + '|notPunctSpace(_+)(?!_)(?=punctSpace|$)' // (2) a___#, a___ can only be a Right Delimiter - + '|(?!_)punctSpace(_+)(?=notPunctSpace)' // (3) #___a, ___a can only be Left Delimiter - + '|[\\s](_+)(?!_)(?=punct)' // (4) ___# can only be Left Delimiter - + '|(?!_)punct(_+)(?!_)(?=punct)', 'gu') // (5) #___# can be either Left or Right Delimiter - .replace(/notPunctSpace/g, _notPunctuationOrSpace) - .replace(/punctSpace/g, _punctuationOrSpace) - .replace(/punct/g, _punctuation) - .getRegex(); -const anyPunctuation = edit(/\\(punct)/, 'gu') - .replace(/punct/g, _punctuation) - .getRegex(); -const autolink = edit(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/) - .replace('scheme', /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/) - .replace('email', /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/) - .getRegex(); -const _inlineComment = edit(_comment).replace('(?:-->|$)', '-->').getRegex(); -const tag = edit('^comment' - + '|^' // self-closing tag - + '|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>' // open tag - + '|^<\\?[\\s\\S]*?\\?>' // processing instruction, e.g. - + '|^' // declaration, e.g. - + '|^') // CDATA section - .replace('comment', _inlineComment) - .replace('attribute', /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/) - .getRegex(); -const _inlineLabel = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/; -const link = edit(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/) - .replace('label', _inlineLabel) - .replace('href', /<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/) - .replace('title', /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/) - .getRegex(); -const reflink = edit(/^!?\[(label)\]\[(ref)\]/) - .replace('label', _inlineLabel) - .replace('ref', _blockLabel) - .getRegex(); -const nolink = edit(/^!?\[(ref)\](?:\[\])?/) - .replace('ref', _blockLabel) - .getRegex(); -const reflinkSearch = edit('reflink|nolink(?!\\()', 'g') - .replace('reflink', reflink) - .replace('nolink', nolink) - .getRegex(); -/** - * Normal Inline Grammar - */ -const inlineNormal = { - _backpedal: noopTest, // only used for GFM url - anyPunctuation, - autolink, - blockSkip, - br, - code: inlineCode, - del: noopTest, - emStrongLDelim, - emStrongRDelimAst, - emStrongRDelimUnd, - escape: escape$1, - link, - nolink, - punctuation, - reflink, - reflinkSearch, - tag, - text: inlineText, - url: noopTest, -}; -/** - * Pedantic Inline Grammar - */ -const inlinePedantic = { - ...inlineNormal, - link: edit(/^!?\[(label)\]\((.*?)\)/) - .replace('label', _inlineLabel) - .getRegex(), - reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/) - .replace('label', _inlineLabel) - .getRegex(), -}; -/** - * GFM Inline Grammar - */ -const inlineGfm = { - ...inlineNormal, - emStrongRDelimAst: emStrongRDelimAstGfm, - emStrongLDelim: emStrongLDelimGfm, - url: edit(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/, 'i') - .replace('email', /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/) - .getRegex(), - _backpedal: /(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/, - del: /^(~~?)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/, - text: /^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\': '>', - '"': '"', - "'": ''', -}; -const getEscapeReplacement = (ch) => escapeReplacements[ch]; -function escape(html, encode) { - if (encode) { - if (other.escapeTest.test(html)) { - return html.replace(other.escapeReplace, getEscapeReplacement); - } - } - else { - if (other.escapeTestNoEncode.test(html)) { - return html.replace(other.escapeReplaceNoEncode, getEscapeReplacement); - } - } - return html; -} -function cleanUrl(href) { - try { - href = encodeURI(href).replace(other.percentDecode, '%'); - } - catch { - return null; - } - return href; -} -function splitCells(tableRow, count) { - // ensure that every cell-delimiting pipe has a space - // before it to distinguish it from an escaped pipe - const row = tableRow.replace(other.findPipe, (match, offset, str) => { - let escaped = false; - let curr = offset; - while (--curr >= 0 && str[curr] === '\\') - escaped = !escaped; - if (escaped) { - // odd number of slashes means | is escaped - // so we leave it alone - return '|'; - } - else { - // add space before unescaped | - return ' |'; - } - }), cells = row.split(other.splitPipe); - let i = 0; - // First/last cell in a row cannot be empty if it has no leading/trailing pipe - if (!cells[0].trim()) { - cells.shift(); - } - if (cells.length > 0 && !cells.at(-1)?.trim()) { - cells.pop(); - } - if (count) { - if (cells.length > count) { - cells.splice(count); - } - else { - while (cells.length < count) - cells.push(''); - } - } - for (; i < cells.length; i++) { - // leading or trailing whitespace is ignored per the gfm spec - cells[i] = cells[i].trim().replace(other.slashPipe, '|'); - } - return cells; -} -/** - * Remove trailing 'c's. Equivalent to str.replace(/c*$/, ''). - * /c*$/ is vulnerable to REDOS. - * - * @param str - * @param c - * @param invert Remove suffix of non-c chars instead. Default falsey. - */ -function rtrim(str, c, invert) { - const l = str.length; - if (l === 0) { - return ''; - } - // Length of suffix matching the invert condition. - let suffLen = 0; - // Step left until we fail to match the invert condition. - while (suffLen < l) { - const currChar = str.charAt(l - suffLen - 1); - if (currChar === c && true) { - suffLen++; - } - else { - break; - } - } - return str.slice(0, l - suffLen); -} -function findClosingBracket(str, b) { - if (str.indexOf(b[1]) === -1) { - return -1; - } - let level = 0; - for (let i = 0; i < str.length; i++) { - if (str[i] === '\\') { - i++; - } - else if (str[i] === b[0]) { - level++; - } - else if (str[i] === b[1]) { - level--; - if (level < 0) { - return i; - } - } - } - return -1; -} - -function outputLink(cap, link, raw, lexer, rules) { - const href = link.href; - const title = link.title || null; - const text = cap[1].replace(rules.other.outputLinkReplace, '$1'); - if (cap[0].charAt(0) !== '!') { - lexer.state.inLink = true; - const token = { - type: 'link', - raw, - href, - title, - text, - tokens: lexer.inlineTokens(text), - }; - lexer.state.inLink = false; - return token; - } - return { - type: 'image', - raw, - href, - title, - text, - }; -} -function indentCodeCompensation(raw, text, rules) { - const matchIndentToCode = raw.match(rules.other.indentCodeCompensation); - if (matchIndentToCode === null) { - return text; - } - const indentToCode = matchIndentToCode[1]; - return text - .split('\n') - .map(node => { - const matchIndentInNode = node.match(rules.other.beginningSpace); - if (matchIndentInNode === null) { - return node; - } - const [indentInNode] = matchIndentInNode; - if (indentInNode.length >= indentToCode.length) { - return node.slice(indentToCode.length); - } - return node; - }) - .join('\n'); -} -/** - * Tokenizer - */ -class _Tokenizer { - options; - rules; // set by the lexer - lexer; // set by the lexer - constructor(options) { - this.options = options || _defaults; - } - space(src) { - const cap = this.rules.block.newline.exec(src); - if (cap && cap[0].length > 0) { - return { - type: 'space', - raw: cap[0], - }; - } - } - code(src) { - const cap = this.rules.block.code.exec(src); - if (cap) { - const text = cap[0].replace(this.rules.other.codeRemoveIndent, ''); - return { - type: 'code', - raw: cap[0], - codeBlockStyle: 'indented', - text: !this.options.pedantic - ? rtrim(text, '\n') - : text, - }; - } - } - fences(src) { - const cap = this.rules.block.fences.exec(src); - if (cap) { - const raw = cap[0]; - const text = indentCodeCompensation(raw, cap[3] || '', this.rules); - return { - type: 'code', - raw, - lang: cap[2] ? cap[2].trim().replace(this.rules.inline.anyPunctuation, '$1') : cap[2], - text, - }; - } - } - heading(src) { - const cap = this.rules.block.heading.exec(src); - if (cap) { - let text = cap[2].trim(); - // remove trailing #s - if (this.rules.other.endingHash.test(text)) { - const trimmed = rtrim(text, '#'); - if (this.options.pedantic) { - text = trimmed.trim(); - } - else if (!trimmed || this.rules.other.endingSpaceChar.test(trimmed)) { - // CommonMark requires space before trailing #s - text = trimmed.trim(); - } - } - return { - type: 'heading', - raw: cap[0], - depth: cap[1].length, - text, - tokens: this.lexer.inline(text), - }; - } - } - hr(src) { - const cap = this.rules.block.hr.exec(src); - if (cap) { - return { - type: 'hr', - raw: rtrim(cap[0], '\n'), - }; - } - } - blockquote(src) { - const cap = this.rules.block.blockquote.exec(src); - if (cap) { - let lines = rtrim(cap[0], '\n').split('\n'); - let raw = ''; - let text = ''; - const tokens = []; - while (lines.length > 0) { - let inBlockquote = false; - const currentLines = []; - let i; - for (i = 0; i < lines.length; i++) { - // get lines up to a continuation - if (this.rules.other.blockquoteStart.test(lines[i])) { - currentLines.push(lines[i]); - inBlockquote = true; - } - else if (!inBlockquote) { - currentLines.push(lines[i]); - } - else { - break; - } - } - lines = lines.slice(i); - const currentRaw = currentLines.join('\n'); - const currentText = currentRaw - // precede setext continuation with 4 spaces so it isn't a setext - .replace(this.rules.other.blockquoteSetextReplace, '\n $1') - .replace(this.rules.other.blockquoteSetextReplace2, ''); - raw = raw ? `${raw}\n${currentRaw}` : currentRaw; - text = text ? `${text}\n${currentText}` : currentText; - // parse blockquote lines as top level tokens - // merge paragraphs if this is a continuation - const top = this.lexer.state.top; - this.lexer.state.top = true; - this.lexer.blockTokens(currentText, tokens, true); - this.lexer.state.top = top; - // if there is no continuation then we are done - if (lines.length === 0) { - break; - } - const lastToken = tokens.at(-1); - if (lastToken?.type === 'code') { - // blockquote continuation cannot be preceded by a code block - break; - } - else if (lastToken?.type === 'blockquote') { - // include continuation in nested blockquote - const oldToken = lastToken; - const newText = oldToken.raw + '\n' + lines.join('\n'); - const newToken = this.blockquote(newText); - tokens[tokens.length - 1] = newToken; - raw = raw.substring(0, raw.length - oldToken.raw.length) + newToken.raw; - text = text.substring(0, text.length - oldToken.text.length) + newToken.text; - break; - } - else if (lastToken?.type === 'list') { - // include continuation in nested list - const oldToken = lastToken; - const newText = oldToken.raw + '\n' + lines.join('\n'); - const newToken = this.list(newText); - tokens[tokens.length - 1] = newToken; - raw = raw.substring(0, raw.length - lastToken.raw.length) + newToken.raw; - text = text.substring(0, text.length - oldToken.raw.length) + newToken.raw; - lines = newText.substring(tokens.at(-1).raw.length).split('\n'); - continue; - } - } - return { - type: 'blockquote', - raw, - tokens, - text, - }; - } - } - list(src) { - let cap = this.rules.block.list.exec(src); - if (cap) { - let bull = cap[1].trim(); - const isordered = bull.length > 1; - const list = { - type: 'list', - raw: '', - ordered: isordered, - start: isordered ? +bull.slice(0, -1) : '', - loose: false, - items: [], - }; - bull = isordered ? `\\d{1,9}\\${bull.slice(-1)}` : `\\${bull}`; - if (this.options.pedantic) { - bull = isordered ? bull : '[*+-]'; - } - // Get next list item - const itemRegex = this.rules.other.listItemRegex(bull); - let endsWithBlankLine = false; - // Check if current bullet point can start a new List Item - while (src) { - let endEarly = false; - let raw = ''; - let itemContents = ''; - if (!(cap = itemRegex.exec(src))) { - break; - } - if (this.rules.block.hr.test(src)) { // End list if bullet was actually HR (possibly move into itemRegex?) - break; - } - raw = cap[0]; - src = src.substring(raw.length); - let line = cap[2].split('\n', 1)[0].replace(this.rules.other.listReplaceTabs, (t) => ' '.repeat(3 * t.length)); - let nextLine = src.split('\n', 1)[0]; - let blankLine = !line.trim(); - let indent = 0; - if (this.options.pedantic) { - indent = 2; - itemContents = line.trimStart(); - } - else if (blankLine) { - indent = cap[1].length + 1; - } - else { - indent = cap[2].search(this.rules.other.nonSpaceChar); // Find first non-space char - indent = indent > 4 ? 1 : indent; // Treat indented code blocks (> 4 spaces) as having only 1 indent - itemContents = line.slice(indent); - indent += cap[1].length; - } - if (blankLine && this.rules.other.blankLine.test(nextLine)) { // Items begin with at most one blank line - raw += nextLine + '\n'; - src = src.substring(nextLine.length + 1); - endEarly = true; - } - if (!endEarly) { - const nextBulletRegex = this.rules.other.nextBulletRegex(indent); - const hrRegex = this.rules.other.hrRegex(indent); - const fencesBeginRegex = this.rules.other.fencesBeginRegex(indent); - const headingBeginRegex = this.rules.other.headingBeginRegex(indent); - const htmlBeginRegex = this.rules.other.htmlBeginRegex(indent); - // Check if following lines should be included in List Item - while (src) { - const rawLine = src.split('\n', 1)[0]; - let nextLineWithoutTabs; - nextLine = rawLine; - // Re-align to follow commonmark nesting rules - if (this.options.pedantic) { - nextLine = nextLine.replace(this.rules.other.listReplaceNesting, ' '); - nextLineWithoutTabs = nextLine; - } - else { - nextLineWithoutTabs = nextLine.replace(this.rules.other.tabCharGlobal, ' '); - } - // End list item if found code fences - if (fencesBeginRegex.test(nextLine)) { - break; - } - // End list item if found start of new heading - if (headingBeginRegex.test(nextLine)) { - break; - } - // End list item if found start of html block - if (htmlBeginRegex.test(nextLine)) { - break; - } - // End list item if found start of new bullet - if (nextBulletRegex.test(nextLine)) { - break; - } - // Horizontal rule found - if (hrRegex.test(nextLine)) { - break; - } - if (nextLineWithoutTabs.search(this.rules.other.nonSpaceChar) >= indent || !nextLine.trim()) { // Dedent if possible - itemContents += '\n' + nextLineWithoutTabs.slice(indent); - } - else { - // not enough indentation - if (blankLine) { - break; - } - // paragraph continuation unless last line was a different block level element - if (line.replace(this.rules.other.tabCharGlobal, ' ').search(this.rules.other.nonSpaceChar) >= 4) { // indented code block - break; - } - if (fencesBeginRegex.test(line)) { - break; - } - if (headingBeginRegex.test(line)) { - break; - } - if (hrRegex.test(line)) { - break; - } - itemContents += '\n' + nextLine; - } - if (!blankLine && !nextLine.trim()) { // Check if current line is blank - blankLine = true; - } - raw += rawLine + '\n'; - src = src.substring(rawLine.length + 1); - line = nextLineWithoutTabs.slice(indent); - } - } - if (!list.loose) { - // If the previous item ended with a blank line, the list is loose - if (endsWithBlankLine) { - list.loose = true; - } - else if (this.rules.other.doubleBlankLine.test(raw)) { - endsWithBlankLine = true; - } - } - let istask = null; - let ischecked; - // Check for task list items - if (this.options.gfm) { - istask = this.rules.other.listIsTask.exec(itemContents); - if (istask) { - ischecked = istask[0] !== '[ ] '; - itemContents = itemContents.replace(this.rules.other.listReplaceTask, ''); - } - } - list.items.push({ - type: 'list_item', - raw, - task: !!istask, - checked: ischecked, - loose: false, - text: itemContents, - tokens: [], - }); - list.raw += raw; - } - // Do not consume newlines at end of final item. Alternatively, make itemRegex *start* with any newlines to simplify/speed up endsWithBlankLine logic - const lastItem = list.items.at(-1); - if (lastItem) { - lastItem.raw = lastItem.raw.trimEnd(); - lastItem.text = lastItem.text.trimEnd(); - } - else { - // not a list since there were no items - return; - } - list.raw = list.raw.trimEnd(); - // Item child tokens handled here at end because we needed to have the final item to trim it first - for (let i = 0; i < list.items.length; i++) { - this.lexer.state.top = false; - list.items[i].tokens = this.lexer.blockTokens(list.items[i].text, []); - if (!list.loose) { - // Check if list should be loose - const spacers = list.items[i].tokens.filter(t => t.type === 'space'); - const hasMultipleLineBreaks = spacers.length > 0 && spacers.some(t => this.rules.other.anyLine.test(t.raw)); - list.loose = hasMultipleLineBreaks; - } - } - // Set all items to loose if list is loose - if (list.loose) { - for (let i = 0; i < list.items.length; i++) { - list.items[i].loose = true; - } - } - return list; - } - } - html(src) { - const cap = this.rules.block.html.exec(src); - if (cap) { - const token = { - type: 'html', - block: true, - raw: cap[0], - pre: cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style', - text: cap[0], - }; - return token; - } - } - def(src) { - const cap = this.rules.block.def.exec(src); - if (cap) { - const tag = cap[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal, ' '); - const href = cap[2] ? cap[2].replace(this.rules.other.hrefBrackets, '$1').replace(this.rules.inline.anyPunctuation, '$1') : ''; - const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline.anyPunctuation, '$1') : cap[3]; - return { - type: 'def', - tag, - raw: cap[0], - href, - title, - }; - } - } - table(src) { - const cap = this.rules.block.table.exec(src); - if (!cap) { - return; - } - if (!this.rules.other.tableDelimiter.test(cap[2])) { - // delimiter row must have a pipe (|) or colon (:) otherwise it is a setext heading - return; - } - const headers = splitCells(cap[1]); - const aligns = cap[2].replace(this.rules.other.tableAlignChars, '').split('|'); - const rows = cap[3]?.trim() ? cap[3].replace(this.rules.other.tableRowBlankLine, '').split('\n') : []; - const item = { - type: 'table', - raw: cap[0], - header: [], - align: [], - rows: [], - }; - if (headers.length !== aligns.length) { - // header and align columns must be equal, rows can be different. - return; - } - for (const align of aligns) { - if (this.rules.other.tableAlignRight.test(align)) { - item.align.push('right'); - } - else if (this.rules.other.tableAlignCenter.test(align)) { - item.align.push('center'); - } - else if (this.rules.other.tableAlignLeft.test(align)) { - item.align.push('left'); - } - else { - item.align.push(null); - } - } - for (let i = 0; i < headers.length; i++) { - item.header.push({ - text: headers[i], - tokens: this.lexer.inline(headers[i]), - header: true, - align: item.align[i], - }); - } - for (const row of rows) { - item.rows.push(splitCells(row, item.header.length).map((cell, i) => { - return { - text: cell, - tokens: this.lexer.inline(cell), - header: false, - align: item.align[i], - }; - })); - } - return item; - } - lheading(src) { - const cap = this.rules.block.lheading.exec(src); - if (cap) { - return { - type: 'heading', - raw: cap[0], - depth: cap[2].charAt(0) === '=' ? 1 : 2, - text: cap[1], - tokens: this.lexer.inline(cap[1]), - }; - } - } - paragraph(src) { - const cap = this.rules.block.paragraph.exec(src); - if (cap) { - const text = cap[1].charAt(cap[1].length - 1) === '\n' - ? cap[1].slice(0, -1) - : cap[1]; - return { - type: 'paragraph', - raw: cap[0], - text, - tokens: this.lexer.inline(text), - }; - } - } - text(src) { - const cap = this.rules.block.text.exec(src); - if (cap) { - return { - type: 'text', - raw: cap[0], - text: cap[0], - tokens: this.lexer.inline(cap[0]), - }; - } - } - escape(src) { - const cap = this.rules.inline.escape.exec(src); - if (cap) { - return { - type: 'escape', - raw: cap[0], - text: cap[1], - }; - } - } - tag(src) { - const cap = this.rules.inline.tag.exec(src); - if (cap) { - if (!this.lexer.state.inLink && this.rules.other.startATag.test(cap[0])) { - this.lexer.state.inLink = true; - } - else if (this.lexer.state.inLink && this.rules.other.endATag.test(cap[0])) { - this.lexer.state.inLink = false; - } - if (!this.lexer.state.inRawBlock && this.rules.other.startPreScriptTag.test(cap[0])) { - this.lexer.state.inRawBlock = true; - } - else if (this.lexer.state.inRawBlock && this.rules.other.endPreScriptTag.test(cap[0])) { - this.lexer.state.inRawBlock = false; - } - return { - type: 'html', - raw: cap[0], - inLink: this.lexer.state.inLink, - inRawBlock: this.lexer.state.inRawBlock, - block: false, - text: cap[0], - }; - } - } - link(src) { - const cap = this.rules.inline.link.exec(src); - if (cap) { - const trimmedUrl = cap[2].trim(); - if (!this.options.pedantic && this.rules.other.startAngleBracket.test(trimmedUrl)) { - // commonmark requires matching angle brackets - if (!(this.rules.other.endAngleBracket.test(trimmedUrl))) { - return; - } - // ending angle bracket cannot be escaped - const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), '\\'); - if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) { - return; - } - } - else { - // find closing parenthesis - const lastParenIndex = findClosingBracket(cap[2], '()'); - if (lastParenIndex > -1) { - const start = cap[0].indexOf('!') === 0 ? 5 : 4; - const linkLen = start + cap[1].length + lastParenIndex; - cap[2] = cap[2].substring(0, lastParenIndex); - cap[0] = cap[0].substring(0, linkLen).trim(); - cap[3] = ''; - } - } - let href = cap[2]; - let title = ''; - if (this.options.pedantic) { - // split pedantic href and title - const link = this.rules.other.pedanticHrefTitle.exec(href); - if (link) { - href = link[1]; - title = link[3]; - } - } - else { - title = cap[3] ? cap[3].slice(1, -1) : ''; - } - href = href.trim(); - if (this.rules.other.startAngleBracket.test(href)) { - if (this.options.pedantic && !(this.rules.other.endAngleBracket.test(trimmedUrl))) { - // pedantic allows starting angle bracket without ending angle bracket - href = href.slice(1); - } - else { - href = href.slice(1, -1); - } - } - return outputLink(cap, { - href: href ? href.replace(this.rules.inline.anyPunctuation, '$1') : href, - title: title ? title.replace(this.rules.inline.anyPunctuation, '$1') : title, - }, cap[0], this.lexer, this.rules); - } - } - reflink(src, links) { - let cap; - if ((cap = this.rules.inline.reflink.exec(src)) - || (cap = this.rules.inline.nolink.exec(src))) { - const linkString = (cap[2] || cap[1]).replace(this.rules.other.multipleSpaceGlobal, ' '); - const link = links[linkString.toLowerCase()]; - if (!link) { - const text = cap[0].charAt(0); - return { - type: 'text', - raw: text, - text, - }; - } - return outputLink(cap, link, cap[0], this.lexer, this.rules); - } - } - emStrong(src, maskedSrc, prevChar = '') { - let match = this.rules.inline.emStrongLDelim.exec(src); - if (!match) - return; - // _ can't be between two alphanumerics. \p{L}\p{N} includes non-english alphabet/numbers as well - if (match[3] && prevChar.match(this.rules.other.unicodeAlphaNumeric)) - return; - const nextChar = match[1] || match[2] || ''; - if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) { - // unicode Regex counts emoji as 1 char; spread into array for proper count (used multiple times below) - const lLength = [...match[0]].length - 1; - let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0; - const endReg = match[0][0] === '*' ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd; - endReg.lastIndex = 0; - // Clip maskedSrc to same section of string as src (move to lexer?) - maskedSrc = maskedSrc.slice(-1 * src.length + lLength); - while ((match = endReg.exec(maskedSrc)) != null) { - rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6]; - if (!rDelim) - continue; // skip single * in __abc*abc__ - rLength = [...rDelim].length; - if (match[3] || match[4]) { // found another Left Delim - delimTotal += rLength; - continue; - } - else if (match[5] || match[6]) { // either Left or Right Delim - if (lLength % 3 && !((lLength + rLength) % 3)) { - midDelimTotal += rLength; - continue; // CommonMark Emphasis Rules 9-10 - } - } - delimTotal -= rLength; - if (delimTotal > 0) - continue; // Haven't found enough closing delimiters - // Remove extra characters. *a*** -> *a* - rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal); - // char length can be >1 for unicode characters; - const lastCharLength = [...match[0]][0].length; - const raw = src.slice(0, lLength + match.index + lastCharLength + rLength); - // Create `em` if smallest delimiter has odd char count. *a*** - if (Math.min(lLength, rLength) % 2) { - const text = raw.slice(1, -1); - return { - type: 'em', - raw, - text, - tokens: this.lexer.inlineTokens(text), - }; - } - // Create 'strong' if smallest delimiter has even char count. **a*** - const text = raw.slice(2, -2); - return { - type: 'strong', - raw, - text, - tokens: this.lexer.inlineTokens(text), - }; - } - } - } - codespan(src) { - const cap = this.rules.inline.code.exec(src); - if (cap) { - let text = cap[2].replace(this.rules.other.newLineCharGlobal, ' '); - const hasNonSpaceChars = this.rules.other.nonSpaceChar.test(text); - const hasSpaceCharsOnBothEnds = this.rules.other.startingSpaceChar.test(text) && this.rules.other.endingSpaceChar.test(text); - if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) { - text = text.substring(1, text.length - 1); - } - return { - type: 'codespan', - raw: cap[0], - text, - }; - } - } - br(src) { - const cap = this.rules.inline.br.exec(src); - if (cap) { - return { - type: 'br', - raw: cap[0], - }; - } - } - del(src) { - const cap = this.rules.inline.del.exec(src); - if (cap) { - return { - type: 'del', - raw: cap[0], - text: cap[2], - tokens: this.lexer.inlineTokens(cap[2]), - }; - } - } - autolink(src) { - const cap = this.rules.inline.autolink.exec(src); - if (cap) { - let text, href; - if (cap[2] === '@') { - text = cap[1]; - href = 'mailto:' + text; - } - else { - text = cap[1]; - href = text; - } - return { - type: 'link', - raw: cap[0], - text, - href, - tokens: [ - { - type: 'text', - raw: text, - text, - }, - ], - }; - } - } - url(src) { - let cap; - if (cap = this.rules.inline.url.exec(src)) { - let text, href; - if (cap[2] === '@') { - text = cap[0]; - href = 'mailto:' + text; - } - else { - // do extended autolink path validation - let prevCapZero; - do { - prevCapZero = cap[0]; - cap[0] = this.rules.inline._backpedal.exec(cap[0])?.[0] ?? ''; - } while (prevCapZero !== cap[0]); - text = cap[0]; - if (cap[1] === 'www.') { - href = 'http://' + cap[0]; - } - else { - href = cap[0]; - } - } - return { - type: 'link', - raw: cap[0], - text, - href, - tokens: [ - { - type: 'text', - raw: text, - text, - }, - ], - }; - } - } - inlineText(src) { - const cap = this.rules.inline.text.exec(src); - if (cap) { - const escaped = this.lexer.state.inRawBlock; - return { - type: 'text', - raw: cap[0], - text: cap[0], - escaped, - }; - } - } -} - -/** - * Block Lexer - */ -class _Lexer { - tokens; - options; - state; - tokenizer; - inlineQueue; - constructor(options) { - // TokenList cannot be created in one go - this.tokens = []; - this.tokens.links = Object.create(null); - this.options = options || _defaults; - this.options.tokenizer = this.options.tokenizer || new _Tokenizer(); - this.tokenizer = this.options.tokenizer; - this.tokenizer.options = this.options; - this.tokenizer.lexer = this; - this.inlineQueue = []; - this.state = { - inLink: false, - inRawBlock: false, - top: true, - }; - const rules = { - other, - block: block.normal, - inline: inline.normal, - }; - if (this.options.pedantic) { - rules.block = block.pedantic; - rules.inline = inline.pedantic; - } - else if (this.options.gfm) { - rules.block = block.gfm; - if (this.options.breaks) { - rules.inline = inline.breaks; - } - else { - rules.inline = inline.gfm; - } - } - this.tokenizer.rules = rules; - } - /** - * Expose Rules - */ - static get rules() { - return { - block, - inline, - }; - } - /** - * Static Lex Method - */ - static lex(src, options) { - const lexer = new _Lexer(options); - return lexer.lex(src); - } - /** - * Static Lex Inline Method - */ - static lexInline(src, options) { - const lexer = new _Lexer(options); - return lexer.inlineTokens(src); - } - /** - * Preprocessing - */ - lex(src) { - src = src.replace(other.carriageReturn, '\n'); - this.blockTokens(src, this.tokens); - for (let i = 0; i < this.inlineQueue.length; i++) { - const next = this.inlineQueue[i]; - this.inlineTokens(next.src, next.tokens); - } - this.inlineQueue = []; - return this.tokens; - } - blockTokens(src, tokens = [], lastParagraphClipped = false) { - if (this.options.pedantic) { - src = src.replace(other.tabCharGlobal, ' ').replace(other.spaceLine, ''); - } - while (src) { - let token; - if (this.options.extensions?.block?.some((extTokenizer) => { - if (token = extTokenizer.call({ lexer: this }, src, tokens)) { - src = src.substring(token.raw.length); - tokens.push(token); - return true; - } - return false; - })) { - continue; - } - // newline - if (token = this.tokenizer.space(src)) { - src = src.substring(token.raw.length); - const lastToken = tokens.at(-1); - if (token.raw.length === 1 && lastToken !== undefined) { - // if there's a single \n as a spacer, it's terminating the last line, - // so move it there so that we don't get unnecessary paragraph tags - lastToken.raw += '\n'; - } - else { - tokens.push(token); - } - continue; - } - // code - if (token = this.tokenizer.code(src)) { - src = src.substring(token.raw.length); - const lastToken = tokens.at(-1); - // An indented code block cannot interrupt a paragraph. - if (lastToken?.type === 'paragraph' || lastToken?.type === 'text') { - lastToken.raw += '\n' + token.raw; - lastToken.text += '\n' + token.text; - this.inlineQueue.at(-1).src = lastToken.text; - } - else { - tokens.push(token); - } - continue; - } - // fences - if (token = this.tokenizer.fences(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // heading - if (token = this.tokenizer.heading(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // hr - if (token = this.tokenizer.hr(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // blockquote - if (token = this.tokenizer.blockquote(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // list - if (token = this.tokenizer.list(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // html - if (token = this.tokenizer.html(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // def - if (token = this.tokenizer.def(src)) { - src = src.substring(token.raw.length); - const lastToken = tokens.at(-1); - if (lastToken?.type === 'paragraph' || lastToken?.type === 'text') { - lastToken.raw += '\n' + token.raw; - lastToken.text += '\n' + token.raw; - this.inlineQueue.at(-1).src = lastToken.text; - } - else if (!this.tokens.links[token.tag]) { - this.tokens.links[token.tag] = { - href: token.href, - title: token.title, - }; - } - continue; - } - // table (gfm) - if (token = this.tokenizer.table(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // lheading - if (token = this.tokenizer.lheading(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // top-level paragraph - // prevent paragraph consuming extensions by clipping 'src' to extension start - let cutSrc = src; - if (this.options.extensions?.startBlock) { - let startIndex = Infinity; - const tempSrc = src.slice(1); - let tempStart; - this.options.extensions.startBlock.forEach((getStartIndex) => { - tempStart = getStartIndex.call({ lexer: this }, tempSrc); - if (typeof tempStart === 'number' && tempStart >= 0) { - startIndex = Math.min(startIndex, tempStart); - } - }); - if (startIndex < Infinity && startIndex >= 0) { - cutSrc = src.substring(0, startIndex + 1); - } - } - if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) { - const lastToken = tokens.at(-1); - if (lastParagraphClipped && lastToken?.type === 'paragraph') { - lastToken.raw += '\n' + token.raw; - lastToken.text += '\n' + token.text; - this.inlineQueue.pop(); - this.inlineQueue.at(-1).src = lastToken.text; - } - else { - tokens.push(token); - } - lastParagraphClipped = cutSrc.length !== src.length; - src = src.substring(token.raw.length); - continue; - } - // text - if (token = this.tokenizer.text(src)) { - src = src.substring(token.raw.length); - const lastToken = tokens.at(-1); - if (lastToken?.type === 'text') { - lastToken.raw += '\n' + token.raw; - lastToken.text += '\n' + token.text; - this.inlineQueue.pop(); - this.inlineQueue.at(-1).src = lastToken.text; - } - else { - tokens.push(token); - } - continue; - } - if (src) { - const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0); - if (this.options.silent) { - console.error(errMsg); - break; - } - else { - throw new Error(errMsg); - } - } - } - this.state.top = true; - return tokens; - } - inline(src, tokens = []) { - this.inlineQueue.push({ src, tokens }); - return tokens; - } - /** - * Lexing/Compiling - */ - inlineTokens(src, tokens = []) { - // String with links masked to avoid interference with em and strong - let maskedSrc = src; - let match = null; - // Mask out reflinks - if (this.tokens.links) { - const links = Object.keys(this.tokens.links); - if (links.length > 0) { - while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) { - if (links.includes(match[0].slice(match[0].lastIndexOf('[') + 1, -1))) { - maskedSrc = maskedSrc.slice(0, match.index) - + '[' + 'a'.repeat(match[0].length - 2) + ']' - + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex); - } - } - } - } - // Mask out other blocks - while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) { - maskedSrc = maskedSrc.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex); - } - // Mask out escaped characters - while ((match = this.tokenizer.rules.inline.anyPunctuation.exec(maskedSrc)) != null) { - maskedSrc = maskedSrc.slice(0, match.index) + '++' + maskedSrc.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex); - } - let keepPrevChar = false; - let prevChar = ''; - while (src) { - if (!keepPrevChar) { - prevChar = ''; - } - keepPrevChar = false; - let token; - // extensions - if (this.options.extensions?.inline?.some((extTokenizer) => { - if (token = extTokenizer.call({ lexer: this }, src, tokens)) { - src = src.substring(token.raw.length); - tokens.push(token); - return true; - } - return false; - })) { - continue; - } - // escape - if (token = this.tokenizer.escape(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // tag - if (token = this.tokenizer.tag(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // link - if (token = this.tokenizer.link(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // reflink, nolink - if (token = this.tokenizer.reflink(src, this.tokens.links)) { - src = src.substring(token.raw.length); - const lastToken = tokens.at(-1); - if (token.type === 'text' && lastToken?.type === 'text') { - lastToken.raw += token.raw; - lastToken.text += token.text; - } - else { - tokens.push(token); - } - continue; - } - // em & strong - if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // code - if (token = this.tokenizer.codespan(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // br - if (token = this.tokenizer.br(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // del (gfm) - if (token = this.tokenizer.del(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // autolink - if (token = this.tokenizer.autolink(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // url (gfm) - if (!this.state.inLink && (token = this.tokenizer.url(src))) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - // text - // prevent inlineText consuming extensions by clipping 'src' to extension start - let cutSrc = src; - if (this.options.extensions?.startInline) { - let startIndex = Infinity; - const tempSrc = src.slice(1); - let tempStart; - this.options.extensions.startInline.forEach((getStartIndex) => { - tempStart = getStartIndex.call({ lexer: this }, tempSrc); - if (typeof tempStart === 'number' && tempStart >= 0) { - startIndex = Math.min(startIndex, tempStart); - } - }); - if (startIndex < Infinity && startIndex >= 0) { - cutSrc = src.substring(0, startIndex + 1); - } - } - if (token = this.tokenizer.inlineText(cutSrc)) { - src = src.substring(token.raw.length); - if (token.raw.slice(-1) !== '_') { // Track prevChar before string of ____ started - prevChar = token.raw.slice(-1); - } - keepPrevChar = true; - const lastToken = tokens.at(-1); - if (lastToken?.type === 'text') { - lastToken.raw += token.raw; - lastToken.text += token.text; - } - else { - tokens.push(token); - } - continue; - } - if (src) { - const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0); - if (this.options.silent) { - console.error(errMsg); - break; - } - else { - throw new Error(errMsg); - } - } - } - return tokens; - } -} - -/** - * Renderer - */ -class _Renderer { - options; - parser; // set by the parser - constructor(options) { - this.options = options || _defaults; - } - space(token) { - return ''; - } - code({ text, lang, escaped }) { - const langString = (lang || '').match(other.notSpaceStart)?.[0]; - const code = text.replace(other.endingNewline, '') + '\n'; - if (!langString) { - return '
    '
    -                + (escaped ? code : escape(code, true))
    -                + '
    \n'; - } - return '
    '
    -            + (escaped ? code : escape(code, true))
    -            + '
    \n'; - } - blockquote({ tokens }) { - const body = this.parser.parse(tokens); - return `
    \n${body}
    \n`; - } - html({ text }) { - return text; - } - heading({ tokens, depth }) { - return `${this.parser.parseInline(tokens)}\n`; - } - hr(token) { - return '
    \n'; - } - list(token) { - const ordered = token.ordered; - const start = token.start; - let body = ''; - for (let j = 0; j < token.items.length; j++) { - const item = token.items[j]; - body += this.listitem(item); - } - const type = ordered ? 'ol' : 'ul'; - const startAttr = (ordered && start !== 1) ? (' start="' + start + '"') : ''; - return '<' + type + startAttr + '>\n' + body + '\n'; - } - listitem(item) { - let itemBody = ''; - if (item.task) { - const checkbox = this.checkbox({ checked: !!item.checked }); - if (item.loose) { - if (item.tokens[0]?.type === 'paragraph') { - item.tokens[0].text = checkbox + ' ' + item.tokens[0].text; - if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') { - item.tokens[0].tokens[0].text = checkbox + ' ' + escape(item.tokens[0].tokens[0].text); - item.tokens[0].tokens[0].escaped = true; - } - } - else { - item.tokens.unshift({ - type: 'text', - raw: checkbox + ' ', - text: checkbox + ' ', - escaped: true, - }); - } - } - else { - itemBody += checkbox + ' '; - } - } - itemBody += this.parser.parse(item.tokens, !!item.loose); - return `
  • ${itemBody}
  • \n`; - } - checkbox({ checked }) { - return ''; - } - paragraph({ tokens }) { - return `

    ${this.parser.parseInline(tokens)}

    \n`; - } - table(token) { - let header = ''; - // header - let cell = ''; - for (let j = 0; j < token.header.length; j++) { - cell += this.tablecell(token.header[j]); - } - header += this.tablerow({ text: cell }); - let body = ''; - for (let j = 0; j < token.rows.length; j++) { - const row = token.rows[j]; - cell = ''; - for (let k = 0; k < row.length; k++) { - cell += this.tablecell(row[k]); - } - body += this.tablerow({ text: cell }); - } - if (body) - body = `${body}`; - return '\n' - + '\n' - + header - + '\n' - + body - + '
    \n'; - } - tablerow({ text }) { - return `\n${text}\n`; - } - tablecell(token) { - const content = this.parser.parseInline(token.tokens); - const type = token.header ? 'th' : 'td'; - const tag = token.align - ? `<${type} align="${token.align}">` - : `<${type}>`; - return tag + content + `\n`; - } - /** - * span level renderer - */ - strong({ tokens }) { - return `${this.parser.parseInline(tokens)}`; - } - em({ tokens }) { - return `${this.parser.parseInline(tokens)}`; - } - codespan({ text }) { - return `${escape(text, true)}`; - } - br(token) { - return '
    '; - } - del({ tokens }) { - return `${this.parser.parseInline(tokens)}`; - } - link({ href, title, tokens }) { - const text = this.parser.parseInline(tokens); - const cleanHref = cleanUrl(href); - if (cleanHref === null) { - return text; - } - href = cleanHref; - let out = '
    '; - return out; - } - image({ href, title, text }) { - const cleanHref = cleanUrl(href); - if (cleanHref === null) { - return escape(text); - } - href = cleanHref; - let out = `${text} { - const tokens = genericToken[childTokens].flat(Infinity); - values = values.concat(this.walkTokens(tokens, callback)); - }); - } - else if (genericToken.tokens) { - values = values.concat(this.walkTokens(genericToken.tokens, callback)); - } - } - } - } - return values; - } - use(...args) { - const extensions = this.defaults.extensions || { renderers: {}, childTokens: {} }; - args.forEach((pack) => { - // copy options to new object - const opts = { ...pack }; - // set async to true if it was set to true before - opts.async = this.defaults.async || opts.async || false; - // ==-- Parse "addon" extensions --== // - if (pack.extensions) { - pack.extensions.forEach((ext) => { - if (!ext.name) { - throw new Error('extension name required'); - } - if ('renderer' in ext) { // Renderer extensions - const prevRenderer = extensions.renderers[ext.name]; - if (prevRenderer) { - // Replace extension with func to run new extension but fall back if false - extensions.renderers[ext.name] = function (...args) { - let ret = ext.renderer.apply(this, args); - if (ret === false) { - ret = prevRenderer.apply(this, args); - } - return ret; - }; - } - else { - extensions.renderers[ext.name] = ext.renderer; - } - } - if ('tokenizer' in ext) { // Tokenizer Extensions - if (!ext.level || (ext.level !== 'block' && ext.level !== 'inline')) { - throw new Error("extension level must be 'block' or 'inline'"); - } - const extLevel = extensions[ext.level]; - if (extLevel) { - extLevel.unshift(ext.tokenizer); - } - else { - extensions[ext.level] = [ext.tokenizer]; - } - if (ext.start) { // Function to check for start of token - if (ext.level === 'block') { - if (extensions.startBlock) { - extensions.startBlock.push(ext.start); - } - else { - extensions.startBlock = [ext.start]; - } - } - else if (ext.level === 'inline') { - if (extensions.startInline) { - extensions.startInline.push(ext.start); - } - else { - extensions.startInline = [ext.start]; - } - } - } - } - if ('childTokens' in ext && ext.childTokens) { // Child tokens to be visited by walkTokens - extensions.childTokens[ext.name] = ext.childTokens; - } - }); - opts.extensions = extensions; - } - // ==-- Parse "overwrite" extensions --== // - if (pack.renderer) { - const renderer = this.defaults.renderer || new _Renderer(this.defaults); - for (const prop in pack.renderer) { - if (!(prop in renderer)) { - throw new Error(`renderer '${prop}' does not exist`); - } - if (['options', 'parser'].includes(prop)) { - // ignore options property - continue; - } - const rendererProp = prop; - const rendererFunc = pack.renderer[rendererProp]; - const prevRenderer = renderer[rendererProp]; - // Replace renderer with func to run extension, but fall back if false - renderer[rendererProp] = (...args) => { - let ret = rendererFunc.apply(renderer, args); - if (ret === false) { - ret = prevRenderer.apply(renderer, args); - } - return ret || ''; - }; - } - opts.renderer = renderer; - } - if (pack.tokenizer) { - const tokenizer = this.defaults.tokenizer || new _Tokenizer(this.defaults); - for (const prop in pack.tokenizer) { - if (!(prop in tokenizer)) { - throw new Error(`tokenizer '${prop}' does not exist`); - } - if (['options', 'rules', 'lexer'].includes(prop)) { - // ignore options, rules, and lexer properties - continue; - } - const tokenizerProp = prop; - const tokenizerFunc = pack.tokenizer[tokenizerProp]; - const prevTokenizer = tokenizer[tokenizerProp]; - // Replace tokenizer with func to run extension, but fall back if false - // @ts-expect-error cannot type tokenizer function dynamically - tokenizer[tokenizerProp] = (...args) => { - let ret = tokenizerFunc.apply(tokenizer, args); - if (ret === false) { - ret = prevTokenizer.apply(tokenizer, args); - } - return ret; - }; - } - opts.tokenizer = tokenizer; - } - // ==-- Parse Hooks extensions --== // - if (pack.hooks) { - const hooks = this.defaults.hooks || new _Hooks(); - for (const prop in pack.hooks) { - if (!(prop in hooks)) { - throw new Error(`hook '${prop}' does not exist`); - } - if (['options', 'block'].includes(prop)) { - // ignore options and block properties - continue; - } - const hooksProp = prop; - const hooksFunc = pack.hooks[hooksProp]; - const prevHook = hooks[hooksProp]; - if (_Hooks.passThroughHooks.has(prop)) { - // @ts-expect-error cannot type hook function dynamically - hooks[hooksProp] = (arg) => { - if (this.defaults.async) { - return Promise.resolve(hooksFunc.call(hooks, arg)).then(ret => { - return prevHook.call(hooks, ret); - }); - } - const ret = hooksFunc.call(hooks, arg); - return prevHook.call(hooks, ret); - }; - } - else { - // @ts-expect-error cannot type hook function dynamically - hooks[hooksProp] = (...args) => { - let ret = hooksFunc.apply(hooks, args); - if (ret === false) { - ret = prevHook.apply(hooks, args); - } - return ret; - }; - } - } - opts.hooks = hooks; - } - // ==-- Parse WalkTokens extensions --== // - if (pack.walkTokens) { - const walkTokens = this.defaults.walkTokens; - const packWalktokens = pack.walkTokens; - opts.walkTokens = function (token) { - let values = []; - values.push(packWalktokens.call(this, token)); - if (walkTokens) { - values = values.concat(walkTokens.call(this, token)); - } - return values; - }; - } - this.defaults = { ...this.defaults, ...opts }; - }); - return this; - } - setOptions(opt) { - this.defaults = { ...this.defaults, ...opt }; - return this; - } - lexer(src, options) { - return _Lexer.lex(src, options ?? this.defaults); - } - parser(tokens, options) { - return _Parser.parse(tokens, options ?? this.defaults); - } - parseMarkdown(blockType) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const parse = (src, options) => { - const origOpt = { ...options }; - const opt = { ...this.defaults, ...origOpt }; - const throwError = this.onError(!!opt.silent, !!opt.async); - // throw error if an extension set async to true but parse was called with async: false - if (this.defaults.async === true && origOpt.async === false) { - return throwError(new Error('marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.')); - } - // throw error in case of non string input - if (typeof src === 'undefined' || src === null) { - return throwError(new Error('marked(): input parameter is undefined or null')); - } - if (typeof src !== 'string') { - return throwError(new Error('marked(): input parameter is of type ' - + Object.prototype.toString.call(src) + ', string expected')); - } - if (opt.hooks) { - opt.hooks.options = opt; - opt.hooks.block = blockType; - } - const lexer = opt.hooks ? opt.hooks.provideLexer() : (blockType ? _Lexer.lex : _Lexer.lexInline); - const parser = opt.hooks ? opt.hooks.provideParser() : (blockType ? _Parser.parse : _Parser.parseInline); - if (opt.async) { - return Promise.resolve(opt.hooks ? opt.hooks.preprocess(src) : src) - .then(src => lexer(src, opt)) - .then(tokens => opt.hooks ? opt.hooks.processAllTokens(tokens) : tokens) - .then(tokens => opt.walkTokens ? Promise.all(this.walkTokens(tokens, opt.walkTokens)).then(() => tokens) : tokens) - .then(tokens => parser(tokens, opt)) - .then(html => opt.hooks ? opt.hooks.postprocess(html) : html) - .catch(throwError); - } - try { - if (opt.hooks) { - src = opt.hooks.preprocess(src); - } - let tokens = lexer(src, opt); - if (opt.hooks) { - tokens = opt.hooks.processAllTokens(tokens); - } - if (opt.walkTokens) { - this.walkTokens(tokens, opt.walkTokens); - } - let html = parser(tokens, opt); - if (opt.hooks) { - html = opt.hooks.postprocess(html); - } - return html; - } - catch (e) { - return throwError(e); - } - }; - return parse; - } - onError(silent, async) { - return (e) => { - e.message += '\nPlease report this to https://github.com/markedjs/marked.'; - if (silent) { - const msg = '

    An error occurred:

    '
    -                    + escape(e.message + '', true)
    -                    + '
    '; - if (async) { - return Promise.resolve(msg); - } - return msg; - } - if (async) { - return Promise.reject(e); - } - throw e; - }; - } -} - -const markedInstance = new Marked(); -function marked(src, opt) { - return markedInstance.parse(src, opt); -} -/** - * Sets the default options. - * - * @param options Hash of options - */ -marked.options = - marked.setOptions = function (options) { - markedInstance.setOptions(options); - marked.defaults = markedInstance.defaults; - changeDefaults(marked.defaults); - return marked; - }; -/** - * Gets the original marked default options. - */ -marked.getDefaults = _getDefaults; -marked.defaults = _defaults; -/** - * Use Extension - */ -marked.use = function (...args) { - markedInstance.use(...args); - marked.defaults = markedInstance.defaults; - changeDefaults(marked.defaults); - return marked; -}; -/** - * Run callback for every token - */ -marked.walkTokens = function (tokens, callback) { - return markedInstance.walkTokens(tokens, callback); -}; -/** - * Compiles markdown to HTML without enclosing `p` tag. - * - * @param src String of markdown source to be compiled - * @param options Hash of options - * @return String of compiled HTML - */ -marked.parseInline = markedInstance.parseInline; -/** - * Expose - */ -marked.Parser = _Parser; -marked.parser = _Parser.parse; -marked.Renderer = _Renderer; -marked.TextRenderer = _TextRenderer; -marked.Lexer = _Lexer; -marked.lexer = _Lexer.lex; -marked.Tokenizer = _Tokenizer; -marked.Hooks = _Hooks; -marked.parse = marked; -const options = marked.options; -const setOptions = marked.setOptions; -const use = marked.use; -const walkTokens = marked.walkTokens; -const parseInline = marked.parseInline; -const parse = marked; -const parser = _Parser.parse; -const lexer = _Lexer.lex; - -export { _Hooks as Hooks, _Lexer as Lexer, Marked, _Parser as Parser, _Renderer as Renderer, _TextRenderer as TextRenderer, _Tokenizer as Tokenizer, _defaults as defaults, _getDefaults as getDefaults, lexer, marked, options, parse, parseInline, parser, setOptions, use, walkTokens }; -//# sourceMappingURL=marked.esm.js.map diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/pdf_viewer/viewer.html b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/pdf_viewer/viewer.html deleted file mode 100644 index 32ac36286a7..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/pdf_viewer/viewer.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - PDF viewer - - - - - - -
    -
    -
    - - - - diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/pdf_viewer/viewer.mjs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/pdf_viewer/viewer.mjs deleted file mode 100644 index 8a4a6b76f5e..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/pdf_viewer/viewer.mjs +++ /dev/null @@ -1,62 +0,0 @@ -import { GlobalWorkerOptions } from '../pdfjs-dist/dist/build/pdf.min.mjs'; -import { EventBus, PDFLinkService, PDFFindController, PDFViewer } from '../pdfjs-dist/dist/web/pdf_viewer.mjs'; - -GlobalWorkerOptions.workerSrc = '../pdfjs-dist/dist/build/pdf.worker.min.mjs'; - -// Extract the file path from the URL query string. -const url = new URL(window.location); -const fileUrl = url.searchParams.get('file'); -if (!fileUrl) { - throw new Error('File not specified in the URL query string'); -} - -const container = document.getElementById('viewerContainer'); -const eventBus = new EventBus(); - -// Enable hyperlinks within PDF files. -const pdfLinkService = new PDFLinkService({ - eventBus, -}); - -// Enable the find controller. -const pdfFindController = new PDFFindController({ - eventBus, - linkService: pdfLinkService, -}); - -// Create the PDF viewer. -const pdfViewer = new PDFViewer({ - container, - eventBus, - linkService: pdfLinkService, - findController: pdfFindController, -}); -pdfLinkService.setViewer(pdfViewer); - -// Allow navigation to a citation from the URL hash. -eventBus.on('pagesinit', function () { - pdfLinkService.setHash(window.location.hash.substring(1)); -}); - -// Define how the "search" query parameter is handled. -eventBus.on('findfromurlhash', function(evt) { - eventBus.dispatch('find', { - source: evt.source, - type: '', - query: evt.query, - caseSensitive: false, - entireWord: false, - highlightAll: false, - findPrevious: false, - matchDiacritics: true, - }); -}); - -// Load and initialize the document. -const pdfDocument = await pdfjsLib.getDocument({ - url: fileUrl, - enableXfa: true, -}).promise; - -pdfViewer.setDocument(pdfDocument); -pdfLinkService.setDocument(pdfDocument, null); diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/pdfjs-dist/README.md b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/pdfjs-dist/README.md deleted file mode 100644 index 8e77fba7d43..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/pdfjs-dist/README.md +++ /dev/null @@ -1,10 +0,0 @@ -pdfjs-dist version 4.10.38 -https://github.com/mozilla/pdf.js -License: Apache-2.0 - -To update, replace the following files with updated versions from https://www.npmjs.com/package/pdfjs-dist: -* `build/pdf.min.mjs` -* `build/pdf.worker.min.mjs` -* `web/pdf_viewer.css` -* `web/pdf_viewer.mjs` -* `web/images/loading-icon.gif` diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/pdfjs-dist/dist/build/pdf.min.mjs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/pdfjs-dist/dist/build/pdf.min.mjs deleted file mode 100644 index d7cfa914562..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/pdfjs-dist/dist/build/pdf.min.mjs +++ /dev/null @@ -1,21 +0,0 @@ -/** - * @licstart The following is the entire license notice for the - * JavaScript code in this page - * - * Copyright 2024 Mozilla Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * @licend The above is the entire license notice for the - * JavaScript code in this page - */var t={d:(e,i)=>{for(var s in i)t.o(i,s)&&!t.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:i[s]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e)},__webpack_exports__ = globalThis.pdfjsLib = {};t.d(__webpack_exports__,{AbortException:()=>AbortException,AnnotationEditorLayer:()=>AnnotationEditorLayer,AnnotationEditorParamsType:()=>m,AnnotationEditorType:()=>g,AnnotationEditorUIManager:()=>AnnotationEditorUIManager,AnnotationLayer:()=>AnnotationLayer,AnnotationMode:()=>p,ColorPicker:()=>ColorPicker,DOMSVGFactory:()=>DOMSVGFactory,DrawLayer:()=>DrawLayer,FeatureTest:()=>util_FeatureTest,GlobalWorkerOptions:()=>GlobalWorkerOptions,ImageKind:()=>_,InvalidPDFException:()=>InvalidPDFException,MissingPDFException:()=>MissingPDFException,OPS:()=>X,OutputScale:()=>OutputScale,PDFDataRangeTransport:()=>PDFDataRangeTransport,PDFDateString:()=>PDFDateString,PDFWorker:()=>PDFWorker,PasswordResponses:()=>K,PermissionFlag:()=>f,PixelsPerInch:()=>PixelsPerInch,RenderingCancelledException:()=>RenderingCancelledException,TextLayer:()=>TextLayer,TouchManager:()=>TouchManager,UnexpectedResponseException:()=>UnexpectedResponseException,Util:()=>Util,VerbosityLevel:()=>q,XfaLayer:()=>XfaLayer,build:()=>Nt,createValidAbsoluteUrl:()=>createValidAbsoluteUrl,fetchData:()=>fetchData,getDocument:()=>getDocument,getFilenameFromUrl:()=>getFilenameFromUrl,getPdfFilenameFromUrl:()=>getPdfFilenameFromUrl,getXfaPageViewport:()=>getXfaPageViewport,isDataScheme:()=>isDataScheme,isPdfFile:()=>isPdfFile,noContextMenu:()=>noContextMenu,normalizeUnicode:()=>normalizeUnicode,setLayerDimensions:()=>setLayerDimensions,shadow:()=>shadow,stopEvent:()=>stopEvent,version:()=>Ot});const e=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),i=[1,0,0,1,0,0],s=[.001,0,0,.001,0,0],n=1.35,a=1,r=2,o=4,l=16,h=32,d=64,c=128,u=256,p={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},g={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},m={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,HIGHLIGHT_COLOR:31,HIGHLIGHT_DEFAULT_COLOR:32,HIGHLIGHT_THICKNESS:33,HIGHLIGHT_FREE:34,HIGHLIGHT_SHOW_ALL:35,DRAW_STEP:41},f={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},b=0,A=1,w=2,v=3,y=3,x=4,_={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},E=1,S=2,C=3,T=4,M=5,P=6,D=7,k=8,R=9,I=10,F=11,L=12,O=13,N=14,B=15,H=16,z=17,U=20,G=1,$=2,V=3,j=4,W=5,q={ERRORS:0,WARNINGS:1,INFOS:5},X={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91,setStrokeTransparent:92,setFillTransparent:93},K={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let Y=q.WARNINGS;function setVerbosityLevel(t){Number.isInteger(t)&&(Y=t)}function getVerbosityLevel(){return Y}function info(t){Y>=q.INFOS&&console.log(`Info: ${t}`)}function warn(t){Y>=q.WARNINGS&&console.log(`Warning: ${t}`)}function unreachable(t){throw new Error(t)}function assert(t,e){t||unreachable(e)}function createValidAbsoluteUrl(t,e=null,i=null){if(!t)return null;try{if(i&&"string"==typeof t){if(i.addDefaultProtocol&&t.startsWith("www.")){const e=t.match(/\./g);e?.length>=2&&(t=`http://${t}`)}if(i.tryConvertEncoding)try{t=function stringToUTF8String(t){return decodeURIComponent(escape(t))}(t)}catch{}}const s=e?new URL(t,e):new URL(t);if(function _isValidProtocol(t){switch(t?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(s))return s}catch{}return null}function shadow(t,e,i,s=!1){Object.defineProperty(t,e,{value:i,enumerable:!s,configurable:!0,writable:!1});return i}const Q=function BaseExceptionClosure(){function BaseException(t,e){this.message=t;this.name=e}BaseException.prototype=new Error;BaseException.constructor=BaseException;return BaseException}();class PasswordException extends Q{constructor(t,e){super(t,"PasswordException");this.code=e}}class UnknownErrorException extends Q{constructor(t,e){super(t,"UnknownErrorException");this.details=e}}class InvalidPDFException extends Q{constructor(t){super(t,"InvalidPDFException")}}class MissingPDFException extends Q{constructor(t){super(t,"MissingPDFException")}}class UnexpectedResponseException extends Q{constructor(t,e){super(t,"UnexpectedResponseException");this.status=e}}class FormatError extends Q{constructor(t){super(t,"FormatError")}}class AbortException extends Q{constructor(t){super(t,"AbortException")}}function bytesToString(t){"object"==typeof t&&void 0!==t?.length||unreachable("Invalid argument for bytesToString");const e=t.length,i=8192;if(et.toString(16).padStart(2,"0")));class Util{static makeHexColor(t,e,i){return`#${J[t]}${J[e]}${J[i]}`}static scaleMinMax(t,e){let i;if(t[0]){if(t[0]<0){i=e[0];e[0]=e[2];e[2]=i}e[0]*=t[0];e[2]*=t[0];if(t[3]<0){i=e[1];e[1]=e[3];e[3]=i}e[1]*=t[3];e[3]*=t[3]}else{i=e[0];e[0]=e[1];e[1]=i;i=e[2];e[2]=e[3];e[3]=i;if(t[1]<0){i=e[1];e[1]=e[3];e[3]=i}e[1]*=t[1];e[3]*=t[1];if(t[2]<0){i=e[0];e[0]=e[2];e[2]=i}e[0]*=t[2];e[2]*=t[2]}e[0]+=t[4];e[1]+=t[5];e[2]+=t[4];e[3]+=t[5]}static transform(t,e){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],t[0]*e[4]+t[2]*e[5]+t[4],t[1]*e[4]+t[3]*e[5]+t[5]]}static applyTransform(t,e){return[t[0]*e[0]+t[1]*e[2]+e[4],t[0]*e[1]+t[1]*e[3]+e[5]]}static applyInverseTransform(t,e){const i=e[0]*e[3]-e[1]*e[2];return[(t[0]*e[3]-t[1]*e[2]+e[2]*e[5]-e[4]*e[3])/i,(-t[0]*e[1]+t[1]*e[0]+e[4]*e[1]-e[5]*e[0])/i]}static getAxialAlignedBoundingBox(t,e){const i=this.applyTransform(t,e),s=this.applyTransform(t.slice(2,4),e),n=this.applyTransform([t[0],t[3]],e),a=this.applyTransform([t[2],t[1]],e);return[Math.min(i[0],s[0],n[0],a[0]),Math.min(i[1],s[1],n[1],a[1]),Math.max(i[0],s[0],n[0],a[0]),Math.max(i[1],s[1],n[1],a[1])]}static inverseTransform(t){const e=t[0]*t[3]-t[1]*t[2];return[t[3]/e,-t[1]/e,-t[2]/e,t[0]/e,(t[2]*t[5]-t[4]*t[3])/e,(t[4]*t[1]-t[5]*t[0])/e]}static singularValueDecompose2dScale(t){const e=[t[0],t[2],t[1],t[3]],i=t[0]*e[0]+t[1]*e[2],s=t[0]*e[1]+t[1]*e[3],n=t[2]*e[0]+t[3]*e[2],a=t[2]*e[1]+t[3]*e[3],r=(i+a)/2,o=Math.sqrt((i+a)**2-4*(i*a-n*s))/2,l=r+o||1,h=r-o||1;return[Math.sqrt(l),Math.sqrt(h)]}static normalizeRect(t){const e=t.slice(0);if(t[0]>t[2]){e[0]=t[2];e[2]=t[0]}if(t[1]>t[3]){e[1]=t[3];e[3]=t[1]}return e}static intersect(t,e){const i=Math.max(Math.min(t[0],t[2]),Math.min(e[0],e[2])),s=Math.min(Math.max(t[0],t[2]),Math.max(e[0],e[2]));if(i>s)return null;const n=Math.max(Math.min(t[1],t[3]),Math.min(e[1],e[3])),a=Math.min(Math.max(t[1],t[3]),Math.max(e[1],e[3]));return n>a?null:[i,n,s,a]}static#t(t,e,i,s,n,a,r,o,l,h){if(l<=0||l>=1)return;const d=1-l,c=l*l,u=c*l,p=d*(d*(d*t+3*l*e)+3*c*i)+u*s,g=d*(d*(d*n+3*l*a)+3*c*r)+u*o;h[0]=Math.min(h[0],p);h[1]=Math.min(h[1],g);h[2]=Math.max(h[2],p);h[3]=Math.max(h[3],g)}static#e(t,e,i,s,n,a,r,o,l,h,d,c){if(Math.abs(l)<1e-12){Math.abs(h)>=1e-12&&this.#t(t,e,i,s,n,a,r,o,-d/h,c);return}const u=h**2-4*d*l;if(u<0)return;const p=Math.sqrt(u),g=2*l;this.#t(t,e,i,s,n,a,r,o,(-h+p)/g,c);this.#t(t,e,i,s,n,a,r,o,(-h-p)/g,c)}static bezierBoundingBox(t,e,i,s,n,a,r,o,l){if(l){l[0]=Math.min(l[0],t,r);l[1]=Math.min(l[1],e,o);l[2]=Math.max(l[2],t,r);l[3]=Math.max(l[3],e,o)}else l=[Math.min(t,r),Math.min(e,o),Math.max(t,r),Math.max(e,o)];this.#e(t,i,n,r,e,s,a,o,3*(3*(i-n)-t+r),6*(t-2*i+n),3*(i-t),l);this.#e(t,i,n,r,e,s,a,o,3*(3*(s-a)-e+o),6*(e-2*s+a),3*(s-e),l);return l}}let Z=null,tt=null;function normalizeUnicode(t){if(!Z){Z=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu;tt=new Map([["ſt","ſt"]])}return t.replaceAll(Z,((t,e,i)=>e?e.normalize("NFKC"):tt.get(i)))}const et="pdfjs_internal_id_";"function"!=typeof Promise.try&&(Promise.try=function(t,...e){return new Promise((i=>{i(t(...e))}))});const it="http://www.w3.org/2000/svg";class PixelsPerInch{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function fetchData(t,e="text"){if(isValidFetchUrl(t,document.baseURI)){const i=await fetch(t);if(!i.ok)throw new Error(i.statusText);switch(e){case"arraybuffer":return i.arrayBuffer();case"blob":return i.blob();case"json":return i.json()}return i.text()}return new Promise(((i,s)=>{const n=new XMLHttpRequest;n.open("GET",t,!0);n.responseType=e;n.onreadystatechange=()=>{if(n.readyState===XMLHttpRequest.DONE)if(200!==n.status&&0!==n.status)s(new Error(n.statusText));else{switch(e){case"arraybuffer":case"blob":case"json":i(n.response);return}i(n.responseText)}};n.send(null)}))}class PageViewport{constructor({viewBox:t,userUnit:e,scale:i,rotation:s,offsetX:n=0,offsetY:a=0,dontFlip:r=!1}){this.viewBox=t;this.userUnit=e;this.scale=i;this.rotation=s;this.offsetX=n;this.offsetY=a;i*=e;const o=(t[2]+t[0])/2,l=(t[3]+t[1])/2;let h,d,c,u,p,g,m,f;(s%=360)<0&&(s+=360);switch(s){case 180:h=-1;d=0;c=0;u=1;break;case 90:h=0;d=1;c=1;u=0;break;case 270:h=0;d=-1;c=-1;u=0;break;case 0:h=1;d=0;c=0;u=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}if(r){c=-c;u=-u}if(0===h){p=Math.abs(l-t[1])*i+n;g=Math.abs(o-t[0])*i+a;m=(t[3]-t[1])*i;f=(t[2]-t[0])*i}else{p=Math.abs(o-t[0])*i+n;g=Math.abs(l-t[1])*i+a;m=(t[2]-t[0])*i;f=(t[3]-t[1])*i}this.transform=[h*i,d*i,c*i,u*i,p-h*i*o-c*i*l,g-d*i*o-u*i*l];this.width=m;this.height=f}get rawDims(){const{userUnit:t,viewBox:e}=this,i=e.map((e=>e*t));return shadow(this,"rawDims",{pageWidth:i[2]-i[0],pageHeight:i[3]-i[1],pageX:i[0],pageY:i[1]})}clone({scale:t=this.scale,rotation:e=this.rotation,offsetX:i=this.offsetX,offsetY:s=this.offsetY,dontFlip:n=!1}={}){return new PageViewport({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:t,rotation:e,offsetX:i,offsetY:s,dontFlip:n})}convertToViewportPoint(t,e){return Util.applyTransform([t,e],this.transform)}convertToViewportRectangle(t){const e=Util.applyTransform([t[0],t[1]],this.transform),i=Util.applyTransform([t[2],t[3]],this.transform);return[e[0],e[1],i[0],i[1]]}convertToPdfPoint(t,e){return Util.applyInverseTransform([t,e],this.transform)}}class RenderingCancelledException extends Q{constructor(t,e=0){super(t,"RenderingCancelledException");this.extraDelay=e}}function isDataScheme(t){const e=t.length;let i=0;for(;i=1&&s<=12?s-1:0;let n=parseInt(e[3],10);n=n>=1&&n<=31?n:1;let a=parseInt(e[4],10);a=a>=0&&a<=23?a:0;let r=parseInt(e[5],10);r=r>=0&&r<=59?r:0;let o=parseInt(e[6],10);o=o>=0&&o<=59?o:0;const l=e[7]||"Z";let h=parseInt(e[8],10);h=h>=0&&h<=23?h:0;let d=parseInt(e[9],10)||0;d=d>=0&&d<=59?d:0;if("-"===l){a+=h;r+=d}else if("+"===l){a-=h;r-=d}return new Date(Date.UTC(i,s,n,a,r,o))}}function getXfaPageViewport(t,{scale:e=1,rotation:i=0}){const{width:s,height:n}=t.attributes.style,a=[0,0,parseInt(s),parseInt(n)];return new PageViewport({viewBox:a,userUnit:1,scale:e,rotation:i})}function getRGB(t){if(t.startsWith("#")){const e=parseInt(t.slice(1),16);return[(16711680&e)>>16,(65280&e)>>8,255&e]}if(t.startsWith("rgb("))return t.slice(4,-1).split(",").map((t=>parseInt(t)));if(t.startsWith("rgba("))return t.slice(5,-1).split(",").map((t=>parseInt(t))).slice(0,3);warn(`Not a valid color format: "${t}"`);return[0,0,0]}function getCurrentTransform(t){const{a:e,b:i,c:s,d:n,e:a,f:r}=t.getTransform();return[e,i,s,n,a,r]}function getCurrentTransformInverse(t){const{a:e,b:i,c:s,d:n,e:a,f:r}=t.getTransform().invertSelf();return[e,i,s,n,a,r]}function setLayerDimensions(t,e,i=!1,s=!0){if(e instanceof PageViewport){const{pageWidth:s,pageHeight:n}=e.rawDims,{style:a}=t,r=util_FeatureTest.isCSSRoundSupported,o=`var(--scale-factor) * ${s}px`,l=`var(--scale-factor) * ${n}px`,h=r?`round(down, ${o}, var(--scale-round-x, 1px))`:`calc(${o})`,d=r?`round(down, ${l}, var(--scale-round-y, 1px))`:`calc(${l})`;if(i&&e.rotation%180!=0){a.width=d;a.height=h}else{a.width=h;a.height=d}}s&&t.setAttribute("data-main-rotation",e.rotation)}class OutputScale{constructor(){const t=window.devicePixelRatio||1;this.sx=t;this.sy=t}get scaled(){return 1!==this.sx||1!==this.sy}get symmetric(){return this.sx===this.sy}}class EditorToolbar{#s=null;#n=null;#a;#r=null;#o=null;static#l=null;constructor(t){this.#a=t;EditorToolbar.#l||=Object.freeze({freetext:"pdfjs-editor-remove-freetext-button",highlight:"pdfjs-editor-remove-highlight-button",ink:"pdfjs-editor-remove-ink-button",stamp:"pdfjs-editor-remove-stamp-button"})}render(){const t=this.#s=document.createElement("div");t.classList.add("editToolbar","hidden");t.setAttribute("role","toolbar");const e=this.#a._uiManager._signal;t.addEventListener("contextmenu",noContextMenu,{signal:e});t.addEventListener("pointerdown",EditorToolbar.#h,{signal:e});const i=this.#r=document.createElement("div");i.className="buttons";t.append(i);const s=this.#a.toolbarPosition;if(s){const{style:e}=t,i="ltr"===this.#a._uiManager.direction?1-s[0]:s[0];e.insetInlineEnd=100*i+"%";e.top=`calc(${100*s[1]}% + var(--editor-toolbar-vert-offset))`}this.#d();return t}get div(){return this.#s}static#h(t){t.stopPropagation()}#c(t){this.#a._focusEventsAllowed=!1;stopEvent(t)}#u(t){this.#a._focusEventsAllowed=!0;stopEvent(t)}#p(t){const e=this.#a._uiManager._signal;t.addEventListener("focusin",this.#c.bind(this),{capture:!0,signal:e});t.addEventListener("focusout",this.#u.bind(this),{capture:!0,signal:e});t.addEventListener("contextmenu",noContextMenu,{signal:e})}hide(){this.#s.classList.add("hidden");this.#n?.hideDropdown()}show(){this.#s.classList.remove("hidden");this.#o?.shown()}#d(){const{editorType:t,_uiManager:e}=this.#a,i=document.createElement("button");i.className="delete";i.tabIndex=0;i.setAttribute("data-l10n-id",EditorToolbar.#l[t]);this.#p(i);i.addEventListener("click",(t=>{e.delete()}),{signal:e._signal});this.#r.append(i)}get#g(){const t=document.createElement("div");t.className="divider";return t}async addAltText(t){const e=await t.render();this.#p(e);this.#r.prepend(e,this.#g);this.#o=t}addColorPicker(t){this.#n=t;const e=t.renderButton();this.#p(e);this.#r.prepend(e,this.#g)}remove(){this.#s.remove();this.#n?.destroy();this.#n=null}}class HighlightToolbar{#r=null;#s=null;#m;constructor(t){this.#m=t}#f(){const t=this.#s=document.createElement("div");t.className="editToolbar";t.setAttribute("role","toolbar");t.addEventListener("contextmenu",noContextMenu,{signal:this.#m._signal});const e=this.#r=document.createElement("div");e.className="buttons";t.append(e);this.#b();return t}#A(t,e){let i=0,s=0;for(const n of t){const t=n.y+n.height;if(ti){s=a;i=t}else e?a>s&&(s=a):a{this.#m.highlightSelection("floating_button")}),{signal:i});this.#r.append(t)}}function bindEvents(t,e,i){for(const s of i)e.addEventListener(s,t[s].bind(t))}class IdManager{#w=0;get id(){return"pdfjs_internal_editor_"+this.#w++}}class ImageManager{#v=function getUuid(){if("function"==typeof crypto.randomUUID)return crypto.randomUUID();const t=new Uint8Array(32);crypto.getRandomValues(t);return bytesToString(t)}();#w=0;#y=null;static get _isSVGFittingCanvas(){const t=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),e=new Image;e.src='data:image/svg+xml;charset=UTF-8,';return shadow(this,"_isSVGFittingCanvas",e.decode().then((()=>{t.drawImage(e,0,0,1,1,0,0,1,3);return 0===new Uint32Array(t.getImageData(0,0,1,1).data.buffer)[0]})))}async#x(t,e){this.#y||=new Map;let i=this.#y.get(t);if(null===i)return null;if(i?.bitmap){i.refCounter+=1;return i}try{i||={bitmap:null,id:`image_${this.#v}_${this.#w++}`,refCounter:0,isSvg:!1};let t;if("string"==typeof e){i.url=e;t=await fetchData(e,"blob")}else e instanceof File?t=i.file=e:e instanceof Blob&&(t=e);if("image/svg+xml"===t.type){const e=ImageManager._isSVGFittingCanvas,s=new FileReader,n=new Image,a=new Promise(((t,a)=>{n.onload=()=>{i.bitmap=n;i.isSvg=!0;t()};s.onload=async()=>{const t=i.svgUrl=s.result;n.src=await e?`${t}#svgView(preserveAspectRatio(none))`:t};n.onerror=s.onerror=a}));s.readAsDataURL(t);await a}else i.bitmap=await createImageBitmap(t);i.refCounter=1}catch(t){warn(t);i=null}this.#y.set(t,i);i&&this.#y.set(i.id,i);return i}async getFromFile(t){const{lastModified:e,name:i,size:s,type:n}=t;return this.#x(`${e}_${i}_${s}_${n}`,t)}async getFromUrl(t){return this.#x(t,t)}async getFromBlob(t,e){const i=await e;return this.#x(t,i)}async getFromId(t){this.#y||=new Map;const e=this.#y.get(t);if(!e)return null;if(e.bitmap){e.refCounter+=1;return e}if(e.file)return this.getFromFile(e.file);if(e.blobPromise){const{blobPromise:t}=e;delete e.blobPromise;return this.getFromBlob(e.id,t)}return this.getFromUrl(e.url)}getFromCanvas(t,e){this.#y||=new Map;let i=this.#y.get(t);if(i?.bitmap){i.refCounter+=1;return i}const s=new OffscreenCanvas(e.width,e.height);s.getContext("2d").drawImage(e,0,0);i={bitmap:s.transferToImageBitmap(),id:`image_${this.#v}_${this.#w++}`,refCounter:1,isSvg:!1};this.#y.set(t,i);this.#y.set(i.id,i);return i}getSvgUrl(t){const e=this.#y.get(t);return e?.isSvg?e.svgUrl:null}deleteId(t){this.#y||=new Map;const e=this.#y.get(t);if(!e)return;e.refCounter-=1;if(0!==e.refCounter)return;const{bitmap:i}=e;if(!e.url&&!e.file){const t=new OffscreenCanvas(i.width,i.height);t.getContext("bitmaprenderer").transferFromImageBitmap(i);e.blobPromise=t.convertToBlob()}i.close?.();e.bitmap=null}isValidId(t){return t.startsWith(`image_${this.#v}_`)}}class CommandManager{#_=[];#E=!1;#S;#C=-1;constructor(t=128){this.#S=t}add({cmd:t,undo:e,post:i,mustExec:s,type:n=NaN,overwriteIfSameType:a=!1,keepUndo:r=!1}){s&&t();if(this.#E)return;const o={cmd:t,undo:e,post:i,type:n};if(-1===this.#C){this.#_.length>0&&(this.#_.length=0);this.#C=0;this.#_.push(o);return}if(a&&this.#_[this.#C].type===n){r&&(o.undo=this.#_[this.#C].undo);this.#_[this.#C]=o;return}const l=this.#C+1;if(l===this.#S)this.#_.splice(0,1);else{this.#C=l;l=0;e--)if(this.#_[e].type!==t){this.#_.splice(e+1,this.#C-e);this.#C=e;return}this.#_.length=0;this.#C=-1}}destroy(){this.#_=null}}class KeyboardManager{constructor(t){this.buffer=[];this.callbacks=new Map;this.allKeys=new Set;const{isMac:e}=util_FeatureTest.platform;for(const[i,s,n={}]of t)for(const t of i){const i=t.startsWith("mac+");if(e&&i){this.callbacks.set(t.slice(4),{callback:s,options:n});this.allKeys.add(t.split("+").at(-1))}else if(!e&&!i){this.callbacks.set(t,{callback:s,options:n});this.allKeys.add(t.split("+").at(-1))}}}#T(t){t.altKey&&this.buffer.push("alt");t.ctrlKey&&this.buffer.push("ctrl");t.metaKey&&this.buffer.push("meta");t.shiftKey&&this.buffer.push("shift");this.buffer.push(t.key);const e=this.buffer.join("+");this.buffer.length=0;return e}exec(t,e){if(!this.allKeys.has(e.key))return;const i=this.callbacks.get(this.#T(e));if(!i)return;const{callback:s,options:{bubbles:n=!1,args:a=[],checker:r=null}}=i;if(!r||r(t,e)){s.bind(t,...a,e)();n||stopEvent(e)}}}class ColorManager{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){const t=new Map([["CanvasText",null],["Canvas",null]]);!function getColorValues(t){const e=document.createElement("span");e.style.visibility="hidden";document.body.append(e);for(const i of t.keys()){e.style.color=i;const s=window.getComputedStyle(e).color;t.set(i,getRGB(s))}e.remove()}(t);return shadow(this,"_colors",t)}convert(t){const e=getRGB(t);if(!window.matchMedia("(forced-colors: active)").matches)return e;for(const[t,i]of this._colors)if(i.every(((t,i)=>t===e[i])))return ColorManager._colorsMapping.get(t);return e}getHexCode(t){const e=this._colors.get(t);return e?Util.makeHexColor(...e):t}}class AnnotationEditorUIManager{#M=new AbortController;#P=null;#D=new Map;#k=new Map;#R=null;#I=null;#F=null;#L=new CommandManager;#O=null;#N=null;#B=0;#H=new Set;#z=null;#U=null;#G=new Set;_editorUndoBar=null;#$=!1;#V=!1;#j=!1;#W=null;#q=null;#X=null;#K=null;#Y=!1;#Q=null;#J=new IdManager;#Z=!1;#tt=!1;#et=null;#it=null;#st=null;#nt=null;#at=g.NONE;#rt=new Set;#ot=null;#lt=null;#ht=null;#dt={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#ct=[0,0];#ut=null;#pt=null;#gt=null;#mt=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=AnnotationEditorUIManager.prototype,arrowChecker=t=>t.#pt.contains(document.activeElement)&&"BUTTON"!==document.activeElement.tagName&&t.hasSomethingToControl(),textInputChecker=(t,{target:e})=>{if(e instanceof HTMLInputElement){const{type:t}=e;return"text"!==t&&"number"!==t}return!0},e=this.TRANSLATE_SMALL,i=this.TRANSLATE_BIG;return shadow(this,"_keyboardManager",new KeyboardManager([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:textInputChecker}],[["ctrl+z","mac+meta+z"],t.undo,{checker:textInputChecker}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:textInputChecker}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],t.delete,{checker:textInputChecker}],[["Enter","mac+Enter"],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#pt.contains(e)&&!t.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#pt.contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-e,0],checker:arrowChecker}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-i,0],checker:arrowChecker}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[e,0],checker:arrowChecker}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[i,0],checker:arrowChecker}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-e],checker:arrowChecker}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-i],checker:arrowChecker}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,e],checker:arrowChecker}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,i],checker:arrowChecker}]]))}constructor(t,e,i,s,n,a,r,o,l,h,d,c,u){const p=this._signal=this.#M.signal;this.#pt=t;this.#gt=e;this.#R=i;this._eventBus=s;s._on("editingaction",this.onEditingAction.bind(this),{signal:p});s._on("pagechanging",this.onPageChanging.bind(this),{signal:p});s._on("scalechanging",this.onScaleChanging.bind(this),{signal:p});s._on("rotationchanging",this.onRotationChanging.bind(this),{signal:p});s._on("setpreference",this.onSetPreference.bind(this),{signal:p});s._on("switchannotationeditorparams",(t=>this.updateParams(t.type,t.value)),{signal:p});this.#ft();this.#bt();this.#At();this.#I=n.annotationStorage;this.#W=n.filterFactory;this.#lt=a;this.#K=r||null;this.#$=o;this.#V=l;this.#j=h;this.#nt=d||null;this.viewParameters={realScale:PixelsPerInch.PDF_TO_CSS_UNITS,rotation:0};this.isShiftKeyDown=!1;this._editorUndoBar=c||null;this._supportsPinchToZoom=!1!==u}destroy(){this.#mt?.resolve();this.#mt=null;this.#M?.abort();this.#M=null;this._signal=null;for(const t of this.#k.values())t.destroy();this.#k.clear();this.#D.clear();this.#G.clear();this.#P=null;this.#rt.clear();this.#L.destroy();this.#R?.destroy();this.#Q?.hide();this.#Q=null;if(this.#q){clearTimeout(this.#q);this.#q=null}if(this.#ut){clearTimeout(this.#ut);this.#ut=null}this._editorUndoBar?.destroy()}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return this.#nt}get useNewAltTextFlow(){return this.#V}get useNewAltTextWhenAddingImage(){return this.#j}get hcmFilter(){return shadow(this,"hcmFilter",this.#lt?this.#W.addHCMFilter(this.#lt.foreground,this.#lt.background):"none")}get direction(){return shadow(this,"direction",getComputedStyle(this.#pt).direction)}get highlightColors(){return shadow(this,"highlightColors",this.#K?new Map(this.#K.split(",").map((t=>t.split("=").map((t=>t.trim()))))):null)}get highlightColorNames(){return shadow(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,(t=>t.reverse()))):null)}setCurrentDrawingSession(t){if(t){this.unselectAll();this.disableUserSelect(!0)}else this.disableUserSelect(!1);this.#N=t}setMainHighlightColorPicker(t){this.#st=t}editAltText(t,e=!1){this.#R?.editAltText(this,t,e)}switchToMode(t,e){this._eventBus.on("annotationeditormodechanged",e,{once:!0,signal:this._signal});this._eventBus.dispatch("showannotationeditorui",{source:this,mode:t})}setPreference(t,e){this._eventBus.dispatch("setpreference",{source:this,name:t,value:e})}onSetPreference({name:t,value:e}){if("enableNewAltTextWhenAddingImage"===t)this.#j=e}onPageChanging({pageNumber:t}){this.#B=t-1}focusMainContainer(){this.#pt.focus()}findParent(t,e){for(const i of this.#k.values()){const{x:s,y:n,width:a,height:r}=i.div.getBoundingClientRect();if(t>=s&&t<=s+a&&e>=n&&e<=n+r)return i}return null}disableUserSelect(t=!1){this.#gt.classList.toggle("noUserSelect",t)}addShouldRescale(t){this.#G.add(t)}removeShouldRescale(t){this.#G.delete(t)}onScaleChanging({scale:t}){this.commitOrRemove();this.viewParameters.realScale=t*PixelsPerInch.PDF_TO_CSS_UNITS;for(const t of this.#G)t.onScaleChanging();this.#N?.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove();this.viewParameters.rotation=t}#wt({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}#vt(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const e of this.#k.values())if(e.hasTextLayer(t))return e;return null}highlightSelection(t=""){const e=document.getSelection();if(!e||e.isCollapsed)return;const{anchorNode:i,anchorOffset:s,focusNode:n,focusOffset:a}=e,r=e.toString(),o=this.#wt(e).closest(".textLayer"),l=this.getSelectionBoxes(o);if(!l)return;e.empty();const h=this.#vt(o),d=this.#at===g.NONE,callback=()=>{h?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:l,anchorNode:i,anchorOffset:s,focusNode:n,focusOffset:a,text:r});d&&this.showAllEditors("highlight",!0,!0)};d?this.switchToMode(g.HIGHLIGHT,callback):callback()}#yt(){const t=document.getSelection();if(!t||t.isCollapsed)return;const e=this.#wt(t).closest(".textLayer"),i=this.getSelectionBoxes(e);if(i){this.#Q||=new HighlightToolbar(this);this.#Q.show(e,i,"ltr"===this.direction)}}addToAnnotationStorage(t){t.isEmpty()||!this.#I||this.#I.has(t.id)||this.#I.setValue(t.id,t)}#xt(){const t=document.getSelection();if(!t||t.isCollapsed){if(this.#ot){this.#Q?.hide();this.#ot=null;this.#_t({hasSelectedText:!1})}return}const{anchorNode:e}=t;if(e===this.#ot)return;const i=this.#wt(t).closest(".textLayer");if(i){this.#Q?.hide();this.#ot=e;this.#_t({hasSelectedText:!0});if(this.#at===g.HIGHLIGHT||this.#at===g.NONE){this.#at===g.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0);this.#Y=this.isShiftKeyDown;if(!this.isShiftKeyDown){const t=this.#at===g.HIGHLIGHT?this.#vt(i):null;t?.toggleDrawing();const e=new AbortController,s=this.combinedSignal(e),pointerup=i=>{if("pointerup"!==i.type||0===i.button){e.abort();t?.toggleDrawing(!0);"pointerup"===i.type&&this.#Et("main_toolbar")}};window.addEventListener("pointerup",pointerup,{signal:s});window.addEventListener("blur",pointerup,{signal:s})}}}else if(this.#ot){this.#Q?.hide();this.#ot=null;this.#_t({hasSelectedText:!1})}}#Et(t=""){this.#at===g.HIGHLIGHT?this.highlightSelection(t):this.#$&&this.#yt()}#ft(){document.addEventListener("selectionchange",this.#xt.bind(this),{signal:this._signal})}#St(){if(this.#X)return;this.#X=new AbortController;const t=this.combinedSignal(this.#X);window.addEventListener("focus",this.focus.bind(this),{signal:t});window.addEventListener("blur",this.blur.bind(this),{signal:t})}#Ct(){this.#X?.abort();this.#X=null}blur(){this.isShiftKeyDown=!1;if(this.#Y){this.#Y=!1;this.#Et("main_toolbar")}if(!this.hasSelection)return;const{activeElement:t}=document;for(const e of this.#rt)if(e.div.contains(t)){this.#it=[e,t];e._focusEventsAllowed=!1;break}}focus(){if(!this.#it)return;const[t,e]=this.#it;this.#it=null;e.addEventListener("focusin",(()=>{t._focusEventsAllowed=!0}),{once:!0,signal:this._signal});e.focus()}#At(){if(this.#et)return;this.#et=new AbortController;const t=this.combinedSignal(this.#et);window.addEventListener("keydown",this.keydown.bind(this),{signal:t});window.addEventListener("keyup",this.keyup.bind(this),{signal:t})}#Tt(){this.#et?.abort();this.#et=null}#Mt(){if(this.#O)return;this.#O=new AbortController;const t=this.combinedSignal(this.#O);document.addEventListener("copy",this.copy.bind(this),{signal:t});document.addEventListener("cut",this.cut.bind(this),{signal:t});document.addEventListener("paste",this.paste.bind(this),{signal:t})}#Pt(){this.#O?.abort();this.#O=null}#bt(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t});document.addEventListener("drop",this.drop.bind(this),{signal:t})}addEditListeners(){this.#At();this.#Mt()}removeEditListeners(){this.#Tt();this.#Pt()}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const i of this.#U)if(i.isHandlingMimeForPasting(e)){t.dataTransfer.dropEffect="copy";t.preventDefault();return}}drop(t){for(const e of t.dataTransfer.items)for(const i of this.#U)if(i.isHandlingMimeForPasting(e.type)){i.paste(e,this.currentLayer);t.preventDefault();return}}copy(t){t.preventDefault();this.#P?.commitOrRemove();if(!this.hasSelection)return;const e=[];for(const t of this.#rt){const i=t.serialize(!0);i&&e.push(i)}0!==e.length&&t.clipboardData.setData("application/pdfjs",JSON.stringify(e))}cut(t){this.copy(t);this.delete()}async paste(t){t.preventDefault();const{clipboardData:e}=t;for(const t of e.items)for(const e of this.#U)if(e.isHandlingMimeForPasting(t.type)){e.paste(t,this.currentLayer);return}let i=e.getData("application/pdfjs");if(!i)return;try{i=JSON.parse(i)}catch(t){warn(`paste: "${t.message}".`);return}if(!Array.isArray(i))return;this.unselectAll();const s=this.currentLayer;try{const t=[];for(const e of i){const i=await s.deserialize(e);if(!i)return;t.push(i)}const cmd=()=>{for(const e of t)this.#Dt(e);this.#kt(t)},undo=()=>{for(const e of t)e.remove()};this.addCommands({cmd,undo,mustExec:!0})}catch(t){warn(`paste: "${t.message}".`)}}keydown(t){this.isShiftKeyDown||"Shift"!==t.key||(this.isShiftKeyDown=!0);this.#at===g.NONE||this.isEditorHandlingKeyboard||AnnotationEditorUIManager._keyboardManager.exec(this,t)}keyup(t){if(this.isShiftKeyDown&&"Shift"===t.key){this.isShiftKeyDown=!1;if(this.#Y){this.#Y=!1;this.#Et("main_toolbar")}}}onEditingAction({name:t}){switch(t){case"undo":case"redo":case"delete":case"selectAll":this[t]();break;case"highlightSelection":this.highlightSelection("context_menu")}}#_t(t){if(Object.entries(t).some((([t,e])=>this.#dt[t]!==e))){this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#dt,t)});this.#at===g.HIGHLIGHT&&!1===t.hasSelectedEditor&&this.#Rt([[m.HIGHLIGHT_FREE,!0]])}}#Rt(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){if(t){this.#St();this.#Mt();this.#_t({isEditing:this.#at!==g.NONE,isEmpty:this.#It(),hasSomethingToUndo:this.#L.hasSomethingToUndo(),hasSomethingToRedo:this.#L.hasSomethingToRedo(),hasSelectedEditor:!1})}else{this.#Ct();this.#Pt();this.#_t({isEditing:!1});this.disableUserSelect(!1)}}registerEditorTypes(t){if(!this.#U){this.#U=t;for(const t of this.#U)this.#Rt(t.defaultPropertiesToUpdate)}}getId(){return this.#J.id}get currentLayer(){return this.#k.get(this.#B)}getLayer(t){return this.#k.get(t)}get currentPageIndex(){return this.#B}addLayer(t){this.#k.set(t.pageIndex,t);this.#Z?t.enable():t.disable()}removeLayer(t){this.#k.delete(t.pageIndex)}async updateMode(t,e=null,i=!1){if(this.#at!==t){if(this.#mt){await this.#mt.promise;if(!this.#mt)return}this.#mt=Promise.withResolvers();this.#at=t;if(t!==g.NONE){this.setEditingState(!0);await this.#Ft();this.unselectAll();for(const e of this.#k.values())e.updateMode(t);if(e){for(const t of this.#D.values())if(t.annotationElementId===e){this.setSelected(t);t.enterInEditMode()}else t.unselect();this.#mt.resolve()}else{i&&this.addNewEditorFromKeyboard();this.#mt.resolve()}}else{this.setEditingState(!1);this.#Lt();this._editorUndoBar?.hide();this.#mt.resolve()}}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==this.#at&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,e){if(this.#U){switch(t){case m.CREATE:this.currentLayer.addNewEditor();return;case m.HIGHLIGHT_DEFAULT_COLOR:this.#st?.updateColor(e);break;case m.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}});(this.#ht||=new Map).set(t,e);this.showAllEditors("highlight",e)}for(const i of this.#rt)i.updateParams(t,e);for(const i of this.#U)i.updateDefaultParams(t,e)}}showAllEditors(t,e,i=!1){for(const i of this.#D.values())i.editorType===t&&i.show(e);(this.#ht?.get(m.HIGHLIGHT_SHOW_ALL)??!0)!==e&&this.#Rt([[m.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(this.#tt!==t){this.#tt=t;for(const e of this.#k.values()){t?e.disableClick():e.enableClick();e.div.classList.toggle("waiting",t)}}}async#Ft(){if(!this.#Z){this.#Z=!0;const t=[];for(const e of this.#k.values())t.push(e.enable());await Promise.all(t);for(const t of this.#D.values())t.enable()}}#Lt(){this.unselectAll();if(this.#Z){this.#Z=!1;for(const t of this.#k.values())t.disable();for(const t of this.#D.values())t.disable()}}getEditors(t){const e=[];for(const i of this.#D.values())i.pageIndex===t&&e.push(i);return e}getEditor(t){return this.#D.get(t)}addEditor(t){this.#D.set(t.id,t)}removeEditor(t){if(t.div.contains(document.activeElement)){this.#q&&clearTimeout(this.#q);this.#q=setTimeout((()=>{this.focusMainContainer();this.#q=null}),0)}this.#D.delete(t.id);this.unselect(t);t.annotationElementId&&this.#H.has(t.annotationElementId)||this.#I?.remove(t.id)}addDeletedAnnotationElement(t){this.#H.add(t.annotationElementId);this.addChangedExistingAnnotation(t);t.deleted=!0}isDeletedAnnotationElement(t){return this.#H.has(t)}removeDeletedAnnotationElement(t){this.#H.delete(t.annotationElementId);this.removeChangedExistingAnnotation(t);t.deleted=!1}#Dt(t){const e=this.#k.get(t.pageIndex);if(e)e.addOrRebuild(t);else{this.addEditor(t);this.addToAnnotationStorage(t)}}setActiveEditor(t){if(this.#P!==t){this.#P=t;t&&this.#Rt(t.propertiesToUpdate)}}get#Ot(){let t=null;for(t of this.#rt);return t}updateUI(t){this.#Ot===t&&this.#Rt(t.propertiesToUpdate)}updateUIForDefaultProperties(t){this.#Rt(t.defaultPropertiesToUpdate)}toggleSelected(t){if(this.#rt.has(t)){this.#rt.delete(t);t.unselect();this.#_t({hasSelectedEditor:this.hasSelection})}else{this.#rt.add(t);t.select();this.#Rt(t.propertiesToUpdate);this.#_t({hasSelectedEditor:!0})}}setSelected(t){this.#N?.commitOrRemove();for(const e of this.#rt)e!==t&&e.unselect();this.#rt.clear();this.#rt.add(t);t.select();this.#Rt(t.propertiesToUpdate);this.#_t({hasSelectedEditor:!0})}isSelected(t){return this.#rt.has(t)}get firstSelectedEditor(){return this.#rt.values().next().value}unselect(t){t.unselect();this.#rt.delete(t);this.#_t({hasSelectedEditor:this.hasSelection})}get hasSelection(){return 0!==this.#rt.size}get isEnterHandled(){return 1===this.#rt.size&&this.firstSelectedEditor.isEnterHandled}undo(){this.#L.undo();this.#_t({hasSomethingToUndo:this.#L.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#It()});this._editorUndoBar?.hide()}redo(){this.#L.redo();this.#_t({hasSomethingToUndo:!0,hasSomethingToRedo:this.#L.hasSomethingToRedo(),isEmpty:this.#It()})}addCommands(t){this.#L.add(t);this.#_t({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#It()})}cleanUndoStack(t){this.#L.cleanType(t)}#It(){if(0===this.#D.size)return!0;if(1===this.#D.size)for(const t of this.#D.values())return t.isEmpty();return!1}delete(){this.commitOrRemove();const t=this.currentLayer?.endDrawingSession(!0);if(!this.hasSelection&&!t)return;const e=t?[t]:[...this.#rt],undo=()=>{for(const t of e)this.#Dt(t)};this.addCommands({cmd:()=>{this._editorUndoBar?.show(undo,1===e.length?e[0].editorType:e.length);for(const t of e)t.remove()},undo,mustExec:!0})}commitOrRemove(){this.#P?.commitOrRemove()}hasSomethingToControl(){return this.#P||this.hasSelection}#kt(t){for(const t of this.#rt)t.unselect();this.#rt.clear();for(const e of t)if(!e.isEmpty()){this.#rt.add(e);e.select()}this.#_t({hasSelectedEditor:this.hasSelection})}selectAll(){for(const t of this.#rt)t.commit();this.#kt(this.#D.values())}unselectAll(){if(this.#P){this.#P.commitOrRemove();if(this.#at!==g.NONE)return}if(!this.#N?.commitOrRemove()&&this.hasSelection){for(const t of this.#rt)t.unselect();this.#rt.clear();this.#_t({hasSelectedEditor:!1})}}translateSelectedEditors(t,e,i=!1){i||this.commitOrRemove();if(!this.hasSelection)return;this.#ct[0]+=t;this.#ct[1]+=e;const[s,n]=this.#ct,a=[...this.#rt];this.#ut&&clearTimeout(this.#ut);this.#ut=setTimeout((()=>{this.#ut=null;this.#ct[0]=this.#ct[1]=0;this.addCommands({cmd:()=>{for(const t of a)this.#D.has(t.id)&&t.translateInPage(s,n)},undo:()=>{for(const t of a)this.#D.has(t.id)&&t.translateInPage(-s,-n)},mustExec:!1})}),1e3);for(const i of a)i.translateInPage(t,e)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0);this.#z=new Map;for(const t of this.#rt)this.#z.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#z)return!1;this.disableUserSelect(!1);const t=this.#z;this.#z=null;let e=!1;for(const[{x:i,y:s,pageIndex:n},a]of t){a.newX=i;a.newY=s;a.newPageIndex=n;e||=i!==a.savedX||s!==a.savedY||n!==a.savedPageIndex}if(!e)return!1;const move=(t,e,i,s)=>{if(this.#D.has(t.id)){const n=this.#k.get(s);if(n)t._setParentAndPosition(n,e,i);else{t.pageIndex=s;t.x=e;t.y=i}}};this.addCommands({cmd:()=>{for(const[e,{newX:i,newY:s,newPageIndex:n}]of t)move(e,i,s,n)},undo:()=>{for(const[e,{savedX:i,savedY:s,savedPageIndex:n}]of t)move(e,i,s,n)},mustExec:!0});return!0}dragSelectedEditors(t,e){if(this.#z)for(const i of this.#z.keys())i.drag(t,e)}rebuild(t){if(null===t.parent){const e=this.getLayer(t.pageIndex);if(e){e.changeParent(t);e.addOrRebuild(t)}else{this.addEditor(t);this.addToAnnotationStorage(t);t.rebuild()}}else t.parent.addOrRebuild(t)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||1===this.#rt.size&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#P===t}getActive(){return this.#P}getMode(){return this.#at}get imageManager(){return shadow(this,"imageManager",new ImageManager)}getSelectionBoxes(t){if(!t)return null;const e=document.getSelection();for(let i=0,s=e.rangeCount;i({x:(e-s)/a,y:1-(t+r-i)/n,width:o/a,height:r/n});break;case"180":r=(t,e,r,o)=>({x:1-(t+r-i)/n,y:1-(e+o-s)/a,width:r/n,height:o/a});break;case"270":r=(t,e,r,o)=>({x:1-(e+o-s)/a,y:(t-i)/n,width:o/a,height:r/n});break;default:r=(t,e,r,o)=>({x:(t-i)/n,y:(e-s)/a,width:r/n,height:o/a})}const o=[];for(let t=0,i=e.rangeCount;tt.stopPropagation()),{signal:i});const onClick=t=>{t.preventDefault();this.#a._uiManager.editAltText(this.#a);this.#Wt&&this.#a._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:this.#Xt}})};t.addEventListener("click",onClick,{capture:!0,signal:i});t.addEventListener("keydown",(e=>{if(e.target===t&&"Enter"===e.key){this.#Gt=!0;onClick(e)}}),{signal:i});await this.#Kt();return t}get#Xt(){return(this.#o?"added":null===this.#o&&this.guessedText&&"review")||"missing"}finish(){if(this.#Bt){this.#Bt.focus({focusVisible:this.#Gt});this.#Gt=!1}}isEmpty(){return this.#Wt?null===this.#o:!this.#o&&!this.#Nt}hasData(){return this.#Wt?null!==this.#o||!!this.#Vt:this.isEmpty()}get guessedText(){return this.#Vt}async setGuessedText(t){if(null===this.#o){this.#Vt=t;this.#jt=await AltText._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t});this.#Kt()}}toggleAltTextBadge(t=!1){if(this.#Wt&&!this.#o){if(!this.#$t){const t=this.#$t=document.createElement("div");t.className="noAltTextBadge";this.#a.div.append(t)}this.#$t.classList.toggle("hidden",!t)}else{this.#$t?.remove();this.#$t=null}}serialize(t){let e=this.#o;t||this.#Vt!==e||(e=this.#jt);return{altText:e,decorative:this.#Nt,guessedText:this.#Vt,textWithDisclaimer:this.#jt}}get data(){return{altText:this.#o,decorative:this.#Nt}}set data({altText:t,decorative:e,guessedText:i,textWithDisclaimer:s,cancel:n=!1}){if(i){this.#Vt=i;this.#jt=s}if(this.#o!==t||this.#Nt!==e){if(!n){this.#o=t;this.#Nt=e}this.#Kt()}}toggle(t=!1){if(this.#Bt){if(!t&&this.#Ut){clearTimeout(this.#Ut);this.#Ut=null}this.#Bt.disabled=!t}}shown(){this.#a._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:this.#Xt}})}destroy(){this.#Bt?.remove();this.#Bt=null;this.#Ht=null;this.#zt=null;this.#$t?.remove();this.#$t=null}async#Kt(){const t=this.#Bt;if(!t)return;if(this.#Wt){t.classList.toggle("done",!!this.#o);t.setAttribute("data-l10n-id",AltText.#qt[this.#Xt]);this.#Ht?.setAttribute("data-l10n-id",AltText.#qt[`${this.#Xt}-label`]);if(!this.#o){this.#zt?.remove();return}}else{if(!this.#o&&!this.#Nt){t.classList.remove("done");this.#zt?.remove();return}t.classList.add("done");t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let e=this.#zt;if(!e){this.#zt=e=document.createElement("span");e.className="tooltip";e.setAttribute("role","tooltip");e.id=`alt-text-tooltip-${this.#a.id}`;const i=100,s=this.#a._uiManager._signal;s.addEventListener("abort",(()=>{clearTimeout(this.#Ut);this.#Ut=null}),{once:!0});t.addEventListener("mouseenter",(()=>{this.#Ut=setTimeout((()=>{this.#Ut=null;this.#zt.classList.add("show");this.#a._reportTelemetry({action:"alt_text_tooltip"})}),i)}),{signal:s});t.addEventListener("mouseleave",(()=>{if(this.#Ut){clearTimeout(this.#Ut);this.#Ut=null}this.#zt?.classList.remove("show")}),{signal:s})}if(this.#Nt)e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip");else{e.removeAttribute("data-l10n-id");e.textContent=this.#o}e.parentNode||t.append(e);const i=this.#a.getImageForAltText();i?.setAttribute("aria-describedby",e.id)}}class TouchManager{#pt;#Yt=!1;#Qt=null;#Jt;#Zt;#te;#ee;#ie;#se=null;#ne;#ae=null;constructor({container:t,isPinchingDisabled:e=null,isPinchingStopped:i=null,onPinchStart:s=null,onPinching:n=null,onPinchEnd:a=null,signal:r}){this.#pt=t;this.#Qt=i;this.#Jt=e;this.#Zt=s;this.#te=n;this.#ee=a;this.#ne=new AbortController;this.#ie=AbortSignal.any([r,this.#ne.signal]);t.addEventListener("touchstart",this.#re.bind(this),{passive:!1,signal:this.#ie})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return shadow(this,"MIN_TOUCH_DISTANCE_TO_PINCH",35/(window.devicePixelRatio||1))}#re(t){if(this.#Jt?.()||t.touches.length<2)return;if(!this.#ae){this.#ae=new AbortController;const t=AbortSignal.any([this.#ie,this.#ae.signal]),e=this.#pt,i={signal:t,passive:!1};e.addEventListener("touchmove",this.#oe.bind(this),i);e.addEventListener("touchend",this.#le.bind(this),i);e.addEventListener("touchcancel",this.#le.bind(this),i);this.#Zt?.()}stopEvent(t);if(2!==t.touches.length||this.#Qt?.()){this.#se=null;return}let[e,i]=t.touches;e.identifier>i.identifier&&([e,i]=[i,e]);this.#se={touch0X:e.screenX,touch0Y:e.screenY,touch1X:i.screenX,touch1Y:i.screenY}}#oe(t){if(!this.#se||2!==t.touches.length)return;let[e,i]=t.touches;e.identifier>i.identifier&&([e,i]=[i,e]);const{screenX:s,screenY:n}=e,{screenX:a,screenY:r}=i,o=this.#se,{touch0X:l,touch0Y:h,touch1X:d,touch1Y:c}=o,u=d-l,p=c-h,g=a-s,m=r-n,f=Math.hypot(g,m)||1,b=Math.hypot(u,p)||1;if(!this.#Yt&&Math.abs(b-f)<=TouchManager.MIN_TOUCH_DISTANCE_TO_PINCH)return;o.touch0X=s;o.touch0Y=n;o.touch1X=a;o.touch1Y=r;t.preventDefault();if(!this.#Yt){this.#Yt=!0;return}const A=[(s+a)/2,(n+r)/2];this.#te?.(A,b,f)}#le(t){this.#ae.abort();this.#ae=null;this.#ee?.();if(this.#se){t.preventDefault();this.#se=null;this.#Yt=!1}}destroy(){this.#ne?.abort();this.#ne=null}}class AnnotationEditor{#he=null;#de=null;#o=null;#ce=!1;#ue=null;#pe="";#ge=!1;#me=null;#fe=null;#be=null;#Ae=null;#we="";#ve=!1;#ye=null;#xe=!1;#_e=!1;#Ee=!1;#Se=null;#Ce=0;#Te=0;#Me=null;#Pe=null;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nResizer=null;#De=!1;#ke=AnnotationEditor._zIndex++;static _borderLineWidth=-1;static _colorManager=new ColorManager;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){const t=AnnotationEditor.prototype._resizeWithKeyboard,e=AnnotationEditorUIManager.TRANSLATE_SMALL,i=AnnotationEditorUIManager.TRANSLATE_BIG;return shadow(this,"_resizerKeyboardManager",new KeyboardManager([[["ArrowLeft","mac+ArrowLeft"],t,{args:[-e,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-i,0]}],[["ArrowRight","mac+ArrowRight"],t,{args:[e,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[i,0]}],[["ArrowUp","mac+ArrowUp"],t,{args:[0,-e]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-i]}],[["ArrowDown","mac+ArrowDown"],t,{args:[0,e]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,i]}],[["Escape","mac+Escape"],AnnotationEditor.prototype._stopResizingWithKeyboard]]))}constructor(t){this.parent=t.parent;this.id=t.id;this.width=this.height=null;this.pageIndex=t.parent.pageIndex;this.name=t.name;this.div=null;this._uiManager=t.uiManager;this.annotationElementId=null;this._willKeepAspectRatio=!1;this._initialOptions.isCentered=t.isCentered;this._structTreeParentId=null;const{rotation:e,rawDims:{pageWidth:i,pageHeight:s,pageX:n,pageY:a}}=this.parent.viewport;this.rotation=e;this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360;this.pageDimensions=[i,s];this.pageTranslation=[n,a];const[r,o]=this.parentDimensions;this.x=t.x/r;this.y=t.y/o;this.isAttachedToDOM=!1;this.deleted=!1}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get isDrawer(){return!1}static get _defaultLineColor(){return shadow(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new FakeEditor({id:t.parent.getNextId(),parent:t.parent,uiManager:t._uiManager});e.annotationElementId=t.annotationElementId;e.deleted=!0;e._uiManager.addToAnnotationStorage(e)}static initialize(t,e){AnnotationEditor._l10n??=t;AnnotationEditor._l10nResizer||=Object.freeze({topLeft:"pdfjs-editor-resizer-top-left",topMiddle:"pdfjs-editor-resizer-top-middle",topRight:"pdfjs-editor-resizer-top-right",middleRight:"pdfjs-editor-resizer-middle-right",bottomRight:"pdfjs-editor-resizer-bottom-right",bottomMiddle:"pdfjs-editor-resizer-bottom-middle",bottomLeft:"pdfjs-editor-resizer-bottom-left",middleLeft:"pdfjs-editor-resizer-middle-left"});if(-1!==AnnotationEditor._borderLineWidth)return;const i=getComputedStyle(document.documentElement);AnnotationEditor._borderLineWidth=parseFloat(i.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){unreachable("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#De}set _isDraggable(t){this.#De=t;this.div?.classList.toggle("draggable",t)}get isEnterHandled(){return!0}center(){const[t,e]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*e/(2*t);this.y+=this.width*t/(2*e);break;case 180:this.x+=this.width/2;this.y+=this.height/2;break;case 270:this.x+=this.height*e/(2*t);this.y-=this.width*t/(2*e);break;default:this.x-=this.width/2;this.y-=this.height/2}this.fixAndSetPosition()}addCommands(t){this._uiManager.addCommands(t)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#ke}setParent(t){if(null!==t){this.pageIndex=t.pageIndex;this.pageDimensions=t.pageDimensions}else this.#Re();this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#ve?this.#ve=!1:this.parent.setSelected(this))}focusout(t){if(!this._focusEventsAllowed)return;if(!this.isAttachedToDOM)return;const e=t.relatedTarget;if(!e?.closest(`#${this.id}`)){t.preventDefault();this.parent?.isMultipleSelection||this.commitOrRemove()}}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(t,e,i,s){const[n,a]=this.parentDimensions;[i,s]=this.screenToPageTranslation(i,s);this.x=(t+i)/n;this.y=(e+s)/a;this.fixAndSetPosition()}#Ie([t,e],i,s){[i,s]=this.screenToPageTranslation(i,s);this.x+=i/t;this.y+=s/e;this._onTranslating(this.x,this.y);this.fixAndSetPosition()}translate(t,e){this.#Ie(this.parentDimensions,t,e)}translateInPage(t,e){this.#ye||=[this.x,this.y,this.width,this.height];this.#Ie(this.pageDimensions,t,e);this.div.scrollIntoView({block:"nearest"})}drag(t,e){this.#ye||=[this.x,this.y,this.width,this.height];const{div:i,parentDimensions:[s,n]}=this;this.x+=t/s;this.y+=e/n;if(this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:t,y:e}=this.div.getBoundingClientRect();if(this.parent.findNewParent(this,t,e)){this.x-=Math.floor(this.x);this.y-=Math.floor(this.y)}}let{x:a,y:r}=this;const[o,l]=this.getBaseTranslation();a+=o;r+=l;const{style:h}=i;h.left=`${(100*a).toFixed(2)}%`;h.top=`${(100*r).toFixed(2)}%`;this._onTranslating(a,r);i.scrollIntoView({block:"nearest"})}_onTranslating(t,e){}_onTranslated(t,e){}get _hasBeenMoved(){return!!this.#ye&&(this.#ye[0]!==this.x||this.#ye[1]!==this.y)}get _hasBeenResized(){return!!this.#ye&&(this.#ye[2]!==this.width||this.#ye[3]!==this.height)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:i}=AnnotationEditor,s=i/t,n=i/e;switch(this.rotation){case 90:return[-s,n];case 180:return[s,n];case 270:return[s,-n];default:return[-s,-n]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const{div:{style:e},pageDimensions:[i,s]}=this;let{x:n,y:a,width:r,height:o}=this;r*=i;o*=s;n*=i;a*=s;if(this._mustFixPosition)switch(t){case 0:n=Math.max(0,Math.min(i-r,n));a=Math.max(0,Math.min(s-o,a));break;case 90:n=Math.max(0,Math.min(i-o,n));a=Math.min(s,Math.max(r,a));break;case 180:n=Math.min(i,Math.max(r,n));a=Math.min(s,Math.max(o,a));break;case 270:n=Math.min(i,Math.max(o,n));a=Math.max(0,Math.min(s-r,a))}this.x=n/=i;this.y=a/=s;const[l,h]=this.getBaseTranslation();n+=l;a+=h;e.left=`${(100*n).toFixed(2)}%`;e.top=`${(100*a).toFixed(2)}%`;this.moveInDOM()}static#Fe(t,e,i){switch(i){case 90:return[e,-t];case 180:return[-t,-e];case 270:return[-e,t];default:return[t,e]}}screenToPageTranslation(t,e){return AnnotationEditor.#Fe(t,e,this.parentRotation)}pageTranslationToScreen(t,e){return AnnotationEditor.#Fe(t,e,360-this.parentRotation)}#Le(t){switch(t){case 90:{const[t,e]=this.pageDimensions;return[0,-t/e,e/t,0]}case 180:return[-1,0,0,-1];case 270:{const[t,e]=this.pageDimensions;return[0,t/e,-e/t,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:t,pageDimensions:[e,i]}=this;return[e*t,i*t]}setDims(t,e){const[i,s]=this.parentDimensions,{style:n}=this.div;n.width=`${(100*t/i).toFixed(2)}%`;this.#ge||(n.height=`${(100*e/s).toFixed(2)}%`)}fixDims(){const{style:t}=this.div,{height:e,width:i}=t,s=i.endsWith("%"),n=!this.#ge&&e.endsWith("%");if(s&&n)return;const[a,r]=this.parentDimensions;s||(t.width=`${(100*parseFloat(i)/a).toFixed(2)}%`);this.#ge||n||(t.height=`${(100*parseFloat(e)/r).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}#Oe(){if(this.#me)return;this.#me=document.createElement("div");this.#me.classList.add("resizers");const t=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],e=this._uiManager._signal;for(const i of t){const t=document.createElement("div");this.#me.append(t);t.classList.add("resizer",i);t.setAttribute("data-resizer-name",i);t.addEventListener("pointerdown",this.#Ne.bind(this,i),{signal:e});t.addEventListener("contextmenu",noContextMenu,{signal:e});t.tabIndex=-1}this.div.prepend(this.#me)}#Ne(t,e){e.preventDefault();const{isMac:i}=util_FeatureTest.platform;if(0!==e.button||e.ctrlKey&&i)return;this.#o?.toggle(!1);const s=this._isDraggable;this._isDraggable=!1;this.#fe=[e.screenX,e.screenY];const n=new AbortController,a=this._uiManager.combinedSignal(n);this.parent.togglePointerEvents(!1);window.addEventListener("pointermove",this.#Be.bind(this,t),{passive:!0,capture:!0,signal:a});window.addEventListener("touchmove",stopEvent,{passive:!1,signal:a});window.addEventListener("contextmenu",noContextMenu,{signal:a});this.#be={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const r=this.parent.div.style.cursor,o=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const pointerUpCallback=()=>{n.abort();this.parent.togglePointerEvents(!0);this.#o?.toggle(!0);this._isDraggable=s;this.parent.div.style.cursor=r;this.div.style.cursor=o;this.#He()};window.addEventListener("pointerup",pointerUpCallback,{signal:a});window.addEventListener("blur",pointerUpCallback,{signal:a})}#ze(t,e,i,s){this.width=i;this.height=s;this.x=t;this.y=e;const[n,a]=this.parentDimensions;this.setDims(n*i,a*s);this.fixAndSetPosition();this._onResized()}_onResized(){}#He(){if(!this.#be)return;const{savedX:t,savedY:e,savedWidth:i,savedHeight:s}=this.#be;this.#be=null;const n=this.x,a=this.y,r=this.width,o=this.height;n===t&&a===e&&r===i&&o===s||this.addCommands({cmd:this.#ze.bind(this,n,a,r,o),undo:this.#ze.bind(this,t,e,i,s),mustExec:!0})}static _round(t){return Math.round(1e4*t)/1e4}#Be(t,e){const[i,s]=this.parentDimensions,n=this.x,a=this.y,r=this.width,o=this.height,l=AnnotationEditor.MIN_SIZE/i,h=AnnotationEditor.MIN_SIZE/s,d=this.#Le(this.rotation),transf=(t,e)=>[d[0]*t+d[2]*e,d[1]*t+d[3]*e],c=this.#Le(360-this.rotation);let u,p,g=!1,m=!1;switch(t){case"topLeft":g=!0;u=(t,e)=>[0,0];p=(t,e)=>[t,e];break;case"topMiddle":u=(t,e)=>[t/2,0];p=(t,e)=>[t/2,e];break;case"topRight":g=!0;u=(t,e)=>[t,0];p=(t,e)=>[0,e];break;case"middleRight":m=!0;u=(t,e)=>[t,e/2];p=(t,e)=>[0,e/2];break;case"bottomRight":g=!0;u=(t,e)=>[t,e];p=(t,e)=>[0,0];break;case"bottomMiddle":u=(t,e)=>[t/2,e];p=(t,e)=>[t/2,0];break;case"bottomLeft":g=!0;u=(t,e)=>[0,e];p=(t,e)=>[t,0];break;case"middleLeft":m=!0;u=(t,e)=>[0,e/2];p=(t,e)=>[t,e/2]}const f=u(r,o),b=p(r,o);let A=transf(...b);const w=AnnotationEditor._round(n+A[0]),v=AnnotationEditor._round(a+A[1]);let y,x,_=1,E=1;if(e.fromKeyboard)({deltaX:y,deltaY:x}=e);else{const{screenX:t,screenY:i}=e,[s,n]=this.#fe;[y,x]=this.screenToPageTranslation(t-s,i-n);this.#fe[0]=t;this.#fe[1]=i}[y,x]=(S=y/i,C=x/s,[c[0]*S+c[2]*C,c[1]*S+c[3]*C]);var S,C;if(g){const t=Math.hypot(r,o);_=E=Math.max(Math.min(Math.hypot(b[0]-f[0]-y,b[1]-f[1]-x)/t,1/r,1/o),l/r,h/o)}else m?_=Math.max(l,Math.min(1,Math.abs(b[0]-f[0]-y)))/r:E=Math.max(h,Math.min(1,Math.abs(b[1]-f[1]-x)))/o;const T=AnnotationEditor._round(r*_),M=AnnotationEditor._round(o*E);A=transf(...p(T,M));const P=w-A[0],D=v-A[1];this.#ye||=[this.x,this.y,this.width,this.height];this.width=T;this.height=M;this.x=P;this.y=D;this.setDims(i*T,s*M);this.fixAndSetPosition();this._onResizing()}_onResizing(){}altTextFinish(){this.#o?.finish()}async addEditToolbar(){if(this._editToolbar||this.#_e)return this._editToolbar;this._editToolbar=new EditorToolbar(this);this.div.append(this._editToolbar.render());this.#o&&await this._editToolbar.addAltText(this.#o);return this._editToolbar}removeEditToolbar(){if(this._editToolbar){this._editToolbar.remove();this._editToolbar=null;this.#o?.destroy()}}addContainer(t){const e=this._editToolbar?.div;e?e.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){if(!this.#o){AltText.initialize(AnnotationEditor._l10n);this.#o=new AltText(this);if(this.#he){this.#o.data=this.#he;this.#he=null}await this.addEditToolbar()}}get altTextData(){return this.#o?.data}set altTextData(t){this.#o&&(this.#o.data=t)}get guessedAltText(){return this.#o?.guessedText}async setGuessedAltText(t){await(this.#o?.setGuessedText(t))}serializeAltText(t){return this.#o?.serialize(t)}hasAltText(){return!!this.#o&&!this.#o.isEmpty()}hasAltTextData(){return this.#o?.hasData()??!1}render(){this.div=document.createElement("div");this.div.setAttribute("data-editor-rotation",(360-this.rotation)%360);this.div.className=this.name;this.div.setAttribute("id",this.id);this.div.tabIndex=this.#ce?-1:0;this._isVisible||this.div.classList.add("hidden");this.setInForeground();this.#Ue();const[t,e]=this.parentDimensions;if(this.parentRotation%180!=0){this.div.style.maxWidth=`${(100*e/t).toFixed(2)}%`;this.div.style.maxHeight=`${(100*t/e).toFixed(2)}%`}const[i,s]=this.getInitialTranslation();this.translate(i,s);bindEvents(this,this.div,["pointerdown"]);this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#Pe||=new TouchManager({container:this.div,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#Ge.bind(this),onPinching:this.#$e.bind(this),onPinchEnd:this.#Ve.bind(this),signal:this._uiManager._signal}));this._uiManager._editorUndoBar?.hide();return this.div}#Ge(){this.#be={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};this.#o?.toggle(!1);this.parent.togglePointerEvents(!1)}#$e(t,e,i){let s=i/e*.7+1-.7;if(1===s)return;const n=this.#Le(this.rotation),transf=(t,e)=>[n[0]*t+n[2]*e,n[1]*t+n[3]*e],[a,r]=this.parentDimensions,o=this.x,l=this.y,h=this.width,d=this.height,c=AnnotationEditor.MIN_SIZE/a,u=AnnotationEditor.MIN_SIZE/r;s=Math.max(Math.min(s,1/h,1/d),c/h,u/d);const p=AnnotationEditor._round(h*s),g=AnnotationEditor._round(d*s);if(p===h&&g===d)return;this.#ye||=[o,l,h,d];const m=transf(h/2,d/2),f=AnnotationEditor._round(o+m[0]),b=AnnotationEditor._round(l+m[1]),A=transf(p/2,g/2);this.x=f-A[0];this.y=b-A[1];this.width=p;this.height=g;this.setDims(a*p,r*g);this.fixAndSetPosition();this._onResizing()}#Ve(){this.#o?.toggle(!0);this.parent.togglePointerEvents(!0);this.#He()}pointerdown(t){const{isMac:e}=util_FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)t.preventDefault();else{this.#ve=!0;this._isDraggable?this.#je(t):this.#We(t)}}get isSelected(){return this._uiManager.isSelected(this)}#We(t){const{isMac:e}=util_FeatureTest.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)}#je(t){const{isSelected:e}=this;this._uiManager.setUpDragSession();let i=!1;const s=new AbortController,n=this._uiManager.combinedSignal(s),a={capture:!0,passive:!1,signal:n},cancelDrag=t=>{s.abort();this.#ue=null;this.#ve=!1;this._uiManager.endDragSession()||this.#We(t);i&&this._onStopDragging()};if(e){this.#Ce=t.clientX;this.#Te=t.clientY;this.#ue=t.pointerId;this.#pe=t.pointerType;window.addEventListener("pointermove",(t=>{if(!i){i=!0;this._onStartDragging()}const{clientX:e,clientY:s,pointerId:n}=t;if(n!==this.#ue){stopEvent(t);return}const[a,r]=this.screenToPageTranslation(e-this.#Ce,s-this.#Te);this.#Ce=e;this.#Te=s;this._uiManager.dragSelectedEditors(a,r)}),a);window.addEventListener("touchmove",stopEvent,a);window.addEventListener("pointerdown",(t=>{t.pointerType===this.#pe&&(this.#Pe||t.isPrimary)&&cancelDrag(t);stopEvent(t)}),a)}const pointerUpCallback=t=>{this.#ue&&this.#ue!==t.pointerId?stopEvent(t):cancelDrag(t)};window.addEventListener("pointerup",pointerUpCallback,{signal:n});window.addEventListener("blur",pointerUpCallback,{signal:n})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#Se&&clearTimeout(this.#Se);this.#Se=setTimeout((()=>{this.#Se=null;this.parent?.moveEditorInDOM(this)}),0)}_setParentAndPosition(t,e,i){t.changeParent(this);this.x=e;this.y=i;this.fixAndSetPosition();this._onTranslated()}getRect(t,e,i=this.rotation){const s=this.parentScale,[n,a]=this.pageDimensions,[r,o]=this.pageTranslation,l=t/s,h=e/s,d=this.x*n,c=this.y*a,u=this.width*n,p=this.height*a;switch(i){case 0:return[d+l+r,a-c-h-p+o,d+l+u+r,a-c-h+o];case 90:return[d+h+r,a-c+l+o,d+h+p+r,a-c+l+u+o];case 180:return[d-l-u+r,a-c+h+o,d-l+r,a-c+h+p+o];case 270:return[d-h-p+r,a-c-l-u+o,d-h+r,a-c-l+o];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,e){const[i,s,n,a]=t,r=n-i,o=a-s;switch(this.rotation){case 0:return[i,e-a,r,o];case 90:return[i,e-s,o,r];case 180:return[n,e-s,r,o];case 270:return[n,e-a,o,r];default:throw new Error("Invalid rotation")}}onceAdded(t){}isEmpty(){return!1}enableEditMode(){this.#_e=!0}disableEditMode(){this.#_e=!1}isInEditMode(){return this.#_e}shouldGetKeyboardEvents(){return this.#Ee}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){const{top:t,left:e,bottom:i,right:s}=this.getClientDimensions(),{innerHeight:n,innerWidth:a}=window;return e0&&t0}#Ue(){if(this.#Ae||!this.div)return;this.#Ae=new AbortController;const t=this._uiManager.combinedSignal(this.#Ae);this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t});this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})}rebuild(){this.#Ue()}rotate(t){}resize(){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||""}}serialize(t=!1,e=null){unreachable("An editor must be serializable")}static async deserialize(t,e,i){const s=new this.prototype.constructor({parent:e,id:e.getNextId(),uiManager:i});s.rotation=t.rotation;s.#he=t.accessibilityData;const[n,a]=s.pageDimensions,[r,o,l,h]=s.getRectInCurrentCoords(t.rect,a);s.x=r/n;s.y=o/a;s.width=l/n;s.height=h/a;return s}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||null!==this.serialize())}remove(){this.#Ae?.abort();this.#Ae=null;this.isEmpty()||this.commit();this.parent?this.parent.remove(this):this._uiManager.removeEditor(this);if(this.#Se){clearTimeout(this.#Se);this.#Se=null}this.#Re();this.removeEditToolbar();if(this.#Me){for(const t of this.#Me.values())clearTimeout(t);this.#Me=null}this.parent=null;this.#Pe?.destroy();this.#Pe=null}get isResizable(){return!1}makeResizable(){if(this.isResizable){this.#Oe();this.#me.classList.remove("hidden");bindEvents(this,this.div,["keydown"])}}get toolbarPosition(){return null}keydown(t){if(!this.isResizable||t.target!==this.div||"Enter"!==t.key)return;this._uiManager.setSelected(this);this.#be={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const e=this.#me.children;if(!this.#de){this.#de=Array.from(e);const t=this.#qe.bind(this),i=this.#Xe.bind(this),s=this._uiManager._signal;for(const e of this.#de){const n=e.getAttribute("data-resizer-name");e.setAttribute("role","spinbutton");e.addEventListener("keydown",t,{signal:s});e.addEventListener("blur",i,{signal:s});e.addEventListener("focus",this.#Ke.bind(this,n),{signal:s});e.setAttribute("data-l10n-id",AnnotationEditor._l10nResizer[n])}}const i=this.#de[0];let s=0;for(const t of e){if(t===i)break;s++}const n=(360-this.rotation+this.parentRotation)%360/90*(this.#de.length/4);if(n!==s){if(ns)for(let t=0;t{this.div?.classList.contains("selectedEditor")&&this._editToolbar?.show()}))}unselect(){this.#me?.classList.add("hidden");this.div?.classList.remove("selectedEditor");this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0});this._editToolbar?.hide();this.#o?.toggleAltTextBadge(!0)}updateParams(t,e){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return this.#xe}set isEditing(t){this.#xe=t;if(this.parent)if(t){this.parent.setSelected(this);this.parent.setActiveEditor(this)}else this.parent.setActiveEditor(null)}setAspectRatio(t,e){this.#ge=!0;const i=t/e,{style:s}=this.div;s.aspectRatio=i;s.height="auto"}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(t,e=!1){if(e){this.#Me||=new Map;const{action:e}=t;let i=this.#Me.get(e);i&&clearTimeout(i);i=setTimeout((()=>{this._reportTelemetry(t);this.#Me.delete(e);0===this.#Me.size&&(this.#Me=null)}),AnnotationEditor._telemetryTimeout);this.#Me.set(e,i)}else{t.type||=this.editorType;this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:t}})}}show(t=this._isVisible){this.div.classList.toggle("hidden",!t);this._isVisible=t}enable(){this.div&&(this.div.tabIndex=0);this.#ce=!1}disable(){this.div&&(this.div.tabIndex=-1);this.#ce=!0}renderAnnotationElement(t){let e=t.container.querySelector(".annotationContent");if(e){if("CANVAS"===e.nodeName){const t=e;e=document.createElement("div");e.classList.add("annotationContent",this.editorType);t.before(e)}}else{e=document.createElement("div");e.classList.add("annotationContent",this.editorType);t.container.prepend(e)}return e}resetAnnotationElement(t){const{firstChild:e}=t.container;"DIV"===e?.nodeName&&e.classList.contains("annotationContent")&&e.remove()}}class FakeEditor extends AnnotationEditor{constructor(t){super(t);this.annotationElementId=t.annotationElementId;this.deleted=!0}serialize(){return this.serializeDeleted()}}const st=3285377520,nt=4294901760,at=65535;class MurmurHash3_64{constructor(t){this.h1=t?4294967295&t:st;this.h2=t?4294967295&t:st}update(t){let e,i;if("string"==typeof t){e=new Uint8Array(2*t.length);i=0;for(let s=0,n=t.length;s>>8;e[i++]=255&n}}}else{if(!ArrayBuffer.isView(t))throw new Error("Invalid data format, must be a string or TypedArray.");e=t.slice();i=e.byteLength}const s=i>>2,n=i-4*s,a=new Uint32Array(e.buffer,0,s);let r=0,o=0,l=this.h1,h=this.h2;const d=3432918353,c=461845907,u=11601,p=13715;for(let t=0;t>>17;r=r*c&nt|r*p&at;l^=r;l=l<<13|l>>>19;l=5*l+3864292196}else{o=a[t];o=o*d&nt|o*u&at;o=o<<15|o>>>17;o=o*c&nt|o*p&at;h^=o;h=h<<13|h>>>19;h=5*h+3864292196}r=0;switch(n){case 3:r^=e[4*s+2]<<16;case 2:r^=e[4*s+1]<<8;case 1:r^=e[4*s];r=r*d&nt|r*u&at;r=r<<15|r>>>17;r=r*c&nt|r*p&at;1&s?l^=r:h^=r}this.h1=l;this.h2=h}hexdigest(){let t=this.h1,e=this.h2;t^=e>>>1;t=3981806797*t&nt|36045*t&at;e=4283543511*e&nt|(2950163797*(e<<16|t>>>16)&nt)>>>16;t^=e>>>1;t=444984403*t&nt|60499*t&at;e=3301882366*e&nt|(3120437893*(e<<16|t>>>16)&nt)>>>16;t^=e>>>1;return(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const rt=Object.freeze({map:null,hash:"",transfer:void 0});class AnnotationStorage{#Qe=!1;#Je=null;#Ze=new Map;constructor(){this.onSetModified=null;this.onResetModified=null;this.onAnnotationEditor=null}getValue(t,e){const i=this.#Ze.get(t);return void 0===i?e:Object.assign(e,i)}getRawValue(t){return this.#Ze.get(t)}remove(t){this.#Ze.delete(t);0===this.#Ze.size&&this.resetModified();if("function"==typeof this.onAnnotationEditor){for(const t of this.#Ze.values())if(t instanceof AnnotationEditor)return;this.onAnnotationEditor(null)}}setValue(t,e){const i=this.#Ze.get(t);let s=!1;if(void 0!==i){for(const[t,n]of Object.entries(e))if(i[t]!==n){s=!0;i[t]=n}}else{s=!0;this.#Ze.set(t,e)}s&&this.#ti();e instanceof AnnotationEditor&&"function"==typeof this.onAnnotationEditor&&this.onAnnotationEditor(e.constructor._type)}has(t){return this.#Ze.has(t)}getAll(){return this.#Ze.size>0?objectFromMap(this.#Ze):null}setAll(t){for(const[e,i]of Object.entries(t))this.setValue(e,i)}get size(){return this.#Ze.size}#ti(){if(!this.#Qe){this.#Qe=!0;"function"==typeof this.onSetModified&&this.onSetModified()}}resetModified(){if(this.#Qe){this.#Qe=!1;"function"==typeof this.onResetModified&&this.onResetModified()}}get print(){return new PrintAnnotationStorage(this)}get serializable(){if(0===this.#Ze.size)return rt;const t=new Map,e=new MurmurHash3_64,i=[],s=Object.create(null);let n=!1;for(const[i,a]of this.#Ze){const r=a instanceof AnnotationEditor?a.serialize(!1,s):a;if(r){t.set(i,r);e.update(`${i}:${JSON.stringify(r)}`);n||=!!r.bitmap}}if(n)for(const e of t.values())e.bitmap&&i.push(e.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:i}:rt}get editorStats(){let t=null;const e=new Map;for(const i of this.#Ze.values()){if(!(i instanceof AnnotationEditor))continue;const s=i.telemetryFinalData;if(!s)continue;const{type:n}=s;e.has(n)||e.set(n,Object.getPrototypeOf(i).constructor);t||=Object.create(null);const a=t[n]||=new Map;for(const[t,e]of Object.entries(s)){if("type"===t)continue;let i=a.get(t);if(!i){i=new Map;a.set(t,i)}const s=i.get(e)??0;i.set(e,s+1)}}for(const[i,s]of e)t[i]=s.computeTelemetryFinalData(t[i]);return t}resetModifiedIds(){this.#Je=null}get modifiedIds(){if(this.#Je)return this.#Je;const t=[];for(const e of this.#Ze.values())e instanceof AnnotationEditor&&e.annotationElementId&&e.serialize()&&t.push(e.annotationElementId);return this.#Je={ids:new Set(t),hash:t.join(",")}}}class PrintAnnotationStorage extends AnnotationStorage{#ei;constructor(t){super();const{map:e,hash:i,transfer:s}=t.serializable,n=structuredClone(e,s?{transfer:s}:null);this.#ei={map:n,hash:i,transfer:s}}get print(){unreachable("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#ei}get modifiedIds(){return shadow(this,"modifiedIds",{ids:new Set,hash:""})}}class FontLoader{#ii=new Set;constructor({ownerDocument:t=globalThis.document,styleElement:e=null}){this._document=t;this.nativeFontFaces=new Set;this.styleElement=null;this.loadingRequests=[];this.loadTestFontId=0}addNativeFontFace(t){this.nativeFontFaces.add(t);this._document.fonts.add(t)}removeNativeFontFace(t){this.nativeFontFaces.delete(t);this._document.fonts.delete(t)}insertRule(t){if(!this.styleElement){this.styleElement=this._document.createElement("style");this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement)}const e=this.styleElement.sheet;e.insertRule(t,e.cssRules.length)}clear(){for(const t of this.nativeFontFaces)this._document.fonts.delete(t);this.nativeFontFaces.clear();this.#ii.clear();if(this.styleElement){this.styleElement.remove();this.styleElement=null}}async loadSystemFont({systemFontInfo:t,_inspectFont:e}){if(t&&!this.#ii.has(t.loadedName)){assert(!this.disableFontFace,"loadSystemFont shouldn't be called when `disableFontFace` is set.");if(this.isFontLoadingAPISupported){const{loadedName:i,src:s,style:n}=t,a=new FontFace(i,s,n);this.addNativeFontFace(a);try{await a.load();this.#ii.add(i);e?.(t)}catch{warn(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`);this.removeNativeFontFace(a)}}else unreachable("Not implemented: loadSystemFont without the Font Loading API.")}}async bind(t){if(t.attached||t.missingFile&&!t.systemFontInfo)return;t.attached=!0;if(t.systemFontInfo){await this.loadSystemFont(t);return}if(this.isFontLoadingAPISupported){const e=t.createNativeFontFace();if(e){this.addNativeFontFace(e);try{await e.loaded}catch(i){warn(`Failed to load font '${e.family}': '${i}'.`);t.disableFontFace=!0;throw i}}return}const e=t.createFontFaceRule();if(e){this.insertRule(e);if(this.isSyncFontLoadingSupported)return;await new Promise((e=>{const i=this._queueLoadingCallback(e);this._prepareFontLoadEvent(t,i)}))}}get isFontLoadingAPISupported(){return shadow(this,"isFontLoadingAPISupported",!!this._document?.fonts)}get isSyncFontLoadingSupported(){let t=!1;(e||"undefined"!=typeof navigator&&"string"==typeof navigator?.userAgent&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(t=!0);return shadow(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){const{loadingRequests:e}=this,i={done:!1,complete:function completeRequest(){assert(!i.done,"completeRequest() cannot be called twice.");i.done=!0;for(;e.length>0&&e[0].done;){const t=e.shift();setTimeout(t.callback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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA=="))}_prepareFontLoadEvent(t,e){function int32(t,e){return t.charCodeAt(e)<<24|t.charCodeAt(e+1)<<16|t.charCodeAt(e+2)<<8|255&t.charCodeAt(e+3)}function spliceString(t,e,i,s){return t.substring(0,e)+s+t.substring(e+i)}let i,s;const n=this._document.createElement("canvas");n.width=1;n.height=1;const a=n.getContext("2d");let r=0;const o=`lt${Date.now()}${this.loadTestFontId++}`;let l=this._loadTestFont;l=spliceString(l,976,o.length,o);const h=1482184792;let d=int32(l,16);for(i=0,s=o.length-3;i>24&255,t>>16&255,t>>8&255,255&t)}(d));const c=`@font-face {font-family:"${o}";src:${`url(data:font/opentype;base64,${btoa(l)});`}}`;this.insertRule(c);const u=this._document.createElement("div");u.style.visibility="hidden";u.style.width=u.style.height="10px";u.style.position="absolute";u.style.top=u.style.left="0px";for(const e of[t.loadedName,o]){const t=this._document.createElement("span");t.textContent="Hi";t.style.fontFamily=e;u.append(t)}this._document.body.append(u);!function isFontReady(t,e){if(++r>30){warn("Load test font never loaded.");e();return}a.font="30px "+t;a.fillText(".",0,20);a.getImageData(0,0,1,1).data[3]>0?e():setTimeout(isFontReady.bind(null,t,e))}(o,(()=>{u.remove();e.complete()}))}}class FontFaceObject{constructor(t,{disableFontFace:e=!1,fontExtraProperties:i=!1,inspectFont:s=null}){this.compiledGlyphs=Object.create(null);for(const e in t)this[e]=t[e];this.disableFontFace=!0===e;this.fontExtraProperties=!0===i;this._inspectFont=s}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let t;if(this.cssFontInfo){const e={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(e.style=`oblique ${this.cssFontInfo.italicAngle}deg`);t=new FontFace(this.cssFontInfo.fontFamily,this.data,e)}else t=new FontFace(this.loadedName,this.data,{});this._inspectFont?.(this);return t}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;const t=`url(data:${this.mimetype};base64,${function toBase64Util(t){return Uint8Array.prototype.toBase64?t.toBase64():btoa(bytesToString(t))}(this.data)});`;let e;if(this.cssFontInfo){let i=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(i+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`);e=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${i}src:${t}}`}else e=`@font-face {font-family:"${this.loadedName}";src:${t}}`;this._inspectFont?.(this,t);return e}getPathGenerator(t,e){if(void 0!==this.compiledGlyphs[e])return this.compiledGlyphs[e];const i=this.loadedName+"_path_"+e;let s;try{s=t.get(i)}catch(t){warn(`getPathGenerator - ignoring character: "${t}".`)}const n=new Path2D(s||"");this.fontExtraProperties||t.delete(i);return this.compiledGlyphs[e]=n}}const ot=1,lt=2,ht=1,dt=2,ct=3,ut=4,pt=5,gt=6,mt=7,ft=8;function onFn(){}function wrapReason(t){if(t instanceof AbortException||t instanceof InvalidPDFException||t instanceof MissingPDFException||t instanceof PasswordException||t instanceof UnexpectedResponseException||t instanceof UnknownErrorException)return t;t instanceof Error||"object"==typeof t&&null!==t||unreachable('wrapReason: Expected "reason" to be a (possibly cloned) Error.');switch(t.name){case"AbortException":return new AbortException(t.message);case"InvalidPDFException":return new InvalidPDFException(t.message);case"MissingPDFException":return new MissingPDFException(t.message);case"PasswordException":return new PasswordException(t.message,t.code);case"UnexpectedResponseException":return new UnexpectedResponseException(t.message,t.status);case"UnknownErrorException":return new UnknownErrorException(t.message,t.details)}return new UnknownErrorException(t.message,t.toString())}class MessageHandler{#si=new AbortController;constructor(t,e,i){this.sourceName=t;this.targetName=e;this.comObj=i;this.callbackId=1;this.streamId=1;this.streamSinks=Object.create(null);this.streamControllers=Object.create(null);this.callbackCapabilities=Object.create(null);this.actionHandler=Object.create(null);i.addEventListener("message",this.#ni.bind(this),{signal:this.#si.signal})}#ni({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream){this.#ai(t);return}if(t.callback){const e=t.callbackId,i=this.callbackCapabilities[e];if(!i)throw new Error(`Cannot resolve callback ${e}`);delete this.callbackCapabilities[e];if(t.callback===ot)i.resolve(t.data);else{if(t.callback!==lt)throw new Error("Unexpected callback case");i.reject(wrapReason(t.reason))}return}const e=this.actionHandler[t.action];if(!e)throw new Error(`Unknown action from worker: ${t.action}`);if(t.callbackId){const i=this.sourceName,s=t.sourceName,n=this.comObj;Promise.try(e,t.data).then((function(e){n.postMessage({sourceName:i,targetName:s,callback:ot,callbackId:t.callbackId,data:e})}),(function(e){n.postMessage({sourceName:i,targetName:s,callback:lt,callbackId:t.callbackId,reason:wrapReason(e)})}))}else t.streamId?this.#ri(t):e(t.data)}on(t,e){const i=this.actionHandler;if(i[t])throw new Error(`There is already an actionName called "${t}"`);i[t]=e}send(t,e,i){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,data:e},i)}sendWithPromise(t,e,i){const s=this.callbackId++,n=Promise.withResolvers();this.callbackCapabilities[s]=n;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:s,data:e},i)}catch(t){n.reject(t)}return n.promise}sendWithStream(t,e,i,s){const n=this.streamId++,a=this.sourceName,r=this.targetName,o=this.comObj;return new ReadableStream({start:i=>{const l=Promise.withResolvers();this.streamControllers[n]={controller:i,startCall:l,pullCall:null,cancelCall:null,isClosed:!1};o.postMessage({sourceName:a,targetName:r,action:t,streamId:n,data:e,desiredSize:i.desiredSize},s);return l.promise},pull:t=>{const e=Promise.withResolvers();this.streamControllers[n].pullCall=e;o.postMessage({sourceName:a,targetName:r,stream:gt,streamId:n,desiredSize:t.desiredSize});return e.promise},cancel:t=>{assert(t instanceof Error,"cancel must have a valid reason");const e=Promise.withResolvers();this.streamControllers[n].cancelCall=e;this.streamControllers[n].isClosed=!0;o.postMessage({sourceName:a,targetName:r,stream:ht,streamId:n,reason:wrapReason(t)});return e.promise}},i)}#ri(t){const e=t.streamId,i=this.sourceName,s=t.sourceName,n=this.comObj,a=this,r=this.actionHandler[t.action],o={enqueue(t,a=1,r){if(this.isCancelled)return;const o=this.desiredSize;this.desiredSize-=a;if(o>0&&this.desiredSize<=0){this.sinkCapability=Promise.withResolvers();this.ready=this.sinkCapability.promise}n.postMessage({sourceName:i,targetName:s,stream:ut,streamId:e,chunk:t},r)},close(){if(!this.isCancelled){this.isCancelled=!0;n.postMessage({sourceName:i,targetName:s,stream:ct,streamId:e});delete a.streamSinks[e]}},error(t){assert(t instanceof Error,"error must have a valid reason");if(!this.isCancelled){this.isCancelled=!0;n.postMessage({sourceName:i,targetName:s,stream:pt,streamId:e,reason:wrapReason(t)})}},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};o.sinkCapability.resolve();o.ready=o.sinkCapability.promise;this.streamSinks[e]=o;Promise.try(r,t.data,o).then((function(){n.postMessage({sourceName:i,targetName:s,stream:ft,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:i,targetName:s,stream:ft,streamId:e,reason:wrapReason(t)})}))}#ai(t){const e=t.streamId,i=this.sourceName,s=t.sourceName,n=this.comObj,a=this.streamControllers[e],r=this.streamSinks[e];switch(t.stream){case ft:t.success?a.startCall.resolve():a.startCall.reject(wrapReason(t.reason));break;case mt:t.success?a.pullCall.resolve():a.pullCall.reject(wrapReason(t.reason));break;case gt:if(!r){n.postMessage({sourceName:i,targetName:s,stream:mt,streamId:e,success:!0});break}r.desiredSize<=0&&t.desiredSize>0&&r.sinkCapability.resolve();r.desiredSize=t.desiredSize;Promise.try(r.onPull||onFn).then((function(){n.postMessage({sourceName:i,targetName:s,stream:mt,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:i,targetName:s,stream:mt,streamId:e,reason:wrapReason(t)})}));break;case ut:assert(a,"enqueue should have stream controller");if(a.isClosed)break;a.controller.enqueue(t.chunk);break;case ct:assert(a,"close should have stream controller");if(a.isClosed)break;a.isClosed=!0;a.controller.close();this.#oi(a,e);break;case pt:assert(a,"error should have stream controller");a.controller.error(wrapReason(t.reason));this.#oi(a,e);break;case dt:t.success?a.cancelCall.resolve():a.cancelCall.reject(wrapReason(t.reason));this.#oi(a,e);break;case ht:if(!r)break;const o=wrapReason(t.reason);Promise.try(r.onCancel||onFn,o).then((function(){n.postMessage({sourceName:i,targetName:s,stream:dt,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:i,targetName:s,stream:dt,streamId:e,reason:wrapReason(t)})}));r.sinkCapability.reject(o);r.isCancelled=!0;delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}}async#oi(t,e){await Promise.allSettled([t.startCall?.promise,t.pullCall?.promise,t.cancelCall?.promise]);delete this.streamControllers[e]}destroy(){this.#si?.abort();this.#si=null}}class BaseCanvasFactory{#li=!1;constructor({enableHWA:t=!1}){this.#li=t}create(t,e){if(t<=0||e<=0)throw new Error("Invalid canvas size");const i=this._createCanvas(t,e);return{canvas:i,context:i.getContext("2d",{willReadFrequently:!this.#li})}}reset(t,e,i){if(!t.canvas)throw new Error("Canvas is not specified");if(e<=0||i<=0)throw new Error("Invalid canvas size");t.canvas.width=e;t.canvas.height=i}destroy(t){if(!t.canvas)throw new Error("Canvas is not specified");t.canvas.width=0;t.canvas.height=0;t.canvas=null;t.context=null}_createCanvas(t,e){unreachable("Abstract method `_createCanvas` called.")}}class BaseCMapReaderFactory{constructor({baseUrl:t=null,isCompressed:e=!0}){this.baseUrl=t;this.isCompressed=e}async fetch({name:t}){if(!this.baseUrl)throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.");if(!t)throw new Error("CMap name must be specified.");const e=this.baseUrl+t+(this.isCompressed?".bcmap":"");return this._fetch(e).then((t=>({cMapData:t,isCompressed:this.isCompressed}))).catch((t=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${e}`)}))}async _fetch(t){unreachable("Abstract method `_fetch` called.")}}class DOMCMapReaderFactory extends BaseCMapReaderFactory{async _fetch(t){const e=await fetchData(t,this.isCompressed?"arraybuffer":"text");return e instanceof ArrayBuffer?new Uint8Array(e):stringToBytes(e)}}class BaseFilterFactory{addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addHighlightHCMFilter(t,e,i,s,n){return"none"}destroy(t=!1){}}class BaseStandardFontDataFactory{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");if(!t)throw new Error("Font filename must be specified.");const e=`${this.baseUrl}${t}`;return this._fetch(e).catch((t=>{throw new Error(`Unable to load font data at: ${e}`)}))}async _fetch(t){unreachable("Abstract method `_fetch` called.")}}class DOMStandardFontDataFactory extends BaseStandardFontDataFactory{async _fetch(t){const e=await fetchData(t,"arraybuffer");return new Uint8Array(e)}}e&&warn("Please use the `legacy` build in Node.js environments.");async function node_utils_fetchData(t){const e=process.getBuiltinModule("fs"),i=await e.promises.readFile(t);return new Uint8Array(i)}const bt="Fill",At="Stroke",wt="Shading";function applyBoundingBox(t,e){if(!e)return;const i=e[2]-e[0],s=e[3]-e[1],n=new Path2D;n.rect(e[0],e[1],i,s);t.clip(n)}class BaseShadingPattern{getPattern(){unreachable("Abstract method `getPattern` called.")}}class RadialAxialShadingPattern extends BaseShadingPattern{constructor(t){super();this._type=t[1];this._bbox=t[2];this._colorStops=t[3];this._p0=t[4];this._p1=t[5];this._r0=t[6];this._r1=t[7];this.matrix=null}_createGradient(t){let e;"axial"===this._type?e=t.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):"radial"===this._type&&(e=t.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(const t of this._colorStops)e.addColorStop(t[0],t[1]);return e}getPattern(t,e,i,s){let n;if(s===At||s===bt){const a=e.current.getClippedPathBoundingBox(s,getCurrentTransform(t))||[0,0,0,0],r=Math.ceil(a[2]-a[0])||1,o=Math.ceil(a[3]-a[1])||1,l=e.cachedCanvases.getCanvas("pattern",r,o),h=l.context;h.clearRect(0,0,h.canvas.width,h.canvas.height);h.beginPath();h.rect(0,0,h.canvas.width,h.canvas.height);h.translate(-a[0],-a[1]);i=Util.transform(i,[1,0,0,1,a[0],a[1]]);h.transform(...e.baseTransform);this.matrix&&h.transform(...this.matrix);applyBoundingBox(h,this._bbox);h.fillStyle=this._createGradient(h);h.fill();n=t.createPattern(l.canvas,"no-repeat");const d=new DOMMatrix(i);n.setTransform(d)}else{applyBoundingBox(t,this._bbox);n=this._createGradient(t)}return n}}function drawTriangle(t,e,i,s,n,a,r,o){const l=e.coords,h=e.colors,d=t.data,c=4*t.width;let u;if(l[i+1]>l[s+1]){u=i;i=s;s=u;u=a;a=r;r=u}if(l[s+1]>l[n+1]){u=s;s=n;n=u;u=r;r=o;o=u}if(l[i+1]>l[s+1]){u=i;i=s;s=u;u=a;a=r;r=u}const p=(l[i]+e.offsetX)*e.scaleX,g=(l[i+1]+e.offsetY)*e.scaleY,m=(l[s]+e.offsetX)*e.scaleX,f=(l[s+1]+e.offsetY)*e.scaleY,b=(l[n]+e.offsetX)*e.scaleX,A=(l[n+1]+e.offsetY)*e.scaleY;if(g>=A)return;const w=h[a],v=h[a+1],y=h[a+2],x=h[r],_=h[r+1],E=h[r+2],S=h[o],C=h[o+1],T=h[o+2],M=Math.round(g),P=Math.round(A);let D,k,R,I,F,L,O,N;for(let t=M;t<=P;t++){if(tA?1:f===A?0:(f-t)/(f-A);D=m-(m-b)*e;k=x-(x-S)*e;R=_-(_-C)*e;I=E-(E-T)*e}let e;e=tA?1:(g-t)/(g-A);F=p-(p-b)*e;L=w-(w-S)*e;O=v-(v-C)*e;N=y-(y-T)*e;const i=Math.round(Math.min(D,F)),s=Math.round(Math.max(D,F));let n=c*t+4*i;for(let t=i;t<=s;t++){e=(D-t)/(D-F);e<0?e=0:e>1&&(e=1);d[n++]=k-(k-L)*e|0;d[n++]=R-(R-O)*e|0;d[n++]=I-(I-N)*e|0;d[n++]=255}}}function drawFigure(t,e,i){const s=e.coords,n=e.colors;let a,r;switch(e.type){case"lattice":const o=e.verticesPerRow,l=Math.floor(s.length/o)-1,h=o-1;for(a=0;a=Math.ceil(p*b)?w=o:y=!0;E>=Math.ceil(g*A)?v=l:x=!0;const S=this.getSizeAndScale(w,this.ctx.canvas.width,b),C=this.getSizeAndScale(v,this.ctx.canvas.height,A),T=t.cachedCanvases.getCanvas("pattern",S.size,C.size),M=T.context,P=r.createCanvasGraphics(M);P.groupLevel=t.groupLevel;this.setFillAndStrokeStyleToContext(P,s,a);M.translate(-S.scale*h,-C.scale*d);P.transform(S.scale,0,0,C.scale,0,0);M.save();this.clipBbox(P,h,d,c,u);P.baseTransform=getCurrentTransform(P.ctx);P.executeOperatorList(i);P.endDrawing();M.restore();if(y||x){const e=T.canvas;y&&(w=o);x&&(v=l);const i=this.getSizeAndScale(w,this.ctx.canvas.width,b),s=this.getSizeAndScale(v,this.ctx.canvas.height,A),n=i.size,a=s.size,r=t.cachedCanvases.getCanvas("pattern-workaround",n,a),c=r.context,u=y?Math.floor(p/o):0,m=x?Math.floor(g/l):0;for(let t=0;t<=u;t++)for(let i=0;i<=m;i++)c.drawImage(e,n*t,a*i,n,a,0,0,n,a);return{canvas:r.canvas,scaleX:i.scale,scaleY:s.scale,offsetX:h,offsetY:d}}return{canvas:T.canvas,scaleX:S.scale,scaleY:C.scale,offsetX:h,offsetY:d}}getSizeAndScale(t,e,i){const s=Math.max(TilingPattern.MAX_PATTERN_SIZE,e);let n=Math.ceil(t*i);n>=s?n=s:i=n/t;return{scale:i,size:n}}clipBbox(t,e,i,s,n){const a=s-e,r=n-i;t.ctx.rect(e,i,a,r);t.current.updateRectMinMax(getCurrentTransform(t.ctx),[e,i,s,n]);t.clip();t.endPath()}setFillAndStrokeStyleToContext(t,e,i){const s=t.ctx,n=t.current;switch(e){case vt:const t=this.ctx;s.fillStyle=t.fillStyle;s.strokeStyle=t.strokeStyle;n.fillColor=t.fillStyle;n.strokeColor=t.strokeStyle;break;case yt:const a=Util.makeHexColor(i[0],i[1],i[2]);s.fillStyle=a;s.strokeStyle=a;n.fillColor=a;n.strokeColor=a;break;default:throw new FormatError(`Unsupported paint type: ${e}`)}}getPattern(t,e,i,s){let n=i;if(s!==wt){n=Util.transform(n,e.baseTransform);this.matrix&&(n=Util.transform(n,this.matrix))}const a=this.createPatternCanvas(e);let r=new DOMMatrix(n);r=r.translate(a.offsetX,a.offsetY);r=r.scale(1/a.scaleX,1/a.scaleY);const o=t.createPattern(a.canvas,"repeat");o.setTransform(r);return o}}function convertBlackAndWhiteToRGBA({src:t,srcPos:e=0,dest:i,width:s,height:n,nonBlackColor:a=4294967295,inverseDecode:r=!1}){const o=util_FeatureTest.isLittleEndian?4278190080:255,[l,h]=r?[a,o]:[o,a],d=s>>3,c=7&s,u=t.length;i=new Uint32Array(i.buffer);let p=0;for(let s=0;s>2),m=i.length,f=s+7>>3,b=4294967295,A=util_FeatureTest.isLittleEndian?4278190080:255;for(u=0;uf?s:8*t-7,r=-8&a;let o=0,c=0;for(;n>=1}}for(;l=a){g=n;m=s*g}l=0;for(p=m;p--;){c[l++]=d[h++];c[l++]=d[h++];c[l++]=d[h++];c[l++]=255}t.putImageData(o,0,u*xt)}}}function putBinaryImageMask(t,e){if(e.bitmap){t.drawImage(e.bitmap,0,0);return}const i=e.height,s=e.width,n=i%xt,a=(i-n)/xt,r=0===n?a:a+1,o=t.createImageData(s,xt);let l=0;const h=e.data,d=o.data;for(let e=0;e10&&"function"==typeof i,h=l?Date.now()+15:0;let d=0;const c=this.commonObjs,u=this.objs;let p;for(;;){if(void 0!==s&&r===s.nextBreakPoint){s.breakIt(r,i);return r}p=a[r];if(p!==X.dependency)this[p].apply(this,n[r]);else for(const t of n[r]){const e=t.startsWith("g_")?c:u;if(!e.has(t)){e.get(t,i);return r}}r++;if(r===o)return r;if(l&&++d>10){if(Date.now()>h){i();return r}d=0}}}#hi(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null;this.ctx.restore();if(this.transparentCanvas){this.ctx=this.compositeCtx;this.ctx.save();this.ctx.setTransform(1,0,0,1,0,0);this.ctx.drawImage(this.transparentCanvas,0,0);this.ctx.restore();this.transparentCanvas=null}}endDrawing(){this.#hi();this.cachedCanvases.clear();this.cachedPatterns.clear();for(const t of this._cachedBitmapsMap.values()){for(const e of t.values())"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement&&(e.width=e.height=0);t.clear()}this._cachedBitmapsMap.clear();this.#di()}#di(){if(this.pageColors){const t=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if("none"!==t){const e=this.ctx.filter;this.ctx.filter=t;this.ctx.drawImage(this.ctx.canvas,0,0);this.ctx.filter=e}}}_scaleImage(t,e){const i=t.width??t.displayWidth,s=t.height??t.displayHeight;let n,a,r=Math.max(Math.hypot(e[0],e[1]),1),o=Math.max(Math.hypot(e[2],e[3]),1),l=i,h=s,d="prescale1";for(;r>2&&l>1||o>2&&h>1;){let e=l,i=h;if(r>2&&l>1){e=l>=16384?Math.floor(l/2)-1||1:Math.ceil(l/2);r/=l/e}if(o>2&&h>1){i=h>=16384?Math.floor(h/2)-1||1:Math.ceil(h)/2;o/=h/i}n=this.cachedCanvases.getCanvas(d,e,i);a=n.context;a.clearRect(0,0,e,i);a.drawImage(t,0,0,l,h,0,0,e,i);t=n.canvas;l=e;h=i;d="prescale1"===d?"prescale2":"prescale1"}return{img:t,paintWidth:l,paintHeight:h}}_createMaskCanvas(t){const e=this.ctx,{width:i,height:s}=t,n=this.current.fillColor,a=this.current.patternFill,r=getCurrentTransform(e);let o,l,h,d;if((t.bitmap||t.data)&&t.count>1){const e=t.bitmap||t.data.buffer;l=JSON.stringify(a?r:[r.slice(0,4),n]);o=this._cachedBitmapsMap.get(e);if(!o){o=new Map;this._cachedBitmapsMap.set(e,o)}const i=o.get(l);if(i&&!a){return{canvas:i,offsetX:Math.round(Math.min(r[0],r[2])+r[4]),offsetY:Math.round(Math.min(r[1],r[3])+r[5])}}h=i}if(!h){d=this.cachedCanvases.getCanvas("maskCanvas",i,s);putBinaryImageMask(d.context,t)}let c=Util.transform(r,[1/i,0,0,-1/s,0,0]);c=Util.transform(c,[1,0,0,1,0,-s]);const[u,p,g,m]=Util.getAxialAlignedBoundingBox([0,0,i,s],c),f=Math.round(g-u)||1,b=Math.round(m-p)||1,A=this.cachedCanvases.getCanvas("fillCanvas",f,b),w=A.context,v=u,y=p;w.translate(-v,-y);w.transform(...c);if(!h){h=this._scaleImage(d.canvas,getCurrentTransformInverse(w));h=h.img;o&&a&&o.set(l,h)}w.imageSmoothingEnabled=getImageSmoothingEnabled(getCurrentTransform(w),t.interpolate);drawImageAtIntegerCoords(w,h,0,0,h.width,h.height,0,0,i,s);w.globalCompositeOperation="source-in";const x=Util.transform(getCurrentTransformInverse(w),[1,0,0,1,-v,-y]);w.fillStyle=a?n.getPattern(e,this,x,bt):n;w.fillRect(0,0,i,s);if(o&&!a){this.cachedCanvases.delete("fillCanvas");o.set(l,A.canvas)}return{canvas:A.canvas,offsetX:Math.round(v),offsetY:Math.round(y)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1);this.current.lineWidth=t;this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=_t[t]}setLineJoin(t){this.ctx.lineJoin=Et[t]}setMiterLimit(t){this.ctx.miterLimit=t}setDash(t,e){const i=this.ctx;if(void 0!==i.setLineDash){i.setLineDash(t);i.lineDashOffset=e}}setRenderingIntent(t){}setFlatness(t){}setGState(t){for(const[e,i]of t)switch(e){case"LW":this.setLineWidth(i);break;case"LC":this.setLineCap(i);break;case"LJ":this.setLineJoin(i);break;case"ML":this.setMiterLimit(i);break;case"D":this.setDash(i[0],i[1]);break;case"RI":this.setRenderingIntent(i);break;case"FL":this.setFlatness(i);break;case"Font":this.setFont(i[0],i[1]);break;case"CA":this.current.strokeAlpha=i;break;case"ca":this.current.fillAlpha=i;this.ctx.globalAlpha=i;break;case"BM":this.ctx.globalCompositeOperation=i;break;case"SMask":this.current.activeSMask=i?this.tempSMask:null;this.tempSMask=null;this.checkSMaskState();break;case"TR":this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(i)}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){const t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode():!this.current.activeSMask&&t&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const t=this.ctx.canvas.width,e=this.ctx.canvas.height,i="smaskGroupAt"+this.groupLevel,s=this.cachedCanvases.getCanvas(i,t,e);this.suspendedCtx=this.ctx;this.ctx=s.context;const n=this.ctx;n.setTransform(...getCurrentTransform(this.suspendedCtx));copyCtxState(this.suspendedCtx,n);!function mirrorContextOperations(t,e){if(t._removeMirroring)throw new Error("Context is already forwarding operations.");t.__originalSave=t.save;t.__originalRestore=t.restore;t.__originalRotate=t.rotate;t.__originalScale=t.scale;t.__originalTranslate=t.translate;t.__originalTransform=t.transform;t.__originalSetTransform=t.setTransform;t.__originalResetTransform=t.resetTransform;t.__originalClip=t.clip;t.__originalMoveTo=t.moveTo;t.__originalLineTo=t.lineTo;t.__originalBezierCurveTo=t.bezierCurveTo;t.__originalRect=t.rect;t.__originalClosePath=t.closePath;t.__originalBeginPath=t.beginPath;t._removeMirroring=()=>{t.save=t.__originalSave;t.restore=t.__originalRestore;t.rotate=t.__originalRotate;t.scale=t.__originalScale;t.translate=t.__originalTranslate;t.transform=t.__originalTransform;t.setTransform=t.__originalSetTransform;t.resetTransform=t.__originalResetTransform;t.clip=t.__originalClip;t.moveTo=t.__originalMoveTo;t.lineTo=t.__originalLineTo;t.bezierCurveTo=t.__originalBezierCurveTo;t.rect=t.__originalRect;t.closePath=t.__originalClosePath;t.beginPath=t.__originalBeginPath;delete t._removeMirroring};t.save=function ctxSave(){e.save();this.__originalSave()};t.restore=function ctxRestore(){e.restore();this.__originalRestore()};t.translate=function ctxTranslate(t,i){e.translate(t,i);this.__originalTranslate(t,i)};t.scale=function ctxScale(t,i){e.scale(t,i);this.__originalScale(t,i)};t.transform=function ctxTransform(t,i,s,n,a,r){e.transform(t,i,s,n,a,r);this.__originalTransform(t,i,s,n,a,r)};t.setTransform=function ctxSetTransform(t,i,s,n,a,r){e.setTransform(t,i,s,n,a,r);this.__originalSetTransform(t,i,s,n,a,r)};t.resetTransform=function ctxResetTransform(){e.resetTransform();this.__originalResetTransform()};t.rotate=function ctxRotate(t){e.rotate(t);this.__originalRotate(t)};t.clip=function ctxRotate(t){e.clip(t);this.__originalClip(t)};t.moveTo=function(t,i){e.moveTo(t,i);this.__originalMoveTo(t,i)};t.lineTo=function(t,i){e.lineTo(t,i);this.__originalLineTo(t,i)};t.bezierCurveTo=function(t,i,s,n,a,r){e.bezierCurveTo(t,i,s,n,a,r);this.__originalBezierCurveTo(t,i,s,n,a,r)};t.rect=function(t,i,s,n){e.rect(t,i,s,n);this.__originalRect(t,i,s,n)};t.closePath=function(){e.closePath();this.__originalClosePath()};t.beginPath=function(){e.beginPath();this.__originalBeginPath()}}(n,this.suspendedCtx);this.setGState([["BM","source-over"],["ca",1],["CA",1]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring();copyCtxState(this.ctx,this.suspendedCtx);this.ctx=this.suspendedCtx;this.suspendedCtx=null}compose(t){if(!this.current.activeSMask)return;if(t){t[0]=Math.floor(t[0]);t[1]=Math.floor(t[1]);t[2]=Math.ceil(t[2]);t[3]=Math.ceil(t[3])}else t=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const e=this.current.activeSMask,i=this.suspendedCtx;this.composeSMask(i,e,this.ctx,t);this.ctx.save();this.ctx.setTransform(1,0,0,1,0,0);this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height);this.ctx.restore()}composeSMask(t,e,i,s){const n=s[0],a=s[1],r=s[2]-n,o=s[3]-a;if(0!==r&&0!==o){this.genericComposeSMask(e.context,i,r,o,e.subtype,e.backdrop,e.transferMap,n,a,e.offsetX,e.offsetY);t.save();t.globalAlpha=1;t.globalCompositeOperation="source-over";t.setTransform(1,0,0,1,0,0);t.drawImage(i.canvas,0,0);t.restore()}}genericComposeSMask(t,e,i,s,n,a,r,o,l,h,d){let c=t.canvas,u=o-h,p=l-d;if(a){const e=Util.makeHexColor(...a);if(u<0||p<0||u+i>c.width||p+s>c.height){const t=this.cachedCanvases.getCanvas("maskExtension",i,s),n=t.context;n.drawImage(c,-u,-p);n.globalCompositeOperation="destination-atop";n.fillStyle=e;n.fillRect(0,0,i,s);n.globalCompositeOperation="source-over";c=t.canvas;u=p=0}else{t.save();t.globalAlpha=1;t.setTransform(1,0,0,1,0,0);const n=new Path2D;n.rect(u,p,i,s);t.clip(n);t.globalCompositeOperation="destination-atop";t.fillStyle=e;t.fillRect(u,p,i,s);t.restore()}}e.save();e.globalAlpha=1;e.setTransform(1,0,0,1,0,0);"Alpha"===n&&r?e.filter=this.filterFactory.addAlphaFilter(r):"Luminosity"===n&&(e.filter=this.filterFactory.addLuminosityFilter(r));const g=new Path2D;g.rect(o,l,i,s);e.clip(g);e.globalCompositeOperation="destination-in";e.drawImage(c,u,p,i,s,o,l,i,s);e.restore()}save(){if(this.inSMaskMode){copyCtxState(this.ctx,this.suspendedCtx);this.suspendedCtx.save()}else this.ctx.save();const t=this.current;this.stateStack.push(t);this.current=t.clone()}restore(){0===this.stateStack.length&&this.inSMaskMode&&this.endSMaskMode();if(0!==this.stateStack.length){this.current=this.stateStack.pop();if(this.inSMaskMode){this.suspendedCtx.restore();copyCtxState(this.suspendedCtx,this.ctx)}else this.ctx.restore();this.checkSMaskState();this.pendingClip=null;this._cachedScaleForStroking[0]=-1;this._cachedGetSinglePixelWidth=null}}transform(t,e,i,s,n,a){this.ctx.transform(t,e,i,s,n,a);this._cachedScaleForStroking[0]=-1;this._cachedGetSinglePixelWidth=null}constructPath(t,e,i){const s=this.ctx,n=this.current;let a,r,o=n.x,l=n.y;const h=getCurrentTransform(s),d=0===h[0]&&0===h[3]||0===h[1]&&0===h[2],c=d?i.slice(0):null;for(let i=0,u=0,p=t.length;i100&&(h=100);this.current.fontSizeScale=e/h;this.ctx.font=`${l} ${o} ${h}px ${r}`}setTextRenderingMode(t){this.current.textRenderingMode=t}setTextRise(t){this.current.textRise=t}moveText(t,e){this.current.x=this.current.lineX+=t;this.current.y=this.current.lineY+=e}setLeadingMoveText(t,e){this.setLeading(-e);this.moveText(t,e)}setTextMatrix(t,e,i,s,n,a){this.current.textMatrix=[t,e,i,s,n,a];this.current.textMatrixScale=Math.hypot(t,e);this.current.x=this.current.lineX=0;this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}#ci(t,e,i){const s=new Path2D;s.addPath(t,new DOMMatrix(i).invertSelf().multiplySelf(e));return s}paintChar(t,e,i,s,n){const a=this.ctx,r=this.current,o=r.font,l=r.textRenderingMode,h=r.fontSize/r.fontSizeScale,d=l&y,c=!!(l&x),u=r.patternFill&&!o.missingFile,p=r.patternStroke&&!o.missingFile;let g;(o.disableFontFace||c||u||p)&&(g=o.getPathGenerator(this.commonObjs,t));if(o.disableFontFace||u||p){a.save();a.translate(e,i);a.scale(h,-h);if(d===b||d===w)if(s){const t=a.getTransform();a.setTransform(...s);a.fill(this.#ci(g,t,s))}else a.fill(g);if(d===A||d===w)if(n){const t=a.getTransform();a.setTransform(...n);a.stroke(this.#ci(g,t,n))}else{a.lineWidth/=h;a.stroke(g)}a.restore()}else{d!==b&&d!==w||a.fillText(t,e,i);d!==A&&d!==w||a.strokeText(t,e,i)}if(c){(this.pendingTextPaths||=[]).push({transform:getCurrentTransform(a),x:e,y:i,fontSize:h,path:g})}}get isFontSubpixelAAEnabled(){const{context:t}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);t.scale(1.5,1);t.fillText("I",0,10);const e=t.getImageData(0,0,10,10).data;let i=!1;for(let t=3;t0&&e[t]<255){i=!0;break}return shadow(this,"isFontSubpixelAAEnabled",i)}showText(t){const e=this.current,i=e.font;if(i.isType3Font)return this.showType3Text(t);const s=e.fontSize;if(0===s)return;const n=this.ctx,a=e.fontSizeScale,r=e.charSpacing,o=e.wordSpacing,l=e.fontDirection,h=e.textHScale*l,d=t.length,c=i.vertical,u=c?1:-1,p=i.defaultVMetrics,g=s*e.fontMatrix[0],m=e.textRenderingMode===b&&!i.disableFontFace&&!e.patternFill;n.save();n.transform(...e.textMatrix);n.translate(e.x,e.y+e.textRise);l>0?n.scale(h,-1):n.scale(h,1);let f,v;if(e.patternFill){n.save();const t=e.fillColor.getPattern(n,this,getCurrentTransformInverse(n),bt);f=getCurrentTransform(n);n.restore();n.fillStyle=t}if(e.patternStroke){n.save();const t=e.strokeColor.getPattern(n,this,getCurrentTransformInverse(n),At);v=getCurrentTransform(n);n.restore();n.strokeStyle=t}let x=e.lineWidth;const _=e.textMatrixScale;if(0===_||0===x){const t=e.textRenderingMode&y;t!==A&&t!==w||(x=this.getSinglePixelWidth())}else x/=_;if(1!==a){n.scale(a,a);x/=a}n.lineWidth=x;if(i.isInvalidPDFjsFont){const i=[];let s=0;for(const e of t){i.push(e.unicode);s+=e.width}n.fillText(i.join(""),0,0);e.x+=s*g*h;n.restore();this.compose();return}let E,S=0;for(E=0;E0){const t=1e3*n.measureText(b).width/s*a;if(xnew CanvasGraphics(t,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};e=new TilingPattern(t,i,this.ctx,n,s)}else e=this._getPattern(t[1],t[2]);return e}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments);this.current.patternStroke=!0}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments);this.current.patternFill=!0}setStrokeRGBColor(t,e,i){this.ctx.strokeStyle=this.current.strokeColor=Util.makeHexColor(t,e,i);this.current.patternStroke=!1}setStrokeTransparent(){this.ctx.strokeStyle=this.current.strokeColor="transparent";this.current.patternStroke=!1}setFillRGBColor(t,e,i){this.ctx.fillStyle=this.current.fillColor=Util.makeHexColor(t,e,i);this.current.patternFill=!1}setFillTransparent(){this.ctx.fillStyle=this.current.fillColor="transparent";this.current.patternFill=!1}_getPattern(t,e=null){let i;if(this.cachedPatterns.has(t))i=this.cachedPatterns.get(t);else{i=function getShadingPattern(t){switch(t[0]){case"RadialAxial":return new RadialAxialShadingPattern(t);case"Mesh":return new MeshShadingPattern(t);case"Dummy":return new DummyShadingPattern}throw new Error(`Unknown IR type: ${t[0]}`)}(this.getObject(t));this.cachedPatterns.set(t,i)}e&&(i.matrix=e);return i}shadingFill(t){if(!this.contentVisible)return;const e=this.ctx;this.save();const i=this._getPattern(t);e.fillStyle=i.getPattern(e,this,getCurrentTransformInverse(e),wt);const s=getCurrentTransformInverse(e);if(s){const{width:t,height:i}=e.canvas,[n,a,r,o]=Util.getAxialAlignedBoundingBox([0,0,t,i],s);this.ctx.fillRect(n,a,r-n,o-a)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox());this.restore()}beginInlineImage(){unreachable("Should not call beginInlineImage")}beginImageData(){unreachable("Should not call beginImageData")}paintFormXObjectBegin(t,e){if(this.contentVisible){this.save();this.baseTransformStack.push(this.baseTransform);t&&this.transform(...t);this.baseTransform=getCurrentTransform(this.ctx);if(e){const t=e[2]-e[0],i=e[3]-e[1];this.ctx.rect(e[0],e[1],t,i);this.current.updateRectMinMax(getCurrentTransform(this.ctx),e);this.clip();this.endPath()}}}paintFormXObjectEnd(){if(this.contentVisible){this.restore();this.baseTransform=this.baseTransformStack.pop()}}beginGroup(t){if(!this.contentVisible)return;this.save();if(this.inSMaskMode){this.endSMaskMode();this.current.activeSMask=null}const e=this.ctx;t.isolated||info("TODO: Support non-isolated groups.");t.knockout&&warn("Knockout groups not supported.");const i=getCurrentTransform(e);t.matrix&&e.transform(...t.matrix);if(!t.bbox)throw new Error("Bounding box is required.");let s=Util.getAxialAlignedBoundingBox(t.bbox,getCurrentTransform(e));const n=[0,0,e.canvas.width,e.canvas.height];s=Util.intersect(s,n)||[0,0,0,0];const a=Math.floor(s[0]),r=Math.floor(s[1]),o=Math.max(Math.ceil(s[2])-a,1),l=Math.max(Math.ceil(s[3])-r,1);this.current.startNewPathAndClipBox([0,0,o,l]);let h="groupAt"+this.groupLevel;t.smask&&(h+="_smask_"+this.smaskCounter++%2);const d=this.cachedCanvases.getCanvas(h,o,l),c=d.context;c.translate(-a,-r);c.transform(...i);if(t.smask)this.smaskStack.push({canvas:d.canvas,context:c,offsetX:a,offsetY:r,subtype:t.smask.subtype,backdrop:t.smask.backdrop,transferMap:t.smask.transferMap||null,startTransformInverse:null});else{e.setTransform(1,0,0,1,0,0);e.translate(a,r);e.save()}copyCtxState(e,c);this.ctx=c;this.setGState([["BM","source-over"],["ca",1],["CA",1]]);this.groupStack.push(e);this.groupLevel++}endGroup(t){if(!this.contentVisible)return;this.groupLevel--;const e=this.ctx,i=this.groupStack.pop();this.ctx=i;this.ctx.imageSmoothingEnabled=!1;if(t.smask){this.tempSMask=this.smaskStack.pop();this.restore()}else{this.ctx.restore();const t=getCurrentTransform(this.ctx);this.restore();this.ctx.save();this.ctx.setTransform(...t);const i=Util.getAxialAlignedBoundingBox([0,0,e.canvas.width,e.canvas.height],t);this.ctx.drawImage(e.canvas,0,0);this.ctx.restore();this.compose(i)}}beginAnnotation(t,e,i,s,n){this.#hi();resetCtxToDefault(this.ctx);this.ctx.save();this.save();this.baseTransform&&this.ctx.setTransform(...this.baseTransform);if(e){const s=e[2]-e[0],a=e[3]-e[1];if(n&&this.annotationCanvasMap){(i=i.slice())[4]-=e[0];i[5]-=e[1];(e=e.slice())[0]=e[1]=0;e[2]=s;e[3]=a;const[n,r]=Util.singularValueDecompose2dScale(getCurrentTransform(this.ctx)),{viewportScale:o}=this,l=Math.ceil(s*this.outputScaleX*o),h=Math.ceil(a*this.outputScaleY*o);this.annotationCanvas=this.canvasFactory.create(l,h);const{canvas:d,context:c}=this.annotationCanvas;this.annotationCanvasMap.set(t,d);this.annotationCanvas.savedCtx=this.ctx;this.ctx=c;this.ctx.save();this.ctx.setTransform(n,0,0,-r,0,a*r);resetCtxToDefault(this.ctx)}else{resetCtxToDefault(this.ctx);this.endPath();this.ctx.rect(e[0],e[1],s,a);this.ctx.clip();this.ctx.beginPath()}}this.current=new CanvasExtraState(this.ctx.canvas.width,this.ctx.canvas.height);this.transform(...i);this.transform(...s)}endAnnotation(){if(this.annotationCanvas){this.ctx.restore();this.#di();this.ctx=this.annotationCanvas.savedCtx;delete this.annotationCanvas.savedCtx;delete this.annotationCanvas}}paintImageMaskXObject(t){if(!this.contentVisible)return;const e=t.count;(t=this.getObject(t.data,t)).count=e;const i=this.ctx,s=this.processingType3;if(s){void 0===s.compiled&&(s.compiled=function compileType3Glyph(t){const{width:e,height:i}=t;if(e>1e3||i>1e3)return null;const s=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),n=e+1;let a,r,o,l=new Uint8Array(n*(i+1));const h=e+7&-8;let d=new Uint8Array(h*i),c=0;for(const e of t.data){let t=128;for(;t>0;){d[c++]=e&t?0:255;t>>=1}}let u=0;c=0;if(0!==d[c]){l[0]=1;++u}for(r=1;r>2)+(d[c+1]?4:0)+(d[c-h+1]?8:0);if(s[t]){l[o+r]=s[t];++u}c++}if(d[c-h]!==d[c]){l[o+r]=d[c]?2:4;++u}if(u>1e3)return null}c=h*(i-1);o=a*n;if(0!==d[c]){l[o]=8;++u}for(r=1;r1e3)return null;const p=new Int32Array([0,n,-1,0,-n,0,0,0,1]),g=new Path2D;for(a=0;u&&a<=i;a++){let t=a*n;const i=t+e;for(;t>4;l[t]&=r>>2|r<<2}g.lineTo(t%n,t/n|0);l[t]||--u}while(s!==t);--a}d=null;l=null;return function(t){t.save();t.scale(1/e,-1/i);t.translate(0,-i);t.fill(g);t.beginPath();t.restore()}}(t));if(s.compiled){s.compiled(i);return}}const n=this._createMaskCanvas(t),a=n.canvas;i.save();i.setTransform(1,0,0,1,0,0);i.drawImage(a,n.offsetX,n.offsetY);i.restore();this.compose()}paintImageMaskXObjectRepeat(t,e,i=0,s=0,n,a){if(!this.contentVisible)return;t=this.getObject(t.data,t);const r=this.ctx;r.save();const o=getCurrentTransform(r);r.transform(e,i,s,n,0,0);const l=this._createMaskCanvas(t);r.setTransform(1,0,0,1,l.offsetX-o[4],l.offsetY-o[5]);for(let t=0,h=a.length;te?h/e:1;r=l>e?l/e:1}}this._cachedScaleForStroking[0]=a;this._cachedScaleForStroking[1]=r}return this._cachedScaleForStroking}rescaleAndStroke(t){const{ctx:e}=this,{lineWidth:i}=this.current,[s,n]=this.getScaleForStroking();e.lineWidth=i||1;if(1===s&&1===n){e.stroke();return}const a=e.getLineDash();t&&e.save();e.scale(s,n);if(a.length>0){const t=Math.max(s,n);e.setLineDash(a.map((e=>e/t)));e.lineDashOffset/=t}e.stroke();t&&e.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}}for(const t in X)void 0!==CanvasGraphics.prototype[t]&&(CanvasGraphics.prototype[X[t]]=CanvasGraphics.prototype[t]);class GlobalWorkerOptions{static#ui=null;static#pi="";static get workerPort(){return this.#ui}static set workerPort(t){if(!("undefined"!=typeof Worker&&t instanceof Worker)&&null!==t)throw new Error("Invalid `workerPort` type.");this.#ui=t}static get workerSrc(){return this.#pi}static set workerSrc(t){if("string"!=typeof t)throw new Error("Invalid `workerSrc` type.");this.#pi=t}}class Metadata{#gi;#mi;constructor({parsedData:t,rawData:e}){this.#gi=t;this.#mi=e}getRaw(){return this.#mi}get(t){return this.#gi.get(t)??null}getAll(){return objectFromMap(this.#gi)}has(t){return this.#gi.has(t)}}const Tt=Symbol("INTERNAL");class OptionalContentGroup{#fi=!1;#bi=!1;#Ai=!1;#wi=!0;constructor(t,{name:e,intent:i,usage:s,rbGroups:n}){this.#fi=!!(t&r);this.#bi=!!(t&o);this.name=e;this.intent=i;this.usage=s;this.rbGroups=n}get visible(){if(this.#Ai)return this.#wi;if(!this.#wi)return!1;const{print:t,view:e}=this.usage;return this.#fi?"OFF"!==e?.viewState:!this.#bi||"OFF"!==t?.printState}_setVisible(t,e,i=!1){t!==Tt&&unreachable("Internal method `_setVisible` called.");this.#Ai=i;this.#wi=e}}class OptionalContentConfig{#vi=null;#yi=new Map;#xi=null;#_i=null;constructor(t,e=r){this.renderingIntent=e;this.name=null;this.creator=null;if(null!==t){this.name=t.name;this.creator=t.creator;this.#_i=t.order;for(const i of t.groups)this.#yi.set(i.id,new OptionalContentGroup(e,i));if("OFF"===t.baseState)for(const t of this.#yi.values())t._setVisible(Tt,!1);for(const e of t.on)this.#yi.get(e)._setVisible(Tt,!0);for(const e of t.off)this.#yi.get(e)._setVisible(Tt,!1);this.#xi=this.getHash()}}#Ei(t){const e=t.length;if(e<2)return!0;const i=t[0];for(let s=1;s0?objectFromMap(this.#yi):null}getGroup(t){return this.#yi.get(t)||null}getHash(){if(null!==this.#vi)return this.#vi;const t=new MurmurHash3_64;for(const[e,i]of this.#yi)t.update(`${e}:${i.visible}`);return this.#vi=t.hexdigest()}}class PDFDataTransportStream{constructor(t,{disableRange:e=!1,disableStream:i=!1}){assert(t,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');const{length:s,initialData:n,progressiveDone:a,contentDispositionFilename:r}=t;this._queuedChunks=[];this._progressiveDone=a;this._contentDispositionFilename=r;if(n?.length>0){const t=n instanceof Uint8Array&&n.byteLength===n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer;this._queuedChunks.push(t)}this._pdfDataRangeTransport=t;this._isStreamingSupported=!i;this._isRangeSupported=!e;this._contentLength=s;this._fullRequestReader=null;this._rangeReaders=[];t.addRangeListener(((t,e)=>{this._onReceiveData({begin:t,chunk:e})}));t.addProgressListener(((t,e)=>{this._onProgress({loaded:t,total:e})}));t.addProgressiveReadListener((t=>{this._onReceiveData({chunk:t})}));t.addProgressiveDoneListener((()=>{this._onProgressiveDone()}));t.transportReady()}_onReceiveData({begin:t,chunk:e}){const i=e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer;if(void 0===t)this._fullRequestReader?this._fullRequestReader._enqueue(i):this._queuedChunks.push(i);else{assert(this._rangeReaders.some((function(e){if(e._begin!==t)return!1;e._enqueue(i);return!0})),"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}_onProgress(t){void 0===t.total?this._rangeReaders[0]?.onProgress?.({loaded:t.loaded}):this._fullRequestReader?.onProgress?.({loaded:t.loaded,total:t.total})}_onProgressiveDone(){this._fullRequestReader?.progressiveDone();this._progressiveDone=!0}_removeRangeReader(t){const e=this._rangeReaders.indexOf(t);e>=0&&this._rangeReaders.splice(e,1)}getFullReader(){assert(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;this._queuedChunks=null;return new PDFDataTransportStreamReader(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new PDFDataTransportStreamRangeReader(this,t,e);this._pdfDataRangeTransport.requestDataRange(t,e);this._rangeReaders.push(i);return i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeReaders.slice(0))e.cancel(t);this._pdfDataRangeTransport.abort()}}class PDFDataTransportStreamReader{constructor(t,e,i=!1,s=null){this._stream=t;this._done=i||!1;this._filename=isPdfFile(s)?s:null;this._queuedChunks=e||[];this._loaded=0;for(const t of this._queuedChunks)this._loaded+=t.byteLength;this._requests=[];this._headersReady=Promise.resolve();t._fullRequestReader=this;this.onProgress=null}_enqueue(t){if(!this._done){if(this._requests.length>0){this._requests.shift().resolve({value:t,done:!1})}else this._queuedChunks.push(t);this._loaded+=t.byteLength}}get headersReady(){return this._headersReady}get filename(){return this._filename}get isRangeSupported(){return this._stream._isRangeSupported}get isStreamingSupported(){return this._stream._isStreamingSupported}get contentLength(){return this._stream._contentLength}async read(){if(this._queuedChunks.length>0){return{value:this._queuedChunks.shift(),done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||(this._done=!0)}}class PDFDataTransportStreamRangeReader{constructor(t,e,i){this._stream=t;this._begin=e;this._end=i;this._queuedChunk=null;this._requests=[];this._done=!1;this.onProgress=null}_enqueue(t){if(!this._done){if(0===this._requests.length)this._queuedChunk=t;else{this._requests.shift().resolve({value:t,done:!1});for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}this._done=!0;this._stream._removeRangeReader(this)}}get isStreamingSupported(){return!1}async read(){if(this._queuedChunk){const t=this._queuedChunk;this._queuedChunk=null;return{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0;this._stream._removeRangeReader(this)}}function createHeaders(t,e){const i=new Headers;if(!t||!e||"object"!=typeof e)return i;for(const t in e){const s=e[t];void 0!==s&&i.append(t,s)}return i}function getResponseOrigin(t){try{return new URL(t).origin}catch{}return null}function validateRangeRequestCapabilities({responseHeaders:t,isHttp:e,rangeChunkSize:i,disableRange:s}){const n={allowRangeRequests:!1,suggestedLength:void 0},a=parseInt(t.get("Content-Length"),10);if(!Number.isInteger(a))return n;n.suggestedLength=a;if(a<=2*i)return n;if(s||!e)return n;if("bytes"!==t.get("Accept-Ranges"))return n;if("identity"!==(t.get("Content-Encoding")||"identity"))return n;n.allowRangeRequests=!0;return n}function extractFilenameFromHeader(t){const e=t.get("Content-Disposition");if(e){let t=function getFilenameFromContentDispositionHeader(t){let e=!0,i=toParamRegExp("filename\\*","i").exec(t);if(i){i=i[1];let t=rfc2616unquote(i);t=unescape(t);t=rfc5987decode(t);t=rfc2047decode(t);return fixupEncoding(t)}i=function rfc2231getparam(t){const e=[];let i;const s=toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;null!==(i=s.exec(t));){let[,t,s,n]=i;t=parseInt(t,10);if(t in e){if(0===t)break}else e[t]=[s,n]}const n=[];for(let t=0;t{t._responseOrigin=getResponseOrigin(e.url);if(!validateResponseStatus(e.status))throw createResponseStatusError(e.status,s);this._reader=e.body.getReader();this._headersCapability.resolve();const i=e.headers,{allowRangeRequests:n,suggestedLength:a}=validateRangeRequestCapabilities({responseHeaders:i,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=n;this._contentLength=a||this._contentLength;this._filename=extractFilenameFromHeader(i);!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new AbortException("Streaming is disabled."))})).catch(this._headersCapability.reject);this.onProgress=null}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._headersCapability.promise;const{value:t,done:e}=await this._reader.read();if(e)return{value:t,done:e};this._loaded+=t.byteLength;this.onProgress?.({loaded:this._loaded,total:this._contentLength});return{value:getArrayBuffer(t),done:!1}}cancel(t){this._reader?.cancel(t);this._abortController.abort()}}class PDFFetchStreamRangeReader{constructor(t,e,i){this._stream=t;this._reader=null;this._loaded=0;const s=t.source;this._withCredentials=s.withCredentials||!1;this._readCapability=Promise.withResolvers();this._isStreamingSupported=!s.disableStream;this._abortController=new AbortController;const n=new Headers(t.headers);n.append("Range",`bytes=${e}-${i-1}`);const a=s.url;fetch(a,createFetchOptions(n,this._withCredentials,this._abortController)).then((e=>{const i=getResponseOrigin(e.url);if(i!==t._responseOrigin)throw new Error(`Expected range response-origin "${i}" to match "${t._responseOrigin}".`);if(!validateResponseStatus(e.status))throw createResponseStatusError(e.status,a);this._readCapability.resolve();this._reader=e.body.getReader()})).catch(this._readCapability.reject);this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();if(e)return{value:t,done:e};this._loaded+=t.byteLength;this.onProgress?.({loaded:this._loaded});return{value:getArrayBuffer(t),done:!1}}cancel(t){this._reader?.cancel(t);this._abortController.abort()}}class NetworkManager{_responseOrigin=null;constructor({url:t,httpHeaders:e,withCredentials:i}){this.url=t;this.isHttp=/^https?:/i.test(t);this.headers=createHeaders(this.isHttp,e);this.withCredentials=i||!1;this.currXhrId=0;this.pendingRequests=Object.create(null)}request(t){const e=new XMLHttpRequest,i=this.currXhrId++,s=this.pendingRequests[i]={xhr:e};e.open("GET",this.url);e.withCredentials=this.withCredentials;for(const[t,i]of this.headers)e.setRequestHeader(t,i);if(this.isHttp&&"begin"in t&&"end"in t){e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`);s.expectedStatus=206}else s.expectedStatus=200;e.responseType="arraybuffer";assert(t.onError,"Expected `onError` callback to be provided.");e.onerror=()=>{t.onError(e.status)};e.onreadystatechange=this.onStateChange.bind(this,i);e.onprogress=this.onProgress.bind(this,i);s.onHeadersReceived=t.onHeadersReceived;s.onDone=t.onDone;s.onError=t.onError;s.onProgress=t.onProgress;e.send(null);return i}onProgress(t,e){const i=this.pendingRequests[t];i&&i.onProgress?.(e)}onStateChange(t,e){const i=this.pendingRequests[t];if(!i)return;const s=i.xhr;if(s.readyState>=2&&i.onHeadersReceived){i.onHeadersReceived();delete i.onHeadersReceived}if(4!==s.readyState)return;if(!(t in this.pendingRequests))return;delete this.pendingRequests[t];if(0===s.status&&this.isHttp){i.onError(s.status);return}const n=s.status||200;if(!(200===n&&206===i.expectedStatus)&&n!==i.expectedStatus){i.onError(s.status);return}const a=function network_getArrayBuffer(t){const e=t.response;return"string"!=typeof e?e:stringToBytes(e).buffer}(s);if(206===n){const t=s.getResponseHeader("Content-Range"),e=/bytes (\d+)-(\d+)\/(\d+)/.exec(t);if(e)i.onDone({begin:parseInt(e[1],10),chunk:a});else{warn('Missing or invalid "Content-Range" header.');i.onError(0)}}else a?i.onDone({begin:0,chunk:a}):i.onError(s.status)}getRequestXhr(t){return this.pendingRequests[t].xhr}isPendingRequest(t){return t in this.pendingRequests}abortRequest(t){const e=this.pendingRequests[t].xhr;delete this.pendingRequests[t];e.abort()}}class PDFNetworkStream{constructor(t){this._source=t;this._manager=new NetworkManager(t);this._rangeChunkSize=t.rangeChunkSize;this._fullRequestReader=null;this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(t){const e=this._rangeRequestReaders.indexOf(t);e>=0&&this._rangeRequestReaders.splice(e,1)}getFullReader(){assert(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once.");this._fullRequestReader=new PDFNetworkStreamFullRequestReader(this._manager,this._source);return this._fullRequestReader}getRangeReader(t,e){const i=new PDFNetworkStreamRangeRequestReader(this._manager,t,e);i.onClosed=this._onRangeRequestReaderClosed.bind(this);this._rangeRequestReaders.push(i);return i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class PDFNetworkStreamFullRequestReader{constructor(t,e){this._manager=t;this._url=e.url;this._fullRequestId=t.request({onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)});this._headersCapability=Promise.withResolvers();this._disableRange=e.disableRange||!1;this._contentLength=e.length;this._rangeChunkSize=e.rangeChunkSize;this._rangeChunkSize||this._disableRange||(this._disableRange=!0);this._isStreamingSupported=!1;this._isRangeSupported=!1;this._cachedChunks=[];this._requests=[];this._done=!1;this._storedError=void 0;this._filename=null;this.onProgress=null}_onHeadersReceived(){const t=this._fullRequestId,e=this._manager.getRequestXhr(t);this._manager._responseOrigin=getResponseOrigin(e.responseURL);const i=e.getAllResponseHeaders(),s=new Headers(i?i.trimStart().replace(/[^\S ]+$/,"").split(/[\r\n]+/).map((t=>{const[e,...i]=t.split(": ");return[e,i.join(": ")]})):[]),{allowRangeRequests:n,suggestedLength:a}=validateRangeRequestCapabilities({responseHeaders:s,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});n&&(this._isRangeSupported=!0);this._contentLength=a||this._contentLength;this._filename=extractFilenameFromHeader(s);this._isRangeSupported&&this._manager.abortRequest(t);this._headersCapability.resolve()}_onDone(t){if(t)if(this._requests.length>0){this._requests.shift().resolve({value:t.chunk,done:!1})}else this._cachedChunks.push(t.chunk);this._done=!0;if(!(this._cachedChunks.length>0)){for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(t){this._storedError=createResponseStatusError(t,this._url);this._headersCapability.reject(this._storedError);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0;this._cachedChunks.length=0}_onProgress(t){this.onProgress?.({loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})}get filename(){return this._filename}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}get contentLength(){return this._contentLength}get headersReady(){return this._headersCapability.promise}async read(){await this._headersCapability.promise;if(this._storedError)throw this._storedError;if(this._cachedChunks.length>0){return{value:this._cachedChunks.shift(),done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;this._headersCapability.reject(t);for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0;this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId);this._fullRequestReader=null}}class PDFNetworkStreamRangeRequestReader{constructor(t,e,i){this._manager=t;this._url=t.url;this._requestId=t.request({begin:e,end:i,onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)});this._requests=[];this._queuedChunk=null;this._done=!1;this._storedError=void 0;this.onProgress=null;this.onClosed=null}_onHeadersReceived(){const t=getResponseOrigin(this._manager.getRequestXhr(this._requestId)?.responseURL);if(t!==this._manager._responseOrigin){this._storedError=new Error(`Expected range response-origin "${t}" to match "${this._manager._responseOrigin}".`);this._onError(0)}}_close(){this.onClosed?.(this)}_onDone(t){const e=t.chunk;if(this._requests.length>0){this._requests.shift().resolve({value:e,done:!1})}else this._queuedChunk=e;this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0;this._close()}_onError(t){this._storedError??=createResponseStatusError(t,this._url);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0;this._queuedChunk=null}_onProgress(t){this.isStreamingSupported||this.onProgress?.({loaded:t.loaded})}get isStreamingSupported(){return!1}async read(){if(this._storedError)throw this._storedError;if(null!==this._queuedChunk){const t=this._queuedChunk;this._queuedChunk=null;return{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0;this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId);this._close()}}const Mt=/^[a-z][a-z0-9\-+.]+:/i;class PDFNodeStream{constructor(t){this.source=t;this.url=function parseUrlOrPath(t){if(Mt.test(t))return new URL(t);const e=process.getBuiltinModule("url");return new URL(e.pathToFileURL(t))}(t.url);assert("file:"===this.url.protocol,"PDFNodeStream only supports file:// URLs.");this._fullRequestReader=null;this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){assert(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once.");this._fullRequestReader=new PDFNodeStreamFsFullReader(this);return this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new PDFNodeStreamFsRangeReader(this,t,e);this._rangeRequestReaders.push(i);return i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class PDFNodeStreamFsFullReader{constructor(t){this._url=t.url;this._done=!1;this._storedError=null;this.onProgress=null;const e=t.source;this._contentLength=e.length;this._loaded=0;this._filename=null;this._disableRange=e.disableRange||!1;this._rangeChunkSize=e.rangeChunkSize;this._rangeChunkSize||this._disableRange||(this._disableRange=!0);this._isStreamingSupported=!e.disableStream;this._isRangeSupported=!e.disableRange;this._readableStream=null;this._readCapability=Promise.withResolvers();this._headersCapability=Promise.withResolvers();const i=process.getBuiltinModule("fs");i.promises.lstat(this._url).then((t=>{this._contentLength=t.size;this._setReadableStream(i.createReadStream(this._url));this._headersCapability.resolve()}),(t=>{"ENOENT"===t.code&&(t=new MissingPDFException(`Missing PDF "${this._url}".`));this._storedError=t;this._headersCapability.reject(t)}))}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;if(this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();if(null===t){this._readCapability=Promise.withResolvers();return this.read()}this._loaded+=t.length;this.onProgress?.({loaded:this._loaded,total:this._contentLength});return{value:new Uint8Array(t).buffer,done:!1}}cancel(t){this._readableStream?this._readableStream.destroy(t):this._error(t)}_error(t){this._storedError=t;this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t;t.on("readable",(()=>{this._readCapability.resolve()}));t.on("end",(()=>{t.destroy();this._done=!0;this._readCapability.resolve()}));t.on("error",(t=>{this._error(t)}));!this._isStreamingSupported&&this._isRangeSupported&&this._error(new AbortException("streaming is disabled"));this._storedError&&this._readableStream.destroy(this._storedError)}}class PDFNodeStreamFsRangeReader{constructor(t,e,i){this._url=t.url;this._done=!1;this._storedError=null;this.onProgress=null;this._loaded=0;this._readableStream=null;this._readCapability=Promise.withResolvers();const s=t.source;this._isStreamingSupported=!s.disableStream;const n=process.getBuiltinModule("fs");this._setReadableStream(n.createReadStream(this._url,{start:e,end:i-1}))}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;if(this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();if(null===t){this._readCapability=Promise.withResolvers();return this.read()}this._loaded+=t.length;this.onProgress?.({loaded:this._loaded});return{value:new Uint8Array(t).buffer,done:!1}}cancel(t){this._readableStream?this._readableStream.destroy(t):this._error(t)}_error(t){this._storedError=t;this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t;t.on("readable",(()=>{this._readCapability.resolve()}));t.on("end",(()=>{t.destroy();this._done=!0;this._readCapability.resolve()}));t.on("error",(t=>{this._error(t)}));this._storedError&&this._readableStream.destroy(this._storedError)}}const Pt=30;class TextLayer{#Si=Promise.withResolvers();#pt=null;#Ci=!1;#Ti=!!globalThis.FontInspector?.enabled;#Mi=null;#Pi=null;#Di=0;#ki=0;#Ri=null;#Ii=null;#Fi=0;#Li=0;#Oi=Object.create(null);#Ni=[];#Bi=null;#Hi=[];#zi=new WeakMap;#Ui=null;static#Gi=new Map;static#$i=new Map;static#Vi=new WeakMap;static#ji=null;static#Wi=new Set;constructor({textContentSource:t,container:e,viewport:i}){if(t instanceof ReadableStream)this.#Bi=t;else{if("object"!=typeof t)throw new Error('No "textContentSource" parameter specified.');this.#Bi=new ReadableStream({start(e){e.enqueue(t);e.close()}})}this.#pt=this.#Ii=e;this.#Li=i.scale*(globalThis.devicePixelRatio||1);this.#Fi=i.rotation;this.#Pi={div:null,properties:null,ctx:null};const{pageWidth:s,pageHeight:n,pageX:a,pageY:r}=i.rawDims;this.#Ui=[1,0,0,-1,-a,r+n];this.#ki=s;this.#Di=n;TextLayer.#qi();setLayerDimensions(e,i);this.#Si.promise.finally((()=>{TextLayer.#Wi.delete(this);this.#Pi=null;this.#Oi=null})).catch((()=>{}))}static get fontFamilyMap(){const{isWindows:t,isFirefox:e}=util_FeatureTest.platform;return shadow(this,"fontFamilyMap",new Map([["sans-serif",(t&&e?"Calibri, ":"")+"sans-serif"],["monospace",(t&&e?"Lucida Console, ":"")+"monospace"]]))}render(){const pump=()=>{this.#Ri.read().then((({value:t,done:e})=>{if(e)this.#Si.resolve();else{this.#Mi??=t.lang;Object.assign(this.#Oi,t.styles);this.#Xi(t.items);pump()}}),this.#Si.reject)};this.#Ri=this.#Bi.getReader();TextLayer.#Wi.add(this);pump();return this.#Si.promise}update({viewport:t,onBefore:e=null}){const i=t.scale*(globalThis.devicePixelRatio||1),s=t.rotation;if(s!==this.#Fi){e?.();this.#Fi=s;setLayerDimensions(this.#Ii,{rotation:s})}if(i!==this.#Li){e?.();this.#Li=i;const t={div:null,properties:null,ctx:TextLayer.#Ki(this.#Mi)};for(const e of this.#Hi){t.properties=this.#zi.get(e);t.div=e;this.#Yi(t)}}}cancel(){const t=new AbortException("TextLayer task cancelled.");this.#Ri?.cancel(t).catch((()=>{}));this.#Ri=null;this.#Si.reject(t)}get textDivs(){return this.#Hi}get textContentItemsStr(){return this.#Ni}#Xi(t){if(this.#Ci)return;this.#Pi.ctx??=TextLayer.#Ki(this.#Mi);const e=this.#Hi,i=this.#Ni;for(const s of t){if(e.length>1e5){warn("Ignoring additional textDivs for performance reasons.");this.#Ci=!0;return}if(void 0!==s.str){i.push(s.str);this.#Qi(s)}else if("beginMarkedContentProps"===s.type||"beginMarkedContent"===s.type){const t=this.#pt;this.#pt=document.createElement("span");this.#pt.classList.add("markedContent");null!==s.id&&this.#pt.setAttribute("id",`${s.id}`);t.append(this.#pt)}else"endMarkedContent"===s.type&&(this.#pt=this.#pt.parentNode)}}#Qi(t){const e=document.createElement("span"),i={angle:0,canvasWidth:0,hasText:""!==t.str,hasEOL:t.hasEOL,fontSize:0};this.#Hi.push(e);const s=Util.transform(this.#Ui,t.transform);let n=Math.atan2(s[1],s[0]);const a=this.#Oi[t.fontName];a.vertical&&(n+=Math.PI/2);let r=this.#Ti&&a.fontSubstitution||a.fontFamily;r=TextLayer.fontFamilyMap.get(r)||r;const o=Math.hypot(s[2],s[3]),l=o*TextLayer.#Ji(r,this.#Mi);let h,d;if(0===n){h=s[4];d=s[5]-l}else{h=s[4]+l*Math.sin(n);d=s[5]-l*Math.cos(n)}const c="calc(var(--scale-factor)*",u=e.style;if(this.#pt===this.#Ii){u.left=`${(100*h/this.#ki).toFixed(2)}%`;u.top=`${(100*d/this.#Di).toFixed(2)}%`}else{u.left=`${c}${h.toFixed(2)}px)`;u.top=`${c}${d.toFixed(2)}px)`}u.fontSize=`${c}${(TextLayer.#ji*o).toFixed(2)}px)`;u.fontFamily=r;i.fontSize=o;e.setAttribute("role","presentation");e.textContent=t.str;e.dir=t.dir;this.#Ti&&(e.dataset.fontName=a.fontSubstitutionLoadedName||t.fontName);0!==n&&(i.angle=n*(180/Math.PI));let p=!1;if(t.str.length>1)p=!0;else if(" "!==t.str&&t.transform[0]!==t.transform[3]){const e=Math.abs(t.transform[0]),i=Math.abs(t.transform[3]);e!==i&&Math.max(e,i)/Math.min(e,i)>1.5&&(p=!0)}p&&(i.canvasWidth=a.vertical?t.height:t.width);this.#zi.set(e,i);this.#Pi.div=e;this.#Pi.properties=i;this.#Yi(this.#Pi);i.hasText&&this.#pt.append(e);if(i.hasEOL){const t=document.createElement("br");t.setAttribute("role","presentation");this.#pt.append(t)}}#Yi(t){const{div:e,properties:i,ctx:s}=t,{style:n}=e;let a="";TextLayer.#ji>1&&(a=`scale(${1/TextLayer.#ji})`);if(0!==i.canvasWidth&&i.hasText){const{fontFamily:t}=n,{canvasWidth:r,fontSize:o}=i;TextLayer.#Zi(s,o*this.#Li,t);const{width:l}=s.measureText(e.textContent);l>0&&(a=`scaleX(${r*this.#Li/l}) ${a}`)}0!==i.angle&&(a=`rotate(${i.angle}deg) ${a}`);a.length>0&&(n.transform=a)}static cleanup(){if(!(this.#Wi.size>0)){this.#Gi.clear();for(const{canvas:t}of this.#$i.values())t.remove();this.#$i.clear()}}static#Ki(t=null){let e=this.#$i.get(t||="");if(!e){const i=document.createElement("canvas");i.className="hiddenCanvasElement";i.lang=t;document.body.append(i);e=i.getContext("2d",{alpha:!1,willReadFrequently:!0});this.#$i.set(t,e);this.#Vi.set(e,{size:0,family:""})}return e}static#Zi(t,e,i){const s=this.#Vi.get(t);if(e!==s.size||i!==s.family){t.font=`${e}px ${i}`;s.size=e;s.family=i}}static#qi(){if(null!==this.#ji)return;const t=document.createElement("div");t.style.opacity=0;t.style.lineHeight=1;t.style.fontSize="1px";t.style.position="absolute";t.textContent="X";document.body.append(t);this.#ji=t.getBoundingClientRect().height;t.remove()}static#Ji(t,e){const i=this.#Gi.get(t);if(i)return i;const s=this.#Ki(e);s.canvas.width=s.canvas.height=Pt;this.#Zi(s,Pt,t);const n=s.measureText("");let a=n.fontBoundingBoxAscent,r=Math.abs(n.fontBoundingBoxDescent);if(a){const e=a/(a+r);this.#Gi.set(t,e);s.canvas.width=s.canvas.height=0;return e}s.strokeStyle="red";s.clearRect(0,0,Pt,Pt);s.strokeText("g",0,0);let o=s.getImageData(0,0,Pt,Pt).data;r=0;for(let t=o.length-1-3;t>=0;t-=4)if(o[t]>0){r=Math.ceil(t/4/Pt);break}s.clearRect(0,0,Pt,Pt);s.strokeText("A",0,Pt);o=s.getImageData(0,0,Pt,Pt).data;a=0;for(let t=0,e=o.length;t0){a=Pt-Math.floor(t/4/Pt);break}s.canvas.width=s.canvas.height=0;const l=a?a/(a+r):.8;this.#Gi.set(t,l);return l}}class XfaText{static textContent(t){const e=[],i={items:e,styles:Object.create(null)};!function walk(t){if(!t)return;let i=null;const s=t.name;if("#text"===s)i=t.value;else{if(!XfaText.shouldBuildText(s))return;t?.attributes?.textContent?i=t.attributes.textContent:t.value&&(i=t.value)}null!==i&&e.push({str:i});if(t.children)for(const e of t.children)walk(e)}(t);return i}static shouldBuildText(t){return!("textarea"===t||"input"===t||"option"===t||"select"===t)}}const Dt=65536,kt=e?class NodeCanvasFactory extends BaseCanvasFactory{_createCanvas(t,e){return process.getBuiltinModule("module").createRequire(import.meta.url)("@napi-rs/canvas").createCanvas(t,e)}}:class DOMCanvasFactory extends BaseCanvasFactory{constructor({ownerDocument:t=globalThis.document,enableHWA:e=!1}){super({enableHWA:e});this._document=t}_createCanvas(t,e){const i=this._document.createElement("canvas");i.width=t;i.height=e;return i}},Rt=e?class NodeCMapReaderFactory extends BaseCMapReaderFactory{async _fetch(t){return node_utils_fetchData(t)}}:DOMCMapReaderFactory,It=e?class NodeFilterFactory extends BaseFilterFactory{}:class DOMFilterFactory extends BaseFilterFactory{#ts;#es;#is;#ss;#ns;#as;#w=0;constructor({docId:t,ownerDocument:e=globalThis.document}){super();this.#ss=t;this.#ns=e}get#y(){return this.#es||=new Map}get#rs(){return this.#as||=new Map}get#os(){if(!this.#is){const t=this.#ns.createElement("div"),{style:e}=t;e.visibility="hidden";e.contain="strict";e.width=e.height=0;e.position="absolute";e.top=e.left=0;e.zIndex=-1;const i=this.#ns.createElementNS(it,"svg");i.setAttribute("width",0);i.setAttribute("height",0);this.#is=this.#ns.createElementNS(it,"defs");t.append(i);i.append(this.#is);this.#ns.body.append(t)}return this.#is}#ls(t){if(1===t.length){const e=t[0],i=new Array(256);for(let t=0;t<256;t++)i[t]=e[t]/255;const s=i.join(",");return[s,s,s]}const[e,i,s]=t,n=new Array(256),a=new Array(256),r=new Array(256);for(let t=0;t<256;t++){n[t]=e[t]/255;a[t]=i[t]/255;r[t]=s[t]/255}return[n.join(","),a.join(","),r.join(",")]}#hs(t){if(void 0===this.#ts){this.#ts="";const t=this.#ns.URL;t!==this.#ns.baseURI&&(isDataScheme(t)?warn('#createUrl: ignore "data:"-URL for performance reasons.'):this.#ts=t.split("#",1)[0])}return`url(${this.#ts}#${t})`}addFilter(t){if(!t)return"none";let e=this.#y.get(t);if(e)return e;const[i,s,n]=this.#ls(t),a=1===t.length?i:`${i}${s}${n}`;e=this.#y.get(a);if(e){this.#y.set(t,e);return e}const r=`g_${this.#ss}_transfer_map_${this.#w++}`,o=this.#hs(r);this.#y.set(t,o);this.#y.set(a,o);const l=this.#ds(r);this.#cs(i,s,n,l);return o}addHCMFilter(t,e){const i=`${t}-${e}`,s="base";let n=this.#rs.get(s);if(n?.key===i)return n.url;if(n){n.filter?.remove();n.key=i;n.url="none";n.filter=null}else{n={key:i,url:"none",filter:null};this.#rs.set(s,n)}if(!t||!e)return n.url;const a=this.#us(t);t=Util.makeHexColor(...a);const r=this.#us(e);e=Util.makeHexColor(...r);this.#os.style.color="";if("#000000"===t&&"#ffffff"===e||t===e)return n.url;const o=new Array(256);for(let t=0;t<=255;t++){const e=t/255;o[t]=e<=.03928?e/12.92:((e+.055)/1.055)**2.4}const l=o.join(","),h=`g_${this.#ss}_hcm_filter`,d=n.filter=this.#ds(h);this.#cs(l,l,l,d);this.#ps(d);const getSteps=(t,e)=>{const i=a[t]/255,s=r[t]/255,n=new Array(e+1);for(let t=0;t<=e;t++)n[t]=i+t/e*(s-i);return n.join(",")};this.#cs(getSteps(0,5),getSteps(1,5),getSteps(2,5),d);n.url=this.#hs(h);return n.url}addAlphaFilter(t){let e=this.#y.get(t);if(e)return e;const[i]=this.#ls([t]),s=`alpha_${i}`;e=this.#y.get(s);if(e){this.#y.set(t,e);return e}const n=`g_${this.#ss}_alpha_map_${this.#w++}`,a=this.#hs(n);this.#y.set(t,a);this.#y.set(s,a);const r=this.#ds(n);this.#gs(i,r);return a}addLuminosityFilter(t){let e,i,s=this.#y.get(t||"luminosity");if(s)return s;if(t){[e]=this.#ls([t]);i=`luminosity_${e}`}else i="luminosity";s=this.#y.get(i);if(s){this.#y.set(t,s);return s}const n=`g_${this.#ss}_luminosity_map_${this.#w++}`,a=this.#hs(n);this.#y.set(t,a);this.#y.set(i,a);const r=this.#ds(n);this.#ms(r);t&&this.#gs(e,r);return a}addHighlightHCMFilter(t,e,i,s,n){const a=`${e}-${i}-${s}-${n}`;let r=this.#rs.get(t);if(r?.key===a)return r.url;if(r){r.filter?.remove();r.key=a;r.url="none";r.filter=null}else{r={key:a,url:"none",filter:null};this.#rs.set(t,r)}if(!e||!i)return r.url;const[o,l]=[e,i].map(this.#us.bind(this));let h=Math.round(.2126*o[0]+.7152*o[1]+.0722*o[2]),d=Math.round(.2126*l[0]+.7152*l[1]+.0722*l[2]),[c,u]=[s,n].map(this.#us.bind(this));d{const s=new Array(256),n=(d-h)/i,a=t/255,r=(e-t)/(255*i);let o=0;for(let t=0;t<=i;t++){const e=Math.round(h+t*n),i=a+t*r;for(let t=o;t<=e;t++)s[t]=i;o=e+1}for(let t=o;t<256;t++)s[t]=s[o-1];return s.join(",")},p=`g_${this.#ss}_hcm_${t}_filter`,g=r.filter=this.#ds(p);this.#ps(g);this.#cs(getSteps(c[0],u[0],5),getSteps(c[1],u[1],5),getSteps(c[2],u[2],5),g);r.url=this.#hs(p);return r.url}destroy(t=!1){if(!t||!this.#as?.size){this.#is?.parentNode.parentNode.remove();this.#is=null;this.#es?.clear();this.#es=null;this.#as?.clear();this.#as=null;this.#w=0}}#ms(t){const e=this.#ns.createElementNS(it,"feColorMatrix");e.setAttribute("type","matrix");e.setAttribute("values","0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0");t.append(e)}#ps(t){const e=this.#ns.createElementNS(it,"feColorMatrix");e.setAttribute("type","matrix");e.setAttribute("values","0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0");t.append(e)}#ds(t){const e=this.#ns.createElementNS(it,"filter");e.setAttribute("color-interpolation-filters","sRGB");e.setAttribute("id",t);this.#os.append(e);return e}#fs(t,e,i){const s=this.#ns.createElementNS(it,e);s.setAttribute("type","discrete");s.setAttribute("tableValues",i);t.append(s)}#cs(t,e,i,s){const n=this.#ns.createElementNS(it,"feComponentTransfer");s.append(n);this.#fs(n,"feFuncR",t);this.#fs(n,"feFuncG",e);this.#fs(n,"feFuncB",i)}#gs(t,e){const i=this.#ns.createElementNS(it,"feComponentTransfer");e.append(i);this.#fs(i,"feFuncA",t)}#us(t){this.#os.style.color=t;return getRGB(getComputedStyle(this.#os).getPropertyValue("color"))}},Ft=e?class NodeStandardFontDataFactory extends BaseStandardFontDataFactory{async _fetch(t){return node_utils_fetchData(t)}}:DOMStandardFontDataFactory;function getDocument(t={}){"string"==typeof t||t instanceof URL?t={url:t}:(t instanceof ArrayBuffer||ArrayBuffer.isView(t))&&(t={data:t});const i=new PDFDocumentLoadingTask,{docId:s}=i,n=t.url?function getUrlProp(t){if(t instanceof URL)return t.href;try{return new URL(t,window.location).href}catch{if(e&&"string"==typeof t)return t}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}(t.url):null,a=t.data?function getDataProp(t){if(e&&"undefined"!=typeof Buffer&&t instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(t instanceof Uint8Array&&t.byteLength===t.buffer.byteLength)return t;if("string"==typeof t)return stringToBytes(t);if(t instanceof ArrayBuffer||ArrayBuffer.isView(t)||"object"==typeof t&&!isNaN(t?.length))return new Uint8Array(t);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}(t.data):null,r=t.httpHeaders||null,o=!0===t.withCredentials,l=t.password??null,h=t.range instanceof PDFDataRangeTransport?t.range:null,d=Number.isInteger(t.rangeChunkSize)&&t.rangeChunkSize>0?t.rangeChunkSize:Dt;let c=t.worker instanceof PDFWorker?t.worker:null;const u=t.verbosity,p="string"!=typeof t.docBaseUrl||isDataScheme(t.docBaseUrl)?null:t.docBaseUrl,g="string"==typeof t.cMapUrl?t.cMapUrl:null,m=!1!==t.cMapPacked,f=t.CMapReaderFactory||Rt,b="string"==typeof t.standardFontDataUrl?t.standardFontDataUrl:null,A=t.StandardFontDataFactory||Ft,w=!0!==t.stopAtErrors,v=Number.isInteger(t.maxImageSize)&&t.maxImageSize>-1?t.maxImageSize:-1,y=!1!==t.isEvalSupported,x="boolean"==typeof t.isOffscreenCanvasSupported?t.isOffscreenCanvasSupported:!e,_="boolean"==typeof t.isImageDecoderSupported?t.isImageDecoderSupported:!e&&(util_FeatureTest.platform.isFirefox||!globalThis.chrome),E=Number.isInteger(t.canvasMaxAreaInBytes)?t.canvasMaxAreaInBytes:-1,S="boolean"==typeof t.disableFontFace?t.disableFontFace:e,C=!0===t.fontExtraProperties,T=!0===t.enableXfa,M=t.ownerDocument||globalThis.document,P=!0===t.disableRange,D=!0===t.disableStream,k=!0===t.disableAutoFetch,R=!0===t.pdfBug,I=t.CanvasFactory||kt,F=t.FilterFactory||It,L=!0===t.enableHWA,O=h?h.length:t.length??NaN,N="boolean"==typeof t.useSystemFonts?t.useSystemFonts:!e&&!S,B="boolean"==typeof t.useWorkerFetch?t.useWorkerFetch:f===DOMCMapReaderFactory&&A===DOMStandardFontDataFactory&&g&&b&&isValidFetchUrl(g,document.baseURI)&&isValidFetchUrl(b,document.baseURI);setVerbosityLevel(u);const H={canvasFactory:new I({ownerDocument:M,enableHWA:L}),filterFactory:new F({docId:s,ownerDocument:M}),cMapReaderFactory:B?null:new f({baseUrl:g,isCompressed:m}),standardFontDataFactory:B?null:new A({baseUrl:b})};if(!c){const t={verbosity:u,port:GlobalWorkerOptions.workerPort};c=t.port?PDFWorker.fromPort(t):new PDFWorker(t);i._worker=c}const z={docId:s,apiVersion:"4.10.38",data:a,password:l,disableAutoFetch:k,rangeChunkSize:d,length:O,docBaseUrl:p,enableXfa:T,evaluatorOptions:{maxImageSize:v,disableFontFace:S,ignoreErrors:w,isEvalSupported:y,isOffscreenCanvasSupported:x,isImageDecoderSupported:_,canvasMaxAreaInBytes:E,fontExtraProperties:C,useSystemFonts:N,cMapUrl:B?g:null,standardFontDataUrl:B?b:null}},U={disableFontFace:S,fontExtraProperties:C,ownerDocument:M,pdfBug:R,styleElement:null,loadingParams:{disableAutoFetch:k,enableXfa:T}};c.promise.then((function(){if(i.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const t=c.messageHandler.sendWithPromise("GetDocRequest",z,a?[a.buffer]:null);let l;if(h)l=new PDFDataTransportStream(h,{disableRange:P,disableStream:D});else if(!a){if(!n)throw new Error("getDocument - no `url` parameter provided.");let t;if(e)if(isValidFetchUrl(n)){if("undefined"==typeof fetch||"undefined"==typeof Response||!("body"in Response.prototype))throw new Error("getDocument - the Fetch API was disabled in Node.js, see `--no-experimental-fetch`.");t=PDFFetchStream}else t=PDFNodeStream;else t=isValidFetchUrl(n)?PDFFetchStream:PDFNetworkStream;l=new t({url:n,length:O,httpHeaders:r,withCredentials:o,rangeChunkSize:d,disableRange:P,disableStream:D})}return t.then((t=>{if(i.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const e=new MessageHandler(s,t,c.port),n=new WorkerTransport(e,i,l,U,H);i._transport=n;e.send("Ready",null)}))})).catch(i._capability.reject);return i}function isRefProxy(t){return"object"==typeof t&&Number.isInteger(t?.num)&&t.num>=0&&Number.isInteger(t?.gen)&&t.gen>=0}class PDFDocumentLoadingTask{static#ss=0;constructor(){this._capability=Promise.withResolvers();this._transport=null;this._worker=null;this.docId="d"+PDFDocumentLoadingTask.#ss++;this.destroyed=!1;this.onPassword=null;this.onProgress=null}get promise(){return this._capability.promise}async destroy(){this.destroyed=!0;try{this._worker?.port&&(this._worker._pendingDestroy=!0);await(this._transport?.destroy())}catch(t){this._worker?.port&&delete this._worker._pendingDestroy;throw t}this._transport=null;this._worker?.destroy();this._worker=null}}class PDFDataRangeTransport{constructor(t,e,i=!1,s=null){this.length=t;this.initialData=e;this.progressiveDone=i;this.contentDispositionFilename=s;this._rangeListeners=[];this._progressListeners=[];this._progressiveReadListeners=[];this._progressiveDoneListeners=[];this._readyCapability=Promise.withResolvers()}addRangeListener(t){this._rangeListeners.push(t)}addProgressListener(t){this._progressListeners.push(t)}addProgressiveReadListener(t){this._progressiveReadListeners.push(t)}addProgressiveDoneListener(t){this._progressiveDoneListeners.push(t)}onDataRange(t,e){for(const i of this._rangeListeners)i(t,e)}onDataProgress(t,e){this._readyCapability.promise.then((()=>{for(const i of this._progressListeners)i(t,e)}))}onDataProgressiveRead(t){this._readyCapability.promise.then((()=>{for(const e of this._progressiveReadListeners)e(t)}))}onDataProgressiveDone(){this._readyCapability.promise.then((()=>{for(const t of this._progressiveDoneListeners)t()}))}transportReady(){this._readyCapability.resolve()}requestDataRange(t,e){unreachable("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class PDFDocumentProxy{constructor(t,e){this._pdfInfo=t;this._transport=e}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return shadow(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(t){return this._transport.getPage(t)}getPageIndex(t){return this._transport.getPageIndex(t)}getDestinations(){return this._transport.getDestinations()}getDestination(t){return this._transport.getDestination(t)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getOptionalContentConfig(e)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(t=!1){return this._transport.startCleanup(t||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}cachedPageNumber(t){return this._transport.cachedPageNumber(t)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}class PDFPageProxy{#bs=null;#As=!1;constructor(t,e,i,s=!1){this._pageIndex=t;this._pageInfo=e;this._transport=i;this._stats=s?new StatTimer:null;this._pdfBug=s;this.commonObjs=i.commonObjs;this.objs=new PDFObjects;this._maybeCleanupAfterRender=!1;this._intentStates=new Map;this.destroyed=!1}get pageNumber(){return this._pageIndex+1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:t,rotation:e=this.rotate,offsetX:i=0,offsetY:s=0,dontFlip:n=!1}={}){return new PageViewport({viewBox:this.view,userUnit:this.userUnit,scale:t,rotation:e,offsetX:i,offsetY:s,dontFlip:n})}getAnnotations({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getAnnotations(this._pageIndex,e)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return shadow(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:t,viewport:e,intent:i="display",annotationMode:s=p.ENABLE,transform:n=null,background:a=null,optionalContentConfigPromise:r=null,annotationCanvasMap:l=null,pageColors:h=null,printAnnotationStorage:d=null,isEditing:c=!1}){this._stats?.time("Overall");const u=this._transport.getRenderingIntent(i,s,d,c),{renderingIntent:g,cacheKey:m}=u;this.#As=!1;this.#ws();r||=this._transport.getOptionalContentConfig(g);let f=this._intentStates.get(m);if(!f){f=Object.create(null);this._intentStates.set(m,f)}if(f.streamReaderCancelTimeout){clearTimeout(f.streamReaderCancelTimeout);f.streamReaderCancelTimeout=null}const b=!!(g&o);if(!f.displayReadyCapability){f.displayReadyCapability=Promise.withResolvers();f.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null};this._stats?.time("Page Request");this._pumpOperatorList(u)}const complete=t=>{f.renderTasks.delete(A);(this._maybeCleanupAfterRender||b)&&(this.#As=!0);this.#vs(!b);if(t){A.capability.reject(t);this._abortOperatorList({intentState:f,reason:t instanceof Error?t:new Error(t)})}else A.capability.resolve();if(this._stats){this._stats.timeEnd("Rendering");this._stats.timeEnd("Overall");globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats)}},A=new InternalRenderTask({callback:complete,params:{canvasContext:t,viewport:e,transform:n,background:a},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:l,operatorList:f.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!b,pdfBug:this._pdfBug,pageColors:h});(f.renderTasks||=new Set).add(A);const w=A.task;Promise.all([f.displayReadyCapability.promise,r]).then((([t,e])=>{if(this.destroyed)complete();else{this._stats?.time("Rendering");if(!(e.renderingIntent&g))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");A.initializeGraphics({transparency:t,optionalContentConfig:e});A.operatorListChanged()}})).catch(complete);return w}getOperatorList({intent:t="display",annotationMode:e=p.ENABLE,printAnnotationStorage:i=null,isEditing:s=!1}={}){const n=this._transport.getRenderingIntent(t,e,i,s,!0);let a,r=this._intentStates.get(n.cacheKey);if(!r){r=Object.create(null);this._intentStates.set(n.cacheKey,r)}if(!r.opListReadCapability){a=Object.create(null);a.operatorListChanged=function operatorListChanged(){if(r.operatorList.lastChunk){r.opListReadCapability.resolve(r.operatorList);r.renderTasks.delete(a)}};r.opListReadCapability=Promise.withResolvers();(r.renderTasks||=new Set).add(a);r.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null};this._stats?.time("Page Request");this._pumpOperatorList(n)}return r.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=!1,disableNormalization:e=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,includeMarkedContent:!0===t,disableNormalization:!0===e},{highWaterMark:100,size:t=>t.items.length})}getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then((t=>XfaText.textContent(t)));const e=this.streamTextContent(t);return new Promise((function(t,i){const s=e.getReader(),n={items:[],styles:Object.create(null),lang:null};!function pump(){s.read().then((function({value:e,done:i}){if(i)t(n);else{n.lang??=e.lang;Object.assign(n.styles,e.styles);n.items.push(...e.items);pump()}}),i)}()}))}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const t=[];for(const e of this._intentStates.values()){this._abortOperatorList({intentState:e,reason:new Error("Page was destroyed."),force:!0});if(!e.opListReadCapability)for(const i of e.renderTasks){t.push(i.completed);i.cancel()}}this.objs.clear();this.#As=!1;this.#ws();return Promise.all(t)}cleanup(t=!1){this.#As=!0;const e=this.#vs(!1);t&&e&&(this._stats&&=new StatTimer);return e}#vs(t=!1){this.#ws();if(!this.#As||this.destroyed)return!1;if(t){this.#bs=setTimeout((()=>{this.#bs=null;this.#vs(!1)}),5e3);return!1}for(const{renderTasks:t,operatorList:e}of this._intentStates.values())if(t.size>0||!e.lastChunk)return!1;this._intentStates.clear();this.objs.clear();this.#As=!1;return!0}#ws(){if(this.#bs){clearTimeout(this.#bs);this.#bs=null}}_startRenderPage(t,e){const i=this._intentStates.get(e);if(i){this._stats?.timeEnd("Page Request");i.displayReadyCapability?.resolve(t)}}_renderPageChunk(t,e){for(let i=0,s=t.length;i{r.read().then((({value:t,done:e})=>{if(e)o.streamReader=null;else if(!this._transport.destroyed){this._renderPageChunk(t,o);pump()}}),(t=>{o.streamReader=null;if(!this._transport.destroyed){if(o.operatorList){o.operatorList.lastChunk=!0;for(const t of o.renderTasks)t.operatorListChanged();this.#vs(!0)}if(o.displayReadyCapability)o.displayReadyCapability.reject(t);else{if(!o.opListReadCapability)throw t;o.opListReadCapability.reject(t)}}}))};pump()}_abortOperatorList({intentState:t,reason:e,force:i=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout){clearTimeout(t.streamReaderCancelTimeout);t.streamReaderCancelTimeout=null}if(!i){if(t.renderTasks.size>0)return;if(e instanceof RenderingCancelledException){let i=100;e.extraDelay>0&&e.extraDelay<1e3&&(i+=e.extraDelay);t.streamReaderCancelTimeout=setTimeout((()=>{t.streamReaderCancelTimeout=null;this._abortOperatorList({intentState:t,reason:e,force:!0})}),i);return}}t.streamReader.cancel(new AbortException(e.message)).catch((()=>{}));t.streamReader=null;if(!this._transport.destroyed){for(const[e,i]of this._intentStates)if(i===t){this._intentStates.delete(e);break}this.cleanup()}}}get stats(){return this._stats}}class LoopbackPort{#ys=new Map;#xs=Promise.resolve();postMessage(t,e){const i={data:structuredClone(t,e?{transfer:e}:null)};this.#xs.then((()=>{for(const[t]of this.#ys)t.call(this,i)}))}addEventListener(t,e,i=null){let s=null;if(i?.signal instanceof AbortSignal){const{signal:n}=i;if(n.aborted){warn("LoopbackPort - cannot use an `aborted` signal.");return}const onAbort=()=>this.removeEventListener(t,e);s=()=>n.removeEventListener("abort",onAbort);n.addEventListener("abort",onAbort)}this.#ys.set(e,s)}removeEventListener(t,e){const i=this.#ys.get(e);i?.();this.#ys.delete(e)}terminate(){for(const[,t]of this.#ys)t?.();this.#ys.clear()}}class PDFWorker{static#_s=0;static#Es=!1;static#Ss;static{if(e){this.#Es=!0;GlobalWorkerOptions.workerSrc||="./pdf.worker.mjs"}this._isSameOrigin=(t,e)=>{let i;try{i=new URL(t);if(!i.origin||"null"===i.origin)return!1}catch{return!1}const s=new URL(e,i);return i.origin===s.origin};this._createCDNWrapper=t=>{const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))}}constructor({name:t=null,port:e=null,verbosity:i=getVerbosityLevel()}={}){this.name=t;this.destroyed=!1;this.verbosity=i;this._readyCapability=Promise.withResolvers();this._port=null;this._webWorker=null;this._messageHandler=null;if(e){if(PDFWorker.#Ss?.has(e))throw new Error("Cannot use more than one PDFWorker per port.");(PDFWorker.#Ss||=new WeakMap).set(e,this);this._initializeFromPort(e)}else this._initialize()}get promise(){return this._readyCapability.promise}#Cs(){this._readyCapability.resolve();this._messageHandler.send("configure",{verbosity:this.verbosity})}get port(){return this._port}get messageHandler(){return this._messageHandler}_initializeFromPort(t){this._port=t;this._messageHandler=new MessageHandler("main","worker",t);this._messageHandler.on("ready",(function(){}));this.#Cs()}_initialize(){if(PDFWorker.#Es||PDFWorker.#Ts){this._setupFakeWorker();return}let{workerSrc:t}=PDFWorker;try{PDFWorker._isSameOrigin(window.location.href,t)||(t=PDFWorker._createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),i=new MessageHandler("main","worker",e),terminateEarly=()=>{s.abort();i.destroy();e.terminate();this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()},s=new AbortController;e.addEventListener("error",(()=>{this._webWorker||terminateEarly()}),{signal:s.signal});i.on("test",(t=>{s.abort();if(!this.destroyed&&t){this._messageHandler=i;this._port=e;this._webWorker=e;this.#Cs()}else terminateEarly()}));i.on("ready",(t=>{s.abort();if(this.destroyed)terminateEarly();else try{sendTest()}catch{this._setupFakeWorker()}}));const sendTest=()=>{const t=new Uint8Array;i.send("test",t,[t.buffer])};sendTest();return}catch{info("The worker has been disabled.")}this._setupFakeWorker()}_setupFakeWorker(){if(!PDFWorker.#Es){warn("Setting up fake worker.");PDFWorker.#Es=!0}PDFWorker._setupFakeWorkerGlobal.then((t=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}const e=new LoopbackPort;this._port=e;const i="fake"+PDFWorker.#_s++,s=new MessageHandler(i+"_worker",i,e);t.setup(s,e);this._messageHandler=new MessageHandler(i,i+"_worker",e);this.#Cs()})).catch((t=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${t.message}".`))}))}destroy(){this.destroyed=!0;this._webWorker?.terminate();this._webWorker=null;PDFWorker.#Ss?.delete(this._port);this._port=null;this._messageHandler?.destroy();this._messageHandler=null}static fromPort(t){if(!t?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");const e=this.#Ss?.get(t.port);if(e){if(e._pendingDestroy)throw new Error("PDFWorker.fromPort - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return e}return new PDFWorker(t)}static get workerSrc(){if(GlobalWorkerOptions.workerSrc)return GlobalWorkerOptions.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get#Ts(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return shadow(this,"_setupFakeWorkerGlobal",(async()=>{if(this.#Ts)return this.#Ts;return(await import(this.workerSrc)).WorkerMessageHandler})())}}class WorkerTransport{#Ms=new Map;#Ps=new Map;#Ds=new Map;#ks=new Map;#Rs=null;constructor(t,e,i,s,n){this.messageHandler=t;this.loadingTask=e;this.commonObjs=new PDFObjects;this.fontLoader=new FontLoader({ownerDocument:s.ownerDocument,styleElement:s.styleElement});this.loadingParams=s.loadingParams;this._params=s;this.canvasFactory=n.canvasFactory;this.filterFactory=n.filterFactory;this.cMapReaderFactory=n.cMapReaderFactory;this.standardFontDataFactory=n.standardFontDataFactory;this.destroyed=!1;this.destroyCapability=null;this._networkStream=i;this._fullReader=null;this._lastProgress=null;this.downloadInfoCapability=Promise.withResolvers();this.setupMessageHandler()}#Is(t,e=null){const i=this.#Ms.get(t);if(i)return i;const s=this.messageHandler.sendWithPromise(t,e);this.#Ms.set(t,s);return s}get annotationStorage(){return shadow(this,"annotationStorage",new AnnotationStorage)}getRenderingIntent(t,e=p.ENABLE,i=null,s=!1,n=!1){let g=r,m=rt;switch(t){case"any":g=a;break;case"display":break;case"print":g=o;break;default:warn(`getRenderingIntent - invalid intent: ${t}`)}const f=g&o&&i instanceof PrintAnnotationStorage?i:this.annotationStorage;switch(e){case p.DISABLE:g+=d;break;case p.ENABLE:break;case p.ENABLE_FORMS:g+=l;break;case p.ENABLE_STORAGE:g+=h;m=f.serializable;break;default:warn(`getRenderingIntent - invalid annotationMode: ${e}`)}s&&(g+=c);n&&(g+=u);const{ids:b,hash:A}=f.modifiedIds;return{renderingIntent:g,cacheKey:[g,m.hash,A].join("_"),annotationStorageSerializable:m,modifiedIds:b}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0;this.destroyCapability=Promise.withResolvers();this.#Rs?.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const e of this.#Ps.values())t.push(e._destroy());this.#Ps.clear();this.#Ds.clear();this.#ks.clear();this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();const e=this.messageHandler.sendWithPromise("Terminate",null);t.push(e);Promise.all(t).then((()=>{this.commonObjs.clear();this.fontLoader.clear();this.#Ms.clear();this.filterFactory.destroy();TextLayer.cleanup();this._networkStream?.cancelAllRequests(new AbortException("Worker was terminated."));this.messageHandler?.destroy();this.messageHandler=null;this.destroyCapability.resolve()}),this.destroyCapability.reject);return this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:t,loadingTask:e}=this;t.on("GetReader",((t,e)=>{assert(this._networkStream,"GetReader - no `IPDFStream` instance available.");this._fullReader=this._networkStream.getFullReader();this._fullReader.onProgress=t=>{this._lastProgress={loaded:t.loaded,total:t.total}};e.onPull=()=>{this._fullReader.read().then((function({value:t,done:i}){if(i)e.close();else{assert(t instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer.");e.enqueue(new Uint8Array(t),1,[t])}})).catch((t=>{e.error(t)}))};e.onCancel=t=>{this._fullReader.cancel(t);e.ready.catch((t=>{if(!this.destroyed)throw t}))}}));t.on("ReaderHeadersReady",(async t=>{await this._fullReader.headersReady;const{isStreamingSupported:i,isRangeSupported:s,contentLength:n}=this._fullReader;if(!i||!s){this._lastProgress&&e.onProgress?.(this._lastProgress);this._fullReader.onProgress=t=>{e.onProgress?.({loaded:t.loaded,total:t.total})}}return{isStreamingSupported:i,isRangeSupported:s,contentLength:n}}));t.on("GetRangeReader",((t,e)=>{assert(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");const i=this._networkStream.getRangeReader(t.begin,t.end);if(i){e.onPull=()=>{i.read().then((function({value:t,done:i}){if(i)e.close();else{assert(t instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer.");e.enqueue(new Uint8Array(t),1,[t])}})).catch((t=>{e.error(t)}))};e.onCancel=t=>{i.cancel(t);e.ready.catch((t=>{if(!this.destroyed)throw t}))}}else e.close()}));t.on("GetDoc",(({pdfInfo:t})=>{this._numPages=t.numPages;this._htmlForXfa=t.htmlForXfa;delete t.htmlForXfa;e._capability.resolve(new PDFDocumentProxy(t,this))}));t.on("DocException",(t=>{e._capability.reject(wrapReason(t))}));t.on("PasswordRequest",(t=>{this.#Rs=Promise.withResolvers();try{if(!e.onPassword)throw wrapReason(t);const updatePassword=t=>{t instanceof Error?this.#Rs.reject(t):this.#Rs.resolve({password:t})};e.onPassword(updatePassword,t.code)}catch(t){this.#Rs.reject(t)}return this.#Rs.promise}));t.on("DataLoaded",(t=>{e.onProgress?.({loaded:t.length,total:t.length});this.downloadInfoCapability.resolve(t)}));t.on("StartRenderPage",(t=>{if(this.destroyed)return;this.#Ps.get(t.pageIndex)._startRenderPage(t.transparency,t.cacheKey)}));t.on("commonobj",(([e,i,s])=>{if(this.destroyed)return null;if(this.commonObjs.has(e))return null;switch(i){case"Font":const{disableFontFace:n,fontExtraProperties:a,pdfBug:r}=this._params;if("error"in s){const t=s.error;warn(`Error during font loading: ${t}`);this.commonObjs.resolve(e,t);break}const o=r&&globalThis.FontInspector?.enabled?(t,e)=>globalThis.FontInspector.fontAdded(t,e):null,l=new FontFaceObject(s,{disableFontFace:n,fontExtraProperties:a,inspectFont:o});this.fontLoader.bind(l).catch((()=>t.sendWithPromise("FontFallback",{id:e}))).finally((()=>{!a&&l.data&&(l.data=null);this.commonObjs.resolve(e,l)}));break;case"CopyLocalImage":const{imageRef:h}=s;assert(h,"The imageRef must be defined.");for(const t of this.#Ps.values())for(const[,i]of t.objs)if(i?.ref===h){if(!i.dataLen)return null;this.commonObjs.resolve(e,structuredClone(i));return i.dataLen}break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(e,s);break;default:throw new Error(`Got unknown common object type ${i}`)}return null}));t.on("obj",(([t,e,i,s])=>{if(this.destroyed)return;const n=this.#Ps.get(e);if(!n.objs.has(t))if(0!==n._intentStates.size)switch(i){case"Image":n.objs.resolve(t,s);s?.dataLen>1e7&&(n._maybeCleanupAfterRender=!0);break;case"Pattern":n.objs.resolve(t,s);break;default:throw new Error(`Got unknown object type ${i}`)}else s?.bitmap?.close()}));t.on("DocProgress",(t=>{this.destroyed||e.onProgress?.({loaded:t.loaded,total:t.total})}));t.on("FetchBuiltInCMap",(async t=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.cMapReaderFactory)throw new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter.");return this.cMapReaderFactory.fetch(t)}));t.on("FetchStandardFontData",(async t=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.standardFontDataFactory)throw new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter.");return this.standardFontDataFactory.fetch(t)}))}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&warn("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:t,transfer:e}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:this._fullReader?.filename??null},e).finally((()=>{this.annotationStorage.resetModified()}))}getPage(t){if(!Number.isInteger(t)||t<=0||t>this._numPages)return Promise.reject(new Error("Invalid page request."));const e=t-1,i=this.#Ds.get(e);if(i)return i;const s=this.messageHandler.sendWithPromise("GetPage",{pageIndex:e}).then((i=>{if(this.destroyed)throw new Error("Transport destroyed");i.refStr&&this.#ks.set(i.refStr,t);const s=new PDFPageProxy(e,i,this,this._params.pdfBug);this.#Ps.set(e,s);return s}));this.#Ds.set(e,s);return s}getPageIndex(t){return isRefProxy(t)?this.messageHandler.sendWithPromise("GetPageIndex",{num:t.num,gen:t.gen}):Promise.reject(new Error("Invalid pageIndex request."))}getAnnotations(t,e){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:t,intent:e})}getFieldObjects(){return this.#Is("GetFieldObjects")}hasJSActions(){return this.#Is("HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(t){return"string"!=typeof t?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:t})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getDocJSActions(){return this.#Is("GetDocJSActions")}getPageJSActions(t){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:t})}getStructTree(t){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:t})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(t){return this.#Is("GetOptionalContentConfig").then((e=>new OptionalContentConfig(e,t)))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",e=this.#Ms.get(t);if(e)return e;const i=this.messageHandler.sendWithPromise(t,null).then((t=>({info:t[0],metadata:t[1]?new Metadata(t[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null})));this.#Ms.set(t,i);return i}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(t=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const t of this.#Ps.values()){if(!t.cleanup())throw new Error(`startCleanup: Page ${t.pageNumber} is currently rendering.`)}this.commonObjs.clear();t||this.fontLoader.clear();this.#Ms.clear();this.filterFactory.destroy(!0);TextLayer.cleanup()}}cachedPageNumber(t){if(!isRefProxy(t))return null;const e=0===t.gen?`${t.num}R`:`${t.num}R${t.gen}`;return this.#ks.get(e)??null}}const Lt=Symbol("INITIAL_DATA");class PDFObjects{#Fs=Object.create(null);#Ls(t){return this.#Fs[t]||={...Promise.withResolvers(),data:Lt}}get(t,e=null){if(e){const i=this.#Ls(t);i.promise.then((()=>e(i.data)));return null}const i=this.#Fs[t];if(!i||i.data===Lt)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return i.data}has(t){const e=this.#Fs[t];return!!e&&e.data!==Lt}delete(t){const e=this.#Fs[t];if(!e||e.data===Lt)return!1;delete this.#Fs[t];return!0}resolve(t,e=null){const i=this.#Ls(t);i.data=e;i.resolve()}clear(){for(const t in this.#Fs){const{data:e}=this.#Fs[t];e?.bitmap?.close()}this.#Fs=Object.create(null)}*[Symbol.iterator](){for(const t in this.#Fs){const{data:e}=this.#Fs[t];e!==Lt&&(yield[t,e])}}}class RenderTask{#Os=null;constructor(t){this.#Os=t;this.onContinue=null}get promise(){return this.#Os.capability.promise}cancel(t=0){this.#Os.cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=this.#Os.operatorList;if(!t)return!1;const{annotationCanvasMap:e}=this.#Os;return t.form||t.canvas&&e?.size>0}}class InternalRenderTask{#Ns=null;static#Bs=new WeakSet;constructor({callback:t,params:e,objs:i,commonObjs:s,annotationCanvasMap:n,operatorList:a,pageIndex:r,canvasFactory:o,filterFactory:l,useRequestAnimationFrame:h=!1,pdfBug:d=!1,pageColors:c=null}){this.callback=t;this.params=e;this.objs=i;this.commonObjs=s;this.annotationCanvasMap=n;this.operatorListIdx=null;this.operatorList=a;this._pageIndex=r;this.canvasFactory=o;this.filterFactory=l;this._pdfBug=d;this.pageColors=c;this.running=!1;this.graphicsReadyCallback=null;this.graphicsReady=!1;this._useRequestAnimationFrame=!0===h&&"undefined"!=typeof window;this.cancelled=!1;this.capability=Promise.withResolvers();this.task=new RenderTask(this);this._cancelBound=this.cancel.bind(this);this._continueBound=this._continue.bind(this);this._scheduleNextBound=this._scheduleNext.bind(this);this._nextBound=this._next.bind(this);this._canvas=e.canvasContext.canvas}get completed(){return this.capability.promise.catch((function(){}))}initializeGraphics({transparency:t=!1,optionalContentConfig:e}){if(this.cancelled)return;if(this._canvas){if(InternalRenderTask.#Bs.has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");InternalRenderTask.#Bs.add(this._canvas)}if(this._pdfBug&&globalThis.StepperManager?.enabled){this.stepper=globalThis.StepperManager.create(this._pageIndex);this.stepper.init(this.operatorList);this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint()}const{canvasContext:i,viewport:s,transform:n,background:a}=this.params;this.gfx=new CanvasGraphics(i,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:e},this.annotationCanvasMap,this.pageColors);this.gfx.beginDrawing({transform:n,viewport:s,transparency:t,background:a});this.operatorListIdx=0;this.graphicsReady=!0;this.graphicsReadyCallback?.()}cancel(t=null,e=0){this.running=!1;this.cancelled=!0;this.gfx?.endDrawing();if(this.#Ns){window.cancelAnimationFrame(this.#Ns);this.#Ns=null}InternalRenderTask.#Bs.delete(this._canvas);this.callback(t||new RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex+1}`,e))}operatorListChanged(){if(this.graphicsReady){this.stepper?.updateOperatorList(this.operatorList);this.running||this._continue()}else this.graphicsReadyCallback||=this._continueBound}_continue(){this.running=!0;this.cancelled||(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?this.#Ns=window.requestAnimationFrame((()=>{this.#Ns=null;this._nextBound().catch(this._cancelBound)})):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){if(!this.cancelled){this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper);if(this.operatorListIdx===this.operatorList.argsArray.length){this.running=!1;if(this.operatorList.lastChunk){this.gfx.endDrawing();InternalRenderTask.#Bs.delete(this._canvas);this.callback()}}}}}const Ot="4.10.38",Nt="f9bea397f";function makeColorComp(t){return Math.floor(255*Math.max(0,Math.min(1,t))).toString(16).padStart(2,"0")}function scaleAndClamp(t){return Math.max(0,Math.min(255,255*t))}class ColorConverters{static CMYK_G([t,e,i,s]){return["G",1-Math.min(1,.3*t+.59*i+.11*e+s)]}static G_CMYK([t]){return["CMYK",0,0,0,1-t]}static G_RGB([t]){return["RGB",t,t,t]}static G_rgb([t]){return[t=scaleAndClamp(t),t,t]}static G_HTML([t]){const e=makeColorComp(t);return`#${e}${e}${e}`}static RGB_G([t,e,i]){return["G",.3*t+.59*e+.11*i]}static RGB_rgb(t){return t.map(scaleAndClamp)}static RGB_HTML(t){return`#${t.map(makeColorComp).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([t,e,i,s]){return["RGB",1-Math.min(1,t+s),1-Math.min(1,i+s),1-Math.min(1,e+s)]}static CMYK_rgb([t,e,i,s]){return[scaleAndClamp(1-Math.min(1,t+s)),scaleAndClamp(1-Math.min(1,i+s)),scaleAndClamp(1-Math.min(1,e+s))]}static CMYK_HTML(t){const e=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(e)}static RGB_CMYK([t,e,i]){const s=1-t,n=1-e,a=1-i;return["CMYK",s,n,a,Math.min(s,n,a)]}}class BaseSVGFactory{create(t,e,i=!1){if(t<=0||e<=0)throw new Error("Invalid SVG dimensions");const s=this._createSVG("svg:svg");s.setAttribute("version","1.1");if(!i){s.setAttribute("width",`${t}px`);s.setAttribute("height",`${e}px`)}s.setAttribute("preserveAspectRatio","none");s.setAttribute("viewBox",`0 0 ${t} ${e}`);return s}createElement(t){if("string"!=typeof t)throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){unreachable("Abstract method `_createSVG` called.")}}class DOMSVGFactory extends BaseSVGFactory{_createSVG(t){return document.createElementNS(it,t)}}class XfaLayer{static setupStorage(t,e,i,s,n){const a=s.getValue(e,{value:null});switch(i.name){case"textarea":null!==a.value&&(t.textContent=a.value);if("print"===n)break;t.addEventListener("input",(t=>{s.setValue(e,{value:t.target.value})}));break;case"input":if("radio"===i.attributes.type||"checkbox"===i.attributes.type){a.value===i.attributes.xfaOn?t.setAttribute("checked",!0):a.value===i.attributes.xfaOff&&t.removeAttribute("checked");if("print"===n)break;t.addEventListener("change",(t=>{s.setValue(e,{value:t.target.checked?t.target.getAttribute("xfaOn"):t.target.getAttribute("xfaOff")})}))}else{null!==a.value&&t.setAttribute("value",a.value);if("print"===n)break;t.addEventListener("input",(t=>{s.setValue(e,{value:t.target.value})}))}break;case"select":if(null!==a.value){t.setAttribute("value",a.value);for(const t of i.children)t.attributes.value===a.value?t.attributes.selected=!0:t.attributes.hasOwnProperty("selected")&&delete t.attributes.selected}t.addEventListener("input",(t=>{const i=t.target.options,n=-1===i.selectedIndex?"":i[i.selectedIndex].value;s.setValue(e,{value:n})}))}}static setAttributes({html:t,element:e,storage:i=null,intent:s,linkService:n}){const{attributes:a}=e,r=t instanceof HTMLAnchorElement;"radio"===a.type&&(a.name=`${a.name}-${s}`);for(const[e,i]of Object.entries(a))if(null!=i)switch(e){case"class":i.length&&t.setAttribute(e,i.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",i);break;case"style":Object.assign(t.style,i);break;case"textContent":t.textContent=i;break;default:(!r||"href"!==e&&"newWindow"!==e)&&t.setAttribute(e,i)}r&&n.addLinkAttributes(t,a.href,a.newWindow);i&&a.dataId&&this.setupStorage(t,a.dataId,e,i)}static render(t){const e=t.annotationStorage,i=t.linkService,s=t.xfaHtml,n=t.intent||"display",a=document.createElement(s.name);s.attributes&&this.setAttributes({html:a,element:s,intent:n,linkService:i});const r="richText"!==n,o=t.div;o.append(a);if(t.viewport){const e=`matrix(${t.viewport.transform.join(",")})`;o.style.transform=e}r&&o.setAttribute("class","xfaLayer xfaFont");const l=[];if(0===s.children.length){if(s.value){const t=document.createTextNode(s.value);a.append(t);r&&XfaText.shouldBuildText(s.name)&&l.push(t)}return{textDivs:l}}const h=[[s,-1,a]];for(;h.length>0;){const[t,s,a]=h.at(-1);if(s+1===t.children.length){h.pop();continue}const o=t.children[++h.at(-1)[1]];if(null===o)continue;const{name:d}=o;if("#text"===d){const t=document.createTextNode(o.value);l.push(t);a.append(t);continue}const c=o?.attributes?.xmlns?document.createElementNS(o.attributes.xmlns,d):document.createElement(d);a.append(c);o.attributes&&this.setAttributes({html:c,element:o,storage:e,intent:n,linkService:i});if(o.children?.length>0)h.push([o,-1,c]);else if(o.value){const t=document.createTextNode(o.value);r&&XfaText.shouldBuildText(d)&&l.push(t);c.append(t)}}for(const t of o.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))t.setAttribute("readOnly",!0);return{textDivs:l}}static update(t){const e=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=e;t.div.hidden=!1}}const Bt=1e3,Ht=new WeakSet;function getRectDims(t){return{width:t[2]-t[0],height:t[3]-t[1]}}class AnnotationElementFactory{static create(t){switch(t.data.annotationType){case S:return new LinkAnnotationElement(t);case E:return new TextAnnotationElement(t);case U:switch(t.data.fieldType){case"Tx":return new TextWidgetAnnotationElement(t);case"Btn":return t.data.radioButton?new RadioButtonWidgetAnnotationElement(t):t.data.checkBox?new CheckboxWidgetAnnotationElement(t):new PushButtonWidgetAnnotationElement(t);case"Ch":return new ChoiceWidgetAnnotationElement(t);case"Sig":return new SignatureWidgetAnnotationElement(t)}return new WidgetAnnotationElement(t);case H:return new PopupAnnotationElement(t);case C:return new FreeTextAnnotationElement(t);case T:return new LineAnnotationElement(t);case M:return new SquareAnnotationElement(t);case P:return new CircleAnnotationElement(t);case k:return new PolylineAnnotationElement(t);case N:return new CaretAnnotationElement(t);case B:return new InkAnnotationElement(t);case D:return new PolygonAnnotationElement(t);case R:return new HighlightAnnotationElement(t);case I:return new UnderlineAnnotationElement(t);case F:return new SquigglyAnnotationElement(t);case L:return new StrikeOutAnnotationElement(t);case O:return new StampAnnotationElement(t);case z:return new FileAttachmentAnnotationElement(t);default:return new AnnotationElement(t)}}}class AnnotationElement{#Hs=null;#zs=!1;#Us=null;constructor(t,{isRenderable:e=!1,ignoreBorder:i=!1,createQuadrilaterals:s=!1}={}){this.isRenderable=e;this.data=t.data;this.layer=t.layer;this.linkService=t.linkService;this.downloadManager=t.downloadManager;this.imageResourcesPath=t.imageResourcesPath;this.renderForms=t.renderForms;this.svgFactory=t.svgFactory;this.annotationStorage=t.annotationStorage;this.enableScripting=t.enableScripting;this.hasJSActions=t.hasJSActions;this._fieldObjects=t.fieldObjects;this.parent=t.parent;e&&(this.container=this._createContainer(i));s&&this._createQuadrilaterals()}static _hasPopupData({titleObj:t,contentsObj:e,richText:i}){return!!(t?.str||e?.str||i?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return AnnotationElement._hasPopupData(this.data)}updateEdited(t){if(!this.container)return;this.#Hs||={rect:this.data.rect.slice(0)};const{rect:e}=t;e&&this.#Gs(e);this.#Us?.popup.updateEdited(t)}resetEdited(){if(this.#Hs){this.#Gs(this.#Hs.rect);this.#Us?.popup.resetEdited();this.#Hs=null}}#Gs(t){const{container:{style:e},data:{rect:i,rotation:s},parent:{viewport:{rawDims:{pageWidth:n,pageHeight:a,pageX:r,pageY:o}}}}=this;i?.splice(0,4,...t);const{width:l,height:h}=getRectDims(t);e.left=100*(t[0]-r)/n+"%";e.top=100*(a-t[3]+o)/a+"%";if(0===s){e.width=100*l/n+"%";e.height=100*h/a+"%"}else this.setRotation(s)}_createContainer(t){const{data:e,parent:{page:i,viewport:s}}=this,n=document.createElement("section");n.setAttribute("data-annotation-id",e.id);this instanceof WidgetAnnotationElement||(n.tabIndex=Bt);const{style:a}=n;a.zIndex=this.parent.zIndex++;e.alternativeText&&(n.title=e.alternativeText);e.noRotate&&n.classList.add("norotate");if(!e.rect||this instanceof PopupAnnotationElement){const{rotation:t}=e;e.hasOwnCanvas||0===t||this.setRotation(t,n);return n}const{width:r,height:o}=getRectDims(e.rect);if(!t&&e.borderStyle.width>0){a.borderWidth=`${e.borderStyle.width}px`;const t=e.borderStyle.horizontalCornerRadius,i=e.borderStyle.verticalCornerRadius;if(t>0||i>0){const e=`calc(${t}px * var(--scale-factor)) / calc(${i}px * var(--scale-factor))`;a.borderRadius=e}else if(this instanceof RadioButtonWidgetAnnotationElement){const t=`calc(${r}px * var(--scale-factor)) / calc(${o}px * var(--scale-factor))`;a.borderRadius=t}switch(e.borderStyle.style){case G:a.borderStyle="solid";break;case $:a.borderStyle="dashed";break;case V:warn("Unimplemented border style: beveled");break;case j:warn("Unimplemented border style: inset");break;case W:a.borderBottomStyle="solid"}const s=e.borderColor||null;if(s){this.#zs=!0;a.borderColor=Util.makeHexColor(0|s[0],0|s[1],0|s[2])}else a.borderWidth=0}const l=Util.normalizeRect([e.rect[0],i.view[3]-e.rect[1]+i.view[1],e.rect[2],i.view[3]-e.rect[3]+i.view[1]]),{pageWidth:h,pageHeight:d,pageX:c,pageY:u}=s.rawDims;a.left=100*(l[0]-c)/h+"%";a.top=100*(l[1]-u)/d+"%";const{rotation:p}=e;if(e.hasOwnCanvas||0===p){a.width=100*r/h+"%";a.height=100*o/d+"%"}else this.setRotation(p,n);return n}setRotation(t,e=this.container){if(!this.data.rect)return;const{pageWidth:i,pageHeight:s}=this.parent.viewport.rawDims,{width:n,height:a}=getRectDims(this.data.rect);let r,o;if(t%180==0){r=100*n/i;o=100*a/s}else{r=100*a/i;o=100*n/s}e.style.width=`${r}%`;e.style.height=`${o}%`;e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const setColor=(t,e,i)=>{const s=i.detail[t],n=s[0],a=s.slice(1);i.target.style[e]=ColorConverters[`${n}_HTML`](a);this.annotationStorage.setValue(this.data.id,{[e]:ColorConverters[`${n}_rgb`](a)})};return shadow(this,"_commonActions",{display:t=>{const{display:e}=t.detail,i=e%2==1;this.container.style.visibility=i?"hidden":"visible";this.annotationStorage.setValue(this.data.id,{noView:i,noPrint:1===e||2===e})},print:t=>{this.annotationStorage.setValue(this.data.id,{noPrint:!t.detail.print})},hidden:t=>{const{hidden:e}=t.detail;this.container.style.visibility=e?"hidden":"visible";this.annotationStorage.setValue(this.data.id,{noPrint:e,noView:e})},focus:t=>{setTimeout((()=>t.target.focus({preventScroll:!1})),0)},userName:t=>{t.target.title=t.detail.userName},readonly:t=>{t.target.disabled=t.detail.readonly},required:t=>{this._setRequired(t.target,t.detail.required)},bgColor:t=>{setColor("bgColor","backgroundColor",t)},fillColor:t=>{setColor("fillColor","backgroundColor",t)},fgColor:t=>{setColor("fgColor","color",t)},textColor:t=>{setColor("textColor","color",t)},borderColor:t=>{setColor("borderColor","borderColor",t)},strokeColor:t=>{setColor("strokeColor","borderColor",t)},rotation:t=>{const e=t.detail.rotation;this.setRotation(e);this.annotationStorage.setValue(this.data.id,{rotation:e})}})}_dispatchEventFromSandbox(t,e){const i=this._commonActions;for(const s of Object.keys(e.detail)){const n=t[s]||i[s];n?.(e)}}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;const e=this.annotationStorage.getRawValue(this.data.id);if(!e)return;const i=this._commonActions;for(const[s,n]of Object.entries(e)){const a=i[s];if(a){a({detail:{[s]:n},target:t});delete e[s]}}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:t}=this.data;if(!t)return;const[e,i,s,n]=this.data.rect.map((t=>Math.fround(t)));if(8===t.length){const[a,r,o,l]=t.subarray(2,6);if(s===a&&n===r&&e===o&&i===l)return}const{style:a}=this.container;let r;if(this.#zs){const{borderColor:t,borderWidth:e}=a;a.borderWidth=0;r=["url('data:image/svg+xml;utf8,",'',``];this.container.classList.add("hasBorder")}const o=s-e,l=n-i,{svgFactory:h}=this,d=h.createElement("svg");d.classList.add("quadrilateralsContainer");d.setAttribute("width",0);d.setAttribute("height",0);const c=h.createElement("defs");d.append(c);const u=h.createElement("clipPath"),p=`clippath_${this.data.id}`;u.setAttribute("id",p);u.setAttribute("clipPathUnits","objectBoundingBox");c.append(u);for(let i=2,s=t.length;i`)}if(this.#zs){r.push("')");a.backgroundImage=r.join("")}this.container.append(d);this.container.style.clipPath=`url(#${p})`}_createPopup(){const{data:t}=this,e=this.#Us=new PopupAnnotationElement({data:{color:t.color,titleObj:t.titleObj,modificationDate:t.modificationDate,contentsObj:t.contentsObj,richText:t.richText,parentRect:t.rect,borderStyle:0,id:`popup_${t.id}`,rotation:t.rotation},parent:this.parent,elements:[this]});this.parent.div.append(e.render())}render(){unreachable("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){const i=[];if(this._fieldObjects){const s=this._fieldObjects[t];if(s)for(const{page:t,id:n,exportValues:a}of s){if(-1===t)continue;if(n===e)continue;const s="string"==typeof a?a:null,r=document.querySelector(`[data-element-id="${n}"]`);!r||Ht.has(r)?i.push({id:n,exportValue:s,domElement:r}):warn(`_getElementsByName - element not allowed: ${n}`)}return i}for(const s of document.getElementsByName(t)){const{exportValue:t}=s,n=s.getAttribute("data-element-id");n!==e&&(Ht.has(s)&&i.push({id:n,exportValue:t,domElement:s}))}return i}show(){this.container&&(this.container.hidden=!1);this.popup?.maybeShow()}hide(){this.container&&(this.container.hidden=!0);this.popup?.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){const t=this.getElementsToTriggerPopup();if(Array.isArray(t))for(const e of t)e.classList.add("highlightArea");else t.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;const{annotationEditorType:t,data:{id:e}}=this;this.container.addEventListener("dblclick",(()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:t,editId:e})}))}}class LinkAnnotationElement extends AnnotationElement{constructor(t,e=null){super(t,{isRenderable:!0,ignoreBorder:!!e?.ignoreBorder,createQuadrilaterals:!0});this.isTooltipOnly=t.data.isTooltipOnly}render(){const{data:t,linkService:e}=this,i=document.createElement("a");i.setAttribute("data-element-id",t.id);let s=!1;if(t.url){e.addLinkAttributes(i,t.url,t.newWindow);s=!0}else if(t.action){this._bindNamedAction(i,t.action);s=!0}else if(t.attachment){this.#$s(i,t.attachment,t.attachmentDest);s=!0}else if(t.setOCGState){this.#Vs(i,t.setOCGState);s=!0}else if(t.dest){this._bindLink(i,t.dest);s=!0}else{if(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions){this._bindJSAction(i,t);s=!0}if(t.resetForm){this._bindResetFormAction(i,t.resetForm);s=!0}else if(this.isTooltipOnly&&!s){this._bindLink(i,"");s=!0}}this.container.classList.add("linkAnnotation");s&&this.container.append(i);return this.container}#js(){this.container.setAttribute("data-internal-link","")}_bindLink(t,e){t.href=this.linkService.getDestinationHash(e);t.onclick=()=>{e&&this.linkService.goToDestination(e);return!1};(e||""===e)&&this.#js()}_bindNamedAction(t,e){t.href=this.linkService.getAnchorUrl("");t.onclick=()=>{this.linkService.executeNamedAction(e);return!1};this.#js()}#$s(t,e,i=null){t.href=this.linkService.getAnchorUrl("");e.description&&(t.title=e.description);t.onclick=()=>{this.downloadManager?.openOrDownloadData(e.content,e.filename,i);return!1};this.#js()}#Vs(t,e){t.href=this.linkService.getAnchorUrl("");t.onclick=()=>{this.linkService.executeSetOCGState(e);return!1};this.#js()}_bindJSAction(t,e){t.href=this.linkService.getAnchorUrl("");const i=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const s of Object.keys(e.actions)){const n=i.get(s);n&&(t[n]=()=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e.id,name:s}});return!1})}t.onclick||(t.onclick=()=>!1);this.#js()}_bindResetFormAction(t,e){const i=t.onclick;i||(t.href=this.linkService.getAnchorUrl(""));this.#js();if(this._fieldObjects)t.onclick=()=>{i?.();const{fields:t,refs:s,include:n}=e,a=[];if(0!==t.length||0!==s.length){const e=new Set(s);for(const i of t){const t=this._fieldObjects[i]||[];for(const{id:i}of t)e.add(i)}for(const t of Object.values(this._fieldObjects))for(const i of t)e.has(i.id)===n&&a.push(i)}else for(const t of Object.values(this._fieldObjects))a.push(...t);const r=this.annotationStorage,o=[];for(const t of a){const{id:e}=t;o.push(e);switch(t.type){case"text":{const i=t.defaultValue||"";r.setValue(e,{value:i});break}case"checkbox":case"radiobutton":{const i=t.defaultValue===t.exportValues;r.setValue(e,{value:i});break}case"combobox":case"listbox":{const i=t.defaultValue||"";r.setValue(e,{value:i});break}default:continue}const i=document.querySelector(`[data-element-id="${e}"]`);i&&(Ht.has(i)?i.dispatchEvent(new Event("resetform")):warn(`_bindResetFormAction - element not allowed: ${e}`))}this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:o,name:"ResetForm"}});return!1};else{warn('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.');i||(t.onclick=()=>!1)}}}class TextAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");const t=document.createElement("img");t.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg";t.setAttribute("data-l10n-id","pdfjs-text-annotation-type");t.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name}));!this.data.popupRef&&this.hasPopupData&&this._createPopup();this.container.append(t);return this.container}}class WidgetAnnotationElement extends AnnotationElement{render(){return this.container}showElementAndHideCanvas(t){if(this.data.hasOwnCanvas){"CANVAS"===t.previousSibling?.nodeName&&(t.previousSibling.hidden=!0);t.hidden=!1}}_getKeyModifier(t){return util_FeatureTest.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,e,i,s,n){i.includes("mouse")?t.addEventListener(i,(t=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:s,value:n(t),shift:t.shiftKey,modifier:this._getKeyModifier(t)}})})):t.addEventListener(i,(t=>{if("blur"===i){if(!e.focused||!t.relatedTarget)return;e.focused=!1}else if("focus"===i){if(e.focused)return;e.focused=!0}n&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:s,value:n(t)}})}))}_setEventListeners(t,e,i,s){for(const[n,a]of i)if("Action"===a||this.data.actions?.[a]){"Focus"!==a&&"Blur"!==a||(e||={focused:!1});this._setEventListener(t,e,n,a,s);"Focus"!==a||this.data.actions?.Blur?"Blur"!==a||this.data.actions?.Focus||this._setEventListener(t,e,"focus","Focus",null):this._setEventListener(t,e,"blur","Blur",null)}}_setBackgroundColor(t){const e=this.data.backgroundColor||null;t.style.backgroundColor=null===e?"transparent":Util.makeHexColor(e[0],e[1],e[2])}_setTextStyle(t){const e=["left","center","right"],{fontColor:i}=this.data.defaultAppearanceData,s=this.data.defaultAppearanceData.fontSize||9,a=t.style;let r;const roundToOneDecimal=t=>Math.round(10*t)/10;if(this.data.multiLine){const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2),e=t/(Math.round(t/(n*s))||1);r=Math.min(s,roundToOneDecimal(e/n))}else{const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2);r=Math.min(s,roundToOneDecimal(t/n))}a.fontSize=`calc(${r}px * var(--scale-factor))`;a.color=Util.makeHexColor(i[0],i[1],i[2]);null!==this.data.textAlignment&&(a.textAlign=e[this.data.textAlignment])}_setRequired(t,e){e?t.setAttribute("required",!0):t.removeAttribute("required");t.setAttribute("aria-required",e)}}class TextWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms||t.data.hasOwnCanvas||!t.data.hasAppearance&&!!t.data.fieldValue})}setPropertyOnSiblings(t,e,i,s){const n=this.annotationStorage;for(const a of this._getElementsByName(t.name,t.id)){a.domElement&&(a.domElement[e]=i);n.setValue(a.id,{[s]:i})}}render(){const t=this.annotationStorage,e=this.data.id;this.container.classList.add("textWidgetAnnotation");let i=null;if(this.renderForms){const s=t.getValue(e,{value:this.data.fieldValue});let n=s.value||"";const a=t.getValue(e,{charLimit:this.data.maxLen}).charLimit;a&&n.length>a&&(n=n.slice(0,a));let r=s.formattedValue||this.data.textContent?.join("\n")||null;r&&this.data.comb&&(r=r.replaceAll(/\s+/g,""));const o={userValue:n,formattedValue:r,lastCommittedValue:null,commitKey:1,focused:!1};if(this.data.multiLine){i=document.createElement("textarea");i.textContent=r??n;this.data.doNotScroll&&(i.style.overflowY="hidden")}else{i=document.createElement("input");i.type="text";i.setAttribute("value",r??n);this.data.doNotScroll&&(i.style.overflowX="hidden")}this.data.hasOwnCanvas&&(i.hidden=!0);Ht.add(i);i.setAttribute("data-element-id",e);i.disabled=this.data.readOnly;i.name=this.data.fieldName;i.tabIndex=Bt;this._setRequired(i,this.data.required);a&&(i.maxLength=a);i.addEventListener("input",(s=>{t.setValue(e,{value:s.target.value});this.setPropertyOnSiblings(i,"value",s.target.value,"value");o.formattedValue=null}));i.addEventListener("resetform",(t=>{const e=this.data.defaultFieldValue??"";i.value=o.userValue=e;o.formattedValue=null}));let blurListener=t=>{const{formattedValue:e}=o;null!=e&&(t.target.value=e);t.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){i.addEventListener("focus",(t=>{if(o.focused)return;const{target:e}=t;o.userValue&&(e.value=o.userValue);o.lastCommittedValue=e.value;o.commitKey=1;this.data.actions?.Focus||(o.focused=!0)}));i.addEventListener("updatefromsandbox",(i=>{this.showElementAndHideCanvas(i.target);const s={value(i){o.userValue=i.detail.value??"";t.setValue(e,{value:o.userValue.toString()});i.target.value=o.userValue},formattedValue(i){const{formattedValue:s}=i.detail;o.formattedValue=s;null!=s&&i.target!==document.activeElement&&(i.target.value=s);t.setValue(e,{formattedValue:s})},selRange(t){t.target.setSelectionRange(...t.detail.selRange)},charLimit:i=>{const{charLimit:s}=i.detail,{target:n}=i;if(0===s){n.removeAttribute("maxLength");return}n.setAttribute("maxLength",s);let a=o.userValue;if(a&&!(a.length<=s)){a=a.slice(0,s);n.value=o.userValue=a;t.setValue(e,{value:a});this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:a,willCommit:!0,commitKey:1,selStart:n.selectionStart,selEnd:n.selectionEnd}})}}};this._dispatchEventFromSandbox(s,i)}));i.addEventListener("keydown",(t=>{o.commitKey=1;let i=-1;"Escape"===t.key?i=0:"Enter"!==t.key||this.data.multiLine?"Tab"===t.key&&(o.commitKey=3):i=2;if(-1===i)return;const{value:s}=t.target;if(o.lastCommittedValue!==s){o.lastCommittedValue=s;o.userValue=s;this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:s,willCommit:!0,commitKey:i,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}})}}));const s=blurListener;blurListener=null;i.addEventListener("blur",(t=>{if(!o.focused||!t.relatedTarget)return;this.data.actions?.Blur||(o.focused=!1);const{value:i}=t.target;o.userValue=i;o.lastCommittedValue!==i&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:i,willCommit:!0,commitKey:o.commitKey,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}});s(t)}));this.data.actions?.Keystroke&&i.addEventListener("beforeinput",(t=>{o.lastCommittedValue=null;const{data:i,target:s}=t,{value:n,selectionStart:a,selectionEnd:r}=s;let l=a,h=r;switch(t.inputType){case"deleteWordBackward":{const t=n.substring(0,a).match(/\w*[^\w]*$/);t&&(l-=t[0].length);break}case"deleteWordForward":{const t=n.substring(a).match(/^[^\w]*\w*/);t&&(h+=t[0].length);break}case"deleteContentBackward":a===r&&(l-=1);break;case"deleteContentForward":a===r&&(h+=1)}t.preventDefault();this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:n,change:i||"",willCommit:!1,selStart:l,selEnd:h}})}));this._setEventListeners(i,o,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.value))}blurListener&&i.addEventListener("blur",blurListener);if(this.data.comb){const t=(this.data.rect[2]-this.data.rect[0])/a;i.classList.add("comb");i.style.letterSpacing=`calc(${t}px * var(--scale-factor) - 1ch)`}}else{i=document.createElement("div");i.textContent=this.data.fieldValue;i.style.verticalAlign="middle";i.style.display="table-cell";this.data.hasOwnCanvas&&(i.hidden=!0)}this._setTextStyle(i);this._setBackgroundColor(i);this._setDefaultPropertiesFromJS(i);this.container.append(i);return this.container}}class SignatureWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){const t=this.annotationStorage,e=this.data,i=e.id;let s=t.getValue(i,{value:e.exportValue===e.fieldValue}).value;if("string"==typeof s){s="Off"!==s;t.setValue(i,{value:s})}this.container.classList.add("buttonWidgetAnnotation","checkBox");const n=document.createElement("input");Ht.add(n);n.setAttribute("data-element-id",i);n.disabled=e.readOnly;this._setRequired(n,this.data.required);n.type="checkbox";n.name=e.fieldName;s&&n.setAttribute("checked",!0);n.setAttribute("exportValue",e.exportValue);n.tabIndex=Bt;n.addEventListener("change",(s=>{const{name:n,checked:a}=s.target;for(const s of this._getElementsByName(n,i)){const i=a&&s.exportValue===e.exportValue;s.domElement&&(s.domElement.checked=i);t.setValue(s.id,{value:i})}t.setValue(i,{value:a})}));n.addEventListener("resetform",(t=>{const i=e.defaultFieldValue||"Off";t.target.checked=i===e.exportValue}));if(this.enableScripting&&this.hasJSActions){n.addEventListener("updatefromsandbox",(e=>{const s={value(e){e.target.checked="Off"!==e.detail.value;t.setValue(i,{value:e.target.checked})}};this._dispatchEventFromSandbox(s,e)}));this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.checked))}this._setBackgroundColor(n);this._setDefaultPropertiesFromJS(n);this.container.append(n);return this.container}}class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const t=this.annotationStorage,e=this.data,i=e.id;let s=t.getValue(i,{value:e.fieldValue===e.buttonValue}).value;if("string"==typeof s){s=s!==e.buttonValue;t.setValue(i,{value:s})}if(s)for(const s of this._getElementsByName(e.fieldName,i))t.setValue(s.id,{value:!1});const n=document.createElement("input");Ht.add(n);n.setAttribute("data-element-id",i);n.disabled=e.readOnly;this._setRequired(n,this.data.required);n.type="radio";n.name=e.fieldName;s&&n.setAttribute("checked",!0);n.tabIndex=Bt;n.addEventListener("change",(e=>{const{name:s,checked:n}=e.target;for(const e of this._getElementsByName(s,i))t.setValue(e.id,{value:!1});t.setValue(i,{value:n})}));n.addEventListener("resetform",(t=>{const i=e.defaultFieldValue;t.target.checked=null!=i&&i===e.buttonValue}));if(this.enableScripting&&this.hasJSActions){const s=e.buttonValue;n.addEventListener("updatefromsandbox",(e=>{const n={value:e=>{const n=s===e.detail.value;for(const s of this._getElementsByName(e.target.name)){const e=n&&s.id===i;s.domElement&&(s.domElement.checked=e);t.setValue(s.id,{value:e})}}};this._dispatchEventFromSandbox(n,e)}));this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.checked))}this._setBackgroundColor(n);this._setDefaultPropertiesFromJS(n);this.container.append(n);return this.container}}class PushButtonWidgetAnnotationElement extends LinkAnnotationElement{constructor(t){super(t,{ignoreBorder:t.data.hasAppearance})}render(){const t=super.render();t.classList.add("buttonWidgetAnnotation","pushButton");const e=t.lastChild;if(this.enableScripting&&this.hasJSActions&&e){this._setDefaultPropertiesFromJS(e);e.addEventListener("updatefromsandbox",(t=>{this._dispatchEventFromSandbox({},t)}))}return t}}class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");const t=this.annotationStorage,e=this.data.id,i=t.getValue(e,{value:this.data.fieldValue}),s=document.createElement("select");Ht.add(s);s.setAttribute("data-element-id",e);s.disabled=this.data.readOnly;this._setRequired(s,this.data.required);s.name=this.data.fieldName;s.tabIndex=Bt;let n=this.data.combo&&this.data.options.length>0;if(!this.data.combo){s.size=this.data.options.length;this.data.multiSelect&&(s.multiple=!0)}s.addEventListener("resetform",(t=>{const e=this.data.defaultFieldValue;for(const t of s.options)t.selected=t.value===e}));for(const t of this.data.options){const e=document.createElement("option");e.textContent=t.displayValue;e.value=t.exportValue;if(i.value.includes(t.exportValue)){e.setAttribute("selected",!0);n=!1}s.append(e)}let a=null;if(n){const t=document.createElement("option");t.value=" ";t.setAttribute("hidden",!0);t.setAttribute("selected",!0);s.prepend(t);a=()=>{t.remove();s.removeEventListener("input",a);a=null};s.addEventListener("input",a)}const getValue=t=>{const e=t?"value":"textContent",{options:i,multiple:n}=s;return n?Array.prototype.filter.call(i,(t=>t.selected)).map((t=>t[e])):-1===i.selectedIndex?null:i[i.selectedIndex][e]};let r=getValue(!1);const getItems=t=>{const e=t.target.options;return Array.prototype.map.call(e,(t=>({displayValue:t.textContent,exportValue:t.value})))};if(this.enableScripting&&this.hasJSActions){s.addEventListener("updatefromsandbox",(i=>{const n={value(i){a?.();const n=i.detail.value,o=new Set(Array.isArray(n)?n:[n]);for(const t of s.options)t.selected=o.has(t.value);t.setValue(e,{value:getValue(!0)});r=getValue(!1)},multipleSelection(t){s.multiple=!0},remove(i){const n=s.options,a=i.detail.remove;n[a].selected=!1;s.remove(a);if(n.length>0){-1===Array.prototype.findIndex.call(n,(t=>t.selected))&&(n[0].selected=!0)}t.setValue(e,{value:getValue(!0),items:getItems(i)});r=getValue(!1)},clear(i){for(;0!==s.length;)s.remove(0);t.setValue(e,{value:null,items:[]});r=getValue(!1)},insert(i){const{index:n,displayValue:a,exportValue:o}=i.detail.insert,l=s.children[n],h=document.createElement("option");h.textContent=a;h.value=o;l?l.before(h):s.append(h);t.setValue(e,{value:getValue(!0),items:getItems(i)});r=getValue(!1)},items(i){const{items:n}=i.detail;for(;0!==s.length;)s.remove(0);for(const t of n){const{displayValue:e,exportValue:i}=t,n=document.createElement("option");n.textContent=e;n.value=i;s.append(n)}s.options.length>0&&(s.options[0].selected=!0);t.setValue(e,{value:getValue(!0),items:getItems(i)});r=getValue(!1)},indices(i){const s=new Set(i.detail.indices);for(const t of i.target.options)t.selected=s.has(t.index);t.setValue(e,{value:getValue(!0)});r=getValue(!1)},editable(t){t.target.disabled=!t.detail.editable}};this._dispatchEventFromSandbox(n,i)}));s.addEventListener("input",(i=>{const s=getValue(!0),n=getValue(!1);t.setValue(e,{value:s});i.preventDefault();this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:r,change:n,changeEx:s,willCommit:!1,commitKey:1,keyDown:!1}})}));this._setEventListeners(s,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],(t=>t.target.value))}else s.addEventListener("input",(function(i){t.setValue(e,{value:getValue(!0)})}));this.data.combo&&this._setTextStyle(s);this._setBackgroundColor(s);this._setDefaultPropertiesFromJS(s);this.container.append(s);return this.container}}class PopupAnnotationElement extends AnnotationElement{constructor(t){const{data:e,elements:i}=t;super(t,{isRenderable:AnnotationElement._hasPopupData(e)});this.elements=i;this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new PopupElement({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate,contentsObj:this.data.contentsObj,richText:this.data.richText,rect:this.data.rect,parentRect:this.data.parentRect||null,parent:this.parent,elements:this.elements,open:this.data.open}),e=[];for(const i of this.elements){i.popup=t;i.container.ariaHasPopup="dialog";e.push(i.data.id);i.addHighlightArea()}this.container.setAttribute("aria-controls",e.map((t=>`${et}${t}`)).join(","));return this.container}}class PopupElement{#Ws=this.#qs.bind(this);#Xs=this.#Ks.bind(this);#Ys=this.#Qs.bind(this);#Js=this.#Zs.bind(this);#tn=null;#pt=null;#en=null;#in=null;#sn=null;#nn=null;#an=null;#rn=!1;#on=null;#C=null;#ln=null;#hn=null;#dn=null;#Hs=null;#cn=!1;constructor({container:t,color:e,elements:i,titleObj:s,modificationDate:n,contentsObj:a,richText:r,parent:o,rect:l,parentRect:h,open:d}){this.#pt=t;this.#dn=s;this.#en=a;this.#hn=r;this.#nn=o;this.#tn=e;this.#ln=l;this.#an=h;this.#sn=i;this.#in=PDFDateString.toDateObject(n);this.trigger=i.flatMap((t=>t.getElementsToTriggerPopup()));for(const t of this.trigger){t.addEventListener("click",this.#Js);t.addEventListener("mouseenter",this.#Ys);t.addEventListener("mouseleave",this.#Xs);t.classList.add("popupTriggerArea")}for(const t of i)t.container?.addEventListener("keydown",this.#Ws);this.#pt.hidden=!0;d&&this.#Zs()}render(){if(this.#on)return;const t=this.#on=document.createElement("div");t.className="popup";if(this.#tn){const e=t.style.outlineColor=Util.makeHexColor(...this.#tn);if(CSS.supports("background-color","color-mix(in srgb, red 30%, white)"))t.style.backgroundColor=`color-mix(in srgb, ${e} 30%, white)`;else{const e=.7;t.style.backgroundColor=Util.makeHexColor(...this.#tn.map((t=>Math.floor(e*(255-t)+t))))}}const e=document.createElement("span");e.className="header";const i=document.createElement("h1");e.append(i);({dir:i.dir,str:i.textContent}=this.#dn);t.append(e);if(this.#in){const t=document.createElement("span");t.classList.add("popupDate");t.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string");t.setAttribute("data-l10n-args",JSON.stringify({dateObj:this.#in.valueOf()}));e.append(t)}const s=this.#un;if(s){XfaLayer.render({xfaHtml:s,intent:"richText",div:t});t.lastChild.classList.add("richText","popupContent")}else{const e=this._formatContents(this.#en);t.append(e)}this.#pt.append(t)}get#un(){const t=this.#hn,e=this.#en;return!t?.str||e?.str&&e.str!==t.str?null:this.#hn.html||null}get#pn(){return this.#un?.attributes?.style?.fontSize||0}get#gn(){return this.#un?.attributes?.style?.color||null}#mn(t){const e=[],i={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},s={style:{color:this.#gn,fontSize:this.#pn?`calc(${this.#pn}px * var(--scale-factor))`:""}};for(const i of t.split("\n"))e.push({name:"span",value:i,attributes:s});return i}_formatContents({str:t,dir:e}){const i=document.createElement("p");i.classList.add("popupContent");i.dir=e;const s=t.split(/(?:\r\n?|\n)/);for(let t=0,e=s.length;t=0&&n.setAttribute("stroke-width",e||1);if(i)for(let t=0,e=this.#xn.length;t{"Enter"===t.key&&(s?t.metaKey:t.ctrlKey)&&this.#Sn()}));!e.popupRef&&this.hasPopupData?this._createPopup():i.classList.add("popupTriggerArea");t.append(i);return t}getElementsToTriggerPopup(){return this.#En}addHighlightArea(){this.container.classList.add("highlightArea")}#Sn(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}}class AnnotationLayer{#Cn=null;#Tn=null;#Mn=new Map;#Pn=null;constructor({div:t,accessibilityManager:e,annotationCanvasMap:i,annotationEditorUIManager:s,page:n,viewport:a,structTreeLayer:r}){this.div=t;this.#Cn=e;this.#Tn=i;this.#Pn=r||null;this.page=n;this.viewport=a;this.zIndex=0;this._annotationEditorUIManager=s}hasEditableAnnotations(){return this.#Mn.size>0}async#Dn(t,e){const i=t.firstChild||t,s=i.id=`${et}${e}`,n=await(this.#Pn?.getAriaAttributes(s));if(n)for(const[t,e]of n)i.setAttribute(t,e);this.div.append(t);this.#Cn?.moveElementInDOM(this.div,t,i,!1)}async render(t){const{annotations:e}=t,i=this.div;setLayerDimensions(i,this.viewport);const s=new Map,n={data:null,layer:i,linkService:t.linkService,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:!1!==t.renderForms,svgFactory:new DOMSVGFactory,annotationStorage:t.annotationStorage||new AnnotationStorage,enableScripting:!0===t.enableScripting,hasJSActions:t.hasJSActions,fieldObjects:t.fieldObjects,parent:this,elements:null};for(const t of e){if(t.noHTML)continue;const e=t.annotationType===H;if(e){const e=s.get(t.id);if(!e)continue;n.elements=e}else{const{width:e,height:i}=getRectDims(t.rect);if(e<=0||i<=0)continue}n.data=t;const i=AnnotationElementFactory.create(n);if(!i.isRenderable)continue;if(!e&&t.popupRef){const e=s.get(t.popupRef);e?e.push(i):s.set(t.popupRef,[i])}const a=i.render();t.hidden&&(a.style.visibility="hidden");await this.#Dn(a,t.id);if(i._isEditable){this.#Mn.set(i.data.id,i);this._annotationEditorUIManager?.renderAnnotationElement(i)}}this.#kn()}update({viewport:t}){const e=this.div;this.viewport=t;setLayerDimensions(e,{rotation:t.rotation});this.#kn();e.hidden=!1}#kn(){if(!this.#Tn)return;const t=this.div;for(const[e,i]of this.#Tn){const s=t.querySelector(`[data-annotation-id="${e}"]`);if(!s)continue;i.className="annotationContent";const{firstChild:n}=s;n?"CANVAS"===n.nodeName?n.replaceWith(i):n.classList.contains("annotationContent")?n.after(i):n.before(i):s.append(i)}this.#Tn.clear()}getEditableAnnotations(){return Array.from(this.#Mn.values())}getEditableAnnotation(t){return this.#Mn.get(t)}}const zt=/\r\n?|\n/g;class FreeTextEditor extends AnnotationEditor{#tn;#Rn="";#In=`${this.id}-editor`;#Fn=null;#pn;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){const t=FreeTextEditor.prototype,arrowChecker=t=>t.isEmpty(),e=AnnotationEditorUIManager.TRANSLATE_SMALL,i=AnnotationEditorUIManager.TRANSLATE_BIG;return shadow(this,"_keyboardManager",new KeyboardManager([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],t.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],t.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],t._translateEmpty,{args:[-e,0],checker:arrowChecker}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t._translateEmpty,{args:[-i,0],checker:arrowChecker}],[["ArrowRight","mac+ArrowRight"],t._translateEmpty,{args:[e,0],checker:arrowChecker}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t._translateEmpty,{args:[i,0],checker:arrowChecker}],[["ArrowUp","mac+ArrowUp"],t._translateEmpty,{args:[0,-e],checker:arrowChecker}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t._translateEmpty,{args:[0,-i],checker:arrowChecker}],[["ArrowDown","mac+ArrowDown"],t._translateEmpty,{args:[0,e],checker:arrowChecker}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t._translateEmpty,{args:[0,i],checker:arrowChecker}]]))}static _type="freetext";static _editorType=g.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"});this.#tn=t.color||FreeTextEditor._defaultColor||AnnotationEditor._defaultLineColor;this.#pn=t.fontSize||FreeTextEditor._defaultFontSize}static initialize(t,e){AnnotationEditor.initialize(t,e);const i=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(i.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,e){switch(t){case m.FREETEXT_SIZE:FreeTextEditor._defaultFontSize=e;break;case m.FREETEXT_COLOR:FreeTextEditor._defaultColor=e}}updateParams(t,e){switch(t){case m.FREETEXT_SIZE:this.#Ln(e);break;case m.FREETEXT_COLOR:this.#On(e)}}static get defaultPropertiesToUpdate(){return[[m.FREETEXT_SIZE,FreeTextEditor._defaultFontSize],[m.FREETEXT_COLOR,FreeTextEditor._defaultColor||AnnotationEditor._defaultLineColor]]}get propertiesToUpdate(){return[[m.FREETEXT_SIZE,this.#pn],[m.FREETEXT_COLOR,this.#tn]]}#Ln(t){const setFontsize=t=>{this.editorDiv.style.fontSize=`calc(${t}px * var(--scale-factor))`;this.translate(0,-(t-this.#pn)*this.parentScale);this.#pn=t;this.#Nn()},e=this.#pn;this.addCommands({cmd:setFontsize.bind(this,t),undo:setFontsize.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:m.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}#On(t){const setColor=t=>{this.#tn=this.editorDiv.style.color=t},e=this.#tn;this.addCommands({cmd:setColor.bind(this,t),undo:setColor.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:m.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(t,e){this._uiManager.translateSelectedEditors(t,e,!0)}getInitialTranslation(){const t=this.parentScale;return[-FreeTextEditor._internalPadding*t,-(FreeTextEditor._internalPadding+this.#pn)*t]}rebuild(){if(this.parent){super.rebuild();null!==this.div&&(this.isAttachedToDOM||this.parent.add(this))}}enableEditMode(){if(this.isInEditMode())return;this.parent.setEditingState(!1);this.parent.updateToolbar(g.FREETEXT);super.enableEditMode();this.overlayDiv.classList.remove("enabled");this.editorDiv.contentEditable=!0;this._isDraggable=!1;this.div.removeAttribute("aria-activedescendant");this.#Fn=new AbortController;const t=this._uiManager.combinedSignal(this.#Fn);this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:t});this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:t});this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:t});this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:t});this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:t})}disableEditMode(){if(this.isInEditMode()){this.parent.setEditingState(!0);super.disableEditMode();this.overlayDiv.classList.add("enabled");this.editorDiv.contentEditable=!1;this.div.setAttribute("aria-activedescendant",this.#In);this._isDraggable=!0;this.#Fn?.abort();this.#Fn=null;this.div.focus({preventScroll:!0});this.isEditing=!1;this.parent.div.classList.add("freetextEditing")}}focusin(t){if(this._focusEventsAllowed){super.focusin(t);t.target!==this.editorDiv&&this.editorDiv.focus()}}onceAdded(t){if(!this.width){this.enableEditMode();t&&this.editorDiv.focus();this._initialOptions?.isCentered&&this.center();this._initialOptions=null}}isEmpty(){return!this.editorDiv||""===this.editorDiv.innerText.trim()}remove(){this.isEditing=!1;if(this.parent){this.parent.setEditingState(!0);this.parent.div.classList.add("freetextEditing")}super.remove()}#Bn(){const t=[];this.editorDiv.normalize();let e=null;for(const i of this.editorDiv.childNodes)if(e?.nodeType!==Node.TEXT_NODE||"BR"!==i.nodeName){t.push(FreeTextEditor.#Hn(i));e=i}return t.join("\n")}#Nn(){const[t,e]=this.parentDimensions;let i;if(this.isAttachedToDOM)i=this.div.getBoundingClientRect();else{const{currentLayer:t,div:e}=this,s=e.style.display,n=e.classList.contains("hidden");e.classList.remove("hidden");e.style.display="hidden";t.div.append(this.div);i=e.getBoundingClientRect();e.remove();e.style.display=s;e.classList.toggle("hidden",n)}if(this.rotation%180==this.parentRotation%180){this.width=i.width/t;this.height=i.height/e}else{this.width=i.height/t;this.height=i.width/e}this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit();this.disableEditMode();const t=this.#Rn,e=this.#Rn=this.#Bn().trimEnd();if(t===e)return;const setText=t=>{this.#Rn=t;if(t){this.#zn();this._uiManager.rebuild(this);this.#Nn()}else this.remove()};this.addCommands({cmd:()=>{setText(e)},undo:()=>{setText(t)},mustExec:!1});this.#Nn()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode();this.editorDiv.focus()}dblclick(t){this.enterInEditMode()}keydown(t){if(t.target===this.div&&"Enter"===t.key){this.enterInEditMode();t.preventDefault()}}editorDivKeydown(t){FreeTextEditor._keyboardManager.exec(this,t)}editorDivFocus(t){this.isEditing=!0}editorDivBlur(t){this.isEditing=!1}editorDivInput(t){this.parent.div.classList.toggle("freetextEditing",this.isEmpty())}disableEditing(){this.editorDiv.setAttribute("role","comment");this.editorDiv.removeAttribute("aria-multiline")}enableEditing(){this.editorDiv.setAttribute("role","textbox");this.editorDiv.setAttribute("aria-multiline",!0)}render(){if(this.div)return this.div;let t,e;if(this.width){t=this.x;e=this.y}super.render();this.editorDiv=document.createElement("div");this.editorDiv.className="internal";this.editorDiv.setAttribute("id",this.#In);this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text2");this.editorDiv.setAttribute("data-l10n-attrs","default-content");this.enableEditing();this.editorDiv.contentEditable=!0;const{style:i}=this.editorDiv;i.fontSize=`calc(${this.#pn}px * var(--scale-factor))`;i.color=this.#tn;this.div.append(this.editorDiv);this.overlayDiv=document.createElement("div");this.overlayDiv.classList.add("overlay","enabled");this.div.append(this.overlayDiv);bindEvents(this,this.div,["dblclick","keydown"]);if(this.width){const[i,s]=this.parentDimensions;if(this.annotationElementId){const{position:n}=this._initialData;let[a,r]=this.getInitialTranslation();[a,r]=this.pageTranslationToScreen(a,r);const[o,l]=this.pageDimensions,[h,d]=this.pageTranslation;let c,u;switch(this.rotation){case 0:c=t+(n[0]-h)/o;u=e+this.height-(n[1]-d)/l;break;case 90:c=t+(n[0]-h)/o;u=e-(n[1]-d)/l;[a,r]=[r,-a];break;case 180:c=t-this.width+(n[0]-h)/o;u=e-(n[1]-d)/l;[a,r]=[-a,-r];break;case 270:c=t+(n[0]-h-this.height*l)/o;u=e+(n[1]-d-this.width*o)/l;[a,r]=[-r,a]}this.setAt(c*i,u*s,a,r)}else this.setAt(t*i,e*s,this.width*i,this.height*s);this.#zn();this._isDraggable=!0;this.editorDiv.contentEditable=!1}else{this._isDraggable=!1;this.editorDiv.contentEditable=!0}return this.div}static#Hn(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(zt,"")}editorDivPaste(t){const e=t.clipboardData||window.clipboardData,{types:i}=e;if(1===i.length&&"text/plain"===i[0])return;t.preventDefault();const s=FreeTextEditor.#Un(e.getData("text")||"").replaceAll(zt,"\n");if(!s)return;const n=window.getSelection();if(!n.rangeCount)return;this.editorDiv.normalize();n.deleteFromDocument();const a=n.getRangeAt(0);if(!s.includes("\n")){a.insertNode(document.createTextNode(s));this.editorDiv.normalize();n.collapseToStart();return}const{startContainer:r,startOffset:o}=a,l=[],h=[];if(r.nodeType===Node.TEXT_NODE){const t=r.parentElement;h.push(r.nodeValue.slice(o).replaceAll(zt,""));if(t!==this.editorDiv){let e=l;for(const i of this.editorDiv.childNodes)i!==t?e.push(FreeTextEditor.#Hn(i)):e=h}l.push(r.nodeValue.slice(0,o).replaceAll(zt,""))}else if(r===this.editorDiv){let t=l,e=0;for(const i of this.editorDiv.childNodes){e++===o&&(t=h);t.push(FreeTextEditor.#Hn(i))}}this.#Rn=`${l.join("\n")}${s}${h.join("\n")}`;this.#zn();const d=new Range;let c=l.reduce(((t,e)=>t+e.length),0);for(const{firstChild:t}of this.editorDiv.childNodes)if(t.nodeType===Node.TEXT_NODE){const e=t.nodeValue.length;if(c<=e){d.setStart(t,c);d.setEnd(t,c);break}c-=e}n.removeAllRanges();n.addRange(d)}#zn(){this.editorDiv.replaceChildren();if(this.#Rn)for(const t of this.#Rn.split("\n")){const e=document.createElement("div");e.append(t?document.createTextNode(t):document.createElement("br"));this.editorDiv.append(e)}}#Gn(){return this.#Rn.replaceAll(" "," ")}static#Un(t){return t.replaceAll(" "," ")}get contentDiv(){return this.editorDiv}static async deserialize(t,e,i){let s=null;if(t instanceof FreeTextAnnotationElement){const{data:{defaultAppearanceData:{fontSize:e,fontColor:i},rect:n,rotation:a,id:r,popupRef:o},textContent:l,textPosition:h,parent:{page:{pageNumber:d}}}=t;if(!l||0===l.length)return null;s=t={annotationType:g.FREETEXT,color:Array.from(i),fontSize:e,value:l.join("\n"),position:h,pageIndex:d-1,rect:n.slice(0),rotation:a,id:r,deleted:!1,popupRef:o}}const n=await super.deserialize(t,e,i);n.#pn=t.fontSize;n.#tn=Util.makeHexColor(...t.color);n.#Rn=FreeTextEditor.#Un(t.value);n.annotationElementId=t.id||null;n._initialData=s;return n}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const e=FreeTextEditor._internalPadding*this.parentScale,i=this.getRect(e,e),s=AnnotationEditor._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.#tn),n={annotationType:g.FREETEXT,color:s,fontSize:this.#pn,value:this.#Gn(),pageIndex:this.pageIndex,rect:i,rotation:this.rotation,structTreeParentId:this._structTreeParentId};if(t)return n;if(this.annotationElementId&&!this.#$n(n))return null;n.id=this.annotationElementId;return n}#$n(t){const{value:e,fontSize:i,color:s,pageIndex:n}=this._initialData;return this._hasBeenMoved||t.value!==e||t.fontSize!==i||t.color.some(((t,e)=>t!==s[e]))||t.pageIndex!==n}renderAnnotationElement(t){const e=super.renderAnnotationElement(t);if(this.deleted)return e;const{style:i}=e;i.fontSize=`calc(${this.#pn}px * var(--scale-factor))`;i.color=this.#tn;e.replaceChildren();for(const t of this.#Rn.split("\n")){const i=document.createElement("div");i.append(t?document.createTextNode(t):document.createElement("br"));e.append(i)}const s=FreeTextEditor._internalPadding*this.parentScale;t.updateEdited({rect:this.getRect(s,s),popupContent:this.#Rn});return e}resetAnnotationElement(t){super.resetAnnotationElement(t);t.resetEdited()}}class Outline{static PRECISION=1e-4;toSVGPath(){unreachable("Abstract method `toSVGPath` must be implemented.")}get box(){unreachable("Abstract getter `box` must be implemented.")}serialize(t,e){unreachable("Abstract method `serialize` must be implemented.")}static _rescale(t,e,i,s,n,a){a||=new Float32Array(t.length);for(let r=0,o=t.length;r=6;t-=6)isNaN(e[t])?i.push(`L${e[t+4]} ${e[t+5]}`):i.push(`C${e[t]} ${e[t+1]} ${e[t+2]} ${e[t+3]} ${e[t+4]} ${e[t+5]}`);this.#ha(i);return i.join(" ")}#oa(){const[t,e,i,s]=this.#Vn,[n,a,r,o]=this.#ra();return`M${(this.#Kn[2]-t)/i} ${(this.#Kn[3]-e)/s} L${(this.#Kn[4]-t)/i} ${(this.#Kn[5]-e)/s} L${n} ${a} L${r} ${o} L${(this.#Kn[16]-t)/i} ${(this.#Kn[17]-e)/s} L${(this.#Kn[14]-t)/i} ${(this.#Kn[15]-e)/s} Z`}#ha(t){const e=this.#jn;t.push(`L${e[4]} ${e[5]} Z`)}#la(t){const[e,i,s,n]=this.#Vn,a=this.#Kn.subarray(4,6),r=this.#Kn.subarray(16,18),[o,l,h,d]=this.#ra();t.push(`L${(a[0]-e)/s} ${(a[1]-i)/n} L${o} ${l} L${h} ${d} L${(r[0]-e)/s} ${(r[1]-i)/n}`)}newFreeDrawOutline(t,e,i,s,n,a){return new FreeDrawOutline(t,e,i,s,n,a)}getOutlines(){const t=this.#Xn,e=this.#jn,i=this.#Kn,[s,n,a,r]=this.#Vn,o=new Float32Array((this.#ia?.length??0)+2);for(let t=0,e=o.length-2;t=6;t-=6)for(let i=0;i<6;i+=2)if(isNaN(e[t+i])){l[h]=l[h+1]=NaN;h+=2}else{l[h]=e[t+i];l[h+1]=e[t+i+1];h+=2}this.#ua(l,h);return this.newFreeDrawOutline(l,o,this.#Vn,this.#ta,this.#Wn,this.#qn)}#da(t){const e=this.#Kn,[i,s,n,a]=this.#Vn,[r,o,l,h]=this.#ra(),d=new Float32Array(36);d.set([NaN,NaN,NaN,NaN,(e[2]-i)/n,(e[3]-s)/a,NaN,NaN,NaN,NaN,(e[4]-i)/n,(e[5]-s)/a,NaN,NaN,NaN,NaN,r,o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,(e[16]-i)/n,(e[17]-s)/a,NaN,NaN,NaN,NaN,(e[14]-i)/n,(e[15]-s)/a],0);return this.newFreeDrawOutline(d,t,this.#Vn,this.#ta,this.#Wn,this.#qn)}#ua(t,e){const i=this.#jn;t.set([NaN,NaN,NaN,NaN,i[4],i[5]],e);return e+6}#ca(t,e){const i=this.#Kn.subarray(4,6),s=this.#Kn.subarray(16,18),[n,a,r,o]=this.#Vn,[l,h,d,c]=this.#ra();t.set([NaN,NaN,NaN,NaN,(i[0]-n)/r,(i[1]-a)/o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,d,c,NaN,NaN,NaN,NaN,(s[0]-n)/r,(s[1]-a)/o],e);return e+24}}class FreeDrawOutline extends Outline{#Vn;#pa=new Float32Array(4);#Wn;#qn;#ia;#ta;#ga;constructor(t,e,i,s,n,a){super();this.#ga=t;this.#ia=e;this.#Vn=i;this.#ta=s;this.#Wn=n;this.#qn=a;this.lastPoint=[NaN,NaN];this.#ma(a);const[r,o,l,h]=this.#pa;for(let e=0,i=t.length;et[0]-e[0]||t[1]-e[1]||t[2]-e[2]));const t=[];for(const e of this.#ba)if(e[3]){t.push(...this.#wa(e));this.#va(e)}else{this.#ya(e);t.push(...this.#wa(e))}return this.#xa(t)}#xa(t){const e=[],i=new Set;for(const i of t){const[t,s,n]=i;e.push([t,s,i],[t,n,i])}e.sort(((t,e)=>t[1]-e[1]||t[0]-e[0]));for(let t=0,s=e.length;t0;){const t=i.values().next().value;let[e,a,r,o,l]=t;i.delete(t);let h=e,d=a;n=[e,r];s.push(n);for(;;){let t;if(i.has(o))t=o;else{if(!i.has(l))break;t=l}i.delete(t);[e,a,r,o,l]=t;if(h!==e){n.push(h,d,e,d===a?a:r);h=e}d=d===a?r:a}n.push(h,d)}return new HighlightOutline(s,this.#Vn,this.#fa)}#_a(t){const e=this.#Aa;let i=0,s=e.length-1;for(;i<=s;){const n=i+s>>1,a=e[n][0];if(a===t)return n;a=0;s--){const[i,n]=this.#Aa[s];if(i!==t)break;if(i===t&&n===e){this.#Aa.splice(s,1);return}}}#wa(t){const[e,i,s]=t,n=[[e,i,s]],a=this.#_a(s);for(let t=0;t=i)if(o>s)n[t][1]=s;else{if(1===a)return[];n.splice(t,1);t--;a--}else{n[t][2]=i;o>s&&n.push([e,s,o])}}}return n}}class HighlightOutline extends Outline{#Vn;#Ea;constructor(t,e,i){super();this.#Ea=t;this.#Vn=e;this.lastPoint=i}toSVGPath(){const t=[];for(const e of this.#Ea){let[i,s]=e;t.push(`M${i} ${s}`);for(let n=2;n-1){this.#Xa=!0;this.#Za(t);this.#tr()}else if(this.#Ua){this.#Ha=t.anchorNode;this.#za=t.anchorOffset;this.#Va=t.focusNode;this.#ja=t.focusOffset;this.#er();this.#tr();this.rotate(this.rotation)}}get telemetryInitialData(){return{action:"added",type:this.#Xa?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:this.#ea,methodOfCreation:this.#Ja}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#er(){const t=new HighlightOutliner(this.#Ua,.001);this.#qa=t.getOutlines();[this.x,this.y,this.width,this.height]=this.#qa.box;const e=new HighlightOutliner(this.#Ua,.0025,.001,"ltr"===this._uiManager.direction);this.#$a=e.getOutlines();const{lastPoint:i}=this.#$a;this.#fa=[(i[0]-this.x)/this.width,(i[1]-this.y)/this.height]}#Za({highlightOutlines:t,highlightId:e,clipPathId:i}){this.#qa=t;this.#$a=t.getNewOutline(this.#ea/2+1.5,.0025);if(e>=0){this.#w=e;this.#Ga=i;this.parent.drawLayer.finalizeDraw(e,{bbox:t.box,path:{d:t.toSVGPath()}});this.#Ya=this.parent.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:!0},bbox:this.#$a.box,path:{d:this.#$a.toSVGPath()}},!0)}else if(this.parent){const e=this.parent.viewport.rotation;this.parent.drawLayer.updateProperties(this.#w,{bbox:HighlightEditor.#ir(this.#qa.box,(e-this.rotation+360)%360),path:{d:t.toSVGPath()}});this.parent.drawLayer.updateProperties(this.#Ya,{bbox:HighlightEditor.#ir(this.#$a.box,e),path:{d:this.#$a.toSVGPath()}})}const[s,n,a,r]=t.box;switch(this.rotation){case 0:this.x=s;this.y=n;this.width=a;this.height=r;break;case 90:{const[t,e]=this.parentDimensions;this.x=n;this.y=1-s;this.width=a*e/t;this.height=r*t/e;break}case 180:this.x=1-s;this.y=1-n;this.width=a;this.height=r;break;case 270:{const[t,e]=this.parentDimensions;this.x=1-n;this.y=s;this.width=a*e/t;this.height=r*t/e;break}}const{lastPoint:o}=this.#$a;this.#fa=[(o[0]-s)/a,(o[1]-n)/r]}static initialize(t,e){AnnotationEditor.initialize(t,e);HighlightEditor._defaultColor||=e.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,e){switch(t){case m.HIGHLIGHT_DEFAULT_COLOR:HighlightEditor._defaultColor=e;break;case m.HIGHLIGHT_THICKNESS:HighlightEditor._defaultThickness=e}}translateInPage(t,e){}get toolbarPosition(){return this.#fa}updateParams(t,e){switch(t){case m.HIGHLIGHT_COLOR:this.#On(e);break;case m.HIGHLIGHT_THICKNESS:this.#sr(e)}}static get defaultPropertiesToUpdate(){return[[m.HIGHLIGHT_DEFAULT_COLOR,HighlightEditor._defaultColor],[m.HIGHLIGHT_THICKNESS,HighlightEditor._defaultThickness]]}get propertiesToUpdate(){return[[m.HIGHLIGHT_COLOR,this.color||HighlightEditor._defaultColor],[m.HIGHLIGHT_THICKNESS,this.#ea||HighlightEditor._defaultThickness],[m.HIGHLIGHT_FREE,this.#Xa]]}#On(t){const setColorAndOpacity=(t,e)=>{this.color=t;this.#Ka=e;this.parent?.drawLayer.updateProperties(this.#w,{root:{fill:t,"fill-opacity":e}});this.#n?.updateColor(t)},e=this.color,i=this.#Ka;this.addCommands({cmd:setColorAndOpacity.bind(this,t,HighlightEditor._defaultOpacity),undo:setColorAndOpacity.bind(this,e,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:m.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0});this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(t)},!0)}#sr(t){const e=this.#ea,setThickness=t=>{this.#ea=t;this.#nr(t)};this.addCommands({cmd:setThickness.bind(this,t),undo:setThickness.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:m.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0});this._reportTelemetry({action:"thickness_changed",thickness:t},!0)}async addEditToolbar(){const t=await super.addEditToolbar();if(!t)return null;if(this._uiManager.highlightColors){this.#n=new ColorPicker({editor:this});t.addColorPicker(this.#n)}return t}disableEditing(){super.disableEditing();this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing();this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#ar())}getBaseTranslation(){return[0,0]}getRect(t,e){return super.getRect(t,e,this.#ar())}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this);t&&this.div.focus()}remove(){this.#rr();this._reportTelemetry({action:"deleted"});super.remove()}rebuild(){if(this.parent){super.rebuild();if(null!==this.div){this.#tr();this.isAttachedToDOM||this.parent.add(this)}}}setParent(t){let e=!1;if(this.parent&&!t)this.#rr();else if(t){this.#tr(t);e=!this.parent&&this.div?.classList.contains("selectedEditor")}super.setParent(t);this.show(this._isVisible);e&&this.select()}#nr(t){if(!this.#Xa)return;this.#Za({highlightOutlines:this.#qa.getNewOutline(t/2)});this.fixAndSetPosition();const[e,i]=this.parentDimensions;this.setDims(this.width*e,this.height*i)}#rr(){if(null!==this.#w&&this.parent){this.parent.drawLayer.remove(this.#w);this.#w=null;this.parent.drawLayer.remove(this.#Ya);this.#Ya=null}}#tr(t=this.parent){if(null===this.#w){({id:this.#w,clipPathId:this.#Ga}=t.drawLayer.draw({bbox:this.#qa.box,root:{viewBox:"0 0 1 1",fill:this.color,"fill-opacity":this.#Ka},rootClass:{highlight:!0,free:this.#Xa},path:{d:this.#qa.toSVGPath()}},!1,!0));this.#Ya=t.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:this.#Xa},bbox:this.#$a.box,path:{d:this.#$a.toSVGPath()}},this.#Xa);this.#Wa&&(this.#Wa.style.clipPath=this.#Ga)}}static#ir([t,e,i,s],n){switch(n){case 90:return[1-e-s,t,s,i];case 180:return[1-t-i,1-e-s,i,s];case 270:return[e,1-t-i,s,i]}return[t,e,i,s]}rotate(t){const{drawLayer:e}=this.parent;let i;if(this.#Xa){t=(t-this.rotation+360)%360;i=HighlightEditor.#ir(this.#qa.box,t)}else i=HighlightEditor.#ir([this.x,this.y,this.width,this.height],t);e.updateProperties(this.#w,{bbox:i,root:{"data-main-rotation":t}});e.updateProperties(this.#Ya,{bbox:HighlightEditor.#ir(this.#$a.box,t),root:{"data-main-rotation":t}})}render(){if(this.div)return this.div;const t=super.render();if(this.#Qa){t.setAttribute("aria-label",this.#Qa);t.setAttribute("role","mark")}this.#Xa?t.classList.add("free"):this.div.addEventListener("keydown",this.#or.bind(this),{signal:this._uiManager._signal});const e=this.#Wa=document.createElement("div");t.append(e);e.setAttribute("aria-hidden","true");e.className="internal";e.style.clipPath=this.#Ga;const[i,s]=this.parentDimensions;this.setDims(this.width*i,this.height*s);bindEvents(this,this.#Wa,["pointerover","pointerleave"]);this.enableEditing();return t}pointerover(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#Ya,{rootClass:{hovered:!0}})}pointerleave(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#Ya,{rootClass:{hovered:!1}})}#or(t){HighlightEditor._keyboardManager.exec(this,t)}_moveCaret(t){this.parent.unselect(this);switch(t){case 0:case 2:this.#lr(!0);break;case 1:case 3:this.#lr(!1)}}#lr(t){if(!this.#Ha)return;const e=window.getSelection();t?e.setPosition(this.#Ha,this.#za):e.setPosition(this.#Va,this.#ja)}select(){super.select();this.#Ya&&this.parent?.drawLayer.updateProperties(this.#Ya,{rootClass:{hovered:!1,selected:!0}})}unselect(){super.unselect();if(this.#Ya){this.parent?.drawLayer.updateProperties(this.#Ya,{rootClass:{selected:!1}});this.#Xa||this.#lr(!1)}}get _mustFixPosition(){return!this.#Xa}show(t=this._isVisible){super.show(t);if(this.parent){this.parent.drawLayer.updateProperties(this.#w,{rootClass:{hidden:!t}});this.parent.drawLayer.updateProperties(this.#Ya,{rootClass:{hidden:!t}})}}#ar(){return this.#Xa?this.rotation:0}#hr(){if(this.#Xa)return null;const[t,e]=this.pageDimensions,[i,s]=this.pageTranslation,n=this.#Ua,a=new Float32Array(8*n.length);let r=0;for(const{x:o,y:l,width:h,height:d}of n){const n=o*t+i,c=(1-l)*e+s;a[r]=a[r+4]=n;a[r+1]=a[r+3]=c;a[r+2]=a[r+6]=n+h*t;a[r+5]=a[r+7]=c-d*e;r+=8}return a}#dr(t){return this.#qa.serialize(t,this.#ar())}static startHighlighting(t,e,{target:i,x:s,y:n}){const{x:a,y:r,width:o,height:l}=i.getBoundingClientRect(),h=new AbortController,d=t.combinedSignal(h),pointerUpCallback=e=>{h.abort();this.#cr(t,e)};window.addEventListener("blur",pointerUpCallback,{signal:d});window.addEventListener("pointerup",pointerUpCallback,{signal:d});window.addEventListener("pointerdown",stopEvent,{capture:!0,passive:!1,signal:d});window.addEventListener("contextmenu",noContextMenu,{signal:d});i.addEventListener("pointermove",this.#ur.bind(this,t),{signal:d});this._freeHighlight=new FreeHighlightOutliner({x:s,y:n},[a,r,o,l],t.scale,this._defaultThickness/2,e,.001);({id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=t.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:this._defaultColor,"fill-opacity":this._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:this._freeHighlight.toSVGPath()}},!0,!0))}static#ur(t,e){this._freeHighlight.add(e)&&t.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})}static#cr(t,e){this._freeHighlight.isEmpty()?t.drawLayer.remove(this._freeHighlightId):t.createAndAddNewEditor(e,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"});this._freeHighlightId=-1;this._freeHighlight=null;this._freeHighlightClipId=""}static async deserialize(t,e,i){let s=null;if(t instanceof HighlightAnnotationElement){const{data:{quadPoints:e,rect:i,rotation:n,id:a,color:r,opacity:o,popupRef:l},parent:{page:{pageNumber:h}}}=t;s=t={annotationType:g.HIGHLIGHT,color:Array.from(r),opacity:o,quadPoints:e,boxes:null,pageIndex:h-1,rect:i.slice(0),rotation:n,id:a,deleted:!1,popupRef:l}}else if(t instanceof InkAnnotationElement){const{data:{inkLists:e,rect:i,rotation:n,id:a,color:r,borderStyle:{rawWidth:o},popupRef:l},parent:{page:{pageNumber:h}}}=t;s=t={annotationType:g.HIGHLIGHT,color:Array.from(r),thickness:o,inkLists:e,boxes:null,pageIndex:h-1,rect:i.slice(0),rotation:n,id:a,deleted:!1,popupRef:l}}const{color:n,quadPoints:a,inkLists:r,opacity:o}=t,l=await super.deserialize(t,e,i);l.color=Util.makeHexColor(...n);l.#Ka=o||1;r&&(l.#ea=t.thickness);l.annotationElementId=t.id||null;l._initialData=s;const[h,d]=l.pageDimensions,[c,u]=l.pageTranslation;if(a){const t=l.#Ua=[];for(let e=0;et!==e[i]))}renderAnnotationElement(t){t.updateEdited({rect:this.getRect(0,0)});return null}static canCreateNewEmptyEditor(){return!1}}class DrawingOptions{#pr=Object.create(null);updateProperty(t,e){this[t]=e;this.updateSVGProperty(t,e)}updateProperties(t){if(t)for(const[e,i]of Object.entries(t))this.updateProperty(e,i)}updateSVGProperty(t,e){this.#pr[t]=e}toSVGProperties(){const t=this.#pr;this.#pr=Object.create(null);return{root:t}}reset(){this.#pr=Object.create(null)}updateAll(t=this){this.updateProperties(t)}clone(){unreachable("Not implemented")}}class DrawingEditor extends AnnotationEditor{#gr=null;#mr;_drawId=null;static _currentDrawId=-1;static _currentParent=null;static#fr=null;static#br=null;static#Ar=null;static#wr=NaN;static#vr=null;static#yr=null;static#xr=NaN;static _INNER_MARGIN=3;constructor(t){super(t);this.#mr=t.mustBeCommitted||!1;if(t.drawOutlines){this.#_r(t);this.#tr()}}#_r({drawOutlines:t,drawId:e,drawingOptions:i}){this.#gr=t;this._drawingOptions||=i;if(e>=0){this._drawId=e;this.parent.drawLayer.finalizeDraw(e,t.defaultProperties)}else this._drawId=this.#Er(t,this.parent);this.#Sr(t.box)}#Er(t,e){const{id:i}=e.drawLayer.draw(DrawingEditor._mergeSVGProperties(this._drawingOptions.toSVGProperties(),t.defaultSVGProperties),!1,!1);return i}static _mergeSVGProperties(t,e){const i=new Set(Object.keys(t));for(const[s,n]of Object.entries(e))i.has(s)?Object.assign(t[s],n):t[s]=n;return t}static getDefaultDrawingOptions(t){unreachable("Not implemented")}static get typesMap(){unreachable("Not implemented")}static get isDrawer(){return!0}static get supportMultipleDrawings(){return!1}static updateDefaultParams(t,e){const i=this.typesMap.get(t);i&&this._defaultDrawingOptions.updateProperty(i,e);if(this._currentParent){DrawingEditor.#fr.updateProperty(i,e);this._currentParent.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties())}}updateParams(t,e){const i=this.constructor.typesMap.get(t);i&&this._updateProperty(t,i,e)}static get defaultPropertiesToUpdate(){const t=[],e=this._defaultDrawingOptions;for(const[i,s]of this.typesMap)t.push([i,e[s]]);return t}get propertiesToUpdate(){const t=[],{_drawingOptions:e}=this;for(const[i,s]of this.constructor.typesMap)t.push([i,e[s]]);return t}_updateProperty(t,e,i){const s=this._drawingOptions,n=s[e],setter=t=>{s.updateProperty(e,t);const i=this.#gr.updateProperty(e,t);i&&this.#Sr(i);this.parent?.drawLayer.updateProperties(this._drawId,s.toSVGProperties())};this.addCommands({cmd:setter.bind(this,i),undo:setter.bind(this,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:t,overwriteIfSameType:!0,keepUndo:!0})}_onResizing(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#gr.getPathResizingSVGProperties(this.#Cr()),{bbox:this.#Tr()}))}_onResized(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#gr.getPathResizedSVGProperties(this.#Cr()),{bbox:this.#Tr()}))}_onTranslating(t,e){this.parent?.drawLayer.updateProperties(this._drawId,{bbox:this.#Tr(t,e)})}_onTranslated(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#gr.getPathTranslatedSVGProperties(this.#Cr(),this.parentDimensions),{bbox:this.#Tr()}))}_onStartDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!0}})}_onStopDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!1}})}commit(){super.commit();this.disableEditMode();this.disableEditing()}disableEditing(){super.disableEditing();this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing();this.div.classList.toggle("disabled",!1)}getBaseTranslation(){return[0,0]}get isResizable(){return!0}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this);this._isDraggable=!0;if(this.#mr){this.#mr=!1;this.commit();this.parent.setSelected(this);t&&this.isOnScreen&&this.div.focus()}}remove(){this.#rr();super.remove()}rebuild(){if(this.parent){super.rebuild();if(null!==this.div){this.#tr();this.#Sr(this.#gr.box);this.isAttachedToDOM||this.parent.add(this)}}}setParent(t){let e=!1;if(this.parent&&!t){this._uiManager.removeShouldRescale(this);this.#rr()}else if(t){this._uiManager.addShouldRescale(this);this.#tr(t);e=!this.parent&&this.div?.classList.contains("selectedEditor")}super.setParent(t);e&&this.select()}#rr(){if(null!==this._drawId&&this.parent){this.parent.drawLayer.remove(this._drawId);this._drawId=null;this._drawingOptions.reset()}}#tr(t=this.parent){if(null===this._drawId||this.parent!==t)if(null===this._drawId){this._drawingOptions.updateAll();this._drawId=this.#Er(this.#gr,t)}else this.parent.drawLayer.updateParent(this._drawId,t.drawLayer)}#Mr([t,e,i,s]){const{parentDimensions:[n,a],rotation:r}=this;switch(r){case 90:return[e,1-t,i*(a/n),s*(n/a)];case 180:return[1-t,1-e,i,s];case 270:return[1-e,t,i*(a/n),s*(n/a)];default:return[t,e,i,s]}}#Cr(){const{x:t,y:e,width:i,height:s,parentDimensions:[n,a],rotation:r}=this;switch(r){case 90:return[1-e,t,i*(n/a),s*(a/n)];case 180:return[1-t,1-e,i,s];case 270:return[e,1-t,i*(n/a),s*(a/n)];default:return[t,e,i,s]}}#Sr(t){[this.x,this.y,this.width,this.height]=this.#Mr(t);if(this.div){this.fixAndSetPosition();const[t,e]=this.parentDimensions;this.setDims(this.width*t,this.height*e)}this._onResized()}#Tr(){const{x:t,y:e,width:i,height:s,rotation:n,parentRotation:a,parentDimensions:[r,o]}=this;switch((4*n+a)/90){case 1:return[1-e-s,t,s,i];case 2:return[1-t-i,1-e-s,i,s];case 3:return[e,1-t-i,s,i];case 4:return[t,e-i*(r/o),s*(o/r),i*(r/o)];case 5:return[1-e,t,i*(r/o),s*(o/r)];case 6:return[1-t-s*(o/r),1-e,s*(o/r),i*(r/o)];case 7:return[e-i*(r/o),1-t-s*(o/r),i*(r/o),s*(o/r)];case 8:return[t-i,e-s,i,s];case 9:return[1-e,t-i,s,i];case 10:return[1-t,1-e,i,s];case 11:return[e-s,1-t,s,i];case 12:return[t-s*(o/r),e,s*(o/r),i*(r/o)];case 13:return[1-e-i*(r/o),t-s*(o/r),i*(r/o),s*(o/r)];case 14:return[1-t,1-e-i*(r/o),s*(o/r),i*(r/o)];case 15:return[e,1-t,i*(r/o),s*(o/r)];default:return[t,e,i,s]}}rotate(){this.parent&&this.parent.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties({bbox:this.#Tr()},this.#gr.updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&this.#Sr(this.#gr.updateParentDimensions(this.parentDimensions,this.parent.scale))}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;const t=super.render();t.classList.add("draw");const e=document.createElement("div");t.append(e);e.setAttribute("aria-hidden","true");e.className="internal";const[i,s]=this.parentDimensions;this.setDims(this.width*i,this.height*s);this._uiManager.addShouldRescale(this);this.disableEditing();return t}static createDrawerInstance(t,e,i,s,n){unreachable("Not implemented")}static startDrawing(t,e,i,s){const{target:n,offsetX:a,offsetY:r,pointerId:o,pointerType:l}=s;if(DrawingEditor.#vr&&DrawingEditor.#vr!==l)return;const{viewport:{rotation:h}}=t,{width:d,height:c}=n.getBoundingClientRect(),u=DrawingEditor.#br=new AbortController,p=t.combinedSignal(u);DrawingEditor.#wr||=o;DrawingEditor.#vr??=l;window.addEventListener("pointerup",(t=>{DrawingEditor.#wr===t.pointerId?this._endDraw(t):DrawingEditor.#yr?.delete(t.pointerId)}),{signal:p});window.addEventListener("pointercancel",(t=>{DrawingEditor.#wr===t.pointerId?this._currentParent.endDrawingSession():DrawingEditor.#yr?.delete(t.pointerId)}),{signal:p});window.addEventListener("pointerdown",(t=>{if(DrawingEditor.#vr===t.pointerType){(DrawingEditor.#yr||=new Set).add(t.pointerId);if(DrawingEditor.#fr.isCancellable()){DrawingEditor.#fr.removeLastElement();DrawingEditor.#fr.isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)}}}),{capture:!0,passive:!1,signal:p});window.addEventListener("contextmenu",noContextMenu,{signal:p});n.addEventListener("pointermove",this._drawMove.bind(this),{signal:p});n.addEventListener("touchmove",(t=>{t.timeStamp===DrawingEditor.#xr&&stopEvent(t)}),{signal:p});t.toggleDrawing();e._editorUndoBar?.hide();if(DrawingEditor.#fr)t.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#fr.startNew(a,r,d,c,h));else{e.updateUIForDefaultProperties(this);DrawingEditor.#fr=this.createDrawerInstance(a,r,d,c,h);DrawingEditor.#Ar=this.getDefaultDrawingOptions();this._currentParent=t;({id:this._currentDrawId}=t.drawLayer.draw(this._mergeSVGProperties(DrawingEditor.#Ar.toSVGProperties(),DrawingEditor.#fr.defaultSVGProperties),!0,!1))}}static _drawMove(t){DrawingEditor.#xr=-1;if(!DrawingEditor.#fr)return;const{offsetX:e,offsetY:i,pointerId:s}=t;if(DrawingEditor.#wr===s)if(DrawingEditor.#yr?.size>=1)this._endDraw(t);else{this._currentParent.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#fr.add(e,i));DrawingEditor.#xr=t.timeStamp;stopEvent(t)}}static _cleanup(t){if(t){this._currentDrawId=-1;this._currentParent=null;DrawingEditor.#fr=null;DrawingEditor.#Ar=null;DrawingEditor.#vr=null;DrawingEditor.#xr=NaN}if(DrawingEditor.#br){DrawingEditor.#br.abort();DrawingEditor.#br=null;DrawingEditor.#wr=NaN;DrawingEditor.#yr=null}}static _endDraw(t){const e=this._currentParent;if(e){e.toggleDrawing(!0);this._cleanup(!1);t&&e.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#fr.end(t.offsetX,t.offsetY));if(this.supportMultipleDrawings){const t=DrawingEditor.#fr,i=this._currentDrawId,s=t.getLastElement();e.addCommands({cmd:()=>{e.drawLayer.updateProperties(i,t.setLastElement(s))},undo:()=>{e.drawLayer.updateProperties(i,t.removeLastElement())},mustExec:!1,type:m.DRAW_STEP})}else this.endDrawing(!1)}}static endDrawing(t){const e=this._currentParent;if(!e)return null;e.toggleDrawing(!0);e.cleanUndoStack(m.DRAW_STEP);if(!DrawingEditor.#fr.isEmpty()){const{pageDimensions:[i,s],scale:n}=e,a=e.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:DrawingEditor.#fr.getOutlines(i*n,s*n,n,this._INNER_MARGIN),drawingOptions:DrawingEditor.#Ar,mustBeCommitted:!t});this._cleanup(!0);return a}e.drawLayer.remove(this._currentDrawId);this._cleanup(!0);return null}createDrawingOptions(t){}static deserializeDraw(t,e,i,s,n,a){unreachable("Not implemented")}static async deserialize(t,e,i){const{rawDims:{pageWidth:s,pageHeight:n,pageX:a,pageY:r}}=e.viewport,o=this.deserializeDraw(a,r,s,n,this._INNER_MARGIN,t),l=await super.deserialize(t,e,i);l.createDrawingOptions(t);l.#_r({drawOutlines:o});l.#tr();l.onScaleChanging();l.rotate();return l}serializeDraw(t){const[e,i]=this.pageTranslation,[s,n]=this.pageDimensions;return this.#gr.serialize([e,i,s,n],t)}renderAnnotationElement(t){t.updateEdited({rect:this.getRect(0,0)});return null}static canCreateNewEmptyEditor(){return!1}}class InkDrawOutliner{#Kn=new Float64Array(6);#bn;#Pr;#Fi;#ea;#ia;#Dr="";#kr=0;#Ea=new InkDrawOutline;#Rr;#Ir;constructor(t,e,i,s,n,a){this.#Rr=i;this.#Ir=s;this.#Fi=n;this.#ea=a;[t,e]=this.#Fr(t,e);const r=this.#bn=[NaN,NaN,NaN,NaN,t,e];this.#ia=[t,e];this.#Pr=[{line:r,points:this.#ia}];this.#Kn.set(r,0)}updateProperty(t,e){"stroke-width"===t&&(this.#ea=e)}#Fr(t,e){return Outline._normalizePoint(t,e,this.#Rr,this.#Ir,this.#Fi)}isEmpty(){return!this.#Pr||0===this.#Pr.length}isCancellable(){return this.#ia.length<=10}add(t,e){[t,e]=this.#Fr(t,e);const[i,s,n,a]=this.#Kn.subarray(2,6),r=t-n,o=e-a;if(Math.hypot(this.#Rr*r,this.#Ir*o)<=2)return null;this.#ia.push(t,e);if(isNaN(i)){this.#Kn.set([n,a,t,e],2);this.#bn.push(NaN,NaN,NaN,NaN,t,e);return{path:{d:this.toSVGPath()}}}isNaN(this.#Kn[0])&&this.#bn.splice(6,6);this.#Kn.set([i,s,n,a,t,e],0);this.#bn.push(...Outline.createBezierPoints(i,s,n,a,t,e));return{path:{d:this.toSVGPath()}}}end(t,e){const i=this.add(t,e);return i||(2===this.#ia.length?{path:{d:this.toSVGPath()}}:null)}startNew(t,e,i,s,n){this.#Rr=i;this.#Ir=s;this.#Fi=n;[t,e]=this.#Fr(t,e);const a=this.#bn=[NaN,NaN,NaN,NaN,t,e];this.#ia=[t,e];const r=this.#Pr.at(-1);if(r){r.line=new Float32Array(r.line);r.points=new Float32Array(r.points)}this.#Pr.push({line:a,points:this.#ia});this.#Kn.set(a,0);this.#kr=0;this.toSVGPath();return null}getLastElement(){return this.#Pr.at(-1)}setLastElement(t){if(!this.#Pr)return this.#Ea.setLastElement(t);this.#Pr.push(t);this.#bn=t.line;this.#ia=t.points;this.#kr=0;return{path:{d:this.toSVGPath()}}}removeLastElement(){if(!this.#Pr)return this.#Ea.removeLastElement();this.#Pr.pop();this.#Dr="";for(let t=0,e=this.#Pr.length;tt??NaN)),d,c,u,p),points:g(r[t].map((t=>t??NaN)),d,c,u,p)});const m=new InkDrawOutline;m.build(h,i,s,1,o,l,n);return m}#Hr(t=this.#ea){const e=this.#Wn+t/2*this.#Or;return this.#Fi%180==0?[e/this.#Rr,e/this.#Ir]:[e/this.#Ir,e/this.#Rr]}#Br(){const[t,e,i,s]=this.#pa,[n,a]=this.#Hr(0);return[t+n,e+a,i-2*n,s-2*a]}#Nr(){const t=this.#pa=new Float32Array([1/0,1/0,-1/0,-1/0]);for(const{line:e}of this.#Pr){if(e.length<=12){for(let i=4,s=e.length;it!==e[i]))||t.thickness!==i||t.opacity!==s||t.pageIndex!==n}renderAnnotationElement(t){const{points:e,rect:i}=this.serializeDraw(!1);t.updateEdited({rect:i,thickness:this._drawingOptions["stroke-width"],points:e});return null}}class StampEditor extends AnnotationEditor{#Ur=null;#Gr=null;#$r=null;#Vr=null;#jr=null;#Wr="";#qr=null;#Xr=null;#Kr=!1;#Yr=!1;static _type="stamp";static _editorType=g.STAMP;constructor(t){super({...t,name:"stampEditor"});this.#Vr=t.bitmapUrl;this.#jr=t.bitmapFile}static initialize(t,e){AnnotationEditor.initialize(t,e)}static get supportedTypes(){return shadow(this,"supportedTypes",["apng","avif","bmp","gif","jpeg","png","svg+xml","webp","x-icon"].map((t=>`image/${t}`)))}static get supportedTypesStr(){return shadow(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(t){return this.supportedTypes.includes(t)}static paste(t,e){e.pasteEditor(g.STAMP,{bitmapFile:t.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1);super.altTextFinish()}get telemetryFinalData(){return{type:"stamp",hasAltText:!!this.altTextData?.altText}}static computeTelemetryFinalData(t){const e=t.get("hasAltText");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}#Qr(t,e=!1){if(t){this.#Ur=t.bitmap;if(!e){this.#Gr=t.id;this.#Kr=t.isSvg}t.file&&(this.#Wr=t.file.name);this.#Jr()}else this.remove()}#Zr(){this.#$r=null;this._uiManager.enableWaiting(!1);if(this.#qr)if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#Ur){this._editToolbar.hide();this._uiManager.editAltText(this,!0)}else{if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#Ur){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}}async mlGuessAltText(t=null,e=!0){if(this.hasAltTextData())return null;const{mlManager:i}=this._uiManager;if(!i)throw new Error("No ML.");if(!await i.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:s,width:n,height:a}=t||this.copyCanvas(null,null,!0).imageData,r=await i.guess({name:"altText",request:{data:s,width:n,height:a,channels:s.length/(n*a)}});if(!r)throw new Error("No response from the AI service.");if(r.error)throw new Error("Error from the AI service.");if(r.cancel)return null;if(!r.output)throw new Error("No valid response from the AI service.");const o=r.output;await this.setGuessedAltText(o);e&&!this.hasAltTextData()&&(this.altTextData={alt:o,decorative:!1});return o}#to(){if(this.#Gr){this._uiManager.enableWaiting(!0);this._uiManager.imageManager.getFromId(this.#Gr).then((t=>this.#Qr(t,!0))).finally((()=>this.#Zr()));return}if(this.#Vr){const t=this.#Vr;this.#Vr=null;this._uiManager.enableWaiting(!0);this.#$r=this._uiManager.imageManager.getFromUrl(t).then((t=>this.#Qr(t))).finally((()=>this.#Zr()));return}if(this.#jr){const t=this.#jr;this.#jr=null;this._uiManager.enableWaiting(!0);this.#$r=this._uiManager.imageManager.getFromFile(t).then((t=>this.#Qr(t))).finally((()=>this.#Zr()));return}const t=document.createElement("input");t.type="file";t.accept=StampEditor.supportedTypesStr;const e=this._uiManager._signal;this.#$r=new Promise((i=>{t.addEventListener("change",(async()=>{if(t.files&&0!==t.files.length){this._uiManager.enableWaiting(!0);const e=await this._uiManager.imageManager.getFromFile(t.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}});this.#Qr(e)}else this.remove();i()}),{signal:e});t.addEventListener("cancel",(()=>{this.remove();i()}),{signal:e})})).finally((()=>this.#Zr()));t.click()}remove(){if(this.#Gr){this.#Ur=null;this._uiManager.imageManager.deleteId(this.#Gr);this.#qr?.remove();this.#qr=null;if(this.#Xr){clearTimeout(this.#Xr);this.#Xr=null}}super.remove()}rebuild(){if(this.parent){super.rebuild();if(null!==this.div){this.#Gr&&null===this.#qr&&this.#to();this.isAttachedToDOM||this.parent.add(this)}}else this.#Gr&&this.#to()}onceAdded(t){this._isDraggable=!0;t&&this.div.focus()}isEmpty(){return!(this.#$r||this.#Ur||this.#Vr||this.#jr||this.#Gr)}get isResizable(){return!0}render(){if(this.div)return this.div;let t,e;if(this.width){t=this.x;e=this.y}super.render();this.div.hidden=!0;this.div.setAttribute("role","figure");this.addAltTextButton();this.#Ur?this.#Jr():this.#to();if(this.width&&!this.annotationElementId){const[i,s]=this.parentDimensions;this.setAt(t*i,e*s,this.width*i,this.height*s)}this._uiManager.addShouldRescale(this);return this.div}_onResized(){this.onScaleChanging()}onScaleChanging(){if(!this.parent)return;null!==this.#Xr&&clearTimeout(this.#Xr);this.#Xr=setTimeout((()=>{this.#Xr=null;this.#eo()}),200)}#Jr(){const{div:t}=this;let{width:e,height:i}=this.#Ur;const[s,n]=this.pageDimensions,a=.75;if(this.width){e=this.width*s;i=this.height*n}else if(e>a*s||i>a*n){const t=Math.min(a*s/e,a*n/i);e*=t;i*=t}const[r,o]=this.parentDimensions;this.setDims(e*r/s,i*o/n);this._uiManager.enableWaiting(!1);const l=this.#qr=document.createElement("canvas");l.setAttribute("role","img");this.addContainer(l);this.width=e/s;this.height=i/n;this._initialOptions?.isCentered?this.center():this.fixAndSetPosition();this._initialOptions=null;this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&!this.annotationElementId||(t.hidden=!1);this.#eo();if(!this.#Yr){this.parent.addUndoableEditor(this);this.#Yr=!0}this._reportTelemetry({action:"inserted_image"});this.#Wr&&l.setAttribute("aria-label",this.#Wr)}copyCanvas(t,e,i=!1){t||(t=224);const{width:s,height:n}=this.#Ur,a=new OutputScale;let r=this.#Ur,o=s,l=n,h=null;if(e){if(s>e||n>e){const t=Math.min(e/s,e/n);o=Math.floor(s*t);l=Math.floor(n*t)}h=document.createElement("canvas");const t=h.width=Math.ceil(o*a.sx),i=h.height=Math.ceil(l*a.sy);this.#Kr||(r=this.#io(t,i));const d=h.getContext("2d");d.filter=this._uiManager.hcmFilter;let c="white",u="#cfcfd8";if("none"!==this._uiManager.hcmFilter)u="black";else if(window.matchMedia?.("(prefers-color-scheme: dark)").matches){c="#8f8f9d";u="#42414d"}const p=15,g=p*a.sx,m=p*a.sy,f=new OffscreenCanvas(2*g,2*m),b=f.getContext("2d");b.fillStyle=c;b.fillRect(0,0,2*g,2*m);b.fillStyle=u;b.fillRect(0,0,g,m);b.fillRect(g,m,g,m);d.fillStyle=d.createPattern(f,"repeat");d.fillRect(0,0,t,i);d.drawImage(r,0,0,r.width,r.height,0,0,t,i)}let d=null;if(i){let e,i;if(a.symmetric&&r.widtht||n>t){const a=Math.min(t/s,t/n);e=Math.floor(s*a);i=Math.floor(n*a);this.#Kr||(r=this.#io(e,i))}}const o=new OffscreenCanvas(e,i).getContext("2d",{willReadFrequently:!0});o.drawImage(r,0,0,r.width,r.height,0,0,e,i);d={width:e,height:i,data:o.getImageData(0,0,e,i).data}}return{canvas:h,width:o,height:l,imageData:d}}#io(t,e){const{width:i,height:s}=this.#Ur;let n=i,a=s,r=this.#Ur;for(;n>2*t||a>2*e;){const i=n,s=a;n>2*t&&(n=n>=16384?Math.floor(n/2)-1:Math.ceil(n/2));a>2*e&&(a=a>=16384?Math.floor(a/2)-1:Math.ceil(a/2));const o=new OffscreenCanvas(n,a);o.getContext("2d").drawImage(r,0,0,i,s,0,0,n,a);r=o.transferToImageBitmap()}return r}#eo(){const[t,e]=this.parentDimensions,{width:i,height:s}=this,n=new OutputScale,a=Math.ceil(i*t*n.sx),r=Math.ceil(s*e*n.sy),o=this.#qr;if(!o||o.width===a&&o.height===r)return;o.width=a;o.height=r;const l=this.#Kr?this.#Ur:this.#io(a,r),h=o.getContext("2d");h.filter=this._uiManager.hcmFilter;h.drawImage(l,0,0,l.width,l.height,0,0,a,r)}getImageForAltText(){return this.#qr}#so(t){if(t){if(this.#Kr){const t=this._uiManager.imageManager.getSvgUrl(this.#Gr);if(t)return t}const t=document.createElement("canvas");({width:t.width,height:t.height}=this.#Ur);t.getContext("2d").drawImage(this.#Ur,0,0);return t.toDataURL()}if(this.#Kr){const[t,e]=this.pageDimensions,i=Math.round(this.width*t*PixelsPerInch.PDF_TO_CSS_UNITS),s=Math.round(this.height*e*PixelsPerInch.PDF_TO_CSS_UNITS),n=new OffscreenCanvas(i,s);n.getContext("2d").drawImage(this.#Ur,0,0,this.#Ur.width,this.#Ur.height,0,0,i,s);return n.transferToImageBitmap()}return structuredClone(this.#Ur)}static async deserialize(t,e,i){let s=null;if(t instanceof StampAnnotationElement){const{data:{rect:n,rotation:a,id:r,structParent:o,popupRef:l},container:h,parent:{page:{pageNumber:d}}}=t,c=h.querySelector("canvas"),u=i.imageManager.getFromCanvas(h.id,c);c.remove();const p=(await e._structTree.getAriaAttributes(`${et}${r}`))?.get("aria-label")||"";s=t={annotationType:g.STAMP,bitmapId:u.id,bitmap:u.bitmap,pageIndex:d-1,rect:n.slice(0),rotation:a,id:r,deleted:!1,accessibilityData:{decorative:!1,altText:p},isSvg:!1,structParent:o,popupRef:l}}const n=await super.deserialize(t,e,i),{rect:a,bitmap:r,bitmapUrl:o,bitmapId:l,isSvg:h,accessibilityData:d}=t;if(l&&i.imageManager.isValidId(l)){n.#Gr=l;r&&(n.#Ur=r)}else n.#Vr=o;n.#Kr=h;const[c,u]=n.pageDimensions;n.width=(a[2]-a[0])/c;n.height=(a[3]-a[1])/u;n.annotationElementId=t.id||null;d&&(n.altTextData=d);n._initialData=s;n.#Yr=!!s;return n}serialize(t=!1,e=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const i={annotationType:g.STAMP,bitmapId:this.#Gr,pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:this.#Kr,structTreeParentId:this._structTreeParentId};if(t){i.bitmapUrl=this.#so(!0);i.accessibilityData=this.serializeAltText(!0);return i}const{decorative:s,altText:n}=this.serializeAltText(!1);!s&&n&&(i.accessibilityData={type:"Figure",alt:n});if(this.annotationElementId){const t=this.#$n(i);if(t.isSame)return null;t.isSameAltText?delete i.accessibilityData:i.accessibilityData.structParent=this._initialData.structParent??-1}i.id=this.annotationElementId;if(null===e)return i;e.stamps||=new Map;const a=this.#Kr?(i.rect[2]-i.rect[0])*(i.rect[3]-i.rect[1]):null;if(e.stamps.has(this.#Gr)){if(this.#Kr){const t=e.stamps.get(this.#Gr);if(a>t.area){t.area=a;t.serialized.bitmap.close();t.serialized.bitmap=this.#so(!1)}}}else{e.stamps.set(this.#Gr,{area:a,serialized:i});i.bitmap=this.#so(!1)}return i}#$n(t){const{pageIndex:e,accessibilityData:{altText:i}}=this._initialData,s=t.pageIndex===e,n=(t.accessibilityData?.alt||"")===i;return{isSame:!this._hasBeenMoved&&!this._hasBeenResized&&s&&n,isSameAltText:n}}renderAnnotationElement(t){t.updateEdited({rect:this.getRect(0,0)});return null}}class AnnotationEditorLayer{#Cn;#no=!1;#ao=null;#ro=null;#oo=null;#lo=new Map;#ho=!1;#do=!1;#co=!1;#uo=null;#po=null;#go=null;#mo=null;#m;static _initialized=!1;static#U=new Map([FreeTextEditor,InkEditor,StampEditor,HighlightEditor].map((t=>[t._editorType,t])));constructor({uiManager:t,pageIndex:e,div:i,structTreeLayer:s,accessibilityManager:n,annotationLayer:a,drawLayer:r,textLayer:o,viewport:l,l10n:h}){const d=[...AnnotationEditorLayer.#U.values()];if(!AnnotationEditorLayer._initialized){AnnotationEditorLayer._initialized=!0;for(const e of d)e.initialize(h,t)}t.registerEditorTypes(d);this.#m=t;this.pageIndex=e;this.div=i;this.#Cn=n;this.#ao=a;this.viewport=l;this.#go=o;this.drawLayer=r;this._structTree=s;this.#m.addLayer(this)}get isEmpty(){return 0===this.#lo.size}get isInvisible(){return this.isEmpty&&this.#m.getMode()===g.NONE}updateToolbar(t){this.#m.updateToolbar(t)}updateMode(t=this.#m.getMode()){this.#fo();switch(t){case g.NONE:this.disableTextSelection();this.togglePointerEvents(!1);this.toggleAnnotationLayerPointerEvents(!0);this.disableClick();return;case g.INK:this.disableTextSelection();this.togglePointerEvents(!0);this.enableClick();break;case g.HIGHLIGHT:this.enableTextSelection();this.togglePointerEvents(!1);this.disableClick();break;default:this.disableTextSelection();this.togglePointerEvents(!0);this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);const{classList:e}=this.div;for(const i of AnnotationEditorLayer.#U.values())e.toggle(`${i._type}Editing`,t===i._editorType);this.div.hidden=!1}hasTextLayer(t){return t===this.#go?.div}setEditingState(t){this.#m.setEditingState(t)}addCommands(t){this.#m.addCommands(t)}cleanUndoStack(t){this.#m.cleanUndoStack(t)}toggleDrawing(t=!1){this.div.classList.toggle("drawing",!t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){this.#ao?.div.classList.toggle("disabled",!t)}async enable(){this.#co=!0;this.div.tabIndex=0;this.togglePointerEvents(!0);const t=new Set;for(const e of this.#lo.values()){e.enableEditing();e.show(!0);if(e.annotationElementId){this.#m.removeChangedExistingAnnotation(e);t.add(e.annotationElementId)}}if(!this.#ao){this.#co=!1;return}const e=this.#ao.getEditableAnnotations();for(const i of e){i.hide();if(this.#m.isDeletedAnnotationElement(i.data.id))continue;if(t.has(i.data.id))continue;const e=await this.deserialize(i);if(e){this.addOrRebuild(e);e.enableEditing()}}this.#co=!1}disable(){this.#do=!0;this.div.tabIndex=-1;this.togglePointerEvents(!1);const t=new Map,e=new Map;for(const i of this.#lo.values()){i.disableEditing();if(i.annotationElementId)if(null===i.serialize()){e.set(i.annotationElementId,i);this.getEditableAnnotation(i.annotationElementId)?.show();i.remove()}else t.set(i.annotationElementId,i)}if(this.#ao){const i=this.#ao.getEditableAnnotations();for(const s of i){const{id:i}=s.data;if(this.#m.isDeletedAnnotationElement(i))continue;let n=e.get(i);if(n){n.resetAnnotationElement(s);n.show(!1);s.show()}else{n=t.get(i);if(n){this.#m.addChangedExistingAnnotation(n);n.renderAnnotationElement(s)&&n.show(!1)}s.show()}}}this.#fo();this.isEmpty&&(this.div.hidden=!0);const{classList:i}=this.div;for(const t of AnnotationEditorLayer.#U.values())i.remove(`${t._type}Editing`);this.disableTextSelection();this.toggleAnnotationLayerPointerEvents(!0);this.#do=!1}getEditableAnnotation(t){return this.#ao?.getEditableAnnotation(t)||null}setActiveEditor(t){this.#m.getActive()!==t&&this.#m.setActiveEditor(t)}enableTextSelection(){this.div.tabIndex=-1;if(this.#go?.div&&!this.#mo){this.#mo=new AbortController;const t=this.#m.combinedSignal(this.#mo);this.#go.div.addEventListener("pointerdown",this.#bo.bind(this),{signal:t});this.#go.div.classList.add("highlighting")}}disableTextSelection(){this.div.tabIndex=0;if(this.#go?.div&&this.#mo){this.#mo.abort();this.#mo=null;this.#go.div.classList.remove("highlighting")}}#bo(t){this.#m.unselectAll();const{target:e}=t;if(e===this.#go.div||("img"===e.getAttribute("role")||e.classList.contains("endOfContent"))&&this.#go.div.contains(e)){const{isMac:e}=util_FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)return;this.#m.showAllEditors("highlight",!0,!0);this.#go.div.classList.add("free");this.toggleDrawing();HighlightEditor.startHighlighting(this,"ltr"===this.#m.direction,{target:this.#go.div,x:t.x,y:t.y});this.#go.div.addEventListener("pointerup",(()=>{this.#go.div.classList.remove("free");this.toggleDrawing(!0)}),{once:!0,signal:this.#m._signal});t.preventDefault()}}enableClick(){if(this.#ro)return;this.#ro=new AbortController;const t=this.#m.combinedSignal(this.#ro);this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t});const e=this.pointerup.bind(this);this.div.addEventListener("pointerup",e,{signal:t});this.div.addEventListener("pointercancel",e,{signal:t})}disableClick(){this.#ro?.abort();this.#ro=null}attach(t){this.#lo.set(t.id,t);const{annotationElementId:e}=t;e&&this.#m.isDeletedAnnotationElement(e)&&this.#m.removeDeletedAnnotationElement(t)}detach(t){this.#lo.delete(t.id);this.#Cn?.removePointerInTextLayer(t.contentDiv);!this.#do&&t.annotationElementId&&this.#m.addDeletedAnnotationElement(t)}remove(t){this.detach(t);this.#m.removeEditor(t);t.div.remove();t.isAttachedToDOM=!1}changeParent(t){if(t.parent!==this){if(t.parent&&t.annotationElementId){this.#m.addDeletedAnnotationElement(t.annotationElementId);AnnotationEditor.deleteAnnotationElement(t);t.annotationElementId=null}this.attach(t);t.parent?.detach(t);t.setParent(this);if(t.div&&t.isAttachedToDOM){t.div.remove();this.div.append(t.div)}}}add(t){if(t.parent!==this||!t.isAttachedToDOM){this.changeParent(t);this.#m.addEditor(t);this.attach(t);if(!t.isAttachedToDOM){const e=t.render();this.div.append(e);t.isAttachedToDOM=!0}t.fixAndSetPosition();t.onceAdded(!this.#co);this.#m.addToAnnotationStorage(t);t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){if(!t.isAttachedToDOM)return;const{activeElement:e}=document;if(t.div.contains(e)&&!this.#oo){t._focusEventsAllowed=!1;this.#oo=setTimeout((()=>{this.#oo=null;if(t.div.contains(document.activeElement))t._focusEventsAllowed=!0;else{t.div.addEventListener("focusin",(()=>{t._focusEventsAllowed=!0}),{once:!0,signal:this.#m._signal});e.focus()}}),0)}t._structTreeParentId=this.#Cn?.moveElementInDOM(this.div,t.div,t.contentDiv,!0)}addOrRebuild(t){if(t.needsToBeRebuilt()){t.parent||=this;t.rebuild();t.show()}else this.add(t)}addUndoableEditor(t){this.addCommands({cmd:()=>t._uiManager.rebuild(t),undo:()=>{t.remove()},mustExec:!1})}getNextId(){return this.#m.getId()}get#Ao(){return AnnotationEditorLayer.#U.get(this.#m.getMode())}combinedSignal(t){return this.#m.combinedSignal(t)}#wo(t){const e=this.#Ao;return e?new e.prototype.constructor(t):null}canCreateNewEmptyEditor(){return this.#Ao?.canCreateNewEmptyEditor()}pasteEditor(t,e){this.#m.updateToolbar(t);this.#m.updateMode(t);const{offsetX:i,offsetY:s}=this.#vo(),n=this.getNextId(),a=this.#wo({parent:this,id:n,x:i,y:s,uiManager:this.#m,isCentered:!0,...e});a&&this.add(a)}async deserialize(t){return await(AnnotationEditorLayer.#U.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#m))||null}createAndAddNewEditor(t,e,i={}){const s=this.getNextId(),n=this.#wo({parent:this,id:s,x:t.offsetX,y:t.offsetY,uiManager:this.#m,isCentered:e,...i});n&&this.add(n);return n}#vo(){const{x:t,y:e,width:i,height:s}=this.div.getBoundingClientRect(),n=Math.max(0,t),a=Math.max(0,e),r=(n+Math.min(window.innerWidth,t+i))/2-t,o=(a+Math.min(window.innerHeight,e+s))/2-e,[l,h]=this.viewport.rotation%180==0?[r,o]:[o,r];return{offsetX:l,offsetY:h}}addNewEditor(){this.createAndAddNewEditor(this.#vo(),!0)}setSelected(t){this.#m.setSelected(t)}toggleSelected(t){this.#m.toggleSelected(t)}unselect(t){this.#m.unselect(t)}pointerup(t){const{isMac:e}=util_FeatureTest.platform;if(!(0!==t.button||t.ctrlKey&&e)&&t.target===this.div&&this.#ho){this.#ho=!1;this.#Ao?.isDrawer&&this.#Ao.supportMultipleDrawings||(this.#no?this.#m.getMode()!==g.STAMP?this.createAndAddNewEditor(t,!1):this.#m.unselectAll():this.#no=!0)}}pointerdown(t){this.#m.getMode()===g.HIGHLIGHT&&this.enableTextSelection();if(this.#ho){this.#ho=!1;return}const{isMac:e}=util_FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)return;if(t.target!==this.div)return;this.#ho=!0;if(this.#Ao?.isDrawer){this.startDrawingSession(t);return}const i=this.#m.getActive();this.#no=!i||i.isEmpty()}startDrawingSession(t){this.div.focus();if(this.#uo){this.#Ao.startDrawing(this,this.#m,!1,t);return}this.#m.setCurrentDrawingSession(this);this.#uo=new AbortController;const e=this.#m.combinedSignal(this.#uo);this.div.addEventListener("blur",(({relatedTarget:t})=>{if(t&&!this.div.contains(t)){this.#po=null;this.commitOrRemove()}}),{signal:e});this.#Ao.startDrawing(this,this.#m,!1,t)}pause(t){if(t){const{activeElement:t}=document;this.div.contains(t)&&(this.#po=t)}else this.#po&&setTimeout((()=>{this.#po?.focus();this.#po=null}),0)}endDrawingSession(t=!1){if(!this.#uo)return null;this.#m.setCurrentDrawingSession(null);this.#uo.abort();this.#uo=null;this.#po=null;return this.#Ao.endDrawing(t)}findNewParent(t,e,i){const s=this.#m.findParent(e,i);if(null===s||s===this)return!1;s.changeParent(t);return!0}commitOrRemove(){if(this.#uo){this.endDrawingSession();return!0}return!1}onScaleChanging(){this.#uo&&this.#Ao.onScaleChangingWhenDrawing(this)}destroy(){this.commitOrRemove();if(this.#m.getActive()?.parent===this){this.#m.commitOrRemove();this.#m.setActiveEditor(null)}if(this.#oo){clearTimeout(this.#oo);this.#oo=null}for(const t of this.#lo.values()){this.#Cn?.removePointerInTextLayer(t.contentDiv);t.setParent(null);t.isAttachedToDOM=!1;t.div.remove()}this.div=null;this.#lo.clear();this.#m.removeLayer(this)}#fo(){for(const t of this.#lo.values())t.isEmpty()&&t.remove()}render({viewport:t}){this.viewport=t;setLayerDimensions(this.div,t);for(const t of this.#m.getEditors(this.pageIndex)){this.add(t);t.rebuild()}this.updateMode()}update({viewport:t}){this.#m.commitOrRemove();this.#fo();const e=this.viewport.rotation,i=t.rotation;this.viewport=t;setLayerDimensions(this.div,{rotation:i});if(e!==i)for(const t of this.#lo.values())t.rotate(i)}get pageDimensions(){const{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return this.#m.viewParameters.realScale}}class DrawLayer{#nn=null;#w=0;#yo=new Map;#xo=new Map;constructor({pageIndex:t}){this.pageIndex=t}setParent(t){if(this.#nn){if(this.#nn!==t){if(this.#yo.size>0)for(const e of this.#yo.values()){e.remove();t.append(e)}this.#nn=t}}else this.#nn=t}static get _svgFactory(){return shadow(this,"_svgFactory",new DOMSVGFactory)}static#_o(t,[e,i,s,n]){const{style:a}=t;a.top=100*i+"%";a.left=100*e+"%";a.width=100*s+"%";a.height=100*n+"%"}#Eo(){const t=DrawLayer._svgFactory.create(1,1,!0);this.#nn.append(t);t.setAttribute("aria-hidden",!0);return t}#So(t,e){const i=DrawLayer._svgFactory.createElement("clipPath");t.append(i);const s=`clip_${e}`;i.setAttribute("id",s);i.setAttribute("clipPathUnits","objectBoundingBox");const n=DrawLayer._svgFactory.createElement("use");i.append(n);n.setAttribute("href",`#${e}`);n.classList.add("clip");return s}#Co(t,e){for(const[i,s]of Object.entries(e))null===s?t.removeAttribute(i):t.setAttribute(i,s)}draw(t,e=!1,i=!1){const s=this.#w++,n=this.#Eo(),a=DrawLayer._svgFactory.createElement("defs");n.append(a);const r=DrawLayer._svgFactory.createElement("path");a.append(r);const o=`path_p${this.pageIndex}_${s}`;r.setAttribute("id",o);r.setAttribute("vector-effect","non-scaling-stroke");e&&this.#xo.set(s,r);const l=i?this.#So(a,o):null,h=DrawLayer._svgFactory.createElement("use");n.append(h);h.setAttribute("href",`#${o}`);this.updateProperties(n,t);this.#yo.set(s,n);return{id:s,clipPathId:`url(#${l})`}}drawOutline(t,e){const i=this.#w++,s=this.#Eo(),n=DrawLayer._svgFactory.createElement("defs");s.append(n);const a=DrawLayer._svgFactory.createElement("path");n.append(a);const r=`path_p${this.pageIndex}_${i}`;a.setAttribute("id",r);a.setAttribute("vector-effect","non-scaling-stroke");let o;if(e){const t=DrawLayer._svgFactory.createElement("mask");n.append(t);o=`mask_p${this.pageIndex}_${i}`;t.setAttribute("id",o);t.setAttribute("maskUnits","objectBoundingBox");const e=DrawLayer._svgFactory.createElement("rect");t.append(e);e.setAttribute("width","1");e.setAttribute("height","1");e.setAttribute("fill","white");const s=DrawLayer._svgFactory.createElement("use");t.append(s);s.setAttribute("href",`#${r}`);s.setAttribute("stroke","none");s.setAttribute("fill","black");s.setAttribute("fill-rule","nonzero");s.classList.add("mask")}const l=DrawLayer._svgFactory.createElement("use");s.append(l);l.setAttribute("href",`#${r}`);o&&l.setAttribute("mask",`url(#${o})`);const h=l.cloneNode();s.append(h);l.classList.add("mainOutline");h.classList.add("secondaryOutline");this.updateProperties(s,t);this.#yo.set(i,s);return i}finalizeDraw(t,e){this.#xo.delete(t);this.updateProperties(t,e)}updateProperties(t,e){if(!e)return;const{root:i,bbox:s,rootClass:n,path:a}=e,r="number"==typeof t?this.#yo.get(t):t;if(r){i&&this.#Co(r,i);s&&DrawLayer.#_o(r,s);if(n){const{classList:t}=r;for(const[e,i]of Object.entries(n))t.toggle(e,i)}if(a){const t=r.firstChild.firstChild;this.#Co(t,a)}}}updateParent(t,e){if(e===this)return;const i=this.#yo.get(t);if(i){e.#nn.append(i);this.#yo.delete(t);e.#yo.set(t,i)}}remove(t){this.#xo.delete(t);if(null!==this.#nn){this.#yo.get(t).remove();this.#yo.delete(t)}}destroy(){this.#nn=null;for(const t of this.#yo.values())t.remove();this.#yo.clear();this.#xo.clear()}}globalThis.pdfjsTestingUtils={HighlightOutliner};var Ut=__webpack_exports__.AbortException,Gt=__webpack_exports__.AnnotationEditorLayer,$t=__webpack_exports__.AnnotationEditorParamsType,Vt=__webpack_exports__.AnnotationEditorType,jt=__webpack_exports__.AnnotationEditorUIManager,Wt=__webpack_exports__.AnnotationLayer,qt=__webpack_exports__.AnnotationMode,Xt=__webpack_exports__.ColorPicker,Kt=__webpack_exports__.DOMSVGFactory,Yt=__webpack_exports__.DrawLayer,Qt=__webpack_exports__.FeatureTest,Jt=__webpack_exports__.GlobalWorkerOptions,Zt=__webpack_exports__.ImageKind,te=__webpack_exports__.InvalidPDFException,ee=__webpack_exports__.MissingPDFException,ie=__webpack_exports__.OPS,se=__webpack_exports__.OutputScale,ne=__webpack_exports__.PDFDataRangeTransport,ae=__webpack_exports__.PDFDateString,re=__webpack_exports__.PDFWorker,oe=__webpack_exports__.PasswordResponses,le=__webpack_exports__.PermissionFlag,he=__webpack_exports__.PixelsPerInch,de=__webpack_exports__.RenderingCancelledException,ce=__webpack_exports__.TextLayer,ue=__webpack_exports__.TouchManager,pe=__webpack_exports__.UnexpectedResponseException,ge=__webpack_exports__.Util,me=__webpack_exports__.VerbosityLevel,fe=__webpack_exports__.XfaLayer,be=__webpack_exports__.build,Ae=__webpack_exports__.createValidAbsoluteUrl,we=__webpack_exports__.fetchData,ve=__webpack_exports__.getDocument,ye=__webpack_exports__.getFilenameFromUrl,xe=__webpack_exports__.getPdfFilenameFromUrl,_e=__webpack_exports__.getXfaPageViewport,Ee=__webpack_exports__.isDataScheme,Se=__webpack_exports__.isPdfFile,Ce=__webpack_exports__.noContextMenu,Te=__webpack_exports__.normalizeUnicode,Me=__webpack_exports__.setLayerDimensions,Pe=__webpack_exports__.shadow,De=__webpack_exports__.stopEvent,ke=__webpack_exports__.version;export{Ut as AbortException,Gt as AnnotationEditorLayer,$t as AnnotationEditorParamsType,Vt as AnnotationEditorType,jt as AnnotationEditorUIManager,Wt as AnnotationLayer,qt as AnnotationMode,Xt as ColorPicker,Kt as DOMSVGFactory,Yt as DrawLayer,Qt as FeatureTest,Jt as GlobalWorkerOptions,Zt as ImageKind,te as InvalidPDFException,ee as MissingPDFException,ie as OPS,se as OutputScale,ne as PDFDataRangeTransport,ae as PDFDateString,re as PDFWorker,oe as PasswordResponses,le as PermissionFlag,he as PixelsPerInch,de as RenderingCancelledException,ce as TextLayer,ue as TouchManager,pe as UnexpectedResponseException,ge as Util,me as VerbosityLevel,fe as XfaLayer,be as build,Ae as createValidAbsoluteUrl,we as fetchData,ve as getDocument,ye as getFilenameFromUrl,xe as getPdfFilenameFromUrl,_e as getXfaPageViewport,Ee as isDataScheme,Se as isPdfFile,Ce as noContextMenu,Te as normalizeUnicode,Me as setLayerDimensions,Pe as shadow,De as stopEvent,ke as version}; \ No newline at end of file diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/pdfjs-dist/dist/build/pdf.worker.min.mjs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/pdfjs-dist/dist/build/pdf.worker.min.mjs deleted file mode 100644 index ee4038504a6..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/pdfjs-dist/dist/build/pdf.worker.min.mjs +++ /dev/null @@ -1,21 +0,0 @@ -/** - * @licstart The following is the entire license notice for the - * JavaScript code in this page - * - * Copyright 2024 Mozilla Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * @licend The above is the entire license notice for the - * JavaScript code in this page - */var e={d:(t,i)=>{for(var a in i)e.o(i,a)&&!e.o(t,a)&&Object.defineProperty(t,a,{enumerable:!0,get:i[a]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},__webpack_exports__ = globalThis.pdfjsWorker = {};e.d(__webpack_exports__,{WorkerMessageHandler:()=>WorkerMessageHandler});const t=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),i=[1,0,0,1,0,0],a=[.001,0,0,.001,0,0],s=1.35,r=.35,n=.25925925925925924,g=1,o=2,c=4,C=8,h=16,l=64,Q=128,E=256,u="pdfjs_internal_editor_",d=3,f=9,p=13,m=15,y={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},w=0,D=4,b=1,F=2,S=3,k=1,R=2,N=3,G=4,M=5,U=6,x=7,L=8,H=9,J=10,Y=11,v=12,K=13,T=14,q=15,O=16,W=17,j=20,X="Group",Z="R",V=1,z=2,_=4,$=16,AA=32,eA=128,tA=512,iA=1,aA=2,sA=4096,rA=8192,nA=32768,gA=65536,oA=131072,IA=1048576,cA=2097152,CA=8388608,hA=16777216,lA=1,BA=2,QA=3,EA=4,uA=5,dA={E:"Mouse Enter",X:"Mouse Exit",D:"Mouse Down",U:"Mouse Up",Fo:"Focus",Bl:"Blur",PO:"PageOpen",PC:"PageClose",PV:"PageVisible",PI:"PageInvisible",K:"Keystroke",F:"Format",V:"Validate",C:"Calculate"},fA={WC:"WillClose",WS:"WillSave",DS:"DidSave",WP:"WillPrint",DP:"DidPrint"},pA={O:"PageOpen",C:"PageClose"},mA=1,yA=5,wA=1,DA=2,bA=3,FA=4,SA=5,kA=6,RA=7,NA=8,GA=9,MA=10,UA=11,xA=12,LA=13,HA=14,JA=15,YA=16,vA=17,KA=18,TA=19,qA=20,OA=21,PA=22,WA=23,jA=24,XA=25,ZA=26,VA=27,zA=28,_A=29,$A=30,Ae=31,ee=32,te=33,ie=34,ae=35,se=36,re=37,ne=38,ge=39,oe=40,Ie=41,ce=42,Ce=43,he=44,le=45,Be=46,Qe=47,Ee=48,ue=49,de=50,fe=51,pe=52,me=53,ye=54,we=55,De=56,be=57,Fe=58,Se=59,ke=60,Re=61,Ne=62,Ge=63,Me=64,Ue=65,xe=66,Le=67,He=68,Je=69,Ye=70,ve=71,Ke=72,Te=73,qe=74,Oe=75,Pe=76,We=77,je=80,Xe=81,Ze=83,Ve=84,ze=85,_e=86,$e=87,At=88,et=89,tt=90,it=91,at=92,st=93,rt=1,nt=2;let gt=mA;function getVerbosityLevel(){return gt}function info(e){gt>=yA&&console.log(`Info: ${e}`)}function warn(e){gt>=mA&&console.log(`Warning: ${e}`)}function unreachable(e){throw new Error(e)}function assert(e,t){e||unreachable(t)}function createValidAbsoluteUrl(e,t=null,i=null){if(!e)return null;try{if(i&&"string"==typeof e){if(i.addDefaultProtocol&&e.startsWith("www.")){const t=e.match(/\./g);t?.length>=2&&(e=`http://${e}`)}if(i.tryConvertEncoding)try{e=stringToUTF8String(e)}catch{}}const a=t?new URL(e,t):new URL(e);if(function _isValidProtocol(e){switch(e?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(a))return a}catch{}return null}function shadow(e,t,i,a=!1){Object.defineProperty(e,t,{value:i,enumerable:!a,configurable:!0,writable:!1});return i}const ot=function BaseExceptionClosure(){function BaseException(e,t){this.message=e;this.name=t}BaseException.prototype=new Error;BaseException.constructor=BaseException;return BaseException}();class PasswordException extends ot{constructor(e,t){super(e,"PasswordException");this.code=t}}class UnknownErrorException extends ot{constructor(e,t){super(e,"UnknownErrorException");this.details=t}}class InvalidPDFException extends ot{constructor(e){super(e,"InvalidPDFException")}}class MissingPDFException extends ot{constructor(e){super(e,"MissingPDFException")}}class UnexpectedResponseException extends ot{constructor(e,t){super(e,"UnexpectedResponseException");this.status=t}}class FormatError extends ot{constructor(e){super(e,"FormatError")}}class AbortException extends ot{constructor(e){super(e,"AbortException")}}function bytesToString(e){"object"==typeof e&&void 0!==e?.length||unreachable("Invalid argument for bytesToString");const t=e.length,i=8192;if(t>24&255,e>>16&255,e>>8&255,255&e)}function objectSize(e){return Object.keys(e).length}class FeatureTest{static get isLittleEndian(){return shadow(this,"isLittleEndian",function isLittleEndian(){const e=new Uint8Array(4);e[0]=1;return 1===new Uint32Array(e.buffer,0,1)[0]}())}static get isEvalSupported(){return shadow(this,"isEvalSupported",function isEvalSupported(){try{new Function("");return!0}catch{return!1}}())}static get isOffscreenCanvasSupported(){return shadow(this,"isOffscreenCanvasSupported","undefined"!=typeof OffscreenCanvas)}static get isImageDecoderSupported(){return shadow(this,"isImageDecoderSupported","undefined"!=typeof ImageDecoder)}static get platform(){return"undefined"!=typeof navigator&&"string"==typeof navigator?.platform?shadow(this,"platform",{isMac:navigator.platform.includes("Mac"),isWindows:navigator.platform.includes("Win"),isFirefox:"string"==typeof navigator?.userAgent&&navigator.userAgent.includes("Firefox")}):shadow(this,"platform",{isMac:!1,isWindows:!1,isFirefox:!1})}static get isCSSRoundSupported(){return shadow(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}const It=Array.from(Array(256).keys(),(e=>e.toString(16).padStart(2,"0")));class Util{static makeHexColor(e,t,i){return`#${It[e]}${It[t]}${It[i]}`}static scaleMinMax(e,t){let i;if(e[0]){if(e[0]<0){i=t[0];t[0]=t[2];t[2]=i}t[0]*=e[0];t[2]*=e[0];if(e[3]<0){i=t[1];t[1]=t[3];t[3]=i}t[1]*=e[3];t[3]*=e[3]}else{i=t[0];t[0]=t[1];t[1]=i;i=t[2];t[2]=t[3];t[3]=i;if(e[1]<0){i=t[1];t[1]=t[3];t[3]=i}t[1]*=e[1];t[3]*=e[1];if(e[2]<0){i=t[0];t[0]=t[2];t[2]=i}t[0]*=e[2];t[2]*=e[2]}t[0]+=e[4];t[1]+=e[5];t[2]+=e[4];t[3]+=e[5]}static transform(e,t){return[e[0]*t[0]+e[2]*t[1],e[1]*t[0]+e[3]*t[1],e[0]*t[2]+e[2]*t[3],e[1]*t[2]+e[3]*t[3],e[0]*t[4]+e[2]*t[5]+e[4],e[1]*t[4]+e[3]*t[5]+e[5]]}static applyTransform(e,t){return[e[0]*t[0]+e[1]*t[2]+t[4],e[0]*t[1]+e[1]*t[3]+t[5]]}static applyInverseTransform(e,t){const i=t[0]*t[3]-t[1]*t[2];return[(e[0]*t[3]-e[1]*t[2]+t[2]*t[5]-t[4]*t[3])/i,(-e[0]*t[1]+e[1]*t[0]+t[4]*t[1]-t[5]*t[0])/i]}static getAxialAlignedBoundingBox(e,t){const i=this.applyTransform(e,t),a=this.applyTransform(e.slice(2,4),t),s=this.applyTransform([e[0],e[3]],t),r=this.applyTransform([e[2],e[1]],t);return[Math.min(i[0],a[0],s[0],r[0]),Math.min(i[1],a[1],s[1],r[1]),Math.max(i[0],a[0],s[0],r[0]),Math.max(i[1],a[1],s[1],r[1])]}static inverseTransform(e){const t=e[0]*e[3]-e[1]*e[2];return[e[3]/t,-e[1]/t,-e[2]/t,e[0]/t,(e[2]*e[5]-e[4]*e[3])/t,(e[4]*e[1]-e[5]*e[0])/t]}static singularValueDecompose2dScale(e){const t=[e[0],e[2],e[1],e[3]],i=e[0]*t[0]+e[1]*t[2],a=e[0]*t[1]+e[1]*t[3],s=e[2]*t[0]+e[3]*t[2],r=e[2]*t[1]+e[3]*t[3],n=(i+r)/2,g=Math.sqrt((i+r)**2-4*(i*r-s*a))/2,o=n+g||1,c=n-g||1;return[Math.sqrt(o),Math.sqrt(c)]}static normalizeRect(e){const t=e.slice(0);if(e[0]>e[2]){t[0]=e[2];t[2]=e[0]}if(e[1]>e[3]){t[1]=e[3];t[3]=e[1]}return t}static intersect(e,t){const i=Math.max(Math.min(e[0],e[2]),Math.min(t[0],t[2])),a=Math.min(Math.max(e[0],e[2]),Math.max(t[0],t[2]));if(i>a)return null;const s=Math.max(Math.min(e[1],e[3]),Math.min(t[1],t[3])),r=Math.min(Math.max(e[1],e[3]),Math.max(t[1],t[3]));return s>r?null:[i,s,a,r]}static#A(e,t,i,a,s,r,n,g,o,c){if(o<=0||o>=1)return;const C=1-o,h=o*o,l=h*o,Q=C*(C*(C*e+3*o*t)+3*h*i)+l*a,E=C*(C*(C*s+3*o*r)+3*h*n)+l*g;c[0]=Math.min(c[0],Q);c[1]=Math.min(c[1],E);c[2]=Math.max(c[2],Q);c[3]=Math.max(c[3],E)}static#e(e,t,i,a,s,r,n,g,o,c,C,h){if(Math.abs(o)<1e-12){Math.abs(c)>=1e-12&&this.#A(e,t,i,a,s,r,n,g,-C/c,h);return}const l=c**2-4*C*o;if(l<0)return;const Q=Math.sqrt(l),E=2*o;this.#A(e,t,i,a,s,r,n,g,(-c+Q)/E,h);this.#A(e,t,i,a,s,r,n,g,(-c-Q)/E,h)}static bezierBoundingBox(e,t,i,a,s,r,n,g,o){if(o){o[0]=Math.min(o[0],e,n);o[1]=Math.min(o[1],t,g);o[2]=Math.max(o[2],e,n);o[3]=Math.max(o[3],t,g)}else o=[Math.min(e,n),Math.min(t,g),Math.max(e,n),Math.max(t,g)];this.#e(e,i,s,n,t,a,r,g,3*(3*(i-s)-e+n),6*(e-2*i+s),3*(i-e),o);this.#e(e,i,s,n,t,a,r,g,3*(3*(a-r)-t+g),6*(t-2*a+r),3*(a-t),o);return o}}const ct=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,728,711,710,729,733,731,730,732,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8226,8224,8225,8230,8212,8211,402,8260,8249,8250,8722,8240,8222,8220,8221,8216,8217,8218,8482,64257,64258,321,338,352,376,381,305,322,339,353,382,0,8364];function stringToPDFString(e){if(e[0]>="ï"){let t;if("þ"===e[0]&&"ÿ"===e[1]){t="utf-16be";e.length%2==1&&(e=e.slice(0,-1))}else if("ÿ"===e[0]&&"þ"===e[1]){t="utf-16le";e.length%2==1&&(e=e.slice(0,-1))}else"ï"===e[0]&&"»"===e[1]&&"¿"===e[2]&&(t="utf-8");if(t)try{const i=new TextDecoder(t,{fatal:!0}),a=stringToBytes(e),s=i.decode(a);return s.includes("")?s.replaceAll(/\x1b[^\x1b]*(?:\x1b|$)/g,""):s}catch(e){warn(`stringToPDFString: "${e}".`)}}const t=[];for(let i=0,a=e.length;iIt[e])).join("")}"function"!=typeof Promise.try&&(Promise.try=function(e,...t){return new Promise((i=>{i(e(...t))}))});const lt=Symbol("CIRCULAR_REF"),Bt=Symbol("EOF");let Qt=Object.create(null),Et=Object.create(null),ut=Object.create(null);class Name{constructor(e){this.name=e}static get(e){return Et[e]||=new Name(e)}}class Cmd{constructor(e){this.cmd=e}static get(e){return Qt[e]||=new Cmd(e)}}const dt=function nonSerializableClosure(){return dt};class Dict{constructor(e=null){this._map=new Map;this.xref=e;this.objId=null;this.suppressEncryption=!1;this.__nonSerializable__=dt}assignXref(e){this.xref=e}get size(){return this._map.size}get(e,t,i){let a=this._map.get(e);if(void 0===a&&void 0!==t){a=this._map.get(t);void 0===a&&void 0!==i&&(a=this._map.get(i))}return a instanceof Ref&&this.xref?this.xref.fetch(a,this.suppressEncryption):a}async getAsync(e,t,i){let a=this._map.get(e);if(void 0===a&&void 0!==t){a=this._map.get(t);void 0===a&&void 0!==i&&(a=this._map.get(i))}return a instanceof Ref&&this.xref?this.xref.fetchAsync(a,this.suppressEncryption):a}getArray(e,t,i){let a=this._map.get(e);if(void 0===a&&void 0!==t){a=this._map.get(t);void 0===a&&void 0!==i&&(a=this._map.get(i))}a instanceof Ref&&this.xref&&(a=this.xref.fetch(a,this.suppressEncryption));if(Array.isArray(a)){a=a.slice();for(let e=0,t=a.length;e{unreachable("Should not call `set` on the empty dictionary.")};return shadow(this,"empty",e)}static merge({xref:e,dictArray:t,mergeSubDicts:i=!1}){const a=new Dict(e),s=new Map;for(const e of t)if(e instanceof Dict)for(const[t,a]of e._map){let e=s.get(t);if(void 0===e){e=[];s.set(t,e)}else if(!(i&&a instanceof Dict))continue;e.push(a)}for(const[t,i]of s){if(1===i.length||!(i[0]instanceof Dict)){a._map.set(t,i[0]);continue}const s=new Dict(e);for(const e of i)for(const[t,i]of e._map)s._map.has(t)||s._map.set(t,i);s.size>0&&a._map.set(t,s)}s.clear();return a.size>0?a:Dict.empty}clone(){const e=new Dict(this.xref);for(const t of this.getKeys())e.set(t,this.getRaw(t));return e}delete(e){delete this._map[e]}}class Ref{constructor(e,t){this.num=e;this.gen=t}toString(){return 0===this.gen?`${this.num}R`:`${this.num}R${this.gen}`}static fromString(e){const t=ut[e];if(t)return t;const i=/^(\d+)R(\d*)$/.exec(e);return i&&"0"!==i[1]?ut[e]=new Ref(parseInt(i[1]),i[2]?parseInt(i[2]):0):null}static get(e,t){const i=0===t?`${e}R`:`${e}R${t}`;return ut[i]||=new Ref(e,t)}}class RefSet{constructor(e=null){this._set=new Set(e?._set)}has(e){return this._set.has(e.toString())}put(e){this._set.add(e.toString())}remove(e){this._set.delete(e.toString())}[Symbol.iterator](){return this._set.values()}clear(){this._set.clear()}}class RefSetCache{constructor(){this._map=new Map}get size(){return this._map.size}get(e){return this._map.get(e.toString())}has(e){return this._map.has(e.toString())}put(e,t){this._map.set(e.toString(),t)}putAlias(e,t){this._map.set(e.toString(),this.get(t))}[Symbol.iterator](){return this._map.values()}clear(){this._map.clear()}*values(){yield*this._map.values()}*items(){for(const[e,t]of this._map)yield[Ref.fromString(e),t]}}function isName(e,t){return e instanceof Name&&(void 0===t||e.name===t)}function isCmd(e,t){return e instanceof Cmd&&(void 0===t||e.cmd===t)}function isDict(e,t){return e instanceof Dict&&(void 0===t||isName(e.get("Type"),t))}function isRefsEqual(e,t){return e.num===t.num&&e.gen===t.gen}class BaseStream{get length(){unreachable("Abstract getter `length` accessed")}get isEmpty(){unreachable("Abstract getter `isEmpty` accessed")}get isDataLoaded(){return shadow(this,"isDataLoaded",!0)}getByte(){unreachable("Abstract method `getByte` called")}getBytes(e){unreachable("Abstract method `getBytes` called")}async getImageData(e,t){return this.getBytes(e,t)}async asyncGetBytes(){unreachable("Abstract method `asyncGetBytes` called")}get isAsync(){return!1}get canAsyncDecodeImageFromBuffer(){return!1}async getTransferableImage(){return null}peekByte(){const e=this.getByte();-1!==e&&this.pos--;return e}peekBytes(e){const t=this.getBytes(e);this.pos-=t.length;return t}getUint16(){const e=this.getByte(),t=this.getByte();return-1===e||-1===t?-1:(e<<8)+t}getInt32(){return(this.getByte()<<24)+(this.getByte()<<16)+(this.getByte()<<8)+this.getByte()}getByteRange(e,t){unreachable("Abstract method `getByteRange` called")}getString(e){return bytesToString(this.getBytes(e))}skip(e){this.pos+=e||1}reset(){unreachable("Abstract method `reset` called")}moveStart(){unreachable("Abstract method `moveStart` called")}makeSubStream(e,t,i=null){unreachable("Abstract method `makeSubStream` called")}getBaseStreams(){return null}}const ft=/^[1-9]\.\d$/,pt=2**31-1;function getLookupTableFactory(e){let t;return function(){if(e){t=Object.create(null);e(t);e=null}return t}}class MissingDataException extends ot{constructor(e,t){super(`Missing data [${e}, ${t})`,"MissingDataException");this.begin=e;this.end=t}}class ParserEOFException extends ot{constructor(e){super(e,"ParserEOFException")}}class XRefEntryException extends ot{constructor(e){super(e,"XRefEntryException")}}class XRefParseException extends ot{constructor(e){super(e,"XRefParseException")}}function arrayBuffersToBytes(e){const t=e.length;if(0===t)return new Uint8Array(0);if(1===t)return new Uint8Array(e[0]);let i=0;for(let a=0;a0,"The number should be a positive integer.");const i="M".repeat(e/1e3|0)+mt[e%1e3/100|0]+mt[10+(e%100/10|0)]+mt[20+e%10];return t?i.toLowerCase():i}function log2(e){return e>0?Math.ceil(Math.log2(e)):0}function readInt8(e,t){return e[t]<<24>>24}function readUint16(e,t){return e[t]<<8|e[t+1]}function readUint32(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}function isWhiteSpace(e){return 32===e||9===e||13===e||10===e}function isNumberArray(e,t){return Array.isArray(e)?(null===t||e.length===t)&&e.every((e=>"number"==typeof e)):ArrayBuffer.isView(e)&&(0===e.length||"number"==typeof e[0])&&(null===t||e.length===t)}function lookupMatrix(e,t){return isNumberArray(e,6)?e:t}function lookupRect(e,t){return isNumberArray(e,4)?e:t}function lookupNormalRect(e,t){return isNumberArray(e,4)?Util.normalizeRect(e):t}function parseXFAPath(e){const t=/(.+)\[(\d+)\]$/;return e.split(".").map((e=>{const i=e.match(t);return i?{name:i[1],pos:parseInt(i[2],10)}:{name:e,pos:0}}))}function escapePDFName(e){const t=[];let i=0;for(let a=0,s=e.length;a126||35===s||40===s||41===s||60===s||62===s||91===s||93===s||123===s||125===s||47===s||37===s){i"\n"===e?"\\n":"\r"===e?"\\r":`\\${e}`))}function _collectJS(e,t,i,a){if(!e)return;let s=null;if(e instanceof Ref){if(a.has(e))return;s=e;a.put(s);e=t.fetch(e)}if(Array.isArray(e))for(const s of e)_collectJS(s,t,i,a);else if(e instanceof Dict){if(isName(e.get("S"),"JavaScript")){const t=e.get("JS");let a;t instanceof BaseStream?a=t.getString():"string"==typeof t&&(a=t);a&&=stringToPDFString(a).replaceAll("\0","");a&&i.push(a)}_collectJS(e.getRaw("Next"),t,i,a)}s&&a.remove(s)}function collectActions(e,t,i){const a=Object.create(null),s=getInheritableProperty({dict:t,key:"AA",stopWhenFound:!1});if(s)for(let t=s.length-1;t>=0;t--){const r=s[t];if(r instanceof Dict)for(const t of r.getKeys()){const s=i[t];if(!s)continue;const n=[];_collectJS(r.getRaw(t),e,n,new RefSet);n.length>0&&(a[s]=n)}}if(t.has("A")){const i=[];_collectJS(t.get("A"),e,i,new RefSet);i.length>0&&(a.Action=i)}return objectSize(a)>0?a:null}const yt={60:"<",62:">",38:"&",34:""",39:"'"};function*codePointIter(e){for(let t=0,i=e.length;t55295&&(i<57344||i>65533)&&t++;yield i}}function encodeToXmlString(e){const t=[];let i=0;for(let a=0,s=e.length;a55295&&(s<57344||s>65533)&&a++;i=a+1}}if(0===t.length)return e;i: ${e}.`);return!1}return!0}function validateCSSFont(e){const t=new Set(["100","200","300","400","500","600","700","800","900","1000","normal","bold","bolder","lighter"]),{fontFamily:i,fontWeight:a,italicAngle:s}=e;if(!validateFontName(i,!0))return!1;const r=a?a.toString():"";e.fontWeight=t.has(r)?r:"400";const n=parseFloat(s);e.italicAngle=isNaN(n)||n<-90||n>90?"14":s.toString();return!0}function recoverJsURL(e){const t=new RegExp("^\\s*("+["app.launchURL","window.open","xfa.host.gotoURL"].join("|").replaceAll(".","\\.")+")\\((?:'|\")([^'\"]*)(?:'|\")(?:,\\s*(\\w+)\\)|\\))","i").exec(e);return t?.[2]?{url:t[2],newWindow:"app.launchURL"===t[1]&&"true"===t[3]}:null}function numberToString(e){if(Number.isInteger(e))return e.toString();const t=Math.round(100*e);return t%100==0?(t/100).toString():t%10==0?e.toFixed(1):e.toFixed(2)}function getNewAnnotationsMap(e){if(!e)return null;const t=new Map;for(const[i,a]of e){if(!i.startsWith(u))continue;let e=t.get(a.pageIndex);if(!e){e=[];t.set(a.pageIndex,e)}e.push(a)}return t.size>0?t:null}function stringToAsciiOrUTF16BE(e){return function isAscii(e){return/^[\x00-\x7F]*$/.test(e)}(e)?e:stringToUTF16String(e,!0)}function stringToUTF16HexString(e){const t=[];for(let i=0,a=e.length;i>8&255],It[255&a])}return t.join("")}function stringToUTF16String(e,t=!1){const i=[];t&&i.push("þÿ");for(let t=0,a=e.length;t>8&255),String.fromCharCode(255&a))}return i.join("")}function getRotationMatrix(e,t,i){switch(e){case 90:return[0,1,-1,0,t,0];case 180:return[-1,0,0,-1,t,i];case 270:return[0,-1,1,0,0,i];default:throw new Error("Invalid rotation")}}function getSizeInBytes(e){return Math.ceil(Math.ceil(Math.log2(1+e))/8)}class Stream extends BaseStream{constructor(e,t,i,a){super();this.bytes=e instanceof Uint8Array?e:new Uint8Array(e);this.start=t||0;this.pos=this.start;this.end=t+i||this.bytes.length;this.dict=a}get length(){return this.end-this.start}get isEmpty(){return 0===this.length}getByte(){return this.pos>=this.end?-1:this.bytes[this.pos++]}getBytes(e){const t=this.bytes,i=this.pos,a=this.end;if(!e)return t.subarray(i,a);let s=i+e;s>a&&(s=a);this.pos=s;return t.subarray(i,s)}getByteRange(e,t){e<0&&(e=0);t>this.end&&(t=this.end);return this.bytes.subarray(e,t)}reset(){this.pos=this.start}moveStart(){this.start=this.pos}makeSubStream(e,t,i=null){return new Stream(this.bytes.buffer,e,t,i)}}class StringStream extends Stream{constructor(e){super(stringToBytes(e))}}class NullStream extends Stream{constructor(){super(new Uint8Array(0))}}class ChunkedStream extends Stream{constructor(e,t,i){super(new Uint8Array(e),0,e,null);this.chunkSize=t;this._loadedChunks=new Set;this.numChunks=Math.ceil(e/t);this.manager=i;this.progressiveDataLength=0;this.lastSuccessfulEnsureByteChunk=-1}getMissingChunks(){const e=[];for(let t=0,i=this.numChunks;t=this.end?this.numChunks:Math.floor(t/this.chunkSize);for(let e=i;ethis.numChunks)&&t!==this.lastSuccessfulEnsureByteChunk){if(!this._loadedChunks.has(t))throw new MissingDataException(e,e+1);this.lastSuccessfulEnsureByteChunk=t}}ensureRange(e,t){if(e>=t)return;if(t<=this.progressiveDataLength)return;const i=Math.floor(e/this.chunkSize);if(i>this.numChunks)return;const a=Math.min(Math.floor((t-1)/this.chunkSize)+1,this.numChunks);for(let s=i;s=this.end)return-1;e>=this.progressiveDataLength&&this.ensureByte(e);return this.bytes[this.pos++]}getBytes(e){const t=this.bytes,i=this.pos,a=this.end;if(!e){a>this.progressiveDataLength&&this.ensureRange(i,a);return t.subarray(i,a)}let s=i+e;s>a&&(s=a);s>this.progressiveDataLength&&this.ensureRange(i,s);this.pos=s;return t.subarray(i,s)}getByteRange(e,t){e<0&&(e=0);t>this.end&&(t=this.end);t>this.progressiveDataLength&&this.ensureRange(e,t);return this.bytes.subarray(e,t)}makeSubStream(e,t,i=null){t?e+t>this.progressiveDataLength&&this.ensureRange(e,e+t):e>=this.progressiveDataLength&&this.ensureByte(e);function ChunkedStreamSubstream(){}ChunkedStreamSubstream.prototype=Object.create(this);ChunkedStreamSubstream.prototype.getMissingChunks=function(){const e=this.chunkSize,t=Math.floor(this.start/e),i=Math.floor((this.end-1)/e)+1,a=[];for(let e=t;e{const readChunk=({value:r,done:n})=>{try{if(n){const t=arrayBuffersToBytes(a);a=null;e(t);return}s+=r.byteLength;i.isStreamingSupported&&this.onProgress({loaded:s});a.push(r);i.read().then(readChunk,t)}catch(e){t(e)}};i.read().then(readChunk,t)})).then((t=>{this.aborted||this.onReceiveData({chunk:t,begin:e})}))}requestAllChunks(e=!1){if(!e){const e=this.stream.getMissingChunks();this._requestChunks(e)}return this._loadedStreamCapability.promise}_requestChunks(e){const t=this.currRequestId++,i=new Set;this._chunksNeededByRequest.set(t,i);for(const t of e)this.stream.hasChunk(t)||i.add(t);if(0===i.size)return Promise.resolve();const a=Promise.withResolvers();this._promisesByRequest.set(t,a);const s=[];for(const e of i){let i=this._requestsByChunk.get(e);if(!i){i=[];this._requestsByChunk.set(e,i);s.push(e)}i.push(t)}if(s.length>0){const e=this.groupChunks(s);for(const t of e){const e=t.beginChunk*this.chunkSize,i=Math.min(t.endChunk*this.chunkSize,this.length);this.sendRequest(e,i).catch(a.reject)}}return a.promise.catch((e=>{if(!this.aborted)throw e}))}getStream(){return this.stream}requestRange(e,t){t=Math.min(t,this.length);const i=this.getBeginChunk(e),a=this.getEndChunk(t),s=[];for(let e=i;e=0&&a+1!==r){t.push({beginChunk:i,endChunk:a+1});i=r}s+1===e.length&&t.push({beginChunk:i,endChunk:r+1});a=r}return t}onProgress(e){this.msgHandler.send("DocProgress",{loaded:this.stream.numChunksLoaded*this.chunkSize+e.loaded,total:this.length})}onReceiveData(e){const t=e.chunk,i=void 0===e.begin,a=i?this.progressiveDataLength:e.begin,s=a+t.byteLength,r=Math.floor(a/this.chunkSize),n=s0||g.push(i)}}}if(!this.disableAutoFetch&&0===this._requestsByChunk.size){let e;if(1===this.stream.numChunksLoaded){const t=this.stream.numChunks-1;this.stream.hasChunk(t)||(e=t)}else e=this.stream.nextEmptyChunk(n);Number.isInteger(e)&&this._requestChunks([e])}for(const e of g){const t=this._promisesByRequest.get(e);this._promisesByRequest.delete(e);t.resolve()}this.msgHandler.send("DocProgress",{loaded:this.stream.numChunksLoaded*this.chunkSize,total:this.length})}onError(e){this._loadedStreamCapability.reject(e)}getBeginChunk(e){return Math.floor(e/this.chunkSize)}getEndChunk(e){return Math.floor((e-1)/this.chunkSize)+1}abort(e){this.aborted=!0;this.pdfNetworkStream?.cancelAllRequests(e);for(const t of this._promisesByRequest.values())t.reject(e)}}class ColorSpace{constructor(e,t){this.name=e;this.numComps=t}getRgb(e,t){const i=new Uint8ClampedArray(3);this.getRgbItem(e,t,i,0);return i}getRgbItem(e,t,i,a){unreachable("Should not call ColorSpace.getRgbItem")}getRgbBuffer(e,t,i,a,s,r,n){unreachable("Should not call ColorSpace.getRgbBuffer")}getOutputLength(e,t){unreachable("Should not call ColorSpace.getOutputLength")}isPassthrough(e){return!1}isDefaultDecode(e,t){return ColorSpace.isDefaultDecode(e,this.numComps)}fillRgb(e,t,i,a,s,r,n,g,o){const c=t*i;let C=null;const h=1<h&&"DeviceGray"!==this.name&&"DeviceRGB"!==this.name){const t=n<=8?new Uint8Array(h):new Uint16Array(h);for(let e=0;e=.99554525?1:this.#B(0,1,1.055*e**(1/2.4)-.055)}#B(e,t,i){return Math.max(e,Math.min(t,i))}#Q(e){return e<0?-this.#Q(-e):e>8?((e+16)/116)**3:e*CalRGBCS.#I}#E(e,t,i){if(0===e[0]&&0===e[1]&&0===e[2]){i[0]=t[0];i[1]=t[1];i[2]=t[2];return}const a=this.#Q(0),s=(1-a)/(1-this.#Q(e[0])),r=1-s,n=(1-a)/(1-this.#Q(e[1])),g=1-n,o=(1-a)/(1-this.#Q(e[2])),c=1-o;i[0]=t[0]*s+r;i[1]=t[1]*n+g;i[2]=t[2]*o+c}#u(e,t,i){if(1===e[0]&&1===e[2]){i[0]=t[0];i[1]=t[1];i[2]=t[2];return}const a=i;this.#c(CalRGBCS.#i,t,a);const s=CalRGBCS.#n;this.#C(e,a,s);this.#c(CalRGBCS.#a,s,i)}#d(e,t,i){const a=i;this.#c(CalRGBCS.#i,t,a);const s=CalRGBCS.#n;this.#h(e,a,s);this.#c(CalRGBCS.#a,s,i)}#t(e,t,i,a,s){const r=this.#B(0,1,e[t]*s),n=this.#B(0,1,e[t+1]*s),g=this.#B(0,1,e[t+2]*s),o=1===r?1:r**this.GR,c=1===n?1:n**this.GG,C=1===g?1:g**this.GB,h=this.MXA*o+this.MXB*c+this.MXC*C,l=this.MYA*o+this.MYB*c+this.MYC*C,Q=this.MZA*o+this.MZB*c+this.MZC*C,E=CalRGBCS.#g;E[0]=h;E[1]=l;E[2]=Q;const u=CalRGBCS.#o;this.#u(this.whitePoint,E,u);const d=CalRGBCS.#g;this.#E(this.blackPoint,u,d);const f=CalRGBCS.#o;this.#d(CalRGBCS.#r,d,f);const p=CalRGBCS.#g;this.#c(CalRGBCS.#s,f,p);i[a]=255*this.#l(p[0]);i[a+1]=255*this.#l(p[1]);i[a+2]=255*this.#l(p[2])}getRgbItem(e,t,i,a){this.#t(e,t,i,a,1)}getRgbBuffer(e,t,i,a,s,r,n){const g=1/((1<this.amax||this.bmin>this.bmax){info("Invalid Range, falling back to defaults");this.amin=-100;this.amax=100;this.bmin=-100;this.bmax=100}}#f(e){return e>=6/29?e**3:108/841*(e-4/29)}#p(e,t,i,a){return i+e*(a-i)/t}#t(e,t,i,a,s){let r=e[t],n=e[t+1],g=e[t+2];if(!1!==i){r=this.#p(r,i,0,100);n=this.#p(n,i,this.amin,this.amax);g=this.#p(g,i,this.bmin,this.bmax)}n>this.amax?n=this.amax:nthis.bmax?g=this.bmax:g>>0}function hexToStr(e,t){return 1===t?String.fromCharCode(e[0],e[1]):3===t?String.fromCharCode(e[0],e[1],e[2],e[3]):String.fromCharCode(...e.subarray(0,t+1))}function addHex(e,t,i){let a=0;for(let s=i;s>=0;s--){a+=e[s]+t[s];e[s]=255&a;a>>=8}}function incHex(e,t){let i=1;for(let a=t;a>=0&&i>0;a--){i+=e[a];e[a]=255&i;i>>=8}}const wt=16;class BinaryCMapStream{constructor(e){this.buffer=e;this.pos=0;this.end=e.length;this.tmpBuf=new Uint8Array(19)}readByte(){return this.pos>=this.end?-1:this.buffer[this.pos++]}readNumber(){let e,t=0;do{const i=this.readByte();if(i<0)throw new FormatError("unexpected EOF in bcmap");e=!(128&i);t=t<<7|127&i}while(!e);return t}readSigned(){const e=this.readNumber();return 1&e?~(e>>>1):e>>>1}readHex(e,t){e.set(this.buffer.subarray(this.pos,this.pos+t+1));this.pos+=t+1}readHexNumber(e,t){let i;const a=this.tmpBuf;let s=0;do{const e=this.readByte();if(e<0)throw new FormatError("unexpected EOF in bcmap");i=!(128&e);a[s++]=127&e}while(!i);let r=t,n=0,g=0;for(;r>=0;){for(;g<8&&a.length>0;){n|=a[--s]<>=8;g-=8}}readHexSigned(e,t){this.readHexNumber(e,t);const i=1&e[t]?255:0;let a=0;for(let s=0;s<=t;s++){a=(1&a)<<8|e[s];e[s]=a>>1^i}}readString(){const e=this.readNumber(),t=new Array(e);for(let i=0;i=0;){const e=l>>5;if(7===e){switch(31&l){case 0:a.readString();break;case 1:r=a.readString()}continue}const i=!!(16&l),s=15&l;if(s+1>wt)throw new Error("BinaryCMapReader.process: Invalid dataSize.");const Q=1,E=a.readNumber();switch(e){case 0:a.readHex(n,s);a.readHexNumber(g,s);addHex(g,n,s);t.addCodespaceRange(s+1,hexToInt(n,s),hexToInt(g,s));for(let e=1;es&&(a=s)}else{for(;!this.eof;)this.readBlock(t);a=this.bufferLength}this.pos=a;return this.buffer.subarray(i,a)}async getImageData(e,t=null){if(!this.canAsyncDecodeImageFromBuffer)return this.getBytes(e,t);const i=await this.stream.asyncGetBytes();return this.decodeImage(i,t)}reset(){this.pos=0}makeSubStream(e,t,i=null){if(void 0===t)for(;!this.eof;)this.readBlock();else{const i=e+t;for(;this.bufferLength<=i&&!this.eof;)this.readBlock()}return new Stream(this.buffer,e,t,i)}getBaseStreams(){return this.str?this.str.getBaseStreams():null}}class StreamsSequenceStream extends DecodeStream{constructor(e,t=null){e=e.filter((e=>e instanceof BaseStream));let i=0;for(const t of e)i+=t instanceof DecodeStream?t._rawMinBufferLength:t.length;super(i);this.streams=e;this._onError=t}readBlock(){const e=this.streams;if(0===e.length){this.eof=!0;return}const t=e.shift();let i;try{i=t.getBytes()}catch(e){if(this._onError){this._onError(e,t.dict?.objId);return}throw e}const a=this.bufferLength,s=a+i.length;this.ensureBuffer(s).set(i,a);this.bufferLength=s}getBaseStreams(){const e=[];for(const t of this.streams){const i=t.getBaseStreams();i&&e.push(...i)}return e.length>0?e:null}}class Ascii85Stream extends DecodeStream{constructor(e,t){t&&(t*=.8);super(t);this.str=e;this.dict=e.dict;this.input=new Uint8Array(5)}readBlock(){const e=this.str;let t=e.getByte();for(;isWhiteSpace(t);)t=e.getByte();if(-1===t||126===t){this.eof=!0;return}const i=this.bufferLength;let a,s;if(122===t){a=this.ensureBuffer(i+4);for(s=0;s<4;++s)a[i+s]=0;this.bufferLength+=4}else{const r=this.input;r[0]=t;for(s=1;s<5;++s){t=e.getByte();for(;isWhiteSpace(t);)t=e.getByte();r[s]=t;if(-1===t||126===t)break}a=this.ensureBuffer(i+s-1);this.bufferLength+=s-1;if(s<5){for(;s<5;++s)r[s]=117;this.eof=!0}let n=0;for(s=0;s<5;++s)n=85*n+(r[s]-33);for(s=3;s>=0;--s){a[i+s]=255&n;n>>=8}}}}class AsciiHexStream extends DecodeStream{constructor(e,t){t&&(t*=.5);super(t);this.str=e;this.dict=e.dict;this.firstDigit=-1}readBlock(){const e=this.str.getBytes(8e3);if(!e.length){this.eof=!0;return}const t=e.length+1>>1,i=this.ensureBuffer(this.bufferLength+t);let a=this.bufferLength,s=this.firstDigit;for(const t of e){let e;if(t>=48&&t<=57)e=15&t;else{if(!(t>=65&&t<=70||t>=97&&t<=102)){if(62===t){this.eof=!0;break}continue}e=9+(15&t)}if(s<0)s=e;else{i[a++]=s<<4|e;s=-1}}if(s>=0&&this.eof){i[a++]=s<<4;s=-1}this.firstDigit=s;this.bufferLength=a}}const bt=-1,Ft=[[-1,-1],[-1,-1],[7,8],[7,7],[6,6],[6,6],[6,5],[6,5],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2]],St=[[-1,-1],[12,-2],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[11,1792],[11,1792],[12,1984],[12,2048],[12,2112],[12,2176],[12,2240],[12,2304],[11,1856],[11,1856],[11,1920],[11,1920],[12,2368],[12,2432],[12,2496],[12,2560]],kt=[[-1,-1],[-1,-1],[-1,-1],[-1,-1],[8,29],[8,29],[8,30],[8,30],[8,45],[8,45],[8,46],[8,46],[7,22],[7,22],[7,22],[7,22],[7,23],[7,23],[7,23],[7,23],[8,47],[8,47],[8,48],[8,48],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[7,20],[7,20],[7,20],[7,20],[8,33],[8,33],[8,34],[8,34],[8,35],[8,35],[8,36],[8,36],[8,37],[8,37],[8,38],[8,38],[7,19],[7,19],[7,19],[7,19],[8,31],[8,31],[8,32],[8,32],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[8,53],[8,53],[8,54],[8,54],[7,26],[7,26],[7,26],[7,26],[8,39],[8,39],[8,40],[8,40],[8,41],[8,41],[8,42],[8,42],[8,43],[8,43],[8,44],[8,44],[7,21],[7,21],[7,21],[7,21],[7,28],[7,28],[7,28],[7,28],[8,61],[8,61],[8,62],[8,62],[8,63],[8,63],[8,0],[8,0],[8,320],[8,320],[8,384],[8,384],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[7,27],[7,27],[7,27],[7,27],[8,59],[8,59],[8,60],[8,60],[9,1472],[9,1536],[9,1600],[9,1728],[7,18],[7,18],[7,18],[7,18],[7,24],[7,24],[7,24],[7,24],[8,49],[8,49],[8,50],[8,50],[8,51],[8,51],[8,52],[8,52],[7,25],[7,25],[7,25],[7,25],[8,55],[8,55],[8,56],[8,56],[8,57],[8,57],[8,58],[8,58],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[8,448],[8,448],[8,512],[8,512],[9,704],[9,768],[8,640],[8,640],[8,576],[8,576],[9,832],[9,896],[9,960],[9,1024],[9,1088],[9,1152],[9,1216],[9,1280],[9,1344],[9,1408],[7,256],[7,256],[7,256],[7,256],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7]],Rt=[[-1,-1],[-1,-1],[12,-2],[12,-2],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[11,1792],[11,1792],[11,1792],[11,1792],[12,1984],[12,1984],[12,2048],[12,2048],[12,2112],[12,2112],[12,2176],[12,2176],[12,2240],[12,2240],[12,2304],[12,2304],[11,1856],[11,1856],[11,1856],[11,1856],[11,1920],[11,1920],[11,1920],[11,1920],[12,2368],[12,2368],[12,2432],[12,2432],[12,2496],[12,2496],[12,2560],[12,2560],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[12,52],[12,52],[13,640],[13,704],[13,768],[13,832],[12,55],[12,55],[12,56],[12,56],[13,1280],[13,1344],[13,1408],[13,1472],[12,59],[12,59],[12,60],[12,60],[13,1536],[13,1600],[11,24],[11,24],[11,24],[11,24],[11,25],[11,25],[11,25],[11,25],[13,1664],[13,1728],[12,320],[12,320],[12,384],[12,384],[12,448],[12,448],[13,512],[13,576],[12,53],[12,53],[12,54],[12,54],[13,896],[13,960],[13,1024],[13,1088],[13,1152],[13,1216],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64]],Nt=[[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[11,23],[11,23],[12,50],[12,51],[12,44],[12,45],[12,46],[12,47],[12,57],[12,58],[12,61],[12,256],[10,16],[10,16],[10,16],[10,16],[10,17],[10,17],[10,17],[10,17],[12,48],[12,49],[12,62],[12,63],[12,30],[12,31],[12,32],[12,33],[12,40],[12,41],[11,22],[11,22],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[12,128],[12,192],[12,26],[12,27],[12,28],[12,29],[11,19],[11,19],[11,20],[11,20],[12,34],[12,35],[12,36],[12,37],[12,38],[12,39],[11,21],[11,21],[12,42],[12,43],[10,0],[10,0],[10,0],[10,0],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12]],Gt=[[-1,-1],[-1,-1],[-1,-1],[-1,-1],[6,9],[6,8],[5,7],[5,7],[4,6],[4,6],[4,6],[4,6],[4,5],[4,5],[4,5],[4,5],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2]];class CCITTFaxDecoder{constructor(e,t={}){if("function"!=typeof e?.next)throw new Error('CCITTFaxDecoder - invalid "source" parameter.');this.source=e;this.eof=!1;this.encoding=t.K||0;this.eoline=t.EndOfLine||!1;this.byteAlign=t.EncodedByteAlign||!1;this.columns=t.Columns||1728;this.rows=t.Rows||0;this.eoblock=t.EndOfBlock??!0;this.black=t.BlackIs1||!1;this.codingLine=new Uint32Array(this.columns+1);this.refLine=new Uint32Array(this.columns+2);this.codingLine[0]=this.columns;this.codingPos=0;this.row=0;this.nextLine2D=this.encoding<0;this.inputBits=0;this.inputBuf=0;this.outputBits=0;this.rowsDone=!1;let i;for(;0===(i=this._lookBits(12));)this._eatBits(1);1===i&&this._eatBits(12);if(this.encoding>0){this.nextLine2D=!this._lookBits(1);this._eatBits(1)}}readNextChar(){if(this.eof)return-1;const e=this.refLine,t=this.codingLine,i=this.columns;let a,s,r,n,g;if(0===this.outputBits){this.rowsDone&&(this.eof=!0);if(this.eof)return-1;this.err=!1;let r,g,o;if(this.nextLine2D){for(n=0;t[n]=64);do{g+=o=this._getWhiteCode()}while(o>=64)}else{do{r+=o=this._getWhiteCode()}while(o>=64);do{g+=o=this._getBlackCode()}while(o>=64)}this._addPixels(t[this.codingPos]+r,s);t[this.codingPos]0?--a:++a;for(;e[a]<=t[this.codingPos]&&e[a]0?--a:++a;for(;e[a]<=t[this.codingPos]&&e[a]0?--a:++a;for(;e[a]<=t[this.codingPos]&&e[a]=64);else do{r+=o=this._getWhiteCode()}while(o>=64);this._addPixels(t[this.codingPos]+r,s);s^=1}}let c=!1;this.byteAlign&&(this.inputBits&=-8);if(this.eoblock||this.row!==this.rows-1){r=this._lookBits(12);if(this.eoline)for(;r!==bt&&1!==r;){this._eatBits(1);r=this._lookBits(12)}else for(;0===r;){this._eatBits(1);r=this._lookBits(12)}if(1===r){this._eatBits(12);c=!0}else r===bt&&(this.eof=!0)}else this.rowsDone=!0;if(!this.eof&&this.encoding>0&&!this.rowsDone){this.nextLine2D=!this._lookBits(1);this._eatBits(1)}if(this.eoblock&&c&&this.byteAlign){r=this._lookBits(12);if(1===r){this._eatBits(12);if(this.encoding>0){this._lookBits(1);this._eatBits(1)}if(this.encoding>=0)for(n=0;n<4;++n){r=this._lookBits(12);1!==r&&info("bad rtc code: "+r);this._eatBits(12);if(this.encoding>0){this._lookBits(1);this._eatBits(1)}}this.eof=!0}}else if(this.err&&this.eoline){for(;;){r=this._lookBits(13);if(r===bt){this.eof=!0;return-1}if(r>>1==1)break;this._eatBits(1)}this._eatBits(12);if(this.encoding>0){this._eatBits(1);this.nextLine2D=!(1&r)}}this.outputBits=t[0]>0?t[this.codingPos=0]:t[this.codingPos=1];this.row++}if(this.outputBits>=8){g=1&this.codingPos?0:255;this.outputBits-=8;if(0===this.outputBits&&t[this.codingPos]r){g<<=r;1&this.codingPos||(g|=255>>8-r);this.outputBits-=r;r=0}else{g<<=this.outputBits;1&this.codingPos||(g|=255>>8-this.outputBits);r-=this.outputBits;this.outputBits=0;if(t[this.codingPos]0){g<<=r;r=0}}}while(r)}this.black&&(g^=255);return g}_addPixels(e,t){const i=this.codingLine;let a=this.codingPos;if(e>i[a]){if(e>this.columns){info("row is wrong length");this.err=!0;e=this.columns}1&a^t&&++a;i[a]=e}this.codingPos=a}_addPixelsNeg(e,t){const i=this.codingLine;let a=this.codingPos;if(e>i[a]){if(e>this.columns){info("row is wrong length");this.err=!0;e=this.columns}1&a^t&&++a;i[a]=e}else if(e0&&e=s){const t=i[e-s];if(t[0]===a){this._eatBits(a);return[!0,t[1],!0]}}}return[!1,0,!1]}_getTwoDimCode(){let e,t=0;if(this.eoblock){t=this._lookBits(7);e=Ft[t];if(e?.[0]>0){this._eatBits(e[0]);return e[1]}}else{const e=this._findTableCode(1,7,Ft);if(e[0]&&e[2])return e[1]}info("Bad two dim code");return bt}_getWhiteCode(){let e,t=0;if(this.eoblock){t=this._lookBits(12);if(t===bt)return 1;e=t>>5?kt[t>>3]:St[t];if(e[0]>0){this._eatBits(e[0]);return e[1]}}else{let e=this._findTableCode(1,9,kt);if(e[0])return e[1];e=this._findTableCode(11,12,St);if(e[0])return e[1]}info("bad white code");this._eatBits(1);return 1}_getBlackCode(){let e,t;if(this.eoblock){e=this._lookBits(13);if(e===bt)return 1;t=e>>7?!(e>>9)&&e>>7?Nt[(e>>1)-64]:Gt[e>>7]:Rt[e];if(t[0]>0){this._eatBits(t[0]);return t[1]}}else{let e=this._findTableCode(2,6,Gt);if(e[0])return e[1];e=this._findTableCode(7,12,Nt,64);if(e[0])return e[1];e=this._findTableCode(10,13,Rt);if(e[0])return e[1]}info("bad black code");this._eatBits(1);return 1}_lookBits(e){let t;for(;this.inputBits>16-e;this.inputBuf=this.inputBuf<<8|t;this.inputBits+=8}return this.inputBuf>>this.inputBits-e&65535>>16-e}_eatBits(e){(this.inputBits-=e)<0&&(this.inputBits=0)}}class CCITTFaxStream extends DecodeStream{constructor(e,t,i){super(t);this.str=e;this.dict=e.dict;i instanceof Dict||(i=Dict.empty);const a={next:()=>e.getByte()};this.ccittFaxDecoder=new CCITTFaxDecoder(a,{K:i.get("K"),EndOfLine:i.get("EndOfLine"),EncodedByteAlign:i.get("EncodedByteAlign"),Columns:i.get("Columns"),Rows:i.get("Rows"),EndOfBlock:i.get("EndOfBlock"),BlackIs1:i.get("BlackIs1")})}readBlock(){for(;!this.eof;){const e=this.ccittFaxDecoder.readNextChar();if(-1===e){this.eof=!0;return}this.ensureBuffer(this.bufferLength+1);this.buffer[this.bufferLength++]=e}}}const Mt=new Int32Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ut=new Int32Array([3,4,5,6,7,8,9,10,65547,65549,65551,65553,131091,131095,131099,131103,196643,196651,196659,196667,262211,262227,262243,262259,327811,327843,327875,327907,258,258,258]),xt=new Int32Array([1,2,3,4,65541,65543,131081,131085,196625,196633,262177,262193,327745,327777,393345,393409,459009,459137,524801,525057,590849,591361,657409,658433,724993,727041,794625,798721,868353,876545]),Lt=[new Int32Array([459008,524368,524304,524568,459024,524400,524336,590016,459016,524384,524320,589984,524288,524416,524352,590048,459012,524376,524312,589968,459028,524408,524344,590032,459020,524392,524328,59e4,524296,524424,524360,590064,459010,524372,524308,524572,459026,524404,524340,590024,459018,524388,524324,589992,524292,524420,524356,590056,459014,524380,524316,589976,459030,524412,524348,590040,459022,524396,524332,590008,524300,524428,524364,590072,459009,524370,524306,524570,459025,524402,524338,590020,459017,524386,524322,589988,524290,524418,524354,590052,459013,524378,524314,589972,459029,524410,524346,590036,459021,524394,524330,590004,524298,524426,524362,590068,459011,524374,524310,524574,459027,524406,524342,590028,459019,524390,524326,589996,524294,524422,524358,590060,459015,524382,524318,589980,459031,524414,524350,590044,459023,524398,524334,590012,524302,524430,524366,590076,459008,524369,524305,524569,459024,524401,524337,590018,459016,524385,524321,589986,524289,524417,524353,590050,459012,524377,524313,589970,459028,524409,524345,590034,459020,524393,524329,590002,524297,524425,524361,590066,459010,524373,524309,524573,459026,524405,524341,590026,459018,524389,524325,589994,524293,524421,524357,590058,459014,524381,524317,589978,459030,524413,524349,590042,459022,524397,524333,590010,524301,524429,524365,590074,459009,524371,524307,524571,459025,524403,524339,590022,459017,524387,524323,589990,524291,524419,524355,590054,459013,524379,524315,589974,459029,524411,524347,590038,459021,524395,524331,590006,524299,524427,524363,590070,459011,524375,524311,524575,459027,524407,524343,590030,459019,524391,524327,589998,524295,524423,524359,590062,459015,524383,524319,589982,459031,524415,524351,590046,459023,524399,524335,590014,524303,524431,524367,590078,459008,524368,524304,524568,459024,524400,524336,590017,459016,524384,524320,589985,524288,524416,524352,590049,459012,524376,524312,589969,459028,524408,524344,590033,459020,524392,524328,590001,524296,524424,524360,590065,459010,524372,524308,524572,459026,524404,524340,590025,459018,524388,524324,589993,524292,524420,524356,590057,459014,524380,524316,589977,459030,524412,524348,590041,459022,524396,524332,590009,524300,524428,524364,590073,459009,524370,524306,524570,459025,524402,524338,590021,459017,524386,524322,589989,524290,524418,524354,590053,459013,524378,524314,589973,459029,524410,524346,590037,459021,524394,524330,590005,524298,524426,524362,590069,459011,524374,524310,524574,459027,524406,524342,590029,459019,524390,524326,589997,524294,524422,524358,590061,459015,524382,524318,589981,459031,524414,524350,590045,459023,524398,524334,590013,524302,524430,524366,590077,459008,524369,524305,524569,459024,524401,524337,590019,459016,524385,524321,589987,524289,524417,524353,590051,459012,524377,524313,589971,459028,524409,524345,590035,459020,524393,524329,590003,524297,524425,524361,590067,459010,524373,524309,524573,459026,524405,524341,590027,459018,524389,524325,589995,524293,524421,524357,590059,459014,524381,524317,589979,459030,524413,524349,590043,459022,524397,524333,590011,524301,524429,524365,590075,459009,524371,524307,524571,459025,524403,524339,590023,459017,524387,524323,589991,524291,524419,524355,590055,459013,524379,524315,589975,459029,524411,524347,590039,459021,524395,524331,590007,524299,524427,524363,590071,459011,524375,524311,524575,459027,524407,524343,590031,459019,524391,524327,589999,524295,524423,524359,590063,459015,524383,524319,589983,459031,524415,524351,590047,459023,524399,524335,590015,524303,524431,524367,590079]),9],Ht=[new Int32Array([327680,327696,327688,327704,327684,327700,327692,327708,327682,327698,327690,327706,327686,327702,327694,0,327681,327697,327689,327705,327685,327701,327693,327709,327683,327699,327691,327707,327687,327703,327695,0]),5];class FlateStream extends DecodeStream{constructor(e,t){super(t);this.str=e;this.dict=e.dict;const i=e.getByte(),a=e.getByte();if(-1===i||-1===a)throw new FormatError(`Invalid header in flate stream: ${i}, ${a}`);if(8!=(15&i))throw new FormatError(`Unknown compression method in flate stream: ${i}, ${a}`);if(((i<<8)+a)%31!=0)throw new FormatError(`Bad FCHECK in flate stream: ${i}, ${a}`);if(32&a)throw new FormatError(`FDICT bit set in flate stream: ${i}, ${a}`);this.codeSize=0;this.codeBuf=0}async getImageData(e,t){const i=await this.asyncGetBytes();return i?.subarray(0,e)||this.getBytes(e)}async asyncGetBytes(){this.str.reset();const e=this.str.getBytes();try{const{readable:t,writable:i}=new DecompressionStream("deflate"),a=i.getWriter();await a.ready;a.write(e).then((async()=>{await a.ready;await a.close()})).catch((()=>{}));const s=[];let r=0;for await(const e of t){s.push(e);r+=e.byteLength}const n=new Uint8Array(r);let g=0;for(const e of s){n.set(e,g);g+=e.byteLength}return n}catch{this.str=new Stream(e,2,e.length,this.str.dict);this.reset();return null}}get isAsync(){return!0}getBits(e){const t=this.str;let i,a=this.codeSize,s=this.codeBuf;for(;a>e;this.codeSize=a-=e;return i}getCode(e){const t=this.str,i=e[0],a=e[1];let s,r=this.codeSize,n=this.codeBuf;for(;r>16,c=65535&g;if(o<1||r>o;this.codeSize=r-o;return c}generateHuffmanTable(e){const t=e.length;let i,a=0;for(i=0;ia&&(a=e[i]);const s=1<>=1}for(i=e;i>=1;if(0===t){let t;if(-1===(t=a.getByte())){this.#m("Bad block header in flate stream");return}let i=t;if(-1===(t=a.getByte())){this.#m("Bad block header in flate stream");return}i|=t<<8;if(-1===(t=a.getByte())){this.#m("Bad block header in flate stream");return}let s=t;if(-1===(t=a.getByte())){this.#m("Bad block header in flate stream");return}s|=t<<8;if(s!==(65535&~i)&&(0!==i||0!==s))throw new FormatError("Bad uncompressed block length in flate stream");this.codeBuf=0;this.codeSize=0;const r=this.bufferLength,n=r+i;e=this.ensureBuffer(n);this.bufferLength=n;if(0===i)-1===a.peekByte()&&(this.eof=!0);else{const t=a.getBytes(i);e.set(t,r);t.length0;)C[g++]=Q}s=this.generateHuffmanTable(C.subarray(0,e));r=this.generateHuffmanTable(C.subarray(e,c))}}e=this.buffer;let n=e?e.length:0,g=this.bufferLength;for(;;){let t=this.getCode(s);if(t<256){if(g+1>=n){e=this.ensureBuffer(g+1);n=e.length}e[g++]=t;continue}if(256===t){this.bufferLength=g;return}t-=257;t=Ut[t];let a=t>>16;a>0&&(a=this.getBits(a));i=(65535&t)+a;t=this.getCode(r);t=xt[t];a=t>>16;a>0&&(a=this.getBits(a));const o=(65535&t)+a;if(g+i>=n){e=this.ensureBuffer(g+i);n=e.length}for(let t=0;t>9&127;this.clow=this.clow<<7&65535;this.ct-=7;this.a=32768}byteIn(){const e=this.data;let t=this.bp;if(255===e[t])if(e[t+1]>143){this.clow+=65280;this.ct=8}else{t++;this.clow+=e[t]<<9;this.ct=7;this.bp=t}else{t++;this.clow+=t65535){this.chigh+=this.clow>>16;this.clow&=65535}}readBit(e,t){let i=e[t]>>1,a=1&e[t];const s=Jt[i],r=s.qe;let n,g=this.a-r;if(this.chigh>15&1;this.clow=this.clow<<1&65535;this.ct--}while(!(32768&g));this.a=g;e[t]=i<<1|a;return n}}class Jbig2Error extends ot{constructor(e){super(e,"Jbig2Error")}}class ContextCache{getContexts(e){return e in this?this[e]:this[e]=new Int8Array(65536)}}class DecodingContext{constructor(e,t,i){this.data=e;this.start=t;this.end=i}get decoder(){return shadow(this,"decoder",new ArithmeticDecoder(this.data,this.start,this.end))}get contextCache(){return shadow(this,"contextCache",new ContextCache)}}function decodeInteger(e,t,i){const a=e.getContexts(t);let s=1;function readBits(e){let t=0;for(let r=0;r>>0}const r=readBits(1),n=readBits(1)?readBits(1)?readBits(1)?readBits(1)?readBits(1)?readBits(32)+4436:readBits(12)+340:readBits(8)+84:readBits(6)+20:readBits(4)+4:readBits(2);let g;0===r?g=n:n>0&&(g=-n);return g>=-2147483648&&g<=pt?g:null}function decodeIAID(e,t,i){const a=e.getContexts("IAID");let s=1;for(let e=0;e=F&&x=S){K=K<<1&d;for(u=0;u=0&&H=0){J=G[L][H];J&&(K|=J<=e?c<<=1:c=c<<1|w[g][o]}for(Q=0;Q=m||o<0||o>=p?c<<=1:c=c<<1|a[g][o]}const E=D.readBit(b,c);t[n]=E}}return w}function decodeTextRegion(e,t,i,a,s,r,n,g,o,c,C,h,l,Q,E,u,d,f,p){if(e&&t)throw new Jbig2Error("refinement with Huffman is not supported");const m=[];let y,w;for(y=0;y1&&(s=e?p.readBits(f):decodeInteger(b,"IAIT",D));const r=n*F+s,S=e?Q.symbolIDTable.decode(p):decodeIAID(b,D,o),k=t&&(e?p.readBit():decodeInteger(b,"IARI",D));let R=g[S],N=R[0].length,G=R.length;if(k){const e=decodeInteger(b,"IARDW",D),t=decodeInteger(b,"IARDH",D);N+=e;G+=t;R=decodeRefinement(N,G,E,R,(e>>1)+decodeInteger(b,"IARDX",D),(t>>1)+decodeInteger(b,"IARDY",D),!1,u,d)}let M=0;c?1&h?M=G-1:a+=G-1:h>1?a+=N-1:M=N-1;const U=r-(1&h?0:G-1),x=a-(2&h?N-1:0);let L,H,J;if(c)for(L=0;L>5&7;const o=[31&n];let c=t+6;if(7===n){g=536870911&readUint32(e,c-1);c+=3;let t=g+7>>3;o[0]=e[c++];for(;--t>0;)o.push(e[c++])}else if(5===n||6===n)throw new Jbig2Error("invalid referred-to flags");i.retainBits=o;let C=4;i.number<=256?C=1:i.number<=65536&&(C=2);const h=[];let l,Q;for(l=0;l>>24&255;r[3]=t.height>>16&255;r[4]=t.height>>8&255;r[5]=255&t.height;for(l=c,Q=e.length;l>2&3;e.huffmanDWSelector=t>>4&3;e.bitmapSizeSelector=t>>6&1;e.aggregationInstancesSelector=t>>7&1;e.bitmapCodingContextUsed=!!(256&t);e.bitmapCodingContextRetained=!!(512&t);e.template=t>>10&3;e.refinementTemplate=t>>12&1;c+=2;if(!e.huffman){o=0===e.template?4:1;n=[];for(g=0;g>2&3;C.stripSize=1<>4&3;C.transposed=!!(64&h);C.combinationOperator=h>>7&3;C.defaultPixelValue=h>>9&1;C.dsOffset=h<<17>>27;C.refinementTemplate=h>>15&1;if(C.huffman){const e=readUint16(a,c);c+=2;C.huffmanFS=3&e;C.huffmanDS=e>>2&3;C.huffmanDT=e>>4&3;C.huffmanRefinementDW=e>>6&3;C.huffmanRefinementDH=e>>8&3;C.huffmanRefinementDX=e>>10&3;C.huffmanRefinementDY=e>>12&3;C.huffmanRefinementSizeSelector=!!(16384&e)}if(C.refinement&&!C.refinementTemplate){n=[];for(g=0;g<2;g++){n.push({x:readInt8(a,c),y:readInt8(a,c+1)});c+=2}C.refinementAt=n}C.numberOfSymbolInstances=readUint32(a,c);c+=4;r=[C,i.referredTo,a,c,s];break;case 16:const l={},Q=a[c++];l.mmr=!!(1&Q);l.template=Q>>1&3;l.patternWidth=a[c++];l.patternHeight=a[c++];l.maxPatternIndex=readUint32(a,c);c+=4;r=[l,i.number,a,c,s];break;case 22:case 23:const E={};E.info=readRegionSegmentInformation(a,c);c+=Ot;const u=a[c++];E.mmr=!!(1&u);E.template=u>>1&3;E.enableSkip=!!(8&u);E.combinationOperator=u>>4&7;E.defaultPixelValue=u>>7&1;E.gridWidth=readUint32(a,c);c+=4;E.gridHeight=readUint32(a,c);c+=4;E.gridOffsetX=4294967295&readUint32(a,c);c+=4;E.gridOffsetY=4294967295&readUint32(a,c);c+=4;E.gridVectorX=readUint16(a,c);c+=2;E.gridVectorY=readUint16(a,c);c+=2;r=[E,i.referredTo,a,c,s];break;case 38:case 39:const d={};d.info=readRegionSegmentInformation(a,c);c+=Ot;const f=a[c++];d.mmr=!!(1&f);d.template=f>>1&3;d.prediction=!!(8&f);if(!d.mmr){o=0===d.template?4:1;n=[];for(g=0;g>2&1;p.combinationOperator=m>>3&3;p.requiresBuffer=!!(32&m);p.combinationOperatorOverride=!!(64&m);r=[p];break;case 49:case 50:case 51:case 62:break;case 53:r=[i.number,a,c,s];break;default:throw new Jbig2Error(`segment type ${i.typeName}(${i.type}) is not implemented`)}const C="on"+i.typeName;C in t&&t[C].apply(t,r)}function processSegments(e,t){for(let i=0,a=e.length;i>3,i=new Uint8ClampedArray(t*e.height);e.defaultPixelValue&&i.fill(255);this.buffer=i}drawBitmap(e,t){const i=this.currentPageInfo,a=e.width,s=e.height,r=i.width+7>>3,n=i.combinationOperatorOverride?e.combinationOperator:i.combinationOperator,g=this.buffer,o=128>>(7&e.x);let c,C,h,l,Q=e.y*r+(e.x>>3);switch(n){case 0:for(c=0;c>=1;if(!h){h=128;l++}}Q+=r}break;case 2:for(c=0;c>=1;if(!h){h=128;l++}}Q+=r}break;default:throw new Jbig2Error(`operator ${n} is not supported`)}}onImmediateGenericRegion(e,t,i,a){const s=e.info,r=new DecodingContext(t,i,a),n=decodeBitmap(e.mmr,s.width,s.height,e.template,e.prediction,null,e.at,r);this.drawBitmap(s,n)}onImmediateLosslessGenericRegion(){this.onImmediateGenericRegion(...arguments)}onSymbolDictionary(e,t,i,a,s,r){let n,g;if(e.huffman){n=function getSymbolDictionaryHuffmanTables(e,t,i){let a,s,r,n,g=0;switch(e.huffmanDHSelector){case 0:case 1:a=getStandardTable(e.huffmanDHSelector+4);break;case 3:a=getCustomHuffmanTable(g,t,i);g++;break;default:throw new Jbig2Error("invalid Huffman DH selector")}switch(e.huffmanDWSelector){case 0:case 1:s=getStandardTable(e.huffmanDWSelector+2);break;case 3:s=getCustomHuffmanTable(g,t,i);g++;break;default:throw new Jbig2Error("invalid Huffman DW selector")}if(e.bitmapSizeSelector){r=getCustomHuffmanTable(g,t,i);g++}else r=getStandardTable(1);n=e.aggregationInstancesSelector?getCustomHuffmanTable(g,t,i):getStandardTable(1);return{tableDeltaHeight:a,tableDeltaWidth:s,tableBitmapSize:r,tableAggregateInstances:n}}(e,i,this.customTables);g=new Reader(a,s,r)}let o=this.symbols;o||(this.symbols=o={});const c=[];for(const e of i){const t=o[e];t&&c.push(...t)}const C=new DecodingContext(a,s,r);o[t]=function decodeSymbolDictionary(e,t,i,a,s,r,n,g,o,c,C,h){if(e&&t)throw new Jbig2Error("symbol refinement with Huffman is not supported");const l=[];let Q=0,E=log2(i.length+a);const u=C.decoder,d=C.contextCache;let f,p;if(e){f=getStandardTable(1);p=[];E=Math.max(E,1)}for(;l.length1)m=decodeTextRegion(e,t,a,Q,0,s,1,i.concat(l),E,0,0,1,0,r,o,c,C,0,h);else{const e=decodeIAID(d,u,E),t=decodeInteger(d,"IARDX",u),s=decodeInteger(d,"IARDY",u);m=decodeRefinement(a,Q,o,e=32){let i,a,n;switch(t){case 32:if(0===e)throw new Jbig2Error("no previous value in symbol ID table");a=s.readBits(2)+3;i=r[e-1].prefixLength;break;case 33:a=s.readBits(3)+3;i=0;break;case 34:a=s.readBits(7)+11;i=0;break;default:throw new Jbig2Error("invalid code length in symbol ID table")}for(n=0;n=0;d--){R=e?decodeMMRBitmap(k,o,c,!0):decodeBitmap(!1,o,c,i,!1,null,F,E);S[d]=R}for(N=0;N=0;f--){M^=S[f][N][G];U|=M<>8;H=h+N*l-G*Q>>8;if(L>=0&&L+w<=a&&H>=0&&H+D<=s)for(d=0;d=s)){Y=u[t];J=x[d];for(f=0;f=0&&e>1&7),o=1+(a>>4&7),c=[];let C,h,l=s;do{C=n.readBits(g);h=n.readBits(o);c.push(new HuffmanLine([l,C,h,0]));l+=1<>t&1;if(t<=0)this.children[i]=new HuffmanTreeNode(e);else{let a=this.children[i];a||(this.children[i]=a=new HuffmanTreeNode(null));a.buildTree(e,t-1)}}decodeNode(e){if(this.isLeaf){if(this.isOOB)return null;const t=e.readBits(this.rangeLength);return this.rangeLow+(this.isLowerRange?-t:t)}const t=this.children[e.readBit()];if(!t)throw new Jbig2Error("invalid Huffman data");return t.decodeNode(e)}}class HuffmanTable{constructor(e,t){t||this.assignPrefixCodes(e);this.rootNode=new HuffmanTreeNode(null);for(let t=0,i=e.length;t0&&this.rootNode.buildTree(i,i.prefixLength-1)}}decode(e){return this.rootNode.decodeNode(e)}assignPrefixCodes(e){const t=e.length;let i=0;for(let a=0;a=this.end)throw new Jbig2Error("end of data while reading bit");this.currentByte=this.data[this.position++];this.shift=7}const e=this.currentByte>>this.shift&1;this.shift--;return e}readBits(e){let t,i=0;for(t=e-1;t>=0;t--)i|=this.readBit()<=this.end?-1:this.data[this.position++]}}function getCustomHuffmanTable(e,t,i){let a=0;for(let s=0,r=t.length;s>i&1;i--}}if(a&&!g){const e=5;for(let t=0;t>2,c=new Uint32Array(e.buffer,t,o);if(FeatureTest.isLittleEndian){for(;n>>24|t<<8|4278190080;i[a+2]=t>>>16|s<<16|4278190080;i[a+3]=s>>>8|4278190080}for(let s=4*n,r=t+g;s>>8|255;i[a+2]=t<<16|s>>>16|255;i[a+3]=s<<8|255}for(let s=4*n,r=t+g;s>3,h=7&a,l=e.length;i=new Uint32Array(i.buffer);let Q=0;for(let a=0;a0&&!e[r-1];)r--;const n=[{children:[],index:0}];let g,o=n[0];for(i=0;i0;)o=n.pop();o.index++;n.push(o);for(;n.length<=i;){n.push(g={children:[],index:0});o.children[o.index]=g.children;o=g}s++}if(i+10){E--;return Q>>E&1}Q=e[t++];if(255===Q){const a=e[t++];if(a){if(220===a&&c){const a=readUint16(e,t+=2);t+=2;if(a>0&&a!==i.scanLines)throw new DNLMarkerError("Found DNL marker (0xFFDC) while parsing scan data",a)}else if(217===a){if(c){const e=p*(8===i.precision?8:0);if(e>0&&Math.round(i.scanLines/e)>=5)throw new DNLMarkerError("Found EOI marker (0xFFD9) while parsing scan data, possibly caused by incorrect `scanLines` parameter",e)}throw new EOIMarkerError("Found EOI marker (0xFFD9) while parsing scan data")}throw new JpegError(`unexpected marker ${(Q<<8|a).toString(16)}`)}}E=7;return Q>>>7}function decodeHuffman(e){let t=e;for(;;){t=t[readBit()];switch(typeof t){case"number":return t;case"object":continue}throw new JpegError("invalid huffman sequence")}}function receive(e){let t=0;for(;e>0;){t=t<<1|readBit();e--}return t}function receiveAndExtend(e){if(1===e)return 1===readBit()?1:-1;const t=receive(e);return t>=1<0){u--;return}let i=r;const a=n;for(;i<=a;){const a=decodeHuffman(e.huffmanTableAC),s=15&a,r=a>>4;if(0===s){if(r<15){u=receive(r)+(1<>4;if(0===s)if(c<15){u=receive(c)+(1<>4;if(0===a){if(r<15)break;s+=16;continue}s+=r;const n=Wt[s];e.blockData[t+n]=receiveAndExtend(a);s++}};let k,R=0;const N=1===m?a[0].blocksPerLine*a[0].blocksPerColumn:C*i.mcusPerColumn;let G,M;for(;R<=N;){const i=s?Math.min(N-R,s):N;if(i>0){for(w=0;w0?"unexpected":"excessive"} MCU data, current marker is: ${k.invalid}`);t=k.offset}if(!(k.marker>=65488&&k.marker<=65495))break;t+=2}return t-l}function quantizeAndInverse(e,t,i){const a=e.quantizationTable,s=e.blockData;let r,n,g,o,c,C,h,l,Q,E,u,d,f,p,m,y,w;if(!a)throw new JpegError("missing required Quantization Table.");for(let e=0;e<64;e+=8){Q=s[t+e];E=s[t+e+1];u=s[t+e+2];d=s[t+e+3];f=s[t+e+4];p=s[t+e+5];m=s[t+e+6];y=s[t+e+7];Q*=a[e];if(E|u|d|f|p|m|y){E*=a[e+1];u*=a[e+2];d*=a[e+3];f*=a[e+4];p*=a[e+5];m*=a[e+6];y*=a[e+7];r=$t*Q+128>>8;n=$t*f+128>>8;g=u;o=m;c=Ai*(E-y)+128>>8;l=Ai*(E+y)+128>>8;C=d<<4;h=p<<4;r=r+n+1>>1;n=r-n;w=g*_t+o*zt+128>>8;g=g*zt-o*_t+128>>8;o=w;c=c+h+1>>1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;s[t+e+56]=y}else{w=$t*Q+8192>>14;w=w<-2040?0:w>=2024?255:w+2056>>4;s[t+e]=w;s[t+e+8]=w;s[t+e+16]=w;s[t+e+24]=w;s[t+e+32]=w;s[t+e+40]=w;s[t+e+48]=w;s[t+e+56]=w}}}function buildComponentData(e,t){const i=t.blocksPerLine,a=t.blocksPerColumn,s=new Int16Array(64);for(let e=0;e=a)return null;const r=readUint16(e,t);if(r>=65472&&r<=65534)return{invalid:null,marker:r,offset:t};let n=readUint16(e,s);for(;!(n>=65472&&n<=65534);){if(++s>=a)return null;n=readUint16(e,s)}return{invalid:r.toString(16),marker:n,offset:s}}function prepareComponents(e){const t=Math.ceil(e.samplesPerLine/8/e.maxH),i=Math.ceil(e.scanLines/8/e.maxV);for(const a of e.components){const s=Math.ceil(Math.ceil(e.samplesPerLine/8)*a.h/e.maxH),r=Math.ceil(Math.ceil(e.scanLines/8)*a.v/e.maxV),n=t*a.h,g=64*(i*a.v)*(n+1);a.blockData=new Int16Array(g);a.blocksPerLine=s;a.blocksPerColumn=r}e.mcusPerLine=t;e.mcusPerColumn=i}function readDataBlock(e,t){const i=readUint16(e,t);let a=(t+=2)+i-2;const s=findNextFileMarker(e,a,t);if(s?.invalid){warn("readDataBlock - incorrect length, current marker is: "+s.invalid);a=s.offset}const r=e.subarray(t,a);return{appData:r,newOffset:t+=r.length}}function skipData(e,t){const i=readUint16(e,t),a=(t+=2)+i-2,s=findNextFileMarker(e,a,t);return s?.invalid?s.offset:a}class JpegImage{constructor({decodeTransform:e=null,colorTransform:t=-1}={}){this._decodeTransform=e;this._colorTransform=t}static canUseImageDecoder(e,t=-1){let i=0,a=null,s=readUint16(e,i);i+=2;if(65496!==s)throw new JpegError("SOI not found");s=readUint16(e,i);i+=2;A:for(;65497!==s;){switch(s){case 65472:case 65473:case 65474:a=e[i+7];break A;case 65535:255!==e[i]&&i--}i=skipData(e,i);s=readUint16(e,i);i+=2}return 4!==a&&(3!==a||0!==t)}parse(e,{dnlScanLines:t=null}={}){let i,a,s=0,r=null,n=null,g=0;const o=[],c=[],C=[];let h=readUint16(e,s);s+=2;if(65496!==h)throw new JpegError("SOI not found");h=readUint16(e,s);s+=2;A:for(;65497!==h;){let l,Q,E;switch(h){case 65504:case 65505:case 65506:case 65507:case 65508:case 65509:case 65510:case 65511:case 65512:case 65513:case 65514:case 65515:case 65516:case 65517:case 65518:case 65519:case 65534:const{appData:u,newOffset:d}=readDataBlock(e,s);s=d;65504===h&&74===u[0]&&70===u[1]&&73===u[2]&&70===u[3]&&0===u[4]&&(r={version:{major:u[5],minor:u[6]},densityUnits:u[7],xDensity:u[8]<<8|u[9],yDensity:u[10]<<8|u[11],thumbWidth:u[12],thumbHeight:u[13],thumbData:u.subarray(14,14+3*u[12]*u[13])});65518===h&&65===u[0]&&100===u[1]&&111===u[2]&&98===u[3]&&101===u[4]&&(n={version:u[5]<<8|u[6],flags0:u[7]<<8|u[8],flags1:u[9]<<8|u[10],transformCode:u[11]});break;case 65499:const f=readUint16(e,s);s+=2;const p=f+s-2;let m;for(;s>4){if(t>>4!=1)throw new JpegError("DQT - invalid table spec");for(Q=0;Q<64;Q++){m=Wt[Q];i[m]=readUint16(e,s);s+=2}}else for(Q=0;Q<64;Q++){m=Wt[Q];i[m]=e[s++]}o[15&t]=i}break;case 65472:case 65473:case 65474:if(i)throw new JpegError("Only single frame JPEGs supported");s+=2;i={};i.extended=65473===h;i.progressive=65474===h;i.precision=e[s++];const y=readUint16(e,s);s+=2;i.scanLines=t||y;i.samplesPerLine=readUint16(e,s);s+=2;i.components=[];i.componentIds={};const w=e[s++];let D=0,b=0;for(l=0;l>4,r=15&e[s+1];D>4?c:C)[15&t]=buildHuffmanTable(i,r)}break;case 65501:s+=2;a=readUint16(e,s);s+=2;break;case 65498:const S=1==++g&&!t;s+=2;const k=e[s++],R=[];for(l=0;l>4];r.huffmanTableAC=c[15&n];R.push(r)}const N=e[s++],G=e[s++],M=e[s++];try{s+=decodeScan(e,s,i,R,a,N,G,M>>4,15&M,S)}catch(t){if(t instanceof DNLMarkerError){warn(`${t.message} -- attempting to re-parse the JPEG image.`);return this.parse(e,{dnlScanLines:t.scanLines})}if(t instanceof EOIMarkerError){warn(`${t.message} -- ignoring the rest of the image data.`);break A}throw t}break;case 65500:s+=4;break;case 65535:255!==e[s]&&s--;break;default:const U=findNextFileMarker(e,s-2,s-3);if(U?.invalid){warn("JpegImage.parse - unexpected data, current marker is: "+U.invalid);s=U.offset;break}if(!U||s>=e.length-1){warn("JpegImage.parse - reached the end of the image data without finding an EOI marker (0xFFD9).");break A}throw new JpegError("JpegImage.parse - unknown marker: "+h.toString(16))}h=readUint16(e,s);s+=2}if(!i)throw new JpegError("JpegImage.parse - no frame data found.");this.width=i.samplesPerLine;this.height=i.scanLines;this.jfif=r;this.adobe=n;this.components=[];for(const e of i.components){const t=o[e.quantizationId];t&&(e.quantizationTable=t);this.components.push({index:e.index,output:buildComponentData(0,e),scaleX:e.h/i.maxH,scaleY:e.v/i.maxV,blocksPerLine:e.blocksPerLine,blocksPerColumn:e.blocksPerColumn})}this.numComponents=this.components.length}_getLinearizedBlockData(e,t,i=!1){const a=this.width/e,s=this.height/t;let r,n,g,o,c,C,h,l,Q,E,u,d=0;const f=this.components.length,p=e*t*f,m=new Uint8ClampedArray(p),y=new Uint32Array(e),w=4294967288;let D;for(h=0;h>8)+b[Q+1];return m}get _isColorConversionNeeded(){return this.adobe?!!this.adobe.transformCode:3===this.numComponents?0!==this._colorTransform&&(82!==this.components[0].index||71!==this.components[1].index||66!==this.components[2].index):1===this._colorTransform}_convertYccToRgb(e){let t,i,a;for(let s=0,r=e.length;s4)throw new JpegError("Unsupported color mode");const r=this._getLinearizedBlockData(e,t,s);if(1===this.numComponents&&(i||a)){const e=r.length*(i?4:3),t=new Uint8ClampedArray(e);let a=0;if(i)!function grayToRGBA(e,t){if(FeatureTest.isLittleEndian)for(let i=0,a=e.length;i0&&(e=e.subarray(t));break}return e}decodeImage(e){if(this.eof)return this.buffer;e=this.#w(e||this.bytes);const t=new JpegImage(this.jpegOptions);t.parse(e);const i=t.getData({width:this.drawWidth,height:this.drawHeight,forceRGBA:this.forceRGBA,forceRGB:this.forceRGB,isSourcePDF:!0});this.buffer=i;this.bufferLength=i.length;this.eof=!0;return this.buffer}get canAsyncDecodeImageFromBuffer(){return this.stream.isAsync}async getTransferableImage(){if(!await JpegStream.canUseImageDecoder)return null;const e=this.jpegOptions;if(e.decodeTransform)return null;let t;try{const i=this.canAsyncDecodeImageFromBuffer&&await this.stream.asyncGetBytes()||this.bytes;if(!i)return null;const a=this.#w(i);if(!JpegImage.canUseImageDecoder(a,e.colorTransform))return null;t=new ImageDecoder({data:a,type:"image/jpeg",preferAnimation:!1});return(await t.decode()).image}catch(e){warn(`getTransferableImage - failed: "${e}".`);return null}finally{t?.close()}}}var ei,ti=(ei="undefined"!=typeof document?document.currentScript?.src:void 0,function(e={}){var t,i,a=e;new Promise(((e,a)=>{t=e;i=a}));a.decode=function(e,{numComponents:t=4,isIndexedColormap:i=!1,smaskInData:s=!1}){const r=e.length,n=a._malloc(r);a.HEAPU8.set(e,n);const g=a._jp2_decode(n,r,t>0?t:0,!!i,!!s);a._free(n);if(g){const{errorMessages:e}=a;if(e){delete a.errorMessages;return e}return"Unknown error"}const{imageData:o}=a;a.imageData=null;return o};var s=Object.assign({},a),r="./this.program",quit_=(e,t)=>{throw t},n="";"undefined"!=typeof document&&document.currentScript&&(n=document.currentScript.src);ei&&(n=ei);n=n.startsWith("blob:")?"":n.substr(0,n.replace(/[?#].*/,"").lastIndexOf("/")+1);var g=a.print||console.log.bind(console),o=a.printErr||console.error.bind(console);Object.assign(a,s);s=null;a.arguments&&a.arguments;a.thisProgram&&(r=a.thisProgram);var c,C=a.wasmBinary;function tryParseAsDataURI(e){if(isDataURI(e))return function intArrayFromBase64(e){for(var t=atob(e),i=new Uint8Array(t.length),a=0;ae.startsWith(b);function instantiateSync(e,t){var i,a=function getBinarySync(e){if(e==d&&C)return new Uint8Array(C);var t=tryParseAsDataURI(e);if(t)return t;throw'sync fetching of the wasm failed: you can preload it to Module["wasmBinary"] manually, or emcc.py will do that for you when generating HTML (but not JS)'}(e);i=new WebAssembly.Module(a);return[new WebAssembly.Instance(i,t),i]}class ExitStatus{name="ExitStatus";constructor(e){this.message=`Program terminated with exit(${e})`;this.status=e}}var F,callRuntimeCallbacks=e=>{for(;e.length>0;)e.shift()(a)},S=a.noExitRuntime||!0,k=0,R={},handleException=e=>{if(e instanceof ExitStatus||"unwind"==e)return h;quit_(0,e)},keepRuntimeAlive=()=>S||k>0,_proc_exit=e=>{h=e;if(!keepRuntimeAlive()){a.onExit?.(e);u=!0}quit_(0,new ExitStatus(e))},_exit=(e,t)=>{h=e;_proc_exit(e)},callUserCallback=e=>{if(!u)try{e();(()=>{if(!keepRuntimeAlive())try{_exit(h)}catch(e){handleException(e)}})()}catch(e){handleException(e)}},growMemory=e=>{var t=(e-c.buffer.byteLength+65535)/65536|0;try{c.grow(t);updateMemoryViews();return 1}catch(e){}},N={},getEnvStrings=()=>{if(!getEnvStrings.strings){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:r||"./this.program"};for(var t in N)void 0===N[t]?delete e[t]:e[t]=N[t];var i=[];for(var t in e)i.push(`${t}=${e[t]}`);getEnvStrings.strings=i}return getEnvStrings.strings},G=[null,[],[]],M="undefined"!=typeof TextDecoder?new TextDecoder:void 0,UTF8ArrayToString=(e,t=0,i=NaN)=>{for(var a=t+i,s=t;e[s]&&!(s>=a);)++s;if(s-t>16&&e.buffer&&M)return M.decode(e.subarray(t,s));for(var r="";t>10,56320|1023&c)}}else r+=String.fromCharCode((31&n)<<6|g)}else r+=String.fromCharCode(n)}return r},printChar=(e,t)=>{var i=G[e];if(0===t||10===t){(1===e?g:o)(UTF8ArrayToString(i));i.length=0}else i.push(t)},UTF8ToString=(e,t)=>e?UTF8ArrayToString(Q,e,t):"",U={m:()=>function abort(e){a.onAbort?.(e);o(e="Aborted("+e+")");u=!0;e+=". Build with -sASSERTIONS for more info.";var t=new WebAssembly.RuntimeError(e);i(t);throw t}(""),c:(e,t,i)=>Q.copyWithin(e,t,t+i),l:()=>{S=!1;k=0},n:(e,t)=>{if(R[e]){clearTimeout(R[e].id);delete R[e]}if(!t)return 0;var i=setTimeout((()=>{delete R[e];callUserCallback((()=>L(e,performance.now())))}),t);R[e]={id:i,timeout_ms:t};return 0},g:function _copy_pixels_1(e,t){e>>=2;const i=a.imageData=new Uint8ClampedArray(t),s=a.HEAP32.subarray(e,e+t);i.set(s)},f:function _copy_pixels_3(e,t,i,s){e>>=2;t>>=2;i>>=2;const r=a.imageData=new Uint8ClampedArray(3*s),n=a.HEAP32.subarray(e,e+s),g=a.HEAP32.subarray(t,t+s),o=a.HEAP32.subarray(i,i+s);for(let e=0;e>=2;t>>=2;i>>=2;s>>=2;const n=a.imageData=new Uint8ClampedArray(4*r),g=a.HEAP32.subarray(e,e+r),o=a.HEAP32.subarray(t,t+r),c=a.HEAP32.subarray(i,i+r),C=a.HEAP32.subarray(s,s+r);for(let e=0;e{var t,i,a=Q.length,s=2147483648;if((e>>>=0)>s)return!1;for(var r=1;r<=4;r*=2){var n=a*(1+.2/r);n=Math.min(n,e+100663296);var g=Math.min(s,(t=Math.max(e,n),i=65536,Math.ceil(t/i)*i));if(growMemory(g))return!0}return!1},p:(e,t)=>{var i=0;getEnvStrings().forEach(((a,s)=>{var r=t+i;E[e+4*s>>2]=r;((e,t)=>{for(var i=0;i{var i=getEnvStrings();E[e>>2]=i.length;var a=0;i.forEach((e=>a+=e.length+1));E[t>>2]=a;return 0},r:e=>52,j:function _fd_seek(e,t,i,a,s){return 70},b:(e,t,i,a)=>{for(var s=0,r=0;r>2],g=E[t+4>>2];t+=8;for(var o=0;o>2]=s;return 0},s:function _gray_to_rgba(e,t){e>>=2;const i=a.imageData=new Uint8ClampedArray(4*t),s=a.HEAP32.subarray(e,e+t);for(let e=0;e>=2;t>>=2;const s=a.imageData=new Uint8ClampedArray(4*i),r=a.HEAP32.subarray(e,e+i),n=a.HEAP32.subarray(t,t+i);for(let e=0;e>=2;t>>=2;i>>=2;const r=a.imageData=new Uint8ClampedArray(4*s),n=a.HEAP32.subarray(e,e+s),g=a.HEAP32.subarray(t,t+s),o=a.HEAP32.subarray(i,i+s);for(let e=0;e0)){!function preRun(){if(a.preRun){"function"==typeof a.preRun&&(a.preRun=[a.preRun]);for(;a.preRun.length;)e=a.preRun.shift(),f.unshift(e)}var e;callRuntimeCallbacks(f)}();if(!(y>0))if(a.setStatus){a.setStatus("Running...");setTimeout((()=>{setTimeout((()=>a.setStatus("")),1);doRun()}),1)}else doRun()}function doRun(){if(!F){F=!0;a.calledRun=!0;if(!u){!function initRuntime(){callRuntimeCallbacks(p)}();t(a);a.onRuntimeInitialized?.();!function postRun(){if(a.postRun){"function"==typeof a.postRun&&(a.postRun=[a.postRun]);for(;a.postRun.length;)e=a.postRun.shift(),m.unshift(e)}var e;callRuntimeCallbacks(m)}()}}}}if(a.preInit){"function"==typeof a.preInit&&(a.preInit=[a.preInit]);for(;a.preInit.length>0;)a.preInit.pop()()}run();return a});const ii=ti;class JpxError extends ot{constructor(e){super(e,"JpxError")}}class JpxImage{static#D=null;static decode(e,t){t||={};this.#D||=ii({warn});const i=this.#D.decode(e,t);if("string"==typeof i)throw new JpxError(i);return i}static cleanup(){this.#D=null}static parseImageProperties(e){let t=e.getByte();for(;t>=0;){const i=t;t=e.getByte();if(65361===(i<<8|t)){e.skip(4);const t=e.getInt32()>>>0,i=e.getInt32()>>>0,a=e.getInt32()>>>0,s=e.getInt32()>>>0;e.skip(16);return{width:t-a,height:i-s,bitsPerComponent:8,componentsCount:e.getUint16()}}}throw new JpxError("No size marker found in JPX stream")}}class JpxStream extends DecodeStream{constructor(e,t,i){super(t);this.stream=e;this.dict=e.dict;this.maybeLength=t;this.params=i}get bytes(){return shadow(this,"bytes",this.stream.getBytes(this.maybeLength))}ensureBuffer(e){}readBlock(e){this.decodeImage(null,e)}decodeImage(e,t){if(this.eof)return this.buffer;e||=this.bytes;this.buffer=JpxImage.decode(e,t);this.bufferLength=this.buffer.length;this.eof=!0;return this.buffer}get canAsyncDecodeImageFromBuffer(){return this.stream.isAsync}}class LZWStream extends DecodeStream{constructor(e,t,i){super(t);this.str=e;this.dict=e.dict;this.cachedData=0;this.bitsCached=0;const a=4096,s={earlyChange:i,codeLength:9,nextCode:258,dictionaryValues:new Uint8Array(a),dictionaryLengths:new Uint16Array(a),dictionaryPrevCodes:new Uint16Array(a),currentSequence:new Uint8Array(a),currentSequenceLength:0};for(let e=0;e<256;++e){s.dictionaryValues[e]=e;s.dictionaryLengths[e]=1}this.lzwState=s}readBits(e){let t=this.bitsCached,i=this.cachedData;for(;t>>t&(1<0;if(e<256){l[0]=e;Q=1}else{if(!(e>=258)){if(256===e){C=9;n=258;Q=0;continue}this.eof=!0;delete this.lzwState;break}if(e=0;t--){l[t]=g[i];i=c[i]}}else l[Q++]=l[0]}if(s){c[n]=h;o[n]=o[h]+1;g[n]=l[0];n++;C=n+r&n+r-1?C:0|Math.min(Math.log(n+r)/.6931471805599453+1,12)}h=e;E+=Q;if(a15))throw new FormatError(`Unsupported predictor: ${a}`);this.readBlock=2===a?this.readBlockTiff:this.readBlockPng;this.str=e;this.dict=e.dict;const s=this.colors=i.get("Colors")||1,r=this.bits=i.get("BPC","BitsPerComponent")||8,n=this.columns=i.get("Columns")||1;this.pixBytes=s*r+7>>3;this.rowBytes=n*s*r+7>>3;return this}readBlockTiff(){const e=this.rowBytes,t=this.bufferLength,i=this.ensureBuffer(t+e),a=this.bits,s=this.colors,r=this.str.getBytes(e);this.eof=!r.length;if(this.eof)return;let n,g=0,o=0,c=0,C=0,h=t;if(1===a&&1===s)for(n=0;n>1;e^=e>>2;e^=e>>4;g=(1&e)<<7;i[h++]=e}else if(8===a){for(n=0;n>8&255;i[h++]=255&e}}else{const e=new Uint8Array(s+1),h=(1<>c-a)&h;c-=a;o=o<=8){i[Q++]=o>>C-8&255;C-=8}}C>0&&(i[Q++]=(o<<8-C)+(g&(1<<8-C)-1))}this.bufferLength+=e}readBlockPng(){const e=this.rowBytes,t=this.pixBytes,i=this.str.getByte(),a=this.str.getBytes(e);this.eof=!a.length;if(this.eof)return;const s=this.bufferLength,r=this.ensureBuffer(s+e);let n=r.subarray(s-e,s);0===n.length&&(n=new Uint8Array(e));let g,o,c,C=s;switch(i){case 0:for(g=0;g>1)+a[g];for(;g>1)+a[g]&255;C++}break;case 4:for(g=0;g0){const e=this.str.getBytes(a);t.set(e,i);i+=a}}else{a=257-a;const s=e[1];t=this.ensureBuffer(i+a+1);for(let e=0;e>")&&this.buf1!==Bt;){if(!(this.buf1 instanceof Name)){info("Malformed dictionary: key must be a name object");this.shift();continue}const t=this.buf1.name;this.shift();if(this.buf1===Bt)break;a.set(t,this.getObj(e))}if(this.buf1===Bt){if(this.recoveryMode)return a;throw new ParserEOFException("End of file inside dictionary.")}if(isCmd(this.buf2,"stream"))return this.allowStreams?this.makeStream(a,e):a;this.shift();return a;default:return t}if(Number.isInteger(t)){if(Number.isInteger(this.buf1)&&isCmd(this.buf2,"R")){const e=Ref.get(t,this.buf1);this.shift();this.shift();return e}return t}return"string"==typeof t&&e?e.decryptString(t):t}findDefaultInlineStreamEnd(e){const{knownCommands:t}=this.lexer,i=e.pos;let a,s,r=0;for(;-1!==(a=e.getByte());)if(0===r)r=69===a?1:0;else if(1===r)r=73===a?2:0;else if(32===a||10===a||13===a){s=e.pos;const i=e.peekBytes(15),n=i.length;if(0===n)break;for(let e=0;e127))){r=0;break}}if(2!==r)continue;if(!t){warn("findDefaultInlineStreamEnd - `lexer.knownCommands` is undefined.");continue}const g=new Lexer(new Stream(i.slice()),t);g._hexStringWarn=()=>{};let o=0;for(;;){const e=g.getObj();if(e===Bt){r=0;break}if(e instanceof Cmd){const i=t[e.cmd];if(!i){r=0;break}if(i.variableArgs?o<=i.numArgs:o===i.numArgs)break;o=0}else o++}if(2===r)break}else r=0;if(-1===a){warn("findDefaultInlineStreamEnd: Reached the end of the stream without finding a valid EI marker");if(s){warn('... trying to recover by using the last "EI" occurrence.');e.skip(-(e.pos-s))}}let n=4;e.skip(-n);a=e.peekByte();e.skip(n);isWhiteSpace(a)||n--;return e.pos-n-i}findDCTDecodeInlineStreamEnd(e){const t=e.pos;let i,a,s=!1;for(;-1!==(i=e.getByte());)if(255===i){switch(e.getByte()){case 0:break;case 255:e.skip(-1);break;case 217:s=!0;break;case 192:case 193:case 194:case 195:case 197:case 198:case 199:case 201:case 202:case 203:case 205:case 206:case 207:case 196:case 204:case 218:case 219:case 220:case 221:case 222:case 223:case 224:case 225:case 226:case 227:case 228:case 229:case 230:case 231:case 232:case 233:case 234:case 235:case 236:case 237:case 238:case 239:case 254:a=e.getUint16();a>2?e.skip(a-2):e.skip(-2)}if(s)break}const r=e.pos-t;if(-1===i){warn("Inline DCTDecode image stream: EOI marker not found, searching for /EI/ instead.");e.skip(-r);return this.findDefaultInlineStreamEnd(e)}this.inlineStreamSkipEI(e);return r}findASCII85DecodeInlineStreamEnd(e){const t=e.pos;let i;for(;-1!==(i=e.getByte());)if(126===i){const t=e.pos;i=e.peekByte();for(;isWhiteSpace(i);){e.skip();i=e.peekByte()}if(62===i){e.skip();break}if(e.pos>t){const t=e.peekBytes(2);if(69===t[0]&&73===t[1])break}}const a=e.pos-t;if(-1===i){warn("Inline ASCII85Decode image stream: EOD marker not found, searching for /EI/ instead.");e.skip(-a);return this.findDefaultInlineStreamEnd(e)}this.inlineStreamSkipEI(e);return a}findASCIIHexDecodeInlineStreamEnd(e){const t=e.pos;let i;for(;-1!==(i=e.getByte())&&62!==i;);const a=e.pos-t;if(-1===i){warn("Inline ASCIIHexDecode image stream: EOD marker not found, searching for /EI/ instead.");e.skip(-a);return this.findDefaultInlineStreamEnd(e)}this.inlineStreamSkipEI(e);return a}inlineStreamSkipEI(e){let t,i=0;for(;-1!==(t=e.getByte());)if(0===i)i=69===t?1:0;else if(1===i)i=73===t?2:0;else if(2===i)break}makeInlineImage(e){const t=this.lexer,i=t.stream,a=Object.create(null);let s;for(;!isCmd(this.buf1,"ID")&&this.buf1!==Bt;){if(!(this.buf1 instanceof Name))throw new FormatError("Dictionary key must be a name object");const t=this.buf1.name;this.shift();if(this.buf1===Bt)break;a[t]=this.getObj(e)}-1!==t.beginInlineImagePos&&(s=i.pos-t.beginInlineImagePos);const r=this.xref.fetchIfRef(a.F||a.Filter);let n;if(r instanceof Name)n=r.name;else if(Array.isArray(r)){const e=this.xref.fetchIfRef(r[0]);e instanceof Name&&(n=e.name)}const g=i.pos;let o,c;switch(n){case"DCT":case"DCTDecode":o=this.findDCTDecodeInlineStreamEnd(i);break;case"A85":case"ASCII85Decode":o=this.findASCII85DecodeInlineStreamEnd(i);break;case"AHx":case"ASCIIHexDecode":o=this.findASCIIHexDecodeInlineStreamEnd(i);break;default:o=this.findDefaultInlineStreamEnd(i)}if(o<1e3&&s>0){const e=i.pos;i.pos=t.beginInlineImagePos;c=function getInlineImageCacheKey(e){const t=[],i=e.length;let a=0;for(;a=a){let a=!1;for(const e of s){const t=e.length;let s=0;for(;s=r){a=!0;break}if(s>=t){if(isWhiteSpace(n[o+g+s])){info(`Found "${bytesToString([...i,...e])}" when searching for endstream command.`);a=!0}break}}if(a){t.pos+=o;return t.pos-e}}o++}t.pos+=g}return-1}makeStream(e,t){const i=this.lexer;let a=i.stream;i.skipToNextLine();const s=a.pos-1;let r=e.get("Length");if(!Number.isInteger(r)){info(`Bad length "${r&&r.toString()}" in stream.`);r=0}a.pos=s+r;i.nextChar();if(this.tryShift()&&isCmd(this.buf2,"endstream"))this.shift();else{r=this.#b(s);if(r<0)throw new FormatError("Missing endstream command.");i.nextChar();this.shift();this.shift()}this.shift();a=a.makeSubStream(s,r,e);t&&(a=t.createStream(a,r));a=this.filter(a,e,r);a.dict=e;return a}filter(e,t,i){let a=t.get("F","Filter"),s=t.get("DP","DecodeParms");if(a instanceof Name){Array.isArray(s)&&warn("/DecodeParms should not be an Array, when /Filter is a Name.");return this.makeFilter(e,a.name,i,s)}let r=i;if(Array.isArray(a)){const t=a,i=s;for(let n=0,g=t.length;n=48&&e<=57?15&e:e>=65&&e<=70||e>=97&&e<=102?9+(15&e):-1}class Lexer{constructor(e,t=null){this.stream=e;this.nextChar();this.strBuf=[];this.knownCommands=t;this._hexStringNumWarn=0;this.beginInlineImagePos=-1}nextChar(){return this.currentChar=this.stream.getByte()}peekChar(){return this.stream.peekByte()}getNumber(){let e=this.currentChar,t=!1,i=0,a=1;if(45===e){a=-1;e=this.nextChar();45===e&&(e=this.nextChar())}else 43===e&&(e=this.nextChar());if(10===e||13===e)do{e=this.nextChar()}while(10===e||13===e);if(46===e){i=10;e=this.nextChar()}if(e<48||e>57){const t=`Invalid number: ${String.fromCharCode(e)} (charCode ${e})`;if(isWhiteSpace(e)||-1===e){info(`Lexer.getNumber - "${t}".`);return 0}throw new FormatError(t)}let s=e-48,r=0,n=1;for(;(e=this.nextChar())>=0;)if(e>=48&&e<=57){const a=e-48;if(t)r=10*r+a;else{0!==i&&(i*=10);s=10*s+a}}else if(46===e){if(0!==i)break;i=1}else if(45===e)warn("Badly formatted number: minus sign in the middle");else{if(69!==e&&101!==e)break;e=this.peekChar();if(43===e||45===e){n=45===e?-1:1;this.nextChar()}else if(e<48||e>57)break;t=!0}0!==i&&(s/=i);t&&(s*=10**(n*r));return a*s}getString(){let e=1,t=!1;const i=this.strBuf;i.length=0;let a=this.nextChar();for(;;){let s=!1;switch(0|a){case-1:warn("Unterminated string");t=!0;break;case 40:++e;i.push("(");break;case 41:if(0==--e){this.nextChar();t=!0}else i.push(")");break;case 92:a=this.nextChar();switch(a){case-1:warn("Unterminated string");t=!0;break;case 110:i.push("\n");break;case 114:i.push("\r");break;case 116:i.push("\t");break;case 98:i.push("\b");break;case 102:i.push("\f");break;case 92:case 40:case 41:i.push(String.fromCharCode(a));break;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:let e=15&a;a=this.nextChar();s=!0;if(a>=48&&a<=55){e=(e<<3)+(15&a);a=this.nextChar();if(a>=48&&a<=55){s=!1;e=(e<<3)+(15&a)}}i.push(String.fromCharCode(e));break;case 13:10===this.peekChar()&&this.nextChar();break;case 10:break;default:i.push(String.fromCharCode(a))}break;default:i.push(String.fromCharCode(a))}if(t)break;s||(a=this.nextChar())}return i.join("")}getName(){let e,t;const i=this.strBuf;i.length=0;for(;(e=this.nextChar())>=0&&!ai[e];)if(35===e){e=this.nextChar();if(ai[e]){warn("Lexer_getName: NUMBER SIGN (#) should be followed by a hexadecimal number.");i.push("#");break}const a=toHexDigit(e);if(-1!==a){t=e;e=this.nextChar();const s=toHexDigit(e);if(-1===s){warn(`Lexer_getName: Illegal digit (${String.fromCharCode(e)}) in hexadecimal number.`);i.push("#",String.fromCharCode(t));if(ai[e])break;i.push(String.fromCharCode(e));continue}i.push(String.fromCharCode(a<<4|s))}else i.push("#",String.fromCharCode(e))}else i.push(String.fromCharCode(e));i.length>127&&warn(`Name token is longer than allowed by the spec: ${i.length}`);return Name.get(i.join(""))}_hexStringWarn(e){5!=this._hexStringNumWarn++?this._hexStringNumWarn>5||warn(`getHexString - ignoring invalid character: ${e}`):warn("getHexString - ignoring additional invalid characters.")}getHexString(){const e=this.strBuf;e.length=0;let t=this.currentChar,i=-1,a=-1;this._hexStringNumWarn=0;for(;;){if(t<0){warn("Unterminated hex string");break}if(62===t){this.nextChar();break}if(1!==ai[t]){a=toHexDigit(t);if(-1===a)this._hexStringWarn(t);else if(-1===i)i=a;else{e.push(String.fromCharCode(i<<4|a));i=-1}t=this.nextChar()}else t=this.nextChar()}-1!==i&&e.push(String.fromCharCode(i<<4));return e.join("")}getObj(){let e=!1,t=this.currentChar;for(;;){if(t<0)return Bt;if(e)10!==t&&13!==t||(e=!1);else if(37===t)e=!0;else if(1!==ai[t])break;t=this.nextChar()}switch(0|t){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 43:case 45:case 46:return this.getNumber();case 40:return this.getString();case 47:return this.getName();case 91:this.nextChar();return Cmd.get("[");case 93:this.nextChar();return Cmd.get("]");case 60:t=this.nextChar();if(60===t){this.nextChar();return Cmd.get("<<")}return this.getHexString();case 62:t=this.nextChar();if(62===t){this.nextChar();return Cmd.get(">>")}return Cmd.get(">");case 123:this.nextChar();return Cmd.get("{");case 125:this.nextChar();return Cmd.get("}");case 41:this.nextChar();throw new FormatError(`Illegal character: ${t}`)}let i=String.fromCharCode(t);if(t<32||t>127){const e=this.peekChar();if(e>=32&&e<=127){this.nextChar();return Cmd.get(i)}}const a=this.knownCommands;let s=void 0!==a?.[i];for(;(t=this.nextChar())>=0&&!ai[t];){const e=i+String.fromCharCode(t);if(s&&void 0===a[e])break;if(128===i.length)throw new FormatError(`Command token too long: ${i.length}`);i=e;s=void 0!==a?.[i]}if("true"===i)return!0;if("false"===i)return!1;if("null"===i)return null;"BI"===i&&(this.beginInlineImagePos=this.stream.pos);return Cmd.get(i)}skipToNextLine(){let e=this.currentChar;for(;e>=0;){if(13===e){e=this.nextChar();10===e&&this.nextChar();break}if(10===e){this.nextChar();break}e=this.nextChar()}}}class Linearization{static create(e){function getInt(e,t,i=!1){const a=e.get(t);if(Number.isInteger(a)&&(i?a>=0:a>0))return a;throw new Error(`The "${t}" parameter in the linearization dictionary is invalid.`)}const t=new Parser({lexer:new Lexer(e),xref:null}),i=t.getObj(),a=t.getObj(),s=t.getObj(),r=t.getObj();let n,g;if(!(Number.isInteger(i)&&Number.isInteger(a)&&isCmd(s,"obj")&&r instanceof Dict&&"number"==typeof(n=r.get("Linearized"))&&n>0))return null;if((g=getInt(r,"L"))!==e.length)throw new Error('The "L" parameter in the linearization dictionary does not equal the stream length.');return{length:g,hints:function getHints(e){const t=e.get("H");let i;if(Array.isArray(t)&&(2===(i=t.length)||4===i)){for(let e=0;e0))throw new Error(`Hint (${e}) in the linearization dictionary is invalid.`)}return t}throw new Error("Hint array in the linearization dictionary is invalid.")}(r),objectNumberFirst:getInt(r,"O"),endFirst:getInt(r,"E"),numPages:getInt(r,"N"),mainXRefEntriesOffset:getInt(r,"T"),pageFirst:r.has("P")?getInt(r,"P",!0):0}}}const si=["Adobe-GB1-UCS2","Adobe-CNS1-UCS2","Adobe-Japan1-UCS2","Adobe-Korea1-UCS2","78-EUC-H","78-EUC-V","78-H","78-RKSJ-H","78-RKSJ-V","78-V","78ms-RKSJ-H","78ms-RKSJ-V","83pv-RKSJ-H","90ms-RKSJ-H","90ms-RKSJ-V","90msp-RKSJ-H","90msp-RKSJ-V","90pv-RKSJ-H","90pv-RKSJ-V","Add-H","Add-RKSJ-H","Add-RKSJ-V","Add-V","Adobe-CNS1-0","Adobe-CNS1-1","Adobe-CNS1-2","Adobe-CNS1-3","Adobe-CNS1-4","Adobe-CNS1-5","Adobe-CNS1-6","Adobe-GB1-0","Adobe-GB1-1","Adobe-GB1-2","Adobe-GB1-3","Adobe-GB1-4","Adobe-GB1-5","Adobe-Japan1-0","Adobe-Japan1-1","Adobe-Japan1-2","Adobe-Japan1-3","Adobe-Japan1-4","Adobe-Japan1-5","Adobe-Japan1-6","Adobe-Korea1-0","Adobe-Korea1-1","Adobe-Korea1-2","B5-H","B5-V","B5pc-H","B5pc-V","CNS-EUC-H","CNS-EUC-V","CNS1-H","CNS1-V","CNS2-H","CNS2-V","ETHK-B5-H","ETHK-B5-V","ETen-B5-H","ETen-B5-V","ETenms-B5-H","ETenms-B5-V","EUC-H","EUC-V","Ext-H","Ext-RKSJ-H","Ext-RKSJ-V","Ext-V","GB-EUC-H","GB-EUC-V","GB-H","GB-V","GBK-EUC-H","GBK-EUC-V","GBK2K-H","GBK2K-V","GBKp-EUC-H","GBKp-EUC-V","GBT-EUC-H","GBT-EUC-V","GBT-H","GBT-V","GBTpc-EUC-H","GBTpc-EUC-V","GBpc-EUC-H","GBpc-EUC-V","H","HKdla-B5-H","HKdla-B5-V","HKdlb-B5-H","HKdlb-B5-V","HKgccs-B5-H","HKgccs-B5-V","HKm314-B5-H","HKm314-B5-V","HKm471-B5-H","HKm471-B5-V","HKscs-B5-H","HKscs-B5-V","Hankaku","Hiragana","KSC-EUC-H","KSC-EUC-V","KSC-H","KSC-Johab-H","KSC-Johab-V","KSC-V","KSCms-UHC-H","KSCms-UHC-HW-H","KSCms-UHC-HW-V","KSCms-UHC-V","KSCpc-EUC-H","KSCpc-EUC-V","Katakana","NWP-H","NWP-V","RKSJ-H","RKSJ-V","Roman","UniCNS-UCS2-H","UniCNS-UCS2-V","UniCNS-UTF16-H","UniCNS-UTF16-V","UniCNS-UTF32-H","UniCNS-UTF32-V","UniCNS-UTF8-H","UniCNS-UTF8-V","UniGB-UCS2-H","UniGB-UCS2-V","UniGB-UTF16-H","UniGB-UTF16-V","UniGB-UTF32-H","UniGB-UTF32-V","UniGB-UTF8-H","UniGB-UTF8-V","UniJIS-UCS2-H","UniJIS-UCS2-HW-H","UniJIS-UCS2-HW-V","UniJIS-UCS2-V","UniJIS-UTF16-H","UniJIS-UTF16-V","UniJIS-UTF32-H","UniJIS-UTF32-V","UniJIS-UTF8-H","UniJIS-UTF8-V","UniJIS2004-UTF16-H","UniJIS2004-UTF16-V","UniJIS2004-UTF32-H","UniJIS2004-UTF32-V","UniJIS2004-UTF8-H","UniJIS2004-UTF8-V","UniJISPro-UCS2-HW-V","UniJISPro-UCS2-V","UniJISPro-UTF8-V","UniJISX0213-UTF32-H","UniJISX0213-UTF32-V","UniJISX02132004-UTF32-H","UniJISX02132004-UTF32-V","UniKS-UCS2-H","UniKS-UCS2-V","UniKS-UTF16-H","UniKS-UTF16-V","UniKS-UTF32-H","UniKS-UTF32-V","UniKS-UTF8-H","UniKS-UTF8-V","V","WP-Symbol"],ri=2**24-1;class CMap{constructor(e=!1){this.codespaceRanges=[[],[],[],[]];this.numCodespaceRanges=0;this._map=[];this.name="";this.vertical=!1;this.useCMap=null;this.builtInCMap=e}addCodespaceRange(e,t,i){this.codespaceRanges[e-1].push(t,i);this.numCodespaceRanges++}mapCidRange(e,t,i){if(t-e>ri)throw new Error("mapCidRange - ignoring data above MAX_MAP_RANGE.");for(;e<=t;)this._map[e++]=i++}mapBfRange(e,t,i){if(t-e>ri)throw new Error("mapBfRange - ignoring data above MAX_MAP_RANGE.");const a=i.length-1;for(;e<=t;){this._map[e++]=i;const t=i.charCodeAt(a)+1;t>255?i=i.substring(0,a-1)+String.fromCharCode(i.charCodeAt(a-1)+1)+"\0":i=i.substring(0,a)+String.fromCharCode(t)}}mapBfRangeToArray(e,t,i){if(t-e>ri)throw new Error("mapBfRangeToArray - ignoring data above MAX_MAP_RANGE.");const a=i.length;let s=0;for(;e<=t&&s>>0;const n=s[r];for(let e=0,t=n.length;e=t&&a<=s){i.charcode=a;i.length=r+1;return}}}i.charcode=0;i.length=1}getCharCodeLength(e){const t=this.codespaceRanges;for(let i=0,a=t.length;i=s&&e<=r)return i+1}}return 1}get length(){return this._map.length}get isIdentityCMap(){if("Identity-H"!==this.name&&"Identity-V"!==this.name)return!1;if(65536!==this._map.length)return!1;for(let e=0;e<65536;e++)if(this._map[e]!==e)return!1;return!0}}class IdentityCMap extends CMap{constructor(e,t){super();this.vertical=e;this.addCodespaceRange(t,0,65535)}mapCidRange(e,t,i){unreachable("should not call mapCidRange")}mapBfRange(e,t,i){unreachable("should not call mapBfRange")}mapBfRangeToArray(e,t,i){unreachable("should not call mapBfRangeToArray")}mapOne(e,t){unreachable("should not call mapCidOne")}lookup(e){return Number.isInteger(e)&&e<=65535?e:void 0}contains(e){return Number.isInteger(e)&&e<=65535}forEach(e){for(let t=0;t<=65535;t++)e(t,t)}charCodeOf(e){return Number.isInteger(e)&&e<=65535?e:-1}getMap(){const e=new Array(65536);for(let t=0;t<=65535;t++)e[t]=t;return e}get length(){return 65536}get isIdentityCMap(){unreachable("should not access .isIdentityCMap")}}function strToInt(e){let t=0;for(let i=0;i>>0}function expectString(e){if("string"!=typeof e)throw new FormatError("Malformed CMap: expected string.")}function expectInt(e){if(!Number.isInteger(e))throw new FormatError("Malformed CMap: expected int.")}function parseBfChar(e,t){for(;;){let i=t.getObj();if(i===Bt)break;if(isCmd(i,"endbfchar"))return;expectString(i);const a=strToInt(i);i=t.getObj();expectString(i);const s=i;e.mapOne(a,s)}}function parseBfRange(e,t){for(;;){let i=t.getObj();if(i===Bt)break;if(isCmd(i,"endbfrange"))return;expectString(i);const a=strToInt(i);i=t.getObj();expectString(i);const s=strToInt(i);i=t.getObj();if(Number.isInteger(i)||"string"==typeof i){const t=Number.isInteger(i)?String.fromCharCode(i):i;e.mapBfRange(a,s,t)}else{if(!isCmd(i,"["))break;{i=t.getObj();const r=[];for(;!isCmd(i,"]")&&i!==Bt;){r.push(i);i=t.getObj()}e.mapBfRangeToArray(a,s,r)}}}throw new FormatError("Invalid bf range.")}function parseCidChar(e,t){for(;;){let i=t.getObj();if(i===Bt)break;if(isCmd(i,"endcidchar"))return;expectString(i);const a=strToInt(i);i=t.getObj();expectInt(i);const s=i;e.mapOne(a,s)}}function parseCidRange(e,t){for(;;){let i=t.getObj();if(i===Bt)break;if(isCmd(i,"endcidrange"))return;expectString(i);const a=strToInt(i);i=t.getObj();expectString(i);const s=strToInt(i);i=t.getObj();expectInt(i);const r=i;e.mapCidRange(a,s,r)}}function parseCodespaceRange(e,t){for(;;){let i=t.getObj();if(i===Bt)break;if(isCmd(i,"endcodespacerange"))return;if("string"!=typeof i)break;const a=strToInt(i);i=t.getObj();if("string"!=typeof i)break;const s=strToInt(i);e.addCodespaceRange(i.length,a,s)}throw new FormatError("Invalid codespace range.")}function parseWMode(e,t){const i=t.getObj();Number.isInteger(i)&&(e.vertical=!!i)}function parseCMapName(e,t){const i=t.getObj();i instanceof Name&&(e.name=i.name)}async function parseCMap(e,t,i,a){let s,r;A:for(;;)try{const i=t.getObj();if(i===Bt)break;if(i instanceof Name){"WMode"===i.name?parseWMode(e,t):"CMapName"===i.name&&parseCMapName(e,t);s=i}else if(i instanceof Cmd)switch(i.cmd){case"endcmap":break A;case"usecmap":s instanceof Name&&(r=s.name);break;case"begincodespacerange":parseCodespaceRange(e,t);break;case"beginbfchar":parseBfChar(e,t);break;case"begincidchar":parseCidChar(e,t);break;case"beginbfrange":parseBfRange(e,t);break;case"begincidrange":parseCidRange(e,t)}}catch(e){if(e instanceof MissingDataException)throw e;warn("Invalid cMap data: "+e);continue}!a&&r&&(a=r);return a?extendCMap(e,i,a):e}async function extendCMap(e,t,i){e.useCMap=await createBuiltInCMap(i,t);if(0===e.numCodespaceRanges){const t=e.useCMap.codespaceRanges;for(let i=0;iextendCMap(s,t,e)));const r=new Lexer(new Stream(i));return parseCMap(s,r,t,null)}class CMapFactory{static async create({encoding:e,fetchBuiltInCMap:t,useCMap:i}){if(e instanceof Name)return createBuiltInCMap(e.name,t);if(e instanceof BaseStream){const a=await parseCMap(new CMap,new Lexer(e),t,i);return a.isIdentityCMap?createBuiltInCMap(a.name,t):a}throw new Error("Encoding required.")}}const ni=[".notdef","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","endash","dagger","daggerdbl","periodcentered","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","questiondown","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","ring","cedilla","hungarumlaut","ogonek","caron","emdash","AE","ordfeminine","Lslash","Oslash","OE","ordmasculine","ae","dotlessi","lslash","oslash","oe","germandbls","onesuperior","logicalnot","mu","trademark","Eth","onehalf","plusminus","Thorn","onequarter","divide","brokenbar","degree","thorn","threequarters","twosuperior","registered","minus","eth","multiply","threesuperior","copyright","Aacute","Acircumflex","Adieresis","Agrave","Aring","Atilde","Ccedilla","Eacute","Ecircumflex","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Ntilde","Oacute","Ocircumflex","Odieresis","Ograve","Otilde","Scaron","Uacute","Ucircumflex","Udieresis","Ugrave","Yacute","Ydieresis","Zcaron","aacute","acircumflex","adieresis","agrave","aring","atilde","ccedilla","eacute","ecircumflex","edieresis","egrave","iacute","icircumflex","idieresis","igrave","ntilde","oacute","ocircumflex","odieresis","ograve","otilde","scaron","uacute","ucircumflex","udieresis","ugrave","yacute","ydieresis","zcaron"],gi=[".notdef","space","exclamsmall","Hungarumlautsmall","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","questionsmall","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","fi","fl","ffi","ffl","parenleftinferior","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","exclamdownsmall","centoldstyle","Lslashsmall","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","Dotaccentsmall","Macronsmall","figuredash","hypheninferior","Ogoneksmall","Ringsmall","Cedillasmall","onequarter","onehalf","threequarters","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall"],oi=[".notdef","space","dollaroldstyle","dollarsuperior","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","fi","fl","ffi","ffl","parenleftinferior","parenrightinferior","hyphensuperior","colonmonetary","onefitted","rupiah","centoldstyle","figuredash","hypheninferior","onequarter","onehalf","threequarters","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior"],Ii=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclamsmall","Hungarumlautsmall","","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","questionsmall","","asuperior","bsuperior","centsuperior","dsuperior","esuperior","","","","isuperior","","","lsuperior","msuperior","nsuperior","osuperior","","","rsuperior","ssuperior","tsuperior","","ff","fi","fl","ffi","ffl","parenleftinferior","","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","exclamdownsmall","centoldstyle","Lslashsmall","","","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","","Dotaccentsmall","","","Macronsmall","","","figuredash","hypheninferior","","","Ogoneksmall","Ringsmall","Cedillasmall","","","","onequarter","onehalf","threequarters","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","","","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall"],ci=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclamsmall","Hungarumlautsmall","centoldstyle","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","","threequartersemdash","","questionsmall","","","","","Ethsmall","","","onequarter","onehalf","threequarters","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","","","","","","","ff","fi","fl","ffi","ffl","parenleftinferior","","parenrightinferior","Circumflexsmall","hypheninferior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","","","asuperior","centsuperior","","","","","Aacutesmall","Agravesmall","Acircumflexsmall","Adieresissmall","Atildesmall","Aringsmall","Ccedillasmall","Eacutesmall","Egravesmall","Ecircumflexsmall","Edieresissmall","Iacutesmall","Igravesmall","Icircumflexsmall","Idieresissmall","Ntildesmall","Oacutesmall","Ogravesmall","Ocircumflexsmall","Odieresissmall","Otildesmall","Uacutesmall","Ugravesmall","Ucircumflexsmall","Udieresissmall","","eightsuperior","fourinferior","threeinferior","sixinferior","eightinferior","seveninferior","Scaronsmall","","centinferior","twoinferior","","Dieresissmall","","Caronsmall","osuperior","fiveinferior","","commainferior","periodinferior","Yacutesmall","","dollarinferior","","","Thornsmall","","nineinferior","zeroinferior","Zcaronsmall","AEsmall","Oslashsmall","questiondownsmall","oneinferior","Lslashsmall","","","","","","","Cedillasmall","","","","","","OEsmall","figuredash","hyphensuperior","","","","","exclamdownsmall","","Ydieresissmall","","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","ninesuperior","zerosuperior","","esuperior","rsuperior","tsuperior","","","isuperior","ssuperior","dsuperior","","","","","","lsuperior","Ogoneksmall","Brevesmall","Macronsmall","bsuperior","nsuperior","msuperior","commasuperior","periodsuperior","Dotaccentsmall","Ringsmall","","","",""],Ci=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","","Adieresis","Aring","Ccedilla","Eacute","Ntilde","Odieresis","Udieresis","aacute","agrave","acircumflex","adieresis","atilde","aring","ccedilla","eacute","egrave","ecircumflex","edieresis","iacute","igrave","icircumflex","idieresis","ntilde","oacute","ograve","ocircumflex","odieresis","otilde","uacute","ugrave","ucircumflex","udieresis","dagger","degree","cent","sterling","section","bullet","paragraph","germandbls","registered","copyright","trademark","acute","dieresis","notequal","AE","Oslash","infinity","plusminus","lessequal","greaterequal","yen","mu","partialdiff","summation","product","pi","integral","ordfeminine","ordmasculine","Omega","ae","oslash","questiondown","exclamdown","logicalnot","radical","florin","approxequal","Delta","guillemotleft","guillemotright","ellipsis","space","Agrave","Atilde","Otilde","OE","oe","endash","emdash","quotedblleft","quotedblright","quoteleft","quoteright","divide","lozenge","ydieresis","Ydieresis","fraction","currency","guilsinglleft","guilsinglright","fi","fl","daggerdbl","periodcentered","quotesinglbase","quotedblbase","perthousand","Acircumflex","Ecircumflex","Aacute","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Oacute","Ocircumflex","apple","Ograve","Uacute","Ucircumflex","Ugrave","dotlessi","circumflex","tilde","macron","breve","dotaccent","ring","cedilla","hungarumlaut","ogonek","caron"],hi=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","","endash","dagger","daggerdbl","periodcentered","","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","","questiondown","","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","","ring","cedilla","","hungarumlaut","ogonek","caron","emdash","","","","","","","","","","","","","","","","","AE","","ordfeminine","","","","","Lslash","Oslash","OE","ordmasculine","","","","","","ae","","","","dotlessi","","","lslash","oslash","oe","germandbls","","","",""],li=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","bullet","Euro","bullet","quotesinglbase","florin","quotedblbase","ellipsis","dagger","daggerdbl","circumflex","perthousand","Scaron","guilsinglleft","OE","bullet","Zcaron","bullet","bullet","quoteleft","quoteright","quotedblleft","quotedblright","bullet","endash","emdash","tilde","trademark","scaron","guilsinglright","oe","bullet","zcaron","Ydieresis","space","exclamdown","cent","sterling","currency","yen","brokenbar","section","dieresis","copyright","ordfeminine","guillemotleft","logicalnot","hyphen","registered","macron","degree","plusminus","twosuperior","threesuperior","acute","mu","paragraph","periodcentered","cedilla","onesuperior","ordmasculine","guillemotright","onequarter","onehalf","threequarters","questiondown","Agrave","Aacute","Acircumflex","Atilde","Adieresis","Aring","AE","Ccedilla","Egrave","Eacute","Ecircumflex","Edieresis","Igrave","Iacute","Icircumflex","Idieresis","Eth","Ntilde","Ograve","Oacute","Ocircumflex","Otilde","Odieresis","multiply","Oslash","Ugrave","Uacute","Ucircumflex","Udieresis","Yacute","Thorn","germandbls","agrave","aacute","acircumflex","atilde","adieresis","aring","ae","ccedilla","egrave","eacute","ecircumflex","edieresis","igrave","iacute","icircumflex","idieresis","eth","ntilde","ograve","oacute","ocircumflex","otilde","odieresis","divide","oslash","ugrave","uacute","ucircumflex","udieresis","yacute","thorn","ydieresis"],Bi=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","universal","numbersign","existential","percent","ampersand","suchthat","parenleft","parenright","asteriskmath","plus","comma","minus","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","congruent","Alpha","Beta","Chi","Delta","Epsilon","Phi","Gamma","Eta","Iota","theta1","Kappa","Lambda","Mu","Nu","Omicron","Pi","Theta","Rho","Sigma","Tau","Upsilon","sigma1","Omega","Xi","Psi","Zeta","bracketleft","therefore","bracketright","perpendicular","underscore","radicalex","alpha","beta","chi","delta","epsilon","phi","gamma","eta","iota","phi1","kappa","lambda","mu","nu","omicron","pi","theta","rho","sigma","tau","upsilon","omega1","omega","xi","psi","zeta","braceleft","bar","braceright","similar","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","Euro","Upsilon1","minute","lessequal","fraction","infinity","florin","club","diamond","heart","spade","arrowboth","arrowleft","arrowup","arrowright","arrowdown","degree","plusminus","second","greaterequal","multiply","proportional","partialdiff","bullet","divide","notequal","equivalence","approxequal","ellipsis","arrowvertex","arrowhorizex","carriagereturn","aleph","Ifraktur","Rfraktur","weierstrass","circlemultiply","circleplus","emptyset","intersection","union","propersuperset","reflexsuperset","notsubset","propersubset","reflexsubset","element","notelement","angle","gradient","registerserif","copyrightserif","trademarkserif","product","radical","dotmath","logicalnot","logicaland","logicalor","arrowdblboth","arrowdblleft","arrowdblup","arrowdblright","arrowdbldown","lozenge","angleleft","registersans","copyrightsans","trademarksans","summation","parenlefttp","parenleftex","parenleftbt","bracketlefttp","bracketleftex","bracketleftbt","bracelefttp","braceleftmid","braceleftbt","braceex","","angleright","integral","integraltp","integralex","integralbt","parenrighttp","parenrightex","parenrightbt","bracketrighttp","bracketrightex","bracketrightbt","bracerighttp","bracerightmid","bracerightbt",""],Qi=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","a1","a2","a202","a3","a4","a5","a119","a118","a117","a11","a12","a13","a14","a15","a16","a105","a17","a18","a19","a20","a21","a22","a23","a24","a25","a26","a27","a28","a6","a7","a8","a9","a10","a29","a30","a31","a32","a33","a34","a35","a36","a37","a38","a39","a40","a41","a42","a43","a44","a45","a46","a47","a48","a49","a50","a51","a52","a53","a54","a55","a56","a57","a58","a59","a60","a61","a62","a63","a64","a65","a66","a67","a68","a69","a70","a71","a72","a73","a74","a203","a75","a204","a76","a77","a78","a79","a81","a82","a83","a84","a97","a98","a99","a100","","a89","a90","a93","a94","a91","a92","a205","a85","a206","a86","a87","a88","a95","a96","","","","","","","","","","","","","","","","","","","","a101","a102","a103","a104","a106","a107","a108","a112","a111","a110","a109","a120","a121","a122","a123","a124","a125","a126","a127","a128","a129","a130","a131","a132","a133","a134","a135","a136","a137","a138","a139","a140","a141","a142","a143","a144","a145","a146","a147","a148","a149","a150","a151","a152","a153","a154","a155","a156","a157","a158","a159","a160","a161","a163","a164","a196","a165","a192","a166","a167","a168","a169","a170","a171","a172","a173","a162","a174","a175","a176","a177","a178","a179","a193","a180","a199","a181","a200","a182","","a201","a183","a184","a197","a185","a194","a198","a186","a195","a187","a188","a189","a190","a191",""];function getEncoding(e){switch(e){case"WinAnsiEncoding":return li;case"StandardEncoding":return hi;case"MacRomanEncoding":return Ci;case"SymbolSetEncoding":return Bi;case"ZapfDingbatsEncoding":return Qi;case"ExpertEncoding":return Ii;case"MacExpertEncoding":return ci;default:return null}}const Ei=[".notdef","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","endash","dagger","daggerdbl","periodcentered","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","questiondown","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","ring","cedilla","hungarumlaut","ogonek","caron","emdash","AE","ordfeminine","Lslash","Oslash","OE","ordmasculine","ae","dotlessi","lslash","oslash","oe","germandbls","onesuperior","logicalnot","mu","trademark","Eth","onehalf","plusminus","Thorn","onequarter","divide","brokenbar","degree","thorn","threequarters","twosuperior","registered","minus","eth","multiply","threesuperior","copyright","Aacute","Acircumflex","Adieresis","Agrave","Aring","Atilde","Ccedilla","Eacute","Ecircumflex","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Ntilde","Oacute","Ocircumflex","Odieresis","Ograve","Otilde","Scaron","Uacute","Ucircumflex","Udieresis","Ugrave","Yacute","Ydieresis","Zcaron","aacute","acircumflex","adieresis","agrave","aring","atilde","ccedilla","eacute","ecircumflex","edieresis","egrave","iacute","icircumflex","idieresis","igrave","ntilde","oacute","ocircumflex","odieresis","ograve","otilde","scaron","uacute","ucircumflex","udieresis","ugrave","yacute","ydieresis","zcaron","exclamsmall","Hungarumlautsmall","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","commasuperior","threequartersemdash","periodsuperior","questionsmall","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","ffi","ffl","parenleftinferior","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","exclamdownsmall","centoldstyle","Lslashsmall","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","Dotaccentsmall","Macronsmall","figuredash","hypheninferior","Ogoneksmall","Ringsmall","Cedillasmall","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall","001.000","001.001","001.002","001.003","Black","Bold","Book","Light","Medium","Regular","Roman","Semibold"],ui=391,di=[null,{id:"hstem",min:2,stackClearing:!0,stem:!0},null,{id:"vstem",min:2,stackClearing:!0,stem:!0},{id:"vmoveto",min:1,stackClearing:!0},{id:"rlineto",min:2,resetStack:!0},{id:"hlineto",min:1,resetStack:!0},{id:"vlineto",min:1,resetStack:!0},{id:"rrcurveto",min:6,resetStack:!0},null,{id:"callsubr",min:1,undefStack:!0},{id:"return",min:0,undefStack:!0},null,null,{id:"endchar",min:0,stackClearing:!0},null,null,null,{id:"hstemhm",min:2,stackClearing:!0,stem:!0},{id:"hintmask",min:0,stackClearing:!0},{id:"cntrmask",min:0,stackClearing:!0},{id:"rmoveto",min:2,stackClearing:!0},{id:"hmoveto",min:1,stackClearing:!0},{id:"vstemhm",min:2,stackClearing:!0,stem:!0},{id:"rcurveline",min:8,resetStack:!0},{id:"rlinecurve",min:8,resetStack:!0},{id:"vvcurveto",min:4,resetStack:!0},{id:"hhcurveto",min:4,resetStack:!0},null,{id:"callgsubr",min:1,undefStack:!0},{id:"vhcurveto",min:4,resetStack:!0},{id:"hvcurveto",min:4,resetStack:!0}],fi=[null,null,null,{id:"and",min:2,stackDelta:-1},{id:"or",min:2,stackDelta:-1},{id:"not",min:1,stackDelta:0},null,null,null,{id:"abs",min:1,stackDelta:0},{id:"add",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]+e[t-1]}},{id:"sub",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]-e[t-1]}},{id:"div",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]/e[t-1]}},null,{id:"neg",min:1,stackDelta:0,stackFn(e,t){e[t-1]=-e[t-1]}},{id:"eq",min:2,stackDelta:-1},null,null,{id:"drop",min:1,stackDelta:-1},null,{id:"put",min:2,stackDelta:-2},{id:"get",min:1,stackDelta:0},{id:"ifelse",min:4,stackDelta:-3},{id:"random",min:0,stackDelta:1},{id:"mul",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]*e[t-1]}},null,{id:"sqrt",min:1,stackDelta:0},{id:"dup",min:1,stackDelta:1},{id:"exch",min:2,stackDelta:0},{id:"index",min:2,stackDelta:0},{id:"roll",min:3,stackDelta:-2},null,null,null,{id:"hflex",min:7,resetStack:!0},{id:"flex",min:13,resetStack:!0},{id:"hflex1",min:9,resetStack:!0},{id:"flex1",min:11,resetStack:!0}];class CFFParser{constructor(e,t,i){this.bytes=e.getBytes();this.properties=t;this.seacAnalysisEnabled=!!i}parse(){const e=this.properties,t=new CFF;this.cff=t;const i=this.parseHeader(),a=this.parseIndex(i.endPos),s=this.parseIndex(a.endPos),r=this.parseIndex(s.endPos),n=this.parseIndex(r.endPos),g=this.parseDict(s.obj.get(0)),o=this.createDict(CFFTopDict,g,t.strings);t.header=i.obj;t.names=this.parseNameIndex(a.obj);t.strings=this.parseStringIndex(r.obj);t.topDict=o;t.globalSubrIndex=n.obj;this.parsePrivateDict(t.topDict);t.isCIDFont=o.hasName("ROS");const c=o.getByName("CharStrings"),C=this.parseIndex(c).obj,h=o.getByName("FontMatrix");h&&(e.fontMatrix=h);const l=o.getByName("FontBBox");if(l){e.ascent=Math.max(l[3],l[1]);e.descent=Math.min(l[1],l[3]);e.ascentScaled=!0}let Q,E;if(t.isCIDFont){const e=this.parseIndex(o.getByName("FDArray")).obj;for(let i=0,a=e.count;i=t)throw new FormatError("Invalid CFF header");if(0!==i){info("cff data is shifted");e=e.subarray(i);this.bytes=e}const a=e[0],s=e[1],r=e[2],n=e[3];return{obj:new CFFHeader(a,s,r,n),endPos:r}}parseDict(e){let t=0;function parseOperand(){let i=e[t++];if(30===i)return function parseFloatOperand(){let i="";const a=15,s=["0","1","2","3","4","5","6","7","8","9",".","E","E-",null,"-"],r=e.length;for(;t>4,g=15&r;if(n===a)break;i+=s[n];if(g===a)break;i+=s[g]}return parseFloat(i)}();if(28===i){i=e[t++];i=(i<<24|e[t++]<<16)>>16;return i}if(29===i){i=e[t++];i=i<<8|e[t++];i=i<<8|e[t++];i=i<<8|e[t++];return i}if(i>=32&&i<=246)return i-139;if(i>=247&&i<=250)return 256*(i-247)+e[t++]+108;if(i>=251&&i<=254)return-256*(i-251)-e[t++]-108;warn('CFFParser_parseDict: "'+i+'" is a reserved command.');return NaN}let i=[];const a=[];t=0;const s=e.length;for(;t10)return!1;let s=e.stackSize;const r=e.stack;let n=t.length;for(let g=0;g>16;g+=2;s++}else if(14===o){if(s>=4){s-=4;if(this.seacAnalysisEnabled){e.seac=r.slice(s,s+4);return!1}}c=di[o]}else if(o>=32&&o<=246){r[s]=o-139;s++}else if(o>=247&&o<=254){r[s]=o<251?(o-247<<8)+t[g]+108:-(o-251<<8)-t[g]-108;g++;s++}else if(255===o){r[s]=(t[g]<<24|t[g+1]<<16|t[g+2]<<8|t[g+3])/65536;g+=4;s++}else if(19===o||20===o){e.hints+=s>>1;if(0===e.hints){t.copyWithin(g-1,g,-1);g-=1;n-=1;continue}g+=e.hints+7>>3;s%=2;c=di[o]}else{if(10===o||29===o){const t=10===o?i:a;if(!t){c=di[o];warn("Missing subrsIndex for "+c.id);return!1}let n=32768;t.count<1240?n=107:t.count<33900&&(n=1131);const g=r[--s]+n;if(g<0||g>=t.count||isNaN(g)){c=di[o];warn("Out of bounds subrIndex for "+c.id);return!1}e.stackSize=s;e.callDepth++;if(!this.parseCharString(e,t.get(g),i,a))return!1;e.callDepth--;s=e.stackSize;continue}if(11===o){e.stackSize=s;return!0}if(0===o&&g===t.length){t[g-1]=14;c=di[14]}else{if(9===o){t.copyWithin(g-1,g,-1);g-=1;n-=1;continue}c=di[o]}}if(c){if(c.stem){e.hints+=s>>1;if(3===o||23===o)e.hasVStems=!0;else if(e.hasVStems&&(1===o||18===o)){warn("CFF stem hints are in wrong order");t[g-1]=1===o?3:23}}if("min"in c&&!e.undefStack&&s=2&&c.stem?s%=2:s>1&&warn("Found too many parameters for stack-clearing command");s>0&&(e.width=r[s-1])}if("stackDelta"in c){"stackFn"in c&&c.stackFn(r,s);s+=c.stackDelta}else if(c.stackClearing)s=0;else if(c.resetStack){s=0;e.undefStack=!1}else if(c.undefStack){s=0;e.undefStack=!0;e.firstStackClearing=!1}}}n=s.length){warn("Invalid fd index for glyph index.");h=!1}if(h){Q=s[e].privateDict;l=Q.subrsIndex}}else t&&(l=t);h&&(h=this.parseCharString(C,o,l,i));if(null!==C.width){const e=Q.getByName("nominalWidthX");g[c]=e+C.width}else{const e=Q.getByName("defaultWidthX");g[c]=e}null!==C.seac&&(n[c]=C.seac);h||e.set(c,new Uint8Array([14]))}return{charStrings:e,seacs:n,widths:g}}emptyPrivateDictionary(e){const t=this.createDict(CFFPrivateDict,[],e.strings);e.setByKey(18,[0,0]);e.privateDict=t}parsePrivateDict(e){if(!e.hasName("Private")){this.emptyPrivateDictionary(e);return}const t=e.getByName("Private");if(!Array.isArray(t)||2!==t.length){e.removeByName("Private");return}const i=t[0],a=t[1];if(0===i||a>=this.bytes.length){this.emptyPrivateDictionary(e);return}const s=a+i,r=this.bytes.subarray(a,s),n=this.parseDict(r),g=this.createDict(CFFPrivateDict,n,e.strings);e.privateDict=g;0===g.getByName("ExpansionFactor")&&g.setByName("ExpansionFactor",.06);if(!g.getByName("Subrs"))return;const o=g.getByName("Subrs"),c=a+o;if(0===o||c>=this.bytes.length){this.emptyPrivateDictionary(e);return}const C=this.parseIndex(c);g.subrsIndex=C.obj}parseCharsets(e,t,i,a){if(0===e)return new CFFCharset(!0,yi.ISO_ADOBE,ni);if(1===e)return new CFFCharset(!0,yi.EXPERT,gi);if(2===e)return new CFFCharset(!0,yi.EXPERT_SUBSET,oi);const s=this.bytes,r=e,n=s[e++],g=[a?0:".notdef"];let o,c,C;t-=1;switch(n){case 0:for(C=0;C=65535){warn("Not enough space in charstrings to duplicate first glyph.");return}const e=this.charStrings.get(0);this.charStrings.add(e);this.isCIDFont&&this.fdSelect.fdSelect.push(this.fdSelect.fdSelect[0])}hasGlyphId(e){if(e<0||e>=this.charStrings.count)return!1;return this.charStrings.get(e).length>0}}class CFFHeader{constructor(e,t,i,a){this.major=e;this.minor=t;this.hdrSize=i;this.offSize=a}}class CFFStrings{constructor(){this.strings=[]}get(e){return e>=0&&e<=390?Ei[e]:e-ui<=this.strings.length?this.strings[e-ui]:Ei[0]}getSID(e){let t=Ei.indexOf(e);if(-1!==t)return t;t=this.strings.indexOf(e);return-1!==t?t+ui:-1}add(e){this.strings.push(e)}get count(){return this.strings.length}}class CFFIndex{constructor(){this.objects=[];this.length=0}add(e){this.length+=e.length;this.objects.push(e)}set(e,t){this.length+=t.length-this.objects[e].length;this.objects[e]=t}get(e){return this.objects[e]}get count(){return this.objects.length}}class CFFDict{constructor(e,t){this.keyToNameMap=e.keyToNameMap;this.nameToKeyMap=e.nameToKeyMap;this.defaults=e.defaults;this.types=e.types;this.opcodes=e.opcodes;this.order=e.order;this.strings=t;this.values=Object.create(null)}setByKey(e,t){if(!(e in this.keyToNameMap))return!1;if(0===t.length)return!0;for(const i of t)if(isNaN(i)){warn(`Invalid CFFDict value: "${t}" for key "${e}".`);return!0}const i=this.types[e];"num"!==i&&"sid"!==i&&"offset"!==i||(t=t[0]);this.values[e]=t;return!0}setByName(e,t){if(!(e in this.nameToKeyMap))throw new FormatError(`Invalid dictionary name "${e}"`);this.values[this.nameToKeyMap[e]]=t}hasName(e){return this.nameToKeyMap[e]in this.values}getByName(e){if(!(e in this.nameToKeyMap))throw new FormatError(`Invalid dictionary name ${e}"`);const t=this.nameToKeyMap[e];return t in this.values?this.values[t]:this.defaults[t]}removeByName(e){delete this.values[this.nameToKeyMap[e]]}static createTables(e){const t={keyToNameMap:{},nameToKeyMap:{},defaults:{},types:{},opcodes:{},order:[]};for(const i of e){const e=Array.isArray(i[0])?(i[0][0]<<8)+i[0][1]:i[0];t.keyToNameMap[e]=i[1];t.nameToKeyMap[i[1]]=e;t.types[e]=i[2];t.defaults[e]=i[3];t.opcodes[e]=Array.isArray(i[0])?i[0]:[i[0]];t.order.push(e)}return t}}const pi=[[[12,30],"ROS",["sid","sid","num"],null],[[12,20],"SyntheticBase","num",null],[0,"version","sid",null],[1,"Notice","sid",null],[[12,0],"Copyright","sid",null],[2,"FullName","sid",null],[3,"FamilyName","sid",null],[4,"Weight","sid",null],[[12,1],"isFixedPitch","num",0],[[12,2],"ItalicAngle","num",0],[[12,3],"UnderlinePosition","num",-100],[[12,4],"UnderlineThickness","num",50],[[12,5],"PaintType","num",0],[[12,6],"CharstringType","num",2],[[12,7],"FontMatrix",["num","num","num","num","num","num"],[.001,0,0,.001,0,0]],[13,"UniqueID","num",null],[5,"FontBBox",["num","num","num","num"],[0,0,0,0]],[[12,8],"StrokeWidth","num",0],[14,"XUID","array",null],[15,"charset","offset",0],[16,"Encoding","offset",0],[17,"CharStrings","offset",0],[18,"Private",["offset","offset"],null],[[12,21],"PostScript","sid",null],[[12,22],"BaseFontName","sid",null],[[12,23],"BaseFontBlend","delta",null],[[12,31],"CIDFontVersion","num",0],[[12,32],"CIDFontRevision","num",0],[[12,33],"CIDFontType","num",0],[[12,34],"CIDCount","num",8720],[[12,35],"UIDBase","num",null],[[12,37],"FDSelect","offset",null],[[12,36],"FDArray","offset",null],[[12,38],"FontName","sid",null]];class CFFTopDict extends CFFDict{static get tables(){return shadow(this,"tables",this.createTables(pi))}constructor(e){super(CFFTopDict.tables,e);this.privateDict=null}}const mi=[[6,"BlueValues","delta",null],[7,"OtherBlues","delta",null],[8,"FamilyBlues","delta",null],[9,"FamilyOtherBlues","delta",null],[[12,9],"BlueScale","num",.039625],[[12,10],"BlueShift","num",7],[[12,11],"BlueFuzz","num",1],[10,"StdHW","num",null],[11,"StdVW","num",null],[[12,12],"StemSnapH","delta",null],[[12,13],"StemSnapV","delta",null],[[12,14],"ForceBold","num",0],[[12,17],"LanguageGroup","num",0],[[12,18],"ExpansionFactor","num",.06],[[12,19],"initialRandomSeed","num",0],[20,"defaultWidthX","num",0],[21,"nominalWidthX","num",0],[19,"Subrs","offset",null]];class CFFPrivateDict extends CFFDict{static get tables(){return shadow(this,"tables",this.createTables(mi))}constructor(e){super(CFFPrivateDict.tables,e);this.subrsIndex=null}}const yi={ISO_ADOBE:0,EXPERT:1,EXPERT_SUBSET:2};class CFFCharset{constructor(e,t,i,a){this.predefined=e;this.format=t;this.charset=i;this.raw=a}}class CFFEncoding{constructor(e,t,i,a){this.predefined=e;this.format=t;this.encoding=i;this.raw=a}}class CFFFDSelect{constructor(e,t){this.format=e;this.fdSelect=t}getFDIndex(e){return e<0||e>=this.fdSelect.length?-1:this.fdSelect[e]}}class CFFOffsetTracker{constructor(){this.offsets=Object.create(null)}isTracking(e){return e in this.offsets}track(e,t){if(e in this.offsets)throw new FormatError(`Already tracking location of ${e}`);this.offsets[e]=t}offset(e){for(const t in this.offsets)this.offsets[t]+=e}setEntryLocation(e,t,i){if(!(e in this.offsets))throw new FormatError(`Not tracking location of ${e}`);const a=i.data,s=this.offsets[e];for(let e=0,i=t.length;e>24&255;a[n]=c>>16&255;a[g]=c>>8&255;a[o]=255&c}}}class CFFCompiler{constructor(e){this.cff=e}compile(){const e=this.cff,t={data:[],length:0,add(e){try{this.data.push(...e)}catch{this.data=this.data.concat(e)}this.length=this.data.length}},i=this.compileHeader(e.header);t.add(i);const a=this.compileNameIndex(e.names);t.add(a);if(e.isCIDFont&&e.topDict.hasName("FontMatrix")){const t=e.topDict.getByName("FontMatrix");e.topDict.removeByName("FontMatrix");for(const i of e.fdArray){let e=t.slice(0);i.hasName("FontMatrix")&&(e=Util.transform(e,i.getByName("FontMatrix")));i.setByName("FontMatrix",e)}}const s=e.topDict.getByName("XUID");s?.length>16&&e.topDict.removeByName("XUID");e.topDict.setByName("charset",0);let r=this.compileTopDicts([e.topDict],t.length,e.isCIDFont);t.add(r.output);const n=r.trackers[0],g=this.compileStringIndex(e.strings.strings);t.add(g);const o=this.compileIndex(e.globalSubrIndex);t.add(o);if(e.encoding&&e.topDict.hasName("Encoding"))if(e.encoding.predefined)n.setEntryLocation("Encoding",[e.encoding.format],t);else{const i=this.compileEncoding(e.encoding);n.setEntryLocation("Encoding",[t.length],t);t.add(i)}const c=this.compileCharset(e.charset,e.charStrings.count,e.strings,e.isCIDFont);n.setEntryLocation("charset",[t.length],t);t.add(c);const C=this.compileCharStrings(e.charStrings);n.setEntryLocation("CharStrings",[t.length],t);t.add(C);if(e.isCIDFont){n.setEntryLocation("FDSelect",[t.length],t);const i=this.compileFDSelect(e.fdSelect);t.add(i);r=this.compileTopDicts(e.fdArray,t.length,!0);n.setEntryLocation("FDArray",[t.length],t);t.add(r.output);const a=r.trackers;this.compilePrivateDicts(e.fdArray,a,t)}this.compilePrivateDicts([e.topDict],[n],t);t.add([0]);return t.data}encodeNumber(e){return Number.isInteger(e)?this.encodeInteger(e):this.encodeFloat(e)}static get EncodeFloatRegExp(){return shadow(this,"EncodeFloatRegExp",/\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/)}encodeFloat(e){let t=e.toString();const i=CFFCompiler.EncodeFloatRegExp.exec(t);if(i){const a=parseFloat("1e"+((i[2]?+i[2]:0)+i[1].length));t=(Math.round(e*a)/a).toString()}let a,s,r="";for(a=0,s=t.length;a=-107&&e<=107?[e+139]:e>=108&&e<=1131?[247+((e-=108)>>8),255&e]:e>=-1131&&e<=-108?[251+((e=-e-108)>>8),255&e]:e>=-32768&&e<=32767?[28,e>>8&255,255&e]:[29,e>>24&255,e>>16&255,e>>8&255,255&e];return t}compileHeader(e){return[e.major,e.minor,4,e.offSize]}compileNameIndex(e){const t=new CFFIndex;for(const i of e){const e=Math.min(i.length,127);let a=new Array(e);for(let t=0;t"~"||"["===e||"]"===e||"("===e||")"===e||"{"===e||"}"===e||"<"===e||">"===e||"/"===e||"%"===e)&&(e="_");a[t]=e}a=a.join("");""===a&&(a="Bad_Font_Name");t.add(stringToBytes(a))}return this.compileIndex(t)}compileTopDicts(e,t,i){const a=[];let s=new CFFIndex;for(const r of e){if(i){r.removeByName("CIDFontVersion");r.removeByName("CIDFontRevision");r.removeByName("CIDFontType");r.removeByName("CIDCount");r.removeByName("UIDBase")}const e=new CFFOffsetTracker,n=this.compileDict(r,e);a.push(e);s.add(n);e.offset(t)}s=this.compileIndex(s,a);return{trackers:a,output:s}}compilePrivateDicts(e,t,i){for(let a=0,s=e.length;a>8&255,255&r]);else{s=new Uint8Array(1+2*r);s[0]=0;let t=0;const a=e.charset.length;let n=!1;for(let r=1;r>8&255;s[r+1]=255&g}}return this.compileTypedArray(s)}compileEncoding(e){return this.compileTypedArray(e.raw)}compileFDSelect(e){const t=e.format;let i,a;switch(t){case 0:i=new Uint8Array(1+e.fdSelect.length);i[0]=t;for(a=0;a>8&255,255&s,r];for(a=1;a>8&255,255&a,t);r=t}}const g=(n.length-3)/3;n[1]=g>>8&255;n[2]=255&g;n.push(a>>8&255,255&a);i=new Uint8Array(n)}return this.compileTypedArray(i)}compileTypedArray(e){return Array.from(e)}compileIndex(e,t=[]){const i=e.objects,a=i.length;if(0===a)return[0,0];const s=[a>>8&255,255&a];let r,n,g=1;for(r=0;r>8&255,255&o):3===n?s.push(o>>16&255,o>>8&255,255&o):s.push(o>>>24&255,o>>16&255,o>>8&255,255&o);i[r]&&(o+=i[r].length)}for(r=0;r=5&&t<=7))return-1;a=e.substring(1)}if(a===a.toUpperCase()){i=parseInt(a,16);if(i>=0)return i}}return-1}const Fi=[[0,127],[128,255],[256,383],[384,591],[592,687,7424,7551,7552,7615],[688,767,42752,42783],[768,879,7616,7679],[880,1023],[11392,11519],[1024,1279,1280,1327,11744,11775,42560,42655],[1328,1423],[1424,1535],[42240,42559],[1536,1791,1872,1919],[1984,2047],[2304,2431],[2432,2559],[2560,2687],[2688,2815],[2816,2943],[2944,3071],[3072,3199],[3200,3327],[3328,3455],[3584,3711],[3712,3839],[4256,4351,11520,11567],[6912,7039],[4352,4607],[7680,7935,11360,11391,42784,43007],[7936,8191],[8192,8303,11776,11903],[8304,8351],[8352,8399],[8400,8447],[8448,8527],[8528,8591],[8592,8703,10224,10239,10496,10623,11008,11263],[8704,8959,10752,11007,10176,10223,10624,10751],[8960,9215],[9216,9279],[9280,9311],[9312,9471],[9472,9599],[9600,9631],[9632,9727],[9728,9983],[9984,10175],[12288,12351],[12352,12447],[12448,12543,12784,12799],[12544,12591,12704,12735],[12592,12687],[43072,43135],[12800,13055],[13056,13311],[44032,55215],[55296,57343],[67840,67871],[19968,40959,11904,12031,12032,12255,12272,12287,13312,19903,131072,173791,12688,12703],[57344,63743],[12736,12783,63744,64255,194560,195103],[64256,64335],[64336,65023],[65056,65071],[65040,65055],[65104,65135],[65136,65279],[65280,65519],[65520,65535],[3840,4095],[1792,1871],[1920,1983],[3456,3583],[4096,4255],[4608,4991,4992,5023,11648,11743],[5024,5119],[5120,5759],[5760,5791],[5792,5887],[6016,6143],[6144,6319],[10240,10495],[40960,42127],[5888,5919,5920,5951,5952,5983,5984,6015],[66304,66351],[66352,66383],[66560,66639],[118784,119039,119040,119295,119296,119375],[119808,120831],[1044480,1048573],[65024,65039,917760,917999],[917504,917631],[6400,6479],[6480,6527],[6528,6623],[6656,6687],[11264,11359],[11568,11647],[19904,19967],[43008,43055],[65536,65663,65664,65791,65792,65855],[65856,65935],[66432,66463],[66464,66527],[66640,66687],[66688,66735],[67584,67647],[68096,68191],[119552,119647],[73728,74751,74752,74879],[119648,119679],[7040,7103],[7168,7247],[7248,7295],[43136,43231],[43264,43311],[43312,43359],[43520,43615],[65936,65999],[66e3,66047],[66208,66271,66176,66207,67872,67903],[127024,127135,126976,127023]];function getUnicodeRangeFor(e,t=-1){if(-1!==t){const i=Fi[t];for(let a=0,s=i.length;a=i[a]&&e<=i[a+1])return t}for(let t=0,i=Fi.length;t=i[a]&&e<=i[a+1])return t}return-1}const Si=new RegExp("^(\\s)|(\\p{Mn})|(\\p{Cf})$","u"),ki=new Map;const Ri=!0,Ni=1,Gi=2,Mi=4,xi=32,Hi=[".notdef",".null","nonmarkingreturn","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","Adieresis","Aring","Ccedilla","Eacute","Ntilde","Odieresis","Udieresis","aacute","agrave","acircumflex","adieresis","atilde","aring","ccedilla","eacute","egrave","ecircumflex","edieresis","iacute","igrave","icircumflex","idieresis","ntilde","oacute","ograve","ocircumflex","odieresis","otilde","uacute","ugrave","ucircumflex","udieresis","dagger","degree","cent","sterling","section","bullet","paragraph","germandbls","registered","copyright","trademark","acute","dieresis","notequal","AE","Oslash","infinity","plusminus","lessequal","greaterequal","yen","mu","partialdiff","summation","product","pi","integral","ordfeminine","ordmasculine","Omega","ae","oslash","questiondown","exclamdown","logicalnot","radical","florin","approxequal","Delta","guillemotleft","guillemotright","ellipsis","nonbreakingspace","Agrave","Atilde","Otilde","OE","oe","endash","emdash","quotedblleft","quotedblright","quoteleft","quoteright","divide","lozenge","ydieresis","Ydieresis","fraction","currency","guilsinglleft","guilsinglright","fi","fl","daggerdbl","periodcentered","quotesinglbase","quotedblbase","perthousand","Acircumflex","Ecircumflex","Aacute","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Oacute","Ocircumflex","apple","Ograve","Uacute","Ucircumflex","Ugrave","dotlessi","circumflex","tilde","macron","breve","dotaccent","ring","cedilla","hungarumlaut","ogonek","caron","Lslash","lslash","Scaron","scaron","Zcaron","zcaron","brokenbar","Eth","eth","Yacute","yacute","Thorn","thorn","minus","multiply","onesuperior","twosuperior","threesuperior","onehalf","onequarter","threequarters","franc","Gbreve","gbreve","Idotaccent","Scedilla","scedilla","Cacute","cacute","Ccaron","ccaron","dcroat"];function recoverGlyphName(e,t){if(void 0!==t[e])return e;const i=getUnicodeForGlyph(e,t);if(-1!==i)for(const e in t)if(t[e]===i)return e;info("Unable to recover a standard glyph name for: "+e);return e}function type1FontGlyphMapping(e,t,i){const a=Object.create(null);let s,r,n;const g=!!(e.flags&Mi);if(e.isInternalFont){n=t;for(r=0;r=0?s:0}}else if(e.baseEncodingName){n=getEncoding(e.baseEncodingName);for(r=0;r=0?s:0}}else if(g)for(r in t)a[r]=t[r];else{n=hi;for(r=0;r=0?s:0}}const o=e.differences;let c;if(o)for(r in o){const e=o[r];s=i.indexOf(e);if(-1===s){c||(c=wi());const t=recoverGlyphName(e,c);t!==e&&(s=i.indexOf(t))}a[r]=s>=0?s:0}return a}function normalizeFontName(e){return e.replaceAll(/[,_]/g,"-").replaceAll(/\s/g,"")}const Ji=getLookupTableFactory((e=>{e[8211]=65074;e[8212]=65073;e[8229]=65072;e[8230]=65049;e[12289]=65041;e[12290]=65042;e[12296]=65087;e[12297]=65088;e[12298]=65085;e[12299]=65086;e[12300]=65089;e[12301]=65090;e[12302]=65091;e[12303]=65092;e[12304]=65083;e[12305]=65084;e[12308]=65081;e[12309]=65082;e[12310]=65047;e[12311]=65048;e[65103]=65076;e[65281]=65045;e[65288]=65077;e[65289]=65078;e[65292]=65040;e[65306]=65043;e[65307]=65044;e[65311]=65046;e[65339]=65095;e[65341]=65096;e[65343]=65075;e[65371]=65079;e[65373]=65080})),Yi=getLookupTableFactory((function(e){e["Times-Roman"]="Times-Roman";e.Helvetica="Helvetica";e.Courier="Courier";e.Symbol="Symbol";e["Times-Bold"]="Times-Bold";e["Helvetica-Bold"]="Helvetica-Bold";e["Courier-Bold"]="Courier-Bold";e.ZapfDingbats="ZapfDingbats";e["Times-Italic"]="Times-Italic";e["Helvetica-Oblique"]="Helvetica-Oblique";e["Courier-Oblique"]="Courier-Oblique";e["Times-BoldItalic"]="Times-BoldItalic";e["Helvetica-BoldOblique"]="Helvetica-BoldOblique";e["Courier-BoldOblique"]="Courier-BoldOblique";e.ArialNarrow="Helvetica";e["ArialNarrow-Bold"]="Helvetica-Bold";e["ArialNarrow-BoldItalic"]="Helvetica-BoldOblique";e["ArialNarrow-Italic"]="Helvetica-Oblique";e.ArialBlack="Helvetica";e["ArialBlack-Bold"]="Helvetica-Bold";e["ArialBlack-BoldItalic"]="Helvetica-BoldOblique";e["ArialBlack-Italic"]="Helvetica-Oblique";e["Arial-Black"]="Helvetica";e["Arial-Black-Bold"]="Helvetica-Bold";e["Arial-Black-BoldItalic"]="Helvetica-BoldOblique";e["Arial-Black-Italic"]="Helvetica-Oblique";e.Arial="Helvetica";e["Arial-Bold"]="Helvetica-Bold";e["Arial-BoldItalic"]="Helvetica-BoldOblique";e["Arial-Italic"]="Helvetica-Oblique";e.ArialMT="Helvetica";e["Arial-BoldItalicMT"]="Helvetica-BoldOblique";e["Arial-BoldMT"]="Helvetica-Bold";e["Arial-ItalicMT"]="Helvetica-Oblique";e["Arial-BoldItalicMT-BoldItalic"]="Helvetica-BoldOblique";e["Arial-BoldMT-Bold"]="Helvetica-Bold";e["Arial-ItalicMT-Italic"]="Helvetica-Oblique";e.ArialUnicodeMS="Helvetica";e["ArialUnicodeMS-Bold"]="Helvetica-Bold";e["ArialUnicodeMS-BoldItalic"]="Helvetica-BoldOblique";e["ArialUnicodeMS-Italic"]="Helvetica-Oblique";e["Courier-BoldItalic"]="Courier-BoldOblique";e["Courier-Italic"]="Courier-Oblique";e.CourierNew="Courier";e["CourierNew-Bold"]="Courier-Bold";e["CourierNew-BoldItalic"]="Courier-BoldOblique";e["CourierNew-Italic"]="Courier-Oblique";e["CourierNewPS-BoldItalicMT"]="Courier-BoldOblique";e["CourierNewPS-BoldMT"]="Courier-Bold";e["CourierNewPS-ItalicMT"]="Courier-Oblique";e.CourierNewPSMT="Courier";e["Helvetica-BoldItalic"]="Helvetica-BoldOblique";e["Helvetica-Italic"]="Helvetica-Oblique";e["HelveticaLTStd-Bold"]="Helvetica-Bold";e["Symbol-Bold"]="Symbol";e["Symbol-BoldItalic"]="Symbol";e["Symbol-Italic"]="Symbol";e.TimesNewRoman="Times-Roman";e["TimesNewRoman-Bold"]="Times-Bold";e["TimesNewRoman-BoldItalic"]="Times-BoldItalic";e["TimesNewRoman-Italic"]="Times-Italic";e.TimesNewRomanPS="Times-Roman";e["TimesNewRomanPS-Bold"]="Times-Bold";e["TimesNewRomanPS-BoldItalic"]="Times-BoldItalic";e["TimesNewRomanPS-BoldItalicMT"]="Times-BoldItalic";e["TimesNewRomanPS-BoldMT"]="Times-Bold";e["TimesNewRomanPS-Italic"]="Times-Italic";e["TimesNewRomanPS-ItalicMT"]="Times-Italic";e.TimesNewRomanPSMT="Times-Roman";e["TimesNewRomanPSMT-Bold"]="Times-Bold";e["TimesNewRomanPSMT-BoldItalic"]="Times-BoldItalic";e["TimesNewRomanPSMT-Italic"]="Times-Italic"})),vi=getLookupTableFactory((function(e){e.Courier="FoxitFixed.pfb";e["Courier-Bold"]="FoxitFixedBold.pfb";e["Courier-BoldOblique"]="FoxitFixedBoldItalic.pfb";e["Courier-Oblique"]="FoxitFixedItalic.pfb";e.Helvetica="LiberationSans-Regular.ttf";e["Helvetica-Bold"]="LiberationSans-Bold.ttf";e["Helvetica-BoldOblique"]="LiberationSans-BoldItalic.ttf";e["Helvetica-Oblique"]="LiberationSans-Italic.ttf";e["Times-Roman"]="FoxitSerif.pfb";e["Times-Bold"]="FoxitSerifBold.pfb";e["Times-BoldItalic"]="FoxitSerifBoldItalic.pfb";e["Times-Italic"]="FoxitSerifItalic.pfb";e.Symbol="FoxitSymbol.pfb";e.ZapfDingbats="FoxitDingbats.pfb";e["LiberationSans-Regular"]="LiberationSans-Regular.ttf";e["LiberationSans-Bold"]="LiberationSans-Bold.ttf";e["LiberationSans-Italic"]="LiberationSans-Italic.ttf";e["LiberationSans-BoldItalic"]="LiberationSans-BoldItalic.ttf"})),Ki=getLookupTableFactory((function(e){e.Calibri="Helvetica";e["Calibri-Bold"]="Helvetica-Bold";e["Calibri-BoldItalic"]="Helvetica-BoldOblique";e["Calibri-Italic"]="Helvetica-Oblique";e.CenturyGothic="Helvetica";e["CenturyGothic-Bold"]="Helvetica-Bold";e["CenturyGothic-BoldItalic"]="Helvetica-BoldOblique";e["CenturyGothic-Italic"]="Helvetica-Oblique";e.ComicSansMS="Comic Sans MS";e["ComicSansMS-Bold"]="Comic Sans MS-Bold";e["ComicSansMS-BoldItalic"]="Comic Sans MS-BoldItalic";e["ComicSansMS-Italic"]="Comic Sans MS-Italic";e.GillSansMT="Helvetica";e["GillSansMT-Bold"]="Helvetica-Bold";e["GillSansMT-BoldItalic"]="Helvetica-BoldOblique";e["GillSansMT-Italic"]="Helvetica-Oblique";e.Impact="Helvetica";e["ItcSymbol-Bold"]="Helvetica-Bold";e["ItcSymbol-BoldItalic"]="Helvetica-BoldOblique";e["ItcSymbol-Book"]="Helvetica";e["ItcSymbol-BookItalic"]="Helvetica-Oblique";e["ItcSymbol-Medium"]="Helvetica";e["ItcSymbol-MediumItalic"]="Helvetica-Oblique";e.LucidaConsole="Courier";e["LucidaConsole-Bold"]="Courier-Bold";e["LucidaConsole-BoldItalic"]="Courier-BoldOblique";e["LucidaConsole-Italic"]="Courier-Oblique";e["LucidaSans-Demi"]="Helvetica-Bold";e["MS-Gothic"]="MS Gothic";e["MS-Gothic-Bold"]="MS Gothic-Bold";e["MS-Gothic-BoldItalic"]="MS Gothic-BoldItalic";e["MS-Gothic-Italic"]="MS Gothic-Italic";e["MS-Mincho"]="MS Mincho";e["MS-Mincho-Bold"]="MS Mincho-Bold";e["MS-Mincho-BoldItalic"]="MS Mincho-BoldItalic";e["MS-Mincho-Italic"]="MS Mincho-Italic";e["MS-PGothic"]="MS PGothic";e["MS-PGothic-Bold"]="MS PGothic-Bold";e["MS-PGothic-BoldItalic"]="MS PGothic-BoldItalic";e["MS-PGothic-Italic"]="MS PGothic-Italic";e["MS-PMincho"]="MS PMincho";e["MS-PMincho-Bold"]="MS PMincho-Bold";e["MS-PMincho-BoldItalic"]="MS PMincho-BoldItalic";e["MS-PMincho-Italic"]="MS PMincho-Italic";e.NuptialScript="Times-Italic";e.SegoeUISymbol="Helvetica"})),Ti=getLookupTableFactory((function(e){e["Adobe Jenson"]=!0;e["Adobe Text"]=!0;e.Albertus=!0;e.Aldus=!0;e.Alexandria=!0;e.Algerian=!0;e["American Typewriter"]=!0;e.Antiqua=!0;e.Apex=!0;e.Arno=!0;e.Aster=!0;e.Aurora=!0;e.Baskerville=!0;e.Bell=!0;e.Bembo=!0;e["Bembo Schoolbook"]=!0;e.Benguiat=!0;e["Berkeley Old Style"]=!0;e["Bernhard Modern"]=!0;e["Berthold City"]=!0;e.Bodoni=!0;e["Bauer Bodoni"]=!0;e["Book Antiqua"]=!0;e.Bookman=!0;e["Bordeaux Roman"]=!0;e["Californian FB"]=!0;e.Calisto=!0;e.Calvert=!0;e.Capitals=!0;e.Cambria=!0;e.Cartier=!0;e.Caslon=!0;e.Catull=!0;e.Centaur=!0;e["Century Old Style"]=!0;e["Century Schoolbook"]=!0;e.Chaparral=!0;e["Charis SIL"]=!0;e.Cheltenham=!0;e["Cholla Slab"]=!0;e.Clarendon=!0;e.Clearface=!0;e.Cochin=!0;e.Colonna=!0;e["Computer Modern"]=!0;e["Concrete Roman"]=!0;e.Constantia=!0;e["Cooper Black"]=!0;e.Corona=!0;e.Ecotype=!0;e.Egyptienne=!0;e.Elephant=!0;e.Excelsior=!0;e.Fairfield=!0;e["FF Scala"]=!0;e.Folkard=!0;e.Footlight=!0;e.FreeSerif=!0;e["Friz Quadrata"]=!0;e.Garamond=!0;e.Gentium=!0;e.Georgia=!0;e.Gloucester=!0;e["Goudy Old Style"]=!0;e["Goudy Schoolbook"]=!0;e["Goudy Pro Font"]=!0;e.Granjon=!0;e["Guardian Egyptian"]=!0;e.Heather=!0;e.Hercules=!0;e["High Tower Text"]=!0;e.Hiroshige=!0;e["Hoefler Text"]=!0;e["Humana Serif"]=!0;e.Imprint=!0;e["Ionic No. 5"]=!0;e.Janson=!0;e.Joanna=!0;e.Korinna=!0;e.Lexicon=!0;e.LiberationSerif=!0;e["Liberation Serif"]=!0;e["Linux Libertine"]=!0;e.Literaturnaya=!0;e.Lucida=!0;e["Lucida Bright"]=!0;e.Melior=!0;e.Memphis=!0;e.Miller=!0;e.Minion=!0;e.Modern=!0;e["Mona Lisa"]=!0;e["Mrs Eaves"]=!0;e["MS Serif"]=!0;e["Museo Slab"]=!0;e["New York"]=!0;e["Nimbus Roman"]=!0;e["NPS Rawlinson Roadway"]=!0;e.NuptialScript=!0;e.Palatino=!0;e.Perpetua=!0;e.Plantin=!0;e["Plantin Schoolbook"]=!0;e.Playbill=!0;e["Poor Richard"]=!0;e["Rawlinson Roadway"]=!0;e.Renault=!0;e.Requiem=!0;e.Rockwell=!0;e.Roman=!0;e["Rotis Serif"]=!0;e.Sabon=!0;e.Scala=!0;e.Seagull=!0;e.Sistina=!0;e.Souvenir=!0;e.STIX=!0;e["Stone Informal"]=!0;e["Stone Serif"]=!0;e.Sylfaen=!0;e.Times=!0;e.Trajan=!0;e["Trinité"]=!0;e["Trump Mediaeval"]=!0;e.Utopia=!0;e["Vale Type"]=!0;e["Bitstream Vera"]=!0;e["Vera Serif"]=!0;e.Versailles=!0;e.Wanted=!0;e.Weiss=!0;e["Wide Latin"]=!0;e.Windsor=!0;e.XITS=!0})),qi=getLookupTableFactory((function(e){e.Dingbats=!0;e.Symbol=!0;e.ZapfDingbats=!0;e.Wingdings=!0;e["Wingdings-Bold"]=!0;e["Wingdings-Regular"]=!0})),Oi=getLookupTableFactory((function(e){e[2]=10;e[3]=32;e[4]=33;e[5]=34;e[6]=35;e[7]=36;e[8]=37;e[9]=38;e[10]=39;e[11]=40;e[12]=41;e[13]=42;e[14]=43;e[15]=44;e[16]=45;e[17]=46;e[18]=47;e[19]=48;e[20]=49;e[21]=50;e[22]=51;e[23]=52;e[24]=53;e[25]=54;e[26]=55;e[27]=56;e[28]=57;e[29]=58;e[30]=894;e[31]=60;e[32]=61;e[33]=62;e[34]=63;e[35]=64;e[36]=65;e[37]=66;e[38]=67;e[39]=68;e[40]=69;e[41]=70;e[42]=71;e[43]=72;e[44]=73;e[45]=74;e[46]=75;e[47]=76;e[48]=77;e[49]=78;e[50]=79;e[51]=80;e[52]=81;e[53]=82;e[54]=83;e[55]=84;e[56]=85;e[57]=86;e[58]=87;e[59]=88;e[60]=89;e[61]=90;e[62]=91;e[63]=92;e[64]=93;e[65]=94;e[66]=95;e[67]=96;e[68]=97;e[69]=98;e[70]=99;e[71]=100;e[72]=101;e[73]=102;e[74]=103;e[75]=104;e[76]=105;e[77]=106;e[78]=107;e[79]=108;e[80]=109;e[81]=110;e[82]=111;e[83]=112;e[84]=113;e[85]=114;e[86]=115;e[87]=116;e[88]=117;e[89]=118;e[90]=119;e[91]=120;e[92]=121;e[93]=122;e[94]=123;e[95]=124;e[96]=125;e[97]=126;e[98]=196;e[99]=197;e[100]=199;e[101]=201;e[102]=209;e[103]=214;e[104]=220;e[105]=225;e[106]=224;e[107]=226;e[108]=228;e[109]=227;e[110]=229;e[111]=231;e[112]=233;e[113]=232;e[114]=234;e[115]=235;e[116]=237;e[117]=236;e[118]=238;e[119]=239;e[120]=241;e[121]=243;e[122]=242;e[123]=244;e[124]=246;e[125]=245;e[126]=250;e[127]=249;e[128]=251;e[129]=252;e[130]=8224;e[131]=176;e[132]=162;e[133]=163;e[134]=167;e[135]=8226;e[136]=182;e[137]=223;e[138]=174;e[139]=169;e[140]=8482;e[141]=180;e[142]=168;e[143]=8800;e[144]=198;e[145]=216;e[146]=8734;e[147]=177;e[148]=8804;e[149]=8805;e[150]=165;e[151]=181;e[152]=8706;e[153]=8721;e[154]=8719;e[156]=8747;e[157]=170;e[158]=186;e[159]=8486;e[160]=230;e[161]=248;e[162]=191;e[163]=161;e[164]=172;e[165]=8730;e[166]=402;e[167]=8776;e[168]=8710;e[169]=171;e[170]=187;e[171]=8230;e[179]=8220;e[180]=8221;e[181]=8216;e[182]=8217;e[200]=193;e[203]=205;e[207]=211;e[210]=218;e[223]=711;e[224]=321;e[225]=322;e[226]=352;e[227]=353;e[228]=381;e[229]=382;e[233]=221;e[234]=253;e[252]=263;e[253]=268;e[254]=269;e[258]=258;e[260]=260;e[261]=261;e[265]=280;e[266]=281;e[267]=282;e[268]=283;e[269]=313;e[275]=323;e[276]=324;e[278]=328;e[283]=344;e[284]=345;e[285]=346;e[286]=347;e[292]=367;e[295]=377;e[296]=378;e[298]=380;e[305]=963;e[306]=964;e[307]=966;e[308]=8215;e[309]=8252;e[310]=8319;e[311]=8359;e[312]=8592;e[313]=8593;e[337]=9552;e[493]=1039;e[494]=1040;e[672]=1488;e[673]=1489;e[674]=1490;e[675]=1491;e[676]=1492;e[677]=1493;e[678]=1494;e[679]=1495;e[680]=1496;e[681]=1497;e[682]=1498;e[683]=1499;e[684]=1500;e[685]=1501;e[686]=1502;e[687]=1503;e[688]=1504;e[689]=1505;e[690]=1506;e[691]=1507;e[692]=1508;e[693]=1509;e[694]=1510;e[695]=1511;e[696]=1512;e[697]=1513;e[698]=1514;e[705]=1524;e[706]=8362;e[710]=64288;e[711]=64298;e[759]=1617;e[761]=1776;e[763]=1778;e[775]=1652;e[777]=1764;e[778]=1780;e[779]=1781;e[780]=1782;e[782]=771;e[783]=64726;e[786]=8363;e[788]=8532;e[790]=768;e[791]=769;e[792]=768;e[795]=803;e[797]=64336;e[798]=64337;e[799]=64342;e[800]=64343;e[801]=64344;e[802]=64345;e[803]=64362;e[804]=64363;e[805]=64364;e[2424]=7821;e[2425]=7822;e[2426]=7823;e[2427]=7824;e[2428]=7825;e[2429]=7826;e[2430]=7827;e[2433]=7682;e[2678]=8045;e[2679]=8046;e[2830]=1552;e[2838]=686;e[2840]=751;e[2842]=753;e[2843]=754;e[2844]=755;e[2846]=757;e[2856]=767;e[2857]=848;e[2858]=849;e[2862]=853;e[2863]=854;e[2864]=855;e[2865]=861;e[2866]=862;e[2906]=7460;e[2908]=7462;e[2909]=7463;e[2910]=7464;e[2912]=7466;e[2913]=7467;e[2914]=7468;e[2916]=7470;e[2917]=7471;e[2918]=7472;e[2920]=7474;e[2921]=7475;e[2922]=7476;e[2924]=7478;e[2925]=7479;e[2926]=7480;e[2928]=7482;e[2929]=7483;e[2930]=7484;e[2932]=7486;e[2933]=7487;e[2934]=7488;e[2936]=7490;e[2937]=7491;e[2938]=7492;e[2940]=7494;e[2941]=7495;e[2942]=7496;e[2944]=7498;e[2946]=7500;e[2948]=7502;e[2950]=7504;e[2951]=7505;e[2952]=7506;e[2954]=7508;e[2955]=7509;e[2956]=7510;e[2958]=7512;e[2959]=7513;e[2960]=7514;e[2962]=7516;e[2963]=7517;e[2964]=7518;e[2966]=7520;e[2967]=7521;e[2968]=7522;e[2970]=7524;e[2971]=7525;e[2972]=7526;e[2974]=7528;e[2975]=7529;e[2976]=7530;e[2978]=1537;e[2979]=1538;e[2980]=1539;e[2982]=1549;e[2983]=1551;e[2984]=1552;e[2986]=1554;e[2987]=1555;e[2988]=1556;e[2990]=1623;e[2991]=1624;e[2995]=1775;e[2999]=1791;e[3002]=64290;e[3003]=64291;e[3004]=64292;e[3006]=64294;e[3007]=64295;e[3008]=64296;e[3011]=1900;e[3014]=8223;e[3015]=8244;e[3017]=7532;e[3018]=7533;e[3019]=7534;e[3075]=7590;e[3076]=7591;e[3079]=7594;e[3080]=7595;e[3083]=7598;e[3084]=7599;e[3087]=7602;e[3088]=7603;e[3091]=7606;e[3092]=7607;e[3095]=7610;e[3096]=7611;e[3099]=7614;e[3100]=7615;e[3103]=7618;e[3104]=7619;e[3107]=8337;e[3108]=8338;e[3116]=1884;e[3119]=1885;e[3120]=1885;e[3123]=1886;e[3124]=1886;e[3127]=1887;e[3128]=1887;e[3131]=1888;e[3132]=1888;e[3135]=1889;e[3136]=1889;e[3139]=1890;e[3140]=1890;e[3143]=1891;e[3144]=1891;e[3147]=1892;e[3148]=1892;e[3153]=580;e[3154]=581;e[3157]=584;e[3158]=585;e[3161]=588;e[3162]=589;e[3165]=891;e[3166]=892;e[3169]=1274;e[3170]=1275;e[3173]=1278;e[3174]=1279;e[3181]=7622;e[3182]=7623;e[3282]=11799;e[3316]=578;e[3379]=42785;e[3393]=1159;e[3416]=8377})),Pi=getLookupTableFactory((function(e){e[227]=322;e[264]=261;e[291]=346})),Wi=getLookupTableFactory((function(e){e[1]=32;e[4]=65;e[5]=192;e[6]=193;e[9]=196;e[17]=66;e[18]=67;e[21]=268;e[24]=68;e[28]=69;e[29]=200;e[30]=201;e[32]=282;e[38]=70;e[39]=71;e[44]=72;e[47]=73;e[48]=204;e[49]=205;e[58]=74;e[60]=75;e[62]=76;e[68]=77;e[69]=78;e[75]=79;e[76]=210;e[80]=214;e[87]=80;e[89]=81;e[90]=82;e[92]=344;e[94]=83;e[97]=352;e[100]=84;e[104]=85;e[109]=220;e[115]=86;e[116]=87;e[121]=88;e[122]=89;e[124]=221;e[127]=90;e[129]=381;e[258]=97;e[259]=224;e[260]=225;e[263]=228;e[268]=261;e[271]=98;e[272]=99;e[273]=263;e[275]=269;e[282]=100;e[286]=101;e[287]=232;e[288]=233;e[290]=283;e[295]=281;e[296]=102;e[336]=103;e[346]=104;e[349]=105;e[350]=236;e[351]=237;e[361]=106;e[364]=107;e[367]=108;e[371]=322;e[373]=109;e[374]=110;e[381]=111;e[382]=242;e[383]=243;e[386]=246;e[393]=112;e[395]=113;e[396]=114;e[398]=345;e[400]=115;e[401]=347;e[403]=353;e[410]=116;e[437]=117;e[442]=252;e[448]=118;e[449]=119;e[454]=120;e[455]=121;e[457]=253;e[460]=122;e[462]=382;e[463]=380;e[853]=44;e[855]=58;e[856]=46;e[876]=47;e[878]=45;e[882]=45;e[894]=40;e[895]=41;e[896]=91;e[897]=93;e[923]=64;e[1004]=48;e[1005]=49;e[1006]=50;e[1007]=51;e[1008]=52;e[1009]=53;e[1010]=54;e[1011]=55;e[1012]=56;e[1013]=57;e[1081]=37;e[1085]=43;e[1086]=45}));function getStandardFontName(e){const t=normalizeFontName(e);return Yi()[t]}function isKnownFontName(e){const t=normalizeFontName(e);return!!(Yi()[t]||Ki()[t]||Ti()[t]||qi()[t])}class ToUnicodeMap{constructor(e=[]){this._map=e}get length(){return this._map.length}forEach(e){for(const t in this._map)e(t,this._map[t].codePointAt(0))}has(e){return void 0!==this._map[e]}get(e){return this._map[e]}charCodeOf(e){const t=this._map;if(t.length<=65536)return t.indexOf(e);for(const i in t)if(t[i]===e)return 0|i;return-1}amend(e){for(const t in e)this._map[t]=e[t]}}class IdentityToUnicodeMap{constructor(e,t){this.firstChar=e;this.lastChar=t}get length(){return this.lastChar+1-this.firstChar}forEach(e){for(let t=this.firstChar,i=this.lastChar;t<=i;t++)e(t,t)}has(e){return this.firstChar<=e&&e<=this.lastChar}get(e){if(this.firstChar<=e&&e<=this.lastChar)return String.fromCharCode(e)}charCodeOf(e){return Number.isInteger(e)&&e>=this.firstChar&&e<=this.lastChar?e:-1}amend(e){unreachable("Should not call amend()")}}class CFFFont{constructor(e,t){this.properties=t;const i=new CFFParser(e,t,Ri);this.cff=i.parse();this.cff.duplicateFirstGlyph();const a=new CFFCompiler(this.cff);this.seacs=this.cff.seacs;try{this.data=a.compile()}catch{warn("Failed to compile font "+t.loadedName);this.data=e}this._createBuiltInEncoding()}get numGlyphs(){return this.cff.charStrings.count}getCharset(){return this.cff.charset.charset}getGlyphMapping(){const e=this.cff,t=this.properties,{cidToGidMap:i,cMap:a}=t,s=e.charset.charset;let r,n;if(t.composite){let t,g;if(i?.length>0){t=Object.create(null);for(let e=0,a=i.length;e=0){const a=i[t];a&&(s[e]=a)}}s.length>0&&(this.properties.builtInEncoding=s)}}function getUint32(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}function getUint16(e,t){return e[t]<<8|e[t+1]}function getInt16(e,t){return(e[t]<<24|e[t+1]<<16)>>16}function getInt8(e,t){return e[t]<<24>>24}function getFloat214(e,t){return getInt16(e,t)/16384}function getSubroutineBias(e){const t=e.length;let i=32768;t<1240?i=107:t<33900&&(i=1131);return i}function parseCmap(e,t,i){const a=1===getUint16(e,t+2)?getUint32(e,t+8):getUint32(e,t+16),s=getUint16(e,t+a);let r,n,g;if(4===s){getUint16(e,t+a+2);const i=getUint16(e,t+a+6)>>1;n=t+a+14;r=[];for(g=0;g>1;i0;)C.push({flags:r})}for(i=0;i>1;p=!0;break;case 4:n+=s.pop();moveTo(r,n);p=!0;break;case 5:for(;s.length>0;){r+=s.shift();n+=s.shift();lineTo(r,n)}break;case 6:for(;s.length>0;){r+=s.shift();lineTo(r,n);if(0===s.length)break;n+=s.shift();lineTo(r,n)}break;case 7:for(;s.length>0;){n+=s.shift();lineTo(r,n);if(0===s.length)break;r+=s.shift();lineTo(r,n)}break;case 8:for(;s.length>0;){c=r+s.shift();h=n+s.shift();C=c+s.shift();l=h+s.shift();r=C+s.shift();n=l+s.shift();bezierCurveTo(c,h,C,l,r,n)}break;case 10:d=s.pop();f=null;if(i.isCFFCIDFont){const e=i.fdSelect.getFDIndex(a);if(e>=0&&eMath.abs(n-t)?r+=s.shift():n+=s.shift();bezierCurveTo(c,h,C,l,r,n);break;default:throw new FormatError(`unknown operator: 12 ${m}`)}break;case 14:if(s.length>=4){const e=s.pop(),a=s.pop();n=s.pop();r=s.pop();t.save();t.translate(r,n);let g=lookupCmap(i.cmap,String.fromCharCode(i.glyphNameMap[hi[e]]));compileCharString(i.glyphs[g.glyphId],t,i,g.glyphId);t.restore();g=lookupCmap(i.cmap,String.fromCharCode(i.glyphNameMap[hi[a]]));compileCharString(i.glyphs[g.glyphId],t,i,g.glyphId)}return;case 19:case 20:g+=s.length>>1;o+=g+7>>3;p=!0;break;case 21:n+=s.pop();r+=s.pop();moveTo(r,n);p=!0;break;case 22:r+=s.pop();moveTo(r,n);p=!0;break;case 24:for(;s.length>2;){c=r+s.shift();h=n+s.shift();C=c+s.shift();l=h+s.shift();r=C+s.shift();n=l+s.shift();bezierCurveTo(c,h,C,l,r,n)}r+=s.shift();n+=s.shift();lineTo(r,n);break;case 25:for(;s.length>6;){r+=s.shift();n+=s.shift();lineTo(r,n)}c=r+s.shift();h=n+s.shift();C=c+s.shift();l=h+s.shift();r=C+s.shift();n=l+s.shift();bezierCurveTo(c,h,C,l,r,n);break;case 26:s.length%2&&(r+=s.shift());for(;s.length>0;){c=r;h=n+s.shift();C=c+s.shift();l=h+s.shift();r=C;n=l+s.shift();bezierCurveTo(c,h,C,l,r,n)}break;case 27:s.length%2&&(n+=s.shift());for(;s.length>0;){c=r+s.shift();h=n;C=c+s.shift();l=h+s.shift();r=C+s.shift();n=l;bezierCurveTo(c,h,C,l,r,n)}break;case 28:s.push((e[o]<<24|e[o+1]<<16)>>16);o+=2;break;case 29:d=s.pop()+i.gsubrsBias;f=i.gsubrs[d];f&&parse(f);break;case 30:for(;s.length>0;){c=r;h=n+s.shift();C=c+s.shift();l=h+s.shift();r=C+s.shift();n=l+(1===s.length?s.shift():0);bezierCurveTo(c,h,C,l,r,n);if(0===s.length)break;c=r+s.shift();h=n;C=c+s.shift();l=h+s.shift();n=l+s.shift();r=C+(1===s.length?s.shift():0);bezierCurveTo(c,h,C,l,r,n)}break;case 31:for(;s.length>0;){c=r+s.shift();h=n;C=c+s.shift();l=h+s.shift();n=l+s.shift();r=C+(1===s.length?s.shift():0);bezierCurveTo(c,h,C,l,r,n);if(0===s.length)break;c=r;h=n+s.shift();C=c+s.shift();l=h+s.shift();r=C+s.shift();n=l+(1===s.length?s.shift():0);bezierCurveTo(c,h,C,l,r,n)}break;default:if(m<32)throw new FormatError(`unknown operator: ${m}`);if(m<247)s.push(m-139);else if(m<251)s.push(256*(m-247)+e[o++]+108);else if(m<255)s.push(256*-(m-251)-e[o++]-108);else{s.push((e[o]<<24|e[o+1]<<16|e[o+2]<<8|e[o+3])/65536);o+=4}}p&&(s.length=0)}}(e)}class Commands{cmds=[];transformStack=[];currentTransform=[1,0,0,1,0,0];add(e,t){if(t){const[i,a,s,r,n,g]=this.currentTransform;for(let e=0,o=t.length;e=0&&e2*getUint16(e,t)}const r=[];let n=s(t,0);for(let i=a;ie+(t.getSize()+3&-4)),0)}write(){const e=this.getSize(),t=new DataView(new ArrayBuffer(e)),i=e>131070,a=i?4:2,s=new DataView(new ArrayBuffer((this.glyphs.length+1)*a));i?s.setUint32(0,0):s.setUint16(0,0);let r=0,n=0;for(const e of this.glyphs){r+=e.write(r,t);r=r+3&-4;n+=a;i?s.setUint32(n,r):s.setUint16(n,r>>1)}return{isLocationLong:i,loca:new Uint8Array(s.buffer),glyf:new Uint8Array(t.buffer)}}scale(e){for(let t=0,i=this.glyphs.length;te+t.getSize()),0);return this.header.getSize()+e}write(e,t){if(!this.header)return 0;const i=e;e+=this.header.write(e,t);if(this.simple)e+=this.simple.write(e,t);else for(const i of this.composites)e+=i.write(e,t);return e-i}scale(e){if(!this.header)return;const t=(this.header.xMin+this.header.xMax)/2;this.header.scale(t,e);if(this.simple)this.simple.scale(t,e);else for(const i of this.composites)i.scale(t,e)}}class GlyphHeader{constructor({numberOfContours:e,xMin:t,yMin:i,xMax:a,yMax:s}){this.numberOfContours=e;this.xMin=t;this.yMin=i;this.xMax=a;this.yMax=s}static parse(e,t){return[10,new GlyphHeader({numberOfContours:t.getInt16(e),xMin:t.getInt16(e+2),yMin:t.getInt16(e+4),xMax:t.getInt16(e+6),yMax:t.getInt16(e+8)})]}getSize(){return 10}write(e,t){t.setInt16(e,this.numberOfContours);t.setInt16(e+2,this.xMin);t.setInt16(e+4,this.yMin);t.setInt16(e+6,this.xMax);t.setInt16(e+8,this.yMax);return 10}scale(e,t){this.xMin=Math.round(e+(this.xMin-e)*t);this.xMax=Math.round(e+(this.xMax-e)*t)}}class Contour{constructor({flags:e,xCoordinates:t,yCoordinates:i}){this.xCoordinates=t;this.yCoordinates=i;this.flags=e}}class SimpleGlyph{constructor({contours:e,instructions:t}){this.contours=e;this.instructions=t}static parse(e,t,i){const a=[];for(let s=0;s255?e+=2:g>0&&(e+=1);t=r;g=Math.abs(n-i);g>255?e+=2:g>0&&(e+=1);i=n}}return e}write(e,t){const i=e,a=[],s=[],r=[];let n=0,g=0;for(const i of this.contours){for(let e=0,t=i.xCoordinates.length;e=0?18:2;a.push(e)}else a.push(c)}n=o;const C=i.yCoordinates[e];c=C-g;if(0===c){t|=32;s.push(0)}else{const e=Math.abs(c);if(e<=255){t|=c>=0?36:4;s.push(e)}else s.push(c)}g=C;r.push(t)}t.setUint16(e,a.length-1);e+=2}t.setUint16(e,this.instructions.length);e+=2;if(this.instructions.length){new Uint8Array(t.buffer,0,t.buffer.byteLength).set(this.instructions,e);e+=this.instructions.length}for(const i of r)t.setUint8(e++,i);for(let i=0,s=a.length;i=-128&&this.argument1<=127&&this.argument2>=-128&&this.argument2<=127||(e+=2):this.argument1>=0&&this.argument1<=255&&this.argument2>=0&&this.argument2<=255||(e+=2);return e}write(e,t){const i=e;2&this.flags?this.argument1>=-128&&this.argument1<=127&&this.argument2>=-128&&this.argument2<=127||(this.flags|=1):this.argument1>=0&&this.argument1<=255&&this.argument2>=0&&this.argument2<=255||(this.flags|=1);t.setUint16(e,this.flags);t.setUint16(e+2,this.glyphIndex);e+=4;if(1&this.flags){if(2&this.flags){t.setInt16(e,this.argument1);t.setInt16(e+2,this.argument2)}else{t.setUint16(e,this.argument1);t.setUint16(e+2,this.argument2)}e+=4}else{t.setUint8(e,this.argument1);t.setUint8(e+1,this.argument2);e+=2}if(256&this.flags){t.setUint16(e,this.instructions.length);e+=2;if(this.instructions.length){new Uint8Array(t.buffer,0,t.buffer.byteLength).set(this.instructions,e);e+=this.instructions.length}}return e-i}scale(e,t){}}function writeInt16(e,t,i){e[t]=i>>8&255;e[t+1]=255&i}function writeInt32(e,t,i){e[t]=i>>24&255;e[t+1]=i>>16&255;e[t+2]=i>>8&255;e[t+3]=255&i}function writeData(e,t,i){if(i instanceof Uint8Array)e.set(i,t);else if("string"==typeof i)for(let a=0,s=i.length;ai;){i<<=1;a++}const s=i*t;return{range:s,entry:a,rangeShift:t*e-s}}toArray(){let e=this.sfnt;const t=this.tables,i=Object.keys(t);i.sort();const a=i.length;let s,r,n,g,o,c=12+16*a;const C=[c];for(s=0;s>>0;C.push(c)}const h=new Uint8Array(c);for(s=0;s>>0}writeInt32(h,c+4,e);writeInt32(h,c+8,C[s]);writeInt32(h,c+12,t[o].length);c+=16}return h}addTable(e,t){if(e in this.tables)throw new Error("Table "+e+" already exists");this.tables[e]=t}}const Zi=[4],Vi=[5],zi=[6],_i=[7],$i=[8],Aa=[12,35],ea=[14],ta=[21],ia=[22],aa=[30],sa=[31];class Type1CharString{constructor(){this.width=0;this.lsb=0;this.flexing=!1;this.output=[];this.stack=[]}convert(e,t,i){const a=e.length;let s,r,n,g=!1;for(let o=0;oa)return!0;const s=a-e;for(let e=s;e>8&255,255&t);else{t=65536*t|0;this.output.push(255,t>>24&255,t>>16&255,t>>8&255,255&t)}}this.output.push(...t);i?this.stack.splice(s,e):this.stack.length=0;return!1}}function isHexDigit(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function decrypt(e,t,i){if(i>=e.length)return new Uint8Array(0);let a,s,r=0|t;for(a=0;a>8;r=52845*(t+r)+22719&65535}return g}function isSpecial(e){return 47===e||91===e||93===e||123===e||125===e||40===e||41===e}class Type1Parser{constructor(e,t,i){if(t){const t=e.getBytes(),i=!((isHexDigit(t[0])||isWhiteSpace(t[0]))&&isHexDigit(t[1])&&isHexDigit(t[2])&&isHexDigit(t[3])&&isHexDigit(t[4])&&isHexDigit(t[5])&&isHexDigit(t[6])&&isHexDigit(t[7]));e=new Stream(i?decrypt(t,55665,4):function decryptAscii(e,t,i){let a=0|t;const s=e.length,r=new Uint8Array(s>>>1);let n,g;for(n=0,g=0;n>8;a=52845*(e+a)+22719&65535}}return r.slice(i,g)}(t,55665,4))}this.seacAnalysisEnabled=!!i;this.stream=e;this.nextChar()}readNumberArray(){this.getToken();const e=[];for(;;){const t=this.getToken();if(null===t||"]"===t||"}"===t)break;e.push(parseFloat(t||0))}return e}readNumber(){const e=this.getToken();return parseFloat(e||0)}readInt(){const e=this.getToken();return 0|parseInt(e||0,10)}readBoolean(){return"true"===this.getToken()?1:0}nextChar(){return this.currentChar=this.stream.getByte()}prevChar(){this.stream.skip(-2);return this.currentChar=this.stream.getByte()}getToken(){let e=!1,t=this.currentChar;for(;;){if(-1===t)return null;if(e)10!==t&&13!==t||(e=!1);else if(37===t)e=!0;else if(!isWhiteSpace(t))break;t=this.nextChar()}if(isSpecial(t)){this.nextChar();return String.fromCharCode(t)}let i="";do{i+=String.fromCharCode(t);t=this.nextChar()}while(t>=0&&!isWhiteSpace(t)&&!isSpecial(t));return i}readCharStrings(e,t){return-1===t?e:decrypt(e,4330,t)}extractFontProgram(e){const t=this.stream,i=[],a=[],s=Object.create(null);s.lenIV=4;const r={subrs:[],charstrings:[],properties:{privateData:s}};let n,g,o,c;for(;null!==(n=this.getToken());)if("/"===n){n=this.getToken();switch(n){case"CharStrings":this.getToken();this.getToken();this.getToken();this.getToken();for(;;){n=this.getToken();if(null===n||"end"===n)break;if("/"!==n)continue;const e=this.getToken();g=this.readInt();this.getToken();o=g>0?t.getBytes(g):new Uint8Array(0);c=r.properties.privateData.lenIV;const i=this.readCharStrings(o,c);this.nextChar();n=this.getToken();"noaccess"===n?this.getToken():"/"===n&&this.prevChar();a.push({glyph:e,encoded:i})}break;case"Subrs":this.readInt();this.getToken();for(;"dup"===this.getToken();){const e=this.readInt();g=this.readInt();this.getToken();o=g>0?t.getBytes(g):new Uint8Array(0);c=r.properties.privateData.lenIV;const a=this.readCharStrings(o,c);this.nextChar();n=this.getToken();"noaccess"===n&&this.getToken();i[e]=a}break;case"BlueValues":case"OtherBlues":case"FamilyBlues":case"FamilyOtherBlues":const e=this.readNumberArray();e.length>0&&e.length,0;break;case"StemSnapH":case"StemSnapV":r.properties.privateData[n]=this.readNumberArray();break;case"StdHW":case"StdVW":r.properties.privateData[n]=this.readNumberArray()[0];break;case"BlueShift":case"lenIV":case"BlueFuzz":case"BlueScale":case"LanguageGroup":r.properties.privateData[n]=this.readNumber();break;case"ExpansionFactor":r.properties.privateData[n]=this.readNumber()||.06;break;case"ForceBold":r.properties.privateData[n]=this.readBoolean()}}for(const{encoded:t,glyph:s}of a){const a=new Type1CharString,n=a.convert(t,i,this.seacAnalysisEnabled);let g=a.output;n&&(g=[14]);const o={glyphName:s,charstring:g,width:a.width,lsb:a.lsb,seac:a.seac};".notdef"===s?r.charstrings.unshift(o):r.charstrings.push(o);if(e.builtInEncoding){const t=e.builtInEncoding.indexOf(s);t>-1&&void 0===e.widths[t]&&t>=e.firstChar&&t<=e.lastChar&&(e.widths[t]=a.width)}}return r}extractFontHeader(e){let t;for(;null!==(t=this.getToken());)if("/"===t){t=this.getToken();switch(t){case"FontMatrix":const i=this.readNumberArray();e.fontMatrix=i;break;case"Encoding":const a=this.getToken();let s;if(/^\d+$/.test(a)){s=[];const e=0|parseInt(a,10);this.getToken();for(let i=0;i=s){n+=i;for(;n=0&&(a[e]=s)}}return type1FontGlyphMapping(e,a,i)}hasGlyphId(e){if(e<0||e>=this.numGlyphs)return!1;if(0===e)return!0;return this.charstrings[e-1].charstring.length>0}getSeacs(e){const t=[];for(let i=0,a=e.length;i0;e--)t[e]-=t[e-1];Q.setByName(e,t)}r.topDict.privateDict=Q;const u=new CFFIndex;for(C=0,h=a.length;C0&&e.toUnicode.amend(t)}class fonts_Glyph{constructor(e,t,i,a,s,r,n,g,o){this.originalCharCode=e;this.fontChar=t;this.unicode=i;this.accent=a;this.width=s;this.vmetric=r;this.operatorListId=n;this.isSpace=g;this.isInFont=o}get category(){return shadow(this,"category",function getCharUnicodeCategory(e){const t=ki.get(e);if(t)return t;const i=e.match(Si),a={isWhitespace:!!i?.[1],isZeroWidthDiacritic:!!i?.[2],isInvisibleFormatMark:!!i?.[3]};ki.set(e,a);return a}(this.unicode),!0)}}function int16(e,t){return(e<<8)+t}function writeSignedInt16(e,t,i){e[t+1]=i;e[t]=i>>>8}function signedInt16(e,t){const i=(e<<8)+t;return 32768&i?i-65536:i}function string16(e){return String.fromCharCode(e>>8&255,255&e)}function safeString16(e){e>32767?e=32767:e<-32768&&(e=-32768);return String.fromCharCode(e>>8&255,255&e)}function isTrueTypeCollectionFile(e){return"ttcf"===bytesToString(e.peekBytes(4))}function getFontFileType(e,{type:t,subtype:i,composite:a}){let s,r;if(function isTrueTypeFile(e){const t=e.peekBytes(4);return 65536===readUint32(t,0)||"true"===bytesToString(t)}(e)||isTrueTypeCollectionFile(e))s=a?"CIDFontType2":"TrueType";else if(function isOpenTypeFile(e){return"OTTO"===bytesToString(e.peekBytes(4))}(e))s=a?"CIDFontType2":"OpenType";else if(function isType1File(e){const t=e.peekBytes(2);return 37===t[0]&&33===t[1]||128===t[0]&&1===t[1]}(e))s=a?"CIDFontType0":"MMType1"===t?"MMType1":"Type1";else if(function isCFFFile(e){const t=e.peekBytes(4);return t[0]>=1&&t[3]>=1&&t[3]<=4}(e))if(a){s="CIDFontType0";r="CIDFontType0C"}else{s="MMType1"===t?"MMType1":"Type1";r="Type1C"}else{warn("getFontFileType: Unable to detect correct font file Type/Subtype.");s=t;r=i}return[s,r]}function applyStandardFontGlyphMap(e,t){for(const i in t)e[+i]=t[i]}function buildToFontChar(e,t,i){const a=[];let s;for(let i=0,r=e.length;iC){o++;if(o>=ra.length){warn("Ran out of space in font private use area.");break}c=ra[o][0];C=ra[o][1]}const E=c++;0===Q&&(Q=i);let u=a.get(l);"string"==typeof u&&(u=u.codePointAt(0));if(u&&!(h=u,ra[0][0]<=h&&h<=ra[0][1]||ra[1][0]<=h&&h<=ra[1][1])&&!g.has(Q)){r.set(u,Q);g.add(Q)}s[E]=Q;n[l]=E}var h;return{toFontChar:n,charCodeToGlyphId:s,toUnicodeExtraMap:r,nextAvailableFontCharCode:c}}function createCmapTable(e,t,i){const a=function getRanges(e,t,i){const a=[];for(const t in e)e[t]>=i||a.push({fontCharCode:0|t,glyphId:e[t]});if(t)for(const[e,s]of t)s>=i||a.push({fontCharCode:e,glyphId:s});0===a.length&&a.push({fontCharCode:0,glyphId:0});a.sort((function fontGetRangesSort(e,t){return e.fontCharCode-t.fontCharCode}));const s=[],r=a.length;for(let e=0;e65535?2:1;let r,n,g,o,c="\0\0"+string16(s)+"\0\0"+string32(4+8*s);for(r=a.length-1;r>=0&&!(a[r][0]<=65535);--r);const C=r+1;a[r][0]<65535&&65535===a[r][1]&&(a[r][1]=65534);const h=a[r][1]<65535?1:0,l=C+h,Q=OpenTypeFileBuilder.getSearchParams(l,2);let E,u,d,f,p="",m="",y="",w="",D="",b=0;for(r=0,n=C;r0){m+="ÿÿ";p+="ÿÿ";y+="\0";w+="\0\0"}const F="\0\0"+string16(2*l)+string16(Q.range)+string16(Q.entry)+string16(Q.rangeShift)+m+"\0\0"+p+y+w+D;let S="",k="";if(s>1){c+="\0\0\n"+string32(4+8*s+4+F.length);S="";for(r=0,n=a.length;re||!g)&&(g=e);o 123 are reserved for internal usage");n|=1<65535&&(o=65535)}else{g=0;o=255}const C=e.bbox||[0,0,0,0],h=i.unitsPerEm||(e.fontMatrix?1/Math.max(...e.fontMatrix.slice(0,4).map(Math.abs)):1e3),l=e.ascentScaled?1:h/na,Q=i.ascent||Math.round(l*(e.ascent||C[3]));let E=i.descent||Math.round(l*(e.descent||C[1]));E>0&&e.descent>0&&C[1]<0&&(E=-E);const u=i.yMax||Q,d=-i.yMin||-E;return"\0$ô\0\0\0Š»\0\0\0ŒŠ»\0\0ß\x001\0\0\0\0"+String.fromCharCode(e.fixedPitch?9:0)+"\0\0\0\0\0\0"+string32(a)+string32(s)+string32(r)+string32(n)+"*21*"+string16(e.italicAngle?1:0)+string16(g||e.firstChar)+string16(o||e.lastChar)+string16(Q)+string16(E)+"\0d"+string16(u)+string16(d)+"\0\0\0\0\0\0\0\0"+string16(e.xHeight)+string16(e.capHeight)+string16(0)+string16(g||e.firstChar)+"\0"}function createPostTable(e){return"\0\0\0"+string32(Math.floor(65536*e.italicAngle))+"\0\0\0\0"+string32(e.fixedPitch?1:0)+"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"}function createPostscriptName(e){return e.replaceAll(/[^\x21-\x7E]|[[\](){}<>/%]/g,"").slice(0,63)}function createNameTable(e,t){t||(t=[[],[]]);const i=[t[0][0]||"Original licence",t[0][1]||e,t[0][2]||"Unknown",t[0][3]||"uniqueID",t[0][4]||e,t[0][5]||"Version 0.11",t[0][6]||createPostscriptName(e),t[0][7]||"Unknown",t[0][8]||"Unknown",t[0][9]||"Unknown"],a=[];let s,r,n,g,o;for(s=0,r=i.length;s0;if((n||g)&&"CIDFontType2"===i&&this.cidEncoding.startsWith("Identity-")){const i=e.cidToGidMap,a=[];applyStandardFontGlyphMap(a,Oi());/Arial-?Black/i.test(t)?applyStandardFontGlyphMap(a,Pi()):/Calibri/i.test(t)&&applyStandardFontGlyphMap(a,Wi());if(i){for(const e in a){const t=a[e];void 0!==i[t]&&(a[+e]=i[t])}i.length!==this.toUnicode.length&&e.hasIncludedToUnicodeMap&&this.toUnicode instanceof IdentityToUnicodeMap&&this.toUnicode.forEach((function(e,t){const s=a[e];void 0===i[s]&&(a[+e]=t)}))}this.toUnicode instanceof IdentityToUnicodeMap||this.toUnicode.forEach((function(e,t){a[+e]=t}));this.toFontChar=a;this.toUnicode=new ToUnicodeMap(a)}else if(/Symbol/i.test(a))this.toFontChar=buildToFontChar(Bi,wi(),this.differences);else if(/Dingbats/i.test(a))this.toFontChar=buildToFontChar(Qi,Di(),this.differences);else if(n||g){const e=buildToFontChar(this.defaultEncoding,wi(),this.differences);"CIDFontType2"!==i||this.cidEncoding.startsWith("Identity-")||this.toUnicode instanceof IdentityToUnicodeMap||this.toUnicode.forEach((function(t,i){e[+t]=i}));this.toFontChar=e}else{const e=wi(),i=[];this.toUnicode.forEach(((t,a)=>{if(!this.composite){const i=getUnicodeForGlyph(this.differences[t]||this.defaultEncoding[t],e);-1!==i&&(a=i)}i[+t]=a}));this.composite&&this.toUnicode instanceof IdentityToUnicodeMap&&/Tahoma|Verdana/i.test(t)&&applyStandardFontGlyphMap(i,Oi());this.toFontChar=i}amendFallbackToUnicode(e);this.loadedName=a.split("-",1)[0]}checkAndRepair(e,t,i){const a=["OS/2","cmap","head","hhea","hmtx","maxp","name","post","loca","glyf","fpgm","prep","cvt ","CFF "];function readTables(e,t){const i=Object.create(null);i["OS/2"]=null;i.cmap=null;i.head=null;i.hhea=null;i.hmtx=null;i.maxp=null;i.name=null;i.post=null;for(let s=0;s>>0,a=e.getInt32()>>>0,s=e.getInt32()>>>0,r=e.pos;e.pos=e.start||0;e.skip(a);const n=e.getBytes(s);e.pos=r;if("head"===t){n[8]=n[9]=n[10]=n[11]=0;n[17]|=32}return{tag:t,checksum:i,length:s,offset:a,data:n}}function readOpenTypeHeader(e){return{version:e.getString(4),numTables:e.getUint16(),searchRange:e.getUint16(),entrySelector:e.getUint16(),rangeShift:e.getUint16()}}function sanitizeGlyph(e,t,i,a,s,r){const n={length:0,sizeOfInstructions:0};if(t<0||t>=e.length||i>e.length||i-t<=12)return n;const g=e.subarray(t,i),o=signedInt16(g[2],g[3]),c=signedInt16(g[4],g[5]),C=signedInt16(g[6],g[7]),h=signedInt16(g[8],g[9]);if(o>C){writeSignedInt16(g,2,C);writeSignedInt16(g,6,o)}if(c>h){writeSignedInt16(g,4,h);writeSignedInt16(g,8,c)}const l=signedInt16(g[0],g[1]);if(l<0){if(l<-1)return n;a.set(g,s);n.length=g.length;return n}let Q,E=10,u=0;for(Q=0;Qg.length)return n;if(!r&&f>0){a.set(g.subarray(0,d),s);a.set([0,0],s+d);a.set(g.subarray(p,y),s+d+2);y-=f;g.length-y>3&&(y=y+3&-4);n.length=y;return n}if(g.length-y>3){y=y+3&-4;a.set(g.subarray(0,y),s);n.length=y;return n}a.set(g,s);n.length=g.length;return n}function readNameTable(e){const i=(t.start||0)+e.offset;t.pos=i;const a=[[],[]],s=[],r=e.length,n=i+r;if(0!==t.getUint16()||r<6)return[a,s];const g=t.getUint16(),o=t.getUint16();let c,C;for(c=0;cn)continue;t.pos=r;const g=e.name;if(e.encoding){let i="";for(let a=0,s=e.length;a0&&(c+=e-1)}}else{if(d||p){warn("TT: nested FDEFs not allowed");u=!0}d=!0;h=c;n=l.pop();t.functionsDefined[n]={data:o,i:c}}else if(!d&&!p){n=l.at(-1);if(isNaN(n))info("TT: CALL empty stack (or invalid entry).");else{t.functionsUsed[n]=!0;if(n in t.functionsStackDeltas){const e=l.length+t.functionsStackDeltas[n];if(e<0){warn("TT: CALL invalid functions stack delta.");t.hintsValid=!1;return}l.length=e}else if(n in t.functionsDefined&&!E.includes(n)){Q.push({data:o,i:c,stackTop:l.length-1});E.push(n);g=t.functionsDefined[n];if(!g){warn("TT: CALL non-existent function");t.hintsValid=!1;return}o=g.data;c=g.i}}}if(!d&&!p){let t=0;e<=142?t=s[e]:e>=192&&e<=223?t=-1:e>=224&&(t=-2);if(e>=113&&e<=117){a=l.pop();isNaN(a)||(t=2*-a)}for(;t<0&&l.length>0;){l.pop();t++}for(;t>0;){l.push(NaN);t--}}}t.tooComplexToFollowFunctions=u;const m=[o];c>o.length&&m.push(new Uint8Array(c-o.length));if(h>C){warn("TT: complementing a missing function tail");m.push(new Uint8Array([34,45]))}!function foldTTTable(e,t){if(t.length>1){let i,a,s=0;for(i=0,a=t.length;i>>0,r=[];for(let t=0;t>>0);const n={ttcTag:t,majorVersion:i,minorVersion:a,numFonts:s,offsetTable:r};switch(i){case 1:return n;case 2:n.dsigTag=e.getInt32()>>>0;n.dsigLength=e.getInt32()>>>0;n.dsigOffset=e.getInt32()>>>0;return n}throw new FormatError(`Invalid TrueType Collection majorVersion: ${i}.`)}(e),s=t.split("+");let r;for(let n=0;n0||!(i.cMap instanceof IdentityCMap));if("OTTO"===r.version&&!t||!n.head||!n.hhea||!n.maxp||!n.post){o=new Stream(n["CFF "].data);g=new CFFFont(o,i);adjustWidths(i);return this.convert(e,g,i)}delete n.glyf;delete n.loca;delete n.fpgm;delete n.prep;delete n["cvt "];this.isOpenType=!0}if(!n.maxp)throw new FormatError('Required "maxp" table is not found');t.pos=(t.start||0)+n.maxp.offset;let C=t.getInt32();const h=t.getUint16();if(65536!==C&&20480!==C){if(6===n.maxp.length)C=20480;else{if(!(n.maxp.length>=32))throw new FormatError('"maxp" table has a wrong version number');C=65536}!function writeUint32(e,t,i){e[t+3]=255&i;e[t+2]=i>>>8;e[t+1]=i>>>16;e[t]=i>>>24}(n.maxp.data,0,C)}if(i.scaleFactors?.length===h&&c){const{scaleFactors:e}=i,t=int16(n.head.data[50],n.head.data[51]),a=new GlyfTable({glyfTable:n.glyf.data,isGlyphLocationsLong:t,locaTable:n.loca.data,numGlyphs:h});a.scale(e);const{glyf:s,loca:r,isLocationLong:g}=a.write();n.glyf.data=s;n.loca.data=r;if(g!==!!t){n.head.data[50]=0;n.head.data[51]=g?1:0}const o=n.hmtx.data;for(let t=0;t>8&255;o[i+1]=255&a;writeSignedInt16(o,i+2,Math.round(e[t]*signedInt16(o[i+2],o[i+3])))}}let l=h+1,Q=!0;if(l>65535){Q=!1;l=h;warn("Not enough space in glyfs to duplicate first glyph.")}let E=0,u=0;if(C>=65536&&n.maxp.length>=32){t.pos+=8;if(t.getUint16()>2){n.maxp.data[14]=0;n.maxp.data[15]=2}t.pos+=4;E=t.getUint16();t.pos+=4;u=t.getUint16()}n.maxp.data[4]=l>>8;n.maxp.data[5]=255&l;const d=function sanitizeTTPrograms(e,t,i,a){const s={functionsDefined:[],functionsUsed:[],functionsStackDeltas:[],tooComplexToFollowFunctions:!1,hintsValid:!0};e&&sanitizeTTProgram(e,s);t&&sanitizeTTProgram(t,s);e&&function checkInvalidFunctions(e,t){if(!e.tooComplexToFollowFunctions)if(e.functionsDefined.length>t){warn("TT: more functions defined than expected");e.hintsValid=!1}else for(let i=0,a=e.functionsUsed.length;it){warn("TT: invalid function id: "+i);e.hintsValid=!1;return}if(e.functionsUsed[i]&&!e.functionsDefined[i]){warn("TT: undefined function: "+i);e.hintsValid=!1;return}}}(s,a);if(i&&1&i.length){const e=new Uint8Array(i.length+1);e.set(i.data);i.data=e}return s.hintsValid}(n.fpgm,n.prep,n["cvt "],E);if(!d){delete n.fpgm;delete n.prep;delete n["cvt "]}!function sanitizeMetrics(e,t,i,a,s,r){if(!t){i&&(i.data=null);return}e.pos=(e.start||0)+t.offset;e.pos+=4;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;const n=e.getUint16();e.pos+=8;e.pos+=2;let g=e.getUint16();if(0!==n){if(!(2&int16(a.data[44],a.data[45]))){t.data[22]=0;t.data[23]=0}}if(g>s){info(`The numOfMetrics (${g}) should not be greater than the numGlyphs (${s}).`);g=s;t.data[34]=(65280&g)>>8;t.data[35]=255&g}const o=s-g-(i.length-4*g>>1);if(o>0){const e=new Uint8Array(i.length+2*o);e.set(i.data);if(r){e[i.length]=i.data[2];e[i.length+1]=i.data[3]}i.data=e}}(t,n.hhea,n.hmtx,n.head,l,Q);if(!n.head)throw new FormatError('Required "head" table is not found');!function sanitizeHead(e,t,i){const a=e.data,s=function int32(e,t,i,a){return(e<<24)+(t<<16)+(i<<8)+a}(a[0],a[1],a[2],a[3]);if(s>>16!=1){info("Attempting to fix invalid version in head table: "+s);a[0]=0;a[1]=1;a[2]=0;a[3]=0}const r=int16(a[50],a[51]);if(r<0||r>1){info("Attempting to fix invalid indexToLocFormat in head table: "+r);const e=t+1;if(i===e<<1){a[50]=0;a[51]=0}else{if(i!==e<<2)throw new FormatError("Could not fix indexToLocFormat: "+r);a[50]=0;a[51]=1}}}(n.head,h,c?n.loca.length:0);let f=Object.create(null);if(c){const e=int16(n.head.data[50],n.head.data[51]),t=function sanitizeGlyphLocations(e,t,i,a,s,r,n){let g,o,c;if(a){g=4;o=function fontItemDecodeLong(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]};c=function fontItemEncodeLong(e,t,i){e[t]=i>>>24&255;e[t+1]=i>>16&255;e[t+2]=i>>8&255;e[t+3]=255&i}}else{g=2;o=function fontItemDecode(e,t){return e[t]<<9|e[t+1]<<1};c=function fontItemEncode(e,t,i){e[t]=i>>9&255;e[t+1]=i>>1&255}}const C=r?i+1:i,h=g*(1+C),l=new Uint8Array(h);l.set(e.data.subarray(0,h));e.data=l;const Q=t.data,E=Q.length,u=new Uint8Array(E);let d,f;const p=[];for(d=0,f=0;dE&&(e=E);p.push({index:d,offset:e,endOffset:0})}p.sort(((e,t)=>e.offset-t.offset));for(d=0;de.index-t.index));for(d=0;dn&&(n=e.sizeOfInstructions);w+=t;c(l,f,w)}if(0===w){const e=new Uint8Array([0,1,0,0,0,0,0,0,0,0,0,0,0,0,49,0]);for(d=0,f=g;di+w)t.data=u.subarray(0,i+w);else{t.data=new Uint8Array(i+w);t.data.set(u.subarray(0,w))}t.data.set(u.subarray(0,i),w);c(e.data,l.length-g,w+i)}else t.data=u.subarray(0,w);return{missingGlyphs:y,maxSizeOfInstructions:n}}(n.loca,n.glyf,h,e,d,Q,u);f=t.missingGlyphs;if(C>=65536&&n.maxp.length>=32){n.maxp.data[26]=t.maxSizeOfInstructions>>8;n.maxp.data[27]=255&t.maxSizeOfInstructions}}if(!n.hhea)throw new FormatError('Required "hhea" table is not found');if(0===n.hhea.data[10]&&0===n.hhea.data[11]){n.hhea.data[10]=255;n.hhea.data[11]=255}const p={unitsPerEm:int16(n.head.data[18],n.head.data[19]),yMax:signedInt16(n.head.data[42],n.head.data[43]),yMin:signedInt16(n.head.data[38],n.head.data[39]),ascent:signedInt16(n.hhea.data[4],n.hhea.data[5]),descent:signedInt16(n.hhea.data[6],n.hhea.data[7]),lineGap:signedInt16(n.hhea.data[8],n.hhea.data[9])};this.ascent=p.ascent/p.unitsPerEm;this.descent=p.descent/p.unitsPerEm;this.lineGap=p.lineGap/p.unitsPerEm;if(this.cssFontInfo?.lineHeight){this.lineHeight=this.cssFontInfo.metrics.lineHeight;this.lineGap=this.cssFontInfo.metrics.lineGap}else this.lineHeight=this.ascent-this.descent+this.lineGap;n.post&&function readPostScriptTable(e,i,a){const s=(t.start||0)+e.offset;t.pos=s;const r=s+e.length,n=t.getInt32();t.skip(28);let g,o,c=!0;switch(n){case 65536:g=Hi;break;case 131072:const e=t.getUint16();if(e!==a){c=!1;break}const s=[];for(o=0;o=32768){c=!1;break}s.push(e)}if(!c)break;const C=[],h=[];for(;t.pos65535)throw new FormatError("Max size of CID is 65,535");let s=-1;t?s=a:void 0!==e[a]&&(s=e[a]);s>=0&&s>>0;let C=!1;if(g?.platformId!==s||g?.encodingId!==r){if(0!==s||0!==r&&1!==r&&3!==r)if(1===s&&0===r)C=!0;else if(3!==s||1!==r||!a&&g){if(i&&3===s&&0===r){C=!0;let i=!0;if(e>3;e.push(a);i=Math.max(a,i)}const a=[];for(let e=0;e<=i;e++)a.push({firstCode:t.getUint16(),entryCount:t.getUint16(),idDelta:signedInt16(t.getByte(),t.getByte()),idRangePos:t.pos+t.getUint16()});for(let i=0;i<256;i++)if(0===e[i]){t.pos=a[0].idRangePos+2*i;Q=t.getUint16();h.push({charCode:i,glyphId:Q})}else{const s=a[e[i]];for(l=0;l>1;t.skip(6);const i=[];let a;for(a=0;a>1)-(e-a);s.offsetIndex=n;g=Math.max(g,n+s.end-s.start+1)}else s.offsetIndex=-1}const o=[];for(l=0;l>>0;for(l=0;l>>0,i=t.getInt32()>>>0;let a=t.getInt32()>>>0;for(let t=e;t<=i;t++)h.push({charCode:t,glyphId:a++})}}}h.sort((function(e,t){return e.charCode-t.charCode}));for(let e=1;e=61440&&t<=61695&&(t&=255);m[t]=e.glyphId}else for(const e of r)m[e.charCode]=e.glyphId;if(i.glyphNames&&(g.length||this.differences.length))for(let e=0;e<256;++e){if(!o&&void 0!==m[e])continue;const t=this.differences[e]||g[e];if(!t)continue;const a=i.glyphNames.indexOf(t);a>0&&hasGlyph(a)&&(m[e]=a)}}0===m.length&&(m[0]=0);let y=l-1;Q||(y=0);if(!i.cssFontInfo){const e=adjustMapping(m,hasGlyph,y,this.toUnicode);this.toFontChar=e.toFontChar;n.cmap={tag:"cmap",data:createCmapTable(e.charCodeToGlyphId,e.toUnicodeExtraMap,l)};n["OS/2"]&&function validateOS2Table(e,t){t.pos=(t.start||0)+e.offset;const i=t.getUint16();t.skip(60);const a=t.getUint16();if(i<4&&768&a)return!1;if(t.getUint16()>t.getUint16())return!1;t.skip(6);if(0===t.getUint16())return!1;e.data[8]=e.data[9]=0;return!0}(n["OS/2"],t)||(n["OS/2"]={tag:"OS/2",data:createOS2Table(i,e.charCodeToGlyphId,p)})}if(!c)try{o=new Stream(n["CFF "].data);g=new CFFParser(o,i,Ri).parse();g.duplicateFirstGlyph();const e=new CFFCompiler(g);n["CFF "].data=e.compile()}catch{warn("Failed to compile font "+i.loadedName)}if(n.name){const[t,a]=readNameTable(n.name);n.name.data=createNameTable(e,t);this.psName=t[0][6]||null;i.composite||function adjustTrueTypeToUnicode(e,t,i){if(e.isInternalFont)return;if(e.hasIncludedToUnicodeMap)return;if(e.hasEncoding)return;if(e.toUnicode instanceof IdentityToUnicodeMap)return;if(!t)return;if(0===i.length)return;if(e.defaultEncoding===li)return;for(const e of i)if(!isWinNameRecord(e))return;const a=li,s=[],r=wi();for(const e in a){const t=a[e];if(""===t)continue;const i=r[t];void 0!==i&&(s[e]=String.fromCharCode(i))}s.length>0&&e.toUnicode.amend(s)}(i,this.isSymbolicFont,a)}else n.name={tag:"name",data:createNameTable(this.name)};const w=new OpenTypeFileBuilder(r.version);for(const e in n)w.addTable(e,n[e].data);return w.toArray()}convert(e,t,i){i.fixedPitch=!1;i.builtInEncoding&&function adjustType1ToUnicode(e,t){if(e.isInternalFont)return;if(e.hasIncludedToUnicodeMap)return;if(t===e.defaultEncoding)return;if(e.toUnicode instanceof IdentityToUnicodeMap)return;const i=[],a=wi();for(const s in t){if(e.hasEncoding&&(e.baseEncodingName||void 0!==e.differences[s]))continue;const r=getUnicodeForGlyph(t[s],a);-1!==r&&(i[s]=String.fromCharCode(r))}i.length>0&&e.toUnicode.amend(i)}(i,i.builtInEncoding);let s=1;t instanceof CFFFont&&(s=t.numGlyphs-1);const r=t.getGlyphMapping(i);let n=null,g=r,o=null;if(!i.cssFontInfo){n=adjustMapping(r,t.hasGlyphId.bind(t),s,this.toUnicode);this.toFontChar=n.toFontChar;g=n.charCodeToGlyphId;o=n.toUnicodeExtraMap}const c=t.numGlyphs;function getCharCodes(e,t){let i=null;for(const a in e)t===e[a]&&(i||=[]).push(0|a);return i}function createCharCode(e,t){for(const i in e)if(t===e[i])return 0|i;n.charCodeToGlyphId[n.nextAvailableFontCharCode]=t;return n.nextAvailableFontCharCode++}const C=t.seacs;if(n&&C?.length){const e=i.fontMatrix||a,s=t.getCharset(),g=Object.create(null);for(let t in C){t|=0;const i=C[t],a=hi[i[2]],o=hi[i[3]],c=s.indexOf(a),h=s.indexOf(o);if(c<0||h<0)continue;const l={x:i[0]*e[0]+i[1]*e[2]+e[4],y:i[0]*e[1]+i[1]*e[3]+e[5]},Q=getCharCodes(r,t);if(Q)for(const e of Q){const t=n.charCodeToGlyphId,i=createCharCode(t,c),a=createCharCode(t,h);g[e]={baseFontCharCode:i,accentFontCharCode:a,accentOffset:l}}}i.seacMap=g}const h=i.fontMatrix?1/Math.max(...i.fontMatrix.slice(0,4).map(Math.abs)):1e3,l=new OpenTypeFileBuilder("OTTO");l.addTable("CFF ",t.data);l.addTable("OS/2",createOS2Table(i,g));l.addTable("cmap",createCmapTable(g,o,c));l.addTable("head","\0\0\0\0\0\0\0\0\0\0_<õ\0\0"+safeString16(h)+"\0\0\0\0ž\v~'\0\0\0\0ž\v~'\0\0"+safeString16(i.descent)+"ÿ"+safeString16(i.ascent)+string16(i.italicAngle?2:0)+"\0\0\0\0\0\0\0");l.addTable("hhea","\0\0\0"+safeString16(i.ascent)+safeString16(i.descent)+"\0\0ÿÿ\0\0\0\0\0\0"+safeString16(i.capHeight)+safeString16(Math.tan(i.italicAngle)*i.xHeight)+"\0\0\0\0\0\0\0\0\0\0\0\0"+string16(c));l.addTable("hmtx",function fontFieldsHmtx(){const e=t.charstrings,i=t.cff?t.cff.widths:null;let a="\0\0\0\0";for(let t=1,s=c;t=65520&&e<=65535?0:e>=62976&&e<=63743?bi()[e]||e:173===e?45:e}(i)}this.isType3Font&&(s=i);let C=null;if(this.seacMap?.[e]){c=!0;const t=this.seacMap[e];i=t.baseFontCharCode;C={fontChar:String.fromCodePoint(t.accentFontCharCode),offset:t.accentOffset}}let h="";"number"==typeof i&&(i<=1114111?h=String.fromCodePoint(i):warn(`charToGlyph - invalid fontCharCode: ${i}`));if(this.missingFile&&this.vertical&&1===h.length){const e=Ji()[h.charCodeAt(0)];e&&(h=o=String.fromCharCode(e))}r=new fonts_Glyph(e,h,o,C,a,g,s,t,c);return this._glyphCache[e]=r}charsToGlyphs(e){let t=this._charsCache[e];if(t)return t;t=[];if(this.cMap){const i=Object.create(null),a=e.length;let s=0;for(;st.length%2==1,a=this.toUnicode instanceof IdentityToUnicodeMap?e=>this.toUnicode.charCodeOf(e):e=>this.toUnicode.charCodeOf(String.fromCodePoint(e));for(let s=0,r=e.length;s55295&&(r<57344||r>65533)&&s++;if(this.toUnicode){const e=a(r);if(-1!==e){if(hasCurrentBufErrors()){t.push(i.join(""));i.length=0}for(let t=(this.cMap?this.cMap.getCharCodeLength(e):1)-1;t>=0;t--)i.push(String.fromCharCode(e>>8*t&255));continue}}if(!hasCurrentBufErrors()){t.push(i.join(""));i.length=0}i.push(String.fromCodePoint(r))}t.push(i.join(""));return t}}class ErrorFont{constructor(e){this.error=e;this.loadedName="g_font_error";this.missingFile=!0}charsToGlyphs(){return[]}encodeString(e){return[e]}exportData(e=!1){return{error:this.error}}}const Ia=2,ca=3,Ca=4,ha=5,la=6,Ba=7;class Pattern{constructor(){unreachable("Cannot initialize Pattern.")}static parseShading(e,t,i,a,s){const r=e instanceof BaseStream?e.dict:e,n=r.get("ShadingType");try{switch(n){case Ia:case ca:return new RadialAxialShading(r,t,i,a,s);case Ca:case ha:case la:case Ba:return new MeshShading(e,t,i,a,s);default:throw new FormatError("Unsupported ShadingType: "+n)}}catch(e){if(e instanceof MissingDataException)throw e;warn(e);return new DummyShading}}}class BaseShading{static SMALL_NUMBER=1e-6;getIR(){unreachable("Abstract method `getIR` called.")}}class RadialAxialShading extends BaseShading{constructor(e,t,i,a,s){super();this.shadingType=e.get("ShadingType");let r=0;this.shadingType===Ia?r=4:this.shadingType===ca&&(r=6);this.coordsArr=e.getArray("Coords");if(!isNumberArray(this.coordsArr,r))throw new FormatError("RadialAxialShading: Invalid /Coords array.");const n=ColorSpace.parse({cs:e.getRaw("CS")||e.getRaw("ColorSpace"),xref:t,resources:i,pdfFunctionFactory:a,localColorSpaceCache:s});this.bbox=lookupNormalRect(e.getArray("BBox"),null);let g=0,o=1;const c=e.getArray("Domain");isNumberArray(c,2)&&([g,o]=c);let C=!1,h=!1;const l=e.getArray("Extend");(function isBooleanArray(e,t){return Array.isArray(e)&&(null===t||e.length===t)&&e.every((e=>"boolean"==typeof e))})(l,2)&&([C,h]=l);if(!(this.shadingType!==ca||C&&h)){const[e,t,i,a,s,r]=this.coordsArr,n=Math.hypot(e-a,t-s);i<=r+n&&r<=i+n&&warn("Unsupported radial gradient.")}this.extendStart=C;this.extendEnd=h;const Q=e.getRaw("Function"),E=a.createFromArray(Q),u=(o-g)/840,d=this.colorStops=[];if(g>=o||u<=0){info("Bad shading domain.");return}const f=new Float32Array(n.numComps),p=new Float32Array(1);let m,y=0;p[0]=g;E(p,0,f,0);let w=n.getRgb(f,0);const D=Util.makeHexColor(w[0],w[1],w[2]);d.push([0,D]);let b=1;p[0]=g+u;E(p,0,f,0);let F=n.getRgb(f,0),S=F[0]-w[0]+1,k=F[1]-w[1]+1,R=F[2]-w[2]+1,N=F[0]-w[0]-1,G=F[1]-w[1]-1,M=F[2]-w[2]-1;for(let e=2;e<840;e++){p[0]=g+e*u;E(p,0,f,0);m=n.getRgb(f,0);const t=e-y;S=Math.min(S,(m[0]-w[0]+1)/t);k=Math.min(k,(m[1]-w[1]+1)/t);R=Math.min(R,(m[2]-w[2]+1)/t);N=Math.max(N,(m[0]-w[0]-1)/t);G=Math.max(G,(m[1]-w[1]-1)/t);M=Math.max(M,(m[2]-w[2]-1)/t);if(!(N<=S&&G<=k&&M<=R)){const e=Util.makeHexColor(F[0],F[1],F[2]);d.push([b/840,e]);S=m[0]-F[0]+1;k=m[1]-F[1]+1;R=m[2]-F[2]+1;N=m[0]-F[0]-1;G=m[1]-F[1]-1;M=m[2]-F[2]-1;y=b;w=F}b=e;F=m}const U=Util.makeHexColor(F[0],F[1],F[2]);d.push([1,U]);let x="transparent";if(e.has("Background")){m=n.getRgb(e.get("Background"),0);x=Util.makeHexColor(m[0],m[1],m[2])}if(!C){d.unshift([0,x]);d[1][0]+=BaseShading.SMALL_NUMBER}if(!h){d.at(-1)[0]-=BaseShading.SMALL_NUMBER;d.push([1,x])}this.colorStops=d}getIR(){const{coordsArr:e,shadingType:t}=this;let i,a,s,r,n;if(t===Ia){a=[e[0],e[1]];s=[e[2],e[3]];r=null;n=null;i="axial"}else if(t===ca){a=[e[0],e[1]];s=[e[3],e[4]];r=e[2];n=e[5];i="radial"}else unreachable(`getPattern type unknown: ${t}`);return["RadialAxial",i,this.bbox,this.colorStops,a,s,r,n]}}class MeshStreamReader{constructor(e,t){this.stream=e;this.context=t;this.buffer=0;this.bufferLength=0;const i=t.numComps;this.tmpCompsBuf=new Float32Array(i);const a=t.colorSpace.numComps;this.tmpCsCompsBuf=t.colorFn?new Float32Array(a):this.tmpCompsBuf}get hasData(){if(this.stream.end)return this.stream.pos0)return!0;const e=this.stream.getByte();if(e<0)return!1;this.buffer=e;this.bufferLength=8;return!0}readBits(e){let t=this.buffer,i=this.bufferLength;if(32===e){if(0===i)return(this.stream.getByte()<<24|this.stream.getByte()<<16|this.stream.getByte()<<8|this.stream.getByte())>>>0;t=t<<24|this.stream.getByte()<<16|this.stream.getByte()<<8|this.stream.getByte();const e=this.stream.getByte();this.buffer=e&(1<>i)>>>0}if(8===e&&0===i)return this.stream.getByte();for(;i>i}align(){this.buffer=0;this.bufferLength=0}readFlag(){return this.readBits(this.context.bitsPerFlag)}readCoordinate(){const e=this.context.bitsPerCoordinate,t=this.readBits(e),i=this.readBits(e),a=this.context.decode,s=e<32?1/((1<r?r:e;t=t>n?n:t;i=ie*s[t])):i;let n,g=-2;const o=[];for(const[e,t]of a.map(((e,t)=>[e,t])).sort((([e],[t])=>e-t)))if(-1!==e)if(e===g+1){n.push(r[t]);g+=1}else{g=e;n=[r[t]];o.push(e,n)}return o}(e),i=new Dict(null);i.set("BaseFont",Name.get(e));i.set("Type",Name.get("Font"));i.set("Subtype",Name.get("CIDFontType2"));i.set("Encoding",Name.get("Identity-H"));i.set("CIDToGIDMap",Name.get("Identity"));i.set("W",t);i.set("FirstChar",t[0]);i.set("LastChar",t.at(-2)+t.at(-1).length-1);const a=new Dict(null);i.set("FontDescriptor",a);const s=new Dict(null);s.set("Ordering","Identity");s.set("Registry","Adobe");s.set("Supplement",0);i.set("CIDSystemInfo",s);return i}class PostScriptParser{constructor(e){this.lexer=e;this.operators=[];this.token=null;this.prev=null}nextToken(){this.prev=this.token;this.token=this.lexer.getToken()}accept(e){if(this.token.type===e){this.nextToken();return!0}return!1}expect(e){if(this.accept(e))return!0;throw new FormatError(`Unexpected symbol: found ${this.token.type} expected ${e}.`)}parse(){this.nextToken();this.expect(as.LBRACE);this.parseBlock();this.expect(as.RBRACE);return this.operators}parseBlock(){for(;;)if(this.accept(as.NUMBER))this.operators.push(this.prev.value);else if(this.accept(as.OPERATOR))this.operators.push(this.prev.value);else{if(!this.accept(as.LBRACE))return;this.parseCondition()}}parseCondition(){const e=this.operators.length;this.operators.push(null,null);this.parseBlock();this.expect(as.RBRACE);if(this.accept(as.IF)){this.operators[e]=this.operators.length;this.operators[e+1]="jz"}else{if(!this.accept(as.LBRACE))throw new FormatError("PS Function: error parsing conditional.");{const t=this.operators.length;this.operators.push(null,null);const i=this.operators.length;this.parseBlock();this.expect(as.RBRACE);this.expect(as.IFELSE);this.operators[t]=this.operators.length;this.operators[t+1]="j";this.operators[e]=i;this.operators[e+1]="jz"}}}}const as={LBRACE:0,RBRACE:1,NUMBER:2,OPERATOR:3,IF:4,IFELSE:5};class PostScriptToken{static get opCache(){return shadow(this,"opCache",Object.create(null))}constructor(e,t){this.type=e;this.value=t}static getOperator(e){return PostScriptToken.opCache[e]||=new PostScriptToken(as.OPERATOR,e)}static get LBRACE(){return shadow(this,"LBRACE",new PostScriptToken(as.LBRACE,"{"))}static get RBRACE(){return shadow(this,"RBRACE",new PostScriptToken(as.RBRACE,"}"))}static get IF(){return shadow(this,"IF",new PostScriptToken(as.IF,"IF"))}static get IFELSE(){return shadow(this,"IFELSE",new PostScriptToken(as.IFELSE,"IFELSE"))}}class PostScriptLexer{constructor(e){this.stream=e;this.nextChar();this.strBuf=[]}nextChar(){return this.currentChar=this.stream.getByte()}getToken(){let e=!1,t=this.currentChar;for(;;){if(t<0)return Bt;if(e)10!==t&&13!==t||(e=!1);else if(37===t)e=!0;else if(!isWhiteSpace(t))break;t=this.nextChar()}switch(0|t){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 43:case 45:case 46:return new PostScriptToken(as.NUMBER,this.getNumber());case 123:this.nextChar();return PostScriptToken.LBRACE;case 125:this.nextChar();return PostScriptToken.RBRACE}const i=this.strBuf;i.length=0;i[0]=String.fromCharCode(t);for(;(t=this.nextChar())>=0&&(t>=65&&t<=90||t>=97&&t<=122);)i.push(String.fromCharCode(t));const a=i.join("");switch(a.toLowerCase()){case"if":return PostScriptToken.IF;case"ifelse":return PostScriptToken.IFELSE;default:return PostScriptToken.getOperator(a)}}getNumber(){let e=this.currentChar;const t=this.strBuf;t.length=0;t[0]=String.fromCharCode(e);for(;(e=this.nextChar())>=0&&(e>=48&&e<=57||45===e||46===e);)t.push(String.fromCharCode(e));const i=parseFloat(t.join(""));if(isNaN(i))throw new FormatError(`Invalid floating point number: ${i}`);return i}}class BaseLocalCache{constructor(e){this._onlyRefs=!0===e?.onlyRefs;if(!this._onlyRefs){this._nameRefMap=new Map;this._imageMap=new Map}this._imageCache=new RefSetCache}getByName(e){this._onlyRefs&&unreachable("Should not call `getByName` method.");const t=this._nameRefMap.get(e);return t?this.getByRef(t):this._imageMap.get(e)||null}getByRef(e){return this._imageCache.get(e)||null}set(e,t,i){unreachable("Abstract method `set` called.")}}class LocalImageCache extends BaseLocalCache{set(e,t=null,i){if("string"!=typeof e)throw new Error('LocalImageCache.set - expected "name" argument.');if(t){if(this._imageCache.has(t))return;this._nameRefMap.set(e,t);this._imageCache.put(t,i)}else this._imageMap.has(e)||this._imageMap.set(e,i)}}class LocalColorSpaceCache extends BaseLocalCache{set(e=null,t=null,i){if("string"!=typeof e&&!t)throw new Error('LocalColorSpaceCache.set - expected "name" and/or "ref" argument.');if(t){if(this._imageCache.has(t))return;null!==e&&this._nameRefMap.set(e,t);this._imageCache.put(t,i)}else this._imageMap.has(e)||this._imageMap.set(e,i)}}class LocalFunctionCache extends BaseLocalCache{constructor(e){super({onlyRefs:!0})}set(e=null,t,i){if(!t)throw new Error('LocalFunctionCache.set - expected "ref" argument.');this._imageCache.has(t)||this._imageCache.put(t,i)}}class LocalGStateCache extends BaseLocalCache{set(e,t=null,i){if("string"!=typeof e)throw new Error('LocalGStateCache.set - expected "name" argument.');if(t){if(this._imageCache.has(t))return;this._nameRefMap.set(e,t);this._imageCache.put(t,i)}else this._imageMap.has(e)||this._imageMap.set(e,i)}}class LocalTilingPatternCache extends BaseLocalCache{constructor(e){super({onlyRefs:!0})}set(e=null,t,i){if(!t)throw new Error('LocalTilingPatternCache.set - expected "ref" argument.');this._imageCache.has(t)||this._imageCache.put(t,i)}}class RegionalImageCache extends BaseLocalCache{constructor(e){super({onlyRefs:!0})}set(e=null,t,i){if(!t)throw new Error('RegionalImageCache.set - expected "ref" argument.');this._imageCache.has(t)||this._imageCache.put(t,i)}}class GlobalImageCache{static NUM_PAGES_THRESHOLD=2;static MIN_IMAGES_TO_CACHE=10;static MAX_BYTE_SIZE=5e7;#F=new RefSet;constructor(){this._refCache=new RefSetCache;this._imageCache=new RefSetCache}get#S(){let e=0;for(const t of this._imageCache)e+=t.byteSize;return e}get#k(){return!(this._imageCache.size+e)):null}class PDFFunction{static getSampleArray(e,t,i,a){let s,r,n=1;for(s=0,r=e.length;s>o)*C;c&=(1<i?e=i:e0&&(l=r[h-1]);let Q=a[1];h>1,c=s.length>>1,C=new PostScriptEvaluator(g),h=Object.create(null);let l=8192;const Q=new Float32Array(c);return function constructPostScriptFn(e,t,i,a){let s,n,g="";const E=Q;for(s=0;se&&(n=e)}d[s]=n}if(l>0){l--;h[g]=d}i.set(d,a)}}}function isPDFFunction(e){let t;if(e instanceof Dict)t=e;else{if(!(e instanceof BaseStream))return!1;t=e.dict}return t.has("FunctionType")}class PostScriptStack{static MAX_STACK_SIZE=100;constructor(e){this.stack=e?Array.from(e):[]}push(e){if(this.stack.length>=PostScriptStack.MAX_STACK_SIZE)throw new Error("PostScript function stack overflow.");this.stack.push(e)}pop(){if(this.stack.length<=0)throw new Error("PostScript function stack underflow.");return this.stack.pop()}copy(e){if(this.stack.length+e>=PostScriptStack.MAX_STACK_SIZE)throw new Error("PostScript function stack overflow.");const t=this.stack;for(let i=t.length-e,a=e-1;a>=0;a--,i++)t.push(t[i])}index(e){this.push(this.stack[this.stack.length-e-1])}roll(e,t){const i=this.stack,a=i.length-e,s=i.length-1,r=a+(t-Math.floor(t/e)*e);for(let e=a,t=s;e0?t.push(n<>g);break;case"ceiling":n=t.pop();t.push(Math.ceil(n));break;case"copy":n=t.pop();t.copy(n);break;case"cos":n=t.pop();t.push(Math.cos(n%360/180*Math.PI));break;case"cvi":n=0|t.pop();t.push(n);break;case"cvr":break;case"div":g=t.pop();n=t.pop();t.push(n/g);break;case"dup":t.copy(1);break;case"eq":g=t.pop();n=t.pop();t.push(n===g);break;case"exch":t.roll(2,1);break;case"exp":g=t.pop();n=t.pop();t.push(n**g);break;case"false":t.push(!1);break;case"floor":n=t.pop();t.push(Math.floor(n));break;case"ge":g=t.pop();n=t.pop();t.push(n>=g);break;case"gt":g=t.pop();n=t.pop();t.push(n>g);break;case"idiv":g=t.pop();n=t.pop();t.push(n/g|0);break;case"index":n=t.pop();t.index(n);break;case"le":g=t.pop();n=t.pop();t.push(n<=g);break;case"ln":n=t.pop();t.push(Math.log(n));break;case"log":n=t.pop();t.push(Math.log10(n));break;case"lt":g=t.pop();n=t.pop();t.push(n=t?new AstLiteral(t):e.max<=t?e:new AstMin(e,t)}class PostScriptCompiler{compile(e,t,i){const a=[],s=[],r=t.length>>1,n=i.length>>1;let g,o,c,C,h,l,Q,E,u=0;for(let e=0;et.min){g.unshift("Math.max(",r,", ");g.push(")")}if(n4){a=!0;t=0}else{a=!1;t=1}const o=[];for(r=0;r=0&&"ET"===gs[e];--e)gs[e]="EN";for(let e=r+1;e0&&(t=gs[r-1]);let i=h;e+1E&&isOdd(E)&&(d=E)}for(E=u;E>=d;--E){let e=-1;for(r=0,n=o.length;r=0){reverseValues(ns,e,r);e=-1}}else e<0&&(e=r);e>=0&&reverseValues(ns,e,o.length)}for(r=0,n=ns.length;r"!==e||(ns[r]="")}return createBidiText(ns.join(""),a)}const os={style:"normal",weight:"normal"},Is={style:"normal",weight:"bold"},cs={style:"italic",weight:"normal"},Cs={style:"italic",weight:"bold"},hs=new Map([["Times-Roman",{local:["Times New Roman","Times-Roman","Times","Liberation Serif","Nimbus Roman","Nimbus Roman L","Tinos","Thorndale","TeX Gyre Termes","FreeSerif","Linux Libertine O","Libertinus Serif","DejaVu Serif","Bitstream Vera Serif","Ubuntu"],style:os,ultimate:"serif"}],["Times-Bold",{alias:"Times-Roman",style:Is,ultimate:"serif"}],["Times-Italic",{alias:"Times-Roman",style:cs,ultimate:"serif"}],["Times-BoldItalic",{alias:"Times-Roman",style:Cs,ultimate:"serif"}],["Helvetica",{local:["Helvetica","Helvetica Neue","Arial","Arial Nova","Liberation Sans","Arimo","Nimbus Sans","Nimbus Sans L","A030","TeX Gyre Heros","FreeSans","DejaVu Sans","Albany","Bitstream Vera Sans","Arial Unicode MS","Microsoft Sans Serif","Apple Symbols","Cantarell"],path:"LiberationSans-Regular.ttf",style:os,ultimate:"sans-serif"}],["Helvetica-Bold",{alias:"Helvetica",path:"LiberationSans-Bold.ttf",style:Is,ultimate:"sans-serif"}],["Helvetica-Oblique",{alias:"Helvetica",path:"LiberationSans-Italic.ttf",style:cs,ultimate:"sans-serif"}],["Helvetica-BoldOblique",{alias:"Helvetica",path:"LiberationSans-BoldItalic.ttf",style:Cs,ultimate:"sans-serif"}],["Courier",{local:["Courier","Courier New","Liberation Mono","Nimbus Mono","Nimbus Mono L","Cousine","Cumberland","TeX Gyre Cursor","FreeMono","Linux Libertine Mono O","Libertinus Mono"],style:os,ultimate:"monospace"}],["Courier-Bold",{alias:"Courier",style:Is,ultimate:"monospace"}],["Courier-Oblique",{alias:"Courier",style:cs,ultimate:"monospace"}],["Courier-BoldOblique",{alias:"Courier",style:Cs,ultimate:"monospace"}],["ArialBlack",{local:["Arial Black"],style:{style:"normal",weight:"900"},fallback:"Helvetica-Bold"}],["ArialBlack-Bold",{alias:"ArialBlack"}],["ArialBlack-Italic",{alias:"ArialBlack",style:{style:"italic",weight:"900"},fallback:"Helvetica-BoldOblique"}],["ArialBlack-BoldItalic",{alias:"ArialBlack-Italic"}],["ArialNarrow",{local:["Arial Narrow","Liberation Sans Narrow","Helvetica Condensed","Nimbus Sans Narrow","TeX Gyre Heros Cn"],style:os,fallback:"Helvetica"}],["ArialNarrow-Bold",{alias:"ArialNarrow",style:Is,fallback:"Helvetica-Bold"}],["ArialNarrow-Italic",{alias:"ArialNarrow",style:cs,fallback:"Helvetica-Oblique"}],["ArialNarrow-BoldItalic",{alias:"ArialNarrow",style:Cs,fallback:"Helvetica-BoldOblique"}],["Calibri",{local:["Calibri","Carlito"],style:os,fallback:"Helvetica"}],["Calibri-Bold",{alias:"Calibri",style:Is,fallback:"Helvetica-Bold"}],["Calibri-Italic",{alias:"Calibri",style:cs,fallback:"Helvetica-Oblique"}],["Calibri-BoldItalic",{alias:"Calibri",style:Cs,fallback:"Helvetica-BoldOblique"}],["Wingdings",{local:["Wingdings","URW Dingbats"],style:os}],["Wingdings-Regular",{alias:"Wingdings"}],["Wingdings-Bold",{alias:"Wingdings"}]]),ls=new Map([["Arial-Black","ArialBlack"]]);function getFamilyName(e){const t=new Set(["thin","extralight","ultralight","demilight","semilight","light","book","regular","normal","medium","demibold","semibold","bold","extrabold","ultrabold","black","heavy","extrablack","ultrablack","roman","italic","oblique","ultracondensed","extracondensed","condensed","semicondensed","normal","semiexpanded","expanded","extraexpanded","ultraexpanded","bolditalic"]);return e.split(/[- ,+]+/g).filter((e=>!t.has(e.toLowerCase()))).join(" ")}function generateFont({alias:e,local:t,path:i,fallback:a,style:s,ultimate:r},n,g,o=!0,c=!0,C=""){const h={style:null,ultimate:null};if(t){const e=C?` ${C}`:"";for(const i of t)n.push(`local(${i}${e})`)}if(e){const t=hs.get(e),r=C||function getStyleToAppend(e){switch(e){case Is:return"Bold";case cs:return"Italic";case Cs:return"Bold Italic";default:if("bold"===e?.weight)return"Bold";if("italic"===e?.style)return"Italic"}return""}(s);Object.assign(h,generateFont(t,n,g,o&&!a,c&&!i,r))}s&&(h.style=s);r&&(h.ultimate=r);if(o&&a){const e=hs.get(a),{ultimate:t}=generateFont(e,n,g,o,c&&!i,C);h.ultimate||=t}c&&i&&g&&n.push(`url(${g}${i})`);return h}function getFontSubstitution(e,t,i,a,s,r){if(a.startsWith("InvalidPDFjsFont_"))return null;"TrueType"!==r&&"Type1"!==r||!/^[A-Z]{6}\+/.test(a)||(a=a.slice(7));const n=a=normalizeFontName(a);let g=e.get(n);if(g)return g;let o=hs.get(a);if(!o)for(const[e,t]of ls)if(a.startsWith(e)){a=`${t}${a.substring(e.length)}`;o=hs.get(a);break}let c=!1;if(!o){o=hs.get(s);c=!0}const C=`${t.getDocId()}_s${t.createFontId()}`;if(!o){if(!validateFontName(a)){warn(`Cannot substitute the font because of its name: ${a}`);e.set(n,null);return null}const t=/bold/gi.test(a),i=/oblique|italic/gi.test(a),s=t&&i&&Cs||t&&Is||i&&cs||os;g={css:`"${getFamilyName(a)}",${C}`,guessFallback:!0,loadedName:C,baseFontName:a,src:`local(${a})`,style:s};e.set(n,g);return g}const h=[];c&&validateFontName(a)&&h.push(`local(${a})`);const{style:l,ultimate:Q}=generateFont(o,h,i),E=null===Q,u=E?"":`,${Q}`;g={css:`"${getFamilyName(a)}",${C}${u}`,guessFallback:E,loadedName:C,baseFontName:a,src:h.join(","),style:l};e.set(n,g);return g}class ImageResizer{static#R=2048;static#y=FeatureTest.isImageDecoderSupported;constructor(e,t){this._imgData=e;this._isMask=t}static get canUseImageDecoder(){return shadow(this,"canUseImageDecoder",this.#y?ImageDecoder.isTypeSupported("image/bmp"):Promise.resolve(!1))}static needsToBeResized(e,t){if(e<=this.#R&&t<=this.#R)return!1;const{MAX_DIM:i}=this;if(e>i||t>i)return!0;const a=e*t;if(this._hasMaxArea)return a>this.MAX_AREA;if(a(this.MAX_AREA=this.#R**2)}static get MAX_DIM(){return shadow(this,"MAX_DIM",this._guessMax(2048,65537,0,1))}static get MAX_AREA(){this._hasMaxArea=!0;return shadow(this,"MAX_AREA",this._guessMax(this.#R,this.MAX_DIM,128,0)**2)}static set MAX_AREA(e){if(e>=0){this._hasMaxArea=!0;shadow(this,"MAX_AREA",e)}}static setOptions({canvasMaxAreaInBytes:e=-1,isImageDecoderSupported:t=!1}){this._hasMaxArea||(this.MAX_AREA=e>>2);this.#y=t}static _areGoodDims(e,t){try{const i=new OffscreenCanvas(e,t),a=i.getContext("2d");a.fillRect(0,0,1,1);const s=a.getImageData(0,0,1,1).data[3];i.width=i.height=1;return 0!==s}catch{return!1}}static _guessMax(e,t,i,a){for(;e+i+1pt){const e=this.#N();if(e)return e}const a=this._encodeBMP();let s,r;if(await ImageResizer.canUseImageDecoder){s=new ImageDecoder({data:a,type:"image/bmp",preferAnimation:!1,transfer:[a.buffer]});r=s.decode().catch((e=>{warn(`BMP image decoding failed: ${e}`);return createImageBitmap(new Blob([this._encodeBMP().buffer],{type:"image/bmp"}))})).finally((()=>{s.close()}))}else r=createImageBitmap(new Blob([a.buffer],{type:"image/bmp"}));const{MAX_AREA:n,MAX_DIM:g}=ImageResizer,o=Math.max(t/g,i/g,Math.sqrt(t*i/n)),c=Math.max(o,2),C=Math.round(10*(o+1.25))/10/c,h=Math.floor(Math.log2(C)),l=new Array(h+2).fill(2);l[0]=c;l.splice(-1,1,C/(1<>n,o=a>>n;let c,C=a;try{c=new Uint8Array(r)}catch{let e=Math.floor(Math.log2(r+1));for(;;)try{c=new Uint8Array(2**e-1);break}catch{e-=1}C=Math.floor((2**e-1)/(4*i));const t=i*C*4;t>n;e>3,n=i+3&-4;if(i!==n){const e=new Uint8Array(n*t);let a=0;for(let r=0,g=t*i;r>>8;t[i++]=255&s}}}else{if(!ArrayBuffer.isView(e))throw new Error("Invalid data format, must be a string or TypedArray.");t=e.slice();i=t.byteLength}const a=i>>2,s=i-4*a,r=new Uint32Array(t.buffer,0,a);let n=0,g=0,o=this.h1,c=this.h2;const C=3432918353,h=461845907,l=11601,Q=13715;for(let e=0;e>>17;n=n*h&Qs|n*Q&Es;o^=n;o=o<<13|o>>>19;o=5*o+3864292196}else{g=r[e];g=g*C&Qs|g*l&Es;g=g<<15|g>>>17;g=g*h&Qs|g*Q&Es;c^=g;c=c<<13|c>>>19;c=5*c+3864292196}n=0;switch(s){case 3:n^=t[4*a+2]<<16;case 2:n^=t[4*a+1]<<8;case 1:n^=t[4*a];n=n*C&Qs|n*l&Es;n=n<<15|n>>>17;n=n*h&Qs|n*Q&Es;1&a?o^=n:c^=n}this.h1=o;this.h2=c}hexdigest(){let e=this.h1,t=this.h2;e^=t>>>1;e=3981806797*e&Qs|36045*e&Es;t=4283543511*t&Qs|(2950163797*(t<<16|e>>>16)&Qs)>>>16;e^=t>>>1;e=444984403*e&Qs|60499*e&Es;t=3301882366*t&Qs|(3120437893*(t<<16|e>>>16)&Qs)>>>16;e^=t>>>1;return(e>>>0).toString(16).padStart(8,"0")+(t>>>0).toString(16).padStart(8,"0")}}function addState(e,t,i,a,s){let r=e;for(let e=0,i=t.length-1;e1e3){c=Math.max(c,l);Q+=h+2;l=0;h=0}C.push({transform:t,x:l,y:Q,w:i.width,h:i.height});l+=i.width+2;h=Math.max(h,i.height)}const E=Math.max(c,l)+1,u=Q+h+1,d=new Uint8Array(E*u*4),f=E<<2;for(let e=0;e=0;){t[r-4]=t[r];t[r-3]=t[r+1];t[r-2]=t[r+2];t[r-1]=t[r+3];t[r+i]=t[r+i-4];t[r+i+1]=t[r+i-3];t[r+i+2]=t[r+i-2];t[r+i+3]=t[r+i-1];r-=f}}const p={width:E,height:u};if(e.isOffscreenCanvasSupported){const e=new OffscreenCanvas(E,u);e.getContext("2d").putImageData(new ImageData(new Uint8ClampedArray(d.buffer),E,u),0,0);p.bitmap=e.transferToImageBitmap();p.data=null}else{p.kind=S;p.data=d}i.splice(r,4*o,$e);a.splice(r,4*o,[p,C]);return r+1}));addState(us,[MA,xA,Ze,UA],null,(function iterateImageMaskGroup(e,t){const i=e.fnArray,a=(t-(e.iCurr-3))%4;switch(a){case 0:return i[t]===MA;case 1:return i[t]===xA;case 2:return i[t]===Ze;case 3:return i[t]===UA}throw new Error(`iterateImageMaskGroup - invalid pos: ${a}`)}),(function foundImageMaskGroup(e,t){const i=e.fnArray,a=e.argsArray,s=e.iCurr,r=s-3,n=s-2,g=s-1;let o=Math.floor((t-r)/4);if(o<10)return t-(t-r)%4;let c,C,h=!1;const l=a[g][0],Q=a[n][0],E=a[n][1],u=a[n][2],d=a[n][3];if(E===u){h=!0;c=n+4;let e=g+4;for(let t=1;t=4&&i[r-4]===i[n]&&i[r-3]===i[g]&&i[r-2]===i[o]&&i[r-1]===i[c]&&a[r-4][0]===C&&a[r-4][1]===h){l++;Q-=5}let E=Q+4;for(let e=1;e=i)break}a=(a||us)[e[t]];if(a&&!Array.isArray(a)){r.iCurr=t;t++;if(!a.checkFn||(0,a.checkFn)(r)){s=a;a=null}else a=null}else t++}this.state=a;this.match=s;this.lastProcessed=t}flush(){for(;this.match;){const e=this.queue.fnArray.length;this.lastProcessed=(0,this.match.processFn)(this.context,e);this.match=null;this.state=null;this._optimize()}}reset(){this.state=null;this.match=null;this.lastProcessed=0}}class OperatorList{static CHUNK_SIZE=1e3;static CHUNK_SIZE_ABOUT=this.CHUNK_SIZE-5;constructor(e=0,t){this._streamSink=t;this.fnArray=[];this.argsArray=[];this.optimizer=!t||e&E?new NullOptimizer(this):new QueueOptimizer(this);this.dependencies=new Set;this._totalLength=0;this.weight=0;this._resolved=t?null:Promise.resolve()}set isOffscreenCanvasSupported(e){this.optimizer.isOffscreenCanvasSupported=e}get length(){return this.argsArray.length}get ready(){return this._resolved||this._streamSink.ready}get totalLength(){return this._totalLength+this.length}addOp(e,t){this.optimizer.push(e,t);this.weight++;this._streamSink&&(this.weight>=OperatorList.CHUNK_SIZE||this.weight>=OperatorList.CHUNK_SIZE_ABOUT&&(e===UA||e===ee))&&this.flush()}addImageOps(e,t,i,a=!1){if(a){this.addOp(MA);this.addOp(GA,[[["SMask",!1]]])}void 0!==i&&this.addOp(Ye,["OC",i]);this.addOp(e,t);void 0!==i&&this.addOp(ve,[]);a&&this.addOp(UA)}addDependency(e){if(!this.dependencies.has(e)){this.dependencies.add(e);this.addOp(wA,[e])}}addDependencies(e){for(const t of e)this.addDependency(t)}addOpList(e){if(e instanceof OperatorList){for(const t of e.dependencies)this.dependencies.add(t);for(let t=0,i=e.length;ta&&(e=a);return e}function resizeImageMask(e,t,i,a,s,r){const n=s*r;let g;g=t<=8?new Uint8Array(n):t<=16?new Uint16Array(n):new Uint32Array(n);const o=i/s,c=a/r;let C,h,l,Q,E=0;const u=new Uint16Array(s),d=i;for(C=0;C0&&Number.isInteger(i.height)&&i.height>0&&(i.width!==l||i.height!==Q)){warn("PDFImage - using the Width/Height of the image data, rather than the image dictionary.");l=i.width;Q=i.height}if(l<1||Q<1)throw new FormatError(`Invalid image width: ${l} or height: ${Q}`);this.width=l;this.height=Q;this.interpolate=c.get("I","Interpolate");this.imageMask=c.get("IM","ImageMask")||!1;this.matte=c.get("Matte")||!1;let E=i.bitsPerComponent;if(!E){E=c.get("BPC","BitsPerComponent");if(!E){if(!this.imageMask)throw new FormatError(`Bits per component missing in image: ${this.imageMask}`);E=1}}this.bpc=E;if(!this.imageMask){let s=c.getRaw("CS")||c.getRaw("ColorSpace");const r=!!s;if(r)this.jpxDecoderOptions?.smaskInData&&(s=Name.get("DeviceRGBA"));else if(this.jpxDecoderOptions)s=Name.get("DeviceRGBA");else switch(i.numComps){case 1:s=Name.get("DeviceGray");break;case 3:s=Name.get("DeviceRGB");break;case 4:s=Name.get("DeviceCMYK");break;default:throw new Error(`Images with ${i.numComps} color components not supported.`)}this.colorSpace=ColorSpace.parse({cs:s,xref:e,resources:a?t:null,pdfFunctionFactory:g,localColorSpaceCache:o});this.numComps=this.colorSpace.numComps;if(this.jpxDecoderOptions){this.jpxDecoderOptions.numComponents=r?this.numComp:0;this.jpxDecoderOptions.isIndexedColormap="Indexed"===this.colorSpace.name}}this.decode=c.getArray("D","Decode");this.needsDecode=!1;if(this.decode&&(this.colorSpace&&!this.colorSpace.isDefaultDecode(this.decode,E)||n&&!ColorSpace.isDefaultDecode(this.decode,1))){this.needsDecode=!0;const e=(1<>3)*i,g=e.byteLength;let o,c;if(!a||s&&!(n===g))if(s){o=new Uint8Array(n);o.set(e);o.fill(255,g)}else o=new Uint8Array(e);else o=e;if(s)for(c=0;c>7&1;n[l+1]=h>>6&1;n[l+2]=h>>5&1;n[l+3]=h>>4&1;n[l+4]=h>>3&1;n[l+5]=h>>2&1;n[l+6]=h>>1&1;n[l+7]=1&h;l+=8}if(l>=1}}}}else{let i=0;h=0;for(l=0,C=r;l>a;s<0?s=0:s>c&&(s=c);n[l]=s;h&=(1<n[a+1]){t=255;break}}g[C]=t}}}if(g)for(C=0,l=3,h=t*a;C>3,C=t&&ImageResizer.needsToBeResized(i,a);if(!this.smask&&!this.mask&&"DeviceRGBA"===this.colorSpace.name){s.kind=S;const e=s.data=await this.getImageBytes(g*n*4,{});return t?C?ImageResizer.createImage(s,!1):this.createBitmap(S,i,a,e):s}if(!e){let e;"DeviceGray"===this.colorSpace.name&&1===o?e=b:"DeviceRGB"!==this.colorSpace.name||8!==o||this.needsDecode||(e=F);if(e&&!this.smask&&!this.mask&&i===n&&a===g){const r=await this.#G(n,g);if(r)return r;const o=await this.getImageBytes(g*c,{});if(t)return C?ImageResizer.createImage({data:o,kind:e,width:i,height:a,interpolate:this.interpolate},this.needsDecode):this.createBitmap(e,n,g,o);s.kind=e;s.data=o;if(this.needsDecode){assert(e===b,"PDFImage.createImageData: The image must be grayscale.");const t=s.data;for(let e=0,i=t.length;e>3,n=await this.getImageBytes(a*r,{internal:!0}),g=this.getComponents(n);let o,c;if(1===s){c=i*a;if(this.needsDecode)for(o=0;o0&&t.args[0].count++}class TimeSlotManager{static TIME_SLOT_DURATION_MS=20;static CHECK_TIME_EVERY=100;constructor(){this.reset()}check(){if(++this.checkedh){const e="Image exceeded maximum allowed size and was removed.";if(this.options.ignoreErrors){warn(e);return}throw new Error(e)}let l;g.has("OC")&&(l=await this.parseMarkedContentProps(g.get("OC"),e));let Q,E;if(g.get("IM","ImageMask")||!1){const e=g.get("I","Interpolate"),i=c+7>>3,n=t.getBytes(i*C),h=g.getArray("D","Decode");if(this.parsingType3Font){Q=PDFImage.createRawMask({imgArray:n,width:c,height:C,imageIsFromDecodeStream:t instanceof DecodeStream,inverseDecode:h?.[0]>0,interpolate:e});Q.cached=!!s;E=[Q];a.addImageOps(Ze,E,l);if(s){const e={fn:Ze,args:E,optionalContent:l};r.set(s,o,e);o&&this._regionalImageCache.set(null,o,e)}return}Q=await PDFImage.createMask({imgArray:n,width:c,height:C,imageIsFromDecodeStream:t instanceof DecodeStream,inverseDecode:h?.[0]>0,interpolate:e,isOffscreenCanvasSupported:this.options.isOffscreenCanvasSupported});if(Q.isSingleOpaquePixel){a.addImageOps(tt,[],l);if(s){const e={fn:tt,args:[],optionalContent:l};r.set(s,o,e);o&&this._regionalImageCache.set(null,o,e)}return}const u=`mask_${this.idFactory.createObjId()}`;a.addDependency(u);Q.dataLen=Q.bitmap?Q.width*Q.height*4:Q.data.length;this._sendImgData(u,Q);E=[{data:u,width:Q.width,height:Q.height,interpolate:Q.interpolate,count:1}];a.addImageOps(Ze,E,l);if(s){const e={objId:u,fn:Ze,args:E,optionalContent:l};r.set(s,o,e);o&&this._regionalImageCache.set(null,o,e)}return}const u=g.has("SMask")||g.has("Mask");if(i&&c+C<200&&!u){try{const s=new PDFImage({xref:this.xref,res:e,image:t,isInline:i,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:n});Q=await s.createImageData(!0,!1);a.isOffscreenCanvasSupported=this.options.isOffscreenCanvasSupported;a.addImageOps(_e,[Q],l)}catch(e){const t=`Unable to decode inline image: "${e}".`;if(!this.options.ignoreErrors)throw new Error(t);warn(t)}return}let d=`img_${this.idFactory.createObjId()}`,f=!1;if(this.parsingType3Font)d=`${this.idFactory.getDocId()}_type3_${d}`;else if(s&&o){f=this.globalImageCache.shouldCache(o,this.pageIndex);if(f){assert(!i,"Cannot cache an inline image globally.");d=`${this.idFactory.getDocId()}_${d}`}}a.addDependency(d);E=[d,c,C];a.addImageOps(ze,E,l,u);if(f){if(this.globalImageCache.hasDecodeFailed(o)){this.globalImageCache.setData(o,{objId:d,fn:ze,args:E,optionalContent:l,hasMask:u,byteSize:0});this._sendImgData(d,null,f);return}if(c*C>25e4||u){const e=await this.handler.sendWithPromise("commonobj",[d,"CopyLocalImage",{imageRef:o}]);if(e){this.globalImageCache.setData(o,{objId:d,fn:ze,args:E,optionalContent:l,hasMask:u,byteSize:0});this.globalImageCache.addByteSize(o,e);return}}}PDFImage.buildImage({xref:this.xref,res:e,image:t,isInline:i,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:n}).then((async e=>{Q=await e.createImageData(!1,this.options.isOffscreenCanvasSupported);Q.dataLen=Q.bitmap?Q.width*Q.height*4:Q.data.length;Q.ref=o;f&&this.globalImageCache.addByteSize(o,Q.dataLen);return this._sendImgData(d,Q,f)})).catch((e=>{warn(`Unable to decode image "${d}": "${e}".`);o&&this.globalImageCache.addDecodeFailed(o);return this._sendImgData(d,null,f)}));if(s){const e={objId:d,fn:ze,args:E,optionalContent:l,hasMask:u};r.set(s,o,e);if(o){this._regionalImageCache.set(null,o,e);f&&this.globalImageCache.setData(o,{objId:d,fn:ze,args:E,optionalContent:l,hasMask:u,byteSize:0})}}}handleSMask(e,t,i,a,s,r){const n=e.get("G"),g={subtype:e.get("S").name,backdrop:e.get("BC")},o=e.get("TR");if(isPDFFunction(o)){const e=this._pdfFunctionFactory.create(o),t=new Uint8Array(256),i=new Float32Array(1);for(let a=0;a<256;a++){i[0]=a/255;e(i,0,i,0);t[a]=255*i[0]|0}g.transferMap=t}return this.buildFormXObject(t,n,g,i,a,s.state.clone(),r)}handleTransferFunction(e){let t;if(Array.isArray(e))t=e;else{if(!isPDFFunction(e))return null;t=[e]}const i=[];let a=0,s=0;for(const e of t){const t=this.xref.fetchIfRef(e);a++;if(isName(t,"Identity")){i.push(null);continue}if(!isPDFFunction(t))return null;const r=this._pdfFunctionFactory.create(t),n=new Uint8Array(256),g=new Float32Array(1);for(let e=0;e<256;e++){g[0]=e/255;r(g,0,g,0);n[e]=255*g[0]|0}i.push(n);s++}return 1!==a&&4!==a||0===s?null:i}handleTilingType(e,t,i,a,s,r,n,g){const o=new OperatorList,c=Dict.merge({xref:this.xref,dictArray:[s.get("Resources"),i]});return this.getOperatorList({stream:a,task:n,resources:c,operatorList:o}).then((function(){const i=o.getIR(),a=getTilingPatternIR(i,s,t);r.addDependencies(o.dependencies);r.addOp(e,a);s.objId&&g.set(null,s.objId,{operatorListIR:i,dict:s})})).catch((e=>{if(!(e instanceof AbortException)){if(!this.options.ignoreErrors)throw e;warn(`handleTilingType - ignoring pattern: "${e}".`)}}))}async handleSetFont(e,t,i,a,s,r,n=null,g=null){const o=t?.[0]instanceof Name?t[0].name:null;let c=await this.loadFont(o,i,e,n,g);if(c.font.isType3Font)try{await c.loadType3Data(this,e,s);a.addDependencies(c.type3Dependencies)}catch(e){c=new TranslatedFont({loadedName:"g_font_error",font:new ErrorFont(`Type3 font load error: ${e}`),dict:c.font,evaluatorOptions:this.options})}r.font=c.font;c.send(this.handler);return c.loadedName}handleText(e,t){const i=t.font,a=i.charsToGlyphs(e);if(i.data){(!!(t.textRenderingMode&D)||"Pattern"===t.fillColorSpace.name||i.disableFontFace||this.options.disableFontFace)&&PartialEvaluator.buildFontPaths(i,a,this.handler,this.options)}return a}ensureStateFont(e){if(e.font)return;const t=new FormatError("Missing setFont (Tf) operator before text rendering operator.");if(!this.options.ignoreErrors)throw t;warn(`ensureStateFont: "${t}".`)}async setGState({resources:e,gState:t,operatorList:i,cacheKey:a,task:s,stateManager:r,localGStateCache:n,localColorSpaceCache:g}){const o=t.objId;let c=!0;const C=[];let h=Promise.resolve();for(const a of t.getKeys()){const n=t.get(a);switch(a){case"Type":break;case"LW":case"LC":case"LJ":case"ML":case"D":case"RI":case"FL":case"CA":case"ca":C.push([a,n]);break;case"Font":c=!1;h=h.then((()=>this.handleSetFont(e,null,n[0],i,s,r.state).then((function(e){i.addDependency(e);C.push([a,[e,n[1]]])}))));break;case"BM":C.push([a,normalizeBlendMode(n)]);break;case"SMask":if(isName(n,"None")){C.push([a,!1]);break}if(n instanceof Dict){c=!1;h=h.then((()=>this.handleSMask(n,e,i,s,r,g)));C.push([a,!0])}else warn("Unsupported SMask type");break;case"TR":const t=this.handleTransferFunction(n);C.push([a,t]);break;case"OP":case"op":case"OPM":case"BG":case"BG2":case"UCR":case"UCR2":case"TR2":case"HT":case"SM":case"SA":case"AIS":case"TK":info("graphic state operator "+a);break;default:info("Unknown graphic state operator "+a)}}await h;C.length>0&&i.addOp(GA,[C]);c&&n.set(a,o,C)}loadFont(e,t,i,a=null,s=null){const errorFont=async()=>new TranslatedFont({loadedName:"g_font_error",font:new ErrorFont(`Font "${e}" is not available.`),dict:t,evaluatorOptions:this.options});let r;if(t)t instanceof Ref&&(r=t);else{const t=i.get("Font");t&&(r=t.getRaw(e))}if(r){if(this.type3FontRefs?.has(r))return errorFont();if(this.fontCache.has(r))return this.fontCache.get(r);try{t=this.xref.fetchIfRef(r)}catch(e){warn(`loadFont - lookup failed: "${e}".`)}}if(!(t instanceof Dict)){if(!this.options.ignoreErrors&&!this.parsingType3Font){warn(`Font "${e}" is not available.`);return errorFont()}warn(`Font "${e}" is not available -- attempting to fallback to a default font.`);t=a||PartialEvaluator.fallbackFontDict}if(t.cacheKey&&this.fontCache.has(t.cacheKey))return this.fontCache.get(t.cacheKey);const{promise:n,resolve:g}=Promise.withResolvers();let o;try{o=this.preEvaluateFont(t);o.cssFontInfo=s}catch(e){warn(`loadFont - preEvaluateFont failed: "${e}".`);return errorFont()}const{descriptor:c,hash:C}=o,h=r instanceof Ref;let l;if(C&&c instanceof Dict){const e=c.fontAliases||=Object.create(null);if(e[C]){const t=e[C].aliasRef;if(h&&t&&this.fontCache.has(t)){this.fontCache.putAlias(r,t);return this.fontCache.get(r)}}else e[C]={fontID:this.idFactory.createFontId()};h&&(e[C].aliasRef=r);l=e[C].fontID}else l=this.idFactory.createFontId();assert(l?.startsWith("f"),'The "fontID" must be (correctly) defined.');if(h)this.fontCache.put(r,n);else{t.cacheKey=`cacheKey_${l}`;this.fontCache.put(t.cacheKey,n)}t.loadedName=`${this.idFactory.getDocId()}_${l}`;this.translateFont(o).then((e=>{g(new TranslatedFont({loadedName:t.loadedName,font:e,dict:t,evaluatorOptions:this.options}))})).catch((e=>{warn(`loadFont - translateFont failed: "${e}".`);g(new TranslatedFont({loadedName:t.loadedName,font:new ErrorFont(e instanceof Error?e.message:e),dict:t,evaluatorOptions:this.options}))}));return n}buildPath(e,t,i,a=!1){const s=e.length-1;i||(i=[]);if(s<0||e.fnArray[s]!==it){if(a){warn(`Encountered path operator "${t}" inside of a text object.`);e.addOp(MA,null)}let s;switch(t){case TA:const e=i[0]+i[2],t=i[1]+i[3];s=[Math.min(i[0],e),Math.min(i[1],t),Math.max(i[0],e),Math.max(i[1],t)];break;case LA:case HA:s=[i[0],i[1],i[0],i[1]];break;default:s=[1/0,1/0,-1/0,-1/0]}e.addOp(it,[[t],i,s]);a&&e.addOp(UA,null)}else{const a=e.argsArray[s];a[0].push(t);a[1].push(...i);const r=a[2];switch(t){case TA:const e=i[0]+i[2],t=i[1]+i[3];r[0]=Math.min(r[0],i[0],e);r[1]=Math.min(r[1],i[1],t);r[2]=Math.max(r[2],i[0],e);r[3]=Math.max(r[3],i[1],t);break;case LA:case HA:r[0]=Math.min(r[0],i[0]);r[1]=Math.min(r[1],i[1]);r[2]=Math.max(r[2],i[0]);r[3]=Math.max(r[3],i[1])}}}parseColorSpace({cs:e,resources:t,localColorSpaceCache:i}){return ColorSpace.parseAsync({cs:e,xref:this.xref,resources:t,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:i}).catch((e=>{if(e instanceof AbortException)return null;if(this.options.ignoreErrors){warn(`parseColorSpace - ignoring ColorSpace: "${e}".`);return null}throw e}))}parseShading({shading:e,resources:t,localColorSpaceCache:i,localShadingPatternCache:a}){let s,r=a.get(e);if(r)return r;try{s=Pattern.parseShading(e,this.xref,t,this._pdfFunctionFactory,i).getIR()}catch(t){if(t instanceof AbortException)return null;if(this.options.ignoreErrors){warn(`parseShading - ignoring shading: "${t}".`);a.set(e,null);return null}throw t}r=`pattern_${this.idFactory.createObjId()}`;this.parsingType3Font&&(r=`${this.idFactory.getDocId()}_type3_${r}`);a.set(e,r);this.parsingType3Font?this.handler.send("commonobj",[r,"Pattern",s]):this.handler.send("obj",[r,this.pageIndex,"Pattern",s]);return r}handleColorN(e,t,i,a,s,r,n,g,o,c){const C=i.pop();if(C instanceof Name){const h=s.getRaw(C.name),l=h instanceof Ref&&o.getByRef(h);if(l)try{const s=a.base?a.base.getRgb(i,0):null,r=getTilingPatternIR(l.operatorListIR,l.dict,s);e.addOp(t,r);return}catch{}const Q=this.xref.fetchIfRef(h);if(Q){const s=Q instanceof BaseStream?Q.dict:Q,C=s.get("PatternType");if(C===fs){const g=a.base?a.base.getRgb(i,0):null;return this.handleTilingType(t,g,r,Q,s,e,n,o)}if(C===ps){const i=s.get("Shading"),a=this.parseShading({shading:i,resources:r,localColorSpaceCache:g,localShadingPatternCache:c});if(a){const i=lookupMatrix(s.getArray("Matrix"),null);e.addOp(t,["Shading",a,i])}return}throw new FormatError(`Unknown PatternType: ${C}`)}}throw new FormatError(`Unknown PatternName: ${C}`)}_parseVisibilityExpression(e,t,i){if(++t>10){warn("Visibility expression is too deeply nested");return}const a=e.length,s=this.xref.fetchIfRef(e[0]);if(!(a<2)&&s instanceof Name){switch(s.name){case"And":case"Or":case"Not":i.push(s.name);break;default:warn(`Invalid operator ${s.name} in visibility expression`);return}for(let s=1;s0)return{type:"OCMD",expression:t}}const t=i.get("OCGs");if(Array.isArray(t)||t instanceof Dict){const e=[];if(Array.isArray(t))for(const i of t)e.push(i.toString());else e.push(t.objId);return{type:a,ids:e,policy:i.get("P")instanceof Name?i.get("P").name:null,expression:null}}if(t instanceof Ref)return{type:a,id:t.toString()}}return null}getOperatorList({stream:e,task:t,resources:i,operatorList:a,initialState:s=null,fallbackFontDict:r=null}){i||=Dict.empty;s||=new EvalState;if(!a)throw new Error('getOperatorList: missing "operatorList" parameter');const n=this,g=this.xref;let o=!1;const c=new LocalImageCache,C=new LocalColorSpaceCache,h=new LocalGStateCache,l=new LocalTilingPatternCache,Q=new Map,E=i.get("XObject")||Dict.empty,u=i.get("Pattern")||Dict.empty,d=new StateManager(s),f=new EvaluatorPreprocessor(e,g,d),p=new TimeSlotManager;function closePendingRestoreOPS(e){for(let e=0,t=f.savedStatesDepth;e0&&a.addOp(GA,[t]);e=null;continue}}next(new Promise((function(e,s){if(!S)throw new FormatError("GState must be referred to by name.");const r=i.get("ExtGState");if(!(r instanceof Dict))throw new FormatError("ExtGState should be a dictionary.");const g=r.get(F);if(!(g instanceof Dict))throw new FormatError("GState should be a dictionary.");n.setGState({resources:i,gState:g,operatorList:a,cacheKey:F,task:t,stateManager:d,localGStateCache:h,localColorSpaceCache:C}).then(e,s)})).catch((function(e){if(!(e instanceof AbortException)){if(!n.options.ignoreErrors)throw e;warn(`getOperatorList - ignoring ExtGState: "${e}".`)}})));return;case LA:case HA:case JA:case YA:case vA:case KA:case TA:n.buildPath(a,s,e,o);continue;case Le:case He:case Ke:case Te:continue;case Ye:if(!(e[0]instanceof Name)){warn(`Expected name for beginMarkedContentProps arg0=${e[0]}`);a.addOp(Ye,["OC",null]);continue}if("OC"===e[0].name){next(n.parseMarkedContentProps(e[1],i).then((e=>{a.addOp(Ye,["OC",e])})).catch((e=>{if(!(e instanceof AbortException)){if(!n.options.ignoreErrors)throw e;warn(`getOperatorList - ignoring beginMarkedContentProps: "${e}".`);a.addOp(Ye,["OC",null])}})));return}e=[e[0].name,e[1]instanceof Dict?e[1].get("MCID"):null];break;default:if(null!==e){for(w=0,D=e.length;w{if(!(e instanceof AbortException)){if(!this.options.ignoreErrors)throw e;warn(`getOperatorList - ignoring errors during "${t.name}" task: "${e}".`);closePendingRestoreOPS()}}))}getTextContent({stream:e,task:t,resources:s,stateManager:r=null,includeMarkedContent:n=!1,sink:g,seenStyles:o=new Set,viewBox:c,lang:C=null,markedContentData:h=null,disableNormalization:l=!1,keepWhiteSpace:Q=!1}){s||=Dict.empty;r||=new StateManager(new TextState);n&&(h||={level:0});const E={items:[],styles:Object.create(null),lang:C},u={initialized:!1,str:[],totalWidth:0,totalHeight:0,width:0,height:0,vertical:!1,prevTransform:null,textAdvanceScale:0,spaceInFlowMin:0,spaceInFlowMax:0,trackingSpaceMin:1/0,negativeSpaceMax:-1/0,notASpace:-1/0,transform:null,fontName:null,hasEOL:!1},d=[" "," "];let f=0;function saveLastChar(e){const t=(f+1)%2,i=" "!==d[f]&&" "===d[t];d[f]=e;f=t;return!Q&&i}function shouldAddWhitepsace(){return!Q&&" "!==d[f]&&" "===d[(f+1)%2]}function resetLastChars(){d[0]=d[1]=" ";f=0}const p=this,m=this.xref,y=[];let w=null;const D=new LocalImageCache,b=new LocalGStateCache,F=new EvaluatorPreprocessor(e,m,r);let S;function pushWhitespace({width:e=0,height:t=0,transform:i=u.prevTransform,fontName:a=u.fontName}){E.items.push({str:" ",dir:"ltr",width:e,height:t,transform:i,fontName:a,hasEOL:!1})}function getCurrentTextTransform(){const e=S.font,t=[S.fontSize*S.textHScale,0,0,S.fontSize,0,S.textRise];if(e.isType3Font&&(S.fontSize<=1||e.isCharBBox)&&!isArrayEqual(S.fontMatrix,a)){const i=e.bbox[3]-e.bbox[1];i>0&&(t[3]*=i*S.fontMatrix[3])}return Util.transform(S.ctm,Util.transform(S.textMatrix,t))}function ensureTextContentItem(){if(u.initialized)return u;const{font:e,loadedName:t}=S;if(!o.has(t)){o.add(t);E.styles[t]={fontFamily:e.fallbackName,ascent:e.ascent,descent:e.descent,vertical:e.vertical};if(p.options.fontExtraProperties&&e.systemFontInfo){const i=E.styles[t];i.fontSubstitution=e.systemFontInfo.css;i.fontSubstitutionLoadedName=e.systemFontInfo.loadedName}}u.fontName=t;const i=u.transform=getCurrentTextTransform();if(e.vertical){u.width=u.totalWidth=Math.hypot(i[0],i[1]);u.height=u.totalHeight=0;u.vertical=!0}else{u.width=u.totalWidth=0;u.height=u.totalHeight=Math.hypot(i[2],i[3]);u.vertical=!1}const a=Math.hypot(S.textLineMatrix[0],S.textLineMatrix[1]),s=Math.hypot(S.ctm[0],S.ctm[1]);u.textAdvanceScale=s*a;const{fontSize:r}=S;u.trackingSpaceMin=.102*r;u.notASpace=.03*r;u.negativeSpaceMax=-.2*r;u.spaceInFlowMin=.102*r;u.spaceInFlowMax=.6*r;u.hasEOL=!1;u.initialized=!0;return u}function updateAdvanceScale(){if(!u.initialized)return;const e=Math.hypot(S.textLineMatrix[0],S.textLineMatrix[1]),t=Math.hypot(S.ctm[0],S.ctm[1])*e;if(t!==u.textAdvanceScale){if(u.vertical){u.totalHeight+=u.height*u.textAdvanceScale;u.height=0}else{u.totalWidth+=u.width*u.textAdvanceScale;u.width=0}u.textAdvanceScale=t}}function runBidiTransform(e){let t=e.str.join("");l||(t=function normalizeUnicode(e){if(!Ct){Ct=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu;ht=new Map([["ſt","ſt"]])}return e.replaceAll(Ct,((e,t,i)=>t?t.normalize("NFKC"):ht.get(i)))}(t));const i=bidi(t,-1,e.vertical);return{str:i.str,dir:i.dir,width:Math.abs(e.totalWidth),height:Math.abs(e.totalHeight),transform:e.transform,fontName:e.fontName,hasEOL:e.hasEOL}}async function handleSetFont(e,i){const r=await p.loadFont(e,i,s);if(r.font.isType3Font)try{await r.loadType3Data(p,s,t)}catch{}S.loadedName=r.loadedName;S.font=r.font;S.fontMatrix=r.font.fontMatrix||a}function applyInverseRotation(e,t,i){const a=Math.hypot(i[0],i[1]);return[(i[0]*e+i[1]*t)/a,(i[2]*e+i[3]*t)/a]}function compareWithLastPosition(e){const t=getCurrentTextTransform();let i=t[4],a=t[5];if(S.font?.vertical){if(ic[2]||a+ec[3])return!1}else if(i+ec[2]||ac[3])return!1;if(!S.font||!u.prevTransform)return!0;let s=u.prevTransform[4],r=u.prevTransform[5];if(s===i&&r===a)return!0;let n=-1;t[0]&&0===t[1]&&0===t[2]?n=t[0]>0?0:180:t[1]&&0===t[0]&&0===t[3]&&(n=t[1]>0?90:270);switch(n){case 0:break;case 90:[i,a]=[a,i];[s,r]=[r,s];break;case 180:[i,a,s,r]=[-i,-a,-s,-r];break;case 270:[i,a]=[-a,-i];[s,r]=[-r,-s];break;default:[i,a]=applyInverseRotation(i,a,t);[s,r]=applyInverseRotation(s,r,u.prevTransform)}if(S.font.vertical){const e=(r-a)/u.textAdvanceScale,t=i-s,n=Math.sign(u.height);if(e.5*u.width){appendEOL();return!0}resetLastChars();flushTextContentItem();return!0}if(Math.abs(t)>u.width){appendEOL();return!0}e<=n*u.notASpace&&resetLastChars();if(e<=n*u.trackingSpaceMin)if(shouldAddWhitepsace()){resetLastChars();flushTextContentItem();pushWhitespace({height:Math.abs(e)})}else u.height+=e;else if(!addFakeSpaces(e,u.prevTransform,n))if(0===u.str.length){resetLastChars();pushWhitespace({height:Math.abs(e)})}else u.height+=e;Math.abs(t)>.25*u.width&&flushTextContentItem();return!0}const g=(i-s)/u.textAdvanceScale,o=a-r,C=Math.sign(u.width);if(g.5*u.height){appendEOL();return!0}resetLastChars();flushTextContentItem();return!0}if(Math.abs(o)>u.height){appendEOL();return!0}g<=C*u.notASpace&&resetLastChars();if(g<=C*u.trackingSpaceMin)if(shouldAddWhitepsace()){resetLastChars();flushTextContentItem();pushWhitespace({width:Math.abs(g)})}else u.width+=g;else if(!addFakeSpaces(g,u.prevTransform,C))if(0===u.str.length){resetLastChars();pushWhitespace({width:Math.abs(g)})}else u.width+=g;Math.abs(o)>.25*u.height&&flushTextContentItem();return!0}function buildTextContentItem({chars:e,extraSpacing:t}){const i=S.font;if(!e){const e=S.charSpacing+t;e&&(i.vertical?S.translateTextMatrix(0,-e):S.translateTextMatrix(e*S.textHScale,0));Q&&compareWithLastPosition(0);return}const a=i.charsToGlyphs(e),s=S.fontMatrix[0]*S.fontSize;for(let e=0,r=a.length;e0){const e=y.join("");y.length=0;buildTextContentItem({chars:e,extraSpacing:0})}break;case he:if(!r.state.font){p.ensureStateFont(r.state);continue}buildTextContentItem({chars:N[0],extraSpacing:0});break;case Be:if(!r.state.font){p.ensureStateFont(r.state);continue}S.carriageReturn();buildTextContentItem({chars:N[0],extraSpacing:0});break;case Qe:if(!r.state.font){p.ensureStateFont(r.state);continue}S.wordSpacing=N[0];S.charSpacing=N[1];S.carriageReturn();buildTextContentItem({chars:N[2],extraSpacing:0});break;case xe:flushTextContentItem();w??=s.get("XObject")||Dict.empty;R=N[0]instanceof Name;f=N[0].name;if(R&&D.getByName(f))break;next(new Promise((function(e,i){if(!R)throw new FormatError("XObject must be referred to by name.");let a=w.getRaw(f);if(a instanceof Ref){if(D.getByRef(a)){e();return}if(p.globalImageCache.getData(a,p.pageIndex)){e();return}a=m.fetch(a)}if(!(a instanceof BaseStream))throw new FormatError("XObject should be a stream");const E=a.dict.get("Subtype");if(!(E instanceof Name))throw new FormatError("XObject should have a Name subtype");if("Form"!==E.name){D.set(f,a.dict.objId,!0);e();return}const u=r.state.clone(),d=new StateManager(u),y=lookupMatrix(a.dict.getArray("Matrix"),null);y&&d.transform(y);enqueueChunk();const b={enqueueInvoked:!1,enqueue(e,t){this.enqueueInvoked=!0;g.enqueue(e,t)},get desiredSize(){return g.desiredSize},get ready(){return g.ready}};p.getTextContent({stream:a,task:t,resources:a.dict.get("Resources")||s,stateManager:d,includeMarkedContent:n,sink:b,seenStyles:o,viewBox:c,lang:C,markedContentData:h,disableNormalization:l,keepWhiteSpace:Q}).then((function(){b.enqueueInvoked||D.set(f,a.dict.objId,!0);e()}),i)})).catch((function(e){if(!(e instanceof AbortException)){if(!p.options.ignoreErrors)throw e;warn(`getTextContent - ignoring XObject: "${e}".`)}})));return;case GA:R=N[0]instanceof Name;f=N[0].name;if(R&&b.getByName(f))break;next(new Promise((function(e,t){if(!R)throw new FormatError("GState must be referred to by name.");const i=s.get("ExtGState");if(!(i instanceof Dict))throw new FormatError("ExtGState should be a dictionary.");const a=i.get(f);if(!(a instanceof Dict))throw new FormatError("GState should be a dictionary.");const r=a.get("Font");if(r){flushTextContentItem();S.fontName=null;S.fontSize=r[1];handleSetFont(null,r[0]).then(e,t)}else{b.set(f,a.objId,!0);e()}})).catch((function(e){if(!(e instanceof AbortException)){if(!p.options.ignoreErrors)throw e;warn(`getTextContent - ignoring ExtGState: "${e}".`)}})));return;case Je:flushTextContentItem();if(n){h.level++;E.items.push({type:"beginMarkedContent",tag:N[0]instanceof Name?N[0].name:null})}break;case Ye:flushTextContentItem();if(n){h.level++;let e=null;N[1]instanceof Dict&&(e=N[1].get("MCID"));E.items.push({type:"beginMarkedContentProps",id:Number.isInteger(e)?`${p.idFactory.getPageObjId()}_mc${e}`:null,tag:N[0]instanceof Name?N[0].name:null})}break;case ve:flushTextContentItem();if(n){if(0===h.level)break;h.level--;E.items.push({type:"endMarkedContent"})}break;case UA:!e||e.font===S.font&&e.fontSize===S.fontSize&&e.fontName===S.fontName||flushTextContentItem()}if(E.items.length>=g.desiredSize){d=!0;break}}if(d)next(ms);else{flushTextContentItem();enqueueChunk();e()}})).catch((e=>{if(!(e instanceof AbortException)){if(!this.options.ignoreErrors)throw e;warn(`getTextContent - ignoring errors during "${t.name}" task: "${e}".`);flushTextContentItem();enqueueChunk()}}))}async extractDataStructures(e,t){const i=this.xref;let a;const s=this.readToUnicode(t.toUnicode);if(t.composite){const i=e.get("CIDSystemInfo");i instanceof Dict&&(t.cidSystemInfo={registry:stringToPDFString(i.get("Registry")),ordering:stringToPDFString(i.get("Ordering")),supplement:i.get("Supplement")});try{const t=e.get("CIDToGIDMap");t instanceof BaseStream&&(a=t.getBytes())}catch(e){if(!this.options.ignoreErrors)throw e;warn(`extractDataStructures - ignoring CIDToGIDMap data: "${e}".`)}}const r=[];let n,g=null;if(e.has("Encoding")){n=e.get("Encoding");if(n instanceof Dict){g=n.get("BaseEncoding");g=g instanceof Name?g.name:null;if(n.has("Differences")){const e=n.get("Differences");let t=0;for(const a of e){const e=i.fetchIfRef(a);if("number"==typeof e)t=e;else{if(!(e instanceof Name))throw new FormatError(`Invalid entry in 'Differences' array: ${e}`);r[t++]=e.name}}}}else if(n instanceof Name)g=n.name;else{const e="Encoding is not a Name nor a Dict";if(!this.options.ignoreErrors)throw new FormatError(e);warn(e)}"MacRomanEncoding"!==g&&"MacExpertEncoding"!==g&&"WinAnsiEncoding"!==g&&(g=null)}const o=!t.file||t.isInternalFont,c=qi()[t.name];g&&o&&c&&(g=null);if(g)t.defaultEncoding=getEncoding(g);else{const e=!!(t.flags&Mi),i=!!(t.flags&xi);n=hi;"TrueType"!==t.type||i||(n=li);if(e||c){n=Ci;o&&(/Symbol/i.test(t.name)?n=Bi:/Dingbats/i.test(t.name)?n=Qi:/Wingdings/i.test(t.name)&&(n=li))}t.defaultEncoding=n}t.differences=r;t.baseEncodingName=g;t.hasEncoding=!!g||r.length>0;t.dict=e;t.toUnicode=await s;const C=await this.buildToUnicode(t);t.toUnicode=C;a&&(t.cidToGidMap=this.readCidToGidMap(a,C));return t}_simpleFontToUnicode(e,t=!1){assert(!e.composite,"Must be a simple font.");const i=[],a=e.defaultEncoding.slice(),s=e.baseEncodingName,r=e.differences;for(const e in r){const t=r[e];".notdef"!==t&&(a[e]=t)}const n=wi();for(const r in a){let g=a[r];if(""===g)continue;let o=n[g];if(void 0!==o){i[r]=String.fromCharCode(o);continue}let c=0;switch(g[0]){case"G":3===g.length&&(c=parseInt(g.substring(1),16));break;case"g":5===g.length&&(c=parseInt(g.substring(1),16));break;case"C":case"c":if(g.length>=3&&g.length<=4){const i=g.substring(1);if(t){c=parseInt(i,16);break}c=+i;if(Number.isNaN(c)&&Number.isInteger(parseInt(i,16)))return this._simpleFontToUnicode(e,!0)}break;case"u":o=getUnicodeForGlyph(g,n);-1!==o&&(c=o);break;default:switch(g){case"f_h":case"f_t":case"T_h":i[r]=g.replaceAll("_","");continue}}if(c>0&&c<=1114111&&Number.isInteger(c)){if(s&&c===+r){const e=getEncoding(s);if(e&&(g=e[r])){i[r]=String.fromCharCode(n[g]);continue}}i[r]=String.fromCodePoint(c)}}return i}async buildToUnicode(e){e.hasIncludedToUnicodeMap=e.toUnicode?.length>0;if(e.hasIncludedToUnicodeMap){!e.composite&&e.hasEncoding&&(e.fallbackToUnicode=this._simpleFontToUnicode(e));return e.toUnicode}if(!e.composite)return new ToUnicodeMap(this._simpleFontToUnicode(e));if(e.composite&&(e.cMap.builtInCMap&&!(e.cMap instanceof IdentityCMap)||"Adobe"===e.cidSystemInfo?.registry&&("GB1"===e.cidSystemInfo.ordering||"CNS1"===e.cidSystemInfo.ordering||"Japan1"===e.cidSystemInfo.ordering||"Korea1"===e.cidSystemInfo.ordering))){const{registry:t,ordering:i}=e.cidSystemInfo,a=Name.get(`${t}-${i}-UCS2`),s=await CMapFactory.create({encoding:a,fetchBuiltInCMap:this._fetchBuiltInCMapBound,useCMap:null}),r=[],n=[];e.cMap.forEach((function(e,t){if(t>65535)throw new FormatError("Max size of CID is 65,535");const i=s.lookup(t);if(i){n.length=0;for(let e=0,t=i.length;e>1;(0!==s||t.has(r))&&(i[r]=s)}return i}extractWidths(e,t,i){const a=this.xref;let s=[],r=0;const n=[];let g;if(i.composite){const t=e.get("DW");r="number"==typeof t?Math.ceil(t):1e3;const o=e.get("W");if(Array.isArray(o))for(let e=0,t=o.length;e{const t=o.get(e),s=new OperatorList;return a.getOperatorList({stream:t,task:i,resources:c,operatorList:s}).then((()=>{s.fnArray[0]===ue&&this._removeType3ColorOperators(s,E);C[e]=s.getIR();for(const e of s.dependencies)n.add(e)})).catch((function(t){warn(`Type3 font resource "${e}" is not available.`);const i=new OperatorList;C[e]=i.getIR()}))}));this.type3Loaded=g.then((()=>{r.charProcOperatorList=C;if(this._bbox){r.isCharBBox=!0;r.bbox=this._bbox}}));return this.type3Loaded}_removeType3ColorOperators(e,t=NaN){const i=Util.normalizeRect(e.argsArray[0].slice(2)),a=i[2]-i[0],s=i[3]-i[1],r=Math.hypot(a,s);if(0===a||0===s){e.fnArray.splice(0,1);e.argsArray.splice(0,1)}else if(0===t||Math.round(r/t)>=10){this._bbox||(this._bbox=[1/0,1/0,-1/0,-1/0]);this._bbox[0]=Math.min(this._bbox[0],i[0]);this._bbox[1]=Math.min(this._bbox[1],i[1]);this._bbox[2]=Math.max(this._bbox[2],i[2]);this._bbox[3]=Math.max(this._bbox[3],i[3])}let n=0,g=e.length;for(;n=LA&&r<=zA;if(s.variableArgs)g>n&&info(`Command ${a}: expected [0, ${n}] args, but received ${g} args.`);else{if(g!==n){const e=this.nonProcessedArgs;for(;g>n;){e.push(t.shift());g--}for(;gEvaluatorPreprocessor.MAX_INVALID_PATH_OPS)throw new FormatError(`Invalid ${e}`);warn(`Skipping ${e}`);null!==t&&(t.length=0);continue}}this.preprocessCommand(r,t);e.fn=r;e.args=t;return!0}if(i===Bt)return!1;if(null!==i){null===t&&(t=[]);t.push(i);if(t.length>33)throw new FormatError("Too many arguments")}}}preprocessCommand(e,t){switch(0|e){case MA:this.stateManager.save();break;case UA:this.stateManager.restore();break;case xA:this.stateManager.transform(t)}}}class DefaultAppearanceEvaluator extends EvaluatorPreprocessor{constructor(e){super(new StringStream(e))}parse(){const e={fn:0,args:[]},t={fontSize:0,fontName:"",fontColor:new Uint8ClampedArray(3)};try{for(;;){e.args.length=0;if(!this.read(e))break;if(0!==this.savedStatesDepth)continue;const{fn:i,args:a}=e;switch(0|i){case re:const[e,i]=a;e instanceof Name&&(t.fontName=e.name);"number"==typeof i&&i>0&&(t.fontSize=i);break;case Se:ColorSpace.singletons.rgb.getRgbItem(a,0,t.fontColor,0);break;case be:ColorSpace.singletons.gray.getRgbItem(a,0,t.fontColor,0);break;case Re:ColorSpace.singletons.cmyk.getRgbItem(a,0,t.fontColor,0)}}}catch(e){warn(`parseDefaultAppearance - ignoring errors: "${e}".`)}return t}}function parseDefaultAppearance(e){return new DefaultAppearanceEvaluator(e).parse()}class AppearanceStreamEvaluator extends EvaluatorPreprocessor{constructor(e,t,i){super(e);this.stream=e;this.evaluatorOptions=t;this.xref=i;this.resources=e.dict?.get("Resources")}parse(){const e={fn:0,args:[]};let t={scaleFactor:1,fontSize:0,fontName:"",fontColor:new Uint8ClampedArray(3),fillColorSpace:ColorSpace.singletons.gray},i=!1;const a=[];try{for(;;){e.args.length=0;if(i||!this.read(e))break;const{fn:s,args:r}=e;switch(0|s){case MA:a.push({scaleFactor:t.scaleFactor,fontSize:t.fontSize,fontName:t.fontName,fontColor:t.fontColor.slice(),fillColorSpace:t.fillColorSpace});break;case UA:t=a.pop()||t;break;case ce:t.scaleFactor*=Math.hypot(r[0],r[1]);break;case re:const[e,s]=r;e instanceof Name&&(t.fontName=e.name);"number"==typeof s&&s>0&&(t.fontSize=s*t.scaleFactor);break;case fe:t.fillColorSpace=ColorSpace.parse({cs:r[0],xref:this.xref,resources:this.resources,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:this._localColorSpaceCache});break;case ye:t.fillColorSpace.getRgbItem(r,0,t.fontColor,0);break;case Se:ColorSpace.singletons.rgb.getRgbItem(r,0,t.fontColor,0);break;case be:ColorSpace.singletons.gray.getRgbItem(r,0,t.fontColor,0);break;case Re:ColorSpace.singletons.cmyk.getRgbItem(r,0,t.fontColor,0);break;case he:case le:case Be:case Qe:i=!0}}}catch(e){warn(`parseAppearanceStream - ignoring errors: "${e}".`)}this.stream.reset();delete t.scaleFactor;delete t.fillColorSpace;return t}get _localColorSpaceCache(){return shadow(this,"_localColorSpaceCache",new LocalColorSpaceCache)}get _pdfFunctionFactory(){return shadow(this,"_pdfFunctionFactory",new PDFFunctionFactory({xref:this.xref,isEvalSupported:this.evaluatorOptions.isEvalSupported}))}}function getPdfColor(e,t){if(e[0]===e[1]&&e[1]===e[2]){return`${numberToString(e[0]/255)} ${t?"g":"G"}`}return Array.from(e,(e=>numberToString(e/255))).join(" ")+" "+(t?"rg":"RG")}class FakeUnicodeFont{constructor(e,t){this.xref=e;this.widths=null;this.firstChar=1/0;this.lastChar=-1/0;this.fontFamily=t;const i=new OffscreenCanvas(1,1);this.ctxMeasure=i.getContext("2d",{willReadFrequently:!0});FakeUnicodeFont._fontNameId||(FakeUnicodeFont._fontNameId=1);this.fontName=Name.get(`InvalidPDFjsFont_${t}_${FakeUnicodeFont._fontNameId++}`)}get fontDescriptorRef(){if(!FakeUnicodeFont._fontDescriptorRef){const e=new Dict(this.xref);e.set("Type",Name.get("FontDescriptor"));e.set("FontName",this.fontName);e.set("FontFamily","MyriadPro Regular");e.set("FontBBox",[0,0,0,0]);e.set("FontStretch",Name.get("Normal"));e.set("FontWeight",400);e.set("ItalicAngle",0);FakeUnicodeFont._fontDescriptorRef=this.xref.getNewPersistentRef(e)}return FakeUnicodeFont._fontDescriptorRef}get descendantFontRef(){const e=new Dict(this.xref);e.set("BaseFont",this.fontName);e.set("Type",Name.get("Font"));e.set("Subtype",Name.get("CIDFontType0"));e.set("CIDToGIDMap",Name.get("Identity"));e.set("FirstChar",this.firstChar);e.set("LastChar",this.lastChar);e.set("FontDescriptor",this.fontDescriptorRef);e.set("DW",1e3);const t=[],i=[...this.widths.entries()].sort();let a=null,s=null;for(const[e,r]of i)if(a)if(e===a+s.length)s.push(r);else{t.push(a,s);a=e;s=[r]}else{a=e;s=[r]}a&&t.push(a,s);e.set("W",t);const r=new Dict(this.xref);r.set("Ordering","Identity");r.set("Registry","Adobe");r.set("Supplement",0);e.set("CIDSystemInfo",r);return this.xref.getNewPersistentRef(e)}get baseFontRef(){const e=new Dict(this.xref);e.set("BaseFont",this.fontName);e.set("Type",Name.get("Font"));e.set("Subtype",Name.get("Type0"));e.set("Encoding",Name.get("Identity-H"));e.set("DescendantFonts",[this.descendantFontRef]);e.set("ToUnicode",Name.get("Identity-H"));return this.xref.getNewPersistentRef(e)}get resources(){const e=new Dict(this.xref),t=new Dict(this.xref);t.set(this.fontName.name,this.baseFontRef);e.set("Font",t);return e}_createContext(){this.widths=new Map;this.ctxMeasure.font=`1000px ${this.fontFamily}`;return this.ctxMeasure}createFontResources(e){const t=this._createContext();for(const i of e.split(/\r\n?|\n/))for(const e of i.split("")){const i=e.charCodeAt(0);if(this.widths.has(i))continue;const a=t.measureText(e),s=Math.ceil(a.width);this.widths.set(i,s);this.firstChar=Math.min(i,this.firstChar);this.lastChar=Math.max(i,this.lastChar)}return this.resources}static getFirstPositionInfo(e,t,i){const[a,n,g,o]=e;let c=g-a,C=o-n;t%180!=0&&([c,C]=[C,c]);const h=s*i;return{coords:[0,C+r*i-h],bbox:[0,0,c,C],matrix:0!==t?getRotationMatrix(t,C,h):void 0}}createAppearance(e,t,i,a,n,g){const o=this._createContext(),c=[];let C=-1/0;for(const t of e.split(/\r\n?|\n/)){c.push(t);const e=o.measureText(t).width;C=Math.max(C,e);for(const e of codePointIter(t)){const t=String.fromCodePoint(e);let i=this.widths.get(e);if(void 0===i){const a=o.measureText(t);i=Math.ceil(a.width);this.widths.set(e,i);this.firstChar=Math.min(e,this.firstChar);this.lastChar=Math.max(e,this.lastChar)}}}C*=a/1e3;const[h,l,Q,E]=t;let u=Q-h,d=E-l;i%180!=0&&([u,d]=[d,u]);let f=1;C>u&&(f=u/C);let p=1;const m=s*a,y=r*a,w=m*c.length;w>d&&(p=d/w);const D=a*Math.min(f,p),b=["q",`0 0 ${numberToString(u)} ${numberToString(d)} re W n`,"BT",`1 0 0 1 0 ${numberToString(d+y)} Tm 0 Tc ${getPdfColor(n,!0)}`,`/${this.fontName.name} ${numberToString(D)} Tf`],{resources:F}=this;if(1!==(g="number"==typeof g&&g>=0&&g<=1?g:1)){b.push("/R0 gs");const e=new Dict(this.xref),t=new Dict(this.xref);t.set("ca",g);t.set("CA",g);t.set("Type",Name.get("ExtGState"));e.set("R0",t);F.set("ExtGState",e)}const S=numberToString(m);for(const e of c)b.push(`0 -${S} Td <${stringToUTF16HexString(e)}> Tj`);b.push("ET","Q");const k=b.join("\n"),R=new Dict(this.xref);R.set("Subtype",Name.get("Form"));R.set("Type",Name.get("XObject"));R.set("BBox",[0,0,u,d]);R.set("Length",k.length);R.set("Resources",F);if(i){const e=getRotationMatrix(i,u,d);R.set("Matrix",e)}const N=new StringStream(k);N.dict=R;return N}}class NameOrNumberTree{constructor(e,t,i){this.root=e;this.xref=t;this._type=i}getAll(){const e=new Map;if(!this.root)return e;const t=this.xref,i=new RefSet;i.put(this.root);const a=[this.root];for(;a.length>0;){const s=t.fetchIfRef(a.shift());if(!(s instanceof Dict))continue;if(s.has("Kids")){const e=s.get("Kids");if(!Array.isArray(e))continue;for(const t of e){if(i.has(t))throw new FormatError(`Duplicate entry in "${this._type}" tree.`);a.push(t);i.put(t)}continue}const r=s.get(this._type);if(Array.isArray(r))for(let i=0,a=r.length;i10){warn(`Search depth limit reached for "${this._type}" tree.`);return null}const s=i.get("Kids");if(!Array.isArray(s))return null;let r=0,n=s.length-1;for(;r<=n;){const a=r+n>>1,g=t.fetchIfRef(s[a]),o=g.get("Limits");if(et.fetchIfRef(o[1]))){i=g;break}r=a+1}}if(r>n)return null}const s=i.get(this._type);if(Array.isArray(s)){let i=0,a=s.length-2;for(;i<=a;){const r=i+a>>1,n=r+(1&r),g=t.fetchIfRef(s[n]);if(eg))return s[n+1];i=n+2}}}return null}get(e){return this.xref.fetchIfRef(this.getRaw(e))}}class NameTree extends NameOrNumberTree{constructor(e,t){super(e,t,"Names")}}class NumberTree extends NameOrNumberTree{constructor(e,t){super(e,t,"Nums")}}function clearGlobalCaches(){!function clearPatternCaches(){Qa=Object.create(null)}();!function clearPrimitiveCaches(){Qt=Object.create(null);Et=Object.create(null);ut=Object.create(null)}();!function clearUnicodeCaches(){ki.clear()}();JpxImage.cleanup()}function pickPlatformItem(e){return e instanceof Dict?e.has("UF")?e.get("UF"):e.has("F")?e.get("F"):e.has("Unix")?e.get("Unix"):e.has("Mac")?e.get("Mac"):e.has("DOS")?e.get("DOS"):null:null}class FileSpec{#U=!1;constructor(e,t,i=!1){if(e instanceof Dict){this.xref=t;this.root=e;e.has("FS")&&(this.fs=e.get("FS"));e.has("RF")&&warn("Related file specifications are not supported");i||(e.has("EF")?this.#U=!0:warn("Non-embedded file specifications are not supported"))}}get filename(){let e="";const t=pickPlatformItem(this.root);t&&"string"==typeof t&&(e=stringToPDFString(t).replaceAll("\\\\","\\").replaceAll("\\/","/").replaceAll("\\","/"));return shadow(this,"filename",e||"unnamed")}get content(){if(!this.#U)return null;this._contentRef||=pickPlatformItem(this.root?.get("EF"));let e=null;if(this._contentRef){const t=this.xref.fetchIfRef(this._contentRef);t instanceof BaseStream?e=t.getBytes():warn("Embedded file specification points to non-existing/invalid content")}else warn("Embedded file specification does not have any content");return e}get description(){let e="";const t=this.root?.get("Desc");t&&"string"==typeof t&&(e=stringToPDFString(t));return shadow(this,"description",e)}get serializable(){return{rawFilename:this.filename,filename:(e=this.filename,e.substring(e.lastIndexOf("/")+1)),content:this.content,description:this.description};var e}}const ys=0,ws=-2,Ds=-3,bs=-4,Fs=-5,Ss=-6,ks=-9;function isWhitespace(e,t){const i=e[t];return" "===i||"\n"===i||"\r"===i||"\t"===i}class XMLParserBase{_resolveEntities(e){return e.replaceAll(/&([^;]+);/g,((e,t)=>{if("#x"===t.substring(0,2))return String.fromCodePoint(parseInt(t.substring(2),16));if("#"===t.substring(0,1))return String.fromCodePoint(parseInt(t.substring(1),10));switch(t){case"lt":return"<";case"gt":return">";case"amp":return"&";case"quot":return'"';case"apos":return"'"}return this.onResolveEntity(t)}))}_parseContent(e,t){const i=[];let a=t;function skipWs(){for(;a"!==e[a]&&"/"!==e[a];)++a;const s=e.substring(t,a);skipWs();for(;a"!==e[a]&&"/"!==e[a]&&"?"!==e[a];){skipWs();let t="",s="";for(;a"!==e[i]&&"?"!==e[i]&&"/"!==e[i];)++i;const a=e.substring(t,i);!function skipWs(){for(;i"!==e[i+1]);)++i;return{name:a,value:e.substring(s,i),parsed:i-t}}parseXml(e){let t=0;for(;t",i);if(t<0){this.onError(ks);return}this.onEndElement(e.substring(i,t));i=t+1;break;case"?":++i;const a=this._parseProcessingInstruction(e,i);if("?>"!==e.substring(i+a.parsed,i+a.parsed+2)){this.onError(Ds);return}this.onPi(a.name,a.value);i+=a.parsed+2;break;case"!":if("--"===e.substring(i+1,i+3)){t=e.indexOf("--\x3e",i+3);if(t<0){this.onError(Fs);return}this.onComment(e.substring(i+3,t));i=t+3}else if("[CDATA["===e.substring(i+1,i+8)){t=e.indexOf("]]>",i+8);if(t<0){this.onError(ws);return}this.onCdata(e.substring(i+8,t));i=t+3}else{if("DOCTYPE"!==e.substring(i+1,i+8)){this.onError(Ss);return}{const a=e.indexOf("[",i+8);let s=!1;t=e.indexOf(">",i+8);if(t<0){this.onError(bs);return}if(a>0&&t>a){t=e.indexOf("]>",i+8);if(t<0){this.onError(bs);return}s=!0}const r=e.substring(i+8,t+(s?1:0));this.onDoctype(r);i=t+(s?2:1)}}break;default:const s=this._parseContent(e,i);if(null===s){this.onError(Ss);return}let r=!1;if("/>"===e.substring(i+s.parsed,i+s.parsed+2))r=!0;else if(">"!==e.substring(i+s.parsed,i+s.parsed+1)){this.onError(ks);return}this.onBeginElement(s.name,s.attributes,r);i+=s.parsed+(r?2:1)}}else{for(;i0}searchNode(e,t){if(t>=e.length)return this;const i=e[t];if(i.name.startsWith("#")&&t0){a.push([s,0]);s=s.childNodes[0]}else{if(0===a.length)return null;for(;0!==a.length;){const[e,t]=a.pop(),i=t+1;if(i");for(const t of this.childNodes)t.dump(e);e.push(``)}else this.nodeValue?e.push(`>${encodeToXmlString(this.nodeValue)}`):e.push("/>")}else e.push(encodeToXmlString(this.nodeValue))}}class SimpleXMLParser extends XMLParserBase{constructor({hasAttributes:e=!1,lowerCaseName:t=!1}){super();this._currentFragment=null;this._stack=null;this._errorCode=ys;this._hasAttributes=e;this._lowerCaseName=t}parseFromString(e){this._currentFragment=[];this._stack=[];this._errorCode=ys;this.parseXml(e);if(this._errorCode!==ys)return;const[t]=this._currentFragment;return t?{documentElement:t}:void 0}onText(e){if(function isWhitespaceString(e){for(let t=0,i=e.length;t\\376\\377([^<]+)/g,(function(e,t){const i=t.replaceAll(/\\([0-3])([0-7])([0-7])/g,(function(e,t,i,a){return String.fromCharCode(64*t+8*i+1*a)})).replaceAll(/&(amp|apos|gt|lt|quot);/g,(function(e,t){switch(t){case"amp":return"&";case"apos":return"'";case"gt":return">";case"lt":return"<";case"quot":return'"'}throw new Error(`_repair: ${t} isn't defined.`)})),a=[">"];for(let e=0,t=i.length;e=32&&t<127&&60!==t&&62!==t&&38!==t?a.push(String.fromCharCode(t)):a.push("&#x"+(65536+t).toString(16).substring(1)+";")}return a.join("")}))}_getSequence(e){const t=e.nodeName;return"rdf:bag"!==t&&"rdf:seq"!==t&&"rdf:alt"!==t?null:e.childNodes.filter((e=>"rdf:li"===e.nodeName))}_parseArray(e){if(!e.hasChildNodes())return;const[t]=e.childNodes,i=this._getSequence(t)||[];this._metadataMap.set(e.nodeName,i.map((e=>e.textContent.trim())))}_parse(e){let t=e.documentElement;if("rdf:rdf"!==t.nodeName){t=t.firstChild;for(;t&&"rdf:rdf"!==t.nodeName;)t=t.nextSibling}if(t&&"rdf:rdf"===t.nodeName&&t.hasChildNodes())for(const e of t.childNodes)if("rdf:description"===e.nodeName)for(const t of e.childNodes){const e=t.nodeName;switch(e){case"#text":continue;case"dc:creator":case"dc:subject":this._parseArray(t);continue}this._metadataMap.set(e,t.textContent.trim())}}get serializable(){return{parsedData:this._metadataMap,rawData:this._data}}}const Rs=1,Ns=2,Gs=3,Ms=4,Us=5;class StructTreeRoot{constructor(e,t){this.dict=e;this.ref=t instanceof Ref?t:null;this.roleMap=new Map;this.structParentIds=null}init(){this.readRoleMap()}#x(e,t,i){if(!(e instanceof Ref)||t<0)return;this.structParentIds||=new RefSetCache;let a=this.structParentIds.get(e);if(!a){a=[];this.structParentIds.put(e,a)}a.push([t,i])}addAnnotationIdToPage(e,t){this.#x(e,t,Ms)}readRoleMap(){const e=this.dict.get("RoleMap");if(e instanceof Dict)for(const[t,i]of e)i instanceof Name&&this.roleMap.set(t,i.name)}static async canCreateStructureTree({catalogRef:e,pdfManager:t,newAnnotationsByPage:i}){if(!(e instanceof Ref)){warn("Cannot save the struct tree: no catalog reference.");return!1}let a=0,s=!0;for(const[e,r]of i){const{ref:i}=await t.getPage(e);if(!(i instanceof Ref)){warn(`Cannot save the struct tree: page ${e} has no ref.`);s=!0;break}for(const e of r)if(e.accessibilityData?.type){e.parentTreeId=a++;s=!1}}if(s){for(const e of i.values())for(const t of e)delete t.parentTreeId;return!1}return!0}static async createStructureTree({newAnnotationsByPage:e,xref:t,catalogRef:i,pdfManager:a,changes:s}){const r=a.catalog.cloneDict(),n=new RefSetCache;n.put(i,r);const g=t.getNewTemporaryRef();r.set("StructTreeRoot",g);const o=new Dict(t);o.set("Type",Name.get("StructTreeRoot"));const c=t.getNewTemporaryRef();o.set("ParentTree",c);const C=[];o.set("K",C);n.put(g,o);const h=new Dict(t),l=[];h.set("Nums",l);const Q=await this.#L({newAnnotationsByPage:e,structTreeRootRef:g,structTreeRoot:null,kids:C,nums:l,xref:t,pdfManager:a,changes:s,cache:n});o.set("ParentTreeNextKey",Q);n.put(c,h);for(const[e,t]of n.items())s.put(e,{data:t})}async canUpdateStructTree({pdfManager:e,xref:t,newAnnotationsByPage:i}){if(!this.ref){warn("Cannot update the struct tree: no root reference.");return!1}let a=this.dict.get("ParentTreeNextKey");if(!Number.isInteger(a)||a<0){warn("Cannot update the struct tree: invalid next key.");return!1}const s=this.dict.get("ParentTree");if(!(s instanceof Dict)){warn("Cannot update the struct tree: ParentTree isn't a dict.");return!1}const r=s.get("Nums");if(!Array.isArray(r)){warn("Cannot update the struct tree: nums isn't an array.");return!1}const n=new NumberTree(s,t);for(const t of i.keys()){const{pageDict:i}=await e.getPage(t);if(!i.has("StructParents"))continue;const a=i.get("StructParents");if(!Number.isInteger(a)||!Array.isArray(n.get(a))){warn(`Cannot save the struct tree: page ${t} has a wrong id.`);return!1}}let g=!0;for(const[t,s]of i){const{pageDict:i}=await e.getPage(t);StructTreeRoot.#H({elements:s,xref:this.dict.xref,pageDict:i,numberTree:n});for(const e of s)if(e.accessibilityData?.type){e.accessibilityData.structParent>=0||(e.parentTreeId=a++);g=!1}}if(g){for(const e of i.values())for(const t of e){delete t.parentTreeId;delete t.structTreeParent}return!1}return!0}async updateStructureTree({newAnnotationsByPage:e,pdfManager:t,changes:i}){const a=this.dict.xref,s=this.dict.clone(),r=this.ref,n=new RefSetCache;n.put(r,s);let g,o=s.getRaw("ParentTree");if(o instanceof Ref)g=a.fetch(o);else{g=o;o=a.getNewTemporaryRef();s.set("ParentTree",o)}g=g.clone();n.put(o,g);let c=g.getRaw("Nums"),C=null;if(c instanceof Ref){C=c;c=a.fetch(C)}c=c.slice();C||g.set("Nums",c);const h=await StructTreeRoot.#L({newAnnotationsByPage:e,structTreeRootRef:r,structTreeRoot:this,kids:null,nums:c,xref:a,pdfManager:t,changes:i,cache:n});if(-1!==h){s.set("ParentTreeNextKey",h);C&&n.put(C,c);for(const[e,t]of n.items())i.put(e,{data:t})}}static async#L({newAnnotationsByPage:e,structTreeRootRef:t,structTreeRoot:i,kids:a,nums:s,xref:r,pdfManager:n,changes:g,cache:o}){const c=Name.get("OBJR");let C,h=-1;for(const[l,Q]of e){const e=await n.getPage(l),{ref:E}=e,u=E instanceof Ref;for(const{accessibilityData:n,ref:d,parentTreeId:f,structTreeParent:p}of Q){if(!n?.type)continue;const{structParent:Q}=n;if(i&&Number.isInteger(Q)&&Q>=0){let t=(C||=new Map).get(l);if(void 0===t){t=new StructTreePage(i,e.pageDict).collectObjects(E);C.set(l,t)}const a=t?.get(Q);if(a){const e=r.fetch(a).clone();StructTreeRoot.#J(e,n);g.put(a,{data:e});continue}}h=Math.max(h,f);const m=r.getNewTemporaryRef(),y=new Dict(r);StructTreeRoot.#J(y,n);await this.#Y({structTreeParent:p,tagDict:y,newTagRef:m,structTreeRootRef:t,fallbackKids:a,xref:r,cache:o});const w=new Dict(r);y.set("K",w);w.set("Type",c);u&&w.set("Pg",E);w.set("Obj",d);o.put(m,y);s.push(f,m)}}return h+1}static#J(e,{type:t,title:i,lang:a,alt:s,expanded:r,actualText:n}){e.set("S",Name.get(t));i&&e.set("T",stringToAsciiOrUTF16BE(i));a&&e.set("Lang",stringToAsciiOrUTF16BE(a));s&&e.set("Alt",stringToAsciiOrUTF16BE(s));r&&e.set("E",stringToAsciiOrUTF16BE(r));n&&e.set("ActualText",stringToAsciiOrUTF16BE(n))}static#H({elements:e,xref:t,pageDict:i,numberTree:a}){const s=new Map;for(const t of e)if(t.structTreeParentId){const e=parseInt(t.structTreeParentId.split("_mc")[1],10);let i=s.get(e);if(!i){i=[];s.set(e,i)}i.push(t)}const r=i.get("StructParents");if(!Number.isInteger(r))return;const n=a.get(r),updateElement=(e,i,a)=>{const r=s.get(e);if(r){const e=i.getRaw("P"),s=t.fetchIfRef(e);if(e instanceof Ref&&s instanceof Dict){const e={ref:a,dict:i};for(const t of r)t.structTreeParent=e}return!0}return!1};for(const e of n){if(!(e instanceof Ref))continue;const i=t.fetch(e),a=i.get("K");if(Number.isInteger(a))updateElement(a,i,e);else if(Array.isArray(a))for(let s of a){s=t.fetchIfRef(s);if(Number.isInteger(s)&&updateElement(s,i,e))break;if(!(s instanceof Dict))continue;if(!isName(s.get("Type"),"MCR"))break;const a=s.get("MCID");if(Number.isInteger(a)&&updateElement(a,i,e))break}}}static async#Y({structTreeParent:e,tagDict:t,newTagRef:i,structTreeRootRef:a,fallbackKids:s,xref:r,cache:n}){let g,o=null;if(e){({ref:o}=e);g=e.dict.getRaw("P")||a}else g=a;t.set("P",g);const c=r.fetchIfRef(g);if(!c){s.push(i);return}let C=n.get(g);if(!C){C=c.clone();n.put(g,C)}const h=C.getRaw("K");let l=h instanceof Ref?n.get(h):null;if(!l){l=r.fetchIfRef(h);l=Array.isArray(l)?l.slice():[h];const e=r.getNewTemporaryRef();C.set("K",e);n.put(e,l)}const Q=l.indexOf(o);l.splice(Q>=0?Q+1:l.length,0,i)}}class StructElementNode{constructor(e,t){this.tree=e;this.dict=t;this.kids=[];this.parseKids()}get role(){const e=this.dict.get("S"),t=e instanceof Name?e.name:"",{root:i}=this.tree;return i.roleMap.has(t)?i.roleMap.get(t):t}parseKids(){let e=null;const t=this.dict.getRaw("Pg");t instanceof Ref&&(e=t.toString());const i=this.dict.get("K");if(Array.isArray(i))for(const t of i){const i=this.parseKid(e,t);i&&this.kids.push(i)}else{const t=this.parseKid(e,i);t&&this.kids.push(t)}}parseKid(e,t){if(Number.isInteger(t))return this.tree.pageDict.objId!==e?null:new StructElement({type:Rs,mcid:t,pageObjId:e});let i=null;t instanceof Ref?i=this.dict.xref.fetch(t):t instanceof Dict&&(i=t);if(!i)return null;const a=i.getRaw("Pg");a instanceof Ref&&(e=a.toString());const s=i.get("Type")instanceof Name?i.get("Type").name:null;if("MCR"===s){if(this.tree.pageDict.objId!==e)return null;const t=i.getRaw("Stm");return new StructElement({type:Ns,refObjId:t instanceof Ref?t.toString():null,pageObjId:e,mcid:i.get("MCID")})}if("OBJR"===s){if(this.tree.pageDict.objId!==e)return null;const t=i.getRaw("Obj");return new StructElement({type:Gs,refObjId:t instanceof Ref?t.toString():null,pageObjId:e})}return new StructElement({type:Us,dict:i})}}class StructElement{constructor({type:e,dict:t=null,mcid:i=null,pageObjId:a=null,refObjId:s=null}){this.type=e;this.dict=t;this.mcid=i;this.pageObjId=a;this.refObjId=s;this.parentNode=null}}class StructTreePage{constructor(e,t){this.root=e;this.rootDict=e?e.dict:null;this.pageDict=t;this.nodes=[]}collectObjects(e){if(!(this.root&&this.rootDict&&e instanceof Ref))return null;const t=this.rootDict.get("ParentTree");if(!t)return null;const i=this.root.structParentIds?.get(e);if(!i)return null;const a=new Map,s=new NumberTree(t,this.rootDict.xref);for(const[e]of i){const t=s.getRaw(e);t instanceof Ref&&a.set(e,t)}return a}parse(e){if(!(this.root&&this.rootDict&&e instanceof Ref))return;const t=this.rootDict.get("ParentTree");if(!t)return;const i=this.pageDict.get("StructParents"),a=this.root.structParentIds?.get(e);if(!Number.isInteger(i)&&!a)return;const s=new Map,r=new NumberTree(t,this.rootDict.xref);if(Number.isInteger(i)){const e=r.get(i);if(Array.isArray(e))for(const t of e)t instanceof Ref&&this.addNode(this.rootDict.xref.fetch(t),s)}if(a)for(const[e,t]of a){const i=r.get(e);if(i){const e=this.addNode(this.rootDict.xref.fetchIfRef(i),s);1===e?.kids?.length&&e.kids[0].type===Gs&&(e.kids[0].type=t)}}}addNode(e,t,i=0){if(i>40){warn("StructTree MAX_DEPTH reached.");return null}if(!(e instanceof Dict))return null;if(t.has(e))return t.get(e);const a=new StructElementNode(this,e);t.set(e,a);const s=e.get("P");if(!s||isName(s.get("Type"),"StructTreeRoot")){this.addTopLevelNode(e,a)||t.delete(e);return a}const r=this.addNode(s,t,i+1);if(!r)return a;let n=!1;for(const t of r.kids)if(t.type===Us&&t.dict===e){t.parentNode=a;n=!0}n||t.delete(e);return a}addTopLevelNode(e,t){const i=this.rootDict.get("K");if(!i)return!1;if(i instanceof Dict){if(i.objId!==e.objId)return!1;this.nodes[0]=t;return!0}if(!Array.isArray(i))return!0;let a=!1;for(let s=0;s40){warn("StructTree too deep to be fully serialized.");return}const a=Object.create(null);a.role=e.role;a.children=[];t.children.push(a);let s=e.dict.get("Alt");"string"!=typeof s&&(s=e.dict.get("ActualText"));"string"==typeof s&&(a.alt=stringToPDFString(s));const r=e.dict.get("A");if(r instanceof Dict){const e=lookupNormalRect(r.getArray("BBox"),null);if(e)a.bbox=e;else{const e=r.get("Width"),t=r.get("Height");"number"==typeof e&&e>0&&"number"==typeof t&&t>0&&(a.bbox=[0,0,e,t])}}const n=e.dict.get("Lang");"string"==typeof n&&(a.lang=stringToPDFString(n));for(const t of e.kids){const e=t.type===Us?t.parentNode:null;e?nodeToSerializable(e,a,i+1):t.type===Rs||t.type===Ns?a.children.push({type:"content",id:`p${t.pageObjId}_mc${t.mcid}`}):t.type===Gs?a.children.push({type:"object",id:t.refObjId}):t.type===Ms&&a.children.push({type:"annotation",id:`pdfjs_internal_id_${t.refObjId}`})}}const e=Object.create(null);e.children=[];e.role="Root";for(const t of this.nodes)t&&nodeToSerializable(t,e);return e}}function isValidExplicitDest(e){if(!Array.isArray(e)||e.length<2)return!1;const[t,i,...a]=e;if(!(t instanceof Ref||Number.isInteger(t)))return!1;if(!(i instanceof Name))return!1;const s=a.length;let r=!0;switch(i.name){case"XYZ":if(s<2||s>3)return!1;break;case"Fit":case"FitB":return 0===s;case"FitH":case"FitBH":case"FitV":case"FitBV":if(s>1)return!1;break;case"FitR":if(4!==s)return!1;r=!1;break;default:return!1}for(const e of a)if(!("number"==typeof e||r&&null===e))return!1;return!0}function fetchDest(e){e instanceof Dict&&(e=e.get("D"));return isValidExplicitDest(e)?e:null}function fetchRemoteDest(e){let t=e.get("D");if(t){t instanceof Name&&(t=t.name);if("string"==typeof t)return stringToPDFString(t);if(isValidExplicitDest(t))return JSON.stringify(t)}return null}class Catalog{constructor(e,t){this.pdfManager=e;this.xref=t;this._catDict=t.getCatalogObj();if(!(this._catDict instanceof Dict))throw new FormatError("Catalog object is not a dictionary.");this.toplevelPagesDict;this._actualNumPages=null;this.fontCache=new RefSetCache;this.builtInCMapCache=new Map;this.standardFontDataCache=new Map;this.globalImageCache=new GlobalImageCache;this.pageKidsCountCache=new RefSetCache;this.pageIndexCache=new RefSetCache;this.pageDictCache=new RefSetCache;this.nonBlendModesSet=new RefSet;this.systemFontCache=new Map}cloneDict(){return this._catDict.clone()}get version(){const e=this._catDict.get("Version");if(e instanceof Name){if(ft.test(e.name))return shadow(this,"version",e.name);warn(`Invalid PDF catalog version: ${e.name}`)}return shadow(this,"version",null)}get lang(){const e=this._catDict.get("Lang");return shadow(this,"lang",e&&"string"==typeof e?stringToPDFString(e):null)}get needsRendering(){const e=this._catDict.get("NeedsRendering");return shadow(this,"needsRendering","boolean"==typeof e&&e)}get collection(){let e=null;try{const t=this._catDict.get("Collection");t instanceof Dict&&t.size>0&&(e=t)}catch(e){if(e instanceof MissingDataException)throw e;info("Cannot fetch Collection entry; assuming no collection is present.")}return shadow(this,"collection",e)}get acroForm(){let e=null;try{const t=this._catDict.get("AcroForm");t instanceof Dict&&t.size>0&&(e=t)}catch(e){if(e instanceof MissingDataException)throw e;info("Cannot fetch AcroForm entry; assuming no forms are present.")}return shadow(this,"acroForm",e)}get acroFormRef(){const e=this._catDict.getRaw("AcroForm");return shadow(this,"acroFormRef",e instanceof Ref?e:null)}get metadata(){const e=this._catDict.getRaw("Metadata");if(!(e instanceof Ref))return shadow(this,"metadata",null);let t=null;try{const i=this.xref.fetch(e,!this.xref.encrypt?.encryptMetadata);if(i instanceof BaseStream&&i.dict instanceof Dict){const e=i.dict.get("Type"),a=i.dict.get("Subtype");if(isName(e,"Metadata")&&isName(a,"XML")){const e=stringToUTF8String(i.getString());e&&(t=new MetadataParser(e).serializable)}}}catch(e){if(e instanceof MissingDataException)throw e;info(`Skipping invalid Metadata: "${e}".`)}return shadow(this,"metadata",t)}get markInfo(){let e=null;try{e=this._readMarkInfo()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read mark info.")}return shadow(this,"markInfo",e)}_readMarkInfo(){const e=this._catDict.get("MarkInfo");if(!(e instanceof Dict))return null;const t={Marked:!1,UserProperties:!1,Suspects:!1};for(const i in t){const a=e.get(i);"boolean"==typeof a&&(t[i]=a)}return t}get structTreeRoot(){let e=null;try{e=this._readStructTreeRoot()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable read to structTreeRoot info.")}return shadow(this,"structTreeRoot",e)}_readStructTreeRoot(){const e=this._catDict.getRaw("StructTreeRoot"),t=this.xref.fetchIfRef(e);if(!(t instanceof Dict))return null;const i=new StructTreeRoot(t,e);i.init();return i}get toplevelPagesDict(){const e=this._catDict.get("Pages");if(!(e instanceof Dict))throw new FormatError("Invalid top-level pages dictionary.");return shadow(this,"toplevelPagesDict",e)}get documentOutline(){let e=null;try{e=this._readDocumentOutline()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read document outline.")}return shadow(this,"documentOutline",e)}_readDocumentOutline(){let e=this._catDict.get("Outlines");if(!(e instanceof Dict))return null;e=e.getRaw("First");if(!(e instanceof Ref))return null;const t={items:[]},i=[{obj:e,parent:t}],a=new RefSet;a.put(e);const s=this.xref,r=new Uint8ClampedArray(3);for(;i.length>0;){const t=i.shift(),n=s.fetchIfRef(t.obj);if(null===n)continue;n.has("Title")||warn("Invalid outline item encountered.");const g={url:null,dest:null,action:null};Catalog.parseDestDictionary({destDict:n,resultObj:g,docBaseUrl:this.baseUrl,docAttachments:this.attachments});const o=n.get("Title"),c=n.get("F")||0,C=n.getArray("C"),h=n.get("Count");let l=r;!isNumberArray(C,3)||0===C[0]&&0===C[1]&&0===C[2]||(l=ColorSpace.singletons.rgb.getRgb(C,0));const Q={action:g.action,attachment:g.attachment,dest:g.dest,url:g.url,unsafeUrl:g.unsafeUrl,newWindow:g.newWindow,setOCGState:g.setOCGState,title:"string"==typeof o?stringToPDFString(o):"",color:l,count:Number.isInteger(h)?h:void 0,bold:!!(2&c),italic:!!(1&c),items:[]};t.parent.items.push(Q);e=n.getRaw("First");if(e instanceof Ref&&!a.has(e)){i.push({obj:e,parent:Q});a.put(e)}e=n.getRaw("Next");if(e instanceof Ref&&!a.has(e)){i.push({obj:e,parent:t.parent});a.put(e)}}return t.items.length>0?t.items:null}get permissions(){let e=null;try{e=this._readPermissions()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read permissions.")}return shadow(this,"permissions",e)}_readPermissions(){const e=this.xref.trailer.get("Encrypt");if(!(e instanceof Dict))return null;let t=e.get("P");if("number"!=typeof t)return null;t+=2**32;const i=[];for(const e in y){const a=y[e];t&a&&i.push(a)}return i}get optionalContentConfig(){let e=null;try{const t=this._catDict.get("OCProperties");if(!t)return shadow(this,"optionalContentConfig",null);const i=t.get("D");if(!i)return shadow(this,"optionalContentConfig",null);const a=t.get("OCGs");if(!Array.isArray(a))return shadow(this,"optionalContentConfig",null);const s=new RefSetCache;for(const e of a)e instanceof Ref&&!s.has(e)&&s.put(e,this.#v(e));e=this.#K(i,s)}catch(e){if(e instanceof MissingDataException)throw e;warn(`Unable to read optional content config: ${e}`)}return shadow(this,"optionalContentConfig",e)}#v(e){const t=this.xref.fetch(e),i={id:e.toString(),name:null,intent:null,usage:{print:null,view:null},rbGroups:[]},a=t.get("Name");"string"==typeof a&&(i.name=stringToPDFString(a));let s=t.getArray("Intent");Array.isArray(s)||(s=[s]);s.every((e=>e instanceof Name))&&(i.intent=s.map((e=>e.name)));const r=t.get("Usage");if(!(r instanceof Dict))return i;const n=i.usage,g=r.get("Print");if(g instanceof Dict){const e=g.get("PrintState");if(e instanceof Name)switch(e.name){case"ON":case"OFF":n.print={printState:e.name}}}const o=r.get("View");if(o instanceof Dict){const e=o.get("ViewState");if(e instanceof Name)switch(e.name){case"ON":case"OFF":n.view={viewState:e.name}}}return i}#K(e,t){function parseOnOff(e){const i=[];if(Array.isArray(e))for(const a of e)a instanceof Ref&&t.has(a)&&i.push(a.toString());return i}function parseOrder(e,i=0){if(!Array.isArray(e))return null;const s=[];for(const r of e){if(r instanceof Ref&&t.has(r)){a.put(r);s.push(r.toString());continue}const e=parseNestedOrder(r,i);e&&s.push(e)}if(i>0)return s;const r=[];for(const[e]of t.items())a.has(e)||r.push(e.toString());r.length&&s.push({name:null,order:r});return s}function parseNestedOrder(e,t){if(++t>s){warn("parseNestedOrder - reached MAX_NESTED_LEVELS.");return null}const a=i.fetchIfRef(e);if(!Array.isArray(a))return null;const r=i.fetchIfRef(a[0]);if("string"!=typeof r)return null;const n=parseOrder(a.slice(1),t);return n?.length?{name:stringToPDFString(r),order:n}:null}const i=this.xref,a=new RefSet,s=10;!function parseRBGroups(e){if(Array.isArray(e))for(const a of e){const e=i.fetchIfRef(a);if(!Array.isArray(e)||!e.length)continue;const s=new Set;for(const i of e)if(i instanceof Ref&&t.has(i)&&!s.has(i.toString())){s.add(i.toString());t.get(i).rbGroups.push(s)}}}(e.get("RBGroups"));return{name:"string"==typeof e.get("Name")?stringToPDFString(e.get("Name")):null,creator:"string"==typeof e.get("Creator")?stringToPDFString(e.get("Creator")):null,baseState:e.get("BaseState")instanceof Name?e.get("BaseState").name:null,on:parseOnOff(e.get("ON")),off:parseOnOff(e.get("OFF")),order:parseOrder(e.get("Order")),groups:[...t]}}setActualNumPages(e=null){this._actualNumPages=e}get hasActualNumPages(){return null!==this._actualNumPages}get _pagesCount(){const e=this.toplevelPagesDict.get("Count");if(!Number.isInteger(e))throw new FormatError("Page count in top-level pages dictionary is not an integer.");return shadow(this,"_pagesCount",e)}get numPages(){return this.hasActualNumPages?this._actualNumPages:this._pagesCount}get destinations(){const e=this._readDests(),t=Object.create(null);if(e instanceof NameTree)for(const[i,a]of e.getAll()){const e=fetchDest(a);e&&(t[stringToPDFString(i)]=e)}else if(e instanceof Dict)for(const[i,a]of e){const e=fetchDest(a);e&&(t[i]=e)}return shadow(this,"destinations",t)}getDestination(e){const t=this._readDests();if(t instanceof NameTree){const i=fetchDest(t.get(e));if(i)return i;const a=this.destinations[e];if(a){warn(`Found "${e}" at an incorrect position in the NameTree.`);return a}}else if(t instanceof Dict){const i=fetchDest(t.get(e));if(i)return i}return null}_readDests(){const e=this._catDict.get("Names");return e?.has("Dests")?new NameTree(e.getRaw("Dests"),this.xref):this._catDict.has("Dests")?this._catDict.get("Dests"):void 0}get pageLabels(){let e=null;try{e=this._readPageLabels()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read page labels.")}return shadow(this,"pageLabels",e)}_readPageLabels(){const e=this._catDict.getRaw("PageLabels");if(!e)return null;const t=new Array(this.numPages);let i=null,a="";const s=new NumberTree(e,this.xref).getAll();let r="",n=1;for(let e=0,g=this.numPages;e=1))throw new FormatError("Invalid start in PageLabel dictionary.");n=e}else n=1}switch(i){case"D":r=n;break;case"R":case"r":r=toRomanNumerals(n,"r"===i);break;case"A":case"a":const e=26,t="a"===i?97:65,a=n-1;r=String.fromCharCode(t+a%e).repeat(Math.floor(a/e)+1);break;default:if(i)throw new FormatError(`Invalid style "${i}" in PageLabel dictionary.`);r=""}t[e]=a+r;n++}return t}get pageLayout(){const e=this._catDict.get("PageLayout");let t="";if(e instanceof Name)switch(e.name){case"SinglePage":case"OneColumn":case"TwoColumnLeft":case"TwoColumnRight":case"TwoPageLeft":case"TwoPageRight":t=e.name}return shadow(this,"pageLayout",t)}get pageMode(){const e=this._catDict.get("PageMode");let t="UseNone";if(e instanceof Name)switch(e.name){case"UseNone":case"UseOutlines":case"UseThumbs":case"FullScreen":case"UseOC":case"UseAttachments":t=e.name}return shadow(this,"pageMode",t)}get viewerPreferences(){const e=this._catDict.get("ViewerPreferences");if(!(e instanceof Dict))return shadow(this,"viewerPreferences",null);let t=null;for(const i of e.getKeys()){const a=e.get(i);let s;switch(i){case"HideToolbar":case"HideMenubar":case"HideWindowUI":case"FitWindow":case"CenterWindow":case"DisplayDocTitle":case"PickTrayByPDFSize":"boolean"==typeof a&&(s=a);break;case"NonFullScreenPageMode":if(a instanceof Name)switch(a.name){case"UseNone":case"UseOutlines":case"UseThumbs":case"UseOC":s=a.name;break;default:s="UseNone"}break;case"Direction":if(a instanceof Name)switch(a.name){case"L2R":case"R2L":s=a.name;break;default:s="L2R"}break;case"ViewArea":case"ViewClip":case"PrintArea":case"PrintClip":if(a instanceof Name)switch(a.name){case"MediaBox":case"CropBox":case"BleedBox":case"TrimBox":case"ArtBox":s=a.name;break;default:s="CropBox"}break;case"PrintScaling":if(a instanceof Name)switch(a.name){case"None":case"AppDefault":s=a.name;break;default:s="AppDefault"}break;case"Duplex":if(a instanceof Name)switch(a.name){case"Simplex":case"DuplexFlipShortEdge":case"DuplexFlipLongEdge":s=a.name;break;default:s="None"}break;case"PrintPageRange":if(Array.isArray(a)&&a.length%2==0){a.every(((e,t,i)=>Number.isInteger(e)&&e>0&&(0===t||e>=i[t-1])&&e<=this.numPages))&&(s=a)}break;case"NumCopies":Number.isInteger(a)&&a>0&&(s=a);break;default:warn(`Ignoring non-standard key in ViewerPreferences: ${i}.`);continue}if(void 0!==s){t||(t=Object.create(null));t[i]=s}else warn(`Bad value, for key "${i}", in ViewerPreferences: ${a}.`)}return shadow(this,"viewerPreferences",t)}get openAction(){const e=this._catDict.get("OpenAction"),t=Object.create(null);if(e instanceof Dict){const i=new Dict(this.xref);i.set("A",e);const a={url:null,dest:null,action:null};Catalog.parseDestDictionary({destDict:i,resultObj:a});Array.isArray(a.dest)?t.dest=a.dest:a.action&&(t.action=a.action)}else Array.isArray(e)&&(t.dest=e);return shadow(this,"openAction",objectSize(t)>0?t:null)}get attachments(){const e=this._catDict.get("Names");let t=null;if(e instanceof Dict&&e.has("EmbeddedFiles")){const i=new NameTree(e.getRaw("EmbeddedFiles"),this.xref);for(const[e,a]of i.getAll()){const i=new FileSpec(a,this.xref);t||(t=Object.create(null));t[stringToPDFString(e)]=i.serializable}}return shadow(this,"attachments",t)}get xfaImages(){const e=this._catDict.get("Names");let t=null;if(e instanceof Dict&&e.has("XFAImages")){const i=new NameTree(e.getRaw("XFAImages"),this.xref);for(const[e,a]of i.getAll()){t||(t=new Dict(this.xref));t.set(stringToPDFString(e),a)}}return shadow(this,"xfaImages",t)}_collectJavaScript(){const e=this._catDict.get("Names");let t=null;function appendIfJavaScriptDict(e,i){if(!(i instanceof Dict))return;if(!isName(i.get("S"),"JavaScript"))return;let a=i.get("JS");if(a instanceof BaseStream)a=a.getString();else if("string"!=typeof a)return;a=stringToPDFString(a).replaceAll("\0","");a&&(t||=new Map).set(e,a)}if(e instanceof Dict&&e.has("JavaScript")){const t=new NameTree(e.getRaw("JavaScript"),this.xref);for(const[e,i]of t.getAll())appendIfJavaScriptDict(stringToPDFString(e),i)}const i=this._catDict.get("OpenAction");i&&appendIfJavaScriptDict("OpenAction",i);return t}get jsActions(){const e=this._collectJavaScript();let t=collectActions(this.xref,this._catDict,fA);if(e){t||=Object.create(null);for(const[i,a]of e)i in t?t[i].push(a):t[i]=[a]}return shadow(this,"jsActions",t)}async fontFallback(e,t){const i=await Promise.all(this.fontCache);for(const a of i)if(a.loadedName===e){a.fallback(t);return}}async cleanup(e=!1){clearGlobalCaches();this.globalImageCache.clear(e);this.pageKidsCountCache.clear();this.pageIndexCache.clear();this.pageDictCache.clear();this.nonBlendModesSet.clear();const t=await Promise.all(this.fontCache);for(const{dict:e}of t)delete e.cacheKey;this.fontCache.clear();this.builtInCMapCache.clear();this.standardFontDataCache.clear();this.systemFontCache.clear()}async getPageDict(e){const t=[this.toplevelPagesDict],i=new RefSet,a=this._catDict.getRaw("Pages");a instanceof Ref&&i.put(a);const s=this.xref,r=this.pageKidsCountCache,n=this.pageIndexCache,g=this.pageDictCache;let o=0;for(;t.length;){const a=t.pop();if(a instanceof Ref){const c=r.get(a);if(c>=0&&o+c<=e){o+=c;continue}if(i.has(a))throw new FormatError("Pages tree contains circular reference.");i.put(a);const C=await(g.get(a)||s.fetchAsync(a));if(C instanceof Dict){let t=C.getRaw("Type");t instanceof Ref&&(t=await s.fetchAsync(t));if(isName(t,"Page")||!C.has("Kids")){r.has(a)||r.put(a,1);n.has(a)||n.put(a,o);if(o===e)return[C,a];o++;continue}}t.push(C);continue}if(!(a instanceof Dict))throw new FormatError("Page dictionary kid reference points to wrong type of object.");const{objId:c}=a;let C=a.getRaw("Count");C instanceof Ref&&(C=await s.fetchAsync(C));if(Number.isInteger(C)&&C>=0){c&&!r.has(c)&&r.put(c,C);if(o+C<=e){o+=C;continue}}let h=a.getRaw("Kids");h instanceof Ref&&(h=await s.fetchAsync(h));if(!Array.isArray(h)){let t=a.getRaw("Type");t instanceof Ref&&(t=await s.fetchAsync(t));if(isName(t,"Page")||!a.has("Kids")){if(o===e)return[a,null];o++;continue}throw new FormatError("Page dictionary kids object is not an array.")}for(let e=h.length-1;e>=0;e--){const i=h[e];t.push(i);a===this.toplevelPagesDict&&i instanceof Ref&&!g.has(i)&&g.put(i,s.fetchAsync(i))}}throw new Error(`Page index ${e} not found.`)}async getAllPageDicts(e=!1){const{ignoreErrors:t}=this.pdfManager.evaluatorOptions,i=[{currentNode:this.toplevelPagesDict,posInKids:0}],a=new RefSet,s=this._catDict.getRaw("Pages");s instanceof Ref&&a.put(s);const r=new Map,n=this.xref,g=this.pageIndexCache;let o=0;function addPageDict(e,t){t&&!g.has(t)&&g.put(t,o);r.set(o++,[e,t])}function addPageError(i){if(i instanceof XRefEntryException&&!e)throw i;if(e&&t&&0===o){warn(`getAllPageDicts - Skipping invalid first page: "${i}".`);i=Dict.empty}r.set(o++,[i,null])}for(;i.length>0;){const e=i.at(-1),{currentNode:t,posInKids:s}=e;let r=t.getRaw("Kids");if(r instanceof Ref)try{r=await n.fetchAsync(r)}catch(e){addPageError(e);break}if(!Array.isArray(r)){addPageError(new FormatError("Page dictionary kids object is not an array."));break}if(s>=r.length){i.pop();continue}const g=r[s];let o;if(g instanceof Ref){if(a.has(g)){addPageError(new FormatError("Pages tree contains circular reference."));break}a.put(g);try{o=await n.fetchAsync(g)}catch(e){addPageError(e);break}}else o=g;if(!(o instanceof Dict)){addPageError(new FormatError("Page dictionary kid reference points to wrong type of object."));break}let c=o.getRaw("Type");if(c instanceof Ref)try{c=await n.fetchAsync(c)}catch(e){addPageError(e);break}isName(c,"Page")||!o.has("Kids")?addPageDict(o,g instanceof Ref?g:null):i.push({currentNode:o,posInKids:0});e.posInKids++}return r}getPageIndex(e){const t=this.pageIndexCache.get(e);if(void 0!==t)return Promise.resolve(t);const i=this.xref;let a=0;const next=t=>function pagesBeforeRef(t){let a,s=0;return i.fetchAsync(t).then((function(i){if(isRefsEqual(t,e)&&!isDict(i,"Page")&&!(i instanceof Dict&&!i.has("Type")&&i.has("Contents")))throw new FormatError("The reference does not point to a /Page dictionary.");if(!i)return null;if(!(i instanceof Dict))throw new FormatError("Node must be a dictionary.");a=i.getRaw("Parent");return i.getAsync("Parent")})).then((function(e){if(!e)return null;if(!(e instanceof Dict))throw new FormatError("Parent must be a dictionary.");return e.getAsync("Kids")})).then((function(e){if(!e)return null;const r=[];let n=!1;for(const a of e){if(!(a instanceof Ref))throw new FormatError("Kid must be a reference.");if(isRefsEqual(a,t)){n=!0;break}r.push(i.fetchAsync(a).then((function(e){if(!(e instanceof Dict))throw new FormatError("Kid node must be a dictionary.");e.has("Count")?s+=e.get("Count"):s++})))}if(!n)throw new FormatError("Kid reference not found in parent's kids.");return Promise.all(r).then((function(){return[s,a]}))}))}(t).then((t=>{if(!t){this.pageIndexCache.put(e,a);return a}const[i,s]=t;a+=i;return next(s)}));return next(e)}get baseUrl(){const e=this._catDict.get("URI");if(e instanceof Dict){const t=e.get("Base");if("string"==typeof t){const e=createValidAbsoluteUrl(t,null,{tryConvertEncoding:!0});if(e)return shadow(this,"baseUrl",e.href)}}return shadow(this,"baseUrl",this.pdfManager.docBaseUrl)}static parseDestDictionary({destDict:e,resultObj:t,docBaseUrl:i=null,docAttachments:a=null}){if(!(e instanceof Dict)){warn("parseDestDictionary: `destDict` must be a dictionary.");return}let s,r,n=e.get("A");if(!(n instanceof Dict))if(e.has("Dest"))n=e.get("Dest");else{n=e.get("AA");n instanceof Dict&&(n.has("D")?n=n.get("D"):n.has("U")&&(n=n.get("U")))}if(n instanceof Dict){const e=n.get("S");if(!(e instanceof Name)){warn("parseDestDictionary: Invalid type in Action dictionary.");return}const i=e.name;switch(i){case"ResetForm":const e=n.get("Flags"),g=!(1&("number"==typeof e?e:0)),o=[],c=[];for(const e of n.get("Fields")||[])e instanceof Ref?c.push(e.toString()):"string"==typeof e&&o.push(stringToPDFString(e));t.resetForm={fields:o,refs:c,include:g};break;case"URI":s=n.get("URI");s instanceof Name&&(s="/"+s.name);break;case"GoTo":r=n.get("D");break;case"Launch":case"GoToR":const C=n.get("F");if(C instanceof Dict){const e=new FileSpec(C,null,!0),{rawFilename:t}=e.serializable;s=t}else"string"==typeof C&&(s=C);const h=fetchRemoteDest(n);h&&"string"==typeof s&&(s=s.split("#",1)[0]+"#"+h);const l=n.get("NewWindow");"boolean"==typeof l&&(t.newWindow=l);break;case"GoToE":const Q=n.get("T");let E;if(a&&Q instanceof Dict){const e=Q.get("R"),t=Q.get("N");isName(e,"C")&&"string"==typeof t&&(E=a[stringToPDFString(t)])}if(E){t.attachment=E;const e=fetchRemoteDest(n);e&&(t.attachmentDest=e)}else warn('parseDestDictionary - unimplemented "GoToE" action.');break;case"Named":const u=n.get("N");u instanceof Name&&(t.action=u.name);break;case"SetOCGState":const d=n.get("State"),f=n.get("PreserveRB");if(!Array.isArray(d)||0===d.length)break;const p=[];for(const e of d)if(e instanceof Name)switch(e.name){case"ON":case"OFF":case"Toggle":p.push(e.name)}else e instanceof Ref&&p.push(e.toString());if(p.length!==d.length)break;t.setOCGState={state:p,preserveRB:"boolean"!=typeof f||f};break;case"JavaScript":const m=n.get("JS");let y;m instanceof BaseStream?y=m.getString():"string"==typeof m&&(y=m);const w=y&&recoverJsURL(stringToPDFString(y));if(w){s=w.url;t.newWindow=w.newWindow;break}default:if("JavaScript"===i||"SubmitForm"===i)break;warn(`parseDestDictionary - unsupported action: "${i}".`)}}else e.has("Dest")&&(r=e.get("Dest"));if("string"==typeof s){const e=createValidAbsoluteUrl(s,i,{addDefaultProtocol:!0,tryConvertEncoding:!0});e&&(t.url=e.href);t.unsafeUrl=s}if(r){r instanceof Name&&(r=r.name);"string"==typeof r?t.dest=stringToPDFString(r):isValidExplicitDest(r)&&(t.dest=r)}}}function addChildren(e,t){if(e instanceof Dict)e=e.getRawValues();else if(e instanceof BaseStream)e=e.dict.getRawValues();else if(!Array.isArray(e))return;for(const a of e)((i=a)instanceof Ref||i instanceof Dict||i instanceof BaseStream||Array.isArray(i))&&t.push(a);var i}class ObjectLoader{constructor(e,t,i){this.dict=e;this.keys=t;this.xref=i;this.refSet=null}async load(){if(this.xref.stream.isDataLoaded)return;const{keys:e,dict:t}=this;this.refSet=new RefSet;const i=[];for(const a of e){const e=t.getRaw(a);void 0!==e&&i.push(e)}return this._walk(i)}async _walk(e){const t=[],i=[];for(;e.length;){let a=e.pop();if(a instanceof Ref){if(this.refSet.has(a))continue;try{this.refSet.put(a);a=this.xref.fetch(a)}catch(e){if(!(e instanceof MissingDataException)){warn(`ObjectLoader._walk - requesting all data: "${e}".`);this.refSet=null;const{manager:t}=this.xref.stream;return t.requestAllChunks()}t.push(a);i.push({begin:e.begin,end:e.end})}}if(a instanceof BaseStream){const e=a.getBaseStreams();if(e){let s=!1;for(const t of e)if(!t.isDataLoaded){s=!0;i.push({begin:t.start,end:t.end})}s&&t.push(a)}}addChildren(a,e)}if(i.length){await this.xref.stream.manager.requestRanges(i);for(const e of t)e instanceof Ref&&this.refSet.remove(e);return this._walk(t)}this.refSet=null}}const xs=Symbol(),Ls=Symbol(),Hs=Symbol(),Js=Symbol(),Ys=Symbol(),vs=Symbol(),Ks=Symbol(),Ts=Symbol(),qs=Symbol(),Os=Symbol("content"),Ws=Symbol("data"),js=Symbol(),Xs=Symbol("extra"),Zs=Symbol(),Vs=Symbol(),zs=Symbol(),_s=Symbol(),$s=Symbol(),Ar=Symbol(),er=Symbol(),tr=Symbol(),ir=Symbol(),ar=Symbol(),sr=Symbol(),rr=Symbol(),nr=Symbol(),gr=Symbol(),or=Symbol(),Ir=Symbol(),cr=Symbol(),Cr=Symbol(),hr=Symbol(),lr=Symbol(),Qr=Symbol(),Er=Symbol(),ur=Symbol(),dr=Symbol(),fr=Symbol(),pr=Symbol(),mr=Symbol(),yr=Symbol(),wr=Symbol(),Dr=Symbol(),br=Symbol(),Fr=Symbol(),Sr=Symbol("namespaceId"),kr=Symbol("nodeName"),Rr=Symbol(),Nr=Symbol(),Gr=Symbol(),Mr=Symbol(),Ur=Symbol(),xr=Symbol(),Lr=Symbol(),Hr=Symbol(),Jr=Symbol("root"),Yr=Symbol(),vr=Symbol(),Kr=Symbol(),Tr=Symbol(),qr=Symbol(),Or=Symbol(),Pr=Symbol(),Wr=Symbol(),jr=Symbol(),Xr=Symbol(),Zr=Symbol(),Vr=Symbol("uid"),zr=Symbol(),_r={config:{id:0,check:e=>e.startsWith("http://www.xfa.org/schema/xci/")},connectionSet:{id:1,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-connection-set/")},datasets:{id:2,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-data/")},form:{id:3,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-form/")},localeSet:{id:4,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-locale-set/")},pdf:{id:5,check:e=>"http://ns.adobe.com/xdp/pdf/"===e},signature:{id:6,check:e=>"http://www.w3.org/2000/09/xmldsig#"===e},sourceSet:{id:7,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-source-set/")},stylesheet:{id:8,check:e=>"http://www.w3.org/1999/XSL/Transform"===e},template:{id:9,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-template/")},xdc:{id:10,check:e=>e.startsWith("http://www.xfa.org/schema/xdc/")},xdp:{id:11,check:e=>"http://ns.adobe.com/xdp/"===e},xfdf:{id:12,check:e=>"http://ns.adobe.com/xfdf/"===e},xhtml:{id:13,check:e=>"http://www.w3.org/1999/xhtml"===e},xmpmeta:{id:14,check:e=>"http://ns.adobe.com/xmpmeta/"===e}},$r={pt:e=>e,cm:e=>e/2.54*72,mm:e=>e/25.4*72,in:e=>72*e,px:e=>e},An=/([+-]?\d+\.?\d*)(.*)/;function stripQuotes(e){return e.startsWith("'")||e.startsWith('"')?e.slice(1,-1):e}function getInteger({data:e,defaultValue:t,validate:i}){if(!e)return t;e=e.trim();const a=parseInt(e,10);return!isNaN(a)&&i(a)?a:t}function getFloat({data:e,defaultValue:t,validate:i}){if(!e)return t;e=e.trim();const a=parseFloat(e);return!isNaN(a)&&i(a)?a:t}function getKeyword({data:e,defaultValue:t,validate:i}){return e&&i(e=e.trim())?e:t}function getStringOption(e,t){return getKeyword({data:e,defaultValue:t[0],validate:e=>t.includes(e)})}function getMeasurement(e,t="0"){t||="0";if(!e)return getMeasurement(t);const i=e.trim().match(An);if(!i)return getMeasurement(t);const[,a,s]=i,r=parseFloat(a);if(isNaN(r))return getMeasurement(t);if(0===r)return 0;const n=$r[s];return n?n(r):r}function getRatio(e){if(!e)return{num:1,den:1};const t=e.trim().split(/\s*:\s*/).map((e=>parseFloat(e))).filter((e=>!isNaN(e)));1===t.length&&t.push(1);if(0===t.length)return{num:1,den:1};const[i,a]=t;return{num:i,den:a}}function getRelevant(e){return e?e.trim().split(/\s+/).map((e=>({excluded:"-"===e[0],viewname:e.substring(1)}))):[]}class HTMLResult{static get FAILURE(){return shadow(this,"FAILURE",new HTMLResult(!1,null,null,null))}static get EMPTY(){return shadow(this,"EMPTY",new HTMLResult(!0,null,null,null))}constructor(e,t,i,a){this.success=e;this.html=t;this.bbox=i;this.breakNode=a}isBreak(){return!!this.breakNode}static breakNode(e){return new HTMLResult(!1,null,null,e)}static success(e,t=null){return new HTMLResult(!0,e,t,null)}}class FontFinder{constructor(e){this.fonts=new Map;this.cache=new Map;this.warned=new Set;this.defaultFont=null;this.add(e)}add(e,t=null){for(const t of e)this.addPdfFont(t);for(const e of this.fonts.values())e.regular||(e.regular=e.italic||e.bold||e.bolditalic);if(!t||0===t.size)return;const i=this.fonts.get("PdfJS-Fallback-PdfJS-XFA");for(const e of t)this.fonts.set(e,i)}addPdfFont(e){const t=e.cssFontInfo,i=t.fontFamily;let a=this.fonts.get(i);if(!a){a=Object.create(null);this.fonts.set(i,a);this.defaultFont||(this.defaultFont=a)}let s="";const r=parseFloat(t.fontWeight);0!==parseFloat(t.italicAngle)?s=r>=700?"bolditalic":"italic":r>=700&&(s="bold");if(!s){(e.name.includes("Bold")||e.psName?.includes("Bold"))&&(s="bold");(e.name.includes("Italic")||e.name.endsWith("It")||e.psName?.includes("Italic")||e.psName?.endsWith("It"))&&(s+="italic")}s||(s="regular");a[s]=e}getDefault(){return this.defaultFont}find(e,t=!0){let i=this.fonts.get(e)||this.cache.get(e);if(i)return i;const a=/,|-|_| |bolditalic|bold|italic|regular|it/gi;let s=e.replaceAll(a,"");i=this.fonts.get(s);if(i){this.cache.set(e,i);return i}s=s.toLowerCase();const r=[];for(const[e,t]of this.fonts.entries())e.replaceAll(a,"").toLowerCase().startsWith(s)&&r.push(t);if(0===r.length)for(const[,e]of this.fonts.entries())e.regular.name?.replaceAll(a,"").toLowerCase().startsWith(s)&&r.push(e);if(0===r.length){s=s.replaceAll(/psmt|mt/gi,"");for(const[e,t]of this.fonts.entries())e.replaceAll(a,"").toLowerCase().startsWith(s)&&r.push(t)}if(0===r.length)for(const e of this.fonts.values())e.regular.name?.replaceAll(a,"").toLowerCase().startsWith(s)&&r.push(e);if(r.length>=1){1!==r.length&&t&&warn(`XFA - Too many choices to guess the correct font: ${e}`);this.cache.set(e,r[0]);return r[0]}if(t&&!this.warned.has(e)){this.warned.add(e);warn(`XFA - Cannot find the font: ${e}`)}return null}}function selectFont(e,t){return"italic"===e.posture?"bold"===e.weight?t.bolditalic:t.italic:"bold"===e.weight?t.bold:t.regular}class FontInfo{constructor(e,t,i,a){this.lineHeight=i;this.paraMargin=t||{top:0,bottom:0,left:0,right:0};if(!e){[this.pdfFont,this.xfaFont]=this.defaultFont(a);return}this.xfaFont={typeface:e.typeface,posture:e.posture,weight:e.weight,size:e.size,letterSpacing:e.letterSpacing};const s=a.find(e.typeface);if(s){this.pdfFont=selectFont(e,s);this.pdfFont||([this.pdfFont,this.xfaFont]=this.defaultFont(a))}else[this.pdfFont,this.xfaFont]=this.defaultFont(a)}defaultFont(e){const t=e.find("Helvetica",!1)||e.find("Myriad Pro",!1)||e.find("Arial",!1)||e.getDefault();if(t?.regular){const e=t.regular;return[e,{typeface:e.cssFontInfo.fontFamily,posture:"normal",weight:"normal",size:10,letterSpacing:0}]}return[null,{typeface:"Courier",posture:"normal",weight:"normal",size:10,letterSpacing:0}]}}class FontSelector{constructor(e,t,i,a){this.fontFinder=a;this.stack=[new FontInfo(e,t,i,a)]}pushData(e,t,i){const a=this.stack.at(-1);for(const t of["typeface","posture","weight","size","letterSpacing"])e[t]||(e[t]=a.xfaFont[t]);for(const e of["top","bottom","left","right"])isNaN(t[e])&&(t[e]=a.paraMargin[e]);const s=new FontInfo(e,t,i||a.lineHeight,this.fontFinder);s.pdfFont||(s.pdfFont=a.pdfFont);this.stack.push(s)}popFont(){this.stack.pop()}topFont(){return this.stack.at(-1)}}class TextMeasure{constructor(e,t,i,a){this.glyphs=[];this.fontSelector=new FontSelector(e,t,i,a);this.extraHeight=0}pushData(e,t,i){this.fontSelector.pushData(e,t,i)}popFont(e){return this.fontSelector.popFont()}addPara(){const e=this.fontSelector.topFont();this.extraHeight+=e.paraMargin.top+e.paraMargin.bottom}addString(e){if(!e)return;const t=this.fontSelector.topFont(),i=t.xfaFont.size;if(t.pdfFont){const a=t.xfaFont.letterSpacing,s=t.pdfFont,r=s.lineHeight||1.2,n=t.lineHeight||Math.max(1.2,r)*i,g=r-(void 0===s.lineGap?.2:s.lineGap),o=Math.max(1,g)*i,c=i/1e3,C=s.defaultWidth||s.charsToGlyphs(" ")[0].width;for(const t of e.split(/[\u2029\n]/)){const e=s.encodeString(t).join(""),i=s.charsToGlyphs(e);for(const e of i){const t=e.width||C;this.glyphs.push([t*c+a,n,o,e.unicode,!1])}this.glyphs.push([0,0,0,"\n",!0])}this.glyphs.pop()}else{for(const t of e.split(/[\u2029\n]/)){for(const e of t.split(""))this.glyphs.push([i,1.2*i,i,e,!1]);this.glyphs.push([0,0,0,"\n",!0])}this.glyphs.pop()}}compute(e){let t=-1,i=0,a=0,s=0,r=0,n=0,g=!1,o=!0;for(let c=0,C=this.glyphs.length;ce){a=Math.max(a,r);r=0;s+=n;n=d;t=-1;i=0;g=!0;o=!1}else{n=Math.max(d,n);i=r;r+=C;t=c}else if(r+C>e){s+=n;n=d;if(-1!==t){c=t;a=Math.max(a,i);r=0;t=-1;i=0}else{a=Math.max(a,r);r=C}g=!0;o=!1}else{r+=C;n=Math.max(d,n)}}a=Math.max(a,r);s+=n+this.extraHeight;return{width:1.02*a,height:s,isBroken:g}}}const en=/^[^.[]+/,tn=/^[^\]]+/,an=0,sn=1,rn=2,nn=3,gn=4,on=new Map([["$data",(e,t)=>e.datasets?e.datasets.data:e],["$record",(e,t)=>(e.datasets?e.datasets.data:e)[rr]()[0]],["$template",(e,t)=>e.template],["$connectionSet",(e,t)=>e.connectionSet],["$form",(e,t)=>e.form],["$layout",(e,t)=>e.layout],["$host",(e,t)=>e.host],["$dataWindow",(e,t)=>e.dataWindow],["$event",(e,t)=>e.event],["!",(e,t)=>e.datasets],["$xfa",(e,t)=>e],["xfa",(e,t)=>e],["$",(e,t)=>t]]),In=new WeakMap;function parseExpression(e,t,i=!0){let a=e.match(en);if(!a)return null;let[s]=a;const r=[{name:s,cacheName:"."+s,index:0,js:null,formCalc:null,operator:an}];let n=s.length;for(;n0&&C.push(e)}if(0!==C.length||g||0!==o)e=isFinite(c)?C.filter((e=>ce[c])):C.flat();else{const i=t[Ir]();if(!(t=i))return null;o=-1;e=[t]}}return 0===e.length?null:e}function createDataNode(e,t,i){const a=parseExpression(i);if(!a)return null;if(a.some((e=>e.operator===sn)))return null;const s=on.get(a[0].name);let r=0;if(s){e=s(e,t);r=1}else e=t||e;for(let t=a.length;re[Pr]())).join("")}get[hn](){const e=Object.getPrototypeOf(this);if(!e._attributes){const t=e._attributes=new Set;for(const e of Object.getOwnPropertyNames(this)){if(null===this[e]||this[e]instanceof XFAObject||this[e]instanceof XFAObjectArray)break;t.add(e)}}return shadow(this,hn,e._attributes)}[pr](e){let t=this;for(;t;){if(t===e)return!0;t=t[Ir]()}return!1}[Ir](){return this[wn]}[or](){return this[Ir]()}[rr](e=null){return e?this[e]:this[ln]}[js](){const e=Object.create(null);this[Os]&&(e.$content=this[Os]);for(const t of Object.getOwnPropertyNames(this)){const i=this[t];null!==i&&(i instanceof XFAObject?e[t]=i[js]():i instanceof XFAObjectArray?i.isEmpty()||(e[t]=i.dump()):e[t]=i)}return e}[Zr](){return null}[jr](){return HTMLResult.EMPTY}*[nr](){for(const e of this[rr]())yield e}*[un](e,t){for(const i of this[nr]())if(!e||t===e.has(i[kr])){const e=this[$s](),t=i[jr](e);t.success||(this[Xs].failingNode=i);yield t}}[Vs](){return null}[Ls](e,t){this[Xs].children.push(e)}[$s](){}[Js]({filter:e=null,include:t=!0}){if(this[Xs].generator){const e=this[$s](),t=this[Xs].failingNode[jr](e);if(!t.success)return t;t.html&&this[Ls](t.html,t.bbox);delete this[Xs].failingNode}else this[Xs].generator=this[un](e,t);for(;;){const e=this[Xs].generator.next();if(e.done)break;const t=e.value;if(!t.success)return t;t.html&&this[Ls](t.html,t.bbox)}this[Xs].generator=null;return HTMLResult.EMPTY}[Tr](e){this[bn]=new Set(Object.keys(e))}[fn](e){const t=this[hn],i=this[bn];return[...e].filter((e=>t.has(e)&&!i.has(e)))}[Yr](e,t=new Set){for(const i of this[ln])i[Dn](e,t)}[Dn](e,t){const i=this[dn](e,t);i?this[cn](i,e,t):this[Yr](e,t)}[dn](e,t){const{use:i,usehref:a}=this;if(!i&&!a)return null;let s=null,r=null,n=null,g=i;if(a){g=a;a.startsWith("#som(")&&a.endsWith(")")?r=a.slice(5,-1):a.startsWith(".#som(")&&a.endsWith(")")?r=a.slice(6,-1):a.startsWith("#")?n=a.slice(1):a.startsWith(".#")&&(n=a.slice(2))}else i.startsWith("#")?n=i.slice(1):r=i;this.use=this.usehref="";if(n)s=e.get(n);else{s=searchNode(e.get(Jr),this,r,!0,!1);s&&(s=s[0])}if(!s){warn(`XFA - Invalid prototype reference: ${g}.`);return null}if(s[kr]!==this[kr]){warn(`XFA - Incompatible prototype: ${s[kr]} !== ${this[kr]}.`);return null}if(t.has(s)){warn("XFA - Cycle detected in prototypes use.");return null}t.add(s);const o=s[dn](e,t);o&&s[cn](o,e,t);s[Yr](e,t);t.delete(s);return s}[cn](e,t,i){if(i.has(e)){warn("XFA - Cycle detected in prototypes use.");return}!this[Os]&&e[Os]&&(this[Os]=e[Os]);new Set(i).add(e);for(const t of this[fn](e[bn])){this[t]=e[t];this[bn]&&this[bn].add(t)}for(const a of Object.getOwnPropertyNames(this)){if(this[hn].has(a))continue;const s=this[a],r=e[a];if(s instanceof XFAObjectArray){for(const e of s[ln])e[Dn](t,i);for(let a=s[ln].length,n=r[ln].length;aXFAObject[Bn](e))):"object"==typeof e&&null!==e?Object.assign({},e):e}[Ts](){const e=Object.create(Object.getPrototypeOf(this));for(const t of Object.getOwnPropertySymbols(this))try{e[t]=this[t]}catch{shadow(e,t,this[t])}e[Vr]=`${e[kr]}${Sn++}`;e[ln]=[];for(const t of Object.getOwnPropertyNames(this)){if(this[hn].has(t)){e[t]=XFAObject[Bn](this[t]);continue}const i=this[t];e[t]=i instanceof XFAObjectArray?new XFAObjectArray(i[mn]):null}for(const t of this[ln]){const i=t[kr],a=t[Ts]();e[ln].push(a);a[wn]=e;null===e[i]?e[i]=a:e[i][ln].push(a)}return e}[rr](e=null){return e?this[ln].filter((t=>t[kr]===e)):this[ln]}[Ar](e){return this[e]}[er](e,t,i=!0){return Array.from(this[tr](e,t,i))}*[tr](e,t,i=!0){if("parent"!==e){for(const i of this[ln]){i[kr]===e&&(yield i);i.name===e&&(yield i);(t||i[Dr]())&&(yield*i[tr](e,t,!1))}i&&this[hn].has(e)&&(yield new XFAAttribute(this,e,this[e]))}else yield this[wn]}}class XFAObjectArray{constructor(e=1/0){this[mn]=e;this[ln]=[]}get isXFAObject(){return!1}get isXFAObjectArray(){return!0}push(e){if(this[ln].length<=this[mn]){this[ln].push(e);return!0}warn(`XFA - node "${e[kr]}" accepts no more than ${this[mn]} children`);return!1}isEmpty(){return 0===this[ln].length}dump(){return 1===this[ln].length?this[ln][0][js]():this[ln].map((e=>e[js]()))}[Ts](){const e=new XFAObjectArray(this[mn]);e[ln]=this[ln].map((e=>e[Ts]()));return e}get children(){return this[ln]}clear(){this[ln].length=0}}class XFAAttribute{constructor(e,t,i){this[wn]=e;this[kr]=t;this[Os]=i;this[qs]=!1;this[Vr]="attribute"+Sn++}[Ir](){return this[wn]}[fr](){return!0}[ir](){return this[Os].trim()}[qr](e){e=e.value||"";this[Os]=e.toString()}[Pr](){return this[Os]}[pr](e){return this[wn]===e||this[wn][pr](e)}}class XmlObject extends XFAObject{constructor(e,t,i={}){super(e,t);this[Os]="";this[Qn]=null;if("#text"!==t){const e=new Map;this[Cn]=e;for(const[t,a]of Object.entries(i))e.set(t,new XFAAttribute(this,t,a));if(i.hasOwnProperty(Rr)){const e=i[Rr].xfa.dataNode;void 0!==e&&("dataGroup"===e?this[Qn]=!1:"dataValue"===e&&(this[Qn]=!0))}}this[qs]=!1}[Xr](e){const t=this[kr];if("#text"===t){e.push(encodeToXmlString(this[Os]));return}const i=utf8StringToString(t),a=this[Sr]===kn?"xfa:":"";e.push(`<${a}${i}`);for(const[t,i]of this[Cn].entries()){const a=utf8StringToString(t);e.push(` ${a}="${encodeToXmlString(i[Os])}"`)}null!==this[Qn]&&(this[Qn]?e.push(' xfa:dataNode="dataValue"'):e.push(' xfa:dataNode="dataGroup"'));if(this[Os]||0!==this[ln].length){e.push(">");if(this[Os])"string"==typeof this[Os]?e.push(encodeToXmlString(this[Os])):this[Os][Xr](e);else for(const t of this[ln])t[Xr](e);e.push(``)}else e.push("/>")}[Nr](e){if(this[Os]){const e=new XmlObject(this[Sr],"#text");this[Hs](e);e[Os]=this[Os];this[Os]=""}this[Hs](e);return!0}[Mr](e){this[Os]+=e}[Zs](){if(this[Os]&&this[ln].length>0){const e=new XmlObject(this[Sr],"#text");this[Hs](e);e[Os]=this[Os];delete this[Os]}}[jr](){return"#text"===this[kr]?HTMLResult.success({name:"#text",value:this[Os]}):HTMLResult.EMPTY}[rr](e=null){return e?this[ln].filter((t=>t[kr]===e)):this[ln]}[_s](){return this[Cn]}[Ar](e){const t=this[Cn].get(e);return void 0!==t?t:this[rr](e)}*[tr](e,t){const i=this[Cn].get(e);i&&(yield i);for(const i of this[ln]){i[kr]===e&&(yield i);t&&(yield*i[tr](e,t))}}*[zs](e,t){const i=this[Cn].get(e);!i||t&&i[qs]||(yield i);for(const i of this[ln])yield*i[zs](e,t)}*[sr](e,t,i){for(const a of this[ln]){a[kr]!==e||i&&a[qs]||(yield a);t&&(yield*a[sr](e,t,i))}}[fr](){return null===this[Qn]?0===this[ln].length||this[ln][0][Sr]===_r.xhtml.id:this[Qn]}[ir](){return null===this[Qn]?0===this[ln].length?this[Os].trim():this[ln][0][Sr]===_r.xhtml.id?this[ln][0][Pr]().trim():null:this[Os].trim()}[qr](e){e=e.value||"";this[Os]=e.toString()}[js](e=!1){const t=Object.create(null);e&&(t.$ns=this[Sr]);this[Os]&&(t.$content=this[Os]);t.$name=this[kr];t.children=[];for(const i of this[ln])t.children.push(i[js](e));t.attributes=Object.create(null);for(const[e,i]of this[Cn])t.attributes[e]=i[Os];return t}}class ContentObject extends XFAObject{constructor(e,t){super(e,t);this[Os]=""}[Mr](e){this[Os]+=e}[Zs](){}}class OptionObject extends ContentObject{constructor(e,t,i){super(e,t);this[yn]=i}[Zs](){this[Os]=getKeyword({data:this[Os],defaultValue:this[yn][0],validate:e=>this[yn].includes(e)})}[Ys](e){super[Ys](e);delete this[yn]}}class StringObject extends ContentObject{[Zs](){this[Os]=this[Os].trim()}}class IntegerObject extends ContentObject{constructor(e,t,i,a){super(e,t);this[En]=i;this[Fn]=a}[Zs](){this[Os]=getInteger({data:this[Os],defaultValue:this[En],validate:this[Fn]})}[Ys](e){super[Ys](e);delete this[En];delete this[Fn]}}class Option01 extends IntegerObject{constructor(e,t){super(e,t,0,(e=>1===e))}}class Option10 extends IntegerObject{constructor(e,t){super(e,t,1,(e=>0===e))}}function measureToString(e){return"string"==typeof e?"0px":Number.isInteger(e)?`${e}px`:`${e.toFixed(2)}px`}const Rn={anchorType(e,t){const i=e[or]();if(i&&(!i.layout||"position"===i.layout)){"transform"in t||(t.transform="");switch(e.anchorType){case"bottomCenter":t.transform+="translate(-50%, -100%)";break;case"bottomLeft":t.transform+="translate(0,-100%)";break;case"bottomRight":t.transform+="translate(-100%,-100%)";break;case"middleCenter":t.transform+="translate(-50%,-50%)";break;case"middleLeft":t.transform+="translate(0,-50%)";break;case"middleRight":t.transform+="translate(-100%,-50%)";break;case"topCenter":t.transform+="translate(-50%,0)";break;case"topRight":t.transform+="translate(-100%,0)"}}},dimensions(e,t){const i=e[or]();let a=e.w;const s=e.h;if(i.layout?.includes("row")){const t=i[Xs],s=e.colSpan;let r;if(-1===s){r=t.columnWidths.slice(t.currentColumn).reduce(((e,t)=>e+t),0);t.currentColumn=0}else{r=t.columnWidths.slice(t.currentColumn,t.currentColumn+s).reduce(((e,t)=>e+t),0);t.currentColumn=(t.currentColumn+e.colSpan)%t.columnWidths.length}isNaN(r)||(a=e.w=r)}t.width=""!==a?measureToString(a):"auto";t.height=""!==s?measureToString(s):"auto"},position(e,t){const i=e[or]();if(!i?.layout||"position"===i.layout){t.position="absolute";t.left=measureToString(e.x);t.top=measureToString(e.y)}},rotate(e,t){if(e.rotate){"transform"in t||(t.transform="");t.transform+=`rotate(-${e.rotate}deg)`;t.transformOrigin="top left"}},presence(e,t){switch(e.presence){case"invisible":t.visibility="hidden";break;case"hidden":case"inactive":t.display="none"}},hAlign(e,t){if("para"===e[kr])switch(e.hAlign){case"justifyAll":t.textAlign="justify-all";break;case"radix":t.textAlign="left";break;default:t.textAlign=e.hAlign}else switch(e.hAlign){case"left":t.alignSelf="start";break;case"center":t.alignSelf="center";break;case"right":t.alignSelf="end"}},margin(e,t){e.margin&&(t.margin=e.margin[Zr]().margin)}};function setMinMaxDimensions(e,t){if("position"===e[or]().layout){e.minW>0&&(t.minWidth=measureToString(e.minW));e.maxW>0&&(t.maxWidth=measureToString(e.maxW));e.minH>0&&(t.minHeight=measureToString(e.minH));e.maxH>0&&(t.maxHeight=measureToString(e.maxH))}}function layoutText(e,t,i,a,s,r){const n=new TextMeasure(t,i,a,s);"string"==typeof e?n.addString(e):e[Ur](n);return n.compute(r)}function layoutNode(e,t){let i=null,a=null,s=!1;if((!e.w||!e.h)&&e.value){let r=0,n=0;if(e.margin){r=e.margin.leftInset+e.margin.rightInset;n=e.margin.topInset+e.margin.bottomInset}let g=null,o=null;if(e.para){o=Object.create(null);g=""===e.para.lineHeight?null:e.para.lineHeight;o.top=""===e.para.spaceAbove?0:e.para.spaceAbove;o.bottom=""===e.para.spaceBelow?0:e.para.spaceBelow;o.left=""===e.para.marginLeft?0:e.para.marginLeft;o.right=""===e.para.marginRight?0:e.para.marginRight}let c=e.font;if(!c){const t=e[cr]();let i=e[Ir]();for(;i&&i!==t;){if(i.font){c=i.font;break}i=i[Ir]()}}const C=(e.w||t.width)-r,h=e[Cr].fontFinder;if(e.value.exData&&e.value.exData[Os]&&"text/html"===e.value.exData.contentType){const t=layoutText(e.value.exData[Os],c,o,g,h,C);a=t.width;i=t.height;s=t.isBroken}else{const t=e.value[Pr]();if(t){const e=layoutText(t,c,o,g,h,C);a=e.width;i=e.height;s=e.isBroken}}null===a||e.w||(a+=r);null===i||e.h||(i+=n)}return{w:a,h:i,isBroken:s}}function computeBbox(e,t,i){let a;if(""!==e.w&&""!==e.h)a=[e.x,e.y,e.w,e.h];else{if(!i)return null;let s=e.w;if(""===s){if(0===e.maxW){const t=e[or]();s="position"===t.layout&&""!==t.w?0:e.minW}else s=Math.min(e.maxW,i.width);t.attributes.style.width=measureToString(s)}let r=e.h;if(""===r){if(0===e.maxH){const t=e[or]();r="position"===t.layout&&""!==t.h?0:e.minH}else r=Math.min(e.maxH,i.height);t.attributes.style.height=measureToString(r)}a=[e.x,e.y,s,r]}return a}function fixDimensions(e){const t=e[or]();if(t.layout?.includes("row")){const i=t[Xs],a=e.colSpan;let s;s=-1===a?i.columnWidths.slice(i.currentColumn).reduce(((e,t)=>e+t),0):i.columnWidths.slice(i.currentColumn,i.currentColumn+a).reduce(((e,t)=>e+t),0);isNaN(s)||(e.w=s)}t.layout&&"position"!==t.layout&&(e.x=e.y=0);"table"===e.layout&&""===e.w&&Array.isArray(e.columnWidths)&&(e.w=e.columnWidths.reduce(((e,t)=>e+t),0))}function layoutClass(e){switch(e.layout){case"position":default:return"xfaPosition";case"lr-tb":return"xfaLrTb";case"rl-row":return"xfaRlRow";case"rl-tb":return"xfaRlTb";case"row":return"xfaRow";case"table":return"xfaTable";case"tb":return"xfaTb"}}function toStyle(e,...t){const i=Object.create(null);for(const a of t){const t=e[a];if(null!==t)if(Rn.hasOwnProperty(a))Rn[a](e,i);else if(t instanceof XFAObject){const e=t[Zr]();e?Object.assign(i,e):warn(`(DEBUG) - XFA - style for ${a} not implemented yet`)}}return i}function createWrapper(e,t){const{attributes:i}=t,{style:a}=i,s={name:"div",attributes:{class:["xfaWrapper"],style:Object.create(null)},children:[]};i.class.push("xfaWrapped");if(e.border){const{widths:i,insets:r}=e.border[Xs];let n,g,o=r[0],c=r[3];const C=r[0]+r[2],h=r[1]+r[3];switch(e.border.hand){case"even":o-=i[0]/2;c-=i[3]/2;n=`calc(100% + ${(i[1]+i[3])/2-h}px)`;g=`calc(100% + ${(i[0]+i[2])/2-C}px)`;break;case"left":o-=i[0];c-=i[3];n=`calc(100% + ${i[1]+i[3]-h}px)`;g=`calc(100% + ${i[0]+i[2]-C}px)`;break;case"right":n=h?`calc(100% - ${h}px)`:"100%";g=C?`calc(100% - ${C}px)`:"100%"}const l=["xfaBorder"];isPrintOnly(e.border)&&l.push("xfaPrintOnly");const Q={name:"div",attributes:{class:l,style:{top:`${o}px`,left:`${c}px`,width:n,height:g}},children:[]};for(const e of["border","borderWidth","borderColor","borderRadius","borderStyle"])if(void 0!==a[e]){Q.attributes.style[e]=a[e];delete a[e]}s.children.push(Q,t)}else s.children.push(t);for(const e of["background","backgroundClip","top","left","width","height","minWidth","minHeight","maxWidth","maxHeight","transform","transformOrigin","visibility"])if(void 0!==a[e]){s.attributes.style[e]=a[e];delete a[e]}s.attributes.style.position="absolute"===a.position?"absolute":"relative";delete a.position;if(a.alignSelf){s.attributes.style.alignSelf=a.alignSelf;delete a.alignSelf}return s}function fixTextIndent(e){const t=getMeasurement(e.textIndent,"0px");if(t>=0)return;const i="padding"+("left"===("right"===e.textAlign?"right":"left")?"Left":"Right"),a=getMeasurement(e[i],"0px");e[i]=a-t+"px"}function setAccess(e,t){switch(e.access){case"nonInteractive":t.push("xfaNonInteractive");break;case"readOnly":t.push("xfaReadOnly");break;case"protected":t.push("xfaDisabled")}}function isPrintOnly(e){return e.relevant.length>0&&!e.relevant[0].excluded&&"print"===e.relevant[0].viewname}function getCurrentPara(e){const t=e[cr]()[Xs].paraStack;return t.length?t.at(-1):null}function setPara(e,t,i){if(i.attributes.class?.includes("xfaRich")){if(t){""===e.h&&(t.height="auto");""===e.w&&(t.width="auto")}const a=getCurrentPara(e);if(a){const e=i.attributes.style;e.display="flex";e.flexDirection="column";switch(a.vAlign){case"top":e.justifyContent="start";break;case"bottom":e.justifyContent="end";break;case"middle":e.justifyContent="center"}const t=a[Zr]();for(const[i,a]of Object.entries(t))i in e||(e[i]=a)}}}function setFontFamily(e,t,i,a){if(!i){delete a.fontFamily;return}const s=stripQuotes(e.typeface);a.fontFamily=`"${s}"`;const r=i.find(s);if(r){const{fontFamily:i}=r.regular.cssFontInfo;i!==s&&(a.fontFamily=`"${i}"`);const n=getCurrentPara(t);if(n&&""!==n.lineHeight)return;if(a.lineHeight)return;const g=selectFont(e,r);g&&(a.lineHeight=Math.max(1.2,g.lineHeight))}}function fixURL(e){const t=createValidAbsoluteUrl(e,null,{addDefaultProtocol:!0,tryConvertEncoding:!0});return t?t.href:null}function createLine(e,t){return{name:"div",attributes:{class:["lr-tb"===e.layout?"xfaLr":"xfaRl"]},children:t}}function flushHTML(e){if(!e[Xs])return null;const t={name:"div",attributes:e[Xs].attributes,children:e[Xs].children};if(e[Xs].failingNode){const i=e[Xs].failingNode[Vs]();i&&(e.layout.endsWith("-tb")?t.children.push(createLine(e,[i])):t.children.push(i))}return 0===t.children.length?null:t}function addHTML(e,t,i){const a=e[Xs],s=a.availableSpace,[r,n,g,o]=i;switch(e.layout){case"position":a.width=Math.max(a.width,r+g);a.height=Math.max(a.height,n+o);a.children.push(t);break;case"lr-tb":case"rl-tb":if(!a.line||1===a.attempt){a.line=createLine(e,[]);a.children.push(a.line);a.numberInLine=0}a.numberInLine+=1;a.line.children.push(t);if(0===a.attempt){a.currentWidth+=g;a.height=Math.max(a.height,a.prevHeight+o)}else{a.currentWidth=g;a.prevHeight=a.height;a.height+=o;a.attempt=0}a.width=Math.max(a.width,a.currentWidth);break;case"rl-row":case"row":{a.children.push(t);a.width+=g;a.height=Math.max(a.height,o);const e=measureToString(a.height);for(const t of a.children)t.attributes.style.height=e;break}case"table":case"tb":a.width=Math.min(s.width,Math.max(a.width,g));a.height+=o;a.children.push(t)}}function getAvailableSpace(e){const t=e[Xs].availableSpace,i=e.margin?e.margin.topInset+e.margin.bottomInset:0,a=e.margin?e.margin.leftInset+e.margin.rightInset:0;switch(e.layout){case"lr-tb":case"rl-tb":return 0===e[Xs].attempt?{width:t.width-a-e[Xs].currentWidth,height:t.height-i-e[Xs].prevHeight}:{width:t.width-a,height:t.height-i-e[Xs].height};case"rl-row":case"row":return{width:e[Xs].columnWidths.slice(e[Xs].currentColumn).reduce(((e,t)=>e+t)),height:t.height-a};case"table":case"tb":return{width:t.width-a,height:t.height-i-e[Xs].height};default:return t}}function checkDimensions(e,t){if(null===e[cr]()[Xs].firstUnsplittable)return!0;if(0===e.w||0===e.h)return!0;const i=e[or](),a=i[Xs]?.attempt||0,[,s,r,n]=function getTransformedBBox(e){let t,i,a=""===e.w?NaN:e.w,s=""===e.h?NaN:e.h,[r,n]=[0,0];switch(e.anchorType||""){case"bottomCenter":[r,n]=[a/2,s];break;case"bottomLeft":[r,n]=[0,s];break;case"bottomRight":[r,n]=[a,s];break;case"middleCenter":[r,n]=[a/2,s/2];break;case"middleLeft":[r,n]=[0,s/2];break;case"middleRight":[r,n]=[a,s/2];break;case"topCenter":[r,n]=[a/2,0];break;case"topRight":[r,n]=[a,0]}switch(e.rotate||0){case 0:[t,i]=[-r,-n];break;case 90:[t,i]=[-n,r];[a,s]=[s,-a];break;case 180:[t,i]=[r,n];[a,s]=[-a,-s];break;case 270:[t,i]=[n,-r];[a,s]=[-s,a]}return[e.x+t+Math.min(0,a),e.y+i+Math.min(0,s),Math.abs(a),Math.abs(s)]}(e);switch(i.layout){case"lr-tb":case"rl-tb":return 0===a?e[cr]()[Xs].noLayoutFailure?""!==e.w?Math.round(r-t.width)<=2:t.width>2:!(""!==e.h&&Math.round(n-t.height)>2)&&(""!==e.w?Math.round(r-t.width)<=2||0===i[Xs].numberInLine&&t.height>2:t.width>2):!!e[cr]()[Xs].noLayoutFailure||!(""!==e.h&&Math.round(n-t.height)>2)&&((""===e.w||Math.round(r-t.width)<=2||!i[wr]())&&t.height>2);case"table":case"tb":return!!e[cr]()[Xs].noLayoutFailure||(""===e.h||e[yr]()?(""===e.w||Math.round(r-t.width)<=2||!i[wr]())&&t.height>2:Math.round(n-t.height)<=2);case"position":if(e[cr]()[Xs].noLayoutFailure)return!0;if(""===e.h||Math.round(n+s-t.height)<=2)return!0;return n+s>e[cr]()[Xs].currentContentArea.h;case"rl-row":case"row":return!!e[cr]()[Xs].noLayoutFailure||(""===e.h||Math.round(n-t.height)<=2);default:return!0}}const Nn=_r.template.id,Gn="http://www.w3.org/2000/svg",Mn=/^H(\d+)$/,Un=new Set(["image/gif","image/jpeg","image/jpg","image/pjpeg","image/png","image/apng","image/x-png","image/bmp","image/x-ms-bmp","image/tiff","image/tif","application/octet-stream"]),xn=[[[66,77],"image/bmp"],[[255,216,255],"image/jpeg"],[[73,73,42,0],"image/tiff"],[[77,77,0,42],"image/tiff"],[[71,73,70,56,57,97],"image/gif"],[[137,80,78,71,13,10,26,10],"image/png"]];function getBorderDims(e){if(!e||!e.border)return{w:0,h:0};const t=e.border[ar]();return t?{w:t.widths[0]+t.widths[2]+t.insets[0]+t.insets[2],h:t.widths[1]+t.widths[3]+t.insets[1]+t.insets[3]}:{w:0,h:0}}function hasMargin(e){return e.margin&&(e.margin.topInset||e.margin.rightInset||e.margin.bottomInset||e.margin.leftInset)}function _setValue(e,t){if(!e.value){const t=new Value({});e[Hs](t);e.value=t}e.value[qr](t)}function*getContainedChildren(e){for(const t of e[rr]())t instanceof SubformSet?yield*t[nr]():yield t}function isRequired(e){return"error"===e.validate?.nullTest}function setTabIndex(e){for(;e;){if(!e.traversal){e[Or]=e[Ir]()[Or];return}if(e[Or])return;let t=null;for(const i of e.traversal[rr]())if("next"===i.operation){t=i;break}if(!t||!t.ref){e[Or]=e[Ir]()[Or];return}const i=e[cr]();e[Or]=++i[Or];const a=i[vr](t.ref,e);if(!a)return;e=a[0]}}function applyAssist(e,t){const i=e.assist;if(i){const e=i[jr]();e&&(t.title=e);const a=i.role.match(Mn);if(a){const e="heading",i=a[1];t.role=e;t["aria-level"]=i}}if("table"===e.layout)t.role="table";else if("row"===e.layout)t.role="row";else{const i=e[Ir]();"row"===i.layout&&(t.role="TH"===i.assist?.role?"columnheader":"cell")}}function ariaLabel(e){if(!e.assist)return null;const t=e.assist;return t.speak&&""!==t.speak[Os]?t.speak[Os]:t.toolTip?t.toolTip[Os]:null}function valueToHtml(e){return HTMLResult.success({name:"div",attributes:{class:["xfaRich"],style:Object.create(null)},children:[{name:"span",attributes:{style:Object.create(null)},value:e}]})}function setFirstUnsplittable(e){const t=e[cr]();if(null===t[Xs].firstUnsplittable){t[Xs].firstUnsplittable=e;t[Xs].noLayoutFailure=!0}}function unsetFirstUnsplittable(e){const t=e[cr]();t[Xs].firstUnsplittable===e&&(t[Xs].noLayoutFailure=!1)}function handleBreak(e){if(e[Xs])return!1;e[Xs]=Object.create(null);if("auto"===e.targetType)return!1;const t=e[cr]();let i=null;if(e.target){i=t[vr](e.target,e[Ir]());if(!i)return!1;i=i[0]}const{currentPageArea:a,currentContentArea:s}=t[Xs];if("pageArea"===e.targetType){i instanceof PageArea||(i=null);if(e.startNew){e[Xs].target=i||a;return!0}if(i&&i!==a){e[Xs].target=i;return!0}return!1}i instanceof ContentArea||(i=null);const r=i&&i[Ir]();let n,g=r;if(e.startNew)if(i){const e=r.contentArea.children,t=e.indexOf(s),a=e.indexOf(i);-1!==t&&te;a[Xs].noLayoutFailure=!0;const n=t[jr](i);e[Ls](n.html,n.bbox);a[Xs].noLayoutFailure=s;t[or]=r}class AppearanceFilter extends StringObject{constructor(e){super(Nn,"appearanceFilter");this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Arc extends XFAObject{constructor(e){super(Nn,"arc",!0);this.circular=getInteger({data:e.circular,defaultValue:0,validate:e=>1===e});this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.startAngle=getFloat({data:e.startAngle,defaultValue:0,validate:e=>!0});this.sweepAngle=getFloat({data:e.sweepAngle,defaultValue:360,validate:e=>!0});this.use=e.use||"";this.usehref=e.usehref||"";this.edge=null;this.fill=null}[jr](){const e=this.edge||new Edge({}),t=e[Zr](),i=Object.create(null);"visible"===this.fill?.presence?Object.assign(i,this.fill[Zr]()):i.fill="transparent";i.strokeWidth=measureToString("visible"===e.presence?e.thickness:0);i.stroke=t.color;let a;const s={xmlns:Gn,style:{width:"100%",height:"100%",overflow:"visible"}};if(360===this.sweepAngle)a={name:"ellipse",attributes:{xmlns:Gn,cx:"50%",cy:"50%",rx:"50%",ry:"50%",style:i}};else{const e=this.startAngle*Math.PI/180,t=this.sweepAngle*Math.PI/180,r=this.sweepAngle>180?1:0,[n,g,o,c]=[50*(1+Math.cos(e)),50*(1-Math.sin(e)),50*(1+Math.cos(e+t)),50*(1-Math.sin(e+t))];a={name:"path",attributes:{xmlns:Gn,d:`M ${n} ${g} A 50 50 0 ${r} 0 ${o} ${c}`,vectorEffect:"non-scaling-stroke",style:i}};Object.assign(s,{viewBox:"0 0 100 100",preserveAspectRatio:"none"})}const r={name:"svg",children:[a],attributes:s};if(hasMargin(this[Ir]()[Ir]()))return HTMLResult.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[r]});r.attributes.style.position="absolute";return HTMLResult.success(r)}}class Area extends XFAObject{constructor(e){super(Nn,"area",!0);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.id=e.id||"";this.name=e.name||"";this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.desc=null;this.extras=null;this.area=new XFAObjectArray;this.draw=new XFAObjectArray;this.exObject=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.field=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray}*[nr](){yield*getContainedChildren(this)}[Dr](){return!0}[dr](){return!0}[Ls](e,t){const[i,a,s,r]=t;this[Xs].width=Math.max(this[Xs].width,i+s);this[Xs].height=Math.max(this[Xs].height,a+r);this[Xs].children.push(e)}[$s](){return this[Xs].availableSpace}[jr](e){const t=toStyle(this,"position"),i={style:t,id:this[Vr],class:["xfaArea"]};isPrintOnly(this)&&i.class.push("xfaPrintOnly");this.name&&(i.xfaName=this.name);const a=[];this[Xs]={children:a,width:0,height:0,availableSpace:e};const s=this[Js]({filter:new Set(["area","draw","field","exclGroup","subform","subformSet"]),include:!0});if(!s.success){if(s.isBreak())return s;delete this[Xs];return HTMLResult.FAILURE}t.width=measureToString(this[Xs].width);t.height=measureToString(this[Xs].height);const r={name:"div",attributes:i,children:a},n=[this.x,this.y,this[Xs].width,this[Xs].height];delete this[Xs];return HTMLResult.success(r,n)}}class Assist extends XFAObject{constructor(e){super(Nn,"assist",!0);this.id=e.id||"";this.role=e.role||"";this.use=e.use||"";this.usehref=e.usehref||"";this.speak=null;this.toolTip=null}[jr](){return this.toolTip?.[Os]||null}}class Barcode extends XFAObject{constructor(e){super(Nn,"barcode",!0);this.charEncoding=getKeyword({data:e.charEncoding?e.charEncoding.toLowerCase():"",defaultValue:"",validate:e=>["utf-8","big-five","fontspecific","gbk","gb-18030","gb-2312","ksc-5601","none","shift-jis","ucs-2","utf-16"].includes(e)||e.match(/iso-8859-\d{2}/)});this.checksum=getStringOption(e.checksum,["none","1mod10","1mod10_1mod11","2mod10","auto"]);this.dataColumnCount=getInteger({data:e.dataColumnCount,defaultValue:-1,validate:e=>e>=0});this.dataLength=getInteger({data:e.dataLength,defaultValue:-1,validate:e=>e>=0});this.dataPrep=getStringOption(e.dataPrep,["none","flateCompress"]);this.dataRowCount=getInteger({data:e.dataRowCount,defaultValue:-1,validate:e=>e>=0});this.endChar=e.endChar||"";this.errorCorrectionLevel=getInteger({data:e.errorCorrectionLevel,defaultValue:-1,validate:e=>e>=0&&e<=8});this.id=e.id||"";this.moduleHeight=getMeasurement(e.moduleHeight,"5mm");this.moduleWidth=getMeasurement(e.moduleWidth,"0.25mm");this.printCheckDigit=getInteger({data:e.printCheckDigit,defaultValue:0,validate:e=>1===e});this.rowColumnRatio=getRatio(e.rowColumnRatio);this.startChar=e.startChar||"";this.textLocation=getStringOption(e.textLocation,["below","above","aboveEmbedded","belowEmbedded","none"]);this.truncate=getInteger({data:e.truncate,defaultValue:0,validate:e=>1===e});this.type=getStringOption(e.type?e.type.toLowerCase():"",["aztec","codabar","code2of5industrial","code2of5interleaved","code2of5matrix","code2of5standard","code3of9","code3of9extended","code11","code49","code93","code128","code128a","code128b","code128c","code128sscc","datamatrix","ean8","ean8add2","ean8add5","ean13","ean13add2","ean13add5","ean13pwcd","fim","logmars","maxicode","msi","pdf417","pdf417macro","plessey","postauscust2","postauscust3","postausreplypaid","postausstandard","postukrm4scc","postusdpbc","postusimb","postusstandard","postus5zip","qrcode","rfid","rss14","rss14expanded","rss14limited","rss14stacked","rss14stackedomni","rss14truncated","telepen","ucc128","ucc128random","ucc128sscc","upca","upcaadd2","upcaadd5","upcapwcd","upce","upceadd2","upceadd5","upcean2","upcean5","upsmaxicode"]);this.upsMode=getStringOption(e.upsMode,["usCarrier","internationalCarrier","secureSymbol","standardSymbol"]);this.use=e.use||"";this.usehref=e.usehref||"";this.wideNarrowRatio=getRatio(e.wideNarrowRatio);this.encrypt=null;this.extras=null}}class Bind extends XFAObject{constructor(e){super(Nn,"bind",!0);this.match=getStringOption(e.match,["once","dataRef","global","none"]);this.ref=e.ref||"";this.picture=null}}class BindItems extends XFAObject{constructor(e){super(Nn,"bindItems");this.connection=e.connection||"";this.labelRef=e.labelRef||"";this.ref=e.ref||"";this.valueRef=e.valueRef||""}}class Bookend extends XFAObject{constructor(e){super(Nn,"bookend");this.id=e.id||"";this.leader=e.leader||"";this.trailer=e.trailer||"";this.use=e.use||"";this.usehref=e.usehref||""}}class BooleanElement extends Option01{constructor(e){super(Nn,"boolean");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[jr](e){return valueToHtml(1===this[Os]?"1":"0")}}class Border extends XFAObject{constructor(e){super(Nn,"border",!0);this.break=getStringOption(e.break,["close","open"]);this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.corner=new XFAObjectArray(4);this.edge=new XFAObjectArray(4);this.extras=null;this.fill=null;this.margin=null}[ar](){if(!this[Xs]){const e=this.edge.children.slice();if(e.length<4){const t=e.at(-1)||new Edge({});for(let i=e.length;i<4;i++)e.push(t)}const t=e.map((e=>e.thickness)),i=[0,0,0,0];if(this.margin){i[0]=this.margin.topInset;i[1]=this.margin.rightInset;i[2]=this.margin.bottomInset;i[3]=this.margin.leftInset}this[Xs]={widths:t,insets:i,edges:e}}return this[Xs]}[Zr](){const{edges:e}=this[ar](),t=e.map((e=>{const t=e[Zr]();t.color||="#000000";return t})),i=Object.create(null);this.margin&&Object.assign(i,this.margin[Zr]());"visible"===this.fill?.presence&&Object.assign(i,this.fill[Zr]());if(this.corner.children.some((e=>0!==e.radius))){const e=this.corner.children.map((e=>e[Zr]()));if(2===e.length||3===e.length){const t=e.at(-1);for(let i=e.length;i<4;i++)e.push(t)}i.borderRadius=e.map((e=>e.radius)).join(" ")}switch(this.presence){case"invisible":case"hidden":i.borderStyle="";break;case"inactive":i.borderStyle="none";break;default:i.borderStyle=t.map((e=>e.style)).join(" ")}i.borderWidth=t.map((e=>e.width)).join(" ");i.borderColor=t.map((e=>e.color)).join(" ");return i}}class Break extends XFAObject{constructor(e){super(Nn,"break",!0);this.after=getStringOption(e.after,["auto","contentArea","pageArea","pageEven","pageOdd"]);this.afterTarget=e.afterTarget||"";this.before=getStringOption(e.before,["auto","contentArea","pageArea","pageEven","pageOdd"]);this.beforeTarget=e.beforeTarget||"";this.bookendLeader=e.bookendLeader||"";this.bookendTrailer=e.bookendTrailer||"";this.id=e.id||"";this.overflowLeader=e.overflowLeader||"";this.overflowTarget=e.overflowTarget||"";this.overflowTrailer=e.overflowTrailer||"";this.startNew=getInteger({data:e.startNew,defaultValue:0,validate:e=>1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}}class BreakAfter extends XFAObject{constructor(e){super(Nn,"breakAfter",!0);this.id=e.id||"";this.leader=e.leader||"";this.startNew=getInteger({data:e.startNew,defaultValue:0,validate:e=>1===e});this.target=e.target||"";this.targetType=getStringOption(e.targetType,["auto","contentArea","pageArea"]);this.trailer=e.trailer||"";this.use=e.use||"";this.usehref=e.usehref||"";this.script=null}}class BreakBefore extends XFAObject{constructor(e){super(Nn,"breakBefore",!0);this.id=e.id||"";this.leader=e.leader||"";this.startNew=getInteger({data:e.startNew,defaultValue:0,validate:e=>1===e});this.target=e.target||"";this.targetType=getStringOption(e.targetType,["auto","contentArea","pageArea"]);this.trailer=e.trailer||"";this.use=e.use||"";this.usehref=e.usehref||"";this.script=null}[jr](e){this[Xs]={};return HTMLResult.FAILURE}}class Button extends XFAObject{constructor(e){super(Nn,"button",!0);this.highlight=getStringOption(e.highlight,["inverted","none","outline","push"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[jr](e){const t=this[Ir]()[Ir](),i={name:"button",attributes:{id:this[Vr],class:["xfaButton"],style:{}},children:[]};for(const e of t.event.children){if("click"!==e.activity||!e.script)continue;const t=recoverJsURL(e.script[Os]);if(!t)continue;const a=fixURL(t.url);a&&i.children.push({name:"a",attributes:{id:"link"+this[Vr],href:a,newWindow:t.newWindow,class:["xfaLink"],style:{}},children:[]})}return HTMLResult.success(i)}}class Calculate extends XFAObject{constructor(e){super(Nn,"calculate",!0);this.id=e.id||"";this.override=getStringOption(e.override,["disabled","error","ignore","warning"]);this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.message=null;this.script=null}}class Caption extends XFAObject{constructor(e){super(Nn,"caption",!0);this.id=e.id||"";this.placement=getStringOption(e.placement,["left","bottom","inline","right","top"]);this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.reserve=Math.ceil(getMeasurement(e.reserve));this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.font=null;this.margin=null;this.para=null;this.value=null}[qr](e){_setValue(this,e)}[ar](e){if(!this[Xs]){let{width:t,height:i}=e;switch(this.placement){case"left":case"right":case"inline":t=this.reserve<=0?t:this.reserve;break;case"top":case"bottom":i=this.reserve<=0?i:this.reserve}this[Xs]=layoutNode(this,{width:t,height:i})}return this[Xs]}[jr](e){if(!this.value)return HTMLResult.EMPTY;this[Lr]();const t=this.value[jr](e).html;if(!t){this[xr]();return HTMLResult.EMPTY}const i=this.reserve;if(this.reserve<=0){const{w:t,h:i}=this[ar](e);switch(this.placement){case"left":case"right":case"inline":this.reserve=t;break;case"top":case"bottom":this.reserve=i}}const a=[];"string"==typeof t?a.push({name:"#text",value:t}):a.push(t);const s=toStyle(this,"font","margin","visibility");switch(this.placement){case"left":case"right":this.reserve>0&&(s.width=measureToString(this.reserve));break;case"top":case"bottom":this.reserve>0&&(s.height=measureToString(this.reserve))}setPara(this,null,t);this[xr]();this.reserve=i;return HTMLResult.success({name:"div",attributes:{style:s,class:["xfaCaption"]},children:a})}}class Certificate extends StringObject{constructor(e){super(Nn,"certificate");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Certificates extends XFAObject{constructor(e){super(Nn,"certificates",!0);this.credentialServerPolicy=getStringOption(e.credentialServerPolicy,["optional","required"]);this.id=e.id||"";this.url=e.url||"";this.urlPolicy=e.urlPolicy||"";this.use=e.use||"";this.usehref=e.usehref||"";this.encryption=null;this.issuers=null;this.keyUsage=null;this.oids=null;this.signing=null;this.subjectDNs=null}}class CheckButton extends XFAObject{constructor(e){super(Nn,"checkButton",!0);this.id=e.id||"";this.mark=getStringOption(e.mark,["default","check","circle","cross","diamond","square","star"]);this.shape=getStringOption(e.shape,["square","round"]);this.size=getMeasurement(e.size,"10pt");this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}[jr](e){const t=toStyle("margin"),i=measureToString(this.size);t.width=t.height=i;let a,s,r;const n=this[Ir]()[Ir](),g=n.items.children.length&&n.items.children[0][jr]().html||[],o={on:(void 0!==g[0]?g[0]:"on").toString(),off:(void 0!==g[1]?g[1]:"off").toString()},c=(n.value?.[Pr]()||"off")===o.on||void 0,C=n[or](),h=n[Vr];let l;if(C instanceof ExclGroup){r=C[Vr];a="radio";s="xfaRadio";l=C[Ws]?.[Vr]||C[Vr]}else{a="checkbox";s="xfaCheckbox";l=n[Ws]?.[Vr]||n[Vr]}const Q={name:"input",attributes:{class:[s],style:t,fieldId:h,dataId:l,type:a,checked:c,xfaOn:o.on,xfaOff:o.off,"aria-label":ariaLabel(n),"aria-required":!1}};r&&(Q.attributes.name=r);if(isRequired(n)){Q.attributes["aria-required"]=!0;Q.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[Q]})}}class ChoiceList extends XFAObject{constructor(e){super(Nn,"choiceList",!0);this.commitOn=getStringOption(e.commitOn,["select","exit"]);this.id=e.id||"";this.open=getStringOption(e.open,["userControl","always","multiSelect","onEntry"]);this.textEntry=getInteger({data:e.textEntry,defaultValue:0,validate:e=>1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}[jr](e){const t=toStyle(this,"border","margin"),i=this[Ir]()[Ir](),a={fontSize:`calc(${i.font?.size||10}px * var(--scale-factor))`},s=[];if(i.items.children.length>0){const e=i.items;let t=0,r=0;if(2===e.children.length){t=e.children[0].save;r=1-t}const n=e.children[t][jr]().html,g=e.children[r][jr]().html;let o=!1;const c=i.value?.[Pr]()||"";for(let e=0,t=n.length;eMath.min(Math.max(0,parseInt(e.trim(),10)),255))).map((e=>isNaN(e)?0:e));if(r.length<3)return{r:i,g:a,b:s};[i,a,s]=r;return{r:i,g:a,b:s}}(e.value):"";this.extras=null}[hr](){return!1}[Zr](){return this.value?Util.makeHexColor(this.value.r,this.value.g,this.value.b):null}}class Comb extends XFAObject{constructor(e){super(Nn,"comb");this.id=e.id||"";this.numberOfCells=getInteger({data:e.numberOfCells,defaultValue:0,validate:e=>e>=0});this.use=e.use||"";this.usehref=e.usehref||""}}class Connect extends XFAObject{constructor(e){super(Nn,"connect",!0);this.connection=e.connection||"";this.id=e.id||"";this.ref=e.ref||"";this.usage=getStringOption(e.usage,["exportAndImport","exportOnly","importOnly"]);this.use=e.use||"";this.usehref=e.usehref||"";this.picture=null}}class ContentArea extends XFAObject{constructor(e){super(Nn,"contentArea",!0);this.h=getMeasurement(e.h);this.id=e.id||"";this.name=e.name||"";this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.w=getMeasurement(e.w);this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.desc=null;this.extras=null}[jr](e){const t={left:measureToString(this.x),top:measureToString(this.y),width:measureToString(this.w),height:measureToString(this.h)},i=["xfaContentarea"];isPrintOnly(this)&&i.push("xfaPrintOnly");return HTMLResult.success({name:"div",children:[],attributes:{style:t,class:i,id:this[Vr]}})}}class Corner extends XFAObject{constructor(e){super(Nn,"corner",!0);this.id=e.id||"";this.inverted=getInteger({data:e.inverted,defaultValue:0,validate:e=>1===e});this.join=getStringOption(e.join,["square","round"]);this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.radius=getMeasurement(e.radius);this.stroke=getStringOption(e.stroke,["solid","dashDot","dashDotDot","dashed","dotted","embossed","etched","lowered","raised"]);this.thickness=getMeasurement(e.thickness,"0.5pt");this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zr](){const e=toStyle(this,"visibility");e.radius=measureToString("square"===this.join?0:this.radius);return e}}class DateElement extends ContentObject{constructor(e){super(Nn,"date");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){const e=this[Os].trim();this[Os]=e?new Date(e):null}[jr](e){return valueToHtml(this[Os]?this[Os].toString():"")}}class DateTime extends ContentObject{constructor(e){super(Nn,"dateTime");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){const e=this[Os].trim();this[Os]=e?new Date(e):null}[jr](e){return valueToHtml(this[Os]?this[Os].toString():"")}}class DateTimeEdit extends XFAObject{constructor(e){super(Nn,"dateTimeEdit",!0);this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.picker=getStringOption(e.picker,["host","none"]);this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.comb=null;this.extras=null;this.margin=null}[jr](e){const t=toStyle(this,"border","font","margin"),i=this[Ir]()[Ir](),a={name:"input",attributes:{type:"text",fieldId:i[Vr],dataId:i[Ws]?.[Vr]||i[Vr],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(i),"aria-required":!1}};if(isRequired(i)){a.attributes["aria-required"]=!0;a.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[a]})}}class Decimal extends ContentObject{constructor(e){super(Nn,"decimal");this.fracDigits=getInteger({data:e.fracDigits,defaultValue:2,validate:e=>!0});this.id=e.id||"";this.leadDigits=getInteger({data:e.leadDigits,defaultValue:-1,validate:e=>!0});this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){const e=parseFloat(this[Os].trim());this[Os]=isNaN(e)?null:e}[jr](e){return valueToHtml(null!==this[Os]?this[Os].toString():"")}}class DefaultUi extends XFAObject{constructor(e){super(Nn,"defaultUi",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}}class Desc extends XFAObject{constructor(e){super(Nn,"desc",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}}class DigestMethod extends OptionObject{constructor(e){super(Nn,"digestMethod",["","SHA1","SHA256","SHA512","RIPEMD160"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class DigestMethods extends XFAObject{constructor(e){super(Nn,"digestMethods",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.digestMethod=new XFAObjectArray}}class Draw extends XFAObject{constructor(e){super(Nn,"draw",!0);this.anchorType=getStringOption(e.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.locale=e.locale||"";this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.rotate=getInteger({data:e.rotate,defaultValue:0,validate:e=>e%90==0});this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.border=null;this.caption=null;this.desc=null;this.extras=null;this.font=null;this.keep=null;this.margin=null;this.para=null;this.traversal=null;this.ui=null;this.value=null;this.setProperty=new XFAObjectArray}[qr](e){_setValue(this,e)}[jr](e){setTabIndex(this);if("hidden"===this.presence||"inactive"===this.presence)return HTMLResult.EMPTY;fixDimensions(this);this[Lr]();const t=this.w,i=this.h,{w:a,h:s,isBroken:r}=layoutNode(this,e);if(a&&""===this.w){if(r&&this[or]()[wr]()){this[xr]();return HTMLResult.FAILURE}this.w=a}s&&""===this.h&&(this.h=s);setFirstUnsplittable(this);if(!checkDimensions(this,e)){this.w=t;this.h=i;this[xr]();return HTMLResult.FAILURE}unsetFirstUnsplittable(this);const n=toStyle(this,"font","hAlign","dimensions","position","presence","rotate","anchorType","border","margin");setMinMaxDimensions(this,n);if(n.margin){n.padding=n.margin;delete n.margin}const g=["xfaDraw"];this.font&&g.push("xfaFont");isPrintOnly(this)&&g.push("xfaPrintOnly");const o={style:n,id:this[Vr],class:g};this.name&&(o.xfaName=this.name);const c={name:"div",attributes:o,children:[]};applyAssist(this,o);const C=computeBbox(this,c,e),h=this.value?this.value[jr](e).html:null;if(null===h){this.w=t;this.h=i;this[xr]();return HTMLResult.success(createWrapper(this,c),C)}c.children.push(h);setPara(this,n,h);this.w=t;this.h=i;this[xr]();return HTMLResult.success(createWrapper(this,c),C)}}class Edge extends XFAObject{constructor(e){super(Nn,"edge",!0);this.cap=getStringOption(e.cap,["square","butt","round"]);this.id=e.id||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.stroke=getStringOption(e.stroke,["solid","dashDot","dashDotDot","dashed","dotted","embossed","etched","lowered","raised"]);this.thickness=getMeasurement(e.thickness,"0.5pt");this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zr](){const e=toStyle(this,"visibility");Object.assign(e,{linecap:this.cap,width:measureToString(this.thickness),color:this.color?this.color[Zr]():"#000000",style:""});if("visible"!==this.presence)e.style="none";else switch(this.stroke){case"solid":e.style="solid";break;case"dashDot":case"dashDotDot":case"dashed":e.style="dashed";break;case"dotted":e.style="dotted";break;case"embossed":e.style="ridge";break;case"etched":e.style="groove";break;case"lowered":e.style="inset";break;case"raised":e.style="outset"}return e}}class Encoding extends OptionObject{constructor(e){super(Nn,"encoding",["adbe.x509.rsa_sha1","adbe.pkcs7.detached","adbe.pkcs7.sha1"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Encodings extends XFAObject{constructor(e){super(Nn,"encodings",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.encoding=new XFAObjectArray}}class Encrypt extends XFAObject{constructor(e){super(Nn,"encrypt",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=null}}class EncryptData extends XFAObject{constructor(e){super(Nn,"encryptData",!0);this.id=e.id||"";this.operation=getStringOption(e.operation,["encrypt","decrypt"]);this.target=e.target||"";this.use=e.use||"";this.usehref=e.usehref||"";this.filter=null;this.manifest=null}}class Encryption extends XFAObject{constructor(e){super(Nn,"encryption",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=new XFAObjectArray}}class EncryptionMethod extends OptionObject{constructor(e){super(Nn,"encryptionMethod",["","AES256-CBC","TRIPLEDES-CBC","AES128-CBC","AES192-CBC"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class EncryptionMethods extends XFAObject{constructor(e){super(Nn,"encryptionMethods",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.encryptionMethod=new XFAObjectArray}}class Event extends XFAObject{constructor(e){super(Nn,"event",!0);this.activity=getStringOption(e.activity,["click","change","docClose","docReady","enter","exit","full","indexChange","initialize","mouseDown","mouseEnter","mouseExit","mouseUp","postExecute","postOpen","postPrint","postSave","postSign","postSubmit","preExecute","preOpen","prePrint","preSave","preSign","preSubmit","ready","validationState"]);this.id=e.id||"";this.listen=getStringOption(e.listen,["refOnly","refAndDescendents"]);this.name=e.name||"";this.ref=e.ref||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.encryptData=null;this.execute=null;this.script=null;this.signData=null;this.submit=null}}class ExData extends ContentObject{constructor(e){super(Nn,"exData");this.contentType=e.contentType||"";this.href=e.href||"";this.id=e.id||"";this.maxLength=getInteger({data:e.maxLength,defaultValue:-1,validate:e=>e>=-1});this.name=e.name||"";this.rid=e.rid||"";this.transferEncoding=getStringOption(e.transferEncoding,["none","base64","package"]);this.use=e.use||"";this.usehref=e.usehref||""}[ur](){return"text/html"===this.contentType}[Nr](e){if("text/html"===this.contentType&&e[Sr]===_r.xhtml.id){this[Os]=e;return!0}if("text/xml"===this.contentType){this[Os]=e;return!0}return!1}[jr](e){return"text/html"===this.contentType&&this[Os]?this[Os][jr](e):HTMLResult.EMPTY}}class ExObject extends XFAObject{constructor(e){super(Nn,"exObject",!0);this.archive=e.archive||"";this.classId=e.classId||"";this.codeBase=e.codeBase||"";this.codeType=e.codeType||"";this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.exObject=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}}class ExclGroup extends XFAObject{constructor(e){super(Nn,"exclGroup",!0);this.access=getStringOption(e.access,["open","nonInteractive","protected","readOnly"]);this.accessKey=e.accessKey||"";this.anchorType=getStringOption(e.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.layout=getStringOption(e.layout,["position","lr-tb","rl-row","rl-tb","row","table","tb"]);this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.bind=null;this.border=null;this.calculate=null;this.caption=null;this.desc=null;this.extras=null;this.margin=null;this.para=null;this.traversal=null;this.validate=null;this.connect=new XFAObjectArray;this.event=new XFAObjectArray;this.field=new XFAObjectArray;this.setProperty=new XFAObjectArray}[dr](){return!0}[hr](){return!0}[qr](e){for(const t of this.field.children){if(!t.value){const e=new Value({});t[Hs](e);t.value=e}t.value[qr](e)}}[wr](){return this.layout.endsWith("-tb")&&0===this[Xs].attempt&&this[Xs].numberInLine>0||this[Ir]()[wr]()}[yr](){const e=this[or]();if(!e[yr]())return!1;if(void 0!==this[Xs]._isSplittable)return this[Xs]._isSplittable;if("position"===this.layout||this.layout.includes("row")){this[Xs]._isSplittable=!1;return!1}if(e.layout?.endsWith("-tb")&&0!==e[Xs].numberInLine)return!1;this[Xs]._isSplittable=!0;return!0}[Vs](){return flushHTML(this)}[Ls](e,t){addHTML(this,e,t)}[$s](){return getAvailableSpace(this)}[jr](e){setTabIndex(this);if("hidden"===this.presence||"inactive"===this.presence||0===this.h||0===this.w)return HTMLResult.EMPTY;fixDimensions(this);const t=[],i={id:this[Vr],class:[]};setAccess(this,i.class);this[Xs]||(this[Xs]=Object.create(null));Object.assign(this[Xs],{children:t,attributes:i,attempt:0,line:null,numberInLine:0,availableSpace:{width:Math.min(this.w||1/0,e.width),height:Math.min(this.h||1/0,e.height)},width:0,height:0,prevHeight:0,currentWidth:0});const a=this[yr]();a||setFirstUnsplittable(this);if(!checkDimensions(this,e))return HTMLResult.FAILURE;const s=new Set(["field"]);if(this.layout.includes("row")){const e=this[or]().columnWidths;if(Array.isArray(e)&&e.length>0){this[Xs].columnWidths=e;this[Xs].currentColumn=0}}const r=toStyle(this,"anchorType","dimensions","position","presence","border","margin","hAlign"),n=["xfaExclgroup"],g=layoutClass(this);g&&n.push(g);isPrintOnly(this)&&n.push("xfaPrintOnly");i.style=r;i.class=n;this.name&&(i.xfaName=this.name);this[Lr]();const o="lr-tb"===this.layout||"rl-tb"===this.layout,c=o?2:1;for(;this[Xs].attempte>=1||-1===e});this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.locale=e.locale||"";this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.rotate=getInteger({data:e.rotate,defaultValue:0,validate:e=>e%90==0});this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.bind=null;this.border=null;this.calculate=null;this.caption=null;this.desc=null;this.extras=null;this.font=null;this.format=null;this.items=new XFAObjectArray(2);this.keep=null;this.margin=null;this.para=null;this.traversal=null;this.ui=null;this.validate=null;this.value=null;this.bindItems=new XFAObjectArray;this.connect=new XFAObjectArray;this.event=new XFAObjectArray;this.setProperty=new XFAObjectArray}[dr](){return!0}[qr](e){_setValue(this,e)}[jr](e){setTabIndex(this);if(!this.ui){this.ui=new Ui({});this.ui[Cr]=this[Cr];this[Hs](this.ui);let e;switch(this.items.children.length){case 0:e=new TextEdit({});this.ui.textEdit=e;break;case 1:e=new CheckButton({});this.ui.checkButton=e;break;case 2:e=new ChoiceList({});this.ui.choiceList=e}this.ui[Hs](e)}if(!this.ui||"hidden"===this.presence||"inactive"===this.presence||0===this.h||0===this.w)return HTMLResult.EMPTY;this.caption&&delete this.caption[Xs];this[Lr]();const t=this.caption?this.caption[jr](e).html:null,i=this.w,a=this.h;let s=0,r=0;if(this.margin){s=this.margin.leftInset+this.margin.rightInset;r=this.margin.topInset+this.margin.bottomInset}let n=null;if(""===this.w||""===this.h){let t=null,i=null,a=0,g=0;if(this.ui.checkButton)a=g=this.ui.checkButton.size;else{const{w:t,h:i}=layoutNode(this,e);if(null!==t){a=t;g=i}else g=function fonts_getMetrics(e,t=!1){let i=null;if(e){const t=stripQuotes(e.typeface),a=e[Cr].fontFinder.find(t);i=selectFont(e,a)}if(!i)return{lineHeight:12,lineGap:2,lineNoGap:10};const a=e.size||10,s=i.lineHeight?Math.max(t?0:1.2,i.lineHeight):1.2,r=void 0===i.lineGap?.2:i.lineGap;return{lineHeight:s*a,lineGap:r*a,lineNoGap:Math.max(1,s-r)*a}}(this.font,!0).lineNoGap}n=getBorderDims(this.ui[ar]());a+=n.w;g+=n.h;if(this.caption){const{w:s,h:r,isBroken:n}=this.caption[ar](e);if(n&&this[or]()[wr]()){this[xr]();return HTMLResult.FAILURE}t=s;i=r;switch(this.caption.placement){case"left":case"right":case"inline":t+=a;break;case"top":case"bottom":i+=g}}else{t=a;i=g}if(t&&""===this.w){t+=s;this.w=Math.min(this.maxW<=0?1/0:this.maxW,this.minW+1e>=1&&e<=5});this.appearanceFilter=null;this.certificates=null;this.digestMethods=null;this.encodings=null;this.encryptionMethods=null;this.handler=null;this.lockDocument=null;this.mdp=null;this.reasons=null;this.timeStamp=null}}class Float extends ContentObject{constructor(e){super(Nn,"float");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){const e=parseFloat(this[Os].trim());this[Os]=isNaN(e)?null:e}[jr](e){return valueToHtml(null!==this[Os]?this[Os].toString():"")}}class template_Font extends XFAObject{constructor(e){super(Nn,"font",!0);this.baselineShift=getMeasurement(e.baselineShift);this.fontHorizontalScale=getFloat({data:e.fontHorizontalScale,defaultValue:100,validate:e=>e>=0});this.fontVerticalScale=getFloat({data:e.fontVerticalScale,defaultValue:100,validate:e=>e>=0});this.id=e.id||"";this.kerningMode=getStringOption(e.kerningMode,["none","pair"]);this.letterSpacing=getMeasurement(e.letterSpacing,"0");this.lineThrough=getInteger({data:e.lineThrough,defaultValue:0,validate:e=>1===e||2===e});this.lineThroughPeriod=getStringOption(e.lineThroughPeriod,["all","word"]);this.overline=getInteger({data:e.overline,defaultValue:0,validate:e=>1===e||2===e});this.overlinePeriod=getStringOption(e.overlinePeriod,["all","word"]);this.posture=getStringOption(e.posture,["normal","italic"]);this.size=getMeasurement(e.size,"10pt");this.typeface=e.typeface||"Courier";this.underline=getInteger({data:e.underline,defaultValue:0,validate:e=>1===e||2===e});this.underlinePeriod=getStringOption(e.underlinePeriod,["all","word"]);this.use=e.use||"";this.usehref=e.usehref||"";this.weight=getStringOption(e.weight,["normal","bold"]);this.extras=null;this.fill=null}[Ys](e){super[Ys](e);this[Cr].usedTypefaces.add(this.typeface)}[Zr](){const e=toStyle(this,"fill"),t=e.color;if(t)if("#000000"===t)delete e.color;else if(!t.startsWith("#")){e.background=t;e.backgroundClip="text";e.color="transparent"}this.baselineShift&&(e.verticalAlign=measureToString(this.baselineShift));e.fontKerning="none"===this.kerningMode?"none":"normal";e.letterSpacing=measureToString(this.letterSpacing);if(0!==this.lineThrough){e.textDecoration="line-through";2===this.lineThrough&&(e.textDecorationStyle="double")}if(0!==this.overline){e.textDecoration="overline";2===this.overline&&(e.textDecorationStyle="double")}e.fontStyle=this.posture;e.fontSize=measureToString(.99*this.size);setFontFamily(this,this,this[Cr].fontFinder,e);if(0!==this.underline){e.textDecoration="underline";2===this.underline&&(e.textDecorationStyle="double")}e.fontWeight=this.weight;return e}}class Format extends XFAObject{constructor(e){super(Nn,"format",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.picture=null}}class Handler extends StringObject{constructor(e){super(Nn,"handler");this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Hyphenation extends XFAObject{constructor(e){super(Nn,"hyphenation");this.excludeAllCaps=getInteger({data:e.excludeAllCaps,defaultValue:0,validate:e=>1===e});this.excludeInitialCap=getInteger({data:e.excludeInitialCap,defaultValue:0,validate:e=>1===e});this.hyphenate=getInteger({data:e.hyphenate,defaultValue:0,validate:e=>1===e});this.id=e.id||"";this.pushCharacterCount=getInteger({data:e.pushCharacterCount,defaultValue:3,validate:e=>e>=0});this.remainCharacterCount=getInteger({data:e.remainCharacterCount,defaultValue:3,validate:e=>e>=0});this.use=e.use||"";this.usehref=e.usehref||"";this.wordCharacterCount=getInteger({data:e.wordCharacterCount,defaultValue:7,validate:e=>e>=0})}}class Image extends StringObject{constructor(e){super(Nn,"image");this.aspect=getStringOption(e.aspect,["fit","actual","height","none","width"]);this.contentType=e.contentType||"";this.href=e.href||"";this.id=e.id||"";this.name=e.name||"";this.transferEncoding=getStringOption(e.transferEncoding,["base64","none","package"]);this.use=e.use||"";this.usehref=e.usehref||""}[jr](){if(this.contentType&&!Un.has(this.contentType.toLowerCase()))return HTMLResult.EMPTY;let e=this[Cr].images&&this[Cr].images.get(this.href);if(!e&&(this.href||!this[Os]))return HTMLResult.EMPTY;e||"base64"!==this.transferEncoding||(e=function fromBase64Util(e){return Uint8Array.fromBase64?Uint8Array.fromBase64(e):stringToBytes(atob(e))}(this[Os]));if(!e)return HTMLResult.EMPTY;if(!this.contentType){for(const[t,i]of xn)if(e.length>t.length&&t.every(((t,i)=>t===e[i]))){this.contentType=i;break}if(!this.contentType)return HTMLResult.EMPTY}const t=new Blob([e],{type:this.contentType});let i;switch(this.aspect){case"fit":case"actual":break;case"height":i={height:"100%",objectFit:"fill"};break;case"none":i={width:"100%",height:"100%",objectFit:"fill"};break;case"width":i={width:"100%",objectFit:"fill"}}const a=this[Ir]();return HTMLResult.success({name:"img",attributes:{class:["xfaImage"],style:i,src:URL.createObjectURL(t),alt:a?ariaLabel(a[Ir]()):null}})}}class ImageEdit extends XFAObject{constructor(e){super(Nn,"imageEdit",!0);this.data=getStringOption(e.data,["link","embed"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}[jr](e){return"embed"===this.data?HTMLResult.success({name:"div",children:[],attributes:{}}):HTMLResult.EMPTY}}class Integer extends ContentObject{constructor(e){super(Nn,"integer");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){const e=parseInt(this[Os].trim(),10);this[Os]=isNaN(e)?null:e}[jr](e){return valueToHtml(null!==this[Os]?this[Os].toString():"")}}class Issuers extends XFAObject{constructor(e){super(Nn,"issuers",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=new XFAObjectArray}}class Items extends XFAObject{constructor(e){super(Nn,"items",!0);this.id=e.id||"";this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.ref=e.ref||"";this.save=getInteger({data:e.save,defaultValue:0,validate:e=>1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}[jr](){const e=[];for(const t of this[rr]())e.push(t[Pr]());return HTMLResult.success(e)}}class Keep extends XFAObject{constructor(e){super(Nn,"keep",!0);this.id=e.id||"";const t=["none","contentArea","pageArea"];this.intact=getStringOption(e.intact,t);this.next=getStringOption(e.next,t);this.previous=getStringOption(e.previous,t);this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}}class KeyUsage extends XFAObject{constructor(e){super(Nn,"keyUsage");const t=["","yes","no"];this.crlSign=getStringOption(e.crlSign,t);this.dataEncipherment=getStringOption(e.dataEncipherment,t);this.decipherOnly=getStringOption(e.decipherOnly,t);this.digitalSignature=getStringOption(e.digitalSignature,t);this.encipherOnly=getStringOption(e.encipherOnly,t);this.id=e.id||"";this.keyAgreement=getStringOption(e.keyAgreement,t);this.keyCertSign=getStringOption(e.keyCertSign,t);this.keyEncipherment=getStringOption(e.keyEncipherment,t);this.nonRepudiation=getStringOption(e.nonRepudiation,t);this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Line extends XFAObject{constructor(e){super(Nn,"line",!0);this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.slope=getStringOption(e.slope,["\\","/"]);this.use=e.use||"";this.usehref=e.usehref||"";this.edge=null}[jr](){const e=this[Ir]()[Ir](),t=this.edge||new Edge({}),i=t[Zr](),a=Object.create(null),s="visible"===t.presence?t.thickness:0;a.strokeWidth=measureToString(s);a.stroke=i.color;let r,n,g,o,c="100%",C="100%";if(e.w<=s){[r,n,g,o]=["50%",0,"50%","100%"];c=a.strokeWidth}else if(e.h<=s){[r,n,g,o]=[0,"50%","100%","50%"];C=a.strokeWidth}else"\\"===this.slope?[r,n,g,o]=[0,0,"100%","100%"]:[r,n,g,o]=[0,"100%","100%",0];const h={name:"svg",children:[{name:"line",attributes:{xmlns:Gn,x1:r,y1:n,x2:g,y2:o,style:a}}],attributes:{xmlns:Gn,width:c,height:C,style:{overflow:"visible"}}};if(hasMargin(e))return HTMLResult.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[h]});h.attributes.style.position="absolute";return HTMLResult.success(h)}}class Linear extends XFAObject{constructor(e){super(Nn,"linear",!0);this.id=e.id||"";this.type=getStringOption(e.type,["toRight","toBottom","toLeft","toTop"]);this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zr](e){e=e?e[Zr]():"#FFFFFF";return`linear-gradient(${this.type.replace(/([RBLT])/," $1").toLowerCase()}, ${e}, ${this.color?this.color[Zr]():"#000000"})`}}class LockDocument extends ContentObject{constructor(e){super(Nn,"lockDocument");this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){this[Os]=getStringOption(this[Os],["auto","0","1"])}}class Manifest extends XFAObject{constructor(e){super(Nn,"manifest",!0);this.action=getStringOption(e.action,["include","all","exclude"]);this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.ref=new XFAObjectArray}}class Margin extends XFAObject{constructor(e){super(Nn,"margin",!0);this.bottomInset=getMeasurement(e.bottomInset,"0");this.id=e.id||"";this.leftInset=getMeasurement(e.leftInset,"0");this.rightInset=getMeasurement(e.rightInset,"0");this.topInset=getMeasurement(e.topInset,"0");this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[Zr](){return{margin:measureToString(this.topInset)+" "+measureToString(this.rightInset)+" "+measureToString(this.bottomInset)+" "+measureToString(this.leftInset)}}}class Mdp extends XFAObject{constructor(e){super(Nn,"mdp");this.id=e.id||"";this.permissions=getInteger({data:e.permissions,defaultValue:2,validate:e=>1===e||3===e});this.signatureType=getStringOption(e.signatureType,["filler","author"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Medium extends XFAObject{constructor(e){super(Nn,"medium");this.id=e.id||"";this.imagingBBox=function getBBox(e){const t=-1;if(!e)return{x:t,y:t,width:t,height:t};const i=e.trim().split(/\s*,\s*/).map((e=>getMeasurement(e,"-1")));if(i.length<4||i[2]<0||i[3]<0)return{x:t,y:t,width:t,height:t};const[a,s,r,n]=i;return{x:a,y:s,width:r,height:n}}(e.imagingBBox);this.long=getMeasurement(e.long);this.orientation=getStringOption(e.orientation,["portrait","landscape"]);this.short=getMeasurement(e.short);this.stock=e.stock||"";this.trayIn=getStringOption(e.trayIn,["auto","delegate","pageFront"]);this.trayOut=getStringOption(e.trayOut,["auto","delegate"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Message extends XFAObject{constructor(e){super(Nn,"message",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.text=new XFAObjectArray}}class NumericEdit extends XFAObject{constructor(e){super(Nn,"numericEdit",!0);this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.comb=null;this.extras=null;this.margin=null}[jr](e){const t=toStyle(this,"border","font","margin"),i=this[Ir]()[Ir](),a={name:"input",attributes:{type:"text",fieldId:i[Vr],dataId:i[Ws]?.[Vr]||i[Vr],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(i),"aria-required":!1}};if(isRequired(i)){a.attributes["aria-required"]=!0;a.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[a]})}}class Occur extends XFAObject{constructor(e){super(Nn,"occur",!0);this.id=e.id||"";this.initial=""!==e.initial?getInteger({data:e.initial,defaultValue:"",validate:e=>!0}):"";this.max=""!==e.max?getInteger({data:e.max,defaultValue:1,validate:e=>!0}):"";this.min=""!==e.min?getInteger({data:e.min,defaultValue:1,validate:e=>!0}):"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[Ys](){const e=this[Ir](),t=this.min;""===this.min&&(this.min=e instanceof PageArea||e instanceof PageSet?0:1);""===this.max&&(this.max=""===t?e instanceof PageArea||e instanceof PageSet?-1:1:this.min);-1!==this.max&&this.max!0});this.name=e.name||"";this.numbered=getInteger({data:e.numbered,defaultValue:1,validate:e=>!0});this.oddOrEven=getStringOption(e.oddOrEven,["any","even","odd"]);this.pagePosition=getStringOption(e.pagePosition,["any","first","last","only","rest"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.desc=null;this.extras=null;this.medium=null;this.occur=null;this.area=new XFAObjectArray;this.contentArea=new XFAObjectArray;this.draw=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.field=new XFAObjectArray;this.subform=new XFAObjectArray}[br](){if(!this[Xs]){this[Xs]={numberOfUse:0};return!0}return!this.occur||-1===this.occur.max||this[Xs].numberOfUsee.oddOrEven===t&&e.pagePosition===i));if(a)return a;a=this.pageArea.children.find((e=>"any"===e.oddOrEven&&e.pagePosition===i));if(a)return a;a=this.pageArea.children.find((e=>"any"===e.oddOrEven&&"any"===e.pagePosition));return a||this.pageArea.children[0]}}class Para extends XFAObject{constructor(e){super(Nn,"para",!0);this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.lineHeight=e.lineHeight?getMeasurement(e.lineHeight,"0pt"):"";this.marginLeft=e.marginLeft?getMeasurement(e.marginLeft,"0pt"):"";this.marginRight=e.marginRight?getMeasurement(e.marginRight,"0pt"):"";this.orphans=getInteger({data:e.orphans,defaultValue:0,validate:e=>e>=0});this.preserve=e.preserve||"";this.radixOffset=e.radixOffset?getMeasurement(e.radixOffset,"0pt"):"";this.spaceAbove=e.spaceAbove?getMeasurement(e.spaceAbove,"0pt"):"";this.spaceBelow=e.spaceBelow?getMeasurement(e.spaceBelow,"0pt"):"";this.tabDefault=e.tabDefault?getMeasurement(this.tabDefault):"";this.tabStops=(e.tabStops||"").trim().split(/\s+/).map(((e,t)=>t%2==1?getMeasurement(e):e));this.textIndent=e.textIndent?getMeasurement(e.textIndent,"0pt"):"";this.use=e.use||"";this.usehref=e.usehref||"";this.vAlign=getStringOption(e.vAlign,["top","bottom","middle"]);this.widows=getInteger({data:e.widows,defaultValue:0,validate:e=>e>=0});this.hyphenation=null}[Zr](){const e=toStyle(this,"hAlign");""!==this.marginLeft&&(e.paddingLeft=measureToString(this.marginLeft));""!==this.marginRight&&(e.paddingRight=measureToString(this.marginRight));""!==this.spaceAbove&&(e.paddingTop=measureToString(this.spaceAbove));""!==this.spaceBelow&&(e.paddingBottom=measureToString(this.spaceBelow));if(""!==this.textIndent){e.textIndent=measureToString(this.textIndent);fixTextIndent(e)}this.lineHeight>0&&(e.lineHeight=measureToString(this.lineHeight));""!==this.tabDefault&&(e.tabSize=measureToString(this.tabDefault));this.tabStops.length;this.hyphenatation&&Object.assign(e,this.hyphenatation[Zr]());return e}}class PasswordEdit extends XFAObject{constructor(e){super(Nn,"passwordEdit",!0);this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.passwordChar=e.passwordChar||"*";this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}}class template_Pattern extends XFAObject{constructor(e){super(Nn,"pattern",!0);this.id=e.id||"";this.type=getStringOption(e.type,["crossHatch","crossDiagonal","diagonalLeft","diagonalRight","horizontal","vertical"]);this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zr](e){e=e?e[Zr]():"#FFFFFF";const t=this.color?this.color[Zr]():"#000000",i="repeating-linear-gradient",a=`${e},${e} 5px,${t} 5px,${t} 10px`;switch(this.type){case"crossHatch":return`${i}(to top,${a}) ${i}(to right,${a})`;case"crossDiagonal":return`${i}(45deg,${a}) ${i}(-45deg,${a})`;case"diagonalLeft":return`${i}(45deg,${a})`;case"diagonalRight":return`${i}(-45deg,${a})`;case"horizontal":return`${i}(to top,${a})`;case"vertical":return`${i}(to right,${a})`}return""}}class Picture extends StringObject{constructor(e){super(Nn,"picture");this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Proto extends XFAObject{constructor(e){super(Nn,"proto",!0);this.appearanceFilter=new XFAObjectArray;this.arc=new XFAObjectArray;this.area=new XFAObjectArray;this.assist=new XFAObjectArray;this.barcode=new XFAObjectArray;this.bindItems=new XFAObjectArray;this.bookend=new XFAObjectArray;this.boolean=new XFAObjectArray;this.border=new XFAObjectArray;this.break=new XFAObjectArray;this.breakAfter=new XFAObjectArray;this.breakBefore=new XFAObjectArray;this.button=new XFAObjectArray;this.calculate=new XFAObjectArray;this.caption=new XFAObjectArray;this.certificate=new XFAObjectArray;this.certificates=new XFAObjectArray;this.checkButton=new XFAObjectArray;this.choiceList=new XFAObjectArray;this.color=new XFAObjectArray;this.comb=new XFAObjectArray;this.connect=new XFAObjectArray;this.contentArea=new XFAObjectArray;this.corner=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.dateTimeEdit=new XFAObjectArray;this.decimal=new XFAObjectArray;this.defaultUi=new XFAObjectArray;this.desc=new XFAObjectArray;this.digestMethod=new XFAObjectArray;this.digestMethods=new XFAObjectArray;this.draw=new XFAObjectArray;this.edge=new XFAObjectArray;this.encoding=new XFAObjectArray;this.encodings=new XFAObjectArray;this.encrypt=new XFAObjectArray;this.encryptData=new XFAObjectArray;this.encryption=new XFAObjectArray;this.encryptionMethod=new XFAObjectArray;this.encryptionMethods=new XFAObjectArray;this.event=new XFAObjectArray;this.exData=new XFAObjectArray;this.exObject=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.execute=new XFAObjectArray;this.extras=new XFAObjectArray;this.field=new XFAObjectArray;this.fill=new XFAObjectArray;this.filter=new XFAObjectArray;this.float=new XFAObjectArray;this.font=new XFAObjectArray;this.format=new XFAObjectArray;this.handler=new XFAObjectArray;this.hyphenation=new XFAObjectArray;this.image=new XFAObjectArray;this.imageEdit=new XFAObjectArray;this.integer=new XFAObjectArray;this.issuers=new XFAObjectArray;this.items=new XFAObjectArray;this.keep=new XFAObjectArray;this.keyUsage=new XFAObjectArray;this.line=new XFAObjectArray;this.linear=new XFAObjectArray;this.lockDocument=new XFAObjectArray;this.manifest=new XFAObjectArray;this.margin=new XFAObjectArray;this.mdp=new XFAObjectArray;this.medium=new XFAObjectArray;this.message=new XFAObjectArray;this.numericEdit=new XFAObjectArray;this.occur=new XFAObjectArray;this.oid=new XFAObjectArray;this.oids=new XFAObjectArray;this.overflow=new XFAObjectArray;this.pageArea=new XFAObjectArray;this.pageSet=new XFAObjectArray;this.para=new XFAObjectArray;this.passwordEdit=new XFAObjectArray;this.pattern=new XFAObjectArray;this.picture=new XFAObjectArray;this.radial=new XFAObjectArray;this.reason=new XFAObjectArray;this.reasons=new XFAObjectArray;this.rectangle=new XFAObjectArray;this.ref=new XFAObjectArray;this.script=new XFAObjectArray;this.setProperty=new XFAObjectArray;this.signData=new XFAObjectArray;this.signature=new XFAObjectArray;this.signing=new XFAObjectArray;this.solid=new XFAObjectArray;this.speak=new XFAObjectArray;this.stipple=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray;this.subjectDN=new XFAObjectArray;this.subjectDNs=new XFAObjectArray;this.submit=new XFAObjectArray;this.text=new XFAObjectArray;this.textEdit=new XFAObjectArray;this.time=new XFAObjectArray;this.timeStamp=new XFAObjectArray;this.toolTip=new XFAObjectArray;this.traversal=new XFAObjectArray;this.traverse=new XFAObjectArray;this.ui=new XFAObjectArray;this.validate=new XFAObjectArray;this.value=new XFAObjectArray;this.variables=new XFAObjectArray}}class Radial extends XFAObject{constructor(e){super(Nn,"radial",!0);this.id=e.id||"";this.type=getStringOption(e.type,["toEdge","toCenter"]);this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zr](e){e=e?e[Zr]():"#FFFFFF";const t=this.color?this.color[Zr]():"#000000";return`radial-gradient(circle at center, ${"toEdge"===this.type?`${e},${t}`:`${t},${e}`})`}}class Reason extends StringObject{constructor(e){super(Nn,"reason");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Reasons extends XFAObject{constructor(e){super(Nn,"reasons",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.reason=new XFAObjectArray}}class Rectangle extends XFAObject{constructor(e){super(Nn,"rectangle",!0);this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.corner=new XFAObjectArray(4);this.edge=new XFAObjectArray(4);this.fill=null}[jr](){const e=this.edge.children.length?this.edge.children[0]:new Edge({}),t=e[Zr](),i=Object.create(null);"visible"===this.fill?.presence?Object.assign(i,this.fill[Zr]()):i.fill="transparent";i.strokeWidth=measureToString("visible"===e.presence?e.thickness:0);i.stroke=t.color;const a=(this.corner.children.length?this.corner.children[0]:new Corner({}))[Zr](),s={name:"svg",children:[{name:"rect",attributes:{xmlns:Gn,width:"100%",height:"100%",x:0,y:0,rx:a.radius,ry:a.radius,style:i}}],attributes:{xmlns:Gn,style:{overflow:"visible"},width:"100%",height:"100%"}};if(hasMargin(this[Ir]()[Ir]()))return HTMLResult.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[s]});s.attributes.style.position="absolute";return HTMLResult.success(s)}}class RefElement extends StringObject{constructor(e){super(Nn,"ref");this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Script extends StringObject{constructor(e){super(Nn,"script");this.binding=e.binding||"";this.contentType=e.contentType||"";this.id=e.id||"";this.name=e.name||"";this.runAt=getStringOption(e.runAt,["client","both","server"]);this.use=e.use||"";this.usehref=e.usehref||""}}class SetProperty extends XFAObject{constructor(e){super(Nn,"setProperty");this.connection=e.connection||"";this.ref=e.ref||"";this.target=e.target||""}}class SignData extends XFAObject{constructor(e){super(Nn,"signData",!0);this.id=e.id||"";this.operation=getStringOption(e.operation,["sign","clear","verify"]);this.ref=e.ref||"";this.target=e.target||"";this.use=e.use||"";this.usehref=e.usehref||"";this.filter=null;this.manifest=null}}class Signature extends XFAObject{constructor(e){super(Nn,"signature",!0);this.id=e.id||"";this.type=getStringOption(e.type,["PDF1.3","PDF1.6"]);this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.filter=null;this.manifest=null;this.margin=null}}class Signing extends XFAObject{constructor(e){super(Nn,"signing",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=new XFAObjectArray}}class Solid extends XFAObject{constructor(e){super(Nn,"solid",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[Zr](e){return e?e[Zr]():"#FFFFFF"}}class Speak extends StringObject{constructor(e){super(Nn,"speak");this.disable=getInteger({data:e.disable,defaultValue:0,validate:e=>1===e});this.id=e.id||"";this.priority=getStringOption(e.priority,["custom","caption","name","toolTip"]);this.rid=e.rid||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Stipple extends XFAObject{constructor(e){super(Nn,"stipple",!0);this.id=e.id||"";this.rate=getInteger({data:e.rate,defaultValue:50,validate:e=>e>=0&&e<=100});this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zr](e){const t=this.rate/100;return Util.makeHexColor(Math.round(e.value.r*(1-t)+this.value.r*t),Math.round(e.value.g*(1-t)+this.value.g*t),Math.round(e.value.b*(1-t)+this.value.b*t))}}class Subform extends XFAObject{constructor(e){super(Nn,"subform",!0);this.access=getStringOption(e.access,["open","nonInteractive","protected","readOnly"]);this.allowMacro=getInteger({data:e.allowMacro,defaultValue:0,validate:e=>1===e});this.anchorType=getStringOption(e.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.columnWidths=(e.columnWidths||"").trim().split(/\s+/).map((e=>"-1"===e?-1:getMeasurement(e)));this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.layout=getStringOption(e.layout,["position","lr-tb","rl-row","rl-tb","row","table","tb"]);this.locale=e.locale||"";this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.mergeMode=getStringOption(e.mergeMode,["consumeData","matchTemplate"]);this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.restoreState=getStringOption(e.restoreState,["manual","auto"]);this.scope=getStringOption(e.scope,["name","none"]);this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.bind=null;this.bookend=null;this.border=null;this.break=null;this.calculate=null;this.desc=null;this.extras=null;this.keep=null;this.margin=null;this.occur=null;this.overflow=null;this.pageSet=null;this.para=null;this.traversal=null;this.validate=null;this.variables=null;this.area=new XFAObjectArray;this.breakAfter=new XFAObjectArray;this.breakBefore=new XFAObjectArray;this.connect=new XFAObjectArray;this.draw=new XFAObjectArray;this.event=new XFAObjectArray;this.exObject=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.field=new XFAObjectArray;this.proto=new XFAObjectArray;this.setProperty=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray}[or](){const e=this[Ir]();return e instanceof SubformSet?e[or]():e}[dr](){return!0}[wr](){return this.layout.endsWith("-tb")&&0===this[Xs].attempt&&this[Xs].numberInLine>0||this[Ir]()[wr]()}*[nr](){yield*getContainedChildren(this)}[Vs](){return flushHTML(this)}[Ls](e,t){addHTML(this,e,t)}[$s](){return getAvailableSpace(this)}[yr](){const e=this[or]();if(!e[yr]())return!1;if(void 0!==this[Xs]._isSplittable)return this[Xs]._isSplittable;if("position"===this.layout||this.layout.includes("row")){this[Xs]._isSplittable=!1;return!1}if(this.keep&&"none"!==this.keep.intact){this[Xs]._isSplittable=!1;return!1}if(e.layout?.endsWith("-tb")&&0!==e[Xs].numberInLine)return!1;this[Xs]._isSplittable=!0;return!0}[jr](e){setTabIndex(this);if(this.break){if("auto"!==this.break.after||""!==this.break.afterTarget){const e=new BreakAfter({targetType:this.break.after,target:this.break.afterTarget,startNew:this.break.startNew.toString()});e[Cr]=this[Cr];this[Hs](e);this.breakAfter.push(e)}if("auto"!==this.break.before||""!==this.break.beforeTarget){const e=new BreakBefore({targetType:this.break.before,target:this.break.beforeTarget,startNew:this.break.startNew.toString()});e[Cr]=this[Cr];this[Hs](e);this.breakBefore.push(e)}if(""!==this.break.overflowTarget){const e=new Overflow({target:this.break.overflowTarget,leader:this.break.overflowLeader,trailer:this.break.overflowTrailer});e[Cr]=this[Cr];this[Hs](e);this.overflow.push(e)}this[Hr](this.break);this.break=null}if("hidden"===this.presence||"inactive"===this.presence)return HTMLResult.EMPTY;(this.breakBefore.children.length>1||this.breakAfter.children.length>1)&&warn("XFA - Several breakBefore or breakAfter in subforms: please file a bug.");if(this.breakBefore.children.length>=1){const e=this.breakBefore.children[0];if(handleBreak(e))return HTMLResult.breakNode(e)}if(this[Xs]?.afterBreakAfter)return HTMLResult.EMPTY;fixDimensions(this);const t=[],i={id:this[Vr],class:[]};setAccess(this,i.class);this[Xs]||(this[Xs]=Object.create(null));Object.assign(this[Xs],{children:t,line:null,attributes:i,attempt:0,numberInLine:0,availableSpace:{width:Math.min(this.w||1/0,e.width),height:Math.min(this.h||1/0,e.height)},width:0,height:0,prevHeight:0,currentWidth:0});const a=this[cr](),s=a[Xs].noLayoutFailure,r=this[yr]();r||setFirstUnsplittable(this);if(!checkDimensions(this,e))return HTMLResult.FAILURE;const n=new Set(["area","draw","exclGroup","field","subform","subformSet"]);if(this.layout.includes("row")){const e=this[or]().columnWidths;if(Array.isArray(e)&&e.length>0){this[Xs].columnWidths=e;this[Xs].currentColumn=0}}const g=toStyle(this,"anchorType","dimensions","position","presence","border","margin","hAlign"),o=["xfaSubform"],c=layoutClass(this);c&&o.push(c);i.style=g;i.class=o;this.name&&(i.xfaName=this.name);if(this.overflow){const t=this.overflow[ar]();if(t.addLeader){t.addLeader=!1;handleOverflow(this,t.leader,e)}}this[Lr]();const C="lr-tb"===this.layout||"rl-tb"===this.layout,h=C?2:1;for(;this[Xs].attempt=1){const e=this.breakAfter.children[0];if(handleBreak(e)){this[Xs].afterBreakAfter=p;return HTMLResult.breakNode(e)}}delete this[Xs];return p}}class SubformSet extends XFAObject{constructor(e){super(Nn,"subformSet",!0);this.id=e.id||"";this.name=e.name||"";this.relation=getStringOption(e.relation,["ordered","choice","unordered"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.bookend=null;this.break=null;this.desc=null;this.extras=null;this.occur=null;this.overflow=null;this.breakAfter=new XFAObjectArray;this.breakBefore=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray}*[nr](){yield*getContainedChildren(this)}[or](){let e=this[Ir]();for(;!(e instanceof Subform);)e=e[Ir]();return e}[dr](){return!0}}class SubjectDN extends ContentObject{constructor(e){super(Nn,"subjectDN");this.delimiter=e.delimiter||",";this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){this[Os]=new Map(this[Os].split(this.delimiter).map((e=>{(e=e.split("=",2))[0]=e[0].trim();return e})))}}class SubjectDNs extends XFAObject{constructor(e){super(Nn,"subjectDNs",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.subjectDN=new XFAObjectArray}}class Submit extends XFAObject{constructor(e){super(Nn,"submit",!0);this.embedPDF=getInteger({data:e.embedPDF,defaultValue:0,validate:e=>1===e});this.format=getStringOption(e.format,["xdp","formdata","pdf","urlencoded","xfd","xml"]);this.id=e.id||"";this.target=e.target||"";this.textEncoding=getKeyword({data:e.textEncoding?e.textEncoding.toLowerCase():"",defaultValue:"",validate:e=>["utf-8","big-five","fontspecific","gbk","gb-18030","gb-2312","ksc-5601","none","shift-jis","ucs-2","utf-16"].includes(e)||e.match(/iso-8859-\d{2}/)});this.use=e.use||"";this.usehref=e.usehref||"";this.xdpContent=e.xdpContent||"";this.encrypt=null;this.encryptData=new XFAObjectArray;this.signData=new XFAObjectArray}}class Template extends XFAObject{constructor(e){super(Nn,"template",!0);this.baseProfile=getStringOption(e.baseProfile,["full","interactiveForms"]);this.extras=null;this.subform=new XFAObjectArray}[Zs](){0===this.subform.children.length&&warn("XFA - No subforms in template node.");this.subform.children.length>=2&&warn("XFA - Several subforms in template node: please file a bug.");this[Or]=5e3}[yr](){return!0}[vr](e,t){return e.startsWith("#")?[this[lr].get(e.slice(1))]:searchNode(this,t,e,!0,!0)}*[Wr](){if(!this.subform.children.length)return HTMLResult.success({name:"div",children:[]});this[Xs]={overflowNode:null,firstUnsplittable:null,currentContentArea:null,currentPageArea:null,noLayoutFailure:!1,pageNumber:1,pagePosition:"first",oddOrEven:"odd",blankOrNotBlank:"nonBlank",paraStack:[]};const e=this.subform.children[0];e.pageSet[vs]();const t=e.pageSet.pageArea.children,i={name:"div",children:[]};let a=null,s=null,r=null;if(e.breakBefore.children.length>=1){s=e.breakBefore.children[0];r=s.target}else if(e.subform.children.length>=1&&e.subform.children[0].breakBefore.children.length>=1){s=e.subform.children[0].breakBefore.children[0];r=s.target}else if(e.break?.beforeTarget){s=e.break;r=s.beforeTarget}else if(e.subform.children.length>=1&&e.subform.children[0].break?.beforeTarget){s=e.subform.children[0].break;r=s.beforeTarget}if(s){const e=this[vr](r,s[Ir]());if(e instanceof PageArea){a=e;s[Xs]={}}}a||(a=t[0]);a[Xs]={numberOfUse:1};const n=a[Ir]();n[Xs]={numberOfUse:1,pageIndex:n.pageArea.children.indexOf(a),pageSetIndex:0};let g,o=null,c=null,C=!0,h=0,l=0;for(;;){if(C)h=0;else{i.children.pop();if(3==++h){warn("XFA - Something goes wrong: please file a bug.");return i}}g=null;this[Xs].currentPageArea=a;const t=a[jr]().html;i.children.push(t);if(o){this[Xs].noLayoutFailure=!0;t.children.push(o[jr](a[Xs].space).html);o=null}if(c){this[Xs].noLayoutFailure=!0;t.children.push(c[jr](a[Xs].space).html);c=null}const s=a.contentArea.children,r=t.children.filter((e=>e.attributes.class.includes("xfaContentarea")));C=!1;this[Xs].firstUnsplittable=null;this[Xs].noLayoutFailure=!1;const flush=t=>{const i=e[Vs]();if(i){C||=i.children?.length>0;r[t].children.push(i)}};for(let t=l,a=s.length;t0;r[t].children.push(h.html)}else!C&&i.children.length>1&&i.children.pop();return i}if(h.isBreak()){const e=h.breakNode;flush(t);if("auto"===e.targetType)continue;if(e.leader){o=this[vr](e.leader,e[Ir]());o=o?o[0]:null}if(e.trailer){c=this[vr](e.trailer,e[Ir]());c=c?c[0]:null}if("pageArea"===e.targetType){g=e[Xs].target;t=1/0}else if(e[Xs].target){g=e[Xs].target;l=e[Xs].index+1;t=1/0}else t=e[Xs].index}else if(this[Xs].overflowNode){const e=this[Xs].overflowNode;this[Xs].overflowNode=null;const i=e[ar](),a=i.target;i.addLeader=null!==i.leader;i.addTrailer=null!==i.trailer;flush(t);const r=t;t=1/0;if(a instanceof PageArea)g=a;else if(a instanceof ContentArea){const e=s.indexOf(a);if(-1!==e)e>r?t=e-1:l=e;else{g=a[Ir]();l=g.contentArea.children.indexOf(a)}}}else flush(t)}this[Xs].pageNumber+=1;g&&(g[br]()?g[Xs].numberOfUse+=1:g=null);a=g||a[gr]();yield null}}}class Text extends ContentObject{constructor(e){super(Nn,"text");this.id=e.id||"";this.maxChars=getInteger({data:e.maxChars,defaultValue:0,validate:e=>e>=0});this.name=e.name||"";this.rid=e.rid||"";this.use=e.use||"";this.usehref=e.usehref||""}[xs](){return!0}[Nr](e){if(e[Sr]===_r.xhtml.id){this[Os]=e;return!0}warn(`XFA - Invalid content in Text: ${e[kr]}.`);return!1}[Mr](e){this[Os]instanceof XFAObject||super[Mr](e)}[Zs](){"string"==typeof this[Os]&&(this[Os]=this[Os].replaceAll("\r\n","\n"))}[ar](){return"string"==typeof this[Os]?this[Os].split(/[\u2029\u2028\n]/).reduce(((e,t)=>{t&&e.push(t);return e}),[]).join("\n"):this[Os][Pr]()}[jr](e){if("string"==typeof this[Os]){const e=valueToHtml(this[Os]).html;if(this[Os].includes("\u2029")){e.name="div";e.children=[];this[Os].split("\u2029").map((e=>e.split(/[\u2028\n]/).reduce(((e,t)=>{e.push({name:"span",value:t},{name:"br"});return e}),[]))).forEach((t=>{e.children.push({name:"p",children:t})}))}else if(/[\u2028\n]/.test(this[Os])){e.name="div";e.children=[];this[Os].split(/[\u2028\n]/).forEach((t=>{e.children.push({name:"span",value:t},{name:"br"})}))}return HTMLResult.success(e)}return this[Os][jr](e)}}class TextEdit extends XFAObject{constructor(e){super(Nn,"textEdit",!0);this.allowRichText=getInteger({data:e.allowRichText,defaultValue:0,validate:e=>1===e});this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.multiLine=getInteger({data:e.multiLine,defaultValue:"",validate:e=>0===e||1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.vScrollPolicy=getStringOption(e.vScrollPolicy,["auto","off","on"]);this.border=null;this.comb=null;this.extras=null;this.margin=null}[jr](e){const t=toStyle(this,"border","font","margin");let i;const a=this[Ir]()[Ir]();""===this.multiLine&&(this.multiLine=a instanceof Draw?1:0);i=1===this.multiLine?{name:"textarea",attributes:{dataId:a[Ws]?.[Vr]||a[Vr],fieldId:a[Vr],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(a),"aria-required":!1}}:{name:"input",attributes:{type:"text",dataId:a[Ws]?.[Vr]||a[Vr],fieldId:a[Vr],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(a),"aria-required":!1}};if(isRequired(a)){i.attributes["aria-required"]=!0;i.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[i]})}}class Time extends StringObject{constructor(e){super(Nn,"time");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){const e=this[Os].trim();this[Os]=e?new Date(e):null}[jr](e){return valueToHtml(this[Os]?this[Os].toString():"")}}class TimeStamp extends XFAObject{constructor(e){super(Nn,"timeStamp");this.id=e.id||"";this.server=e.server||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class ToolTip extends StringObject{constructor(e){super(Nn,"toolTip");this.id=e.id||"";this.rid=e.rid||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Traversal extends XFAObject{constructor(e){super(Nn,"traversal",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.traverse=new XFAObjectArray}}class Traverse extends XFAObject{constructor(e){super(Nn,"traverse",!0);this.id=e.id||"";this.operation=getStringOption(e.operation,["next","back","down","first","left","right","up"]);this.ref=e.ref||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.script=null}get name(){return this.operation}[Dr](){return!1}}class Ui extends XFAObject{constructor(e){super(Nn,"ui",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.picture=null;this.barcode=null;this.button=null;this.checkButton=null;this.choiceList=null;this.dateTimeEdit=null;this.defaultUi=null;this.imageEdit=null;this.numericEdit=null;this.passwordEdit=null;this.signature=null;this.textEdit=null}[ar](){if(void 0===this[Xs]){for(const e of Object.getOwnPropertyNames(this)){if("extras"===e||"picture"===e)continue;const t=this[e];if(t instanceof XFAObject){this[Xs]=t;return t}}this[Xs]=null}return this[Xs]}[jr](e){const t=this[ar]();return t?t[jr](e):HTMLResult.EMPTY}}class Validate extends XFAObject{constructor(e){super(Nn,"validate",!0);this.formatTest=getStringOption(e.formatTest,["warning","disabled","error"]);this.id=e.id||"";this.nullTest=getStringOption(e.nullTest,["disabled","error","warning"]);this.scriptTest=getStringOption(e.scriptTest,["error","disabled","warning"]);this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.message=null;this.picture=null;this.script=null}}class Value extends XFAObject{constructor(e){super(Nn,"value",!0);this.id=e.id||"";this.override=getInteger({data:e.override,defaultValue:0,validate:e=>1===e});this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.arc=null;this.boolean=null;this.date=null;this.dateTime=null;this.decimal=null;this.exData=null;this.float=null;this.image=null;this.integer=null;this.line=null;this.rectangle=null;this.text=null;this.time=null}[qr](e){const t=this[Ir]();if(t instanceof Field&&t.ui?.imageEdit){if(!this.image){this.image=new Image({});this[Hs](this.image)}this.image[Os]=e[Os];return}const i=e[kr];if(null===this[i]){for(const e of Object.getOwnPropertyNames(this)){const t=this[e];if(t instanceof XFAObject){this[e]=null;this[Hr](t)}}this[e[kr]]=e;this[Hs](e)}else this[i][Os]=e[Os]}[Pr](){if(this.exData)return"string"==typeof this.exData[Os]?this.exData[Os].trim():this.exData[Os][Pr]().trim();for(const e of Object.getOwnPropertyNames(this)){if("image"===e)continue;const t=this[e];if(t instanceof XFAObject)return(t[Os]||"").toString().trim()}return null}[jr](e){for(const t of Object.getOwnPropertyNames(this)){const i=this[t];if(i instanceof XFAObject)return i[jr](e)}return HTMLResult.EMPTY}}class Variables extends XFAObject{constructor(e){super(Nn,"variables",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.manifest=new XFAObjectArray;this.script=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}[Dr](){return!0}}class TemplateNamespace{static[zr](e,t){if(TemplateNamespace.hasOwnProperty(e)){const i=TemplateNamespace[e](t);i[Tr](t);return i}}static appearanceFilter(e){return new AppearanceFilter(e)}static arc(e){return new Arc(e)}static area(e){return new Area(e)}static assist(e){return new Assist(e)}static barcode(e){return new Barcode(e)}static bind(e){return new Bind(e)}static bindItems(e){return new BindItems(e)}static bookend(e){return new Bookend(e)}static boolean(e){return new BooleanElement(e)}static border(e){return new Border(e)}static break(e){return new Break(e)}static breakAfter(e){return new BreakAfter(e)}static breakBefore(e){return new BreakBefore(e)}static button(e){return new Button(e)}static calculate(e){return new Calculate(e)}static caption(e){return new Caption(e)}static certificate(e){return new Certificate(e)}static certificates(e){return new Certificates(e)}static checkButton(e){return new CheckButton(e)}static choiceList(e){return new ChoiceList(e)}static color(e){return new Color(e)}static comb(e){return new Comb(e)}static connect(e){return new Connect(e)}static contentArea(e){return new ContentArea(e)}static corner(e){return new Corner(e)}static date(e){return new DateElement(e)}static dateTime(e){return new DateTime(e)}static dateTimeEdit(e){return new DateTimeEdit(e)}static decimal(e){return new Decimal(e)}static defaultUi(e){return new DefaultUi(e)}static desc(e){return new Desc(e)}static digestMethod(e){return new DigestMethod(e)}static digestMethods(e){return new DigestMethods(e)}static draw(e){return new Draw(e)}static edge(e){return new Edge(e)}static encoding(e){return new Encoding(e)}static encodings(e){return new Encodings(e)}static encrypt(e){return new Encrypt(e)}static encryptData(e){return new EncryptData(e)}static encryption(e){return new Encryption(e)}static encryptionMethod(e){return new EncryptionMethod(e)}static encryptionMethods(e){return new EncryptionMethods(e)}static event(e){return new Event(e)}static exData(e){return new ExData(e)}static exObject(e){return new ExObject(e)}static exclGroup(e){return new ExclGroup(e)}static execute(e){return new Execute(e)}static extras(e){return new Extras(e)}static field(e){return new Field(e)}static fill(e){return new Fill(e)}static filter(e){return new Filter(e)}static float(e){return new Float(e)}static font(e){return new template_Font(e)}static format(e){return new Format(e)}static handler(e){return new Handler(e)}static hyphenation(e){return new Hyphenation(e)}static image(e){return new Image(e)}static imageEdit(e){return new ImageEdit(e)}static integer(e){return new Integer(e)}static issuers(e){return new Issuers(e)}static items(e){return new Items(e)}static keep(e){return new Keep(e)}static keyUsage(e){return new KeyUsage(e)}static line(e){return new Line(e)}static linear(e){return new Linear(e)}static lockDocument(e){return new LockDocument(e)}static manifest(e){return new Manifest(e)}static margin(e){return new Margin(e)}static mdp(e){return new Mdp(e)}static medium(e){return new Medium(e)}static message(e){return new Message(e)}static numericEdit(e){return new NumericEdit(e)}static occur(e){return new Occur(e)}static oid(e){return new Oid(e)}static oids(e){return new Oids(e)}static overflow(e){return new Overflow(e)}static pageArea(e){return new PageArea(e)}static pageSet(e){return new PageSet(e)}static para(e){return new Para(e)}static passwordEdit(e){return new PasswordEdit(e)}static pattern(e){return new template_Pattern(e)}static picture(e){return new Picture(e)}static proto(e){return new Proto(e)}static radial(e){return new Radial(e)}static reason(e){return new Reason(e)}static reasons(e){return new Reasons(e)}static rectangle(e){return new Rectangle(e)}static ref(e){return new RefElement(e)}static script(e){return new Script(e)}static setProperty(e){return new SetProperty(e)}static signData(e){return new SignData(e)}static signature(e){return new Signature(e)}static signing(e){return new Signing(e)}static solid(e){return new Solid(e)}static speak(e){return new Speak(e)}static stipple(e){return new Stipple(e)}static subform(e){return new Subform(e)}static subformSet(e){return new SubformSet(e)}static subjectDN(e){return new SubjectDN(e)}static subjectDNs(e){return new SubjectDNs(e)}static submit(e){return new Submit(e)}static template(e){return new Template(e)}static text(e){return new Text(e)}static textEdit(e){return new TextEdit(e)}static time(e){return new Time(e)}static timeStamp(e){return new TimeStamp(e)}static toolTip(e){return new ToolTip(e)}static traversal(e){return new Traversal(e)}static traverse(e){return new Traverse(e)}static ui(e){return new Ui(e)}static validate(e){return new Validate(e)}static value(e){return new Value(e)}static variables(e){return new Variables(e)}}const Ln=_r.datasets.id;function createText(e){const t=new Text({});t[Os]=e;return t}class Binder{constructor(e){this.root=e;this.datasets=e.datasets;this.data=e.datasets?.data||new XmlObject(_r.datasets.id,"data");this.emptyMerge=0===this.data[rr]().length;this.root.form=this.form=e.template[Ts]()}_isConsumeData(){return!this.emptyMerge&&this._mergeMode}_isMatchTemplate(){return!this._isConsumeData()}bind(){this._bindElement(this.form,this.data);return this.form}getData(){return this.data}_bindValue(e,t,i){e[Ws]=t;if(e[hr]())if(t[fr]()){const i=t[ir]();e[qr](createText(i))}else if(e instanceof Field&&"multiSelect"===e.ui?.choiceList?.open){const i=t[rr]().map((e=>e[Os].trim())).join("\n");e[qr](createText(i))}else this._isConsumeData()&&warn("XFA - Nodes haven't the same type.");else!t[fr]()||this._isMatchTemplate()?this._bindElement(e,t):warn("XFA - Nodes haven't the same type.")}_findDataByNameToConsume(e,t,i,a){if(!e)return null;let s,r;for(let a=0;a<3;a++){s=i[sr](e,!1,!0);for(;;){r=s.next().value;if(!r)break;if(t===r[fr]())return r}if(i[Sr]===_r.datasets.id&&"data"===i[kr])break;i=i[Ir]()}if(!a)return null;s=this.data[sr](e,!0,!1);r=s.next().value;if(r)return r;s=this.data[zs](e,!0);r=s.next().value;return r?.[fr]()?r:null}_setProperties(e,t){if(e.hasOwnProperty("setProperty"))for(const{ref:i,target:a,connection:s}of e.setProperty.children){if(s)continue;if(!i)continue;const r=searchNode(this.root,t,i,!1,!1);if(!r){warn(`XFA - Invalid reference: ${i}.`);continue}const[n]=r;if(!n[pr](this.data)){warn("XFA - Invalid node: must be a data node.");continue}const g=searchNode(this.root,e,a,!1,!1);if(!g){warn(`XFA - Invalid target: ${a}.`);continue}const[o]=g;if(!o[pr](e)){warn("XFA - Invalid target: must be a property or subproperty.");continue}const c=o[Ir]();if(o instanceof SetProperty||c instanceof SetProperty){warn("XFA - Invalid target: cannot be a setProperty or one of its properties.");continue}if(o instanceof BindItems||c instanceof BindItems){warn("XFA - Invalid target: cannot be a bindItems or one of its properties.");continue}const C=n[Pr](),h=o[kr];if(o instanceof XFAAttribute){const e=Object.create(null);e[h]=C;const t=Reflect.construct(Object.getPrototypeOf(c).constructor,[e]);c[h]=t[h]}else if(o.hasOwnProperty(Os)){o[Ws]=n;o[Os]=C;o[Zs]()}else warn("XFA - Invalid node to use in setProperty")}}_bindItems(e,t){if(!e.hasOwnProperty("items")||!e.hasOwnProperty("bindItems")||e.bindItems.isEmpty())return;for(const t of e.items.children)e[Hr](t);e.items.clear();const i=new Items({}),a=new Items({});e[Hs](i);e.items.push(i);e[Hs](a);e.items.push(a);for(const{ref:s,labelRef:r,valueRef:n,connection:g}of e.bindItems.children){if(g)continue;if(!s)continue;const e=searchNode(this.root,t,s,!1,!1);if(e)for(const t of e){if(!t[pr](this.datasets)){warn(`XFA - Invalid ref (${s}): must be a datasets child.`);continue}const e=searchNode(this.root,t,r,!0,!1);if(!e){warn(`XFA - Invalid label: ${r}.`);continue}const[g]=e;if(!g[pr](this.datasets)){warn("XFA - Invalid label: must be a datasets child.");continue}const o=searchNode(this.root,t,n,!0,!1);if(!o){warn(`XFA - Invalid value: ${n}.`);continue}const[c]=o;if(!c[pr](this.datasets)){warn("XFA - Invalid value: must be a datasets child.");continue}const C=createText(g[Pr]()),h=createText(c[Pr]());i[Hs](C);i.text.push(C);a[Hs](h);a.text.push(h)}else warn(`XFA - Invalid reference: ${s}.`)}}_bindOccurrences(e,t,i){let a;if(t.length>1){a=e[Ts]();a[Hr](a.occur);a.occur=null}this._bindValue(e,t[0],i);this._setProperties(e,t[0]);this._bindItems(e,t[0]);if(1===t.length)return;const s=e[Ir](),r=e[kr],n=s[Qr](e);for(let e=1,g=t.length;et.name===e.name)).length:i[a].children.length;const r=i[Qr](e)+1,n=t.initial-s;if(n){const t=e[Ts]();t[Hr](t.occur);t.occur=null;i[a].push(t);i[Er](r,t);for(let e=1;e0)this._bindOccurrences(a,[e[0]],null);else if(this.emptyMerge){const e=t[Sr]===Ln?-1:t[Sr],i=a[Ws]=new XmlObject(e,a.name||"root");t[Hs](i);this._bindElement(a,i)}continue}if(!a[dr]())continue;let e=!1,s=null,r=null,n=null;if(a.bind){switch(a.bind.match){case"none":this._setAndBind(a,t);continue;case"global":e=!0;break;case"dataRef":if(!a.bind.ref){warn(`XFA - ref is empty in node ${a[kr]}.`);this._setAndBind(a,t);continue}r=a.bind.ref}a.bind.picture&&(s=a.bind.picture[Os])}const[g,o]=this._getOccurInfo(a);if(r){n=searchNode(this.root,t,r,!0,!1);if(null===n){n=createDataNode(this.data,t,r);if(!n)continue;this._isConsumeData()&&(n[qs]=!0);this._setAndBind(a,n);continue}this._isConsumeData()&&(n=n.filter((e=>!e[qs])));n.length>o?n=n.slice(0,o):0===n.length&&(n=null);n&&this._isConsumeData()&&n.forEach((e=>{e[qs]=!0}))}else{if(!a.name){this._setAndBind(a,t);continue}if(this._isConsumeData()){const i=[];for(;i.length0?i:null}else{n=t[sr](a.name,!1,this.emptyMerge).next().value;if(!n){if(0===g){i.push(a);continue}const e=t[Sr]===Ln?-1:t[Sr];n=a[Ws]=new XmlObject(e,a.name);this.emptyMerge&&(n[qs]=!0);t[Hs](n);this._setAndBind(a,n);continue}this.emptyMerge&&(n[qs]=!0);n=[n]}}n?this._bindOccurrences(a,n,s):g>0?this._setAndBind(a,t):i.push(a)}i.forEach((e=>e[Ir]()[Hr](e)))}}class DataHandler{constructor(e,t){this.data=t;this.dataset=e.datasets||null}serialize(e){const t=[[-1,this.data[rr]()]];for(;t.length>0;){const i=t.at(-1),[a,s]=i;if(a+1===s.length){t.pop();continue}const r=s[++i[0]],n=e.get(r[Vr]);if(n)r[qr](n);else{const t=r[_s]();for(const i of t.values()){const t=e.get(i[Vr]);if(t){i[qr](t);break}}}const g=r[rr]();g.length>0&&t.push([-1,g])}const i=[''];if(this.dataset)for(const e of this.dataset[rr]())"data"!==e[kr]&&e[Xr](i);this.data[Xr](i);i.push("");return i.join("")}}const Hn=_r.config.id;class Acrobat extends XFAObject{constructor(e){super(Hn,"acrobat",!0);this.acrobat7=null;this.autoSave=null;this.common=null;this.validate=null;this.validateApprovalSignatures=null;this.submitUrl=new XFAObjectArray}}class Acrobat7 extends XFAObject{constructor(e){super(Hn,"acrobat7",!0);this.dynamicRender=null}}class ADBE_JSConsole extends OptionObject{constructor(e){super(Hn,"ADBE_JSConsole",["delegate","Enable","Disable"])}}class ADBE_JSDebugger extends OptionObject{constructor(e){super(Hn,"ADBE_JSDebugger",["delegate","Enable","Disable"])}}class AddSilentPrint extends Option01{constructor(e){super(Hn,"addSilentPrint")}}class AddViewerPreferences extends Option01{constructor(e){super(Hn,"addViewerPreferences")}}class AdjustData extends Option10{constructor(e){super(Hn,"adjustData")}}class AdobeExtensionLevel extends IntegerObject{constructor(e){super(Hn,"adobeExtensionLevel",0,(e=>e>=1&&e<=8))}}class Agent extends XFAObject{constructor(e){super(Hn,"agent",!0);this.name=e.name?e.name.trim():"";this.common=new XFAObjectArray}}class AlwaysEmbed extends ContentObject{constructor(e){super(Hn,"alwaysEmbed")}}class Amd extends StringObject{constructor(e){super(Hn,"amd")}}class config_Area extends XFAObject{constructor(e){super(Hn,"area");this.level=getInteger({data:e.level,defaultValue:0,validate:e=>e>=1&&e<=3});this.name=getStringOption(e.name,["","barcode","coreinit","deviceDriver","font","general","layout","merge","script","signature","sourceSet","templateCache"])}}class Attributes extends OptionObject{constructor(e){super(Hn,"attributes",["preserve","delegate","ignore"])}}class AutoSave extends OptionObject{constructor(e){super(Hn,"autoSave",["disabled","enabled"])}}class Base extends StringObject{constructor(e){super(Hn,"base")}}class BatchOutput extends XFAObject{constructor(e){super(Hn,"batchOutput");this.format=getStringOption(e.format,["none","concat","zip","zipCompress"])}}class BehaviorOverride extends ContentObject{constructor(e){super(Hn,"behaviorOverride")}[Zs](){this[Os]=new Map(this[Os].trim().split(/\s+/).filter((e=>e.includes(":"))).map((e=>e.split(":",2))))}}class Cache extends XFAObject{constructor(e){super(Hn,"cache",!0);this.templateCache=null}}class Change extends Option01{constructor(e){super(Hn,"change")}}class Common extends XFAObject{constructor(e){super(Hn,"common",!0);this.data=null;this.locale=null;this.localeSet=null;this.messaging=null;this.suppressBanner=null;this.template=null;this.validationMessaging=null;this.versionControl=null;this.log=new XFAObjectArray}}class Compress extends XFAObject{constructor(e){super(Hn,"compress");this.scope=getStringOption(e.scope,["imageOnly","document"])}}class CompressLogicalStructure extends Option01{constructor(e){super(Hn,"compressLogicalStructure")}}class CompressObjectStream extends Option10{constructor(e){super(Hn,"compressObjectStream")}}class Compression extends XFAObject{constructor(e){super(Hn,"compression",!0);this.compressLogicalStructure=null;this.compressObjectStream=null;this.level=null;this.type=null}}class Config extends XFAObject{constructor(e){super(Hn,"config",!0);this.acrobat=null;this.present=null;this.trace=null;this.agent=new XFAObjectArray}}class Conformance extends OptionObject{constructor(e){super(Hn,"conformance",["A","B"])}}class ContentCopy extends Option01{constructor(e){super(Hn,"contentCopy")}}class Copies extends IntegerObject{constructor(e){super(Hn,"copies",1,(e=>e>=1))}}class Creator extends StringObject{constructor(e){super(Hn,"creator")}}class CurrentPage extends IntegerObject{constructor(e){super(Hn,"currentPage",0,(e=>e>=0))}}class Data extends XFAObject{constructor(e){super(Hn,"data",!0);this.adjustData=null;this.attributes=null;this.incrementalLoad=null;this.outputXSL=null;this.range=null;this.record=null;this.startNode=null;this.uri=null;this.window=null;this.xsl=null;this.excludeNS=new XFAObjectArray;this.transform=new XFAObjectArray}}class Debug extends XFAObject{constructor(e){super(Hn,"debug",!0);this.uri=null}}class DefaultTypeface extends ContentObject{constructor(e){super(Hn,"defaultTypeface");this.writingScript=getStringOption(e.writingScript,["*","Arabic","Cyrillic","EastEuropeanRoman","Greek","Hebrew","Japanese","Korean","Roman","SimplifiedChinese","Thai","TraditionalChinese","Vietnamese"])}}class Destination extends OptionObject{constructor(e){super(Hn,"destination",["pdf","pcl","ps","webClient","zpl"])}}class DocumentAssembly extends Option01{constructor(e){super(Hn,"documentAssembly")}}class Driver extends XFAObject{constructor(e){super(Hn,"driver",!0);this.name=e.name?e.name.trim():"";this.fontInfo=null;this.xdc=null}}class DuplexOption extends OptionObject{constructor(e){super(Hn,"duplexOption",["simplex","duplexFlipLongEdge","duplexFlipShortEdge"])}}class DynamicRender extends OptionObject{constructor(e){super(Hn,"dynamicRender",["forbidden","required"])}}class Embed extends Option01{constructor(e){super(Hn,"embed")}}class config_Encrypt extends Option01{constructor(e){super(Hn,"encrypt")}}class config_Encryption extends XFAObject{constructor(e){super(Hn,"encryption",!0);this.encrypt=null;this.encryptionLevel=null;this.permissions=null}}class EncryptionLevel extends OptionObject{constructor(e){super(Hn,"encryptionLevel",["40bit","128bit"])}}class Enforce extends StringObject{constructor(e){super(Hn,"enforce")}}class Equate extends XFAObject{constructor(e){super(Hn,"equate");this.force=getInteger({data:e.force,defaultValue:1,validate:e=>0===e});this.from=e.from||"";this.to=e.to||""}}class EquateRange extends XFAObject{constructor(e){super(Hn,"equateRange");this.from=e.from||"";this.to=e.to||"";this._unicodeRange=e.unicodeRange||""}get unicodeRange(){const e=[],t=/U\+([0-9a-fA-F]+)/,i=this._unicodeRange;for(let a of i.split(",").map((e=>e.trim())).filter((e=>!!e))){a=a.split("-",2).map((e=>{const i=e.match(t);return i?parseInt(i[1],16):0}));1===a.length&&a.push(a[0]);e.push(a)}return shadow(this,"unicodeRange",e)}}class Exclude extends ContentObject{constructor(e){super(Hn,"exclude")}[Zs](){this[Os]=this[Os].trim().split(/\s+/).filter((e=>e&&["calculate","close","enter","exit","initialize","ready","validate"].includes(e)))}}class ExcludeNS extends StringObject{constructor(e){super(Hn,"excludeNS")}}class FlipLabel extends OptionObject{constructor(e){super(Hn,"flipLabel",["usePrinterSetting","on","off"])}}class config_FontInfo extends XFAObject{constructor(e){super(Hn,"fontInfo",!0);this.embed=null;this.map=null;this.subsetBelow=null;this.alwaysEmbed=new XFAObjectArray;this.defaultTypeface=new XFAObjectArray;this.neverEmbed=new XFAObjectArray}}class FormFieldFilling extends Option01{constructor(e){super(Hn,"formFieldFilling")}}class GroupParent extends StringObject{constructor(e){super(Hn,"groupParent")}}class IfEmpty extends OptionObject{constructor(e){super(Hn,"ifEmpty",["dataValue","dataGroup","ignore","remove"])}}class IncludeXDPContent extends StringObject{constructor(e){super(Hn,"includeXDPContent")}}class IncrementalLoad extends OptionObject{constructor(e){super(Hn,"incrementalLoad",["none","forwardOnly"])}}class IncrementalMerge extends Option01{constructor(e){super(Hn,"incrementalMerge")}}class Interactive extends Option01{constructor(e){super(Hn,"interactive")}}class Jog extends OptionObject{constructor(e){super(Hn,"jog",["usePrinterSetting","none","pageSet"])}}class LabelPrinter extends XFAObject{constructor(e){super(Hn,"labelPrinter",!0);this.name=getStringOption(e.name,["zpl","dpl","ipl","tcpl"]);this.batchOutput=null;this.flipLabel=null;this.fontInfo=null;this.xdc=null}}class Layout extends OptionObject{constructor(e){super(Hn,"layout",["paginate","panel"])}}class Level extends IntegerObject{constructor(e){super(Hn,"level",0,(e=>e>0))}}class Linearized extends Option01{constructor(e){super(Hn,"linearized")}}class Locale extends StringObject{constructor(e){super(Hn,"locale")}}class LocaleSet extends StringObject{constructor(e){super(Hn,"localeSet")}}class Log extends XFAObject{constructor(e){super(Hn,"log",!0);this.mode=null;this.threshold=null;this.to=null;this.uri=null}}class MapElement extends XFAObject{constructor(e){super(Hn,"map",!0);this.equate=new XFAObjectArray;this.equateRange=new XFAObjectArray}}class MediumInfo extends XFAObject{constructor(e){super(Hn,"mediumInfo",!0);this.map=null}}class config_Message extends XFAObject{constructor(e){super(Hn,"message",!0);this.msgId=null;this.severity=null}}class Messaging extends XFAObject{constructor(e){super(Hn,"messaging",!0);this.message=new XFAObjectArray}}class Mode extends OptionObject{constructor(e){super(Hn,"mode",["append","overwrite"])}}class ModifyAnnots extends Option01{constructor(e){super(Hn,"modifyAnnots")}}class MsgId extends IntegerObject{constructor(e){super(Hn,"msgId",1,(e=>e>=1))}}class NameAttr extends StringObject{constructor(e){super(Hn,"nameAttr")}}class NeverEmbed extends ContentObject{constructor(e){super(Hn,"neverEmbed")}}class NumberOfCopies extends IntegerObject{constructor(e){super(Hn,"numberOfCopies",null,(e=>e>=2&&e<=5))}}class OpenAction extends XFAObject{constructor(e){super(Hn,"openAction",!0);this.destination=null}}class Output extends XFAObject{constructor(e){super(Hn,"output",!0);this.to=null;this.type=null;this.uri=null}}class OutputBin extends StringObject{constructor(e){super(Hn,"outputBin")}}class OutputXSL extends XFAObject{constructor(e){super(Hn,"outputXSL",!0);this.uri=null}}class Overprint extends OptionObject{constructor(e){super(Hn,"overprint",["none","both","draw","field"])}}class Packets extends StringObject{constructor(e){super(Hn,"packets")}[Zs](){"*"!==this[Os]&&(this[Os]=this[Os].trim().split(/\s+/).filter((e=>["config","datasets","template","xfdf","xslt"].includes(e))))}}class PageOffset extends XFAObject{constructor(e){super(Hn,"pageOffset");this.x=getInteger({data:e.x,defaultValue:"useXDCSetting",validate:e=>!0});this.y=getInteger({data:e.y,defaultValue:"useXDCSetting",validate:e=>!0})}}class PageRange extends StringObject{constructor(e){super(Hn,"pageRange")}[Zs](){const e=this[Os].trim().split(/\s+/).map((e=>parseInt(e,10))),t=[];for(let i=0,a=e.length;i!1))}}class Pcl extends XFAObject{constructor(e){super(Hn,"pcl",!0);this.name=e.name||"";this.batchOutput=null;this.fontInfo=null;this.jog=null;this.mediumInfo=null;this.outputBin=null;this.pageOffset=null;this.staple=null;this.xdc=null}}class Pdf extends XFAObject{constructor(e){super(Hn,"pdf",!0);this.name=e.name||"";this.adobeExtensionLevel=null;this.batchOutput=null;this.compression=null;this.creator=null;this.encryption=null;this.fontInfo=null;this.interactive=null;this.linearized=null;this.openAction=null;this.pdfa=null;this.producer=null;this.renderPolicy=null;this.scriptModel=null;this.silentPrint=null;this.submitFormat=null;this.tagged=null;this.version=null;this.viewerPreferences=null;this.xdc=null}}class Pdfa extends XFAObject{constructor(e){super(Hn,"pdfa",!0);this.amd=null;this.conformance=null;this.includeXDPContent=null;this.part=null}}class Permissions extends XFAObject{constructor(e){super(Hn,"permissions",!0);this.accessibleContent=null;this.change=null;this.contentCopy=null;this.documentAssembly=null;this.formFieldFilling=null;this.modifyAnnots=null;this.plaintextMetadata=null;this.print=null;this.printHighQuality=null}}class PickTrayByPDFSize extends Option01{constructor(e){super(Hn,"pickTrayByPDFSize")}}class config_Picture extends StringObject{constructor(e){super(Hn,"picture")}}class PlaintextMetadata extends Option01{constructor(e){super(Hn,"plaintextMetadata")}}class Presence extends OptionObject{constructor(e){super(Hn,"presence",["preserve","dissolve","dissolveStructure","ignore","remove"])}}class Present extends XFAObject{constructor(e){super(Hn,"present",!0);this.behaviorOverride=null;this.cache=null;this.common=null;this.copies=null;this.destination=null;this.incrementalMerge=null;this.layout=null;this.output=null;this.overprint=null;this.pagination=null;this.paginationOverride=null;this.script=null;this.validate=null;this.xdp=null;this.driver=new XFAObjectArray;this.labelPrinter=new XFAObjectArray;this.pcl=new XFAObjectArray;this.pdf=new XFAObjectArray;this.ps=new XFAObjectArray;this.submitUrl=new XFAObjectArray;this.webClient=new XFAObjectArray;this.zpl=new XFAObjectArray}}class Print extends Option01{constructor(e){super(Hn,"print")}}class PrintHighQuality extends Option01{constructor(e){super(Hn,"printHighQuality")}}class PrintScaling extends OptionObject{constructor(e){super(Hn,"printScaling",["appdefault","noScaling"])}}class PrinterName extends StringObject{constructor(e){super(Hn,"printerName")}}class Producer extends StringObject{constructor(e){super(Hn,"producer")}}class Ps extends XFAObject{constructor(e){super(Hn,"ps",!0);this.name=e.name||"";this.batchOutput=null;this.fontInfo=null;this.jog=null;this.mediumInfo=null;this.outputBin=null;this.staple=null;this.xdc=null}}class Range extends ContentObject{constructor(e){super(Hn,"range")}[Zs](){this[Os]=this[Os].trim().split(/\s*,\s*/,2).map((e=>e.split("-").map((e=>parseInt(e.trim(),10))))).filter((e=>e.every((e=>!isNaN(e))))).map((e=>{1===e.length&&e.push(e[0]);return e}))}}class Record extends ContentObject{constructor(e){super(Hn,"record")}[Zs](){this[Os]=this[Os].trim();const e=parseInt(this[Os],10);!isNaN(e)&&e>=0&&(this[Os]=e)}}class Relevant extends ContentObject{constructor(e){super(Hn,"relevant")}[Zs](){this[Os]=this[Os].trim().split(/\s+/)}}class Rename extends ContentObject{constructor(e){super(Hn,"rename")}[Zs](){this[Os]=this[Os].trim();(this[Os].toLowerCase().startsWith("xml")||new RegExp("[\\p{L}_][\\p{L}\\d._\\p{M}-]*","u").test(this[Os]))&&warn("XFA - Rename: invalid XFA name")}}class RenderPolicy extends OptionObject{constructor(e){super(Hn,"renderPolicy",["server","client"])}}class RunScripts extends OptionObject{constructor(e){super(Hn,"runScripts",["both","client","none","server"])}}class config_Script extends XFAObject{constructor(e){super(Hn,"script",!0);this.currentPage=null;this.exclude=null;this.runScripts=null}}class ScriptModel extends OptionObject{constructor(e){super(Hn,"scriptModel",["XFA","none"])}}class Severity extends OptionObject{constructor(e){super(Hn,"severity",["ignore","error","information","trace","warning"])}}class SilentPrint extends XFAObject{constructor(e){super(Hn,"silentPrint",!0);this.addSilentPrint=null;this.printerName=null}}class Staple extends XFAObject{constructor(e){super(Hn,"staple");this.mode=getStringOption(e.mode,["usePrinterSetting","on","off"])}}class StartNode extends StringObject{constructor(e){super(Hn,"startNode")}}class StartPage extends IntegerObject{constructor(e){super(Hn,"startPage",0,(e=>!0))}}class SubmitFormat extends OptionObject{constructor(e){super(Hn,"submitFormat",["html","delegate","fdf","xml","pdf"])}}class SubmitUrl extends StringObject{constructor(e){super(Hn,"submitUrl")}}class SubsetBelow extends IntegerObject{constructor(e){super(Hn,"subsetBelow",100,(e=>e>=0&&e<=100))}}class SuppressBanner extends Option01{constructor(e){super(Hn,"suppressBanner")}}class Tagged extends Option01{constructor(e){super(Hn,"tagged")}}class config_Template extends XFAObject{constructor(e){super(Hn,"template",!0);this.base=null;this.relevant=null;this.startPage=null;this.uri=null;this.xsl=null}}class Threshold extends OptionObject{constructor(e){super(Hn,"threshold",["trace","error","information","warning"])}}class To extends OptionObject{constructor(e){super(Hn,"to",["null","memory","stderr","stdout","system","uri"])}}class TemplateCache extends XFAObject{constructor(e){super(Hn,"templateCache");this.maxEntries=getInteger({data:e.maxEntries,defaultValue:5,validate:e=>e>=0})}}class Trace extends XFAObject{constructor(e){super(Hn,"trace",!0);this.area=new XFAObjectArray}}class Transform extends XFAObject{constructor(e){super(Hn,"transform",!0);this.groupParent=null;this.ifEmpty=null;this.nameAttr=null;this.picture=null;this.presence=null;this.rename=null;this.whitespace=null}}class Type extends OptionObject{constructor(e){super(Hn,"type",["none","ascii85","asciiHex","ccittfax","flate","lzw","runLength","native","xdp","mergedXDP"])}}class Uri extends StringObject{constructor(e){super(Hn,"uri")}}class config_Validate extends OptionObject{constructor(e){super(Hn,"validate",["preSubmit","prePrint","preExecute","preSave"])}}class ValidateApprovalSignatures extends ContentObject{constructor(e){super(Hn,"validateApprovalSignatures")}[Zs](){this[Os]=this[Os].trim().split(/\s+/).filter((e=>["docReady","postSign"].includes(e)))}}class ValidationMessaging extends OptionObject{constructor(e){super(Hn,"validationMessaging",["allMessagesIndividually","allMessagesTogether","firstMessageOnly","noMessages"])}}class Version extends OptionObject{constructor(e){super(Hn,"version",["1.7","1.6","1.5","1.4","1.3","1.2"])}}class VersionControl extends XFAObject{constructor(e){super(Hn,"VersionControl");this.outputBelow=getStringOption(e.outputBelow,["warn","error","update"]);this.sourceAbove=getStringOption(e.sourceAbove,["warn","error"]);this.sourceBelow=getStringOption(e.sourceBelow,["update","maintain"])}}class ViewerPreferences extends XFAObject{constructor(e){super(Hn,"viewerPreferences",!0);this.ADBE_JSConsole=null;this.ADBE_JSDebugger=null;this.addViewerPreferences=null;this.duplexOption=null;this.enforce=null;this.numberOfCopies=null;this.pageRange=null;this.pickTrayByPDFSize=null;this.printScaling=null}}class WebClient extends XFAObject{constructor(e){super(Hn,"webClient",!0);this.name=e.name?e.name.trim():"";this.fontInfo=null;this.xdc=null}}class Whitespace extends OptionObject{constructor(e){super(Hn,"whitespace",["preserve","ltrim","normalize","rtrim","trim"])}}class Window extends ContentObject{constructor(e){super(Hn,"window")}[Zs](){const e=this[Os].trim().split(/\s*,\s*/,2).map((e=>parseInt(e,10)));if(e.some((e=>isNaN(e))))this[Os]=[0,0];else{1===e.length&&e.push(e[0]);this[Os]=e}}}class Xdc extends XFAObject{constructor(e){super(Hn,"xdc",!0);this.uri=new XFAObjectArray;this.xsl=new XFAObjectArray}}class Xdp extends XFAObject{constructor(e){super(Hn,"xdp",!0);this.packets=null}}class Xsl extends XFAObject{constructor(e){super(Hn,"xsl",!0);this.debug=null;this.uri=null}}class Zpl extends XFAObject{constructor(e){super(Hn,"zpl",!0);this.name=e.name?e.name.trim():"";this.batchOutput=null;this.flipLabel=null;this.fontInfo=null;this.xdc=null}}class ConfigNamespace{static[zr](e,t){if(ConfigNamespace.hasOwnProperty(e))return ConfigNamespace[e](t)}static acrobat(e){return new Acrobat(e)}static acrobat7(e){return new Acrobat7(e)}static ADBE_JSConsole(e){return new ADBE_JSConsole(e)}static ADBE_JSDebugger(e){return new ADBE_JSDebugger(e)}static addSilentPrint(e){return new AddSilentPrint(e)}static addViewerPreferences(e){return new AddViewerPreferences(e)}static adjustData(e){return new AdjustData(e)}static adobeExtensionLevel(e){return new AdobeExtensionLevel(e)}static agent(e){return new Agent(e)}static alwaysEmbed(e){return new AlwaysEmbed(e)}static amd(e){return new Amd(e)}static area(e){return new config_Area(e)}static attributes(e){return new Attributes(e)}static autoSave(e){return new AutoSave(e)}static base(e){return new Base(e)}static batchOutput(e){return new BatchOutput(e)}static behaviorOverride(e){return new BehaviorOverride(e)}static cache(e){return new Cache(e)}static change(e){return new Change(e)}static common(e){return new Common(e)}static compress(e){return new Compress(e)}static compressLogicalStructure(e){return new CompressLogicalStructure(e)}static compressObjectStream(e){return new CompressObjectStream(e)}static compression(e){return new Compression(e)}static config(e){return new Config(e)}static conformance(e){return new Conformance(e)}static contentCopy(e){return new ContentCopy(e)}static copies(e){return new Copies(e)}static creator(e){return new Creator(e)}static currentPage(e){return new CurrentPage(e)}static data(e){return new Data(e)}static debug(e){return new Debug(e)}static defaultTypeface(e){return new DefaultTypeface(e)}static destination(e){return new Destination(e)}static documentAssembly(e){return new DocumentAssembly(e)}static driver(e){return new Driver(e)}static duplexOption(e){return new DuplexOption(e)}static dynamicRender(e){return new DynamicRender(e)}static embed(e){return new Embed(e)}static encrypt(e){return new config_Encrypt(e)}static encryption(e){return new config_Encryption(e)}static encryptionLevel(e){return new EncryptionLevel(e)}static enforce(e){return new Enforce(e)}static equate(e){return new Equate(e)}static equateRange(e){return new EquateRange(e)}static exclude(e){return new Exclude(e)}static excludeNS(e){return new ExcludeNS(e)}static flipLabel(e){return new FlipLabel(e)}static fontInfo(e){return new config_FontInfo(e)}static formFieldFilling(e){return new FormFieldFilling(e)}static groupParent(e){return new GroupParent(e)}static ifEmpty(e){return new IfEmpty(e)}static includeXDPContent(e){return new IncludeXDPContent(e)}static incrementalLoad(e){return new IncrementalLoad(e)}static incrementalMerge(e){return new IncrementalMerge(e)}static interactive(e){return new Interactive(e)}static jog(e){return new Jog(e)}static labelPrinter(e){return new LabelPrinter(e)}static layout(e){return new Layout(e)}static level(e){return new Level(e)}static linearized(e){return new Linearized(e)}static locale(e){return new Locale(e)}static localeSet(e){return new LocaleSet(e)}static log(e){return new Log(e)}static map(e){return new MapElement(e)}static mediumInfo(e){return new MediumInfo(e)}static message(e){return new config_Message(e)}static messaging(e){return new Messaging(e)}static mode(e){return new Mode(e)}static modifyAnnots(e){return new ModifyAnnots(e)}static msgId(e){return new MsgId(e)}static nameAttr(e){return new NameAttr(e)}static neverEmbed(e){return new NeverEmbed(e)}static numberOfCopies(e){return new NumberOfCopies(e)}static openAction(e){return new OpenAction(e)}static output(e){return new Output(e)}static outputBin(e){return new OutputBin(e)}static outputXSL(e){return new OutputXSL(e)}static overprint(e){return new Overprint(e)}static packets(e){return new Packets(e)}static pageOffset(e){return new PageOffset(e)}static pageRange(e){return new PageRange(e)}static pagination(e){return new Pagination(e)}static paginationOverride(e){return new PaginationOverride(e)}static part(e){return new Part(e)}static pcl(e){return new Pcl(e)}static pdf(e){return new Pdf(e)}static pdfa(e){return new Pdfa(e)}static permissions(e){return new Permissions(e)}static pickTrayByPDFSize(e){return new PickTrayByPDFSize(e)}static picture(e){return new config_Picture(e)}static plaintextMetadata(e){return new PlaintextMetadata(e)}static presence(e){return new Presence(e)}static present(e){return new Present(e)}static print(e){return new Print(e)}static printHighQuality(e){return new PrintHighQuality(e)}static printScaling(e){return new PrintScaling(e)}static printerName(e){return new PrinterName(e)}static producer(e){return new Producer(e)}static ps(e){return new Ps(e)}static range(e){return new Range(e)}static record(e){return new Record(e)}static relevant(e){return new Relevant(e)}static rename(e){return new Rename(e)}static renderPolicy(e){return new RenderPolicy(e)}static runScripts(e){return new RunScripts(e)}static script(e){return new config_Script(e)}static scriptModel(e){return new ScriptModel(e)}static severity(e){return new Severity(e)}static silentPrint(e){return new SilentPrint(e)}static staple(e){return new Staple(e)}static startNode(e){return new StartNode(e)}static startPage(e){return new StartPage(e)}static submitFormat(e){return new SubmitFormat(e)}static submitUrl(e){return new SubmitUrl(e)}static subsetBelow(e){return new SubsetBelow(e)}static suppressBanner(e){return new SuppressBanner(e)}static tagged(e){return new Tagged(e)}static template(e){return new config_Template(e)}static templateCache(e){return new TemplateCache(e)}static threshold(e){return new Threshold(e)}static to(e){return new To(e)}static trace(e){return new Trace(e)}static transform(e){return new Transform(e)}static type(e){return new Type(e)}static uri(e){return new Uri(e)}static validate(e){return new config_Validate(e)}static validateApprovalSignatures(e){return new ValidateApprovalSignatures(e)}static validationMessaging(e){return new ValidationMessaging(e)}static version(e){return new Version(e)}static versionControl(e){return new VersionControl(e)}static viewerPreferences(e){return new ViewerPreferences(e)}static webClient(e){return new WebClient(e)}static whitespace(e){return new Whitespace(e)}static window(e){return new Window(e)}static xdc(e){return new Xdc(e)}static xdp(e){return new Xdp(e)}static xsl(e){return new Xsl(e)}static zpl(e){return new Zpl(e)}}const Jn=_r.connectionSet.id;class ConnectionSet extends XFAObject{constructor(e){super(Jn,"connectionSet",!0);this.wsdlConnection=new XFAObjectArray;this.xmlConnection=new XFAObjectArray;this.xsdConnection=new XFAObjectArray}}class EffectiveInputPolicy extends XFAObject{constructor(e){super(Jn,"effectiveInputPolicy");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class EffectiveOutputPolicy extends XFAObject{constructor(e){super(Jn,"effectiveOutputPolicy");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Operation extends StringObject{constructor(e){super(Jn,"operation");this.id=e.id||"";this.input=e.input||"";this.name=e.name||"";this.output=e.output||"";this.use=e.use||"";this.usehref=e.usehref||""}}class RootElement extends StringObject{constructor(e){super(Jn,"rootElement");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class SoapAction extends StringObject{constructor(e){super(Jn,"soapAction");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class SoapAddress extends StringObject{constructor(e){super(Jn,"soapAddress");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class connection_set_Uri extends StringObject{constructor(e){super(Jn,"uri");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class WsdlAddress extends StringObject{constructor(e){super(Jn,"wsdlAddress");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class WsdlConnection extends XFAObject{constructor(e){super(Jn,"wsdlConnection",!0);this.dataDescription=e.dataDescription||"";this.name=e.name||"";this.effectiveInputPolicy=null;this.effectiveOutputPolicy=null;this.operation=null;this.soapAction=null;this.soapAddress=null;this.wsdlAddress=null}}class XmlConnection extends XFAObject{constructor(e){super(Jn,"xmlConnection",!0);this.dataDescription=e.dataDescription||"";this.name=e.name||"";this.uri=null}}class XsdConnection extends XFAObject{constructor(e){super(Jn,"xsdConnection",!0);this.dataDescription=e.dataDescription||"";this.name=e.name||"";this.rootElement=null;this.uri=null}}class ConnectionSetNamespace{static[zr](e,t){if(ConnectionSetNamespace.hasOwnProperty(e))return ConnectionSetNamespace[e](t)}static connectionSet(e){return new ConnectionSet(e)}static effectiveInputPolicy(e){return new EffectiveInputPolicy(e)}static effectiveOutputPolicy(e){return new EffectiveOutputPolicy(e)}static operation(e){return new Operation(e)}static rootElement(e){return new RootElement(e)}static soapAction(e){return new SoapAction(e)}static soapAddress(e){return new SoapAddress(e)}static uri(e){return new connection_set_Uri(e)}static wsdlAddress(e){return new WsdlAddress(e)}static wsdlConnection(e){return new WsdlConnection(e)}static xmlConnection(e){return new XmlConnection(e)}static xsdConnection(e){return new XsdConnection(e)}}const Yn=_r.datasets.id;class datasets_Data extends XmlObject{constructor(e){super(Yn,"data",e)}[mr](){return!0}}class Datasets extends XFAObject{constructor(e){super(Yn,"datasets",!0);this.data=null;this.Signature=null}[Nr](e){const t=e[kr];("data"===t&&e[Sr]===Yn||"Signature"===t&&e[Sr]===_r.signature.id)&&(this[t]=e);this[Hs](e)}}class DatasetsNamespace{static[zr](e,t){if(DatasetsNamespace.hasOwnProperty(e))return DatasetsNamespace[e](t)}static datasets(e){return new Datasets(e)}static data(e){return new datasets_Data(e)}}const vn=_r.localeSet.id;class CalendarSymbols extends XFAObject{constructor(e){super(vn,"calendarSymbols",!0);this.name="gregorian";this.dayNames=new XFAObjectArray(2);this.eraNames=null;this.meridiemNames=null;this.monthNames=new XFAObjectArray(2)}}class CurrencySymbol extends StringObject{constructor(e){super(vn,"currencySymbol");this.name=getStringOption(e.name,["symbol","isoname","decimal"])}}class CurrencySymbols extends XFAObject{constructor(e){super(vn,"currencySymbols",!0);this.currencySymbol=new XFAObjectArray(3)}}class DatePattern extends StringObject{constructor(e){super(vn,"datePattern");this.name=getStringOption(e.name,["full","long","med","short"])}}class DatePatterns extends XFAObject{constructor(e){super(vn,"datePatterns",!0);this.datePattern=new XFAObjectArray(4)}}class DateTimeSymbols extends ContentObject{constructor(e){super(vn,"dateTimeSymbols")}}class Day extends StringObject{constructor(e){super(vn,"day")}}class DayNames extends XFAObject{constructor(e){super(vn,"dayNames",!0);this.abbr=getInteger({data:e.abbr,defaultValue:0,validate:e=>1===e});this.day=new XFAObjectArray(7)}}class Era extends StringObject{constructor(e){super(vn,"era")}}class EraNames extends XFAObject{constructor(e){super(vn,"eraNames",!0);this.era=new XFAObjectArray(2)}}class locale_set_Locale extends XFAObject{constructor(e){super(vn,"locale",!0);this.desc=e.desc||"";this.name="isoname";this.calendarSymbols=null;this.currencySymbols=null;this.datePatterns=null;this.dateTimeSymbols=null;this.numberPatterns=null;this.numberSymbols=null;this.timePatterns=null;this.typeFaces=null}}class locale_set_LocaleSet extends XFAObject{constructor(e){super(vn,"localeSet",!0);this.locale=new XFAObjectArray}}class Meridiem extends StringObject{constructor(e){super(vn,"meridiem")}}class MeridiemNames extends XFAObject{constructor(e){super(vn,"meridiemNames",!0);this.meridiem=new XFAObjectArray(2)}}class Month extends StringObject{constructor(e){super(vn,"month")}}class MonthNames extends XFAObject{constructor(e){super(vn,"monthNames",!0);this.abbr=getInteger({data:e.abbr,defaultValue:0,validate:e=>1===e});this.month=new XFAObjectArray(12)}}class NumberPattern extends StringObject{constructor(e){super(vn,"numberPattern");this.name=getStringOption(e.name,["full","long","med","short"])}}class NumberPatterns extends XFAObject{constructor(e){super(vn,"numberPatterns",!0);this.numberPattern=new XFAObjectArray(4)}}class NumberSymbol extends StringObject{constructor(e){super(vn,"numberSymbol");this.name=getStringOption(e.name,["decimal","grouping","percent","minus","zero"])}}class NumberSymbols extends XFAObject{constructor(e){super(vn,"numberSymbols",!0);this.numberSymbol=new XFAObjectArray(5)}}class TimePattern extends StringObject{constructor(e){super(vn,"timePattern");this.name=getStringOption(e.name,["full","long","med","short"])}}class TimePatterns extends XFAObject{constructor(e){super(vn,"timePatterns",!0);this.timePattern=new XFAObjectArray(4)}}class TypeFace extends XFAObject{constructor(e){super(vn,"typeFace",!0);this.name=""|e.name}}class TypeFaces extends XFAObject{constructor(e){super(vn,"typeFaces",!0);this.typeFace=new XFAObjectArray}}class LocaleSetNamespace{static[zr](e,t){if(LocaleSetNamespace.hasOwnProperty(e))return LocaleSetNamespace[e](t)}static calendarSymbols(e){return new CalendarSymbols(e)}static currencySymbol(e){return new CurrencySymbol(e)}static currencySymbols(e){return new CurrencySymbols(e)}static datePattern(e){return new DatePattern(e)}static datePatterns(e){return new DatePatterns(e)}static dateTimeSymbols(e){return new DateTimeSymbols(e)}static day(e){return new Day(e)}static dayNames(e){return new DayNames(e)}static era(e){return new Era(e)}static eraNames(e){return new EraNames(e)}static locale(e){return new locale_set_Locale(e)}static localeSet(e){return new locale_set_LocaleSet(e)}static meridiem(e){return new Meridiem(e)}static meridiemNames(e){return new MeridiemNames(e)}static month(e){return new Month(e)}static monthNames(e){return new MonthNames(e)}static numberPattern(e){return new NumberPattern(e)}static numberPatterns(e){return new NumberPatterns(e)}static numberSymbol(e){return new NumberSymbol(e)}static numberSymbols(e){return new NumberSymbols(e)}static timePattern(e){return new TimePattern(e)}static timePatterns(e){return new TimePatterns(e)}static typeFace(e){return new TypeFace(e)}static typeFaces(e){return new TypeFaces(e)}}const Kn=_r.signature.id;class signature_Signature extends XFAObject{constructor(e){super(Kn,"signature",!0)}}class SignatureNamespace{static[zr](e,t){if(SignatureNamespace.hasOwnProperty(e))return SignatureNamespace[e](t)}static signature(e){return new signature_Signature(e)}}const Tn=_r.stylesheet.id;class Stylesheet extends XFAObject{constructor(e){super(Tn,"stylesheet",!0)}}class StylesheetNamespace{static[zr](e,t){if(StylesheetNamespace.hasOwnProperty(e))return StylesheetNamespace[e](t)}static stylesheet(e){return new Stylesheet(e)}}const qn=_r.xdp.id;class xdp_Xdp extends XFAObject{constructor(e){super(qn,"xdp",!0);this.uuid=e.uuid||"";this.timeStamp=e.timeStamp||"";this.config=null;this.connectionSet=null;this.datasets=null;this.localeSet=null;this.stylesheet=new XFAObjectArray;this.template=null}[Gr](e){const t=_r[e[kr]];return t&&e[Sr]===t.id}}class XdpNamespace{static[zr](e,t){if(XdpNamespace.hasOwnProperty(e))return XdpNamespace[e](t)}static xdp(e){return new xdp_Xdp(e)}}const On=_r.xhtml.id,Pn=Symbol(),Wn=new Set(["color","font","font-family","font-size","font-stretch","font-style","font-weight","margin","margin-bottom","margin-left","margin-right","margin-top","letter-spacing","line-height","orphans","page-break-after","page-break-before","page-break-inside","tab-interval","tab-stop","text-align","text-decoration","text-indent","vertical-align","widows","kerning-mode","xfa-font-horizontal-scale","xfa-font-vertical-scale","xfa-spacerun","xfa-tab-stops"]),jn=new Map([["page-break-after","breakAfter"],["page-break-before","breakBefore"],["page-break-inside","breakInside"],["kerning-mode",e=>"none"===e?"none":"normal"],["xfa-font-horizontal-scale",e=>`scaleX(${Math.max(0,Math.min(parseInt(e)/100)).toFixed(2)})`],["xfa-font-vertical-scale",e=>`scaleY(${Math.max(0,Math.min(parseInt(e)/100)).toFixed(2)})`],["xfa-spacerun",""],["xfa-tab-stops",""],["font-size",(e,t)=>measureToString(.99*(e=t.fontSize=Math.abs(getMeasurement(e))))],["letter-spacing",e=>measureToString(getMeasurement(e))],["line-height",e=>measureToString(getMeasurement(e))],["margin",e=>measureToString(getMeasurement(e))],["margin-bottom",e=>measureToString(getMeasurement(e))],["margin-left",e=>measureToString(getMeasurement(e))],["margin-right",e=>measureToString(getMeasurement(e))],["margin-top",e=>measureToString(getMeasurement(e))],["text-indent",e=>measureToString(getMeasurement(e))],["font-family",e=>e],["vertical-align",e=>measureToString(getMeasurement(e))]]),Xn=/\s+/g,Zn=/[\r\n]+/g,Vn=/\r\n?/g;function mapStyle(e,t,i){const a=Object.create(null);if(!e)return a;const s=Object.create(null);for(const[t,i]of e.split(";").map((e=>e.split(":",2)))){const e=jn.get(t);if(""===e)continue;let r=i;e&&(r="string"==typeof e?e:e(i,s));t.endsWith("scale")?a.transform=a.transform?`${a[t]} ${r}`:r:a[t.replaceAll(/-([a-zA-Z])/g,((e,t)=>t.toUpperCase()))]=r}a.fontFamily&&setFontFamily({typeface:a.fontFamily,weight:a.fontWeight||"normal",posture:a.fontStyle||"normal",size:s.fontSize||0},t,t[Cr].fontFinder,a);if(i&&a.verticalAlign&&"0px"!==a.verticalAlign&&a.fontSize){const e=.583,t=.333,i=getMeasurement(a.fontSize);a.fontSize=measureToString(i*e);a.verticalAlign=measureToString(Math.sign(getMeasurement(a.verticalAlign))*i*t)}i&&a.fontSize&&(a.fontSize=`calc(${a.fontSize} * var(--scale-factor))`);fixTextIndent(a);return a}const zn=new Set(["body","html"]);class XhtmlObject extends XmlObject{constructor(e,t){super(On,t);this[Pn]=!1;this.style=e.style||""}[Ys](e){super[Ys](e);this.style=function checkStyle(e){return e.style?e.style.trim().split(/\s*;\s*/).filter((e=>!!e)).map((e=>e.split(/\s*:\s*/,2))).filter((([t,i])=>{"font-family"===t&&e[Cr].usedTypefaces.add(i);return Wn.has(t)})).map((e=>e.join(":"))).join(";"):""}(this)}[xs](){return!zn.has(this[kr])}[Mr](e,t=!1){if(t)this[Pn]=!0;else{e=e.replaceAll(Zn,"");this.style.includes("xfa-spacerun:yes")||(e=e.replaceAll(Xn," "))}e&&(this[Os]+=e)}[Ur](e,t=!0){const i=Object.create(null),a={top:NaN,bottom:NaN,left:NaN,right:NaN};let s=null;for(const[e,t]of this.style.split(";").map((e=>e.split(":",2))))switch(e){case"font-family":i.typeface=stripQuotes(t);break;case"font-size":i.size=getMeasurement(t);break;case"font-weight":i.weight=t;break;case"font-style":i.posture=t;break;case"letter-spacing":i.letterSpacing=getMeasurement(t);break;case"margin":const e=t.split(/ \t/).map((e=>getMeasurement(e)));switch(e.length){case 1:a.top=a.bottom=a.left=a.right=e[0];break;case 2:a.top=a.bottom=e[0];a.left=a.right=e[1];break;case 3:a.top=e[0];a.bottom=e[2];a.left=a.right=e[1];break;case 4:a.top=e[0];a.left=e[1];a.bottom=e[2];a.right=e[3]}break;case"margin-top":a.top=getMeasurement(t);break;case"margin-bottom":a.bottom=getMeasurement(t);break;case"margin-left":a.left=getMeasurement(t);break;case"margin-right":a.right=getMeasurement(t);break;case"line-height":s=getMeasurement(t)}e.pushData(i,a,s);if(this[Os])e.addString(this[Os]);else for(const t of this[rr]())"#text"!==t[kr]?t[Ur](e):e.addString(t[Os]);t&&e.popFont()}[jr](e){const t=[];this[Xs]={children:t};this[Js]({});if(0===t.length&&!this[Os])return HTMLResult.EMPTY;let i;i=this[Pn]?this[Os]?this[Os].replaceAll(Vn,"\n"):void 0:this[Os]||void 0;return HTMLResult.success({name:this[kr],attributes:{href:this.href,style:mapStyle(this.style,this,this[Pn])},children:t,value:i})}}class A extends XhtmlObject{constructor(e){super(e,"a");this.href=fixURL(e.href)||""}}class B extends XhtmlObject{constructor(e){super(e,"b")}[Ur](e){e.pushFont({weight:"bold"});super[Ur](e);e.popFont()}}class Body extends XhtmlObject{constructor(e){super(e,"body")}[jr](e){const t=super[jr](e),{html:i}=t;if(!i)return HTMLResult.EMPTY;i.name="div";i.attributes.class=["xfaRich"];return t}}class Br extends XhtmlObject{constructor(e){super(e,"br")}[Pr](){return"\n"}[Ur](e){e.addString("\n")}[jr](e){return HTMLResult.success({name:"br"})}}class Html extends XhtmlObject{constructor(e){super(e,"html")}[jr](e){const t=[];this[Xs]={children:t};this[Js]({});if(0===t.length)return HTMLResult.success({name:"div",attributes:{class:["xfaRich"],style:{}},value:this[Os]||""});if(1===t.length){const e=t[0];if(e.attributes?.class.includes("xfaRich"))return HTMLResult.success(e)}return HTMLResult.success({name:"div",attributes:{class:["xfaRich"],style:{}},children:t})}}class I extends XhtmlObject{constructor(e){super(e,"i")}[Ur](e){e.pushFont({posture:"italic"});super[Ur](e);e.popFont()}}class Li extends XhtmlObject{constructor(e){super(e,"li")}}class Ol extends XhtmlObject{constructor(e){super(e,"ol")}}class P extends XhtmlObject{constructor(e){super(e,"p")}[Ur](e){super[Ur](e,!1);e.addString("\n");e.addPara();e.popFont()}[Pr](){return this[Ir]()[rr]().at(-1)===this?super[Pr]():super[Pr]()+"\n"}}class Span extends XhtmlObject{constructor(e){super(e,"span")}}class Sub extends XhtmlObject{constructor(e){super(e,"sub")}}class Sup extends XhtmlObject{constructor(e){super(e,"sup")}}class Ul extends XhtmlObject{constructor(e){super(e,"ul")}}class XhtmlNamespace{static[zr](e,t){if(XhtmlNamespace.hasOwnProperty(e))return XhtmlNamespace[e](t)}static a(e){return new A(e)}static b(e){return new B(e)}static body(e){return new Body(e)}static br(e){return new Br(e)}static html(e){return new Html(e)}static i(e){return new I(e)}static li(e){return new Li(e)}static ol(e){return new Ol(e)}static p(e){return new P(e)}static span(e){return new Span(e)}static sub(e){return new Sub(e)}static sup(e){return new Sup(e)}static ul(e){return new Ul(e)}}const _n={config:ConfigNamespace,connection:ConnectionSetNamespace,datasets:DatasetsNamespace,localeSet:LocaleSetNamespace,signature:SignatureNamespace,stylesheet:StylesheetNamespace,template:TemplateNamespace,xdp:XdpNamespace,xhtml:XhtmlNamespace};class UnknownNamespace{constructor(e){this.namespaceId=e}[zr](e,t){return new XmlObject(this.namespaceId,e,t)}}class Root extends XFAObject{constructor(e){super(-1,"root",Object.create(null));this.element=null;this[lr]=e}[Nr](e){this.element=e;return!0}[Zs](){super[Zs]();if(this.element.template instanceof Template){this[lr].set(Jr,this.element);this.element.template[Yr](this[lr]);this.element.template[lr]=this[lr]}}}class Empty extends XFAObject{constructor(){super(-1,"",Object.create(null))}[Nr](e){return!1}}class Builder{constructor(e=null){this._namespaceStack=[];this._nsAgnosticLevel=0;this._namespacePrefixes=new Map;this._namespaces=new Map;this._nextNsId=Math.max(...Object.values(_r).map((({id:e})=>e)));this._currentNamespace=e||new UnknownNamespace(++this._nextNsId)}buildRoot(e){return new Root(e)}build({nsPrefix:e,name:t,attributes:i,namespace:a,prefixes:s}){const r=null!==a;if(r){this._namespaceStack.push(this._currentNamespace);this._currentNamespace=this._searchNamespace(a)}s&&this._addNamespacePrefix(s);if(i.hasOwnProperty(Rr)){const e=_n.datasets,t=i[Rr];let a=null;for(const[i,s]of Object.entries(t)){if(this._getNamespaceToUse(i)===e){a={xfa:s};break}}a?i[Rr]=a:delete i[Rr]}const n=this._getNamespaceToUse(e),g=n?.[zr](t,i)||new Empty;g[mr]()&&this._nsAgnosticLevel++;(r||s||g[mr]())&&(g[Ks]={hasNamespace:r,prefixes:s,nsAgnostic:g[mr]()});return g}isNsAgnostic(){return this._nsAgnosticLevel>0}_searchNamespace(e){let t=this._namespaces.get(e);if(t)return t;for(const[i,{check:a}]of Object.entries(_r))if(a(e)){t=_n[i];if(t){this._namespaces.set(e,t);return t}break}t=new UnknownNamespace(++this._nextNsId);this._namespaces.set(e,t);return t}_addNamespacePrefix(e){for(const{prefix:t,value:i}of e){const e=this._searchNamespace(i);let a=this._namespacePrefixes.get(t);if(!a){a=[];this._namespacePrefixes.set(t,a)}a.push(e)}}_getNamespaceToUse(e){if(!e)return this._currentNamespace;const t=this._namespacePrefixes.get(e);if(t?.length>0)return t.at(-1);warn(`Unknown namespace prefix: ${e}.`);return null}clean(e){const{hasNamespace:t,prefixes:i,nsAgnostic:a}=e;t&&(this._currentNamespace=this._namespaceStack.pop());i&&i.forEach((({prefix:e})=>{this._namespacePrefixes.get(e).pop()}));a&&this._nsAgnosticLevel--}}class XFAParser extends XMLParserBase{constructor(e=null,t=!1){super();this._builder=new Builder(e);this._stack=[];this._globalData={usedTypefaces:new Set};this._ids=new Map;this._current=this._builder.buildRoot(this._ids);this._errorCode=ys;this._whiteRegex=/^\s+$/;this._nbsps=/\xa0+/g;this._richText=t}parse(e){this.parseXml(e);if(this._errorCode===ys){this._current[Zs]();return this._current.element}}onText(e){e=e.replace(this._nbsps,(e=>e.slice(1)+" "));this._richText||this._current[xs]()?this._current[Mr](e,this._richText):this._whiteRegex.test(e)||this._current[Mr](e.trim())}onCdata(e){this._current[Mr](e)}_mkAttributes(e,t){let i=null,a=null;const s=Object.create({});for(const{name:r,value:n}of e)if("xmlns"===r)i?warn(`XFA - multiple namespace definition in <${t}>`):i=n;else if(r.startsWith("xmlns:")){const e=r.substring(6);a||(a=[]);a.push({prefix:e,value:n})}else{const e=r.indexOf(":");if(-1===e)s[r]=n;else{let t=s[Rr];t||(t=s[Rr]=Object.create(null));const[i,a]=[r.slice(0,e),r.slice(e+1)];(t[i]||=Object.create(null))[a]=n}}return[i,a,s]}_getNameAndPrefix(e,t){const i=e.indexOf(":");return-1===i?[e,null]:[e.substring(i+1),t?"":e.substring(0,i)]}onBeginElement(e,t,i){const[a,s,r]=this._mkAttributes(t,e),[n,g]=this._getNameAndPrefix(e,this._builder.isNsAgnostic()),o=this._builder.build({nsPrefix:g,name:n,attributes:r,namespace:a,prefixes:s});o[Cr]=this._globalData;if(i){o[Zs]();this._current[Nr](o)&&o[Kr](this._ids);o[Ys](this._builder)}else{this._stack.push(this._current);this._current=o}}onEndElement(e){const t=this._current;if(t[ur]()&&"string"==typeof t[Os]){const e=new XFAParser;e._globalData=this._globalData;const i=e.parse(t[Os]);t[Os]=null;t[Nr](i)}t[Zs]();this._current=this._stack.pop();this._current[Nr](t)&&t[Kr](this._ids);t[Ys](this._builder)}onError(e){this._errorCode=e}}class XFAFactory{constructor(e){try{this.root=(new XFAParser).parse(XFAFactory._createDocument(e));const t=new Binder(this.root);this.form=t.bind();this.dataHandler=new DataHandler(this.root,t.getData());this.form[Cr].template=this.form}catch(e){warn(`XFA - an error occurred during parsing and binding: ${e}`)}}isValid(){return this.root&&this.form}_createPagesHelper(){const e=this.form[Wr]();return new Promise(((t,i)=>{const nextIteration=()=>{try{const i=e.next();i.done?t(i.value):setTimeout(nextIteration,0)}catch(e){i(e)}};setTimeout(nextIteration,0)}))}async _createPages(){try{this.pages=await this._createPagesHelper();this.dims=this.pages.children.map((e=>{const{width:t,height:i}=e.attributes.style;return[0,0,parseInt(t),parseInt(i)]}))}catch(e){warn(`XFA - an error occurred during layout: ${e}`)}}getBoundingBox(e){return this.dims[e]}async getNumPages(){this.pages||await this._createPages();return this.dims.length}setImages(e){this.form[Cr].images=e}setFonts(e){this.form[Cr].fontFinder=new FontFinder(e);const t=[];for(let e of this.form[Cr].usedTypefaces){e=stripQuotes(e);this.form[Cr].fontFinder.find(e)||t.push(e)}return t.length>0?t:null}appendFonts(e,t){this.form[Cr].fontFinder.add(e,t)}async getPages(){this.pages||await this._createPages();const e=this.pages;this.pages=null;return e}serializeData(e){return this.dataHandler.serialize(e)}static _createDocument(e){return e["/xdp:xdp"]?Object.values(e).join(""):e["xdp:xdp"]}static getRichTextAsHtml(e){if(!e||"string"!=typeof e)return null;try{let t=new XFAParser(XhtmlNamespace,!0).parse(e);if(!["body","xhtml"].includes(t[kr])){const e=XhtmlNamespace.body({});e[Hs](t);t=e}const i=t[jr]();if(!i.success)return null;const{html:a}=i,{attributes:s}=a;if(s){s.class&&(s.class=s.class.filter((e=>!e.startsWith("xfa"))));s.dir="auto"}return{html:a,str:t[Pr]()}}catch(e){warn(`XFA - an error occurred during parsing of rich text: ${e}`)}return null}}class AnnotationFactory{static createGlobals(e){return Promise.all([e.ensureCatalog("acroForm"),e.ensureDoc("xfaDatasets"),e.ensureCatalog("structTreeRoot"),e.ensureCatalog("baseUrl"),e.ensureCatalog("attachments")]).then((([t,i,a,s,r])=>({pdfManager:e,acroForm:t instanceof Dict?t:Dict.empty,xfaDatasets:i,structTreeRoot:a,baseUrl:s,attachments:r})),(e=>{warn(`createGlobals: "${e}".`);return null}))}static async create(e,t,i,a,s,r,n){const g=s?await this._getPageIndex(e,t,i.pdfManager):null;return i.pdfManager.ensure(this,"_create",[e,t,i,a,s,r,g,n])}static _create(e,t,i,a,s=!1,r=null,n=null,g=null){const o=e.fetchIfRef(t);if(!(o instanceof Dict))return;const{acroForm:c,pdfManager:C}=i,h=t instanceof Ref?t.toString():`annot_${a.createObjId()}`;let l=o.get("Subtype");l=l instanceof Name?l.name:null;const Q={xref:e,ref:t,dict:o,subtype:l,id:h,annotationGlobals:i,collectFields:s,orphanFields:r,needAppearances:!s&&!0===c.get("NeedAppearances"),pageIndex:n,evaluatorOptions:C.evaluatorOptions,pageRef:g};switch(l){case"Link":return new LinkAnnotation(Q);case"Text":return new TextAnnotation(Q);case"Widget":let e=getInheritableProperty({dict:o,key:"FT"});e=e instanceof Name?e.name:null;switch(e){case"Tx":return new TextWidgetAnnotation(Q);case"Btn":return new ButtonWidgetAnnotation(Q);case"Ch":return new ChoiceWidgetAnnotation(Q);case"Sig":return new SignatureWidgetAnnotation(Q)}warn(`Unimplemented widget field type "${e}", falling back to base field type.`);return new WidgetAnnotation(Q);case"Popup":return new PopupAnnotation(Q);case"FreeText":return new FreeTextAnnotation(Q);case"Line":return new LineAnnotation(Q);case"Square":return new SquareAnnotation(Q);case"Circle":return new CircleAnnotation(Q);case"PolyLine":return new PolylineAnnotation(Q);case"Polygon":return new PolygonAnnotation(Q);case"Caret":return new CaretAnnotation(Q);case"Ink":return new InkAnnotation(Q);case"Highlight":return new HighlightAnnotation(Q);case"Underline":return new UnderlineAnnotation(Q);case"Squiggly":return new SquigglyAnnotation(Q);case"StrikeOut":return new StrikeOutAnnotation(Q);case"Stamp":return new StampAnnotation(Q);case"FileAttachment":return new FileAttachmentAnnotation(Q);default:s||warn(l?`Unimplemented annotation type "${l}", falling back to base annotation.`:"Annotation is missing the required /Subtype.");return new Annotation(Q)}}static async _getPageIndex(e,t,i){try{const a=await e.fetchIfRefAsync(t);if(!(a instanceof Dict))return-1;const s=a.getRaw("P");if(s instanceof Ref)try{return await i.ensureCatalog("getPageIndex",[s])}catch(e){info(`_getPageIndex -- not a valid page reference: "${e}".`)}if(a.has("Kids"))return-1;const r=await i.ensureDoc("numPages");for(let e=0;ee/255))}function getQuadPoints(e,t){const i=e.getArray("QuadPoints");if(!isNumberArray(i,null)||0===i.length||i.length%8>0)return null;const a=new Float32Array(i.length);for(let e=0,s=i.length;et[2]||Et[3]))return null;a.set([l,u,Q,u,l,E,Q,E],e)}return a}function getTransformMatrix(e,t,i){const[a,s,r,n]=Util.getAxialAlignedBoundingBox(t,i);if(a===r||s===n)return[1,0,0,1,e[0],e[1]];const g=(e[2]-e[0])/(r-a),o=(e[3]-e[1])/(n-s);return[g,0,0,o,e[0]-a*g,e[1]-s*o]}class Annotation{constructor(e){const{dict:t,xref:i,annotationGlobals:a,ref:s,orphanFields:r}=e,n=r?.get(s);n&&t.set("Parent",n);this.setTitle(t.get("T"));this.setContents(t.get("Contents"));this.setModificationDate(t.get("M"));this.setFlags(t.get("F"));this.setRectangle(t.getArray("Rect"));this.setColor(t.getArray("C"));this.setBorderStyle(t);this.setAppearance(t);this.setOptionalContent(t);const g=t.get("MK");this.setBorderAndBackgroundColors(g);this.setRotation(g,t);this.ref=e.ref instanceof Ref?e.ref:null;this._streams=[];this.appearance&&this._streams.push(this.appearance);const o=!!(this.flags&eA),c=!!(this.flags&tA);this.data={annotationFlags:this.flags,borderStyle:this.borderStyle,color:this.color,backgroundColor:this.backgroundColor,borderColor:this.borderColor,rotation:this.rotation,contentsObj:this._contents,hasAppearance:!!this.appearance,id:e.id,modificationDate:this.modificationDate,rect:this.rectangle,subtype:e.subtype,hasOwnCanvas:!1,noRotate:!!(this.flags&$),noHTML:o&&c,isEditable:!1,structParent:-1};if(a.structTreeRoot){let i=t.get("StructParent");this.data.structParent=i=Number.isInteger(i)&&i>=0?i:-1;a.structTreeRoot.addAnnotationIdToPage(e.pageRef,i)}if(e.collectFields){const a=t.get("Kids");if(Array.isArray(a)){const e=[];for(const t of a)t instanceof Ref&&e.push(t.toString());0!==e.length&&(this.data.kidIds=e)}this.data.actions=collectActions(i,t,dA);this.data.fieldName=this._constructFieldName(t);this.data.pageIndex=e.pageIndex}const C=t.get("IT");C instanceof Name&&(this.data.it=C.name);this._isOffscreenCanvasSupported=e.evaluatorOptions.isOffscreenCanvasSupported;this._fallbackFontDict=null;this._needAppearances=!1}_hasFlag(e,t){return!!(e&t)}_buildFlags(e,t){let{flags:i}=this;if(void 0===e){if(void 0===t)return;return t?i&~_:i&~z|_}if(e){i|=_;return t?i&~AA|z:i&~z|AA}i&=~(z|AA);return t?i&~_:i|_}_isViewable(e){return!this._hasFlag(e,V)&&!this._hasFlag(e,AA)}_isPrintable(e){return this._hasFlag(e,_)&&!this._hasFlag(e,z)&&!this._hasFlag(e,V)}mustBeViewed(e,t){const i=e?.get(this.data.id)?.noView;return void 0!==i?!i:this.viewable&&!this._hasFlag(this.flags,z)}mustBePrinted(e){const t=e?.get(this.data.id)?.noPrint;return void 0!==t?!t:this.printable}mustBeViewedWhenEditing(e,t=null){return e?!this.data.isEditable:!t?.has(this.data.id)}get viewable(){return null!==this.data.quadPoints&&(0===this.flags||this._isViewable(this.flags))}get printable(){return null!==this.data.quadPoints&&(0!==this.flags&&this._isPrintable(this.flags))}_parseStringHelper(e){const t="string"==typeof e?stringToPDFString(e):"";return{str:t,dir:t&&"rtl"===bidi(t).dir?"rtl":"ltr"}}setDefaultAppearance(e){const{dict:t,annotationGlobals:i}=e,a=getInheritableProperty({dict:t,key:"DA"})||i.acroForm.get("DA");this._defaultAppearance="string"==typeof a?a:"";this.data.defaultAppearanceData=parseDefaultAppearance(this._defaultAppearance)}setTitle(e){this._title=this._parseStringHelper(e)}setContents(e){this._contents=this._parseStringHelper(e)}setModificationDate(e){this.modificationDate="string"==typeof e?e:null}setFlags(e){this.flags=Number.isInteger(e)&&e>0?e:0;this.flags&V&&"Annotation"!==this.constructor.name&&(this.flags^=V)}hasFlag(e){return this._hasFlag(this.flags,e)}setRectangle(e){this.rectangle=lookupNormalRect(e,[0,0,0,0])}setColor(e){this.color=getRgbColor(e)}setLineEndings(e){this.lineEndings=["None","None"];if(Array.isArray(e)&&2===e.length)for(let t=0;t<2;t++){const i=e[t];if(i instanceof Name)switch(i.name){case"None":continue;case"Square":case"Circle":case"Diamond":case"OpenArrow":case"ClosedArrow":case"Butt":case"ROpenArrow":case"RClosedArrow":case"Slash":this.lineEndings[t]=i.name;continue}warn(`Ignoring invalid lineEnding: ${i}`)}}setRotation(e,t){this.rotation=0;let i=e instanceof Dict?e.get("R")||0:t.get("Rotate")||0;if(Number.isInteger(i)&&0!==i){i%=360;i<0&&(i+=360);i%90==0&&(this.rotation=i)}}setBorderAndBackgroundColors(e){if(e instanceof Dict){this.borderColor=getRgbColor(e.getArray("BC"),null);this.backgroundColor=getRgbColor(e.getArray("BG"),null)}else this.borderColor=this.backgroundColor=null}setBorderStyle(e){this.borderStyle=new AnnotationBorderStyle;if(e instanceof Dict)if(e.has("BS")){const t=e.get("BS");if(t instanceof Dict){const e=t.get("Type");if(!e||isName(e,"Border")){this.borderStyle.setWidth(t.get("W"),this.rectangle);this.borderStyle.setStyle(t.get("S"));this.borderStyle.setDashArray(t.getArray("D"))}}}else if(e.has("Border")){const t=e.getArray("Border");if(Array.isArray(t)&&t.length>=3){this.borderStyle.setHorizontalCornerRadius(t[0]);this.borderStyle.setVerticalCornerRadius(t[1]);this.borderStyle.setWidth(t[2],this.rectangle);4===t.length&&this.borderStyle.setDashArray(t[3],!0)}}else this.borderStyle.setWidth(0)}setAppearance(e){this.appearance=null;const t=e.get("AP");if(!(t instanceof Dict))return;const i=t.get("N");if(i instanceof BaseStream){this.appearance=i;return}if(!(i instanceof Dict))return;const a=e.get("AS");if(!(a instanceof Name&&i.has(a.name)))return;const s=i.get(a.name);s instanceof BaseStream&&(this.appearance=s)}setOptionalContent(e){this.oc=null;const t=e.get("OC");t instanceof Name?warn("setOptionalContent: Support for /Name-entry is not implemented."):t instanceof Dict&&(this.oc=t)}loadResources(e,t){return t.dict.getAsync("Resources").then((t=>{if(!t)return;return new ObjectLoader(t,e,t.xref).load().then((function(){return t}))}))}async getOperatorList(e,t,a,s){const{hasOwnCanvas:r,id:n,rect:g}=this.data;let c=this.appearance;const C=!!(r&&a&o);if(C&&(g[0]===g[2]||g[1]===g[3])){this.data.hasOwnCanvas=!1;return{opList:new OperatorList,separateForm:!1,separateCanvas:!1}}if(!c){if(!C)return{opList:new OperatorList,separateForm:!1,separateCanvas:!1};c=new StringStream("");c.dict=new Dict}const h=c.dict,l=await this.loadResources(["ExtGState","ColorSpace","Pattern","Shading","XObject","Font"],c),Q=lookupRect(h.getArray("BBox"),[0,0,1,1]),E=lookupMatrix(h.getArray("Matrix"),i),u=getTransformMatrix(g,Q,E),d=new OperatorList;let f;this.oc&&(f=await e.parseMarkedContentProps(this.oc,null));void 0!==f&&d.addOp(Ye,["OC",f]);d.addOp(je,[n,g,u,E,C]);await e.getOperatorList({stream:c,task:t,resources:l,operatorList:d,fallbackFontDict:this._fallbackFontDict});d.addOp(Xe,[]);void 0!==f&&d.addOp(ve,[]);this.reset();return{opList:d,separateForm:!1,separateCanvas:C}}async save(e,t,i,a){return null}get hasTextContent(){return!1}async extractTextContent(e,t,i){if(!this.appearance)return;const a=await this.loadResources(["ExtGState","Font","Properties","XObject"],this.appearance),s=[],r=[];let n=null;const g={desiredSize:Math.Infinity,ready:!0,enqueue(e,t){for(const t of e.items)if(void 0!==t.str){n||=t.transform.slice(-2);r.push(t.str);if(t.hasEOL){s.push(r.join("").trimEnd());r.length=0}}}};await e.getTextContent({stream:this.appearance,task:t,resources:a,includeMarkedContent:!0,keepWhiteSpace:!0,sink:g,viewBox:i});this.reset();r.length&&s.push(r.join("").trimEnd());if(s.length>1||s[0]){const e=this.appearance.dict,t=lookupRect(e.getArray("BBox"),null),i=lookupMatrix(e.getArray("Matrix"),null);this.data.textPosition=this._transformPoint(n,t,i);this.data.textContent=s}}_transformPoint(e,t,i){const{rect:a}=this.data;t||=[0,0,1,1];i||=[1,0,0,1,0,0];const s=getTransformMatrix(a,t,i);s[4]-=a[0];s[5]-=a[1];e=Util.applyTransform(e,s);return Util.applyTransform(e,i)}getFieldObject(){return this.data.kidIds?{id:this.data.id,actions:this.data.actions,name:this.data.fieldName,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,type:"",kidIds:this.data.kidIds,page:this.data.pageIndex,rotation:this.rotation}:null}reset(){for(const e of this._streams)e.reset()}_constructFieldName(e){if(!e.has("T")&&!e.has("Parent")){warn("Unknown field name, falling back to empty field name.");return""}if(!e.has("Parent"))return stringToPDFString(e.get("T"));const t=[];e.has("T")&&t.unshift(stringToPDFString(e.get("T")));let i=e;const a=new RefSet;e.objId&&a.put(e.objId);for(;i.has("Parent");){i=i.get("Parent");if(!(i instanceof Dict)||i.objId&&a.has(i.objId))break;i.objId&&a.put(i.objId);i.has("T")&&t.unshift(stringToPDFString(i.get("T")))}return t.join(".")}}class AnnotationBorderStyle{constructor(){this.width=1;this.rawWidth=1;this.style=lA;this.dashArray=[3];this.horizontalCornerRadius=0;this.verticalCornerRadius=0}setWidth(e,t=[0,0,0,0]){if(e instanceof Name)this.width=0;else if("number"==typeof e){if(e>0){this.rawWidth=e;const i=(t[2]-t[0])/2,a=(t[3]-t[1])/2;if(i>0&&a>0&&(e>i||e>a)){warn(`AnnotationBorderStyle.setWidth - ignoring width: ${e}`);e=1}}this.width=e}}setStyle(e){if(e instanceof Name)switch(e.name){case"S":this.style=lA;break;case"D":this.style=BA;break;case"B":this.style=QA;break;case"I":this.style=EA;break;case"U":this.style=uA}}setDashArray(e,t=!1){if(Array.isArray(e)){let i=!0,a=!0;for(const t of e){if(!(+t>=0)){i=!1;break}t>0&&(a=!1)}if(0===e.length||i&&!a){this.dashArray=e;t&&this.setStyle(Name.get("D"))}else this.width=0}else e&&(this.width=0)}setHorizontalCornerRadius(e){Number.isInteger(e)&&(this.horizontalCornerRadius=e)}setVerticalCornerRadius(e){Number.isInteger(e)&&(this.verticalCornerRadius=e)}}class MarkupAnnotation extends Annotation{constructor(e){super(e);const{dict:t}=e;if(t.has("IRT")){const e=t.getRaw("IRT");this.data.inReplyTo=e instanceof Ref?e.toString():null;const i=t.get("RT");this.data.replyType=i instanceof Name?i.name:Z}let i=null;if(this.data.replyType===X){const e=t.get("IRT");this.setTitle(e.get("T"));this.data.titleObj=this._title;this.setContents(e.get("Contents"));this.data.contentsObj=this._contents;if(e.has("CreationDate")){this.setCreationDate(e.get("CreationDate"));this.data.creationDate=this.creationDate}else this.data.creationDate=null;if(e.has("M")){this.setModificationDate(e.get("M"));this.data.modificationDate=this.modificationDate}else this.data.modificationDate=null;i=e.getRaw("Popup");if(e.has("C")){this.setColor(e.getArray("C"));this.data.color=this.color}else this.data.color=null}else{this.data.titleObj=this._title;this.setCreationDate(t.get("CreationDate"));this.data.creationDate=this.creationDate;i=t.getRaw("Popup");t.has("C")||(this.data.color=null)}this.data.popupRef=i instanceof Ref?i.toString():null;t.has("RC")&&(this.data.richText=XFAFactory.getRichTextAsHtml(t.get("RC")))}setCreationDate(e){this.creationDate="string"==typeof e?e:null}_setDefaultAppearance({xref:e,extra:t,strokeColor:i,fillColor:a,blendMode:s,strokeAlpha:r,fillAlpha:n,pointsCallback:g}){let o=Number.MAX_VALUE,c=Number.MAX_VALUE,C=Number.MIN_VALUE,h=Number.MIN_VALUE;const l=["q"];t&&l.push(t);i&&l.push(`${i[0]} ${i[1]} ${i[2]} RG`);a&&l.push(`${a[0]} ${a[1]} ${a[2]} rg`);const Q=this.data.quadPoints||Float32Array.from([this.rectangle[0],this.rectangle[3],this.rectangle[2],this.rectangle[3],this.rectangle[0],this.rectangle[1],this.rectangle[2],this.rectangle[1]]);for(let e=0,t=Q.length;e"string"==typeof e)).map((e=>stringToPDFString(e))):e instanceof Name?stringToPDFString(e.name):"string"==typeof e?stringToPDFString(e):null}hasFieldFlag(e){return!!(this.data.fieldFlags&e)}_isViewable(e){return!0}mustBeViewed(e,t){return t?this.viewable:super.mustBeViewed(e,t)&&!this._hasFlag(this.flags,AA)}getRotationMatrix(e){let t=e?.get(this.data.id)?.rotation;void 0===t&&(t=this.rotation);if(0===t)return i;return getRotationMatrix(t,this.data.rect[2]-this.data.rect[0],this.data.rect[3]-this.data.rect[1])}getBorderAndBackgroundAppearances(e){let t=e?.get(this.data.id)?.rotation;void 0===t&&(t=this.rotation);if(!this.backgroundColor&&!this.borderColor)return"";const i=this.data.rect[2]-this.data.rect[0],a=this.data.rect[3]-this.data.rect[1],s=0===t||180===t?`0 0 ${i} ${a} re`:`0 0 ${a} ${i} re`;let r="";this.backgroundColor&&(r=`${getPdfColor(this.backgroundColor,!0)} ${s} f `);if(this.borderColor){r+=`${this.borderStyle.width||1} w ${getPdfColor(this.borderColor,!1)} ${s} S `}return r}async getOperatorList(e,t,i,a){if(i&h&&!(this instanceof SignatureWidgetAnnotation)&&!this.data.noHTML&&!this.data.hasOwnCanvas)return{opList:new OperatorList,separateForm:!0,separateCanvas:!1};if(!this._hasText)return super.getOperatorList(e,t,i,a);const s=await this._getAppearance(e,t,i,a);if(this.appearance&&null===s)return super.getOperatorList(e,t,i,a);const r=new OperatorList;if(!this._defaultAppearance||null===s)return{opList:r,separateForm:!1,separateCanvas:!1};const n=!!(this.data.hasOwnCanvas&&i&o),g=[0,0,this.data.rect[2]-this.data.rect[0],this.data.rect[3]-this.data.rect[1]],c=getTransformMatrix(this.data.rect,g,[1,0,0,1,0,0]);let C;this.oc&&(C=await e.parseMarkedContentProps(this.oc,null));void 0!==C&&r.addOp(Ye,["OC",C]);r.addOp(je,[this.data.id,this.data.rect,c,this.getRotationMatrix(a),n]);const l=new StringStream(s);await e.getOperatorList({stream:l,task:t,resources:this._fieldResources.mergedResources,operatorList:r});r.addOp(Xe,[]);void 0!==C&&r.addOp(ve,[]);return{opList:r,separateForm:!1,separateCanvas:n}}_getMKDict(e){const t=new Dict(null);e&&t.set("R",e);this.borderColor&&t.set("BC",getPdfColorArray(this.borderColor));this.backgroundColor&&t.set("BG",getPdfColorArray(this.backgroundColor));return t.size>0?t:null}amendSavedDict(e,t){}setValue(e,t,i,a){const{dict:s,ref:r}=function getParentToUpdate(e,t,i){const a=new RefSet,s=e,r={dict:null,ref:null};for(;e instanceof Dict&&!a.has(t);){a.put(t);if(e.has("T"))break;if(!((t=e.getRaw("Parent"))instanceof Ref))return r;e=i.fetch(t)}if(e instanceof Dict&&e!==s){r.dict=e;r.ref=t}return r}(e,this.ref,i);if(s){if(!a.has(r)){const e=s.clone();e.set("V",t);a.put(r,{data:e});return e}}else e.set("V",t);return null}async save(e,t,a,s){const r=a?.get(this.data.id),n=this._buildFlags(r?.noView,r?.noPrint);let g=r?.value,o=r?.rotation;if(g===this.data.fieldValue||void 0===g){if(!this._hasValueFromXFA&&void 0===o&&void 0===n)return;g||=this.data.fieldValue}if(void 0===o&&!this._hasValueFromXFA&&Array.isArray(g)&&Array.isArray(this.data.fieldValue)&&isArrayEqual(g,this.data.fieldValue)&&void 0===n)return;void 0===o&&(o=this.rotation);let c=null;if(!this._needAppearances){c=await this._getAppearance(e,t,C,a);if(null===c&&void 0===n)return}let h=!1;if(c?.needAppearances){h=!0;c=null}const{xref:l}=e,Q=l.fetchIfRef(this.ref);if(!(Q instanceof Dict))return;const E=new Dict(l);for(const e of Q.getKeys())"AP"!==e&&E.set(e,Q.getRaw(e));if(void 0!==n){E.set("F",n);if(null===c&&!h){const e=Q.getRaw("AP");e&&E.set("AP",e)}}const u={path:this.data.fieldName,value:g},d=this.setValue(E,Array.isArray(g)?g.map(stringToAsciiOrUTF16BE):stringToAsciiOrUTF16BE(g),l,s);this.amendSavedDict(a,d||E);const f=this._getMKDict(o);f&&E.set("MK",f);s.put(this.ref,{data:E,xfa:u,needAppearances:h});if(null!==c){const e=l.getNewTemporaryRef(),t=new Dict(l);E.set("AP",t);t.set("N",e);const r=this._getSaveFieldResources(l),n=new StringStream(c),g=n.dict=new Dict(l);g.set("Subtype",Name.get("Form"));g.set("Resources",r);g.set("BBox",[0,0,this.data.rect[2]-this.data.rect[0],this.data.rect[3]-this.data.rect[1]]);const o=this.getRotationMatrix(a);o!==i&&g.set("Matrix",o);s.put(e,{data:n,xfa:null,needAppearances:!1})}E.set("M",`D:${getModificationDate()}`)}async _getAppearance(e,t,i,a){if(this.hasFieldFlag(rA))return null;const s=a?.get(this.data.id);let r,g;if(s){r=s.formattedValue||s.value;g=s.rotation}if(void 0===g&&void 0===r&&!this._needAppearances&&(!this._hasValueFromXFA||this.appearance))return null;const o=this.getBorderAndBackgroundAppearances(a);if(void 0===r){r=this.data.fieldValue;if(!r)return`/Tx BMC q ${o}Q EMC`}Array.isArray(r)&&1===r.length&&(r=r[0]);assert("string"==typeof r,"Expected `value` to be a string.");r=r.trimEnd();if(this.data.combo){const e=this.data.options.find((({exportValue:e})=>r===e));r=e?.displayValue||r}if(""===r)return`/Tx BMC q ${o}Q EMC`;void 0===g&&(g=this.rotation);let c,h=-1;if(this.data.multiLine){c=r.split(/\r\n?|\n/).map((e=>e.normalize("NFC")));h=c.length}else c=[r.replace(/\r\n?|\n/,"").normalize("NFC")];let l=this.data.rect[3]-this.data.rect[1],Q=this.data.rect[2]-this.data.rect[0];90!==g&&270!==g||([Q,l]=[l,Q]);this._defaultAppearance||(this.data.defaultAppearanceData=parseDefaultAppearance(this._defaultAppearance="/Helvetica 0 Tf 0 g"));let E,u,d,f=await WidgetAnnotation._getFontData(e,t,this.data.defaultAppearanceData,this._fieldResources.mergedResources);const p=[];let m=!1;for(const e of c){const t=f.encodeString(e);t.length>1&&(m=!0);p.push(t.join(""))}if(m&&i&C)return{needAppearances:!0};if(m&&this._isOffscreenCanvasSupported){const i=this.data.comb?"monospace":"sans-serif",a=new FakeUnicodeFont(e.xref,i),s=a.createFontResources(c.join("")),n=s.getRaw("Font");if(this._fieldResources.mergedResources.has("Font")){const e=this._fieldResources.mergedResources.get("Font");for(const t of n.getKeys())e.set(t,n.getRaw(t))}else this._fieldResources.mergedResources.set("Font",n);const g=a.fontName.name;f=await WidgetAnnotation._getFontData(e,t,{fontName:g,fontSize:0},s);for(let e=0,t=p.length;e2)return`/Tx BMC q ${o}BT `+E+` 1 0 0 1 ${numberToString(2)} ${numberToString(b)} Tm (${escapeString(p[0])}) Tj ET Q EMC`;return`/Tx BMC q ${o}BT `+E+` 1 0 0 1 0 0 Tm ${this._renderText(p[0],f,u,Q,D,{shift:0},2,b)} ET Q EMC`}static async _getFontData(e,t,i,a){const s=new OperatorList,r={font:null,clone(){return this}},{fontName:n,fontSize:g}=i;await e.handleSetFont(a,[n&&Name.get(n),g],null,s,t,r,null);return r.font}_getTextWidth(e,t){return t.charsToGlyphs(e).reduce(((e,t)=>e+t.width),0)/1e3}_computeFontSize(e,t,i,a,r){let{fontSize:n}=this.data.defaultAppearanceData,g=(n||12)*s,o=Math.round(e/g);if(!n){const roundWithTwoDigits=e=>Math.floor(100*e)/100;if(-1===r){const r=this._getTextWidth(i,a);n=roundWithTwoDigits(Math.min(e/s,t/r));o=1}else{const c=i.split(/\r\n?|\n/),C=[];for(const e of c){const t=a.encodeString(e).join(""),i=a.charsToGlyphs(t),s=a.getCharPositions(t);C.push({line:t,glyphs:i,positions:s})}const isTooBig=i=>{let s=0;for(const r of C){s+=this._splitLine(null,a,i,t,r).length*i;if(s>e)return!0}return!1};o=Math.max(o,r);for(;;){g=e/o;n=roundWithTwoDigits(g/s);if(!isTooBig(n))break;o++}}const{fontName:c,fontColor:C}=this.data.defaultAppearanceData;this._defaultAppearance=function createDefaultAppearance({fontSize:e,fontName:t,fontColor:i}){return`/${escapePDFName(t)} ${e} Tf ${getPdfColor(i,!0)}`}({fontSize:n,fontName:c,fontColor:C})}return[this._defaultAppearance,n,e/o]}_renderText(e,t,i,a,s,r,n,g){let o;if(1===s){o=(a-this._getTextWidth(e,t)*i)/2}else if(2===s){o=a-this._getTextWidth(e,t)*i-n}else o=n;const c=numberToString(o-r.shift);r.shift=o;return`${c} ${g=numberToString(g)} Td (${escapeString(e)}) Tj`}_getSaveFieldResources(e){const{localResources:t,appearanceResources:i,acroFormResources:a}=this._fieldResources,s=this.data.defaultAppearanceData?.fontName;if(!s)return t||Dict.empty;for(const e of[t,i])if(e instanceof Dict){const t=e.get("Font");if(t instanceof Dict&&t.has(s))return e}if(a instanceof Dict){const i=a.get("Font");if(i instanceof Dict&&i.has(s)){const a=new Dict(e);a.set(s,i.getRaw(s));const r=new Dict(e);r.set("Font",a);return Dict.merge({xref:e,dictArray:[r,t],mergeSubDicts:!0})}}return t||Dict.empty}getFieldObject(){return null}}class TextWidgetAnnotation extends WidgetAnnotation{constructor(e){super(e);const{dict:t}=e;if(t.has("PMD")){this.flags|=z;this.data.hidden=!0;warn("Barcodes are not supported")}this.data.hasOwnCanvas=this.data.readOnly&&!this.data.noHTML;this._hasText=!0;"string"!=typeof this.data.fieldValue&&(this.data.fieldValue="");let i=getInheritableProperty({dict:t,key:"Q"});(!Number.isInteger(i)||i<0||i>2)&&(i=null);this.data.textAlignment=i;let a=getInheritableProperty({dict:t,key:"MaxLen"});(!Number.isInteger(a)||a<0)&&(a=0);this.data.maxLen=a;this.data.multiLine=this.hasFieldFlag(sA);this.data.comb=this.hasFieldFlag(hA)&&!this.hasFieldFlag(sA)&&!this.hasFieldFlag(rA)&&!this.hasFieldFlag(IA)&&0!==this.data.maxLen;this.data.doNotScroll=this.hasFieldFlag(CA)}get hasTextContent(){return!!this.appearance&&!this._needAppearances}_getCombAppearance(e,t,i,a,s,r,n,g,o,c,C){const h=s/this.data.maxLen,l=this.getBorderAndBackgroundAppearances(C),Q=[],E=t.getCharPositions(i);for(const[e,t]of E)Q.push(`(${escapeString(i.substring(e,t))}) Tj`);const u=Q.join(` ${numberToString(h)} 0 Td `);return`/Tx BMC q ${l}BT `+e+` 1 0 0 1 ${numberToString(n)} ${numberToString(g+o)} Tm ${u} ET Q EMC`}_getMultilineAppearance(e,t,i,a,s,r,n,g,o,c,C,h){const l=[],Q=s-2*g,E={shift:0};for(let e=0,r=t.length;ea){o.push(e.substring(l,i));l=i;Q=u;c=-1;h=-1}else{Q+=u;c=i;C=s;h=t}else if(Q+u>a)if(-1!==c){o.push(e.substring(l,C));l=C;t=h+1;c=-1;Q=0}else{o.push(e.substring(l,i));l=i;Q=u}else Q+=u}lt?`\\${t}`:"\\s+"));new RegExp(`^\\s*${r}\\s*$`).test(this.data.fieldValue)&&(this.data.textContent=this.data.fieldValue.split("\n"))}getFieldObject(){return{id:this.data.id,value:this.data.fieldValue,defaultValue:this.data.defaultFieldValue||"",multiline:this.data.multiLine,password:this.hasFieldFlag(rA),charLimit:this.data.maxLen,comb:this.data.comb,editable:!this.data.readOnly,hidden:this.data.hidden,name:this.data.fieldName,rect:this.data.rect,actions:this.data.actions,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,type:"text"}}}class ButtonWidgetAnnotation extends WidgetAnnotation{constructor(e){super(e);this.checkedAppearance=null;this.uncheckedAppearance=null;this.data.checkBox=!this.hasFieldFlag(nA)&&!this.hasFieldFlag(gA);this.data.radioButton=this.hasFieldFlag(nA)&&!this.hasFieldFlag(gA);this.data.pushButton=this.hasFieldFlag(gA);this.data.isTooltipOnly=!1;if(this.data.checkBox)this._processCheckBox(e);else if(this.data.radioButton)this._processRadioButton(e);else if(this.data.pushButton){this.data.hasOwnCanvas=!0;this.data.noHTML=!1;this._processPushButton(e)}else warn("Invalid field flags for button widget annotation")}async getOperatorList(e,t,a,s){if(this.data.pushButton)return super.getOperatorList(e,t,a,!1,s);let r=null,n=null;if(s){const e=s.get(this.data.id);r=e?e.value:null;n=e?e.rotation:null}if(null===r&&this.appearance)return super.getOperatorList(e,t,a,s);null==r&&(r=this.data.checkBox?this.data.fieldValue===this.data.exportValue:this.data.fieldValue===this.data.buttonValue);const g=r?this.checkedAppearance:this.uncheckedAppearance;if(g){const r=this.appearance,o=lookupMatrix(g.dict.getArray("Matrix"),i);n&&g.dict.set("Matrix",this.getRotationMatrix(s));this.appearance=g;const c=super.getOperatorList(e,t,a,s);this.appearance=r;g.dict.set("Matrix",o);return c}return{opList:new OperatorList,separateForm:!1,separateCanvas:!1}}async save(e,t,i,a){this.data.checkBox?this._saveCheckbox(e,t,i,a):this.data.radioButton&&this._saveRadioButton(e,t,i,a)}async _saveCheckbox(e,t,i,a){if(!i)return;const s=i.get(this.data.id),r=this._buildFlags(s?.noView,s?.noPrint);let n=s?.rotation,g=s?.value;if(void 0===n&&void 0===r){if(void 0===g)return;if(this.data.fieldValue===this.data.exportValue===g)return}let o=e.xref.fetchIfRef(this.ref);if(!(o instanceof Dict))return;o=o.clone();void 0===n&&(n=this.rotation);void 0===g&&(g=this.data.fieldValue===this.data.exportValue);const c={path:this.data.fieldName,value:g?this.data.exportValue:""},C=Name.get(g?this.data.exportValue:"Off");this.setValue(o,C,e.xref,a);o.set("AS",C);o.set("M",`D:${getModificationDate()}`);void 0!==r&&o.set("F",r);const h=this._getMKDict(n);h&&o.set("MK",h);a.put(this.ref,{data:o,xfa:c,needAppearances:!1})}async _saveRadioButton(e,t,i,a){if(!i)return;const s=i.get(this.data.id),r=this._buildFlags(s?.noView,s?.noPrint);let n=s?.rotation,g=s?.value;if(void 0===n&&void 0===r){if(void 0===g)return;if(this.data.fieldValue===this.data.buttonValue===g)return}let o=e.xref.fetchIfRef(this.ref);if(!(o instanceof Dict))return;o=o.clone();void 0===g&&(g=this.data.fieldValue===this.data.buttonValue);void 0===n&&(n=this.rotation);const c={path:this.data.fieldName,value:g?this.data.buttonValue:""},C=Name.get(g?this.data.buttonValue:"Off");g&&this.setValue(o,C,e.xref,a);o.set("AS",C);o.set("M",`D:${getModificationDate()}`);void 0!==r&&o.set("F",r);const h=this._getMKDict(n);h&&o.set("MK",h);a.put(this.ref,{data:o,xfa:c,needAppearances:!1})}_getDefaultCheckedAppearance(e,t){const i=this.data.rect[2]-this.data.rect[0],a=this.data.rect[3]-this.data.rect[1],s=[0,0,i,a],r=.8*Math.min(i,a);let n,g;if("check"===t){n={width:.755*r,height:.705*r};g="3"}else if("disc"===t){n={width:.791*r,height:.705*r};g="l"}else unreachable(`_getDefaultCheckedAppearance - unsupported type: ${t}`);const o=`q BT /PdfJsZaDb ${r} Tf 0 g ${numberToString((i-n.width)/2)} ${numberToString((a-n.height)/2)} Td (${g}) Tj ET Q`,c=new Dict(e.xref);c.set("FormType",1);c.set("Subtype",Name.get("Form"));c.set("Type",Name.get("XObject"));c.set("BBox",s);c.set("Matrix",[1,0,0,1,0,0]);c.set("Length",o.length);const C=new Dict(e.xref),h=new Dict(e.xref);h.set("PdfJsZaDb",this.fallbackFontDict);C.set("Font",h);c.set("Resources",C);this.checkedAppearance=new StringStream(o);this.checkedAppearance.dict=c;this._streams.push(this.checkedAppearance)}_processCheckBox(e){const t=e.dict.get("AP");if(!(t instanceof Dict))return;const i=t.get("N");if(!(i instanceof Dict))return;const a=this._decodeFormValue(e.dict.get("AS"));"string"==typeof a&&(this.data.fieldValue=a);const s=null!==this.data.fieldValue&&"Off"!==this.data.fieldValue?this.data.fieldValue:"Yes",r=i.getKeys();if(0===r.length)r.push("Off",s);else if(1===r.length)"Off"===r[0]?r.push(s):r.unshift("Off");else if(r.includes(s)){r.length=0;r.push("Off",s)}else{const e=r.find((e=>"Off"!==e));r.length=0;r.push("Off",e)}r.includes(this.data.fieldValue)||(this.data.fieldValue="Off");this.data.exportValue=r[1];const n=i.get(this.data.exportValue);this.checkedAppearance=n instanceof BaseStream?n:null;const g=i.get("Off");this.uncheckedAppearance=g instanceof BaseStream?g:null;this.checkedAppearance?this._streams.push(this.checkedAppearance):this._getDefaultCheckedAppearance(e,"check");this.uncheckedAppearance&&this._streams.push(this.uncheckedAppearance);this._fallbackFontDict=this.fallbackFontDict;null===this.data.defaultFieldValue&&(this.data.defaultFieldValue="Off")}_processRadioButton(e){this.data.buttonValue=null;const t=e.dict.get("Parent");if(t instanceof Dict){this.parent=e.dict.getRaw("Parent");const i=t.get("V");i instanceof Name&&(this.data.fieldValue=this._decodeFormValue(i))}const i=e.dict.get("AP");if(!(i instanceof Dict))return;const a=i.get("N");if(!(a instanceof Dict))return;for(const e of a.getKeys())if("Off"!==e){this.data.buttonValue=this._decodeFormValue(e);break}const s=a.get(this.data.buttonValue);this.checkedAppearance=s instanceof BaseStream?s:null;const r=a.get("Off");this.uncheckedAppearance=r instanceof BaseStream?r:null;this.checkedAppearance?this._streams.push(this.checkedAppearance):this._getDefaultCheckedAppearance(e,"disc");this.uncheckedAppearance&&this._streams.push(this.uncheckedAppearance);this._fallbackFontDict=this.fallbackFontDict;null===this.data.defaultFieldValue&&(this.data.defaultFieldValue="Off")}_processPushButton(e){const{dict:t,annotationGlobals:i}=e;if(t.has("A")||t.has("AA")||this.data.alternativeText){this.data.isTooltipOnly=!t.has("A")&&!t.has("AA");Catalog.parseDestDictionary({destDict:t,resultObj:this.data,docBaseUrl:i.baseUrl,docAttachments:i.attachments})}else warn("Push buttons without action dictionaries are not supported")}getFieldObject(){let e,t="button";if(this.data.checkBox){t="checkbox";e=this.data.exportValue}else if(this.data.radioButton){t="radiobutton";e=this.data.buttonValue}return{id:this.data.id,value:this.data.fieldValue||"Off",defaultValue:this.data.defaultFieldValue,exportValues:e,editable:!this.data.readOnly,name:this.data.fieldName,rect:this.data.rect,hidden:this.data.hidden,actions:this.data.actions,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,type:t}}get fallbackFontDict(){const e=new Dict;e.set("BaseFont",Name.get("ZapfDingbats"));e.set("Type",Name.get("FallbackType"));e.set("Subtype",Name.get("FallbackType"));e.set("Encoding",Name.get("ZapfDingbatsEncoding"));return shadow(this,"fallbackFontDict",e)}}class ChoiceWidgetAnnotation extends WidgetAnnotation{constructor(e){super(e);const{dict:t,xref:i}=e;this.indices=t.getArray("I");this.hasIndices=Array.isArray(this.indices)&&this.indices.length>0;this.data.options=[];const a=getInheritableProperty({dict:t,key:"Opt"});if(Array.isArray(a))for(let e=0,t=a.length;e=0&&t0&&(this.data.options=this.data.fieldValue.map((e=>({exportValue:e,displayValue:e}))));this.data.combo=this.hasFieldFlag(oA);this.data.multiSelect=this.hasFieldFlag(cA);this._hasText=!0}getFieldObject(){const e=this.data.combo?"combobox":"listbox",t=this.data.fieldValue.length>0?this.data.fieldValue[0]:null;return{id:this.data.id,value:t,defaultValue:this.data.defaultFieldValue,editable:!this.data.readOnly,name:this.data.fieldName,rect:this.data.rect,numItems:this.data.fieldValue.length,multipleSelection:this.data.multiSelect,hidden:this.data.hidden,actions:this.data.actions,items:this.data.options,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,type:e}}amendSavedDict(e,t){if(!this.hasIndices)return;let i=e?.get(this.data.id)?.value;Array.isArray(i)||(i=[i]);const a=[],{options:s}=this.data;for(let e=0,t=0,r=s.length;ei){i=a;t=e}}[Q,E]=this._computeFontSize(e,c-4,t,l,-1)}const u=E*s,d=(u-E)/2,f=Math.floor(o/u);let p=0;if(h.length>0){const e=Math.min(...h),t=Math.max(...h);p=Math.max(0,t-f+1);p>e&&(p=e)}const m=Math.min(p+f+1,C),y=["/Tx BMC q",`1 1 ${c} ${o} re W n`];if(h.length){y.push("0.600006 0.756866 0.854904 rg");for(const e of h)p<=e&&ee.trimEnd()));const{coords:e,bbox:t,matrix:i}=FakeUnicodeFont.getFirstPositionInfo(this.rectangle,this.rotation,a);this.data.textPosition=this._transformPoint(e,t,i)}if(this._isOffscreenCanvasSupported){const s=e.dict.get("CA"),r=new FakeUnicodeFont(i,"sans-serif");this.appearance=r.createAppearance(this._contents.str,this.rectangle,this.rotation,a,t,s);this._streams.push(this.appearance)}else warn("FreeTextAnnotation: OffscreenCanvas is not supported, annotation may not render correctly.")}}get hasTextContent(){return this._hasAppearance}static createNewDict(e,t,{apRef:i,ap:a}){const{color:s,fontSize:r,oldAnnotation:n,rect:g,rotation:o,user:c,value:C}=e,h=n||new Dict(t);h.set("Type",Name.get("Annot"));h.set("Subtype",Name.get("FreeText"));if(n){h.set("M",`D:${getModificationDate()}`);h.delete("RC")}else h.set("CreationDate",`D:${getModificationDate()}`);h.set("Rect",g);const l=`/Helv ${r} Tf ${getPdfColor(s,!0)}`;h.set("DA",l);h.set("Contents",stringToAsciiOrUTF16BE(C));h.set("F",4);h.set("Border",[0,0,0]);h.set("Rotate",o);c&&h.set("T",stringToAsciiOrUTF16BE(c));if(i||a){const e=new Dict(t);h.set("AP",e);i?e.set("N",i):e.set("N",a)}return h}static async createNewAppearanceStream(e,t,i){const{baseFontRef:a,evaluator:r,task:n}=i,{color:g,fontSize:o,rect:c,rotation:C,value:h}=e,l=new Dict(t),Q=new Dict(t);if(a)Q.set("Helv",a);else{const e=new Dict(t);e.set("BaseFont",Name.get("Helvetica"));e.set("Type",Name.get("Font"));e.set("Subtype",Name.get("Type1"));e.set("Encoding",Name.get("WinAnsiEncoding"));Q.set("Helv",e)}l.set("Font",Q);const E=await WidgetAnnotation._getFontData(r,n,{fontName:"Helv",fontSize:o},l),[u,d,f,p]=c;let m=f-u,y=p-d;C%180!=0&&([m,y]=[y,m]);const w=h.split("\n"),D=o/1e3;let b=-1/0;const F=[];for(let e of w){const t=E.encodeString(e);if(t.length>1)return null;e=t.join("");F.push(e);let i=0;const a=E.charsToGlyphs(e);for(const e of a)i+=e.width*D;b=Math.max(b,i)}let S=1;b>m&&(S=m/b);let k=1;const R=s*o,N=1*o,G=R*w.length;G>y&&(k=y/G);const M=o*Math.min(S,k);let U,x,L;switch(C){case 0:L=[1,0,0,1];x=[c[0],c[1],m,y];U=[c[0],c[3]-N];break;case 90:L=[0,1,-1,0];x=[c[1],-c[2],m,y];U=[c[1],-c[0]-N];break;case 180:L=[-1,0,0,-1];x=[-c[2],-c[3],m,y];U=[-c[2],-c[1]-N];break;case 270:L=[0,-1,1,0];x=[-c[3],c[0],m,y];U=[-c[3],c[2]-N]}const H=["q",`${L.join(" ")} 0 0 cm`,`${x.join(" ")} re W n`,"BT",`${getPdfColor(g,!0)}`,`0 Tc /Helv ${numberToString(M)} Tf`];H.push(`${U.join(" ")} Td (${escapeString(F[0])}) Tj`);const J=numberToString(R);for(let e=1,t=F.length;e{e.push(`${a[0]} ${a[1]} m`,`${a[2]} ${a[3]} l`,"S");return[t[0]-o,t[2]+o,t[7]-o,t[3]+o]}})}}}class SquareAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:i}=e;this.data.annotationType=M;this.data.hasOwnCanvas=this.data.noRotate;this.data.noHTML=!1;if(!this.appearance){const e=this.color?getPdfColorArray(this.color):[0,0,0],a=t.get("CA"),s=getRgbColor(t.getArray("IC"),null),r=s?getPdfColorArray(s):null,n=r?a:null;if(0===this.borderStyle.width&&!r)return;this._setDefaultAppearance({xref:i,extra:`${this.borderStyle.width} w`,strokeColor:e,fillColor:r,strokeAlpha:a,fillAlpha:n,pointsCallback:(e,t)=>{const i=t[4]+this.borderStyle.width/2,a=t[5]+this.borderStyle.width/2,s=t[6]-t[4]-this.borderStyle.width,n=t[3]-t[7]-this.borderStyle.width;e.push(`${i} ${a} ${s} ${n} re`);r?e.push("B"):e.push("S");return[t[0],t[2],t[7],t[3]]}})}}}class CircleAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:i}=e;this.data.annotationType=U;if(!this.appearance){const e=this.color?getPdfColorArray(this.color):[0,0,0],a=t.get("CA"),s=getRgbColor(t.getArray("IC"),null),r=s?getPdfColorArray(s):null,n=r?a:null;if(0===this.borderStyle.width&&!r)return;const g=4/3*Math.tan(Math.PI/8);this._setDefaultAppearance({xref:i,extra:`${this.borderStyle.width} w`,strokeColor:e,fillColor:r,strokeAlpha:a,fillAlpha:n,pointsCallback:(e,t)=>{const i=t[0]+this.borderStyle.width/2,a=t[1]-this.borderStyle.width/2,s=t[6]-this.borderStyle.width/2,n=t[7]+this.borderStyle.width/2,o=i+(s-i)/2,c=a+(n-a)/2,C=(s-i)/2*g,h=(n-a)/2*g;e.push(`${o} ${n} m`,`${o+C} ${n} ${s} ${c+h} ${s} ${c} c`,`${s} ${c-h} ${o+C} ${a} ${o} ${a} c`,`${o-C} ${a} ${i} ${c-h} ${i} ${c} c`,`${i} ${c+h} ${o-C} ${n} ${o} ${n} c`,"h");r?e.push("B"):e.push("S");return[t[0],t[2],t[7],t[3]]}})}}}class PolylineAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:i}=e;this.data.annotationType=L;this.data.hasOwnCanvas=this.data.noRotate;this.data.noHTML=!1;this.data.vertices=null;if(!(this instanceof PolygonAnnotation)){this.setLineEndings(t.getArray("LE"));this.data.lineEndings=this.lineEndings}const a=t.getArray("Vertices");if(!isNumberArray(a,null))return;const s=this.data.vertices=Float32Array.from(a);if(!this.appearance){const e=this.color?getPdfColorArray(this.color):[0,0,0],a=t.get("CA"),r=this.borderStyle.width||1,n=2*r,g=[1/0,1/0,-1/0,-1/0];for(let e=0,t=s.length;e{for(let t=0,i=s.length;t{for(const t of this.data.inkLists){for(let i=0,a=t.length;ie/255)));Q.set("CA",n);const u=new Dict(t);Q.set("AP",u);i?u.set("N",i):u.set("N",a);return Q}static async createNewAppearanceStream(e,t,i){if(e.outlines)return this.createNewAppearanceStreamForHighlight(e,t,i);const{color:a,rect:s,paths:r,thickness:n,opacity:g}=e,o=[`${n} w 1 J 1 j`,`${getPdfColor(a,!1)}`];1!==g&&o.push("/R0 gs");for(const e of r.lines){o.push(`${numberToString(e[4])} ${numberToString(e[5])} m`);for(let t=6,i=e.length;t{e.push(`${t[0]} ${t[1]} m`,`${t[2]} ${t[3]} l`,`${t[6]} ${t[7]} l`,`${t[4]} ${t[5]} l`,"f");return[t[0],t[2],t[7],t[3]]}})}}else this.data.popupRef=null}static createNewDict(e,t,{apRef:i,ap:a}){const{color:s,oldAnnotation:r,opacity:n,rect:g,rotation:o,user:c,quadPoints:C}=e,h=r||new Dict(t);h.set("Type",Name.get("Annot"));h.set("Subtype",Name.get("Highlight"));h.set(r?"M":"CreationDate",`D:${getModificationDate()}`);h.set("CreationDate",`D:${getModificationDate()}`);h.set("Rect",g);h.set("F",4);h.set("Border",[0,0,0]);h.set("Rotate",o);h.set("QuadPoints",C);h.set("C",Array.from(s,(e=>e/255)));h.set("CA",n);c&&h.set("T",stringToAsciiOrUTF16BE(c));if(i||a){const e=new Dict(t);h.set("AP",e);e.set("N",i||a)}return h}static async createNewAppearanceStream(e,t,i){const{color:a,rect:s,outlines:r,opacity:n}=e,g=[`${getPdfColor(a,!0)}`,"/R0 gs"],o=[];for(const e of r){o.length=0;o.push(`${numberToString(e[0])} ${numberToString(e[1])} m`);for(let t=2,i=e.length;t{e.push(`${t[4]} ${t[5]+1.3} m`,`${t[6]} ${t[7]+1.3} l`,"S");return[t[0],t[2],t[7],t[3]]}})}}else this.data.popupRef=null}}class SquigglyAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:i}=e;this.data.annotationType=Y;if(this.data.quadPoints=getQuadPoints(t,null)){if(!this.appearance){const e=this.color?getPdfColorArray(this.color):[0,0,0],a=t.get("CA");this._setDefaultAppearance({xref:i,extra:"[] 0 d 1 w",strokeColor:e,strokeAlpha:a,pointsCallback:(e,t)=>{const i=(t[1]-t[5])/6;let a=i,s=t[4];const r=t[5],n=t[6];e.push(`${s} ${r+a} m`);do{s+=2;a=0===a?i:0;e.push(`${s} ${r+a} l`)}while(s{e.push((t[0]+t[4])/2+" "+(t[1]+t[5])/2+" m",(t[2]+t[6])/2+" "+(t[3]+t[7])/2+" l","S");return[t[0],t[2],t[7],t[3]]}})}}else this.data.popupRef=null}}class StampAnnotation extends MarkupAnnotation{#T;constructor(e){super(e);this.data.annotationType=K;this.#T=this.data.hasOwnCanvas=this.data.noRotate;this.data.isEditable=!this.data.noHTML;this.data.noHTML=!1}mustBeViewedWhenEditing(e,t=null){if(e){if(!this.data.isEditable)return!1;this.#T=this.data.hasOwnCanvas;this.data.hasOwnCanvas=!0;return!0}this.data.hasOwnCanvas=this.#T;return!t?.has(this.data.id)}static async createImage(e,t){const{width:i,height:a}=e,s=new OffscreenCanvas(i,a),r=s.getContext("2d",{alpha:!0});r.drawImage(e,0,0);const n=r.getImageData(0,0,i,a).data,g=new Uint32Array(n.buffer),o=g.some(FeatureTest.isLittleEndian?e=>e>>>24!=255:e=>!!(255&~e));if(o){r.fillStyle="white";r.fillRect(0,0,i,a);r.drawImage(e,0,0)}const c=s.convertToBlob({type:"image/jpeg",quality:1}).then((e=>e.arrayBuffer())),C=Name.get("XObject"),h=Name.get("Image"),l=new Dict(t);l.set("Type",C);l.set("Subtype",h);l.set("BitsPerComponent",8);l.set("ColorSpace",Name.get("DeviceRGB"));l.set("Filter",Name.get("DCTDecode"));l.set("BBox",[0,0,i,a]);l.set("Width",i);l.set("Height",a);let Q=null;if(o){const e=new Uint8Array(g.length);if(FeatureTest.isLittleEndian)for(let t=0,i=g.length;t>>24;else for(let t=0,i=g.length;t=0&&r<=1?r:null}}class DecryptStream extends DecodeStream{constructor(e,t,i){super(t);this.str=e;this.dict=e.dict;this.decrypt=i;this.nextChunk=null;this.initialized=!1}readBlock(){let e;if(this.initialized)e=this.nextChunk;else{e=this.str.getBytes(512);this.initialized=!0}if(!e?.length){this.eof=!0;return}this.nextChunk=this.str.getBytes(512);const t=this.nextChunk?.length>0;e=(0,this.decrypt)(e,!t);const i=this.bufferLength,a=i+e.length;this.ensureBuffer(a).set(e,i);this.bufferLength=a}}class ARCFourCipher{constructor(e){this.a=0;this.b=0;const t=new Uint8Array(256),i=e.length;for(let e=0;e<256;++e)t[e]=e;for(let a=0,s=0;a<256;++a){const r=t[a];s=s+r+e[a%i]&255;t[a]=t[s];t[s]=r}this.s=t}encryptBlock(e){let t=this.a,i=this.b;const a=this.s,s=e.length,r=new Uint8Array(s);for(let n=0;n>5&255;C[h++]=s>>13&255;C[h++]=s>>21&255;C[h++]=s>>>29&255;C[h++]=0;C[h++]=0;C[h++]=0;const E=new Int32Array(16);for(h=0;h>>32-g)|0;s=r}r=r+s|0;n=n+c|0;g=g+Q|0;o=o+u|0}return new Uint8Array([255&r,r>>8&255,r>>16&255,r>>>24&255,255&n,n>>8&255,n>>16&255,n>>>24&255,255&g,g>>8&255,g>>16&255,g>>>24&255,255&o,o>>8&255,o>>16&255,o>>>24&255])}}();class Word64{constructor(e,t){this.high=0|e;this.low=0|t}and(e){this.high&=e.high;this.low&=e.low}xor(e){this.high^=e.high;this.low^=e.low}or(e){this.high|=e.high;this.low|=e.low}shiftRight(e){if(e>=32){this.low=this.high>>>e-32|0;this.high=0}else{this.low=this.low>>>e|this.high<<32-e;this.high=this.high>>>e|0}}shiftLeft(e){if(e>=32){this.high=this.low<>>32-e;this.low<<=e}}rotateRight(e){let t,i;if(32&e){i=this.low;t=this.high}else{t=this.low;i=this.high}e&=31;this.low=t>>>e|i<<32-e;this.high=i>>>e|t<<32-e}not(){this.high=~this.high;this.low=~this.low}add(e){const t=(this.low>>>0)+(e.low>>>0);let i=(this.high>>>0)+(e.high>>>0);t>4294967295&&(i+=1);this.low=0|t;this.high=0|i}copyTo(e,t){e[t]=this.high>>>24&255;e[t+1]=this.high>>16&255;e[t+2]=this.high>>8&255;e[t+3]=255&this.high;e[t+4]=this.low>>>24&255;e[t+5]=this.low>>16&255;e[t+6]=this.low>>8&255;e[t+7]=255&this.low}assign(e){this.high=e.high;this.low=e.low}}const Ag=function calculateSHA256Closure(){function rotr(e,t){return e>>>t|e<<32-t}function ch(e,t,i){return e&t^~e&i}function maj(e,t,i){return e&t^e&i^t&i}function sigma(e){return rotr(e,2)^rotr(e,13)^rotr(e,22)}function sigmaPrime(e){return rotr(e,6)^rotr(e,11)^rotr(e,25)}function littleSigma(e){return rotr(e,7)^rotr(e,18)^e>>>3}const e=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];return function hash(t,i,a){let s=1779033703,r=3144134277,n=1013904242,g=2773480762,o=1359893119,c=2600822924,C=528734635,h=1541459225;const l=64*Math.ceil((a+9)/64),Q=new Uint8Array(l);let E,u;for(E=0;E>>29&255;Q[E++]=a>>21&255;Q[E++]=a>>13&255;Q[E++]=a>>5&255;Q[E++]=a<<3&255;const f=new Uint32Array(64);for(E=0;E>>10)+f[u-7]+littleSigma(f[u-15])+f[u-16]|0;let t,i,a=s,l=r,d=n,m=g,y=o,w=c,D=C,b=h;for(u=0;u<64;++u){t=b+sigmaPrime(y)+ch(y,w,D)+e[u]+f[u];i=sigma(a)+maj(a,l,d);b=D;D=w;w=y;y=m+t|0;m=d;d=l;l=a;a=t+i|0}s=s+a|0;r=r+l|0;n=n+d|0;g=g+m|0;o=o+y|0;c=c+w|0;C=C+D|0;h=h+b|0}var p;return new Uint8Array([s>>24&255,s>>16&255,s>>8&255,255&s,r>>24&255,r>>16&255,r>>8&255,255&r,n>>24&255,n>>16&255,n>>8&255,255&n,g>>24&255,g>>16&255,g>>8&255,255&g,o>>24&255,o>>16&255,o>>8&255,255&o,c>>24&255,c>>16&255,c>>8&255,255&c,C>>24&255,C>>16&255,C>>8&255,255&C,h>>24&255,h>>16&255,h>>8&255,255&h])}}(),eg=function calculateSHA512Closure(){function ch(e,t,i,a,s){e.assign(t);e.and(i);s.assign(t);s.not();s.and(a);e.xor(s)}function maj(e,t,i,a,s){e.assign(t);e.and(i);s.assign(t);s.and(a);e.xor(s);s.assign(i);s.and(a);e.xor(s)}function sigma(e,t,i){e.assign(t);e.rotateRight(28);i.assign(t);i.rotateRight(34);e.xor(i);i.assign(t);i.rotateRight(39);e.xor(i)}function sigmaPrime(e,t,i){e.assign(t);e.rotateRight(14);i.assign(t);i.rotateRight(18);e.xor(i);i.assign(t);i.rotateRight(41);e.xor(i)}function littleSigma(e,t,i){e.assign(t);e.rotateRight(1);i.assign(t);i.rotateRight(8);e.xor(i);i.assign(t);i.shiftRight(7);e.xor(i)}function littleSigmaPrime(e,t,i){e.assign(t);e.rotateRight(19);i.assign(t);i.rotateRight(61);e.xor(i);i.assign(t);i.shiftRight(6);e.xor(i)}const e=[new Word64(1116352408,3609767458),new Word64(1899447441,602891725),new Word64(3049323471,3964484399),new Word64(3921009573,2173295548),new Word64(961987163,4081628472),new Word64(1508970993,3053834265),new Word64(2453635748,2937671579),new Word64(2870763221,3664609560),new Word64(3624381080,2734883394),new Word64(310598401,1164996542),new Word64(607225278,1323610764),new Word64(1426881987,3590304994),new Word64(1925078388,4068182383),new Word64(2162078206,991336113),new Word64(2614888103,633803317),new Word64(3248222580,3479774868),new Word64(3835390401,2666613458),new Word64(4022224774,944711139),new Word64(264347078,2341262773),new Word64(604807628,2007800933),new Word64(770255983,1495990901),new Word64(1249150122,1856431235),new Word64(1555081692,3175218132),new Word64(1996064986,2198950837),new Word64(2554220882,3999719339),new Word64(2821834349,766784016),new Word64(2952996808,2566594879),new Word64(3210313671,3203337956),new Word64(3336571891,1034457026),new Word64(3584528711,2466948901),new Word64(113926993,3758326383),new Word64(338241895,168717936),new Word64(666307205,1188179964),new Word64(773529912,1546045734),new Word64(1294757372,1522805485),new Word64(1396182291,2643833823),new Word64(1695183700,2343527390),new Word64(1986661051,1014477480),new Word64(2177026350,1206759142),new Word64(2456956037,344077627),new Word64(2730485921,1290863460),new Word64(2820302411,3158454273),new Word64(3259730800,3505952657),new Word64(3345764771,106217008),new Word64(3516065817,3606008344),new Word64(3600352804,1432725776),new Word64(4094571909,1467031594),new Word64(275423344,851169720),new Word64(430227734,3100823752),new Word64(506948616,1363258195),new Word64(659060556,3750685593),new Word64(883997877,3785050280),new Word64(958139571,3318307427),new Word64(1322822218,3812723403),new Word64(1537002063,2003034995),new Word64(1747873779,3602036899),new Word64(1955562222,1575990012),new Word64(2024104815,1125592928),new Word64(2227730452,2716904306),new Word64(2361852424,442776044),new Word64(2428436474,593698344),new Word64(2756734187,3733110249),new Word64(3204031479,2999351573),new Word64(3329325298,3815920427),new Word64(3391569614,3928383900),new Word64(3515267271,566280711),new Word64(3940187606,3454069534),new Word64(4118630271,4000239992),new Word64(116418474,1914138554),new Word64(174292421,2731055270),new Word64(289380356,3203993006),new Word64(460393269,320620315),new Word64(685471733,587496836),new Word64(852142971,1086792851),new Word64(1017036298,365543100),new Word64(1126000580,2618297676),new Word64(1288033470,3409855158),new Word64(1501505948,4234509866),new Word64(1607167915,987167468),new Word64(1816402316,1246189591)];return function hash(t,i,a,s=!1){let r,n,g,o,c,C,h,l;if(s){r=new Word64(3418070365,3238371032);n=new Word64(1654270250,914150663);g=new Word64(2438529370,812702999);o=new Word64(355462360,4144912697);c=new Word64(1731405415,4290775857);C=new Word64(2394180231,1750603025);h=new Word64(3675008525,1694076839);l=new Word64(1203062813,3204075428)}else{r=new Word64(1779033703,4089235720);n=new Word64(3144134277,2227873595);g=new Word64(1013904242,4271175723);o=new Word64(2773480762,1595750129);c=new Word64(1359893119,2917565137);C=new Word64(2600822924,725511199);h=new Word64(528734635,4215389547);l=new Word64(1541459225,327033209)}const Q=128*Math.ceil((a+17)/128),E=new Uint8Array(Q);let u,d;for(u=0;u>>29&255;E[u++]=a>>21&255;E[u++]=a>>13&255;E[u++]=a>>5&255;E[u++]=a<<3&255;const p=new Array(80);for(u=0;u<80;u++)p[u]=new Word64(0,0);let m=new Word64(0,0),y=new Word64(0,0),w=new Word64(0,0),D=new Word64(0,0),b=new Word64(0,0),F=new Word64(0,0),S=new Word64(0,0),k=new Word64(0,0);const R=new Word64(0,0),N=new Word64(0,0),G=new Word64(0,0),M=new Word64(0,0);let U,x;for(u=0;u=1;--e){i=r[13];r[13]=r[9];r[9]=r[5];r[5]=r[1];r[1]=i;i=r[14];a=r[10];r[14]=r[6];r[10]=r[2];r[6]=i;r[2]=a;i=r[15];a=r[11];s=r[7];r[15]=r[3];r[11]=i;r[7]=a;r[3]=s;for(let e=0;e<16;++e)r[e]=this._inv_s[r[e]];for(let i=0,a=16*e;i<16;++i,++a)r[i]^=t[a];for(let e=0;e<16;e+=4){const t=this._mix[r[e]],a=this._mix[r[e+1]],s=this._mix[r[e+2]],n=this._mix[r[e+3]];i=t^a>>>8^a<<24^s>>>16^s<<16^n>>>24^n<<8;r[e]=i>>>24&255;r[e+1]=i>>16&255;r[e+2]=i>>8&255;r[e+3]=255&i}}i=r[13];r[13]=r[9];r[9]=r[5];r[5]=r[1];r[1]=i;i=r[14];a=r[10];r[14]=r[6];r[10]=r[2];r[6]=i;r[2]=a;i=r[15];a=r[11];s=r[7];r[15]=r[3];r[11]=i;r[7]=a;r[3]=s;for(let e=0;e<16;++e){r[e]=this._inv_s[r[e]];r[e]^=t[e]}return r}_encrypt(e,t){const i=this._s;let a,s,r;const n=new Uint8Array(16);n.set(e);for(let e=0;e<16;++e)n[e]^=t[e];for(let e=1;e=a;--i)if(e[i]!==t){t=0;break}g-=t;r[r.length-1]=e.subarray(0,16-t)}}const o=new Uint8Array(g);for(let e=0,t=0,i=r.length;e=256&&(g=255&(27^g))}for(let t=0;t<4;++t){i[e]=a^=i[e-32];e++;i[e]=s^=i[e-32];e++;i[e]=r^=i[e-32];e++;i[e]=n^=i[e-32];e++}}return i}}class PDF17{checkOwnerPassword(e,t,i,a){const s=new Uint8Array(e.length+56);s.set(e,0);s.set(t,e.length);s.set(i,e.length+t.length);return isArrayEqual(Ag(s,0,s.length),a)}checkUserPassword(e,t,i){const a=new Uint8Array(e.length+8);a.set(e,0);a.set(t,e.length);return isArrayEqual(Ag(a,0,a.length),i)}getOwnerKey(e,t,i,a){const s=new Uint8Array(e.length+56);s.set(e,0);s.set(t,e.length);s.set(i,e.length+t.length);const r=Ag(s,0,s.length);return new AES256Cipher(r).decryptBlock(a,!1,new Uint8Array(16))}getUserKey(e,t,i){const a=new Uint8Array(e.length+8);a.set(e,0);a.set(t,e.length);const s=Ag(a,0,a.length);return new AES256Cipher(s).decryptBlock(i,!1,new Uint8Array(16))}}class PDF20{_hash(e,t,i){let a=Ag(t,0,t.length).subarray(0,32),s=[0],r=0;for(;r<64||s.at(-1)>r-32;){const t=e.length+a.length+i.length,c=new Uint8Array(t);let C=0;c.set(e,C);C+=e.length;c.set(a,C);C+=a.length;c.set(i,C);const h=new Uint8Array(64*t);for(let e=0,i=0;e<64;e++,i+=t)h.set(c,i);s=new AES128Cipher(a.subarray(0,16)).encrypt(h,a.subarray(16,32));const l=s.slice(0,16).reduce(((e,t)=>e+t),0)%3;0===l?a=Ag(s,0,s.length):1===l?a=(n=s,g=0,o=s.length,eg(n,g,o,!0)):2===l&&(a=eg(s,0,s.length));r++}var n,g,o;return a.subarray(0,32)}checkOwnerPassword(e,t,i,a){const s=new Uint8Array(e.length+56);s.set(e,0);s.set(t,e.length);s.set(i,e.length+t.length);return isArrayEqual(this._hash(e,s,i),a)}checkUserPassword(e,t,i){const a=new Uint8Array(e.length+8);a.set(e,0);a.set(t,e.length);return isArrayEqual(this._hash(e,a,[]),i)}getOwnerKey(e,t,i,a){const s=new Uint8Array(e.length+56);s.set(e,0);s.set(t,e.length);s.set(i,e.length+t.length);const r=this._hash(e,s,i);return new AES256Cipher(r).decryptBlock(a,!1,new Uint8Array(16))}getUserKey(e,t,i){const a=new Uint8Array(e.length+8);a.set(e,0);a.set(t,e.length);const s=this._hash(e,a,[]);return new AES256Cipher(s).decryptBlock(i,!1,new Uint8Array(16))}}class CipherTransform{constructor(e,t){this.StringCipherConstructor=e;this.StreamCipherConstructor=t}createStream(e,t){const i=new this.StreamCipherConstructor;return new DecryptStream(e,t,(function cipherTransformDecryptStream(e,t){return i.decryptBlock(e,t)}))}decryptString(e){const t=new this.StringCipherConstructor;let i=stringToBytes(e);i=t.decryptBlock(i,!0);return bytesToString(i)}encryptString(e){const t=new this.StringCipherConstructor;if(t instanceof AESBaseCipher){const i=16-e.length%16;e+=String.fromCharCode(i).repeat(i);const a=new Uint8Array(16);if("undefined"!=typeof crypto)crypto.getRandomValues(a);else for(let e=0;e<16;e++)a[e]=Math.floor(256*Math.random());let s=stringToBytes(e);s=t.encrypt(s,a);const r=new Uint8Array(16+s.length);r.set(a);r.set(s,16);return bytesToString(r)}let i=stringToBytes(e);i=t.encrypt(i);return bytesToString(i)}}class CipherTransformFactory{static#q=new Uint8Array([40,191,78,94,78,117,138,65,100,0,78,86,255,250,1,8,46,46,0,182,208,104,62,128,47,12,169,254,100,83,105,122]);#O(e,t,i,a,s,r,n,g,o,c,C,h){if(t){const e=Math.min(127,t.length);t=t.subarray(0,e)}else t=[];const l=6===e?new PDF20:new PDF17;return l.checkUserPassword(t,g,n)?l.getUserKey(t,o,C):t.length&&l.checkOwnerPassword(t,a,r,i)?l.getOwnerKey(t,s,r,c):null}#P(e,t,i,a,s,r,n,g){const o=40+i.length+e.length,c=new Uint8Array(o);let C,h,l=0;if(t){h=Math.min(32,t.length);for(;l>8&255;c[l++]=s>>16&255;c[l++]=s>>>24&255;for(C=0,h=e.length;C=4&&!g){c[l++]=255;c[l++]=255;c[l++]=255;c[l++]=255}let Q=$n(c,0,l);const E=n>>3;if(r>=3)for(C=0;C<50;++C)Q=$n(Q,0,E);const u=Q.subarray(0,E);let d,f;if(r>=3){for(l=0;l<32;++l)c[l]=CipherTransformFactory.#q[l];for(C=0,h=e.length;C>3;if(i>=3)for(g=0;g<50;++g)o=$n(o,0,o.length);let C,h;if(i>=3){h=t;const e=new Uint8Array(c);for(g=19;g>=0;g--){for(let t=0;t>8&255;s[n++]=e>>16&255;s[n++]=255&t;s[n++]=t>>8&255;if(a){s[n++]=115;s[n++]=65;s[n++]=108;s[n++]=84}return $n(s,0,n).subarray(0,Math.min(i.length+5,16))}#X(e,t,i,a,s){if(!(t instanceof Name))throw new FormatError("Invalid crypt filter name.");const r=this,n=e.get(t.name),g=n?.get("CFM");if(!g||"None"===g.name)return function(){return new NullCipher};if("V2"===g.name)return function(){return new ARCFourCipher(r.#j(i,a,s,!1))};if("AESV2"===g.name)return function(){return new AES128Cipher(r.#j(i,a,s,!0))};if("AESV3"===g.name)return function(){return new AES256Cipher(s)};throw new FormatError("Unknown crypto method")}constructor(e,t,i){const a=e.get("Filter");if(!isName(a,"Standard"))throw new FormatError("unknown encryption method");this.filterName=a.name;this.dict=e;const s=e.get("V");if(!Number.isInteger(s)||1!==s&&2!==s&&4!==s&&5!==s)throw new FormatError("unsupported encryption algorithm");this.algorithm=s;let r=e.get("Length");if(!r)if(s<=3)r=40;else{const t=e.get("CF"),i=e.get("StmF");if(t instanceof Dict&&i instanceof Name){t.suppressEncryption=!0;const e=t.get(i.name);r=e?.get("Length")||128;r<40&&(r<<=3)}}if(!Number.isInteger(r)||r<40||r%8!=0)throw new FormatError("invalid key length");const n=stringToBytes(e.get("O")),g=stringToBytes(e.get("U")),o=n.subarray(0,32),c=g.subarray(0,32),C=e.get("P"),h=e.get("R"),l=(4===s||5===s)&&!1!==e.get("EncryptMetadata");this.encryptMetadata=l;const Q=stringToBytes(t);let E,u;if(i){if(6===h)try{i=utf8StringToString(i)}catch{warn("CipherTransformFactory: Unable to convert UTF8 encoded password.")}E=stringToBytes(i)}if(5!==s)u=this.#P(Q,E,o,c,C,h,r,l);else{const t=n.subarray(32,40),i=n.subarray(40,48),a=g.subarray(0,48),s=g.subarray(32,40),r=g.subarray(40,48),C=stringToBytes(e.get("OE")),l=stringToBytes(e.get("UE")),Q=stringToBytes(e.get("Perms"));u=this.#O(h,E,o,t,i,a,c,s,r,C,l,Q)}if(!u&&!i)throw new PasswordException("No password given",rt);if(!u&&i){const e=this.#W(E,o,h,r);u=this.#P(Q,e,o,c,C,h,r,l)}if(!u)throw new PasswordException("Incorrect Password",nt);this.encryptionKey=u;if(s>=4){const t=e.get("CF");t instanceof Dict&&(t.suppressEncryption=!0);this.cf=t;this.stmf=e.get("StmF")||Name.get("Identity");this.strf=e.get("StrF")||Name.get("Identity");this.eff=e.get("EFF")||this.stmf}}createCipherTransform(e,t){if(4===this.algorithm||5===this.algorithm)return new CipherTransform(this.#X(this.cf,this.strf,e,t,this.encryptionKey),this.#X(this.cf,this.stmf,e,t,this.encryptionKey));const i=this.#j(e,t,this.encryptionKey,!1),cipherConstructor=function(){return new ARCFourCipher(i)};return new CipherTransform(cipherConstructor,cipherConstructor)}}function decodeString(e){try{return stringToUTF8String(e)}catch(t){warn(`UTF-8 decoding failed: "${t}".`);return e}}class DatasetXMLParser extends SimpleXMLParser{constructor(e){super(e);this.node=null}onEndElement(e){const t=super.onEndElement(e);if(t&&"xfa:datasets"===e){this.node=t;throw new Error("Aborting DatasetXMLParser.")}}}class DatasetReader{constructor(e){if(e.datasets)this.node=new SimpleXMLParser({hasAttributes:!0}).parseFromString(e.datasets).documentElement;else{const t=new DatasetXMLParser({hasAttributes:!0});try{t.parseFromString(e["xdp:xdp"])}catch{}this.node=t.node}}getValue(e){if(!this.node||!e)return"";const t=this.node.searchNode(parseXFAPath(e),0);if(!t)return"";const i=t.firstChild;return"value"===i?.nodeName?t.children.map((e=>decodeString(e.textContent))):decodeString(t.textContent)}}class XRef{#Z=null;constructor(e,t){this.stream=e;this.pdfManager=t;this.entries=[];this._xrefStms=new Set;this._cacheMap=new Map;this._pendingRefs=new RefSet;this._newPersistentRefNum=null;this._newTemporaryRefNum=null;this._persistentRefsCache=null}getNewPersistentRef(e){null===this._newPersistentRefNum&&(this._newPersistentRefNum=this.entries.length||1);const t=this._newPersistentRefNum++;this._cacheMap.set(t,e);return Ref.get(t,0)}getNewTemporaryRef(){if(null===this._newTemporaryRefNum){this._newTemporaryRefNum=this.entries.length||1;if(this._newPersistentRefNum){this._persistentRefsCache=new Map;for(let e=this._newTemporaryRefNum;e0;){const[n,g]=r;if(!Number.isInteger(n)||!Number.isInteger(g))throw new FormatError(`Invalid XRef range fields: ${n}, ${g}`);if(!Number.isInteger(i)||!Number.isInteger(a)||!Number.isInteger(s))throw new FormatError(`Invalid XRef entry fields length: ${n}, ${g}`);for(let r=t.entryNum;r=e.length);){i+=String.fromCharCode(a);a=e[t]}return i}function skipUntil(e,t,i){const a=i.length,s=e.length;let r=0;for(;t=a)break;t++;r++}return r}const e=/\b(endobj|\d+\s+\d+\s+obj|xref|trailer\s*<<)\b/g,t=/\b(startxref|\d+\s+\d+\s+obj)\b/g,i=/^(\d+)\s+(\d+)\s+obj\b/,a=new Uint8Array([116,114,97,105,108,101,114]),s=new Uint8Array([115,116,97,114,116,120,114,101,102]),r=new Uint8Array([47,88,82,101,102]);this.entries.length=0;this._cacheMap.clear();const n=this.stream;n.pos=0;const g=n.getBytes(),o=bytesToString(g),c=g.length;let C=n.start;const h=[],l=[];for(;C=c)break;Q=g[C]}while(10!==Q&&13!==Q);continue}const E=readToken(g,C);let u;if(E.startsWith("xref")&&(4===E.length||/\s/.test(E[4]))){C+=skipUntil(g,C,a);h.push(C);C+=skipUntil(g,C,s)}else if(u=i.exec(E)){const t=0|u[1],i=0|u[2],a=C+E.length;let s,h=!1;if(this.entries[t]){if(this.entries[t].gen===i)try{new Parser({lexer:new Lexer(n.makeSubStream(a))}).getObj();h=!0}catch(e){e instanceof ParserEOFException?warn(`indexObjects -- checking object (${E}): "${e}".`):h=!0}}else h=!0;h&&(this.entries[t]={offset:C-n.start,gen:i,uncompressed:!0});e.lastIndex=a;const Q=e.exec(o);if(Q){s=e.lastIndex+1-C;if("endobj"!==Q[1]){warn(`indexObjects: Found "${Q[1]}" inside of another "obj", caused by missing "endobj" -- trying to recover.`);s-=Q[1].length+1}}else s=c-C;const d=g.subarray(C,C+s),f=skipUntil(d,0,r);if(f0?Math.max(...this._xrefStms):null)}getEntry(e){const t=this.entries[e];return t&&!t.free&&t.offset?t:null}fetchIfRef(e,t=!1){return e instanceof Ref?this.fetch(e,t):e}fetch(e,t=!1){if(!(e instanceof Ref))throw new Error("ref object is not a reference");const i=e.num,a=this._cacheMap.get(i);if(void 0!==a){a instanceof Dict&&!a.objId&&(a.objId=e.toString());return a}let s=this.getEntry(i);if(null===s){this._cacheMap.set(i,s);return s}if(this._pendingRefs.has(e)){this._pendingRefs.remove(e);warn(`Ignoring circular reference: ${e}.`);return lt}this._pendingRefs.put(e);try{s=s.uncompressed?this.fetchUncompressed(e,s,t):this.fetchCompressed(e,s,t);this._pendingRefs.remove(e)}catch(t){this._pendingRefs.remove(e);throw t}s instanceof Dict?s.objId=e.toString():s instanceof BaseStream&&(s.dict.objId=e.toString());return s}fetchUncompressed(e,t,i=!1){const a=e.gen;let s=e.num;if(t.gen!==a){const r=`Inconsistent generation in XRef: ${e}`;if(this._generationFallback&&t.gen0&&t[3]-t[1]>0)return t;warn(`Empty, or invalid, /${e} entry.`)}return null}get mediaBox(){return shadow(this,"mediaBox",this._getBoundingBox("MediaBox")||tg)}get cropBox(){return shadow(this,"cropBox",this._getBoundingBox("CropBox")||this.mediaBox)}get userUnit(){const e=this.pageDict.get("UserUnit");return shadow(this,"userUnit","number"==typeof e&&e>0?e:1)}get view(){const{cropBox:e,mediaBox:t}=this;if(e!==t&&!isArrayEqual(e,t)){const i=Util.intersect(e,t);if(i&&i[2]-i[0]>0&&i[3]-i[1]>0)return shadow(this,"view",i);warn("Empty /CropBox and /MediaBox intersection.")}return shadow(this,"view",t)}get rotate(){let e=this._getInheritableProperty("Rotate")||0;e%90!=0?e=0:e>=360?e%=360:e<0&&(e=(e%360+360)%360);return shadow(this,"rotate",e)}_onSubStreamError(e,t){if(!this.evaluatorOptions.ignoreErrors)throw e;warn(`getContentStream - ignoring sub-stream (${t}): "${e}".`)}getContentStream(){return this.pdfManager.ensure(this,"content").then((e=>e instanceof BaseStream?e:Array.isArray(e)?new StreamsSequenceStream(e,this._onSubStreamError.bind(this)):new NullStream))}get xfaData(){return shadow(this,"xfaData",this.xfaFactory?{bbox:this.xfaFactory.getBoundingBox(this.pageIndex)}:null)}async#V(e,t,i){const a=[];for(const s of e)if(s.id){const e=Ref.fromString(s.id);if(!e){warn(`A non-linked annotation cannot be modified: ${s.id}`);continue}if(s.deleted){t.put(e,e);if(s.popupRef){const e=Ref.fromString(s.popupRef);e&&t.put(e,e)}continue}i?.put(e);s.ref=e;a.push(this.xref.fetchAsync(e).then((e=>{e instanceof Dict&&(s.oldAnnotation=e.clone())}),(()=>{warn(`Cannot fetch \`oldAnnotation\` for: ${e}.`)})));delete s.id}await Promise.all(a)}async saveNewAnnotations(e,t,i,a,s){if(this.xfaFactory)throw new Error("XFA: Cannot save new annotations.");const r=new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions}),n=new RefSetCache,g=new RefSet;await this.#V(i,n,g);const o=this.pageDict,c=this.annotations.filter((e=>!(e instanceof Ref&&n.has(e)))),C=await AnnotationFactory.saveNewAnnotations(r,t,i,a,s);for(const{ref:e}of C.annotations)e instanceof Ref&&!g.has(e)&&c.push(e);const h=o.clone();h.set("Annots",c);s.put(this.ref,{data:h});for(const e of n)s.put(e,{data:null})}save(e,t,i,a){const s=new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions});return this._parsedAnnotations.then((function(e){const r=[];for(const n of e)r.push(n.save(s,t,i,a).catch((function(e){warn(`save - ignoring annotation data during "${t.name}" task: "${e}".`);return null})));return Promise.all(r)}))}loadResources(e){this.resourcesPromise||=this.pdfManager.ensure(this,"resources");return this.resourcesPromise.then((()=>new ObjectLoader(this.resources,e,this.xref).load()))}getOperatorList({handler:e,sink:t,task:i,intent:a,cacheKey:s,annotationStorage:r=null,modifiedIds:n=null}){const C=this.getContentStream(),E=this.loadResources(["ColorSpace","ExtGState","Font","Pattern","Properties","Shading","XObject"]),d=new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions}),f=this.xfaFactory?null:getNewAnnotationsMap(r),p=f?.get(this.pageIndex);let m=Promise.resolve(null),y=null;if(p){const e=this.pdfManager.ensureDoc("annotationGlobals");let t;const a=new Set;for(const{bitmapId:e,bitmap:t}of p)!e||t||a.has(e)||a.add(e);const{isOffscreenCanvasSupported:s}=this.evaluatorOptions;if(a.size>0){const e=p.slice();for(const[t,i]of r)t.startsWith(u)&&i.bitmap&&a.has(i.bitmapId)&&e.push(i);t=AnnotationFactory.generateImages(e,this.xref,s)}else t=AnnotationFactory.generateImages(p,this.xref,s);y=new RefSet;m=Promise.all([e,this.#V(p,y,null)]).then((([e])=>e?AnnotationFactory.printNewAnnotations(e,d,i,p,t):null))}const w=Promise.all([C,E]).then((([r])=>{const n=new OperatorList(a,t);e.send("StartRenderPage",{transparency:d.hasBlendModes(this.resources,this.nonBlendModesSet),pageIndex:this.pageIndex,cacheKey:s});return d.getOperatorList({stream:r,task:i,resources:this.resources,operatorList:n}).then((function(){return n}))}));return Promise.all([w,this._parsedAnnotations,m]).then((function([e,t,s]){if(s){t=t.filter((e=>!(e.ref&&y.has(e.ref))));for(let e=0,i=s.length;ee.ref&&isRefsEqual(e.ref,a.refToReplace)));if(r>=0){t.splice(r,1,a);s.splice(e--,1);i--}}}t=t.concat(s)}if(0===t.length||a&l){e.flush(!0);return{length:e.totalLength}}const C=!!(a&h),E=!!(a&Q),u=!!(a&g),f=!!(a&o),p=!!(a&c),m=[];for(const e of t)(u||f&&e.mustBeViewed(r,C)&&e.mustBeViewedWhenEditing(E,n)||p&&e.mustBePrinted(r))&&m.push(e.getOperatorList(d,i,a,r).catch((function(e){warn(`getOperatorList - ignoring annotation data during "${i.name}" task: "${e}".`);return{opList:null,separateForm:!1,separateCanvas:!1}})));return Promise.all(m).then((function(t){let i=!1,a=!1;for(const{opList:s,separateForm:r,separateCanvas:n}of t){e.addOpList(s);i||=r;a||=n}e.flush(!0,{form:i,canvas:a});return{length:e.totalLength}}))}))}async extractTextContent({handler:e,task:t,includeMarkedContent:i,disableNormalization:a,sink:s}){const r=this.getContentStream(),n=this.loadResources(["ExtGState","Font","Properties","XObject"]),g=this.pdfManager.ensureCatalog("lang"),[o,,c]=await Promise.all([r,n,g]);return new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions}).getTextContent({stream:o,task:t,resources:this.resources,includeMarkedContent:i,disableNormalization:a,sink:s,viewBox:this.view,lang:c})}async getStructTree(){const e=await this.pdfManager.ensureCatalog("structTreeRoot");if(!e)return null;await this._parsedAnnotations;const t=await this.pdfManager.ensure(this,"_parseStructTree",[e]);return this.pdfManager.ensure(t,"serializable")}_parseStructTree(e){const t=new StructTreePage(e,this.pageDict);t.parse(this.ref);return t}async getAnnotationsData(e,t,i){const a=await this._parsedAnnotations;if(0===a.length)return a;const s=[],r=[];let n;const C=!!(i&g),h=!!(i&o),l=!!(i&c);for(const i of a){const a=C||h&&i.viewable;(a||l&&i.printable)&&s.push(i.data);if(i.hasTextContent&&a){n||=new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions});r.push(i.extractTextContent(n,t,[-1/0,-1/0,1/0,1/0]).catch((function(e){warn(`getAnnotationsData - ignoring textContent during "${t.name}" task: "${e}".`)})))}}await Promise.all(r);return s}get annotations(){const e=this._getInheritableProperty("Annots");return shadow(this,"annotations",Array.isArray(e)?e:[])}get _parsedAnnotations(){return shadow(this,"_parsedAnnotations",this.pdfManager.ensure(this,"annotations").then((async e=>{if(0===e.length)return e;const[t,i]=await Promise.all([this.pdfManager.ensureDoc("annotationGlobals"),this.pdfManager.ensureDoc("fieldObjects")]);if(!t)return[];const a=i?.orphanFields,s=[];for(const i of e)s.push(AnnotationFactory.create(this.xref,i,t,this._localIdFactory,!1,a,this.ref).catch((function(e){warn(`_parsedAnnotations: "${e}".`);return null})));const r=[];let n,g;for(const e of await Promise.all(s))e&&(e instanceof WidgetAnnotation?(g||=[]).push(e):e instanceof PopupAnnotation?(n||=[]).push(e):r.push(e));g&&r.push(...g);n&&r.push(...n);return r})))}get jsActions(){return shadow(this,"jsActions",collectActions(this.xref,this.pageDict,pA))}}const ig=new Uint8Array([37,80,68,70,45]),ag=new Uint8Array([115,116,97,114,116,120,114,101,102]),sg=new Uint8Array([101,110,100,111,98,106]);function find(e,t,i=1024,a=!1){const s=t.length,r=e.peekBytes(i),n=r.length-s;if(n<=0)return!1;if(a){const i=s-1;let a=r.length-1;for(;a>=i;){let n=0;for(;n=s){e.pos+=a-i;return!0}a--}}else{let i=0;for(;i<=n;){let a=0;for(;a=s){e.pos+=i;return!0}i++}}return!1}class PDFDocument{constructor(e,t){if(t.length<=0)throw new InvalidPDFException("The PDF file is empty, i.e. its size is zero bytes.");this.pdfManager=e;this.stream=t;this.xref=new XRef(t,e);this._pagePromises=new Map;this._version=null;const i={font:0};this._globalIdFactory=class{static getDocId(){return`g_${e.docId}`}static createFontId(){return"f"+ ++i.font}static createObjId(){unreachable("Abstract method `createObjId` called.")}static getPageObjId(){unreachable("Abstract method `getPageObjId` called.")}}}parse(e){this.xref.parse(e);this.catalog=new Catalog(this.pdfManager,this.xref)}get linearization(){let e=null;try{e=Linearization.create(this.stream)}catch(e){if(e instanceof MissingDataException)throw e;info(e)}return shadow(this,"linearization",e)}get startXRef(){const e=this.stream;let t=0;if(this.linearization){e.reset();if(find(e,sg)){e.skip(6);let i=e.peekByte();for(;isWhiteSpace(i);){e.pos++;i=e.peekByte()}t=e.pos-e.start}}else{const i=1024,a=ag.length;let s=!1,r=e.end;for(;!s&&r>0;){r-=i-a;r<0&&(r=0);e.pos=r;s=find(e,ag,i,!0)}if(s){e.skip(9);let i;do{i=e.getByte()}while(isWhiteSpace(i));let a="";for(;i>=32&&i<=57;){a+=String.fromCharCode(i);i=e.getByte()}t=parseInt(a,10);isNaN(t)&&(t=0)}}return shadow(this,"startXRef",t)}checkHeader(){const e=this.stream;e.reset();if(!find(e,ig))return;e.moveStart();e.skip(ig.length);let t,i="";for(;(t=e.getByte())>32&&i.length<7;)i+=String.fromCharCode(t);ft.test(i)?this._version=i:warn(`Invalid PDF header version: ${i}`)}parseStartXRef(){this.xref.setStartXRef(this.startXRef)}get numPages(){let e=0;e=this.catalog.hasActualNumPages?this.catalog.numPages:this.xfaFactory?this.xfaFactory.getNumPages():this.linearization?this.linearization.numPages:this.catalog.numPages;return shadow(this,"numPages",e)}_hasOnlyDocumentSignatures(e,t=0){return!!Array.isArray(e)&&e.every((e=>{if(!((e=this.xref.fetchIfRef(e))instanceof Dict))return!1;if(e.has("Kids")){if(++t>10){warn("_hasOnlyDocumentSignatures: maximum recursion depth reached");return!1}return this._hasOnlyDocumentSignatures(e.get("Kids"),t)}const i=isName(e.get("FT"),"Sig"),a=e.get("Rect"),s=Array.isArray(a)&&a.every((e=>0===e));return i&&s}))}get _xfaStreams(){const e=this.catalog.acroForm;if(!e)return null;const t=e.get("XFA"),i={"xdp:xdp":"",template:"",datasets:"",config:"",connectionSet:"",localeSet:"",stylesheet:"","/xdp:xdp":""};if(t instanceof BaseStream&&!t.isEmpty){i["xdp:xdp"]=t;return i}if(!Array.isArray(t)||0===t.length)return null;for(let e=0,a=t.length;e0;e.hasFields=a;const s=t.get("XFA");e.hasXfa=Array.isArray(s)&&s.length>0||s instanceof BaseStream&&!s.isEmpty;const r=!!(1&t.get("SigFlags")),n=r&&this._hasOnlyDocumentSignatures(i);e.hasAcroForm=a&&!n;e.hasSignatures=r}catch(e){if(e instanceof MissingDataException)throw e;warn(`Cannot fetch form information: "${e}".`)}return shadow(this,"formInfo",e)}get documentInfo(){const e={PDFFormatVersion:this.version,Language:this.catalog.lang,EncryptFilterName:this.xref.encrypt?this.xref.encrypt.filterName:null,IsLinearized:!!this.linearization,IsAcroFormPresent:this.formInfo.hasAcroForm,IsXFAPresent:this.formInfo.hasXfa,IsCollectionPresent:!!this.catalog.collection,IsSignaturesPresent:this.formInfo.hasSignatures};let t;try{t=this.xref.trailer.get("Info")}catch(e){if(e instanceof MissingDataException)throw e;info("The document information dictionary is invalid.")}if(!(t instanceof Dict))return shadow(this,"documentInfo",e);for(const i of t.getKeys()){const a=t.get(i);switch(i){case"Title":case"Author":case"Subject":case"Keywords":case"Creator":case"Producer":case"CreationDate":case"ModDate":if("string"==typeof a){e[i]=stringToPDFString(a);continue}break;case"Trapped":if(a instanceof Name){e[i]=a;continue}break;default:let t;switch(typeof a){case"string":t=stringToPDFString(a);break;case"number":case"boolean":t=a;break;default:a instanceof Name&&(t=a)}if(void 0===t){warn(`Bad value, for custom key "${i}", in Info: ${a}.`);continue}e.Custom||(e.Custom=Object.create(null));e.Custom[i]=t;continue}warn(`Bad value, for key "${i}", in Info: ${a}.`)}return shadow(this,"documentInfo",e)}get fingerprints(){const e="\0".repeat(16);function validate(t){return"string"==typeof t&&16===t.length&&t!==e}const t=this.xref.trailer.get("ID");let i,a;if(Array.isArray(t)&&validate(t[0])){i=stringToBytes(t[0]);t[1]!==t[0]&&validate(t[1])&&(a=stringToBytes(t[1]))}else i=$n(this.stream.getByteRange(0,1024),0,1024);return shadow(this,"fingerprints",[toHexUtil(i),a?toHexUtil(a):null])}async _getLinearizationPage(e){const{catalog:t,linearization:i,xref:a}=this,s=Ref.get(i.objectNumberFirst,0);try{const e=await a.fetchAsync(s);if(e instanceof Dict){let i=e.getRaw("Type");i instanceof Ref&&(i=await a.fetchAsync(i));if(isName(i,"Page")||!e.has("Type")&&!e.has("Kids")&&e.has("Contents")){t.pageKidsCountCache.has(s)||t.pageKidsCountCache.put(s,1);t.pageIndexCache.has(s)||t.pageIndexCache.put(s,0);return[e,s]}}throw new FormatError("The Linearization dictionary doesn't point to a valid Page dictionary.")}catch(i){warn(`_getLinearizationPage: "${i.message}".`);return t.getPageDict(e)}}getPage(e){const t=this._pagePromises.get(e);if(t)return t;const{catalog:i,linearization:a,xfaFactory:s}=this;let r;r=s?Promise.resolve([Dict.empty,null]):a?.pageFirst===e?this._getLinearizationPage(e):i.getPageDict(e);r=r.then((([t,a])=>new Page({pdfManager:this.pdfManager,xref:this.xref,pageIndex:e,pageDict:t,ref:a,globalIdFactory:this._globalIdFactory,fontCache:i.fontCache,builtInCMapCache:i.builtInCMapCache,standardFontDataCache:i.standardFontDataCache,globalImageCache:i.globalImageCache,systemFontCache:i.systemFontCache,nonBlendModesSet:i.nonBlendModesSet,xfaFactory:s})));this._pagePromises.set(e,r);return r}async checkFirstPage(e=!1){if(!e)try{await this.getPage(0)}catch(e){if(e instanceof XRefEntryException){this._pagePromises.delete(0);await this.cleanup();throw new XRefParseException}}}async checkLastPage(e=!1){const{catalog:t,pdfManager:i}=this;t.setActualNumPages();let a;try{await Promise.all([i.ensureDoc("xfaFactory"),i.ensureDoc("linearization"),i.ensureCatalog("numPages")]);if(this.xfaFactory)return;a=this.linearization?this.linearization.numPages:t.numPages;if(!Number.isInteger(a))throw new FormatError("Page count is not an integer.");if(a<=1)return;await this.getPage(a-1)}catch(s){this._pagePromises.delete(a-1);await this.cleanup();if(s instanceof XRefEntryException&&!e)throw new XRefParseException;warn(`checkLastPage - invalid /Pages tree /Count: ${a}.`);let r;try{r=await t.getAllPageDicts(e)}catch(i){if(i instanceof XRefEntryException&&!e)throw new XRefParseException;t.setActualNumPages(1);return}for(const[e,[a,s]]of r){let r;if(a instanceof Error){r=Promise.reject(a);r.catch((()=>{}))}else r=Promise.resolve(new Page({pdfManager:i,xref:this.xref,pageIndex:e,pageDict:a,ref:s,globalIdFactory:this._globalIdFactory,fontCache:t.fontCache,builtInCMapCache:t.builtInCMapCache,standardFontDataCache:t.standardFontDataCache,globalImageCache:t.globalImageCache,systemFontCache:t.systemFontCache,nonBlendModesSet:t.nonBlendModesSet,xfaFactory:null}));this._pagePromises.set(e,r)}t.setActualNumPages(r.size)}}fontFallback(e,t){return this.catalog.fontFallback(e,t)}async cleanup(e=!1){return this.catalog?this.catalog.cleanup(e):clearGlobalCaches()}async#z(e,t,i,a,s,r,n){const{xref:g}=this;if(!(i instanceof Ref)||r.has(i))return;r.put(i);const o=await g.fetchAsync(i);if(!(o instanceof Dict))return;if(o.has("T")){const t=stringToPDFString(await o.getAsync("T"));e=""===e?t:`${e}.${t}`}else{let i=o;for(;;){i=i.getRaw("Parent")||t;if(i instanceof Ref){if(r.has(i))break;i=await g.fetchAsync(i)}if(!(i instanceof Dict))break;if(i.has("T")){const t=stringToPDFString(await i.getAsync("T"));e=""===e?t:`${e}.${t}`;break}}}t&&!o.has("Parent")&&isName(o.get("Subtype"),"Widget")&&n.put(i,t);a.has(e)||a.set(e,[]);a.get(e).push(AnnotationFactory.create(g,i,s,null,!0,n,null).then((e=>e?.getFieldObject())).catch((function(e){warn(`#collectFieldObjects: "${e}".`);return null})));if(!o.has("Kids"))return;const c=await o.getAsync("Kids");if(Array.isArray(c))for(const t of c)await this.#z(e,i,t,a,s,r,n)}get fieldObjects(){return shadow(this,"fieldObjects",this.pdfManager.ensureDoc("formInfo").then((async e=>{if(!e.hasFields)return null;const[t,i]=await Promise.all([this.pdfManager.ensureDoc("annotationGlobals"),this.pdfManager.ensureCatalog("acroForm")]);if(!t)return null;const a=new RefSet,s=Object.create(null),r=new Map,n=new RefSetCache;for(const e of await i.getAsync("Fields"))await this.#z("",null,e,r,t,a,n);const g=[];for(const[e,t]of r)g.push(Promise.all(t).then((t=>{(t=t.filter((e=>!!e))).length>0&&(s[e]=t)})));await Promise.all(g);return{allFields:s,orphanFields:n}})))}get hasJSActions(){return shadow(this,"hasJSActions",this.pdfManager.ensureDoc("_parseHasJSActions"))}async _parseHasJSActions(){const[e,t]=await Promise.all([this.pdfManager.ensureCatalog("jsActions"),this.pdfManager.ensureDoc("fieldObjects")]);return!!e||!!t&&Object.values(t.allFields).some((e=>e.some((e=>null!==e.actions))))}get calculationOrderIds(){const e=this.catalog.acroForm?.get("CO");if(!Array.isArray(e)||0===e.length)return shadow(this,"calculationOrderIds",null);const t=[];for(const i of e)i instanceof Ref&&t.push(i.toString());return shadow(this,"calculationOrderIds",t.length?t:null)}get annotationGlobals(){return shadow(this,"annotationGlobals",AnnotationFactory.createGlobals(this.pdfManager))}}class BasePdfManager{constructor(e){this._docBaseUrl=function parseDocBaseUrl(e){if(e){const t=createValidAbsoluteUrl(e);if(t)return t.href;warn(`Invalid absolute docBaseUrl: "${e}".`)}return null}(e.docBaseUrl);this._docId=e.docId;this._password=e.password;this.enableXfa=e.enableXfa;e.evaluatorOptions.isOffscreenCanvasSupported&&=FeatureTest.isOffscreenCanvasSupported;e.evaluatorOptions.isImageDecoderSupported&&=FeatureTest.isImageDecoderSupported;this.evaluatorOptions=Object.freeze(e.evaluatorOptions)}get docId(){return this._docId}get password(){return this._password}get docBaseUrl(){return this._docBaseUrl}get catalog(){return this.pdfDocument.catalog}ensureDoc(e,t){return this.ensure(this.pdfDocument,e,t)}ensureXRef(e,t){return this.ensure(this.pdfDocument.xref,e,t)}ensureCatalog(e,t){return this.ensure(this.pdfDocument.catalog,e,t)}getPage(e){return this.pdfDocument.getPage(e)}fontFallback(e,t){return this.pdfDocument.fontFallback(e,t)}loadXfaFonts(e,t){return this.pdfDocument.loadXfaFonts(e,t)}loadXfaImages(){return this.pdfDocument.loadXfaImages()}serializeXfaData(e){return this.pdfDocument.serializeXfaData(e)}cleanup(e=!1){return this.pdfDocument.cleanup(e)}async ensure(e,t,i){unreachable("Abstract method `ensure` called")}requestRange(e,t){unreachable("Abstract method `requestRange` called")}requestLoadedStream(e=!1){unreachable("Abstract method `requestLoadedStream` called")}sendProgressiveData(e){unreachable("Abstract method `sendProgressiveData` called")}updatePassword(e){this._password=e}terminate(e){unreachable("Abstract method `terminate` called")}}class LocalPdfManager extends BasePdfManager{constructor(e){super(e);const t=new Stream(e.source);this.pdfDocument=new PDFDocument(this,t);this._loadedStreamPromise=Promise.resolve(t)}async ensure(e,t,i){const a=e[t];return"function"==typeof a?a.apply(e,i):a}requestRange(e,t){return Promise.resolve()}requestLoadedStream(e=!1){return this._loadedStreamPromise}terminate(e){}}class NetworkPdfManager extends BasePdfManager{constructor(e){super(e);this.streamManager=new ChunkedStreamManager(e.source,{msgHandler:e.handler,length:e.length,disableAutoFetch:e.disableAutoFetch,rangeChunkSize:e.rangeChunkSize});this.pdfDocument=new PDFDocument(this,this.streamManager.getStream())}async ensure(e,t,i){try{const a=e[t];return"function"==typeof a?a.apply(e,i):a}catch(a){if(!(a instanceof MissingDataException))throw a;await this.requestRange(a.begin,a.end);return this.ensure(e,t,i)}}requestRange(e,t){return this.streamManager.requestRange(e,t)}requestLoadedStream(e=!1){return this.streamManager.requestAllChunks(e)}sendProgressiveData(e){this.streamManager.onReceiveData({chunk:e})}terminate(e){this.streamManager.abort(e)}}const rg=1,ng=2,gg=1,og=2,Ig=3,cg=4,Cg=5,hg=6,lg=7,Bg=8;function onFn(){}function wrapReason(e){if(e instanceof AbortException||e instanceof InvalidPDFException||e instanceof MissingPDFException||e instanceof PasswordException||e instanceof UnexpectedResponseException||e instanceof UnknownErrorException)return e;e instanceof Error||"object"==typeof e&&null!==e||unreachable('wrapReason: Expected "reason" to be a (possibly cloned) Error.');switch(e.name){case"AbortException":return new AbortException(e.message);case"InvalidPDFException":return new InvalidPDFException(e.message);case"MissingPDFException":return new MissingPDFException(e.message);case"PasswordException":return new PasswordException(e.message,e.code);case"UnexpectedResponseException":return new UnexpectedResponseException(e.message,e.status);case"UnknownErrorException":return new UnknownErrorException(e.message,e.details)}return new UnknownErrorException(e.message,e.toString())}class MessageHandler{#_=new AbortController;constructor(e,t,i){this.sourceName=e;this.targetName=t;this.comObj=i;this.callbackId=1;this.streamId=1;this.streamSinks=Object.create(null);this.streamControllers=Object.create(null);this.callbackCapabilities=Object.create(null);this.actionHandler=Object.create(null);i.addEventListener("message",this.#$.bind(this),{signal:this.#_.signal})}#$({data:e}){if(e.targetName!==this.sourceName)return;if(e.stream){this.#AA(e);return}if(e.callback){const t=e.callbackId,i=this.callbackCapabilities[t];if(!i)throw new Error(`Cannot resolve callback ${t}`);delete this.callbackCapabilities[t];if(e.callback===rg)i.resolve(e.data);else{if(e.callback!==ng)throw new Error("Unexpected callback case");i.reject(wrapReason(e.reason))}return}const t=this.actionHandler[e.action];if(!t)throw new Error(`Unknown action from worker: ${e.action}`);if(e.callbackId){const i=this.sourceName,a=e.sourceName,s=this.comObj;Promise.try(t,e.data).then((function(t){s.postMessage({sourceName:i,targetName:a,callback:rg,callbackId:e.callbackId,data:t})}),(function(t){s.postMessage({sourceName:i,targetName:a,callback:ng,callbackId:e.callbackId,reason:wrapReason(t)})}))}else e.streamId?this.#eA(e):t(e.data)}on(e,t){const i=this.actionHandler;if(i[e])throw new Error(`There is already an actionName called "${e}"`);i[e]=t}send(e,t,i){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,data:t},i)}sendWithPromise(e,t,i){const a=this.callbackId++,s=Promise.withResolvers();this.callbackCapabilities[a]=s;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,callbackId:a,data:t},i)}catch(e){s.reject(e)}return s.promise}sendWithStream(e,t,i,a){const s=this.streamId++,r=this.sourceName,n=this.targetName,g=this.comObj;return new ReadableStream({start:i=>{const o=Promise.withResolvers();this.streamControllers[s]={controller:i,startCall:o,pullCall:null,cancelCall:null,isClosed:!1};g.postMessage({sourceName:r,targetName:n,action:e,streamId:s,data:t,desiredSize:i.desiredSize},a);return o.promise},pull:e=>{const t=Promise.withResolvers();this.streamControllers[s].pullCall=t;g.postMessage({sourceName:r,targetName:n,stream:hg,streamId:s,desiredSize:e.desiredSize});return t.promise},cancel:e=>{assert(e instanceof Error,"cancel must have a valid reason");const t=Promise.withResolvers();this.streamControllers[s].cancelCall=t;this.streamControllers[s].isClosed=!0;g.postMessage({sourceName:r,targetName:n,stream:gg,streamId:s,reason:wrapReason(e)});return t.promise}},i)}#eA(e){const t=e.streamId,i=this.sourceName,a=e.sourceName,s=this.comObj,r=this,n=this.actionHandler[e.action],g={enqueue(e,r=1,n){if(this.isCancelled)return;const g=this.desiredSize;this.desiredSize-=r;if(g>0&&this.desiredSize<=0){this.sinkCapability=Promise.withResolvers();this.ready=this.sinkCapability.promise}s.postMessage({sourceName:i,targetName:a,stream:cg,streamId:t,chunk:e},n)},close(){if(!this.isCancelled){this.isCancelled=!0;s.postMessage({sourceName:i,targetName:a,stream:Ig,streamId:t});delete r.streamSinks[t]}},error(e){assert(e instanceof Error,"error must have a valid reason");if(!this.isCancelled){this.isCancelled=!0;s.postMessage({sourceName:i,targetName:a,stream:Cg,streamId:t,reason:wrapReason(e)})}},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:e.desiredSize,ready:null};g.sinkCapability.resolve();g.ready=g.sinkCapability.promise;this.streamSinks[t]=g;Promise.try(n,e.data,g).then((function(){s.postMessage({sourceName:i,targetName:a,stream:Bg,streamId:t,success:!0})}),(function(e){s.postMessage({sourceName:i,targetName:a,stream:Bg,streamId:t,reason:wrapReason(e)})}))}#AA(e){const t=e.streamId,i=this.sourceName,a=e.sourceName,s=this.comObj,r=this.streamControllers[t],n=this.streamSinks[t];switch(e.stream){case Bg:e.success?r.startCall.resolve():r.startCall.reject(wrapReason(e.reason));break;case lg:e.success?r.pullCall.resolve():r.pullCall.reject(wrapReason(e.reason));break;case hg:if(!n){s.postMessage({sourceName:i,targetName:a,stream:lg,streamId:t,success:!0});break}n.desiredSize<=0&&e.desiredSize>0&&n.sinkCapability.resolve();n.desiredSize=e.desiredSize;Promise.try(n.onPull||onFn).then((function(){s.postMessage({sourceName:i,targetName:a,stream:lg,streamId:t,success:!0})}),(function(e){s.postMessage({sourceName:i,targetName:a,stream:lg,streamId:t,reason:wrapReason(e)})}));break;case cg:assert(r,"enqueue should have stream controller");if(r.isClosed)break;r.controller.enqueue(e.chunk);break;case Ig:assert(r,"close should have stream controller");if(r.isClosed)break;r.isClosed=!0;r.controller.close();this.#tA(r,t);break;case Cg:assert(r,"error should have stream controller");r.controller.error(wrapReason(e.reason));this.#tA(r,t);break;case og:e.success?r.cancelCall.resolve():r.cancelCall.reject(wrapReason(e.reason));this.#tA(r,t);break;case gg:if(!n)break;const g=wrapReason(e.reason);Promise.try(n.onCancel||onFn,g).then((function(){s.postMessage({sourceName:i,targetName:a,stream:og,streamId:t,success:!0})}),(function(e){s.postMessage({sourceName:i,targetName:a,stream:og,streamId:t,reason:wrapReason(e)})}));n.sinkCapability.reject(g);n.isCancelled=!0;delete this.streamSinks[t];break;default:throw new Error("Unexpected stream case")}}async#tA(e,t){await Promise.allSettled([e.startCall?.promise,e.pullCall?.promise,e.cancelCall?.promise]);delete this.streamControllers[t]}destroy(){this.#_?.abort();this.#_=null}}async function writeObject(e,t,i,{encrypt:a=null}){const s=a?.createCipherTransform(e.num,e.gen);i.push(`${e.num} ${e.gen} obj\n`);t instanceof Dict?await writeDict(t,i,s):t instanceof BaseStream?await writeStream(t,i,s):(Array.isArray(t)||ArrayBuffer.isView(t))&&await writeArray(t,i,s);i.push("\nendobj\n")}async function writeDict(e,t,i){t.push("<<");for(const a of e.getKeys()){t.push(` /${escapePDFName(a)} `);await writeValue(e.getRaw(a),t,i)}t.push(">>")}async function writeStream(e,t,i){let a=e.getBytes();const{dict:s}=e,[r,n]=await Promise.all([s.getAsync("Filter"),s.getAsync("DecodeParms")]),g=isName(Array.isArray(r)?await s.xref.fetchIfRefAsync(r[0]):r,"FlateDecode");if(a.length>=256||g)try{const e=new CompressionStream("deflate"),t=e.writable.getWriter();await t.ready;t.write(a).then((async()=>{await t.ready;await t.close()})).catch((()=>{}));const i=await new Response(e.readable).arrayBuffer();a=new Uint8Array(i);let o,c;if(r){if(!g){o=Array.isArray(r)?[Name.get("FlateDecode"),...r]:[Name.get("FlateDecode"),r];n&&(c=Array.isArray(n)?[null,...n]:[null,n])}}else o=Name.get("FlateDecode");o&&s.set("Filter",o);c&&s.set("DecodeParms",c)}catch(e){info(`writeStream - cannot compress data: "${e}".`)}let o=bytesToString(a);i&&(o=i.encryptString(o));s.set("Length",o.length);await writeDict(s,t,i);t.push(" stream\n",o,"\nendstream")}async function writeArray(e,t,i){t.push("[");let a=!0;for(const s of e){a?a=!1:t.push(" ");await writeValue(s,t,i)}t.push("]")}async function writeValue(e,t,i){if(e instanceof Name)t.push(`/${escapePDFName(e.name)}`);else if(e instanceof Ref)t.push(`${e.num} ${e.gen} R`);else if(Array.isArray(e)||ArrayBuffer.isView(e))await writeArray(e,t,i);else if("string"==typeof e){i&&(e=i.encryptString(e));t.push(`(${escapeString(e)})`)}else"number"==typeof e?t.push(numberToString(e)):"boolean"==typeof e?t.push(e.toString()):e instanceof Dict?await writeDict(e,t,i):e instanceof BaseStream?await writeStream(e,t,i):null===e?t.push("null"):warn(`Unhandled value in writer: ${typeof e}, please file a bug.`)}function writeInt(e,t,i,a){for(let s=t+i-1;s>i-1;s--){a[s]=255&e;e>>=8}return i+t}function writeString(e,t,i){for(let a=0,s=e.length;a1&&(r=i.documentElement.searchNode([s.at(-1)],0));r?r.childNodes=Array.isArray(a)?a.map((e=>new SimpleDOMNode("value",e))):[new SimpleDOMNode("#text",a)]:warn(`Node not found for path: ${t}`)}const a=[];i.documentElement.dump(a);return a.join("")}(a.fetchIfRef(t).getString(),i)}const s=new StringStream(e);s.dict=new Dict(a);s.dict.set("Type",Name.get("EmbeddedFile"));i.put(t,{data:s})}function getIndexes(e){const t=[];for(const{ref:i}of e)i.num===t.at(-2)+t.at(-1)?t[t.length-1]+=1:t.push(i.num,1);return t}function computeIDs(e,t,i){if(Array.isArray(t.fileIds)&&t.fileIds.length>0){const a=function computeMD5(e,t){const i=Math.floor(Date.now()/1e3),a=t.filename||"",s=[i.toString(),a,e.toString()];let r=s.reduce(((e,t)=>e+t.length),0);for(const e of Object.values(t.info)){s.push(e);r+=e.length}const n=new Uint8Array(r);let g=0;for(const e of s){writeString(e,g,n);g+=e.length}return bytesToString($n(n))}(e,t);i.set("ID",[t.fileIds[0],a])}}async function incrementalUpdate({originalData:e,xrefInfo:t,changes:i,xref:a=null,hasXfa:s=!1,xfaDatasetsRef:r=null,hasXfaDatasetsEntry:n=!1,needAppearances:g,acroFormRef:o=null,acroForm:c=null,xfaData:C=null,useXrefStream:h=!1}){await async function updateAcroform({xref:e,acroForm:t,acroFormRef:i,hasXfa:a,hasXfaDatasetsEntry:s,xfaDatasetsRef:r,needAppearances:n,changes:g}){!a||s||r||warn("XFA - Cannot save it");if(!n&&(!a||!r||s))return;const o=t.clone();if(a&&!s){const e=t.get("XFA").slice();e.splice(2,0,"datasets");e.splice(3,0,r);o.set("XFA",e)}n&&o.set("NeedAppearances",!0);g.put(i,{data:o})}({xref:a,acroForm:c,acroFormRef:o,hasXfa:s,hasXfaDatasetsEntry:n,xfaDatasetsRef:r,needAppearances:g,changes:i});s&&updateXFA({xfaData:C,xfaDatasetsRef:r,changes:i,xref:a});const l=function getTrailerDict(e,t,i){const a=new Dict(null);a.set("Prev",e.startXRef);const s=e.newRef;if(i){t.put(s,{data:""});a.set("Size",s.num+1);a.set("Type",Name.get("XRef"))}else a.set("Size",s.num);null!==e.rootRef&&a.set("Root",e.rootRef);null!==e.infoRef&&a.set("Info",e.infoRef);null!==e.encryptRef&&a.set("Encrypt",e.encryptRef);return a}(t,i,h),Q=[],E=await async function writeChanges(e,t,i=[]){const a=[];for(const[s,{data:r}]of e.items())if(null!==r&&"string"!=typeof r){await writeObject(s,r,i,t);a.push({ref:s,data:i.join("")});i.length=0}else a.push({ref:s,data:r});return a.sort(((e,t)=>e.ref.num-t.ref.num))}(i,a,Q);let u=e.length;const d=e.at(-1);if(10!==d&&13!==d){Q.push("\n");u+=1}for(const{data:e}of E)null!==e&&Q.push(e);await(h?async function getXRefStreamTable(e,t,i,a,s){const r=[];let n=0,g=0;for(const{ref:e,data:a}of i){let i;n=Math.max(n,t);if(null!==a){i=Math.min(e.gen,65535);r.push([1,t,i]);t+=a.length}else{i=Math.min(e.gen+1,65535);r.push([0,0,i])}g=Math.max(g,i)}a.set("Index",getIndexes(i));const o=[1,getSizeInBytes(n),getSizeInBytes(g)];a.set("W",o);computeIDs(t,e,a);const c=o.reduce(((e,t)=>e+t),0),C=new Uint8Array(c*r.length),h=new Stream(C);h.dict=a;let l=0;for(const[e,t,i]of r){l=writeInt(e,o[0],l,C);l=writeInt(t,o[1],l,C);l=writeInt(i,o[2],l,C)}await writeObject(e.newRef,h,s,{});s.push("startxref\n",t.toString(),"\n%%EOF\n")}(t,u,E,l,Q):async function getXRefTable(e,t,i,a,s){s.push("xref\n");const r=getIndexes(i);let n=0;for(const{ref:e,data:a}of i){if(e.num===r[n]){s.push(`${r[n]} ${r[n+1]}\n`);n+=2}if(null!==a){s.push(`${t.toString().padStart(10,"0")} ${Math.min(e.gen,65535).toString().padStart(5,"0")} n\r\n`);t+=a.length}else s.push(`0000000000 ${Math.min(e.gen+1,65535).toString().padStart(5,"0")} f\r\n`)}computeIDs(t,e,a);s.push("trailer\n");await writeDict(a,s);s.push("\nstartxref\n",t.toString(),"\n%%EOF\n")}(t,u,E,l,Q));const f=Q.reduce(((e,t)=>e+t.length),e.length),p=new Uint8Array(f);p.set(e);let m=e.length;for(const e of Q){writeString(e,m,p);m+=e.length}return p}class PDFWorkerStream{constructor(e){this._msgHandler=e;this._contentLength=null;this._fullRequestReader=null;this._rangeRequestReaders=[]}getFullReader(){assert(!this._fullRequestReader,"PDFWorkerStream.getFullReader can only be called once.");this._fullRequestReader=new PDFWorkerStreamReader(this._msgHandler);return this._fullRequestReader}getRangeReader(e,t){const i=new PDFWorkerStreamRangeReader(e,t,this._msgHandler);this._rangeRequestReaders.push(i);return i}cancelAllRequests(e){this._fullRequestReader?.cancel(e);for(const t of this._rangeRequestReaders.slice(0))t.cancel(e)}}class PDFWorkerStreamReader{constructor(e){this._msgHandler=e;this.onProgress=null;this._contentLength=null;this._isRangeSupported=!1;this._isStreamingSupported=!1;const t=this._msgHandler.sendWithStream("GetReader");this._reader=t.getReader();this._headersReady=this._msgHandler.sendWithPromise("ReaderHeadersReady").then((e=>{this._isStreamingSupported=e.isStreamingSupported;this._isRangeSupported=e.isRangeSupported;this._contentLength=e.contentLength}))}get headersReady(){return this._headersReady}get contentLength(){return this._contentLength}get isStreamingSupported(){return this._isStreamingSupported}get isRangeSupported(){return this._isRangeSupported}async read(){const{value:e,done:t}=await this._reader.read();return t?{value:void 0,done:!0}:{value:e.buffer,done:!1}}cancel(e){this._reader.cancel(e)}}class PDFWorkerStreamRangeReader{constructor(e,t,i){this._msgHandler=i;this.onProgress=null;const a=this._msgHandler.sendWithStream("GetRangeReader",{begin:e,end:t});this._reader=a.getReader()}get isStreamingSupported(){return!1}async read(){const{value:e,done:t}=await this._reader.read();return t?{value:void 0,done:!0}:{value:e.buffer,done:!1}}cancel(e){this._reader.cancel(e)}}class WorkerTask{constructor(e){this.name=e;this.terminated=!1;this._capability=Promise.withResolvers()}get finished(){return this._capability.promise}finish(){this._capability.resolve()}terminate(){this.terminated=!0}ensureNotTerminated(){if(this.terminated)throw new Error("Worker task was terminated")}}class WorkerMessageHandler{static{"undefined"==typeof window&&!t&&"undefined"!=typeof self&&"function"==typeof self.postMessage&&"onmessage"in self&&this.initializeFromPort(self)}static setup(e,t){let i=!1;e.on("test",(t=>{if(!i){i=!0;e.send("test",t instanceof Uint8Array)}}));e.on("configure",(e=>{!function setVerbosityLevel(e){Number.isInteger(e)&&(gt=e)}(e.verbosity)}));e.on("GetDocRequest",(e=>this.createDocumentHandler(e,t)))}static createDocumentHandler(e,t){let i,a=!1,s=null;const r=new Set,n=getVerbosityLevel(),{docId:g,apiVersion:o}=e,c="4.10.38";if(o!==c)throw new Error(`The API version "${o}" does not match the Worker version "${c}".`);const C=[];for(const e in[])C.push(e);if(C.length)throw new Error("The `Array.prototype` contains unexpected enumerable properties: "+C.join(", ")+"; thus breaking e.g. `for...in` iteration of `Array`s.");const h=g+"_worker";let l=new MessageHandler(h,g,t);function ensureNotTerminated(){if(a)throw new Error("Worker was terminated")}function startWorkerTask(e){r.add(e)}function finishWorkerTask(e){e.finish();r.delete(e)}async function loadDocument(e){await i.ensureDoc("checkHeader");await i.ensureDoc("parseStartXRef");await i.ensureDoc("parse",[e]);await i.ensureDoc("checkFirstPage",[e]);await i.ensureDoc("checkLastPage",[e]);const t=await i.ensureDoc("isPureXfa");if(t){const e=new WorkerTask("loadXfaFonts");startWorkerTask(e);await Promise.all([i.loadXfaFonts(l,e).catch((e=>{})).then((()=>finishWorkerTask(e))),i.loadXfaImages()])}const[a,s]=await Promise.all([i.ensureDoc("numPages"),i.ensureDoc("fingerprints")]);return{numPages:a,fingerprints:s,htmlForXfa:t?await i.ensureDoc("htmlForXfa"):null}}function setupDoc(e){function onSuccess(e){ensureNotTerminated();l.send("GetDoc",{pdfInfo:e})}function onFailure(e){ensureNotTerminated();if(e instanceof PasswordException){const t=new WorkerTask(`PasswordException: response ${e.code}`);startWorkerTask(t);l.sendWithPromise("PasswordRequest",e).then((function({password:e}){finishWorkerTask(t);i.updatePassword(e);pdfManagerReady()})).catch((function(){finishWorkerTask(t);l.send("DocException",e)}))}else l.send("DocException",wrapReason(e))}function pdfManagerReady(){ensureNotTerminated();loadDocument(!1).then(onSuccess,(function(e){ensureNotTerminated();e instanceof XRefParseException?i.requestLoadedStream().then((function(){ensureNotTerminated();loadDocument(!0).then(onSuccess,onFailure)})):onFailure(e)}))}ensureNotTerminated();(async function getPdfManager({data:e,password:t,disableAutoFetch:i,rangeChunkSize:a,length:r,docBaseUrl:n,enableXfa:o,evaluatorOptions:c}){const C={source:null,disableAutoFetch:i,docBaseUrl:n,docId:g,enableXfa:o,evaluatorOptions:c,handler:l,length:r,password:t,rangeChunkSize:a};if(e){C.source=e;return new LocalPdfManager(C)}const h=new PDFWorkerStream(l),Q=h.getFullReader(),E=Promise.withResolvers();let u,d=[],f=0;Q.headersReady.then((function(){if(Q.isRangeSupported){C.source=h;C.length=Q.contentLength;C.disableAutoFetch||=Q.isStreamingSupported;u=new NetworkPdfManager(C);for(const e of d)u.sendProgressiveData(e);d=[];E.resolve(u);s=null}})).catch((function(e){E.reject(e);s=null}));new Promise((function(e,t){const readChunk=function({value:e,done:i}){try{ensureNotTerminated();if(i){if(!u){const e=arrayBuffersToBytes(d);d=[];r&&e.length!==r&&warn("reported HTTP length is different from actual");C.source=e;u=new LocalPdfManager(C);E.resolve(u)}s=null;return}f+=e.byteLength;Q.isStreamingSupported||l.send("DocProgress",{loaded:f,total:Math.max(f,Q.contentLength||0)});u?u.sendProgressiveData(e):d.push(e);Q.read().then(readChunk,t)}catch(e){t(e)}};Q.read().then(readChunk,t)})).catch((function(e){E.reject(e);s=null}));s=e=>{h.cancelAllRequests(e)};return E.promise})(e).then((function(e){if(a){e.terminate(new AbortException("Worker was terminated."));throw new Error("Worker was terminated")}i=e;i.requestLoadedStream(!0).then((e=>{l.send("DataLoaded",{length:e.bytes.byteLength})}))})).then(pdfManagerReady,onFailure)}l.on("GetPage",(function(e){return i.getPage(e.pageIndex).then((function(e){return Promise.all([i.ensure(e,"rotate"),i.ensure(e,"ref"),i.ensure(e,"userUnit"),i.ensure(e,"view")]).then((function([e,t,i,a]){return{rotate:e,ref:t,refStr:t?.toString()??null,userUnit:i,view:a}}))}))}));l.on("GetPageIndex",(function(e){const t=Ref.get(e.num,e.gen);return i.ensureCatalog("getPageIndex",[t])}));l.on("GetDestinations",(function(e){return i.ensureCatalog("destinations")}));l.on("GetDestination",(function(e){return i.ensureCatalog("getDestination",[e.id])}));l.on("GetPageLabels",(function(e){return i.ensureCatalog("pageLabels")}));l.on("GetPageLayout",(function(e){return i.ensureCatalog("pageLayout")}));l.on("GetPageMode",(function(e){return i.ensureCatalog("pageMode")}));l.on("GetViewerPreferences",(function(e){return i.ensureCatalog("viewerPreferences")}));l.on("GetOpenAction",(function(e){return i.ensureCatalog("openAction")}));l.on("GetAttachments",(function(e){return i.ensureCatalog("attachments")}));l.on("GetDocJSActions",(function(e){return i.ensureCatalog("jsActions")}));l.on("GetPageJSActions",(function({pageIndex:e}){return i.getPage(e).then((function(e){return i.ensure(e,"jsActions")}))}));l.on("GetOutline",(function(e){return i.ensureCatalog("documentOutline")}));l.on("GetOptionalContentConfig",(function(e){return i.ensureCatalog("optionalContentConfig")}));l.on("GetPermissions",(function(e){return i.ensureCatalog("permissions")}));l.on("GetMetadata",(function(e){return Promise.all([i.ensureDoc("documentInfo"),i.ensureCatalog("metadata")])}));l.on("GetMarkInfo",(function(e){return i.ensureCatalog("markInfo")}));l.on("GetData",(function(e){return i.requestLoadedStream().then((function(e){return e.bytes}))}));l.on("GetAnnotations",(function({pageIndex:e,intent:t}){return i.getPage(e).then((function(i){const a=new WorkerTask(`GetAnnotations: page ${e}`);startWorkerTask(a);return i.getAnnotationsData(l,a,t).then((e=>{finishWorkerTask(a);return e}),(e=>{finishWorkerTask(a);throw e}))}))}));l.on("GetFieldObjects",(function(e){return i.ensureDoc("fieldObjects").then((e=>e?.allFields||null))}));l.on("HasJSActions",(function(e){return i.ensureDoc("hasJSActions")}));l.on("GetCalculationOrderIds",(function(e){return i.ensureDoc("calculationOrderIds")}));l.on("SaveDocument",(async function({isPureXfa:e,numPages:t,annotationStorage:a,filename:s}){const r=[i.requestLoadedStream(),i.ensureCatalog("acroForm"),i.ensureCatalog("acroFormRef"),i.ensureDoc("startXRef"),i.ensureDoc("xref"),i.ensureDoc("linearization"),i.ensureCatalog("structTreeRoot")],n=new RefSetCache,g=[],o=e?null:getNewAnnotationsMap(a),[c,C,h,Q,E,u,d]=await Promise.all(r),f=E.trailer.getRaw("Root")||null;let p;if(o){d?await d.canUpdateStructTree({pdfManager:i,xref:E,newAnnotationsByPage:o})&&(p=d):await StructTreeRoot.canCreateStructureTree({catalogRef:f,pdfManager:i,newAnnotationsByPage:o})&&(p=null);const e=AnnotationFactory.generateImages(a.values(),E,i.evaluatorOptions.isOffscreenCanvasSupported),t=void 0===p?g:[];for(const[a,s]of o)t.push(i.getPage(a).then((t=>{const i=new WorkerTask(`Save (editor): page ${a}`);startWorkerTask(i);return t.saveNewAnnotations(l,i,s,e,n).finally((function(){finishWorkerTask(i)}))})));null===p?g.push(Promise.all(t).then((async()=>{await StructTreeRoot.createStructureTree({newAnnotationsByPage:o,xref:E,catalogRef:f,pdfManager:i,changes:n})}))):p&&g.push(Promise.all(t).then((async()=>{await p.updateStructureTree({newAnnotationsByPage:o,pdfManager:i,changes:n})})))}if(e)g.push(i.serializeXfaData(a));else for(let e=0;ee.needAppearances)),D=C instanceof Dict&&C.get("XFA")||null;let b=null,F=!1;if(Array.isArray(D)){for(let e=0,t=D.length;e{E.resetNewTemporaryRef()}))}));l.on("GetOperatorList",(function(e,t){const a=e.pageIndex;i.getPage(a).then((function(i){const s=new WorkerTask(`GetOperatorList: page ${a}`);startWorkerTask(s);const r=n>=yA?Date.now():0;i.getOperatorList({handler:l,sink:t,task:s,intent:e.intent,cacheKey:e.cacheKey,annotationStorage:e.annotationStorage,modifiedIds:e.modifiedIds}).then((function(e){finishWorkerTask(s);r&&info(`page=${a+1} - getOperatorList: time=${Date.now()-r}ms, len=${e.length}`);t.close()}),(function(e){finishWorkerTask(s);s.terminated||t.error(e)}))}))}));l.on("GetTextContent",(function(e,t){const{pageIndex:a,includeMarkedContent:s,disableNormalization:r}=e;i.getPage(a).then((function(e){const i=new WorkerTask("GetTextContent: page "+a);startWorkerTask(i);const g=n>=yA?Date.now():0;e.extractTextContent({handler:l,task:i,sink:t,includeMarkedContent:s,disableNormalization:r}).then((function(){finishWorkerTask(i);g&&info(`page=${a+1} - getTextContent: time=`+(Date.now()-g)+"ms");t.close()}),(function(e){finishWorkerTask(i);i.terminated||t.error(e)}))}))}));l.on("GetStructTree",(function(e){return i.getPage(e.pageIndex).then((function(e){return i.ensure(e,"getStructTree")}))}));l.on("FontFallback",(function(e){return i.fontFallback(e.id,l)}));l.on("Cleanup",(function(e){return i.cleanup(!0)}));l.on("Terminate",(function(e){a=!0;const t=[];if(i){i.terminate(new AbortException("Worker was terminated."));const e=i.cleanup();t.push(e);i=null}else clearGlobalCaches();s?.(new AbortException("Worker was terminated."));for(const e of r){t.push(e.finished);e.terminate()}return Promise.all(t).then((function(){l.destroy();l=null}))}));l.on("Ready",(function(t){setupDoc(e);e=null}));return h}static initializeFromPort(e){const t=new MessageHandler("worker","main",e);this.setup(t,e);t.send("ready",null)}}var Qg=__webpack_exports__.WorkerMessageHandler;export{Qg as WorkerMessageHandler}; \ No newline at end of file diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/pdfjs-dist/dist/web/images/loading-icon.gif b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/pdfjs-dist/dist/web/images/loading-icon.gif deleted file mode 100644 index 1c72ebb554be018511ae972c3f2361dff02dce02..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2545 zcma*pX;2es8VB%~zPr=ibVMCx-JQ^BhLDAsK)^**h(ZDp9YGuzZ%~j!}+w%FI;|aC7){7CdVvG)P{bng1y9Te*f}~*`1kQl$jwb z$tlW~rRS!X?#xfm_&6tTdp_`cjgYwbRFLNdoJCN$S-yhg`ZnC-yvedRSmOh%;Y`Gl6bY$Z-}#C=#F4%9!I1b zWQ~f+9P?;vhCxWwlwl=lrWG|7IYo;{jjmzJ5R9?f>n%-d@>kLINUc z4wM5dAO;kq<$}Dk{2-u0$I6@2N}&cUx9nmV1dYc8jfC}%=F9WCg^OQK9C6poh#2!A z3^EU*UFZvS^)?bu3T?J;@Ahb~%I?+@4!l5!*TjC}GIslNan-RCrrd~PdHYnNLJk+m&`$Y+NV(e>CCu%R#_8GqY4cv#j`#uRWdsg9DxWy(?oOvgCU}&@jy%c!H&-Q zqXJxajAtmQRoRa9V-RFXXh-bK*;Fum{BjpkYQGX~i@OZ^Dx0n&H}kvGKqQ?w(6iGXu_g08T|_hp#ZvFzIwKF*a=oMJ~3UGAjZ?g}GOxm44td zXoyYrU*I=y*vHv89hkYH(v5R#wc)BC3dZJKb3K)f>zaM3%JP(mpecViP0eKKYf3zy z->jx_mc?mCtPEvCQ?uppk?eLJt}_IR7giW%Jr)RyI!+E-voIs*lXI*z`GQc_&D#X( z{6G};HPYj6O|$lXxBJeDaweqa{4L=tOZCjTI^&UOxXg})LRG_cr^B9Rqt(i5ORbQX zq`_xCRsH>xEYY%&*Nyi#{S_JZNlTm#K56`RI%7^amom;*h90Si&g1CfaFV3D|a!`3Y-GKKbL*KSbl z>I96`TR@CqPJl(>QqB~RvK~-U)`e`l4LIqj+IU^~yyIe*|BRVB>4Bup%j{tLdKz4j zY^<8P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/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.css deleted file mode 100644 index 86a3716c501..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.css +++ /dev/null @@ -1,3274 +0,0 @@ -/* Copyright 2014 Mozilla Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -.messageBar{ - --closing-button-icon:url(images/messageBar_closingButton.svg); - --message-bar-close-button-color:var(--text-primary-color); - --message-bar-close-button-color-hover:var(--text-primary-color); - --message-bar-close-button-border-radius:4px; - --message-bar-close-button-border:none; - --message-bar-close-button-hover-bg-color:rgb(21 20 26 / 0.14); - --message-bar-close-button-active-bg-color:rgb(21 20 26 / 0.21); - --message-bar-close-button-focus-bg-color:rgb(21 20 26 / 0.07); -} - -@media (prefers-color-scheme: dark){ - -.messageBar{ - --message-bar-close-button-hover-bg-color:rgb(251 251 254 / 0.14); - --message-bar-close-button-active-bg-color:rgb(251 251 254 / 0.21); - --message-bar-close-button-focus-bg-color:rgb(251 251 254 / 0.07); -} - } - -@media screen and (forced-colors: active){ - -.messageBar{ - --message-bar-close-button-color:ButtonText; - --message-bar-close-button-border:1px solid ButtonText; - --message-bar-close-button-hover-bg-color:ButtonText; - --message-bar-close-button-active-bg-color:ButtonText; - --message-bar-close-button-focus-bg-color:ButtonText; - --message-bar-close-button-color-hover:HighlightText; -} - } - -.messageBar{ - - display:flex; - position:relative; - padding:8px 8px 8px 16px; - flex-direction:column; - justify-content:center; - align-items:center; - gap:8px; - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; - - border-radius:4px; - - border:1px solid var(--message-bar-border-color); - background:var(--message-bar-bg-color); - color:var(--message-bar-fg-color); -} - -.messageBar > div{ - display:flex; - align-items:flex-start; - gap:8px; - align-self:stretch; - } - -:is(.messageBar > div)::before{ - content:""; - display:inline-block; - width:16px; - height:16px; - -webkit-mask-image:var(--message-bar-icon); - mask-image:var(--message-bar-icon); - -webkit-mask-size:cover; - mask-size:cover; - background-color:var(--message-bar-icon-color); - flex-shrink:0; - } - -.messageBar button{ - cursor:pointer; - } - -:is(.messageBar button):focus-visible{ - outline:var(--focus-ring-outline); - outline-offset:2px; - } - -.messageBar .closeButton{ - width:32px; - height:32px; - background:none; - border-radius:var(--message-bar-close-button-border-radius); - border:var(--message-bar-close-button-border); - - display:flex; - align-items:center; - justify-content:center; - } - -:is(.messageBar .closeButton)::before{ - content:""; - display:inline-block; - width:16px; - height:16px; - -webkit-mask-image:var(--closing-button-icon); - mask-image:var(--closing-button-icon); - -webkit-mask-size:cover; - mask-size:cover; - background-color:var(--message-bar-close-button-color); - } - -:is(.messageBar .closeButton):is(:hover,:active,:focus)::before{ - background-color:var(--message-bar-close-button-color-hover); - } - -:is(.messageBar .closeButton):hover{ - background-color:var(--message-bar-close-button-hover-bg-color); - } - -:is(.messageBar .closeButton):active{ - background-color:var(--message-bar-close-button-active-bg-color); - } - -:is(.messageBar .closeButton):focus{ - background-color:var(--message-bar-close-button-focus-bg-color); - } - -:is(.messageBar .closeButton) > span{ - display:inline-block; - width:0; - height:0; - overflow:hidden; - } - -#editorUndoBar{ - --text-primary-color:#15141a; - - --message-bar-icon:url(images/secondaryToolbarButton-documentProperties.svg); - --message-bar-icon-color:#0060df; - --message-bar-bg-color:#deeafc; - --message-bar-fg-color:var(--text-primary-color); - --message-bar-border-color:rgb(0 0 0 / 0.08); - - --undo-button-bg-color:rgb(21 20 26 / 0.07); - --undo-button-bg-color-hover:rgb(21 20 26 / 0.14); - --undo-button-bg-color-active:rgb(21 20 26 / 0.21); - - --undo-button-fg-color:var(--message-bar-fg-color); - --undo-button-fg-color-hover:var(--undo-button-fg-color); - --undo-button-fg-color-active:var(--undo-button-fg-color); - - --focus-ring-color:#0060df; - --focus-ring-outline:2px solid var(--focus-ring-color); -} - -@media (prefers-color-scheme: dark){ - -#editorUndoBar{ - --text-primary-color:#fbfbfe; - - --message-bar-icon-color:#73a7f3; - --message-bar-bg-color:#003070; - --message-bar-border-color:rgb(255 255 255 / 0.08); - - --undo-button-bg-color:rgb(255 255 255 / 0.08); - --undo-button-bg-color-hover:rgb(255 255 255 / 0.14); - --undo-button-bg-color-active:rgb(255 255 255 / 0.21); -} - } - -@media screen and (forced-colors: active){ - -#editorUndoBar{ - --text-primary-color:CanvasText; - - --message-bar-icon-color:CanvasText; - --message-bar-bg-color:Canvas; - --message-bar-border-color:CanvasText; - - --undo-button-bg-color:ButtonText; - --undo-button-bg-color-hover:SelectedItem; - --undo-button-bg-color-active:SelectedItem; - - --undo-button-fg-color:ButtonFace; - --undo-button-fg-color-hover:SelectedItemText; - --undo-button-fg-color-active:SelectedItemText; - - --focus-ring-color:CanvasText; -} - } - -#editorUndoBar{ - - position:fixed; - top:50px; - left:50%; - transform:translateX(-50%); - z-index:10; - - padding-block:8px; - padding-inline:16px 8px; - - font:menu; - font-size:15px; - - cursor:default; -} - -#editorUndoBar button{ - cursor:pointer; - } - -#editorUndoBar #editorUndoBarUndoButton{ - border-radius:4px; - font-weight:590; - line-height:19.5px; - color:var(--undo-button-fg-color); - border:none; - padding:4px 16px; - margin-inline-start:8px; - height:32px; - - background-color:var(--undo-button-bg-color); - } - -:is(#editorUndoBar #editorUndoBarUndoButton):hover{ - background-color:var(--undo-button-bg-color-hover); - color:var(--undo-button-fg-color-hover); - } - -:is(#editorUndoBar #editorUndoBarUndoButton):active{ - background-color:var(--undo-button-bg-color-active); - color:var(--undo-button-fg-color-active); - } - -#editorUndoBar > div{ - align-items:center; - } - -.dialog{ - --dialog-bg-color:white; - --dialog-border-color:white; - --dialog-shadow:0 2px 14px 0 rgb(58 57 68 / 0.2); - --text-primary-color:#15141a; - --text-secondary-color:#5b5b66; - --hover-filter:brightness(0.9); - --focus-ring-color:#0060df; - --focus-ring-outline:2px solid var(--focus-ring-color); - --link-fg-color:#0060df; - --link-hover-fg-color:#0250bb; - --separator-color:#f0f0f4; - - --textarea-border-color:#8f8f9d; - --textarea-bg-color:white; - --textarea-fg-color:var(--text-secondary-color); - - --radio-bg-color:#f0f0f4; - --radio-checked-bg-color:#fbfbfe; - --radio-border-color:#8f8f9d; - --radio-checked-border-color:#0060df; - - --button-secondary-bg-color:#f0f0f4; - --button-secondary-fg-color:var(--text-primary-color); - --button-secondary-border-color:var(--button-secondary-bg-color); - --button-secondary-hover-bg-color:var(--button-secondary-bg-color); - --button-secondary-hover-fg-color:var(--button-secondary-fg-color); - --button-secondary-hover-border-color:var(--button-secondary-hover-bg-color); - - --button-primary-bg-color:#0060df; - --button-primary-fg-color:#fbfbfe; - --button-primary-border-color:var(--button-primary-bg-color); - --button-primary-hover-bg-color:var(--button-primary-bg-color); - --button-primary-hover-fg-color:var(--button-primary-fg-color); - --button-primary-hover-border-color:var(--button-primary-hover-bg-color); -} - -@media (prefers-color-scheme: dark){ - -.dialog{ - --dialog-bg-color:#1c1b22; - --dialog-border-color:#1c1b22; - --dialog-shadow:0 2px 14px 0 #15141a; - --text-primary-color:#fbfbfe; - --text-secondary-color:#cfcfd8; - --focus-ring-color:#0df; - --hover-filter:brightness(1.4); - --link-fg-color:#0df; - --link-hover-fg-color:#80ebff; - --separator-color:#52525e; - - --textarea-bg-color:#42414d; - - --radio-bg-color:#2b2a33; - --radio-checked-bg-color:#15141a; - --radio-checked-border-color:#0df; - - --button-secondary-bg-color:#2b2a33; - --button-primary-bg-color:#0df; - --button-primary-fg-color:#15141a; -} - } - -@media screen and (forced-colors: active){ - -.dialog{ - --dialog-bg-color:Canvas; - --dialog-border-color:CanvasText; - --dialog-shadow:none; - --text-primary-color:CanvasText; - --text-secondary-color:CanvasText; - --hover-filter:none; - --focus-ring-color:ButtonBorder; - --link-fg-color:LinkText; - --link-hover-fg-color:LinkText; - --separator-color:CanvasText; - - --textarea-border-color:ButtonBorder; - --textarea-bg-color:Field; - --textarea-fg-color:ButtonText; - - --radio-bg-color:ButtonFace; - --radio-checked-bg-color:ButtonFace; - --radio-border-color:ButtonText; - --radio-checked-border-color:ButtonText; - - --button-secondary-bg-color:ButtonFace; - --button-secondary-fg-color:ButtonText; - --button-secondary-border-color:ButtonText; - --button-secondary-hover-bg-color:AccentColor; - --button-secondary-hover-fg-color:AccentColorText; - - --button-primary-bg-color:ButtonText; - --button-primary-fg-color:ButtonFace; - --button-primary-hover-bg-color:AccentColor; - --button-primary-hover-fg-color:AccentColorText; -} - } - -.dialog{ - - font:message-box; - font-size:13px; - font-weight:400; - line-height:150%; - border-radius:4px; - padding:12px 16px; - border:1px solid var(--dialog-border-color); - background:var(--dialog-bg-color); - color:var(--text-primary-color); - box-shadow:var(--dialog-shadow); -} - -:is(.dialog .mainContainer) *:focus-visible{ - outline:var(--focus-ring-outline); - outline-offset:2px; - } - -:is(.dialog .mainContainer) .title{ - display:flex; - width:auto; - flex-direction:column; - justify-content:flex-end; - align-items:flex-start; - gap:12px; - } - -:is(:is(.dialog .mainContainer) .title) > span{ - font-size:13px; - font-style:normal; - font-weight:590; - line-height:150%; - } - -:is(.dialog .mainContainer) .dialogSeparator{ - width:100%; - height:0; - margin-block:4px; - border-top:1px solid var(--separator-color); - border-bottom:none; - } - -:is(.dialog .mainContainer) .dialogButtonsGroup{ - display:flex; - gap:12px; - align-self:flex-end; - } - -:is(.dialog .mainContainer) .radio{ - display:flex; - flex-direction:column; - align-items:flex-start; - gap:4px; - } - -:is(:is(.dialog .mainContainer) .radio) > .radioButton{ - display:flex; - gap:8px; - align-self:stretch; - align-items:center; - } - -:is(:is(:is(.dialog .mainContainer) .radio) > .radioButton) input{ - -webkit-appearance:none; - -moz-appearance:none; - appearance:none; - box-sizing:border-box; - width:16px; - height:16px; - border-radius:50%; - background-color:var(--radio-bg-color); - border:1px solid var(--radio-border-color); - } - -:is(:is(:is(:is(.dialog .mainContainer) .radio) > .radioButton) input):hover{ - filter:var(--hover-filter); - } - -:is(:is(:is(:is(.dialog .mainContainer) .radio) > .radioButton) input):checked{ - background-color:var(--radio-checked-bg-color); - border:4px solid var(--radio-checked-border-color); - } - -:is(:is(.dialog .mainContainer) .radio) > .radioLabel{ - display:flex; - padding-inline-start:24px; - align-items:flex-start; - gap:10px; - align-self:stretch; - } - -:is(:is(:is(.dialog .mainContainer) .radio) > .radioLabel) > span{ - flex:1 0 0; - font-size:11px; - color:var(--text-secondary-color); - } - -:is(.dialog .mainContainer) button:not(:is(.toggle-button,.closeButton)){ - border-radius:4px; - border:1px solid; - font:menu; - font-weight:600; - padding:4px 16px; - width:auto; - height:32px; - } - -:is(:is(.dialog .mainContainer) button:not(:is(.toggle-button,.closeButton))):hover{ - cursor:pointer; - filter:var(--hover-filter); - } - -.secondaryButton:is(:is(.dialog .mainContainer) button:not(:is(.toggle-button,.closeButton))){ - color:var(--button-secondary-fg-color); - background-color:var(--button-secondary-bg-color); - border-color:var(--button-secondary-border-color); - } - -.secondaryButton:is(:is(.dialog .mainContainer) button:not(:is(.toggle-button,.closeButton))):hover{ - color:var(--button-secondary-hover-fg-color); - background-color:var(--button-secondary-hover-bg-color); - border-color:var(--button-secondary-hover-border-color); - } - -.primaryButton:is(:is(.dialog .mainContainer) button:not(:is(.toggle-button,.closeButton))){ - color:var(--button-primary-fg-color); - background-color:var(--button-primary-bg-color); - border-color:var(--button-primary-border-color); - opacity:1; - } - -.primaryButton:is(:is(.dialog .mainContainer) button:not(:is(.toggle-button,.closeButton))):hover{ - color:var(--button-primary-hover-fg-color); - background-color:var(--button-primary-hover-bg-color); - border-color:var(--button-primary-hover-border-color); - } - -:is(.dialog .mainContainer) a{ - color:var(--link-fg-color); - } - -:is(:is(.dialog .mainContainer) a):hover{ - color:var(--link-hover-fg-color); - } - -:is(.dialog .mainContainer) textarea{ - font:inherit; - padding:8px; - resize:none; - margin:0; - box-sizing:border-box; - border-radius:4px; - border:1px solid var(--textarea-border-color); - background:var(--textarea-bg-color); - color:var(--textarea-fg-color); - } - -:is(:is(.dialog .mainContainer) textarea):focus{ - outline-offset:0; - border-color:transparent; - } - -:is(:is(.dialog .mainContainer) textarea):disabled{ - pointer-events:none; - opacity:0.4; - } - -:is(.dialog .mainContainer) .messageBar{ - --message-bar-bg-color:#ffebcd; - --message-bar-fg-color:#15141a; - --message-bar-border-color:rgb(0 0 0 / 0.08); - --message-bar-icon:url(images/messageBar_warning.svg); - --message-bar-icon-color:#cd411e; - } - -@media (prefers-color-scheme: dark){ - -:is(.dialog .mainContainer) .messageBar{ - --message-bar-bg-color:#5a3100; - --message-bar-fg-color:#fbfbfe; - --message-bar-border-color:rgb(255 255 255 / 0.08); - --message-bar-icon-color:#e49c49; - } - } - -@media screen and (forced-colors: active){ - -:is(.dialog .mainContainer) .messageBar{ - --message-bar-bg-color:HighlightText; - --message-bar-fg-color:CanvasText; - --message-bar-border-color:CanvasText; - --message-bar-icon-color:CanvasText; - } - } - -:is(.dialog .mainContainer) .messageBar{ - - align-self:stretch; - } - -:is(:is(:is(.dialog .mainContainer) .messageBar) > div)::before,:is(:is(:is(.dialog .mainContainer) .messageBar) > div) > div{ - margin-block:4px; - } - -:is(:is(:is(.dialog .mainContainer) .messageBar) > div) > div{ - display:flex; - flex-direction:column; - align-items:flex-start; - gap:8px; - flex:1 0 0; - } - -:is(:is(:is(:is(.dialog .mainContainer) .messageBar) > div) > div) .title{ - font-size:13px; - font-weight:590; - } - -:is(:is(:is(:is(.dialog .mainContainer) .messageBar) > div) > div) .description{ - font-size:13px; - } - -:is(.dialog .mainContainer) .toggler{ - display:flex; - align-items:center; - gap:8px; - align-self:stretch; - } - -:is(:is(.dialog .mainContainer) .toggler) > .togglerLabel{ - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; - } - -.textLayer{ - position:absolute; - text-align:initial; - inset:0; - overflow:clip; - opacity:1; - line-height:1; - -webkit-text-size-adjust:none; - -moz-text-size-adjust:none; - text-size-adjust:none; - forced-color-adjust:none; - transform-origin:0 0; - caret-color:CanvasText; - z-index:0; -} - -.textLayer.highlighting{ - touch-action:none; - } - -.textLayer :is(span,br){ - color:transparent; - position:absolute; - white-space:pre; - cursor:text; - transform-origin:0% 0%; - } - -.textLayer > :not(.markedContent),.textLayer .markedContent span:not(.markedContent){ - z-index:1; - } - -.textLayer span.markedContent{ - top:0; - height:0; - } - -.textLayer span[role="img"]{ - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; - cursor:default; - } - -.textLayer .highlight{ - --highlight-bg-color:rgb(180 0 170 / 0.25); - --highlight-selected-bg-color:rgb(0 100 0 / 0.25); - --highlight-backdrop-filter:none; - --highlight-selected-backdrop-filter:none; - } - -@media screen and (forced-colors: active){ - -.textLayer .highlight{ - --highlight-bg-color:transparent; - --highlight-selected-bg-color:transparent; - --highlight-backdrop-filter:var(--hcm-highlight-filter); - --highlight-selected-backdrop-filter:var( - --hcm-highlight-selected-filter - ); - } - } - -.textLayer .highlight{ - - margin:-1px; - padding:1px; - background-color:var(--highlight-bg-color); - -webkit-backdrop-filter:var(--highlight-backdrop-filter); - backdrop-filter:var(--highlight-backdrop-filter); - border-radius:4px; - } - -.appended:is(.textLayer .highlight){ - position:initial; - } - -.begin:is(.textLayer .highlight){ - border-radius:4px 0 0 4px; - } - -.end:is(.textLayer .highlight){ - border-radius:0 4px 4px 0; - } - -.middle:is(.textLayer .highlight){ - border-radius:0; - } - -.selected:is(.textLayer .highlight){ - background-color:var(--highlight-selected-bg-color); - -webkit-backdrop-filter:var(--highlight-selected-backdrop-filter); - backdrop-filter:var(--highlight-selected-backdrop-filter); - } - -.textLayer ::-moz-selection{ - background:rgba(0 0 255 / 0.25); - background:color-mix(in srgb, AccentColor, transparent 75%); - } - -.textLayer ::selection{ - background:rgba(0 0 255 / 0.25); - background:color-mix(in srgb, AccentColor, transparent 75%); - } - -.textLayer br::-moz-selection{ - background:transparent; - } - -.textLayer br::selection{ - background:transparent; - } - -.textLayer .endOfContent{ - display:block; - position:absolute; - inset:100% 0 0; - z-index:0; - cursor:default; - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; - } - -.textLayer.selecting .endOfContent{ - top:0; - } - -.annotationLayer{ - --annotation-unfocused-field-background:url("data:image/svg+xml;charset=UTF-8,"); - --input-focus-border-color:Highlight; - --input-focus-outline:1px solid Canvas; - --input-unfocused-border-color:transparent; - --input-disabled-border-color:transparent; - --input-hover-border-color:black; - --link-outline:none; -} - -@media screen and (forced-colors: active){ - -.annotationLayer{ - --input-focus-border-color:CanvasText; - --input-unfocused-border-color:ActiveText; - --input-disabled-border-color:GrayText; - --input-hover-border-color:Highlight; - --link-outline:1.5px solid LinkText; -} - - .annotationLayer .textWidgetAnnotation :is(input,textarea):required,.annotationLayer .choiceWidgetAnnotation select:required,.annotationLayer .buttonWidgetAnnotation:is(.checkBox,.radioButton) input:required{ - outline:1.5px solid selectedItem; - } - - .annotationLayer .linkAnnotation{ - outline:var(--link-outline); - } - - :is(.annotationLayer .linkAnnotation):hover{ - -webkit-backdrop-filter:var(--hcm-highlight-filter); - backdrop-filter:var(--hcm-highlight-filter); - } - - :is(.annotationLayer .linkAnnotation) > a:hover{ - opacity:0 !important; - background:none !important; - box-shadow:none; - } - - .annotationLayer .popupAnnotation .popup{ - outline:calc(1.5px * var(--scale-factor)) solid CanvasText !important; - background-color:ButtonFace !important; - color:ButtonText !important; - } - - .annotationLayer .highlightArea:hover::after{ - position:absolute; - top:0; - left:0; - width:100%; - height:100%; - -webkit-backdrop-filter:var(--hcm-highlight-filter); - backdrop-filter:var(--hcm-highlight-filter); - content:""; - pointer-events:none; - } - - .annotationLayer .popupAnnotation.focused .popup{ - outline:calc(3px * var(--scale-factor)) solid Highlight !important; - } - } - -.annotationLayer{ - - position:absolute; - top:0; - left:0; - pointer-events:none; - transform-origin:0 0; -} - -.annotationLayer[data-main-rotation="90"] .norotate{ - transform:rotate(270deg) translateX(-100%); - } - -.annotationLayer[data-main-rotation="180"] .norotate{ - transform:rotate(180deg) translate(-100%, -100%); - } - -.annotationLayer[data-main-rotation="270"] .norotate{ - transform:rotate(90deg) translateY(-100%); - } - -.annotationLayer.disabled section,.annotationLayer.disabled .popup{ - pointer-events:none; - } - -.annotationLayer .annotationContent{ - position:absolute; - width:100%; - height:100%; - pointer-events:none; - } - -.freetext:is(.annotationLayer .annotationContent){ - background:transparent; - border:none; - inset:0; - overflow:visible; - white-space:nowrap; - font:10px sans-serif; - line-height:1.35; - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; - } - -.annotationLayer section{ - position:absolute; - text-align:initial; - pointer-events:auto; - box-sizing:border-box; - transform-origin:0 0; - } - -:is(.annotationLayer section):has(div.annotationContent) canvas.annotationContent{ - display:none; - } - -.textLayer.selecting ~ .annotationLayer section{ - pointer-events:none; - } - -.annotationLayer :is(.linkAnnotation,.buttonWidgetAnnotation.pushButton) > a{ - position:absolute; - font-size:1em; - top:0; - left:0; - width:100%; - height:100%; - } - -.annotationLayer :is(.linkAnnotation,.buttonWidgetAnnotation.pushButton):not(.hasBorder) > a:hover{ - opacity:0.2; - background-color:rgb(255 255 0); - box-shadow:0 2px 10px rgb(255 255 0); - } - -.annotationLayer .linkAnnotation.hasBorder:hover{ - background-color:rgb(255 255 0 / 0.2); - } - -.annotationLayer .hasBorder{ - background-size:100% 100%; - } - -.annotationLayer .textAnnotation img{ - position:absolute; - cursor:pointer; - width:100%; - height:100%; - top:0; - left:0; - } - -.annotationLayer .textWidgetAnnotation :is(input,textarea),.annotationLayer .choiceWidgetAnnotation select,.annotationLayer .buttonWidgetAnnotation:is(.checkBox,.radioButton) input{ - background-image:var(--annotation-unfocused-field-background); - border:2px solid var(--input-unfocused-border-color); - box-sizing:border-box; - font:calc(9px * var(--scale-factor)) sans-serif; - height:100%; - margin:0; - vertical-align:top; - width:100%; - } - -.annotationLayer .textWidgetAnnotation :is(input,textarea):required,.annotationLayer .choiceWidgetAnnotation select:required,.annotationLayer .buttonWidgetAnnotation:is(.checkBox,.radioButton) input:required{ - outline:1.5px solid red; - } - -.annotationLayer .choiceWidgetAnnotation select option{ - padding:0; - } - -.annotationLayer .buttonWidgetAnnotation.radioButton input{ - border-radius:50%; - } - -.annotationLayer .textWidgetAnnotation textarea{ - resize:none; - } - -.annotationLayer .textWidgetAnnotation [disabled]:is(input,textarea),.annotationLayer .choiceWidgetAnnotation select[disabled],.annotationLayer .buttonWidgetAnnotation:is(.checkBox,.radioButton) input[disabled]{ - background:none; - border:2px solid var(--input-disabled-border-color); - cursor:not-allowed; - } - -.annotationLayer .textWidgetAnnotation :is(input,textarea):hover,.annotationLayer .choiceWidgetAnnotation select:hover,.annotationLayer .buttonWidgetAnnotation:is(.checkBox,.radioButton) input:hover{ - border:2px solid var(--input-hover-border-color); - } - -.annotationLayer .textWidgetAnnotation :is(input,textarea):hover,.annotationLayer .choiceWidgetAnnotation select:hover,.annotationLayer .buttonWidgetAnnotation.checkBox input:hover{ - border-radius:2px; - } - -.annotationLayer .textWidgetAnnotation :is(input,textarea):focus,.annotationLayer .choiceWidgetAnnotation select:focus{ - background:none; - border:2px solid var(--input-focus-border-color); - border-radius:2px; - outline:var(--input-focus-outline); - } - -.annotationLayer .buttonWidgetAnnotation:is(.checkBox,.radioButton) :focus{ - background-image:none; - background-color:transparent; - } - -.annotationLayer .buttonWidgetAnnotation.checkBox :focus{ - border:2px solid var(--input-focus-border-color); - border-radius:2px; - outline:var(--input-focus-outline); - } - -.annotationLayer .buttonWidgetAnnotation.radioButton :focus{ - border:2px solid var(--input-focus-border-color); - outline:var(--input-focus-outline); - } - -.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::before,.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::after,.annotationLayer .buttonWidgetAnnotation.radioButton input:checked::before{ - background-color:CanvasText; - content:""; - display:block; - position:absolute; - } - -.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::before,.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::after{ - height:80%; - left:45%; - width:1px; - } - -.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::before{ - transform:rotate(45deg); - } - -.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::after{ - transform:rotate(-45deg); - } - -.annotationLayer .buttonWidgetAnnotation.radioButton input:checked::before{ - border-radius:50%; - height:50%; - left:25%; - top:25%; - width:50%; - } - -.annotationLayer .textWidgetAnnotation input.comb{ - font-family:monospace; - padding-left:2px; - padding-right:0; - } - -.annotationLayer .textWidgetAnnotation input.comb:focus{ - width:103%; - } - -.annotationLayer .buttonWidgetAnnotation:is(.checkBox,.radioButton) input{ - -webkit-appearance:none; - -moz-appearance:none; - appearance:none; - } - -.annotationLayer .fileAttachmentAnnotation .popupTriggerArea{ - height:100%; - width:100%; - } - -.annotationLayer .popupAnnotation{ - position:absolute; - font-size:calc(9px * var(--scale-factor)); - pointer-events:none; - width:-moz-max-content; - width:max-content; - max-width:45%; - height:auto; - } - -.annotationLayer .popup{ - background-color:rgb(255 255 153); - box-shadow:0 calc(2px * var(--scale-factor)) calc(5px * var(--scale-factor)) rgb(136 136 136); - border-radius:calc(2px * var(--scale-factor)); - outline:1.5px solid rgb(255 255 74); - padding:calc(6px * var(--scale-factor)); - cursor:pointer; - font:message-box; - white-space:normal; - word-wrap:break-word; - pointer-events:auto; - } - -.annotationLayer .popupAnnotation.focused .popup{ - outline-width:3px; - } - -.annotationLayer .popup *{ - font-size:calc(9px * var(--scale-factor)); - } - -.annotationLayer .popup > .header{ - display:inline-block; - } - -.annotationLayer .popup > .header h1{ - display:inline; - } - -.annotationLayer .popup > .header .popupDate{ - display:inline-block; - margin-left:calc(5px * var(--scale-factor)); - width:-moz-fit-content; - width:fit-content; - } - -.annotationLayer .popupContent{ - border-top:1px solid rgb(51 51 51); - margin-top:calc(2px * var(--scale-factor)); - padding-top:calc(2px * var(--scale-factor)); - } - -.annotationLayer .richText > *{ - white-space:pre-wrap; - font-size:calc(9px * var(--scale-factor)); - } - -.annotationLayer .popupTriggerArea{ - cursor:pointer; - } - -.annotationLayer section svg{ - position:absolute; - width:100%; - height:100%; - top:0; - left:0; - } - -.annotationLayer .annotationTextContent{ - position:absolute; - width:100%; - height:100%; - opacity:0; - color:transparent; - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; - pointer-events:none; - } - -:is(.annotationLayer .annotationTextContent) span{ - width:100%; - display:inline-block; - } - -.annotationLayer svg.quadrilateralsContainer{ - contain:strict; - width:0; - height:0; - position:absolute; - top:0; - left:0; - z-index:-1; - } - -:root{ - --xfa-unfocused-field-background:url("data:image/svg+xml;charset=UTF-8,"); - --xfa-focus-outline:auto; -} - -@media screen and (forced-colors: active){ - :root{ - --xfa-focus-outline:2px solid CanvasText; - } - .xfaLayer *:required{ - outline:1.5px solid selectedItem; - } -} - -.xfaLayer{ - background-color:transparent; -} - -.xfaLayer .highlight{ - margin:-1px; - padding:1px; - background-color:rgb(239 203 237); - border-radius:4px; -} - -.xfaLayer .highlight.appended{ - position:initial; -} - -.xfaLayer .highlight.begin{ - border-radius:4px 0 0 4px; -} - -.xfaLayer .highlight.end{ - border-radius:0 4px 4px 0; -} - -.xfaLayer .highlight.middle{ - border-radius:0; -} - -.xfaLayer .highlight.selected{ - background-color:rgb(203 223 203); -} - -.xfaPage{ - overflow:hidden; - position:relative; -} - -.xfaContentarea{ - position:absolute; -} - -.xfaPrintOnly{ - display:none; -} - -.xfaLayer{ - position:absolute; - text-align:initial; - top:0; - left:0; - transform-origin:0 0; - line-height:1.2; -} - -.xfaLayer *{ - color:inherit; - font:inherit; - font-style:inherit; - font-weight:inherit; - font-kerning:inherit; - letter-spacing:-0.01px; - text-align:inherit; - text-decoration:inherit; - box-sizing:border-box; - background-color:transparent; - padding:0; - margin:0; - pointer-events:auto; - line-height:inherit; -} - -.xfaLayer *:required{ - outline:1.5px solid red; -} - -.xfaLayer div, -.xfaLayer svg, -.xfaLayer svg *{ - pointer-events:none; -} - -.xfaLayer a{ - color:blue; -} - -.xfaRich li{ - margin-left:3em; -} - -.xfaFont{ - color:black; - font-weight:normal; - font-kerning:none; - font-size:10px; - font-style:normal; - letter-spacing:0; - text-decoration:none; - vertical-align:0; -} - -.xfaCaption{ - overflow:hidden; - flex:0 0 auto; -} - -.xfaCaptionForCheckButton{ - overflow:hidden; - flex:1 1 auto; -} - -.xfaLabel{ - height:100%; - width:100%; -} - -.xfaLeft{ - display:flex; - flex-direction:row; - align-items:center; -} - -.xfaRight{ - display:flex; - flex-direction:row-reverse; - align-items:center; -} - -:is(.xfaLeft, .xfaRight) > :is(.xfaCaption, .xfaCaptionForCheckButton){ - max-height:100%; -} - -.xfaTop{ - display:flex; - flex-direction:column; - align-items:flex-start; -} - -.xfaBottom{ - display:flex; - flex-direction:column-reverse; - align-items:flex-start; -} - -:is(.xfaTop, .xfaBottom) > :is(.xfaCaption, .xfaCaptionForCheckButton){ - width:100%; -} - -.xfaBorder{ - background-color:transparent; - position:absolute; - pointer-events:none; -} - -.xfaWrapped{ - width:100%; - height:100%; -} - -:is(.xfaTextfield, .xfaSelect):focus{ - background-image:none; - background-color:transparent; - outline:var(--xfa-focus-outline); - outline-offset:-1px; -} - -:is(.xfaCheckbox, .xfaRadio):focus{ - outline:var(--xfa-focus-outline); -} - -.xfaTextfield, -.xfaSelect{ - height:100%; - width:100%; - flex:1 1 auto; - border:none; - resize:none; - background-image:var(--xfa-unfocused-field-background); -} - -.xfaSelect{ - padding-inline:2px; -} - -:is(.xfaTop, .xfaBottom) > :is(.xfaTextfield, .xfaSelect){ - flex:0 1 auto; -} - -.xfaButton{ - cursor:pointer; - width:100%; - height:100%; - border:none; - text-align:center; -} - -.xfaLink{ - width:100%; - height:100%; - position:absolute; - top:0; - left:0; -} - -.xfaCheckbox, -.xfaRadio{ - width:100%; - height:100%; - flex:0 0 auto; - border:none; -} - -.xfaRich{ - white-space:pre-wrap; - width:100%; - height:100%; -} - -.xfaImage{ - -o-object-position:left top; - object-position:left top; - -o-object-fit:contain; - object-fit:contain; - width:100%; - height:100%; -} - -.xfaLrTb, -.xfaRlTb, -.xfaTb{ - display:flex; - flex-direction:column; - align-items:stretch; -} - -.xfaLr{ - display:flex; - flex-direction:row; - align-items:stretch; -} - -.xfaRl{ - display:flex; - flex-direction:row-reverse; - align-items:stretch; -} - -.xfaTb > div{ - justify-content:left; -} - -.xfaPosition{ - position:relative; -} - -.xfaArea{ - position:relative; -} - -.xfaValignMiddle{ - display:flex; - align-items:center; -} - -.xfaTable{ - display:flex; - flex-direction:column; - align-items:stretch; -} - -.xfaTable .xfaRow{ - display:flex; - flex-direction:row; - align-items:stretch; -} - -.xfaTable .xfaRlRow{ - display:flex; - flex-direction:row-reverse; - align-items:stretch; - flex:1; -} - -.xfaTable .xfaRlRow > div{ - flex:1; -} - -:is(.xfaNonInteractive, .xfaDisabled, .xfaReadOnly) :is(input, textarea){ - background:initial; -} - -@media print{ - .xfaTextfield, - .xfaSelect{ - background:transparent; - } - - .xfaSelect{ - -webkit-appearance:none; - -moz-appearance:none; - appearance:none; - text-indent:1px; - text-overflow:""; - } -} - -.canvasWrapper svg{ - transform:none; - } - -.moving:is(.canvasWrapper svg){ - z-index:100000; - } - -[data-main-rotation="90"]:is(.highlight:is(.canvasWrapper svg),.highlightOutline:is(.canvasWrapper svg)) mask,[data-main-rotation="90"]:is(.highlight:is(.canvasWrapper svg),.highlightOutline:is(.canvasWrapper svg)) use:not(.clip,.mask){ - transform:matrix(0, 1, -1, 0, 1, 0); - } - -[data-main-rotation="180"]:is(.highlight:is(.canvasWrapper svg),.highlightOutline:is(.canvasWrapper svg)) mask,[data-main-rotation="180"]:is(.highlight:is(.canvasWrapper svg),.highlightOutline:is(.canvasWrapper svg)) use:not(.clip,.mask){ - transform:matrix(-1, 0, 0, -1, 1, 1); - } - -[data-main-rotation="270"]:is(.highlight:is(.canvasWrapper svg),.highlightOutline:is(.canvasWrapper svg)) mask,[data-main-rotation="270"]:is(.highlight:is(.canvasWrapper svg),.highlightOutline:is(.canvasWrapper svg)) use:not(.clip,.mask){ - transform:matrix(0, -1, 1, 0, 0, 1); - } - -.draw:is(.canvasWrapper svg){ - position:absolute; - mix-blend-mode:normal; - } - -.draw[data-draw-rotation="90"]:is(.canvasWrapper svg){ - transform:rotate(90deg); - } - -.draw[data-draw-rotation="180"]:is(.canvasWrapper svg){ - transform:rotate(180deg); - } - -.draw[data-draw-rotation="270"]:is(.canvasWrapper svg){ - transform:rotate(270deg); - } - -.highlight:is(.canvasWrapper svg){ - --blend-mode:multiply; - } - -@media screen and (forced-colors: active){ - -.highlight:is(.canvasWrapper svg){ - --blend-mode:difference; - } - } - -.highlight:is(.canvasWrapper svg){ - - position:absolute; - mix-blend-mode:var(--blend-mode); - } - -.highlight:is(.canvasWrapper svg):not(.free){ - fill-rule:evenodd; - } - -.highlightOutline:is(.canvasWrapper svg){ - position:absolute; - mix-blend-mode:normal; - fill-rule:evenodd; - fill:none; - } - -.highlightOutline.hovered:is(.canvasWrapper svg):not(.free):not(.selected){ - stroke:var(--hover-outline-color); - stroke-width:var(--outline-width); - } - -.highlightOutline.selected:is(.canvasWrapper svg):not(.free) .mainOutline{ - stroke:var(--outline-around-color); - stroke-width:calc( - var(--outline-width) + 2 * var(--outline-around-width) - ); - } - -.highlightOutline.selected:is(.canvasWrapper svg):not(.free) .secondaryOutline{ - stroke:var(--outline-color); - stroke-width:var(--outline-width); - } - -.highlightOutline.free.hovered:is(.canvasWrapper svg):not(.selected){ - stroke:var(--hover-outline-color); - stroke-width:calc(2 * var(--outline-width)); - } - -.highlightOutline.free.selected:is(.canvasWrapper svg) .mainOutline{ - stroke:var(--outline-around-color); - stroke-width:calc( - 2 * (var(--outline-width) + var(--outline-around-width)) - ); - } - -.highlightOutline.free.selected:is(.canvasWrapper svg) .secondaryOutline{ - stroke:var(--outline-color); - stroke-width:calc(2 * var(--outline-width)); - } - -.toggle-button{ - --button-background-color:#f0f0f4; - --button-background-color-hover:#e0e0e6; - --button-background-color-active:#cfcfd8; - --color-accent-primary:#0060df; - --color-accent-primary-hover:#0250bb; - --color-accent-primary-active:#054096; - --border-interactive-color:#8f8f9d; - --border-radius-circle:9999px; - --border-width:1px; - --size-item-small:16px; - --size-item-large:32px; - --color-canvas:white; -} - -@media (prefers-color-scheme: dark){ - -.toggle-button{ - --button-background-color:color-mix(in srgb, currentColor 7%, transparent); - --button-background-color-hover:color-mix( - in srgb, - currentColor 14%, - transparent - ); - --button-background-color-active:color-mix( - in srgb, - currentColor 21%, - transparent - ); - --color-accent-primary:#0df; - --color-accent-primary-hover:#80ebff; - --color-accent-primary-active:#aaf2ff; - --border-interactive-color:#bfbfc9; - --color-canvas:#1c1b22; -} - } - -@media (forced-colors: active){ - -.toggle-button{ - --color-accent-primary:ButtonText; - --color-accent-primary-hover:SelectedItem; - --color-accent-primary-active:SelectedItem; - --border-interactive-color:ButtonText; - --button-background-color:ButtonFace; - --border-interactive-color-hover:SelectedItem; - --border-interactive-color-active:SelectedItem; - --border-interactive-color-disabled:GrayText; - --color-canvas:ButtonText; -} - } - -.toggle-button{ - - --toggle-background-color:var(--button-background-color); - --toggle-background-color-hover:var(--button-background-color-hover); - --toggle-background-color-active:var(--button-background-color-active); - --toggle-background-color-pressed:var(--color-accent-primary); - --toggle-background-color-pressed-hover:var(--color-accent-primary-hover); - --toggle-background-color-pressed-active:var(--color-accent-primary-active); - --toggle-border-color:var(--border-interactive-color); - --toggle-border-color-hover:var(--toggle-border-color); - --toggle-border-color-active:var(--toggle-border-color); - --toggle-border-radius:var(--border-radius-circle); - --toggle-border-width:var(--border-width); - --toggle-height:var(--size-item-small); - --toggle-width:var(--size-item-large); - --toggle-dot-background-color:var(--toggle-border-color); - --toggle-dot-background-color-hover:var(--toggle-dot-background-color); - --toggle-dot-background-color-active:var(--toggle-dot-background-color); - --toggle-dot-background-color-on-pressed:var(--color-canvas); - --toggle-dot-margin:1px; - --toggle-dot-height:calc( - var(--toggle-height) - 2 * var(--toggle-dot-margin) - 2 * - var(--toggle-border-width) - ); - --toggle-dot-width:var(--toggle-dot-height); - --toggle-dot-transform-x:calc( - var(--toggle-width) - 4 * var(--toggle-dot-margin) - var(--toggle-dot-width) - ); - - -webkit-appearance:none; - - -moz-appearance:none; - - appearance:none; - padding:0; - margin:0; - border:var(--toggle-border-width) solid var(--toggle-border-color); - height:var(--toggle-height); - width:var(--toggle-width); - border-radius:var(--toggle-border-radius); - background:var(--toggle-background-color); - box-sizing:border-box; - flex-shrink:0; -} - -.toggle-button:focus-visible{ - outline:var(--focus-outline); - outline-offset:var(--focus-outline-offset); - } - -.toggle-button:enabled:hover{ - background:var(--toggle-background-color-hover); - border-color:var(--toggle-border-color); - } - -.toggle-button:enabled:active{ - background:var(--toggle-background-color-active); - border-color:var(--toggle-border-color); - } - -.toggle-button[aria-pressed="true"]{ - background:var(--toggle-background-color-pressed); - border-color:transparent; - } - -.toggle-button[aria-pressed="true"]:enabled:hover{ - background:var(--toggle-background-color-pressed-hover); - border-color:transparent; - } - -.toggle-button[aria-pressed="true"]:enabled:active{ - background:var(--toggle-background-color-pressed-active); - border-color:transparent; - } - -.toggle-button::before{ - display:block; - content:""; - background-color:var(--toggle-dot-background-color); - height:var(--toggle-dot-height); - width:var(--toggle-dot-width); - margin:var(--toggle-dot-margin); - border-radius:var(--toggle-border-radius); - translate:0; - } - -.toggle-button[aria-pressed="true"]::before{ - translate:var(--toggle-dot-transform-x); - background-color:var(--toggle-dot-background-color-on-pressed); - } - -.toggle-button[aria-pressed="true"]:enabled:hover::before,.toggle-button[aria-pressed="true"]:enabled:active::before{ - background-color:var(--toggle-dot-background-color-on-pressed); - } - -[dir="rtl"] .toggle-button[aria-pressed="true"]::before{ - translate:calc(-1 * var(--toggle-dot-transform-x)); - } - -@media (prefers-reduced-motion: no-preference){ - .toggle-button::before{ - transition:translate 100ms; - } - } - -@media (prefers-contrast){ - .toggle-button:enabled:hover{ - border-color:var(--toggle-border-color-hover); - } - - .toggle-button:enabled:active{ - border-color:var(--toggle-border-color-active); - } - - .toggle-button[aria-pressed="true"]:enabled{ - border-color:var(--toggle-border-color); - position:relative; - } - - .toggle-button[aria-pressed="true"]:enabled:hover,.toggle-button[aria-pressed="true"]:enabled:hover:active{ - border-color:var(--toggle-border-color-hover); - } - - .toggle-button[aria-pressed="true"]:enabled:active{ - background-color:var(--toggle-dot-background-color-active); - border-color:var(--toggle-dot-background-color-hover); - } - - .toggle-button:hover::before,.toggle-button:active::before{ - background-color:var(--toggle-dot-background-color-hover); - } - } - -@media (forced-colors){ - -.toggle-button{ - --toggle-dot-background-color:var(--color-accent-primary); - --toggle-dot-background-color-hover:var(--color-accent-primary-hover); - --toggle-dot-background-color-active:var(--color-accent-primary-active); - --toggle-dot-background-color-on-pressed:var(--button-background-color); - --toggle-background-color-disabled:var(--button-background-color-disabled); - --toggle-border-color-hover:var(--border-interactive-color-hover); - --toggle-border-color-active:var(--border-interactive-color-active); - --toggle-border-color-disabled:var(--border-interactive-color-disabled); -} - - .toggle-button[aria-pressed="true"]:enabled::after{ - border:1px solid var(--button-background-color); - content:""; - position:absolute; - height:var(--toggle-height); - width:var(--toggle-width); - display:block; - border-radius:var(--toggle-border-radius); - inset:-2px; - } - - .toggle-button[aria-pressed="true"]:enabled:active::after{ - border-color:var(--toggle-border-color-active); - } - } - -:root{ - --outline-width:2px; - --outline-color:#0060df; - --outline-around-width:1px; - --outline-around-color:#f0f0f4; - --hover-outline-around-color:var(--outline-around-color); - --focus-outline:solid var(--outline-width) var(--outline-color); - --unfocus-outline:solid var(--outline-width) transparent; - --focus-outline-around:solid var(--outline-around-width) var(--outline-around-color); - --hover-outline-color:#8f8f9d; - --hover-outline:solid var(--outline-width) var(--hover-outline-color); - --hover-outline-around:solid var(--outline-around-width) var(--hover-outline-around-color); - --freetext-line-height:1.35; - --freetext-padding:2px; - --resizer-bg-color:var(--outline-color); - --resizer-size:6px; - --resizer-shift:calc( - 0px - (var(--outline-width) + var(--resizer-size)) / 2 - - var(--outline-around-width) - ); - --editorFreeText-editing-cursor:text; - --editorInk-editing-cursor:url(images/cursor-editorInk.svg) 0 16, pointer; - --editorHighlight-editing-cursor:url(images/cursor-editorTextHighlight.svg) 24 24, text; - --editorFreeHighlight-editing-cursor:url(images/cursor-editorFreeHighlight.svg) 1 18, pointer; - - --new-alt-text-warning-image:url(images/altText_warning.svg); -} -.visuallyHidden{ - position:absolute; - top:0; - left:0; - border:0; - margin:0; - padding:0; - width:0; - height:0; - overflow:hidden; - white-space:nowrap; - font-size:0; -} - -.textLayer.highlighting{ - cursor:var(--editorFreeHighlight-editing-cursor); - } - -.textLayer.highlighting:not(.free) span{ - cursor:var(--editorHighlight-editing-cursor); - } - -[role="img"]:is(.textLayer.highlighting:not(.free) span){ - cursor:var(--editorFreeHighlight-editing-cursor); - } - -.textLayer.highlighting.free span{ - cursor:var(--editorFreeHighlight-editing-cursor); - } - -:is(#viewerContainer.pdfPresentationMode:fullscreen,.annotationEditorLayer.disabled) .noAltTextBadge{ - display:none !important; - } - -@media (min-resolution: 1.1dppx){ - :root{ - --editorFreeText-editing-cursor:url(images/cursor-editorFreeText.svg) 0 16, text; - } -} - -@media screen and (forced-colors: active){ - :root{ - --outline-color:CanvasText; - --outline-around-color:ButtonFace; - --resizer-bg-color:ButtonText; - --hover-outline-color:Highlight; - --hover-outline-around-color:SelectedItemText; - } -} - -[data-editor-rotation="90"]{ - transform:rotate(90deg); -} - -[data-editor-rotation="180"]{ - transform:rotate(180deg); -} - -[data-editor-rotation="270"]{ - transform:rotate(270deg); -} - -.annotationEditorLayer{ - background:transparent; - position:absolute; - inset:0; - font-size:calc(100px * var(--scale-factor)); - transform-origin:0 0; - cursor:auto; -} - -.annotationEditorLayer .selectedEditor{ - z-index:100000 !important; - } - -.annotationEditorLayer.drawing *{ - pointer-events:none !important; - } - -.annotationEditorLayer.waiting{ - content:""; - cursor:wait; - position:absolute; - inset:0; - width:100%; - height:100%; -} - -.annotationEditorLayer.disabled{ - pointer-events:none; -} - -.annotationEditorLayer.freetextEditing{ - cursor:var(--editorFreeText-editing-cursor); -} - -.annotationEditorLayer.inkEditing{ - cursor:var(--editorInk-editing-cursor); -} - -.annotationEditorLayer .draw{ - box-sizing:border-box; -} - -.annotationEditorLayer :is(.freeTextEditor, .inkEditor, .stampEditor){ - position:absolute; - background:transparent; - z-index:1; - transform-origin:0 0; - cursor:auto; - max-width:100%; - max-height:100%; - border:var(--unfocus-outline); -} - -.draggable.selectedEditor:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)){ - cursor:move; - } - -.selectedEditor:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)){ - border:var(--focus-outline); - outline:var(--focus-outline-around); - } - -.selectedEditor:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor))::before{ - content:""; - position:absolute; - inset:0; - border:var(--focus-outline-around); - pointer-events:none; - } - -:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)):hover:not(.selectedEditor){ - border:var(--hover-outline); - outline:var(--hover-outline-around); - } - -:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)):hover:not(.selectedEditor)::before{ - content:""; - position:absolute; - inset:0; - border:var(--focus-outline-around); - } - -:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar{ - --editor-toolbar-delete-image:url(images/editor-toolbar-delete.svg); - --editor-toolbar-bg-color:#f0f0f4; - --editor-toolbar-highlight-image:url(images/toolbarButton-editorHighlight.svg); - --editor-toolbar-fg-color:#2e2e56; - --editor-toolbar-border-color:#8f8f9d; - --editor-toolbar-hover-border-color:var(--editor-toolbar-border-color); - --editor-toolbar-hover-bg-color:#e0e0e6; - --editor-toolbar-hover-fg-color:var(--editor-toolbar-fg-color); - --editor-toolbar-hover-outline:none; - --editor-toolbar-focus-outline-color:#0060df; - --editor-toolbar-shadow:0 2px 6px 0 rgb(58 57 68 / 0.2); - --editor-toolbar-vert-offset:6px; - --editor-toolbar-height:28px; - --editor-toolbar-padding:2px; - --alt-text-done-color:#2ac3a2; - --alt-text-warning-color:#0090ed; - --alt-text-hover-done-color:var(--alt-text-done-color); - --alt-text-hover-warning-color:var(--alt-text-warning-color); - } - -@media (prefers-color-scheme: dark){ - -:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar{ - --editor-toolbar-bg-color:#2b2a33; - --editor-toolbar-fg-color:#fbfbfe; - --editor-toolbar-hover-bg-color:#52525e; - --editor-toolbar-focus-outline-color:#0df; - --alt-text-done-color:#54ffbd; - --alt-text-warning-color:#80ebff; - } - } - -@media screen and (forced-colors: active){ - -:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar{ - --editor-toolbar-bg-color:ButtonFace; - --editor-toolbar-fg-color:ButtonText; - --editor-toolbar-border-color:ButtonText; - --editor-toolbar-hover-border-color:AccentColor; - --editor-toolbar-hover-bg-color:ButtonFace; - --editor-toolbar-hover-fg-color:AccentColor; - --editor-toolbar-hover-outline:2px solid var(--editor-toolbar-hover-border-color); - --editor-toolbar-focus-outline-color:ButtonBorder; - --editor-toolbar-shadow:none; - --alt-text-done-color:var(--editor-toolbar-fg-color); - --alt-text-warning-color:var(--editor-toolbar-fg-color); - --alt-text-hover-done-color:var(--editor-toolbar-hover-fg-color); - --alt-text-hover-warning-color:var(--editor-toolbar-hover-fg-color); - } - } - -:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar{ - - display:flex; - width:-moz-fit-content; - width:fit-content; - height:var(--editor-toolbar-height); - flex-direction:column; - justify-content:center; - align-items:center; - cursor:default; - pointer-events:auto; - box-sizing:content-box; - padding:var(--editor-toolbar-padding); - - position:absolute; - inset-inline-end:0; - inset-block-start:calc(100% + var(--editor-toolbar-vert-offset)); - - border-radius:6px; - background-color:var(--editor-toolbar-bg-color); - border:1px solid var(--editor-toolbar-border-color); - box-shadow:var(--editor-toolbar-shadow); - } - -.hidden:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar){ - display:none; - } - -:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar):has(:focus-visible){ - border-color:transparent; - } - -[dir="ltr"] :is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar){ - transform-origin:100% 0; - } - -[dir="rtl"] :is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar){ - transform-origin:0 0; - } - -:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons{ - display:flex; - justify-content:center; - align-items:center; - gap:0; - height:100%; - } - -:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) button{ - padding:0; - } - -:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .divider{ - width:0; - height:calc( - 2 * var(--editor-toolbar-padding) + var(--editor-toolbar-height) - ); - border-left:1px solid var(--editor-toolbar-border-color); - border-right:none; - display:inline-block; - margin-inline:2px; - } - -:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .highlightButton{ - width:var(--editor-toolbar-height); - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .highlightButton)::before{ - content:""; - -webkit-mask-image:var(--editor-toolbar-highlight-image); - mask-image:var(--editor-toolbar-highlight-image); - -webkit-mask-repeat:no-repeat; - mask-repeat:no-repeat; - -webkit-mask-position:center; - mask-position:center; - display:inline-block; - background-color:var(--editor-toolbar-fg-color); - width:100%; - height:100%; - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .highlightButton):hover::before{ - background-color:var(--editor-toolbar-hover-fg-color); - } - -:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .delete{ - width:var(--editor-toolbar-height); - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .delete)::before{ - content:""; - -webkit-mask-image:var(--editor-toolbar-delete-image); - mask-image:var(--editor-toolbar-delete-image); - -webkit-mask-repeat:no-repeat; - mask-repeat:no-repeat; - -webkit-mask-position:center; - mask-position:center; - display:inline-block; - background-color:var(--editor-toolbar-fg-color); - width:100%; - height:100%; - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .delete):hover::before{ - background-color:var(--editor-toolbar-hover-fg-color); - } - -:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) > *{ - height:var(--editor-toolbar-height); - } - -:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) > :not(.divider){ - border:none; - background-color:transparent; - cursor:pointer; - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) > :not(.divider)):hover{ - border-radius:2px; - background-color:var(--editor-toolbar-hover-bg-color); - color:var(--editor-toolbar-hover-fg-color); - outline:var(--editor-toolbar-hover-outline); - outline-offset:1px; - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) > :not(.divider)):hover:active{ - outline:none; - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) > :not(.divider)):focus-visible{ - border-radius:2px; - outline:2px solid var(--editor-toolbar-focus-outline-color); - } - -:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText{ - --alt-text-add-image:url(images/altText_add.svg); - --alt-text-done-image:url(images/altText_done.svg); - - display:flex; - align-items:center; - justify-content:center; - width:-moz-max-content; - width:max-content; - padding-inline:8px; - pointer-events:all; - font:menu; - font-weight:590; - font-size:12px; - color:var(--editor-toolbar-fg-color); - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText):disabled{ - pointer-events:none; - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText)::before{ - content:""; - -webkit-mask-image:var(--alt-text-add-image); - mask-image:var(--alt-text-add-image); - -webkit-mask-repeat:no-repeat; - mask-repeat:no-repeat; - -webkit-mask-position:center; - mask-position:center; - display:inline-block; - width:12px; - height:13px; - background-color:var(--editor-toolbar-fg-color); - margin-inline-end:4px; - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText):hover::before{ - background-color:var(--editor-toolbar-hover-fg-color); - } - -.done:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText)::before{ - -webkit-mask-image:var(--alt-text-done-image); - mask-image:var(--alt-text-done-image); - } - -.new:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText)::before{ - width:16px; - height:16px; - -webkit-mask-image:var(--new-alt-text-warning-image); - mask-image:var(--new-alt-text-warning-image); - background-color:var(--alt-text-warning-color); - -webkit-mask-size:cover; - mask-size:cover; - } - -.new:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText):hover::before{ - background-color:var(--alt-text-hover-warning-color); - } - -.new.done:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText)::before{ - -webkit-mask-image:var(--alt-text-done-image); - mask-image:var(--alt-text-done-image); - background-color:var(--alt-text-done-color); - } - -.new.done:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText):hover::before{ - background-color:var(--alt-text-hover-done-color); - } - -:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText) .tooltip{ - display:none; - word-wrap:anywhere; - } - -.show:is(:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText) .tooltip){ - --alt-text-tooltip-bg:#f0f0f4; - --alt-text-tooltip-fg:#15141a; - --alt-text-tooltip-border:#8f8f9d; - --alt-text-tooltip-shadow:0px 2px 6px 0px rgb(58 57 68 / 0.2); - } - -@media (prefers-color-scheme: dark){ - -.show:is(:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText) .tooltip){ - --alt-text-tooltip-bg:#1c1b22; - --alt-text-tooltip-fg:#fbfbfe; - --alt-text-tooltip-shadow:0px 2px 6px 0px #15141a; - } - } - -@media screen and (forced-colors: active){ - -.show:is(:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText) .tooltip){ - --alt-text-tooltip-bg:Canvas; - --alt-text-tooltip-fg:CanvasText; - --alt-text-tooltip-border:CanvasText; - --alt-text-tooltip-shadow:none; - } - } - -.show:is(:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText) .tooltip){ - - display:inline-flex; - flex-direction:column; - align-items:center; - justify-content:center; - position:absolute; - top:calc(100% + 2px); - inset-inline-start:0; - padding-block:2px 3px; - padding-inline:3px; - max-width:300px; - width:-moz-max-content; - width:max-content; - height:auto; - font-size:12px; - - border:0.5px solid var(--alt-text-tooltip-border); - background:var(--alt-text-tooltip-bg); - box-shadow:var(--alt-text-tooltip-shadow); - color:var(--alt-text-tooltip-fg); - - pointer-events:none; - } - -.annotationEditorLayer .freeTextEditor{ - padding:calc(var(--freetext-padding) * var(--scale-factor)); - width:auto; - height:auto; - touch-action:none; -} - -.annotationEditorLayer .freeTextEditor .internal{ - background:transparent; - border:none; - inset:0; - overflow:visible; - white-space:nowrap; - font:10px sans-serif; - line-height:var(--freetext-line-height); - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; -} - -.annotationEditorLayer .freeTextEditor .overlay{ - position:absolute; - display:none; - background:transparent; - inset:0; - width:100%; - height:100%; -} - -.annotationEditorLayer freeTextEditor .overlay.enabled{ - display:block; -} - -.annotationEditorLayer .freeTextEditor .internal:empty::before{ - content:attr(default-content); - color:gray; -} - -.annotationEditorLayer .freeTextEditor .internal:focus{ - outline:none; - -webkit-user-select:auto; - -moz-user-select:auto; - user-select:auto; -} - -.annotationEditorLayer .inkEditor{ - width:100%; - height:100%; -} - -.annotationEditorLayer .inkEditor.editing{ - cursor:inherit; -} - -.annotationEditorLayer .inkEditor .inkEditorCanvas{ - position:absolute; - inset:0; - width:100%; - height:100%; - touch-action:none; -} - -.annotationEditorLayer .stampEditor{ - width:auto; - height:auto; -} - -:is(.annotationEditorLayer .stampEditor) canvas{ - position:absolute; - width:100%; - height:100%; - margin:0; - top:0; - left:0; - } - -:is(.annotationEditorLayer .stampEditor) .noAltTextBadge{ - --no-alt-text-badge-border-color:#f0f0f4; - --no-alt-text-badge-bg-color:#cfcfd8; - --no-alt-text-badge-fg-color:#5b5b66; - } - -@media (prefers-color-scheme: dark){ - -:is(.annotationEditorLayer .stampEditor) .noAltTextBadge{ - --no-alt-text-badge-border-color:#52525e; - --no-alt-text-badge-bg-color:#fbfbfe; - --no-alt-text-badge-fg-color:#15141a; - } - } - -@media screen and (forced-colors: active){ - -:is(.annotationEditorLayer .stampEditor) .noAltTextBadge{ - --no-alt-text-badge-border-color:ButtonText; - --no-alt-text-badge-bg-color:ButtonFace; - --no-alt-text-badge-fg-color:ButtonText; - } - } - -:is(.annotationEditorLayer .stampEditor) .noAltTextBadge{ - - position:absolute; - inset-inline-end:5px; - inset-block-end:5px; - display:inline-flex; - width:32px; - height:32px; - padding:3px; - justify-content:center; - align-items:center; - pointer-events:none; - z-index:1; - - border-radius:2px; - border:1px solid var(--no-alt-text-badge-border-color); - background:var(--no-alt-text-badge-bg-color); - } - -:is(:is(.annotationEditorLayer .stampEditor) .noAltTextBadge)::before{ - content:""; - display:inline-block; - width:16px; - height:16px; - -webkit-mask-image:var(--new-alt-text-warning-image); - mask-image:var(--new-alt-text-warning-image); - -webkit-mask-size:cover; - mask-size:cover; - background-color:var(--no-alt-text-badge-fg-color); - } - -:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers{ - position:absolute; - inset:0; - } - -.hidden:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers){ - display:none; - } - -:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer{ - width:var(--resizer-size); - height:var(--resizer-size); - background:content-box var(--resizer-bg-color); - border:var(--focus-outline-around); - border-radius:2px; - position:absolute; - } - -.topLeft:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer){ - top:var(--resizer-shift); - left:var(--resizer-shift); - } - -.topMiddle:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer){ - top:var(--resizer-shift); - left:calc(50% + var(--resizer-shift)); - } - -.topRight:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer){ - top:var(--resizer-shift); - right:var(--resizer-shift); - } - -.middleRight:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer){ - top:calc(50% + var(--resizer-shift)); - right:var(--resizer-shift); - } - -.bottomRight:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer){ - bottom:var(--resizer-shift); - right:var(--resizer-shift); - } - -.bottomMiddle:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer){ - bottom:var(--resizer-shift); - left:calc(50% + var(--resizer-shift)); - } - -.bottomLeft:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer){ - bottom:var(--resizer-shift); - left:var(--resizer-shift); - } - -.middleLeft:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor)) > .resizers) > .resizer){ - top:calc(50% + var(--resizer-shift)); - left:var(--resizer-shift); - } - -.topLeft:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="180"],[data-editor-rotation="0"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="90"],[data-editor-rotation="270"])) > .resizers > .resizer),.bottomRight:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="180"],[data-editor-rotation="0"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="90"],[data-editor-rotation="270"])) > .resizers > .resizer){ - cursor:nwse-resize; - } - -.topMiddle:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="180"],[data-editor-rotation="0"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="90"],[data-editor-rotation="270"])) > .resizers > .resizer),.bottomMiddle:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="180"],[data-editor-rotation="0"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="90"],[data-editor-rotation="270"])) > .resizers > .resizer){ - cursor:ns-resize; - } - -.topRight:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="180"],[data-editor-rotation="0"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="90"],[data-editor-rotation="270"])) > .resizers > .resizer),.bottomLeft:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="180"],[data-editor-rotation="0"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="90"],[data-editor-rotation="270"])) > .resizers > .resizer){ - cursor:nesw-resize; - } - -.middleRight:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="180"],[data-editor-rotation="0"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="90"],[data-editor-rotation="270"])) > .resizers > .resizer),.middleLeft:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="180"],[data-editor-rotation="0"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="90"],[data-editor-rotation="270"])) > .resizers > .resizer){ - cursor:ew-resize; - } - -.topLeft:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="90"],[data-editor-rotation="270"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="180"],[data-editor-rotation="0"])) > .resizers > .resizer),.bottomRight:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="90"],[data-editor-rotation="270"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="180"],[data-editor-rotation="0"])) > .resizers > .resizer){ - cursor:nesw-resize; - } - -.topMiddle:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="90"],[data-editor-rotation="270"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="180"],[data-editor-rotation="0"])) > .resizers > .resizer),.bottomMiddle:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="90"],[data-editor-rotation="270"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="180"],[data-editor-rotation="0"])) > .resizers > .resizer){ - cursor:ew-resize; - } - -.topRight:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="90"],[data-editor-rotation="270"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="180"],[data-editor-rotation="0"])) > .resizers > .resizer),.bottomLeft:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="90"],[data-editor-rotation="270"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="180"],[data-editor-rotation="0"])) > .resizers > .resizer){ - cursor:nwse-resize; - } - -.middleRight:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="90"],[data-editor-rotation="270"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="180"],[data-editor-rotation="0"])) > .resizers > .resizer),.middleLeft:is(:is(.annotationEditorLayer[data-main-rotation="0"] :is([data-editor-rotation="90"],[data-editor-rotation="270"]),.annotationEditorLayer[data-main-rotation="90"] :is([data-editor-rotation="0"],[data-editor-rotation="180"]),.annotationEditorLayer[data-main-rotation="180"] :is([data-editor-rotation="270"],[data-editor-rotation="90"]),.annotationEditorLayer[data-main-rotation="270"] :is([data-editor-rotation="180"],[data-editor-rotation="0"])) > .resizers > .resizer){ - cursor:ns-resize; - } - -:is(.annotationEditorLayer :is([data-main-rotation="0"] [data-editor-rotation="90"],[data-main-rotation="90"] [data-editor-rotation="0"],[data-main-rotation="180"] [data-editor-rotation="270"],[data-main-rotation="270"] [data-editor-rotation="180"])) .editToolbar{ - rotate:270deg; - } - -[dir="ltr"] :is(:is(.annotationEditorLayer :is([data-main-rotation="0"] [data-editor-rotation="90"],[data-main-rotation="90"] [data-editor-rotation="0"],[data-main-rotation="180"] [data-editor-rotation="270"],[data-main-rotation="270"] [data-editor-rotation="180"])) .editToolbar){ - inset-inline-end:calc(0px - var(--editor-toolbar-vert-offset)); - inset-block-start:0; - } - -[dir="rtl"] :is(:is(.annotationEditorLayer :is([data-main-rotation="0"] [data-editor-rotation="90"],[data-main-rotation="90"] [data-editor-rotation="0"],[data-main-rotation="180"] [data-editor-rotation="270"],[data-main-rotation="270"] [data-editor-rotation="180"])) .editToolbar){ - inset-inline-end:calc(100% + var(--editor-toolbar-vert-offset)); - inset-block-start:0; - } - -:is(.annotationEditorLayer :is([data-main-rotation="0"] [data-editor-rotation="180"],[data-main-rotation="90"] [data-editor-rotation="90"],[data-main-rotation="180"] [data-editor-rotation="0"],[data-main-rotation="270"] [data-editor-rotation="270"])) .editToolbar{ - rotate:180deg; - inset-inline-end:100%; - inset-block-start:calc(0pc - var(--editor-toolbar-vert-offset)); - } - -:is(.annotationEditorLayer :is([data-main-rotation="0"] [data-editor-rotation="270"],[data-main-rotation="90"] [data-editor-rotation="180"],[data-main-rotation="180"] [data-editor-rotation="90"],[data-main-rotation="270"] [data-editor-rotation="0"])) .editToolbar{ - rotate:90deg; - } - -[dir="ltr"] :is(:is(.annotationEditorLayer :is([data-main-rotation="0"] [data-editor-rotation="270"],[data-main-rotation="90"] [data-editor-rotation="180"],[data-main-rotation="180"] [data-editor-rotation="90"],[data-main-rotation="270"] [data-editor-rotation="0"])) .editToolbar){ - inset-inline-end:calc(100% + var(--editor-toolbar-vert-offset)); - inset-block-start:100%; - } - -[dir="rtl"] :is(:is(.annotationEditorLayer :is([data-main-rotation="0"] [data-editor-rotation="270"],[data-main-rotation="90"] [data-editor-rotation="180"],[data-main-rotation="180"] [data-editor-rotation="90"],[data-main-rotation="270"] [data-editor-rotation="0"])) .editToolbar){ - inset-inline-start:calc(0px - var(--editor-toolbar-vert-offset)); - inset-block-start:0; - } - -.dialog.altText::backdrop{ - -webkit-mask:url(#alttext-manager-mask); - mask:url(#alttext-manager-mask); - } - -.dialog.altText.positioned{ - margin:0; - } - -.dialog.altText #altTextContainer{ - width:300px; - height:-moz-fit-content; - height:fit-content; - display:inline-flex; - flex-direction:column; - align-items:flex-start; - gap:16px; - } - -:is(.dialog.altText #altTextContainer) #overallDescription{ - display:flex; - flex-direction:column; - align-items:flex-start; - gap:4px; - align-self:stretch; - } - -:is(:is(.dialog.altText #altTextContainer) #overallDescription) span{ - align-self:stretch; - } - -:is(:is(.dialog.altText #altTextContainer) #overallDescription) .title{ - font-size:13px; - font-style:normal; - font-weight:590; - } - -:is(.dialog.altText #altTextContainer) #addDescription{ - display:flex; - flex-direction:column; - align-items:stretch; - gap:8px; - } - -:is(:is(.dialog.altText #altTextContainer) #addDescription) .descriptionArea{ - flex:1; - padding-inline:24px 10px; - } - -:is(:is(:is(.dialog.altText #altTextContainer) #addDescription) .descriptionArea) textarea{ - width:100%; - min-height:75px; - } - -:is(.dialog.altText #altTextContainer) #buttons{ - display:flex; - justify-content:flex-end; - align-items:flex-start; - gap:8px; - align-self:stretch; - } - -.dialog.newAltText{ - --new-alt-text-ai-disclaimer-icon:url(images/altText_disclaimer.svg); - --new-alt-text-spinner-icon:url(images/altText_spinner.svg); - --preview-image-bg-color:#f0f0f4; - --preview-image-border:none; -} - -@media (prefers-color-scheme: dark){ - -.dialog.newAltText{ - --preview-image-bg-color:#2b2a33; -} - } - -@media screen and (forced-colors: active){ - -.dialog.newAltText{ - --preview-image-bg-color:ButtonFace; - --preview-image-border:1px solid ButtonText; -} - } - -.dialog.newAltText{ - - width:80%; - max-width:570px; - min-width:300px; - padding:0; -} - -.dialog.newAltText.noAi #newAltTextDisclaimer,.dialog.newAltText.noAi #newAltTextCreateAutomatically{ - display:none !important; - } - -.dialog.newAltText.aiInstalling #newAltTextCreateAutomatically{ - display:none !important; - } - -.dialog.newAltText.aiInstalling #newAltTextDownloadModel{ - display:flex !important; - } - -.dialog.newAltText.error #newAltTextNotNow{ - display:none !important; - } - -.dialog.newAltText.error #newAltTextCancel{ - display:inline-block !important; - } - -.dialog.newAltText:not(.error) #newAltTextError{ - display:none !important; - } - -.dialog.newAltText #newAltTextContainer{ - display:flex; - width:auto; - padding:16px; - flex-direction:column; - justify-content:flex-end; - align-items:flex-start; - gap:12px; - flex:0 1 auto; - line-height:normal; - } - -:is(.dialog.newAltText #newAltTextContainer) #mainContent{ - display:flex; - justify-content:flex-end; - align-items:flex-start; - gap:12px; - align-self:stretch; - flex:1 1 auto; - } - -:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionAndSettings{ - display:flex; - flex-direction:column; - align-items:flex-start; - gap:16px; - flex:1 0 0; - align-self:stretch; - } - -:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction{ - display:flex; - flex-direction:column; - align-items:flex-start; - gap:8px; - align-self:stretch; - flex:1 1 auto; - } - -:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescriptionContainer{ - width:100%; - height:70px; - position:relative; - } - -:is(:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescriptionContainer) textarea{ - width:100%; - height:100%; - padding:8px; - } - -:is(:is(:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescriptionContainer) textarea)::-moz-placeholder{ - color:var(--text-secondary-color); - } - -:is(:is(:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescriptionContainer) textarea)::placeholder{ - color:var(--text-secondary-color); - } - -:is(:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescriptionContainer) .altTextSpinner{ - display:none; - position:absolute; - width:16px; - height:16px; - inset-inline-start:8px; - inset-block-start:8px; - -webkit-mask-size:cover; - mask-size:cover; - background-color:var(--text-secondary-color); - pointer-events:none; - } - -.loading:is(:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescriptionContainer) textarea::-moz-placeholder{ - color:transparent; - } - -.loading:is(:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescriptionContainer) textarea::placeholder{ - color:transparent; - } - -.loading:is(:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescriptionContainer) .altTextSpinner{ - display:inline-block; - -webkit-mask-image:var(--new-alt-text-spinner-icon); - mask-image:var(--new-alt-text-spinner-icon); - } - -:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDescription{ - font-size:11px; - } - -:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDisclaimer{ - display:flex; - flex-direction:row; - align-items:flex-start; - gap:4px; - font-size:11px; - } - -:is(:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #descriptionInstruction) #newAltTextDisclaimer)::before{ - content:""; - display:inline-block; - width:17px; - height:16px; - -webkit-mask-image:var(--new-alt-text-ai-disclaimer-icon); - mask-image:var(--new-alt-text-ai-disclaimer-icon); - -webkit-mask-size:cover; - mask-size:cover; - background-color:var(--text-secondary-color); - flex:1 0 auto; - } - -:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #newAltTextDownloadModel{ - display:flex; - align-items:center; - gap:4px; - align-self:stretch; - } - -:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #newAltTextDownloadModel)::before{ - content:""; - display:inline-block; - width:16px; - height:16px; - -webkit-mask-image:var(--new-alt-text-spinner-icon); - mask-image:var(--new-alt-text-spinner-icon); - -webkit-mask-size:cover; - mask-size:cover; - background-color:var(--text-secondary-color); - } - -:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #newAltTextImagePreview{ - width:180px; - aspect-ratio:1; - display:flex; - justify-content:center; - align-items:center; - flex:0 0 auto; - background-color:var(--preview-image-bg-color); - border:var(--preview-image-border); - } - -:is(:is(:is(.dialog.newAltText #newAltTextContainer) #mainContent) #newAltTextImagePreview) > canvas{ - max-width:100%; - max-height:100%; - } - -.colorPicker{ - --hover-outline-color:#0250bb; - --selected-outline-color:#0060df; - --swatch-border-color:#cfcfd8; -} - -@media (prefers-color-scheme: dark){ - -.colorPicker{ - --hover-outline-color:#80ebff; - --selected-outline-color:#aaf2ff; - --swatch-border-color:#52525e; -} - } - -@media screen and (forced-colors: active){ - -.colorPicker{ - --hover-outline-color:Highlight; - --selected-outline-color:var(--hover-outline-color); - --swatch-border-color:ButtonText; -} - } - -.colorPicker .swatch{ - width:16px; - height:16px; - border:1px solid var(--swatch-border-color); - border-radius:100%; - outline-offset:2px; - box-sizing:border-box; - forced-color-adjust:none; - } - -.colorPicker button:is(:hover,.selected) > .swatch{ - border:none; - } - -.annotationEditorLayer[data-main-rotation="0"] .highlightEditor:not(.free) > .editToolbar{ - rotate:0deg; - } - -.annotationEditorLayer[data-main-rotation="90"] .highlightEditor:not(.free) > .editToolbar{ - rotate:270deg; - } - -.annotationEditorLayer[data-main-rotation="180"] .highlightEditor:not(.free) > .editToolbar{ - rotate:180deg; - } - -.annotationEditorLayer[data-main-rotation="270"] .highlightEditor:not(.free) > .editToolbar{ - rotate:90deg; - } - -.annotationEditorLayer .highlightEditor{ - position:absolute; - background:transparent; - z-index:1; - cursor:auto; - max-width:100%; - max-height:100%; - border:none; - outline:none; - pointer-events:none; - transform-origin:0 0; - } - -:is(.annotationEditorLayer .highlightEditor):not(.free){ - transform:none; - } - -:is(.annotationEditorLayer .highlightEditor) .internal{ - position:absolute; - top:0; - left:0; - width:100%; - height:100%; - pointer-events:auto; - } - -.disabled:is(.annotationEditorLayer .highlightEditor) .internal{ - pointer-events:none; - } - -.selectedEditor:is(.annotationEditorLayer .highlightEditor) .internal{ - cursor:pointer; - } - -:is(.annotationEditorLayer .highlightEditor) .editToolbar{ - --editor-toolbar-colorpicker-arrow-image:url(images/toolbarButton-menuArrow.svg); - - transform-origin:center !important; - } - -:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker{ - position:relative; - width:auto; - display:flex; - justify-content:center; - align-items:center; - gap:4px; - padding:4px; - } - -:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker)::after{ - content:""; - -webkit-mask-image:var(--editor-toolbar-colorpicker-arrow-image); - mask-image:var(--editor-toolbar-colorpicker-arrow-image); - -webkit-mask-repeat:no-repeat; - mask-repeat:no-repeat; - -webkit-mask-position:center; - mask-position:center; - display:inline-block; - background-color:var(--editor-toolbar-fg-color); - width:12px; - height:12px; - } - -:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker):hover::after{ - background-color:var(--editor-toolbar-hover-fg-color); - } - -:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker):has(.dropdown:not(.hidden)){ - background-color:var(--editor-toolbar-hover-bg-color); - } - -:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker):has(.dropdown:not(.hidden))::after{ - scale:-1; - } - -:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker) .dropdown{ - position:absolute; - display:flex; - justify-content:center; - align-items:center; - flex-direction:column; - gap:11px; - padding-block:8px; - border-radius:6px; - background-color:var(--editor-toolbar-bg-color); - border:1px solid var(--editor-toolbar-border-color); - box-shadow:var(--editor-toolbar-shadow); - inset-block-start:calc(100% + 4px); - width:calc(100% + 2 * var(--editor-toolbar-padding)); - } - -:is(:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker) .dropdown) button{ - width:100%; - height:auto; - border:none; - cursor:pointer; - display:flex; - justify-content:center; - align-items:center; - background:none; - } - -:is(:is(:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker) .dropdown) button):is(:active,:focus-visible){ - outline:none; - } - -:is(:is(:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker) .dropdown) button) > .swatch{ - outline-offset:2px; - } - -[aria-selected="true"]:is(:is(:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker) .dropdown) button) > .swatch{ - outline:2px solid var(--selected-outline-color); - } - -:is(:is(:is(:is(:is(:is(.annotationEditorLayer .highlightEditor) .editToolbar) .buttons) .colorPicker) .dropdown) button):is(:hover,:active,:focus-visible) > .swatch{ - outline:2px solid var(--hover-outline-color); - } - -.editorParamsToolbar:has(#highlightParamsToolbarContainer){ - padding:unset; -} - -#highlightParamsToolbarContainer{ - gap:16px; - padding-inline:10px; - padding-block-end:12px; -} - -#highlightParamsToolbarContainer .colorPicker{ - display:flex; - flex-direction:column; - gap:8px; - } - -:is(#highlightParamsToolbarContainer .colorPicker) .dropdown{ - display:flex; - justify-content:space-between; - align-items:center; - flex-direction:row; - height:auto; - } - -:is(:is(#highlightParamsToolbarContainer .colorPicker) .dropdown) button{ - width:auto; - height:auto; - border:none; - cursor:pointer; - display:flex; - justify-content:center; - align-items:center; - background:none; - flex:0 0 auto; - padding:0; - } - -:is(:is(:is(#highlightParamsToolbarContainer .colorPicker) .dropdown) button) .swatch{ - width:24px; - height:24px; - } - -:is(:is(:is(#highlightParamsToolbarContainer .colorPicker) .dropdown) button):is(:active,:focus-visible){ - outline:none; - } - -[aria-selected="true"]:is(:is(:is(#highlightParamsToolbarContainer .colorPicker) .dropdown) button) > .swatch{ - outline:2px solid var(--selected-outline-color); - } - -:is(:is(:is(#highlightParamsToolbarContainer .colorPicker) .dropdown) button):is(:hover,:active,:focus-visible) > .swatch{ - outline:2px solid var(--hover-outline-color); - } - -#highlightParamsToolbarContainer #editorHighlightThickness{ - display:flex; - flex-direction:column; - align-items:center; - gap:4px; - align-self:stretch; - } - -:is(#highlightParamsToolbarContainer #editorHighlightThickness) .editorParamsLabel{ - height:auto; - align-self:stretch; - } - -:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker{ - display:flex; - justify-content:space-between; - align-items:center; - align-self:stretch; - - --example-color:#bfbfc9; - } - -@media (prefers-color-scheme: dark){ - -:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker{ - --example-color:#80808e; - } - } - -@media screen and (forced-colors: active){ - -:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker{ - --example-color:CanvasText; - } - } - -:is(:is(:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker) > .editorParamsSlider[disabled]){ - opacity:0.4; - } - -:is(:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker)::before,:is(:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker)::after{ - content:""; - width:8px; - aspect-ratio:1; - display:block; - border-radius:100%; - background-color:var(--example-color); - } - -:is(:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker)::after{ - width:24px; - } - -:is(:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker) .editorParamsSlider{ - width:unset; - height:14px; - } - -#highlightParamsToolbarContainer #editorHighlightVisibility{ - display:flex; - flex-direction:column; - align-items:flex-start; - gap:8px; - align-self:stretch; - } - -:is(#highlightParamsToolbarContainer #editorHighlightVisibility) .divider{ - --divider-color:#d7d7db; - } - -@media (prefers-color-scheme: dark){ - -:is(#highlightParamsToolbarContainer #editorHighlightVisibility) .divider{ - --divider-color:#8f8f9d; - } - } - -@media screen and (forced-colors: active){ - -:is(#highlightParamsToolbarContainer #editorHighlightVisibility) .divider{ - --divider-color:CanvasText; - } - } - -:is(#highlightParamsToolbarContainer #editorHighlightVisibility) .divider{ - - margin-block:4px; - width:100%; - height:1px; - background-color:var(--divider-color); - } - -:is(#highlightParamsToolbarContainer #editorHighlightVisibility) .toggler{ - display:flex; - justify-content:space-between; - align-items:center; - align-self:stretch; - } - -#altTextSettingsDialog{ - padding:16px; -} - -#altTextSettingsDialog #altTextSettingsContainer{ - display:flex; - width:573px; - flex-direction:column; - gap:16px; - } - -:is(#altTextSettingsDialog #altTextSettingsContainer) .mainContainer{ - gap:16px; - } - -:is(#altTextSettingsDialog #altTextSettingsContainer) .description{ - color:var(--text-secondary-color); - } - -:is(#altTextSettingsDialog #altTextSettingsContainer) #aiModelSettings{ - display:flex; - flex-direction:column; - gap:12px; - } - -:is(:is(#altTextSettingsDialog #altTextSettingsContainer) #aiModelSettings) button{ - width:-moz-fit-content; - width:fit-content; - } - -.download:is(:is(#altTextSettingsDialog #altTextSettingsContainer) #aiModelSettings) #deleteModelButton{ - display:none; - } - -:is(:is(#altTextSettingsDialog #altTextSettingsContainer) #aiModelSettings):not(.download) #downloadModelButton{ - display:none; - } - -:is(#altTextSettingsDialog #altTextSettingsContainer) #automaticAltText,:is(#altTextSettingsDialog #altTextSettingsContainer) #altTextEditor{ - display:flex; - flex-direction:column; - gap:8px; - } - -:is(#altTextSettingsDialog #altTextSettingsContainer) #createModelDescription,:is(#altTextSettingsDialog #altTextSettingsContainer) #aiModelSettings,:is(#altTextSettingsDialog #altTextSettingsContainer) #showAltTextDialogDescription{ - padding-inline-start:40px; - } - -:is(#altTextSettingsDialog #altTextSettingsContainer) #automaticSettings{ - display:flex; - flex-direction:column; - gap:16px; - } - -:root{ - --viewer-container-height:0; - --pdfViewer-padding-bottom:0; - --page-margin:1px auto -8px; - --page-border:9px solid transparent; - --spreadHorizontalWrapped-margin-LR:-3.5px; - --loading-icon-delay:400ms; -} - -@media screen and (forced-colors: active){ - :root{ - --pdfViewer-padding-bottom:9px; - --page-margin:8px auto -1px; - --page-border:1px solid CanvasText; - --spreadHorizontalWrapped-margin-LR:3.5px; - } -} - -[data-main-rotation="90"]{ - transform:rotate(90deg) translateY(-100%); -} -[data-main-rotation="180"]{ - transform:rotate(180deg) translate(-100%, -100%); -} -[data-main-rotation="270"]{ - transform:rotate(270deg) translateX(-100%); -} - -#hiddenCopyElement, -.hiddenCanvasElement{ - position:absolute; - top:0; - left:0; - width:0; - height:0; - display:none; -} - -.pdfViewer{ - --scale-factor:1; - --page-bg-color:unset; - - padding-bottom:var(--pdfViewer-padding-bottom); - - --hcm-highlight-filter:none; - --hcm-highlight-selected-filter:none; -} - -@media screen and (forced-colors: active){ - -.pdfViewer{ - --hcm-highlight-filter:invert(100%); -} - } - -.pdfViewer.copyAll{ - cursor:wait; - } - -.pdfViewer .canvasWrapper{ - overflow:hidden; - width:100%; - height:100%; - } - -:is(.pdfViewer .canvasWrapper) canvas{ - position:absolute; - top:0; - left:0; - margin:0; - display:block; - width:100%; - height:100%; - contain:content; - } - -:is(:is(.pdfViewer .canvasWrapper) canvas) .structTree{ - contain:strict; - } - -.pdfViewer .page{ - --scale-round-x:1px; - --scale-round-y:1px; - - direction:ltr; - width:816px; - height:1056px; - margin:var(--page-margin); - position:relative; - overflow:visible; - border:var(--page-border); - background-clip:content-box; - background-color:var(--page-bg-color, rgb(255 255 255)); -} - -.pdfViewer .dummyPage{ - position:relative; - width:0; - height:var(--viewer-container-height); -} - -.pdfViewer.noUserSelect{ - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; -} - -.pdfViewer.removePageBorders .page{ - margin:0 auto 10px; - border:none; -} - -.pdfViewer.singlePageView{ - display:inline-block; -} - -.pdfViewer.singlePageView .page{ - margin:0; - border:none; -} - -.pdfViewer:is(.scrollHorizontal, .scrollWrapped), -.spread{ - margin-inline:3.5px; - text-align:center; -} - -.pdfViewer.scrollHorizontal, -.spread{ - white-space:nowrap; -} - -.pdfViewer.removePageBorders, -.pdfViewer:is(.scrollHorizontal, .scrollWrapped) .spread{ - margin-inline:0; -} - -.spread :is(.page, .dummyPage), -.pdfViewer:is(.scrollHorizontal, .scrollWrapped) :is(.page, .spread){ - display:inline-block; - vertical-align:middle; -} - -.spread .page, -.pdfViewer:is(.scrollHorizontal, .scrollWrapped) .page{ - margin-inline:var(--spreadHorizontalWrapped-margin-LR); -} - -.pdfViewer.removePageBorders .spread .page, -.pdfViewer.removePageBorders:is(.scrollHorizontal, .scrollWrapped) .page{ - margin-inline:5px; -} - -.pdfViewer .page.loadingIcon::after{ - position:absolute; - top:0; - left:0; - content:""; - width:100%; - height:100%; - background:url("images/loading-icon.gif") center no-repeat; - display:none; - transition-property:display; - transition-delay:var(--loading-icon-delay); - z-index:5; - contain:strict; -} - -.pdfViewer .page.loading::after{ - display:block; -} - -.pdfViewer .page:not(.loading)::after{ - transition-property:none; - display:none; -} - -.pdfPresentationMode .pdfViewer{ - padding-bottom:0; -} - -.pdfPresentationMode .spread{ - margin:0; -} - -.pdfPresentationMode .pdfViewer .page{ - margin:0 auto; - border:2px solid transparent; -} diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.mjs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.mjs deleted file mode 100644 index 9b2c200c99e..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.mjs +++ /dev/null @@ -1,8435 +0,0 @@ -/** - * @licstart The following is the entire license notice for the - * JavaScript code in this page - * - * Copyright 2024 Mozilla Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * @licend The above is the entire license notice for the - * JavaScript code in this page - */ - -/******/ // The require scope -/******/ var __webpack_require__ = {}; -/******/ -/************************************************************************/ -/******/ /* webpack/runtime/define property getters */ -/******/ (() => { -/******/ // define getter functions for harmony exports -/******/ __webpack_require__.d = (exports, definition) => { -/******/ for(var key in definition) { -/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { -/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); -/******/ } -/******/ } -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/hasOwnProperty shorthand */ -/******/ (() => { -/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) -/******/ })(); -/******/ -/************************************************************************/ -var __webpack_exports__ = globalThis.pdfjsViewer = {}; - -// EXPORTS -__webpack_require__.d(__webpack_exports__, { - AnnotationLayerBuilder: () => (/* reexport */ AnnotationLayerBuilder), - DownloadManager: () => (/* reexport */ DownloadManager), - EventBus: () => (/* reexport */ EventBus), - FindState: () => (/* reexport */ FindState), - GenericL10n: () => (/* reexport */ genericl10n_GenericL10n), - LinkTarget: () => (/* reexport */ LinkTarget), - PDFFindController: () => (/* reexport */ PDFFindController), - PDFHistory: () => (/* reexport */ PDFHistory), - PDFLinkService: () => (/* reexport */ PDFLinkService), - PDFPageView: () => (/* reexport */ PDFPageView), - PDFScriptingManager: () => (/* reexport */ PDFScriptingManagerComponents), - PDFSinglePageViewer: () => (/* reexport */ PDFSinglePageViewer), - PDFViewer: () => (/* reexport */ PDFViewer), - ProgressBar: () => (/* reexport */ ProgressBar), - RenderingStates: () => (/* reexport */ RenderingStates), - ScrollMode: () => (/* reexport */ ScrollMode), - SimpleLinkService: () => (/* reexport */ SimpleLinkService), - SpreadMode: () => (/* reexport */ SpreadMode), - StructTreeLayerBuilder: () => (/* reexport */ StructTreeLayerBuilder), - TextLayerBuilder: () => (/* reexport */ TextLayerBuilder), - XfaLayerBuilder: () => (/* reexport */ XfaLayerBuilder), - parseQueryString: () => (/* reexport */ parseQueryString) -}); - -;// ./web/ui_utils.js -const DEFAULT_SCALE_VALUE = "auto"; -const DEFAULT_SCALE = 1.0; -const DEFAULT_SCALE_DELTA = 1.1; -const MIN_SCALE = 0.1; -const MAX_SCALE = 10.0; -const UNKNOWN_SCALE = 0; -const MAX_AUTO_SCALE = 1.25; -const SCROLLBAR_PADDING = 40; -const VERTICAL_PADDING = 5; -const RenderingStates = { - INITIAL: 0, - RUNNING: 1, - PAUSED: 2, - FINISHED: 3 -}; -const PresentationModeState = { - UNKNOWN: 0, - NORMAL: 1, - CHANGING: 2, - FULLSCREEN: 3 -}; -const SidebarView = { - UNKNOWN: -1, - NONE: 0, - THUMBS: 1, - OUTLINE: 2, - ATTACHMENTS: 3, - LAYERS: 4 -}; -const TextLayerMode = { - DISABLE: 0, - ENABLE: 1, - ENABLE_PERMISSIONS: 2 -}; -const ScrollMode = { - UNKNOWN: -1, - VERTICAL: 0, - HORIZONTAL: 1, - WRAPPED: 2, - PAGE: 3 -}; -const SpreadMode = { - UNKNOWN: -1, - NONE: 0, - ODD: 1, - EVEN: 2 -}; -const CursorTool = { - SELECT: 0, - HAND: 1, - ZOOM: 2 -}; -const AutoPrintRegExp = /\bprint\s*\(/; -function scrollIntoView(element, spot, scrollMatches = false) { - let parent = element.offsetParent; - if (!parent) { - console.error("offsetParent is not set -- cannot scroll"); - return; - } - let offsetY = element.offsetTop + element.clientTop; - let offsetX = element.offsetLeft + element.clientLeft; - while (parent.clientHeight === parent.scrollHeight && parent.clientWidth === parent.scrollWidth || scrollMatches && (parent.classList.contains("markedContent") || getComputedStyle(parent).overflow === "hidden")) { - offsetY += parent.offsetTop; - offsetX += parent.offsetLeft; - parent = parent.offsetParent; - if (!parent) { - return; - } - } - if (spot) { - if (spot.top !== undefined) { - offsetY += spot.top; - } - if (spot.left !== undefined) { - offsetX += spot.left; - parent.scrollLeft = offsetX; - } - } - parent.scrollTop = offsetY; -} -function watchScroll(viewAreaElement, callback, abortSignal = undefined) { - const debounceScroll = function (evt) { - if (rAF) { - return; - } - rAF = window.requestAnimationFrame(function viewAreaElementScrolled() { - rAF = null; - const currentX = viewAreaElement.scrollLeft; - const lastX = state.lastX; - if (currentX !== lastX) { - state.right = currentX > lastX; - } - state.lastX = currentX; - const currentY = viewAreaElement.scrollTop; - const lastY = state.lastY; - if (currentY !== lastY) { - state.down = currentY > lastY; - } - state.lastY = currentY; - callback(state); - }); - }; - const state = { - right: true, - down: true, - lastX: viewAreaElement.scrollLeft, - lastY: viewAreaElement.scrollTop, - _eventHandler: debounceScroll - }; - let rAF = null; - viewAreaElement.addEventListener("scroll", debounceScroll, { - useCapture: true, - signal: abortSignal - }); - abortSignal?.addEventListener("abort", () => window.cancelAnimationFrame(rAF), { - once: true - }); - return state; -} -function parseQueryString(query) { - const params = new Map(); - for (const [key, value] of new URLSearchParams(query)) { - params.set(key.toLowerCase(), value); - } - return params; -} -const InvisibleCharsRegExp = /[\x00-\x1F]/g; -function removeNullCharacters(str, replaceInvisible = false) { - if (!InvisibleCharsRegExp.test(str)) { - return str; - } - if (replaceInvisible) { - return str.replaceAll(InvisibleCharsRegExp, m => m === "\x00" ? "" : " "); - } - return str.replaceAll("\x00", ""); -} -function binarySearchFirstItem(items, condition, start = 0) { - let minIndex = start; - let maxIndex = items.length - 1; - if (maxIndex < 0 || !condition(items[maxIndex])) { - return items.length; - } - if (condition(items[minIndex])) { - return minIndex; - } - while (minIndex < maxIndex) { - const currentIndex = minIndex + maxIndex >> 1; - const currentItem = items[currentIndex]; - if (condition(currentItem)) { - maxIndex = currentIndex; - } else { - minIndex = currentIndex + 1; - } - } - return minIndex; -} -function approximateFraction(x) { - if (Math.floor(x) === x) { - return [x, 1]; - } - const xinv = 1 / x; - const limit = 8; - if (xinv > limit) { - return [1, limit]; - } else if (Math.floor(xinv) === xinv) { - return [1, xinv]; - } - const x_ = x > 1 ? xinv : x; - let a = 0, - b = 1, - c = 1, - d = 1; - while (true) { - const p = a + c, - q = b + d; - if (q > limit) { - break; - } - if (x_ <= p / q) { - c = p; - d = q; - } else { - a = p; - b = q; - } - } - let result; - if (x_ - a / b < c / d - x_) { - result = x_ === x ? [a, b] : [b, a]; - } else { - result = x_ === x ? [c, d] : [d, c]; - } - return result; -} -function floorToDivide(x, div) { - return x - x % div; -} -function getPageSizeInches({ - view, - userUnit, - rotate -}) { - const [x1, y1, x2, y2] = view; - const changeOrientation = rotate % 180 !== 0; - const width = (x2 - x1) / 72 * userUnit; - const height = (y2 - y1) / 72 * userUnit; - return { - width: changeOrientation ? height : width, - height: changeOrientation ? width : height - }; -} -function backtrackBeforeAllVisibleElements(index, views, top) { - if (index < 2) { - return index; - } - let elt = views[index].div; - let pageTop = elt.offsetTop + elt.clientTop; - if (pageTop >= top) { - elt = views[index - 1].div; - pageTop = elt.offsetTop + elt.clientTop; - } - for (let i = index - 2; i >= 0; --i) { - elt = views[i].div; - if (elt.offsetTop + elt.clientTop + elt.clientHeight <= pageTop) { - break; - } - index = i; - } - return index; -} -function getVisibleElements({ - scrollEl, - views, - sortByVisibility = false, - horizontal = false, - rtl = false -}) { - const top = scrollEl.scrollTop, - bottom = top + scrollEl.clientHeight; - const left = scrollEl.scrollLeft, - right = left + scrollEl.clientWidth; - function isElementBottomAfterViewTop(view) { - const element = view.div; - const elementBottom = element.offsetTop + element.clientTop + element.clientHeight; - return elementBottom > top; - } - function isElementNextAfterViewHorizontally(view) { - const element = view.div; - const elementLeft = element.offsetLeft + element.clientLeft; - const elementRight = elementLeft + element.clientWidth; - return rtl ? elementLeft < right : elementRight > left; - } - const visible = [], - ids = new Set(), - numViews = views.length; - let firstVisibleElementInd = binarySearchFirstItem(views, horizontal ? isElementNextAfterViewHorizontally : isElementBottomAfterViewTop); - if (firstVisibleElementInd > 0 && firstVisibleElementInd < numViews && !horizontal) { - firstVisibleElementInd = backtrackBeforeAllVisibleElements(firstVisibleElementInd, views, top); - } - let lastEdge = horizontal ? right : -1; - for (let i = firstVisibleElementInd; i < numViews; i++) { - const view = views[i], - element = view.div; - const currentWidth = element.offsetLeft + element.clientLeft; - const currentHeight = element.offsetTop + element.clientTop; - const viewWidth = element.clientWidth, - viewHeight = element.clientHeight; - const viewRight = currentWidth + viewWidth; - const viewBottom = currentHeight + viewHeight; - if (lastEdge === -1) { - if (viewBottom >= bottom) { - lastEdge = viewBottom; - } - } else if ((horizontal ? currentWidth : currentHeight) > lastEdge) { - break; - } - if (viewBottom <= top || currentHeight >= bottom || viewRight <= left || currentWidth >= right) { - continue; - } - const hiddenHeight = Math.max(0, top - currentHeight) + Math.max(0, viewBottom - bottom); - const hiddenWidth = Math.max(0, left - currentWidth) + Math.max(0, viewRight - right); - const fractionHeight = (viewHeight - hiddenHeight) / viewHeight, - fractionWidth = (viewWidth - hiddenWidth) / viewWidth; - const percent = fractionHeight * fractionWidth * 100 | 0; - visible.push({ - id: view.id, - x: currentWidth, - y: currentHeight, - view, - percent, - widthPercent: fractionWidth * 100 | 0 - }); - ids.add(view.id); - } - const first = visible[0], - last = visible.at(-1); - if (sortByVisibility) { - visible.sort(function (a, b) { - const pc = a.percent - b.percent; - if (Math.abs(pc) > 0.001) { - return -pc; - } - return a.id - b.id; - }); - } - return { - first, - last, - views: visible, - ids - }; -} -function normalizeWheelEventDirection(evt) { - let delta = Math.hypot(evt.deltaX, evt.deltaY); - const angle = Math.atan2(evt.deltaY, evt.deltaX); - if (-0.25 * Math.PI < angle && angle < 0.75 * Math.PI) { - delta = -delta; - } - return delta; -} -function normalizeWheelEventDelta(evt) { - const deltaMode = evt.deltaMode; - let delta = normalizeWheelEventDirection(evt); - const MOUSE_PIXELS_PER_LINE = 30; - const MOUSE_LINES_PER_PAGE = 30; - if (deltaMode === WheelEvent.DOM_DELTA_PIXEL) { - delta /= MOUSE_PIXELS_PER_LINE * MOUSE_LINES_PER_PAGE; - } else if (deltaMode === WheelEvent.DOM_DELTA_LINE) { - delta /= MOUSE_LINES_PER_PAGE; - } - return delta; -} -function isValidRotation(angle) { - return Number.isInteger(angle) && angle % 90 === 0; -} -function isValidScrollMode(mode) { - return Number.isInteger(mode) && Object.values(ScrollMode).includes(mode) && mode !== ScrollMode.UNKNOWN; -} -function isValidSpreadMode(mode) { - return Number.isInteger(mode) && Object.values(SpreadMode).includes(mode) && mode !== SpreadMode.UNKNOWN; -} -function isPortraitOrientation(size) { - return size.width <= size.height; -} -const animationStarted = new Promise(function (resolve) { - window.requestAnimationFrame(resolve); -}); -const docStyle = document.documentElement.style; -function clamp(v, min, max) { - return Math.min(Math.max(v, min), max); -} -class ProgressBar { - #classList = null; - #disableAutoFetchTimeout = null; - #percent = 0; - #style = null; - #visible = true; - constructor(bar) { - this.#classList = bar.classList; - this.#style = bar.style; - } - get percent() { - return this.#percent; - } - set percent(val) { - this.#percent = clamp(val, 0, 100); - if (isNaN(val)) { - this.#classList.add("indeterminate"); - return; - } - this.#classList.remove("indeterminate"); - this.#style.setProperty("--progressBar-percent", `${this.#percent}%`); - } - setWidth(viewer) { - if (!viewer) { - return; - } - const container = viewer.parentNode; - const scrollbarWidth = container.offsetWidth - viewer.offsetWidth; - if (scrollbarWidth > 0) { - this.#style.setProperty("--progressBar-end-offset", `${scrollbarWidth}px`); - } - } - setDisableAutoFetch(delay = 5000) { - if (this.#percent === 100 || isNaN(this.#percent)) { - return; - } - if (this.#disableAutoFetchTimeout) { - clearTimeout(this.#disableAutoFetchTimeout); - } - this.show(); - this.#disableAutoFetchTimeout = setTimeout(() => { - this.#disableAutoFetchTimeout = null; - this.hide(); - }, delay); - } - hide() { - if (!this.#visible) { - return; - } - this.#visible = false; - this.#classList.add("hidden"); - } - show() { - if (this.#visible) { - return; - } - this.#visible = true; - this.#classList.remove("hidden"); - } -} -function getActiveOrFocusedElement() { - let curRoot = document; - let curActiveOrFocused = curRoot.activeElement || curRoot.querySelector(":focus"); - while (curActiveOrFocused?.shadowRoot) { - curRoot = curActiveOrFocused.shadowRoot; - curActiveOrFocused = curRoot.activeElement || curRoot.querySelector(":focus"); - } - return curActiveOrFocused; -} -function apiPageLayoutToViewerModes(layout) { - let scrollMode = ScrollMode.VERTICAL, - spreadMode = SpreadMode.NONE; - switch (layout) { - case "SinglePage": - scrollMode = ScrollMode.PAGE; - break; - case "OneColumn": - break; - case "TwoPageLeft": - scrollMode = ScrollMode.PAGE; - case "TwoColumnLeft": - spreadMode = SpreadMode.ODD; - break; - case "TwoPageRight": - scrollMode = ScrollMode.PAGE; - case "TwoColumnRight": - spreadMode = SpreadMode.EVEN; - break; - } - return { - scrollMode, - spreadMode - }; -} -function apiPageModeToSidebarView(mode) { - switch (mode) { - case "UseNone": - return SidebarView.NONE; - case "UseThumbs": - return SidebarView.THUMBS; - case "UseOutlines": - return SidebarView.OUTLINE; - case "UseAttachments": - return SidebarView.ATTACHMENTS; - case "UseOC": - return SidebarView.LAYERS; - } - return SidebarView.NONE; -} -function toggleCheckedBtn(button, toggle, view = null) { - button.classList.toggle("toggled", toggle); - button.setAttribute("aria-checked", toggle); - view?.classList.toggle("hidden", !toggle); -} -function toggleExpandedBtn(button, toggle, view = null) { - button.classList.toggle("toggled", toggle); - button.setAttribute("aria-expanded", toggle); - view?.classList.toggle("hidden", !toggle); -} -const calcRound = function () { - const e = document.createElement("div"); - e.style.width = "round(down, calc(1.6666666666666665 * 792px), 1px)"; - return e.style.width === "calc(1320px)" ? Math.fround : x => x; -}(); - -;// ./web/pdf_find_utils.js -const CharacterType = { - SPACE: 0, - ALPHA_LETTER: 1, - PUNCT: 2, - HAN_LETTER: 3, - KATAKANA_LETTER: 4, - HIRAGANA_LETTER: 5, - HALFWIDTH_KATAKANA_LETTER: 6, - THAI_LETTER: 7 -}; -function isAlphabeticalScript(charCode) { - return charCode < 0x2e80; -} -function isAscii(charCode) { - return (charCode & 0xff80) === 0; -} -function isAsciiAlpha(charCode) { - return charCode >= 0x61 && charCode <= 0x7a || charCode >= 0x41 && charCode <= 0x5a; -} -function isAsciiDigit(charCode) { - return charCode >= 0x30 && charCode <= 0x39; -} -function isAsciiSpace(charCode) { - return charCode === 0x20 || charCode === 0x09 || charCode === 0x0d || charCode === 0x0a; -} -function isHan(charCode) { - return charCode >= 0x3400 && charCode <= 0x9fff || charCode >= 0xf900 && charCode <= 0xfaff; -} -function isKatakana(charCode) { - return charCode >= 0x30a0 && charCode <= 0x30ff; -} -function isHiragana(charCode) { - return charCode >= 0x3040 && charCode <= 0x309f; -} -function isHalfwidthKatakana(charCode) { - return charCode >= 0xff60 && charCode <= 0xff9f; -} -function isThai(charCode) { - return (charCode & 0xff80) === 0x0e00; -} -function getCharacterType(charCode) { - if (isAlphabeticalScript(charCode)) { - if (isAscii(charCode)) { - if (isAsciiSpace(charCode)) { - return CharacterType.SPACE; - } else if (isAsciiAlpha(charCode) || isAsciiDigit(charCode) || charCode === 0x5f) { - return CharacterType.ALPHA_LETTER; - } - return CharacterType.PUNCT; - } else if (isThai(charCode)) { - return CharacterType.THAI_LETTER; - } else if (charCode === 0xa0) { - return CharacterType.SPACE; - } - return CharacterType.ALPHA_LETTER; - } - if (isHan(charCode)) { - return CharacterType.HAN_LETTER; - } else if (isKatakana(charCode)) { - return CharacterType.KATAKANA_LETTER; - } else if (isHiragana(charCode)) { - return CharacterType.HIRAGANA_LETTER; - } else if (isHalfwidthKatakana(charCode)) { - return CharacterType.HALFWIDTH_KATAKANA_LETTER; - } - return CharacterType.ALPHA_LETTER; -} -let NormalizeWithNFKC; -function getNormalizeWithNFKC() { - NormalizeWithNFKC ||= ` ¨ª¯²-µ¸-º¼-¾IJ-ijĿ-ŀʼnſDŽ-njDZ-dzʰ-ʸ˘-˝ˠ-ˤʹͺ;΄-΅·ϐ-ϖϰ-ϲϴ-ϵϹևٵ-ٸक़-य़ড়-ঢ়য়ਲ਼ਸ਼ਖ਼-ਜ਼ਫ਼ଡ଼-ଢ଼ำຳໜ-ໝ༌གྷཌྷདྷབྷཛྷཀྵჼᴬ-ᴮᴰ-ᴺᴼ-ᵍᵏ-ᵪᵸᶛ-ᶿẚ-ẛάέήίόύώΆ᾽-῁ΈΉ῍-῏ΐΊ῝-῟ΰΎ῭-`ΌΏ´-῾ - ‑‗․-… ″-‴‶-‷‼‾⁇-⁉⁗ ⁰-ⁱ⁴-₎ₐ-ₜ₨℀-℃℅-ℇ℉-ℓℕ-№ℙ-ℝ℠-™ℤΩℨK-ℭℯ-ℱℳ-ℹ℻-⅀ⅅ-ⅉ⅐-ⅿ↉∬-∭∯-∰〈-〉①-⓪⨌⩴-⩶⫝̸ⱼ-ⱽⵯ⺟⻳⼀-⿕ 〶〸-〺゛-゜ゟヿㄱ-ㆎ㆒-㆟㈀-㈞㈠-㉇㉐-㉾㊀-㏿ꚜ-ꚝꝰꟲ-ꟴꟸ-ꟹꭜ-ꭟꭩ豈-嗀塚晴凞-羽蘒諸逸-都飯-舘並-龎ff-stﬓ-ﬗיִײַ-זּטּ-לּמּנּ-סּףּ-פּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-﷼︐-︙︰-﹄﹇-﹒﹔-﹦﹨-﹫ﹰ-ﹲﹴﹶ-ﻼ!-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ¢-₩`; - return NormalizeWithNFKC; -} - -;// ./web/pdf_find_controller.js - - -const FindState = { - FOUND: 0, - NOT_FOUND: 1, - WRAPPED: 2, - PENDING: 3 -}; -const FIND_TIMEOUT = 250; -const MATCH_SCROLL_OFFSET_TOP = -50; -const MATCH_SCROLL_OFFSET_LEFT = -400; -const CHARACTERS_TO_NORMALIZE = { - "\u2010": "-", - "\u2018": "'", - "\u2019": "'", - "\u201A": "'", - "\u201B": "'", - "\u201C": '"', - "\u201D": '"', - "\u201E": '"', - "\u201F": '"', - "\u00BC": "1/4", - "\u00BD": "1/2", - "\u00BE": "3/4" -}; -const DIACRITICS_EXCEPTION = new Set([0x3099, 0x309a, 0x094d, 0x09cd, 0x0a4d, 0x0acd, 0x0b4d, 0x0bcd, 0x0c4d, 0x0ccd, 0x0d3b, 0x0d3c, 0x0d4d, 0x0dca, 0x0e3a, 0x0eba, 0x0f84, 0x1039, 0x103a, 0x1714, 0x1734, 0x17d2, 0x1a60, 0x1b44, 0x1baa, 0x1bab, 0x1bf2, 0x1bf3, 0x2d7f, 0xa806, 0xa82c, 0xa8c4, 0xa953, 0xa9c0, 0xaaf6, 0xabed, 0x0c56, 0x0f71, 0x0f72, 0x0f7a, 0x0f7b, 0x0f7c, 0x0f7d, 0x0f80, 0x0f74]); -let DIACRITICS_EXCEPTION_STR; -const DIACRITICS_REG_EXP = /\p{M}+/gu; -const SPECIAL_CHARS_REG_EXP = /([.*+?^${}()|[\]\\])|(\p{P})|(\s+)|(\p{M})|(\p{L})/gu; -const NOT_DIACRITIC_FROM_END_REG_EXP = /([^\p{M}])\p{M}*$/u; -const NOT_DIACRITIC_FROM_START_REG_EXP = /^\p{M}*([^\p{M}])/u; -const SYLLABLES_REG_EXP = /[\uAC00-\uD7AF\uFA6C\uFACF-\uFAD1\uFAD5-\uFAD7]+/g; -const SYLLABLES_LENGTHS = new Map(); -const FIRST_CHAR_SYLLABLES_REG_EXP = "[\\u1100-\\u1112\\ud7a4-\\ud7af\\ud84a\\ud84c\\ud850\\ud854\\ud857\\ud85f]"; -const NFKC_CHARS_TO_NORMALIZE = new Map(); -let noSyllablesRegExp = null; -let withSyllablesRegExp = null; -function normalize(text) { - const syllablePositions = []; - let m; - while ((m = SYLLABLES_REG_EXP.exec(text)) !== null) { - let { - index - } = m; - for (const char of m[0]) { - let len = SYLLABLES_LENGTHS.get(char); - if (!len) { - len = char.normalize("NFD").length; - SYLLABLES_LENGTHS.set(char, len); - } - syllablePositions.push([len, index++]); - } - } - let normalizationRegex; - if (syllablePositions.length === 0 && noSyllablesRegExp) { - normalizationRegex = noSyllablesRegExp; - } else if (syllablePositions.length > 0 && withSyllablesRegExp) { - normalizationRegex = withSyllablesRegExp; - } else { - const replace = Object.keys(CHARACTERS_TO_NORMALIZE).join(""); - const toNormalizeWithNFKC = getNormalizeWithNFKC(); - const CJK = "(?:\\p{Ideographic}|[\u3040-\u30FF])"; - const HKDiacritics = "(?:\u3099|\u309A)"; - const CompoundWord = "\\p{Ll}-\\n\\p{Lu}"; - const regexp = `([${replace}])|([${toNormalizeWithNFKC}])|(${HKDiacritics}\\n)|(\\p{M}+(?:-\\n)?)|(${CompoundWord})|(\\S-\\n)|(${CJK}\\n)|(\\n)`; - if (syllablePositions.length === 0) { - normalizationRegex = noSyllablesRegExp = new RegExp(regexp + "|(\\u0000)", "gum"); - } else { - normalizationRegex = withSyllablesRegExp = new RegExp(regexp + `|(${FIRST_CHAR_SYLLABLES_REG_EXP})`, "gum"); - } - } - const rawDiacriticsPositions = []; - while ((m = DIACRITICS_REG_EXP.exec(text)) !== null) { - rawDiacriticsPositions.push([m[0].length, m.index]); - } - let normalized = text.normalize("NFD"); - const positions = [0, 0]; - let rawDiacriticsIndex = 0; - let syllableIndex = 0; - let shift = 0; - let shiftOrigin = 0; - let eol = 0; - let hasDiacritics = false; - normalized = normalized.replace(normalizationRegex, (match, p1, p2, p3, p4, p5, p6, p7, p8, p9, i) => { - i -= shiftOrigin; - if (p1) { - const replacement = CHARACTERS_TO_NORMALIZE[p1]; - const jj = replacement.length; - for (let j = 1; j < jj; j++) { - positions.push(i - shift + j, shift - j); - } - shift -= jj - 1; - return replacement; - } - if (p2) { - let replacement = NFKC_CHARS_TO_NORMALIZE.get(p2); - if (!replacement) { - replacement = p2.normalize("NFKC"); - NFKC_CHARS_TO_NORMALIZE.set(p2, replacement); - } - const jj = replacement.length; - for (let j = 1; j < jj; j++) { - positions.push(i - shift + j, shift - j); - } - shift -= jj - 1; - return replacement; - } - if (p3) { - hasDiacritics = true; - if (i + eol === rawDiacriticsPositions[rawDiacriticsIndex]?.[1]) { - ++rawDiacriticsIndex; - } else { - positions.push(i - 1 - shift + 1, shift - 1); - shift -= 1; - shiftOrigin += 1; - } - positions.push(i - shift + 1, shift); - shiftOrigin += 1; - eol += 1; - return p3.charAt(0); - } - if (p4) { - const hasTrailingDashEOL = p4.endsWith("\n"); - const len = hasTrailingDashEOL ? p4.length - 2 : p4.length; - hasDiacritics = true; - let jj = len; - if (i + eol === rawDiacriticsPositions[rawDiacriticsIndex]?.[1]) { - jj -= rawDiacriticsPositions[rawDiacriticsIndex][0]; - ++rawDiacriticsIndex; - } - for (let j = 1; j <= jj; j++) { - positions.push(i - 1 - shift + j, shift - j); - } - shift -= jj; - shiftOrigin += jj; - if (hasTrailingDashEOL) { - i += len - 1; - positions.push(i - shift + 1, 1 + shift); - shift += 1; - shiftOrigin += 1; - eol += 1; - return p4.slice(0, len); - } - return p4; - } - if (p5) { - shiftOrigin += 1; - eol += 1; - return p5.replace("\n", ""); - } - if (p6) { - const len = p6.length - 2; - positions.push(i - shift + len, 1 + shift); - shift += 1; - shiftOrigin += 1; - eol += 1; - return p6.slice(0, -2); - } - if (p7) { - const len = p7.length - 1; - positions.push(i - shift + len, shift); - shiftOrigin += 1; - eol += 1; - return p7.slice(0, -1); - } - if (p8) { - positions.push(i - shift + 1, shift - 1); - shift -= 1; - shiftOrigin += 1; - eol += 1; - return " "; - } - if (i + eol === syllablePositions[syllableIndex]?.[1]) { - const newCharLen = syllablePositions[syllableIndex][0] - 1; - ++syllableIndex; - for (let j = 1; j <= newCharLen; j++) { - positions.push(i - (shift - j), shift - j); - } - shift -= newCharLen; - shiftOrigin += newCharLen; - } - return p9; - }); - positions.push(normalized.length, shift); - const starts = new Uint32Array(positions.length >> 1); - const shifts = new Int32Array(positions.length >> 1); - for (let i = 0, ii = positions.length; i < ii; i += 2) { - starts[i >> 1] = positions[i]; - shifts[i >> 1] = positions[i + 1]; - } - return [normalized, [starts, shifts], hasDiacritics]; -} -function getOriginalIndex(diffs, pos, len) { - if (!diffs) { - return [pos, len]; - } - const [starts, shifts] = diffs; - const start = pos; - const end = pos + len - 1; - let i = binarySearchFirstItem(starts, x => x >= start); - if (starts[i] > start) { - --i; - } - let j = binarySearchFirstItem(starts, x => x >= end, i); - if (starts[j] > end) { - --j; - } - const oldStart = start + shifts[i]; - const oldEnd = end + shifts[j]; - const oldLen = oldEnd + 1 - oldStart; - return [oldStart, oldLen]; -} -class PDFFindController { - #state = null; - #updateMatchesCountOnProgress = true; - #visitedPagesCount = 0; - constructor({ - linkService, - eventBus, - updateMatchesCountOnProgress = true - }) { - this._linkService = linkService; - this._eventBus = eventBus; - this.#updateMatchesCountOnProgress = updateMatchesCountOnProgress; - this.onIsPageVisible = null; - this.#reset(); - eventBus._on("find", this.#onFind.bind(this)); - eventBus._on("findbarclose", this.#onFindBarClose.bind(this)); - } - get highlightMatches() { - return this._highlightMatches; - } - get pageMatches() { - return this._pageMatches; - } - get pageMatchesLength() { - return this._pageMatchesLength; - } - get selected() { - return this._selected; - } - get state() { - return this.#state; - } - setDocument(pdfDocument) { - if (this._pdfDocument) { - this.#reset(); - } - if (!pdfDocument) { - return; - } - this._pdfDocument = pdfDocument; - this._firstPageCapability.resolve(); - } - #onFind(state) { - if (!state) { - return; - } - const pdfDocument = this._pdfDocument; - const { - type - } = state; - if (this.#state === null || this.#shouldDirtyMatch(state)) { - this._dirtyMatch = true; - } - this.#state = state; - if (type !== "highlightallchange") { - this.#updateUIState(FindState.PENDING); - } - this._firstPageCapability.promise.then(() => { - if (!this._pdfDocument || pdfDocument && this._pdfDocument !== pdfDocument) { - return; - } - this.#extractText(); - const findbarClosed = !this._highlightMatches; - const pendingTimeout = !!this._findTimeout; - if (this._findTimeout) { - clearTimeout(this._findTimeout); - this._findTimeout = null; - } - if (!type) { - this._findTimeout = setTimeout(() => { - this.#nextMatch(); - this._findTimeout = null; - }, FIND_TIMEOUT); - } else if (this._dirtyMatch) { - this.#nextMatch(); - } else if (type === "again") { - this.#nextMatch(); - if (findbarClosed && this.#state.highlightAll) { - this.#updateAllPages(); - } - } else if (type === "highlightallchange") { - if (pendingTimeout) { - this.#nextMatch(); - } else { - this._highlightMatches = true; - } - this.#updateAllPages(); - } else { - this.#nextMatch(); - } - }); - } - scrollMatchIntoView({ - element = null, - selectedLeft = 0, - pageIndex = -1, - matchIndex = -1 - }) { - if (!this._scrollMatches || !element) { - return; - } else if (matchIndex === -1 || matchIndex !== this._selected.matchIdx) { - return; - } else if (pageIndex === -1 || pageIndex !== this._selected.pageIdx) { - return; - } - this._scrollMatches = false; - const spot = { - top: MATCH_SCROLL_OFFSET_TOP, - left: selectedLeft + MATCH_SCROLL_OFFSET_LEFT - }; - scrollIntoView(element, spot, true); - } - #reset() { - this._highlightMatches = false; - this._scrollMatches = false; - this._pdfDocument = null; - this._pageMatches = []; - this._pageMatchesLength = []; - this.#visitedPagesCount = 0; - this.#state = null; - this._selected = { - pageIdx: -1, - matchIdx: -1 - }; - this._offset = { - pageIdx: null, - matchIdx: null, - wrapped: false - }; - this._extractTextPromises = []; - this._pageContents = []; - this._pageDiffs = []; - this._hasDiacritics = []; - this._matchesCountTotal = 0; - this._pagesToSearch = null; - this._pendingFindMatches = new Set(); - this._resumePageIdx = null; - this._dirtyMatch = false; - clearTimeout(this._findTimeout); - this._findTimeout = null; - this._firstPageCapability = Promise.withResolvers(); - } - get #query() { - const { - query - } = this.#state; - if (typeof query === "string") { - if (query !== this._rawQuery) { - this._rawQuery = query; - [this._normalizedQuery] = normalize(query); - } - return this._normalizedQuery; - } - return (query || []).filter(q => !!q).map(q => normalize(q)[0]); - } - #shouldDirtyMatch(state) { - const newQuery = state.query, - prevQuery = this.#state.query; - const newType = typeof newQuery, - prevType = typeof prevQuery; - if (newType !== prevType) { - return true; - } - if (newType === "string") { - if (newQuery !== prevQuery) { - return true; - } - } else if (JSON.stringify(newQuery) !== JSON.stringify(prevQuery)) { - return true; - } - switch (state.type) { - case "again": - const pageNumber = this._selected.pageIdx + 1; - const linkService = this._linkService; - return pageNumber >= 1 && pageNumber <= linkService.pagesCount && pageNumber !== linkService.page && !(this.onIsPageVisible?.(pageNumber) ?? true); - case "highlightallchange": - return false; - } - return true; - } - #isEntireWord(content, startIdx, length) { - let match = content.slice(0, startIdx).match(NOT_DIACRITIC_FROM_END_REG_EXP); - if (match) { - const first = content.charCodeAt(startIdx); - const limit = match[1].charCodeAt(0); - if (getCharacterType(first) === getCharacterType(limit)) { - return false; - } - } - match = content.slice(startIdx + length).match(NOT_DIACRITIC_FROM_START_REG_EXP); - if (match) { - const last = content.charCodeAt(startIdx + length - 1); - const limit = match[1].charCodeAt(0); - if (getCharacterType(last) === getCharacterType(limit)) { - return false; - } - } - return true; - } - #convertToRegExpString(query, hasDiacritics) { - const { - matchDiacritics - } = this.#state; - let isUnicode = false; - query = query.replaceAll(SPECIAL_CHARS_REG_EXP, (match, p1, p2, p3, p4, p5) => { - if (p1) { - return `[ ]*\\${p1}[ ]*`; - } - if (p2) { - return `[ ]*${p2}[ ]*`; - } - if (p3) { - return "[ ]+"; - } - if (matchDiacritics) { - return p4 || p5; - } - if (p4) { - return DIACRITICS_EXCEPTION.has(p4.charCodeAt(0)) ? p4 : ""; - } - if (hasDiacritics) { - isUnicode = true; - return `${p5}\\p{M}*`; - } - return p5; - }); - const trailingSpaces = "[ ]*"; - if (query.endsWith(trailingSpaces)) { - query = query.slice(0, query.length - trailingSpaces.length); - } - if (matchDiacritics) { - if (hasDiacritics) { - DIACRITICS_EXCEPTION_STR ||= String.fromCharCode(...DIACRITICS_EXCEPTION); - isUnicode = true; - query = `${query}(?=[${DIACRITICS_EXCEPTION_STR}]|[^\\p{M}]|$)`; - } - } - return [isUnicode, query]; - } - #calculateMatch(pageIndex) { - const query = this.#query; - if (query.length === 0) { - return; - } - const pageContent = this._pageContents[pageIndex]; - const matcherResult = this.match(query, pageContent, pageIndex); - const matches = this._pageMatches[pageIndex] = []; - const matchesLength = this._pageMatchesLength[pageIndex] = []; - const diffs = this._pageDiffs[pageIndex]; - matcherResult?.forEach(({ - index, - length - }) => { - const [matchPos, matchLen] = getOriginalIndex(diffs, index, length); - if (matchLen) { - matches.push(matchPos); - matchesLength.push(matchLen); - } - }); - if (this.#state.highlightAll) { - this.#updatePage(pageIndex); - } - if (this._resumePageIdx === pageIndex) { - this._resumePageIdx = null; - this.#nextPageMatch(); - } - const pageMatchesCount = matches.length; - this._matchesCountTotal += pageMatchesCount; - if (this.#updateMatchesCountOnProgress) { - if (pageMatchesCount > 0) { - this.#updateUIResultsCount(); - } - } else if (++this.#visitedPagesCount === this._linkService.pagesCount) { - this.#updateUIResultsCount(); - } - } - match(query, pageContent, pageIndex) { - const hasDiacritics = this._hasDiacritics[pageIndex]; - let isUnicode = false; - if (typeof query === "string") { - [isUnicode, query] = this.#convertToRegExpString(query, hasDiacritics); - } else { - query = query.sort().reverse().map(q => { - const [isUnicodePart, queryPart] = this.#convertToRegExpString(q, hasDiacritics); - isUnicode ||= isUnicodePart; - return `(${queryPart})`; - }).join("|"); - } - if (!query) { - return undefined; - } - const { - caseSensitive, - entireWord - } = this.#state; - const flags = `g${isUnicode ? "u" : ""}${caseSensitive ? "" : "i"}`; - query = new RegExp(query, flags); - const matches = []; - let match; - while ((match = query.exec(pageContent)) !== null) { - if (entireWord && !this.#isEntireWord(pageContent, match.index, match[0].length)) { - continue; - } - matches.push({ - index: match.index, - length: match[0].length - }); - } - return matches; - } - #extractText() { - if (this._extractTextPromises.length > 0) { - return; - } - let deferred = Promise.resolve(); - const textOptions = { - disableNormalization: true - }; - for (let i = 0, ii = this._linkService.pagesCount; i < ii; i++) { - const { - promise, - resolve - } = Promise.withResolvers(); - this._extractTextPromises[i] = promise; - deferred = deferred.then(() => { - return this._pdfDocument.getPage(i + 1).then(pdfPage => pdfPage.getTextContent(textOptions)).then(textContent => { - const strBuf = []; - for (const textItem of textContent.items) { - strBuf.push(textItem.str); - if (textItem.hasEOL) { - strBuf.push("\n"); - } - } - [this._pageContents[i], this._pageDiffs[i], this._hasDiacritics[i]] = normalize(strBuf.join("")); - resolve(); - }, reason => { - console.error(`Unable to get text content for page ${i + 1}`, reason); - this._pageContents[i] = ""; - this._pageDiffs[i] = null; - this._hasDiacritics[i] = false; - resolve(); - }); - }); - } - } - #updatePage(index) { - if (this._scrollMatches && this._selected.pageIdx === index) { - this._linkService.page = index + 1; - } - this._eventBus.dispatch("updatetextlayermatches", { - source: this, - pageIndex: index - }); - } - #updateAllPages() { - this._eventBus.dispatch("updatetextlayermatches", { - source: this, - pageIndex: -1 - }); - } - #nextMatch() { - const previous = this.#state.findPrevious; - const currentPageIndex = this._linkService.page - 1; - const numPages = this._linkService.pagesCount; - this._highlightMatches = true; - if (this._dirtyMatch) { - this._dirtyMatch = false; - this._selected.pageIdx = this._selected.matchIdx = -1; - this._offset.pageIdx = currentPageIndex; - this._offset.matchIdx = null; - this._offset.wrapped = false; - this._resumePageIdx = null; - this._pageMatches.length = 0; - this._pageMatchesLength.length = 0; - this.#visitedPagesCount = 0; - this._matchesCountTotal = 0; - this.#updateAllPages(); - for (let i = 0; i < numPages; i++) { - if (this._pendingFindMatches.has(i)) { - continue; - } - this._pendingFindMatches.add(i); - this._extractTextPromises[i].then(() => { - this._pendingFindMatches.delete(i); - this.#calculateMatch(i); - }); - } - } - const query = this.#query; - if (query.length === 0) { - this.#updateUIState(FindState.FOUND); - return; - } - if (this._resumePageIdx) { - return; - } - const offset = this._offset; - this._pagesToSearch = numPages; - if (offset.matchIdx !== null) { - const numPageMatches = this._pageMatches[offset.pageIdx].length; - if (!previous && offset.matchIdx + 1 < numPageMatches || previous && offset.matchIdx > 0) { - offset.matchIdx = previous ? offset.matchIdx - 1 : offset.matchIdx + 1; - this.#updateMatch(true); - return; - } - this.#advanceOffsetPage(previous); - } - this.#nextPageMatch(); - } - #matchesReady(matches) { - const offset = this._offset; - const numMatches = matches.length; - const previous = this.#state.findPrevious; - if (numMatches) { - offset.matchIdx = previous ? numMatches - 1 : 0; - this.#updateMatch(true); - return true; - } - this.#advanceOffsetPage(previous); - if (offset.wrapped) { - offset.matchIdx = null; - if (this._pagesToSearch < 0) { - this.#updateMatch(false); - return true; - } - } - return false; - } - #nextPageMatch() { - if (this._resumePageIdx !== null) { - console.error("There can only be one pending page."); - } - let matches = null; - do { - const pageIdx = this._offset.pageIdx; - matches = this._pageMatches[pageIdx]; - if (!matches) { - this._resumePageIdx = pageIdx; - break; - } - } while (!this.#matchesReady(matches)); - } - #advanceOffsetPage(previous) { - const offset = this._offset; - const numPages = this._linkService.pagesCount; - offset.pageIdx = previous ? offset.pageIdx - 1 : offset.pageIdx + 1; - offset.matchIdx = null; - this._pagesToSearch--; - if (offset.pageIdx >= numPages || offset.pageIdx < 0) { - offset.pageIdx = previous ? numPages - 1 : 0; - offset.wrapped = true; - } - } - #updateMatch(found = false) { - let state = FindState.NOT_FOUND; - const wrapped = this._offset.wrapped; - this._offset.wrapped = false; - if (found) { - const previousPage = this._selected.pageIdx; - this._selected.pageIdx = this._offset.pageIdx; - this._selected.matchIdx = this._offset.matchIdx; - state = wrapped ? FindState.WRAPPED : FindState.FOUND; - if (previousPage !== -1 && previousPage !== this._selected.pageIdx) { - this.#updatePage(previousPage); - } - } - this.#updateUIState(state, this.#state.findPrevious); - if (this._selected.pageIdx !== -1) { - this._scrollMatches = true; - this.#updatePage(this._selected.pageIdx); - } - } - #onFindBarClose(evt) { - const pdfDocument = this._pdfDocument; - this._firstPageCapability.promise.then(() => { - if (!this._pdfDocument || pdfDocument && this._pdfDocument !== pdfDocument) { - return; - } - if (this._findTimeout) { - clearTimeout(this._findTimeout); - this._findTimeout = null; - } - if (this._resumePageIdx) { - this._resumePageIdx = null; - this._dirtyMatch = true; - } - this.#updateUIState(FindState.FOUND); - this._highlightMatches = false; - this.#updateAllPages(); - }); - } - #requestMatchesCount() { - const { - pageIdx, - matchIdx - } = this._selected; - let current = 0, - total = this._matchesCountTotal; - if (matchIdx !== -1) { - for (let i = 0; i < pageIdx; i++) { - current += this._pageMatches[i]?.length || 0; - } - current += matchIdx + 1; - } - if (current < 1 || current > total) { - current = total = 0; - } - return { - current, - total - }; - } - #updateUIResultsCount() { - this._eventBus.dispatch("updatefindmatchescount", { - source: this, - matchesCount: this.#requestMatchesCount() - }); - } - #updateUIState(state, previous = false) { - if (!this.#updateMatchesCountOnProgress && (this.#visitedPagesCount !== this._linkService.pagesCount || state === FindState.PENDING)) { - return; - } - this._eventBus.dispatch("updatefindcontrolstate", { - source: this, - state, - previous, - entireWord: this.#state?.entireWord ?? null, - matchesCount: this.#requestMatchesCount(), - rawQuery: this.#state?.query ?? null - }); - } -} - -;// ./web/pdf_link_service.js - -const DEFAULT_LINK_REL = "noopener noreferrer nofollow"; -const LinkTarget = { - NONE: 0, - SELF: 1, - BLANK: 2, - PARENT: 3, - TOP: 4 -}; -class PDFLinkService { - externalLinkEnabled = true; - constructor({ - eventBus, - externalLinkTarget = null, - externalLinkRel = null, - ignoreDestinationZoom = false - } = {}) { - this.eventBus = eventBus; - this.externalLinkTarget = externalLinkTarget; - this.externalLinkRel = externalLinkRel; - this._ignoreDestinationZoom = ignoreDestinationZoom; - this.baseUrl = null; - this.pdfDocument = null; - this.pdfViewer = null; - this.pdfHistory = null; - } - setDocument(pdfDocument, baseUrl = null) { - this.baseUrl = baseUrl; - this.pdfDocument = pdfDocument; - } - setViewer(pdfViewer) { - this.pdfViewer = pdfViewer; - } - setHistory(pdfHistory) { - this.pdfHistory = pdfHistory; - } - get pagesCount() { - return this.pdfDocument ? this.pdfDocument.numPages : 0; - } - get page() { - return this.pdfDocument ? this.pdfViewer.currentPageNumber : 1; - } - set page(value) { - if (this.pdfDocument) { - this.pdfViewer.currentPageNumber = value; - } - } - get rotation() { - return this.pdfDocument ? this.pdfViewer.pagesRotation : 0; - } - set rotation(value) { - if (this.pdfDocument) { - this.pdfViewer.pagesRotation = value; - } - } - get isInPresentationMode() { - return this.pdfDocument ? this.pdfViewer.isInPresentationMode : false; - } - async goToDestination(dest) { - if (!this.pdfDocument) { - return; - } - let namedDest, explicitDest, pageNumber; - if (typeof dest === "string") { - namedDest = dest; - explicitDest = await this.pdfDocument.getDestination(dest); - } else { - namedDest = null; - explicitDest = await dest; - } - if (!Array.isArray(explicitDest)) { - console.error(`goToDestination: "${explicitDest}" is not a valid destination array, for dest="${dest}".`); - return; - } - const [destRef] = explicitDest; - if (destRef && typeof destRef === "object") { - pageNumber = this.pdfDocument.cachedPageNumber(destRef); - if (!pageNumber) { - try { - pageNumber = (await this.pdfDocument.getPageIndex(destRef)) + 1; - } catch { - console.error(`goToDestination: "${destRef}" is not a valid page reference, for dest="${dest}".`); - return; - } - } - } else if (Number.isInteger(destRef)) { - pageNumber = destRef + 1; - } - if (!pageNumber || pageNumber < 1 || pageNumber > this.pagesCount) { - console.error(`goToDestination: "${pageNumber}" is not a valid page number, for dest="${dest}".`); - return; - } - if (this.pdfHistory) { - this.pdfHistory.pushCurrentPosition(); - this.pdfHistory.push({ - namedDest, - explicitDest, - pageNumber - }); - } - this.pdfViewer.scrollPageIntoView({ - pageNumber, - destArray: explicitDest, - ignoreDestinationZoom: this._ignoreDestinationZoom - }); - } - goToPage(val) { - if (!this.pdfDocument) { - return; - } - const pageNumber = typeof val === "string" && this.pdfViewer.pageLabelToPageNumber(val) || val | 0; - if (!(Number.isInteger(pageNumber) && pageNumber > 0 && pageNumber <= this.pagesCount)) { - console.error(`PDFLinkService.goToPage: "${val}" is not a valid page.`); - return; - } - if (this.pdfHistory) { - this.pdfHistory.pushCurrentPosition(); - this.pdfHistory.pushPage(pageNumber); - } - this.pdfViewer.scrollPageIntoView({ - pageNumber - }); - } - addLinkAttributes(link, url, newWindow = false) { - if (!url || typeof url !== "string") { - throw new Error('A valid "url" parameter must provided.'); - } - const target = newWindow ? LinkTarget.BLANK : this.externalLinkTarget, - rel = this.externalLinkRel; - if (this.externalLinkEnabled) { - link.href = link.title = url; - } else { - link.href = ""; - link.title = `Disabled: ${url}`; - link.onclick = () => false; - } - let targetStr = ""; - switch (target) { - case LinkTarget.NONE: - break; - case LinkTarget.SELF: - targetStr = "_self"; - break; - case LinkTarget.BLANK: - targetStr = "_blank"; - break; - case LinkTarget.PARENT: - targetStr = "_parent"; - break; - case LinkTarget.TOP: - targetStr = "_top"; - break; - } - link.target = targetStr; - link.rel = typeof rel === "string" ? rel : DEFAULT_LINK_REL; - } - getDestinationHash(dest) { - if (typeof dest === "string") { - if (dest.length > 0) { - return this.getAnchorUrl("#" + escape(dest)); - } - } else if (Array.isArray(dest)) { - const str = JSON.stringify(dest); - if (str.length > 0) { - return this.getAnchorUrl("#" + escape(str)); - } - } - return this.getAnchorUrl(""); - } - getAnchorUrl(anchor) { - return this.baseUrl ? this.baseUrl + anchor : anchor; - } - setHash(hash) { - if (!this.pdfDocument) { - return; - } - let pageNumber, dest; - if (hash.includes("=")) { - const params = parseQueryString(hash); - if (params.has("search")) { - const query = params.get("search").replaceAll('"', ""), - phrase = params.get("phrase") === "true"; - this.eventBus.dispatch("findfromurlhash", { - source: this, - query: phrase ? query : query.match(/\S+/g) - }); - } - if (params.has("page")) { - pageNumber = params.get("page") | 0 || 1; - } - if (params.has("zoom")) { - const zoomArgs = params.get("zoom").split(","); - const zoomArg = zoomArgs[0]; - const zoomArgNumber = parseFloat(zoomArg); - if (!zoomArg.includes("Fit")) { - dest = [null, { - name: "XYZ" - }, zoomArgs.length > 1 ? zoomArgs[1] | 0 : null, zoomArgs.length > 2 ? zoomArgs[2] | 0 : null, zoomArgNumber ? zoomArgNumber / 100 : zoomArg]; - } else if (zoomArg === "Fit" || zoomArg === "FitB") { - dest = [null, { - name: zoomArg - }]; - } else if (zoomArg === "FitH" || zoomArg === "FitBH" || zoomArg === "FitV" || zoomArg === "FitBV") { - dest = [null, { - name: zoomArg - }, zoomArgs.length > 1 ? zoomArgs[1] | 0 : null]; - } else if (zoomArg === "FitR") { - if (zoomArgs.length !== 5) { - console.error('PDFLinkService.setHash: Not enough parameters for "FitR".'); - } else { - dest = [null, { - name: zoomArg - }, zoomArgs[1] | 0, zoomArgs[2] | 0, zoomArgs[3] | 0, zoomArgs[4] | 0]; - } - } else { - console.error(`PDFLinkService.setHash: "${zoomArg}" is not a valid zoom value.`); - } - } - if (dest) { - this.pdfViewer.scrollPageIntoView({ - pageNumber: pageNumber || this.page, - destArray: dest, - allowNegativeOffset: true - }); - } else if (pageNumber) { - this.page = pageNumber; - } - if (params.has("pagemode")) { - this.eventBus.dispatch("pagemode", { - source: this, - mode: params.get("pagemode") - }); - } - if (params.has("nameddest")) { - this.goToDestination(params.get("nameddest")); - } - return; - } - dest = unescape(hash); - try { - dest = JSON.parse(dest); - if (!Array.isArray(dest)) { - dest = dest.toString(); - } - } catch {} - if (typeof dest === "string" || PDFLinkService.#isValidExplicitDest(dest)) { - this.goToDestination(dest); - return; - } - console.error(`PDFLinkService.setHash: "${unescape(hash)}" is not a valid destination.`); - } - executeNamedAction(action) { - if (!this.pdfDocument) { - return; - } - switch (action) { - case "GoBack": - this.pdfHistory?.back(); - break; - case "GoForward": - this.pdfHistory?.forward(); - break; - case "NextPage": - this.pdfViewer.nextPage(); - break; - case "PrevPage": - this.pdfViewer.previousPage(); - break; - case "LastPage": - this.page = this.pagesCount; - break; - case "FirstPage": - this.page = 1; - break; - default: - break; - } - this.eventBus.dispatch("namedaction", { - source: this, - action - }); - } - async executeSetOCGState(action) { - if (!this.pdfDocument) { - return; - } - const pdfDocument = this.pdfDocument, - optionalContentConfig = await this.pdfViewer.optionalContentConfigPromise; - if (pdfDocument !== this.pdfDocument) { - return; - } - optionalContentConfig.setOCGState(action); - this.pdfViewer.optionalContentConfigPromise = Promise.resolve(optionalContentConfig); - } - static #isValidExplicitDest(dest) { - if (!Array.isArray(dest) || dest.length < 2) { - return false; - } - const [page, zoom, ...args] = dest; - if (!(typeof page === "object" && Number.isInteger(page?.num) && Number.isInteger(page?.gen)) && !Number.isInteger(page)) { - return false; - } - if (!(typeof zoom === "object" && typeof zoom?.name === "string")) { - return false; - } - const argsLen = args.length; - let allowNull = true; - switch (zoom.name) { - case "XYZ": - if (argsLen < 2 || argsLen > 3) { - return false; - } - break; - case "Fit": - case "FitB": - return argsLen === 0; - case "FitH": - case "FitBH": - case "FitV": - case "FitBV": - if (argsLen > 1) { - return false; - } - break; - case "FitR": - if (argsLen !== 4) { - return false; - } - allowNull = false; - break; - default: - return false; - } - for (const arg of args) { - if (!(typeof arg === "number" || allowNull && arg === null)) { - return false; - } - } - return true; - } -} -class SimpleLinkService extends PDFLinkService { - setDocument(pdfDocument, baseUrl = null) {} -} - -;// ./web/pdfjs.js -const { - AbortException, - AnnotationEditorLayer, - AnnotationEditorParamsType, - AnnotationEditorType, - AnnotationEditorUIManager, - AnnotationLayer, - AnnotationMode, - build, - ColorPicker, - createValidAbsoluteUrl, - DOMSVGFactory, - DrawLayer, - FeatureTest, - fetchData, - getDocument, - getFilenameFromUrl, - getPdfFilenameFromUrl, - getXfaPageViewport, - GlobalWorkerOptions, - ImageKind, - InvalidPDFException, - isDataScheme, - isPdfFile, - MissingPDFException, - noContextMenu, - normalizeUnicode, - OPS, - OutputScale, - PasswordResponses, - PDFDataRangeTransport, - PDFDateString, - PDFWorker, - PermissionFlag, - PixelsPerInch, - RenderingCancelledException, - setLayerDimensions, - shadow, - stopEvent, - TextLayer, - TouchManager, - UnexpectedResponseException, - Util, - VerbosityLevel, - version, - XfaLayer -} = globalThis.pdfjsLib; - -;// ./web/annotation_layer_builder.js - - -class AnnotationLayerBuilder { - #onAppend = null; - #eventAbortController = null; - constructor({ - pdfPage, - linkService, - downloadManager, - annotationStorage = null, - imageResourcesPath = "", - renderForms = true, - enableScripting = false, - hasJSActionsPromise = null, - fieldObjectsPromise = null, - annotationCanvasMap = null, - accessibilityManager = null, - annotationEditorUIManager = null, - onAppend = null - }) { - this.pdfPage = pdfPage; - this.linkService = linkService; - this.downloadManager = downloadManager; - this.imageResourcesPath = imageResourcesPath; - this.renderForms = renderForms; - this.annotationStorage = annotationStorage; - this.enableScripting = enableScripting; - this._hasJSActionsPromise = hasJSActionsPromise || Promise.resolve(false); - this._fieldObjectsPromise = fieldObjectsPromise || Promise.resolve(null); - this._annotationCanvasMap = annotationCanvasMap; - this._accessibilityManager = accessibilityManager; - this._annotationEditorUIManager = annotationEditorUIManager; - this.#onAppend = onAppend; - this.annotationLayer = null; - this.div = null; - this._cancelled = false; - this._eventBus = linkService.eventBus; - } - async render(viewport, options, intent = "display") { - if (this.div) { - if (this._cancelled || !this.annotationLayer) { - return; - } - this.annotationLayer.update({ - viewport: viewport.clone({ - dontFlip: true - }) - }); - return; - } - const [annotations, hasJSActions, fieldObjects] = await Promise.all([this.pdfPage.getAnnotations({ - intent - }), this._hasJSActionsPromise, this._fieldObjectsPromise]); - if (this._cancelled) { - return; - } - const div = this.div = document.createElement("div"); - div.className = "annotationLayer"; - this.#onAppend?.(div); - if (annotations.length === 0) { - this.hide(); - return; - } - this.annotationLayer = new AnnotationLayer({ - div, - accessibilityManager: this._accessibilityManager, - annotationCanvasMap: this._annotationCanvasMap, - annotationEditorUIManager: this._annotationEditorUIManager, - page: this.pdfPage, - viewport: viewport.clone({ - dontFlip: true - }), - structTreeLayer: options?.structTreeLayer || null - }); - await this.annotationLayer.render({ - annotations, - imageResourcesPath: this.imageResourcesPath, - renderForms: this.renderForms, - linkService: this.linkService, - downloadManager: this.downloadManager, - annotationStorage: this.annotationStorage, - enableScripting: this.enableScripting, - hasJSActions, - fieldObjects - }); - if (this.linkService.isInPresentationMode) { - this.#updatePresentationModeState(PresentationModeState.FULLSCREEN); - } - if (!this.#eventAbortController) { - this.#eventAbortController = new AbortController(); - this._eventBus?._on("presentationmodechanged", evt => { - this.#updatePresentationModeState(evt.state); - }, { - signal: this.#eventAbortController.signal - }); - } - } - cancel() { - this._cancelled = true; - this.#eventAbortController?.abort(); - this.#eventAbortController = null; - } - hide() { - if (!this.div) { - return; - } - this.div.hidden = true; - } - hasEditableAnnotations() { - return !!this.annotationLayer?.hasEditableAnnotations(); - } - #updatePresentationModeState(state) { - if (!this.div) { - return; - } - let disableFormElements = false; - switch (state) { - case PresentationModeState.FULLSCREEN: - disableFormElements = true; - break; - case PresentationModeState.NORMAL: - break; - default: - return; - } - for (const section of this.div.childNodes) { - if (section.hasAttribute("data-internal-link")) { - continue; - } - section.inert = disableFormElements; - } - } -} - -;// ./web/download_manager.js - -function download(blobUrl, filename) { - const a = document.createElement("a"); - if (!a.click) { - throw new Error('DownloadManager: "a.click()" is not supported.'); - } - a.href = blobUrl; - a.target = "_parent"; - if ("download" in a) { - a.download = filename; - } - (document.body || document.documentElement).append(a); - a.click(); - a.remove(); -} -class DownloadManager { - #openBlobUrls = new WeakMap(); - downloadData(data, filename, contentType) { - const blobUrl = URL.createObjectURL(new Blob([data], { - type: contentType - })); - download(blobUrl, filename); - } - openOrDownloadData(data, filename, dest = null) { - const isPdfData = isPdfFile(filename); - const contentType = isPdfData ? "application/pdf" : ""; - this.downloadData(data, filename, contentType); - return false; - } - download(data, url, filename) { - let blobUrl; - if (data) { - blobUrl = URL.createObjectURL(new Blob([data], { - type: "application/pdf" - })); - } else { - if (!createValidAbsoluteUrl(url, "http://example.com")) { - console.error(`download - not a valid URL: ${url}`); - return; - } - blobUrl = url + "#pdfjs.action=download"; - } - download(blobUrl, filename); - } -} - -;// ./web/event_utils.js -const WaitOnType = { - EVENT: "event", - TIMEOUT: "timeout" -}; -async function waitOnEventOrTimeout({ - target, - name, - delay = 0 -}) { - if (typeof target !== "object" || !(name && typeof name === "string") || !(Number.isInteger(delay) && delay >= 0)) { - throw new Error("waitOnEventOrTimeout - invalid parameters."); - } - const { - promise, - resolve - } = Promise.withResolvers(); - const ac = new AbortController(); - function handler(type) { - ac.abort(); - clearTimeout(timeout); - resolve(type); - } - const evtMethod = target instanceof EventBus ? "_on" : "addEventListener"; - target[evtMethod](name, handler.bind(null, WaitOnType.EVENT), { - signal: ac.signal - }); - const timeout = setTimeout(handler.bind(null, WaitOnType.TIMEOUT), delay); - return promise; -} -class EventBus { - #listeners = Object.create(null); - on(eventName, listener, options = null) { - this._on(eventName, listener, { - external: true, - once: options?.once, - signal: options?.signal - }); - } - off(eventName, listener, options = null) { - this._off(eventName, listener); - } - dispatch(eventName, data) { - const eventListeners = this.#listeners[eventName]; - if (!eventListeners || eventListeners.length === 0) { - return; - } - let externalListeners; - for (const { - listener, - external, - once - } of eventListeners.slice(0)) { - if (once) { - this._off(eventName, listener); - } - if (external) { - (externalListeners ||= []).push(listener); - continue; - } - listener(data); - } - if (externalListeners) { - for (const listener of externalListeners) { - listener(data); - } - externalListeners = null; - } - } - _on(eventName, listener, options = null) { - let rmAbort = null; - if (options?.signal instanceof AbortSignal) { - const { - signal - } = options; - if (signal.aborted) { - console.error("Cannot use an `aborted` signal."); - return; - } - const onAbort = () => this._off(eventName, listener); - rmAbort = () => signal.removeEventListener("abort", onAbort); - signal.addEventListener("abort", onAbort); - } - const eventListeners = this.#listeners[eventName] ||= []; - eventListeners.push({ - listener, - external: options?.external === true, - once: options?.once === true, - rmAbort - }); - } - _off(eventName, listener, options = null) { - const eventListeners = this.#listeners[eventName]; - if (!eventListeners) { - return; - } - for (let i = 0, ii = eventListeners.length; i < ii; i++) { - const evt = eventListeners[i]; - if (evt.listener === listener) { - evt.rmAbort?.(); - eventListeners.splice(i, 1); - return; - } - } - } -} -class FirefoxEventBus extends EventBus { - #externalServices; - #globalEventNames; - #isInAutomation; - constructor(globalEventNames, externalServices, isInAutomation) { - super(); - this.#globalEventNames = globalEventNames; - this.#externalServices = externalServices; - this.#isInAutomation = isInAutomation; - } - dispatch(eventName, data) { - throw new Error("Not implemented: FirefoxEventBus.dispatch"); - } -} - -;// ./node_modules/@fluent/bundle/esm/types.js -class FluentType { - constructor(value) { - this.value = value; - } - valueOf() { - return this.value; - } -} -class FluentNone extends FluentType { - constructor(value = "???") { - super(value); - } - toString(scope) { - return `{${this.value}}`; - } -} -class FluentNumber extends FluentType { - constructor(value, opts = {}) { - super(value); - this.opts = opts; - } - toString(scope) { - try { - const nf = scope.memoizeIntlObject(Intl.NumberFormat, this.opts); - return nf.format(this.value); - } catch (err) { - scope.reportError(err); - return this.value.toString(10); - } - } -} -class FluentDateTime extends FluentType { - constructor(value, opts = {}) { - super(value); - this.opts = opts; - } - toString(scope) { - try { - const dtf = scope.memoizeIntlObject(Intl.DateTimeFormat, this.opts); - return dtf.format(this.value); - } catch (err) { - scope.reportError(err); - return new Date(this.value).toISOString(); - } - } -} -;// ./node_modules/@fluent/bundle/esm/resolver.js - -const MAX_PLACEABLES = 100; -const FSI = "\u2068"; -const PDI = "\u2069"; -function match(scope, selector, key) { - if (key === selector) { - return true; - } - if (key instanceof FluentNumber && selector instanceof FluentNumber && key.value === selector.value) { - return true; - } - if (selector instanceof FluentNumber && typeof key === "string") { - let category = scope.memoizeIntlObject(Intl.PluralRules, selector.opts).select(selector.value); - if (key === category) { - return true; - } - } - return false; -} -function getDefault(scope, variants, star) { - if (variants[star]) { - return resolvePattern(scope, variants[star].value); - } - scope.reportError(new RangeError("No default")); - return new FluentNone(); -} -function getArguments(scope, args) { - const positional = []; - const named = Object.create(null); - for (const arg of args) { - if (arg.type === "narg") { - named[arg.name] = resolveExpression(scope, arg.value); - } else { - positional.push(resolveExpression(scope, arg)); - } - } - return { - positional, - named - }; -} -function resolveExpression(scope, expr) { - switch (expr.type) { - case "str": - return expr.value; - case "num": - return new FluentNumber(expr.value, { - minimumFractionDigits: expr.precision - }); - case "var": - return resolveVariableReference(scope, expr); - case "mesg": - return resolveMessageReference(scope, expr); - case "term": - return resolveTermReference(scope, expr); - case "func": - return resolveFunctionReference(scope, expr); - case "select": - return resolveSelectExpression(scope, expr); - default: - return new FluentNone(); - } -} -function resolveVariableReference(scope, { - name -}) { - let arg; - if (scope.params) { - if (Object.prototype.hasOwnProperty.call(scope.params, name)) { - arg = scope.params[name]; - } else { - return new FluentNone(`$${name}`); - } - } else if (scope.args && Object.prototype.hasOwnProperty.call(scope.args, name)) { - arg = scope.args[name]; - } else { - scope.reportError(new ReferenceError(`Unknown variable: $${name}`)); - return new FluentNone(`$${name}`); - } - if (arg instanceof FluentType) { - return arg; - } - switch (typeof arg) { - case "string": - return arg; - case "number": - return new FluentNumber(arg); - case "object": - if (arg instanceof Date) { - return new FluentDateTime(arg.getTime()); - } - default: - scope.reportError(new TypeError(`Variable type not supported: $${name}, ${typeof arg}`)); - return new FluentNone(`$${name}`); - } -} -function resolveMessageReference(scope, { - name, - attr -}) { - const message = scope.bundle._messages.get(name); - if (!message) { - scope.reportError(new ReferenceError(`Unknown message: ${name}`)); - return new FluentNone(name); - } - if (attr) { - const attribute = message.attributes[attr]; - if (attribute) { - return resolvePattern(scope, attribute); - } - scope.reportError(new ReferenceError(`Unknown attribute: ${attr}`)); - return new FluentNone(`${name}.${attr}`); - } - if (message.value) { - return resolvePattern(scope, message.value); - } - scope.reportError(new ReferenceError(`No value: ${name}`)); - return new FluentNone(name); -} -function resolveTermReference(scope, { - name, - attr, - args -}) { - const id = `-${name}`; - const term = scope.bundle._terms.get(id); - if (!term) { - scope.reportError(new ReferenceError(`Unknown term: ${id}`)); - return new FluentNone(id); - } - if (attr) { - const attribute = term.attributes[attr]; - if (attribute) { - scope.params = getArguments(scope, args).named; - const resolved = resolvePattern(scope, attribute); - scope.params = null; - return resolved; - } - scope.reportError(new ReferenceError(`Unknown attribute: ${attr}`)); - return new FluentNone(`${id}.${attr}`); - } - scope.params = getArguments(scope, args).named; - const resolved = resolvePattern(scope, term.value); - scope.params = null; - return resolved; -} -function resolveFunctionReference(scope, { - name, - args -}) { - let func = scope.bundle._functions[name]; - if (!func) { - scope.reportError(new ReferenceError(`Unknown function: ${name}()`)); - return new FluentNone(`${name}()`); - } - if (typeof func !== "function") { - scope.reportError(new TypeError(`Function ${name}() is not callable`)); - return new FluentNone(`${name}()`); - } - try { - let resolved = getArguments(scope, args); - return func(resolved.positional, resolved.named); - } catch (err) { - scope.reportError(err); - return new FluentNone(`${name}()`); - } -} -function resolveSelectExpression(scope, { - selector, - variants, - star -}) { - let sel = resolveExpression(scope, selector); - if (sel instanceof FluentNone) { - return getDefault(scope, variants, star); - } - for (const variant of variants) { - const key = resolveExpression(scope, variant.key); - if (match(scope, sel, key)) { - return resolvePattern(scope, variant.value); - } - } - return getDefault(scope, variants, star); -} -function resolveComplexPattern(scope, ptn) { - if (scope.dirty.has(ptn)) { - scope.reportError(new RangeError("Cyclic reference")); - return new FluentNone(); - } - scope.dirty.add(ptn); - const result = []; - const useIsolating = scope.bundle._useIsolating && ptn.length > 1; - for (const elem of ptn) { - if (typeof elem === "string") { - result.push(scope.bundle._transform(elem)); - continue; - } - scope.placeables++; - if (scope.placeables > MAX_PLACEABLES) { - scope.dirty.delete(ptn); - throw new RangeError(`Too many placeables expanded: ${scope.placeables}, ` + `max allowed is ${MAX_PLACEABLES}`); - } - if (useIsolating) { - result.push(FSI); - } - result.push(resolveExpression(scope, elem).toString(scope)); - if (useIsolating) { - result.push(PDI); - } - } - scope.dirty.delete(ptn); - return result.join(""); -} -function resolvePattern(scope, value) { - if (typeof value === "string") { - return scope.bundle._transform(value); - } - return resolveComplexPattern(scope, value); -} -;// ./node_modules/@fluent/bundle/esm/scope.js -class Scope { - constructor(bundle, errors, args) { - this.dirty = new WeakSet(); - this.params = null; - this.placeables = 0; - this.bundle = bundle; - this.errors = errors; - this.args = args; - } - reportError(error) { - if (!this.errors || !(error instanceof Error)) { - throw error; - } - this.errors.push(error); - } - memoizeIntlObject(ctor, opts) { - let cache = this.bundle._intls.get(ctor); - if (!cache) { - cache = {}; - this.bundle._intls.set(ctor, cache); - } - let id = JSON.stringify(opts); - if (!cache[id]) { - cache[id] = new ctor(this.bundle.locales, opts); - } - return cache[id]; - } -} -;// ./node_modules/@fluent/bundle/esm/builtins.js - -function values(opts, allowed) { - const unwrapped = Object.create(null); - for (const [name, opt] of Object.entries(opts)) { - if (allowed.includes(name)) { - unwrapped[name] = opt.valueOf(); - } - } - return unwrapped; -} -const NUMBER_ALLOWED = ["unitDisplay", "currencyDisplay", "useGrouping", "minimumIntegerDigits", "minimumFractionDigits", "maximumFractionDigits", "minimumSignificantDigits", "maximumSignificantDigits"]; -function NUMBER(args, opts) { - let arg = args[0]; - if (arg instanceof FluentNone) { - return new FluentNone(`NUMBER(${arg.valueOf()})`); - } - if (arg instanceof FluentNumber) { - return new FluentNumber(arg.valueOf(), { - ...arg.opts, - ...values(opts, NUMBER_ALLOWED) - }); - } - if (arg instanceof FluentDateTime) { - return new FluentNumber(arg.valueOf(), { - ...values(opts, NUMBER_ALLOWED) - }); - } - throw new TypeError("Invalid argument to NUMBER"); -} -const DATETIME_ALLOWED = ["dateStyle", "timeStyle", "fractionalSecondDigits", "dayPeriod", "hour12", "weekday", "era", "year", "month", "day", "hour", "minute", "second", "timeZoneName"]; -function DATETIME(args, opts) { - let arg = args[0]; - if (arg instanceof FluentNone) { - return new FluentNone(`DATETIME(${arg.valueOf()})`); - } - if (arg instanceof FluentDateTime) { - return new FluentDateTime(arg.valueOf(), { - ...arg.opts, - ...values(opts, DATETIME_ALLOWED) - }); - } - if (arg instanceof FluentNumber) { - return new FluentDateTime(arg.valueOf(), { - ...values(opts, DATETIME_ALLOWED) - }); - } - throw new TypeError("Invalid argument to DATETIME"); -} -;// ./node_modules/@fluent/bundle/esm/memoizer.js -const cache = new Map(); -function getMemoizerForLocale(locales) { - const stringLocale = Array.isArray(locales) ? locales.join(" ") : locales; - let memoizer = cache.get(stringLocale); - if (memoizer === undefined) { - memoizer = new Map(); - cache.set(stringLocale, memoizer); - } - return memoizer; -} -;// ./node_modules/@fluent/bundle/esm/bundle.js - - - - - -class FluentBundle { - constructor(locales, { - functions, - useIsolating = true, - transform = v => v - } = {}) { - this._terms = new Map(); - this._messages = new Map(); - this.locales = Array.isArray(locales) ? locales : [locales]; - this._functions = { - NUMBER: NUMBER, - DATETIME: DATETIME, - ...functions - }; - this._useIsolating = useIsolating; - this._transform = transform; - this._intls = getMemoizerForLocale(locales); - } - hasMessage(id) { - return this._messages.has(id); - } - getMessage(id) { - return this._messages.get(id); - } - addResource(res, { - allowOverrides = false - } = {}) { - const errors = []; - for (let i = 0; i < res.body.length; i++) { - let entry = res.body[i]; - if (entry.id.startsWith("-")) { - if (allowOverrides === false && this._terms.has(entry.id)) { - errors.push(new Error(`Attempt to override an existing term: "${entry.id}"`)); - continue; - } - this._terms.set(entry.id, entry); - } else { - if (allowOverrides === false && this._messages.has(entry.id)) { - errors.push(new Error(`Attempt to override an existing message: "${entry.id}"`)); - continue; - } - this._messages.set(entry.id, entry); - } - } - return errors; - } - formatPattern(pattern, args = null, errors = null) { - if (typeof pattern === "string") { - return this._transform(pattern); - } - let scope = new Scope(this, errors, args); - try { - let value = resolveComplexPattern(scope, pattern); - return value.toString(scope); - } catch (err) { - if (scope.errors && err instanceof Error) { - scope.errors.push(err); - return new FluentNone().toString(scope); - } - throw err; - } - } -} -;// ./node_modules/@fluent/bundle/esm/resource.js -const RE_MESSAGE_START = /^(-?[a-zA-Z][\w-]*) *= */gm; -const RE_ATTRIBUTE_START = /\.([a-zA-Z][\w-]*) *= */y; -const RE_VARIANT_START = /\*?\[/y; -const RE_NUMBER_LITERAL = /(-?[0-9]+(?:\.([0-9]+))?)/y; -const RE_IDENTIFIER = /([a-zA-Z][\w-]*)/y; -const RE_REFERENCE = /([$-])?([a-zA-Z][\w-]*)(?:\.([a-zA-Z][\w-]*))?/y; -const RE_FUNCTION_NAME = /^[A-Z][A-Z0-9_-]*$/; -const RE_TEXT_RUN = /([^{}\n\r]+)/y; -const RE_STRING_RUN = /([^\\"\n\r]*)/y; -const RE_STRING_ESCAPE = /\\([\\"])/y; -const RE_UNICODE_ESCAPE = /\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{6})/y; -const RE_LEADING_NEWLINES = /^\n+/; -const RE_TRAILING_SPACES = / +$/; -const RE_BLANK_LINES = / *\r?\n/g; -const RE_INDENT = /( *)$/; -const TOKEN_BRACE_OPEN = /{\s*/y; -const TOKEN_BRACE_CLOSE = /\s*}/y; -const TOKEN_BRACKET_OPEN = /\[\s*/y; -const TOKEN_BRACKET_CLOSE = /\s*] */y; -const TOKEN_PAREN_OPEN = /\s*\(\s*/y; -const TOKEN_ARROW = /\s*->\s*/y; -const TOKEN_COLON = /\s*:\s*/y; -const TOKEN_COMMA = /\s*,?\s*/y; -const TOKEN_BLANK = /\s+/y; -class FluentResource { - constructor(source) { - this.body = []; - RE_MESSAGE_START.lastIndex = 0; - let cursor = 0; - while (true) { - let next = RE_MESSAGE_START.exec(source); - if (next === null) { - break; - } - cursor = RE_MESSAGE_START.lastIndex; - try { - this.body.push(parseMessage(next[1])); - } catch (err) { - if (err instanceof SyntaxError) { - continue; - } - throw err; - } - } - function test(re) { - re.lastIndex = cursor; - return re.test(source); - } - function consumeChar(char, errorClass) { - if (source[cursor] === char) { - cursor++; - return true; - } - if (errorClass) { - throw new errorClass(`Expected ${char}`); - } - return false; - } - function consumeToken(re, errorClass) { - if (test(re)) { - cursor = re.lastIndex; - return true; - } - if (errorClass) { - throw new errorClass(`Expected ${re.toString()}`); - } - return false; - } - function match(re) { - re.lastIndex = cursor; - let result = re.exec(source); - if (result === null) { - throw new SyntaxError(`Expected ${re.toString()}`); - } - cursor = re.lastIndex; - return result; - } - function match1(re) { - return match(re)[1]; - } - function parseMessage(id) { - let value = parsePattern(); - let attributes = parseAttributes(); - if (value === null && Object.keys(attributes).length === 0) { - throw new SyntaxError("Expected message value or attributes"); - } - return { - id, - value, - attributes - }; - } - function parseAttributes() { - let attrs = Object.create(null); - while (test(RE_ATTRIBUTE_START)) { - let name = match1(RE_ATTRIBUTE_START); - let value = parsePattern(); - if (value === null) { - throw new SyntaxError("Expected attribute value"); - } - attrs[name] = value; - } - return attrs; - } - function parsePattern() { - let first; - if (test(RE_TEXT_RUN)) { - first = match1(RE_TEXT_RUN); - } - if (source[cursor] === "{" || source[cursor] === "}") { - return parsePatternElements(first ? [first] : [], Infinity); - } - let indent = parseIndent(); - if (indent) { - if (first) { - return parsePatternElements([first, indent], indent.length); - } - indent.value = trim(indent.value, RE_LEADING_NEWLINES); - return parsePatternElements([indent], indent.length); - } - if (first) { - return trim(first, RE_TRAILING_SPACES); - } - return null; - } - function parsePatternElements(elements = [], commonIndent) { - while (true) { - if (test(RE_TEXT_RUN)) { - elements.push(match1(RE_TEXT_RUN)); - continue; - } - if (source[cursor] === "{") { - elements.push(parsePlaceable()); - continue; - } - if (source[cursor] === "}") { - throw new SyntaxError("Unbalanced closing brace"); - } - let indent = parseIndent(); - if (indent) { - elements.push(indent); - commonIndent = Math.min(commonIndent, indent.length); - continue; - } - break; - } - let lastIndex = elements.length - 1; - let lastElement = elements[lastIndex]; - if (typeof lastElement === "string") { - elements[lastIndex] = trim(lastElement, RE_TRAILING_SPACES); - } - let baked = []; - for (let element of elements) { - if (element instanceof Indent) { - element = element.value.slice(0, element.value.length - commonIndent); - } - if (element) { - baked.push(element); - } - } - return baked; - } - function parsePlaceable() { - consumeToken(TOKEN_BRACE_OPEN, SyntaxError); - let selector = parseInlineExpression(); - if (consumeToken(TOKEN_BRACE_CLOSE)) { - return selector; - } - if (consumeToken(TOKEN_ARROW)) { - let variants = parseVariants(); - consumeToken(TOKEN_BRACE_CLOSE, SyntaxError); - return { - type: "select", - selector, - ...variants - }; - } - throw new SyntaxError("Unclosed placeable"); - } - function parseInlineExpression() { - if (source[cursor] === "{") { - return parsePlaceable(); - } - if (test(RE_REFERENCE)) { - let [, sigil, name, attr = null] = match(RE_REFERENCE); - if (sigil === "$") { - return { - type: "var", - name - }; - } - if (consumeToken(TOKEN_PAREN_OPEN)) { - let args = parseArguments(); - if (sigil === "-") { - return { - type: "term", - name, - attr, - args - }; - } - if (RE_FUNCTION_NAME.test(name)) { - return { - type: "func", - name, - args - }; - } - throw new SyntaxError("Function names must be all upper-case"); - } - if (sigil === "-") { - return { - type: "term", - name, - attr, - args: [] - }; - } - return { - type: "mesg", - name, - attr - }; - } - return parseLiteral(); - } - function parseArguments() { - let args = []; - while (true) { - switch (source[cursor]) { - case ")": - cursor++; - return args; - case undefined: - throw new SyntaxError("Unclosed argument list"); - } - args.push(parseArgument()); - consumeToken(TOKEN_COMMA); - } - } - function parseArgument() { - let expr = parseInlineExpression(); - if (expr.type !== "mesg") { - return expr; - } - if (consumeToken(TOKEN_COLON)) { - return { - type: "narg", - name: expr.name, - value: parseLiteral() - }; - } - return expr; - } - function parseVariants() { - let variants = []; - let count = 0; - let star; - while (test(RE_VARIANT_START)) { - if (consumeChar("*")) { - star = count; - } - let key = parseVariantKey(); - let value = parsePattern(); - if (value === null) { - throw new SyntaxError("Expected variant value"); - } - variants[count++] = { - key, - value - }; - } - if (count === 0) { - return null; - } - if (star === undefined) { - throw new SyntaxError("Expected default variant"); - } - return { - variants, - star - }; - } - function parseVariantKey() { - consumeToken(TOKEN_BRACKET_OPEN, SyntaxError); - let key; - if (test(RE_NUMBER_LITERAL)) { - key = parseNumberLiteral(); - } else { - key = { - type: "str", - value: match1(RE_IDENTIFIER) - }; - } - consumeToken(TOKEN_BRACKET_CLOSE, SyntaxError); - return key; - } - function parseLiteral() { - if (test(RE_NUMBER_LITERAL)) { - return parseNumberLiteral(); - } - if (source[cursor] === '"') { - return parseStringLiteral(); - } - throw new SyntaxError("Invalid expression"); - } - function parseNumberLiteral() { - let [, value, fraction = ""] = match(RE_NUMBER_LITERAL); - let precision = fraction.length; - return { - type: "num", - value: parseFloat(value), - precision - }; - } - function parseStringLiteral() { - consumeChar('"', SyntaxError); - let value = ""; - while (true) { - value += match1(RE_STRING_RUN); - if (source[cursor] === "\\") { - value += parseEscapeSequence(); - continue; - } - if (consumeChar('"')) { - return { - type: "str", - value - }; - } - throw new SyntaxError("Unclosed string literal"); - } - } - function parseEscapeSequence() { - if (test(RE_STRING_ESCAPE)) { - return match1(RE_STRING_ESCAPE); - } - if (test(RE_UNICODE_ESCAPE)) { - let [, codepoint4, codepoint6] = match(RE_UNICODE_ESCAPE); - let codepoint = parseInt(codepoint4 || codepoint6, 16); - return codepoint <= 0xd7ff || 0xe000 <= codepoint ? String.fromCodePoint(codepoint) : "�"; - } - throw new SyntaxError("Unknown escape sequence"); - } - function parseIndent() { - let start = cursor; - consumeToken(TOKEN_BLANK); - switch (source[cursor]) { - case ".": - case "[": - case "*": - case "}": - case undefined: - return false; - case "{": - return makeIndent(source.slice(start, cursor)); - } - if (source[cursor - 1] === " ") { - return makeIndent(source.slice(start, cursor)); - } - return false; - } - function trim(text, re) { - return text.replace(re, ""); - } - function makeIndent(blank) { - let value = blank.replace(RE_BLANK_LINES, "\n"); - let length = RE_INDENT.exec(blank)[1].length; - return new Indent(value, length); - } - } -} -class Indent { - constructor(value, length) { - this.value = value; - this.length = length; - } -} -;// ./node_modules/@fluent/bundle/esm/index.js - - - -;// ./node_modules/@fluent/dom/esm/overlay.js -const reOverlay = /<|&#?\w+;/; -const TEXT_LEVEL_ELEMENTS = { - "http://www.w3.org/1999/xhtml": ["em", "strong", "small", "s", "cite", "q", "dfn", "abbr", "data", "time", "code", "var", "samp", "kbd", "sub", "sup", "i", "b", "u", "mark", "bdi", "bdo", "span", "br", "wbr"] -}; -const LOCALIZABLE_ATTRIBUTES = { - "http://www.w3.org/1999/xhtml": { - global: ["title", "aria-label", "aria-valuetext"], - a: ["download"], - area: ["download", "alt"], - input: ["alt", "placeholder"], - menuitem: ["label"], - menu: ["label"], - optgroup: ["label"], - option: ["label"], - track: ["label"], - img: ["alt"], - textarea: ["placeholder"], - th: ["abbr"] - }, - "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul": { - global: ["accesskey", "aria-label", "aria-valuetext", "label", "title", "tooltiptext"], - description: ["value"], - key: ["key", "keycode"], - label: ["value"], - textbox: ["placeholder", "value"] - } -}; -function translateElement(element, translation) { - const { - value - } = translation; - if (typeof value === "string") { - if (element.localName === "title" && element.namespaceURI === "http://www.w3.org/1999/xhtml") { - element.textContent = value; - } else if (!reOverlay.test(value)) { - element.textContent = value; - } else { - const templateElement = element.ownerDocument.createElementNS("http://www.w3.org/1999/xhtml", "template"); - templateElement.innerHTML = value; - overlayChildNodes(templateElement.content, element); - } - } - overlayAttributes(translation, element); -} -function overlayChildNodes(fromFragment, toElement) { - for (const childNode of fromFragment.childNodes) { - if (childNode.nodeType === childNode.TEXT_NODE) { - continue; - } - if (childNode.hasAttribute("data-l10n-name")) { - const sanitized = getNodeForNamedElement(toElement, childNode); - fromFragment.replaceChild(sanitized, childNode); - continue; - } - if (isElementAllowed(childNode)) { - const sanitized = createSanitizedElement(childNode); - fromFragment.replaceChild(sanitized, childNode); - continue; - } - console.warn(`An element of forbidden type "${childNode.localName}" was found in ` + "the translation. Only safe text-level elements and elements with " + "data-l10n-name are allowed."); - fromFragment.replaceChild(createTextNodeFromTextContent(childNode), childNode); - } - toElement.textContent = ""; - toElement.appendChild(fromFragment); -} -function hasAttribute(attributes, name) { - if (!attributes) { - return false; - } - for (let attr of attributes) { - if (attr.name === name) { - return true; - } - } - return false; -} -function overlayAttributes(fromElement, toElement) { - const explicitlyAllowed = toElement.hasAttribute("data-l10n-attrs") ? toElement.getAttribute("data-l10n-attrs").split(",").map(i => i.trim()) : null; - for (const attr of Array.from(toElement.attributes)) { - if (isAttrNameLocalizable(attr.name, toElement, explicitlyAllowed) && !hasAttribute(fromElement.attributes, attr.name)) { - toElement.removeAttribute(attr.name); - } - } - if (!fromElement.attributes) { - return; - } - for (const attr of Array.from(fromElement.attributes)) { - if (isAttrNameLocalizable(attr.name, toElement, explicitlyAllowed) && toElement.getAttribute(attr.name) !== attr.value) { - toElement.setAttribute(attr.name, attr.value); - } - } -} -function getNodeForNamedElement(sourceElement, translatedChild) { - const childName = translatedChild.getAttribute("data-l10n-name"); - const sourceChild = sourceElement.querySelector(`[data-l10n-name="${childName}"]`); - if (!sourceChild) { - console.warn(`An element named "${childName}" wasn't found in the source.`); - return createTextNodeFromTextContent(translatedChild); - } - if (sourceChild.localName !== translatedChild.localName) { - console.warn(`An element named "${childName}" was found in the translation ` + `but its type ${translatedChild.localName} didn't match the ` + `element found in the source (${sourceChild.localName}).`); - return createTextNodeFromTextContent(translatedChild); - } - sourceElement.removeChild(sourceChild); - const clone = sourceChild.cloneNode(false); - return shallowPopulateUsing(translatedChild, clone); -} -function createSanitizedElement(element) { - const clone = element.ownerDocument.createElement(element.localName); - return shallowPopulateUsing(element, clone); -} -function createTextNodeFromTextContent(element) { - return element.ownerDocument.createTextNode(element.textContent); -} -function isElementAllowed(element) { - const allowed = TEXT_LEVEL_ELEMENTS[element.namespaceURI]; - return allowed && allowed.includes(element.localName); -} -function isAttrNameLocalizable(name, element, explicitlyAllowed = null) { - if (explicitlyAllowed && explicitlyAllowed.includes(name)) { - return true; - } - const allowed = LOCALIZABLE_ATTRIBUTES[element.namespaceURI]; - if (!allowed) { - return false; - } - const attrName = name.toLowerCase(); - const elemName = element.localName; - if (allowed.global.includes(attrName)) { - return true; - } - if (!allowed[elemName]) { - return false; - } - if (allowed[elemName].includes(attrName)) { - return true; - } - if (element.namespaceURI === "http://www.w3.org/1999/xhtml" && elemName === "input" && attrName === "value") { - const type = element.type.toLowerCase(); - if (type === "submit" || type === "button" || type === "reset") { - return true; - } - } - return false; -} -function shallowPopulateUsing(fromElement, toElement) { - toElement.textContent = fromElement.textContent; - overlayAttributes(fromElement, toElement); - return toElement; -} -;// ./node_modules/cached-iterable/src/cached_iterable.mjs -class CachedIterable extends Array { - static from(iterable) { - if (iterable instanceof this) { - return iterable; - } - return new this(iterable); - } -} -;// ./node_modules/cached-iterable/src/cached_sync_iterable.mjs - -class CachedSyncIterable extends CachedIterable { - constructor(iterable) { - super(); - if (Symbol.iterator in Object(iterable)) { - this.iterator = iterable[Symbol.iterator](); - } else { - throw new TypeError("Argument must implement the iteration protocol."); - } - } - [Symbol.iterator]() { - const cached = this; - let cur = 0; - return { - next() { - if (cached.length <= cur) { - cached.push(cached.iterator.next()); - } - return cached[cur++]; - } - }; - } - touchNext(count = 1) { - let idx = 0; - while (idx++ < count) { - const last = this[this.length - 1]; - if (last && last.done) { - break; - } - this.push(this.iterator.next()); - } - return this[this.length - 1]; - } -} -;// ./node_modules/cached-iterable/src/cached_async_iterable.mjs - -class CachedAsyncIterable extends CachedIterable { - constructor(iterable) { - super(); - if (Symbol.asyncIterator in Object(iterable)) { - this.iterator = iterable[Symbol.asyncIterator](); - } else if (Symbol.iterator in Object(iterable)) { - this.iterator = iterable[Symbol.iterator](); - } else { - throw new TypeError("Argument must implement the iteration protocol."); - } - } - [Symbol.asyncIterator]() { - const cached = this; - let cur = 0; - return { - async next() { - if (cached.length <= cur) { - cached.push(cached.iterator.next()); - } - return cached[cur++]; - } - }; - } - async touchNext(count = 1) { - let idx = 0; - while (idx++ < count) { - const last = this[this.length - 1]; - if (last && (await last).done) { - break; - } - this.push(this.iterator.next()); - } - return this[this.length - 1]; - } -} -;// ./node_modules/cached-iterable/src/index.mjs - - -;// ./node_modules/@fluent/dom/esm/localization.js - -class Localization { - constructor(resourceIds = [], generateBundles) { - this.resourceIds = resourceIds; - this.generateBundles = generateBundles; - this.onChange(true); - } - addResourceIds(resourceIds, eager = false) { - this.resourceIds.push(...resourceIds); - this.onChange(eager); - return this.resourceIds.length; - } - removeResourceIds(resourceIds) { - this.resourceIds = this.resourceIds.filter(r => !resourceIds.includes(r)); - this.onChange(); - return this.resourceIds.length; - } - async formatWithFallback(keys, method) { - const translations = []; - let hasAtLeastOneBundle = false; - for await (const bundle of this.bundles) { - hasAtLeastOneBundle = true; - const missingIds = keysFromBundle(method, bundle, keys, translations); - if (missingIds.size === 0) { - break; - } - if (typeof console !== "undefined") { - const locale = bundle.locales[0]; - const ids = Array.from(missingIds).join(", "); - console.warn(`[fluent] Missing translations in ${locale}: ${ids}`); - } - } - if (!hasAtLeastOneBundle && typeof console !== "undefined") { - console.warn(`[fluent] Request for keys failed because no resource bundles got generated. - keys: ${JSON.stringify(keys)}. - resourceIds: ${JSON.stringify(this.resourceIds)}.`); - } - return translations; - } - formatMessages(keys) { - return this.formatWithFallback(keys, messageFromBundle); - } - formatValues(keys) { - return this.formatWithFallback(keys, valueFromBundle); - } - async formatValue(id, args) { - const [val] = await this.formatValues([{ - id, - args - }]); - return val; - } - handleEvent() { - this.onChange(); - } - onChange(eager = false) { - this.bundles = CachedAsyncIterable.from(this.generateBundles(this.resourceIds)); - if (eager) { - this.bundles.touchNext(2); - } - } -} -function valueFromBundle(bundle, errors, message, args) { - if (message.value) { - return bundle.formatPattern(message.value, args, errors); - } - return null; -} -function messageFromBundle(bundle, errors, message, args) { - const formatted = { - value: null, - attributes: null - }; - if (message.value) { - formatted.value = bundle.formatPattern(message.value, args, errors); - } - let attrNames = Object.keys(message.attributes); - if (attrNames.length > 0) { - formatted.attributes = new Array(attrNames.length); - for (let [i, name] of attrNames.entries()) { - let value = bundle.formatPattern(message.attributes[name], args, errors); - formatted.attributes[i] = { - name, - value - }; - } - } - return formatted; -} -function keysFromBundle(method, bundle, keys, translations) { - const messageErrors = []; - const missingIds = new Set(); - keys.forEach(({ - id, - args - }, i) => { - if (translations[i] !== undefined) { - return; - } - let message = bundle.getMessage(id); - if (message) { - messageErrors.length = 0; - translations[i] = method(bundle, messageErrors, message, args); - if (messageErrors.length > 0 && typeof console !== "undefined") { - const locale = bundle.locales[0]; - const errors = messageErrors.join(", "); - console.warn(`[fluent][resolver] errors in ${locale}/${id}: ${errors}.`); - } - } else { - missingIds.add(id); - } - }); - return missingIds; -} -;// ./node_modules/@fluent/dom/esm/dom_localization.js - - -const L10NID_ATTR_NAME = "data-l10n-id"; -const L10NARGS_ATTR_NAME = "data-l10n-args"; -const L10N_ELEMENT_QUERY = `[${L10NID_ATTR_NAME}]`; -class DOMLocalization extends Localization { - constructor(resourceIds, generateBundles) { - super(resourceIds, generateBundles); - this.roots = new Set(); - this.pendingrAF = null; - this.pendingElements = new Set(); - this.windowElement = null; - this.mutationObserver = null; - this.observerConfig = { - attributes: true, - characterData: false, - childList: true, - subtree: true, - attributeFilter: [L10NID_ATTR_NAME, L10NARGS_ATTR_NAME] - }; - } - onChange(eager = false) { - super.onChange(eager); - if (this.roots) { - this.translateRoots(); - } - } - setAttributes(element, id, args) { - element.setAttribute(L10NID_ATTR_NAME, id); - if (args) { - element.setAttribute(L10NARGS_ATTR_NAME, JSON.stringify(args)); - } else { - element.removeAttribute(L10NARGS_ATTR_NAME); - } - return element; - } - getAttributes(element) { - return { - id: element.getAttribute(L10NID_ATTR_NAME), - args: JSON.parse(element.getAttribute(L10NARGS_ATTR_NAME) || null) - }; - } - connectRoot(newRoot) { - for (const root of this.roots) { - if (root === newRoot || root.contains(newRoot) || newRoot.contains(root)) { - throw new Error("Cannot add a root that overlaps with existing root."); - } - } - if (this.windowElement) { - if (this.windowElement !== newRoot.ownerDocument.defaultView) { - throw new Error(`Cannot connect a root: - DOMLocalization already has a root from a different window.`); - } - } else { - this.windowElement = newRoot.ownerDocument.defaultView; - this.mutationObserver = new this.windowElement.MutationObserver(mutations => this.translateMutations(mutations)); - } - this.roots.add(newRoot); - this.mutationObserver.observe(newRoot, this.observerConfig); - } - disconnectRoot(root) { - this.roots.delete(root); - this.pauseObserving(); - if (this.roots.size === 0) { - this.mutationObserver = null; - if (this.windowElement && this.pendingrAF) { - this.windowElement.cancelAnimationFrame(this.pendingrAF); - } - this.windowElement = null; - this.pendingrAF = null; - this.pendingElements.clear(); - return true; - } - this.resumeObserving(); - return false; - } - translateRoots() { - const roots = Array.from(this.roots); - return Promise.all(roots.map(root => this.translateFragment(root))); - } - pauseObserving() { - if (!this.mutationObserver) { - return; - } - this.translateMutations(this.mutationObserver.takeRecords()); - this.mutationObserver.disconnect(); - } - resumeObserving() { - if (!this.mutationObserver) { - return; - } - for (const root of this.roots) { - this.mutationObserver.observe(root, this.observerConfig); - } - } - translateMutations(mutations) { - for (const mutation of mutations) { - switch (mutation.type) { - case "attributes": - if (mutation.target.hasAttribute("data-l10n-id")) { - this.pendingElements.add(mutation.target); - } - break; - case "childList": - for (const addedNode of mutation.addedNodes) { - if (addedNode.nodeType === addedNode.ELEMENT_NODE) { - if (addedNode.childElementCount) { - for (const element of this.getTranslatables(addedNode)) { - this.pendingElements.add(element); - } - } else if (addedNode.hasAttribute(L10NID_ATTR_NAME)) { - this.pendingElements.add(addedNode); - } - } - } - break; - } - } - if (this.pendingElements.size > 0) { - if (this.pendingrAF === null) { - this.pendingrAF = this.windowElement.requestAnimationFrame(() => { - this.translateElements(Array.from(this.pendingElements)); - this.pendingElements.clear(); - this.pendingrAF = null; - }); - } - } - } - translateFragment(frag) { - return this.translateElements(this.getTranslatables(frag)); - } - async translateElements(elements) { - if (!elements.length) { - return undefined; - } - const keys = elements.map(this.getKeysForElement); - const translations = await this.formatMessages(keys); - return this.applyTranslations(elements, translations); - } - applyTranslations(elements, translations) { - this.pauseObserving(); - for (let i = 0; i < elements.length; i++) { - if (translations[i] !== undefined) { - translateElement(elements[i], translations[i]); - } - } - this.resumeObserving(); - } - getTranslatables(element) { - const nodes = Array.from(element.querySelectorAll(L10N_ELEMENT_QUERY)); - if (typeof element.hasAttribute === "function" && element.hasAttribute(L10NID_ATTR_NAME)) { - nodes.push(element); - } - return nodes; - } - getKeysForElement(element) { - return { - id: element.getAttribute(L10NID_ATTR_NAME), - args: JSON.parse(element.getAttribute(L10NARGS_ATTR_NAME) || null) - }; - } -} -;// ./node_modules/@fluent/dom/esm/index.js - - -;// ./web/l10n.js -class L10n { - #dir; - #elements; - #lang; - #l10n; - constructor({ - lang, - isRTL - }, l10n = null) { - this.#lang = L10n.#fixupLangCode(lang); - this.#l10n = l10n; - this.#dir = isRTL ?? L10n.#isRTL(this.#lang) ? "rtl" : "ltr"; - } - _setL10n(l10n) { - this.#l10n = l10n; - } - getLanguage() { - return this.#lang; - } - getDirection() { - return this.#dir; - } - async get(ids, args = null, fallback) { - if (Array.isArray(ids)) { - ids = ids.map(id => ({ - id - })); - const messages = await this.#l10n.formatMessages(ids); - return messages.map(message => message.value); - } - const messages = await this.#l10n.formatMessages([{ - id: ids, - args - }]); - return messages[0]?.value || fallback; - } - async translate(element) { - (this.#elements ||= new Set()).add(element); - try { - this.#l10n.connectRoot(element); - await this.#l10n.translateRoots(); - } catch {} - } - async translateOnce(element) { - try { - await this.#l10n.translateElements([element]); - } catch (ex) { - console.error("translateOnce:", ex); - } - } - async destroy() { - if (this.#elements) { - for (const element of this.#elements) { - this.#l10n.disconnectRoot(element); - } - this.#elements.clear(); - this.#elements = null; - } - this.#l10n.pauseObserving(); - } - pause() { - this.#l10n.pauseObserving(); - } - resume() { - this.#l10n.resumeObserving(); - } - static #fixupLangCode(langCode) { - langCode = langCode?.toLowerCase() || "en-us"; - const PARTIAL_LANG_CODES = { - en: "en-us", - es: "es-es", - fy: "fy-nl", - ga: "ga-ie", - gu: "gu-in", - hi: "hi-in", - hy: "hy-am", - nb: "nb-no", - ne: "ne-np", - nn: "nn-no", - pa: "pa-in", - pt: "pt-pt", - sv: "sv-se", - zh: "zh-cn" - }; - return PARTIAL_LANG_CODES[langCode] || langCode; - } - static #isRTL(lang) { - const shortCode = lang.split("-", 1)[0]; - return ["ar", "he", "fa", "ps", "ur"].includes(shortCode); - } -} -const GenericL10n = null; - -;// ./web/genericl10n.js - - - - -function createBundle(lang, text) { - const resource = new FluentResource(text); - const bundle = new FluentBundle(lang); - const errors = bundle.addResource(resource); - if (errors.length) { - console.error("L10n errors", errors); - } - return bundle; -} -class genericl10n_GenericL10n extends L10n { - constructor(lang) { - super({ - lang - }); - const generateBundles = !lang ? genericl10n_GenericL10n.#generateBundlesFallback.bind(genericl10n_GenericL10n, this.getLanguage()) : genericl10n_GenericL10n.#generateBundles.bind(genericl10n_GenericL10n, "en-us", this.getLanguage()); - this._setL10n(new DOMLocalization([], generateBundles)); - } - static async *#generateBundles(defaultLang, baseLang) { - const { - baseURL, - paths - } = await this.#getPaths(); - const langs = [baseLang]; - if (defaultLang !== baseLang) { - const shortLang = baseLang.split("-", 1)[0]; - if (shortLang !== baseLang) { - langs.push(shortLang); - } - langs.push(defaultLang); - } - for (const lang of langs) { - const bundle = await this.#createBundle(lang, baseURL, paths); - if (bundle) { - yield bundle; - } else if (lang === "en-us") { - yield this.#createBundleFallback(lang); - } - } - } - static async #createBundle(lang, baseURL, paths) { - const path = paths[lang]; - if (!path) { - return null; - } - const url = new URL(path, baseURL); - const text = await fetchData(url, "text"); - return createBundle(lang, text); - } - static async #getPaths() { - try { - const { - href - } = document.querySelector(`link[type="application/l10n"]`); - const paths = await fetchData(href, "json"); - return { - baseURL: href.replace(/[^/]*$/, "") || "./", - paths - }; - } catch {} - return { - baseURL: "./", - paths: Object.create(null) - }; - } - static async *#generateBundlesFallback(lang) { - yield this.#createBundleFallback(lang); - } - static async #createBundleFallback(lang) { - const text = "pdfjs-previous-button =\n .title = Previous Page\npdfjs-previous-button-label = Previous\npdfjs-next-button =\n .title = Next Page\npdfjs-next-button-label = Next\npdfjs-page-input =\n .title = Page\npdfjs-of-pages = of { $pagesCount }\npdfjs-page-of-pages = ({ $pageNumber } of { $pagesCount })\npdfjs-zoom-out-button =\n .title = Zoom Out\npdfjs-zoom-out-button-label = Zoom Out\npdfjs-zoom-in-button =\n .title = Zoom In\npdfjs-zoom-in-button-label = Zoom In\npdfjs-zoom-select =\n .title = Zoom\npdfjs-presentation-mode-button =\n .title = Switch to Presentation Mode\npdfjs-presentation-mode-button-label = Presentation Mode\npdfjs-open-file-button =\n .title = Open File\npdfjs-open-file-button-label = Open\npdfjs-print-button =\n .title = Print\npdfjs-print-button-label = Print\npdfjs-save-button =\n .title = Save\npdfjs-save-button-label = Save\npdfjs-download-button =\n .title = Download\npdfjs-download-button-label = Download\npdfjs-bookmark-button =\n .title = Current Page (View URL from Current Page)\npdfjs-bookmark-button-label = Current Page\npdfjs-tools-button =\n .title = Tools\npdfjs-tools-button-label = Tools\npdfjs-first-page-button =\n .title = Go to First Page\npdfjs-first-page-button-label = Go to First Page\npdfjs-last-page-button =\n .title = Go to Last Page\npdfjs-last-page-button-label = Go to Last Page\npdfjs-page-rotate-cw-button =\n .title = Rotate Clockwise\npdfjs-page-rotate-cw-button-label = Rotate Clockwise\npdfjs-page-rotate-ccw-button =\n .title = Rotate Counterclockwise\npdfjs-page-rotate-ccw-button-label = Rotate Counterclockwise\npdfjs-cursor-text-select-tool-button =\n .title = Enable Text Selection Tool\npdfjs-cursor-text-select-tool-button-label = Text Selection Tool\npdfjs-cursor-hand-tool-button =\n .title = Enable Hand Tool\npdfjs-cursor-hand-tool-button-label = Hand Tool\npdfjs-scroll-page-button =\n .title = Use Page Scrolling\npdfjs-scroll-page-button-label = Page Scrolling\npdfjs-scroll-vertical-button =\n .title = Use Vertical Scrolling\npdfjs-scroll-vertical-button-label = Vertical Scrolling\npdfjs-scroll-horizontal-button =\n .title = Use Horizontal Scrolling\npdfjs-scroll-horizontal-button-label = Horizontal Scrolling\npdfjs-scroll-wrapped-button =\n .title = Use Wrapped Scrolling\npdfjs-scroll-wrapped-button-label = Wrapped Scrolling\npdfjs-spread-none-button =\n .title = Do not join page spreads\npdfjs-spread-none-button-label = No Spreads\npdfjs-spread-odd-button =\n .title = Join page spreads starting with odd-numbered pages\npdfjs-spread-odd-button-label = Odd Spreads\npdfjs-spread-even-button =\n .title = Join page spreads starting with even-numbered pages\npdfjs-spread-even-button-label = Even Spreads\npdfjs-document-properties-button =\n .title = Document Properties\u2026\npdfjs-document-properties-button-label = Document Properties\u2026\npdfjs-document-properties-file-name = File name:\npdfjs-document-properties-file-size = File size:\npdfjs-document-properties-size-kb = { NUMBER($kb, maximumSignificantDigits: 3) } KB ({ $b } bytes)\npdfjs-document-properties-size-mb = { NUMBER($mb, maximumSignificantDigits: 3) } MB ({ $b } bytes)\npdfjs-document-properties-title = Title:\npdfjs-document-properties-author = Author:\npdfjs-document-properties-subject = Subject:\npdfjs-document-properties-keywords = Keywords:\npdfjs-document-properties-creation-date = Creation Date:\npdfjs-document-properties-modification-date = Modification Date:\npdfjs-document-properties-date-time-string = { DATETIME($dateObj, dateStyle: \"short\", timeStyle: \"medium\") }\npdfjs-document-properties-creator = Creator:\npdfjs-document-properties-producer = PDF Producer:\npdfjs-document-properties-version = PDF Version:\npdfjs-document-properties-page-count = Page Count:\npdfjs-document-properties-page-size = Page Size:\npdfjs-document-properties-page-size-unit-inches = in\npdfjs-document-properties-page-size-unit-millimeters = mm\npdfjs-document-properties-page-size-orientation-portrait = portrait\npdfjs-document-properties-page-size-orientation-landscape = landscape\npdfjs-document-properties-page-size-name-a-three = A3\npdfjs-document-properties-page-size-name-a-four = A4\npdfjs-document-properties-page-size-name-letter = Letter\npdfjs-document-properties-page-size-name-legal = Legal\npdfjs-document-properties-page-size-dimension-string = { $width } \xD7 { $height } { $unit } ({ $orientation })\npdfjs-document-properties-page-size-dimension-name-string = { $width } \xD7 { $height } { $unit } ({ $name }, { $orientation })\npdfjs-document-properties-linearized = Fast Web View:\npdfjs-document-properties-linearized-yes = Yes\npdfjs-document-properties-linearized-no = No\npdfjs-document-properties-close-button = Close\npdfjs-print-progress-message = Preparing document for printing\u2026\npdfjs-print-progress-percent = { $progress }%\npdfjs-print-progress-close-button = Cancel\npdfjs-printing-not-supported = Warning: Printing is not fully supported by this browser.\npdfjs-printing-not-ready = Warning: The PDF is not fully loaded for printing.\npdfjs-toggle-sidebar-button =\n .title = Toggle Sidebar\npdfjs-toggle-sidebar-notification-button =\n .title = Toggle Sidebar (document contains outline/attachments/layers)\npdfjs-toggle-sidebar-button-label = Toggle Sidebar\npdfjs-document-outline-button =\n .title = Show Document Outline (double-click to expand/collapse all items)\npdfjs-document-outline-button-label = Document Outline\npdfjs-attachments-button =\n .title = Show Attachments\npdfjs-attachments-button-label = Attachments\npdfjs-layers-button =\n .title = Show Layers (double-click to reset all layers to the default state)\npdfjs-layers-button-label = Layers\npdfjs-thumbs-button =\n .title = Show Thumbnails\npdfjs-thumbs-button-label = Thumbnails\npdfjs-current-outline-item-button =\n .title = Find Current Outline Item\npdfjs-current-outline-item-button-label = Current Outline Item\npdfjs-findbar-button =\n .title = Find in Document\npdfjs-findbar-button-label = Find\npdfjs-additional-layers = Additional Layers\npdfjs-thumb-page-title =\n .title = Page { $page }\npdfjs-thumb-page-canvas =\n .aria-label = Thumbnail of Page { $page }\npdfjs-find-input =\n .title = Find\n .placeholder = Find in document\u2026\npdfjs-find-previous-button =\n .title = Find the previous occurrence of the phrase\npdfjs-find-previous-button-label = Previous\npdfjs-find-next-button =\n .title = Find the next occurrence of the phrase\npdfjs-find-next-button-label = Next\npdfjs-find-highlight-checkbox = Highlight All\npdfjs-find-match-case-checkbox-label = Match Case\npdfjs-find-match-diacritics-checkbox-label = Match Diacritics\npdfjs-find-entire-word-checkbox-label = Whole Words\npdfjs-find-reached-top = Reached top of document, continued from bottom\npdfjs-find-reached-bottom = Reached end of document, continued from top\npdfjs-find-match-count =\n { $total ->\n [one] { $current } of { $total } match\n *[other] { $current } of { $total } matches\n }\npdfjs-find-match-count-limit =\n { $limit ->\n [one] More than { $limit } match\n *[other] More than { $limit } matches\n }\npdfjs-find-not-found = Phrase not found\npdfjs-page-scale-width = Page Width\npdfjs-page-scale-fit = Page Fit\npdfjs-page-scale-auto = Automatic Zoom\npdfjs-page-scale-actual = Actual Size\npdfjs-page-scale-percent = { $scale }%\npdfjs-page-landmark =\n .aria-label = Page { $page }\npdfjs-loading-error = An error occurred while loading the PDF.\npdfjs-invalid-file-error = Invalid or corrupted PDF file.\npdfjs-missing-file-error = Missing PDF file.\npdfjs-unexpected-response-error = Unexpected server response.\npdfjs-rendering-error = An error occurred while rendering the page.\npdfjs-annotation-date-time-string = { DATETIME($dateObj, dateStyle: \"short\", timeStyle: \"medium\") }\npdfjs-text-annotation-type =\n .alt = [{ $type } Annotation]\npdfjs-password-label = Enter the password to open this PDF file.\npdfjs-password-invalid = Invalid password. Please try again.\npdfjs-password-ok-button = OK\npdfjs-password-cancel-button = Cancel\npdfjs-web-fonts-disabled = Web fonts are disabled: unable to use embedded PDF fonts.\npdfjs-editor-free-text-button =\n .title = Text\npdfjs-editor-free-text-button-label = Text\npdfjs-editor-ink-button =\n .title = Draw\npdfjs-editor-ink-button-label = Draw\npdfjs-editor-stamp-button =\n .title = Add or edit images\npdfjs-editor-stamp-button-label = Add or edit images\npdfjs-editor-highlight-button =\n .title = Highlight\npdfjs-editor-highlight-button-label = Highlight\npdfjs-highlight-floating-button1 =\n .title = Highlight\n .aria-label = Highlight\npdfjs-highlight-floating-button-label = Highlight\npdfjs-editor-remove-ink-button =\n .title = Remove drawing\npdfjs-editor-remove-freetext-button =\n .title = Remove text\npdfjs-editor-remove-stamp-button =\n .title = Remove image\npdfjs-editor-remove-highlight-button =\n .title = Remove highlight\npdfjs-editor-free-text-color-input = Color\npdfjs-editor-free-text-size-input = Size\npdfjs-editor-ink-color-input = Color\npdfjs-editor-ink-thickness-input = Thickness\npdfjs-editor-ink-opacity-input = Opacity\npdfjs-editor-stamp-add-image-button =\n .title = Add image\npdfjs-editor-stamp-add-image-button-label = Add image\npdfjs-editor-free-highlight-thickness-input = Thickness\npdfjs-editor-free-highlight-thickness-title =\n .title = Change thickness when highlighting items other than text\npdfjs-free-text2 =\n .aria-label = Text Editor\n .default-content = Start typing\u2026\npdfjs-ink =\n .aria-label = Draw Editor\npdfjs-ink-canvas =\n .aria-label = User-created image\npdfjs-editor-alt-text-button =\n .aria-label = Alt text\npdfjs-editor-alt-text-button-label = Alt text\npdfjs-editor-alt-text-edit-button =\n .aria-label = Edit alt text\npdfjs-editor-alt-text-dialog-label = Choose an option\npdfjs-editor-alt-text-dialog-description = Alt text (alternative text) helps when people can\u2019t see the image or when it doesn\u2019t load.\npdfjs-editor-alt-text-add-description-label = Add a description\npdfjs-editor-alt-text-add-description-description = Aim for 1-2 sentences that describe the subject, setting, or actions.\npdfjs-editor-alt-text-mark-decorative-label = Mark as decorative\npdfjs-editor-alt-text-mark-decorative-description = This is used for ornamental images, like borders or watermarks.\npdfjs-editor-alt-text-cancel-button = Cancel\npdfjs-editor-alt-text-save-button = Save\npdfjs-editor-alt-text-decorative-tooltip = Marked as decorative\npdfjs-editor-alt-text-textarea =\n .placeholder = For example, \u201CA young man sits down at a table to eat a meal\u201D\npdfjs-editor-resizer-top-left =\n .aria-label = Top left corner \u2014 resize\npdfjs-editor-resizer-top-middle =\n .aria-label = Top middle \u2014 resize\npdfjs-editor-resizer-top-right =\n .aria-label = Top right corner \u2014 resize\npdfjs-editor-resizer-middle-right =\n .aria-label = Middle right \u2014 resize\npdfjs-editor-resizer-bottom-right =\n .aria-label = Bottom right corner \u2014 resize\npdfjs-editor-resizer-bottom-middle =\n .aria-label = Bottom middle \u2014 resize\npdfjs-editor-resizer-bottom-left =\n .aria-label = Bottom left corner \u2014 resize\npdfjs-editor-resizer-middle-left =\n .aria-label = Middle left \u2014 resize\npdfjs-editor-highlight-colorpicker-label = Highlight color\npdfjs-editor-colorpicker-button =\n .title = Change color\npdfjs-editor-colorpicker-dropdown =\n .aria-label = Color choices\npdfjs-editor-colorpicker-yellow =\n .title = Yellow\npdfjs-editor-colorpicker-green =\n .title = Green\npdfjs-editor-colorpicker-blue =\n .title = Blue\npdfjs-editor-colorpicker-pink =\n .title = Pink\npdfjs-editor-colorpicker-red =\n .title = Red\npdfjs-editor-highlight-show-all-button-label = Show all\npdfjs-editor-highlight-show-all-button =\n .title = Show all\npdfjs-editor-new-alt-text-dialog-edit-label = Edit alt text (image description)\npdfjs-editor-new-alt-text-dialog-add-label = Add alt text (image description)\npdfjs-editor-new-alt-text-textarea =\n .placeholder = Write your description here\u2026\npdfjs-editor-new-alt-text-description = Short description for people who can\u2019t see the image or when the image doesn\u2019t load.\npdfjs-editor-new-alt-text-disclaimer1 = This alt text was created automatically and may be inaccurate.\npdfjs-editor-new-alt-text-disclaimer-learn-more-url = Learn more\npdfjs-editor-new-alt-text-create-automatically-button-label = Create alt text automatically\npdfjs-editor-new-alt-text-not-now-button = Not now\npdfjs-editor-new-alt-text-error-title = Couldn\u2019t create alt text automatically\npdfjs-editor-new-alt-text-error-description = Please write your own alt text or try again later.\npdfjs-editor-new-alt-text-error-close-button = Close\npdfjs-editor-new-alt-text-ai-model-downloading-progress = Downloading alt text AI model ({ $downloadedSize } of { $totalSize } MB)\n .aria-valuetext = Downloading alt text AI model ({ $downloadedSize } of { $totalSize } MB)\npdfjs-editor-new-alt-text-added-button =\n .aria-label = Alt text added\npdfjs-editor-new-alt-text-added-button-label = Alt text added\npdfjs-editor-new-alt-text-missing-button =\n .aria-label = Missing alt text\npdfjs-editor-new-alt-text-missing-button-label = Missing alt text\npdfjs-editor-new-alt-text-to-review-button =\n .aria-label = Review alt text\npdfjs-editor-new-alt-text-to-review-button-label = Review alt text\npdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer = Created automatically: { $generatedAltText }\npdfjs-image-alt-text-settings-button =\n .title = Image alt text settings\npdfjs-image-alt-text-settings-button-label = Image alt text settings\npdfjs-editor-alt-text-settings-dialog-label = Image alt text settings\npdfjs-editor-alt-text-settings-automatic-title = Automatic alt text\npdfjs-editor-alt-text-settings-create-model-button-label = Create alt text automatically\npdfjs-editor-alt-text-settings-create-model-description = Suggests descriptions to help people who can\u2019t see the image or when the image doesn\u2019t load.\npdfjs-editor-alt-text-settings-download-model-label = Alt text AI model ({ $totalSize } MB)\npdfjs-editor-alt-text-settings-ai-model-description = Runs locally on your device so your data stays private. Required for automatic alt text.\npdfjs-editor-alt-text-settings-delete-model-button = Delete\npdfjs-editor-alt-text-settings-download-model-button = Download\npdfjs-editor-alt-text-settings-downloading-model-button = Downloading\u2026\npdfjs-editor-alt-text-settings-editor-title = Alt text editor\npdfjs-editor-alt-text-settings-show-dialog-button-label = Show alt text editor right away when adding an image\npdfjs-editor-alt-text-settings-show-dialog-description = Helps you make sure all your images have alt text.\npdfjs-editor-alt-text-settings-close-button = Close\npdfjs-editor-undo-bar-message-highlight = Highlight removed\npdfjs-editor-undo-bar-message-freetext = Text removed\npdfjs-editor-undo-bar-message-ink = Drawing removed\npdfjs-editor-undo-bar-message-stamp = Image removed\npdfjs-editor-undo-bar-message-multiple =\n { $count ->\n [one] { $count } annotation removed\n *[other] { $count } annotations removed\n }\npdfjs-editor-undo-bar-undo-button =\n .title = Undo\npdfjs-editor-undo-bar-undo-button-label = Undo\npdfjs-editor-undo-bar-close-button =\n .title = Close\npdfjs-editor-undo-bar-close-button-label = Close"; - return createBundle(lang, text); - } -} - -;// ./web/pdf_history.js - - -const HASH_CHANGE_TIMEOUT = 1000; -const POSITION_UPDATED_THRESHOLD = 50; -const UPDATE_VIEWAREA_TIMEOUT = 1000; -function getCurrentHash() { - return document.location.hash; -} -class PDFHistory { - #eventAbortController = null; - constructor({ - linkService, - eventBus - }) { - this.linkService = linkService; - this.eventBus = eventBus; - this._initialized = false; - this._fingerprint = ""; - this.reset(); - this.eventBus._on("pagesinit", () => { - this._isPagesLoaded = false; - this.eventBus._on("pagesloaded", evt => { - this._isPagesLoaded = !!evt.pagesCount; - }, { - once: true - }); - }); - } - initialize({ - fingerprint, - resetHistory = false, - updateUrl = false - }) { - if (!fingerprint || typeof fingerprint !== "string") { - console.error('PDFHistory.initialize: The "fingerprint" must be a non-empty string.'); - return; - } - if (this._initialized) { - this.reset(); - } - const reInitialized = this._fingerprint !== "" && this._fingerprint !== fingerprint; - this._fingerprint = fingerprint; - this._updateUrl = updateUrl === true; - this._initialized = true; - this.#bindEvents(); - const state = window.history.state; - this._popStateInProgress = false; - this._blockHashChange = 0; - this._currentHash = getCurrentHash(); - this._numPositionUpdates = 0; - this._uid = this._maxUid = 0; - this._destination = null; - this._position = null; - if (!this.#isValidState(state, true) || resetHistory) { - const { - hash, - page, - rotation - } = this.#parseCurrentHash(true); - if (!hash || reInitialized || resetHistory) { - this.#pushOrReplaceState(null, true); - return; - } - this.#pushOrReplaceState({ - hash, - page, - rotation - }, true); - return; - } - const destination = state.destination; - this.#updateInternalState(destination, state.uid, true); - if (destination.rotation !== undefined) { - this._initialRotation = destination.rotation; - } - if (destination.dest) { - this._initialBookmark = JSON.stringify(destination.dest); - this._destination.page = null; - } else if (destination.hash) { - this._initialBookmark = destination.hash; - } else if (destination.page) { - this._initialBookmark = `page=${destination.page}`; - } - } - reset() { - if (this._initialized) { - this.#pageHide(); - this._initialized = false; - this.#unbindEvents(); - } - if (this._updateViewareaTimeout) { - clearTimeout(this._updateViewareaTimeout); - this._updateViewareaTimeout = null; - } - this._initialBookmark = null; - this._initialRotation = null; - } - push({ - namedDest = null, - explicitDest, - pageNumber - }) { - if (!this._initialized) { - return; - } - if (namedDest && typeof namedDest !== "string") { - console.error("PDFHistory.push: " + `"${namedDest}" is not a valid namedDest parameter.`); - return; - } else if (!Array.isArray(explicitDest)) { - console.error("PDFHistory.push: " + `"${explicitDest}" is not a valid explicitDest parameter.`); - return; - } else if (!this.#isValidPage(pageNumber)) { - if (pageNumber !== null || this._destination) { - console.error("PDFHistory.push: " + `"${pageNumber}" is not a valid pageNumber parameter.`); - return; - } - } - const hash = namedDest || JSON.stringify(explicitDest); - if (!hash) { - return; - } - let forceReplace = false; - if (this._destination && (isDestHashesEqual(this._destination.hash, hash) || isDestArraysEqual(this._destination.dest, explicitDest))) { - if (this._destination.page) { - return; - } - forceReplace = true; - } - if (this._popStateInProgress && !forceReplace) { - return; - } - this.#pushOrReplaceState({ - dest: explicitDest, - hash, - page: pageNumber, - rotation: this.linkService.rotation - }, forceReplace); - if (!this._popStateInProgress) { - this._popStateInProgress = true; - Promise.resolve().then(() => { - this._popStateInProgress = false; - }); - } - } - pushPage(pageNumber) { - if (!this._initialized) { - return; - } - if (!this.#isValidPage(pageNumber)) { - console.error(`PDFHistory.pushPage: "${pageNumber}" is not a valid page number.`); - return; - } - if (this._destination?.page === pageNumber) { - return; - } - if (this._popStateInProgress) { - return; - } - this.#pushOrReplaceState({ - dest: null, - hash: `page=${pageNumber}`, - page: pageNumber, - rotation: this.linkService.rotation - }); - if (!this._popStateInProgress) { - this._popStateInProgress = true; - Promise.resolve().then(() => { - this._popStateInProgress = false; - }); - } - } - pushCurrentPosition() { - if (!this._initialized || this._popStateInProgress) { - return; - } - this.#tryPushCurrentPosition(); - } - back() { - if (!this._initialized || this._popStateInProgress) { - return; - } - const state = window.history.state; - if (this.#isValidState(state) && state.uid > 0) { - window.history.back(); - } - } - forward() { - if (!this._initialized || this._popStateInProgress) { - return; - } - const state = window.history.state; - if (this.#isValidState(state) && state.uid < this._maxUid) { - window.history.forward(); - } - } - get popStateInProgress() { - return this._initialized && (this._popStateInProgress || this._blockHashChange > 0); - } - get initialBookmark() { - return this._initialized ? this._initialBookmark : null; - } - get initialRotation() { - return this._initialized ? this._initialRotation : null; - } - #pushOrReplaceState(destination, forceReplace = false) { - const shouldReplace = forceReplace || !this._destination; - const newState = { - fingerprint: this._fingerprint, - uid: shouldReplace ? this._uid : this._uid + 1, - destination - }; - this.#updateInternalState(destination, newState.uid); - let newUrl; - if (this._updateUrl && destination?.hash) { - const baseUrl = document.location.href.split("#", 1)[0]; - if (!baseUrl.startsWith("file://")) { - newUrl = `${baseUrl}#${destination.hash}`; - } - } - if (shouldReplace) { - window.history.replaceState(newState, "", newUrl); - } else { - window.history.pushState(newState, "", newUrl); - } - } - #tryPushCurrentPosition(temporary = false) { - if (!this._position) { - return; - } - let position = this._position; - if (temporary) { - position = Object.assign(Object.create(null), this._position); - position.temporary = true; - } - if (!this._destination) { - this.#pushOrReplaceState(position); - return; - } - if (this._destination.temporary) { - this.#pushOrReplaceState(position, true); - return; - } - if (this._destination.hash === position.hash) { - return; - } - if (!this._destination.page && (POSITION_UPDATED_THRESHOLD <= 0 || this._numPositionUpdates <= POSITION_UPDATED_THRESHOLD)) { - return; - } - let forceReplace = false; - if (this._destination.page >= position.first && this._destination.page <= position.page) { - if (this._destination.dest !== undefined || !this._destination.first) { - return; - } - forceReplace = true; - } - this.#pushOrReplaceState(position, forceReplace); - } - #isValidPage(val) { - return Number.isInteger(val) && val > 0 && val <= this.linkService.pagesCount; - } - #isValidState(state, checkReload = false) { - if (!state) { - return false; - } - if (state.fingerprint !== this._fingerprint) { - if (checkReload) { - if (typeof state.fingerprint !== "string" || state.fingerprint.length !== this._fingerprint.length) { - return false; - } - const [perfEntry] = performance.getEntriesByType("navigation"); - if (perfEntry?.type !== "reload") { - return false; - } - } else { - return false; - } - } - if (!Number.isInteger(state.uid) || state.uid < 0) { - return false; - } - if (state.destination === null || typeof state.destination !== "object") { - return false; - } - return true; - } - #updateInternalState(destination, uid, removeTemporary = false) { - if (this._updateViewareaTimeout) { - clearTimeout(this._updateViewareaTimeout); - this._updateViewareaTimeout = null; - } - if (removeTemporary && destination?.temporary) { - delete destination.temporary; - } - this._destination = destination; - this._uid = uid; - this._maxUid = Math.max(this._maxUid, uid); - this._numPositionUpdates = 0; - } - #parseCurrentHash(checkNameddest = false) { - const hash = unescape(getCurrentHash()).substring(1); - const params = parseQueryString(hash); - const nameddest = params.get("nameddest") || ""; - let page = params.get("page") | 0; - if (!this.#isValidPage(page) || checkNameddest && nameddest.length > 0) { - page = null; - } - return { - hash, - page, - rotation: this.linkService.rotation - }; - } - #updateViewarea({ - location - }) { - if (this._updateViewareaTimeout) { - clearTimeout(this._updateViewareaTimeout); - this._updateViewareaTimeout = null; - } - this._position = { - hash: location.pdfOpenParams.substring(1), - page: this.linkService.page, - first: location.pageNumber, - rotation: location.rotation - }; - if (this._popStateInProgress) { - return; - } - if (POSITION_UPDATED_THRESHOLD > 0 && this._isPagesLoaded && this._destination && !this._destination.page) { - this._numPositionUpdates++; - } - if (UPDATE_VIEWAREA_TIMEOUT > 0) { - this._updateViewareaTimeout = setTimeout(() => { - if (!this._popStateInProgress) { - this.#tryPushCurrentPosition(true); - } - this._updateViewareaTimeout = null; - }, UPDATE_VIEWAREA_TIMEOUT); - } - } - #popState({ - state - }) { - const newHash = getCurrentHash(), - hashChanged = this._currentHash !== newHash; - this._currentHash = newHash; - if (!state) { - this._uid++; - const { - hash, - page, - rotation - } = this.#parseCurrentHash(); - this.#pushOrReplaceState({ - hash, - page, - rotation - }, true); - return; - } - if (!this.#isValidState(state)) { - return; - } - this._popStateInProgress = true; - if (hashChanged) { - this._blockHashChange++; - waitOnEventOrTimeout({ - target: window, - name: "hashchange", - delay: HASH_CHANGE_TIMEOUT - }).then(() => { - this._blockHashChange--; - }); - } - const destination = state.destination; - this.#updateInternalState(destination, state.uid, true); - if (isValidRotation(destination.rotation)) { - this.linkService.rotation = destination.rotation; - } - if (destination.dest) { - this.linkService.goToDestination(destination.dest); - } else if (destination.hash) { - this.linkService.setHash(destination.hash); - } else if (destination.page) { - this.linkService.page = destination.page; - } - Promise.resolve().then(() => { - this._popStateInProgress = false; - }); - } - #pageHide() { - if (!this._destination || this._destination.temporary) { - this.#tryPushCurrentPosition(); - } - } - #bindEvents() { - if (this.#eventAbortController) { - return; - } - this.#eventAbortController = new AbortController(); - const { - signal - } = this.#eventAbortController; - this.eventBus._on("updateviewarea", this.#updateViewarea.bind(this), { - signal - }); - window.addEventListener("popstate", this.#popState.bind(this), { - signal - }); - window.addEventListener("pagehide", this.#pageHide.bind(this), { - signal - }); - } - #unbindEvents() { - this.#eventAbortController?.abort(); - this.#eventAbortController = null; - } -} -function isDestHashesEqual(destHash, pushHash) { - if (typeof destHash !== "string" || typeof pushHash !== "string") { - return false; - } - if (destHash === pushHash) { - return true; - } - const nameddest = parseQueryString(destHash).get("nameddest"); - if (nameddest === pushHash) { - return true; - } - return false; -} -function isDestArraysEqual(firstDest, secondDest) { - function isEntryEqual(first, second) { - if (typeof first !== typeof second) { - return false; - } - if (Array.isArray(first) || Array.isArray(second)) { - return false; - } - if (first !== null && typeof first === "object" && second !== null) { - if (Object.keys(first).length !== Object.keys(second).length) { - return false; - } - for (const key in first) { - if (!isEntryEqual(first[key], second[key])) { - return false; - } - } - return true; - } - return first === second || Number.isNaN(first) && Number.isNaN(second); - } - if (!(Array.isArray(firstDest) && Array.isArray(secondDest))) { - return false; - } - if (firstDest.length !== secondDest.length) { - return false; - } - for (let i = 0, ii = firstDest.length; i < ii; i++) { - if (!isEntryEqual(firstDest[i], secondDest[i])) { - return false; - } - } - return true; -} - -;// ./web/annotation_editor_layer_builder.js - - -class AnnotationEditorLayerBuilder { - #annotationLayer = null; - #drawLayer = null; - #onAppend = null; - #structTreeLayer = null; - #textLayer = null; - #uiManager; - constructor(options) { - this.pdfPage = options.pdfPage; - this.accessibilityManager = options.accessibilityManager; - this.l10n = options.l10n; - this.l10n ||= new genericl10n_GenericL10n(); - this.annotationEditorLayer = null; - this.div = null; - this._cancelled = false; - this.#uiManager = options.uiManager; - this.#annotationLayer = options.annotationLayer || null; - this.#textLayer = options.textLayer || null; - this.#drawLayer = options.drawLayer || null; - this.#onAppend = options.onAppend || null; - this.#structTreeLayer = options.structTreeLayer || null; - } - async render(viewport, intent = "display") { - if (intent !== "display") { - return; - } - if (this._cancelled) { - return; - } - const clonedViewport = viewport.clone({ - dontFlip: true - }); - if (this.div) { - this.annotationEditorLayer.update({ - viewport: clonedViewport - }); - this.show(); - return; - } - const div = this.div = document.createElement("div"); - div.className = "annotationEditorLayer"; - div.hidden = true; - div.dir = this.#uiManager.direction; - this.#onAppend?.(div); - this.annotationEditorLayer = new AnnotationEditorLayer({ - uiManager: this.#uiManager, - div, - structTreeLayer: this.#structTreeLayer, - accessibilityManager: this.accessibilityManager, - pageIndex: this.pdfPage.pageNumber - 1, - l10n: this.l10n, - viewport: clonedViewport, - annotationLayer: this.#annotationLayer, - textLayer: this.#textLayer, - drawLayer: this.#drawLayer - }); - const parameters = { - viewport: clonedViewport, - div, - annotations: null, - intent - }; - this.annotationEditorLayer.render(parameters); - this.show(); - } - cancel() { - this._cancelled = true; - if (!this.div) { - return; - } - this.annotationEditorLayer.destroy(); - } - hide() { - if (!this.div) { - return; - } - this.annotationEditorLayer.pause(true); - this.div.hidden = true; - } - show() { - if (!this.div || this.annotationEditorLayer.isInvisible) { - return; - } - this.div.hidden = false; - this.annotationEditorLayer.pause(false); - } -} - -;// ./web/app_options.js -{ - var compatParams = new Map(); - const userAgent = navigator.userAgent || ""; - const platform = navigator.platform || ""; - const maxTouchPoints = navigator.maxTouchPoints || 1; - const isAndroid = /Android/.test(userAgent); - const isIOS = /\b(iPad|iPhone|iPod)(?=;)/.test(userAgent) || platform === "MacIntel" && maxTouchPoints > 1; - (function () { - if (isIOS || isAndroid) { - compatParams.set("maxCanvasPixels", 5242880); - } - })(); - (function () { - if (isAndroid) { - compatParams.set("useSystemFonts", false); - } - })(); -} -const OptionKind = { - BROWSER: 0x01, - VIEWER: 0x02, - API: 0x04, - WORKER: 0x08, - EVENT_DISPATCH: 0x10, - PREFERENCE: 0x80 -}; -const Type = { - BOOLEAN: 0x01, - NUMBER: 0x02, - OBJECT: 0x04, - STRING: 0x08, - UNDEFINED: 0x10 -}; -const defaultOptions = { - allowedGlobalEvents: { - value: null, - kind: OptionKind.BROWSER - }, - canvasMaxAreaInBytes: { - value: -1, - kind: OptionKind.BROWSER + OptionKind.API - }, - isInAutomation: { - value: false, - kind: OptionKind.BROWSER - }, - localeProperties: { - value: { - lang: navigator.language || "en-US" - }, - kind: OptionKind.BROWSER - }, - nimbusDataStr: { - value: "", - kind: OptionKind.BROWSER - }, - supportsCaretBrowsingMode: { - value: false, - kind: OptionKind.BROWSER - }, - supportsDocumentFonts: { - value: true, - kind: OptionKind.BROWSER - }, - supportsIntegratedFind: { - value: false, - kind: OptionKind.BROWSER - }, - supportsMouseWheelZoomCtrlKey: { - value: true, - kind: OptionKind.BROWSER - }, - supportsMouseWheelZoomMetaKey: { - value: true, - kind: OptionKind.BROWSER - }, - supportsPinchToZoom: { - value: true, - kind: OptionKind.BROWSER - }, - toolbarDensity: { - value: 0, - kind: OptionKind.BROWSER + OptionKind.EVENT_DISPATCH - }, - altTextLearnMoreUrl: { - value: "", - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - annotationEditorMode: { - value: 0, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - annotationMode: { - value: 2, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - cursorToolOnLoad: { - value: 0, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - debuggerSrc: { - value: "./debugger.mjs", - kind: OptionKind.VIEWER - }, - defaultZoomDelay: { - value: 400, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - defaultZoomValue: { - value: "", - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - disableHistory: { - value: false, - kind: OptionKind.VIEWER - }, - disablePageLabels: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enableAltText: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enableAltTextModelDownload: { - value: true, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE + OptionKind.EVENT_DISPATCH - }, - enableGuessAltText: { - value: true, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE + OptionKind.EVENT_DISPATCH - }, - enableHighlightFloatingButton: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enableNewAltTextWhenAddingImage: { - value: true, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enablePermissions: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enablePrintAutoRotate: { - value: true, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enableScripting: { - value: true, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enableUpdatedAddImage: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - externalLinkRel: { - value: "noopener noreferrer nofollow", - kind: OptionKind.VIEWER - }, - externalLinkTarget: { - value: 0, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - highlightEditorColors: { - value: "yellow=#FFFF98,green=#53FFBC,blue=#80EBFF,pink=#FFCBE6,red=#FF4F5F", - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - historyUpdateUrl: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - ignoreDestinationZoom: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - imageResourcesPath: { - value: "./images/", - kind: OptionKind.VIEWER - }, - maxCanvasPixels: { - value: 2 ** 25, - kind: OptionKind.VIEWER - }, - forcePageColors: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - pageColorsBackground: { - value: "Canvas", - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - pageColorsForeground: { - value: "CanvasText", - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - pdfBugEnabled: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - printResolution: { - value: 150, - kind: OptionKind.VIEWER - }, - sidebarViewOnLoad: { - value: -1, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - scrollModeOnLoad: { - value: -1, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - spreadModeOnLoad: { - value: -1, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - textLayerMode: { - value: 1, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - viewOnLoad: { - value: 0, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - cMapPacked: { - value: true, - kind: OptionKind.API - }, - cMapUrl: { - value: "../web/cmaps/", - kind: OptionKind.API - }, - disableAutoFetch: { - value: false, - kind: OptionKind.API + OptionKind.PREFERENCE - }, - disableFontFace: { - value: false, - kind: OptionKind.API + OptionKind.PREFERENCE - }, - disableRange: { - value: false, - kind: OptionKind.API + OptionKind.PREFERENCE - }, - disableStream: { - value: false, - kind: OptionKind.API + OptionKind.PREFERENCE - }, - docBaseUrl: { - value: "", - kind: OptionKind.API - }, - enableHWA: { - value: true, - kind: OptionKind.API + OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enableXfa: { - value: true, - kind: OptionKind.API + OptionKind.PREFERENCE - }, - fontExtraProperties: { - value: false, - kind: OptionKind.API - }, - isEvalSupported: { - value: true, - kind: OptionKind.API - }, - isOffscreenCanvasSupported: { - value: true, - kind: OptionKind.API - }, - maxImageSize: { - value: -1, - kind: OptionKind.API - }, - pdfBug: { - value: false, - kind: OptionKind.API - }, - standardFontDataUrl: { - value: "../web/standard_fonts/", - kind: OptionKind.API - }, - useSystemFonts: { - value: undefined, - kind: OptionKind.API, - type: Type.BOOLEAN + Type.UNDEFINED - }, - verbosity: { - value: 1, - kind: OptionKind.API - }, - workerPort: { - value: null, - kind: OptionKind.WORKER - }, - workerSrc: { - value: "../build/pdf.worker.mjs", - kind: OptionKind.WORKER - } -}; -{ - defaultOptions.defaultUrl = { - value: "compressed.tracemonkey-pldi-09.pdf", - kind: OptionKind.VIEWER - }; - defaultOptions.sandboxBundleSrc = { - value: "../build/pdf.sandbox.mjs", - kind: OptionKind.VIEWER - }; - defaultOptions.viewerCssTheme = { - value: 0, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }; - defaultOptions.enableFakeMLManager = { - value: true, - kind: OptionKind.VIEWER - }; -} -{ - defaultOptions.disablePreferences = { - value: false, - kind: OptionKind.VIEWER - }; -} -class AppOptions { - static eventBus; - static #opts = new Map(); - static { - for (const name in defaultOptions) { - this.#opts.set(name, defaultOptions[name].value); - } - for (const [name, value] of compatParams) { - this.#opts.set(name, value); - } - this._hasInvokedSet = false; - this._checkDisablePreferences = () => { - if (this.get("disablePreferences")) { - return true; - } - if (this._hasInvokedSet) { - console.warn("The Preferences may override manually set AppOptions; " + 'please use the "disablePreferences"-option to prevent that.'); - } - return false; - }; - } - static get(name) { - return this.#opts.get(name); - } - static getAll(kind = null, defaultOnly = false) { - const options = Object.create(null); - for (const name in defaultOptions) { - const defaultOpt = defaultOptions[name]; - if (kind && !(kind & defaultOpt.kind)) { - continue; - } - options[name] = !defaultOnly ? this.#opts.get(name) : defaultOpt.value; - } - return options; - } - static set(name, value) { - this.setAll({ - [name]: value - }); - } - static setAll(options, prefs = false) { - this._hasInvokedSet ||= true; - let events; - for (const name in options) { - const defaultOpt = defaultOptions[name], - userOpt = options[name]; - if (!defaultOpt || !(typeof userOpt === typeof defaultOpt.value || Type[(typeof userOpt).toUpperCase()] & defaultOpt.type)) { - continue; - } - const { - kind - } = defaultOpt; - if (prefs && !(kind & OptionKind.BROWSER || kind & OptionKind.PREFERENCE)) { - continue; - } - if (this.eventBus && kind & OptionKind.EVENT_DISPATCH) { - (events ||= new Map()).set(name, userOpt); - } - this.#opts.set(name, userOpt); - } - if (events) { - for (const [name, value] of events) { - this.eventBus.dispatch(name.toLowerCase(), { - source: this, - value - }); - } - } - } -} - -;// ./web/draw_layer_builder.js - -class DrawLayerBuilder { - #drawLayer = null; - constructor(options) { - this.pageIndex = options.pageIndex; - } - async render(intent = "display") { - if (intent !== "display" || this.#drawLayer || this._cancelled) { - return; - } - this.#drawLayer = new DrawLayer({ - pageIndex: this.pageIndex - }); - } - cancel() { - this._cancelled = true; - if (!this.#drawLayer) { - return; - } - this.#drawLayer.destroy(); - this.#drawLayer = null; - } - setParent(parent) { - this.#drawLayer?.setParent(parent); - } - getDrawLayer() { - return this.#drawLayer; - } -} - -;// ./web/struct_tree_layer_builder.js - -const PDF_ROLE_TO_HTML_ROLE = { - Document: null, - DocumentFragment: null, - Part: "group", - Sect: "group", - Div: "group", - Aside: "note", - NonStruct: "none", - P: null, - H: "heading", - Title: null, - FENote: "note", - Sub: "group", - Lbl: null, - Span: null, - Em: null, - Strong: null, - Link: "link", - Annot: "note", - Form: "form", - Ruby: null, - RB: null, - RT: null, - RP: null, - Warichu: null, - WT: null, - WP: null, - L: "list", - LI: "listitem", - LBody: null, - Table: "table", - TR: "row", - TH: "columnheader", - TD: "cell", - THead: "columnheader", - TBody: null, - TFoot: null, - Caption: null, - Figure: "figure", - Formula: null, - Artifact: null -}; -const HEADING_PATTERN = /^H(\d+)$/; -class StructTreeLayerBuilder { - #promise; - #treeDom = null; - #treePromise; - #elementAttributes = new Map(); - #rawDims; - #elementsToAddToTextLayer = null; - constructor(pdfPage, rawDims) { - this.#promise = pdfPage.getStructTree(); - this.#rawDims = rawDims; - } - async render() { - if (this.#treePromise) { - return this.#treePromise; - } - const { - promise, - resolve, - reject - } = Promise.withResolvers(); - this.#treePromise = promise; - try { - this.#treeDom = this.#walk(await this.#promise); - } catch (ex) { - reject(ex); - } - this.#promise = null; - this.#treeDom?.classList.add("structTree"); - resolve(this.#treeDom); - return promise; - } - async getAriaAttributes(annotationId) { - try { - await this.render(); - return this.#elementAttributes.get(annotationId); - } catch {} - return null; - } - hide() { - if (this.#treeDom && !this.#treeDom.hidden) { - this.#treeDom.hidden = true; - } - } - show() { - if (this.#treeDom?.hidden) { - this.#treeDom.hidden = false; - } - } - #setAttributes(structElement, htmlElement) { - const { - alt, - id, - lang - } = structElement; - if (alt !== undefined) { - let added = false; - const label = removeNullCharacters(alt); - for (const child of structElement.children) { - if (child.type === "annotation") { - let attrs = this.#elementAttributes.get(child.id); - if (!attrs) { - attrs = new Map(); - this.#elementAttributes.set(child.id, attrs); - } - attrs.set("aria-label", label); - added = true; - } - } - if (!added) { - htmlElement.setAttribute("aria-label", label); - } - } - if (id !== undefined) { - htmlElement.setAttribute("aria-owns", id); - } - if (lang !== undefined) { - htmlElement.setAttribute("lang", removeNullCharacters(lang, true)); - } - } - #addImageInTextLayer(node, element) { - const { - alt, - bbox, - children - } = node; - const child = children?.[0]; - if (!this.#rawDims || !alt || !bbox || child?.type !== "content") { - return false; - } - const { - id - } = child; - if (!id) { - return false; - } - element.setAttribute("aria-owns", id); - const img = document.createElement("span"); - (this.#elementsToAddToTextLayer ||= new Map()).set(id, img); - img.setAttribute("role", "img"); - img.setAttribute("aria-label", removeNullCharacters(alt)); - const { - pageHeight, - pageX, - pageY - } = this.#rawDims; - const calc = "calc(var(--scale-factor)*"; - const { - style - } = img; - style.width = `${calc}${bbox[2] - bbox[0]}px)`; - style.height = `${calc}${bbox[3] - bbox[1]}px)`; - style.left = `${calc}${bbox[0] - pageX}px)`; - style.top = `${calc}${pageHeight - bbox[3] + pageY}px)`; - return true; - } - addElementsToTextLayer() { - if (!this.#elementsToAddToTextLayer) { - return; - } - for (const [id, img] of this.#elementsToAddToTextLayer) { - document.getElementById(id)?.append(img); - } - this.#elementsToAddToTextLayer.clear(); - this.#elementsToAddToTextLayer = null; - } - #walk(node) { - if (!node) { - return null; - } - const element = document.createElement("span"); - if ("role" in node) { - const { - role - } = node; - const match = role.match(HEADING_PATTERN); - if (match) { - element.setAttribute("role", "heading"); - element.setAttribute("aria-level", match[1]); - } else if (PDF_ROLE_TO_HTML_ROLE[role]) { - element.setAttribute("role", PDF_ROLE_TO_HTML_ROLE[role]); - } - if (role === "Figure" && this.#addImageInTextLayer(node, element)) { - return element; - } - } - this.#setAttributes(node, element); - if (node.children) { - if (node.children.length === 1 && "id" in node.children[0]) { - this.#setAttributes(node.children[0], element); - } else { - for (const kid of node.children) { - element.append(this.#walk(kid)); - } - } - } - return element; - } -} - -;// ./web/text_accessibility.js - -class TextAccessibilityManager { - #enabled = false; - #textChildren = null; - #textNodes = new Map(); - #waitingElements = new Map(); - setTextMapping(textDivs) { - this.#textChildren = textDivs; - } - static #compareElementPositions(e1, e2) { - const rect1 = e1.getBoundingClientRect(); - const rect2 = e2.getBoundingClientRect(); - if (rect1.width === 0 && rect1.height === 0) { - return +1; - } - if (rect2.width === 0 && rect2.height === 0) { - return -1; - } - const top1 = rect1.y; - const bot1 = rect1.y + rect1.height; - const mid1 = rect1.y + rect1.height / 2; - const top2 = rect2.y; - const bot2 = rect2.y + rect2.height; - const mid2 = rect2.y + rect2.height / 2; - if (mid1 <= top2 && mid2 >= bot1) { - return -1; - } - if (mid2 <= top1 && mid1 >= bot2) { - return +1; - } - const centerX1 = rect1.x + rect1.width / 2; - const centerX2 = rect2.x + rect2.width / 2; - return centerX1 - centerX2; - } - enable() { - if (this.#enabled) { - throw new Error("TextAccessibilityManager is already enabled."); - } - if (!this.#textChildren) { - throw new Error("Text divs and strings have not been set."); - } - this.#enabled = true; - this.#textChildren = this.#textChildren.slice(); - this.#textChildren.sort(TextAccessibilityManager.#compareElementPositions); - if (this.#textNodes.size > 0) { - const textChildren = this.#textChildren; - for (const [id, nodeIndex] of this.#textNodes) { - const element = document.getElementById(id); - if (!element) { - this.#textNodes.delete(id); - continue; - } - this.#addIdToAriaOwns(id, textChildren[nodeIndex]); - } - } - for (const [element, isRemovable] of this.#waitingElements) { - this.addPointerInTextLayer(element, isRemovable); - } - this.#waitingElements.clear(); - } - disable() { - if (!this.#enabled) { - return; - } - this.#waitingElements.clear(); - this.#textChildren = null; - this.#enabled = false; - } - removePointerInTextLayer(element) { - if (!this.#enabled) { - this.#waitingElements.delete(element); - return; - } - const children = this.#textChildren; - if (!children || children.length === 0) { - return; - } - const { - id - } = element; - const nodeIndex = this.#textNodes.get(id); - if (nodeIndex === undefined) { - return; - } - const node = children[nodeIndex]; - this.#textNodes.delete(id); - let owns = node.getAttribute("aria-owns"); - if (owns?.includes(id)) { - owns = owns.split(" ").filter(x => x !== id).join(" "); - if (owns) { - node.setAttribute("aria-owns", owns); - } else { - node.removeAttribute("aria-owns"); - node.setAttribute("role", "presentation"); - } - } - } - #addIdToAriaOwns(id, node) { - const owns = node.getAttribute("aria-owns"); - if (!owns?.includes(id)) { - node.setAttribute("aria-owns", owns ? `${owns} ${id}` : id); - } - node.removeAttribute("role"); - } - addPointerInTextLayer(element, isRemovable) { - const { - id - } = element; - if (!id) { - return null; - } - if (!this.#enabled) { - this.#waitingElements.set(element, isRemovable); - return null; - } - if (isRemovable) { - this.removePointerInTextLayer(element); - } - const children = this.#textChildren; - if (!children || children.length === 0) { - return null; - } - const index = binarySearchFirstItem(children, node => TextAccessibilityManager.#compareElementPositions(element, node) < 0); - const nodeIndex = Math.max(0, index - 1); - const child = children[nodeIndex]; - this.#addIdToAriaOwns(id, child); - this.#textNodes.set(id, nodeIndex); - const parent = child.parentNode; - return parent?.classList.contains("markedContent") ? parent.id : null; - } - moveElementInDOM(container, element, contentElement, isRemovable) { - const id = this.addPointerInTextLayer(contentElement, isRemovable); - if (!container.hasChildNodes()) { - container.append(element); - return id; - } - const children = Array.from(container.childNodes).filter(node => node !== element); - if (children.length === 0) { - return id; - } - const elementToCompare = contentElement || element; - const index = binarySearchFirstItem(children, node => TextAccessibilityManager.#compareElementPositions(elementToCompare, node) < 0); - if (index === 0) { - children[0].before(element); - } else { - children[index - 1].after(element); - } - return id; - } -} - -;// ./web/text_highlighter.js -class TextHighlighter { - #eventAbortController = null; - constructor({ - findController, - eventBus, - pageIndex - }) { - this.findController = findController; - this.matches = []; - this.eventBus = eventBus; - this.pageIdx = pageIndex; - this.textDivs = null; - this.textContentItemsStr = null; - this.enabled = false; - } - setTextMapping(divs, texts) { - this.textDivs = divs; - this.textContentItemsStr = texts; - } - enable() { - if (!this.textDivs || !this.textContentItemsStr) { - throw new Error("Text divs and strings have not been set."); - } - if (this.enabled) { - throw new Error("TextHighlighter is already enabled."); - } - this.enabled = true; - if (!this.#eventAbortController) { - this.#eventAbortController = new AbortController(); - this.eventBus._on("updatetextlayermatches", evt => { - if (evt.pageIndex === this.pageIdx || evt.pageIndex === -1) { - this._updateMatches(); - } - }, { - signal: this.#eventAbortController.signal - }); - } - this._updateMatches(); - } - disable() { - if (!this.enabled) { - return; - } - this.enabled = false; - this.#eventAbortController?.abort(); - this.#eventAbortController = null; - this._updateMatches(true); - } - _convertMatches(matches, matchesLength) { - if (!matches) { - return []; - } - const { - textContentItemsStr - } = this; - let i = 0, - iIndex = 0; - const end = textContentItemsStr.length - 1; - const result = []; - for (let m = 0, mm = matches.length; m < mm; m++) { - let matchIdx = matches[m]; - while (i !== end && matchIdx >= iIndex + textContentItemsStr[i].length) { - iIndex += textContentItemsStr[i].length; - i++; - } - if (i === textContentItemsStr.length) { - console.error("Could not find a matching mapping"); - } - const match = { - begin: { - divIdx: i, - offset: matchIdx - iIndex - } - }; - matchIdx += matchesLength[m]; - while (i !== end && matchIdx > iIndex + textContentItemsStr[i].length) { - iIndex += textContentItemsStr[i].length; - i++; - } - match.end = { - divIdx: i, - offset: matchIdx - iIndex - }; - result.push(match); - } - return result; - } - _renderMatches(matches) { - if (matches.length === 0) { - return; - } - const { - findController, - pageIdx - } = this; - const { - textContentItemsStr, - textDivs - } = this; - const isSelectedPage = pageIdx === findController.selected.pageIdx; - const selectedMatchIdx = findController.selected.matchIdx; - const highlightAll = findController.state.highlightAll; - let prevEnd = null; - const infinity = { - divIdx: -1, - offset: undefined - }; - function beginText(begin, className) { - const divIdx = begin.divIdx; - textDivs[divIdx].textContent = ""; - return appendTextToDiv(divIdx, 0, begin.offset, className); - } - function appendTextToDiv(divIdx, fromOffset, toOffset, className) { - let div = textDivs[divIdx]; - if (div.nodeType === Node.TEXT_NODE) { - const span = document.createElement("span"); - div.before(span); - span.append(div); - textDivs[divIdx] = span; - div = span; - } - const content = textContentItemsStr[divIdx].substring(fromOffset, toOffset); - const node = document.createTextNode(content); - if (className) { - const span = document.createElement("span"); - span.className = `${className} appended`; - span.append(node); - div.append(span); - if (className.includes("selected")) { - const { - left - } = span.getClientRects()[0]; - const parentLeft = div.getBoundingClientRect().left; - return left - parentLeft; - } - return 0; - } - div.append(node); - return 0; - } - let i0 = selectedMatchIdx, - i1 = i0 + 1; - if (highlightAll) { - i0 = 0; - i1 = matches.length; - } else if (!isSelectedPage) { - return; - } - let lastDivIdx = -1; - let lastOffset = -1; - for (let i = i0; i < i1; i++) { - const match = matches[i]; - const begin = match.begin; - if (begin.divIdx === lastDivIdx && begin.offset === lastOffset) { - continue; - } - lastDivIdx = begin.divIdx; - lastOffset = begin.offset; - const end = match.end; - const isSelected = isSelectedPage && i === selectedMatchIdx; - const highlightSuffix = isSelected ? " selected" : ""; - let selectedLeft = 0; - if (!prevEnd || begin.divIdx !== prevEnd.divIdx) { - if (prevEnd !== null) { - appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset); - } - beginText(begin); - } else { - appendTextToDiv(prevEnd.divIdx, prevEnd.offset, begin.offset); - } - if (begin.divIdx === end.divIdx) { - selectedLeft = appendTextToDiv(begin.divIdx, begin.offset, end.offset, "highlight" + highlightSuffix); - } else { - selectedLeft = appendTextToDiv(begin.divIdx, begin.offset, infinity.offset, "highlight begin" + highlightSuffix); - for (let n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) { - textDivs[n0].className = "highlight middle" + highlightSuffix; - } - beginText(end, "highlight end" + highlightSuffix); - } - prevEnd = end; - if (isSelected) { - findController.scrollMatchIntoView({ - element: textDivs[begin.divIdx], - selectedLeft, - pageIndex: pageIdx, - matchIndex: selectedMatchIdx - }); - } - } - if (prevEnd) { - appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset); - } - } - _updateMatches(reset = false) { - if (!this.enabled && !reset) { - return; - } - const { - findController, - matches, - pageIdx - } = this; - const { - textContentItemsStr, - textDivs - } = this; - let clearedUntilDivIdx = -1; - for (const match of matches) { - const begin = Math.max(clearedUntilDivIdx, match.begin.divIdx); - for (let n = begin, end = match.end.divIdx; n <= end; n++) { - const div = textDivs[n]; - div.textContent = textContentItemsStr[n]; - div.className = ""; - } - clearedUntilDivIdx = match.end.divIdx + 1; - } - if (!findController?.highlightMatches || reset) { - return; - } - const pageMatches = findController.pageMatches[pageIdx] || null; - const pageMatchesLength = findController.pageMatchesLength[pageIdx] || null; - this.matches = this._convertMatches(pageMatches, pageMatchesLength); - this._renderMatches(this.matches); - } -} - -;// ./web/text_layer_builder.js - - -class TextLayerBuilder { - #enablePermissions = false; - #onAppend = null; - #renderingDone = false; - #textLayer = null; - static #textLayers = new Map(); - static #selectionChangeAbortController = null; - constructor({ - pdfPage, - highlighter = null, - accessibilityManager = null, - enablePermissions = false, - onAppend = null - }) { - this.pdfPage = pdfPage; - this.highlighter = highlighter; - this.accessibilityManager = accessibilityManager; - this.#enablePermissions = enablePermissions === true; - this.#onAppend = onAppend; - this.div = document.createElement("div"); - this.div.tabIndex = 0; - this.div.className = "textLayer"; - } - async render(viewport, textContentParams = null) { - if (this.#renderingDone && this.#textLayer) { - this.#textLayer.update({ - viewport, - onBefore: this.hide.bind(this) - }); - this.show(); - return; - } - this.cancel(); - this.#textLayer = new TextLayer({ - textContentSource: this.pdfPage.streamTextContent(textContentParams || { - includeMarkedContent: true, - disableNormalization: true - }), - container: this.div, - viewport - }); - const { - textDivs, - textContentItemsStr - } = this.#textLayer; - this.highlighter?.setTextMapping(textDivs, textContentItemsStr); - this.accessibilityManager?.setTextMapping(textDivs); - await this.#textLayer.render(); - this.#renderingDone = true; - const endOfContent = document.createElement("div"); - endOfContent.className = "endOfContent"; - this.div.append(endOfContent); - this.#bindMouse(endOfContent); - this.#onAppend?.(this.div); - this.highlighter?.enable(); - this.accessibilityManager?.enable(); - } - hide() { - if (!this.div.hidden && this.#renderingDone) { - this.highlighter?.disable(); - this.div.hidden = true; - } - } - show() { - if (this.div.hidden && this.#renderingDone) { - this.div.hidden = false; - this.highlighter?.enable(); - } - } - cancel() { - this.#textLayer?.cancel(); - this.#textLayer = null; - this.highlighter?.disable(); - this.accessibilityManager?.disable(); - TextLayerBuilder.#removeGlobalSelectionListener(this.div); - } - #bindMouse(end) { - const { - div - } = this; - div.addEventListener("mousedown", () => { - div.classList.add("selecting"); - }); - div.addEventListener("copy", event => { - if (!this.#enablePermissions) { - const selection = document.getSelection(); - event.clipboardData.setData("text/plain", removeNullCharacters(normalizeUnicode(selection.toString()))); - } - stopEvent(event); - }); - TextLayerBuilder.#textLayers.set(div, end); - TextLayerBuilder.#enableGlobalSelectionListener(); - } - static #removeGlobalSelectionListener(textLayerDiv) { - this.#textLayers.delete(textLayerDiv); - if (this.#textLayers.size === 0) { - this.#selectionChangeAbortController?.abort(); - this.#selectionChangeAbortController = null; - } - } - static #enableGlobalSelectionListener() { - if (this.#selectionChangeAbortController) { - return; - } - this.#selectionChangeAbortController = new AbortController(); - const { - signal - } = this.#selectionChangeAbortController; - const reset = (end, textLayer) => { - textLayer.append(end); - end.style.width = ""; - end.style.height = ""; - textLayer.classList.remove("selecting"); - }; - let isPointerDown = false; - document.addEventListener("pointerdown", () => { - isPointerDown = true; - }, { - signal - }); - document.addEventListener("pointerup", () => { - isPointerDown = false; - this.#textLayers.forEach(reset); - }, { - signal - }); - window.addEventListener("blur", () => { - isPointerDown = false; - this.#textLayers.forEach(reset); - }, { - signal - }); - document.addEventListener("keyup", () => { - if (!isPointerDown) { - this.#textLayers.forEach(reset); - } - }, { - signal - }); - var isFirefox, prevRange; - document.addEventListener("selectionchange", () => { - const selection = document.getSelection(); - if (selection.rangeCount === 0) { - this.#textLayers.forEach(reset); - return; - } - const activeTextLayers = new Set(); - for (let i = 0; i < selection.rangeCount; i++) { - const range = selection.getRangeAt(i); - for (const textLayerDiv of this.#textLayers.keys()) { - if (!activeTextLayers.has(textLayerDiv) && range.intersectsNode(textLayerDiv)) { - activeTextLayers.add(textLayerDiv); - } - } - } - for (const [textLayerDiv, endDiv] of this.#textLayers) { - if (activeTextLayers.has(textLayerDiv)) { - textLayerDiv.classList.add("selecting"); - } else { - reset(endDiv, textLayerDiv); - } - } - isFirefox ??= getComputedStyle(this.#textLayers.values().next().value).getPropertyValue("-moz-user-select") === "none"; - if (isFirefox) { - return; - } - const range = selection.getRangeAt(0); - const modifyStart = prevRange && (range.compareBoundaryPoints(Range.END_TO_END, prevRange) === 0 || range.compareBoundaryPoints(Range.START_TO_END, prevRange) === 0); - let anchor = modifyStart ? range.startContainer : range.endContainer; - if (anchor.nodeType === Node.TEXT_NODE) { - anchor = anchor.parentNode; - } - const parentTextLayer = anchor.parentElement?.closest(".textLayer"); - const endDiv = this.#textLayers.get(parentTextLayer); - if (endDiv) { - endDiv.style.width = parentTextLayer.style.width; - endDiv.style.height = parentTextLayer.style.height; - anchor.parentElement.insertBefore(endDiv, modifyStart ? anchor : anchor.nextSibling); - } - prevRange = range.cloneRange(); - }, { - signal - }); - } -} - -;// ./web/xfa_layer_builder.js - -class XfaLayerBuilder { - constructor({ - pdfPage, - annotationStorage = null, - linkService, - xfaHtml = null - }) { - this.pdfPage = pdfPage; - this.annotationStorage = annotationStorage; - this.linkService = linkService; - this.xfaHtml = xfaHtml; - this.div = null; - this._cancelled = false; - } - async render(viewport, intent = "display") { - if (intent === "print") { - const parameters = { - viewport: viewport.clone({ - dontFlip: true - }), - div: this.div, - xfaHtml: this.xfaHtml, - annotationStorage: this.annotationStorage, - linkService: this.linkService, - intent - }; - this.div = document.createElement("div"); - parameters.div = this.div; - return XfaLayer.render(parameters); - } - const xfaHtml = await this.pdfPage.getXfa(); - if (this._cancelled || !xfaHtml) { - return { - textDivs: [] - }; - } - const parameters = { - viewport: viewport.clone({ - dontFlip: true - }), - div: this.div, - xfaHtml, - annotationStorage: this.annotationStorage, - linkService: this.linkService, - intent - }; - if (this.div) { - return XfaLayer.update(parameters); - } - this.div = document.createElement("div"); - parameters.div = this.div; - return XfaLayer.render(parameters); - } - cancel() { - this._cancelled = true; - } - hide() { - if (!this.div) { - return; - } - this.div.hidden = true; - } -} - -;// ./web/pdf_page_view.js - - - - - - - - - - - - - -const DEFAULT_LAYER_PROPERTIES = { - annotationEditorUIManager: null, - annotationStorage: null, - downloadManager: null, - enableScripting: false, - fieldObjectsPromise: null, - findController: null, - hasJSActionsPromise: null, - get linkService() { - return new SimpleLinkService(); - } -}; -const LAYERS_ORDER = new Map([["canvasWrapper", 0], ["textLayer", 1], ["annotationLayer", 2], ["annotationEditorLayer", 3], ["xfaLayer", 3]]); -class PDFPageView { - #annotationMode = AnnotationMode.ENABLE_FORMS; - #canvasWrapper = null; - #enableHWA = false; - #hasRestrictedScaling = false; - #isEditing = false; - #layerProperties = null; - #loadingId = null; - #originalViewport = null; - #previousRotation = null; - #scaleRoundX = 1; - #scaleRoundY = 1; - #renderError = null; - #renderingState = RenderingStates.INITIAL; - #textLayerMode = TextLayerMode.ENABLE; - #useThumbnailCanvas = { - directDrawing: true, - initialOptionalContent: true, - regularAnnotations: true - }; - #layers = [null, null, null, null]; - constructor(options) { - const container = options.container; - const defaultViewport = options.defaultViewport; - this.id = options.id; - this.renderingId = "page" + this.id; - this.#layerProperties = options.layerProperties || DEFAULT_LAYER_PROPERTIES; - this.pdfPage = null; - this.pageLabel = null; - this.rotation = 0; - this.scale = options.scale || DEFAULT_SCALE; - this.viewport = defaultViewport; - this.pdfPageRotate = defaultViewport.rotation; - this._optionalContentConfigPromise = options.optionalContentConfigPromise || null; - this.#textLayerMode = options.textLayerMode ?? TextLayerMode.ENABLE; - this.#annotationMode = options.annotationMode ?? AnnotationMode.ENABLE_FORMS; - this.imageResourcesPath = options.imageResourcesPath || ""; - this.maxCanvasPixels = options.maxCanvasPixels ?? AppOptions.get("maxCanvasPixels"); - this.pageColors = options.pageColors || null; - this.#enableHWA = options.enableHWA || false; - this.eventBus = options.eventBus; - this.renderingQueue = options.renderingQueue; - this.l10n = options.l10n; - this.l10n ||= new genericl10n_GenericL10n(); - this.renderTask = null; - this.resume = null; - this._isStandalone = !this.renderingQueue?.hasViewer(); - this._container = container; - this._annotationCanvasMap = null; - this.annotationLayer = null; - this.annotationEditorLayer = null; - this.textLayer = null; - this.xfaLayer = null; - this.structTreeLayer = null; - this.drawLayer = null; - const div = document.createElement("div"); - div.className = "page"; - div.setAttribute("data-page-number", this.id); - div.setAttribute("role", "region"); - div.setAttribute("data-l10n-id", "pdfjs-page-landmark"); - div.setAttribute("data-l10n-args", JSON.stringify({ - page: this.id - })); - this.div = div; - this.#setDimensions(); - container?.append(div); - if (this._isStandalone) { - container?.style.setProperty("--scale-factor", this.scale * PixelsPerInch.PDF_TO_CSS_UNITS); - if (this.pageColors?.background) { - container?.style.setProperty("--page-bg-color", this.pageColors.background); - } - const { - optionalContentConfigPromise - } = options; - if (optionalContentConfigPromise) { - optionalContentConfigPromise.then(optionalContentConfig => { - if (optionalContentConfigPromise !== this._optionalContentConfigPromise) { - return; - } - this.#useThumbnailCanvas.initialOptionalContent = optionalContentConfig.hasInitialVisibility; - }); - } - if (!options.l10n) { - this.l10n.translate(this.div); - } - } - } - #addLayer(div, name) { - const pos = LAYERS_ORDER.get(name); - const oldDiv = this.#layers[pos]; - this.#layers[pos] = div; - if (oldDiv) { - oldDiv.replaceWith(div); - return; - } - for (let i = pos - 1; i >= 0; i--) { - const layer = this.#layers[i]; - if (layer) { - layer.after(div); - return; - } - } - this.div.prepend(div); - } - get renderingState() { - return this.#renderingState; - } - set renderingState(state) { - if (state === this.#renderingState) { - return; - } - this.#renderingState = state; - if (this.#loadingId) { - clearTimeout(this.#loadingId); - this.#loadingId = null; - } - switch (state) { - case RenderingStates.PAUSED: - this.div.classList.remove("loading"); - break; - case RenderingStates.RUNNING: - this.div.classList.add("loadingIcon"); - this.#loadingId = setTimeout(() => { - this.div.classList.add("loading"); - this.#loadingId = null; - }, 0); - break; - case RenderingStates.INITIAL: - case RenderingStates.FINISHED: - this.div.classList.remove("loadingIcon", "loading"); - break; - } - } - #setDimensions() { - const { - viewport - } = this; - if (this.pdfPage) { - if (this.#previousRotation === viewport.rotation) { - return; - } - this.#previousRotation = viewport.rotation; - } - setLayerDimensions(this.div, viewport, true, false); - } - setPdfPage(pdfPage) { - if (this._isStandalone && (this.pageColors?.foreground === "CanvasText" || this.pageColors?.background === "Canvas")) { - this._container?.style.setProperty("--hcm-highlight-filter", pdfPage.filterFactory.addHighlightHCMFilter("highlight", "CanvasText", "Canvas", "HighlightText", "Highlight")); - this._container?.style.setProperty("--hcm-highlight-selected-filter", pdfPage.filterFactory.addHighlightHCMFilter("highlight_selected", "CanvasText", "Canvas", "HighlightText", "Highlight")); - } - this.pdfPage = pdfPage; - this.pdfPageRotate = pdfPage.rotate; - const totalRotation = (this.rotation + this.pdfPageRotate) % 360; - this.viewport = pdfPage.getViewport({ - scale: this.scale * PixelsPerInch.PDF_TO_CSS_UNITS, - rotation: totalRotation - }); - this.#setDimensions(); - this.reset(); - } - destroy() { - this.reset(); - this.pdfPage?.cleanup(); - } - hasEditableAnnotations() { - return !!this.annotationLayer?.hasEditableAnnotations(); - } - get _textHighlighter() { - return shadow(this, "_textHighlighter", new TextHighlighter({ - pageIndex: this.id - 1, - eventBus: this.eventBus, - findController: this.#layerProperties.findController - })); - } - #dispatchLayerRendered(name, error) { - this.eventBus.dispatch(name, { - source: this, - pageNumber: this.id, - error - }); - } - async #renderAnnotationLayer() { - let error = null; - try { - await this.annotationLayer.render(this.viewport, { - structTreeLayer: this.structTreeLayer - }, "display"); - } catch (ex) { - console.error("#renderAnnotationLayer:", ex); - error = ex; - } finally { - this.#dispatchLayerRendered("annotationlayerrendered", error); - } - } - async #renderAnnotationEditorLayer() { - let error = null; - try { - await this.annotationEditorLayer.render(this.viewport, "display"); - } catch (ex) { - console.error("#renderAnnotationEditorLayer:", ex); - error = ex; - } finally { - this.#dispatchLayerRendered("annotationeditorlayerrendered", error); - } - } - async #renderDrawLayer() { - try { - await this.drawLayer.render("display"); - } catch (ex) { - console.error("#renderDrawLayer:", ex); - } - } - async #renderXfaLayer() { - let error = null; - try { - const result = await this.xfaLayer.render(this.viewport, "display"); - if (result?.textDivs && this._textHighlighter) { - this.#buildXfaTextContentItems(result.textDivs); - } - } catch (ex) { - console.error("#renderXfaLayer:", ex); - error = ex; - } finally { - if (this.xfaLayer?.div) { - this.l10n.pause(); - this.#addLayer(this.xfaLayer.div, "xfaLayer"); - this.l10n.resume(); - } - this.#dispatchLayerRendered("xfalayerrendered", error); - } - } - async #renderTextLayer() { - if (!this.textLayer) { - return; - } - let error = null; - try { - await this.textLayer.render(this.viewport); - } catch (ex) { - if (ex instanceof AbortException) { - return; - } - console.error("#renderTextLayer:", ex); - error = ex; - } - this.#dispatchLayerRendered("textlayerrendered", error); - this.#renderStructTreeLayer(); - } - async #renderStructTreeLayer() { - if (!this.textLayer) { - return; - } - const treeDom = await this.structTreeLayer?.render(); - if (treeDom) { - this.l10n.pause(); - this.structTreeLayer?.addElementsToTextLayer(); - if (this.canvas && treeDom.parentNode !== this.canvas) { - this.canvas.append(treeDom); - } - this.l10n.resume(); - } - this.structTreeLayer?.show(); - } - async #buildXfaTextContentItems(textDivs) { - const text = await this.pdfPage.getTextContent(); - const items = []; - for (const item of text.items) { - items.push(item.str); - } - this._textHighlighter.setTextMapping(textDivs, items); - this._textHighlighter.enable(); - } - #resetCanvas() { - const { - canvas - } = this; - if (!canvas) { - return; - } - canvas.remove(); - canvas.width = canvas.height = 0; - this.canvas = null; - this.#originalViewport = null; - } - reset({ - keepAnnotationLayer = false, - keepAnnotationEditorLayer = false, - keepXfaLayer = false, - keepTextLayer = false, - keepCanvasWrapper = false - } = {}) { - this.cancelRendering({ - keepAnnotationLayer, - keepAnnotationEditorLayer, - keepXfaLayer, - keepTextLayer - }); - this.renderingState = RenderingStates.INITIAL; - const div = this.div; - const childNodes = div.childNodes, - annotationLayerNode = keepAnnotationLayer && this.annotationLayer?.div || null, - annotationEditorLayerNode = keepAnnotationEditorLayer && this.annotationEditorLayer?.div || null, - xfaLayerNode = keepXfaLayer && this.xfaLayer?.div || null, - textLayerNode = keepTextLayer && this.textLayer?.div || null, - canvasWrapperNode = keepCanvasWrapper && this.#canvasWrapper || null; - for (let i = childNodes.length - 1; i >= 0; i--) { - const node = childNodes[i]; - switch (node) { - case annotationLayerNode: - case annotationEditorLayerNode: - case xfaLayerNode: - case textLayerNode: - case canvasWrapperNode: - continue; - } - node.remove(); - const layerIndex = this.#layers.indexOf(node); - if (layerIndex >= 0) { - this.#layers[layerIndex] = null; - } - } - div.removeAttribute("data-loaded"); - if (annotationLayerNode) { - this.annotationLayer.hide(); - } - if (annotationEditorLayerNode) { - this.annotationEditorLayer.hide(); - } - if (xfaLayerNode) { - this.xfaLayer.hide(); - } - if (textLayerNode) { - this.textLayer.hide(); - } - this.structTreeLayer?.hide(); - if (!keepCanvasWrapper && this.#canvasWrapper) { - this.#canvasWrapper = null; - this.#resetCanvas(); - } - } - toggleEditingMode(isEditing) { - if (!this.hasEditableAnnotations()) { - return; - } - this.#isEditing = isEditing; - this.reset({ - keepAnnotationLayer: true, - keepAnnotationEditorLayer: true, - keepXfaLayer: true, - keepTextLayer: true, - keepCanvasWrapper: true - }); - } - update({ - scale = 0, - rotation = null, - optionalContentConfigPromise = null, - drawingDelay = -1 - }) { - this.scale = scale || this.scale; - if (typeof rotation === "number") { - this.rotation = rotation; - } - if (optionalContentConfigPromise instanceof Promise) { - this._optionalContentConfigPromise = optionalContentConfigPromise; - optionalContentConfigPromise.then(optionalContentConfig => { - if (optionalContentConfigPromise !== this._optionalContentConfigPromise) { - return; - } - this.#useThumbnailCanvas.initialOptionalContent = optionalContentConfig.hasInitialVisibility; - }); - } - this.#useThumbnailCanvas.directDrawing = true; - const totalRotation = (this.rotation + this.pdfPageRotate) % 360; - this.viewport = this.viewport.clone({ - scale: this.scale * PixelsPerInch.PDF_TO_CSS_UNITS, - rotation: totalRotation - }); - this.#setDimensions(); - if (this._isStandalone) { - this._container?.style.setProperty("--scale-factor", this.viewport.scale); - } - if (this.canvas) { - let onlyCssZoom = false; - if (this.#hasRestrictedScaling) { - if (this.maxCanvasPixels === 0) { - onlyCssZoom = true; - } else if (this.maxCanvasPixels > 0) { - const { - width, - height - } = this.viewport; - const { - sx, - sy - } = this.outputScale; - onlyCssZoom = (Math.floor(width) * sx | 0) * (Math.floor(height) * sy | 0) > this.maxCanvasPixels; - } - } - const postponeDrawing = drawingDelay >= 0 && drawingDelay < 1000; - if (postponeDrawing || onlyCssZoom) { - if (postponeDrawing && !onlyCssZoom && this.renderingState !== RenderingStates.FINISHED) { - this.cancelRendering({ - keepAnnotationLayer: true, - keepAnnotationEditorLayer: true, - keepXfaLayer: true, - keepTextLayer: true, - cancelExtraDelay: drawingDelay - }); - this.renderingState = RenderingStates.FINISHED; - this.#useThumbnailCanvas.directDrawing = false; - } - this.cssTransform({ - redrawAnnotationLayer: true, - redrawAnnotationEditorLayer: true, - redrawXfaLayer: true, - redrawTextLayer: !postponeDrawing, - hideTextLayer: postponeDrawing - }); - if (postponeDrawing) { - return; - } - this.eventBus.dispatch("pagerendered", { - source: this, - pageNumber: this.id, - cssTransform: true, - timestamp: performance.now(), - error: this.#renderError - }); - return; - } - } - this.cssTransform({}); - this.reset({ - keepAnnotationLayer: true, - keepAnnotationEditorLayer: true, - keepXfaLayer: true, - keepTextLayer: true, - keepCanvasWrapper: true - }); - } - cancelRendering({ - keepAnnotationLayer = false, - keepAnnotationEditorLayer = false, - keepXfaLayer = false, - keepTextLayer = false, - cancelExtraDelay = 0 - } = {}) { - if (this.renderTask) { - this.renderTask.cancel(cancelExtraDelay); - this.renderTask = null; - } - this.resume = null; - if (this.textLayer && (!keepTextLayer || !this.textLayer.div)) { - this.textLayer.cancel(); - this.textLayer = null; - } - if (this.annotationLayer && (!keepAnnotationLayer || !this.annotationLayer.div)) { - this.annotationLayer.cancel(); - this.annotationLayer = null; - this._annotationCanvasMap = null; - } - if (this.structTreeLayer && !this.textLayer) { - this.structTreeLayer = null; - } - if (this.annotationEditorLayer && (!keepAnnotationEditorLayer || !this.annotationEditorLayer.div)) { - if (this.drawLayer) { - this.drawLayer.cancel(); - this.drawLayer = null; - } - this.annotationEditorLayer.cancel(); - this.annotationEditorLayer = null; - } - if (this.xfaLayer && (!keepXfaLayer || !this.xfaLayer.div)) { - this.xfaLayer.cancel(); - this.xfaLayer = null; - this._textHighlighter?.disable(); - } - } - cssTransform({ - redrawAnnotationLayer = false, - redrawAnnotationEditorLayer = false, - redrawXfaLayer = false, - redrawTextLayer = false, - hideTextLayer = false - }) { - const { - canvas - } = this; - if (!canvas) { - return; - } - const originalViewport = this.#originalViewport; - if (this.viewport !== originalViewport) { - const relativeRotation = (360 + this.viewport.rotation - originalViewport.rotation) % 360; - if (relativeRotation === 90 || relativeRotation === 270) { - const { - width, - height - } = this.viewport; - const scaleX = height / width; - const scaleY = width / height; - canvas.style.transform = `rotate(${relativeRotation}deg) scale(${scaleX},${scaleY})`; - } else { - canvas.style.transform = relativeRotation === 0 ? "" : `rotate(${relativeRotation}deg)`; - } - } - if (redrawAnnotationLayer && this.annotationLayer) { - this.#renderAnnotationLayer(); - } - if (redrawAnnotationEditorLayer && this.annotationEditorLayer) { - if (this.drawLayer) { - this.#renderDrawLayer(); - } - this.#renderAnnotationEditorLayer(); - } - if (redrawXfaLayer && this.xfaLayer) { - this.#renderXfaLayer(); - } - if (this.textLayer) { - if (hideTextLayer) { - this.textLayer.hide(); - this.structTreeLayer?.hide(); - } else if (redrawTextLayer) { - this.#renderTextLayer(); - } - } - } - get width() { - return this.viewport.width; - } - get height() { - return this.viewport.height; - } - getPagePoint(x, y) { - return this.viewport.convertToPdfPoint(x, y); - } - async #finishRenderTask(renderTask, error = null) { - if (renderTask === this.renderTask) { - this.renderTask = null; - } - if (error instanceof RenderingCancelledException) { - this.#renderError = null; - return; - } - this.#renderError = error; - this.renderingState = RenderingStates.FINISHED; - this.#useThumbnailCanvas.regularAnnotations = !renderTask.separateAnnots; - this.eventBus.dispatch("pagerendered", { - source: this, - pageNumber: this.id, - cssTransform: false, - timestamp: performance.now(), - error: this.#renderError - }); - if (error) { - throw error; - } - } - async draw() { - if (this.renderingState !== RenderingStates.INITIAL) { - console.error("Must be in new state before drawing"); - this.reset(); - } - const { - div, - l10n, - pageColors, - pdfPage, - viewport - } = this; - if (!pdfPage) { - this.renderingState = RenderingStates.FINISHED; - throw new Error("pdfPage is not loaded"); - } - this.renderingState = RenderingStates.RUNNING; - let canvasWrapper = this.#canvasWrapper; - if (!canvasWrapper) { - canvasWrapper = this.#canvasWrapper = document.createElement("div"); - canvasWrapper.classList.add("canvasWrapper"); - this.#addLayer(canvasWrapper, "canvasWrapper"); - } - if (!this.textLayer && this.#textLayerMode !== TextLayerMode.DISABLE && !pdfPage.isPureXfa) { - this._accessibilityManager ||= new TextAccessibilityManager(); - this.textLayer = new TextLayerBuilder({ - pdfPage, - highlighter: this._textHighlighter, - accessibilityManager: this._accessibilityManager, - enablePermissions: this.#textLayerMode === TextLayerMode.ENABLE_PERMISSIONS, - onAppend: textLayerDiv => { - this.l10n.pause(); - this.#addLayer(textLayerDiv, "textLayer"); - this.l10n.resume(); - } - }); - } - if (!this.annotationLayer && this.#annotationMode !== AnnotationMode.DISABLE) { - const { - annotationStorage, - annotationEditorUIManager, - downloadManager, - enableScripting, - fieldObjectsPromise, - hasJSActionsPromise, - linkService - } = this.#layerProperties; - this._annotationCanvasMap ||= new Map(); - this.annotationLayer = new AnnotationLayerBuilder({ - pdfPage, - annotationStorage, - imageResourcesPath: this.imageResourcesPath, - renderForms: this.#annotationMode === AnnotationMode.ENABLE_FORMS, - linkService, - downloadManager, - enableScripting, - hasJSActionsPromise, - fieldObjectsPromise, - annotationCanvasMap: this._annotationCanvasMap, - accessibilityManager: this._accessibilityManager, - annotationEditorUIManager, - onAppend: annotationLayerDiv => { - this.#addLayer(annotationLayerDiv, "annotationLayer"); - } - }); - } - const renderContinueCallback = cont => { - showCanvas?.(false); - if (this.renderingQueue && !this.renderingQueue.isHighestPriority(this)) { - this.renderingState = RenderingStates.PAUSED; - this.resume = () => { - this.renderingState = RenderingStates.RUNNING; - cont(); - }; - return; - } - cont(); - }; - const { - width, - height - } = viewport; - const canvas = document.createElement("canvas"); - canvas.setAttribute("role", "presentation"); - const hasHCM = !!(pageColors?.background && pageColors?.foreground); - const prevCanvas = this.canvas; - const updateOnFirstShow = !prevCanvas && !hasHCM; - this.canvas = canvas; - this.#originalViewport = viewport; - let showCanvas = isLastShow => { - if (updateOnFirstShow) { - canvasWrapper.prepend(canvas); - showCanvas = null; - return; - } - if (!isLastShow) { - return; - } - if (prevCanvas) { - prevCanvas.replaceWith(canvas); - prevCanvas.width = prevCanvas.height = 0; - } else { - canvasWrapper.prepend(canvas); - } - showCanvas = null; - }; - const ctx = canvas.getContext("2d", { - alpha: false, - willReadFrequently: !this.#enableHWA - }); - const outputScale = this.outputScale = new OutputScale(); - if (this.maxCanvasPixels === 0) { - const invScale = 1 / this.scale; - outputScale.sx *= invScale; - outputScale.sy *= invScale; - this.#hasRestrictedScaling = true; - } else if (this.maxCanvasPixels > 0) { - const pixelsInViewport = width * height; - const maxScale = Math.sqrt(this.maxCanvasPixels / pixelsInViewport); - if (outputScale.sx > maxScale || outputScale.sy > maxScale) { - outputScale.sx = maxScale; - outputScale.sy = maxScale; - this.#hasRestrictedScaling = true; - } else { - this.#hasRestrictedScaling = false; - } - } - const sfx = approximateFraction(outputScale.sx); - const sfy = approximateFraction(outputScale.sy); - const canvasWidth = canvas.width = floorToDivide(calcRound(width * outputScale.sx), sfx[0]); - const canvasHeight = canvas.height = floorToDivide(calcRound(height * outputScale.sy), sfy[0]); - const pageWidth = floorToDivide(calcRound(width), sfx[1]); - const pageHeight = floorToDivide(calcRound(height), sfy[1]); - outputScale.sx = canvasWidth / pageWidth; - outputScale.sy = canvasHeight / pageHeight; - if (this.#scaleRoundX !== sfx[1]) { - div.style.setProperty("--scale-round-x", `${sfx[1]}px`); - this.#scaleRoundX = sfx[1]; - } - if (this.#scaleRoundY !== sfy[1]) { - div.style.setProperty("--scale-round-y", `${sfy[1]}px`); - this.#scaleRoundY = sfy[1]; - } - const transform = outputScale.scaled ? [outputScale.sx, 0, 0, outputScale.sy, 0, 0] : null; - const renderContext = { - canvasContext: ctx, - transform, - viewport, - annotationMode: this.#annotationMode, - optionalContentConfigPromise: this._optionalContentConfigPromise, - annotationCanvasMap: this._annotationCanvasMap, - pageColors, - isEditing: this.#isEditing - }; - const renderTask = this.renderTask = pdfPage.render(renderContext); - renderTask.onContinue = renderContinueCallback; - const resultPromise = renderTask.promise.then(async () => { - showCanvas?.(true); - await this.#finishRenderTask(renderTask); - this.structTreeLayer ||= new StructTreeLayerBuilder(pdfPage, viewport.rawDims); - this.#renderTextLayer(); - if (this.annotationLayer) { - await this.#renderAnnotationLayer(); - } - const { - annotationEditorUIManager - } = this.#layerProperties; - if (!annotationEditorUIManager) { - return; - } - this.drawLayer ||= new DrawLayerBuilder({ - pageIndex: this.id - }); - await this.#renderDrawLayer(); - this.drawLayer.setParent(canvasWrapper); - this.annotationEditorLayer ||= new AnnotationEditorLayerBuilder({ - uiManager: annotationEditorUIManager, - pdfPage, - l10n, - structTreeLayer: this.structTreeLayer, - accessibilityManager: this._accessibilityManager, - annotationLayer: this.annotationLayer?.annotationLayer, - textLayer: this.textLayer, - drawLayer: this.drawLayer.getDrawLayer(), - onAppend: annotationEditorLayerDiv => { - this.#addLayer(annotationEditorLayerDiv, "annotationEditorLayer"); - } - }); - this.#renderAnnotationEditorLayer(); - }, error => { - if (!(error instanceof RenderingCancelledException)) { - showCanvas?.(true); - } else { - prevCanvas?.remove(); - this.#resetCanvas(); - } - return this.#finishRenderTask(renderTask, error); - }); - if (pdfPage.isPureXfa) { - if (!this.xfaLayer) { - const { - annotationStorage, - linkService - } = this.#layerProperties; - this.xfaLayer = new XfaLayerBuilder({ - pdfPage, - annotationStorage, - linkService - }); - } - this.#renderXfaLayer(); - } - div.setAttribute("data-loaded", true); - this.eventBus.dispatch("pagerender", { - source: this, - pageNumber: this.id - }); - return resultPromise; - } - setPageLabel(label) { - this.pageLabel = typeof label === "string" ? label : null; - this.div.setAttribute("data-l10n-args", JSON.stringify({ - page: this.pageLabel ?? this.id - })); - if (this.pageLabel !== null) { - this.div.setAttribute("data-page-label", this.pageLabel); - } else { - this.div.removeAttribute("data-page-label"); - } - } - get thumbnailCanvas() { - const { - directDrawing, - initialOptionalContent, - regularAnnotations - } = this.#useThumbnailCanvas; - return directDrawing && initialOptionalContent && regularAnnotations ? this.canvas : null; - } -} - -;// ./web/generic_scripting.js - -async function docProperties(pdfDocument) { - const url = "", - baseUrl = url.split("#", 1)[0]; - let { - info, - metadata, - contentDispositionFilename, - contentLength - } = await pdfDocument.getMetadata(); - if (!contentLength) { - const { - length - } = await pdfDocument.getDownloadInfo(); - contentLength = length; - } - return { - ...info, - baseURL: baseUrl, - filesize: contentLength, - filename: contentDispositionFilename || getPdfFilenameFromUrl(url), - metadata: metadata?.getRaw(), - authors: metadata?.get("dc:creator"), - numPages: pdfDocument.numPages, - URL: url - }; -} -class GenericScripting { - constructor(sandboxBundleSrc) { - this._ready = new Promise((resolve, reject) => { - const sandbox = import(/*webpackIgnore: true*/sandboxBundleSrc); - sandbox.then(pdfjsSandbox => { - resolve(pdfjsSandbox.QuickJSSandbox()); - }).catch(reject); - }); - } - async createSandbox(data) { - const sandbox = await this._ready; - sandbox.create(data); - } - async dispatchEventInSandbox(event) { - const sandbox = await this._ready; - setTimeout(() => sandbox.dispatchEvent(event), 0); - } - async destroySandbox() { - const sandbox = await this._ready; - sandbox.nukeSandbox(); - } -} - -;// ./web/pdf_scripting_manager.js - - -class PDFScriptingManager { - #closeCapability = null; - #destroyCapability = null; - #docProperties = null; - #eventAbortController = null; - #eventBus = null; - #externalServices = null; - #pdfDocument = null; - #pdfViewer = null; - #ready = false; - #scripting = null; - #willPrintCapability = null; - constructor({ - eventBus, - externalServices = null, - docProperties = null - }) { - this.#eventBus = eventBus; - this.#externalServices = externalServices; - this.#docProperties = docProperties; - } - setViewer(pdfViewer) { - this.#pdfViewer = pdfViewer; - } - async setDocument(pdfDocument) { - if (this.#pdfDocument) { - await this.#destroyScripting(); - } - this.#pdfDocument = pdfDocument; - if (!pdfDocument) { - return; - } - const [objects, calculationOrder, docActions] = await Promise.all([pdfDocument.getFieldObjects(), pdfDocument.getCalculationOrderIds(), pdfDocument.getJSActions()]); - if (!objects && !docActions) { - await this.#destroyScripting(); - return; - } - if (pdfDocument !== this.#pdfDocument) { - return; - } - try { - this.#scripting = this.#initScripting(); - } catch (error) { - console.error("setDocument:", error); - await this.#destroyScripting(); - return; - } - const eventBus = this.#eventBus; - this.#eventAbortController = new AbortController(); - const { - signal - } = this.#eventAbortController; - eventBus._on("updatefromsandbox", event => { - if (event?.source === window) { - this.#updateFromSandbox(event.detail); - } - }, { - signal - }); - eventBus._on("dispatcheventinsandbox", event => { - this.#scripting?.dispatchEventInSandbox(event.detail); - }, { - signal - }); - eventBus._on("pagechanging", ({ - pageNumber, - previous - }) => { - if (pageNumber === previous) { - return; - } - this.#dispatchPageClose(previous); - this.#dispatchPageOpen(pageNumber); - }, { - signal - }); - eventBus._on("pagerendered", ({ - pageNumber - }) => { - if (!this._pageOpenPending.has(pageNumber)) { - return; - } - if (pageNumber !== this.#pdfViewer.currentPageNumber) { - return; - } - this.#dispatchPageOpen(pageNumber); - }, { - signal - }); - eventBus._on("pagesdestroy", async () => { - await this.#dispatchPageClose(this.#pdfViewer.currentPageNumber); - await this.#scripting?.dispatchEventInSandbox({ - id: "doc", - name: "WillClose" - }); - this.#closeCapability?.resolve(); - }, { - signal - }); - try { - const docProperties = await this.#docProperties(pdfDocument); - if (pdfDocument !== this.#pdfDocument) { - return; - } - await this.#scripting.createSandbox({ - objects, - calculationOrder, - appInfo: { - platform: navigator.platform, - language: navigator.language - }, - docInfo: { - ...docProperties, - actions: docActions - } - }); - eventBus.dispatch("sandboxcreated", { - source: this - }); - } catch (error) { - console.error("setDocument:", error); - await this.#destroyScripting(); - return; - } - await this.#scripting?.dispatchEventInSandbox({ - id: "doc", - name: "Open" - }); - await this.#dispatchPageOpen(this.#pdfViewer.currentPageNumber, true); - Promise.resolve().then(() => { - if (pdfDocument === this.#pdfDocument) { - this.#ready = true; - } - }); - } - async dispatchWillSave() { - return this.#scripting?.dispatchEventInSandbox({ - id: "doc", - name: "WillSave" - }); - } - async dispatchDidSave() { - return this.#scripting?.dispatchEventInSandbox({ - id: "doc", - name: "DidSave" - }); - } - async dispatchWillPrint() { - if (!this.#scripting) { - return; - } - await this.#willPrintCapability?.promise; - this.#willPrintCapability = Promise.withResolvers(); - try { - await this.#scripting.dispatchEventInSandbox({ - id: "doc", - name: "WillPrint" - }); - } catch (ex) { - this.#willPrintCapability.resolve(); - this.#willPrintCapability = null; - throw ex; - } - await this.#willPrintCapability.promise; - } - async dispatchDidPrint() { - return this.#scripting?.dispatchEventInSandbox({ - id: "doc", - name: "DidPrint" - }); - } - get destroyPromise() { - return this.#destroyCapability?.promise || null; - } - get ready() { - return this.#ready; - } - get _pageOpenPending() { - return shadow(this, "_pageOpenPending", new Set()); - } - get _visitedPages() { - return shadow(this, "_visitedPages", new Map()); - } - async #updateFromSandbox(detail) { - const pdfViewer = this.#pdfViewer; - const isInPresentationMode = pdfViewer.isInPresentationMode || pdfViewer.isChangingPresentationMode; - const { - id, - siblings, - command, - value - } = detail; - if (!id) { - switch (command) { - case "clear": - console.clear(); - break; - case "error": - console.error(value); - break; - case "layout": - if (!isInPresentationMode) { - const modes = apiPageLayoutToViewerModes(value); - pdfViewer.spreadMode = modes.spreadMode; - } - break; - case "page-num": - pdfViewer.currentPageNumber = value + 1; - break; - case "print": - await pdfViewer.pagesPromise; - this.#eventBus.dispatch("print", { - source: this - }); - break; - case "println": - console.log(value); - break; - case "zoom": - if (!isInPresentationMode) { - pdfViewer.currentScaleValue = value; - } - break; - case "SaveAs": - this.#eventBus.dispatch("download", { - source: this - }); - break; - case "FirstPage": - pdfViewer.currentPageNumber = 1; - break; - case "LastPage": - pdfViewer.currentPageNumber = pdfViewer.pagesCount; - break; - case "NextPage": - pdfViewer.nextPage(); - break; - case "PrevPage": - pdfViewer.previousPage(); - break; - case "ZoomViewIn": - if (!isInPresentationMode) { - pdfViewer.increaseScale(); - } - break; - case "ZoomViewOut": - if (!isInPresentationMode) { - pdfViewer.decreaseScale(); - } - break; - case "WillPrintFinished": - this.#willPrintCapability?.resolve(); - this.#willPrintCapability = null; - break; - } - return; - } - if (isInPresentationMode && detail.focus) { - return; - } - delete detail.id; - delete detail.siblings; - const ids = siblings ? [id, ...siblings] : [id]; - for (const elementId of ids) { - const element = document.querySelector(`[data-element-id="${elementId}"]`); - if (element) { - element.dispatchEvent(new CustomEvent("updatefromsandbox", { - detail - })); - } else { - this.#pdfDocument?.annotationStorage.setValue(elementId, detail); - } - } - } - async #dispatchPageOpen(pageNumber, initialize = false) { - const pdfDocument = this.#pdfDocument, - visitedPages = this._visitedPages; - if (initialize) { - this.#closeCapability = Promise.withResolvers(); - } - if (!this.#closeCapability) { - return; - } - const pageView = this.#pdfViewer.getPageView(pageNumber - 1); - if (pageView?.renderingState !== RenderingStates.FINISHED) { - this._pageOpenPending.add(pageNumber); - return; - } - this._pageOpenPending.delete(pageNumber); - const actionsPromise = (async () => { - const actions = await (!visitedPages.has(pageNumber) ? pageView.pdfPage?.getJSActions() : null); - if (pdfDocument !== this.#pdfDocument) { - return; - } - await this.#scripting?.dispatchEventInSandbox({ - id: "page", - name: "PageOpen", - pageNumber, - actions - }); - })(); - visitedPages.set(pageNumber, actionsPromise); - } - async #dispatchPageClose(pageNumber) { - const pdfDocument = this.#pdfDocument, - visitedPages = this._visitedPages; - if (!this.#closeCapability) { - return; - } - if (this._pageOpenPending.has(pageNumber)) { - return; - } - const actionsPromise = visitedPages.get(pageNumber); - if (!actionsPromise) { - return; - } - visitedPages.set(pageNumber, null); - await actionsPromise; - if (pdfDocument !== this.#pdfDocument) { - return; - } - await this.#scripting?.dispatchEventInSandbox({ - id: "page", - name: "PageClose", - pageNumber - }); - } - #initScripting() { - this.#destroyCapability = Promise.withResolvers(); - if (this.#scripting) { - throw new Error("#initScripting: Scripting already exists."); - } - return this.#externalServices.createScripting(); - } - async #destroyScripting() { - if (!this.#scripting) { - this.#pdfDocument = null; - this.#destroyCapability?.resolve(); - return; - } - if (this.#closeCapability) { - await Promise.race([this.#closeCapability.promise, new Promise(resolve => { - setTimeout(resolve, 1000); - })]).catch(() => {}); - this.#closeCapability = null; - } - this.#pdfDocument = null; - try { - await this.#scripting.destroySandbox(); - } catch {} - this.#willPrintCapability?.reject(new Error("Scripting destroyed.")); - this.#willPrintCapability = null; - this.#eventAbortController?.abort(); - this.#eventAbortController = null; - this._pageOpenPending.clear(); - this._visitedPages.clear(); - this.#scripting = null; - this.#ready = false; - this.#destroyCapability?.resolve(); - } -} - -;// ./web/pdf_scripting_manager.component.js - - -class PDFScriptingManagerComponents extends PDFScriptingManager { - constructor(options) { - if (!options.externalServices) { - window.addEventListener("updatefromsandbox", event => { - options.eventBus.dispatch("updatefromsandbox", { - source: window, - detail: event.detail - }); - }); - } - options.externalServices ||= { - createScripting: () => new GenericScripting(options.sandboxBundleSrc) - }; - options.docProperties ||= pdfDocument => docProperties(pdfDocument); - super(options); - } -} - -;// ./web/pdf_rendering_queue.js - - -const CLEANUP_TIMEOUT = 30000; -class PDFRenderingQueue { - constructor() { - this.pdfViewer = null; - this.pdfThumbnailViewer = null; - this.onIdle = null; - this.highestPriorityPage = null; - this.idleTimeout = null; - this.printing = false; - this.isThumbnailViewEnabled = false; - Object.defineProperty(this, "hasViewer", { - value: () => !!this.pdfViewer - }); - } - setViewer(pdfViewer) { - this.pdfViewer = pdfViewer; - } - setThumbnailViewer(pdfThumbnailViewer) { - this.pdfThumbnailViewer = pdfThumbnailViewer; - } - isHighestPriority(view) { - return this.highestPriorityPage === view.renderingId; - } - renderHighestPriority(currentlyVisiblePages) { - if (this.idleTimeout) { - clearTimeout(this.idleTimeout); - this.idleTimeout = null; - } - if (this.pdfViewer.forceRendering(currentlyVisiblePages)) { - return; - } - if (this.isThumbnailViewEnabled && this.pdfThumbnailViewer?.forceRendering()) { - return; - } - if (this.printing) { - return; - } - if (this.onIdle) { - this.idleTimeout = setTimeout(this.onIdle.bind(this), CLEANUP_TIMEOUT); - } - } - getHighestPriority(visible, views, scrolledDown, preRenderExtra = false) { - const visibleViews = visible.views, - numVisible = visibleViews.length; - if (numVisible === 0) { - return null; - } - for (let i = 0; i < numVisible; i++) { - const view = visibleViews[i].view; - if (!this.isViewFinished(view)) { - return view; - } - } - const firstId = visible.first.id, - lastId = visible.last.id; - if (lastId - firstId + 1 > numVisible) { - const visibleIds = visible.ids; - for (let i = 1, ii = lastId - firstId; i < ii; i++) { - const holeId = scrolledDown ? firstId + i : lastId - i; - if (visibleIds.has(holeId)) { - continue; - } - const holeView = views[holeId - 1]; - if (!this.isViewFinished(holeView)) { - return holeView; - } - } - } - let preRenderIndex = scrolledDown ? lastId : firstId - 2; - let preRenderView = views[preRenderIndex]; - if (preRenderView && !this.isViewFinished(preRenderView)) { - return preRenderView; - } - if (preRenderExtra) { - preRenderIndex += scrolledDown ? 1 : -1; - preRenderView = views[preRenderIndex]; - if (preRenderView && !this.isViewFinished(preRenderView)) { - return preRenderView; - } - } - return null; - } - isViewFinished(view) { - return view.renderingState === RenderingStates.FINISHED; - } - renderView(view) { - switch (view.renderingState) { - case RenderingStates.FINISHED: - return false; - case RenderingStates.PAUSED: - this.highestPriorityPage = view.renderingId; - view.resume(); - break; - case RenderingStates.RUNNING: - this.highestPriorityPage = view.renderingId; - break; - case RenderingStates.INITIAL: - this.highestPriorityPage = view.renderingId; - view.draw().finally(() => { - this.renderHighestPriority(); - }).catch(reason => { - if (reason instanceof RenderingCancelledException) { - return; - } - console.error("renderView:", reason); - }); - break; - } - return true; - } -} - -;// ./web/pdf_viewer.js - - - - - - -const DEFAULT_CACHE_SIZE = 10; -const PagesCountLimit = { - FORCE_SCROLL_MODE_PAGE: 10000, - FORCE_LAZY_PAGE_INIT: 5000, - PAUSE_EAGER_PAGE_INIT: 250 -}; -function isValidAnnotationEditorMode(mode) { - return Object.values(AnnotationEditorType).includes(mode) && mode !== AnnotationEditorType.DISABLE; -} -class PDFPageViewBuffer { - #buf = new Set(); - #size = 0; - constructor(size) { - this.#size = size; - } - push(view) { - const buf = this.#buf; - if (buf.has(view)) { - buf.delete(view); - } - buf.add(view); - if (buf.size > this.#size) { - this.#destroyFirstView(); - } - } - resize(newSize, idsToKeep = null) { - this.#size = newSize; - const buf = this.#buf; - if (idsToKeep) { - const ii = buf.size; - let i = 1; - for (const view of buf) { - if (idsToKeep.has(view.id)) { - buf.delete(view); - buf.add(view); - } - if (++i > ii) { - break; - } - } - } - while (buf.size > this.#size) { - this.#destroyFirstView(); - } - } - has(view) { - return this.#buf.has(view); - } - [Symbol.iterator]() { - return this.#buf.keys(); - } - #destroyFirstView() { - const firstView = this.#buf.keys().next().value; - firstView?.destroy(); - this.#buf.delete(firstView); - } -} -class PDFViewer { - #buffer = null; - #altTextManager = null; - #annotationEditorHighlightColors = null; - #annotationEditorMode = AnnotationEditorType.NONE; - #annotationEditorUIManager = null; - #annotationMode = AnnotationMode.ENABLE_FORMS; - #containerTopLeft = null; - #editorUndoBar = null; - #enableHWA = false; - #enableHighlightFloatingButton = false; - #enablePermissions = false; - #enableUpdatedAddImage = false; - #enableNewAltTextWhenAddingImage = false; - #eventAbortController = null; - #mlManager = null; - #switchAnnotationEditorModeAC = null; - #switchAnnotationEditorModeTimeoutId = null; - #getAllTextInProgress = false; - #hiddenCopyElement = null; - #interruptCopyCondition = false; - #previousContainerHeight = 0; - #resizeObserver = new ResizeObserver(this.#resizeObserverCallback.bind(this)); - #scrollModePageState = null; - #scaleTimeoutId = null; - #supportsPinchToZoom = true; - #textLayerMode = TextLayerMode.ENABLE; - constructor(options) { - const viewerVersion = "4.10.38"; - if (version !== viewerVersion) { - throw new Error(`The API version "${version}" does not match the Viewer version "${viewerVersion}".`); - } - this.container = options.container; - this.viewer = options.viewer || options.container.firstElementChild; - if (this.container?.tagName !== "DIV" || this.viewer?.tagName !== "DIV") { - throw new Error("Invalid `container` and/or `viewer` option."); - } - if (this.container.offsetParent && getComputedStyle(this.container).position !== "absolute") { - throw new Error("The `container` must be absolutely positioned."); - } - this.#resizeObserver.observe(this.container); - this.eventBus = options.eventBus; - this.linkService = options.linkService || new SimpleLinkService(); - this.downloadManager = options.downloadManager || null; - this.findController = options.findController || null; - this.#altTextManager = options.altTextManager || null; - this.#editorUndoBar = options.editorUndoBar || null; - if (this.findController) { - this.findController.onIsPageVisible = pageNumber => this._getVisiblePages().ids.has(pageNumber); - } - this._scriptingManager = options.scriptingManager || null; - this.#textLayerMode = options.textLayerMode ?? TextLayerMode.ENABLE; - this.#annotationMode = options.annotationMode ?? AnnotationMode.ENABLE_FORMS; - this.#annotationEditorMode = options.annotationEditorMode ?? AnnotationEditorType.NONE; - this.#annotationEditorHighlightColors = options.annotationEditorHighlightColors || null; - this.#enableHighlightFloatingButton = options.enableHighlightFloatingButton === true; - this.#enableUpdatedAddImage = options.enableUpdatedAddImage === true; - this.#enableNewAltTextWhenAddingImage = options.enableNewAltTextWhenAddingImage === true; - this.imageResourcesPath = options.imageResourcesPath || ""; - this.enablePrintAutoRotate = options.enablePrintAutoRotate || false; - this.removePageBorders = options.removePageBorders || false; - this.maxCanvasPixels = options.maxCanvasPixels; - this.l10n = options.l10n; - this.l10n ||= new genericl10n_GenericL10n(); - this.#enablePermissions = options.enablePermissions || false; - this.pageColors = options.pageColors || null; - this.#mlManager = options.mlManager || null; - this.#enableHWA = options.enableHWA || false; - this.#supportsPinchToZoom = options.supportsPinchToZoom !== false; - this.defaultRenderingQueue = !options.renderingQueue; - if (this.defaultRenderingQueue) { - this.renderingQueue = new PDFRenderingQueue(); - this.renderingQueue.setViewer(this); - } else { - this.renderingQueue = options.renderingQueue; - } - const { - abortSignal - } = options; - abortSignal?.addEventListener("abort", () => { - this.#resizeObserver.disconnect(); - this.#resizeObserver = null; - }, { - once: true - }); - this.scroll = watchScroll(this.container, this._scrollUpdate.bind(this), abortSignal); - this.presentationModeState = PresentationModeState.UNKNOWN; - this._resetView(); - if (this.removePageBorders) { - this.viewer.classList.add("removePageBorders"); - } - this.#updateContainerHeightCss(); - this.eventBus._on("thumbnailrendered", ({ - pageNumber, - pdfPage - }) => { - const pageView = this._pages[pageNumber - 1]; - if (!this.#buffer.has(pageView)) { - pdfPage?.cleanup(); - } - }); - if (!options.l10n) { - this.l10n.translate(this.container); - } - } - get pagesCount() { - return this._pages.length; - } - getPageView(index) { - return this._pages[index]; - } - getCachedPageViews() { - return new Set(this.#buffer); - } - get pageViewsReady() { - return this._pages.every(pageView => pageView?.pdfPage); - } - get renderForms() { - return this.#annotationMode === AnnotationMode.ENABLE_FORMS; - } - get enableScripting() { - return !!this._scriptingManager; - } - get currentPageNumber() { - return this._currentPageNumber; - } - set currentPageNumber(val) { - if (!Number.isInteger(val)) { - throw new Error("Invalid page number."); - } - if (!this.pdfDocument) { - return; - } - if (!this._setCurrentPageNumber(val, true)) { - console.error(`currentPageNumber: "${val}" is not a valid page.`); - } - } - _setCurrentPageNumber(val, resetCurrentPageView = false) { - if (this._currentPageNumber === val) { - if (resetCurrentPageView) { - this.#resetCurrentPageView(); - } - return true; - } - if (!(0 < val && val <= this.pagesCount)) { - return false; - } - const previous = this._currentPageNumber; - this._currentPageNumber = val; - this.eventBus.dispatch("pagechanging", { - source: this, - pageNumber: val, - pageLabel: this._pageLabels?.[val - 1] ?? null, - previous - }); - if (resetCurrentPageView) { - this.#resetCurrentPageView(); - } - return true; - } - get currentPageLabel() { - return this._pageLabels?.[this._currentPageNumber - 1] ?? null; - } - set currentPageLabel(val) { - if (!this.pdfDocument) { - return; - } - let page = val | 0; - if (this._pageLabels) { - const i = this._pageLabels.indexOf(val); - if (i >= 0) { - page = i + 1; - } - } - if (!this._setCurrentPageNumber(page, true)) { - console.error(`currentPageLabel: "${val}" is not a valid page.`); - } - } - get currentScale() { - return this._currentScale !== UNKNOWN_SCALE ? this._currentScale : DEFAULT_SCALE; - } - set currentScale(val) { - if (isNaN(val)) { - throw new Error("Invalid numeric scale."); - } - if (!this.pdfDocument) { - return; - } - this.#setScale(val, { - noScroll: false - }); - } - get currentScaleValue() { - return this._currentScaleValue; - } - set currentScaleValue(val) { - if (!this.pdfDocument) { - return; - } - this.#setScale(val, { - noScroll: false - }); - } - get pagesRotation() { - return this._pagesRotation; - } - set pagesRotation(rotation) { - if (!isValidRotation(rotation)) { - throw new Error("Invalid pages rotation angle."); - } - if (!this.pdfDocument) { - return; - } - rotation %= 360; - if (rotation < 0) { - rotation += 360; - } - if (this._pagesRotation === rotation) { - return; - } - this._pagesRotation = rotation; - const pageNumber = this._currentPageNumber; - this.refresh(true, { - rotation - }); - if (this._currentScaleValue) { - this.#setScale(this._currentScaleValue, { - noScroll: true - }); - } - this.eventBus.dispatch("rotationchanging", { - source: this, - pagesRotation: rotation, - pageNumber - }); - if (this.defaultRenderingQueue) { - this.update(); - } - } - get firstPagePromise() { - return this.pdfDocument ? this._firstPageCapability.promise : null; - } - get onePageRendered() { - return this.pdfDocument ? this._onePageRenderedCapability.promise : null; - } - get pagesPromise() { - return this.pdfDocument ? this._pagesCapability.promise : null; - } - get _layerProperties() { - const self = this; - return shadow(this, "_layerProperties", { - get annotationEditorUIManager() { - return self.#annotationEditorUIManager; - }, - get annotationStorage() { - return self.pdfDocument?.annotationStorage; - }, - get downloadManager() { - return self.downloadManager; - }, - get enableScripting() { - return !!self._scriptingManager; - }, - get fieldObjectsPromise() { - return self.pdfDocument?.getFieldObjects(); - }, - get findController() { - return self.findController; - }, - get hasJSActionsPromise() { - return self.pdfDocument?.hasJSActions(); - }, - get linkService() { - return self.linkService; - } - }); - } - #initializePermissions(permissions) { - const params = { - annotationEditorMode: this.#annotationEditorMode, - annotationMode: this.#annotationMode, - textLayerMode: this.#textLayerMode - }; - if (!permissions) { - return params; - } - if (!permissions.includes(PermissionFlag.COPY) && this.#textLayerMode === TextLayerMode.ENABLE) { - params.textLayerMode = TextLayerMode.ENABLE_PERMISSIONS; - } - if (!permissions.includes(PermissionFlag.MODIFY_CONTENTS)) { - params.annotationEditorMode = AnnotationEditorType.DISABLE; - } - if (!permissions.includes(PermissionFlag.MODIFY_ANNOTATIONS) && !permissions.includes(PermissionFlag.FILL_INTERACTIVE_FORMS) && this.#annotationMode === AnnotationMode.ENABLE_FORMS) { - params.annotationMode = AnnotationMode.ENABLE; - } - return params; - } - async #onePageRenderedOrForceFetch(signal) { - if (document.visibilityState === "hidden" || !this.container.offsetParent || this._getVisiblePages().views.length === 0) { - return; - } - const hiddenCapability = Promise.withResolvers(), - ac = new AbortController(); - document.addEventListener("visibilitychange", () => { - if (document.visibilityState === "hidden") { - hiddenCapability.resolve(); - } - }, { - signal: typeof AbortSignal.any === "function" ? AbortSignal.any([signal, ac.signal]) : signal - }); - await Promise.race([this._onePageRenderedCapability.promise, hiddenCapability.promise]); - ac.abort(); - } - async getAllText() { - const texts = []; - const buffer = []; - for (let pageNum = 1, pagesCount = this.pdfDocument.numPages; pageNum <= pagesCount; ++pageNum) { - if (this.#interruptCopyCondition) { - return null; - } - buffer.length = 0; - const page = await this.pdfDocument.getPage(pageNum); - const { - items - } = await page.getTextContent(); - for (const item of items) { - if (item.str) { - buffer.push(item.str); - } - if (item.hasEOL) { - buffer.push("\n"); - } - } - texts.push(removeNullCharacters(buffer.join(""))); - } - return texts.join("\n"); - } - #copyCallback(textLayerMode, event) { - const selection = document.getSelection(); - const { - focusNode, - anchorNode - } = selection; - if (anchorNode && focusNode && selection.containsNode(this.#hiddenCopyElement)) { - if (this.#getAllTextInProgress || textLayerMode === TextLayerMode.ENABLE_PERMISSIONS) { - stopEvent(event); - return; - } - this.#getAllTextInProgress = true; - const { - classList - } = this.viewer; - classList.add("copyAll"); - const ac = new AbortController(); - window.addEventListener("keydown", ev => this.#interruptCopyCondition = ev.key === "Escape", { - signal: ac.signal - }); - this.getAllText().then(async text => { - if (text !== null) { - await navigator.clipboard.writeText(text); - } - }).catch(reason => { - console.warn(`Something goes wrong when extracting the text: ${reason.message}`); - }).finally(() => { - this.#getAllTextInProgress = false; - this.#interruptCopyCondition = false; - ac.abort(); - classList.remove("copyAll"); - }); - stopEvent(event); - } - } - setDocument(pdfDocument) { - if (this.pdfDocument) { - this.eventBus.dispatch("pagesdestroy", { - source: this - }); - this._cancelRendering(); - this._resetView(); - this.findController?.setDocument(null); - this._scriptingManager?.setDocument(null); - this.#annotationEditorUIManager?.destroy(); - this.#annotationEditorUIManager = null; - } - this.pdfDocument = pdfDocument; - if (!pdfDocument) { - return; - } - const pagesCount = pdfDocument.numPages; - const firstPagePromise = pdfDocument.getPage(1); - const optionalContentConfigPromise = pdfDocument.getOptionalContentConfig({ - intent: "display" - }); - const permissionsPromise = this.#enablePermissions ? pdfDocument.getPermissions() : Promise.resolve(); - const { - eventBus, - pageColors, - viewer - } = this; - this.#eventAbortController = new AbortController(); - const { - signal - } = this.#eventAbortController; - if (pagesCount > PagesCountLimit.FORCE_SCROLL_MODE_PAGE) { - console.warn("Forcing PAGE-scrolling for performance reasons, given the length of the document."); - const mode = this._scrollMode = ScrollMode.PAGE; - eventBus.dispatch("scrollmodechanged", { - source: this, - mode - }); - } - this._pagesCapability.promise.then(() => { - eventBus.dispatch("pagesloaded", { - source: this, - pagesCount - }); - }, () => {}); - const onBeforeDraw = evt => { - const pageView = this._pages[evt.pageNumber - 1]; - if (!pageView) { - return; - } - this.#buffer.push(pageView); - }; - eventBus._on("pagerender", onBeforeDraw, { - signal - }); - const onAfterDraw = evt => { - if (evt.cssTransform) { - return; - } - this._onePageRenderedCapability.resolve({ - timestamp: evt.timestamp - }); - eventBus._off("pagerendered", onAfterDraw); - }; - eventBus._on("pagerendered", onAfterDraw, { - signal - }); - Promise.all([firstPagePromise, permissionsPromise]).then(([firstPdfPage, permissions]) => { - if (pdfDocument !== this.pdfDocument) { - return; - } - this._firstPageCapability.resolve(firstPdfPage); - this._optionalContentConfigPromise = optionalContentConfigPromise; - const { - annotationEditorMode, - annotationMode, - textLayerMode - } = this.#initializePermissions(permissions); - if (textLayerMode !== TextLayerMode.DISABLE) { - const element = this.#hiddenCopyElement = document.createElement("div"); - element.id = "hiddenCopyElement"; - viewer.before(element); - } - if (typeof AbortSignal.any === "function" && annotationEditorMode !== AnnotationEditorType.DISABLE) { - const mode = annotationEditorMode; - if (pdfDocument.isPureXfa) { - console.warn("Warning: XFA-editing is not implemented."); - } else if (isValidAnnotationEditorMode(mode)) { - this.#annotationEditorUIManager = new AnnotationEditorUIManager(this.container, viewer, this.#altTextManager, eventBus, pdfDocument, pageColors, this.#annotationEditorHighlightColors, this.#enableHighlightFloatingButton, this.#enableUpdatedAddImage, this.#enableNewAltTextWhenAddingImage, this.#mlManager, this.#editorUndoBar, this.#supportsPinchToZoom); - eventBus.dispatch("annotationeditoruimanager", { - source: this, - uiManager: this.#annotationEditorUIManager - }); - if (mode !== AnnotationEditorType.NONE) { - if (mode === AnnotationEditorType.STAMP) { - this.#mlManager?.loadModel("altText"); - } - this.#annotationEditorUIManager.updateMode(mode); - } - } else { - console.error(`Invalid AnnotationEditor mode: ${mode}`); - } - } - const viewerElement = this._scrollMode === ScrollMode.PAGE ? null : viewer; - const scale = this.currentScale; - const viewport = firstPdfPage.getViewport({ - scale: scale * PixelsPerInch.PDF_TO_CSS_UNITS - }); - viewer.style.setProperty("--scale-factor", viewport.scale); - if (pageColors?.background) { - viewer.style.setProperty("--page-bg-color", pageColors.background); - } - if (pageColors?.foreground === "CanvasText" || pageColors?.background === "Canvas") { - viewer.style.setProperty("--hcm-highlight-filter", pdfDocument.filterFactory.addHighlightHCMFilter("highlight", "CanvasText", "Canvas", "HighlightText", "Highlight")); - viewer.style.setProperty("--hcm-highlight-selected-filter", pdfDocument.filterFactory.addHighlightHCMFilter("highlight_selected", "CanvasText", "Canvas", "HighlightText", "ButtonText")); - } - for (let pageNum = 1; pageNum <= pagesCount; ++pageNum) { - const pageView = new PDFPageView({ - container: viewerElement, - eventBus, - id: pageNum, - scale, - defaultViewport: viewport.clone(), - optionalContentConfigPromise, - renderingQueue: this.renderingQueue, - textLayerMode, - annotationMode, - imageResourcesPath: this.imageResourcesPath, - maxCanvasPixels: this.maxCanvasPixels, - pageColors, - l10n: this.l10n, - layerProperties: this._layerProperties, - enableHWA: this.#enableHWA - }); - this._pages.push(pageView); - } - this._pages[0]?.setPdfPage(firstPdfPage); - if (this._scrollMode === ScrollMode.PAGE) { - this.#ensurePageViewVisible(); - } else if (this._spreadMode !== SpreadMode.NONE) { - this._updateSpreadMode(); - } - this.#onePageRenderedOrForceFetch(signal).then(async () => { - if (pdfDocument !== this.pdfDocument) { - return; - } - this.findController?.setDocument(pdfDocument); - this._scriptingManager?.setDocument(pdfDocument); - if (this.#hiddenCopyElement) { - document.addEventListener("copy", this.#copyCallback.bind(this, textLayerMode), { - signal - }); - } - if (this.#annotationEditorUIManager) { - eventBus.dispatch("annotationeditormodechanged", { - source: this, - mode: this.#annotationEditorMode - }); - } - if (pdfDocument.loadingParams.disableAutoFetch || pagesCount > PagesCountLimit.FORCE_LAZY_PAGE_INIT) { - this._pagesCapability.resolve(); - return; - } - let getPagesLeft = pagesCount - 1; - if (getPagesLeft <= 0) { - this._pagesCapability.resolve(); - return; - } - for (let pageNum = 2; pageNum <= pagesCount; ++pageNum) { - const promise = pdfDocument.getPage(pageNum).then(pdfPage => { - const pageView = this._pages[pageNum - 1]; - if (!pageView.pdfPage) { - pageView.setPdfPage(pdfPage); - } - if (--getPagesLeft === 0) { - this._pagesCapability.resolve(); - } - }, reason => { - console.error(`Unable to get page ${pageNum} to initialize viewer`, reason); - if (--getPagesLeft === 0) { - this._pagesCapability.resolve(); - } - }); - if (pageNum % PagesCountLimit.PAUSE_EAGER_PAGE_INIT === 0) { - await promise; - } - } - }); - eventBus.dispatch("pagesinit", { - source: this - }); - pdfDocument.getMetadata().then(({ - info - }) => { - if (pdfDocument !== this.pdfDocument) { - return; - } - if (info.Language) { - viewer.lang = info.Language; - } - }); - if (this.defaultRenderingQueue) { - this.update(); - } - }).catch(reason => { - console.error("Unable to initialize viewer", reason); - this._pagesCapability.reject(reason); - }); - } - setPageLabels(labels) { - if (!this.pdfDocument) { - return; - } - if (!labels) { - this._pageLabels = null; - } else if (!(Array.isArray(labels) && this.pdfDocument.numPages === labels.length)) { - this._pageLabels = null; - console.error(`setPageLabels: Invalid page labels.`); - } else { - this._pageLabels = labels; - } - for (let i = 0, ii = this._pages.length; i < ii; i++) { - this._pages[i].setPageLabel(this._pageLabels?.[i] ?? null); - } - } - _resetView() { - this._pages = []; - this._currentPageNumber = 1; - this._currentScale = UNKNOWN_SCALE; - this._currentScaleValue = null; - this._pageLabels = null; - this.#buffer = new PDFPageViewBuffer(DEFAULT_CACHE_SIZE); - this._location = null; - this._pagesRotation = 0; - this._optionalContentConfigPromise = null; - this._firstPageCapability = Promise.withResolvers(); - this._onePageRenderedCapability = Promise.withResolvers(); - this._pagesCapability = Promise.withResolvers(); - this._scrollMode = ScrollMode.VERTICAL; - this._previousScrollMode = ScrollMode.UNKNOWN; - this._spreadMode = SpreadMode.NONE; - this.#scrollModePageState = { - previousPageNumber: 1, - scrollDown: true, - pages: [] - }; - this.#eventAbortController?.abort(); - this.#eventAbortController = null; - this.viewer.textContent = ""; - this._updateScrollMode(); - this.viewer.removeAttribute("lang"); - this.#hiddenCopyElement?.remove(); - this.#hiddenCopyElement = null; - this.#cleanupSwitchAnnotationEditorMode(); - } - #ensurePageViewVisible() { - if (this._scrollMode !== ScrollMode.PAGE) { - throw new Error("#ensurePageViewVisible: Invalid scrollMode value."); - } - const pageNumber = this._currentPageNumber, - state = this.#scrollModePageState, - viewer = this.viewer; - viewer.textContent = ""; - state.pages.length = 0; - if (this._spreadMode === SpreadMode.NONE && !this.isInPresentationMode) { - const pageView = this._pages[pageNumber - 1]; - viewer.append(pageView.div); - state.pages.push(pageView); - } else { - const pageIndexSet = new Set(), - parity = this._spreadMode - 1; - if (parity === -1) { - pageIndexSet.add(pageNumber - 1); - } else if (pageNumber % 2 !== parity) { - pageIndexSet.add(pageNumber - 1); - pageIndexSet.add(pageNumber); - } else { - pageIndexSet.add(pageNumber - 2); - pageIndexSet.add(pageNumber - 1); - } - const spread = document.createElement("div"); - spread.className = "spread"; - if (this.isInPresentationMode) { - const dummyPage = document.createElement("div"); - dummyPage.className = "dummyPage"; - spread.append(dummyPage); - } - for (const i of pageIndexSet) { - const pageView = this._pages[i]; - if (!pageView) { - continue; - } - spread.append(pageView.div); - state.pages.push(pageView); - } - viewer.append(spread); - } - state.scrollDown = pageNumber >= state.previousPageNumber; - state.previousPageNumber = pageNumber; - } - _scrollUpdate() { - if (this.pagesCount === 0) { - return; - } - this.update(); - } - #scrollIntoView(pageView, pageSpot = null) { - const { - div, - id - } = pageView; - if (this._currentPageNumber !== id) { - this._setCurrentPageNumber(id); - } - if (this._scrollMode === ScrollMode.PAGE) { - this.#ensurePageViewVisible(); - this.update(); - } - if (!pageSpot && !this.isInPresentationMode) { - const left = div.offsetLeft + div.clientLeft, - right = left + div.clientWidth; - const { - scrollLeft, - clientWidth - } = this.container; - if (this._scrollMode === ScrollMode.HORIZONTAL || left < scrollLeft || right > scrollLeft + clientWidth) { - pageSpot = { - left: 0, - top: 0 - }; - } - } - scrollIntoView(div, pageSpot); - if (!this._currentScaleValue && this._location) { - this._location = null; - } - } - #isSameScale(newScale) { - return newScale === this._currentScale || Math.abs(newScale - this._currentScale) < 1e-15; - } - #setScaleUpdatePages(newScale, newValue, { - noScroll = false, - preset = false, - drawingDelay = -1, - origin = null - }) { - this._currentScaleValue = newValue.toString(); - if (this.#isSameScale(newScale)) { - if (preset) { - this.eventBus.dispatch("scalechanging", { - source: this, - scale: newScale, - presetValue: newValue - }); - } - return; - } - this.viewer.style.setProperty("--scale-factor", newScale * PixelsPerInch.PDF_TO_CSS_UNITS); - const postponeDrawing = drawingDelay >= 0 && drawingDelay < 1000; - this.refresh(true, { - scale: newScale, - drawingDelay: postponeDrawing ? drawingDelay : -1 - }); - if (postponeDrawing) { - this.#scaleTimeoutId = setTimeout(() => { - this.#scaleTimeoutId = null; - this.refresh(); - }, drawingDelay); - } - const previousScale = this._currentScale; - this._currentScale = newScale; - if (!noScroll) { - let page = this._currentPageNumber, - dest; - if (this._location && !(this.isInPresentationMode || this.isChangingPresentationMode)) { - page = this._location.pageNumber; - dest = [null, { - name: "XYZ" - }, this._location.left, this._location.top, null]; - } - this.scrollPageIntoView({ - pageNumber: page, - destArray: dest, - allowNegativeOffset: true - }); - if (Array.isArray(origin)) { - const scaleDiff = newScale / previousScale - 1; - const [top, left] = this.containerTopLeft; - this.container.scrollLeft += (origin[0] - left) * scaleDiff; - this.container.scrollTop += (origin[1] - top) * scaleDiff; - } - } - this.eventBus.dispatch("scalechanging", { - source: this, - scale: newScale, - presetValue: preset ? newValue : undefined - }); - if (this.defaultRenderingQueue) { - this.update(); - } - } - get #pageWidthScaleFactor() { - if (this._spreadMode !== SpreadMode.NONE && this._scrollMode !== ScrollMode.HORIZONTAL) { - return 2; - } - return 1; - } - #setScale(value, options) { - let scale = parseFloat(value); - if (scale > 0) { - options.preset = false; - this.#setScaleUpdatePages(scale, value, options); - } else { - const currentPage = this._pages[this._currentPageNumber - 1]; - if (!currentPage) { - return; - } - let hPadding = SCROLLBAR_PADDING, - vPadding = VERTICAL_PADDING; - if (this.isInPresentationMode) { - hPadding = vPadding = 4; - if (this._spreadMode !== SpreadMode.NONE) { - hPadding *= 2; - } - } else if (this.removePageBorders) { - hPadding = vPadding = 0; - } else if (this._scrollMode === ScrollMode.HORIZONTAL) { - [hPadding, vPadding] = [vPadding, hPadding]; - } - const pageWidthScale = (this.container.clientWidth - hPadding) / currentPage.width * currentPage.scale / this.#pageWidthScaleFactor; - const pageHeightScale = (this.container.clientHeight - vPadding) / currentPage.height * currentPage.scale; - switch (value) { - case "page-actual": - scale = 1; - break; - case "page-width": - scale = pageWidthScale; - break; - case "page-height": - scale = pageHeightScale; - break; - case "page-fit": - scale = Math.min(pageWidthScale, pageHeightScale); - break; - case "auto": - const horizontalScale = isPortraitOrientation(currentPage) ? pageWidthScale : Math.min(pageHeightScale, pageWidthScale); - scale = Math.min(MAX_AUTO_SCALE, horizontalScale); - break; - default: - console.error(`#setScale: "${value}" is an unknown zoom value.`); - return; - } - options.preset = true; - this.#setScaleUpdatePages(scale, value, options); - } - } - #resetCurrentPageView() { - const pageView = this._pages[this._currentPageNumber - 1]; - if (this.isInPresentationMode) { - this.#setScale(this._currentScaleValue, { - noScroll: true - }); - } - this.#scrollIntoView(pageView); - } - pageLabelToPageNumber(label) { - if (!this._pageLabels) { - return null; - } - const i = this._pageLabels.indexOf(label); - if (i < 0) { - return null; - } - return i + 1; - } - scrollPageIntoView({ - pageNumber, - destArray = null, - allowNegativeOffset = false, - ignoreDestinationZoom = false - }) { - if (!this.pdfDocument) { - return; - } - const pageView = Number.isInteger(pageNumber) && this._pages[pageNumber - 1]; - if (!pageView) { - console.error(`scrollPageIntoView: "${pageNumber}" is not a valid pageNumber parameter.`); - return; - } - if (this.isInPresentationMode || !destArray) { - this._setCurrentPageNumber(pageNumber, true); - return; - } - let x = 0, - y = 0; - let width = 0, - height = 0, - widthScale, - heightScale; - const changeOrientation = pageView.rotation % 180 !== 0; - const pageWidth = (changeOrientation ? pageView.height : pageView.width) / pageView.scale / PixelsPerInch.PDF_TO_CSS_UNITS; - const pageHeight = (changeOrientation ? pageView.width : pageView.height) / pageView.scale / PixelsPerInch.PDF_TO_CSS_UNITS; - let scale = 0; - switch (destArray[1].name) { - case "XYZ": - x = destArray[2]; - y = destArray[3]; - scale = destArray[4]; - x = x !== null ? x : 0; - y = y !== null ? y : pageHeight; - break; - case "Fit": - case "FitB": - scale = "page-fit"; - break; - case "FitH": - case "FitBH": - y = destArray[2]; - scale = "page-width"; - if (y === null && this._location) { - x = this._location.left; - y = this._location.top; - } else if (typeof y !== "number" || y < 0) { - y = pageHeight; - } - break; - case "FitV": - case "FitBV": - x = destArray[2]; - width = pageWidth; - height = pageHeight; - scale = "page-height"; - break; - case "FitR": - x = destArray[2]; - y = destArray[3]; - width = destArray[4] - x; - height = destArray[5] - y; - let hPadding = SCROLLBAR_PADDING, - vPadding = VERTICAL_PADDING; - if (this.removePageBorders) { - hPadding = vPadding = 0; - } - widthScale = (this.container.clientWidth - hPadding) / width / PixelsPerInch.PDF_TO_CSS_UNITS; - heightScale = (this.container.clientHeight - vPadding) / height / PixelsPerInch.PDF_TO_CSS_UNITS; - scale = Math.min(Math.abs(widthScale), Math.abs(heightScale)); - break; - default: - console.error(`scrollPageIntoView: "${destArray[1].name}" is not a valid destination type.`); - return; - } - if (!ignoreDestinationZoom) { - if (scale && scale !== this._currentScale) { - this.currentScaleValue = scale; - } else if (this._currentScale === UNKNOWN_SCALE) { - this.currentScaleValue = DEFAULT_SCALE_VALUE; - } - } - if (scale === "page-fit" && !destArray[4]) { - this.#scrollIntoView(pageView); - return; - } - const boundingRect = [pageView.viewport.convertToViewportPoint(x, y), pageView.viewport.convertToViewportPoint(x + width, y + height)]; - let left = Math.min(boundingRect[0][0], boundingRect[1][0]); - let top = Math.min(boundingRect[0][1], boundingRect[1][1]); - if (!allowNegativeOffset) { - left = Math.max(left, 0); - top = Math.max(top, 0); - } - this.#scrollIntoView(pageView, { - left, - top - }); - } - _updateLocation(firstPage) { - const currentScale = this._currentScale; - const currentScaleValue = this._currentScaleValue; - const normalizedScaleValue = parseFloat(currentScaleValue) === currentScale ? Math.round(currentScale * 10000) / 100 : currentScaleValue; - const pageNumber = firstPage.id; - const currentPageView = this._pages[pageNumber - 1]; - const container = this.container; - const topLeft = currentPageView.getPagePoint(container.scrollLeft - firstPage.x, container.scrollTop - firstPage.y); - const intLeft = Math.round(topLeft[0]); - const intTop = Math.round(topLeft[1]); - let pdfOpenParams = `#page=${pageNumber}`; - if (!this.isInPresentationMode) { - pdfOpenParams += `&zoom=${normalizedScaleValue},${intLeft},${intTop}`; - } - this._location = { - pageNumber, - scale: normalizedScaleValue, - top: intTop, - left: intLeft, - rotation: this._pagesRotation, - pdfOpenParams - }; - } - update() { - const visible = this._getVisiblePages(); - const visiblePages = visible.views, - numVisiblePages = visiblePages.length; - if (numVisiblePages === 0) { - return; - } - const newCacheSize = Math.max(DEFAULT_CACHE_SIZE, 2 * numVisiblePages + 1); - this.#buffer.resize(newCacheSize, visible.ids); - this.renderingQueue.renderHighestPriority(visible); - const isSimpleLayout = this._spreadMode === SpreadMode.NONE && (this._scrollMode === ScrollMode.PAGE || this._scrollMode === ScrollMode.VERTICAL); - const currentId = this._currentPageNumber; - let stillFullyVisible = false; - for (const page of visiblePages) { - if (page.percent < 100) { - break; - } - if (page.id === currentId && isSimpleLayout) { - stillFullyVisible = true; - break; - } - } - this._setCurrentPageNumber(stillFullyVisible ? currentId : visiblePages[0].id); - this._updateLocation(visible.first); - this.eventBus.dispatch("updateviewarea", { - source: this, - location: this._location - }); - } - #switchToEditAnnotationMode() { - const visible = this._getVisiblePages(); - const pagesToRefresh = []; - const { - ids, - views - } = visible; - for (const page of views) { - const { - view - } = page; - if (!view.hasEditableAnnotations()) { - ids.delete(view.id); - continue; - } - pagesToRefresh.push(page); - } - if (pagesToRefresh.length === 0) { - return null; - } - this.renderingQueue.renderHighestPriority({ - first: pagesToRefresh[0], - last: pagesToRefresh.at(-1), - views: pagesToRefresh, - ids - }); - return ids; - } - containsElement(element) { - return this.container.contains(element); - } - focus() { - this.container.focus(); - } - get _isContainerRtl() { - return getComputedStyle(this.container).direction === "rtl"; - } - get isInPresentationMode() { - return this.presentationModeState === PresentationModeState.FULLSCREEN; - } - get isChangingPresentationMode() { - return this.presentationModeState === PresentationModeState.CHANGING; - } - get isHorizontalScrollbarEnabled() { - return this.isInPresentationMode ? false : this.container.scrollWidth > this.container.clientWidth; - } - get isVerticalScrollbarEnabled() { - return this.isInPresentationMode ? false : this.container.scrollHeight > this.container.clientHeight; - } - _getVisiblePages() { - const views = this._scrollMode === ScrollMode.PAGE ? this.#scrollModePageState.pages : this._pages, - horizontal = this._scrollMode === ScrollMode.HORIZONTAL, - rtl = horizontal && this._isContainerRtl; - return getVisibleElements({ - scrollEl: this.container, - views, - sortByVisibility: true, - horizontal, - rtl - }); - } - cleanup() { - for (const pageView of this._pages) { - if (pageView.renderingState !== RenderingStates.FINISHED) { - pageView.reset(); - } - } - } - _cancelRendering() { - for (const pageView of this._pages) { - pageView.cancelRendering(); - } - } - async #ensurePdfPageLoaded(pageView) { - if (pageView.pdfPage) { - return pageView.pdfPage; - } - try { - const pdfPage = await this.pdfDocument.getPage(pageView.id); - if (!pageView.pdfPage) { - pageView.setPdfPage(pdfPage); - } - return pdfPage; - } catch (reason) { - console.error("Unable to get page for page view", reason); - return null; - } - } - #getScrollAhead(visible) { - if (visible.first?.id === 1) { - return true; - } else if (visible.last?.id === this.pagesCount) { - return false; - } - switch (this._scrollMode) { - case ScrollMode.PAGE: - return this.#scrollModePageState.scrollDown; - case ScrollMode.HORIZONTAL: - return this.scroll.right; - } - return this.scroll.down; - } - forceRendering(currentlyVisiblePages) { - const visiblePages = currentlyVisiblePages || this._getVisiblePages(); - const scrollAhead = this.#getScrollAhead(visiblePages); - const preRenderExtra = this._spreadMode !== SpreadMode.NONE && this._scrollMode !== ScrollMode.HORIZONTAL; - const pageView = this.renderingQueue.getHighestPriority(visiblePages, this._pages, scrollAhead, preRenderExtra); - if (pageView) { - this.#ensurePdfPageLoaded(pageView).then(() => { - this.renderingQueue.renderView(pageView); - }); - return true; - } - return false; - } - get hasEqualPageSizes() { - const firstPageView = this._pages[0]; - for (let i = 1, ii = this._pages.length; i < ii; ++i) { - const pageView = this._pages[i]; - if (pageView.width !== firstPageView.width || pageView.height !== firstPageView.height) { - return false; - } - } - return true; - } - getPagesOverview() { - let initialOrientation; - return this._pages.map(pageView => { - const viewport = pageView.pdfPage.getViewport({ - scale: 1 - }); - const orientation = isPortraitOrientation(viewport); - if (initialOrientation === undefined) { - initialOrientation = orientation; - } else if (this.enablePrintAutoRotate && orientation !== initialOrientation) { - return { - width: viewport.height, - height: viewport.width, - rotation: (viewport.rotation - 90) % 360 - }; - } - return { - width: viewport.width, - height: viewport.height, - rotation: viewport.rotation - }; - }); - } - get optionalContentConfigPromise() { - if (!this.pdfDocument) { - return Promise.resolve(null); - } - if (!this._optionalContentConfigPromise) { - console.error("optionalContentConfigPromise: Not initialized yet."); - return this.pdfDocument.getOptionalContentConfig({ - intent: "display" - }); - } - return this._optionalContentConfigPromise; - } - set optionalContentConfigPromise(promise) { - if (!(promise instanceof Promise)) { - throw new Error(`Invalid optionalContentConfigPromise: ${promise}`); - } - if (!this.pdfDocument) { - return; - } - if (!this._optionalContentConfigPromise) { - return; - } - this._optionalContentConfigPromise = promise; - this.refresh(false, { - optionalContentConfigPromise: promise - }); - this.eventBus.dispatch("optionalcontentconfigchanged", { - source: this, - promise - }); - } - get scrollMode() { - return this._scrollMode; - } - set scrollMode(mode) { - if (this._scrollMode === mode) { - return; - } - if (!isValidScrollMode(mode)) { - throw new Error(`Invalid scroll mode: ${mode}`); - } - if (this.pagesCount > PagesCountLimit.FORCE_SCROLL_MODE_PAGE) { - return; - } - this._previousScrollMode = this._scrollMode; - this._scrollMode = mode; - this.eventBus.dispatch("scrollmodechanged", { - source: this, - mode - }); - this._updateScrollMode(this._currentPageNumber); - } - _updateScrollMode(pageNumber = null) { - const scrollMode = this._scrollMode, - viewer = this.viewer; - viewer.classList.toggle("scrollHorizontal", scrollMode === ScrollMode.HORIZONTAL); - viewer.classList.toggle("scrollWrapped", scrollMode === ScrollMode.WRAPPED); - if (!this.pdfDocument || !pageNumber) { - return; - } - if (scrollMode === ScrollMode.PAGE) { - this.#ensurePageViewVisible(); - } else if (this._previousScrollMode === ScrollMode.PAGE) { - this._updateSpreadMode(); - } - if (this._currentScaleValue && isNaN(this._currentScaleValue)) { - this.#setScale(this._currentScaleValue, { - noScroll: true - }); - } - this._setCurrentPageNumber(pageNumber, true); - this.update(); - } - get spreadMode() { - return this._spreadMode; - } - set spreadMode(mode) { - if (this._spreadMode === mode) { - return; - } - if (!isValidSpreadMode(mode)) { - throw new Error(`Invalid spread mode: ${mode}`); - } - this._spreadMode = mode; - this.eventBus.dispatch("spreadmodechanged", { - source: this, - mode - }); - this._updateSpreadMode(this._currentPageNumber); - } - _updateSpreadMode(pageNumber = null) { - if (!this.pdfDocument) { - return; - } - const viewer = this.viewer, - pages = this._pages; - if (this._scrollMode === ScrollMode.PAGE) { - this.#ensurePageViewVisible(); - } else { - viewer.textContent = ""; - if (this._spreadMode === SpreadMode.NONE) { - for (const pageView of this._pages) { - viewer.append(pageView.div); - } - } else { - const parity = this._spreadMode - 1; - let spread = null; - for (let i = 0, ii = pages.length; i < ii; ++i) { - if (spread === null) { - spread = document.createElement("div"); - spread.className = "spread"; - viewer.append(spread); - } else if (i % 2 === parity) { - spread = spread.cloneNode(false); - viewer.append(spread); - } - spread.append(pages[i].div); - } - } - } - if (!pageNumber) { - return; - } - if (this._currentScaleValue && isNaN(this._currentScaleValue)) { - this.#setScale(this._currentScaleValue, { - noScroll: true - }); - } - this._setCurrentPageNumber(pageNumber, true); - this.update(); - } - _getPageAdvance(currentPageNumber, previous = false) { - switch (this._scrollMode) { - case ScrollMode.WRAPPED: - { - const { - views - } = this._getVisiblePages(), - pageLayout = new Map(); - for (const { - id, - y, - percent, - widthPercent - } of views) { - if (percent === 0 || widthPercent < 100) { - continue; - } - let yArray = pageLayout.get(y); - if (!yArray) { - pageLayout.set(y, yArray ||= []); - } - yArray.push(id); - } - for (const yArray of pageLayout.values()) { - const currentIndex = yArray.indexOf(currentPageNumber); - if (currentIndex === -1) { - continue; - } - const numPages = yArray.length; - if (numPages === 1) { - break; - } - if (previous) { - for (let i = currentIndex - 1, ii = 0; i >= ii; i--) { - const currentId = yArray[i], - expectedId = yArray[i + 1] - 1; - if (currentId < expectedId) { - return currentPageNumber - expectedId; - } - } - } else { - for (let i = currentIndex + 1, ii = numPages; i < ii; i++) { - const currentId = yArray[i], - expectedId = yArray[i - 1] + 1; - if (currentId > expectedId) { - return expectedId - currentPageNumber; - } - } - } - if (previous) { - const firstId = yArray[0]; - if (firstId < currentPageNumber) { - return currentPageNumber - firstId + 1; - } - } else { - const lastId = yArray[numPages - 1]; - if (lastId > currentPageNumber) { - return lastId - currentPageNumber + 1; - } - } - break; - } - break; - } - case ScrollMode.HORIZONTAL: - { - break; - } - case ScrollMode.PAGE: - case ScrollMode.VERTICAL: - { - if (this._spreadMode === SpreadMode.NONE) { - break; - } - const parity = this._spreadMode - 1; - if (previous && currentPageNumber % 2 !== parity) { - break; - } else if (!previous && currentPageNumber % 2 === parity) { - break; - } - const { - views - } = this._getVisiblePages(), - expectedId = previous ? currentPageNumber - 1 : currentPageNumber + 1; - for (const { - id, - percent, - widthPercent - } of views) { - if (id !== expectedId) { - continue; - } - if (percent > 0 && widthPercent === 100) { - return 2; - } - break; - } - break; - } - } - return 1; - } - nextPage() { - const currentPageNumber = this._currentPageNumber, - pagesCount = this.pagesCount; - if (currentPageNumber >= pagesCount) { - return false; - } - const advance = this._getPageAdvance(currentPageNumber, false) || 1; - this.currentPageNumber = Math.min(currentPageNumber + advance, pagesCount); - return true; - } - previousPage() { - const currentPageNumber = this._currentPageNumber; - if (currentPageNumber <= 1) { - return false; - } - const advance = this._getPageAdvance(currentPageNumber, true) || 1; - this.currentPageNumber = Math.max(currentPageNumber - advance, 1); - return true; - } - updateScale({ - drawingDelay, - scaleFactor = null, - steps = null, - origin - }) { - if (steps === null && scaleFactor === null) { - throw new Error("Invalid updateScale options: either `steps` or `scaleFactor` must be provided."); - } - if (!this.pdfDocument) { - return; - } - let newScale = this._currentScale; - if (scaleFactor > 0 && scaleFactor !== 1) { - newScale = Math.round(newScale * scaleFactor * 100) / 100; - } else if (steps) { - const delta = steps > 0 ? DEFAULT_SCALE_DELTA : 1 / DEFAULT_SCALE_DELTA; - const round = steps > 0 ? Math.ceil : Math.floor; - steps = Math.abs(steps); - do { - newScale = round((newScale * delta).toFixed(2) * 10) / 10; - } while (--steps > 0); - } - newScale = Math.max(MIN_SCALE, Math.min(MAX_SCALE, newScale)); - this.#setScale(newScale, { - noScroll: false, - drawingDelay, - origin - }); - } - increaseScale(options = {}) { - this.updateScale({ - ...options, - steps: options.steps ?? 1 - }); - } - decreaseScale(options = {}) { - this.updateScale({ - ...options, - steps: -(options.steps ?? 1) - }); - } - #updateContainerHeightCss(height = this.container.clientHeight) { - if (height !== this.#previousContainerHeight) { - this.#previousContainerHeight = height; - docStyle.setProperty("--viewer-container-height", `${height}px`); - } - } - #resizeObserverCallback(entries) { - for (const entry of entries) { - if (entry.target === this.container) { - this.#updateContainerHeightCss(Math.floor(entry.borderBoxSize[0].blockSize)); - this.#containerTopLeft = null; - break; - } - } - } - get containerTopLeft() { - return this.#containerTopLeft ||= [this.container.offsetTop, this.container.offsetLeft]; - } - #cleanupSwitchAnnotationEditorMode() { - this.#switchAnnotationEditorModeAC?.abort(); - this.#switchAnnotationEditorModeAC = null; - if (this.#switchAnnotationEditorModeTimeoutId !== null) { - clearTimeout(this.#switchAnnotationEditorModeTimeoutId); - this.#switchAnnotationEditorModeTimeoutId = null; - } - } - get annotationEditorMode() { - return this.#annotationEditorUIManager ? this.#annotationEditorMode : AnnotationEditorType.DISABLE; - } - set annotationEditorMode({ - mode, - editId = null, - isFromKeyboard = false - }) { - if (!this.#annotationEditorUIManager) { - throw new Error(`The AnnotationEditor is not enabled.`); - } - if (this.#annotationEditorMode === mode) { - return; - } - if (!isValidAnnotationEditorMode(mode)) { - throw new Error(`Invalid AnnotationEditor mode: ${mode}`); - } - if (!this.pdfDocument) { - return; - } - if (mode === AnnotationEditorType.STAMP) { - this.#mlManager?.loadModel("altText"); - } - const { - eventBus - } = this; - const updater = () => { - this.#cleanupSwitchAnnotationEditorMode(); - this.#annotationEditorMode = mode; - this.#annotationEditorUIManager.updateMode(mode, editId, isFromKeyboard); - eventBus.dispatch("annotationeditormodechanged", { - source: this, - mode - }); - }; - if (mode === AnnotationEditorType.NONE || this.#annotationEditorMode === AnnotationEditorType.NONE) { - const isEditing = mode !== AnnotationEditorType.NONE; - if (!isEditing) { - this.pdfDocument.annotationStorage.resetModifiedIds(); - } - for (const pageView of this._pages) { - pageView.toggleEditingMode(isEditing); - } - const idsToRefresh = this.#switchToEditAnnotationMode(); - if (isEditing && idsToRefresh) { - this.#cleanupSwitchAnnotationEditorMode(); - this.#switchAnnotationEditorModeAC = new AbortController(); - const signal = AbortSignal.any([this.#eventAbortController.signal, this.#switchAnnotationEditorModeAC.signal]); - eventBus._on("pagerendered", ({ - pageNumber - }) => { - idsToRefresh.delete(pageNumber); - if (idsToRefresh.size === 0) { - this.#switchAnnotationEditorModeTimeoutId = setTimeout(updater, 0); - } - }, { - signal - }); - return; - } - } - updater(); - } - refresh(noUpdate = false, updateArgs = Object.create(null)) { - if (!this.pdfDocument) { - return; - } - for (const pageView of this._pages) { - pageView.update(updateArgs); - } - if (this.#scaleTimeoutId !== null) { - clearTimeout(this.#scaleTimeoutId); - this.#scaleTimeoutId = null; - } - if (!noUpdate) { - this.update(); - } - } -} - -;// ./web/pdf_single_page_viewer.js - - -class PDFSinglePageViewer extends PDFViewer { - _resetView() { - super._resetView(); - this._scrollMode = ScrollMode.PAGE; - this._spreadMode = SpreadMode.NONE; - } - set scrollMode(mode) {} - _updateScrollMode() {} - set spreadMode(mode) {} - _updateSpreadMode() {} -} - -;// ./web/pdf_viewer.component.js - - - - - - - - - - - - - - - -const pdfjsVersion = "4.10.38"; -const pdfjsBuild = "f9bea397f"; - -var __webpack_exports__AnnotationLayerBuilder = __webpack_exports__.AnnotationLayerBuilder; -var __webpack_exports__DownloadManager = __webpack_exports__.DownloadManager; -var __webpack_exports__EventBus = __webpack_exports__.EventBus; -var __webpack_exports__FindState = __webpack_exports__.FindState; -var __webpack_exports__GenericL10n = __webpack_exports__.GenericL10n; -var __webpack_exports__LinkTarget = __webpack_exports__.LinkTarget; -var __webpack_exports__PDFFindController = __webpack_exports__.PDFFindController; -var __webpack_exports__PDFHistory = __webpack_exports__.PDFHistory; -var __webpack_exports__PDFLinkService = __webpack_exports__.PDFLinkService; -var __webpack_exports__PDFPageView = __webpack_exports__.PDFPageView; -var __webpack_exports__PDFScriptingManager = __webpack_exports__.PDFScriptingManager; -var __webpack_exports__PDFSinglePageViewer = __webpack_exports__.PDFSinglePageViewer; -var __webpack_exports__PDFViewer = __webpack_exports__.PDFViewer; -var __webpack_exports__ProgressBar = __webpack_exports__.ProgressBar; -var __webpack_exports__RenderingStates = __webpack_exports__.RenderingStates; -var __webpack_exports__ScrollMode = __webpack_exports__.ScrollMode; -var __webpack_exports__SimpleLinkService = __webpack_exports__.SimpleLinkService; -var __webpack_exports__SpreadMode = __webpack_exports__.SpreadMode; -var __webpack_exports__StructTreeLayerBuilder = __webpack_exports__.StructTreeLayerBuilder; -var __webpack_exports__TextLayerBuilder = __webpack_exports__.TextLayerBuilder; -var __webpack_exports__XfaLayerBuilder = __webpack_exports__.XfaLayerBuilder; -var __webpack_exports__parseQueryString = __webpack_exports__.parseQueryString; -export { __webpack_exports__AnnotationLayerBuilder as AnnotationLayerBuilder, __webpack_exports__DownloadManager as DownloadManager, __webpack_exports__EventBus as EventBus, __webpack_exports__FindState as FindState, __webpack_exports__GenericL10n as GenericL10n, __webpack_exports__LinkTarget as LinkTarget, __webpack_exports__PDFFindController as PDFFindController, __webpack_exports__PDFHistory as PDFHistory, __webpack_exports__PDFLinkService as PDFLinkService, __webpack_exports__PDFPageView as PDFPageView, __webpack_exports__PDFScriptingManager as PDFScriptingManager, __webpack_exports__PDFSinglePageViewer as PDFSinglePageViewer, __webpack_exports__PDFViewer as PDFViewer, __webpack_exports__ProgressBar as ProgressBar, __webpack_exports__RenderingStates as RenderingStates, __webpack_exports__ScrollMode as ScrollMode, __webpack_exports__SimpleLinkService as SimpleLinkService, __webpack_exports__SpreadMode as SpreadMode, __webpack_exports__StructTreeLayerBuilder as StructTreeLayerBuilder, __webpack_exports__TextLayerBuilder as TextLayerBuilder, __webpack_exports__XfaLayerBuilder as XfaLayerBuilder, __webpack_exports__parseQueryString as parseQueryString }; - -//# sourceMappingURL=pdf_viewer.mjs.map \ No newline at end of file diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/tailwindcss/README.md b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/tailwindcss/README.md deleted file mode 100644 index 69fb53bf322..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/tailwindcss/README.md +++ /dev/null @@ -1,7 +0,0 @@ -tailwindcss version 4.0.3 -https://github.com/tailwindlabs/tailwindcss -License: MIT - -This template uses only `preflight.css`, the CSS reset stylesheet from Tailwind. For simplicity, this template doesn't use a complete deployment of Tailwind. If you want to use the full Tailwind library, remove `preflight.css` and reference the full version of Tailwind. - -To update, replace the `preflight.css` file with the one in an updated build from https://www.npmjs.com/package/tailwindcss diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/tailwindcss/dist/preflight.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/tailwindcss/dist/preflight.css deleted file mode 100644 index 178c881dd23..00000000000 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/wwwroot/lib/tailwindcss/dist/preflight.css +++ /dev/null @@ -1,383 +0,0 @@ -/* - 1. Prevent padding and border from affecting element width. (https://github.com/mozdevs/cssremedy/issues/4) - 2. Remove default margins and padding - 3. Reset all borders. -*/ - -*, -::after, -::before, -::backdrop, -::file-selector-button { - box-sizing: border-box; /* 1 */ - margin: 0; /* 2 */ - padding: 0; /* 2 */ - border: 0 solid; /* 3 */ -} - -/* - 1. Use a consistent sensible line-height in all browsers. - 2. Prevent adjustments of font size after orientation changes in iOS. - 3. Use a more readable tab size. - 4. Use the user's configured `sans` font-family by default. - 5. Use the user's configured `sans` font-feature-settings by default. - 6. Use the user's configured `sans` font-variation-settings by default. - 7. Disable tap highlights on iOS. -*/ - -html, -:host { - line-height: 1.5; /* 1 */ - -webkit-text-size-adjust: 100%; /* 2 */ - tab-size: 4; /* 3 */ - font-family: var( - --default-font-family, - ui-sans-serif, - system-ui, - sans-serif, - 'Apple Color Emoji', - 'Segoe UI Emoji', - 'Segoe UI Symbol', - 'Noto Color Emoji' - ); /* 4 */ - font-feature-settings: var(--default-font-feature-settings, normal); /* 5 */ - font-variation-settings: var(--default-font-variation-settings, normal); /* 6 */ - -webkit-tap-highlight-color: transparent; /* 7 */ -} - -/* - Inherit line-height from `html` so users can set them as a class directly on the `html` element. -*/ - -body { - line-height: inherit; -} - -/* - 1. Add the correct height in Firefox. - 2. Correct the inheritance of border color in Firefox. (https://bugzilla.mozilla.org/show_bug.cgi?id=190655) - 3. Reset the default border style to a 1px solid border. -*/ - -hr { - height: 0; /* 1 */ - color: inherit; /* 2 */ - border-top-width: 1px; /* 3 */ -} - -/* - Add the correct text decoration in Chrome, Edge, and Safari. -*/ - -abbr:where([title]) { - -webkit-text-decoration: underline dotted; - text-decoration: underline dotted; -} - -/* - Remove the default font size and weight for headings. -*/ - -h1, -h2, -h3, -h4, -h5, -h6 { - font-size: inherit; - font-weight: inherit; -} - -/* - Reset links to optimize for opt-in styling instead of opt-out. -*/ - -a { - color: inherit; - -webkit-text-decoration: inherit; - text-decoration: inherit; -} - -/* - Add the correct font weight in Edge and Safari. -*/ - -b, -strong { - font-weight: bolder; -} - -/* - 1. Use the user's configured `mono` font-family by default. - 2. Use the user's configured `mono` font-feature-settings by default. - 3. Use the user's configured `mono` font-variation-settings by default. - 4. Correct the odd `em` font sizing in all browsers. -*/ - -code, -kbd, -samp, -pre { - font-family: var( - --default-mono-font-family, - ui-monospace, - SFMono-Regular, - Menlo, - Monaco, - Consolas, - 'Liberation Mono', - 'Courier New', - monospace - ); /* 4 */ - font-feature-settings: var(--default-mono-font-feature-settings, normal); /* 5 */ - font-variation-settings: var(--default-mono-font-variation-settings, normal); /* 6 */ - font-size: 1em; /* 4 */ -} - -/* - Add the correct font size in all browsers. -*/ - -small { - font-size: 80%; -} - -/* - Prevent `sub` and `sup` elements from affecting the line height in all browsers. -*/ - -sub, -sup { - font-size: 75%; - line-height: 0; - position: relative; - vertical-align: baseline; -} - -sub { - bottom: -0.25em; -} - -sup { - top: -0.5em; -} - -/* - 1. Remove text indentation from table contents in Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=999088, https://bugs.webkit.org/show_bug.cgi?id=201297) - 2. Correct table border color inheritance in all Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=935729, https://bugs.webkit.org/show_bug.cgi?id=195016) - 3. Remove gaps between table borders by default. -*/ - -table { - text-indent: 0; /* 1 */ - border-color: inherit; /* 2 */ - border-collapse: collapse; /* 3 */ -} - -/* - Use the modern Firefox focus style for all focusable elements. -*/ - -:-moz-focusring { - outline: auto; -} - -/* - Add the correct vertical alignment in Chrome and Firefox. -*/ - -progress { - vertical-align: baseline; -} - -/* - Add the correct display in Chrome and Safari. -*/ - -summary { - display: list-item; -} - -/* - Make lists unstyled by default. -*/ - -ol, -ul, -menu { - list-style: none; -} - -/* - 1. Make replaced elements `display: block` by default. (https://github.com/mozdevs/cssremedy/issues/14) - 2. Add `vertical-align: middle` to align replaced elements more sensibly by default. (https://github.com/jensimmons/cssremedy/issues/14#issuecomment-634934210) - This can trigger a poorly considered lint error in some tools but is included by design. -*/ - -img, -svg, -video, -canvas, -audio, -iframe, -embed, -object { - display: block; /* 1 */ - vertical-align: middle; /* 2 */ -} - -/* - Constrain images and videos to the parent width and preserve their intrinsic aspect ratio. (https://github.com/mozdevs/cssremedy/issues/14) -*/ - -img, -video { - max-width: 100%; - height: auto; -} - -/* - 1. Inherit font styles in all browsers. - 2. Remove border radius in all browsers. - 3. Remove background color in all browsers. - 4. Ensure consistent opacity for disabled states in all browsers. -*/ - -button, -input, -select, -optgroup, -textarea, -::file-selector-button { - font: inherit; /* 1 */ - font-feature-settings: inherit; /* 1 */ - font-variation-settings: inherit; /* 1 */ - letter-spacing: inherit; /* 1 */ - color: inherit; /* 1 */ - border-radius: 0; /* 2 */ - background-color: transparent; /* 3 */ - opacity: 1; /* 4 */ -} - -/* - Restore default font weight. -*/ - -:where(select:is([multiple], [size])) optgroup { - font-weight: bolder; -} - -/* - Restore indentation. -*/ - -:where(select:is([multiple], [size])) optgroup option { - padding-inline-start: 20px; -} - -/* - Restore space after button. -*/ - -::file-selector-button { - margin-inline-end: 4px; -} - -/* - 1. Reset the default placeholder opacity in Firefox. (https://github.com/tailwindlabs/tailwindcss/issues/3300) - 2. Set the default placeholder color to a semi-transparent version of the current text color. -*/ - -::placeholder { - opacity: 1; /* 1 */ - color: color-mix(in oklab, currentColor 50%, transparent); /* 2 */ -} - -/* - Prevent resizing textareas horizontally by default. -*/ - -textarea { - resize: vertical; -} - -/* - Remove the inner padding in Chrome and Safari on macOS. -*/ - -::-webkit-search-decoration { - -webkit-appearance: none; -} - -/* - 1. Ensure date/time inputs have the same height when empty in iOS Safari. - 2. Ensure text alignment can be changed on date/time inputs in iOS Safari. -*/ - -::-webkit-date-and-time-value { - min-height: 1lh; /* 1 */ - text-align: inherit; /* 2 */ -} - -/* - Prevent height from changing on date/time inputs in macOS Safari when the input is set to `display: block`. -*/ - -::-webkit-datetime-edit { - display: inline-flex; -} - -/* - Remove excess padding from pseudo-elements in date/time inputs to ensure consistent height across browsers. -*/ - -::-webkit-datetime-edit-fields-wrapper { - padding: 0; -} - -::-webkit-datetime-edit, -::-webkit-datetime-edit-year-field, -::-webkit-datetime-edit-month-field, -::-webkit-datetime-edit-day-field, -::-webkit-datetime-edit-hour-field, -::-webkit-datetime-edit-minute-field, -::-webkit-datetime-edit-second-field, -::-webkit-datetime-edit-millisecond-field, -::-webkit-datetime-edit-meridiem-field { - padding-block: 0; -} - -/* - Remove the additional `:invalid` styles in Firefox. (https://github.com/mozilla/gecko-dev/blob/2f9eacd9d3d995c937b4251a5557d95d494c9be1/layout/style/res/forms.css#L728-L737) -*/ - -:-moz-ui-invalid { - box-shadow: none; -} - -/* - Correct the inability to style the border radius in iOS Safari. -*/ - -button, -input:where([type='button'], [type='reset'], [type='submit']), -::file-selector-button { - appearance: button; -} - -/* - Correct the cursor style of increment and decrement buttons in Safari. -*/ - -::-webkit-inner-spin-button, -::-webkit-outer-spin-button { - height: auto; -} - -/* - Make elements with the HTML hidden attribute stay hidden by default. -*/ - -[hidden]:where(:not([hidden='until-found'])) { - display: none !important; -} diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/README.md b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/README.md similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/README.md rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/README.md diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.AppHost/AppHost.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.AppHost/AppHost.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.AppHost/AppHost.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.AppHost/AppHost.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.AppHost/Properties/launchSettings.json b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.AppHost/Properties/launchSettings.json similarity index 84% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.AppHost/Properties/launchSettings.json rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.AppHost/Properties/launchSettings.json index 681e3bf0d26..f08691f26f1 100644 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.AppHost/Properties/launchSettings.json +++ b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.AppHost/Properties/launchSettings.json @@ -5,24 +5,24 @@ "commandName": "Project", "dotnetRunMessages": true, "launchBrowser": true, - "applicationUrl": "https://localhost:9999;http://localhost:9999", + "applicationUrl": "https://localhost:9995;http://localhost:9996", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development", "DOTNET_ENVIRONMENT": "Development", - "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:9999", - "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:9999" + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:9995", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:9995" } }, "http": { "commandName": "Project", "dotnetRunMessages": true, "launchBrowser": true, - "applicationUrl": "http://localhost:9999", + "applicationUrl": "http://localhost:9996", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development", "DOTNET_ENVIRONMENT": "Development", - "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:9999", - "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:9999" + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:9996", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:9996" } } } diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.AppHost/aichatweb.AppHost.csproj b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.AppHost/aichatweb.AppHost.csproj similarity index 84% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.AppHost/aichatweb.AppHost.csproj rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.AppHost/aichatweb.AppHost.csproj index 83eb394f7ca..c9340b988a1 100644 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.AppHost/aichatweb.AppHost.csproj +++ b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.AppHost/aichatweb.AppHost.csproj @@ -7,11 +7,11 @@ net10.0 enable enable - secret + {00000000-0000-0000-0000-000000000000} - + diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.AppHost/appsettings.Development.json b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.AppHost/appsettings.Development.json similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.AppHost/appsettings.Development.json rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.AppHost/appsettings.Development.json diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.AppHost/appsettings.json b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.AppHost/appsettings.json similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.AppHost/appsettings.json rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.AppHost/appsettings.json diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.ServiceDefaults/Extensions.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.ServiceDefaults/Extensions.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.ServiceDefaults/Extensions.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.ServiceDefaults/Extensions.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.ServiceDefaults/aichatweb.ServiceDefaults.csproj b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.ServiceDefaults/aichatweb.ServiceDefaults.csproj similarity index 79% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.ServiceDefaults/aichatweb.ServiceDefaults.csproj rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.ServiceDefaults/aichatweb.ServiceDefaults.csproj index 78bf2e15f6e..b3853baa2d2 100644 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.ServiceDefaults/aichatweb.ServiceDefaults.csproj +++ b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.ServiceDefaults/aichatweb.ServiceDefaults.csproj @@ -10,13 +10,13 @@ - - - - - - - + + + + + + + diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/App.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/App.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/App.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/App.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Layout/LoadingSpinner.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Layout/LoadingSpinner.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Layout/LoadingSpinner.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Layout/LoadingSpinner.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Layout/LoadingSpinner.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Layout/LoadingSpinner.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Layout/LoadingSpinner.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Layout/LoadingSpinner.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Layout/MainLayout.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Layout/MainLayout.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Layout/MainLayout.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Layout/MainLayout.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Layout/MainLayout.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Layout/MainLayout.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Layout/MainLayout.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Layout/MainLayout.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Layout/SurveyPrompt.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Layout/SurveyPrompt.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Layout/SurveyPrompt.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Layout/SurveyPrompt.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Layout/SurveyPrompt.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Layout/SurveyPrompt.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Layout/SurveyPrompt.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Layout/SurveyPrompt.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/Chat.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/Chat.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/Chat.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/Chat.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/Chat.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/Chat.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/Chat.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/Chat.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatCitation.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatCitation.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatCitation.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatCitation.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatCitation.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatCitation.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatCitation.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatCitation.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatHeader.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatHeader.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatHeader.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatHeader.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatHeader.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatHeader.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatHeader.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatHeader.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor.js b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor.js similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor.js rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor.js diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageItem.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageItem.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageItem.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageItem.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageItem.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageItem.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageItem.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageItem.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor.js b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor.js similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor.js rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor.js diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatSuggestions.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatSuggestions.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatSuggestions.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatSuggestions.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatSuggestions.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatSuggestions.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatSuggestions.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatSuggestions.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Pages/Error.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Pages/Error.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Pages/Error.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Pages/Error.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Routes.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Routes.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/Routes.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/Routes.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/_Imports.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/_Imports.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Components/_Imports.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Components/_Imports.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Program.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Program.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Program.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Program.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Properties/launchSettings.json b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Properties/launchSettings.json similarity index 80% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Properties/launchSettings.json rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Properties/launchSettings.json index e2d900a219d..6e300d8a802 100644 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Properties/launchSettings.json +++ b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Properties/launchSettings.json @@ -5,7 +5,7 @@ "commandName": "Project", "dotnetRunMessages": true, "launchBrowser": true, - "applicationUrl": "http://localhost:9999", + "applicationUrl": "http://localhost:9996", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } @@ -14,7 +14,7 @@ "commandName": "Project", "dotnetRunMessages": true, "launchBrowser": true, - "applicationUrl": "https://localhost:9999;http://localhost:9999", + "applicationUrl": "https://localhost:9995;http://localhost:9996", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Services/IngestedChunk.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Services/IngestedChunk.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Services/IngestedChunk.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Services/IngestedChunk.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Services/Ingestion/DataIngestor.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Services/Ingestion/DataIngestor.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Services/Ingestion/DataIngestor.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Services/Ingestion/DataIngestor.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Services/Ingestion/DocumentReader.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Services/Ingestion/DocumentReader.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Services/Ingestion/DocumentReader.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Services/Ingestion/DocumentReader.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Services/SemanticSearch.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Services/SemanticSearch.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Services/SemanticSearch.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/Services/SemanticSearch.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/aichatweb.Web.csproj b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/aichatweb.Web.csproj similarity index 74% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/aichatweb.Web.csproj rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/aichatweb.Web.csproj index 07b23118444..ebe90e63c31 100644 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/aichatweb.Web.csproj +++ b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/aichatweb.Web.csproj @@ -4,19 +4,19 @@ net10.0 enable enable - secret + {00000000-0000-0000-0000-000000000000} - - - - - - - - - + + + + + + + + + diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/appsettings.Development.json b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/appsettings.Development.json similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/appsettings.Development.json rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/appsettings.Development.json diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/appsettings.json b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/appsettings.json similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/appsettings.json rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.Web/appsettings.json diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.sln b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.sln similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.sln rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A.verified/aichatweb/aichatweb.sln diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/README.md b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/README.md similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/README.md rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/README.md diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.AppHost/AppHost.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.AppHost/AppHost.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.AppHost/AppHost.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.AppHost/AppHost.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.AppHost/Properties/launchSettings.json b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.AppHost/Properties/launchSettings.json similarity index 84% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.AppHost/Properties/launchSettings.json rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.AppHost/Properties/launchSettings.json index 681e3bf0d26..f08691f26f1 100644 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.AppHost/Properties/launchSettings.json +++ b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.AppHost/Properties/launchSettings.json @@ -5,24 +5,24 @@ "commandName": "Project", "dotnetRunMessages": true, "launchBrowser": true, - "applicationUrl": "https://localhost:9999;http://localhost:9999", + "applicationUrl": "https://localhost:9995;http://localhost:9996", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development", "DOTNET_ENVIRONMENT": "Development", - "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:9999", - "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:9999" + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:9995", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:9995" } }, "http": { "commandName": "Project", "dotnetRunMessages": true, "launchBrowser": true, - "applicationUrl": "http://localhost:9999", + "applicationUrl": "http://localhost:9996", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development", "DOTNET_ENVIRONMENT": "Development", - "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:9999", - "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:9999" + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:9996", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:9996" } } } diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.AppHost/aichatweb.AppHost.csproj b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.AppHost/aichatweb.AppHost.csproj similarity index 81% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.AppHost/aichatweb.AppHost.csproj rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.AppHost/aichatweb.AppHost.csproj index 9278bb73627..a7fda7e47f6 100644 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.AppHost/aichatweb.AppHost.csproj +++ b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.AppHost/aichatweb.AppHost.csproj @@ -7,13 +7,13 @@ net10.0 enable enable - secret + {00000000-0000-0000-0000-000000000000} - - - + + + diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.AppHost/appsettings.Development.json b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.AppHost/appsettings.Development.json similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.AppHost/appsettings.Development.json rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.AppHost/appsettings.Development.json diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.AppHost/appsettings.json b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.AppHost/appsettings.json similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.AppHost/appsettings.json rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.AppHost/appsettings.json diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.ServiceDefaults/Extensions.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.ServiceDefaults/Extensions.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.ServiceDefaults/Extensions.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.ServiceDefaults/Extensions.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.ServiceDefaults/aichatweb.ServiceDefaults.csproj b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.ServiceDefaults/aichatweb.ServiceDefaults.csproj similarity index 79% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.ServiceDefaults/aichatweb.ServiceDefaults.csproj rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.ServiceDefaults/aichatweb.ServiceDefaults.csproj index 78bf2e15f6e..b3853baa2d2 100644 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.ServiceDefaults/aichatweb.ServiceDefaults.csproj +++ b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.ServiceDefaults/aichatweb.ServiceDefaults.csproj @@ -10,13 +10,13 @@ - - - - - - - + + + + + + + diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/App.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/App.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/App.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/App.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Layout/LoadingSpinner.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Layout/LoadingSpinner.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Layout/LoadingSpinner.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Layout/LoadingSpinner.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Layout/LoadingSpinner.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Layout/LoadingSpinner.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Layout/LoadingSpinner.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Layout/LoadingSpinner.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Layout/MainLayout.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Layout/MainLayout.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Layout/MainLayout.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Layout/MainLayout.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Layout/MainLayout.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Layout/MainLayout.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Layout/MainLayout.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Layout/MainLayout.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Layout/SurveyPrompt.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Layout/SurveyPrompt.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Layout/SurveyPrompt.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Layout/SurveyPrompt.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Layout/SurveyPrompt.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Layout/SurveyPrompt.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Layout/SurveyPrompt.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Layout/SurveyPrompt.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Pages/Chat/Chat.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/Chat.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Pages/Chat/Chat.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/Chat.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Pages/Chat/Chat.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/Chat.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Pages/Chat/Chat.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/Chat.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Pages/Chat/ChatCitation.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatCitation.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Pages/Chat/ChatCitation.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatCitation.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Pages/Chat/ChatCitation.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatCitation.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Pages/Chat/ChatCitation.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatCitation.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatHeader.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatHeader.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatHeader.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatHeader.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Pages/Chat/ChatHeader.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatHeader.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Pages/Chat/ChatHeader.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatHeader.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Pages/Chat/ChatInput.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Pages/Chat/ChatInput.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Pages/Chat/ChatInput.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Pages/Chat/ChatInput.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Pages/Chat/ChatInput.razor.js b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor.js similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Pages/Chat/ChatInput.razor.js rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor.js diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Pages/Chat/ChatMessageItem.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageItem.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Pages/Chat/ChatMessageItem.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageItem.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Pages/Chat/ChatMessageItem.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageItem.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Pages/Chat/ChatMessageItem.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageItem.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Pages/Chat/ChatMessageList.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Pages/Chat/ChatMessageList.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Pages/Chat/ChatMessageList.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Pages/Chat/ChatMessageList.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Pages/Chat/ChatMessageList.razor.js b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor.js similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Pages/Chat/ChatMessageList.razor.js rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor.js diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Pages/Chat/ChatSuggestions.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatSuggestions.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Pages/Chat/ChatSuggestions.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatSuggestions.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Pages/Chat/ChatSuggestions.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatSuggestions.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Pages/Chat/ChatSuggestions.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatSuggestions.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Pages/Error.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Pages/Error.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Pages/Error.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Pages/Error.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Routes.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Routes.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Routes.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/Routes.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/_Imports.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/_Imports.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/_Imports.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Components/_Imports.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Program.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Program.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Program.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Program.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Properties/launchSettings.json b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Properties/launchSettings.json similarity index 80% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Properties/launchSettings.json rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Properties/launchSettings.json index e2d900a219d..6e300d8a802 100644 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Properties/launchSettings.json +++ b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Properties/launchSettings.json @@ -5,7 +5,7 @@ "commandName": "Project", "dotnetRunMessages": true, "launchBrowser": true, - "applicationUrl": "http://localhost:9999", + "applicationUrl": "http://localhost:9996", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } @@ -14,7 +14,7 @@ "commandName": "Project", "dotnetRunMessages": true, "launchBrowser": true, - "applicationUrl": "https://localhost:9999;http://localhost:9999", + "applicationUrl": "https://localhost:9995;http://localhost:9996", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Services/IngestedChunk.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Services/IngestedChunk.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/Services/IngestedChunk.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Services/IngestedChunk.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Services/Ingestion/DataIngestor.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Services/Ingestion/DataIngestor.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Services/Ingestion/DataIngestor.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Services/Ingestion/DataIngestor.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Services/Ingestion/DocumentReader.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Services/Ingestion/DocumentReader.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Services/Ingestion/DocumentReader.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Services/Ingestion/DocumentReader.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Services/SemanticSearch.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Services/SemanticSearch.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Services/SemanticSearch.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/Services/SemanticSearch.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/aichatweb.Web.csproj b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/aichatweb.Web.csproj similarity index 74% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/aichatweb.Web.csproj rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/aichatweb.Web.csproj index 47cf239e07b..6ddb23e8847 100644 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.AzureOpenAI_Qdrant_Aspire.verified/aichatweb/aichatweb.Web/aichatweb.Web.csproj +++ b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/aichatweb.Web.csproj @@ -4,20 +4,20 @@ net10.0 enable enable - secret + {00000000-0000-0000-0000-000000000000} - - - - - - - - - - + + + + + + + + + + diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/appsettings.Development.json b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/appsettings.Development.json similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/appsettings.Development.json rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/appsettings.Development.json diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/appsettings.json b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/appsettings.json similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/appsettings.json rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.Web/appsettings.json diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.sln b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.sln similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.sln rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.A_aoai_aais.verified/aichatweb/aichatweb.sln diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/App.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/App.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/App.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/App.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Layout/LoadingSpinner.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Layout/LoadingSpinner.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Layout/LoadingSpinner.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Layout/LoadingSpinner.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Layout/LoadingSpinner.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Layout/LoadingSpinner.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Layout/LoadingSpinner.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Layout/LoadingSpinner.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Layout/MainLayout.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Layout/MainLayout.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Layout/MainLayout.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Layout/MainLayout.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Layout/MainLayout.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Layout/MainLayout.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Layout/MainLayout.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Layout/MainLayout.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Layout/SurveyPrompt.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Layout/SurveyPrompt.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Layout/SurveyPrompt.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Layout/SurveyPrompt.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Layout/SurveyPrompt.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Layout/SurveyPrompt.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Layout/SurveyPrompt.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Layout/SurveyPrompt.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/Chat.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Pages/Chat/Chat.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/Chat.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Pages/Chat/Chat.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/Chat.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Pages/Chat/Chat.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/Chat.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Pages/Chat/Chat.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatCitation.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Pages/Chat/ChatCitation.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatCitation.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Pages/Chat/ChatCitation.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatCitation.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Pages/Chat/ChatCitation.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatCitation.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Pages/Chat/ChatCitation.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Pages/Chat/ChatHeader.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Pages/Chat/ChatHeader.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/Pages/Chat/ChatHeader.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Pages/Chat/ChatHeader.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatHeader.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Pages/Chat/ChatHeader.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatHeader.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Pages/Chat/ChatHeader.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Pages/Chat/ChatInput.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Pages/Chat/ChatInput.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Pages/Chat/ChatInput.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Pages/Chat/ChatInput.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor.js b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Pages/Chat/ChatInput.razor.js similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor.js rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Pages/Chat/ChatInput.razor.js diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageItem.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Pages/Chat/ChatMessageItem.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageItem.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Pages/Chat/ChatMessageItem.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageItem.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Pages/Chat/ChatMessageItem.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageItem.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Pages/Chat/ChatMessageItem.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Pages/Chat/ChatMessageList.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Pages/Chat/ChatMessageList.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Pages/Chat/ChatMessageList.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Pages/Chat/ChatMessageList.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor.js b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Pages/Chat/ChatMessageList.razor.js similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor.js rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Pages/Chat/ChatMessageList.razor.js diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatSuggestions.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Pages/Chat/ChatSuggestions.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatSuggestions.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Pages/Chat/ChatSuggestions.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatSuggestions.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Pages/Chat/ChatSuggestions.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatSuggestions.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Pages/Chat/ChatSuggestions.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Pages/Error.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Pages/Error.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Pages/Error.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Pages/Error.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Routes.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Routes.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Components/Routes.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/Routes.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/_Imports.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/_Imports.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Components/_Imports.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Components/_Imports.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Program.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Program.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Program.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Program.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Properties/launchSettings.json b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Properties/launchSettings.json similarity index 80% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Properties/launchSettings.json rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Properties/launchSettings.json index e2d900a219d..6e300d8a802 100644 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/Properties/launchSettings.json +++ b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Properties/launchSettings.json @@ -5,7 +5,7 @@ "commandName": "Project", "dotnetRunMessages": true, "launchBrowser": true, - "applicationUrl": "http://localhost:9999", + "applicationUrl": "http://localhost:9996", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } @@ -14,7 +14,7 @@ "commandName": "Project", "dotnetRunMessages": true, "launchBrowser": true, - "applicationUrl": "https://localhost:9999;http://localhost:9999", + "applicationUrl": "https://localhost:9995;http://localhost:9996", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/README.md b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/README.md similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/README.md rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/README.md diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Services/IngestedChunk.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Services/IngestedChunk.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Services/IngestedChunk.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Services/IngestedChunk.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Services/Ingestion/DataIngestor.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Services/Ingestion/DataIngestor.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Services/Ingestion/DataIngestor.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Services/Ingestion/DataIngestor.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Services/Ingestion/DocumentReader.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Services/Ingestion/DocumentReader.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Services/Ingestion/DocumentReader.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Services/Ingestion/DocumentReader.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Services/Ingestion/PdfPigReader.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Services/Ingestion/PdfPigReader.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Services/Ingestion/PdfPigReader.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Services/Ingestion/PdfPigReader.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Services/SemanticSearch.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Services/SemanticSearch.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/Services/SemanticSearch.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/Services/SemanticSearch.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/aichatweb.csproj b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/aichatweb.csproj similarity index 67% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/aichatweb.csproj rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/aichatweb.csproj index 77ead7c69ea..32d3733d56b 100644 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Basic.verified/aichatweb/aichatweb.csproj +++ b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/aichatweb.csproj @@ -4,18 +4,18 @@ net10.0 enable enable - secret + {00000000-0000-0000-0000-000000000000} - - - - - - - - + + + + + + + + diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/appsettings.Development.json b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/appsettings.Development.json similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/appsettings.Development.json rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/appsettings.Development.json diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/appsettings.json b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/appsettings.json similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.BasicAspire.verified/aichatweb/aichatweb.Web/appsettings.json rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb._defaults.verified/aichatweb/appsettings.json diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/README.md b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/README.md similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/README.md rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/README.md diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.AppHost/AppHost.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.AppHost/AppHost.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.AppHost/AppHost.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.AppHost/AppHost.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.AppHost/Properties/launchSettings.json b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.AppHost/Properties/launchSettings.json similarity index 84% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.AppHost/Properties/launchSettings.json rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.AppHost/Properties/launchSettings.json index 681e3bf0d26..f08691f26f1 100644 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.AppHost/Properties/launchSettings.json +++ b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.AppHost/Properties/launchSettings.json @@ -5,24 +5,24 @@ "commandName": "Project", "dotnetRunMessages": true, "launchBrowser": true, - "applicationUrl": "https://localhost:9999;http://localhost:9999", + "applicationUrl": "https://localhost:9995;http://localhost:9996", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development", "DOTNET_ENVIRONMENT": "Development", - "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:9999", - "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:9999" + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:9995", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:9995" } }, "http": { "commandName": "Project", "dotnetRunMessages": true, "launchBrowser": true, - "applicationUrl": "http://localhost:9999", + "applicationUrl": "http://localhost:9996", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development", "DOTNET_ENVIRONMENT": "Development", - "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:9999", - "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:9999" + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:9996", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:9996" } } } diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.AppHost/aichatweb.AppHost.csproj b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.AppHost/aichatweb.AppHost.csproj similarity index 74% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.AppHost/aichatweb.AppHost.csproj rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.AppHost/aichatweb.AppHost.csproj index 2d7345e70ca..d65dd7ef340 100644 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.AppHost/aichatweb.AppHost.csproj +++ b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.AppHost/aichatweb.AppHost.csproj @@ -7,13 +7,13 @@ net10.0 enable enable - secret + {00000000-0000-0000-0000-000000000000} - - - + + + diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.AppHost/appsettings.Development.json b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.AppHost/appsettings.Development.json similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.AppHost/appsettings.Development.json rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.AppHost/appsettings.Development.json diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.AppHost/appsettings.json b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.AppHost/appsettings.json similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.AppHost/appsettings.json rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.AppHost/appsettings.json diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.ServiceDefaults/Extensions.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.ServiceDefaults/Extensions.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.ServiceDefaults/Extensions.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.ServiceDefaults/Extensions.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.ServiceDefaults/aichatweb.ServiceDefaults.csproj b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.ServiceDefaults/aichatweb.ServiceDefaults.csproj similarity index 79% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.ServiceDefaults/aichatweb.ServiceDefaults.csproj rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.ServiceDefaults/aichatweb.ServiceDefaults.csproj index 78bf2e15f6e..b3853baa2d2 100644 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.ServiceDefaults/aichatweb.ServiceDefaults.csproj +++ b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.ServiceDefaults/aichatweb.ServiceDefaults.csproj @@ -10,13 +10,13 @@ - - - - - - - + + + + + + + diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/App.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/App.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/App.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/App.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Layout/LoadingSpinner.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Layout/LoadingSpinner.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Layout/LoadingSpinner.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Layout/LoadingSpinner.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Layout/LoadingSpinner.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Layout/LoadingSpinner.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Layout/LoadingSpinner.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Layout/LoadingSpinner.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Layout/MainLayout.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Layout/MainLayout.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Layout/MainLayout.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Layout/MainLayout.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Layout/MainLayout.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Layout/MainLayout.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Layout/MainLayout.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Layout/MainLayout.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Layout/SurveyPrompt.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Layout/SurveyPrompt.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Layout/SurveyPrompt.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Layout/SurveyPrompt.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Layout/SurveyPrompt.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Layout/SurveyPrompt.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Layout/SurveyPrompt.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Layout/SurveyPrompt.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/Chat.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/Chat.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/Chat.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/Chat.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/Chat.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/Chat.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/Chat.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/Chat.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatCitation.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatCitation.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatCitation.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatCitation.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatCitation.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatCitation.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatCitation.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatCitation.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatHeader.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatHeader.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatHeader.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatHeader.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatHeader.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatHeader.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatHeader.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatHeader.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor.js b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor.js similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor.js rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatInput.razor.js diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageItem.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageItem.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageItem.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageItem.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageItem.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageItem.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageItem.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageItem.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor.js b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor.js similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor.js rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatMessageList.razor.js diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatSuggestions.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatSuggestions.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatSuggestions.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatSuggestions.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatSuggestions.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatSuggestions.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatSuggestions.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Pages/Chat/ChatSuggestions.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Pages/Error.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Pages/Error.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Pages/Error.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Pages/Error.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Routes.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Routes.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/Routes.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/Routes.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/_Imports.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/_Imports.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Components/_Imports.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Components/_Imports.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/OllamaResilienceHandlerExtensions.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/OllamaResilienceHandlerExtensions.cs similarity index 99% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/OllamaResilienceHandlerExtensions.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/OllamaResilienceHandlerExtensions.cs index ae82393302c..9f159b84765 100644 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/OllamaResilienceHandlerExtensions.cs +++ b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/OllamaResilienceHandlerExtensions.cs @@ -31,4 +31,3 @@ public static IServiceCollection AddOllamaResilienceHandler(this IServiceCollect return services; } } - diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Program.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Program.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Program.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Program.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Properties/launchSettings.json b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Properties/launchSettings.json similarity index 80% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Properties/launchSettings.json rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Properties/launchSettings.json index e2d900a219d..6e300d8a802 100644 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Properties/launchSettings.json +++ b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Properties/launchSettings.json @@ -5,7 +5,7 @@ "commandName": "Project", "dotnetRunMessages": true, "launchBrowser": true, - "applicationUrl": "http://localhost:9999", + "applicationUrl": "http://localhost:9996", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } @@ -14,7 +14,7 @@ "commandName": "Project", "dotnetRunMessages": true, "launchBrowser": true, - "applicationUrl": "https://localhost:9999;http://localhost:9999", + "applicationUrl": "https://localhost:9995;http://localhost:9996", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Services/IngestedChunk.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Services/IngestedChunk.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Services/IngestedChunk.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Services/IngestedChunk.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Services/Ingestion/DataIngestor.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Services/Ingestion/DataIngestor.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Services/Ingestion/DataIngestor.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Services/Ingestion/DataIngestor.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Services/Ingestion/DocumentReader.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Services/Ingestion/DocumentReader.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Services/Ingestion/DocumentReader.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Services/Ingestion/DocumentReader.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Services/SemanticSearch.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Services/SemanticSearch.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/Services/SemanticSearch.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/Services/SemanticSearch.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/aichatweb.Web.csproj b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/aichatweb.Web.csproj similarity index 66% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/aichatweb.Web.csproj rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/aichatweb.Web.csproj index 58262329c83..3fc87d336c7 100644 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/aichatweb.Web.csproj +++ b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/aichatweb.Web.csproj @@ -4,20 +4,20 @@ net10.0 enable enable - secret + {00000000-0000-0000-0000-000000000000} - - - - - - - - - - + + + + + + + + + + diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/appsettings.Development.json b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/appsettings.Development.json similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/appsettings.Development.json rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/appsettings.Development.json diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/appsettings.json b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/appsettings.json similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.Web/appsettings.json rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.Web/appsettings.json diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.sln b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.sln similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.Ollama_Qdrant.verified/aichatweb/aichatweb.sln rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.o_q.verified/aichatweb/aichatweb.sln diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/App.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/App.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/App.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/App.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Layout/LoadingSpinner.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Layout/LoadingSpinner.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Layout/LoadingSpinner.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Layout/LoadingSpinner.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Layout/LoadingSpinner.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Layout/LoadingSpinner.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Layout/LoadingSpinner.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Layout/LoadingSpinner.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Layout/MainLayout.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Layout/MainLayout.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Layout/MainLayout.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Layout/MainLayout.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Layout/MainLayout.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Layout/MainLayout.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Layout/MainLayout.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Layout/MainLayout.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Layout/SurveyPrompt.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Layout/SurveyPrompt.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Layout/SurveyPrompt.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Layout/SurveyPrompt.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Layout/SurveyPrompt.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Layout/SurveyPrompt.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Layout/SurveyPrompt.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Layout/SurveyPrompt.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Pages/Chat/Chat.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Pages/Chat/Chat.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Pages/Chat/Chat.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Pages/Chat/Chat.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Pages/Chat/Chat.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Pages/Chat/Chat.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Pages/Chat/Chat.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Pages/Chat/Chat.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Pages/Chat/ChatCitation.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Pages/Chat/ChatCitation.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Pages/Chat/ChatCitation.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Pages/Chat/ChatCitation.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Pages/Chat/ChatCitation.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Pages/Chat/ChatCitation.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Pages/Chat/ChatCitation.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Pages/Chat/ChatCitation.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Pages/Chat/ChatHeader.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Pages/Chat/ChatHeader.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Pages/Chat/ChatHeader.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Pages/Chat/ChatHeader.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Pages/Chat/ChatHeader.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Pages/Chat/ChatHeader.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Pages/Chat/ChatHeader.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Pages/Chat/ChatHeader.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Pages/Chat/ChatInput.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Pages/Chat/ChatInput.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Pages/Chat/ChatInput.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Pages/Chat/ChatInput.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Pages/Chat/ChatInput.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Pages/Chat/ChatInput.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Pages/Chat/ChatInput.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Pages/Chat/ChatInput.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Pages/Chat/ChatInput.razor.js b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Pages/Chat/ChatInput.razor.js similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Pages/Chat/ChatInput.razor.js rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Pages/Chat/ChatInput.razor.js diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Pages/Chat/ChatMessageItem.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Pages/Chat/ChatMessageItem.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Pages/Chat/ChatMessageItem.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Pages/Chat/ChatMessageItem.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Pages/Chat/ChatMessageItem.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Pages/Chat/ChatMessageItem.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Pages/Chat/ChatMessageItem.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Pages/Chat/ChatMessageItem.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Pages/Chat/ChatMessageList.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Pages/Chat/ChatMessageList.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Pages/Chat/ChatMessageList.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Pages/Chat/ChatMessageList.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Pages/Chat/ChatMessageList.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Pages/Chat/ChatMessageList.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Pages/Chat/ChatMessageList.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Pages/Chat/ChatMessageList.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Pages/Chat/ChatMessageList.razor.js b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Pages/Chat/ChatMessageList.razor.js similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Pages/Chat/ChatMessageList.razor.js rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Pages/Chat/ChatMessageList.razor.js diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Pages/Chat/ChatSuggestions.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Pages/Chat/ChatSuggestions.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Pages/Chat/ChatSuggestions.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Pages/Chat/ChatSuggestions.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Pages/Chat/ChatSuggestions.razor.css b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Pages/Chat/ChatSuggestions.razor.css similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Pages/Chat/ChatSuggestions.razor.css rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Pages/Chat/ChatSuggestions.razor.css diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Pages/Error.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Pages/Error.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Pages/Error.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Pages/Error.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Routes.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Routes.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/Routes.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/Routes.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/_Imports.razor b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/_Imports.razor similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Components/_Imports.razor rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Components/_Imports.razor diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Program.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Program.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Program.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Program.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Properties/launchSettings.json b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Properties/launchSettings.json new file mode 100644 index 00000000000..6e300d8a802 --- /dev/null +++ b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Properties/launchSettings.json @@ -0,0 +1,23 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:9996", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:9995;http://localhost:9996", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/README.md b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/README.md similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/README.md rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/README.md diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Services/IngestedChunk.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Services/IngestedChunk.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Services/IngestedChunk.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Services/IngestedChunk.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Services/Ingestion/DataIngestor.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Services/Ingestion/DataIngestor.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Services/Ingestion/DataIngestor.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Services/Ingestion/DataIngestor.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Services/Ingestion/DocumentReader.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Services/Ingestion/DocumentReader.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Services/Ingestion/DocumentReader.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Services/Ingestion/DocumentReader.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Services/Ingestion/PdfPigReader.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Services/Ingestion/PdfPigReader.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Services/Ingestion/PdfPigReader.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Services/Ingestion/PdfPigReader.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Services/SemanticSearch.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Services/SemanticSearch.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/Services/SemanticSearch.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/Services/SemanticSearch.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/aichatweb.csproj b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/aichatweb.csproj similarity index 64% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/aichatweb.csproj rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/aichatweb.csproj index 383a6012b2c..29733223cdf 100644 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/aichatweb.csproj +++ b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/aichatweb.csproj @@ -4,20 +4,20 @@ net10.0 enable enable - secret + {00000000-0000-0000-0000-000000000000} - - - - - - - - - - + + + + + + + + + + diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/appsettings.Development.json b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/appsettings.Development.json similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/appsettings.Development.json rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/appsettings.Development.json diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/appsettings.json b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/appsettings.json similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb.OpenAI_AzureAISearch.verified/aichatweb/appsettings.json rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/aichatweb/aichatweb.oai_aais.verified/aichatweb/appsettings.json diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.AotTrue.verified/mcpserver/.mcp/server.json b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.AOT_T.verified/mcpserver/.mcp/server.json similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.AotTrue.verified/mcpserver/.mcp/server.json rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.AOT_T.verified/mcpserver/.mcp/server.json diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.AotTrue.verified/mcpserver/Program.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.AOT_T.verified/mcpserver/Program.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.AotTrue.verified/mcpserver/Program.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.AOT_T.verified/mcpserver/Program.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.AotTrue.verified/mcpserver/README.md b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.AOT_T.verified/mcpserver/README.md similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.AotTrue.verified/mcpserver/README.md rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.AOT_T.verified/mcpserver/README.md diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.AotTrue.verified/mcpserver/Tools/RandomNumberTools.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.AOT_T.verified/mcpserver/Tools/RandomNumberTools.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.AotTrue.verified/mcpserver/Tools/RandomNumberTools.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.AOT_T.verified/mcpserver/Tools/RandomNumberTools.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.AotTrue.verified/mcpserver/mcpserver.csproj b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.AOT_T.verified/mcpserver/mcpserver.csproj similarity index 94% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.AotTrue.verified/mcpserver/mcpserver.csproj rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.AOT_T.verified/mcpserver/mcpserver.csproj index c66758ea7a9..b119f227f6d 100644 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.AotTrue.verified/mcpserver/mcpserver.csproj +++ b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.AOT_T.verified/mcpserver/mcpserver.csproj @@ -37,8 +37,8 @@ - - + + diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.Basic.verified/mcpserver/.mcp/server.json b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.SC_F.verified/mcpserver/.mcp/server.json similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.Basic.verified/mcpserver/.mcp/server.json rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.SC_F.verified/mcpserver/.mcp/server.json diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.Basic.verified/mcpserver/Program.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.SC_F.verified/mcpserver/Program.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.Basic.verified/mcpserver/Program.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.SC_F.verified/mcpserver/Program.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.SelfContainedFalse.verified/mcpserver/README.md b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.SC_F.verified/mcpserver/README.md similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.SelfContainedFalse.verified/mcpserver/README.md rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.SC_F.verified/mcpserver/README.md diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.Basic.verified/mcpserver/Tools/RandomNumberTools.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.SC_F.verified/mcpserver/Tools/RandomNumberTools.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.Basic.verified/mcpserver/Tools/RandomNumberTools.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.SC_F.verified/mcpserver/Tools/RandomNumberTools.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.SelfContainedFalse.verified/mcpserver/mcpserver.csproj b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.SC_F.verified/mcpserver/mcpserver.csproj similarity index 91% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.SelfContainedFalse.verified/mcpserver/mcpserver.csproj rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.SC_F.verified/mcpserver/mcpserver.csproj index 032c5dd1cdf..03b810e5a7e 100644 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.SelfContainedFalse.verified/mcpserver/mcpserver.csproj +++ b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.SC_F.verified/mcpserver/mcpserver.csproj @@ -26,8 +26,8 @@ - - + + diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.SelfContainedFalse.verified/mcpserver/.mcp/server.json b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver._defaults.verified/mcpserver/.mcp/server.json similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.SelfContainedFalse.verified/mcpserver/.mcp/server.json rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver._defaults.verified/mcpserver/.mcp/server.json diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.SelfContainedFalse.verified/mcpserver/Program.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver._defaults.verified/mcpserver/Program.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.SelfContainedFalse.verified/mcpserver/Program.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver._defaults.verified/mcpserver/Program.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.Basic.verified/mcpserver/README.md b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver._defaults.verified/mcpserver/README.md similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.Basic.verified/mcpserver/README.md rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver._defaults.verified/mcpserver/README.md diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.SelfContainedFalse.verified/mcpserver/Tools/RandomNumberTools.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver._defaults.verified/mcpserver/Tools/RandomNumberTools.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.SelfContainedFalse.verified/mcpserver/Tools/RandomNumberTools.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver._defaults.verified/mcpserver/Tools/RandomNumberTools.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.Basic.verified/mcpserver/mcpserver.csproj b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver._defaults.verified/mcpserver/mcpserver.csproj similarity index 93% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.Basic.verified/mcpserver/mcpserver.csproj rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver._defaults.verified/mcpserver/mcpserver.csproj index 5773e8c13cb..dc39713adb5 100644 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.Basic.verified/mcpserver/mcpserver.csproj +++ b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver._defaults.verified/mcpserver/mcpserver.csproj @@ -33,8 +33,8 @@ - - + + diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.net10.verified/mcpserver/.mcp/server.json b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.net8.verified/mcpserver/.mcp/server.json similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.net10.verified/mcpserver/.mcp/server.json rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.net8.verified/mcpserver/.mcp/server.json diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.net10.verified/mcpserver/Program.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.net8.verified/mcpserver/Program.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.net10.verified/mcpserver/Program.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.net8.verified/mcpserver/Program.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.net10.verified/mcpserver/README.md b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.net8.verified/mcpserver/README.md similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.net10.verified/mcpserver/README.md rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.net8.verified/mcpserver/README.md diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.net10.verified/mcpserver/Tools/RandomNumberTools.cs b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.net8.verified/mcpserver/Tools/RandomNumberTools.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.net10.verified/mcpserver/Tools/RandomNumberTools.cs rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.net8.verified/mcpserver/Tools/RandomNumberTools.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.net10.verified/mcpserver/mcpserver.csproj b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.net8.verified/mcpserver/mcpserver.csproj similarity index 90% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.net10.verified/mcpserver/mcpserver.csproj rename to test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.net8.verified/mcpserver/mcpserver.csproj index 5773e8c13cb..6961054eb76 100644 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver.net10.verified/mcpserver/mcpserver.csproj +++ b/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.net8.verified/mcpserver/mcpserver.csproj @@ -1,7 +1,7 @@  - net10.0 + net8.0 win-x64;win-arm64;osx-arm64;linux-x64;linux-arm64;linux-musl-x64 Exe enable @@ -33,8 +33,8 @@ - - + + From 8d530794073c4e466c53b3c8d034d96a1d05316b Mon Sep 17 00:00:00 2001 From: Jeff Handley Date: Fri, 19 Dec 2025 13:41:08 -0800 Subject: [PATCH 3/6] Update Microsoft.Agents.AI.ProjectTemplates to latest Agent Framework (#7167) --- eng/packages/ProjectTemplates.props | 6 +++--- .../templates/AIAgentWebApi-CSharp/Program.cs | 9 ++++++--- .../AIAgentWebAPIExecutionTests.cs | 2 +- .../aiagent-webapi/Program.cs | 9 ++++++--- .../aiagent-webapi/Program.cs | 9 ++++++--- .../aiagent-webapi/Program.cs | 9 ++++++--- .../aiagent-webapi.o.verified/aiagent-webapi/Program.cs | 9 ++++++--- .../aiagent-webapi/Program.cs | 9 ++++++--- 8 files changed, 40 insertions(+), 22 deletions(-) diff --git a/eng/packages/ProjectTemplates.props b/eng/packages/ProjectTemplates.props index 1abaa66643f..e6db615e55e 100644 --- a/eng/packages/ProjectTemplates.props +++ b/eng/packages/ProjectTemplates.props @@ -18,9 +18,9 @@ - - - + + + diff --git a/src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/templates/AIAgentWebApi-CSharp/Program.cs b/src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/templates/AIAgentWebApi-CSharp/Program.cs index 743658f6c8a..3702afef4cd 100644 --- a/src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/templates/AIAgentWebApi-CSharp/Program.cs +++ b/src/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates/templates/AIAgentWebApi-CSharp/Program.cs @@ -87,9 +87,12 @@ builder.AddWorkflow("publisher", (sp, key) => AgentWorkflowBuilder.BuildSequential( workflowName: key, - sp.GetRequiredKeyedService("writer"), - sp.GetRequiredKeyedService("editor") -)).AddAsAIAgent(); + agents: + [ + sp.GetRequiredKeyedService("writer"), + sp.GetRequiredKeyedService("editor") + ] +)).AddAsAIAgent("publisher-agent"); // Register services for OpenAI responses and conversations (also required for DevUI) builder.Services.AddOpenAIResponses(); diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/AIAgentWebAPIExecutionTests.cs b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/AIAgentWebAPIExecutionTests.cs index 03806abac7c..675fb642aa6 100644 --- a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/AIAgentWebAPIExecutionTests.cs +++ b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/AIAgentWebAPIExecutionTests.cs @@ -39,7 +39,7 @@ public static IEnumerable GetSupportedProjectConfigurations() (string name, string[] values)[] allOptionValues = [ ("--provider", ["azureopenai", "githubmodels", "ollama", "openai"]), ("--managed-identity", ["true", "false"]), - ("--framework", [/* net8.0 is not supported until 1.0.0-preview.251125.1 */ "net9.0", "net10.0"]) + ("--framework", ["net8.0", "net9.0", "net10.0"]) ]; foreach (var args in GetPossibleOptions(allOptionValues)) diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi._defaults.verified/aiagent-webapi/Program.cs b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi._defaults.verified/aiagent-webapi/Program.cs index 025dffc9c9f..2744b8bb8af 100644 --- a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi._defaults.verified/aiagent-webapi/Program.cs +++ b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi._defaults.verified/aiagent-webapi/Program.cs @@ -33,9 +33,12 @@ builder.AddWorkflow("publisher", (sp, key) => AgentWorkflowBuilder.BuildSequential( workflowName: key, - sp.GetRequiredKeyedService("writer"), - sp.GetRequiredKeyedService("editor") -)).AddAsAIAgent(); + agents: + [ + sp.GetRequiredKeyedService("writer"), + sp.GetRequiredKeyedService("editor") + ] +)).AddAsAIAgent("publisher-agent"); // Register services for OpenAI responses and conversations (also required for DevUI) builder.Services.AddOpenAIResponses(); diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.aoai_ID_F.verified/aiagent-webapi/Program.cs b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.aoai_ID_F.verified/aiagent-webapi/Program.cs index ddc551393fa..3ece18c0d08 100644 --- a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.aoai_ID_F.verified/aiagent-webapi/Program.cs +++ b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.aoai_ID_F.verified/aiagent-webapi/Program.cs @@ -36,9 +36,12 @@ builder.AddWorkflow("publisher", (sp, key) => AgentWorkflowBuilder.BuildSequential( workflowName: key, - sp.GetRequiredKeyedService("writer"), - sp.GetRequiredKeyedService("editor") -)).AddAsAIAgent(); + agents: + [ + sp.GetRequiredKeyedService("writer"), + sp.GetRequiredKeyedService("editor") + ] +)).AddAsAIAgent("publisher-agent"); // Register services for OpenAI responses and conversations (also required for DevUI) builder.Services.AddOpenAIResponses(); diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.aoai_ID_T.verified/aiagent-webapi/Program.cs b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.aoai_ID_T.verified/aiagent-webapi/Program.cs index 3749e820b45..037ac3deb7e 100644 --- a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.aoai_ID_T.verified/aiagent-webapi/Program.cs +++ b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.aoai_ID_T.verified/aiagent-webapi/Program.cs @@ -38,9 +38,12 @@ builder.AddWorkflow("publisher", (sp, key) => AgentWorkflowBuilder.BuildSequential( workflowName: key, - sp.GetRequiredKeyedService("writer"), - sp.GetRequiredKeyedService("editor") -)).AddAsAIAgent(); + agents: + [ + sp.GetRequiredKeyedService("writer"), + sp.GetRequiredKeyedService("editor") + ] +)).AddAsAIAgent("publisher-agent"); // Register services for OpenAI responses and conversations (also required for DevUI) builder.Services.AddOpenAIResponses(); diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.o.verified/aiagent-webapi/Program.cs b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.o.verified/aiagent-webapi/Program.cs index 2e9c6d25484..dfc311d6e17 100644 --- a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.o.verified/aiagent-webapi/Program.cs +++ b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.o.verified/aiagent-webapi/Program.cs @@ -25,9 +25,12 @@ builder.AddWorkflow("publisher", (sp, key) => AgentWorkflowBuilder.BuildSequential( workflowName: key, - sp.GetRequiredKeyedService("writer"), - sp.GetRequiredKeyedService("editor") -)).AddAsAIAgent(); + agents: + [ + sp.GetRequiredKeyedService("writer"), + sp.GetRequiredKeyedService("editor") + ] +)).AddAsAIAgent("publisher-agent"); // Register services for OpenAI responses and conversations (also required for DevUI) builder.Services.AddOpenAIResponses(); diff --git a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.oai.verified/aiagent-webapi/Program.cs b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.oai.verified/aiagent-webapi/Program.cs index 15009d121cd..efed4c96ad5 100644 --- a/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.oai.verified/aiagent-webapi/Program.cs +++ b/test/ProjectTemplates/Microsoft.Agents.AI.ProjectTemplates.IntegrationTests/Snapshots/aiagent-webapi/aiagent-webapi.oai.verified/aiagent-webapi/Program.cs @@ -31,9 +31,12 @@ builder.AddWorkflow("publisher", (sp, key) => AgentWorkflowBuilder.BuildSequential( workflowName: key, - sp.GetRequiredKeyedService("writer"), - sp.GetRequiredKeyedService("editor") -)).AddAsAIAgent(); + agents: + [ + sp.GetRequiredKeyedService("writer"), + sp.GetRequiredKeyedService("editor") + ] +)).AddAsAIAgent("publisher-agent"); // Register services for OpenAI responses and conversations (also required for DevUI) builder.Services.AddOpenAIResponses(); From 3660f7603b7d0bcdb359f5c5e5f9e9721c3a8208 Mon Sep 17 00:00:00 2001 From: Jeff Handley Date: Fri, 19 Dec 2025 16:24:10 -0800 Subject: [PATCH 4/6] Introduce local vs. remote mcpserver template option (#7168) * Move the mcpserver template into a new Microsoft.McpServer.ProjectTemplates package * Add local/remote option to McpServer template. Bump to MCP 0.5.0-preview.1. * Address feedback on the mcpserver remote template 1. Move the VS/VS Code local config documentation blurb up in the README 2. Add a Known Issues section to the README 3. When using VS (not CLI or VS Code), use HTTPS instead of HTTP * Fix typo in README --- eng/packages/ProjectTemplates.props | 3 +- .../Microsoft.Extensions.AI.Templates.csproj | 20 +- .../.template.config/template.json | 2 +- .../.template.config/template.json | 108 --------- ...icrosoft.McpServer.ProjectTemplates.csproj | 40 ++++ .../README.md | 3 + .../.template.config/dotnetcli.host.json | 19 +- .../.template.config/ide.host.json | 4 + .../.template.config/ide/icon.ico | Bin .../.template.config/template.json | 210 ++++++++++++++++++ .../common}/Tools/RandomNumberTools.cs | 0 .../McpServer-CSharp/local}/.mcp/server.json | 0 .../local}/McpServer-CSharp.csproj-in | 3 +- .../McpServer-CSharp/local}/Program.cs | 0 .../McpServer-CSharp/local}/README.md | 11 +- .../remote/McpServer-CSharp.csproj-in | 35 +++ .../remote/McpServer-CSharp.http | 21 ++ .../McpServer-CSharp/remote/Program.cs | 15 ++ .../remote/Properties/launchSettings.json | 23 ++ .../McpServer-CSharp/remote/README.md | 78 +++++++ .../Infrastructure/TemplateTestUtilities.cs | 2 +- .../Infrastructure/VerifyScrubbers.cs | 1 + .../McpServerExecutionTests.cs | 3 +- .../McpServerSnapshotTests.cs | 10 +- ...ft.McpServer.ProjectTemplates.Tests.csproj | 27 +++ .../README.md | 7 + .../mcpserver/.mcp/server.json | 0 .../mcpserver/Program.cs | 0 .../mcpserver/README.md | 11 +- .../mcpserver/Tools/RandomNumberTools.cs | 0 .../mcpserver/mcpserver.csproj | 0 .../mcpserver/.mcp/server.json | 0 .../mcpserver/Program.cs | 0 .../mcpserver/README.md | 11 +- .../mcpserver/Tools/RandomNumberTools.cs | 0 .../mcpserver/mcpserver.csproj | 0 .../mcpserver/.mcp/server.json | 0 .../mcpserver/Program.cs | 0 .../mcpserver/README.md | 11 +- .../mcpserver/Tools/RandomNumberTools.cs | 0 .../mcpserver/mcpserver.csproj | 0 .../mcpserver/.mcp/server.json | 0 .../mcpserver/Program.cs | 0 .../mcpserver/README.md | 11 +- .../mcpserver/Tools/RandomNumberTools.cs | 0 .../mcpserver/mcpserver.csproj | 0 .../mcpserver/Program.cs | 12 + .../mcpserver/Properties/launchSettings.json | 23 ++ .../mcpserver/README.md | 58 +++++ .../mcpserver/Tools/RandomNumberTools.cs | 18 ++ .../mcpserver/mcpserver.csproj | 23 ++ .../xunit.runner.json | 5 + 52 files changed, 664 insertions(+), 164 deletions(-) delete mode 100644 src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp/.template.config/template.json create mode 100644 src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/Microsoft.McpServer.ProjectTemplates.csproj create mode 100644 src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/README.md rename src/ProjectTemplates/{Microsoft.Extensions.AI.Templates => Microsoft.McpServer.ProjectTemplates}/templates/McpServer-CSharp/.template.config/dotnetcli.host.json (66%) rename src/ProjectTemplates/{Microsoft.Extensions.AI.Templates => Microsoft.McpServer.ProjectTemplates}/templates/McpServer-CSharp/.template.config/ide.host.json (79%) rename src/ProjectTemplates/{Microsoft.Extensions.AI.Templates => Microsoft.McpServer.ProjectTemplates}/templates/McpServer-CSharp/.template.config/ide/icon.ico (100%) create mode 100644 src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/.template.config/template.json rename src/ProjectTemplates/{Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp => Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/common}/Tools/RandomNumberTools.cs (100%) rename src/ProjectTemplates/{Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp => Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/local}/.mcp/server.json (100%) rename src/ProjectTemplates/{Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp => Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/local}/McpServer-CSharp.csproj-in (90%) rename src/ProjectTemplates/{Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp => Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/local}/Program.cs (100%) rename src/ProjectTemplates/{Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp => Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/local}/README.md (98%) create mode 100644 src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/remote/McpServer-CSharp.csproj-in create mode 100644 src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/remote/McpServer-CSharp.http create mode 100644 src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/remote/Program.cs create mode 100644 src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/remote/Properties/launchSettings.json create mode 100644 src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/remote/README.md rename test/ProjectTemplates/{Microsoft.Extensions.AI.Templates.IntegrationTests => Microsoft.McpServer.ProjectTemplates.IntegrationTests}/McpServerExecutionTests.cs (94%) rename test/ProjectTemplates/{Microsoft.Extensions.AI.Templates.IntegrationTests => Microsoft.McpServer.ProjectTemplates.IntegrationTests}/McpServerSnapshotTests.cs (77%) create mode 100644 test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Microsoft.McpServer.ProjectTemplates.Tests.csproj create mode 100644 test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/README.md rename test/ProjectTemplates/{Microsoft.Extensions.AI.Templates.IntegrationTests => Microsoft.McpServer.ProjectTemplates.IntegrationTests}/Snapshots/mcpserver/mcpserver.AOT_T.verified/mcpserver/.mcp/server.json (100%) rename test/ProjectTemplates/{Microsoft.Extensions.AI.Templates.IntegrationTests => Microsoft.McpServer.ProjectTemplates.IntegrationTests}/Snapshots/mcpserver/mcpserver.AOT_T.verified/mcpserver/Program.cs (100%) rename test/ProjectTemplates/{Microsoft.Extensions.AI.Templates.IntegrationTests => Microsoft.McpServer.ProjectTemplates.IntegrationTests}/Snapshots/mcpserver/mcpserver.AOT_T.verified/mcpserver/README.md (98%) rename test/ProjectTemplates/{Microsoft.Extensions.AI.Templates.IntegrationTests => Microsoft.McpServer.ProjectTemplates.IntegrationTests}/Snapshots/mcpserver/mcpserver.AOT_T.verified/mcpserver/Tools/RandomNumberTools.cs (100%) rename test/ProjectTemplates/{Microsoft.Extensions.AI.Templates.IntegrationTests => Microsoft.McpServer.ProjectTemplates.IntegrationTests}/Snapshots/mcpserver/mcpserver.AOT_T.verified/mcpserver/mcpserver.csproj (100%) rename test/ProjectTemplates/{Microsoft.Extensions.AI.Templates.IntegrationTests => Microsoft.McpServer.ProjectTemplates.IntegrationTests}/Snapshots/mcpserver/mcpserver.SC_F.verified/mcpserver/.mcp/server.json (100%) rename test/ProjectTemplates/{Microsoft.Extensions.AI.Templates.IntegrationTests => Microsoft.McpServer.ProjectTemplates.IntegrationTests}/Snapshots/mcpserver/mcpserver.SC_F.verified/mcpserver/Program.cs (100%) rename test/ProjectTemplates/{Microsoft.Extensions.AI.Templates.IntegrationTests => Microsoft.McpServer.ProjectTemplates.IntegrationTests}/Snapshots/mcpserver/mcpserver.SC_F.verified/mcpserver/README.md (98%) rename test/ProjectTemplates/{Microsoft.Extensions.AI.Templates.IntegrationTests => Microsoft.McpServer.ProjectTemplates.IntegrationTests}/Snapshots/mcpserver/mcpserver.SC_F.verified/mcpserver/Tools/RandomNumberTools.cs (100%) rename test/ProjectTemplates/{Microsoft.Extensions.AI.Templates.IntegrationTests => Microsoft.McpServer.ProjectTemplates.IntegrationTests}/Snapshots/mcpserver/mcpserver.SC_F.verified/mcpserver/mcpserver.csproj (100%) rename test/ProjectTemplates/{Microsoft.Extensions.AI.Templates.IntegrationTests => Microsoft.McpServer.ProjectTemplates.IntegrationTests}/Snapshots/mcpserver/mcpserver._defaults.verified/mcpserver/.mcp/server.json (100%) rename test/ProjectTemplates/{Microsoft.Extensions.AI.Templates.IntegrationTests => Microsoft.McpServer.ProjectTemplates.IntegrationTests}/Snapshots/mcpserver/mcpserver._defaults.verified/mcpserver/Program.cs (100%) rename test/ProjectTemplates/{Microsoft.Extensions.AI.Templates.IntegrationTests => Microsoft.McpServer.ProjectTemplates.IntegrationTests}/Snapshots/mcpserver/mcpserver._defaults.verified/mcpserver/README.md (98%) rename test/ProjectTemplates/{Microsoft.Extensions.AI.Templates.IntegrationTests => Microsoft.McpServer.ProjectTemplates.IntegrationTests}/Snapshots/mcpserver/mcpserver._defaults.verified/mcpserver/Tools/RandomNumberTools.cs (100%) rename test/ProjectTemplates/{Microsoft.Extensions.AI.Templates.IntegrationTests => Microsoft.McpServer.ProjectTemplates.IntegrationTests}/Snapshots/mcpserver/mcpserver._defaults.verified/mcpserver/mcpserver.csproj (100%) rename test/ProjectTemplates/{Microsoft.Extensions.AI.Templates.IntegrationTests => Microsoft.McpServer.ProjectTemplates.IntegrationTests}/Snapshots/mcpserver/mcpserver.net8.verified/mcpserver/.mcp/server.json (100%) rename test/ProjectTemplates/{Microsoft.Extensions.AI.Templates.IntegrationTests => Microsoft.McpServer.ProjectTemplates.IntegrationTests}/Snapshots/mcpserver/mcpserver.net8.verified/mcpserver/Program.cs (100%) rename test/ProjectTemplates/{Microsoft.Extensions.AI.Templates.IntegrationTests => Microsoft.McpServer.ProjectTemplates.IntegrationTests}/Snapshots/mcpserver/mcpserver.net8.verified/mcpserver/README.md (98%) rename test/ProjectTemplates/{Microsoft.Extensions.AI.Templates.IntegrationTests => Microsoft.McpServer.ProjectTemplates.IntegrationTests}/Snapshots/mcpserver/mcpserver.net8.verified/mcpserver/Tools/RandomNumberTools.cs (100%) rename test/ProjectTemplates/{Microsoft.Extensions.AI.Templates.IntegrationTests => Microsoft.McpServer.ProjectTemplates.IntegrationTests}/Snapshots/mcpserver/mcpserver.net8.verified/mcpserver/mcpserver.csproj (100%) create mode 100644 test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.remote.verified/mcpserver/Program.cs create mode 100644 test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.remote.verified/mcpserver/Properties/launchSettings.json create mode 100644 test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.remote.verified/mcpserver/README.md create mode 100644 test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.remote.verified/mcpserver/Tools/RandomNumberTools.cs create mode 100644 test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.remote.verified/mcpserver/mcpserver.csproj create mode 100644 test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/xunit.runner.json diff --git a/eng/packages/ProjectTemplates.props b/eng/packages/ProjectTemplates.props index e6db615e55e..2ffd2914778 100644 --- a/eng/packages/ProjectTemplates.props +++ b/eng/packages/ProjectTemplates.props @@ -26,7 +26,8 @@ - + + diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/Microsoft.Extensions.AI.Templates.csproj b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/Microsoft.Extensions.AI.Templates.csproj index 7571f225353..f83fda4db7e 100644 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/Microsoft.Extensions.AI.Templates.csproj +++ b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/Microsoft.Extensions.AI.Templates.csproj @@ -38,24 +38,14 @@ + Include="templates\**\*" + Exclude="templates\**\*.csproj-in" + PackagePath="content" /> - - - - + PackagePath="content" /> + + + Template + netstandard2.0 + MCP Server project templates. + dotnet-new;templates;ai + + preview + 1 + AI + 0 + 0 + + true + false + true + false + false + content + false + true + true + + + + + + + + + + + diff --git a/src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/README.md b/src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/README.md new file mode 100644 index 00000000000..c8d71cb61fd --- /dev/null +++ b/src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/README.md @@ -0,0 +1,3 @@ +# Microsoft.McpServer.ProjectTemplates + +Provides MCP Server Project Templates. diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp/.template.config/dotnetcli.host.json b/src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/.template.config/dotnetcli.host.json similarity index 66% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp/.template.config/dotnetcli.host.json rename to src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/.template.config/dotnetcli.host.json index 64694e46660..c2105a0018c 100644 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp/.template.config/dotnetcli.host.json +++ b/src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/.template.config/dotnetcli.host.json @@ -1,13 +1,9 @@ { "$schema": "https://json.schemastore.org/dotnetcli.host", "symbolInfo": { - "TargetFrameworkOverride": { - "isHidden": "true", - "longName": "target-framework-override", - "shortName": "" - }, - "Framework": { - "longName": "framework" + "Transport": { + "longName": "transport", + "shortName": "t" }, "NativeAot": { "longName": "aot", @@ -16,6 +12,15 @@ "SelfContained": { "longName": "self-contained", "shortName": "" + }, + "Framework": { + "longName": "framework" + }, + "httpPort": { + "isHidden": true + }, + "httpsPort": { + "isHidden": true } }, "usageExamples": [ diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp/.template.config/ide.host.json b/src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/.template.config/ide.host.json similarity index 79% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp/.template.config/ide.host.json rename to src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/.template.config/ide.host.json index 8574a4767a5..a4971fdf7fc 100644 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp/.template.config/ide.host.json +++ b/src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/.template.config/ide.host.json @@ -3,6 +3,10 @@ "order": 0, "icon": "ide/icon.ico", "symbolInfo": [ + { + "id": "Transport", + "isVisible": true + }, { "id": "NativeAot", "isVisible": true diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp/.template.config/ide/icon.ico b/src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/.template.config/ide/icon.ico similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp/.template.config/ide/icon.ico rename to src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/.template.config/ide/icon.ico diff --git a/src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/.template.config/template.json b/src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/.template.config/template.json new file mode 100644 index 00000000000..74ea40a826e --- /dev/null +++ b/src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/.template.config/template.json @@ -0,0 +1,210 @@ +{ + "$schema": "http://json.schemastore.org/template", + "author": "Microsoft", + "classifications": [ + "Common", + "AI", + "MCP" + ], + "identity": "Microsoft.McpServer.ProjectTemplates.McpServer.CSharp", + "name": "MCP Server App", + "description": "A project template for creating a Model Context Protocol (MCP) server using C# and the ModelContextProtocol package.", + "shortName": "mcpserver", + "defaultName": "McpServer", + "sourceName": "McpServer-CSharp", + "preferNameDirectory": true, + "tags": { + "language": "C#", + "type": "project" + }, + "guids": [ + "aaaaaaaa-bbbb-cccc-dddd-eeeeeeffffff" + ], + "symbols": { + "hostIdentifier": { + "type": "bind", + "binding": "HostIdentifier" + }, + "Transport": { + "type": "parameter", + "displayName": "The MCP server _transport type to use", + "description": "Whether to create a 'local' (stdio transport) or 'remote' (http transport) MCP server", + "datatype": "choice", + "choices": [ + { + "choice": "local", + "description": "A console application will be created to use the stdio transport as a local MCP server" + }, + { + "choice": "remote", + "description": "An ASP.NET Core web application will be created to use the http transport as a remote MCP server" + } + ], + "defaultValue": "local" + }, + "NativeAot": { + "type": "parameter", + "datatype": "bool", + "defaultValue": "false", + "displayName": "Enable _native AOT publish", + "description": "Whether to enable the MCP server for publishing as a native AOT application." + }, + "SelfContained": { + "type": "parameter", + "datatype": "bool", + "defaultValue": "true", + "displayName": "Enable _self-contained publish", + "description": "Whether to enable the MCP server for publishing as a self-contained application." + }, + "Framework": { + "type": "parameter", + "description": "The target framework for the project.", + "displayName": "Framework", + "datatype": "choice", + "choices": [ + { + "choice": "net10.0", + "description": ".NET 10" + }, + { + "choice": "net9.0", + "description": ".NET 9" + }, + { + "choice": "net8.0", + "description": ".NET 8" + } + ], + "replaces": "net10.0", + "defaultValue": "net10.0" + }, + "httpsPort": { + "type": "parameter", + "datatype": "integer", + "description": "Port number to use for the HTTPS endpoint in launchSettings.json." + }, + "httpsPortGenerated": { + "type": "generated", + "generator": "port", + "parameters": { + "low": 5000, + "high": 5300 + } + }, + "httpsPortReplacer": { + "type": "generated", + "generator": "coalesce", + "parameters": { + "sourceVariableName": "httpsPort", + "fallbackVariableName": "httpsPortGenerated" + }, + "replaces": "9995", + "onlyIf": [{ + "after": "localhost:" + }] + }, + "httpPort": { + "type": "parameter", + "datatype": "integer", + "description": "Port number to use for the HTTP endpoint in launchSettings.json." + }, + "httpPortGenerated": { + "type": "generated", + "generator": "port", + "parameters": { + "low": 6000, + "high": 6300 + } + }, + "httpPortReplacer": { + "type": "generated", + "generator": "coalesce", + "parameters": { + "sourceVariableName": "httpPort", + "fallbackVariableName": "httpPortGenerated" + }, + "replaces": "9996", + "onlyIf": [{ + "after": "localhost:" + }] + }, + "IsTransportRemote": { + "type": "computed", + "value": "(Transport == \"remote\")" + }, + "IsTransportLocal": { + "type": "computed", + "value": "(!IsTransportRemote)" + } + }, + "primaryOutputs": [ + { + "path": "./README.md" + }, + { + "path": "./McpServer-CSharp.csproj" + } + ], + "sources": [ + { + "source": "./common", + "target": "./" + }, + { + "condition": "(IsTransportLocal)", + "source": "./local", + "target": "./" + }, + { + "condition": "(IsTransportRemote)", + "source": "./remote", + "target": "./" + } + ], + "postActions": [ + { + "condition": "(hostIdentifier != \"dotnetcli\" && hostIdentifier != \"dotnetcli-preview\")", + "description": "Opens README file in the editor", + "manualInstructions": [], + "actionId": "84C0DA21-51C8-4541-9940-6CA19AF04EE6", + "args": { + "files": "0" + }, + "continueOnError": true + } + ], + "SpecialCustomOperations": { + "**/*.md": { + "operations": [ + { + "type": "conditional", + "configuration": { + "if": [ "#### ---#if" ], + "else": [ "#### ---#else" ], + "elseif": [ "#### ---#elseif", "#### ---#elif" ], + "endif": [ "#### ---#endif" ], + "trim": "true", + "wholeLine": "true", + "evaluator": "C++" + } + } + ] + }, + "**/*.http": { + "operations": [ + { + "type": "conditional", + "configuration": { + "if": [ "#if" ], + "else": [ "#else" ], + "elseif": [ "#elseif", "#elif" ], + "endif": [ "#endif" ], + "trim": "true", + "wholeLine": "true", + "evaluator": "C++" + } + } + ] + } + } +} diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp/Tools/RandomNumberTools.cs b/src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/common/Tools/RandomNumberTools.cs similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp/Tools/RandomNumberTools.cs rename to src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/common/Tools/RandomNumberTools.cs diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp/.mcp/server.json b/src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/local/.mcp/server.json similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp/.mcp/server.json rename to src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/local/.mcp/server.json diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp/McpServer-CSharp.csproj-in b/src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/local/McpServer-CSharp.csproj-in similarity index 90% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp/McpServer-CSharp.csproj-in rename to src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/local/McpServer-CSharp.csproj-in index ae86a5b9475..6105d4d53a9 100644 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp/McpServer-CSharp.csproj-in +++ b/src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/local/McpServer-CSharp.csproj-in @@ -1,8 +1,7 @@ - net10.0 - TargetFrameworkOverride + net10.0 win-x64;win-arm64;osx-arm64;linux-x64;linux-arm64;linux-musl-x64 diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp/Program.cs b/src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/local/Program.cs similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp/Program.cs rename to src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/local/Program.cs diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp/README.md b/src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/local/README.md similarity index 98% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp/README.md rename to src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/local/README.md index 95612c5e35e..85da5d0e61f 100644 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/templates/McpServer-CSharp/README.md +++ b/src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/local/README.md @@ -56,6 +56,11 @@ To test this MCP server from source code (locally) without using a built MCP ser } ``` +Refer to the VS Code or Visual Studio documentation for more information on configuring and using MCP servers: + +- [Use MCP servers in VS Code (Preview)](https://code.visualstudio.com/docs/copilot/chat/mcp-servers) +- [Use MCP servers in Visual Studio (Preview)](https://learn.microsoft.com/visualstudio/ide/mcp-servers) + ## Testing the MCP Server Once configured, you can ask Copilot Chat for a random number, for example, `Give me 3 random numbers`. It should prompt you to use the `get_random_number` tool on the `McpServer-CSharp` MCP server and show you the results. @@ -98,8 +103,4 @@ For both VS Code and Visual Studio, the configuration file uses the following se - [Official Documentation](https://modelcontextprotocol.io/) - [Protocol Specification](https://spec.modelcontextprotocol.io/) - [GitHub Organization](https://github.com/modelcontextprotocol) - -Refer to the VS Code or Visual Studio documentation for more information on configuring and using MCP servers: - -- [Use MCP servers in VS Code (Preview)](https://code.visualstudio.com/docs/copilot/chat/mcp-servers) -- [Use MCP servers in Visual Studio (Preview)](https://learn.microsoft.com/visualstudio/ide/mcp-servers) +- [MCP C# SDK](https://modelcontextprotocol.github.io/csharp-sdk) diff --git a/src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/remote/McpServer-CSharp.csproj-in b/src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/remote/McpServer-CSharp.csproj-in new file mode 100644 index 00000000000..dfeea98e66b --- /dev/null +++ b/src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/remote/McpServer-CSharp.csproj-in @@ -0,0 +1,35 @@ + + + + net10.0 + + win-x64;win-arm64;osx-arm64;linux-x64;linux-arm64;linux-musl-x64 + + Major + + enable + enable + aaaaaaaa-bbbb-cccc-dddd-eeeeeeffffff + + + + + true + true + + + true + + + + + true + true + + + + + + + + diff --git a/src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/remote/McpServer-CSharp.http b/src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/remote/McpServer-CSharp.http new file mode 100644 index 00000000000..f79d8ec1429 --- /dev/null +++ b/src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/remote/McpServer-CSharp.http @@ -0,0 +1,21 @@ +# For more info on HTTP files go to https://aka.ms/vs/httpfile + +#if (hostIdentifier == "vs") +@HostAddress = https://localhost:9995 +#else +@HostAddress = http://localhost:9996 +#endif + +POST {{HostAddress}}/ +Accept: application/json, text/event-stream +Content-Type: application/json +MCP-Protocol-Version: 2025-11-25 + +{ + "jsonrpc": "2.0", + "id": 1, + "method": "tools/call", + "params": { + "name": "get_random_number" + } +} diff --git a/src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/remote/Program.cs b/src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/remote/Program.cs new file mode 100644 index 00000000000..3a3ce231e69 --- /dev/null +++ b/src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/remote/Program.cs @@ -0,0 +1,15 @@ +var builder = WebApplication.CreateBuilder(args); + +// Add the MCP services: the transport to use (http) and the tools to register. +builder.Services + .AddMcpServer() + .WithHttpTransport() + .WithTools(); + +var app = builder.Build(); +app.MapMcp(); +#if (hostIdentifier == "vs") +app.UseHttpsRedirection(); +#endif + +app.Run(); diff --git a/src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/remote/Properties/launchSettings.json b/src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/remote/Properties/launchSettings.json new file mode 100644 index 00000000000..37d5661e4de --- /dev/null +++ b/src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/remote/Properties/launchSettings.json @@ -0,0 +1,23 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "http://localhost:9996", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "https://localhost:9995;http://localhost:9996", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/remote/README.md b/src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/remote/README.md new file mode 100644 index 00000000000..a8700767510 --- /dev/null +++ b/src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/templates/McpServer-CSharp/remote/README.md @@ -0,0 +1,78 @@ +# MCP Server + +This README was created using the C# MCP server project template. +It demonstrates how you can easily create an MCP server using C# and run it as an ASP.NET Core web application. + +#### ---#if (SelfContained) +The MCP server is built as a self-contained application and does not require the .NET runtime to be installed on the target machine. +However, since it is self-contained, it must be built for each target platform separately. +By default, the template is configured to build for: +* `win-x64` +* `win-arm64` +* `osx-arm64` +* `linux-x64` +* `linux-arm64` +* `linux-musl-x64` + +If you require more platforms to be supported, update the list of runtime identifiers in the project's `` element. +#### ---#else +The MCP server is built as a framework-dependent application and requires the ASP.NET Core runtime to be installed on the target machine. +The application is configured to roll-forward to the next highest major version of the runtime if one is available on the target machine. +If an applicable .NET runtime is not available, the MCP server will not start. +Consider building the MCP server as a self-contained application if you want to avoid this dependency. +#### ---#endif + +Please note that this template is currently in an early preview stage. If you have feedback, please take a [brief survey](http://aka.ms/dotnet-mcp-template-survey). + +## Developing locally + +To test this MCP server from source code (locally), you can configure your IDE to connect to the server using localhost. + +#### ---#if (hostIdentifier == "vs") +```json +{ + "servers": { + "McpServer-CSharp": { + "type": "http", + "url": "https://localhost:9995" + } + } +} +``` +#### ---#else +```json +{ + "servers": { + "McpServer-CSharp": { + "type": "http", + "url": "http://localhost:9996" + } + } +} +``` +#### ---#endif + +Refer to the VS Code or Visual Studio documentation for more information on configuring and using MCP servers: + +- [Use MCP servers in VS Code (Preview)](https://code.visualstudio.com/docs/copilot/chat/mcp-servers) +- [Use MCP servers in Visual Studio (Preview)](https://learn.microsoft.com/visualstudio/ide/mcp-servers) + +## Testing the MCP Server + +Once configured, you can ask Copilot Chat for a random number, for example, `Give me 3 random numbers`. It should prompt you to use the `get_random_number` tool on the `McpServer-CSharp` MCP server and show you the results. + +## Known issues + +1. When using VS Code, connecting to `https://localhost:9995` fails. + * This is related to using a self-signed developer certificate, even when the certificate is trusted by the system. + * Connecting with `http://localhost:9996` succeeds. + * See [Cannot connect to MCP server via SSE using trusted developer certificate (microsoft/vscode#248170)](https://github.com/microsoft/vscode/issues/248170) for more information. + +## More information + +ASP.NET Core MCP servers use the [ModelContextProtocol.AspNetCore](https://www.nuget.org/packages/ModelContextProtocol.AspNetCore) package from the MCP C# SDK. For more information about MCP: + +- [Official Documentation](https://modelcontextprotocol.io/) +- [Protocol Specification](https://spec.modelcontextprotocol.io/) +- [GitHub Organization](https://github.com/modelcontextprotocol) +- [MCP C# SDK](https://modelcontextprotocol.github.io/csharp-sdk) diff --git a/test/ProjectTemplates/Infrastructure/TemplateTestUtilities.cs b/test/ProjectTemplates/Infrastructure/TemplateTestUtilities.cs index 051b9515ccd..58fe84b7198 100644 --- a/test/ProjectTemplates/Infrastructure/TemplateTestUtilities.cs +++ b/test/ProjectTemplates/Infrastructure/TemplateTestUtilities.cs @@ -36,7 +36,7 @@ public static class TemplateTestUtilities public static string GetProjectNameForArgs(string[] args, string? prefix = null) { IEnumerable nameParts = args - .Select(arg => Regex.Replace(arg, @"--[Ff]ramework=(net[0-9]+)\.0", "$1")) + .Select(arg => Regex.Replace(arg, @"-(?:f|-[Ff]ramework)=(net[0-9]+)\.0", "$1")) .Select(arg => Regex.Replace(arg, "--(.*?)=true", "$1_T")) .Select(arg => Regex.Replace(arg, "--(.*?)=false", "$1_F")) .Select(arg => Regex.Replace(arg, "--(.*?)=(.*)", "$2")) diff --git a/test/ProjectTemplates/Infrastructure/VerifyScrubbers.cs b/test/ProjectTemplates/Infrastructure/VerifyScrubbers.cs index d172082c5e3..1fa35f33a5e 100644 --- a/test/ProjectTemplates/Infrastructure/VerifyScrubbers.cs +++ b/test/ProjectTemplates/Infrastructure/VerifyScrubbers.cs @@ -44,6 +44,7 @@ public static ScrubbersDefinition AddLocalhostPortScrubber( return scrubbers .AddScrubber(scrubPorts, extension: "md") + .AddScrubber(scrubPorts, extension: "http") .AddScrubber((path, content) => { if (Path.GetFileName(path).Equals("launchSettings.json", StringComparison.OrdinalIgnoreCase)) diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/McpServerExecutionTests.cs b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/McpServerExecutionTests.cs similarity index 94% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/McpServerExecutionTests.cs rename to test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/McpServerExecutionTests.cs index 5a3abd9591b..48aaee30a1c 100644 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/McpServerExecutionTests.cs +++ b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/McpServerExecutionTests.cs @@ -30,7 +30,7 @@ public McpServerExecutionTests(TemplateExecutionTestFixture fixture, ITestOutput public static TemplateExecutionTestConfiguration Configuration { get; } = new() { - TemplatePackageName = "Microsoft.Extensions.AI.Templates", + TemplatePackageName = "Microsoft.McpServer.ProjectTemplates", TemplateName = "mcpserver" }; @@ -39,6 +39,7 @@ public static IEnumerable GetSupportedProjectConfigurations() (string name, string[] values)[] allOptionValues = [ ("--aot", ["true", "false"]), ("--self-contained", ["true", "false"]), + ("--transport", ["local", "remote"]), ("--framework", ["net8.0", "net9.0", "net10.0"]) ]; diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/McpServerSnapshotTests.cs b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/McpServerSnapshotTests.cs similarity index 77% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/McpServerSnapshotTests.cs rename to test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/McpServerSnapshotTests.cs index c20b9345606..60e38c0f504 100644 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/McpServerSnapshotTests.cs +++ b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/McpServerSnapshotTests.cs @@ -23,22 +23,26 @@ public McpServerSnapshotTests(ITestOutputHelper log) } [Theory] - [InlineData /* Defaults: --self-contained=true --aot=false --framework=net10.0 */] + [InlineData /* Defaults: --transport local --self-contained=true --aot=false --framework=net10.0 */] + [InlineData("--transport=remote")] [InlineData("--self-contained=false")] [InlineData("--aot=true")] [InlineData("--framework=net8.0")] public async Task TestSnapshots(params string[] templateArgs) { string projectNamePrefix = "McpServer"; - string templatePackageName = "Microsoft.Extensions.AI.Templates"; + string templatePackageName = "Microsoft.McpServer.ProjectTemplates"; string templateName = "mcpserver"; TemplateVerifierOptions options = PrepareSnapshotVerifier( projectNamePrefix, templatePackageName, templateName, - templateArgs) + templateArgs, + verificationExcludePatterns: ["*.http"]) // Snapshot verifier fails on .http files .WithCustomScrubbers(ScrubbersDefinition.Empty + .AddUserSecretsScrubber() + .AddLocalhostPortScrubber() .AddPackageReferenceScrubber()); VerificationEngine engine = new VerificationEngine(_log); diff --git a/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Microsoft.McpServer.ProjectTemplates.Tests.csproj b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Microsoft.McpServer.ProjectTemplates.Tests.csproj new file mode 100644 index 00000000000..1a51fcb19cb --- /dev/null +++ b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Microsoft.McpServer.ProjectTemplates.Tests.csproj @@ -0,0 +1,27 @@ + + + + Tests for Microsoft.McpServer.ProjectTemplates. + false + true + + + + $(NoWarn);CA1063;CA1716;CA1861;CA2201;VSTHRD003;S104;S125;S2699 + + + + + + + + + + + + + + + + + diff --git a/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/README.md b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/README.md new file mode 100644 index 00000000000..5516215cdd5 --- /dev/null +++ b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/README.md @@ -0,0 +1,7 @@ +# Microsoft.McpServer.ProjectTemplates tests + +Contains snapshot and execution tests for `Microsoft.McpServer.ProjectTemplates`. + +To update test snapshots, install and run the `DiffEngineTray` tool following [these instructions](https://github.com/VerifyTests/DiffEngine/blob/main/docs/tray.md), run the snapshot tests either in VS or using `dotnet test`, and use `DiffEngineTray` to accept or discard changes. + +For information on debugging template execution tests, see [this README](./TemplateSandbox/README.md). diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.AOT_T.verified/mcpserver/.mcp/server.json b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.AOT_T.verified/mcpserver/.mcp/server.json similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.AOT_T.verified/mcpserver/.mcp/server.json rename to test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.AOT_T.verified/mcpserver/.mcp/server.json diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.AOT_T.verified/mcpserver/Program.cs b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.AOT_T.verified/mcpserver/Program.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.AOT_T.verified/mcpserver/Program.cs rename to test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.AOT_T.verified/mcpserver/Program.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.AOT_T.verified/mcpserver/README.md b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.AOT_T.verified/mcpserver/README.md similarity index 98% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.AOT_T.verified/mcpserver/README.md rename to test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.AOT_T.verified/mcpserver/README.md index 31035a6370e..e73eb0c2ba8 100644 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.AOT_T.verified/mcpserver/README.md +++ b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.AOT_T.verified/mcpserver/README.md @@ -49,6 +49,11 @@ To test this MCP server from source code (locally) without using a built MCP ser } ``` +Refer to the VS Code or Visual Studio documentation for more information on configuring and using MCP servers: + +- [Use MCP servers in VS Code (Preview)](https://code.visualstudio.com/docs/copilot/chat/mcp-servers) +- [Use MCP servers in Visual Studio (Preview)](https://learn.microsoft.com/visualstudio/ide/mcp-servers) + ## Testing the MCP Server Once configured, you can ask Copilot Chat for a random number, for example, `Give me 3 random numbers`. It should prompt you to use the `get_random_number` tool on the `mcpserver` MCP server and show you the results. @@ -91,8 +96,4 @@ For both VS Code and Visual Studio, the configuration file uses the following se - [Official Documentation](https://modelcontextprotocol.io/) - [Protocol Specification](https://spec.modelcontextprotocol.io/) - [GitHub Organization](https://github.com/modelcontextprotocol) - -Refer to the VS Code or Visual Studio documentation for more information on configuring and using MCP servers: - -- [Use MCP servers in VS Code (Preview)](https://code.visualstudio.com/docs/copilot/chat/mcp-servers) -- [Use MCP servers in Visual Studio (Preview)](https://learn.microsoft.com/visualstudio/ide/mcp-servers) +- [MCP C# SDK](https://modelcontextprotocol.github.io/csharp-sdk) diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.AOT_T.verified/mcpserver/Tools/RandomNumberTools.cs b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.AOT_T.verified/mcpserver/Tools/RandomNumberTools.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.AOT_T.verified/mcpserver/Tools/RandomNumberTools.cs rename to test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.AOT_T.verified/mcpserver/Tools/RandomNumberTools.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.AOT_T.verified/mcpserver/mcpserver.csproj b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.AOT_T.verified/mcpserver/mcpserver.csproj similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.AOT_T.verified/mcpserver/mcpserver.csproj rename to test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.AOT_T.verified/mcpserver/mcpserver.csproj diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.SC_F.verified/mcpserver/.mcp/server.json b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.SC_F.verified/mcpserver/.mcp/server.json similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.SC_F.verified/mcpserver/.mcp/server.json rename to test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.SC_F.verified/mcpserver/.mcp/server.json diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.SC_F.verified/mcpserver/Program.cs b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.SC_F.verified/mcpserver/Program.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.SC_F.verified/mcpserver/Program.cs rename to test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.SC_F.verified/mcpserver/Program.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.SC_F.verified/mcpserver/README.md b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.SC_F.verified/mcpserver/README.md similarity index 98% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.SC_F.verified/mcpserver/README.md rename to test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.SC_F.verified/mcpserver/README.md index 1702211733a..0075771030f 100644 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.SC_F.verified/mcpserver/README.md +++ b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.SC_F.verified/mcpserver/README.md @@ -42,6 +42,11 @@ To test this MCP server from source code (locally) without using a built MCP ser } ``` +Refer to the VS Code or Visual Studio documentation for more information on configuring and using MCP servers: + +- [Use MCP servers in VS Code (Preview)](https://code.visualstudio.com/docs/copilot/chat/mcp-servers) +- [Use MCP servers in Visual Studio (Preview)](https://learn.microsoft.com/visualstudio/ide/mcp-servers) + ## Testing the MCP Server Once configured, you can ask Copilot Chat for a random number, for example, `Give me 3 random numbers`. It should prompt you to use the `get_random_number` tool on the `mcpserver` MCP server and show you the results. @@ -84,8 +89,4 @@ For both VS Code and Visual Studio, the configuration file uses the following se - [Official Documentation](https://modelcontextprotocol.io/) - [Protocol Specification](https://spec.modelcontextprotocol.io/) - [GitHub Organization](https://github.com/modelcontextprotocol) - -Refer to the VS Code or Visual Studio documentation for more information on configuring and using MCP servers: - -- [Use MCP servers in VS Code (Preview)](https://code.visualstudio.com/docs/copilot/chat/mcp-servers) -- [Use MCP servers in Visual Studio (Preview)](https://learn.microsoft.com/visualstudio/ide/mcp-servers) +- [MCP C# SDK](https://modelcontextprotocol.github.io/csharp-sdk) diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.SC_F.verified/mcpserver/Tools/RandomNumberTools.cs b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.SC_F.verified/mcpserver/Tools/RandomNumberTools.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.SC_F.verified/mcpserver/Tools/RandomNumberTools.cs rename to test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.SC_F.verified/mcpserver/Tools/RandomNumberTools.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.SC_F.verified/mcpserver/mcpserver.csproj b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.SC_F.verified/mcpserver/mcpserver.csproj similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.SC_F.verified/mcpserver/mcpserver.csproj rename to test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.SC_F.verified/mcpserver/mcpserver.csproj diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver._defaults.verified/mcpserver/.mcp/server.json b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver._defaults.verified/mcpserver/.mcp/server.json similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver._defaults.verified/mcpserver/.mcp/server.json rename to test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver._defaults.verified/mcpserver/.mcp/server.json diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver._defaults.verified/mcpserver/Program.cs b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver._defaults.verified/mcpserver/Program.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver._defaults.verified/mcpserver/Program.cs rename to test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver._defaults.verified/mcpserver/Program.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver._defaults.verified/mcpserver/README.md b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver._defaults.verified/mcpserver/README.md similarity index 98% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver._defaults.verified/mcpserver/README.md rename to test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver._defaults.verified/mcpserver/README.md index 31035a6370e..e73eb0c2ba8 100644 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver._defaults.verified/mcpserver/README.md +++ b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver._defaults.verified/mcpserver/README.md @@ -49,6 +49,11 @@ To test this MCP server from source code (locally) without using a built MCP ser } ``` +Refer to the VS Code or Visual Studio documentation for more information on configuring and using MCP servers: + +- [Use MCP servers in VS Code (Preview)](https://code.visualstudio.com/docs/copilot/chat/mcp-servers) +- [Use MCP servers in Visual Studio (Preview)](https://learn.microsoft.com/visualstudio/ide/mcp-servers) + ## Testing the MCP Server Once configured, you can ask Copilot Chat for a random number, for example, `Give me 3 random numbers`. It should prompt you to use the `get_random_number` tool on the `mcpserver` MCP server and show you the results. @@ -91,8 +96,4 @@ For both VS Code and Visual Studio, the configuration file uses the following se - [Official Documentation](https://modelcontextprotocol.io/) - [Protocol Specification](https://spec.modelcontextprotocol.io/) - [GitHub Organization](https://github.com/modelcontextprotocol) - -Refer to the VS Code or Visual Studio documentation for more information on configuring and using MCP servers: - -- [Use MCP servers in VS Code (Preview)](https://code.visualstudio.com/docs/copilot/chat/mcp-servers) -- [Use MCP servers in Visual Studio (Preview)](https://learn.microsoft.com/visualstudio/ide/mcp-servers) +- [MCP C# SDK](https://modelcontextprotocol.github.io/csharp-sdk) diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver._defaults.verified/mcpserver/Tools/RandomNumberTools.cs b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver._defaults.verified/mcpserver/Tools/RandomNumberTools.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver._defaults.verified/mcpserver/Tools/RandomNumberTools.cs rename to test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver._defaults.verified/mcpserver/Tools/RandomNumberTools.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver._defaults.verified/mcpserver/mcpserver.csproj b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver._defaults.verified/mcpserver/mcpserver.csproj similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver._defaults.verified/mcpserver/mcpserver.csproj rename to test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver._defaults.verified/mcpserver/mcpserver.csproj diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.net8.verified/mcpserver/.mcp/server.json b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.net8.verified/mcpserver/.mcp/server.json similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.net8.verified/mcpserver/.mcp/server.json rename to test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.net8.verified/mcpserver/.mcp/server.json diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.net8.verified/mcpserver/Program.cs b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.net8.verified/mcpserver/Program.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.net8.verified/mcpserver/Program.cs rename to test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.net8.verified/mcpserver/Program.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.net8.verified/mcpserver/README.md b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.net8.verified/mcpserver/README.md similarity index 98% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.net8.verified/mcpserver/README.md rename to test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.net8.verified/mcpserver/README.md index 31035a6370e..e73eb0c2ba8 100644 --- a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.net8.verified/mcpserver/README.md +++ b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.net8.verified/mcpserver/README.md @@ -49,6 +49,11 @@ To test this MCP server from source code (locally) without using a built MCP ser } ``` +Refer to the VS Code or Visual Studio documentation for more information on configuring and using MCP servers: + +- [Use MCP servers in VS Code (Preview)](https://code.visualstudio.com/docs/copilot/chat/mcp-servers) +- [Use MCP servers in Visual Studio (Preview)](https://learn.microsoft.com/visualstudio/ide/mcp-servers) + ## Testing the MCP Server Once configured, you can ask Copilot Chat for a random number, for example, `Give me 3 random numbers`. It should prompt you to use the `get_random_number` tool on the `mcpserver` MCP server and show you the results. @@ -91,8 +96,4 @@ For both VS Code and Visual Studio, the configuration file uses the following se - [Official Documentation](https://modelcontextprotocol.io/) - [Protocol Specification](https://spec.modelcontextprotocol.io/) - [GitHub Organization](https://github.com/modelcontextprotocol) - -Refer to the VS Code or Visual Studio documentation for more information on configuring and using MCP servers: - -- [Use MCP servers in VS Code (Preview)](https://code.visualstudio.com/docs/copilot/chat/mcp-servers) -- [Use MCP servers in Visual Studio (Preview)](https://learn.microsoft.com/visualstudio/ide/mcp-servers) +- [MCP C# SDK](https://modelcontextprotocol.github.io/csharp-sdk) diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.net8.verified/mcpserver/Tools/RandomNumberTools.cs b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.net8.verified/mcpserver/Tools/RandomNumberTools.cs similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.net8.verified/mcpserver/Tools/RandomNumberTools.cs rename to test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.net8.verified/mcpserver/Tools/RandomNumberTools.cs diff --git a/test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.net8.verified/mcpserver/mcpserver.csproj b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.net8.verified/mcpserver/mcpserver.csproj similarity index 100% rename from test/ProjectTemplates/Microsoft.Extensions.AI.Templates.IntegrationTests/Snapshots/mcpserver/mcpserver.net8.verified/mcpserver/mcpserver.csproj rename to test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.net8.verified/mcpserver/mcpserver.csproj diff --git a/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.remote.verified/mcpserver/Program.cs b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.remote.verified/mcpserver/Program.cs new file mode 100644 index 00000000000..aaf2a58e5d4 --- /dev/null +++ b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.remote.verified/mcpserver/Program.cs @@ -0,0 +1,12 @@ +var builder = WebApplication.CreateBuilder(args); + +// Add the MCP services: the transport to use (http) and the tools to register. +builder.Services + .AddMcpServer() + .WithHttpTransport() + .WithTools(); + +var app = builder.Build(); +app.MapMcp(); + +app.Run(); diff --git a/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.remote.verified/mcpserver/Properties/launchSettings.json b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.remote.verified/mcpserver/Properties/launchSettings.json new file mode 100644 index 00000000000..2ed7b6843b1 --- /dev/null +++ b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.remote.verified/mcpserver/Properties/launchSettings.json @@ -0,0 +1,23 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "http://localhost:9996", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "https://localhost:9995;http://localhost:9996", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.remote.verified/mcpserver/README.md b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.remote.verified/mcpserver/README.md new file mode 100644 index 00000000000..56429ca7018 --- /dev/null +++ b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.remote.verified/mcpserver/README.md @@ -0,0 +1,58 @@ +# MCP Server + +This README was created using the C# MCP server project template. +It demonstrates how you can easily create an MCP server using C# and run it as an ASP.NET Core web application. + +The MCP server is built as a self-contained application and does not require the .NET runtime to be installed on the target machine. +However, since it is self-contained, it must be built for each target platform separately. +By default, the template is configured to build for: +* `win-x64` +* `win-arm64` +* `osx-arm64` +* `linux-x64` +* `linux-arm64` +* `linux-musl-x64` + +If you require more platforms to be supported, update the list of runtime identifiers in the project's `` element. + +Please note that this template is currently in an early preview stage. If you have feedback, please take a [brief survey](http://aka.ms/dotnet-mcp-template-survey). + +## Developing locally + +To test this MCP server from source code (locally), you can configure your IDE to connect to the server using localhost. + +```json +{ + "servers": { + "mcpserver": { + "type": "http", + "url": "http://localhost:9996" + } + } +} +``` + +Refer to the VS Code or Visual Studio documentation for more information on configuring and using MCP servers: + +- [Use MCP servers in VS Code (Preview)](https://code.visualstudio.com/docs/copilot/chat/mcp-servers) +- [Use MCP servers in Visual Studio (Preview)](https://learn.microsoft.com/visualstudio/ide/mcp-servers) + +## Testing the MCP Server + +Once configured, you can ask Copilot Chat for a random number, for example, `Give me 3 random numbers`. It should prompt you to use the `get_random_number` tool on the `mcpserver` MCP server and show you the results. + +## Known issues + +1. When using VS Code, connecting to `https://localhost:9995` fails. + * This is related to using a self-signed developer certificate, even when the certificate is trusted by the system. + * Connecting with `http://localhost:9996` succeeds. + * See [Cannot connect to MCP server via SSE using trusted developer certificate (microsoft/vscode#248170)](https://github.com/microsoft/vscode/issues/248170) for more information. + +## More information + +ASP.NET Core MCP servers use the [ModelContextProtocol.AspNetCore](https://www.nuget.org/packages/ModelContextProtocol.AspNetCore) package from the MCP C# SDK. For more information about MCP: + +- [Official Documentation](https://modelcontextprotocol.io/) +- [Protocol Specification](https://spec.modelcontextprotocol.io/) +- [GitHub Organization](https://github.com/modelcontextprotocol) +- [MCP C# SDK](https://modelcontextprotocol.github.io/csharp-sdk) diff --git a/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.remote.verified/mcpserver/Tools/RandomNumberTools.cs b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.remote.verified/mcpserver/Tools/RandomNumberTools.cs new file mode 100644 index 00000000000..611745f4129 --- /dev/null +++ b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.remote.verified/mcpserver/Tools/RandomNumberTools.cs @@ -0,0 +1,18 @@ +using System.ComponentModel; +using ModelContextProtocol.Server; + +/// +/// Sample MCP tools for demonstration purposes. +/// These tools can be invoked by MCP clients to perform various operations. +/// +internal class RandomNumberTools +{ + [McpServerTool] + [Description("Generates a random number between the specified minimum and maximum values.")] + public int GetRandomNumber( + [Description("Minimum value (inclusive)")] int min = 0, + [Description("Maximum value (exclusive)")] int max = 100) + { + return Random.Shared.Next(min, max); + } +} diff --git a/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.remote.verified/mcpserver/mcpserver.csproj b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.remote.verified/mcpserver/mcpserver.csproj new file mode 100644 index 00000000000..794e7c35766 --- /dev/null +++ b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/Snapshots/mcpserver/mcpserver.remote.verified/mcpserver/mcpserver.csproj @@ -0,0 +1,23 @@ + + + + net10.0 + win-x64;win-arm64;osx-arm64;linux-x64;linux-arm64;linux-musl-x64 + enable + enable + {00000000-0000-0000-0000-000000000000} + + + + true + true + + + true + + + + + + + diff --git a/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/xunit.runner.json b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/xunit.runner.json new file mode 100644 index 00000000000..9faab404ec0 --- /dev/null +++ b/test/ProjectTemplates/Microsoft.McpServer.ProjectTemplates.IntegrationTests/xunit.runner.json @@ -0,0 +1,5 @@ +{ + "longRunningTestSeconds": 60, + "diagnosticMessages": true, + "maxParallelThreads": 1 +} From 637e824c8d7ccfc7a4dfd8196d4dd69b65d66551 Mon Sep 17 00:00:00 2001 From: Jeff Handley Date: Fri, 19 Dec 2025 16:51:42 -0800 Subject: [PATCH 5/6] Pin AIChatWeb projtect template to published package versions --- .../Microsoft.Extensions.AI.Templates.csproj | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/Microsoft.Extensions.AI.Templates.csproj b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/Microsoft.Extensions.AI.Templates.csproj index f83fda4db7e..629b29e204f 100644 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/Microsoft.Extensions.AI.Templates.csproj +++ b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/Microsoft.Extensions.AI.Templates.csproj @@ -34,6 +34,18 @@ + + + + + + + + + + + + From 2f3af7d2513aa8f7c03c4b46702354ab09223ba9 Mon Sep 17 00:00:00 2001 From: Jeff Handley Date: Fri, 19 Dec 2025 17:01:40 -0800 Subject: [PATCH 6/6] Set Microsoft.McpServer.ProjectTemplates version to align with MCP packages --- .../Microsoft.McpServer.ProjectTemplates.csproj | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/Microsoft.McpServer.ProjectTemplates.csproj b/src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/Microsoft.McpServer.ProjectTemplates.csproj index 82c9428f159..d13bce3c597 100644 --- a/src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/Microsoft.McpServer.ProjectTemplates.csproj +++ b/src/ProjectTemplates/Microsoft.McpServer.ProjectTemplates/Microsoft.McpServer.ProjectTemplates.csproj @@ -7,7 +7,14 @@ dotnet-new;templates;ai preview + + + 0 + 5 + 0 + preview 1 + AI 0 0