zcode-app-cli 3.16.2-38 → 3.16.3-40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/LICENSES/README.md +1 -1
  2. package/README.md +19 -4
  3. package/bin/zcode.js +47 -16
  4. package/docs/CONFIGURATION.md +2 -1
  5. package/docs/CONFIGURATION.zh-CN.md +2 -1
  6. package/docs/THIRD_PARTY_CONTENT.md +2 -2
  7. package/package.json +2 -2
  8. package/vendor/cli-config.cjs +21 -0
  9. package/vendor/extraction.json +9 -4
  10. package/vendor/node_modules/@zcode/tui/dist/index.js +79 -22
  11. package/vendor/packages/documents-plugin/.zcode-plugin/plugin.json +3 -2
  12. package/vendor/packages/documents-plugin/dist/server.mjs +201 -152
  13. package/vendor/packages/documents-plugin/dist/ui/bundle-0.txt +1 -1
  14. package/vendor/packages/documents-plugin/dist/ui/panel.html +1 -1
  15. package/vendor/packages/documents-plugin/package.json +1 -1
  16. package/vendor/packages/node-repl-host/dist/mcp/server.js +1 -1
  17. package/vendor/packages/pdf-plugin/.zcode-plugin/plugin.json +3 -2
  18. package/vendor/packages/pdf-plugin/dist/server.mjs +201 -152
  19. package/vendor/packages/pdf-plugin/dist/ui/bundle-0.txt +1 -1
  20. package/vendor/packages/pdf-plugin/dist/ui/panel.html +1 -1
  21. package/vendor/packages/pdf-plugin/package.json +1 -1
  22. package/vendor/packages/presentations-plugin/.zcode-plugin/plugin.json +3 -2
  23. package/vendor/packages/presentations-plugin/dist/server.mjs +201 -152
  24. package/vendor/packages/presentations-plugin/dist/ui/bundle-0.txt +1 -1
  25. package/vendor/packages/presentations-plugin/dist/ui/panel.html +1 -1
  26. package/vendor/packages/presentations-plugin/package.json +1 -1
  27. package/vendor/packages/spreadsheets-plugin/.zcode-plugin/plugin.json +3 -2
  28. package/vendor/packages/spreadsheets-plugin/dist/server.mjs +201 -152
  29. package/vendor/packages/spreadsheets-plugin/dist/ui/bundle-0.txt +1 -1
  30. package/vendor/packages/spreadsheets-plugin/dist/ui/panel.html +1 -1
  31. package/vendor/packages/spreadsheets-plugin/package.json +1 -1
  32. package/vendor/zcode.cjs +1033 -1031
  33. package/zcode-runtime.lock.json +3 -3
@@ -105,7 +105,7 @@ Boolean requesting whether a visible border and background is provided by the ho
105
105
  - omitted: host decides border`)}),KJ=x.object({method:x.literal("ui/request-display-mode"),params:x.object({mode:Am.describe("The display mode being requested.")})}),z5=x.object({mode:Am.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough(),k5=x.union([x.literal("model"),x.literal("app")]).describe("Tool visibility scope - who can access the tool."),YJ=x.object({resourceUri:x.string().optional(),visibility:x.array(k5).optional().describe(`Who can access this tool. Default: ["model", "app"]
106
106
  - "model": Tool visible to and callable by the agent
107
107
  - "app": Tool callable by the app from this server only`),csp:x.never().optional(),permissions:x.never().optional()}),XJ=x.object({mimeTypes:x.array(x.string()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),JJ=x.object({method:x.literal("ui/download-file"),params:x.object({contents:x.array(x.union([Is,Os])).describe("Resource contents to download \u2014 embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),WJ=x.object({method:x.literal("ui/message"),params:x.object({role:x.literal("user").describe('Message role, currently only "user" is supported.'),content:x.array(Er).describe("Message content blocks (text, image, etc.).")})}),QJ=x.object({method:x.literal("ui/notifications/sandbox-resource-ready"),params:x.object({html:x.string().describe("HTML content to load into the inner iframe."),sandbox:x.string().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:zz.optional().describe("CSP configuration from resource metadata."),permissions:kz.optional().describe("Sandbox permissions from resource metadata.")})}),R5=x.object({method:x.literal("ui/notifications/tool-result"),params:xa.describe("Standard MCP tool execution result.")}),z2=x.object({toolInfo:x.object({id:er.optional().describe("JSON-RPC id of the tools/call request."),tool:wa.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:f5.optional().describe("Current color theme preference."),styles:x5.optional().describe("Style configuration for theming the app."),displayMode:Am.optional().describe("How the UI is currently displayed."),availableDisplayModes:x.array(Am).optional().describe("Display modes the host supports."),containerDimensions:x.union([x.object({height:x.number().describe("Fixed container height in pixels.")}),x.object({maxHeight:x.union([x.number(),x.undefined()]).optional().describe("Maximum container height in pixels.")})]).and(x.union([x.object({width:x.number().describe("Fixed container width in pixels.")}),x.object({maxWidth:x.union([x.number(),x.undefined()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
108
- container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:x.string().optional().describe("User's language and region preference in BCP 47 format."),timeZone:x.string().optional().describe("User's timezone in IANA format."),userAgent:x.string().optional().describe("Host application identifier."),platform:x.union([x.literal("web"),x.literal("desktop"),x.literal("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:x.object({touch:x.boolean().optional().describe("Whether the device supports touch input."),hover:x.boolean().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:x.object({top:x.number().describe("Top safe area inset in pixels."),right:x.number().describe("Right safe area inset in pixels."),bottom:x.number().describe("Bottom safe area inset in pixels."),left:x.number().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),C5=x.object({method:x.literal("ui/notifications/host-context-changed"),params:z2.describe("Partial context update containing only changed fields.")}),e7=x.object({method:x.literal("ui/update-model-context"),params:x.object({content:x.array(Er).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:x.record(x.string(),x.unknown().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),t7=x.object({method:x.literal("ui/initialize"),params:x.object({appInfo:$r.describe("App identification (name and version)."),appCapabilities:T5.describe("Features and capabilities this app provides."),protocolVersion:x.string().describe("Protocol version this app supports.")})}),I5=x.object({protocolVersion:x.string().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:$r.describe("Host application identification and version."),hostCapabilities:E5.describe("Features and capabilities provided by the host."),hostContext:z2.describe("Rich context about the host environment.")}).passthrough(),O5={target:"draft-2020-12"};async function E2(t,e){let n=t["~standard"];if(n.jsonSchema)return n.jsonSchema[e](O5);throw Error(`Schema (vendor: ${n.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function T2(t,e,n=""){let r=await t["~standard"].validate(e);if(r.issues){let i=r.issues.map(o=>{let a=o.path?.map(s=>typeof s=="object"?s.key:s).join(".");return a?`${a}: ${o.message}`:o.message}).join("; ");throw Error(n+i)}return r.value}function k2(t,e=document.documentElement){for(let[n,r]of Object.entries(t))r!==void 0&&e.style.setProperty(n,r)}function P5(t,e){let n={...t,...e};return e.experimental!==void 0&&(n.experimental={...t.experimental,...e.experimental}),e.tools!==void 0&&(n.tools={...t.tools,...e.tools}),n}var Ly=class t extends Az{_appInfo;_appCapabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_registeredEvents=new Set;_events=new Ez;_methods=new Tz;setRequestHandler=(...e)=>{let[n,...r]=$2("request",e)??e;this._methods.claim(n,"setRequestHandler"),super.setRequestHandler.call(this,n,...r)};setNotificationHandler=(...e)=>{let[n,...r]=$2("notification",e)??e;this._methods.claim(n,"setNotificationHandler"),super.setNotificationHandler.call(this,n,...r)};removeRequestHandler=e=>{this._methods.release(e),super.removeRequestHandler(e)};removeNotificationHandler=e=>{this._methods.release(e),super.removeNotificationHandler(e)};replaceRequestHandler=(e,...n)=>{this._methods.replace(e),super.setRequestHandler.call(this,e,...n)};_assertInitialized(e){if(this._initializedSent)return;let n=`[ext-apps] App.${e}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(n);console.warn(`${n}. This will throw in a future release.`)}eventSchemas={toolinput:y5,toolinputpartial:S5,toolresult:R5,toolcancelled:_5,hostcontextchanged:C5};static ONE_SHOT_EVENTS=new Set(["toolinput","toolinputpartial","toolresult","toolcancelled"]);_everHadListener=new Set;_assertHandlerTiming(e){if(!t.ONE_SHOT_EVENTS.has(e)||this._everHadListener.has(e)||(this._everHadListener.add(e),!this._initializedSent))return;let n=`[ext-apps] "${String(e)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(n);console.warn(n)}setEventHandler(e,n){n&&this._assertHandlerTiming(e),this._ensureEventSlot(e),this._events.setHandler(e,n)}addEventListener(e,n){this._assertHandlerTiming(e),this._ensureEventSlot(e),this._events.addEventListener(e,n)}removeEventListener(e,n){this._events.removeEventListener(e,n)}_ensureEventSlot(e){if(this._registeredEvents.has(e))return;let n=this.eventSchemas[e];if(!n)throw Error(`Unknown event: ${String(e)}`);this.setNotificationHandler(n.shape.method.value,{params:n.shape.params},r=>{let i=r;e==="hostcontextchanged"&&(this._hostContext={...this._hostContext,...i}),this._events.dispatch(e,i)}),this._registeredEvents.add(e)}getEventHandler(e){return this._events.getHandler(e)}warnIfRequestHandlerReplaced(e,n,r){n&&r&&console.warn(`[MCP Apps] ${e} handler replaced. Previous handler will no longer be called.`)}constructor(e,n={},r={autoResize:!0}){super(r),this._appInfo=e,this._appCapabilities=n,this.options=r,this._methods.replace("notifications/cancelled"),this._methods.replace("notifications/progress"),!r.allowUnsafeEval&&x.config({jitless:!0}),this.replaceRequestHandler("ping",i=>(console.log("Received ping:",i.params),{})),this.setEventHandler("hostcontextchanged",void 0)}buildContext(e){return e}registerAppCapabilities(e){if(this.transport)throw Error("Cannot register capabilities after transport is established");this._appCapabilities=P5(this._appCapabilities,e)}registerTool(e,n,r){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let i=this,o=()=>{i._initializedSent&&i._appCapabilities.tools?.listChanged&&i.sendToolListChanged()},a=n.inputSchema!==void 0,s={title:n.title,description:n.description,inputSchema:n.inputSchema,outputSchema:n.outputSchema,annotations:n.annotations,_meta:n._meta,enabled:!0,enable(){this.enabled=!0,o()},disable(){this.enabled=!1,o()},update(l){Object.assign(this,l),o()},remove(){i._registeredTools[e]===s&&(delete i._registeredTools[e],o())},handler:async(l,c)=>{if(!s.enabled)throw Error(`Tool ${e} is disabled`);let u;if(a){let d=s.inputSchema,h=d?await T2(d,l??{},`Invalid input for tool ${e}: `):l??{};u=await r(h,c)}else u=await r(c);return s.outputSchema&&!u.isError&&(u.structuredContent=await T2(s.outputSchema,u.structuredContent,`Invalid output for tool ${e}: `)),u}};return this._registeredTools[e]=s,!this._appCapabilities.tools&&!this.transport&&this.registerAppCapabilities({tools:{listChanged:!0}}),this.ensureToolHandlersInitialized(),o(),s}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){this._toolHandlersInitialized||(this._toolHandlersInitialized=!0,this.oncalltool=async(e,n)=>{let r=this._registeredTools[e.name];if(!r)throw Error(`Tool ${e.name} not found`);return r.handler(e.arguments,n)},this.onlisttools=async(e,n)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([r,i])=>i.enabled).map(async([r,i])=>{let o={name:r,title:i.title,description:i.description,inputSchema:i.inputSchema?await E2(i.inputSchema,"input"):{type:"object",properties:{}}};return i.outputSchema&&(o.outputSchema=await E2(i.outputSchema,"output")),i.annotations&&(o.annotations=i.annotations),i._meta&&(o._meta=i._meta),o}))}))}async sendToolListChanged(e={}){this._assertInitialized("sendToolListChanged"),await this.notification({method:"notifications/tools/list_changed",params:e})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler("toolinput")}set ontoolinput(e){this.setEventHandler("toolinput",e)}get ontoolinputpartial(){return this.getEventHandler("toolinputpartial")}set ontoolinputpartial(e){this.setEventHandler("toolinputpartial",e)}get ontoolresult(){return this.getEventHandler("toolresult")}set ontoolresult(e){this.setEventHandler("toolresult",e)}get ontoolcancelled(){return this.getEventHandler("toolcancelled")}set ontoolcancelled(e){this.setEventHandler("toolcancelled",e)}get onhostcontextchanged(){return this.getEventHandler("hostcontextchanged")}set onhostcontextchanged(e){this.setEventHandler("hostcontextchanged",e)}_onteardown;get onteardown(){return this._onteardown}set onteardown(e){this.warnIfRequestHandlerReplaced("onteardown",this._onteardown,e),this._onteardown=e,this.replaceRequestHandler("ui/resource-teardown",{params:$5.shape.params,result:A5},(n,r)=>{if(!this._onteardown)throw Error("No onteardown handler set");return this._onteardown(n,r)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler("tools/call",(n,r)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(n.params,r)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(e){this.warnIfRequestHandlerReplaced("onlisttools",this._onlisttools,e),this._onlisttools=e,this.replaceRequestHandler("tools/list",(n,r)=>{if(!this._onlisttools)throw Error("No onlisttools handler set");return this._onlisttools(n.params,r)})}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${e})`);break}}assertRequestHandlerCapability(e){switch(e){case"tools/call":case"tools/list":if(!this._appCapabilities.tools)throw Error(`Client does not support tool capability (required for ${e})`);return;default:return}}assertNotificationCapability(e){}async callServerTool(e,n){if(this._assertInitialized("callServerTool"),typeof e=="string")throw Error(`callServerTool() expects an object as its first argument, but received a string ("${e}"). Did you mean: callServerTool({ name: "${e}", arguments: { ... } })?`);return await this.request({method:"tools/call",params:e},{onprogress:()=>{},resetTimeoutOnProgress:!0,...n})}async readServerResource(e,n){return this._assertInitialized("readServerResource"),await this.request({method:"resources/read",params:e},n)}async listServerResources(e,n){return this._assertInitialized("listServerResources"),await this.request({method:"resources/list",params:e},n)}async createSamplingMessage(e,n){return this._assertInitialized("createSamplingMessage"),await this.request({method:"sampling/createMessage",params:e},n)}sendMessage(e,n){return this._assertInitialized("sendMessage"),this.request({method:"ui/message",params:e},b5,n)}sendLog(e){return this.notification({method:"notifications/message",params:e})}updateModelContext(e,n){return this._assertInitialized("updateModelContext"),this.request({method:"ui/update-model-context",params:e},_a,n)}openLink(e,n){return this._assertInitialized("openLink"),this.request({method:"ui/open-link",params:e},g5,n)}sendOpenLink=this.openLink;downloadFile(e,n){return this._assertInitialized("downloadFile"),this.request({method:"ui/download-file",params:e},v5,n)}requestTeardown(e={}){return this.notification({method:"ui/notifications/request-teardown",params:e})}requestDisplayMode(e,n){return this._assertInitialized("requestDisplayMode"),this.request({method:"ui/request-display-mode",params:e},z5,n)}sendSizeChanged(e){return this.notification({method:"ui/notifications/size-changed",params:e})}setupSizeChangedNotifications(){let e=!1,n=0,r=0,i=()=>{e||(e=!0,requestAnimationFrame(()=>{e=!1;let a=document.documentElement,s=a.style.height;a.style.height="max-content";let l=Math.ceil(a.getBoundingClientRect().height);a.style.height=s;let c=Math.ceil(window.innerWidth);(c!==n||l!==r)&&(n=c,r=l,this.sendSizeChanged({width:c,height:l}))}))};i();let o=new ResizeObserver(i);return o.observe(document.documentElement),o.observe(document.body),()=>o.disconnect()}async connect(e=new $m(window.parent,window.parent),n){if(this.transport)throw Error("App is already connected. Call close() before connecting again.");this._initializedSent=!1;try{await super.connect(e);let r=await this.request({method:"ui/initialize",params:{appCapabilities:this._appCapabilities,appInfo:this._appInfo,protocolVersion:d5}},I5,n);if(r===void 0)throw Error(`Server sent invalid initialize result: ${r}`);this._hostCapabilities=r.hostCapabilities,this._hostInfo=r.hostInfo,this._hostContext=r.hostContext,await this.notification({method:"ui/notifications/initialized"}),this._initializedSent=!0,this.options?.autoResize&&this.setupSizeChangedNotifications()}catch(r){throw this.close(),r}}};var gt={name:"pdf",version:"0.2.1",title:{en:"PDF","zh-CN":"PDF"},kinds:["pdf"]};var R2=gt.version,C2=gt.name,c7=gt.name,u7=`ui://${gt.name}/panel.html`,Rz=`ui://${gt.name}/assets/`,I2=`ui://${gt.name}/file/`;var tr=gt.kinds,Tm=100*1024*1024,d7=512*1024*1024,Cz=4*1024*1024,h7=24*1024,Em=class extends Error{constructor(n,r){super(r);this.code=n;this.name="OfficeError"}};function zm(t){let e=t.toLowerCase().match(/\.([a-z]+)$/)?.[1];return tr.includes(e??"")?e:null}var N5={en:{sep:", ",and:" and ",or:" or "},"zh-CN":{sep:"\u3001",and:"\u548C",or:"\u6216"}};function Ci(t,e="en",n="and"){let r=N5[e];if(t.length<2)return t.join("");let i=t[t.length-1],o=e==="zh-CN"&&/^[\x20-\x7e]/.test(i)?` ${r[n]} `:r[n];return`${t.slice(0,-1).join(r.sep)}${o}${i}`}function js(t="en",e="and"){return Ci(tr.map(n=>`.${n}`),t,e)}var zr=(t,e)=>new Em("invalid_anchor",`Cannot read location "${t}". ${e}`),kr={docx:"Use p:N, p:N-M, t:N or t:N/rRcC.",pptx:"Use slide:N, slide:N-M or slide:N/shape:ID.",pdf:"Use page:N or page:N-M.",xlsx:"Use Sheet, Sheet!A1 or Sheet!A1:C9 (quote names with spaces: 'My sheet'!A1)."};function Iz(t,e,n){if(!e)throw zr(t,kr[n]);let r=Number(e[1]),i=e[2]===void 0?r:Number(e[2]);if(!(r>=1)||!(i>=r)||i>1e6)throw zr(t,kr[n]);return{from:r,to:i}}function O2(t){let e=/^\$?([A-Za-z]{1,3})\$?(\d{1,7})$/.exec(t);if(!e)return null;let n=0;for(let i of e[1].toUpperCase())n=n*26+(i.charCodeAt(0)-64);let r=Number(e[2]);return r<1||r>1048576||n>16384?null:{row:r,col:n}}function M5(t){let e,n;if(t.startsWith("'")){let s=1;for(e="";s<t.length;s++)if(t[s]==="'")if(t[s+1]==="'")e+="'",s++;else break;else e+=t[s];if(s>=t.length||(n=t.slice(s+1),n&&!n.startsWith("!")))throw zr(t,kr.xlsx);n=n.slice(1)}else{let s=t.lastIndexOf("!");e=s<0?t:t.slice(0,s),n=s<0?"":t.slice(s+1)}if(!e||e.length>64)throw zr(t,kr.xlsx);if(!n)return{kind:"xlsx",sheet:e};let[r,i=r]=n.split(":"),o=O2(r),a=O2(i);if(!o||!a)throw zr(t,kr.xlsx);return{kind:"xlsx",sheet:e,range:{start:{row:Math.min(o.row,a.row),col:Math.min(o.col,a.col)},end:{row:Math.max(o.row,a.row),col:Math.max(o.col,a.col)}}}}function jy(t,e){let n=e.trim();if(!n||n.length>300)throw zr(e,kr[t]);switch(t){case"docx":{let r=/^t:(\d+)(?:\/r(\d+)c(\d+))?$/i.exec(n);if(r){let i=Number(r[1]);if(i<1)throw zr(n,kr.docx);if(r[2]===void 0)return{kind:t,type:"table",table:i};let o={row:Number(r[2]),col:Number(r[3])};if(o.row<1||o.col<1)throw zr(n,kr.docx);return{kind:t,type:"table",table:i,cell:o}}return{kind:t,type:"paragraph",...Iz(n,/^p:(\d+)(?:-(?:p:)?(\d+))?$/i.exec(n),t)}}case"pptx":{let r=/^slide:(\d+)\/shape:([\w-]{1,32})$/i.exec(n);if(r){let i=Number(r[1]);if(i<1)throw zr(n,kr.pptx);return{kind:t,from:i,to:i,shape:r[2]}}return{kind:t,...Iz(n,/^slide:(\d+)(?:-(?:slide:)?(\d+))?$/i.exec(n),t)}}case"pdf":return{kind:t,...Iz(n,/^page:(\d+)(?:-(?:page:)?(\d+))?$/i.exec(n),t)};case"xlsx":return M5(n)}}function P2(t){let e=/^(.*?\.(?:docx|xlsx|pptx|pdf))(?:#(.*))?$/i.exec(t.trim());if(!e)throw new Em("invalid_anchor",`"${t}" is not a document anchor. Use <path>.docx|.xlsx|.pptx|.pdf optionally followed by #<location>.`);return{path:e[1],at:e[2]?.trim()?e[2].trim():null}}function km(t,e){return e?`${t}#${e}`:t}var N2=t=>t>=55296&&t<=56319,M2=t=>t>=56320&&t<=57343;function D2(t,e,n=t.length){let r=Math.max(0,Math.min(e,t.length)),i=Math.max(r,Math.min(n,t.length));return r>0&&M2(t.charCodeAt(r))&&N2(t.charCodeAt(r-1))&&r--,i<t.length&&M2(t.charCodeAt(i))&&N2(t.charCodeAt(i-1))&&i--,t.slice(r,i)}var D5=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,qy=t=>t.replace(D5,"\uFFFD");function Uy(t){return typeof t=="string"?qy(t):Array.isArray(t)?t.map(e=>Uy(e)):t&&typeof t=="object"&&Object.getPrototypeOf(t)===Object.prototype?Object.fromEntries(Object.entries(t).map(([e,n])=>[e,Uy(n)])):t}var L2=`${gt.name}:windows:v1`,L5=128;function j2(t){try{let e=JSON.parse(t.getItem(L2)??"{}");return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function Oz(t,e){let n=j2(t)[e];return!n||typeof n!="object"?{}:{...typeof n.path=="string"?{path:n.path}:{},...Array.isArray(n.recent)?{recent:n.recent.filter(r=>typeof r?.path=="string"&&zm(r.path)===r.kind)}:{}}}function U2(t,e,n){try{let r=j2(t),i={...Oz(t,e),...n};delete r[e],r[e]=i;for(let o of Object.keys(r).slice(0,-L5))delete r[o];t.setItem(L2,JSON.stringify(r))}catch{}}var au=t=>t.filter(([e])=>tr.includes(e)).map(([,e])=>e),j5={docx:"Word",xlsx:"Excel",pptx:"PowerPoint",pdf:"PDF"},q2=tr.filter(t=>t!=="pdf"),F2=[...q2.length===3?["Office"]:q2.map(t=>j5[t]),...tr.includes("pdf")?["PDF"]:[]],Rm=gt.title.en,w7=(()=>{let t=Ci(F2,"en","or");return`${/^[AEIOU]/.test(t)?"an":"a"} ${t} file`})(),x7=`${Ci(F2)} files`,$7=js("en","or"),A7=au([["docx","report.docx#p:12"],["xlsx","model.xlsx#Revenue!B2:F9"],["pptx","deck.pptx#slide:3"],["pdf","paper.pdf#page:5"]]).join(", "),E7=au([["docx","p:12"],["pptx","slide:3"],["pdf","page:5"],["xlsx","Revenue!B2:F9"]]).join(", "),T7=au([["docx","Word paragraphs and tables (markdown)"],["xlsx","spreadsheet cells as a grid with formulas"],["pptx","slides with their shapes and speaker notes"],["pdf","PDF page text"]]).join(", "),z7=Ci(au([["docx","paragraph"],["xlsx","cell range"],["pptx","slide"],["pptx","shape"],["pdf","page"]]),"en","or"),k7=Ci(au([["pdf","PDF pages"],["docx","long paragraphs"]]))||"long passages",B2=Ci(au([["pptx","deck.pptx#slide:3"],["pdf","paper.pdf#page:2"],["docx","report.docx#p:12"],["xlsx","model.xlsx#Revenue!A1:H30"]]),"en","or");var H2=[{name:"capture_view",title:`Capture ${Rm} view`,description:`Take a picture of a rendered document location in the ${Rm} panel so you can see layout, charts, images and formatting that text extraction misses. Pass an anchor such as ${B2} (the document must be open in the panel; call open_document first), or omit it to capture what the user currently sees.`,inputSchema:{type:"object",properties:{anchor:{type:"string",maxLength:1200,description:"Location to capture; defaults to the visible view."},maxWidth:{type:"integer",minimum:320,maximum:2e3,description:"Maximum image width in pixels (default 1600)."}},additionalProperties:!1},annotations:{readOnlyHint:!0,idempotentHint:!0}}];function U5(){let t=crypto.randomUUID(),e=()=>n.getHostCapabilities()?.experimental?.["zcode/surface"]?.stateKey??t,n=new Ly({name:C2,version:R2},{tools:{listChanged:!0},availableDisplayModes:["inline","fullscreen"]},{autoResize:!1}),r=[],i=new Map,o=new Set,a,s=c=>void window.dispatchEvent(new Event(`office:${c}`));return n.ontoolresult=c=>{r.push(c),r.length>20&&r.shift(),s("toolresult")},n.onhostcontextchanged=()=>s("hostchange"),n.onlisttools=async()=>({tools:H2}),n.oncalltool=async(c,u)=>{if(!H2.some(d=>d.name===c.name))return{isError:!0,content:[{type:"text",text:`The ${Rm} page has no tool ${c.name}.`}]};try{let d=Date.now()+2e4;for(;!i.has(c.name)&&Date.now()<d;)await new Promise(m=>{let p=()=>(o.delete(p),m());o.add(p),setTimeout(p,500)});let h=i.get(c.name);if(!h)throw new Error(`The ${Rm} panel is still loading; try again in a moment.`);let f=u;return await h(c.arguments??{},f.mcpReq?.signal??f.signal)}catch(d){return{isError:!0,content:[{type:"text",text:d instanceof Error?d.message:String(d)}]}}},window.addEventListener("pagehide",()=>{n.callServerTool({name:"release_view",arguments:{viewId:e()}}).catch(()=>{})}),{app:n,get viewId(){return e()},ready:()=>a??=n.connect(new $m(window.parent,window.parent)).then(()=>s("hostchange")),readWindow(){let c=n.getHostCapabilities()?.experimental?.["zcode/surface"];if(!c?.stateKey)return{};try{return Oz(localStorage,c.stateKey)}catch{return{}}},saveWindow(c){let u=n.getHostCapabilities()?.experimental?.["zcode/surface"];if(u?.stateKey)try{U2(localStorage,u.stateKey,c)}catch{}},readDocument(){return this.readWindow().path??null},saveDocument(c){this.saveWindow({path:c})},takeResults:()=>r.splice(0,r.length),handleTool(c,u){i.set(c,u);for(let d of o)d()},get context(){return n.getHostContext()},get capabilities(){return n.getHostCapabilities()}}}function Ii(){return window.__officeHost??=U5()}async function Nz(t){let e=Ii();await e.ready();let r=(await e.app.readServerResource({uri:t})).contents[0];if(!r)throw new Error(`Empty resource ${t}`);return r}async function Fy(t){let e=await Nz(Rz+t);if(typeof e.text!="string")throw new Error(`Asset ${t} is not text`);return e.text}function V2(t){let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}var Pz=new Map;function Cm(t){let e=Pz.get(t);return e||(e=Nz(Rz+t).then(n=>{if(typeof n.blob!="string")throw new Error(`Asset ${t} is not binary`);return V2(n.blob)}),e.catch(()=>Pz.delete(t)),Pz.set(t,e)),e}async function Z2(t,e){let n=new Uint8Array(t.bytes),r=0;for(let i=0;i<t.chunks;i++){e?.throwIfAborted();let o=await Nz(`${I2}${t.token}/${i}`);if(typeof o.blob!="string")throw new Error("File chunk is not binary");let a=V2(o.blob);n.set(a,r),r+=a.byteLength}if(r!==t.bytes)throw new Error("The file changed while it was loading; reload it.");return n.buffer}var By=lt(Jn(),1);var Im=class extends Error{constructor(n,r){super(n);this.code=r;this.name="CallError"}};async function Rr(t,e={}){let n=Ii();await n.ready();let r=await n.app.callServerTool({name:t,arguments:e}),i=r.structuredContent,o=i?.error;if(r.isError||o){let a=r.content?.[0]?.text;throw new Im(o?.message??a??`${t} failed`,o?.code)}return i}var Us=t=>t.slice(t.lastIndexOf("/")+1),G2=t=>{let e=t.lastIndexOf("/");return e>0?t.slice(0,e):""};async function K2(t){let{id:e}=await Rr("begin_file_import",{name:t.name,size:t.size});try{for(let r=0;r<t.size;r+=Cz){let i=await new Promise((o,a)=>{let s=new FileReader;s.onload=()=>o(String(s.result).split(",")[1]),s.onerror=()=>a(s.error),s.readAsDataURL(t.slice(r,r+Cz))});await Rr("write_file_import",{id:e,offset:r,data:i})}return(await Rr("finish_file_import",{id:e})).path}catch(n){throw await Rr("cancel_file_import",{id:e}).catch(()=>{}),n}}var Hy=(t,e)=>t.length>e?`${D2(t,0,e-1)}\u2026`:t;function Mz(){return Ii().readWindow().recent??[]}function Y2(t){Ii().saveWindow({recent:t})}function Om(t,e,n){let r=e instanceof Im?e.code:e?.name==="PasswordException"?"password":void 0,[i,o]=r&&t.errors[r]||t.errors.generic,a=e instanceof Error?e.message:String(e);return{path:n,title:i,detail:o||a}}function X2(){let[,t]=(0,By.useState)(0);return(0,By.useEffect)(()=>{let e=()=>t(n=>n+1);return window.addEventListener("office:hostchange",e),()=>window.removeEventListener("office:hostchange",e)},[]),Ii().context}var q5={docx:"Word",xlsx:"Excel",pptx:"PowerPoint",pdf:"PDF"},W2=tr.map(t=>q5[t]),su=t=>tr.includes(t),J2=su("docx")||su("pdf"),Q2={en:`any ${Ci([...J2?["passage"]:[],...su("xlsx")?["cell"]:[],...su("pptx")?["slide"]:[]],"en","or")}`,zh:Ci([...J2?["\u6BB5\u843D"]:[],...su("xlsx")?["\u5355\u5143\u683C"]:[],...su("pptx")?["\u5E7B\u706F\u7247"]:[]],"zh-CN","or")},Dz=gt.title["zh-CN"].replace(/[\x20-\x7e]$/,"$& "),F5={title:gt.title.en,openTitle:"Open a document",openFile:"Open file",emptyTitle:`Open your ${Ci(W2)} file`,emptyDescription:`Read alongside your conversation and discuss ${Q2.en}.`,emptyCaption:`Choose a local file \xB7 ${js("en","or")}`,importing:"Importing\u2026",importTooLarge:`Choose a file no larger than ${Tm/1024/1024} MiB.`,recent:"Recent",switchDocument:"Switch document",pagesAndOutline:"Pages and outline",outlineOnly:"Outline",pages:"Pages",slides:"Slides",outline:"Outline",find:"Find",findPlaceholder:"Find in document",findCount:(t,e)=>`${t} of ${e}`,noResults:"No results",previousMatch:"Previous match (\u21E7Enter)",nextMatch:"Next match (Enter)",closeFind:"Close (Esc)",more:"More",fitWidth:"Fit width",fitPage:"Fit page",actualSize:"Actual size",reload:"Reload from disk",previousPage:"Previous page",nextPage:"Next page",pageNumber:"Page number",ofPages:t=>`of ${t}`,zoomIn:"Zoom in (\u2318+)",zoomOut:"Zoom out (\u2318\u2212)",fit:"Fit",addToChat:"Add to chat",addShort:"Add",addToChatHint:"Attach this to your next message (\u2318/Ctrl+Enter)",added:"Added to chat",ask:"Ask",askPlaceholder:"Ask about this\u2026",send:"Send",cancel:"Cancel",sendKey:"send",cancelKey:"cancel",copy:"Copy",copied:"Copied",agent:"Agent",agentOf:(t,e)=>`Agent \xB7 ${t} of ${e}`,nextTarget:"Next",moreOn:(t,e)=>t===1?`1 more on ${e}`:`${t} more`,close:"Close",changed:"This file changed on disk.",reloadShort:"Reload",dismiss:"Dismiss",openAnother:"Open another file",sidePanel:"Open in side panel",meta:{pdf:t=>t===1?"1 page":`${t} pages`,pptx:t=>t===1?"1 slide":`${t} slides`,xlsx:t=>t===1?"1 sheet":`${t} sheets`,docx:t=>""},errors:{generic:["Couldn\u2019t open this document",""],password:["This PDF is password protected",`${gt.title.en} can\u2019t open encrypted files yet.`],not_found:["This file no longer exists","It may have been moved or deleted."],file_too_large:["This file is too large to open",""],corrupt_file:["This file appears to be damaged",`${gt.title.en} couldn\u2019t read its contents.`],unsupported_type:["This kind of file isn\u2019t supported",`${gt.title.en} opens ${js()} files.`],path_outside_workspace:["This file is outside the workspace",""]},sendFailed:"The message was not sent.",contextFailed:"ZCode did not accept the reference.",where:{page:t=>`Page ${t}`,pages:(t,e)=>`Pages ${t}\u2013${e}`,pageLower:t=>`page ${t}`,slide:t=>`Slide ${t}`,slides:(t,e)=>`Slides ${t}\u2013${e}`,slideLower:t=>`slide ${t}`,shape:t=>`Slide ${t} \xB7 Shape`,paragraph:t=>`Paragraph ${t}`,paragraphs:(t,e)=>`Paragraphs ${t}\u2013${e}`,paragraphLower:t=>`paragraph ${t}`,table:t=>`Table ${t}`,cell:(t,e,n)=>`Table ${t} \xB7 R${e}C${n}`}},B5={title:gt.title["zh-CN"],openTitle:"\u6253\u5F00\u6587\u6863",openFile:"\u6253\u5F00\u6587\u4EF6",emptyTitle:`\u6253\u5F00\u4F60\u7684 ${Ci(W2,"zh-CN")} \u6587\u4EF6`,emptyDescription:`\u8FB9\u770B\u8FB9\u804A\uFF0C\u9009\u4E2D${Q2.zh}\u5373\u53EF\u5E26\u5165\u5BF9\u8BDD\u3002`,emptyCaption:`\u9009\u62E9\u672C\u5730\u6587\u4EF6 \xB7 ${js("zh-CN","or")}`,importing:"\u6B63\u5728\u5BFC\u5165\u2026",importTooLarge:`\u8BF7\u9009\u62E9\u4E0D\u8D85\u8FC7 ${Tm/1024/1024} MiB \u7684\u6587\u4EF6\u3002`,recent:"\u6700\u8FD1",switchDocument:"\u5207\u6362\u6587\u6863",pagesAndOutline:"\u9875\u9762\u4E0E\u76EE\u5F55",outlineOnly:"\u76EE\u5F55",pages:"\u9875\u9762",slides:"\u5E7B\u706F\u7247",outline:"\u76EE\u5F55",find:"\u67E5\u627E",findPlaceholder:"\u5728\u6587\u6863\u4E2D\u67E5\u627E",findCount:(t,e)=>`${t} / ${e}`,noResults:"\u65E0\u7ED3\u679C",previousMatch:"\u4E0A\u4E00\u4E2A\uFF08\u21E7Enter\uFF09",nextMatch:"\u4E0B\u4E00\u4E2A\uFF08Enter\uFF09",closeFind:"\u5173\u95ED\uFF08Esc\uFF09",more:"\u66F4\u591A",fitWidth:"\u9002\u5E94\u5BBD\u5EA6",fitPage:"\u9002\u5E94\u9875\u9762",actualSize:"\u5B9E\u9645\u5927\u5C0F",reload:"\u4ECE\u78C1\u76D8\u91CD\u65B0\u52A0\u8F7D",previousPage:"\u4E0A\u4E00\u9875",nextPage:"\u4E0B\u4E00\u9875",pageNumber:"\u9875\u7801",ofPages:t=>`/ ${t}`,zoomIn:"\u653E\u5927\uFF08\u2318+\uFF09",zoomOut:"\u7F29\u5C0F\uFF08\u2318\u2212\uFF09",fit:"\u9002\u5E94",addToChat:"\u6DFB\u52A0\u5230\u5BF9\u8BDD",addShort:"\u6DFB\u52A0",addToChatHint:"\u9644\u52A0\u5230\u4E0B\u4E00\u6761\u6D88\u606F\uFF08\u2318/Ctrl+Enter\uFF09",added:"\u5DF2\u6DFB\u52A0\u5230\u5BF9\u8BDD",ask:"\u63D0\u95EE",askPlaceholder:"\u5C31\u8FD9\u91CC\u63D0\u95EE\u2026",send:"\u53D1\u9001",cancel:"\u53D6\u6D88",sendKey:"\u53D1\u9001",cancelKey:"\u53D6\u6D88",copy:"\u590D\u5236",copied:"\u5DF2\u590D\u5236",agent:"Agent",agentOf:(t,e)=>`Agent \xB7 \u7B2C ${t} \u5904\uFF0C\u5171 ${e} \u5904`,nextTarget:"\u4E0B\u4E00\u5904",moreOn:(t,e)=>t===1?`${e}\u8FD8\u6709 1 \u5904`:`\u8FD8\u6709 ${t} \u5904`,close:"\u5173\u95ED",changed:"\u6587\u4EF6\u5DF2\u5728\u78C1\u76D8\u4E0A\u66F4\u6539\u3002",reloadShort:"\u91CD\u65B0\u52A0\u8F7D",dismiss:"\u5FFD\u7565",openAnother:"\u6253\u5F00\u5176\u4ED6\u6587\u4EF6",sidePanel:"\u5728\u4FA7\u680F\u6253\u5F00",meta:{pdf:t=>`${t} \u9875`,pptx:t=>`${t} \u5F20\u5E7B\u706F\u7247`,xlsx:t=>`${t} \u4E2A\u5DE5\u4F5C\u8868`,docx:()=>""},errors:{generic:["\u65E0\u6CD5\u6253\u5F00\u8BE5\u6587\u6863",""],password:["\u8BE5 PDF \u53D7\u5BC6\u7801\u4FDD\u62A4",`${Dz}\u6682\u4E0D\u652F\u6301\u6253\u5F00\u52A0\u5BC6\u6587\u4EF6\u3002`],not_found:["\u8BE5\u6587\u4EF6\u5DF2\u4E0D\u5B58\u5728","\u5B83\u53EF\u80FD\u5DF2\u88AB\u79FB\u52A8\u6216\u5220\u9664\u3002"],file_too_large:["\u6587\u4EF6\u592A\u5927\uFF0C\u65E0\u6CD5\u6253\u5F00",""],corrupt_file:["\u8BE5\u6587\u4EF6\u4F3C\u4E4E\u5DF2\u635F\u574F",`${Dz}\u65E0\u6CD5\u8BFB\u53D6\u5176\u5185\u5BB9\u3002`],unsupported_type:["\u4E0D\u652F\u6301\u8FD9\u79CD\u6587\u4EF6",`${Dz}\u53EF\u4EE5\u6253\u5F00 ${js("zh-CN")} \u6587\u4EF6\u3002`],path_outside_workspace:["\u8BE5\u6587\u4EF6\u4E0D\u5728\u5DE5\u4F5C\u533A\u5185",""]},sendFailed:"\u6D88\u606F\u672A\u53D1\u9001\u3002",contextFailed:"ZCode \u672A\u63A5\u53D7\u8BE5\u5F15\u7528\u3002",where:{page:t=>`\u7B2C ${t} \u9875`,pages:(t,e)=>`\u7B2C ${t}\u2013${e} \u9875`,pageLower:t=>`\u7B2C ${t} \u9875`,slide:t=>`\u7B2C ${t} \u5F20\u5E7B\u706F\u7247`,slides:(t,e)=>`\u7B2C ${t}\u2013${e} \u5F20\u5E7B\u706F\u7247`,slideLower:t=>`\u7B2C ${t} \u5F20\u5E7B\u706F\u7247`,shape:t=>`\u7B2C ${t} \u5F20\u5E7B\u706F\u7247 \xB7 \u5F62\u72B6`,paragraph:t=>`\u7B2C ${t} \u6BB5`,paragraphs:(t,e)=>`\u7B2C ${t}\u2013${e} \u6BB5`,paragraphLower:t=>`\u7B2C ${t} \u6BB5`,table:t=>`\u8868\u683C ${t}`,cell:(t,e,n)=>`\u8868\u683C ${t} \xB7 R${e}C${n}`}},ej=t=>t?.toLowerCase().startsWith("zh")?B5:F5;function Vy(t,e,n=!1){let r=e.where,i;if(i=/^page:(\d+)(?:-(\d+))?$/.exec(t))return i[2]?r.pages(i[1],i[2]):n?r.pageLower(i[1]):r.page(i[1]);if(i=/^slide:(\d+)\/shape:/.exec(t))return r.shape(i[1]);if(i=/^slide:(\d+)(?:-(\d+))?$/.exec(t))return i[2]?r.slides(i[1],i[2]):n?r.slideLower(i[1]):r.slide(i[1]);if(i=/^p:(\d+)(?:-(\d+))?$/.exec(t))return i[2]?r.paragraphs(i[1],i[2]):n?r.paragraphLower(i[1]):r.paragraph(i[1]);if(i=/^t:(\d+)\/r(\d+)c(\d+)$/.exec(t))return r.cell(i[1],i[2],i[3]);if(i=/^t:(\d+)$/.exec(t))return r.table(i[1]);let o=t.lastIndexOf("!");return o>0?`${t.slice(0,o).replace(/^'(.*)'$/,"$1").replace(/''/g,"'")} \xB7 ${t.slice(o+1)}`:t.replace(/^'(.*)'$/,"$1")}var Lz=lt(An(),1),Z5={search:'<circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/>',x:'<path d="M18 6 6 18"/><path d="m6 6 12 12"/>',"chevron-up":'<path d="m18 15-6-6-6 6"/>',"chevron-down":'<path d="m6 9 6 6 6-6"/>',minus:'<path d="M5 12h14"/>',plus:'<path d="M5 12h14"/><path d="M12 5v14"/>',ellipsis:'<circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/><circle cx="5" cy="12" r="1"/>',"panel-left":'<rect width="18" height="18" x="3" y="3" rx="2"/><path d="M9 3v18"/>',"file-text":'<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="M10 9H8"/><path d="M16 13H8"/><path d="M16 17H8"/>',copy:'<rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/>',"message-square-plus":'<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/><path d="M12 7v6"/><path d="M9 10h6"/>',"message-circle-question":'<path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z"/><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/><path d="M12 17h.01"/>',check:'<path d="M20 6 9 17l-5-5"/>',"rotate-cw":'<path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/>',"arrow-down":'<path d="M12 5v14"/><path d="m19 12-7 7-7-7"/>',"arrow-up":'<path d="m5 12 7-7 7 7"/><path d="M12 19V5"/>',"folder-open":'<path d="m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"/>',"maximize-2":'<polyline points="15 3 21 3 21 9"/><polyline points="9 21 3 21 3 15"/><line x1="21" x2="14" y1="3" y2="10"/><line x1="3" x2="10" y1="21" y2="14"/>'};function Fe({name:t,size:e=14,className:n}){return(0,Lz.jsx)("svg",{className:`icon${n?` ${n}`:""}`,width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",dangerouslySetInnerHTML:{__html:Z5[t]}})}var G5={pdf:"PDF",docx:"W",xlsx:"X",pptx:"P"};function rj({kind:t}){return(0,Lz.jsx)("span",{className:`filetype ${t}`,"aria-hidden":"true",children:G5[t]})}var _o=lt(Jn(),1);var _e=lt(An(),1);function K5({handle:t,page:e,width:n,ratio:r,current:i,onPick:o,root:a}){let s=(0,_o.useRef)(null);return(0,_o.useEffect)(()=>{let l=s.current;if(!l||!t.thumbnail)return;let c=!1,u=new IntersectionObserver(d=>{c||!d.some(h=>h.isIntersecting)||(c=!0,u.disconnect(),t.thumbnail(e,n).then(h=>{l.replaceChildren(h),l.style.height=""},()=>{}))},{root:a.current,rootMargin:"300px 0px"});return u.observe(l),()=>u.disconnect()},[t,e,n,a]),(0,_e.jsxs)("button",{type:"button",className:`thumb${i?" on":""}`,"aria-current":i?"page":void 0,onClick:()=>o(e),"data-page":e,children:[(0,_e.jsx)("div",{ref:s,className:"mini",style:{width:n,height:Math.round(n*r)}}),(0,_e.jsx)("span",{children:e})]})}var oj=t=>/^(?:page|slide):(\d+)/.exec(t)?.[1]??"";function aj({t,info:e,handle:n,page:r,tab:i,docked:o,onTab:a,onPage:s,onOutline:l}){let c=(0,_o.useRef)(null),u=!!(n?.thumbnail&&r),d=e.outline.length>0,h=u&&(i==="pages"||!d)?"pages":"outline",f=e.kind==="pptx"?9/16:1.294;(0,_o.useEffect)(()=>{let p=c.current?.querySelector("[aria-current=page]");p&&c.current&&(c.current.scrollTop=p.offsetTop-c.current.clientHeight/3)},[h]);let m=(()=>{if(!r)return-1;let p=-1;return e.outline.forEach((y,g)=>{let v=Number(oj(y.at));v&&v<=r.current&&(p=g)}),p})();return(0,_e.jsxs)("nav",{className:`drawer${o?" docked":""}`,"aria-label":t.pagesAndOutline,children:[u&&d?(0,_e.jsxs)("div",{className:"seg",role:"tablist",children:[(0,_e.jsx)("button",{type:"button",role:"tab","aria-selected":h==="pages",className:h==="pages"?"on":"",onClick:()=>a("pages"),children:e.kind==="pptx"?t.slides:t.pages}),(0,_e.jsx)("button",{type:"button",role:"tab","aria-selected":h==="outline",className:h==="outline"?"on":"",onClick:()=>a("outline"),children:t.outline})]}):null,(0,_e.jsx)("div",{ref:c,className:h==="pages"?"thumbs":"outline",children:h==="pages"&&n&&r?Array.from({length:r.count},(p,y)=>(0,_e.jsx)(K5,{handle:n,page:y+1,width:136,ratio:f,current:r.current===y+1,onPick:s,root:c},y)):e.outline.map((p,y)=>(0,_e.jsxs)("button",{type:"button",className:`oi level-${Math.min(3,Math.max(1,p.level))}${y===m?" on":""}`,"aria-current":y===m?"page":void 0,title:p.label,onClick:()=>l(p.at),children:[(0,_e.jsx)("span",{className:"label",children:p.label}),(0,_e.jsx)("span",{className:"n",children:oj(p.at)})]},`${p.at}-${y}`))})]})}function sj({t,onBrowse:e,importing:n}){return(0,_e.jsx)("div",{className:"empty",children:(0,_e.jsxs)("div",{className:"empty-content",children:[(0,_e.jsx)("h3",{children:t.emptyTitle}),(0,_e.jsx)("p",{className:"empty-description",children:t.emptyDescription}),(0,_e.jsxs)("button",{type:"button",className:"btn empty-open",onClick:e,disabled:n,children:[(0,_e.jsx)(Fe,{name:"folder-open",size:16}),n?t.importing:t.openFile]}),(0,_e.jsx)("p",{className:"empty-caption",children:t.emptyCaption})]})})}var Y5=["title","subtitle","line","line","short","heading","line","line","line","mid","figure"];function Gy({kind:t}){if(t==="xlsx")return(0,_e.jsx)("div",{className:"skeleton sheet","aria-busy":"true",children:Array.from({length:18},(n,r)=>(0,_e.jsx)("div",{className:"skel-row"},r))});let e=t==="pptx";return(0,_e.jsx)("div",{className:"skeleton","aria-busy":"true",children:[0,1].map(n=>(0,_e.jsxs)("div",{className:`skelpage${e?" slide":""}`,children:[n===0&&!e?Y5.map((r,i)=>(0,_e.jsx)("div",{className:`skel ${r}`},i)):null,n===0&&e?(0,_e.jsxs)(_e.Fragment,{children:[(0,_e.jsx)("div",{className:"skel title left"}),(0,_e.jsx)("div",{className:"skel line"}),(0,_e.jsx)("div",{className:"skel mid"})]}):null]},n))})}function Ky({t,title:e,detail:n,onOpenAnother:r}){return(0,_e.jsxs)("div",{className:"failed",role:"alert",children:[(0,_e.jsx)(Fe,{name:"file-text",size:28,className:"subtlest"}),(0,_e.jsxs)("div",{children:[(0,_e.jsx)("h3",{children:e}),n?(0,_e.jsx)("p",{children:n}):null]}),(0,_e.jsx)("button",{type:"button",className:"btn secondary",onClick:r,children:t.openAnother})]})}function lj({t,onReload:e,onDismiss:n}){return(0,_e.jsxs)("div",{className:"banner",role:"status",children:[(0,_e.jsx)("span",{children:t.changed}),(0,_e.jsx)("button",{type:"button",className:"btn sm primary",onClick:e,children:t.reloadShort}),(0,_e.jsx)("button",{type:"button",className:"btn icon sm dim",title:t.dismiss,"aria-label":t.dismiss,onClick:n,children:(0,_e.jsx)(Fe,{name:"x"})})]})}function X5({inputRef:t,t:e,importing:n,onImporting:r,onOpen:i,onError:o}){return(0,_e.jsx)("input",{ref:t,type:"file",hidden:!0,accept:tr.map(a=>`.${a}`).join(","),disabled:n,onChange:async a=>{let s=a.currentTarget.files?.[0];if(a.currentTarget.value="",!!s){r(!0);try{if(s.size>Tm)throw new Error(e.importTooLarge);i(await K2(s))}catch(l){o(l,s.name)}finally{r(!1)}}}})}function cj(t,e,n){let r=(0,_o.useRef)(null),[i,o]=(0,_o.useState)(!1);return{importing:i,browse:()=>r.current?.click(),input:(0,_e.jsx)(X5,{inputRef:r,t,importing:i,onImporting:o,onOpen:e,onError:n})}}var mn=lt(An(),1);function uj({appRef:t,canvasRef:e,t:n,path:r,info:i,kind:o,showSkeleton:a,failure:s,nothing:l,onExpand:c,children:u}){return(0,mn.jsxs)("div",{ref:t,className:"app inline",children:[(0,mn.jsxs)("header",{className:"docbar",children:[(0,mn.jsxs)("div",{className:"doctitle static",title:r??void 0,children:[(0,mn.jsx)("span",{className:"name",children:r?Us(r):n.title}),i&&n.meta[i.kind](i.units)?(0,mn.jsx)("span",{className:"meta",children:n.meta[i.kind](i.units)}):null]}),(0,mn.jsx)("span",{className:"spacer"}),(0,mn.jsxs)("button",{type:"button",className:"btn sm",title:n.sidePanel,onClick:c,children:[(0,mn.jsx)(Fe,{name:"maximize-2",size:12}),n.sidePanel]})]}),(0,mn.jsx)("div",{className:"stage",children:(0,mn.jsxs)("div",{ref:e,className:"canvas",children:[u,a?(0,mn.jsx)(Gy,{kind:o}):null,s?(0,mn.jsx)(Ky,{t:n,title:s.title,detail:s.detail,onOpenAnother:c}):null,l?(0,mn.jsx)("div",{className:"failed muted",children:n.openTitle}):null,(0,mn.jsx)("button",{type:"button",className:"glance-cover","aria-label":n.sidePanel,onClick:c})]})})]})}var Vn=lt(Jn(),1);var Yy=lt(Jn(),1),qs=8;function jz(t,e,n){let r=(0,Yy.useRef)(null),{side:i,offset:o=8,dock:a=!1}=n;return(0,Yy.useLayoutEffect)(()=>{let s=r.current,l=t.current;if(!s||!l)return;let c=0,u=()=>{c=0;let m=l.getBoundingClientRect(),p=s.offsetWidth,y=s.offsetHeight,g=e?.()??null,v=(I,D,H,ge)=>{s.style.visibility="",s.style.left=`${Math.round(I)}px`,s.style.top=`${Math.round(D)}px`,s.dataset.side=H,s.style.setProperty("--tip",`${Math.round(Math.max(14,Math.min(p-14,ge-I)))}px`)};if(!g){a?v((m.width-p)/2,qs,"none",m.width/2):s.style.visibility="hidden";return}if(g.bottom<m.top+4||g.top>m.bottom-4){s.style.visibility="hidden";return}let S=(g.left+g.right)/2-m.left,_=Math.max(qs,Math.min(m.width-p-qs,S-p/2)),$=g.top-m.top-y-o,w=g.bottom-m.top+o,A=$>=qs,k=w+y<=m.height-qs;(i==="top"||!k)&&A?v(_,$,"top",S):k?v(_,w,"bottom",S):v(_,i==="top"?qs:m.height-y-qs,"none",S)},d=()=>{c||(c=requestAnimationFrame(u))};u(),l.addEventListener("scroll",d,{capture:!0,passive:!0});let h=new ResizeObserver(d);h.observe(l),h.observe(s);let f=setInterval(d,250);return()=>{l.removeEventListener("scroll",d,{capture:!0}),h.disconnect(),clearInterval(f),c&&cancelAnimationFrame(c)}},[t,e,i,o,a]),r}var X=lt(An(),1);function Uz({className:t,onClose:e,children:n,label:r}){let i=(0,Vn.useRef)(null);(0,Vn.useEffect)(()=>{let a=l=>{let c=l.target;!i.current?.contains(c)&&!c.closest?.("[data-menu-trigger]")&&e()},s=l=>{l.key==="Escape"&&(l.stopPropagation(),e())};return document.addEventListener("pointerdown",a,!0),document.addEventListener("keydown",s,!0),i.current?.querySelector("[role^=menuitem]")?.focus(),()=>{document.removeEventListener("pointerdown",a,!0),document.removeEventListener("keydown",s,!0)}},[e]);let o=a=>{if(a.key!=="ArrowDown"&&a.key!=="ArrowUp")return;a.preventDefault();let s=[...i.current?.querySelectorAll("[role^=menuitem]")??[]],l=s.indexOf(document.activeElement);s[(l+(a.key==="ArrowDown"?1:-1)+s.length)%s.length]?.focus()};return(0,X.jsx)("div",{ref:i,className:`menu ${t}`,role:"menu","aria-label":r,onKeyDown:o,children:n})}function $a({icon:t,checked:e,children:n,hint:r,onSelect:i}){return(0,X.jsxs)("button",{type:"button",role:e===void 0?"menuitem":"menuitemradio","aria-checked":e,className:"mi",onClick:i,children:[(0,X.jsx)("span",{className:"mi-icon",children:e?(0,X.jsx)(Fe,{name:"check",size:16}):t}),(0,X.jsx)("span",{className:"mi-label",children:n}),r?(0,X.jsx)("span",{className:"mi-hint",children:r}):null]})}function hj({t,query:e,total:n,index:r,onQuery:i,onStep:o,onClose:a}){let s=(0,Vn.useRef)(null);(0,Vn.useEffect)(()=>{s.current?.focus(),s.current?.select()},[]);let l=!e.trim()||n===null?"":n?t.findCount(r+1,n):t.noResults;return(0,X.jsxs)("div",{className:"docbar findbar",role:"search",children:[(0,X.jsxs)("label",{className:"findfield",children:[(0,X.jsx)(Fe,{name:"search",className:"muted"}),(0,X.jsx)("input",{ref:s,className:"find-input",type:"text","aria-label":t.find,placeholder:t.findPlaceholder,value:e,onChange:c=>i(c.target.value),onKeyDown:c=>{c.key==="Enter"?(c.preventDefault(),o(c.shiftKey?-1:1)):c.key==="Escape"&&(c.preventDefault(),c.stopPropagation(),a())}}),(0,X.jsx)("span",{className:"count","aria-live":"polite",children:l})]}),(0,X.jsx)("button",{type:"button",className:"btn icon dim",title:t.previousMatch,"aria-label":t.previousMatch,disabled:!n,onClick:()=>o(-1),children:(0,X.jsx)(Fe,{name:"chevron-up"})}),(0,X.jsx)("button",{type:"button",className:"btn icon dim",title:t.nextMatch,"aria-label":t.nextMatch,disabled:!n,onClick:()=>o(1),children:(0,X.jsx)(Fe,{name:"chevron-down"})}),(0,X.jsx)("button",{type:"button",className:"btn icon dim",title:t.closeFind,"aria-label":t.closeFind,onClick:a,children:(0,X.jsx)(Fe,{name:"x"})})]})}var J5=1500;function fj({t,frame:e,page:n,zoom:r,onPage:i,onZoom:o,onFit:a}){let s=(0,Vn.useRef)(null),[l,c]=(0,Vn.useState)(!0),[u,d]=(0,Vn.useState)(null),h=(0,Vn.useRef)(!1);(0,Vn.useEffect)(()=>{let m=e.current;if(!m)return;let p=0,y=()=>{clearTimeout(p),p=window.setTimeout(()=>{!h.current&&!s.current?.contains(document.activeElement)&&c(!1)},J5)},g=()=>{c(!0),y()},v=S=>{let _=m.getBoundingClientRect();S.clientY>_.bottom-80&&g()};return m.addEventListener("scroll",g,{capture:!0,passive:!0}),m.addEventListener("pointermove",v,{passive:!0}),y(),()=>{clearTimeout(p),m.removeEventListener("scroll",g,{capture:!0}),m.removeEventListener("pointermove",v)}},[e]);let f=()=>{let m=Number(u);d(null),Number.isInteger(m)&&m>=1&&i(Math.min(m,n.count))};return(0,X.jsxs)("div",{ref:s,className:`pill${l?"":" faded"}`,onPointerEnter:()=>{h.current=!0,c(!0)},onPointerLeave:()=>{h.current=!1},onFocus:()=>c(!0),children:[(0,X.jsx)("button",{type:"button",className:"btn icon sm dim",title:t.previousPage,"aria-label":t.previousPage,disabled:n.current<=1,onClick:()=>i(n.current-1),children:(0,X.jsx)(Fe,{name:"chevron-up"})}),(0,X.jsxs)("span",{className:"pg",children:[(0,X.jsx)("input",{className:"pgin","aria-label":t.pageNumber,inputMode:"numeric",style:{width:`${Math.max(2,String(n.count).length)+1.6}ch`},value:u??String(n.current),onFocus:m=>{d(String(n.current)),m.target.select()},onChange:m=>d(m.target.value.replace(/\D/g,"")),onBlur:()=>d(null),onKeyDown:m=>{m.key==="Enter"?(f(),m.currentTarget.blur()):m.key==="Escape"&&(m.stopPropagation(),d(null),m.currentTarget.blur())}}),(0,X.jsx)("span",{children:t.ofPages(n.count)})]}),(0,X.jsx)("button",{type:"button",className:"btn icon sm dim",title:t.nextPage,"aria-label":t.nextPage,disabled:n.current>=n.count,onClick:()=>i(n.current+1),children:(0,X.jsx)(Fe,{name:"chevron-down"})}),r?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)("span",{className:"vsep"}),(0,X.jsx)("button",{type:"button",className:"btn icon sm dim",title:t.zoomOut,"aria-label":t.zoomOut,disabled:r.mode!=="width"&&r.percent<=25,onClick:()=>o(-1),children:(0,X.jsx)(Fe,{name:"minus"})}),(0,X.jsx)("button",{type:"button",className:"zoom",title:t.fitWidth,onClick:a,children:r.mode==="width"?t.fit:`${r.percent}%`}),(0,X.jsx)("button",{type:"button",className:"btn icon sm dim",title:t.zoomIn,"aria-label":t.zoomIn,disabled:r.mode!=="width"&&r.percent>=400,onClick:()=>o(1),children:(0,X.jsx)(Fe,{name:"plus"})})]}):null]})}var dj=t=>{t.target.closest("textarea")||t.preventDefault()};function mj({t,frame:e,locate:n,text:r,label:i,quote:o,short:a,mode:s,canAsk:l,copied:c,onAdd:u,onAsk:d,onCopy:h,onCancelAsk:f,onSend:m}){let p=s==="ask",y=jz(e,n,{side:p?"bottom":"top",dock:!0}),[g,v]=(0,Vn.useState)(""),[S,_]=(0,Vn.useState)(!1),$=async()=>{if(!g.trim()||S)return;_(!0);let w=await m(g.trim());_(!1),w&&v("")};return p?(0,X.jsxs)("div",{ref:y,className:"pop ask",role:"dialog","aria-label":t.ask,onMouseDown:dj,children:[(0,X.jsxs)("div",{className:"ctx",children:[(0,X.jsx)("span",{className:"where",children:i}),o?(0,X.jsxs)("span",{className:"q",children:["\u201C",o,"\u201D"]}):null]}),(0,X.jsx)("textarea",{autoFocus:!0,className:"textarea",rows:2,"aria-label":t.askPlaceholder,placeholder:t.askPlaceholder,value:g,onChange:w=>v(w.target.value),onKeyDown:w=>{w.key==="Enter"&&!w.shiftKey&&!w.nativeEvent.isComposing?(w.preventDefault(),$()):w.key==="Escape"&&(w.preventDefault(),w.stopPropagation(),f())}}),(0,X.jsxs)("div",{className:"row",children:[(0,X.jsxs)("span",{className:"hint",children:[(0,X.jsx)("kbd",{children:"\u21B5"})," ",t.sendKey]}),(0,X.jsx)("button",{type:"button",className:"btn sm",onClick:f,children:t.cancel}),(0,X.jsx)("button",{type:"button",className:"btn sm primary",disabled:!g.trim()||S,onClick:()=>void $(),children:t.send})]})]}):(0,X.jsxs)("div",{ref:y,className:"pop bar",role:"toolbar","aria-label":i,onMouseDown:dj,children:[r?null:(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)("span",{className:"where",children:i}),(0,X.jsx)("span",{className:"vsep"})]}),(0,X.jsx)("button",{type:"button",className:"btn lg",title:t.addToChatHint,onClick:u,disabled:s==="added",children:s==="added"?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(Fe,{name:"check",size:16,className:"ok"}),t.added]}):(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(Fe,{name:"message-square-plus",size:16}),a?t.addShort:t.addToChat]})}),l?(0,X.jsxs)("button",{type:"button",className:"btn lg",onClick:d,children:[(0,X.jsx)(Fe,{name:"message-circle-question",size:16}),t.ask]}):null,r?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)("span",{className:"vsep"}),(0,X.jsx)("button",{type:"button",className:"btn icon lg dim",title:c?t.copied:t.copy,"aria-label":c?t.copied:t.copy,onClick:h,children:(0,X.jsx)(Fe,{name:c?"check":"copy"})})]}):null]})}function pj({t,frame:e,locate:n,note:r,index:i,total:o,onNext:a,onClose:s}){let l=jz(e,n,{side:"bottom",offset:6,dock:!0});return(0,X.jsxs)("div",{ref:l,className:"callout",role:"note",children:[(0,X.jsxs)("div",{className:"body",children:[(0,X.jsxs)("div",{className:"who",children:[(0,X.jsx)("span",{className:"dot"}),o>1?t.agentOf(i+1,o):t.agent]}),r?(0,X.jsx)("div",{className:"text",children:r}):null]}),o>1?(0,X.jsx)("button",{type:"button",className:"btn icon sm dim",title:t.nextTarget,"aria-label":t.nextTarget,onClick:a,children:(0,X.jsx)(Fe,{name:"chevron-down"})}):null,(0,X.jsx)("button",{type:"button",className:"btn icon sm dim",title:t.close,"aria-label":t.close,onClick:s,children:(0,X.jsx)(Fe,{name:"x"})})]})}function gj({text:t,down:e,raised:n,onClick:r}){return(0,X.jsxs)("button",{type:"button",className:`chip offscreen${n?" raised":""}`,onClick:r,children:[(0,X.jsx)("span",{className:"dot"}),t,(0,X.jsx)(Fe,{name:e?"arrow-down":"arrow-up",size:12})]})}function vj(t,e){return t.moreOn(e.length,Vy(e[0],t,!0))}var At=lt(An(),1);function bj({t,recent:e,currentPath:n,onOpen:r,onBrowse:i,onClose:o}){return(0,At.jsxs)(Uz,{className:"switcher",label:t.switchDocument,onClose:o,children:[e.length?(0,At.jsx)("div",{className:"mlabel",children:t.recent}):null,e.map(a=>(0,At.jsx)($a,{icon:(0,At.jsx)(rj,{kind:a.kind}),hint:a.path===n?(0,At.jsx)(Fe,{name:"check",size:16}):Us(G2(a.path)),onSelect:()=>a.path===n?o():r(a.path),children:Us(a.path)},a.path)),e.length?(0,At.jsx)("div",{className:"msep"}):null,(0,At.jsx)($a,{icon:(0,At.jsx)(Fe,{name:"folder-open",size:16}),onSelect:i,children:t.openFile})]})}function yj({t,zoomable:e,zoomMode:n,onFit:r,onFind:i,onReload:o,onClose:a}){return(0,At.jsxs)(Uz,{className:"more",label:t.more,onClose:a,children:[e?(0,At.jsxs)(At.Fragment,{children:[(0,At.jsx)($a,{checked:n==="width",onSelect:()=>r("width"),children:t.fitWidth}),(0,At.jsx)($a,{checked:n==="page",onSelect:()=>r("page"),children:t.fitPage}),(0,At.jsx)($a,{checked:n==="actual",hint:"100%",onSelect:()=>r("actual"),children:t.actualSize}),(0,At.jsx)("div",{className:"msep"})]}):null,(0,At.jsx)($a,{icon:(0,At.jsx)(Fe,{name:"search",size:16}),hint:"\u2318F",onSelect:i,children:t.find}),(0,At.jsx)($a,{icon:(0,At.jsx)(Fe,{name:"rotate-cw",size:16}),onSelect:o,children:t.reload})]})}var nr=lt(Jn(),1),Pm={open:!1,query:"",total:null,index:-1};function Sj({viewer:t,docRef:e,ready:n,onOpen:r}){let[i,o]=(0,nr.useState)(Pm),a=(0,nr.useRef)(0),s=(0,nr.useCallback)(()=>{e.current&&(r(),o(d=>({...d,open:!0})),requestAnimationFrame(()=>{let d=document.querySelector(".findbar .find-input");d?.focus(),d?.select()}))},[e,r]),l=(0,nr.useCallback)(()=>{a.current++,t.current?.clearFind(),o(Pm)},[t]),c=(0,nr.useCallback)(d=>{o(h=>({...h,query:d,total:d.trim()?h.total:null}))},[]);(0,nr.useEffect)(()=>{if(!i.open||!n)return;let d=++a.current,h=setTimeout(async()=>{let f=t.current;if(!f)return;let m=await f.find(i.query).catch(()=>0);d===a.current&&(o(p=>({...p,total:m,index:m?0:-1})),m&&f.findGo(0))},200);return()=>clearTimeout(h)},[i.open,i.query,n,t]);let u=(0,nr.useCallback)(d=>{if(!i.total)return;let h=(i.index+d+i.total)%i.total;o(f=>({...f,index:h})),t.current?.findGo(h)},[i.total,i.index,t]);return{find:i,setFind:o,openFind:s,closeFind:l,queryFind:c,stepFind:u}}var _j=lt(Jn(),1);function wj(t,e){(0,_j.useEffect)(()=>{Ii().handleTool("capture_view",async r=>{let i=t.current;if(!i||!e.current)throw new Error(`No document is open in the ${gt.title.en} panel. Call open_document first.`);let o=null;if(typeof r.anchor=="string"&&r.anchor.trim()){let l=P2(r.anchor);if(l.path.replace(/^\.\//,"")!==i.info.path)throw new Error(`The panel shows ${i.info.path}, not ${l.path}. Call open_document with that path first.`);o=l.at}let a=typeof r.maxWidth=="number"?Math.min(2e3,Math.max(320,r.maxWidth)):1600,s=await e.current.capture(o,a);return{content:[{type:"image",data:s.data,mimeType:"image/png"},{type:"text",text:`Captured ${km(i.info.path,s.at)} (${s.width}\xD7${s.height} px).`}]}})},[t,e])}var Xy=lt(Jn(),1);function xj(t,e){let[n,r]=(0,Xy.useState)(null);return(0,Xy.useEffect)(()=>{let i=t.current;if(!i||!e||e.targets.length<2){r(null);return}let o=0,a=()=>{o=0;let c=i.getBoundingClientRect(),u=[],d=[];e.targets.forEach((f,m)=>{if(m===e.index)return;let p=f.locate();p&&(p.top>c.bottom-8?u.push(m):p.bottom<c.top+8&&d.push(m))});let h=u.length?{indexes:u,down:!0}:d.length?{indexes:d,down:!1}:null;r(f=>JSON.stringify(f)===JSON.stringify(h)?f:h)},s=()=>{o||(o=requestAnimationFrame(a))};a(),i.addEventListener("scroll",s,{capture:!0,passive:!0});let l=setInterval(s,500);return()=>{i.removeEventListener("scroll",s,{capture:!0}),clearInterval(l),o&&cancelAnimationFrame(o)}},[e,t]),[n,r]}var $j=lt(Jn(),1);function Aj({docRef:t,viewer:e,picked:n,addReference:r,openFind:i,closeFind:o,clearSelection:a,paged:s,page:l,goToPage:c,drawer:u,setDrawer:d,docked:h,find:f,agent:m,setAgent:p}){(0,$j.useEffect)(()=>{let y=g=>{if(g.defaultPrevented)return;let v=g.metaKey||g.ctrlKey,S=g.target?.closest?.("input, textarea, [contenteditable]"),_=g.key.toLowerCase();if(v&&_==="f"&&t.current)g.preventDefault(),i();else if(v&&g.key==="Enter"&&n)g.preventDefault(),r();else if(v&&(g.key==="="||g.key==="+"))g.preventDefault(),e.current?.zoom(1);else if(v&&g.key==="-")g.preventDefault(),e.current?.zoom(-1);else if(v&&g.key==="0")g.preventDefault(),e.current?.fit("width");else if(!v&&!S&&s&&l&&["ArrowLeft","ArrowRight","PageUp","PageDown"].includes(g.key)){g.preventDefault();let $=g.key==="ArrowLeft"||g.key==="PageUp";c(l.current+($?-1:1))}else if(g.key==="Escape"&&!S){if(n)a();else if(u.open&&!h)d($=>({...$,open:!1}));else if(f.open)o();else if(m?.visible)p({...m,visible:!1});else return;g.preventDefault()}};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[n,r,i,o,a,s,l,c,u.open,h,f.open,m,t,e,d,p])}var Be=lt(Jn(),1);var qz="zcode-cjk-fallback",Tj="cjk-fallback.json",zj="U+1100-11FF, U+2E80-2FDF, U+2FF0-303F, U+3040-30FF, U+3100-31FF, U+3200-33FF, U+3400-4DBF, U+4E00-9FFF, U+A960-A97F, U+AC00-D7FF, U+F900-FAFF, U+FE10-FE1F, U+FE30-FE4F, U+FF00-FFEF, U+20000-2FA1F",Fz={"sc-serif":["STSongti-SC-Regular","Songti SC Regular","STSong","SimSun","NSimSun","Noto Serif CJK SC","NotoSerifCJKsc-Regular","Noto Serif SC","NotoSerifSC-Regular","Source Han Serif SC","SourceHanSerifSC-Regular","AR PL UMing CN","AR PL SungtiL GB"],"sc-sans":["PingFangSC-Regular","PingFang SC Regular","HiraginoSansGB-W3","Hiragino Sans GB W3","STHeitiSC-Light","Heiti SC Light","Microsoft YaHei","SimHei","Noto Sans CJK SC","NotoSansCJKsc-Regular","Noto Sans SC","NotoSansSC-Regular","Source Han Sans SC","SourceHanSansSC-Regular","WenQuanYi Micro Hei","WenQuanYi Zen Hei"],"sc-kai":["STKaitiSC-Regular","Kaiti SC Regular","STKaiti","KaiTi","KaiTi_GB2312","AR PL UKai CN","LXGW WenKai","LXGWWenKai-Regular"],"sc-fang":["STFangsong","FangSong","FangSong_GB2312"],"tc-serif":["STSongti-TC-Regular","Songti TC Regular","LiSongPro","LiSong Pro","PMingLiU","MingLiU","Noto Serif CJK TC","NotoSerifCJKtc-Regular","Noto Serif TC","Source Han Serif TC","SourceHanSerifTC-Regular","AR PL UMing TW"],"tc-sans":["PingFangTC-Regular","PingFang TC Regular","STHeitiTC-Light","Heiti TC Light","Microsoft JhengHei","Noto Sans CJK TC","NotoSansCJKtc-Regular","Noto Sans TC","Source Han Sans TC","SourceHanSansTC-Regular","WenQuanYi Zen Hei"],"tc-kai":["STKaitiTC-Regular","Kaiti TC Regular","BiauKaiTC-Regular","BiauKaiTC Regular","DFKai-SB","AR PL UKai TW"],"jp-serif":["HiraMinProN-W3","Hiragino Mincho ProN W3","Yu Mincho","YuMincho-Regular","MS Mincho","MS PMincho","Noto Serif CJK JP","NotoSerifCJKjp-Regular","Noto Serif JP","Source Han Serif","SourceHanSerif-Regular","IPAexMincho","IPAMincho"],"jp-sans":["HiraginoSans-W3","Hiragino Sans W3","HiraKakuProN-W3","Hiragino Kaku Gothic ProN W3","Yu Gothic","YuGothic-Medium","Meiryo","MS Gothic","MS PGothic","Noto Sans CJK JP","NotoSansCJKjp-Regular","Noto Sans JP","Source Han Sans","SourceHanSans-Regular","IPAexGothic","IPAGothic"],"kr-serif":["AppleMyungjo","AppleMyungjo Regular","Batang","Noto Serif CJK KR","NotoSerifCJKkr-Regular","Noto Serif KR","Source Han Serif K","SourceHanSerifK-Regular","UnBatang","NanumMyeongjo"],"kr-sans":["AppleSDGothicNeo-Regular","Apple SD Gothic Neo Regular","Malgun Gothic","Gulim","Dotum","Noto Sans CJK KR","NotoSansCJKkr-Regular","Noto Sans KR","Source Han Sans K","SourceHanSansK-Regular","NanumGothic","UnDotum"]},Bz=t=>`zcode-cjk-${t}`,W5=[[/fang|仿/,"fang"],[/kai|楷/,"kai"],[/hei(?!sei)|gothic|kakugo|kozgo|gulim|dotum|yuanti|ゴシック|黑|黒|굴림|돋움|고딕/,"sans"],[/song|sung|simsun|ming|mincho|kozmin|ryumin|heiseimin|batang|myeongjo|myungjo|宋|明|바탕|명조/,"serif"]],Q5=[[/sans/,"sans"],[/serif/,"serif"]],eG=[[/^hy|batang|gulim|dotum|malgun|myeongjo|myungjo|nanum|^un(batang|dotum)|applesdgothic|cjkkr|(kr|ko)\b|바탕|굴림|돋움|명조|고딕/,"kr"],[/^msung|^mhei|mingliu|dfkai|biaukai|jhenghei|lisong|cjktc|(tc|tw|hk)\b|細明|標楷/,"tc"],[/heisei|mincho|kozmin|kozgo|ryumin|gothicbbb|hira(kaku|min|maru)|hiraginosans(?!gb)|yu(gothic|mincho)|meiryo|ms-?p?gothic|ipa(ex)?(mincho|gothic)|cjkjp|jp\b|明朝|ゴシック/,"jp"],[/simsun|simhei|stsong|stheiti|stkaiti|stfangsong|yahei|^fz|songti|heiti|kaiti|fangsong|gb2312|cjksc|(sc|cn|gb)\b|宋|黑|楷|仿/,"sc"]],tG=[["utf-8",null],["gbk","sc"],["big5","tc"],["shift_jis","jp"],["euc-kr","kr"]];function Ej(t){let e=t.replace(/[\s_]+/g,"").toLowerCase(),n=W5.find(([o])=>o.test(e))?.[1]??null,r=eG.find(([o])=>o.test(e))?.[1]??null;if(!n&&!r)return null;let i=n??Q5.find(([o])=>o.test(e))?.[1]??null;return{script:r,style:i}}function nG(t){let e=t.replace(/^[A-Z]{6}\+/,"");if(!/[\x80-\xff]/.test(e)||/[\u0100-\uffff]/.test(e)){let r=Ej(e);return r&&{script:r.script??"sc",style:r.style}}let n=Uint8Array.from(e,r=>r.charCodeAt(0));for(let[r,i]of tG){let o;try{o=new TextDecoder(r,{fatal:!0}).decode(n)}catch{continue}let a=Ej(o);if(a)return{script:a.script??i??"sc",style:a.style}}return null}function kj(t,e){if(!t.missingFile||t.isType3Font)return[];let n=nG(t.name??""),r=n?.script??"sc",i=n?.style??(t.fallbackName==="serif"?"serif":"sans"),o=`${r}-${i}`,a=`${r}-serif`,s=o in Fz?[o]:[];return i!=="sans"&&!s.includes(a)&&s.push(a),[...s.map(Bz),...e?[qz]:[]]}var iG=new Set(["serif","sans-serif","monospace","cursive","fantasy","system-ui"]);function Rj(t,e){if(!e.length)return t;let n=t.split(","),r=e.map(o=>`"${o}"`),i=n.at(-1).trim();return iG.has(i)?[...n.slice(0,-1),...r,i].join(","):[...n,...r].join(",")}var rG,Cj=!1;function Ij(){return rG??=(async()=>{(await Promise.all(Object.entries(Fz).map(async([e,n])=>{let r=new FontFace(Bz(e),n.map(i=>`local("${i}")`).join(", "),{unicodeRange:zj});try{return await r.load(),document.fonts.add(r),!0}catch{return!1}}))).some(Boolean)||(Cj=await oG())})()}async function oG(){try{let t=JSON.parse(await Fy(Tj));return await Promise.all(t.faces.map(async({file:e,unicodeRange:n})=>{let r=new FontFace(qz,await Cm(e),{unicodeRange:n});await r.load(),document.fonts.add(r)})),!0}catch(t){return console.warn("CJK fallback font",t),!1}}function Oj(t,e){return Rj(e,kj(t,Cj))}var YG={},aS={};aS.d=(t,e)=>{for(var n in e)aS.o(e,n)&&!aS.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:e[n]})};aS.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var En=typeof process=="object"&&process+""=="[object process]"&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser"),Xz=[.001,0,0,.001,0,0],sS=1.35,aG=.35,TW=aG/sS,di={ANY:1,DISPLAY:2,PRINT:4,SAVE:8,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},Aa={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},qm="pdfjs_internal_editor_",$e={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15,POPUP:16,SIGNATURE:101,COMMENT:102},je={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_THICKNESS:32,HIGHLIGHT_FREE:33,HIGHLIGHT_SHOW_ALL:34,DRAW_STEP:41},sG={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},ln={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_ADD_TO_PATH:4,STROKE_ADD_TO_PATH:5,FILL_STROKE_ADD_TO_PATH:6,ADD_TO_PATH:7,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},lS={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},Mt={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26};var cu={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5};var VS={ERRORS:0,WARNINGS:1,INFOS:5},Fm={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,rawFillPath:94},Jy={moveTo:0,lineTo:1,curveTo:2,closePath:3},lG={NEED_PASSWORD:1,INCORRECT_PASSWORD:2},ZS=VS.WARNINGS;function cG(t){Number.isInteger(t)&&(ZS=t)}function uG(){return ZS}function GS(t){ZS>=VS.INFOS&&console.info(`Info: ${t}`)}function we(t){ZS>=VS.WARNINGS&&console.warn(`Warning: ${t}`)}function rt(t){throw new Error(t)}function Ue(t,e){t||rt(e)}function dG(t){switch(t?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function Qj(t,e=null,n=null){if(!t)return null;if(n&&typeof t=="string"&&(n.addDefaultProtocol&&t.startsWith("www.")&&t.match(/\./g)?.length>=2&&(t=`http://${t}`),n.tryConvertEncoding))try{t=pG(t)}catch{}let r=e?URL.parse(t,e):URL.parse(t);return dG(r)?r:null}function eU(t,e,n=!1){let r=URL.parse(t);return r?(r.hash=e,r.href):n&&Qj(t,"http://example.com")?t.split("#",1)[0]+`${e?`#${e}`:""}`:""}function Re(t,e,n,r=!1){return Object.defineProperty(t,e,{value:n,enumerable:!r,configurable:!0,writable:!1}),n}var Js=(function(){function e(n,r){this.message=n,this.name=r}return e.prototype=new Error,e.constructor=e,e})(),cS=class extends Js{constructor(e,n){super(e,"PasswordException"),this.code=n}},Um=class extends Js{constructor(e,n){super(e,"UnknownErrorException"),this.details=n}},Bm=class extends Js{constructor(e){super(e,"InvalidPDFException")}},mu=class extends Js{constructor(e,n,r){super(e,"ResponseException"),this.status=n,this.missing=r}},Jz=class extends Js{constructor(e){super(e,"FormatError")}},Or=class extends Js{constructor(e){super(e,"AbortException")}};function tU(t){(typeof t!="object"||t?.length===void 0)&&rt("Invalid argument for bytesToString");let e=t.length,n=8192;if(e<n)return String.fromCharCode.apply(null,t);let r=[];for(let i=0;i<e;i+=n){let o=Math.min(i+n,e),a=t.subarray(i,o);r.push(String.fromCharCode.apply(null,a))}return r.join("")}function np(t){typeof t!="string"&&rt("Invalid argument for stringToBytes");let e=t.length,n=new Uint8Array(e);for(let r=0;r<e;++r)n[r]=t.charCodeAt(r)&255;return n}function hG(t){return String.fromCharCode(t>>24&255,t>>16&255,t>>8&255,t&255)}function fG(){let t=new Uint8Array(4);return t[0]=1,new Uint32Array(t.buffer,0,1)[0]===1}function mG(){try{return new Function(""),!0}catch{return!1}}var Ft=class{static get isLittleEndian(){return Re(this,"isLittleEndian",fG())}static get isEvalSupported(){return Re(this,"isEvalSupported",mG())}static get isOffscreenCanvasSupported(){return Re(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas<"u")}static get isImageDecoderSupported(){return Re(this,"isImageDecoderSupported",typeof ImageDecoder<"u")}static get platform(){let{platform:e,userAgent:n}=navigator;return Re(this,"platform",{isAndroid:n.includes("Android"),isLinux:e.includes("Linux"),isMac:e.includes("Mac"),isWindows:e.includes("Win"),isFirefox:n.includes("Firefox")})}static get isCSSRoundSupported(){return Re(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}},Hz=Array.from(Array(256).keys(),t=>t.toString(16).padStart(2,"0")),oe=class{static makeHexColor(e,n,r){return`#${Hz[e]}${Hz[n]}${Hz[r]}`}static domMatrixToTransform(e){return[e.a,e.b,e.c,e.d,e.e,e.f]}static scaleMinMax(e,n){let r;e[0]?(e[0]<0&&(r=n[0],n[0]=n[2],n[2]=r),n[0]*=e[0],n[2]*=e[0],e[3]<0&&(r=n[1],n[1]=n[3],n[3]=r),n[1]*=e[3],n[3]*=e[3]):(r=n[0],n[0]=n[1],n[1]=r,r=n[2],n[2]=n[3],n[3]=r,e[1]<0&&(r=n[1],n[1]=n[3],n[3]=r),n[1]*=e[1],n[3]*=e[1],e[2]<0&&(r=n[0],n[0]=n[2],n[2]=r),n[0]*=e[2],n[2]*=e[2]),n[0]+=e[4],n[1]+=e[5],n[2]+=e[4],n[3]+=e[5]}static transform(e,n){return[e[0]*n[0]+e[2]*n[1],e[1]*n[0]+e[3]*n[1],e[0]*n[2]+e[2]*n[3],e[1]*n[2]+e[3]*n[3],e[0]*n[4]+e[2]*n[5]+e[4],e[1]*n[4]+e[3]*n[5]+e[5]]}static multiplyByDOMMatrix(e,n){return[e[0]*n.a+e[2]*n.b,e[1]*n.a+e[3]*n.b,e[0]*n.c+e[2]*n.d,e[1]*n.c+e[3]*n.d,e[0]*n.e+e[2]*n.f+e[4],e[1]*n.e+e[3]*n.f+e[5]]}static applyTransform(e,n,r=0){let i=e[r],o=e[r+1];e[r]=i*n[0]+o*n[2]+n[4],e[r+1]=i*n[1]+o*n[3]+n[5]}static applyTransformToBezier(e,n,r=0){let i=n[0],o=n[1],a=n[2],s=n[3],l=n[4],c=n[5];for(let u=0;u<6;u+=2){let d=e[r+u],h=e[r+u+1];e[r+u]=d*i+h*a+l,e[r+u+1]=d*o+h*s+c}}static applyInverseTransform(e,n){let r=e[0],i=e[1],o=n[0]*n[3]-n[1]*n[2];e[0]=(r*n[3]-i*n[2]+n[2]*n[5]-n[4]*n[3])/o,e[1]=(-r*n[1]+i*n[0]+n[4]*n[1]-n[5]*n[0])/o}static axialAlignedBoundingBox(e,n,r){let i=n[0],o=n[1],a=n[2],s=n[3],l=n[4],c=n[5],u=e[0],d=e[1],h=e[2],f=e[3],m=i*u+l,p=m,y=i*h+l,g=y,v=s*d+c,S=v,_=s*f+c,$=_;if(o!==0||a!==0){let w=o*u,A=o*h,k=a*d,I=a*f;m+=k,g+=k,y+=I,p+=I,v+=w,$+=w,_+=A,S+=A}r[0]=Math.min(r[0],m,y,p,g),r[1]=Math.min(r[1],v,_,S,$),r[2]=Math.max(r[2],m,y,p,g),r[3]=Math.max(r[3],v,_,S,$)}static inverseTransform(e){let n=e[0]*e[3]-e[1]*e[2];return[e[3]/n,-e[1]/n,-e[2]/n,e[0]/n,(e[2]*e[5]-e[4]*e[3])/n,(e[4]*e[1]-e[5]*e[0])/n]}static singularValueDecompose2dScale(e,n){let r=e[0],i=e[1],o=e[2],a=e[3],s=r**2+i**2,l=r*o+i*a,c=o**2+a**2,u=(s+c)/2,d=Math.sqrt(u**2-(s*c-l**2));n[0]=Math.sqrt(u+d||1),n[1]=Math.sqrt(u-d||1)}static normalizeRect(e){let n=e.slice(0);return e[0]>e[2]&&(n[0]=e[2],n[2]=e[0]),e[1]>e[3]&&(n[1]=e[3],n[3]=e[1]),n}static intersect(e,n){let r=Math.max(Math.min(e[0],e[2]),Math.min(n[0],n[2])),i=Math.min(Math.max(e[0],e[2]),Math.max(n[0],n[2]));if(r>i)return null;let o=Math.max(Math.min(e[1],e[3]),Math.min(n[1],n[3])),a=Math.min(Math.max(e[1],e[3]),Math.max(n[1],n[3]));return o>a?null:[r,o,i,a]}static pointBoundingBox(e,n,r){r[0]=Math.min(r[0],e),r[1]=Math.min(r[1],n),r[2]=Math.max(r[2],e),r[3]=Math.max(r[3],n)}static rectBoundingBox(e,n,r,i,o){o[0]=Math.min(o[0],e,r),o[1]=Math.min(o[1],n,i),o[2]=Math.max(o[2],e,r),o[3]=Math.max(o[3],n,i)}static#e(e,n,r,i,o,a,s,l,c,u){if(c<=0||c>=1)return;let d=1-c,h=c*c,f=h*c,m=d*(d*(d*e+3*c*n)+3*h*r)+f*i,p=d*(d*(d*o+3*c*a)+3*h*s)+f*l;u[0]=Math.min(u[0],m),u[1]=Math.min(u[1],p),u[2]=Math.max(u[2],m),u[3]=Math.max(u[3],p)}static#t(e,n,r,i,o,a,s,l,c,u,d,h){if(Math.abs(c)<1e-12){Math.abs(u)>=1e-12&&this.#e(e,n,r,i,o,a,s,l,-d/u,h);return}let f=u**2-4*d*c;if(f<0)return;let m=Math.sqrt(f),p=2*c;this.#e(e,n,r,i,o,a,s,l,(-u+m)/p,h),this.#e(e,n,r,i,o,a,s,l,(-u-m)/p,h)}static bezierBoundingBox(e,n,r,i,o,a,s,l,c){c[0]=Math.min(c[0],e,s),c[1]=Math.min(c[1],n,l),c[2]=Math.max(c[2],e,s),c[3]=Math.max(c[3],n,l),this.#t(e,r,o,s,n,i,a,l,3*(-e+3*(r-o)+s),6*(e-2*r+o),3*(r-e),c),this.#t(e,r,o,s,n,i,a,l,3*(-n+3*(i-a)+l),6*(n-2*i+a),3*(i-n),c)}};function pG(t){return decodeURIComponent(escape(t))}var Vz=null,Pj=null;function gG(t){return Vz||(Vz=/([\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,Pj=new Map([["\uFB05","\u017Ft"]])),t.replaceAll(Vz,(e,n,r)=>n?n.normalize("NFKC"):Pj.get(r))}function nU(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let t=new Uint8Array(32);return crypto.getRandomValues(t),tU(t)}var kR="pdfjs_internal_id_";function vG(t,e,n){if(!Array.isArray(n)||n.length<2)return!1;let[r,i,...o]=n;if(!t(r)&&!Number.isInteger(r)||!e(i))return!1;let a=o.length,s=!0;switch(i.name){case"XYZ":if(a<2||a>3)return!1;break;case"Fit":case"FitB":return a===0;case"FitH":case"FitBH":case"FitV":case"FitBV":if(a>1)return!1;break;case"FitR":if(a!==4)return!1;s=!1;break;default:return!1}for(let l of o)if(!(typeof l=="number"||s&&l===null))return!1;return!0}function Tn(t,e,n){return Math.min(Math.max(t,e),n)}function iU(t){return Uint8Array.prototype.toBase64?t.toBase64():btoa(tU(t))}function bG(t){return Uint8Array.fromBase64?Uint8Array.fromBase64(t):np(atob(t))}typeof Promise.try!="function"&&(Promise.try=function(t,...e){return new Promise(n=>{n(t(...e))})});typeof Math.sumPrecise!="function"&&(Math.sumPrecise=function(t){return t.reduce((e,n)=>e+n,0)});var Hm=class t{static textContent(e){let n=[],r={items:n,styles:Object.create(null)};function i(o){if(!o)return;let a=null,s=o.name;if(s==="#text")a=o.value;else if(t.shouldBuildText(s))o?.attributes?.textContent?a=o.attributes.textContent:o.value&&(a=o.value);else return;if(a!==null&&n.push({str:a}),!!o.children)for(let l of o.children)i(l)}return i(e),r}static shouldBuildText(e){return!(e==="textarea"||e==="input"||e==="option"||e==="select")}},uS=class{static setupStorage(e,n,r,i,o){let a=i.getValue(n,{value:null});switch(r.name){case"textarea":if(a.value!==null&&(e.textContent=a.value),o==="print")break;e.addEventListener("input",s=>{i.setValue(n,{value:s.target.value})});break;case"input":if(r.attributes.type==="radio"||r.attributes.type==="checkbox"){if(a.value===r.attributes.xfaOn?e.setAttribute("checked",!0):a.value===r.attributes.xfaOff&&e.removeAttribute("checked"),o==="print")break;e.addEventListener("change",s=>{i.setValue(n,{value:s.target.checked?s.target.getAttribute("xfaOn"):s.target.getAttribute("xfaOff")})})}else{if(a.value!==null&&e.setAttribute("value",a.value),o==="print")break;e.addEventListener("input",s=>{i.setValue(n,{value:s.target.value})})}break;case"select":if(a.value!==null){e.setAttribute("value",a.value);for(let s of r.children)s.attributes.value===a.value?s.attributes.selected=!0:s.attributes.hasOwnProperty("selected")&&delete s.attributes.selected}e.addEventListener("input",s=>{let l=s.target.options,c=l.selectedIndex===-1?"":l[l.selectedIndex].value;i.setValue(n,{value:c})});break}}static setAttributes({html:e,element:n,storage:r=null,intent:i,linkService:o}){let{attributes:a}=n,s=e instanceof HTMLAnchorElement;a.type==="radio"&&(a.name=`${a.name}-${i}`);for(let[l,c]of Object.entries(a))if(c!=null)switch(l){case"class":c.length&&e.setAttribute(l,c.join(" "));break;case"dataId":break;case"id":e.setAttribute("data-element-id",c);break;case"style":Object.assign(e.style,c);break;case"textContent":e.textContent=c;break;default:(!s||l!=="href"&&l!=="newWindow")&&e.setAttribute(l,c)}s&&o.addLinkAttributes(e,a.href,a.newWindow),r&&a.dataId&&this.setupStorage(e,a.dataId,n,r)}static render(e){let n=e.annotationStorage,r=e.linkService,i=e.xfaHtml,o=e.intent||"display",a=document.createElement(i.name);i.attributes&&this.setAttributes({html:a,element:i,intent:o,linkService:r});let s=o!=="richText",l=e.div;if(l.append(a),e.viewport){let d=`matrix(${e.viewport.transform.join(",")})`;l.style.transform=d}s&&l.setAttribute("class","xfaLayer xfaFont");let c=[];if(i.children.length===0){if(i.value){let d=document.createTextNode(i.value);a.append(d),s&&Hm.shouldBuildText(i.name)&&c.push(d)}return{textDivs:c}}let u=[[i,-1,a]];for(;u.length>0;){let[d,h,f]=u.at(-1);if(h+1===d.children.length){u.pop();continue}let m=d.children[++u.at(-1)[1]];if(m===null)continue;let{name:p}=m;if(p==="#text"){let g=document.createTextNode(m.value);c.push(g),f.append(g);continue}let y=m?.attributes?.xmlns?document.createElementNS(m.attributes.xmlns,p):document.createElement(p);if(f.append(y),m.attributes&&this.setAttributes({html:y,element:m,storage:n,intent:o,linkService:r}),m.children?.length>0)u.push([m,-1,y]);else if(m.value){let g=document.createTextNode(m.value);s&&Hm.shouldBuildText(p)&&c.push(g),y.append(g)}}for(let d of l.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))d.setAttribute("readOnly",!0);return{textDivs:c}}static update(e){let n=`matrix(${e.viewport.transform.join(",")})`;e.div.style.transform=n,e.div.hidden=!1}},wo="http://www.w3.org/2000/svg",Ta=class{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF};async function ip(t,e="text"){if(jm(t,document.baseURI)){let n=await fetch(t);if(!n.ok)throw new Error(n.statusText);switch(e){case"arraybuffer":return n.arrayBuffer();case"blob":return n.blob();case"json":return n.json()}return n.text()}return new Promise((n,r)=>{let i=new XMLHttpRequest;i.open("GET",t,!0),i.responseType=e,i.onreadystatechange=()=>{if(i.readyState===XMLHttpRequest.DONE){if(i.status===200||i.status===0){switch(e){case"arraybuffer":case"blob":case"json":n(i.response);return}n(i.responseText);return}r(new Error(i.statusText))}},i.send(null)})}var Vm=class t{constructor({viewBox:e,userUnit:n,scale:r,rotation:i,offsetX:o=0,offsetY:a=0,dontFlip:s=!1}){this.viewBox=e,this.userUnit=n,this.scale=r,this.rotation=i,this.offsetX=o,this.offsetY=a,r*=n;let l=(e[2]+e[0])/2,c=(e[3]+e[1])/2,u,d,h,f;switch(i%=360,i<0&&(i+=360),i){case 180:u=-1,d=0,h=0,f=1;break;case 90:u=0,d=1,h=1,f=0;break;case 270:u=0,d=-1,h=-1,f=0;break;case 0:u=1,d=0,h=0,f=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}s&&(h=-h,f=-f);let m,p,y,g;u===0?(m=Math.abs(c-e[1])*r+o,p=Math.abs(l-e[0])*r+a,y=(e[3]-e[1])*r,g=(e[2]-e[0])*r):(m=Math.abs(l-e[0])*r+o,p=Math.abs(c-e[1])*r+a,y=(e[2]-e[0])*r,g=(e[3]-e[1])*r),this.transform=[u*r,d*r,h*r,f*r,m-u*r*l-h*r*c,p-d*r*l-f*r*c],this.width=y,this.height=g}get rawDims(){let e=this.viewBox;return Re(this,"rawDims",{pageWidth:e[2]-e[0],pageHeight:e[3]-e[1],pageX:e[0],pageY:e[1]})}clone({scale:e=this.scale,rotation:n=this.rotation,offsetX:r=this.offsetX,offsetY:i=this.offsetY,dontFlip:o=!1}={}){return new t({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:e,rotation:n,offsetX:r,offsetY:i,dontFlip:o})}convertToViewportPoint(e,n){let r=[e,n];return oe.applyTransform(r,this.transform),r}convertToViewportRectangle(e){let n=[e[0],e[1]];oe.applyTransform(n,this.transform);let r=[e[2],e[3]];return oe.applyTransform(r,this.transform),[n[0],n[1],r[0],r[1]]}convertToPdfPoint(e,n){let r=[e,n];return oe.applyInverseTransform(r,this.transform),r}},Zm=class extends Js{constructor(e,n=0){super(e,"RenderingCancelledException"),this.extraDelay=n}};function KS(t){let e=t.length,n=0;for(;n<e&&t[n].trim()==="";)n++;return t.substring(n,n+5).toLowerCase()==="data:"}function RR(t){return typeof t=="string"&&/\.pdf$/i.test(t)}function yG(t){return[t]=t.split(/[#?]/,1),t.substring(t.lastIndexOf("/")+1)}function SG(t,e="document.pdf"){if(typeof t!="string")return e;if(KS(t))return we('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'),e;let r=(s=>{try{return new URL(s)}catch{try{return new URL(decodeURIComponent(s))}catch{try{return new URL(s,"https://foo.bar")}catch{try{return new URL(decodeURIComponent(s),"https://foo.bar")}catch{return null}}}}})(t);if(!r)return e;let i=s=>{try{let l=decodeURIComponent(s);return l.includes("/")?(l=l.split("/").at(-1),l.test(/^\.pdf$/i)?l:s):l}catch{return s}},o=/\.pdf$/i,a=r.pathname.split("/").at(-1);if(o.test(a))return i(a);if(r.searchParams.size>0){let s=Array.from(r.searchParams.values()).reverse();for(let c of s)if(o.test(c))return i(c);let l=Array.from(r.searchParams.keys()).reverse();for(let c of l)if(o.test(c))return i(c)}if(r.hash){let l=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i.exec(r.hash);if(l)return i(l[0])}return e}var dS=class{started=Object.create(null);times=[];time(e){e in this.started&&we(`Timer is already running for ${e}`),this.started[e]=Date.now()}timeEnd(e){e in this.started||we(`Timer has not been started for ${e}`),this.times.push({name:e,start:this.started[e],end:Date.now()}),delete this.started[e]}toString(){let e=[],n=0;for(let{name:r}of this.times)n=Math.max(r.length,n);for(let{name:r,start:i,end:o}of this.times)e.push(`${r.padEnd(n)} ${o-i}ms
108
+ container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:x.string().optional().describe("User's language and region preference in BCP 47 format."),timeZone:x.string().optional().describe("User's timezone in IANA format."),userAgent:x.string().optional().describe("Host application identifier."),platform:x.union([x.literal("web"),x.literal("desktop"),x.literal("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:x.object({touch:x.boolean().optional().describe("Whether the device supports touch input."),hover:x.boolean().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:x.object({top:x.number().describe("Top safe area inset in pixels."),right:x.number().describe("Right safe area inset in pixels."),bottom:x.number().describe("Bottom safe area inset in pixels."),left:x.number().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),C5=x.object({method:x.literal("ui/notifications/host-context-changed"),params:z2.describe("Partial context update containing only changed fields.")}),e7=x.object({method:x.literal("ui/update-model-context"),params:x.object({content:x.array(Er).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:x.record(x.string(),x.unknown().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),t7=x.object({method:x.literal("ui/initialize"),params:x.object({appInfo:$r.describe("App identification (name and version)."),appCapabilities:T5.describe("Features and capabilities this app provides."),protocolVersion:x.string().describe("Protocol version this app supports.")})}),I5=x.object({protocolVersion:x.string().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:$r.describe("Host application identification and version."),hostCapabilities:E5.describe("Features and capabilities provided by the host."),hostContext:z2.describe("Rich context about the host environment.")}).passthrough(),O5={target:"draft-2020-12"};async function E2(t,e){let n=t["~standard"];if(n.jsonSchema)return n.jsonSchema[e](O5);throw Error(`Schema (vendor: ${n.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function T2(t,e,n=""){let r=await t["~standard"].validate(e);if(r.issues){let i=r.issues.map(o=>{let a=o.path?.map(s=>typeof s=="object"?s.key:s).join(".");return a?`${a}: ${o.message}`:o.message}).join("; ");throw Error(n+i)}return r.value}function k2(t,e=document.documentElement){for(let[n,r]of Object.entries(t))r!==void 0&&e.style.setProperty(n,r)}function P5(t,e){let n={...t,...e};return e.experimental!==void 0&&(n.experimental={...t.experimental,...e.experimental}),e.tools!==void 0&&(n.tools={...t.tools,...e.tools}),n}var Ly=class t extends Az{_appInfo;_appCapabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_registeredEvents=new Set;_events=new Ez;_methods=new Tz;setRequestHandler=(...e)=>{let[n,...r]=$2("request",e)??e;this._methods.claim(n,"setRequestHandler"),super.setRequestHandler.call(this,n,...r)};setNotificationHandler=(...e)=>{let[n,...r]=$2("notification",e)??e;this._methods.claim(n,"setNotificationHandler"),super.setNotificationHandler.call(this,n,...r)};removeRequestHandler=e=>{this._methods.release(e),super.removeRequestHandler(e)};removeNotificationHandler=e=>{this._methods.release(e),super.removeNotificationHandler(e)};replaceRequestHandler=(e,...n)=>{this._methods.replace(e),super.setRequestHandler.call(this,e,...n)};_assertInitialized(e){if(this._initializedSent)return;let n=`[ext-apps] App.${e}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(n);console.warn(`${n}. This will throw in a future release.`)}eventSchemas={toolinput:y5,toolinputpartial:S5,toolresult:R5,toolcancelled:_5,hostcontextchanged:C5};static ONE_SHOT_EVENTS=new Set(["toolinput","toolinputpartial","toolresult","toolcancelled"]);_everHadListener=new Set;_assertHandlerTiming(e){if(!t.ONE_SHOT_EVENTS.has(e)||this._everHadListener.has(e)||(this._everHadListener.add(e),!this._initializedSent))return;let n=`[ext-apps] "${String(e)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(n);console.warn(n)}setEventHandler(e,n){n&&this._assertHandlerTiming(e),this._ensureEventSlot(e),this._events.setHandler(e,n)}addEventListener(e,n){this._assertHandlerTiming(e),this._ensureEventSlot(e),this._events.addEventListener(e,n)}removeEventListener(e,n){this._events.removeEventListener(e,n)}_ensureEventSlot(e){if(this._registeredEvents.has(e))return;let n=this.eventSchemas[e];if(!n)throw Error(`Unknown event: ${String(e)}`);this.setNotificationHandler(n.shape.method.value,{params:n.shape.params},r=>{let i=r;e==="hostcontextchanged"&&(this._hostContext={...this._hostContext,...i}),this._events.dispatch(e,i)}),this._registeredEvents.add(e)}getEventHandler(e){return this._events.getHandler(e)}warnIfRequestHandlerReplaced(e,n,r){n&&r&&console.warn(`[MCP Apps] ${e} handler replaced. Previous handler will no longer be called.`)}constructor(e,n={},r={autoResize:!0}){super(r),this._appInfo=e,this._appCapabilities=n,this.options=r,this._methods.replace("notifications/cancelled"),this._methods.replace("notifications/progress"),!r.allowUnsafeEval&&x.config({jitless:!0}),this.replaceRequestHandler("ping",i=>(console.log("Received ping:",i.params),{})),this.setEventHandler("hostcontextchanged",void 0)}buildContext(e){return e}registerAppCapabilities(e){if(this.transport)throw Error("Cannot register capabilities after transport is established");this._appCapabilities=P5(this._appCapabilities,e)}registerTool(e,n,r){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let i=this,o=()=>{i._initializedSent&&i._appCapabilities.tools?.listChanged&&i.sendToolListChanged()},a=n.inputSchema!==void 0,s={title:n.title,description:n.description,inputSchema:n.inputSchema,outputSchema:n.outputSchema,annotations:n.annotations,_meta:n._meta,enabled:!0,enable(){this.enabled=!0,o()},disable(){this.enabled=!1,o()},update(l){Object.assign(this,l),o()},remove(){i._registeredTools[e]===s&&(delete i._registeredTools[e],o())},handler:async(l,c)=>{if(!s.enabled)throw Error(`Tool ${e} is disabled`);let u;if(a){let d=s.inputSchema,h=d?await T2(d,l??{},`Invalid input for tool ${e}: `):l??{};u=await r(h,c)}else u=await r(c);return s.outputSchema&&!u.isError&&(u.structuredContent=await T2(s.outputSchema,u.structuredContent,`Invalid output for tool ${e}: `)),u}};return this._registeredTools[e]=s,!this._appCapabilities.tools&&!this.transport&&this.registerAppCapabilities({tools:{listChanged:!0}}),this.ensureToolHandlersInitialized(),o(),s}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){this._toolHandlersInitialized||(this._toolHandlersInitialized=!0,this.oncalltool=async(e,n)=>{let r=this._registeredTools[e.name];if(!r)throw Error(`Tool ${e.name} not found`);return r.handler(e.arguments,n)},this.onlisttools=async(e,n)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([r,i])=>i.enabled).map(async([r,i])=>{let o={name:r,title:i.title,description:i.description,inputSchema:i.inputSchema?await E2(i.inputSchema,"input"):{type:"object",properties:{}}};return i.outputSchema&&(o.outputSchema=await E2(i.outputSchema,"output")),i.annotations&&(o.annotations=i.annotations),i._meta&&(o._meta=i._meta),o}))}))}async sendToolListChanged(e={}){this._assertInitialized("sendToolListChanged"),await this.notification({method:"notifications/tools/list_changed",params:e})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler("toolinput")}set ontoolinput(e){this.setEventHandler("toolinput",e)}get ontoolinputpartial(){return this.getEventHandler("toolinputpartial")}set ontoolinputpartial(e){this.setEventHandler("toolinputpartial",e)}get ontoolresult(){return this.getEventHandler("toolresult")}set ontoolresult(e){this.setEventHandler("toolresult",e)}get ontoolcancelled(){return this.getEventHandler("toolcancelled")}set ontoolcancelled(e){this.setEventHandler("toolcancelled",e)}get onhostcontextchanged(){return this.getEventHandler("hostcontextchanged")}set onhostcontextchanged(e){this.setEventHandler("hostcontextchanged",e)}_onteardown;get onteardown(){return this._onteardown}set onteardown(e){this.warnIfRequestHandlerReplaced("onteardown",this._onteardown,e),this._onteardown=e,this.replaceRequestHandler("ui/resource-teardown",{params:$5.shape.params,result:A5},(n,r)=>{if(!this._onteardown)throw Error("No onteardown handler set");return this._onteardown(n,r)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler("tools/call",(n,r)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(n.params,r)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(e){this.warnIfRequestHandlerReplaced("onlisttools",this._onlisttools,e),this._onlisttools=e,this.replaceRequestHandler("tools/list",(n,r)=>{if(!this._onlisttools)throw Error("No onlisttools handler set");return this._onlisttools(n.params,r)})}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${e})`);break}}assertRequestHandlerCapability(e){switch(e){case"tools/call":case"tools/list":if(!this._appCapabilities.tools)throw Error(`Client does not support tool capability (required for ${e})`);return;default:return}}assertNotificationCapability(e){}async callServerTool(e,n){if(this._assertInitialized("callServerTool"),typeof e=="string")throw Error(`callServerTool() expects an object as its first argument, but received a string ("${e}"). Did you mean: callServerTool({ name: "${e}", arguments: { ... } })?`);return await this.request({method:"tools/call",params:e},{onprogress:()=>{},resetTimeoutOnProgress:!0,...n})}async readServerResource(e,n){return this._assertInitialized("readServerResource"),await this.request({method:"resources/read",params:e},n)}async listServerResources(e,n){return this._assertInitialized("listServerResources"),await this.request({method:"resources/list",params:e},n)}async createSamplingMessage(e,n){return this._assertInitialized("createSamplingMessage"),await this.request({method:"sampling/createMessage",params:e},n)}sendMessage(e,n){return this._assertInitialized("sendMessage"),this.request({method:"ui/message",params:e},b5,n)}sendLog(e){return this.notification({method:"notifications/message",params:e})}updateModelContext(e,n){return this._assertInitialized("updateModelContext"),this.request({method:"ui/update-model-context",params:e},_a,n)}openLink(e,n){return this._assertInitialized("openLink"),this.request({method:"ui/open-link",params:e},g5,n)}sendOpenLink=this.openLink;downloadFile(e,n){return this._assertInitialized("downloadFile"),this.request({method:"ui/download-file",params:e},v5,n)}requestTeardown(e={}){return this.notification({method:"ui/notifications/request-teardown",params:e})}requestDisplayMode(e,n){return this._assertInitialized("requestDisplayMode"),this.request({method:"ui/request-display-mode",params:e},z5,n)}sendSizeChanged(e){return this.notification({method:"ui/notifications/size-changed",params:e})}setupSizeChangedNotifications(){let e=!1,n=0,r=0,i=()=>{e||(e=!0,requestAnimationFrame(()=>{e=!1;let a=document.documentElement,s=a.style.height;a.style.height="max-content";let l=Math.ceil(a.getBoundingClientRect().height);a.style.height=s;let c=Math.ceil(window.innerWidth);(c!==n||l!==r)&&(n=c,r=l,this.sendSizeChanged({width:c,height:l}))}))};i();let o=new ResizeObserver(i);return o.observe(document.documentElement),o.observe(document.body),()=>o.disconnect()}async connect(e=new $m(window.parent,window.parent),n){if(this.transport)throw Error("App is already connected. Call close() before connecting again.");this._initializedSent=!1;try{await super.connect(e);let r=await this.request({method:"ui/initialize",params:{appCapabilities:this._appCapabilities,appInfo:this._appInfo,protocolVersion:d5}},I5,n);if(r===void 0)throw Error(`Server sent invalid initialize result: ${r}`);this._hostCapabilities=r.hostCapabilities,this._hostInfo=r.hostInfo,this._hostContext=r.hostContext,await this.notification({method:"ui/notifications/initialized"}),this._initializedSent=!0,this.options?.autoResize&&this.setupSizeChangedNotifications()}catch(r){throw this.close(),r}}};var gt={name:"pdf",version:"0.2.2",title:{en:"PDF","zh-CN":"PDF"},kinds:["pdf"]};var R2=gt.version,C2=gt.name,c7=gt.name,u7=`ui://${gt.name}/panel.html`,Rz=`ui://${gt.name}/assets/`,I2=`ui://${gt.name}/file/`;var tr=gt.kinds,Tm=100*1024*1024,d7=512*1024*1024,Cz=4*1024*1024,h7=24*1024,Em=class extends Error{constructor(n,r){super(r);this.code=n;this.name="OfficeError"}};function zm(t){let e=t.toLowerCase().match(/\.([a-z]+)$/)?.[1];return tr.includes(e??"")?e:null}var N5={en:{sep:", ",and:" and ",or:" or "},"zh-CN":{sep:"\u3001",and:"\u548C",or:"\u6216"}};function Ci(t,e="en",n="and"){let r=N5[e];if(t.length<2)return t.join("");let i=t[t.length-1],o=e==="zh-CN"&&/^[\x20-\x7e]/.test(i)?` ${r[n]} `:r[n];return`${t.slice(0,-1).join(r.sep)}${o}${i}`}function js(t="en",e="and"){return Ci(tr.map(n=>`.${n}`),t,e)}var zr=(t,e)=>new Em("invalid_anchor",`Cannot read location "${t}". ${e}`),kr={docx:"Use p:N, p:N-M, t:N or t:N/rRcC.",pptx:"Use slide:N, slide:N-M or slide:N/shape:ID.",pdf:"Use page:N or page:N-M.",xlsx:"Use Sheet, Sheet!A1 or Sheet!A1:C9 (quote names with spaces: 'My sheet'!A1)."};function Iz(t,e,n){if(!e)throw zr(t,kr[n]);let r=Number(e[1]),i=e[2]===void 0?r:Number(e[2]);if(!(r>=1)||!(i>=r)||i>1e6)throw zr(t,kr[n]);return{from:r,to:i}}function O2(t){let e=/^\$?([A-Za-z]{1,3})\$?(\d{1,7})$/.exec(t);if(!e)return null;let n=0;for(let i of e[1].toUpperCase())n=n*26+(i.charCodeAt(0)-64);let r=Number(e[2]);return r<1||r>1048576||n>16384?null:{row:r,col:n}}function M5(t){let e,n;if(t.startsWith("'")){let s=1;for(e="";s<t.length;s++)if(t[s]==="'")if(t[s+1]==="'")e+="'",s++;else break;else e+=t[s];if(s>=t.length||(n=t.slice(s+1),n&&!n.startsWith("!")))throw zr(t,kr.xlsx);n=n.slice(1)}else{let s=t.lastIndexOf("!");e=s<0?t:t.slice(0,s),n=s<0?"":t.slice(s+1)}if(!e||e.length>64)throw zr(t,kr.xlsx);if(!n)return{kind:"xlsx",sheet:e};let[r,i=r]=n.split(":"),o=O2(r),a=O2(i);if(!o||!a)throw zr(t,kr.xlsx);return{kind:"xlsx",sheet:e,range:{start:{row:Math.min(o.row,a.row),col:Math.min(o.col,a.col)},end:{row:Math.max(o.row,a.row),col:Math.max(o.col,a.col)}}}}function jy(t,e){let n=e.trim();if(!n||n.length>300)throw zr(e,kr[t]);switch(t){case"docx":{let r=/^t:(\d+)(?:\/r(\d+)c(\d+))?$/i.exec(n);if(r){let i=Number(r[1]);if(i<1)throw zr(n,kr.docx);if(r[2]===void 0)return{kind:t,type:"table",table:i};let o={row:Number(r[2]),col:Number(r[3])};if(o.row<1||o.col<1)throw zr(n,kr.docx);return{kind:t,type:"table",table:i,cell:o}}return{kind:t,type:"paragraph",...Iz(n,/^p:(\d+)(?:-(?:p:)?(\d+))?$/i.exec(n),t)}}case"pptx":{let r=/^slide:(\d+)\/shape:([\w-]{1,32})$/i.exec(n);if(r){let i=Number(r[1]);if(i<1)throw zr(n,kr.pptx);return{kind:t,from:i,to:i,shape:r[2]}}return{kind:t,...Iz(n,/^slide:(\d+)(?:-(?:slide:)?(\d+))?$/i.exec(n),t)}}case"pdf":return{kind:t,...Iz(n,/^page:(\d+)(?:-(?:page:)?(\d+))?$/i.exec(n),t)};case"xlsx":return M5(n)}}function P2(t){let e=/^(.*?\.(?:docx|xlsx|pptx|pdf))(?:#(.*))?$/i.exec(t.trim());if(!e)throw new Em("invalid_anchor",`"${t}" is not a document anchor. Use <path>.docx|.xlsx|.pptx|.pdf optionally followed by #<location>.`);return{path:e[1],at:e[2]?.trim()?e[2].trim():null}}function km(t,e){return e?`${t}#${e}`:t}var N2=t=>t>=55296&&t<=56319,M2=t=>t>=56320&&t<=57343;function D2(t,e,n=t.length){let r=Math.max(0,Math.min(e,t.length)),i=Math.max(r,Math.min(n,t.length));return r>0&&M2(t.charCodeAt(r))&&N2(t.charCodeAt(r-1))&&r--,i<t.length&&M2(t.charCodeAt(i))&&N2(t.charCodeAt(i-1))&&i--,t.slice(r,i)}var D5=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,qy=t=>t.replace(D5,"\uFFFD");function Uy(t){return typeof t=="string"?qy(t):Array.isArray(t)?t.map(e=>Uy(e)):t&&typeof t=="object"&&Object.getPrototypeOf(t)===Object.prototype?Object.fromEntries(Object.entries(t).map(([e,n])=>[e,Uy(n)])):t}var L2=`${gt.name}:windows:v1`,L5=128;function j2(t){try{let e=JSON.parse(t.getItem(L2)??"{}");return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function Oz(t,e){let n=j2(t)[e];return!n||typeof n!="object"?{}:{...typeof n.path=="string"?{path:n.path}:{},...Array.isArray(n.recent)?{recent:n.recent.filter(r=>typeof r?.path=="string"&&zm(r.path)===r.kind)}:{}}}function U2(t,e,n){try{let r=j2(t),i={...Oz(t,e),...n};delete r[e],r[e]=i;for(let o of Object.keys(r).slice(0,-L5))delete r[o];t.setItem(L2,JSON.stringify(r))}catch{}}var au=t=>t.filter(([e])=>tr.includes(e)).map(([,e])=>e),j5={docx:"Word",xlsx:"Excel",pptx:"PowerPoint",pdf:"PDF"},q2=tr.filter(t=>t!=="pdf"),F2=[...q2.length===3?["Office"]:q2.map(t=>j5[t]),...tr.includes("pdf")?["PDF"]:[]],Rm=gt.title.en,w7=(()=>{let t=Ci(F2,"en","or");return`${/^[AEIOU]/.test(t)?"an":"a"} ${t} file`})(),x7=`${Ci(F2)} files`,$7=js("en","or"),A7=au([["docx","report.docx#p:12"],["xlsx","model.xlsx#Revenue!B2:F9"],["pptx","deck.pptx#slide:3"],["pdf","paper.pdf#page:5"]]).join(", "),E7=au([["docx","p:12"],["pptx","slide:3"],["pdf","page:5"],["xlsx","Revenue!B2:F9"]]).join(", "),T7=au([["docx","Word paragraphs and tables (markdown)"],["xlsx","spreadsheet cells as a grid with formulas"],["pptx","slides with their shapes and speaker notes"],["pdf","PDF page text"]]).join(", "),z7=Ci(au([["docx","paragraph"],["xlsx","cell range"],["pptx","slide"],["pptx","shape"],["pdf","page"]]),"en","or"),k7=Ci(au([["pdf","PDF pages"],["docx","long paragraphs"]]))||"long passages",B2=Ci(au([["pptx","deck.pptx#slide:3"],["pdf","paper.pdf#page:2"],["docx","report.docx#p:12"],["xlsx","model.xlsx#Revenue!A1:H30"]]),"en","or");var H2=[{name:"capture_view",title:`Capture ${Rm} view`,description:`Take a picture of a rendered document location in the ${Rm} panel so you can see layout, charts, images and formatting that text extraction misses. Pass an anchor such as ${B2} (the document must be open in the panel; call open_document first), or omit it to capture what the user currently sees.`,inputSchema:{type:"object",properties:{anchor:{type:"string",maxLength:1200,description:"Location to capture; defaults to the visible view."},maxWidth:{type:"integer",minimum:320,maximum:2e3,description:"Maximum image width in pixels (default 1600)."}},additionalProperties:!1},annotations:{readOnlyHint:!0,idempotentHint:!0}}];function U5(){let t=crypto.randomUUID(),e=()=>n.getHostCapabilities()?.experimental?.["zcode/surface"]?.stateKey??t,n=new Ly({name:C2,version:R2},{tools:{listChanged:!0},availableDisplayModes:["inline","fullscreen"]},{autoResize:!1}),r=[],i=new Map,o=new Set,a,s=c=>void window.dispatchEvent(new Event(`office:${c}`));return n.ontoolresult=c=>{r.push(c),r.length>20&&r.shift(),s("toolresult")},n.onhostcontextchanged=()=>s("hostchange"),n.onlisttools=async()=>({tools:H2}),n.oncalltool=async(c,u)=>{if(!H2.some(d=>d.name===c.name))return{isError:!0,content:[{type:"text",text:`The ${Rm} page has no tool ${c.name}.`}]};try{let d=Date.now()+2e4;for(;!i.has(c.name)&&Date.now()<d;)await new Promise(m=>{let p=()=>(o.delete(p),m());o.add(p),setTimeout(p,500)});let h=i.get(c.name);if(!h)throw new Error(`The ${Rm} panel is still loading; try again in a moment.`);let f=u;return await h(c.arguments??{},f.mcpReq?.signal??f.signal)}catch(d){return{isError:!0,content:[{type:"text",text:d instanceof Error?d.message:String(d)}]}}},window.addEventListener("pagehide",()=>{n.callServerTool({name:"release_view",arguments:{viewId:e()}}).catch(()=>{})}),{app:n,get viewId(){return e()},ready:()=>a??=n.connect(new $m(window.parent,window.parent)).then(()=>s("hostchange")),readWindow(){let c=n.getHostCapabilities()?.experimental?.["zcode/surface"];if(!c?.stateKey)return{};try{return Oz(localStorage,c.stateKey)}catch{return{}}},saveWindow(c){let u=n.getHostCapabilities()?.experimental?.["zcode/surface"];if(u?.stateKey)try{U2(localStorage,u.stateKey,c)}catch{}},readDocument(){return this.readWindow().path??null},saveDocument(c){this.saveWindow({path:c})},takeResults:()=>r.splice(0,r.length),handleTool(c,u){i.set(c,u);for(let d of o)d()},get context(){return n.getHostContext()},get capabilities(){return n.getHostCapabilities()}}}function Ii(){return window.__officeHost??=U5()}async function Nz(t){let e=Ii();await e.ready();let r=(await e.app.readServerResource({uri:t})).contents[0];if(!r)throw new Error(`Empty resource ${t}`);return r}async function Fy(t){let e=await Nz(Rz+t);if(typeof e.text!="string")throw new Error(`Asset ${t} is not text`);return e.text}function V2(t){let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}var Pz=new Map;function Cm(t){let e=Pz.get(t);return e||(e=Nz(Rz+t).then(n=>{if(typeof n.blob!="string")throw new Error(`Asset ${t} is not binary`);return V2(n.blob)}),e.catch(()=>Pz.delete(t)),Pz.set(t,e)),e}async function Z2(t,e){let n=new Uint8Array(t.bytes),r=0;for(let i=0;i<t.chunks;i++){e?.throwIfAborted();let o=await Nz(`${I2}${t.token}/${i}`);if(typeof o.blob!="string")throw new Error("File chunk is not binary");let a=V2(o.blob);n.set(a,r),r+=a.byteLength}if(r!==t.bytes)throw new Error("The file changed while it was loading; reload it.");return n.buffer}var By=lt(Jn(),1);var Im=class extends Error{constructor(n,r){super(n);this.code=r;this.name="CallError"}};async function Rr(t,e={}){let n=Ii();await n.ready();let r=await n.app.callServerTool({name:t,arguments:e}),i=r.structuredContent,o=i?.error;if(r.isError||o){let a=r.content?.[0]?.text;throw new Im(o?.message??a??`${t} failed`,o?.code)}return i}var Us=t=>t.slice(t.lastIndexOf("/")+1),G2=t=>{let e=t.lastIndexOf("/");return e>0?t.slice(0,e):""};async function K2(t){let{id:e}=await Rr("begin_file_import",{name:t.name,size:t.size});try{for(let r=0;r<t.size;r+=Cz){let i=await new Promise((o,a)=>{let s=new FileReader;s.onload=()=>o(String(s.result).split(",")[1]),s.onerror=()=>a(s.error),s.readAsDataURL(t.slice(r,r+Cz))});await Rr("write_file_import",{id:e,offset:r,data:i})}return(await Rr("finish_file_import",{id:e})).path}catch(n){throw await Rr("cancel_file_import",{id:e}).catch(()=>{}),n}}var Hy=(t,e)=>t.length>e?`${D2(t,0,e-1)}\u2026`:t;function Mz(){return Ii().readWindow().recent??[]}function Y2(t){Ii().saveWindow({recent:t})}function Om(t,e,n){let r=e instanceof Im?e.code:e?.name==="PasswordException"?"password":void 0,[i,o]=r&&t.errors[r]||t.errors.generic,a=e instanceof Error?e.message:String(e);return{path:n,title:i,detail:o||a}}function X2(){let[,t]=(0,By.useState)(0);return(0,By.useEffect)(()=>{let e=()=>t(n=>n+1);return window.addEventListener("office:hostchange",e),()=>window.removeEventListener("office:hostchange",e)},[]),Ii().context}var q5={docx:"Word",xlsx:"Excel",pptx:"PowerPoint",pdf:"PDF"},W2=tr.map(t=>q5[t]),su=t=>tr.includes(t),J2=su("docx")||su("pdf"),Q2={en:`any ${Ci([...J2?["passage"]:[],...su("xlsx")?["cell"]:[],...su("pptx")?["slide"]:[]],"en","or")}`,zh:Ci([...J2?["\u6BB5\u843D"]:[],...su("xlsx")?["\u5355\u5143\u683C"]:[],...su("pptx")?["\u5E7B\u706F\u7247"]:[]],"zh-CN","or")},Dz=gt.title["zh-CN"].replace(/[\x20-\x7e]$/,"$& "),F5={title:gt.title.en,openTitle:"Open a document",openFile:"Open file",emptyTitle:`Open your ${Ci(W2)} file`,emptyDescription:`Read alongside your conversation and discuss ${Q2.en}.`,emptyCaption:`Choose a local file \xB7 ${js("en","or")}`,importing:"Importing\u2026",importTooLarge:`Choose a file no larger than ${Tm/1024/1024} MiB.`,recent:"Recent",switchDocument:"Switch document",pagesAndOutline:"Pages and outline",outlineOnly:"Outline",pages:"Pages",slides:"Slides",outline:"Outline",find:"Find",findPlaceholder:"Find in document",findCount:(t,e)=>`${t} of ${e}`,noResults:"No results",previousMatch:"Previous match (\u21E7Enter)",nextMatch:"Next match (Enter)",closeFind:"Close (Esc)",more:"More",fitWidth:"Fit width",fitPage:"Fit page",actualSize:"Actual size",reload:"Reload from disk",previousPage:"Previous page",nextPage:"Next page",pageNumber:"Page number",ofPages:t=>`of ${t}`,zoomIn:"Zoom in (\u2318+)",zoomOut:"Zoom out (\u2318\u2212)",fit:"Fit",addToChat:"Add to chat",addShort:"Add",addToChatHint:"Attach this to your next message (\u2318/Ctrl+Enter)",added:"Added to chat",ask:"Ask",askPlaceholder:"Ask about this\u2026",send:"Send",cancel:"Cancel",sendKey:"send",cancelKey:"cancel",copy:"Copy",copied:"Copied",agent:"Agent",agentOf:(t,e)=>`Agent \xB7 ${t} of ${e}`,nextTarget:"Next",moreOn:(t,e)=>t===1?`1 more on ${e}`:`${t} more`,close:"Close",changed:"This file changed on disk.",reloadShort:"Reload",dismiss:"Dismiss",openAnother:"Open another file",sidePanel:"Open in side panel",meta:{pdf:t=>t===1?"1 page":`${t} pages`,pptx:t=>t===1?"1 slide":`${t} slides`,xlsx:t=>t===1?"1 sheet":`${t} sheets`,docx:t=>""},errors:{generic:["Couldn\u2019t open this document",""],password:["This PDF is password protected",`${gt.title.en} can\u2019t open encrypted files yet.`],not_found:["This file no longer exists","It may have been moved or deleted."],file_too_large:["This file is too large to open",""],corrupt_file:["This file appears to be damaged",`${gt.title.en} couldn\u2019t read its contents.`],unsupported_type:["This kind of file isn\u2019t supported",`${gt.title.en} opens ${js()} files.`],path_outside_workspace:["This file is outside the workspace",""]},sendFailed:"The message was not sent.",contextFailed:"ZCode did not accept the reference.",where:{page:t=>`Page ${t}`,pages:(t,e)=>`Pages ${t}\u2013${e}`,pageLower:t=>`page ${t}`,slide:t=>`Slide ${t}`,slides:(t,e)=>`Slides ${t}\u2013${e}`,slideLower:t=>`slide ${t}`,shape:t=>`Slide ${t} \xB7 Shape`,paragraph:t=>`Paragraph ${t}`,paragraphs:(t,e)=>`Paragraphs ${t}\u2013${e}`,paragraphLower:t=>`paragraph ${t}`,table:t=>`Table ${t}`,cell:(t,e,n)=>`Table ${t} \xB7 R${e}C${n}`}},B5={title:gt.title["zh-CN"],openTitle:"\u6253\u5F00\u6587\u6863",openFile:"\u6253\u5F00\u6587\u4EF6",emptyTitle:`\u6253\u5F00\u4F60\u7684 ${Ci(W2,"zh-CN")} \u6587\u4EF6`,emptyDescription:`\u8FB9\u770B\u8FB9\u804A\uFF0C\u9009\u4E2D${Q2.zh}\u5373\u53EF\u5E26\u5165\u5BF9\u8BDD\u3002`,emptyCaption:`\u9009\u62E9\u672C\u5730\u6587\u4EF6 \xB7 ${js("zh-CN","or")}`,importing:"\u6B63\u5728\u5BFC\u5165\u2026",importTooLarge:`\u8BF7\u9009\u62E9\u4E0D\u8D85\u8FC7 ${Tm/1024/1024} MiB \u7684\u6587\u4EF6\u3002`,recent:"\u6700\u8FD1",switchDocument:"\u5207\u6362\u6587\u6863",pagesAndOutline:"\u9875\u9762\u4E0E\u76EE\u5F55",outlineOnly:"\u76EE\u5F55",pages:"\u9875\u9762",slides:"\u5E7B\u706F\u7247",outline:"\u76EE\u5F55",find:"\u67E5\u627E",findPlaceholder:"\u5728\u6587\u6863\u4E2D\u67E5\u627E",findCount:(t,e)=>`${t} / ${e}`,noResults:"\u65E0\u7ED3\u679C",previousMatch:"\u4E0A\u4E00\u4E2A\uFF08\u21E7Enter\uFF09",nextMatch:"\u4E0B\u4E00\u4E2A\uFF08Enter\uFF09",closeFind:"\u5173\u95ED\uFF08Esc\uFF09",more:"\u66F4\u591A",fitWidth:"\u9002\u5E94\u5BBD\u5EA6",fitPage:"\u9002\u5E94\u9875\u9762",actualSize:"\u5B9E\u9645\u5927\u5C0F",reload:"\u4ECE\u78C1\u76D8\u91CD\u65B0\u52A0\u8F7D",previousPage:"\u4E0A\u4E00\u9875",nextPage:"\u4E0B\u4E00\u9875",pageNumber:"\u9875\u7801",ofPages:t=>`/ ${t}`,zoomIn:"\u653E\u5927\uFF08\u2318+\uFF09",zoomOut:"\u7F29\u5C0F\uFF08\u2318\u2212\uFF09",fit:"\u9002\u5E94",addToChat:"\u6DFB\u52A0\u5230\u5BF9\u8BDD",addShort:"\u6DFB\u52A0",addToChatHint:"\u9644\u52A0\u5230\u4E0B\u4E00\u6761\u6D88\u606F\uFF08\u2318/Ctrl+Enter\uFF09",added:"\u5DF2\u6DFB\u52A0\u5230\u5BF9\u8BDD",ask:"\u63D0\u95EE",askPlaceholder:"\u5C31\u8FD9\u91CC\u63D0\u95EE\u2026",send:"\u53D1\u9001",cancel:"\u53D6\u6D88",sendKey:"\u53D1\u9001",cancelKey:"\u53D6\u6D88",copy:"\u590D\u5236",copied:"\u5DF2\u590D\u5236",agent:"Agent",agentOf:(t,e)=>`Agent \xB7 \u7B2C ${t} \u5904\uFF0C\u5171 ${e} \u5904`,nextTarget:"\u4E0B\u4E00\u5904",moreOn:(t,e)=>t===1?`${e}\u8FD8\u6709 1 \u5904`:`\u8FD8\u6709 ${t} \u5904`,close:"\u5173\u95ED",changed:"\u6587\u4EF6\u5DF2\u5728\u78C1\u76D8\u4E0A\u66F4\u6539\u3002",reloadShort:"\u91CD\u65B0\u52A0\u8F7D",dismiss:"\u5FFD\u7565",openAnother:"\u6253\u5F00\u5176\u4ED6\u6587\u4EF6",sidePanel:"\u5728\u4FA7\u680F\u6253\u5F00",meta:{pdf:t=>`${t} \u9875`,pptx:t=>`${t} \u5F20\u5E7B\u706F\u7247`,xlsx:t=>`${t} \u4E2A\u5DE5\u4F5C\u8868`,docx:()=>""},errors:{generic:["\u65E0\u6CD5\u6253\u5F00\u8BE5\u6587\u6863",""],password:["\u8BE5 PDF \u53D7\u5BC6\u7801\u4FDD\u62A4",`${Dz}\u6682\u4E0D\u652F\u6301\u6253\u5F00\u52A0\u5BC6\u6587\u4EF6\u3002`],not_found:["\u8BE5\u6587\u4EF6\u5DF2\u4E0D\u5B58\u5728","\u5B83\u53EF\u80FD\u5DF2\u88AB\u79FB\u52A8\u6216\u5220\u9664\u3002"],file_too_large:["\u6587\u4EF6\u592A\u5927\uFF0C\u65E0\u6CD5\u6253\u5F00",""],corrupt_file:["\u8BE5\u6587\u4EF6\u4F3C\u4E4E\u5DF2\u635F\u574F",`${Dz}\u65E0\u6CD5\u8BFB\u53D6\u5176\u5185\u5BB9\u3002`],unsupported_type:["\u4E0D\u652F\u6301\u8FD9\u79CD\u6587\u4EF6",`${Dz}\u53EF\u4EE5\u6253\u5F00 ${js("zh-CN")} \u6587\u4EF6\u3002`],path_outside_workspace:["\u8BE5\u6587\u4EF6\u4E0D\u5728\u5DE5\u4F5C\u533A\u5185",""]},sendFailed:"\u6D88\u606F\u672A\u53D1\u9001\u3002",contextFailed:"ZCode \u672A\u63A5\u53D7\u8BE5\u5F15\u7528\u3002",where:{page:t=>`\u7B2C ${t} \u9875`,pages:(t,e)=>`\u7B2C ${t}\u2013${e} \u9875`,pageLower:t=>`\u7B2C ${t} \u9875`,slide:t=>`\u7B2C ${t} \u5F20\u5E7B\u706F\u7247`,slides:(t,e)=>`\u7B2C ${t}\u2013${e} \u5F20\u5E7B\u706F\u7247`,slideLower:t=>`\u7B2C ${t} \u5F20\u5E7B\u706F\u7247`,shape:t=>`\u7B2C ${t} \u5F20\u5E7B\u706F\u7247 \xB7 \u5F62\u72B6`,paragraph:t=>`\u7B2C ${t} \u6BB5`,paragraphs:(t,e)=>`\u7B2C ${t}\u2013${e} \u6BB5`,paragraphLower:t=>`\u7B2C ${t} \u6BB5`,table:t=>`\u8868\u683C ${t}`,cell:(t,e,n)=>`\u8868\u683C ${t} \xB7 R${e}C${n}`}},ej=t=>t?.toLowerCase().startsWith("zh")?B5:F5;function Vy(t,e,n=!1){let r=e.where,i;if(i=/^page:(\d+)(?:-(\d+))?$/.exec(t))return i[2]?r.pages(i[1],i[2]):n?r.pageLower(i[1]):r.page(i[1]);if(i=/^slide:(\d+)\/shape:/.exec(t))return r.shape(i[1]);if(i=/^slide:(\d+)(?:-(\d+))?$/.exec(t))return i[2]?r.slides(i[1],i[2]):n?r.slideLower(i[1]):r.slide(i[1]);if(i=/^p:(\d+)(?:-(\d+))?$/.exec(t))return i[2]?r.paragraphs(i[1],i[2]):n?r.paragraphLower(i[1]):r.paragraph(i[1]);if(i=/^t:(\d+)\/r(\d+)c(\d+)$/.exec(t))return r.cell(i[1],i[2],i[3]);if(i=/^t:(\d+)$/.exec(t))return r.table(i[1]);let o=t.lastIndexOf("!");return o>0?`${t.slice(0,o).replace(/^'(.*)'$/,"$1").replace(/''/g,"'")} \xB7 ${t.slice(o+1)}`:t.replace(/^'(.*)'$/,"$1")}var Lz=lt(An(),1),Z5={search:'<circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/>',x:'<path d="M18 6 6 18"/><path d="m6 6 12 12"/>',"chevron-up":'<path d="m18 15-6-6-6 6"/>',"chevron-down":'<path d="m6 9 6 6 6-6"/>',minus:'<path d="M5 12h14"/>',plus:'<path d="M5 12h14"/><path d="M12 5v14"/>',ellipsis:'<circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/><circle cx="5" cy="12" r="1"/>',"panel-left":'<rect width="18" height="18" x="3" y="3" rx="2"/><path d="M9 3v18"/>',"file-text":'<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="M10 9H8"/><path d="M16 13H8"/><path d="M16 17H8"/>',copy:'<rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/>',"message-square-plus":'<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/><path d="M12 7v6"/><path d="M9 10h6"/>',"message-circle-question":'<path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z"/><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/><path d="M12 17h.01"/>',check:'<path d="M20 6 9 17l-5-5"/>',"rotate-cw":'<path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/>',"arrow-down":'<path d="M12 5v14"/><path d="m19 12-7 7-7-7"/>',"arrow-up":'<path d="m5 12 7-7 7 7"/><path d="M12 19V5"/>',"folder-open":'<path d="m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"/>',"maximize-2":'<polyline points="15 3 21 3 21 9"/><polyline points="9 21 3 21 3 15"/><line x1="21" x2="14" y1="3" y2="10"/><line x1="3" x2="10" y1="21" y2="14"/>'};function Fe({name:t,size:e=14,className:n}){return(0,Lz.jsx)("svg",{className:`icon${n?` ${n}`:""}`,width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",dangerouslySetInnerHTML:{__html:Z5[t]}})}var G5={pdf:"PDF",docx:"W",xlsx:"X",pptx:"P"};function rj({kind:t}){return(0,Lz.jsx)("span",{className:`filetype ${t}`,"aria-hidden":"true",children:G5[t]})}var _o=lt(Jn(),1);var _e=lt(An(),1);function K5({handle:t,page:e,width:n,ratio:r,current:i,onPick:o,root:a}){let s=(0,_o.useRef)(null);return(0,_o.useEffect)(()=>{let l=s.current;if(!l||!t.thumbnail)return;let c=!1,u=new IntersectionObserver(d=>{c||!d.some(h=>h.isIntersecting)||(c=!0,u.disconnect(),t.thumbnail(e,n).then(h=>{l.replaceChildren(h),l.style.height=""},()=>{}))},{root:a.current,rootMargin:"300px 0px"});return u.observe(l),()=>u.disconnect()},[t,e,n,a]),(0,_e.jsxs)("button",{type:"button",className:`thumb${i?" on":""}`,"aria-current":i?"page":void 0,onClick:()=>o(e),"data-page":e,children:[(0,_e.jsx)("div",{ref:s,className:"mini",style:{width:n,height:Math.round(n*r)}}),(0,_e.jsx)("span",{children:e})]})}var oj=t=>/^(?:page|slide):(\d+)/.exec(t)?.[1]??"";function aj({t,info:e,handle:n,page:r,tab:i,docked:o,onTab:a,onPage:s,onOutline:l}){let c=(0,_o.useRef)(null),u=!!(n?.thumbnail&&r),d=e.outline.length>0,h=u&&(i==="pages"||!d)?"pages":"outline",f=e.kind==="pptx"?9/16:1.294;(0,_o.useEffect)(()=>{let p=c.current?.querySelector("[aria-current=page]");p&&c.current&&(c.current.scrollTop=p.offsetTop-c.current.clientHeight/3)},[h]);let m=(()=>{if(!r)return-1;let p=-1;return e.outline.forEach((y,g)=>{let v=Number(oj(y.at));v&&v<=r.current&&(p=g)}),p})();return(0,_e.jsxs)("nav",{className:`drawer${o?" docked":""}`,"aria-label":t.pagesAndOutline,children:[u&&d?(0,_e.jsxs)("div",{className:"seg",role:"tablist",children:[(0,_e.jsx)("button",{type:"button",role:"tab","aria-selected":h==="pages",className:h==="pages"?"on":"",onClick:()=>a("pages"),children:e.kind==="pptx"?t.slides:t.pages}),(0,_e.jsx)("button",{type:"button",role:"tab","aria-selected":h==="outline",className:h==="outline"?"on":"",onClick:()=>a("outline"),children:t.outline})]}):null,(0,_e.jsx)("div",{ref:c,className:h==="pages"?"thumbs":"outline",children:h==="pages"&&n&&r?Array.from({length:r.count},(p,y)=>(0,_e.jsx)(K5,{handle:n,page:y+1,width:136,ratio:f,current:r.current===y+1,onPick:s,root:c},y)):e.outline.map((p,y)=>(0,_e.jsxs)("button",{type:"button",className:`oi level-${Math.min(3,Math.max(1,p.level))}${y===m?" on":""}`,"aria-current":y===m?"page":void 0,title:p.label,onClick:()=>l(p.at),children:[(0,_e.jsx)("span",{className:"label",children:p.label}),(0,_e.jsx)("span",{className:"n",children:oj(p.at)})]},`${p.at}-${y}`))})]})}function sj({t,onBrowse:e,importing:n}){return(0,_e.jsx)("div",{className:"empty",children:(0,_e.jsxs)("div",{className:"empty-content",children:[(0,_e.jsx)("h3",{children:t.emptyTitle}),(0,_e.jsx)("p",{className:"empty-description",children:t.emptyDescription}),(0,_e.jsxs)("button",{type:"button",className:"btn empty-open",onClick:e,disabled:n,children:[(0,_e.jsx)(Fe,{name:"folder-open",size:16}),n?t.importing:t.openFile]}),(0,_e.jsx)("p",{className:"empty-caption",children:t.emptyCaption})]})})}var Y5=["title","subtitle","line","line","short","heading","line","line","line","mid","figure"];function Gy({kind:t}){if(t==="xlsx")return(0,_e.jsx)("div",{className:"skeleton sheet","aria-busy":"true",children:Array.from({length:18},(n,r)=>(0,_e.jsx)("div",{className:"skel-row"},r))});let e=t==="pptx";return(0,_e.jsx)("div",{className:"skeleton","aria-busy":"true",children:[0,1].map(n=>(0,_e.jsxs)("div",{className:`skelpage${e?" slide":""}`,children:[n===0&&!e?Y5.map((r,i)=>(0,_e.jsx)("div",{className:`skel ${r}`},i)):null,n===0&&e?(0,_e.jsxs)(_e.Fragment,{children:[(0,_e.jsx)("div",{className:"skel title left"}),(0,_e.jsx)("div",{className:"skel line"}),(0,_e.jsx)("div",{className:"skel mid"})]}):null]},n))})}function Ky({t,title:e,detail:n,onOpenAnother:r}){return(0,_e.jsxs)("div",{className:"failed",role:"alert",children:[(0,_e.jsx)(Fe,{name:"file-text",size:28,className:"subtlest"}),(0,_e.jsxs)("div",{children:[(0,_e.jsx)("h3",{children:e}),n?(0,_e.jsx)("p",{children:n}):null]}),(0,_e.jsx)("button",{type:"button",className:"btn secondary",onClick:r,children:t.openAnother})]})}function lj({t,onReload:e,onDismiss:n}){return(0,_e.jsxs)("div",{className:"banner",role:"status",children:[(0,_e.jsx)("span",{children:t.changed}),(0,_e.jsx)("button",{type:"button",className:"btn sm primary",onClick:e,children:t.reloadShort}),(0,_e.jsx)("button",{type:"button",className:"btn icon sm dim",title:t.dismiss,"aria-label":t.dismiss,onClick:n,children:(0,_e.jsx)(Fe,{name:"x"})})]})}function X5({inputRef:t,t:e,importing:n,onImporting:r,onOpen:i,onError:o}){return(0,_e.jsx)("input",{ref:t,type:"file",hidden:!0,accept:tr.map(a=>`.${a}`).join(","),disabled:n,onChange:async a=>{let s=a.currentTarget.files?.[0];if(a.currentTarget.value="",!!s){r(!0);try{if(s.size>Tm)throw new Error(e.importTooLarge);i(await K2(s))}catch(l){o(l,s.name)}finally{r(!1)}}}})}function cj(t,e,n){let r=(0,_o.useRef)(null),[i,o]=(0,_o.useState)(!1);return{importing:i,browse:()=>r.current?.click(),input:(0,_e.jsx)(X5,{inputRef:r,t,importing:i,onImporting:o,onOpen:e,onError:n})}}var mn=lt(An(),1);function uj({appRef:t,canvasRef:e,t:n,path:r,info:i,kind:o,showSkeleton:a,failure:s,nothing:l,onExpand:c,children:u}){return(0,mn.jsxs)("div",{ref:t,className:"app inline",children:[(0,mn.jsxs)("header",{className:"docbar",children:[(0,mn.jsxs)("div",{className:"doctitle static",title:r??void 0,children:[(0,mn.jsx)("span",{className:"name",children:r?Us(r):n.title}),i&&n.meta[i.kind](i.units)?(0,mn.jsx)("span",{className:"meta",children:n.meta[i.kind](i.units)}):null]}),(0,mn.jsx)("span",{className:"spacer"}),(0,mn.jsxs)("button",{type:"button",className:"btn sm",title:n.sidePanel,onClick:c,children:[(0,mn.jsx)(Fe,{name:"maximize-2",size:12}),n.sidePanel]})]}),(0,mn.jsx)("div",{className:"stage",children:(0,mn.jsxs)("div",{ref:e,className:"canvas",children:[u,a?(0,mn.jsx)(Gy,{kind:o}):null,s?(0,mn.jsx)(Ky,{t:n,title:s.title,detail:s.detail,onOpenAnother:c}):null,l?(0,mn.jsx)("div",{className:"failed muted",children:n.openTitle}):null,(0,mn.jsx)("button",{type:"button",className:"glance-cover","aria-label":n.sidePanel,onClick:c})]})})]})}var Vn=lt(Jn(),1);var Yy=lt(Jn(),1),qs=8;function jz(t,e,n){let r=(0,Yy.useRef)(null),{side:i,offset:o=8,dock:a=!1}=n;return(0,Yy.useLayoutEffect)(()=>{let s=r.current,l=t.current;if(!s||!l)return;let c=0,u=()=>{c=0;let m=l.getBoundingClientRect(),p=s.offsetWidth,y=s.offsetHeight,g=e?.()??null,v=(I,D,H,ge)=>{s.style.visibility="",s.style.left=`${Math.round(I)}px`,s.style.top=`${Math.round(D)}px`,s.dataset.side=H,s.style.setProperty("--tip",`${Math.round(Math.max(14,Math.min(p-14,ge-I)))}px`)};if(!g){a?v((m.width-p)/2,qs,"none",m.width/2):s.style.visibility="hidden";return}if(g.bottom<m.top+4||g.top>m.bottom-4){s.style.visibility="hidden";return}let S=(g.left+g.right)/2-m.left,_=Math.max(qs,Math.min(m.width-p-qs,S-p/2)),$=g.top-m.top-y-o,w=g.bottom-m.top+o,A=$>=qs,k=w+y<=m.height-qs;(i==="top"||!k)&&A?v(_,$,"top",S):k?v(_,w,"bottom",S):v(_,i==="top"?qs:m.height-y-qs,"none",S)},d=()=>{c||(c=requestAnimationFrame(u))};u(),l.addEventListener("scroll",d,{capture:!0,passive:!0});let h=new ResizeObserver(d);h.observe(l),h.observe(s);let f=setInterval(d,250);return()=>{l.removeEventListener("scroll",d,{capture:!0}),h.disconnect(),clearInterval(f),c&&cancelAnimationFrame(c)}},[t,e,i,o,a]),r}var X=lt(An(),1);function Uz({className:t,onClose:e,children:n,label:r}){let i=(0,Vn.useRef)(null);(0,Vn.useEffect)(()=>{let a=l=>{let c=l.target;!i.current?.contains(c)&&!c.closest?.("[data-menu-trigger]")&&e()},s=l=>{l.key==="Escape"&&(l.stopPropagation(),e())};return document.addEventListener("pointerdown",a,!0),document.addEventListener("keydown",s,!0),i.current?.querySelector("[role^=menuitem]")?.focus(),()=>{document.removeEventListener("pointerdown",a,!0),document.removeEventListener("keydown",s,!0)}},[e]);let o=a=>{if(a.key!=="ArrowDown"&&a.key!=="ArrowUp")return;a.preventDefault();let s=[...i.current?.querySelectorAll("[role^=menuitem]")??[]],l=s.indexOf(document.activeElement);s[(l+(a.key==="ArrowDown"?1:-1)+s.length)%s.length]?.focus()};return(0,X.jsx)("div",{ref:i,className:`menu ${t}`,role:"menu","aria-label":r,onKeyDown:o,children:n})}function $a({icon:t,checked:e,children:n,hint:r,onSelect:i}){return(0,X.jsxs)("button",{type:"button",role:e===void 0?"menuitem":"menuitemradio","aria-checked":e,className:"mi",onClick:i,children:[(0,X.jsx)("span",{className:"mi-icon",children:e?(0,X.jsx)(Fe,{name:"check",size:16}):t}),(0,X.jsx)("span",{className:"mi-label",children:n}),r?(0,X.jsx)("span",{className:"mi-hint",children:r}):null]})}function hj({t,query:e,total:n,index:r,onQuery:i,onStep:o,onClose:a}){let s=(0,Vn.useRef)(null);(0,Vn.useEffect)(()=>{s.current?.focus(),s.current?.select()},[]);let l=!e.trim()||n===null?"":n?t.findCount(r+1,n):t.noResults;return(0,X.jsxs)("div",{className:"docbar findbar",role:"search",children:[(0,X.jsxs)("label",{className:"findfield",children:[(0,X.jsx)(Fe,{name:"search",className:"muted"}),(0,X.jsx)("input",{ref:s,className:"find-input",type:"text","aria-label":t.find,placeholder:t.findPlaceholder,value:e,onChange:c=>i(c.target.value),onKeyDown:c=>{c.key==="Enter"?(c.preventDefault(),o(c.shiftKey?-1:1)):c.key==="Escape"&&(c.preventDefault(),c.stopPropagation(),a())}}),(0,X.jsx)("span",{className:"count","aria-live":"polite",children:l})]}),(0,X.jsx)("button",{type:"button",className:"btn icon dim",title:t.previousMatch,"aria-label":t.previousMatch,disabled:!n,onClick:()=>o(-1),children:(0,X.jsx)(Fe,{name:"chevron-up"})}),(0,X.jsx)("button",{type:"button",className:"btn icon dim",title:t.nextMatch,"aria-label":t.nextMatch,disabled:!n,onClick:()=>o(1),children:(0,X.jsx)(Fe,{name:"chevron-down"})}),(0,X.jsx)("button",{type:"button",className:"btn icon dim",title:t.closeFind,"aria-label":t.closeFind,onClick:a,children:(0,X.jsx)(Fe,{name:"x"})})]})}var J5=1500;function fj({t,frame:e,page:n,zoom:r,onPage:i,onZoom:o,onFit:a}){let s=(0,Vn.useRef)(null),[l,c]=(0,Vn.useState)(!0),[u,d]=(0,Vn.useState)(null),h=(0,Vn.useRef)(!1);(0,Vn.useEffect)(()=>{let m=e.current;if(!m)return;let p=0,y=()=>{clearTimeout(p),p=window.setTimeout(()=>{!h.current&&!s.current?.contains(document.activeElement)&&c(!1)},J5)},g=()=>{c(!0),y()},v=S=>{let _=m.getBoundingClientRect();S.clientY>_.bottom-80&&g()};return m.addEventListener("scroll",g,{capture:!0,passive:!0}),m.addEventListener("pointermove",v,{passive:!0}),y(),()=>{clearTimeout(p),m.removeEventListener("scroll",g,{capture:!0}),m.removeEventListener("pointermove",v)}},[e]);let f=()=>{let m=Number(u);d(null),Number.isInteger(m)&&m>=1&&i(Math.min(m,n.count))};return(0,X.jsxs)("div",{ref:s,className:`pill${l?"":" faded"}`,onPointerEnter:()=>{h.current=!0,c(!0)},onPointerLeave:()=>{h.current=!1},onFocus:()=>c(!0),children:[(0,X.jsx)("button",{type:"button",className:"btn icon sm dim",title:t.previousPage,"aria-label":t.previousPage,disabled:n.current<=1,onClick:()=>i(n.current-1),children:(0,X.jsx)(Fe,{name:"chevron-up"})}),(0,X.jsxs)("span",{className:"pg",children:[(0,X.jsx)("input",{className:"pgin","aria-label":t.pageNumber,inputMode:"numeric",style:{width:`${Math.max(2,String(n.count).length)+1.6}ch`},value:u??String(n.current),onFocus:m=>{d(String(n.current)),m.target.select()},onChange:m=>d(m.target.value.replace(/\D/g,"")),onBlur:()=>d(null),onKeyDown:m=>{m.key==="Enter"?(f(),m.currentTarget.blur()):m.key==="Escape"&&(m.stopPropagation(),d(null),m.currentTarget.blur())}}),(0,X.jsx)("span",{children:t.ofPages(n.count)})]}),(0,X.jsx)("button",{type:"button",className:"btn icon sm dim",title:t.nextPage,"aria-label":t.nextPage,disabled:n.current>=n.count,onClick:()=>i(n.current+1),children:(0,X.jsx)(Fe,{name:"chevron-down"})}),r?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)("span",{className:"vsep"}),(0,X.jsx)("button",{type:"button",className:"btn icon sm dim",title:t.zoomOut,"aria-label":t.zoomOut,disabled:r.mode!=="width"&&r.percent<=25,onClick:()=>o(-1),children:(0,X.jsx)(Fe,{name:"minus"})}),(0,X.jsx)("button",{type:"button",className:"zoom",title:t.fitWidth,onClick:a,children:r.mode==="width"?t.fit:`${r.percent}%`}),(0,X.jsx)("button",{type:"button",className:"btn icon sm dim",title:t.zoomIn,"aria-label":t.zoomIn,disabled:r.mode!=="width"&&r.percent>=400,onClick:()=>o(1),children:(0,X.jsx)(Fe,{name:"plus"})})]}):null]})}var dj=t=>{t.target.closest("textarea")||t.preventDefault()};function mj({t,frame:e,locate:n,text:r,label:i,quote:o,short:a,mode:s,canAsk:l,copied:c,onAdd:u,onAsk:d,onCopy:h,onCancelAsk:f,onSend:m}){let p=s==="ask",y=jz(e,n,{side:p?"bottom":"top",dock:!0}),[g,v]=(0,Vn.useState)(""),[S,_]=(0,Vn.useState)(!1),$=async()=>{if(!g.trim()||S)return;_(!0);let w=await m(g.trim());_(!1),w&&v("")};return p?(0,X.jsxs)("div",{ref:y,className:"pop ask",role:"dialog","aria-label":t.ask,onMouseDown:dj,children:[(0,X.jsxs)("div",{className:"ctx",children:[(0,X.jsx)("span",{className:"where",children:i}),o?(0,X.jsxs)("span",{className:"q",children:["\u201C",o,"\u201D"]}):null]}),(0,X.jsx)("textarea",{autoFocus:!0,className:"textarea",rows:2,"aria-label":t.askPlaceholder,placeholder:t.askPlaceholder,value:g,onChange:w=>v(w.target.value),onKeyDown:w=>{w.key==="Enter"&&!w.shiftKey&&!w.nativeEvent.isComposing?(w.preventDefault(),$()):w.key==="Escape"&&(w.preventDefault(),w.stopPropagation(),f())}}),(0,X.jsxs)("div",{className:"row",children:[(0,X.jsxs)("span",{className:"hint",children:[(0,X.jsx)("kbd",{children:"\u21B5"})," ",t.sendKey]}),(0,X.jsx)("button",{type:"button",className:"btn sm",onClick:f,children:t.cancel}),(0,X.jsx)("button",{type:"button",className:"btn sm primary",disabled:!g.trim()||S,onClick:()=>void $(),children:t.send})]})]}):(0,X.jsxs)("div",{ref:y,className:"pop bar",role:"toolbar","aria-label":i,onMouseDown:dj,children:[r?null:(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)("span",{className:"where",children:i}),(0,X.jsx)("span",{className:"vsep"})]}),(0,X.jsx)("button",{type:"button",className:"btn lg",title:t.addToChatHint,onClick:u,disabled:s==="added",children:s==="added"?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(Fe,{name:"check",size:16,className:"ok"}),t.added]}):(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(Fe,{name:"message-square-plus",size:16}),a?t.addShort:t.addToChat]})}),l?(0,X.jsxs)("button",{type:"button",className:"btn lg",onClick:d,children:[(0,X.jsx)(Fe,{name:"message-circle-question",size:16}),t.ask]}):null,r?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)("span",{className:"vsep"}),(0,X.jsx)("button",{type:"button",className:"btn icon lg dim",title:c?t.copied:t.copy,"aria-label":c?t.copied:t.copy,onClick:h,children:(0,X.jsx)(Fe,{name:c?"check":"copy"})})]}):null]})}function pj({t,frame:e,locate:n,note:r,index:i,total:o,onNext:a,onClose:s}){let l=jz(e,n,{side:"bottom",offset:6,dock:!0});return(0,X.jsxs)("div",{ref:l,className:"callout",role:"note",children:[(0,X.jsxs)("div",{className:"body",children:[(0,X.jsxs)("div",{className:"who",children:[(0,X.jsx)("span",{className:"dot"}),o>1?t.agentOf(i+1,o):t.agent]}),r?(0,X.jsx)("div",{className:"text",children:r}):null]}),o>1?(0,X.jsx)("button",{type:"button",className:"btn icon sm dim",title:t.nextTarget,"aria-label":t.nextTarget,onClick:a,children:(0,X.jsx)(Fe,{name:"chevron-down"})}):null,(0,X.jsx)("button",{type:"button",className:"btn icon sm dim",title:t.close,"aria-label":t.close,onClick:s,children:(0,X.jsx)(Fe,{name:"x"})})]})}function gj({text:t,down:e,raised:n,onClick:r}){return(0,X.jsxs)("button",{type:"button",className:`chip offscreen${n?" raised":""}`,onClick:r,children:[(0,X.jsx)("span",{className:"dot"}),t,(0,X.jsx)(Fe,{name:e?"arrow-down":"arrow-up",size:12})]})}function vj(t,e){return t.moreOn(e.length,Vy(e[0],t,!0))}var At=lt(An(),1);function bj({t,recent:e,currentPath:n,onOpen:r,onBrowse:i,onClose:o}){return(0,At.jsxs)(Uz,{className:"switcher",label:t.switchDocument,onClose:o,children:[e.length?(0,At.jsx)("div",{className:"mlabel",children:t.recent}):null,e.map(a=>(0,At.jsx)($a,{icon:(0,At.jsx)(rj,{kind:a.kind}),hint:a.path===n?(0,At.jsx)(Fe,{name:"check",size:16}):Us(G2(a.path)),onSelect:()=>a.path===n?o():r(a.path),children:Us(a.path)},a.path)),e.length?(0,At.jsx)("div",{className:"msep"}):null,(0,At.jsx)($a,{icon:(0,At.jsx)(Fe,{name:"folder-open",size:16}),onSelect:i,children:t.openFile})]})}function yj({t,zoomable:e,zoomMode:n,onFit:r,onFind:i,onReload:o,onClose:a}){return(0,At.jsxs)(Uz,{className:"more",label:t.more,onClose:a,children:[e?(0,At.jsxs)(At.Fragment,{children:[(0,At.jsx)($a,{checked:n==="width",onSelect:()=>r("width"),children:t.fitWidth}),(0,At.jsx)($a,{checked:n==="page",onSelect:()=>r("page"),children:t.fitPage}),(0,At.jsx)($a,{checked:n==="actual",hint:"100%",onSelect:()=>r("actual"),children:t.actualSize}),(0,At.jsx)("div",{className:"msep"})]}):null,(0,At.jsx)($a,{icon:(0,At.jsx)(Fe,{name:"search",size:16}),hint:"\u2318F",onSelect:i,children:t.find}),(0,At.jsx)($a,{icon:(0,At.jsx)(Fe,{name:"rotate-cw",size:16}),onSelect:o,children:t.reload})]})}var nr=lt(Jn(),1),Pm={open:!1,query:"",total:null,index:-1};function Sj({viewer:t,docRef:e,ready:n,onOpen:r}){let[i,o]=(0,nr.useState)(Pm),a=(0,nr.useRef)(0),s=(0,nr.useCallback)(()=>{e.current&&(r(),o(d=>({...d,open:!0})),requestAnimationFrame(()=>{let d=document.querySelector(".findbar .find-input");d?.focus(),d?.select()}))},[e,r]),l=(0,nr.useCallback)(()=>{a.current++,t.current?.clearFind(),o(Pm)},[t]),c=(0,nr.useCallback)(d=>{o(h=>({...h,query:d,total:d.trim()?h.total:null}))},[]);(0,nr.useEffect)(()=>{if(!i.open||!n)return;let d=++a.current,h=setTimeout(async()=>{let f=t.current;if(!f)return;let m=await f.find(i.query).catch(()=>0);d===a.current&&(o(p=>({...p,total:m,index:m?0:-1})),m&&f.findGo(0))},200);return()=>clearTimeout(h)},[i.open,i.query,n,t]);let u=(0,nr.useCallback)(d=>{if(!i.total)return;let h=(i.index+d+i.total)%i.total;o(f=>({...f,index:h})),t.current?.findGo(h)},[i.total,i.index,t]);return{find:i,setFind:o,openFind:s,closeFind:l,queryFind:c,stepFind:u}}var _j=lt(Jn(),1);function wj(t,e){(0,_j.useEffect)(()=>{Ii().handleTool("capture_view",async r=>{let i=t.current;if(!i||!e.current)throw new Error(`No document is open in the ${gt.title.en} panel. Call open_document first.`);let o=null;if(typeof r.anchor=="string"&&r.anchor.trim()){let l=P2(r.anchor);if(l.path.replace(/^\.\//,"")!==i.info.path)throw new Error(`The panel shows ${i.info.path}, not ${l.path}. Call open_document with that path first.`);o=l.at}let a=typeof r.maxWidth=="number"?Math.min(2e3,Math.max(320,r.maxWidth)):1600,s=await e.current.capture(o,a);return{content:[{type:"image",data:s.data,mimeType:"image/png"},{type:"text",text:`Captured ${km(i.info.path,s.at)} (${s.width}\xD7${s.height} px).`}]}})},[t,e])}var Xy=lt(Jn(),1);function xj(t,e){let[n,r]=(0,Xy.useState)(null);return(0,Xy.useEffect)(()=>{let i=t.current;if(!i||!e||e.targets.length<2){r(null);return}let o=0,a=()=>{o=0;let c=i.getBoundingClientRect(),u=[],d=[];e.targets.forEach((f,m)=>{if(m===e.index)return;let p=f.locate();p&&(p.top>c.bottom-8?u.push(m):p.bottom<c.top+8&&d.push(m))});let h=u.length?{indexes:u,down:!0}:d.length?{indexes:d,down:!1}:null;r(f=>JSON.stringify(f)===JSON.stringify(h)?f:h)},s=()=>{o||(o=requestAnimationFrame(a))};a(),i.addEventListener("scroll",s,{capture:!0,passive:!0});let l=setInterval(s,500);return()=>{i.removeEventListener("scroll",s,{capture:!0}),clearInterval(l),o&&cancelAnimationFrame(o)}},[e,t]),[n,r]}var $j=lt(Jn(),1);function Aj({docRef:t,viewer:e,picked:n,addReference:r,openFind:i,closeFind:o,clearSelection:a,paged:s,page:l,goToPage:c,drawer:u,setDrawer:d,docked:h,find:f,agent:m,setAgent:p}){(0,$j.useEffect)(()=>{let y=g=>{if(g.defaultPrevented)return;let v=g.metaKey||g.ctrlKey,S=g.target?.closest?.("input, textarea, [contenteditable]"),_=g.key.toLowerCase();if(v&&_==="f"&&t.current)g.preventDefault(),i();else if(v&&g.key==="Enter"&&n)g.preventDefault(),r();else if(v&&(g.key==="="||g.key==="+"))g.preventDefault(),e.current?.zoom(1);else if(v&&g.key==="-")g.preventDefault(),e.current?.zoom(-1);else if(v&&g.key==="0")g.preventDefault(),e.current?.fit("width");else if(!v&&!S&&s&&l&&["ArrowLeft","ArrowRight","PageUp","PageDown"].includes(g.key)){g.preventDefault();let $=g.key==="ArrowLeft"||g.key==="PageUp";c(l.current+($?-1:1))}else if(g.key==="Escape"&&!S){if(n)a();else if(u.open&&!h)d($=>({...$,open:!1}));else if(f.open)o();else if(m?.visible)p({...m,visible:!1});else return;g.preventDefault()}};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[n,r,i,o,a,s,l,c,u.open,h,f.open,m,t,e,d,p])}var Be=lt(Jn(),1);var qz="zcode-cjk-fallback",Tj="cjk-fallback.json",zj="U+1100-11FF, U+2E80-2FDF, U+2FF0-303F, U+3040-30FF, U+3100-31FF, U+3200-33FF, U+3400-4DBF, U+4E00-9FFF, U+A960-A97F, U+AC00-D7FF, U+F900-FAFF, U+FE10-FE1F, U+FE30-FE4F, U+FF00-FFEF, U+20000-2FA1F",Fz={"sc-serif":["STSongti-SC-Regular","Songti SC Regular","STSong","SimSun","NSimSun","Noto Serif CJK SC","NotoSerifCJKsc-Regular","Noto Serif SC","NotoSerifSC-Regular","Source Han Serif SC","SourceHanSerifSC-Regular","AR PL UMing CN","AR PL SungtiL GB"],"sc-sans":["PingFangSC-Regular","PingFang SC Regular","HiraginoSansGB-W3","Hiragino Sans GB W3","STHeitiSC-Light","Heiti SC Light","Microsoft YaHei","SimHei","Noto Sans CJK SC","NotoSansCJKsc-Regular","Noto Sans SC","NotoSansSC-Regular","Source Han Sans SC","SourceHanSansSC-Regular","WenQuanYi Micro Hei","WenQuanYi Zen Hei"],"sc-kai":["STKaitiSC-Regular","Kaiti SC Regular","STKaiti","KaiTi","KaiTi_GB2312","AR PL UKai CN","LXGW WenKai","LXGWWenKai-Regular"],"sc-fang":["STFangsong","FangSong","FangSong_GB2312"],"tc-serif":["STSongti-TC-Regular","Songti TC Regular","LiSongPro","LiSong Pro","PMingLiU","MingLiU","Noto Serif CJK TC","NotoSerifCJKtc-Regular","Noto Serif TC","Source Han Serif TC","SourceHanSerifTC-Regular","AR PL UMing TW"],"tc-sans":["PingFangTC-Regular","PingFang TC Regular","STHeitiTC-Light","Heiti TC Light","Microsoft JhengHei","Noto Sans CJK TC","NotoSansCJKtc-Regular","Noto Sans TC","Source Han Sans TC","SourceHanSansTC-Regular","WenQuanYi Zen Hei"],"tc-kai":["STKaitiTC-Regular","Kaiti TC Regular","BiauKaiTC-Regular","BiauKaiTC Regular","DFKai-SB","AR PL UKai TW"],"jp-serif":["HiraMinProN-W3","Hiragino Mincho ProN W3","Yu Mincho","YuMincho-Regular","MS Mincho","MS PMincho","Noto Serif CJK JP","NotoSerifCJKjp-Regular","Noto Serif JP","Source Han Serif","SourceHanSerif-Regular","IPAexMincho","IPAMincho"],"jp-sans":["HiraginoSans-W3","Hiragino Sans W3","HiraKakuProN-W3","Hiragino Kaku Gothic ProN W3","Yu Gothic","YuGothic-Medium","Meiryo","MS Gothic","MS PGothic","Noto Sans CJK JP","NotoSansCJKjp-Regular","Noto Sans JP","Source Han Sans","SourceHanSans-Regular","IPAexGothic","IPAGothic"],"kr-serif":["AppleMyungjo","AppleMyungjo Regular","Batang","Noto Serif CJK KR","NotoSerifCJKkr-Regular","Noto Serif KR","Source Han Serif K","SourceHanSerifK-Regular","UnBatang","NanumMyeongjo"],"kr-sans":["AppleSDGothicNeo-Regular","Apple SD Gothic Neo Regular","Malgun Gothic","Gulim","Dotum","Noto Sans CJK KR","NotoSansCJKkr-Regular","Noto Sans KR","Source Han Sans K","SourceHanSansK-Regular","NanumGothic","UnDotum"]},Bz=t=>`zcode-cjk-${t}`,W5=[[/fang|仿/,"fang"],[/kai|楷/,"kai"],[/hei(?!sei)|gothic|kakugo|kozgo|gulim|dotum|yuanti|ゴシック|黑|黒|굴림|돋움|고딕/,"sans"],[/song|sung|simsun|ming|mincho|kozmin|ryumin|heiseimin|batang|myeongjo|myungjo|宋|明|바탕|명조/,"serif"]],Q5=[[/sans/,"sans"],[/serif/,"serif"]],eG=[[/^hy|batang|gulim|dotum|malgun|myeongjo|myungjo|nanum|^un(batang|dotum)|applesdgothic|cjkkr|(kr|ko)\b|바탕|굴림|돋움|명조|고딕/,"kr"],[/^msung|^mhei|mingliu|dfkai|biaukai|jhenghei|lisong|cjktc|(tc|tw|hk)\b|細明|標楷/,"tc"],[/heisei|mincho|kozmin|kozgo|ryumin|gothicbbb|hira(kaku|min|maru)|hiraginosans(?!gb)|yu(gothic|mincho)|meiryo|ms-?p?gothic|ipa(ex)?(mincho|gothic)|cjkjp|jp\b|明朝|ゴシック/,"jp"],[/simsun|simhei|stsong|stheiti|stkaiti|stfangsong|yahei|^fz|songti|heiti|kaiti|fangsong|gb2312|cjksc|(sc|cn|gb)\b|宋|黑|楷|仿/,"sc"]],tG=[["utf-8",null],["gbk","sc"],["big5","tc"],["shift_jis","jp"],["euc-kr","kr"]];function Ej(t){let e=t.replace(/[\s_]+/g,"").toLowerCase(),n=W5.find(([o])=>o.test(e))?.[1]??null,r=eG.find(([o])=>o.test(e))?.[1]??null;if(!n&&!r)return null;let i=n??Q5.find(([o])=>o.test(e))?.[1]??null;return{script:r,style:i}}function nG(t){let e=t.replace(/^[A-Z]{6}\+/,"");if(!/[\x80-\xff]/.test(e)||/[\u0100-\uffff]/.test(e)){let r=Ej(e);return r&&{script:r.script??"sc",style:r.style}}let n=Uint8Array.from(e,r=>r.charCodeAt(0));for(let[r,i]of tG){let o;try{o=new TextDecoder(r,{fatal:!0}).decode(n)}catch{continue}let a=Ej(o);if(a)return{script:a.script??i??"sc",style:a.style}}return null}function kj(t,e){if(!t.missingFile||t.isType3Font)return[];let n=nG(t.name??""),r=n?.script??"sc",i=n?.style??(t.fallbackName==="serif"?"serif":"sans"),o=`${r}-${i}`,a=`${r}-serif`,s=o in Fz?[o]:[];return i!=="sans"&&!s.includes(a)&&s.push(a),[...s.map(Bz),...e?[qz]:[]]}var iG=new Set(["serif","sans-serif","monospace","cursive","fantasy","system-ui"]);function Rj(t,e){if(!e.length)return t;let n=t.split(","),r=e.map(o=>`"${o}"`),i=n.at(-1).trim();return iG.has(i)?[...n.slice(0,-1),...r,i].join(","):[...n,...r].join(",")}var rG,Cj=!1;function Ij(){return rG??=(async()=>{(await Promise.all(Object.entries(Fz).map(async([e,n])=>{let r=new FontFace(Bz(e),n.map(i=>`local("${i}")`).join(", "),{unicodeRange:zj});try{return await r.load(),document.fonts.add(r),!0}catch{return!1}}))).some(Boolean)||(Cj=await oG())})()}async function oG(){try{let t=JSON.parse(await Fy(Tj));return await Promise.all(t.faces.map(async({file:e,unicodeRange:n})=>{let r=new FontFace(qz,await Cm(e),{unicodeRange:n});await r.load(),document.fonts.add(r)})),!0}catch(t){return console.warn("CJK fallback font",t),!1}}function Oj(t,e){return Rj(e,kj(t,Cj))}var YG={},aS={};aS.d=(t,e)=>{for(var n in e)aS.o(e,n)&&!aS.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:e[n]})};aS.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var En=typeof process=="object"&&process+""=="[object process]"&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser"),Xz=[.001,0,0,.001,0,0],sS=1.35,aG=.35,TW=aG/sS,di={ANY:1,DISPLAY:2,PRINT:4,SAVE:8,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},Aa={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},qm="pdfjs_internal_editor_",$e={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15,POPUP:16,SIGNATURE:101,COMMENT:102},je={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_THICKNESS:32,HIGHLIGHT_FREE:33,HIGHLIGHT_SHOW_ALL:34,DRAW_STEP:41},sG={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},ln={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_ADD_TO_PATH:4,STROKE_ADD_TO_PATH:5,FILL_STROKE_ADD_TO_PATH:6,ADD_TO_PATH:7,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},lS={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},Mt={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26};var cu={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5};var VS={ERRORS:0,WARNINGS:1,INFOS:5},Fm={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,rawFillPath:94},Jy={moveTo:0,lineTo:1,curveTo:2,closePath:3},lG={NEED_PASSWORD:1,INCORRECT_PASSWORD:2},ZS=VS.WARNINGS;function cG(t){Number.isInteger(t)&&(ZS=t)}function uG(){return ZS}function GS(t){ZS>=VS.INFOS&&console.info(`Info: ${t}`)}function we(t){ZS>=VS.WARNINGS&&console.warn(`Warning: ${t}`)}function rt(t){throw new Error(t)}function Ue(t,e){t||rt(e)}function dG(t){switch(t?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function Qj(t,e=null,n=null){if(!t)return null;if(n&&typeof t=="string"&&(n.addDefaultProtocol&&t.startsWith("www.")&&t.match(/\./g)?.length>=2&&(t=`http://${t}`),n.tryConvertEncoding))try{t=pG(t)}catch{}let r=e?URL.parse(t,e):URL.parse(t);return dG(r)?r:null}function eU(t,e,n=!1){let r=URL.parse(t);return r?(r.hash=e,r.href):n&&Qj(t,"http://example.com")?t.split("#",1)[0]+`${e?`#${e}`:""}`:""}function Re(t,e,n,r=!1){return Object.defineProperty(t,e,{value:n,enumerable:!r,configurable:!0,writable:!1}),n}var Js=(function(){function e(n,r){this.message=n,this.name=r}return e.prototype=new Error,e.constructor=e,e})(),cS=class extends Js{constructor(e,n){super(e,"PasswordException"),this.code=n}},Um=class extends Js{constructor(e,n){super(e,"UnknownErrorException"),this.details=n}},Bm=class extends Js{constructor(e){super(e,"InvalidPDFException")}},mu=class extends Js{constructor(e,n,r){super(e,"ResponseException"),this.status=n,this.missing=r}},Jz=class extends Js{constructor(e){super(e,"FormatError")}},Or=class extends Js{constructor(e){super(e,"AbortException")}};function tU(t){(typeof t!="object"||t?.length===void 0)&&rt("Invalid argument for bytesToString");let e=t.length,n=8192;if(e<n)return String.fromCharCode.apply(null,t);let r=[];for(let i=0;i<e;i+=n){let o=Math.min(i+n,e),a=t.subarray(i,o);r.push(String.fromCharCode.apply(null,a))}return r.join("")}function np(t){typeof t!="string"&&rt("Invalid argument for stringToBytes");let e=t.length,n=new Uint8Array(e);for(let r=0;r<e;++r)n[r]=t.charCodeAt(r)&255;return n}function hG(t){return String.fromCharCode(t>>24&255,t>>16&255,t>>8&255,t&255)}function fG(){let t=new Uint8Array(4);return t[0]=1,new Uint32Array(t.buffer,0,1)[0]===1}function mG(){try{return new Function(""),!0}catch{return!1}}var Ft=class{static get isLittleEndian(){return Re(this,"isLittleEndian",fG())}static get isEvalSupported(){return Re(this,"isEvalSupported",mG())}static get isOffscreenCanvasSupported(){return Re(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas<"u")}static get isImageDecoderSupported(){return Re(this,"isImageDecoderSupported",typeof ImageDecoder<"u")}static get platform(){let{platform:e,userAgent:n}=navigator;return Re(this,"platform",{isAndroid:n.includes("Android"),isLinux:e.includes("Linux"),isMac:e.includes("Mac"),isWindows:e.includes("Win"),isFirefox:n.includes("Firefox")})}static get isCSSRoundSupported(){return Re(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}},Hz=Array.from(Array(256).keys(),t=>t.toString(16).padStart(2,"0")),oe=class{static makeHexColor(e,n,r){return`#${Hz[e]}${Hz[n]}${Hz[r]}`}static domMatrixToTransform(e){return[e.a,e.b,e.c,e.d,e.e,e.f]}static scaleMinMax(e,n){let r;e[0]?(e[0]<0&&(r=n[0],n[0]=n[2],n[2]=r),n[0]*=e[0],n[2]*=e[0],e[3]<0&&(r=n[1],n[1]=n[3],n[3]=r),n[1]*=e[3],n[3]*=e[3]):(r=n[0],n[0]=n[1],n[1]=r,r=n[2],n[2]=n[3],n[3]=r,e[1]<0&&(r=n[1],n[1]=n[3],n[3]=r),n[1]*=e[1],n[3]*=e[1],e[2]<0&&(r=n[0],n[0]=n[2],n[2]=r),n[0]*=e[2],n[2]*=e[2]),n[0]+=e[4],n[1]+=e[5],n[2]+=e[4],n[3]+=e[5]}static transform(e,n){return[e[0]*n[0]+e[2]*n[1],e[1]*n[0]+e[3]*n[1],e[0]*n[2]+e[2]*n[3],e[1]*n[2]+e[3]*n[3],e[0]*n[4]+e[2]*n[5]+e[4],e[1]*n[4]+e[3]*n[5]+e[5]]}static multiplyByDOMMatrix(e,n){return[e[0]*n.a+e[2]*n.b,e[1]*n.a+e[3]*n.b,e[0]*n.c+e[2]*n.d,e[1]*n.c+e[3]*n.d,e[0]*n.e+e[2]*n.f+e[4],e[1]*n.e+e[3]*n.f+e[5]]}static applyTransform(e,n,r=0){let i=e[r],o=e[r+1];e[r]=i*n[0]+o*n[2]+n[4],e[r+1]=i*n[1]+o*n[3]+n[5]}static applyTransformToBezier(e,n,r=0){let i=n[0],o=n[1],a=n[2],s=n[3],l=n[4],c=n[5];for(let u=0;u<6;u+=2){let d=e[r+u],h=e[r+u+1];e[r+u]=d*i+h*a+l,e[r+u+1]=d*o+h*s+c}}static applyInverseTransform(e,n){let r=e[0],i=e[1],o=n[0]*n[3]-n[1]*n[2];e[0]=(r*n[3]-i*n[2]+n[2]*n[5]-n[4]*n[3])/o,e[1]=(-r*n[1]+i*n[0]+n[4]*n[1]-n[5]*n[0])/o}static axialAlignedBoundingBox(e,n,r){let i=n[0],o=n[1],a=n[2],s=n[3],l=n[4],c=n[5],u=e[0],d=e[1],h=e[2],f=e[3],m=i*u+l,p=m,y=i*h+l,g=y,v=s*d+c,S=v,_=s*f+c,$=_;if(o!==0||a!==0){let w=o*u,A=o*h,k=a*d,I=a*f;m+=k,g+=k,y+=I,p+=I,v+=w,$+=w,_+=A,S+=A}r[0]=Math.min(r[0],m,y,p,g),r[1]=Math.min(r[1],v,_,S,$),r[2]=Math.max(r[2],m,y,p,g),r[3]=Math.max(r[3],v,_,S,$)}static inverseTransform(e){let n=e[0]*e[3]-e[1]*e[2];return[e[3]/n,-e[1]/n,-e[2]/n,e[0]/n,(e[2]*e[5]-e[4]*e[3])/n,(e[4]*e[1]-e[5]*e[0])/n]}static singularValueDecompose2dScale(e,n){let r=e[0],i=e[1],o=e[2],a=e[3],s=r**2+i**2,l=r*o+i*a,c=o**2+a**2,u=(s+c)/2,d=Math.sqrt(u**2-(s*c-l**2));n[0]=Math.sqrt(u+d||1),n[1]=Math.sqrt(u-d||1)}static normalizeRect(e){let n=e.slice(0);return e[0]>e[2]&&(n[0]=e[2],n[2]=e[0]),e[1]>e[3]&&(n[1]=e[3],n[3]=e[1]),n}static intersect(e,n){let r=Math.max(Math.min(e[0],e[2]),Math.min(n[0],n[2])),i=Math.min(Math.max(e[0],e[2]),Math.max(n[0],n[2]));if(r>i)return null;let o=Math.max(Math.min(e[1],e[3]),Math.min(n[1],n[3])),a=Math.min(Math.max(e[1],e[3]),Math.max(n[1],n[3]));return o>a?null:[r,o,i,a]}static pointBoundingBox(e,n,r){r[0]=Math.min(r[0],e),r[1]=Math.min(r[1],n),r[2]=Math.max(r[2],e),r[3]=Math.max(r[3],n)}static rectBoundingBox(e,n,r,i,o){o[0]=Math.min(o[0],e,r),o[1]=Math.min(o[1],n,i),o[2]=Math.max(o[2],e,r),o[3]=Math.max(o[3],n,i)}static#e(e,n,r,i,o,a,s,l,c,u){if(c<=0||c>=1)return;let d=1-c,h=c*c,f=h*c,m=d*(d*(d*e+3*c*n)+3*h*r)+f*i,p=d*(d*(d*o+3*c*a)+3*h*s)+f*l;u[0]=Math.min(u[0],m),u[1]=Math.min(u[1],p),u[2]=Math.max(u[2],m),u[3]=Math.max(u[3],p)}static#t(e,n,r,i,o,a,s,l,c,u,d,h){if(Math.abs(c)<1e-12){Math.abs(u)>=1e-12&&this.#e(e,n,r,i,o,a,s,l,-d/u,h);return}let f=u**2-4*d*c;if(f<0)return;let m=Math.sqrt(f),p=2*c;this.#e(e,n,r,i,o,a,s,l,(-u+m)/p,h),this.#e(e,n,r,i,o,a,s,l,(-u-m)/p,h)}static bezierBoundingBox(e,n,r,i,o,a,s,l,c){c[0]=Math.min(c[0],e,s),c[1]=Math.min(c[1],n,l),c[2]=Math.max(c[2],e,s),c[3]=Math.max(c[3],n,l),this.#t(e,r,o,s,n,i,a,l,3*(-e+3*(r-o)+s),6*(e-2*r+o),3*(r-e),c),this.#t(e,r,o,s,n,i,a,l,3*(-n+3*(i-a)+l),6*(n-2*i+a),3*(i-n),c)}};function pG(t){return decodeURIComponent(escape(t))}var Vz=null,Pj=null;function gG(t){return Vz||(Vz=/([\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,Pj=new Map([["\uFB05","\u017Ft"]])),t.replaceAll(Vz,(e,n,r)=>n?n.normalize("NFKC"):Pj.get(r))}function nU(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let t=new Uint8Array(32);return crypto.getRandomValues(t),tU(t)}var kR="pdfjs_internal_id_";function vG(t,e,n){if(!Array.isArray(n)||n.length<2)return!1;let[r,i,...o]=n;if(!t(r)&&!Number.isInteger(r)||!e(i))return!1;let a=o.length,s=!0;switch(i.name){case"XYZ":if(a<2||a>3)return!1;break;case"Fit":case"FitB":return a===0;case"FitH":case"FitBH":case"FitV":case"FitBV":if(a>1)return!1;break;case"FitR":if(a!==4)return!1;s=!1;break;default:return!1}for(let l of o)if(!(typeof l=="number"||s&&l===null))return!1;return!0}function Tn(t,e,n){return Math.min(Math.max(t,e),n)}function iU(t){return Uint8Array.prototype.toBase64?t.toBase64():btoa(tU(t))}function bG(t){return Uint8Array.fromBase64?Uint8Array.fromBase64(t):np(atob(t))}typeof Promise.try!="function"&&(Promise.try=function(t,...e){return new Promise(n=>{n(t(...e))})});typeof Math.sumPrecise!="function"&&(Math.sumPrecise=function(t){return t.reduce((e,n)=>e+n,0)});var Hm=class t{static textContent(e){let n=[],r={items:n,styles:Object.create(null)};function i(o){if(!o)return;let a=null,s=o.name;if(s==="#text")a=o.value;else if(t.shouldBuildText(s))o?.attributes?.textContent?a=o.attributes.textContent:o.value&&(a=o.value);else return;if(a!==null&&n.push({str:a}),!!o.children)for(let l of o.children)i(l)}return i(e),r}static shouldBuildText(e){return!(e==="textarea"||e==="input"||e==="option"||e==="select")}},uS=class{static setupStorage(e,n,r,i,o){let a=i.getValue(n,{value:null});switch(r.name){case"textarea":if(a.value!==null&&(e.textContent=a.value),o==="print")break;e.addEventListener("input",s=>{i.setValue(n,{value:s.target.value})});break;case"input":if(r.attributes.type==="radio"||r.attributes.type==="checkbox"){if(a.value===r.attributes.xfaOn?e.setAttribute("checked",!0):a.value===r.attributes.xfaOff&&e.removeAttribute("checked"),o==="print")break;e.addEventListener("change",s=>{i.setValue(n,{value:s.target.checked?s.target.getAttribute("xfaOn"):s.target.getAttribute("xfaOff")})})}else{if(a.value!==null&&e.setAttribute("value",a.value),o==="print")break;e.addEventListener("input",s=>{i.setValue(n,{value:s.target.value})})}break;case"select":if(a.value!==null){e.setAttribute("value",a.value);for(let s of r.children)s.attributes.value===a.value?s.attributes.selected=!0:s.attributes.hasOwnProperty("selected")&&delete s.attributes.selected}e.addEventListener("input",s=>{let l=s.target.options,c=l.selectedIndex===-1?"":l[l.selectedIndex].value;i.setValue(n,{value:c})});break}}static setAttributes({html:e,element:n,storage:r=null,intent:i,linkService:o}){let{attributes:a}=n,s=e instanceof HTMLAnchorElement;a.type==="radio"&&(a.name=`${a.name}-${i}`);for(let[l,c]of Object.entries(a))if(c!=null)switch(l){case"class":c.length&&e.setAttribute(l,c.join(" "));break;case"dataId":break;case"id":e.setAttribute("data-element-id",c);break;case"style":Object.assign(e.style,c);break;case"textContent":e.textContent=c;break;default:(!s||l!=="href"&&l!=="newWindow")&&e.setAttribute(l,c)}s&&o.addLinkAttributes(e,a.href,a.newWindow),r&&a.dataId&&this.setupStorage(e,a.dataId,n,r)}static render(e){let n=e.annotationStorage,r=e.linkService,i=e.xfaHtml,o=e.intent||"display",a=document.createElement(i.name);i.attributes&&this.setAttributes({html:a,element:i,intent:o,linkService:r});let s=o!=="richText",l=e.div;if(l.append(a),e.viewport){let d=`matrix(${e.viewport.transform.join(",")})`;l.style.transform=d}s&&l.setAttribute("class","xfaLayer xfaFont");let c=[];if(i.children.length===0){if(i.value){let d=document.createTextNode(i.value);a.append(d),s&&Hm.shouldBuildText(i.name)&&c.push(d)}return{textDivs:c}}let u=[[i,-1,a]];for(;u.length>0;){let[d,h,f]=u.at(-1);if(h+1===d.children.length){u.pop();continue}let m=d.children[++u.at(-1)[1]];if(m===null)continue;let{name:p}=m;if(p==="#text"){let g=document.createTextNode(m.value);c.push(g),f.append(g);continue}let y=m?.attributes?.xmlns?document.createElementNS(m.attributes.xmlns,p):document.createElement(p);if(f.append(y),m.attributes&&this.setAttributes({html:y,element:m,storage:n,intent:o,linkService:r}),m.children?.length>0)u.push([m,-1,y]);else if(m.value){let g=document.createTextNode(m.value);s&&Hm.shouldBuildText(p)&&c.push(g),y.append(g)}}for(let d of l.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))d.setAttribute("readOnly",!0);return{textDivs:c}}static update(e){let n=`matrix(${e.viewport.transform.join(",")})`;e.div.style.transform=n,e.div.hidden=!1}},wo="http://www.w3.org/2000/svg",Ta=class{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF};async function ip(t,e="text"){if(jm(t,document.baseURI)){let n=await fetch(t);if(!n.ok)throw new Error(n.statusText);switch(e){case"arraybuffer":return n.arrayBuffer();case"blob":return n.blob();case"json":return n.json()}return n.text()}return new Promise((n,r)=>{let i=new XMLHttpRequest;i.open("GET",t,!0),i.responseType=e,i.onreadystatechange=()=>{if(i.readyState===XMLHttpRequest.DONE){if(i.status===200||i.status===0){switch(e){case"arraybuffer":case"blob":case"json":n(i.response);return}n(i.responseText);return}r(new Error(i.statusText))}},i.send(null)})}var Vm=class t{constructor({viewBox:e,userUnit:n,scale:r,rotation:i,offsetX:o=0,offsetY:a=0,dontFlip:s=!1}){this.viewBox=e,this.userUnit=n,this.scale=r,this.rotation=i,this.offsetX=o,this.offsetY=a,r*=n;let l=(e[2]+e[0])/2,c=(e[3]+e[1])/2,u,d,h,f;switch(i%=360,i<0&&(i+=360),i){case 180:u=-1,d=0,h=0,f=1;break;case 90:u=0,d=1,h=1,f=0;break;case 270:u=0,d=-1,h=-1,f=0;break;case 0:u=1,d=0,h=0,f=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}s&&(h=-h,f=-f);let m,p,y,g;u===0?(m=Math.abs(c-e[1])*r+o,p=Math.abs(l-e[0])*r+a,y=(e[3]-e[1])*r,g=(e[2]-e[0])*r):(m=Math.abs(l-e[0])*r+o,p=Math.abs(c-e[1])*r+a,y=(e[2]-e[0])*r,g=(e[3]-e[1])*r),this.transform=[u*r,d*r,h*r,f*r,m-u*r*l-h*r*c,p-d*r*l-f*r*c],this.width=y,this.height=g}get rawDims(){let e=this.viewBox;return Re(this,"rawDims",{pageWidth:e[2]-e[0],pageHeight:e[3]-e[1],pageX:e[0],pageY:e[1]})}clone({scale:e=this.scale,rotation:n=this.rotation,offsetX:r=this.offsetX,offsetY:i=this.offsetY,dontFlip:o=!1}={}){return new t({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:e,rotation:n,offsetX:r,offsetY:i,dontFlip:o})}convertToViewportPoint(e,n){let r=[e,n];return oe.applyTransform(r,this.transform),r}convertToViewportRectangle(e){let n=[e[0],e[1]];oe.applyTransform(n,this.transform);let r=[e[2],e[3]];return oe.applyTransform(r,this.transform),[n[0],n[1],r[0],r[1]]}convertToPdfPoint(e,n){let r=[e,n];return oe.applyInverseTransform(r,this.transform),r}},Zm=class extends Js{constructor(e,n=0){super(e,"RenderingCancelledException"),this.extraDelay=n}};function KS(t){let e=t.length,n=0;for(;n<e&&t[n].trim()==="";)n++;return t.substring(n,n+5).toLowerCase()==="data:"}function RR(t){return typeof t=="string"&&/\.pdf$/i.test(t)}function yG(t){return[t]=t.split(/[#?]/,1),t.substring(t.lastIndexOf("/")+1)}function SG(t,e="document.pdf"){if(typeof t!="string")return e;if(KS(t))return we('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'),e;let r=(s=>{try{return new URL(s)}catch{try{return new URL(decodeURIComponent(s))}catch{try{return new URL(s,"https://foo.bar")}catch{try{return new URL(decodeURIComponent(s),"https://foo.bar")}catch{return null}}}}})(t);if(!r)return e;let i=s=>{try{let l=decodeURIComponent(s);return l.includes("/")?(l=l.split("/").at(-1),l.test(/^\.pdf$/i)?l:s):l}catch{return s}},o=/\.pdf$/i,a=r.pathname.split("/").at(-1);if(o.test(a))return i(a);if(r.searchParams.size>0){let s=Array.from(r.searchParams.values()).reverse();for(let c of s)if(o.test(c))return i(c);let l=Array.from(r.searchParams.keys()).reverse();for(let c of l)if(o.test(c))return i(c)}if(r.hash){let l=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i.exec(r.hash);if(l)return i(l[0])}return e}var dS=class{started=Object.create(null);times=[];time(e){e in this.started&&we(`Timer is already running for ${e}`),this.started[e]=Date.now()}timeEnd(e){e in this.started||we(`Timer has not been started for ${e}`),this.times.push({name:e,start:this.started[e],end:Date.now()}),delete this.started[e]}toString(){let e=[],n=0;for(let{name:r}of this.times)n=Math.max(r.length,n);for(let{name:r,start:i,end:o}of this.times)e.push(`${r.padEnd(n)} ${o-i}ms
109
109
  `);return e.join("")}};function jm(t,e){let n=e?URL.parse(t,e):URL.parse(t);return n?.protocol==="http:"||n?.protocol==="https:"}function Ni(t){t.preventDefault()}function Et(t){t.preventDefault(),t.stopPropagation()}function _G(t){console.log("Deprecated API usage: "+t)}var Gm=class{static#e;static toDateObject(e){if(e instanceof Date)return e;if(!e||typeof e!="string")return null;this.#e||=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?");let n=this.#e.exec(e);if(!n)return null;let r=parseInt(n[1],10),i=parseInt(n[2],10);i=i>=1&&i<=12?i-1:0;let o=parseInt(n[3],10);o=o>=1&&o<=31?o:1;let a=parseInt(n[4],10);a=a>=0&&a<=23?a:0;let s=parseInt(n[5],10);s=s>=0&&s<=59?s:0;let l=parseInt(n[6],10);l=l>=0&&l<=59?l:0;let c=n[7]||"Z",u=parseInt(n[8],10);u=u>=0&&u<=23?u:0;let d=parseInt(n[9],10)||0;return d=d>=0&&d<=59?d:0,c==="-"?(a+=u,s+=d):c==="+"&&(a-=u,s-=d),new Date(Date.UTC(r,i,o,a,s,l))}};function wG(t,{scale:e=1,rotation:n=0}){let{width:r,height:i}=t.attributes.style,o=[0,0,parseInt(r),parseInt(i)];return new Vm({viewBox:o,userUnit:1,scale:e,rotation:n})}function rp(t){if(t.startsWith("#")){let e=parseInt(t.slice(1),16);return[(e&16711680)>>16,(e&65280)>>8,e&255]}return t.startsWith("rgb(")?t.slice(4,-1).split(",").map(e=>parseInt(e)):t.startsWith("rgba(")?t.slice(5,-1).split(",").map(e=>parseInt(e)).slice(0,3):(we(`Not a valid color format: "${t}"`),[0,0,0])}function xG(t){let e=document.createElement("span");e.style.visibility="hidden",e.style.colorScheme="only light",document.body.append(e);for(let n of t.keys()){e.style.color=n;let r=window.getComputedStyle(e).color;t.set(n,rp(r))}e.remove()}function St(t){let{a:e,b:n,c:r,d:i,e:o,f:a}=t.getTransform();return[e,n,r,i,o,a]}function Cr(t){let{a:e,b:n,c:r,d:i,e:o,f:a}=t.getTransform().invertSelf();return[e,n,r,i,o,a]}function Hs(t,e,n=!1,r=!0){if(e instanceof Vm){let{pageWidth:i,pageHeight:o}=e.rawDims,{style:a}=t,s=Ft.isCSSRoundSupported,l=`var(--total-scale-factor) * ${i}px`,c=`var(--total-scale-factor) * ${o}px`,u=s?`round(down, ${l}, var(--scale-round-x))`:`calc(${l})`,d=s?`round(down, ${c}, var(--scale-round-y))`:`calc(${c})`;!n||e.rotation%180===0?(a.width=u,a.height=d):(a.width=d,a.height=u)}r&&t.setAttribute("data-main-rotation",e.rotation)}var xo=class t{constructor(){let{pixelRatio:e}=t;this.sx=e,this.sy=e}get scaled(){return this.sx!==1||this.sy!==1}get symmetric(){return this.sx===this.sy}limitCanvas(e,n,r,i,o=-1){let a=1/0,s=1/0,l=1/0;r=t.capPixels(r,o),r>0&&(a=Math.sqrt(r/(e*n))),i!==-1&&(s=i/e,l=i/n);let c=Math.min(a,s,l);return this.sx>c||this.sy>c?(this.sx=c,this.sy=c,!0):!1}static get pixelRatio(){return globalThis.devicePixelRatio||1}static capPixels(e,n){if(n>=0){let r=Math.ceil(window.screen.availWidth*window.screen.availHeight*this.pixelRatio**2*(1+n/100));return e>0?Math.min(e,r):r}return e}},Wz=["image/apng","image/avif","image/bmp","image/gif","image/jpeg","image/png","image/svg+xml","image/webp","image/x-icon"],Qz=class{static get isDarkMode(){return Re(this,"isDarkMode",!!window?.matchMedia?.("(prefers-color-scheme: dark)").matches)}},ek=class{static get commentForegroundColor(){let e=document.createElement("span");e.classList.add("comment","sidebar");let{style:n}=e;n.width=n.height="0",n.display="none",n.color="var(--comment-fg-color)",document.body.append(e);let{color:r}=window.getComputedStyle(e);return e.remove(),Re(this,"commentForegroundColor",rp(r))}};function $G(t,e,n,r){r=Math.min(Math.max(r??1,0),1);let i=255*(1-r);return t=Math.round(t*r+i),e=Math.round(e*r+i),n=Math.round(n*r+i),[t,e,n]}function Nj(t,e){let n=t[0]/255,r=t[1]/255,i=t[2]/255,o=Math.max(n,r,i),a=Math.min(n,r,i),s=(o+a)/2;if(o===a)e[0]=e[1]=0;else{let l=o-a;switch(e[1]=s<.5?l/(o+a):l/(2-o-a),o){case n:e[0]=((r-i)/l+(r<i?6:0))*60;break;case r:e[0]=((i-n)/l+2)*60;break;case i:e[0]=((n-r)/l+4)*60;break}}e[2]=s}function tk(t,e){let n=t[0],r=t[1],i=t[2],o=(1-Math.abs(2*i-1))*r,a=o*(1-Math.abs(n/60%2-1)),s=i-o/2;switch(Math.floor(n/60)){case 0:e[0]=o+s,e[1]=a+s,e[2]=s;break;case 1:e[0]=a+s,e[1]=o+s,e[2]=s;break;case 2:e[0]=s,e[1]=o+s,e[2]=a+s;break;case 3:e[0]=s,e[1]=a+s,e[2]=o+s;break;case 4:e[0]=a+s,e[1]=s,e[2]=o+s;break;case 5:case 6:e[0]=o+s,e[1]=s,e[2]=a+s;break}}function Mj(t){return t<=.03928?t/12.92:((t+.055)/1.055)**2.4}function Dj(t,e,n){tk(t,n),n.map(Mj);let r=.2126*n[0]+.7152*n[1]+.0722*n[2];tk(e,n),n.map(Mj);let i=.2126*n[0]+.7152*n[1]+.0722*n[2];return r>i?(r+.05)/(i+.05):(i+.05)/(r+.05)}var Lj=new Map;function AG(t,e){let n=t[0]+t[1]*256+t[2]*65536+e[0]*16777216+e[1]*4294967296+e[2]*1099511627776,r=Lj.get(n);if(r)return r;let i=new Float32Array(9),o=i.subarray(0,3),a=i.subarray(3,6);Nj(t,a);let s=i.subarray(6,9);Nj(e,s);let l=s[2]<.5,c=l?12:4.5;if(a[2]=l?Math.sqrt(a[2]):1-Math.sqrt(1-a[2]),Dj(a,s,o)<c){let u,d;l?(u=a[2],d=1):(u=0,d=a[2]);let h=.005;for(;d-u>h;){let f=a[2]=(u+d)/2;l===Dj(a,s,o)<c?u=f:d=f}a[2]=l?d:u}return tk(a,o),r=oe.makeHexColor(Math.round(o[0]*255),Math.round(o[1]*255),Math.round(o[2]*255)),Lj.set(n,r),r}function rU({html:t,dir:e,className:n},r){let i=document.createDocumentFragment();if(typeof t=="string"){let o=document.createElement("p");o.dir=e||"auto";let a=t.split(/(?:\r\n?|\n)/);for(let s=0,l=a.length;s<l;++s){let c=a[s];o.append(document.createTextNode(c)),s<l-1&&o.append(document.createElement("br"))}i.append(o)}else uS.render({xfaHtml:t,div:i,intent:"richText"});i.firstChild.classList.add("richText",n),r.append(i)}var nk=class t{#e=null;#t=null;#i;#n=null;#a=null;#r=null;#o=null;#s=null;static#c=null;constructor(e){this.#i=e,t.#c||=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",signature:"pdfjs-editor-remove-signature-button"})}render(){let e=this.#e=document.createElement("div");e.classList.add("editToolbar","hidden"),e.setAttribute("role","toolbar");let n=this.#i._uiManager._signal;n instanceof AbortSignal&&!n.aborted&&(e.addEventListener("contextmenu",Ni,{signal:n}),e.addEventListener("pointerdown",t.#l,{signal:n}));let r=this.#n=document.createElement("div");r.className="buttons",e.append(r);let i=this.#i.toolbarPosition;if(i){let{style:o}=e,a=this.#i._uiManager.direction==="ltr"?1-i[0]:i[0];o.insetInlineEnd=`${100*a}%`,o.top=`calc(${100*i[1]}% + var(--editor-toolbar-vert-offset))`}return e}get div(){return this.#e}static#l(e){e.stopPropagation()}#h(e){this.#i._focusEventsAllowed=!1,Et(e)}#d(e){this.#i._focusEventsAllowed=!0,Et(e)}#f(e){let n=this.#i._uiManager._signal;return!(n instanceof AbortSignal)||n.aborted?!1:(e.addEventListener("focusin",this.#h.bind(this),{capture:!0,signal:n}),e.addEventListener("focusout",this.#d.bind(this),{capture:!0,signal:n}),e.addEventListener("contextmenu",Ni,{signal:n}),!0)}hide(){this.#e.classList.add("hidden"),this.#t?.hideDropdown()}show(){this.#e.classList.remove("hidden"),this.#a?.shown(),this.#r?.shown()}addDeleteButton(){let{editorType:e,_uiManager:n}=this.#i,r=document.createElement("button");r.classList.add("basic","deleteButton"),r.tabIndex=0,r.setAttribute("data-l10n-id",t.#c[e]),this.#f(r)&&r.addEventListener("click",i=>{n.delete()},{signal:n._signal}),this.#n.append(r)}get#g(){let e=document.createElement("div");return e.className="divider",e}async addAltText(e){let n=await e.render();this.#f(n),this.#n.append(n,this.#g),this.#a=e}addComment(e,n=null){if(this.#r)return;let r=e.renderForToolbar();if(!r)return;this.#f(r);let i=this.#o=this.#g;n?(this.#n.insertBefore(r,n),this.#n.insertBefore(i,n)):this.#n.append(r,i),this.#r=e,e.toolbar=this}addColorPicker(e){if(this.#t)return;this.#t=e;let n=e.renderButton();this.#f(n),this.#n.append(n,this.#g)}async addEditSignatureButton(e){let n=this.#s=await e.renderEditButton(this.#i);this.#f(n),this.#n.append(n,this.#g)}removeButton(e){switch(e){case"comment":this.#r?.removeToolbarCommentButton(),this.#r=null,this.#o?.remove(),this.#o=null;break}}async addButton(e,n){switch(e){case"colorPicker":this.addColorPicker(n);break;case"altText":await this.addAltText(n);break;case"editSignature":await this.addEditSignatureButton(n);break;case"delete":this.addDeleteButton();break;case"comment":this.addComment(n);break}}async addButtonBefore(e,n,r){let i=this.#n.querySelector(r);i&&e==="comment"&&this.addComment(n,i)}updateEditSignatureButton(e){this.#s&&(this.#s.title=e)}remove(){this.#e.remove(),this.#t?.destroy(),this.#t=null}},ik=class{#e=null;#t=null;#i;constructor(e){this.#i=e}#n(){let e=this.#t=document.createElement("div");e.className="editToolbar",e.setAttribute("role","toolbar");let n=this.#i._signal;n instanceof AbortSignal&&!n.aborted&&e.addEventListener("contextmenu",Ni,{signal:n});let r=this.#e=document.createElement("div");return r.className="buttons",e.append(r),this.#i.hasCommentManager()&&this.#r("commentButton","pdfjs-comment-floating-button","pdfjs-comment-floating-button-label",()=>{this.#i.commentSelection("floating_button")}),this.#r("highlightButton","pdfjs-highlight-floating-button1","pdfjs-highlight-floating-button-label",()=>{this.#i.highlightSelection("floating_button")}),e}#a(e,n){let r=0,i=0;for(let o of e){let a=o.y+o.height;if(a<r)continue;let s=o.x+(n?o.width:0);if(a>r){i=s,r=a;continue}n?s>i&&(i=s):s<i&&(i=s)}return[n?1-i:i,r]}show(e,n,r){let[i,o]=this.#a(n,r),{style:a}=this.#t||=this.#n();e.append(this.#t),a.insetInlineEnd=`${100*i}%`,a.top=`calc(${100*o}% + var(--editor-toolbar-vert-offset))`}hide(){this.#t.remove()}#r(e,n,r,i){let o=document.createElement("button");o.classList.add("basic",e),o.tabIndex=0,o.setAttribute("data-l10n-id",n);let a=document.createElement("span");o.append(a),a.className="visuallyHidden",a.setAttribute("data-l10n-id",r);let s=this.#i._signal;s instanceof AbortSignal&&!s.aborted&&(o.addEventListener("contextmenu",Ni,{signal:s}),o.addEventListener("click",i,{signal:s})),this.#e.append(o)}};function oU(t,e,n){for(let r of n)e.addEventListener(r,t[r].bind(t))}var rk=class{#e=0;get id(){return`${qm}${this.#e++}`}},ok=class t{#e=nU();#t=0;#i=null;static get _isSVGFittingCanvas(){let e='data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1" style="fill:red;"/></svg>',r=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),i=new Image;i.src=e;let o=i.decode().then(()=>(r.drawImage(i,0,0,1,1,0,0,1,3),new Uint32Array(r.getImageData(0,0,1,1).data.buffer)[0]===0));return Re(this,"_isSVGFittingCanvas",o)}async#n(e,n){this.#i||=new Map;let r=this.#i.get(e);if(r===null)return null;if(r?.bitmap)return r.refCounter+=1,r;try{r||={bitmap:null,id:`image_${this.#e}_${this.#t++}`,refCounter:0,isSvg:!1};let i;if(typeof n=="string"?(r.url=n,i=await ip(n,"blob")):n instanceof File?i=r.file=n:n instanceof Blob&&(i=n),i.type==="image/svg+xml"){let o=t._isSVGFittingCanvas,a=new FileReader,s=new Image,l=new Promise((c,u)=>{s.onload=()=>{r.bitmap=s,r.isSvg=!0,c()},a.onload=async()=>{let d=r.svgUrl=a.result;s.src=await o?`${d}#svgView(preserveAspectRatio(none))`:d},s.onerror=a.onerror=u});a.readAsDataURL(i),await l}else r.bitmap=await createImageBitmap(i);r.refCounter=1}catch(i){we(i),r=null}return this.#i.set(e,r),r&&this.#i.set(r.id,r),r}async getFromFile(e){let{lastModified:n,name:r,size:i,type:o}=e;return this.#n(`${n}_${r}_${i}_${o}`,e)}async getFromUrl(e){return this.#n(e,e)}async getFromBlob(e,n){let r=await n;return this.#n(e,r)}async getFromId(e){this.#i||=new Map;let n=this.#i.get(e);if(!n)return null;if(n.bitmap)return n.refCounter+=1,n;if(n.file)return this.getFromFile(n.file);if(n.blobPromise){let{blobPromise:r}=n;return delete n.blobPromise,this.getFromBlob(n.id,r)}return this.getFromUrl(n.url)}getFromCanvas(e,n){this.#i||=new Map;let r=this.#i.get(e);if(r?.bitmap)return r.refCounter+=1,r;let i=new OffscreenCanvas(n.width,n.height);return i.getContext("2d").drawImage(n,0,0),r={bitmap:i.transferToImageBitmap(),id:`image_${this.#e}_${this.#t++}`,refCounter:1,isSvg:!1},this.#i.set(e,r),this.#i.set(r.id,r),r}getSvgUrl(e){let n=this.#i.get(e);return n?.isSvg?n.svgUrl:null}deleteId(e){this.#i||=new Map;let n=this.#i.get(e);if(!n||(n.refCounter-=1,n.refCounter!==0))return;let{bitmap:r}=n;if(!n.url&&!n.file){let i=new OffscreenCanvas(r.width,r.height);i.getContext("bitmaprenderer").transferFromImageBitmap(r),n.blobPromise=i.convertToBlob()}r.close?.(),n.bitmap=null}isValidId(e){return e.startsWith(`image_${this.#e}_`)}},ak=class{#e=[];#t=!1;#i;#n=-1;constructor(e=128){this.#i=e}add({cmd:e,undo:n,post:r,mustExec:i,type:o=NaN,overwriteIfSameType:a=!1,keepUndo:s=!1}){if(i&&e(),this.#t)return;let l={cmd:e,undo:n,post:r,type:o};if(this.#n===-1){this.#e.length>0&&(this.#e.length=0),this.#n=0,this.#e.push(l);return}if(a&&this.#e[this.#n].type===o){s&&(l.undo=this.#e[this.#n].undo),this.#e[this.#n]=l;return}let c=this.#n+1;c===this.#i?this.#e.splice(0,1):(this.#n=c,c<this.#e.length&&this.#e.splice(c)),this.#e.push(l)}undo(){if(this.#n===-1)return;this.#t=!0;let{undo:e,post:n}=this.#e[this.#n];e(),n?.(),this.#t=!1,this.#n-=1}redo(){if(this.#n<this.#e.length-1){this.#n+=1,this.#t=!0;let{cmd:e,post:n}=this.#e[this.#n];e(),n?.(),this.#t=!1}}hasSomethingToUndo(){return this.#n!==-1}hasSomethingToRedo(){return this.#n<this.#e.length-1}cleanType(e){if(this.#n!==-1){for(let n=this.#n;n>=0;n--)if(this.#e[n].type!==e){this.#e.splice(n+1,this.#n-n),this.#n=n;return}this.#e.length=0,this.#n=-1}}destroy(){this.#e=null}},Vs=class{constructor(e){this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;let{isMac:n}=Ft.platform;for(let[r,i,o={}]of e)for(let a of r){let s=a.startsWith("mac+");n&&s?(this.callbacks.set(a.slice(4),{callback:i,options:o}),this.allKeys.add(a.split("+").at(-1))):!n&&!s&&(this.callbacks.set(a,{callback:i,options:o}),this.allKeys.add(a.split("+").at(-1)))}}#e(e){e.altKey&&this.buffer.push("alt"),e.ctrlKey&&this.buffer.push("ctrl"),e.metaKey&&this.buffer.push("meta"),e.shiftKey&&this.buffer.push("shift"),this.buffer.push(e.key);let n=this.buffer.join("+");return this.buffer.length=0,n}exec(e,n){if(!this.allKeys.has(n.key))return;let r=this.callbacks.get(this.#e(n));if(!r)return;let{callback:i,options:{bubbles:o=!1,args:a=[],checker:s=null}}=r;s&&!s(e,n)||(i.bind(e,...a,n)(),o||Et(n))}},sk=class t{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){let e=new Map([["CanvasText",null],["Canvas",null]]);return xG(e),Re(this,"_colors",e)}convert(e){let n=rp(e);if(!window.matchMedia("(forced-colors: active)").matches)return n;for(let[r,i]of this._colors)if(i.every((o,a)=>o===n[a]))return t._colorsMapping.get(r);return n}getHexCode(e){let n=this._colors.get(e);return n?oe.makeHexColor(...n):e}},Zs=class t{#e=new AbortController;#t=null;#i=null;#n=new Map;#a=new Map;#r=null;#o=null;#s=null;#c=new ak;#l=null;#h=null;#d=null;#f=0;#g=new Set;#m=null;#u=null;#p=new Set;_editorUndoBar=null;#v=!1;#y=!1;#b=!1;#A=null;#x=null;#S=null;#T=null;#w=!1;#$=null;#R=new rk;#z=!1;#k=!1;#D=!1;#I=null;#P=null;#L=null;#N=null;#H=null;#E=$e.NONE;#_=new Set;#O=null;#j=null;#q=null;#G=null;#Z=null;#K={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#F=[0,0];#M=null;#V=null;#W=null;#Q=null;#U=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){let e=t.prototype,n=a=>a.#V.contains(document.activeElement)&&document.activeElement.tagName!=="BUTTON"&&a.hasSomethingToControl(),r=(a,{target:s})=>{if(s instanceof HTMLInputElement){let{type:l}=s;return l!=="text"&&l!=="number"}return!0},i=this.TRANSLATE_SMALL,o=this.TRANSLATE_BIG;return Re(this,"_keyboardManager",new Vs([[["ctrl+a","mac+meta+a"],e.selectAll,{checker:r}],[["ctrl+z","mac+meta+z"],e.undo,{checker:r}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],e.redo,{checker:r}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],e.delete,{checker:r}],[["Enter","mac+Enter"],e.addNewEditorFromKeyboard,{checker:(a,{target:s})=>!(s instanceof HTMLButtonElement)&&a.#V.contains(s)&&!a.isEnterHandled}],[[" ","mac+ "],e.addNewEditorFromKeyboard,{checker:(a,{target:s})=>!(s instanceof HTMLButtonElement)&&a.#V.contains(document.activeElement)}],[["Escape","mac+Escape"],e.unselectAll],[["ArrowLeft","mac+ArrowLeft"],e.translateSelectedEditors,{args:[-i,0],checker:n}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],e.translateSelectedEditors,{args:[-o,0],checker:n}],[["ArrowRight","mac+ArrowRight"],e.translateSelectedEditors,{args:[i,0],checker:n}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],e.translateSelectedEditors,{args:[o,0],checker:n}],[["ArrowUp","mac+ArrowUp"],e.translateSelectedEditors,{args:[0,-i],checker:n}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],e.translateSelectedEditors,{args:[0,-o],checker:n}],[["ArrowDown","mac+ArrowDown"],e.translateSelectedEditors,{args:[0,i],checker:n}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],e.translateSelectedEditors,{args:[0,o],checker:n}]]))}constructor(e,n,r,i,o,a,s,l,c,u,d,h,f,m,p,y){let g=this._signal=this.#e.signal;this.#V=e,this.#W=n,this.#Q=r,this.#r=i,this.#l=o,this.#j=a,this.#Z=l,this._eventBus=s,s._on("editingaction",this.onEditingAction.bind(this),{signal:g}),s._on("pagechanging",this.onPageChanging.bind(this),{signal:g}),s._on("scalechanging",this.onScaleChanging.bind(this),{signal:g}),s._on("rotationchanging",this.onRotationChanging.bind(this),{signal:g}),s._on("setpreference",this.onSetPreference.bind(this),{signal:g}),s._on("switchannotationeditorparams",v=>this.updateParams(v.type,v.value),{signal:g}),window.addEventListener("pointerdown",()=>{this.#k=!0},{capture:!0,signal:g}),window.addEventListener("pointerup",()=>{this.#k=!1},{capture:!0,signal:g}),this.#le(),this.#he(),this.#te(),this.#o=l.annotationStorage,this.#A=l.filterFactory,this.#q=c,this.#T=u||null,this.#v=d,this.#y=h,this.#b=f,this.#H=m||null,this.viewParameters={realScale:Ta.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1,this._editorUndoBar=p||null,this._supportsPinchToZoom=y!==!1,o?.setSidebarUiManager(this)}destroy(){this.#U?.resolve(),this.#U=null,this.#e?.abort(),this.#e=null,this._signal=null;for(let e of this.#a.values())e.destroy();this.#a.clear(),this.#n.clear(),this.#p.clear(),this.#N?.clear(),this.#t=null,this.#_.clear(),this.#c.destroy(),this.#r?.destroy(),this.#l?.destroy(),this.#j?.destroy(),this.#$?.hide(),this.#$=null,this.#L?.destroy(),this.#L=null,this.#i=null,this.#x&&(clearTimeout(this.#x),this.#x=null),this.#M&&(clearTimeout(this.#M),this.#M=null),this._editorUndoBar?.destroy(),this.#Z=null}combinedSignal(e){return AbortSignal.any([this._signal,e.signal])}get mlManager(){return this.#H}get useNewAltTextFlow(){return this.#y}get useNewAltTextWhenAddingImage(){return this.#b}get hcmFilter(){return Re(this,"hcmFilter",this.#q?this.#A.addHCMFilter(this.#q.foreground,this.#q.background):"none")}get direction(){return Re(this,"direction",getComputedStyle(this.#V).direction)}get _highlightColors(){return Re(this,"_highlightColors",this.#T?new Map(this.#T.split(",").map(e=>(e=e.split("=").map(n=>n.trim()),e[1]=e[1].toUpperCase(),e))):null)}get highlightColors(){let{_highlightColors:e}=this;if(!e)return Re(this,"highlightColors",null);let n=new Map,r=!!this.#q;for(let[i,o]of e){let a=i.endsWith("_HCM");if(r&&a){n.set(i.replace("_HCM",""),o);continue}!r&&!a&&n.set(i,o)}return Re(this,"highlightColors",n)}get highlightColorNames(){return Re(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,e=>e.reverse())):null)}getNonHCMColor(e){if(!this._highlightColors)return e;let n=this.highlightColorNames.get(e);return this._highlightColors.get(n)||e}getNonHCMColorName(e){return this.highlightColorNames.get(e)||e}setCurrentDrawingSession(e){e?(this.unselectAll(),this.disableUserSelect(!0)):this.disableUserSelect(!1),this.#d=e}setMainHighlightColorPicker(e){this.#L=e}editAltText(e,n=!1){this.#r?.editAltText(this,e,n)}hasCommentManager(){return!!this.#l}editComment(e,n,r,i){this.#l?.showDialog(this,e,n,r,i)}selectComment(e,n){this.#a.get(e)?.getEditorByUID(n)?.toggleComment(!0,!0)}updateComment(e){this.#l?.updateComment(e.getData())}updatePopupColor(e){this.#l?.updatePopupColor(e)}removeComment(e){this.#l?.removeComments([e.uid])}toggleComment(e,n,r=void 0){this.#l?.toggleCommentPopup(e,n,r)}makeCommentColor(e,n){return e&&this.#l?.makeCommentColor(e,n)||null}getCommentDialogElement(){return this.#l?.dialogElement||null}async waitForEditorsRendered(e){if(this.#a.has(e-1))return;let{resolve:n,promise:r}=Promise.withResolvers(),i=o=>{o.pageNumber===e&&(this._eventBus._off("editorsrendered",i),n())};this._eventBus.on("editorsrendered",i),await r}getSignature(e){this.#j?.getSignature({uiManager:this,editor:e})}get signatureManager(){return this.#j}switchToMode(e,n){this._eventBus.on("annotationeditormodechanged",n,{once:!0,signal:this._signal}),this._eventBus.dispatch("showannotationeditorui",{source:this,mode:e})}setPreference(e,n){this._eventBus.dispatch("setpreference",{source:this,name:e,value:n})}onSetPreference({name:e,value:n}){switch(e){case"enableNewAltTextWhenAddingImage":this.#b=n;break}}onPageChanging({pageNumber:e}){this.#f=e-1}focusMainContainer(){this.#V.focus()}findParent(e,n){for(let r of this.#a.values()){let{x:i,y:o,width:a,height:s}=r.div.getBoundingClientRect();if(e>=i&&e<=i+a&&n>=o&&n<=o+s)return r}return null}disableUserSelect(e=!1){this.#W.classList.toggle("noUserSelect",e)}addShouldRescale(e){this.#p.add(e)}removeShouldRescale(e){this.#p.delete(e)}onScaleChanging({scale:e}){this.commitOrRemove(),this.viewParameters.realScale=e*Ta.PDF_TO_CSS_UNITS;for(let n of this.#p)n.onScaleChanging();this.#d?.onScaleChanging()}onRotationChanging({pagesRotation:e}){this.commitOrRemove(),this.viewParameters.rotation=e}#J({anchorNode:e}){return e.nodeType===Node.TEXT_NODE?e.parentElement:e}#ee(e){let{currentLayer:n}=this;if(n.hasTextLayer(e))return n;for(let r of this.#a.values())if(r.hasTextLayer(e))return r;return null}highlightSelection(e="",n=!1){let r=document.getSelection();if(!r||r.isCollapsed)return;let{anchorNode:i,anchorOffset:o,focusNode:a,focusOffset:s}=r,l=r.toString(),u=this.#J(r).closest(".textLayer"),d=this.getSelectionBoxes(u);if(!d)return;r.empty();let h=this.#ee(u),f=this.#E===$e.NONE,m=()=>{let p=h?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:e,boxes:d,anchorNode:i,anchorOffset:o,focusNode:a,focusOffset:s,text:l});f&&this.showAllEditors("highlight",!0,!0),n&&p?.editComment()};if(f){this.switchToMode($e.HIGHLIGHT,m);return}m()}commentSelection(e=""){this.highlightSelection(e,!0)}#ae(){let e=document.getSelection();if(!e||e.isCollapsed)return;let r=this.#J(e).closest(".textLayer"),i=this.getSelectionBoxes(r);i&&(this.#$||=new ik(this),this.#$.show(r,i,this.direction==="ltr"))}getAndRemoveDataFromAnnotationStorage(e){if(!this.#o)return null;let n=`${qm}${e}`,r=this.#o.getRawValue(n);return r&&this.#o.remove(n),r}addToAnnotationStorage(e){!e.isEmpty()&&this.#o&&!this.#o.has(e.id)&&this.#o.setValue(e.id,e)}a11yAlert(e,n=null){let r=this.#Q;r&&(r.setAttribute("data-l10n-id",e),n?r.setAttribute("data-l10n-args",JSON.stringify(n)):r.removeAttribute("data-l10n-args"))}#se(){let e=document.getSelection();if(!e||e.isCollapsed){this.#O&&(this.#$?.hide(),this.#O=null,this.#C({hasSelectedText:!1}));return}let{anchorNode:n}=e;if(n===this.#O)return;let i=this.#J(e).closest(".textLayer");if(!i){this.#O&&(this.#$?.hide(),this.#O=null,this.#C({hasSelectedText:!1}));return}if(this.#$?.hide(),this.#O=n,this.#C({hasSelectedText:!0}),!(this.#E!==$e.HIGHLIGHT&&this.#E!==$e.NONE)&&(this.#E===$e.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),this.#w=this.isShiftKeyDown,!this.isShiftKeyDown)){let o=this.#E===$e.HIGHLIGHT?this.#ee(i):null;if(o?.toggleDrawing(),this.#k){let a=new AbortController,s=this.combinedSignal(a),l=c=>{c.type==="pointerup"&&c.button!==0||(a.abort(),o?.toggleDrawing(!0),c.type==="pointerup"&&this.#Y("main_toolbar"))};window.addEventListener("pointerup",l,{signal:s}),window.addEventListener("blur",l,{signal:s})}else o?.toggleDrawing(!0),this.#Y("main_toolbar")}}#Y(e=""){this.#E===$e.HIGHLIGHT?this.highlightSelection(e):this.#v&&this.#ae()}#le(){document.addEventListener("selectionchange",this.#se.bind(this),{signal:this._signal})}#ce(){if(this.#S)return;this.#S=new AbortController;let e=this.combinedSignal(this.#S);window.addEventListener("focus",this.focus.bind(this),{signal:e}),window.addEventListener("blur",this.blur.bind(this),{signal:e})}#ue(){this.#S?.abort(),this.#S=null}blur(){if(this.isShiftKeyDown=!1,this.#w&&(this.#w=!1,this.#Y("main_toolbar")),!this.hasSelection)return;let{activeElement:e}=document;for(let n of this.#_)if(n.div.contains(e)){this.#P=[n,e],n._focusEventsAllowed=!1;break}}focus(){if(!this.#P)return;let[e,n]=this.#P;this.#P=null,n.addEventListener("focusin",()=>{e._focusEventsAllowed=!0},{once:!0,signal:this._signal}),n.focus()}#te(){if(this.#I)return;this.#I=new AbortController;let e=this.combinedSignal(this.#I);window.addEventListener("keydown",this.keydown.bind(this),{signal:e}),window.addEventListener("keyup",this.keyup.bind(this),{signal:e})}#de(){this.#I?.abort(),this.#I=null}#ne(){if(this.#h)return;this.#h=new AbortController;let e=this.combinedSignal(this.#h);document.addEventListener("copy",this.copy.bind(this),{signal:e}),document.addEventListener("cut",this.cut.bind(this),{signal:e}),document.addEventListener("paste",this.paste.bind(this),{signal:e})}#ie(){this.#h?.abort(),this.#h=null}#he(){let e=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:e}),document.addEventListener("drop",this.drop.bind(this),{signal:e})}addEditListeners(){this.#te(),this.#ne()}removeEditListeners(){this.#de(),this.#ie()}dragOver(e){for(let{type:n}of e.dataTransfer.items)for(let r of this.#u)if(r.isHandlingMimeForPasting(n)){e.dataTransfer.dropEffect="copy",e.preventDefault();return}}drop(e){for(let n of e.dataTransfer.items)for(let r of this.#u)if(r.isHandlingMimeForPasting(n.type)){r.paste(n,this.currentLayer),e.preventDefault();return}}copy(e){if(e.preventDefault(),this.#t?.commitOrRemove(),!this.hasSelection)return;let n=[];for(let r of this.#_){let i=r.serialize(!0);i&&n.push(i)}n.length!==0&&e.clipboardData.setData("application/pdfjs",JSON.stringify(n))}cut(e){this.copy(e),this.delete()}async paste(e){e.preventDefault();let{clipboardData:n}=e;for(let o of n.items)for(let a of this.#u)if(a.isHandlingMimeForPasting(o.type)){a.paste(o,this.currentLayer);return}let r=n.getData("application/pdfjs");if(!r)return;try{r=JSON.parse(r)}catch(o){we(`paste: "${o.message}".`);return}if(!Array.isArray(r))return;this.unselectAll();let i=this.currentLayer;try{let o=[];for(let l of r){let c=await i.deserialize(l);if(!c)return;o.push(c)}let a=()=>{for(let l of o)this.#re(l);this.#oe(o)},s=()=>{for(let l of o)l.remove()};this.addCommands({cmd:a,undo:s,mustExec:!0})}catch(o){we(`paste: "${o.message}".`)}}keydown(e){!this.isShiftKeyDown&&e.key==="Shift"&&(this.isShiftKeyDown=!0),this.#E!==$e.NONE&&!this.isEditorHandlingKeyboard&&t._keyboardManager.exec(this,e)}keyup(e){this.isShiftKeyDown&&e.key==="Shift"&&(this.isShiftKeyDown=!1,this.#w&&(this.#w=!1,this.#Y("main_toolbar")))}onEditingAction({name:e}){switch(e){case"undo":case"redo":case"delete":case"selectAll":this[e]();break;case"highlightSelection":this.highlightSelection("context_menu");break;case"commentSelection":this.commentSelection("context_menu");break}}#C(e){Object.entries(e).some(([r,i])=>this.#K[r]!==i)&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#K,e)}),this.#E===$e.HIGHLIGHT&&e.hasSelectedEditor===!1&&this.#B([[je.HIGHLIGHT_FREE,!0]]))}#B(e){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:e})}setEditingState(e){e?(this.#ce(),this.#ne(),this.#C({isEditing:this.#E!==$e.NONE,isEmpty:this.#X(),hasSomethingToUndo:this.#c.hasSomethingToUndo(),hasSomethingToRedo:this.#c.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#ue(),this.#ie(),this.#C({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(e){if(!this.#u){this.#u=e;for(let n of this.#u)this.#B(n.defaultPropertiesToUpdate)}}getId(){return this.#R.id}get currentLayer(){return this.#a.get(this.#f)}getLayer(e){return this.#a.get(e)}get currentPageIndex(){return this.#f}addLayer(e){this.#a.set(e.pageIndex,e),this.#z?e.enable():e.disable()}removeLayer(e){this.#a.delete(e.pageIndex)}async updateMode(e,n=null,r=!1,i=!1,o=!1){if(this.#E!==e&&!(this.#U&&(await this.#U.promise,!this.#U))){if(this.#U=Promise.withResolvers(),this.#d?.commitOrRemove(),this.#E===$e.POPUP&&this.#l?.hideSidebar(),this.#l?.destroyPopup(),this.#E=e,e===$e.NONE){this.setEditingState(!1),this.#me();for(let a of this.#n.values())a.hideStandaloneCommentButton();this._editorUndoBar?.hide(),this.toggleComment(null),this.#U.resolve();return}for(let a of this.#n.values())a.addStandaloneCommentButton();e===$e.SIGNATURE&&await this.#j?.loadSignatures(),this.setEditingState(!0),await this.#fe(),this.unselectAll();for(let a of this.#a.values())a.updateMode(e);if(e===$e.POPUP){this.#i||=await this.#Z.getAnnotationsByType(new Set(this.#u.map(l=>l._editorType)));let a=new Set,s=[];for(let l of this.#n.values()){let{annotationElementId:c,hasComment:u,deleted:d}=l;c&&a.add(c),u&&!d&&s.push(l.getData())}for(let l of this.#i){let{id:c,popupRef:u,contentsObj:d}=l;u&&d?.str&&!a.has(c)&&!this.#g.has(c)&&s.push(l)}this.#l?.showSidebar(s)}if(!n){r&&this.addNewEditorFromKeyboard(),this.#U.resolve();return}for(let a of this.#n.values())a.uid===n?(this.setSelected(a),o?a.editComment():i?a.enterInEditMode():a.focus()):a.unselect();this.#U.resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(e){e.mode!==this.#E&&this._eventBus.dispatch("switchannotationeditormode",{source:this,...e})}updateParams(e,n){if(this.#u){switch(e){case je.CREATE:this.currentLayer.addNewEditor(n);return;case je.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(this.#G||=new Map).set(e,n),this.showAllEditors("highlight",n);break}if(this.hasSelection)for(let r of this.#_)r.updateParams(e,n);else for(let r of this.#u)r.updateDefaultParams(e,n)}}showAllEditors(e,n,r=!1){for(let o of this.#n.values())o.editorType===e&&o.show(n);(this.#G?.get(je.HIGHLIGHT_SHOW_ALL)??!0)!==n&&this.#B([[je.HIGHLIGHT_SHOW_ALL,n]])}enableWaiting(e=!1){if(this.#D!==e){this.#D=e;for(let n of this.#a.values())e?n.disableClick():n.enableClick(),n.div.classList.toggle("waiting",e)}}async#fe(){if(!this.#z){this.#z=!0;let e=[];for(let n of this.#a.values())e.push(n.enable());await Promise.all(e);for(let n of this.#n.values())n.enable()}}#me(){if(this.unselectAll(),this.#z){this.#z=!1;for(let e of this.#a.values())e.disable();for(let e of this.#n.values())e.disable()}}*getEditors(e){for(let n of this.#n.values())n.pageIndex===e&&(yield n)}getEditor(e){return this.#n.get(e)}addEditor(e){this.#n.set(e.id,e)}removeEditor(e){e.div.contains(document.activeElement)&&(this.#x&&clearTimeout(this.#x),this.#x=setTimeout(()=>{this.focusMainContainer(),this.#x=null},0)),this.#n.delete(e.id),e.annotationElementId&&this.#N?.delete(e.annotationElementId),this.unselect(e),(!e.annotationElementId||!this.#g.has(e.annotationElementId))&&this.#o?.remove(e.id)}addDeletedAnnotationElement(e){this.#g.add(e.annotationElementId),this.addChangedExistingAnnotation(e),e.deleted=!0}isDeletedAnnotationElement(e){return this.#g.has(e)}removeDeletedAnnotationElement(e){this.#g.delete(e.annotationElementId),this.removeChangedExistingAnnotation(e),e.deleted=!1}#re(e){let n=this.#a.get(e.pageIndex);n?n.addOrRebuild(e):(this.addEditor(e),this.addToAnnotationStorage(e))}setActiveEditor(e){this.#t!==e&&(this.#t=e,e&&this.#B(e.propertiesToUpdate))}get#pe(){let e=null;for(e of this.#_);return e}updateUI(e){this.#pe===e&&this.#B(e.propertiesToUpdate)}updateUIForDefaultProperties(e){this.#B(e.defaultPropertiesToUpdate)}toggleSelected(e){if(this.#_.has(e)){this.#_.delete(e),e.unselect(),this.#C({hasSelectedEditor:this.hasSelection});return}this.#_.add(e),e.select(),this.#B(e.propertiesToUpdate),this.#C({hasSelectedEditor:!0})}setSelected(e){this.updateToolbar({mode:e.mode,editId:e.id}),this.#d?.commitOrRemove();for(let n of this.#_)n!==e&&n.unselect();this.#_.clear(),this.#_.add(e),e.select(),this.#B(e.propertiesToUpdate),this.#C({hasSelectedEditor:!0})}isSelected(e){return this.#_.has(e)}get firstSelectedEditor(){return this.#_.values().next().value}unselect(e){e.unselect(),this.#_.delete(e),this.#C({hasSelectedEditor:this.hasSelection})}get hasSelection(){return this.#_.size!==0}get isEnterHandled(){return this.#_.size===1&&this.firstSelectedEditor.isEnterHandled}undo(){this.#c.undo(),this.#C({hasSomethingToUndo:this.#c.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#X()}),this._editorUndoBar?.hide()}redo(){this.#c.redo(),this.#C({hasSomethingToUndo:!0,hasSomethingToRedo:this.#c.hasSomethingToRedo(),isEmpty:this.#X()})}addCommands(e){this.#c.add(e),this.#C({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#X()})}cleanUndoStack(e){this.#c.cleanType(e)}#X(){if(this.#n.size===0)return!0;if(this.#n.size===1)for(let e of this.#n.values())return e.isEmpty();return!1}delete(){this.commitOrRemove();let e=this.currentLayer?.endDrawingSession(!0);if(!this.hasSelection&&!e)return;let n=e?[e]:[...this.#_],r=()=>{this._editorUndoBar?.show(i,n.length===1?n[0].editorType:n.length);for(let o of n)o.remove()},i=()=>{for(let o of n)this.#re(o)};this.addCommands({cmd:r,undo:i,mustExec:!0})}commitOrRemove(){this.#t?.commitOrRemove()}hasSomethingToControl(){return this.#t||this.hasSelection}#oe(e){for(let n of this.#_)n.unselect();this.#_.clear();for(let n of e)n.isEmpty()||(this.#_.add(n),n.select());this.#C({hasSelectedEditor:this.hasSelection})}selectAll(){for(let e of this.#_)e.commit();this.#oe(this.#n.values())}unselectAll(){if(!(this.#t&&(this.#t.commitOrRemove(),this.#E!==$e.NONE))&&!this.#d?.commitOrRemove()&&this.hasSelection){for(let e of this.#_)e.unselect();this.#_.clear(),this.#C({hasSelectedEditor:!1})}}translateSelectedEditors(e,n,r=!1){if(r||this.commitOrRemove(),!this.hasSelection)return;this.#F[0]+=e,this.#F[1]+=n;let[i,o]=this.#F,a=[...this.#_],s=1e3;this.#M&&clearTimeout(this.#M),this.#M=setTimeout(()=>{this.#M=null,this.#F[0]=this.#F[1]=0,this.addCommands({cmd:()=>{for(let l of a)this.#n.has(l.id)&&(l.translateInPage(i,o),l.translationDone())},undo:()=>{for(let l of a)this.#n.has(l.id)&&(l.translateInPage(-i,-o),l.translationDone())},mustExec:!1})},s);for(let l of a)l.translateInPage(e,n),l.translationDone()}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#m=new Map;for(let e of this.#_)this.#m.set(e,{savedX:e.x,savedY:e.y,savedPageIndex:e.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#m)return!1;this.disableUserSelect(!1);let e=this.#m;this.#m=null;let n=!1;for(let[{x:i,y:o,pageIndex:a},s]of e)s.newX=i,s.newY=o,s.newPageIndex=a,n||=i!==s.savedX||o!==s.savedY||a!==s.savedPageIndex;if(!n)return!1;let r=(i,o,a,s)=>{if(this.#n.has(i.id)){let l=this.#a.get(s);l?i._setParentAndPosition(l,o,a):(i.pageIndex=s,i.x=o,i.y=a)}};return this.addCommands({cmd:()=>{for(let[i,{newX:o,newY:a,newPageIndex:s}]of e)r(i,o,a,s)},undo:()=>{for(let[i,{savedX:o,savedY:a,savedPageIndex:s}]of e)r(i,o,a,s)},mustExec:!0}),!0}dragSelectedEditors(e,n){if(this.#m)for(let r of this.#m.keys())r.drag(e,n)}rebuild(e){if(e.parent===null){let n=this.getLayer(e.pageIndex);n?(n.changeParent(e),n.addOrRebuild(e)):(this.addEditor(e),this.addToAnnotationStorage(e),e.rebuild())}else e.parent.addOrRebuild(e)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||this.#_.size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(e){return this.#t===e}getActive(){return this.#t}getMode(){return this.#E}isEditingMode(){return this.#E!==$e.NONE}get imageManager(){return Re(this,"imageManager",new ok)}getSelectionBoxes(e){if(!e)return null;let n=document.getSelection();for(let c=0,u=n.rangeCount;c<u;c++)if(!e.contains(n.getRangeAt(c).commonAncestorContainer))return null;let{x:r,y:i,width:o,height:a}=e.getBoundingClientRect(),s;switch(e.getAttribute("data-main-rotation")){case"90":s=(c,u,d,h)=>({x:(u-i)/a,y:1-(c+d-r)/o,width:h/a,height:d/o});break;case"180":s=(c,u,d,h)=>({x:1-(c+d-r)/o,y:1-(u+h-i)/a,width:d/o,height:h/a});break;case"270":s=(c,u,d,h)=>({x:1-(u+h-i)/a,y:(c-r)/o,width:h/a,height:d/o});break;default:s=(c,u,d,h)=>({x:(c-r)/o,y:(u-i)/a,width:d/o,height:h/a});break}let l=[];for(let c=0,u=n.rangeCount;c<u;c++){let d=n.getRangeAt(c);if(!d.collapsed)for(let{x:h,y:f,width:m,height:p}of d.getClientRects())m===0||p===0||l.push(s(h,f,m,p))}return l.length===0?null:l}addChangedExistingAnnotation({annotationElementId:e,id:n}){(this.#s||=new Map).set(e,n)}removeChangedExistingAnnotation({annotationElementId:e}){this.#s?.delete(e)}renderAnnotationElement(e){let n=this.#s?.get(e.data.id);if(!n)return;let r=this.#o.getRawValue(n);r&&(this.#E===$e.NONE&&!r.hasBeenModified||r.renderAnnotationElement(e))}setMissingCanvas(e,n,r){let i=this.#N?.get(e);i&&(i.setCanvas(n,r),this.#N.delete(e))}addMissingCanvas(e,n){(this.#N||=new Map).set(e,n)}},hS=class t{#e=null;#t=!1;#i=null;#n=null;#a=null;#r=null;#o=!1;#s=null;#c=null;#l=null;#h=null;#d=!1;static#f=null;static _l10n=null;constructor(e){this.#c=e,this.#d=e._uiManager.useNewAltTextFlow,t.#f||=Object.freeze({added:"pdfjs-editor-new-alt-text-added-button","added-label":"pdfjs-editor-new-alt-text-added-button-label",missing:"pdfjs-editor-new-alt-text-missing-button","missing-label":"pdfjs-editor-new-alt-text-missing-button-label",review:"pdfjs-editor-new-alt-text-to-review-button","review-label":"pdfjs-editor-new-alt-text-to-review-button-label"})}static initialize(e){t._l10n??=e}async render(){let e=this.#i=document.createElement("button");e.className="altText",e.tabIndex="0";let n=this.#n=document.createElement("span");e.append(n),this.#d?(e.classList.add("new"),e.setAttribute("data-l10n-id",t.#f.missing),n.setAttribute("data-l10n-id",t.#f["missing-label"])):(e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button"),n.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button-label"));let r=this.#c._uiManager._signal;e.addEventListener("contextmenu",Ni,{signal:r}),e.addEventListener("pointerdown",o=>o.stopPropagation(),{signal:r});let i=o=>{o.preventDefault(),this.#c._uiManager.editAltText(this.#c),this.#d&&this.#c._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:this.#g}})};return e.addEventListener("click",i,{capture:!0,signal:r}),e.addEventListener("keydown",o=>{o.target===e&&o.key==="Enter"&&(this.#o=!0,i(o))},{signal:r}),await this.#m(),e}get#g(){return this.#e&&"added"||this.#e===null&&this.guessedText&&"review"||"missing"}finish(){this.#i&&(this.#i.focus({focusVisible:this.#o}),this.#o=!1)}isEmpty(){return this.#d?this.#e===null:!this.#e&&!this.#t}hasData(){return this.#d?this.#e!==null||!!this.#l:this.isEmpty()}get guessedText(){return this.#l}async setGuessedText(e){this.#e===null&&(this.#l=e,this.#h=await t._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:e}),this.#m())}toggleAltTextBadge(e=!1){if(!this.#d||this.#e){this.#s?.remove(),this.#s=null;return}if(!this.#s){let n=this.#s=document.createElement("div");n.className="noAltTextBadge",this.#c.div.append(n)}this.#s.classList.toggle("hidden",!e)}serialize(e){let n=this.#e;return!e&&this.#l===n&&(n=this.#h),{altText:n,decorative:this.#t,guessedText:this.#l,textWithDisclaimer:this.#h}}get data(){return{altText:this.#e,decorative:this.#t}}set data({altText:e,decorative:n,guessedText:r,textWithDisclaimer:i,cancel:o=!1}){r&&(this.#l=r,this.#h=i),!(this.#e===e&&this.#t===n)&&(o||(this.#e=e,this.#t=n),this.#m())}toggle(e=!1){this.#i&&(!e&&this.#r&&(clearTimeout(this.#r),this.#r=null),this.#i.disabled=!e)}shown(){this.#c._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:this.#g}})}destroy(){this.#i?.remove(),this.#i=null,this.#n=null,this.#a=null,this.#s?.remove(),this.#s=null}async#m(){let e=this.#i;if(!e)return;if(this.#d){if(e.classList.toggle("done",!!this.#e),e.setAttribute("data-l10n-id",t.#f[this.#g]),this.#n?.setAttribute("data-l10n-id",t.#f[`${this.#g}-label`]),!this.#e){this.#a?.remove();return}}else{if(!this.#e&&!this.#t){e.classList.remove("done"),this.#a?.remove();return}e.classList.add("done"),e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let n=this.#a;if(!n){this.#a=n=document.createElement("span"),n.className="tooltip",n.setAttribute("role","tooltip"),n.id=`alt-text-tooltip-${this.#c.id}`;let i=100,o=this.#c._uiManager._signal;o.addEventListener("abort",()=>{clearTimeout(this.#r),this.#r=null},{once:!0}),e.addEventListener("mouseenter",()=>{this.#r=setTimeout(()=>{this.#r=null,this.#a.classList.add("show"),this.#c._reportTelemetry({action:"alt_text_tooltip"})},i)},{signal:o}),e.addEventListener("mouseleave",()=>{this.#r&&(clearTimeout(this.#r),this.#r=null),this.#a?.classList.remove("show")},{signal:o})}this.#t?n.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip"):(n.removeAttribute("data-l10n-id"),n.textContent=this.#e),n.parentNode||e.append(n),this.#c.getElementForAltText()?.setAttribute("aria-describedby",n.id)}},du=class{#e=null;#t=null;#i=!1;#n=null;#a=null;#r=null;#o=null;#s=null;#c=!1;#l=null;constructor(e){this.#n=e}renderForToolbar(){let e=this.#t=document.createElement("button");return e.className="comment",this.#h(e,!1)}renderForStandalone(){let e=this.#e=document.createElement("button");e.className="annotationCommentButton";let n=this.#n.commentButtonPosition;if(n){let{style:r}=e;r.insetInlineEnd=`calc(${100*(this.#n._uiManager.direction==="ltr"?1-n[0]:n[0])}% - var(--comment-button-dim))`,r.top=`calc(${100*n[1]}% - var(--comment-button-dim))`;let i=this.#n.commentButtonColor;i&&(r.backgroundColor=i)}return this.#h(e,!0)}focusButton(){setTimeout(()=>{(this.#e??this.#t)?.focus()},0)}onUpdatedColor(){if(!this.#e)return;let e=this.#n.commentButtonColor;e&&(this.#e.style.backgroundColor=e),this.#n._uiManager.updatePopupColor(this.#n)}get commentButtonWidth(){return(this.#e?.getBoundingClientRect().width??0)/this.#n.parent.boundingClientRect.width}get commentPopupPositionInLayer(){if(this.#l)return this.#l;if(!this.#e)return null;let{x:e,y:n,height:r}=this.#e.getBoundingClientRect(),{x:i,y:o,width:a,height:s}=this.#n.parent.boundingClientRect;return[(e-i)/a,(n+r-o)/s]}set commentPopupPositionInLayer(e){this.#l=e}hasDefaultPopupPosition(){return this.#l===null}removeStandaloneCommentButton(){this.#e?.remove(),this.#e=null}removeToolbarCommentButton(){this.#t?.remove(),this.#t=null}setCommentButtonStates({selected:e,hasPopup:n}){this.#e&&(this.#e.classList.toggle("selected",e),this.#e.ariaExpanded=n)}#h(e,n){if(!this.#n._uiManager.hasCommentManager())return null;e.tabIndex="0",e.ariaHasPopup="dialog",n?(e.ariaControls="commentPopup",e.setAttribute("data-l10n-id","pdfjs-show-comment-button")):(e.ariaControlsElements=[this.#n._uiManager.getCommentDialogElement()],e.setAttribute("data-l10n-id","pdfjs-editor-edit-comment-button"));let r=this.#n._uiManager._signal;if(!(r instanceof AbortSignal)||r.aborted)return e;e.addEventListener("contextmenu",Ni,{signal:r}),n&&(e.addEventListener("focusin",o=>{this.#n._focusEventsAllowed=!1,Et(o)},{capture:!0,signal:r}),e.addEventListener("focusout",o=>{this.#n._focusEventsAllowed=!0,Et(o)},{capture:!0,signal:r})),e.addEventListener("pointerdown",o=>o.stopPropagation(),{signal:r});let i=o=>{o.preventDefault(),e===this.#t?this.edit():this.#n.toggleComment(!0)};return e.addEventListener("click",i,{capture:!0,signal:r}),e.addEventListener("keydown",o=>{o.target===e&&o.key==="Enter"&&(this.#i=!0,i(o))},{signal:r}),e.addEventListener("pointerenter",()=>{this.#n.toggleComment(!1,!0)},{signal:r}),e.addEventListener("pointerleave",()=>{this.#n.toggleComment(!1,!1)},{signal:r}),e}edit(e){let n=this.commentPopupPositionInLayer,r,i;if(n)[r,i]=n;else{[r,i]=this.#n.commentButtonPosition;let{width:u,height:d,x:h,y:f}=this.#n;r=h+r*u,i=f+i*d}let o=this.#n.parent.boundingClientRect,{x:a,y:s,width:l,height:c}=o;this.#n._uiManager.editComment(this.#n,a+r*l,s+i*c,{...e,parentDimensions:o})}finish(){this.#t&&(this.#t.focus({focusVisible:this.#i}),this.#i=!1)}isDeleted(){return this.#c||this.#o===""}isEmpty(){return this.#o===null}hasBeenEdited(){return this.isDeleted()||this.#o!==this.#a}serialize(){return this.data}get data(){return{text:this.#o,richText:this.#r,date:this.#s,deleted:this.isDeleted()}}set data(e){if(e!==this.#o&&(this.#r=null),e===null){this.#o="",this.#c=!0;return}this.#o=e,this.#s=new Date,this.#c=!1}setInitialText(e,n=null){this.#a=e,this.data=e,this.#s=null,this.#r=n}shown(){}destroy(){this.#t?.remove(),this.#t=null,this.#e?.remove(),this.#e=null,this.#o="",this.#r=null,this.#s=null,this.#n=null,this.#i=!1,this.#c=!1}},fS=class t{#e;#t=!1;#i=null;#n;#a;#r;#o;#s=null;#c;#l=null;#h;#d=null;constructor({container:e,isPinchingDisabled:n=null,isPinchingStopped:r=null,onPinchStart:i=null,onPinching:o=null,onPinchEnd:a=null,signal:s}){this.#e=e,this.#i=r,this.#n=n,this.#a=i,this.#r=o,this.#o=a,this.#h=new AbortController,this.#c=AbortSignal.any([s,this.#h.signal]),e.addEventListener("touchstart",this.#f.bind(this),{passive:!1,signal:this.#c})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return 35/xo.pixelRatio}#f(e){if(this.#n?.())return;if(e.touches.length===1){if(this.#s)return;let i=this.#s=new AbortController,o=AbortSignal.any([this.#c,i.signal]),a=this.#e,s={capture:!0,signal:o,passive:!1},l=c=>{c.pointerType==="touch"&&(this.#s?.abort(),this.#s=null)};a.addEventListener("pointerdown",c=>{c.pointerType==="touch"&&(Et(c),l(c))},s),a.addEventListener("pointerup",l,s),a.addEventListener("pointercancel",l,s);return}if(!this.#d){this.#d=new AbortController;let i=AbortSignal.any([this.#c,this.#d.signal]),o=this.#e,a={signal:i,capture:!1,passive:!1};o.addEventListener("touchmove",this.#g.bind(this),a);let s=this.#m.bind(this);o.addEventListener("touchend",s,a),o.addEventListener("touchcancel",s,a),a.capture=!0,o.addEventListener("pointerdown",Et,a),o.addEventListener("pointermove",Et,a),o.addEventListener("pointercancel",Et,a),o.addEventListener("pointerup",Et,a),this.#a?.()}if(Et(e),e.touches.length!==2||this.#i?.()){this.#l=null;return}let[n,r]=e.touches;n.identifier>r.identifier&&([n,r]=[r,n]),this.#l={touch0X:n.screenX,touch0Y:n.screenY,touch1X:r.screenX,touch1Y:r.screenY}}#g(e){if(!this.#l||e.touches.length!==2)return;Et(e);let[n,r]=e.touches;n.identifier>r.identifier&&([n,r]=[r,n]);let{screenX:i,screenY:o}=n,{screenX:a,screenY:s}=r,l=this.#l,{touch0X:c,touch0Y:u,touch1X:d,touch1Y:h}=l,f=d-c,m=h-u,p=a-i,y=s-o,g=Math.hypot(p,y)||1,v=Math.hypot(f,m)||1;if(!this.#t&&Math.abs(v-g)<=t.MIN_TOUCH_DISTANCE_TO_PINCH)return;if(l.touch0X=i,l.touch0Y=o,l.touch1X=a,l.touch1Y=s,!this.#t){this.#t=!0;return}let S=[(i+a)/2,(o+s)/2];this.#r?.(S,v,g)}#m(e){e.touches.length>=2||(this.#d&&(this.#d.abort(),this.#d=null,this.#o?.()),this.#l&&(Et(e),this.#l=null,this.#t=!1))}destroy(){this.#h?.abort(),this.#h=null,this.#s?.abort(),this.#s=null}},at=class t{#e=null;#t=null;#i=null;#n=null;#a=null;#r=!1;#o=null;#s="";#c=null;#l=null;#h=null;#d=null;#f=null;#g="";#m=!1;#u=null;#p=!1;#v=!1;#y=!1;#b=null;#A=0;#x=0;#S=null;#T=null;isSelected=!1;_isCopy=!1;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nResizer=null;#w=!1;#$=t._zIndex++;static _borderLineWidth=-1;static _colorManager=new sk;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){let e=t.prototype._resizeWithKeyboard,n=Zs.TRANSLATE_SMALL,r=Zs.TRANSLATE_BIG;return Re(this,"_resizerKeyboardManager",new Vs([[["ArrowLeft","mac+ArrowLeft"],e,{args:[-n,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],e,{args:[-r,0]}],[["ArrowRight","mac+ArrowRight"],e,{args:[n,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],e,{args:[r,0]}],[["ArrowUp","mac+ArrowUp"],e,{args:[0,-n]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],e,{args:[0,-r]}],[["ArrowDown","mac+ArrowDown"],e,{args:[0,n]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],e,{args:[0,r]}],[["Escape","mac+Escape"],t.prototype._stopResizingWithKeyboard]]))}constructor(e){this.parent=e.parent,this.id=e.id,this.width=this.height=null,this.pageIndex=e.parent.pageIndex,this.name=e.name,this.div=null,this._uiManager=e.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=e.isCentered,this._structTreeParentId=null,this.annotationElementId=e.annotationElementId||null,this.creationDate=e.creationDate||new Date,this.modificationDate=e.modificationDate||null;let{rotation:n,rawDims:{pageWidth:r,pageHeight:i,pageX:o,pageY:a}}=this.parent.viewport;this.rotation=n,this.pageRotation=(360+n-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[r,i],this.pageTranslation=[o,a];let[s,l]=this.parentDimensions;this.x=e.x/s,this.y=e.y/l,this.isAttachedToDOM=!1,this.deleted=!1}get editorType(){return Object.getPrototypeOf(this).constructor._type}get mode(){return Object.getPrototypeOf(this).constructor._editorType}static get isDrawer(){return!1}static get _defaultLineColor(){return Re(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(e){let n=new lk({id:e.parent.getNextId(),parent:e.parent,uiManager:e._uiManager});n.annotationElementId=e.annotationElementId,n.deleted=!0,n._uiManager.addToAnnotationStorage(n)}static initialize(e,n){if(t._l10n??=e,t._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"}),t._borderLineWidth!==-1)return;let r=getComputedStyle(document.documentElement);t._borderLineWidth=parseFloat(r.getPropertyValue("--outline-width"))||0}static updateDefaultParams(e,n){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(e){return!1}static paste(e,n){rt("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#w}set _isDraggable(e){this.#w=e,this.div?.classList.toggle("draggable",e)}get uid(){return this.annotationElementId||this.id}get isEnterHandled(){return!0}center(){let[e,n]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*n/(e*2),this.y+=this.width*e/(n*2);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*n/(e*2),this.y-=this.width*e/(n*2);break;default:this.x-=this.width/2,this.y-=this.height/2;break}this.fixAndSetPosition()}addCommands(e){this._uiManager.addCommands(e)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#$}setParent(e){e!==null?(this.pageIndex=e.pageIndex,this.pageDimensions=e.pageDimensions):(this.#M(),this.#d?.remove(),this.#d=null),this.parent=e}focusin(e){this._focusEventsAllowed&&(this.#m?this.#m=!1:this.parent.setSelected(this))}focusout(e){!this._focusEventsAllowed||!this.isAttachedToDOM||e.relatedTarget?.closest(`#${this.id}`)||(e.preventDefault(),this.parent?.isMultipleSelection||this.commitOrRemove())}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.isInEditMode()&&this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(e,n,r,i){let[o,a]=this.parentDimensions;[r,i]=this.screenToPageTranslation(r,i),this.x=(e+r)/o,this.y=(n+i)/a,this.fixAndSetPosition()}_moveAfterPaste(e,n){let[r,i]=this.parentDimensions;this.setAt(e*r,n*i,this.width*r,this.height*i),this._onTranslated()}#R([e,n],r,i){[r,i]=this.screenToPageTranslation(r,i),this.x+=r/e,this.y+=i/n,this._onTranslating(this.x,this.y),this.fixAndSetPosition()}translate(e,n){this.#R(this.parentDimensions,e,n)}translateInPage(e,n){this.#u||=[this.x,this.y,this.width,this.height],this.#R(this.pageDimensions,e,n),this.div.scrollIntoView({block:"nearest"})}translationDone(){this._onTranslated(this.x,this.y)}drag(e,n){this.#u||=[this.x,this.y,this.width,this.height];let{div:r,parentDimensions:[i,o]}=this;if(this.x+=e/i,this.y+=n/o,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){let{x:d,y:h}=this.div.getBoundingClientRect();this.parent.findNewParent(this,d,h)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:a,y:s}=this,[l,c]=this.getBaseTranslation();a+=l,s+=c;let{style:u}=r;u.left=`${(100*a).toFixed(2)}%`,u.top=`${(100*s).toFixed(2)}%`,this._onTranslating(a,s),r.scrollIntoView({block:"nearest"})}_onTranslating(e,n){}_onTranslated(e,n){}get _hasBeenMoved(){return!!this.#u&&(this.#u[0]!==this.x||this.#u[1]!==this.y)}get _hasBeenResized(){return!!this.#u&&(this.#u[2]!==this.width||this.#u[3]!==this.height)}getBaseTranslation(){let[e,n]=this.parentDimensions,{_borderLineWidth:r}=t,i=r/e,o=r/n;switch(this.rotation){case 90:return[-i,o];case 180:return[i,o];case 270:return[i,-o];default:return[-i,-o]}}get _mustFixPosition(){return!0}fixAndSetPosition(e=this.rotation){let{div:{style:n},pageDimensions:[r,i]}=this,{x:o,y:a,width:s,height:l}=this;if(s*=r,l*=i,o*=r,a*=i,this._mustFixPosition)switch(e){case 0:o=Tn(o,0,r-s),a=Tn(a,0,i-l);break;case 90:o=Tn(o,0,r-l),a=Tn(a,s,i);break;case 180:o=Tn(o,s,r),a=Tn(a,l,i);break;case 270:o=Tn(o,l,r),a=Tn(a,0,i-s);break}this.x=o/=r,this.y=a/=i;let[c,u]=this.getBaseTranslation();o+=c,a+=u,n.left=`${(100*o).toFixed(2)}%`,n.top=`${(100*a).toFixed(2)}%`,this.moveInDOM()}static#z(e,n,r){switch(r){case 90:return[n,-e];case 180:return[-e,-n];case 270:return[-n,e];default:return[e,n]}}screenToPageTranslation(e,n){return t.#z(e,n,this.parentRotation)}pageTranslationToScreen(e,n){return t.#z(e,n,360-this.parentRotation)}#k(e){switch(e){case 90:{let[n,r]=this.pageDimensions;return[0,-n/r,r/n,0]}case 180:return[-1,0,0,-1];case 270:{let[n,r]=this.pageDimensions;return[0,n/r,-r/n,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(){let{parentScale:e,pageDimensions:[n,r]}=this;return[n*e,r*e]}setDims(){let{div:{style:e},width:n,height:r}=this;e.width=`${(100*n).toFixed(2)}%`,e.height=`${(100*r).toFixed(2)}%`}getInitialTranslation(){return[0,0]}#D(){if(this.#c)return;this.#c=document.createElement("div"),this.#c.classList.add("resizers");let e=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],n=this._uiManager._signal;for(let r of e){let i=document.createElement("div");this.#c.append(i),i.classList.add("resizer",r),i.setAttribute("data-resizer-name",r),i.addEventListener("pointerdown",this.#I.bind(this,r),{signal:n}),i.addEventListener("contextmenu",Ni,{signal:n}),i.tabIndex=-1}this.div.prepend(this.#c)}#I(e,n){n.preventDefault();let{isMac:r}=Ft.platform;if(n.button!==0||n.ctrlKey&&r)return;this.#i?.toggle(!1);let i=this._isDraggable;this._isDraggable=!1,this.#l=[n.screenX,n.screenY];let o=new AbortController,a=this._uiManager.combinedSignal(o);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",this.#N.bind(this,e),{passive:!0,capture:!0,signal:a}),window.addEventListener("touchmove",Et,{passive:!1,signal:a}),window.addEventListener("contextmenu",Ni,{signal:a}),this.#h={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};let s=this.parent.div.style.cursor,l=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(n.target).cursor;let c=()=>{o.abort(),this.parent.togglePointerEvents(!0),this.#i?.toggle(!0),this._isDraggable=i,this.parent.div.style.cursor=s,this.div.style.cursor=l,this.#L()};window.addEventListener("pointerup",c,{signal:a}),window.addEventListener("blur",c,{signal:a})}#P(e,n,r,i){this.width=r,this.height=i,this.x=e,this.y=n,this.setDims(),this.fixAndSetPosition(),this._onResized()}_onResized(){}#L(){if(!this.#h)return;let{savedX:e,savedY:n,savedWidth:r,savedHeight:i}=this.#h;this.#h=null;let o=this.x,a=this.y,s=this.width,l=this.height;o===e&&a===n&&s===r&&l===i||this.addCommands({cmd:this.#P.bind(this,o,a,s,l),undo:this.#P.bind(this,e,n,r,i),mustExec:!0})}static _round(e){return Math.round(e*1e4)/1e4}#N(e,n){let[r,i]=this.parentDimensions,o=this.x,a=this.y,s=this.width,l=this.height,c=t.MIN_SIZE/r,u=t.MIN_SIZE/i,d=this.#k(this.rotation),h=(ie,ne)=>[d[0]*ie+d[2]*ne,d[1]*ie+d[3]*ne],f=this.#k(360-this.rotation),m=(ie,ne)=>[f[0]*ie+f[2]*ne,f[1]*ie+f[3]*ne],p,y,g=!1,v=!1;switch(e){case"topLeft":g=!0,p=(ie,ne)=>[0,0],y=(ie,ne)=>[ie,ne];break;case"topMiddle":p=(ie,ne)=>[ie/2,0],y=(ie,ne)=>[ie/2,ne];break;case"topRight":g=!0,p=(ie,ne)=>[ie,0],y=(ie,ne)=>[0,ne];break;case"middleRight":v=!0,p=(ie,ne)=>[ie,ne/2],y=(ie,ne)=>[0,ne/2];break;case"bottomRight":g=!0,p=(ie,ne)=>[ie,ne],y=(ie,ne)=>[0,0];break;case"bottomMiddle":p=(ie,ne)=>[ie/2,ne],y=(ie,ne)=>[ie/2,0];break;case"bottomLeft":g=!0,p=(ie,ne)=>[0,ne],y=(ie,ne)=>[ie,0];break;case"middleLeft":v=!0,p=(ie,ne)=>[0,ne/2],y=(ie,ne)=>[ie,ne/2];break}let S=p(s,l),_=y(s,l),$=h(..._),w=t._round(o+$[0]),A=t._round(a+$[1]),k=1,I=1,D,H;if(n.fromKeyboard)({deltaX:D,deltaY:H}=n);else{let{screenX:ie,screenY:ne}=n,[Se,nt]=this.#l;[D,H]=this.screenToPageTranslation(ie-Se,ne-nt),this.#l[0]=ie,this.#l[1]=ne}if([D,H]=m(D/r,H/i),g){let ie=Math.hypot(s,l);k=I=Math.max(Math.min(Math.hypot(_[0]-S[0]-D,_[1]-S[1]-H)/ie,1/s,1/l),c/s,u/l)}else v?k=Tn(Math.abs(_[0]-S[0]-D),c,1)/s:I=Tn(Math.abs(_[1]-S[1]-H),u,1)/l;let ge=t._round(s*k),ce=t._round(l*I);$=h(...y(ge,ce));let me=w-$[0],Te=A-$[1];this.#u||=[this.x,this.y,this.width,this.height],this.width=ge,this.height=ce,this.x=me,this.y=Te,this.setDims(),this.fixAndSetPosition(),this._onResizing()}_onResizing(){}altTextFinish(){this.#i?.finish()}get toolbarButtons(){return null}async addEditToolbar(){if(this._editToolbar||this.#v)return this._editToolbar;this._editToolbar=new nk(this),this.div.append(this._editToolbar.render());let{toolbarButtons:e}=this;if(e)for(let[n,r]of e)await this._editToolbar.addButton(n,r);return this.hasComment||this._editToolbar.addButton("comment",this.addCommentButton()),this._editToolbar.addButton("delete"),this._editToolbar}addCommentButtonInToolbar(){this._editToolbar?.addButtonBefore("comment",this.addCommentButton(),".deleteButton")}removeCommentButtonFromToolbar(){this._editToolbar?.removeButton("comment")}removeEditToolbar(){this._editToolbar?.remove(),this._editToolbar=null,this.#i?.destroy()}addContainer(e){let n=this._editToolbar?.div;n?n.before(e):this.div.append(e)}getClientDimensions(){return this.div.getBoundingClientRect()}createAltText(){return this.#i||(hS.initialize(t._l10n),this.#i=new hS(this),this.#e&&(this.#i.data=this.#e,this.#e=null)),this.#i}get altTextData(){return this.#i?.data}set altTextData(e){this.#i&&(this.#i.data=e)}get guessedAltText(){return this.#i?.guessedText}async setGuessedAltText(e){await this.#i?.setGuessedText(e)}serializeAltText(e){return this.#i?.serialize(e)}hasAltText(){return!!this.#i&&!this.#i.isEmpty()}hasAltTextData(){return this.#i?.hasData()??!1}focusCommentButton(){this.#n?.focusButton()}addCommentButton(){return this.#n||=new du(this)}addStandaloneCommentButton(){if(this.#a){this._uiManager.isEditingMode()&&this.#a.classList.remove("hidden");return}this.hasComment&&(this.#a=this.#n.renderForStandalone(),this.div.append(this.#a))}removeStandaloneCommentButton(){this.#n.removeStandaloneCommentButton(),this.#a=null}hideStandaloneCommentButton(){this.#a?.classList.add("hidden")}get comment(){let{data:{richText:e,text:n,date:r,deleted:i}}=this.#n;return{text:n,richText:e,date:r,deleted:i,color:this.getNonHCMColor(),opacity:this.opacity??1}}set comment(e){this.#n||=new du(this),this.#n.data=e,this.hasComment?(this.removeCommentButtonFromToolbar(),this.addStandaloneCommentButton(),this._uiManager.updateComment(this)):(this.addCommentButtonInToolbar(),this.removeStandaloneCommentButton(),this._uiManager.removeComment(this))}setCommentData({comment:e,popupRef:n,richText:r}){if(!n||(this.#n||=new du(this),this.#n.setInitialText(e,r),!this.annotationElementId))return;let i=this._uiManager.getAndRemoveDataFromAnnotationStorage(this.annotationElementId);i&&this.updateFromAnnotationLayer(i)}get hasEditedComment(){return this.#n?.hasBeenEdited()}get hasDeletedComment(){return this.#n?.isDeleted()}get hasComment(){return!!this.#n&&!this.#n.isEmpty()&&!this.#n.isDeleted()}async editComment(e){this.#n||=new du(this),this.#n.edit(e)}toggleComment(e,n=void 0){this.hasComment&&this._uiManager.toggleComment(this,e,n)}setSelectedCommentButton(e){this.#n.setSelectedButton(e)}addComment(e){if(this.hasEditedComment){let[,,,i]=e.rect,[o]=this.pageDimensions,[a]=this.pageTranslation,s=a+o+1,l=i-100,c=s+180;e.popup={contents:this.comment.text,deleted:this.comment.deleted,rect:[s,l,c,i]}}}updateFromAnnotationLayer({popup:{contents:e,deleted:n}}){this.#n.data=n?null:e}get parentBoundingClientRect(){return this.parent.boundingClientRect}render(){let e=this.div=document.createElement("div");e.setAttribute("data-editor-rotation",(360-this.rotation)%360),e.className=this.name,e.setAttribute("id",this.id),e.tabIndex=this.#r?-1:0,e.setAttribute("role","application"),this.defaultL10nId&&e.setAttribute("data-l10n-id",this.defaultL10nId),this._isVisible||e.classList.add("hidden"),this.setInForeground(),this.#q();let[n,r]=this.parentDimensions;this.parentRotation%180!==0&&(e.style.maxWidth=`${(100*r/n).toFixed(2)}%`,e.style.maxHeight=`${(100*n/r).toFixed(2)}%`);let[i,o]=this.getInitialTranslation();return this.translate(i,o),oU(this,e,["keydown","pointerdown","dblclick"]),this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#T||=new fS({container:e,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#H.bind(this),onPinching:this.#E.bind(this),onPinchEnd:this.#_.bind(this),signal:this._uiManager._signal})),this.addStandaloneCommentButton(),this._uiManager._editorUndoBar?.hide(),e}#H(){this.#h={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height},this.#i?.toggle(!1),this.parent.togglePointerEvents(!1)}#E(e,n,r){let o=.7*(r/n)+1-.7;if(o===1)return;let a=this.#k(this.rotation),s=(w,A)=>[a[0]*w+a[2]*A,a[1]*w+a[3]*A],[l,c]=this.parentDimensions,u=this.x,d=this.y,h=this.width,f=this.height,m=t.MIN_SIZE/l,p=t.MIN_SIZE/c;o=Math.max(Math.min(o,1/h,1/f),m/h,p/f);let y=t._round(h*o),g=t._round(f*o);if(y===h&&g===f)return;this.#u||=[u,d,h,f];let v=s(h/2,f/2),S=t._round(u+v[0]),_=t._round(d+v[1]),$=s(y/2,g/2);this.x=S-$[0],this.y=_-$[1],this.width=y,this.height=g,this.setDims(),this.fixAndSetPosition(),this._onResizing()}#_(){this.#i?.toggle(!0),this.parent.togglePointerEvents(!0),this.#L()}pointerdown(e){let{isMac:n}=Ft.platform;if(e.button!==0||e.ctrlKey&&n){e.preventDefault();return}if(this.#m=!0,this._isDraggable){this.#j(e);return}this.#O(e)}#O(e){let{isMac:n}=Ft.platform;e.ctrlKey&&!n||e.shiftKey||e.metaKey&&n?this.parent.toggleSelected(this):this.parent.setSelected(this)}#j(e){let{isSelected:n}=this;this._uiManager.setUpDragSession();let r=!1,i=new AbortController,o=this._uiManager.combinedSignal(i),a={capture:!0,passive:!1,signal:o},s=c=>{i.abort(),this.#o=null,this.#m=!1,this._uiManager.endDragSession()||this.#O(c),r&&this._onStopDragging()};n&&(this.#A=e.clientX,this.#x=e.clientY,this.#o=e.pointerId,this.#s=e.pointerType,window.addEventListener("pointermove",c=>{r||(r=!0,this._uiManager.toggleComment(this,!0,!1),this._onStartDragging());let{clientX:u,clientY:d,pointerId:h}=c;if(h!==this.#o){Et(c);return}let[f,m]=this.screenToPageTranslation(u-this.#A,d-this.#x);this.#A=u,this.#x=d,this._uiManager.dragSelectedEditors(f,m)},a),window.addEventListener("touchmove",Et,a),window.addEventListener("pointerdown",c=>{c.pointerType===this.#s&&(this.#T||c.isPrimary)&&s(c),Et(c)},a));let l=c=>{if(!this.#o||this.#o===c.pointerId){s(c);return}Et(c)};window.addEventListener("pointerup",l,{signal:o}),window.addEventListener("blur",l,{signal:o})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#b&&clearTimeout(this.#b),this.#b=setTimeout(()=>{this.#b=null,this.parent?.moveEditorInDOM(this)},0)}_setParentAndPosition(e,n,r){e.changeParent(this),this.x=n,this.y=r,this.fixAndSetPosition(),this._onTranslated()}getRect(e,n,r=this.rotation){let i=this.parentScale,[o,a]=this.pageDimensions,[s,l]=this.pageTranslation,c=e/i,u=n/i,d=this.x*o,h=this.y*a,f=this.width*o,m=this.height*a;switch(r){case 0:return[d+c+s,a-h-u-m+l,d+c+f+s,a-h-u+l];case 90:return[d+u+s,a-h+c+l,d+u+m+s,a-h+c+f+l];case 180:return[d-c-f+s,a-h+u+l,d-c+s,a-h+u+m+l];case 270:return[d-u-m+s,a-h-c-f+l,d-u+s,a-h-c+l];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(e,n){let[r,i,o,a]=e,s=o-r,l=a-i;switch(this.rotation){case 0:return[r,n-a,s,l];case 90:return[r,n-i,l,s];case 180:return[o,n-i,s,l];case 270:return[o,n-a,l,s];default:throw new Error("Invalid rotation")}}getPDFRect(){return this.getRect(0,0)}getNonHCMColor(){return this.color&&t._colorManager.convert(this._uiManager.getNonHCMColor(this.color))}onUpdatedColor(){this.#n?.onUpdatedColor()}getData(){let{comment:{text:e,color:n,date:r,opacity:i,deleted:o,richText:a},uid:s,pageIndex:l,creationDate:c,modificationDate:u}=this;return{id:s,pageIndex:l,rect:this.getPDFRect(),richText:a,contentsObj:{str:e},creationDate:c,modificationDate:r||u,popupRef:!o,color:n,opacity:i}}onceAdded(e){}isEmpty(){return!1}enableEditMode(){return this.isInEditMode()?!1:(this.parent.setEditingState(!1),this.#v=!0,!0)}disableEditMode(){return this.isInEditMode()?(this.parent.setEditingState(!0),this.#v=!1,!0):!1}isInEditMode(){return this.#v}shouldGetKeyboardEvents(){return this.#y}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){let{top:e,left:n,bottom:r,right:i}=this.getClientDimensions(),{innerHeight:o,innerWidth:a}=window;return n<a&&i>0&&e<o&&r>0}#q(){if(this.#f||!this.div)return;this.#f=new AbortController;let e=this._uiManager.combinedSignal(this.#f);this.div.addEventListener("focusin",this.focusin.bind(this),{signal:e}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:e})}rebuild(){this.#q()}rotate(e){}resize(){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||""}}serialize(e=!1,n=null){return{annotationType:this.mode,pageIndex:this.pageIndex,rect:this.getPDFRect(),rotation:this.rotation,structTreeParentId:this._structTreeParentId,popupRef:this._initialData?.popupRef||""}}static async deserialize(e,n,r){let i=new this.prototype.constructor({parent:n,id:n.getNextId(),uiManager:r,annotationElementId:e.annotationElementId,creationDate:e.creationDate,modificationDate:e.modificationDate});i.rotation=e.rotation,i.#e=e.accessibilityData,i._isCopy=e.isCopy||!1;let[o,a]=i.pageDimensions,[s,l,c,u]=i.getRectInCurrentCoords(e.rect,a);return i.x=s/o,i.y=l/a,i.width=c/o,i.height=u/a,i}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||this.serialize()!==null)}remove(){if(this.#f?.abort(),this.#f=null,this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.#b&&(clearTimeout(this.#b),this.#b=null),this.#M(),this.removeEditToolbar(),this.#S){for(let e of this.#S.values())clearTimeout(e);this.#S=null}this.parent=null,this.#T?.destroy(),this.#T=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(this.#D(),this.#c.classList.remove("hidden"))}get toolbarPosition(){return null}get commentButtonPosition(){return this._uiManager.direction==="ltr"?[1,0]:[0,0]}get commentButtonPositionInPage(){let{commentButtonPosition:[e,n]}=this,[r,i,o,a]=this.getPDFRect();return[t._round(r+(o-r)*e),t._round(i+(a-i)*(1-n))]}get commentButtonColor(){return this._uiManager.makeCommentColor(this.getNonHCMColor(),this.opacity)}get commentPopupPosition(){return this.#n.commentPopupPositionInLayer}set commentPopupPosition(e){this.#n.commentPopupPositionInLayer=e}hasDefaultPopupPosition(){return this.#n.hasDefaultPopupPosition()}get commentButtonWidth(){return this.#n.commentButtonWidth}get elementBeforePopup(){return this.div}setCommentButtonStates(e){this.#n.setCommentButtonStates(e)}keydown(e){if(!this.isResizable||e.target!==this.div||e.key!=="Enter")return;this._uiManager.setSelected(this),this.#h={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};let n=this.#c.children;if(!this.#t){this.#t=Array.from(n);let a=this.#G.bind(this),s=this.#Z.bind(this),l=this._uiManager._signal;for(let c of this.#t){let u=c.getAttribute("data-resizer-name");c.setAttribute("role","spinbutton"),c.addEventListener("keydown",a,{signal:l}),c.addEventListener("blur",s,{signal:l}),c.addEventListener("focus",this.#K.bind(this,u),{signal:l}),c.setAttribute("data-l10n-id",t._l10nResizer[u])}}let r=this.#t[0],i=0;for(let a of n){if(a===r)break;i++}let o=(360-this.rotation+this.parentRotation)%360/90*(this.#t.length/4);if(o!==i){if(o<i)for(let s=0;s<i-o;s++)this.#c.append(this.#c.firstChild);else if(o>i)for(let s=0;s<o-i;s++)this.#c.firstChild.before(this.#c.lastChild);let a=0;for(let s of n){let c=this.#t[a++].getAttribute("data-resizer-name");s.setAttribute("data-l10n-id",t._l10nResizer[c])}}this.#F(0),this.#y=!0,this.#c.firstChild.focus({focusVisible:!0}),e.preventDefault(),e.stopImmediatePropagation()}#G(e){t._resizerKeyboardManager.exec(this,e)}#Z(e){this.#y&&e.relatedTarget?.parentNode!==this.#c&&this.#M()}#K(e){this.#g=this.#y?e:""}#F(e){if(this.#t)for(let n of this.#t)n.tabIndex=e}_resizeWithKeyboard(e,n){this.#y&&this.#N(this.#g,{deltaX:e,deltaY:n,fromKeyboard:!0})}#M(){this.#y=!1,this.#F(-1),this.#L()}_stopResizingWithKeyboard(){this.#M(),this.div.focus()}select(){if(this.isSelected&&this._editToolbar){this._editToolbar.show();return}if(this.isSelected=!0,this.makeResizable(),this.div?.classList.add("selectedEditor"),!this._editToolbar){this.addEditToolbar().then(()=>{this.div?.classList.contains("selectedEditor")&&this._editToolbar?.show()});return}this._editToolbar?.show(),this.#i?.toggleAltTextBadge(!1)}focus(){this.div&&!this.div.contains(document.activeElement)&&setTimeout(()=>this.div?.focus({preventScroll:!0}),0)}unselect(){this.isSelected&&(this.isSelected=!1,this.#c?.classList.add("hidden"),this.div?.classList.remove("selectedEditor"),this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),this._editToolbar?.hide(),this.#i?.toggleAltTextBadge(!0),this.hasComment&&this._uiManager.toggleComment(this,!1,!1))}updateParams(e,n){}disableEditing(){}enableEditing(){}get canChangeContent(){return!1}enterInEditMode(){this.canChangeContent&&(this.enableEditMode(),this.div.focus())}dblclick(e){e.target.nodeName!=="BUTTON"&&(this.enterInEditMode(),this.parent.updateToolbar({mode:this.constructor._editorType,editId:this.id}))}getElementForAltText(){return this.div}get contentDiv(){return this.div}get isEditing(){return this.#p}set isEditing(e){this.#p=e,this.parent&&(e?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(e,n=!1){if(n){this.#S||=new Map;let{action:r}=e,i=this.#S.get(r);i&&clearTimeout(i),i=setTimeout(()=>{this._reportTelemetry(e),this.#S.delete(r),this.#S.size===0&&(this.#S=null)},t._telemetryTimeout),this.#S.set(r,i);return}e.type||=this.editorType,this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:e}})}show(e=this._isVisible){this.div.classList.toggle("hidden",!e),this._isVisible=e}enable(){this.div&&(this.div.tabIndex=0),this.#r=!1}disable(){this.div&&(this.div.tabIndex=-1),this.#r=!0}updateFakeAnnotationElement(e){if(!this.#d&&!this.deleted){this.#d=e.addFakeAnnotation(this);return}if(this.deleted){this.#d.remove(),this.#d=null;return}(this.hasEditedComment||this._hasBeenMoved||this._hasBeenResized)&&this.#d.updateEdited({rect:this.getPDFRect(),popup:this.comment})}renderAnnotationElement(e){if(this.deleted)return e.hide(),null;let n=e.container.querySelector(".annotationContent");if(!n)n=document.createElement("div"),n.classList.add("annotationContent",this.editorType),e.container.prepend(n);else if(n.nodeName==="CANVAS"){let r=n;n=document.createElement("div"),n.classList.add("annotationContent",this.editorType),r.before(n)}return n}resetAnnotationElement(e){let{firstChild:n}=e.container;n?.nodeName==="DIV"&&n.classList.contains("annotationContent")&&n.remove()}},lk=class extends at{constructor(e){super(e),this.annotationElementId=e.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}},jj=3285377520,Oi=4294901760,Ir=65535,mS=class{constructor(e){this.h1=e?e&4294967295:jj,this.h2=e?e&4294967295:jj}update(e){let n,r;if(typeof e=="string"){n=new Uint8Array(e.length*2),r=0;for(let p=0,y=e.length;p<y;p++){let g=e.charCodeAt(p);g<=255?n[r++]=g:(n[r++]=g>>>8,n[r++]=g&255)}}else if(ArrayBuffer.isView(e))n=e.slice(),r=n.byteLength;else throw new Error("Invalid data format, must be a string or TypedArray.");let i=r>>2,o=r-i*4,a=new Uint32Array(n.buffer,0,i),s=0,l=0,c=this.h1,u=this.h2,d=3432918353,h=461845907,f=d&Ir,m=h&Ir;for(let p=0;p<i;p++)p&1?(s=a[p],s=s*d&Oi|s*f&Ir,s=s<<15|s>>>17,s=s*h&Oi|s*m&Ir,c^=s,c=c<<13|c>>>19,c=c*5+3864292196):(l=a[p],l=l*d&Oi|l*f&Ir,l=l<<15|l>>>17,l=l*h&Oi|l*m&Ir,u^=l,u=u<<13|u>>>19,u=u*5+3864292196);switch(s=0,o){case 3:s^=n[i*4+2]<<16;case 2:s^=n[i*4+1]<<8;case 1:s^=n[i*4],s=s*d&Oi|s*f&Ir,s=s<<15|s>>>17,s=s*h&Oi|s*m&Ir,i&1?c^=s:u^=s}this.h1=c,this.h2=u}hexdigest(){let e=this.h1,n=this.h2;return e^=n>>>1,e=e*3981806797&Oi|e*36045&Ir,n=n*4283543511&Oi|((n<<16|e>>>16)*2950163797&Oi)>>>16,e^=n>>>1,e=e*444984403&Oi|e*60499&Ir,n=n*3301882366&Oi|((n<<16|e>>>16)*3120437893&Oi)>>>16,e^=n>>>1,(e>>>0).toString(16).padStart(8,"0")+(n>>>0).toString(16).padStart(8,"0")}},ck=Object.freeze({map:null,hash:"",transfer:void 0}),Km=class{#e=!1;#t=null;#i=null;#n=new Map;constructor(){this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(e,n){let r=this.#n.get(e);return r===void 0?n:Object.assign(n,r)}getRawValue(e){return this.#n.get(e)}remove(e){let n=this.#n.get(e);if(n!==void 0&&(n instanceof at&&this.#i.delete(n.annotationElementId),this.#n.delete(e),this.#n.size===0&&this.resetModified(),typeof this.onAnnotationEditor=="function")){for(let r of this.#n.values())if(r instanceof at)return;this.onAnnotationEditor(null)}}setValue(e,n){let r=this.#n.get(e),i=!1;if(r!==void 0)for(let[o,a]of Object.entries(n))r[o]!==a&&(i=!0,r[o]=a);else i=!0,this.#n.set(e,n);i&&this.#a(),n instanceof at&&((this.#i||=new Map).set(n.annotationElementId,n),typeof this.onAnnotationEditor=="function"&&this.onAnnotationEditor(n.constructor._type))}has(e){return this.#n.has(e)}get size(){return this.#n.size}#a(){this.#e||(this.#e=!0,typeof this.onSetModified=="function"&&this.onSetModified())}resetModified(){this.#e&&(this.#e=!1,typeof this.onResetModified=="function"&&this.onResetModified())}get print(){return new pS(this)}get serializable(){if(this.#n.size===0)return ck;let e=new Map,n=new mS,r=[],i=Object.create(null),o=!1;for(let[a,s]of this.#n){let l=s instanceof at?s.serialize(!1,i):s;l&&(e.set(a,l),n.update(`${a}:${JSON.stringify(l)}`),o||=!!l.bitmap)}if(o)for(let a of e.values())a.bitmap&&r.push(a.bitmap);return e.size>0?{map:e,hash:n.hexdigest(),transfer:r}:ck}get editorStats(){let e=null,n=new Map,r=0,i=0;for(let o of this.#n.values()){if(!(o instanceof at)){o.popup&&(o.popup.deleted?i+=1:r+=1);continue}o.isCommentDeleted?i+=1:o.hasEditedComment&&(r+=1);let a=o.telemetryFinalData;if(!a)continue;let{type:s}=a;n.has(s)||n.set(s,Object.getPrototypeOf(o).constructor),e||=Object.create(null);let l=e[s]||=new Map;for(let[c,u]of Object.entries(a)){if(c==="type")continue;let d=l.get(c);d||(d=new Map,l.set(c,d));let h=d.get(u)??0;d.set(u,h+1)}}if((i>0||r>0)&&(e||=Object.create(null),e.comments={deleted:i,edited:r}),!e)return null;for(let[o,a]of n)e[o]=a.computeTelemetryFinalData(e[o]);return e}resetModifiedIds(){this.#t=null}updateEditor(e,n){let r=this.#i?.get(e);return r?(r.updateFromAnnotationLayer(n),!0):!1}getEditor(e){return this.#i?.get(e)||null}get modifiedIds(){if(this.#t)return this.#t;let e=[];if(this.#i)for(let n of this.#i.values())n.serialize()&&e.push(n.annotationElementId);return this.#t={ids:new Set(e),hash:e.join(",")}}[Symbol.iterator](){return this.#n.entries()}},pS=class extends Km{#e;constructor(e){super();let{map:n,hash:r,transfer:i}=e.serializable,o=structuredClone(n,i?{transfer:i}:null);this.#e={map:o,hash:r,transfer:i}}get print(){rt("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#e}get modifiedIds(){return Re(this,"modifiedIds",{ids:new Set,hash:""})}},uk=class{#e=new Set;constructor({ownerDocument:e=globalThis.document,styleElement:n=null}){this._document=e,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(e){this.nativeFontFaces.add(e),this._document.fonts.add(e)}removeNativeFontFace(e){this.nativeFontFaces.delete(e),this._document.fonts.delete(e)}insertRule(e){this.styleElement||(this.styleElement=this._document.createElement("style"),this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement));let n=this.styleElement.sheet;n.insertRule(e,n.cssRules.length)}clear(){for(let e of this.nativeFontFaces)this._document.fonts.delete(e);this.nativeFontFaces.clear(),this.#e.clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:e,disableFontFace:n,_inspectFont:r}){if(!(!e||this.#e.has(e.loadedName))){if(Ue(!n,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){let{loadedName:i,src:o,style:a}=e,s=new FontFace(i,o,a);this.addNativeFontFace(s);try{await s.load(),this.#e.add(i),r?.(e)}catch{we(`Cannot load system font: ${e.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(s)}return}rt("Not implemented: loadSystemFont without the Font Loading API.")}}async bind(e){if(e.attached||e.missingFile&&!e.systemFontInfo)return;if(e.attached=!0,e.systemFontInfo){await this.loadSystemFont(e);return}if(this.isFontLoadingAPISupported){let r=e.createNativeFontFace();if(r){this.addNativeFontFace(r);try{await r.loaded}catch(i){throw we(`Failed to load font '${r.family}': '${i}'.`),e.disableFontFace=!0,i}}return}let n=e.createFontFaceRule();if(n){if(this.insertRule(n),this.isSyncFontLoadingSupported)return;await new Promise(r=>{let i=this._queueLoadingCallback(r);this._prepareFontLoadEvent(e,i)})}}get isFontLoadingAPISupported(){let e=!!this._document?.fonts;return Re(this,"isFontLoadingAPISupported",e)}get isSyncFontLoadingSupported(){return Re(this,"isSyncFontLoadingSupported",En||Ft.platform.isFirefox)}_queueLoadingCallback(e){function n(){for(Ue(!i.done,"completeRequest() cannot be called twice."),i.done=!0;r.length>0&&r[0].done;){let o=r.shift();setTimeout(o.callback,0)}}let{loadingRequests:r}=this,i={done:!1,complete:n,callback:e};return r.push(i),i}get _loadTestFont(){let e=atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");return Re(this,"_loadTestFont",e)}_prepareFontLoadEvent(e,n){function r(_,$){return _.charCodeAt($)<<24|_.charCodeAt($+1)<<16|_.charCodeAt($+2)<<8|_.charCodeAt($+3)&255}function i(_,$,w,A){let k=_.substring(0,$),I=_.substring($+w);return k+A+I}let o,a,s=this._document.createElement("canvas");s.width=1,s.height=1;let l=s.getContext("2d"),c=0;function u(_,$){if(++c>30){we("Load test font never loaded."),$();return}if(l.font="30px "+_,l.fillText(".",0,20),l.getImageData(0,0,1,1).data[3]>0){$();return}setTimeout(u.bind(null,_,$))}let d=`lt${Date.now()}${this.loadTestFontId++}`,h=this._loadTestFont;h=i(h,976,d.length,d);let m=16,p=1482184792,y=r(h,m);for(o=0,a=d.length-3;o<a;o+=4)y=y-p+r(d,o)|0;o<d.length&&(y=y-p+r(d+"XXX",o)|0),h=i(h,m,4,hG(y));let g=`url(data:font/opentype;base64,${btoa(h)});`,v=`@font-face {font-family:"${d}";src:${g}}`;this.insertRule(v);let S=this._document.createElement("div");S.style.visibility="hidden",S.style.width=S.style.height="10px",S.style.position="absolute",S.style.top=S.style.left="0px";for(let _ of[e.loadedName,d]){let $=this._document.createElement("span");$.textContent="Hi",$.style.fontFamily=_,S.append($)}this._document.body.append(S),u(d,()=>{S.remove(),n.complete()})}},dk=class{#e;constructor(e,n=null,r,i){this.compiledGlyphs=Object.create(null),this.#e=e,this._inspectFont=n,r&&Object.assign(this,r),i&&(this.charProcOperatorList=i)}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let e;if(!this.cssFontInfo)e=new FontFace(this.loadedName,this.data,{});else{let n={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(n.style=`oblique ${this.cssFontInfo.italicAngle}deg`),e=new FontFace(this.cssFontInfo.fontFamily,this.data,n)}return this._inspectFont?.(this),e}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;let e=`url(data:${this.mimetype};base64,${iU(this.data)});`,n;if(!this.cssFontInfo)n=`@font-face {font-family:"${this.loadedName}";src:${e}}`;else{let r=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(r+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),n=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${r}src:${e}}`}return this._inspectFont?.(this,e),n}getPathGenerator(e,n){if(this.compiledGlyphs[n]!==void 0)return this.compiledGlyphs[n];let r=this.loadedName+"_path_"+n,i;try{i=e.get(r)}catch(a){we(`getPathGenerator - ignoring character: "${a}".`)}let o=new Path2D(i||"");return this.fontExtraProperties||e.delete(r),this.compiledGlyphs[n]=o}get black(){return this.#e.black}get bold(){return this.#e.bold}get disableFontFace(){return this.#e.disableFontFace??!1}get fontExtraProperties(){return this.#e.fontExtraProperties??!1}get isInvalidPDFjsFont(){return this.#e.isInvalidPDFjsFont}get isType3Font(){return this.#e.isType3Font}get italic(){return this.#e.italic}get missingFile(){return this.#e.missingFile}get remeasure(){return this.#e.remeasure}get vertical(){return this.#e.vertical}get ascent(){return this.#e.ascent}get defaultWidth(){return this.#e.defaultWidth}get descent(){return this.#e.descent}get bbox(){return this.#e.bbox}get fontMatrix(){return this.#e.fontMatrix}get fallbackName(){return this.#e.fallbackName}get loadedName(){return this.#e.loadedName}get mimetype(){return this.#e.mimetype}get name(){return this.#e.name}get data(){return this.#e.data}clearData(){this.#e.clearData()}get cssFontInfo(){return this.#e.cssFontInfo}get systemFontInfo(){return this.#e.systemFontInfo}get defaultVMetrics(){return this.#e.defaultVMetrics}};function EG(t){if(t instanceof URL)return t.href;if(typeof t=="string"){if(En)return t;let e=URL.parse(t,window.location);if(e)return e.href}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}function TG(t){if(En&&typeof Buffer<"u"&&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(typeof t=="string")return np(t);if(t instanceof ArrayBuffer||ArrayBuffer.isView(t)||typeof t=="object"&&!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.")}function Wy(t){if(typeof t!="string")return null;if(t.endsWith("/"))return t;throw new Error(`Invalid factory url: "${t}" must include trailing slash.`)}var hk=t=>typeof t=="object"&&Number.isInteger(t?.num)&&t.num>=0&&Number.isInteger(t?.gen)&&t.gen>=0,zG=t=>typeof t=="object"&&typeof t?.name=="string",kG=vG.bind(null,hk,zG),fk=class{#e=new Map;#t=Promise.resolve();postMessage(e,n){let r={data:structuredClone(e,n?{transfer:n}:null)};this.#t.then(()=>{for(let[i]of this.#e)i.call(this,r)})}addEventListener(e,n,r=null){let i=null;if(r?.signal instanceof AbortSignal){let{signal:o}=r;if(o.aborted){we("LoopbackPort - cannot use an `aborted` signal.");return}let a=()=>this.removeEventListener(e,n);i=()=>o.removeEventListener("abort",a),o.addEventListener("abort",a)}this.#e.set(n,i)}removeEventListener(e,n){this.#e.get(n)?.(),this.#e.delete(n)}terminate(){for(let[,e]of this.#e)e?.();this.#e.clear()}},Qy={DATA:1,ERROR:2},Nt={CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function Uj(){}function Zn(t){if(t instanceof Or||t instanceof Bm||t instanceof cS||t instanceof mu||t instanceof Um)return t;switch(t instanceof Error||typeof t=="object"&&t!==null||rt('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),t.name){case"AbortException":return new Or(t.message);case"InvalidPDFException":return new Bm(t.message);case"PasswordException":return new cS(t.message,t.code);case"ResponseException":return new mu(t.message,t.status,t.missing);case"UnknownErrorException":return new Um(t.message,t.details)}return new Um(t.message,t.toString())}var Fs=class{#e=new AbortController;constructor(e,n,r){this.sourceName=e,this.targetName=n,this.comObj=r,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),r.addEventListener("message",this.#t.bind(this),{signal:this.#e.signal})}#t({data:e}){if(e.targetName!==this.sourceName)return;if(e.stream){this.#n(e);return}if(e.callback){let r=e.callbackId,i=this.callbackCapabilities[r];if(!i)throw new Error(`Cannot resolve callback ${r}`);if(delete this.callbackCapabilities[r],e.callback===Qy.DATA)i.resolve(e.data);else if(e.callback===Qy.ERROR)i.reject(Zn(e.reason));else throw new Error("Unexpected callback case");return}let n=this.actionHandler[e.action];if(!n)throw new Error(`Unknown action from worker: ${e.action}`);if(e.callbackId){let r=this.sourceName,i=e.sourceName,o=this.comObj;Promise.try(n,e.data).then(function(a){o.postMessage({sourceName:r,targetName:i,callback:Qy.DATA,callbackId:e.callbackId,data:a})},function(a){o.postMessage({sourceName:r,targetName:i,callback:Qy.ERROR,callbackId:e.callbackId,reason:Zn(a)})});return}if(e.streamId){this.#i(e);return}n(e.data)}on(e,n){let r=this.actionHandler;if(r[e])throw new Error(`There is already an actionName called "${e}"`);r[e]=n}send(e,n,r){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,data:n},r)}sendWithPromise(e,n,r){let i=this.callbackId++,o=Promise.withResolvers();this.callbackCapabilities[i]=o;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,callbackId:i,data:n},r)}catch(a){o.reject(a)}return o.promise}sendWithStream(e,n,r,i){let o=this.streamId++,a=this.sourceName,s=this.targetName,l=this.comObj;return new ReadableStream({start:c=>{let u=Promise.withResolvers();return this.streamControllers[o]={controller:c,startCall:u,pullCall:null,cancelCall:null,isClosed:!1},l.postMessage({sourceName:a,targetName:s,action:e,streamId:o,data:n,desiredSize:c.desiredSize},i),u.promise},pull:c=>{let u=Promise.withResolvers();return this.streamControllers[o].pullCall=u,l.postMessage({sourceName:a,targetName:s,stream:Nt.PULL,streamId:o,desiredSize:c.desiredSize}),u.promise},cancel:c=>{Ue(c instanceof Error,"cancel must have a valid reason");let u=Promise.withResolvers();return this.streamControllers[o].cancelCall=u,this.streamControllers[o].isClosed=!0,l.postMessage({sourceName:a,targetName:s,stream:Nt.CANCEL,streamId:o,reason:Zn(c)}),u.promise}},r)}#i(e){let n=e.streamId,r=this.sourceName,i=e.sourceName,o=this.comObj,a=this,s=this.actionHandler[e.action],l={enqueue(c,u=1,d){if(this.isCancelled)return;let h=this.desiredSize;this.desiredSize-=u,h>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),o.postMessage({sourceName:r,targetName:i,stream:Nt.ENQUEUE,streamId:n,chunk:c},d)},close(){this.isCancelled||(this.isCancelled=!0,o.postMessage({sourceName:r,targetName:i,stream:Nt.CLOSE,streamId:n}),delete a.streamSinks[n])},error(c){Ue(c instanceof Error,"error must have a valid reason"),!this.isCancelled&&(this.isCancelled=!0,o.postMessage({sourceName:r,targetName:i,stream:Nt.ERROR,streamId:n,reason:Zn(c)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:e.desiredSize,ready:null};l.sinkCapability.resolve(),l.ready=l.sinkCapability.promise,this.streamSinks[n]=l,Promise.try(s,e.data,l).then(function(){o.postMessage({sourceName:r,targetName:i,stream:Nt.START_COMPLETE,streamId:n,success:!0})},function(c){o.postMessage({sourceName:r,targetName:i,stream:Nt.START_COMPLETE,streamId:n,reason:Zn(c)})})}#n(e){let n=e.streamId,r=this.sourceName,i=e.sourceName,o=this.comObj,a=this.streamControllers[n],s=this.streamSinks[n];switch(e.stream){case Nt.START_COMPLETE:e.success?a.startCall.resolve():a.startCall.reject(Zn(e.reason));break;case Nt.PULL_COMPLETE:e.success?a.pullCall.resolve():a.pullCall.reject(Zn(e.reason));break;case Nt.PULL:if(!s){o.postMessage({sourceName:r,targetName:i,stream:Nt.PULL_COMPLETE,streamId:n,success:!0});break}s.desiredSize<=0&&e.desiredSize>0&&s.sinkCapability.resolve(),s.desiredSize=e.desiredSize,Promise.try(s.onPull||Uj).then(function(){o.postMessage({sourceName:r,targetName:i,stream:Nt.PULL_COMPLETE,streamId:n,success:!0})},function(c){o.postMessage({sourceName:r,targetName:i,stream:Nt.PULL_COMPLETE,streamId:n,reason:Zn(c)})});break;case Nt.ENQUEUE:if(Ue(a,"enqueue should have stream controller"),a.isClosed)break;a.controller.enqueue(e.chunk);break;case Nt.CLOSE:if(Ue(a,"close should have stream controller"),a.isClosed)break;a.isClosed=!0,a.controller.close(),this.#a(a,n);break;case Nt.ERROR:Ue(a,"error should have stream controller"),a.controller.error(Zn(e.reason)),this.#a(a,n);break;case Nt.CANCEL_COMPLETE:e.success?a.cancelCall.resolve():a.cancelCall.reject(Zn(e.reason)),this.#a(a,n);break;case Nt.CANCEL:if(!s)break;let l=Zn(e.reason);Promise.try(s.onCancel||Uj,l).then(function(){o.postMessage({sourceName:r,targetName:i,stream:Nt.CANCEL_COMPLETE,streamId:n,success:!0})},function(c){o.postMessage({sourceName:r,targetName:i,stream:Nt.CANCEL_COMPLETE,streamId:n,reason:Zn(c)})}),s.sinkCapability.reject(l),s.isCancelled=!0,delete this.streamSinks[n];break;default:throw new Error("Unexpected stream case")}}async#a(e,n){await Promise.allSettled([e.startCall?.promise,e.pullCall?.promise,e.cancelCall?.promise]),delete this.streamControllers[n]}destroy(){this.#e?.abort(),this.#e=null}},gS=class{#e=!1;constructor({enableHWA:e=!1}){this.#e=e}create(e,n){if(e<=0||n<=0)throw new Error("Invalid canvas size");let r=this._createCanvas(e,n);return{canvas:r,context:r.getContext("2d",{willReadFrequently:!this.#e})}}reset(e,n,r){if(!e.canvas)throw new Error("Canvas is not specified");if(n<=0||r<=0)throw new Error("Invalid canvas size");e.canvas.width=n,e.canvas.height=r}destroy(e){if(!e.canvas)throw new Error("Canvas is not specified");e.canvas.width=0,e.canvas.height=0,e.canvas=null,e.context=null}_createCanvas(e,n){rt("Abstract method `_createCanvas` called.")}},mk=class extends gS{constructor({ownerDocument:e=globalThis.document,enableHWA:n=!1}){super({enableHWA:n}),this._document=e}_createCanvas(e,n){let r=this._document.createElement("canvas");return r.width=e,r.height=n,r}},vS=class{constructor({baseUrl:e=null,isCompressed:n=!0}){this.baseUrl=e,this.isCompressed=n}async fetch({name:e}){if(!this.baseUrl)throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.");if(!e)throw new Error("CMap name must be specified.");let n=this.baseUrl+e+(this.isCompressed?".bcmap":"");return this._fetch(n).then(r=>({cMapData:r,isCompressed:this.isCompressed})).catch(r=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${n}`)})}async _fetch(e){rt("Abstract method `_fetch` called.")}},bS=class extends vS{async _fetch(e){let n=await ip(e,this.isCompressed?"arraybuffer":"text");return n instanceof ArrayBuffer?new Uint8Array(n):np(n)}},yS=class{addFilter(e){return"none"}addHCMFilter(e,n){return"none"}addAlphaFilter(e){return"none"}addLuminosityFilter(e){return"none"}addHighlightHCMFilter(e,n,r,i,o){return"none"}destroy(e=!1){}},pk=class extends yS{#e;#t;#i;#n;#a;#r;#o=0;constructor({docId:e,ownerDocument:n=globalThis.document}){super(),this.#n=e,this.#a=n}get#s(){return this.#t||=new Map}get#c(){return this.#r||=new Map}get#l(){if(!this.#i){let e=this.#a.createElement("div"),{style:n}=e;n.visibility="hidden",n.contain="strict",n.width=n.height=0,n.position="absolute",n.top=n.left=0,n.zIndex=-1;let r=this.#a.createElementNS(wo,"svg");r.setAttribute("width",0),r.setAttribute("height",0),this.#i=this.#a.createElementNS(wo,"defs"),e.append(r),r.append(this.#i),this.#a.body.append(e)}return this.#i}#h(e){if(e.length===1){let l=e[0],c=new Array(256);for(let d=0;d<256;d++)c[d]=l[d]/255;let u=c.join(",");return[u,u,u]}let[n,r,i]=e,o=new Array(256),a=new Array(256),s=new Array(256);for(let l=0;l<256;l++)o[l]=n[l]/255,a[l]=r[l]/255,s[l]=i[l]/255;return[o.join(","),a.join(","),s.join(",")]}#d(e){if(this.#e===void 0){this.#e="";let n=this.#a.URL;n!==this.#a.baseURI&&(KS(n)?we('#createUrl: ignore "data:"-URL for performance reasons.'):this.#e=eU(n,""))}return`url(${this.#e}#${e})`}addFilter(e){if(!e)return"none";let n=this.#s.get(e);if(n)return n;let[r,i,o]=this.#h(e),a=e.length===1?r:`${r}${i}${o}`;if(n=this.#s.get(a),n)return this.#s.set(e,n),n;let s=`g_${this.#n}_transfer_map_${this.#o++}`,l=this.#d(s);this.#s.set(e,l),this.#s.set(a,l);let c=this.#m(s);return this.#p(r,i,o,c),l}addHCMFilter(e,n){let r=`${e}-${n}`,i="base",o=this.#c.get(i);if(o?.key===r||(o?(o.filter?.remove(),o.key=r,o.url="none",o.filter=null):(o={key:r,url:"none",filter:null},this.#c.set(i,o)),!e||!n))return o.url;let a=this.#y(e);e=oe.makeHexColor(...a);let s=this.#y(n);if(n=oe.makeHexColor(...s),this.#l.style.color="",e==="#000000"&&n==="#ffffff"||e===n)return o.url;let l=new Array(256);for(let f=0;f<=255;f++){let m=f/255;l[f]=m<=.03928?m/12.92:((m+.055)/1.055)**2.4}let c=l.join(","),u=`g_${this.#n}_hcm_filter`,d=o.filter=this.#m(u);this.#p(c,c,c,d),this.#g(d);let h=(f,m)=>{let p=a[f]/255,y=s[f]/255,g=new Array(m+1);for(let v=0;v<=m;v++)g[v]=p+v/m*(y-p);return g.join(",")};return this.#p(h(0,5),h(1,5),h(2,5),d),o.url=this.#d(u),o.url}addAlphaFilter(e){let n=this.#s.get(e);if(n)return n;let[r]=this.#h([e]),i=`alpha_${r}`;if(n=this.#s.get(i),n)return this.#s.set(e,n),n;let o=`g_${this.#n}_alpha_map_${this.#o++}`,a=this.#d(o);this.#s.set(e,a),this.#s.set(i,a);let s=this.#m(o);return this.#v(r,s),a}addLuminosityFilter(e){let n=this.#s.get(e||"luminosity");if(n)return n;let r,i;if(e?([r]=this.#h([e]),i=`luminosity_${r}`):i="luminosity",n=this.#s.get(i),n)return this.#s.set(e,n),n;let o=`g_${this.#n}_luminosity_map_${this.#o++}`,a=this.#d(o);this.#s.set(e,a),this.#s.set(i,a);let s=this.#m(o);return this.#f(s),e&&this.#v(r,s),a}addHighlightHCMFilter(e,n,r,i,o){let a=`${n}-${r}-${i}-${o}`,s=this.#c.get(e);if(s?.key===a||(s?(s.filter?.remove(),s.key=a,s.url="none",s.filter=null):(s={key:a,url:"none",filter:null},this.#c.set(e,s)),!n||!r))return s.url;let[l,c]=[n,r].map(this.#y.bind(this)),u=Math.round(.2126*l[0]+.7152*l[1]+.0722*l[2]),d=Math.round(.2126*c[0]+.7152*c[1]+.0722*c[2]),[h,f]=[i,o].map(this.#y.bind(this));d<u&&([u,d,h,f]=[d,u,f,h]),this.#l.style.color="";let m=(g,v,S)=>{let _=new Array(256),$=(d-u)/S,w=g/255,A=(v-g)/(255*S),k=0;for(let I=0;I<=S;I++){let D=Math.round(u+I*$),H=w+I*A;for(let ge=k;ge<=D;ge++)_[ge]=H;k=D+1}for(let I=k;I<256;I++)_[I]=_[k-1];return _.join(",")},p=`g_${this.#n}_hcm_${e}_filter`,y=s.filter=this.#m(p);return this.#g(y),this.#p(m(h[0],f[0],5),m(h[1],f[1],5),m(h[2],f[2],5),y),s.url=this.#d(p),s.url}destroy(e=!1){e&&this.#r?.size||(this.#i?.parentNode.parentNode.remove(),this.#i=null,this.#t?.clear(),this.#t=null,this.#r?.clear(),this.#r=null,this.#o=0)}#f(e){let n=this.#a.createElementNS(wo,"feColorMatrix");n.setAttribute("type","matrix"),n.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"),e.append(n)}#g(e){let n=this.#a.createElementNS(wo,"feColorMatrix");n.setAttribute("type","matrix"),n.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"),e.append(n)}#m(e){let n=this.#a.createElementNS(wo,"filter");return n.setAttribute("color-interpolation-filters","sRGB"),n.setAttribute("id",e),this.#l.append(n),n}#u(e,n,r){let i=this.#a.createElementNS(wo,n);i.setAttribute("type","discrete"),i.setAttribute("tableValues",r),e.append(i)}#p(e,n,r,i){let o=this.#a.createElementNS(wo,"feComponentTransfer");i.append(o),this.#u(o,"feFuncR",e),this.#u(o,"feFuncG",n),this.#u(o,"feFuncB",r)}#v(e,n){let r=this.#a.createElementNS(wo,"feComponentTransfer");n.append(r),this.#u(r,"feFuncA",e)}#y(e){return this.#l.style.color=e,rp(getComputedStyle(this.#l).getPropertyValue("color"))}},SS=class{constructor({baseUrl:e=null}){this.baseUrl=e}async fetch({filename:e}){if(!this.baseUrl)throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");if(!e)throw new Error("Font filename must be specified.");let n=`${this.baseUrl}${e}`;return this._fetch(n).catch(r=>{throw new Error(`Unable to load font data at: ${n}`)})}async _fetch(e){rt("Abstract method `_fetch` called.")}},_S=class extends SS{async _fetch(e){let n=await ip(e,"arraybuffer");return new Uint8Array(n)}},wS=class{constructor({baseUrl:e=null}){this.baseUrl=e}async fetch({filename:e}){if(!this.baseUrl)throw new Error("Ensure that the `wasmUrl` API parameter is provided.");if(!e)throw new Error("Wasm filename must be specified.");let n=`${this.baseUrl}${e}`;return this._fetch(n).catch(r=>{throw new Error(`Unable to load wasm data at: ${n}`)})}async _fetch(e){rt("Abstract method `_fetch` called.")}},xS=class extends wS{async _fetch(e){let n=await ip(e,"arraybuffer");return new Uint8Array(n)}};En&&we("Please use the `legacy` build in Node.js environments.");async function CR(t){let n=await process.getBuiltinModule("fs").promises.readFile(t);return new Uint8Array(n)}var gk=class extends yS{},vk=class extends gS{_createCanvas(e,n){return process.getBuiltinModule("module").createRequire(YG.url)("@napi-rs/canvas").createCanvas(e,n)}},bk=class extends vS{async _fetch(e){return CR(e)}},yk=class extends SS{async _fetch(e){return CR(e)}},Sk=class extends wS{async _fetch(e){return CR(e)}},lu="__forcedDependency",{floor:qj,ceil:Fj}=Math;function eS(t,e,n,r,i,o){t[e*4+0]=Math.min(t[e*4+0],n),t[e*4+1]=Math.min(t[e*4+1],r),t[e*4+2]=Math.max(t[e*4+2],i),t[e*4+3]=Math.max(t[e*4+3],o)}var _k=new Uint32Array(new Uint8Array([255,255,0,0]).buffer)[0],wk=class{#e;#t;constructor(e,n){this.#e=e,this.#t=n}get length(){return this.#e.length}isEmpty(e){return this.#e[e]===_k}minX(e){return this.#t[e*4+0]/256}minY(e){return this.#t[e*4+1]/256}maxX(e){return(this.#t[e*4+2]+1)/256}maxY(e){return(this.#t[e*4+3]+1)/256}},tS=(t,e)=>{if(!t)return;let n=t.get(e);return n||(n={dependencies:new Set,isRenderingOperation:!1},t.set(e,n)),n},xk=class{#e={__proto__:null};#t={__proto__:null,transform:[],moveText:[],sameLineText:[],[lu]:[]};#i=new Map;#n=[];#a=[];#r=[[1,0,0,1,0,0]];#o=[-1/0,-1/0,1/0,1/0];#s=new Float64Array([1/0,1/0,-1/0,-1/0]);#c=-1;#l=new Set;#h=new Map;#d=new Map;#f;#g;#m;#u;#p;constructor(e,n,r=!1){this.#f=e.width,this.#g=e.height,this.#v(n),r&&(this.#p=new Map)}growOperationsCount(e){e>=this.#u.length&&this.#v(e,this.#u)}#v(e,n){let r=new ArrayBuffer(e*4);this.#m=new Uint8ClampedArray(r),this.#u=new Uint32Array(r),n&&n.length>0?(this.#u.set(n),this.#u.fill(_k,n.length)):this.#u.fill(_k)}save(e){return this.#e={__proto__:this.#e},this.#t={__proto__:this.#t,transform:{__proto__:this.#t.transform},moveText:{__proto__:this.#t.moveText},sameLineText:{__proto__:this.#t.sameLineText},[lu]:{__proto__:this.#t[lu]}},this.#o={__proto__:this.#o},this.#n.push(e),this}restore(e){let n=Object.getPrototypeOf(this.#e);if(n===null)return this;this.#e=n,this.#t=Object.getPrototypeOf(this.#t),this.#o=Object.getPrototypeOf(this.#o);let r=this.#n.pop();return r!==void 0&&(tS(this.#p,e)?.dependencies.add(r),this.#u[e]=this.#u[r]),this}recordOpenMarker(e){return this.#n.push(e),this}getOpenMarker(){return this.#n.length===0?null:this.#n.at(-1)}recordCloseMarker(e){let n=this.#n.pop();return n!==void 0&&(tS(this.#p,e)?.dependencies.add(n),this.#u[e]=this.#u[n]),this}beginMarkedContent(e){return this.#a.push(e),this}endMarkedContent(e){let n=this.#a.pop();return n!==void 0&&(tS(this.#p,e)?.dependencies.add(n),this.#u[e]=this.#u[n]),this}pushBaseTransform(e){return this.#r.push(oe.multiplyByDOMMatrix(this.#r.at(-1),e.getTransform())),this}popBaseTransform(){return this.#r.length>1&&this.#r.pop(),this}recordSimpleData(e,n){return this.#e[e]=n,this}recordIncrementalData(e,n){return this.#t[e].push(n),this}resetIncrementalData(e,n){return this.#t[e].length=0,this}recordNamedData(e,n){return this.#i.set(e,n),this}recordSimpleDataFromNamed(e,n,r){this.#e[e]=this.#i.get(n)??r}recordFutureForcedDependency(e,n){return this.recordIncrementalData(lu,n),this}inheritSimpleDataAsFutureForcedDependencies(e){for(let n of e)n in this.#e&&this.recordFutureForcedDependency(n,this.#e[n]);return this}inheritPendingDependenciesAsFutureForcedDependencies(){for(let e of this.#l)this.recordFutureForcedDependency(lu,e);return this}resetBBox(e){return this.#c!==e&&(this.#c=e,this.#s[0]=1/0,this.#s[1]=1/0,this.#s[2]=-1/0,this.#s[3]=-1/0),this}recordClipBox(e,n,r,i,o,a){let s=oe.multiplyByDOMMatrix(this.#r.at(-1),n.getTransform()),l=[1/0,1/0,-1/0,-1/0];oe.axialAlignedBoundingBox([r,o,i,a],s,l);let c=oe.intersect(this.#o,l);return c?(this.#o[0]=c[0],this.#o[1]=c[1],this.#o[2]=c[2],this.#o[3]=c[3]):(this.#o[0]=this.#o[1]=1/0,this.#o[2]=this.#o[3]=-1/0),this}recordBBox(e,n,r,i,o,a){let s=this.#o;if(s[0]===1/0)return this;let l=oe.multiplyByDOMMatrix(this.#r.at(-1),n.getTransform());if(s[0]===-1/0)return oe.axialAlignedBoundingBox([r,o,i,a],l,this.#s),this;let c=[1/0,1/0,-1/0,-1/0];return oe.axialAlignedBoundingBox([r,o,i,a],l,c),this.#s[0]=Math.min(this.#s[0],Math.max(c[0],s[0])),this.#s[1]=Math.min(this.#s[1],Math.max(c[1],s[1])),this.#s[2]=Math.max(this.#s[2],Math.min(c[2],s[2])),this.#s[3]=Math.max(this.#s[3],Math.min(c[3],s[3])),this}recordCharacterBBox(e,n,r,i=1,o=0,a=0,s){let l=r.bbox,c,u;if(l&&(c=l[2]!==l[0]&&l[3]!==l[1]&&this.#d.get(r),c!==!1&&(u=[0,0,0,0],oe.axialAlignedBoundingBox(l,r.fontMatrix,u),(i!==1||o!==0||a!==0)&&oe.scaleMinMax([i,0,0,-i,o,a],u),c)))return this.recordBBox(e,n,u[0],u[2],u[1],u[3]);if(!s)return this.recordFullPageBBox(e);let d=s();return l&&u&&c===void 0&&(c=u[0]<=o-d.actualBoundingBoxLeft&&u[2]>=o+d.actualBoundingBoxRight&&u[1]<=a-d.actualBoundingBoxAscent&&u[3]>=a+d.actualBoundingBoxDescent,this.#d.set(r,c),c)?this.recordBBox(e,n,u[0],u[2],u[1],u[3]):this.recordBBox(e,n,o-d.actualBoundingBoxLeft,o+d.actualBoundingBoxRight,a-d.actualBoundingBoxAscent,a+d.actualBoundingBoxDescent)}recordFullPageBBox(e){return this.#s[0]=Math.max(0,this.#o[0]),this.#s[1]=Math.max(0,this.#o[1]),this.#s[2]=Math.min(this.#f,this.#o[2]),this.#s[3]=Math.min(this.#g,this.#o[3]),this}getSimpleIndex(e){return this.#e[e]}recordDependencies(e,n){let r=this.#l,i=this.#e,o=this.#t;for(let a of n)a in this.#e?r.add(i[a]):a in o&&o[a].forEach(r.add,r);return this}recordNamedDependency(e,n){return this.#i.has(n)&&this.#l.add(this.#i.get(n)),this}recordOperation(e,n=!1){if(this.recordDependencies(e,[lu]),this.#p){let r=tS(this.#p,e),{dependencies:i}=r;this.#l.forEach(i.add,i),this.#n.forEach(i.add,i),this.#a.forEach(i.add,i),i.delete(e),r.isRenderingOperation=!0}if(this.#c===e){let r=qj(this.#s[0]*256/this.#f),i=qj(this.#s[1]*256/this.#g),o=Fj(this.#s[2]*256/this.#f),a=Fj(this.#s[3]*256/this.#g);eS(this.#m,e,r,i,o,a);for(let s of this.#l)s!==e&&eS(this.#m,s,r,i,o,a);for(let s of this.#n)s!==e&&eS(this.#m,s,r,i,o,a);for(let s of this.#a)s!==e&&eS(this.#m,s,r,i,o,a);n||(this.#l.clear(),this.#c=-1)}return this}recordShowTextOperation(e,n=!1){let r=Array.from(this.#l);this.recordOperation(e,n),this.recordIncrementalData("sameLineText",e);for(let i of r)this.recordIncrementalData("sameLineText",i);return this}bboxToClipBoxDropOperation(e,n=!1){return this.#c===e&&(this.#c=-1,this.#o[0]=Math.max(this.#o[0],this.#s[0]),this.#o[1]=Math.max(this.#o[1],this.#s[1]),this.#o[2]=Math.min(this.#o[2],this.#s[2]),this.#o[3]=Math.min(this.#o[3],this.#s[3]),n||this.#l.clear()),this}_takePendingDependencies(){let e=this.#l;return this.#l=new Set,e}_extractOperation(e){let n=this.#h.get(e);return this.#h.delete(e),n}_pushPendingDependencies(e){for(let n of e)this.#l.add(n)}take(){return this.#d.clear(),new wk(this.#u,this.#m)}takeDebugMetadata(){return this.#p}},$S=class t{#e;#t;#i;#n=0;#a=0;constructor(e,n,r){if(e instanceof t&&e.#i===!!r)return e;this.#e=e,this.#t=n,this.#i=!!r}growOperationsCount(){throw new Error("Unreachable")}save(e){return this.#a++,this.#e.save(this.#t),this}restore(e){return this.#a>0&&(this.#e.restore(this.#t),this.#a--),this}recordOpenMarker(e){return this.#n++,this}getOpenMarker(){return this.#n>0?this.#t:this.#e.getOpenMarker()}recordCloseMarker(e){return this.#n--,this}beginMarkedContent(e){return this}endMarkedContent(e){return this}pushBaseTransform(e){return this.#e.pushBaseTransform(e),this}popBaseTransform(){return this.#e.popBaseTransform(),this}recordSimpleData(e,n){return this.#e.recordSimpleData(e,this.#t),this}recordIncrementalData(e,n){return this.#e.recordIncrementalData(e,this.#t),this}resetIncrementalData(e,n){return this.#e.resetIncrementalData(e,this.#t),this}recordNamedData(e,n){return this}recordSimpleDataFromNamed(e,n,r){return this.#e.recordSimpleDataFromNamed(e,n,this.#t),this}recordFutureForcedDependency(e,n){return this.#e.recordFutureForcedDependency(e,this.#t),this}inheritSimpleDataAsFutureForcedDependencies(e){return this.#e.inheritSimpleDataAsFutureForcedDependencies(e),this}inheritPendingDependenciesAsFutureForcedDependencies(){return this.#e.inheritPendingDependenciesAsFutureForcedDependencies(),this}resetBBox(e){return this.#i||this.#e.resetBBox(this.#t),this}recordClipBox(e,n,r,i,o,a){return this.#i||this.#e.recordClipBox(this.#t,n,r,i,o,a),this}recordBBox(e,n,r,i,o,a){return this.#i||this.#e.recordBBox(this.#t,n,r,i,o,a),this}recordCharacterBBox(e,n,r,i,o,a,s){return this.#i||this.#e.recordCharacterBBox(this.#t,n,r,i,o,a,s),this}recordFullPageBBox(e){return this.#i||this.#e.recordFullPageBBox(this.#t),this}getSimpleIndex(e){return this.#e.getSimpleIndex(e)}recordDependencies(e,n){return this.#e.recordDependencies(this.#t,n),this}recordNamedDependency(e,n){return this.#e.recordNamedDependency(this.#t,n),this}recordOperation(e){return this.#e.recordOperation(this.#t,!0),this}recordShowTextOperation(e){return this.#e.recordShowTextOperation(this.#t,!0),this}bboxToClipBoxDropOperation(e){return this.#i||this.#e.bboxToClipBoxDropOperation(this.#t,!0),this}take(){throw new Error("Unreachable")}takeDebugMetadata(){throw new Error("Unreachable")}},Pi={stroke:["path","transform","filter","strokeColor","strokeAlpha","lineWidth","lineCap","lineJoin","miterLimit","dash"],fill:["path","transform","filter","fillColor","fillAlpha","globalCompositeOperation","SMask"],imageXObject:["transform","SMask","filter","fillAlpha","strokeAlpha","globalCompositeOperation"],rawFillPath:["filter","fillColor","fillAlpha"],showText:["transform","leading","charSpacing","wordSpacing","hScale","textRise","moveText","textMatrix","font","fontObj","filter","fillColor","textRenderingMode","SMask","fillAlpha","strokeAlpha","globalCompositeOperation","sameLineText"],transform:["transform"],transformAndFill:["transform","fillColor"]},cn={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};function $k(t,e){if(!e)return;let n=e[2]-e[0],r=e[3]-e[1],i=new Path2D;i.rect(e[0],e[1],n,r),t.clip(i)}var Ym=class{isModifyingCurrentTransform(){return!1}getPattern(){rt("Abstract method `getPattern` called.")}},Ak=class extends Ym{constructor(e){super(),this._type=e[1],this._bbox=e[2],this._colorStops=e[3],this._p0=e[4],this._p1=e[5],this._r0=e[6],this._r1=e[7],this.matrix=null}_createGradient(e){let n;this._type==="axial"?n=e.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):this._type==="radial"&&(n=e.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(let r of this._colorStops)n.addColorStop(r[0],r[1]);return n}getPattern(e,n,r,i){let o;if(i===cn.STROKE||i===cn.FILL){let a=n.current.getClippedPathBoundingBox(i,St(e))||[0,0,0,0],s=Math.ceil(a[2]-a[0])||1,l=Math.ceil(a[3]-a[1])||1,c=n.cachedCanvases.getCanvas("pattern",s,l),u=c.context;u.clearRect(0,0,u.canvas.width,u.canvas.height),u.beginPath(),u.rect(0,0,u.canvas.width,u.canvas.height),u.translate(-a[0],-a[1]),r=oe.transform(r,[1,0,0,1,a[0],a[1]]),u.transform(...n.baseTransform),this.matrix&&u.transform(...this.matrix),$k(u,this._bbox),u.fillStyle=this._createGradient(u),u.fill(),o=e.createPattern(c.canvas,"no-repeat");let d=new DOMMatrix(r);o.setTransform(d)}else $k(e,this._bbox),o=this._createGradient(e);return o}};function Zz(t,e,n,r,i,o,a,s){let l=e.coords,c=e.colors,u=t.data,d=t.width*4,h;l[n+1]>l[r+1]&&(h=n,n=r,r=h,h=o,o=a,a=h),l[r+1]>l[i+1]&&(h=r,r=i,i=h,h=a,a=s,s=h),l[n+1]>l[r+1]&&(h=n,n=r,r=h,h=o,o=a,a=h);let f=(l[n]+e.offsetX)*e.scaleX,m=(l[n+1]+e.offsetY)*e.scaleY,p=(l[r]+e.offsetX)*e.scaleX,y=(l[r+1]+e.offsetY)*e.scaleY,g=(l[i]+e.offsetX)*e.scaleX,v=(l[i+1]+e.offsetY)*e.scaleY;if(m>=v)return;let S=c[o],_=c[o+1],$=c[o+2],w=c[a],A=c[a+1],k=c[a+2],I=c[s],D=c[s+1],H=c[s+2],ge=Math.round(m),ce=Math.round(v),me,Te,ie,ne,Se,nt,j,N;for(let V=ge;V<=ce;V++){if(V<y){let K=V<m?0:(m-V)/(m-y);me=f-(f-p)*K,Te=S-(S-w)*K,ie=_-(_-A)*K,ne=$-($-k)*K}else{let K;V>v?K=1:y===v?K=0:K=(y-V)/(y-v),me=p-(p-g)*K,Te=w-(w-I)*K,ie=A-(A-D)*K,ne=k-(k-H)*K}let q;V<m?q=0:V>v?q=1:q=(m-V)/(m-v),Se=f-(f-g)*q,nt=S-(S-I)*q,j=_-(_-D)*q,N=$-($-H)*q;let G=Math.round(Math.min(me,Se)),Z=Math.round(Math.max(me,Se)),W=d*V+G*4;for(let K=G;K<=Z;K++)q=(me-K)/(me-Se),q<0?q=0:q>1&&(q=1),u[W++]=Te-(Te-nt)*q|0,u[W++]=ie-(ie-j)*q|0,u[W++]=ne-(ne-N)*q|0,u[W++]=255}}function RG(t,e,n){let r=e.coords,i=e.colors,o,a;switch(e.type){case"lattice":let s=e.verticesPerRow,l=Math.floor(r.length/s)-1,c=s-1;for(o=0;o<l;o++){let u=o*s;for(let d=0;d<c;d++,u++)Zz(t,n,r[u],r[u+1],r[u+s],i[u],i[u+1],i[u+s]),Zz(t,n,r[u+s+1],r[u+1],r[u+s],i[u+s+1],i[u+1],i[u+s])}break;case"triangles":for(o=0,a=r.length;o<a;o+=3)Zz(t,n,r[o],r[o+1],r[o+2],i[o],i[o+1],i[o+2]);break;default:throw new Error("illegal figure")}}var Ek=class extends Ym{constructor(e){super(),this._coords=e[2],this._colors=e[3],this._figures=e[4],this._bounds=e[5],this._bbox=e[6],this._background=e[7],this.matrix=null}_createMeshCanvas(e,n,r){let s=Math.floor(this._bounds[0]),l=Math.floor(this._bounds[1]),c=Math.ceil(this._bounds[2])-s,u=Math.ceil(this._bounds[3])-l,d=Math.min(Math.ceil(Math.abs(c*e[0]*1.1)),3e3),h=Math.min(Math.ceil(Math.abs(u*e[1]*1.1)),3e3),f=c/d,m=u/h,p={coords:this._coords,colors:this._colors,offsetX:-s,offsetY:-l,scaleX:1/f,scaleY:1/m},y=d+4,g=h+4,v=r.getCanvas("mesh",y,g),S=v.context,_=S.createImageData(d,h);if(n){let w=_.data;for(let A=0,k=w.length;A<k;A+=4)w[A]=n[0],w[A+1]=n[1],w[A+2]=n[2],w[A+3]=255}for(let w of this._figures)RG(_,w,p);return S.putImageData(_,2,2),{canvas:v.canvas,offsetX:s-2*f,offsetY:l-2*m,scaleX:f,scaleY:m}}isModifyingCurrentTransform(){return!0}getPattern(e,n,r,i){$k(e,this._bbox);let o=new Float32Array(2);if(i===cn.SHADING)oe.singularValueDecompose2dScale(St(e),o);else if(this.matrix){oe.singularValueDecompose2dScale(this.matrix,o);let[s,l]=o;oe.singularValueDecompose2dScale(n.baseTransform,o),o[0]*=s,o[1]*=l}else oe.singularValueDecompose2dScale(n.baseTransform,o);let a=this._createMeshCanvas(o,i===cn.SHADING?null:this._background,n.cachedCanvases);return i!==cn.SHADING&&(e.setTransform(...n.baseTransform),this.matrix&&e.transform(...this.matrix)),e.translate(a.offsetX,a.offsetY),e.scale(a.scaleX,a.scaleY),e.createPattern(a.canvas,"no-repeat")}},Tk=class extends Ym{getPattern(){return"hotpink"}};function CG(t){switch(t[0]){case"RadialAxial":return new Ak(t);case"Mesh":return new Ek(t);case"Dummy":return new Tk}throw new Error(`Unknown IR type: ${t[0]}`)}var Bj={COLORED:1,UNCOLORED:2},zk=class t{static MAX_PATTERN_SIZE=3e3;constructor(e,n,r,i){this.color=e[1],this.operatorList=e[2],this.matrix=e[3],this.bbox=e[4],this.xstep=e[5],this.ystep=e[6],this.paintType=e[7],this.tilingType=e[8],this.ctx=n,this.canvasGraphicsFactory=r,this.baseTransform=i}createPatternCanvas(e,n){let{bbox:r,operatorList:i,paintType:o,tilingType:a,color:s,canvasGraphicsFactory:l}=this,{xstep:c,ystep:u}=this;c=Math.abs(c),u=Math.abs(u),GS("TilingType: "+a);let d=r[0],h=r[1],f=r[2],m=r[3],p=f-d,y=m-h,g=new Float32Array(2);oe.singularValueDecompose2dScale(this.matrix,g);let[v,S]=g;oe.singularValueDecompose2dScale(this.baseTransform,g);let _=v*g[0],$=S*g[1],w=p,A=y,k=!1,I=!1,D=Math.ceil(c*_),H=Math.ceil(u*$),ge=Math.ceil(p*_),ce=Math.ceil(y*$);D>=ge?w=c:k=!0,H>=ce?A=u:I=!0;let me=this.getSizeAndScale(w,this.ctx.canvas.width,_),Te=this.getSizeAndScale(A,this.ctx.canvas.height,$),ie=e.cachedCanvases.getCanvas("pattern",me.size,Te.size),ne=ie.context,Se=l.createCanvasGraphics(ne,n);if(Se.groupLevel=e.groupLevel,this.setFillAndStrokeStyleToContext(Se,o,s),ne.translate(-me.scale*d,-Te.scale*h),Se.transform(0,me.scale,0,0,Te.scale,0,0),ne.save(),Se.dependencyTracker?.save(),this.clipBbox(Se,d,h,f,m),Se.baseTransform=St(Se.ctx),Se.executeOperatorList(i),Se.endDrawing(),Se.dependencyTracker?.restore(),ne.restore(),k||I){let nt=ie.canvas;k&&(w=c),I&&(A=u);let j=this.getSizeAndScale(w,this.ctx.canvas.width,_),N=this.getSizeAndScale(A,this.ctx.canvas.height,$),V=j.size,q=N.size,G=e.cachedCanvases.getCanvas("pattern-workaround",V,q),Z=G.context,W=k?Math.floor(p/c):0,K=I?Math.floor(y/u):0;for(let he=0;he<=W;he++)for(let ze=0;ze<=K;ze++)Z.drawImage(nt,V*he,q*ze,V,q,0,0,V,q);return{canvas:G.canvas,scaleX:j.scale,scaleY:N.scale,offsetX:d,offsetY:h}}return{canvas:ie.canvas,scaleX:me.scale,scaleY:Te.scale,offsetX:d,offsetY:h}}getSizeAndScale(e,n,r){let i=Math.max(t.MAX_PATTERN_SIZE,n),o=Math.ceil(e*r);return o>=i?o=i:r=o/e,{scale:r,size:o}}clipBbox(e,n,r,i,o){let a=i-n,s=o-r;e.ctx.rect(n,r,a,s),oe.axialAlignedBoundingBox([n,r,i,o],St(e.ctx),e.current.minMax),e.clip(),e.endPath()}setFillAndStrokeStyleToContext(e,n,r){let i=e.ctx,o=e.current;switch(n){case Bj.COLORED:let{fillStyle:a,strokeStyle:s}=this.ctx;i.fillStyle=o.fillColor=a,i.strokeStyle=o.strokeColor=s;break;case Bj.UNCOLORED:i.fillStyle=i.strokeStyle=r,o.fillColor=o.strokeColor=r;break;default:throw new Jz(`Unsupported paint type: ${n}`)}}isModifyingCurrentTransform(){return!1}getPattern(e,n,r,i,o){let a=r;i!==cn.SHADING&&(a=oe.transform(a,n.baseTransform),this.matrix&&(a=oe.transform(a,this.matrix)));let s=this.createPatternCanvas(n,o),l=new DOMMatrix(a);l=l.translate(s.offsetX,s.offsetY),l=l.scale(1/s.scaleX,1/s.scaleY);let c=e.createPattern(s.canvas,"repeat");return c.setTransform(l),c}};function IG({src:t,srcPos:e=0,dest:n,width:r,height:i,nonBlackColor:o=4294967295,inverseDecode:a=!1}){let s=Ft.isLittleEndian?4278190080:255,[l,c]=a?[o,s]:[s,o],u=r>>3,d=r&7,h=t.length;n=new Uint32Array(n.buffer);let f=0;for(let m=0;m<i;m++){for(let y=e+u;e<y;e++){let g=e<h?t[e]:255;n[f++]=g&128?c:l,n[f++]=g&64?c:l,n[f++]=g&32?c:l,n[f++]=g&16?c:l,n[f++]=g&8?c:l,n[f++]=g&4?c:l,n[f++]=g&2?c:l,n[f++]=g&1?c:l}if(d===0)continue;let p=e<h?t[e++]:255;for(let y=0;y<d;y++)n[f++]=p&1<<7-y?c:l}return{srcPos:e,destPos:f}}var Hj=16,Vj=100,OG=15,Zj=10,Gn=16,Gz=new DOMMatrix,hi=new Float32Array(2),hu=new Float32Array([1/0,1/0,-1/0,-1/0]);function PG(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(){e.save(),this.__originalSave()},t.restore=function(){e.restore(),this.__originalRestore()},t.translate=function(n,r){e.translate(n,r),this.__originalTranslate(n,r)},t.scale=function(n,r){e.scale(n,r),this.__originalScale(n,r)},t.transform=function(n,r,i,o,a,s){e.transform(n,r,i,o,a,s),this.__originalTransform(n,r,i,o,a,s)},t.setTransform=function(n,r,i,o,a,s){e.setTransform(n,r,i,o,a,s),this.__originalSetTransform(n,r,i,o,a,s)},t.resetTransform=function(){e.resetTransform(),this.__originalResetTransform()},t.rotate=function(n){e.rotate(n),this.__originalRotate(n)},t.clip=function(n){e.clip(n),this.__originalClip(n)},t.moveTo=function(n,r){e.moveTo(n,r),this.__originalMoveTo(n,r)},t.lineTo=function(n,r){e.lineTo(n,r),this.__originalLineTo(n,r)},t.bezierCurveTo=function(n,r,i,o,a,s){e.bezierCurveTo(n,r,i,o,a,s),this.__originalBezierCurveTo(n,r,i,o,a,s)},t.rect=function(n,r,i,o){e.rect(n,r,i,o),this.__originalRect(n,r,i,o)},t.closePath=function(){e.closePath(),this.__originalClosePath()},t.beginPath=function(){e.beginPath(),this.__originalBeginPath()}}var kk=class{constructor(e){this.canvasFactory=e,this.cache=Object.create(null)}getCanvas(e,n,r){let i;return this.cache[e]!==void 0?(i=this.cache[e],this.canvasFactory.reset(i,n,r)):(i=this.canvasFactory.create(n,r),this.cache[e]=i),i}delete(e){delete this.cache[e]}clear(){for(let e in this.cache){let n=this.cache[e];this.canvasFactory.destroy(n),delete this.cache[e]}}};function nS(t,e,n,r,i,o,a,s,l,c){let[u,d,h,f,m,p]=St(t);if(d===0&&h===0){let v=a*u+m,S=Math.round(v),_=s*f+p,$=Math.round(_),w=(a+l)*u+m,A=Math.abs(Math.round(w)-S)||1,k=(s+c)*f+p,I=Math.abs(Math.round(k)-$)||1;return t.setTransform(Math.sign(u),0,0,Math.sign(f),S,$),t.drawImage(e,n,r,i,o,0,0,A,I),t.setTransform(u,d,h,f,m,p),[A,I]}if(u===0&&f===0){let v=s*h+m,S=Math.round(v),_=a*d+p,$=Math.round(_),w=(s+c)*h+m,A=Math.abs(Math.round(w)-S)||1,k=(a+l)*d+p,I=Math.abs(Math.round(k)-$)||1;return t.setTransform(0,Math.sign(d),Math.sign(h),0,S,$),t.drawImage(e,n,r,i,o,0,0,I,A),t.setTransform(u,d,h,f,m,p),[I,A]}t.drawImage(e,n,r,i,o,a,s,l,c);let y=Math.hypot(u,d),g=Math.hypot(h,f);return[y*l,g*c]}var AS=class{alphaIsShape=!1;fontSize=0;fontSizeScale=1;textMatrix=null;textMatrixScale=1;fontMatrix=Xz;leading=0;x=0;y=0;lineX=0;lineY=0;charSpacing=0;wordSpacing=0;textHScale=1;textRenderingMode=ln.FILL;textRise=0;fillColor="#000000";strokeColor="#000000";patternFill=!1;patternStroke=!1;fillAlpha=1;strokeAlpha=1;lineWidth=1;activeSMask=null;transferMaps="none";constructor(e,n,r){r?.(this),this.clipBox=new Float32Array([0,0,e,n]),this.minMax=hu.slice()}clone(){let e=Object.create(this);return e.clipBox=this.clipBox.slice(),e.minMax=this.minMax.slice(),e}getPathBoundingBox(e=cn.FILL,n=null){let r=this.minMax.slice();if(e===cn.STROKE){n||rt("Stroke bounding box must include transform."),oe.singularValueDecompose2dScale(n,hi);let i=hi[0]*this.lineWidth/2,o=hi[1]*this.lineWidth/2;r[0]-=i,r[1]-=o,r[2]+=i,r[3]+=o}return r}updateClipFromPath(){let e=oe.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(e||[0,0,0,0])}isEmptyClip(){return this.minMax[0]===1/0}startNewPathAndClipBox(e){this.clipBox.set(e,0),this.minMax.set(hu,0)}getClippedPathBoundingBox(e=cn.FILL,n=null){return oe.intersect(this.clipBox,this.getPathBoundingBox(e,n))}};function Gj(t,e){if(e instanceof ImageData){t.putImageData(e,0,0);return}let n=e.height,r=e.width,i=n%Gn,o=(n-i)/Gn,a=i===0?o:o+1,s=t.createImageData(r,Gn),l=0,c,u=e.data,d=s.data,h,f,m,p;if(e.kind===lS.GRAYSCALE_1BPP){let y=u.byteLength,g=new Uint32Array(d.buffer,0,d.byteLength>>2),v=g.length,S=r+7>>3,_=4294967295,$=Ft.isLittleEndian?4278190080:255;for(h=0;h<a;h++){for(m=h<o?Gn:i,c=0,f=0;f<m;f++){let w=y-l,A=0,k=w>S?r:w*8-7,I=k&-8,D=0,H=0;for(;A<I;A+=8)H=u[l++],g[c++]=H&128?_:$,g[c++]=H&64?_:$,g[c++]=H&32?_:$,g[c++]=H&16?_:$,g[c++]=H&8?_:$,g[c++]=H&4?_:$,g[c++]=H&2?_:$,g[c++]=H&1?_:$;for(;A<k;A++)D===0&&(H=u[l++],D=128),g[c++]=H&D?_:$,D>>=1}for(;c<v;)g[c++]=0;t.putImageData(s,0,h*Gn)}}else if(e.kind===lS.RGBA_32BPP){for(f=0,p=r*Gn*4,h=0;h<o;h++)d.set(u.subarray(l,l+p)),l+=p,t.putImageData(s,0,f),f+=Gn;h<a&&(p=r*i*4,d.set(u.subarray(l,l+p)),t.putImageData(s,0,f))}else if(e.kind===lS.RGB_24BPP)for(m=Gn,p=r*m,h=0;h<a;h++){for(h>=o&&(m=i,p=r*m),c=0,f=p;f--;)d[c++]=u[l++],d[c++]=u[l++],d[c++]=u[l++],d[c++]=255;t.putImageData(s,0,h*Gn)}else throw new Error(`bad image kind: ${e.kind}`)}function Kj(t,e){if(e.bitmap){t.drawImage(e.bitmap,0,0);return}let n=e.height,r=e.width,i=n%Gn,o=(n-i)/Gn,a=i===0?o:o+1,s=t.createImageData(r,Gn),l=0,c=e.data,u=s.data;for(let d=0;d<a;d++){let h=d<o?Gn:i;({srcPos:l}=IG({src:c,srcPos:l,dest:u,width:r,height:h,nonBlackColor:0})),t.putImageData(s,0,d*Gn)}}function Nm(t,e){let n=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font","filter"];for(let r of n)t[r]!==void 0&&(e[r]=t[r]);t.setLineDash!==void 0&&(e.setLineDash(t.getLineDash()),e.lineDashOffset=t.lineDashOffset)}function iS(t){t.strokeStyle=t.fillStyle="#000000",t.fillRule="nonzero",t.globalAlpha=1,t.lineWidth=1,t.lineCap="butt",t.lineJoin="miter",t.miterLimit=10,t.globalCompositeOperation="source-over",t.font="10px sans-serif",t.setLineDash!==void 0&&(t.setLineDash([]),t.lineDashOffset=0);let{filter:e}=t;e!=="none"&&e!==""&&(t.filter="none")}function Yj(t,e){if(e)return!0;oe.singularValueDecompose2dScale(t,hi);let n=Math.fround(xo.pixelRatio*Ta.PDF_TO_CSS_UNITS);return hi[0]<=n&&hi[1]<=n}var NG=["butt","round","square"],MG=["miter","round","bevel"],DG={},Xj={},fu=class t{constructor(e,n,r,i,o,{optionalContentConfig:a,markedContentStack:s=null},l,c,u){this.ctx=e,this.current=new AS(this.ctx.canvas.width,this.ctx.canvas.height),this.stateStack=[],this.pendingClip=null,this.pendingEOFill=!1,this.res=null,this.xobjs=null,this.commonObjs=n,this.objs=r,this.canvasFactory=i,this.filterFactory=o,this.groupStack=[],this.baseTransform=null,this.baseTransformStack=[],this.groupLevel=0,this.smaskStack=[],this.smaskCounter=0,this.tempSMask=null,this.suspendedCtx=null,this.contentVisible=!0,this.markedContentStack=s||[],this.optionalContentConfig=a,this.cachedCanvases=new kk(this.canvasFactory),this.cachedPatterns=new Map,this.annotationCanvasMap=l,this.viewportScale=1,this.outputScaleX=1,this.outputScaleY=1,this.pageColors=c,this._cachedScaleForStroking=[-1,0],this._cachedGetSinglePixelWidth=null,this._cachedBitmapsMap=new Map,this.dependencyTracker=u??null}getObject(e,n,r=null){return typeof n=="string"?(this.dependencyTracker?.recordNamedDependency(e,n),n.startsWith("g_")?this.commonObjs.get(n):this.objs.get(n)):r}beginDrawing({transform:e,viewport:n,transparency:r=!1,background:i=null}){let o=this.ctx.canvas.width,a=this.ctx.canvas.height,s=this.ctx.fillStyle;if(this.ctx.fillStyle=i||"#ffffff",this.ctx.fillRect(0,0,o,a),this.ctx.fillStyle=s,r){let l=this.cachedCanvases.getCanvas("transparent",o,a);this.compositeCtx=this.ctx,this.transparentCanvas=l.canvas,this.ctx=l.context,this.ctx.save(),this.ctx.transform(...St(this.compositeCtx))}this.ctx.save(),iS(this.ctx),e&&(this.ctx.transform(...e),this.outputScaleX=e[0],this.outputScaleY=e[0]),this.ctx.transform(...n.transform),this.viewportScale=n.scale,this.baseTransform=St(this.ctx)}executeOperatorList(e,n,r,i,o){let a=e.argsArray,s=e.fnArray,l=n||0,c=a.length;if(c===l)return l;let u=c-l>Zj&&typeof r=="function",d=u?Date.now()+OG:0,h=0,f=this.commonObjs,m=this.objs,p,y;for(;;){if(i!==void 0&&l===i.nextBreakPoint)return i.breakIt(l,r),l;if(!o||o(l))if(p=s[l],y=a[l]??null,p!==Fm.dependency)y===null?this[p](l):this[p](l,...y);else for(let g of y){this.dependencyTracker?.recordNamedData(g,l);let v=g.startsWith("g_")?f:m;if(!v.has(g))return v.get(g,r),l}if(l++,l===c)return l;if(u&&++h>Zj){if(Date.now()>d)return r(),l;h=0}}}#e(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null,this.ctx.restore(),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.#e(),this.cachedCanvases.clear(),this.cachedPatterns.clear();for(let e of this._cachedBitmapsMap.values()){for(let n of e.values())typeof HTMLCanvasElement<"u"&&n instanceof HTMLCanvasElement&&(n.width=n.height=0);e.clear()}this._cachedBitmapsMap.clear(),this.#t()}#t(){if(this.pageColors){let e=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if(e!=="none"){let n=this.ctx.filter;this.ctx.filter=e,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=n}}}_scaleImage(e,n){let r=e.width??e.displayWidth,i=e.height??e.displayHeight,o=Math.max(Math.hypot(n[0],n[1]),1),a=Math.max(Math.hypot(n[2],n[3]),1),s=r,l=i,c="prescale1",u,d;for(;o>2&&s>1||a>2&&l>1;){let h=s,f=l;o>2&&s>1&&(h=s>=16384?Math.floor(s/2)-1||1:Math.ceil(s/2),o/=s/h),a>2&&l>1&&(f=l>=16384?Math.floor(l/2)-1||1:Math.ceil(l)/2,a/=l/f),u=this.cachedCanvases.getCanvas(c,h,f),d=u.context,d.clearRect(0,0,h,f),d.drawImage(e,0,0,s,l,0,0,h,f),e=u.canvas,s=h,l=f,c=c==="prescale1"?"prescale2":"prescale1"}return{img:e,paintWidth:s,paintHeight:l}}_createMaskCanvas(e,n){let r=this.ctx,{width:i,height:o}=n,a=this.current.fillColor,s=this.current.patternFill,l=St(r),c,u,d,h;if((n.bitmap||n.data)&&n.count>1){let D=n.bitmap||n.data.buffer;u=JSON.stringify(s?l:[l.slice(0,4),a]),c=this._cachedBitmapsMap.get(D),c||(c=new Map,this._cachedBitmapsMap.set(D,c));let H=c.get(u);if(H&&!s){let ge=Math.round(Math.min(l[0],l[2])+l[4]),ce=Math.round(Math.min(l[1],l[3])+l[5]);return this.dependencyTracker?.recordDependencies(e,Pi.transformAndFill),{canvas:H,offsetX:ge,offsetY:ce}}d=H}d||(h=this.cachedCanvases.getCanvas("maskCanvas",i,o),Kj(h.context,n));let f=oe.transform(l,[1/i,0,0,-1/o,0,0]);f=oe.transform(f,[1,0,0,1,0,-o]);let m=hu.slice();oe.axialAlignedBoundingBox([0,0,i,o],f,m);let[p,y,g,v]=m,S=Math.round(g-p)||1,_=Math.round(v-y)||1,$=this.cachedCanvases.getCanvas("fillCanvas",S,_),w=$.context,A=p,k=y;w.translate(-A,-k),w.transform(...f),d||(d=this._scaleImage(h.canvas,Cr(w)),d=d.img,c&&s&&c.set(u,d)),w.imageSmoothingEnabled=Yj(St(w),n.interpolate),nS(w,d,0,0,d.width,d.height,0,0,i,o),w.globalCompositeOperation="source-in";let I=oe.transform(Cr(w),[1,0,0,1,-A,-k]);return w.fillStyle=s?a.getPattern(r,this,I,cn.FILL,e):a,w.fillRect(0,0,i,o),c&&!s&&(this.cachedCanvases.delete("fillCanvas"),c.set(u,$.canvas)),this.dependencyTracker?.recordDependencies(e,Pi.transformAndFill),{canvas:$.canvas,offsetX:Math.round(A),offsetY:Math.round(k)}}setLineWidth(e,n){this.dependencyTracker?.recordSimpleData("lineWidth",e),n!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=n,this.ctx.lineWidth=n}setLineCap(e,n){this.dependencyTracker?.recordSimpleData("lineCap",e),this.ctx.lineCap=NG[n]}setLineJoin(e,n){this.dependencyTracker?.recordSimpleData("lineJoin",e),this.ctx.lineJoin=MG[n]}setMiterLimit(e,n){this.dependencyTracker?.recordSimpleData("miterLimit",e),this.ctx.miterLimit=n}setDash(e,n,r){this.dependencyTracker?.recordSimpleData("dash",e);let i=this.ctx;i.setLineDash!==void 0&&(i.setLineDash(n),i.lineDashOffset=r)}setRenderingIntent(e,n){}setFlatness(e,n){}setGState(e,n){for(let[r,i]of n)switch(r){case"LW":this.setLineWidth(e,i);break;case"LC":this.setLineCap(e,i);break;case"LJ":this.setLineJoin(e,i);break;case"ML":this.setMiterLimit(e,i);break;case"D":this.setDash(e,i[0],i[1]);break;case"RI":this.setRenderingIntent(e,i);break;case"FL":this.setFlatness(e,i);break;case"Font":this.setFont(e,i[0],i[1]);break;case"CA":this.dependencyTracker?.recordSimpleData("strokeAlpha",e),this.current.strokeAlpha=i;break;case"ca":this.dependencyTracker?.recordSimpleData("fillAlpha",e),this.ctx.globalAlpha=this.current.fillAlpha=i;break;case"BM":this.dependencyTracker?.recordSimpleData("globalCompositeOperation",e),this.ctx.globalCompositeOperation=i;break;case"SMask":this.dependencyTracker?.recordSimpleData("SMask",e),this.current.activeSMask=i?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case"TR":this.dependencyTracker?.recordSimpleData("filter",e),this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(i);break}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){let e=this.inSMaskMode;this.current.activeSMask&&!e?this.beginSMaskMode():!this.current.activeSMask&&e&&this.endSMaskMode()}beginSMaskMode(e){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");let n=this.ctx.canvas.width,r=this.ctx.canvas.height,i="smaskGroupAt"+this.groupLevel,o=this.cachedCanvases.getCanvas(i,n,r);this.suspendedCtx=this.ctx;let a=this.ctx=o.context;a.setTransform(this.suspendedCtx.getTransform()),Nm(this.suspendedCtx,a),PG(a,this.suspendedCtx),this.setGState(e,[["BM","source-over"]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),Nm(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null}compose(e){if(!this.current.activeSMask)return;e?(e[0]=Math.floor(e[0]),e[1]=Math.floor(e[1]),e[2]=Math.ceil(e[2]),e[3]=Math.ceil(e[3])):e=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];let n=this.current.activeSMask,r=this.suspendedCtx;this.composeSMask(r,n,this.ctx,e),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(e,n,r,i){let o=i[0],a=i[1],s=i[2]-o,l=i[3]-a;s===0||l===0||(this.genericComposeSMask(n.context,r,s,l,n.subtype,n.backdrop,n.transferMap,o,a,n.offsetX,n.offsetY),e.save(),e.globalAlpha=1,e.globalCompositeOperation="source-over",e.setTransform(1,0,0,1,0,0),e.drawImage(r.canvas,0,0),e.restore())}genericComposeSMask(e,n,r,i,o,a,s,l,c,u,d){let h=e.canvas,f=l-u,m=c-d;if(a)if(f<0||m<0||f+r>h.width||m+i>h.height){let y=this.cachedCanvases.getCanvas("maskExtension",r,i),g=y.context;g.drawImage(h,-f,-m),g.globalCompositeOperation="destination-atop",g.fillStyle=a,g.fillRect(0,0,r,i),g.globalCompositeOperation="source-over",h=y.canvas,f=m=0}else{e.save(),e.globalAlpha=1,e.setTransform(1,0,0,1,0,0);let y=new Path2D;y.rect(f,m,r,i),e.clip(y),e.globalCompositeOperation="destination-atop",e.fillStyle=a,e.fillRect(f,m,r,i),e.restore()}n.save(),n.globalAlpha=1,n.setTransform(1,0,0,1,0,0),o==="Alpha"&&s?n.filter=this.filterFactory.addAlphaFilter(s):o==="Luminosity"&&(n.filter=this.filterFactory.addLuminosityFilter(s));let p=new Path2D;p.rect(l,c,r,i),n.clip(p),n.globalCompositeOperation="destination-in",n.drawImage(h,f,m,r,i,l,c,r,i),n.restore()}save(e){this.inSMaskMode&&Nm(this.ctx,this.suspendedCtx),this.ctx.save();let n=this.current;this.stateStack.push(n),this.current=n.clone(),this.dependencyTracker?.save(e)}restore(e){if(this.dependencyTracker?.restore(e),this.stateStack.length===0){this.inSMaskMode&&this.endSMaskMode();return}this.current=this.stateStack.pop(),this.ctx.restore(),this.inSMaskMode&&Nm(this.suspendedCtx,this.ctx),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}transform(e,n,r,i,o,a,s){this.dependencyTracker?.recordIncrementalData("transform",e),this.ctx.transform(n,r,i,o,a,s),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(e,n,r,i){let[o]=r;if(!i){o||=r[0]=new Path2D,this[n](e,o);return}if(this.dependencyTracker!==null){let a=n===Fm.stroke?this.current.lineWidth/2:0;this.dependencyTracker.resetBBox(e).recordBBox(e,this.ctx,i[0]-a,i[2]+a,i[1]-a,i[3]+a).recordDependencies(e,["transform"])}if(!(o instanceof Path2D)){let a=r[0]=new Path2D;for(let s=0,l=o.length;s<l;)switch(o[s++]){case Jy.moveTo:a.moveTo(o[s++],o[s++]);break;case Jy.lineTo:a.lineTo(o[s++],o[s++]);break;case Jy.curveTo:a.bezierCurveTo(o[s++],o[s++],o[s++],o[s++],o[s++],o[s++]);break;case Jy.closePath:a.closePath();break;default:we(`Unrecognized drawing path operator: ${o[s-1]}`);break}o=a}oe.axialAlignedBoundingBox(i,St(this.ctx),this.current.minMax),this[n](e,o),this._pathStartIdx=e}closePath(e){this.ctx.closePath()}stroke(e,n,r=!0){let i=this.ctx,o=this.current.strokeColor;if(i.globalAlpha=this.current.strokeAlpha,this.contentVisible)if(typeof o=="object"&&o?.getPattern){let a=o.isModifyingCurrentTransform()?i.getTransform():null;if(i.save(),i.strokeStyle=o.getPattern(i,this,Cr(i),cn.STROKE,e),a){let s=new Path2D;s.addPath(n,i.getTransform().invertSelf().multiplySelf(a)),n=s}this.rescaleAndStroke(n,!1),i.restore()}else this.rescaleAndStroke(n,!0);this.dependencyTracker?.recordDependencies(e,Pi.stroke),r&&this.consumePath(e,n,this.current.getClippedPathBoundingBox(cn.STROKE,St(this.ctx))),i.globalAlpha=this.current.fillAlpha}closeStroke(e,n){this.stroke(e,n)}fill(e,n,r=!0){let i=this.ctx,o=this.current.fillColor,a=this.current.patternFill,s=!1;if(a){let c=o.isModifyingCurrentTransform()?i.getTransform():null;if(this.dependencyTracker?.save(e),i.save(),i.fillStyle=o.getPattern(i,this,Cr(i),cn.FILL,e),c){let u=new Path2D;u.addPath(n,i.getTransform().invertSelf().multiplySelf(c)),n=u}s=!0}let l=this.current.getClippedPathBoundingBox();this.contentVisible&&l!==null&&(this.pendingEOFill?(i.fill(n,"evenodd"),this.pendingEOFill=!1):i.fill(n)),this.dependencyTracker?.recordDependencies(e,Pi.fill),s&&(i.restore(),this.dependencyTracker?.restore(e)),r&&this.consumePath(e,n,l)}eoFill(e,n){this.pendingEOFill=!0,this.fill(e,n)}fillStroke(e,n){this.fill(e,n,!1),this.stroke(e,n,!1),this.consumePath(e,n)}eoFillStroke(e,n){this.pendingEOFill=!0,this.fillStroke(e,n)}closeFillStroke(e,n){this.fillStroke(e,n)}closeEOFillStroke(e,n){this.pendingEOFill=!0,this.fillStroke(e,n)}endPath(e,n){this.consumePath(e,n)}rawFillPath(e,n){this.ctx.fill(n),this.dependencyTracker?.recordDependencies(e,Pi.rawFillPath).recordOperation(e)}clip(e){this.dependencyTracker?.recordFutureForcedDependency("clipMode",e),this.pendingClip=DG}eoClip(e){this.dependencyTracker?.recordFutureForcedDependency("clipMode",e),this.pendingClip=Xj}beginText(e){this.current.textMatrix=null,this.current.textMatrixScale=1,this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0,this.dependencyTracker?.recordOpenMarker(e).resetIncrementalData("sameLineText").resetIncrementalData("moveText",e)}endText(e){let n=this.pendingTextPaths,r=this.ctx;if(this.dependencyTracker){let{dependencyTracker:i}=this;n!==void 0&&i.recordFutureForcedDependency("textClip",i.getOpenMarker()).recordFutureForcedDependency("textClip",e),i.recordCloseMarker(e)}if(n!==void 0){let i=new Path2D,o=r.getTransform().invertSelf();for(let{transform:a,x:s,y:l,fontSize:c,path:u}of n)u&&i.addPath(u,new DOMMatrix(a).preMultiplySelf(o).translate(s,l).scale(c,-c));r.clip(i)}delete this.pendingTextPaths}setCharSpacing(e,n){this.dependencyTracker?.recordSimpleData("charSpacing",e),this.current.charSpacing=n}setWordSpacing(e,n){this.dependencyTracker?.recordSimpleData("wordSpacing",e),this.current.wordSpacing=n}setHScale(e,n){this.dependencyTracker?.recordSimpleData("hScale",e),this.current.textHScale=n/100}setLeading(e,n){this.dependencyTracker?.recordSimpleData("leading",e),this.current.leading=-n}setFont(e,n,r){this.dependencyTracker?.recordSimpleData("font",e).recordSimpleDataFromNamed("fontObj",n,e);let i=this.commonObjs.get(n),o=this.current;if(!i)throw new Error(`Can't find font for ${n}`);if(o.fontMatrix=i.fontMatrix||Xz,(o.fontMatrix[0]===0||o.fontMatrix[3]===0)&&we("Invalid font matrix for font "+n),r<0?(r=-r,o.fontDirection=-1):o.fontDirection=1,this.current.font=i,this.current.fontSize=r,i.isType3Font)return;let a=i.loadedName||"sans-serif",s=Oj(i,i.systemFontInfo?.css||`"${a}", ${i.fallbackName}`),l="normal";i.black?l="900":i.bold&&(l="bold");let c=i.italic?"italic":"normal",u=r;r<Hj?u=Hj:r>Vj&&(u=Vj),this.current.fontSizeScale=r/u,this.ctx.font=`${c} ${l} ${u}px ${s}`}setTextRenderingMode(e,n){this.dependencyTracker?.recordSimpleData("textRenderingMode",e),this.current.textRenderingMode=n}setTextRise(e,n){this.dependencyTracker?.recordSimpleData("textRise",e),this.current.textRise=n}moveText(e,n,r){this.dependencyTracker?.resetIncrementalData("sameLineText").recordIncrementalData("moveText",e),this.current.x=this.current.lineX+=n,this.current.y=this.current.lineY+=r}setLeadingMoveText(e,n,r){this.setLeading(e,-r),this.moveText(e,n,r)}setTextMatrix(e,n){this.dependencyTracker?.recordSimpleData("textMatrix",e);let{current:r}=this;r.textMatrix=n,r.textMatrixScale=Math.hypot(n[0],n[1]),r.x=r.lineX=0,r.y=r.lineY=0}nextLine(e){this.moveText(e,0,this.current.leading),this.dependencyTracker?.recordIncrementalData("moveText",this.dependencyTracker.getSimpleIndex("leading")??e)}#i(e,n,r){let i=new Path2D;return i.addPath(e,new DOMMatrix(r).invertSelf().multiplySelf(n)),i}paintChar(e,n,r,i,o,a){let s=this.ctx,l=this.current,c=l.font,u=l.textRenderingMode,d=l.fontSize/l.fontSizeScale,h=u&ln.FILL_STROKE_MASK,f=!!(u&ln.ADD_TO_PATH_FLAG),m=l.patternFill&&!c.missingFile,p=l.patternStroke&&!c.missingFile,y;if((c.disableFontFace||f||m||p)&&!c.missingFile&&(y=c.getPathGenerator(this.commonObjs,n)),y&&(c.disableFontFace||m||p)){s.save(),s.translate(r,i),s.scale(d,-d),this.dependencyTracker?.recordCharacterBBox(e,s,c);let g;if(h===ln.FILL||h===ln.FILL_STROKE)if(o){g=s.getTransform(),s.setTransform(...o);let v=this.#i(y,g,o);s.fill(v)}else s.fill(y);if(h===ln.STROKE||h===ln.FILL_STROKE)if(a){g||=s.getTransform(),s.setTransform(...a);let{a:v,b:S,c:_,d:$}=g,w=oe.inverseTransform(a),A=oe.transform([v,S,_,$,0,0],w);oe.singularValueDecompose2dScale(A,hi),s.lineWidth*=Math.max(hi[0],hi[1])/d,s.stroke(this.#i(y,g,a))}else s.lineWidth/=d,s.stroke(y);s.restore()}else(h===ln.FILL||h===ln.FILL_STROKE)&&(s.fillText(n,r,i),this.dependencyTracker?.recordCharacterBBox(e,s,c,d,r,i,()=>s.measureText(n))),(h===ln.STROKE||h===ln.FILL_STROKE)&&(this.dependencyTracker&&this.dependencyTracker?.recordCharacterBBox(e,s,c,d,r,i,()=>s.measureText(n)).recordDependencies(e,Pi.stroke),s.strokeText(n,r,i));f&&((this.pendingTextPaths||=[]).push({transform:St(s),x:r,y:i,fontSize:d,path:y}),this.dependencyTracker?.recordCharacterBBox(e,s,c,d,r,i))}get isFontSubpixelAAEnabled(){let{context:e}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);e.scale(1.5,1),e.fillText("I",0,10);let n=e.getImageData(0,0,10,10).data,r=!1;for(let i=3;i<n.length;i+=4)if(n[i]>0&&n[i]<255){r=!0;break}return Re(this,"isFontSubpixelAAEnabled",r)}showText(e,n){this.dependencyTracker&&(this.dependencyTracker.recordDependencies(e,Pi.showText).resetBBox(e),this.current.textRenderingMode&ln.ADD_TO_PATH_FLAG&&this.dependencyTracker.recordFutureForcedDependency("textClip",e).inheritPendingDependenciesAsFutureForcedDependencies());let r=this.current,i=r.font;if(i.isType3Font){this.showType3Text(e,n),this.dependencyTracker?.recordShowTextOperation(e);return}let o=r.fontSize;if(o===0){this.dependencyTracker?.recordOperation(e);return}let a=this.ctx,s=r.fontSizeScale,l=r.charSpacing,c=r.wordSpacing,u=r.fontDirection,d=r.textHScale*u,h=n.length,f=i.vertical,m=f?1:-1,p=i.defaultVMetrics,y=o*r.fontMatrix[0],g=r.textRenderingMode===ln.FILL&&!i.disableFontFace&&!r.patternFill;a.save(),r.textMatrix&&a.transform(...r.textMatrix),a.translate(r.x,r.y+r.textRise),u>0?a.scale(d,-1):a.scale(d,1);let v,S;if(r.patternFill){a.save();let k=r.fillColor.getPattern(a,this,Cr(a),cn.FILL,e);v=St(a),a.restore(),a.fillStyle=k}if(r.patternStroke){a.save();let k=r.strokeColor.getPattern(a,this,Cr(a),cn.STROKE,e);S=St(a),a.restore(),a.strokeStyle=k}let _=r.lineWidth,$=r.textMatrixScale;if($===0||_===0){let k=r.textRenderingMode&ln.FILL_STROKE_MASK;(k===ln.STROKE||k===ln.FILL_STROKE)&&(_=this.getSinglePixelWidth())}else _/=$;if(s!==1&&(a.scale(s,s),_/=s),a.lineWidth=_,i.isInvalidPDFjsFont){let k=[],I=0;for(let H of n)k.push(H.unicode),I+=H.width;let D=k.join("");if(a.fillText(D,0,0),this.dependencyTracker!==null){let H=a.measureText(D);this.dependencyTracker.recordBBox(e,this.ctx,-H.actualBoundingBoxLeft,H.actualBoundingBoxRight,-H.actualBoundingBoxAscent,H.actualBoundingBoxDescent).recordShowTextOperation(e)}r.x+=I*y*d,a.restore(),this.compose();return}let w=0,A;for(A=0;A<h;++A){let k=n[A];if(typeof k=="number"){w+=m*k*o/1e3;continue}let I=!1,D=(k.isSpace?c:0)+l,H=k.fontChar,ge=k.accent,ce,me,Te=k.width;if(f){let Se=k.vmetric||p,nt=-(k.vmetric?Se[1]:Te*.5)*y,j=Se[2]*y;Te=Se?-Se[0]:Te,ce=nt/s,me=(w+j)/s}else ce=w/s,me=0;let ie;if(i.remeasure&&Te>0){ie=a.measureText(H);let Se=ie.width*1e3/o*s;if(Te<Se&&this.isFontSubpixelAAEnabled){let nt=Te/Se;I=!0,a.save(),a.scale(nt,1),ce/=nt}else Te!==Se&&(ce+=(Te-Se)/2e3*o/s)}if(this.contentVisible&&(k.isInFont||i.missingFile)){if(g&&!ge)a.fillText(H,ce,me),this.dependencyTracker?.recordCharacterBBox(e,a,ie?{bbox:null}:i,o/s,ce,me,()=>ie??a.measureText(H));else if(this.paintChar(e,H,ce,me,v,S),ge){let Se=ce+o*ge.offset.x/s,nt=me-o*ge.offset.y/s;this.paintChar(e,ge.fontChar,Se,nt,v,S)}}let ne=f?Te*y-D*u:Te*y+D*u;w+=ne,I&&a.restore()}f?r.y-=w:r.x+=w*d,a.restore(),this.compose(),this.dependencyTracker?.recordShowTextOperation(e)}showType3Text(e,n){let r=this.ctx,i=this.current,o=i.font,a=i.fontSize,s=i.fontDirection,l=o.vertical?1:-1,c=i.charSpacing,u=i.wordSpacing,d=i.textHScale*s,h=i.fontMatrix||Xz,f=n.length,m=i.textRenderingMode===ln.INVISIBLE,p,y,g,v;if(m||a===0)return;this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null,r.save(),i.textMatrix&&r.transform(...i.textMatrix),r.translate(i.x,i.y+i.textRise),r.scale(d,s);let S=this.dependencyTracker;for(this.dependencyTracker=S?new $S(S,e):null,p=0;p<f;++p){if(y=n[p],typeof y=="number"){v=l*y*a/1e3,this.ctx.translate(v,0),i.x+=v*d;continue}let _=(y.isSpace?u:0)+c,$=o.charProcOperatorList[y.operatorListId];$?this.contentVisible&&(this.save(),r.scale(a,a),r.transform(...h),this.executeOperatorList($),this.restore()):we(`Type3 character "${y.operatorListId}" is not available.`);let w=[y.width,0];oe.applyTransform(w,h),g=w[0]*a+_,r.translate(g,0),i.x+=g*d}r.restore(),S&&(this.dependencyTracker=S)}setCharWidth(e,n,r){}setCharWidthAndBounds(e,n,r,i,o,a,s){let l=new Path2D;l.rect(i,o,a-i,s-o),this.ctx.clip(l),this.dependencyTracker?.recordBBox(e,this.ctx,i,a,o,s).recordClipBox(e,this.ctx,i,a,o,s),this.endPath(e)}getColorN_Pattern(e,n){let r;if(n[0]==="TilingPattern"){let i=this.baseTransform||St(this.ctx),o={createCanvasGraphics:(a,s)=>new t(a,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack},void 0,void 0,this.dependencyTracker?new $S(this.dependencyTracker,s,!0):null)};r=new zk(n,this.ctx,o,i)}else r=this._getPattern(e,n[1],n[2]);return r}setStrokeColorN(e,...n){this.dependencyTracker?.recordSimpleData("strokeColor",e),this.current.strokeColor=this.getColorN_Pattern(e,n),this.current.patternStroke=!0}setFillColorN(e,...n){this.dependencyTracker?.recordSimpleData("fillColor",e),this.current.fillColor=this.getColorN_Pattern(e,n),this.current.patternFill=!0}setStrokeRGBColor(e,n){this.dependencyTracker?.recordSimpleData("strokeColor",e),this.ctx.strokeStyle=this.current.strokeColor=n,this.current.patternStroke=!1}setStrokeTransparent(e){this.dependencyTracker?.recordSimpleData("strokeColor",e),this.ctx.strokeStyle=this.current.strokeColor="transparent",this.current.patternStroke=!1}setFillRGBColor(e,n){this.dependencyTracker?.recordSimpleData("fillColor",e),this.ctx.fillStyle=this.current.fillColor=n,this.current.patternFill=!1}setFillTransparent(e){this.dependencyTracker?.recordSimpleData("fillColor",e),this.ctx.fillStyle=this.current.fillColor="transparent",this.current.patternFill=!1}_getPattern(e,n,r=null){let i;return this.cachedPatterns.has(n)?i=this.cachedPatterns.get(n):(i=CG(this.getObject(e,n)),this.cachedPatterns.set(n,i)),r&&(i.matrix=r),i}shadingFill(e,n){if(!this.contentVisible)return;let r=this.ctx;this.save(e);let i=this._getPattern(e,n);r.fillStyle=i.getPattern(r,this,Cr(r),cn.SHADING,e);let o=Cr(r);if(o){let{width:a,height:s}=r.canvas,l=hu.slice();oe.axialAlignedBoundingBox([0,0,a,s],o,l);let[c,u,d,h]=l;this.ctx.fillRect(c,u,d-c,h-u)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.dependencyTracker?.resetBBox(e).recordFullPageBBox(e).recordDependencies(e,Pi.transform).recordDependencies(e,Pi.fill).recordOperation(e),this.compose(this.current.getClippedPathBoundingBox()),this.restore(e)}beginInlineImage(){rt("Should not call beginInlineImage")}beginImageData(){rt("Should not call beginImageData")}paintFormXObjectBegin(e,n,r){if(this.contentVisible&&(this.save(e),this.baseTransformStack.push(this.baseTransform),n&&this.transform(e,...n),this.baseTransform=St(this.ctx),r)){oe.axialAlignedBoundingBox(r,this.baseTransform,this.current.minMax);let[i,o,a,s]=r,l=new Path2D;l.rect(i,o,a-i,s-o),this.ctx.clip(l),this.dependencyTracker?.recordClipBox(e,this.ctx,i,a,o,s),this.endPath(e)}}paintFormXObjectEnd(e){this.contentVisible&&(this.restore(e),this.baseTransform=this.baseTransformStack.pop())}beginGroup(e,n){if(!this.contentVisible)return;this.save(e),this.inSMaskMode&&(this.endSMaskMode(),this.current.activeSMask=null);let r=this.ctx;n.isolated||GS("TODO: Support non-isolated groups."),n.knockout&&we("Knockout groups not supported.");let i=St(r);if(n.matrix&&r.transform(...n.matrix),!n.bbox)throw new Error("Bounding box is required.");let o=hu.slice();oe.axialAlignedBoundingBox(n.bbox,St(r),o);let a=[0,0,r.canvas.width,r.canvas.height];o=oe.intersect(o,a)||[0,0,0,0];let s=Math.floor(o[0]),l=Math.floor(o[1]),c=Math.max(Math.ceil(o[2])-s,1),u=Math.max(Math.ceil(o[3])-l,1);this.current.startNewPathAndClipBox([0,0,c,u]);let d="groupAt"+this.groupLevel;n.smask&&(d+="_smask_"+this.smaskCounter++%2);let h=this.cachedCanvases.getCanvas(d,c,u),f=h.context;f.translate(-s,-l),f.transform(...i);let m=new Path2D,[p,y,g,v]=n.bbox;if(m.rect(p,y,g-p,v-y),n.matrix){let S=new Path2D;S.addPath(m,new DOMMatrix(n.matrix)),m=S}f.clip(m),n.smask&&this.smaskStack.push({canvas:h.canvas,context:f,offsetX:s,offsetY:l,subtype:n.smask.subtype,backdrop:n.smask.backdrop,transferMap:n.smask.transferMap||null,startTransformInverse:null}),(!n.smask||this.dependencyTracker)&&(r.setTransform(1,0,0,1,0,0),r.translate(s,l),r.save()),Nm(r,f),this.ctx=f,this.dependencyTracker?.inheritSimpleDataAsFutureForcedDependencies(["fillAlpha","strokeAlpha","globalCompositeOperation"]).pushBaseTransform(r),this.setGState(e,[["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(r),this.groupLevel++}endGroup(e,n){if(!this.contentVisible)return;this.groupLevel--;let r=this.ctx,i=this.groupStack.pop();if(this.ctx=i,this.ctx.imageSmoothingEnabled=!1,this.dependencyTracker?.popBaseTransform(),n.smask)this.tempSMask=this.smaskStack.pop(),this.restore(e),this.dependencyTracker&&this.ctx.restore();else{this.ctx.restore();let o=St(this.ctx);this.restore(e),this.ctx.save(),this.ctx.setTransform(...o);let a=hu.slice();oe.axialAlignedBoundingBox([0,0,r.canvas.width,r.canvas.height],o,a),this.ctx.drawImage(r.canvas,0,0),this.ctx.restore(),this.compose(a)}}beginAnnotation(e,n,r,i,o,a){if(this.#e(),iS(this.ctx),this.ctx.save(),this.save(e),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),r){let s=r[2]-r[0],l=r[3]-r[1];if(a&&this.annotationCanvasMap){i=i.slice(),i[4]-=r[0],i[5]-=r[1],r=r.slice(),r[0]=r[1]=0,r[2]=s,r[3]=l,oe.singularValueDecompose2dScale(St(this.ctx),hi);let{viewportScale:c}=this,u=Math.ceil(s*this.outputScaleX*c),d=Math.ceil(l*this.outputScaleY*c);this.annotationCanvas=this.canvasFactory.create(u,d);let{canvas:h,context:f}=this.annotationCanvas;this.annotationCanvasMap.set(n,h),this.annotationCanvas.savedCtx=this.ctx,this.ctx=f,this.ctx.save(),this.ctx.setTransform(hi[0],0,0,-hi[1],0,l*hi[1]),iS(this.ctx)}else{iS(this.ctx),this.endPath(e);let c=new Path2D;c.rect(r[0],r[1],s,l),this.ctx.clip(c)}}this.current=new AS(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(e,...i),this.transform(e,...o)}endAnnotation(e){this.annotationCanvas&&(this.ctx.restore(),this.#t(),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas)}paintImageMaskXObject(e,n){if(!this.contentVisible)return;let r=n.count;n=this.getObject(e,n.data,n),n.count=r;let i=this.ctx,o=this._createMaskCanvas(e,n),a=o.canvas;i.save(),i.setTransform(1,0,0,1,0,0),i.drawImage(a,o.offsetX,o.offsetY),this.dependencyTracker?.resetBBox(e).recordBBox(e,this.ctx,o.offsetX,o.offsetX+a.width,o.offsetY,o.offsetY+a.height).recordOperation(e),i.restore(),this.compose()}paintImageMaskXObjectRepeat(e,n,r,i=0,o=0,a,s){if(!this.contentVisible)return;n=this.getObject(e,n.data,n);let l=this.ctx;l.save();let c=St(l);l.transform(r,i,o,a,0,0);let u=this._createMaskCanvas(e,n);l.setTransform(1,0,0,1,u.offsetX-c[4],u.offsetY-c[5]),this.dependencyTracker?.resetBBox(e);for(let d=0,h=s.length;d<h;d+=2){let f=oe.transform(c,[r,i,o,a,s[d],s[d+1]]);l.drawImage(u.canvas,f[4],f[5]),this.dependencyTracker?.recordBBox(e,this.ctx,f[4],f[4]+u.canvas.width,f[5],f[5]+u.canvas.height)}l.restore(),this.compose(),this.dependencyTracker?.recordOperation(e)}paintImageMaskXObjectGroup(e,n){if(!this.contentVisible)return;let r=this.ctx,i=this.current.fillColor,o=this.current.patternFill;this.dependencyTracker?.resetBBox(e).recordDependencies(e,Pi.transformAndFill);for(let a of n){let{data:s,width:l,height:c,transform:u}=a,d=this.cachedCanvases.getCanvas("maskCanvas",l,c),h=d.context;h.save();let f=this.getObject(e,s,a);Kj(h,f),h.globalCompositeOperation="source-in",h.fillStyle=o?i.getPattern(h,this,Cr(r),cn.FILL,e):i,h.fillRect(0,0,l,c),h.restore(),r.save(),r.transform(...u),r.scale(1,-1),nS(r,d.canvas,0,0,l,c,0,-1,1,1),this.dependencyTracker?.recordBBox(e,r,0,l,0,c),r.restore()}this.compose(),this.dependencyTracker?.recordOperation(e)}paintImageXObject(e,n){if(!this.contentVisible)return;let r=this.getObject(e,n);if(!r){we("Dependent image isn't ready yet");return}this.paintInlineImageXObject(e,r)}paintImageXObjectRepeat(e,n,r,i,o){if(!this.contentVisible)return;let a=this.getObject(e,n);if(!a){we("Dependent image isn't ready yet");return}let s=a.width,l=a.height,c=[];for(let u=0,d=o.length;u<d;u+=2)c.push({transform:[r,0,0,i,o[u],o[u+1]],x:0,y:0,w:s,h:l});this.paintInlineImageXObjectGroup(e,a,c)}applyTransferMapsToCanvas(e){return this.current.transferMaps!=="none"&&(e.filter=this.current.transferMaps,e.drawImage(e.canvas,0,0),e.filter="none"),e.canvas}applyTransferMapsToBitmap(e){if(this.current.transferMaps==="none")return e.bitmap;let{bitmap:n,width:r,height:i}=e,o=this.cachedCanvases.getCanvas("inlineImage",r,i),a=o.context;return a.filter=this.current.transferMaps,a.drawImage(n,0,0),a.filter="none",o.canvas}paintInlineImageXObject(e,n){if(!this.contentVisible)return;let r=n.width,i=n.height,o=this.ctx;this.save(e);let{filter:a}=o;a!=="none"&&a!==""&&(o.filter="none"),o.scale(1/r,-1/i);let s;if(n.bitmap)s=this.applyTransferMapsToBitmap(n);else if(typeof HTMLElement=="function"&&n instanceof HTMLElement||!n.data)s=n;else{let u=this.cachedCanvases.getCanvas("inlineImage",r,i).context;Gj(u,n),s=this.applyTransferMapsToCanvas(u)}let l=this._scaleImage(s,Cr(o));o.imageSmoothingEnabled=Yj(St(o),n.interpolate),this.dependencyTracker?.resetBBox(e).recordBBox(e,o,0,r,-i,0).recordDependencies(e,Pi.imageXObject).recordOperation(e),nS(o,l.img,0,0,l.paintWidth,l.paintHeight,0,-i,r,i),this.compose(),this.restore(e)}paintInlineImageXObjectGroup(e,n,r){if(!this.contentVisible)return;let i=this.ctx,o;if(n.bitmap)o=n.bitmap;else{let a=n.width,s=n.height,c=this.cachedCanvases.getCanvas("inlineImage",a,s).context;Gj(c,n),o=this.applyTransferMapsToCanvas(c)}this.dependencyTracker?.resetBBox(e);for(let a of r)i.save(),i.transform(...a.transform),i.scale(1,-1),nS(i,o,a.x,a.y,a.w,a.h,0,-1,1,1),this.dependencyTracker?.recordBBox(e,i,0,1,-1,0),i.restore();this.dependencyTracker?.recordOperation(e),this.compose()}paintSolidColorImageMask(e){this.contentVisible&&(this.dependencyTracker?.resetBBox(e).recordBBox(e,this.ctx,0,1,0,1).recordDependencies(e,Pi.fill).recordOperation(e),this.ctx.fillRect(0,0,1,1),this.compose())}markPoint(e,n){}markPointProps(e,n,r){}beginMarkedContent(e,n){this.dependencyTracker?.beginMarkedContent(e),this.markedContentStack.push({visible:!0})}beginMarkedContentProps(e,n,r){this.dependencyTracker?.beginMarkedContent(e),n==="OC"?this.markedContentStack.push({visible:this.optionalContentConfig.isVisible(r)}):this.markedContentStack.push({visible:!0}),this.contentVisible=this.isContentVisible()}endMarkedContent(e){this.dependencyTracker?.endMarkedContent(e),this.markedContentStack.pop(),this.contentVisible=this.isContentVisible()}beginCompat(e){}endCompat(e){}consumePath(e,n,r){let i=this.current.isEmptyClip();this.pendingClip&&this.current.updateClipFromPath(),this.pendingClip||this.compose(r);let o=this.ctx;this.pendingClip?(i||(this.pendingClip===Xj?o.clip(n,"evenodd"):o.clip(n)),this.pendingClip=null,this.dependencyTracker?.bboxToClipBoxDropOperation(e).recordFutureForcedDependency("clipPath",e)):this.dependencyTracker?.recordOperation(e),this.current.startNewPathAndClipBox(this.current.clipBox)}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){let e=St(this.ctx);if(e[1]===0&&e[2]===0)this._cachedGetSinglePixelWidth=1/Math.min(Math.abs(e[0]),Math.abs(e[3]));else{let n=Math.abs(e[0]*e[3]-e[2]*e[1]),r=Math.hypot(e[0],e[2]),i=Math.hypot(e[1],e[3]);this._cachedGetSinglePixelWidth=Math.max(r,i)/n}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(this._cachedScaleForStroking[0]===-1){let{lineWidth:e}=this.current,{a:n,b:r,c:i,d:o}=this.ctx.getTransform(),a,s;if(r===0&&i===0){let l=Math.abs(n),c=Math.abs(o);if(l===c)if(e===0)a=s=1/l;else{let u=l*e;a=s=u<1?1/u:1}else if(e===0)a=1/l,s=1/c;else{let u=l*e,d=c*e;a=u<1?1/u:1,s=d<1?1/d:1}}else{let l=Math.abs(n*o-r*i),c=Math.hypot(n,r),u=Math.hypot(i,o);if(e===0)a=u/l,s=c/l;else{let d=e*l;a=u>d?u/d:1,s=c>d?c/d:1}}this._cachedScaleForStroking[0]=a,this._cachedScaleForStroking[1]=s}return this._cachedScaleForStroking}rescaleAndStroke(e,n){let{ctx:r,current:{lineWidth:i}}=this,[o,a]=this.getScaleForStroking();if(o===a){r.lineWidth=(i||1)*o,r.stroke(e);return}let s=r.getLineDash();n&&r.save(),r.scale(o,a),Gz.a=1/o,Gz.d=1/a;let l=new Path2D;if(l.addPath(e,Gz),s.length>0){let c=Math.max(o,a);r.setLineDash(s.map(u=>u/c)),r.lineDashOffset/=c}r.lineWidth=i||1,r.stroke(l),n&&r.restore()}isContentVisible(){for(let e=this.markedContentStack.length-1;e>=0;e--)if(!this.markedContentStack[e].visible)return!1;return!0}};for(let t in Fm)fu.prototype[t]!==void 0&&(fu.prototype[Fm[t]]=fu.prototype[t]);var ES=class t{#e;#t;#i;static strings=["fontFamily","fontWeight","italicAngle"];static write(e){let n=new TextEncoder,r={},i=0;for(let c of t.strings){let u=n.encode(e[c]);r[c]=u,i+=4+u.length}let o=new ArrayBuffer(i),a=new Uint8Array(o),s=new DataView(o),l=0;for(let c of t.strings){let u=r[c],d=u.length;s.setUint32(l,d),a.set(u,l+4),l+=4+d}return Ue(l===o.byteLength,"CssFontInfo.write: Buffer overflow"),o}constructor(e){this.#e=e,this.#t=new DataView(this.#e),this.#i=new TextDecoder}#n(e){Ue(e<t.strings.length,"Invalid string index");let n=0;for(let i=0;i<e;i++)n+=this.#t.getUint32(n)+4;let r=this.#t.getUint32(n);return this.#i.decode(new Uint8Array(this.#e,n+4,r))}get fontFamily(){return this.#n(0)}get fontWeight(){return this.#n(1)}get italicAngle(){return this.#n(2)}},TS=class t{#e;#t;#i;static strings=["css","loadedName","baseFontName","src"];static write(e){let n=new TextEncoder,r={},i=0;for(let h of t.strings){let f=n.encode(e[h]);r[h]=f,i+=4+f.length}i+=4;let o,a,s=1+i;e.style&&(o=n.encode(e.style.style),a=n.encode(e.style.weight),s+=4+o.length+4+a.length);let l=new ArrayBuffer(s),c=new Uint8Array(l),u=new DataView(l),d=0;u.setUint8(d++,e.guessFallback?1:0),u.setUint32(d,0),d+=4,i=0;for(let h of t.strings){let f=r[h],m=f.length;i+=4+m,u.setUint32(d,m),c.set(f,d+4),d+=4+m}return u.setUint32(d-i-4,i),e.style&&(u.setUint32(d,o.length),c.set(o,d+4),d+=4+o.length,u.setUint32(d,a.length),c.set(a,d+4),d+=4+a.length),Ue(d<=l.byteLength,"SubstitionInfo.write: Buffer overflow"),l.transferToFixedLength(d)}constructor(e){this.#e=e,this.#t=new DataView(this.#e),this.#i=new TextDecoder}get guessFallback(){return this.#t.getUint8(0)!==0}#n(e){Ue(e<t.strings.length,"Invalid string index");let n=5;for(let i=0;i<e;i++)n+=this.#t.getUint32(n)+4;let r=this.#t.getUint32(n);return this.#i.decode(new Uint8Array(this.#e,n+4,r))}get css(){return this.#n(0)}get loadedName(){return this.#n(1)}get baseFontName(){return this.#n(2)}get src(){return this.#n(3)}get style(){let e=1;e+=4+this.#t.getUint32(e);let n=this.#t.getUint32(e),r=this.#i.decode(new Uint8Array(this.#e,e+4,n));e+=4+n;let i=this.#t.getUint32(e),o=this.#i.decode(new Uint8Array(this.#e,e+4,i));return{style:r,weight:o}}},Rk=class t{static bools=["black","bold","disableFontFace","fontExtraProperties","isInvalidPDFjsFont","isType3Font","italic","missingFile","remeasure","vertical"];static numbers=["ascent","defaultWidth","descent"];static strings=["fallbackName","loadedName","mimetype","name"];static#e=Math.ceil(this.bools.length*2/8);static#t=this.#e+this.numbers.length*8;static#i=this.#t+1+8;static#n=this.#i+1+48;static#a=this.#n+1+6;#r;#o;#s;constructor({data:e,extra:n}){this.#r=e,this.#o=new TextDecoder,this.#s=new DataView(this.#r),n&&Object.assign(this,n)}#c(e){Ue(e<t.bools.length,"Invalid boolean index");let n=Math.floor(e/4),r=e*2%8,i=this.#s.getUint8(n)>>r&3;return i===0?void 0:i===2}get black(){return this.#c(0)}get bold(){return this.#c(1)}get disableFontFace(){return this.#c(2)}get fontExtraProperties(){return this.#c(3)}get isInvalidPDFjsFont(){return this.#c(4)}get isType3Font(){return this.#c(5)}get italic(){return this.#c(6)}get missingFile(){return this.#c(7)}get remeasure(){return this.#c(8)}get vertical(){return this.#c(9)}#l(e){return Ue(e<t.numbers.length,"Invalid number index"),this.#s.getFloat64(t.#e+e*8)}get ascent(){return this.#l(0)}get defaultWidth(){return this.#l(1)}get descent(){return this.#l(2)}get bbox(){let e=t.#t;if(this.#s.getUint8(e)===0)return;e+=1;let r=[];for(let i=0;i<4;i++)r.push(this.#s.getInt16(e,!0)),e+=2;return r}get fontMatrix(){let e=t.#i;if(this.#s.getUint8(e)===0)return;e+=1;let r=[];for(let i=0;i<6;i++)r.push(this.#s.getFloat64(e,!0)),e+=8;return r}get defaultVMetrics(){let e=t.#n;if(this.#s.getUint8(e)===0)return;e+=1;let r=[];for(let i=0;i<3;i++)r.push(this.#s.getInt16(e,!0)),e+=2;return r}#h(e){Ue(e<t.strings.length,"Invalid string index");let n=t.#a+4;for(let o=0;o<e;o++)n+=this.#s.getUint32(n)+4;let r=this.#s.getUint32(n),i=new Uint8Array(r);return i.set(new Uint8Array(this.#r,n+4,r)),this.#o.decode(i)}get fallbackName(){return this.#h(0)}get loadedName(){return this.#h(1)}get mimetype(){return this.#h(2)}get name(){return this.#h(3)}get data(){let e=t.#a,n=this.#s.getUint32(e);e+=4+n;let r=this.#s.getUint32(e);e+=4+r;let i=this.#s.getUint32(e);e+=4+i;let o=this.#s.getUint32(e);if(o!==0)return new Uint8Array(this.#r,e+4,o)}clearData(){let e=t.#a,n=this.#s.getUint32(e);e+=4+n;let r=this.#s.getUint32(e);e+=4+r;let i=this.#s.getUint32(e);e+=4+i;let o=this.#s.getUint32(e);new Uint8Array(this.#r,e+4,o).fill(0),this.#s.setUint32(e,0)}get cssFontInfo(){let e=t.#a,n=this.#s.getUint32(e);e+=4+n;let r=this.#s.getUint32(e);e+=4+r;let i=this.#s.getUint32(e);if(i===0)return null;let o=new Uint8Array(i);return o.set(new Uint8Array(this.#r,e+4,i)),new ES(o.buffer)}get systemFontInfo(){let e=t.#a,n=this.#s.getUint32(e);e+=4+n;let r=this.#s.getUint32(e);if(r===0)return null;let i=new Uint8Array(r);return i.set(new Uint8Array(this.#r,e+4,r)),new TS(i.buffer)}static write(e){let n=e.systemFontInfo?TS.write(e.systemFontInfo):null,r=e.cssFontInfo?ES.write(e.cssFontInfo):null,i=new TextEncoder,o={},a=0;for(let p of t.strings)o[p]=i.encode(e[p]),a+=4+o[p].length;let s=t.#a+4+a+4+(n?n.byteLength:0)+4+(r?r.byteLength:0)+4+(e.data?e.data.length:0),l=new ArrayBuffer(s),c=new Uint8Array(l),u=new DataView(l),d=0,h=t.bools.length,f=0,m=0;for(let p=0;p<h;p++){let y=e[t.bools[p]];f|=(y===void 0?0:y?2:1)<<m,m+=2,(m===8||p===h-1)&&(u.setUint8(d++,f),f=0,m=0)}Ue(d===t.#e,"FontInfo.write: Boolean properties offset mismatch");for(let p of t.numbers)u.setFloat64(d,e[p]),d+=8;if(Ue(d===t.#t,"FontInfo.write: Number properties offset mismatch"),e.bbox){u.setUint8(d++,4);for(let p of e.bbox)u.setInt16(d,p,!0),d+=2}else u.setUint8(d++,0),d+=8;if(Ue(d===t.#i,"FontInfo.write: BBox properties offset mismatch"),e.fontMatrix){u.setUint8(d++,6);for(let p of e.fontMatrix)u.setFloat64(d,p,!0),d+=8}else u.setUint8(d++,0),d+=48;if(Ue(d===t.#n,"FontInfo.write: FontMatrix properties offset mismatch"),e.defaultVMetrics){u.setUint8(d++,1);for(let p of e.defaultVMetrics)u.setInt16(d,p,!0),d+=2}else u.setUint8(d++,0),d+=6;Ue(d===t.#a,"FontInfo.write: DefaultVMetrics properties offset mismatch"),u.setUint32(t.#a,0),d+=4;for(let p of t.strings){let y=o[p],g=y.length;u.setUint32(d,g),c.set(y,d+4),d+=4+g}if(u.setUint32(t.#a,d-t.#a-4),!n)u.setUint32(d,0),d+=4;else{let p=n.byteLength;u.setUint32(d,p),Ue(d+4+p<=l.byteLength,"FontInfo.write: Buffer overflow at systemFontInfo"),c.set(new Uint8Array(n),d+4),d+=4+p}if(!r)u.setUint32(d,0),d+=4;else{let p=r.byteLength;u.setUint32(d,p),Ue(d+4+p<=l.byteLength,"FontInfo.write: Buffer overflow at cssFontInfo"),c.set(new Uint8Array(r),d+4),d+=4+p}return e.data===void 0?(u.setUint32(d,0),d+=4):(u.setUint32(d,e.data.length),c.set(e.data,d+4),d+=4+e.data.length),Ue(d<=l.byteLength,"FontInfo.write: Buffer overflow"),l.transferToFixedLength(d)}},Bs=class{static#e=null;static#t="";static get workerPort(){return this.#e}static set workerPort(e){if(!(typeof Worker<"u"&&e instanceof Worker)&&e!==null)throw new Error("Invalid `workerPort` type.");this.#e=e}static get workerSrc(){return this.#t}static set workerSrc(e){if(typeof e!="string")throw new Error("Invalid `workerSrc` type.");this.#t=e}},Ck=class{#e;#t;constructor({parsedData:e,rawData:n}){this.#e=e,this.#t=n}getRaw(){return this.#t}get(e){return this.#e.get(e)??null}[Symbol.iterator](){return this.#e.entries()}},uu=Symbol("INTERNAL"),Ik=class{#e=!1;#t=!1;#i=!1;#n=!0;constructor(e,{name:n,intent:r,usage:i,rbGroups:o}){this.#e=!!(e&di.DISPLAY),this.#t=!!(e&di.PRINT),this.name=n,this.intent=r,this.usage=i,this.rbGroups=o}get visible(){if(this.#i)return this.#n;if(!this.#n)return!1;let{print:e,view:n}=this.usage;return this.#e?n?.viewState!=="OFF":this.#t?e?.printState!=="OFF":!0}_setVisible(e,n,r=!1){e!==uu&&rt("Internal method `_setVisible` called."),this.#i=r,this.#n=n}},Ok=class{#e=null;#t=new Map;#i=null;#n=null;constructor(e,n=di.DISPLAY){if(this.renderingIntent=n,this.name=null,this.creator=null,e!==null){this.name=e.name,this.creator=e.creator,this.#n=e.order;for(let r of e.groups)this.#t.set(r.id,new Ik(n,r));if(e.baseState==="OFF")for(let r of this.#t.values())r._setVisible(uu,!1);for(let r of e.on)this.#t.get(r)._setVisible(uu,!0);for(let r of e.off)this.#t.get(r)._setVisible(uu,!1);this.#i=this.getHash()}}#a(e){let n=e.length;if(n<2)return!0;let r=e[0];for(let i=1;i<n;i++){let o=e[i],a;if(Array.isArray(o))a=this.#a(o);else if(this.#t.has(o))a=this.#t.get(o).visible;else return we(`Optional content group not found: ${o}`),!0;switch(r){case"And":if(!a)return!1;break;case"Or":if(a)return!0;break;case"Not":return!a;default:return!0}}return r==="And"}isVisible(e){if(this.#t.size===0)return!0;if(!e)return GS("Optional content group not defined."),!0;if(e.type==="OCG")return this.#t.has(e.id)?this.#t.get(e.id).visible:(we(`Optional content group not found: ${e.id}`),!0);if(e.type==="OCMD"){if(e.expression)return this.#a(e.expression);if(!e.policy||e.policy==="AnyOn"){for(let n of e.ids){if(!this.#t.has(n))return we(`Optional content group not found: ${n}`),!0;if(this.#t.get(n).visible)return!0}return!1}else if(e.policy==="AllOn"){for(let n of e.ids){if(!this.#t.has(n))return we(`Optional content group not found: ${n}`),!0;if(!this.#t.get(n).visible)return!1}return!0}else if(e.policy==="AnyOff"){for(let n of e.ids){if(!this.#t.has(n))return we(`Optional content group not found: ${n}`),!0;if(!this.#t.get(n).visible)return!0}return!1}else if(e.policy==="AllOff"){for(let n of e.ids){if(!this.#t.has(n))return we(`Optional content group not found: ${n}`),!0;if(this.#t.get(n).visible)return!1}return!0}return we(`Unknown optional content policy ${e.policy}.`),!0}return we(`Unknown group type ${e.type}.`),!0}setVisibility(e,n=!0,r=!0){let i=this.#t.get(e);if(!i){we(`Optional content group not found: ${e}`);return}if(r&&n&&i.rbGroups.length)for(let o of i.rbGroups)for(let a of o)a!==e&&this.#t.get(a)?._setVisible(uu,!1,!0);i._setVisible(uu,!!n,!0),this.#e=null}setOCGState({state:e,preserveRB:n}){let r;for(let i of e){switch(i){case"ON":case"OFF":case"Toggle":r=i;continue}let o=this.#t.get(i);if(o)switch(r){case"ON":this.setVisibility(i,!0,n);break;case"OFF":this.setVisibility(i,!1,n);break;case"Toggle":this.setVisibility(i,!o.visible,n);break}}this.#e=null}get hasInitialVisibility(){return this.#i===null||this.getHash()===this.#i}getOrder(){return this.#t.size?this.#n?this.#n.slice():[...this.#t.keys()]:null}getGroup(e){return this.#t.get(e)||null}getHash(){if(this.#e!==null)return this.#e;let e=new mS;for(let[n,r]of this.#t)e.update(`${n}:${r.visible}`);return this.#e=e.hexdigest()}[Symbol.iterator](){return this.#t.entries()}},Pk=class{constructor(e,{disableRange:n=!1,disableStream:r=!1}){Ue(e,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');let{length:i,initialData:o,progressiveDone:a,contentDispositionFilename:s}=e;if(this._queuedChunks=[],this._progressiveDone=a,this._contentDispositionFilename=s,o?.length>0){let l=o instanceof Uint8Array&&o.byteLength===o.buffer.byteLength?o.buffer:new Uint8Array(o).buffer;this._queuedChunks.push(l)}this._pdfDataRangeTransport=e,this._isStreamingSupported=!r,this._isRangeSupported=!n,this._contentLength=i,this._fullRequestReader=null,this._rangeReaders=[],e.addRangeListener((l,c)=>{this._onReceiveData({begin:l,chunk:c})}),e.addProgressListener((l,c)=>{this._onProgress({loaded:l,total:c})}),e.addProgressiveReadListener(l=>{this._onReceiveData({chunk:l})}),e.addProgressiveDoneListener(()=>{this._onProgressiveDone()}),e.transportReady()}_onReceiveData({begin:e,chunk:n}){let r=n instanceof Uint8Array&&n.byteLength===n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer;if(e===void 0)this._fullRequestReader?this._fullRequestReader._enqueue(r):this._queuedChunks.push(r);else{let i=this._rangeReaders.some(function(o){return o._begin!==e?!1:(o._enqueue(r),!0)});Ue(i,"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}_onProgress(e){e.total===void 0?this._rangeReaders[0]?.onProgress?.({loaded:e.loaded}):this._fullRequestReader?.onProgress?.({loaded:e.loaded,total:e.total})}_onProgressiveDone(){this._fullRequestReader?.progressiveDone(),this._progressiveDone=!0}_removeRangeReader(e){let n=this._rangeReaders.indexOf(e);n>=0&&this._rangeReaders.splice(n,1)}getFullReader(){Ue(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");let e=this._queuedChunks;return this._queuedChunks=null,new Nk(this,e,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(e,n){if(n<=this._progressiveDataLength)return null;let r=new Mk(this,e,n);return this._pdfDataRangeTransport.requestDataRange(e,n),this._rangeReaders.push(r),r}cancelAllRequests(e){this._fullRequestReader?.cancel(e);for(let n of this._rangeReaders.slice(0))n.cancel(e);this._pdfDataRangeTransport.abort()}},Nk=class{constructor(e,n,r=!1,i=null){this._stream=e,this._done=r||!1,this._filename=RR(i)?i:null,this._queuedChunks=n||[],this._loaded=0;for(let o of this._queuedChunks)this._loaded+=o.byteLength;this._requests=[],this._headersReady=Promise.resolve(),e._fullRequestReader=this,this.onProgress=null}_enqueue(e){this._done||(this._requests.length>0?this._requests.shift().resolve({value:e,done:!1}):this._queuedChunks.push(e),this._loaded+=e.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};let e=Promise.withResolvers();return this._requests.push(e),e.promise}cancel(e){this._done=!0;for(let n of this._requests)n.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||(this._done=!0)}},Mk=class{constructor(e,n,r){this._stream=e,this._begin=n,this._end=r,this._queuedChunk=null,this._requests=[],this._done=!1,this.onProgress=null}_enqueue(e){if(!this._done){if(this._requests.length===0)this._queuedChunk=e;else{this._requests.shift().resolve({value:e,done:!1});for(let r of this._requests)r.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){let n=this._queuedChunk;return this._queuedChunk=null,{value:n,done:!1}}if(this._done)return{value:void 0,done:!0};let e=Promise.withResolvers();return this._requests.push(e),e.promise}cancel(e){this._done=!0;for(let n of this._requests)n.resolve({value:void 0,done:!0});this._requests.length=0,this._stream._removeRangeReader(this)}};function LG(t){let e=!0,n=r("filename\\*","i").exec(t);if(n){n=n[1];let u=s(n);return u=unescape(u),u=l(u),u=c(u),o(u)}if(n=a(t),n){let u=c(n);return o(u)}if(n=r("filename","i").exec(t),n){n=n[1];let u=s(n);return u=c(u),o(u)}function r(u,d){return new RegExp("(?:^|;)\\s*"+u+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',d)}function i(u,d){if(u){if(!/^[\x00-\xFF]+$/.test(d))return d;try{let h=new TextDecoder(u,{fatal:!0}),f=np(d);d=h.decode(f),e=!1}catch{}}return d}function o(u){return e&&/[\x80-\xff]/.test(u)&&(u=i("utf-8",u),e&&(u=i("iso-8859-1",u))),u}function a(u){let d=[],h,f=r("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;(h=f.exec(u))!==null;){let[,p,y,g]=h;if(p=parseInt(p,10),p in d){if(p===0)break;continue}d[p]=[y,g]}let m=[];for(let p=0;p<d.length&&p in d;++p){let[y,g]=d[p];g=s(g),y&&(g=unescape(g),p===0&&(g=l(g))),m.push(g)}return m.join("")}function s(u){if(u.startsWith('"')){let d=u.slice(1).split('\\"');for(let h=0;h<d.length;++h){let f=d[h].indexOf('"');f!==-1&&(d[h]=d[h].slice(0,f),d.length=h+1),d[h]=d[h].replaceAll(/\\(.)/g,"$1")}u=d.join('"')}return u}function l(u){let d=u.indexOf("'");if(d===-1)return u;let h=u.slice(0,d),m=u.slice(d+1).replace(/^[^']*'/,"");return i(h,m)}function c(u){return!u.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(u)?u:u.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,function(d,h,f,m){if(f==="q"||f==="Q")return m=m.replaceAll("_"," "),m=m.replaceAll(/=([0-9a-fA-F]{2})/g,function(p,y){return String.fromCharCode(parseInt(y,16))}),i(h,m);try{m=atob(m)}catch{}return i(h,m)})}return""}function aU(t,e){let n=new Headers;if(!t||!e||typeof e!="object")return n;for(let r in e){let i=e[r];i!==void 0&&n.append(r,i)}return n}function YS(t){return URL.parse(t)?.origin??null}function sU({responseHeaders:t,isHttp:e,rangeChunkSize:n,disableRange:r}){let i={allowRangeRequests:!1,suggestedLength:void 0},o=parseInt(t.get("Content-Length"),10);return!Number.isInteger(o)||(i.suggestedLength=o,o<=2*n)||r||!e||t.get("Accept-Ranges")!=="bytes"||(t.get("Content-Encoding")||"identity")!=="identity"||(i.allowRangeRequests=!0),i}function lU(t){let e=t.get("Content-Disposition");if(e){let n=LG(e);if(n.includes("%"))try{n=decodeURIComponent(n)}catch{}if(RR(n))return n}return null}function op(t,e){return new mu(`Unexpected server response (${t}) while retrieving PDF "${e}".`,t,t===404||t===0&&e.startsWith("file:"))}function cU(t){return t===200||t===206}function uU(t,e,n){return{method:"GET",headers:t,signal:n.signal,mode:"cors",credentials:e?"include":"same-origin",redirect:"follow"}}function dU(t){return t instanceof Uint8Array?t.buffer:t instanceof ArrayBuffer?t:(we(`getArrayBuffer - unexpected data format: ${t}`),new Uint8Array(t).buffer)}var Dk=class{_responseOrigin=null;constructor(e){this.source=e,this.isHttp=/^https?:/i.test(e.url),this.headers=aU(this.isHttp,e.httpHeaders),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return Ue(!this._fullRequestReader,"PDFFetchStream.getFullReader can only be called once."),this._fullRequestReader=new Lk(this),this._fullRequestReader}getRangeReader(e,n){if(n<=this._progressiveDataLength)return null;let r=new jk(this,e,n);return this._rangeRequestReaders.push(r),r}cancelAllRequests(e){this._fullRequestReader?.cancel(e);for(let n of this._rangeRequestReaders.slice(0))n.cancel(e)}},Lk=class{constructor(e){this._stream=e,this._reader=null,this._loaded=0,this._filename=null;let n=e.source;this._withCredentials=n.withCredentials||!1,this._contentLength=n.length,this._headersCapability=Promise.withResolvers(),this._disableRange=n.disableRange||!1,this._rangeChunkSize=n.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._abortController=new AbortController,this._isStreamingSupported=!n.disableStream,this._isRangeSupported=!n.disableRange;let r=new Headers(e.headers),i=n.url;fetch(i,uU(r,this._withCredentials,this._abortController)).then(o=>{if(e._responseOrigin=YS(o.url),!cU(o.status))throw op(o.status,i);this._reader=o.body.getReader(),this._headersCapability.resolve();let a=o.headers,{allowRangeRequests:s,suggestedLength:l}=sU({responseHeaders:a,isHttp:e.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=s,this._contentLength=l||this._contentLength,this._filename=lU(a),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new Or("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;let{value:e,done:n}=await this._reader.read();return n?{value:e,done:n}:(this._loaded+=e.byteLength,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:dU(e),done:!1})}cancel(e){this._reader?.cancel(e),this._abortController.abort()}},jk=class{constructor(e,n,r){this._stream=e,this._reader=null,this._loaded=0;let i=e.source;this._withCredentials=i.withCredentials||!1,this._readCapability=Promise.withResolvers(),this._isStreamingSupported=!i.disableStream,this._abortController=new AbortController;let o=new Headers(e.headers);o.append("Range",`bytes=${n}-${r-1}`);let a=i.url;fetch(a,uU(o,this._withCredentials,this._abortController)).then(s=>{let l=YS(s.url);if(l!==e._responseOrigin)throw new Error(`Expected range response-origin "${l}" to match "${e._responseOrigin}".`);if(!cU(s.status))throw op(s.status,a);this._readCapability.resolve(),this._reader=s.body.getReader()}).catch(this._readCapability.reject),this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;let{value:e,done:n}=await this._reader.read();return n?{value:e,done:n}:(this._loaded+=e.byteLength,this.onProgress?.({loaded:this._loaded}),{value:dU(e),done:!1})}cancel(e){this._reader?.cancel(e),this._abortController.abort()}},Kz=200,Yz=206;function jG(t){let e=t.response;return typeof e!="string"?e:np(e).buffer}var Uk=class{_responseOrigin=null;constructor({url:e,httpHeaders:n,withCredentials:r}){this.url=e,this.isHttp=/^https?:/i.test(e),this.headers=aU(this.isHttp,n),this.withCredentials=r||!1,this.currXhrId=0,this.pendingRequests=Object.create(null)}request(e){let n=new XMLHttpRequest,r=this.currXhrId++,i=this.pendingRequests[r]={xhr:n};n.open("GET",this.url),n.withCredentials=this.withCredentials;for(let[o,a]of this.headers)n.setRequestHeader(o,a);return this.isHttp&&"begin"in e&&"end"in e?(n.setRequestHeader("Range",`bytes=${e.begin}-${e.end-1}`),i.expectedStatus=Yz):i.expectedStatus=Kz,n.responseType="arraybuffer",Ue(e.onError,"Expected `onError` callback to be provided."),n.onerror=()=>{e.onError(n.status)},n.onreadystatechange=this.onStateChange.bind(this,r),n.onprogress=this.onProgress.bind(this,r),i.onHeadersReceived=e.onHeadersReceived,i.onDone=e.onDone,i.onError=e.onError,i.onProgress=e.onProgress,n.send(null),r}onProgress(e,n){let r=this.pendingRequests[e];r&&r.onProgress?.(n)}onStateChange(e,n){let r=this.pendingRequests[e];if(!r)return;let i=r.xhr;if(i.readyState>=2&&r.onHeadersReceived&&(r.onHeadersReceived(),delete r.onHeadersReceived),i.readyState!==4||!(e in this.pendingRequests))return;if(delete this.pendingRequests[e],i.status===0&&this.isHttp){r.onError(i.status);return}let o=i.status||Kz;if(!(o===Kz&&r.expectedStatus===Yz)&&o!==r.expectedStatus){r.onError(i.status);return}let s=jG(i);if(o===Yz){let l=i.getResponseHeader("Content-Range"),c=/bytes (\d+)-(\d+)\/(\d+)/.exec(l);c?r.onDone({begin:parseInt(c[1],10),chunk:s}):(we('Missing or invalid "Content-Range" header.'),r.onError(0))}else s?r.onDone({begin:0,chunk:s}):r.onError(i.status)}getRequestXhr(e){return this.pendingRequests[e].xhr}isPendingRequest(e){return e in this.pendingRequests}abortRequest(e){let n=this.pendingRequests[e].xhr;delete this.pendingRequests[e],n.abort()}},qk=class{constructor(e){this._source=e,this._manager=new Uk(e),this._rangeChunkSize=e.rangeChunkSize,this._fullRequestReader=null,this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(e){let n=this._rangeRequestReaders.indexOf(e);n>=0&&this._rangeRequestReaders.splice(n,1)}getFullReader(){return Ue(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new Fk(this._manager,this._source),this._fullRequestReader}getRangeReader(e,n){let r=new Bk(this._manager,e,n);return r.onClosed=this._onRangeRequestReaderClosed.bind(this),this._rangeRequestReaders.push(r),r}cancelAllRequests(e){this._fullRequestReader?.cancel(e);for(let n of this._rangeRequestReaders.slice(0))n.cancel(e)}},Fk=class{constructor(e,n){this._manager=e,this._url=n.url,this._fullRequestId=e.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=n.disableRange||!1,this._contentLength=n.length,this._rangeChunkSize=n.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(){let e=this._fullRequestId,n=this._manager.getRequestXhr(e);this._manager._responseOrigin=YS(n.responseURL);let r=n.getAllResponseHeaders(),i=new Headers(r?r.trimStart().replace(/[^\S ]+$/,"").split(/[\r\n]+/).map(s=>{let[l,...c]=s.split(": ");return[l,c.join(": ")]}):[]),{allowRangeRequests:o,suggestedLength:a}=sU({responseHeaders:i,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});o&&(this._isRangeSupported=!0),this._contentLength=a||this._contentLength,this._filename=lU(i),this._isRangeSupported&&this._manager.abortRequest(e),this._headersCapability.resolve()}_onDone(e){if(e&&(this._requests.length>0?this._requests.shift().resolve({value:e.chunk,done:!1}):this._cachedChunks.push(e.chunk)),this._done=!0,!(this._cachedChunks.length>0)){for(let n of this._requests)n.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(e){this._storedError=op(e,this._url),this._headersCapability.reject(this._storedError);for(let n of this._requests)n.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}_onProgress(e){this.onProgress?.({loaded:e.loaded,total:e.lengthComputable?e.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(){if(await this._headersCapability.promise,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};let e=Promise.withResolvers();return this._requests.push(e),e.promise}cancel(e){this._done=!0,this._headersCapability.reject(e);for(let n of this._requests)n.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId),this._fullRequestReader=null}},Bk=class{constructor(e,n,r){this._manager=e,this._url=e.url,this._requestId=e.request({begin:n,end:r,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(){let e=YS(this._manager.getRequestXhr(this._requestId)?.responseURL);e!==this._manager._responseOrigin&&(this._storedError=new Error(`Expected range response-origin "${e}" to match "${this._manager._responseOrigin}".`),this._onError(0))}_close(){this.onClosed?.(this)}_onDone(e){let n=e.chunk;this._requests.length>0?this._requests.shift().resolve({value:n,done:!1}):this._queuedChunk=n,this._done=!0;for(let r of this._requests)r.resolve({value:void 0,done:!0});this._requests.length=0,this._close()}_onError(e){this._storedError??=op(e,this._url);for(let n of this._requests)n.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}_onProgress(e){this.isStreamingSupported||this.onProgress?.({loaded:e.loaded})}get isStreamingSupported(){return!1}async read(){if(this._storedError)throw this._storedError;if(this._queuedChunk!==null){let n=this._queuedChunk;return this._queuedChunk=null,{value:n,done:!1}}if(this._done)return{value:void 0,done:!0};let e=Promise.withResolvers();return this._requests.push(e),e.promise}cancel(e){this._done=!0;for(let n of this._requests)n.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId),this._close()}},UG=/^[a-z][a-z0-9\-+.]+:/i;function qG(t){if(UG.test(t))return new URL(t);let e=process.getBuiltinModule("url");return new URL(e.pathToFileURL(t))}var Hk=class{constructor(e){this.source=e,this.url=qG(e.url),Ue(this.url.protocol==="file:","PDFNodeStream only supports file:// URLs."),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return Ue(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=new Vk(this),this._fullRequestReader}getRangeReader(e,n){if(n<=this._progressiveDataLength)return null;let r=new Zk(this,e,n);return this._rangeRequestReaders.push(r),r}cancelAllRequests(e){this._fullRequestReader?.cancel(e);for(let n of this._rangeRequestReaders.slice(0))n.cancel(e)}},Vk=class{constructor(e){this._url=e.url,this._done=!1,this._storedError=null,this.onProgress=null;let n=e.source;this._contentLength=n.length,this._loaded=0,this._filename=null,this._disableRange=n.disableRange||!1,this._rangeChunkSize=n.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._isStreamingSupported=!n.disableStream,this._isRangeSupported=!n.disableRange,this._readableStream=null,this._readCapability=Promise.withResolvers(),this._headersCapability=Promise.withResolvers();let r=process.getBuiltinModule("fs");r.promises.lstat(this._url).then(i=>{this._contentLength=i.size,this._setReadableStream(r.createReadStream(this._url)),this._headersCapability.resolve()},i=>{i.code==="ENOENT"&&(i=op(0,this._url.href)),this._storedError=i,this._headersCapability.reject(i)})}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(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;let e=this._readableStream.read();return e===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=e.length,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:new Uint8Array(e).buffer,done:!1})}cancel(e){if(!this._readableStream){this._error(e);return}this._readableStream.destroy(e)}_error(e){this._storedError=e,this._readCapability.resolve()}_setReadableStream(e){this._readableStream=e,e.on("readable",()=>{this._readCapability.resolve()}),e.on("end",()=>{e.destroy(),this._done=!0,this._readCapability.resolve()}),e.on("error",n=>{this._error(n)}),!this._isStreamingSupported&&this._isRangeSupported&&this._error(new Or("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}},Zk=class{constructor(e,n,r){this._url=e.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=Promise.withResolvers();let i=e.source;this._isStreamingSupported=!i.disableStream;let o=process.getBuiltinModule("fs");this._setReadableStream(o.createReadStream(this._url,{start:n,end:r-1}))}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;let e=this._readableStream.read();return e===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=e.length,this.onProgress?.({loaded:this._loaded}),{value:new Uint8Array(e).buffer,done:!1})}cancel(e){if(!this._readableStream){this._error(e);return}this._readableStream.destroy(e)}_error(e){this._storedError=e,this._readCapability.resolve()}_setReadableStream(e){this._readableStream=e,e.on("readable",()=>{this._readCapability.resolve()}),e.on("end",()=>{e.destroy(),this._done=!0,this._readCapability.resolve()}),e.on("error",n=>{this._error(n)}),this._storedError&&this._readableStream.destroy(this._storedError)}},Mm=Symbol("INITIAL_DATA"),zS=class{#e=Object.create(null);#t(e){return this.#e[e]||={...Promise.withResolvers(),data:Mm}}get(e,n=null){if(n){let i=this.#t(e);return i.promise.then(()=>n(i.data)),null}let r=this.#e[e];if(!r||r.data===Mm)throw new Error(`Requesting object that isn't resolved yet ${e}.`);return r.data}has(e){let n=this.#e[e];return!!n&&n.data!==Mm}delete(e){let n=this.#e[e];return!n||n.data===Mm?!1:(delete this.#e[e],!0)}resolve(e,n=null){let r=this.#t(e);r.data=n,r.resolve()}clear(){for(let e in this.#e){let{data:n}=this.#e[e];n?.bitmap?.close()}this.#e=Object.create(null)}*[Symbol.iterator](){for(let e in this.#e){let{data:n}=this.#e[e];n!==Mm&&(yield[e,n])}}},FG=1e5,Jj=30,Gs=class t{#e=Promise.withResolvers();#t=null;#i=!1;#n=!!globalThis.FontInspector?.enabled;#a=null;#r=null;#o=0;#s=0;#c=null;#l=null;#h=0;#d=0;#f=Object.create(null);#g=[];#m=null;#u=[];#p=new WeakMap;#v=null;static#y=new Map;static#b=new Map;static#A=new WeakMap;static#x=null;static#S=new Set;constructor({textContentSource:e,container:n,viewport:r}){if(e instanceof ReadableStream)this.#m=e;else if(typeof e=="object")this.#m=new ReadableStream({start(l){l.enqueue(e),l.close()}});else throw new Error('No "textContentSource" parameter specified.');this.#t=this.#l=n,this.#d=r.scale*xo.pixelRatio,this.#h=r.rotation,this.#r={div:null,properties:null,ctx:null};let{pageWidth:i,pageHeight:o,pageX:a,pageY:s}=r.rawDims;this.#v=[1,0,0,-1,-a,s+o],this.#s=i,this.#o=o,t.#k(),Hs(n,r),this.#e.promise.finally(()=>{t.#S.delete(this),this.#r=null,this.#f=null}).catch(()=>{})}static get fontFamilyMap(){let{isWindows:e,isFirefox:n}=Ft.platform;return Re(this,"fontFamilyMap",new Map([["sans-serif",`${e&&n?"Calibri, ":""}sans-serif`],["monospace",`${e&&n?"Lucida Console, ":""}monospace`]]))}render(){let e=()=>{this.#c.read().then(({value:n,done:r})=>{if(r){this.#e.resolve();return}this.#a??=n.lang,Object.assign(this.#f,n.styles),this.#T(n.items),e()},this.#e.reject)};return this.#c=this.#m.getReader(),t.#S.add(this),e(),this.#e.promise}update({viewport:e,onBefore:n=null}){let r=e.scale*xo.pixelRatio,i=e.rotation;if(i!==this.#h&&(n?.(),this.#h=i,Hs(this.#l,{rotation:i})),r!==this.#d){n?.(),this.#d=r;let o={div:null,properties:null,ctx:t.#R(this.#a)};for(let a of this.#u)o.properties=this.#p.get(a),o.div=a,this.#$(o)}}cancel(){let e=new Or("TextLayer task cancelled.");this.#c?.cancel(e).catch(()=>{}),this.#c=null,this.#e.reject(e)}get textDivs(){return this.#u}get textContentItemsStr(){return this.#g}#T(e){if(this.#i)return;this.#r.ctx??=t.#R(this.#a);let n=this.#u,r=this.#g;for(let i of e){if(n.length>FG){we("Ignoring additional textDivs for performance reasons."),this.#i=!0;return}if(i.str===void 0){if(i.type==="beginMarkedContentProps"||i.type==="beginMarkedContent"){let o=this.#t;this.#t=document.createElement("span"),this.#t.classList.add("markedContent"),i.id&&this.#t.setAttribute("id",`${i.id}`),o.append(this.#t)}else i.type==="endMarkedContent"&&(this.#t=this.#t.parentNode);continue}r.push(i.str),this.#w(i)}}#w(e){let n=document.createElement("span"),r={angle:0,canvasWidth:0,hasText:e.str!=="",hasEOL:e.hasEOL,fontSize:0};this.#u.push(n);let i=oe.transform(this.#v,e.transform),o=Math.atan2(i[1],i[0]),a=this.#f[e.fontName];a.vertical&&(o+=Math.PI/2);let s=this.#n&&a.fontSubstitution||a.fontFamily;s=t.fontFamilyMap.get(s)||s;let l=Math.hypot(i[2],i[3]),c=l*t.#D(s,a,this.#a),u,d;o===0?(u=i[4],d=i[5]-c):(u=i[4]+c*Math.sin(o),d=i[5]-c*Math.cos(o));let h="calc(var(--total-scale-factor) *",f=n.style;this.#t===this.#l?(f.left=`${(100*u/this.#s).toFixed(2)}%`,f.top=`${(100*d/this.#o).toFixed(2)}%`):(f.left=`${h}${u.toFixed(2)}px)`,f.top=`${h}${d.toFixed(2)}px)`),f.fontSize=`${h}${(t.#x*l).toFixed(2)}px)`,f.fontFamily=s,r.fontSize=l,n.setAttribute("role","presentation"),n.textContent=e.str,n.dir=e.dir,this.#n&&(n.dataset.fontName=a.fontSubstitutionLoadedName||e.fontName),o!==0&&(r.angle=o*(180/Math.PI));let m=!1;if(e.str.length>1)m=!0;else if(e.str!==" "&&e.transform[0]!==e.transform[3]){let p=Math.abs(e.transform[0]),y=Math.abs(e.transform[3]);p!==y&&Math.max(p,y)/Math.min(p,y)>1.5&&(m=!0)}if(m&&(r.canvasWidth=a.vertical?e.height:e.width),this.#p.set(n,r),this.#r.div=n,this.#r.properties=r,this.#$(this.#r),r.hasText&&this.#t.append(n),r.hasEOL){let p=document.createElement("br");p.setAttribute("role","presentation"),this.#t.append(p)}}#$(e){let{div:n,properties:r,ctx:i}=e,{style:o}=n,a="";if(t.#x>1&&(a=`scale(${1/t.#x})`),r.canvasWidth!==0&&r.hasText){let{fontFamily:s}=o,{canvasWidth:l,fontSize:c}=r;t.#z(i,c*this.#d,s);let{width:u}=i.measureText(n.textContent);u>0&&(a=`scaleX(${l*this.#d/u}) ${a}`)}r.angle!==0&&(a=`rotate(${r.angle}deg) ${a}`),a.length>0&&(o.transform=a)}static cleanup(){if(!(this.#S.size>0)){this.#y.clear();for(let{canvas:e}of this.#b.values())e.remove();this.#b.clear()}}static#R(e=null){let n=this.#b.get(e||="");if(!n){let r=document.createElement("canvas");r.className="hiddenCanvasElement",r.lang=e,document.body.append(r),n=r.getContext("2d",{alpha:!1,willReadFrequently:!0}),this.#b.set(e,n),this.#A.set(n,{size:0,family:""})}return n}static#z(e,n,r){let i=this.#A.get(e);n===i.size&&r===i.family||(e.font=`${n}px ${r}`,i.size=n,i.family=r)}static#k(){if(this.#x!==null)return;let e=document.createElement("div");e.style.opacity=0,e.style.lineHeight=1,e.style.fontSize="1px",e.style.position="absolute",e.textContent="X",document.body.append(e),this.#x=e.getBoundingClientRect().height,e.remove()}static#D(e,n,r){let i=this.#y.get(e);if(i)return i;let o=this.#R(r);o.canvas.width=o.canvas.height=Jj,this.#z(o,Jj,e);let a=o.measureText(""),s=a.fontBoundingBoxAscent,l=Math.abs(a.fontBoundingBoxDescent);o.canvas.width=o.canvas.height=0;let c=.8;return s?c=s/(s+l):(Ft.platform.isFirefox&&we("Enable the `dom.textMetrics.fontBoundingBox.enabled` preference in `about:config` to improve TextLayer rendering."),n.ascent?c=n.ascent:n.descent&&(c=1+n.descent)),this.#y.set(e,c),c}},BG=100;function IR(t={}){typeof t=="string"||t instanceof URL?t={url:t}:(t instanceof ArrayBuffer||ArrayBuffer.isView(t))&&(t={data:t});let e=new Gk,{docId:n}=e,r=t.url?EG(t.url):null,i=t.data?TG(t.data):null,o=t.httpHeaders||null,a=t.withCredentials===!0,s=t.password??null,l=t.range instanceof kS?t.range:null,c=Number.isInteger(t.rangeChunkSize)&&t.rangeChunkSize>0?t.rangeChunkSize:2**16,u=t.worker instanceof Ks?t.worker:null,d=t.verbosity,h=typeof t.docBaseUrl=="string"&&!KS(t.docBaseUrl)?t.docBaseUrl:null,f=Wy(t.cMapUrl),m=t.cMapPacked!==!1,p=t.CMapReaderFactory||(En?bk:bS),y=Wy(t.iccUrl),g=Wy(t.standardFontDataUrl),v=t.StandardFontDataFactory||(En?yk:_S),S=Wy(t.wasmUrl),_=t.WasmFactory||(En?Sk:xS),$=t.stopAtErrors!==!0,w=Number.isInteger(t.maxImageSize)&&t.maxImageSize>-1?t.maxImageSize:-1,A=t.isEvalSupported!==!1,k=typeof t.isOffscreenCanvasSupported=="boolean"?t.isOffscreenCanvasSupported:!En,I=typeof t.isImageDecoderSupported=="boolean"?t.isImageDecoderSupported:!En&&(Ft.platform.isFirefox||!globalThis.chrome),D=Number.isInteger(t.canvasMaxAreaInBytes)?t.canvasMaxAreaInBytes:-1,H=typeof t.disableFontFace=="boolean"?t.disableFontFace:En,ge=t.fontExtraProperties===!0,ce=t.enableXfa===!0,me=t.ownerDocument||globalThis.document,Te=t.disableRange===!0,ie=t.disableStream===!0,ne=t.disableAutoFetch===!0,Se=t.pdfBug===!0,nt=t.CanvasFactory||(En?vk:mk),j=t.FilterFactory||(En?gk:pk),N=t.enableHWA===!0,V=t.useWasm!==!1,q=l?l.length:t.length??NaN,G=typeof t.useSystemFonts=="boolean"?t.useSystemFonts:!En&&!H,Z=typeof t.useWorkerFetch=="boolean"?t.useWorkerFetch:!!(p===bS&&v===_S&&_===xS&&f&&g&&S&&jm(f,document.baseURI)&&jm(g,document.baseURI)&&jm(S,document.baseURI)),W=null;cG(d);let K={canvasFactory:new nt({ownerDocument:me,enableHWA:N}),filterFactory:new j({docId:n,ownerDocument:me}),cMapReaderFactory:Z?null:new p({baseUrl:f,isCompressed:m}),standardFontDataFactory:Z?null:new v({baseUrl:g}),wasmFactory:Z?null:new _({baseUrl:S})};u||(u=Ks.create({verbosity:d,port:Bs.workerPort}),e._worker=u);let he={docId:n,apiVersion:"5.4.296",data:i,password:s,disableAutoFetch:ne,rangeChunkSize:c,length:q,docBaseUrl:h,enableXfa:ce,evaluatorOptions:{maxImageSize:w,disableFontFace:H,ignoreErrors:$,isEvalSupported:A,isOffscreenCanvasSupported:k,isImageDecoderSupported:I,canvasMaxAreaInBytes:D,fontExtraProperties:ge,useSystemFonts:G,useWasm:V,useWorkerFetch:Z,cMapUrl:f,iccUrl:y,standardFontDataUrl:g,wasmUrl:S}},ze={ownerDocument:me,pdfBug:Se,styleElement:W,loadingParams:{disableAutoFetch:ne,enableXfa:ce}};return u.promise.then(function(){if(e.destroyed)throw new Error("Loading aborted");if(u.destroyed)throw new Error("Worker was destroyed");let st=u.messageHandler.sendWithPromise("GetDocRequest",he,i?[i.buffer]:null),qe;if(l)qe=new Pk(l,{disableRange:Te,disableStream:ie});else if(!i){if(!r)throw new Error("getDocument - no `url` parameter provided.");let He=jm(r)?Dk:En?Hk:qk;qe=new He({url:r,length:q,httpHeaders:o,withCredentials:a,rangeChunkSize:c,disableRange:Te,disableStream:ie})}return st.then(He=>{if(e.destroyed)throw new Error("Loading aborted");if(u.destroyed)throw new Error("Worker was destroyed");let Bt=new Fs(n,He,u.port),zn=new Xk(Bt,e,qe,ze,K,N);e._transport=zn,Bt.send("Ready",null)})}).catch(e._capability.reject),e}var Gk=class t{static#e=0;_capability=Promise.withResolvers();_transport=null;_worker=null;docId=`d${t.#e++}`;destroyed=!1;onPassword=null;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(e){throw this._worker?.port&&delete this._worker._pendingDestroy,e}this._transport=null,this._worker?.destroy(),this._worker=null}async getData(){return this._transport.getData()}},kS=class{#e=Promise.withResolvers();#t=[];#i=[];#n=[];#a=[];constructor(e,n,r=!1,i=null){this.length=e,this.initialData=n,this.progressiveDone=r,this.contentDispositionFilename=i}addRangeListener(e){this.#a.push(e)}addProgressListener(e){this.#n.push(e)}addProgressiveReadListener(e){this.#i.push(e)}addProgressiveDoneListener(e){this.#t.push(e)}onDataRange(e,n){for(let r of this.#a)r(e,n)}onDataProgress(e,n){this.#e.promise.then(()=>{for(let r of this.#n)r(e,n)})}onDataProgressiveRead(e){this.#e.promise.then(()=>{for(let n of this.#i)n(e)})}onDataProgressiveDone(){this.#e.promise.then(()=>{for(let e of this.#t)e()})}transportReady(){this.#e.resolve()}requestDataRange(e,n){rt("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}},Kk=class{constructor(e,n){this._pdfInfo=e,this._transport=n}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 Re(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(e){return this._transport.getPage(e)}getPageIndex(e){return this._transport.getPageIndex(e)}getDestinations(){return this._transport.getDestinations()}getDestination(e){return this._transport.getDestination(e)}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()}getAnnotationsByType(e,n){return this._transport.getAnnotationsByType(e,n)}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:e="display"}={}){let{renderingIntent:n}=this._transport.getRenderingIntent(e);return this._transport.getOptionalContentConfig(n)}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(e=!1){return this._transport.startCleanup(e||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}cachedPageNumber(e){return this._transport.cachedPageNumber(e)}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()}},Yk=class{#e=!1;constructor(e,n,r,i=!1){this._pageIndex=e,this._pageInfo=n,this._transport=r,this._stats=i?new dS:null,this._pdfBug=i,this.commonObjs=r.commonObjs,this.objs=new zS,this._intentStates=new Map,this.destroyed=!1,this.recordedBBoxes=null}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:e,rotation:n=this.rotate,offsetX:r=0,offsetY:i=0,dontFlip:o=!1}={}){return new Vm({viewBox:this.view,userUnit:this.userUnit,scale:e,rotation:n,offsetX:r,offsetY:i,dontFlip:o})}getAnnotations({intent:e="display"}={}){let{renderingIntent:n}=this._transport.getRenderingIntent(e);return this._transport.getAnnotations(this._pageIndex,n)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return Re(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:e,canvas:n=e.canvas,viewport:r,intent:i="display",annotationMode:o=Aa.ENABLE,transform:a=null,background:s=null,optionalContentConfigPromise:l=null,annotationCanvasMap:c=null,pageColors:u=null,printAnnotationStorage:d=null,isEditing:h=!1,recordOperations:f=!1,operationsFilter:m=null}){this._stats?.time("Overall");let p=this._transport.getRenderingIntent(i,o,d,h),{renderingIntent:y,cacheKey:g}=p;this.#e=!1,l||=this._transport.getOptionalContentConfig(y);let v=this._intentStates.get(g);v||(v=Object.create(null),this._intentStates.set(g,v)),v.streamReaderCancelTimeout&&(clearTimeout(v.streamReaderCancelTimeout),v.streamReaderCancelTimeout=null);let S=!!(y&di.PRINT);v.displayReadyCapability||(v.displayReadyCapability=Promise.withResolvers(),v.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(p));let _=!!(this._pdfBug&&globalThis.StepperManager?.enabled),$=!this.recordedBBoxes&&(f||_),w=I=>{if(v.renderTasks.delete(A),$){let D=A.gfx?.dependencyTracker.take();D&&(A.stepper&&A.stepper.setOperatorBBoxes(D,A.gfx.dependencyTracker.takeDebugMetadata()),f&&(this.recordedBBoxes=D))}S&&(this.#e=!0),this.#t(),I?(A.capability.reject(I),this._abortOperatorList({intentState:v,reason:I instanceof Error?I:new Error(I)})):A.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},A=new Wk({callback:w,params:{canvas:n,canvasContext:e,dependencyTracker:$?new xk(n,v.operatorList.length,_):null,viewport:r,transform:a,background:s},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:c,operatorList:v.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!S,pdfBug:this._pdfBug,pageColors:u,enableHWA:this._transport.enableHWA,operationsFilter:m});(v.renderTasks||=new Set).add(A);let k=A.task;return Promise.all([v.displayReadyCapability.promise,l]).then(([I,D])=>{if(this.destroyed){w();return}if(this._stats?.time("Rendering"),!(D.renderingIntent&y))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");A.initializeGraphics({transparency:I,optionalContentConfig:D}),A.operatorListChanged()}).catch(w),k}getOperatorList({intent:e="display",annotationMode:n=Aa.ENABLE,printAnnotationStorage:r=null,isEditing:i=!1}={}){function o(){s.operatorList.lastChunk&&(s.opListReadCapability.resolve(s.operatorList),s.renderTasks.delete(l))}let a=this._transport.getRenderingIntent(e,n,r,i,!0),s=this._intentStates.get(a.cacheKey);s||(s=Object.create(null),this._intentStates.set(a.cacheKey,s));let l;return s.opListReadCapability||(l=Object.create(null),l.operatorListChanged=o,s.opListReadCapability=Promise.withResolvers(),(s.renderTasks||=new Set).add(l),s.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(a)),s.opListReadCapability.promise}streamTextContent({includeMarkedContent:e=!1,disableNormalization:n=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,includeMarkedContent:e===!0,disableNormalization:n===!0},{highWaterMark:100,size(i){return i.items.length}})}getTextContent(e={}){if(this._transport._htmlForXfa)return this.getXfa().then(r=>Hm.textContent(r));let n=this.streamTextContent(e);return new Promise(function(r,i){function o(){a.read().then(function({value:l,done:c}){if(c){r(s);return}s.lang??=l.lang,Object.assign(s.styles,l.styles),s.items.push(...l.items),o()},i)}let a=n.getReader(),s={items:[],styles:Object.create(null),lang:null};o()})}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;let e=[];for(let n of this._intentStates.values())if(this._abortOperatorList({intentState:n,reason:new Error("Page was destroyed."),force:!0}),!n.opListReadCapability)for(let r of n.renderTasks)e.push(r.completed),r.cancel();return this.objs.clear(),this.#e=!1,Promise.all(e)}cleanup(e=!1){this.#e=!0;let n=this.#t();return e&&n&&(this._stats&&=new dS),n}#t(){if(!this.#e||this.destroyed)return!1;for(let{renderTasks:e,operatorList:n}of this._intentStates.values())if(e.size>0||!n.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),this.#e=!1,!0}_startRenderPage(e,n){let r=this._intentStates.get(n);r&&(this._stats?.timeEnd("Page Request"),r.displayReadyCapability?.resolve(e))}_renderPageChunk(e,n){for(let r=0,i=e.length;r<i;r++)n.operatorList.fnArray.push(e.fnArray[r]),n.operatorList.argsArray.push(e.argsArray[r]);n.operatorList.lastChunk=e.lastChunk,n.operatorList.separateAnnots=e.separateAnnots;for(let r of n.renderTasks)r.operatorListChanged();e.lastChunk&&this.#t()}_pumpOperatorList({renderingIntent:e,cacheKey:n,annotationStorageSerializable:r,modifiedIds:i}){let{map:o,transfer:a}=r,l=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageIndex:this._pageIndex,intent:e,cacheKey:n,annotationStorage:o,modifiedIds:i},a).getReader(),c=this._intentStates.get(n);c.streamReader=l;let u=()=>{l.read().then(({value:d,done:h})=>{if(h){c.streamReader=null;return}this._transport.destroyed||(this._renderPageChunk(d,c),u())},d=>{if(c.streamReader=null,!this._transport.destroyed){if(c.operatorList){c.operatorList.lastChunk=!0;for(let h of c.renderTasks)h.operatorListChanged();this.#t()}if(c.displayReadyCapability)c.displayReadyCapability.reject(d);else if(c.opListReadCapability)c.opListReadCapability.reject(d);else throw d}})};u()}_abortOperatorList({intentState:e,reason:n,force:r=!1}){if(e.streamReader){if(e.streamReaderCancelTimeout&&(clearTimeout(e.streamReaderCancelTimeout),e.streamReaderCancelTimeout=null),!r){if(e.renderTasks.size>0)return;if(n instanceof Zm){let i=BG;n.extraDelay>0&&n.extraDelay<1e3&&(i+=n.extraDelay),e.streamReaderCancelTimeout=setTimeout(()=>{e.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:e,reason:n,force:!0})},i);return}}if(e.streamReader.cancel(new Or(n.message)).catch(()=>{}),e.streamReader=null,!this._transport.destroyed){for(let[i,o]of this._intentStates)if(o===e){this._intentStates.delete(i);break}this.cleanup()}}}get stats(){return this._stats}},Ks=class t{#e=Promise.withResolvers();#t=null;#i=null;#n=null;static#a=0;static#r=!1;static#o=new WeakMap;static{En&&(this.#r=!0,Bs.workerSrc||="./pdf.worker.mjs"),this._isSameOrigin=(e,n)=>{let r=URL.parse(e);if(!r?.origin||r.origin==="null")return!1;let i=new URL(n,r);return r.origin===i.origin},this._createCDNWrapper=e=>{let n=`await import("${e}");`;return URL.createObjectURL(new Blob([n],{type:"text/javascript"}))},this.fromPort=e=>{if(_G("`PDFWorker.fromPort` - please use `PDFWorker.create` instead."),!e?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");return this.create(e)}}constructor({name:e=null,port:n=null,verbosity:r=uG()}={}){if(this.name=e,this.destroyed=!1,this.verbosity=r,n){if(t.#o.has(n))throw new Error("Cannot use more than one PDFWorker per port.");t.#o.set(n,this),this.#c(n)}else this.#l()}get promise(){return this.#e.promise}#s(){this.#e.resolve(),this.#t.send("configure",{verbosity:this.verbosity})}get port(){return this.#i}get messageHandler(){return this.#t}#c(e){this.#i=e,this.#t=new Fs("main","worker",e),this.#t.on("ready",()=>{}),this.#s()}#l(){if(t.#r||t.#d){this.#h();return}let{workerSrc:e}=t;try{t._isSameOrigin(window.location,e)||(e=t._createCDNWrapper(new URL(e,window.location).href));let n=new Worker(e,{type:"module"}),r=new Fs("main","worker",n),i=()=>{o.abort(),r.destroy(),n.terminate(),this.destroyed?this.#e.reject(new Error("Worker was destroyed")):this.#h()},o=new AbortController;n.addEventListener("error",()=>{this.#n||i()},{signal:o.signal}),r.on("test",s=>{if(o.abort(),this.destroyed||!s){i();return}this.#t=r,this.#i=n,this.#n=n,this.#s()}),r.on("ready",s=>{if(o.abort(),this.destroyed){i();return}try{a()}catch{this.#h()}});let a=()=>{let s=new Uint8Array;r.send("test",s,[s.buffer])};a();return}catch{GS("The worker has been disabled.")}this.#h()}#h(){t.#r||(we("Setting up fake worker."),t.#r=!0),t._setupFakeWorkerGlobal.then(e=>{if(this.destroyed){this.#e.reject(new Error("Worker was destroyed"));return}let n=new fk;this.#i=n;let r=`fake${t.#a++}`,i=new Fs(r+"_worker",r,n);e.setup(i,n),this.#t=new Fs(r,r+"_worker",n),this.#s()}).catch(e=>{this.#e.reject(new Error(`Setting up fake worker failed: "${e.message}".`))})}destroy(){this.destroyed=!0,this.#n?.terminate(),this.#n=null,t.#o.delete(this.#i),this.#i=null,this.#t?.destroy(),this.#t=null}static create(e){let n=this.#o.get(e?.port);if(n){if(n._pendingDestroy)throw new Error("PDFWorker.create - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return n}return new t(e)}static get workerSrc(){if(Bs.workerSrc)return Bs.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get#d(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return Re(this,"_setupFakeWorkerGlobal",(async()=>this.#d?this.#d:(await import(this.workerSrc)).WorkerMessageHandler)())}},Xk=class{#e=new Map;#t=new Map;#i=new Map;#n=new Map;#a=null;constructor(e,n,r,i,o,a){this.messageHandler=e,this.loadingTask=n,this.commonObjs=new zS,this.fontLoader=new uk({ownerDocument:i.ownerDocument,styleElement:i.styleElement}),this.loadingParams=i.loadingParams,this._params=i,this.canvasFactory=o.canvasFactory,this.filterFactory=o.filterFactory,this.cMapReaderFactory=o.cMapReaderFactory,this.standardFontDataFactory=o.standardFontDataFactory,this.wasmFactory=o.wasmFactory,this.destroyed=!1,this.destroyCapability=null,this._networkStream=r,this._fullReader=null,this._lastProgress=null,this.downloadInfoCapability=Promise.withResolvers(),this.enableHWA=a,this.setupMessageHandler()}#r(e,n=null){let r=this.#e.get(e);if(r)return r;let i=this.messageHandler.sendWithPromise(e,n);return this.#e.set(e,i),i}get annotationStorage(){return Re(this,"annotationStorage",new Km)}getRenderingIntent(e,n=Aa.ENABLE,r=null,i=!1,o=!1){let a=di.DISPLAY,s=ck;switch(e){case"any":a=di.ANY;break;case"display":break;case"print":a=di.PRINT;break;default:we(`getRenderingIntent - invalid intent: ${e}`)}let l=a&di.PRINT&&r instanceof pS?r:this.annotationStorage;switch(n){case Aa.DISABLE:a+=di.ANNOTATIONS_DISABLE;break;case Aa.ENABLE:break;case Aa.ENABLE_FORMS:a+=di.ANNOTATIONS_FORMS;break;case Aa.ENABLE_STORAGE:a+=di.ANNOTATIONS_STORAGE,s=l.serializable;break;default:we(`getRenderingIntent - invalid annotationMode: ${n}`)}i&&(a+=di.IS_EDITING),o&&(a+=di.OPLIST);let{ids:c,hash:u}=l.modifiedIds,d=[a,s.hash,u];return{renderingIntent:a,cacheKey:d.join("_"),annotationStorageSerializable:s,modifiedIds:c}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),this.#a?.reject(new Error("Worker was destroyed during onPassword callback"));let e=[];for(let r of this.#t.values())e.push(r._destroy());this.#t.clear(),this.#i.clear(),this.#n.clear(),this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();let n=this.messageHandler.sendWithPromise("Terminate",null);return e.push(n),Promise.all(e).then(()=>{this.commonObjs.clear(),this.fontLoader.clear(),this.#e.clear(),this.filterFactory.destroy(),Gs.cleanup(),this._networkStream?.cancelAllRequests(new Or("Worker was terminated.")),this.messageHandler?.destroy(),this.messageHandler=null,this.destroyCapability.resolve()},this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){let{messageHandler:e,loadingTask:n}=this;e.on("GetReader",(r,i)=>{Ue(this._networkStream,"GetReader - no `IPDFStream` instance available."),this._fullReader=this._networkStream.getFullReader(),this._fullReader.onProgress=o=>{this._lastProgress={loaded:o.loaded,total:o.total}},i.onPull=()=>{this._fullReader.read().then(function({value:o,done:a}){if(a){i.close();return}Ue(o instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),i.enqueue(new Uint8Array(o),1,[o])}).catch(o=>{i.error(o)})},i.onCancel=o=>{this._fullReader.cancel(o),i.ready.catch(a=>{if(!this.destroyed)throw a})}}),e.on("ReaderHeadersReady",async r=>{await this._fullReader.headersReady;let{isStreamingSupported:i,isRangeSupported:o,contentLength:a}=this._fullReader;return(!i||!o)&&(this._lastProgress&&n.onProgress?.(this._lastProgress),this._fullReader.onProgress=s=>{n.onProgress?.({loaded:s.loaded,total:s.total})}),{isStreamingSupported:i,isRangeSupported:o,contentLength:a}}),e.on("GetRangeReader",(r,i)=>{Ue(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");let o=this._networkStream.getRangeReader(r.begin,r.end);if(!o){i.close();return}i.onPull=()=>{o.read().then(function({value:a,done:s}){if(s){i.close();return}Ue(a instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),i.enqueue(new Uint8Array(a),1,[a])}).catch(a=>{i.error(a)})},i.onCancel=a=>{o.cancel(a),i.ready.catch(s=>{if(!this.destroyed)throw s})}}),e.on("GetDoc",({pdfInfo:r})=>{this._numPages=r.numPages,this._htmlForXfa=r.htmlForXfa,delete r.htmlForXfa,n._capability.resolve(new Kk(r,this))}),e.on("DocException",r=>{n._capability.reject(Zn(r))}),e.on("PasswordRequest",r=>{this.#a=Promise.withResolvers();try{if(!n.onPassword)throw Zn(r);let i=o=>{o instanceof Error?this.#a.reject(o):this.#a.resolve({password:o})};n.onPassword(i,r.code)}catch(i){this.#a.reject(i)}return this.#a.promise}),e.on("DataLoaded",r=>{n.onProgress?.({loaded:r.length,total:r.length}),this.downloadInfoCapability.resolve(r)}),e.on("StartRenderPage",r=>{if(this.destroyed)return;this.#t.get(r.pageIndex)._startRenderPage(r.transparency,r.cacheKey)}),e.on("commonobj",([r,i,o])=>{if(this.destroyed||this.commonObjs.has(r))return null;switch(i){case"Font":if("error"in o){let u=o.error;we(`Error during font loading: ${u}`),this.commonObjs.resolve(r,u);break}let a=new Rk(o),s=this._params.pdfBug&&globalThis.FontInspector?.enabled?(u,d)=>globalThis.FontInspector.fontAdded(u,d):null,l=new dk(a,s,o.extra,o.charProcOperatorList);this.fontLoader.bind(l).catch(()=>e.sendWithPromise("FontFallback",{id:r})).finally(()=>{!l.fontExtraProperties&&l.data&&l.clearData(),this.commonObjs.resolve(r,l)});break;case"CopyLocalImage":let{imageRef:c}=o;Ue(c,"The imageRef must be defined.");for(let u of this.#t.values())for(let[,d]of u.objs)if(d?.ref===c)return d.dataLen?(this.commonObjs.resolve(r,structuredClone(d)),d.dataLen):null;break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(r,o);break;default:throw new Error(`Got unknown common object type ${i}`)}return null}),e.on("obj",([r,i,o,a])=>{if(this.destroyed)return;let s=this.#t.get(i);if(!s.objs.has(r)){if(s._intentStates.size===0){a?.bitmap?.close();return}switch(o){case"Image":case"Pattern":s.objs.resolve(r,a);break;default:throw new Error(`Got unknown object type ${o}`)}}}),e.on("DocProgress",r=>{this.destroyed||n.onProgress?.({loaded:r.loaded,total:r.total})}),e.on("FetchBinaryData",async r=>{if(this.destroyed)throw new Error("Worker was destroyed.");let i=this[r.type];if(!i)throw new Error(`${r.type} not initialized, see the \`useWorkerFetch\` parameter.`);return i.fetch(r)})}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&we("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");let{map:e,transfer:n}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:e,filename:this._fullReader?.filename??null},n).finally(()=>{this.annotationStorage.resetModified()})}getPage(e){if(!Number.isInteger(e)||e<=0||e>this._numPages)return Promise.reject(new Error("Invalid page request."));let n=e-1,r=this.#i.get(n);if(r)return r;let i=this.messageHandler.sendWithPromise("GetPage",{pageIndex:n}).then(o=>{if(this.destroyed)throw new Error("Transport destroyed");o.refStr&&this.#n.set(o.refStr,e);let a=new Yk(n,o,this,this._params.pdfBug);return this.#t.set(n,a),a});return this.#i.set(n,i),i}getPageIndex(e){return hk(e)?this.messageHandler.sendWithPromise("GetPageIndex",{num:e.num,gen:e.gen}):Promise.reject(new Error("Invalid pageIndex request."))}getAnnotations(e,n){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:e,intent:n})}getFieldObjects(){return this.#r("GetFieldObjects")}hasJSActions(){return this.#r("HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(e){return typeof e!="string"?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:e})}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)}getAnnotationsByType(e,n){return this.messageHandler.sendWithPromise("GetAnnotationsByType",{types:e,pageIndexesToSkip:n})}getDocJSActions(){return this.#r("GetDocJSActions")}getPageJSActions(e){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:e})}getStructTree(e){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:e})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(e){return this.#r("GetOptionalContentConfig").then(n=>new Ok(n,e))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){let e="GetMetadata",n=this.#e.get(e);if(n)return n;let r=this.messageHandler.sendWithPromise(e,null).then(i=>({info:i[0],metadata:i[1]?new Ck(i[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null}));return this.#e.set(e,r),r}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(e=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(let n of this.#t.values())if(!n.cleanup())throw new Error(`startCleanup: Page ${n.pageNumber} is currently rendering.`);this.commonObjs.clear(),e||this.fontLoader.clear(),this.#e.clear(),this.filterFactory.destroy(!0),Gs.cleanup()}}cachedPageNumber(e){if(!hk(e))return null;let n=e.gen===0?`${e.num}R`:`${e.num}R${e.gen}`;return this.#n.get(n)??null}},Jk=class{#e=null;onContinue=null;onError=null;constructor(e){this.#e=e}get promise(){return this.#e.capability.promise}cancel(e=0){this.#e.cancel(null,e)}get separateAnnots(){let{separateAnnots:e}=this.#e.operatorList;if(!e)return!1;let{annotationCanvasMap:n}=this.#e;return e.form||e.canvas&&n?.size>0}},Wk=class t{#e=null;static#t=new WeakSet;constructor({callback:e,params:n,objs:r,commonObjs:i,annotationCanvasMap:o,operatorList:a,pageIndex:s,canvasFactory:l,filterFactory:c,useRequestAnimationFrame:u=!1,pdfBug:d=!1,pageColors:h=null,enableHWA:f=!1,operationsFilter:m=null}){this.callback=e,this.params=n,this.objs=r,this.commonObjs=i,this.annotationCanvasMap=o,this.operatorListIdx=null,this.operatorList=a,this._pageIndex=s,this.canvasFactory=l,this.filterFactory=c,this._pdfBug=d,this.pageColors=h,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=u===!0&&typeof window<"u",this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new Jk(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=n.canvas,this._canvasContext=n.canvas?null:n.canvasContext,this._enableHWA=f,this._dependencyTracker=n.dependencyTracker,this._operationsFilter=m}get completed(){return this.capability.promise.catch(function(){})}initializeGraphics({transparency:e=!1,optionalContentConfig:n}){if(this.cancelled)return;if(this._canvas){if(t.#t.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.");t.#t.add(this._canvas)}this._pdfBug&&globalThis.StepperManager?.enabled&&(this.stepper=globalThis.StepperManager.create(this._pageIndex),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());let{viewport:r,transform:i,background:o,dependencyTracker:a}=this.params,s=this._canvasContext||this._canvas.getContext("2d",{alpha:!1,willReadFrequently:!this._enableHWA});this.gfx=new fu(s,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:n},this.annotationCanvasMap,this.pageColors,a),this.gfx.beginDrawing({transform:i,viewport:r,transparency:e,background:o}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback?.()}cancel(e=null,n=0){this.running=!1,this.cancelled=!0,this.gfx?.endDrawing(),this.#e&&(window.cancelAnimationFrame(this.#e),this.#e=null),t.#t.delete(this._canvas),e||=new Zm(`Rendering cancelled, page ${this._pageIndex+1}`,n),this.callback(e),this.task.onError?.(e)}operatorListChanged(){if(!this.graphicsReady){this.graphicsReadyCallback||=this._continueBound;return}this.gfx.dependencyTracker?.growOperationsCount(this.operatorList.fnArray.length),this.stepper?.updateOperatorList(this.operatorList),!this.running&&this._continue()}_continue(){this.running=!0,!this.cancelled&&(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?this.#e=window.requestAnimationFrame(()=>{this.#e=null,this._nextBound().catch(this._cancelBound)}):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper,this._operationsFilter),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),t.#t.delete(this._canvas),this.callback())))}},HG="5.4.296",VG="f56dc8601",RS=class t{#e=null;#t=null;#i;#n=null;#a=!1;#r=!1;#o=null;#s;#c=null;#l=null;static#h=null;static get _keyboardManager(){return Re(this,"_keyboardManager",new Vs([[["Escape","mac+Escape"],t.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],t.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],t.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],t.prototype._moveToPrevious],[["Home","mac+Home"],t.prototype._moveToBeginning],[["End","mac+End"],t.prototype._moveToEnd]]))}constructor({editor:e=null,uiManager:n=null}){e?(this.#r=!1,this.#o=e):this.#r=!0,this.#l=e?._uiManager||n,this.#s=this.#l._eventBus,this.#i=e?.color?.toUpperCase()||this.#l?.highlightColors.values().next().value||"#FFFF98",t.#h||=Object.freeze({blue:"pdfjs-editor-colorpicker-blue",green:"pdfjs-editor-colorpicker-green",pink:"pdfjs-editor-colorpicker-pink",red:"pdfjs-editor-colorpicker-red",yellow:"pdfjs-editor-colorpicker-yellow"})}renderButton(){let e=this.#e=document.createElement("button");e.className="colorPicker",e.tabIndex="0",e.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-button"),e.ariaHasPopup="true",this.#o&&(e.ariaControls=`${this.#o.id}_colorpicker_dropdown`);let n=this.#l._signal;e.addEventListener("click",this.#m.bind(this),{signal:n}),e.addEventListener("keydown",this.#g.bind(this),{signal:n});let r=this.#t=document.createElement("span");return r.className="swatch",r.ariaHidden="true",r.style.backgroundColor=this.#i,e.append(r),e}renderMainDropdown(){let e=this.#n=this.#d();return e.ariaOrientation="horizontal",e.ariaLabelledBy="highlightColorPickerLabel",e}#d(){let e=document.createElement("div"),n=this.#l._signal;e.addEventListener("contextmenu",Ni,{signal:n}),e.className="dropdown",e.role="listbox",e.ariaMultiSelectable="false",e.ariaOrientation="vertical",e.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-dropdown"),this.#o&&(e.id=`${this.#o.id}_colorpicker_dropdown`);for(let[r,i]of this.#l.highlightColors){let o=document.createElement("button");o.tabIndex="0",o.role="option",o.setAttribute("data-color",i),o.title=r,o.setAttribute("data-l10n-id",t.#h[r]);let a=document.createElement("span");o.append(a),a.className="swatch",a.style.backgroundColor=i,o.ariaSelected=i===this.#i,o.addEventListener("click",this.#f.bind(this,i),{signal:n}),e.append(o)}return e.addEventListener("keydown",this.#g.bind(this),{signal:n}),e}#f(e,n){n.stopPropagation(),this.#s.dispatch("switchannotationeditorparams",{source:this,type:je.HIGHLIGHT_COLOR,value:e}),this.updateColor(e)}_colorSelectFromKeyboard(e){if(e.target===this.#e){this.#m(e);return}let n=e.target.getAttribute("data-color");n&&this.#f(n,e)}_moveToNext(e){if(!this.#p){this.#m(e);return}if(e.target===this.#e){this.#n.firstChild?.focus();return}e.target.nextSibling?.focus()}_moveToPrevious(e){if(e.target===this.#n?.firstChild||e.target===this.#e){this.#p&&this._hideDropdownFromKeyboard();return}this.#p||this.#m(e),e.target.previousSibling?.focus()}_moveToBeginning(e){if(!this.#p){this.#m(e);return}this.#n.firstChild?.focus()}_moveToEnd(e){if(!this.#p){this.#m(e);return}this.#n.lastChild?.focus()}#g(e){t._keyboardManager.exec(this,e)}#m(e){if(this.#p){this.hideDropdown();return}if(this.#a=e.detail===0,this.#c||(this.#c=new AbortController,window.addEventListener("pointerdown",this.#u.bind(this),{signal:this.#l.combinedSignal(this.#c)})),this.#e.ariaExpanded="true",this.#n){this.#n.classList.remove("hidden");return}let n=this.#n=this.#d();this.#e.append(n)}#u(e){this.#n?.contains(e.target)||this.hideDropdown()}hideDropdown(){this.#n?.classList.add("hidden"),this.#e.ariaExpanded="false",this.#c?.abort(),this.#c=null}get#p(){return this.#n&&!this.#n.classList.contains("hidden")}_hideDropdownFromKeyboard(){if(!this.#r){if(!this.#p){this.#o?.unselect();return}this.hideDropdown(),this.#e.focus({preventScroll:!0,focusVisible:this.#a})}}updateColor(e){if(this.#t&&(this.#t.style.backgroundColor=e),!this.#n)return;let n=this.#l.highlightColors.values();for(let r of this.#n.children)r.ariaSelected=n.next().value===e.toUpperCase()}destroy(){this.#e?.remove(),this.#e=null,this.#t=null,this.#n?.remove(),this.#n=null}},CS=class t{#e=null;#t=null;#i=null;static#n=null;constructor(e){this.#t=e,this.#i=e._uiManager,t.#n||=Object.freeze({freetext:"pdfjs-editor-color-picker-free-text-input",ink:"pdfjs-editor-color-picker-ink-input"})}renderButton(){if(this.#e)return this.#e;let{editorType:e,colorType:n,colorValue:r}=this.#t,i=this.#e=document.createElement("input");return i.type="color",i.value=r||"#000000",i.className="basicColorPicker",i.tabIndex=0,i.setAttribute("data-l10n-id",t.#n[e]),i.addEventListener("input",()=>{this.#i.updateParams(n,i.value)},{signal:this.#i._signal}),i}update(e){this.#e&&(this.#e.value=e)}destroy(){this.#e?.remove(),this.#e=null}hideDropdown(){}};function Wj(t){return Math.floor(Math.max(0,Math.min(1,t))*255).toString(16).padStart(2,"0")}function Dm(t){return Math.max(0,Math.min(255,255*t))}var IS=class{static CMYK_G([e,n,r,i]){return["G",1-Math.min(1,.3*e+.59*r+.11*n+i)]}static G_CMYK([e]){return["CMYK",0,0,0,1-e]}static G_RGB([e]){return["RGB",e,e,e]}static G_rgb([e]){return e=Dm(e),[e,e,e]}static G_HTML([e]){let n=Wj(e);return`#${n}${n}${n}`}static RGB_G([e,n,r]){return["G",.3*e+.59*n+.11*r]}static RGB_rgb(e){return e.map(Dm)}static RGB_HTML(e){return`#${e.map(Wj).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([e,n,r,i]){return["RGB",1-Math.min(1,e+i),1-Math.min(1,r+i),1-Math.min(1,n+i)]}static CMYK_rgb([e,n,r,i]){return[Dm(1-Math.min(1,e+i)),Dm(1-Math.min(1,r+i)),Dm(1-Math.min(1,n+i))]}static CMYK_HTML(e){let n=this.CMYK_RGB(e).slice(1);return this.RGB_HTML(n)}static RGB_CMYK([e,n,r]){let i=1-e,o=1-n,a=1-r,s=Math.min(i,o,a);return["CMYK",i,o,a,s]}};var Qk=class{create(e,n,r=!1){if(e<=0||n<=0)throw new Error("Invalid SVG dimensions");let i=this._createSVG("svg:svg");return i.setAttribute("version","1.1"),r||(i.setAttribute("width",`${e}px`),i.setAttribute("height",`${n}px`)),i.setAttribute("preserveAspectRatio","none"),i.setAttribute("viewBox",`0 0 ${e} ${n}`),i}createElement(e){if(typeof e!="string")throw new Error("Invalid SVG element type");return this._createSVG(e)}_createSVG(e){rt("Abstract method `_createSVG` called.")}},pu=class extends Qk{_createSVG(e){return document.createElementNS(wo,e)}},ZG=9,Ys=new WeakSet,GG=new Date().getTimezoneOffset()*60*1e3,OS=class{static create(e){switch(e.data.annotationType){case Mt.LINK:return new Xm(e);case Mt.TEXT:return new tR(e);case Mt.WIDGET:switch(e.data.fieldType){case"Tx":return new nR(e);case"Btn":return e.data.radioButton?new PS(e):e.data.checkBox?new rR(e):new oR(e);case"Ch":return new aR(e);case"Sig":return new iR(e)}return new $o(e);case Mt.POPUP:return new Jm(e);case Mt.FREETEXT:return new NS(e);case Mt.LINE:return new lR(e);case Mt.SQUARE:return new cR(e);case Mt.CIRCLE:return new uR(e);case Mt.POLYLINE:return new MS(e);case Mt.CARET:return new hR(e);case Mt.INK:return new Wm(e);case Mt.POLYGON:return new dR(e);case Mt.HIGHLIGHT:return new DS(e);case Mt.UNDERLINE:return new fR(e);case Mt.SQUIGGLY:return new mR(e);case Mt.STRIKEOUT:return new pR(e);case Mt.STAMP:return new LS(e);case Mt.FILEATTACHMENT:return new gR(e);default:return new _t(e)}}},_t=class t{#e=null;#t=!1;#i=null;constructor(e,{isRenderable:n=!1,ignoreBorder:r=!1,createQuadrilaterals:i=!1}={}){this.isRenderable=n,this.data=e.data,this.layer=e.layer,this.linkService=e.linkService,this.downloadManager=e.downloadManager,this.imageResourcesPath=e.imageResourcesPath,this.renderForms=e.renderForms,this.svgFactory=e.svgFactory,this.annotationStorage=e.annotationStorage,this.enableComment=e.enableComment,this.enableScripting=e.enableScripting,this.hasJSActions=e.hasJSActions,this._fieldObjects=e.fieldObjects,this.parent=e.parent,n&&(this.container=this._createContainer(r)),i&&this._createQuadrilaterals()}static _hasPopupData({contentsObj:e,richText:n}){return!!(e?.str||n?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return t._hasPopupData(this.data)||this.enableComment&&!!this.commentText}get commentData(){let{data:e}=this,n=this.annotationStorage?.getEditor(e.id);return n?n.getData():e}get hasCommentButton(){return this.enableComment&&this.hasPopupElement}get commentButtonPosition(){let e=this.annotationStorage?.getEditor(this.data.id);if(e)return e.commentButtonPositionInPage;let{quadPoints:n,inkLists:r,rect:i}=this.data,o=-1/0,a=-1/0;if(n?.length>=8){for(let s=0;s<n.length;s+=8)n[s+1]>a?(a=n[s+1],o=n[s+2]):n[s+1]===a&&(o=Math.max(o,n[s+2]));return[o,a]}if(r?.length>=1){for(let s of r)for(let l=0,c=s.length;l<c;l+=2)s[l+1]>a?(a=s[l+1],o=s[l]):s[l+1]===a&&(o=Math.max(o,s[l]));if(o!==1/0)return[o,a]}return i?[i[2],i[3]]:null}_normalizePoint(e){let{page:{view:n},viewport:{rawDims:{pageWidth:r,pageHeight:i,pageX:o,pageY:a}}}=this.parent;return e[1]=n[3]-e[1]+n[1],e[0]=100*(e[0]-o)/r,e[1]=100*(e[1]-a)/i,e}get commentText(){let{data:e}=this;return this.annotationStorage.getRawValue(`${qm}${e.id}`)?.popup?.contents||e.contentsObj?.str||""}set commentText(e){let{data:n}=this,r={deleted:!e,contents:e||""};this.annotationStorage.updateEditor(n.id,{popup:r})||this.annotationStorage.setValue(`${qm}${n.id}`,{id:n.id,annotationType:n.annotationType,pageIndex:this.parent.page._pageIndex,popup:r,popupRef:n.popupRef,modificationDate:new Date}),e||this.removePopup()}removePopup(){(this.#i?.popup||this.popup)?.remove(),this.#i=this.popup=null}updateEdited(e){if(!this.container)return;e.rect&&(this.#e||={rect:this.data.rect.slice(0)});let{rect:n,popup:r}=e;n&&this.#n(n);let i=this.#i?.popup||this.popup;!i&&r?.text&&(this._createPopup(r),i=this.#i.popup),i&&(i.updateEdited(e),r?.deleted&&(i.remove(),this.#i=null,this.popup=null))}resetEdited(){this.#e&&(this.#n(this.#e.rect),this.#i?.popup.resetEdited(),this.#e=null)}#n(e){let{container:{style:n},data:{rect:r,rotation:i},parent:{viewport:{rawDims:{pageWidth:o,pageHeight:a,pageX:s,pageY:l}}}}=this;r?.splice(0,4,...e),n.left=`${100*(e[0]-s)/o}%`,n.top=`${100*(a-e[3]+l)/a}%`,i===0?(n.width=`${100*(e[2]-e[0])/o}%`,n.height=`${100*(e[3]-e[1])/a}%`):this.setRotation(i)}_createContainer(e){let{data:n,parent:{page:r,viewport:i}}=this,o=document.createElement("section");o.setAttribute("data-annotation-id",n.id),!(this instanceof $o)&&!(this instanceof Xm)&&(o.tabIndex=0);let{style:a}=o;if(a.zIndex=this.parent.zIndex,this.parent.zIndex+=2,n.alternativeText&&(o.title=n.alternativeText),n.noRotate&&o.classList.add("norotate"),!n.rect||this instanceof Jm){let{rotation:p}=n;return!n.hasOwnCanvas&&p!==0&&this.setRotation(p,o),o}let{width:s,height:l}=this;if(!e&&n.borderStyle.width>0){a.borderWidth=`${n.borderStyle.width}px`;let p=n.borderStyle.horizontalCornerRadius,y=n.borderStyle.verticalCornerRadius;if(p>0||y>0){let v=`calc(${p}px * var(--total-scale-factor)) / calc(${y}px * var(--total-scale-factor))`;a.borderRadius=v}else if(this instanceof PS){let v=`calc(${s}px * var(--total-scale-factor)) / calc(${l}px * var(--total-scale-factor))`;a.borderRadius=v}switch(n.borderStyle.style){case cu.SOLID:a.borderStyle="solid";break;case cu.DASHED:a.borderStyle="dashed";break;case cu.BEVELED:we("Unimplemented border style: beveled");break;case cu.INSET:we("Unimplemented border style: inset");break;case cu.UNDERLINE:a.borderBottomStyle="solid";break;default:break}let g=n.borderColor||null;g?(this.#t=!0,a.borderColor=oe.makeHexColor(g[0]|0,g[1]|0,g[2]|0)):a.borderWidth=0}let c=oe.normalizeRect([n.rect[0],r.view[3]-n.rect[1]+r.view[1],n.rect[2],r.view[3]-n.rect[3]+r.view[1]]),{pageWidth:u,pageHeight:d,pageX:h,pageY:f}=i.rawDims;a.left=`${100*(c[0]-h)/u}%`,a.top=`${100*(c[1]-f)/d}%`;let{rotation:m}=n;return n.hasOwnCanvas||m===0?(a.width=`${100*s/u}%`,a.height=`${100*l/d}%`):this.setRotation(m,o),o}setRotation(e,n=this.container){if(!this.data.rect)return;let{pageWidth:r,pageHeight:i}=this.parent.viewport.rawDims,{width:o,height:a}=this;e%180!==0&&([o,a]=[a,o]),n.style.width=`${100*o/r}%`,n.style.height=`${100*a/i}%`,n.setAttribute("data-main-rotation",(360-e)%360)}get _commonActions(){let e=(n,r,i)=>{let o=i.detail[n],a=o[0],s=o.slice(1);i.target.style[r]=IS[`${a}_HTML`](s),this.annotationStorage.setValue(this.data.id,{[r]:IS[`${a}_rgb`](s)})};return Re(this,"_commonActions",{display:n=>{let{display:r}=n.detail,i=r%2===1;this.container.style.visibility=i?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:i,noPrint:r===1||r===2})},print:n=>{this.annotationStorage.setValue(this.data.id,{noPrint:!n.detail.print})},hidden:n=>{let{hidden:r}=n.detail;this.container.style.visibility=r?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:r,noView:r})},focus:n=>{setTimeout(()=>n.target.focus({preventScroll:!1}),0)},userName:n=>{n.target.title=n.detail.userName},readonly:n=>{n.target.disabled=n.detail.readonly},required:n=>{this._setRequired(n.target,n.detail.required)},bgColor:n=>{e("bgColor","backgroundColor",n)},fillColor:n=>{e("fillColor","backgroundColor",n)},fgColor:n=>{e("fgColor","color",n)},textColor:n=>{e("textColor","color",n)},borderColor:n=>{e("borderColor","borderColor",n)},strokeColor:n=>{e("strokeColor","borderColor",n)},rotation:n=>{let r=n.detail.rotation;this.setRotation(r),this.annotationStorage.setValue(this.data.id,{rotation:r})}})}_dispatchEventFromSandbox(e,n){let r=this._commonActions;for(let i of Object.keys(n.detail))(e[i]||r[i])?.(n)}_setDefaultPropertiesFromJS(e){if(!this.enableScripting)return;let n=this.annotationStorage.getRawValue(this.data.id);if(!n)return;let r=this._commonActions;for(let[i,o]of Object.entries(n)){let a=r[i];if(a){let s={detail:{[i]:o},target:e};a(s),delete n[i]}}}_createQuadrilaterals(){if(!this.container)return;let{quadPoints:e}=this.data;if(!e)return;let[n,r,i,o]=this.data.rect.map(p=>Math.fround(p));if(e.length===8){let[p,y,g,v]=e.subarray(2,6);if(i===p&&o===y&&n===g&&r===v)return}let{style:a}=this.container,s;if(this.#t){let{borderColor:p,borderWidth:y}=a;a.borderWidth=0,s=["url('data:image/svg+xml;utf8,",'<svg xmlns="http://www.w3.org/2000/svg"',' preserveAspectRatio="none" viewBox="0 0 1 1">',`<g fill="transparent" stroke="${p}" stroke-width="${y}">`],this.container.classList.add("hasBorder")}let l=i-n,c=o-r,{svgFactory:u}=this,d=u.createElement("svg");d.classList.add("quadrilateralsContainer"),d.setAttribute("width",0),d.setAttribute("height",0),d.role="none";let h=u.createElement("defs");d.append(h);let f=u.createElement("clipPath"),m=`clippath_${this.data.id}`;f.setAttribute("id",m),f.setAttribute("clipPathUnits","objectBoundingBox"),h.append(f);for(let p=2,y=e.length;p<y;p+=8){let g=e[p],v=e[p+1],S=e[p+2],_=e[p+3],$=u.createElement("rect"),w=(S-n)/l,A=(o-v)/c,k=(g-S)/l,I=(v-_)/c;$.setAttribute("x",w),$.setAttribute("y",A),$.setAttribute("width",k),$.setAttribute("height",I),f.append($),s?.push(`<rect vector-effect="non-scaling-stroke" x="${w}" y="${A}" width="${k}" height="${I}"/>`)}this.#t&&(s.push("</g></svg>')"),a.backgroundImage=s.join("")),this.container.append(d),this.container.style.clipPath=`url(#${m})`}_createPopup(e=null){let{data:n}=this,r,i;e?(r={str:e.text},i=e.date):(r=n.contentsObj,i=n.modificationDate);let o=this.#i=new Jm({data:{color:n.color,titleObj:n.titleObj,modificationDate:i,contentsObj:r,richText:n.richText,parentRect:n.rect,borderStyle:0,id:`popup_${n.id}`,rotation:n.rotation,noRotate:!0},linkService:this.linkService,parent:this.parent,elements:[this]});this.parent._commentManager||this.parent.div.append(o.render())}get hasPopupElement(){return!!(this.#i||this.popup||this.data.popupRef)}get extraPopupElement(){return this.#i}render(){rt("Abstract method `AnnotationElement.render` called")}_getElementsByName(e,n=null){let r=[];if(this._fieldObjects){let i=this._fieldObjects[e];if(i)for(let{page:o,id:a,exportValues:s}of i){if(o===-1||a===n)continue;let l=typeof s=="string"?s:null,c=document.querySelector(`[data-element-id="${a}"]`);if(c&&!Ys.has(c)){we(`_getElementsByName - element not allowed: ${a}`);continue}r.push({id:a,exportValue:l,domElement:c})}return r}for(let i of document.getElementsByName(e)){let{exportValue:o}=i,a=i.getAttribute("data-element-id");a!==n&&Ys.has(i)&&r.push({id:a,exportValue:o,domElement:i})}return r}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(){let e=this.getElementsToTriggerPopup();if(Array.isArray(e))for(let n of e)n.classList.add("highlightArea");else e.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;let{annotationEditorType:e,data:{id:n}}=this;this.container.addEventListener("dblclick",()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:e,editId:n,mustEnterInEditMode:!0})})}get width(){return this.data.rect[2]-this.data.rect[0]}get height(){return this.data.rect[3]-this.data.rect[1]}},eR=class extends _t{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0}),this.editor=e.editor}render(){return this.container.className="editorAnnotation",this.container}createOrUpdatePopup(){let{editor:e}=this;e.hasComment&&(this._createPopup(e.comment),this.extraPopupElement.popup.renderCommentButton())}get hasCommentButton(){return this.enableComment&&this.editor.hasComment}get commentButtonPosition(){return this.editor.commentButtonPositionInPage}get commentText(){return this.editor.comment.text}set commentText(e){this.editor.comment=e,e||this.removePopup()}get commentData(){return this.editor.getData()}remove(){this.container.remove(),this.container=null,this.removePopup()}},Xm=class extends _t{constructor(e,n=null){super(e,{isRenderable:!0,ignoreBorder:!!n?.ignoreBorder,createQuadrilaterals:!0}),this.isTooltipOnly=e.data.isTooltipOnly}render(){let{data:e,linkService:n}=this,r=document.createElement("a");r.setAttribute("data-element-id",e.id);let i=!1;return e.url?(n.addLinkAttributes(r,e.url,e.newWindow),i=!0):e.action?(this._bindNamedAction(r,e.action,e.overlaidText),i=!0):e.attachment?(this.#t(r,e.attachment,e.overlaidText,e.attachmentDest),i=!0):e.setOCGState?(this.#i(r,e.setOCGState,e.overlaidText),i=!0):e.dest?(this._bindLink(r,e.dest,e.overlaidText),i=!0):(e.actions&&(e.actions.Action||e.actions["Mouse Up"]||e.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(r,e),i=!0),e.resetForm?(this._bindResetFormAction(r,e.resetForm),i=!0):this.isTooltipOnly&&!i&&(this._bindLink(r,""),i=!0)),this.container.classList.add("linkAnnotation"),i&&this.container.append(r),this.container}#e(){this.container.setAttribute("data-internal-link","")}_bindLink(e,n,r=""){e.href=this.linkService.getDestinationHash(n),e.onclick=()=>(n&&this.linkService.goToDestination(n),!1),(n||n==="")&&this.#e(),r&&(e.title=r)}_bindNamedAction(e,n,r=""){e.href=this.linkService.getAnchorUrl(""),e.onclick=()=>(this.linkService.executeNamedAction(n),!1),r&&(e.title=r),this.#e()}#t(e,n,r="",i=null){e.href=this.linkService.getAnchorUrl(""),n.description?e.title=n.description:r&&(e.title=r),e.onclick=()=>(this.downloadManager?.openOrDownloadData(n.content,n.filename,i),!1),this.#e()}#i(e,n,r=""){e.href=this.linkService.getAnchorUrl(""),e.onclick=()=>(this.linkService.executeSetOCGState(n),!1),r&&(e.title=r),this.#e()}_bindJSAction(e,n){e.href=this.linkService.getAnchorUrl("");let r=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(let i of Object.keys(n.actions)){let o=r.get(i);o&&(e[o]=()=>(this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n.id,name:i}}),!1))}n.overlaidText&&(e.title=n.overlaidText),e.onclick||(e.onclick=()=>!1),this.#e()}_bindResetFormAction(e,n){let r=e.onclick;if(r||(e.href=this.linkService.getAnchorUrl("")),this.#e(),!this._fieldObjects){we('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),r||(e.onclick=()=>!1);return}e.onclick=()=>{r?.();let{fields:i,refs:o,include:a}=n,s=[];if(i.length!==0||o.length!==0){let u=new Set(o);for(let d of i){let h=this._fieldObjects[d]||[];for(let{id:f}of h)u.add(f)}for(let d of Object.values(this._fieldObjects))for(let h of d)u.has(h.id)===a&&s.push(h)}else for(let u of Object.values(this._fieldObjects))s.push(...u);let l=this.annotationStorage,c=[];for(let u of s){let{id:d}=u;switch(c.push(d),u.type){case"text":{let f=u.defaultValue||"";l.setValue(d,{value:f});break}case"checkbox":case"radiobutton":{let f=u.defaultValue===u.exportValues;l.setValue(d,{value:f});break}case"combobox":case"listbox":{let f=u.defaultValue||"";l.setValue(d,{value:f});break}default:continue}let h=document.querySelector(`[data-element-id="${d}"]`);if(h){if(!Ys.has(h)){we(`_bindResetFormAction - element not allowed: ${d}`);continue}}else continue;h.dispatchEvent(new Event("resetform"))}return this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:c,name:"ResetForm"}}),!1}}},tR=class extends _t{constructor(e){super(e,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");let e=document.createElement("img");return e.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",e.setAttribute("data-l10n-id","pdfjs-text-annotation-type"),e.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name})),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.append(e),this.container}},$o=class extends _t{render(){return this.container}showElementAndHideCanvas(e){this.data.hasOwnCanvas&&(e.previousSibling?.nodeName==="CANVAS"&&(e.previousSibling.hidden=!0),e.hidden=!1)}_getKeyModifier(e){return Ft.platform.isMac?e.metaKey:e.ctrlKey}_setEventListener(e,n,r,i,o){r.includes("mouse")?e.addEventListener(r,a=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:o(a),shift:a.shiftKey,modifier:this._getKeyModifier(a)}})}):e.addEventListener(r,a=>{if(r==="blur"){if(!n.focused||!a.relatedTarget)return;n.focused=!1}else if(r==="focus"){if(n.focused)return;n.focused=!0}o&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:o(a)}})})}_setEventListeners(e,n,r,i){for(let[o,a]of r)(a==="Action"||this.data.actions?.[a])&&((a==="Focus"||a==="Blur")&&(n||={focused:!1}),this._setEventListener(e,n,o,a,i),a==="Focus"&&!this.data.actions?.Blur?this._setEventListener(e,n,"blur","Blur",null):a==="Blur"&&!this.data.actions?.Focus&&this._setEventListener(e,n,"focus","Focus",null))}_setBackgroundColor(e){let n=this.data.backgroundColor||null;e.style.backgroundColor=n===null?"transparent":oe.makeHexColor(n[0],n[1],n[2])}_setTextStyle(e){let n=["left","center","right"],{fontColor:r}=this.data.defaultAppearanceData,i=this.data.defaultAppearanceData.fontSize||ZG,o=e.style,a,s=2,l=c=>Math.round(10*c)/10;if(this.data.multiLine){let c=Math.abs(this.data.rect[3]-this.data.rect[1]-s),u=Math.round(c/(sS*i))||1,d=c/u;a=Math.min(i,l(d/sS))}else{let c=Math.abs(this.data.rect[3]-this.data.rect[1]-s);a=Math.min(i,l(c/sS))}o.fontSize=`calc(${a}px * var(--total-scale-factor))`,o.color=oe.makeHexColor(r[0],r[1],r[2]),this.data.textAlignment!==null&&(o.textAlign=n[this.data.textAlignment])}_setRequired(e,n){n?e.setAttribute("required",!0):e.removeAttribute("required"),e.setAttribute("aria-required",n)}},nR=class extends $o{constructor(e){let n=e.renderForms||e.data.hasOwnCanvas||!e.data.hasAppearance&&!!e.data.fieldValue;super(e,{isRenderable:n})}setPropertyOnSiblings(e,n,r,i){let o=this.annotationStorage;for(let a of this._getElementsByName(e.name,e.id))a.domElement&&(a.domElement[n]=r),o.setValue(a.id,{[i]:r})}render(){let e=this.annotationStorage,n=this.data.id;this.container.classList.add("textWidgetAnnotation");let r=null;if(this.renderForms){let i=e.getValue(n,{value:this.data.fieldValue}),o=i.value||"",a=e.getValue(n,{charLimit:this.data.maxLen}).charLimit;a&&o.length>a&&(o=o.slice(0,a));let s=i.formattedValue||this.data.textContent?.join(`
110
110
  `)||null;s&&this.data.comb&&(s=s.replaceAll(/\s+/g,""));let l={userValue:o,formattedValue:s,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(r=document.createElement("textarea"),r.textContent=s??o,this.data.doNotScroll&&(r.style.overflowY="hidden")):(r=document.createElement("input"),r.type=this.data.password?"password":"text",r.setAttribute("value",s??o),this.data.doNotScroll&&(r.style.overflowX="hidden")),this.data.hasOwnCanvas&&(r.hidden=!0),Ys.add(r),r.setAttribute("data-element-id",n),r.disabled=this.data.readOnly,r.name=this.data.fieldName,r.tabIndex=0;let{datetimeFormat:c,datetimeType:u,timeStep:d}=this.data,h=!!u&&this.enableScripting;c&&(r.title=c),this._setRequired(r,this.data.required),a&&(r.maxLength=a),r.addEventListener("input",m=>{e.setValue(n,{value:m.target.value}),this.setPropertyOnSiblings(r,"value",m.target.value,"value"),l.formattedValue=null}),r.addEventListener("resetform",m=>{let p=this.data.defaultFieldValue??"";r.value=l.userValue=p,l.formattedValue=null});let f=m=>{let{formattedValue:p}=l;p!=null&&(m.target.value=p),m.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){r.addEventListener("focus",p=>{if(l.focused)return;let{target:y}=p;if(h&&(y.type=u,d&&(y.step=d)),l.userValue){let g=l.userValue;if(h)if(u==="time"){let v=new Date(g),S=[v.getHours(),v.getMinutes(),v.getSeconds()];y.value=S.map(_=>_.toString().padStart(2,"0")).join(":")}else y.value=new Date(g-GG).toISOString().split(u==="date"?"T":".",1)[0];else y.value=g}l.lastCommittedValue=y.value,l.commitKey=1,this.data.actions?.Focus||(l.focused=!0)}),r.addEventListener("updatefromsandbox",p=>{this.showElementAndHideCanvas(p.target);let y={value(g){l.userValue=g.detail.value??"",h||e.setValue(n,{value:l.userValue.toString()}),g.target.value=l.userValue},formattedValue(g){let{formattedValue:v}=g.detail;l.formattedValue=v,v!=null&&g.target!==document.activeElement&&(g.target.value=v);let S={formattedValue:v};h&&(S.value=v),e.setValue(n,S)},selRange(g){g.target.setSelectionRange(...g.detail.selRange)},charLimit:g=>{let{charLimit:v}=g.detail,{target:S}=g;if(v===0){S.removeAttribute("maxLength");return}S.setAttribute("maxLength",v);let _=l.userValue;!_||_.length<=v||(_=_.slice(0,v),S.value=l.userValue=_,e.setValue(n,{value:_}),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:_,willCommit:!0,commitKey:1,selStart:S.selectionStart,selEnd:S.selectionEnd}}))}};this._dispatchEventFromSandbox(y,p)}),r.addEventListener("keydown",p=>{l.commitKey=1;let y=-1;if(p.key==="Escape"?y=0:p.key==="Enter"&&!this.data.multiLine?y=2:p.key==="Tab"&&(l.commitKey=3),y===-1)return;let{value:g}=p.target;l.lastCommittedValue!==g&&(l.lastCommittedValue=g,l.userValue=g,this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:g,willCommit:!0,commitKey:y,selStart:p.target.selectionStart,selEnd:p.target.selectionEnd}}))});let m=f;f=null,r.addEventListener("blur",p=>{if(!l.focused||!p.relatedTarget)return;this.data.actions?.Blur||(l.focused=!1);let{target:y}=p,{value:g}=y;if(h){if(g&&u==="time"){let v=g.split(":").map(S=>parseInt(S,10));g=new Date(2e3,0,1,v[0],v[1],v[2]||0).valueOf(),y.step=""}else g.includes("T")||(g=`${g}T00:00`),g=new Date(g).valueOf();y.type="text"}l.userValue=g,l.lastCommittedValue!==g&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:g,willCommit:!0,commitKey:l.commitKey,selStart:p.target.selectionStart,selEnd:p.target.selectionEnd}}),m(p)}),this.data.actions?.Keystroke&&r.addEventListener("beforeinput",p=>{l.lastCommittedValue=null;let{data:y,target:g}=p,{value:v,selectionStart:S,selectionEnd:_}=g,$=S,w=_;switch(p.inputType){case"deleteWordBackward":{let A=v.substring(0,S).match(/\w*[^\w]*$/);A&&($-=A[0].length);break}case"deleteWordForward":{let A=v.substring(S).match(/^[^\w]*\w*/);A&&(w+=A[0].length);break}case"deleteContentBackward":S===_&&($-=1);break;case"deleteContentForward":S===_&&(w+=1);break}p.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:v,change:y||"",willCommit:!1,selStart:$,selEnd:w}})}),this._setEventListeners(r,l,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],p=>p.target.value)}if(f&&r.addEventListener("blur",f),this.data.comb){let p=(this.data.rect[2]-this.data.rect[0])/a;r.classList.add("comb"),r.style.letterSpacing=`calc(${p}px * var(--total-scale-factor) - 1ch)`}}else r=document.createElement("div"),r.textContent=this.data.fieldValue,r.style.verticalAlign="middle",r.style.display="table-cell",this.data.hasOwnCanvas&&(r.hidden=!0);return this._setTextStyle(r),this._setBackgroundColor(r),this._setDefaultPropertiesFromJS(r),this.container.append(r),this.container}},iR=class extends $o{constructor(e){super(e,{isRenderable:!!e.data.hasOwnCanvas})}},rR=class extends $o{constructor(e){super(e,{isRenderable:e.renderForms})}render(){let e=this.annotationStorage,n=this.data,r=n.id,i=e.getValue(r,{value:n.exportValue===n.fieldValue}).value;typeof i=="string"&&(i=i!=="Off",e.setValue(r,{value:i})),this.container.classList.add("buttonWidgetAnnotation","checkBox");let o=document.createElement("input");return Ys.add(o),o.setAttribute("data-element-id",r),o.disabled=n.readOnly,this._setRequired(o,this.data.required),o.type="checkbox",o.name=n.fieldName,i&&o.setAttribute("checked",!0),o.setAttribute("exportValue",n.exportValue),o.tabIndex=0,o.addEventListener("change",a=>{let{name:s,checked:l}=a.target;for(let c of this._getElementsByName(s,r)){let u=l&&c.exportValue===n.exportValue;c.domElement&&(c.domElement.checked=u),e.setValue(c.id,{value:u})}e.setValue(r,{value:l})}),o.addEventListener("resetform",a=>{let s=n.defaultFieldValue||"Off";a.target.checked=s===n.exportValue}),this.enableScripting&&this.hasJSActions&&(o.addEventListener("updatefromsandbox",a=>{let s={value(l){l.target.checked=l.detail.value!=="Off",e.setValue(r,{value:l.target.checked})}};this._dispatchEventFromSandbox(s,a)}),this._setEventListeners(o,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],a=>a.target.checked)),this._setBackgroundColor(o),this._setDefaultPropertiesFromJS(o),this.container.append(o),this.container}},PS=class extends $o{constructor(e){super(e,{isRenderable:e.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");let e=this.annotationStorage,n=this.data,r=n.id,i=e.getValue(r,{value:n.fieldValue===n.buttonValue}).value;if(typeof i=="string"&&(i=i!==n.buttonValue,e.setValue(r,{value:i})),i)for(let a of this._getElementsByName(n.fieldName,r))e.setValue(a.id,{value:!1});let o=document.createElement("input");if(Ys.add(o),o.setAttribute("data-element-id",r),o.disabled=n.readOnly,this._setRequired(o,this.data.required),o.type="radio",o.name=n.fieldName,i&&o.setAttribute("checked",!0),o.tabIndex=0,o.addEventListener("change",a=>{let{name:s,checked:l}=a.target;for(let c of this._getElementsByName(s,r))e.setValue(c.id,{value:!1});e.setValue(r,{value:l})}),o.addEventListener("resetform",a=>{let s=n.defaultFieldValue;a.target.checked=s!=null&&s===n.buttonValue}),this.enableScripting&&this.hasJSActions){let a=n.buttonValue;o.addEventListener("updatefromsandbox",s=>{let l={value:c=>{let u=a===c.detail.value;for(let d of this._getElementsByName(c.target.name)){let h=u&&d.id===r;d.domElement&&(d.domElement.checked=h),e.setValue(d.id,{value:h})}}};this._dispatchEventFromSandbox(l,s)}),this._setEventListeners(o,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],s=>s.target.checked)}return this._setBackgroundColor(o),this._setDefaultPropertiesFromJS(o),this.container.append(o),this.container}},oR=class extends Xm{constructor(e){super(e,{ignoreBorder:e.data.hasAppearance})}render(){let e=super.render();e.classList.add("buttonWidgetAnnotation","pushButton");let n=e.lastChild;return this.enableScripting&&this.hasJSActions&&n&&(this._setDefaultPropertiesFromJS(n),n.addEventListener("updatefromsandbox",r=>{this._dispatchEventFromSandbox({},r)})),e}},aR=class extends $o{constructor(e){super(e,{isRenderable:e.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");let e=this.annotationStorage,n=this.data.id,r=e.getValue(n,{value:this.data.fieldValue}),i=document.createElement("select");Ys.add(i),i.setAttribute("data-element-id",n),i.disabled=this.data.readOnly,this._setRequired(i,this.data.required),i.name=this.data.fieldName,i.tabIndex=0;let o=this.data.combo&&this.data.options.length>0;this.data.combo||(i.size=this.data.options.length,this.data.multiSelect&&(i.multiple=!0)),i.addEventListener("resetform",u=>{let d=this.data.defaultFieldValue;for(let h of i.options)h.selected=h.value===d});for(let u of this.data.options){let d=document.createElement("option");d.textContent=u.displayValue,d.value=u.exportValue,r.value.includes(u.exportValue)&&(d.setAttribute("selected",!0),o=!1),i.append(d)}let a=null;if(o){let u=document.createElement("option");u.value=" ",u.setAttribute("hidden",!0),u.setAttribute("selected",!0),i.prepend(u),a=()=>{u.remove(),i.removeEventListener("input",a),a=null},i.addEventListener("input",a)}let s=u=>{let d=u?"value":"textContent",{options:h,multiple:f}=i;return f?Array.prototype.filter.call(h,m=>m.selected).map(m=>m[d]):h.selectedIndex===-1?null:h[h.selectedIndex][d]},l=s(!1),c=u=>{let d=u.target.options;return Array.prototype.map.call(d,h=>({displayValue:h.textContent,exportValue:h.value}))};return this.enableScripting&&this.hasJSActions?(i.addEventListener("updatefromsandbox",u=>{let d={value(h){a?.();let f=h.detail.value,m=new Set(Array.isArray(f)?f:[f]);for(let p of i.options)p.selected=m.has(p.value);e.setValue(n,{value:s(!0)}),l=s(!1)},multipleSelection(h){i.multiple=!0},remove(h){let f=i.options,m=h.detail.remove;f[m].selected=!1,i.remove(m),f.length>0&&Array.prototype.findIndex.call(f,y=>y.selected)===-1&&(f[0].selected=!0),e.setValue(n,{value:s(!0),items:c(h)}),l=s(!1)},clear(h){for(;i.length!==0;)i.remove(0);e.setValue(n,{value:null,items:[]}),l=s(!1)},insert(h){let{index:f,displayValue:m,exportValue:p}=h.detail.insert,y=i.children[f],g=document.createElement("option");g.textContent=m,g.value=p,y?y.before(g):i.append(g),e.setValue(n,{value:s(!0),items:c(h)}),l=s(!1)},items(h){let{items:f}=h.detail;for(;i.length!==0;)i.remove(0);for(let m of f){let{displayValue:p,exportValue:y}=m,g=document.createElement("option");g.textContent=p,g.value=y,i.append(g)}i.options.length>0&&(i.options[0].selected=!0),e.setValue(n,{value:s(!0),items:c(h)}),l=s(!1)},indices(h){let f=new Set(h.detail.indices);for(let m of h.target.options)m.selected=f.has(m.index);e.setValue(n,{value:s(!0)}),l=s(!1)},editable(h){h.target.disabled=!h.detail.editable}};this._dispatchEventFromSandbox(d,u)}),i.addEventListener("input",u=>{let d=s(!0),h=s(!1);e.setValue(n,{value:d}),u.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:l,change:h,changeEx:d,willCommit:!1,commitKey:1,keyDown:!1}})}),this._setEventListeners(i,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],u=>u.target.value)):i.addEventListener("input",function(u){e.setValue(n,{value:s(!0)})}),this.data.combo&&this._setTextStyle(i),this._setBackgroundColor(i),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}},Jm=class extends _t{constructor(e){let{data:n,elements:r,parent:i}=e,o=!!i._commentManager;if(super(e,{isRenderable:!o&&_t._hasPopupData(n)}),this.elements=r,o&&_t._hasPopupData(n)){let a=this.popup=this.#e();for(let s of r)s.popup=a}else this.popup=null}#e(){return new sR({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate||this.data.creationDate,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,commentManager:this.parent._commentManager})}render(){let{container:e}=this;e.classList.add("popupAnnotation"),e.role="comment";let n=this.popup=this.#e(),r=[];for(let i of this.elements)i.popup=n,i.container.ariaHasPopup="dialog",r.push(i.data.id),i.addHighlightArea();return this.container.setAttribute("aria-controls",r.map(i=>`${kR}${i}`).join(",")),this.container}},sR=class{#e=null;#t=this.#H.bind(this);#i=this.#j.bind(this);#n=this.#O.bind(this);#a=this.#_.bind(this);#r=null;#o=null;#s=null;#c=null;#l=null;#h=null;#d=null;#f=!1;#g=null;#m=null;#u=null;#p=null;#v=null;#y=null;#b=null;#A=null;#x=null;#S=null;#T=!1;#w=null;#$=null;constructor({container:e,color:n,elements:r,titleObj:i,modificationDate:o,contentsObj:a,richText:s,parent:l,rect:c,parentRect:u,open:d,commentManager:h=null}){this.#o=e,this.#x=i,this.#s=a,this.#A=s,this.#h=l,this.#r=n,this.#b=c,this.#d=u,this.#l=r,this.#e=h,this.#w=r[0],this.#c=Gm.toDateObject(o),this.trigger=r.flatMap(f=>f.getElementsToTriggerPopup()),h?this.renderCommentButton():(this.#R(),this.#o.hidden=!0,d&&this.#_())}#R(){if(this.#m)return;this.#m=new AbortController;let{signal:e}=this.#m;for(let n of this.trigger)n.addEventListener("click",this.#a,{signal:e}),n.addEventListener("pointerenter",this.#n,{signal:e}),n.addEventListener("pointerleave",this.#i,{signal:e}),n.classList.add("popupTriggerArea");for(let n of this.#l)n.container?.addEventListener("keydown",this.#t,{signal:e})}#z(){let e=this.#l.find(n=>n.hasCommentButton);e&&(this.#v=e._normalizePoint(e.commentButtonPosition))}renderCommentButton(){if(this.#p||(this.#v||this.#z(),!this.#v))return;let{signal:e}=this.#m=new AbortController,n=!!this.#w.extraPopupElement,r=()=>{this.#e.toggleCommentPopup(this,!0,void 0,!n)},i=()=>{this.#e.toggleCommentPopup(this,!1,!0,!n)},o=()=>{this.#e.toggleCommentPopup(this,!1,!1)};if(n){this.#p=this.#w.container;for(let a of this.trigger)a.ariaHasPopup="dialog",a.ariaControls="commentPopup",a.addEventListener("keydown",this.#t,{signal:e}),a.addEventListener("click",r,{signal:e}),a.addEventListener("pointerenter",i,{signal:e}),a.addEventListener("pointerleave",o,{signal:e}),a.classList.add("popupTriggerArea")}else{let a=this.#p=document.createElement("button");a.className="annotationCommentButton";let s=this.#w.container;a.style.zIndex=s.style.zIndex+1,a.tabIndex=0,a.ariaHasPopup="dialog",a.ariaControls="commentPopup",a.setAttribute("data-l10n-id","pdfjs-show-comment-button"),this.#D(),this.#k(),a.addEventListener("keydown",this.#t,{signal:e}),a.addEventListener("click",r,{signal:e}),a.addEventListener("pointerenter",i,{signal:e}),a.addEventListener("pointerleave",o,{signal:e}),s.after(a)}}#k(){if(this.#w.extraPopupElement&&!this.#w.editor)return;this.renderCommentButton();let[e,n]=this.#v,{style:r}=this.#p;r.left=`calc(${e}%)`,r.top=`calc(${n}% - var(--comment-button-dim))`}#D(){this.#w.extraPopupElement||(this.renderCommentButton(),this.#p.style.backgroundColor=this.commentButtonColor||"")}get commentButtonColor(){let{color:e,opacity:n}=this.#w.commentData;return e?this.#h._commentManager.makeCommentColor(e,n):null}focusCommentButton(){setTimeout(()=>{this.#p?.focus()},0)}getData(){let{richText:e,color:n,opacity:r,creationDate:i,modificationDate:o}=this.#w.commentData;return{contentsObj:{str:this.comment},richText:e,color:n,opacity:r,creationDate:i,modificationDate:o}}get elementBeforePopup(){return this.#p}get comment(){return this.#$||=this.#w.commentText,this.#$}set comment(e){e!==this.comment&&(this.#w.commentText=this.#$=e)}get parentBoundingClientRect(){return this.#w.layer.getBoundingClientRect()}setCommentButtonStates({selected:e,hasPopup:n}){this.#p&&(this.#p.classList.toggle("selected",e),this.#p.ariaExpanded=n)}setSelectedCommentButton(e){this.#p.classList.toggle("selected",e)}get commentPopupPosition(){if(this.#y)return this.#y;let{x:e,y:n,height:r}=this.#p.getBoundingClientRect(),{x:i,y:o,width:a,height:s}=this.#w.layer.getBoundingClientRect();return[(e-i)/a,(n+r-o)/s]}set commentPopupPosition(e){this.#y=e}hasDefaultPopupPosition(){return this.#y===null}get commentButtonPosition(){return this.#v}get commentButtonWidth(){return this.#p.getBoundingClientRect().width/this.parentBoundingClientRect.width}editComment(e){let[n,r]=this.#y||this.commentButtonPosition.map(c=>c/100),i=this.parentBoundingClientRect,{x:o,y:a,width:s,height:l}=i;this.#e.showDialog(null,this,o+n*s,a+r*l,{...e,parentDimensions:i})}render(){if(this.#g)return;let e=this.#g=document.createElement("div");if(e.className="popup",this.#r){let r=e.style.outlineColor=oe.makeHexColor(...this.#r);e.style.backgroundColor=`color-mix(in srgb, ${r} 30%, white)`}let n=document.createElement("span");if(n.className="header",this.#x?.str){let r=document.createElement("span");r.className="title",n.append(r),{dir:r.dir,str:r.textContent}=this.#x}if(e.append(n),this.#c){let r=document.createElement("time");r.className="popupDate",r.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string"),r.setAttribute("data-l10n-args",JSON.stringify({dateObj:this.#c.valueOf()})),r.dateTime=this.#c.toISOString(),n.append(r)}rU({html:this.#I||this.#s.str,dir:this.#s?.dir,className:"popupContent"},e),this.#o.append(e)}get#I(){let e=this.#A,n=this.#s;return e?.str&&(!n?.str||n.str===e.str)&&this.#A.html||null}get#P(){return this.#I?.attributes?.style?.fontSize||0}get#L(){return this.#I?.attributes?.style?.color||null}#N(e){let n=[],r={str:e,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:n}]}},i={style:{color:this.#L,fontSize:this.#P?`calc(${this.#P}px * var(--total-scale-factor))`:""}};for(let o of e.split(`
111
111
  `))n.push({name:"span",value:o,attributes:i});return r}#H(e){e.altKey||e.shiftKey||e.ctrlKey||e.metaKey||(e.key==="Enter"||e.key==="Escape"&&this.#f)&&this.#_()}updateEdited({rect:e,popup:n,deleted:r}){if(this.#e){r?(this.remove(),this.#$=null):n&&(n.deleted?this.remove():(this.#D(),this.#$=n.text)),e&&(this.#v=null,this.#z(),this.#k());return}if(r||n?.deleted){this.remove();return}this.#R(),this.#S||={contentsObj:this.#s,richText:this.#A},e&&(this.#u=null),n&&n.text&&(this.#A=this.#N(n.text),this.#c=Gm.toDateObject(n.date),this.#s=null),this.#g?.remove(),this.#g=null}resetEdited(){this.#S&&({contentsObj:this.#s,richText:this.#A}=this.#S,this.#S=null,this.#g?.remove(),this.#g=null,this.#u=null)}remove(){if(this.#m?.abort(),this.#m=null,this.#g?.remove(),this.#g=null,this.#T=!1,this.#f=!1,this.#p?.remove(),this.#p=null,this.trigger)for(let e of this.trigger)e.classList.remove("popupTriggerArea")}#E(){if(this.#u!==null)return;let{page:{view:e},viewport:{rawDims:{pageWidth:n,pageHeight:r,pageX:i,pageY:o}}}=this.#h,a=!!this.#d,s=a?this.#d:this.#b;for(let m of this.#l)if(!s||oe.intersect(m.data.rect,s)!==null){s=m.data.rect,a=!0;break}let l=oe.normalizeRect([s[0],e[3]-s[1]+e[1],s[2],e[3]-s[3]+e[1]]),u=a?s[2]-s[0]+5:0,d=l[0]+u,h=l[1];this.#u=[100*(d-i)/n,100*(h-o)/r];let{style:f}=this.#o;f.left=`${this.#u[0]}%`,f.top=`${this.#u[1]}%`}#_(){if(this.#e){this.#e.toggleCommentPopup(this,!1);return}this.#f=!this.#f,this.#f?(this.#O(),this.#o.addEventListener("click",this.#a),this.#o.addEventListener("keydown",this.#t)):(this.#j(),this.#o.removeEventListener("click",this.#a),this.#o.removeEventListener("keydown",this.#t))}#O(){this.#g||this.render(),this.isVisible?this.#f&&this.#o.classList.add("focused"):(this.#E(),this.#o.hidden=!1,this.#o.style.zIndex=parseInt(this.#o.style.zIndex)+1e3)}#j(){this.#o.classList.remove("focused"),!(this.#f||!this.isVisible)&&(this.#o.hidden=!0,this.#o.style.zIndex=parseInt(this.#o.style.zIndex)-1e3)}forceHide(){this.#T=this.isVisible,this.#T&&(this.#o.hidden=!0)}maybeShow(){this.#e||(this.#R(),this.#T&&(this.#g||this.#O(),this.#T=!1,this.#o.hidden=!1))}get isVisible(){return this.#e?!1:this.#o.hidden===!1}},NS=class extends _t{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0}),this.textContent=e.data.textContent,this.textPosition=e.data.textPosition,this.annotationEditorType=$e.FREETEXT}render(){if(this.container.classList.add("freeTextAnnotation"),this.textContent){let e=document.createElement("div");e.classList.add("annotationTextContent"),e.setAttribute("role","comment");for(let n of this.textContent){let r=document.createElement("span");r.textContent=n,e.append(r)}this.container.append(e)}return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this._editOnDoubleClick(),this.container}},lR=class extends _t{#e=null;constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("lineAnnotation");let{data:e,width:n,height:r}=this,i=this.svgFactory.create(n,r,!0),o=this.#e=this.svgFactory.createElement("svg:line");return o.setAttribute("x1",e.rect[2]-e.lineCoordinates[0]),o.setAttribute("y1",e.rect[3]-e.lineCoordinates[1]),o.setAttribute("x2",e.rect[2]-e.lineCoordinates[2]),o.setAttribute("y2",e.rect[3]-e.lineCoordinates[3]),o.setAttribute("stroke-width",e.borderStyle.width||1),o.setAttribute("stroke","transparent"),o.setAttribute("fill","transparent"),i.append(o),this.container.append(i),!e.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add("highlightArea")}},cR=class extends _t{#e=null;constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("squareAnnotation");let{data:e,width:n,height:r}=this,i=this.svgFactory.create(n,r,!0),o=e.borderStyle.width,a=this.#e=this.svgFactory.createElement("svg:rect");return a.setAttribute("x",o/2),a.setAttribute("y",o/2),a.setAttribute("width",n-o),a.setAttribute("height",r-o),a.setAttribute("stroke-width",o||1),a.setAttribute("stroke","transparent"),a.setAttribute("fill","transparent"),i.append(a),this.container.append(i),!e.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add("highlightArea")}},uR=class extends _t{#e=null;constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("circleAnnotation");let{data:e,width:n,height:r}=this,i=this.svgFactory.create(n,r,!0),o=e.borderStyle.width,a=this.#e=this.svgFactory.createElement("svg:ellipse");return a.setAttribute("cx",n/2),a.setAttribute("cy",r/2),a.setAttribute("rx",n/2-o/2),a.setAttribute("ry",r/2-o/2),a.setAttribute("stroke-width",o||1),a.setAttribute("stroke","transparent"),a.setAttribute("fill","transparent"),i.append(a),this.container.append(i),!e.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add("highlightArea")}},MS=class extends _t{#e=null;constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="polylineAnnotation",this.svgElementName="svg:polyline"}render(){this.container.classList.add(this.containerClassName);let{data:{rect:e,vertices:n,borderStyle:r,popupRef:i},width:o,height:a}=this;if(!n)return this.container;let s=this.svgFactory.create(o,a,!0),l=[];for(let u=0,d=n.length;u<d;u+=2){let h=n[u]-e[0],f=e[3]-n[u+1];l.push(`${h},${f}`)}l=l.join(" ");let c=this.#e=this.svgFactory.createElement(this.svgElementName);return c.setAttribute("points",l),c.setAttribute("stroke-width",r.width||1),c.setAttribute("stroke","transparent"),c.setAttribute("fill","transparent"),s.append(c),this.container.append(s),!i&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add("highlightArea")}},dR=class extends MS{constructor(e){super(e),this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}},hR=class extends _t{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0})}render(){return this.container.classList.add("caretAnnotation"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container}},Wm=class extends _t{#e=null;#t=[];constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline",this.annotationEditorType=this.data.it==="InkHighlight"?$e.HIGHLIGHT:$e.INK}#i(e,n){switch(e){case 90:return{transform:`rotate(90) translate(${-n[0]},${n[1]}) scale(1,-1)`,width:n[3]-n[1],height:n[2]-n[0]};case 180:return{transform:`rotate(180) translate(${-n[2]},${n[1]}) scale(1,-1)`,width:n[2]-n[0],height:n[3]-n[1]};case 270:return{transform:`rotate(270) translate(${-n[2]},${n[3]}) scale(1,-1)`,width:n[3]-n[1],height:n[2]-n[0]};default:return{transform:`translate(${-n[0]},${n[3]}) scale(1,-1)`,width:n[2]-n[0],height:n[3]-n[1]}}}render(){this.container.classList.add(this.containerClassName);let{data:{rect:e,rotation:n,inkLists:r,borderStyle:i,popupRef:o}}=this,{transform:a,width:s,height:l}=this.#i(n,e),c=this.svgFactory.create(s,l,!0),u=this.#e=this.svgFactory.createElement("svg:g");c.append(u),u.setAttribute("stroke-width",i.width||1),u.setAttribute("stroke-linecap","round"),u.setAttribute("stroke-linejoin","round"),u.setAttribute("stroke-miterlimit",10),u.setAttribute("stroke","transparent"),u.setAttribute("fill","transparent"),u.setAttribute("transform",a);for(let d=0,h=r.length;d<h;d++){let f=this.svgFactory.createElement(this.svgElementName);this.#t.push(f),f.setAttribute("points",r[d].join(",")),u.append(f)}return!o&&this.hasPopupData&&this._createPopup(),this.container.append(c),this._editOnDoubleClick(),this.container}updateEdited(e){super.updateEdited(e);let{thickness:n,points:r,rect:i}=e,o=this.#e;if(n>=0&&o.setAttribute("stroke-width",n||1),r)for(let a=0,s=this.#t.length;a<s;a++)this.#t[a].setAttribute("points",r[a].join(","));if(i){let{transform:a,width:s,height:l}=this.#i(this.data.rotation,i);o.parentElement.setAttribute("viewBox",`0 0 ${s} ${l}`),o.setAttribute("transform",a)}}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}},DS=class extends _t{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0}),this.annotationEditorType=$e.HIGHLIGHT}render(){let{data:{overlaidText:e,popupRef:n}}=this;if(!n&&this.hasPopupData&&this._createPopup(),this.container.classList.add("highlightAnnotation"),this._editOnDoubleClick(),e){let r=document.createElement("mark");r.classList.add("overlaidText"),r.textContent=e,this.container.append(r)}return this.container}},fR=class extends _t{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){let{data:{overlaidText:e,popupRef:n}}=this;if(!n&&this.hasPopupData&&this._createPopup(),this.container.classList.add("underlineAnnotation"),e){let r=document.createElement("u");r.classList.add("overlaidText"),r.textContent=e,this.container.append(r)}return this.container}},mR=class extends _t{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){let{data:{overlaidText:e,popupRef:n}}=this;if(!n&&this.hasPopupData&&this._createPopup(),this.container.classList.add("squigglyAnnotation"),e){let r=document.createElement("u");r.classList.add("overlaidText"),r.textContent=e,this.container.append(r)}return this.container}},pR=class extends _t{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){let{data:{overlaidText:e,popupRef:n}}=this;if(!n&&this.hasPopupData&&this._createPopup(),this.container.classList.add("strikeoutAnnotation"),e){let r=document.createElement("s");r.classList.add("overlaidText"),r.textContent=e,this.container.append(r)}return this.container}},LS=class extends _t{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0}),this.annotationEditorType=$e.STAMP}render(){return this.container.classList.add("stampAnnotation"),this.container.setAttribute("role","img"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this._editOnDoubleClick(),this.container}},gR=class extends _t{#e=null;constructor(e){super(e,{isRenderable:!0});let{file:n}=this.data;this.filename=n.filename,this.content=n.content,this.linkService.eventBus?.dispatch("fileattachmentannotation",{source:this,...n})}render(){this.container.classList.add("fileAttachmentAnnotation");let{container:e,data:n}=this,r;n.hasAppearance||n.fillAlpha===0?r=document.createElement("div"):(r=document.createElement("img"),r.src=`${this.imageResourcesPath}annotation-${/paperclip/i.test(n.name)?"paperclip":"pushpin"}.svg`,n.fillAlpha&&n.fillAlpha<1&&(r.style=`filter: opacity(${Math.round(n.fillAlpha*100)}%);`)),r.addEventListener("dblclick",this.#t.bind(this)),this.#e=r;let{isMac:i}=Ft.platform;return e.addEventListener("keydown",o=>{o.key==="Enter"&&(i?o.metaKey:o.ctrlKey)&&this.#t()}),!n.popupRef&&this.hasPopupData?this._createPopup():r.classList.add("popupTriggerArea"),e.append(r),e}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add("highlightArea")}#t(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}},vR=class t{#e=null;#t=null;#i=null;#n=new Map;#a=null;#r=null;constructor({div:e,accessibilityManager:n,annotationCanvasMap:r,annotationEditorUIManager:i,page:o,viewport:a,structTreeLayer:s,commentManager:l,linkService:c,annotationStorage:u}){this.div=e,this.#e=n,this.#t=r,this.#a=s||null,this.#r=c||null,this.#i=u||new Km,this.page=o,this.viewport=a,this.zIndex=0,this._annotationEditorUIManager=i,this._commentManager=l||null}hasEditableAnnotations(){return this.#n.size>0}async#o(e,n,r){let i=e.firstChild||e,o=i.id=`${kR}${n}`,a=await this.#a?.getAriaAttributes(o);if(a)for(let[s,l]of a)i.setAttribute(s,l);r?r.at(-1).container.after(e):(this.div.append(e),this.#e?.moveElementInDOM(this.div,e,i,!1))}async render(e){let{annotations:n}=e,r=this.div;Hs(r,this.viewport);let i=new Map,o={data:null,layer:r,linkService:this.#r,downloadManager:e.downloadManager,imageResourcesPath:e.imageResourcesPath||"",renderForms:e.renderForms!==!1,svgFactory:new pu,annotationStorage:this.#i,enableComment:e.enableComment===!0,enableScripting:e.enableScripting===!0,hasJSActions:e.hasJSActions,fieldObjects:e.fieldObjects,parent:this,elements:null};for(let a of n){if(a.noHTML)continue;let s=a.annotationType===Mt.POPUP;if(s){let u=i.get(a.id);if(!u)continue;o.elements=u}else if(a.rect[2]===a.rect[0]||a.rect[3]===a.rect[1])continue;o.data=a;let l=OS.create(o);if(!l.isRenderable)continue;if(!s&&a.popupRef){let u=i.get(a.popupRef);u?u.push(l):i.set(a.popupRef,[l])}let c=l.render();a.hidden&&(c.style.visibility="hidden"),await this.#o(c,a.id,o.elements),l.extraPopupElement?.popup?.renderCommentButton(),l._isEditable&&(this.#n.set(l.data.id,l),this._annotationEditorUIManager?.renderAnnotationElement(l))}this.#s()}async addLinkAnnotations(e){let n={data:null,layer:this.div,linkService:this.#r,svgFactory:new pu,parent:this};for(let r of e){r.borderStyle||=t._defaultBorderStyle,n.data=r;let i=OS.create(n);if(!i.isRenderable)continue;let o=i.render();await this.#o(o,r.id,null)}}update({viewport:e}){let n=this.div;this.viewport=e,Hs(n,{rotation:e.rotation}),this.#s(),n.hidden=!1}#s(){if(!this.#t)return;let e=this.div;for(let[n,r]of this.#t){let i=e.querySelector(`[data-annotation-id="${n}"]`);if(!i)continue;r.className="annotationContent";let{firstChild:o}=i;o?o.nodeName==="CANVAS"?o.replaceWith(r):o.classList.contains("annotationContent")?o.after(r):o.before(r):i.append(r);let a=this.#n.get(n);a&&(a._hasNoCanvas?(this._annotationEditorUIManager?.setMissingCanvas(n,i.id,r),a._hasNoCanvas=!1):a.canvas=r)}this.#t.clear()}getEditableAnnotations(){return Array.from(this.#n.values())}getEditableAnnotation(e){return this.#n.get(e)}addFakeAnnotation(e){let{div:n}=this,{id:r,rotation:i}=e,o=new eR({data:{id:r,rect:e.getPDFRect(),rotation:i},editor:e,layer:n,parent:this,enableComment:!!this._commentManager,linkService:this.#r,annotationStorage:this.#i}),a=o.render();return n.append(a),this.#e?.moveElementInDOM(n,a,a,!1),o.createOrUpdatePopup(),o}static get _defaultBorderStyle(){return Re(this,"_defaultBorderStyle",Object.freeze({width:1,rawWidth:1,style:cu.SOLID,dashArray:[3],horizontalCornerRadius:0,verticalCornerRadius:0}))}},rS=/\r\n?|\n/g,bR=class t extends at{#e="";#t=`${this.id}-editor`;#i=null;#n;_colorPicker=null;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){let e=t.prototype,n=o=>o.isEmpty(),r=Zs.TRANSLATE_SMALL,i=Zs.TRANSLATE_BIG;return Re(this,"_keyboardManager",new Vs([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],e.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],e.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],e._translateEmpty,{args:[-r,0],checker:n}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],e._translateEmpty,{args:[-i,0],checker:n}],[["ArrowRight","mac+ArrowRight"],e._translateEmpty,{args:[r,0],checker:n}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],e._translateEmpty,{args:[i,0],checker:n}],[["ArrowUp","mac+ArrowUp"],e._translateEmpty,{args:[0,-r],checker:n}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],e._translateEmpty,{args:[0,-i],checker:n}],[["ArrowDown","mac+ArrowDown"],e._translateEmpty,{args:[0,r],checker:n}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],e._translateEmpty,{args:[0,i],checker:n}]]))}static _type="freetext";static _editorType=$e.FREETEXT;constructor(e){super({...e,name:"freeTextEditor"}),this.color=e.color||t._defaultColor||at._defaultLineColor,this.#n=e.fontSize||t._defaultFontSize,this.annotationElementId||this._uiManager.a11yAlert("pdfjs-editor-freetext-added-alert")}static initialize(e,n){at.initialize(e,n);let r=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(r.getPropertyValue("--freetext-padding"))}static updateDefaultParams(e,n){switch(e){case je.FREETEXT_SIZE:t._defaultFontSize=n;break;case je.FREETEXT_COLOR:t._defaultColor=n;break}}updateParams(e,n){switch(e){case je.FREETEXT_SIZE:this.#a(n);break;case je.FREETEXT_COLOR:this.#r(n);break}}static get defaultPropertiesToUpdate(){return[[je.FREETEXT_SIZE,t._defaultFontSize],[je.FREETEXT_COLOR,t._defaultColor||at._defaultLineColor]]}get propertiesToUpdate(){return[[je.FREETEXT_SIZE,this.#n],[je.FREETEXT_COLOR,this.color]]}get toolbarButtons(){return this._colorPicker||=new CS(this),[["colorPicker",this._colorPicker]]}get colorType(){return je.FREETEXT_COLOR}#a(e){let n=i=>{this.editorDiv.style.fontSize=`calc(${i}px * var(--total-scale-factor))`,this.translate(0,-(i-this.#n)*this.parentScale),this.#n=i,this.#s()},r=this.#n;this.addCommands({cmd:n.bind(this,e),undo:n.bind(this,r),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:je.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}onUpdatedColor(){this.editorDiv.style.color=this.color,this._colorPicker?.update(this.color),super.onUpdatedColor()}#r(e){let n=i=>{this.color=i,this.onUpdatedColor()},r=this.color;this.addCommands({cmd:n.bind(this,e),undo:n.bind(this,r),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:je.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(e,n){this._uiManager.translateSelectedEditors(e,n,!0)}getInitialTranslation(){let e=this.parentScale;return[-t._internalPadding*e,-(t._internalPadding+this.#n)*e]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){if(!super.enableEditMode())return!1;this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),this.#i=new AbortController;let e=this._uiManager.combinedSignal(this.#i);return this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:e}),this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:e}),this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:e}),this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:e}),this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:e}),!0}disableEditMode(){return super.disableEditMode()?(this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",this.#t),this._isDraggable=!0,this.#i?.abort(),this.#i=null,this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add("freetextEditing"),!0):!1}focusin(e){this._focusEventsAllowed&&(super.focusin(e),e.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(e){this.width||(this.enableEditMode(),e&&this.editorDiv.focus(),this._initialOptions?.isCentered&&this.center(),this._initialOptions=null)}isEmpty(){return!this.editorDiv||this.editorDiv.innerText.trim()===""}remove(){this.isEditing=!1,this.parent&&(this.parent.setEditingState(!0),this.parent.div.classList.add("freetextEditing")),super.remove()}#o(){let e=[];this.editorDiv.normalize();let n=null;for(let r of this.editorDiv.childNodes)n?.nodeType===Node.TEXT_NODE&&r.nodeName==="BR"||(e.push(t.#c(r)),n=r);return e.join(`