turbollm 1.7.2 → 1.7.3
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.
- package/README.md +13 -11
- package/dist/chunk-TPYU5ZAX.js +175 -0
- package/dist/cli.js +2124 -1948
- package/dist/distiller-UROKYEBN.js +9 -0
- package/dist/webdist/assets/AgentEditPage-DLuckXeR.js +1 -0
- package/dist/webdist/assets/ChatScreen-BOZjtqGu.js +65 -0
- package/dist/webdist/assets/CustomizeScreen-DoVGTM4C.js +4 -0
- package/dist/webdist/assets/DeveloperScreen-BJ7m4ZxK.js +1 -0
- package/dist/webdist/assets/EnginesScreen-D3b9VNx0.js +7 -0
- package/dist/webdist/assets/{MessageBubble-COuZ8jTd.js → MessageBubble-mJwFfOab.js} +15 -16
- package/dist/webdist/assets/ModelDetailDialog-M2tPWvP4.js +1 -0
- package/dist/webdist/assets/ModelDirs-CaIf1TUh.js +1 -0
- package/dist/webdist/assets/{ModelsScreen-DncNvsj6.js → ModelsScreen--sPDS_sx.js} +2 -2
- package/dist/webdist/assets/SettingsScreen-lBpo_MAD.js +1 -0
- package/dist/webdist/assets/SkillEditPage-B5S9Gtlh.js +1 -0
- package/dist/webdist/assets/WorkspaceScreen-Cpm-gLG1.js +1 -0
- package/dist/webdist/assets/agent-api-B3GXwr4Y.js +1 -0
- package/dist/webdist/assets/{arc-BrQAHE5c.js → arc-CRcL8nar.js} +1 -1
- package/dist/webdist/assets/{architectureDiagram-3BPJPVTR-DzOwDk0E.js → architectureDiagram-3BPJPVTR-BmOKGMd0.js} +1 -1
- package/dist/webdist/assets/{blockDiagram-GPEHLZMM-Cbs2lNCh.js → blockDiagram-GPEHLZMM-C4vusmQ-.js} +1 -1
- package/dist/webdist/assets/{c4Diagram-AAUBKEIU-BAull9Yv.js → c4Diagram-AAUBKEIU-DdY0YXKs.js} +1 -1
- package/dist/webdist/assets/channel-BB6NPD_B.js +1 -0
- package/dist/webdist/assets/chat-api-DrMO_g5m.js +3 -0
- package/dist/webdist/assets/check-BLFw3EpE.js +1 -0
- package/dist/webdist/assets/chevron-left-CfyO2AXW.js +1 -0
- package/dist/webdist/assets/chevron-right--1OIa5uV.js +1 -0
- package/dist/webdist/assets/{chunk-2J33WTMH-B38k4sJL.js → chunk-2J33WTMH-DzCJsNN1.js} +1 -1
- package/dist/webdist/assets/{chunk-4BX2VUAB-VxAkYvb7.js → chunk-4BX2VUAB-BNPfO47j.js} +1 -1
- package/dist/webdist/assets/{chunk-55IACEB6-CAz9ZWyR.js → chunk-55IACEB6-_vELiE2B.js} +1 -1
- package/dist/webdist/assets/{chunk-727SXJPM-CvLX5ghS.js → chunk-727SXJPM-CsQCgUxY.js} +1 -1
- package/dist/webdist/assets/{chunk-AQP2D5EJ-CZ0fsnc1.js → chunk-AQP2D5EJ-G0waQ7sq.js} +1 -1
- package/dist/webdist/assets/{chunk-FMBD7UC4-tjHz_yw8.js → chunk-FMBD7UC4-CkNtvlrw.js} +1 -1
- package/dist/webdist/assets/{chunk-ND2GUHAM-DVSh5E5_.js → chunk-ND2GUHAM-DGnw4n1I.js} +1 -1
- package/dist/webdist/assets/{chunk-QZHKN3VN-D1rUM2SU.js → chunk-QZHKN3VN-BpJ4HH0V.js} +1 -1
- package/dist/webdist/assets/circle-check-ByN99MCf.js +1 -0
- package/dist/webdist/assets/classDiagram-4FO5ZUOK-DwCs4wFr.js +1 -0
- package/dist/webdist/assets/classDiagram-v2-Q7XG4LA2-DwCs4wFr.js +1 -0
- package/dist/webdist/assets/collapsible-B_M28W08.js +1 -0
- package/dist/webdist/assets/{common-BD4Wa3KL.js → common-Cy1uxtS_.js} +1 -1
- package/dist/webdist/assets/{copy-button-DypRNkqI.js → copy-button-DgYGL35x.js} +1 -1
- package/dist/webdist/assets/{cose-bilkent-S5V4N54A-DIUqY7o2.js → cose-bilkent-S5V4N54A-fol9bGNP.js} +1 -1
- package/dist/webdist/assets/{dagre-BM42HDAG-BzTcsgZ1.js → dagre-BM42HDAG-kyg4YiiE.js} +1 -1
- package/dist/webdist/assets/{diagram-2AECGRRQ-DanHH-W_.js → diagram-2AECGRRQ-CK_mQs9l.js} +1 -1
- package/dist/webdist/assets/{diagram-5GNKFQAL-DQ5sWHUL.js → diagram-5GNKFQAL-MBl66jsh.js} +1 -1
- package/dist/webdist/assets/{diagram-KO2AKTUF-Jqr_pLwu.js → diagram-KO2AKTUF-IxjaUqTu.js} +1 -1
- package/dist/webdist/assets/{diagram-LMA3HP47-BZ89-cp0.js → diagram-LMA3HP47-Cc_fuuLo.js} +1 -1
- package/dist/webdist/assets/{diagram-OG6HWLK6-cidBc5qa.js → diagram-OG6HWLK6-DvprGLFT.js} +1 -1
- package/dist/webdist/assets/{dialog-3hyZ9j4e.js → dialog-d6eLRBbl.js} +1 -1
- package/dist/webdist/assets/{erDiagram-TEJ5UH35-DEAKZN7b.js → erDiagram-TEJ5UH35-BEebeQO0.js} +1 -1
- package/dist/webdist/assets/{flowDiagram-I6XJVG4X-Cyx8gMzN.js → flowDiagram-I6XJVG4X--NtrYHee.js} +1 -1
- package/dist/webdist/assets/folder-input-C5Td4Oz0.js +1 -0
- package/dist/webdist/assets/{ganttDiagram-6RSMTGT7-CqXYW44d.js → ganttDiagram-6RSMTGT7-DOx3A2YH.js} +1 -1
- package/dist/webdist/assets/{gitGraphDiagram-PVQCEYII-0dv_zKYA.js → gitGraphDiagram-PVQCEYII-BEY69HKU.js} +1 -1
- package/dist/webdist/assets/index-B8H9eSFq.css +1 -0
- package/dist/webdist/assets/{index-DHmOrvk5.js → index-Tpho8qZ0.js} +1 -1
- package/dist/webdist/assets/index-tVO2x-Rw.js +10 -0
- package/dist/webdist/assets/{infoDiagram-5YYISTIA-PxeM6E3u.js → infoDiagram-5YYISTIA-C4X5I5eI.js} +1 -1
- package/dist/webdist/assets/{ishikawaDiagram-YF4QCWOH-BnNdTjj1.js → ishikawaDiagram-YF4QCWOH-BhUZzSmP.js} +1 -1
- package/dist/webdist/assets/{journeyDiagram-JHISSGLW-D3AHUGxz.js → journeyDiagram-JHISSGLW-R-rmKLZ-.js} +1 -1
- package/dist/webdist/assets/{kanban-definition-UN3LZRKU-YARl6SUt.js → kanban-definition-UN3LZRKU-DUcDGDiT.js} +1 -1
- package/dist/webdist/assets/{linear-CMEhaWGh.js → linear-Cbr5iYFb.js} +1 -1
- package/dist/webdist/assets/{mermaid.core-Dfl2pPvv.js → mermaid.core-DJVxydy1.js} +4 -4
- package/dist/webdist/assets/{mindmap-definition-RKZ34NQL-BojWC6jk.js → mindmap-definition-RKZ34NQL-BSOgl-Cn.js} +1 -1
- package/dist/webdist/assets/pencil-Blh_Q7or.js +1 -0
- package/dist/webdist/assets/personas-Dm0JD8kn.js +305 -0
- package/dist/webdist/assets/{pieDiagram-4H26LBE5-cjsdMtJJ.js → pieDiagram-4H26LBE5-BwQ854zg.js} +1 -1
- package/dist/webdist/assets/plus-D4IwdkJ3.js +1 -0
- package/dist/webdist/assets/{quadrantDiagram-W4KKPZXB-DYVcgQuL.js → quadrantDiagram-W4KKPZXB-BOQGjhZD.js} +1 -1
- package/dist/webdist/assets/{radix-BY-fjzwm.js → radix-DVGeLgPN.js} +2 -2
- package/dist/webdist/assets/{refresh-cw-Cco9RapO.js → refresh-cw-BVSLL9xa.js} +1 -1
- package/dist/webdist/assets/{requirementDiagram-4Y6WPE33-Dkj58nhB.js → requirementDiagram-4Y6WPE33-b3dNYy6K.js} +1 -1
- package/dist/webdist/assets/rotate-ccw-B7QiZxpr.js +1 -0
- package/dist/webdist/assets/{sankeyDiagram-5OEKKPKP-l3GwUuNl.js → sankeyDiagram-5OEKKPKP-C26ntsbR.js} +1 -1
- package/dist/webdist/assets/{save-CSISNMk8.js → save-DI4M5kP-.js} +1 -1
- package/dist/webdist/assets/{sequenceDiagram-3UESZ5HK-CWj1Dplo.js → sequenceDiagram-3UESZ5HK-Bp8i1DIR.js} +1 -1
- package/dist/webdist/assets/{skeleton-CBRf-twG.js → skeleton-D6toQA7p.js} +1 -1
- package/dist/webdist/assets/star-BCxsXqcv.js +1 -0
- package/dist/webdist/assets/{stateDiagram-AJRCARHV-zbnPRcoE.js → stateDiagram-AJRCARHV-CmZpIELB.js} +1 -1
- package/dist/webdist/assets/stateDiagram-v2-BHNVJYJU-CswfYrBO.js +1 -0
- package/dist/webdist/assets/{timeline-definition-PNZ67QCA-C_zAo1WZ.js → timeline-definition-PNZ67QCA-slNuxmat.js} +1 -1
- package/dist/webdist/assets/{trash-2-DJmVqx0w.js → trash-2-DGVXsIsP.js} +1 -1
- package/dist/webdist/assets/{vendor-W5GIuFcv.js → vendor-BE0HADM8.js} +1 -1
- package/dist/webdist/assets/{vennDiagram-CIIHVFJN-DxfcocQu.js → vennDiagram-CIIHVFJN-Lf4xPS3i.js} +1 -1
- package/dist/webdist/assets/{vram-Dn53zt7R.js → vram-DVAmNgRC.js} +1 -1
- package/dist/webdist/assets/{wardley-L42UT6IY-BnZ8BinJ.js → wardley-L42UT6IY-DbEeYkcX.js} +1 -1
- package/dist/webdist/assets/{wardleyDiagram-YWT4CUSO-DMk9z7hr.js → wardleyDiagram-YWT4CUSO-WNGbDcCj.js} +1 -1
- package/dist/webdist/assets/wrench-DzoqtmhJ.js +1 -0
- package/dist/webdist/assets/{xychartDiagram-2RQKCTM6-BUtTPXPF.js → xychartDiagram-2RQKCTM6-D2kBZ8cG.js} +1 -1
- package/dist/webdist/index.html +4 -4
- package/package.json +1 -1
- package/dist/webdist/assets/AgentsScreen-sMeMB3IQ.js +0 -2
- package/dist/webdist/assets/ChatScreen-rXB7PrWJ.js +0 -65
- package/dist/webdist/assets/CustomizeScreen-BBwvtk28.js +0 -4
- package/dist/webdist/assets/DeveloperScreen-fXV-qXB5.js +0 -1
- package/dist/webdist/assets/EnginesScreen-CrmYzhio.js +0 -7
- package/dist/webdist/assets/ModelDetailDialog-Dlt5uF3h.js +0 -1
- package/dist/webdist/assets/ModelDirs-BYN-DmHL.js +0 -1
- package/dist/webdist/assets/SettingsScreen-DXX3r4Ep.js +0 -1
- package/dist/webdist/assets/arrow-left-Dp4XRnbs.js +0 -1
- package/dist/webdist/assets/channel-Bt5-ol5R.js +0 -1
- package/dist/webdist/assets/check-jMeH6YsH.js +0 -1
- package/dist/webdist/assets/chevron-down-C5ZMFCtb.js +0 -1
- package/dist/webdist/assets/chevron-right-DNVnXbZ1.js +0 -1
- package/dist/webdist/assets/circle-check-qnghY_qF.js +0 -1
- package/dist/webdist/assets/circle-x-FM28MwOL.js +0 -1
- package/dist/webdist/assets/classDiagram-4FO5ZUOK-jfnUpxOr.js +0 -1
- package/dist/webdist/assets/classDiagram-v2-Q7XG4LA2-jfnUpxOr.js +0 -1
- package/dist/webdist/assets/collapsible-CwqYFc9v.js +0 -1
- package/dist/webdist/assets/index-B_WtFoLC.css +0 -1
- package/dist/webdist/assets/index-CriwC5VH.js +0 -10
- package/dist/webdist/assets/pencil-CS33zp9q.js +0 -1
- package/dist/webdist/assets/personas-CzcXp8zg.js +0 -75
- package/dist/webdist/assets/plus-BO3vGy6f.js +0 -1
- package/dist/webdist/assets/stateDiagram-v2-BHNVJYJU-Ukx8AVKZ.js +0 -1
- package/dist/webdist/assets/wrench-Di5WLTz2.js +0 -1
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
var xn=d=>{throw TypeError(d)};var hi=(d,t,e)=>t.has(d)||xn("Cannot "+e);var at=(d,t,e)=>(hi(d,t,"read from private field"),e?e.call(d):t.get(d)),zt=(d,t,e)=>t.has(d)?xn("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(d):t.set(d,e),St=(d,t,e,s)=>(hi(d,t,"write to private field"),s?s.call(d,e):t.set(d,e),e),$t=(d,t,e)=>(hi(d,t,"access private method"),e);var wn=(d,t,e,s)=>({set _(i){St(d,t,i,e)},get _(){return at(d,t,s)}});import{j as v}from"./radix-DVGeLgPN.js";import{r as R,u as va,c as Aa}from"./vendor-BE0HADM8.js";import{m as xa,d as wa,r as Sa,c as Ca,a as Ea,b as _a,e as ka,s as Ta,g as Ma,u as Pa,h as Ia,l as Da,i as Na,j as Fa,k as La,n as Sn,o as Ra,p as Oa}from"./chat-api-DrMO_g5m.js";import{g as oe,u as hr,a0 as jt,a as os,B as yt,t as it,A as ge,Q as Ai,I as Ba,L as ja,_ as Ha,a1 as Ua,p as za,b as $a,d as Ga,a2 as Va,m as Wa,v as Cn,X as As,f as Xa,a3 as Ya,a4 as Ka,a5 as qa,a6 as Qa}from"./index-tVO2x-Rw.js";import{f as dr,a as ur}from"./agent-api-B3GXwr4Y.js";import{f as fr,M as Ja,S as Za}from"./MessageBubble-mJwFfOab.js";import{A as En,a as _n,b as kn,c as Tn,d as Mn,f as Pn,h as In,i as Dn,D as Oi,j as Bi,k as ji,l as Re,m as pr,E as to,C as eo}from"./vram-DVAmNgRC.js";import{C as so,a as io,b as no}from"./collapsible-B_M28W08.js";import{C as ro}from"./chevron-right--1OIa5uV.js";import{C as ao}from"./chevron-left-CfyO2AXW.js";import{S as oo,a as gr,M as lo}from"./ModelDetailDialog-M2tPWvP4.js";import{F as co}from"./save-DI4M5kP-.js";import{F as Fs,D as ho,f as uo,a as fo,g as po}from"./dialog-d6eLRBbl.js";import{F as go}from"./folder-input-C5Td4Oz0.js";import{P as mr}from"./pencil-Blh_Q7or.js";import{T as br}from"./trash-2-DGVXsIsP.js";import{C as yr}from"./circle-check-ByN99MCf.js";import{C as mo}from"./check-BLFw3EpE.js";import{a as di,r as bo,c as yo,d as vo,g as Ao,e as xo}from"./personas-Dm0JD8kn.js";import{a as Nn}from"./copy-button-DgYGL35x.js";import"./refresh-cw-BVSLL9xa.js";import"./index-Tpho8qZ0.js";import"./rotate-ccw-B7QiZxpr.js";const wo=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],So=oe("arrow-down",wo);const Co=[["path",{d:"M12 18V5",key:"adv99a"}],["path",{d:"M15 13a4.17 4.17 0 0 1-3-4 4.17 4.17 0 0 1-3 4",key:"1e3is1"}],["path",{d:"M17.598 6.5A3 3 0 1 0 12 5a3 3 0 1 0-5.598 1.5",key:"1gqd8o"}],["path",{d:"M17.997 5.125a4 4 0 0 1 2.526 5.77",key:"iwvgf7"}],["path",{d:"M18 18a4 4 0 0 0 2-7.464",key:"efp6ie"}],["path",{d:"M19.967 17.483A4 4 0 1 1 12 18a4 4 0 1 1-7.967-.517",key:"1gq6am"}],["path",{d:"M6 18a4 4 0 0 1-2-7.464",key:"k1g0md"}],["path",{d:"M6.003 5.125a4 4 0 0 0-2.526 5.77",key:"q97ue3"}]],Eo=oe("brain",Co);const _o=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}],["path",{d:"M12 8v6",key:"1ib9pf"}],["path",{d:"M9 11h6",key:"1fldmi"}]],Fn=oe("message-square-plus",_o);const ko=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",key:"1miecu"}]],To=oe("paperclip",ko);const Mo=[["path",{d:"M3.714 3.048a.498.498 0 0 0-.683.627l2.843 7.627a2 2 0 0 1 0 1.396l-2.842 7.627a.498.498 0 0 0 .682.627l18-8.5a.5.5 0 0 0 0-.904z",key:"117uat"}],["path",{d:"M6 12h16",key:"s4cdu5"}]],Po=oe("send-horizontal",Mo);const Io=[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]],Do=oe("share-2",Io);const No=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],Fo=oe("square",No);const Lo=[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],Ro=oe("user-round",Lo),Pt=typeof process=="object"&&process+""=="[object process]"&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser"),te=[1/0,1/0,-1/0,-1/0],me=new Float32Array(te),xi=[.001,0,0,.001,0,0],ui=1.35,kt="http://www.w3.org/2000/svg",Tt={ANY:1,DISPLAY:2,PRINT:4,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},ie={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},Fe="pdfjs_internal_id_",ts="pdfjs_internal_editor_",G={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15,POPUP:16,SIGNATURE:101,COMMENT:102},X={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,INK_COLOR_AND_OPACITY:24,HIGHLIGHT_COLOR:31,HIGHLIGHT_THICKNESS:32,HIGHLIGHT_FREE:33,HIGHLIGHT_SHOW_ALL:34,DRAW_STEP:41},Oo={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},bt={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},Ps={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},ft={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,RICHMEDIA:27},Ie={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},Hs={ERRORS:0,WARNINGS:1,INFOS:5},Xt={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},We={moveTo:0,lineTo:1,curveTo:2,quadraticCurveTo:3,closePath:4},Bo={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let Us=Hs.WARNINGS;function jo(d){Number.isInteger(d)&&(Us=d)}function Ho(){return Us}function zs(d){Us>=Hs.INFOS&&console.info(`Info: ${d}`)}function V(d){Us>=Hs.WARNINGS&&console.warn(`Warning: ${d}`)}function K(d){throw new Error(d)}function ct(d,t){d||K(t)}function Uo(d){switch(d?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function vr(d,t=null,e=null){if(!d)return null;if(e&&typeof d=="string"&&(e.addDefaultProtocol&&d.startsWith("www.")&&d.match(/\./g)?.length>=2&&(d=`http://${d}`),e.tryConvertEncoding))try{d=Go(d)}catch{}const s=t?URL.parse(d,t):URL.parse(d);return Uo(s)?s:null}function Ar(d,t,e=!1){const s=URL.parse(d);return s?(s.hash=t,s.href):e&&vr(d,"http://example.com")?d.split("#",1)[0]+`${t?`#${t}`:""}`:""}function wi(d){return d.substring(d.lastIndexOf("/")+1)}function z(d,t,e,s=!1){return Object.defineProperty(d,t,{value:e,enumerable:!s,configurable:!0,writable:!1}),e}const Se=(function(){function t(e,s){this.message=e,this.name=s}return t.prototype=new Error,t.constructor=t,t})();class Si extends Se{constructor(t,e){super(t,"PasswordException"),this.code=e}}class fi extends Se{constructor(t,e){super(t,"UnknownErrorException"),this.details=e}}class Ci extends Se{constructor(t){super(t,"InvalidPDFException")}}class Ls extends Se{constructor(t,e,s){super(t,"ResponseException"),this.status=e,this.missing=s}}class zo extends Se{constructor(t){super(t,"FormatError")}}class re extends Se{constructor(t){super(t,"AbortException")}}function $o(d){(typeof d!="object"||d?.length===void 0)&&K("Invalid argument for bytesToString");const t=d.length,e=8192;if(t<e)return String.fromCharCode.apply(null,d);const s=[];for(let i=0;i<t;i+=e){const n=Math.min(i+e,t),r=d.subarray(i,n);s.push(String.fromCharCode.apply(null,r))}return s.join("")}function $s(d){typeof d!="string"&&K("Invalid argument for stringToBytes");const t=d.length,e=new Uint8Array(t);for(let s=0;s<t;++s)e[s]=d.charCodeAt(s)&255;return e}class J{static get isLittleEndian(){const t=new Uint8Array(4);t[0]=1;const e=new Uint32Array(t.buffer,0,1);return z(this,"isLittleEndian",e[0]===1)}static get isOffscreenCanvasSupported(){return z(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas<"u")}static get isImageDecoderSupported(){return z(this,"isImageDecoderSupported",typeof ImageDecoder<"u")}static get isFloat16ArraySupported(){return z(this,"isFloat16ArraySupported",typeof Float16Array<"u")}static get isSanitizerSupported(){return z(this,"isSanitizerSupported",typeof Sanitizer<"u")}static get platform(){const{platform:t,userAgent:e}=navigator;return z(this,"platform",{isAndroid:e.includes("Android"),isLinux:t.includes("Linux"),isMac:t.includes("Mac"),isWindows:t.includes("Win"),isFirefox:e.includes("Firefox")})}static get isCanvasFilterSupported(){let t;return this.isOffscreenCanvasSupported?t=new OffscreenCanvas(1,1).getContext("2d"):typeof document<"u"&&(t=document.createElement("canvas").getContext("2d")),z(this,"isCanvasFilterSupported",t?.filter!==void 0)}static get isAlphaColorInputSupported(){if(typeof document>"u")return z(this,"isAlphaColorInputSupported",!1);const t=document.createElement("input");return t.type="color",t.setAttribute("alpha",""),t.value="#ff000080",z(this,"isAlphaColorInputSupported",t.value!=="#ff0000")}static get isBackdropFilterSupported(){return z(this,"isBackdropFilterSupported",typeof CSS<"u"&&CSS.supports("backdrop-filter","blur(1px)"))}}class T{static get hexNums(){return z(this,"hexNums",Array.from(Array(256).keys(),t=>t.toString(16).padStart(2,"0")))}static makeHexColor(t,e,s){return`#${this.hexNums[t]}${this.hexNums[e]}${this.hexNums[s]}`}static transform(t,e){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],t[0]*e[4]+t[2]*e[5]+t[4],t[1]*e[4]+t[3]*e[5]+t[5]]}static multiplyByDOMMatrix(t,e){return[t[0]*e.a+t[2]*e.b,t[1]*e.a+t[3]*e.b,t[0]*e.c+t[2]*e.d,t[1]*e.c+t[3]*e.d,t[0]*e.e+t[2]*e.f+t[4],t[1]*e.e+t[3]*e.f+t[5]]}static applyTransform(t,e,s=0){const i=t[s],n=t[s+1];t[s]=i*e[0]+n*e[2]+e[4],t[s+1]=i*e[1]+n*e[3]+e[5]}static applyTransformToBezier(t,e,s=0){const i=e[0],n=e[1],r=e[2],a=e[3],o=e[4],l=e[5];for(let c=0;c<6;c+=2){const h=t[s+c],u=t[s+c+1];t[s+c]=h*i+u*r+o,t[s+c+1]=h*n+u*a+l}}static applyInverseTransform(t,e){const s=t[0],i=t[1],n=e[0]*e[3]-e[1]*e[2];t[0]=(s*e[3]-i*e[2]+e[2]*e[5]-e[4]*e[3])/n,t[1]=(-s*e[1]+i*e[0]+e[4]*e[1]-e[5]*e[0])/n}static axialAlignedBoundingBox(t,e,s){const i=e[0],n=e[1],r=e[2],a=e[3],o=e[4],l=e[5],c=t[0],h=t[1],u=t[2],f=t[3];let p=i*c+o,g=p,m=i*u+o,b=m,y=a*h+l,A=y,w=a*f+l,x=w;if(n!==0||r!==0){const S=n*c,E=n*u,_=r*h,k=r*f;p+=_,b+=_,m+=k,g+=k,y+=S,x+=S,w+=E,A+=E}s[0]=Math.min(s[0],p,m,g,b),s[1]=Math.min(s[1],y,w,A,x),s[2]=Math.max(s[2],p,m,g,b),s[3]=Math.max(s[3],y,w,A,x)}static inverseTransform(t){const e=t[0]*t[3]-t[1]*t[2];return[t[3]/e,-t[1]/e,-t[2]/e,t[0]/e,(t[2]*t[5]-t[4]*t[3])/e,(t[4]*t[1]-t[5]*t[0])/e]}static singularValueDecompose2dScale(t,e){const s=t[0],i=t[1],n=t[2],r=t[3],a=s**2+i**2,o=s*n+i*r,l=n**2+r**2,c=(a+l)/2,h=Math.sqrt(c**2-(a*l-o**2));e[0]=Math.sqrt(c+h||1),e[1]=Math.sqrt(c-h||1)}static normalizeRect(t){const e=t.slice(0);return t[0]>t[2]&&(e[0]=t[2],e[2]=t[0]),t[1]>t[3]&&(e[1]=t[3],e[3]=t[1]),e}static intersect(t,e){const s=Math.max(Math.min(t[0],t[2]),Math.min(e[0],e[2])),i=Math.min(Math.max(t[0],t[2]),Math.max(e[0],e[2]));if(s>i)return null;const n=Math.max(Math.min(t[1],t[3]),Math.min(e[1],e[3])),r=Math.min(Math.max(t[1],t[3]),Math.max(e[1],e[3]));return n>r?null:[s,n,i,r]}static pointBoundingBox(t,e,s){s[0]=Math.min(s[0],t),s[1]=Math.min(s[1],e),s[2]=Math.max(s[2],t),s[3]=Math.max(s[3],e)}static rectBoundingBox(t,e,s,i,n){n[0]=Math.min(n[0],t,s),n[1]=Math.min(n[1],e,i),n[2]=Math.max(n[2],t,s),n[3]=Math.max(n[3],e,i)}static#t(t,e,s,i,n,r,a,o,l,c){if(l<=0||l>=1)return;const h=1-l,u=l*l,f=u*l,p=h*(h*(h*t+3*l*e)+3*u*s)+f*i,g=h*(h*(h*n+3*l*r)+3*u*a)+f*o;c[0]=Math.min(c[0],p),c[1]=Math.min(c[1],g),c[2]=Math.max(c[2],p),c[3]=Math.max(c[3],g)}static#e(t,e,s,i,n,r,a,o,l,c,h,u){if(Math.abs(l)<1e-12){Math.abs(c)>=1e-12&&this.#t(t,e,s,i,n,r,a,o,-h/c,u);return}const f=c**2-4*h*l;if(f<0)return;const p=Math.sqrt(f),g=2*l;this.#t(t,e,s,i,n,r,a,o,(-c+p)/g,u),this.#t(t,e,s,i,n,r,a,o,(-c-p)/g,u)}static bezierBoundingBox(t,e,s,i,n,r,a,o,l){l[0]=Math.min(l[0],t,a),l[1]=Math.min(l[1],e,o),l[2]=Math.max(l[2],t,a),l[3]=Math.max(l[3],e,o),this.#e(t,s,n,a,e,i,r,o,3*(-t+3*(s-n)+a),6*(t-2*s+n),3*(s-t),l),this.#e(t,s,n,a,e,i,r,o,3*(-e+3*(i-r)+o),6*(e-2*i+r),3*(i-e),l)}}function Go(d){return decodeURIComponent(escape(d))}let pi=null,Ln=null;function Vo(d){return pi||(pi=/([\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,Ln=new Map([["ſt","ſt"]])),d.replaceAll(pi,(t,e,s)=>e?e.normalize("NFKC"):Ln.get(s))}function xr(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();const d=new Uint8Array(32);return crypto.getRandomValues(d),$o(d)}function Wo(d,t,e){if(!Array.isArray(e)||e.length<2)return!1;const[s,i,...n]=e;if(!d(s)&&!Number.isInteger(s)||!t(i))return!1;const r=n.length;let a=!0;switch(i.name){case"XYZ":if(r<2||r>3)return!1;break;case"Fit":case"FitB":return r===0;case"FitH":case"FitBH":case"FitV":case"FitBV":if(r>1)return!1;break;case"FitR":if(r!==4)return!1;a=!1;break;default:return!1}for(const o of n)if(!(typeof o=="number"||a&&o===null))return!1;return!0}const ls=()=>[],Hi=()=>new Map,Ei=()=>Object.create(null);function nt(d,t,e){return Math.min(Math.max(d,t),e)}class cs{constructor({viewBox:t,userUnit:e,scale:s,rotation:i,offsetX:n=0,offsetY:r=0,dontFlip:a=!1}){this.viewBox=t,this.userUnit=e,this.scale=s,this.rotation=i,this.offsetX=n,this.offsetY=r,s*=e;const o=(t[2]+t[0])/2,l=(t[3]+t[1])/2;let c,h,u,f;switch(i%=360,i<0&&(i+=360),i){case 180:c=-1,h=0,u=0,f=1;break;case 90:c=0,h=1,u=1,f=0;break;case 270:c=0,h=-1,u=-1,f=0;break;case 0:c=1,h=0,u=0,f=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}a&&(u=-u,f=-f);let p,g,m,b;c===0?(p=Math.abs(l-t[1])*s+n,g=Math.abs(o-t[0])*s+r,m=(t[3]-t[1])*s,b=(t[2]-t[0])*s):(p=Math.abs(o-t[0])*s+n,g=Math.abs(l-t[1])*s+r,m=(t[2]-t[0])*s,b=(t[3]-t[1])*s),this.transform=[c*s,h*s,u*s,f*s,p-c*s*o-u*s*l,g-h*s*o-f*s*l],this.width=m,this.height=b}get rawDims(){const t=this.viewBox;return z(this,"rawDims",{pageWidth:t[2]-t[0],pageHeight:t[3]-t[1],pageX:t[0],pageY:t[1]})}clone({scale:t=this.scale,rotation:e=this.rotation,offsetX:s=this.offsetX,offsetY:i=this.offsetY,dontFlip:n=!1}={}){return new cs({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:t,rotation:e,offsetX:s,offsetY:i,dontFlip:n})}convertToViewportPoint(t,e){const s=[t,e];return T.applyTransform(s,this.transform),s}convertToPdfPoint(t,e){const s=[t,e];return T.applyInverseTransform(s,this.transform),s}}class es{static textContent(t){const e=[],s={items:e,styles:Object.create(null)};function i(n){if(!n)return;let r=null;const a=n.name;if(a==="#text")r=n.value;else if(es.shouldBuildText(a))n?.attributes?.textContent?r=n.attributes.textContent:n.value&&(r=n.value);else return;if(r!==null&&e.push({str:r}),!!n.children)for(const o of n.children)i(o)}return i(t),s}static shouldBuildText(t){return!(t==="textarea"||t==="input"||t==="option"||t==="select")}}class wr{static setupStorage(t,e,s,i,n){const r=i.getValue(e,{value:null});switch(s.name){case"textarea":if(r.value!==null&&(t.textContent=r.value),n==="print")break;t.addEventListener("input",a=>{i.setValue(e,{value:a.target.value})});break;case"input":if(s.attributes.type==="radio"||s.attributes.type==="checkbox"){if(r.value===s.attributes.xfaOn?t.setAttribute("checked",!0):r.value===s.attributes.xfaOff&&t.removeAttribute("checked"),n==="print")break;t.addEventListener("change",a=>{i.setValue(e,{value:a.target.checked?a.target.getAttribute("xfaOn"):a.target.getAttribute("xfaOff")})})}else{if(r.value!==null&&t.setAttribute("value",r.value),n==="print")break;t.addEventListener("input",a=>{i.setValue(e,{value:a.target.value})})}break;case"select":if(r.value!==null){t.setAttribute("value",r.value);for(const a of s.children)a.attributes.value===r.value?a.attributes.selected=!0:Object.hasOwn(a.attributes,"selected")&&delete a.attributes.selected}t.addEventListener("input",a=>{const o=a.target.options,l=o.selectedIndex===-1?"":o[o.selectedIndex].value;i.setValue(e,{value:l})});break}}static setAttributes({html:t,element:e,storage:s=null,intent:i,linkService:n}){const{attributes:r}=e,a=t instanceof HTMLAnchorElement;r.type==="radio"&&(r.name=`${r.name}-${i}`);for(const[o,l]of Object.entries(r))if(l!=null)switch(o){case"class":l.length&&t.setAttribute(o,l.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",l);break;case"style":Object.assign(t.style,l);break;case"textContent":t.textContent=l;break;default:(!a||o!=="href"&&o!=="newWindow")&&t.setAttribute(o,l)}a&&n.addLinkAttributes(t,r.href,r.newWindow),s&&r.dataId&&this.setupStorage(t,r.dataId,e,s)}static render(t){const e=t.annotationStorage,s=t.linkService,i=t.xfaHtml,n=t.intent||"display",r=document.createElement(i.name);i.attributes&&this.setAttributes({html:r,element:i,intent:n,linkService:s});const a=n!=="richText",o=t.div;if(o.append(r),t.viewport){const h=`matrix(${t.viewport.transform.join(",")})`;o.style.transform=h}a&&o.setAttribute("class","xfaLayer xfaFont");const l=[];if(i.children.length===0){if(i.value){const h=document.createTextNode(i.value);r.append(h),a&&es.shouldBuildText(i.name)&&l.push(h)}return{textDivs:l}}const c=[[i,-1,r]];for(;c.length>0;){const[h,u,f]=c.at(-1);if(u+1===h.children.length){c.pop();continue}const p=h.children[++c.at(-1)[1]];if(p===null)continue;const{name:g}=p;if(g==="#text"){const b=document.createTextNode(p.value);l.push(b),f.append(b);continue}const m=p?.attributes?.xmlns?document.createElementNS(p.attributes.xmlns,g):document.createElement(g);if(f.append(m),p.attributes&&this.setAttributes({html:m,element:p,storage:e,intent:n,linkService:s}),p.children?.length>0)c.push([p,-1,m]);else if(p.value){const b=document.createTextNode(p.value);a&&es.shouldBuildText(g)&&l.push(b),m.append(b)}}for(const h of o.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))h.setAttribute("readOnly",!0);return{textDivs:l}}static update(t){const e=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=e,t.div.hidden=!1}static getPageViewport(t,{scale:e=1,rotation:s=0}){const{width:i,height:n}=t.attributes.style;return new cs({viewBox:[0,0,parseInt(i,10),parseInt(n,10)],userUnit:1,scale:e,rotation:s})}}class He{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function Ui(d,t="text"){if(Qe(d,document.baseURI)){const e=await fetch(d);if(!e.ok)throw new Error(e.statusText);switch(t){case"blob":return e.blob();case"bytes":return e.bytes();case"json":return e.json()}return e.text()}return new Promise((e,s)=>{const i=new XMLHttpRequest;i.open("GET",d,!0),i.responseType=t==="bytes"?"arraybuffer":t,i.onreadystatechange=()=>{if(i.readyState===XMLHttpRequest.DONE){if(i.status===200||i.status===0){switch(t){case"bytes":e(new Uint8Array(i.response));return;case"blob":case"json":e(i.response);return}e(i.responseText);return}s(new Error(i.statusText))}},i.send(null)})}class zi extends Se{constructor(t,e=0){super(t,"RenderingCancelledException"),this.extraDelay=e}}function Gs(d){const t=d.length;let e=0;for(;e<t&&d[e].trim()==="";)e++;return d.substring(e,e+5).toLowerCase()==="data:"}function $i(d){return typeof d=="string"&&/\.pdf$/i.test(d)}function Xo(d){return[d]=d.split(/[#?]/,1),wi(d)}function Yo(d,t="document.pdf"){if(typeof d!="string")return t;if(Gs(d))return V('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'),t;const s=(a=>{try{return new URL(a)}catch{}try{return new URL(decodeURIComponent(a))}catch{}try{return new URL(a,"https://foo.bar")}catch{}try{return new URL(decodeURIComponent(a),"https://foo.bar")}catch{}return null})(d);if(!s)return t;const i=a=>{try{let o=decodeURIComponent(a);return o.includes("/")&&(o=wi(o),o.length===4&&n.test(o))?a:o}catch{return a}},n=/\.pdf$/i,r=wi(s.pathname);if(n.test(r))return i(r);if(s.searchParams.size>0){const a=l=>[...l].findLast(c=>n.test(c)),o=a(s.searchParams.values())??a(s.searchParams.keys());if(o)return i(o)}if(s.hash){const o=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i.exec(s.hash);if(o)return i(o[0])}return t}class Rn{#t=new Map;times=[];time(t){this.#t.has(t)&&V(`Timer is already running for ${t}`),this.#t.set(t,Date.now())}timeEnd(t){this.#t.has(t)||V(`Timer has not been started for ${t}`),this.times.push({name:t,start:this.#t.get(t),end:Date.now()}),this.#t.delete(t)}toString(){const t=Math.max(...this.times.map(e=>e.name.length));return this.times.map(e=>`${e.name.padEnd(t)} ${e.end-e.start}ms
|
|
2
|
+
`).join("")}}function Qe(d,t){const e=t?URL.parse(d,t):URL.parse(d);return/https?:/.test(e?.protocol??"")}function Rt(d){d.preventDefault()}function lt(d){d.preventDefault(),d.stopPropagation()}class _i{static#t;static toDateObject(t){if(t instanceof Date)return t;if(!t||typeof t!="string")return null;this.#t||=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+\\-])?(\\d{2})?'?(\\d{2})?'?");const e=this.#t.exec(t);if(!e)return null;const s=parseInt(e[1],10);let i=parseInt(e[2],10);i=i>=1&&i<=12?i-1:0;let n=parseInt(e[3],10);n=n>=1&&n<=31?n:1;let r=parseInt(e[4],10);r=r>=0&&r<=23?r:0;let a=parseInt(e[5],10);a=a>=0&&a<=59?a:0;let o=parseInt(e[6],10);o=o>=0&&o<=59?o:0;const l=e[7]||"Z";let c=parseInt(e[8],10);c=c>=0&&c<=23?c:0;let h=parseInt(e[9],10)||0;return h=h>=0&&h<=59?h:0,l==="-"?(r+=c,a+=h):l==="+"&&(r-=c,a-=h),new Date(Date.UTC(s,i,n,r,a,o))}}function hs(d){if(d.startsWith("#")){const e=d.slice(1);return[parseInt(e.slice(0,2),16),parseInt(e.slice(2,4),16),parseInt(e.slice(4,6),16),e.length>=8?parseInt(e.slice(6,8),16)/255:1]}if(d.startsWith("rgb(")){const[e,s,i]=d.slice(4,-1).split(",").map(n=>parseInt(n,10));return[e,s,i,1]}if(d.startsWith("rgba(")){const e=d.slice(5,-1).split(",");return[parseInt(e[0],10),parseInt(e[1],10),parseInt(e[2],10),parseFloat(e[3])]}const t=d.match(/^color\(srgb\s+([\d.]+)\s+([\d.]+)\s+([\d.]+)(?:\s*\/\s*([\d.]+|none))?\)$/);return t?[Math.round(parseFloat(t[1])*255),Math.round(parseFloat(t[2])*255),Math.round(parseFloat(t[3])*255),t[4]!==void 0&&t[4]!=="none"?parseFloat(t[4]):1]:null}function ds(d){const t=hs(d);return t?t.slice(0,3):(V(`Not a valid color format: "${d}"`),[0,0,0])}function Ko(d){const t=document.createElement("span");t.style.visibility="hidden",t.style.colorScheme="only light",document.body.append(t);for(const e of d.keys()){t.style.color=e;const s=window.getComputedStyle(t).color;d.set(e,ds(s))}t.remove()}function et(d){const{a:t,b:e,c:s,d:i,e:n,f:r}=d.getTransform();return[t,e,s,i,n,r]}function Gt(d){const{a:t,b:e,c:s,d:i,e:n,f:r}=d.getTransform().invertSelf();return[t,e,s,i,n,r]}function xe(d,t,e=!1,s=!0){if(t instanceof cs){const{pageWidth:i,pageHeight:n}=t.rawDims,{style:r}=d,a=`round(down, var(--total-scale-factor) * ${i}px, var(--scale-round-x))`,o=`round(down, var(--total-scale-factor) * ${n}px, var(--scale-round-y))`;!e||t.rotation%180===0?(r.width=a,r.height=o):(r.width=o,r.height=a)}s&&d.setAttribute("data-main-rotation",t.rotation)}class Kt{constructor(){const{pixelRatio:t}=Kt;this.sx=t,this.sy=t}get scaled(){return this.sx!==1||this.sy!==1}get symmetric(){return this.sx===this.sy}limitCanvas(t,e,s,i,n=-1){let r=1/0,a=1/0,o=1/0;s=Kt.capPixels(s,n),s>0&&(r=Math.sqrt(s/(t*e))),i!==-1&&(a=i/t,o=i/e);const l=Math.min(r,a,o);return this.sx>l||this.sy>l?(this.sx=l,this.sy=l,!0):!1}static get pixelRatio(){return globalThis.devicePixelRatio||1}static capPixels(t,e){if(e>=0){const s=Math.ceil(window.screen.availWidth*window.screen.availHeight*this.pixelRatio**2*(1+e/100));return t>0?Math.min(t,s):s}return t}}const ki=["image/apng","image/avif","image/bmp","image/gif","image/jpeg","image/png","image/svg+xml","image/webp","image/x-icon"];class qo{static get isDarkMode(){return z(this,"isDarkMode",!!window?.matchMedia?.("(prefers-color-scheme: dark)").matches)}}class Qo{static get commentForegroundColor(){const t=document.createElement("span");t.classList.add("comment","sidebar");const{style:e}=t;e.width=e.height="0",e.display="none",e.color="var(--comment-fg-color)",document.body.append(t);const{color:s}=window.getComputedStyle(t);return t.remove(),z(this,"commentForegroundColor",ds(s))}}function Jo(d,t){t=nt(t??1,0,1);const e=255*(1-t);return d.map(s=>Math.round(s*t+e))}function On(d,t){const e=d[0]/255,s=d[1]/255,i=d[2]/255,n=Math.max(e,s,i),r=Math.min(e,s,i),a=(n+r)/2;if(n===r)t[0]=t[1]=0;else{const o=n-r;switch(t[1]=a<.5?o/(n+r):o/(2-n-r),n){case e:t[0]=((s-i)/o+(s<i?6:0))*60;break;case s:t[0]=((i-e)/o+2)*60;break;case i:t[0]=((e-s)/o+4)*60;break}}t[2]=a}function Ti(d,t){const e=d[0],s=d[1],i=d[2],n=(1-Math.abs(2*i-1))*s,r=n*(1-Math.abs(e/60%2-1)),a=i-n/2;switch(Math.floor(e/60)){case 0:t[0]=n+a,t[1]=r+a,t[2]=a;break;case 1:t[0]=r+a,t[1]=n+a,t[2]=a;break;case 2:t[0]=a,t[1]=n+a,t[2]=r+a;break;case 3:t[0]=a,t[1]=r+a,t[2]=n+a;break;case 4:t[0]=r+a,t[1]=a,t[2]=n+a;break;case 5:case 6:t[0]=n+a,t[1]=a,t[2]=r+a;break}}function Bn(d){return d<=.03928?d/12.92:((d+.055)/1.055)**2.4}function jn(d,t,e){Ti(d,e),e.map(Bn);const s=.2126*e[0]+.7152*e[1]+.0722*e[2];Ti(t,e),e.map(Bn);const i=.2126*e[0]+.7152*e[1]+.0722*e[2];return s>i?(s+.05)/(i+.05):(i+.05)/(s+.05)}const Hn=new Map;function Zo(d,t){const e=d[0]+d[1]*256+d[2]*65536+t[0]*16777216+t[1]*4294967296+t[2]*1099511627776;let s=Hn.get(e);if(s)return s;const i=new Float32Array(9),n=i.subarray(0,3),r=i.subarray(3,6);On(d,r);const a=i.subarray(6,9);On(t,a);const o=a[2]<.5,l=o?12:4.5;if(r[2]=o?Math.sqrt(r[2]):1-Math.sqrt(1-r[2]),jn(r,a,n)<l){let c,h;o?(c=r[2],h=1):(c=0,h=r[2]);const u=.005;for(;h-c>u;){const f=r[2]=(c+h)/2;o===jn(r,a,n)<l?c=f:h=f}r[2]=o?h:c}return Ti(r,n),s=T.makeHexColor(Math.round(n[0]*255),Math.round(n[1]*255),Math.round(n[2]*255)),Hn.set(e,s),s}function Sr({html:d,dir:t,className:e},s){const i=document.createDocumentFragment();if(typeof d=="string"){const n=document.createElement("p");n.dir=t||"auto";const r=d.split(/\r\n?|\n/);for(let a=0,o=r.length;a<o;++a){const l=r[a];n.append(document.createTextNode(l)),a<o-1&&n.append(document.createElement("br"))}i.append(n)}else wr.render({xfaHtml:d,div:i,intent:"richText"});i.firstElementChild.classList.add("richText",e),s.append(i)}function Cr(d){const t=new Path2D;if(!d)return t;for(let e=0,s=d.length;e<s;)switch(d[e++]){case We.moveTo:t.moveTo(d[e++],d[e++]);break;case We.lineTo:t.lineTo(d[e++],d[e++]);break;case We.curveTo:t.bezierCurveTo(d[e++],d[e++],d[e++],d[e++],d[e++],d[e++]);break;case We.quadraticCurveTo:t.quadraticCurveTo(d[e++],d[e++],d[e++],d[e++]);break;case We.closePath:t.closePath();break;default:V(`Unrecognized drawing path operator: ${d[e-1]}`);break}return t}class Je{#t=null;#e=null;#s;#i=null;#n=null;#a=null;#r=null;#o=null;static#h=null;constructor(t){this.#s=t,Je.#h||=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(){const t=this.#t=document.createElement("div");t.classList.add("editToolbar","hidden"),t.setAttribute("role","toolbar");const e=this.#s._uiManager._signal;e instanceof AbortSignal&&!e.aborted&&(t.addEventListener("contextmenu",Rt,{signal:e}),t.addEventListener("pointerdown",Je.#l,{signal:e}));const s=this.#i=document.createElement("div");s.className="buttons",t.append(s);const i=this.#s.toolbarPosition;if(i){const{style:n}=t,r=this.#s._uiManager.direction==="ltr"?1-i[0]:i[0];n.insetInlineEnd=`${100*r}%`,n.top=`calc(${100*i[1]}% + var(--editor-toolbar-vert-offset))`}return t}get div(){return this.#t}static#l(t){t.stopPropagation()}#u(t){this.#s._focusEventsAllowed=!1,lt(t)}#d(t){this.#s._focusEventsAllowed=!0,lt(t)}#p(t){const e=this.#s._uiManager._signal;return!(e instanceof AbortSignal)||e.aborted?!1:(t.addEventListener("focusin",this.#u.bind(this),{capture:!0,signal:e}),t.addEventListener("focusout",this.#d.bind(this),{capture:!0,signal:e}),t.addEventListener("contextmenu",Rt,{signal:e}),!0)}hide(){this.#t.classList.add("hidden"),this.#e?.hideDropdown()}show(){this.#t.classList.remove("hidden"),this.#n?.shown(),this.#a?.shown()}addDeleteButton(){const{editorType:t,_uiManager:e}=this.#s,s=document.createElement("button");s.classList.add("basic","deleteButton"),s.tabIndex=0,s.setAttribute("data-l10n-id",Je.#h[t]),this.#p(s)&&s.addEventListener("click",i=>{e.delete()},{signal:e._signal}),this.#i.append(s)}get#m(){const t=document.createElement("div");return t.className="divider",t}async addAltText(t){const e=await t.render();this.#p(e),this.#i.append(e,this.#m),this.#n=t}addComment(t,e=null){if(this.#a)return;const s=t.renderForToolbar();if(!s)return;this.#p(s);const i=this.#r=this.#m;e?(this.#i.insertBefore(s,e),this.#i.insertBefore(i,e)):this.#i.append(s,i),this.#a=t,t.toolbar=this}addColorPicker(t){if(this.#e)return;this.#e=t;const e=t.renderButton();this.#p(e),this.#i.append(e,this.#m)}async addEditSignatureButton(t){const e=this.#o=await t.renderEditButton(this.#s);this.#p(e),this.#i.append(e,this.#m)}removeButton(t){t==="comment"&&(this.#a?.removeToolbarCommentButton(),this.#a=null,this.#r?.remove(),this.#r=null)}async addButton(t,e){switch(t){case"colorPicker":e&&this.addColorPicker(e);break;case"altText":e&&await this.addAltText(e);break;case"editSignature":e&&await this.addEditSignatureButton(e);break;case"delete":this.addDeleteButton();break;case"comment":e&&this.addComment(e);break}}async addButtonBefore(t,e,s){if(!e&&t==="comment")return;const i=this.#i.querySelector(s);i&&t==="comment"&&this.addComment(e,i)}updateEditSignatureButton(t){this.#o&&(this.#o.title=t)}remove(){this.#t.remove(),this.#e?.destroy(),this.#e=null}}class tl{#t=null;#e=null;#s;constructor(t){this.#s=t}#i(){const t=this.#e=document.createElement("div");t.className="editToolbar",t.setAttribute("role","toolbar");const e=this.#s._signal;e instanceof AbortSignal&&!e.aborted&&t.addEventListener("contextmenu",Rt,{signal:e});const s=this.#t=document.createElement("div");return s.className="buttons",t.append(s),this.#s.hasCommentManager()&&this.#a("commentButton","pdfjs-comment-floating-button","pdfjs-comment-floating-button-label",()=>{this.#s.commentSelection("floating_button")}),this.#a("highlightButton","pdfjs-highlight-floating-button1","pdfjs-highlight-floating-button-label",()=>{this.#s.highlightSelection("floating_button")}),t}#n(t,e){let s=0,i=0;for(const n of t){const r=n.y+n.height;if(r<s)continue;const a=n.x+(e?n.width:0);if(r>s){i=a,s=r;continue}e?a>i&&(i=a):a<i&&(i=a)}return[e?1-i:i,s]}show(t,e,s){const[i,n]=this.#n(e,s),{style:r}=this.#e||=this.#i();t.append(this.#e),r.insetInlineEnd=`${100*i}%`,r.top=`calc(${100*n}% + var(--editor-toolbar-vert-offset))`}hide(){this.#e.remove()}#a(t,e,s,i){const n=document.createElement("button");n.classList.add("basic",t),n.tabIndex=0,n.setAttribute("data-l10n-id",e);const r=document.createElement("span");n.append(r),r.className="visuallyHidden",r.setAttribute("data-l10n-id",s);const a=this.#s._signal;a instanceof AbortSignal&&!a.aborted&&(n.addEventListener("contextmenu",Rt,{signal:a}),n.addEventListener("click",i,{signal:a})),this.#t.append(n)}}const el="068f09d6-5b37-4f77-a97a-f8ff4f253b68",gi=Object.freeze({internal:el});function Er(d,t,e){for(const s of e)t.addEventListener(s,d[s].bind(d))}class Q{static#t=NaN;static#e=null;static#s=NaN;static#i=null;static initializeAndAddPointerId(t){(Q.#e||=new Set).add(t)}static setPointer(t,e){Q.#t||=e,Q.#i??=t}static setTimeStamp(t){Q.#s=t}static isSamePointerId(t){return Q.#t===t}static isSamePointerIdOrRemove(t){return Q.#t===t?!0:(Q.#e?.delete(t),!1)}static isSamePointerType(t){return Q.#i===t}static isInitializedAndDifferentPointerType(t){return Q.#i!==null&&!Q.isSamePointerType(t)}static isSameTimeStamp(t){return Q.#s===t}static isUsingMultiplePointers(){return Q.#e?.size>=1}static clearPointerType(){Q.#i=null}static clearPointerIds(){Q.#t=NaN,Q.#e=null}static clearTimeStamp(){Q.#s=NaN}}class sl{#t=0;get id(){return`${ts}${this.#t++}`}}class Gi{#t=xr();#e=0;#s=null;static get _isSVGFittingCanvas(){const t=`data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="${kt}"><rect width="1" height="1" style="fill:red;"/></svg>`,s=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),i=new Image;i.src=t;const n=i.decode().then(()=>(s.drawImage(i,0,0,1,1,0,0,1,3),new Uint32Array(s.getImageData(0,0,1,1).data.buffer)[0]===0));return z(this,"_isSVGFittingCanvas",n)}async#i(t,e){this.#s||=new Map;let s=this.#s.get(t);if(s===null)return null;if(s?.bitmap)return s.refCounter+=1,s;try{s||={bitmap:null,id:`image_${this.#t}_${this.#e++}`,refCounter:0,isSvg:!1};let i;if(typeof e=="string"?(s.url=e,i=await Ui(e,"blob")):e instanceof File?i=s.file=e:e instanceof Blob&&(i=e),i.type==="image/svg+xml"){const n=Gi._isSVGFittingCanvas,r=new FileReader,a=new Image,o=new Promise((l,c)=>{a.onload=()=>{s.bitmap=a,s.isSvg=!0,l()},r.onload=async()=>{const h=s.svgUrl=r.result;a.src=await n?`${h}#svgView(preserveAspectRatio(none))`:h},a.onerror=r.onerror=c});r.readAsDataURL(i),await o}else s.bitmap=await createImageBitmap(i);s.refCounter=1}catch(i){V(i),s=null}return this.#s.set(t,s),s&&this.#s.set(s.id,s),s}async getFromFile(t){const{lastModified:e,name:s,size:i,type:n}=t;return this.#i(`${e}_${s}_${i}_${n}`,t)}async getFromUrl(t){return this.#i(t,t)}async getFromBlob(t,e){const s=await e;return this.#i(t,s)}async getFromId(t){this.#s||=new Map;const e=this.#s.get(t);if(!e)return null;if(e.bitmap)return e.refCounter+=1,e;if(e.file)return this.getFromFile(e.file);if(e.blobPromise){const{blobPromise:s}=e;return delete e.blobPromise,this.getFromBlob(e.id,s)}return this.getFromUrl(e.url)}getFromCanvas(t,e){this.#s||=new Map;let s=this.#s.get(t);if(s?.bitmap)return s.refCounter+=1,s;const i=new OffscreenCanvas(e.width,e.height);return i.getContext("2d").drawImage(e,0,0),s={bitmap:i.transferToImageBitmap(),id:`image_${this.#t}_${this.#e++}`,refCounter:1,isSvg:!1},this.#s.set(t,s),this.#s.set(s.id,s),s}getSvgUrl(t){const e=this.#s.get(t);return e?.isSvg?e.svgUrl:null}deleteId(t){this.#s||=new Map;const e=this.#s.get(t);if(!e||(e.refCounter-=1,e.refCounter!==0))return;const{bitmap:s}=e;if(!e.url&&!e.file){const i=new OffscreenCanvas(s.width,s.height);i.getContext("bitmaprenderer").transferFromImageBitmap(s),e.blobPromise=i.convertToBlob()}s.close?.(),e.bitmap=null}isValidId(t){return t.startsWith(`image_${this.#t}_`)}}class il{#t=[];#e=!1;#s;#i=-1;constructor(t=128){this.#s=t}add({cmd:t,undo:e,post:s,mustExec:i,type:n=NaN,overwriteIfSameType:r=!1,keepUndo:a=!1}){if(i&&t(),this.#e)return;const o={cmd:t,undo:e,post:s,type:n};if(this.#i===-1){this.#t.length>0&&(this.#t.length=0),this.#i=0,this.#t.push(o);return}if(r&&this.#t[this.#i].type===n){a&&(o.undo=this.#t[this.#i].undo),this.#t[this.#i]=o;return}const l=this.#i+1;l===this.#s?this.#t.splice(0,1):(this.#i=l,l<this.#t.length&&this.#t.splice(l)),this.#t.push(o)}undo(){if(this.#i===-1)return;this.#e=!0;const{undo:t,post:e}=this.#t[this.#i];t(),e?.(),this.#e=!1,this.#i-=1}redo(){if(this.#i<this.#t.length-1){this.#i+=1,this.#e=!0;const{cmd:t,post:e}=this.#t[this.#i];t(),e?.(),this.#e=!1}}hasSomethingToUndo(){return this.#i!==-1}hasSomethingToRedo(){return this.#i<this.#t.length-1}cleanType(t){if(this.#i!==-1){for(let e=this.#i;e>=0;e--)if(this.#t[e].type!==t){this.#t.splice(e+1,this.#i-e),this.#i=e;return}this.#t.length=0,this.#i=-1}}destroy(){this.#t=null}}class It{static ALT=1;static CTRL=2;static META=4;static SHIFT=8;constructor(t){this.callbacks=new Map;const{isMac:e}=J.platform;for(const[s,i,n={}]of t){const r=s.some(a=>a.startsWith("mac+"));for(const a of s){let o=a;if(r){const h=a.startsWith("mac+");if(e!==h)continue;h&&(o=a.slice(4))}const[l,c]=It.#t(o);l!==null&&this.callbacks.getOrInsertComputed(l,ls).push({callback:i,options:n,modifiers:c})}}}static#t(t){let e=null,s=0;for(let i of t.split("+")){if(i=i.trim(),!i)continue;const n=i.toUpperCase(),r=It[n];if(r){s|=r;continue}if(e!==null){V(`KeyboardManager: multiple keys in shortcut "${t}"`);break}e=n==="SPACE"?" ":i}return e===null&&V(`KeyboardManager: no key found in shortcut "${t}"`),[e,s]}static#e(t){const e=/^(?:Key([A-Z])|(?:Digit|Numpad)(\d))$/.exec(t);return e?e[1]?.toLowerCase()??e[2]:null}exec(t,e){let s=this.callbacks.get(e.key);if(!s){if(/^[a-z]$/i.test(e.key))return;const c=It.#e(e.code);if(c===null||c===e.key||(s=this.callbacks.get(c),!s))return}const i=(e.altKey?It.ALT:0)|(e.ctrlKey?It.CTRL:0)|(e.metaKey?It.META:0)|(e.shiftKey?It.SHIFT:0),n=s.find(c=>c.modifiers===i);if(!n)return;const{callback:r,options:{bubbles:a=!1,args:o=[],checker:l=null}}=n;l&&!l(t,e)||(r.bind(t,...o,e)(),a||lt(e))}}class Vi{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){const t=new Map([["CanvasText",null],["Canvas",null]]);return Ko(t),z(this,"_colors",t)}convert(t){const e=ds(t);if(!window.matchMedia("(forced-colors: active)").matches)return e;for(const[s,i]of this._colors)if(i.every((n,r)=>n===e[r]))return Vi._colorsMapping.get(s);return e}getHexCode(t){const e=this._colors.get(t);return e?T.makeHexColor(...e):t}}class ae{#t=new AbortController;#e=null;#s=null;#i=new Map;#n=new Map;#a=null;#r=null;#o=null;#h=null;#l=new il;#u=null;#d=null;#p=null;#m=0;#g=new Set;#c=null;#f=null;#y=new Set;_editorUndoBar=null;#v=!1;#b=!1;#S=!1;#C=null;#A=null;#E=null;#w=null;#k=!1;#M=null;#P=new sl;#T=!1;#N=!1;#F=!1;#D=null;#L=null;#O=null;#j=null;#V=null;#_=G.NONE;#x=new Set;#R=null;#U=null;#$=null;#K=null;#X=null;#Y={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#B=[0,0];#G=null;#W=null;#Z=null;#tt=null;#H=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=ae.prototype,e=r=>r.#W.contains(document.activeElement)&&document.activeElement.tagName!=="BUTTON"&&r.hasSomethingToControl(),s=(r,{target:a})=>{if(a instanceof HTMLInputElement){const{type:o}=a;return o!=="text"&&o!=="number"}return!0},i=this.TRANSLATE_SMALL,n=this.TRANSLATE_BIG;return z(this,"_keyboardManager",new It([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:s}],[["ctrl+z","mac+meta+z"],t.undo,{checker:s}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:s}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],t.delete,{checker:s}],[["Enter"],t.addNewEditorFromKeyboard,{checker:(r,{target:a})=>!(a instanceof HTMLButtonElement)&&r.#W.contains(a)&&!r.isEnterHandled}],[["Space"],t.addNewEditorFromKeyboard,{checker:(r,{target:a})=>!(a instanceof HTMLButtonElement)&&r.#W.contains(document.activeElement)}],[["Escape"],t.unselectAll],[["ArrowLeft"],t.translateSelectedEditors,{args:[-i,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-n,0],checker:e}],[["ArrowRight"],t.translateSelectedEditors,{args:[i,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[n,0],checker:e}],[["ArrowUp"],t.translateSelectedEditors,{args:[0,-i],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-n],checker:e}],[["ArrowDown"],t.translateSelectedEditors,{args:[0,i],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,n],checker:e}]]))}constructor(t,e,s,i,n,r,a,o,l,c,h,u,f,p,g,m){const b=this._signal=this.#t.signal;this.#W=t,this.#Z=e,this.#tt=s,this.#r=i,this.#u=n,this.#U=r,this.#X=o,this._eventBus=a;const y={signal:b,...gi};a.on("editingaction",this.onEditingAction.bind(this),y),a.on("pagechanging",this.onPageChanging.bind(this),y),a.on("scalechanging",this.onScaleChanging.bind(this),y),a.on("rotationchanging",this.onRotationChanging.bind(this),y),a.on("setpreference",this.onSetPreference.bind(this),y),a.on("switchannotationeditorparams",A=>this.updateParams(A.type,A.value),y),window.addEventListener("pointerdown",()=>{this.#N=!0},{capture:!0,signal:b}),window.addEventListener("pointerup",()=>{this.#N=!1},{capture:!0,signal:b}),window.addEventListener("beforeunload",this.#rt.bind(this),{capture:!0,signal:b}),this.#lt(),this.#pt(),this.#st(),this.#o=o.annotationStorage,this.#C=o.filterFactory,this.#$=l,this.#w=c||null,this.#v=h,this.#b=u,this.#S=f,this.#V=p||null,this.viewParameters={realScale:He.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1,this._editorUndoBar=g||null,this._supportsPinchToZoom=m!==!1,n?.setSidebarUiManager(this)}destroy(){this.#H?.resolve(),this.#H=null,this.#t?.abort(),this.#t=null,this._signal=null;for(const t of this.#n.values())t.destroy();this.#n.clear(),this.#i.clear(),this.#y.clear(),this.#j?.clear(),this.#e=null,this.#x.clear(),this.#l.destroy(),this.#r?.destroy(),this.#u?.destroy(),this.#U?.destroy(),this.#M?.hide(),this.#M=null,this.#O?.destroy(),this.#O=null,this.#s=null,this.#A&&(clearTimeout(this.#A),this.#A=null),this.#G&&(clearTimeout(this.#G),this.#G=null),this._editorUndoBar?.destroy(),this.#X=null}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return this.#V}get useNewAltTextFlow(){return this.#b}get useNewAltTextWhenAddingImage(){return this.#S}get hcmFilter(){return z(this,"hcmFilter",this.#$?this.#C.addHCMFilter(this.#$.foreground,this.#$.background):"none")}get direction(){return z(this,"direction",getComputedStyle(this.#W).direction)}get _highlightColors(){return z(this,"_highlightColors",this.#w?new Map(this.#w.split(",").map(t=>(t=t.split("=").map(e=>e.trim()),t[1]=t[1].toUpperCase(),t))):null)}get highlightColors(){const{_highlightColors:t}=this;if(!t)return z(this,"highlightColors",null);const e=new Map,s=!!this.#$;for(const[i,n]of t){const r=i.endsWith("_HCM");if(s&&r){e.set(i.replace("_HCM",""),n);continue}!s&&!r&&e.set(i,n)}return z(this,"highlightColors",e)}get highlightColorNames(){return z(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,t=>t.reverse())):null)}getNonHCMColor(t){if(!this._highlightColors)return t;const e=this.highlightColorNames.get(t);return this._highlightColors.get(e)||t}getNonHCMColorName(t){return this.highlightColorNames.get(t)||t}setCurrentDrawingSession(t){t?(this.unselectAll(),this.disableUserSelect(!0)):this.disableUserSelect(!1),this.#p=t}setMainHighlightColorPicker(t){this.#O=t}editAltText(t,e=!1){this.#r?.editAltText(this,t,e)}hasCommentManager(){return!!this.#u}editComment(t,e,s,i){this.#u?.showDialog(this,t,e,s,i)}selectComment(t,e){this.#n.get(t)?.getEditorByUID(e)?.toggleComment(!0,!0)}updateComment(t){this.#u?.updateComment(t.getData())}updatePopupColor(t){this.#u?.updatePopupColor(t)}removeComment(t){this.#u?.removeComments([t.uid])}deleteComment(t,e){const s=()=>{t.comment=e},i=()=>{this._editorUndoBar?.show(s,"comment"),this.toggleComment(null),t.comment=null};this.addCommands({cmd:i,undo:s,mustExec:!0})}toggleComment(t,e,s=void 0){this.#u?.toggleCommentPopup(t,e,s)}makeCommentColor(t,e){return t&&this.#u?.makeCommentColor(t,e)||null}getCommentDialogElement(){return this.#u?.dialogElement||null}async waitForEditorsRendered(t){if(this.#n.has(t-1))return;const{resolve:e,promise:s}=Promise.withResolvers(),i=n=>{n.pageNumber===t&&(this._eventBus.off("editorsrendered",i),e())};this._eventBus.on("editorsrendered",i,gi),await s}getSignature(t){this.#U?.getSignature({uiManager:this,editor:t})}get signatureManager(){return this.#U}switchToMode(t,e){this._eventBus.on("annotationeditormodechanged",e,{once:!0,signal:this._signal,...gi}),this._eventBus.dispatch("showannotationeditorui",{source:this,mode:t})}setPreference(t,e){this._eventBus.dispatch("setpreference",{source:this,name:t,value:e})}onSetPreference({name:t,value:e}){t==="enableNewAltTextWhenAddingImage"&&(this.#S=e)}onPageChanging({pageNumber:t}){this.#m=t-1}deletePage(t){for(const e of this.getEditors(t))e.remove();this.#n.delete(t),this.#m===t&&(this.#m=0)}focusMainContainer(){this.#W.focus()}findParent(t,e){for(const s of this.#n.values()){const{x:i,y:n,width:r,height:a}=s.div.getBoundingClientRect();if(t>=i&&t<=i+r&&e>=n&&e<=n+a)return s}return null}disableUserSelect(t=!1){this.#Z.classList.toggle("noUserSelect",t)}addShouldRescale(t){this.#y.add(t)}removeShouldRescale(t){this.#y.delete(t)}onScaleChanging({scale:t}){this.commitOrRemove(),this.viewParameters.realScale=t*He.PDF_TO_CSS_UNITS;for(const e of this.#y)e.onScaleChanging();this.#p?.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove(),this.viewParameters.rotation=t}#J({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}#et(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const s of this.#n.values())if(s.hasTextLayer(t))return s;return null}highlightSelection(t="",e=!1){const s=document.getSelection();if(!s||s.isCollapsed)return;const{anchorNode:i,anchorOffset:n,focusNode:r,focusOffset:a}=s,o=s.toString(),c=this.#J(s).closest(".textLayer"),h=this.getSelectionBoxes(c);if(!h)return;s.empty();const u=this.#et(c),f=this.#_===G.NONE,p=()=>{const g=u?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:h,anchorNode:i,anchorOffset:n,focusNode:r,focusOffset:a,text:o});f&&this.showAllEditors("highlight",!0,!0),e&&g?.editComment()};if(f){this.switchToMode(G.HIGHLIGHT,p);return}p()}commentSelection(t=""){this.highlightSelection(t,!0)}#rt(t){this.commitOrRemove(),this.currentLayer?.endDrawingSession(!1)}#at(){const t=document.getSelection();if(!t||t.isCollapsed)return;const s=this.#J(t).closest(".textLayer"),i=this.getSelectionBoxes(s);i&&(this.#M||=new tl(this),this.#M.show(s,i,this.direction==="ltr"))}getAndRemoveDataFromAnnotationStorage(t){if(!this.#o)return null;const e=`${ts}${t}`,s=this.#o.getRawValue(e);return s&&this.#o.remove(e),s}addToAnnotationStorage(t){!t.isEmpty()&&this.#o&&!this.#o.has(t.id)&&this.#o.setValue(t.id,t)}a11yAlert(t,e=null){const s=this.#tt;s&&(s.setAttribute("data-l10n-id",t),e?s.setAttribute("data-l10n-args",JSON.stringify(e)):s.removeAttribute("data-l10n-args"))}#ot(){const t=document.getSelection();if(!t||t.isCollapsed){this.#R&&(this.#M?.hide(),this.#R=null,this.#I({hasSelectedText:!1}));return}const{anchorNode:e}=t;if(e===this.#R)return;const i=this.#J(t).closest(".textLayer");if(!i){this.#R&&(this.#M?.hide(),this.#R=null,this.#I({hasSelectedText:!1}));return}if(this.#M?.hide(),this.#R=e,this.#I({hasSelectedText:!0}),!(this.#_!==G.HIGHLIGHT&&this.#_!==G.NONE)&&(this.#_===G.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),this.#k=this.isShiftKeyDown,!this.isShiftKeyDown)){const n=this.#_===G.HIGHLIGHT?this.#et(i):null;if(n?.toggleDrawing(),this.#N){const r=new AbortController,a=this.combinedSignal(r),o=l=>{l.type==="pointerup"&&l.button!==0||(r.abort(),n?.toggleDrawing(!0),l.type==="pointerup"&&this.#q("main_toolbar"))};window.addEventListener("pointerup",o,{signal:a}),window.addEventListener("blur",o,{signal:a})}else n?.toggleDrawing(!0),this.#q("main_toolbar")}}#q(t=""){this.#_===G.HIGHLIGHT?this.highlightSelection(t):this.#v&&this.#at()}#lt(){document.addEventListener("selectionchange",this.#ot.bind(this),{signal:this._signal})}#ct(){if(this.#E)return;this.#E=new AbortController;const t=this.combinedSignal(this.#E);window.addEventListener("focus",this.focus.bind(this),{signal:t}),window.addEventListener("blur",this.blur.bind(this),{signal:t})}#ht(){this.#E?.abort(),this.#E=null}blur(){if(this.isShiftKeyDown=!1,this.#k&&(this.#k=!1,this.#q("main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const e of this.#x)if(e.div.contains(t)){this.#L=[e,t],e._focusEventsAllowed=!1;break}}focus(){if(!this.#L)return;const[t,e]=this.#L;this.#L=null,e.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal}),e.focus()}#st(){if(this.#D)return;this.#D=new AbortController;const t=this.combinedSignal(this.#D);window.addEventListener("keydown",this.keydown.bind(this),{signal:t}),window.addEventListener("keyup",this.keyup.bind(this),{signal:t})}#dt(){this.#D?.abort(),this.#D=null}#ut(){if(this.#d)return;this.#d=new AbortController;const t=this.combinedSignal(this.#d);document.addEventListener("copy",this.copy.bind(this),{signal:t}),document.addEventListener("cut",this.cut.bind(this),{signal:t}),document.addEventListener("paste",this.paste.bind(this),{signal:t})}#ft(){this.#d?.abort(),this.#d=null}#pt(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})}addEditListeners(){this.#st(),this.setEditingState(!0)}removeEditListeners(){this.#dt(),this.setEditingState(!1)}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const s of this.#f)if(s.isHandlingMimeForPasting(e)){t.dataTransfer.dropEffect="copy",t.preventDefault();return}}drop(t){for(const e of t.dataTransfer.items)for(const s of this.#f)if(s.isHandlingMimeForPasting(e.type)){s.paste(e,this.currentLayer),t.preventDefault();return}}copy(t){if(t.preventDefault(),this.#e?.commitOrRemove(),!this.hasSelection)return;const e=[];for(const s of this.#x){const i=s.serialize(!0);i&&e.push(i)}e.length!==0&&t.clipboardData.setData("application/pdfjs",JSON.stringify(e))}cut(t){this.copy(t),this.delete()}async paste(t){t.preventDefault();const{clipboardData:e}=t;for(const n of e.items)for(const r of this.#f)if(r.isHandlingMimeForPasting(n.type)){r.paste(n,this.currentLayer);return}let s=e.getData("application/pdfjs");if(!s)return;try{s=JSON.parse(s)}catch(n){V(`paste: "${n.message}".`);return}if(!Array.isArray(s))return;this.unselectAll();const i=this.currentLayer;try{const n=[];for(const o of s){const l=await i.deserialize(o);if(!l)return;n.push(l)}const r=()=>{for(const o of n)this.#it(o);this.#nt(n)},a=()=>{for(const o of n)o.remove()};this.addCommands({cmd:r,undo:a,mustExec:!0})}catch(n){V(`paste: "${n.message}".`)}}keydown(t){!this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!0),this.#_!==G.NONE&&!this.isEditorHandlingKeyboard&&ae._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!1,this.#k&&(this.#k=!1,this.#q("main_toolbar")))}onEditingAction({name:t}){switch(t){case"undo":case"redo":case"delete":case"selectAll":this[t]();break;case"highlightSelection":this.highlightSelection("context_menu");break;case"commentSelection":this.commentSelection("context_menu");break}}updatePageIndex(t,e){for(const i of this.getEditors(t))i.pageIndex=e;const s=this.#a.get(t);s&&(s.pageIndex=e,this.#n.set(e,s),this.#T?s.enable():s.disable())}startUpdatePages(){this.#a=new Map(this.#n),this.#n.clear()}endUpdatePages(){this.#a=null}clonePage(t,e){for(const s of this.getEditors(t)){const i=s.serialize(s.mode!==G.HIGHLIGHT);i&&(i.pageIndex=e,i.id=this.getId(),i.isClone=!0,delete i.popupRef,this.#o.setValue(i.id,i))}}findClonesForPage(t){const e=[],{pageIndex:s}=t;for(const[i,n]of this.#o)n.pageIndex===s&&n.isClone&&(this.#o.remove(i),e.push(t.deserialize(n).then(r=>{r&&(r.isClone=!0,t.addOrRebuild(r))})));return Promise.all(e)}#I(t){Object.entries(t).some(([s,i])=>this.#Y[s]!==i)&&(this._eventBus.dispatch("editingstateschanged",{source:this,details:Object.assign(this.#Y,t)}),this.#_===G.HIGHLIGHT&&t.hasSelectedEditor===!1&&this.#z([[X.HIGHLIGHT_FREE,!0]]))}#z(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){t?(this.#ct(),this.#ut(),this.#I({isEditing:this.#_!==G.NONE,isEmpty:this.#Q(),hasSomethingToUndo:this.#l.hasSomethingToUndo(),hasSomethingToRedo:this.#l.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#ht(),this.#ft(),this.#I({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!this.#f){this.#f=t;for(const e of this.#f)this.#z(e.defaultPropertiesToUpdate)}}getId(){return this.#P.id}get currentLayer(){return this.#n.get(this.#m)}getLayer(t){return this.#n.get(t)}get currentPageIndex(){return this.#m}addLayer(t){this.#n.set(t.pageIndex,t),this.#T?t.enable():t.disable()}removeLayer(t){this.#n.delete(t.pageIndex)}async updateMode(t,e=null,s=!1,i=!1,n=!1,r=!1){if(this.#_!==t&&!(this.#H&&(await this.#H.promise,!this.#H))){if(this.#H=Promise.withResolvers(),this.#p?.commitOrRemove(),this.#_===G.POPUP&&this.#u?.hideSidebar(),this.#u?.destroyPopup(),this.#_=t,t===G.NONE){this.setEditingState(!1),this.#mt();for(const a of this.#i.values())a.hideStandaloneCommentButton();this._editorUndoBar?.hide(),this.toggleComment(null),this.#H.resolve();return}for(const a of this.#i.values())a.addStandaloneCommentButton();t===G.SIGNATURE&&await this.#U?.loadSignatures(),s&&Q.clearPointerType(),this.setEditingState(!0),await this.#gt(),this.unselectAll();for(const a of this.#n.values())a.updateMode(t);if(t===G.POPUP){this.#s||=await this.#X.getAnnotationsByType(new Set(this.#f.map(l=>l._editorType)));const a=new Set,o=[];for(const l of this.#i.values()){const{annotationElementId:c,hasComment:h,deleted:u}=l;c&&a.add(c),h&&!u&&o.push(l.getData())}for(const l of this.#s){const{id:c,popupRef:h,contentsObj:u}=l;h&&u?.str&&!a.has(c)&&!this.#g.has(c)&&o.push(l)}this.#u?.showSidebar(o)}if(!e){i&&this.addNewEditorFromKeyboard(),this.#H.resolve();return}for(const a of this.#i.values())a.uid===e?(this.setSelected(a),r?a.editComment():n?a.enterInEditMode():a.focus()):a.unselect();this.#H.resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t.mode!==this.#_&&this._eventBus.dispatch("switchannotationeditormode",{source:this,...t})}updateParams(t,e){if(this.#f){switch(t){case X.CREATE:this.currentLayer.addNewEditor(e);return;case X.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(this.#K||=new Map).set(t,e),this.showAllEditors("highlight",e);break}if(this.hasSelection)for(const s of this.#x)s.updateParams(t,e);else for(const s of this.#f)s.updateDefaultParams(t,e)}}showAllEditors(t,e,s=!1){for(const n of this.#i.values())n.editorType===t&&n.show(e);(this.#K?.get(X.HIGHLIGHT_SHOW_ALL)??!0)!==e&&this.#z([[X.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(this.#F!==t){this.#F=t;for(const e of this.#n.values())t?e.disableClick():e.enableClick(),e.div.classList.toggle("waiting",t)}}async#gt(){if(!this.#T){this.#T=!0;const t=[];for(const e of this.#n.values())t.push(e.enable());await Promise.all(t);for(const e of this.#i.values())e.enable()}}#mt(){if(this.unselectAll(),this.#T){this.#T=!1;for(const t of this.#n.values())t.disable();for(const t of this.#i.values())t.disable()}}*getEditors(t){for(const e of this.#i.values())e.pageIndex===t&&(yield e)}getEditor(t){return this.#i.get(t)}addEditor(t){this.#i.set(t.id,t)}removeEditor(t){t.div.contains(document.activeElement)&&(this.#A&&clearTimeout(this.#A),this.#A=setTimeout(()=>{this.focusMainContainer(),this.#A=null},0)),this.#i.delete(t.id),t.annotationElementId&&this.#j?.delete(t.annotationElementId),this.unselect(t),(!t.annotationElementId||!this.#g.has(t.annotationElementId))&&this.#o?.remove(t.id)}addDeletedAnnotationElement(t){this.#g.add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return this.#g.has(t)}removeDeletedAnnotationElement(t){this.#g.delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}#it(t){const e=this.#n.get(t.pageIndex);e?e.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))}setActiveEditor(t){this.#e!==t&&(this.#e=t,t&&this.#z(t.propertiesToUpdate))}get#bt(){let t=null;for(t of this.#x);return t}updateUI(t){this.#bt===t&&this.#z(t.propertiesToUpdate)}updateUIForDefaultProperties(t){this.#z(t.defaultPropertiesToUpdate)}toggleSelected(t){if(this.#x.has(t)){this.#x.delete(t),t.unselect(),this.#I({hasSelectedEditor:this.hasSelection});return}this.#x.add(t),t.select(),this.#z(t.propertiesToUpdate),this.#I({hasSelectedEditor:!0})}setSelected(t){this.updateToolbar({mode:t.mode,editId:t.uid}),this.#p?.commitOrRemove();for(const e of this.#x)e!==t&&e.unselect();this.#u?.destroyPopup(),this.#x.clear(),this.#x.add(t),t.select(),this.#z(t.propertiesToUpdate),this.#I({hasSelectedEditor:!0})}get firstSelectedEditor(){return this.#x.values().next().value}unselect(t){t.unselect(),this.#x.delete(t),this.#I({hasSelectedEditor:this.hasSelection})}get hasSelection(){return this.#x.size!==0}get isEnterHandled(){return this.#x.size===1&&this.firstSelectedEditor.isEnterHandled}undo(){this.#l.undo(),this.#I({hasSomethingToUndo:this.#l.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#Q()}),this._editorUndoBar?.hide()}redo(){this.#l.redo(),this.#I({hasSomethingToUndo:!0,hasSomethingToRedo:this.#l.hasSomethingToRedo(),isEmpty:this.#Q()})}addCommands(t){this.#l.add(t),this.#I({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#Q()})}cleanUndoStack(t){this.#l.cleanType(t)}#Q(){if(this.#i.size===0)return!0;if(this.#i.size===1)for(const t of this.#i.values())return t.isEmpty();return!1}delete(){this.commitOrRemove();const t=this.currentLayer?.endDrawingSession(!0);if(!this.hasSelection&&!t)return;const e=t?[t]:[...this.#x],s=()=>{this._editorUndoBar?.show(i,e.length===1?e[0].editorType:e.length);for(const n of e)n.remove()},i=()=>{for(const n of e)this.#it(n)};this.addCommands({cmd:s,undo:i,mustExec:!0})}commitOrRemove(){this.#e?.commitOrRemove()}hasSomethingToControl(){return this.#e||this.hasSelection}#nt(t){for(const e of this.#x)e.unselect();this.#x.clear();for(const e of t)e.isEmpty()||(this.#x.add(e),e.select());this.#I({hasSelectedEditor:this.hasSelection})}selectAll(){for(const t of this.#x)t.commit();this.#nt(this.#i.values())}unselectAll(){if(!(this.#e&&(this.#e.commitOrRemove(),this.#_!==G.NONE))&&!this.#p?.commitOrRemove()&&(this.#u?.destroyPopup(),!!this.hasSelection)){for(const t of this.#x)t.unselect();this.#x.clear(),this.#I({hasSelectedEditor:!1})}}translateSelectedEditors(t,e,s=!1){if(s||this.commitOrRemove(),!this.hasSelection)return;this.#B[0]+=t,this.#B[1]+=e;const[i,n]=this.#B,r=[...this.#x],a=1e3;this.#G&&clearTimeout(this.#G),this.#G=setTimeout(()=>{this.#G=null,this.#B[0]=this.#B[1]=0,this.addCommands({cmd:()=>{for(const o of r)this.#i.has(o.id)&&(o.translateInPage(i,n),o.translationDone())},undo:()=>{for(const o of r)this.#i.has(o.id)&&(o.translateInPage(-i,-n),o.translationDone())},mustExec:!1})},a);for(const o of r)o.translateInPage(t,e),o.translationDone()}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#c=new Map;for(const t of this.#x)this.#c.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#c)return!1;this.disableUserSelect(!1);const t=this.#c;this.#c=null;let e=!1;for(const[{x:i,y:n,pageIndex:r},a]of t)a.newX=i,a.newY=n,a.newPageIndex=r,e||=i!==a.savedX||n!==a.savedY||r!==a.savedPageIndex;if(!e)return!1;const s=(i,n,r,a)=>{if(this.#i.has(i.id)){const o=this.#n.get(a);o?i._setParentAndPosition(o,n,r):(i.pageIndex=a,i.x=n,i.y=r)}};return this.addCommands({cmd:()=>{for(const[i,{newX:n,newY:r,newPageIndex:a}]of t)s(i,n,r,a)},undo:()=>{for(const[i,{savedX:n,savedY:r,savedPageIndex:a}]of t)s(i,n,r,a)},mustExec:!0}),!0}dragSelectedEditors(t,e){if(this.#c)for(const s of this.#c.keys())s.drag(t,e)}rebuild(t){if(t.parent===null){const e=this.getLayer(t.pageIndex);e?(e.changeParent(t),e.addOrRebuild(t)):(this.addEditor(t),this.addToAnnotationStorage(t),t.rebuild())}else t.parent.addOrRebuild(t)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||this.#x.size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#e===t}getActive(){return this.#e}getMode(){return this.#_}isEditingMode(){return this.#_!==G.NONE}get imageManager(){return z(this,"imageManager",new Gi)}getSelectionBoxes(t){if(!t)return null;const e=document.getSelection();for(let l=0,c=e.rangeCount;l<c;l++)if(!t.contains(e.getRangeAt(l).commonAncestorContainer))return null;const{x:s,y:i,width:n,height:r}=t.getBoundingClientRect();let a;switch(t.getAttribute("data-main-rotation")){case"90":a=(l,c,h,u)=>({x:(c-i)/r,y:1-(l+h-s)/n,width:u/r,height:h/n});break;case"180":a=(l,c,h,u)=>({x:1-(l+h-s)/n,y:1-(c+u-i)/r,width:h/n,height:u/r});break;case"270":a=(l,c,h,u)=>({x:1-(c+u-i)/r,y:(l-s)/n,width:u/r,height:h/n});break;default:a=(l,c,h,u)=>({x:(l-s)/n,y:(c-i)/r,width:h/n,height:u/r});break}const o=[];for(let l=0,c=e.rangeCount;l<c;l++){const h=e.getRangeAt(l);if(!h.collapsed)for(const{x:u,y:f,width:p,height:g}of h.getClientRects())p===0||g===0||o.push(a(u,f,p,g))}return o.length===0?null:o}addChangedExistingAnnotation({annotationElementId:t,id:e}){(this.#h||=new Map).set(t,e)}removeChangedExistingAnnotation({annotationElementId:t}){this.#h?.delete(t)}renderAnnotationElement(t){const e=this.#h?.get(t.data.id);if(!e)return;const s=this.#o.getRawValue(e);s&&(this.#_===G.NONE&&!s.hasBeenModified||s.renderAnnotationElement(t))}setMissingCanvas(t,e,s){const i=this.#j?.get(t);i&&(i.setCanvas(e,s),this.#j.delete(t))}addMissingCanvas(t,e){(this.#j||=new Map).set(t,e)}}class Yt{#t=null;#e=!1;#s=null;#i=null;#n=null;#a=null;#r=!1;#o=null;#h=null;#l=null;#u=null;#d=!1;static#p=null;static _l10n=null;constructor(t){this.#h=t,this.#d=t._uiManager.useNewAltTextFlow,Yt.#p||=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(t){Yt._l10n??=t}async render(){const t=this.#s=document.createElement("button");t.className="altText",t.tabIndex="0";const e=this.#i=document.createElement("span");t.append(e),this.#d?(t.classList.add("new"),t.setAttribute("data-l10n-id",Yt.#p.missing),e.setAttribute("data-l10n-id",Yt.#p["missing-label"])):(t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button"),e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button-label"));const s=this.#h._uiManager._signal;t.addEventListener("contextmenu",Rt,{signal:s}),t.addEventListener("pointerdown",n=>n.stopPropagation(),{signal:s});const i=n=>{n.preventDefault(),this.#h._uiManager.editAltText(this.#h),this.#d&&this.#h._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:this.#m}})};return t.addEventListener("click",i,{capture:!0,signal:s}),t.addEventListener("keydown",n=>{n.target===t&&n.key==="Enter"&&(this.#r=!0,i(n))},{signal:s}),await this.#g(),t}get#m(){return this.#t&&"added"||this.#t===null&&this.guessedText&&"review"||"missing"}finish(){this.#s&&(this.#s.focus({focusVisible:this.#r}),this.#r=!1)}isEmpty(){return this.#d?this.#t===null:!this.#t&&!this.#e}hasData(){return this.#d?this.#t!==null||!!this.#l:this.isEmpty()}get guessedText(){return this.#l}async setGuessedText(t){this.#t===null&&(this.#l=t,this.#u=await Yt._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t}),this.#g())}toggleAltTextBadge(t=!1){if(!this.#d||this.#t){this.#o?.remove(),this.#o=null;return}if(!this.#o){const e=this.#o=document.createElement("div");e.className="noAltTextBadge",this.#h.div.append(e)}this.#o.classList.toggle("hidden",!t)}serialize(t){let e=this.#t;return!t&&this.#l===e&&(e=this.#u),{altText:e,decorative:this.#e,guessedText:this.#l,textWithDisclaimer:this.#u}}get data(){return{altText:this.#t,decorative:this.#e}}set data({altText:t,decorative:e,guessedText:s,textWithDisclaimer:i,cancel:n=!1}){s&&(this.#l=s,this.#u=i),!(this.#t===t&&this.#e===e)&&(n||(this.#t=t,this.#e=e),this.#g())}toggle(t=!1){this.#s&&(!t&&this.#a&&(clearTimeout(this.#a),this.#a=null),this.#s.disabled=!t)}shown(){this.#h._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:this.#m}})}destroy(){this.#s?.remove(),this.#s=null,this.#i=null,this.#n=null,this.#o?.remove(),this.#o=null}async#g(){const t=this.#s;if(!t)return;if(this.#d){if(t.classList.toggle("done",!!this.#t),t.setAttribute("data-l10n-id",Yt.#p[this.#m]),this.#i?.setAttribute("data-l10n-id",Yt.#p[`${this.#m}-label`]),!this.#t){this.#n?.remove();return}}else{if(!this.#t&&!this.#e){t.classList.remove("done"),this.#n?.remove();return}t.classList.add("done"),t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let e=this.#n;if(!e){this.#n=e=document.createElement("span"),e.className="tooltip",e.setAttribute("role","tooltip"),e.id=`alt-text-tooltip-${this.#h.id}`;const i=100,n=this.#h._uiManager._signal;n.addEventListener("abort",()=>{clearTimeout(this.#a),this.#a=null},{once:!0}),t.addEventListener("mouseenter",()=>{this.#a=setTimeout(()=>{this.#a=null,this.#n.classList.add("show"),this.#h._reportTelemetry({action:"alt_text_tooltip"})},i)},{signal:n}),t.addEventListener("mouseleave",()=>{this.#a&&(clearTimeout(this.#a),this.#a=null),this.#n?.classList.remove("show")},{signal:n})}this.#e?e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip"):(e.removeAttribute("data-l10n-id"),e.textContent=this.#t),e.parentNode||t.append(e),this.#h.getElementForAltText()?.setAttribute("aria-describedby",e.id)}}class xs{#t=null;#e=null;#s=!1;#i=null;#n=null;#a=null;#r=null;#o=null;#h=!1;#l=null;constructor(t){this.#i=t}renderForToolbar(){const t=this.#e=document.createElement("button");return t.className="comment",this.#u(t,!1)}renderForStandalone(){const t=this.#t=document.createElement("button");t.className="annotationCommentButton";const e=this.#i.commentButtonPosition;if(e){const{style:s}=t;s.insetInlineEnd=`calc(${100*(this.#i._uiManager.direction==="ltr"?1-e[0]:e[0])}% - var(--comment-button-dim))`,s.top=`calc(${100*e[1]}% - var(--comment-button-dim))`;const i=this.#i.commentButtonColor;i&&(s.backgroundColor=i)}return this.#u(t,!0)}focusButton(){setTimeout(()=>{(this.#t??this.#e)?.focus()},0)}onUpdatedColor(){if(!this.#t)return;const t=this.#i.commentButtonColor;t&&(this.#t.style.backgroundColor=t),this.#i._uiManager.updatePopupColor(this.#i)}get commentButtonWidth(){return(this.#t?.getBoundingClientRect().width??0)/this.#i.parent.boundingClientRect.width}get commentPopupPositionInLayer(){if(this.#l)return this.#l;if(!this.#t)return null;const{x:t,y:e,height:s}=this.#t.getBoundingClientRect(),{x:i,y:n,width:r,height:a}=this.#i.parent.boundingClientRect;return[(t-i)/r,(e+s-n)/a]}set commentPopupPositionInLayer(t){this.#l=t}hasDefaultPopupPosition(){return this.#l===null}removeStandaloneCommentButton(){this.#t?.remove(),this.#t=null}removeToolbarCommentButton(){this.#e?.remove(),this.#e=null}setCommentButtonStates({selected:t,hasPopup:e}){this.#t&&(this.#t.classList.toggle("selected",t),this.#t.ariaExpanded=e)}#u(t,e){if(!this.#i._uiManager.hasCommentManager())return null;t.tabIndex="0",t.ariaHasPopup="dialog",e?(t.ariaControls="commentPopup",t.setAttribute("data-l10n-id","pdfjs-show-comment-button")):(t.ariaControlsElements=[this.#i._uiManager.getCommentDialogElement()],t.setAttribute("data-l10n-id","pdfjs-editor-add-comment-button"));const s=this.#i._uiManager._signal;if(!(s instanceof AbortSignal)||s.aborted)return t;t.addEventListener("contextmenu",Rt,{signal:s}),e&&(t.addEventListener("focusin",n=>{this.#i._focusEventsAllowed=!1,lt(n)},{capture:!0,signal:s}),t.addEventListener("focusout",n=>{this.#i._focusEventsAllowed=!0,lt(n)},{capture:!0,signal:s})),t.addEventListener("pointerdown",n=>n.stopPropagation(),{signal:s});const i=n=>{n.preventDefault(),t===this.#e?this.edit():this.#i.toggleComment(!0)};return t.addEventListener("click",i,{capture:!0,signal:s}),t.addEventListener("keydown",n=>{n.target===t&&n.key==="Enter"&&(this.#s=!0,i(n))},{signal:s}),t.addEventListener("pointerenter",()=>{this.#i.toggleComment(!1,!0)},{signal:s}),t.addEventListener("pointerleave",()=>{this.#i.toggleComment(!1,!1)},{signal:s}),t}edit(t){const e=this.commentPopupPositionInLayer;let s,i;if(e)[s,i]=e;else{[s,i]=this.#i.commentButtonPosition;const{width:c,height:h,x:u,y:f}=this.#i;s=u+s*c,i=f+i*h}const n=this.#i.parent.boundingClientRect,{x:r,y:a,width:o,height:l}=n;this.#i._uiManager.editComment(this.#i,r+s*o,a+i*l,{...t,parentDimensions:n})}finish(){this.#e&&(this.#e.focus({focusVisible:this.#s}),this.#s=!1)}isDeleted(){return this.#h||this.#r===""}isEmpty(){return this.#r===null}hasBeenEdited(){return this.isDeleted()||this.#r!==this.#n}serialize(){return this.data}get data(){return{text:this.#r,richText:this.#a,date:this.#o,deleted:this.isDeleted()}}set data(t){if(t!==this.#r&&(this.#a=null),t===null){this.#r="",this.#h=!0;return}this.#r=t,this.#o=new Date,this.#h=!1}restoreData({text:t,richText:e,date:s}){this.#r=t,this.#a=e,this.#o=s,this.#h=!1}setInitialText(t,e=null){this.#n=t,this.data=t,this.#o=null,this.#a=e}shown(){}destroy(){this.#e?.remove(),this.#e=null,this.#t?.remove(),this.#t=null,this.#r="",this.#a=null,this.#o=null,this.#i=null,this.#s=!1,this.#h=!1}}class Vs{#t;#e=!1;#s=null;#i;#n;#a;#r;#o=null;#h;#l=null;#u;#d=null;constructor({container:t,isPinchingDisabled:e=null,isPinchingStopped:s=null,onPinchStart:i=null,onPinching:n=null,onPinchEnd:r=null,signal:a}){this.#t=t,this.#s=s,this.#i=e,this.#n=i,this.#a=n,this.#r=r,this.#u=new AbortController,this.#h=AbortSignal.any([a,this.#u.signal]),t.addEventListener("touchstart",this.#p.bind(this),{passive:!1,signal:this.#h})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return 35/Kt.pixelRatio}#p(t){if(this.#i?.())return;if(t.touches.length===1){if(this.#o)return;const i=this.#o=new AbortController,n=AbortSignal.any([this.#h,i.signal]),r=this.#t,a={capture:!0,signal:n,passive:!1},o=l=>{l.pointerType==="touch"&&(this.#o?.abort(),this.#o=null)};r.addEventListener("pointerdown",l=>{l.pointerType==="touch"&&(lt(l),o(l))},a),r.addEventListener("pointerup",o,a),r.addEventListener("pointercancel",o,a);return}if(!this.#d){this.#d=new AbortController;const i=AbortSignal.any([this.#h,this.#d.signal]),n=this.#t,r={signal:i,capture:!1,passive:!1};n.addEventListener("touchmove",this.#m.bind(this),r);const a=this.#g.bind(this);n.addEventListener("touchend",a,r),n.addEventListener("touchcancel",a,r),r.capture=!0,n.addEventListener("pointerdown",lt,r),n.addEventListener("pointermove",lt,r),n.addEventListener("pointercancel",lt,r),n.addEventListener("pointerup",lt,r),this.#n?.()}if(lt(t),t.touches.length!==2||this.#s?.()){this.#l=null;return}let[e,s]=t.touches;e.identifier>s.identifier&&([e,s]=[s,e]),this.#l={touch0X:e.screenX,touch0Y:e.screenY,touch1X:s.screenX,touch1Y:s.screenY}}#m(t){if(!this.#l||t.touches.length!==2)return;lt(t);let[e,s]=t.touches;e.identifier>s.identifier&&([e,s]=[s,e]);const{screenX:i,screenY:n}=e,{screenX:r,screenY:a}=s,o=this.#l,{touch0X:l,touch0Y:c,touch1X:h,touch1Y:u}=o,f=h-l,p=u-c,g=r-i,m=a-n,b=Math.hypot(g,m)||1,y=Math.hypot(f,p)||1;if(!this.#e&&Math.abs(y-b)<=Vs.MIN_TOUCH_DISTANCE_TO_PINCH)return;if(o.touch0X=i,o.touch0Y=n,o.touch1X=r,o.touch1Y=a,!this.#e){this.#e=!0;return}const A=[(i+r)/2,(n+a)/2];this.#a?.(A,y,b)}#g(t){t.touches.length>=2||(this.#d&&(this.#d.abort(),this.#d=null,this.#r?.()),this.#l&&(lt(t),this.#l=null,this.#e=!1))}destroy(){this.#u?.abort(),this.#u=null,this.#o?.abort(),this.#o=null}}class N{#t=null;#e=null;#s=null;#i=null;#n=null;#a=!1;#r=null;#o="";#h=null;#l=null;#u=null;#d=null;#p=null;#m="";#g=!1;#c=null;#f=!1;#y=!1;#v=!1;#b=null;#S=0;#C=0;#A=null;#E=null;isSelected=!1;_isCopy=!1;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nAlert=null;static _l10nResizer=null;#w=!1;#k=N._zIndex++;static _borderLineWidth=-1;static _colorManager=new Vi;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){const t=N.prototype._resizeWithKeyboard,e=ae.TRANSLATE_SMALL,s=ae.TRANSLATE_BIG;return z(this,"_resizerKeyboardManager",new It([[["ArrowLeft"],t,{args:[-e,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-s,0]}],[["ArrowRight"],t,{args:[e,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[s,0]}],[["ArrowUp"],t,{args:[0,-e]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-s]}],[["ArrowDown"],t,{args:[0,e]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,s]}],[["Escape"],N.prototype._stopResizingWithKeyboard]]))}constructor(t){this.parent=t.parent,this.id=t.id,this.width=this.height=null,this.pageIndex=t.parent.pageIndex,this.name=t.name,this.div=null,this._uiManager=t.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=t.isCentered,this._structTreeParentId=null,this.annotationElementId=t.annotationElementId||null,this.creationDate=t.creationDate||new Date,this.modificationDate=t.modificationDate||null,this.canAddComment=!0;const{rotation:e,rawDims:{pageWidth:s,pageHeight:i,pageX:n,pageY:r}}=this.parent.viewport;this.rotation=e,this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[s,i],this.pageTranslation=[n,r];const[a,o]=this.parentDimensions;this.x=t.x/a,this.y=t.y/o,this.isAttachedToDOM=!1,this.deleted=!1}updatePageIndex(t){this.pageIndex=t}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 z(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new nl({id:t._uiManager.getId(),parent:t.parent,uiManager:t._uiManager});e.annotationElementId=t.annotationElementId,e.deleted=!0,e._uiManager.addToAnnotationStorage(e)}static initialize(t,e){if(N._l10n??=t,N._l10nAlert??=Object.freeze({highlight:"pdfjs-editor-highlight-added-alert",freetext:"pdfjs-editor-freetext-added-alert",ink:"pdfjs-editor-ink-added-alert",stamp:"pdfjs-editor-stamp-added-alert",signature:"pdfjs-editor-signature-added-alert"}),N._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"}),N._borderLineWidth!==-1)return;const s=getComputedStyle(document.documentElement);N._borderLineWidth=parseFloat(s.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){K("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#w}set _isDraggable(t){this.#w=t,this.div?.classList.toggle("draggable",t)}get uid(){return this.annotationElementId||this.id}get isEnterHandled(){return!0}center(){const[t,e]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*e/(t*2),this.y+=this.width*t/(e*2);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*e/(t*2),this.y-=this.width*t/(e*2);break;default:this.x-=this.width/2,this.y-=this.height/2;break}this.fixAndSetPosition()}addCommands(t){this._uiManager.addCommands(t)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#k}setParent(t){t!==null?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):(this.#B(),this.#d?.remove(),this.#d=null),this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#g?this.#g=!1:this.parent.setSelected(this))}focusout(t){!this._focusEventsAllowed||!this.isAttachedToDOM||t.relatedTarget?.closest(`#${this.id}`)||(t.preventDefault(),this.parent?.isMultipleSelection||this.commitOrRemove())}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.isInEditMode()&&this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(t,e,s,i){const[n,r]=this.parentDimensions;[s,i]=this.screenToPageTranslation(s,i),this.x=(t+s)/n,this.y=(e+i)/r,this.fixAndSetPosition()}_moveAfterPaste(t,e){if(this.isClone){delete this.isClone;return}const[s,i]=this.parentDimensions;this.setAt(t*s,e*i,this.width*s,this.height*i),this._onTranslated()}#M([t,e],s,i){[s,i]=this.screenToPageTranslation(s,i),this.x+=s/t,this.y+=i/e,this._onTranslating(this.x,this.y),this.fixAndSetPosition()}translate(t,e){this.#M(this.parentDimensions,t,e)}translateInPage(t,e){this.#c||=[this.x,this.y,this.width,this.height],this.#M(this.pageDimensions,t,e),this.div.scrollIntoView({block:"nearest"})}translationDone(){this._onTranslated(this.x,this.y)}drag(t,e){this.#c||=[this.x,this.y,this.width,this.height];const{div:s,parentDimensions:[i,n]}=this;if(this.x+=t/i,this.y+=e/n,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:h,y:u}=this.div.getBoundingClientRect();this.parent.findNewParent(this,h,u)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:r,y:a}=this;const[o,l]=this.getBaseTranslation();r+=o,a+=l;const{style:c}=s;c.left=`${(100*r).toFixed(2)}%`,c.top=`${(100*a).toFixed(2)}%`,this._onTranslating(r,a),s.scrollIntoView({block:"nearest"})}_onTranslating(t,e){}_onTranslated(t,e){}get _hasBeenMoved(){return!!this.#c&&(this.#c[0]!==this.x||this.#c[1]!==this.y)}get _hasBeenResized(){return!!this.#c&&(this.#c[2]!==this.width||this.#c[3]!==this.height)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:s}=N,i=s/t,n=s/e;switch(this.rotation){case 90:return[-i,n];case 180:return[i,n];case 270:return[i,-n];default:return[-i,-n]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const{div:{style:e},pageDimensions:[s,i]}=this;let{x:n,y:r,width:a,height:o}=this;if(a*=s,o*=i,n*=s,r*=i,this._mustFixPosition)switch(t){case 0:n=nt(n,0,s-a),r=nt(r,0,i-o);break;case 90:n=nt(n,0,s-o),r=nt(r,a,i);break;case 180:n=nt(n,a,s),r=nt(r,o,i);break;case 270:n=nt(n,o,s),r=nt(r,0,i-a);break}this.x=n/=s,this.y=r/=i;const[l,c]=this.getBaseTranslation();n+=l,r+=c,e.left=`${(100*n).toFixed(2)}%`,e.top=`${(100*r).toFixed(2)}%`,this.moveInDOM()}static#P(t,e,s){switch(s){case 90:return[e,-t];case 180:return[-t,-e];case 270:return[-e,t];default:return[t,e]}}screenToPageTranslation(t,e){return N.#P(t,e,this.parentRotation)}pageTranslationToScreen(t,e){return N.#P(t,e,360-this.parentRotation)}#T(t){switch(t){case 90:{const[e,s]=this.pageDimensions;return[0,-e/s,s/e,0]}case 180:return[-1,0,0,-1];case 270:{const[e,s]=this.pageDimensions;return[0,e/s,-s/e,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:t,pageDimensions:[e,s]}=this;return[e*t,s*t]}setDims(){const{div:{style:t},width:e,height:s}=this;t.width=`${(100*e).toFixed(2)}%`,t.height=`${(100*s).toFixed(2)}%`}getInitialTranslation(){return[0,0]}#N(){if(this.#h)return;this.#h=document.createElement("div"),this.#h.classList.add("resizers");const t=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],e=this._uiManager._signal;for(const s of t){const i=document.createElement("div");this.#h.append(i),i.classList.add("resizer",s),i.setAttribute("data-resizer-name",s),i.addEventListener("pointerdown",this.#F.bind(this,s),{signal:e}),i.addEventListener("contextmenu",Rt,{signal:e}),i.tabIndex=-1}this.div.prepend(this.#h)}#F(t,e){e.preventDefault();const{isMac:s}=J.platform;if(e.button!==0||e.ctrlKey&&s)return;this.#s?.toggle(!1);const i=this._isDraggable;this._isDraggable=!1,this.#l=[e.screenX,e.screenY];const n=new AbortController,r=this._uiManager.combinedSignal(n);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",this.#O.bind(this,t),{passive:!0,capture:!0,signal:r}),window.addEventListener("touchmove",lt,{passive:!1,signal:r}),window.addEventListener("contextmenu",Rt,{signal:r}),this.#u={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const a=this.parent.div.style.cursor,o=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const l=()=>{n.abort(),this.parent.togglePointerEvents(!0),this.#s?.toggle(!0),this._isDraggable=i,this.parent.div.style.cursor=a,this.div.style.cursor=o,this.#L()};window.addEventListener("pointerup",l,{signal:r}),window.addEventListener("blur",l,{signal:r})}#D(t,e,s,i){this.width=s,this.height=i,this.x=t,this.y=e,this.setDims(),this.fixAndSetPosition(),this._onResized()}_onResized(){}#L(){if(!this.#u)return;const{savedX:t,savedY:e,savedWidth:s,savedHeight:i}=this.#u;this.#u=null;const n=this.x,r=this.y,a=this.width,o=this.height;n===t&&r===e&&a===s&&o===i||this.addCommands({cmd:this.#D.bind(this,n,r,a,o),undo:this.#D.bind(this,t,e,s,i),mustExec:!0})}static _round(t){return Math.round(t*1e4)/1e4}#O(t,e){const[s,i]=this.parentDimensions,n=this.x,r=this.y,a=this.width,o=this.height,l=N.MIN_SIZE/s,c=N.MIN_SIZE/i,h=this.#T(this.rotation),u=(L,F)=>[h[0]*L+h[2]*F,h[1]*L+h[3]*F],f=this.#T(360-this.rotation),p=(L,F)=>[f[0]*L+f[2]*F,f[1]*L+f[3]*F];let g,m,b=!1,y=!1;switch(t){case"topLeft":b=!0,g=(L,F)=>[0,0],m=(L,F)=>[L,F];break;case"topMiddle":g=(L,F)=>[L/2,0],m=(L,F)=>[L/2,F];break;case"topRight":b=!0,g=(L,F)=>[L,0],m=(L,F)=>[0,F];break;case"middleRight":y=!0,g=(L,F)=>[L,F/2],m=(L,F)=>[0,F/2];break;case"bottomRight":b=!0,g=(L,F)=>[L,F],m=(L,F)=>[0,0];break;case"bottomMiddle":g=(L,F)=>[L/2,F],m=(L,F)=>[L/2,0];break;case"bottomLeft":b=!0,g=(L,F)=>[0,F],m=(L,F)=>[L,0];break;case"middleLeft":y=!0,g=(L,F)=>[0,F/2],m=(L,F)=>[L,F/2];break}const A=g(a,o),w=m(a,o);let x=u(...w);const S=N._round(n+x[0]),E=N._round(r+x[1]);let _=1,k=1,I,P;if(e.fromKeyboard)({deltaX:I,deltaY:P}=e);else{const{screenX:L,screenY:F}=e,[rt,ht]=this.#l;[I,P]=this.screenToPageTranslation(L-rt,F-ht),this.#l[0]=L,this.#l[1]=F}if([I,P]=p(I/s,P/i),b){const L=Math.hypot(a,o);_=k=Math.max(Math.min(Math.hypot(w[0]-A[0]-I,w[1]-A[1]-P)/L,1/a,1/o),l/a,c/o)}else y?_=nt(Math.abs(w[0]-A[0]-I),l,1)/a:k=nt(Math.abs(w[1]-A[1]-P),c,1)/o;const B=N._round(a*_),W=N._round(o*k);x=u(...m(B,W));const Y=S-x[0],Z=E-x[1];this.#c||=[this.x,this.y,this.width,this.height],this.width=B,this.height=W,this.x=Y,this.y=Z,this.setDims(),this.fixAndSetPosition(),this._onResizing()}_onResizing(){}altTextFinish(){this.#s?.finish()}get toolbarButtons(){return null}async addEditToolbar(){if(this._editToolbar||this.#y)return this._editToolbar;this._editToolbar=new Je(this),this.div.append(this._editToolbar.render());const{toolbarButtons:t}=this;if(t)for(const[e,s]of t)await this._editToolbar.addButton(e,s);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.#s?.destroy()}addContainer(t){const e=this._editToolbar?.div;e?e.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}createAltText(){return this.#s||(Yt.initialize(N._l10n),this.#s=new Yt(this),this.#t&&(this.#s.data=this.#t,this.#t=null)),this.#s}get altTextData(){return this.#s?.data}set altTextData(t){this.#s&&(this.#s.data=t)}get guessedAltText(){return this.#s?.guessedText}async setGuessedAltText(t){await this.#s?.setGuessedText(t)}serializeAltText(t){return this.#s?.serialize(t)}hasAltText(){return!!this.#s&&!this.#s.isEmpty()}hasAltTextData(){return this.#s?.hasData()??!1}focusCommentButton(){this.#i?.focusButton()}addCommentButton(){return this.canAddComment?this.#i||=new xs(this):null}addStandaloneCommentButton(){if(this._uiManager.hasCommentManager()){if(this.#n){this._uiManager.isEditingMode()&&this.#n.classList.remove("hidden");return}this.hasComment&&(this.#n=this.#i.renderForStandalone(),this.div.append(this.#n))}}removeStandaloneCommentButton(){this.#i.removeStandaloneCommentButton(),this.#n=null}hideStandaloneCommentButton(){this.#n?.classList.add("hidden")}get comment(){if(!this.#i)return null;const{data:{richText:t,text:e,date:s,deleted:i}}=this.#i;return{text:e,richText:t,date:s,deleted:i,color:this.getNonHCMColor(),opacity:this.opacity??1}}set comment(t){this.#i||=new xs(this),typeof t=="object"&&t!==null?this.#i.restoreData(t):this.#i.data=t,this.hasComment?(this.removeCommentButtonFromToolbar(),this.addStandaloneCommentButton(),this._uiManager.updateComment(this)):(this.addCommentButtonInToolbar(),this.removeStandaloneCommentButton(),this._uiManager.removeComment(this))}setCommentData({comment:t,popupRef:e,richText:s}){if(!e||(this.#i||=new xs(this),this.#i.setInitialText(t,s),!this.annotationElementId))return;const i=this._uiManager.getAndRemoveDataFromAnnotationStorage(this.annotationElementId);i&&this.updateFromAnnotationLayer(i)}get hasEditedComment(){return this.#i?.hasBeenEdited()}get hasDeletedComment(){return this.#i?.isDeleted()}get hasComment(){return!!this.#i&&!this.#i.isEmpty()&&!this.#i.isDeleted()}async editComment(t){this.#i||=new xs(this),this.#i.edit(t)}toggleComment(t,e=void 0){this.hasComment&&this._uiManager.toggleComment(this,t,e)}setSelectedCommentButton(t){this.#i.setSelectedButton(t)}addComment(t){if(this.hasEditedComment){const[,,,i]=t.rect,[n]=this.pageDimensions,[r]=this.pageTranslation,a=r+n+1,o=i-100,l=a+180;t.popup={contents:this.comment.text,deleted:this.comment.deleted,rect:[a,o,l,i]}}}updateFromAnnotationLayer({popup:{contents:t,deleted:e}}){this.#i.data=e?null:t}get parentBoundingClientRect(){return this.parent.boundingClientRect}render(){const t=this.div=document.createElement("div");t.setAttribute("data-editor-rotation",(360-this.rotation)%360),t.className=this.name,t.setAttribute("id",this.id),t.tabIndex=this.#a?-1:0,t.setAttribute("role","application"),this.defaultL10nId&&t.setAttribute("data-l10n-id",this.defaultL10nId),this._isVisible||t.classList.add("hidden"),this.setInForeground(),this.#U();const[e,s]=this.parentDimensions;this.parentRotation%180!==0&&(t.style.maxWidth=`${(100*s/e).toFixed(2)}%`,t.style.maxHeight=`${(100*e/s).toFixed(2)}%`);const[i,n]=this.getInitialTranslation();return this.translate(i,n),Er(this,t,["keydown","pointerdown","dblclick"]),this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#E||=new Vs({container:t,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#j.bind(this),onPinching:this.#V.bind(this),onPinchEnd:this.#_.bind(this),signal:this._uiManager._signal})),this.addStandaloneCommentButton(),this._uiManager._editorUndoBar?.hide(),t}#j(){this.#u={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height},this.#s?.toggle(!1),this.parent.togglePointerEvents(!1)}#V(t,e,s){let n=.7*(s/e)+1-.7;if(n===1)return;const r=this.#T(this.rotation),a=(S,E)=>[r[0]*S+r[2]*E,r[1]*S+r[3]*E],[o,l]=this.parentDimensions,c=this.x,h=this.y,u=this.width,f=this.height,p=N.MIN_SIZE/o,g=N.MIN_SIZE/l;n=Math.max(Math.min(n,1/u,1/f),p/u,g/f);const m=N._round(u*n),b=N._round(f*n);if(m===u&&b===f)return;this.#c||=[c,h,u,f];const y=a(u/2,f/2),A=N._round(c+y[0]),w=N._round(h+y[1]),x=a(m/2,b/2);this.x=A-x[0],this.y=w-x[1],this.width=m,this.height=b,this.setDims(),this.fixAndSetPosition(),this._onResizing()}#_(){this.#s?.toggle(!0),this.parent.togglePointerEvents(!0),this.#L()}pointerdown(t){const{isMac:e}=J.platform;if(t.button!==0||t.ctrlKey&&e){t.preventDefault();return}if(this.#g=!0,this._isDraggable){this.#R(t);return}this.#x(t)}#x(t){const{isMac:e}=J.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)}#R(t){const{isSelected:e}=this;this._uiManager.setUpDragSession();let s=!1;const i=new AbortController,n=this._uiManager.combinedSignal(i),r={capture:!0,passive:!1,signal:n},a=l=>{i.abort(),this.#r=null,this.#g=!1,this._uiManager.endDragSession()||this.#x(l),s&&this._onStopDragging()};e&&(this.#S=t.clientX,this.#C=t.clientY,this.#r=t.pointerId,this.#o=t.pointerType,window.addEventListener("pointermove",l=>{s||(s=!0,this._uiManager.toggleComment(this,!0,!1),this._onStartDragging());const{clientX:c,clientY:h,pointerId:u}=l;if(u!==this.#r){lt(l);return}const[f,p]=this.screenToPageTranslation(c-this.#S,h-this.#C);this.#S=c,this.#C=h,this._uiManager.dragSelectedEditors(f,p)},r),window.addEventListener("touchmove",lt,r),window.addEventListener("pointerdown",l=>{l.pointerType===this.#o&&(this.#E||l.isPrimary)&&a(l),lt(l)},r));const o=l=>{if(!this.#r||this.#r===l.pointerId){a(l);return}lt(l)};window.addEventListener("pointerup",o,{signal:n}),window.addEventListener("blur",o,{signal:n})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#b&&clearTimeout(this.#b),this.#b=setTimeout(()=>{this.#b=null,this.parent?.moveEditorInDOM(this)},0)}_setParentAndPosition(t,e,s){t.changeParent(this),this.x=e,this.y=s,this.fixAndSetPosition(),this._onTranslated()}getRect(t,e,s=this.rotation){const i=this.parentScale,[n,r]=this.pageDimensions,[a,o]=this.pageTranslation,l=t/i,c=e/i,h=this.x*n,u=this.y*r,f=this.width*n,p=this.height*r;switch(s){case 0:return[h+l+a,r-u-c-p+o,h+l+f+a,r-u-c+o];case 90:return[h+c+a,r-u+l+o,h+c+p+a,r-u+l+f+o];case 180:return[h-l-f+a,r-u+c+o,h-l+a,r-u+c+p+o];case 270:return[h-c-p+a,r-u-l-f+o,h-c+a,r-u-l+o];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,e){const[s,i,n,r]=t,a=n-s,o=r-i;switch(this.rotation){case 0:return[s,e-r,a,o];case 90:return[s,e-i,o,a];case 180:return[n,e-i,a,o];case 270:return[n,e-r,o,a];default:throw new Error("Invalid rotation")}}getPDFRect(){return this.getRect(0,0)}getNonHCMColor(){return this.color&&N._colorManager.convert(this._uiManager.getNonHCMColor(this.color))}onUpdatedColor(){this.#i?.onUpdatedColor()}getData(){const{comment:{text:t,color:e,date:s,opacity:i,deleted:n,richText:r},uid:a,pageIndex:o,creationDate:l,modificationDate:c}=this;return{id:a,pageIndex:o,rect:this.getPDFRect(),richText:r,contentsObj:{str:t},creationDate:l,modificationDate:s||c,popupRef:!n,color:e,opacity:i}}onceAdded(t){}isEmpty(){return!1}enableEditMode(){return this.isInEditMode()?!1:(this.parent.setEditingState(!1),this.#y=!0,!0)}disableEditMode(){return this.isInEditMode()?(this.parent.setEditingState(!0),this.#y=!1,!0):!1}isInEditMode(){return this.#y}shouldGetKeyboardEvents(){return this.#v}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){const{top:t,left:e,bottom:s,right:i}=this.getClientDimensions(),{innerHeight:n,innerWidth:r}=window;return e<r&&i>0&&t<n&&s>0}#U(){if(this.#p||!this.div)return;this.#p=new AbortController;const t=this._uiManager.combinedSignal(this.#p);this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})}rebuild(){this.#U()}rotate(t){}resize(){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||""}}serialize(t=!1,e=null){return{annotationType:this.mode,pageIndex:this.pageIndex,rect:this.getPDFRect(),rotation:this.rotation,structTreeParentId:this._structTreeParentId,popupRef:this._initialData?.popupRef||""}}static async deserialize(t,e,s){const i=new this.prototype.constructor({parent:e,id:s.getId(),uiManager:s,annotationElementId:t.annotationElementId,creationDate:t.creationDate,modificationDate:t.modificationDate});i.rotation=t.rotation,i.#t=t.accessibilityData,i._isCopy=t.isCopy||!1;const[n,r]=i.pageDimensions,[a,o,l,c]=i.getRectInCurrentCoords(t.rect,r);return i.x=a/n,i.y=o/r,i.width=l/n,i.height=c/r,i}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||this.serialize()!==null)}remove(){if(this.#p?.abort(),this.#p=null,this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.hideCommentPopup(),this.#b&&(clearTimeout(this.#b),this.#b=null),this.#B(),this.removeEditToolbar(),this.#A){for(const t of this.#A.values())clearTimeout(t);this.#A=null}this.parent=null,this.#E?.destroy(),this.#E=null,this.#d?.remove(),this.#d=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(this.#N(),this.#h.classList.remove("hidden"))}get toolbarPosition(){return null}get commentButtonPosition(){return this._uiManager.direction==="ltr"?[1,0]:[0,0]}get commentButtonPositionInPage(){const{commentButtonPosition:[t,e]}=this,[s,i,n,r]=this.getPDFRect();return[N._round(s+(n-s)*t),N._round(i+(r-i)*(1-e))]}get commentButtonColor(){return this._uiManager.makeCommentColor(this.getNonHCMColor(),this.opacity)}get commentPopupPosition(){return this.#i.commentPopupPositionInLayer}set commentPopupPosition(t){this.#i.commentPopupPositionInLayer=t}hasDefaultPopupPosition(){return this.#i.hasDefaultPopupPosition()}get commentButtonWidth(){return this.#i.commentButtonWidth}get elementBeforePopup(){return this.div}setCommentButtonStates(t){this.#i?.setCommentButtonStates(t)}keydown(t){if(!this.isResizable||t.target!==this.div||t.key!=="Enter")return;this._uiManager.setSelected(this),this.#u={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const e=this.#h.children;if(!this.#e){this.#e=Array.from(e);const r=this.#$.bind(this),a=this.#K.bind(this),o=this._uiManager._signal;for(const l of this.#e){const c=l.getAttribute("data-resizer-name");l.setAttribute("role","spinbutton"),l.addEventListener("keydown",r,{signal:o}),l.addEventListener("blur",a,{signal:o}),l.addEventListener("focus",this.#X.bind(this,c),{signal:o}),l.setAttribute("data-l10n-id",N._l10nResizer[c])}}const s=this.#e[0];let i=0;for(const r of e){if(r===s)break;i++}const n=(360-this.rotation+this.parentRotation)%360/90*(this.#e.length/4);if(n!==i){if(n<i)for(let a=0;a<i-n;a++)this.#h.append(this.#h.firstElementChild);else if(n>i)for(let a=0;a<n-i;a++)this.#h.firstElementChild.before(this.#h.lastElementChild);let r=0;for(const a of e){const l=this.#e[r++].getAttribute("data-resizer-name");a.setAttribute("data-l10n-id",N._l10nResizer[l])}}this.#Y(0),this.#v=!0,this.#h.firstElementChild.focus({focusVisible:!0}),t.preventDefault(),t.stopImmediatePropagation()}#$(t){N._resizerKeyboardManager.exec(this,t)}#K(t){this.#v&&t.relatedTarget?.parentNode!==this.#h&&this.#B()}#X(t){this.#m=this.#v?t:""}#Y(t){if(this.#e)for(const e of this.#e)e.tabIndex=t}_resizeWithKeyboard(t,e){this.#v&&this.#O(this.#m,{deltaX:t,deltaY:e,fromKeyboard:!0})}#B(){this.#v=!1,this.#Y(-1),this.#L()}_stopResizingWithKeyboard(){this.#B(),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.#s?.toggleAltTextBadge(!1)}focus(){this.div&&!this.div.contains(document.activeElement)&&setTimeout(()=>this.div?.focus({preventScroll:!0}),0)}unselect(){this.isSelected&&(this.isSelected=!1,this.#h?.classList.add("hidden"),this.div?.classList.remove("selectedEditor"),this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),this._editToolbar?.hide(),this.#s?.toggleAltTextBadge(!0),this.hideCommentPopup())}hideCommentPopup(){this.hasComment&&this._uiManager.toggleComment(null)}updateParams(t,e){}disableEditing(){}enableEditing(){}get canChangeContent(){return!1}enterInEditMode(){this.canChangeContent&&(this.enableEditMode(),this.div.focus())}dblclick(t){t.target.nodeName!=="BUTTON"&&(this.enterInEditMode(),this.parent.updateToolbar({mode:this.constructor._editorType,editId:this.uid}))}getElementForAltText(){return this.div}get contentDiv(){return this.div}get isEditing(){return this.#f}set isEditing(t){this.#f=t,this.parent&&(t?(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(t,e=!1){if(e){this.#A||=new Map;const{action:s}=t;let i=this.#A.get(s);i&&clearTimeout(i),i=setTimeout(()=>{this._reportTelemetry(t),this.#A.delete(s),this.#A.size===0&&(this.#A=null)},N._telemetryTimeout),this.#A.set(s,i);return}t.type||=this.editorType,this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:t}})}show(t=this._isVisible){this.div.classList.toggle("hidden",!t),this._isVisible=t}enable(){this.div&&(this.div.tabIndex=0),this.#a=!1}disable(){this.div&&(this.div.tabIndex=-1),this.#a=!0}updateFakeAnnotationElement(t){if(!this.#d&&!this.deleted){this.#d=t.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(t){if(this.deleted)return t.hide(),null;let e=t.container.querySelector(".annotationContent");if(!e)e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),t.container.prepend(e);else if(e.nodeName==="CANVAS"){const s=e;e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),s.before(e)}return e}resetAnnotationElement(t){const{firstElementChild:e}=t.container;e?.nodeName==="DIV"&&e.classList.contains("annotationContent")&&e.remove()}}class nl extends N{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const Un=3285377520,Nt=4294901760,Vt=65535;class Mi{constructor(t){this.h1=t?t&4294967295:Un,this.h2=t?t&4294967295:Un}update(t){let e,s;if(typeof t=="string"){e=new Uint8Array(t.length*2),s=0;for(let g=0,m=t.length;g<m;g++){const b=t.charCodeAt(g);b<=255?e[s++]=b:(e[s++]=b>>>8,e[s++]=b&255)}}else if(ArrayBuffer.isView(t))e=t.slice(),s=e.byteLength;else throw new Error("Invalid data format, must be a string or TypedArray.");const i=s>>2,n=s-i*4,r=new Uint32Array(e.buffer,0,i);let a=0,o=0,l=this.h1,c=this.h2;const h=3432918353,u=461845907,f=h&Vt,p=u&Vt;for(let g=0;g<i;g++)g&1?(a=r[g],a=a*h&Nt|a*f&Vt,a=a<<15|a>>>17,a=a*u&Nt|a*p&Vt,l^=a,l=l<<13|l>>>19,l=l*5+3864292196):(o=r[g],o=o*h&Nt|o*f&Vt,o=o<<15|o>>>17,o=o*u&Nt|o*p&Vt,c^=o,c=c<<13|c>>>19,c=c*5+3864292196);switch(a=0,n){case 3:a^=e[i*4+2]<<16;case 2:a^=e[i*4+1]<<8;case 1:a^=e[i*4],a=a*h&Nt|a*f&Vt,a=a<<15|a>>>17,a=a*u&Nt|a*p&Vt,i&1?l^=a:c^=a}this.h1=l,this.h2=c}hexdigest(){let t=this.h1,e=this.h2;return t^=e>>>1,t=t*3981806797&Nt|t*36045&Vt,e=e*4283543511&Nt|((e<<16|t>>>16)*2950163797&Nt)>>>16,t^=e>>>1,t=t*444984403&Nt|t*60499&Vt,e=e*3301882366&Nt|((e<<16|t>>>16)*3120437893&Nt)>>>16,t^=e>>>1,(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const ss=Object.freeze({map:null,hash:"",transfer:void 0});class Wi{#t=!1;#e=null;#s=null;#i=new Map;onSetModified=null;onResetModified=null;onAnnotationEditor=null;getValue(t,e){const s=this.#i.get(t);return s===void 0?e:Object.assign(e,s)}getRawValue(t){return this.#i.get(t)}remove(t){const e=this.#i.get(t);e!==void 0&&(e instanceof N&&this.#s.delete(e.annotationElementId),this.#i.delete(t),this.#i.size===0&&this.resetModified(),!this.#i.values().some(s=>s instanceof N)&&this.onAnnotationEditor?.(null))}setValue(t,e){const s=this.#i.get(t);let i=!1;if(s!==void 0)for(const[n,r]of Object.entries(e))s[n]!==r&&(i=!0,s[n]=r);else i=!0,this.#i.set(t,e);i&&this.#n(),e instanceof N&&((this.#s||=new Map).set(e.annotationElementId,e),this.onAnnotationEditor?.(e.constructor._type))}has(t){return this.#i.has(t)}get size(){return this.#i.size}#n(){this.#t||(this.#t=!0,this.onSetModified?.())}resetModified(){this.#t&&(this.#t=!1,this.onResetModified?.())}get print(){return new _r(this)}get serializable(){if(this.#i.size===0)return ss;const t=new Map,e=new Mi,s=[],i=Object.create(null);let n=!1;for(const[r,a]of this.#i){const o=a instanceof N?a.serialize(!1,i):a;a.page&&(a.pageIndex=a.page._pageIndex,delete a.page),o&&(t.set(r,o),e.update(`${r}:${JSON.stringify(o)}`),n||=!!o.bitmap)}if(n)for(const r of t.values())r.bitmap&&s.push(r.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:s}:ss}get editorStats(){let t=null;const e=new Map;let s=0,i=0;for(const n of this.#i.values()){if(!(n instanceof N)){n.popup&&(n.popup.deleted?i+=1:s+=1);continue}n.isCommentDeleted?i+=1:n.hasEditedComment&&(s+=1);const r=n.telemetryFinalData;if(!r)continue;const{type:a}=r;e.getOrInsertComputed(a,()=>Object.getPrototypeOf(n).constructor),t||=Object.create(null);const o=t[a]||=new Map;for(const[l,c]of Object.entries(r)){if(l==="type")continue;const h=o.getOrInsertComputed(l,Hi);h.set(c,(h.get(c)??0)+1)}}if((i>0||s>0)&&(t||=Object.create(null),t.comments={deleted:i,edited:s}),!t)return null;for(const[n,r]of e)t[n]=r.computeTelemetryFinalData(t[n]);return t}resetModifiedIds(){this.#e=null}updateEditor(t,e){const s=this.#s?.get(t);return s?(s.updateFromAnnotationLayer(e),!0):!1}getEditor(t){return this.#s?.get(t)||null}get modifiedIds(){if(this.#e)return this.#e;const t=[];if(this.#s)for(const s of this.#s.values())s.serialize()&&t.push(s.annotationElementId);let e="";if(t.length){const s=new Mi;s.update(t.join(",")),e=s.hexdigest()}return this.#e={ids:new Set(t),hash:e}}[Symbol.iterator](){return this.#i.entries()}}class _r extends Wi{#t=ss;constructor(t){super();const{serializable:e}=t;if(e===ss)return;const{map:s,hash:i,transfer:n}=e,r=structuredClone(s,n?{transfer:n}:null);this.#t={map:r,hash:i,transfer:[]}}get print(){K("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#t}get modifiedIds(){return z(this,"modifiedIds",{ids:new Set,hash:""})}}const Pe="__forcedDependency",{floor:zn,ceil:$n}=Math;function Gn(d,t,e,s,i,n){d[t*4+0]=Math.min(d[t*4+0],e),d[t*4+1]=Math.min(d[t*4+1],s),d[t*4+2]=Math.max(d[t*4+2],i),d[t*4+3]=Math.max(d[t*4+3],n)}function rl(d,t,e,s,i){let n;d?(d<0&&(n=i[0],i[0]=i[2],i[2]=n),i[0]*=d,i[2]*=d,t<0&&(n=i[1],i[1]=i[3],i[3]=n),i[1]*=t,i[3]*=t):i.fill(0),i[0]+=e,i[1]+=s,i[2]+=e,i[3]+=s}const Pi=new Uint32Array(new Uint8Array([255,255,0,0]).buffer)[0];class al{#t;#e;constructor(t,e){this.#t=t,this.#e=e}get length(){return this.#t.length}isEmpty(t){return this.#t[t]===Pi}minX(t){return this.#e[t*4+0]/256}minY(t){return this.#e[t*4+1]/256}maxX(t){return(this.#e[t*4+2]+1)/256}maxY(t){return(this.#e[t*4+3]+1)/256}}const Vn=(d,t)=>d?.getOrInsertComputed(t,()=>({dependencies:new Set,isRenderingOperation:!1}));class ol{#t=[[1,0,0,1,0,0]];#e=[-1/0,-1/0,1/0,1/0];#s=new Float64Array(te);_pendingBBoxIdx=-1;#i;#n;#a;#r;_savesStack=[];_markedContentStack=[];constructor(t,e){this.#i=t.width,this.#n=t.height,this.#o(e)}growOperationsCount(t){t>=this.#r.length&&this.#o(t,this.#r)}#o(t,e){const s=new ArrayBuffer(t*4);this.#a=new Uint8ClampedArray(s),this.#r=new Uint32Array(s),e&&e.length>0?(this.#r.set(e),this.#r.fill(Pi,e.length)):this.#r.fill(Pi)}get clipBox(){return this.#e}save(t){return this.#e={__proto__:this.#e},this._savesStack.push(t),this}restore(t,e){const s=Object.getPrototypeOf(this.#e);if(s===null)return this;this.#e=s;const i=this._savesStack.pop();return i!==void 0&&(e?.(i,t),this.#r[t]=this.#r[i]),this}recordOpenMarker(t){return this._savesStack.push(t),this}getOpenMarker(){return this._savesStack.length===0?null:this._savesStack.at(-1)}recordCloseMarker(t,e){const s=this._savesStack.pop();return s!==void 0&&(e?.(s,t),this.#r[t]=this.#r[s]),this}beginMarkedContent(t){return this._markedContentStack.push(t),this}endMarkedContent(t,e){const s=this._markedContentStack.pop();return s!==void 0&&(e?.(s,t),this.#r[t]=this.#r[s]),this}pushBaseTransform(t){return this.#t.push(T.multiplyByDOMMatrix(this.#t.at(-1),t.getTransform())),this}popBaseTransform(){return this.#t.length>1&&this.#t.pop(),this}resetBBox(t){return this._pendingBBoxIdx!==t&&(this._pendingBBoxIdx=t,this.#s.set(te,0)),this}recordClipBox(t,e,s,i,n,r){const a=T.multiplyByDOMMatrix(this.#t.at(-1),e.getTransform()),o=te.slice();T.axialAlignedBoundingBox([s,n,i,r],a,o);const l=T.intersect(this.#e,o);return l?(this.#e[0]=l[0],this.#e[1]=l[1],this.#e[2]=l[2],this.#e[3]=l[3]):(this.#e[0]=this.#e[1]=1/0,this.#e[2]=this.#e[3]=-1/0),this}recordBBox(t,e,s,i,n,r){const a=this.#e;if(a[0]===1/0)return this;const o=T.multiplyByDOMMatrix(this.#t.at(-1),e.getTransform());if(a[0]===-1/0)return T.axialAlignedBoundingBox([s,n,i,r],o,this.#s),this;const l=te.slice();return T.axialAlignedBoundingBox([s,n,i,r],o,l),this.#s[0]=nt(l[0],a[0],this.#s[0]),this.#s[1]=nt(l[1],a[1],this.#s[1]),this.#s[2]=nt(l[2],this.#s[2],a[2]),this.#s[3]=nt(l[3],this.#s[3],a[3]),this}recordFullPageBBox(t){return this.#s[0]=Math.max(0,this.#e[0]),this.#s[1]=Math.max(0,this.#e[1]),this.#s[2]=Math.min(this.#i,this.#e[2]),this.#s[3]=Math.min(this.#n,this.#e[3]),this}recordOperation(t,e=!1,s){if(this._pendingBBoxIdx!==t)return this;const i=zn(this.#s[0]*256/this.#i),n=zn(this.#s[1]*256/this.#n),r=$n(this.#s[2]*256/this.#i),a=$n(this.#s[3]*256/this.#n);if(Gn(this.#a,t,i,n,r,a),s)for(const o of s)for(const l of o)l!==t&&Gn(this.#a,l,i,n,r,a);return e||(this._pendingBBoxIdx=-1),this}bboxToClipBoxDropOperation(t){return this._pendingBBoxIdx===t&&(this._pendingBBoxIdx=-1,this.#e[0]=Math.max(this.#e[0],this.#s[0]),this.#e[1]=Math.max(this.#e[1],this.#s[1]),this.#e[2]=Math.min(this.#e[2],this.#s[2]),this.#e[3]=Math.min(this.#e[3],this.#s[3])),this}take(){return new al(this.#r,this.#a)}takeDebugMetadata(){throw new Error("Unreachable")}recordSimpleData(t,e){return this}recordIncrementalData(t,e){return this}resetIncrementalData(t,e){return this}recordNamedData(t,e){return this}recordSimpleDataFromNamed(t,e,s){return this}recordFutureForcedDependency(t,e){return this}inheritSimpleDataAsFutureForcedDependencies(t){return this}inheritPendingDependenciesAsFutureForcedDependencies(){return this}recordCharacterBBox(t,e,s,i=1,n=0,r=0,a){return this}getSimpleIndex(t){}recordDependencies(t,e){return this}recordNamedDependency(t,e){return this}recordShowTextOperation(t,e=!1){return this}}class ll{#t={__proto__:null};#e={__proto__:null,transform:[],moveText:[],sameLineText:[],[Pe]:[]};#s=new Map;#i=new Set;#n=new Map;#a;#r;#o;constructor(t,e=!1){this.#o=t,e&&(this.#a=new Map,this.#r=(s,i)=>{Vn(this.#a,i).dependencies.add(s)})}get clipBox(){return this.#o.clipBox}growOperationsCount(t){this.#o.growOperationsCount(t)}save(t){return this.#t={__proto__:this.#t},this.#e={__proto__:this.#e,transform:{__proto__:this.#e.transform},moveText:{__proto__:this.#e.moveText},sameLineText:{__proto__:this.#e.sameLineText},[Pe]:{__proto__:this.#e[Pe]}},this.#o.save(t),this}restore(t){this.#o.restore(t,this.#r);const e=Object.getPrototypeOf(this.#t);return e===null?this:(this.#t=e,this.#e=Object.getPrototypeOf(this.#e),this)}recordOpenMarker(t){return this.#o.recordOpenMarker(t,this.#r),this}getOpenMarker(){return this.#o.getOpenMarker()}recordCloseMarker(t){return this.#o.recordCloseMarker(t,this.#r),this}beginMarkedContent(t){return this.#o.beginMarkedContent(t),this}endMarkedContent(t){return this.#o.endMarkedContent(t,this.#r),this}pushBaseTransform(t){return this.#o.pushBaseTransform(t),this}popBaseTransform(){return this.#o.popBaseTransform(),this}recordSimpleData(t,e){return this.#t[t]=e,this}recordIncrementalData(t,e){return this.#e[t].push(e),this}resetIncrementalData(t,e){return this.#e[t].length=0,this}recordNamedData(t,e){return this.#s.set(t,e),this}recordSimpleDataFromNamed(t,e,s){this.#t[t]=this.#s.get(e)??s}recordFutureForcedDependency(t,e){return this.recordIncrementalData(Pe,e),this}inheritSimpleDataAsFutureForcedDependencies(t){for(const e of t)e in this.#t&&this.recordFutureForcedDependency(e,this.#t[e]);return this}inheritPendingDependenciesAsFutureForcedDependencies(){for(const t of this.#i)this.recordFutureForcedDependency(Pe,t);return this}resetBBox(t){return this.#o.resetBBox(t),this}recordClipBox(t,e,s,i,n,r){return this.#o.recordClipBox(t,e,s,i,n,r),this}recordBBox(t,e,s,i,n,r){return this.#o.recordBBox(t,e,s,i,n,r),this}recordCharacterBBox(t,e,s,i=1,n=0,r=0,a){const o=s.bbox;let l,c;if(o&&(l=o[2]!==o[0]&&o[3]!==o[1]&&this.#n.get(s),l!==!1&&(c=[0,0,0,0],T.axialAlignedBoundingBox(o,s.fontMatrix,c),(i!==1||n!==0||r!==0)&&rl(i,-i,n,r,c),l)))return this.recordBBox(t,e,c[0],c[2],c[1],c[3]);if(!a)return this.recordFullPageBBox(t);const h=a();return o&&c&&l===void 0&&(l=c[0]<=n-h.actualBoundingBoxLeft&&c[2]>=n+h.actualBoundingBoxRight&&c[1]<=r-h.actualBoundingBoxAscent&&c[3]>=r+h.actualBoundingBoxDescent,this.#n.set(s,l),l)?this.recordBBox(t,e,c[0],c[2],c[1],c[3]):this.recordBBox(t,e,n-h.actualBoundingBoxLeft,n+h.actualBoundingBoxRight,r-h.actualBoundingBoxAscent,r+h.actualBoundingBoxDescent)}recordFullPageBBox(t){return this.#o.recordFullPageBBox(t),this}getSimpleIndex(t){return this.#t[t]}recordDependencies(t,e){const s=this.#i,i=this.#t,n=this.#e;for(const r of e)r in this.#t?s.add(i[r]):r in n&&n[r].forEach(s.add,s);return this}recordNamedDependency(t,e){return this.#s.has(e)&&this.#i.add(this.#s.get(e)),this}recordOperation(t,e=!1){if(this.recordDependencies(t,[Pe]),this.#a){const i=Vn(this.#a,t),{dependencies:n}=i;this.#i.forEach(n.add,n),this.#o._savesStack.forEach(n.add,n),this.#o._markedContentStack.forEach(n.add,n),n.delete(t),i.isRenderingOperation=!0}const s=!e&&t===this.#o._pendingBBoxIdx;return this.#o.recordOperation(t,e,[this.#i,this.#o._savesStack,this.#o._markedContentStack]),s&&this.#i.clear(),this}recordShowTextOperation(t,e=!1){const s=Array.from(this.#i);this.recordOperation(t,e),this.recordIncrementalData("sameLineText",t);for(const i of s)this.recordIncrementalData("sameLineText",i);return this}bboxToClipBoxDropOperation(t,e=!1){const s=!e&&t===this.#o._pendingBBoxIdx;return this.#o.bboxToClipBoxDropOperation(t),s&&this.#i.clear(),this}take(){return this.#n.clear(),this.#o.take()}takeDebugMetadata(){return this.#a}}class is{#t;#e;#s;#i=0;#n=0;constructor(t,e,s){if(t instanceof is&&t.#s===!!s)return t;this.#t=t,this.#e=e,this.#s=!!s}get clipBox(){return this.#t.clipBox}growOperationsCount(){throw new Error("Unreachable")}save(t){return this.#n++,this.#t.save(this.#e),this}restore(t){return this.#n>0&&(this.#t.restore(this.#e),this.#n--),this}recordOpenMarker(t){return this.#i++,this}getOpenMarker(){return this.#i>0?this.#e:this.#t.getOpenMarker()}recordCloseMarker(t){return this.#i--,this}beginMarkedContent(t){return this}endMarkedContent(t){return this}pushBaseTransform(t){return this.#t.pushBaseTransform(t),this}popBaseTransform(){return this.#t.popBaseTransform(),this}recordSimpleData(t,e){return this.#t.recordSimpleData(t,this.#e),this}recordIncrementalData(t,e){return this.#t.recordIncrementalData(t,this.#e),this}resetIncrementalData(t,e){return this.#t.resetIncrementalData(t,this.#e),this}recordNamedData(t,e){return this}recordSimpleDataFromNamed(t,e,s){return this.#t.recordSimpleDataFromNamed(t,e,this.#e),this}recordFutureForcedDependency(t,e){return this.#t.recordFutureForcedDependency(t,this.#e),this}inheritSimpleDataAsFutureForcedDependencies(t){return this.#t.inheritSimpleDataAsFutureForcedDependencies(t),this}inheritPendingDependenciesAsFutureForcedDependencies(){return this.#t.inheritPendingDependenciesAsFutureForcedDependencies(),this}resetBBox(t){return this.#s||this.#t.resetBBox(this.#e),this}recordClipBox(t,e,s,i,n,r){return this.#s||this.#t.recordClipBox(this.#e,e,s,i,n,r),this}recordBBox(t,e,s,i,n,r){return this.#s||this.#t.recordBBox(this.#e,e,s,i,n,r),this}recordCharacterBBox(t,e,s,i,n,r,a){return this.#s||this.#t.recordCharacterBBox(this.#e,e,s,i,n,r,a),this}recordFullPageBBox(t){return this.#s||this.#t.recordFullPageBBox(this.#e),this}getSimpleIndex(t){return this.#t.getSimpleIndex(t)}recordDependencies(t,e){return this.#t.recordDependencies(this.#e,e),this}recordNamedDependency(t,e){return this.#t.recordNamedDependency(this.#e,e),this}recordOperation(t){return this.#t.recordOperation(this.#e,!0),this}recordShowTextOperation(t){return this.#t.recordShowTextOperation(this.#e,!0),this}bboxToClipBoxDropOperation(t){return this.#s||this.#t.bboxToClipBoxDropOperation(this.#e,!0),this}take(){throw new Error("Unreachable")}takeDebugMetadata(){throw new Error("Unreachable")}}const Ft={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"]};class Rs{#t;#e;#s=4;#i=0;#n=new Rs.#a(this.#s*6);static#a=J.isFloat16ArraySupported?Float16Array:Float32Array;constructor(t){this.#t=t.width,this.#e=t.height}record(t,e,s,i){if(this.#i===this.#s){this.#s*=2;const a=new Rs.#a(this.#s*6);a.set(this.#n),this.#n=a}const n=et(t);let r;if(i[0]!==1/0){const a=te.slice();T.axialAlignedBoundingBox([0,-s,e,0],n,a);const o=T.intersect(i,a);if(!o)return;const[l,c,h,u]=o;if(l!==a[0]||c!==a[1]||h!==a[2]||u!==a[3]){const f=Math.atan2(n[1],n[0]),p=Math.abs(Math.sin(f)),g=Math.abs(Math.cos(f));if(p<1e-6||g<1e-6||Math.abs(p-g)<1e-6)r=[l,c,l,u,h,c];else{const m=h-l,b=u-c,y=p*p,A=g*g,w=g*p,x=A-y,S=(b*A-m*w)/x,E=(b*w-m*y)/x;r=[l+E,c,l,c+S,h,u-S]}}}r||(r=[0,-s,0,0,e,-s],T.applyTransform(r,n,0),T.applyTransform(r,n,2),T.applyTransform(r,n,4)),r[0]/=this.#t,r[1]/=this.#e,r[2]/=this.#t,r[3]/=this.#e,r[4]/=this.#t,r[5]/=this.#e,this.#n.set(r,this.#i*6),this.#i++}take(){return this.#n.subarray(0,this.#i*6)}}class cl{#t=new Set;#e=null;constructor({ownerDocument:t=globalThis.document,styleElement:e=null}){this._document=t,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(t){this.nativeFontFaces.add(t),this._document.fonts.add(t)}removeNativeFontFace(t){this.nativeFontFaces.delete(t),this._document.fonts.delete(t)}insertRule(t){const e=this.#s();e.insertRule(t,e.cssRules.length)}#s(){if(this.#e)return this.#e;const t=this._document.defaultView?.CSSStyleSheet||globalThis.CSSStyleSheet;if(!this.styleElement&&t){const{adoptedStyleSheets:e}=this._document;if(e){const s=new t;return e.push(s),this.#e=s}}return this.styleElement||(this.styleElement=this._document.createElement("style"),this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement)),this.#e=this.styleElement.sheet}clear(){for(const t of this.nativeFontFaces)this._document.fonts.delete(t);if(this.nativeFontFaces.clear(),this.#t.clear(),this.#e){const{adoptedStyleSheets:t}=this._document;t?.includes(this.#e)&&(this._document.adoptedStyleSheets=t.filter(e=>e!==this.#e)),this.#e=null}this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,disableFontFace:e,_inspectFont:s}){if(!(!t||this.#t.has(t.loadedName))){if(ct(!e,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){const{loadedName:i,src:n,style:r}=t,a=new FontFace(i,n,r);this.addNativeFontFace(a);try{await a.load(),this.#t.add(i),s?.(t)}catch{V(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(a)}return}K("Not implemented: loadSystemFont without the Font Loading API.")}}async bind(t){if(t.attached||t.missingFile&&!t.systemFontInfo)return;if(t.attached=!0,t.systemFontInfo){await this.loadSystemFont(t);return}if(this.isFontLoadingAPISupported){const s=t.createNativeFontFace();if(s){this.addNativeFontFace(s);try{await s.loaded}catch(i){throw V(`Failed to load font '${s.family}': '${i}'.`),t.disableFontFace=!0,i}}return}const e=t.createFontFaceRule();if(e){if(this.insertRule(e),this.isSyncFontLoadingSupported)return;await new Promise(s=>{const i=this._queueLoadingCallback(s);this._prepareFontLoadEvent(t,i)})}}get isFontLoadingAPISupported(){const t=!!this._document?.fonts;return z(this,"isFontLoadingAPISupported",t)}get isSyncFontLoadingSupported(){return z(this,"isSyncFontLoadingSupported",Pt||J.platform.isFirefox)}_queueLoadingCallback(t){function e(){for(ct(!i.done,"completeRequest() cannot be called twice."),i.done=!0;s.length>0&&s[0].done;){const n=s.shift();setTimeout(n.callback,0)}}const{loadingRequests:s}=this,i={done:!1,complete:e,callback:t};return s.push(i),i}get _loadTestFont(){const t=atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");return z(this,"_loadTestFont",t)}_prepareFontLoadEvent(t,e){function s(x,S){return x.charCodeAt(S)<<24|x.charCodeAt(S+1)<<16|x.charCodeAt(S+2)<<8|x.charCodeAt(S+3)&255}function i(x){return String.fromCharCode(x>>24&255,x>>16&255,x>>8&255,x&255)}function n(x,S,E,_){const k=x.substring(0,S),I=x.substring(S+E);return k+_+I}let r,a;const o=this._document.createElement("canvas");o.width=1,o.height=1;const l=o.getContext("2d");let c=0;function h(x,S){if(++c>30){V("Load test font never loaded."),S();return}if(l.font="30px "+x,l.fillText(".",0,20),l.getImageData(0,0,1,1).data[3]>0){S();return}setTimeout(h.bind(null,x,S))}const u=`lt${Date.now()}${this.loadTestFontId++}`;let f=this._loadTestFont;f=n(f,976,u.length,u);const g=16,m=1482184792;let b=s(f,g);for(r=0,a=u.length-3;r<a;r+=4)b=b-m+s(u,r)|0;r<u.length&&(b=b-m+s(u+"XXX",r)|0),f=n(f,g,4,i(b));const y=`url(data:font/opentype;base64,${btoa(f)});`,A=`@font-face {font-family:"${u}";src:${y}}`;this.insertRule(A);const w=this._document.createElement("div");w.style.visibility="hidden",w.style.width=w.style.height="10px",w.style.position="absolute",w.style.top=w.style.left="0px";for(const x of[t.loadedName,u]){const S=this._document.createElement("span");S.textContent="Hi",S.style.fontFamily=x,w.append(S)}this._document.body.append(w),h(u,()=>{w.remove(),e.complete()})}}class hl{compiledGlyphs=Object.create(null);#t;constructor(t,e=null,s,i){this.#t=t,this._inspectFont=e,s&&(this.charProcOperatorList=s),i&&Object.assign(this,i)}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let t;if(!this.cssFontInfo)t=new FontFace(this.loadedName,this.data,{});else{const e={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(e.style=`oblique ${this.cssFontInfo.italicAngle}deg`),t=new FontFace(this.cssFontInfo.fontFamily,this.data,e)}return this._inspectFont?.(this),t}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;const t=`url(data:${this.mimetype};base64,${this.data.toBase64()});`;let e;if(!this.cssFontInfo)e=`@font-face {font-family:"${this.loadedName}";src:${t}}`;else{let s=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(s+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),e=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${s}src:${t}}`}return this._inspectFont?.(this,t),e}getPathGenerator(t,e){if(this.compiledGlyphs[e]!==void 0)return this.compiledGlyphs[e];const s=this.loadedName+"_path_"+e;let i;try{i=t.get(s)}catch(r){V(`getPathGenerator - ignoring character: "${r}".`)}const n=Cr(i?.path);return this.fontExtraProperties||t.delete(s),this.compiledGlyphs[e]=n}get black(){return this.#t.black}get bold(){return this.#t.bold}get disableFontFace(){return this.#t.disableFontFace}set disableFontFace(t){z(this,"disableFontFace",!!t)}get fontExtraProperties(){return this.#t.fontExtraProperties}get isInvalidPDFjsFont(){return this.#t.isInvalidPDFjsFont}get isType3Font(){return this.#t.isType3Font}get italic(){return this.#t.italic}get missingFile(){return this.#t.missingFile}get remeasure(){return this.#t.remeasure}get vertical(){return this.#t.vertical}get ascent(){return this.#t.ascent}get defaultWidth(){return this.#t.defaultWidth}get descent(){return this.#t.descent}get bbox(){return this.#t.bbox}get fontMatrix(){return this.#t.fontMatrix}get fallbackName(){return this.#t.fallbackName}get loadedName(){return this.#t.loadedName}get mimetype(){return this.#t.mimetype}get name(){return this.#t.name}get data(){return this.#t.data}clearData(){this.#t.clearData()}get cssFontInfo(){return this.#t.cssFontInfo}get systemFontInfo(){return this.#t.systemFontInfo}get defaultVMetrics(){return this.#t.defaultVMetrics}}class dl{static strings=["fontFamily","fontWeight","italicAngle"]}class ul{static strings=["css","loadedName","baseFontName","src"]}class Ht{static bools=["black","bold","disableFontFace","fontExtraProperties","isInvalidPDFjsFont","isType3Font","italic","missingFile","remeasure","vertical"];static numbers=["ascent","defaultWidth","descent"];static strings=["fallbackName","loadedName","mimetype","name"];static OFFSET_NUMBERS=Math.ceil(this.bools.length*2/8);static OFFSET_BBOX=this.OFFSET_NUMBERS+this.numbers.length*8;static OFFSET_FONT_MATRIX=this.OFFSET_BBOX+1+8;static OFFSET_DEFAULT_VMETRICS=this.OFFSET_FONT_MATRIX+1+48;static OFFSET_STRINGS=this.OFFSET_DEFAULT_VMETRICS+1+6}class ue{static KIND=0;static HAS_BBOX=1;static HAS_BACKGROUND=2;static SHADING_TYPE=3;static N_COORD=4;static N_COLOR=8;static N_STOP=12;static N_FIGURES=16}class fl{#t;#e=new TextDecoder;#s;constructor(t){this.#t=t,this.#s=new DataView(t)}#i(t){ct(t<dl.strings.length,"Invalid string index");let e=0;for(let i=0;i<t;i++)e+=this.#s.getUint32(e)+4;const s=this.#s.getUint32(e);return this.#e.decode(new Uint8Array(this.#t,e+4,s))}get fontFamily(){return this.#i(0)}get fontWeight(){return this.#i(1)}get italicAngle(){return this.#i(2)}}class pl{#t;#e=new TextDecoder;#s;constructor(t){this.#t=t,this.#s=new DataView(t)}get guessFallback(){return this.#s.getUint8(0)!==0}#i(t){ct(t<ul.strings.length,"Invalid string index");let e=5;for(let i=0;i<t;i++)e+=this.#s.getUint32(e)+4;const s=this.#s.getUint32(e);return this.#e.decode(new Uint8Array(this.#t,e+4,s))}get css(){return this.#i(0)}get loadedName(){return this.#i(1)}get baseFontName(){return this.#i(2)}get src(){return this.#i(3)}get style(){let t=1;t+=4+this.#s.getUint32(t);const e=this.#s.getUint32(t),s=this.#e.decode(new Uint8Array(this.#t,t+4,e));t+=4+e;const i=this.#s.getUint32(t),n=this.#e.decode(new Uint8Array(this.#t,t+4,i));return{style:s,weight:n}}}class gl{#t;#e=new TextDecoder;#s;constructor({buffer:t,extra:e}){this.#t=t,this.#s=new DataView(t),e&&Object.assign(this,e)}#i(t){ct(t<Ht.bools.length,"Invalid boolean index");const e=Math.floor(t/4),s=t*2%8,i=this.#s.getUint8(e)>>s&3;return i===0?void 0:i===2}get black(){return this.#i(0)}get bold(){return this.#i(1)}get disableFontFace(){return this.#i(2)}get fontExtraProperties(){return this.#i(3)}get isInvalidPDFjsFont(){return this.#i(4)}get isType3Font(){return this.#i(5)}get italic(){return this.#i(6)}get missingFile(){return this.#i(7)}get remeasure(){return this.#i(8)}get vertical(){return this.#i(9)}#n(t){return ct(t<Ht.numbers.length,"Invalid number index"),this.#s.getFloat64(Ht.OFFSET_NUMBERS+t*8)}get ascent(){return this.#n(0)}get defaultWidth(){return this.#n(1)}get descent(){return this.#n(2)}#a(t,e,s,i){const n=this.#s.getUint8(t);if(n===0)return;ct(n===e,"Invalid array length."),t+=1;const r=new Array(n);for(let a=0;a<n;a++)r[a]=this.#s[s](t,!0),t+=i;return r}get bbox(){return this.#a(Ht.OFFSET_BBOX,4,"getInt16",2)}get fontMatrix(){return this.#a(Ht.OFFSET_FONT_MATRIX,6,"getFloat64",8)}get defaultVMetrics(){return this.#a(Ht.OFFSET_DEFAULT_VMETRICS,3,"getInt16",2)}#r(t){ct(t<Ht.strings.length,"Invalid string index");let e=Ht.OFFSET_STRINGS+4;for(let i=0;i<t;i++)e+=this.#s.getUint32(e)+4;const s=this.#s.getUint32(e);return this.#e.decode(new Uint8Array(this.#t,e+4,s))}get fallbackName(){return this.#r(0)}get loadedName(){return this.#r(1)}get mimetype(){return this.#r(2)}get name(){return this.#r(3)}#o(){let t=Ht.OFFSET_STRINGS;const e=this.#s.getUint32(t);t+=4+e;const s=this.#s.getUint32(t);t+=4+s;const i=this.#s.getUint32(t);t+=4+i;const n=this.#s.getUint32(t);return{offset:t,length:n}}get data(){const{offset:t,length:e}=this.#o();return e===0?void 0:new Uint8Array(this.#t,t+4,e)}clearData(){const{offset:t,length:e}=this.#o();e!==0&&(this.#s.setUint32(t,0),this.#t=new Uint8Array(this.#t,0,t+4).slice().buffer,this.#s=new DataView(this.#t))}get cssFontInfo(){let t=Ht.OFFSET_STRINGS;const e=this.#s.getUint32(t);t+=4+e;const s=this.#s.getUint32(t);t+=4+s;const i=this.#s.getUint32(t);if(i===0)return null;const n=new Uint8Array(i);return n.set(new Uint8Array(this.#t,t+4,i)),new fl(n.buffer)}get systemFontInfo(){let t=Ht.OFFSET_STRINGS;const e=this.#s.getUint32(t);t+=4+e;const s=this.#s.getUint32(t);if(s===0)return null;const i=new Uint8Array(s);return i.set(new Uint8Array(this.#t,t+4,s)),new pl(i.buffer)}}class ml{constructor(t){this.buffer=t,this.view=new DataView(t),this.data=new Uint8Array(t)}getIR(){const t=this.view,e=this.data[ue.KIND],s=!!this.data[ue.HAS_BBOX],i=!!this.data[ue.HAS_BACKGROUND],n=t.getUint32(ue.N_COORD,!0),r=t.getUint32(ue.N_COLOR,!0),a=t.getUint32(ue.N_STOP,!0);let o=20;const l=new Float32Array(this.buffer,o,n*2);o+=n*8;const c=new Uint8Array(this.buffer,o,r*4);o+=r*4;const h=[];for(let p=0;p<a;++p){const g=t.getFloat32(o,!0);o+=4;const m=t.getUint32(o,!0);o+=4,h.push([g,`#${m.toString(16).padStart(6,"0")}`])}let u=null;if(s){u=[];for(let p=0;p<4;++p)u.push(t.getFloat32(o,!0)),o+=4}let f=null;if(i&&(f=new Uint8Array(this.buffer,o,3),o+=3),e===1)return["RadialAxial","axial",u,h,Array.from(l.slice(0,2)),Array.from(l.slice(2,4)),null,null];if(e===2)return["RadialAxial","radial",u,h,[l[0],l[1]],[l[3],l[4]],l[2],l[5]];if(e===3){const p=this.data[ue.SHADING_TYPE];let g=null;if(l.length>0){g=te.slice();for(let m=0,b=l.length;m<b;m+=2)T.pointBoundingBox(l[m],l[m+1],g)}return["Mesh",p,l,c,n,g,u,f]}throw new Error(`Unsupported pattern kind: ${e}`)}}class bl{#t;constructor(t){this.#t=t}get path(){return J.isFloat16ArraySupported?new Float16Array(this.#t):new Float32Array(this.#t)}}function yl(d){if(d instanceof URL)return d;if(typeof d=="string"){if(Pt){if(/^[a-z][a-z0-9\-+.]+:/i.test(d))return new URL(d);const e=process.getBuiltinModule("url");return new URL(e.pathToFileURL(d))}const t=URL.parse(d,window.location);if(t)return t}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}function vl(d){if(Pt&&typeof Buffer<"u"&&d instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(d instanceof Uint8Array&&d.byteLength===d.buffer.byteLength)return d;if(typeof d=="string")return $s(d);if(d instanceof ArrayBuffer||ArrayBuffer.isView(d)||typeof d=="object"&&!isNaN(d?.length))return new Uint8Array(d);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}function ws(d){if(typeof d!="string")return null;if(d.endsWith("/"))return d;throw new Error(`Invalid factory url: "${d}" must include trailing slash.`)}const Ii=d=>typeof d=="object"&&Number.isInteger(d?.num)&&d.num>=0&&Number.isInteger(d?.gen)&&d.gen>=0,Al=d=>typeof d=="object"&&typeof d?.name=="string",xl=Wo.bind(null,Ii,Al);class wl{#t=new Map;#e=Promise.resolve();postMessage(t,e){const s={data:structuredClone(t,e?{transfer:e}:null)};this.#e.then(()=>{for(const[i]of this.#t)i.call(this,s)})}addEventListener(t,e,s=null){let i=null;if(s?.signal instanceof AbortSignal){const{signal:n}=s;if(n.aborted){V("LoopbackPort - cannot use an `aborted` signal.");return}const r=()=>this.removeEventListener(t,e);i=()=>n.removeEventListener("abort",r),n.addEventListener("abort",r)}this.#t.set(e,i)}removeEventListener(t,e){this.#t.get(e)?.(),this.#t.delete(e)}terminate(){for(const[,t]of this.#t)t?.();this.#t.clear()}}const Ss={DATA:1,ERROR:2},mt={CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function Wn(){}function Ct(d){if(d instanceof re||d instanceof Ci||d instanceof Si||d instanceof Ls||d instanceof fi)return d;switch(d instanceof Error||typeof d=="object"&&d!==null||K('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),d.name){case"AbortException":return new re(d.message);case"InvalidPDFException":return new Ci(d.message);case"PasswordException":return new Si(d.message,d.code);case"ResponseException":return new Ls(d.message,d.status,d.missing);case"UnknownErrorException":return new fi(d.message,d.details)}return new fi(d.message,d.toString())}class Ke{#t=new AbortController;constructor(t,e,s){this.sourceName=t,this.targetName=e,this.comObj=s,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),s.addEventListener("message",this.#e.bind(this),{signal:this.#t.signal})}#e({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream){this.#i(t);return}if(t.callback){const s=t.callbackId,i=this.callbackCapabilities[s];if(!i)throw new Error(`Cannot resolve callback ${s}`);if(delete this.callbackCapabilities[s],t.callback===Ss.DATA)i.resolve(t.data);else if(t.callback===Ss.ERROR)i.reject(Ct(t.reason));else throw new Error("Unexpected callback case");return}const e=this.actionHandler[t.action];if(!e)throw new Error(`Unknown action from worker: ${t.action}`);if(t.callbackId){const s=this.sourceName,i=t.sourceName,n=this.comObj;Promise.try(e,t.data).then(function(r){n.postMessage({sourceName:s,targetName:i,callback:Ss.DATA,callbackId:t.callbackId,data:r})},function(r){n.postMessage({sourceName:s,targetName:i,callback:Ss.ERROR,callbackId:t.callbackId,reason:Ct(r)})});return}if(t.streamId){this.#s(t);return}e(t.data)}on(t,e){const s=this.actionHandler;if(s[t])throw new Error(`There is already an actionName called "${t}"`);s[t]=e}send(t,e,s){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,data:e},s)}sendWithPromise(t,e,s){const i=this.callbackId++,n=Promise.withResolvers();this.callbackCapabilities[i]=n;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:i,data:e},s)}catch(r){n.reject(r)}return n.promise}sendWithStream(t,e,s,i){const n=this.streamId++,r=this.sourceName,a=this.targetName,o=this.comObj;return new ReadableStream({start:l=>{const c=Promise.withResolvers();return this.streamControllers[n]={controller:l,startCall:c,pullCall:null,cancelCall:null,isClosed:!1},o.postMessage({sourceName:r,targetName:a,action:t,streamId:n,data:e,desiredSize:l.desiredSize},i),c.promise},pull:l=>{const c=Promise.withResolvers();return this.streamControllers[n].pullCall=c,o.postMessage({sourceName:r,targetName:a,stream:mt.PULL,streamId:n,desiredSize:l.desiredSize}),c.promise},cancel:l=>{ct(l instanceof Error,"cancel must have a valid reason");const c=Promise.withResolvers();return this.streamControllers[n].cancelCall=c,this.streamControllers[n].isClosed=!0,o.postMessage({sourceName:r,targetName:a,stream:mt.CANCEL,streamId:n,reason:Ct(l)}),c.promise}},s)}#s(t){const e=t.streamId,s=this.sourceName,i=t.sourceName,n=this.comObj,r=this,a=this.actionHandler[t.action],o={enqueue(l,c=1,h){if(this.isCancelled)return;const u=this.desiredSize;this.desiredSize-=c,u>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),n.postMessage({sourceName:s,targetName:i,stream:mt.ENQUEUE,streamId:e,chunk:l},h)},close(){this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:mt.CLOSE,streamId:e}),delete r.streamSinks[e])},error(l){ct(l instanceof Error,"error must have a valid reason"),!this.isCancelled&&(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:mt.ERROR,streamId:e,reason:Ct(l)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};o.sinkCapability.resolve(),o.ready=o.sinkCapability.promise,this.streamSinks[e]=o,Promise.try(a,t.data,o).then(function(){n.postMessage({sourceName:s,targetName:i,stream:mt.START_COMPLETE,streamId:e,success:!0})},function(l){n.postMessage({sourceName:s,targetName:i,stream:mt.START_COMPLETE,streamId:e,reason:Ct(l)})})}#i(t){const e=t.streamId,s=this.sourceName,i=t.sourceName,n=this.comObj,r=this.streamControllers[e],a=this.streamSinks[e];switch(t.stream){case mt.START_COMPLETE:t.success?r.startCall.resolve():r.startCall.reject(Ct(t.reason));break;case mt.PULL_COMPLETE:t.success?r.pullCall.resolve():r.pullCall.reject(Ct(t.reason));break;case mt.PULL:if(!a){n.postMessage({sourceName:s,targetName:i,stream:mt.PULL_COMPLETE,streamId:e,success:!0});break}a.desiredSize<=0&&t.desiredSize>0&&a.sinkCapability.resolve(),a.desiredSize=t.desiredSize,Promise.try(a.onPull||Wn).then(function(){n.postMessage({sourceName:s,targetName:i,stream:mt.PULL_COMPLETE,streamId:e,success:!0})},function(l){n.postMessage({sourceName:s,targetName:i,stream:mt.PULL_COMPLETE,streamId:e,reason:Ct(l)})});break;case mt.ENQUEUE:if(ct(r,"enqueue should have stream controller"),r.isClosed)break;r.controller.enqueue(t.chunk);break;case mt.CLOSE:if(ct(r,"close should have stream controller"),r.isClosed)break;r.isClosed=!0,r.controller.close(),this.#n(r,e);break;case mt.ERROR:ct(r,"error should have stream controller"),r.controller.error(Ct(t.reason)),this.#n(r,e);break;case mt.CANCEL_COMPLETE:t.success?r.cancelCall.resolve():r.cancelCall.reject(Ct(t.reason)),this.#n(r,e);break;case mt.CANCEL:if(!a)break;const o=Ct(t.reason);Promise.try(a.onCancel||Wn,o).then(function(){n.postMessage({sourceName:s,targetName:i,stream:mt.CANCEL_COMPLETE,streamId:e,success:!0})},function(l){n.postMessage({sourceName:s,targetName:i,stream:mt.CANCEL_COMPLETE,streamId:e,reason:Ct(l)})}),a.sinkCapability.reject(o),a.isCancelled=!0,delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}}async#n(t,e){await Promise.allSettled([t.startCall?.promise,t.pullCall?.promise,t.cancelCall?.promise]),delete this.streamControllers[e]}destroy(){this.#t?.abort(),this.#t=null}}class kr{#t=Object.freeze({cMapUrl:"CMap",standardFontDataUrl:"font",wasmUrl:"wasm"});constructor({cMapUrl:t=null,standardFontDataUrl:e=null,wasmUrl:s=null}){this.cMapUrl=t,this.standardFontDataUrl=e,this.wasmUrl=s}async fetch({kind:t,filename:e}){switch(t){case"cMapUrl":case"standardFontDataUrl":case"wasmUrl":break;default:K(`Not implemented: ${t}`)}const s=this[t];if(!s)throw new Error(`Ensure that the \`${t}\` API parameter is provided.`);const i=`${s}${e}`;return this._fetch(i,t).catch(n=>{throw new Error(`Unable to load ${this.#t[t]} data at: ${i}`)})}async _fetch(t,e){K("Abstract method `_fetch` called.")}}class Xn extends kr{async _fetch(t,e){const s=e==="cMapUrl"&&!t.endsWith(".bcmap")?"text":"bytes",i=await Ui(t,s);return i instanceof Uint8Array?i:$s(i)}}class Tr{#t=!1;constructor({enableHWA:t=!1}){this.#t=t}create(t,e){if(t<=0||e<=0)throw new Error("Invalid canvas size");const s=this._createCanvas(t,e);return{canvas:s,context:s.getContext("2d",{willReadFrequently:!this.#t})}}reset({canvas:t},e,s){if(!t)throw new Error("Canvas is not specified");if(e<=0||s<=0)throw new Error("Invalid canvas size");t.width=e,t.height=s}destroy(t){const{canvas:e}=t;if(!e)throw new Error("Canvas is not specified");e.width=e.height=0,t.canvas=null,t.context=null}_createCanvas(t,e){K("Abstract method `_createCanvas` called.")}}class Sl extends Tr{constructor({ownerDocument:t=globalThis.document,enableHWA:e=!1}){super({enableHWA:e}),this._document=t}_createCanvas(t,e){const s=this._document.createElement("canvas");return s.width=t,s.height=e,s}}class Mr{addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addKnockoutFilter(t=0){return"none"}addHighlightHCMFilter(t,e,s,i,n){return"none"}addSelectionHCMFilter(t,e){return"none"}addSelectionFilter(){return"none"}createSelectionStyle(t=null){return null}destroy(t=!1){}}class Cl extends Mr{#t;#e;#s;#i;#n;#a;#r=0;constructor({docId:t,ownerDocument:e=globalThis.document}){super(),this.#i=t,this.#n=e}get#o(){return this.#e||=new Map}get#h(){return this.#a||=new Map}get#l(){if(!this.#s){const t=this.#n.createElement("div"),{style:e}=t;e.colorScheme="only light",e.visibility="hidden",e.contain="strict",e.width=e.height=0,e.position="absolute",e.top=e.left=0,e.zIndex=-1;const s=this.#n.createElementNS(kt,"svg");s.setAttribute("width",0),s.setAttribute("height",0),this.#s=this.#n.createElementNS(kt,"defs"),t.append(s),s.append(this.#s),this.#n.body.append(t)}return this.#s}#u(t){if(t.length===1){const o=t[0],l=new Array(256);for(let h=0;h<256;h++)l[h]=o[h]/255;const c=l.join(",");return[c,c,c]}const[e,s,i]=t,n=new Array(256),r=new Array(256),a=new Array(256);for(let o=0;o<256;o++)n[o]=e[o]/255,r[o]=s[o]/255,a[o]=i[o]/255;return[n.join(","),r.join(","),a.join(",")]}#d(t){if(this.#t===void 0){this.#t="";const e=this.#n.URL;e!==this.#n.baseURI&&(Gs(e)?V('#createUrl: ignore "data:"-URL for performance reasons.'):this.#t=Ar(e,""))}return`url(${this.#t}#${t})`}addFilter(t){if(!t)return"none";let e=this.#o.get(t);if(e)return e;const[s,i,n]=this.#u(t),r=t.length===1?s:`${s}${i}${n}`;if(e=this.#o.get(r),e)return this.#o.set(t,e),e;const a=`g_${this.#i}_transfer_map_${this.#r++}`,o=this.#d(a);this.#o.set(t,o),this.#o.set(r,o);const l=this.#g(a);return this.#f(s,i,n,l),o}addHCMFilter(t,e){const s=`${t}-${e}`,i="base";let n=this.#h.get(i);if(n?.key===s||(n?(n.filter?.remove(),n.key=s,n.url="none",n.filter=null):(n={key:s,url:"none",filter:null},this.#h.set(i,n)),!t||!e))return n.url;const r=this.#v(t);t=T.makeHexColor(...r);const a=this.#v(e);if(e=T.makeHexColor(...a),this.#l.style.color="",t==="#000000"&&e==="#ffffff"||t===e)return n.url;const o=new Array(256);for(let f=0;f<=255;f++){const p=f/255;o[f]=p<=.03928?p/12.92:((p+.055)/1.055)**2.4}const l=o.join(","),c=`g_${this.#i}_hcm_filter`,h=n.filter=this.#g(c);this.#f(l,l,l,h),this.#m(h);const u=(f,p)=>{const g=r[f]/255,m=a[f]/255,b=new Array(p+1);for(let y=0;y<=p;y++)b[y]=g+y/p*(m-g);return b.join(",")};return this.#f(u(0,5),u(1,5),u(2,5),h),n.url=this.#d(c),n.url}addSelectionHCMFilter(t,e){return this.addHighlightHCMFilter("selection",t,e,"HighlightText","Highlight")}addSelectionFilter(){return this.addHighlightHCMFilter("selection_default","black","white","HighlightText","Highlight")}createSelectionStyle(t=null){const e=t?this.addSelectionHCMFilter(t.foreground,t.background):this.addSelectionFilter();return e==="none"||!J.platform.isFirefox?null:{"backdrop-filter":e,"background-color":"transparent"}}addAlphaFilter(t){let e=this.#o.get(t);if(e)return e;const[s]=this.#u([t]),i=`alpha_${s}`;if(e=this.#o.get(i),e)return this.#o.set(t,e),e;const n=`g_${this.#i}_alpha_map_${this.#r++}`,r=this.#d(n);this.#o.set(t,r),this.#o.set(i,r);const a=this.#g(n);return this.#y(s,a),r}addLuminosityFilter(t){let e=this.#o.get(t||"luminosity");if(e)return e;let s,i;if(t?([s]=this.#u([t]),i=`luminosity_${s}`):i="luminosity",e=this.#o.get(i),e)return this.#o.set(t,e),e;const n=`g_${this.#i}_luminosity_map_${this.#r++}`,r=this.#d(n);this.#o.set(t,r),this.#o.set(i,r);const a=this.#g(n);return this.#p(a),t&&this.#y(s,a),r}addKnockoutFilter(t=0){const e=t>0?Math.min(1/t,1e6):1e6,s=`knockout_${e}`,i=this.#o.get(s);if(i)return i;const n=`g_${this.#i}_knockout_filter_${this.#r++}`,r=this.#d(n);this.#o.set(s,r);const a=this.#g(n),o=this.#n.createElementNS(kt,"feComponentTransfer");a.append(o);const l=this.#n.createElementNS(kt,"feFuncA");return l.setAttribute("type","linear"),l.setAttribute("slope",`${e}`),l.setAttribute("intercept","0"),o.append(l),r}addHighlightHCMFilter(t,e,s,i,n){const r=`${e}-${s}-${i}-${n}`;let a=this.#h.get(t);if(a?.key===r||(a?(a.filter?.remove(),a.key=r,a.url="none",a.filter=null):(a={key:r,url:"none",filter:null},this.#h.set(t,a)),!e||!s))return a.url;const[o,l]=[e,s].map(this.#v.bind(this));let c=Math.round(.2126*o[0]+.7152*o[1]+.0722*o[2]),h=Math.round(.2126*l[0]+.7152*l[1]+.0722*l[2]),[u,f]=[i,n].map(this.#S.bind(this));h<c&&([c,h,u,f]=[h,c,f,u]),this.#l.style.color="";const p=(b,y,A)=>{const w=new Array(256),x=(h-c)/A,S=b/255,E=(y-b)/(255*A);let _=0;for(let k=0;k<=A;k++){const I=Math.round(c+k*x),P=S+k*E;for(let B=_;B<=I;B++)w[B]=P;_=I+1}for(let k=_;k<256;k++)w[k]=w[_-1];return w.join(",")},g=`g_${this.#i}_hcm_${t}_filter`,m=a.filter=this.#g(g);return this.#m(m),this.#f(p(u[0],f[0],5),p(u[1],f[1],5),p(u[2],f[2],5),m),a.url=this.#d(g),a.url}destroy(t=!1){t&&this.#a?.size||(this.#s?.parentNode.parentNode.remove(),this.#s=null,this.#e?.clear(),this.#e=null,this.#a?.clear(),this.#a=null,this.#r=0)}#p(t){const e=this.#n.createElementNS(kt,"feColorMatrix");e.setAttribute("type","matrix"),e.setAttribute("values","0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0"),t.append(e)}#m(t){const e=this.#n.createElementNS(kt,"feColorMatrix");e.setAttribute("type","matrix"),e.setAttribute("values","0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0"),t.append(e)}#g(t){const e=this.#n.createElementNS(kt,"filter");return e.setAttribute("color-interpolation-filters","sRGB"),e.setAttribute("id",t),this.#l.append(e),e}#c(t,e,s){const i=this.#n.createElementNS(kt,e);i.setAttribute("type","discrete"),i.setAttribute("tableValues",s),t.append(i)}#f(t,e,s,i){const n=this.#n.createElementNS(kt,"feComponentTransfer");i.append(n),this.#c(n,"feFuncR",t),this.#c(n,"feFuncG",e),this.#c(n,"feFuncB",s)}#y(t,e){const s=this.#n.createElementNS(kt,"feComponentTransfer");e.append(s),this.#c(s,"feFuncA",t)}#v(t){return this.#l.style.color=t,ds(getComputedStyle(this.#l).getPropertyValue("color"))}#b(t){return this.#l.style.color=t,hs(getComputedStyle(this.#l).getPropertyValue("color"))}#S(t){const[e,s,i,n]=this.#b(t);if(n===1)return[e,s,i];const[r,a,o]=this.#v("Canvas");return[mi(e,r,n),mi(s,a,n),mi(i,o,n)]}}function mi(d,t,e){return Math.round(e*d+(1-e)*t)}Pt&&V("Please use the `legacy` build in Node.js environments.");async function El(d){const e=await process.getBuiltinModule("fs/promises").readFile(d);return new Uint8Array(e)}class _l extends Mr{}class kl extends Tr{_createCanvas(t,e){return process.getBuiltinModule("module").createRequire(import.meta.url)("@napi-rs/canvas").createCanvas(t,e)}}class Tl extends kr{async _fetch(t,e){return El(t)}}function Pr({src:d,srcPos:t=0,dest:e,width:s,height:i,nonBlackColor:n=4294967295,inverseDecode:r=!1}){const a=J.isLittleEndian?4278190080:255,[o,l]=r?[n,a]:[a,n],c=s>>3,h=s&7,u=o^l,f=d.length;e=new Uint32Array(e.buffer);let p=0;for(let g=0;g<i;++g){for(const b=t+c;t<b;++t,p+=8){const y=d[t];e[p]=o^-(y>>7&1)&u,e[p+1]=o^-(y>>6&1)&u,e[p+2]=o^-(y>>5&1)&u,e[p+3]=o^-(y>>4&1)&u,e[p+4]=o^-(y>>3&1)&u,e[p+5]=o^-(y>>2&1)&u,e[p+6]=o^-(y>>1&1)&u,e[p+7]=o^-(y&1)&u}if(h===0)continue;const m=t<f?d[t++]:255;for(let b=0;b<h;++b,++p)e[p]=o^-(m>>7-b&1)&u}return{srcPos:t,destPos:p}}function Ml({src:d,srcPos:t=0,dest:e,destPos:s=0,width:i,height:n}){let r=0;const a=i*n*3,o=a>>2,l=new Uint32Array(d.buffer,t,o),c=J.isLittleEndian?4278190080:255;if(J.isLittleEndian){for(;r<o-2;r+=3,s+=4){const h=l[r],u=l[r+1],f=l[r+2];e[s]=h|c,e[s+1]=h>>>24|u<<8|c,e[s+2]=u>>>16|f<<16|c,e[s+3]=f>>>8|c}for(let h=r*4,u=t+a;h<u;h+=3)e[s++]=d[h]|d[h+1]<<8|d[h+2]<<16|c}else{for(;r<o-2;r+=3,s+=4){const h=l[r],u=l[r+1],f=l[r+2];e[s]=h|c,e[s+1]=h<<24|u>>>8|c,e[s+2]=u<<16|f>>>16|c,e[s+3]=f<<8|c}for(let h=r*4,u=t+a;h<u;h+=3)e[s++]=d[h]<<24|d[h+1]<<16|d[h+2]<<8|c}return{srcPos:t+a,destPos:s}}const Pl=`
|
|
3
|
+
struct Uniforms {
|
|
4
|
+
offsetX : f32,
|
|
5
|
+
offsetY : f32,
|
|
6
|
+
scaleX : f32,
|
|
7
|
+
scaleY : f32,
|
|
8
|
+
paddedWidth : f32,
|
|
9
|
+
paddedHeight : f32,
|
|
10
|
+
borderSize : f32,
|
|
11
|
+
_pad : f32,
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
@group(0) @binding(0) var<uniform> u : Uniforms;
|
|
15
|
+
|
|
16
|
+
struct VertexInput {
|
|
17
|
+
@location(0) position : vec2<f32>,
|
|
18
|
+
@location(1) color : vec4<f32>,
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
struct VertexOutput {
|
|
22
|
+
@builtin(position) position : vec4<f32>,
|
|
23
|
+
@location(0) color : vec3<f32>,
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
@vertex
|
|
27
|
+
fn vs_main(in : VertexInput) -> VertexOutput {
|
|
28
|
+
var out : VertexOutput;
|
|
29
|
+
let cx = (in.position.x + u.offsetX) * u.scaleX;
|
|
30
|
+
let cy = (in.position.y + u.offsetY) * u.scaleY;
|
|
31
|
+
out.position = vec4<f32>(
|
|
32
|
+
((cx + u.borderSize) / u.paddedWidth) * 2.0 - 1.0,
|
|
33
|
+
1.0 - ((cy + u.borderSize) / u.paddedHeight) * 2.0,
|
|
34
|
+
0.0,
|
|
35
|
+
1.0
|
|
36
|
+
);
|
|
37
|
+
out.color = in.color.rgb;
|
|
38
|
+
return out;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
@fragment
|
|
42
|
+
fn fs_main(in : VertexOutput) -> @location(0) vec4<f32> {
|
|
43
|
+
return vec4<f32>(in.color, 1.0);
|
|
44
|
+
}
|
|
45
|
+
`;class Il{#t=null;#e=null;#s=null;#i=null;async#n(){if(!globalThis.navigator?.gpu)return!1;try{const t=await navigator.gpu.requestAdapter();return t?(this.#i=navigator.gpu.getPreferredCanvasFormat(),this.#e=await t.requestDevice(),!0):!1}catch{return!1}}init(){return this.#t||=this.#n()}get isReady(){return this.#e!==null}loadMeshShader(){if(!this.#e||this.#s)return;const t=this.#e.createShaderModule({code:Pl});this.#s=this.#e.createRenderPipeline({layout:"auto",vertex:{module:t,entryPoint:"vs_main",buffers:[{arrayStride:8,attributes:[{shaderLocation:0,offset:0,format:"float32x2"}]},{arrayStride:4,attributes:[{shaderLocation:1,offset:0,format:"unorm8x4"}]}]},fragment:{module:t,entryPoint:"fs_main",targets:[{format:this.#i}]},primitive:{topology:"triangle-list"}})}draw(t,e,s,i,n,r,a,o){this.loadMeshShader();const l=this.#e,{offsetX:c,offsetY:h,scaleX:u,scaleY:f}=i,p=l.createBuffer({size:Math.max(t.byteLength,4),usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});t.byteLength>0&&l.queue.writeBuffer(p,0,t);const g=l.createBuffer({size:Math.max(e.byteLength,4),usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});e.byteLength>0&&l.queue.writeBuffer(g,0,e);const m=l.createBuffer({size:32,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});l.queue.writeBuffer(m,0,new Float32Array([c,h,u,f,r,a,o,0]));const b=l.createBindGroup({layout:this.#s.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:m}}]}),y=new OffscreenCanvas(r,a),A=y.getContext("webgpu");A.configure({device:l,format:this.#i,alphaMode:n?"opaque":"premultiplied"});const w=n?{r:n[0]/255,g:n[1]/255,b:n[2]/255,a:1}:{r:0,g:0,b:0,a:0},x=l.createCommandEncoder(),S=x.beginRenderPass({colorAttachments:[{view:A.getCurrentTexture().createView(),clearValue:w,loadOp:"clear",storeOp:"store"}]});return s>0&&(S.setPipeline(this.#s),S.setBindGroup(0,b),S.setVertexBuffer(0,p),S.setVertexBuffer(1,g),S.draw(s)),S.end(),l.queue.submit([x.finish()]),p.destroy(),g.destroy(),m.destroy(),y.transferToImageBitmap()}}const Ws=new Il;function Dl(){return Ws.init()}function Nl(){return Ws.isReady}function Fl(){Ws.loadMeshShader()}function Ll(d,t,e,s,i,n,r,a){return Ws.draw(d,t,e,s,i,n,r,a)}const xt={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};function Is(d,t){if(!t)return;const e=t[2]-t[0],s=t[3]-t[1],i=new Path2D;i.rect(t[0],t[1],e,s),d.clip(i)}class Xi{isModifyingCurrentTransform(){return!1}getPattern(){K("Abstract method `getPattern` called.")}}class Rl extends Xi{constructor(t){super(),this._type=t[1],this._bbox=t[2],this._colorStops=t[3],this._p0=t[4],this._p1=t[5],this._r0=t[6],this._r1=t[7],this.matrix=null}isOriginBased(){return this._p0[0]===0&&this._p0[1]===0&&(!this.isRadial()||this._p1[0]===0&&this._p1[1]===0)}isRadial(){return this._type==="radial"}areConic(){if(!this.isRadial())return!1;const t=Math.hypot(this._p0[0]-this._p1[0],this._p0[1]-this._p1[1]);return t+this._r1>this._r0&&t+this._r0>this._r1}_createGradient(t,e=null){let s,i=this._p0,n=this._p1;if(e&&(i=i.slice(),n=n.slice(),T.applyTransform(i,e),T.applyTransform(n,e)),this._type==="axial")s=t.createLinearGradient(i[0],i[1],n[0],n[1]);else if(this._type==="radial"){let r=this._r0,a=this._r1;if(e){const o=new Float32Array(2);T.singularValueDecompose2dScale(e,o),r*=o[0],a*=o[0]}s=t.createRadialGradient(i[0],i[1],r,n[0],n[1],a)}for(const r of this._colorStops)s.addColorStop(r[0],r[1]);return s}_createReversedGradient(t,e=null){let s=this._p1,i=this._p0;e&&(s=s.slice(),i=i.slice(),T.applyTransform(s,e),T.applyTransform(i,e));let n=this._r1,r=this._r0;if(e){const l=new Float32Array(2);T.singularValueDecompose2dScale(e,l),n*=l[0],r*=l[0]}const a=t.createRadialGradient(s[0],s[1],n,i[0],i[1],r),o=this._colorStops.map(([l,c])=>[1-l,c]).reverse();for(const[l,c]of o)a.addColorStop(l,c);return a}getPattern(t,e,s,i){let n;if(i===xt.STROKE||i===xt.FILL){if(this.isOriginBased()){let u=T.transform(s,e.baseTransform);this.matrix&&(u=T.transform(u,this.matrix));const f=.001,p=Math.hypot(u[0],u[1]),g=Math.hypot(u[2],u[3]),m=(u[0]*u[2]+u[1]*u[3])/(p*g);if(Math.abs(m)<f)if(this.isRadial()){if(Math.abs(p-g)<f)return this._createGradient(t,u)}else return this._createGradient(t,u)}const r=e.current.getClippedPathBoundingBox(i,et(t))||[0,0,0,0],a=Math.ceil(r[2]-r[0])||1,o=Math.ceil(r[3]-r[1])||1,l=e.canvasFactory.create(a,o),c=l.context;c.clearRect(0,0,c.canvas.width,c.canvas.height),c.beginPath(),c.rect(0,0,c.canvas.width,c.canvas.height),c.translate(-r[0],-r[1]),s=T.transform(s,[1,0,0,1,r[0],r[1]]),c.transform(...e.baseTransform),this.matrix&&c.transform(...this.matrix),Is(c,this._bbox),this.areConic()&&(c.fillStyle=this._createReversedGradient(c),c.fill()),c.fillStyle=this._createGradient(c),c.fill(),n=t.createPattern(l.canvas,"no-repeat"),e.canvasFactory.destroy(l);const h=new DOMMatrix(s);n.setTransform(h)}else this.areConic()&&(t.save(),Is(t,this._bbox),t.fillStyle=this._createReversedGradient(t),t.fillRect(-1e10,-1e10,2e10,2e10),t.restore()),Is(t,this._bbox),n=this._createGradient(t);return n}}function Ol(d,t,e,s,i,n,r,a){const o=t.coords,l=t.colors,c=d.data,h=d.width*4;let u;o[e*2+1]>o[s*2+1]&&(u=e,e=s,s=u,u=n,n=r,r=u),o[s*2+1]>o[i*2+1]&&(u=s,s=i,i=u,u=r,r=a,a=u),o[e*2+1]>o[s*2+1]&&(u=e,e=s,s=u,u=n,n=r,r=u);const f=(o[e*2]+t.offsetX)*t.scaleX,p=(o[e*2+1]+t.offsetY)*t.scaleY,g=(o[s*2]+t.offsetX)*t.scaleX,m=(o[s*2+1]+t.offsetY)*t.scaleY,b=(o[i*2]+t.offsetX)*t.scaleX,y=(o[i*2+1]+t.offsetY)*t.scaleY;if(p>=y)return;const A=l[n*4],w=l[n*4+1],x=l[n*4+2],S=l[r*4],E=l[r*4+1],_=l[r*4+2],k=l[a*4],I=l[a*4+1],P=l[a*4+2],B=Math.round(p),W=Math.round(y);let Y,Z,L,F,rt,ht,vt,Ot;for(let M=B;M<=W;M++){if(M<m){const tt=M<p?0:(p-M)/(p-m);Y=f-(f-g)*tt,Z=A-(A-S)*tt,L=w-(w-E)*tt,F=x-(x-_)*tt}else{let tt;M>y?tt=1:m===y?tt=0:tt=(m-M)/(m-y),Y=g-(g-b)*tt,Z=S-(S-k)*tt,L=E-(E-I)*tt,F=_-(_-P)*tt}let j;M<p?j=0:M>y?j=1:j=(p-M)/(p-y),rt=f-(f-b)*j,ht=A-(A-k)*j,vt=w-(w-I)*j,Ot=x-(x-P)*j;const dt=Math.round(Math.min(Y,rt)),Bt=Math.round(Math.max(Y,rt));let _t=h*M+dt*4;for(let tt=dt;tt<=Bt;tt++)j=(Y-tt)/(Y-rt),j<0?j=0:j>1&&(j=1),c[_t++]=Z-(Z-ht)*j|0,c[_t++]=L-(L-vt)*j|0,c[_t++]=F-(F-Ot)*j|0,c[_t++]=255}}class Bl extends Xi{constructor(t){super(),this._posData=t[2],this._colData=t[3],this._vertexCount=t[4],this._bounds=t[5],this._bbox=t[6],this._background=t[7],this.matrix=null,Fl()}_createMeshCanvas(t,e,s){const a=Math.floor(this._bounds[0]),o=Math.floor(this._bounds[1]),l=Math.ceil(this._bounds[2])-a,c=Math.ceil(this._bounds[3])-o,h=Math.min(Math.ceil(Math.abs(l*t[0]*1.1)),3e3)||1,u=Math.min(Math.ceil(Math.abs(c*t[1]*1.1)),3e3)||1,f=l?l/h:1,p=c?c/u:1,g={coords:this._posData,colors:this._colData,offsetX:-a,offsetY:-o,scaleX:1/f,scaleY:1/p},m=h+4,b=u+4,y=s.create(m,b);if(Nl()&&this._vertexCount>48)y.context.drawImage(Ll(this._posData,this._colData,this._vertexCount,g,e,m,b,2),0,0);else{const A=y.context.createImageData(h,u);if(e){const w=A.data;for(let x=0,S=w.length;x<S;x+=4)w[x]=e[0],w[x+1]=e[1],w[x+2]=e[2],w[x+3]=255}for(let w=0,x=this._vertexCount;w<x;w+=3)Ol(A,g,w,w+1,w+2,w,w+1,w+2);y.context.putImageData(A,2,2)}return{canvas:y.canvas,offsetX:a-2*f,offsetY:o-2*p,scaleX:f,scaleY:p}}isModifyingCurrentTransform(){return!0}getPattern(t,e,s,i){Is(t,this._bbox);const n=new Float32Array(2);if(i===xt.SHADING)T.singularValueDecompose2dScale(et(t),n);else if(this.matrix){T.singularValueDecompose2dScale(this.matrix,n);const[o,l]=n;T.singularValueDecompose2dScale(e.baseTransform,n),n[0]*=o,n[1]*=l}else T.singularValueDecompose2dScale(e.baseTransform,n);const r=this._createMeshCanvas(n,i===xt.SHADING?null:this._background,e.canvasFactory);i!==xt.SHADING&&(t.setTransform(...e.baseTransform),this.matrix&&t.transform(...this.matrix)),t.translate(r.offsetX,r.offsetY),t.scale(r.scaleX,r.scaleY);const a=t.createPattern(r.canvas,"no-repeat");return e.canvasFactory.destroy(r),a}}class jl extends Xi{getPattern(){return"hotpink"}}function Hl(d){switch(d[0]){case"RadialAxial":return new Rl(d);case"Mesh":return new Bl(d);case"Dummy":return new jl}throw new Error(`Unknown IR type: ${d[0]}`)}const Yn={COLORED:1,UNCOLORED:2};class Ze{static MAX_PATTERN_SIZE=3e3;constructor(t,e,s,i){this.color=t[1],this.operatorList=t[2],this.matrix=t[3],this.bbox=t[4],this.xstep=t[5],this.ystep=t[6],this.paintType=t[7],this.tilingType=t[8],this.needsIsolation=t[9]??!0,this.ctx=e,this.canvasGraphicsFactory=s,this.baseTransform=i,this.patternBaseMatrix=this.matrix?T.transform(i,this.matrix):i}canSkipPatternCanvas([t,e,s,i]){const[n,r,a,o]=this.bbox,l=Math.abs(this.xstep),c=Math.abs(this.ystep);if(t>l+1e-6||e>c+1e-6)return null;const h=Math.floor((s-a)/l)+1,u=Math.ceil((s+t-n)/l)-1,f=Math.floor((i-o)/c)+1,p=Math.ceil((i+e-r)/c)-1;return u<=h&&p<=f?[h,f]:null}updatePatternDims(t,e){const s=T.inverseTransform(this.patternBaseMatrix),i=[t[0],t[1]],n=[t[2],t[3]];T.applyTransform(i,s),T.applyTransform(n,s),e[0]=Math.abs(n[0]-i[0]),e[1]=Math.abs(n[1]-i[1]),e[2]=Math.min(i[0],n[0]),e[3]=Math.min(i[1],n[1])}_renderTileCanvas(t,e,s,i){const[n,r,a,o]=this.bbox,l=t.canvasFactory.create(s.size,i.size),c=l.context,h=this.canvasGraphicsFactory.createCanvasGraphics(c,e);return h.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(h,this.paintType,this.color),c.translate(-s.scale*n,-i.scale*r),h.transform(0,s.scale,0,0,i.scale,0,0),c.save(),h.dependencyTracker?.save(),this.clipBbox(h,n,r,a,o),h.baseTransform=et(h.ctx),h.executeOperatorList(this.operatorList),h.endDrawing(),h.dependencyTracker?.restore(),c.restore(),l}_getCombinedScales(){const t=new Float32Array(2);T.singularValueDecompose2dScale(this.matrix,t);const[e,s]=t;return T.singularValueDecompose2dScale(this.baseTransform,t),[e*t[0],s*t[1]]}drawPattern(t,e,s=!1,[i,n],r){const[a,o,l,c]=this.bbox,h=t.dependencyTracker;if(h&&(t.dependencyTracker=new is(h,r)),t.save(),s?t.ctx.clip(e,"evenodd"):t.ctx.clip(e),t.ctx.setTransform(...this.patternBaseMatrix),t.ctx.translate(i*this.xstep,n*this.ystep),this.needsIsolation||t.ctx.globalAlpha!==1||t.ctx.globalCompositeOperation!=="source-over"||t.inSMaskMode){const u=l-a,f=c-o,[p,g]=this._getCombinedScales(),m=this.getSizeAndScale(u,this.ctx.canvas.width,p),b=this.getSizeAndScale(f,this.ctx.canvas.height,g),y=this._renderTileCanvas(t,r,m,b);t.ctx.drawImage(y.canvas,a,o,u,f),t.canvasFactory.destroy(y)}else this.setFillAndStrokeStyleToContext(t,this.paintType,this.color),this.clipBbox(t,a,o,l,c),t.baseTransformStack.push(t.baseTransform),t.baseTransform=et(t.ctx),t.executeOperatorList(this.operatorList),t.baseTransform=t.baseTransformStack.pop();t.restore(),h&&(t.dependencyTracker=h)}createPatternCanvas(t,e){const[s,i,n,r]=this.bbox,a=n-s,o=r-i;let{xstep:l,ystep:c}=this;l=Math.abs(l),c=Math.abs(c),zs("TilingType: "+this.tilingType);const[h,u]=this._getCombinedScales();let f=a,p=o,g=!1,m=!1;Math.ceil(l*h)>=Math.ceil(a*h)?f=l:g=!0,Math.ceil(c*u)>=Math.ceil(o*u)?p=c:m=!0;const b=this.getSizeAndScale(f,this.ctx.canvas.width,h),y=this.getSizeAndScale(p,this.ctx.canvas.height,u),A=this._renderTileCanvas(t,e,b,y);if(g||m){const w=A.canvas;g&&(f=l),m&&(p=c);const x=this.getSizeAndScale(f,this.ctx.canvas.width,h),S=this.getSizeAndScale(p,this.ctx.canvas.height,u),E=x.size,_=S.size,k=t.canvasFactory.create(E,_),I=k.context,P=g?Math.floor(a/l):0,B=m?Math.floor(o/c):0;for(let W=0;W<=P;W++)for(let Y=0;Y<=B;Y++)I.drawImage(w,E*W,_*Y,E,_,0,0,E,_);return t.canvasFactory.destroy(A),{canvas:k.canvas,canvasEntry:k,scaleX:x.scale,scaleY:S.scale,offsetX:s,offsetY:i}}return{canvas:A.canvas,canvasEntry:A,scaleX:b.scale,scaleY:y.scale,offsetX:s,offsetY:i}}getSizeAndScale(t,e,s){const i=Math.max(Ze.MAX_PATTERN_SIZE,e);let n=Math.ceil(t*s);return n>=i?n=i:s=n/t,{scale:s,size:n}}clipBbox(t,e,s,i,n){const r=i-e,a=n-s,o=new Path2D;o.rect(e,s,r,a),T.axialAlignedBoundingBox([e,s,i,n],et(t.ctx),t.current.minMax),t.ctx.clip(o),t.current.updateClipFromPath()}setFillAndStrokeStyleToContext(t,e,s){const i=t.ctx,n=t.current;switch(n.patternFill=n.patternStroke=!1,e){case Yn.COLORED:const{fillStyle:r,strokeStyle:a}=this.ctx;i.fillStyle=n.fillColor=r,i.strokeStyle=n.strokeColor=a;break;case Yn.UNCOLORED:i.fillStyle=i.strokeStyle=s,n.fillColor=n.strokeColor=s;break;default:throw new zo(`Unsupported paint type: ${e}`)}}isModifyingCurrentTransform(){return!1}getPattern(t,e,s,i,n){const r=i!==xt.SHADING?T.transform(s,this.patternBaseMatrix):s,a=this.createPatternCanvas(e,n);let o=new DOMMatrix(r);o=o.translate(a.offsetX,a.offsetY),o=o.scale(1/a.scaleX,1/a.scaleY);const l=t.createPattern(a.canvas,"repeat");return e.canvasFactory.destroy(a.canvasEntry),l.setTransform(o),l}}const Ul=16,zl=100,$l=15,Kn=10,Et=16,bi=new DOMMatrix,Dt=new Float32Array(2);function qn(d,t){if(d._removeMirroring)throw new Error("Context is already forwarding operations.");const e=new Map;for(const s of["save","restore","rotate","scale","translate","transform","setTransform","resetTransform","clip","moveTo","lineTo","bezierCurveTo","quadraticCurveTo","arc","arcTo","ellipse","rect","roundRect","closePath","beginPath"]){const i=d[s];typeof i!="function"||typeof t[s]!="function"||(e.set(s,i),d[s]=function(...n){return t[s](...n),i.apply(this,n)})}d._removeMirroring=()=>{for(const[s,i]of e)d[s]=i;delete d._removeMirroring}}function Cs(d,t,e,s,i,n,r,a,o,l){const[c,h,u,f,p,g]=et(d);if(h===0&&u===0){const y=r*c+p,A=Math.round(y),w=a*f+g,x=Math.round(w),S=(r+o)*c+p,E=Math.abs(Math.round(S)-A)||1,_=(a+l)*f+g,k=Math.abs(Math.round(_)-x)||1;return d.setTransform(Math.sign(c),0,0,Math.sign(f),A,x),d.drawImage(t,e,s,i,n,0,0,E,k),d.setTransform(c,h,u,f,p,g),[E,k]}if(c===0&&f===0){const y=a*u+p,A=Math.round(y),w=r*h+g,x=Math.round(w),S=(a+l)*u+p,E=Math.abs(Math.round(S)-A)||1,_=(r+o)*h+g,k=Math.abs(Math.round(_)-x)||1;return d.setTransform(0,Math.sign(h),Math.sign(u),0,A,x),d.drawImage(t,e,s,i,n,0,0,k,E),d.setTransform(c,h,u,f,p,g),[k,E]}d.drawImage(t,e,s,i,n,r,a,o,l);const m=Math.hypot(c,h),b=Math.hypot(u,f);return[m*o,b*l]}class Qn{alphaIsShape=!1;fontSize=0;fontSizeScale=1;textMatrix=null;textMatrixScale=1;fontMatrix=xi;leading=0;x=0;y=0;lineX=0;lineY=0;charSpacing=0;wordSpacing=0;textHScale=1;textRenderingMode=bt.FILL;textRise=0;fillColor="#000000";strokeColor="#000000";tilingPatternDims=null;patternFill=!1;patternStroke=!1;fillAlpha=1;strokeAlpha=1;lineWidth=1;activeSMask=null;transferMaps="none";minMax=me.slice();constructor(t,e){this.clipBox=new Float32Array([0,0,t,e])}clone(){const t=Object.create(this);return t.clipBox=this.clipBox.slice(),t.minMax=this.minMax.slice(),t.tilingPatternDims=this.tilingPatternDims?.slice(),t}getPathBoundingBox(t=xt.FILL,e=null){const s=this.minMax.slice();if(t===xt.STROKE){e||K("Stroke bounding box must include transform."),T.singularValueDecompose2dScale(e,Dt);const i=Dt[0]*this.lineWidth/2,n=Dt[1]*this.lineWidth/2;s[0]-=i,s[1]-=n,s[2]+=i,s[3]+=n}return s}updateClipFromPath(){const t=T.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(t||[0,0,0,0])}isEmptyClip(){return this.minMax[0]===1/0}startNewPathAndClipBox(t){this.clipBox.set(t,0),this.minMax.set(me,0)}getClippedPathBoundingBox(t=xt.FILL,e=null){return T.intersect(this.clipBox,this.getPathBoundingBox(t,e))}}function Jn(d,t){const{width:e,height:s,kind:i}=t,n=s%Et,r=(s-n)/Et,a=n===0?r:r+1,o=d.createImageData(e,Et);let l=0;const c=t.data,h=o.data;let u;if(i===Ps.GRAYSCALE_1BPP)for(u=0;u<a;u++)({srcPos:l}=Pr({src:c,srcPos:l,dest:h,width:e,height:u<r?Et:n})),d.putImageData(o,0,u*Et);else if(i===Ps.RGBA_32BPP){let f=0,p=e*Et*4;for(u=0;u<r;u++)h.set(c.subarray(l,l+p)),l+=p,d.putImageData(o,0,f),f+=Et;u<a&&(p=e*n*4,h.set(c.subarray(l,l+p)),d.putImageData(o,0,f))}else if(i===Ps.RGB_24BPP)for(u=0;u<a;u++)({srcPos:l}=Ml({src:c,srcPos:l,dest:new Uint32Array(h.buffer),width:e,height:u<r?Et:n})),d.putImageData(o,0,u*Et);else throw new Error(`bad image kind: ${i}`)}function Zn(d,t){if(t.bitmap){d.drawImage(t.bitmap,0,0);return}const{width:e,height:s}=t,i=s%Et,n=(s-i)/Et,r=i===0?n:n+1,a=d.createImageData(e,Et);let o=0;const l=t.data,c=a.data;for(let h=0;h<r;h++)({srcPos:o}=Pr({src:l,srcPos:o,dest:c,width:e,height:h<n?Et:i,nonBlackColor:0})),d.putImageData(a,0,h*Et)}function fe(d,t){const e=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font","filter"];for(const s of e)d[s]!==void 0&&(t[s]=d[s]);d.setLineDash!==void 0&&(t.setLineDash(d.getLineDash()),t.lineDashOffset=d.lineDashOffset)}function Es(d){d.strokeStyle=d.fillStyle="#000000",d.fillRule="nonzero",d.globalAlpha=1,d.lineWidth=1,d.lineCap="butt",d.lineJoin="miter",d.miterLimit=10,d.globalCompositeOperation="source-over",d.font="10px sans-serif",d.setLineDash!==void 0&&(d.setLineDash([]),d.lineDashOffset=0);const{filter:t}=d;t!=="none"&&t!==""&&(d.filter="none")}function tr(d,t){if(t)return!0;T.singularValueDecompose2dScale(d,Dt);const e=Math.fround(Kt.pixelRatio*He.PDF_TO_CSS_UNITS);return Dt[0]<=e&&Dt[1]<=e}const Gl=["butt","round","square"],Vl=["miter","round","bevel"],Wl={},er={};class Oe{#t=0;#e=0;#s=null;#i=null;#n=null;#a=null;#r=1;#o;#h=null;#l=[];constructor(t,e,s,i,n,{optionalContentConfig:r,markedContentStack:a=null},o,l,c,h){this.ctx=t,this.current=new Qn(this.ctx.canvas.width,this.ctx.canvas.height),this.stateStack=[],this.pendingClip=null,this.pendingEOFill=!1,this.commonObjs=e,this.objs=s,this.canvasFactory=i,this.filterFactory=n,this.groupStack=[],this.baseTransform=null,this.baseTransformStack=[],this.groupLevel=0,this.smaskStack=[],this.tempSMask=null,this.smaskGroupCanvases=[],this.smaskPreparedEntry=null,this.smaskPreparedFor=null,this.smaskPreparedOffsetX=0,this.smaskPreparedOffsetY=0,this.smaskPreparedOOBAlpha=null,this.suspendedCtx=null,this.contentVisible=!0,this.markedContentStack=a||[],this.optionalContentConfig=r,this.cachedPatterns=new Map,this.annotationCanvasMap=o,this.viewportScale=1,this.outputScaleX=1,this.outputScaleY=1,this.pageColors=l,this._cachedScaleForStroking=[-1,0],this._cachedGetSinglePixelWidth=null,this._cachedBitmapsMap=new Map,this.dependencyTracker=c??null,this.imagesTracker=h??null}getObject(t,e,s=null){return typeof e=="string"?(this.dependencyTracker?.recordNamedDependency(t,e),e.startsWith("g_")?this.commonObjs.get(e):this.objs.get(e)):s}beginDrawing({transform:t,viewport:e,transparency:s=!1,background:i=null}){const n=this.ctx.canvas.width,r=this.ctx.canvas.height,a=this.ctx.fillStyle;if(this.ctx.fillStyle=i||"#ffffff",this.ctx.fillRect(0,0,n,r),this.ctx.fillStyle=a,s){const o=this.transparentCanvasEntry=this.canvasFactory.create(n,r);this.compositeCtx=this.ctx,{canvas:this.transparentCanvas,context:this.ctx}=o,this.ctx.save(),this.ctx.transform(...et(this.compositeCtx))}this.ctx.save(),Es(this.ctx),t&&(this.ctx.transform(...t),this.outputScaleX=t[0],this.outputScaleY=t[3]),this.ctx.transform(...e.transform),this.viewportScale=e.scale,this.baseTransform=et(this.ctx)}executeOperatorList(t,e,s,i,n){const r=t.argsArray,a=t.fnArray;let o=e||0;const l=r.length;if(l===o)return o;const c=l-o>Kn&&typeof s=="function",h=c?Date.now()+$l:0;let u=0;const f=this.commonObjs,p=this.objs;let g,m;for(;;){if(i!==void 0){if(o===i.nextBreakPoint)return i.breakIt(o,s),o;if(i.shouldSkip(o)){if(++o===l)return o;continue}}if(!n||n(o))if(g=a[o],m=r[o]??null,g!==Xt.dependency)m===null?this[g](o):this[g](o,...m);else for(const b of m){this.dependencyTracker?.recordNamedData(b,o);const y=b.startsWith("g_")?f:p;if(!y.has(b))return y.get(b,s),o}if(o++,o===l)return o;if(c&&++u>Kn){if(Date.now()>h)return s(),o;u=0}}}#u(){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.canvasFactory.destroy(this.transparentCanvasEntry),this.transparentCanvas=null,this.transparentCanvasEntry=null)}endDrawing(){this.#u();for(const t of this.smaskGroupCanvases)this.canvasFactory.destroy(t);this.smaskGroupCanvases.length=0,this._clearPreparedSMask(),this.tempSMask=null,this.smaskStack.length=0;for(const t of this.#l)this.#b(t);this.#l.length=0,this.#s=null,this.#i=null,this.#n=null,this.#a=null,this.#r=1,this.#h=null,this.#e=0,this.#t=0,this.cachedPatterns.clear();for(const t of this._cachedBitmapsMap.values()){for(const e of t.values())typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement&&(e.width=e.height=0);t.clear()}this._cachedBitmapsMap.clear(),this.#d()}#d(){if(this.pageColors){const t=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if(t!=="none"){const e=this.ctx.filter;this.ctx.filter=t,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=e}}}_scaleImage(t,e){const s=t.width??t.displayWidth,i=t.height??t.displayHeight,n=Math.max(Math.hypot(e[0],e[1]),1),r=Math.max(Math.hypot(e[2],e[3]),1),a=[];let o=n,l=r,c=s,h=i;for(;o>2&&c>1||l>2&&h>1;){let b=c,y=h;o>2&&c>1&&(b=Math.ceil(c/2),o/=c/b),l>2&&h>1&&(y=Math.ceil(h/2),l/=h/y),a.push({newWidth:b,newHeight:y}),c=b,h=y}if(a.length===0)return{img:t,paintWidth:s,paintHeight:i,tmpCanvas:null};if(a.length===1){const{newWidth:b,newHeight:y}=a[0],A=this.canvasFactory.create(b,y);return A.context.drawImage(t,0,0,s,i,0,0,b,y),{img:A.canvas,paintWidth:b,paintHeight:y,tmpCanvas:A}}let u=this.canvasFactory.create(1,1),f=this.canvasFactory.create(1,1),p=s,g=i,m=t;for(const{newWidth:b,newHeight:y}of a)this.canvasFactory.reset(f,b,y),f.context.drawImage(m,0,0,p,g,0,0,b,y),[u,f]=[f,u],m=u.canvas,p=b,g=y;return this.canvasFactory.destroy(f),{img:u.canvas,paintWidth:p,paintHeight:g,tmpCanvas:u}}_createMaskCanvas(t,e){const s=this.ctx,{width:i,height:n}=e,r=this.current.fillColor,a=this.current.patternFill,o=et(s);let l,c,h,u;if((e.bitmap||e.data)&&e.count>1){const P=e.bitmap||e.data.buffer;c=JSON.stringify(a?o:[o.slice(0,4),r]),l=this._cachedBitmapsMap.getOrInsertComputed(P,Hi);const B=l.get(c);if(B&&!a){const W=Math.round(Math.min(o[0],o[2])+o[4]),Y=Math.round(Math.min(o[1],o[3])+o[5]);return this.dependencyTracker?.recordDependencies(t,Ft.transformAndFill),{canvas:B,offsetX:W,offsetY:Y}}h=B}h||(u=this.canvasFactory.create(i,n),Zn(u.context,e));let f=T.transform(o,[1/i,0,0,-1/n,0,0]);f=T.transform(f,[1,0,0,1,0,-n]);const p=me.slice();T.axialAlignedBoundingBox([0,0,i,n],f,p);const[g,m,b,y]=p,A=Math.round(b-g)||1,w=Math.round(y-m)||1,x=this.canvasFactory.create(A,w),S=x.context,E=g,_=m;S.translate(-E,-_),S.transform(...f);let k=null;if(!h){const P=this._scaleImage(u.canvas,Gt(S));h=P.img,k=P.tmpCanvas,h!==u.canvas&&(this.canvasFactory.destroy(u),u=null),l&&a&&(l.set(c,h),k=null,u=null)}S.imageSmoothingEnabled=tr(et(S),e.interpolate),Cs(S,h,0,0,h.width,h.height,0,0,i,n),k&&this.canvasFactory.destroy(k),u&&this.canvasFactory.destroy(u),S.globalCompositeOperation="source-in";const I=T.transform(Gt(S),[1,0,0,1,-E,-_]);return S.fillStyle=a?r.getPattern(s,this,I,xt.FILL,t):r,S.fillRect(0,0,i,n),l&&!a&&l.set(c,x.canvas),this.dependencyTracker?.recordDependencies(t,Ft.transformAndFill),{canvas:x.canvas,canvasEntry:l&&!a?null:x,offsetX:Math.round(E),offsetY:Math.round(_)}}setLineWidth(t,e){this.dependencyTracker?.recordSimpleData("lineWidth",t),e!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=e,this.ctx.lineWidth=e}setLineCap(t,e){this.dependencyTracker?.recordSimpleData("lineCap",t),this.ctx.lineCap=Gl[e]}setLineJoin(t,e){this.dependencyTracker?.recordSimpleData("lineJoin",t),this.ctx.lineJoin=Vl[e]}setMiterLimit(t,e){this.dependencyTracker?.recordSimpleData("miterLimit",t),this.ctx.miterLimit=e}setDash(t,e,s){this.dependencyTracker?.recordSimpleData("dash",t);const i=this.ctx;i.setLineDash!==void 0&&(i.setLineDash(e),i.lineDashOffset=s)}setRenderingIntent(t,e){}setFlatness(t,e){}setGState(t,e){for(const[s,i]of e)switch(s){case"LW":this.setLineWidth(t,i);break;case"LC":this.setLineCap(t,i);break;case"LJ":this.setLineJoin(t,i);break;case"ML":this.setMiterLimit(t,i);break;case"D":this.setDash(t,i[0],i[1]);break;case"RI":this.setRenderingIntent(t,i);break;case"FL":this.setFlatness(t,i);break;case"Font":this.setFont(t,i[0],i[1]);break;case"CA":this.dependencyTracker?.recordSimpleData("strokeAlpha",t),this.current.strokeAlpha=i;break;case"ca":this.dependencyTracker?.recordSimpleData("fillAlpha",t),this.ctx.globalAlpha=this.current.fillAlpha=i;break;case"BM":this.dependencyTracker?.recordSimpleData("globalCompositeOperation",t),this.ctx.globalCompositeOperation=i;break;case"SMask":this.dependencyTracker?.recordSimpleData("SMask",t),this.current.activeSMask=i?this.tempSMask:null,this.current.activeSMask&&(this.current.activeSMask.blendMode=this.ctx.globalCompositeOperation),this.tempSMask=null,this.checkSMaskState(t);break;case"TR":this.dependencyTracker?.recordSimpleData("filter",t),this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(i);break}}get inSMaskMode(){return!!this.suspendedCtx}_clearPreparedSMask(){this.smaskPreparedEntry&&(this.canvasFactory.destroy(this.smaskPreparedEntry),this.smaskPreparedEntry=null),this.smaskPreparedFor=null,this.smaskPreparedOffsetX=0,this.smaskPreparedOffsetY=0,this.smaskPreparedOOBAlpha=null}_ensurePreparedSMask(t){t!==this.smaskPreparedFor&&(this._clearPreparedSMask(),this._prepareSMaskCanvas(t))}checkSMaskState(t){const e=this.inSMaskMode;this.current.activeSMask&&!e?this.beginSMaskMode(t):!this.current.activeSMask&&e?this.endSMaskMode():this.current.activeSMask&&e&&this._ensurePreparedSMask(this.current.activeSMask)}_prepareSMaskCanvas(t){const{canvas:e,subtype:s,backdrop:i,transferMap:n}=t,r=s==="Luminosity"||s==="Alpha"&&n;if(!r&&!(s==="Luminosity"&&i)){this.smaskPreparedFor=t;return}let a;if(s==="Luminosity"&&i){const[y,A,w]=hs(i),x=Math.round(.3*y+.59*A+.11*w);a=n?.[x]??x}else a=n?.[0]??0;const o=4,{width:l,height:c}=this.ctx.canvas,h=e.width*e.height,u=l*c<o*h,f=r?{url:s==="Alpha"?this.filterFactory.addAlphaFilter(n):this.filterFactory.addLuminosityFilter(n),subtype:s,transferMap:n}:null,p=s==="Luminosity"?i:null;let g,m,b;u?(g=this._bakeSMaskCanvas(e,t.offsetX,t.offsetY,l,c,p,f),m=0,b=0):(g=this._bakeSMaskCanvas(e,0,0,e.width,e.height,p,f),m=t.offsetX,b=t.offsetY),this.smaskPreparedEntry=g,this.smaskPreparedFor=t,this.smaskPreparedOffsetX=m,this.smaskPreparedOffsetY=b,this.smaskPreparedOOBAlpha=!u&&a!==0?a:null}_bakeSMaskCanvas(t,e,s,i,n,r,a){!r&&!a&&K("_bakeSMaskCanvas with neither backdrop nor filter");const o=this.canvasFactory.create(i,n),l=o.context;if(l.drawImage(t,e,s),r&&(l.globalCompositeOperation="destination-atop",l.fillStyle=r,l.fillRect(0,0,i,n)),!a)return o;const c=this.canvasFactory.create(i,n),h=c.context;h.filter=a.url;const u=J.isCanvasFilterSupported&&h.filter!=="none"&&h.filter!=="";if(h.drawImage(o.canvas,0,0),J.isCanvasFilterSupported&&(h.filter="none"),!u){const f=h.getImageData(0,0,i,n),{data:p}=f,{transferMap:g}=a;if(a.subtype==="Luminosity")for(let m=0,b=p.length;m<b;m+=4){const y=.3*p[m]+.59*p[m+1]+.11*p[m+2]+.5|0;p[m]=p[m+1]=p[m+2]=0,p[m+3]=g?.[y]??y}else for(let m=3,b=p.length;m<b;m+=4)p[m]=g[p[m]];h.putImageData(f,0,0)}return this.canvasFactory.destroy(o),c}beginSMaskMode(t){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const{width:e,height:s}=this.ctx.canvas,i=this.canvasFactory.create(e,s);this.smaskScratchCanvas=i,this.suspendedCtx=this.ctx;const n=this.ctx=i.context;n.setTransform(this.suspendedCtx.getTransform()),fe(this.suspendedCtx,n),qn(n,this.suspendedCtx),this._ensurePreparedSMask(this.current.activeSMask),this.setGState(t,[["BM","source-over"]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),fe(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null,this.canvasFactory.destroy(this.smaskScratchCanvas),this.smaskScratchCanvas=null,this._clearPreparedSMask()}#p(t,e=null,s=1){const{width:i,height:n}=t,r=e??this.canvasFactory.create(i,n),a=r.context;s=Math.round(s*255)/255;const o=s<1;o&&this.#o===void 0&&(this.#o=J.isCanvasFilterSupported?new Map:"none");let l="none";if(o&&this.#o instanceof Map&&(l=this.#o.getOrInsertComputed(s,()=>this.filterFactory.addKnockoutFilter(s))),!o||l!=="none")return e&&(a.save(),a.setTransform(1,0,0,1,0,0),a.clearRect(0,0,i,n),a.restore()),a.filter=l,a.drawImage(t,0,0),a.filter="none",r;const c=t.getContext("2d",{willReadFrequently:!0}).getImageData(0,0,i,n),h=a.createImageData(i,n),u=c.data,f=h.data,p=s>0?1/s:1e6;for(let g=3,m=u.length;g<m;g+=4)f[g]=Math.min(Math.round(u[g]*p),255);return a.putImageData(h,0,0),r}#m(t,e,s,i){let n=t?.[e]??null;if(n&&(n.canvas.width!==s||n.canvas.height!==i)&&(this.canvasFactory.destroy(n),n=null),!n)return n=this.canvasFactory.create(s,i),t&&(t[e]=n),n;const r=n.context;return r.save(),r.setTransform(1,0,0,1,0,0),r.clearRect(0,0,s,i),r.restore(),n}#g(t,e,s={}){const{backdropCanvas:i=null,destTransform:n=[1,0,0,1,0,0],backdropOffset:r=[0,0],reuseMaskEntry:a=null,poolMeta:o=null,sourceAlpha:l=1,sourceFilter:c="none",knockoutAlpha:h=1}=s,{width:u,height:f}=e,p=this.#p(e,a,h),g=t.globalCompositeOperation;if(t.save(),t.setTransform(...n),t.globalAlpha=1,J.isCanvasFilterSupported&&(t.filter="none"),t.globalCompositeOperation="destination-out",t.drawImage(p.canvas,0,0),i){const[m,b]=r,y=this.#m(o,"knockoutBackdropEntry",u,f),A=y.context;A.drawImage(i,m,b,u,f,0,0,u,f),A.globalCompositeOperation="destination-in",A.drawImage(p.canvas,0,0),A.globalCompositeOperation="source-over",t.globalCompositeOperation="destination-over",t.drawImage(y.canvas,0,0),o||this.canvasFactory.destroy(y)}t.globalCompositeOperation=g,t.globalAlpha=l,J.isCanvasFilterSupported&&(t.filter=c??"none"),t.drawImage(e,0,0),t.restore(),a||this.canvasFactory.destroy(p)}#c(t=1){if(this.#t===0||this.#e>0||!this.contentVisible)return!1;this.#e++,this.#r=t;const e=this.#l.at(-1),{canvas:s}=this.ctx,i=this.#m(e,"knockoutTempEntry",s.width,s.height);this.#s=i;const n=i.context;return n.save(),n.setTransform(this.ctx.getTransform()),fe(this.ctx,n),this.#a=n.globalCompositeOperation,n.globalCompositeOperation="source-over",qn(n,this.ctx),this.#h=e,this.#i=this.ctx,this.#n=this.suspendedCtx,this.ctx=n,this.inSMaskMode&&(this.suspendedCtx=n),!0}#f(t){if(!t)return;const e=this.#s,s=this.#i,i=this.#n,n=e.context;this.#s=null,this.#i=null,this.#n=null,this.inSMaskMode&&this.suspendedCtx===n&&this.ctx!==n&&this.endSMaskMode(),this.inSMaskMode&&(this.suspendedCtx=i),this.ctx._removeMirroring(),this.ctx.globalCompositeOperation=this.#a,this.#a=null,fe(this.ctx,s),this.ctx=s;const r=this.#h;this.#h=null;const a=this.#r;this.#r=1;try{this.#g(i??s,e.canvas,{backdropCanvas:r?.backdropCtx?.canvas??null,backdropOffset:r?.backdropCtx?[r.offsetX,r.offsetY]:[0,0],reuseMaskEntry:r?.knockoutMaskEntry??null,poolMeta:r,knockoutAlpha:a})}finally{n.restore(),this.#e--,r||this.canvasFactory.destroy(e)}}compose(t){if(!this.current.activeSMask)return;t=t?[Math.floor(t[0]),Math.floor(t[1]),Math.ceil(t[2]),Math.ceil(t[3])]:[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const e=this.current.activeSMask,s=this.suspendedCtx,i=this.#e>0&&s===this.ctx;this.composeSMask(i?null:s,e,this.ctx,t),!i&&(this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore())}composeSMask(t,e,s,i){const n=i[0],r=i[1],a=i[2]-n,o=i[3]-r;if(a===0||o===0)return;const l=this.smaskPreparedEntry;if(l){let c=n,h=r,u=a,f=o;const p=this.smaskPreparedOOBAlpha,g=p!==null;if(g){c=Math.max(n,e.offsetX),h=Math.max(r,e.offsetY);const m=Math.min(n+a,e.offsetX+e.canvas.width),b=Math.min(r+o,e.offsetY+e.canvas.height);u=m-c,f=b-h}if(u>0&&f>0){const m=c-this.smaskPreparedOffsetX,b=h-this.smaskPreparedOffsetY;s.save(),s.globalAlpha=1,s.setTransform(1,0,0,1,0,0);const y=new Path2D;y.rect(c,h,u,f),s.clip(y),s.globalCompositeOperation="destination-in",s.drawImage(l.canvas,m,b,u,f,c,h,u,f),s.restore()}g&&p<255&&this._applySMaskOOBAlpha(s,n,r,a,o,c,h,c+u,h+f,p)}else this.genericComposeSMask(e,s,a,o,n,r);t&&(t.save(),t.globalAlpha=1,t.globalCompositeOperation=e.blendMode||"source-over",t.setTransform(1,0,0,1,0,0),t.drawImage(s.canvas,n,r,a,o,n,r,a,o),t.restore())}_applySMaskOOBAlpha(t,e,s,i,n,r,a,o,l,c){const h=r<o&&a<l;if(h&&r===e&&a===s&&o===e+i&&l===s+n)return;const u=new Path2D;u.rect(e,s,i,n),h&&u.rect(r,a,o-r,l-a),t.save(),t.globalAlpha=c/255,t.setTransform(1,0,0,1,0,0),t.clip(u,"evenodd"),t.globalCompositeOperation="destination-in",t.fillStyle="#000000",t.fillRect(e,s,i,n),t.restore()}genericComposeSMask(t,e,s,i,n,r){const{context:a,offsetX:o,offsetY:l}=t;e.save(),e.globalAlpha=1,e.setTransform(1,0,0,1,0,0);const c=new Path2D;c.rect(n,r,s,i),e.clip(c),e.globalCompositeOperation="destination-in",e.drawImage(a.canvas,n-o,r-l,s,i,n,r,s,i),e.restore()}save(t){this.inSMaskMode&&fe(this.ctx,this.suspendedCtx),this.ctx.save();const e=this.current;this.stateStack.push(e),this.current=e.clone(),this.dependencyTracker?.save(t)}restore(t){if(this.dependencyTracker?.restore(t),this.stateStack.length===0){this.inSMaskMode&&this.endSMaskMode();return}this.current=this.stateStack.pop(),this.ctx.restore(),this.inSMaskMode&&(fe(this.suspendedCtx,this.ctx),this.ctx.setTransform(this.suspendedCtx.getTransform())),this.checkSMaskState(t),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}transform(t,e,s,i,n,r,a){this.dependencyTracker?.recordIncrementalData("transform",t),this.ctx.transform(e,s,i,n,r,a),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(t,e,s,i){let[n]=s;if(!i){n||=s[0]=new Path2D,e!==Xt.stroke&&e!==Xt.closeStroke&&(this.current.tilingPatternDims=null),this[e](t,n);return}if(this.dependencyTracker!==null){const a=e===Xt.stroke?this.current.lineWidth/2:0;this.dependencyTracker.resetBBox(t).recordBBox(t,this.ctx,i[0]-a,i[2]+a,i[1]-a,i[3]+a).recordDependencies(t,["transform"])}n instanceof Path2D||(n=s[0]=Cr(n)),T.axialAlignedBoundingBox(i,et(this.ctx),this.current.minMax);const r=this.current.tilingPatternDims;if(r&&e!==Xt.stroke&&e!==Xt.closeStroke&&this.current.fillColor instanceof Ze){const a=T.intersect(this.current.clipBox,this.current.minMax);a?this.current.fillColor.updatePatternDims(a,r):this.current.tilingPatternDims=null}this[e](t,n),this._pathStartIdx=t}closePath(t){this.ctx.closePath()}stroke(t,e,s=!0){const i=s&&this.#c(this.current.strokeAlpha),n=this.ctx,r=this.current.strokeColor;if(n.globalAlpha=this.current.strokeAlpha,this.contentVisible)if(typeof r=="object"&&r?.getPattern){const a=r.isModifyingCurrentTransform()?n.getTransform():null;if(n.save(),n.strokeStyle=r.getPattern(n,this,Gt(n),xt.STROKE,t),a){const o=new Path2D;o.addPath(e,n.getTransform().invertSelf().multiplySelf(a)),e=o}this.rescaleAndStroke(e,!1),n.restore()}else this.rescaleAndStroke(e,!0);this.dependencyTracker?.recordDependencies(t,Ft.stroke),s&&this.consumePath(t,e,this.current.getClippedPathBoundingBox(xt.STROKE,et(this.ctx))),n.globalAlpha=this.current.fillAlpha,this.#f(i)}closeStroke(t,e){this.stroke(t,e)}fill(t,e,s=!0){const i=s&&this.#c(this.current.fillAlpha),n=this.ctx,r=this.current.fillColor,a=this.current.patternFill;let o=!1;const l=this.current.getClippedPathBoundingBox();if(this.dependencyTracker?.recordDependencies(t,Ft.fill),a){const c=this.current.tilingPatternDims,h=c&&r.canSkipPatternCanvas(c);if(h){r.drawPattern(this,e,this.pendingEOFill,h,t),this.pendingEOFill=!1,s&&this.consumePath(t,e,l),this.current.tilingPatternDims=null,this.#f(i);return}const u=r.isModifyingCurrentTransform()?n.getTransform():null;if(this.dependencyTracker?.save(t),n.save(),n.fillStyle=r.getPattern(n,this,Gt(n),xt.FILL,t),u){const f=new Path2D;f.addPath(e,n.getTransform().invertSelf().multiplySelf(u)),e=f}o=!0}this.contentVisible&&l!==null&&(this.pendingEOFill?(n.fill(e,"evenodd"),this.pendingEOFill=!1):n.fill(e)),o&&(n.restore(),this.dependencyTracker?.restore(t)),s&&this.consumePath(t,e,l),this.#f(i)}eoFill(t,e){this.pendingEOFill=!0,this.fill(t,e)}fillStroke(t,e){const s=this.#c(Math.min(this.current.fillAlpha,this.current.strokeAlpha));this.fill(t,e,!1),this.stroke(t,e,!1),this.consumePath(t,e),this.#f(s)}eoFillStroke(t,e){this.pendingEOFill=!0,this.fillStroke(t,e)}closeFillStroke(t,e){this.fillStroke(t,e)}closeEOFillStroke(t,e){this.pendingEOFill=!0,this.fillStroke(t,e)}endPath(t,e){this.consumePath(t,e)}rawFillPath(t,e){const s=this.#c(this.current.fillAlpha);this.ctx.fill(e),this.dependencyTracker?.recordDependencies(t,Ft.rawFillPath).recordOperation(t),this.#f(s)}clip(t){this.dependencyTracker?.recordFutureForcedDependency("clipMode",t),this.pendingClip=Wl}eoClip(t){this.dependencyTracker?.recordFutureForcedDependency("clipMode",t),this.pendingClip=er}beginText(t){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(t).resetIncrementalData("sameLineText").resetIncrementalData("moveText",t)}endText(t){const e=this.pendingTextPaths,s=this.ctx;if(this.dependencyTracker){const{dependencyTracker:i}=this;e!==void 0&&i.recordFutureForcedDependency("textClip",i.getOpenMarker()).recordFutureForcedDependency("textClip",t),i.recordCloseMarker(t)}if(e!==void 0){const i=new Path2D,n=s.getTransform().invertSelf();for(const{transform:r,x:a,y:o,fontSize:l,path:c}of e)c&&i.addPath(c,new DOMMatrix(r).preMultiplySelf(n).translate(a,o).scale(l,-l));s.clip(i)}delete this.pendingTextPaths}setCharSpacing(t,e){this.dependencyTracker?.recordSimpleData("charSpacing",t),this.current.charSpacing=e}setWordSpacing(t,e){this.dependencyTracker?.recordSimpleData("wordSpacing",t),this.current.wordSpacing=e}setHScale(t,e){this.dependencyTracker?.recordSimpleData("hScale",t),this.current.textHScale=e/100}setLeading(t,e){this.dependencyTracker?.recordSimpleData("leading",t),this.current.leading=-e}setFont(t,e,s){this.dependencyTracker?.recordSimpleData("font",t).recordSimpleDataFromNamed("fontObj",e,t);const i=this.commonObjs.get(e),n=this.current;if(!i)throw new Error(`Can't find font for ${e}`);if(n.fontMatrix=i.fontMatrix||xi,(n.fontMatrix[0]===0||n.fontMatrix[3]===0)&&V("Invalid font matrix for font "+e),s<0?(s=-s,n.fontDirection=-1):n.fontDirection=1,this.current.font=i,this.current.fontSize=s,i.isType3Font)return;const r=i.loadedName||"sans-serif",a=i.systemFontInfo?.css||`"${r}", ${i.fallbackName}`;let o="normal";i.black?o="900":i.bold&&(o="bold");const l=i.italic?"italic":"normal",c=nt(s,Ul,zl);this.current.fontSizeScale=s/c,this.ctx.font=`${l} ${o} ${c}px ${a}`}setTextRenderingMode(t,e){this.dependencyTracker?.recordSimpleData("textRenderingMode",t),this.current.textRenderingMode=e}setTextRise(t,e){this.dependencyTracker?.recordSimpleData("textRise",t),this.current.textRise=e}moveText(t,e,s){this.dependencyTracker?.resetIncrementalData("sameLineText").recordIncrementalData("moveText",t),this.current.x=this.current.lineX+=e,this.current.y=this.current.lineY+=s}setLeadingMoveText(t,e,s){this.setLeading(t,-s),this.moveText(t,e,s)}setTextMatrix(t,e){this.dependencyTracker?.resetIncrementalData("sameLineText").recordSimpleData("textMatrix",t);const{current:s}=this;s.textMatrix=e,s.textMatrixScale=Math.hypot(e[0],e[1]),s.x=s.lineX=0,s.y=s.lineY=0}nextLine(t){this.moveText(t,0,this.current.leading),this.dependencyTracker?.recordIncrementalData("moveText",this.dependencyTracker.getSimpleIndex("leading")??t)}#y(t,e,s){const i=new Path2D;return i.addPath(t,new DOMMatrix(s).invertSelf().multiplySelf(e)),i}paintChar(t,e,s,i,n,r){const a=this.ctx,o=this.current,l=o.font,c=o.textRenderingMode,h=o.fontSize/o.fontSizeScale,u=c&bt.FILL_STROKE_MASK,f=!!(c&bt.ADD_TO_PATH_FLAG),p=o.patternFill&&!l.missingFile,g=o.patternStroke&&!l.missingFile;let m;if((l.disableFontFace||f||p||g)&&!l.missingFile&&(m=l.getPathGenerator(this.commonObjs,e)),m&&(l.disableFontFace||p||g)){a.save(),a.translate(s,i),a.scale(h,-h),this.dependencyTracker?.recordCharacterBBox(t,a,l);let b;if(u===bt.FILL||u===bt.FILL_STROKE)if(n){b=a.getTransform(),a.setTransform(...n);const y=this.#y(m,b,n);a.fill(y)}else a.fill(m);if(u===bt.STROKE||u===bt.FILL_STROKE)if(r){b||=a.getTransform(),a.setTransform(...r);const{a:y,b:A,c:w,d:x}=b,S=T.inverseTransform(r),E=T.transform([y,A,w,x,0,0],S);T.singularValueDecompose2dScale(E,Dt),a.lineWidth*=Math.max(Dt[0],Dt[1])/h,a.stroke(this.#y(m,b,r))}else a.lineWidth/=h,a.stroke(m);a.restore()}else(u===bt.FILL||u===bt.FILL_STROKE)&&(a.fillText(e,s,i),this.dependencyTracker?.recordCharacterBBox(t,a,l,h,s,i,()=>a.measureText(e))),(u===bt.STROKE||u===bt.FILL_STROKE)&&(this.dependencyTracker&&this.dependencyTracker?.recordCharacterBBox(t,a,l,h,s,i,()=>a.measureText(e)).recordDependencies(t,Ft.stroke),a.strokeText(e,s,i));f&&((this.pendingTextPaths||=[]).push({transform:et(a),x:s,y:i,fontSize:h,path:m}),this.dependencyTracker?.recordCharacterBBox(t,a,l,h,s,i))}get isFontSubpixelAAEnabled(){const t=this.canvasFactory.create(10,10),e=t.context;e.scale(1.5,1),e.fillText("I",0,10);const s=e.getImageData(0,0,10,10).data;this.canvasFactory.destroy(t);let i=!1;for(let n=3;n<s.length;n+=4)if(s[n]>0&&s[n]<255){i=!0;break}return z(this,"isFontSubpixelAAEnabled",i)}showText(t,e){this.dependencyTracker&&(this.dependencyTracker.recordDependencies(t,Ft.showText).resetBBox(t),this.current.textRenderingMode&bt.ADD_TO_PATH_FLAG&&this.dependencyTracker.recordFutureForcedDependency("textClip",t).inheritPendingDependenciesAsFutureForcedDependencies());const s=this.current,i=s.font;if(i.isType3Font){const B=this.#c(s.fillAlpha);this.showType3Text(t,e),this.dependencyTracker?.recordShowTextOperation(t),this.#f(B);return}const n=s.fontSize;if(n===0){this.dependencyTracker?.recordOperation(t);return}const r=this.#c(s.fillAlpha),a=this.ctx,o=s.fontSizeScale,l=s.charSpacing,c=s.wordSpacing,h=s.fontDirection,u=s.textHScale*h,f=e.length,p=i.vertical,g=p?1:-1,m=i.defaultVMetrics,b=n*s.fontMatrix[0],y=s.textRenderingMode===bt.FILL&&!i.disableFontFace&&!s.patternFill;a.save(),s.textMatrix&&a.transform(...s.textMatrix),a.translate(s.x,s.y+s.textRise),h>0?a.scale(u,-1):a.scale(u,1);let A,w;const x=s.textRenderingMode&bt.FILL_STROKE_MASK,S=x===bt.FILL||x===bt.FILL_STROKE,E=x===bt.STROKE||x===bt.FILL_STROKE;let _=s.lineWidth;const k=s.textMatrixScale;if(k===0||_===0?E&&(_=this.getSinglePixelWidth()):_/=k,o!==1&&(a.scale(o,o),_/=o),a.lineWidth=_,S&&s.patternFill){a.save();const B=s.fillColor.getPattern(a,this,Gt(a),xt.FILL,t);A=et(a),a.restore(),a.fillStyle=B}if(E&&s.patternStroke){a.save();const B=s.strokeColor.getPattern(a,this,Gt(a),xt.STROKE,t);w=et(a),a.restore(),a.strokeStyle=B}if(i.isInvalidPDFjsFont){const B=[];let W=0;for(const Z of e)B.push(Z.unicode),W+=Z.width;const Y=B.join("");if(a.fillText(Y,0,0),this.dependencyTracker!==null){const Z=a.measureText(Y);this.dependencyTracker.recordBBox(t,this.ctx,-Z.actualBoundingBoxLeft,Z.actualBoundingBoxRight,-Z.actualBoundingBoxAscent,Z.actualBoundingBoxDescent).recordShowTextOperation(t)}s.x+=W*b*u,a.restore(),this.compose(),this.#f(r);return}let I=0,P;for(P=0;P<f;++P){const B=e[P];if(typeof B=="number"){I+=g*B*n/1e3;continue}let W=!1;const Y=(B.isSpace?c:0)+l,Z=B.fontChar,L=B.accent;let F,rt,ht=B.width;if(p){const M=B.vmetric||m,j=-(B.vmetric?M[1]:ht*.5)*b,dt=M[2]*b;ht=M?-M[0]:ht,F=j/o,rt=(I+dt)/o}else F=I/o,rt=0;let vt;if(i.remeasure&&ht>0){vt=a.measureText(Z);const M=vt.width*1e3/n*o;if(ht<M&&this.isFontSubpixelAAEnabled){const j=ht/M;W=!0,a.save(),a.scale(j,1),F/=j}else ht!==M&&(F+=(ht-M)/2e3*n/o)}if(this.contentVisible&&(B.isInFont||i.missingFile)){if(y&&!L)a.fillText(Z,F,rt),this.dependencyTracker?.recordCharacterBBox(t,a,vt?{bbox:null}:i,n/o,F,rt,()=>vt??a.measureText(Z));else if(this.paintChar(t,Z,F,rt,A,w),L){const M=F+n*L.offset.x/o,j=rt-n*L.offset.y/o;this.paintChar(t,L.fontChar,M,j,A,w)}}const Ot=p?ht*b-Y*h:ht*b+Y*h;I+=Ot,W&&a.restore()}p?s.y-=I:s.x+=I*u,a.restore(),this.compose(),this.dependencyTracker?.recordShowTextOperation(t),this.#f(r)}showType3Text(t,e){const s=this.ctx,i=this.current,n=i.font,r=i.fontSize,a=i.fontDirection,o=n.vertical?1:-1,l=i.charSpacing,c=i.wordSpacing,h=i.textHScale*a,u=i.fontMatrix||xi,f=e.length,p=i.textRenderingMode===bt.INVISIBLE;let g,m,b,y;if(p||r===0)return;this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null,s.save(),i.textMatrix&&s.transform(...i.textMatrix),s.translate(i.x,i.y+i.textRise),s.scale(h,a);const A=this.dependencyTracker;for(this.dependencyTracker=A?new is(A,t):null,g=0;g<f;++g){if(m=e[g],typeof m=="number"){y=o*m*r/1e3,this.ctx.translate(y,0),i.x+=y*h;continue}const w=(m.isSpace?c:0)+l,x=n.charProcOperatorList[m.operatorListId];x?this.contentVisible&&(this.save(),x.fnArray[0]===Xt.setCharWidth&&(i.fillAlpha=i.strokeAlpha=1,s.globalAlpha=1),s.scale(r,r),s.transform(...u),this.executeOperatorList(x),this.restore()):V(`Type3 character "${m.operatorListId}" is not available.`);const S=[m.width,0];T.applyTransform(S,u),b=S[0]*r+w,s.translate(b,0),i.x+=b*h}s.restore(),A&&(this.dependencyTracker=A)}setCharWidth(t,e,s){}setCharWidthAndBounds(t,e,s,i,n,r,a){const o=new Path2D;o.rect(i,n,r-i,a-n),this.ctx.clip(o),this.dependencyTracker?.recordBBox(t,this.ctx,i,r,n,a).recordClipBox(t,this.ctx,i,r,n,a),this.endPath(t)}getColorN_Pattern(t,e){let s;if(e[0]==="TilingPattern"){const i=this.baseTransform||et(this.ctx),n={createCanvasGraphics:(r,a)=>new Oe(r,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack},void 0,void 0,this.dependencyTracker?new is(this.dependencyTracker,a,!0):null)};s=new Ze(e,this.ctx,n,i)}else s=this._getPattern(t,e[1],e[2]);return s}setStrokeColorN(t,...e){this.dependencyTracker?.recordSimpleData("strokeColor",t),this.current.strokeColor=this.getColorN_Pattern(t,e),this.current.patternStroke=!0}setFillColorN(t,...e){this.dependencyTracker?.recordSimpleData("fillColor",t);const s=this.current.fillColor=this.getColorN_Pattern(t,e);this.current.patternFill=!0,this.current.tilingPatternDims=s instanceof Ze?[0,0,0,0]:null}setStrokeRGBColor(t,e){this.dependencyTracker?.recordSimpleData("strokeColor",t),this.ctx.strokeStyle=this.current.strokeColor=e,this.current.patternStroke=!1}setStrokeTransparent(t){this.dependencyTracker?.recordSimpleData("strokeColor",t),this.ctx.strokeStyle=this.current.strokeColor="transparent",this.current.patternStroke=!1}setFillRGBColor(t,e){this.dependencyTracker?.recordSimpleData("fillColor",t),this.ctx.fillStyle=this.current.fillColor=e,this.current.patternFill=!1,this.current.tilingPatternDims=null}setFillTransparent(t){this.dependencyTracker?.recordSimpleData("fillColor",t),this.ctx.fillStyle=this.current.fillColor="transparent",this.current.patternFill=!1,this.current.tilingPatternDims=null}_getPattern(t,e,s=null){let i;return this.cachedPatterns.has(e)?i=this.cachedPatterns.get(e):(i=Hl(this.getObject(t,e)),this.cachedPatterns.set(e,i)),s&&(i.matrix=s),i}shadingFill(t,e){if(!this.contentVisible)return;const s=this.#c(this.current.fillAlpha),i=this.ctx;this.save(t);const n=this._getPattern(t,e);i.fillStyle=n.getPattern(i,this,Gt(i),xt.SHADING,t);const r=Gt(i);if(r){const{width:a,height:o}=i.canvas,l=me.slice();T.axialAlignedBoundingBox([0,0,a,o],r,l);const[c,h,u,f]=l;this.ctx.fillRect(c,h,u-c,f-h)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.dependencyTracker?.resetBBox(t).recordFullPageBBox(t).recordDependencies(t,Ft.transform).recordDependencies(t,Ft.fill).recordOperation(t),this.compose(this.current.getClippedPathBoundingBox()),this.restore(t),this.#f(s)}beginInlineImage(){K("Should not call beginInlineImage")}beginImageData(){K("Should not call beginImageData")}paintFormXObjectBegin(t,e,s){if(this.contentVisible&&(this.save(t),this.baseTransformStack.push(this.baseTransform),e&&this.transform(t,...e),this.baseTransform=et(this.ctx),s)){T.axialAlignedBoundingBox(s,this.baseTransform,this.current.minMax);const[i,n,r,a]=s,o=new Path2D;o.rect(i,n,r-i,a-n),this.ctx.clip(o),this.dependencyTracker?.recordClipBox(t,this.ctx,i,r,n,a),this.endPath(t)}}paintFormXObjectEnd(t){this.contentVisible&&(this.restore(t),this.baseTransform=this.baseTransformStack.pop())}beginGroup(t,e){if(!this.contentVisible)return;this.save(t);const{inSMaskMode:s}=this;s&&(this.endSMaskMode(),this.current.activeSMask=null);const i=this.ctx;if((!e.needsIsolation||!e.isolated&&!e.hasSoftMask)&&!e.knockout&&!e.isGray&&this.#t===0&&i.globalAlpha===1&&i.globalCompositeOperation==="source-over"&&!s){if(e.bbox){let y=new Path2D;const[A,w,x,S]=e.bbox;if(y.rect(A,w,x-A,S-w),e.matrix){const E=new Path2D;E.addPath(y,new DOMMatrix(e.matrix)),y=E}i.clip(y)}this.groupStack.push(null),this.#l.push(null),this.groupLevel++;return}!e.isolated&&!e.knockout&&this.#t===0&&zs("TODO: Fully support non-isolated non-knockout groups.");const n=et(i);e.matrix&&i.transform(...e.matrix);const r=[0,0,i.canvas.width,i.canvas.height];let a;e.bbox?(a=me.slice(),T.axialAlignedBoundingBox(e.bbox,et(i),a),a=T.intersect(a,r)||[0,0,0,0]):a=r;const o=Math.floor(a[0]),l=Math.floor(a[1]),c=Math.max(Math.ceil(a[2])-o,1),h=Math.max(Math.ceil(a[3])-l,1);this.current.startNewPathAndClipBox([0,0,c,h]);const u=this.canvasFactory.create(c,h);e.smask&&this.smaskGroupCanvases.push(u);const f=u.context,p=e.knockout&&!e.isolated?i:null,g=!e.isolated&&!e.knockout&&!e.smask&&e.needsIsolation&&this.#t>0,m=e.knockout?this.canvasFactory.create(c,h):null,b=this.#t;if(e.knockout?this.#t++:this.#t=0,f.translate(-o,-l),f.transform(...n),!e.isolated&&!e.smask&&s&&e.needsIsolation&&(f.save(),f.setTransform(1,0,0,1,0,0),f.drawImage(i.canvas,-o,-l),f.restore()),e.bbox){let y=new Path2D;const[A,w,x,S]=e.bbox;if(y.rect(A,w,x-A,S-w),e.matrix){const E=new Path2D;E.addPath(y,new DOMMatrix(e.matrix)),y=E}f.clip(y)}e.smask&&this.smaskStack.push({canvas:u.canvas,context:f,offsetX:o,offsetY:l,subtype:e.smask.subtype,backdrop:e.smask.backdrop,transferMap:e.smask.transferMap||null}),(!e.smask||this.dependencyTracker)&&(i.setTransform(1,0,0,1,0,0),i.translate(o,l),i.save()),fe(i,f),this.ctx=f,this.dependencyTracker?.inheritSimpleDataAsFutureForcedDependencies(["fillAlpha","strokeAlpha","globalCompositeOperation"]).pushBaseTransform(i),this.setGState(t,[["BM","source-over"],["ca",1],["CA",1],["TR",null]]),this.groupStack.push(i),this.#l.push({backdropCtx:p,savedKnockoutLevel:b,offsetX:o,offsetY:l,hasInnerBackdrop:g,knockoutMaskEntry:m,knockoutTempEntry:null,knockoutBackdropEntry:null}),this.groupLevel++}endGroup(t,e){if(!this.contentVisible)return;this.groupLevel--;const s=this.ctx,i=this.groupStack.pop(),n=this.#l.pop();if(n&&(this.#t=n.savedKnockoutLevel),i===null){this.restore(t);return}if(e.isGray&&this.#v(s),this.ctx=i,this.ctx.imageSmoothingEnabled=!1,this.dependencyTracker?.popBaseTransform(),e.smask)this.tempSMask=this.smaskStack.pop(),this.restore(t),this.dependencyTracker&&(this.ctx.restore(),this.inSMaskMode&&this.ctx.setTransform(this.suspendedCtx.getTransform())),this.#b(n);else{this.ctx.restore();const r=et(this.ctx);this.restore(t),this.ctx.save(),this.ctx.setTransform(...r);const a=me.slice();T.axialAlignedBoundingBox([0,0,s.canvas.width,s.canvas.height],r,a);const o=this.#l.at(-1);if(this.#t>0)if(n.hasInnerBackdrop){const{width:l,height:c}=s.canvas,h=this.canvasFactory.create(l,c),u=h.context;u.drawImage(i.canvas,n.offsetX,n.offsetY,l,c,0,0,l,c),u.globalCompositeOperation="source-over",u.drawImage(s.canvas,0,0);const f=this.#p(s.canvas);u.globalCompositeOperation="destination-in",u.drawImage(f.canvas,0,0);const p=this.ctx.globalCompositeOperation,g=this.ctx.globalAlpha,m=this.ctx.filter;this.ctx.save(),this.ctx.setTransform(...r),this.ctx.globalAlpha=1,J.isCanvasFilterSupported&&(this.ctx.filter="none"),this.ctx.globalCompositeOperation="destination-out",this.ctx.drawImage(f.canvas,0,0),this.ctx.globalCompositeOperation=p,this.ctx.globalAlpha=g,J.isCanvasFilterSupported&&(this.ctx.filter=m??"none"),this.ctx.drawImage(h.canvas,0,0),this.ctx.restore(),this.canvasFactory.destroy(f),this.canvasFactory.destroy(h)}else{const l=o?.backdropCtx??null;this.#g(this.ctx,s.canvas,{backdropCanvas:l?.canvas??null,destTransform:r,backdropOffset:l?[o.offsetX+n.offsetX,o.offsetY+n.offsetY]:[0,0],sourceAlpha:this.ctx.globalAlpha,sourceFilter:this.ctx.filter})}else this.ctx.drawImage(s.canvas,0,0);this.ctx.restore(),this.canvasFactory.destroy({canvas:s.canvas,context:s}),this.#b(n),this.compose(a)}}#v(t){const{canvas:e}=t,{width:s,height:i}=e;if(J.isCanvasFilterSupported){t.save(),t.setTransform(1,0,0,1,0,0),t.filter="grayscale(1)",t.globalAlpha=1,t.globalCompositeOperation="copy",t.drawImage(e,0,0),t.restore();return}const n=t.getImageData(0,0,s,i),{data:r}=n;for(let a=0,o=r.length;a<o;a+=4){const l=r[a]*.2126+r[a+1]*.7152+r[a+2]*.0722+.5|0;r[a]=r[a+1]=r[a+2]=l}t.putImageData(n,0,0)}#b(t){t&&(t.knockoutMaskEntry&&(this.canvasFactory.destroy(t.knockoutMaskEntry),t.knockoutMaskEntry=null),t.knockoutTempEntry&&(this.canvasFactory.destroy(t.knockoutTempEntry),t.knockoutTempEntry=null),t.knockoutBackdropEntry&&(this.canvasFactory.destroy(t.knockoutBackdropEntry),t.knockoutBackdropEntry=null))}beginAnnotation(t,e,s,i,n,r,a){if(this.#u(),Es(this.ctx),this.ctx.save(),this.save(t),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),s){const o=s[2]-s[0],l=s[3]-s[1];if(r&&this.annotationCanvasMap){i=i.slice(),i[4]-=s[0],i[5]-=s[1],s=s.slice(),s[0]=s[1]=0,s[2]=o,s[3]=l,T.singularValueDecompose2dScale(et(this.ctx),Dt);const{viewportScale:c}=this,h=Math.ceil(o*this.outputScaleX*c),u=Math.ceil(l*this.outputScaleY*c);this.annotationCanvas=this.canvasFactory.create(h,u);const{canvas:f,context:p}=this.annotationCanvas;if(a){const g=this.annotationCanvasMap.getOrInsertComputed(e,ls);f.setAttribute("data-canvas-name",a);const m=g.findIndex(b=>b.getAttribute("data-canvas-name")===a);m===-1?g.push(f):g[m]=f}else this.annotationCanvasMap.set(e,f);this.annotationCanvas.savedCtx=this.ctx,this.ctx=p,this.ctx.save(),this.ctx.setTransform(Dt[0],0,0,-Dt[1],0,l*Dt[1]),Es(this.ctx)}else{Es(this.ctx),this.endPath(t);const c=new Path2D;c.rect(s[0],s[1],o,l),this.ctx.clip(c)}}this.current=new Qn(this.ctx.canvas.width,this.ctx.canvas.height),this.baseTransformStack.push(this.baseTransform),this.transform(t,...i),this.transform(t,...n),this.baseTransform=et(this.ctx)}endAnnotation(t){this.annotationCanvas&&(this.ctx.restore(),this.#d(),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas),this.baseTransform=this.baseTransformStack.pop()}paintImageMaskXObject(t,e){if(!this.contentVisible)return;const s=e.count;e=this.getObject(t,e.data,e),e.count=s;const i=this.#c(this.current.fillAlpha),n=this.ctx,r=this._createMaskCanvas(t,e),a=r.canvas;n.save(),n.setTransform(1,0,0,1,0,0),n.drawImage(a,r.offsetX,r.offsetY),this.dependencyTracker?.resetBBox(t).recordBBox(t,this.ctx,r.offsetX,r.offsetX+a.width,r.offsetY,r.offsetY+a.height).recordOperation(t),n.restore(),r.canvasEntry&&this.canvasFactory.destroy(r.canvasEntry),this.compose(),this.#f(i)}paintImageMaskXObjectRepeat(t,e,s,i=0,n=0,r,a){if(!this.contentVisible)return;e=this.getObject(t,e.data,e);const o=this.#c(this.current.fillAlpha),l=this.ctx;l.save();const c=et(l);l.transform(s,i,n,r,0,0);const h=this._createMaskCanvas(t,e);l.setTransform(1,0,0,1,h.offsetX-c[4],h.offsetY-c[5]),this.dependencyTracker?.resetBBox(t);for(let u=0,f=a.length;u<f;u+=2){const p=T.transform(c,[s,i,n,r,a[u],a[u+1]]);l.drawImage(h.canvas,p[4],p[5]),this.dependencyTracker?.recordBBox(t,this.ctx,p[4],p[4]+h.canvas.width,p[5],p[5]+h.canvas.height)}l.restore(),h.canvasEntry&&this.canvasFactory.destroy(h.canvasEntry),this.compose(),this.dependencyTracker?.recordOperation(t),this.#f(o)}paintImageMaskXObjectGroup(t,e){if(!this.contentVisible)return;const s=this.#c(this.current.fillAlpha),i=this.ctx,n=this.current.fillColor,r=this.current.patternFill;this.dependencyTracker?.resetBBox(t).recordDependencies(t,Ft.transformAndFill);for(const a of e){const{data:o,width:l,height:c,transform:h}=a,u=this.canvasFactory.create(l,c),f=u.context;f.save();const p=this.getObject(t,o,a);Zn(f,p),f.globalCompositeOperation="source-in",f.fillStyle=r?n.getPattern(f,this,Gt(i),xt.FILL,t):n,f.fillRect(0,0,l,c),f.restore(),i.save(),i.transform(...h),i.scale(1,-1),Cs(i,u.canvas,0,0,l,c,0,-1,1,1),this.canvasFactory.destroy(u),this.dependencyTracker?.recordBBox(t,i,0,l,0,c),i.restore()}this.compose(),this.dependencyTracker?.recordOperation(t),this.#f(s)}paintImageXObject(t,e){if(!this.contentVisible)return;const s=this.getObject(t,e);if(!s){V("Dependent image isn't ready yet");return}this.paintInlineImageXObject(t,s)}paintImageXObjectRepeat(t,e,s,i,n){if(!this.contentVisible)return;const r=this.getObject(t,e);if(!r){V("Dependent image isn't ready yet");return}const a=r.width,o=r.height,l=[];for(let c=0,h=n.length;c<h;c+=2)l.push({transform:[s,0,0,i,n[c],n[c+1]],x:0,y:0,w:a,h:o});this.paintInlineImageXObjectGroup(t,r,l)}applyTransferMapsToCanvas(t){return this.current.transferMaps!=="none"&&(t.filter=this.current.transferMaps,t.drawImage(t.canvas,0,0),t.filter="none"),t.canvas}applyTransferMapsToBitmap(t){if(this.current.transferMaps==="none")return{img:t.bitmap,canvasEntry:null};const{bitmap:e,width:s,height:i}=t,n=this.canvasFactory.create(s,i),r=n.context;return r.filter=this.current.transferMaps,r.drawImage(e,0,0),r.filter="none",{img:n.canvas,canvasEntry:n}}paintInlineImageXObject(t,e){if(!this.contentVisible)return;const s=e.width,i=e.height,n=this.#c(this.current.fillAlpha),r=this.ctx;this.save(t);const{filter:a}=r;a!=="none"&&a!==""&&(r.filter="none"),r.scale(1/s,-1/i);let o,l=null;if(e.bitmap){const h=this.applyTransferMapsToBitmap(e);o=h.img,l=h.canvasEntry}else{const h=this.canvasFactory.create(s,i);Jn(h.context,e),o=this.applyTransferMapsToCanvas(h.context),l=h}const c=this._scaleImage(o,Gt(r));r.imageSmoothingEnabled=tr(et(r),e.interpolate),this.dependencyTracker&&(this.dependencyTracker.resetBBox(t).recordBBox(t,r,0,s,-i,0).recordDependencies(t,Ft.imageXObject).recordOperation(t),this.imagesTracker?.record(r,s,i,this.dependencyTracker.clipBox)),Cs(r,c.img,0,0,c.paintWidth,c.paintHeight,0,-i,s,i),c.tmpCanvas&&this.canvasFactory.destroy(c.tmpCanvas),l&&this.canvasFactory.destroy(l),this.compose(),this.restore(t),this.#f(n)}paintInlineImageXObjectGroup(t,e,s){if(!this.contentVisible)return;const i=this.#c(this.current.fillAlpha),n=this.ctx;let r,a=null;if(e.bitmap)r=e.bitmap;else{const o=e.width,l=e.height,c=this.canvasFactory.create(o,l);Jn(c.context,e),r=this.applyTransferMapsToCanvas(c.context),a=c}this.dependencyTracker?.resetBBox(t);for(const o of s)n.save(),n.transform(...o.transform),n.scale(1,-1),Cs(n,r,o.x,o.y,o.w,o.h,0,-1,1,1),this.dependencyTracker?.recordBBox(t,n,0,1,-1,0),n.restore();a&&this.canvasFactory.destroy(a),this.dependencyTracker?.recordOperation(t),this.compose(),this.#f(i)}paintSolidColorImageMask(t){if(!this.contentVisible)return;const e=this.#c(this.current.fillAlpha);this.dependencyTracker?.resetBBox(t).recordBBox(t,this.ctx,0,1,0,1).recordDependencies(t,Ft.fill).recordOperation(t),this.ctx.fillRect(0,0,1,1),this.compose(),this.#f(e)}markPoint(t,e){}markPointProps(t,e,s){}beginMarkedContent(t,e){this.dependencyTracker?.beginMarkedContent(t),this.markedContentStack.push({visible:!0})}beginMarkedContentProps(t,e,s){this.dependencyTracker?.beginMarkedContent(t),e==="OC"?this.markedContentStack.push({visible:this.optionalContentConfig.isVisible(s)}):this.markedContentStack.push({visible:!0}),this.contentVisible=this.isContentVisible()}endMarkedContent(t){this.dependencyTracker?.endMarkedContent(t),this.markedContentStack.pop(),this.contentVisible=this.isContentVisible()}beginCompat(t){}endCompat(t){}consumePath(t,e,s){const i=this.current.isEmptyClip();this.pendingClip&&this.current.updateClipFromPath(),this.pendingClip||this.compose(s);const n=this.ctx;this.pendingClip?(i||(this.pendingClip===er?n.clip(e,"evenodd"):n.clip(e)),this.pendingClip=null,this.dependencyTracker?.bboxToClipBoxDropOperation(t).recordFutureForcedDependency("clipPath",t)):this.dependencyTracker?.recordOperation(t),this.current.startNewPathAndClipBox(this.current.clipBox)}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){const t=et(this.ctx);if(t[1]===0&&t[2]===0)this._cachedGetSinglePixelWidth=1/Math.min(Math.abs(t[0]),Math.abs(t[3]));else{const e=Math.abs(t[0]*t[3]-t[2]*t[1]),s=Math.hypot(t[0],t[2]),i=Math.hypot(t[1],t[3]);this._cachedGetSinglePixelWidth=Math.max(s,i)/e}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(this._cachedScaleForStroking[0]===-1){const{lineWidth:t}=this.current,{a:e,b:s,c:i,d:n}=this.ctx.getTransform();let r,a;if(s===0&&i===0){const o=Math.abs(e),l=Math.abs(n);if(o===l)if(t===0)r=a=1/o;else{const c=o*t;r=a=c<1?1/c:1}else if(t===0)r=1/o,a=1/l;else{const c=o*t,h=l*t;r=c<1?1/c:1,a=h<1?1/h:1}}else{const o=Math.abs(e*n-s*i),l=Math.hypot(e,s),c=Math.hypot(i,n);if(t===0)r=c/o,a=l/o;else{const h=t*o;r=c>h?c/h:1,a=l>h?l/h:1}}this._cachedScaleForStroking[0]=r,this._cachedScaleForStroking[1]=a}return this._cachedScaleForStroking}rescaleAndStroke(t,e){const{ctx:s,current:{lineWidth:i}}=this,[n,r]=this.getScaleForStroking();if(n===r){s.lineWidth=(i||1)*n,s.stroke(t);return}const a=s.getLineDash();e&&s.save(),s.scale(n,r),bi.a=1/n,bi.d=1/r;const o=new Path2D;if(o.addPath(t,bi),a.length>0){const l=Math.max(n,r);s.setLineDash(a.map(c=>c/l)),s.lineDashOffset/=l}s.lineWidth=i||1,s.stroke(o),e&&s.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}}for(const d in Xt)Oe.prototype[d]!==void 0&&(Oe.prototype[Xt[d]]=Oe.prototype[d]);class Xs{#t=null;#e=null;_fullReader=null;_rangeReaders=new Set;_source=null;constructor(t,e,s){this._source=t,this.#t=e,this.#e=s}get _progressiveDataLength(){return this._fullReader?._loaded??0}getFullReader(){return ct(!this._fullReader,"BasePDFStream.getFullReader can only be called once."),this._fullReader=new this.#t(this)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new this.#e(this,t,e);return this._rangeReaders.add(s),s}cancelAllRequests(t){this._fullReader?.cancel(t);for(const e of new Set(this._rangeReaders))e.cancel(t)}}class Ys{onProgress=null;_contentLength=0;_filename=null;_headersCapability=Promise.withResolvers();_isRangeSupported=!1;_isStreamingSupported=!1;_loaded=0;_stream=null;constructor(t){this._stream=t}_callOnProgress(){this.onProgress?.({loaded:this._loaded,total:this._contentLength})}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(){K("Abstract method `read` called")}cancel(t){K("Abstract method `cancel` called")}}class Ks{_stream=null;constructor(t,e,s){this._stream=t}async read(){K("Abstract method `read` called")}cancel(t){K("Abstract method `cancel` called")}}function Xl(d){let t=!0,e=s("filename\\*","i").exec(d);if(e){e=e[1];let c=a(e);return c=unescape(c),c=o(c),c=l(c),n(c)}if(e=r(d),e){const c=l(e);return n(c)}if(e=s("filename","i").exec(d),e){e=e[1];let c=a(e);return c=l(c),n(c)}function s(c,h){return new RegExp("(?:^|;)\\s*"+c+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',h)}function i(c,h){if(c){if(!/^[\x00-\xFF]+$/.test(h))return h;try{const u=new TextDecoder(c,{fatal:!0}),f=$s(h);h=u.decode(f),t=!1}catch{}}return h}function n(c){return t&&/[\x80-\xff]/.test(c)&&(c=i("utf-8",c),t&&(c=i("iso-8859-1",c))),c}function r(c){const h=[];let u;const f=s("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;(u=f.exec(c))!==null;){let[,g,m,b]=u;if(g=parseInt(g,10),g in h){if(g===0)break;continue}h[g]=[m,b]}const p=[];for(let g=0;g<h.length&&g in h;++g){let[m,b]=h[g];b=a(b),m&&(b=unescape(b),g===0&&(b=o(b))),p.push(b)}return p.join("")}function a(c){if(c.startsWith('"')){const h=c.slice(1).split('\\"');for(let u=0;u<h.length;++u){const f=h[u].indexOf('"');f!==-1&&(h[u]=h[u].slice(0,f),h.length=u+1),h[u]=h[u].replaceAll(/\\(.)/g,"$1")}c=h.join('"')}return c}function o(c){const h=c.indexOf("'");if(h===-1)return c;const u=c.slice(0,h),p=c.slice(h+1).replace(/^[^']*'/,"");return i(u,p)}function l(c){return!c.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(c)?c:c.replaceAll(/=\?([\w-]*)\?([QB])\?((?:[^?]|\?(?!=))*)\?=/gi,function(h,u,f,p){if(f==="q"||f==="Q")return p=p.replaceAll("_"," "),p=p.replaceAll(/=([0-9a-f]{2})/gi,function(g,m){return String.fromCharCode(parseInt(m,16))}),i(u,p);try{p=atob(p)}catch{}return i(u,p)})}return""}function Ir(d,t){const e=new Headers;if(!d||!t||typeof t!="object")return e;for(const s in t){const i=t[s];i!==void 0&&e.append(s,i)}return e}function qs(d){return URL.parse(d)?.origin??null}function Dr({responseHeaders:d,isHttp:t,rangeChunkSize:e,disableRange:s}){const i={contentLength:0,isRangeSupported:!1},n=parseInt(d.get("Content-Length"),10);return!Number.isInteger(n)||(i.contentLength=n,n<=2*e)||s||!t||d.get("Accept-Ranges")!=="bytes"||(d.get("Content-Encoding")||"identity")==="identity"&&(i.isRangeSupported=!0),i}function Nr(d){const t=d.get("Content-Disposition");if(t){let e=Xl(t);if(e.includes("%"))try{e=decodeURIComponent(e)}catch{}if($i(e))return e}return null}function Qs(d,t){return new Ls(`Unexpected server response (${d}) while retrieving PDF "${t.href}".`,d,d===404||d===0&&t.protocol==="file:")}function Fr(d,t){if(d!==t)throw new Error(`Expected range response-origin "${d}" to match "${t}".`)}function Lr(d,t,e,s){return fetch(d,{method:"GET",headers:t,signal:s.signal,mode:"cors",credentials:e?"include":"same-origin",redirect:"follow"})}function Rr(d,t){if(d!==200&&d!==206)throw Qs(d,t)}function Js(d){if(d instanceof Uint8Array)return d.buffer;if(d instanceof ArrayBuffer)return d;throw new Error(`getArrayBuffer - unexpected data: ${d}`)}class Yl extends Xs{_responseOrigin=null;constructor(t){super(t,Kl,ql);const{httpHeaders:e,url:s}=t;ct(/https?:/.test(s.protocol),"PDFFetchStream only supports http(s):// URLs."),this.headers=Ir(!0,e)}}class Kl extends Ys{_abortController=new AbortController;_reader=null;constructor(t){super(t);const{disableRange:e,disableStream:s,rangeChunkSize:i,url:n,withCredentials:r}=t._source;this._isStreamingSupported=!s;const a=new Headers(t.headers);Lr(n,a,r,this._abortController).then(o=>{t._responseOrigin=qs(o.url),Rr(o.status,n),this._reader=o.body.getReader();const l=o.headers,{contentLength:c,isRangeSupported:h}=Dr({responseHeaders:l,isHttp:!0,rangeChunkSize:i,disableRange:e});this._contentLength=c,this._isRangeSupported=h,this._filename=Nr(l),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new re("Streaming is disabled.")),this._headersCapability.resolve()}).catch(this._headersCapability.reject)}async read(){await this._headersCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,this._callOnProgress(),{value:Js(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}class ql extends Ks{_abortController=new AbortController;_readCapability=Promise.withResolvers();_reader=null;constructor(t,e,s){super(t,e,s);const{url:i,withCredentials:n}=t._source,r=new Headers(t.headers);r.append("Range",`bytes=${e}-${s-1}`),Lr(i,r,n,this._abortController).then(a=>{const o=qs(a.url);Fr(o,t._responseOrigin),Rr(a.status,i),this._reader=a.body.getReader(),this._readCapability.resolve()}).catch(this._readCapability.reject)}async read(){await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:{value:Js(t),done:!1}}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}function sr(d){return d instanceof Uint8Array&&d.byteLength===d.buffer.byteLength?d.buffer:new Uint8Array(d).buffer}function Zs(){for(const d of this._requests)d.resolve({value:void 0,done:!0});this._requests.length=0}class Ql extends Xs{_progressiveDone=!1;_queuedChunks=[];constructor(t){super(t,Jl,Zl);const{pdfDataRangeTransport:e}=t,{initialData:s,progressiveDone:i}=e;if(s?.length>0){const r=sr(s);this._queuedChunks.push(r)}this._progressiveDone=i;const n=r=>{switch(r.type){case"range":case"progressiveRead":this.#t(r.begin,r.chunk);break;case"progressiveDone":this._fullReader?.progressiveDone(),this._progressiveDone=!0;break}};e.transportReady(n)}#t(t,e){const s=sr(e);if(t===void 0)this._fullReader?this._fullReader._enqueue(s):this._queuedChunks.push(s);else{const i=this._rangeReaders.keys().find(n=>n._begin===t);ct(i,"#onReceiveData - no `PDFDataTransportStreamRangeReader` instance found."),i._enqueue(s)}}getFullReader(){const t=super.getFullReader();return this._queuedChunks=null,t}getRangeReader(t,e){const s=super.getRangeReader(t,e);return s&&(s.onDone=()=>this._rangeReaders.delete(s),this._source.pdfDataRangeTransport.requestDataRange(t,e)),s}cancelAllRequests(t){super.cancelAllRequests(t),this._source.pdfDataRangeTransport.abort()}}class Jl extends Ys{#t=Zs.bind(this);_done=!1;_queuedChunks=null;_requests=[];constructor(t){super(t);const{pdfDataRangeTransport:e,disableRange:s,disableStream:i}=t._source,{length:n,contentDispositionFilename:r}=e;this._queuedChunks=t._queuedChunks||[];for(const o of this._queuedChunks)this._loaded+=o.byteLength;this._done=t._progressiveDone,this._contentLength=n,this._isStreamingSupported=!i,this._isRangeSupported=!s,$i(r)&&(this._filename=r),this._headersCapability.resolve();const a=this._loaded;Promise.resolve().then(()=>{a>0&&this._loaded===a&&this._callOnProgress()})}_enqueue(t){this._done||(this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._queuedChunks.push(t),this._loaded+=t.byteLength,this._callOnProgress())}async read(){if(this._queuedChunks.length>0)return{value:this._queuedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this.#t()}progressiveDone(){this._done||=!0,this._queuedChunks.length===0&&this.#t()}}class Zl extends Ks{#t=Zs.bind(this);onDone=null;_begin=-1;_done=!1;_queuedChunk=null;_requests=[];constructor(t,e,s){super(t,e,s),this._begin=e}_enqueue(t){this._done||(this._requests.length===0?this._queuedChunk=t:(this._requests.shift().resolve({value:t,done:!1}),this.#t()),this._done=!0,this.onDone?.())}async read(){if(this._queuedChunk){const e=this._queuedChunk;return this._queuedChunk=null,{value:e,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this.#t(),this.onDone?.()}}const yi=200,ir=206;function tc(d){return typeof d!="string"?d:$s(d).buffer}class ec extends Xs{#t=new WeakMap;_responseOrigin=null;constructor(t){super(t,sc,ic);const{httpHeaders:e,url:s}=t;this.url=s,this.isHttp=/https?:/.test(s.protocol),this.headers=Ir(this.isHttp,e)}_request(t){const e=new XMLHttpRequest,s={validateStatus:null,onHeadersReceived:t.onHeadersReceived,onDone:t.onDone,onError:t.onError,onProgress:t.onProgress};this.#t.set(e,s),e.open("GET",this.url),e.withCredentials=this._source.withCredentials;for(const[i,n]of this.headers)e.setRequestHeader(i,n);return this.isHttp&&"begin"in t&&"end"in t?(e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`),s.validateStatus=i=>i===ir||i===yi):s.validateStatus=i=>i===yi,e.responseType="arraybuffer",ct(t.onError,"Expected `onError` callback to be provided."),e.onerror=()=>t.onError(e.status),e.onreadystatechange=this.#s.bind(this,e),e.onprogress=this.#e.bind(this,e),e.send(null),e}#e(t,e){this.#t.get(t)?.onProgress?.(e)}#s(t,e){const s=this.#t.get(t);if(!s||(t.readyState>=2&&s.onHeadersReceived&&(s.onHeadersReceived(),delete s.onHeadersReceived),t.readyState!==4)||!this.#t.has(t))return;if(this.#t.delete(t),t.status===0&&this.isHttp){s.onError(t.status);return}const i=t.status||yi;if(!s.validateStatus(i)){s.onError(t.status);return}const n=tc(t.response);if(i===ir){const r=t.getResponseHeader("Content-Range");/bytes \d+-\d+\/\d+/.test(r)?s.onDone(n):(V('Missing or invalid "Content-Range" header.'),s.onError(0))}else n?s.onDone(n):s.onError(t.status)}_abortRequest(t){this.#t.has(t)&&(this.#t.delete(t),t.abort())}getRangeReader(t,e){const s=super.getRangeReader(t,e);return s&&(s.onClosed=()=>this._rangeReaders.delete(s)),s}}class sc extends Ys{#t=Zs.bind(this);_cachedChunks=[];_done=!1;_requests=[];_storedError=null;constructor(t){super(t),this._fullRequestXhr=t._request({onHeadersReceived:this.#e.bind(this),onDone:this.#s.bind(this),onError:this.#i.bind(this),onProgress:this.#n.bind(this)})}#e(){const t=this._stream,{disableRange:e,rangeChunkSize:s}=t._source,i=this._fullRequestXhr;t._responseOrigin=qs(i.responseURL);const n=i.getAllResponseHeaders(),r=new Headers(n?n.trimStart().replace(/[^\S ]+$/,"").split(/[\r\n]+/).map(l=>{const[c,...h]=l.split(": ");return[c,h.join(": ")]}):[]),{contentLength:a,isRangeSupported:o}=Dr({responseHeaders:r,isHttp:t.isHttp,rangeChunkSize:s,disableRange:e});this._contentLength=a,this._isRangeSupported=o,this._filename=Nr(r),this._isRangeSupported&&t._abortRequest(i),this._headersCapability.resolve()}#s(t){this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._cachedChunks.push(t),this._done=!0,this._cachedChunks.length===0&&this.#t()}#i(t){this._storedError=Qs(t,this._stream.url),this._headersCapability.reject(this._storedError);for(const e of this._requests)e.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}#n(t){this.onProgress?.({loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})}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};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this._headersCapability.reject(t),this.#t(),this._stream._abortRequest(this._fullRequestXhr),this._fullRequestXhr=null}}class ic extends Ks{#t=Zs.bind(this);onClosed=null;_done=!1;_queuedChunk=null;_requests=[];_storedError=null;constructor(t,e,s){super(t,e,s),this._requestXhr=t._request({begin:e,end:s,onHeadersReceived:this.#e.bind(this),onDone:this.#s.bind(this),onError:this.#i.bind(this),onProgress:null})}#e(){const t=qs(this._requestXhr?.responseURL);try{Fr(t,this._stream._responseOrigin)}catch(e){this._storedError=e,this.#i(0)}}#s(t){this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._queuedChunk=t,this._done=!0,this.#t(),this.onClosed?.()}#i(t){this._storedError??=Qs(t,this._stream.url);for(const e of this._requests)e.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}async read(){if(this._storedError)throw this._storedError;if(this._queuedChunk!==null){const e=this._queuedChunk;return this._queuedChunk=null,{value:e,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this.#t(),this._stream._abortRequest(this._requestXhr),this.onClosed?.()}}function Or(d,t=null){const e=process.getBuiltinModule("fs"),{Readable:s}=process.getBuiltinModule("stream"),i=e.createReadStream(d,t);return s.toWeb(i)}class nc extends Xs{constructor(t){super(t,rc,ac);const{url:e}=t;ct(e.protocol==="file:","PDFNodeStream only supports file:// URLs.")}}class rc extends Ys{_reader=null;constructor(t){super(t);const{disableRange:e,disableStream:s,rangeChunkSize:i,url:n}=t._source;this._isStreamingSupported=!s,process.getBuiltinModule("fs/promises").lstat(n).then(a=>{const o=Or(n);this._reader=o.getReader();const{size:l}=a;this._contentLength=l,this._isRangeSupported=!e&&l>2*i,!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new re("Streaming is disabled.")),this._headersCapability.resolve()}).catch(a=>{a.code==="ENOENT"&&(a=Qs(0,n)),this._headersCapability.reject(a)})}async read(){await this._headersCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,this._callOnProgress(),{value:Js(t),done:!1})}cancel(t){this._reader?.cancel(t)}}class ac extends Ks{_readCapability=Promise.withResolvers();_reader=null;constructor(t,e,s){super(t,e,s);const{url:i}=t._source;try{const n=Or(i,{start:e,end:s-1});this._reader=n.getReader(),this._readCapability.resolve()}catch(n){this._readCapability.reject(n)}}async read(){await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:{value:Js(t),done:!1}}cancel(t){this._reader?.cancel(t)}}function oc(d){return Qe(d)?Yl:Pt?nc:ec}class Be{static#t=null;static#e="";static get workerPort(){return this.#t}static set workerPort(t){if(!(typeof Worker<"u"&&t instanceof Worker)&&t!==null)throw new Error("Invalid `workerPort` type.");this.#t=t}static get workerSrc(){return this.#e}static set workerSrc(t){if(typeof t!="string")throw new Error("Invalid `workerSrc` type.");this.#e=t}}class lc{#t;#e;constructor({parsedData:t,rawData:e}){this.#t=t,this.#e=e}getRaw(){return this.#e}get(t){return this.#t.get(t)??null}[Symbol.iterator](){return this.#t.entries()}}const pe=Symbol("INTERNAL");class cc{#t=!1;#e=!1;#s=!1;#i=!0;constructor(t,{name:e,intent:s,usage:i,rbGroups:n}){this.#t=!!(t&Tt.DISPLAY),this.#e=!!(t&Tt.PRINT),this.name=e,this.intent=s,this.usage=i,this.rbGroups=n}get visible(){if(this.#s)return this.#i;if(!this.#i)return!1;const{print:t,view:e}=this.usage;return this.#t?e?.viewState!=="OFF":this.#e?t?.printState!=="OFF":!0}_setVisible(t,e,s=!1){t!==pe&&K("Internal method `_setVisible` called."),this.#s=s,this.#i=e}get serializable(){return{userSet:this.#s,visible:this.#i}}}class Yi{#t=null;#e=new Map;#s=null;#i=null;#n;creator=null;name=null;constructor(t,e=Tt.DISPLAY,s=null){if(this.#n=t,this.renderingIntent=e,t!==null){this.name=t.name,this.creator=t.creator,this.#i=t.order;for(const i of t.groups)this.#e.set(i.id,new cc(e,i));if(s){s.size!==this.#e.size&&K("Incorrect serialized groupState.");for(const[i,n]of s)this.#e.get(i)._setVisible(pe,n.visible,n.userSet)}else{if(t.baseState==="OFF")for(const i of this.#e.values())i._setVisible(pe,!1);for(const i of t.on)this.#e.get(i)._setVisible(pe,!0);for(const i of t.off)this.#e.get(i)._setVisible(pe,!1)}this.#s=this.getHash()}}#a(t){const e=t.length;if(e<2)return!0;const s=t[0];for(let i=1;i<e;i++){const n=t[i];let r;if(Array.isArray(n))r=this.#a(n);else if(this.#e.has(n))r=this.#e.get(n).visible;else return V(`Optional content group not found: ${n}`),!0;switch(s){case"And":if(!r)return!1;break;case"Or":if(r)return!0;break;case"Not":return!r;default:return!0}}return s==="And"}isVisible(t){if(this.#e.size===0)return!0;if(!t)return zs("Optional content group not defined."),!0;if(t.type==="OCG")return this.#e.has(t.id)?this.#e.get(t.id).visible:(V(`Optional content group not found: ${t.id}`),!0);if(t.type==="OCMD"){if(t.expression)return this.#a(t.expression);if(!t.policy||t.policy==="AnyOn"){for(const e of t.ids){if(!this.#e.has(e))return V(`Optional content group not found: ${e}`),!0;if(this.#e.get(e).visible)return!0}return!1}else if(t.policy==="AllOn"){for(const e of t.ids){if(!this.#e.has(e))return V(`Optional content group not found: ${e}`),!0;if(!this.#e.get(e).visible)return!1}return!0}else if(t.policy==="AnyOff"){for(const e of t.ids){if(!this.#e.has(e))return V(`Optional content group not found: ${e}`),!0;if(!this.#e.get(e).visible)return!0}return!1}else if(t.policy==="AllOff"){for(const e of t.ids){if(!this.#e.has(e))return V(`Optional content group not found: ${e}`),!0;if(this.#e.get(e).visible)return!1}return!0}return V(`Unknown optional content policy ${t.policy}.`),!0}return V(`Unknown group type ${t.type}.`),!0}setVisibility(t,e=!0,s=!0){const i=this.#e.get(t);if(!i){V(`Optional content group not found: ${t}`);return}if(s&&e&&i.rbGroups.length)for(const n of i.rbGroups)for(const r of n)r!==t&&this.#e.get(r)?._setVisible(pe,!1,!0);i._setVisible(pe,!!e,!0),this.#t=null}setOCGState({state:t,preserveRB:e}){let s;for(const i of t){switch(i){case"ON":case"OFF":case"Toggle":s=i;continue}const n=this.#e.get(i);if(n)switch(s){case"ON":this.setVisibility(i,!0,e);break;case"OFF":this.setVisibility(i,!1,e);break;case"Toggle":this.setVisibility(i,!n.visible,e);break}}this.#t=null}get hasInitialVisibility(){return this.#s===null||this.getHash()===this.#s}getOrder(){return this.#e.size?this.#i?this.#i.slice():[...this.#e.keys()]:null}getGroup(t){return this.#e.get(t)||null}getHash(){if(this.#t!==null)return this.#t;const t=new Mi;for(const[e,s]of this.#e)t.update(`${e}:${s.visible}`);return this.#t=t.hexdigest()}[Symbol.iterator](){return this.#e.entries()}get serializable(){const t=new Map;for(const[e,s]of this.#e)t.set(e,s.serializable);return{data:this.#n,renderingIntent:this.renderingIntent,groupState:t}}static fromSerializable({data:t,renderingIntent:e,groupState:s}){return new Yi(t,e,s)}}class hc{#t=null;#e=null;#s=0;#i=null;#n=null;get pagesNumber(){return this.#s}set pagesNumber(t){this.#s!==t&&(this.#s=t,this.#t=null,this.#e=null)}#a(){if(this.#t)return;const t=this.#s,e=this.#t=new Uint32Array(t);for(let s=0;s<t;s++)e[s]=s+1;this.#e=new Int32Array(e)}#r(){const t=new Map,e=this.#t;for(let s=0,i=this.#s;s<i;s++){const n=e[s],r=t.get(n);r?r.push(s+1):t.set(n,[s+1])}return t}movePages(t,e,s){this.#a();const i=this.#t,n=this.#r(),r=e.length,a=new Uint32Array(r);let o=0;for(let u=0;u<r;u++){const f=e[u]-1;a[u]=i[f],f<s&&o++}const l=this.#s,c=l-r,h=nt(s-o,0,c);for(let u=0,f=0;u<l;u++)t.has(u+1)||(i[f++]=i[u]);i.copyWithin(h+r,h,c),i.set(a,h),this.#o(n),i.every((u,f)=>u===f+1)&&(this.#t=null)}deletePages(t){this.#a();const e=this.#t,s=this.#r();this.#n={pageNumberToId:e.slice(),pagesNumber:this.#s,prevPageNumbers:this.#e.slice()};const i=this.#s-t.length;this.#s=i;const n=this.#t=new Uint32Array(i);this.#e=new Int32Array(i);let r=0,a=0;for(const o of t){const l=o-1;l!==r&&(n.set(e.subarray(r,l),a),a+=l-r),r=l+1}r<e.length&&n.set(e.subarray(r),a),this.#o(s,new Set(t))}cancelDelete(){this.#n&&(this.#t=this.#n.pageNumberToId,this.#s=this.#n.pagesNumber,this.#e=this.#n.prevPageNumbers,this.#n=null)}cleanSavedData(){this.#n=null}copyPages(t){this.#a(),this.#i={pageNumbers:t,pageIds:t.map(e=>this.#t[e-1])}}cancelCopy(){this.#i=null}pastePages(t){this.#a();const e=this.#t,s=this.#r(),{pageNumbers:i,pageIds:n}=this.#i,r=this.#s+i.length;this.#s=r;const a=this.#t=new Uint32Array(r);this.#e=new Int32Array(r),a.set(e.subarray(0,t),0),a.set(n,t),a.set(e.subarray(t),t+i.length),this.#o(s,null,t,i),this.#i=null}#o(t,e=null,s=-1,i=null){const n=this.#e,r=this.#t,a=s+(i?.length??0),o=new Map;for(let l=0,c=this.#s;l<c;l++){if(l>=s&&l<a){n[l]=-i[l-s];continue}const h=r[l],u=t.get(h);let f=o.get(h)||0;if(e&&u)for(;f<u.length&&e.has(u[f]);)f++;n[l]=u?.[f],o.set(h,f+1)}}hasBeenAltered(){return this.#t!==null}getPageMappingForSaving(t=null){t??=this.#r();let e=0;for(const i of t.values())e=Math.max(e,i.length);const s=new Array(e);for(let i=0;i<e;i++)s[i]={document:null,pageIndices:[],includePages:[]};for(const[i,n]of t)for(let r=0,a=n.length;r<a;r++)s[r].includePages.push([i-1,n[r]-1]);for(const{includePages:i,pageIndices:n}of s){i.sort((r,a)=>r[0]-a[0]);for(let r=0,a=i.length;r<a;r++)n.push(i[r][1]),i[r]=i[r][0]}return s}extractPages(t){t=Array.from(t).sort((s,i)=>s-i);const e=new Map;for(let s=0,i=t.length;s<i;s++){const n=this.getPageId(t[s]);e.getOrInsertComputed(n,ls).push(s+1)}return this.getPageMappingForSaving(e)}getPrevPageNumber(t){return this.#e?.[t-1]??0}getPageNumber(t){if(!this.#t)return t;const e=this.#t;for(let s=0,i=this.#s;s<i;s++)if(e[s]===t)return s+1;return 0}getPageId(t){return this.#t?.[t-1]??t}getMapping(){return this.#t?.subarray(0,this.pagesNumber)}}const De=Symbol("INITIAL_DATA"),nr=()=>({...Promise.withResolvers(),data:De});class Br{#t=new Map;get(t,e=null){if(e){const i=this.#t.getOrInsertComputed(t,nr);return i.promise.then(()=>e(i.data)),null}const s=this.#t.get(t);if(!s||s.data===De)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return s.data}has(t){const e=this.#t.get(t);return!!e&&e.data!==De}delete(t){const e=this.#t.get(t);return!e||e.data===De?!1:(this.#t.delete(t),!0)}resolve(t,e=null){const s=this.#t.getOrInsertComputed(t,nr);if(s.data!==De)throw new Error(`Object already resolved ${t}.`);s.data=e,s.resolve()}clear(){for(const{data:t}of this.#t.values())t?.bitmap?.close();this.#t.clear()}*[Symbol.iterator](){for(const[t,{data:e}]of this.#t)e!==De&&(yield[t,e])}}const dc=1e5,rr=30;class Mt{#t=Promise.withResolvers();#e=null;#s=!1;#i=!!globalThis.FontInspector?.enabled;#n=null;#a=null;#r=null;#o=0;#h=0;#l=null;#u=null;#d=0;#p=0;#m=Object.create(null);#g=[];#c=null;#f=[];#y=new WeakMap;#v=null;static#b=new Map;static#S=new Map;static#C=new WeakMap;static#A=null;static#E=new Set;constructor({textContentSource:t,images:e,container:s,viewport:i}){if(t instanceof ReadableStream)this.#c=t;else if(typeof t=="object")this.#c=new ReadableStream({start(l){l.enqueue(t),l.close()}});else throw new Error('No "textContentSource" parameter specified.');this.#e=this.#u=s,this.#n=e,this.#p=i.scale*Kt.pixelRatio,this.#d=i.rotation,this.#r={div:null,properties:null,ctx:null};const{pageWidth:n,pageHeight:r,pageX:a,pageY:o}=i.rawDims;this.#v=[1,0,0,-1,-a,o+r],this.#h=n,this.#o=r,Mt.#N(),s.style.setProperty("--min-font-size",Mt.#A),xe(s,i),this.#t.promise.finally(()=>{Mt.#E.delete(this),this.#r=null,this.#m=null}).catch(()=>{})}static get fontFamilyMap(){const{isWindows:t,isFirefox:e}=J.platform;return z(this,"fontFamilyMap",new Map([["sans-serif",`${t&&e?"Calibri, ":""}sans-serif`],["monospace",`${t&&e?"Lucida Console, ":""}monospace`]]))}render(){this.#n&&this.#e.append(this.#n.render());const t=()=>{this.#l.read().then(({value:e,done:s})=>{if(s){this.#t.resolve();return}this.#a??=e.lang,Object.assign(this.#m,e.styles),this.#w(e.items),t()},this.#t.reject)};return this.#l=this.#c.getReader(),Mt.#E.add(this),t(),this.#t.promise}update({viewport:t,onBefore:e=null}){const s=t.scale*Kt.pixelRatio,i=t.rotation;if(i!==this.#d&&(e?.(),this.#d=i,xe(this.#u,{rotation:i})),s!==this.#p){e?.(),this.#p=s;const n={div:null,properties:null,ctx:Mt.#P(this.#a)};for(const r of this.#f)n.properties=this.#y.get(r),n.div=r,this.#M(n)}}cancel(){const t=new re("TextLayer task cancelled.");this.#l?.cancel(t).catch(()=>{}),this.#l=null,this.#t.reject(t)}get textDivs(){return this.#f}get textContentItemsStr(){return this.#g}#w(t){if(this.#s)return;this.#r.ctx??=Mt.#P(this.#a);const e=this.#f,s=this.#g;for(const i of t){if(e.length>dc){V("Ignoring additional textDivs for performance reasons."),this.#s=!0;return}if(i.str===void 0){if(i.type==="beginMarkedContentProps"||i.type==="beginMarkedContent"){const n=this.#e;this.#e=document.createElement("span"),this.#e.classList.add("markedContent"),i.id&&this.#e.setAttribute("id",`${i.id}`),i.tag==="Artifact"&&(this.#e.ariaHidden=!0),n.append(this.#e)}else i.type==="endMarkedContent"&&(this.#e=this.#e.parentNode);continue}s.push(i.str),this.#k(i)}}#k(t){const e=document.createElement("span"),s={angle:0,canvasWidth:0,hasText:t.str!=="",hasEOL:t.hasEOL,fontSize:0};this.#f.push(e);const i=T.transform(this.#v,t.transform);let n=Math.atan2(i[1],i[0]);const r=this.#m[t.fontName];r.vertical&&(n+=Math.PI/2);let a=this.#i&&r.fontSubstitution||r.fontFamily;a=Mt.fontFamilyMap.get(a)||a;const o=Math.hypot(i[2],i[3]),l=o*Mt.#F(a,r,this.#a);let c,h;n===0?(c=i[4],h=i[5]-l):(c=i[4]+l*Math.sin(n),h=i[5]-l*Math.cos(n));const u=e.style;u.left=`${(100*c/this.#h).toFixed(2)}%`,u.top=`${(100*h/this.#o).toFixed(2)}%`,u.setProperty("--font-height",`${o.toFixed(2)}px`),u.fontFamily=a,s.fontSize=o,e.setAttribute("role","presentation"),e.textContent=t.str,e.dir=t.dir,this.#i&&(e.dataset.fontName=r.fontSubstitutionLoadedName||t.fontName),n!==0&&(s.angle=n*(180/Math.PI));let f=!1;if(t.str.length>1)f=!0;else if(t.str!==" "&&t.transform[0]!==t.transform[3]){const p=Math.abs(t.transform[0]),g=Math.abs(t.transform[3]);p!==g&&Math.max(p,g)/Math.min(p,g)>1.5&&(f=!0)}if(f&&(s.canvasWidth=r.vertical?t.height:t.width),this.#y.set(e,s),this.#r.div=e,this.#r.properties=s,this.#M(this.#r),s.hasText&&this.#e.append(e),s.hasEOL){const p=document.createElement("br");p.setAttribute("role","presentation"),this.#e.append(p)}}#M(t){const{div:e,properties:s,ctx:i}=t,{style:n}=e;if(s.canvasWidth!==0&&s.hasText){const{fontFamily:r}=n,{canvasWidth:a,fontSize:o}=s;Mt.#T(i,o*this.#p,r);const{width:l}=i.measureText(e.textContent);l>0&&n.setProperty("--scale-x",a*this.#p/l)}s.angle!==0&&n.setProperty("--rotate",`${s.angle}deg`)}static cleanup(){if(!(this.#E.size>0)){this.#b.clear();for(const{canvas:t}of this.#S.values())t.remove();this.#S.clear()}}static#P(t=null){let e=this.#S.get(t||="");if(!e){const s=document.createElement("canvas");s.style.cssText="position:absolute;top:0;left:0;width:0;height:0;display:none;letter-spacing:normal;word-spacing:normal",s.lang=t,document.body.append(s),e=s.getContext("2d",{alpha:!1,willReadFrequently:!0}),this.#S.set(t,e),this.#C.set(e,{size:0,family:""})}return e}static#T(t,e,s){const i=this.#C.get(t);e===i.size&&s===i.family||(t.font=`${e}px ${s}`,i.size=e,i.family=s)}static#N(){if(this.#A!==null)return;const t=document.createElement("div");t.style.opacity=0,t.style.lineHeight=1,t.style.fontSize="1px",t.style.position="absolute",t.textContent="X",document.body.append(t),this.#A=t.getBoundingClientRect().height,t.remove()}static#F(t,e,s){const i=this.#b.get(t);if(i)return i;const n=this.#P(s);n.canvas.width=n.canvas.height=rr,this.#T(n,rr,t);const r=n.measureText(""),a=r.fontBoundingBoxAscent,o=Math.abs(r.fontBoundingBoxDescent);n.canvas.width=n.canvas.height=0;let l=.8;return a?l=a/(a+o):(J.platform.isFirefox&&V("Enable the `dom.textMetrics.fontBoundingBox.enabled` preference in `about:config` to improve TextLayer rendering."),e.ascent?l=e.ascent:e.descent&&(l=1+e.descent)),this.#b.set(t,l),l}}const uc=100;function jr(d={}){const t=new Ki,{docId:e}=t,s=d.url?yl(d.url):null,i=d.data?vl(d.data):null,n=d.httpHeaders||null,r=d.withCredentials===!0,a=d.password??null,o=d.range instanceof Hr?d.range:null,l=Number.isInteger(d.rangeChunkSize)&&d.rangeChunkSize>0?d.rangeChunkSize:2**16;let c=d.worker instanceof ns?d.worker:null;const h=d.verbosity,u=typeof d.docBaseUrl=="string"&&!Gs(d.docBaseUrl)?d.docBaseUrl:null,f=ws(d.cMapUrl),p=d.cMapPacked!==!1,g=ws(d.iccUrl),m=ws(d.standardFontDataUrl),b=ws(d.wasmUrl),y=d.stopAtErrors!==!0,A=Number.isInteger(d.maxImageSize)&&d.maxImageSize>-1?d.maxImageSize:-1,w=typeof d.isOffscreenCanvasSupported=="boolean"?d.isOffscreenCanvasSupported:!Pt,x=typeof d.isImageDecoderSupported=="boolean"?d.isImageDecoderSupported:!Pt,S=Number.isInteger(d.canvasMaxAreaInBytes)?d.canvasMaxAreaInBytes:-1,E=typeof d.disableFontFace=="boolean"?d.disableFontFace:Pt,_=d.fontExtraProperties===!0,k=d.enableXfa===!0,I=d.ownerDocument||globalThis.document,P=d.disableRange===!0,B=d.disableStream===!0,W=d.disableAutoFetch===!0,Y=d.pdfBug===!0,Z=d.CanvasFactory||(Pt?kl:Sl),L=d.FilterFactory||(Pt?_l:Cl),F=d.BinaryDataFactory||(Pt?Tl:Xn),rt=d.enableHWA===!0,vt=d.enableWebGPU===!0?Dl():Promise.resolve(!1),Ot=d.useWasm!==!1,M=d.pagesMapper||new hc,j=typeof d.useSystemFonts=="boolean"?d.useSystemFonts:!Pt&&!E,dt=typeof d.useWorkerFetch=="boolean"?d.useWorkerFetch:!!(F===Xn&&f&&p&&m&&b&&Qe(f,document.baseURI)&&Qe(m,document.baseURI)&&Qe(b,document.baseURI)),Bt=null;jo(h);const _t={canvasFactory:new Z({ownerDocument:I,enableHWA:rt}),filterFactory:new L({docId:e,ownerDocument:I}),binaryDataFactory:dt?null:new F({cMapUrl:f,standardFontDataUrl:m,wasmUrl:b})};c||(c=ns.create({verbosity:h,port:Be.workerPort}),t._worker=c);const tt={docId:e,apiVersion:"6.1.200",data:i,password:a,disableAutoFetch:W,rangeChunkSize:l,docBaseUrl:u,enableXfa:k,evaluatorOptions:{maxImageSize:A,disableFontFace:E,ignoreErrors:y,isOffscreenCanvasSupported:w,isImageDecoderSupported:x,canvasMaxAreaInBytes:S,fontExtraProperties:_,useSystemFonts:j,useWasm:Ot,useWorkerFetch:dt,cMapUrl:f,cMapPacked:p,iccUrl:g,standardFontDataUrl:m,wasmUrl:b,hasGPU:!1}},Ue={ownerDocument:I,pdfBug:Y,styleElement:Bt,enableHWA:rt,loadingParams:{disableAutoFetch:W,enableXfa:k}};return Promise.all([c.promise,vt]).then(function([,qt]){if(c.destroyed)throw new Error("Worker was destroyed");tt.evaluatorOptions.hasGPU=qt;const le=c.messageHandler.sendWithPromise("GetDocRequest",tt,i?[i.buffer]:null);let ce;if(!i)if(o)ce=new Ql({pdfDataRangeTransport:o,disableRange:P,disableStream:B});else if(s){const Qt=oc(s);ce=new Qt({url:s,httpHeaders:n,withCredentials:r,rangeChunkSize:l,disableRange:P,disableStream:B})}else throw new Error("getDocument - expected either `data`, `range`, or `url` parameter.");return le.then(Qt=>{if(c.destroyed)throw new Error("Worker was destroyed");const ps=new Ke(e,Qt,c.port),gs=new pc(ps,t,ce,Ue,_t,M);if(t._transport=gs,t.destroyed)throw new Error("Loading aborted");ps.send("Ready",null)})}).catch(t._capability.reject).finally(t._setupCapability.resolve),t}class Ki{static#t=0;_capability=Promise.withResolvers();_setupCapability=Promise.withResolvers();_transport=null;_worker=null;docId=`d${Ki.#t++}`;destroyed=!1;onPassword=null;onProgress=null;get promise(){return this._capability.promise}async destroy(){this.destroyed=!0,this._capability.promise.catch(()=>{});try{this._worker?.port&&(this._worker._pendingDestroy=!0),await this._setupCapability.promise,await this._transport?.destroy()}catch(t){throw this._worker?.port&&delete this._worker._pendingDestroy,t}this._transport=null,this._worker?.destroy(),this._worker=null}async getData(){return this._transport.getData()}}class Hr{#t=Promise.withResolvers();#e=null;constructor(t,e,s=!1,i=null){this.length=t,this.initialData=e,this.progressiveDone=s,this.contentDispositionFilename=i}onDataRange(t,e){this.#e({type:"range",begin:t,chunk:e})}onDataProgressiveRead(t){this.#t.promise.then(()=>{this.#e({type:"progressiveRead",chunk:t})})}onDataProgressiveDone(){this.#t.promise.then(()=>{this.#e({type:"progressiveDone"})})}transportReady(t){this.#e=t,this.#t.resolve()}requestDataRange(t,e){K("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class fc{constructor(t,e){this._pdfInfo=t,this._transport=e}get pagesMapper(){return this._transport.pagesMapper}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 z(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(t){return this._transport.getPage(t)}getPageIndex(t){return this._transport.getPageIndex(t)}getDestinations(){return this._transport.getDestinations()}getDestination(t){return this._transport.getDestination(t)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getAttachmentContent(t){return this._transport.getAttachmentContent(t)}getAnnotationsByType(t,e){return this._transport.getAnnotationsByType(t,e)}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getOptionalContentConfig(e)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}extractPages(t){return this._transport.extractPages(t)}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}getRawData(t){return this._transport.getRawData(t)}cleanup(t=!1){return this._transport.startCleanup(t||this.isPureXfa)}cachedPageNumber(t){return this._transport.cachedPageNumber(t)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}class qi{#t=!1;#e=null;constructor(t,e,s,i,n=!1){this._pageIndex=t,this._pageInfo=e,this._transport=s,this._stats=n?new Rn:null,this._pdfBug=n,this.commonObjs=s.commonObjs,this.objs=new Br,this._intentStates=new Map,this.destroyed=!1,this.recordedBBoxes=null,this.#e=i,this.imageCoordinates=null}clone(t){const e=new qi(t,this._pageInfo,this._transport,this.#e,this._pdfBug);return e.clonedFromIndex=this.clonedFromIndex??this._pageIndex,this._transport.updatePage(e),e}get pageNumber(){return this._pageIndex+1}set pageNumber(t){this._pageIndex=t-1,this._transport.updatePage(this)}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:t,rotation:e=this.rotate,offsetX:s=0,offsetY:i=0,dontFlip:n=!1}={}){return new cs({viewBox:this.view,userUnit:this.userUnit,scale:t,rotation:e,offsetX:s,offsetY:i,dontFlip:n})}getAnnotations({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getAnnotations(this._pageIndex,e)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return z(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:t,canvas:e=t.canvas,viewport:s,intent:i="display",annotationMode:n=ie.ENABLE,transform:r=null,background:a=null,optionalContentConfigPromise:o=null,annotationCanvasMap:l=null,pageColors:c=null,printAnnotationStorage:h=null,isEditing:u=!1,recordImages:f=!1,recordOperations:p=!1,operationsFilter:g=null}){this._stats?.time("Overall");const m=this._transport.getRenderingIntent(i,n,h,u),{renderingIntent:b,cacheKey:y}=m;this.#t=!1,o||=this._transport.getOptionalContentConfig(b);const A=this._intentStates.getOrInsertComputed(y,Ei);A.streamReaderCancelTimeout&&(clearTimeout(A.streamReaderCancelTimeout),A.streamReaderCancelTimeout=null);const w=!!(b&Tt.PRINT);A.displayReadyCapability||(A.displayReadyCapability=Promise.withResolvers(),A.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(m));const x=!!(this._pdfBug&&globalThis.StepperManager?.enabled),S=!!e&&!this.recordedBBoxes&&(p||x),E=!!e&&!this.imageCoordinates&&f,_=W=>{if(A.renderTasks.delete(P),S){const Y=P.gfx?.dependencyTracker.take();Y&&(P.stepper?.setOperatorBBoxes(Y,P.gfx.dependencyTracker.takeDebugMetadata()),p&&(this.recordedBBoxes=Y))}E&&!W&&(this.imageCoordinates=P.gfx?.imagesTracker.take()),w&&(this.#t=!0),this.#s(),W?(P.capability.reject(W),this._abortOperatorList({intentState:A,reason:W instanceof Error?W:new Error(W)})):P.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))};let k=null,I=null;(S||E)&&(I=new ol(e,A.operatorList.length)),S&&(k=new ll(I,x));const P=new Le({callback:_,params:{canvas:e,canvasContext:t,dependencyTracker:k??I,imagesTracker:E?new Rs(e):null,viewport:s,transform:r,background:a},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:l,operatorList:A.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!w,pdfBug:this._pdfBug,pageColors:c,enableHWA:this._transport.enableHWA,operationsFilter:g});(A.renderTasks||=new Set).add(P);const B=P.task;return Promise.all([A.displayReadyCapability.promise,o]).then(([W,Y])=>{if(this.destroyed){_();return}if(this._stats?.time("Rendering"),!(Y.renderingIntent&b))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");P.initializeGraphics({transparency:W,optionalContentConfig:Y}),P.operatorListChanged()}).catch(_),B}getOperatorList({intent:t="display",annotationMode:e=ie.ENABLE,printAnnotationStorage:s=null,isEditing:i=!1}={}){function n(){a.operatorList.lastChunk&&(a.opListReadCapability.resolve(a.operatorList),a.renderTasks.delete(o))}const r=this._transport.getRenderingIntent(t,e,s,i,!0),a=this._intentStates.getOrInsertComputed(r.cacheKey,Ei);let o;return a.opListReadCapability||(o=Object.create(null),o.operatorListChanged=n,a.opListReadCapability=Promise.withResolvers(),(a.renderTasks||=new Set).add(o),a.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(r)),a.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=!1,disableNormalization:e=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageId:this.#e.getPageId(this._pageIndex+1)-1,pageIndex:this._pageIndex,includeMarkedContent:t===!0,disableNormalization:e===!0},{highWaterMark:100,size(i){return i.items.length}})}async getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then(i=>es.textContent(i));const e=this.streamTextContent(t),s={items:[],styles:Object.create(null),lang:null};for await(const i of e)s.lang??=i.lang,Object.assign(s.styles,i.styles),s.items.push(...i.items);return s}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const t=[];for(const e of this._intentStates.values())if(this._abortOperatorList({intentState:e,reason:new Error("Page was destroyed."),force:!0}),!e.opListReadCapability)for(const s of e.renderTasks)t.push(s.completed),s.cancel();return this.objs.clear(),this.#t=!1,Promise.all(t)}cleanup(t=!1){this.#t=!0;const e=this.#s();return t&&e&&(this._stats&&=new Rn),e}#s(){if(!this.#t||this.destroyed)return!1;for(const{renderTasks:t,operatorList:e}of this._intentStates.values())if(t.size>0||!e.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),this.#t=!1,!0}_startRenderPage(t,e){const s=this._intentStates.get(e);s&&(this._stats?.timeEnd("Page Request"),s.displayReadyCapability?.resolve(t))}_renderPageChunk(t,e){for(let s=0,i=t.length;s<i;s++)e.operatorList.fnArray.push(t.fnArray[s]),e.operatorList.argsArray.push(t.argsArray[s]);e.operatorList.lastChunk=t.lastChunk,e.operatorList.separateAnnots=t.separateAnnots;for(const s of e.renderTasks)s.operatorListChanged();t.lastChunk&&this.#s()}_pumpOperatorList({renderingIntent:t,cacheKey:e,annotationStorageSerializable:s,modifiedIds:i}){const{map:n,transfer:r}=s,o=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageId:this.#e.getPageId(this._pageIndex+1)-1,pageIndex:this._pageIndex,intent:t,cacheKey:e,annotationStorage:n,modifiedIds:i},void 0,r).getReader(),l=this._intentStates.get(e);l.streamReader=o;const c=()=>{o.read().then(({value:h,done:u})=>{if(u){l.streamReader=null;return}this._transport.destroyed||(this._renderPageChunk(h,l),c())},h=>{if(l.streamReader=null,!this._transport.destroyed){if(l.operatorList){l.operatorList.lastChunk=!0;for(const u of l.renderTasks)u.operatorListChanged();this.#s()}if(l.displayReadyCapability)l.displayReadyCapability.reject(h);else if(l.opListReadCapability)l.opListReadCapability.reject(h);else throw h}})};c()}_abortOperatorList({intentState:t,reason:e,force:s=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout&&(clearTimeout(t.streamReaderCancelTimeout),t.streamReaderCancelTimeout=null),!s){if(t.renderTasks.size>0)return;if(e instanceof zi){let i=uc;e.extraDelay>0&&e.extraDelay<1e3&&(i+=e.extraDelay),t.streamReaderCancelTimeout=setTimeout(()=>{t.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:t,reason:e,force:!0})},i);return}}if(t.streamReader.cancel(new re(e.message)).catch(()=>{}),t.streamReader=null,!this._transport.destroyed){for(const[i,n]of this._intentStates)if(n===t){this._intentStates.delete(i);break}this.cleanup()}}}get stats(){return this._stats}}var ne,Ut,Zt,ye,js,ve,Ae,wt,Ds,Ur,zr,qe,je,Ns;const pt=class pt{constructor({name:t=null,port:e=null,verbosity:s=Ho()}={}){zt(this,wt);zt(this,ne,Promise.withResolvers());zt(this,Ut,null);zt(this,Zt,null);zt(this,ye,null);if(this.name=t,this.destroyed=!1,this.verbosity=s,e){if(at(pt,Ae).has(e))throw new Error("Cannot use more than one PDFWorker per port.");at(pt,Ae).set(e,this),$t(this,wt,Ur).call(this,e)}else $t(this,wt,zr).call(this)}get promise(){return at(this,ne).promise}get port(){return at(this,Zt)}get messageHandler(){return at(this,Ut)}destroy(){this.destroyed=!0,at(this,ye)?.terminate(),St(this,ye,null),at(pt,Ae).delete(at(this,Zt)),St(this,Zt,null),at(this,Ut)?.destroy(),St(this,Ut,null)}static create(t){const e=at(this,Ae).get(t?.port);if(e){if(e._pendingDestroy)throw new Error("PDFWorker.create - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return e}return new pt(t)}static get workerSrc(){if(Be.workerSrc)return Be.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get _setupFakeWorkerGlobal(){return z(this,"_setupFakeWorkerGlobal",(async()=>at(this,je,Ns)?at(this,je,Ns):(await import(this.workerSrc)).WorkerMessageHandler)())}};ne=new WeakMap,Ut=new WeakMap,Zt=new WeakMap,ye=new WeakMap,js=new WeakMap,ve=new WeakMap,Ae=new WeakMap,wt=new WeakSet,Ds=function(){at(this,ne).resolve(),at(this,Ut).send("configure",{verbosity:this.verbosity})},Ur=function(t){St(this,Zt,t),St(this,Ut,new Ke("main","worker",t)),at(this,Ut).on("ready",()=>{}),$t(this,wt,Ds).call(this)},zr=function(){if(at(pt,ve)||at(pt,je,Ns)){$t(this,wt,qe).call(this);return}let{workerSrc:t}=pt;try{pt._isSameOrigin(window.location,t)||(t=pt._createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),s=new Ke("main","worker",e),i=()=>{n.abort(),s.destroy(),e.terminate(),this.destroyed?at(this,ne).reject(new Error("Worker was destroyed")):$t(this,wt,qe).call(this)},n=new AbortController;e.addEventListener("error",()=>{at(this,ye)||i()},{signal:n.signal}),s.on("test",a=>{if(n.abort(),this.destroyed||!a){i();return}St(this,Ut,s),St(this,Zt,e),St(this,ye,e),$t(this,wt,Ds).call(this)}),s.on("ready",a=>{if(n.abort(),this.destroyed){i();return}try{r()}catch{$t(this,wt,qe).call(this)}});const r=()=>{const a=new Uint8Array;s.send("test",a,[a.buffer])};r();return}catch{zs("The worker has been disabled.")}$t(this,wt,qe).call(this)},qe=function(){at(pt,ve)||(V("Setting up fake worker."),St(pt,ve,!0)),pt._setupFakeWorkerGlobal.then(t=>{if(this.destroyed){at(this,ne).reject(new Error("Worker was destroyed"));return}const e=new wl;St(this,Zt,e);const s=`fake${wn(pt,js)._++}`,i=new Ke(s+"_worker",s,e);t.setup(i,e),St(this,Ut,new Ke(s,s+"_worker",e)),$t(this,wt,Ds).call(this)}).catch(t=>{at(this,ne).reject(new Error(`Setting up fake worker failed: "${t.message}".`))})},je=new WeakSet,Ns=function(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}},zt(pt,je),zt(pt,js,0),zt(pt,ve,!1),zt(pt,Ae,new WeakMap),Pt&&(St(pt,ve,!0),Be.workerSrc||="./pdf.worker.mjs"),pt._isSameOrigin=(t,e)=>{const s=URL.parse(t);if(!s?.origin||s.origin==="null")return!1;const i=new URL(e,s);return s.origin===i.origin},pt._createCDNWrapper=t=>{const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))};let ns=pt;class pc{downloadInfoCapability=Promise.withResolvers();#t=null;#e=new Map;#s=null;#i=new Map;#n=new Map;#a=new Map;#r=null;constructor(t,e,s,i,n,r){this.messageHandler=t,this.loadingTask=e,this.#s=s,this.commonObjs=new Br,this.fontLoader=new cl({ownerDocument:i.ownerDocument,styleElement:i.styleElement}),this.enableHWA=i.enableHWA,this.loadingParams=i.loadingParams,this._params=i,this.canvasFactory=n.canvasFactory,this.filterFactory=n.filterFactory,this.binaryDataFactory=n.binaryDataFactory,this.pagesMapper=r,this.destroyed=!1,this.destroyCapability=null,this.setupMessageHandler()}updatePage(t){const{_pageIndex:e}=t;this.#i.set(e,t),this.#n.set(e,Promise.resolve(t))}#o(t,e=null){return this.#e.getOrInsertComputed(t,()=>this.messageHandler.sendWithPromise(t,e))}#h({loaded:t,total:e}){this.loadingTask.onProgress?.({loaded:t,total:e,percent:e?nt(Math.round(t/e*100),0,100):NaN})}get annotationStorage(){return z(this,"annotationStorage",new Wi)}getRenderingIntent(t,e=ie.ENABLE,s=null,i=!1,n=!1){let r=Tt.DISPLAY,a=ss;switch(t){case"any":r=Tt.ANY;break;case"display":break;case"print":r=Tt.PRINT;break;default:V(`getRenderingIntent - invalid intent: ${t}`)}const o=r&Tt.PRINT&&s instanceof _r?s:this.annotationStorage;switch(e){case ie.DISABLE:r+=Tt.ANNOTATIONS_DISABLE;break;case ie.ENABLE:break;case ie.ENABLE_FORMS:r+=Tt.ANNOTATIONS_FORMS;break;case ie.ENABLE_STORAGE:r+=Tt.ANNOTATIONS_STORAGE,a=o.serializable;break;default:V(`getRenderingIntent - invalid annotationMode: ${e}`)}i&&(r+=Tt.IS_EDITING),n&&(r+=Tt.OPLIST);const{ids:l,hash:c}=o.modifiedIds,h=[r,a.hash,c];return{renderingIntent:r,cacheKey:h.join("_"),annotationStorageSerializable:a,modifiedIds:l}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),this.#r?.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const s of this.#i.values())t.push(s._destroy());this.#i.clear(),this.#n.clear(),this.#a.clear(),Object.hasOwn(this,"annotationStorage")&&this.annotationStorage.resetModified();const e=this.messageHandler.sendWithPromise("Terminate",null);return t.push(e),Promise.all(t).then(()=>{this.commonObjs.clear(),this.fontLoader.clear(),this.#e.clear(),this.filterFactory.destroy(),Mt.cleanup(),this.#s?.cancelAllRequests(new re("Worker was terminated.")),this.messageHandler?.destroy(),this.messageHandler=null,this.destroyCapability.resolve()},this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:t,loadingTask:e}=this;t.on("GetReader",(s,i)=>{ct(this.#s,"GetReader - no `BasePDFStream` instance available."),this.#t=this.#s.getFullReader(),this.#t.onProgress=n=>this.#h(n),i.onPull=()=>{this.#t.read().then(function({value:n,done:r}){if(r){i.close();return}ct(n instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),i.enqueue(new Uint8Array(n),1,[n])}).catch(n=>{i.error(n)})},i.onCancel=n=>{this.#t.cancel(n),i.ready.catch(r=>{if(!this.destroyed)throw r})}}),t.on("ReaderHeadersReady",async s=>{await this.#t.headersReady;const{isStreamingSupported:i,isRangeSupported:n,contentLength:r}=this.#t;return i&&n&&(this.#t.onProgress=null),{isStreamingSupported:i,isRangeSupported:n,contentLength:r}}),t.on("GetRangeReader",(s,i)=>{ct(this.#s,"GetRangeReader - no `BasePDFStream` instance available.");const n=this.#s.getRangeReader(s.begin,s.end);if(!n){i.close();return}i.onPull=()=>{n.read().then(function({value:r,done:a}){if(a){i.close();return}ct(r instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),i.enqueue(new Uint8Array(r),1,[r])}).catch(r=>{i.error(r)})},i.onCancel=r=>{n.cancel(r),i.ready.catch(a=>{if(!this.destroyed)throw a})}}),t.on("GetDoc",({pdfInfo:s})=>{this.pagesMapper.pagesNumber=s.numPages,this._numPages=s.numPages,this._htmlForXfa=s.htmlForXfa,delete s.htmlForXfa,e._capability.resolve(new fc(s,this))}),t.on("DocException",s=>{e._capability.reject(Ct(s))}),t.on("PasswordRequest",s=>{this.#r=Promise.withResolvers();try{if(!e.onPassword)throw Ct(s);const i=n=>{n instanceof Error?this.#r.reject(n):this.#r.resolve({password:n})};e.onPassword(i,s.code)}catch(i){this.#r.reject(i)}return this.#r.promise}),t.on("DataLoaded",s=>{this.#h({loaded:s.length,total:s.length}),this.downloadInfoCapability.resolve(s)}),t.on("StartRenderPage",s=>{if(this.destroyed)return;this.#i.get(s.pageIndex)._startRenderPage(s.transparency,s.cacheKey)}),t.on("commonobj",([s,i,n])=>{if(this.destroyed||this.commonObjs.has(s))return null;switch(i){case"Font":if("error"in n){const h=n.error;V(`Error during font loading: ${h}`),this.commonObjs.resolve(s,h);break}const r=new gl(n),a=this._params.pdfBug&&globalThis.FontInspector?.enabled?(h,u)=>globalThis.FontInspector.fontAdded(h,u):null,o=new hl(r,a,n.charProcOperatorList,n.extra);this.fontLoader.bind(o).catch(()=>t.sendWithPromise("FontFallback",{id:s})).finally(()=>{o.fontExtraProperties||o.clearData(),this.commonObjs.resolve(s,o)});break;case"CopyLocalImage":const{imageRef:l}=n;ct(l,"The imageRef must be defined.");for(const h of this.#i.values())for(const[,u]of h.objs){if(u?.ref!==l)continue;if(!u.dataLen)return null;const f=structuredClone(u);return this.commonObjs.resolve(s,f),u.dataLen}break;case"FontPath":this.commonObjs.resolve(s,new bl(n));break;case"Image":this.commonObjs.resolve(s,n);break;case"Pattern":const c=new ml(n);this.commonObjs.resolve(s,c.getIR());break;default:throw new Error(`Got unknown common object type ${i}`)}return null}),t.on("obj",([s,i,n,r])=>{if(this.destroyed)return;const a=this.#i.get(i);if(!a.objs.has(s)){if(a._intentStates.size===0){r?.bitmap?.close();return}switch(n){case"Image":case"Pattern":a.objs.resolve(s,r);break;default:throw new Error(`Got unknown object type ${n}`)}}}),t.on("DocProgress",s=>{this.destroyed||this.#h(s)}),t.on("FetchBinaryData",async s=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.binaryDataFactory)throw new Error("`BinaryDataFactory` not initialized, see the `useWorkerFetch` parameter.");return this.binaryDataFactory.fetch(s)})}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&V("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:t,transfer:e}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:this.#t?.filename??null},e).finally(()=>{this.annotationStorage.resetModified()})}extractPages(t){const e={pageInfos:t};let s;const i=globalThis.ImageBitmap;if(typeof i=="function"){const n=Array.isArray(t)?t:[t];for(const r of n)r?.image instanceof i&&(s||=[]).push(r.image)}if(this.annotationStorage.size>0){const n=this.annotationStorage.serializable;let{map:r}=n;n.transfer?.length&&(s?s.push(...n.transfer):s=n.transfer);const a=this.pagesMapper.getMapping();if(a){const o=new Map;for(const[l,c]of r){if(c?.pageIndex!==void 0&&c.pageIndex>=0&&c.pageIndex<a.length){const h=a[c.pageIndex]-1;if(h!==c.pageIndex){o.set(l,{...c,pageIndex:h});continue}}o.set(l,c)}r=o}e.annotationStorage=r}return this.messageHandler.sendWithPromise("ExtractPages",e,s).finally(()=>{this.annotationStorage.resetModified()})}getPage(t){if(!Number.isInteger(t)||t<=0||t>this.pagesMapper.pagesNumber)return Promise.reject(new Error("Invalid page request."));const e=t-1,s=this.pagesMapper.getPageId(t)-1,i=this.#n.get(e);if(i)return i;const n=this.messageHandler.sendWithPromise("GetPage",{pageIndex:s}).then(r=>{if(this.destroyed)throw new Error("Transport destroyed");r.refStr&&this.#a.set(r.refStr,s);const a=new qi(e,r,this,this.pagesMapper,this._params.pdfBug);return this.#i.set(e,a),a});return this.#n.set(e,n),n}async getPageIndex(t){if(!Ii(t))throw new Error("Invalid pageIndex request.");const e=await this.messageHandler.sendWithPromise("GetPageIndex",{num:t.num,gen:t.gen}),s=this.pagesMapper.getPageNumber(e+1);if(s===0)throw new Error("GetPageIndex: page has been removed.");return s-1}getAnnotations(t,e){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:this.pagesMapper.getPageId(t+1)-1,intent:e})}getFieldObjects(){return this.#o("GetFieldObjects")}hasJSActions(){return this.#o("HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(t){return typeof t!="string"?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:t})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getAttachmentContent(t){return this.messageHandler.sendWithPromise("GetAttachmentContent",t)}getAnnotationsByType(t,e){return this.messageHandler.sendWithPromise("GetAnnotationsByType",{types:t,pageIndexesToSkip:e})}getDocJSActions(){return this.#o("GetDocJSActions")}getPageJSActions(t){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:this.pagesMapper.getPageId(t+1)-1})}getStructTree(t){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:this.pagesMapper.getPageId(t+1)-1})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(t){return this.#o("GetOptionalContentConfig").then(e=>new Yi(e,t))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata";return this.#e.getOrInsertComputed(t,()=>this.messageHandler.sendWithPromise(t,null).then(e=>({info:e[0],metadata:e[1]?new lc(e[1]):null,contentDispositionFilename:this.#t?.filename??null,contentLength:this.#t?.contentLength??null,hasStructTree:e[2]})))}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}getRawData(t){return this.messageHandler.sendWithPromise("GetRawData",t)}async startCleanup(t=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const e of this.#i.values())if(!e.cleanup())throw new Error(`startCleanup: Page ${e.pageNumber} is currently rendering.`);this.commonObjs.clear(),t||this.fontLoader.clear(),this.#e.clear(),this.filterFactory.destroy(!0),Mt.cleanup()}}cachedPageNumber(t){if(!Ii(t))return null;const e=t.gen===0?`${t.num}R`:`${t.num}R${t.gen}`,s=this.#a.get(e);if(s>=0){const i=this.pagesMapper.getPageNumber(s+1);if(i!==0)return i}return null}}class gc{_internalRenderTask=null;onContinue=null;onError=null;constructor(t){this._internalRenderTask=t}get promise(){return this._internalRenderTask.capability.promise}cancel(t=0){this._internalRenderTask.cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=this._internalRenderTask.operatorList;if(!t)return!1;const{annotationCanvasMap:e}=this._internalRenderTask;return t.form||t.canvas&&e?.size>0}get imageCoordinates(){return this._internalRenderTask.imageCoordinates||null}}class Le{#t=null;static#e=new WeakSet;constructor({callback:t,params:e,objs:s,commonObjs:i,annotationCanvasMap:n,operatorList:r,pageIndex:a,canvasFactory:o,filterFactory:l,useRequestAnimationFrame:c=!1,pdfBug:h=!1,pageColors:u=null,enableHWA:f=!1,operationsFilter:p=null}){this.callback=t,this.params=e,this.objs=s,this.commonObjs=i,this.annotationCanvasMap=n,this.operatorListIdx=null,this.operatorList=r,this._pageIndex=a,this.canvasFactory=o,this.filterFactory=l,this._pdfBug=h,this.pageColors=u,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=c===!0&&typeof window<"u",this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new gc(this),this._cancelBound=this.cancel.bind(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=e.canvas,this._canvasContext=e.canvas?null:e.canvasContext,this._enableHWA=f,this._dependencyTracker=e.dependencyTracker,this._imagesTracker=e.imagesTracker,this._operationsFilter=p}get completed(){return this.capability.promise.catch(function(){})}initializeGraphics({transparency:t=!1,optionalContentConfig:e}){if(this.cancelled)return;if(this._canvas){if(Le.#e.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.");Le.#e.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());const{viewport:s,transform:i,background:n,dependencyTracker:r,imagesTracker:a}=this.params,o=this._canvasContext||this._canvas.getContext("2d",{alpha:!1,willReadFrequently:!this._enableHWA});this.gfx=new Oe(o,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:e},this.annotationCanvasMap,this.pageColors,r,a),this.gfx.beginDrawing({transform:i,viewport:s,transparency:t,background:n}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback?.()}cancel(t=null,e=0){this.running=!1,this.cancelled=!0,this.gfx?.endDrawing(),this.#t&&(window.cancelAnimationFrame(this.#t),this.#t=null),Le.#e.delete(this._canvas),t||=new zi(`Rendering cancelled, page ${this._pageIndex+1}`,e),this.callback(t),this.task.onError?.(t)}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.#t=window.requestAnimationFrame(()=>{this.#t=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(),Le.#e.delete(this._canvas),this.callback())))}}const mc="6.1.200",bc="6353acefe";class Lt{#t=null;#e=null;#s;#i=null;#n=!1;#a=!1;#r=null;#o;#h=null;#l=null;static#u=null;static get _keyboardManager(){return z(this,"_keyboardManager",new It([[["Escape"],Lt.prototype._hideDropdownFromKeyboard],[["Space"],Lt.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight"],Lt.prototype._moveToNext],[["ArrowUp","ArrowLeft"],Lt.prototype._moveToPrevious],[["Home"],Lt.prototype._moveToBeginning],[["End"],Lt.prototype._moveToEnd]]))}constructor({editor:t=null,uiManager:e=null}){t?(this.#a=!1,this.#r=t):this.#a=!0,this.#l=t?._uiManager||e,this.#o=this.#l._eventBus,this.#s=t?.color?.toUpperCase()||this.#l?.highlightColors.values().next().value||"#FFFF98",Lt.#u||=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(){const t=this.#t=document.createElement("button");t.className="colorPicker",t.tabIndex="0",t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-button"),t.ariaHasPopup="true",this.#r&&(t.ariaControls=`${this.#r.id}_colorpicker_dropdown`);const e=this.#l._signal;t.addEventListener("click",this.#g.bind(this),{signal:e}),t.addEventListener("keydown",this.#m.bind(this),{signal:e});const s=this.#e=document.createElement("span");return s.className="swatch",s.ariaHidden="true",s.style.backgroundColor=this.#s,t.append(s),t}renderMainDropdown(){const t=this.#i=this.#d();return t.ariaOrientation="horizontal",t.ariaLabelledBy="highlightColorPickerLabel",t}#d(){const t=document.createElement("div"),e=this.#l._signal;t.addEventListener("contextmenu",Rt,{signal:e}),t.className="dropdown",t.role="listbox",t.ariaMultiSelectable="false",t.ariaOrientation="vertical",t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-dropdown"),this.#r&&(t.id=`${this.#r.id}_colorpicker_dropdown`);for(const[s,i]of this.#l.highlightColors){const n=document.createElement("button");n.tabIndex="0",n.role="option",n.setAttribute("data-color",i),n.title=s,n.setAttribute("data-l10n-id",Lt.#u[s]);const r=document.createElement("span");n.append(r),r.className="swatch",r.style.backgroundColor=i,n.ariaSelected=i===this.#s,n.addEventListener("click",this.#p.bind(this,i),{signal:e}),t.append(n)}return t.addEventListener("keydown",this.#m.bind(this),{signal:e}),t}#p(t,e){e.stopPropagation(),this.#o.dispatch("switchannotationeditorparams",{source:this,type:X.HIGHLIGHT_COLOR,value:t}),this.updateColor(t)}_colorSelectFromKeyboard(t){if(t.target===this.#t){this.#g(t);return}const e=t.target.getAttribute("data-color");e&&this.#p(e,t)}_moveToNext(t){if(!this.#f){this.#g(t);return}if(t.target===this.#t){this.#i.firstElementChild?.focus();return}t.target.nextSibling?.focus()}_moveToPrevious(t){if(t.target===this.#i?.firstElementChild||t.target===this.#t){this.#f&&this._hideDropdownFromKeyboard();return}this.#f||this.#g(t),t.target.previousSibling?.focus()}_moveToBeginning(t){if(!this.#f){this.#g(t);return}this.#i.firstElementChild?.focus()}_moveToEnd(t){if(!this.#f){this.#g(t);return}this.#i.lastElementChild?.focus()}#m(t){Lt._keyboardManager.exec(this,t)}#g(t){if(this.#f){this.hideDropdown();return}if(this.#n=t.detail===0,this.#h||(this.#h=new AbortController,window.addEventListener("pointerdown",this.#c.bind(this),{signal:this.#l.combinedSignal(this.#h)})),this.#t.ariaExpanded="true",this.#i){this.#i.classList.remove("hidden");return}const e=this.#i=this.#d();this.#t.append(e)}#c(t){this.#i?.contains(t.target)||this.hideDropdown()}hideDropdown(){this.#i?.classList.add("hidden"),this.#t.ariaExpanded="false",this.#h?.abort(),this.#h=null}get#f(){return this.#i&&!this.#i.classList.contains("hidden")}_hideDropdownFromKeyboard(){if(!this.#a){if(!this.#f){this.#r?.unselect();return}this.hideDropdown(),this.#t.focus({preventScroll:!0,focusVisible:this.#n})}}updateColor(t){if(this.#e&&(this.#e.style.backgroundColor=t),!this.#i)return;const e=this.#l.highlightColors.values();for(const s of this.#i.children)s.ariaSelected=e.next().value===t.toUpperCase()}destroy(){this.#t?.remove(),this.#t=null,this.#e=null,this.#i?.remove(),this.#i=null}}class rs{#t=null;#e=!1;#s=null;#i=null;static#n=null;constructor(t){this.#s=t,this.#i=t._uiManager,rs.#n||=Object.freeze({freetext:"pdfjs-editor-color-picker-free-text-input",ink:"pdfjs-editor-color-picker-ink-input"})}renderButton(){if(this.#t)return this.#t;const{editorType:t,colorType:e,colorAndOpacityType:s,opacityType:i,color:n,opacity:r}=this.#s,a=this.#e=J.isAlphaColorInputSupported&&i!==void 0,o=this.#t=document.createElement("input");if(o.type="color",a){o.setAttribute("alpha","");const l=T.hexNums[Math.round((r??1)*255)];o.value=(n||"#000000")+l}else o.value=n||"#000000";return o.className="basicColorPicker",o.tabIndex=0,o.setAttribute("data-l10n-id",rs.#n[t]),o.addEventListener("input",()=>{if(a){const l=hs(o.value);if(!l)return;const[c,h,u,f]=l,p=T.makeHexColor(c,h,u);s!==void 0?this.#i.updateParams(s,{color:p,opacity:f}):(this.#i.updateParams(e,p),this.#i.updateParams(i,f))}else this.#i.updateParams(e,o.value)},{signal:this.#i._signal}),o}update(t){if(this.#t)if(this.#e){const e=T.hexNums[Math.round(this.#s.opacity*255)];this.#t.value=t+e}else this.#t.value=t}updateOpacity(t){if(!this.#t||!this.#e)return;const e=T.hexNums[Math.round(t*255)];this.#t.value=this.#s.color+e}destroy(){this.#t?.remove(),this.#t=null}hideDropdown(){}}function ar(d){return Math.floor(nt(d,0,1)*255).toString(16).padStart(2,"0")}function Xe(d){return nt(d,0,1)*255}class or{static CMYK_G([t,e,s,i]){return["G",1-Math.min(1,.3*t+.59*s+.11*e+i)]}static G_CMYK([t]){return["CMYK",0,0,0,1-t]}static G_RGB([t]){return["RGB",t,t,t]}static G_rgb([t]){return t=Xe(t),[t,t,t]}static G_HTML([t]){const e=ar(t);return`#${e}${e}${e}`}static RGB_G([t,e,s]){return["G",.3*t+.59*e+.11*s]}static RGB_rgb(t){return t.map(Xe)}static RGB_HTML(t){return`#${t.map(ar).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([t,e,s,i]){return["RGB",1-Math.min(1,t+i),1-Math.min(1,s+i),1-Math.min(1,e+i)]}static CMYK_rgb([t,e,s,i]){return[Xe(1-Math.min(1,t+i)),Xe(1-Math.min(1,s+i)),Xe(1-Math.min(1,e+i))]}static CMYK_HTML(t){const e=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(e)}static RGB_CMYK([t,e,s]){const i=1-t,n=1-e,r=1-s,a=Math.min(i,n,r);return["CMYK",i,n,r,a]}}class yc{create(t,e,s=!1){if(t<=0||e<=0)throw new Error("Invalid SVG dimensions");const i=this._createSVG("svg:svg");return i.setAttribute("version","1.1"),s||(i.setAttribute("width",`${t}px`),i.setAttribute("height",`${e}px`)),i.setAttribute("preserveAspectRatio","none"),i.setAttribute("viewBox",`0 0 ${t} ${e}`),i}createElement(t){if(typeof t!="string")throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){K("Abstract method `_createSVG` called.")}}class Os extends yc{_createSVG(t){return document.createElementNS(kt,t)}}const vc=9,we=new WeakSet,Ac=new Date().getTimezoneOffset()*60*1e3;class vi{static create(t){switch(t.data.annotationType){case ft.LINK:return new Qi(t);case ft.TEXT:return new wc(t);case ft.WIDGET:switch(t.data.fieldType){case"Tx":return new Sc(t);case"Btn":return t.data.radioButton?new _c(t):t.data.checkBox?new Ec(t):new kc(t);case"Ch":return new Tc(t);case"Sig":return new Cc(t)}return new Ce(t);case ft.POPUP:return new Di(t);case ft.FREETEXT:return new $r(t);case ft.LINE:return new Pc(t);case ft.SQUARE:return new Ic(t);case ft.CIRCLE:return new Dc(t);case ft.POLYLINE:return new Gr(t);case ft.CARET:return new Fc(t);case ft.INK:return new Ji(t);case ft.POLYGON:return new Nc(t);case ft.HIGHLIGHT:return new Vr(t);case ft.UNDERLINE:return new Lc(t);case ft.SQUIGGLY:return new Rc(t);case ft.STRIKEOUT:return new Oc(t);case ft.STAMP:return new Wr(t);case ft.FILEATTACHMENT:return new Bc(t);case ft.RICHMEDIA:case ft.SCREEN:return new Xr(t);default:return new ot(t)}}}class ot{#t=null;#e=!1;#s=null;constructor(t,{isRenderable:e=!1,ignoreBorder:s=!1,createQuadrilaterals:i=!1}={}){this.isRenderable=e,this.data=t.data,this.layer=t.layer,this.linkService=t.linkService,this.downloadManager=t.downloadManager,this.imageResourcesPath=t.imageResourcesPath,this.renderForms=t.renderForms,this.svgFactory=t.svgFactory,this.annotationStorage=t.annotationStorage,this.enableComment=t.enableComment,this.enableScripting=t.enableScripting,this.hasJSActions=t.hasJSActions,this._fieldObjects=t.fieldObjects,this.parent=t.parent,this.hasOwnCommentButton=!1,e&&(this.contentElement=this.container=this._createContainer(s)),i&&this._createQuadrilaterals()}static _hasPopupData({contentsObj:t,richText:e}){return!!(t?.str||e?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return ot._hasPopupData(this.data)||this.enableComment&&!!this.commentText}get commentData(){const{data:t}=this,e=this.annotationStorage?.getEditor(t.id);return e?e.getData():t}get hasCommentButton(){return this.enableComment&&this.hasPopupElement}get commentButtonPosition(){const t=this.annotationStorage?.getEditor(this.data.id);if(t)return t.commentButtonPositionInPage;const{quadPoints:e,inkLists:s,rect:i}=this.data;let n=-1/0,r=-1/0;if(e?.length>=8){for(let a=0;a<e.length;a+=8)e[a+1]>r?(r=e[a+1],n=e[a+2]):e[a+1]===r&&(n=Math.max(n,e[a+2]));return[n,r]}if(s?.length>=1){for(const a of s)for(let o=0,l=a.length;o<l;o+=2)a[o+1]>r?(r=a[o+1],n=a[o]):a[o+1]===r&&(n=Math.max(n,a[o]));if(n!==1/0)return[n,r]}return i?[i[2],i[3]]:null}_normalizePoint(t){const{page:{view:e},viewport:{rawDims:{pageWidth:s,pageHeight:i,pageX:n,pageY:r}}}=this.parent;return t[1]=e[3]-t[1]+e[1],t[0]=100*(t[0]-n)/s,t[1]=100*(t[1]-r)/i,t}get commentText(){const{data:t}=this;return this.annotationStorage.getRawValue(`${ts}${t.id}`)?.popup?.contents||t.contentsObj?.str||""}set commentText(t){const{data:e}=this,s={deleted:!t,contents:t||""};this.annotationStorage.updateEditor(e.id,{popup:s})||this.annotationStorage.setValue(`${ts}${e.id}`,{id:e.id,annotationType:e.annotationType,page:this.parent.page,popup:s,popupRef:e.popupRef,modificationDate:new Date}),t||this.removePopup()}removePopup(){(this.#s?.popup||this.popup)?.remove(),this.#s=this.popup=null}updateEdited(t){if(!this.container)return;t.rect&&(this.#t||={rect:this.data.rect.slice(0)});const{rect:e,popup:s}=t;e&&this.#i(e);let i=this.#s?.popup||this.popup;!i&&s?.text&&(this._createPopup(s),i=this.#s.popup),i&&(i.updateEdited(t),s?.deleted&&(i.remove(),this.#s=null,this.popup=null))}resetEdited(){this.#t&&(this.#i(this.#t.rect),this.#s?.popup.resetEdited(),this.#t=null)}#i(t){const{container:{style:e},data:{rect:s,rotation:i},parent:{viewport:{rawDims:{pageWidth:n,pageHeight:r,pageX:a,pageY:o}}}}=this;s?.splice(0,4,...t),e.left=`${100*(t[0]-a)/n}%`,e.top=`${100*(r-t[3]+o)/r}%`,i===0?(e.width=`${100*(t[2]-t[0])/n}%`,e.height=`${100*(t[3]-t[1])/r}%`):this.setRotation(i)}_createContainer(t){const{data:e,parent:{page:s,viewport:i}}=this,n=document.createElement("section");n.setAttribute("data-annotation-id",e.id),!(this instanceof Ce)&&!(this instanceof Qi)&&!(this instanceof Xr)&&(n.tabIndex=0);const{style:r}=n;if(r.zIndex=this.parent.zIndex,this.parent.zIndex+=2,e.alternativeText&&(n.title=e.alternativeText),e.noRotate&&n.classList.add("norotate"),!e.rect||this instanceof Di){const{rotation:g}=e;return!e.hasOwnCanvas&&g!==0&&this.setRotation(g,n),n}const{width:a,height:o}=this;if(!t&&e.borderStyle.width>0){r.borderWidth=`${e.borderStyle.width}px`;const g=e.borderStyle.horizontalCornerRadius,m=e.borderStyle.verticalCornerRadius;if(g>0||m>0){const y=`calc(${g}px * var(--total-scale-factor)) / calc(${m}px * var(--total-scale-factor))`;r.borderRadius=y}switch(e.borderStyle.style){case Ie.SOLID:r.borderStyle="solid";break;case Ie.DASHED:r.borderStyle="dashed";break;case Ie.BEVELED:V("Unimplemented border style: beveled");break;case Ie.INSET:V("Unimplemented border style: inset");break;case Ie.UNDERLINE:r.borderBottomStyle="solid";break}const b=e.borderColor||null;b?(this.#e=!0,r.borderColor=T.makeHexColor(...b)):r.borderWidth=0}const l=T.normalizeRect([e.rect[0],s.view[3]-e.rect[1]+s.view[1],e.rect[2],s.view[3]-e.rect[3]+s.view[1]]),{pageWidth:c,pageHeight:h,pageX:u,pageY:f}=i.rawDims;r.left=`${100*(l[0]-u)/c}%`,r.top=`${100*(l[1]-f)/h}%`;const{rotation:p}=e;return e.hasOwnCanvas||p===0?(r.width=`${100*a/c}%`,r.height=`${100*o/h}%`):this.setRotation(p,n),n}setRotation(t,e=this.container){if(!this.data.rect)return;const{pageWidth:s,pageHeight:i}=this.parent.viewport.rawDims;let{width:n,height:r}=this;t%180!==0&&([n,r]=[r,n]),e.style.width=`${100*n/s}%`,e.style.height=`${100*r/i}%`,e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const t=(e,s,i)=>{const n=i.detail[e],r=n[0],a=n.slice(1);i.target.style[s]=or[`${r}_HTML`](a),this.annotationStorage.setValue(this.data.id,{[s]:or[`${r}_rgb`](a)})};return z(this,"_commonActions",{display:e=>{const{display:s}=e.detail,i=s%2===1;this.container.style.visibility=i?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:i,noPrint:s===1||s===2})},print:e=>{this.annotationStorage.setValue(this.data.id,{noPrint:!e.detail.print})},hidden:e=>{const{hidden:s}=e.detail;this.container.style.visibility=s?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:s,noView:s})},focus:e=>{setTimeout(()=>e.target.focus({preventScroll:!1}),0)},userName:e=>{e.target.title=e.detail.userName},readonly:e=>{e.target.disabled=e.detail.readonly},required:e=>{this._setRequired(e.target,e.detail.required)},bgColor:e=>{t("bgColor","backgroundColor",e)},fillColor:e=>{t("fillColor","backgroundColor",e)},fgColor:e=>{t("fgColor","color",e)},textColor:e=>{t("textColor","color",e)},borderColor:e=>{t("borderColor","borderColor",e)},strokeColor:e=>{t("strokeColor","borderColor",e)},rotation:e=>{const s=e.detail.rotation;this.setRotation(s),this.annotationStorage.setValue(this.data.id,{rotation:s})}})}_dispatchEventFromSandbox(t,e){const s=this._commonActions;for(const i of Object.keys(e.detail))(t[i]||s[i])?.(e)}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;const e=this.annotationStorage.getRawValue(this.data.id);if(!e)return;const s=this._commonActions;for(const[i,n]of Object.entries(e)){const r=s[i];if(r){const a={detail:{[i]:n},target:t};r(a),delete e[i]}}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:t}=this.data;if(!t)return;const[e,s,i,n]=this.data.rect.map(g=>Math.fround(g));if(t.length===8){const[g,m,b,y]=t.subarray(2,6);if(i===g&&n===m&&e===b&&s===y)return}const{style:r}=this.container;let a;if(this.#e){const{borderColor:g,borderWidth:m}=r;r.borderWidth=0,a=["url('data:image/svg+xml;utf8,",`<svg xmlns="${kt}" preserveAspectRatio="none" viewBox="0 0 1 1">`,`<g fill="transparent" stroke="${g}" stroke-width="${m}">`],this.container.classList.add("hasBorder")}const o=i-e,l=n-s,{svgFactory:c}=this,h=c.createElement("svg");h.classList.add("quadrilateralsContainer"),h.setAttribute("width",0),h.setAttribute("height",0),h.role="none";const u=c.createElement("defs");h.append(u);const f=c.createElement("clipPath"),p=`clippath_${this.data.id}`;f.setAttribute("id",p),f.setAttribute("clipPathUnits","objectBoundingBox"),u.append(f);for(let g=2,m=t.length;g<m;g+=8){const b=t[g],y=t[g+1],A=t[g+2],w=t[g+3],x=c.createElement("rect"),S=(A-e)/o,E=(n-y)/l,_=(b-A)/o,k=(y-w)/l;x.setAttribute("x",S),x.setAttribute("y",E),x.setAttribute("width",_),x.setAttribute("height",k),f.append(x),a?.push(`<rect vector-effect="non-scaling-stroke" x="${S}" y="${E}" width="${_}" height="${k}"/>`)}this.#e&&(a.push("</g></svg>')"),r.backgroundImage=a.join("")),this.container.append(h),this.container.style.clipPath=`url(#${p})`}_createPopup(t=null){const{data:e}=this;let s,i;t?(s={str:t.text},i=t.date):(s=e.contentsObj,i=e.modificationDate),this.#s=new Di({data:{color:e.color,titleObj:e.titleObj,modificationDate:i,contentsObj:s,richText:e.richText,parentRect:e.rect,borderStyle:0,id:`popup_${e.id}`,rotation:e.rotation,noRotate:!0},linkService:this.linkService,parent:this.parent,elements:[this]})}get hasPopupElement(){return!!(this.#s||this.popup||this.data.popupRef)}get extraPopupElement(){return this.#s}render(){K("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){const s=[];if(this._fieldObjects){const i=this._fieldObjects[t];if(i)for(const{page:n,id:r,exportValues:a}of i){if(n===-1||r===e)continue;const o=typeof a=="string"?a:null,l=document.querySelector(`[data-element-id="${r}"]`);if(l&&!we.has(l)){V(`_getElementsByName - element not allowed: ${r}`);continue}s.push({id:r,exportValue:o,domElement:l})}return s}for(const i of document.getElementsByName(t)){const{exportValue:n}=i,r=i.getAttribute("data-element-id");r!==e&&we.has(i)&&s.push({id:r,exportValue:n,domElement:i})}return s}show(){this.container&&(this.container.hidden=!1),this.popup?.maybeShow()}hide(){this.container&&(this.container.hidden=!0),this.popup?.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){const t=this.getElementsToTriggerPopup();if(Array.isArray(t))for(const e of t)e.classList.add("highlightArea");else t.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;const{annotationEditorType:t,data:{id:e}}=this;this.container.addEventListener("dblclick",()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:t,editId:e,mustEnterInEditMode:!0})})}updateOC(t){if(!this.data.oc||!t)return;t.isVisible(this.data.oc)?this.show():this.hide()}get width(){return this.data.rect[2]-this.data.rect[0]}get height(){return this.data.rect[3]-this.data.rect[1]}_setBackgroundColor(t){const e=this.data.backgroundColor||null;t.style.backgroundColor=e===null?"transparent":T.makeHexColor(...e)}}class xc extends ot{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.editor=t.editor}render(){return this.container.className="editorAnnotation",this.container}createOrUpdatePopup(){const{editor:t}=this;t.hasComment&&this._createPopup(t.comment)}get hasCommentButton(){return this.enableComment&&this.editor.hasComment}get commentButtonPosition(){return this.editor.commentButtonPositionInPage}get commentText(){return this.editor.comment.text}set commentText(t){this.editor.comment=t,t||this.removePopup()}get commentData(){return this.editor.getData()}remove(){this.parent.removeAnnotation(this.data.id),this.container.remove(),this.container=null,this.removePopup()}}class Qi extends ot{constructor(t,e=null){super(t,{isRenderable:!0,ignoreBorder:!!e?.ignoreBorder,createQuadrilaterals:!0}),this.isTooltipOnly=t.data.isTooltipOnly}render(){const{data:t,linkService:e}=this,s=document.createElement("a");s.setAttribute("data-element-id",t.id);let i=!1;return t.url?(e.addLinkAttributes(s,t.url,t.newWindow),i=!0):t.action?(this._bindNamedAction(s,t.action,t.overlaidText),i=!0):t.attachment?(this.#e(s,t.attachmentId,t.attachment,t.overlaidText,t.attachmentDest),i=!0):t.setOCGState?(this.#s(s,t.setOCGState,t.overlaidText),i=!0):t.dest?(this._bindLink(s,t.dest,t.overlaidText),i=!0):(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(s,t),i=!0),t.resetForm?(this._bindResetFormAction(s,t.resetForm),i=!0):this.isTooltipOnly&&!i&&(this._bindLink(s,""),i=!0)),this.container.classList.add("linkAnnotation"),i&&(this.contentElement=s,this.container.append(s)),this.container}#t(){this.container.setAttribute("data-internal-link","")}_bindLink(t,e,s=""){t.href=this.linkService.getDestinationHash(e),t.onclick=()=>(e&&this.linkService.goToDestination(e),!1),(e||e==="")&&this.#t(),s&&(t.title=s)}_bindNamedAction(t,e,s=""){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeNamedAction(e),!1),s&&(t.title=s),this.#t()}#e(t,e,s,i="",n=null){t.href=this.linkService.getAnchorUrl(""),s.description?t.title=s.description:i&&(t.title=i);const r=async()=>{const a=await this.linkService.getAttachmentContent(e);a&&this.downloadManager?.openOrDownloadData(a,s.filename,n)};t.onclick=()=>(r(),!1),this.#t()}#s(t,e,s=""){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeSetOCGState(e),!1),s&&(t.title=s),this.#t()}_bindJSAction(t,e){t.href=this.linkService.getAnchorUrl("");const s=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const i of Object.keys(e.actions)){const n=s.get(i);n&&(t[n]=()=>(this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e.id,name:i}}),!1))}e.overlaidText&&(t.title=e.overlaidText),t.onclick||(t.onclick=()=>!1),this.#t()}_bindResetFormAction(t,e){const s=t.onclick;if(s||(t.href=this.linkService.getAnchorUrl("")),this.#t(),!this._fieldObjects){V('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),s||(t.onclick=()=>!1);return}t.onclick=()=>{s?.();const{fields:i,refs:n,include:r}=e,a=[];if(i.length!==0||n.length!==0){const c=new Set(n);for(const h of i){const u=this._fieldObjects[h]||[];for(const{id:f}of u)c.add(f)}for(const h of Object.values(this._fieldObjects))for(const u of h)c.has(u.id)===r&&a.push(u)}else for(const c of Object.values(this._fieldObjects))a.push(...c);const o=this.annotationStorage,l=[];for(const c of a){const{id:h}=c;switch(l.push(h),c.type){case"text":{const f=c.defaultValue||"";o.setValue(h,{value:f});break}case"checkbox":case"radiobutton":{const f=c.defaultValue===c.exportValues;o.setValue(h,{value:f});break}case"combobox":case"listbox":{const f=c.defaultValue||"";o.setValue(h,{value:f});break}default:continue}const u=document.querySelector(`[data-element-id="${h}"]`);if(u){if(!we.has(u)){V(`_bindResetFormAction - element not allowed: ${h}`);continue}}else continue;u.dispatchEvent(new Event("resetform"))}return this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:l,name:"ResetForm"}}),!1}}}class wc extends ot{constructor(t){super(t,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");const t=document.createElement("img");return t.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",t.setAttribute("data-l10n-id","pdfjs-text-annotation-type"),t.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name})),!this.data.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.append(t),this.container}}class Ce extends ot{render(){return this.container}_getKeyModifier(t){return J.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,e,s,i,n){s.includes("mouse")?t.addEventListener(s,r=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:n(r),shift:r.shiftKey,modifier:this._getKeyModifier(r)}})}):t.addEventListener(s,r=>{if(s==="blur"){if(!e.focused||!r.relatedTarget)return;e.focused=!1}else if(s==="focus"){if(e.focused)return;e.focused=!0}n&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:n(r)}})})}_setEventListeners(t,e,s,i){for(const[n,r]of s)(r==="Action"||this.data.actions?.[r])&&((r==="Focus"||r==="Blur")&&(e||={focused:!1}),this._setEventListener(t,e,n,r,i),r==="Focus"&&!this.data.actions?.Blur?this._setEventListener(t,e,"blur","Blur",null):r==="Blur"&&!this.data.actions?.Focus&&this._setEventListener(t,e,"focus","Focus",null))}_setTextStyle(t){const e=["left","center","right"],{fontColor:s}=this.data.defaultAppearanceData,i=this.data.defaultAppearanceData.fontSize||vc,n=t.style;let r;const a=2,o=l=>Math.round(10*l)/10;if(this.data.multiLine){const l=Math.abs(this.data.rect[3]-this.data.rect[1]-a),c=Math.round(l/(ui*i))||1,h=l/c;r=Math.min(i,o(h/ui))}else{const l=Math.abs(this.data.rect[3]-this.data.rect[1]-a);r=Math.min(i,o(l/ui))}n.fontSize=`calc(${r}px * var(--total-scale-factor))`,n.color=T.makeHexColor(...s),this.data.textAlignment!==null&&!this.data.comb&&(n.textAlign=e[this.data.textAlignment])}_setRequired(t,e){e?t.setAttribute("required",!0):t.removeAttribute("required"),t.setAttribute("aria-required",e)}}class Sc extends Ce{constructor(t){const e=t.renderForms||t.data.hasOwnCanvas||!t.data.hasAppearance&&!!t.data.fieldValue;super(t,{isRenderable:e})}setPropertyOnSiblings(t,e,s,i){const n=this.annotationStorage;for(const r of this._getElementsByName(t.name,t.id))r.domElement&&(r.domElement[e]=s),n.setValue(r.id,{[i]:s})}render(){const t=this.annotationStorage,e=this.data.id;this.container.classList.add("textWidgetAnnotation");let s=null;if(this.renderForms){const i=t.getValue(e,{value:this.data.fieldValue});let n=i.value||"";const r=t.getValue(e,{charLimit:this.data.maxLen}).charLimit;r&&n.length>r&&(n=n.slice(0,r));let a=i.formattedValue||this.data.textContent?.join(`
|
|
46
|
+
`)||null;a&&this.data.comb&&(a=a.replaceAll(/\s+/g,""));const o={userValue:n,formattedValue:a,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(s=document.createElement("textarea"),s.textContent=a??n,this.data.doNotScroll&&(s.style.overflowY="hidden")):(s=document.createElement("input"),s.type=this.data.password?"password":"text",s.setAttribute("value",a??n),this.data.doNotScroll&&(s.style.overflowX="hidden")),this.data.hasOwnCanvas&&(this.container.classList.add("hasOwnCanvas"),t.has(e)&&this.container.classList.add("sandboxModified")),we.add(s),this.contentElement=s,s.setAttribute("data-element-id",e),s.disabled=this.data.readOnly,s.name=this.data.fieldName,s.tabIndex=0;const{datetimeFormat:l,datetimeType:c,timeStep:h}=this.data,u=!!c&&this.enableScripting;l&&(s.title=l),this._setRequired(s,this.data.required),r&&(s.maxLength=r),s.addEventListener("input",p=>{t.setValue(e,{value:p.target.value}),this.setPropertyOnSiblings(s,"value",p.target.value,"value"),o.formattedValue=null}),s.addEventListener("resetform",p=>{const g=this.data.defaultFieldValue??"";s.value=o.userValue=g,o.formattedValue=null});let f=p=>{const{formattedValue:g}=o;g!=null&&(p.target.value=g),p.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){s.addEventListener("focus",g=>{if(o.focused)return;const{target:m}=g;if(u&&(m.type=c,h&&(m.step=h)),o.userValue){const b=o.userValue;if(u)if(c==="time"){const y=new Date(b),A=[y.getHours(),y.getMinutes(),y.getSeconds()];m.value=A.map(w=>w.toString().padStart(2,"0")).join(":")}else m.value=new Date(b-Ac).toISOString().split(c==="date"?"T":".",1)[0];else m.value=b}o.lastCommittedValue=m.value,o.commitKey=1,this.data.actions?.Focus||(o.focused=!0)}),s.addEventListener("updatefromsandbox",g=>{this.container.classList.add("sandboxModified");const m={value(b){o.userValue=b.detail.value??"",u||t.setValue(e,{value:o.userValue.toString()}),b.target.value=o.userValue},formattedValue(b){const{formattedValue:y}=b.detail;o.formattedValue=y,y!=null&&b.target!==document.activeElement&&(b.target.value=y);const A={formattedValue:y};u&&(A.value=y),t.setValue(e,A)},selRange(b){b.target.setSelectionRange(...b.detail.selRange)},charLimit:b=>{const{charLimit:y}=b.detail,{target:A}=b;if(y===0){A.removeAttribute("maxLength");return}A.setAttribute("maxLength",y);let w=o.userValue;!w||w.length<=y||(w=w.slice(0,y),A.value=o.userValue=w,t.setValue(e,{value:w}),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:w,willCommit:!0,commitKey:1,selStart:A.selectionStart,selEnd:A.selectionEnd}}))}};this._dispatchEventFromSandbox(m,g)}),s.addEventListener("keydown",g=>{o.commitKey=1;let m=-1;if(g.key==="Escape"?m=0:g.key==="Enter"&&!this.data.multiLine?m=2:g.key==="Tab"&&(o.commitKey=3),m===-1)return;const{value:b}=g.target;o.lastCommittedValue!==b&&(o.lastCommittedValue=b,o.userValue=b,this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:b,willCommit:!0,commitKey:m,selStart:g.target.selectionStart,selEnd:g.target.selectionEnd}}))});const p=f;f=null,s.addEventListener("blur",g=>{if(!o.focused||!g.relatedTarget)return;this.data.actions?.Blur||(o.focused=!1);const{target:m}=g;let{value:b}=m;if(u){if(b&&c==="time"){const y=b.split(":").map(A=>parseInt(A,10));b=new Date(2e3,0,1,y[0],y[1],y[2]||0).valueOf(),m.step=""}else b.includes("T")||(b=`${b}T00:00`),b=new Date(b).valueOf();m.type="text"}o.userValue=b,o.lastCommittedValue!==b&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:b,willCommit:!0,commitKey:o.commitKey,selStart:g.target.selectionStart,selEnd:g.target.selectionEnd}}),p(g)}),this.data.actions?.Keystroke&&s.addEventListener("beforeinput",g=>{o.lastCommittedValue=null;const{data:m,target:b}=g,{value:y,selectionStart:A,selectionEnd:w}=b;let x=A,S=w;switch(g.inputType){case"deleteWordBackward":{const E=y.substring(0,A).match(/\w*\W*$/);E&&(x-=E[0].length);break}case"deleteWordForward":{const E=y.substring(A).match(/^\W*\w*/);E&&(S+=E[0].length);break}case"deleteContentBackward":A===w&&(x-=1);break;case"deleteContentForward":A===w&&(S+=1);break}g.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:y,change:m||"",willCommit:!1,selStart:x,selEnd:S}})}),this._setEventListeners(s,o,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],g=>g.target.value)}if(f&&s.addEventListener("blur",f),this.data.comb){const g=(this.data.rect[2]-this.data.rect[0])/r;s.classList.add("comb"),s.style.setProperty("--comb-width",`calc(${g}px * var(--total-scale-factor))`);const m=this.data.textAlignment;if(m===1||m===2){const b=()=>{const y=r-s.value.length;s.style.setProperty("--comb-offset",`${m===1?y>>1:y}`)};b();for(const y of["input","blur","resetform","updatefromsandbox"])s.addEventListener(y,b)}}}else s=document.createElement("div"),s.textContent=this.data.fieldValue,s.style.verticalAlign="middle",s.style.display="table-cell",this.data.hasOwnCanvas&&(s.hidden=!0);return this._setTextStyle(s),this._setBackgroundColor(s),this._setDefaultPropertiesFromJS(s),this.container.append(s),this.container}}class Cc extends Ce{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class Ec extends Ce{constructor(t){super(t,{isRenderable:t.renderForms})}render(){const t=this.annotationStorage,e=this.data,s=e.id;let i=t.getValue(s,{value:e.exportValue===e.fieldValue}).value;typeof i=="string"&&(i=i!=="Off",t.setValue(s,{value:i})),this.container.classList.add("buttonWidgetAnnotation","checkBox");const n=document.createElement("input");return we.add(n),n.setAttribute("data-element-id",s),n.disabled=e.readOnly,this._setRequired(n,this.data.required),n.type="checkbox",n.name=e.fieldName,i&&n.setAttribute("checked",!0),n.setAttribute("exportValue",e.exportValue),n.tabIndex=0,n.addEventListener("change",r=>{const{name:a,checked:o}=r.target;for(const l of this._getElementsByName(a,s)){const c=o&&l.exportValue===e.exportValue;l.domElement&&(l.domElement.checked=c),t.setValue(l.id,{value:c})}t.setValue(s,{value:o})}),n.addEventListener("resetform",r=>{const a=e.defaultFieldValue||"Off";r.target.checked=a===e.exportValue}),this.enableScripting&&this.hasJSActions&&(n.addEventListener("updatefromsandbox",r=>{const a={value(o){o.target.checked=o.detail.value!=="Off",t.setValue(s,{value:o.target.checked})}};this._dispatchEventFromSandbox(a,r)}),this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],r=>r.target.checked)),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class _c extends Ce{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const t=this.annotationStorage,e=this.data,s=e.id;let i=t.getValue(s,{value:e.buttonValue!==null&&e.fieldValue===e.buttonValue}).value;if(typeof i=="string"&&(i=i!==e.buttonValue,t.setValue(s,{value:i})),i)for(const r of this._getElementsByName(e.fieldName,s))t.setValue(r.id,{value:!1});const n=document.createElement("input");if(we.add(n),n.setAttribute("data-element-id",s),n.disabled=e.readOnly,this._setRequired(n,this.data.required),n.type="radio",n.name=e.fieldName,i&&n.setAttribute("checked",!0),n.tabIndex=0,n.addEventListener("change",r=>{const{name:a,checked:o}=r.target;for(const l of this._getElementsByName(a,s))t.setValue(l.id,{value:!1});t.setValue(s,{value:o})}),n.addEventListener("resetform",r=>{const a=e.defaultFieldValue;r.target.checked=a!=null&&a===e.buttonValue}),this.enableScripting&&this.hasJSActions){const r=e.buttonValue;n.addEventListener("updatefromsandbox",a=>{const o={value:l=>{const c=r===l.detail.value;for(const h of this._getElementsByName(l.target.name)){const u=c&&h.id===s;h.domElement&&(h.domElement.checked=u),t.setValue(h.id,{value:u})}}};this._dispatchEventFromSandbox(o,a)}),this._setEventListeners(n,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)}return this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class kc extends Qi{constructor(t){super(t,{ignoreBorder:t.data.hasAppearance})}render(){const t=super.render();t.classList.add("buttonWidgetAnnotation","pushButton");const e=t.lastChild;return this.enableScripting&&this.hasJSActions&&e&&(this._setDefaultPropertiesFromJS(e),e.addEventListener("updatefromsandbox",s=>{this._dispatchEventFromSandbox({},s)})),t}}class Tc extends Ce{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");const t=this.annotationStorage,e=this.data.id,s=t.getValue(e,{value:this.data.fieldValue}),i=document.createElement("select");we.add(i),i.setAttribute("data-element-id",e),i.disabled=this.data.readOnly,this._setRequired(i,this.data.required),i.name=this.data.fieldName,i.tabIndex=0;let n=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",h=>{const u=this.data.defaultFieldValue;for(const f of i.options)f.selected=f.value===u});const r=(h,u)=>{const f=u.replaceAll(" "," ");h.textContent=f,f!==u&&h.setAttribute("display-value",u)};for(const h of this.data.options){const u=document.createElement("option");r(u,h.displayValue),u.value=h.exportValue,s.value.includes(h.exportValue)&&(u.setAttribute("selected",!0),n=!1),i.append(u)}let a=null;if(n){const h=document.createElement("option");h.value=" ",h.setAttribute("hidden",!0),h.setAttribute("selected",!0),i.prepend(h),a=()=>{h.remove(),i.removeEventListener("input",a),a=null},i.addEventListener("input",a)}const o=h=>{const u=h?"value":"textContent",{options:f,multiple:p}=i;return p?Array.prototype.filter.call(f,g=>g.selected).map(g=>g[u]):f.selectedIndex===-1?null:f[f.selectedIndex][u]};let l=o(!1);const c=h=>{const u=h.target.options;return Array.prototype.map.call(u,f=>({displayValue:f.getAttribute("display-value")||f.textContent,exportValue:f.value}))};return this.enableScripting&&this.hasJSActions?(i.addEventListener("updatefromsandbox",h=>{const u={value(f){a?.();const p=f.detail.value,g=new Set(Array.isArray(p)?p:[p]);for(const m of i.options)m.selected=g.has(m.value);t.setValue(e,{value:o(!0)}),l=o(!1)},multipleSelection(f){i.multiple=!0},remove(f){const p=i.options,g=f.detail.remove;p[g].selected=!1,i.remove(g),p.length>0&&Array.prototype.findIndex.call(p,b=>b.selected)===-1&&(p[0].selected=!0),t.setValue(e,{value:o(!0),items:c(f)}),l=o(!1)},clear(f){for(;i.length!==0;)i.remove(0);t.setValue(e,{value:null,items:[]}),l=o(!1)},insert(f){const{index:p,displayValue:g,exportValue:m}=f.detail.insert,b=i.children[p],y=document.createElement("option");r(y,g),y.value=m,b?b.before(y):i.append(y),t.setValue(e,{value:o(!0),items:c(f)}),l=o(!1)},items(f){const{items:p}=f.detail;for(;i.length!==0;)i.remove(0);for(const g of p){const{displayValue:m,exportValue:b}=g,y=document.createElement("option");r(y,m),y.value=b,i.append(y)}i.options.length>0&&(i.options[0].selected=!0),t.setValue(e,{value:o(!0),items:c(f)}),l=o(!1)},indices(f){const p=new Set(f.detail.indices);for(const g of f.target.options)g.selected=p.has(g.index);t.setValue(e,{value:o(!0)}),l=o(!1)},editable(f){f.target.disabled=!f.detail.editable}};this._dispatchEventFromSandbox(u,h)}),i.addEventListener("input",h=>{const u=o(!0),f=o(!1);t.setValue(e,{value:u}),h.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:l,change:f,changeEx:u,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"]],h=>h.target.value)):i.addEventListener("input",function(h){t.setValue(e,{value:o(!0)})}),this.data.combo&&this._setTextStyle(i),this._setBackgroundColor(i),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}}class Di extends ot{constructor(t){const{data:e,elements:s,parent:i}=t,n=!!i._commentManager;if(super(t,{isRenderable:!n&&ot._hasPopupData(e)}),this.elements=s,n&&ot._hasPopupData(e)){const r=this.popup=this.#t();for(const a of s)a.popup=r}else this.popup=null}#t(){return new Mc({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(){const{container:t}=this;t.classList.add("popupAnnotation"),t.role="comment";const e=this.popup=this.#t(),s=[];for(const i of this.elements)i.popup=e,i.container.ariaHasPopup="dialog",s.push(i.data.id),i.addHighlightArea();return this.container.setAttribute("aria-controls",s.map(i=>`${Fe}${i}`).join(",")),this.container}}class Mc{#t=null;#e=this.#j.bind(this);#s=this.#R.bind(this);#i=this.#x.bind(this);#n=this.#_.bind(this);#a=null;#r=null;#o=null;#h=null;#l=null;#u=null;#d=null;#p=!1;#m=null;#g=null;#c=null;#f=null;#y=null;#v=null;#b=null;#S=null;#C=null;#A=null;#E=!1;#w=null;#k=null;constructor({container:t,color:e,elements:s,titleObj:i,modificationDate:n,contentsObj:r,richText:a,parent:o,rect:l,parentRect:c,open:h,commentManager:u=null}){this.#r=t,this.#C=i,this.#o=r,this.#S=a,this.#u=o,this.#a=e,this.#b=l,this.#d=c,this.#l=s,this.#t=u,this.#w=s[0],this.#h=_i.toDateObject(n),this.trigger=s.flatMap(f=>f.getElementsToTriggerPopup()),u||(this.#M(),this.#r.hidden=!0,h&&this.#_())}#M(){if(this.#g)return;this.#g=new AbortController;const{signal:t}=this.#g;for(const e of this.trigger)e.addEventListener("click",this.#n,{signal:t}),e.addEventListener("pointerenter",this.#i,{signal:t}),e.addEventListener("pointerleave",this.#s,{signal:t}),e.classList.add("popupTriggerArea");for(const e of this.#l)e.container?.addEventListener("keydown",this.#e,{signal:t})}#P(){const t=this.#l.find(e=>e.hasCommentButton);t&&(this.#y=t._normalizePoint(t.commentButtonPosition))}renderCommentButton(){if(this.#f){this.#f.parentNode||this.#w.container.after(this.#f);return}if(this.#y||this.#P(),!this.#y)return;const{signal:t}=this.#g=new AbortController,e=this.#w.hasOwnCommentButton,s=()=>{this.#t.toggleCommentPopup(this,!0,void 0,!e)},i=()=>{this.#t.toggleCommentPopup(this,!1,!0,!e)},n=()=>{this.#t.toggleCommentPopup(this,!1,!1)};if(e){this.#f=this.#w.container;for(const r of this.trigger)r.ariaHasPopup="dialog",r.ariaControls="commentPopup",r.addEventListener("keydown",this.#e,{signal:t}),r.addEventListener("click",s,{signal:t}),r.addEventListener("pointerenter",i,{signal:t}),r.addEventListener("pointerleave",n,{signal:t}),r.classList.add("popupTriggerArea")}else{const r=this.#f=document.createElement("button");r.className="annotationCommentButton";const a=this.#w.container;r.style.zIndex=parseInt(a.style.zIndex,10)+1,r.tabIndex=0,r.ariaHasPopup="dialog",r.ariaControls="commentPopup",r.setAttribute("data-l10n-id","pdfjs-show-comment-button"),this.#N(),this.#T(),r.addEventListener("keydown",this.#e,{signal:t}),r.addEventListener("click",s,{signal:t}),r.addEventListener("pointerenter",i,{signal:t}),r.addEventListener("pointerleave",n,{signal:t}),a.after(r)}}#T(){if(this.#w.extraPopupElement&&!this.#w.editor)return;this.#f||this.renderCommentButton();const[t,e]=this.#y,{style:s}=this.#f;s.left=`calc(${t}%)`,s.top=`calc(${e}% - var(--comment-button-dim))`}#N(){this.#w.extraPopupElement||(this.#f||this.renderCommentButton(),this.#f.style.backgroundColor=this.commentButtonColor||"")}get commentButtonColor(){const{color:t,opacity:e}=this.#w.commentData;return t?this.#u._commentManager.makeCommentColor(t,e):null}focusCommentButton(){setTimeout(()=>{this.#f?.focus()},0)}getData(){const{richText:t,color:e,opacity:s,creationDate:i,modificationDate:n}=this.#w.commentData;return{contentsObj:{str:this.comment},richText:t,color:e,opacity:s,creationDate:i,modificationDate:n}}get elementBeforePopup(){return this.#f}get comment(){return this.#k||=this.#w.commentText,this.#k}set comment(t){t!==this.comment&&(this.#w.commentText=this.#k=t)}focus(){this.#w.container?.focus()}get parentBoundingClientRect(){return this.#w.layer.getBoundingClientRect()}setCommentButtonStates({selected:t,hasPopup:e}){this.#f&&(this.#f.classList.toggle("selected",t),this.#f.ariaExpanded=e)}setSelectedCommentButton(t){this.#f.classList.toggle("selected",t)}get commentPopupPosition(){if(this.#v)return this.#v;const{x:t,y:e,height:s}=this.#f.getBoundingClientRect(),{x:i,y:n,width:r,height:a}=this.#w.layer.getBoundingClientRect();return[(t-i)/r,(e+s-n)/a]}set commentPopupPosition(t){this.#v=t}hasDefaultPopupPosition(){return this.#v===null}get commentButtonPosition(){return this.#y}get commentButtonWidth(){return this.#f.getBoundingClientRect().width/this.parentBoundingClientRect.width}editComment(t){const[e,s]=this.#v||this.commentButtonPosition.map(l=>l/100),i=this.parentBoundingClientRect,{x:n,y:r,width:a,height:o}=i;this.#t.showDialog(null,this,n+e*a,r+s*o,{...t,parentDimensions:i})}render(){if(this.#m)return;const t=this.#m=document.createElement("div");if(t.className="popup",this.#a){const s=t.style.outlineColor=T.makeHexColor(...this.#a);t.style.backgroundColor=`color-mix(in srgb, ${s} 30%, white)`}const e=document.createElement("span");if(e.className="header",this.#C?.str){const s=document.createElement("span");s.className="title",e.append(s),{dir:s.dir,str:s.textContent}=this.#C}if(t.append(e),this.#h){const s=document.createElement("time");s.className="popupDate",s.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string"),s.setAttribute("data-l10n-args",JSON.stringify({dateObj:this.#h.valueOf()})),s.dateTime=this.#h.toISOString(),e.append(s)}Sr({html:this.#F||this.#o.str,dir:this.#o?.dir,className:"popupContent"},t),this.#r.append(t)}get#F(){const t=this.#S,e=this.#o;return t?.str&&(!e?.str||e.str===t.str)&&this.#S.html||null}get#D(){return this.#F?.attributes?.style?.fontSize||0}get#L(){return this.#F?.attributes?.style?.color||null}#O(t){const e=[],s={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},i={style:{color:this.#L,fontSize:this.#D?`calc(${this.#D}px * var(--total-scale-factor))`:""}};for(const n of t.split(`
|
|
47
|
+
`))e.push({name:"span",value:n,attributes:i});return s}#j(t){t.altKey||t.shiftKey||t.ctrlKey||t.metaKey||(t.key==="Enter"||t.key==="Escape"&&this.#p)&&this.#_()}updateEdited({rect:t,popup:e,deleted:s}){if(this.#t){s?(this.remove(),this.#k=null):e&&(e.deleted?this.remove():(this.#N(),this.#k=e.text)),t&&(this.#y=null,this.#P(),this.#T());return}if(s||e?.deleted){this.remove();return}this.#M(),this.#A||={contentsObj:this.#o,richText:this.#S},t&&(this.#c=null),e&&e.text&&(this.#S=this.#O(e.text),this.#h=_i.toDateObject(e.date),this.#o=null),this.#m?.remove(),this.#m=null}resetEdited(){this.#A&&({contentsObj:this.#o,richText:this.#S}=this.#A,this.#A=null,this.#m?.remove(),this.#m=null,this.#c=null)}remove(){if(this.#g?.abort(),this.#g=null,this.#m?.remove(),this.#m=null,this.#E=!1,this.#p=!1,this.#f?.remove(),this.#f=null,this.trigger)for(const t of this.trigger)t.classList.remove("popupTriggerArea")}#V(){if(this.#c!==null)return;const{page:{view:t},viewport:{rawDims:{pageWidth:e,pageHeight:s,pageX:i,pageY:n}}}=this.#u;let r=!!this.#d,a=r?this.#d:this.#b;for(const p of this.#l)if(!a||T.intersect(p.data.rect,a)!==null){a=p.data.rect,r=!0;break}const o=T.normalizeRect([a[0],t[3]-a[1]+t[1],a[2],t[3]-a[3]+t[1]]),c=r?a[2]-a[0]+5:0,h=o[0]+c,u=o[1];this.#c=[100*(h-i)/e,100*(u-n)/s];const{style:f}=this.#r;f.left=`${this.#c[0]}%`,f.top=`${this.#c[1]}%`}#_(){if(this.#t){this.#t.toggleCommentPopup(this,!1);return}this.#p=!this.#p,this.#p?(this.#x(),this.#r.addEventListener("click",this.#n),this.#r.addEventListener("keydown",this.#e)):(this.#R(),this.#r.removeEventListener("click",this.#n),this.#r.removeEventListener("keydown",this.#e))}#x(){this.#m||this.render(),this.isVisible?this.#p&&this.#r.classList.add("focused"):(this.#V(),this.#r.hidden=!1,this.#r.style.zIndex=parseInt(this.#r.style.zIndex,10)+1e3)}#R(){this.#r.classList.remove("focused"),!(this.#p||!this.isVisible)&&(this.#r.hidden=!0,this.#r.style.zIndex=parseInt(this.#r.style.zIndex,10)-1e3)}forceHide(){this.#E=this.isVisible,this.#E&&(this.#r.hidden=!0)}maybeShow(){this.#t||(this.#M(),this.#E&&(this.#m||this.#x(),this.#E=!1,this.#r.hidden=!1))}get isVisible(){return this.#t?!1:this.#r.hidden===!1}}class $r extends ot{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.textContent=t.data.textContent,this.textPosition=t.data.textPosition,this.annotationEditorType=G.FREETEXT}render(){if(this.container.classList.add("freeTextAnnotation"),this.textContent){const t=this.contentElement=document.createElement("div");t.classList.add("annotationTextContent"),t.setAttribute("role","comment");for(const e of this.textContent){const s=document.createElement("span");s.textContent=e,t.append(s)}this.container.append(t)}return!this.data.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this._editOnDoubleClick(),this.container}}class Pc extends ot{#t=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("lineAnnotation");const{data:t,width:e,height:s}=this,i=this.svgFactory.create(e,s,!0),n=this.#t=this.svgFactory.createElement("svg:line");return n.setAttribute("x1",t.rect[2]-t.lineCoordinates[0]),n.setAttribute("y1",t.rect[3]-t.lineCoordinates[1]),n.setAttribute("x2",t.rect[2]-t.lineCoordinates[2]),n.setAttribute("y2",t.rect[3]-t.lineCoordinates[3]),n.setAttribute("stroke-width",t.borderStyle.width||1),n.setAttribute("stroke","transparent"),n.setAttribute("fill","transparent"),i.append(n),this.container.append(i),!t.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class Ic extends ot{#t=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("squareAnnotation");const{data:t,width:e,height:s}=this,i=this.svgFactory.create(e,s,!0),n=t.borderStyle.width,r=this.#t=this.svgFactory.createElement("svg:rect");return r.setAttribute("x",n/2),r.setAttribute("y",n/2),r.setAttribute("width",e-n),r.setAttribute("height",s-n),r.setAttribute("stroke-width",n||1),r.setAttribute("stroke","transparent"),r.setAttribute("fill","transparent"),i.append(r),this.container.append(i),!t.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class Dc extends ot{#t=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("circleAnnotation");const{data:t,width:e,height:s}=this,i=this.svgFactory.create(e,s,!0),n=t.borderStyle.width,r=this.#t=this.svgFactory.createElement("svg:ellipse");return r.setAttribute("cx",e/2),r.setAttribute("cy",s/2),r.setAttribute("rx",e/2-n/2),r.setAttribute("ry",s/2-n/2),r.setAttribute("stroke-width",n||1),r.setAttribute("stroke","transparent"),r.setAttribute("fill","transparent"),i.append(r),this.container.append(i),!t.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class Gr extends ot{#t=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="polylineAnnotation",this.svgElementName="svg:polyline"}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,vertices:e,borderStyle:s,popupRef:i},width:n,height:r}=this;if(!e)return this.container;const a=this.svgFactory.create(n,r,!0);let o=[];for(let c=0,h=e.length;c<h;c+=2){const u=e[c]-t[0],f=t[3]-e[c+1];o.push(`${u},${f}`)}o=o.join(" ");const l=this.#t=this.svgFactory.createElement(this.svgElementName);return l.setAttribute("points",o),l.setAttribute("stroke-width",s.width||1),l.setAttribute("stroke","transparent"),l.setAttribute("fill","transparent"),a.append(l),this.container.append(a),!i&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class Nc extends Gr{constructor(t){super(t),this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}}class Fc extends ot{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){return this.container.classList.add("caretAnnotation"),!this.data.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}}class Ji extends ot{#t=null;#e=[];constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline",this.annotationEditorType=this.data.it==="InkHighlight"?G.HIGHLIGHT:G.INK}#s(t,e){switch(t){case 90:return{transform:`rotate(90) translate(${-e[0]},${e[1]}) scale(1,-1)`,width:e[3]-e[1],height:e[2]-e[0]};case 180:return{transform:`rotate(180) translate(${-e[2]},${e[1]}) scale(1,-1)`,width:e[2]-e[0],height:e[3]-e[1]};case 270:return{transform:`rotate(270) translate(${-e[2]},${e[3]}) scale(1,-1)`,width:e[3]-e[1],height:e[2]-e[0]};default:return{transform:`translate(${-e[0]},${e[3]}) scale(1,-1)`,width:e[2]-e[0],height:e[3]-e[1]}}}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,rotation:e,inkLists:s,borderStyle:i,popupRef:n}}=this,{transform:r,width:a,height:o}=this.#s(e,t),l=this.svgFactory.create(a,o,!0),c=this.#t=this.svgFactory.createElement("svg:g");l.append(c),c.setAttribute("stroke-width",i.width||1),c.setAttribute("stroke-linecap","round"),c.setAttribute("stroke-linejoin","round"),c.setAttribute("stroke-miterlimit",10),c.setAttribute("stroke","transparent"),c.setAttribute("fill","transparent"),c.setAttribute("transform",r);for(let h=0,u=s.length;h<u;h++){const f=this.svgFactory.createElement(this.svgElementName);this.#e.push(f),f.setAttribute("points",s[h].join(",")),c.append(f)}return!n&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.append(l),this._editOnDoubleClick(),this.container}updateEdited(t){super.updateEdited(t);const{thickness:e,points:s,rect:i}=t,n=this.#t;if(e>=0&&n.setAttribute("stroke-width",e||1),s)for(let r=0,a=this.#e.length;r<a;r++)this.#e[r].setAttribute("points",s[r].join(","));if(i){const{transform:r,width:a,height:o}=this.#s(this.data.rotation,i);n.parentElement.setAttribute("viewBox",`0 0 ${a} ${o}`),n.setAttribute("transform",r)}}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add("highlightArea")}}class Vr extends ot{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0}),this.annotationEditorType=G.HIGHLIGHT}render(){const{data:{overlaidText:t,popupRef:e}}=this;if(!e&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.classList.add("highlightAnnotation"),this._editOnDoubleClick(),t){const s=document.createElement("mark");s.classList.add("overlaidText"),s.textContent=t,this.container.append(s)}return this.container}}class Lc extends ot{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){const{data:{overlaidText:t,popupRef:e}}=this;if(!e&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.classList.add("underlineAnnotation"),t){const s=document.createElement("u");s.classList.add("overlaidText"),s.textContent=t,this.container.append(s)}return this.container}}class Rc extends ot{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){const{data:{overlaidText:t,popupRef:e}}=this;if(!e&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.classList.add("squigglyAnnotation"),t){const s=document.createElement("u");s.classList.add("overlaidText"),s.textContent=t,this.container.append(s)}return this.container}}class Oc extends ot{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){const{data:{overlaidText:t,popupRef:e}}=this;if(!e&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.classList.add("strikeoutAnnotation"),t){const s=document.createElement("s");s.classList.add("overlaidText"),s.textContent=t,this.container.append(s)}return this.container}}class Wr extends ot{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.annotationEditorType=G.STAMP}render(){return this.container.classList.add("stampAnnotation"),this.container.setAttribute("role","img"),!this.data.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this._editOnDoubleClick(),this.container}}class Bc extends ot{#t=null;constructor(t){super(t,{isRenderable:!0});const{fileId:e,file:s}=this.data;this.filename=s.filename,this.content=s.content,this.fileId=e,this.linkService.eventBus?.dispatch("fileattachmentannotation",{source:this,attachmentId:this.fileId,...s})}render(){this.container.classList.add("fileAttachmentAnnotation");const{container:t,data:e}=this;let s;e.hasAppearance||e.fillAlpha===0?s=document.createElement("div"):(s=document.createElement("img"),s.src=`${this.imageResourcesPath}annotation-${/paperclip/i.test(e.name)?"paperclip":"pushpin"}.svg`,e.fillAlpha&&e.fillAlpha<1&&(s.style=`filter: opacity(${Math.round(e.fillAlpha*100)}%);`)),s.addEventListener("dblclick",this.#e.bind(this)),this.#t=s;const{isMac:i}=J.platform;return t.addEventListener("keydown",n=>{n.key==="Enter"&&(i?n.metaKey:n.ctrlKey)&&this.#e()}),!e.popupRef&&this.hasPopupData?(this.hasOwnCommentButton=!0,this._createPopup()):s.classList.add("popupTriggerArea"),t.append(s),t}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}async#e(){const{fileId:t,filename:e,content:s}=this,i=await this.linkService.getAttachmentContent(t)||s;i&&this.downloadManager?.openOrDownloadData(i,e)}}class Xr extends ot{#t=new AbortController;#e=null;#s=null;constructor(t){super(t,{isRenderable:!!t.data.richMedia})}render(){this.container.classList.add("mediaAnnotation");const{filename:t}=this.data.richMedia,e=document.createElement("button");return e.className="mediaPlayButton",e.type="button",e.title=e.ariaLabel=t,e.addEventListener("click",()=>this.#i(e),{signal:this.#t.signal}),this.container.append(e),this.container}async#i(t){const{fileId:e,filename:s,contentType:i}=this.data.richMedia;t.disabled=!0;let n;try{n=await this.linkService.getAttachmentContent(e)}catch{return}finally{t.disabled=!1}if(!n||!t.isConnected)return;const{signal:r}=this.#t,a=URL.createObjectURL(new Blob([n],{type:i}));this.#e=a;const o=i.startsWith("audio/"),l=document.createElement(o?"audio":"video");if(this.#s=l,l.className="mediaContent",this._setBackgroundColor(l),l.src=a,l.title=s,l.controls=!0,l.autoplay=!0,l.tabIndex=0,o){let c=!1,h=!1;const u=()=>{l.controls=c||h};this.container.addEventListener("pointerenter",()=>{c=!0,u()},{signal:r}),this.container.addEventListener("pointerleave",()=>{c=!1,u()},{signal:r}),this.container.addEventListener("focusin",()=>{h=!0,u()},{signal:r}),this.container.addEventListener("focusout",()=>{h=!1,u()},{signal:r})}l.addEventListener("emptied",()=>this.#n(a),{once:!0,signal:r}),t.replaceWith(l),l.play().catch(()=>{})}#n(t=this.#e){t&&t===this.#e&&(URL.revokeObjectURL(t),this.#e=null)}destroy(){this.#t.abort(),this.#s&&(this.#s.pause(),this.#s.removeAttribute("src"),this.#s.load(),this.#s=null),this.#n()}}class Zi{#t=null;#e=null;#s=null;#i=new Map;#n=null;#a=null;#r=[];#o=!1;zIndex=0;constructor({div:t,accessibilityManager:e,annotationCanvasMap:s,annotationEditorUIManager:i,page:n,viewport:r,structTreeLayer:a,commentManager:o,linkService:l,annotationStorage:c}){this.div=t,this.#t=e,this.#e=s,this.#n=a||null,this.#a=l||null,this.#s=c||new Wi,this.page=n,this.viewport=r,this._annotationEditorUIManager=i,this._commentManager=o||null}hasEditableAnnotations(){return this.#i.size>0}async render(t){const{annotations:e,optionalContentConfig:s}=t,i=this.div;xe(i,this.viewport);const n=new Map,r=[],a={data:null,layer:i,linkService:this.#a,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:t.renderForms!==!1,svgFactory:new Os,annotationStorage:this.#s,enableComment:t.enableComment===!0,enableScripting:t.enableScripting===!0,hasJSActions:t.hasJSActions,fieldObjects:t.fieldObjects,parent:this,elements:null};for(const o of e){if(o.noHTML)continue;const l=o.annotationType===ft.POPUP;if(l){const u=n.get(o.id);if(!u)continue;if(!this._commentManager){r.push(o);continue}a.elements=u}else if(o.rect[2]===o.rect[0]||o.rect[3]===o.rect[1])continue;a.data=o;const c=vi.create(a);if(!c.isRenderable)continue;l||(this.#r.push(c),o.popupRef&&n.getOrInsertComputed(o.popupRef,ls).push(c));const h=c.render();o.hidden&&(h.style.visibility="hidden"),c.updateOC(s),c._isEditable&&(this.#i.set(c.data.id,c),this._annotationEditorUIManager?.renderAnnotationElement(c))}await this.#h();for(const o of r){const l=a.elements=n.get(o.id);a.data=o;const c=vi.create(a);if(!c.isRenderable)continue;const h=c.render();c.contentElement.id=`${Fe}${o.id}`,o.hidden&&(h.style.visibility="hidden"),l.at(-1).container.after(h)}this.#l()}async#h(){if(this.#r.length===0)return;this.div.replaceChildren();const t=[];if(!this.#o){this.#o=!0;for(const{contentElement:s,data:{id:i}}of this.#r){const n=s.id=`${Fe}${i}`;t.push(this.#n?.getAriaAttributes(n).then(r=>{if(r)for(const[a,o]of r)s.setAttribute(a,o)}))}}this.#r.sort(({data:{rect:[s,i,n,r]}},{data:{rect:[a,o,l,c]}})=>{if(s===n&&i===r)return 1;if(a===l&&o===c)return-1;const h=r,u=i,f=(i+r)/2,p=c,g=o,m=(o+c)/2;if(f>=p&&m<=u)return-1;if(m>=h&&f<=g)return 1;const b=(s+n)/2,y=(a+l)/2;return b-y});const e=document.createDocumentFragment();for(const s of this.#r)e.append(s.container),this._commentManager?(s.extraPopupElement?.popup||s.popup)?.renderCommentButton():s.extraPopupElement&&e.append(s.extraPopupElement.render());if(this.div.append(e),await Promise.all(t),this.#t)for(const s of this.#r)this.#t.addPointerInTextLayer(s.contentElement,!1)}async addLinkAnnotations(t){const e={data:null,layer:this.div,linkService:this.#a,svgFactory:new Os,parent:this};for(const s of t){s.borderStyle||=Zi._defaultBorderStyle,e.data=s;const i=vi.create(e);i.isRenderable&&(i.render(),i.contentElement.id=`${Fe}${s.id}`,this.#r.push(i))}await this.#h()}update({viewport:t,optionalContentConfig:e}){const s=this.div;this.viewport=t,xe(s,{rotation:t.rotation});for(const i of this.#r)i.updateOC(e);this.#l(),s.hidden=!1}destroy(){for(const t of this.#r)t.destroy?.(),this.#t?.removePointerInTextLayer(t.contentElement);this.#r.length=0,this.#i.clear(),this.div.replaceChildren()}#l(){if(!this.#e)return;const t=this.div;for(const[e,s]of this.#e){const i=t.querySelector(`[data-annotation-id="${e}"]`);if(!i)continue;if(Array.isArray(s))for(const l of s)l.className="annotationContent",l.ariaHidden=!0;else s.className="annotationContent",s.ariaHidden=!0;const n=[];for(const l of i.children)l.nodeName==="CANVAS"&&n.push(l);for(const l of n)l.remove();const r=Array.isArray(s)?s[0]:s,{firstChild:a}=i;if(a?a.classList.contains("annotationContent")?a.after(r):a.before(r):i.append(r),Array.isArray(s)){let l=r;for(let c=1,h=s.length;c<h;c++)l.after(s[c]),l=s[c]}this.#e.delete(e);const o=this.#i.get(e);o&&(o._hasNoCanvas?(this._annotationEditorUIManager?.setMissingCanvas(e,i.id,s),o._hasNoCanvas=!1):o.canvas=s)}}refreshCanvases(){this.#l()}getEditableAnnotations(){return this.#i.values()}getEditableAnnotation(t){return this.#i.get(t)}addFakeAnnotation(t){const{div:e}=this,{id:s,rotation:i}=t,n=new xc({data:{id:s,rect:t.getPDFRect(),rotation:i},editor:t,layer:e,parent:this,enableComment:!!this._commentManager,linkService:this.#a,annotationStorage:this.#s});return n.render(),n.contentElement.id=`${Fe}${s}`,n.createOrUpdatePopup(),this.#r.push(n),n}removeAnnotation(t){const e=this.#r.findIndex(i=>i.data.id===t);if(e<0)return;const[s]=this.#r.splice(e,1);this.#t?.removePointerInTextLayer(s.contentElement)}updateFakeAnnotations(t){if(t.length!==0){for(const e of t)e.updateFakeAnnotationElement(this);this.#h()}}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}static get _defaultBorderStyle(){return z(this,"_defaultBorderStyle",Object.freeze({width:1,rawWidth:1,style:Ie.SOLID,dashArray:[3],horizontalCornerRadius:0,verticalCornerRadius:0}))}}const _s=/\r\n?|\n/g;class At extends N{#t="";#e=`${this.id}-editor`;#s=null;#i;_colorPicker=null;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){const t=At.prototype,e=n=>n.isEmpty(),s=ae.TRANSLATE_SMALL,i=ae.TRANSLATE_BIG;return z(this,"_keyboardManager",new It([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],t.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter"],t.commitOrRemove],[["Escape"],t.commitOrRemove],[["ArrowLeft"],t._translateEmpty,{args:[-s,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t._translateEmpty,{args:[-i,0],checker:e}],[["ArrowRight"],t._translateEmpty,{args:[s,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t._translateEmpty,{args:[i,0],checker:e}],[["ArrowUp"],t._translateEmpty,{args:[0,-s],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t._translateEmpty,{args:[0,-i],checker:e}],[["ArrowDown"],t._translateEmpty,{args:[0,s],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t._translateEmpty,{args:[0,i],checker:e}]]))}static _type="freetext";static _editorType=G.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"}),this.color=t.color||At._defaultColor||N._defaultLineColor,this.#i=t.fontSize||At._defaultFontSize,this.annotationElementId||this._uiManager.a11yAlert(N._l10nAlert.freetext),this.canAddComment=!1}static initialize(t,e){N.initialize(t,e);const s=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(s.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,e){switch(t){case X.FREETEXT_SIZE:At._defaultFontSize=e;break;case X.FREETEXT_COLOR:At._defaultColor=e;break}}updateParams(t,e){switch(t){case X.FREETEXT_SIZE:this.#n(e);break;case X.FREETEXT_COLOR:this.#a(e);break}}static get defaultPropertiesToUpdate(){return[[X.FREETEXT_SIZE,At._defaultFontSize],[X.FREETEXT_COLOR,At._defaultColor||N._defaultLineColor]]}get propertiesToUpdate(){return[[X.FREETEXT_SIZE,this.#i],[X.FREETEXT_COLOR,this.color]]}get toolbarButtons(){return this._colorPicker||=new rs(this),[["colorPicker",this._colorPicker]]}get colorType(){return X.FREETEXT_COLOR}#n(t){const e=i=>{this.editorDiv.style.fontSize=`calc(${i}px * var(--total-scale-factor))`,this.translate(0,-(i-this.#i)*this.parentScale),this.#i=i,this.#o()},s=this.#i;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:X.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}onUpdatedColor(){this.editorDiv.style.color=this.color,this._colorPicker?.update(this.color),super.onUpdatedColor()}#a(t){const e=i=>{this.color=i,this.onUpdatedColor()},s=this.color;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:X.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(t,e){this._uiManager.translateSelectedEditors(t,e,!0)}getInitialTranslation(){const t=this.parentScale;return[-At._internalPadding*t,-(At._internalPadding+this.#i)*t]}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.#s=new AbortController;const t=this._uiManager.combinedSignal(this.#s);return this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:t}),this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:t}),this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:t}),this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:t}),this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:t}),!0}disableEditMode(){return super.disableEditMode()?(this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",this.#e),this._isDraggable=!0,this.#s?.abort(),this.#s=null,this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add("freetextEditing"),!0):!1}focusin(t){this._focusEventsAllowed&&(super.focusin(t),t.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(t){this.width||(this.enableEditMode(),t&&this.editorDiv.focus(),this._initialOptions?.isCentered&&this.center(),this._initialOptions=null)}isEmpty(){return!this.editorDiv||this.editorDiv.innerText.trim()===""}remove(){this.isEditing=!1,this.parent&&(this.parent.setEditingState(!0),this.parent.div.classList.add("freetextEditing")),super.remove()}#r(){const t=[];this.editorDiv.normalize();let e=null;for(const s of this.editorDiv.childNodes)e?.nodeType===Node.TEXT_NODE&&s.nodeName==="BR"||(t.push(At.#h(s)),e=s);return t.join(`
|
|
48
|
+
`)}#o(){const[t,e]=this.parentDimensions;let s;if(this.isAttachedToDOM)s=this.div.getBoundingClientRect();else{const{currentLayer:i,div:n}=this,r=n.style.display,a=n.classList.contains("hidden");n.classList.remove("hidden"),n.style.display="hidden",i.div.append(this.div),s=n.getBoundingClientRect(),n.remove(),n.style.display=r,n.classList.toggle("hidden",a)}this.rotation%180===this.parentRotation%180?(this.width=s.width/t,this.height=s.height/e):(this.width=s.height/t,this.height=s.width/e),this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();const t=this.#t,e=this.#t=this.#r().trimEnd();if(t===e)return;const s=i=>{if(this.#t=i,!i){this.remove();return}this.#l(),this._uiManager.rebuild(this),this.#o()};this.addCommands({cmd:()=>{s(e)},undo:()=>{s(t)},mustExec:!1}),this.#o()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode(),this.editorDiv.focus()}keydown(t){t.target===this.div&&t.key==="Enter"&&(this.enterInEditMode(),t.preventDefault())}editorDivKeydown(t){At._keyboardManager.exec(this,t)}editorDivFocus(t){this.isEditing=!0}editorDivBlur(t){this.isEditing=!1}editorDivInput(t){this.parent.div.classList.toggle("freetextEditing",this.isEmpty())}disableEditing(){this.editorDiv.setAttribute("role","comment"),this.editorDiv.removeAttribute("aria-multiline")}enableEditing(){this.editorDiv.setAttribute("role","textbox"),this.editorDiv.setAttribute("aria-multiline",!0)}get canChangeContent(){return!0}render(){if(this.div)return this.div;let t,e;(this._isCopy||this.annotationElementId)&&(t=this.x,e=this.y),super.render(),this.editorDiv=document.createElement("div"),this.editorDiv.className="internal",this.editorDiv.setAttribute("id",this.#e),this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text2"),this.editorDiv.setAttribute("data-l10n-attrs","default-content"),this.enableEditing(),this.editorDiv.contentEditable=!0;const{style:s}=this.editorDiv;if(s.fontSize=`calc(${this.#i}px * var(--total-scale-factor))`,s.color=this.color,this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),this._isCopy||this.annotationElementId){const[i,n]=this.parentDimensions;if(this.annotationElementId){const{position:r}=this._initialData;let[a,o]=this.getInitialTranslation();[a,o]=this.pageTranslationToScreen(a,o);const[l,c]=this.pageDimensions,[h,u]=this.pageTranslation;let f,p;switch(this.rotation){case 0:f=t+(r[0]-h)/l,p=e+this.height-(r[1]-u)/c;break;case 90:f=t+(r[0]-h)/l,p=e-(r[1]-u)/c,[a,o]=[o,-a];break;case 180:f=t-this.width+(r[0]-h)/l,p=e-(r[1]-u)/c,[a,o]=[-a,-o];break;case 270:f=t+(r[0]-h-this.height*c)/l,p=e+(r[1]-u-this.width*l)/c,[a,o]=[-o,a];break}this.setAt(f*i,p*n,a,o)}else this._moveAfterPaste(t,e);this.#l(),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}static#h(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(_s,"")}editorDivPaste(t){const e=t.clipboardData||window.clipboardData,{types:s}=e;if(s.length===1&&s[0]==="text/plain")return;t.preventDefault();const i=At.#d(e.getData("text")||"").replaceAll(_s,`
|
|
49
|
+
`);if(!i)return;const n=window.getSelection();if(!n.rangeCount)return;this.editorDiv.normalize(),n.deleteFromDocument();const r=n.getRangeAt(0);if(!i.includes(`
|
|
50
|
+
`)){r.insertNode(document.createTextNode(i)),this.editorDiv.normalize(),n.collapseToStart();return}const{startContainer:a,startOffset:o}=r,l=[],c=[];if(a.nodeType===Node.TEXT_NODE){const f=a.parentElement;if(c.push(a.nodeValue.slice(o).replaceAll(_s,"")),f!==this.editorDiv){let p=l;for(const g of this.editorDiv.childNodes){if(g===f){p=c;continue}p.push(At.#h(g))}}l.push(a.nodeValue.slice(0,o).replaceAll(_s,""))}else if(a===this.editorDiv){let f=l,p=0;for(const g of this.editorDiv.childNodes)p++===o&&(f=c),f.push(At.#h(g))}this.#t=`${l.join(`
|
|
51
|
+
`)}${i}${c.join(`
|
|
52
|
+
`)}`,this.#l();const h=new Range;let u=Math.sumPrecise(l.map(f=>f.length));for(const{firstChild:f}of this.editorDiv.childNodes)if(f.nodeType===Node.TEXT_NODE){const p=f.nodeValue.length;if(u<=p){h.setStart(f,u),h.setEnd(f,u);break}u-=p}n.removeAllRanges(),n.addRange(h)}#l(){if(this.editorDiv.replaceChildren(),!!this.#t)for(const t of this.#t.split(`
|
|
53
|
+
`)){const e=document.createElement("div");e.append(t?document.createTextNode(t):document.createElement("br")),this.editorDiv.append(e)}}#u(){return this.#t.replaceAll(" "," ")}static#d(t){return t.replaceAll(" "," ")}get contentDiv(){return this.editorDiv}getPDFRect(){const t=At._internalPadding*this.parentScale;return this.getRect(t,t)}static async deserialize(t,e,s){let i=null;if(t instanceof $r){const{data:{defaultAppearanceData:{fontSize:r,fontColor:a},rect:o,rotation:l,id:c,popupRef:h,richText:u,contentsObj:f,creationDate:p,modificationDate:g},textContent:m,textPosition:b,parent:{page:{pageNumber:y}}}=t;if(!m?.length)return null;i=t={annotationType:G.FREETEXT,color:Array.from(a),fontSize:r,value:m.join(`
|
|
54
|
+
`),position:b,pageIndex:y-1,rect:o.slice(0),rotation:l,annotationElementId:c,id:c,deleted:!1,popupRef:h,comment:f?.str||null,richText:u,creationDate:p,modificationDate:g}}const n=await super.deserialize(t,e,s);return n.#i=t.fontSize,n.color=T.makeHexColor(...t.color),n.#t=At.#d(t.value),n._initialData=i,t.comment&&n.setCommentData(t),n}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const e=N._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.color),s=Object.assign(super.serialize(t),{color:e,fontSize:this.#i,value:this.#u()});return this.addComment(s),t?(s.isCopy=!0,s):this.annotationElementId&&!this.#p(s)?null:(s.id=this.annotationElementId,s)}#p(t){const{value:e,fontSize:s,color:i,pageIndex:n}=this._initialData;return this.hasEditedComment||this._hasBeenMoved||t.value!==e||t.fontSize!==s||t.color.some((r,a)=>r!==i[a])||t.pageIndex!==n}renderAnnotationElement(t){const e=super.renderAnnotationElement(t);if(!e)return null;const{style:s}=e;s.fontSize=`calc(${this.#i}px * var(--total-scale-factor))`,s.color=this.color,e.replaceChildren();for(const i of this.#t.split(`
|
|
55
|
+
`)){const n=document.createElement("div");n.append(i?document.createTextNode(i):document.createElement("br")),e.append(n)}return t.updateEdited({rect:this.getPDFRect(),popup:this._uiManager.hasCommentManager()||this.hasEditedComment?this.comment:{text:this.#t}}),e}resetAnnotationElement(t){super.resetAnnotationElement(t),t.resetEdited()}}class D{static PRECISION=1e-4;toSVGPath(){K("Abstract method `toSVGPath` must be implemented.")}get box(){K("Abstract getter `box` must be implemented.")}serialize(t,e){K("Abstract method `serialize` must be implemented.")}static _rescale(t,e,s,i,n,r){r||=new Float32Array(t.length);for(let a=0,o=t.length;a<o;a+=2)r[a]=e+t[a]*i,r[a+1]=s+t[a+1]*n;return r}static _rescaleAndSwap(t,e,s,i,n,r){r||=new Float32Array(t.length);for(let a=0,o=t.length;a<o;a+=2)r[a]=e+t[a+1]*i,r[a+1]=s+t[a]*n;return r}static _translate(t,e,s,i){i||=new Float32Array(t.length);for(let n=0,r=t.length;n<r;n+=2)i[n]=e+t[n],i[n+1]=s+t[n+1];return i}static svgRound(t){return Math.round(t*1e4)}static _normalizePoint(t,e,s,i,n){switch(n){case 90:return[1-e/s,t/i];case 180:return[1-t/s,1-e/i];case 270:return[e/s,1-t/i];default:return[t/s,e/i]}}static createBezierPoints(t,e,s,i,n,r){return[(t+5*s)/6,(e+5*i)/6,(5*s+n)/6,(5*i+r)/6,(s+n)/2,(i+r)/2]}}class be{#t;#e=[];#s;#i;#n=[];#a=new Float32Array(18);#r;#o;#h;#l;#u;#d;#p=[];static#m=8;static#g=2;static#c=be.#m+be.#g;constructor({x:t,y:e},s,i,n,r,a=0){this.#t=s,this.#d=n*i,this.#i=r,this.#a.set([NaN,NaN,NaN,NaN,t,e],6),this.#s=a,this.#l=be.#m*i,this.#h=be.#c*i,this.#u=i,this.#p.push(t,e)}isEmpty(){return isNaN(this.#a[8])}#f(){const t=this.#a.subarray(4,6),e=this.#a.subarray(16,18),[s,i,n,r]=this.#t;return[(this.#r+(t[0]-e[0])/2-s)/n,(this.#o+(t[1]-e[1])/2-i)/r,(this.#r+(e[0]-t[0])/2-s)/n,(this.#o+(e[1]-t[1])/2-i)/r]}add({x:t,y:e}){this.#r=t,this.#o=e;const[s,i,n,r]=this.#t;let[a,o,l,c]=this.#a.subarray(8,12);const h=t-l,u=e-c,f=Math.hypot(h,u);if(f<this.#h)return!1;const p=f-this.#l,g=p/f,m=g*h,b=g*u;let y=a,A=o;a=l,o=c,l+=m,c+=b,this.#p?.push(t,e);const w=-b/p,x=m/p,S=w*this.#d,E=x*this.#d;return this.#a.set(this.#a.subarray(2,8),0),this.#a.set([l+S,c+E],4),this.#a.set(this.#a.subarray(14,18),12),this.#a.set([l-S,c-E],16),isNaN(this.#a[6])?(this.#n.length===0&&(this.#a.set([a+S,o+E],2),this.#n.push(NaN,NaN,NaN,NaN,(a+S-s)/n,(o+E-i)/r),this.#a.set([a-S,o-E],14),this.#e.push(NaN,NaN,NaN,NaN,(a-S-s)/n,(o-E-i)/r)),this.#a.set([y,A,a,o,l,c],6),!this.isEmpty()):(this.#a.set([y,A,a,o,l,c],6),Math.abs(Math.atan2(A-o,y-a)-Math.atan2(b,m))<Math.PI/2?([a,o,l,c]=this.#a.subarray(2,6),this.#n.push(NaN,NaN,NaN,NaN,((a+l)/2-s)/n,((o+c)/2-i)/r),[a,o,y,A]=this.#a.subarray(14,18),this.#e.push(NaN,NaN,NaN,NaN,((y+a)/2-s)/n,((A+o)/2-i)/r),!0):([y,A,a,o,l,c]=this.#a.subarray(0,6),this.#n.push(((y+5*a)/6-s)/n,((A+5*o)/6-i)/r,((5*a+l)/6-s)/n,((5*o+c)/6-i)/r,((a+l)/2-s)/n,((o+c)/2-i)/r),[l,c,a,o,y,A]=this.#a.subarray(12,18),this.#e.push(((y+5*a)/6-s)/n,((A+5*o)/6-i)/r,((5*a+l)/6-s)/n,((5*o+c)/6-i)/r,((a+l)/2-s)/n,((o+c)/2-i)/r),!0))}toSVGPath(){if(this.isEmpty())return"";const t=this.#n,e=this.#e;if(isNaN(this.#a[6])&&!this.isEmpty())return this.#y();const s=[];s.push(`M${t[4]} ${t[5]}`);for(let i=6;i<t.length;i+=6)isNaN(t[i])?s.push(`L${t[i+4]} ${t[i+5]}`):s.push(`C${t[i]} ${t[i+1]} ${t[i+2]} ${t[i+3]} ${t[i+4]} ${t[i+5]}`);this.#b(s);for(let i=e.length-6;i>=6;i-=6)isNaN(e[i])?s.push(`L${e[i+4]} ${e[i+5]}`):s.push(`C${e[i]} ${e[i+1]} ${e[i+2]} ${e[i+3]} ${e[i+4]} ${e[i+5]}`);return this.#v(s),s.join(" ")}#y(){const[t,e,s,i]=this.#t,[n,r,a,o]=this.#f();return`M${(this.#a[2]-t)/s} ${(this.#a[3]-e)/i} L${(this.#a[4]-t)/s} ${(this.#a[5]-e)/i} L${n} ${r} L${a} ${o} L${(this.#a[16]-t)/s} ${(this.#a[17]-e)/i} L${(this.#a[14]-t)/s} ${(this.#a[15]-e)/i} Z`}#v(t){const e=this.#e;t.push(`L${e[4]} ${e[5]} Z`)}#b(t){const[e,s,i,n]=this.#t,r=this.#a.subarray(4,6),a=this.#a.subarray(16,18),[o,l,c,h]=this.#f();t.push(`L${(r[0]-e)/i} ${(r[1]-s)/n} L${o} ${l} L${c} ${h} L${(a[0]-e)/i} ${(a[1]-s)/n}`)}newFreeDrawOutline(t,e,s,i,n,r){return new Yr(t,e,s,i,n,r)}getOutlines(){const t=this.#n,e=this.#e,s=this.#a,[i,n,r,a]=this.#t,o=new Float32Array((this.#p?.length??0)+2);for(let h=0,u=o.length-2;h<u;h+=2)o[h]=(this.#p[h]-i)/r,o[h+1]=(this.#p[h+1]-n)/a;if(o[o.length-2]=(this.#r-i)/r,o[o.length-1]=(this.#o-n)/a,isNaN(s[6])&&!this.isEmpty())return this.#S(o);const l=new Float32Array(this.#n.length+24+this.#e.length);let c=t.length;for(let h=0;h<c;h+=2){if(isNaN(t[h])){l[h]=l[h+1]=NaN;continue}l[h]=t[h],l[h+1]=t[h+1]}c=this.#A(l,c);for(let h=e.length-6;h>=6;h-=6)for(let u=0;u<6;u+=2){if(isNaN(e[h+u])){l[c]=l[c+1]=NaN,c+=2;continue}l[c]=e[h+u],l[c+1]=e[h+u+1],c+=2}return this.#C(l,c),this.newFreeDrawOutline(l,o,this.#t,this.#u,this.#s,this.#i)}#S(t){const e=this.#a,[s,i,n,r]=this.#t,[a,o,l,c]=this.#f(),h=new Float32Array(36);return h.set([NaN,NaN,NaN,NaN,(e[2]-s)/n,(e[3]-i)/r,NaN,NaN,NaN,NaN,(e[4]-s)/n,(e[5]-i)/r,NaN,NaN,NaN,NaN,a,o,NaN,NaN,NaN,NaN,l,c,NaN,NaN,NaN,NaN,(e[16]-s)/n,(e[17]-i)/r,NaN,NaN,NaN,NaN,(e[14]-s)/n,(e[15]-i)/r],0),this.newFreeDrawOutline(h,t,this.#t,this.#u,this.#s,this.#i)}#C(t,e){const s=this.#e;return t.set([NaN,NaN,NaN,NaN,s[4],s[5]],e),e+=6}#A(t,e){const s=this.#a.subarray(4,6),i=this.#a.subarray(16,18),[n,r,a,o]=this.#t,[l,c,h,u]=this.#f();return t.set([NaN,NaN,NaN,NaN,(s[0]-n)/a,(s[1]-r)/o,NaN,NaN,NaN,NaN,l,c,NaN,NaN,NaN,NaN,h,u,NaN,NaN,NaN,NaN,(i[0]-n)/a,(i[1]-r)/o],e),e+=24}}class Yr extends D{#t;#e=new Float32Array(4);#s;#i;#n;#a;#r;constructor(t,e,s,i,n,r){super(),this.#r=t,this.#n=e,this.#t=s,this.#a=i,this.#s=n,this.#i=r,this.firstPoint=[NaN,NaN],this.lastPoint=[NaN,NaN],this.#o(r);const[a,o,l,c]=this.#e;for(let h=0,u=t.length;h<u;h+=2)t[h]=(t[h]-a)/l,t[h+1]=(t[h+1]-o)/c;for(let h=0,u=e.length;h<u;h+=2)e[h]=(e[h]-a)/l,e[h+1]=(e[h+1]-o)/c}toSVGPath(){const t=[`M${this.#r[4]} ${this.#r[5]}`];for(let e=6,s=this.#r.length;e<s;e+=6){if(isNaN(this.#r[e])){t.push(`L${this.#r[e+4]} ${this.#r[e+5]}`);continue}t.push(`C${this.#r[e]} ${this.#r[e+1]} ${this.#r[e+2]} ${this.#r[e+3]} ${this.#r[e+4]} ${this.#r[e+5]}`)}return t.push("Z"),t.join(" ")}serialize([t,e,s,i],n){const r=s-t,a=i-e;let o,l;switch(n){case 0:o=D._rescale(this.#r,t,i,r,-a),l=D._rescale(this.#n,t,i,r,-a);break;case 90:o=D._rescaleAndSwap(this.#r,t,e,r,a),l=D._rescaleAndSwap(this.#n,t,e,r,a);break;case 180:o=D._rescale(this.#r,s,e,-r,a),l=D._rescale(this.#n,s,e,-r,a);break;case 270:o=D._rescaleAndSwap(this.#r,s,i,-r,-a),l=D._rescaleAndSwap(this.#n,s,i,-r,-a);break}return{outline:Array.from(o),points:[Array.from(l)]}}#o(t){const e=this.#r;let s=e[4],i=e[5];const n=[s,i,s,i];let r=s,a=i,o=s,l=i;const c=t?Math.max:Math.min,h=new Float32Array(4);for(let f=6,p=e.length;f<p;f+=6){const g=e[f+4],m=e[f+5];isNaN(e[f])?(T.pointBoundingBox(g,m,n),a>m?(r=g,a=m):a===m&&(r=c(r,g)),l<m?(o=g,l=m):l===m&&(o=c(o,g))):(h.set(te,0),T.bezierBoundingBox(s,i,...e.slice(f,f+6),h),T.rectBoundingBox(...h,n),a>h[1]?(r=h[0],a=h[1]):a===h[1]&&(r=c(r,h[0])),l<h[3]?(o=h[2],l=h[3]):l===h[3]&&(o=c(o,h[2]))),s=g,i=m}const u=this.#e;u[0]=n[0]-this.#s,u[1]=n[1]-this.#s,u[2]=n[2]-n[0]+2*this.#s,u[3]=n[3]-n[1]+2*this.#s,this.firstPoint=[r,a],this.lastPoint=[o,l]}get box(){return this.#e}newOutliner(t,e,s,i,n,r=0){return new be(t,e,s,i,n,r)}getNewOutline(t,e){const[s,i,n,r]=this.#e,[a,o,l,c]=this.#t,h=n*l,u=r*c,f=s*l+a,p=i*c+o,g=this.newOutliner({x:this.#n[0]*h+f,y:this.#n[1]*u+p},this.#t,this.#a,t,this.#i,e??this.#s);for(let m=2;m<this.#n.length;m+=2)g.add({x:this.#n[m]*h+f,y:this.#n[m+1]*u+p});return g.getOutlines()}}class Ni{#t;#e;#s;#i=[];#n=[];constructor(t,e=0,s=0,i=!0){const n=te.slice(),r=10**-4;for(const{x:g,y:m,width:b,height:y}of t){const A=Math.floor((g-e)/r)*r,w=Math.ceil((g+b+e)/r)*r,x=Math.floor((m-e)/r)*r,S=Math.ceil((m+y+e)/r)*r,E=[A,x,S,!0],_=[w,x,S,!1];this.#i.push(E,_),T.rectBoundingBox(A,x,w,S,n)}const a=n[2]-n[0]+2*s,o=n[3]-n[1]+2*s,l=n[0]-s,c=n[1]-s;let h=i?-1/0:1/0,u=1/0;const f=this.#i.at(i?-1:-2),p=[f[0],f[2]];for(const g of this.#i){const[m,b,y,A]=g;!A&&i?b<u?(u=b,h=m):b===u&&(h=Math.max(h,m)):A&&!i&&(b<u?(u=b,h=m):b===u&&(h=Math.min(h,m))),g[0]=(m-l)/a,g[1]=(b-c)/o,g[2]=(y-c)/o}this.#t=new Float32Array([l,c,a,o]),this.#e=[h,u],this.#s=p}getOutlines(){this.#i.sort((e,s)=>e[0]-s[0]||e[1]-s[1]||e[2]-s[2]);const t=[];for(const e of this.#i)e[3]?(t.push(...this.#l(e)),this.#o(e)):(this.#h(e),t.push(...this.#l(e)));return this.#a(t)}#a(t){const e=[],s=new Set;for(const r of t){const[a,o,l]=r;e.push([a,o,r],[a,l,r])}e.sort((r,a)=>r[1]-a[1]||r[0]-a[0]);for(let r=0,a=e.length;r<a;r+=2){const o=e[r][2],l=e[r+1][2];o.push(l),l.push(o),s.add(o),s.add(l)}const i=[];let n;for(;s.size>0;){const r=s.values().next().value;let[a,o,l,c,h]=r;s.delete(r);let u=a,f=o;for(n=[a,l],i.push(n);;){let p;if(s.has(c))p=c;else if(s.has(h))p=h;else break;s.delete(p),[a,o,l,c,h]=p,u!==a&&(n.push(u,f,a,f===o?o:l),u=a),f=f===o?l:o}n.push(u,f)}return new jc(i,this.#t,this.#e,this.#s)}#r(t){const e=this.#n;let s=0,i=e.length-1;for(;s<=i;){const n=s+i>>1,r=e[n][0];if(r===t)return n;r<t?s=n+1:i=n-1}return i+1}#o([,t,e]){const s=this.#r(t);this.#n.splice(s,0,[t,e])}#h([,t,e]){const s=this.#r(t);for(let i=s;i<this.#n.length;i++){const[n,r]=this.#n[i];if(n!==t)break;if(n===t&&r===e){this.#n.splice(i,1);return}}for(let i=s-1;i>=0;i--){const[n,r]=this.#n[i];if(n!==t)break;if(n===t&&r===e){this.#n.splice(i,1);return}}}#l(t){const[e,s,i]=t,n=[[e,s,i]],r=this.#r(i);for(let a=0;a<r;a++){const[o,l]=this.#n[a];for(let c=0,h=n.length;c<h;c++){const[,u,f]=n[c];if(!(l<=u||f<=o)){if(u>=o){if(f>l)n[c][1]=l;else{if(h===1)return[];n.splice(c,1),c--,h--}continue}n[c][2]=o,f>l&&n.push([e,l,f])}}}return n}}class jc extends D{#t;#e;constructor(t,e,s,i){super(),this.#e=t,this.#t=e,this.firstPoint=s,this.lastPoint=i}toSVGPath(){const t=[];for(const e of this.#e){let[s,i]=e;t.push(`M${s} ${i}`);for(let n=2;n<e.length;n+=2){const r=e[n],a=e[n+1];r===s?(t.push(`V${a}`),i=a):a===i&&(t.push(`H${r}`),s=r)}t.push("Z")}return t.join(" ")}serialize([t,e,s,i],n){const r=[],a=s-t,o=i-e;for(const l of this.#e){const c=new Array(l.length);for(let h=0;h<l.length;h+=2)c[h]=t+l[h]*a,c[h+1]=i-l[h+1]*o;r.push(c)}return r}get box(){return this.#t}}class Fi extends be{newFreeDrawOutline(t,e,s,i,n,r){return new Hc(t,e,s,i,n,r)}}class Hc extends Yr{newOutliner(t,e,s,i,n,r=0){return new Fi(t,e,s,i,n,r)}}class gt extends N{#t=null;#e=0;#s;#i=null;#n=null;#a=null;#r=null;#o=0;#h=null;#l=null;#u=null;#d=!1;#p=null;#m=null;#g=null;#c="";#f;#y="";static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=12;static _type="highlight";static _editorType=G.HIGHLIGHT;static _freeHighlightId=-1;static _freeHighlight=null;static _freeHighlightClipId="";static get _keyboardManager(){const t=gt.prototype;return z(this,"_keyboardManager",new It([[["ArrowLeft"],t._moveCaret,{args:[0]}],[["ArrowRight"],t._moveCaret,{args:[1]}],[["ArrowUp"],t._moveCaret,{args:[2]}],[["ArrowDown"],t._moveCaret,{args:[3]}]]))}constructor(t){super({...t,name:"highlightEditor"}),this.color=t.color||gt._defaultColor,this.#f=t.thickness||gt._defaultThickness,this.opacity=t.opacity||gt._defaultOpacity,this.#s=t.boxes||null,this.#y=t.methodOfCreation||"",this.#c=t.text||"",this._isDraggable=!1,this.defaultL10nId="pdfjs-editor-highlight-editor",t.highlightId>-1?(this.#d=!0,this.#b(t),this.#w()):this.#s&&(this.#t=t.anchorNode,this.#e=t.anchorOffset,this.#r=t.focusNode,this.#o=t.focusOffset,this.#v(),this.#w(),this.rotate(this.rotation)),this.annotationElementId||this._uiManager.a11yAlert(N._l10nAlert.highlight)}get telemetryInitialData(){return{action:"added",type:this.#d?"free_highlight":"highlight",color:this._uiManager.getNonHCMColorName(this.color),thickness:this.#f,methodOfCreation:this.#y}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.getNonHCMColorName(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#v(){const t=new Ni(this.#s,.001);this.#l=t.getOutlines(),[this.x,this.y,this.width,this.height]=this.#l.box;const e=new Ni(this.#s,.0025,.001,this._uiManager.direction==="ltr");this.#a=e.getOutlines();const{firstPoint:s}=this.#l;this.#p=[(s[0]-this.x)/this.width,(s[1]-this.y)/this.height];const{lastPoint:i}=this.#a;this.#m=[(i[0]-this.x)/this.width,(i[1]-this.y)/this.height]}#b({highlightOutlines:t,highlightId:e,clipPathId:s}){this.#l=t;const i=1.5;if(this.#a=t.getNewOutline(this.#f/2+i,.0025),e>=0)this.#u=e,this.#i=s,this.parent.drawLayer.finalizeDraw(e,{bbox:t.box,path:{d:t.toSVGPath()}}),this.#g=this.parent.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:!0},bbox:this.#a.box,path:{d:this.#a.toSVGPath()}},!0);else if(this.parent){const h=this.parent.viewport.rotation;this.parent.drawLayer.updateProperties(this.#u,{bbox:gt.#k(this.#l.box,(h-this.rotation+360)%360),path:{d:t.toSVGPath()}}),this.parent.drawLayer.updateProperties(this.#g,{bbox:gt.#k(this.#a.box,h),path:{d:this.#a.toSVGPath()}})}const[n,r,a,o]=t.box;switch(this.rotation){case 0:this.x=n,this.y=r,this.width=a,this.height=o;break;case 90:{const[h,u]=this.parentDimensions;this.x=r,this.y=1-n,this.width=a*u/h,this.height=o*h/u;break}case 180:this.x=1-n,this.y=1-r,this.width=a,this.height=o;break;case 270:{const[h,u]=this.parentDimensions;this.x=1-r,this.y=n,this.width=a*u/h,this.height=o*h/u;break}}const{firstPoint:l}=t;this.#p=[(l[0]-n)/a,(l[1]-r)/o];const{lastPoint:c}=this.#a;this.#m=[(c[0]-n)/a,(c[1]-r)/o]}static initialize(t,e){N.initialize(t,e),gt._defaultColor||=e.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,e){switch(t){case X.HIGHLIGHT_COLOR:gt._defaultColor=e;break;case X.HIGHLIGHT_THICKNESS:gt._defaultThickness=e;break}}translateInPage(t,e){}get toolbarPosition(){return this.#m}get commentButtonPosition(){return this.#p}updateParams(t,e){switch(t){case X.HIGHLIGHT_COLOR:this.#S(e);break;case X.HIGHLIGHT_THICKNESS:this.#C(e);break}}static get defaultPropertiesToUpdate(){return[[X.HIGHLIGHT_COLOR,gt._defaultColor],[X.HIGHLIGHT_THICKNESS,gt._defaultThickness]]}get propertiesToUpdate(){return[[X.HIGHLIGHT_COLOR,this.color||gt._defaultColor],[X.HIGHLIGHT_THICKNESS,this.#f||gt._defaultThickness],[X.HIGHLIGHT_FREE,this.#d]]}onUpdatedColor(){this.parent?.drawLayer.updateProperties(this.#u,{root:{fill:this.color,"fill-opacity":this.opacity}}),this.#n?.updateColor(this.color),super.onUpdatedColor()}#S(t){const e=(n,r)=>{this.color=n,this.opacity=r,this.onUpdatedColor()},s=this.color,i=this.opacity;this.addCommands({cmd:e.bind(this,t,gt._defaultOpacity),undo:e.bind(this,s,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:X.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.getNonHCMColorName(t)},!0)}#C(t){const e=this.#f,s=i=>{this.#f=i,this.#A(i)};this.addCommands({cmd:s.bind(this,t),undo:s.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:X.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:t},!0)}get toolbarButtons(){return this._uiManager.highlightColors?[["colorPicker",this.#n=new Lt({editor:this})]]:super.toolbarButtons}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#T())}getBaseTranslation(){return[0,0]}getRect(t,e){return super.getRect(t,e,this.#T())}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),t&&this.div.focus()}remove(){this.#E(),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.#w(),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?this.#E():t&&(this.#w(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),this.show(this._isVisible),e&&this.select()}#A(t){this.#d&&(this.#b({highlightOutlines:this.#l.getNewOutline(t/2)}),this.fixAndSetPosition(),this.setDims())}#E(){this.#u===null||!this.parent||(this.parent.drawLayer.remove(this.#u),this.#u=null,this.parent.drawLayer.remove(this.#g),this.#g=null)}#w(t=this.parent){this.#u===null&&({id:this.#u,clipPathId:this.#i}=t.drawLayer.draw({bbox:this.#l.box,root:{viewBox:"0 0 1 1",fill:this.color,"fill-opacity":this.opacity},rootClass:{highlight:!0,free:this.#d},path:{d:this.#l.toSVGPath()}},!1,!0),this.#g=t.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:this.#d},bbox:this.#a.box,path:{d:this.#a.toSVGPath()}},this.#d),this.#h&&(this.#h.style.clipPath=this.#i))}static#k([t,e,s,i],n){switch(n){case 90:return[1-e-i,t,i,s];case 180:return[1-t-s,1-e-i,s,i];case 270:return[e,1-t-s,i,s]}return[t,e,s,i]}rotate(t){const{drawLayer:e}=this.parent;let s;this.#d?(t=(t-this.rotation+360)%360,s=gt.#k(this.#l.box,t)):s=gt.#k([this.x,this.y,this.width,this.height],t),e.updateProperties(this.#u,{bbox:s,root:{"data-main-rotation":t}}),e.updateProperties(this.#g,{bbox:gt.#k(this.#a.box,t),root:{"data-main-rotation":t}})}render(){if(this.div)return this.div;const t=super.render();this.#c&&(t.setAttribute("aria-label",this.#c),t.setAttribute("role","mark")),this.#d?t.classList.add("free"):this.div.addEventListener("keydown",this.#M.bind(this),{signal:this._uiManager._signal});const e=this.#h=document.createElement("div");return t.append(e),e.setAttribute("aria-hidden","true"),e.className="internal",e.style.clipPath=this.#i,this.setDims(),Er(this,this.#h,["pointerover","pointerleave"]),this.enableEditing(),t}pointerover(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#g,{rootClass:{hovered:!0}})}pointerleave(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#g,{rootClass:{hovered:!1}})}#M(t){gt._keyboardManager.exec(this,t)}_moveCaret(t){switch(this.parent.unselect(this),t){case 0:case 2:this.#P(!0);break;case 1:case 3:this.#P(!1);break}}#P(t){if(!this.#t)return;const e=window.getSelection();t?e.setPosition(this.#t,this.#e):e.setPosition(this.#r,this.#o)}select(){super.select(),this.#g&&this.parent?.drawLayer.updateProperties(this.#g,{rootClass:{hovered:!1,selected:!0}})}unselect(){super.unselect(),this.#g&&(this.parent?.drawLayer.updateProperties(this.#g,{rootClass:{selected:!1}}),this.#d||this.#P(!1))}get _mustFixPosition(){return!this.#d}show(t=this._isVisible){super.show(t),this.parent&&(this.parent.drawLayer.updateProperties(this.#u,{rootClass:{hidden:!t}}),this.parent.drawLayer.updateProperties(this.#g,{rootClass:{hidden:!t}}))}#T(){return this.#d?this.rotation:0}#N(){if(this.#d)return null;const[t,e]=this.pageDimensions,[s,i]=this.pageTranslation,n=this.#s,r=new Float32Array(n.length*8);let a=0;for(const{x:o,y:l,width:c,height:h}of n){const u=o*t+s,f=(1-l)*e+i;r[a]=r[a+4]=u,r[a+1]=r[a+3]=f,r[a+2]=r[a+6]=u+c*t,r[a+5]=r[a+7]=f-h*e,a+=8}return r}#F(t){return this.#l.serialize(t,this.#T())}static startHighlighting(t,e,{target:s,x:i,y:n}){const{x:r,y:a,width:o,height:l}=s.getBoundingClientRect(),c=new AbortController,h=t.combinedSignal(c),u=f=>{c.abort(),this.#L(t,f)};window.addEventListener("blur",u,{signal:h}),window.addEventListener("pointerup",u,{signal:h}),window.addEventListener("pointerdown",lt,{capture:!0,passive:!1,signal:h}),window.addEventListener("contextmenu",Rt,{signal:h}),s.addEventListener("pointermove",this.#D.bind(this,t),{signal:h}),this._freeHighlight=new Fi({x:i,y:n},[r,a,o,l],t.scale,this._defaultThickness/2,e,.001),{id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=t.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:this._defaultColor,"fill-opacity":this._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:this._freeHighlight.toSVGPath()}},!0,!0)}static#D(t,e){this._freeHighlight.add(e)&&t.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})}static#L(t,e){this._freeHighlight.isEmpty()?t.drawLayer.remove(this._freeHighlightId):t.createAndAddNewEditor(e,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"}),this._freeHighlightId=-1,this._freeHighlight=null,this._freeHighlightClipId=""}static async deserialize(t,e,s){let i=null;if(t instanceof Vr){const{data:{quadPoints:g,rect:m,rotation:b,id:y,color:A,opacity:w,popupRef:x,richText:S,contentsObj:E,creationDate:_,modificationDate:k},parent:{page:{pageNumber:I}}}=t;i=t={annotationType:G.HIGHLIGHT,color:Array.from(A),opacity:w,quadPoints:g,boxes:null,pageIndex:I-1,rect:m.slice(0),rotation:b,annotationElementId:y,id:y,deleted:!1,popupRef:x,richText:S,comment:E?.str||null,creationDate:_,modificationDate:k}}else if(t instanceof Ji){const{data:{inkLists:g,rect:m,rotation:b,id:y,color:A,borderStyle:{rawWidth:w},popupRef:x,richText:S,contentsObj:E,creationDate:_,modificationDate:k},parent:{page:{pageNumber:I}}}=t;i=t={annotationType:G.HIGHLIGHT,color:Array.from(A),thickness:w,inkLists:g,boxes:null,pageIndex:I-1,rect:m.slice(0),rotation:b,annotationElementId:y,id:y,deleted:!1,popupRef:x,richText:S,comment:E?.str||null,creationDate:_,modificationDate:k}}const{color:n,quadPoints:r,inkLists:a,outlines:o,opacity:l}=t,c=await super.deserialize(t,e,s);c.color=T.makeHexColor(...n),c.opacity=l||1,a&&(c.#f=t.thickness),c._initialData=i,t.comment&&c.setCommentData(t);const[h,u]=c.pageDimensions,[f,p]=c.pageTranslation;if(r){const g=c.#s=[];for(let m=0;m<r.length;m+=8)g.push({x:(r[m]-f)/h,y:1-(r[m+1]-p)/u,width:(r[m+2]-r[m])/h,height:(r[m+1]-r[m+5])/u});c.#v(),c.#w(),c.rotate(c.rotation)}else if(a||o){c.#d=!0;const g=(a||o.points)[0],m={x:g[0]-f,y:u-(g[1]-p)},b=new Fi(m,[0,0,h,u],1,c.#f/2,!0,.001);for(let w=0,x=g.length;w<x;w+=2)m.x=g[w]-f,m.y=u-(g[w+1]-p),b.add(m);const{id:y,clipPathId:A}=e.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:c.color,"fill-opacity":c._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:b.toSVGPath()}},!0,!0);c.#b({highlightOutlines:b.getOutlines(),highlightId:y,clipPathId:A}),c.#w(),c.rotate(c.parentRotation)}return c}serialize(t=!1){if(this.isEmpty()||t)return null;if(this.deleted)return this.serializeDeleted();const e=N._colorManager.convert(this._uiManager.getNonHCMColor(this.color)),s=super.serialize(t);return Object.assign(s,{color:e,opacity:this.opacity,thickness:this.#f,quadPoints:this.#N(),outlines:this.#F(s.rect)}),this.addComment(s),this.annotationElementId&&!this.#O(s)?null:(s.id=this.annotationElementId,s)}#O(t){const{color:e}=this._initialData;return this.hasEditedComment||t.color.some((s,i)=>s!==e[i])}renderAnnotationElement(t){return this.deleted?(t.hide(),null):(t.updateEdited({rect:this.getPDFRect(),popup:this.comment}),null)}static canCreateNewEmptyEditor(){return!1}}class Kr{#t=Object.create(null);updateProperty(t,e){this[t]=e,this.updateSVGProperty(t,e)}updateProperties(t){if(t)for(const[e,s]of Object.entries(t))e.startsWith("_")||this.updateProperty(e,s)}updateSVGProperty(t,e){this.#t[t]=e}toSVGProperties(){const t=this.#t;return this.#t=Object.create(null),{root:t}}reset(){this.#t=Object.create(null)}updateAll(t=this){this.updateProperties(t)}clone(){K("Not implemented")}}class q extends N{#t=null;#e;_colorPicker=null;_drawId=null;static _currentDrawId=-1;static _currentParent=null;static#s=null;static#i=null;static#n=null;static _INNER_MARGIN=3;constructor(t){super(t),this.#e=t.mustBeCommitted||!1,this._addOutlines(t)}onUpdatedColor(){this._colorPicker?.update(this.color),super.onUpdatedColor()}onUpdatedOpacity(){this._colorPicker?.updateOpacity?.(this.opacity)}_addOutlines(t){t.drawOutlines&&(this.#a(t),this.#h())}#a({drawOutlines:t,drawId:e,drawingOptions:s}){this.#t=t,this._drawingOptions||=s,this.annotationElementId||this._uiManager.a11yAlert(N._l10nAlert[this.editorType]),e>=0?(this._drawId=e,this.parent.drawLayer.finalizeDraw(e,t.defaultProperties)):this._drawId=this.#r(t,this.parent),this.#d(t.box)}#r(t,e){const{id:s}=e.drawLayer.draw(q._mergeSVGProperties(this._drawingOptions.toSVGProperties(),t.defaultSVGProperties),!1,!1);return s}static _mergeSVGProperties(t,e){const s=new Set(Object.keys(t));for(const[i,n]of Object.entries(e))s.has(i)?Object.assign(t[i],n):t[i]=n;return t}static getDefaultDrawingOptions(t){K("Not implemented")}static get typesMap(){K("Not implemented")}static get isDrawer(){return!0}static get supportMultipleDrawings(){return!1}static updateDefaultParams(t,e){const s=this.typesMap.get(t);s&&this._defaultDrawingOptions.updateProperty(s,e),this._currentParent&&(q.#s.updateProperty(s,e),this._currentParent.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}updateParams(t,e){const s=this.constructor.typesMap.get(t);s&&this._updateProperty(t,s,e)}static get defaultPropertiesToUpdate(){const t=[],e=this._defaultDrawingOptions;for(const[s,i]of this.typesMap)t.push([s,e[i]]);return t}get propertiesToUpdate(){const t=[],{_drawingOptions:e}=this;for(const[s,i]of this.constructor.typesMap)t.push([s,e[i]]);return t}_updateProperty(t,e,s){const i=this._drawingOptions,n=i[e],r=a=>{i.updateProperty(e,a);const o=this.#t.updateProperty(e,a);o&&this.#d(o),this.parent?.drawLayer.updateProperties(this._drawId,i.toSVGProperties()),t===this.colorType?this.onUpdatedColor():t===this.opacityType&&this.onUpdatedOpacity()};this.addCommands({cmd:r.bind(this,s),undo:r.bind(this,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:t,overwriteIfSameType:!0,keepUndo:!0})}_updateColorAndOpacity(t,e){const s=this.constructor.typesMap.get(this.colorType),i=this.constructor.typesMap.get(this.opacityType),n=this._drawingOptions,r=n[s],a=n[i],o=(l,c)=>{n.updateProperty(s,l),n.updateProperty(i,c),this.#t.updateProperty(s,l),this.#t.updateProperty(i,c),this.parent?.drawLayer.updateProperties(this._drawId,n.toSVGProperties()),this.onUpdatedColor(),this.onUpdatedOpacity()};this.addCommands({cmd:o.bind(this,t,e),undo:o.bind(this,r,a),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:X.INK_COLOR_AND_OPACITY,overwriteIfSameType:!0,keepUndo:!0})}_onResizing(){this.parent?.drawLayer.updateProperties(this._drawId,q._mergeSVGProperties(this.#t.getPathResizingSVGProperties(this.#u()),{bbox:this.#p()}))}_onResized(){this.parent?.drawLayer.updateProperties(this._drawId,q._mergeSVGProperties(this.#t.getPathResizedSVGProperties(this.#u()),{bbox:this.#p()}))}_onTranslating(t,e){this.parent?.drawLayer.updateProperties(this._drawId,{bbox:this.#p()})}_onTranslated(){this.parent?.drawLayer.updateProperties(this._drawId,q._mergeSVGProperties(this.#t.getPathTranslatedSVGProperties(this.#u(),this.parentDimensions),{bbox:this.#p()}))}_onStartDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!0}})}_onStopDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!1}})}commit(){super.commit(),this.disableEditMode(),this.disableEditing()}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}getBaseTranslation(){return[0,0]}get isResizable(){return!0}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),this._isDraggable=!0,this.#e&&(this.#e=!1,this.commit(),this.parent.setSelected(this),t&&this.isOnScreen&&this.div.focus())}remove(){this.#o(),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.#h(),this.#d(this.#t.box),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?(this._uiManager.removeShouldRescale(this),this.#o()):t&&(this._uiManager.addShouldRescale(this),this.#h(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),e&&this.select()}#o(){this._drawId===null||!this.parent||(this.parent.drawLayer.remove(this._drawId),this._drawId=null,this._drawingOptions.reset())}#h(t=this.parent){if(!(this._drawId!==null&&this.parent===t)){if(this._drawId!==null){this.parent.drawLayer.updateParent(this._drawId,t.drawLayer);return}this._drawingOptions.updateAll(),this._drawId=this.#r(this.#t,t)}}#l([t,e,s,i]){const{parentDimensions:[n,r],rotation:a}=this;switch(a){case 90:return[e,1-t,s*(r/n),i*(n/r)];case 180:return[1-t,1-e,s,i];case 270:return[1-e,t,s*(r/n),i*(n/r)];default:return[t,e,s,i]}}#u(){const{x:t,y:e,width:s,height:i,parentDimensions:[n,r],rotation:a}=this;switch(a){case 90:return[1-e,t,s*(n/r),i*(r/n)];case 180:return[1-t,1-e,s,i];case 270:return[e,1-t,s*(n/r),i*(r/n)];default:return[t,e,s,i]}}#d(t){[this.x,this.y,this.width,this.height]=this.#l(t),this.div&&(this.fixAndSetPosition(),this.setDims()),this._onResized()}#p(){const{x:t,y:e,width:s,height:i,rotation:n,parentRotation:r,parentDimensions:[a,o]}=this;switch((n*4+r)/90){case 1:return[1-e-i,t,i,s];case 2:return[1-t-s,1-e-i,s,i];case 3:return[e,1-t-s,i,s];case 4:return[t,e-s*(a/o),i*(o/a),s*(a/o)];case 5:return[1-e,t,s*(a/o),i*(o/a)];case 6:return[1-t-i*(o/a),1-e,i*(o/a),s*(a/o)];case 7:return[e-s*(a/o),1-t-i*(o/a),s*(a/o),i*(o/a)];case 8:return[t-s,e-i,s,i];case 9:return[1-e,t-s,i,s];case 10:return[1-t,1-e,s,i];case 11:return[e-i,1-t,i,s];case 12:return[t-i*(o/a),e,i*(o/a),s*(a/o)];case 13:return[1-e-s*(a/o),t-i*(o/a),s*(a/o),i*(o/a)];case 14:return[1-t,1-e-s*(a/o),i*(o/a),s*(a/o)];case 15:return[e,1-t,s*(a/o),i*(o/a)];default:return[t,e,s,i]}}rotate(){this.parent&&this.parent.drawLayer.updateProperties(this._drawId,q._mergeSVGProperties({bbox:this.#p()},this.#t.updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&this.#d(this.#t.updateParentDimensions(this.parentDimensions,this.parent.scale))}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;let t,e;this._isCopy&&(t=this.x,e=this.y);const s=super.render();s.classList.add("draw");const i=document.createElement("div");return s.append(i),i.setAttribute("aria-hidden","true"),i.className="internal",this.setDims(),this._uiManager.addShouldRescale(this),this.disableEditing(),this._isCopy&&this._moveAfterPaste(t,e),s}static createDrawerInstance(t,e,s,i,n){K("Not implemented")}static startDrawing(t,e,s,i){const{target:n,offsetX:r,offsetY:a,pointerId:o,pointerType:l}=i;if(Q.isInitializedAndDifferentPointerType(l))return;const{viewport:{rotation:c}}=t,{width:h,height:u}=n.getBoundingClientRect(),f=q.#i=new AbortController,p=t.combinedSignal(f);if(Q.setPointer(l,o),window.addEventListener("pointerup",g=>{Q.isSamePointerIdOrRemove(g.pointerId)&&this._endDraw(g)},{signal:p}),window.addEventListener("pointercancel",g=>{Q.isSamePointerIdOrRemove(g.pointerId)&&this._currentParent.endDrawingSession()},{signal:p}),window.addEventListener("pointerdown",g=>{Q.isSamePointerType(g.pointerType)&&(Q.initializeAndAddPointerId(g.pointerId),q.#s.isCancellable()&&(q.#s.removeLastElement(),q.#s.isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)))},{capture:!0,passive:!1,signal:p}),window.addEventListener("contextmenu",Rt,{signal:p}),n.addEventListener("pointermove",this._drawMove.bind(this),{signal:p}),n.addEventListener("touchmove",g=>{Q.isSameTimeStamp(g.timeStamp)&<(g)},{signal:p}),t.toggleDrawing(),e._editorUndoBar?.hide(),q.#s){t.drawLayer.updateProperties(this._currentDrawId,q.#s.startNew(r,a,h,u,c));return}e.updateUIForDefaultProperties(this),q.#s=this.createDrawerInstance(r,a,h,u,c),q.#n=this.getDefaultDrawingOptions(),this._currentParent=t,{id:this._currentDrawId}=t.drawLayer.draw(this._mergeSVGProperties(q.#n.toSVGProperties(),q.#s.defaultSVGProperties),!0,!1)}static _drawMove(t){if(Q.isSameTimeStamp(t.timeStamp),!q.#s)return;const{offsetX:e,offsetY:s,pointerId:i}=t;if(Q.isSamePointerId(i)){if(Q.isUsingMultiplePointers()){this._endDraw(t);return}this._currentParent.drawLayer.updateProperties(this._currentDrawId,q.#s.add(e,s)),Q.setTimeStamp(t.timeStamp),lt(t)}}static _cleanup(t){t&&(this._currentDrawId=-1,this._currentParent=null,q.#s=null,q.#n=null,Q.clearTimeStamp()),q.#i&&(q.#i.abort(),q.#i=null,Q.clearPointerIds())}static _endDraw(t){const e=this._currentParent;if(e){if(e.toggleDrawing(!0),this._cleanup(!1),t?.target===e.div&&e.drawLayer.updateProperties(this._currentDrawId,q.#s.end(t.offsetX,t.offsetY)),this.supportMultipleDrawings){const s=q.#s,i=this._currentDrawId,n=s.getLastElement();e.addCommands({cmd:()=>{e.drawLayer.updateProperties(i,s.setLastElement(n))},undo:()=>{e.drawLayer.updateProperties(i,s.removeLastElement())},mustExec:!1,type:X.DRAW_STEP});return}this.endDrawing(!1)}}static endDrawing(t){const e=this._currentParent;if(!e)return null;if(e.toggleDrawing(!0),e.cleanUndoStack(X.DRAW_STEP),!q.#s.isEmpty()){const{pageDimensions:[s,i],scale:n}=e,r=e.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:q.#s.getOutlines(s*n,i*n,n,this._INNER_MARGIN),drawingOptions:q.#n,mustBeCommitted:!t});return this._cleanup(!0),r}return e.drawLayer.remove(this._currentDrawId),this._cleanup(!0),null}createDrawingOptions(t){}static deserializeDraw(t,e,s,i,n,r){K("Not implemented")}static async deserialize(t,e,s){const{rawDims:{pageWidth:i,pageHeight:n,pageX:r,pageY:a}}=e.viewport,o=this.deserializeDraw(r,a,i,n,this._INNER_MARGIN,t),l=await super.deserialize(t,e,s);return l.createDrawingOptions(t),l.#a({drawOutlines:o}),l.#h(),l.onScaleChanging(),l.rotate(),l}serializeDraw(t){const[e,s]=this.pageTranslation,[i,n]=this.pageDimensions;return this.#t.serialize([e,s,i,n],t)}renderAnnotationElement(t){return t.updateEdited({rect:this.getPDFRect()}),null}static canCreateNewEmptyEditor(){return!1}}class Uc{#t=new Float64Array(6);#e;#s;#i;#n;#a;#r="";#o=0;#h=new us;#l;#u;constructor(t,e,s,i,n,r){this.#l=s,this.#u=i,this.#i=n,this.#n=r,[t,e]=this.#d(t,e);const a=this.#e=[NaN,NaN,NaN,NaN,t,e];this.#a=[t,e],this.#s=[{line:a,points:this.#a}],this.#t.set(a,0)}updateProperty(t,e){t==="stroke-width"&&(this.#n=e)}#d(t,e){return D._normalizePoint(t,e,this.#l,this.#u,this.#i)}isEmpty(){return!this.#s?.length}isCancellable(){return this.#a.length<=10}add(t,e){[t,e]=this.#d(t,e);const[s,i,n,r]=this.#t.subarray(2,6),a=t-n,o=e-r;return Math.hypot(this.#l*a,this.#u*o)<=2?null:(this.#a.push(t,e),isNaN(s)?(this.#t.set([n,r,t,e],2),this.#e.push(NaN,NaN,NaN,NaN,t,e),{path:{d:this.toSVGPath()}}):(isNaN(this.#t[0])&&this.#e.splice(6,6),this.#t.set([s,i,n,r,t,e],0),this.#e.push(...D.createBezierPoints(s,i,n,r,t,e)),{path:{d:this.toSVGPath()}}))}end(t,e){const s=this.add(t,e);return s||(this.#a.length===2?{path:{d:this.toSVGPath()}}:null)}startNew(t,e,s,i,n){this.#l=s,this.#u=i,this.#i=n,[t,e]=this.#d(t,e);const r=this.#e=[NaN,NaN,NaN,NaN,t,e];this.#a=[t,e];const a=this.#s.at(-1);return a&&(a.line=new Float32Array(a.line),a.points=new Float32Array(a.points)),this.#s.push({line:r,points:this.#a}),this.#t.set(r,0),this.#o=0,this.toSVGPath(),null}getLastElement(){return this.#s.at(-1)}setLastElement(t){return this.#s?(this.#s.push(t),this.#e=t.line,this.#a=t.points,this.#o=0,{path:{d:this.toSVGPath()}}):this.#h.setLastElement(t)}removeLastElement(){if(!this.#s)return this.#h.removeLastElement();this.#s.pop(),this.#r="";for(let t=0,e=this.#s.length;t<e;t++){const{line:s,points:i}=this.#s[t];this.#e=s,this.#a=i,this.#o=0,this.toSVGPath()}return{path:{d:this.#r}}}toSVGPath(){const t=D.svgRound(this.#e[4]),e=D.svgRound(this.#e[5]);if(this.#a.length===2)return this.#r=`${this.#r} M ${t} ${e} Z`,this.#r;if(this.#a.length<=6){const i=this.#r.lastIndexOf("M");this.#r=`${this.#r.slice(0,i)} M ${t} ${e}`,this.#o=6}if(this.#a.length===4){const i=D.svgRound(this.#e[10]),n=D.svgRound(this.#e[11]);return this.#r=`${this.#r} L ${i} ${n}`,this.#o=12,this.#r}const s=[];this.#o===0&&(s.push(`M ${t} ${e}`),this.#o=6);for(let i=this.#o,n=this.#e.length;i<n;i+=6){const[r,a,o,l,c,h]=this.#e.slice(i,i+6).map(D.svgRound);s.push(`C${r} ${a} ${o} ${l} ${c} ${h}`)}return this.#r+=s.join(" "),this.#o=this.#e.length,this.#r}getOutlines(t,e,s,i){const n=this.#s.at(-1);return n.line=new Float32Array(n.line),n.points=new Float32Array(n.points),this.#h.build(this.#s,t,e,s,this.#i,this.#n,i),this.#t=null,this.#e=null,this.#s=null,this.#r=null,this.#h}get defaultSVGProperties(){return{root:{viewBox:"0 0 10000 10000"},rootClass:{draw:!0},bbox:[0,0,1,1]}}}class us extends D{#t;#e=0;#s;#i;#n;#a;#r;#o;#h;build(t,e,s,i,n,r,a){this.#n=e,this.#a=s,this.#r=i,this.#o=n,this.#h=r,this.#s=a??0,this.#i=t,this.#d()}get thickness(){return this.#h}setLastElement(t){return this.#i.push(t),{path:{d:this.toSVGPath()}}}removeLastElement(){return this.#i.pop(),{path:{d:this.toSVGPath()}}}toSVGPath(){const t=[];for(const{line:e}of this.#i){if(t.push(`M${D.svgRound(e[4])} ${D.svgRound(e[5])}`),e.length===6){t.push("Z");continue}if(e.length===12&&isNaN(e[6])){t.push(`L${D.svgRound(e[10])} ${D.svgRound(e[11])}`);continue}for(let s=6,i=e.length;s<i;s+=6){const[n,r,a,o,l,c]=e.subarray(s,s+6).map(D.svgRound);t.push(`C${n} ${r} ${a} ${o} ${l} ${c}`)}}return t.join("")}serialize([t,e,s,i],n){const r=[],a=[],[o,l,c,h]=this.#u();let u,f,p,g,m,b,y,A,w;switch(this.#o){case 0:w=D._rescale,u=t,f=e+i,p=s,g=-i,m=t+o*s,b=e+(1-l-h)*i,y=t+(o+c)*s,A=e+(1-l)*i;break;case 90:w=D._rescaleAndSwap,u=t,f=e,p=s,g=i,m=t+l*s,b=e+o*i,y=t+(l+h)*s,A=e+(o+c)*i;break;case 180:w=D._rescale,u=t+s,f=e,p=-s,g=i,m=t+(1-o-c)*s,b=e+l*i,y=t+(1-o)*s,A=e+(l+h)*i;break;case 270:w=D._rescaleAndSwap,u=t+s,f=e+i,p=-s,g=-i,m=t+(1-l-h)*s,b=e+(1-o-c)*i,y=t+(1-l)*s,A=e+(1-o)*i;break}for(const{line:x,points:S}of this.#i)r.push(w(x,u,f,p,g,n?new Array(x.length):null)),a.push(w(S,u,f,p,g,n?new Array(S.length):null));return{lines:r,points:a,rect:[m,b,y,A]}}static deserialize(t,e,s,i,n,{paths:{lines:r,points:a},rotation:o,thickness:l}){const c=[];let h,u,f,p,g;switch(o){case 0:g=D._rescale,h=-t/s,u=e/i+1,f=1/s,p=-1/i;break;case 90:g=D._rescaleAndSwap,h=-e/i,u=-t/s,f=1/i,p=1/s;break;case 180:g=D._rescale,h=t/s+1,u=-e/i,f=-1/s,p=1/i;break;case 270:g=D._rescaleAndSwap,h=e/i+1,u=t/s+1,f=-1/i,p=-1/s;break}if(!r){r=[];for(const b of a){const y=b.length;if(y===2){r.push(new Float32Array([NaN,NaN,NaN,NaN,b[0],b[1]]));continue}if(y===4){r.push(new Float32Array([NaN,NaN,NaN,NaN,b[0],b[1],NaN,NaN,NaN,NaN,b[2],b[3]]));continue}const A=new Float32Array(3*(y-2));r.push(A);let[w,x,S,E]=b.subarray(0,4);A.set([NaN,NaN,NaN,NaN,w,x],0);for(let _=4;_<y;_+=2){const k=b[_],I=b[_+1];A.set(D.createBezierPoints(w,x,S,E,k,I),(_-2)*3),[w,x,S,E]=[S,E,k,I]}}}for(let b=0,y=r.length;b<y;b++)c.push({line:g(r[b].map(A=>A??NaN),h,u,f,p),points:g(a[b].map(A=>A??NaN),h,u,f,p)});const m=new this.prototype.constructor;return m.build(c,s,i,1,o,l,n),m}#l(t=this.#h){const e=this.#s+t/2*this.#r;return this.#o%180===0?[e/this.#n,e/this.#a]:[e/this.#a,e/this.#n]}#u(){const[t,e,s,i]=this.#t,[n,r]=this.#l(0);return[t+n,e+r,s-2*n,i-2*r]}#d(){const t=this.#t=me.slice();for(const{line:i}of this.#i){if(i.length<=12){for(let a=4,o=i.length;a<o;a+=6)T.pointBoundingBox(i[a],i[a+1],t);continue}let n=i[4],r=i[5];for(let a=6,o=i.length;a<o;a+=6){const[l,c,h,u,f,p]=i.subarray(a,a+6);T.bezierBoundingBox(n,r,l,c,h,u,f,p,t),n=f,r=p}}const[e,s]=this.#l();t[0]=nt(t[0]-e,0,1),t[1]=nt(t[1]-s,0,1),t[2]=nt(t[2]+e,0,1),t[3]=nt(t[3]+s,0,1),t[2]-=t[0],t[3]-=t[1]}get box(){return this.#t}updateProperty(t,e){return t==="stroke-width"?this.#p(e):null}#p(t){const[e,s]=this.#l();this.#h=t;const[i,n]=this.#l(),[r,a]=[i-e,n-s],o=this.#t;return o[0]-=r,o[1]-=a,o[2]+=2*r,o[3]+=2*a,o}updateParentDimensions([t,e],s){const[i,n]=this.#l();this.#n=t,this.#a=e,this.#r=s;const[r,a]=this.#l(),o=r-i,l=a-n,c=this.#t;return c[0]-=o,c[1]-=l,c[2]+=2*o,c[3]+=2*l,c}updateRotation(t){return this.#e=t,{path:{transform:this.rotationTransform}}}get viewBox(){return this.#t.map(D.svgRound).join(" ")}get defaultProperties(){const[t,e]=this.#t;return{root:{viewBox:this.viewBox},path:{"transform-origin":`${D.svgRound(t)} ${D.svgRound(e)}`}}}get rotationTransform(){const[,,t,e]=this.#t;let s=0,i=0,n=0,r=0,a=0,o=0;switch(this.#e){case 90:i=e/t,n=-t/e,a=t;break;case 180:s=-1,r=-1,a=t,o=e;break;case 270:i=-e/t,n=t/e,o=e;break;default:return""}return`matrix(${s} ${i} ${n} ${r} ${D.svgRound(a)} ${D.svgRound(o)})`}getPathResizingSVGProperties([t,e,s,i]){const[n,r]=this.#l(),[a,o,l,c]=this.#t;if(Math.abs(l-n)<=D.PRECISION||Math.abs(c-r)<=D.PRECISION){const g=t+s/2-(a+l/2),m=e+i/2-(o+c/2);return{path:{"transform-origin":`${D.svgRound(t)} ${D.svgRound(e)}`,transform:`${this.rotationTransform} translate(${g} ${m})`}}}const h=(s-2*n)/(l-2*n),u=(i-2*r)/(c-2*r),f=l/s,p=c/i;return{path:{"transform-origin":`${D.svgRound(a)} ${D.svgRound(o)}`,transform:`${this.rotationTransform} scale(${f} ${p}) translate(${D.svgRound(n)} ${D.svgRound(r)}) scale(${h} ${u}) translate(${D.svgRound(-n)} ${D.svgRound(-r)})`}}}getPathResizedSVGProperties([t,e,s,i]){const[n,r]=this.#l(),a=this.#t,[o,l,c,h]=a;if(a[0]=t,a[1]=e,a[2]=s,a[3]=i,Math.abs(c-n)<=D.PRECISION||Math.abs(h-r)<=D.PRECISION){const m=t+s/2-(o+c/2),b=e+i/2-(l+h/2);for(const{line:y,points:A}of this.#i)D._translate(y,m,b,y),D._translate(A,m,b,A);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${D.svgRound(t)} ${D.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}const u=(s-2*n)/(c-2*n),f=(i-2*r)/(h-2*r),p=-u*(o+n)+t+n,g=-f*(l+r)+e+r;if(u!==1||f!==1||p!==0||g!==0)for(const{line:m,points:b}of this.#i)D._rescale(m,p,g,u,f,m),D._rescale(b,p,g,u,f,b);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${D.svgRound(t)} ${D.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}getPathTranslatedSVGProperties([t,e],s){const[i,n]=s,r=this.#t,a=t-r[0],o=e-r[1];if(this.#n===i&&this.#a===n)for(const{line:l,points:c}of this.#i)D._translate(l,a,o,l),D._translate(c,a,o,c);else{const l=this.#n/i,c=this.#a/n;this.#n=i,this.#a=n;for(const{line:h,points:u}of this.#i)D._rescale(h,a,o,l,c,h),D._rescale(u,a,o,l,c,u);r[2]*=l,r[3]*=c}return r[0]=t,r[1]=e,{root:{viewBox:this.viewBox},path:{d:this.toSVGPath(),"transform-origin":`${D.svgRound(t)} ${D.svgRound(e)}`}}}get defaultSVGProperties(){const t=this.#t;return{root:{viewBox:this.viewBox},rootClass:{draw:!0},path:{d:this.toSVGPath(),"transform-origin":`${D.svgRound(t[0])} ${D.svgRound(t[1])}`,transform:this.rotationTransform||null},bbox:t}}}class ti extends Kr{constructor(t){super(),this._viewParameters=t,super.updateProperties({fill:"none",stroke:N._defaultLineColor,"stroke-opacity":1,"stroke-width":1,"stroke-linecap":"round","stroke-linejoin":"round","stroke-miterlimit":10})}updateSVGProperty(t,e){t==="stroke-width"&&(e??=this["stroke-width"],e*=this._viewParameters.realScale),super.updateSVGProperty(t,e)}clone(){const t=new ti(this._viewParameters);return t.updateAll(this),t}}class tn extends q{static _type="ink";static _editorType=G.INK;static _defaultDrawingOptions=null;constructor(t){super({...t,name:"inkEditor"}),this._willKeepAspectRatio=!0,this.defaultL10nId="pdfjs-editor-ink-editor"}static initialize(t,e){N.initialize(t,e),this._defaultDrawingOptions=new ti(e.viewParameters)}static getDefaultDrawingOptions(t){const e=this._defaultDrawingOptions.clone();return e.updateProperties(t),e}static get supportMultipleDrawings(){return!0}static get typesMap(){return z(this,"typesMap",new Map([[X.INK_THICKNESS,"stroke-width"],[X.INK_COLOR,"stroke"],[X.INK_OPACITY,"stroke-opacity"]]))}static createDrawerInstance(t,e,s,i,n){return new Uc(t,e,s,i,n,this._defaultDrawingOptions["stroke-width"])}static deserializeDraw(t,e,s,i,n,r){return us.deserialize(t,e,s,i,n,r)}static async deserialize(t,e,s){let i=null;if(t instanceof Ji){const{data:{inkLists:r,rect:a,rotation:o,id:l,color:c,opacity:h,borderStyle:{rawWidth:u},popupRef:f,richText:p,contentsObj:g,creationDate:m,modificationDate:b},parent:{page:{pageNumber:y}}}=t;i=t={annotationType:G.INK,color:Array.from(c),thickness:u,opacity:h,paths:{points:r},boxes:null,pageIndex:y-1,rect:a.slice(0),rotation:o,annotationElementId:l,id:l,deleted:!1,popupRef:f,richText:p,comment:g?.str||null,creationDate:m,modificationDate:b}}const n=await super.deserialize(t,e,s);return n._initialData=i,t.comment&&n.setCommentData(t),n}get toolbarButtons(){return this._colorPicker||=new rs(this),[["colorPicker",this._colorPicker]]}get colorType(){return X.INK_COLOR}get colorAndOpacityType(){return X.INK_COLOR_AND_OPACITY}get opacityType(){return X.INK_OPACITY}updateParams(t,e){if(t===X.INK_COLOR_AND_OPACITY){this._updateColorAndOpacity(e.color,e.opacity);return}super.updateParams(t,e)}static updateDefaultParams(t,e){if(t===X.INK_COLOR_AND_OPACITY){super.updateDefaultParams(X.INK_COLOR,e.color),super.updateDefaultParams(X.INK_OPACITY,e.opacity);return}super.updateDefaultParams(t,e)}get color(){return this._drawingOptions.stroke}get opacity(){return this._drawingOptions["stroke-opacity"]}onScaleChanging(){if(!this.parent)return;super.onScaleChanging();const{_drawId:t,_drawingOptions:e,parent:s}=this;e.updateSVGProperty("stroke-width"),s.drawLayer.updateProperties(t,e.toSVGProperties())}static onScaleChangingWhenDrawing(){const t=this._currentParent;t&&(super.onScaleChangingWhenDrawing(),this._defaultDrawingOptions.updateSVGProperty("stroke-width"),t.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}createDrawingOptions({color:t,thickness:e,opacity:s}){this._drawingOptions=tn.getDefaultDrawingOptions({stroke:T.makeHexColor(...t),"stroke-width":e,"stroke-opacity":s})}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const{lines:e,points:s}=this.serializeDraw(t),{_drawingOptions:{stroke:i,"stroke-opacity":n,"stroke-width":r}}=this,a=Object.assign(super.serialize(t),{color:N._colorManager.convert(i),opacity:n,thickness:r,paths:{lines:e,points:s}});return this.addComment(a),t?(a.isCopy=!0,a):this.annotationElementId&&!this.#t(a)?null:(a.id=this.annotationElementId,a)}#t(t){const{color:e,thickness:s,opacity:i,pageIndex:n}=this._initialData;return this.hasEditedComment||this._hasBeenMoved||this._hasBeenResized||t.color.some((r,a)=>r!==e[a])||t.thickness!==s||t.opacity!==i||t.pageIndex!==n}renderAnnotationElement(t){if(this.deleted)return t.hide(),null;const{points:e,rect:s}=this.serializeDraw(!1);return t.updateEdited({rect:s,thickness:this._drawingOptions["stroke-width"],points:e,popup:this.comment}),null}}class Li extends us{toSVGPath(){let t=super.toSVGPath();return t.endsWith("Z")||(t+="Z"),t}}const ks=8,Ye=3;class Ne{static#t={maxDim:512,sigmaSFactor:.02,sigmaR:25,kernelSize:16};static#e(t,e,s,i){return s-=t,i-=e,s===0?i>0?0:4:s===1?i+6:2-i}static#s=new Int32Array([0,1,-1,1,-1,0,-1,-1,0,-1,1,-1,1,0,1,1]);static#i(t,e,s,i,n,r,a){const o=this.#e(s,i,n,r);for(let l=0;l<8;l++){const c=(-l+o-a+16)%8,h=this.#s[2*c],u=this.#s[2*c+1];if(t[(s+h)*e+(i+u)]!==0)return c}return-1}static#n(t,e,s,i,n,r,a){const o=this.#e(s,i,n,r);for(let l=0;l<8;l++){const c=(l+o+a+16)%8,h=this.#s[2*c],u=this.#s[2*c+1];if(t[(s+h)*e+(i+u)]!==0)return c}return-1}static#a(t,e,s,i){const n=t.length,r=new Int32Array(n);for(let c=0;c<n;c++)r[c]=t[c]<=i?1:0;for(let c=1;c<s-1;c++)r[c*e]=r[c*e+e-1]=0;for(let c=0;c<e;c++)r[c]=r[e*s-1-c]=0;let a=1,o;const l=[];for(let c=1;c<s-1;c++){o=1;for(let h=1;h<e-1;h++){const u=c*e+h,f=r[u];if(f===0)continue;let p=c,g=h;if(f===1&&r[u-1]===0)a+=1,g-=1;else if(f>=1&&r[u+1]===0)a+=1,g+=1,f>1&&(o=f);else{f!==1&&(o=Math.abs(f));continue}const m=[h,c],b=g===h+1,y={isHole:b,points:m,id:a,parent:0};l.push(y);let A;for(const P of l)if(P.id===o){A=P;break}A?A.isHole?y.parent=b?A.parent:o:y.parent=b?o:A.parent:y.parent=b?o:0;const w=this.#i(r,e,c,h,p,g,0);if(w===-1){r[u]=-a,r[u]!==1&&(o=Math.abs(r[u]));continue}let x=this.#s[2*w],S=this.#s[2*w+1];const E=c+x,_=h+S;p=E,g=_;let k=c,I=h;for(;;){const P=this.#n(r,e,k,I,p,g,1);x=this.#s[2*P],S=this.#s[2*P+1];const B=k+x,W=I+S;m.push(W,B);const Y=k*e+I;if(r[Y+1]===0?r[Y]=-a:r[Y]===1&&(r[Y]=a),B===c&&W===h&&k===E&&I===_){r[u]!==1&&(o=Math.abs(r[u]));break}else p=k,g=I,k=B,I=W}}}return l}static#r(t,e,s,i){if(s-e<=4){for(let E=e;E<s-2;E+=2)i.push(t[E],t[E+1]);return}const n=t[e],r=t[e+1],a=t[s-4]-n,o=t[s-3]-r,l=Math.hypot(a,o),c=a/l,h=o/l,u=c*r-h*n,f=o/a,p=1/l,g=Math.atan(f),m=Math.cos(g),b=Math.sin(g),y=p*(Math.abs(m)+Math.abs(b)),A=p*(1-y+y**2),w=Math.max(Math.atan(Math.abs(b+m)*A),Math.atan(Math.abs(b-m)*A));let x=0,S=e;for(let E=e+2;E<s-2;E+=2){const _=Math.abs(u-c*t[E+1]+h*t[E]);_>x&&(S=E,x=_)}x>(l*w)**2?(this.#r(t,e,S+2,i),this.#r(t,S,s,i)):i.push(n,r)}static#o(t){const e=[],s=t.length;return this.#r(t,0,s,e),e.push(t[s-2],t[s-1]),e.length<=4?null:e}static#h(t,e,s,i,n,r){const a=new Float32Array(r**2),o=-2*i**2,l=r>>1;for(let g=0;g<r;g++){const m=(g-l)**2;for(let b=0;b<r;b++)a[g*r+b]=Math.exp((m+(b-l)**2)/o)}const c=new Float32Array(256),h=-2*n**2;for(let g=0;g<256;g++)c[g]=Math.exp(g**2/h);const u=t.length,f=new Uint8Array(u),p=new Uint32Array(256);for(let g=0;g<s;g++)for(let m=0;m<e;m++){const b=g*e+m,y=t[b];let A=0,w=0;for(let S=0;S<r;S++){const E=g+S-l;if(!(E<0||E>=s))for(let _=0;_<r;_++){const k=m+_-l;if(k<0||k>=e)continue;const I=t[E*e+k],P=a[S*r+_]*c[Math.abs(I-y)];A+=I*P,w+=P}}const x=f[b]=Math.round(A/w);p[x]++}return[f,p]}static#l(t){const e=new Uint32Array(256);for(const s of t)e[s]++;return e}static#u(t){const e=t.length,s=new Uint8ClampedArray(e>>2);let i=-1/0,n=1/0;for(let a=0,o=s.length;a<o;a++){const l=s[a]=t[a<<2];i=Math.max(i,l),n=Math.min(n,l)}const r=255/(i-n);for(let a=0,o=s.length;a<o;a++)s[a]=(s[a]-n)*r;return s}static#d(t){let e,s=-1/0,i=-1/0;const n=t.findIndex(o=>o!==0);let r=n,a=n;for(e=n;e<256;e++){const o=t[e];o>s&&(e-r>i&&(i=e-r,a=e-1),s=o,r=e)}for(e=a-1;e>=0&&!(t[e]>t[e+1]);e--);return e}static#p(t){const e=t,{width:s,height:i}=t,{maxDim:n}=this.#t;let r=s,a=i;if(s>n||i>n){let u=s,f=i,p=Math.log2(Math.max(s,i)/n);const g=Math.floor(p);p=p===g?g-1:g;for(let b=0;b<p;b++){r=Math.ceil(u/2),a=Math.ceil(f/2);const y=new OffscreenCanvas(r,a);y.getContext("2d").drawImage(t,0,0,u,f,0,0,r,a),u=r,f=a,t!==e&&t.close(),t=y.transferToImageBitmap()}const m=Math.min(n/r,n/a);r=Math.round(r*m),a=Math.round(a*m)}const l=new OffscreenCanvas(r,a).getContext("2d",{willReadFrequently:!0});l.fillStyle="white",l.fillRect(0,0,r,a),l.filter="grayscale(1)",l.drawImage(t,0,0,t.width,t.height,0,0,r,a);const c=l.getImageData(0,0,r,a).data;return[this.#u(c),r,a]}static extractContoursFromText(t,{fontFamily:e,fontStyle:s,fontWeight:i},n,r,a,o){let l=new OffscreenCanvas(1,1),c=l.getContext("2d",{alpha:!1});const h=200,u=c.font=`${s} ${i} ${h}px ${e}`,{actualBoundingBoxLeft:f,actualBoundingBoxRight:p,actualBoundingBoxAscent:g,actualBoundingBoxDescent:m,fontBoundingBoxAscent:b,fontBoundingBoxDescent:y,width:A}=c.measureText(t),w=1.5,x=Math.ceil(Math.max(Math.abs(f)+Math.abs(p)||0,A)*w),S=Math.ceil(Math.max(Math.abs(g)+Math.abs(m)||h,Math.abs(b)+Math.abs(y)||h)*w);l=new OffscreenCanvas(x,S),c=l.getContext("2d",{alpha:!0,willReadFrequently:!0}),c.font=u,c.filter="grayscale(1)",c.fillStyle="white",c.fillRect(0,0,x,S),c.fillStyle="black",c.fillText(t,x*(w-1)/2,S*(3-w)/2);const E=this.#u(c.getImageData(0,0,x,S).data),_=this.#l(E),k=this.#d(_),I=this.#a(E,x,S,k);return this.processDrawnLines({lines:{curves:I,width:x,height:S},pageWidth:n,pageHeight:r,rotation:a,innerMargin:o,mustSmooth:!0,areContours:!0})}static process(t,e,s,i,n){const[r,a,o]=this.#p(t),[l,c]=this.#h(r,a,o,Math.hypot(a,o)*this.#t.sigmaSFactor,this.#t.sigmaR,this.#t.kernelSize),h=this.#d(c),u=this.#a(l,a,o,h);return this.processDrawnLines({lines:{curves:u,width:a,height:o},pageWidth:e,pageHeight:s,rotation:i,innerMargin:n,mustSmooth:!0,areContours:!0})}static processDrawnLines({lines:t,pageWidth:e,pageHeight:s,rotation:i,innerMargin:n,mustSmooth:r,areContours:a}){i%180!==0&&([e,s]=[s,e]);const{curves:o,width:l,height:c}=t,h=t.thickness??0,u=[],f=Math.min(e/l,s/c),p=f/e,g=f/s,m=[];for(const{points:y}of o){const A=r?this.#o(y):y;if(!A)continue;m.push(A);const w=A.length,x=new Float32Array(w),S=new Float32Array(3*(w===2?2:w-2));if(u.push({line:S,points:x}),w===2){x[0]=A[0]*p,x[1]=A[1]*g,S.set([NaN,NaN,NaN,NaN,x[0],x[1]],0);continue}let[E,_,k,I]=A;E*=p,_*=g,k*=p,I*=g,x.set([E,_,k,I],0),S.set([NaN,NaN,NaN,NaN,E,_],0);for(let P=4;P<w;P+=2){const B=x[P]=A[P]*p,W=x[P+1]=A[P+1]*g;S.set(D.createBezierPoints(E,_,k,I,B,W),(P-2)*3),[E,_,k,I]=[k,I,B,W]}}if(u.length===0)return null;const b=a?new Li:new us;return b.build(u,e,s,1,i,a?0:h,n),{outline:b,newCurves:m,areContours:a,thickness:h,width:l,height:c}}static async compressSignature({outlines:t,areContours:e,thickness:s,width:i,height:n}){let r=1/0,a=-1/0,o=0;for(const y of t){o+=y.length;for(let A=2,w=y.length;A<w;A++){const x=y[A]-y[A-2];r=Math.min(r,x),a=Math.max(a,x)}}let l;r>=-128&&a<=127?l=Int8Array:r>=-32768&&a<=32767?l=Int16Array:l=Int32Array;const c=t.length,h=ks+Ye*c,u=new Uint32Array(h);let f=0;u[f++]=h*Uint32Array.BYTES_PER_ELEMENT+(o-2*c)*l.BYTES_PER_ELEMENT,u[f++]=0,u[f++]=i,u[f++]=n,u[f++]=e?0:1,u[f++]=Math.max(0,Math.floor(s??0)),u[f++]=c,u[f++]=l.BYTES_PER_ELEMENT;for(const y of t)u[f++]=y.length-2,u[f++]=y[0],u[f++]=y[1];const p=new CompressionStream("deflate-raw"),g=p.writable.getWriter();await g.ready,g.write(u);const m=l.prototype.constructor;for(const y of t){const A=new m(y.length-2);for(let w=2,x=y.length;w<x;w++)A[w-2]=y[w]-y[w-2];g.write(A)}return g.close(),(await new Response(p.readable).bytes()).toBase64()}static async decompressSignature(t){try{const e=Uint8Array.fromBase64(t),{readable:s,writable:i}=new DecompressionStream("deflate-raw"),n=i.getWriter();await n.ready,n.write(e).then(async()=>{await n.ready,await n.close()}).catch(()=>{});let r=null,a=0;for await(const A of s)r||=new Uint8Array(new Uint32Array(A.buffer,0,4)[0]),r.set(A,a),a+=A.length;const o=new Uint32Array(r.buffer,0,r.length>>2),l=o[1];if(l!==0)throw new Error(`Invalid version: ${l}`);const c=o[2],h=o[3],u=o[4]===0,f=o[5],p=o[6],g=o[7],m=[],b=(ks+Ye*p)*Uint32Array.BYTES_PER_ELEMENT;let y;switch(g){case Int8Array.BYTES_PER_ELEMENT:y=new Int8Array(r.buffer,b);break;case Int16Array.BYTES_PER_ELEMENT:y=new Int16Array(r.buffer,b);break;case Int32Array.BYTES_PER_ELEMENT:y=new Int32Array(r.buffer,b);break}a=0;for(let A=0;A<p;A++){const w=o[Ye*A+ks],x=new Float32Array(w+2);m.push(x);for(let S=0;S<Ye-1;S++)x[S]=o[Ye*A+ks+S+1];for(let S=0;S<w;S++)x[S+2]=x[S]+y[a++]}return{areContours:u,thickness:f,outlines:m,width:c,height:h}}catch(e){return V(`decompressSignature: ${e}`),null}}}class en extends Kr{constructor(){super(),super.updateProperties({fill:N._defaultLineColor,"stroke-width":0})}clone(){const t=new en;return t.updateAll(this),t}}class sn extends ti{constructor(t){super(t),super.updateProperties({stroke:N._defaultLineColor,"stroke-width":1})}clone(){const t=new sn(this._viewParameters);return t.updateAll(this),t}}class Wt extends q{#t=!1;#e=null;#s=null;#i=null;static _type="signature";static _editorType=G.SIGNATURE;static _defaultDrawingOptions=null;constructor(t){super({...t,mustBeCommitted:!0,name:"signatureEditor"}),this._willKeepAspectRatio=!0,this.#s=t.signatureData||null,this.#e=null,this.defaultL10nId="pdfjs-editor-signature-editor1"}static initialize(t,e){N.initialize(t,e),this._defaultDrawingOptions=new en,this._defaultDrawnSignatureOptions=new sn(e.viewParameters)}static getDefaultDrawingOptions(t){const e=this._defaultDrawingOptions.clone();return e.updateProperties(t),e}static get supportMultipleDrawings(){return!1}static get typesMap(){return z(this,"typesMap",new Map)}static get isDrawer(){return!1}get telemetryFinalData(){return{type:"signature",hasDescription:!!this.#e}}static computeTelemetryFinalData(t){const e=t.get("hasDescription");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}get isResizable(){return!0}onScaleChanging(){this._drawId!==null&&super.onScaleChanging()}render(){if(this.div)return this.div;let t,e;const{_isCopy:s}=this;if(s&&(this._isCopy=!1,t=this.x,e=this.y),super.render(),this._drawId===null)if(this.#s){const{lines:i,mustSmooth:n,areContours:r,description:a,uuid:o,heightInPage:l}=this.#s,{rawDims:{pageWidth:c,pageHeight:h},rotation:u}=this.parent.viewport,f=Ne.processDrawnLines({lines:i,pageWidth:c,pageHeight:h,rotation:u,innerMargin:Wt._INNER_MARGIN,mustSmooth:n,areContours:r});this.addSignature(f,l,a,o)}else this.div.setAttribute("data-l10n-args",JSON.stringify({description:""})),this.div.hidden=!0,this._uiManager.getSignature(this);else this.div.setAttribute("data-l10n-args",JSON.stringify({description:this.#e||""}));return s&&(this._isCopy=!0,this._moveAfterPaste(t,e)),this.div}setUuid(t){this.#i=t,this.addEditToolbar()}getUuid(){return this.#i}get description(){return this.#e}set description(t){this.#e=t,this.div&&(this.div.setAttribute("data-l10n-args",JSON.stringify({description:t})),super.addEditToolbar().then(e=>{e?.updateEditSignatureButton(t)}))}getSignaturePreview(){const{newCurves:t,areContours:e,thickness:s,width:i,height:n}=this.#s,r=Math.max(i,n),a=Ne.processDrawnLines({lines:{curves:t.map(o=>({points:o})),thickness:s,width:i,height:n},pageWidth:r,pageHeight:r,rotation:0,innerMargin:0,mustSmooth:!1,areContours:e});return{areContours:e,outline:a.outline}}get toolbarButtons(){return this._uiManager.signatureManager?[["editSignature",this._uiManager.signatureManager]]:super.toolbarButtons}addSignature(t,e,s,i){const{x:n,y:r}=this,{outline:a}=this.#s=t;this.#t=a instanceof Li,this.description=s;let o;this.#t?o=Wt.getDefaultDrawingOptions():(o=Wt._defaultDrawnSignatureOptions.clone(),o.updateProperties({"stroke-width":a.thickness})),this._addOutlines({drawOutlines:a,drawingOptions:o});const[,l]=this.pageDimensions;let c=e/l;c=c>=1?.5:c,this.width*=c/this.height,this.width>=1&&(c*=.9/this.width,this.width=.9),this.height=c,this.setDims(),this.x=n,this.y=r,this.center(),this._onResized(),this.onScaleChanging(),this.rotate(),this._uiManager.addToAnnotationStorage(this),this.setUuid(i),this._reportTelemetry({action:"pdfjs.signature.inserted",data:{hasBeenSaved:!!i,hasDescription:!!s}}),this.div.hidden=!1}getFromImage(t){const{rawDims:{pageWidth:e,pageHeight:s},rotation:i}=this.parent.viewport;return Ne.process(t,e,s,i,Wt._INNER_MARGIN)}getFromText(t,e){const{rawDims:{pageWidth:s,pageHeight:i},rotation:n}=this.parent.viewport;return Ne.extractContoursFromText(t,e,s,i,n,Wt._INNER_MARGIN)}getDrawnSignature(t){const{rawDims:{pageWidth:e,pageHeight:s},rotation:i}=this.parent.viewport;return Ne.processDrawnLines({lines:t,pageWidth:e,pageHeight:s,rotation:i,innerMargin:Wt._INNER_MARGIN,mustSmooth:!1,areContours:!1})}createDrawingOptions({areContours:t,thickness:e}){t?this._drawingOptions=Wt.getDefaultDrawingOptions():(this._drawingOptions=Wt._defaultDrawnSignatureOptions.clone(),this._drawingOptions.updateProperties({"stroke-width":e}))}serialize(t=!1){if(this.isEmpty())return null;const{lines:e,points:s}=this.serializeDraw(t),{_drawingOptions:{"stroke-width":i}}=this,n=Object.assign(super.serialize(t),{isSignature:!0,areContours:this.#t,color:[0,0,0],thickness:this.#t?0:i});return this.addComment(n),t?(n.paths={lines:e,points:s},n.uuid=this.#i,n.isCopy=!0):n.lines=e,this.#e&&(n.accessibilityData={type:"Figure",alt:this.#e}),n}static deserializeDraw(t,e,s,i,n,r){return r.areContours?Li.deserialize(t,e,s,i,n,r):us.deserialize(t,e,s,i,n,r)}static async deserialize(t,e,s){const i=await super.deserialize(t,e,s);return i.#t=t.areContours,i.description=t.accessibilityData?.alt||"",i.#i=t.uuid,i}}class zc extends N{#t=null;#e=null;#s=null;#i=null;#n=null;#a="";#r=null;#o=!1;#h=null;#l=!1;#u=!1;static _type="stamp";static _editorType=G.STAMP;constructor(t){super({...t,name:"stampEditor"}),this.#i=t.bitmapUrl,this.#n=t.bitmapFile,this.defaultL10nId="pdfjs-editor-stamp-editor"}static initialize(t,e){N.initialize(t,e)}static isHandlingMimeForPasting(t){return ki.includes(t)}static paste(t,e){e.pasteEditor({mode:G.STAMP},{bitmapFile:t.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1),super.altTextFinish()}get telemetryFinalData(){return{type:"stamp",hasAltText:!!this.altTextData?.altText}}static computeTelemetryFinalData(t){const e=t.get("hasAltText");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}#d(t,e=!1){if(!t){this.remove();return}this.#t=t.bitmap,e||(this.#e=t.id,this.#l=t.isSvg),t.file&&(this.#a=t.file.name),this.#g()}#p(){if(this.#s=null,this._uiManager.enableWaiting(!1),!!this.#r){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#t){this.addEditToolbar().then(()=>{this._editToolbar.hide(),this._uiManager.editAltText(this,!0)});return}if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#t){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}}async mlGuessAltText(t=null,e=!0){if(this.hasAltTextData())return null;const{mlManager:s}=this._uiManager;if(!s)throw new Error("No ML.");if(!await s.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:i,width:n,height:r}=t||this.copyCanvas(null,null,!0).imageData,a=await s.guess({name:"altText",request:{data:i,width:n,height:r,channels:i.length/(n*r)}});if(!a)throw new Error("No response from the AI service.");if(a.error)throw new Error("Error from the AI service.");if(a.cancel)return null;if(!a.output)throw new Error("No valid response from the AI service.");const o=a.output;return await this.setGuessedAltText(o),e&&!this.hasAltTextData()&&(this.altTextData={alt:o,decorative:!1}),o}#m(){if(this.#e){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(this.#e).then(s=>this.#d(s,!0)).finally(()=>this.#p());return}if(this.#i){const s=this.#i;this.#i=null,this._uiManager.enableWaiting(!0),this.#s=this._uiManager.imageManager.getFromUrl(s).then(i=>this.#d(i)).finally(()=>this.#p());return}if(this.#n){const s=this.#n;this.#n=null,this._uiManager.enableWaiting(!0),this.#s=this._uiManager.imageManager.getFromFile(s).then(i=>this.#d(i)).finally(()=>this.#p());return}const t=document.createElement("input");t.type="file",t.accept=ki.join(",");const e=this._uiManager._signal;this.#s=new Promise(s=>{t.addEventListener("change",async()=>{if(!t.files||t.files.length===0)this.remove();else{this._uiManager.enableWaiting(!0);const i=await this._uiManager.imageManager.getFromFile(t.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),this.#d(i)}s()},{signal:e}),t.addEventListener("cancel",()=>{this.remove(),s()},{signal:e})}).finally(()=>this.#p()),t.click()}remove(){this.#e&&(this.#t=null,this._uiManager.imageManager.deleteId(this.#e),this.#r?.remove(),this.#r=null,this.#h&&(clearTimeout(this.#h),this.#h=null)),super.remove()}rebuild(){if(!this.parent){this.#e&&this.#m();return}super.rebuild(),this.div!==null&&(this.#e&&this.#r===null&&this.#m(),this.isAttachedToDOM||this.parent.add(this))}onceAdded(t){this._isDraggable=!0,t&&this.div.focus()}isEmpty(){return!(this.#s||this.#t||this.#i||this.#n||this.#e||this.#o)}get toolbarButtons(){return[["altText",this.createAltText()]]}get isResizable(){return!0}render(){if(this.div)return this.div;let t,e;return this._isCopy&&(t=this.x,e=this.y),super.render(),this.div.hidden=!0,this.createAltText(),this.#o||(this.#t?this.#g():this.#m()),this._isCopy&&this._moveAfterPaste(t,e),this._uiManager.addShouldRescale(this),this.div}setCanvas(t,e){const{id:s,bitmap:i}=this._uiManager.imageManager.getFromCanvas(t,e);e.remove(),s&&this._uiManager.imageManager.isValidId(s)&&(this.#e=s,i&&(this.#t=i),this.#o=!1,this.#g())}_onResized(){this.onScaleChanging()}onScaleChanging(){if(!this.parent)return;this.#h!==null&&clearTimeout(this.#h);const t=200;this.#h=setTimeout(()=>{this.#h=null,this.#f()},t)}#g(){const{div:t}=this;let{width:e,height:s}=this.#t;const[i,n]=this.pageDimensions,r=.75;if(this.width)e=this.width*i,s=this.height*n;else if(e>r*i||s>r*n){const o=Math.min(r*i/e,r*n/s);e*=o,s*=o}this._uiManager.enableWaiting(!1);const a=this.#r=document.createElement("canvas");a.setAttribute("role","img"),this.addContainer(a),this.width=e/i,this.height=s/n,this.setDims(),this._initialOptions?.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,(!this._uiManager.useNewAltTextWhenAddingImage||!this._uiManager.useNewAltTextFlow||this.annotationElementId)&&(t.hidden=!1),this.#f(),this.#u||(this.parent.addUndoableEditor(this),this.#u=!0),this._reportTelemetry({action:"inserted_image"}),this.#a&&this.div.setAttribute("aria-description",this.#a),this.annotationElementId||this._uiManager.a11yAlert(N._l10nAlert.stamp)}copyCanvas(t,e,s=!1){t||(t=224);const{width:i,height:n}=this.#t,r=new Kt;let a=this.#t,o=i,l=n,c=null;if(e){if(i>e||n>e){const S=Math.min(e/i,e/n);o=Math.floor(i*S),l=Math.floor(n*S)}c=document.createElement("canvas");const u=c.width=Math.ceil(o*r.sx),f=c.height=Math.ceil(l*r.sy);this.#l||(a=this.#c(u,f));const p=c.getContext("2d");p.filter=this._uiManager.hcmFilter;let g="white",m="#cfcfd8";this._uiManager.hcmFilter!=="none"?m="black":qo.isDarkMode&&(g="#8f8f9d",m="#42414d");const b=15,y=b*r.sx,A=b*r.sy,w=new OffscreenCanvas(y*2,A*2),x=w.getContext("2d");x.fillStyle=g,x.fillRect(0,0,y*2,A*2),x.fillStyle=m,x.fillRect(0,0,y,A),x.fillRect(y,A,y,A),p.fillStyle=p.createPattern(w,"repeat"),p.fillRect(0,0,u,f),p.drawImage(a,0,0,a.width,a.height,0,0,u,f)}let h=null;if(s){let u,f;if(r.symmetric&&a.width<t&&a.height<t)u=a.width,f=a.height;else if(a=this.#t,i>t||n>t){const m=Math.min(t/i,t/n);u=Math.floor(i*m),f=Math.floor(n*m),this.#l||(a=this.#c(u,f))}const g=new OffscreenCanvas(u,f).getContext("2d",{willReadFrequently:!0});g.drawImage(a,0,0,a.width,a.height,0,0,u,f),h={width:u,height:f,data:g.getImageData(0,0,u,f).data}}return{canvas:c,width:o,height:l,imageData:h}}#c(t,e){const{width:s,height:i}=this.#t;let n=s,r=i,a=this.#t;for(;n>2*t||r>2*e;){const o=n,l=r;n>2*t&&(n=Math.ceil(n/2)),r>2*e&&(r=Math.ceil(r/2));const c=new OffscreenCanvas(n,r);c.getContext("2d").drawImage(a,0,0,o,l,0,0,n,r),a=c.transferToImageBitmap()}return a}#f(){const[t,e]=this.parentDimensions,{width:s,height:i}=this,n=new Kt,r=Math.ceil(s*t*n.sx),a=Math.ceil(i*e*n.sy),o=this.#r;if(!o||o.width===r&&o.height===a)return;o.width=r,o.height=a;const l=this.#l?this.#t:this.#c(r,a),c=o.getContext("2d");c.filter=this._uiManager.hcmFilter,c.drawImage(l,0,0,l.width,l.height,0,0,r,a)}#y(t){if(t){if(this.#l){const i=this._uiManager.imageManager.getSvgUrl(this.#e);if(i)return i}const e=document.createElement("canvas");return{width:e.width,height:e.height}=this.#t,e.getContext("2d").drawImage(this.#t,0,0),e.toDataURL()}if(this.#l){const[e,s]=this.pageDimensions,i=Math.round(this.width*e*He.PDF_TO_CSS_UNITS),n=Math.round(this.height*s*He.PDF_TO_CSS_UNITS),r=new OffscreenCanvas(i,n);return r.getContext("2d").drawImage(this.#t,0,0,this.#t.width,this.#t.height,0,0,i,n),r.transferToImageBitmap()}return structuredClone(this.#t)}static async deserialize(t,e,s){let i=null,n=!1;if(t instanceof Wr){const{data:{rect:g,rotation:m,id:b,structParent:y,popupRef:A,richText:w,contentsObj:x,creationDate:S,modificationDate:E},container:_,parent:{page:{pageNumber:k}},canvas:I}=t;let P,B;I?(delete t.canvas,{id:P,bitmap:B}=s.imageManager.getFromCanvas(_.id,I),I.remove()):(n=!0,t._hasNoCanvas=!0);const W=(await e._structTree.getAriaAttributes(`${Fe}${b}`))?.get("aria-label")||"";i=t={annotationType:G.STAMP,bitmapId:P,bitmap:B,pageIndex:k-1,rect:g.slice(0),rotation:m,annotationElementId:b,id:b,deleted:!1,accessibilityData:{decorative:!1,altText:W},isSvg:!1,structParent:y,popupRef:A,richText:w,comment:x?.str||null,creationDate:S,modificationDate:E}}const r=await super.deserialize(t,e,s),{rect:a,bitmap:o,bitmapUrl:l,bitmapId:c,isSvg:h,accessibilityData:u}=t;n?(s.addMissingCanvas(t.id,r),r.#o=!0):c&&s.imageManager.isValidId(c)?(r.#e=c,o&&(r.#t=o)):r.#i=l,r.#l=h;const[f,p]=r.pageDimensions;return r.width=(a[2]-a[0])/f,r.height=(a[3]-a[1])/p,u&&(r.altTextData=u),r._initialData=i,t.comment&&r.setCommentData(t),r.#u=!!i,r}serialize(t=!1,e=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const s=Object.assign(super.serialize(t),{bitmapId:this.#e,isSvg:this.#l});if(this.addComment(s),t)return s.bitmapUrl=this.#y(!0),s.accessibilityData=this.serializeAltText(!0),s.isCopy=!0,s;const{decorative:i,altText:n}=this.serializeAltText(!1);if(!i&&n&&(s.accessibilityData={type:"Figure",alt:n}),this.annotationElementId){const a=this.#v(s);return a.isSame?null:(a.isSameAltText?delete s.accessibilityData:s.accessibilityData.structParent=this._initialData.structParent??-1,s.id=this.annotationElementId,delete s.bitmapId,s)}if(e===null)return s;e.stamps||=new Map;const r=this.#l?(s.rect[2]-s.rect[0])*(s.rect[3]-s.rect[1]):null;if(!e.stamps.has(this.#e))e.stamps.set(this.#e,{area:r,serialized:s}),s.bitmap=this.#y(!1);else if(this.#l){const a=e.stamps.get(this.#e);r>a.area&&(a.area=r,a.serialized.bitmap.close(),a.serialized.bitmap=this.#y(!1))}return s}#v(t){const{pageIndex:e,accessibilityData:{altText:s}}=this._initialData,i=t.pageIndex===e,n=(t.accessibilityData?.alt||"")===s;return{isSame:!this.hasEditedComment&&!this._hasBeenMoved&&!this._hasBeenResized&&i&&n,isSameAltText:n}}renderAnnotationElement(t){return this.deleted?(t.hide(),null):(t.updateEdited({rect:this.getPDFRect(),popup:this.comment}),null)}}class Jt{#t;#e=!1;#s=null;#i=null;#n=null;#a=new Map;#r=!1;#o=!1;#h=!1;#l=null;#u=null;#d=null;#p=null;#m=null;#g=-1;#c;static _initialized=!1;static#f=new Map([At,tn,zc,gt,Wt].map(t=>[t._editorType,t]));constructor({uiManager:t,pageIndex:e,div:s,structTreeLayer:i,accessibilityManager:n,annotationLayer:r,drawLayer:a,textLayer:o,viewport:l,l10n:c}){const h=[...Jt.#f.values()];if(!Jt._initialized){Jt._initialized=!0;for(const u of h)u.initialize(c,t)}t.registerEditorTypes(h),this.#c=t,this.pageIndex=e,this.div=s,this.#t=n,this.#s=r,this.viewport=l,this.#d=o,this.drawLayer=a,this._structTree=i,this.#c.addLayer(this)}get isEmpty(){return this.#a.size===0}get isInvisible(){return this.isEmpty&&this.#c.getMode()===G.NONE}updateToolbar(t){this.#c.updateToolbar(t)}updateMode(t=this.#c.getMode()){switch(this.#A(),t){case G.NONE:this.div.classList.toggle("nonEditing",!0),this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case G.INK:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick();break;case G.HIGHLIGHT:this.enableTextSelection(),this.togglePointerEvents(!1),this.disableClick();break;default:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);const{classList:e}=this.div;if(e.toggle("nonEditing",!1),t===G.POPUP)e.toggle("commentEditing",!0);else{e.toggle("commentEditing",!1);for(const s of Jt.#f.values())e.toggle(`${s._type}Editing`,t===s._editorType)}this.div.hidden=!1}hasTextLayer(t){return t===this.#d?.div}setEditingState(t){this.#c.setEditingState(t)}addCommands(t){this.#c.addCommands(t)}cleanUndoStack(t){this.#c.cleanUndoStack(t)}toggleDrawing(t=!1){this.div.classList.toggle("drawing",!t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){this.#s?.togglePointerEvents(t)}get#y(){return this.#a.size!==0?this.#a.values():this.#c.getEditors(this.pageIndex)}async enable(){this.#h=!0,this.div.tabIndex=0,this.togglePointerEvents(!0),this.div.classList.toggle("nonEditing",!1),this.#m?.abort(),this.#m=null;const t=new Set;for(const s of this.#y)s.enableEditing(),s.show(!0),s.annotationElementId&&(this.#c.removeChangedExistingAnnotation(s),t.add(s.annotationElementId));const e=this.#s;if(e)for(const s of e.getEditableAnnotations()){if(s.hide(),this.#c.isDeletedAnnotationElement(s.data.id)||t.has(s.data.id))continue;const i=await this.deserialize(s);i&&(this.addOrRebuild(i),i.enableEditing())}this.#h=!1,this.#c._eventBus.dispatch("editorsrendered",{source:this,pageNumber:this.pageIndex+1})}disable(){if(this.#o=!0,this.div.tabIndex=-1,this.togglePointerEvents(!1),this.div.classList.toggle("nonEditing",!0),this.#d&&!this.#m){this.#m=new AbortController;const i=this.#c.combinedSignal(this.#m);this.#d.div.addEventListener("pointerdown",n=>{const{clientX:a,clientY:o,timeStamp:l}=n,c=this.#g;if(l-c>500){this.#g=l;return}this.#g=-1;const{classList:h}=this.div;h.toggle("getElements",!0);const u=document.elementsFromPoint(a,o);if(h.toggle("getElements",!1),!this.div.contains(u[0]))return;let f;const p=new RegExp(`^${ts}[0-9]+$`);for(const m of u)if(p.test(m.id)){f=m.id;break}if(!f)return;const g=this.#a.get(f);g?.annotationElementId===null&&(lt(n),g.dblclick(n))},{signal:i,capture:!0})}const t=this.#s,e=[];if(t){const i=new Map,n=new Map;for(const r of this.#y){if(r.disableEditing(),!r.annotationElementId){e.push(r);continue}if(r.serialize()!==null){i.set(r.annotationElementId,r);continue}else n.set(r.annotationElementId,r);this.getEditableAnnotation(r.annotationElementId)?.show(),r.remove()}for(const r of t.getEditableAnnotations()){const{id:a}=r.data;if(this.#c.isDeletedAnnotationElement(a)){r.updateEdited({deleted:!0});continue}let o=n.get(a);if(o){o.resetAnnotationElement(r),o.show(!1),r.show();continue}o=i.get(a),o&&(this.#c.addChangedExistingAnnotation(o),o.renderAnnotationElement(r)&&o.show(!1)),r.show()}}this.#A(),this.isEmpty&&(this.div.hidden=!0);const{classList:s}=this.div;for(const i of Jt.#f.values())s.remove(`${i._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),t?.updateFakeAnnotations(e),this.#o=!1}getEditableAnnotation(t){return this.#s?.getEditableAnnotation(t)||null}setActiveEditor(t){this.#c.getActive()!==t&&this.#c.setActiveEditor(t)}enableTextSelection(){if(this.div.tabIndex=-1,this.#d?.div&&!this.#p){this.#p=new AbortController;const t=this.#c.combinedSignal(this.#p);this.#d.div.addEventListener("pointerdown",this.#v.bind(this),{signal:t}),this.#d.div.classList.add("highlighting")}}disableTextSelection(){this.div.tabIndex=0,this.#d?.div&&this.#p&&(this.#p.abort(),this.#p=null,this.#d.div.classList.remove("highlighting"))}#v(t){this.#c.unselectAll();const{target:e}=t;if(e===this.#d.div||(e.getAttribute("role")==="img"||e.classList.contains("endOfContent")||e.classList.contains("textLayerImages")||e.classList.contains("textLayerImagePlaceholder"))&&this.#d.div.contains(e)){const{isMac:s}=J.platform;if(t.button!==0||t.ctrlKey&&s)return;this.#c.showAllEditors("highlight",!0,!0),this.#d.div.classList.add("free"),this.toggleDrawing(),gt.startHighlighting(this,this.#c.direction==="ltr",{target:this.#d.div,x:t.x,y:t.y}),this.#d.div.addEventListener("pointerup",()=>{this.#d.div.classList.remove("free"),this.toggleDrawing(!0)},{once:!0,signal:this.#c._signal}),t.preventDefault()}}enableClick(){if(this.#i)return;this.#i=new AbortController;const t=this.#c.combinedSignal(this.#i);this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t});const e=this.pointerup.bind(this);this.div.addEventListener("pointerup",e,{signal:t}),this.div.addEventListener("pointercancel",e,{signal:t})}disableClick(){this.#i?.abort(),this.#i=null}attach(t){this.#a.set(t.id,t);const{annotationElementId:e}=t;e&&this.#c.isDeletedAnnotationElement(e)&&this.#c.removeDeletedAnnotationElement(t)}detach(t){this.#a.delete(t.id),this.#t?.removePointerInTextLayer(t.contentDiv),!this.#o&&t.annotationElementId&&this.#c.addDeletedAnnotationElement(t)}remove(t){this.detach(t),this.#c.removeEditor(t),t.div.remove(),t.isAttachedToDOM=!1}changeParent(t){t.parent!==this&&(t.parent&&t.annotationElementId&&(this.#c.addDeletedAnnotationElement(t),N.deleteAnnotationElement(t),t.annotationElementId=null),this.attach(t),t.parent?.detach(t),t.setParent(this),t.div&&t.isAttachedToDOM&&(t.div.remove(),this.div.append(t.div)))}add(t){if(!(t.parent===this&&t.isAttachedToDOM)){if(this.changeParent(t),this.#c.addEditor(t),this.attach(t),!t.isAttachedToDOM){const e=t.render();this.div.append(e),t.isAttachedToDOM=!0}t.fixAndSetPosition(),t.onceAdded(!this.#h),this.#c.addToAnnotationStorage(t),t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){if(!t.isAttachedToDOM)return;const{activeElement:e}=document;t.div.contains(e)&&!this.#n&&(t._focusEventsAllowed=!1,this.#n=setTimeout(()=>{this.#n=null,t.div.contains(document.activeElement)?t._focusEventsAllowed=!0:(t.div.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this.#c._signal}),e.focus())},0)),t._structTreeParentId=this.#t?.moveElementInDOM(this.div,t.div,t.contentDiv,!0)}addOrRebuild(t){t.needsToBeRebuilt()?(t.parent||=this,t.rebuild(),t.show()):this.add(t)}addUndoableEditor(t){const e=()=>t._uiManager.rebuild(t),s=()=>{t.remove()};this.addCommands({cmd:e,undo:s,mustExec:!1})}getEditorByUID(t){for(const e of this.#a.values())if(e.uid===t)return e;return null}get#b(){return Jt.#f.get(this.#c.getMode())}combinedSignal(t){return this.#c.combinedSignal(t)}#S(t){const e=this.#b;return e?new e.prototype.constructor(t):null}canCreateNewEmptyEditor(){return this.#b?.canCreateNewEmptyEditor()}async pasteEditor(t,e){this.updateToolbar(t),await this.#c.updateMode(t.mode);const{offsetX:s,offsetY:i}=this.#C(),n=this.#c.getId(),r=this.#S({parent:this,id:n,x:s,y:i,uiManager:this.#c,isCentered:!0,...e});r&&this.add(r)}async deserialize(t){return await Jt.#f.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#c)||null}createAndAddNewEditor(t,e,s={}){const i=this.#c.getId(),n=this.#S({parent:this,id:i,x:t.offsetX,y:t.offsetY,uiManager:this.#c,isCentered:e,...s});return n&&this.add(n),n}get boundingClientRect(){return this.div.getBoundingClientRect()}#C(){const{x:t,y:e,width:s,height:i}=this.boundingClientRect,n=Math.max(0,t),r=Math.max(0,e),a=Math.min(window.innerWidth,t+s),o=Math.min(window.innerHeight,e+i),l=(n+a)/2-t,c=(r+o)/2-e,[h,u]=this.viewport.rotation%180===0?[l,c]:[c,l];return{offsetX:h,offsetY:u}}addNewEditor(t={}){this.createAndAddNewEditor(this.#C(),!0,t)}setSelected(t){this.#c.setSelected(t)}toggleSelected(t){this.#c.toggleSelected(t)}unselect(t){this.#c.unselect(t)}pointerup(t){const{isMac:e}=J.platform;if(t.button!==0||t.ctrlKey&&e||t.target!==this.div||!this.#r||(this.#r=!1,this.#b?.isDrawer&&this.#b.supportMultipleDrawings))return;if(!this.#e){this.#e=!0;return}const s=this.#c.getMode();if(s===G.STAMP||s===G.POPUP||s===G.SIGNATURE){this.#c.unselectAll();return}this.createAndAddNewEditor(t,!1)}pointerdown(t){if(this.#c.getMode()===G.HIGHLIGHT&&this.enableTextSelection(),this.#r){this.#r=!1;return}const{isMac:e}=J.platform;if(t.button!==0||t.ctrlKey&&e||t.target!==this.div)return;if(this.#r=!0,this.#b?.isDrawer){this.startDrawingSession(t);return}const s=this.#c.getActive();this.#e=!s||s.isEmpty()}startDrawingSession(t){if(this.div.focus({preventScroll:!0}),this.#l){this.#b.startDrawing(this,this.#c,!1,t);return}this.#c.setCurrentDrawingSession(this),this.#l=new AbortController;const e=this.#c.combinedSignal(this.#l);this.div.addEventListener("blur",({relatedTarget:s})=>{s&&!this.div.contains(s)&&(this.#u=null,this.commitOrRemove())},{signal:e}),this.#b.startDrawing(this,this.#c,!1,t)}pause(t){if(t){const{activeElement:e}=document;this.div.contains(e)&&(this.#u=e);return}this.#u&&setTimeout(()=>{this.#u?.focus(),this.#u=null},0)}endDrawingSession(t=!1){return this.#l?(this.#c.setCurrentDrawingSession(null),this.#l.abort(),this.#l=null,this.#u=null,this.#b.endDrawing(t)):null}findNewParent(t,e,s){const i=this.#c.findParent(e,s);return i===null||i===this?!1:(i.changeParent(t),!0)}commitOrRemove(){return this.#l?(this.endDrawingSession(),!0):!1}onScaleChanging(){this.#l&&this.#b.onScaleChangingWhenDrawing(this)}destroy(){this.commitOrRemove(),this.#c.getActive()?.parent===this&&(this.#c.commitOrRemove(),this.#c.setActiveEditor(null)),this.#n&&(clearTimeout(this.#n),this.#n=null);for(const t of this.#a.values())this.#t?.removePointerInTextLayer(t.contentDiv),t.setParent(null),t.isAttachedToDOM=!1,t.div.remove();this.div=null,this.#a.clear(),this.#c.removeLayer(this)}#A(){for(const t of this.#a.values())t.isEmpty()&&t.remove()}async render({viewport:t}){this.viewport=t,xe(this.div,t);for(const e of this.#c.getEditors(this.pageIndex))this.add(e),e.rebuild();await this.#c.findClonesForPage(this),this.div.hidden=this.isEmpty,this.updateMode()}update({viewport:t}){this.#c.commitOrRemove(),this.#A();const e=this.viewport.rotation,s=t.rotation;if(this.viewport=t,xe(this.div,{rotation:s}),e!==s)for(const i of this.#a.values())i.rotate(s)}get pageDimensions(){const{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return this.#c.viewParameters.realScale}}function $c(d,t){return d===t?0:d.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1}function Ts(d){return d?d.nodeType===Node.ELEMENT_NODE?d.closest(".textLayer"):d.parentElement?.closest(".textLayer")||null:null}function Gc(d,t,e,s){if(d===e)return t<=s;const i=d.compareDocumentPosition(e);return i&Node.DOCUMENT_POSITION_FOLLOWING?!0:i&Node.DOCUMENT_POSITION_PRECEDING?!1:null}function lr(d,t,e){if(d.nodeType!==Node.ELEMENT_NODE||!d.classList.contains("textLayer")||t!==d.childNodes.length)return{container:d,offset:t};let s=d.lastChild;return s?.nodeType===Node.ELEMENT_NODE&&s.classList.contains("endOfContent")&&(s=s.previousSibling),!s||!e.contains(s)?null:s.nodeType===Node.TEXT_NODE?{container:s,offset:s.textContent.length}:{container:s,offset:s.childNodes.length}}class U{#t=null;#e=new Map;#s=null;#i=null;#n=null;#a=null;#r=new Map;static#o=0;static#h=0;static#l=null;static#u=new Set;static#d=!1;static#p=new Set;static#m=new WeakMap;constructor({filterFactory:t=null,pageColors:e=null,pageIndex:s,textLayer:i=null}){if(this.pageIndex=s,this.#i=t,this.#n=e,i){const n=U.#m.get(i);if(n?.selectionDiv&&(n.selectionDiv.remove(),U.#u.delete(n.selectionDiv)),U.#m.set(i,{drawLayer:this}),U.#p.add(i),this.#s=i,this.#a=new MutationObserver(r=>{if(!(!this.#t||!this.#s?.isConnected||!U.#c())){for(const{addedNodes:a}of r)for(const o of a)if(o.nodeType===Node.ELEMENT_NODE&&o.classList.contains("endOfContent")){U.#y();return}}}),this.#a.observe(i,{childList:!0}),U.#l===null){U.#l=new AbortController;const{signal:r}=U.#l;document.addEventListener("selectionchange",U.#y.bind(U),{signal:r}),document.addEventListener("pointerdown",()=>{U.#d=!0},{signal:r}),document.addEventListener("pointerup",()=>{U.#d=!1},{signal:r}),window.addEventListener("blur",()=>{U.#d=!1},{signal:r})}}}setParent(t){if(!this.#t){this.#t=t,this.#s?.isConnected&&U.#c()&&U.#y();return}if(this.#t!==t){if(this.#e.size>0)for(const e of this.#e.values())e.remove(),t.append(e);this.#t=t}}static#g(t){const e=this.#m.get(t);e?.selectionDiv&&(e.selectionDiv.remove(),this.#u.delete(e.selectionDiv),e.selectionDiv=null,e.path=null)}static#c(){const t=document.getSelection();return!!t&&!t.isCollapsed}static#f(){return[...this.#p].filter(t=>t.isConnected).sort($c)}static#y(){const t=document.getSelection();if(!t||t.isCollapsed){for(const r of this.#u)r.remove();this.#u.clear();return}const e=new WeakMap,s=this.#f(),i=[];for(let r=0,a=t.rangeCount;r<a;r++){const o=t.getRangeAt(r);if(o.collapsed)continue;let{startContainer:l,startOffset:c,endContainer:h,endOffset:u}=o,f=Ts(l),p=Ts(h);const g=f===null,m=p===null;if(this.#d&&g!==m)return;if(t.rangeCount===1){const{anchorNode:A,anchorOffset:w,focusNode:x,focusOffset:S}=t,E=Ts(A),_=Ts(x),k=Gc(A,w,x,S);E&&_&&k!==null&&(k?(l=A,c=w,f=E,h=x,u=S,p=_):(l=x,c=S,f=_,h=A,u=w,p=E))}const b=s.filter(A=>o.intersectsNode(A));if(b.length===0)continue;let y=!1;if(f||(f=b[0],l=f,c=0,y=!0),p||(p=b.at(-1),h=p,u=p.childNodes.length,y=!0),h.nodeType===Node.ELEMENT_NODE){if(h.classList.contains("endOfContent")){const A=h.previousSibling;if(!A)continue;h=A,u=A.nodeType===Node.TEXT_NODE?A.textContent.length:A.childNodes.length}else if(h.classList.contains("textLayer")&&h.childNodes.length===u){const A=lr(h,u,p);if(!A)continue;h=A.container,u=A.offset}}if(l.nodeType===Node.ELEMENT_NODE){const A=lr(l,c,f);if(!A)continue;l=A.container,c=A.offset}if(f===p&&!y&&b.includes(f)){i.push([o,f]);continue}for(const A of b){const w=A.firstChild;if(!w)continue;const x=document.createRange();if(A===f?x.setStart(l,c):x.setStartBefore(w),A===p)x.setEnd(h,u);else{const S=A.lastChild;if(!S)continue;if(S.nodeType===Node.ELEMENT_NODE&&S.classList.contains("endOfContent")){const E=S.previousSibling;if(!E)continue;x.setEndAfter(E)}else x.setEndAfter(S)}x.collapsed||i.push([x,A])}}const n=new Set(i.map(r=>r[1]));for(const r of this.#p)n.has(r)||this.#g(r);for(const[r,a]of i){const o=U.#m.get(a);if(!o)continue;let l=e.get(a);if(!l){const p=a.getBoundingClientRect();l=(g,m,b,y)=>({x:(g-p.x)/p.width,y:(m-p.y)/p.height,width:b/p.width,height:y/p.height}),e.set(a,l)}const c=[];for(let{x:p,y:g,width:m,height:b}of r.getClientRects())m===0||b===0||({x:p,y:g,width:m,height:b}=l(p,g,m,b),!(m===1&&b===1)&&c.push(`M${p} ${g} h${m} v${b} h-${m} Z`));if(c.length===0)continue;const h=o.drawLayer;let u=o.selectionDiv,f=o.path;if(!u){const p=`clip_selection_${U.#h++}`;u=document.createElement("div"),u.className="selection",u.style.clipPath=`url(#${p})`;const g=h.#i?.createSelectionStyle(h.#n);if(g)for(const[y,A]of Object.entries(g))u.style.setProperty(y,A);const m=U._svgFactory.create(1,1,!0);m.setAttribute("aria-hidden","true"),m.setAttribute("width","100%"),m.setAttribute("height","100%");const b=U._svgFactory.createElement("clipPath");b.setAttribute("id",p),b.setAttribute("clipPathUnits","objectBoundingBox"),f=U._svgFactory.createElement("path"),b.append(f),m.append(b),u.append(m),o.path=f,o.selectionDiv=u}!u.parentNode&&h.#t&&(h.#t.append(u),this.#u.add(u)),f.setAttribute("d",c.join(" "))}}static get _svgFactory(){return z(this,"_svgFactory",new Os)}static#v(t,[e,s,i,n]){const{style:r}=t;r.top=`${100*s}%`,r.left=`${100*e}%`,r.width=`${100*i}%`,r.height=`${100*n}%`}#b(){const t=U._svgFactory.create(1,1,!0);return this.#t.append(t),t.setAttribute("aria-hidden","true"),t}#S(t,e){const s=U._svgFactory.createElement("clipPath");t.append(s);const i=`clip_${e}`;s.setAttribute("id",i),s.setAttribute("clipPathUnits","objectBoundingBox");const n=U._svgFactory.createElement("use");return s.append(n),n.setAttribute("href",`#${e}`),n.classList.add("clip"),i}#C(t,e){for(const[s,i]of Object.entries(e))i===null?t.removeAttribute(s):t.setAttribute(s,i)}draw(t,e=!1,s=!1){const i=U.#o++,n=this.#b(),r=U._svgFactory.createElement("defs");n.append(r);const a=U._svgFactory.createElement("path");r.append(a);const o=`path_${i}`;a.setAttribute("id",o),a.setAttribute("vector-effect","non-scaling-stroke"),e&&this.#r.set(i,a);const l=s?this.#S(r,o):null,c=U._svgFactory.createElement("use");return n.append(c),c.setAttribute("href",`#${o}`),this.updateProperties(n,t),this.#e.set(i,n),{id:i,clipPathId:`url(#${l})`}}drawOutline(t,e){const s=U.#o++,i=this.#b(),n=U._svgFactory.createElement("defs");i.append(n);const r=U._svgFactory.createElement("path");n.append(r);const a=`path_${s}`;r.setAttribute("id",a),r.setAttribute("vector-effect","non-scaling-stroke");let o;if(e){const h=U._svgFactory.createElement("mask");n.append(h),o=`mask_${s}`,h.setAttribute("id",o),h.setAttribute("maskUnits","objectBoundingBox");const u=U._svgFactory.createElement("rect");h.append(u),u.setAttribute("width","1"),u.setAttribute("height","1"),u.setAttribute("fill","white");const f=U._svgFactory.createElement("use");h.append(f),f.setAttribute("href",`#${a}`),f.setAttribute("stroke","none"),f.setAttribute("fill","black"),f.setAttribute("fill-rule","nonzero"),f.classList.add("mask")}const l=U._svgFactory.createElement("use");i.append(l),l.setAttribute("href",`#${a}`),o&&l.setAttribute("mask",`url(#${o})`);const c=l.cloneNode();return i.append(c),l.classList.add("mainOutline"),c.classList.add("secondaryOutline"),this.updateProperties(i,t),this.#e.set(s,i),s}finalizeDraw(t,e){this.#r.delete(t),this.updateProperties(t,e)}updateProperties(t,e){if(!e)return;const{root:s,bbox:i,rootClass:n,path:r}=e,a=typeof t=="number"?this.#e.get(t):t;if(a){if(s&&this.#C(a,s),i&&U.#v(a,i),n){const{classList:o}=a;for(const[l,c]of Object.entries(n))o.toggle(l,c)}if(r){const l=a.firstElementChild.firstElementChild;this.#C(l,r)}}}updateParent(t,e){if(e===this)return;const s=this.#e.get(t);s&&(e.#t.append(s),this.#e.delete(t),e.#e.set(t,s))}remove(t){this.#r.delete(t),this.#t!==null&&(this.#e.get(t).remove(),this.#e.delete(t))}destroy(){this.#t=null;for(const t of this.#e.values())t.remove();this.#e.clear(),this.#r.clear(),this.#a?.disconnect(),this.#a=null,this.#s&&(U.#m.get(this.#s)?.drawLayer===this&&(U.#g(this.#s),U.#m.delete(this.#s),U.#p.delete(this.#s),U.#p.size===0&&(U.#l?.abort(),U.#l=null,U.#d=!1)),this.#s=null)}}function Ms(d){return`${(d*100).toFixed(2)}%`}class Bs{#t=[];#e=new Map;#s=null;#i=0;#n=0;#a=0;static#r=null;constructor(t,e,s,i){this.#i=t,this.#t=e,this.#n=s.rawDims.pageWidth,this.#a=s.rawDims.pageHeight,this.#s=i}render(){const t=document.createElement("div");t.className="textLayerImages";for(let e=0;e<this.#t.length;e+=6){const s=this.#o(this.#t.subarray(e,e+6));s&&t.append(s)}return t.addEventListener("contextmenu",e=>{if(!(e.target instanceof HTMLCanvasElement))return;const s=e.target,i=this.#e.get(s);if(!i)return;const n=Bs.#r?.deref();if(n===s)return;n&&(n.width=0,n.height=0),Bs.#r=new WeakRef(s);const{inverseTransform:r,x1:a,y1:o,width:l,height:c}=i,h=this.#s(),u=Math.ceil(a*h.width),f=Math.ceil(o*h.height),p=Math.floor((a+l/this.#n)*h.width),g=Math.floor((o+c/this.#a)*h.height);s.width=p-u,s.height=g-f;const m=s.getContext("2d");m.setTransform(...r),m.translate(-u,-f),m.drawImage(h,0,0)}),t}#o([t,e,s,i,n,r]){const a=Math.hypot((n-t)*this.#n,(r-e)*this.#a),o=Math.hypot((s-t)*this.#n,(i-e)*this.#a);if(a<this.#i||o<this.#i)return null;const l=[(n-t)*this.#n/a,(r-e)*this.#a/a,(s-t)*this.#n/o,(i-e)*this.#a/o,0,0],c=T.inverseTransform(l),h=document.createElement("canvas");return h.className="textLayerImagePlaceholder",h.width=0,h.height=0,Object.assign(h.style,{opacity:0,position:"absolute",left:Ms(t),top:Ms(e),width:Ms(a/this.#n),height:Ms(o/this.#a),transformOrigin:"0% 0%",transform:`matrix(${l.join(",")})`}),this.#e.set(h,{inverseTransform:c,width:a,height:o,x1:t,y1:e}),h}}globalThis._pdfjsTestingUtils={HighlightOutliner:Ni};globalThis.pdfjsLib={AbortException:re,AnnotationEditorLayer:Jt,AnnotationEditorParamsType:X,AnnotationEditorType:G,AnnotationEditorUIManager:ae,AnnotationLayer:Zi,AnnotationMode:ie,AnnotationType:ft,applyOpacity:Jo,build:bc,ColorPicker:Lt,createValidAbsoluteUrl:vr,CSSConstants:Qo,DOMSVGFactory:Os,DrawLayer:U,FeatureTest:J,fetchData:Ui,findContrastColor:Zo,getDocument:jr,getFilenameFromUrl:Xo,getPdfFilenameFromUrl:Yo,getRGB:ds,getRGBA:hs,getUuid:xr,GlobalWorkerOptions:Be,ImageKind:Ps,InvalidPDFException:Ci,isDataScheme:Gs,isPdfFile:$i,isValidExplicitDest:xl,makeArr:ls,makeMap:Hi,makeObj:Ei,MathClamp:nt,noContextMenu:Rt,normalizeUnicode:Vo,OPS:Xt,OutputScale:Kt,PasswordException:Si,PasswordResponses:Bo,PDFDataRangeTransport:Hr,PDFDateString:_i,PDFWorker:ns,PermissionFlag:Oo,PixelsPerInch:He,RenderingCancelledException:zi,renderRichText:Sr,ResponseException:Ls,setLayerDimensions:xe,shadow:z,SignatureExtractor:Ne,stopEvent:lt,SupportedImageMimeTypes:ki,TextLayer:Mt,TextLayerImages:Bs,TouchManager:Vs,updateUrlHash:Ar,Util:T,VerbosityLevel:Hs,version:mc,XfaLayer:wr};const Vc="/assets/pdf.worker.min-DEtVeC4l.mjs";Be.workerSrc=Vc;async function Wc(d){const t=await d.arrayBuffer(),e=await jr({data:t}).promise,s=[];for(let i=1;i<=e.numPages;i++){const a=(await(await e.getPage(i)).getTextContent()).items.map(o=>"str"in o?o.str:"").join(" ");s.push(a)}return s.join(`
|
|
56
|
+
|
|
57
|
+
`)}const as={list:d=>["conversations",d??""],detail:d=>["conversation",d],folders:["folders"]};function Xc(d){return os({queryKey:as.list(d),queryFn:()=>Da(d),staleTime:0,retry:!1})}function Yc(){return os({queryKey:as.folders,queryFn:()=>Na(),staleTime:0,retry:!1})}function Kc(d){return os({queryKey:as.detail(d),queryFn:()=>Fa(d),enabled:!!d,retry:!1})}function fs(){const d=hr(),t=()=>{d.invalidateQueries({queryKey:["conversations"]})},e=i=>{d.invalidateQueries({queryKey:as.detail(i)})},s=()=>{d.invalidateQueries({queryKey:as.folders})};return{create:jt({mutationFn:i=>Ia(i),onSuccess:t}),update:jt({mutationFn:i=>Pa(i.id,i),onSuccess:(i,n)=>{t(),e(n.id)}}),remove:jt({mutationFn:i=>Ma(i),onSuccess:t}),stop:jt({mutationFn:i=>Ta(i)}),editMsg:jt({mutationFn:i=>ka(i.convId,i.msgId,i.content),onSuccess:(i,n)=>e(n.convId)}),deleteMsg:jt({mutationFn:i=>_a(i.convId,i.msgId),onSuccess:(i,n)=>e(n.convId)}),regenerate:jt({mutationFn:i=>Ea(i),onSuccess:(i,n)=>e(n)}),createFolder:jt({mutationFn:i=>Ca(i),onSuccess:()=>{s(),t()}}),renameFolder:jt({mutationFn:i=>Sa(i.id,i.name),onSuccess:()=>{s(),t()}}),deleteFolder:jt({mutationFn:i=>wa(i),onSuccess:()=>{s(),t()}}),moveToFolder:jt({mutationFn:i=>xa(i.convId,i.folderId),onSuccess:(i,n)=>{s(),t(),e(n.convId)}})}}function qc(d,t){const e=d[d.length-1];if(e&&e.kind==="text"){const s=d.slice();return s[s.length-1]={kind:"text",text:e.text+t},s}return[...d,{kind:"text",text:t}]}function Qc(d,t){const e=d.findIndex(s=>s.kind==="tool"&&s.call.id===t.id);if(e>=0){const s=d.slice(),i=s[e];return s[e]={kind:"tool",call:{...i.call,...t,name:t.name&&t.name!=="undefined"?t.name:i.call.name,args:t.args&&Object.keys(t.args).length?t.args:i.call.args}},s}return[...d,{kind:"tool",call:t}]}function Jc(d,t){if(d==="web_search")return`Search the web for "${String(t.query)}"`;if(d==="fetch_url")return`Fetch ${String(t.url)}`;if(d==="run_code"){const e=String(t.code);return`Run JavaScript: ${e.slice(0,80)}${e.length>80?"…":""}`}if(d.startsWith("mcp__")){const s=d.match(/^mcp__([^_]+(?:_[^_]+)*)__/)?.[1]??"server";return`Call "${fr(d)}" on ${s}`}return`Run "${d}"`}function Zc({pending:d,convId:t,onResolved:e}){const[s,i]=R.useState(!1),[n,r]=R.useState(!1),a=async o=>{if(!s){r(!0),i(!0);try{await La(t,d.id,d.name,o)}catch(l){it.error(l instanceof ge?l.message:"Could not send your decision — please try again."),r(!1)}finally{i(!1),e()}}};return n?null:v.jsxs("div",{className:"mx-8 mb-3 rounded-md border border-[color:var(--warn,#ca8a04)] bg-[color-mix(in_srgb,var(--warn,#ca8a04)_8%,transparent)] px-3 py-2.5 text-[13px]",children:[v.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-2",children:[v.jsx("span",{className:"font-medium text-ink",children:"Tool call needs your approval:"}),v.jsx("span",{className:"font-mono text-[12px] text-ink",children:fr(d.name)})]}),v.jsx("p",{className:"mt-0.5 text-[12px] text-muted",children:Jc(d.name,d.args)}),v.jsxs("div",{className:"mt-2 flex flex-wrap gap-1.5",children:[v.jsx(yt,{size:"sm",variant:"outline",disabled:s,onClick:()=>{a("deny")},children:"Deny"}),v.jsx(yt,{size:"sm",disabled:s,onClick:()=>{a("allow")},children:"Allow"}),v.jsx(yt,{size:"sm",variant:"outline",disabled:s,onClick:()=>{a("allow_chat")},children:"Allow for this chat"}),v.jsx(yt,{size:"sm",variant:"outline",disabled:s,onClick:()=>{a("always_allow")},children:"Always Allow"})]})]})}function cr(d){return d>=1e6?`${(d/1e6).toFixed(1)}M`:d>=1e3?`${(d/1e3).toFixed(1)}k`:String(d)}function th({ctxUsed:d,ctxMax:t}){if(t<=0)return null;const e=t>0?d/t:0,s=Math.min(1,e),i=Math.round(s*100),n=e>.9?"var(--err)":e>.75?"var(--warn)":"var(--accent)",r=e>.9?{color:"var(--err)"}:e>.75?{color:"var(--warn)"}:{},a=e>.9?"Context nearly full — older messages may be truncated":`Context: ${d.toLocaleString()} / ${t.toLocaleString()} tokens`;return v.jsxs("div",{className:"flex items-center gap-1.5 ml-auto",title:a,children:[v.jsx("div",{className:"h-[3px] w-20 overflow-hidden rounded-full shrink-0",style:{background:"var(--border)"},children:v.jsx("div",{className:"h-full rounded-full transition-all duration-300",style:{width:`${(s*100).toFixed(1)}%`,background:n}})}),v.jsx("span",{className:"text-[11px] text-faint whitespace-nowrap tabular-nums shrink-0",style:r,children:`${cr(d)} / ${cr(t)} · ${i}%`})]})}const eh="tllm.confirmDeleteConversation",sh=()=>localStorage.getItem(eh)!=="false";function ih(d){const t=Date.now()-new Date(d).getTime();return t<6e4?"just now":t<36e5?`${Math.floor(t/6e4)}m ago`:t<864e5?`${Math.floor(t/36e5)}h ago`:`${Math.floor(t/864e5)}d ago`}function nh({activeId:d,onSelect:t,onNew:e,onImport:s,collapsed:i,onToggle:n,generating:r,onDeleted:a}){const[o,l]=R.useState(""),[c,h]=R.useState(""),[u,f]=R.useState(null),[p,g]=R.useState(null),[m,b]=R.useState(new Set),[y,A]=R.useState(!1),[w,x]=R.useState(""),S=R.useRef(null),E=fs(),k=Xc(c||void 0).data?.conversations??[],P=Yc().data?.folders??[],B=!!c,{byFolder:W,ungrouped:Y}=R.useMemo(()=>{const M=new Set(P.map(Bt=>Bt.id)),j=new Map,dt=[];for(const Bt of k){const _t=Bt.folderId;if(_t&&M.has(_t)){const tt=j.get(_t)??[];tt.push(Bt),j.set(_t,tt)}else dt.push(Bt)}return{byFolder:j,ungrouped:dt}},[k,P]);R.useEffect(()=>{const M=setTimeout(()=>h(o),200);return()=>clearTimeout(M)},[o]),R.useEffect(()=>{const M=j=>{(j.ctrlKey||j.metaKey)&&j.key==="k"&&(j.preventDefault(),S.current?.focus())};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[]);const Z=M=>{b(j=>{const dt=new Set(j);return dt.has(M)?dt.delete(M):dt.add(M),dt})},L=M=>{const j=M.id===d;E.remove.mutate(M.id,{onSuccess:()=>{it.success("Conversation deleted"),j&&a?.(M.id)},onError:()=>{it.error("Could not delete conversation.")}})},F=(M,j)=>{M.stopPropagation(),sh()?f(j):L(j)},rt=(M,j)=>{E.moveToFolder.mutate({convId:M.id,folderId:j},{onError:()=>{it.error("Could not move conversation.")}})},ht=()=>{const M=w.trim();A(!1),x(""),M&&E.createFolder.mutate(M,{onSuccess:j=>{b(dt=>new Set(dt).add(j.id))},onError:()=>{it.error("Could not create folder.")}})},vt=M=>{E.deleteFolder.mutate(M.id,{onSuccess:()=>{it.success("Folder deleted")},onError:()=>{it.error("Could not delete folder.")}})},Ot=!!u&&u.id===d&&!!r;return i?v.jsxs("div",{className:"flex h-full flex-col items-center gap-1 border-r border-border bg-panel-2 py-3",children:[n&&v.jsx(yt,{size:"icon",variant:"ghost",onClick:n,title:"Expand sidebar",className:"h-7 w-7",children:v.jsx(ro,{size:15})}),v.jsx(yt,{size:"icon",variant:"ghost",onClick:e,title:"New chat (Ctrl+N)",className:"h-7 w-7",children:v.jsx(Fn,{size:15})}),s&&v.jsx(yt,{size:"icon",variant:"ghost",onClick:s,title:"Import chat (.turbollm-chat.json or OpenAI JSON)",className:"h-7 w-7",children:v.jsx(Ai,{size:15})})]}):v.jsxs("div",{className:"flex h-full flex-col border-r border-border bg-panel-2",children:[v.jsxs("div",{className:"flex items-center gap-2 px-3 py-3",children:[n&&v.jsx(yt,{size:"icon",variant:"ghost",onClick:n,title:"Collapse sidebar",className:"h-7 w-7 shrink-0",children:v.jsx(ao,{size:15})}),v.jsxs("div",{className:"relative flex-1",children:[v.jsx(oo,{size:13,className:"absolute left-2.5 top-1/2 -translate-y-1/2 text-faint"}),v.jsx(Ba,{ref:S,value:o,onChange:M=>l(M.target.value),placeholder:"Search…",className:"h-7 pl-7 text-[12px]"})]}),v.jsx(yt,{size:"icon",variant:"ghost",onClick:e,title:"New chat (Ctrl+N)",className:"h-7 w-7 shrink-0",children:v.jsx(Fn,{size:15})}),v.jsx(yt,{size:"icon",variant:"ghost",onClick:()=>{A(!0),x("")},title:"New folder",className:"h-7 w-7 shrink-0",children:v.jsx(co,{size:15})}),s&&v.jsx(yt,{size:"icon",variant:"ghost",onClick:s,title:"Import chat (.turbollm-chat.json or OpenAI JSON)",className:"h-7 w-7 shrink-0",children:v.jsx(Ai,{size:15})})]}),y&&v.jsxs("div",{className:"flex items-center gap-2 px-3 pb-2",children:[v.jsx(Fs,{size:13,className:"shrink-0 text-faint"}),v.jsx("input",{autoFocus:!0,className:"w-full bg-transparent text-[13px] font-medium text-ink outline-none placeholder:text-faint",value:w,placeholder:"Folder name…",onChange:M=>x(M.target.value),onBlur:ht,onKeyDown:M=>{M.key==="Enter"&&ht(),M.key==="Escape"&&(A(!1),x(""))}})]}),v.jsx("div",{className:"flex-1 overflow-y-auto px-1 pb-2",children:B?v.jsxs(v.Fragment,{children:[k.length===0&&v.jsx("p",{className:"px-3 py-4 text-[12px] text-faint",children:"No results."}),k.map(M=>v.jsx(Ri,{conv:M,active:M.id===d,folders:P,onSelect:t,onDelete:F,onMove:rt},M.id))]}):v.jsxs(v.Fragment,{children:[k.length===0&&P.length===0&&v.jsx("p",{className:"px-3 py-4 text-[12px] text-faint",children:"No conversations yet."}),P.map(M=>v.jsx(rh,{folder:M,items:W.get(M.id)??[],open:m.has(M.id),onToggle:()=>Z(M.id),onRequestDelete:()=>g(M),activeId:d,folders:P,onSelect:t,onDelete:F,onMove:rt},M.id)),P.length>0&&Y.length>0&&v.jsx("div",{className:"px-2 py-1.5 text-[11px] font-medium uppercase tracking-wide text-faint",children:"Uncategorized"}),Y.map(M=>v.jsx(Ri,{conv:M,active:M.id===d,folders:P,onSelect:t,onDelete:F,onMove:rt},M.id))]})}),v.jsx(En,{open:!!u,onOpenChange:M=>{M||f(null)},children:v.jsxs(_n,{children:[v.jsxs(kn,{children:[v.jsx(Tn,{children:"Delete this conversation?"}),v.jsx(Mn,{children:u?v.jsxs(v.Fragment,{children:[v.jsx("span",{className:"font-medium text-ink",children:u.title||"Untitled conversation"})," ","will be permanently deleted. This can’t be undone.",Ot&&v.jsx(v.Fragment,{children:" A response is still generating in this conversation — it will be stopped and lost."})]}):null})]}),v.jsxs(Pn,{children:[v.jsx(In,{children:"Cancel"}),v.jsx(Dn,{onClick:()=>{u&&L(u),f(null)},children:"Delete"})]})]})}),v.jsx(En,{open:!!p,onOpenChange:M=>{M||g(null)},children:v.jsxs(_n,{children:[v.jsxs(kn,{children:[v.jsx(Tn,{children:"Delete this folder?"}),v.jsx(Mn,{children:p?v.jsxs(v.Fragment,{children:[v.jsx("span",{className:"font-medium text-ink",children:p.name})," ","will be deleted. Conversations inside it won’t be deleted — they’ll move back to Uncategorized."]}):null})]}),v.jsxs(Pn,{children:[v.jsx(In,{children:"Cancel"}),v.jsx(Dn,{onClick:()=>{p&&vt(p),g(null)},children:"Delete folder"})]})]})})]})}function rh({folder:d,items:t,open:e,onToggle:s,onRequestDelete:i,activeId:n,folders:r,onSelect:a,onDelete:o,onMove:l}){const[c,h]=R.useState(!1),[u,f]=R.useState(d.name),p=fs(),g=()=>{h(!1);const m=u.trim();if(!m||m===d.name){f(d.name);return}p.renameFolder.mutate({id:d.id,name:m},{onError:()=>{f(d.name),it.error("Could not rename folder.")}})};return v.jsxs(so,{open:e,onOpenChange:s,children:[v.jsxs("div",{className:"group/folder relative flex items-center rounded-md pr-1",children:[c?v.jsxs("div",{className:"flex flex-1 items-center gap-1.5 px-2 py-1.5",children:[v.jsx(Fs,{size:13,className:"shrink-0 text-faint"}),v.jsx("input",{autoFocus:!0,className:"w-full bg-transparent text-[12px] font-semibold text-ink outline-none",value:u,onChange:m=>f(m.target.value),onBlur:g,onKeyDown:m=>{m.key==="Enter"&&g(),m.key==="Escape"&&(f(d.name),h(!1))},onClick:m=>m.stopPropagation()})]}):v.jsxs(io,{className:"flex flex-1 items-center gap-1.5 rounded-md px-2 py-1.5 text-left text-[12px] font-semibold text-ink transition-colors hover:bg-[color-mix(in_srgb,var(--accent)_8%,transparent)]",children:[v.jsx(yr,{size:13,className:`shrink-0 text-faint transition-transform ${e?"":"-rotate-90"}`}),v.jsx(Fs,{size:13,className:"shrink-0 text-faint"}),v.jsx("span",{className:"truncate",onDoubleClick:m=>{m.stopPropagation(),f(d.name),h(!0)},children:d.name}),v.jsx("span",{className:"ml-auto pl-1 text-[11px] font-normal text-faint",children:t.length})]}),!c&&v.jsxs(Oi,{children:[v.jsx(Bi,{asChild:!0,children:v.jsx("button",{type:"button",onClick:m=>m.stopPropagation(),className:"rounded p-1 text-faint opacity-0 transition-opacity hover:text-ink group-hover/folder:opacity-100 data-[state=open]:opacity-100",title:"Folder actions",children:v.jsx(to,{size:13})})}),v.jsxs(ji,{align:"end",children:[v.jsxs(Re,{onSelect:()=>{f(d.name),h(!0)},children:[v.jsx(mr,{size:13})," Rename"]}),v.jsxs(Re,{destructive:!0,onSelect:i,children:[v.jsx(br,{size:13})," Delete folder"]})]})]})]}),v.jsx(no,{children:v.jsx("div",{className:"ml-3 border-l border-border pl-2",children:t.length===0?v.jsx("p",{className:"px-3 py-1.5 text-[11px] text-faint",children:"Empty folder"}):t.map(m=>v.jsx(Ri,{conv:m,active:m.id===n,folders:r,onSelect:a,onDelete:o,onMove:l},m.id))})})]})}function Ri({conv:d,active:t,folders:e,onSelect:s,onDelete:i,onMove:n}){const[r,a]=R.useState(!1),[o,l]=R.useState(d.title),c=fs(),h=()=>{a(!1);const u=o.trim();if(!u||u===d.title){l(d.title);return}c.update.mutate({id:d.id,title:u},{onError:()=>{l(d.title),it.error("Could not rename conversation.")}})};return v.jsxs("div",{onClick:()=>!r&&s(d.id),className:"group relative flex cursor-pointer flex-col gap-0.5 rounded-md px-3 py-2 transition-colors",style:{background:t?"color-mix(in srgb, var(--accent) 10%, transparent)":"transparent"},children:[r?v.jsx("input",{autoFocus:!0,className:"w-full bg-transparent text-[13px] font-medium text-ink outline-none",value:o,onChange:u=>l(u.target.value),onBlur:h,onKeyDown:u=>{u.key==="Enter"&&h(),u.key==="Escape"&&(l(d.title),a(!1))},onClick:u=>u.stopPropagation()}):v.jsx("span",{className:"truncate text-[13px] font-medium text-ink",style:{color:t?"var(--accent)":void 0},onDoubleClick:u=>{u.stopPropagation(),a(!0)},children:d.title}),v.jsx("span",{className:"text-[11px] text-faint",children:ih(d.updatedAt)}),!r&&v.jsxs("div",{className:"absolute right-1.5 top-1/2 flex -translate-y-1/2 items-center gap-0.5 opacity-0 transition-opacity group-hover:opacity-100",children:[v.jsxs(Oi,{children:[v.jsx(Bi,{asChild:!0,children:v.jsx("button",{type:"button",onClick:u=>u.stopPropagation(),className:"rounded p-1 text-faint transition-colors hover:text-ink data-[state=open]:text-ink",title:"Move to folder",children:v.jsx(go,{size:13})})}),v.jsxs(ji,{align:"end",children:[e.length===0&&v.jsx(Re,{disabled:!0,children:"No folders yet"}),e.map(u=>v.jsxs(Re,{disabled:u.id===d.folderId,onSelect:()=>n(d,u.id),children:[v.jsx(Fs,{size:13})," ",u.name]},u.id)),d.folderId&&v.jsxs(v.Fragment,{children:[e.length>0&&v.jsx(pr,{}),v.jsx(Re,{onSelect:()=>n(d,null),children:"Uncategorized"})]})]})]}),v.jsx("button",{type:"button",onClick:u=>{u.stopPropagation(),l(d.title),a(!0)},className:"rounded p-1 text-faint transition-colors hover:text-ink",title:"Rename conversation",children:v.jsx(mr,{size:13})}),v.jsx("button",{type:"button",onClick:u=>i(u,d),className:"rounded p-1 text-faint transition-colors hover:text-err",title:"Delete conversation",children:v.jsx(br,{size:13})})]})]})}function ah({models:d,loadedKey:t,loadedName:e,pending:s,ejecting:i,onLoad:n,onEject:r,onSettings:a,align:o="start"}){const l=d.filter(h=>!h.incomplete&&!h.parseError),c=i?"Ejecting…":e||(t?"Loaded model":"Load a model");return v.jsxs(Oi,{children:[v.jsxs(Bi,{className:"flex h-8 max-w-[260px] items-center gap-1.5 rounded-md border border-border bg-panel px-2.5 text-[13px] text-ink transition-colors hover:border-[color:var(--accent)] disabled:opacity-60",disabled:s,children:[s||i?v.jsx(ja,{size:14,className:"animate-spin text-muted"}):v.jsx(Ha,{size:14,className:t?"text-accent":"text-muted"}),v.jsx("span",{className:"truncate",children:c}),v.jsx(yr,{size:14,className:"shrink-0 text-muted"})]}),v.jsxs(ji,{align:o,className:"max-h-[60vh] w-[280px] overflow-y-auto",children:[v.jsx("div",{className:"px-2 py-1.5 text-[11px] font-medium uppercase tracking-wide text-faint",children:l.length?"Load a model":"No models found"}),l.map(h=>{const u=h.key===t;return v.jsxs("div",{role:"menuitem",tabIndex:-1,className:"flex cursor-pointer select-none items-center gap-2 rounded-sm px-2 py-1.5 text-[13px] outline-none hover:bg-panel-2 focus:bg-panel-2",onClick:f=>{if(f.altKey&&a){a(h.key);return}u||n(h.key)},children:[v.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center",children:u&&v.jsx(mo,{size:14,className:"text-accent"})}),v.jsx("span",{className:"min-w-0 flex-1 truncate",children:h.name}),a&&v.jsx("button",{type:"button",onClick:f=>{f.stopPropagation(),a(h.key)},className:"grid h-6 w-6 shrink-0 place-items-center rounded text-faint transition-colors hover:bg-panel hover:text-ink",title:"Configure before loading","aria-label":`Configure ${h.name} before loading`,children:v.jsx(gr,{size:13})}),v.jsx("span",{className:"shrink-0 text-[11px] uppercase text-faint",children:h.quant})]},h.key)}),t&&v.jsxs(v.Fragment,{children:[v.jsx(pr,{}),v.jsxs(Re,{onSelect:r,style:{color:"var(--err)"},children:[v.jsx(eo,{size:14})," Eject model"]})]})]})]})}const oh=new Set(["filesystem"]),lh=[{key:"temperature",label:"Temperature",min:0,max:2,step:.01,def:.8},{key:"top_p",label:"Top P",min:0,max:1,step:.01,def:.95},{key:"top_k",label:"Top K",min:0,max:200,step:1,def:40},{key:"min_p",label:"Min P",min:0,max:1,step:.01,def:.05}];function ch({conv:d}){const t=fs(),[e,s]=R.useState(!1),[i,n]=R.useState(""),[r,a]=R.useState({}),[o,l]=R.useState([]),c=os({queryKey:ur.list(),queryFn:dr,enabled:e,staleTime:0}),h=(c.data??[]).filter(y=>!oh.has(y.id));R.useEffect(()=>{e&&d&&(n(d.systemPrompt??""),a(d.sampling??{}),l(d.skillIds??[]))},[e,d]);const u=y=>l(A=>A.includes(y)?A.filter(w=>w!==y):[...A,y]),f=Object.keys(r).length>0,p=d?.expertMode??!1,g=(y,A)=>a(w=>({...w,[y]:A})),m=()=>a({}),b=()=>{if(!d)return;const y=p?{id:d.id,sampling:r,skillIds:o}:{id:d.id,systemPrompt:i,sampling:r,skillIds:o};t.update.mutate(y,{onSuccess:()=>{it.success("Thread settings saved"),s(!1)},onError:A=>it.error(A instanceof ge?A.message:"Could not save settings.")})};return v.jsxs(ho,{open:e,onOpenChange:s,children:[v.jsx(uo,{asChild:!0,children:v.jsx(yt,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Thread settings — system prompt & sampling overrides",disabled:!d,children:v.jsx(Ua,{size:15})})}),v.jsxs(fo,{className:"max-w-md",children:[v.jsx("div",{className:"mb-4",children:v.jsx("span",{className:"text-[15px] font-semibold text-ink",children:"Thread settings"})}),v.jsxs("div",{className:"flex flex-col gap-5",children:[v.jsxs("div",{children:[v.jsx("label",{className:"mb-1.5 block text-[11px] font-medium uppercase tracking-wide text-faint",children:"System prompt"}),p?v.jsx("p",{className:"rounded-lg border border-border bg-panel-2 px-3 py-2 text-[13px] text-muted",children:"System prompt is managed by TurboLLM for the Expert assistant."}):v.jsx("textarea",{rows:4,value:i,onChange:y=>n(y.target.value),placeholder:"Leave blank to use the model's built-in default",className:"w-full resize-none rounded-lg border border-border bg-bg px-3 py-2 text-[14px] leading-[1.6] text-ink outline-none placeholder:text-faint focus:border-[color:var(--accent)]"})]}),v.jsxs("div",{children:[v.jsxs("div",{className:"mb-2.5 flex items-center justify-between",children:[v.jsx("span",{className:"text-[11px] font-medium uppercase tracking-wide text-faint",children:"Sampling overrides"}),f&&v.jsx("button",{type:"button",onClick:m,className:"text-[12px] text-muted underline-offset-2 hover:text-ink hover:underline",children:"Reset to model defaults"})]}),v.jsx("div",{className:"flex flex-col gap-3.5",children:lh.map(y=>{const A=y.key in r,w=A?r[y.key]??y.def:y.def;return v.jsxs("div",{className:"flex items-center gap-3",children:[v.jsx("span",{className:"w-24 shrink-0 text-[13px]",style:{color:A?"var(--ink)":"var(--muted)"},children:y.label}),v.jsx("input",{type:"range",min:y.min,max:y.max,step:y.step,value:w,onChange:x=>g(y.key,parseFloat(x.target.value)),className:"flex-1",style:{accentColor:"var(--accent)"}}),v.jsx("span",{className:"w-10 shrink-0 text-right font-mono text-[13px] tabular-nums text-ink",children:y.step<1?w.toFixed(2):String(Math.round(w))})]},y.key)})}),!f&&v.jsx("p",{className:"mt-2.5 text-[12px] text-faint",children:"Using model defaults · move any slider to override for this thread"})]}),v.jsxs("div",{children:[v.jsx("span",{className:"mb-2.5 block text-[11px] font-medium uppercase tracking-wide text-faint",children:"Skills"}),c.isLoading?v.jsx("p",{className:"text-[12px] text-faint",children:"Loading…"}):h.length===0?v.jsx("p",{className:"text-[12px] text-faint",children:"No skills yet — create one under Skills."}):v.jsx("div",{className:"flex flex-col gap-2",children:h.map(y=>v.jsxs("label",{className:"flex cursor-pointer items-start gap-2 text-[13px]",children:[v.jsx("input",{type:"checkbox",className:"mt-0.5",checked:o.includes(y.id),onChange:()=>u(y.id)}),v.jsxs("span",{className:"flex flex-col",children:[v.jsx("span",{className:"text-ink",children:y.name}),y.description&&v.jsx("span",{className:"text-[12px] text-muted",children:y.description})]})]},y.id))})]})]}),v.jsxs("div",{className:"mt-5 flex justify-end gap-2",children:[v.jsx(po,{asChild:!0,children:v.jsx(yt,{variant:"ghost",size:"sm",children:"Cancel"})}),v.jsx(yt,{size:"sm",onClick:b,disabled:t.update.isPending,children:t.update.isPending?"Saving…":"Save"})]})]})]})}const qr="tllm-sidebar-w",nn=200;function Qr(){return Math.max(nn,Math.min(480,window.innerWidth-480))}function Jr(){try{const d=parseInt(localStorage.getItem(qr)??"",10);return Number.isFinite(d)?d:224}catch{return 224}}function jh(){const{data:d}=za(),t=d?.model,e=d?.engine.state,{convId:s}=va(),[i]=Aa(),n=i.get("readonly")==="1",[r,a]=R.useState(s??null),[o,l]=R.useState(null),[c,h]=R.useState(""),[u,f]=R.useState(null),[p,g]=R.useState(null),[m,b]=R.useState(!1),[y,A]=R.useState(!0),w=R.useRef(null),[x,S]=R.useState(()=>Math.min(Math.max(Jr(),nn),Qr())),[E,_]=R.useState([]),[k,I]=R.useState(!1),[P,B]=R.useState(null),W=R.useRef(null),Y=R.useRef(null),[Z,L]=R.useState(null),[F,rt]=R.useState(null),ht=C=>{if(C){const H=localStorage.getItem(`tllm.thinkingEnabled.${C}`);if(H!==null)return H!=="false"}return localStorage.getItem("tllm.thinkingEnabled.default")!=="false"},[vt,Ot]=R.useState(()=>ht(null)),M=C=>{r&&localStorage.setItem(`tllm.thinkingEnabled.${r}`,String(C)),Ot(C)},[j,dt]=R.useState(()=>di()),Bt=$a(),_t=Ga(),tt=bo(Bt.data??[],_t.data??{}),Ue=tt.find(C=>C.id===j),qt=R.useRef(null),le=R.useRef([]),ce=R.useRef(null),Qt=R.useRef(null),ps=R.useRef(null),gs=R.useRef(null),Ee=R.useRef(!1),ee=hr(),he=fs(),rn=Va(),ze=Wa(),ei=Kc(r).data,$e=ei?.messages??[],[an,on]=R.useState([]),ms=ei?.skillIds??an,Zr=os({queryKey:ur.list(),queryFn:dr,staleTime:3e4}),ta=new Set(["filesystem"]),ln=(Zr.data??[]).filter(C=>!ta.has(C.id)),si=/^\/([a-z0-9-]*)$/i.exec(c),bs=si?.[1]?.toLowerCase()??"",de=si?ln.filter(C=>!bs||C.id.includes(bs)||C.name.toLowerCase().includes(bs)):[],ii=!!si&&de.length>0&&!o,[ni,ri]=R.useState(0);R.useEffect(()=>{ri(0)},[bs,ii]);const cn=C=>{if(h(`/${C.id} `),setTimeout(ys,0),r){const O=Array.from(new Set([...ms,C.id]));he.update.mutate({id:r,skillIds:O})}else on(O=>Array.from(new Set([...O,C.id])));it.success(`Skill enabled: ${C.name}`),setTimeout(()=>Qt.current?.focus(),0)},ai=Cn(C=>C.pendingConversationId),ea=Cn(C=>C.setPendingConversationId);R.useEffect(()=>{ai&&(oi(ai),ea(null))},[ai]);const sa=(rn.data?.models??[]).filter(C=>C.compatibleWithActiveEngine),ia=ze.load.isPending||ze.eject.isPending||e==="starting"||e==="stopping",na=C=>{ze.load.mutate({key:C},{onError:O=>it.error(O instanceof ge?O.message:"Could not load model.")})},ra=()=>{o&&(qt.current?.abort(),l(null)),ze.eject.mutate(void 0,{onError:C=>it.error(C instanceof ge?C.message:"Could not eject model.")})},ys=()=>{const C=Qt.current;C&&(C.style.height="auto",C.style.height=`${Math.min(C.scrollHeight,160)}px`)},Ge=R.useCallback((C=!1)=>{const O=ce.current;O&&(C||!Ee.current)&&(O.scrollTo({top:O.scrollHeight,behavior:"smooth"}),b(!1))},[]);R.useEffect(()=>{const C=ce.current;if(!C)return;const O=()=>{const H=C.scrollHeight-C.scrollTop-C.clientHeight<80;Ee.current=!H,b(!H&&!!o)};return C.addEventListener("scroll",O),()=>C.removeEventListener("scroll",O)},[o]),R.useEffect(()=>{o&&Ge()},[o,Ge]),R.useEffect(()=>{const C=O=>{if((O.ctrlKey||O.metaKey)&&(O.key==="n"||O.key==="N")){O.preventDefault(),dn();return}O.key==="Escape"&&o&&un()};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)}),R.useEffect(()=>{Ot(ht(r))},[r]),R.useEffect(()=>{if(!k)return;const C=O=>{W.current&&!W.current.contains(O.target)&&I(!1)};return document.addEventListener("mousedown",C),()=>document.removeEventListener("mousedown",C)},[k]);const hn=async(C,O,H)=>{I(!1);try{await navigator.clipboard.writeText(C),it.success(O)}catch{B({text:C,title:H})}},aa=async()=>{if(r)try{const{url:C}=await Ya(r);await hn(C,"Link copied","Share link")}catch{it.error("Could not get share URL.")}},oa=async()=>{if(r)try{const C=await Ka(r);await hn(C,"Debug info copied","Debug snapshot")}catch{it.error("Could not get debug info.")}},la=()=>{r&&(I(!1),qa(r))},ca=async C=>{const O=C.target.files?.[0];if(C.target.value="",!O)return;L(null),rt(null);let H;try{const $=await O.text();H=JSON.parse($)}catch{L("Invalid file — could not parse JSON.");return}if(!Array.isArray(H)){const $=H?.model;$&&((rn.data?.models??[]).some(se=>se.key===$)||rt($))}try{const{id:$}=await Qa(H);ee.invalidateQueries({queryKey:["conversations"]}),oi($)}catch($){const st=$ instanceof ge?$.message:"Import failed. Check the file is a valid .turbollm-chat.json or OpenAI-format JSON.";L(st)}},dn=()=>{a(null),h(""),l(null),dt(di()),Qt.current?.focus()},oi=C=>{o&&(qt.current?.abort(),l(null)),a(C),f(null),dt(yo(C)),Ee.current=!1,setTimeout(()=>Ge(!0),50)},ha=C=>{C===r&&(o&&(qt.current?.abort(),l(null)),a(null),f(null),h(""),dt(di()))},un=async()=>{qt.current?.abort(),r&&await he.stop.mutateAsync(r).catch(()=>{})},da=async C=>{const O=Array.from(C.target.files??[]),H=await Promise.all(O.map(async $=>{if($.type==="application/pdf"||/\.pdf$/i.test($.name)){const se=await Wc($);return{file:$,dataUrl:se}}const _e=await new Promise(se=>{const ke=new FileReader;ke.onload=()=>se(ke.result),$.type.startsWith("image/")?ke.readAsDataURL($):ke.readAsText($)});return{file:$,dataUrl:_e}}));_($=>[...$,...H]),C.target.value=""},fn=()=>{const C=Date.now();return le.current.push(C),le.current=le.current.filter(O=>O>C-2e3),Math.round(le.current.length/2*10)/10},li=async(C,O)=>{try{for await(const H of O)if(H.event==="meta")le.current=[],l({assistantId:H.data.assistantMessageId,content:"",reasoning:"",progress:null,liveGenTps:0,genTokens:0,timeline:[]}),ee.invalidateQueries({queryKey:["conversation",C]});else if(H.event==="progress")l($=>$&&{...$,progress:{phase:H.data.phase,pct:H.data.pct,tps:H.data.tps}});else if(H.event==="reasoning"){const $=fn();l(st=>st&&{...st,reasoning:st.reasoning+H.data.delta,progress:null,liveGenTps:$,genTokens:st.genTokens+1})}else if(H.event==="delta"){const $=fn();l(st=>st&&{...st,content:st.content+H.data.delta,timeline:qc(st.timeline,H.data.delta),progress:null,liveGenTps:$,genTokens:st.genTokens+1})}else if(H.event==="tool_call"){const $=H.data;l(st=>{if(!st)return st;const _e={id:$.id,name:$.name,args:$.args,status:$.status,result:$.result};return{...st,timeline:Qc(st.timeline,_e)}})}else H.event==="done"?(l(null),ee.invalidateQueries({queryKey:["conversation",C]}),ee.invalidateQueries({queryKey:["conversations"]}),setTimeout(()=>Ge(!0),80)):H.event==="error"&&(l(null),ee.invalidateQueries({queryKey:["conversation",C]}),it.error(H.data.message));l(null),ee.invalidateQueries({queryKey:["conversation",C]})}catch(H){l(null),H?.name!=="AbortError"&&it.error(H instanceof ge?H.message:"Request failed."),ee.invalidateQueries({queryKey:["conversation",C]})}},pn=async C=>{const O=c.trim();if(!O&&E.length===0||o)return;if(e!=="running"||!t){it.error("Load a model first.");return}const H=/^\/([a-z0-9-]+)(?:\s+([\s\S]*))?$/.exec(O),$=H?ln.find(ut=>ut.id===H[1]):void 0,st=$?(H?.[2]??"").trim():O,_e=E.filter(ut=>ut.file.type.startsWith("image/")),se=E.filter(ut=>!ut.file.type.startsWith("image/")),ke=_e.map(ut=>ut.dataUrl),ba=se.map(ut=>`[Attached: ${ut.file.name}]
|
|
58
|
+
${ut.dataUrl}`).join(`
|
|
59
|
+
|
|
60
|
+
`);h(""),_([]),setTimeout(ys,0),Ee.current=!1;try{let ut=r;if(ut)$&&!ms.includes($.id)&&await he.update.mutateAsync({id:ut,skillIds:Array.from(new Set([...ms,$.id]))});else{const Te=tt.find(Me=>Me.id===j);let vs=vo(j,Te?.systemPrompt??"",Ao());if(j==="expert")try{const Me=await Ra(),vn=`## User's hardware
|
|
61
|
+
GPU: ${Me.gpus.length>0?Me.gpus.map(An=>`${An.name} (${Math.round(An.vramMb/1024)} GB VRAM)`).join(", "):"No GPU detected (CPU inference)"}
|
|
62
|
+
RAM: ${Math.round(Me.ramMB/1024)} GB
|
|
63
|
+
OS: ${Me.os}`;vs=vs?`${vs}
|
|
64
|
+
|
|
65
|
+
${vn}`:vn}catch{}const yn=Array.from(new Set([...an,...Te?.skillIds??[],...$?[$.id]:[]]));ut=(await he.create.mutateAsync({modelKey:t.key,systemPrompt:vs||void 0,toolPolicy:j==="research"?"force_web_search":void 0,skillIds:yn.length?yn:void 0,allowedTools:Te?.tools?.length?Te.tools:void 0})).id,xo(ut,j),a(ut),on([])}$&&it.success(`Using skill: ${$.name}`);const bn=new AbortController;qt.current=bn;const ya=se.map(Te=>Te.file.name);await li(ut,Oa(ut,st,bn.signal,ke,ba,ya,!vt))}catch(ut){l(null),ut?.name!=="AbortError"&&it.error(ut instanceof ge?ut.message:"Request failed."),r&&ee.invalidateQueries({queryKey:["conversation",r]})}},ua=(C,O)=>{r&&(f(null),he.editMsg.mutate({convId:r,msgId:C,content:O},{onSuccess:()=>{if(Ee.current=!1,e==="running"&&t){const H=new AbortController;qt.current=H,li(r,Sn(r,H.signal,!vt))}},onError:()=>it.error("Could not edit message.")}))},fa=async()=>{if(!r||o)return;if(e!=="running"||!t){it.error("Load a model first.");return}await he.regenerate.mutateAsync(r).catch(()=>{});const C=new AbortController;qt.current=C,li(r,Sn(r,C.signal,!vt))},pa=C=>{r&&he.deleteMsg.mutate({convId:r,msgId:C.id},{onError:()=>it.error("Could not delete message.")})},gn=$e.findLast(C=>C.role==="assistant")?.stats,ga=gn?.ctxUsed??0,ma=t?.ctx||gn?.ctxMax||0,Ve=e==="running"&&!!t,mn=o?.timeline.find(C=>C.kind==="tool"&&C.call.status==="awaiting_approval"),ci=mn?.kind==="tool"?mn.call:void 0;return v.jsxs("div",{className:"flex h-full overflow-hidden",children:[v.jsx("div",{ref:w,className:y?"tllm-chat-sidebar shrink-0":"tllm-chat-sidebar w-10 shrink-0",style:y?{width:x}:void 0,children:v.jsx(nh,{activeId:r,onSelect:oi,onNew:dn,onImport:n?void 0:()=>Y.current?.click(),collapsed:!y,onToggle:()=>A(C=>!C),generating:!!o,onDeleted:ha})}),y&&v.jsx(hh,{sidebarRef:w,onCommit:S}),v.jsxs("div",{className:"relative flex min-w-0 flex-1 flex-col",children:[n&&v.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border bg-panel-2 px-4 py-1.5 text-[12px] text-muted",children:[v.jsx("span",{className:"font-medium text-ink",children:"Shared view"}),v.jsx("span",{className:"text-faint",children:"—"}),v.jsx("span",{children:"read only"})]}),v.jsxs("div",{className:"flex h-12 shrink-0 items-center gap-2 border-b border-border px-4",children:[v.jsx(ah,{models:sa,loadedKey:t?.key??null,loadedName:t?.name??null,pending:ia,ejecting:ze.eject.isPending,onLoad:na,onEject:ra,onSettings:C=>g(C)}),t&&v.jsx(yt,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>g(t.key),title:"Model settings — change on the fly",children:v.jsx(gr,{size:15})}),v.jsx(ch,{conv:ei}),v.jsx(yt,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>M(!vt),title:vt?"Thinking on — model reasons before answering. Click to disable.":"Thinking off — model answers directly. Click to enable reasoning.",style:{color:vt?"var(--accent)":"var(--faint)"},children:v.jsx(Eo,{size:15})}),r&&Ue&&v.jsxs("span",{title:Ue.description,className:"inline-flex items-center gap-1 rounded-full border border-border px-2 py-0.5 text-[11px] text-muted select-none",children:[v.jsx(Ro,{size:11}),Ue.name]}),e==="starting"&&v.jsx("span",{className:"text-[12px] text-muted",children:"Loading model…"}),e==="stopping"&&v.jsx("span",{className:"text-[12px] text-muted",children:"Ejecting…"}),Ve&&v.jsx(th,{ctxUsed:ga,ctxMax:ma}),r&&v.jsxs("div",{ref:W,className:"relative ml-auto",children:[v.jsx(yt,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>I(C=>!C),title:"Share or export this chat",children:v.jsx(Do,{size:15})}),k&&v.jsxs("div",{className:"absolute right-0 top-9 z-50 min-w-[180px] rounded-md border border-border bg-panel shadow-[var(--shadow-2)] py-1",children:[v.jsxs("button",{type:"button",onClick:()=>{aa()},className:"flex w-full items-center gap-2 px-3 py-2 text-[13px] text-ink hover:bg-panel-2",children:[v.jsx(Nn,{size:13,className:"text-muted"}),"Copy link (LAN)"]}),v.jsxs("button",{type:"button",onClick:()=>{oa()},className:"flex w-full items-center gap-2 px-3 py-2 text-[13px] text-ink hover:bg-panel-2",children:[v.jsx(Nn,{size:13,className:"text-muted"}),"Copy debug info"]}),v.jsx("div",{className:"my-1 border-t border-border"}),v.jsxs("button",{type:"button",onClick:la,className:"flex w-full items-center gap-2 px-3 py-2 text-[13px] text-ink hover:bg-panel-2",children:[v.jsx(Ai,{size:13,className:"text-muted"}),"Export chat"]})]})]})]}),v.jsx("div",{ref:ce,className:"min-h-0 flex-1 overflow-y-auto overflow-x-hidden",children:v.jsxs("div",{className:"flex w-full flex-col gap-6 px-8 py-6",children:[v.jsx("input",{ref:Y,type:"file",accept:".json,.turbollm-chat.json",hidden:!0,onChange:C=>{ca(C)}}),F&&v.jsxs("div",{className:"mb-2 flex items-start gap-2 rounded-md border border-[color:var(--warn,#ca8a04)] bg-[color-mix(in_srgb,var(--warn,#ca8a04)_8%,transparent)] px-3 py-2 text-[13px]",children:[v.jsxs("span",{className:"flex-1",children:[v.jsx("span",{className:"font-medium",children:"Model not found:"})," ",v.jsx("span",{className:"font-mono",children:F})," is not available on this machine. The chat was imported — select a different model to continue."]}),v.jsx("button",{type:"button",onClick:()=>rt(null),className:"shrink-0 text-faint hover:text-ink",children:v.jsx(As,{size:13})})]}),Z&&v.jsxs("div",{className:"mb-2 flex items-start gap-2 rounded-md border border-[color:var(--err)] bg-[color-mix(in_srgb,var(--err)_8%,transparent)] px-3 py-2 text-[13px]",children:[v.jsx("span",{className:"flex-1 text-[color:var(--err)]",children:Z}),v.jsx("button",{type:"button",onClick:()=>L(null),className:"shrink-0 text-faint hover:text-ink",children:v.jsx(As,{size:13})})]}),$e.length===0&&!o&&v.jsx("div",{className:"flex flex-col items-center gap-4 py-16",children:t?v.jsxs(v.Fragment,{children:[v.jsx("p",{className:"text-[15px] font-medium text-ink",children:t.name}),v.jsx(dh,{selected:j,onChange:dt,agents:tt}),v.jsx("div",{className:"flex flex-wrap justify-center gap-2",children:["Explain something to me","Help me write","Review this code"].map(C=>v.jsx("button",{type:"button",onClick:()=>{h(C),setTimeout(()=>Qt.current?.focus(),0)},className:"rounded-full border border-border px-4 py-1.5 text-[13px] text-muted hover:border-accent hover:text-ink transition-colors",children:C},C))})]}):v.jsx("p",{className:"text-[14px] text-muted",children:"Select a model above to begin"})}),$e.map((C,O)=>v.jsx(Ja,{message:C,isLast:O===$e.length-1&&!o,onEdit:n?void 0:H=>f(H.id),onDelete:n?void 0:pa,onRegenerate:n?void 0:fa,editingId:u,onEditSave:H=>ua(C.id,H),onEditCancel:()=>f(null)},C.id)),o&&v.jsx(Za,{timeline:o.timeline,reasoning:o.reasoning,progress:o.progress,liveGenTps:o.liveGenTps,genTokens:o.genTokens}),v.jsx("div",{ref:ps})]})}),m&&v.jsxs("button",{type:"button",onClick:()=>{Ee.current=!1,Ge(!0)},className:"absolute bottom-28 left-1/2 -translate-x-1/2 flex items-center gap-1.5 rounded-full border border-border bg-panel px-3 py-1.5 text-[12px] text-muted shadow-[var(--shadow-1)] hover:text-ink",children:[v.jsx(So,{size:13})," Jump to latest"]}),P&&v.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-black/40",onClick:()=>B(null),children:v.jsxs("div",{className:"mx-4 w-full max-w-lg rounded-lg border border-border bg-panel p-4 shadow-[var(--shadow-2)]",onClick:C=>C.stopPropagation(),children:[v.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[v.jsx("span",{className:"text-[13px] font-medium text-ink",children:P.title}),v.jsx("button",{type:"button",onClick:()=>B(null),className:"text-faint hover:text-ink",children:v.jsx(As,{size:14})})]}),v.jsx("textarea",{readOnly:!0,autoFocus:!0,className:"h-48 w-full resize-none rounded border border-border bg-panel-2 p-2 text-[12px] font-mono text-ink outline-none",value:P.text,onFocus:C=>C.target.select()}),v.jsx("p",{className:"mt-1 text-[11px] text-faint",children:"Select all and copy (Ctrl+C / Cmd+C)"})]})}),!n&&r&&ci&&v.jsx(Zc,{pending:ci,convId:r,onResolved:()=>{}},ci.id),n?null:v.jsx("div",{className:"px-8 pb-5",children:v.jsxs("div",{className:"relative w-full",children:[ii&&v.jsx("div",{className:"absolute bottom-full left-0 mb-2 w-full max-w-sm overflow-hidden rounded-lg border border-border bg-panel shadow-[var(--shadow-2)]",children:de.map((C,O)=>v.jsxs("button",{type:"button",onClick:()=>cn(C),className:Xa("flex w-full flex-col items-start gap-0.5 px-3 py-2 text-left text-[13px]",O===ni?"bg-panel-2":"hover:bg-panel-2"),children:[v.jsxs("span",{className:"text-ink",children:["/",C.id,ms.includes(C.id)?" · already on":""]}),C.description&&v.jsx("span",{className:"text-[12px] text-muted",children:C.description})]},C.id))}),v.jsxs("div",{className:"rounded-[var(--radius-lg)] border border-border bg-panel shadow-[var(--shadow-2)] focus-within:border-[color:var(--accent)]",children:[E.length>0&&v.jsx("div",{className:"flex flex-wrap gap-1.5 px-2 pt-2",children:E.map((C,O)=>v.jsxs("div",{className:"relative flex items-center gap-1 rounded border border-border bg-panel-2 px-2 py-1 text-[12px]",children:[C.file.type.startsWith("image/")?v.jsx("img",{src:C.dataUrl,className:"h-8 w-8 rounded object-cover",alt:""}):v.jsx("span",{className:"text-muted",children:C.file.name}),v.jsx("button",{type:"button",onClick:()=>_(H=>H.filter(($,st)=>st!==O)),className:"text-faint hover:text-err",children:v.jsx(As,{size:11})})]},O))}),v.jsxs("div",{className:"flex items-end gap-2 p-2",children:[v.jsx("button",{type:"button",onClick:()=>gs.current?.click(),disabled:!Ve||!!o,className:"grid h-9 w-9 shrink-0 place-items-center rounded-md hover:bg-panel-2 disabled:opacity-40",title:"Attach image or document",children:v.jsx(To,{size:15,className:"text-muted"})}),v.jsx("input",{ref:gs,type:"file",multiple:!0,accept:"image/*,.pdf,.txt,.md,.csv,.json,.yaml,.yml,.log,.ts,.tsx,.js,.jsx,.py,.go,.rs,.java,.c,.cpp,.h,.rb,.php,.sh,.sql,.xml,.toml,.ini",hidden:!0,onChange:da}),v.jsx("textarea",{ref:Qt,rows:1,className:"max-h-40 min-h-9 flex-1 resize-none bg-transparent px-2 py-1.5 text-[15px] text-ink outline-none placeholder:overflow-hidden placeholder:whitespace-nowrap placeholder:text-faint",placeholder:Ve?`Message ${t.name}…`:"Load a model above to start chatting",value:c,disabled:!Ve||!!o||!!u,onChange:C=>{h(C.target.value),ys()},onKeyDown:C=>{if(ii){if(C.key==="ArrowDown"){C.preventDefault(),ri(O=>Math.min(O+1,de.length-1));return}if(C.key==="ArrowUp"){C.preventDefault(),ri(O=>Math.max(O-1,0));return}if(C.key==="Tab"){C.preventDefault();const O=de[Math.min(ni,de.length-1)];h(`/${O.id}`),setTimeout(ys,0);return}if(C.key==="Enter"&&!C.shiftKey){C.preventDefault(),cn(de[Math.min(ni,de.length-1)]);return}if(C.key==="Escape"){C.preventDefault(),h("");return}}if(C.key==="Enter"&&!C.shiftKey&&(C.preventDefault(),pn()),C.key==="ArrowUp"&&!c&&!o){const O=$e.findLast(H=>H.role==="user");O&&f(O.id)}}}),o?v.jsx(yt,{size:"icon",variant:"outline",onClick:()=>{un()},title:"Stop generation (Esc)",children:v.jsx(Fo,{size:15})}):v.jsx(yt,{size:"icon",onClick:()=>{pn()},disabled:!Ve||!c.trim()&&E.length===0||!!u,"aria-label":"Send",children:v.jsx(Po,{size:15})})]})]}),v.jsx("p",{className:"mt-1.5 px-1 text-[11px] text-faint",children:t?`${t.name} · Enter to send · Shift+Enter for newline`:"Load a model above to start chatting"})]})})]}),v.jsx(lo,{modelKey:p,onClose:()=>g(null)})]})}function hh({sidebarRef:d,onCommit:t}){const e=s=>{if(s.button!==0)return;s.preventDefault();const i=s.clientX,n=d.current?.getBoundingClientRect().width??Jr();document.documentElement.classList.add("tllm-resizing");const r=o=>{const l=Math.min(Math.max(n+(o.clientX-i),nn),Qr());d.current&&(d.current.style.width=`${Math.round(l)}px`)},a=()=>{document.documentElement.classList.remove("tllm-resizing"),window.removeEventListener("pointermove",r),window.removeEventListener("pointerup",a);const o=d.current?.getBoundingClientRect().width;if(o){const l=Math.round(o);t(l);try{localStorage.setItem(qr,String(l))}catch{}}};window.addEventListener("pointermove",r),window.addEventListener("pointerup",a)};return v.jsx("div",{className:"tllm-split-resizer",onPointerDown:e,role:"separator","aria-orientation":"vertical","aria-label":"Resize conversation sidebar"})}function dh({selected:d,onChange:t,agents:e}){return v.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[v.jsx("p",{className:"text-[11px] uppercase tracking-wide text-faint",children:"Agent"}),v.jsx("select",{value:d,onChange:s=>t(s.target.value),className:"rounded-md border border-border bg-bg px-2 py-1.5 text-[13px] text-ink outline-none",children:e.map(s=>v.jsxs("option",{value:s.id,children:[s.name," — ",s.description]},s.id))})]})}export{jh as ChatScreen};
|