@fudanda/admin-antd 2.20261107.1-beta.1 → 2.20261109.1-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/dist/chunks/ApiTokensPage-w3JGRNQC.js +2 -0
  2. package/dist/chunks/ApiTokensPage-w3JGRNQC.js.map +1 -0
  3. package/dist/chunks/{App-BF96TQ_D.js → App-nh6_qOo8.js} +5 -5
  4. package/dist/chunks/{App-BF96TQ_D.js.map → App-nh6_qOo8.js.map} +1 -1
  5. package/dist/chunks/{AppModal-CLkMJ-96.js → AppModal-CEouaU03.js} +2 -2
  6. package/dist/chunks/{AppModal-CLkMJ-96.js.map → AppModal-CEouaU03.js.map} +1 -1
  7. package/dist/chunks/{ArcBaseAdmin--xQxd4tg.js → ArcBaseAdmin-CX7fQz4x.js} +2 -2
  8. package/dist/chunks/{ArcBaseAdmin--xQxd4tg.js.map → ArcBaseAdmin-CX7fQz4x.js.map} +1 -1
  9. package/dist/chunks/{DepartmentsPage-D6YVegPU.js → DepartmentsPage-BdD9VfDI.js} +2 -2
  10. package/dist/chunks/{DepartmentsPage-D6YVegPU.js.map → DepartmentsPage-BdD9VfDI.js.map} +1 -1
  11. package/dist/chunks/{DictsPage-uV3Uukwc.js → DictsPage-fxBdV1-3.js} +2 -2
  12. package/dist/chunks/{DictsPage-uV3Uukwc.js.map → DictsPage-fxBdV1-3.js.map} +1 -1
  13. package/dist/chunks/{EntityContextRuntime-DbjyzCtY.js → EntityContextRuntime-CMhoj6qe.js} +2 -2
  14. package/dist/chunks/{EntityContextRuntime-DbjyzCtY.js.map → EntityContextRuntime-CMhoj6qe.js.map} +1 -1
  15. package/dist/chunks/EntityContextRuntime-Dc89ZSnM.js +1 -0
  16. package/dist/chunks/{ExportButton-e2ybxuHb.js → ExportButton-DGxB2tcu.js} +2 -2
  17. package/dist/chunks/{ExportButton-e2ybxuHb.js.map → ExportButton-DGxB2tcu.js.map} +1 -1
  18. package/dist/chunks/{FileViewerPreviewPanel-BhI3pTi8.js → FileViewerPreviewPanel-BMZ7FdKV.js} +3 -3
  19. package/dist/chunks/{FileViewerPreviewPanel-BhI3pTi8.js.map → FileViewerPreviewPanel-BMZ7FdKV.js.map} +1 -1
  20. package/dist/chunks/{FilesPage-BI35mStl.js → FilesPage-DrgWELKy.js} +3 -3
  21. package/dist/chunks/{FilesPage-BI35mStl.js.map → FilesPage-DrgWELKy.js.map} +1 -1
  22. package/dist/chunks/IdentitySecurityPage-BjTKvr-O.js +9 -0
  23. package/dist/chunks/IdentitySecurityPage-BjTKvr-O.js.map +1 -0
  24. package/dist/chunks/{LogStatsScaffold-m0vVUXPh.js → LogStatsScaffold-DaB0JeAN.js} +2 -2
  25. package/dist/chunks/{LogStatsScaffold-m0vVUXPh.js.map → LogStatsScaffold-DaB0JeAN.js.map} +1 -1
  26. package/dist/chunks/{LoginLogsPage-BzBUR4Oo.js → LoginLogsPage-VmYC7i6q.js} +2 -2
  27. package/dist/chunks/{LoginLogsPage-BzBUR4Oo.js.map → LoginLogsPage-VmYC7i6q.js.map} +1 -1
  28. package/dist/chunks/{LoginLogsTable-BweUEjQX.js → LoginLogsTable-CULcc_e8.js} +2 -2
  29. package/dist/chunks/{LoginLogsTable-BweUEjQX.js.map → LoginLogsTable-CULcc_e8.js.map} +1 -1
  30. package/dist/chunks/{MarkdownPreviewPanel-C1OKSLmh.js → MarkdownPreviewPanel-CBcPc7Wv.js} +2 -2
  31. package/dist/chunks/{MarkdownPreviewPanel-C1OKSLmh.js.map → MarkdownPreviewPanel-CBcPc7Wv.js.map} +1 -1
  32. package/dist/chunks/{MasterDetailLayout-KVizcSNO.js → MasterDetailLayout-ByIBpmkZ.js} +2 -2
  33. package/dist/chunks/{MasterDetailLayout-KVizcSNO.js.map → MasterDetailLayout-ByIBpmkZ.js.map} +1 -1
  34. package/dist/chunks/{McpSettingsPage-Dhf0CbDN.js → McpSettingsPage-C5V_rj2V.js} +2 -2
  35. package/dist/chunks/{McpSettingsPage-Dhf0CbDN.js.map → McpSettingsPage-C5V_rj2V.js.map} +1 -1
  36. package/dist/chunks/{MemberAssignmentSheet-TYpnyA0z.js → MemberAssignmentSheet-DL0fg1Yf.js} +2 -2
  37. package/dist/chunks/{MemberAssignmentSheet-TYpnyA0z.js.map → MemberAssignmentSheet-DL0fg1Yf.js.map} +1 -1
  38. package/dist/chunks/{MenuCommandPalette-BcvpUfK7.js → MenuCommandPalette-C2PvK3Gh.js} +2 -2
  39. package/dist/chunks/{MenuCommandPalette-BcvpUfK7.js.map → MenuCommandPalette-C2PvK3Gh.js.map} +1 -1
  40. package/dist/chunks/{MenusPage-Dd7OLQYT.js → MenusPage-Bytd1HlW.js} +2 -2
  41. package/dist/chunks/{MenusPage-Dd7OLQYT.js.map → MenusPage-Bytd1HlW.js.map} +1 -1
  42. package/dist/chunks/{MonacoPreviewPanel-BW1j3ZTF.js → MonacoPreviewPanel-BZrNIcFZ.js} +2 -2
  43. package/dist/chunks/{MonacoPreviewPanel-BW1j3ZTF.js.map → MonacoPreviewPanel-BZrNIcFZ.js.map} +1 -1
  44. package/dist/chunks/{NavListPanel-Iz1RCkVw.js → NavListPanel-zwUDIYSP.js} +2 -2
  45. package/dist/chunks/{NavListPanel-Iz1RCkVw.js.map → NavListPanel-zwUDIYSP.js.map} +1 -1
  46. package/dist/chunks/{OperationLogsPage-Dt22tU4I.js → OperationLogsPage-D2BQdGNp.js} +2 -2
  47. package/dist/chunks/{OperationLogsPage-Dt22tU4I.js.map → OperationLogsPage-D2BQdGNp.js.map} +1 -1
  48. package/dist/chunks/{OperationLogsTable-B23Ry-2v.js → OperationLogsTable-DaaON4QR.js} +3 -3
  49. package/dist/chunks/{OperationLogsTable-B23Ry-2v.js.map → OperationLogsTable-DaaON4QR.js.map} +1 -1
  50. package/dist/chunks/{PDFPreviewPanel-kBPz5dQr.js → PDFPreviewPanel-CMmnWBKW.js} +3 -3
  51. package/dist/chunks/{PDFPreviewPanel-kBPz5dQr.js.map → PDFPreviewPanel-CMmnWBKW.js.map} +1 -1
  52. package/dist/chunks/{PositionsPage-BIKYQDB5.js → PositionsPage-CBZITssT.js} +2 -2
  53. package/dist/chunks/{PositionsPage-BIKYQDB5.js.map → PositionsPage-CBZITssT.js.map} +1 -1
  54. package/dist/chunks/{PreferencesSheetBody-D276rrp4.js → PreferencesSheetBody-B0poTPEA.js} +2 -2
  55. package/dist/chunks/{PreferencesSheetBody-D276rrp4.js.map → PreferencesSheetBody-B0poTPEA.js.map} +1 -1
  56. package/dist/chunks/{ProfilePage-DLftC6KZ.js → ProfilePage-DLhacdWt.js} +2 -2
  57. package/dist/chunks/{ProfilePage-DLftC6KZ.js.map → ProfilePage-DLhacdWt.js.map} +1 -1
  58. package/dist/chunks/{ProjectInfoPage-DkuBLC8t.js → ProjectInfoPage-CJpGxpu5.js} +2 -2
  59. package/dist/chunks/{ProjectInfoPage-DkuBLC8t.js.map → ProjectInfoPage-CJpGxpu5.js.map} +1 -1
  60. package/dist/chunks/{RelationPanel-B4BeO0Bz.js → RelationPanel-BsbfEDo2.js} +2 -2
  61. package/dist/chunks/{RelationPanel-B4BeO0Bz.js.map → RelationPanel-BsbfEDo2.js.map} +1 -1
  62. package/dist/chunks/{RolesPage-BhltU2Qm.js → RolesPage-46dzdiah.js} +2 -2
  63. package/dist/chunks/{RolesPage-BhltU2Qm.js.map → RolesPage-46dzdiah.js.map} +1 -1
  64. package/dist/chunks/{SessionConflictModal-3R8jdYkI.js → SessionConflictModal-Bm38eExL.js} +2 -2
  65. package/dist/chunks/{SessionConflictModal-3R8jdYkI.js.map → SessionConflictModal-Bm38eExL.js.map} +1 -1
  66. package/dist/chunks/SettingModuleDetail-BjxUJeH5.js +17 -0
  67. package/dist/chunks/SettingModuleDetail-BjxUJeH5.js.map +1 -0
  68. package/dist/chunks/{SettingsPage-DMzeDrnc.js → SettingsPage-C32Vuizm.js} +2 -2
  69. package/dist/chunks/{SettingsPage-DMzeDrnc.js.map → SettingsPage-C32Vuizm.js.map} +1 -1
  70. package/dist/chunks/{StatCard-C0xSZyiS.js → StatCard-CRPfkSBY.js} +2 -2
  71. package/dist/chunks/{StatCard-C0xSZyiS.js.map → StatCard-CRPfkSBY.js.map} +1 -1
  72. package/dist/chunks/{UserGroupsPage-DTJdszHl.js → UserGroupsPage-08G5MdGm.js} +2 -2
  73. package/dist/chunks/{UserGroupsPage-DTJdszHl.js.map → UserGroupsPage-08G5MdGm.js.map} +1 -1
  74. package/dist/chunks/{UserLogsPanels-z4UhQtgu.js → UserLogsPanels-nbIrMym9.js} +2 -2
  75. package/dist/chunks/{UserLogsPanels-z4UhQtgu.js.map → UserLogsPanels-nbIrMym9.js.map} +1 -1
  76. package/dist/chunks/{UserTransferSelect-BJNUXMhl.js → UserTransferSelect-C8betaWG.js} +2 -2
  77. package/dist/chunks/{UserTransferSelect-BJNUXMhl.js.map → UserTransferSelect-C8betaWG.js.map} +1 -1
  78. package/dist/chunks/{UsersPage--p68X2Yr.js → UsersPage-BjTiNEqF.js} +2 -2
  79. package/dist/chunks/{UsersPage--p68X2Yr.js.map → UsersPage-BjTiNEqF.js.map} +1 -1
  80. package/dist/chunks/{browser-BKLM0ThC-3Xar5rZw.js → browser-BKLM0ThC-Cp7Gi4-F.js} +1 -1
  81. package/dist/chunks/{code-P0HJS_q1.js → code-LswxAr98.js} +1 -1
  82. package/dist/chunks/{direct-engine-BYEscsGg.js → direct-engine-Dv_6v4sx.js} +1 -1
  83. package/dist/chunks/{html-B__1Vr_C.js → html-BokjxlLb.js} +1 -1
  84. package/dist/chunks/{line-DzLRZVEq.js → line-Bqh6atHH.js} +1 -1
  85. package/dist/chunks/{lrc-kf-TilFB.js → lrc-T5e1svZG.js} +1 -1
  86. package/dist/chunks/{markdown-xIo-vnKK.js → markdown-BpWokN1s.js} +1 -1
  87. package/dist/chunks/{patch-BEaX-xYV.js → patch-BYVX5C9G.js} +1 -1
  88. package/dist/chunks/{worker-engine-FCdIQLzN.js → worker-engine-CtUAeI4G.js} +1 -1
  89. package/dist/core/hooks/queries/settings.d.ts +6 -0
  90. package/dist/core/hooks/queries/settings.d.ts.map +1 -1
  91. package/dist/core/hooks/queries/settings.js +34 -25
  92. package/dist/core/hooks/queries/settings.js.map +1 -1
  93. package/dist/core/hooks/useAuth.d.ts +2 -0
  94. package/dist/core/hooks/useAuth.d.ts.map +1 -1
  95. package/dist/core/hooks/useAuth.js.map +1 -1
  96. package/dist/core/index.js +7 -7
  97. package/dist/core/lib/go-auth-api.d.ts +1 -1
  98. package/dist/core/lib/go-auth-api.d.ts.map +1 -1
  99. package/dist/core/lib/go-auth-api.js +12 -8
  100. package/dist/core/lib/go-auth-api.js.map +1 -1
  101. package/dist/core/lib/native-operations.d.ts +85 -4
  102. package/dist/core/lib/native-operations.d.ts.map +1 -1
  103. package/dist/core/lib/native-operations.js +1 -0
  104. package/dist/core/lib/native-operations.js.map +1 -1
  105. package/dist/core/providers/GoAuthProvider.d.ts.map +1 -1
  106. package/dist/core/providers/GoAuthProvider.js +191 -142
  107. package/dist/core/providers/GoAuthProvider.js.map +1 -1
  108. package/dist/core/session-renewal.d.ts +15 -0
  109. package/dist/core/session-renewal.d.ts.map +1 -0
  110. package/dist/core/session-renewal.js +95 -0
  111. package/dist/core/session-renewal.js.map +1 -0
  112. package/dist/core/session-transition.d.ts +2 -0
  113. package/dist/core/session-transition.d.ts.map +1 -1
  114. package/dist/core/session-transition.js +20 -7
  115. package/dist/core/session-transition.js.map +1 -1
  116. package/dist/core/session.d.ts +4 -0
  117. package/dist/core/session.d.ts.map +1 -1
  118. package/dist/core/session.js +88 -61
  119. package/dist/core/session.js.map +1 -1
  120. package/dist/index.js +1 -1
  121. package/dist/{src-C8_bzBi4.js → src-D6UlLiVN.js} +2 -2
  122. package/dist/{src-C8_bzBi4.js.map → src-D6UlLiVN.js.map} +1 -1
  123. package/package.json +9 -9
  124. package/dist/chunks/ApiTokensPage-DiRMgViD.js +0 -2
  125. package/dist/chunks/ApiTokensPage-DiRMgViD.js.map +0 -1
  126. package/dist/chunks/EntityContextRuntime-BOJySc1D.js +0 -1
  127. package/dist/chunks/IdentitySecurityPage-DW5ybVL4.js +0 -9
  128. package/dist/chunks/IdentitySecurityPage-DW5ybVL4.js.map +0 -1
  129. package/dist/chunks/SettingModuleDetail-Dppk9An1.js +0 -17
  130. package/dist/chunks/SettingModuleDetail-Dppk9An1.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"mappings":";;;;;;;IASMA,GAAa,CACjB,KAAM,OACN,KAAM,GACN,KAAM,CACJ,CAAC,OAAQ,CAAE,EAAG,uCAAwC,IAAK,QAAS,CAAC,EACrE,CAAC,OAAQ,CAAE,EAAG,yCAA0C,IAAK,QAAS,CAAC,EACvE,CAAC,OAAQ,CAAE,EAAG,2CAA4C,IAAK,QAAS,CAAC,EACzE,CACE,OACA,CACE,EAAG,oGACH,IAAK,QACP,CACF,CACF,CACF,EACAC,GAAW,KACL,GAAOC,EAAiBF,EAAU,C;;;;;;;ICjBlCA,GAAa,CACjB,KAAM,aACN,KAAM,GACN,KAAM,CACJ,CAAC,OAAQ,CAAE,EAAG,YAAa,IAAK,QAAS,CAAC,EAC1C,CAAC,OAAQ,CAAE,EAAG,YAAa,IAAK,QAAS,CAAC,EAC1C,CAAC,OAAQ,CAAE,EAAG,YAAa,IAAK,QAAS,CAAC,EAC1C,CAAC,OAAQ,CAAE,EAAG,aAAc,IAAK,QAAS,CAAC,CAC7C,CACF,EACAG,GAAW,KACL,GAAYD,EAAiBF,EAAU,C;;;;;;;ICXvCA,GAAa,CACjB,KAAM,aACN,KAAM,GACN,KAAM,CACJ,CAAC,OAAQ,CAAE,EAAG,aAAc,IAAK,QAAS,CAAC,EAC3C,CAAC,OAAQ,CAAE,EAAG,cAAe,IAAK,QAAS,CAAC,EAC5C,CAAC,OAAQ,CAAE,EAAG,YAAa,IAAK,QAAS,CAAC,EAC1C,CAAC,OAAQ,CAAE,EAAG,YAAa,IAAK,QAAS,CAAC,CAC5C,CACF,EACA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KAAmBC,EAAbD,EAAcE,GAAyBC,GAA1B,CAAW,KAAM,EAAI,CAAyB,EAAG,QAASJ,CAAoB,GACxM,kBAAChC,EAAD,CAAQ,aAAW,OAAO,MAAM,aAAa,KAAK,QAAQ,KAAM,kBAACqC,EAAD,CAAG,KAAM,EAAI,GAAG,QAASC,CAAS,EACjG,CACL,qBAACvB,GAAD,CAAkB,MAAM,EACvB,C,EACT,C,oLA3IQ,UAASwB,EACX,GAAe,CACjB,CAAE,MAAO1nB,EAAS,UAAW,MAAO,MAAO,EAC3C,CAAE,MAAOA,EAAS,QAAS,MAAO,MAAO,EACzC,CAAE,MAAOA,EAAS,SAAU,MAAO,MAAO,EAC1C,CAAE,MAAO,IAAK,MAAO,MAAO,CAChC,C","names":["__iconData","__iconData$4","createLucideIcon","__iconData$3","__iconData$2","__iconData$1","randomBytes","bytes","size","offset","toIntPos","p","toIntSize","s","toIntRect","r","swap","height","width","transformSize","rotation","scaleFactor","quadToRect","xs","q","ys","rectToQuad","rotatePosition","x","position","y","containerSize","scalePosition","transformPosition","restorePosition","rotateRect","rect","scaleRect","transformRect","boundingRect","rects","minX","minY","maxX","maxY","buildUserToDeviceMatrix","L","B","W","H","sx0","outW","sy0","outH","sx90","sy90","stripPdfUnwantedMarkers","text","PdfUnwantedTextRegex","flagsToNames","PdfAnnotationFlagName","raw","flag","namesToFlags","names","mask","PdfAnnotationFlagValue","name","pdfColorToWebColor","clamp","n","toHex","c","webColorToPdfColor","color","g","b","pdfAlphaToWebOpacity","alpha","webOpacityToPdfAlpha","hi","opacity","pdfDateToDate","pdf","mo","d","M","S","dateToPdfDate","z","len","date","serializeLogger","logger","NoopLogger","ConsoleLogger","PerfLogger","LevelLogger","levelLogger","AllLogger","allLogger","getRandomBytes","__require","__toCommonJS","browser_random_exports","i","uuidV4","hex","getImageMetadata","buffer","parsePng","parseJpeg","view","marker","segLen","ignore","\"Degree0\"","\"Degree90\"","\"Degree180\"","\"Degree270\"","Rotation2","Rotation","args","source","category","event","phase","level","markName","identifier","measureName","beginMark","startTime","duration","loggers","\"Pending\"","\"Resolved\"","\"Rejected\"","\"Aborted\"","TaskStage2","TaskStage","reason","Task","resolve","result","error","reject","TaskAbortedError","TaskRejectedError","resolvedCallback","rejectedCallback","cb","combinedTask","tasks","results","resolvedCount","isSettled","task","index","settledCount","onProgress","completedCount","PdfUnwantedTextMarkers","\"Unknown\"","\"XYZ\"","\"FitPage\"","\"FitHorizontal\"","\"FitVertical\"","\"FitRectangle\"","\"FitBoundingBox\"","\"FitBoundingBoxHorizontal\"","\"FitBoundingBoxVertical\"","PdfZoomMode2","PdfZoomMode","\"NotSet\"","\"True\"","\"False\"","PdfTrappedStatus2","PdfTrappedStatus","\"Courier\"","\"Courier_Bold\"","\"Courier_BoldOblique\"","\"Courier_Oblique\"","\"Helvetica\"","\"Helvetica_Bold\"","\"Helvetica_BoldOblique\"","\"Helvetica_Oblique\"","\"Times_Roman\"","\"Times_Bold\"","\"Times_BoldItalic\"","\"Times_Italic\"","\"Symbol\"","\"ZapfDingbats\"","PdfStandardFont2","PdfStandardFont","\"Left\"","\"Center\"","\"Right\"","PdfTextAlignment2","PdfTextAlignment","\"Normal\"","\"Multiply\"","\"Screen\"","\"Overlay\"","\"Darken\"","\"Lighten\"","\"ColorDodge\"","\"ColorBurn\"","\"HardLight\"","\"SoftLight\"","\"Difference\"","\"Exclusion\"","\"Hue\"","\"Saturation\"","\"Color\"","\"Luminosity\"","PdfBlendMode2","PdfBlendMode","\"Contain\"","\"Cover\"","\"Stretch\"","PdfStampFit2","PdfStampFit","\"Unsupported\"","\"Goto\"","\"RemoteGoto\"","\"URI\"","\"LaunchAppOrOpenFile\"","PdfActionType2","PdfActionType","\"UNKNOWN\"","\"TEXT\"","\"LINK\"","\"FREETEXT\"","\"LINE\"","\"SQUARE\"","\"CIRCLE\"","\"POLYGON\"","\"POLYLINE\"","\"HIGHLIGHT\"","\"UNDERLINE\"","\"SQUIGGLY\"","\"STRIKEOUT\"","\"STAMP\"","\"CARET\"","\"INK\"","\"POPUP\"","\"FILEATTACHMENT\"","\"SOUND\"","\"MOVIE\"","\"WIDGET\"","\"SCREEN\"","\"PRINTERMARK\"","\"TRAPNET\"","\"WATERMARK\"","\"THREED\"","\"RICHMEDIA\"","\"XFAWIDGET\"","\"REDACT\"","PdfAnnotationSubtype2","PdfAnnotationSubtype","\"Rollover\"","\"Down\"","AppearanceMode2","AppearanceMode","\"Comment\"","\"Key\"","\"Note\"","\"Help\"","\"NewParagraph\"","\"Paragraph\"","\"Insert\"","\"Graph\"","\"PushPin\"","\"Paperclip\"","\"Tag\"","\"Speaker\"","\"Mic\"","\"Approved\"","\"Experimental\"","\"NotApproved\"","\"AsIs\"","\"Expired\"","\"NotForPublicRelease\"","\"Confidential\"","\"Final\"","\"Sold\"","\"Departmental\"","\"ForComment\"","\"TopSecret\"","\"Draft\"","\"ForPublicRelease\"","\"Completed\"","\"Void\"","\"PreliminaryResults\"","\"InformationOnly\"","\"Witness\"","\"InitialHere\"","\"SignHere\"","\"Accepted\"","\"Custom\"","\"Image\"","PdfAnnotationName2","PdfAnnotationName","\"None\"","\"Square\"","\"Circle\"","\"Diamond\"","\"OpenArrow\"","\"ClosedArrow\"","\"Butt\"","\"ROpenArrow\"","\"RClosedArrow\"","\"Slash\"","PdfAnnotationLineEnding2","PdfAnnotationLineEnding","\"Reply\"","\"Group\"","PdfAnnotationReplyType2","PdfAnnotationReplyType","\"PUSHBUTTON\"","\"CHECKBOX\"","\"RADIOBUTTON\"","\"COMBOBOX\"","\"LISTBOX\"","\"TEXTFIELD\"","\"SIGNATURE\"","\"XFA\"","\"XFA_CHECKBOX\"","\"XFA_COMBOBOX\"","\"XFA_IMAGEFIELD\"","\"XFA_LISTBOX\"","\"XFA_PUSHBUTTON\"","\"XFA_SIGNATURE\"","\"XFA_TEXTFIELD\"","PDF_FORM_FIELD_TYPE2","PDF_FORM_FIELD_TYPE","\"InteriorColor\"","\"OverlayColor\"","\"TextColor\"","PdfAnnotationColorType2","PdfAnnotationColorType","\"SOLID\"","\"DASHED\"","\"BEVELED\"","\"INSET\"","\"CLOUDY\"","PdfAnnotationBorderStyle2","PdfAnnotationBorderStyle","\"NONE\"","\"READONLY\"","\"REQUIRED\"","\"NOEXPORT\"","\"TEXT_MULTIPLINE\"","\"TEXT_PASSWORD\"","\"TEXT_FILESELECT\"","\"TEXT_DONOTSPELLCHECK\"","\"TEXT_DONOTSCROLL\"","\"TEXT_COMB\"","\"TEXT_RICHTEXT\"","\"BUTTON_NOTOGGLETOOFF\"","\"BUTTON_RADIO\"","\"BUTTON_PUSHBUTTON\"","\"BUTTON_RADIOSINUNISON\"","\"CHOICE_COMBO\"","\"CHOICE_EDIT\"","\"CHOICE_SORT\"","\"CHOICE_MULTL_SELECT\"","\"CHOICE_DONOTSPELLCHECK\"","\"CHOICE_COMMITONSELCHANGE\"","PDF_FORM_FIELD_FLAG2","PDF_FORM_FIELD_FLAG","\"PATH\"","\"IMAGE\"","\"SHADING\"","\"FORM\"","PdfPageObjectType2","PdfPageObjectType","bit","acc","\"KEY_STROKE\"","\"FORMAT\"","\"VALIDATE\"","\"CALCULATE\"","PDF_ANNOT_AACTION_EVENT2","PDF_ANNOT_AACTION_EVENT","\"Keystroke\"","\"Format\"","\"Validate\"","\"Calculate\"","PdfJavaScriptWidgetEventType2","PdfJavaScriptWidgetEventType","\"DocumentNamed\"","\"WidgetKeystroke\"","\"WidgetFormat\"","\"WidgetValidate\"","\"WidgetCalculate\"","PdfJavaScriptActionTrigger2","PdfJavaScriptActionTrigger","\"Create\"","\"Read\"","\"Update\"","\"Delete\"","PdfEngineOperation2","PdfEngineOperation","\"Print\"","\"ModifyContents\"","\"CopyContents\"","\"ModifyAnnotations\"","\"FillForms\"","\"ExtractForAccessibility\"","\"AssembleDocument\"","\"PrintHighQuality\"","\"AllowAll\"","PdfPermissionFlag2","PdfPermissionFlag","flagNames","requiredFlags","f","currentPermissions","\"Display\"","PdfPageFlattenFlag2","PdfPageFlattenFlag","\"Ok\"","\"NotFound\"","\"WrongFormat\"","\"Password\"","\"Security\"","\"PageError\"","\"XFALoad\"","\"XFALayout\"","\"Cancelled\"","\"Initialization\"","\"NotReady\"","\"NotSupport\"","\"LoadDoc\"","\"DocNotOpen\"","\"CantCloseDoc\"","\"CantCreateNewDoc\"","\"CantImportPages\"","\"CantCreateAnnot\"","\"CantSetAnnotRect\"","\"CantSetAnnotContent\"","\"CantRemoveInkList\"","\"CantAddInkStoke\"","\"CantReadAttachmentSize\"","\"CantReadAttachmentContent\"","\"CantFocusAnnot\"","\"CantSelectText\"","\"CantSelectOption\"","\"CantCheckField\"","\"CantSetAnnotString\"","\"CantDeletePage\"","PdfErrorCode2","PdfErrorCode","TEXT_ALIGNMENT_INFOS","info","m","\"Times\"","PdfStandardFontFamily2","PdfStandardFontFamily","HELVETICA_DESC","STANDARD_FONT_DESCRIPTORS","familyStyleToId","family","BLEND_MODE_INFOS","CompoundTask","config","child","childIndex","progressValue","finalResult","otherChild","compound","record","resolved","\"handleChildSuccess\"","\"children\"","getPermissionOverride","overrides","PERMISSION_FLAG_TO_NAME","getEffectivePermission","docState","state","documentId","docConfig","globalConfig","pdfPermissions","docOverride","globalOverride","getEffectivePermissions","ALL_PERMISSION_FLAGS","calculateNextActiveDocument","currentActiveId","closingDocumentId","explicitNext","closingIndex","moveDocumentInOrder","fromIndex","currentOrder","toIndex","newOrder","createPluginRegistration","pluginPackage","hasAutoMountElements","pkg","isKeyedOptions","options","value","min","max","arePropsEqual","a","aType","visited","pairId","getPairId","aIsArray","bIsArray","arraysEqualUnordered","objectsEqual","objectId","objectIds","obj","objectIdCounter","used","elemA","j","aKeys","bKeys","key","valA","valB","createEmitter","listeners","l","v","createBehaviorEmitter","proxyMap","_value","initial","notify","baseOn","realListener","listener","destroy","ctl","KeyedEventControl","EventControl","equality","proxy","prev","mapped","selector","next","eq","createScopedEmitter","shouldCache","scopeCaches","scopeListeners","scopeProxyMaps","globalListeners","globalProxyMap","normalizeKey","getOrCreateListeners","getOrCreateProxyMap","normalizedKey","cached","data","globalEvent","toGlobalEvent","options2","set","map","createPluginPackage","PluginPackageBuilder","basePackage","id","dependencies","recursionStack","dfs","dep","temp","visit","message","store","pluginId","action","newPluginState","oldPluginState","type","handler","oldState","SET_ACTIVE_DOCUMENT","SET_ROTATION","START_LOADING_DOCUMENT","UPDATE_DOCUMENT_LOADING_PROGRESS","SET_DOCUMENT_LOADED","CLOSE_DOCUMENT","SET_DOCUMENT_ERROR","RETRY_LOADING_DOCUMENT","REFRESH_DOCUMENT","REFRESH_PAGES","SET_PAGES","SET_SCALE","SET_DEFAULT_SCALE","SET_DEFAULT_ROTATION","REORDER_DOCUMENTS","MOVE_DOCUMENT","UPDATE_DOCUMENT_SECURITY","setRotation","order","initialCoreState2","reducer","initialState","oldGlobalState","notifyGlobal","currentPluginState","newState","PluginStore","CORE_ACTION_TYPES","_a","_b","newDocState","scale","passwordProvided","autoActivate","progress","removed","remainingDocs","nextActiveDocumentId","targetId","newVersions","pageIndex","pageIndexes","DependencyResolver","engine","initialCoreState","Store","coreReducer","PluginRegistrationError","readyPromises","reg","dependsOn","allDeps","cap","provider","loadOrder","err","CircularDependencyError","finalConfig","manifest","plugin","packageCreator","capability","PluginNotFoundError","missingKeys","defaultConfig","PluginConfigurationError","currentConfig","newConfig","registrations","otherId","otherManifest","status","registry","now","cooldownTime","actionKey","debounceTime","actionType","timeout","doc","docId","flags","missingFlags","effectivePermissions","PermissionDeniedError","throttleMode","control","AutoMount","useMemo","utilities2","wrappers2","plugins","elements","element","contentWithUtilities","Fragment","children","utilities","Utility","wrappedContent","wrappers","Wrapper","content","EmbedPDF","setRegistry","useState","coreState","setCoreState","isInitializing","setIsInitializing","pluginsReady","setPluginsReady","initRef","useRef","onInitialized","useEffect","pdfViewer","PluginRegistry","initialize","unsubscribe","cleanup","unsub","contextValue","activeDocumentId","documents","documentOrder","activeDocument","documentStates","PDFContext","autoMountDomElements","useRegistry","useContext","usePlugin","useCapability","useCoreState","useDocumentState","createContext","usePdfiumEngine","defaultWasmUrl","setEngine","loading","setLoading","setError","engineRef","cancelled","worker","__vitePreload","pdfEngine","createPdfiumEngine","wasmUrl","e","_a2","_b2","fontFallback","BasePlugin","setActiveDocument","activeId","moveDocument","index1","id1","index2","id2","reorderDocuments","ownerPassword","previousId","currentId","limitError","documentName","startLoadingDocument","file","engineTask","validation","mergedOptions","retryOptions","retryLoadingDocument","closeDocument","documentIds","success","document","updateDocumentSecurity","setDocumentLoaded","pdfDocument","context","errorMessage","setDocumentError","lastSegment","url","filename","_DocumentManagerPlugin","DOCUMENT_MANAGER_PLUGIN_ID","DocumentManagerPluginPackage","manifest$10","DocumentManagerPlugin","DocumentContent","documentState","isLoading","isError","isLoaded","FilePicker","useDocumentManagerPlugin","useDocumentManagerCapability","inputRef","taskRef","optionsRef","provides","DocumentManagerPluginPackage$1","initViewportState","INIT_VIEWPORT_STATE","cleanupViewportState","CLEANUP_VIEWPORT_STATE","registerViewport","REGISTER_VIEWPORT","unregisterViewport","UNREGISTER_VIEWPORT","setViewportGap","SET_VIEWPORT_GAP","viewportGap","setViewportMetrics","SET_VIEWPORT_METRICS","setViewportScrollMetrics","SET_VIEWPORT_SCROLL_METRICS","setScrollActivity","SET_SCROLL_ACTIVITY","setSmoothScrollActivity","SET_SMOOTH_SCROLL_ACTIVITY","addViewportGate","ADD_VIEWPORT_GATE","removeViewportGate","REMOVE_VIEWPORT_GATE","VIEWPORT_PLUGIN_ID","initialViewportDocumentState","newActiveViewports","SET_ACTIVE_VIEWPORT_DOCUMENT","viewport","metrics","scrollMetrics","newGates","pos","emitter","behavior","finalX","finalY","alignX","alignY","prevViewport","prevState","newViewport","prevGates","addedGate","removedGate","_ViewportPlugin","manifest$9","ViewportPlugin","viewportReducer","initialState$8","useViewportRef","viewportPlugin","useViewportPlugin","containerRef","useLayoutEffect","container","onScroll","resizeObserver","unsubscribeScrollRequest","Viewport","props","viewportRef","viewportProvides","useViewportCapability","isGated","useIsViewportGated","restProps","ViewportElementContext","style","setIsGated","initScrollState","INIT_SCROLL_STATE","cleanupScrollState","CLEANUP_SCROLL_STATE","updateDocumentScrollState","UPDATE_DOCUMENT_SCROLL_STATE","setScrollStrategy","SET_SCROLL_STRATEGY","\"Vertical\"","\"Horizontal\"","ScrollStrategy2","ScrollStrategy","totalContentSize","_item","scrollOffset","clientSize","viewportStart","viewportEnd","startIndex","virtualItems","endIndex","range","visibleItems","pageVisibilityMetrics","visiblePages","renderedPageIndexes","item","currentPage","first","last","startSpacing","lastItem","endSpacing","visibilityMetrics","centeringOffsetX","centeringOffsetY","itemX","itemY","pageX","page","pageY","pageWidth","pageHeight","viewportLeft","viewportTop","viewportRight","viewportBottom","intersectionLeft","intersectionTop","intersectionRight","intersectionBottom","visibleWidth","visibleHeight","totalArea","visibleArea","maxVisibility","mostVisiblePages","item2","pageNumber","pageLayout","layout","pageRect","scaledBasePosition","pageCoordinates","rotatedSize","BaseScrollStrategy","yOffset","pdfPageObject","pageLayouts","pagesInSpread","sum","xOffset","remaining","updates","idx","elevatedPages","im","pages","computedMetrics","coreDoc","strategy","viewportScope","callback","getScrollerLayout","isInitial","strategyType","HorizontalScrollStrategy","VerticalScrollStrategy","defaultPageChangeState","pageChangeState","targetPage","coreDocState","vp","items","isProgrammaticScroll","metricsToCommit","spread","effectiveRotation","currentItemIndex","newStrategy","prevDoc","newDoc","_ScrollPlugin","SCROLL_PLUGIN_ID","manifest$8","ScrollPlugin","scrollReducer","Scroller","scrollPlugin","useScrollPlugin","layoutData","setLayoutData","newLayout","scrollerLayout","renderPage","useScrollCapability","setCurrentPage","totalPages","setTotalPages","scope","_RenderPlugin","RENDER_PLUGIN_ID","RenderPlugin","RenderLayer","scaleOverride","dprOverride","renderProvides","useRenderCapability","imageUrl","setImageUrl","urlRef","refreshVersion","actualScale","actualDpr","blob","initZoomState","INIT_ZOOM_STATE","cleanupZoomState","CLEANUP_ZOOM_STATE","setZoomLevel","SET_ZOOM_LEVEL","setMarqueeZoomActive","SET_MARQUEE_ZOOM_ACTIVE","createMarqueeHandler","opts","start","onPreview","evt","pageSize","minDragPx","onCommit","onSmallDrag","\"Automatic\"","\"FitWidth\"","ZoomMode2","ZoomMode","\"Top\"","VerticalZoomFocus2","VerticalZoomFocus","ZOOM_PLUGIN_ID","initialDocumentState","isActive","_c","interactionManager","cfg","isMarqueeActive","cur","target","delta","oldZoom","base","exactZoom","newZoom","focusPoint","center","focus","align","desiredScrollLeft","desiredScrollTop","setScale","scrollScope","pgGap","vpGap","spreads","availableWidth","availableHeight","maxContentW","maxContentH","contentW","contentH","mode","off","cw","zoom","availableSpace","offXold","offYold","offXnew","offYnew","cx","cy","baseLeft","baseTop","oldZ","availableW","availableH","vItem","it","pageRel","rotatedRect","targetZoom","pageAbsX","pageAbsY","cxContent","cyContent","avail","centerVX","centerVY","ranges","r2","handlers","_ZoomPlugin","manifest$7","ZoomPlugin","zoomReducer","initialState$6","useZoomCapability","setState","initSearchState","INIT_SEARCH_STATE","cleanupSearchState","CLEANUP_SEARCH_STATE","startSearchSession","START_SEARCH_SESSION","stopSearchSession","STOP_SEARCH_SESSION","setSearchFlags","SET_SEARCH_FLAGS","setShowAllResults","SET_SHOW_ALL_RESULTS","startSearch","START_SEARCH","setSearchResults","SET_SEARCH_RESULTS","appendSearchResults","APPEND_SEARCH_RESULTS","setActiveResultIndex","SET_ACTIVE_RESULT_INDEX","updateDocState","oldDocState","initialSearchDocumentState","newResults","firstHitIndex","initialState2","prevDocState","getDocId","getDocState","keyword","showAll","PdfTaskHelper","trimmedKeyword","force","oldTask","activeResultIndex","nextIndex","prevIndex","_SearchPlugin","SEARCH_PLUGIN_ID","manifest$6","SearchPlugin","searchReducer","initialState$5","SearchLayer","searchProvides","useSearchCapability","searchResultState","setSearchResultState","currentState","resultsToShow","originalIndex","activeHighlightColor","highlightColor","rectIndex","searchState","setSearchState","selectRectsForPage","selectBoundingRectForPage","selectBoundingRectsForAllPages","out","rectMap","bRect","getFormattedSelectionForPage","segmentRects","boundingRect2","getFormattedSelection","glyphAt","run","geo","pt","rel","gx","gy","gw","gh","toleranceFactor","halfTol","computeTolerance","bestIndex","bestDist","expandedLeft","expandedRight","expandedTop","expandedBottom","dist","totalHeight","count","factor","sliceBounds","sel","from","lastRun","lastCharOnPage","rectsWithinSlice","textRuns","runStart","runEnd","to","sIdx","eIdx","charCount","widthSum","prevRight","flushSubRun","gap","avgWidth","merge","mergeAdjacentRects","rectUnion","left","rect1","rect2","top","right","bottom","rectIntersect","rectIsEmpty","getVerticalOverlap","unionRect","shouldMergeHorizontalRects","textRun1","textRun2","averageWidth1","averageWidth2","rect1Left","rect1Right","rect2Left","previousTextRun","currentRect","textRun","resolveCharIndex","localIdx","charIndex","isGlyphWordBoundary","expandToWordBoundary","totalChars","getTotalCharCount","expandToLineBoundary","anchorRun","anchorTop","anchorBottom","runsOverlapVertically","isZeroSizeRun","unionHeight","bottom1","bottom2","top1","top2","intersectHeight","VERTICAL_OVERLAP_THRESHOLD_LINE","createTextSelectionHandler","minDrag","tolFactor","anchorGlyph","anchorPos","dragStarted","lastDblClickTime","reset","modeId","TRIPLE_CLICK_INTERVAL_MS","point","dx","dy","createMarqueeSelectionHandler","SELECTION_PLUGIN_ID","INIT_SELECTION_STATE","CLEANUP_SELECTION_STATE","CACHE_PAGE_GEOMETRY","SET_SELECTION","START_SELECTION","END_SELECTION","CLEAR_SELECTION","SET_RECTS","allRects","SET_SLICES","EVICT_PAGE_GEOMETRY","geometry","slices","RESET","initialSelectionDocumentState","imPlugin","initSelectionState","marqueeEnabled","cleanupSelectionState","enabled","onRectsChange","geoTask","interactionScope","enabledModes","sb","pageRects","setRects","setSlices","textHandler","cursor","active","unregisterHandlers","shouldShowRect","marqueeHandler","onRectChange","viewportRect","rectTopInView","vpMetrics","rectBottomInView","placement","bounds","tail","head","tailMetrics","headMetrics","modeConfig","pageIdx","cachePageGeometry","pinned","toEvict","candidate","evictPageGeometry","startSelection","endSelection","clearSelection","validationError","normalized","geoTasks","clamped","previouslyHighlighted","setSelection","pagesToNotify","isValidPointer","pageCount","minPage","maxPage","lastGlyphIndex","startMax","endMax","clampIndex","end","forward","allSlices","req","text2","modes","current","_SelectionPlugin","SelectionPluginPackage","manifest$5","SelectionPlugin","selectionReducer","initialState$4","getCounterRotation","w","h","CounterRotate","elementRef","handlePointerDown","handleTouchStart","menuWrapperProps","matrix","el","TextSelection","rotationOverride","selPlugin","useSelectionPlugin","setBoundingRect","setPlacement","rects2","newPlacement","actualRotation","shouldRenderMenu","selectionMenu","SelectionLayer","Fragment$1","textStyle","background","MarqueeSelection","marqueeStyle","marqueeClassName","CopyToClipboard","useSelectionCapability","setRect","resolvedBorderColor","borderColor","stroke","resolvedBackground","fill","borderStyle","SelectionPluginPackage$1","initInteractionState","INIT_INTERACTION_STATE","cleanupInteractionState","CLEANUP_INTERACTION_STATE","activateMode","ACTIVATE_MODE","pauseInteraction","PAUSE_INTERACTION","resumeInteraction","RESUME_INTERACTION","setCursor","SET_CURSOR","setDefaultMode","SET_DEFAULT_MODE","setExclusionRules","SET_EXCLUSION_RULES","addExclusionClass","ADD_EXCLUSION_CLASS","removeExclusionClass","REMOVE_EXCLUSION_CLASS","addExclusionAttribute","ADD_EXCLUSION_ATTRIBUTE","removeExclusionAttribute","REMOVE_EXCLUSION_ATTRIBUTE","mergeHandlers","keys","k","list","INITIAL_MODE$1","docBuckets","topics","activePages","token","priority","rules","className","attribute","topic","previousMode","modeIds","cleanupFunctions","bucket","set2","docPageMap","mergeSets","claims","oldPage","handlerSet","_InteractionManagerPlugin","INTERACTION_MANAGER_PLUGIN_ID","INITIAL_MODE","manifest$4","InteractionManagerPlugin","initialState$3","useIsPageExclusive","useInteractionManagerCapability","isPageExclusive","setIsPageExclusive","listenerOpts","eventType","wantsRawTouch","isTouchEvent","shouldExcludeElement","attr","createPointerProvider","capScope","wantsRawTouchNow","attachedWithRawTouch","addListeners","allEventTypes","fn","handleEvent","removeListeners","stopMode","stopHandler","initialMode","initialCursor","stopCursor","toPos","convertEventToPoint","host","exclusionRules","handlerKey","domEventMap","normEvt","propagationStopped","tp","pe","pointerEventTypes","touchEventTypes","ref","naturalPageSize","pageRotation","docRotation","displaySize","defaultConvertEventToPoint","useCallback","displayPoint","getRotationMatrix","getRotationMatrixString","getNextRotation","getPreviousRotation","initRotateState","INIT_ROTATE_STATE","cleanupRotateState","CLEANUP_ROTATE_STATE","ROTATE_PLUGIN_ID","setRotation$1","nextRotation","prevRotation","_RotatePlugin","SET_ACTIVE_ROTATE_DOCUMENT","manifest$3","RotatePlugin","rotateReducer","initialState$2","useRotateCapability","newRotation","initPanState","INIT_PAN_STATE","cleanupPanState","CLEANUP_PAN_STATE","setPanMode","SET_PAN_MODE","isPanMode","dragState","unregister","_PanPlugin","SET_ACTIVE_PAN_DOCUMENT","PanPluginPackage","manifest$2","PanPlugin","panReducer","initialState$1","usePanCapability","isPanning","setIsPanning","isPan","pan","panPlugin","usePanPlugin","SUPPORT_TOUCH","PanPluginPackage$1","PanMode","initThumbnailState","INIT_THUMBNAIL_STATE","cleanupThumbnailState","CLEANUP_THUMBNAIL_STATE","setWindowState","SET_WINDOW_STATE","updateViewportMetrics","UPDATE_VIEWPORT_METRICS","THUMBNAIL_PLUGIN_ID","taskCache","dpr","scrollY","viewportH","OUTER_W","GAP","P","PADDING_Y","INNER_W","thumbs","isRotated90or270","effectiveWidth","ratio","imgH","wrapH","meta","window","BUF","low","high","mid","limit","newWindow","needsUp","needsDown","cache","_ThumbnailPlugin","manifest$1","ThumbnailPlugin","thumbnailReducer","ThumbnailsPane","thumbnailPlugin","useThumbnailPlugin","windowData","setWindowData","window2","initialWindow","paddingY","ThumbImg","useThumbnailCapability","setUrl","refreshTick","setRefreshTick","tick","objectUrl","PRINT_PLUGIN_ID","printOptions","_PrintPlugin","PrintPluginPackage","PrintPlugin","requireClient","hasRequiredClient","client","require$$0","PrintFrame","printCapability","usePrintCapability","printPlugin","usePrintPlugin","iframeRef","iframe","PrintPluginPackage$1","import.meta.ROLLDOWN_FILE_URL_FKNdLzKnlftW3t_gzo81yw","PDFDocument","scroll","useScroll","useZoom","search","useSearch","rotate","useRotate","usePan","print","usePrint","zoomLabelId","useId","zoomLevel","query","setQuery","thumbnails","setThumbnails","_Fragment","Button","PanelLeft","ChevronLeft","ChevronRight","Select","ZOOM_OPTIONS","RotateCw","Hand","Printer","fileName","Download","PagePointerProvider","PDFLoadError","password","setPassword","PDFContent","pdfiumWasmUrl","setSource","ViewportPluginPackage","ScrollPluginPackage","RenderPluginPackage","InteractionManagerPluginPackage","ZoomPluginPackage","SearchPluginPackage","RotatePluginPackage","ThumbnailPluginPackage","PDFPreviewPanel","useThemeController","isDark","FileTypeIcon","Text","actions","onToggleFullscreen","fullscreen","jsx","Minimize2","Maximize2","X","onClose","Typography"],"ignoreList":[0,1,2,3,4,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36],"sources":["../../../../node_modules/lucide-react/dist/esm/icons/hand.mjs","../../../../node_modules/lucide-react/dist/esm/icons/maximize-2.mjs","../../../../node_modules/lucide-react/dist/esm/icons/minimize-2.mjs","../../../../node_modules/lucide-react/dist/esm/icons/panel-left.mjs","../../../../node_modules/lucide-react/dist/esm/icons/printer.mjs","../../../../scripts/lib/browser-random.mjs","../../../../node_modules/@embedpdf/models/dist/index.js","../../../../node_modules/@embedpdf/core/dist/index.js","../../../../node_modules/@embedpdf/core/dist/react/index.js","../../../../node_modules/@embedpdf/engines/dist/react/index.js","../../../../node_modules/@embedpdf/plugin-document-manager/dist/index.js","../../../../node_modules/@embedpdf/plugin-document-manager/dist/react/index.js","../../../../node_modules/@embedpdf/plugin-viewport/dist/index.js","../../../../node_modules/@embedpdf/plugin-viewport/dist/react/index.js","../../../../node_modules/@embedpdf/plugin-scroll/dist/index.js","../../../../node_modules/@embedpdf/plugin-scroll/dist/react/index.js","../../../../node_modules/@embedpdf/plugin-render/dist/index.js","../../../../node_modules/@embedpdf/plugin-render/dist/react/index.js","../../../../node_modules/@embedpdf/plugin-zoom/dist/index.js","../../../../node_modules/@embedpdf/plugin-zoom/dist/react/index.js","../../../../node_modules/@embedpdf/plugin-search/dist/index.js","../../../../node_modules/@embedpdf/plugin-search/dist/react/index.js","../../../../node_modules/@embedpdf/plugin-selection/dist/index.js","../../../../node_modules/@embedpdf/utils/dist/index.js","../../../../node_modules/@embedpdf/utils/dist/react/index.js","../../../../node_modules/@embedpdf/plugin-selection/dist/react/index.js","../../../../node_modules/@embedpdf/plugin-interaction-manager/dist/index.js","../../../../node_modules/@embedpdf/plugin-interaction-manager/dist/react/index.js","../../../../node_modules/@embedpdf/plugin-rotate/dist/index.js","../../../../node_modules/@embedpdf/plugin-rotate/dist/react/index.js","../../../../node_modules/@embedpdf/plugin-pan/dist/index.js","../../../../node_modules/@embedpdf/plugin-pan/dist/react/index.js","../../../../node_modules/@embedpdf/plugin-thumbnail/dist/index.js","../../../../node_modules/@embedpdf/plugin-thumbnail/dist/react/index.js","../../../../node_modules/@embedpdf/plugin-print/dist/index.js","../../../../node_modules/@embedpdf/plugin-print/dist/react/index.js","../../../../node_modules/@embedpdf/pdfium/dist/pdfium.wasm?url","../../src/components/PDFPreviewPanel.tsx"],"sourcesContent":["/**\n * @license lucide-react v1.67.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.mjs';\n\nconst __iconData = {\n name: \"hand\",\n size: 24,\n node: [\n [\"path\", { d: \"M18 11V6a2 2 0 0 0-2-2a2 2 0 0 0-2 2\", key: \"1fvzgz\" }],\n [\"path\", { d: \"M14 10V4a2 2 0 0 0-2-2a2 2 0 0 0-2 2v2\", key: \"1kc0my\" }],\n [\"path\", { d: \"M10 10.5V6a2 2 0 0 0-2-2a2 2 0 0 0-2 2v8\", key: \"10h0bg\" }],\n [\n \"path\",\n {\n d: \"M18 8a2 2 0 1 1 4 0v6a8 8 0 0 1-8 8h-2c-2.8 0-4.5-.86-5.99-2.34l-3.6-3.6a2 2 0 0 1 2.83-2.82L7 15\",\n key: \"1s1gnw\"\n }\n ]\n ]\n};\n__iconData.node;\nconst Hand = createLucideIcon(__iconData);\n\nexport { __iconData, Hand as default };\n//# sourceMappingURL=hand.mjs.map\n","/**\n * @license lucide-react v1.67.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.mjs';\n\nconst __iconData = {\n name: \"maximize-2\",\n size: 24,\n node: [\n [\"path\", { d: \"M15 3h6v6\", key: \"1q9fwt\" }],\n [\"path\", { d: \"m21 3-7 7\", key: \"1l2asr\" }],\n [\"path\", { d: \"m3 21 7-7\", key: \"tjx5ai\" }],\n [\"path\", { d: \"M9 21H3v-6\", key: \"wtvkvv\" }]\n ]\n};\n__iconData.node;\nconst Maximize2 = createLucideIcon(__iconData);\n\nexport { __iconData, Maximize2 as default };\n//# sourceMappingURL=maximize-2.mjs.map\n","/**\n * @license lucide-react v1.67.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.mjs';\n\nconst __iconData = {\n name: \"minimize-2\",\n size: 24,\n node: [\n [\"path\", { d: \"m14 10 7-7\", key: \"oa77jy\" }],\n [\"path\", { d: \"M20 10h-6V4\", key: \"mjg0md\" }],\n [\"path\", { d: \"m3 21 7-7\", key: \"tjx5ai\" }],\n [\"path\", { d: \"M4 14h6v6\", key: \"rmj7iw\" }]\n ]\n};\n__iconData.node;\nconst Minimize2 = createLucideIcon(__iconData);\n\nexport { __iconData, Minimize2 as default };\n//# sourceMappingURL=minimize-2.mjs.map\n","/**\n * @license lucide-react v1.67.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.mjs';\n\nconst __iconData = {\n name: \"panel-left\",\n size: 24,\n node: [\n [\"rect\", { width: \"18\", height: \"18\", x: \"3\", y: \"3\", rx: \"2\", key: \"afitv7\" }],\n [\"path\", { d: \"M9 3v18\", key: \"fh3hqa\" }]\n ],\n aliases: [\"sidebar\"]\n};\n__iconData.node;\nconst PanelLeft = createLucideIcon(__iconData);\n\nexport { __iconData, PanelLeft as default };\n//# sourceMappingURL=panel-left.mjs.map\n","/**\n * @license lucide-react v1.67.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.mjs';\n\nconst __iconData = {\n name: \"printer\",\n size: 24,\n node: [\n [\n \"path\",\n {\n d: \"M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2\",\n key: \"143wyd\"\n }\n ],\n [\"path\", { d: \"M6 9V3a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v6\", key: \"1itne7\" }],\n [\"rect\", { x: \"6\", y: \"14\", width: \"12\", height: \"8\", rx: \"1\", key: \"1ue0tg\" }]\n ]\n};\n__iconData.node;\nconst Printer = createLucideIcon(__iconData);\n\nexport { __iconData, Printer as default };\n//# sourceMappingURL=printer.mjs.map\n","// EmbedPDF's UUID fallback needs bytes, not the Node crypto API or a Buffer.\nexport function randomBytes(size) {\n const bytes = new Uint8Array(size);\n for (let offset = 0; offset < size; offset += 65536) {\n globalThis.crypto.getRandomValues(bytes.subarray(offset, offset + 65536));\n }\n return bytes;\n}\n","var Rotation = /* @__PURE__ */ ((Rotation2) => {\n Rotation2[Rotation2[\"Degree0\"] = 0] = \"Degree0\";\n Rotation2[Rotation2[\"Degree90\"] = 1] = \"Degree90\";\n Rotation2[Rotation2[\"Degree180\"] = 2] = \"Degree180\";\n Rotation2[Rotation2[\"Degree270\"] = 3] = \"Degree270\";\n return Rotation2;\n})(Rotation || {});\nfunction toIntPos(p) {\n return { x: Math.floor(p.x), y: Math.floor(p.y) };\n}\nfunction toIntSize(s) {\n return { width: Math.ceil(s.width), height: Math.ceil(s.height) };\n}\nfunction toIntRect(r) {\n return {\n origin: toIntPos(r.origin),\n size: toIntSize(r.size)\n };\n}\nfunction calculateDegree(rotation) {\n switch (rotation) {\n case 0:\n return 0;\n case 1:\n return 90;\n case 2:\n return 180;\n case 3:\n return 270;\n }\n}\nfunction calculateAngle(rotation) {\n return calculateDegree(rotation) * Math.PI / 180;\n}\nfunction swap(size) {\n const { width, height } = size;\n return {\n width: height,\n height: width\n };\n}\nfunction transformSize(size, rotation, scaleFactor) {\n size = rotation % 2 === 0 ? size : swap(size);\n return {\n width: size.width * scaleFactor,\n height: size.height * scaleFactor\n };\n}\nfunction quadToRect(q) {\n const xs = [q.p1.x, q.p2.x, q.p3.x, q.p4.x];\n const ys = [q.p1.y, q.p2.y, q.p3.y, q.p4.y];\n return {\n origin: { x: Math.min(...xs), y: Math.min(...ys) },\n size: {\n width: Math.max(...xs) - Math.min(...xs),\n height: Math.max(...ys) - Math.min(...ys)\n }\n };\n}\nfunction rectToQuad(r) {\n return {\n p1: { x: r.origin.x, y: r.origin.y },\n p2: { x: r.origin.x + r.size.width, y: r.origin.y },\n p3: { x: r.origin.x + r.size.width, y: r.origin.y + r.size.height },\n p4: { x: r.origin.x, y: r.origin.y + r.size.height }\n };\n}\nfunction rotatePosition(containerSize, position, rotation) {\n let x = position.x;\n let y = position.y;\n switch (rotation) {\n case 0:\n x = position.x;\n y = position.y;\n break;\n case 1:\n x = containerSize.height - position.y;\n y = position.x;\n break;\n case 2:\n x = containerSize.width - position.x;\n y = containerSize.height - position.y;\n break;\n case 3:\n x = position.y;\n y = containerSize.width - position.x;\n break;\n }\n return {\n x,\n y\n };\n}\nfunction scalePosition(position, scaleFactor) {\n return {\n x: position.x * scaleFactor,\n y: position.y * scaleFactor\n };\n}\nfunction transformPosition(containerSize, position, rotation, scaleFactor) {\n return scalePosition(rotatePosition(containerSize, position, rotation), scaleFactor);\n}\nfunction restorePosition(containerSize, position, rotation, scaleFactor) {\n return scalePosition(\n rotatePosition(containerSize, position, (4 - rotation) % 4),\n 1 / scaleFactor\n );\n}\nfunction rectEquals(a, b) {\n return a.origin.x === b.origin.x && a.origin.y === b.origin.y && a.size.width === b.size.width && a.size.height === b.size.height;\n}\nfunction rectFromPoints(positions) {\n if (positions.length === 0) {\n return { origin: { x: 0, y: 0 }, size: { width: 0, height: 0 } };\n }\n const xs = positions.map((p) => p.x);\n const ys = positions.map((p) => p.y);\n const minX = Math.min(...xs);\n const minY = Math.min(...ys);\n return {\n origin: { x: minX, y: minY },\n size: {\n width: Math.max(...xs) - minX,\n height: Math.max(...ys) - minY\n }\n };\n}\nfunction rotateAndTranslatePoint(pos, angleRad, translate) {\n const cos = Math.cos(angleRad);\n const sin = Math.sin(angleRad);\n const newX = pos.x * cos - pos.y * sin;\n const newY = pos.x * sin + pos.y * cos;\n return {\n x: newX + translate.x,\n y: newY + translate.y\n };\n}\nfunction expandRect(rect, padding) {\n return {\n origin: { x: rect.origin.x - padding, y: rect.origin.y - padding },\n size: { width: rect.size.width + padding * 2, height: rect.size.height + padding * 2 }\n };\n}\nfunction rotateRect(containerSize, rect, rotation) {\n let x = rect.origin.x;\n let y = rect.origin.y;\n let size = rect.size;\n switch (rotation) {\n case 0:\n break;\n case 1:\n x = containerSize.height - rect.origin.y - rect.size.height;\n y = rect.origin.x;\n size = swap(rect.size);\n break;\n case 2:\n x = containerSize.width - rect.origin.x - rect.size.width;\n y = containerSize.height - rect.origin.y - rect.size.height;\n break;\n case 3:\n x = rect.origin.y;\n y = containerSize.width - rect.origin.x - rect.size.width;\n size = swap(rect.size);\n break;\n }\n return {\n origin: {\n x,\n y\n },\n size: {\n width: size.width,\n height: size.height\n }\n };\n}\nfunction scaleRect(rect, scaleFactor) {\n return {\n origin: {\n x: rect.origin.x * scaleFactor,\n y: rect.origin.y * scaleFactor\n },\n size: {\n width: rect.size.width * scaleFactor,\n height: rect.size.height * scaleFactor\n }\n };\n}\nfunction transformRect(containerSize, rect, rotation, scaleFactor) {\n return scaleRect(rotateRect(containerSize, rect, rotation), scaleFactor);\n}\nfunction restoreRect(containerSize, rect, rotation, scaleFactor) {\n return scaleRect(rotateRect(containerSize, rect, (4 - rotation) % 4), 1 / scaleFactor);\n}\nfunction restoreOffset(offset, rotation, scaleFactor) {\n let offsetX = offset.x;\n let offsetY = offset.y;\n switch (rotation) {\n case 0:\n offsetX = offset.x / scaleFactor;\n offsetY = offset.y / scaleFactor;\n break;\n case 1:\n offsetX = offset.y / scaleFactor;\n offsetY = -offset.x / scaleFactor;\n break;\n case 2:\n offsetX = -offset.x / scaleFactor;\n offsetY = -offset.y / scaleFactor;\n break;\n case 3:\n offsetX = -offset.y / scaleFactor;\n offsetY = offset.x / scaleFactor;\n break;\n }\n return {\n x: offsetX,\n y: offsetY\n };\n}\nconst EMPTY_RECT = { origin: { x: 0, y: 0 }, size: { width: 0, height: 0 } };\nfunction boundingRect(rects) {\n if (rects.length === 0) return null;\n let minX = rects[0].origin.x, minY = rects[0].origin.y, maxX = rects[0].origin.x + rects[0].size.width, maxY = rects[0].origin.y + rects[0].size.height;\n for (const r of rects) {\n minX = Math.min(minX, r.origin.x);\n minY = Math.min(minY, r.origin.y);\n maxX = Math.max(maxX, r.origin.x + r.size.width);\n maxY = Math.max(maxY, r.origin.y + r.size.height);\n }\n return {\n origin: {\n x: minX,\n y: minY\n },\n size: {\n width: maxX - minX,\n height: maxY - minY\n }\n };\n}\nfunction boundingRectOrEmpty(rects) {\n return boundingRect(rects) ?? EMPTY_RECT;\n}\nfunction normalizeAngle(degrees) {\n const normalized = degrees % 360;\n return normalized < 0 ? normalized + 360 : normalized;\n}\nfunction getRectCenter(rect) {\n return {\n x: rect.origin.x + rect.size.width / 2,\n y: rect.origin.y + rect.size.height / 2\n };\n}\nfunction rotatePointAround(point, center, angleDegrees) {\n const angleRad = angleDegrees * Math.PI / 180;\n const cos = Math.cos(angleRad);\n const sin = Math.sin(angleRad);\n const dx = point.x - center.x;\n const dy = point.y - center.y;\n return {\n x: center.x + dx * cos - dy * sin,\n y: center.y + dx * sin + dy * cos\n };\n}\nfunction rotateVertices(points, center, angleDegrees) {\n return points.map((v) => rotatePointAround(v, center, angleDegrees));\n}\nfunction calculateRotatedRectAABBAroundPoint(rect, angleDegrees, center) {\n const corners = [\n { x: rect.origin.x, y: rect.origin.y },\n { x: rect.origin.x + rect.size.width, y: rect.origin.y },\n { x: rect.origin.x + rect.size.width, y: rect.origin.y + rect.size.height },\n { x: rect.origin.x, y: rect.origin.y + rect.size.height }\n ];\n const rotated = rotateVertices(corners, center, angleDegrees);\n return rectFromPoints(rotated);\n}\nfunction calculateRotatedRectAABB(unrotatedRect, angleDegrees) {\n return calculateRotatedRectAABBAroundPoint(\n unrotatedRect,\n angleDegrees,\n getRectCenter(unrotatedRect)\n );\n}\nfunction inferRotationCenterFromRects(unrotatedRect, rotatedAabb, angleDegrees) {\n const angleRad = angleDegrees * Math.PI / 180;\n const cos = Math.cos(angleRad);\n const sin = Math.sin(angleRad);\n const m00 = 1 - cos;\n const m01 = sin;\n const m10 = -sin;\n const m11 = 1 - cos;\n const det = m00 * m11 - m01 * m10;\n const unrotatedCenter = getRectCenter(unrotatedRect);\n if (Math.abs(det) < 1e-10) return unrotatedCenter;\n const rotatedCenter = getRectCenter(rotatedAabb);\n const rhsX = rotatedCenter.x - (cos * unrotatedCenter.x - sin * unrotatedCenter.y);\n const rhsY = rotatedCenter.y - (sin * unrotatedCenter.x + cos * unrotatedCenter.y);\n return {\n x: (m11 * rhsX - m01 * rhsY) / det,\n y: (-m10 * rhsX + m00 * rhsY) / det\n };\n}\nfunction buildUserToDeviceMatrix(rect, rotation, outW, outH) {\n const L = rect.origin.x;\n const B = rect.origin.y;\n const W = rect.size.width;\n const H = rect.size.height;\n const sx0 = outW / W;\n const sy0 = outH / H;\n const sx90 = outW / H;\n const sy90 = outH / W;\n switch (rotation) {\n case 0:\n return { a: sx0, b: 0, c: 0, d: sy0, e: -sx0 * L, f: -sy0 * B };\n case 3:\n return { a: 0, b: -sy90, c: sx90, d: 0, e: -sx90 * B, f: sy90 * (L + W) };\n case 2:\n return { a: -sx0, b: 0, c: 0, d: -sy0, e: sx0 * (L + W), f: sy0 * (B + H) };\n case 1:\n return { a: 0, b: sy90, c: -sx90, d: 0, e: sx90 * (B + H), f: -sy90 * L };\n }\n}\nfunction fitSizeWithin(size, bounds) {\n const scale = Math.min(bounds.width / size.width, bounds.height / size.height, 1);\n return { width: size.width * scale, height: size.height * scale };\n}\nclass NoopLogger {\n /** {@inheritDoc Logger.isEnabled} */\n isEnabled() {\n return false;\n }\n /** {@inheritDoc Logger.debug} */\n debug() {\n }\n /** {@inheritDoc Logger.info} */\n info() {\n }\n /** {@inheritDoc Logger.warn} */\n warn() {\n }\n /** {@inheritDoc Logger.error} */\n error() {\n }\n /** {@inheritDoc Logger.perf} */\n perf() {\n }\n}\nclass ConsoleLogger {\n /** {@inheritDoc Logger.isEnabled} */\n isEnabled() {\n return true;\n }\n /** {@inheritDoc Logger.debug} */\n debug(source, category, ...args) {\n console.debug(`${source}.${category}`, ...args);\n }\n /** {@inheritDoc Logger.info} */\n info(source, category, ...args) {\n console.info(`${source}.${category}`, ...args);\n }\n /** {@inheritDoc Logger.warn} */\n warn(source, category, ...args) {\n console.warn(`${source}.${category}`, ...args);\n }\n /** {@inheritDoc Logger.error} */\n error(source, category, ...args) {\n console.error(`${source}.${category}`, ...args);\n }\n /** {@inheritDoc Logger.perf} */\n perf(source, category, event, phase, ...args) {\n console.info(`${source}.${category}.${event}.${phase}`, ...args);\n }\n}\nvar LogLevel = /* @__PURE__ */ ((LogLevel2) => {\n LogLevel2[LogLevel2[\"Debug\"] = 0] = \"Debug\";\n LogLevel2[LogLevel2[\"Info\"] = 1] = \"Info\";\n LogLevel2[LogLevel2[\"Warn\"] = 2] = \"Warn\";\n LogLevel2[LogLevel2[\"Error\"] = 3] = \"Error\";\n return LogLevel2;\n})(LogLevel || {});\nclass LevelLogger {\n /**\n * create new LevelLogger\n * @param logger - the original logger\n * @param level - log level that used for filtering, all logs lower than this level will be filtered out\n */\n constructor(logger, level) {\n this.logger = logger;\n this.level = level;\n }\n /** {@inheritDoc Logger.isEnabled} */\n isEnabled(level) {\n const levelMap = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3\n /* Error */\n };\n return this.level <= levelMap[level];\n }\n /** {@inheritDoc Logger.debug} */\n debug(source, category, ...args) {\n if (this.level <= 0) {\n this.logger.debug(source, category, ...args);\n }\n }\n /** {@inheritDoc Logger.info} */\n info(source, category, ...args) {\n if (this.level <= 1) {\n this.logger.info(source, category, ...args);\n }\n }\n /** {@inheritDoc Logger.warn} */\n warn(source, category, ...args) {\n if (this.level <= 2) {\n this.logger.warn(source, category, ...args);\n }\n }\n /** {@inheritDoc Logger.error} */\n error(source, category, ...args) {\n if (this.level <= 3) {\n this.logger.error(source, category, ...args);\n }\n }\n /** {@inheritDoc Logger.perf} */\n perf(source, category, event, phase, ...args) {\n this.logger.perf(source, category, event, phase, ...args);\n }\n}\nclass PerfLogger {\n /**\n * create new PerfLogger\n */\n constructor() {\n this.marks = /* @__PURE__ */ new Map();\n }\n /** {@inheritDoc Logger.isEnabled} */\n isEnabled() {\n return false;\n }\n /** {@inheritDoc Logger.debug} */\n debug(source, category, ...args) {\n }\n /** {@inheritDoc Logger.info} */\n info(source, category, ...args) {\n }\n /** {@inheritDoc Logger.warn} */\n warn(source, category, ...args) {\n }\n /** {@inheritDoc Logger.error} */\n error(source, category, ...args) {\n }\n /** {@inheritDoc Logger.perf} */\n perf(source, category, event, phase, identifier, ...args) {\n const markName = `${source}.${category}.${event}.${phase}.${identifier}`;\n switch (phase) {\n case \"Begin\":\n globalThis.performance.mark(markName, { detail: args });\n this.marks.set(`${source}.${category}.${event}.${identifier}`, Date.now());\n break;\n case \"End\":\n globalThis.performance.mark(markName, { detail: args });\n const measureName = `${source}.${category}.${event}.Measure.${identifier}`;\n const beginMark = `${source}.${category}.${event}.Begin.${identifier}`;\n globalThis.performance.measure(measureName, beginMark, markName);\n const startTime = this.marks.get(`${source}.${category}.${event}.${identifier}`);\n if (startTime) {\n const duration = Date.now() - startTime;\n console.info(`⏱️ ${source}.${category}.${event}.${identifier}: ${duration}ms`);\n this.marks.delete(`${source}.${category}.${event}.${identifier}`);\n }\n break;\n }\n }\n}\nclass AllLogger {\n /**\n * create new PerfLogger\n */\n constructor(loggers) {\n this.loggers = loggers;\n }\n /** {@inheritDoc Logger.isEnabled} */\n isEnabled(level) {\n return this.loggers.some((logger) => logger.isEnabled(level));\n }\n /** {@inheritDoc Logger.debug} */\n debug(source, category, ...args) {\n for (const logger of this.loggers) {\n logger.debug(source, category, ...args);\n }\n }\n /** {@inheritDoc Logger.info} */\n info(source, category, ...args) {\n for (const logger of this.loggers) {\n logger.info(source, category, ...args);\n }\n }\n /** {@inheritDoc Logger.warn} */\n warn(source, category, ...args) {\n for (const logger of this.loggers) {\n logger.warn(source, category, ...args);\n }\n }\n /** {@inheritDoc Logger.error} */\n error(source, category, ...args) {\n for (const logger of this.loggers) {\n logger.error(source, category, ...args);\n }\n }\n /** {@inheritDoc Logger.perf} */\n perf(source, category, event, phase, ...args) {\n for (const logger of this.loggers) {\n logger.perf(source, category, event, phase, ...args);\n }\n }\n}\nvar TaskStage = /* @__PURE__ */ ((TaskStage2) => {\n TaskStage2[TaskStage2[\"Pending\"] = 0] = \"Pending\";\n TaskStage2[TaskStage2[\"Resolved\"] = 1] = \"Resolved\";\n TaskStage2[TaskStage2[\"Rejected\"] = 2] = \"Rejected\";\n TaskStage2[TaskStage2[\"Aborted\"] = 3] = \"Aborted\";\n return TaskStage2;\n})(TaskStage || {});\nclass TaskAbortedError extends Error {\n constructor(reason) {\n super(`Task aborted: ${JSON.stringify(reason)}`);\n this.name = \"TaskAbortedError\";\n this.reason = reason;\n }\n}\nclass TaskRejectedError extends Error {\n constructor(reason) {\n super(`Task rejected: ${JSON.stringify(reason)}`);\n this.name = \"TaskRejectedError\";\n this.reason = reason;\n }\n}\nclass Task {\n constructor() {\n this.state = {\n stage: 0\n /* Pending */\n };\n this.resolvedCallbacks = [];\n this.rejectedCallbacks = [];\n this._promise = null;\n this.progressCbs = [];\n }\n /**\n * Convert task to promise\n * @returns promise that will be resolved when task is settled\n */\n toPromise() {\n if (!this._promise) {\n this._promise = new Promise((resolve, reject) => {\n this.wait(\n (result) => resolve(result),\n (error) => {\n if (error.type === \"abort\") {\n reject(new TaskAbortedError(error.reason));\n } else {\n reject(new TaskRejectedError(error.reason));\n }\n }\n );\n });\n }\n return this._promise;\n }\n /**\n * wait for task to be settled\n * @param resolvedCallback - callback for resolved value\n * @param rejectedCallback - callback for rejected value\n */\n wait(resolvedCallback, rejectedCallback) {\n switch (this.state.stage) {\n case 0:\n this.resolvedCallbacks.push(resolvedCallback);\n this.rejectedCallbacks.push(rejectedCallback);\n break;\n case 1:\n resolvedCallback(this.state.result);\n break;\n case 2:\n rejectedCallback({\n type: \"reject\",\n reason: this.state.reason\n });\n break;\n case 3:\n rejectedCallback({\n type: \"abort\",\n reason: this.state.reason\n });\n break;\n }\n }\n /**\n * resolve task with specific result\n * @param result - result value\n */\n resolve(result) {\n if (this.state.stage === 0) {\n this.state = {\n stage: 1,\n result\n };\n for (const resolvedCallback of this.resolvedCallbacks) {\n try {\n resolvedCallback(result);\n } catch (e) {\n }\n }\n this.resolvedCallbacks = [];\n this.rejectedCallbacks = [];\n }\n }\n /**\n * reject task with specific reason\n * @param reason - abort reason\n *\n */\n reject(reason) {\n if (this.state.stage === 0) {\n this.state = {\n stage: 2,\n reason\n };\n for (const rejectedCallback of this.rejectedCallbacks) {\n try {\n rejectedCallback({\n type: \"reject\",\n reason\n });\n } catch (e) {\n }\n }\n this.resolvedCallbacks = [];\n this.rejectedCallbacks = [];\n }\n }\n /**\n * abort task with specific reason\n * @param reason - abort reason\n */\n abort(reason) {\n if (this.state.stage === 0) {\n this.state = {\n stage: 3,\n reason\n };\n for (const rejectedCallback of this.rejectedCallbacks) {\n try {\n rejectedCallback({\n type: \"abort\",\n reason\n });\n } catch (e) {\n }\n }\n this.resolvedCallbacks = [];\n this.rejectedCallbacks = [];\n }\n }\n /**\n * fail task with a TaskError from another task\n * This is a convenience method for error propagation between tasks\n * @param error - TaskError from another task\n */\n fail(error) {\n if (error.type === \"abort\") {\n this.abort(error.reason);\n } else {\n this.reject(error.reason);\n }\n }\n /**\n * add a progress callback\n * @param cb - progress callback\n */\n onProgress(cb) {\n this.progressCbs.push(cb);\n }\n /**\n * call progress callback\n * @param p - progress value\n */\n progress(p) {\n for (const cb of this.progressCbs) cb(p);\n }\n /**\n * Static method to wait for all tasks to resolve\n * Returns a new task that resolves with an array of all results\n * Rejects immediately if any task fails\n *\n * @param tasks - array of tasks to wait for\n * @returns new task that resolves when all input tasks resolve\n * @public\n */\n static all(tasks) {\n const combinedTask = new Task();\n if (tasks.length === 0) {\n combinedTask.resolve([]);\n return combinedTask;\n }\n const results = new Array(tasks.length);\n let resolvedCount = 0;\n let isSettled = false;\n tasks.forEach((task, index) => {\n task.wait(\n (result) => {\n if (isSettled) return;\n results[index] = result;\n resolvedCount++;\n if (resolvedCount === tasks.length) {\n isSettled = true;\n combinedTask.resolve(results);\n }\n },\n (error) => {\n if (isSettled) return;\n isSettled = true;\n if (error.type === \"abort\") {\n combinedTask.abort(error.reason);\n } else {\n combinedTask.reject(error.reason);\n }\n }\n );\n });\n return combinedTask;\n }\n /**\n * Static method to wait for all tasks to settle (resolve, reject, or abort)\n * Always resolves with an array of settlement results\n *\n * @param tasks - array of tasks to wait for\n * @returns new task that resolves when all input tasks settle\n * @public\n */\n static allSettled(tasks) {\n const combinedTask = new Task();\n if (tasks.length === 0) {\n combinedTask.resolve([]);\n return combinedTask;\n }\n const results = new Array(tasks.length);\n let settledCount = 0;\n tasks.forEach((task, index) => {\n task.wait(\n (result) => {\n results[index] = { status: \"resolved\", value: result };\n settledCount++;\n if (settledCount === tasks.length) {\n combinedTask.resolve(results);\n }\n },\n (error) => {\n results[index] = {\n status: error.type === \"abort\" ? \"aborted\" : \"rejected\",\n reason: error.reason\n };\n settledCount++;\n if (settledCount === tasks.length) {\n combinedTask.resolve(results);\n }\n }\n );\n });\n return combinedTask;\n }\n /**\n * Static method that resolves/rejects with the first task that settles\n *\n * @param tasks - array of tasks to race\n * @returns new task that settles with the first input task that settles\n * @public\n */\n static race(tasks) {\n const combinedTask = new Task();\n if (tasks.length === 0) {\n combinedTask.reject(\"No tasks provided\");\n return combinedTask;\n }\n let isSettled = false;\n tasks.forEach((task) => {\n task.wait(\n (result) => {\n if (isSettled) return;\n isSettled = true;\n combinedTask.resolve(result);\n },\n (error) => {\n if (isSettled) return;\n isSettled = true;\n if (error.type === \"abort\") {\n combinedTask.abort(error.reason);\n } else {\n combinedTask.reject(error.reason);\n }\n }\n );\n });\n return combinedTask;\n }\n /**\n * Utility to track progress of multiple tasks\n *\n * @param tasks - array of tasks to track\n * @param onProgress - callback called when any task completes\n * @returns new task that resolves when all input tasks resolve\n * @public\n */\n static withProgress(tasks, onProgress) {\n const combinedTask = Task.all(tasks);\n if (onProgress) {\n let completedCount = 0;\n tasks.forEach((task) => {\n task.wait(\n () => {\n completedCount++;\n onProgress(completedCount, tasks.length);\n },\n () => {\n completedCount++;\n onProgress(completedCount, tasks.length);\n }\n );\n });\n }\n return combinedTask;\n }\n}\nconst PdfSoftHyphenMarker = \"­\";\nconst PdfZeroWidthSpace = \"​\";\nconst PdfWordJoiner = \"⁠\";\nconst PdfBomOrZwnbsp = \"\\uFEFF\";\nconst PdfNonCharacterFFFE = \"￾\";\nconst PdfNonCharacterFFFF = \"￿\";\nconst PdfUnwantedTextMarkers = Object.freeze([\n PdfSoftHyphenMarker,\n PdfZeroWidthSpace,\n PdfWordJoiner,\n PdfBomOrZwnbsp,\n PdfNonCharacterFFFE,\n PdfNonCharacterFFFF\n]);\nconst PdfUnwantedTextRegex = new RegExp(`[${PdfUnwantedTextMarkers.join(\"\")}]`, \"g\");\nfunction stripPdfUnwantedMarkers(text) {\n return text.replace(PdfUnwantedTextRegex, \"\");\n}\nvar PdfZoomMode = /* @__PURE__ */ ((PdfZoomMode2) => {\n PdfZoomMode2[PdfZoomMode2[\"Unknown\"] = 0] = \"Unknown\";\n PdfZoomMode2[PdfZoomMode2[\"XYZ\"] = 1] = \"XYZ\";\n PdfZoomMode2[PdfZoomMode2[\"FitPage\"] = 2] = \"FitPage\";\n PdfZoomMode2[PdfZoomMode2[\"FitHorizontal\"] = 3] = \"FitHorizontal\";\n PdfZoomMode2[PdfZoomMode2[\"FitVertical\"] = 4] = \"FitVertical\";\n PdfZoomMode2[PdfZoomMode2[\"FitRectangle\"] = 5] = \"FitRectangle\";\n PdfZoomMode2[PdfZoomMode2[\"FitBoundingBox\"] = 6] = \"FitBoundingBox\";\n PdfZoomMode2[PdfZoomMode2[\"FitBoundingBoxHorizontal\"] = 7] = \"FitBoundingBoxHorizontal\";\n PdfZoomMode2[PdfZoomMode2[\"FitBoundingBoxVertical\"] = 8] = \"FitBoundingBoxVertical\";\n return PdfZoomMode2;\n})(PdfZoomMode || {});\nvar PdfTrappedStatus = /* @__PURE__ */ ((PdfTrappedStatus2) => {\n PdfTrappedStatus2[PdfTrappedStatus2[\"NotSet\"] = 0] = \"NotSet\";\n PdfTrappedStatus2[PdfTrappedStatus2[\"True\"] = 1] = \"True\";\n PdfTrappedStatus2[PdfTrappedStatus2[\"False\"] = 2] = \"False\";\n PdfTrappedStatus2[PdfTrappedStatus2[\"Unknown\"] = 3] = \"Unknown\";\n return PdfTrappedStatus2;\n})(PdfTrappedStatus || {});\nvar PdfStandardFont = /* @__PURE__ */ ((PdfStandardFont2) => {\n PdfStandardFont2[PdfStandardFont2[\"Unknown\"] = -1] = \"Unknown\";\n PdfStandardFont2[PdfStandardFont2[\"Courier\"] = 0] = \"Courier\";\n PdfStandardFont2[PdfStandardFont2[\"Courier_Bold\"] = 1] = \"Courier_Bold\";\n PdfStandardFont2[PdfStandardFont2[\"Courier_BoldOblique\"] = 2] = \"Courier_BoldOblique\";\n PdfStandardFont2[PdfStandardFont2[\"Courier_Oblique\"] = 3] = \"Courier_Oblique\";\n PdfStandardFont2[PdfStandardFont2[\"Helvetica\"] = 4] = \"Helvetica\";\n PdfStandardFont2[PdfStandardFont2[\"Helvetica_Bold\"] = 5] = \"Helvetica_Bold\";\n PdfStandardFont2[PdfStandardFont2[\"Helvetica_BoldOblique\"] = 6] = \"Helvetica_BoldOblique\";\n PdfStandardFont2[PdfStandardFont2[\"Helvetica_Oblique\"] = 7] = \"Helvetica_Oblique\";\n PdfStandardFont2[PdfStandardFont2[\"Times_Roman\"] = 8] = \"Times_Roman\";\n PdfStandardFont2[PdfStandardFont2[\"Times_Bold\"] = 9] = \"Times_Bold\";\n PdfStandardFont2[PdfStandardFont2[\"Times_BoldItalic\"] = 10] = \"Times_BoldItalic\";\n PdfStandardFont2[PdfStandardFont2[\"Times_Italic\"] = 11] = \"Times_Italic\";\n PdfStandardFont2[PdfStandardFont2[\"Symbol\"] = 12] = \"Symbol\";\n PdfStandardFont2[PdfStandardFont2[\"ZapfDingbats\"] = 13] = \"ZapfDingbats\";\n return PdfStandardFont2;\n})(PdfStandardFont || {});\nvar PdfTextAlignment = /* @__PURE__ */ ((PdfTextAlignment2) => {\n PdfTextAlignment2[PdfTextAlignment2[\"Left\"] = 0] = \"Left\";\n PdfTextAlignment2[PdfTextAlignment2[\"Center\"] = 1] = \"Center\";\n PdfTextAlignment2[PdfTextAlignment2[\"Right\"] = 2] = \"Right\";\n return PdfTextAlignment2;\n})(PdfTextAlignment || {});\nvar PdfVerticalAlignment = /* @__PURE__ */ ((PdfVerticalAlignment2) => {\n PdfVerticalAlignment2[PdfVerticalAlignment2[\"Top\"] = 0] = \"Top\";\n PdfVerticalAlignment2[PdfVerticalAlignment2[\"Middle\"] = 1] = \"Middle\";\n PdfVerticalAlignment2[PdfVerticalAlignment2[\"Bottom\"] = 2] = \"Bottom\";\n return PdfVerticalAlignment2;\n})(PdfVerticalAlignment || {});\nvar PdfBlendMode = /* @__PURE__ */ ((PdfBlendMode2) => {\n PdfBlendMode2[PdfBlendMode2[\"Normal\"] = 0] = \"Normal\";\n PdfBlendMode2[PdfBlendMode2[\"Multiply\"] = 1] = \"Multiply\";\n PdfBlendMode2[PdfBlendMode2[\"Screen\"] = 2] = \"Screen\";\n PdfBlendMode2[PdfBlendMode2[\"Overlay\"] = 3] = \"Overlay\";\n PdfBlendMode2[PdfBlendMode2[\"Darken\"] = 4] = \"Darken\";\n PdfBlendMode2[PdfBlendMode2[\"Lighten\"] = 5] = \"Lighten\";\n PdfBlendMode2[PdfBlendMode2[\"ColorDodge\"] = 6] = \"ColorDodge\";\n PdfBlendMode2[PdfBlendMode2[\"ColorBurn\"] = 7] = \"ColorBurn\";\n PdfBlendMode2[PdfBlendMode2[\"HardLight\"] = 8] = \"HardLight\";\n PdfBlendMode2[PdfBlendMode2[\"SoftLight\"] = 9] = \"SoftLight\";\n PdfBlendMode2[PdfBlendMode2[\"Difference\"] = 10] = \"Difference\";\n PdfBlendMode2[PdfBlendMode2[\"Exclusion\"] = 11] = \"Exclusion\";\n PdfBlendMode2[PdfBlendMode2[\"Hue\"] = 12] = \"Hue\";\n PdfBlendMode2[PdfBlendMode2[\"Saturation\"] = 13] = \"Saturation\";\n PdfBlendMode2[PdfBlendMode2[\"Color\"] = 14] = \"Color\";\n PdfBlendMode2[PdfBlendMode2[\"Luminosity\"] = 15] = \"Luminosity\";\n return PdfBlendMode2;\n})(PdfBlendMode || {});\nvar PdfStampFit = /* @__PURE__ */ ((PdfStampFit2) => {\n PdfStampFit2[PdfStampFit2[\"Contain\"] = 0] = \"Contain\";\n PdfStampFit2[PdfStampFit2[\"Cover\"] = 1] = \"Cover\";\n PdfStampFit2[PdfStampFit2[\"Stretch\"] = 2] = \"Stretch\";\n return PdfStampFit2;\n})(PdfStampFit || {});\nvar PdfActionType = /* @__PURE__ */ ((PdfActionType2) => {\n PdfActionType2[PdfActionType2[\"Unsupported\"] = 0] = \"Unsupported\";\n PdfActionType2[PdfActionType2[\"Goto\"] = 1] = \"Goto\";\n PdfActionType2[PdfActionType2[\"RemoteGoto\"] = 2] = \"RemoteGoto\";\n PdfActionType2[PdfActionType2[\"URI\"] = 3] = \"URI\";\n PdfActionType2[PdfActionType2[\"LaunchAppOrOpenFile\"] = 4] = \"LaunchAppOrOpenFile\";\n return PdfActionType2;\n})(PdfActionType || {});\nconst AP_MODE_NORMAL = 1;\nconst AP_MODE_ROLLOVER = 2;\nconst AP_MODE_DOWN = 4;\nvar PdfAnnotationSubtype = /* @__PURE__ */ ((PdfAnnotationSubtype2) => {\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"UNKNOWN\"] = 0] = \"UNKNOWN\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"TEXT\"] = 1] = \"TEXT\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"LINK\"] = 2] = \"LINK\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"FREETEXT\"] = 3] = \"FREETEXT\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"LINE\"] = 4] = \"LINE\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"SQUARE\"] = 5] = \"SQUARE\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"CIRCLE\"] = 6] = \"CIRCLE\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"POLYGON\"] = 7] = \"POLYGON\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"POLYLINE\"] = 8] = \"POLYLINE\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"HIGHLIGHT\"] = 9] = \"HIGHLIGHT\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"UNDERLINE\"] = 10] = \"UNDERLINE\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"SQUIGGLY\"] = 11] = \"SQUIGGLY\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"STRIKEOUT\"] = 12] = \"STRIKEOUT\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"STAMP\"] = 13] = \"STAMP\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"CARET\"] = 14] = \"CARET\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"INK\"] = 15] = \"INK\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"POPUP\"] = 16] = \"POPUP\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"FILEATTACHMENT\"] = 17] = \"FILEATTACHMENT\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"SOUND\"] = 18] = \"SOUND\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"MOVIE\"] = 19] = \"MOVIE\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"WIDGET\"] = 20] = \"WIDGET\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"SCREEN\"] = 21] = \"SCREEN\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"PRINTERMARK\"] = 22] = \"PRINTERMARK\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"TRAPNET\"] = 23] = \"TRAPNET\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"WATERMARK\"] = 24] = \"WATERMARK\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"THREED\"] = 25] = \"THREED\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"RICHMEDIA\"] = 26] = \"RICHMEDIA\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"XFAWIDGET\"] = 27] = \"XFAWIDGET\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"REDACT\"] = 28] = \"REDACT\";\n return PdfAnnotationSubtype2;\n})(PdfAnnotationSubtype || {});\nconst PdfAnnotationSubtypeName = {\n [\n 0\n /* UNKNOWN */\n ]: \"unknow\",\n [\n 1\n /* TEXT */\n ]: \"text\",\n [\n 2\n /* LINK */\n ]: \"link\",\n [\n 3\n /* FREETEXT */\n ]: \"freetext\",\n [\n 4\n /* LINE */\n ]: \"line\",\n [\n 5\n /* SQUARE */\n ]: \"square\",\n [\n 6\n /* CIRCLE */\n ]: \"circle\",\n [\n 7\n /* POLYGON */\n ]: \"polygon\",\n [\n 8\n /* POLYLINE */\n ]: \"polyline\",\n [\n 9\n /* HIGHLIGHT */\n ]: \"highlight\",\n [\n 10\n /* UNDERLINE */\n ]: \"underline\",\n [\n 11\n /* SQUIGGLY */\n ]: \"squiggly\",\n [\n 12\n /* STRIKEOUT */\n ]: \"strikeout\",\n [\n 13\n /* STAMP */\n ]: \"stamp\",\n [\n 14\n /* CARET */\n ]: \"caret\",\n [\n 15\n /* INK */\n ]: \"ink\",\n [\n 16\n /* POPUP */\n ]: \"popup\",\n [\n 17\n /* FILEATTACHMENT */\n ]: \"fileattachment\",\n [\n 18\n /* SOUND */\n ]: \"sound\",\n [\n 19\n /* MOVIE */\n ]: \"movie\",\n [\n 20\n /* WIDGET */\n ]: \"widget\",\n [\n 21\n /* SCREEN */\n ]: \"screen\",\n [\n 22\n /* PRINTERMARK */\n ]: \"printermark\",\n [\n 23\n /* TRAPNET */\n ]: \"trapnet\",\n [\n 24\n /* WATERMARK */\n ]: \"watermark\",\n [\n 25\n /* THREED */\n ]: \"threed\",\n [\n 26\n /* RICHMEDIA */\n ]: \"richmedia\",\n [\n 27\n /* XFAWIDGET */\n ]: \"xfawidget\",\n [\n 28\n /* REDACT */\n ]: \"redact\"\n};\nvar PdfAnnotationObjectStatus = /* @__PURE__ */ ((PdfAnnotationObjectStatus2) => {\n PdfAnnotationObjectStatus2[PdfAnnotationObjectStatus2[\"Created\"] = 0] = \"Created\";\n PdfAnnotationObjectStatus2[PdfAnnotationObjectStatus2[\"Committed\"] = 1] = \"Committed\";\n return PdfAnnotationObjectStatus2;\n})(PdfAnnotationObjectStatus || {});\nvar AppearanceMode = /* @__PURE__ */ ((AppearanceMode2) => {\n AppearanceMode2[AppearanceMode2[\"Normal\"] = 0] = \"Normal\";\n AppearanceMode2[AppearanceMode2[\"Rollover\"] = 1] = \"Rollover\";\n AppearanceMode2[AppearanceMode2[\"Down\"] = 2] = \"Down\";\n return AppearanceMode2;\n})(AppearanceMode || {});\nvar PdfAnnotationState = /* @__PURE__ */ ((PdfAnnotationState2) => {\n PdfAnnotationState2[\"Marked\"] = \"Marked\";\n PdfAnnotationState2[\"Unmarked\"] = \"Unmarked\";\n PdfAnnotationState2[\"Accepted\"] = \"Accepted\";\n PdfAnnotationState2[\"Rejected\"] = \"Rejected\";\n PdfAnnotationState2[\"Completed\"] = \"Completed\";\n PdfAnnotationState2[\"Cancelled\"] = \"Cancelled\";\n PdfAnnotationState2[\"None\"] = \"None\";\n return PdfAnnotationState2;\n})(PdfAnnotationState || {});\nvar PdfAnnotationStateModel = /* @__PURE__ */ ((PdfAnnotationStateModel2) => {\n PdfAnnotationStateModel2[\"Marked\"] = \"Marked\";\n PdfAnnotationStateModel2[\"Review\"] = \"Review\";\n return PdfAnnotationStateModel2;\n})(PdfAnnotationStateModel || {});\nvar PdfAnnotationName = /* @__PURE__ */ ((PdfAnnotationName2) => {\n PdfAnnotationName2[PdfAnnotationName2[\"Unknown\"] = -1] = \"Unknown\";\n PdfAnnotationName2[PdfAnnotationName2[\"Comment\"] = 0] = \"Comment\";\n PdfAnnotationName2[PdfAnnotationName2[\"Key\"] = 1] = \"Key\";\n PdfAnnotationName2[PdfAnnotationName2[\"Note\"] = 2] = \"Note\";\n PdfAnnotationName2[PdfAnnotationName2[\"Help\"] = 3] = \"Help\";\n PdfAnnotationName2[PdfAnnotationName2[\"NewParagraph\"] = 4] = \"NewParagraph\";\n PdfAnnotationName2[PdfAnnotationName2[\"Paragraph\"] = 5] = \"Paragraph\";\n PdfAnnotationName2[PdfAnnotationName2[\"Insert\"] = 6] = \"Insert\";\n PdfAnnotationName2[PdfAnnotationName2[\"Graph\"] = 7] = \"Graph\";\n PdfAnnotationName2[PdfAnnotationName2[\"PushPin\"] = 8] = \"PushPin\";\n PdfAnnotationName2[PdfAnnotationName2[\"Paperclip\"] = 9] = \"Paperclip\";\n PdfAnnotationName2[PdfAnnotationName2[\"Tag\"] = 10] = \"Tag\";\n PdfAnnotationName2[PdfAnnotationName2[\"Speaker\"] = 11] = \"Speaker\";\n PdfAnnotationName2[PdfAnnotationName2[\"Mic\"] = 12] = \"Mic\";\n PdfAnnotationName2[PdfAnnotationName2[\"Approved\"] = 13] = \"Approved\";\n PdfAnnotationName2[PdfAnnotationName2[\"Experimental\"] = 14] = \"Experimental\";\n PdfAnnotationName2[PdfAnnotationName2[\"NotApproved\"] = 15] = \"NotApproved\";\n PdfAnnotationName2[PdfAnnotationName2[\"AsIs\"] = 16] = \"AsIs\";\n PdfAnnotationName2[PdfAnnotationName2[\"Expired\"] = 17] = \"Expired\";\n PdfAnnotationName2[PdfAnnotationName2[\"NotForPublicRelease\"] = 18] = \"NotForPublicRelease\";\n PdfAnnotationName2[PdfAnnotationName2[\"Confidential\"] = 19] = \"Confidential\";\n PdfAnnotationName2[PdfAnnotationName2[\"Final\"] = 20] = \"Final\";\n PdfAnnotationName2[PdfAnnotationName2[\"Sold\"] = 21] = \"Sold\";\n PdfAnnotationName2[PdfAnnotationName2[\"Departmental\"] = 22] = \"Departmental\";\n PdfAnnotationName2[PdfAnnotationName2[\"ForComment\"] = 23] = \"ForComment\";\n PdfAnnotationName2[PdfAnnotationName2[\"TopSecret\"] = 24] = \"TopSecret\";\n PdfAnnotationName2[PdfAnnotationName2[\"Draft\"] = 25] = \"Draft\";\n PdfAnnotationName2[PdfAnnotationName2[\"ForPublicRelease\"] = 26] = \"ForPublicRelease\";\n PdfAnnotationName2[PdfAnnotationName2[\"Completed\"] = 27] = \"Completed\";\n PdfAnnotationName2[PdfAnnotationName2[\"Void\"] = 28] = \"Void\";\n PdfAnnotationName2[PdfAnnotationName2[\"PreliminaryResults\"] = 29] = \"PreliminaryResults\";\n PdfAnnotationName2[PdfAnnotationName2[\"InformationOnly\"] = 30] = \"InformationOnly\";\n PdfAnnotationName2[PdfAnnotationName2[\"Rejected\"] = 31] = \"Rejected\";\n PdfAnnotationName2[PdfAnnotationName2[\"Witness\"] = 32] = \"Witness\";\n PdfAnnotationName2[PdfAnnotationName2[\"InitialHere\"] = 33] = \"InitialHere\";\n PdfAnnotationName2[PdfAnnotationName2[\"SignHere\"] = 34] = \"SignHere\";\n PdfAnnotationName2[PdfAnnotationName2[\"Accepted\"] = 35] = \"Accepted\";\n PdfAnnotationName2[PdfAnnotationName2[\"Custom\"] = 36] = \"Custom\";\n PdfAnnotationName2[PdfAnnotationName2[\"Image\"] = 37] = \"Image\";\n return PdfAnnotationName2;\n})(PdfAnnotationName || {});\nconst PdfAnnotationIcon = PdfAnnotationName;\nvar PdfAnnotationLineEnding = /* @__PURE__ */ ((PdfAnnotationLineEnding2) => {\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2[\"None\"] = 0] = \"None\";\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2[\"Square\"] = 1] = \"Square\";\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2[\"Circle\"] = 2] = \"Circle\";\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2[\"Diamond\"] = 3] = \"Diamond\";\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2[\"OpenArrow\"] = 4] = \"OpenArrow\";\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2[\"ClosedArrow\"] = 5] = \"ClosedArrow\";\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2[\"Butt\"] = 6] = \"Butt\";\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2[\"ROpenArrow\"] = 7] = \"ROpenArrow\";\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2[\"RClosedArrow\"] = 8] = \"RClosedArrow\";\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2[\"Slash\"] = 9] = \"Slash\";\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2[\"Unknown\"] = 10] = \"Unknown\";\n return PdfAnnotationLineEnding2;\n})(PdfAnnotationLineEnding || {});\nvar PdfAnnotationReplyType = /* @__PURE__ */ ((PdfAnnotationReplyType2) => {\n PdfAnnotationReplyType2[PdfAnnotationReplyType2[\"Unknown\"] = 0] = \"Unknown\";\n PdfAnnotationReplyType2[PdfAnnotationReplyType2[\"Reply\"] = 1] = \"Reply\";\n PdfAnnotationReplyType2[PdfAnnotationReplyType2[\"Group\"] = 2] = \"Group\";\n return PdfAnnotationReplyType2;\n})(PdfAnnotationReplyType || {});\nvar PDF_FORM_FIELD_TYPE = /* @__PURE__ */ ((PDF_FORM_FIELD_TYPE2) => {\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2[\"UNKNOWN\"] = 0] = \"UNKNOWN\";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2[\"PUSHBUTTON\"] = 1] = \"PUSHBUTTON\";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2[\"CHECKBOX\"] = 2] = \"CHECKBOX\";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2[\"RADIOBUTTON\"] = 3] = \"RADIOBUTTON\";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2[\"COMBOBOX\"] = 4] = \"COMBOBOX\";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2[\"LISTBOX\"] = 5] = \"LISTBOX\";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2[\"TEXTFIELD\"] = 6] = \"TEXTFIELD\";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2[\"SIGNATURE\"] = 7] = \"SIGNATURE\";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2[\"XFA\"] = 8] = \"XFA\";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2[\"XFA_CHECKBOX\"] = 9] = \"XFA_CHECKBOX\";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2[\"XFA_COMBOBOX\"] = 10] = \"XFA_COMBOBOX\";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2[\"XFA_IMAGEFIELD\"] = 11] = \"XFA_IMAGEFIELD\";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2[\"XFA_LISTBOX\"] = 12] = \"XFA_LISTBOX\";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2[\"XFA_PUSHBUTTON\"] = 13] = \"XFA_PUSHBUTTON\";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2[\"XFA_SIGNATURE\"] = 14] = \"XFA_SIGNATURE\";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2[\"XFA_TEXTFIELD\"] = 15] = \"XFA_TEXTFIELD\";\n return PDF_FORM_FIELD_TYPE2;\n})(PDF_FORM_FIELD_TYPE || {});\nvar PdfAnnotationColorType = /* @__PURE__ */ ((PdfAnnotationColorType2) => {\n PdfAnnotationColorType2[PdfAnnotationColorType2[\"Color\"] = 0] = \"Color\";\n PdfAnnotationColorType2[PdfAnnotationColorType2[\"InteriorColor\"] = 1] = \"InteriorColor\";\n PdfAnnotationColorType2[PdfAnnotationColorType2[\"OverlayColor\"] = 2] = \"OverlayColor\";\n PdfAnnotationColorType2[PdfAnnotationColorType2[\"TextColor\"] = 3] = \"TextColor\";\n return PdfAnnotationColorType2;\n})(PdfAnnotationColorType || {});\nvar PdfAnnotationBorderStyle = /* @__PURE__ */ ((PdfAnnotationBorderStyle2) => {\n PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2[\"UNKNOWN\"] = 0] = \"UNKNOWN\";\n PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2[\"SOLID\"] = 1] = \"SOLID\";\n PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2[\"DASHED\"] = 2] = \"DASHED\";\n PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2[\"BEVELED\"] = 3] = \"BEVELED\";\n PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2[\"INSET\"] = 4] = \"INSET\";\n PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2[\"UNDERLINE\"] = 5] = \"UNDERLINE\";\n PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2[\"CLOUDY\"] = 6] = \"CLOUDY\";\n return PdfAnnotationBorderStyle2;\n})(PdfAnnotationBorderStyle || {});\nvar PdfAnnotationFlags = /* @__PURE__ */ ((PdfAnnotationFlags2) => {\n PdfAnnotationFlags2[PdfAnnotationFlags2[\"NONE\"] = 0] = \"NONE\";\n PdfAnnotationFlags2[PdfAnnotationFlags2[\"INVISIBLE\"] = 1] = \"INVISIBLE\";\n PdfAnnotationFlags2[PdfAnnotationFlags2[\"HIDDEN\"] = 2] = \"HIDDEN\";\n PdfAnnotationFlags2[PdfAnnotationFlags2[\"PRINT\"] = 4] = \"PRINT\";\n PdfAnnotationFlags2[PdfAnnotationFlags2[\"NO_ZOOM\"] = 8] = \"NO_ZOOM\";\n PdfAnnotationFlags2[PdfAnnotationFlags2[\"NO_ROTATE\"] = 16] = \"NO_ROTATE\";\n PdfAnnotationFlags2[PdfAnnotationFlags2[\"NO_VIEW\"] = 32] = \"NO_VIEW\";\n PdfAnnotationFlags2[PdfAnnotationFlags2[\"READ_ONLY\"] = 64] = \"READ_ONLY\";\n PdfAnnotationFlags2[PdfAnnotationFlags2[\"LOCKED\"] = 128] = \"LOCKED\";\n PdfAnnotationFlags2[PdfAnnotationFlags2[\"TOGGLE_NOVIEW\"] = 256] = \"TOGGLE_NOVIEW\";\n PdfAnnotationFlags2[PdfAnnotationFlags2[\"LOCKED_CONTENTS\"] = 512] = \"LOCKED_CONTENTS\";\n return PdfAnnotationFlags2;\n})(PdfAnnotationFlags || {});\nvar PDF_FORM_FIELD_FLAG = /* @__PURE__ */ ((PDF_FORM_FIELD_FLAG2) => {\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"NONE\"] = 0] = \"NONE\";\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"READONLY\"] = 1] = \"READONLY\";\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"REQUIRED\"] = 2] = \"REQUIRED\";\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"NOEXPORT\"] = 4] = \"NOEXPORT\";\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"TEXT_MULTIPLINE\"] = 4096] = \"TEXT_MULTIPLINE\";\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"TEXT_PASSWORD\"] = 8192] = \"TEXT_PASSWORD\";\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"TEXT_FILESELECT\"] = 1048576] = \"TEXT_FILESELECT\";\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"TEXT_DONOTSPELLCHECK\"] = 4194304] = \"TEXT_DONOTSPELLCHECK\";\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"TEXT_DONOTSCROLL\"] = 8388608] = \"TEXT_DONOTSCROLL\";\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"TEXT_COMB\"] = 16777216] = \"TEXT_COMB\";\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"TEXT_RICHTEXT\"] = 33554432] = \"TEXT_RICHTEXT\";\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"BUTTON_NOTOGGLETOOFF\"] = 16384] = \"BUTTON_NOTOGGLETOOFF\";\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"BUTTON_RADIO\"] = 32768] = \"BUTTON_RADIO\";\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"BUTTON_PUSHBUTTON\"] = 65536] = \"BUTTON_PUSHBUTTON\";\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"BUTTON_RADIOSINUNISON\"] = 33554432] = \"BUTTON_RADIOSINUNISON\";\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"CHOICE_COMBO\"] = 131072] = \"CHOICE_COMBO\";\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"CHOICE_EDIT\"] = 262144] = \"CHOICE_EDIT\";\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"CHOICE_SORT\"] = 524288] = \"CHOICE_SORT\";\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"CHOICE_MULTL_SELECT\"] = 2097152] = \"CHOICE_MULTL_SELECT\";\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"CHOICE_DONOTSPELLCHECK\"] = 4194304] = \"CHOICE_DONOTSPELLCHECK\";\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"CHOICE_COMMITONSELCHANGE\"] = 67108864] = \"CHOICE_COMMITONSELCHANGE\";\n return PDF_FORM_FIELD_FLAG2;\n})(PDF_FORM_FIELD_FLAG || {});\nvar PdfPageObjectType = /* @__PURE__ */ ((PdfPageObjectType2) => {\n PdfPageObjectType2[PdfPageObjectType2[\"UNKNOWN\"] = 0] = \"UNKNOWN\";\n PdfPageObjectType2[PdfPageObjectType2[\"TEXT\"] = 1] = \"TEXT\";\n PdfPageObjectType2[PdfPageObjectType2[\"PATH\"] = 2] = \"PATH\";\n PdfPageObjectType2[PdfPageObjectType2[\"IMAGE\"] = 3] = \"IMAGE\";\n PdfPageObjectType2[PdfPageObjectType2[\"SHADING\"] = 4] = \"SHADING\";\n PdfPageObjectType2[PdfPageObjectType2[\"FORM\"] = 5] = \"FORM\";\n return PdfPageObjectType2;\n})(PdfPageObjectType || {});\nconst PdfAnnotationFlagName = Object.freeze({\n [\n 1\n /* INVISIBLE */\n ]: \"invisible\",\n [\n 2\n /* HIDDEN */\n ]: \"hidden\",\n [\n 4\n /* PRINT */\n ]: \"print\",\n [\n 8\n /* NO_ZOOM */\n ]: \"noZoom\",\n [\n 16\n /* NO_ROTATE */\n ]: \"noRotate\",\n [\n 32\n /* NO_VIEW */\n ]: \"noView\",\n [\n 64\n /* READ_ONLY */\n ]: \"readOnly\",\n [\n 128\n /* LOCKED */\n ]: \"locked\",\n [\n 256\n /* TOGGLE_NOVIEW */\n ]: \"toggleNoView\",\n [\n 512\n /* LOCKED_CONTENTS */\n ]: \"lockedContents\"\n});\nconst PdfAnnotationFlagValue = Object.entries(\n PdfAnnotationFlagName\n).reduce(\n (acc, [bit, name]) => {\n acc[name] = Number(bit);\n return acc;\n },\n {}\n);\nfunction flagsToNames(raw) {\n return Object.keys(PdfAnnotationFlagName).filter((flag) => (raw & flag) !== 0).map((flag) => PdfAnnotationFlagName[flag]);\n}\nfunction namesToFlags(names) {\n return names.reduce(\n (mask, name) => mask | PdfAnnotationFlagValue[name],\n 0\n /* NONE */\n );\n}\nfunction isWidgetChecked(widget) {\n return widget.exportValue != null && widget.field.value === widget.exportValue;\n}\nvar PDF_ANNOT_AACTION_EVENT = /* @__PURE__ */ ((PDF_ANNOT_AACTION_EVENT2) => {\n PDF_ANNOT_AACTION_EVENT2[PDF_ANNOT_AACTION_EVENT2[\"KEY_STROKE\"] = 12] = \"KEY_STROKE\";\n PDF_ANNOT_AACTION_EVENT2[PDF_ANNOT_AACTION_EVENT2[\"FORMAT\"] = 13] = \"FORMAT\";\n PDF_ANNOT_AACTION_EVENT2[PDF_ANNOT_AACTION_EVENT2[\"VALIDATE\"] = 14] = \"VALIDATE\";\n PDF_ANNOT_AACTION_EVENT2[PDF_ANNOT_AACTION_EVENT2[\"CALCULATE\"] = 15] = \"CALCULATE\";\n return PDF_ANNOT_AACTION_EVENT2;\n})(PDF_ANNOT_AACTION_EVENT || {});\nvar PdfJavaScriptWidgetEventType = /* @__PURE__ */ ((PdfJavaScriptWidgetEventType2) => {\n PdfJavaScriptWidgetEventType2[\"Keystroke\"] = \"keystroke\";\n PdfJavaScriptWidgetEventType2[\"Format\"] = \"format\";\n PdfJavaScriptWidgetEventType2[\"Validate\"] = \"validate\";\n PdfJavaScriptWidgetEventType2[\"Calculate\"] = \"calculate\";\n return PdfJavaScriptWidgetEventType2;\n})(PdfJavaScriptWidgetEventType || {});\nvar PdfJavaScriptActionTrigger = /* @__PURE__ */ ((PdfJavaScriptActionTrigger2) => {\n PdfJavaScriptActionTrigger2[\"DocumentNamed\"] = \"document_named\";\n PdfJavaScriptActionTrigger2[\"WidgetKeystroke\"] = \"widget_keystroke\";\n PdfJavaScriptActionTrigger2[\"WidgetFormat\"] = \"widget_format\";\n PdfJavaScriptActionTrigger2[\"WidgetValidate\"] = \"widget_validate\";\n PdfJavaScriptActionTrigger2[\"WidgetCalculate\"] = \"widget_calculate\";\n return PdfJavaScriptActionTrigger2;\n})(PdfJavaScriptActionTrigger || {});\nvar PdfSegmentObjectType = /* @__PURE__ */ ((PdfSegmentObjectType2) => {\n PdfSegmentObjectType2[PdfSegmentObjectType2[\"UNKNOWN\"] = -1] = \"UNKNOWN\";\n PdfSegmentObjectType2[PdfSegmentObjectType2[\"LINETO\"] = 0] = \"LINETO\";\n PdfSegmentObjectType2[PdfSegmentObjectType2[\"BEZIERTO\"] = 1] = \"BEZIERTO\";\n PdfSegmentObjectType2[PdfSegmentObjectType2[\"MOVETO\"] = 2] = \"MOVETO\";\n return PdfSegmentObjectType2;\n})(PdfSegmentObjectType || {});\nvar FontCharset = /* @__PURE__ */ ((FontCharset2) => {\n FontCharset2[FontCharset2[\"ANSI\"] = 0] = \"ANSI\";\n FontCharset2[FontCharset2[\"DEFAULT\"] = 1] = \"DEFAULT\";\n FontCharset2[FontCharset2[\"SYMBOL\"] = 2] = \"SYMBOL\";\n FontCharset2[FontCharset2[\"SHIFTJIS\"] = 128] = \"SHIFTJIS\";\n FontCharset2[FontCharset2[\"HANGEUL\"] = 129] = \"HANGEUL\";\n FontCharset2[FontCharset2[\"GB2312\"] = 134] = \"GB2312\";\n FontCharset2[FontCharset2[\"CHINESEBIG5\"] = 136] = \"CHINESEBIG5\";\n FontCharset2[FontCharset2[\"GREEK\"] = 161] = \"GREEK\";\n FontCharset2[FontCharset2[\"VIETNAMESE\"] = 163] = \"VIETNAMESE\";\n FontCharset2[FontCharset2[\"HEBREW\"] = 177] = \"HEBREW\";\n FontCharset2[FontCharset2[\"ARABIC\"] = 178] = \"ARABIC\";\n FontCharset2[FontCharset2[\"CYRILLIC\"] = 204] = \"CYRILLIC\";\n FontCharset2[FontCharset2[\"THAI\"] = 222] = \"THAI\";\n FontCharset2[FontCharset2[\"EASTERNEUROPEAN\"] = 238] = \"EASTERNEUROPEAN\";\n return FontCharset2;\n})(FontCharset || {});\nvar PdfEngineFeature = /* @__PURE__ */ ((PdfEngineFeature2) => {\n PdfEngineFeature2[PdfEngineFeature2[\"RenderPage\"] = 0] = \"RenderPage\";\n PdfEngineFeature2[PdfEngineFeature2[\"RenderPageRect\"] = 1] = \"RenderPageRect\";\n PdfEngineFeature2[PdfEngineFeature2[\"Thumbnails\"] = 2] = \"Thumbnails\";\n PdfEngineFeature2[PdfEngineFeature2[\"Bookmarks\"] = 3] = \"Bookmarks\";\n PdfEngineFeature2[PdfEngineFeature2[\"Annotations\"] = 4] = \"Annotations\";\n return PdfEngineFeature2;\n})(PdfEngineFeature || {});\nvar PdfEngineOperation = /* @__PURE__ */ ((PdfEngineOperation2) => {\n PdfEngineOperation2[PdfEngineOperation2[\"Create\"] = 0] = \"Create\";\n PdfEngineOperation2[PdfEngineOperation2[\"Read\"] = 1] = \"Read\";\n PdfEngineOperation2[PdfEngineOperation2[\"Update\"] = 2] = \"Update\";\n PdfEngineOperation2[PdfEngineOperation2[\"Delete\"] = 3] = \"Delete\";\n return PdfEngineOperation2;\n})(PdfEngineOperation || {});\nvar MatchFlag = /* @__PURE__ */ ((MatchFlag2) => {\n MatchFlag2[MatchFlag2[\"None\"] = 0] = \"None\";\n MatchFlag2[MatchFlag2[\"MatchCase\"] = 1] = \"MatchCase\";\n MatchFlag2[MatchFlag2[\"MatchWholeWord\"] = 2] = \"MatchWholeWord\";\n MatchFlag2[MatchFlag2[\"MatchConsecutive\"] = 4] = \"MatchConsecutive\";\n return MatchFlag2;\n})(MatchFlag || {});\nfunction unionFlags(flags) {\n return flags.reduce(\n (flag, currFlag) => {\n return flag | currFlag;\n },\n 0\n /* None */\n );\n}\nfunction compareSearchTarget(targetA, targetB) {\n const flagA = unionFlags(targetA.flags);\n const flagB = unionFlags(targetB.flags);\n return flagA === flagB && targetA.keyword === targetB.keyword;\n}\nvar PdfPermissionFlag = /* @__PURE__ */ ((PdfPermissionFlag2) => {\n PdfPermissionFlag2[PdfPermissionFlag2[\"Print\"] = 4] = \"Print\";\n PdfPermissionFlag2[PdfPermissionFlag2[\"ModifyContents\"] = 8] = \"ModifyContents\";\n PdfPermissionFlag2[PdfPermissionFlag2[\"CopyContents\"] = 16] = \"CopyContents\";\n PdfPermissionFlag2[PdfPermissionFlag2[\"ModifyAnnotations\"] = 32] = \"ModifyAnnotations\";\n PdfPermissionFlag2[PdfPermissionFlag2[\"FillForms\"] = 256] = \"FillForms\";\n PdfPermissionFlag2[PdfPermissionFlag2[\"ExtractForAccessibility\"] = 512] = \"ExtractForAccessibility\";\n PdfPermissionFlag2[PdfPermissionFlag2[\"AssembleDocument\"] = 1024] = \"AssembleDocument\";\n PdfPermissionFlag2[PdfPermissionFlag2[\"PrintHighQuality\"] = 2048] = \"PrintHighQuality\";\n PdfPermissionFlag2[PdfPermissionFlag2[\"AllowAll\"] = 3900] = \"AllowAll\";\n return PdfPermissionFlag2;\n})(PdfPermissionFlag || {});\nfunction buildPermissions(...flags) {\n let result = flags.reduce((acc, flag) => acc | flag, 0);\n if (result & 2048) {\n result |= 4;\n }\n return result;\n}\nclass PermissionDeniedError extends Error {\n constructor(requiredFlags, currentPermissions) {\n const flagNames = requiredFlags.map((f) => PdfPermissionFlag[f]).join(\", \");\n super(`Permission denied. Required: ${flagNames}`);\n this.requiredFlags = requiredFlags;\n this.currentPermissions = currentPermissions;\n this.name = \"PermissionDeniedError\";\n }\n}\nvar PdfPageFlattenFlag = /* @__PURE__ */ ((PdfPageFlattenFlag2) => {\n PdfPageFlattenFlag2[PdfPageFlattenFlag2[\"Display\"] = 0] = \"Display\";\n PdfPageFlattenFlag2[PdfPageFlattenFlag2[\"Print\"] = 1] = \"Print\";\n return PdfPageFlattenFlag2;\n})(PdfPageFlattenFlag || {});\nvar PdfPageFlattenResult = /* @__PURE__ */ ((PdfPageFlattenResult2) => {\n PdfPageFlattenResult2[PdfPageFlattenResult2[\"Fail\"] = 0] = \"Fail\";\n PdfPageFlattenResult2[PdfPageFlattenResult2[\"Success\"] = 1] = \"Success\";\n PdfPageFlattenResult2[PdfPageFlattenResult2[\"NothingToDo\"] = 2] = \"NothingToDo\";\n return PdfPageFlattenResult2;\n})(PdfPageFlattenResult || {});\nvar PdfErrorCode = /* @__PURE__ */ ((PdfErrorCode2) => {\n PdfErrorCode2[PdfErrorCode2[\"Ok\"] = 0] = \"Ok\";\n PdfErrorCode2[PdfErrorCode2[\"Unknown\"] = 1] = \"Unknown\";\n PdfErrorCode2[PdfErrorCode2[\"NotFound\"] = 2] = \"NotFound\";\n PdfErrorCode2[PdfErrorCode2[\"WrongFormat\"] = 3] = \"WrongFormat\";\n PdfErrorCode2[PdfErrorCode2[\"Password\"] = 4] = \"Password\";\n PdfErrorCode2[PdfErrorCode2[\"Security\"] = 5] = \"Security\";\n PdfErrorCode2[PdfErrorCode2[\"PageError\"] = 6] = \"PageError\";\n PdfErrorCode2[PdfErrorCode2[\"XFALoad\"] = 7] = \"XFALoad\";\n PdfErrorCode2[PdfErrorCode2[\"XFALayout\"] = 8] = \"XFALayout\";\n PdfErrorCode2[PdfErrorCode2[\"Cancelled\"] = 9] = \"Cancelled\";\n PdfErrorCode2[PdfErrorCode2[\"Initialization\"] = 10] = \"Initialization\";\n PdfErrorCode2[PdfErrorCode2[\"NotReady\"] = 11] = \"NotReady\";\n PdfErrorCode2[PdfErrorCode2[\"NotSupport\"] = 12] = \"NotSupport\";\n PdfErrorCode2[PdfErrorCode2[\"LoadDoc\"] = 13] = \"LoadDoc\";\n PdfErrorCode2[PdfErrorCode2[\"DocNotOpen\"] = 14] = \"DocNotOpen\";\n PdfErrorCode2[PdfErrorCode2[\"CantCloseDoc\"] = 15] = \"CantCloseDoc\";\n PdfErrorCode2[PdfErrorCode2[\"CantCreateNewDoc\"] = 16] = \"CantCreateNewDoc\";\n PdfErrorCode2[PdfErrorCode2[\"CantImportPages\"] = 17] = \"CantImportPages\";\n PdfErrorCode2[PdfErrorCode2[\"CantCreateAnnot\"] = 18] = \"CantCreateAnnot\";\n PdfErrorCode2[PdfErrorCode2[\"CantSetAnnotRect\"] = 19] = \"CantSetAnnotRect\";\n PdfErrorCode2[PdfErrorCode2[\"CantSetAnnotContent\"] = 20] = \"CantSetAnnotContent\";\n PdfErrorCode2[PdfErrorCode2[\"CantRemoveInkList\"] = 21] = \"CantRemoveInkList\";\n PdfErrorCode2[PdfErrorCode2[\"CantAddInkStoke\"] = 22] = \"CantAddInkStoke\";\n PdfErrorCode2[PdfErrorCode2[\"CantReadAttachmentSize\"] = 23] = \"CantReadAttachmentSize\";\n PdfErrorCode2[PdfErrorCode2[\"CantReadAttachmentContent\"] = 24] = \"CantReadAttachmentContent\";\n PdfErrorCode2[PdfErrorCode2[\"CantFocusAnnot\"] = 25] = \"CantFocusAnnot\";\n PdfErrorCode2[PdfErrorCode2[\"CantSelectText\"] = 26] = \"CantSelectText\";\n PdfErrorCode2[PdfErrorCode2[\"CantSelectOption\"] = 27] = \"CantSelectOption\";\n PdfErrorCode2[PdfErrorCode2[\"CantCheckField\"] = 28] = \"CantCheckField\";\n PdfErrorCode2[PdfErrorCode2[\"CantSetAnnotString\"] = 29] = \"CantSetAnnotString\";\n PdfErrorCode2[PdfErrorCode2[\"CantDeletePage\"] = 30] = \"CantDeletePage\";\n return PdfErrorCode2;\n})(PdfErrorCode || {});\nclass PdfTaskHelper {\n /**\n * Create a task\n * @returns new task\n */\n static create() {\n return new Task();\n }\n /**\n * Create a task that has been resolved with value\n * @param result - resolved value\n * @returns resolved task\n */\n static resolve(result) {\n const task = new Task();\n task.resolve(result);\n return task;\n }\n /**\n * Create a task that has been rejected with error\n * @param reason - rejected error\n * @returns rejected task\n */\n static reject(reason) {\n const task = new Task();\n task.reject(reason);\n return task;\n }\n /**\n * Create a task that has been aborted with error\n * @param reason - aborted error\n * @returns aborted task\n */\n static abort(reason) {\n const task = new Task();\n task.reject(reason);\n return task;\n }\n}\nfunction pdfColorToWebColor(c) {\n const clamp = (n) => Math.max(0, Math.min(255, n));\n const toHex = (n) => clamp(n).toString(16).padStart(2, \"0\");\n return `#${toHex(c.red)}${toHex(c.green)}${toHex(c.blue)}`;\n}\nfunction webColorToPdfColor(color) {\n if (/^#?[0-9a-f]{3}$/i.test(color)) {\n color = color.replace(/^#?([0-9a-f])([0-9a-f])([0-9a-f])$/i, \"#$1$1$2$2$3$3\").toLowerCase();\n }\n const [, r, g, b] = /^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(color) ?? (() => {\n throw new Error(`Invalid hex colour: \"${color}\"`);\n })();\n return {\n red: parseInt(r, 16),\n green: parseInt(g, 16),\n blue: parseInt(b, 16)\n };\n}\nfunction getContrastStrokeColor(fillColor) {\n try {\n const { red, green, blue } = webColorToPdfColor(fillColor);\n const luminance = (0.299 * red + 0.587 * green + 0.114 * blue) / 255;\n return luminance < 0.45 ? \"#fff\" : \"#000\";\n } catch {\n return \"#000\";\n }\n}\nfunction pdfAlphaToWebOpacity(alpha) {\n const clamp = (n) => Math.max(0, Math.min(255, n));\n return clamp(alpha) / 255;\n}\nfunction webOpacityToPdfAlpha(opacity) {\n const clamp = (n, hi = 255) => Math.max(0, Math.min(hi, n));\n return clamp(Math.round(opacity * 255));\n}\nfunction extractPdfColor(c) {\n return { red: c.red, green: c.green, blue: c.blue };\n}\nfunction extractWebOpacity(c) {\n return pdfAlphaToWebOpacity(c.alpha);\n}\nfunction combinePdfColorWithAlpha(color, alpha) {\n return { ...color, alpha };\n}\nfunction combineWebColorWithOpacity(color, opacity) {\n return { color, opacity };\n}\nfunction pdfAlphaColorToWebAlphaColor(c) {\n const color = pdfColorToWebColor(extractPdfColor(c));\n const opacity = extractWebOpacity(c);\n return { color, opacity };\n}\nfunction webAlphaColorToPdfAlphaColor({ color, opacity }) {\n const pdfColor = webColorToPdfColor(color);\n const alpha = webOpacityToPdfAlpha(opacity);\n return combinePdfColorWithAlpha(pdfColor, alpha);\n}\nfunction pdfDateToDate(pdf) {\n if (!(pdf == null ? void 0 : pdf.startsWith(\"D:\")) || pdf.length < 16) return;\n const y = +pdf.slice(2, 6);\n const mo = +pdf.slice(6, 8) - 1;\n const d = +pdf.slice(8, 10);\n const H = +pdf.slice(10, 12);\n const M = +pdf.slice(12, 14);\n const S = +pdf.slice(14, 16);\n return new Date(Date.UTC(y, mo, d, H, M, S));\n}\nfunction dateToPdfDate(date = /* @__PURE__ */ new Date()) {\n const z = (n, len = 2) => n.toString().padStart(len, \"0\");\n const YYYY = date.getUTCFullYear();\n const MM = z(date.getUTCMonth() + 1);\n const DD = z(date.getUTCDate());\n const HH = z(date.getUTCHours());\n const mm = z(date.getUTCMinutes());\n const SS = z(date.getUTCSeconds());\n return `D:${YYYY}${MM}${DD}${HH}${mm}${SS}`;\n}\nconst MixedTextAlignment = Symbol(\"mixed\");\nconst TEXT_ALIGNMENT_INFOS = Object.freeze([\n { id: PdfTextAlignment.Left, label: \"Left\", css: \"left\" },\n { id: PdfTextAlignment.Center, label: \"Center\", css: \"center\" },\n { id: PdfTextAlignment.Right, label: \"Right\", css: \"right\" }\n]);\nconst enumToTextInfo = TEXT_ALIGNMENT_INFOS.reduce(\n (m, info) => {\n m[info.id] = info;\n return m;\n },\n {}\n);\nconst cssToTextEnum = TEXT_ALIGNMENT_INFOS.reduce(\n (m, info) => {\n m[info.css] = info.id;\n return m;\n },\n {}\n);\nfunction getTextAlignmentInfo(alignment) {\n return enumToTextInfo[alignment] ?? enumToTextInfo[PdfTextAlignment.Left];\n}\nfunction textAlignmentToCss(alignment) {\n return getTextAlignmentInfo(alignment).css;\n}\nfunction cssToTextAlignment(value) {\n return cssToTextEnum[value];\n}\nfunction textAlignmentLabel(alignment) {\n return getTextAlignmentInfo(alignment).label;\n}\nfunction reduceTextAlignments(values) {\n if (!values.length) return PdfTextAlignment.Left;\n const first = values[0];\n return values.every((a) => a === first) ? first : MixedTextAlignment;\n}\nconst textAlignmentSelectOptions = TEXT_ALIGNMENT_INFOS.map((info) => ({\n value: info.id,\n label: info.label\n}));\nvar PdfStandardFontFamily = /* @__PURE__ */ ((PdfStandardFontFamily2) => {\n PdfStandardFontFamily2[\"Courier\"] = \"Courier\";\n PdfStandardFontFamily2[\"Helvetica\"] = \"Helvetica\";\n PdfStandardFontFamily2[\"Times\"] = \"Times\";\n PdfStandardFontFamily2[\"Symbol\"] = \"Symbol\";\n PdfStandardFontFamily2[\"ZapfDingbats\"] = \"ZapfDingbats\";\n PdfStandardFontFamily2[\"Unknown\"] = \"Unknown\";\n return PdfStandardFontFamily2;\n})(PdfStandardFontFamily || {});\nconst DEFAULT_FALLBACK_FONT = PdfStandardFont.Helvetica;\nconst MixedStandardFont = Symbol(\"mixed\");\nconst HELVETICA_DESC = {\n id: PdfStandardFont.Helvetica,\n family: \"Helvetica\",\n bold: false,\n italic: false,\n label: \"Helvetica\",\n css: \"Helvetica, Arial, sans-serif\"\n};\nconst STANDARD_FONT_DESCRIPTORS = Object.freeze([\n {\n id: PdfStandardFont.Courier,\n family: \"Courier\",\n bold: false,\n italic: false,\n label: \"Courier\",\n css: \"Courier, monospace\"\n },\n {\n id: PdfStandardFont.Courier_Bold,\n family: \"Courier\",\n bold: true,\n italic: false,\n label: \"Courier Bold\",\n css: \"Courier, monospace\"\n },\n {\n id: PdfStandardFont.Courier_BoldOblique,\n family: \"Courier\",\n bold: true,\n italic: true,\n label: \"Courier Bold Oblique\",\n css: \"Courier, monospace\"\n },\n {\n id: PdfStandardFont.Courier_Oblique,\n family: \"Courier\",\n bold: false,\n italic: true,\n label: \"Courier Oblique\",\n css: \"Courier, monospace\"\n },\n HELVETICA_DESC,\n {\n id: PdfStandardFont.Helvetica_Bold,\n family: \"Helvetica\",\n bold: true,\n italic: false,\n label: \"Helvetica Bold\",\n css: \"Helvetica, Arial, sans-serif\"\n },\n {\n id: PdfStandardFont.Helvetica_BoldOblique,\n family: \"Helvetica\",\n bold: true,\n italic: true,\n label: \"Helvetica Bold Oblique\",\n css: \"Helvetica, Arial, sans-serif\"\n },\n {\n id: PdfStandardFont.Helvetica_Oblique,\n family: \"Helvetica\",\n bold: false,\n italic: true,\n label: \"Helvetica Oblique\",\n css: \"Helvetica, Arial, sans-serif\"\n },\n {\n id: PdfStandardFont.Times_Roman,\n family: \"Times\",\n bold: false,\n italic: false,\n label: \"Times Roman\",\n css: '\"Times New Roman\", Times, serif'\n },\n {\n id: PdfStandardFont.Times_Bold,\n family: \"Times\",\n bold: true,\n italic: false,\n label: \"Times Bold\",\n css: '\"Times New Roman\", Times, serif'\n },\n {\n id: PdfStandardFont.Times_BoldItalic,\n family: \"Times\",\n bold: true,\n italic: true,\n label: \"Times Bold Italic\",\n css: '\"Times New Roman\", Times, serif'\n },\n {\n id: PdfStandardFont.Times_Italic,\n family: \"Times\",\n bold: false,\n italic: true,\n label: \"Times Italic\",\n css: '\"Times New Roman\", Times, serif'\n },\n {\n id: PdfStandardFont.Symbol,\n family: \"Symbol\",\n bold: false,\n italic: false,\n label: \"Symbol\",\n css: \"Symbol, serif\"\n },\n {\n id: PdfStandardFont.ZapfDingbats,\n family: \"ZapfDingbats\",\n bold: false,\n italic: false,\n label: \"Zapf Dingbats\",\n css: \"ZapfDingbats, serif\"\n }\n]);\nconst idToDescriptor = STANDARD_FONT_DESCRIPTORS.reduce((m, d) => (m[d.id] = d, m), {});\nconst familyStyleToId = /* @__PURE__ */ new Map();\nfor (const d of STANDARD_FONT_DESCRIPTORS) {\n familyStyleToId.set(`${d.family}_${d.bold}_${d.italic}`, d.id);\n}\nfunction unknownDescriptor() {\n return HELVETICA_DESC;\n}\nfunction getStandardFontDescriptor(font) {\n return idToDescriptor[font] ?? unknownDescriptor();\n}\nfunction standardFontFamily(font) {\n return getStandardFontDescriptor(font).family;\n}\nfunction standardFontIsBold(font) {\n return getStandardFontDescriptor(font).bold;\n}\nfunction standardFontIsItalic(font) {\n return getStandardFontDescriptor(font).italic;\n}\nfunction makeStandardFont(family, { bold, italic }) {\n return familyStyleToId.get(`${family}_${bold}_${italic}`) ?? DEFAULT_FALLBACK_FONT;\n}\nfunction standardFontLabel(font) {\n return getStandardFontDescriptor(font).label;\n}\nfunction standardFontCss(font) {\n return getStandardFontDescriptor(font).css;\n}\nfunction standardFontCssProperties(font) {\n const desc = getStandardFontDescriptor(font);\n return {\n fontFamily: desc.css,\n fontWeight: desc.bold ? \"bold\" : \"normal\",\n fontStyle: desc.italic ? \"italic\" : \"normal\"\n };\n}\nconst standardFontFamilySelectOptions = Object.values(PdfStandardFontFamily).filter(\n (f) => f !== \"Unknown\"\n /* Unknown */\n).map((family) => ({ value: family, label: family }));\nfunction reduceStandardFonts(fonts) {\n if (!fonts.length) return PdfStandardFont.Unknown;\n const first = fonts[0];\n return fonts.every((f) => f === first) ? first : MixedStandardFont;\n}\nconst STANDARD_FONT_FAMILIES = [\n ...new Set(STANDARD_FONT_DESCRIPTORS.map((d) => d.family))\n];\nfunction standardFontFamilyLabel(fam) {\n switch (fam) {\n case \"Courier\":\n return \"Courier\";\n case \"Helvetica\":\n return \"Helvetica\";\n case \"Times\":\n return \"Times\";\n case \"Symbol\":\n return \"Symbol\";\n case \"ZapfDingbats\":\n return \"ZapfDingbats\";\n /* fallback */\n default:\n return \"Helvetica\";\n }\n}\nconst MixedBlendMode = Symbol(\"mixed\");\nconst BLEND_MODE_INFOS = Object.freeze([\n { id: PdfBlendMode.Normal, label: \"Normal\", css: \"normal\" },\n { id: PdfBlendMode.Multiply, label: \"Multiply\", css: \"multiply\" },\n { id: PdfBlendMode.Screen, label: \"Screen\", css: \"screen\" },\n { id: PdfBlendMode.Overlay, label: \"Overlay\", css: \"overlay\" },\n { id: PdfBlendMode.Darken, label: \"Darken\", css: \"darken\" },\n { id: PdfBlendMode.Lighten, label: \"Lighten\", css: \"lighten\" },\n { id: PdfBlendMode.ColorDodge, label: \"Color Dodge\", css: \"color-dodge\" },\n { id: PdfBlendMode.ColorBurn, label: \"Color Burn\", css: \"color-burn\" },\n { id: PdfBlendMode.HardLight, label: \"Hard Light\", css: \"hard-light\" },\n { id: PdfBlendMode.SoftLight, label: \"Soft Light\", css: \"soft-light\" },\n { id: PdfBlendMode.Difference, label: \"Difference\", css: \"difference\" },\n { id: PdfBlendMode.Exclusion, label: \"Exclusion\", css: \"exclusion\" },\n { id: PdfBlendMode.Hue, label: \"Hue\", css: \"hue\" },\n { id: PdfBlendMode.Saturation, label: \"Saturation\", css: \"saturation\" },\n { id: PdfBlendMode.Color, label: \"Color\", css: \"color\" },\n { id: PdfBlendMode.Luminosity, label: \"Luminosity\", css: \"luminosity\" }\n]);\nconst enumToInfo = BLEND_MODE_INFOS.reduce(\n (m, info) => {\n m[info.id] = info;\n return m;\n },\n {}\n);\nconst cssToEnum = BLEND_MODE_INFOS.reduce(\n (m, info) => {\n m[info.css] = info.id;\n return m;\n },\n {}\n);\nfunction getBlendModeInfo(mode) {\n return enumToInfo[mode] ?? enumToInfo[PdfBlendMode.Normal];\n}\nfunction blendModeToCss(mode) {\n return getBlendModeInfo(mode).css;\n}\nfunction cssToBlendMode(value) {\n return cssToEnum[value];\n}\nfunction blendModeLabel(mode) {\n return getBlendModeInfo(mode).label;\n}\nfunction reduceBlendModes(modes) {\n if (!modes.length) return PdfBlendMode.Normal;\n const first = modes[0];\n return modes.every((m) => m === first) ? first : MixedBlendMode;\n}\nconst blendModeSelectOptions = BLEND_MODE_INFOS.map((info) => ({\n value: info.id,\n label: info.label\n}));\nconst blendModeValues = BLEND_MODE_INFOS.map((info) => info.id);\nfunction uiBlendModeDisplay(value) {\n return value === MixedBlendMode ? \"(mixed)\" : blendModeLabel(value);\n}\nfunction serializeLogger(logger) {\n if (logger instanceof NoopLogger) {\n return { type: \"noop\" };\n }\n if (logger instanceof ConsoleLogger) {\n return { type: \"console\" };\n }\n if (logger instanceof PerfLogger) {\n return { type: \"perf\" };\n }\n if (logger instanceof LevelLogger) {\n const levelLogger = logger;\n return {\n type: \"level\",\n config: {\n level: levelLogger.level,\n logger: serializeLogger(levelLogger.logger)\n }\n };\n }\n if (logger instanceof AllLogger) {\n const allLogger = logger;\n return {\n type: \"all\",\n config: {\n loggers: allLogger.loggers.map(serializeLogger)\n }\n };\n }\n return { type: \"noop\" };\n}\nfunction deserializeLogger(serialized) {\n var _a, _b, _c;\n switch (serialized.type) {\n case \"noop\":\n return new NoopLogger();\n case \"console\":\n return new ConsoleLogger();\n case \"perf\":\n return new PerfLogger();\n case \"level\":\n if (!((_a = serialized.config) == null ? void 0 : _a.logger) || ((_b = serialized.config) == null ? void 0 : _b.level) === void 0) {\n throw new Error(\"LevelLogger requires logger and level in config\");\n }\n return new LevelLogger(deserializeLogger(serialized.config.logger), serialized.config.level);\n case \"all\":\n if (!((_c = serialized.config) == null ? void 0 : _c.loggers)) {\n throw new Error(\"AllLogger requires loggers array in config\");\n }\n return new AllLogger(serialized.config.loggers.map(deserializeLogger));\n default:\n return new NoopLogger();\n }\n}\nconst V4_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\nfunction isUuidV4(str) {\n return V4_REGEX.test(str);\n}\nfunction getRandomBytes(len) {\n var _a;\n if (typeof ((_a = globalThis.crypto) == null ? void 0 : _a.getRandomValues) === \"function\") {\n return globalThis.crypto.getRandomValues(new Uint8Array(len));\n }\n if (typeof require === \"function\") {\n try {\n const { randomBytes } = require(\"crypto\");\n return randomBytes(len);\n } catch {\n }\n }\n const bytes = new Uint8Array(len);\n for (let i = 0; i < len; i++) bytes[i] = Math.floor(Math.random() * 256);\n return bytes;\n}\nfunction uuidV4() {\n var _a;\n if (typeof ((_a = globalThis.crypto) == null ? void 0 : _a.randomUUID) === \"function\") {\n return globalThis.crypto.randomUUID();\n }\n const bytes = getRandomBytes(16);\n bytes[6] = bytes[6] & 15 | 64;\n bytes[8] = bytes[8] & 63 | 128;\n const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\nclass CompoundTask extends Task {\n constructor(config = {}) {\n super();\n this.children = /* @__PURE__ */ new Map();\n this.childResults = [];\n this.completedCount = 0;\n this.expectedCount = 0;\n this.isFinalized = false;\n this.config = {\n aggregate: config.aggregate ?? ((results) => results),\n onChildComplete: config.onChildComplete ?? (() => {\n }),\n failFast: config.failFast ?? true\n };\n }\n /**\n * Add a child task - automatically wires up completion handling\n */\n addChild(child, index) {\n if (this.state.stage !== TaskStage.Pending) {\n if (this.state.stage === TaskStage.Aborted) {\n child.abort(this.state.reason);\n }\n return this;\n }\n const childIndex = index ?? this.expectedCount;\n this.expectedCount = Math.max(this.expectedCount, childIndex + 1);\n this.children.set(child, childIndex);\n child.wait(\n (result) => this.handleChildSuccess(child, result, childIndex),\n (error) => this.handleChildError(child, error, childIndex)\n );\n return this;\n }\n /**\n * Finalize - signals that no more children will be added\n * If no children were added, resolves immediately\n */\n finalize() {\n if (this.isFinalized) return this;\n this.isFinalized = true;\n if (this.expectedCount === 0) {\n this.resolve(this.config.aggregate([]));\n }\n return this;\n }\n handleChildSuccess(child, result, index) {\n if (this.state.stage !== TaskStage.Pending) return;\n this.childResults[index] = result;\n this.completedCount++;\n this.children.delete(child);\n const progressValue = this.config.onChildComplete(\n this.completedCount,\n this.expectedCount,\n result,\n index\n );\n if (progressValue !== void 0) {\n this.progress(progressValue);\n }\n if (this.completedCount === this.expectedCount) {\n const finalResult = this.config.aggregate(this.childResults);\n this.resolve(finalResult);\n }\n }\n handleChildError(child, error, index) {\n if (this.state.stage !== TaskStage.Pending) return;\n this.children.delete(child);\n if (this.config.failFast) {\n for (const [otherChild] of this.children) {\n otherChild.abort(\"Sibling task failed\");\n }\n this.children.clear();\n this.fail(error);\n } else {\n this.childResults[index] = void 0;\n this.completedCount++;\n if (this.completedCount === this.expectedCount) {\n const finalResult = this.config.aggregate(this.childResults);\n this.resolve(finalResult);\n }\n }\n }\n /**\n * Override abort to propagate to all children\n */\n abort(reason) {\n for (const [child] of this.children) {\n child.abort(reason);\n }\n this.children.clear();\n super.abort(reason);\n }\n /**\n * Override reject to abort all children\n */\n reject(reason) {\n for (const [child] of this.children) {\n child.abort(reason);\n }\n this.children.clear();\n super.reject(reason);\n }\n /**\n * Get count of pending children\n */\n getPendingCount() {\n return this.children.size;\n }\n /**\n * Get count of completed children\n */\n getCompletedCount() {\n return this.completedCount;\n }\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n /**\n * Gather results from an array of tasks (progress-friendly).\n * (Formerly: all)\n */\n static gather(tasks) {\n const compound = new CompoundTask({\n aggregate: (results) => results,\n onChildComplete: (completed, total) => ({ completed, total })\n });\n tasks.forEach((task, index) => compound.addChild(task, index));\n compound.finalize();\n return compound;\n }\n /**\n * Gather into a Record indexed by number.\n * (Formerly: allIndexed)\n */\n static gatherIndexed(tasks) {\n const compound = new CompoundTask({\n aggregate: (results) => {\n const record = {};\n results.forEach((result, index) => {\n record[index] = result;\n });\n return record;\n },\n onChildComplete: (_completed, _total, result, index) => ({ page: index, result })\n });\n tasks.forEach((task, index) => compound.addChild(task, index));\n compound.finalize();\n return compound;\n }\n /**\n * Gather with custom aggregation config.\n * (Formerly: from)\n */\n static gatherFrom(tasks, config) {\n const compound = new CompoundTask(config);\n tasks.forEach((task, index) => compound.addChild(task, index));\n compound.finalize();\n return compound;\n }\n /**\n * Resolve with the first successful child; abort the rest.\n * (Formerly: race)\n */\n static first(tasks) {\n let resolved = false;\n const compound = new CompoundTask({\n aggregate: (results) => results[0],\n failFast: false\n });\n compound[\"handleChildSuccess\"] = (child, result) => {\n if (!resolved) {\n resolved = true;\n for (const [otherChild] of compound[\"children\"]) {\n if (otherChild !== child) otherChild.abort(\"Race won by sibling\");\n }\n compound.resolve(result);\n }\n };\n tasks.forEach((task, index) => compound.addChild(task, index));\n compound.finalize();\n return compound;\n }\n}\nclass TaskSequence {\n constructor(parentTask) {\n this.parentTask = parentTask;\n this.activeChild = null;\n this.disposed = false;\n const origAbort = parentTask.abort.bind(parentTask);\n parentTask.abort = (reason) => {\n var _a;\n this.disposed = true;\n (_a = this.activeChild) == null ? void 0 : _a.abort(reason);\n origAbort(reason);\n };\n }\n /**\n * Execute a child Task and return its result as a Promise.\n *\n * If the parent task has been aborted, throws `TaskAbortedError` immediately.\n * If the parent task is aborted while the child is running, the child is aborted too.\n */\n run(factory) {\n return new Promise((resolve, reject) => {\n if (this.disposed || this.parentTask.state.stage !== TaskStage.Pending) {\n reject(new TaskAbortedError(\"Sequence aborted\"));\n return;\n }\n const child = factory();\n this.activeChild = child;\n child.wait(\n (result) => {\n this.activeChild = null;\n resolve(result);\n },\n (error) => {\n this.activeChild = null;\n if (error.type === \"abort\") {\n reject(new TaskAbortedError(error.reason));\n } else {\n reject(new TaskRejectedError(error.reason));\n }\n }\n );\n });\n }\n /**\n * Execute a child Task and return its result as a Promise,\n * forwarding the child's progress events to the parent task\n * through the provided mapper function.\n *\n * If the parent task has been aborted, throws `TaskAbortedError` immediately.\n * If the parent task is aborted while the child is running, the child is aborted too.\n */\n runWithProgress(factory, mapProgress) {\n return new Promise((resolve, reject) => {\n if (this.disposed || this.parentTask.state.stage !== TaskStage.Pending) {\n reject(new TaskAbortedError(\"Sequence aborted\"));\n return;\n }\n const child = factory();\n this.activeChild = child;\n child.onProgress((p) => {\n this.parentTask.progress(mapProgress(p));\n });\n child.wait(\n (result) => {\n this.activeChild = null;\n resolve(result);\n },\n (error) => {\n this.activeChild = null;\n if (error.type === \"abort\") {\n reject(new TaskAbortedError(error.reason));\n } else {\n reject(new TaskRejectedError(error.reason));\n }\n }\n );\n });\n }\n /**\n * Execute an async function body that uses `run()` / `runWithProgress()`,\n * automatically handling abort and error routing to the parent task.\n *\n * - If the body throws `TaskAbortedError`, it is silently ignored\n * (the parent task was already aborted via the abort override).\n * - If the body throws `TaskRejectedError` (from a child task rejection\n * via `run()` / `runWithProgress()`), its `.reason` is forwarded directly\n * to the parent task, bypassing `mapError`.\n * - Any other thrown error is mapped through `mapError` and used to\n * reject the parent task. This handles unexpected runtime exceptions\n * in the async body itself.\n * - On success, the body is responsible for calling `parentTask.resolve()`.\n */\n execute(fn, mapError) {\n fn().catch((err) => {\n if (err instanceof TaskAbortedError) return;\n if (err instanceof TaskRejectedError) {\n this.parentTask.reject(err.reason);\n return;\n }\n this.parentTask.reject(mapError(err));\n });\n }\n}\nfunction getImageMetadata(buffer) {\n if (buffer.byteLength < 4) return null;\n const bytes = new Uint8Array(buffer);\n if (bytes[0] === 137 && bytes[1] === 80 && bytes[2] === 78 && bytes[3] === 71) {\n return parsePng(buffer);\n }\n if (bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) {\n return parseJpeg(buffer);\n }\n if (bytes[0] === 37 && bytes[1] === 80 && bytes[2] === 68 && bytes[3] === 70) {\n return { mimeType: \"application/pdf\" };\n }\n return null;\n}\nfunction parsePng(buffer) {\n if (buffer.byteLength < 24) return null;\n const view = new DataView(buffer);\n const width = view.getUint32(16);\n const height = view.getUint32(20);\n if (width === 0 || height === 0) return null;\n return { mimeType: \"image/png\", width, height };\n}\nfunction parseJpeg(buffer) {\n const bytes = new Uint8Array(buffer);\n let offset = 2;\n while (offset + 4 < bytes.byteLength) {\n if (bytes[offset] !== 255) return null;\n const marker = bytes[offset + 1];\n if (marker >= 192 && marker <= 195) {\n if (offset + 9 > bytes.byteLength) return null;\n const view = new DataView(buffer, offset + 5);\n const height = view.getUint16(0);\n const width = view.getUint16(2);\n if (width === 0 || height === 0) return null;\n return { mimeType: \"image/jpeg\", width, height };\n }\n if (marker === 216 || marker === 217) {\n offset += 2;\n } else if (marker === 255) {\n offset += 1;\n } else {\n const segLen = bytes[offset + 2] << 8 | bytes[offset + 3];\n offset += 2 + segLen;\n }\n }\n return null;\n}\nfunction ignore() {\n}\nexport {\n AP_MODE_DOWN,\n AP_MODE_NORMAL,\n AP_MODE_ROLLOVER,\n AllLogger,\n AppearanceMode,\n CompoundTask,\n ConsoleLogger,\n FontCharset,\n LevelLogger,\n LogLevel,\n MatchFlag,\n MixedBlendMode,\n MixedStandardFont,\n MixedTextAlignment,\n NoopLogger,\n PDF_ANNOT_AACTION_EVENT,\n PDF_FORM_FIELD_FLAG,\n PDF_FORM_FIELD_TYPE,\n PdfActionType,\n PdfAnnotationBorderStyle,\n PdfAnnotationColorType,\n PdfAnnotationFlagName,\n PdfAnnotationFlags,\n PdfAnnotationIcon,\n PdfAnnotationLineEnding,\n PdfAnnotationName,\n PdfAnnotationObjectStatus,\n PdfAnnotationReplyType,\n PdfAnnotationState,\n PdfAnnotationStateModel,\n PdfAnnotationSubtype,\n PdfAnnotationSubtypeName,\n PdfBlendMode,\n PdfBomOrZwnbsp,\n PdfEngineFeature,\n PdfEngineOperation,\n PdfErrorCode,\n PdfJavaScriptActionTrigger,\n PdfJavaScriptWidgetEventType,\n PdfNonCharacterFFFE,\n PdfNonCharacterFFFF,\n PdfPageFlattenFlag,\n PdfPageFlattenResult,\n PdfPageObjectType,\n PdfPermissionFlag,\n PdfSegmentObjectType,\n PdfSoftHyphenMarker,\n PdfStampFit,\n PdfStandardFont,\n PdfStandardFontFamily,\n PdfTaskHelper,\n PdfTextAlignment,\n PdfTrappedStatus,\n PdfUnwantedTextMarkers,\n PdfUnwantedTextRegex,\n PdfVerticalAlignment,\n PdfWordJoiner,\n PdfZeroWidthSpace,\n PdfZoomMode,\n PerfLogger,\n PermissionDeniedError,\n Rotation,\n STANDARD_FONT_FAMILIES,\n Task,\n TaskAbortedError,\n TaskRejectedError,\n TaskSequence,\n TaskStage,\n blendModeLabel,\n blendModeSelectOptions,\n blendModeToCss,\n blendModeValues,\n boundingRect,\n boundingRectOrEmpty,\n buildPermissions,\n buildUserToDeviceMatrix,\n calculateAngle,\n calculateDegree,\n calculateRotatedRectAABB,\n calculateRotatedRectAABBAroundPoint,\n combinePdfColorWithAlpha,\n combineWebColorWithOpacity,\n compareSearchTarget,\n cssToBlendMode,\n cssToTextAlignment,\n dateToPdfDate,\n deserializeLogger,\n expandRect,\n extractPdfColor,\n extractWebOpacity,\n fitSizeWithin,\n flagsToNames,\n getBlendModeInfo,\n getContrastStrokeColor,\n getImageMetadata,\n getRectCenter,\n getStandardFontDescriptor,\n getTextAlignmentInfo,\n ignore,\n inferRotationCenterFromRects,\n isUuidV4,\n isWidgetChecked,\n makeStandardFont,\n namesToFlags,\n normalizeAngle,\n pdfAlphaColorToWebAlphaColor,\n pdfAlphaToWebOpacity,\n pdfColorToWebColor,\n pdfDateToDate,\n quadToRect,\n rectEquals,\n rectFromPoints,\n rectToQuad,\n reduceBlendModes,\n reduceStandardFonts,\n reduceTextAlignments,\n restoreOffset,\n restorePosition,\n restoreRect,\n rotateAndTranslatePoint,\n rotatePointAround,\n rotatePosition,\n rotateRect,\n rotateVertices,\n scalePosition,\n scaleRect,\n serializeLogger,\n standardFontCss,\n standardFontCssProperties,\n standardFontFamily,\n standardFontFamilyLabel,\n standardFontFamilySelectOptions,\n standardFontIsBold,\n standardFontIsItalic,\n standardFontLabel,\n stripPdfUnwantedMarkers,\n swap,\n textAlignmentLabel,\n textAlignmentSelectOptions,\n textAlignmentToCss,\n toIntPos,\n toIntRect,\n toIntSize,\n transformPosition,\n transformRect,\n transformSize,\n uiBlendModeDisplay,\n unionFlags,\n uuidV4,\n webAlphaColorToPdfAlphaColor,\n webColorToPdfColor,\n webOpacityToPdfAlpha\n};\n//# sourceMappingURL=index.js.map\n","import { Rotation, PdfPermissionFlag, NoopLogger, PermissionDeniedError } from \"@embedpdf/models\";\nclass DependencyResolver {\n constructor() {\n this.dependencyGraph = /* @__PURE__ */ new Map();\n }\n addNode(id, dependencies = []) {\n this.dependencyGraph.set(id, new Set(dependencies));\n }\n hasCircularDependencies() {\n const visited = /* @__PURE__ */ new Set();\n const recursionStack = /* @__PURE__ */ new Set();\n const dfs = (id) => {\n visited.add(id);\n recursionStack.add(id);\n const dependencies = this.dependencyGraph.get(id) || /* @__PURE__ */ new Set();\n for (const dep of dependencies) {\n if (!visited.has(dep)) {\n if (dfs(dep)) return true;\n } else if (recursionStack.has(dep)) {\n return true;\n }\n }\n recursionStack.delete(id);\n return false;\n };\n for (const id of this.dependencyGraph.keys()) {\n if (!visited.has(id)) {\n if (dfs(id)) return true;\n }\n }\n return false;\n }\n resolveLoadOrder() {\n if (this.hasCircularDependencies()) {\n throw new Error(\"Circular dependencies detected\");\n }\n const result = [];\n const visited = /* @__PURE__ */ new Set();\n const temp = /* @__PURE__ */ new Set();\n const visit = (id) => {\n if (temp.has(id)) throw new Error(\"Circular dependency\");\n if (visited.has(id)) return;\n temp.add(id);\n const dependencies = this.dependencyGraph.get(id) || /* @__PURE__ */ new Set();\n for (const dep of dependencies) {\n visit(dep);\n }\n temp.delete(id);\n visited.add(id);\n result.push(id);\n };\n for (const id of this.dependencyGraph.keys()) {\n if (!visited.has(id)) {\n visit(id);\n }\n }\n return result;\n }\n}\nclass PluginRegistrationError extends Error {\n constructor(message) {\n super(message);\n this.name = \"PluginRegistrationError\";\n }\n}\nclass PluginNotFoundError extends Error {\n constructor(message) {\n super(message);\n this.name = \"PluginNotFoundError\";\n }\n}\nclass CircularDependencyError extends Error {\n constructor(message) {\n super(message);\n this.name = \"CircularDependencyError\";\n }\n}\nclass CapabilityNotFoundError extends Error {\n constructor(message) {\n super(message);\n this.name = \"CapabilityNotFoundError\";\n }\n}\nclass CapabilityConflictError extends Error {\n constructor(message) {\n super(message);\n this.name = \"CapabilityConflictError\";\n }\n}\nclass PluginInitializationError extends Error {\n constructor(message) {\n super(message);\n this.name = \"PluginInitializationError\";\n }\n}\nclass PluginConfigurationError extends Error {\n constructor(message) {\n super(message);\n this.name = \"PluginConfigurationError\";\n }\n}\nclass PluginStore {\n /**\n * Initializes the PluginStore with the main store and plugin ID.\n * @param store The main store instance.\n * @param pluginId The unique identifier for the plugin.\n */\n constructor(store, pluginId) {\n this.store = store;\n this.pluginId = pluginId;\n }\n /**\n * Gets the current state of the plugin.\n * @returns The plugin's state.\n */\n getState() {\n return this.store.getState().plugins[this.pluginId];\n }\n /**\n * Dispatches an action for the plugin and returns the *new* global state.\n * If you only need the plugin’s updated state, call `getState()` afterward.\n * @param action The action to dispatch.\n * @returns The updated global store state (after plugin reducer).\n */\n dispatch(action) {\n return this.store.dispatchToPlugin(this.pluginId, action);\n }\n /**\n * Subscribes to state changes only for this specific plugin.\n * You now receive (action, newPluginState, oldPluginState) in the callback.\n *\n * @param listener The callback to invoke when plugin state changes.\n * @returns A function to unsubscribe the listener.\n */\n subscribeToState(listener) {\n return this.store.subscribeToPlugin(this.pluginId, (action, newPluginState, oldPluginState) => {\n listener(\n action,\n newPluginState,\n oldPluginState\n );\n });\n }\n /**\n * Subscribes to a specific action type for the plugin.\n * This still uses the main store's `onAction`, so you get the *global*\n * old/new store states there. If you specifically want old/new plugin state,\n * use `subscribeToState` instead.\n *\n * @param type The action type to listen for.\n * @param handler The callback to invoke when the action occurs.\n * @returns A function to unsubscribe the handler.\n */\n onAction(type, handler) {\n return this.store.onAction(type, (action, state, oldState) => {\n handler(\n action,\n state.plugins[this.pluginId],\n oldState.plugins[this.pluginId]\n );\n });\n }\n}\nconst START_LOADING_DOCUMENT = \"START_LOADING_DOCUMENT\";\nconst UPDATE_DOCUMENT_LOADING_PROGRESS = \"UPDATE_DOCUMENT_LOADING_PROGRESS\";\nconst SET_DOCUMENT_LOADED = \"SET_DOCUMENT_LOADED\";\nconst SET_DOCUMENT_ERROR = \"SET_DOCUMENT_ERROR\";\nconst RETRY_LOADING_DOCUMENT = \"RETRY_LOADING_DOCUMENT\";\nconst CLOSE_DOCUMENT = \"CLOSE_DOCUMENT\";\nconst SET_ACTIVE_DOCUMENT = \"SET_ACTIVE_DOCUMENT\";\nconst REORDER_DOCUMENTS = \"REORDER_DOCUMENTS\";\nconst MOVE_DOCUMENT = \"MOVE_DOCUMENT\";\nconst UPDATE_DOCUMENT_SECURITY = \"UPDATE_DOCUMENT_SECURITY\";\nconst REFRESH_DOCUMENT = \"REFRESH_DOCUMENT\";\nconst REFRESH_PAGES = \"REFRESH_PAGES\";\nconst SET_PAGES = \"SET_PAGES\";\nconst SET_SCALE = \"SET_SCALE\";\nconst SET_ROTATION = \"SET_ROTATION\";\nconst SET_DEFAULT_SCALE = \"SET_DEFAULT_SCALE\";\nconst SET_DEFAULT_ROTATION = \"SET_DEFAULT_ROTATION\";\nconst CORE_ACTION_TYPES = [\n START_LOADING_DOCUMENT,\n UPDATE_DOCUMENT_LOADING_PROGRESS,\n SET_DOCUMENT_LOADED,\n CLOSE_DOCUMENT,\n SET_ACTIVE_DOCUMENT,\n SET_DOCUMENT_ERROR,\n RETRY_LOADING_DOCUMENT,\n REFRESH_DOCUMENT,\n REFRESH_PAGES,\n SET_PAGES,\n SET_SCALE,\n SET_ROTATION,\n SET_DEFAULT_SCALE,\n SET_DEFAULT_ROTATION,\n REORDER_DOCUMENTS,\n MOVE_DOCUMENT,\n UPDATE_DOCUMENT_SECURITY\n];\nconst startLoadingDocument = (documentId, name, scale, rotation, passwordProvided, autoActivate, permissions) => ({\n type: START_LOADING_DOCUMENT,\n payload: { documentId, name, scale, rotation, passwordProvided, autoActivate, permissions }\n});\nconst updateDocumentLoadingProgress = (documentId, progress) => ({\n type: UPDATE_DOCUMENT_LOADING_PROGRESS,\n payload: { documentId, progress }\n});\nconst setDocumentLoaded = (documentId, document) => ({\n type: SET_DOCUMENT_LOADED,\n payload: { documentId, document }\n});\nconst setDocumentError = (documentId, error, errorCode, errorDetails) => ({\n type: SET_DOCUMENT_ERROR,\n payload: { documentId, error, errorCode, errorDetails }\n});\nconst retryLoadingDocument = (documentId, passwordProvided) => ({\n type: RETRY_LOADING_DOCUMENT,\n payload: { documentId, passwordProvided }\n});\nconst closeDocument = (documentId, nextActiveDocumentId) => ({\n type: CLOSE_DOCUMENT,\n payload: { documentId, nextActiveDocumentId }\n});\nconst setActiveDocument = (documentId) => ({\n type: SET_ACTIVE_DOCUMENT,\n payload: documentId\n});\nconst refreshDocument = (documentId, document) => ({\n type: REFRESH_DOCUMENT,\n payload: { documentId, document }\n});\nconst refreshPages = (documentId, pageIndexes) => ({\n type: REFRESH_PAGES,\n payload: { documentId, pageIndexes }\n});\nconst setPages = (documentId, pages) => ({\n type: SET_PAGES,\n payload: { documentId, pages }\n});\nconst setScale = (scale, documentId) => ({\n type: SET_SCALE,\n payload: { scale, documentId }\n});\nconst setRotation = (rotation, documentId) => ({\n type: SET_ROTATION,\n payload: { rotation, documentId }\n});\nconst setDefaultScale = (scale) => ({\n type: SET_DEFAULT_SCALE,\n payload: scale\n});\nconst setDefaultRotation = (rotation) => ({\n type: SET_DEFAULT_ROTATION,\n payload: rotation\n});\nconst reorderDocuments = (order) => ({\n type: REORDER_DOCUMENTS,\n payload: order\n});\nconst moveDocument = (documentId, toIndex) => ({\n type: MOVE_DOCUMENT,\n payload: { documentId, toIndex }\n});\nconst updateDocumentSecurity = (documentId, permissions, isOwnerUnlocked) => ({\n type: UPDATE_DOCUMENT_SECURITY,\n payload: { documentId, permissions, isOwnerUnlocked }\n});\nclass Store {\n /**\n * Initializes the store with the provided core state.\n * @param reducer The core reducer function\n * @param initialCoreState The initial core state\n */\n constructor(reducer, initialCoreState2) {\n this.initialCoreState = initialCoreState2;\n this.pluginReducers = {};\n this.listeners = [];\n this.pluginListeners = {};\n this.isDispatching = false;\n this.state = { core: initialCoreState2, plugins: {} };\n this.coreReducer = reducer;\n }\n /**\n * Adds a reducer for a plugin-specific state.\n * @param pluginId The unique identifier for the plugin.\n * @param reducer The reducer function for the plugin state.\n * @param initialState The initial state for the plugin.\n */\n addPluginReducer(pluginId, reducer, initialState) {\n this.state.plugins[pluginId] = initialState;\n this.pluginReducers[pluginId] = reducer;\n }\n /**\n * Dispatches an action *only* to the core reducer.\n * Notifies the global store listeners with (action, newState, oldState).\n *\n * @param action The action to dispatch, typed as CoreAction\n * @returns The updated *global* store state\n */\n dispatchToCore(action) {\n if (!this.coreReducer) {\n return this.getState();\n }\n if (this.isDispatching) {\n throw new Error(\n \"Reducers may not dispatch actions. To trigger cascading actions, dispatch from a listener callback instead.\"\n );\n }\n const oldState = this.getState();\n try {\n this.isDispatching = true;\n this.state.core = this.coreReducer(this.state.core, action);\n } finally {\n this.isDispatching = false;\n }\n this.listeners.forEach((listener) => {\n const currentState = this.getState();\n listener(action, currentState, oldState);\n });\n return this.getState();\n }\n /**\n * Dispatches an action *only* to a specific plugin.\n * Optionally notifies global store listeners if `notifyGlobal` is true.\n * Always notifies plugin-specific listeners with (action, newPluginState, oldPluginState).\n *\n * @param pluginId The plugin identifier\n * @param action The plugin action to dispatch\n * @param notifyGlobal Whether to also notify global store listeners\n * @returns The updated plugin state\n */\n dispatchToPlugin(pluginId, action, notifyGlobal = true) {\n if (this.isDispatching) {\n throw new Error(\n \"Reducers may not dispatch actions. To trigger cascading actions, dispatch from a listener callback instead.\"\n );\n }\n const oldGlobalState = this.getState();\n const reducer = this.pluginReducers[pluginId];\n if (!reducer) {\n return oldGlobalState.plugins[pluginId];\n }\n const oldPluginState = oldGlobalState.plugins[pluginId];\n try {\n this.isDispatching = true;\n const newPluginState = reducer(oldPluginState, action);\n this.state.plugins[pluginId] = newPluginState;\n } finally {\n this.isDispatching = false;\n }\n if (notifyGlobal) {\n this.listeners.forEach((listener) => {\n const currentGlobalState = this.getState();\n listener(action, currentGlobalState, oldGlobalState);\n });\n }\n if (this.pluginListeners[pluginId]) {\n this.pluginListeners[pluginId].forEach((listener) => {\n const currentPluginState = this.getState().plugins[pluginId];\n listener(action, currentPluginState, oldPluginState);\n });\n }\n return this.getState().plugins[pluginId];\n }\n /**\n * Dispatches an action to update the state using:\n * - the core reducer (if it's a CoreAction)\n * - *all* plugin reducers (regardless of action type), with no global notify for each plugin\n *\n * Returns the new *global* store state after all reducers have processed the action.\n *\n * @param action The action to dispatch (can be CoreAction or any Action).\n */\n dispatch(action) {\n if (this.isDispatching) {\n throw new Error(\n \"Reducers may not dispatch actions. To trigger cascading actions, dispatch from a listener callback instead.\"\n );\n }\n const oldState = this.getState();\n try {\n this.isDispatching = true;\n if (this.isCoreAction(action)) {\n this.state.core = this.coreReducer(this.state.core, action);\n }\n for (const pluginId in this.pluginReducers) {\n const reducer = this.pluginReducers[pluginId];\n const oldPluginState = oldState.plugins[pluginId];\n if (reducer) {\n this.state.plugins[pluginId] = reducer(oldPluginState, action);\n }\n }\n } finally {\n this.isDispatching = false;\n }\n this.listeners.forEach((listener) => {\n const currentState = this.getState();\n listener(action, currentState, oldState);\n });\n return this.getState();\n }\n /**\n * Returns a shallow copy of the current state.\n * @returns The current store state.\n */\n getState() {\n if (this.isDispatching) {\n throw new Error(\n \"You may not call store.getState() while the reducer is executing. The reducer has already received the state as an argument. Pass it down from the top reducer instead of reading it from the store.\"\n );\n }\n return {\n core: { ...this.state.core },\n plugins: { ...this.state.plugins }\n };\n }\n /**\n * Subscribes a listener to *global* state changes.\n * The callback signature is now (action, newState, oldState).\n *\n * @param listener The callback to invoke on state changes\n * @returns A function to unsubscribe the listener\n */\n subscribe(listener) {\n if (this.isDispatching) {\n throw new Error(\n \"You may not call store.subscribe() while the reducer is executing. If you would like to be notified after the store has been updated, subscribe from a component and invoke store.getState() in the callback to access the latest state.\"\n );\n }\n this.listeners.push(listener);\n return () => {\n if (this.isDispatching) {\n throw new Error(\n \"You may not unsubscribe from a store listener while the reducer is executing.\"\n );\n }\n this.listeners = this.listeners.filter((l) => l !== listener);\n };\n }\n /**\n * Subscribes a listener to *plugin-specific* state changes.\n * The callback signature is now (action, newPluginState, oldPluginState).\n *\n * @param pluginId The unique identifier for the plugin.\n * @param listener The callback to invoke on plugin state changes.\n * @returns A function to unsubscribe the listener.\n */\n subscribeToPlugin(pluginId, listener) {\n if (!(pluginId in this.state.plugins)) {\n throw new Error(\n `Plugin state not found for plugin \"${pluginId}\". Did you forget to call addPluginReducer?`\n );\n }\n if (this.isDispatching) {\n throw new Error(\"You may not call store.subscribeToPlugin() while the reducer is executing.\");\n }\n if (!this.pluginListeners[pluginId]) {\n this.pluginListeners[pluginId] = [];\n }\n this.pluginListeners[pluginId].push(listener);\n return () => {\n if (this.isDispatching) {\n throw new Error(\n \"You may not unsubscribe from a store listener while the reducer is executing.\"\n );\n }\n this.pluginListeners[pluginId] = this.pluginListeners[pluginId].filter((l) => l !== listener);\n if (this.pluginListeners[pluginId].length === 0) {\n delete this.pluginListeners[pluginId];\n }\n };\n }\n /**\n * Subscribes to a specific action type (only from the core's action union).\n * The callback signature is (action, newState, oldState).\n *\n * @param type The action type to listen for.\n * @param handler The callback to invoke when the action occurs.\n * @returns A function to unsubscribe the handler.\n */\n onAction(type, handler) {\n return this.subscribe((action, newState, oldState) => {\n if (action.type === type) {\n handler(action, newState, oldState);\n }\n });\n }\n /**\n * Gets a PluginStore handle for a specific plugin.\n * @param pluginId The unique identifier for the plugin.\n * @returns A PluginStore instance for the plugin.\n */\n getPluginStore(pluginId) {\n if (!(pluginId in this.state.plugins)) {\n throw new Error(\n `Plugin state not found for plugin \"${pluginId}\". Did you forget to call addPluginReducer?`\n );\n }\n return new PluginStore(this, pluginId);\n }\n /**\n * Helper method to check if an action is a CoreAction.\n * Adjust if you have a more refined way to differentiate CoreAction vs. any other Action.\n */\n isCoreAction(action) {\n return CORE_ACTION_TYPES.includes(action.type);\n }\n /**\n * Destroy the store: drop every listener and plugin reducer\n */\n destroy() {\n var _a, _b;\n this.listeners.length = 0;\n for (const id in this.pluginListeners) {\n (_b = (_a = this.pluginListeners[id]) == null ? void 0 : _a.splice) == null ? void 0 : _b.call(_a, 0);\n }\n this.pluginListeners = {};\n this.pluginReducers = {};\n this.state.plugins = {};\n this.state.core = { ...this.initialCoreState };\n }\n}\nconst initialCoreState = (config) => ({\n documents: {},\n documentOrder: [],\n activeDocumentId: null,\n defaultScale: (config == null ? void 0 : config.defaultScale) ?? 1,\n defaultRotation: (config == null ? void 0 : config.defaultRotation) ?? Rotation.Degree0,\n globalPermissions: config == null ? void 0 : config.permissions\n});\nconst PERMISSION_NAME_TO_FLAG = {\n print: PdfPermissionFlag.Print,\n modifyContents: PdfPermissionFlag.ModifyContents,\n copyContents: PdfPermissionFlag.CopyContents,\n modifyAnnotations: PdfPermissionFlag.ModifyAnnotations,\n fillForms: PdfPermissionFlag.FillForms,\n extractForAccessibility: PdfPermissionFlag.ExtractForAccessibility,\n assembleDocument: PdfPermissionFlag.AssembleDocument,\n printHighQuality: PdfPermissionFlag.PrintHighQuality\n};\nconst ALL_PERMISSION_FLAGS = [\n PdfPermissionFlag.Print,\n PdfPermissionFlag.ModifyContents,\n PdfPermissionFlag.CopyContents,\n PdfPermissionFlag.ModifyAnnotations,\n PdfPermissionFlag.FillForms,\n PdfPermissionFlag.ExtractForAccessibility,\n PdfPermissionFlag.AssembleDocument,\n PdfPermissionFlag.PrintHighQuality\n];\nconst ALL_PERMISSION_NAMES = [\n \"print\",\n \"modifyContents\",\n \"copyContents\",\n \"modifyAnnotations\",\n \"fillForms\",\n \"extractForAccessibility\",\n \"assembleDocument\",\n \"printHighQuality\"\n];\nconst PERMISSION_FLAG_TO_NAME = {\n [PdfPermissionFlag.Print]: \"print\",\n [PdfPermissionFlag.ModifyContents]: \"modifyContents\",\n [PdfPermissionFlag.CopyContents]: \"copyContents\",\n [PdfPermissionFlag.ModifyAnnotations]: \"modifyAnnotations\",\n [PdfPermissionFlag.FillForms]: \"fillForms\",\n [PdfPermissionFlag.ExtractForAccessibility]: \"extractForAccessibility\",\n [PdfPermissionFlag.AssembleDocument]: \"assembleDocument\",\n [PdfPermissionFlag.PrintHighQuality]: \"printHighQuality\"\n};\nfunction getPermissionOverride(overrides, flag) {\n if (!overrides) return void 0;\n if (flag in overrides) {\n return overrides[flag];\n }\n const name = PERMISSION_FLAG_TO_NAME[flag];\n if (name && name in overrides) {\n return overrides[name];\n }\n return void 0;\n}\nconst getActiveDocumentState = (state) => {\n if (!state.activeDocumentId) return null;\n return state.documents[state.activeDocumentId] ?? null;\n};\nconst getDocumentState = (state, documentId) => {\n return state.documents[documentId] ?? null;\n};\nconst getDocumentIds = (state) => {\n return Object.keys(state.documents);\n};\nconst isDocumentLoaded = (state, documentId) => {\n return !!state.documents[documentId];\n};\nconst getDocumentCount = (state) => {\n return Object.keys(state.documents).length;\n};\nfunction getEffectivePermission(state, documentId, flag) {\n var _a;\n const docState = state.documents[documentId];\n const docConfig = docState == null ? void 0 : docState.permissions;\n const globalConfig = state.globalPermissions;\n const pdfPermissions = ((_a = docState == null ? void 0 : docState.document) == null ? void 0 : _a.permissions) ?? PdfPermissionFlag.AllowAll;\n const docOverride = getPermissionOverride(docConfig == null ? void 0 : docConfig.overrides, flag);\n if (docOverride !== void 0) {\n return docOverride;\n }\n const globalOverride = getPermissionOverride(globalConfig == null ? void 0 : globalConfig.overrides, flag);\n if (globalOverride !== void 0) {\n return globalOverride;\n }\n const enforce = (docConfig == null ? void 0 : docConfig.enforceDocumentPermissions) ?? (globalConfig == null ? void 0 : globalConfig.enforceDocumentPermissions) ?? true;\n if (!enforce) return true;\n return (pdfPermissions & flag) !== 0;\n}\nfunction getEffectivePermissions(state, documentId) {\n return ALL_PERMISSION_FLAGS.reduce((acc, flag) => {\n return getEffectivePermission(state, documentId, flag) ? acc | flag : acc;\n }, 0);\n}\nfunction calculateNextActiveDocument(state, closingDocumentId, explicitNext) {\n const currentActiveId = state.activeDocumentId;\n if (currentActiveId !== closingDocumentId) {\n return currentActiveId;\n }\n if (explicitNext !== void 0) {\n return explicitNext && state.documents[explicitNext] ? explicitNext : null;\n }\n const closingIndex = state.documentOrder.indexOf(closingDocumentId);\n if (closingIndex === -1) {\n return null;\n }\n if (closingIndex > 0) {\n return state.documentOrder[closingIndex - 1];\n }\n if (closingIndex < state.documentOrder.length - 1) {\n return state.documentOrder[closingIndex + 1];\n }\n return null;\n}\nfunction moveDocumentInOrder(currentOrder, documentId, toIndex) {\n const fromIndex = currentOrder.indexOf(documentId);\n if (fromIndex === -1) return null;\n if (toIndex < 0 || toIndex >= currentOrder.length) return null;\n if (fromIndex === toIndex) return null;\n const newOrder = [...currentOrder];\n newOrder.splice(fromIndex, 1);\n newOrder.splice(toIndex, 0, documentId);\n return newOrder;\n}\nconst coreReducer = (state, action) => {\n switch (action.type) {\n case START_LOADING_DOCUMENT: {\n const {\n documentId,\n name,\n scale,\n rotation,\n passwordProvided,\n autoActivate = true,\n permissions\n } = action.payload;\n const newDocState = {\n id: documentId,\n name,\n status: \"loading\",\n loadingProgress: 0,\n error: null,\n document: null,\n scale: scale ?? state.defaultScale,\n rotation: rotation ?? state.defaultRotation,\n passwordProvided: passwordProvided ?? false,\n pageRefreshVersions: {},\n permissions,\n loadStartedAt: Date.now()\n };\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: newDocState\n },\n documentOrder: [...state.documentOrder, documentId],\n // Only activate if autoActivate is true (default), or if no document is currently active\n activeDocumentId: autoActivate || !state.activeDocumentId ? documentId : state.activeDocumentId\n };\n }\n case UPDATE_DOCUMENT_LOADING_PROGRESS: {\n const { documentId, progress } = action.payload;\n const docState = state.documents[documentId];\n if (!docState || docState.status !== \"loading\") return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...docState,\n loadingProgress: progress\n }\n }\n };\n }\n case SET_DOCUMENT_LOADED: {\n const { documentId, document } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...docState,\n status: \"loaded\",\n document,\n error: null,\n errorCode: void 0,\n errorDetails: void 0,\n passwordProvided: void 0,\n loadedAt: Date.now()\n }\n }\n };\n }\n case SET_DOCUMENT_ERROR: {\n const { documentId, error, errorCode, errorDetails } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...docState,\n status: \"error\",\n error,\n errorCode,\n errorDetails\n }\n }\n };\n }\n case RETRY_LOADING_DOCUMENT: {\n const { documentId, passwordProvided } = action.payload;\n const docState = state.documents[documentId];\n if (!docState || docState.status !== \"error\") return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...docState,\n status: \"loading\",\n loadingProgress: 0,\n error: null,\n errorCode: void 0,\n errorDetails: void 0,\n passwordProvided: passwordProvided ?? false,\n loadStartedAt: Date.now()\n }\n }\n };\n }\n case CLOSE_DOCUMENT: {\n const { documentId, nextActiveDocumentId } = action.payload;\n const { [documentId]: removed, ...remainingDocs } = state.documents;\n return {\n ...state,\n documents: remainingDocs,\n documentOrder: state.documentOrder.filter((id) => id !== documentId),\n activeDocumentId: calculateNextActiveDocument(state, documentId, nextActiveDocumentId)\n };\n }\n case MOVE_DOCUMENT: {\n const { documentId, toIndex } = action.payload;\n const newOrder = moveDocumentInOrder(state.documentOrder, documentId, toIndex);\n if (!newOrder) return state;\n return {\n ...state,\n documentOrder: newOrder\n };\n }\n case REORDER_DOCUMENTS: {\n return {\n ...state,\n documentOrder: action.payload\n };\n }\n case SET_ACTIVE_DOCUMENT: {\n return {\n ...state,\n activeDocumentId: action.payload\n };\n }\n case SET_SCALE: {\n const { scale, documentId } = action.payload;\n const targetId = documentId ?? state.activeDocumentId;\n if (!targetId) return state;\n const docState = state.documents[targetId];\n if (!docState) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [targetId]: {\n ...docState,\n scale\n }\n }\n };\n }\n case SET_ROTATION: {\n const { rotation, documentId } = action.payload;\n const targetId = documentId ?? state.activeDocumentId;\n if (!targetId) return state;\n const docState = state.documents[targetId];\n if (!docState) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [targetId]: {\n ...docState,\n rotation\n }\n }\n };\n }\n case REFRESH_PAGES: {\n const { documentId, pageIndexes } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n const newVersions = { ...docState.pageRefreshVersions };\n for (const pageIndex of pageIndexes) {\n newVersions[pageIndex] = (newVersions[pageIndex] || 0) + 1;\n }\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...docState,\n pageRefreshVersions: newVersions\n }\n }\n };\n }\n case UPDATE_DOCUMENT_SECURITY: {\n const { documentId, permissions, isOwnerUnlocked } = action.payload;\n const docState = state.documents[documentId];\n if (!(docState == null ? void 0 : docState.document)) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...docState,\n document: {\n ...docState.document,\n permissions,\n isOwnerUnlocked\n }\n }\n }\n };\n }\n default:\n return state;\n }\n};\nclass PluginRegistry {\n constructor(engine, config) {\n this.plugins = /* @__PURE__ */ new Map();\n this.manifests = /* @__PURE__ */ new Map();\n this.capabilities = /* @__PURE__ */ new Map();\n this.status = /* @__PURE__ */ new Map();\n this.configurations = /* @__PURE__ */ new Map();\n this.initPromise = null;\n this.pendingRegistrations = [];\n this.processingRegistrations = [];\n this.initialized = false;\n this.isInitializing = false;\n this.pluginsReadyPromise = null;\n this.destroyed = false;\n this.resolver = new DependencyResolver();\n this.engine = engine;\n this.initialCoreState = initialCoreState(config);\n this.store = new Store(coreReducer, this.initialCoreState);\n this.logger = (config == null ? void 0 : config.logger) ?? new NoopLogger();\n }\n /**\n * Get the logger instance\n */\n getLogger() {\n return this.logger;\n }\n /**\n * Register a plugin without initializing it\n */\n registerPlugin(pluginPackage, config) {\n if (this.initialized && !this.isInitializing) {\n throw new PluginRegistrationError(\"Cannot register plugins after initialization\");\n }\n this.validateManifest(pluginPackage.manifest);\n this.store.addPluginReducer(\n pluginPackage.manifest.id,\n // We need one type assertion here since we can't fully reconcile TAction with Action\n // due to TypeScript's type system limitations with generic variance\n pluginPackage.reducer,\n \"function\" === typeof pluginPackage.initialState ? pluginPackage.initialState(\n this.initialCoreState,\n {\n ...pluginPackage.manifest.defaultConfig,\n ...config\n }\n ) : pluginPackage.initialState\n );\n this.pendingRegistrations.push({\n package: pluginPackage,\n config\n });\n }\n /**\n * Get the central store instance\n */\n getStore() {\n return this.store;\n }\n /**\n * Get the engine instance\n */\n getEngine() {\n return this.engine;\n }\n /**\n * Get a promise that resolves when all plugins are ready\n */\n pluginsReady() {\n if (this.pluginsReadyPromise) {\n return this.pluginsReadyPromise;\n }\n this.pluginsReadyPromise = (async () => {\n if (!this.initialized) {\n await this.initialize();\n }\n const readyPromises = Array.from(this.plugins.values()).map(\n (p) => typeof p.ready === \"function\" ? p.ready() : Promise.resolve()\n );\n await Promise.all(readyPromises);\n })();\n return this.pluginsReadyPromise;\n }\n /**\n * INITIALISE THE REGISTRY – runs once no-matter-how-many calls *\n */\n async initialize() {\n if (this.destroyed) {\n throw new PluginRegistrationError(\"Registry has been destroyed\");\n }\n if (this.initPromise) {\n return this.initPromise;\n }\n this.initPromise = (async () => {\n if (this.initialized) {\n throw new PluginRegistrationError(\"Registry is already initialized\");\n }\n this.isInitializing = true;\n try {\n if (this.destroyed) return;\n while (this.pendingRegistrations.length > 0) {\n if (this.destroyed) return;\n this.processingRegistrations = [...this.pendingRegistrations];\n this.pendingRegistrations = [];\n for (const reg of this.processingRegistrations) {\n const dependsOn = /* @__PURE__ */ new Set();\n const allDeps = [...reg.package.manifest.requires, ...reg.package.manifest.optional];\n for (const cap of allDeps) {\n const provider = this.processingRegistrations.find(\n (r) => r.package.manifest.provides.includes(cap)\n );\n if (provider) {\n dependsOn.add(provider.package.manifest.id);\n }\n }\n this.resolver.addNode(reg.package.manifest.id, [...dependsOn]);\n }\n const loadOrder = this.resolver.resolveLoadOrder();\n for (const id of loadOrder) {\n const reg = this.processingRegistrations.find((r) => r.package.manifest.id === id);\n this.instantiatePlugin(reg.package.manifest, reg.package.create, reg.config);\n }\n for (const id of loadOrder) {\n await this.runPluginInitialization(id);\n }\n this.processingRegistrations = [];\n this.resolver = new DependencyResolver();\n }\n this.initialized = true;\n } catch (err) {\n if (err instanceof Error) {\n throw new CircularDependencyError(\n `Failed to resolve plugin dependencies: ${err.message}`\n );\n }\n throw err;\n } finally {\n this.isInitializing = false;\n }\n })();\n return this.initPromise;\n }\n /**\n * Phase 2: Create instance and register capabilities\n */\n instantiatePlugin(manifest, packageCreator, config) {\n const finalConfig = {\n ...manifest.defaultConfig,\n ...config\n };\n this.validateConfig(manifest.id, finalConfig, manifest.defaultConfig);\n const plugin = packageCreator(this, finalConfig);\n this.validatePlugin(plugin);\n for (const capability of manifest.provides) {\n if (this.capabilities.has(capability)) {\n throw new PluginRegistrationError(\n `Capability ${capability} is already provided by plugin ${this.capabilities.get(capability)}`\n );\n }\n this.capabilities.set(capability, manifest.id);\n }\n this.plugins.set(manifest.id, plugin);\n this.manifests.set(manifest.id, manifest);\n this.status.set(manifest.id, \"registered\");\n this.configurations.set(manifest.id, finalConfig);\n }\n /**\n * Phase 3: Run the initialize method\n */\n async runPluginInitialization(pluginId) {\n const plugin = this.plugins.get(pluginId);\n if (!plugin) return;\n const manifest = this.manifests.get(pluginId);\n const config = this.configurations.get(pluginId);\n for (const capability of manifest.requires) {\n if (!this.capabilities.has(capability)) {\n throw new PluginRegistrationError(\n `Missing required capability: ${capability} for plugin ${pluginId}`\n );\n }\n }\n this.logger.debug(\"PluginRegistry\", \"InitializePlugin\", `Initializing plugin ${pluginId}`);\n try {\n if (plugin.initialize) {\n await plugin.initialize(config);\n }\n this.status.set(pluginId, \"active\");\n this.logger.info(\n \"PluginRegistry\",\n \"PluginInitialized\",\n `Plugin ${pluginId} initialized successfully`\n );\n } catch (error) {\n this.status.set(pluginId, \"error\");\n this.logger.error(\n \"PluginRegistry\",\n \"InitializationFailed\",\n `Plugin ${pluginId} initialization failed`,\n { error }\n );\n throw error;\n }\n }\n getPluginConfig(pluginId) {\n const config = this.configurations.get(pluginId);\n if (!config) {\n throw new PluginNotFoundError(`Configuration for plugin ${pluginId} not found`);\n }\n return config;\n }\n validateConfig(pluginId, config, defaultConfig) {\n const requiredKeys = Object.keys(defaultConfig);\n const missingKeys = requiredKeys.filter((key) => !config.hasOwnProperty(key));\n if (missingKeys.length > 0) {\n throw new PluginConfigurationError(\n `Missing required configuration keys for plugin ${pluginId}: ${missingKeys.join(\", \")}`\n );\n }\n }\n async updatePluginConfig(pluginId, config) {\n const plugin = this.getPlugin(pluginId);\n if (!plugin) {\n throw new PluginNotFoundError(`Plugin ${pluginId} not found`);\n }\n const manifest = this.manifests.get(pluginId);\n const currentConfig = this.configurations.get(pluginId);\n if (!manifest || !currentConfig) {\n throw new PluginNotFoundError(`Plugin ${pluginId} not found`);\n }\n const newConfig = {\n ...currentConfig,\n ...config\n };\n this.validateConfig(pluginId, newConfig, manifest.defaultConfig);\n this.configurations.set(pluginId, newConfig);\n if (plugin.initialize) {\n await plugin.initialize(newConfig);\n }\n }\n /**\n * Register multiple plugins at once\n */\n registerPluginBatch(registrations) {\n for (const reg of registrations) {\n this.registerPlugin(reg.package, reg.config);\n }\n }\n /**\n * Unregister a plugin\n */\n async unregisterPlugin(pluginId) {\n const plugin = this.plugins.get(pluginId);\n if (!plugin) {\n throw new PluginNotFoundError(`Plugin ${pluginId} is not registered`);\n }\n const manifest = this.manifests.get(pluginId);\n if (!manifest) {\n throw new PluginNotFoundError(`Manifest for plugin ${pluginId} not found`);\n }\n for (const [otherId, otherManifest] of this.manifests.entries()) {\n if (otherId === pluginId) continue;\n const dependsOnThis = [...otherManifest.requires, ...otherManifest.optional].some(\n (cap) => manifest.provides.includes(cap)\n );\n if (dependsOnThis) {\n throw new PluginRegistrationError(\n `Cannot unregister plugin ${pluginId}: plugin ${otherId} depends on it`\n );\n }\n }\n try {\n if (plugin.destroy) {\n await plugin.destroy();\n }\n for (const capability of manifest.provides) {\n this.capabilities.delete(capability);\n }\n this.plugins.delete(pluginId);\n this.manifests.delete(pluginId);\n this.status.delete(pluginId);\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to unregister plugin ${pluginId}: ${error.message}`);\n }\n throw error;\n }\n }\n /**\n * Get a plugin instance\n * @param pluginId The ID of the plugin to get\n * @returns The plugin instance or null if not found\n */\n getPlugin(pluginId) {\n const plugin = this.plugins.get(pluginId);\n if (!plugin) {\n return null;\n }\n return plugin;\n }\n /**\n * Get a plugin that provides a specific capability\n * @param capability The capability to get a provider for\n * @returns The plugin providing the capability or null if not found\n */\n getCapabilityProvider(capability) {\n const pluginId = this.capabilities.get(capability);\n if (!pluginId) {\n return null;\n }\n return this.getPlugin(pluginId);\n }\n /**\n * Check if a capability is available\n */\n hasCapability(capability) {\n return this.capabilities.has(capability);\n }\n /**\n * Get all registered plugins\n */\n getAllPlugins() {\n return Array.from(this.plugins.values());\n }\n /**\n * Get plugin status\n */\n getPluginStatus(pluginId) {\n const status = this.status.get(pluginId);\n if (!status) {\n throw new PluginNotFoundError(`Plugin ${pluginId} not found`);\n }\n return status;\n }\n /**\n * Validate plugin object\n */\n validatePlugin(plugin) {\n if (!plugin.id) {\n throw new PluginRegistrationError(\"Plugin must have an id\");\n }\n }\n /**\n * Validate plugin manifest\n */\n validateManifest(manifest) {\n if (!manifest.id) {\n throw new PluginRegistrationError(\"Manifest must have an id\");\n }\n if (!manifest.name) {\n throw new PluginRegistrationError(\"Manifest must have a name\");\n }\n if (!manifest.version) {\n throw new PluginRegistrationError(\"Manifest must have a version\");\n }\n if (!Array.isArray(manifest.provides)) {\n throw new PluginRegistrationError(\"Manifest must have a provides array\");\n }\n if (!Array.isArray(manifest.requires)) {\n throw new PluginRegistrationError(\"Manifest must have a requires array\");\n }\n if (!Array.isArray(manifest.optional)) {\n throw new PluginRegistrationError(\"Manifest must have an optional array\");\n }\n }\n isDestroyed() {\n return this.destroyed;\n }\n /**\n * DESTROY EVERYTHING – waits for any ongoing initialise(), once *\n */\n async destroy() {\n var _a;\n if (this.destroyed) throw new PluginRegistrationError(\"Registry has already been destroyed\");\n this.destroyed = true;\n try {\n await this.initPromise;\n } catch {\n }\n for (const plugin of Array.from(this.plugins.values()).reverse()) {\n await ((_a = plugin.destroy) == null ? void 0 : _a.call(plugin));\n }\n this.store.destroy();\n this.plugins.clear();\n this.manifests.clear();\n this.capabilities.clear();\n this.status.clear();\n this.pendingRegistrations.length = 0;\n this.processingRegistrations.length = 0;\n }\n}\nfunction createPluginRegistration(pluginPackage, config) {\n return {\n package: pluginPackage,\n config\n };\n}\nfunction hasAutoMountElements(pkg) {\n return \"autoMountElements\" in pkg && typeof pkg.autoMountElements === \"function\";\n}\nclass BasePlugin {\n constructor(id, registry) {\n this.id = id;\n this.registry = registry;\n this.cooldownActions = {};\n this.debouncedTimeouts = {};\n this.unsubscribeFromState = null;\n this.unsubscribeFromCoreStore = null;\n this.unsubscribeFromStartLoadingDocument = null;\n this.unsubscribeFromSetDocumentLoaded = null;\n this.unsubscribeFromCloseDocument = null;\n this.unsubscribeFromSetScale = null;\n this.unsubscribeFromSetRotation = null;\n if (id !== this.constructor.id) {\n throw new Error(\n `Plugin ID mismatch: ${id} !== ${this.constructor.id}`\n );\n }\n this.engine = this.registry.getEngine();\n this.logger = this.registry.getLogger();\n this.coreStore = this.registry.getStore();\n this.pluginStore = this.coreStore.getPluginStore(this.id);\n this.unsubscribeFromState = this.pluginStore.subscribeToState((action, newState, oldState) => {\n this.onStoreUpdated(oldState, newState);\n });\n this.unsubscribeFromCoreStore = this.coreStore.subscribe((action, newState, oldState) => {\n this.onCoreStoreUpdated(oldState, newState);\n if (newState.core.activeDocumentId !== oldState.core.activeDocumentId) {\n this.onActiveDocumentChanged(\n oldState.core.activeDocumentId,\n newState.core.activeDocumentId\n );\n }\n });\n this.unsubscribeFromStartLoadingDocument = this.coreStore.onAction(\n START_LOADING_DOCUMENT,\n (action) => {\n this.onDocumentLoadingStarted(action.payload.documentId);\n }\n );\n this.unsubscribeFromSetDocumentLoaded = this.coreStore.onAction(\n SET_DOCUMENT_LOADED,\n (action) => {\n this.onDocumentLoaded(action.payload.documentId);\n }\n );\n this.unsubscribeFromCloseDocument = this.coreStore.onAction(CLOSE_DOCUMENT, (action) => {\n this.onDocumentClosed(action.payload.documentId);\n });\n this.unsubscribeFromSetScale = this.coreStore.onAction(SET_SCALE, (action, state) => {\n const targetId = action.payload.documentId ?? state.core.activeDocumentId;\n if (targetId) {\n this.onScaleChanged(targetId, action.payload.scale);\n }\n });\n this.unsubscribeFromSetRotation = this.coreStore.onAction(SET_ROTATION, (action, state) => {\n const targetId = action.payload.documentId ?? state.core.activeDocumentId;\n if (targetId) {\n this.onRotationChanged(targetId, action.payload.rotation);\n }\n });\n this.readyPromise = new Promise((resolve) => {\n this.readyResolve = resolve;\n });\n this.readyResolve();\n }\n provides() {\n if (!this._capability) {\n const cap = this.buildCapability();\n this._capability = Object.freeze(cap);\n }\n return this._capability;\n }\n /**\n * Get a copy of the current state\n */\n get state() {\n return this.pluginStore.getState();\n }\n /**\n * Get a copy of the current core state\n */\n get coreState() {\n return this.coreStore.getState();\n }\n /**\n * @deprecated use `this.state` Get a copy of the current state\n */\n getState() {\n return this.pluginStore.getState();\n }\n /**\n * @deprecated use `this.coreState` Get a copy of the current core state\n */\n getCoreState() {\n return this.coreStore.getState();\n }\n /**\n * Core Dispatch\n */\n dispatchCoreAction(action) {\n return this.coreStore.dispatchToCore(action);\n }\n /**\n * Dispatch an action to all plugins\n */\n dispatchToAllPlugins(action) {\n return this.coreStore.dispatch(action);\n }\n /**\n * Dispatch an action\n */\n dispatch(action) {\n return this.pluginStore.dispatch(action);\n }\n /**\n * Dispatch an action with a cooldown to prevent rapid repeated calls\n * This executes immediately if cooldown has expired, then blocks subsequent calls\n * @param action The action to dispatch\n * @param cooldownTime Time in ms for cooldown (default: 100ms)\n * @returns boolean indicating whether the action was dispatched or blocked\n */\n cooldownDispatch(action, cooldownTime = 100) {\n const now = Date.now();\n const lastActionTime = this.cooldownActions[action.type] || 0;\n if (now - lastActionTime >= cooldownTime) {\n this.cooldownActions[action.type] = now;\n this.dispatch(action);\n return true;\n }\n return false;\n }\n /**\n * Dispatch an action with true debouncing - waits for the delay after the last call\n * Each new call resets the timer. Action only executes after no calls for the specified time.\n * @param action The action to dispatch\n * @param debounceTime Time in ms to wait after the last call\n */\n debouncedDispatch(action, debounceTime = 100) {\n const actionKey = action.type;\n if (this.debouncedTimeouts[actionKey]) {\n clearTimeout(this.debouncedTimeouts[actionKey]);\n }\n this.debouncedTimeouts[actionKey] = setTimeout(() => {\n this.dispatch(action);\n delete this.debouncedTimeouts[actionKey];\n }, debounceTime);\n }\n /**\n * Cancel a pending debounced action\n * @param actionType The action type to cancel\n */\n cancelDebouncedDispatch(actionType) {\n if (this.debouncedTimeouts[actionType]) {\n clearTimeout(this.debouncedTimeouts[actionType]);\n delete this.debouncedTimeouts[actionType];\n }\n }\n /**\n * Subscribe to state changes\n */\n subscribe(listener) {\n return this.pluginStore.subscribeToState(listener);\n }\n /**\n * Subscribe to core store changes\n */\n subscribeToCoreStore(listener) {\n return this.coreStore.subscribe(listener);\n }\n /**\n * Called when the plugin store state is updated\n * @param oldState Previous state\n * @param newState New state\n */\n onStoreUpdated(oldState, newState) {\n }\n /**\n * Called when the core store state is updated\n * @param oldState Previous state\n * @param newState New state\n */\n onCoreStoreUpdated(oldState, newState) {\n }\n /**\n * Called when a document is opened\n * Override to initialize per-document state\n * @param documentId The ID of the document that was opened\n */\n onDocumentLoadingStarted(documentId) {\n }\n /**\n * Called when a document is loaded\n * @param documentId The ID of the document that is loaded\n */\n onDocumentLoaded(documentId) {\n }\n /**\n * Called when a document is closed\n * Override to cleanup per-document state\n * @param documentId The ID of the document that was closed\n */\n onDocumentClosed(documentId) {\n }\n /**\n * Called when the active document changes\n * @param previousId The ID of the previous active document\n * @param currentId The ID of the new active document\n */\n onActiveDocumentChanged(previousId, currentId) {\n }\n onScaleChanged(documentId, scale) {\n }\n onRotationChanged(documentId, rotation) {\n }\n /**\n * Cleanup method to be called when plugin is being destroyed\n */\n destroy() {\n Object.values(this.debouncedTimeouts).forEach((timeout) => {\n clearTimeout(timeout);\n });\n this.debouncedTimeouts = {};\n if (this.unsubscribeFromState) {\n this.unsubscribeFromState();\n this.unsubscribeFromState = null;\n }\n if (this.unsubscribeFromCoreStore) {\n this.unsubscribeFromCoreStore();\n this.unsubscribeFromCoreStore = null;\n }\n if (this.unsubscribeFromStartLoadingDocument) {\n this.unsubscribeFromStartLoadingDocument();\n this.unsubscribeFromStartLoadingDocument = null;\n }\n if (this.unsubscribeFromSetDocumentLoaded) {\n this.unsubscribeFromSetDocumentLoaded();\n this.unsubscribeFromSetDocumentLoaded = null;\n }\n if (this.unsubscribeFromCloseDocument) {\n this.unsubscribeFromCloseDocument();\n this.unsubscribeFromCloseDocument = null;\n }\n if (this.unsubscribeFromSetScale) {\n this.unsubscribeFromSetScale();\n this.unsubscribeFromSetScale = null;\n }\n if (this.unsubscribeFromSetRotation) {\n this.unsubscribeFromSetRotation();\n this.unsubscribeFromSetRotation = null;\n }\n }\n /**\n * Returns a promise that resolves when the plugin is ready\n */\n ready() {\n return this.readyPromise;\n }\n /**\n * Mark the plugin as ready\n */\n markReady() {\n this.readyResolve();\n }\n /**\n * Reset the ready state (useful for plugins that need to reinitialize)\n */\n resetReady() {\n this.readyPromise = new Promise((resolve) => {\n this.readyResolve = resolve;\n });\n }\n /**\n * Get the active document ID\n * @throws Error if no active document exists\n */\n getActiveDocumentId() {\n const id = this.coreState.core.activeDocumentId;\n if (!id) {\n throw new Error(\"No active document\");\n }\n return id;\n }\n /**\n * Get the active document ID or null if none exists\n */\n getActiveDocumentIdOrNull() {\n return this.coreState.core.activeDocumentId;\n }\n /**\n * Get core document state for a specific document\n * @param documentId Document ID (optional, defaults to active document)\n * @returns Document state or null if not found\n */\n getCoreDocument(documentId) {\n const id = documentId ?? this.getActiveDocumentIdOrNull();\n if (!id) return null;\n return this.coreState.core.documents[id] ?? null;\n }\n /**\n * Get core document state for a specific document\n * @param documentId Document ID (optional, defaults to active document)\n * @throws Error if document not found\n */\n getCoreDocumentOrThrow(documentId) {\n const doc = this.getCoreDocument(documentId);\n if (!doc) {\n throw new Error(`Document not found: ${documentId ?? \"active\"}`);\n }\n return doc;\n }\n // ─────────────────────────────────────────────────────────\n // Permission Helpers\n // ─────────────────────────────────────────────────────────\n /**\n * Get the effective permission flags for a document.\n * Applies layered resolution: per-document override → global override → PDF permission.\n * Returns AllowAll if document not found.\n * @param documentId Document ID (optional, defaults to active document)\n */\n getDocumentPermissions(documentId) {\n const docId = documentId ?? this.coreState.core.activeDocumentId;\n if (!docId) return PdfPermissionFlag.AllowAll;\n return getEffectivePermissions(this.coreState.core, docId);\n }\n /**\n * Check if a document has the required permissions (returns boolean).\n * Applies layered resolution: per-document override → global override → PDF permission.\n * Useful for conditional UI logic.\n * @param documentId Document ID (optional, defaults to active document)\n * @param flags Permission flags to check\n */\n checkPermission(documentId, ...flags) {\n const docId = documentId ?? this.coreState.core.activeDocumentId;\n if (!docId) return true;\n return flags.every((flag) => getEffectivePermission(this.coreState.core, docId, flag));\n }\n /**\n * Assert that a document has the required permissions.\n * Applies layered resolution: per-document override → global override → PDF permission.\n * Throws PermissionDeniedError if any flag is missing.\n * @param documentId Document ID (optional, defaults to active document)\n * @param flags Permission flags to require\n */\n requirePermission(documentId, ...flags) {\n const docId = documentId ?? this.coreState.core.activeDocumentId;\n if (!docId) return;\n const missingFlags = [];\n for (const flag of flags) {\n if (!getEffectivePermission(this.coreState.core, docId, flag)) {\n missingFlags.push(flag);\n }\n }\n if (missingFlags.length > 0) {\n const effectivePermissions = getEffectivePermissions(this.coreState.core, docId);\n throw new PermissionDeniedError(missingFlags, effectivePermissions);\n }\n }\n}\nclass EventControl {\n constructor(handler, options) {\n this.handler = handler;\n this.options = options;\n this.lastRun = 0;\n this.handle = (data) => {\n if (this.options.mode === \"debounce\") {\n this.debounce(data);\n } else {\n this.throttle(data);\n }\n };\n }\n debounce(data) {\n if (this.timeoutId) {\n window.clearTimeout(this.timeoutId);\n }\n this.timeoutId = window.setTimeout(() => {\n this.handler(data);\n this.timeoutId = void 0;\n }, this.options.wait);\n }\n throttle(data) {\n if (this.options.mode === \"debounce\") return;\n const now = Date.now();\n const throttleMode = this.options.throttleMode || \"leading-trailing\";\n if (now - this.lastRun >= this.options.wait) {\n if (throttleMode === \"leading-trailing\") {\n this.handler(data);\n }\n this.lastRun = now;\n }\n if (this.timeoutId) {\n window.clearTimeout(this.timeoutId);\n }\n this.timeoutId = window.setTimeout(\n () => {\n this.handler(data);\n this.lastRun = Date.now();\n this.timeoutId = void 0;\n },\n this.options.wait - (now - this.lastRun)\n );\n }\n destroy() {\n if (this.timeoutId) {\n window.clearTimeout(this.timeoutId);\n }\n }\n}\nclass KeyedEventControl {\n constructor(handler, options) {\n this.handler = handler;\n this.options = options;\n this.controls = /* @__PURE__ */ new Map();\n this.handle = (data) => {\n const key = String(this.options.keyExtractor(data));\n let control = this.controls.get(key);\n if (!control) {\n control = new EventControl(this.handler, this.baseOptions);\n this.controls.set(key, control);\n }\n control.handle(data);\n };\n this.baseOptions = {\n mode: options.mode,\n wait: options.wait,\n ...options.mode === \"throttle\" && \"throttleMode\" in options ? { throttleMode: options.throttleMode } : {}\n };\n }\n destroy() {\n for (const control of this.controls.values()) {\n control.destroy();\n }\n this.controls.clear();\n }\n}\nfunction isKeyedOptions(options) {\n return \"keyExtractor\" in options;\n}\nfunction clamp(value, min, max) {\n return value < min ? min : value > max ? max : value;\n}\nfunction arePropsEqual(a, b, visited) {\n if (a === b) {\n return true;\n }\n if (a == null || b == null) {\n return a === b;\n }\n const aType = typeof a;\n const bType = typeof b;\n if (aType !== bType) return false;\n if (aType === \"object\") {\n if (!visited) visited = /* @__PURE__ */ new Set();\n const pairId = getPairId(a, b);\n if (visited.has(pairId)) {\n return true;\n }\n visited.add(pairId);\n const aIsArray = Array.isArray(a);\n const bIsArray = Array.isArray(b);\n if (aIsArray && bIsArray) {\n return arraysEqualUnordered(a, b, visited);\n } else if (!aIsArray && !bIsArray) {\n return objectsEqual(a, b, visited);\n } else {\n return false;\n }\n }\n return false;\n}\nfunction getPairId(a, b) {\n return `${objectId(a)}__${objectId(b)}`;\n}\nlet objectIdCounter = 0;\nconst objectIds = /* @__PURE__ */ new WeakMap();\nfunction objectId(obj) {\n if (!objectIds.has(obj)) {\n objectIds.set(obj, ++objectIdCounter);\n }\n return objectIds.get(obj);\n}\nfunction arraysEqualUnordered(a, b, visited) {\n if (a.length !== b.length) return false;\n const used = new Array(b.length).fill(false);\n outer: for (let i = 0; i < a.length; i++) {\n const elemA = a[i];\n for (let j = 0; j < b.length; j++) {\n if (used[j]) continue;\n if (arePropsEqual(elemA, b[j], visited)) {\n used[j] = true;\n continue outer;\n }\n }\n return false;\n }\n return true;\n}\nfunction objectsEqual(a, b, visited) {\n const aKeys = Object.keys(a).sort();\n const bKeys = Object.keys(b).sort();\n if (aKeys.length !== bKeys.length) return false;\n for (let i = 0; i < aKeys.length; i++) {\n if (aKeys[i] !== bKeys[i]) return false;\n }\n for (const key of aKeys) {\n const valA = a[key];\n const valB = b[key];\n if (!arePropsEqual(valA, valB, visited)) {\n return false;\n }\n }\n return true;\n}\nfunction createEmitter() {\n const listeners = /* @__PURE__ */ new Set();\n const on = (l) => {\n listeners.add(l);\n return () => listeners.delete(l);\n };\n return {\n emit: (v = void 0) => listeners.forEach((l) => l(v)),\n on,\n off: (l) => listeners.delete(l),\n clear: () => listeners.clear()\n };\n}\nfunction createBehaviorEmitter(initial, equality = arePropsEqual) {\n const listeners = /* @__PURE__ */ new Set();\n const proxyMap = /* @__PURE__ */ new Map();\n let _value = initial;\n const notify = (v) => listeners.forEach((l) => l(v));\n const baseOn = (listener, options) => {\n let realListener = listener;\n let destroy = () => {\n };\n if (options) {\n if (isKeyedOptions(options)) {\n const ctl = new KeyedEventControl(listener, options);\n realListener = ctl.handle;\n destroy = () => ctl.destroy();\n } else {\n const ctl = new EventControl(listener, options);\n realListener = ctl.handle;\n destroy = () => ctl.destroy();\n }\n proxyMap.set(listener, { wrapped: realListener, destroy });\n }\n if (_value !== void 0) realListener(_value);\n listeners.add(realListener);\n return () => {\n listeners.delete(realListener);\n destroy();\n proxyMap.delete(listener);\n };\n };\n return {\n /* emitter behaviour ---------------------------------------- */\n get value() {\n return _value;\n },\n emit(v = void 0) {\n if (_value === void 0 || !equality(_value, v)) {\n _value = v;\n notify(v);\n }\n },\n on: baseOn,\n off(listener) {\n const proxy = proxyMap.get(listener);\n if (proxy) {\n listeners.delete(proxy.wrapped);\n proxy.destroy();\n proxyMap.delete(listener);\n } else {\n listeners.delete(listener);\n }\n },\n clear() {\n listeners.clear();\n proxyMap.forEach((p) => p.destroy());\n proxyMap.clear();\n },\n /* derived hook --------------------------------------------- */\n select(selector, eq = arePropsEqual) {\n return (listener, options) => {\n let prev;\n if (_value !== void 0) {\n const mapped = selector(_value);\n prev = mapped;\n listener(mapped);\n }\n return baseOn(\n (next) => {\n const mapped = selector(next);\n if (prev === void 0 || !eq(prev, mapped)) {\n prev = mapped;\n listener(mapped);\n }\n },\n options\n );\n };\n }\n };\n}\nfunction createScopedEmitter(toGlobalEvent, options) {\n const shouldCache = (options == null ? void 0 : options.cache) ?? true;\n const equality = (options == null ? void 0 : options.equality) ?? arePropsEqual;\n const scopeCaches = /* @__PURE__ */ new Map();\n const scopeListeners = /* @__PURE__ */ new Map();\n const scopeProxyMaps = /* @__PURE__ */ new Map();\n const globalListeners = /* @__PURE__ */ new Set();\n const globalProxyMap = /* @__PURE__ */ new Map();\n const normalizeKey = (key) => String(key);\n const getOrCreateListeners = (key) => {\n let listeners = scopeListeners.get(key);\n if (!listeners) {\n listeners = /* @__PURE__ */ new Set();\n scopeListeners.set(key, listeners);\n }\n return listeners;\n };\n const getOrCreateProxyMap = (key) => {\n let proxyMap = scopeProxyMaps.get(key);\n if (!proxyMap) {\n proxyMap = /* @__PURE__ */ new Map();\n scopeProxyMaps.set(key, proxyMap);\n }\n return proxyMap;\n };\n const onGlobal = (listener, options2) => {\n let realListener = listener;\n let destroy = () => {\n };\n if (options2) {\n if (isKeyedOptions(options2)) {\n const ctl = new KeyedEventControl(listener, options2);\n realListener = ctl.handle;\n destroy = () => ctl.destroy();\n } else {\n const ctl = new EventControl(listener, options2);\n realListener = ctl.handle;\n destroy = () => ctl.destroy();\n }\n globalProxyMap.set(listener, { wrapped: realListener, destroy });\n }\n globalListeners.add(realListener);\n return () => {\n globalListeners.delete(realListener);\n destroy();\n globalProxyMap.delete(listener);\n };\n };\n return {\n emit(key, data) {\n const normalizedKey = normalizeKey(key);\n if (shouldCache) {\n const cached = scopeCaches.get(normalizedKey);\n if (cached !== void 0 && equality(cached, data)) {\n return;\n }\n scopeCaches.set(normalizedKey, data);\n }\n const listeners = scopeListeners.get(normalizedKey);\n if (listeners) {\n listeners.forEach((l) => l(data));\n }\n const globalEvent = toGlobalEvent(key, data);\n globalListeners.forEach((l) => l(globalEvent));\n },\n forScope(key) {\n const normalizedKey = normalizeKey(key);\n return (listener, options2) => {\n const listeners = getOrCreateListeners(normalizedKey);\n const proxyMap = getOrCreateProxyMap(normalizedKey);\n let realListener = listener;\n let destroy = () => {\n };\n if (options2) {\n if (isKeyedOptions(options2)) {\n const ctl = new KeyedEventControl(listener, options2);\n realListener = ctl.handle;\n destroy = () => ctl.destroy();\n } else {\n const ctl = new EventControl(listener, options2);\n realListener = ctl.handle;\n destroy = () => ctl.destroy();\n }\n proxyMap.set(listener, { wrapped: realListener, destroy });\n }\n if (shouldCache) {\n const cached = scopeCaches.get(normalizedKey);\n if (cached !== void 0) {\n realListener(cached);\n }\n }\n listeners.add(realListener);\n return () => {\n listeners.delete(realListener);\n destroy();\n proxyMap.delete(listener);\n if (listeners.size === 0) {\n scopeListeners.delete(normalizedKey);\n }\n if (proxyMap.size === 0) {\n scopeProxyMaps.delete(normalizedKey);\n }\n };\n };\n },\n onGlobal,\n getValue(key) {\n return shouldCache ? scopeCaches.get(normalizeKey(key)) : void 0;\n },\n getScopes() {\n if (shouldCache) {\n return Array.from(scopeCaches.keys());\n }\n return Array.from(scopeListeners.keys());\n },\n clearScope(key) {\n const normalizedKey = normalizeKey(key);\n if (shouldCache) {\n scopeCaches.delete(normalizedKey);\n }\n const listeners = scopeListeners.get(normalizedKey);\n if (listeners) {\n listeners.clear();\n scopeListeners.delete(normalizedKey);\n }\n const proxyMap = scopeProxyMaps.get(normalizedKey);\n if (proxyMap) {\n proxyMap.forEach((p) => p.destroy());\n proxyMap.clear();\n scopeProxyMaps.delete(normalizedKey);\n }\n },\n clear() {\n if (shouldCache) {\n scopeCaches.clear();\n }\n scopeListeners.forEach((set) => set.clear());\n scopeListeners.clear();\n scopeProxyMaps.forEach((map) => {\n map.forEach((p) => p.destroy());\n map.clear();\n });\n scopeProxyMaps.clear();\n globalListeners.clear();\n globalProxyMap.forEach((p) => p.destroy());\n globalProxyMap.clear();\n }\n };\n}\nfunction enumEntries(record) {\n return Object.entries(record).map(([k, v]) => {\n const maybeNum = Number(k);\n const typedKey = Number.isFinite(maybeNum) && k.trim() !== \"\" ? maybeNum : k;\n return [typedKey, v];\n });\n}\nclass PluginPackageBuilder {\n constructor(basePackage) {\n this.autoMountElements = [];\n this.package = basePackage;\n }\n addUtility(component) {\n this.autoMountElements.push({ component, type: \"utility\" });\n return this;\n }\n addWrapper(component) {\n this.autoMountElements.push({ component, type: \"wrapper\" });\n return this;\n }\n build() {\n return {\n ...this.package,\n autoMountElements: () => this.autoMountElements\n };\n }\n}\nfunction createPluginPackage(basePackage) {\n return new PluginPackageBuilder(basePackage);\n}\nexport {\n ALL_PERMISSION_FLAGS,\n ALL_PERMISSION_NAMES,\n BasePlugin,\n CLOSE_DOCUMENT,\n CORE_ACTION_TYPES,\n CapabilityConflictError,\n CapabilityNotFoundError,\n CircularDependencyError,\n DependencyResolver,\n EventControl,\n KeyedEventControl,\n MOVE_DOCUMENT,\n PERMISSION_FLAG_TO_NAME,\n PERMISSION_NAME_TO_FLAG,\n PluginConfigurationError,\n PluginInitializationError,\n PluginNotFoundError,\n PluginPackageBuilder,\n PluginRegistrationError,\n PluginRegistry,\n REFRESH_DOCUMENT,\n REFRESH_PAGES,\n REORDER_DOCUMENTS,\n RETRY_LOADING_DOCUMENT,\n SET_ACTIVE_DOCUMENT,\n SET_DEFAULT_ROTATION,\n SET_DEFAULT_SCALE,\n SET_DOCUMENT_ERROR,\n SET_DOCUMENT_LOADED,\n SET_PAGES,\n SET_ROTATION,\n SET_SCALE,\n START_LOADING_DOCUMENT,\n UPDATE_DOCUMENT_LOADING_PROGRESS,\n UPDATE_DOCUMENT_SECURITY,\n arePropsEqual,\n clamp,\n closeDocument,\n createBehaviorEmitter,\n createEmitter,\n createPluginPackage,\n createPluginRegistration,\n createScopedEmitter,\n enumEntries,\n getActiveDocumentState,\n getDocumentCount,\n getDocumentIds,\n getDocumentState,\n getEffectivePermission,\n getEffectivePermissions,\n getPermissionOverride,\n hasAutoMountElements,\n initialCoreState,\n isDocumentLoaded,\n isKeyedOptions,\n moveDocument,\n refreshDocument,\n refreshPages,\n reorderDocuments,\n retryLoadingDocument,\n setActiveDocument,\n setDefaultRotation,\n setDefaultScale,\n setDocumentError,\n setDocumentLoaded,\n setPages,\n setRotation,\n setScale,\n startLoadingDocument,\n updateDocumentLoadingProgress,\n updateDocumentSecurity\n};\n//# sourceMappingURL=index.js.map\n","import { createContext, useMemo, Fragment, useState, useRef, useEffect, useContext } from \"react\";\nimport { jsxs, jsx } from \"react/jsx-runtime\";\nimport { hasAutoMountElements, PluginRegistry } from \"@embedpdf/core\";\nimport { PdfPermissionFlag } from \"@embedpdf/models\";\nconst PDFContext = createContext({\n registry: null,\n coreState: null,\n isInitializing: true,\n pluginsReady: false,\n activeDocumentId: null,\n activeDocument: null,\n documents: {},\n documentStates: []\n});\nfunction AutoMount({ plugins, children }) {\n const { utilities, wrappers } = useMemo(() => {\n const utilities2 = [];\n const wrappers2 = [];\n for (const reg of plugins) {\n const pkg = reg.package;\n if (hasAutoMountElements(pkg)) {\n const elements = pkg.autoMountElements() || [];\n for (const element of elements) {\n if (element.type === \"utility\") {\n utilities2.push(element.component);\n } else if (element.type === \"wrapper\") {\n wrappers2.push(element.component);\n }\n }\n }\n }\n return { utilities: utilities2, wrappers: wrappers2 };\n }, [plugins]);\n const contentWithUtilities = /* @__PURE__ */ jsxs(Fragment, { children: [\n children,\n utilities.map((Utility, i) => /* @__PURE__ */ jsx(Utility, {}, `utility-${i}`))\n ] });\n const wrappedContent = wrappers.reduce(\n (content, Wrapper) => /* @__PURE__ */ jsx(Wrapper, { children: content }),\n contentWithUtilities\n );\n return /* @__PURE__ */ jsx(Fragment, { children: wrappedContent });\n}\nfunction EmbedPDF({\n engine,\n config,\n logger,\n onInitialized,\n plugins,\n children,\n autoMountDomElements = true\n}) {\n const [registry, setRegistry] = useState(null);\n const [coreState, setCoreState] = useState(null);\n const [isInitializing, setIsInitializing] = useState(true);\n const [pluginsReady, setPluginsReady] = useState(false);\n const initRef = useRef(onInitialized);\n useEffect(() => {\n initRef.current = onInitialized;\n }, [onInitialized]);\n useEffect(() => {\n const finalConfig = {\n ...config,\n logger: (config == null ? void 0 : config.logger) ?? logger\n };\n const pdfViewer = new PluginRegistry(engine, finalConfig);\n pdfViewer.registerPluginBatch(plugins);\n const initialize = async () => {\n var _a;\n await pdfViewer.initialize();\n if (pdfViewer.isDestroyed()) {\n return;\n }\n const store = pdfViewer.getStore();\n setCoreState(store.getState().core);\n const unsubscribe = store.subscribe((action, newState, oldState) => {\n if (store.isCoreAction(action) && newState.core !== oldState.core) {\n setCoreState(newState.core);\n }\n });\n await ((_a = initRef.current) == null ? void 0 : _a.call(initRef, pdfViewer));\n if (pdfViewer.isDestroyed()) {\n unsubscribe();\n return;\n }\n pdfViewer.pluginsReady().then(() => {\n if (!pdfViewer.isDestroyed()) {\n setPluginsReady(true);\n }\n });\n setRegistry(pdfViewer);\n setIsInitializing(false);\n return unsubscribe;\n };\n let cleanup;\n initialize().then((unsub) => {\n cleanup = unsub;\n }).catch(console.error);\n return () => {\n cleanup == null ? void 0 : cleanup();\n pdfViewer.destroy();\n setRegistry(null);\n setCoreState(null);\n setIsInitializing(true);\n setPluginsReady(false);\n };\n }, [engine, plugins]);\n const contextValue = useMemo(() => {\n const activeDocumentId = (coreState == null ? void 0 : coreState.activeDocumentId) ?? null;\n const documents = (coreState == null ? void 0 : coreState.documents) ?? {};\n const documentOrder = (coreState == null ? void 0 : coreState.documentOrder) ?? [];\n const activeDocument = activeDocumentId && documents[activeDocumentId] ? documents[activeDocumentId] : null;\n const documentStates = documentOrder.map((docId) => documents[docId]).filter((doc) => doc !== null && doc !== void 0);\n return {\n registry,\n coreState,\n isInitializing,\n pluginsReady,\n // Convenience accessors (always safe to use)\n activeDocumentId,\n activeDocument,\n documents,\n documentStates\n };\n }, [registry, coreState, isInitializing, pluginsReady]);\n const content = typeof children === \"function\" ? children(contextValue) : children;\n return /* @__PURE__ */ jsx(PDFContext.Provider, { value: contextValue, children: pluginsReady && autoMountDomElements ? /* @__PURE__ */ jsx(AutoMount, { plugins, children: content }) : content });\n}\nfunction useRegistry() {\n const contextValue = useContext(PDFContext);\n if (contextValue === void 0) {\n throw new Error(\"useCapability must be used within a PDFContext.Provider\");\n }\n const { registry, isInitializing } = contextValue;\n if (isInitializing) {\n return contextValue;\n }\n if (registry === null) {\n throw new Error(\"PDF registry failed to initialize properly\");\n }\n return contextValue;\n}\nfunction usePlugin(pluginId) {\n const { registry } = useRegistry();\n if (registry === null) {\n return {\n plugin: null,\n isLoading: true,\n ready: new Promise(() => {\n })\n };\n }\n const plugin = registry.getPlugin(pluginId);\n if (!plugin) {\n throw new Error(`Plugin ${pluginId} not found`);\n }\n return {\n plugin,\n isLoading: false,\n ready: plugin.ready()\n };\n}\nfunction useCapability(pluginId) {\n const { plugin, isLoading, ready } = usePlugin(pluginId);\n if (!plugin) {\n return {\n provides: null,\n isLoading,\n ready\n };\n }\n if (!plugin.provides) {\n throw new Error(`Plugin ${pluginId} does not provide a capability`);\n }\n return {\n provides: plugin.provides(),\n isLoading,\n ready\n };\n}\nfunction useStoreState() {\n const { registry } = useRegistry();\n const [state, setState] = useState(null);\n useEffect(() => {\n if (!registry) return;\n setState(registry.getStore().getState());\n const unsubscribe = registry.getStore().subscribe((_action, newState) => {\n setState(newState);\n });\n return () => unsubscribe();\n }, [registry]);\n return state;\n}\nfunction useCoreState() {\n const { coreState } = useContext(PDFContext);\n return coreState;\n}\nfunction useDocumentState(documentId) {\n const coreState = useCoreState();\n const documentState = useMemo(() => {\n if (!coreState || !documentId) return null;\n return coreState.documents[documentId] ?? null;\n }, [coreState, documentId]);\n return documentState;\n}\n({\n print: PdfPermissionFlag.Print,\n modifyContents: PdfPermissionFlag.ModifyContents,\n copyContents: PdfPermissionFlag.CopyContents,\n modifyAnnotations: PdfPermissionFlag.ModifyAnnotations,\n fillForms: PdfPermissionFlag.FillForms,\n extractForAccessibility: PdfPermissionFlag.ExtractForAccessibility,\n assembleDocument: PdfPermissionFlag.AssembleDocument,\n printHighQuality: PdfPermissionFlag.PrintHighQuality\n});\nconst ALL_PERMISSION_FLAGS = [\n PdfPermissionFlag.Print,\n PdfPermissionFlag.ModifyContents,\n PdfPermissionFlag.CopyContents,\n PdfPermissionFlag.ModifyAnnotations,\n PdfPermissionFlag.FillForms,\n PdfPermissionFlag.ExtractForAccessibility,\n PdfPermissionFlag.AssembleDocument,\n PdfPermissionFlag.PrintHighQuality\n];\nconst PERMISSION_FLAG_TO_NAME = {\n [PdfPermissionFlag.Print]: \"print\",\n [PdfPermissionFlag.ModifyContents]: \"modifyContents\",\n [PdfPermissionFlag.CopyContents]: \"copyContents\",\n [PdfPermissionFlag.ModifyAnnotations]: \"modifyAnnotations\",\n [PdfPermissionFlag.FillForms]: \"fillForms\",\n [PdfPermissionFlag.ExtractForAccessibility]: \"extractForAccessibility\",\n [PdfPermissionFlag.AssembleDocument]: \"assembleDocument\",\n [PdfPermissionFlag.PrintHighQuality]: \"printHighQuality\"\n};\nfunction getPermissionOverride(overrides, flag) {\n if (!overrides) return void 0;\n if (flag in overrides) {\n return overrides[flag];\n }\n const name = PERMISSION_FLAG_TO_NAME[flag];\n if (name && name in overrides) {\n return overrides[name];\n }\n return void 0;\n}\nfunction getEffectivePermission(state, documentId, flag) {\n var _a;\n const docState = state.documents[documentId];\n const docConfig = docState == null ? void 0 : docState.permissions;\n const globalConfig = state.globalPermissions;\n const pdfPermissions = ((_a = docState == null ? void 0 : docState.document) == null ? void 0 : _a.permissions) ?? PdfPermissionFlag.AllowAll;\n const docOverride = getPermissionOverride(docConfig == null ? void 0 : docConfig.overrides, flag);\n if (docOverride !== void 0) {\n return docOverride;\n }\n const globalOverride = getPermissionOverride(globalConfig == null ? void 0 : globalConfig.overrides, flag);\n if (globalOverride !== void 0) {\n return globalOverride;\n }\n const enforce = (docConfig == null ? void 0 : docConfig.enforceDocumentPermissions) ?? (globalConfig == null ? void 0 : globalConfig.enforceDocumentPermissions) ?? true;\n if (!enforce) return true;\n return (pdfPermissions & flag) !== 0;\n}\nfunction getEffectivePermissions(state, documentId) {\n return ALL_PERMISSION_FLAGS.reduce((acc, flag) => {\n return getEffectivePermission(state, documentId, flag) ? acc | flag : acc;\n }, 0);\n}\nfunction useDocumentPermissions(documentId) {\n const coreState = useCoreState();\n return useMemo(() => {\n var _a, _b;\n if (!coreState) {\n return {\n permissions: PdfPermissionFlag.AllowAll,\n pdfPermissions: PdfPermissionFlag.AllowAll,\n hasPermission: () => true,\n hasAllPermissions: () => true,\n canPrint: true,\n canModifyContents: true,\n canCopyContents: true,\n canModifyAnnotations: true,\n canFillForms: true,\n canExtractForAccessibility: true,\n canAssembleDocument: true,\n canPrintHighQuality: true\n };\n }\n const effectivePermissions = getEffectivePermissions(coreState, documentId);\n const pdfPermissions = ((_b = (_a = coreState.documents[documentId]) == null ? void 0 : _a.document) == null ? void 0 : _b.permissions) ?? PdfPermissionFlag.AllowAll;\n const hasPermission = (flag) => getEffectivePermission(coreState, documentId, flag);\n const hasAllPermissions = (...flags) => flags.every((flag) => getEffectivePermission(coreState, documentId, flag));\n return {\n permissions: effectivePermissions,\n pdfPermissions,\n hasPermission,\n hasAllPermissions,\n // All permission flags as booleans (using effective permissions)\n canPrint: hasPermission(PdfPermissionFlag.Print),\n canModifyContents: hasPermission(PdfPermissionFlag.ModifyContents),\n canCopyContents: hasPermission(PdfPermissionFlag.CopyContents),\n canModifyAnnotations: hasPermission(PdfPermissionFlag.ModifyAnnotations),\n canFillForms: hasPermission(PdfPermissionFlag.FillForms),\n canExtractForAccessibility: hasPermission(PdfPermissionFlag.ExtractForAccessibility),\n canAssembleDocument: hasPermission(PdfPermissionFlag.AssembleDocument),\n canPrintHighQuality: hasPermission(PdfPermissionFlag.PrintHighQuality)\n };\n }, [coreState, documentId]);\n}\nexport {\n EmbedPDF,\n PDFContext,\n useCapability,\n useCoreState,\n useDocumentPermissions,\n useDocumentState,\n usePlugin,\n useRegistry,\n useStoreState\n};\n//# sourceMappingURL=index.js.map\n","import { useState, useRef, useEffect, createContext, useContext } from \"react\";\nimport { ignore } from \"@embedpdf/models\";\nimport { jsx } from \"react/jsx-runtime\";\nconst defaultWasmUrl = `https://cdn.jsdelivr.net/npm/@embedpdf/pdfium@2.15.1/dist/pdfium.wasm`;\nfunction usePdfiumEngine(config) {\n const {\n wasmUrl = defaultWasmUrl,\n worker = true,\n logger,\n encoderPoolSize,\n fontFallback\n } = config ?? {};\n const [engine, setEngine] = useState(null);\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState(null);\n const engineRef = useRef(null);\n useEffect(() => {\n let cancelled = false;\n (async () => {\n try {\n const { createPdfiumEngine } = worker ? await import(\"@embedpdf/engines/pdfium-worker-engine\") : await import(\"@embedpdf/engines/pdfium-direct-engine\");\n const pdfEngine = await createPdfiumEngine(wasmUrl, {\n logger,\n encoderPoolSize,\n fontFallback\n });\n engineRef.current = pdfEngine;\n setEngine(pdfEngine);\n setLoading(false);\n } catch (e) {\n if (!cancelled) {\n setError(e);\n setLoading(false);\n }\n }\n })();\n return () => {\n var _a, _b;\n cancelled = true;\n (_b = (_a = engineRef.current) == null ? void 0 : _a.closeAllDocuments) == null ? void 0 : _b.call(_a).wait(() => {\n var _a2, _b2;\n (_b2 = (_a2 = engineRef.current) == null ? void 0 : _a2.destroy) == null ? void 0 : _b2.call(_a2);\n engineRef.current = null;\n }, ignore);\n };\n }, [wasmUrl, worker, logger, fontFallback]);\n return { engine, isLoading: loading, error };\n}\nconst PdfEngineContext = createContext(void 0);\nfunction useEngineContext() {\n const contextValue = useContext(PdfEngineContext);\n if (contextValue === void 0) {\n throw new Error(\"useEngineContext must be used within a PdfEngineProvider\");\n }\n return contextValue;\n}\nfunction useEngine() {\n const { engine, error } = useEngineContext();\n if (error) {\n throw error;\n }\n return engine;\n}\nfunction PdfEngineProvider({ children, engine, isLoading, error }) {\n const contextValue = {\n engine,\n isLoading,\n error\n };\n return /* @__PURE__ */ jsx(PdfEngineContext.Provider, { value: contextValue, children });\n}\nexport {\n PdfEngineProvider,\n useEngine,\n useEngineContext,\n usePdfiumEngine\n};\n//# sourceMappingURL=index.js.map\n","import { BasePlugin, createBehaviorEmitter, createEmitter, reorderDocuments, moveDocument, setActiveDocument, startLoadingDocument, retryLoadingDocument, closeDocument, updateDocumentSecurity, setDocumentLoaded, setDocumentError } from \"@embedpdf/core\";\nimport { Task, PdfErrorCode } from \"@embedpdf/models\";\nconst _DocumentManagerPlugin = class _DocumentManagerPlugin extends BasePlugin {\n constructor(id, registry, config) {\n super(id, registry);\n this.id = id;\n this.documentOpened$ = createBehaviorEmitter();\n this.documentClosed$ = createBehaviorEmitter();\n this.activeDocumentChanged$ = createBehaviorEmitter();\n this.documentError$ = createBehaviorEmitter();\n this.documentOrderChanged$ = createBehaviorEmitter();\n this.openFileRequest$ = createEmitter();\n this.loadOptions = /* @__PURE__ */ new Map();\n this.maxDocuments = config == null ? void 0 : config.maxDocuments;\n }\n buildCapability() {\n return {\n // Document lifecycle - orchestration only\n openFileDialog: (options) => this.openFileDialog(options),\n openDocumentUrl: (options) => this.openDocumentUrl(options),\n openDocumentBuffer: (options) => this.openDocumentBuffer(options),\n retryDocument: (documentId, options) => this.retryDocument(documentId, options),\n closeDocument: (documentId) => this.closeDocument(documentId),\n closeAllDocuments: () => this.closeAllDocuments(),\n setActiveDocument: (documentId) => {\n if (!this.isDocumentOpen(documentId)) {\n throw new Error(`Cannot set active document: ${documentId} is not open`);\n }\n this.dispatchCoreAction(setActiveDocument(documentId));\n },\n getActiveDocumentId: () => this.coreState.core.activeDocumentId,\n getActiveDocument: () => {\n var _a;\n const activeId = this.coreState.core.activeDocumentId;\n if (!activeId) return null;\n return ((_a = this.coreState.core.documents[activeId]) == null ? void 0 : _a.document) ?? null;\n },\n getDocumentOrder: () => this.coreState.core.documentOrder,\n moveDocument: (documentId, toIndex) => {\n this.dispatchCoreAction(moveDocument(documentId, toIndex));\n },\n swapDocuments: (id1, id2) => {\n const order = this.coreState.core.documentOrder;\n const index1 = order.indexOf(id1);\n const index2 = order.indexOf(id2);\n if (index1 === -1 || index2 === -1) {\n throw new Error(\"One or both documents not found in order\");\n }\n const newOrder = [...order];\n [newOrder[index1], newOrder[index2]] = [newOrder[index2], newOrder[index1]];\n this.dispatchCoreAction(reorderDocuments(newOrder));\n },\n getDocument: (documentId) => {\n var _a;\n return ((_a = this.coreState.core.documents[documentId]) == null ? void 0 : _a.document) ?? null;\n },\n getDocumentState: (documentId) => {\n return this.coreState.core.documents[documentId] ?? null;\n },\n getOpenDocuments: () => {\n return this.coreState.core.documentOrder.map((documentId) => this.coreState.core.documents[documentId]).filter((state) => state !== null);\n },\n isDocumentOpen: (documentId) => this.isDocumentOpen(documentId),\n getDocumentCount: () => {\n return Object.keys(this.coreState.core.documents).length;\n },\n getDocumentIndex: (documentId) => {\n return this.coreState.core.documentOrder.indexOf(documentId);\n },\n // Security\n setDocumentEncryption: (documentId, options) => this.setDocumentEncryption(documentId, options),\n unlockOwnerPermissions: (documentId, ownerPassword) => this.unlockOwnerPermissions(documentId, ownerPassword),\n removeEncryption: (documentId) => this.removeEncryption(documentId),\n // Events\n onDocumentOpened: this.documentOpened$.on,\n onDocumentClosed: this.documentClosed$.on,\n onDocumentError: this.documentError$.on,\n onActiveDocumentChanged: this.activeDocumentChanged$.on,\n onDocumentOrderChanged: this.documentOrderChanged$.on\n };\n }\n /**\n * Check if a document is currently open\n */\n isDocumentOpen(documentId) {\n return !!this.coreState.core.documents[documentId];\n }\n // ─────────────────────────────────────────────────────────\n // Document Lifecycle Hooks (from BasePlugin)\n // ─────────────────────────────────────────────────────────\n onDocumentLoaded(documentId) {\n const docState = this.coreState.core.documents[documentId];\n if (!docState || docState.status !== \"loaded\") return;\n this.loadOptions.delete(documentId);\n this.documentOpened$.emit(docState);\n this.logger.info(\n \"DocumentManagerPlugin\",\n \"DocumentOpened\",\n `Document ${documentId} opened successfully`,\n { name: docState.name }\n );\n }\n onDocumentClosed(documentId) {\n this.loadOptions.delete(documentId);\n this.documentClosed$.emit(documentId);\n this.logger.info(\"DocumentManagerPlugin\", \"DocumentClosed\", `Document ${documentId} closed`);\n }\n onActiveDocumentChanged(previousId, currentId) {\n this.activeDocumentChanged$.emit({\n previousDocumentId: previousId,\n currentDocumentId: currentId\n });\n this.logger.info(\n \"DocumentManagerPlugin\",\n \"ActiveDocumentChanged\",\n `Active document changed from ${previousId} to ${currentId}`\n );\n }\n onCoreStoreUpdated(oldState, newState) {\n if (oldState.core.documentOrder !== newState.core.documentOrder) {\n this.documentOrderChanged$.emit({\n order: newState.core.documentOrder\n });\n }\n }\n onOpenFileRequest(handler) {\n return this.openFileRequest$.on(handler);\n }\n // ─────────────────────────────────────────────────────────\n // Document Loading (orchestration only - no state management)\n // ─────────────────────────────────────────────────────────\n openDocumentUrl(options) {\n const task = new Task();\n const documentId = options.documentId || this.generateDocumentId();\n const limitError = this.checkDocumentLimit();\n if (limitError) {\n task.reject(limitError);\n return task;\n }\n const documentName = options.name ?? this.extractNameFromUrl(options.url);\n this.loadOptions.set(documentId, options);\n this.dispatchCoreAction(\n startLoadingDocument(\n documentId,\n documentName,\n options.scale,\n options.rotation,\n !!options.password,\n options.autoActivate,\n options.permissions\n )\n );\n this.logger.info(\n \"DocumentManagerPlugin\",\n \"OpenDocumentUrl\",\n `Starting to load document from URL: ${options.url}`,\n { documentId, passwordProvided: !!options.password }\n );\n const file = {\n id: documentId,\n url: options.url\n };\n const engineTask = this.engine.openDocumentUrl(file, {\n password: options.password,\n mode: options.mode,\n requestOptions: options.requestOptions,\n normalizeRotation: true\n });\n task.resolve({\n documentId,\n task: engineTask\n });\n this.handleLoadTask(documentId, engineTask, \"OpenDocumentUrl\");\n return task;\n }\n openDocumentBuffer(options) {\n const task = new Task();\n const limitError = this.checkDocumentLimit();\n if (limitError) {\n task.reject(limitError);\n return task;\n }\n const documentId = options.documentId || this.generateDocumentId();\n this.loadOptions.set(documentId, options);\n this.dispatchCoreAction(\n startLoadingDocument(\n documentId,\n options.name,\n options.scale,\n options.rotation,\n !!options.password,\n options.autoActivate,\n options.permissions\n )\n );\n this.logger.info(\n \"DocumentManagerPlugin\",\n \"OpenDocumentBuffer\",\n `Starting to load document from buffer: ${options.name}`,\n { documentId, passwordProvided: !!options.password }\n );\n const file = {\n id: documentId,\n content: options.buffer\n };\n const engineTask = this.engine.openDocumentBuffer(file, {\n password: options.password,\n normalizeRotation: true\n });\n task.resolve({\n documentId,\n task: engineTask\n });\n this.handleLoadTask(documentId, engineTask, \"OpenDocumentBuffer\");\n return task;\n }\n retryDocument(documentId, retryOptions) {\n const task = new Task();\n const validation = this.validateRetry(documentId);\n if (!validation.valid) {\n task.reject(validation.error);\n return task;\n }\n const originalOptions = this.loadOptions.get(documentId);\n const mergedOptions = {\n ...originalOptions,\n ...(retryOptions == null ? void 0 : retryOptions.password) && { password: retryOptions.password }\n };\n this.loadOptions.set(documentId, mergedOptions);\n this.dispatchCoreAction(retryLoadingDocument(documentId, !!(retryOptions == null ? void 0 : retryOptions.password)));\n this.logger.info(\n \"DocumentManagerPlugin\",\n \"RetryDocument\",\n `Retrying to load document ${documentId}`,\n { passwordProvided: !!(retryOptions == null ? void 0 : retryOptions.password) }\n );\n const engineTask = \"url\" in mergedOptions ? this.retryUrlDocument(documentId, mergedOptions) : this.retryBufferDocument(documentId, mergedOptions);\n task.resolve({\n documentId,\n task: engineTask\n });\n this.handleLoadTask(documentId, engineTask, \"RetryDocument\");\n return task;\n }\n openFileDialog(options) {\n const task = new Task();\n this.openFileRequest$.emit({ task, options });\n return task;\n }\n closeDocument(documentId) {\n const task = new Task();\n const docState = this.coreState.core.documents[documentId];\n if (!docState) {\n this.logger.warn(\n \"DocumentManagerPlugin\",\n \"CloseDocument\",\n `Cannot close document ${documentId}: not found in state`\n );\n task.resolve();\n return task;\n }\n if (docState.status === \"loaded\" && docState.document) {\n this.engine.closeDocument(docState.document).wait(\n () => {\n this.dispatchCoreAction(closeDocument(documentId));\n task.resolve();\n },\n (error) => {\n this.logger.error(\n \"DocumentManagerPlugin\",\n \"CloseDocument\",\n `Failed to close document ${documentId}`,\n error\n );\n task.fail(error);\n }\n );\n } else {\n this.logger.info(\n \"DocumentManagerPlugin\",\n \"CloseDocument\",\n `Closing document ${documentId} in ${docState.status} state (skipping engine close)`\n );\n this.dispatchCoreAction(closeDocument(documentId));\n task.resolve();\n }\n return task;\n }\n closeAllDocuments() {\n const documentIds = Object.keys(this.coreState.core.documents);\n const tasks = documentIds.map((documentId) => this.closeDocument(documentId));\n this.logger.info(\n \"DocumentManagerPlugin\",\n \"CloseAllDocuments\",\n `Closing ${documentIds.length} documents`\n );\n return Task.all(tasks);\n }\n // ─────────────────────────────────────────────────────────\n // Security Methods\n // ─────────────────────────────────────────────────────────\n setDocumentEncryption(documentId, options) {\n const task = new Task();\n const docState = this.coreState.core.documents[documentId];\n if (!(docState == null ? void 0 : docState.document)) {\n task.reject({\n code: PdfErrorCode.DocNotOpen,\n message: `Document ${documentId} is not open`\n });\n return task;\n }\n this.logger.info(\n \"DocumentManagerPlugin\",\n \"SetDocumentEncryption\",\n `Setting encryption on document ${documentId}`,\n { hasUserPassword: !!options.userPassword, allowedFlags: options.allowedFlags }\n );\n const engineTask = this.engine.setDocumentEncryption(\n docState.document,\n options.userPassword ?? \"\",\n options.ownerPassword,\n options.allowedFlags\n );\n engineTask.wait(\n (success) => {\n if (success) {\n this.logger.info(\n \"DocumentManagerPlugin\",\n \"SetDocumentEncryption\",\n `Encryption set successfully on document ${documentId}`\n );\n }\n task.resolve(success);\n },\n (error) => {\n this.logger.error(\n \"DocumentManagerPlugin\",\n \"SetDocumentEncryption\",\n `Failed to set encryption on document ${documentId}`,\n error\n );\n task.fail(error);\n }\n );\n return task;\n }\n unlockOwnerPermissions(documentId, ownerPassword) {\n const task = new Task();\n const docState = this.coreState.core.documents[documentId];\n if (!(docState == null ? void 0 : docState.document)) {\n task.reject({\n code: PdfErrorCode.DocNotOpen,\n message: `Document ${documentId} is not open`\n });\n return task;\n }\n const document = docState.document;\n this.logger.info(\n \"DocumentManagerPlugin\",\n \"UnlockOwnerPermissions\",\n `Attempting to unlock owner permissions on document ${documentId}`\n );\n const engineTask = this.engine.unlockOwnerPermissions(document, ownerPassword);\n engineTask.wait(\n (success) => {\n if (success) {\n this.logger.info(\n \"DocumentManagerPlugin\",\n \"UnlockOwnerPermissions\",\n `Owner permissions unlocked on document ${documentId}`\n );\n const fullPermissions = 4294967295;\n this.dispatchCoreAction(updateDocumentSecurity(documentId, fullPermissions, true));\n }\n task.resolve(success);\n },\n (error) => {\n this.logger.error(\n \"DocumentManagerPlugin\",\n \"UnlockOwnerPermissions\",\n `Failed to unlock owner permissions on document ${documentId}`,\n error\n );\n task.fail(error);\n }\n );\n return task;\n }\n removeEncryption(documentId) {\n const task = new Task();\n const docState = this.coreState.core.documents[documentId];\n if (!(docState == null ? void 0 : docState.document)) {\n task.reject({\n code: PdfErrorCode.DocNotOpen,\n message: `Document ${documentId} is not open`\n });\n return task;\n }\n this.logger.info(\n \"DocumentManagerPlugin\",\n \"RemoveEncryption\",\n `Marking document ${documentId} for encryption removal on save`\n );\n const engineTask = this.engine.removeEncryption(docState.document);\n engineTask.wait(\n (success) => {\n if (success) {\n this.logger.info(\n \"DocumentManagerPlugin\",\n \"RemoveEncryption\",\n `Document ${documentId} marked for encryption removal`\n );\n }\n task.resolve(success);\n },\n (error) => {\n this.logger.error(\n \"DocumentManagerPlugin\",\n \"RemoveEncryption\",\n `Failed to mark document ${documentId} for encryption removal`,\n error\n );\n task.fail(error);\n }\n );\n return task;\n }\n // ─────────────────────────────────────────────────────────\n // Helper Methods\n // ─────────────────────────────────────────────────────────\n checkDocumentLimit() {\n if (this.maxDocuments && Object.keys(this.coreState.core.documents).length >= this.maxDocuments) {\n return {\n code: PdfErrorCode.Unknown,\n message: `Maximum number of documents (${this.maxDocuments}) reached`\n };\n }\n return null;\n }\n validateRetry(documentId) {\n const docState = this.coreState.core.documents[documentId];\n if (!docState) {\n return {\n valid: false,\n error: {\n code: PdfErrorCode.NotFound,\n message: `Document ${documentId} not found`\n }\n };\n }\n if (docState.status === \"loaded\") {\n return {\n valid: false,\n error: {\n code: PdfErrorCode.Unknown,\n message: `Document ${documentId} is already loaded successfully`\n }\n };\n }\n if (docState.status !== \"error\") {\n return {\n valid: false,\n error: {\n code: PdfErrorCode.Unknown,\n message: `Document ${documentId} is not in error state (current state: ${docState.status})`\n }\n };\n }\n if (!this.loadOptions.has(documentId)) {\n return {\n valid: false,\n error: {\n code: PdfErrorCode.Unknown,\n message: `No retry information available for document ${documentId}`\n }\n };\n }\n return { valid: true };\n }\n retryUrlDocument(documentId, options) {\n const file = {\n id: documentId,\n url: options.url\n };\n return this.engine.openDocumentUrl(file, {\n password: options.password,\n mode: options.mode,\n requestOptions: options.requestOptions\n });\n }\n retryBufferDocument(documentId, options) {\n const file = {\n id: documentId,\n content: options.buffer\n };\n return this.engine.openDocumentBuffer(file, {\n password: options.password,\n normalizeRotation: true\n });\n }\n handleLoadTask(documentId, engineTask, context) {\n engineTask.wait(\n (pdfDocument) => {\n this.dispatchCoreAction(setDocumentLoaded(documentId, pdfDocument));\n },\n (error) => {\n this.handleLoadError(documentId, error, context);\n }\n );\n }\n handleLoadError(documentId, error, context) {\n var _a, _b, _c;\n const errorMessage = ((_a = error.reason) == null ? void 0 : _a.message) || \"Failed to load document\";\n this.logger.error(\"DocumentManagerPlugin\", context, \"Failed to load document\", error);\n this.dispatchCoreAction(\n setDocumentError(documentId, errorMessage, (_b = error.reason) == null ? void 0 : _b.code, error.reason)\n );\n this.documentError$.emit({\n documentId,\n message: errorMessage,\n code: (_c = error.reason) == null ? void 0 : _c.code,\n reason: error.reason\n });\n }\n generateDocumentId() {\n return `doc-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n }\n extractNameFromUrl(url) {\n try {\n const urlObj = new URL(url);\n const pathname = urlObj.pathname;\n const lastSegment = pathname.split(\"/\").pop();\n if (!lastSegment) {\n return void 0;\n }\n let filename = decodeURIComponent(lastSegment);\n if (!filename.toLowerCase().endsWith(\".pdf\")) {\n filename += \".pdf\";\n }\n return filename;\n } catch {\n return void 0;\n }\n }\n // ─────────────────────────────────────────────────────────\n // Plugin Lifecycle\n // ─────────────────────────────────────────────────────────\n async initialize(config) {\n var _a;\n this.logger.info(\"DocumentManagerPlugin\", \"Initialize\", \"Document Manager Plugin initialized\", {\n maxDocuments: this.maxDocuments,\n initialDocumentsCount: ((_a = config.initialDocuments) == null ? void 0 : _a.length) ?? 0\n });\n if (config.initialDocuments && config.initialDocuments.length > 0) {\n for (const docConfig of config.initialDocuments) {\n try {\n if (\"buffer\" in docConfig) {\n this.openDocumentBuffer(docConfig);\n } else if (\"url\" in docConfig) {\n this.openDocumentUrl(docConfig);\n }\n } catch (error) {\n this.logger.error(\n \"DocumentManagerPlugin\",\n \"Initialize\",\n \"Failed to initiate initial document load\",\n error\n );\n }\n }\n }\n }\n async destroy() {\n await this.closeAllDocuments().toPromise();\n this.loadOptions.clear();\n this.documentOpened$.clear();\n this.documentClosed$.clear();\n this.activeDocumentChanged$.clear();\n this.documentOrderChanged$.clear();\n this.documentError$.clear();\n super.destroy();\n }\n};\n_DocumentManagerPlugin.id = \"document-manager\";\nlet DocumentManagerPlugin = _DocumentManagerPlugin;\nconst DOCUMENT_MANAGER_PLUGIN_ID = \"document-manager\";\nconst manifest = {\n id: DOCUMENT_MANAGER_PLUGIN_ID,\n name: \"Document Manager Plugin\",\n version: \"1.0.0\",\n provides: [\"document-manager\"],\n requires: [],\n optional: [],\n defaultConfig: {\n maxDocuments: 10\n }\n};\nconst DocumentManagerPluginPackage = {\n manifest,\n create: (registry, config) => new DocumentManagerPlugin(DOCUMENT_MANAGER_PLUGIN_ID, registry, config),\n reducer: (state) => state,\n initialState: {}\n};\nexport {\n DOCUMENT_MANAGER_PLUGIN_ID,\n DocumentManagerPlugin,\n DocumentManagerPluginPackage,\n manifest\n};\n//# sourceMappingURL=index.js.map\n","import { createPluginPackage } from \"@embedpdf/core\";\nimport { DocumentManagerPlugin, DocumentManagerPluginPackage as DocumentManagerPluginPackage$1 } from \"@embedpdf/plugin-document-manager\";\nexport * from \"@embedpdf/plugin-document-manager\";\nimport { jsx, Fragment } from \"react/jsx-runtime\";\nimport { useDocumentState, usePlugin, useCapability, useCoreState } from \"@embedpdf/core/react\";\nimport { useMemo, useCallback, useRef, useEffect } from \"react\";\nfunction DocumentContent({ documentId, children }) {\n const documentState = useDocumentState(documentId);\n if (!documentState) return null;\n const isLoading = documentState.status === \"loading\";\n const isError = documentState.status === \"error\";\n const isLoaded = documentState.status === \"loaded\";\n return /* @__PURE__ */ jsx(Fragment, { children: children({ documentState, isLoading, isError, isLoaded }) });\n}\nconst useDocumentManagerPlugin = () => usePlugin(DocumentManagerPlugin.id);\nconst useDocumentManagerCapability = () => useCapability(DocumentManagerPlugin.id);\nconst useActiveDocument = () => {\n const coreState = useCoreState();\n return useMemo(() => {\n if (!coreState) {\n return {\n activeDocumentId: null,\n activeDocument: null\n };\n }\n const activeDocumentId = coreState.activeDocumentId;\n const activeDocument = activeDocumentId ? coreState.documents[activeDocumentId] ?? null : null;\n return {\n activeDocumentId,\n activeDocument\n };\n }, [coreState]);\n};\nconst useOpenDocuments = (documentIds) => {\n const coreState = useCoreState();\n return useMemo(() => {\n if (!coreState) return [];\n if (documentIds) {\n return documentIds.map((docId) => coreState.documents[docId]).filter((doc) => doc !== null && doc !== void 0);\n }\n return coreState.documentOrder.map((docId) => coreState.documents[docId]).filter((doc) => doc !== null && doc !== void 0);\n }, [coreState, documentIds]);\n};\nfunction DocumentContext({ children }) {\n const documentStates = useOpenDocuments();\n const { activeDocumentId } = useActiveDocument();\n const { provides } = useDocumentManagerCapability();\n const select = useCallback(\n (documentId) => {\n provides == null ? void 0 : provides.setActiveDocument(documentId);\n },\n [provides]\n );\n const close = useCallback(\n (documentId) => {\n provides == null ? void 0 : provides.closeDocument(documentId);\n },\n [provides]\n );\n const move = useCallback(\n (documentId, toIndex) => {\n provides == null ? void 0 : provides.moveDocument(documentId, toIndex);\n },\n [provides]\n );\n const actions = {\n select,\n close,\n move\n };\n return /* @__PURE__ */ jsx(Fragment, { children: children({ documentStates, activeDocumentId, actions }) });\n}\nfunction FilePicker() {\n const { plugin } = useDocumentManagerPlugin();\n const { provides } = useDocumentManagerCapability();\n const inputRef = useRef(null);\n const taskRef = useRef(null);\n const optionsRef = useRef(void 0);\n useEffect(() => {\n if (!(plugin == null ? void 0 : plugin.onOpenFileRequest)) return;\n const unsub = plugin.onOpenFileRequest(({ task, options }) => {\n var _a;\n taskRef.current = task;\n optionsRef.current = options;\n (_a = inputRef.current) == null ? void 0 : _a.click();\n });\n return unsub;\n }, [plugin]);\n const onChange = async (e) => {\n var _a, _b, _c, _d, _e;\n const file = (_a = e.currentTarget.files) == null ? void 0 : _a[0];\n if (!file || !provides) return;\n const buffer = await file.arrayBuffer();\n const openTask = provides.openDocumentBuffer({\n name: file.name,\n buffer,\n documentId: (_b = optionsRef.current) == null ? void 0 : _b.documentId,\n scale: (_c = optionsRef.current) == null ? void 0 : _c.scale,\n rotation: (_d = optionsRef.current) == null ? void 0 : _d.rotation,\n autoActivate: (_e = optionsRef.current) == null ? void 0 : _e.autoActivate\n });\n openTask.wait(\n (result) => {\n var _a2;\n (_a2 = taskRef.current) == null ? void 0 : _a2.resolve(result);\n },\n (error) => {\n var _a2;\n (_a2 = taskRef.current) == null ? void 0 : _a2.fail(error);\n }\n );\n };\n return /* @__PURE__ */ jsx(\n \"input\",\n {\n ref: inputRef,\n type: \"file\",\n accept: \"application/pdf\",\n style: { display: \"none\" },\n onChange\n }\n );\n}\nconst DocumentManagerPluginPackage = createPluginPackage(DocumentManagerPluginPackage$1).addUtility(FilePicker).build();\nexport {\n DocumentContent,\n DocumentContext,\n DocumentManagerPluginPackage,\n FilePicker,\n useActiveDocument,\n useDocumentManagerCapability,\n useDocumentManagerPlugin,\n useOpenDocuments\n};\n//# sourceMappingURL=index.js.map\n","import { BasePlugin, createBehaviorEmitter, createEmitter } from \"@embedpdf/core\";\nconst VIEWPORT_PLUGIN_ID = \"viewport\";\nconst manifest = {\n id: VIEWPORT_PLUGIN_ID,\n name: \"Viewport Plugin\",\n version: \"1.0.0\",\n provides: [\"viewport\"],\n requires: [],\n optional: [],\n defaultConfig: {\n viewportGap: 10,\n scrollEndDelay: 300\n }\n};\nconst INIT_VIEWPORT_STATE = \"INIT_VIEWPORT_STATE\";\nconst CLEANUP_VIEWPORT_STATE = \"CLEANUP_VIEWPORT_STATE\";\nconst REGISTER_VIEWPORT = \"REGISTER_VIEWPORT\";\nconst UNREGISTER_VIEWPORT = \"UNREGISTER_VIEWPORT\";\nconst SET_VIEWPORT_METRICS = \"SET_VIEWPORT_METRICS\";\nconst SET_VIEWPORT_SCROLL_METRICS = \"SET_VIEWPORT_SCROLL_METRICS\";\nconst SET_VIEWPORT_GAP = \"SET_VIEWPORT_GAP\";\nconst SET_SCROLL_ACTIVITY = \"SET_SCROLL_ACTIVITY\";\nconst SET_SMOOTH_SCROLL_ACTIVITY = \"SET_SMOOTH_SCROLL_ACTIVITY\";\nconst SET_ACTIVE_VIEWPORT_DOCUMENT = \"SET_ACTIVE_VIEWPORT_DOCUMENT\";\nconst ADD_VIEWPORT_GATE = \"ADD_VIEWPORT_GATE\";\nconst REMOVE_VIEWPORT_GATE = \"REMOVE_VIEWPORT_GATE\";\nfunction initViewportState(documentId) {\n return { type: INIT_VIEWPORT_STATE, payload: { documentId } };\n}\nfunction cleanupViewportState(documentId) {\n return { type: CLEANUP_VIEWPORT_STATE, payload: { documentId } };\n}\nfunction registerViewport(documentId) {\n return { type: REGISTER_VIEWPORT, payload: { documentId } };\n}\nfunction unregisterViewport(documentId) {\n return { type: UNREGISTER_VIEWPORT, payload: { documentId } };\n}\nfunction setViewportGap(viewportGap) {\n return { type: SET_VIEWPORT_GAP, payload: viewportGap };\n}\nfunction setViewportMetrics(documentId, metrics) {\n return { type: SET_VIEWPORT_METRICS, payload: { documentId, metrics } };\n}\nfunction setViewportScrollMetrics(documentId, scrollMetrics) {\n return { type: SET_VIEWPORT_SCROLL_METRICS, payload: { documentId, scrollMetrics } };\n}\nfunction setScrollActivity(documentId, isScrolling) {\n return { type: SET_SCROLL_ACTIVITY, payload: { documentId, isScrolling } };\n}\nfunction setSmoothScrollActivity(documentId, isSmoothScrolling) {\n return { type: SET_SMOOTH_SCROLL_ACTIVITY, payload: { documentId, isSmoothScrolling } };\n}\nfunction addViewportGate(documentId, key) {\n return { type: ADD_VIEWPORT_GATE, payload: { documentId, key } };\n}\nfunction removeViewportGate(documentId, key) {\n return { type: REMOVE_VIEWPORT_GATE, payload: { documentId, key } };\n}\nconst initialViewportDocumentState = {\n viewportMetrics: {\n width: 0,\n height: 0,\n scrollTop: 0,\n scrollLeft: 0,\n clientWidth: 0,\n clientHeight: 0,\n scrollWidth: 0,\n scrollHeight: 0,\n clientLeft: 0,\n clientTop: 0,\n relativePosition: { x: 0, y: 0 }\n },\n isScrolling: false,\n isSmoothScrolling: false,\n gates: /* @__PURE__ */ new Set()\n};\nconst initialState = {\n viewportGap: 0,\n documents: {},\n activeViewports: /* @__PURE__ */ new Set(),\n activeDocumentId: null\n};\nconst viewportReducer = (state = initialState, action) => {\n switch (action.type) {\n // ─────────────────────────────────────────────────────────\n // State Persistence (Document Lifecycle)\n // ─────────────────────────────────────────────────────────\n case INIT_VIEWPORT_STATE: {\n const { documentId } = action.payload;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: { ...initialViewportDocumentState, gates: /* @__PURE__ */ new Set() }\n }\n };\n }\n case CLEANUP_VIEWPORT_STATE: {\n const { documentId } = action.payload;\n const { [documentId]: removed, ...remainingDocs } = state.documents;\n const newActiveViewports = new Set(state.activeViewports);\n newActiveViewports.delete(documentId);\n return {\n ...state,\n documents: remainingDocs,\n activeViewports: newActiveViewports,\n activeDocumentId: state.activeDocumentId === documentId ? null : state.activeDocumentId\n };\n }\n // ─────────────────────────────────────────────────────────\n // Viewport Registration (DOM Lifecycle)\n // ─────────────────────────────────────────────────────────\n case REGISTER_VIEWPORT: {\n const { documentId } = action.payload;\n const newActiveViewports = new Set(state.activeViewports);\n newActiveViewports.add(documentId);\n return {\n ...state,\n activeViewports: newActiveViewports,\n // Set as active if no active document\n activeDocumentId: state.activeDocumentId ?? documentId\n };\n }\n case UNREGISTER_VIEWPORT: {\n const { documentId } = action.payload;\n const newActiveViewports = new Set(state.activeViewports);\n newActiveViewports.delete(documentId);\n return {\n ...state,\n activeViewports: newActiveViewports\n };\n }\n case SET_ACTIVE_VIEWPORT_DOCUMENT: {\n return {\n ...state,\n activeDocumentId: action.payload\n };\n }\n // ─────────────────────────────────────────────────────────\n // Viewport Operations\n // ─────────────────────────────────────────────────────────\n case SET_VIEWPORT_GAP: {\n return {\n ...state,\n viewportGap: action.payload\n };\n }\n case SET_VIEWPORT_METRICS: {\n const { documentId, metrics } = action.payload;\n const viewport = state.documents[documentId];\n if (!viewport) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...viewport,\n viewportMetrics: {\n width: metrics.width,\n height: metrics.height,\n scrollTop: metrics.scrollTop,\n scrollLeft: metrics.scrollLeft,\n clientWidth: metrics.clientWidth,\n clientHeight: metrics.clientHeight,\n scrollWidth: metrics.scrollWidth,\n scrollHeight: metrics.scrollHeight,\n clientLeft: metrics.clientLeft,\n clientTop: metrics.clientTop,\n relativePosition: {\n x: metrics.scrollWidth <= metrics.clientWidth ? 0 : metrics.scrollLeft / (metrics.scrollWidth - metrics.clientWidth),\n y: metrics.scrollHeight <= metrics.clientHeight ? 0 : metrics.scrollTop / (metrics.scrollHeight - metrics.clientHeight)\n }\n }\n }\n }\n };\n }\n case SET_VIEWPORT_SCROLL_METRICS: {\n const { documentId, scrollMetrics } = action.payload;\n const viewport = state.documents[documentId];\n if (!viewport) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...viewport,\n viewportMetrics: {\n ...viewport.viewportMetrics,\n scrollTop: scrollMetrics.scrollTop,\n scrollLeft: scrollMetrics.scrollLeft\n },\n isScrolling: true\n }\n }\n };\n }\n case SET_SCROLL_ACTIVITY: {\n const { documentId, isScrolling } = action.payload;\n const viewport = state.documents[documentId];\n if (!viewport) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...viewport,\n isScrolling\n }\n }\n };\n }\n case SET_SMOOTH_SCROLL_ACTIVITY: {\n const { documentId, isSmoothScrolling } = action.payload;\n const viewport = state.documents[documentId];\n if (!viewport) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...viewport,\n isSmoothScrolling\n }\n }\n };\n }\n // ─────────────────────────────────────────────────────────\n // Named Gate Operations\n // ─────────────────────────────────────────────────────────\n case ADD_VIEWPORT_GATE: {\n const { documentId, key } = action.payload;\n const viewport = state.documents[documentId];\n if (!viewport) return state;\n const newGates = new Set(viewport.gates);\n newGates.add(key);\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...viewport,\n gates: newGates\n }\n }\n };\n }\n case REMOVE_VIEWPORT_GATE: {\n const { documentId, key } = action.payload;\n const viewport = state.documents[documentId];\n if (!viewport) return state;\n const newGates = new Set(viewport.gates);\n newGates.delete(key);\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...viewport,\n gates: newGates\n }\n }\n };\n }\n default:\n return state;\n }\n};\nconst _ViewportPlugin = class _ViewportPlugin extends BasePlugin {\n constructor(id, registry, config) {\n super(id, registry);\n this.id = id;\n this.viewportResize$ = createBehaviorEmitter();\n this.viewportMetrics$ = createBehaviorEmitter();\n this.scrollMetrics$ = createBehaviorEmitter();\n this.scrollActivity$ = createBehaviorEmitter();\n this.gateState$ = createBehaviorEmitter();\n this.scrollRequests$ = /* @__PURE__ */ new Map();\n if (config.viewportGap) {\n this.dispatch(setViewportGap(config.viewportGap));\n }\n this.scrollEndDelay = config.scrollEndDelay || 100;\n }\n // ─────────────────────────────────────────────────────────\n // Document Lifecycle (from BasePlugin)\n // ─────────────────────────────────────────────────────────\n onDocumentLoadingStarted(documentId) {\n this.dispatch(initViewportState(documentId));\n this.scrollRequests$.set(documentId, createEmitter());\n this.logger.debug(\n \"ViewportPlugin\",\n \"DocumentOpened\",\n `Initialized viewport state for document: ${documentId}`\n );\n }\n onDocumentClosed(documentId) {\n var _a;\n this.dispatch(cleanupViewportState(documentId));\n (_a = this.scrollRequests$.get(documentId)) == null ? void 0 : _a.clear();\n this.scrollRequests$.delete(documentId);\n this.logger.debug(\n \"ViewportPlugin\",\n \"DocumentClosed\",\n `Cleaned up viewport state for document: ${documentId}`\n );\n }\n // ─────────────────────────────────────────────────────────\n // Capability\n // ─────────────────────────────────────────────────────────\n buildCapability() {\n return {\n // Global\n getViewportGap: () => this.state.viewportGap,\n // Active document operations\n getMetrics: () => this.getMetrics(),\n scrollTo: (pos) => this.scrollTo(pos),\n isScrolling: () => this.isScrolling(),\n isSmoothScrolling: () => this.isSmoothScrolling(),\n isGated: (documentId) => this.isGated(documentId),\n hasGate: (key, documentId) => this.hasGate(key, documentId),\n getGates: (documentId) => this.getGates(documentId),\n // Document-scoped operations\n forDocument: (documentId) => this.createViewportScope(documentId),\n gate: (key, documentId) => this.gate(key, documentId),\n releaseGate: (key, documentId) => this.releaseGate(key, documentId),\n // Check if viewport is currently mounted\n isViewportMounted: (documentId) => this.state.activeViewports.has(documentId),\n // Events\n onViewportChange: this.viewportMetrics$.on,\n onViewportResize: this.viewportResize$.on,\n onScrollChange: this.scrollMetrics$.on,\n onScrollActivity: this.scrollActivity$.on,\n onGateChange: this.gateState$.on\n };\n }\n // ─────────────────────────────────────────────────────────\n // Document Scoping\n // ─────────────────────────────────────────────────────────\n createViewportScope(documentId) {\n return {\n getMetrics: () => this.getMetrics(documentId),\n scrollTo: (pos) => this.scrollTo(pos, documentId),\n isScrolling: () => this.isScrolling(documentId),\n isSmoothScrolling: () => this.isSmoothScrolling(documentId),\n isGated: () => this.isGated(documentId),\n hasGate: (key) => this.hasGate(key, documentId),\n getGates: () => this.getGates(documentId),\n gate: (key) => this.gate(key, documentId),\n releaseGate: (key) => this.releaseGate(key, documentId),\n onViewportChange: (listener) => this.viewportMetrics$.on((event) => {\n if (event.documentId === documentId) listener(event.metrics);\n }),\n onScrollChange: (listener) => this.scrollMetrics$.on((event) => {\n if (event.documentId === documentId) listener(event.scrollMetrics);\n }),\n onScrollActivity: (listener) => this.scrollActivity$.on((event) => {\n if (event.documentId === documentId) listener(event.activity);\n }),\n onGateChange: (listener) => this.gateState$.on((event) => {\n if ((event == null ? void 0 : event.documentId) === documentId) listener(event);\n })\n };\n }\n // ─────────────────────────────────────────────────────────\n // Viewport Registration (Public API for components)\n // ─────────────────────────────────────────────────────────\n registerViewport(documentId) {\n if (!this.state.documents[documentId]) {\n throw new Error(\n `Cannot register viewport for ${documentId}: document state not found. Document must be opened before registering viewport.`\n );\n }\n if (!this.state.activeViewports.has(documentId)) {\n this.dispatch(registerViewport(documentId));\n this.logger.debug(\n \"ViewportPlugin\",\n \"RegisterViewport\",\n `Registered viewport (DOM mounted) for document: ${documentId}`\n );\n }\n }\n unregisterViewport(documentId) {\n if (this.registry.isDestroyed()) return;\n if (this.state.activeViewports.has(documentId)) {\n this.dispatch(unregisterViewport(documentId));\n this.logger.debug(\n \"ViewportPlugin\",\n \"UnregisterViewport\",\n `Unregistered viewport (DOM unmounted) for document: ${documentId}. State preserved.`\n );\n }\n }\n // ─────────────────────────────────────────────────────────\n // Per-Document Operations\n // ─────────────────────────────────────────────────────────\n setViewportResizeMetrics(documentId, metrics) {\n if (this.registry.isDestroyed()) return;\n this.dispatch(setViewportMetrics(documentId, metrics));\n const viewport = this.state.documents[documentId];\n if (viewport) {\n this.viewportResize$.emit({\n documentId,\n metrics: viewport.viewportMetrics\n });\n }\n }\n setViewportScrollMetrics(documentId, scrollMetrics) {\n if (this.registry.isDestroyed()) return;\n const viewport = this.state.documents[documentId];\n if (!viewport) return;\n if (scrollMetrics.scrollTop !== viewport.viewportMetrics.scrollTop || scrollMetrics.scrollLeft !== viewport.viewportMetrics.scrollLeft) {\n this.dispatch(setViewportScrollMetrics(documentId, scrollMetrics));\n this.bumpScrollActivity(documentId);\n this.scrollMetrics$.emit({\n documentId,\n scrollMetrics\n });\n }\n }\n onScrollRequest(documentId, listener) {\n const emitter = this.scrollRequests$.get(documentId);\n if (!emitter) {\n throw new Error(\n `Cannot subscribe to scroll requests for ${documentId}: document state not initialized`\n );\n }\n return emitter.on(listener);\n }\n // ─────────────────────────────────────────────────────────\n // Public Gating API\n // ─────────────────────────────────────────────────────────\n gate(key, documentId) {\n const viewport = this.state.documents[documentId];\n if (!viewport) {\n this.logger.warn(\n \"ViewportPlugin\",\n \"GateViewport\",\n `Cannot gate viewport for ${documentId}: document not found`\n );\n return;\n }\n if (!viewport.gates.has(key)) {\n this.dispatch(addViewportGate(documentId, key));\n this.logger.debug(\n \"ViewportPlugin\",\n \"GateAdded\",\n `Added gate '${key}' for document: ${documentId}. Total gates: ${viewport.gates.size + 1}`\n );\n }\n }\n releaseGate(key, documentId) {\n const viewport = this.state.documents[documentId];\n if (!viewport) {\n this.logger.warn(\n \"ViewportPlugin\",\n \"ReleaseGate\",\n `Cannot release gate for ${documentId}: document not found`\n );\n return;\n }\n if (viewport.gates.has(key)) {\n this.dispatch(removeViewportGate(documentId, key));\n this.logger.debug(\n \"ViewportPlugin\",\n \"GateReleased\",\n `Released gate '${key}' for document: ${documentId}. Remaining gates: ${viewport.gates.size - 1}`\n );\n }\n }\n // ─────────────────────────────────────────────────────────\n // Helper Methods\n // ─────────────────────────────────────────────────────────\n getViewportState(documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const viewport = this.state.documents[id];\n if (!viewport) {\n throw new Error(`Viewport state not found for document: ${id}`);\n }\n return viewport;\n }\n getMetrics(documentId) {\n return this.getViewportState(documentId).viewportMetrics;\n }\n isScrolling(documentId) {\n return this.getViewportState(documentId).isScrolling;\n }\n isSmoothScrolling(documentId) {\n return this.getViewportState(documentId).isSmoothScrolling;\n }\n isGated(documentId) {\n const viewport = this.getViewportState(documentId);\n return viewport.gates.size > 0;\n }\n hasGate(key, documentId) {\n const viewport = this.getViewportState(documentId);\n return viewport.gates.has(key);\n }\n getGates(documentId) {\n const viewport = this.getViewportState(documentId);\n return Array.from(viewport.gates);\n }\n scrollTo(pos, documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const viewport = this.getViewportState(id);\n const { x, y, alignX, alignY, behavior = \"auto\" } = pos;\n if (behavior === \"smooth\") {\n this.dispatch(setSmoothScrollActivity(id, true));\n }\n const metrics = viewport.viewportMetrics;\n let finalX = x;\n let finalY = y;\n if (alignX !== void 0) {\n finalX = x - metrics.clientWidth * (alignX / 100);\n }\n if (alignY !== void 0) {\n finalY = y - metrics.clientHeight * (alignY / 100);\n }\n const emitter = this.scrollRequests$.get(id);\n if (emitter) {\n emitter.emit({ x: finalX, y: finalY, behavior });\n }\n }\n bumpScrollActivity(documentId) {\n this.debouncedDispatch(setScrollActivity(documentId, false), this.scrollEndDelay);\n this.debouncedDispatch(setSmoothScrollActivity(documentId, false), this.scrollEndDelay);\n }\n // ─────────────────────────────────────────────────────────\n // State Change Handling\n // ─────────────────────────────────────────────────────────\n onStoreUpdated(prevState, newState) {\n for (const documentId in newState.documents) {\n const prevViewport = prevState.documents[documentId];\n const newViewport = newState.documents[documentId];\n if (prevViewport !== newViewport) {\n this.viewportMetrics$.emit({\n documentId,\n metrics: newViewport.viewportMetrics\n });\n if (prevViewport && (prevViewport.isScrolling !== newViewport.isScrolling || prevViewport.isSmoothScrolling !== newViewport.isSmoothScrolling)) {\n this.scrollActivity$.emit({\n documentId,\n activity: {\n isScrolling: newViewport.isScrolling,\n isSmoothScrolling: newViewport.isSmoothScrolling\n }\n });\n }\n if (prevViewport && prevViewport.gates !== newViewport.gates) {\n const prevGates = Array.from(prevViewport.gates);\n const newGates = Array.from(newViewport.gates);\n const addedGate = newGates.find((g) => !prevGates.includes(g));\n const removedGate = prevGates.find((g) => !newGates.includes(g));\n this.gateState$.emit({\n documentId,\n isGated: newViewport.gates.size > 0,\n gates: newGates,\n addedGate,\n removedGate\n });\n this.logger.debug(\n \"ViewportPlugin\",\n \"GateStateChanged\",\n `Gate state changed for document ${documentId}. Gates: [${newGates.join(\", \")}], Gated: ${newViewport.gates.size > 0}`\n );\n }\n }\n }\n }\n // ─────────────────────────────────────────────────────────\n // Lifecycle\n // ─────────────────────────────────────────────────────────\n async initialize(_config) {\n this.logger.info(\"ViewportPlugin\", \"Initialize\", \"Viewport plugin initialized\");\n }\n async destroy() {\n this.viewportMetrics$.clear();\n this.viewportResize$.clear();\n this.scrollMetrics$.clear();\n this.scrollActivity$.clear();\n this.gateState$.clear();\n this.scrollRequests$.forEach((emitter) => emitter.clear());\n this.scrollRequests$.clear();\n super.destroy();\n }\n};\n_ViewportPlugin.id = \"viewport\";\nlet ViewportPlugin = _ViewportPlugin;\nconst ViewportPluginPackage = {\n manifest,\n create: (registry, config) => new ViewportPlugin(VIEWPORT_PLUGIN_ID, registry, config),\n reducer: viewportReducer,\n initialState\n};\nexport {\n VIEWPORT_PLUGIN_ID,\n ViewportPlugin,\n ViewportPluginPackage,\n manifest\n};\n//# sourceMappingURL=index.js.map\n","import { jsx } from \"react/jsx-runtime\";\nimport { createContext, useState, useEffect, useContext, useRef, useLayoutEffect } from \"react\";\nimport { useCapability, usePlugin } from \"@embedpdf/core/react\";\nimport { ViewportPlugin } from \"@embedpdf/plugin-viewport\";\nexport * from \"@embedpdf/plugin-viewport\";\nconst ViewportElementContext = createContext(null);\nconst useViewportPlugin = () => usePlugin(ViewportPlugin.id);\nconst useViewportCapability = () => useCapability(ViewportPlugin.id);\nconst useViewportElement = () => {\n return useContext(ViewportElementContext);\n};\nconst useIsViewportGated = (documentId) => {\n const { provides } = useViewportCapability();\n const [isGated, setIsGated] = useState((provides == null ? void 0 : provides.isGated(documentId)) ?? false);\n useEffect(() => {\n if (!provides) return;\n setIsGated(provides.isGated(documentId));\n return provides.onGateChange((event) => {\n if (event.documentId === documentId) {\n setIsGated(event.isGated);\n }\n });\n }, [provides, documentId]);\n return isGated;\n};\nconst useViewportScrollActivity = (documentId) => {\n const { provides } = useViewportCapability();\n const [scrollActivity, setScrollActivity] = useState({\n isScrolling: false,\n isSmoothScrolling: false\n });\n useEffect(() => {\n if (!provides) return;\n return provides.onScrollActivity((event) => {\n if (event.documentId === documentId) {\n setScrollActivity(event.activity);\n }\n });\n }, [provides, documentId]);\n return scrollActivity;\n};\nfunction useViewportRef(documentId) {\n const { plugin: viewportPlugin } = useViewportPlugin();\n const containerRef = useRef(null);\n useLayoutEffect(() => {\n if (!viewportPlugin) return;\n const container = containerRef.current;\n if (!container) return;\n try {\n viewportPlugin.registerViewport(documentId);\n } catch (error) {\n console.error(`Failed to register viewport for document ${documentId}:`, error);\n return;\n }\n const onScroll = () => {\n viewportPlugin.setViewportScrollMetrics(documentId, {\n scrollTop: container.scrollTop,\n scrollLeft: container.scrollLeft\n });\n };\n container.addEventListener(\"scroll\", onScroll);\n const resizeObserver = new ResizeObserver(() => {\n viewportPlugin.setViewportResizeMetrics(documentId, {\n width: container.offsetWidth,\n height: container.offsetHeight,\n clientWidth: container.clientWidth,\n clientHeight: container.clientHeight,\n scrollTop: container.scrollTop,\n scrollLeft: container.scrollLeft,\n scrollWidth: container.scrollWidth,\n scrollHeight: container.scrollHeight,\n clientLeft: container.clientLeft,\n clientTop: container.clientTop\n });\n });\n resizeObserver.observe(container);\n const unsubscribeScrollRequest = viewportPlugin.onScrollRequest(\n documentId,\n ({ x, y, behavior = \"auto\" }) => {\n requestAnimationFrame(() => {\n container.scrollTo({ left: x, top: y, behavior });\n });\n }\n );\n return () => {\n viewportPlugin.unregisterViewport(documentId);\n resizeObserver.disconnect();\n container.removeEventListener(\"scroll\", onScroll);\n unsubscribeScrollRequest();\n };\n }, [viewportPlugin, documentId]);\n return containerRef;\n}\nfunction Viewport({ children, documentId, ...props }) {\n const [viewportGap, setViewportGap] = useState(0);\n const viewportRef = useViewportRef(documentId);\n const { provides: viewportProvides } = useViewportCapability();\n const isGated = useIsViewportGated(documentId);\n useEffect(() => {\n if (viewportProvides) {\n setViewportGap(viewportProvides.getViewportGap());\n }\n }, [viewportProvides]);\n const { style, ...restProps } = props;\n return /* @__PURE__ */ jsx(ViewportElementContext.Provider, { value: viewportRef, children: /* @__PURE__ */ jsx(\n \"div\",\n {\n ...restProps,\n ref: viewportRef,\n style: {\n width: \"100%\",\n height: \"100%\",\n overflow: \"auto\",\n ...typeof style === \"object\" ? style : {},\n padding: `${viewportGap}px`\n },\n children: !isGated && children\n }\n ) });\n}\nexport {\n Viewport,\n ViewportElementContext,\n useIsViewportGated,\n useViewportCapability,\n useViewportElement,\n useViewportPlugin,\n useViewportRef,\n useViewportScrollActivity\n};\n//# sourceMappingURL=index.js.map\n","import { BasePlugin, createBehaviorEmitter } from \"@embedpdf/core\";\nimport { scalePosition, transformPosition, transformRect, transformSize } from \"@embedpdf/models\";\nvar ScrollStrategy = /* @__PURE__ */ ((ScrollStrategy2) => {\n ScrollStrategy2[\"Vertical\"] = \"vertical\";\n ScrollStrategy2[\"Horizontal\"] = \"horizontal\";\n return ScrollStrategy2;\n})(ScrollStrategy || {});\nclass BaseScrollStrategy {\n constructor(config) {\n this.pageGap = config.pageGap ?? 20;\n this.viewportGap = config.viewportGap ?? 20;\n this.bufferSize = config.bufferSize ?? 2;\n }\n /**\n * Horizontal centering offset for items narrower than the content max width.\n * Vertical layout centers spreads within the row; horizontal layout overrides to 0\n * since items stay in a simple row without centering.\n */\n getCenteringOffsetX(_item, totalContentSize) {\n if (!totalContentSize || _item.width >= totalContentSize.width) return 0;\n return (totalContentSize.width - _item.width) / 2;\n }\n /**\n * Vertical centering offset for items shorter than the content max height.\n * Horizontal layout centers items within the row height; vertical layout keeps\n * items top-aligned and uses the default of 0.\n */\n getCenteringOffsetY(_item, _totalContentSize) {\n return 0;\n }\n getVisibleRange(viewport, virtualItems, scale) {\n const scrollOffset = this.getScrollOffset(viewport);\n const clientSize = this.getClientSize(viewport);\n const viewportStart = scrollOffset;\n const viewportEnd = scrollOffset + clientSize;\n let startIndex = 0;\n while (startIndex < virtualItems.length && (virtualItems[startIndex].offset + this.getItemSizeAlongScrollAxis(virtualItems[startIndex])) * scale <= viewportStart) {\n startIndex++;\n }\n let endIndex = startIndex;\n while (endIndex < virtualItems.length && virtualItems[endIndex].offset * scale <= viewportEnd) {\n endIndex++;\n }\n return {\n start: Math.max(0, startIndex - this.bufferSize),\n end: Math.min(virtualItems.length - 1, endIndex + this.bufferSize - 1)\n };\n }\n handleScroll(viewport, virtualItems, scale) {\n const range = this.getVisibleRange(viewport, virtualItems, scale);\n const visibleItems = virtualItems.slice(range.start, range.end + 1);\n const totalContentSize = this.getTotalContentSize(virtualItems);\n const pageVisibilityMetrics = this.calculatePageVisibility(\n visibleItems,\n viewport,\n scale,\n totalContentSize\n );\n const visiblePages = pageVisibilityMetrics.map((m) => m.pageNumber);\n const renderedPageIndexes = virtualItems.slice(range.start, range.end + 1).flatMap((item) => item.index);\n const currentPage = this.determineCurrentPage(pageVisibilityMetrics);\n const first = virtualItems[range.start];\n const last = virtualItems[range.end];\n const startSpacing = first ? first.offset * scale : 0;\n const lastItem = virtualItems[virtualItems.length - 1];\n const endSpacing = last ? (lastItem.offset + this.getItemSizeAlongScrollAxis(lastItem)) * scale - (last.offset + this.getItemSizeAlongScrollAxis(last)) * scale : 0;\n return {\n currentPage,\n visiblePages,\n pageVisibilityMetrics,\n renderedPageIndexes,\n scrollOffset: { x: viewport.scrollLeft, y: viewport.scrollTop },\n startSpacing,\n endSpacing\n };\n }\n calculatePageVisibility(virtualItems, viewport, scale, totalContentSize) {\n const visibilityMetrics = [];\n virtualItems.forEach((item) => {\n const centeringOffsetX = this.getCenteringOffsetX(item, totalContentSize);\n const centeringOffsetY = this.getCenteringOffsetY(item, totalContentSize);\n item.pageLayouts.forEach((page) => {\n const itemX = (item.x + centeringOffsetX) * scale;\n const itemY = (item.y + centeringOffsetY) * scale;\n const pageX = itemX + page.x * scale;\n const pageY = itemY + page.y * scale;\n const pageWidth = page.rotatedWidth * scale;\n const pageHeight = page.rotatedHeight * scale;\n const viewportLeft = viewport.scrollLeft;\n const viewportTop = viewport.scrollTop;\n const viewportRight = viewportLeft + viewport.clientWidth;\n const viewportBottom = viewportTop + viewport.clientHeight;\n const intersectionLeft = Math.max(pageX, viewportLeft);\n const intersectionTop = Math.max(pageY, viewportTop);\n const intersectionRight = Math.min(pageX + pageWidth, viewportRight);\n const intersectionBottom = Math.min(pageY + pageHeight, viewportBottom);\n if (intersectionLeft < intersectionRight && intersectionTop < intersectionBottom) {\n const visibleWidth = intersectionRight - intersectionLeft;\n const visibleHeight = intersectionBottom - intersectionTop;\n const totalArea = pageWidth * pageHeight;\n const visibleArea = visibleWidth * visibleHeight;\n visibilityMetrics.push({\n pageNumber: page.pageNumber,\n viewportX: intersectionLeft - viewportLeft,\n viewportY: intersectionTop - viewportTop,\n visiblePercentage: visibleArea / totalArea * 100,\n original: {\n pageX: (intersectionLeft - pageX) / scale,\n pageY: (intersectionTop - pageY) / scale,\n visibleWidth: visibleWidth / scale,\n visibleHeight: visibleHeight / scale,\n scale: 1\n },\n scaled: {\n pageX: intersectionLeft - pageX,\n pageY: intersectionTop - pageY,\n visibleWidth,\n visibleHeight,\n scale\n }\n });\n }\n });\n });\n return visibilityMetrics;\n }\n determineCurrentPage(visibilityMetrics) {\n if (visibilityMetrics.length === 0) return 1;\n const maxVisibility = Math.max(...visibilityMetrics.map((m) => m.visiblePercentage));\n const mostVisiblePages = visibilityMetrics.filter((m) => m.visiblePercentage === maxVisibility);\n return mostVisiblePages.length === 1 ? mostVisiblePages[0].pageNumber : mostVisiblePages.sort((a, b) => a.pageNumber - b.pageNumber)[0].pageNumber;\n }\n getRectLocationForPage(pageNumber, virtualItems, totalContentSize) {\n const item = virtualItems.find((item2) => item2.pageNumbers.includes(pageNumber));\n if (!item) return null;\n const pageLayout = item.pageLayouts.find((layout) => layout.pageNumber === pageNumber);\n if (!pageLayout) return null;\n const centeringOffsetX = this.getCenteringOffsetX(item, totalContentSize);\n const centeringOffsetY = this.getCenteringOffsetY(item, totalContentSize);\n return {\n origin: {\n x: item.x + pageLayout.x + centeringOffsetX,\n y: item.y + pageLayout.y + centeringOffsetY\n },\n size: {\n width: pageLayout.width,\n height: pageLayout.height\n }\n };\n }\n getScrollPositionForPage(pageNumber, virtualItems, scale, rotation, pageCoordinates) {\n const totalContentSize = this.getTotalContentSize(virtualItems);\n const pageRect = this.getRectLocationForPage(pageNumber, virtualItems, totalContentSize);\n if (!pageRect) return null;\n const scaledBasePosition = scalePosition(pageRect.origin, scale);\n if (pageCoordinates) {\n const rotatedSize = transformPosition(\n {\n width: pageRect.size.width,\n height: pageRect.size.height\n },\n {\n x: pageCoordinates.x,\n y: pageCoordinates.y\n },\n rotation,\n scale\n );\n return {\n x: scaledBasePosition.x + rotatedSize.x + this.viewportGap,\n y: scaledBasePosition.y + rotatedSize.y + this.viewportGap\n };\n }\n return {\n x: scaledBasePosition.x + this.viewportGap,\n y: scaledBasePosition.y + this.viewportGap\n };\n }\n getRectPositionForPage(pageNumber, virtualItems, scale, rotation, rect) {\n const totalContentSize = this.getTotalContentSize(virtualItems);\n const pageRect = this.getRectLocationForPage(pageNumber, virtualItems, totalContentSize);\n if (!pageRect) return null;\n const scaledBasePosition = scalePosition(pageRect.origin, scale);\n const rotatedSize = transformRect(\n {\n width: pageRect.size.width,\n height: pageRect.size.height\n },\n rect,\n rotation,\n scale\n );\n return {\n origin: {\n x: scaledBasePosition.x + rotatedSize.origin.x,\n y: scaledBasePosition.y + rotatedSize.origin.y\n },\n size: rotatedSize.size\n };\n }\n}\nclass VerticalScrollStrategy extends BaseScrollStrategy {\n constructor(config) {\n super(config);\n }\n createVirtualItems(pdfPageObject) {\n let yOffset = 0;\n return pdfPageObject.map((pagesInSpread, index) => {\n let pageX = 0;\n const pageLayouts = pagesInSpread.map((page) => {\n const layout = {\n pageNumber: page.index + 1,\n pageIndex: page.index,\n x: pageX,\n y: 0,\n width: page.size.width,\n height: page.size.height,\n rotatedWidth: page.rotatedSize.width,\n rotatedHeight: page.rotatedSize.height,\n elevated: false\n };\n pageX += page.rotatedSize.width + this.pageGap;\n return layout;\n });\n const width = pagesInSpread.reduce(\n (sum, page, i) => sum + page.rotatedSize.width + (i < pagesInSpread.length - 1 ? this.pageGap : 0),\n 0\n );\n const height = Math.max(...pagesInSpread.map((p) => p.rotatedSize.height));\n const item = {\n id: `item-${index}`,\n x: 0,\n y: yOffset,\n offset: yOffset,\n width,\n height,\n pageLayouts,\n pageNumbers: pagesInSpread.map((p) => p.index + 1),\n index\n };\n yOffset += height + this.pageGap;\n return item;\n });\n }\n getTotalContentSize(virtualItems) {\n if (virtualItems.length === 0) return { width: 0, height: 0 };\n const maxWidth = Math.max(...virtualItems.map((item) => item.width));\n const totalHeight = virtualItems[virtualItems.length - 1].y + virtualItems[virtualItems.length - 1].height;\n return {\n width: maxWidth,\n height: totalHeight\n };\n }\n getScrollOffset(viewport) {\n return viewport.scrollTop;\n }\n getClientSize(viewport) {\n return viewport.clientHeight;\n }\n /** Vertical scroll: extent along scroll axis is height. */\n getItemSizeAlongScrollAxis(item) {\n return item.height;\n }\n}\nclass HorizontalScrollStrategy extends BaseScrollStrategy {\n constructor(config) {\n super(config);\n }\n createVirtualItems(pdfPageObject) {\n let xOffset = 0;\n return pdfPageObject.map((pagesInSpread, index) => {\n let pageX = 0;\n const pageLayouts = pagesInSpread.map((page) => {\n const layout = {\n pageNumber: page.index + 1,\n pageIndex: page.index,\n x: pageX,\n y: 0,\n width: page.size.width,\n height: page.size.height,\n rotatedWidth: page.rotatedSize.width,\n rotatedHeight: page.rotatedSize.height,\n elevated: false\n };\n pageX += page.rotatedSize.width + this.pageGap;\n return layout;\n });\n const width = pagesInSpread.reduce(\n (sum, page, i) => sum + page.rotatedSize.width + (i < pagesInSpread.length - 1 ? this.pageGap : 0),\n 0\n );\n const height = Math.max(...pagesInSpread.map((p) => p.rotatedSize.height));\n const item = {\n id: `item-${index}`,\n x: xOffset,\n y: 0,\n offset: xOffset,\n width,\n height,\n pageLayouts,\n pageNumbers: pagesInSpread.map((p) => p.index + 1),\n index\n };\n xOffset += width + this.pageGap;\n return item;\n });\n }\n getTotalContentSize(virtualItems) {\n if (virtualItems.length === 0) return { width: 0, height: 0 };\n const totalWidth = virtualItems[virtualItems.length - 1].x + virtualItems[virtualItems.length - 1].width;\n const maxHeight = Math.max(...virtualItems.map((item) => item.height));\n return {\n width: totalWidth,\n height: maxHeight\n };\n }\n getScrollOffset(viewport) {\n return viewport.scrollLeft;\n }\n getClientSize(viewport) {\n return viewport.clientWidth;\n }\n /** Horizontal scroll: extent along scroll axis is width. */\n getItemSizeAlongScrollAxis(item) {\n return item.width;\n }\n /**\n * No centering for horizontal layout. Items are laid out in a simple row;\n * using total content width would produce incorrect offsets and shift pages.\n */\n /* eslint-disable no-unused-vars -- override intentionally ignores params */\n getCenteringOffsetX(_item, _totalContentSize) {\n return 0;\n }\n /**\n * Horizontal rows visually center shorter items within the tallest row height.\n * Match that DOM layout so page-coordinate targeting lands on the rendered page.\n */\n getCenteringOffsetY(item, totalContentSize) {\n if (!totalContentSize || item.height >= totalContentSize.height) return 0;\n return (totalContentSize.height - item.height) / 2;\n }\n}\nconst INIT_SCROLL_STATE = \"INIT_SCROLL_STATE\";\nconst CLEANUP_SCROLL_STATE = \"CLEANUP_SCROLL_STATE\";\nconst UPDATE_DOCUMENT_SCROLL_STATE = \"UPDATE_DOCUMENT_SCROLL_STATE\";\nconst SET_SCROLL_STRATEGY = \"SET_SCROLL_STRATEGY\";\nfunction initScrollState(documentId, state) {\n return { type: INIT_SCROLL_STATE, payload: { documentId, state } };\n}\nfunction cleanupScrollState(documentId) {\n return { type: CLEANUP_SCROLL_STATE, payload: documentId };\n}\nfunction updateDocumentScrollState(documentId, state) {\n return { type: UPDATE_DOCUMENT_SCROLL_STATE, payload: { documentId, state } };\n}\nfunction setScrollStrategy(documentId, strategy) {\n return { type: SET_SCROLL_STRATEGY, payload: { documentId, strategy } };\n}\nconst defaultPageChangeState = {\n isChanging: false,\n targetPage: 1,\n fromPage: 1,\n startTime: 0\n};\nconst initialState = (_coreState, config) => ({\n defaultStrategy: config.defaultStrategy ?? ScrollStrategy.Vertical,\n defaultPageGap: config.defaultPageGap ?? 10,\n defaultBufferSize: config.defaultBufferSize ?? 2,\n documents: {}\n});\nconst scrollReducer = (state, action) => {\n switch (action.type) {\n case INIT_SCROLL_STATE: {\n const { documentId, state: docState } = action.payload;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: docState\n }\n };\n }\n case CLEANUP_SCROLL_STATE: {\n const { [action.payload]: removed, ...remaining } = state.documents;\n return {\n ...state,\n documents: remaining\n };\n }\n case UPDATE_DOCUMENT_SCROLL_STATE: {\n const { documentId, state: updates } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...docState,\n ...updates\n }\n }\n };\n }\n case SET_SCROLL_STRATEGY: {\n const { documentId, strategy } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...docState,\n strategy\n }\n }\n };\n }\n default:\n return state;\n }\n};\nconst getScrollerLayout = (documentState, scale, elevatedPages) => {\n return {\n startSpacing: documentState.startSpacing,\n endSpacing: documentState.endSpacing,\n totalWidth: documentState.totalContentSize.width * scale,\n totalHeight: documentState.totalContentSize.height * scale,\n pageGap: documentState.pageGap * scale,\n strategy: documentState.strategy,\n items: documentState.renderedPageIndexes.map((idx) => {\n return {\n ...documentState.virtualItems[idx],\n pageLayouts: documentState.virtualItems[idx].pageLayouts.map((layout) => {\n return {\n ...layout,\n rotatedWidth: layout.rotatedWidth * scale,\n rotatedHeight: layout.rotatedHeight * scale,\n width: layout.width * scale,\n height: layout.height * scale,\n elevated: (elevatedPages == null ? void 0 : elevatedPages.has(layout.pageIndex)) ?? false\n };\n })\n };\n })\n };\n};\nconst _ScrollPlugin = class _ScrollPlugin extends BasePlugin {\n constructor(id, registry, config) {\n var _a, _b, _c;\n super(id, registry);\n this.id = id;\n this.config = config;\n this.elevatedPages = /* @__PURE__ */ new Map();\n this.strategies = /* @__PURE__ */ new Map();\n this.layoutReady = /* @__PURE__ */ new Set();\n this.initialLayoutFired = /* @__PURE__ */ new Set();\n this.scrollerLayoutEmitters = /* @__PURE__ */ new Map();\n this.pageChange$ = createBehaviorEmitter();\n this.scroll$ = createBehaviorEmitter();\n this.layoutChange$ = createBehaviorEmitter();\n this.pageChangeState$ = createBehaviorEmitter();\n this.layoutReady$ = createBehaviorEmitter();\n this.state$ = createBehaviorEmitter();\n this.viewport = this.registry.getPlugin(\"viewport\").provides();\n this.spread = ((_a = this.registry.getPlugin(\"spread\")) == null ? void 0 : _a.provides()) ?? null;\n this.viewport.onScrollActivity((event) => {\n const docState = this.getDocumentState(event.documentId);\n if ((docState == null ? void 0 : docState.pageChangeState.isChanging) && !event.activity.isSmoothScrolling) {\n this.completePageChange(event.documentId);\n }\n });\n (_b = this.spread) == null ? void 0 : _b.onSpreadChange((event) => {\n this.refreshDocumentLayout(event.documentId);\n });\n const im = (_c = this.registry.getPlugin(\"interaction-manager\")) == null ? void 0 : _c.provides();\n if (im) {\n im.onPageActivityChange((event) => {\n let pages = this.elevatedPages.get(event.documentId);\n if (event.hasActivity) {\n if (!pages) {\n pages = /* @__PURE__ */ new Set();\n this.elevatedPages.set(event.documentId, pages);\n }\n pages.add(event.pageIndex);\n } else {\n pages == null ? void 0 : pages.delete(event.pageIndex);\n }\n this.pushScrollerLayout(event.documentId);\n });\n }\n this.viewport.onViewportChange((event) => {\n const docState = this.getDocumentState(event.documentId);\n if (!docState) return;\n const computedMetrics = this.computeMetrics(event.documentId, event.metrics);\n if (this.layoutReady.has(event.documentId)) {\n this.commitMetrics(event.documentId, computedMetrics);\n } else {\n this.commitMetrics(event.documentId, {\n ...computedMetrics,\n scrollOffset: docState.scrollOffset\n });\n }\n });\n }\n // ─────────────────────────────────────────────────────────\n // Document Lifecycle Hooks (from BasePlugin)\n // ─────────────────────────────────────────────────────────\n onDocumentLoadingStarted(documentId) {\n const coreDoc = this.getCoreDocument(documentId);\n if (!coreDoc) return;\n const docState = this.createDocumentState(coreDoc);\n this.dispatch(initScrollState(documentId, docState));\n const strategy = this.createStrategy(docState.strategy);\n this.strategies.set(documentId, strategy);\n this.scrollerLayoutEmitters.set(documentId, createBehaviorEmitter());\n }\n onDocumentLoaded(documentId) {\n var _a;\n const coreDoc = this.getCoreDocument(documentId);\n if (!coreDoc) return;\n this.dispatch(\n updateDocumentScrollState(documentId, { totalPages: ((_a = coreDoc.document) == null ? void 0 : _a.pageCount) ?? 0 })\n );\n this.refreshDocumentLayout(documentId);\n this.logger.debug(\n \"ScrollPlugin\",\n \"DocumentOpened\",\n `Initialized scroll state for document: ${documentId}`\n );\n }\n onDocumentClosed(documentId) {\n this.strategies.delete(documentId);\n this.layoutReady.delete(documentId);\n this.initialLayoutFired.delete(documentId);\n this.elevatedPages.delete(documentId);\n const emitter = this.scrollerLayoutEmitters.get(documentId);\n if (emitter) {\n emitter.clear();\n this.scrollerLayoutEmitters.delete(documentId);\n }\n this.dispatch(cleanupScrollState(documentId));\n this.logger.debug(\n \"ScrollPlugin\",\n \"DocumentClosed\",\n `Cleaned up scroll state for document: ${documentId}`\n );\n }\n onScaleChanged(documentId) {\n const coreDoc = this.coreState.core.documents[documentId];\n if (!coreDoc || coreDoc.status !== \"loaded\") return;\n const viewportScope = this.viewport.forDocument(documentId);\n const metrics = this.computeMetrics(documentId, viewportScope.getMetrics());\n this.commitMetrics(documentId, metrics);\n }\n onRotationChanged(documentId) {\n this.refreshDocumentLayout(documentId);\n }\n // ─────────────────────────────────────────────────────────\n // Public API for Components (Scroller Layout)\n // ─────────────────────────────────────────────────────────\n /**\n * Subscribe to scroller layout updates for a specific document\n * This is the key method for the Scroller component to stay reactive\n */\n onScrollerData(documentId, callback) {\n const emitter = this.scrollerLayoutEmitters.get(documentId);\n if (!emitter) {\n throw new Error(`No scroller layout emitter found for document: ${documentId}`);\n }\n return emitter.on(callback);\n }\n /**\n * Get current scroller layout for a document\n */\n getScrollerLayout(documentId) {\n const docState = this.getDocumentState(documentId);\n const coreDoc = this.getCoreDocumentOrThrow(documentId);\n if (!docState || !coreDoc) {\n throw new Error(`Cannot get scroller layout for document: ${documentId}`);\n }\n return getScrollerLayout(docState, coreDoc.scale, this.elevatedPages.get(documentId));\n }\n setLayoutReady(documentId) {\n if (this.layoutReady.has(documentId)) {\n return;\n }\n const docState = this.getDocumentState(documentId);\n if (!docState) return;\n this.layoutReady.add(documentId);\n const isInitial = !this.initialLayoutFired.has(documentId);\n if (isInitial) {\n this.initialLayoutFired.add(documentId);\n }\n const viewport = this.viewport.forDocument(documentId);\n viewport.scrollTo({ ...docState.scrollOffset, behavior: \"instant\" });\n this.layoutReady$.emit({\n documentId,\n isInitial,\n pageNumber: docState.currentPage,\n totalPages: docState.totalPages\n });\n }\n clearLayoutReady(documentId) {\n this.layoutReady.delete(documentId);\n }\n // ─────────────────────────────────────────────────────────\n // Capability\n // ─────────────────────────────────────────────────────────\n buildCapability() {\n return {\n // Active document operations\n getCurrentPage: () => this.getCurrentPage(),\n getTotalPages: () => this.getTotalPages(),\n getPageChangeState: () => this.getPageChangeState(),\n scrollToPage: (options) => this.scrollToPage(options),\n scrollToNextPage: (behavior) => this.scrollToNextPage(behavior),\n scrollToPreviousPage: (behavior) => this.scrollToPreviousPage(behavior),\n getMetrics: (viewport) => this.getMetrics(viewport),\n getLayout: () => this.getLayout(),\n getRectPositionForPage: (page, rect, scale, rotation) => this.getRectPositionForPage(page, rect, scale, rotation),\n // Document-scoped operations\n forDocument: (documentId) => this.createScrollScope(documentId),\n // Global settings\n setScrollStrategy: (strategy, documentId) => this.setScrollStrategyForDocument(strategy, documentId),\n getPageGap: () => this.state.defaultPageGap,\n // Events\n onPageChange: this.pageChange$.on,\n onScroll: this.scroll$.on,\n onLayoutChange: this.layoutChange$.on,\n onLayoutReady: this.layoutReady$.on,\n onPageChangeState: this.pageChangeState$.on,\n onStateChange: this.state$.on\n };\n }\n // ─────────────────────────────────────────────────────────\n // Document Scoping\n // ─────────────────────────────────────────────────────────\n createScrollScope(documentId) {\n return {\n getCurrentPage: () => this.getCurrentPage(documentId),\n getTotalPages: () => this.getTotalPages(documentId),\n getPageChangeState: () => this.getPageChangeState(documentId),\n scrollToPage: (options) => this.scrollToPage(options, documentId),\n scrollToNextPage: (behavior) => this.scrollToNextPage(behavior, documentId),\n scrollToPreviousPage: (behavior) => this.scrollToPreviousPage(behavior, documentId),\n getSpreadPagesWithRotatedSize: () => this.getSpreadPagesWithRotatedSize(documentId),\n getMetrics: (viewport) => this.getMetrics(viewport, documentId),\n getLayout: () => this.getLayout(documentId),\n getRectPositionForPage: (page, rect, scale, rotation) => this.getRectPositionForPage(page, rect, scale, rotation, documentId),\n setScrollStrategy: (strategy) => this.setScrollStrategyForDocument(strategy, documentId),\n onPageChange: (listener) => this.pageChange$.on((event) => {\n if (event.documentId === documentId) listener(event);\n }),\n onScroll: (listener) => this.scroll$.on((event) => {\n if (event.documentId === documentId) listener(event.metrics);\n }),\n onLayoutChange: (listener) => this.layoutChange$.on((event) => {\n if (event.documentId === documentId) listener(event.layout);\n })\n };\n }\n // ─────────────────────────────────────────────────────────\n // State Helpers\n // ─────────────────────────────────────────────────────────\n getDocumentState(documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n return this.state.documents[id] ?? null;\n }\n getDocumentStateOrThrow(documentId) {\n const state = this.getDocumentState(documentId);\n if (!state) {\n throw new Error(`Scroll state not found for document: ${documentId ?? \"active\"}`);\n }\n return state;\n }\n getStrategy(documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const strategy = this.strategies.get(id);\n if (!strategy) {\n throw new Error(`Strategy not found for document: ${id}`);\n }\n return strategy;\n }\n createStrategy(strategyType) {\n const config = {\n pageGap: this.state.defaultPageGap,\n viewportGap: this.viewport.getViewportGap(),\n bufferSize: this.state.defaultBufferSize\n };\n return strategyType === ScrollStrategy.Horizontal ? new HorizontalScrollStrategy(config) : new VerticalScrollStrategy(config);\n }\n createDocumentState(coreDoc) {\n var _a;\n return {\n virtualItems: [],\n totalPages: ((_a = coreDoc.document) == null ? void 0 : _a.pageCount) ?? 0,\n currentPage: 1,\n totalContentSize: { width: 0, height: 0 },\n strategy: this.state.defaultStrategy,\n pageGap: this.state.defaultPageGap,\n visiblePages: [],\n pageVisibilityMetrics: [],\n renderedPageIndexes: [],\n scrollOffset: { x: 0, y: 0 },\n startSpacing: 0,\n endSpacing: 0,\n pageChangeState: defaultPageChangeState\n };\n }\n // ─────────────────────────────────────────────────────────\n // Page Change Management\n // ─────────────────────────────────────────────────────────\n startPageChange(documentId, targetPage, behavior = \"smooth\") {\n const docState = this.getDocumentState(documentId);\n if (!docState) return;\n const pageChangeState = {\n isChanging: true,\n targetPage,\n fromPage: docState.currentPage,\n startTime: Date.now()\n };\n this.dispatch(\n updateDocumentScrollState(documentId, {\n pageChangeState,\n currentPage: targetPage\n })\n );\n this.pageChange$.emit({\n documentId,\n pageNumber: targetPage,\n totalPages: docState.totalPages\n });\n if (behavior === \"instant\") {\n this.completePageChange(documentId);\n }\n }\n completePageChange(documentId) {\n const docState = this.getDocumentState(documentId);\n if (!docState || !docState.pageChangeState.isChanging) return;\n const pageChangeState = {\n isChanging: false,\n targetPage: docState.pageChangeState.targetPage,\n fromPage: docState.pageChangeState.fromPage,\n startTime: docState.pageChangeState.startTime\n };\n this.dispatch(updateDocumentScrollState(documentId, { pageChangeState }));\n }\n // ─────────────────────────────────────────────────────────\n // Layout & Metrics Computation\n // ─────────────────────────────────────────────────────────\n computeLayout(documentId, pages) {\n const strategy = this.getStrategy(documentId);\n const virtualItems = strategy.createVirtualItems(pages);\n const totalContentSize = strategy.getTotalContentSize(virtualItems);\n return { virtualItems, totalContentSize };\n }\n computeMetrics(documentId, vp, items) {\n const coreDocState = this.getCoreDocumentOrThrow(documentId);\n const docState = this.getDocumentState(documentId);\n const strategy = this.getStrategy(documentId);\n if (!docState) throw new Error(`Document state not found: ${documentId}`);\n return strategy.handleScroll(vp, items ?? docState.virtualItems, coreDocState.scale);\n }\n // ─────────────────────────────────────────────────────────\n // Commit (Single Source of Truth)\n // ─────────────────────────────────────────────────────────\n commitMetrics(documentId, metrics) {\n const docState = this.getDocumentState(documentId);\n if (!docState) return;\n const isProgrammaticScroll = docState.pageChangeState.isChanging;\n const metricsToCommit = isProgrammaticScroll && metrics.currentPage !== docState.currentPage ? { ...metrics, currentPage: docState.currentPage } : metrics;\n this.dispatch(updateDocumentScrollState(documentId, metricsToCommit));\n this.scroll$.emit({ documentId, metrics: metricsToCommit });\n if (!isProgrammaticScroll && metrics.currentPage !== docState.currentPage) {\n this.pageChange$.emit({\n documentId,\n pageNumber: metrics.currentPage,\n totalPages: docState.totalPages\n });\n }\n this.pushScrollerLayout(documentId);\n }\n pushScrollerLayout(documentId) {\n const emitter = this.scrollerLayoutEmitters.get(documentId);\n if (!emitter) return;\n try {\n const layout = this.getScrollerLayout(documentId);\n emitter.emit(layout);\n } catch (error) {\n }\n }\n refreshDocumentLayout(documentId) {\n const coreDoc = this.coreState.core.documents[documentId];\n const docState = this.getDocumentState(documentId);\n if (!coreDoc || !docState || coreDoc.status !== \"loaded\") return;\n const pages = this.getSpreadPagesWithRotatedSize(documentId);\n const layout = this.computeLayout(documentId, pages);\n const viewport = this.viewport.forDocument(documentId);\n const metrics = this.computeMetrics(documentId, viewport.getMetrics(), layout.virtualItems);\n this.dispatch(\n updateDocumentScrollState(documentId, {\n ...layout,\n ...metrics\n })\n );\n this.layoutChange$.emit({ documentId, layout });\n this.pushScrollerLayout(documentId);\n }\n getSpreadPagesWithRotatedSize(documentId) {\n var _a, _b;\n const id = documentId ?? this.getActiveDocumentId();\n const coreDoc = this.coreState.core.documents[id];\n if (!coreDoc) throw new Error(`Document ${id} not loaded`);\n const spreadPages = ((_a = this.spread) == null ? void 0 : _a.forDocument(id).getSpreadPages()) || ((_b = coreDoc.document) == null ? void 0 : _b.pages.map((page) => [page])) || [];\n return spreadPages.map(\n (spread) => spread.map((page) => {\n const effectiveRotation = ((page.rotation ?? 0) + coreDoc.rotation) % 4;\n return {\n ...page,\n rotatedSize: transformSize(page.size, effectiveRotation, 1)\n };\n })\n );\n }\n // ─────────────────────────────────────────────────────────\n // Core Operations\n // ─────────────────────────────────────────────────────────\n getCurrentPage(documentId) {\n return this.getDocumentStateOrThrow(documentId).currentPage;\n }\n getTotalPages(documentId) {\n return this.getDocumentStateOrThrow(documentId).totalPages;\n }\n getPageChangeState(documentId) {\n return this.getDocumentStateOrThrow(documentId).pageChangeState;\n }\n scrollToPage(options, documentId) {\n var _a;\n const id = documentId ?? this.getActiveDocumentId();\n const docState = this.getDocumentStateOrThrow(id);\n const strategy = this.getStrategy(id);\n const coreDoc = this.getCoreDocumentOrThrow(id);\n const { pageNumber, behavior = \"smooth\", pageCoordinates, alignX, alignY } = options;\n this.startPageChange(id, pageNumber, behavior);\n const pageObj = (_a = coreDoc.document) == null ? void 0 : _a.pages[pageNumber - 1];\n const effectiveRotation = (((pageObj == null ? void 0 : pageObj.rotation) ?? 0) + coreDoc.rotation) % 4;\n const position = strategy.getScrollPositionForPage(\n pageNumber,\n docState.virtualItems,\n coreDoc.scale,\n effectiveRotation,\n pageCoordinates\n );\n if (position) {\n const viewport = this.viewport.forDocument(id);\n viewport.scrollTo({ ...position, behavior, alignX, alignY });\n } else {\n this.completePageChange(id);\n }\n }\n scrollToNextPage(behavior = \"smooth\", documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const docState = this.getDocumentStateOrThrow(id);\n const strategy = this.getStrategy(id);\n const coreDoc = this.getCoreDocumentOrThrow(id);\n const currentItemIndex = docState.virtualItems.findIndex(\n (item) => item.pageNumbers.includes(docState.currentPage)\n );\n if (currentItemIndex >= 0 && currentItemIndex < docState.virtualItems.length - 1) {\n const nextItem = docState.virtualItems[currentItemIndex + 1];\n const targetPage = nextItem.pageNumbers[0];\n this.startPageChange(id, targetPage, behavior);\n const position = strategy.getScrollPositionForPage(\n targetPage,\n docState.virtualItems,\n coreDoc.scale,\n coreDoc.rotation\n );\n if (position) {\n const viewport = this.viewport.forDocument(id);\n viewport.scrollTo({ ...position, behavior });\n } else {\n this.completePageChange(id);\n }\n }\n }\n scrollToPreviousPage(behavior = \"smooth\", documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const docState = this.getDocumentStateOrThrow(id);\n const strategy = this.getStrategy(id);\n const coreDoc = this.coreState.core.documents[id];\n const currentItemIndex = docState.virtualItems.findIndex(\n (item) => item.pageNumbers.includes(docState.currentPage)\n );\n if (currentItemIndex > 0) {\n const prevItem = docState.virtualItems[currentItemIndex - 1];\n const targetPage = prevItem.pageNumbers[0];\n this.startPageChange(id, targetPage, behavior);\n const position = strategy.getScrollPositionForPage(\n targetPage,\n docState.virtualItems,\n coreDoc.scale,\n coreDoc.rotation\n );\n if (position) {\n const viewport = this.viewport.forDocument(id);\n viewport.scrollTo({ ...position, behavior });\n } else {\n this.completePageChange(id);\n }\n }\n }\n getMetrics(viewport, documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n if (viewport) {\n return this.computeMetrics(id, viewport);\n }\n const viewportScope = this.viewport.forDocument(id);\n return this.computeMetrics(id, viewportScope.getMetrics());\n }\n getLayout(documentId) {\n const docState = this.getDocumentStateOrThrow(documentId);\n return {\n virtualItems: docState.virtualItems,\n totalContentSize: docState.totalContentSize\n };\n }\n getRectPositionForPage(pageIndex, rect, scale, rotation, documentId) {\n var _a;\n const id = documentId ?? this.getActiveDocumentId();\n const docState = this.getDocumentStateOrThrow(id);\n const strategy = this.getStrategy(id);\n const coreDoc = this.getCoreDocumentOrThrow(id);\n let effectiveRotation = rotation;\n if (effectiveRotation === void 0) {\n const pageObj = (_a = coreDoc.document) == null ? void 0 : _a.pages[pageIndex];\n effectiveRotation = (((pageObj == null ? void 0 : pageObj.rotation) ?? 0) + coreDoc.rotation) % 4;\n }\n return strategy.getRectPositionForPage(\n pageIndex + 1,\n docState.virtualItems,\n scale ?? coreDoc.scale,\n effectiveRotation,\n rect\n );\n }\n setScrollStrategyForDocument(newStrategy, documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const docState = this.getDocumentState(id);\n if (!docState || docState.strategy === newStrategy) return;\n const strategy = this.createStrategy(newStrategy);\n this.strategies.set(id, strategy);\n this.dispatch(setScrollStrategy(id, newStrategy));\n this.refreshDocumentLayout(id);\n }\n // ─────────────────────────────────────────────────────────\n // Store Update Handlers\n // ─────────────────────────────────────────────────────────\n onStoreUpdated(prevState, newState) {\n for (const documentId in newState.documents) {\n const prevDoc = prevState.documents[documentId];\n const newDoc = newState.documents[documentId];\n if (prevDoc !== newDoc) {\n this.state$.emit(newDoc);\n if ((prevDoc == null ? void 0 : prevDoc.pageChangeState) !== newDoc.pageChangeState) {\n this.pageChangeState$.emit({\n documentId,\n state: newDoc.pageChangeState\n });\n }\n this.pushScrollerLayout(documentId);\n }\n }\n }\n // ─────────────────────────────────────────────────────────\n // Lifecycle\n // ─────────────────────────────────────────────────────────\n async initialize() {\n this.logger.info(\"ScrollPlugin\", \"Initialize\", \"Scroll plugin initialized\");\n }\n async destroy() {\n this.strategies.clear();\n this.layoutReady.clear();\n this.initialLayoutFired.clear();\n this.elevatedPages.clear();\n for (const emitter of this.scrollerLayoutEmitters.values()) {\n emitter.clear();\n }\n this.scrollerLayoutEmitters.clear();\n this.pageChange$.clear();\n this.scroll$.clear();\n this.layoutChange$.clear();\n this.pageChangeState$.clear();\n this.layoutReady$.clear();\n this.state$.clear();\n super.destroy();\n }\n};\n_ScrollPlugin.id = \"scroll\";\nlet ScrollPlugin = _ScrollPlugin;\nconst SCROLL_PLUGIN_ID = \"scroll\";\nconst manifest = {\n id: SCROLL_PLUGIN_ID,\n name: \"Scroll Plugin\",\n version: \"1.0.0\",\n provides: [\"scroll\"],\n requires: [\"viewport\"],\n optional: [\"spread\", \"interaction-manager\"],\n defaultConfig: {\n defaultPageGap: 10,\n defaultBufferSize: 4,\n defaultStrategy: ScrollStrategy.Vertical\n }\n};\nconst ScrollPluginPackage = {\n manifest,\n create: (registry, config) => new ScrollPlugin(SCROLL_PLUGIN_ID, registry, config),\n reducer: scrollReducer,\n initialState: (coreState, config) => initialState(coreState, config)\n};\nexport {\n SCROLL_PLUGIN_ID,\n ScrollPlugin,\n ScrollPluginPackage,\n ScrollStrategy,\n getScrollerLayout,\n manifest\n};\n//# sourceMappingURL=index.js.map\n","import { useState, useEffect, useLayoutEffect } from \"react\";\nimport { useCapability, usePlugin } from \"@embedpdf/core/react\";\nimport { ScrollPlugin, ScrollStrategy } from \"@embedpdf/plugin-scroll\";\nexport * from \"@embedpdf/plugin-scroll\";\nimport { jsxs, jsx } from \"react/jsx-runtime\";\nconst useScrollPlugin = () => usePlugin(ScrollPlugin.id);\nconst useScrollCapability = () => useCapability(ScrollPlugin.id);\nconst useScroll = (documentId) => {\n const { provides } = useScrollCapability();\n const [currentPage, setCurrentPage] = useState(1);\n const [totalPages, setTotalPages] = useState(1);\n useEffect(() => {\n if (!provides || !documentId) return;\n const scope = provides.forDocument(documentId);\n setCurrentPage(scope.getCurrentPage());\n setTotalPages(scope.getTotalPages());\n return provides.onPageChange((event) => {\n if (event.documentId === documentId) {\n setCurrentPage(event.pageNumber);\n setTotalPages(event.totalPages);\n }\n });\n }, [provides, documentId]);\n return {\n // New format (preferred)\n provides: (provides == null ? void 0 : provides.forDocument(documentId)) ?? null,\n state: {\n currentPage,\n totalPages\n }\n };\n};\nfunction Scroller({ documentId, renderPage, ...props }) {\n const { plugin: scrollPlugin } = useScrollPlugin();\n const [layoutData, setLayoutData] = useState({ layout: null, docId: null });\n useEffect(() => {\n if (!scrollPlugin || !documentId) return;\n const unsubscribe = scrollPlugin.onScrollerData(documentId, (newLayout) => {\n setLayoutData({ layout: newLayout, docId: documentId });\n });\n return () => {\n unsubscribe();\n setLayoutData({ layout: null, docId: null });\n scrollPlugin.clearLayoutReady(documentId);\n };\n }, [scrollPlugin, documentId]);\n const scrollerLayout = layoutData.docId === documentId ? layoutData.layout : null;\n useLayoutEffect(() => {\n if (!scrollPlugin || !documentId || !scrollerLayout) return;\n scrollPlugin.setLayoutReady(documentId);\n }, [scrollPlugin, documentId, scrollerLayout]);\n if (!scrollerLayout) return null;\n return /* @__PURE__ */ jsxs(\n \"div\",\n {\n ...props,\n style: {\n width: `${scrollerLayout.totalWidth}px`,\n height: `${scrollerLayout.totalHeight}px`,\n position: \"relative\",\n boxSizing: \"border-box\",\n margin: \"0 auto\",\n ...scrollerLayout.strategy === ScrollStrategy.Horizontal && {\n display: \"flex\",\n flexDirection: \"row\"\n }\n },\n children: [\n /* @__PURE__ */ jsx(\n \"div\",\n {\n style: {\n ...scrollerLayout.strategy === ScrollStrategy.Horizontal ? {\n width: scrollerLayout.startSpacing,\n height: \"100%\",\n flexShrink: 0\n } : {\n height: scrollerLayout.startSpacing,\n width: \"100%\"\n }\n }\n }\n ),\n /* @__PURE__ */ jsx(\n \"div\",\n {\n style: {\n gap: scrollerLayout.pageGap,\n display: \"flex\",\n alignItems: \"center\",\n position: \"relative\",\n boxSizing: \"border-box\",\n ...scrollerLayout.strategy === ScrollStrategy.Horizontal ? {\n flexDirection: \"row\",\n minHeight: \"100%\"\n } : {\n flexDirection: \"column\",\n minWidth: \"fit-content\"\n }\n },\n children: scrollerLayout.items.map((item) => /* @__PURE__ */ jsx(\n \"div\",\n {\n style: {\n display: \"flex\",\n justifyContent: \"center\",\n gap: scrollerLayout.pageGap\n },\n children: item.pageLayouts.map((layout) => /* @__PURE__ */ jsx(\n \"div\",\n {\n style: {\n width: `${layout.rotatedWidth}px`,\n height: `${layout.rotatedHeight}px`,\n position: \"relative\",\n zIndex: layout.elevated ? 1 : void 0\n },\n children: renderPage({\n ...layout\n })\n },\n layout.pageNumber\n ))\n },\n item.pageNumbers[0]\n ))\n }\n ),\n /* @__PURE__ */ jsx(\n \"div\",\n {\n style: {\n ...scrollerLayout.strategy === ScrollStrategy.Horizontal ? {\n width: scrollerLayout.endSpacing,\n height: \"100%\",\n flexShrink: 0\n } : {\n height: scrollerLayout.endSpacing,\n width: \"100%\"\n }\n }\n }\n )\n ]\n }\n );\n}\nexport {\n Scroller,\n useScroll,\n useScrollCapability,\n useScrollPlugin\n};\n//# sourceMappingURL=index.js.map\n","import { BasePlugin } from \"@embedpdf/core\";\nconst _RenderPlugin = class _RenderPlugin extends BasePlugin {\n constructor(id, registry, config) {\n super(id, registry);\n this.config = config;\n }\n // No onDocumentLoadingStarted or onDocumentClosed needed!\n buildCapability() {\n return {\n // Active document operations\n renderPage: (options) => this.renderPage(options),\n renderPageRect: (options) => this.renderPageRect(options),\n renderPageRaw: (options) => this.renderPageRaw(options),\n renderPageRectRaw: (options) => this.renderPageRectRaw(options),\n // Document-scoped operations\n forDocument: (documentId) => this.createRenderScope(documentId)\n };\n }\n // ─────────────────────────────────────────────────────────\n // Document Scoping\n // ─────────────────────────────────────────────────────────\n createRenderScope(documentId) {\n return {\n renderPage: (options) => this.renderPage(options, documentId),\n renderPageRect: (options) => this.renderPageRect(options, documentId),\n renderPageRaw: (options) => this.renderPageRaw(options, documentId),\n renderPageRectRaw: (options) => this.renderPageRectRaw(options, documentId)\n };\n }\n // ─────────────────────────────────────────────────────────\n // Core Operations\n // ─────────────────────────────────────────────────────────\n renderPage({ pageIndex, options }, documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const coreDoc = this.coreState.core.documents[id];\n if (!(coreDoc == null ? void 0 : coreDoc.document)) {\n throw new Error(`Document ${id} not loaded`);\n }\n const page = coreDoc.document.pages.find((p) => p.index === pageIndex);\n if (!page) {\n throw new Error(`Page ${pageIndex} not found in document ${id}`);\n }\n const mergedOptions = {\n ...options ?? {},\n withForms: (options == null ? void 0 : options.withForms) ?? this.config.withForms ?? false,\n withAnnotations: (options == null ? void 0 : options.withAnnotations) ?? this.config.withAnnotations ?? false,\n imageType: (options == null ? void 0 : options.imageType) ?? this.config.defaultImageType ?? \"image/png\",\n imageQuality: (options == null ? void 0 : options.imageQuality) ?? this.config.defaultImageQuality ?? 0.92\n };\n return this.engine.renderPage(coreDoc.document, page, mergedOptions);\n }\n renderPageRect({ pageIndex, rect, options }, documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const coreDoc = this.coreState.core.documents[id];\n if (!(coreDoc == null ? void 0 : coreDoc.document)) {\n throw new Error(`Document ${id} not loaded`);\n }\n const page = coreDoc.document.pages.find((p) => p.index === pageIndex);\n if (!page) {\n throw new Error(`Page ${pageIndex} not found in document ${id}`);\n }\n const mergedOptions = {\n ...options ?? {},\n withForms: (options == null ? void 0 : options.withForms) ?? this.config.withForms ?? false,\n withAnnotations: (options == null ? void 0 : options.withAnnotations) ?? this.config.withAnnotations ?? false,\n imageType: (options == null ? void 0 : options.imageType) ?? this.config.defaultImageType ?? \"image/png\",\n imageQuality: (options == null ? void 0 : options.imageQuality) ?? this.config.defaultImageQuality ?? 0.92\n };\n return this.engine.renderPageRect(coreDoc.document, page, rect, mergedOptions);\n }\n // ─────────────────────────────────────────────────────────\n // Raw Rendering (returns ImageDataLike, skips encoding)\n // ─────────────────────────────────────────────────────────\n renderPageRaw({ pageIndex, options }, documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const coreDoc = this.coreState.core.documents[id];\n if (!(coreDoc == null ? void 0 : coreDoc.document)) {\n throw new Error(`Document ${id} not loaded`);\n }\n const page = coreDoc.document.pages.find((p) => p.index === pageIndex);\n if (!page) {\n throw new Error(`Page ${pageIndex} not found in document ${id}`);\n }\n const mergedOptions = {\n ...options ?? {},\n withForms: (options == null ? void 0 : options.withForms) ?? this.config.withForms ?? false,\n withAnnotations: (options == null ? void 0 : options.withAnnotations) ?? this.config.withAnnotations ?? false\n };\n return this.engine.renderPageRaw(coreDoc.document, page, mergedOptions);\n }\n renderPageRectRaw({ pageIndex, rect, options }, documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const coreDoc = this.coreState.core.documents[id];\n if (!(coreDoc == null ? void 0 : coreDoc.document)) {\n throw new Error(`Document ${id} not loaded`);\n }\n const page = coreDoc.document.pages.find((p) => p.index === pageIndex);\n if (!page) {\n throw new Error(`Page ${pageIndex} not found in document ${id}`);\n }\n const mergedOptions = {\n ...options ?? {},\n withForms: (options == null ? void 0 : options.withForms) ?? this.config.withForms ?? false,\n withAnnotations: (options == null ? void 0 : options.withAnnotations) ?? this.config.withAnnotations ?? false\n };\n return this.engine.renderPageRectRaw(coreDoc.document, page, rect, mergedOptions);\n }\n // ─────────────────────────────────────────────────────────\n // Lifecycle\n // ─────────────────────────────────────────────────────────\n async initialize(_config) {\n this.logger.info(\"RenderPlugin\", \"Initialize\", \"Render plugin initialized\");\n }\n async destroy() {\n super.destroy();\n }\n};\n_RenderPlugin.id = \"render\";\nlet RenderPlugin = _RenderPlugin;\nconst RENDER_PLUGIN_ID = \"render\";\nconst manifest = {\n id: RENDER_PLUGIN_ID,\n name: \"Render Plugin\",\n version: \"1.0.0\",\n provides: [\"render\"],\n requires: [],\n optional: [],\n defaultConfig: {}\n};\nconst RenderPluginPackage = {\n manifest,\n create: (registry, config) => new RenderPlugin(RENDER_PLUGIN_ID, registry, config),\n reducer: () => {\n },\n initialState: {}\n};\nexport {\n RenderPlugin,\n RenderPluginPackage\n};\n//# sourceMappingURL=index.js.map\n","import { jsx } from \"react/jsx-runtime\";\nimport { useState, useRef, useMemo, useEffect, Fragment } from \"react\";\nimport { ignore, PdfErrorCode } from \"@embedpdf/models\";\nimport { useCapability, usePlugin, useDocumentState } from \"@embedpdf/core/react\";\nimport { RenderPlugin } from \"@embedpdf/plugin-render\";\nexport * from \"@embedpdf/plugin-render\";\nconst useRenderPlugin = () => usePlugin(RenderPlugin.id);\nconst useRenderCapability = () => useCapability(RenderPlugin.id);\nfunction RenderLayer({\n documentId,\n pageIndex,\n scale: scaleOverride,\n dpr: dprOverride,\n style,\n ...props\n}) {\n const { provides: renderProvides } = useRenderCapability();\n const documentState = useDocumentState(documentId);\n const [imageUrl, setImageUrl] = useState(null);\n const urlRef = useRef(null);\n const refreshVersion = useMemo(() => {\n if (!documentState) return 0;\n return documentState.pageRefreshVersions[pageIndex] || 0;\n }, [documentState, pageIndex]);\n const actualScale = useMemo(() => {\n if (scaleOverride !== void 0) return scaleOverride;\n return (documentState == null ? void 0 : documentState.scale) ?? 1;\n }, [scaleOverride, documentState == null ? void 0 : documentState.scale]);\n const actualDpr = useMemo(() => {\n if (dprOverride !== void 0) return dprOverride;\n return window.devicePixelRatio;\n }, [dprOverride]);\n useEffect(() => {\n if (!renderProvides) return;\n const task = renderProvides.forDocument(documentId).renderPage({\n pageIndex,\n options: {\n scaleFactor: actualScale,\n dpr: actualDpr\n }\n });\n task.wait((blob) => {\n const url = URL.createObjectURL(blob);\n setImageUrl(url);\n urlRef.current = url;\n }, ignore);\n return () => {\n if (urlRef.current) {\n URL.revokeObjectURL(urlRef.current);\n urlRef.current = null;\n } else {\n task.abort({\n code: PdfErrorCode.Cancelled,\n message: \"canceled render task\"\n });\n }\n };\n }, [documentId, pageIndex, actualScale, actualDpr, renderProvides, refreshVersion]);\n const handleImageLoad = () => {\n if (urlRef.current) {\n URL.revokeObjectURL(urlRef.current);\n urlRef.current = null;\n }\n };\n return /* @__PURE__ */ jsx(Fragment, { children: imageUrl && /* @__PURE__ */ jsx(\n \"img\",\n {\n src: imageUrl,\n onLoad: handleImageLoad,\n ...props,\n style: {\n width: \"100%\",\n height: \"100%\",\n ...style || {}\n }\n }\n ) });\n}\nexport {\n RenderLayer,\n useRenderCapability,\n useRenderPlugin\n};\n//# sourceMappingURL=index.js.map\n","import { clamp, BasePlugin, createEmitter, createBehaviorEmitter, setScale } from \"@embedpdf/core\";\nimport { rotateRect } from \"@embedpdf/models\";\nvar ZoomMode = /* @__PURE__ */ ((ZoomMode2) => {\n ZoomMode2[\"Automatic\"] = \"automatic\";\n ZoomMode2[\"FitPage\"] = \"fit-page\";\n ZoomMode2[\"FitWidth\"] = \"fit-width\";\n return ZoomMode2;\n})(ZoomMode || {});\nvar VerticalZoomFocus = /* @__PURE__ */ ((VerticalZoomFocus2) => {\n VerticalZoomFocus2[VerticalZoomFocus2[\"Center\"] = 0] = \"Center\";\n VerticalZoomFocus2[VerticalZoomFocus2[\"Top\"] = 1] = \"Top\";\n return VerticalZoomFocus2;\n})(VerticalZoomFocus || {});\nconst ZOOM_PLUGIN_ID = \"zoom\";\nconst manifest = {\n id: ZOOM_PLUGIN_ID,\n name: \"Zoom Plugin\",\n version: \"1.0.0\",\n provides: [\"zoom\"],\n requires: [\"viewport\", \"scroll\"],\n optional: [\"interaction-manager\", \"spread\"],\n defaultConfig: {\n defaultZoomLevel: ZoomMode.Automatic,\n minZoom: 0.2,\n maxZoom: 60,\n zoomStep: 0.1,\n zoomRanges: [\n {\n min: 0.2,\n max: 0.5,\n step: 0.05\n },\n {\n min: 0.5,\n max: 1,\n step: 0.1\n },\n {\n min: 1,\n max: 2,\n step: 0.2\n },\n {\n min: 2,\n max: 4,\n step: 0.4\n },\n {\n min: 4,\n max: 10,\n step: 0.8\n },\n {\n min: 10,\n max: 20,\n step: 1.6\n },\n {\n min: 20,\n max: 40,\n step: 3.2\n },\n {\n min: 40,\n max: 60,\n step: 6.4\n }\n ],\n presets: [\n {\n name: \"Fit Page\",\n value: ZoomMode.FitPage\n },\n {\n name: \"Fit Width\",\n value: ZoomMode.FitWidth\n },\n {\n name: \"Automatic\",\n value: ZoomMode.Automatic\n },\n {\n name: \"25%\",\n value: 0.25\n },\n {\n name: \"50%\",\n value: 0.5\n },\n {\n name: \"100%\",\n value: 1\n },\n {\n name: \"125%\",\n value: 1.25\n },\n {\n name: \"150%\",\n value: 1.5\n },\n {\n name: \"200%\",\n value: 2\n },\n {\n name: \"400%\",\n value: 4\n },\n {\n name: \"800%\",\n value: 8\n },\n {\n name: \"1600%\",\n value: 16\n }\n ]\n }\n};\nconst INIT_ZOOM_STATE = \"ZOOM/INIT_STATE\";\nconst CLEANUP_ZOOM_STATE = \"ZOOM/CLEANUP_STATE\";\nconst SET_ACTIVE_DOCUMENT = \"ZOOM/SET_ACTIVE_DOCUMENT\";\nconst SET_ZOOM_LEVEL = \"ZOOM/SET_ZOOM_LEVEL\";\nconst SET_MARQUEE_ZOOM_ACTIVE = \"ZOOM/SET_MARQUEE_ZOOM_ACTIVE\";\nfunction initZoomState(documentId, state) {\n return { type: INIT_ZOOM_STATE, payload: { documentId, state } };\n}\nfunction cleanupZoomState(documentId) {\n return { type: CLEANUP_ZOOM_STATE, payload: documentId };\n}\nfunction setZoomLevel(documentId, zoomLevel, currentZoomLevel) {\n return { type: SET_ZOOM_LEVEL, payload: { documentId, zoomLevel, currentZoomLevel } };\n}\nfunction setMarqueeZoomActive(documentId, isActive) {\n return { type: SET_MARQUEE_ZOOM_ACTIVE, payload: { documentId, isActive } };\n}\nconst initialDocumentState = {\n zoomLevel: ZoomMode.Automatic,\n currentZoomLevel: 1,\n isMarqueeZoomActive: false\n};\nconst initialState = {\n documents: {},\n activeDocumentId: null\n};\nconst zoomReducer = (state = initialState, action) => {\n switch (action.type) {\n case INIT_ZOOM_STATE: {\n const { documentId, state: docState } = action.payload;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: docState\n },\n // Set as active if no active document\n activeDocumentId: state.activeDocumentId ?? documentId\n };\n }\n case CLEANUP_ZOOM_STATE: {\n const documentId = action.payload;\n const { [documentId]: removed, ...remainingDocs } = state.documents;\n return {\n ...state,\n documents: remainingDocs,\n activeDocumentId: state.activeDocumentId === documentId ? null : state.activeDocumentId\n };\n }\n case SET_ACTIVE_DOCUMENT: {\n return {\n ...state,\n activeDocumentId: action.payload\n };\n }\n case SET_ZOOM_LEVEL: {\n const { documentId, zoomLevel, currentZoomLevel } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...docState,\n zoomLevel,\n currentZoomLevel\n }\n }\n };\n }\n case SET_MARQUEE_ZOOM_ACTIVE: {\n const { documentId, isActive } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...docState,\n isMarqueeZoomActive: isActive\n }\n }\n };\n }\n default:\n return state;\n }\n};\nfunction createMarqueeHandler(opts) {\n const { pageSize, scale, minDragPx = 5, onPreview, onCommit, onSmallDrag } = opts;\n let start = null;\n let last = null;\n return {\n onPointerDown: (pos, evt) => {\n var _a;\n start = pos;\n last = { origin: { x: pos.x, y: pos.y }, size: { width: 0, height: 0 } };\n onPreview == null ? void 0 : onPreview(last);\n (_a = evt.setPointerCapture) == null ? void 0 : _a.call(evt);\n },\n onPointerMove: (pos) => {\n if (!start) return;\n const x = clamp(pos.x, 0, pageSize.width);\n const y = clamp(pos.y, 0, pageSize.height);\n last = {\n origin: { x: Math.min(start.x, x), y: Math.min(start.y, y) },\n size: { width: Math.abs(x - start.x), height: Math.abs(y - start.y) }\n };\n onPreview == null ? void 0 : onPreview(last);\n },\n onPointerUp: (_pos, evt) => {\n var _a;\n if (last) {\n const dragPx = Math.max(last.size.width, last.size.height) * scale;\n if (dragPx > minDragPx) {\n onCommit == null ? void 0 : onCommit(last);\n } else {\n onSmallDrag == null ? void 0 : onSmallDrag();\n }\n }\n start = null;\n last = null;\n onPreview == null ? void 0 : onPreview(null);\n (_a = evt.releasePointerCapture) == null ? void 0 : _a.call(evt);\n },\n onPointerCancel: (_pos, evt) => {\n var _a;\n start = null;\n last = null;\n onPreview == null ? void 0 : onPreview(null);\n (_a = evt.releasePointerCapture) == null ? void 0 : _a.call(evt);\n }\n };\n}\nconst _ZoomPlugin = class _ZoomPlugin extends BasePlugin {\n constructor(id, registry, cfg) {\n var _a, _b, _c;\n super(id, registry);\n this.zoom$ = createEmitter();\n this.state$ = createBehaviorEmitter();\n this.viewportPlugin = registry.getPlugin(\"viewport\");\n this.viewport = this.viewportPlugin.provides();\n this.scroll = registry.getPlugin(\"scroll\").provides();\n const interactionManager = registry.getPlugin(\"interaction-manager\");\n this.interactionManager = (interactionManager == null ? void 0 : interactionManager.provides()) ?? null;\n const spread = registry.getPlugin(\"spread\");\n this.spread = (spread == null ? void 0 : spread.provides()) ?? null;\n this.minZoom = cfg.minZoom ?? 0.25;\n this.maxZoom = cfg.maxZoom ?? 10;\n this.zoomStep = cfg.zoomStep ?? 0.1;\n this.defaultZoomLevel = cfg.defaultZoomLevel;\n this.presets = cfg.presets ?? [];\n this.zoomRanges = this.normalizeRanges(cfg.zoomRanges ?? []);\n this.viewport.onViewportResize(\n (event) => this.recalcAuto(event.documentId, VerticalZoomFocus.Top),\n {\n mode: \"debounce\",\n wait: 150,\n keyExtractor: (event) => event.documentId\n }\n );\n (_a = this.spread) == null ? void 0 : _a.onSpreadChange((event) => {\n this.recalcAuto(event.documentId, VerticalZoomFocus.Top);\n });\n (_b = this.interactionManager) == null ? void 0 : _b.registerMode({\n id: \"marqueeZoom\",\n scope: \"page\",\n exclusive: true,\n cursor: \"zoom-in\"\n });\n (_c = this.interactionManager) == null ? void 0 : _c.onModeChange((state) => {\n const isMarqueeActive = state.activeMode === \"marqueeZoom\";\n const docState = this.getDocumentState(state.documentId);\n if (docState && docState.isMarqueeZoomActive !== isMarqueeActive) {\n this.dispatch(setMarqueeZoomActive(state.documentId, isMarqueeActive));\n }\n });\n }\n // ─────────────────────────────────────────────────────────\n // Document Lifecycle Hooks (from BasePlugin)\n // ─────────────────────────────────────────────────────────\n onDocumentLoadingStarted(documentId) {\n this.viewport.gate(\"zoom\", documentId);\n const docState = {\n ...initialDocumentState,\n zoomLevel: this.defaultZoomLevel\n };\n this.dispatch(initZoomState(documentId, docState));\n this.logger.debug(\n \"ZoomPlugin\",\n \"DocumentOpened\",\n `Initialized zoom state for document: ${documentId}`\n );\n }\n onDocumentLoaded(documentId) {\n this.recalcAuto(documentId, VerticalZoomFocus.Top);\n }\n onDocumentClosed(documentId) {\n this.dispatch(cleanupZoomState(documentId));\n this.logger.debug(\n \"ZoomPlugin\",\n \"DocumentClosed\",\n `Cleaned up zoom state for document: ${documentId}`\n );\n }\n onRotationChanged(documentId) {\n this.recalcAuto(documentId, VerticalZoomFocus.Top);\n }\n /*\n protected override onPagesChanged(documentId: string): void {\n // Recalculate auto modes when pages change\n this.recalcAuto(documentId, VerticalZoomFocus.Top);\n }*/\n // ─────────────────────────────────────────────────────────\n // Capability\n // ─────────────────────────────────────────────────────────\n buildCapability() {\n return {\n // Active document operations\n requestZoom: (level, c) => this.requestZoom(level, c),\n requestZoomBy: (d, c) => this.requestZoomBy(d, c),\n zoomIn: () => this.zoomIn(),\n zoomOut: () => this.zoomOut(),\n zoomToArea: (pageIndex, rect) => this.zoomToArea(pageIndex, rect),\n enableMarqueeZoom: () => this.enableMarqueeZoom(),\n disableMarqueeZoom: () => this.disableMarqueeZoom(),\n toggleMarqueeZoom: () => this.toggleMarqueeZoom(),\n isMarqueeZoomActive: () => this.isMarqueeZoomActive(),\n getState: () => this.getDocumentStateOrThrow(),\n // Document-scoped operations\n forDocument: (documentId) => this.createZoomScope(documentId),\n // Global\n registerMarqueeOnPage: (opts) => this.registerMarqueeOnPage(opts),\n getPresets: () => this.presets,\n // Events\n onZoomChange: this.zoom$.on,\n onStateChange: this.state$.on\n };\n }\n // ─────────────────────────────────────────────────────────\n // Document Scoping\n // ─────────────────────────────────────────────────────────\n createZoomScope(documentId) {\n return {\n requestZoom: (level, c) => this.requestZoom(level, c, documentId),\n requestZoomBy: (d, c) => this.requestZoomBy(d, c, documentId),\n zoomIn: () => this.zoomIn(documentId),\n zoomOut: () => this.zoomOut(documentId),\n zoomToArea: (pageIndex, rect) => this.zoomToArea(pageIndex, rect, documentId),\n enableMarqueeZoom: () => this.enableMarqueeZoom(documentId),\n disableMarqueeZoom: () => this.disableMarqueeZoom(documentId),\n toggleMarqueeZoom: () => this.toggleMarqueeZoom(documentId),\n isMarqueeZoomActive: () => this.isMarqueeZoomActive(documentId),\n getState: () => this.getDocumentStateOrThrow(documentId),\n onZoomChange: (listener) => this.zoom$.on((event) => {\n if (event.documentId === documentId) listener(event);\n }),\n onStateChange: (listener) => this.state$.on((event) => {\n if (event.documentId === documentId) listener(event.state);\n })\n };\n }\n // ─────────────────────────────────────────────────────────\n // State Helpers\n // ─────────────────────────────────────────────────────────\n getDocumentState(documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n return this.state.documents[id] ?? null;\n }\n getDocumentStateOrThrow(documentId) {\n const state = this.getDocumentState(documentId);\n if (!state) {\n throw new Error(`Zoom state not found for document: ${documentId ?? \"active\"}`);\n }\n return state;\n }\n // ─────────────────────────────────────────────────────────\n // Core Operations\n // ─────────────────────────────────────────────────────────\n requestZoom(level, center, documentId) {\n this.handleRequest({ level, center }, documentId);\n }\n requestZoomBy(delta, center, documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const docState = this.getDocumentStateOrThrow(id);\n const cur = docState.currentZoomLevel;\n const target = this.toZoom(cur + delta);\n this.handleRequest({ level: target, center }, id);\n }\n zoomIn(documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const docState = this.getDocumentStateOrThrow(id);\n const cur = docState.currentZoomLevel;\n this.handleRequest({ level: cur, delta: this.stepFor(cur) }, id);\n }\n zoomOut(documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const docState = this.getDocumentStateOrThrow(id);\n const cur = docState.currentZoomLevel;\n this.handleRequest({ level: cur, delta: -this.stepFor(cur) }, id);\n }\n zoomToArea(pageIndex, rect, documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n this.handleZoomToArea(id, pageIndex, rect);\n }\n enableMarqueeZoom(documentId) {\n var _a;\n const id = documentId ?? this.getActiveDocumentId();\n (_a = this.interactionManager) == null ? void 0 : _a.forDocument(id).activate(\"marqueeZoom\");\n }\n disableMarqueeZoom(documentId) {\n var _a;\n const id = documentId ?? this.getActiveDocumentId();\n (_a = this.interactionManager) == null ? void 0 : _a.forDocument(id).activateDefaultMode();\n }\n toggleMarqueeZoom(documentId) {\n var _a;\n const id = documentId ?? this.getActiveDocumentId();\n const scope = (_a = this.interactionManager) == null ? void 0 : _a.forDocument(id);\n if ((scope == null ? void 0 : scope.getActiveMode()) === \"marqueeZoom\") {\n scope.activateDefaultMode();\n } else {\n scope == null ? void 0 : scope.activate(\"marqueeZoom\");\n }\n }\n isMarqueeZoomActive(documentId) {\n var _a;\n const id = documentId ?? this.getActiveDocumentId();\n return ((_a = this.interactionManager) == null ? void 0 : _a.forDocument(id).getActiveMode()) === \"marqueeZoom\";\n }\n // ─────────────────────────────────────────────────────────\n // Main Zoom Logic\n // ─────────────────────────────────────────────────────────\n handleRequest({ level, delta = 0, center, focus = VerticalZoomFocus.Center, align = \"keep\" }, documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const docState = this.getDocumentStateOrThrow(id);\n const coreDoc = this.coreState.core.documents[id];\n if (!coreDoc) return;\n const viewport = this.viewport.forDocument(id);\n const metrics = viewport.getMetrics();\n const oldZoom = docState.currentZoomLevel;\n if (metrics.clientWidth === 0 || metrics.clientHeight === 0) {\n return;\n }\n const base = typeof level === \"number\" ? level : this.computeZoomForMode(id, level, metrics);\n if (base === false) return;\n const exactZoom = clamp(base + delta, this.minZoom, this.maxZoom);\n const newZoom = Math.floor(exactZoom * 1e3) / 1e3;\n const focusPoint = center ?? {\n vx: metrics.clientWidth / 2,\n vy: focus === VerticalZoomFocus.Top ? 0 : metrics.clientHeight / 2\n };\n const { desiredScrollLeft, desiredScrollTop } = this.computeScrollForZoomChange(\n id,\n metrics,\n oldZoom,\n newZoom,\n focusPoint,\n align\n );\n if (!isNaN(desiredScrollLeft) && !isNaN(desiredScrollTop)) {\n this.viewportPlugin.setViewportScrollMetrics(id, {\n scrollLeft: desiredScrollLeft,\n scrollTop: desiredScrollTop\n });\n }\n this.dispatch(setZoomLevel(id, typeof level === \"number\" ? newZoom : level, newZoom));\n this.dispatchCoreAction(setScale(newZoom, id));\n if (this.viewport.isGated(id)) {\n this.viewport.releaseGate(\"zoom\", id);\n }\n viewport.scrollTo({\n x: desiredScrollLeft,\n y: desiredScrollTop,\n behavior: \"instant\"\n });\n const evt = {\n documentId: id,\n oldZoom,\n newZoom,\n level,\n center: focusPoint,\n desiredScrollLeft,\n desiredScrollTop,\n viewport: metrics\n };\n this.zoom$.emit(evt);\n }\n computeZoomForMode(documentId, mode, vp) {\n const coreDoc = this.coreState.core.documents[documentId];\n if (!coreDoc) return false;\n const scrollScope = this.scroll.forDocument(documentId);\n const pgGap = scrollScope ? this.scroll.getPageGap() : 0;\n const vpGap = this.viewport.getViewportGap();\n const spreads = scrollScope.getSpreadPagesWithRotatedSize();\n if (!spreads.length) return false;\n if (vp.clientWidth === 0 || vp.clientHeight === 0) return false;\n const availableWidth = vp.clientWidth - 2 * vpGap;\n const availableHeight = vp.clientHeight - 2 * vpGap;\n if (availableWidth <= 0 || availableHeight <= 0) return false;\n let maxContentW = 0, maxContentH = 0;\n spreads.forEach((spread) => {\n const contentW = spread.reduce((s, p, i) => s + p.rotatedSize.width + (i ? pgGap : 0), 0);\n const contentH = Math.max(...spread.map((p) => p.rotatedSize.height));\n maxContentW = Math.max(maxContentW, contentW);\n maxContentH = Math.max(maxContentH, contentH);\n });\n switch (mode) {\n case ZoomMode.FitWidth:\n return availableWidth / maxContentW;\n case ZoomMode.FitPage:\n return Math.min(availableWidth / maxContentW, availableHeight / maxContentH);\n case ZoomMode.Automatic:\n return Math.min(availableWidth / maxContentW, 1);\n default:\n return 1;\n }\n }\n computeScrollForZoomChange(documentId, vp, oldZoom, newZoom, focus, align = \"keep\") {\n const scrollScope = this.scroll.forDocument(documentId);\n const layout = scrollScope.getLayout();\n const vpGap = this.viewport.getViewportGap();\n const contentW = layout.totalContentSize.width;\n const contentH = layout.totalContentSize.height;\n const availableWidth = vp.clientWidth - 2 * vpGap;\n const availableHeight = vp.clientHeight - 2 * vpGap;\n const off = (availableSpace, cw, zoom) => cw * zoom < availableSpace ? (availableSpace - cw * zoom) / 2 : 0;\n const offXold = off(availableWidth, contentW, oldZoom);\n const offYold = off(availableHeight, contentH, oldZoom);\n const offXnew = off(availableWidth, contentW, newZoom);\n const offYnew = off(availableHeight, contentH, newZoom);\n const cx = (vp.scrollLeft + focus.vx - vpGap - offXold) / oldZoom;\n const cy = (vp.scrollTop + focus.vy - vpGap - offYold) / oldZoom;\n const baseLeft = cx * newZoom + vpGap + offXnew;\n const baseTop = cy * newZoom + vpGap + offYnew;\n const desiredScrollLeft = align === \"center\" ? baseLeft - vp.clientWidth / 2 : baseLeft - focus.vx;\n const desiredScrollTop = align === \"center\" ? baseTop - vp.clientHeight / 2 : baseTop - focus.vy;\n return {\n desiredScrollLeft: Math.max(0, desiredScrollLeft),\n desiredScrollTop: Math.max(0, desiredScrollTop)\n };\n }\n handleZoomToArea(documentId, pageIndex, rect) {\n const coreDoc = this.coreState.core.documents[documentId];\n if (!coreDoc) return;\n const rotation = coreDoc.rotation;\n const viewport = this.viewport.forDocument(documentId);\n const vp = viewport.getMetrics();\n const vpGap = this.viewport.getViewportGap();\n const docState = this.getDocumentStateOrThrow(documentId);\n const oldZ = docState.currentZoomLevel;\n const availableW = vp.clientWidth - 2 * vpGap;\n const availableH = vp.clientHeight - 2 * vpGap;\n const scrollScope = this.scroll.forDocument(documentId);\n const layout = scrollScope.getLayout();\n const vItem = layout.virtualItems.find(\n (it) => it.pageLayouts.some((p) => p.pageIndex === pageIndex)\n );\n if (!vItem) return;\n const pageRel = vItem.pageLayouts.find((p) => p.pageIndex === pageIndex);\n const rotatedRect = rotateRect(\n { width: pageRel.width, height: pageRel.height },\n rect,\n rotation\n );\n const targetZoom = this.toZoom(\n Math.min(availableW / rotatedRect.size.width, availableH / rotatedRect.size.height)\n );\n const pageAbsX = vItem.x + pageRel.x;\n const pageAbsY = vItem.y + pageRel.y;\n const cxContent = pageAbsX + rotatedRect.origin.x + rotatedRect.size.width / 2;\n const cyContent = pageAbsY + rotatedRect.origin.y + rotatedRect.size.height / 2;\n const off = (avail, cw, z) => cw * z < avail ? (avail - cw * z) / 2 : 0;\n const offXold = off(availableW, layout.totalContentSize.width, oldZ);\n const offYold = off(availableH, layout.totalContentSize.height, oldZ);\n const centerVX = vpGap + offXold + cxContent * oldZ - vp.scrollLeft;\n const centerVY = vpGap + offYold + cyContent * oldZ - vp.scrollTop;\n this.handleRequest(\n {\n level: targetZoom,\n center: { vx: centerVX, vy: centerVY },\n align: \"center\"\n },\n documentId\n );\n }\n recalcAuto(documentId, focus) {\n const docState = this.getDocumentState(documentId);\n if (!docState) return;\n if (docState.zoomLevel === ZoomMode.Automatic || docState.zoomLevel === ZoomMode.FitPage || docState.zoomLevel === ZoomMode.FitWidth) {\n this.handleRequest({ level: docState.zoomLevel, focus }, documentId);\n }\n }\n // ─────────────────────────────────────────────────────────\n // Helpers\n // ─────────────────────────────────────────────────────────\n normalizeRanges(ranges) {\n return [...ranges].filter((r) => r.step > 0 && r.max > r.min).sort((a, b) => a.min - b.min);\n }\n stepFor(zoom) {\n const r = this.zoomRanges.find((r2) => zoom >= r2.min && zoom < r2.max);\n return r ? r.step : this.zoomStep;\n }\n toZoom(v) {\n return parseFloat(clamp(v, this.minZoom, this.maxZoom).toFixed(2));\n }\n // ─────────────────────────────────────────────────────────\n // Marquee Zoom\n // ─────────────────────────────────────────────────────────\n registerMarqueeOnPage(opts) {\n if (!this.interactionManager) {\n this.logger.warn(\n \"ZoomPlugin\",\n \"MissingDependency\",\n \"Interaction manager plugin not loaded, marquee zoom disabled\"\n );\n return () => {\n };\n }\n const coreDoc = this.coreState.core.documents[opts.documentId];\n if (!coreDoc || !coreDoc.document) {\n this.logger.warn(\"ZoomPlugin\", \"DocumentNotFound\", \"Document not found\");\n return () => {\n };\n }\n const page = coreDoc.document.pages[opts.pageIndex];\n if (!page) {\n this.logger.warn(\"ZoomPlugin\", \"PageNotFound\", `Page ${opts.pageIndex} not found`);\n return () => {\n };\n }\n const handlers = createMarqueeHandler({\n pageSize: page.size,\n scale: opts.scale,\n onPreview: opts.callback.onPreview,\n onCommit: (rect) => {\n var _a, _b;\n this.zoomToArea(opts.pageIndex, rect, opts.documentId);\n (_b = (_a = opts.callback).onCommit) == null ? void 0 : _b.call(_a, rect);\n },\n onSmallDrag: () => {\n var _a, _b;\n this.zoomIn(opts.documentId);\n (_b = (_a = opts.callback).onSmallDrag) == null ? void 0 : _b.call(_a);\n }\n });\n const off = this.interactionManager.registerHandlers({\n documentId: opts.documentId,\n modeId: \"marqueeZoom\",\n handlers,\n pageIndex: opts.pageIndex\n });\n return off;\n }\n // ─────────────────────────────────────────────────────────\n // Store Update Handlers\n // ─────────────────────────────────────────────────────────\n onStoreUpdated(prevState, newState) {\n for (const documentId in newState.documents) {\n const prevDoc = prevState.documents[documentId];\n const newDoc = newState.documents[documentId];\n if (prevDoc && newDoc && (prevDoc.currentZoomLevel !== newDoc.currentZoomLevel || prevDoc.zoomLevel !== newDoc.zoomLevel || prevDoc.isMarqueeZoomActive !== newDoc.isMarqueeZoomActive)) {\n this.state$.emit({\n documentId,\n state: newDoc\n });\n }\n }\n }\n // ─────────────────────────────────────────────────────────\n // Lifecycle\n // ─────────────────────────────────────────────────────────\n async initialize() {\n this.logger.info(\"ZoomPlugin\", \"Initialize\", \"Zoom plugin initialized\");\n }\n async destroy() {\n this.zoom$.clear();\n this.state$.clear();\n super.destroy();\n }\n};\n_ZoomPlugin.id = \"zoom\";\nlet ZoomPlugin = _ZoomPlugin;\nconst ZoomPluginPackage = {\n manifest,\n create: (registry, config) => new ZoomPlugin(ZOOM_PLUGIN_ID, registry, config),\n reducer: zoomReducer,\n initialState\n};\nexport {\n VerticalZoomFocus,\n ZOOM_PLUGIN_ID,\n ZoomMode,\n ZoomPlugin,\n ZoomPluginPackage,\n initialDocumentState,\n initialState,\n manifest\n};\n//# sourceMappingURL=index.js.map\n","import { useCapability, usePlugin, useDocumentState } from \"@embedpdf/core/react\";\nimport { initialDocumentState, ZoomPlugin } from \"@embedpdf/plugin-zoom\";\nexport * from \"@embedpdf/plugin-zoom\";\nimport { useState, useEffect, useRef, useLayoutEffect, useMemo } from \"react\";\nimport { useViewportElement } from \"@embedpdf/plugin-viewport/react\";\nimport { jsx } from \"react/jsx-runtime\";\nconst useZoomCapability = () => useCapability(ZoomPlugin.id);\nconst useZoomPlugin = () => usePlugin(ZoomPlugin.id);\nconst useZoom = (documentId) => {\n const { provides } = useZoomCapability();\n const [state, setState] = useState(initialDocumentState);\n useEffect(() => {\n if (!provides) return;\n const scope = provides.forDocument(documentId);\n setState(scope.getState());\n return scope.onStateChange((newState) => {\n setState(newState);\n });\n }, [provides, documentId]);\n return {\n state,\n provides: (provides == null ? void 0 : provides.forDocument(documentId)) ?? null\n };\n};\nfunction getTouchDistance(touches) {\n const [t1, t2] = [touches[0], touches[1]];\n const dx = t2.clientX - t1.clientX;\n const dy = t2.clientY - t1.clientY;\n return Math.hypot(dx, dy);\n}\nfunction getTouchCenter(touches) {\n const [t1, t2] = [touches[0], touches[1]];\n return {\n x: (t1.clientX + t2.clientX) / 2,\n y: (t1.clientY + t2.clientY) / 2\n };\n}\nfunction setupZoomGestures({\n element,\n container,\n documentId,\n zoomProvides,\n viewportGap = 0,\n options = {}\n}) {\n const { enablePinch = true, enableWheel = true } = options;\n if (typeof window === \"undefined\") {\n return () => {\n };\n }\n const zoomScope = zoomProvides.forDocument(documentId);\n const getState = () => zoomScope.getState();\n let initialZoom = 0;\n let currentScale = 1;\n let isPinching = false;\n let initialDistance = 0;\n let wheelZoomTimeout = null;\n let accumulatedWheelScale = 1;\n let initialElementWidth = 0;\n let initialElementHeight = 0;\n let initialElementLeft = 0;\n let initialElementTop = 0;\n let containerRectWidth = 0;\n let containerRectHeight = 0;\n let layoutWidth = 0;\n let layoutCenterX = 0;\n let pointerLocalY = 0;\n let pointerContainerX = 0;\n let pointerContainerY = 0;\n let currentGap = 0;\n let pivotLocalX = 0;\n const clamp = (val, min, max) => Math.min(Math.max(val, min), max);\n const updateMargin = () => {\n const availableWidth = container.clientWidth - 2 * viewportGap;\n const elementWidth = element.offsetWidth;\n const newMargin = elementWidth < availableWidth ? (availableWidth - elementWidth) / 2 : 0;\n element.style.marginLeft = `${newMargin}px`;\n };\n const calculateTransform = (scale) => {\n const finalWidth = initialElementWidth * scale;\n const finalHeight = initialElementHeight * scale;\n let ty = pointerLocalY * (1 - scale);\n const targetX = layoutCenterX - finalWidth / 2;\n const txCenter = targetX - initialElementLeft;\n const txMouse = pointerContainerX - pivotLocalX * scale - initialElementLeft;\n const overflow = Math.max(0, finalWidth - layoutWidth);\n const blendRange = layoutWidth * 0.3;\n const blend = Math.min(1, overflow / blendRange);\n let tx = txCenter + (txMouse - txCenter) * blend;\n const safeHeight = containerRectHeight - currentGap * 2;\n if (finalHeight > safeHeight) {\n const currentTop = initialElementTop + ty;\n const maxTop = currentGap;\n const minTop = containerRectHeight - currentGap - finalHeight;\n const constrainedTop = clamp(currentTop, minTop, maxTop);\n ty = constrainedTop - initialElementTop;\n }\n const safeWidth = containerRectWidth - currentGap * 2;\n if (finalWidth > safeWidth) {\n const currentLeft = initialElementLeft + tx;\n const maxLeft = currentGap;\n const minLeft = containerRectWidth - currentGap - finalWidth;\n const constrainedLeft = clamp(currentLeft, minLeft, maxLeft);\n tx = constrainedLeft - initialElementLeft;\n }\n return { tx, ty, blend, finalWidth };\n };\n const updateTransform = (scale) => {\n currentScale = scale;\n const { tx, ty } = calculateTransform(scale);\n element.style.transformOrigin = \"0 0\";\n element.style.transform = `translate(${tx}px, ${ty}px) scale(${scale})`;\n };\n const resetTransform = () => {\n element.style.transform = \"none\";\n element.style.transformOrigin = \"0 0\";\n currentScale = 1;\n };\n const commitZoom = () => {\n const { tx, finalWidth } = calculateTransform(currentScale);\n const delta = (currentScale - 1) * initialZoom;\n let anchorX;\n let anchorY = pointerContainerY;\n if (finalWidth <= layoutWidth) {\n anchorX = layoutCenterX;\n } else {\n const scaleDiff = 1 - currentScale;\n anchorX = Math.abs(scaleDiff) > 1e-3 ? initialElementLeft + tx / scaleDiff : pointerContainerX;\n }\n zoomScope.requestZoomBy(delta, { vx: anchorX, vy: anchorY });\n resetTransform();\n initialZoom = 0;\n };\n const initializeGestureState = (clientX, clientY) => {\n const containerRect = container.getBoundingClientRect();\n const innerRect = element.getBoundingClientRect();\n currentGap = viewportGap;\n initialElementWidth = innerRect.width;\n initialElementHeight = innerRect.height;\n initialElementLeft = innerRect.left - containerRect.left;\n initialElementTop = innerRect.top - containerRect.top;\n containerRectWidth = containerRect.width;\n containerRectHeight = containerRect.height;\n layoutWidth = container.clientWidth;\n layoutCenterX = container.clientLeft + layoutWidth / 2;\n const rawPointerLocalX = clientX - innerRect.left;\n pointerLocalY = clientY - innerRect.top;\n pointerContainerX = clientX - containerRect.left;\n pointerContainerY = clientY - containerRect.top;\n if (initialElementWidth < layoutWidth) {\n pivotLocalX = pointerContainerX * initialElementWidth / layoutWidth;\n } else {\n pivotLocalX = rawPointerLocalX;\n }\n };\n const handleTouchStart = (e) => {\n if (e.touches.length !== 2) return;\n isPinching = true;\n initialZoom = getState().currentZoomLevel;\n initialDistance = getTouchDistance(e.touches);\n const center = getTouchCenter(e.touches);\n initializeGestureState(center.x, center.y);\n e.preventDefault();\n };\n const handleTouchMove = (e) => {\n if (!isPinching || e.touches.length !== 2) return;\n const currentDistance = getTouchDistance(e.touches);\n const scale = currentDistance / initialDistance;\n updateTransform(scale);\n e.preventDefault();\n };\n const handleTouchEnd = (e) => {\n if (!isPinching) return;\n if (e.touches.length >= 2) return;\n isPinching = false;\n commitZoom();\n };\n const handleWheel = (e) => {\n if (!e.ctrlKey && !e.metaKey) return;\n e.preventDefault();\n if (wheelZoomTimeout === null) {\n initialZoom = getState().currentZoomLevel;\n accumulatedWheelScale = 1;\n initializeGestureState(e.clientX, e.clientY);\n } else {\n clearTimeout(wheelZoomTimeout);\n }\n const zoomFactor = 1 - e.deltaY * 0.01;\n accumulatedWheelScale *= zoomFactor;\n accumulatedWheelScale = Math.max(0.1, Math.min(10, accumulatedWheelScale));\n updateTransform(accumulatedWheelScale);\n wheelZoomTimeout = setTimeout(() => {\n wheelZoomTimeout = null;\n commitZoom();\n accumulatedWheelScale = 1;\n }, 150);\n };\n const unsubZoom = zoomScope.onStateChange(() => updateMargin());\n const resizeObserver = new ResizeObserver(() => updateMargin());\n resizeObserver.observe(element);\n resizeObserver.observe(container);\n updateMargin();\n if (enablePinch) {\n container.addEventListener(\"touchstart\", handleTouchStart, { passive: false });\n container.addEventListener(\"touchmove\", handleTouchMove, { passive: false });\n container.addEventListener(\"touchend\", handleTouchEnd);\n container.addEventListener(\"touchcancel\", handleTouchEnd);\n }\n if (enableWheel) {\n container.addEventListener(\"wheel\", handleWheel, { passive: false });\n }\n return () => {\n if (enablePinch) {\n container.removeEventListener(\"touchstart\", handleTouchStart);\n container.removeEventListener(\"touchmove\", handleTouchMove);\n container.removeEventListener(\"touchend\", handleTouchEnd);\n container.removeEventListener(\"touchcancel\", handleTouchEnd);\n }\n if (enableWheel) {\n container.removeEventListener(\"wheel\", handleWheel);\n }\n if (wheelZoomTimeout) {\n clearTimeout(wheelZoomTimeout);\n }\n unsubZoom();\n resizeObserver.disconnect();\n resetTransform();\n element.style.marginLeft = \"\";\n };\n}\nfunction useZoomGesture(documentId, options = {}) {\n const { provides: viewportProvides } = useCapability(\"viewport\");\n const { provides: zoomProvides } = useZoomCapability();\n const viewportElementRef = useViewportElement();\n const elementRef = useRef(null);\n useLayoutEffect(() => {\n const element = elementRef.current;\n const container = viewportElementRef == null ? void 0 : viewportElementRef.current;\n if (!element || !container || !zoomProvides) {\n return;\n }\n return setupZoomGestures({\n element,\n container,\n documentId,\n zoomProvides,\n viewportGap: (viewportProvides == null ? void 0 : viewportProvides.getViewportGap()) || 0,\n options\n });\n }, [\n viewportProvides,\n zoomProvides,\n documentId,\n viewportElementRef,\n options.enablePinch,\n options.enableWheel\n ]);\n return { elementRef };\n}\nfunction ZoomGestureWrapper({\n children,\n documentId,\n style,\n enablePinch = true,\n enableWheel = true,\n ...props\n}) {\n const options = useMemo(\n () => ({ enablePinch, enableWheel }),\n [enablePinch, enableWheel]\n );\n const { elementRef } = useZoomGesture(documentId, options);\n return /* @__PURE__ */ jsx(\n \"div\",\n {\n ref: elementRef,\n ...props,\n style: {\n ...style,\n display: \"inline-block\",\n overflow: \"visible\",\n boxSizing: \"border-box\"\n },\n children\n }\n );\n}\nconst MarqueeZoom = ({\n documentId,\n pageIndex,\n scale: scaleOverride,\n className,\n stroke = \"rgba(33,150,243,0.8)\",\n fill = \"rgba(33,150,243,0.15)\"\n}) => {\n const { provides: zoomPlugin } = useZoomCapability();\n const documentState = useDocumentState(documentId);\n const [rect, setRect] = useState(null);\n const actualScale = useMemo(() => {\n if (scaleOverride !== void 0) return scaleOverride;\n return (documentState == null ? void 0 : documentState.scale) ?? 1;\n }, [scaleOverride, documentState == null ? void 0 : documentState.scale]);\n useEffect(() => {\n if (!zoomPlugin) return;\n return zoomPlugin.registerMarqueeOnPage({\n documentId,\n pageIndex,\n scale: actualScale,\n callback: {\n onPreview: setRect\n }\n });\n }, [zoomPlugin, documentId, pageIndex, actualScale]);\n if (!rect) return null;\n return /* @__PURE__ */ jsx(\n \"div\",\n {\n style: {\n position: \"absolute\",\n pointerEvents: \"none\",\n left: rect.origin.x * actualScale,\n top: rect.origin.y * actualScale,\n width: rect.size.width * actualScale,\n height: rect.size.height * actualScale,\n border: `1px solid ${stroke}`,\n background: fill,\n boxSizing: \"border-box\"\n },\n className\n }\n );\n};\nexport {\n MarqueeZoom,\n ZoomGestureWrapper,\n useZoom,\n useZoomCapability,\n useZoomGesture,\n useZoomPlugin\n};\n//# sourceMappingURL=index.js.map\n","import { BasePlugin, createBehaviorEmitter } from \"@embedpdf/core\";\nimport { PdfErrorCode, PdfTaskHelper } from \"@embedpdf/models\";\nconst INIT_SEARCH_STATE = \"SEARCH/INIT_STATE\";\nconst CLEANUP_SEARCH_STATE = \"SEARCH/CLEANUP_STATE\";\nconst START_SEARCH_SESSION = \"SEARCH/START_SEARCH_SESSION\";\nconst STOP_SEARCH_SESSION = \"SEARCH/STOP_SEARCH_SESSION\";\nconst SET_SEARCH_FLAGS = \"SEARCH/SET_SEARCH_FLAGS\";\nconst SET_SHOW_ALL_RESULTS = \"SEARCH/SET_SHOW_ALL_RESULTS\";\nconst START_SEARCH = \"SEARCH/START_SEARCH\";\nconst SET_SEARCH_RESULTS = \"SEARCH/SET_SEARCH_RESULTS\";\nconst APPEND_SEARCH_RESULTS = \"SEARCH/APPEND_SEARCH_RESULTS\";\nconst SET_ACTIVE_RESULT_INDEX = \"SEARCH/SET_ACTIVE_RESULT_INDEX\";\nfunction initSearchState(documentId, state) {\n return { type: INIT_SEARCH_STATE, payload: { documentId, state } };\n}\nfunction cleanupSearchState(documentId) {\n return { type: CLEANUP_SEARCH_STATE, payload: documentId };\n}\nfunction startSearchSession(documentId) {\n return { type: START_SEARCH_SESSION, payload: { documentId } };\n}\nfunction stopSearchSession(documentId) {\n return { type: STOP_SEARCH_SESSION, payload: { documentId } };\n}\nfunction setSearchFlags(documentId, flags) {\n return { type: SET_SEARCH_FLAGS, payload: { documentId, flags } };\n}\nfunction setShowAllResults(documentId, showAll) {\n return { type: SET_SHOW_ALL_RESULTS, payload: { documentId, showAll } };\n}\nfunction startSearch(documentId, query) {\n return { type: START_SEARCH, payload: { documentId, query } };\n}\nfunction setSearchResults(documentId, results, total, activeResultIndex) {\n return { type: SET_SEARCH_RESULTS, payload: { documentId, results, total, activeResultIndex } };\n}\nfunction appendSearchResults(documentId, results) {\n return { type: APPEND_SEARCH_RESULTS, payload: { documentId, results } };\n}\nfunction setActiveResultIndex(documentId, index) {\n return { type: SET_ACTIVE_RESULT_INDEX, payload: { documentId, index } };\n}\nconst initialSearchDocumentState = {\n flags: [],\n results: [],\n total: 0,\n activeResultIndex: -1,\n showAllResults: true,\n query: \"\",\n loading: false,\n active: false\n};\nconst initialState = {\n documents: {}\n};\nconst updateDocState = (state, documentId, newDocState) => {\n const oldDocState = state.documents[documentId] || initialSearchDocumentState;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...oldDocState,\n ...newDocState\n }\n }\n };\n};\nconst searchReducer = (state = initialState, action) => {\n switch (action.type) {\n case INIT_SEARCH_STATE:\n return {\n ...state,\n documents: {\n ...state.documents,\n [action.payload.documentId]: action.payload.state\n }\n };\n case CLEANUP_SEARCH_STATE: {\n const documentId = action.payload;\n const { [documentId]: removed, ...remaining } = state.documents;\n return {\n ...state,\n documents: remaining\n };\n }\n case START_SEARCH_SESSION:\n return updateDocState(state, action.payload.documentId, { active: true });\n case STOP_SEARCH_SESSION:\n return updateDocState(state, action.payload.documentId, {\n results: [],\n total: 0,\n activeResultIndex: -1,\n query: \"\",\n loading: false,\n active: false\n });\n case SET_SEARCH_FLAGS:\n return updateDocState(state, action.payload.documentId, { flags: action.payload.flags });\n case SET_SHOW_ALL_RESULTS:\n return updateDocState(state, action.payload.documentId, {\n showAllResults: action.payload.showAll\n });\n case START_SEARCH:\n return updateDocState(state, action.payload.documentId, {\n loading: true,\n query: action.payload.query,\n // clear old results on new search start\n results: [],\n total: 0,\n activeResultIndex: -1\n });\n case APPEND_SEARCH_RESULTS: {\n const { documentId, results } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n const newResults = [...docState.results, ...results];\n const firstHitIndex = docState.activeResultIndex === -1 && newResults.length > 0 ? 0 : docState.activeResultIndex;\n return updateDocState(state, documentId, {\n results: newResults,\n total: newResults.length,\n // total-so-far\n activeResultIndex: firstHitIndex,\n // keep loading true until final SET_SEARCH_RESULTS\n loading: true\n });\n }\n case SET_SEARCH_RESULTS: {\n const { documentId, results, total, activeResultIndex } = action.payload;\n return updateDocState(state, documentId, {\n results,\n total,\n activeResultIndex,\n loading: false\n });\n }\n case SET_ACTIVE_RESULT_INDEX:\n return updateDocState(state, action.payload.documentId, {\n activeResultIndex: action.payload.index\n });\n default:\n return state;\n }\n};\nconst _SearchPlugin = class _SearchPlugin extends BasePlugin {\n constructor(id, registry, config) {\n super(id, registry);\n this.searchStop$ = createBehaviorEmitter();\n this.searchStart$ = createBehaviorEmitter();\n this.searchResult$ = createBehaviorEmitter();\n this.searchActiveResultChange$ = createBehaviorEmitter();\n this.searchResultState$ = createBehaviorEmitter();\n this.searchState$ = createBehaviorEmitter();\n this.currentTask = /* @__PURE__ */ new Map();\n this.pluginConfig = config;\n }\n onDocumentLoadingStarted(documentId) {\n const initialState2 = {\n ...initialSearchDocumentState,\n flags: this.pluginConfig.flags || [],\n showAllResults: this.pluginConfig.showAllResults ?? true\n };\n this.dispatch(initSearchState(documentId, initialState2));\n }\n onDocumentClosed(documentId) {\n this.stopSearchSession(documentId);\n this.dispatch(cleanupSearchState(documentId));\n this.currentTask.delete(documentId);\n }\n async initialize() {\n }\n onStoreUpdated(prevState, newState) {\n for (const documentId in newState.documents) {\n const prevDocState = prevState.documents[documentId];\n const newDocState = newState.documents[documentId];\n if (prevDocState !== newDocState) {\n this.searchState$.emit({ documentId, state: newDocState });\n if (!prevDocState || prevDocState.results !== newDocState.results || prevDocState.activeResultIndex !== newDocState.activeResultIndex || prevDocState.showAllResults !== newDocState.showAllResults || prevDocState.active !== newDocState.active) {\n this.searchResultState$.emit({\n documentId,\n state: {\n results: newDocState.results,\n activeResultIndex: newDocState.activeResultIndex,\n showAllResults: newDocState.showAllResults,\n active: newDocState.active\n }\n });\n }\n }\n }\n }\n buildCapability() {\n const getDocId = (documentId) => documentId ?? this.getActiveDocumentId();\n const getDocState = (docId) => {\n const id = getDocId(docId);\n const state = this.state.documents[id];\n if (!state) throw new Error(`Search state not found for document ${id}`);\n return state;\n };\n return {\n startSearch: (docId) => this.startSearchSession(getDocId(docId)),\n stopSearch: (docId) => this.stopSearchSession(getDocId(docId)),\n searchAllPages: (keyword, docId) => this.searchAllPages(keyword, getDocId(docId)),\n nextResult: (docId) => this.nextResult(getDocId(docId)),\n previousResult: (docId) => this.previousResult(getDocId(docId)),\n goToResult: (index, docId) => this.goToResult(index, getDocId(docId)),\n setShowAllResults: (showAll, docId) => this.dispatch(setShowAllResults(getDocId(docId), showAll)),\n getShowAllResults: (docId) => getDocState(docId).showAllResults,\n getFlags: (docId) => getDocState(docId).flags,\n setFlags: (flags, docId) => this.setFlags(flags, getDocId(docId)),\n getState: (docId) => getDocState(docId),\n forDocument: this.createSearchScope.bind(this),\n onSearchResult: this.searchResult$.on,\n onSearchStart: this.searchStart$.on,\n onSearchStop: this.searchStop$.on,\n onActiveResultChange: this.searchActiveResultChange$.on,\n onSearchResultStateChange: this.searchResultState$.on,\n onStateChange: this.searchState$.on\n };\n }\n createSearchScope(documentId) {\n const getDocState = () => {\n const state = this.state.documents[documentId];\n if (!state) throw new Error(`Search state not found for document ${documentId}`);\n return state;\n };\n return {\n startSearch: () => this.startSearchSession(documentId),\n stopSearch: () => this.stopSearchSession(documentId),\n searchAllPages: (keyword) => this.searchAllPages(keyword, documentId),\n nextResult: () => this.nextResult(documentId),\n previousResult: () => this.previousResult(documentId),\n goToResult: (index) => this.goToResult(index, documentId),\n setShowAllResults: (showAll) => this.dispatch(setShowAllResults(documentId, showAll)),\n getShowAllResults: () => getDocState().showAllResults,\n getFlags: () => getDocState().flags,\n setFlags: (flags) => this.setFlags(flags, documentId),\n getState: getDocState,\n onSearchResult: (listener) => this.searchResult$.on((event) => {\n if (event.documentId === documentId) listener(event.results);\n }),\n onSearchStart: (listener) => this.searchStart$.on((event) => {\n if (event.documentId === documentId) listener();\n }),\n onSearchStop: (listener) => this.searchStop$.on((event) => {\n if (event.documentId === documentId) listener();\n }),\n onActiveResultChange: (listener) => this.searchActiveResultChange$.on((event) => {\n if (event.documentId === documentId) listener(event.index);\n }),\n onSearchResultStateChange: (listener) => this.searchResultState$.on((event) => {\n if (event.documentId === documentId) listener(event.state);\n }),\n onStateChange: (listener) => this.searchState$.on((event) => {\n if (event.documentId === documentId) listener(event.state);\n })\n };\n }\n setFlags(flags, documentId) {\n this.dispatch(setSearchFlags(documentId, flags));\n const docState = this.state.documents[documentId];\n if (docState == null ? void 0 : docState.active) {\n this.searchAllPages(docState.query, documentId, true);\n }\n }\n notifySearchStart(documentId) {\n this.searchStart$.emit({ documentId });\n }\n notifySearchStop(documentId) {\n this.searchStop$.emit({ documentId });\n }\n notifyActiveResultChange(documentId, index) {\n this.searchActiveResultChange$.emit({ documentId, index });\n }\n startSearchSession(documentId) {\n const coreDoc = this.getCoreDocument(documentId);\n if (!coreDoc) return;\n this.dispatch(startSearchSession(documentId));\n this.notifySearchStart(documentId);\n }\n stopSearchSession(documentId) {\n var _a;\n const docState = this.state.documents[documentId];\n if (!(docState == null ? void 0 : docState.active)) return;\n const task = this.currentTask.get(documentId);\n if (task) {\n try {\n (_a = task.abort) == null ? void 0 : _a.call(task, { code: PdfErrorCode.Cancelled, message: \"search stopped\" });\n } catch {\n }\n this.currentTask.delete(documentId);\n }\n this.dispatch(stopSearchSession(documentId));\n this.notifySearchStop(documentId);\n }\n searchAllPages(keyword, documentId, force = false) {\n var _a;\n const docState = this.state.documents[documentId];\n if (!docState) {\n return PdfTaskHelper.reject({\n code: PdfErrorCode.NotFound,\n message: \"Search state not initialized\"\n });\n }\n const coreDoc = this.getCoreDocument(documentId);\n if (!(coreDoc == null ? void 0 : coreDoc.document)) {\n return PdfTaskHelper.reject({ code: PdfErrorCode.NotFound, message: \"Document not loaded\" });\n }\n const trimmedKeyword = keyword.trim();\n if (docState.query === trimmedKeyword && !force) {\n return PdfTaskHelper.resolve({\n results: docState.results,\n total: docState.total\n });\n }\n const oldTask = this.currentTask.get(documentId);\n if (oldTask) {\n try {\n (_a = oldTask.abort) == null ? void 0 : _a.call(oldTask, { code: PdfErrorCode.Cancelled, message: \"new search\" });\n } catch {\n }\n this.currentTask.delete(documentId);\n }\n this.dispatch(startSearch(documentId, trimmedKeyword));\n if (!trimmedKeyword) {\n this.dispatch(setSearchResults(documentId, [], 0, -1));\n return PdfTaskHelper.resolve({\n results: [],\n total: 0\n });\n }\n if (!docState.active) {\n this.startSearchSession(documentId);\n }\n const task = this.engine.searchAllPages(coreDoc.document, trimmedKeyword, {\n flags: docState.flags\n });\n this.currentTask.set(documentId, task);\n task.onProgress((p) => {\n var _a2;\n if ((_a2 = p == null ? void 0 : p.results) == null ? void 0 : _a2.length) {\n if (this.currentTask.get(documentId) === task) {\n this.dispatch(appendSearchResults(documentId, p.results));\n if (this.state.documents[documentId].activeResultIndex === -1) {\n this.dispatch(setActiveResultIndex(documentId, 0));\n this.notifyActiveResultChange(documentId, 0);\n }\n }\n }\n });\n task.wait(\n (results) => {\n this.currentTask.delete(documentId);\n const activeResultIndex = results.total > 0 ? 0 : -1;\n this.dispatch(\n setSearchResults(documentId, results.results, results.total, activeResultIndex)\n );\n this.searchResult$.emit({ documentId, results });\n if (results.total > 0) {\n this.notifyActiveResultChange(documentId, 0);\n }\n },\n (error) => {\n var _a2;\n if (((_a2 = error == null ? void 0 : error.reason) == null ? void 0 : _a2.code) !== PdfErrorCode.Cancelled) {\n console.error(\"Error during search:\", error);\n this.dispatch(setSearchResults(documentId, [], 0, -1));\n }\n this.currentTask.delete(documentId);\n }\n );\n return task;\n }\n nextResult(documentId) {\n const docState = this.state.documents[documentId];\n if (!docState || docState.results.length === 0) return -1;\n const nextIndex = docState.activeResultIndex >= docState.results.length - 1 ? 0 : docState.activeResultIndex + 1;\n return this.goToResult(nextIndex, documentId);\n }\n previousResult(documentId) {\n const docState = this.state.documents[documentId];\n if (!docState || docState.results.length === 0) return -1;\n const prevIndex = docState.activeResultIndex <= 0 ? docState.results.length - 1 : docState.activeResultIndex - 1;\n return this.goToResult(prevIndex, documentId);\n }\n goToResult(index, documentId) {\n const docState = this.state.documents[documentId];\n if (!docState || docState.results.length === 0 || index < 0 || index >= docState.results.length) {\n return -1;\n }\n this.dispatch(setActiveResultIndex(documentId, index));\n this.notifyActiveResultChange(documentId, index);\n return index;\n }\n async destroy() {\n for (const documentId of Object.keys(this.state.documents)) {\n this.stopSearchSession(documentId);\n }\n this.searchResult$.clear();\n this.searchStart$.clear();\n this.searchStop$.clear();\n this.searchActiveResultChange$.clear();\n this.searchResultState$.clear();\n this.searchState$.clear();\n super.destroy();\n }\n};\n_SearchPlugin.id = \"search\";\nlet SearchPlugin = _SearchPlugin;\nconst SEARCH_PLUGIN_ID = \"search\";\nconst manifest = {\n id: SEARCH_PLUGIN_ID,\n name: \"Search Plugin\",\n version: \"1.0.0\",\n provides: [\"search\"],\n requires: [],\n optional: [],\n defaultConfig: {\n flags: []\n }\n};\nconst SearchPluginPackage = {\n manifest,\n create: (registry, config) => new SearchPlugin(SEARCH_PLUGIN_ID, registry, config),\n reducer: searchReducer,\n initialState\n};\nexport {\n SEARCH_PLUGIN_ID,\n SearchPlugin,\n SearchPluginPackage,\n initialSearchDocumentState,\n initialState,\n manifest\n};\n//# sourceMappingURL=index.js.map\n","import { useCapability, usePlugin, useDocumentState } from \"@embedpdf/core/react\";\nimport { initialSearchDocumentState, SearchPlugin } from \"@embedpdf/plugin-search\";\nexport * from \"@embedpdf/plugin-search\";\nimport { useState, useMemo, useEffect } from \"react\";\nimport { jsx } from \"react/jsx-runtime\";\nconst useSearchPlugin = () => usePlugin(SearchPlugin.id);\nconst useSearchCapability = () => useCapability(SearchPlugin.id);\nconst useSearch = (documentId) => {\n const { provides } = useSearchCapability();\n const [searchState, setSearchState] = useState(initialSearchDocumentState);\n const scope = useMemo(() => provides == null ? void 0 : provides.forDocument(documentId), [provides, documentId]);\n useEffect(() => {\n if (!scope) {\n setSearchState(initialSearchDocumentState);\n return;\n }\n setSearchState(scope.getState());\n return scope.onStateChange((state) => setSearchState(state));\n }, [scope]);\n return {\n state: searchState,\n provides: scope ?? null\n };\n};\nfunction SearchLayer({\n documentId,\n pageIndex,\n scale: scaleOverride,\n style,\n highlightColor = \"#FFFF00\",\n activeHighlightColor = \"#FFBF00\",\n ...props\n}) {\n const { provides: searchProvides } = useSearchCapability();\n const [searchResultState, setSearchResultState] = useState(null);\n const documentState = useDocumentState(documentId);\n const scope = useMemo(\n () => searchProvides == null ? void 0 : searchProvides.forDocument(documentId),\n [searchProvides, documentId]\n );\n const actualScale = useMemo(() => {\n if (scaleOverride !== void 0) return scaleOverride;\n return (documentState == null ? void 0 : documentState.scale) ?? 1;\n }, [scaleOverride, documentState == null ? void 0 : documentState.scale]);\n useEffect(() => {\n if (!scope) {\n setSearchResultState(null);\n return;\n }\n const currentState = scope.getState();\n setSearchResultState({\n results: currentState.results,\n activeResultIndex: currentState.activeResultIndex,\n showAllResults: currentState.showAllResults,\n active: currentState.active\n });\n return scope.onSearchResultStateChange((state) => {\n setSearchResultState(state);\n });\n }, [scope]);\n if (!searchResultState || !searchResultState.active) {\n return null;\n }\n const pageResults = searchResultState.results.map((result, originalIndex) => ({ result, originalIndex })).filter(({ result }) => result.pageIndex === pageIndex);\n const resultsToShow = pageResults.filter(\n ({ originalIndex }) => searchResultState.showAllResults || originalIndex === searchResultState.activeResultIndex\n );\n return /* @__PURE__ */ jsx(\n \"div\",\n {\n style: {\n ...style,\n pointerEvents: \"none\"\n },\n ...props,\n children: resultsToShow.map(\n ({ result, originalIndex }) => result.rects.map((rect, rectIndex) => /* @__PURE__ */ jsx(\n \"div\",\n {\n style: {\n position: \"absolute\",\n top: rect.origin.y * actualScale,\n left: rect.origin.x * actualScale,\n width: rect.size.width * actualScale,\n height: rect.size.height * actualScale,\n backgroundColor: originalIndex === searchResultState.activeResultIndex ? activeHighlightColor : highlightColor,\n mixBlendMode: \"multiply\",\n transform: \"scale(1.02)\",\n transformOrigin: \"center\",\n transition: \"opacity .3s ease-in-out\",\n opacity: 1\n }\n },\n `${originalIndex}-${rectIndex}`\n ))\n )\n }\n );\n}\nexport {\n SearchLayer,\n useSearch,\n useSearchCapability,\n useSearchPlugin\n};\n//# sourceMappingURL=index.js.map\n","import { clamp, BasePlugin, createScopedEmitter, REFRESH_PAGES } from \"@embedpdf/core\";\nimport { boundingRect, Task, ignore, PdfErrorCode, PdfTaskHelper, PdfPermissionFlag } from \"@embedpdf/models\";\nconst SELECTION_PLUGIN_ID = \"selection\";\nconst manifest = {\n id: SELECTION_PLUGIN_ID,\n name: \"Selection Plugin\",\n version: \"1.0.0\",\n provides: [\"selection\"],\n requires: [\"interaction-manager\"],\n optional: [\"viewport\", \"scroll\"],\n defaultConfig: {\n menuHeight: 40\n }\n};\nconst INIT_SELECTION_STATE = \"SELECTION/INIT_STATE\";\nconst CLEANUP_SELECTION_STATE = \"SELECTION/CLEANUP_STATE\";\nconst CACHE_PAGE_GEOMETRY = \"SELECTION/CACHE_PAGE_GEOMETRY\";\nconst SET_SELECTION = \"SELECTION/SET_SELECTION\";\nconst START_SELECTION = \"SELECTION/START_SELECTION\";\nconst END_SELECTION = \"SELECTION/END_SELECTION\";\nconst CLEAR_SELECTION = \"SELECTION/CLEAR_SELECTION\";\nconst SET_RECTS = \"SELECTION/SET_RECTS\";\nconst SET_SLICES = \"SELECTION/SET_SLICES\";\nconst EVICT_PAGE_GEOMETRY = \"SELECTION/EVICT_PAGE_GEOMETRY\";\nconst RESET = \"SELECTION/RESET\";\nconst initSelectionState = (documentId, state) => ({\n type: INIT_SELECTION_STATE,\n payload: { documentId, state }\n});\nconst cleanupSelectionState = (documentId) => ({\n type: CLEANUP_SELECTION_STATE,\n payload: documentId\n});\nconst cachePageGeometry = (documentId, page, geo) => ({\n type: CACHE_PAGE_GEOMETRY,\n payload: { documentId, page, geo }\n});\nconst setSelection = (documentId, sel) => ({\n type: SET_SELECTION,\n payload: { documentId, selection: sel }\n});\nconst startSelection = (documentId) => ({\n type: START_SELECTION,\n payload: { documentId }\n});\nconst endSelection = (documentId) => ({\n type: END_SELECTION,\n payload: { documentId }\n});\nconst clearSelection = (documentId) => ({\n type: CLEAR_SELECTION,\n payload: { documentId }\n});\nconst setRects = (documentId, allRects) => ({\n type: SET_RECTS,\n payload: { documentId, rects: allRects }\n});\nconst setSlices = (documentId, slices) => ({ type: SET_SLICES, payload: { documentId, slices } });\nconst evictPageGeometry = (documentId, pages) => ({\n type: EVICT_PAGE_GEOMETRY,\n payload: { documentId, pages }\n});\nconst initialSelectionDocumentState = {\n geometry: {},\n rects: {},\n slices: {},\n selection: null,\n active: false,\n selecting: false\n};\nconst initialState = {\n documents: {}\n};\nconst updateDocState = (state, documentId, newDocState) => ({\n ...state,\n documents: {\n ...state.documents,\n [documentId]: newDocState\n }\n});\nconst selectionReducer = (state = initialState, action) => {\n switch (action.type) {\n case INIT_SELECTION_STATE: {\n const { documentId, state: docState } = action.payload;\n return updateDocState(state, documentId, docState);\n }\n case CLEANUP_SELECTION_STATE: {\n const documentId = action.payload;\n const { [documentId]: removed, ...remaining } = state.documents;\n return {\n ...state,\n documents: remaining\n };\n }\n case CACHE_PAGE_GEOMETRY: {\n const { documentId, page, geo } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return updateDocState(state, documentId, {\n ...docState,\n geometry: { ...docState.geometry, [page]: geo }\n });\n }\n case SET_SELECTION: {\n const { documentId, selection } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return updateDocState(state, documentId, {\n ...docState,\n selection,\n active: true\n });\n }\n case START_SELECTION: {\n const { documentId } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return updateDocState(state, documentId, {\n ...docState,\n selecting: true,\n selection: null,\n rects: {}\n });\n }\n case END_SELECTION: {\n const { documentId } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return updateDocState(state, documentId, { ...docState, selecting: false });\n }\n case CLEAR_SELECTION: {\n const { documentId } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return updateDocState(state, documentId, {\n ...docState,\n selecting: false,\n selection: null,\n rects: {},\n active: false\n });\n }\n case SET_RECTS: {\n const { documentId, rects } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return updateDocState(state, documentId, { ...docState, rects });\n }\n case SET_SLICES: {\n const { documentId, slices } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return updateDocState(state, documentId, { ...docState, slices });\n }\n case EVICT_PAGE_GEOMETRY: {\n const { documentId, pages } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n const geometry = { ...docState.geometry };\n const rects = { ...docState.rects };\n const slices = { ...docState.slices };\n for (const p of pages) {\n delete geometry[p];\n delete rects[p];\n delete slices[p];\n }\n return updateDocState(state, documentId, { ...docState, geometry, rects, slices });\n }\n case RESET: {\n const { documentId } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return updateDocState(state, documentId, initialSelectionDocumentState);\n }\n default:\n return state;\n }\n};\nfunction selectRectsForPage(state, page) {\n return state.rects[page] ?? [];\n}\nfunction selectBoundingRectForPage(state, page) {\n return boundingRect(selectRectsForPage(state, page));\n}\nfunction selectBoundingRectsForAllPages(state) {\n const out = [];\n const rectMap = state.rects;\n for (const key in rectMap) {\n const page = Number(key);\n const bRect = boundingRect(rectMap[page]);\n if (bRect) out.push({ page, rect: bRect });\n }\n return out;\n}\nfunction getFormattedSelectionForPage(state, page) {\n const segmentRects = state.rects[page] || [];\n if (segmentRects.length === 0) return null;\n const boundingRect2 = selectBoundingRectForPage(state, page);\n if (!boundingRect2) return null;\n return { pageIndex: page, rect: boundingRect2, segmentRects };\n}\nfunction getFormattedSelection(state) {\n const result = [];\n const pages = Object.keys(state.rects).map(Number);\n for (const pageIndex of pages) {\n const segmentRects = state.rects[pageIndex] || [];\n if (segmentRects.length === 0) continue;\n const boundingRect2 = selectBoundingRectForPage(state, pageIndex);\n if (boundingRect2) {\n result.push({\n pageIndex,\n rect: boundingRect2,\n segmentRects\n });\n }\n }\n return result;\n}\nfunction glyphAt(geo, pt, toleranceFactor = 1.5) {\n for (const run of geo.runs) {\n const inRun = pt.y >= run.rect.y && pt.y <= run.rect.y + run.rect.height && pt.x >= run.rect.x && pt.x <= run.rect.x + run.rect.width;\n if (!inRun) continue;\n const rel = run.glyphs.findIndex((g) => {\n const gx = g.tightX ?? g.x;\n const gy = g.tightY ?? g.y;\n const gw = g.tightWidth ?? g.width;\n const gh = g.tightHeight ?? g.height;\n return pt.x >= gx && pt.x <= gx + gw && pt.y >= gy && pt.y <= gy + gh;\n });\n if (rel !== -1) {\n return run.charStart + rel;\n }\n }\n if (toleranceFactor <= 0) return -1;\n const tolerance = computeTolerance(geo, toleranceFactor);\n const halfTol = tolerance / 2;\n let bestIndex = -1;\n let bestDist = Infinity;\n for (const run of geo.runs) {\n if (pt.y < run.rect.y - halfTol || pt.y > run.rect.y + run.rect.height + halfTol || pt.x < run.rect.x - halfTol || pt.x > run.rect.x + run.rect.width + halfTol) {\n continue;\n }\n for (let i = 0; i < run.glyphs.length; i++) {\n const g = run.glyphs[i];\n if (g.flags === 2) continue;\n const gx = g.tightX ?? g.x;\n const gy = g.tightY ?? g.y;\n const gw = g.tightWidth ?? g.width;\n const gh = g.tightHeight ?? g.height;\n const expandedLeft = gx - halfTol;\n const expandedRight = gx + gw + halfTol;\n const expandedTop = gy - halfTol;\n const expandedBottom = gy + gh + halfTol;\n if (pt.x < expandedLeft || pt.x > expandedRight || pt.y < expandedTop || pt.y > expandedBottom) {\n continue;\n }\n const curXdif = Math.min(Math.abs(pt.x - gx), Math.abs(pt.x - (gx + gw)));\n const curYdif = Math.min(Math.abs(pt.y - gy), Math.abs(pt.y - (gy + gh)));\n const dist = curXdif + curYdif;\n if (dist < bestDist) {\n bestDist = dist;\n bestIndex = run.charStart + i;\n }\n }\n }\n return bestIndex;\n}\nfunction computeTolerance(geo, factor) {\n let totalHeight = 0;\n let count = 0;\n for (const run of geo.runs) {\n for (const g of run.glyphs) {\n if (g.flags === 2) continue;\n totalHeight += g.height;\n count++;\n }\n }\n if (count === 0) return 0;\n return totalHeight / count * factor;\n}\nfunction sliceBounds(sel, geo, page) {\n if (!sel || !geo) return null;\n if (page < sel.start.page || page > sel.end.page) return null;\n const from = page === sel.start.page ? sel.start.index : 0;\n const lastRun = geo.runs[geo.runs.length - 1];\n const lastCharOnPage = lastRun.charStart + lastRun.glyphs.length - 1;\n const to = page === sel.end.page ? sel.end.index : lastCharOnPage;\n return { from, to };\n}\nfunction rectsWithinSlice(geo, from, to, merge = true) {\n const textRuns = [];\n const CHAR_DISTANCE_FACTOR = 2.5;\n for (const run of geo.runs) {\n const runStart = run.charStart;\n const runEnd = runStart + run.glyphs.length - 1;\n if (runEnd < from || runStart > to) continue;\n const sIdx = Math.max(from, runStart) - runStart;\n const eIdx = Math.min(to, runEnd) - runStart;\n let minX = Infinity, maxX = -Infinity;\n let minY = Infinity, maxY = -Infinity;\n let charCount = 0;\n let widthSum = 0;\n let prevRight = -Infinity;\n const flushSubRun = () => {\n if (minX !== Infinity && charCount > 0) {\n textRuns.push({\n rect: {\n origin: { x: minX, y: minY },\n size: { width: maxX - minX, height: maxY - minY }\n },\n charCount,\n fontSize: run.fontSize\n });\n }\n minX = Infinity;\n maxX = -Infinity;\n minY = Infinity;\n maxY = -Infinity;\n charCount = 0;\n widthSum = 0;\n prevRight = -Infinity;\n };\n for (let i = sIdx; i <= eIdx; i++) {\n const g = run.glyphs[i];\n if (g.flags === 2) continue;\n if (charCount > 0 && prevRight > -Infinity) {\n const gap = Math.abs(g.x - prevRight);\n const avgWidth = widthSum / charCount;\n if (avgWidth > 0 && gap > CHAR_DISTANCE_FACTOR * avgWidth) {\n flushSubRun();\n }\n }\n minX = Math.min(minX, g.x);\n maxX = Math.max(maxX, g.x + g.width);\n minY = Math.min(minY, g.y);\n maxY = Math.max(maxY, g.y + g.height);\n charCount++;\n widthSum += g.width;\n prevRight = g.x + g.width;\n }\n flushSubRun();\n }\n if (!merge) {\n return textRuns.map((run) => run.rect);\n }\n return mergeAdjacentRects(textRuns);\n}\nfunction rectUnion(rect1, rect2) {\n const left = Math.min(rect1.origin.x, rect2.origin.x);\n const top = Math.min(rect1.origin.y, rect2.origin.y);\n const right = Math.max(rect1.origin.x + rect1.size.width, rect2.origin.x + rect2.size.width);\n const bottom = Math.max(rect1.origin.y + rect1.size.height, rect2.origin.y + rect2.size.height);\n return {\n origin: { x: left, y: top },\n size: { width: right - left, height: bottom - top }\n };\n}\nfunction rectIntersect(rect1, rect2) {\n const left = Math.max(rect1.origin.x, rect2.origin.x);\n const top = Math.max(rect1.origin.y, rect2.origin.y);\n const right = Math.min(rect1.origin.x + rect1.size.width, rect2.origin.x + rect2.size.width);\n const bottom = Math.min(rect1.origin.y + rect1.size.height, rect2.origin.y + rect2.size.height);\n const width = Math.max(0, right - left);\n const height = Math.max(0, bottom - top);\n return {\n origin: { x: left, y: top },\n size: { width, height }\n };\n}\nfunction rectIsEmpty(rect) {\n return rect.size.width <= 0 || rect.size.height <= 0;\n}\nfunction getVerticalOverlap(rect1, rect2) {\n if (rectIsEmpty(rect1) || rectIsEmpty(rect2)) return 0;\n const unionRect = rectUnion(rect1, rect2);\n if (unionRect.size.height === rect1.size.height || unionRect.size.height === rect2.size.height) {\n return 1;\n }\n const intersectRect = rectIntersect(rect1, rect2);\n return intersectRect.size.height / unionRect.size.height;\n}\nfunction shouldMergeHorizontalRects(textRun1, textRun2) {\n const FONT_SIZE_RATIO_THRESHOLD = 1.5;\n if (textRun1.fontSize != null && textRun2.fontSize != null && textRun1.fontSize > 0 && textRun2.fontSize > 0) {\n const ratio = Math.max(textRun1.fontSize, textRun2.fontSize) / Math.min(textRun1.fontSize, textRun2.fontSize);\n if (ratio > FONT_SIZE_RATIO_THRESHOLD) {\n return false;\n }\n }\n const VERTICAL_OVERLAP_THRESHOLD = 0.8;\n const rect1 = textRun1.rect;\n const rect2 = textRun2.rect;\n if (getVerticalOverlap(rect1, rect2) < VERTICAL_OVERLAP_THRESHOLD) {\n return false;\n }\n const HORIZONTAL_WIDTH_FACTOR = 1;\n const averageWidth1 = HORIZONTAL_WIDTH_FACTOR * rect1.size.width / textRun1.charCount;\n const averageWidth2 = HORIZONTAL_WIDTH_FACTOR * rect2.size.width / textRun2.charCount;\n const rect1Left = rect1.origin.x - averageWidth1;\n const rect1Right = rect1.origin.x + rect1.size.width + averageWidth1;\n const rect2Left = rect2.origin.x - averageWidth2;\n const rect2Right = rect2.origin.x + rect2.size.width + averageWidth2;\n return rect1Left < rect2Right && rect1Right > rect2Left;\n}\nfunction mergeAdjacentRects(textRuns) {\n const results = [];\n let previousTextRun = null;\n let currentRect = null;\n for (const textRun of textRuns) {\n if (previousTextRun && currentRect) {\n if (shouldMergeHorizontalRects(previousTextRun, textRun)) {\n currentRect = rectUnion(currentRect, textRun.rect);\n } else {\n results.push(currentRect);\n currentRect = textRun.rect;\n }\n } else {\n currentRect = textRun.rect;\n }\n previousTextRun = textRun;\n }\n if (currentRect && !rectIsEmpty(currentRect)) {\n results.push(currentRect);\n }\n return results;\n}\nconst VERTICAL_OVERLAP_THRESHOLD_LINE = 0.5;\nfunction resolveCharIndex(geo, charIndex) {\n for (let r = 0; r < geo.runs.length; r++) {\n const run = geo.runs[r];\n const localIdx = charIndex - run.charStart;\n if (localIdx >= 0 && localIdx < run.glyphs.length) {\n return { runIdx: r, localIdx };\n }\n }\n return null;\n}\nfunction isGlyphWordBoundary(flags) {\n return flags === 1 || flags === 2;\n}\nfunction expandToWordBoundary(geo, charIndex) {\n const resolved = resolveCharIndex(geo, charIndex);\n if (!resolved) return null;\n const totalChars = getTotalCharCount(geo);\n if (totalChars === 0) return null;\n let from = charIndex;\n while (from > 0) {\n const prev = resolveCharIndex(geo, from - 1);\n if (!prev) break;\n if (isGlyphWordBoundary(geo.runs[prev.runIdx].glyphs[prev.localIdx].flags)) break;\n from--;\n }\n let to = charIndex;\n while (to < totalChars - 1) {\n const next = resolveCharIndex(geo, to + 1);\n if (!next) break;\n if (isGlyphWordBoundary(geo.runs[next.runIdx].glyphs[next.localIdx].flags)) break;\n to++;\n }\n return { from, to };\n}\nfunction expandToLineBoundary(geo, charIndex) {\n const resolved = resolveCharIndex(geo, charIndex);\n if (!resolved) return null;\n const anchorRun = geo.runs[resolved.runIdx];\n const anchorTop = anchorRun.rect.y;\n const anchorBottom = anchorRun.rect.y + anchorRun.rect.height;\n let from = anchorRun.charStart;\n let to = anchorRun.charStart + anchorRun.glyphs.length - 1;\n for (let r = resolved.runIdx - 1; r >= 0; r--) {\n const run = geo.runs[r];\n if (isZeroSizeRun(run)) continue;\n if (!runsOverlapVertically(run.rect.y, run.rect.y + run.rect.height, anchorTop, anchorBottom)) {\n break;\n }\n from = run.charStart;\n }\n for (let r = resolved.runIdx + 1; r < geo.runs.length; r++) {\n const run = geo.runs[r];\n if (isZeroSizeRun(run)) continue;\n if (!runsOverlapVertically(run.rect.y, run.rect.y + run.rect.height, anchorTop, anchorBottom)) {\n break;\n }\n to = run.charStart + run.glyphs.length - 1;\n }\n return { from, to };\n}\nfunction isZeroSizeRun(run) {\n return run.rect.width === 0 && run.rect.height === 0;\n}\nfunction runsOverlapVertically(top1, bottom1, top2, bottom2) {\n const unionHeight = Math.max(bottom1, bottom2) - Math.min(top1, top2);\n const intersectHeight = Math.max(0, Math.min(bottom1, bottom2) - Math.max(top1, top2));\n if (unionHeight === 0) return false;\n return intersectHeight / unionHeight >= VERTICAL_OVERLAP_THRESHOLD_LINE;\n}\nfunction getTotalCharCount(geo) {\n if (geo.runs.length === 0) return 0;\n const lastRun = geo.runs[geo.runs.length - 1];\n return lastRun.charStart + lastRun.glyphs.length;\n}\nconst TRIPLE_CLICK_INTERVAL_MS = 500;\nfunction createTextSelectionHandler(opts) {\n const minDrag = opts.minDragDistance ?? 3;\n const tolFactor = opts.toleranceFactor ?? 1.5;\n let anchorGlyph = null;\n let anchorPos = null;\n let dragStarted = false;\n let lastDblClickTime = 0;\n function reset() {\n var _a;\n anchorGlyph = null;\n anchorPos = null;\n dragStarted = false;\n (_a = opts.setHasTextAnchor) == null ? void 0 : _a.call(opts, false);\n }\n return {\n onPointerDown: (point, evt, modeId) => {\n var _a, _b;\n if (evt.target === evt.currentTarget) {\n (_a = opts.onEmptySpaceClick) == null ? void 0 : _a.call(opts, modeId);\n }\n if (!opts.isEnabled(modeId)) return;\n const now = Date.now();\n if (lastDblClickTime === 0 || now - lastDblClickTime >= TRIPLE_CLICK_INTERVAL_MS) {\n opts.onClear(modeId);\n }\n const geo = opts.getGeometry();\n if (!geo) return;\n const g = glyphAt(geo, point, tolFactor);\n if (g !== -1) {\n anchorGlyph = g;\n anchorPos = point;\n dragStarted = false;\n (_b = opts.setHasTextAnchor) == null ? void 0 : _b.call(opts, true);\n }\n },\n onPointerMove: (point, _evt, modeId) => {\n if (!opts.isEnabled(modeId)) return;\n const geo = opts.getGeometry();\n if (!geo) return;\n const g = glyphAt(geo, point, tolFactor);\n opts.setCursor(g !== -1 ? \"text\" : null);\n if (anchorGlyph !== null && anchorPos && !dragStarted) {\n const dx = point.x - anchorPos.x;\n const dy = point.y - anchorPos.y;\n const dist = Math.sqrt(dx * dx + dy * dy);\n if (dist >= minDrag) {\n dragStarted = true;\n opts.onBegin(anchorGlyph, modeId);\n if (g !== -1) {\n opts.onUpdate(g, modeId);\n }\n }\n return;\n }\n if (opts.isSelecting() && g !== -1) {\n opts.onUpdate(g, modeId);\n }\n },\n onPointerUp: (_point, _evt, modeId) => {\n if (!opts.isEnabled(modeId)) {\n reset();\n return;\n }\n if (dragStarted) {\n opts.onEnd(modeId);\n }\n reset();\n },\n onDoubleClick: (point, _evt, modeId) => {\n var _a;\n if (!opts.isEnabled(modeId)) return;\n const geo = opts.getGeometry();\n if (!geo) return;\n const g = glyphAt(geo, point, tolFactor);\n if (g === -1) return;\n lastDblClickTime = Date.now();\n (_a = opts.onWordSelect) == null ? void 0 : _a.call(opts, g, modeId);\n },\n onClick: (point, _evt, modeId) => {\n var _a;\n if (!opts.isEnabled(modeId)) return;\n if (lastDblClickTime === 0) return;\n const now = Date.now();\n if (now - lastDblClickTime > TRIPLE_CLICK_INTERVAL_MS) {\n lastDblClickTime = 0;\n return;\n }\n lastDblClickTime = 0;\n const geo = opts.getGeometry();\n if (!geo) return;\n const g = glyphAt(geo, point, tolFactor);\n if (g === -1) return;\n (_a = opts.onLineSelect) == null ? void 0 : _a.call(opts, g, modeId);\n },\n onHandlerActiveEnd: (modeId) => {\n reset();\n if (!opts.isEnabled(modeId)) return;\n opts.onClear(modeId);\n }\n };\n}\nfunction createMarqueeSelectionHandler(opts) {\n const { pageSize, scale, minDragPx = 5 } = opts;\n let start = null;\n let last = null;\n return {\n onPointerDown: (pos, evt, modeId) => {\n var _a, _b;\n if (!opts.isEnabled(modeId)) return;\n if ((_a = opts.isTextSelecting) == null ? void 0 : _a.call(opts)) return;\n start = pos;\n last = { origin: { x: pos.x, y: pos.y }, size: { width: 0, height: 0 } };\n opts.onBegin(pos, modeId);\n (_b = evt.setPointerCapture) == null ? void 0 : _b.call(evt);\n },\n onPointerMove: (pos, _evt, modeId) => {\n if (!start || !opts.isEnabled(modeId)) return;\n const x = clamp(pos.x, 0, pageSize.width);\n const y = clamp(pos.y, 0, pageSize.height);\n last = {\n origin: { x: Math.min(start.x, x), y: Math.min(start.y, y) },\n size: { width: Math.abs(x - start.x), height: Math.abs(y - start.y) }\n };\n opts.onChange(last, modeId);\n },\n onPointerUp: (_pos, evt, modeId) => {\n var _a;\n if (!opts.isEnabled(modeId)) return;\n if (last && start) {\n const dragPx = Math.max(last.size.width, last.size.height) * scale;\n if (dragPx > minDragPx) {\n opts.onEnd(last, modeId);\n } else {\n opts.onCancel(modeId);\n }\n }\n start = null;\n last = null;\n (_a = evt.releasePointerCapture) == null ? void 0 : _a.call(evt);\n },\n onPointerCancel: (_pos, evt, modeId) => {\n var _a;\n if (!opts.isEnabled(modeId)) return;\n start = null;\n last = null;\n opts.onCancel(modeId);\n (_a = evt.releasePointerCapture) == null ? void 0 : _a.call(evt);\n }\n };\n}\nconst _SelectionPlugin = class _SelectionPlugin extends BasePlugin {\n constructor(id, registry, config) {\n var _a, _b, _c;\n super(id, registry);\n this.enabledModesPerDoc = /* @__PURE__ */ new Map();\n this.selecting = /* @__PURE__ */ new Map();\n this.anchor = /* @__PURE__ */ new Map();\n this.hasTextAnchor = /* @__PURE__ */ new Map();\n this.marqueePage = /* @__PURE__ */ new Map();\n this.pageCallbacks = /* @__PURE__ */ new Map();\n this.geoAccessOrder = /* @__PURE__ */ new Map();\n this.menuPlacement$ = createScopedEmitter((documentId, placement) => ({ documentId, placement }));\n this.selChange$ = createScopedEmitter((documentId, selection) => ({\n documentId,\n selection,\n modeId: this.interactionManagerCapability.forDocument(documentId).getActiveMode()\n }));\n this.textRetrieved$ = createScopedEmitter(\n (documentId, text) => ({ documentId, text })\n );\n this.copyToClipboard$ = createScopedEmitter(\n (documentId, text) => ({ documentId, text }),\n { cache: false }\n );\n this.beginSelection$ = createScopedEmitter(\n (documentId, data) => ({\n documentId,\n page: data.page,\n index: data.index,\n modeId: data.modeId\n }),\n { cache: false }\n );\n this.endSelection$ = createScopedEmitter((documentId, data) => ({ documentId, modeId: data.modeId }), { cache: false });\n this.marqueeChange$ = createScopedEmitter(\n (documentId, data) => ({\n documentId,\n pageIndex: data.pageIndex,\n rect: data.rect,\n modeId: data.modeId\n }),\n { cache: false }\n );\n this.marqueeEnd$ = createScopedEmitter(\n (documentId, data) => ({\n documentId,\n pageIndex: data.pageIndex,\n rect: data.rect,\n modeId: data.modeId\n }),\n { cache: false }\n );\n this.emptySpaceClick$ = createScopedEmitter(\n (documentId, data) => ({\n documentId,\n pageIndex: data.pageIndex,\n modeId: data.modeId\n }),\n { cache: false }\n );\n this.viewportCapability = null;\n this.scrollCapability = null;\n this.config = config;\n this.menuHeight = config.menuHeight ?? 40;\n const imPlugin = registry.getPlugin(\"interaction-manager\");\n if (!imPlugin) {\n throw new Error(\"SelectionPlugin: InteractionManagerPlugin is required.\");\n }\n this.interactionManagerCapability = imPlugin.provides();\n this.viewportCapability = ((_a = registry.getPlugin(\"viewport\")) == null ? void 0 : _a.provides()) ?? null;\n this.scrollCapability = ((_b = registry.getPlugin(\"scroll\")) == null ? void 0 : _b.provides()) ?? null;\n this.coreStore.onAction(REFRESH_PAGES, (action) => {\n const { documentId, pageIndexes } = action.payload;\n const tasks = pageIndexes.map(\n (pageIndex) => this.getNewPageGeometryAndCache(documentId, pageIndex)\n );\n Task.all(tasks).wait(() => {\n pageIndexes.forEach((pageIndex) => {\n this.notifyPage(documentId, pageIndex);\n });\n }, ignore);\n });\n (_c = this.viewportCapability) == null ? void 0 : _c.onViewportChange(\n (event) => {\n this.recalculateMenuPlacement(event.documentId);\n },\n { mode: \"throttle\", wait: 100 }\n );\n }\n /* ── life-cycle ────────────────────────────────────────── */\n onDocumentLoadingStarted(documentId) {\n var _a;\n this.dispatch(initSelectionState(documentId, initialSelectionDocumentState));\n const marqueeEnabled = ((_a = this.config.marquee) == null ? void 0 : _a.enabled) !== false;\n this.enabledModesPerDoc.set(\n documentId,\n /* @__PURE__ */ new Map([\n [\n \"pointerMode\",\n {\n enableSelection: true,\n showSelectionRects: true,\n enableMarquee: marqueeEnabled,\n showMarqueeRects: true\n }\n ]\n ])\n );\n this.pageCallbacks.set(documentId, /* @__PURE__ */ new Map());\n this.geoAccessOrder.set(documentId, []);\n this.selecting.set(documentId, false);\n this.anchor.set(documentId, void 0);\n this.hasTextAnchor.set(documentId, false);\n }\n onDocumentClosed(documentId) {\n this.dispatch(cleanupSelectionState(documentId));\n this.enabledModesPerDoc.delete(documentId);\n this.pageCallbacks.delete(documentId);\n this.geoAccessOrder.delete(documentId);\n this.selecting.delete(documentId);\n this.hasTextAnchor.delete(documentId);\n this.anchor.delete(documentId);\n this.marqueePage.delete(documentId);\n this.selChange$.clearScope(documentId);\n this.textRetrieved$.clearScope(documentId);\n this.copyToClipboard$.clearScope(documentId);\n this.beginSelection$.clearScope(documentId);\n this.endSelection$.clearScope(documentId);\n this.menuPlacement$.clearScope(documentId);\n this.marqueeChange$.clearScope(documentId);\n this.marqueeEnd$.clearScope(documentId);\n this.emptySpaceClick$.clearScope(documentId);\n }\n async initialize() {\n }\n async destroy() {\n this.selChange$.clear();\n this.textRetrieved$.clear();\n this.copyToClipboard$.clear();\n this.beginSelection$.clear();\n this.endSelection$.clear();\n this.menuPlacement$.clear();\n this.marqueeChange$.clear();\n this.marqueeEnd$.clear();\n this.emptySpaceClick$.clear();\n super.destroy();\n }\n /* ── capability exposed to UI / other plugins ─────────── */\n buildCapability() {\n const getDocId = (documentId) => documentId ?? this.getActiveDocumentId();\n return {\n // Active document operations\n getFormattedSelection: (docId) => getFormattedSelection(this.getDocumentState(getDocId(docId))),\n getFormattedSelectionForPage: (p, docId) => getFormattedSelectionForPage(this.getDocumentState(getDocId(docId)), p),\n getHighlightRectsForPage: (p, docId) => selectRectsForPage(this.getDocumentState(getDocId(docId)), p),\n getHighlightRects: (docId) => this.getDocumentState(getDocId(docId)).rects,\n getBoundingRectForPage: (p, docId) => selectBoundingRectForPage(this.getDocumentState(getDocId(docId)), p),\n getBoundingRects: (docId) => selectBoundingRectsForAllPages(this.getDocumentState(getDocId(docId))),\n getSelectedText: (docId) => this.getSelectedText(getDocId(docId)),\n setSelection: (range, docId) => this.applySelection(getDocId(docId), range),\n clear: (docId) => this.clearSelection(getDocId(docId)),\n copyToClipboard: (docId) => this.copyToClipboard(getDocId(docId)),\n getState: (docId) => this.getDocumentState(getDocId(docId)),\n enableForMode: (modeId, options, docId) => {\n var _a;\n return (_a = this.enabledModesPerDoc.get(getDocId(docId))) == null ? void 0 : _a.set(modeId, { ...options });\n },\n isEnabledForMode: (modeId, docId) => {\n var _a;\n return ((_a = this.enabledModesPerDoc.get(getDocId(docId))) == null ? void 0 : _a.has(modeId)) ?? false;\n },\n setMarqueeEnabled: (enabled, docId) => this.setMarqueeEnabled(getDocId(docId), enabled),\n isMarqueeEnabled: (docId) => this.isMarqueeEnabled(getDocId(docId)),\n // Document-scoped operations\n forDocument: this.createSelectionScope.bind(this),\n // Global events\n onCopyToClipboard: this.copyToClipboard$.onGlobal,\n onSelectionChange: this.selChange$.onGlobal,\n onTextRetrieved: this.textRetrieved$.onGlobal,\n onBeginSelection: this.beginSelection$.onGlobal,\n onEndSelection: this.endSelection$.onGlobal,\n // Marquee selection events\n onMarqueeChange: this.marqueeChange$.onGlobal,\n onMarqueeEnd: this.marqueeEnd$.onGlobal,\n // Empty space click event\n onEmptySpaceClick: this.emptySpaceClick$.onGlobal\n };\n }\n createSelectionScope(documentId) {\n return {\n getFormattedSelection: () => getFormattedSelection(this.getDocumentState(documentId)),\n getFormattedSelectionForPage: (p) => getFormattedSelectionForPage(this.getDocumentState(documentId), p),\n getHighlightRectsForPage: (p) => selectRectsForPage(this.getDocumentState(documentId), p),\n getHighlightRects: () => this.getDocumentState(documentId).rects,\n getBoundingRectForPage: (p) => selectBoundingRectForPage(this.getDocumentState(documentId), p),\n getBoundingRects: () => selectBoundingRectsForAllPages(this.getDocumentState(documentId)),\n getSelectedText: () => this.getSelectedText(documentId),\n setSelection: (range) => this.applySelection(documentId, range),\n clear: () => this.clearSelection(documentId),\n copyToClipboard: () => this.copyToClipboard(documentId),\n getState: () => this.getDocumentState(documentId),\n setMarqueeEnabled: (enabled) => this.setMarqueeEnabled(documentId, enabled),\n isMarqueeEnabled: () => this.isMarqueeEnabled(documentId),\n onSelectionChange: this.selChange$.forScope(documentId),\n onTextRetrieved: this.textRetrieved$.forScope(documentId),\n onCopyToClipboard: this.copyToClipboard$.forScope(documentId),\n onBeginSelection: this.beginSelection$.forScope(documentId),\n onEndSelection: this.endSelection$.forScope(documentId),\n onMarqueeChange: this.marqueeChange$.forScope(documentId),\n onMarqueeEnd: this.marqueeEnd$.forScope(documentId),\n onEmptySpaceClick: this.emptySpaceClick$.forScope(documentId)\n };\n }\n getDocumentState(documentId) {\n const state = this.state.documents[documentId];\n if (!state) {\n throw new Error(`Selection state not found for document: ${documentId}`);\n }\n return state;\n }\n /**\n * Subscribe to menu placement changes for a specific document\n * @param documentId - The document ID to subscribe to\n * @param listener - Callback function that receives placement updates\n * @returns Unsubscribe function\n */\n onMenuPlacement(documentId, listener) {\n return this.menuPlacement$.forScope(documentId)(listener);\n }\n /**\n * Register text selection on a page. Uses `registerAlways` so any plugin\n * can enable text selection for their mode via `enableForMode()`.\n */\n registerSelectionOnPage(opts) {\n var _a;\n const { documentId, pageIndex, onRectsChange } = opts;\n const docState = this.state.documents[documentId];\n if (!docState) {\n this.logger.warn(\n \"SelectionPlugin\",\n \"RegisterFailed\",\n `Cannot register selection on page ${pageIndex} for document ${documentId}: document state not initialized.`\n );\n return () => {\n };\n }\n (_a = this.pageCallbacks.get(documentId)) == null ? void 0 : _a.set(pageIndex, onRectsChange);\n const geoTask = this.getOrLoadGeometry(documentId, pageIndex);\n const interactionScope = this.interactionManagerCapability.forDocument(documentId);\n const enabledModes = this.enabledModesPerDoc.get(documentId);\n onRectsChange({\n rects: selectRectsForPage(docState, pageIndex),\n boundingRect: selectBoundingRectForPage(docState, pageIndex)\n });\n geoTask.wait((geo) => {\n const currentState = this.getDocumentState(documentId);\n const sel = currentState.selection;\n if (!sel || pageIndex < sel.start.page || pageIndex > sel.end.page) return;\n const sb = sliceBounds(sel, geo, pageIndex);\n if (!sb) return;\n const pageRects = rectsWithinSlice(geo, sb.from, sb.to);\n this.dispatch(setRects(documentId, { ...currentState.rects, [pageIndex]: pageRects }));\n this.dispatch(\n setSlices(documentId, {\n ...currentState.slices,\n [pageIndex]: { start: sb.from, count: sb.to - sb.from + 1 }\n })\n );\n this.notifyPage(documentId, pageIndex);\n }, ignore);\n const textHandler = createTextSelectionHandler({\n getGeometry: () => this.getDocumentState(documentId).geometry[pageIndex],\n isEnabled: (modeId) => {\n const config = enabledModes == null ? void 0 : enabledModes.get(modeId);\n if (!config) return false;\n return config.enableSelection !== false;\n },\n onBegin: (g, modeId) => this.beginSelection(documentId, pageIndex, g, modeId),\n onUpdate: (g, modeId) => this.updateSelection(documentId, pageIndex, g, modeId),\n onEnd: (modeId) => this.endSelection(documentId, modeId),\n onClear: (modeId) => this.clearSelection(documentId, modeId),\n isSelecting: () => this.selecting.get(documentId) ?? false,\n setCursor: (cursor) => cursor ? interactionScope.setCursor(\"selection-text\", cursor, 10) : interactionScope.removeCursor(\"selection-text\"),\n onEmptySpaceClick: (modeId) => this.emptySpaceClick$.emit(documentId, { pageIndex, modeId }),\n onWordSelect: (g, modeId) => this.selectWord(documentId, pageIndex, g, modeId),\n onLineSelect: (g, modeId) => this.selectLine(documentId, pageIndex, g, modeId),\n setHasTextAnchor: (active) => this.hasTextAnchor.set(documentId, active),\n minDragDistance: this.config.minSelectionDragDistance,\n toleranceFactor: this.config.toleranceFactor\n });\n const unregisterHandlers = this.interactionManagerCapability.registerAlways({\n scope: { type: \"page\", documentId, pageIndex },\n handlers: textHandler\n });\n return () => {\n var _a2;\n unregisterHandlers();\n (_a2 = this.pageCallbacks.get(documentId)) == null ? void 0 : _a2.delete(pageIndex);\n geoTask.abort({ code: PdfErrorCode.Cancelled, message: \"Cleanup\" });\n };\n }\n /**\n * Register marquee selection on a page. Uses `registerAlways` so any plugin\n * can enable marquee selection for their mode via `enableForMode({ enableMarquee: true })`.\n */\n registerMarqueeOnPage(opts) {\n var _a;\n const { documentId, pageIndex, scale, onRectChange } = opts;\n const docState = this.state.documents[documentId];\n if (!docState) {\n this.logger.warn(\n \"SelectionPlugin\",\n \"RegisterMarqueeFailed\",\n `Cannot register marquee on page ${pageIndex} for document ${documentId}: document state not initialized.`\n );\n return () => {\n };\n }\n const coreDoc = this.coreState.core.documents[documentId];\n if (!coreDoc || !coreDoc.document) {\n this.logger.warn(\n \"SelectionPlugin\",\n \"DocumentNotFound\",\n `Cannot register marquee on page ${pageIndex}: document not found`\n );\n return () => {\n };\n }\n const page = coreDoc.document.pages[pageIndex];\n if (!page) {\n this.logger.warn(\n \"SelectionPlugin\",\n \"PageNotFound\",\n `Cannot register marquee on page ${pageIndex}: page not found`\n );\n return () => {\n };\n }\n const pageSize = page.size;\n const minDragPx = ((_a = this.config.marquee) == null ? void 0 : _a.minDragPx) ?? 5;\n const shouldShowRect = () => {\n var _a2;\n const mode = this.interactionManagerCapability.forDocument(documentId).getActiveMode();\n const config = (_a2 = this.enabledModesPerDoc.get(documentId)) == null ? void 0 : _a2.get(mode);\n return (config == null ? void 0 : config.showMarqueeRects) !== false;\n };\n const marqueeHandler = createMarqueeSelectionHandler({\n pageSize,\n scale,\n minDragPx,\n isEnabled: (modeId) => {\n var _a2;\n const config = (_a2 = this.enabledModesPerDoc.get(documentId)) == null ? void 0 : _a2.get(modeId);\n return (config == null ? void 0 : config.enableMarquee) === true;\n },\n isTextSelecting: () => (this.selecting.get(documentId) ?? false) || (this.hasTextAnchor.get(documentId) ?? false),\n onBegin: (pos, modeId) => this.beginMarquee(documentId, pageIndex, pos, modeId),\n onChange: (rect, modeId) => {\n this.updateMarquee(documentId, pageIndex, rect, modeId);\n onRectChange(shouldShowRect() ? rect : null);\n },\n onEnd: (rect, modeId) => {\n this.endMarquee(documentId, pageIndex, rect, modeId);\n onRectChange(null);\n },\n onCancel: (modeId) => {\n this.cancelMarquee(documentId, modeId);\n onRectChange(null);\n }\n });\n const unregisterHandlers = this.interactionManagerCapability.registerAlways({\n scope: { type: \"page\", documentId, pageIndex },\n handlers: marqueeHandler\n });\n return unregisterHandlers;\n }\n /**\n * Helper to calculate viewport relative metrics for a page rect.\n * Returns null if the rect cannot be converted to viewport space.\n */\n getPlacementMetrics(documentId, pageIndex, rect, vpMetrics) {\n var _a;\n const scrollScope = (_a = this.scrollCapability) == null ? void 0 : _a.forDocument(documentId);\n const viewportRect = scrollScope == null ? void 0 : scrollScope.getRectPositionForPage(pageIndex, rect);\n if (!viewportRect) return null;\n const rectTopInView = viewportRect.origin.y - vpMetrics.scrollTop;\n const rectBottomInView = viewportRect.origin.y + viewportRect.size.height - vpMetrics.scrollTop;\n return {\n pageIndex,\n rect,\n // Original Page Rect\n spaceAbove: rectTopInView,\n spaceBelow: vpMetrics.clientHeight - rectBottomInView,\n isBottomVisible: rectBottomInView > 0 && rectBottomInView <= vpMetrics.clientHeight,\n isTopVisible: rectTopInView >= 0 && rectTopInView < vpMetrics.clientHeight\n };\n }\n emitMenuPlacement(documentId, placement) {\n this.menuPlacement$.emit(documentId, placement);\n if (placement) {\n this.interactionManagerCapability.claimPageActivity(\n documentId,\n \"selection-menu\",\n placement.pageIndex\n );\n } else {\n this.interactionManagerCapability.releasePageActivity(documentId, \"selection-menu\");\n }\n }\n recalculateMenuPlacement(documentId) {\n const docState = this.state.documents[documentId];\n if (!docState) return;\n if (docState.selecting || docState.selection === null) {\n this.emitMenuPlacement(documentId, null);\n return;\n }\n const bounds = selectBoundingRectsForAllPages(docState);\n if (bounds.length === 0) {\n this.emitMenuPlacement(documentId, null);\n return;\n }\n const tail = bounds[bounds.length - 1];\n if (!this.viewportCapability || !this.scrollCapability) {\n this.emitMenuPlacement(documentId, {\n pageIndex: tail.page,\n rect: tail.rect,\n spaceAbove: 0,\n spaceBelow: Infinity,\n // Pretend we have infinite space below to prevent auto-flipping\n suggestTop: false,\n isVisible: true\n // Assume visible\n });\n return;\n }\n const viewportScope = this.viewportCapability.forDocument(documentId);\n const vpMetrics = viewportScope.getMetrics();\n const head = bounds[0];\n const tailMetrics = this.getPlacementMetrics(documentId, tail.page, tail.rect, vpMetrics);\n const headMetrics = this.getPlacementMetrics(documentId, head.page, head.rect, vpMetrics);\n if (tailMetrics) {\n if (tailMetrics.isBottomVisible && tailMetrics.spaceBelow > this.menuHeight) {\n this.emitMenuPlacement(documentId, {\n ...tailMetrics,\n suggestTop: false,\n isVisible: true\n });\n return;\n }\n }\n if (headMetrics) {\n if (headMetrics.isTopVisible) {\n this.emitMenuPlacement(documentId, {\n ...headMetrics,\n suggestTop: true,\n isVisible: true\n });\n return;\n }\n }\n if (tailMetrics && tailMetrics.isBottomVisible) {\n this.emitMenuPlacement(documentId, {\n ...tailMetrics,\n suggestTop: false,\n isVisible: true\n });\n return;\n }\n this.emitMenuPlacement(documentId, null);\n }\n notifyPage(documentId, pageIndex) {\n var _a, _b;\n const callback = (_a = this.pageCallbacks.get(documentId)) == null ? void 0 : _a.get(pageIndex);\n if (callback) {\n const docState = this.getDocumentState(documentId);\n const mode = this.interactionManagerCapability.forDocument(documentId).getActiveMode();\n const modeConfig = (_b = this.enabledModesPerDoc.get(documentId)) == null ? void 0 : _b.get(mode);\n const shouldShowRects = modeConfig && (modeConfig.showSelectionRects ?? modeConfig.showRects) !== false;\n if (shouldShowRects) {\n callback({\n rects: selectRectsForPage(docState, pageIndex),\n boundingRect: selectBoundingRectForPage(docState, pageIndex)\n });\n } else {\n callback({ rects: [], boundingRect: null });\n }\n }\n }\n notifyAllPages(documentId) {\n var _a;\n (_a = this.pageCallbacks.get(documentId)) == null ? void 0 : _a.forEach((_, pageIndex) => {\n this.notifyPage(documentId, pageIndex);\n });\n }\n getNewPageGeometryAndCache(documentId, pageIdx) {\n const coreDoc = this.getCoreDocument(documentId);\n if (!coreDoc || !coreDoc.document)\n return PdfTaskHelper.reject({ code: PdfErrorCode.NotFound, message: \"Doc Not Found\" });\n const page = coreDoc.document.pages.find((p) => p.index === pageIdx);\n const task = this.engine.getPageGeometry(coreDoc.document, page);\n task.wait((geo) => {\n this.dispatch(cachePageGeometry(documentId, pageIdx, geo));\n this.touchGeometry(documentId, pageIdx);\n }, ignore);\n return task;\n }\n /* ── geometry cache ───────────────────────────────────── */\n getOrLoadGeometry(documentId, pageIdx) {\n const cached = this.getDocumentState(documentId).geometry[pageIdx];\n if (cached) {\n this.touchGeometry(documentId, pageIdx);\n return PdfTaskHelper.resolve(cached);\n }\n return this.getNewPageGeometryAndCache(documentId, pageIdx);\n }\n /* ── geometry LRU eviction ──────────────────────────────── */\n touchGeometry(documentId, pageIdx) {\n const order = this.geoAccessOrder.get(documentId);\n if (!order) return;\n const idx = order.indexOf(pageIdx);\n if (idx > -1) order.splice(idx, 1);\n order.push(pageIdx);\n this.evictGeometryIfNeeded(documentId);\n }\n evictGeometryIfNeeded(documentId) {\n const max = this.config.maxCachedGeometries ?? 50;\n const order = this.geoAccessOrder.get(documentId);\n if (!order || order.length <= max) return;\n const pinned = this.pageCallbacks.get(documentId);\n const toEvict = [];\n while (order.length - toEvict.length > max) {\n const candidate = order.find((p) => !toEvict.includes(p) && !(pinned == null ? void 0 : pinned.has(p)));\n if (candidate === void 0) break;\n toEvict.push(candidate);\n }\n if (toEvict.length === 0) return;\n for (const p of toEvict) {\n const idx = order.indexOf(p);\n if (idx > -1) order.splice(idx, 1);\n }\n this.dispatch(evictPageGeometry(documentId, toEvict));\n }\n /* ── selection state updates ───────────────────────────── */\n beginSelection(documentId, page, index, modeId) {\n this.selecting.set(documentId, true);\n this.anchor.set(documentId, { page, index });\n this.dispatch(startSelection(documentId));\n this.beginSelection$.emit(documentId, { page, index, modeId });\n this.recalculateMenuPlacement(documentId);\n }\n endSelection(documentId, modeId) {\n this.selecting.set(documentId, false);\n this.anchor.set(documentId, void 0);\n this.dispatch(endSelection(documentId));\n this.endSelection$.emit(documentId, { modeId });\n this.recalculateMenuPlacement(documentId);\n }\n clearSelection(documentId, _modeId) {\n this.selecting.set(documentId, false);\n this.anchor.set(documentId, void 0);\n this.dispatch(clearSelection(documentId));\n this.selChange$.emit(documentId, null);\n this.emitMenuPlacement(documentId, null);\n this.notifyAllPages(documentId);\n }\n /**\n * Programmatically apply (or restore) a text selection without going through\n * the pointer drag flow. Useful for restoring a previously persisted selection\n * or driving selection from code (e.g. search results).\n *\n * Geometry for every page spanned by the range is loaded on demand (the data\n * comes from the WASM engine), so the returned task settles only once the\n * selection rects have actually been computed.\n *\n * Passing `null` is equivalent to calling {@link clearSelection}.\n *\n * @returns a task that resolves once the selection has been applied.\n */\n applySelection(documentId, range) {\n if (!this.state.documents[documentId]) {\n return PdfTaskHelper.reject({\n code: PdfErrorCode.NotFound,\n message: `Selection state not found for document: ${documentId}`\n });\n }\n if (range === null) {\n this.clearSelection(documentId);\n return PdfTaskHelper.resolve(void 0);\n }\n const validationError = this.validateRange(documentId, range);\n if (validationError) {\n return PdfTaskHelper.reject(validationError);\n }\n const normalized = this.normalizeRange(range);\n const pages = [];\n for (let p = normalized.start.page; p <= normalized.end.page; p++) {\n pages.push(p);\n }\n const geoTasks = pages.map((p) => this.getOrLoadGeometry(documentId, p));\n const result = PdfTaskHelper.create();\n Task.all(geoTasks).wait(() => {\n if (!this.state.documents[documentId]) {\n result.reject({\n code: PdfErrorCode.NotFound,\n message: `Selection state not found for document: ${documentId}`\n });\n return;\n }\n const clamped = this.clampRangeToGeometry(documentId, normalized);\n if (!clamped) {\n result.reject({\n code: PdfErrorCode.NotFound,\n message: `Cannot apply selection: page(s) ${normalized.start.page}-${normalized.end.page} have no text geometry`\n });\n return;\n }\n this.selecting.set(documentId, false);\n this.anchor.set(documentId, void 0);\n const previouslyHighlighted = Object.keys(this.getDocumentState(documentId).rects).map(\n Number\n );\n this.dispatch(startSelection(documentId));\n this.dispatch(setSelection(documentId, clamped));\n this.updateRectsAndSlices(documentId, clamped);\n this.dispatch(endSelection(documentId));\n this.selChange$.emit(documentId, clamped);\n const pagesToNotify = new Set(previouslyHighlighted);\n for (let p = clamped.start.page; p <= clamped.end.page; p++) {\n pagesToNotify.add(p);\n }\n pagesToNotify.forEach((p) => this.notifyPage(documentId, p));\n this.recalculateMenuPlacement(documentId);\n result.resolve(void 0);\n }, (error) => result.reject(error.reason));\n return result;\n }\n /**\n * Validate the structure and page bounds of a programmatic selection range.\n * Returns a rejection reason when the input is invalid, or null when it is\n * structurally sound. Glyph-index bounds are enforced separately, after the\n * page geometry has loaded (see {@link clampRangeToGeometry}).\n */\n validateRange(documentId, range) {\n var _a, _b;\n const isValidPointer = (g) => !!g && typeof g === \"object\" && Number.isInteger(g.page) && Number.isInteger(g.index);\n if (!range || typeof range !== \"object\" || !range.start || !range.end) {\n return { code: PdfErrorCode.Unknown, message: \"Invalid selection range: expected { start, end }\" };\n }\n if (!isValidPointer(range.start) || !isValidPointer(range.end)) {\n return {\n code: PdfErrorCode.Unknown,\n message: \"Invalid selection range: start/end must have integer page and index\"\n };\n }\n if (range.start.index < 0 || range.end.index < 0) {\n return { code: PdfErrorCode.Unknown, message: \"Invalid selection range: glyph index cannot be negative\" };\n }\n const pageCount = ((_b = (_a = this.getCoreDocument(documentId)) == null ? void 0 : _a.document) == null ? void 0 : _b.pageCount) ?? 0;\n const minPage = Math.min(range.start.page, range.end.page);\n const maxPage = Math.max(range.start.page, range.end.page);\n if (minPage < 0 || maxPage >= pageCount) {\n return {\n code: PdfErrorCode.NotFound,\n message: `Invalid selection range: page ${minPage < 0 ? minPage : maxPage} out of bounds [0, ${pageCount})`\n };\n }\n return null;\n }\n /**\n * Clamp the glyph indices of a (normalized) range to the number of glyphs\n * available on the corresponding pages. Returns null when none of the\n * spanned pages have any text geometry to select.\n */\n clampRangeToGeometry(documentId, range) {\n const docState = this.getDocumentState(documentId);\n const lastGlyphIndex = (page) => {\n const geo = docState.geometry[page];\n if (!geo || geo.runs.length === 0) return -1;\n const lastRun = geo.runs[geo.runs.length - 1];\n return lastRun.charStart + lastRun.glyphs.length - 1;\n };\n const startMax = lastGlyphIndex(range.start.page);\n const endMax = lastGlyphIndex(range.end.page);\n if (startMax < 0 && endMax < 0) return null;\n const clampIndex = (index, max) => max < 0 ? 0 : Math.min(Math.max(index, 0), max);\n return {\n start: { page: range.start.page, index: clampIndex(range.start.index, startMax) },\n end: { page: range.end.page, index: clampIndex(range.end.index, endMax) }\n };\n }\n /** Order a range so that `start` never comes after `end`. */\n normalizeRange(range) {\n const { start, end } = range;\n const forward = end.page > start.page || end.page === start.page && end.index >= start.index;\n return forward ? { start, end } : { start: end, end: start };\n }\n selectWord(documentId, page, charIndex, modeId) {\n const geo = this.getDocumentState(documentId).geometry[page];\n if (!geo) return;\n const bounds = expandToWordBoundary(geo, charIndex);\n if (!bounds) return;\n this.applyInstantSelection(documentId, page, bounds.from, bounds.to, modeId);\n }\n selectLine(documentId, page, charIndex, modeId) {\n const geo = this.getDocumentState(documentId).geometry[page];\n if (!geo) return;\n const bounds = expandToLineBoundary(geo, charIndex);\n if (!bounds) return;\n this.applyInstantSelection(documentId, page, bounds.from, bounds.to, modeId);\n }\n /**\n * Set a selection range without going through the drag begin/update/end flow.\n * Used by double-click (word) and triple-click (line) selection.\n */\n applyInstantSelection(documentId, page, from, to, modeId) {\n const range = {\n start: { page, index: from },\n end: { page, index: to }\n };\n this.selecting.set(documentId, false);\n this.anchor.set(documentId, void 0);\n this.dispatch(startSelection(documentId));\n this.dispatch(setSelection(documentId, range));\n this.updateRectsAndSlices(documentId, range);\n this.dispatch(endSelection(documentId));\n this.selChange$.emit(documentId, range);\n this.beginSelection$.emit(documentId, { page, index: from, modeId });\n this.endSelection$.emit(documentId, { modeId });\n for (let p = range.start.page; p <= range.end.page; p++) {\n this.notifyPage(documentId, p);\n }\n this.recalculateMenuPlacement(documentId);\n }\n updateSelection(documentId, page, index, modeId) {\n if (!this.selecting.get(documentId) || !this.anchor.get(documentId)) return;\n const a = this.anchor.get(documentId);\n const forward = page > a.page || page === a.page && index >= a.index;\n const start = forward ? a : { page, index };\n const end = forward ? { page, index } : a;\n const range = { start, end };\n this.dispatch(setSelection(documentId, range));\n this.updateRectsAndSlices(documentId, range);\n this.selChange$.emit(documentId, range);\n for (let p = range.start.page; p <= range.end.page; p++) {\n this.notifyPage(documentId, p);\n }\n }\n updateRectsAndSlices(documentId, range) {\n const docState = this.getDocumentState(documentId);\n const allRects = {};\n const allSlices = {};\n for (let p = range.start.page; p <= range.end.page; p++) {\n const geo = docState.geometry[p];\n const sb = sliceBounds(range, geo, p);\n if (!sb) continue;\n allRects[p] = rectsWithinSlice(geo, sb.from, sb.to);\n allSlices[p] = { start: sb.from, count: sb.to - sb.from + 1 };\n }\n this.dispatch(setRects(documentId, allRects));\n this.dispatch(setSlices(documentId, allSlices));\n }\n getSelectedText(documentId) {\n if (!this.checkPermission(documentId, PdfPermissionFlag.CopyContents)) {\n this.logger.debug(\n \"SelectionPlugin\",\n \"GetSelectedText\",\n `Cannot get selected text: document ${documentId} lacks CopyContents permission`\n );\n return PdfTaskHelper.reject({\n code: PdfErrorCode.Security,\n message: \"Document lacks CopyContents permission\"\n });\n }\n const coreDoc = this.getCoreDocument(documentId);\n const docState = this.getDocumentState(documentId);\n if (!(coreDoc == null ? void 0 : coreDoc.document) || !docState.selection) {\n return PdfTaskHelper.reject({\n code: PdfErrorCode.NotFound,\n message: \"Doc Not Found or No Selection\"\n });\n }\n const sel = docState.selection;\n const req = [];\n for (let p = sel.start.page; p <= sel.end.page; p++) {\n const s = docState.slices[p];\n if (s) req.push({ pageIndex: p, charIndex: s.start, charCount: s.count });\n }\n if (req.length === 0) return PdfTaskHelper.resolve([]);\n const task = this.engine.getTextSlices(coreDoc.document, req);\n task.wait((text) => {\n this.textRetrieved$.emit(documentId, text);\n }, ignore);\n return task;\n }\n copyToClipboard(documentId) {\n if (!this.checkPermission(documentId, PdfPermissionFlag.CopyContents)) {\n this.logger.debug(\n \"SelectionPlugin\",\n \"CopyToClipboard\",\n `Cannot copy to clipboard: document ${documentId} lacks CopyContents permission`\n );\n return;\n }\n const text = this.getSelectedText(documentId);\n text.wait((text2) => {\n this.copyToClipboard$.emit(documentId, text2.join(\"\\n\"));\n }, ignore);\n }\n /* ── marquee selection state updates ─────────────────────── */\n beginMarquee(documentId, pageIndex, _startPos, _modeId) {\n this.marqueePage.set(documentId, pageIndex);\n }\n updateMarquee(documentId, pageIndex, rect, modeId) {\n this.marqueeChange$.emit(documentId, { pageIndex, rect, modeId });\n }\n endMarquee(documentId, pageIndex, rect, modeId) {\n this.marqueeEnd$.emit(documentId, { pageIndex, rect, modeId });\n this.marqueeChange$.emit(documentId, { pageIndex, rect: null, modeId });\n this.marqueePage.delete(documentId);\n }\n cancelMarquee(documentId, modeId) {\n const pageIndex = this.marqueePage.get(documentId);\n if (pageIndex !== void 0) {\n this.marqueeChange$.emit(documentId, { pageIndex, rect: null, modeId });\n this.marqueePage.delete(documentId);\n }\n }\n /** @deprecated — shim for backward compat; delegates to pointerMode config */\n setMarqueeEnabled(documentId, enabled) {\n const modes = this.enabledModesPerDoc.get(documentId);\n if (!modes) return;\n const current = modes.get(\"pointerMode\");\n if (current) {\n current.enableMarquee = enabled;\n } else if (enabled) {\n modes.set(\"pointerMode\", { enableMarquee: true });\n }\n }\n /** @deprecated — shim for backward compat; reads pointerMode config */\n isMarqueeEnabled(documentId) {\n var _a;\n const config = (_a = this.enabledModesPerDoc.get(documentId)) == null ? void 0 : _a.get(\"pointerMode\");\n return (config == null ? void 0 : config.enableMarquee) !== false;\n }\n};\n_SelectionPlugin.id = \"selection\";\nlet SelectionPlugin = _SelectionPlugin;\nconst SelectionPluginPackage = {\n manifest,\n create: (registry, config) => new SelectionPlugin(SELECTION_PLUGIN_ID, registry, config),\n reducer: selectionReducer,\n initialState\n};\nexport {\n SELECTION_PLUGIN_ID,\n SelectionPlugin,\n SelectionPluginPackage,\n expandToLineBoundary,\n expandToWordBoundary,\n getVerticalOverlap,\n glyphAt,\n manifest,\n mergeAdjacentRects,\n rectIntersect,\n rectIsEmpty,\n rectUnion,\n rectsWithinSlice,\n shouldMergeHorizontalRects,\n sliceBounds\n};\n//# sourceMappingURL=index.js.map\n","function getCounterRotation(rect, rotation) {\n const { width: w, height: h } = rect.size;\n switch (rotation % 4) {\n case 1:\n return {\n matrix: `matrix(0, -1, 1, 0, 0, ${h})`,\n width: h,\n height: w\n };\n case 2:\n return {\n matrix: `matrix(-1, 0, 0, -1, ${w}, ${h})`,\n width: w,\n height: h\n };\n case 3:\n return {\n matrix: `matrix(0, 1, -1, 0, ${w}, 0)`,\n width: h,\n height: w\n };\n default:\n return {\n matrix: `matrix(1, 0, 0, 1, 0, 0)`,\n width: w,\n height: h\n };\n }\n}\nexport {\n getCounterRotation\n};\n//# sourceMappingURL=index.js.map\n","import { jsx } from \"react/jsx-runtime\";\nimport { getCounterRotation } from \"@embedpdf/utils\";\nimport { useRef, useEffect, Fragment, useCallback, useMemo } from \"react\";\nimport { rotatePointAround, calculateRotatedRectAABB, normalizeAngle } from \"@embedpdf/models\";\nconst dblClickProp = \"onDoubleClick\";\nfunction CounterRotate({ children, ...props }) {\n const { rect, rotation } = props;\n const { matrix, width, height } = getCounterRotation(rect, rotation);\n const elementRef = useRef(null);\n useEffect(() => {\n const element = elementRef.current;\n if (!element) return;\n const handlePointerDown = (e) => {\n e.stopPropagation();\n };\n const handleTouchStart = (e) => {\n e.stopPropagation();\n };\n element.addEventListener(\"pointerdown\", handlePointerDown, { capture: true });\n element.addEventListener(\"touchstart\", handleTouchStart, { capture: true, passive: true });\n return () => {\n element.removeEventListener(\"pointerdown\", handlePointerDown, { capture: true });\n element.removeEventListener(\"touchstart\", handleTouchStart, { capture: true });\n };\n }, []);\n const menuWrapperStyle = {\n position: \"absolute\",\n left: rect.origin.x,\n top: rect.origin.y,\n transform: matrix,\n transformOrigin: \"0 0\",\n width,\n height,\n pointerEvents: \"none\",\n zIndex: 3\n };\n const menuWrapperProps = {\n style: menuWrapperStyle,\n ref: (el) => {\n elementRef.current = el;\n }\n };\n return /* @__PURE__ */ jsx(Fragment, { children: children({\n menuWrapperProps,\n matrix,\n rect: {\n origin: { x: rect.origin.x, y: rect.origin.y },\n size: { width, height }\n }\n }) });\n}\nfunction getAnchor(handle) {\n return {\n x: handle.includes(\"e\") ? \"left\" : handle.includes(\"w\") ? \"right\" : \"center\",\n y: handle.includes(\"s\") ? \"top\" : handle.includes(\"n\") ? \"bottom\" : \"center\"\n };\n}\nfunction getAnchorPoint(rect, anchor) {\n const x = anchor.x === \"left\" ? rect.origin.x : anchor.x === \"right\" ? rect.origin.x + rect.size.width : rect.origin.x + rect.size.width / 2;\n const y = anchor.y === \"top\" ? rect.origin.y : anchor.y === \"bottom\" ? rect.origin.y + rect.size.height : rect.origin.y + rect.size.height / 2;\n return { x, y };\n}\nfunction applyResizeDelta(startRect, delta, anchor) {\n let x = startRect.origin.x;\n let y = startRect.origin.y;\n let width = startRect.size.width;\n let height = startRect.size.height;\n if (anchor.x === \"left\") {\n width += delta.x;\n } else if (anchor.x === \"right\") {\n x += delta.x;\n width -= delta.x;\n }\n if (anchor.y === \"top\") {\n height += delta.y;\n } else if (anchor.y === \"bottom\") {\n y += delta.y;\n height -= delta.y;\n }\n return { origin: { x, y }, size: { width, height } };\n}\nfunction enforceAspectRatio(rect, startRect, anchor, aspectRatio) {\n let { x, y } = rect.origin;\n let { width, height } = rect.size;\n const isEdgeHandle = anchor.x === \"center\" || anchor.y === \"center\";\n if (isEdgeHandle) {\n if (anchor.y === \"center\") {\n height = width / aspectRatio;\n y = startRect.origin.y + (startRect.size.height - height) / 2;\n } else {\n width = height * aspectRatio;\n x = startRect.origin.x + (startRect.size.width - width) / 2;\n }\n } else {\n const dw = Math.abs(width - startRect.size.width);\n const dh = Math.abs(height - startRect.size.height);\n const total = dw + dh;\n if (total === 0) {\n width = startRect.size.width;\n height = startRect.size.height;\n } else {\n const wWeight = dw / total;\n const hWeight = dh / total;\n const wFromW = width;\n const hFromW = width / aspectRatio;\n const wFromH = height * aspectRatio;\n const hFromH = height;\n width = wWeight * wFromW + hWeight * wFromH;\n height = wWeight * hFromW + hWeight * hFromH;\n }\n }\n if (anchor.x === \"right\") {\n x = startRect.origin.x + startRect.size.width - width;\n }\n if (anchor.y === \"bottom\") {\n y = startRect.origin.y + startRect.size.height - height;\n }\n return { origin: { x, y }, size: { width, height } };\n}\nfunction clampToBounds(rect, startRect, anchor, bbox, maintainAspectRatio) {\n if (!bbox) return rect;\n let { x, y } = rect.origin;\n let { width, height } = rect.size;\n width = Math.max(1, width);\n height = Math.max(1, height);\n const anchorX = anchor.x === \"left\" ? startRect.origin.x : startRect.origin.x + startRect.size.width;\n const anchorY = anchor.y === \"top\" ? startRect.origin.y : startRect.origin.y + startRect.size.height;\n const maxW = anchor.x === \"left\" ? bbox.width - anchorX : anchor.x === \"right\" ? anchorX : Math.min(startRect.origin.x, bbox.width - startRect.origin.x - startRect.size.width) * 2 + startRect.size.width;\n const maxH = anchor.y === \"top\" ? bbox.height - anchorY : anchor.y === \"bottom\" ? anchorY : Math.min(startRect.origin.y, bbox.height - startRect.origin.y - startRect.size.height) * 2 + startRect.size.height;\n if (maintainAspectRatio) {\n const scaleW = width > maxW ? maxW / width : 1;\n const scaleH = height > maxH ? maxH / height : 1;\n const scale = Math.min(scaleW, scaleH);\n if (scale < 1) {\n width *= scale;\n height *= scale;\n }\n } else {\n width = Math.min(width, maxW);\n height = Math.min(height, maxH);\n }\n if (anchor.x === \"left\") {\n x = anchorX;\n } else if (anchor.x === \"right\") {\n x = anchorX - width;\n } else {\n x = startRect.origin.x + (startRect.size.width - width) / 2;\n }\n if (anchor.y === \"top\") {\n y = anchorY;\n } else if (anchor.y === \"bottom\") {\n y = anchorY - height;\n } else {\n y = startRect.origin.y + (startRect.size.height - height) / 2;\n }\n x = Math.max(0, Math.min(x, bbox.width - width));\n y = Math.max(0, Math.min(y, bbox.height - height));\n return { origin: { x, y }, size: { width, height } };\n}\nfunction reanchorRect(rect, startRect, anchor) {\n let x;\n let y;\n if (anchor.x === \"left\") {\n x = startRect.origin.x;\n } else if (anchor.x === \"right\") {\n x = startRect.origin.x + startRect.size.width - rect.size.width;\n } else {\n x = startRect.origin.x + (startRect.size.width - rect.size.width) / 2;\n }\n if (anchor.y === \"top\") {\n y = startRect.origin.y;\n } else if (anchor.y === \"bottom\") {\n y = startRect.origin.y + startRect.size.height - rect.size.height;\n } else {\n y = startRect.origin.y + (startRect.size.height - rect.size.height) / 2;\n }\n return { origin: { x, y }, size: rect.size };\n}\nfunction applyConstraints(position, constraints, maintainAspectRatio, skipBoundingClamp = false) {\n if (!constraints) return position;\n let {\n origin: { x, y },\n size: { width, height }\n } = position;\n const minW = constraints.minWidth ?? 1;\n const minH = constraints.minHeight ?? 1;\n const maxW = constraints.maxWidth;\n const maxH = constraints.maxHeight;\n if (maintainAspectRatio && width > 0 && height > 0) {\n const ratio = width / height;\n if (width < minW) {\n width = minW;\n height = width / ratio;\n }\n if (height < minH) {\n height = minH;\n width = height * ratio;\n }\n if (maxW !== void 0 && width > maxW) {\n width = maxW;\n height = width / ratio;\n }\n if (maxH !== void 0 && height > maxH) {\n height = maxH;\n width = height * ratio;\n }\n } else {\n width = Math.max(minW, width);\n height = Math.max(minH, height);\n if (maxW !== void 0) width = Math.min(maxW, width);\n if (maxH !== void 0) height = Math.min(maxH, height);\n }\n if (constraints.boundingBox && !skipBoundingClamp) {\n x = Math.max(0, Math.min(x, constraints.boundingBox.width - width));\n y = Math.max(0, Math.min(y, constraints.boundingBox.height - height));\n }\n return { origin: { x, y }, size: { width, height } };\n}\nfunction isRectWithinRotatedBounds(rect, angleDegrees, bbox) {\n const eps = 1e-6;\n const aabb = calculateRotatedRectAABB(rect, angleDegrees);\n return aabb.origin.x >= -eps && aabb.origin.y >= -eps && aabb.origin.x + aabb.size.width <= bbox.width + eps && aabb.origin.y + aabb.size.height <= bbox.height + eps;\n}\nfunction computeResizeStep(delta, handle, config, clampLocalBounds, skipConstraintBoundingClamp) {\n const { startRect, maintainAspectRatio = false, annotationRotation = 0, constraints } = config;\n const anchor = getAnchor(handle);\n const aspectRatio = startRect.size.width / startRect.size.height || 1;\n let rect = applyResizeDelta(startRect, delta, anchor);\n if (maintainAspectRatio) {\n rect = enforceAspectRatio(rect, startRect, anchor, aspectRatio);\n }\n if (clampLocalBounds) {\n rect = clampToBounds(rect, startRect, anchor, constraints == null ? void 0 : constraints.boundingBox, maintainAspectRatio);\n }\n rect = applyConstraints(rect, constraints, maintainAspectRatio, skipConstraintBoundingClamp);\n if (skipConstraintBoundingClamp) {\n rect = reanchorRect(rect, startRect, anchor);\n }\n if (annotationRotation !== 0) {\n const anchorPt = getAnchorPoint(startRect, anchor);\n const oldCenter = {\n x: startRect.origin.x + startRect.size.width / 2,\n y: startRect.origin.y + startRect.size.height / 2\n };\n const newCenter = {\n x: rect.origin.x + rect.size.width / 2,\n y: rect.origin.y + rect.size.height / 2\n };\n const oldVisual = rotatePointAround(anchorPt, oldCenter, annotationRotation);\n const newVisual = rotatePointAround(anchorPt, newCenter, annotationRotation);\n rect = {\n origin: {\n x: rect.origin.x + (oldVisual.x - newVisual.x),\n y: rect.origin.y + (oldVisual.y - newVisual.y)\n },\n size: rect.size\n };\n }\n return rect;\n}\nfunction computeResizedRect(delta, handle, config) {\n const { annotationRotation = 0, constraints } = config;\n const bbox = constraints == null ? void 0 : constraints.boundingBox;\n if (annotationRotation !== 0 && bbox) {\n const target = computeResizeStep(delta, handle, config, false, true);\n if (isRectWithinRotatedBounds(target, annotationRotation, bbox)) {\n return target;\n }\n let best = computeResizeStep({ x: 0, y: 0 }, handle, config, false, true);\n let low = 0;\n let high = 1;\n for (let i = 0; i < 20; i += 1) {\n const mid = (low + high) / 2;\n const trial = computeResizeStep(\n { x: delta.x * mid, y: delta.y * mid },\n handle,\n config,\n false,\n true\n );\n if (isRectWithinRotatedBounds(trial, annotationRotation, bbox)) {\n best = trial;\n low = mid;\n } else {\n high = mid;\n }\n }\n return best;\n }\n return computeResizeStep(delta, handle, config, true, false);\n}\nconst ROTATION_HANDLE_MARGIN = 35;\nconst HANDLE_BASE_ANGLE = {\n n: 0,\n ne: 45,\n e: 90,\n se: 135,\n s: 180,\n sw: 225,\n w: 270,\n nw: 315\n};\nconst SECTOR_CURSORS = [\n \"ns-resize\",\n // 0: north\n \"nesw-resize\",\n // 1: NE\n \"ew-resize\",\n // 2: east\n \"nwse-resize\",\n // 3: SE\n \"ns-resize\",\n // 4: south\n \"nesw-resize\",\n // 5: SW\n \"ew-resize\",\n // 6: west\n \"nwse-resize\"\n // 7: NW\n];\nfunction diagonalCursor(handle, pageQuarterTurns, annotationRotation = 0) {\n const pageAngle = pageQuarterTurns * 90;\n const totalAngle = HANDLE_BASE_ANGLE[handle] + pageAngle + annotationRotation;\n const normalized = (totalAngle % 360 + 360) % 360;\n const sector = Math.round(normalized / 45) % 8;\n return SECTOR_CURSORS[sector];\n}\nfunction edgeOffset(k, spacing, mode) {\n const base = -k / 2;\n if (mode === \"center\") return base;\n return mode === \"outside\" ? base - spacing : base + spacing;\n}\nfunction describeResizeFromConfig(cfg, ui = {}) {\n const {\n handleSize = 8,\n spacing = 1,\n offsetMode = \"outside\",\n includeSides = false,\n zIndex = 3,\n rotationAwareCursor = true\n } = ui;\n const pageQuarterTurns = (cfg.pageRotation ?? 0) % 4;\n const annotationRot = cfg.annotationRotation ?? 0;\n const off = (edge) => ({\n [edge]: edgeOffset(handleSize, spacing, offsetMode) + \"px\"\n });\n const corners = [\n [\"nw\", { ...off(\"top\"), ...off(\"left\") }],\n [\"ne\", { ...off(\"top\"), ...off(\"right\") }],\n [\"sw\", { ...off(\"bottom\"), ...off(\"left\") }],\n [\"se\", { ...off(\"bottom\"), ...off(\"right\") }]\n ];\n const sides = includeSides ? [\n [\"n\", { ...off(\"top\"), left: `calc(50% - ${handleSize / 2}px)` }],\n [\"s\", { ...off(\"bottom\"), left: `calc(50% - ${handleSize / 2}px)` }],\n [\"w\", { ...off(\"left\"), top: `calc(50% - ${handleSize / 2}px)` }],\n [\"e\", { ...off(\"right\"), top: `calc(50% - ${handleSize / 2}px)` }]\n ] : [];\n const all = [...corners, ...sides];\n return all.map(([handle, pos]) => ({\n handle,\n style: {\n position: \"absolute\",\n width: handleSize + \"px\",\n height: handleSize + \"px\",\n borderRadius: \"50%\",\n zIndex,\n cursor: rotationAwareCursor ? diagonalCursor(handle, pageQuarterTurns, annotationRot) : \"default\",\n pointerEvents: \"auto\",\n touchAction: \"none\",\n ...pos\n },\n attrs: { \"data-epdf-handle\": handle }\n }));\n}\nfunction describeVerticesFromConfig(cfg, ui = {}, liveVertices) {\n const { vertexSize = 12, zIndex = 4 } = ui;\n const rect = cfg.element;\n const scale = cfg.scale ?? 1;\n const verts = liveVertices ?? cfg.vertices ?? [];\n return verts.map((v, i) => {\n const left = (v.x - rect.origin.x) * scale - vertexSize / 2;\n const top = (v.y - rect.origin.y) * scale - vertexSize / 2;\n return {\n handle: \"nw\",\n // not used; kept for type\n style: {\n position: \"absolute\",\n left: left + \"px\",\n top: top + \"px\",\n width: vertexSize + \"px\",\n height: vertexSize + \"px\",\n borderRadius: \"50%\",\n cursor: \"pointer\",\n zIndex,\n pointerEvents: \"auto\",\n touchAction: \"none\"\n },\n attrs: { \"data-epdf-vertex\": i }\n };\n });\n}\nfunction describeRotationFromConfig(cfg, ui = {}, currentAngle = 0) {\n const { handleSize = 16, zIndex = 5, showConnector = true, connectorWidth = 1 } = ui;\n const scale = cfg.scale ?? 1;\n const rect = cfg.element;\n const orbitRect = cfg.rotationElement ?? rect;\n const orbitCenter = cfg.rotationCenter ?? {\n x: rect.origin.x + rect.size.width / 2,\n y: rect.origin.y + rect.size.height / 2\n };\n orbitRect.size.width * scale;\n orbitRect.size.height * scale;\n const centerX = (orbitCenter.x - orbitRect.origin.x) * scale;\n const centerY = (orbitCenter.y - orbitRect.origin.y) * scale;\n const angleRad = currentAngle * Math.PI / 180;\n const margin = ui.margin ?? ROTATION_HANDLE_MARGIN;\n const radius = rect.size.height * scale / 2 + margin;\n const handleCenterX = centerX + radius * Math.sin(angleRad);\n const handleCenterY = centerY - radius * Math.cos(angleRad);\n const handleLeft = handleCenterX - handleSize / 2;\n const handleTop = handleCenterY - handleSize / 2;\n return {\n handleStyle: {\n position: \"absolute\",\n left: handleLeft + \"px\",\n top: handleTop + \"px\",\n width: handleSize + \"px\",\n height: handleSize + \"px\",\n borderRadius: \"50%\",\n cursor: \"grab\",\n zIndex,\n pointerEvents: \"auto\",\n touchAction: \"none\"\n },\n connectorStyle: showConnector ? {\n position: \"absolute\",\n left: centerX - connectorWidth / 2 + \"px\",\n top: centerY - radius + \"px\",\n width: connectorWidth + \"px\",\n height: radius + \"px\",\n transformOrigin: \"center bottom\",\n transform: `rotate(${currentAngle}deg)`,\n zIndex: zIndex - 1,\n pointerEvents: \"none\"\n } : {},\n radius,\n attrs: { \"data-epdf-rotation-handle\": true }\n };\n}\nclass DragResizeController {\n constructor(config, onUpdate) {\n this.config = config;\n this.onUpdate = onUpdate;\n this.state = \"idle\";\n this.startPoint = null;\n this.startElement = null;\n this.startRotationElement = null;\n this.gestureRotationCenter = null;\n this.activeHandle = null;\n this.currentPosition = null;\n this.activeVertexIndex = null;\n this.startVertices = [];\n this.currentVertices = [];\n this.rotationCenter = null;\n this.centerScreen = null;\n this.initialRotation = 0;\n this.lastComputedRotation = 0;\n this.rotationDelta = 0;\n this.rotationSnappedAngle = null;\n this.currentVertices = config.vertices || [];\n }\n updateConfig(config) {\n this.config = { ...this.config, ...config };\n if (this.state !== \"vertex-editing\") {\n this.currentVertices = config.vertices || [];\n }\n }\n // ---------------------------------------------------------------------------\n // Gesture start\n // ---------------------------------------------------------------------------\n startDrag(clientX, clientY) {\n this.state = \"dragging\";\n this.startPoint = { x: clientX, y: clientY };\n this.startElement = { ...this.config.element };\n this.startRotationElement = this.config.rotationElement ? { ...this.config.rotationElement } : null;\n this.currentPosition = { ...this.config.element };\n this.onUpdate({\n state: \"start\",\n transformData: {\n type: \"move\",\n changes: { rect: this.startElement }\n }\n });\n }\n startResize(handle, clientX, clientY) {\n this.state = \"resizing\";\n this.activeHandle = handle;\n this.startPoint = { x: clientX, y: clientY };\n this.startElement = { ...this.config.element };\n this.currentPosition = { ...this.config.element };\n this.onUpdate({\n state: \"start\",\n transformData: {\n type: \"resize\",\n changes: { rect: this.startElement },\n metadata: {\n handle: this.activeHandle,\n maintainAspectRatio: this.config.maintainAspectRatio\n }\n }\n });\n }\n startVertexEdit(vertexIndex, clientX, clientY) {\n this.currentVertices = [...this.config.vertices ?? this.currentVertices];\n if (vertexIndex < 0 || vertexIndex >= this.currentVertices.length) return;\n this.state = \"vertex-editing\";\n this.activeVertexIndex = vertexIndex;\n this.startPoint = { x: clientX, y: clientY };\n this.startVertices = [...this.currentVertices];\n this.gestureRotationCenter = this.config.rotationCenter ?? {\n x: this.config.element.origin.x + this.config.element.size.width / 2,\n y: this.config.element.origin.y + this.config.element.size.height / 2\n };\n this.onUpdate({\n state: \"start\",\n transformData: {\n type: \"vertex-edit\",\n changes: { vertices: this.startVertices },\n metadata: { vertexIndex }\n }\n });\n }\n startRotation(clientX, clientY, initialRotation = 0, orbitRadiusPx) {\n this.state = \"rotating\";\n this.startPoint = { x: clientX, y: clientY };\n this.startElement = { ...this.config.element };\n this.rotationCenter = this.config.rotationCenter ?? {\n x: this.config.element.origin.x + this.config.element.size.width / 2,\n y: this.config.element.origin.y + this.config.element.size.height / 2\n };\n const { scale = 1 } = this.config;\n const orbitRect = this.config.rotationElement ?? this.config.element;\n const sw = orbitRect.size.width * scale;\n const sh = orbitRect.size.height * scale;\n const radius = orbitRadiusPx ?? Math.max(sw, sh) / 2 + ROTATION_HANDLE_MARGIN;\n const pageRotOffset = (this.config.pageRotation ?? 0) * 90;\n const screenAngleRad = (initialRotation + pageRotOffset) * Math.PI / 180;\n this.centerScreen = {\n x: clientX - radius * Math.sin(screenAngleRad),\n y: clientY + radius * Math.cos(screenAngleRad)\n };\n this.initialRotation = initialRotation;\n this.lastComputedRotation = initialRotation;\n this.rotationDelta = 0;\n this.rotationSnappedAngle = null;\n this.onUpdate({\n state: \"start\",\n transformData: {\n type: \"rotate\",\n changes: { rotation: initialRotation },\n metadata: {\n rotationAngle: initialRotation,\n rotationDelta: 0,\n rotationCenter: this.rotationCenter,\n isSnapped: false\n }\n }\n });\n }\n // ---------------------------------------------------------------------------\n // Gesture move\n // ---------------------------------------------------------------------------\n move(clientX, clientY, buttons, lockAspectRatio) {\n if (this.state === \"idle\" || !this.startPoint) return;\n if (buttons !== void 0 && buttons === 0) {\n this.end();\n return;\n }\n if (this.state === \"dragging\" && this.startElement) {\n const delta = this.calculateDelta(clientX, clientY);\n const position = this.calculateDragPosition(delta);\n this.currentPosition = position;\n this.onUpdate({\n state: \"move\",\n transformData: { type: \"move\", changes: { rect: position } }\n });\n } else if (this.state === \"resizing\" && this.activeHandle && this.startElement) {\n const delta = this.calculateLocalDelta(clientX, clientY);\n const position = computeResizedRect(delta, this.activeHandle, {\n startRect: this.startElement,\n maintainAspectRatio: this.config.maintainAspectRatio || !!lockAspectRatio,\n annotationRotation: this.config.annotationRotation,\n constraints: this.config.constraints\n });\n this.currentPosition = position;\n this.onUpdate({\n state: \"move\",\n transformData: {\n type: \"resize\",\n changes: { rect: position },\n metadata: {\n handle: this.activeHandle,\n maintainAspectRatio: this.config.maintainAspectRatio || !!lockAspectRatio\n }\n }\n });\n } else if (this.state === \"vertex-editing\" && this.activeVertexIndex !== null) {\n const vertices = this.calculateVertexPosition(clientX, clientY);\n this.currentVertices = vertices;\n this.onUpdate({\n state: \"move\",\n transformData: {\n type: \"vertex-edit\",\n changes: { vertices },\n metadata: { vertexIndex: this.activeVertexIndex }\n }\n });\n } else if (this.state === \"rotating\" && this.rotationCenter) {\n const absoluteAngle = this.calculateAngleFromMouse(clientX, clientY);\n const snapResult = this.applyRotationSnapping(absoluteAngle);\n const snappedAngle = normalizeAngle(snapResult.angle);\n const previousAngle = this.lastComputedRotation;\n const rawDelta = snappedAngle - previousAngle;\n const adjustedDelta = rawDelta > 180 ? rawDelta - 360 : rawDelta < -180 ? rawDelta + 360 : rawDelta;\n this.rotationDelta += adjustedDelta;\n this.lastComputedRotation = snappedAngle;\n this.rotationSnappedAngle = snapResult.isSnapped ? snappedAngle : null;\n this.onUpdate({\n state: \"move\",\n transformData: {\n type: \"rotate\",\n changes: { rotation: snappedAngle },\n metadata: {\n rotationAngle: snappedAngle,\n rotationDelta: this.rotationDelta,\n rotationCenter: this.rotationCenter,\n isSnapped: snapResult.isSnapped,\n snappedAngle: this.rotationSnappedAngle ?? void 0,\n cursorPosition: { clientX, clientY }\n }\n }\n });\n }\n }\n // ---------------------------------------------------------------------------\n // Gesture end / cancel\n // ---------------------------------------------------------------------------\n end() {\n if (this.state === \"idle\") return;\n const wasState = this.state;\n const handle = this.activeHandle;\n const vertexIndex = this.activeVertexIndex;\n if (wasState === \"vertex-editing\") {\n this.onUpdate({\n state: \"end\",\n transformData: {\n type: \"vertex-edit\",\n changes: { vertices: this.currentVertices },\n metadata: { vertexIndex: vertexIndex || void 0 }\n }\n });\n } else if (wasState === \"rotating\") {\n this.onUpdate({\n state: \"end\",\n transformData: {\n type: \"rotate\",\n changes: { rotation: this.lastComputedRotation },\n metadata: {\n rotationAngle: this.lastComputedRotation,\n rotationDelta: this.rotationDelta,\n rotationCenter: this.rotationCenter || void 0,\n isSnapped: this.rotationSnappedAngle !== null,\n snappedAngle: this.rotationSnappedAngle ?? void 0\n }\n }\n });\n } else {\n const finalPosition = this.currentPosition || this.config.element;\n this.onUpdate({\n state: \"end\",\n transformData: {\n type: wasState === \"dragging\" ? \"move\" : \"resize\",\n changes: { rect: finalPosition },\n metadata: wasState === \"dragging\" ? void 0 : {\n handle: handle || void 0,\n maintainAspectRatio: this.config.maintainAspectRatio\n }\n }\n });\n }\n this.reset();\n }\n cancel() {\n if (this.state === \"idle\") return;\n if (this.state === \"vertex-editing\") {\n this.onUpdate({\n state: \"end\",\n transformData: {\n type: \"vertex-edit\",\n changes: { vertices: this.startVertices },\n metadata: { vertexIndex: this.activeVertexIndex || void 0 }\n }\n });\n } else if (this.state === \"rotating\") {\n this.onUpdate({\n state: \"end\",\n transformData: {\n type: \"rotate\",\n changes: { rotation: this.initialRotation },\n metadata: {\n rotationAngle: this.initialRotation,\n rotationDelta: 0,\n rotationCenter: this.rotationCenter || void 0,\n isSnapped: false\n }\n }\n });\n } else if (this.startElement) {\n this.onUpdate({\n state: \"end\",\n transformData: {\n type: this.state === \"dragging\" ? \"move\" : \"resize\",\n changes: { rect: this.startElement },\n metadata: this.state === \"dragging\" ? void 0 : {\n handle: this.activeHandle || void 0,\n maintainAspectRatio: this.config.maintainAspectRatio\n }\n }\n });\n }\n this.reset();\n }\n // ---------------------------------------------------------------------------\n // Private: state management\n // ---------------------------------------------------------------------------\n reset() {\n this.state = \"idle\";\n this.startPoint = null;\n this.startElement = null;\n this.startRotationElement = null;\n this.gestureRotationCenter = null;\n this.activeHandle = null;\n this.currentPosition = null;\n this.activeVertexIndex = null;\n this.startVertices = [];\n this.rotationCenter = null;\n this.centerScreen = null;\n this.initialRotation = 0;\n this.lastComputedRotation = 0;\n this.rotationDelta = 0;\n this.rotationSnappedAngle = null;\n }\n // ---------------------------------------------------------------------------\n // Private: coordinate transformation (screen → page → local)\n // ---------------------------------------------------------------------------\n calculateDelta(clientX, clientY) {\n if (!this.startPoint) return { x: 0, y: 0 };\n const rawDelta = {\n x: clientX - this.startPoint.x,\n y: clientY - this.startPoint.y\n };\n return this.transformDelta(rawDelta);\n }\n transformDelta(delta) {\n const { pageRotation = 0, scale = 1 } = this.config;\n const rad = pageRotation * Math.PI / 2;\n const cos = Math.cos(rad);\n const sin = Math.sin(rad);\n const scaledX = delta.x / scale;\n const scaledY = delta.y / scale;\n return {\n x: cos * scaledX + sin * scaledY,\n y: -sin * scaledX + cos * scaledY\n };\n }\n /**\n * Calculate delta projected into the annotation's local (unrotated) coordinate space.\n * Used for resize and vertex-edit where mouse movement must be mapped to the\n * annotation's own axes, accounting for its rotation.\n */\n calculateLocalDelta(clientX, clientY) {\n const pageDelta = this.calculateDelta(clientX, clientY);\n const { annotationRotation = 0 } = this.config;\n if (annotationRotation === 0) return pageDelta;\n const rad = annotationRotation * Math.PI / 180;\n const cos = Math.cos(rad);\n const sin = Math.sin(rad);\n return {\n x: cos * pageDelta.x + sin * pageDelta.y,\n y: -sin * pageDelta.x + cos * pageDelta.y\n };\n }\n // ---------------------------------------------------------------------------\n // Private: vertex clamping\n // ---------------------------------------------------------------------------\n clampPoint(p) {\n var _a;\n const bbox = (_a = this.config.constraints) == null ? void 0 : _a.boundingBox;\n if (!bbox) return p;\n const { annotationRotation = 0 } = this.config;\n if (annotationRotation === 0) {\n return {\n x: Math.max(0, Math.min(p.x, bbox.width)),\n y: Math.max(0, Math.min(p.y, bbox.height))\n };\n }\n const center = this.gestureRotationCenter ?? this.config.rotationCenter ?? {\n x: this.config.element.origin.x + this.config.element.size.width / 2,\n y: this.config.element.origin.y + this.config.element.size.height / 2\n };\n const visual = rotatePointAround(p, center, annotationRotation);\n const clampedX = Math.max(0, Math.min(visual.x, bbox.width));\n const clampedY = Math.max(0, Math.min(visual.y, bbox.height));\n if (clampedX === visual.x && clampedY === visual.y) return p;\n return rotatePointAround({ x: clampedX, y: clampedY }, center, -annotationRotation);\n }\n calculateVertexPosition(clientX, clientY) {\n if (this.activeVertexIndex === null) return this.startVertices;\n const delta = this.calculateLocalDelta(clientX, clientY);\n const newVertices = [...this.startVertices];\n const currentVertex = newVertices[this.activeVertexIndex];\n const moved = {\n x: currentVertex.x + delta.x,\n y: currentVertex.y + delta.y\n };\n newVertices[this.activeVertexIndex] = this.clampPoint(moved);\n return newVertices;\n }\n // ---------------------------------------------------------------------------\n // Private: drag position\n // ---------------------------------------------------------------------------\n calculateDragPosition(delta) {\n if (!this.startElement) return this.config.element;\n const position = {\n origin: {\n x: this.startElement.origin.x + delta.x,\n y: this.startElement.origin.y + delta.y\n },\n size: {\n width: this.startElement.size.width,\n height: this.startElement.size.height\n }\n };\n const { annotationRotation = 0, constraints } = this.config;\n const bbox = constraints == null ? void 0 : constraints.boundingBox;\n if (annotationRotation !== 0 && bbox) {\n let aabbW;\n let aabbH;\n let offsetX;\n let offsetY;\n if (this.startRotationElement) {\n aabbW = this.startRotationElement.size.width;\n aabbH = this.startRotationElement.size.height;\n offsetX = this.startRotationElement.origin.x - this.startElement.origin.x;\n offsetY = this.startRotationElement.origin.y - this.startElement.origin.y;\n } else {\n const rad = Math.abs(annotationRotation * Math.PI / 180);\n const cos = Math.abs(Math.cos(rad));\n const sin = Math.abs(Math.sin(rad));\n const w = position.size.width;\n const h = position.size.height;\n aabbW = w * cos + h * sin;\n aabbH = w * sin + h * cos;\n offsetX = (w - aabbW) / 2;\n offsetY = (h - aabbH) / 2;\n }\n let { x, y } = position.origin;\n x = Math.max(-offsetX, Math.min(x, bbox.width - aabbW - offsetX));\n y = Math.max(-offsetY, Math.min(y, bbox.height - aabbH - offsetY));\n return { origin: { x, y }, size: position.size };\n }\n return applyConstraints(position, constraints, this.config.maintainAspectRatio ?? false);\n }\n // ---------------------------------------------------------------------------\n // Private: rotation\n // ---------------------------------------------------------------------------\n /**\n * Calculate the angle from the center to a point in screen coordinates.\n */\n calculateAngleFromMouse(clientX, clientY) {\n if (!this.centerScreen) return this.initialRotation;\n const dx = clientX - this.centerScreen.x;\n const dy = clientY - this.centerScreen.y;\n const dist = Math.sqrt(dx * dx + dy * dy);\n if (dist < 10) return this.lastComputedRotation;\n const pageRotOffset = (this.config.pageRotation ?? 0) * 90;\n const angleDeg = Math.atan2(dy, dx) * (180 / Math.PI) + 90 - pageRotOffset;\n return normalizeAngle(Math.round(angleDeg));\n }\n applyRotationSnapping(angle) {\n const snapAngles = this.config.rotationSnapAngles ?? [0, 90, 180, 270];\n const threshold = this.config.rotationSnapThreshold ?? 4;\n const normalizedAngle = normalizeAngle(angle);\n for (const candidate of snapAngles) {\n const normalizedCandidate = normalizeAngle(candidate);\n const diff = Math.abs(normalizedAngle - normalizedCandidate);\n const minimalDiff = Math.min(diff, 360 - diff);\n if (minimalDiff <= threshold) {\n return {\n angle: normalizedCandidate,\n isSnapped: true,\n snapTarget: normalizedCandidate\n };\n }\n }\n return { angle: normalizedAngle, isSnapped: false };\n }\n}\nfunction useDragResize(options) {\n const { onUpdate, enabled = true, ...config } = options;\n const controllerRef = useRef(null);\n const onUpdateRef = useRef(onUpdate);\n const activePointerIdRef = useRef(null);\n const activeTargetRef = useRef(null);\n useEffect(() => {\n onUpdateRef.current = onUpdate;\n }, [onUpdate]);\n useEffect(() => {\n if (!controllerRef.current) {\n controllerRef.current = new DragResizeController(\n config,\n (event) => {\n var _a;\n return (_a = onUpdateRef.current) == null ? void 0 : _a.call(onUpdateRef, event);\n }\n );\n } else {\n controllerRef.current.updateConfig(config);\n }\n }, [\n config.element,\n config.rotationCenter,\n config.rotationElement,\n config.constraints,\n config.maintainAspectRatio,\n config.pageRotation,\n config.annotationRotation,\n config.scale,\n config.vertices\n ]);\n const endPointerSession = useCallback((pointerId) => {\n var _a, _b;\n const activePointerId = activePointerIdRef.current;\n const target = activeTargetRef.current;\n const id = pointerId ?? activePointerId;\n if (target && id !== null) {\n try {\n if ((_a = target.hasPointerCapture) == null ? void 0 : _a.call(target, id)) {\n (_b = target.releasePointerCapture) == null ? void 0 : _b.call(target, id);\n }\n } catch {\n }\n }\n activePointerIdRef.current = null;\n activeTargetRef.current = null;\n }, []);\n const startPointerSession = useCallback(\n (e) => {\n var _a;\n if (activePointerIdRef.current !== null && activePointerIdRef.current !== e.pointerId) {\n (_a = controllerRef.current) == null ? void 0 : _a.end();\n endPointerSession(activePointerIdRef.current);\n }\n const target = e.currentTarget;\n activePointerIdRef.current = e.pointerId;\n activeTargetRef.current = target;\n try {\n target.setPointerCapture(e.pointerId);\n } catch {\n }\n },\n [endPointerSession]\n );\n useEffect(() => {\n const eventTarget = globalThis;\n const handleGlobalPointerEnd = (e) => {\n var _a;\n const activePointerId = activePointerIdRef.current;\n if (activePointerId === null || e.pointerId !== activePointerId) return;\n (_a = controllerRef.current) == null ? void 0 : _a.end();\n endPointerSession(e.pointerId);\n };\n const handleWindowBlur = () => {\n var _a;\n if (activePointerIdRef.current === null) return;\n (_a = controllerRef.current) == null ? void 0 : _a.end();\n endPointerSession();\n };\n eventTarget.addEventListener(\"pointerup\", handleGlobalPointerEnd, true);\n eventTarget.addEventListener(\"pointercancel\", handleGlobalPointerEnd, true);\n eventTarget.addEventListener(\"blur\", handleWindowBlur, true);\n return () => {\n eventTarget.removeEventListener(\"pointerup\", handleGlobalPointerEnd, true);\n eventTarget.removeEventListener(\"pointercancel\", handleGlobalPointerEnd, true);\n eventTarget.removeEventListener(\"blur\", handleWindowBlur, true);\n };\n }, [endPointerSession]);\n useEffect(() => {\n return () => {\n var _a;\n if (activePointerIdRef.current !== null) {\n (_a = controllerRef.current) == null ? void 0 : _a.end();\n endPointerSession();\n }\n };\n }, [endPointerSession]);\n const handleDragStart = useCallback(\n (e) => {\n var _a;\n if (!enabled) return;\n e.preventDefault();\n e.stopPropagation();\n (_a = controllerRef.current) == null ? void 0 : _a.startDrag(e.clientX, e.clientY);\n startPointerSession(e);\n },\n [enabled, startPointerSession]\n );\n const handleMove = useCallback(\n (e) => {\n var _a;\n e.preventDefault();\n e.stopPropagation();\n const activePointerId = activePointerIdRef.current;\n if (activePointerId !== null && e.pointerId !== activePointerId) return;\n (_a = controllerRef.current) == null ? void 0 : _a.move(e.clientX, e.clientY, e.buttons, e.shiftKey);\n if (activePointerIdRef.current === e.pointerId && e.buttons === 0) {\n endPointerSession(e.pointerId);\n }\n },\n [endPointerSession]\n );\n const handleEndLike = useCallback(\n (e) => {\n var _a;\n e.preventDefault();\n e.stopPropagation();\n const activePointerId = activePointerIdRef.current;\n if (activePointerId !== null && e.pointerId !== activePointerId) return;\n (_a = controllerRef.current) == null ? void 0 : _a.end();\n endPointerSession(e.pointerId);\n },\n [endPointerSession]\n );\n const handleLostPointerCapture = useCallback(\n (e) => {\n var _a;\n const activePointerId = activePointerIdRef.current;\n if (activePointerId === null || e.pointerId !== activePointerId) return;\n (_a = controllerRef.current) == null ? void 0 : _a.end();\n endPointerSession(e.pointerId);\n },\n [endPointerSession]\n );\n const createResizeHandler = useCallback(\n (handle) => ({\n onPointerDown: (e) => {\n var _a;\n if (!enabled) return;\n e.preventDefault();\n e.stopPropagation();\n (_a = controllerRef.current) == null ? void 0 : _a.startResize(handle, e.clientX, e.clientY);\n startPointerSession(e);\n },\n onPointerMove: handleMove,\n onPointerUp: handleEndLike,\n onPointerCancel: handleEndLike,\n onLostPointerCapture: handleLostPointerCapture\n }),\n [enabled, handleMove, handleEndLike, handleLostPointerCapture, startPointerSession]\n );\n const createVertexHandler = useCallback(\n (vertexIndex) => ({\n onPointerDown: (e) => {\n var _a;\n if (!enabled) return;\n e.preventDefault();\n e.stopPropagation();\n (_a = controllerRef.current) == null ? void 0 : _a.startVertexEdit(vertexIndex, e.clientX, e.clientY);\n startPointerSession(e);\n },\n onPointerMove: handleMove,\n onPointerUp: handleEndLike,\n onPointerCancel: handleEndLike,\n onLostPointerCapture: handleLostPointerCapture\n }),\n [enabled, handleMove, handleEndLike, handleLostPointerCapture, startPointerSession]\n );\n const createRotationHandler = useCallback(\n (initialRotation = 0, orbitRadiusPx) => ({\n onPointerDown: (e) => {\n var _a;\n if (!enabled) return;\n e.preventDefault();\n e.stopPropagation();\n const handleRect = e.currentTarget.getBoundingClientRect();\n const handleCenterX = handleRect.left + handleRect.width / 2;\n const handleCenterY = handleRect.top + handleRect.height / 2;\n (_a = controllerRef.current) == null ? void 0 : _a.startRotation(\n handleCenterX,\n handleCenterY,\n initialRotation,\n orbitRadiusPx\n );\n startPointerSession(e);\n },\n onPointerMove: handleMove,\n onPointerUp: handleEndLike,\n onPointerCancel: handleEndLike,\n onLostPointerCapture: handleLostPointerCapture\n }),\n [enabled, handleMove, handleEndLike, handleLostPointerCapture, startPointerSession]\n );\n return {\n dragProps: enabled ? {\n onPointerDown: handleDragStart,\n onPointerMove: handleMove,\n onPointerUp: handleEndLike,\n onPointerCancel: handleEndLike,\n onLostPointerCapture: handleLostPointerCapture\n } : {},\n createResizeProps: createResizeHandler,\n createVertexProps: createVertexHandler,\n createRotationProps: createRotationHandler\n };\n}\nfunction useInteractionHandles(opts) {\n var _a, _b, _c, _d, _e, _f;\n const {\n controller,\n resizeUI,\n vertexUI,\n rotationUI,\n includeVertices = false,\n includeRotation = false,\n currentRotation = 0,\n handleAttrs,\n vertexAttrs,\n rotationAttrs\n } = opts;\n const { dragProps, createResizeProps, createVertexProps, createRotationProps } = useDragResize(controller);\n const resize = useMemo(() => {\n const desc = describeResizeFromConfig(controller, resizeUI);\n return desc.map((d) => {\n var _a2;\n return {\n key: (_a2 = d.attrs) == null ? void 0 : _a2[\"data-epdf-handle\"],\n style: d.style,\n ...createResizeProps(d.handle),\n ...d.attrs ?? {},\n ...(handleAttrs == null ? void 0 : handleAttrs(d.handle)) ?? {}\n };\n });\n }, [\n controller.element.origin.x,\n controller.element.origin.y,\n controller.element.size.width,\n controller.element.size.height,\n controller.scale,\n controller.pageRotation,\n controller.annotationRotation,\n controller.maintainAspectRatio,\n resizeUI == null ? void 0 : resizeUI.handleSize,\n resizeUI == null ? void 0 : resizeUI.spacing,\n resizeUI == null ? void 0 : resizeUI.offsetMode,\n resizeUI == null ? void 0 : resizeUI.includeSides,\n resizeUI == null ? void 0 : resizeUI.zIndex,\n resizeUI == null ? void 0 : resizeUI.rotationAwareCursor,\n createResizeProps,\n handleAttrs\n ]);\n const vertices = useMemo(() => {\n if (!includeVertices) return [];\n const desc = describeVerticesFromConfig(controller, vertexUI, controller.vertices);\n return desc.map((d, i) => ({\n key: i,\n style: d.style,\n ...createVertexProps(i),\n ...d.attrs ?? {},\n ...(vertexAttrs == null ? void 0 : vertexAttrs(i)) ?? {}\n }));\n }, [\n includeVertices,\n controller.element.origin.x,\n controller.element.origin.y,\n controller.element.size.width,\n controller.element.size.height,\n controller.scale,\n controller.vertices,\n // identity/content drives recalculation\n vertexUI == null ? void 0 : vertexUI.vertexSize,\n vertexUI == null ? void 0 : vertexUI.zIndex,\n createVertexProps,\n vertexAttrs\n ]);\n const rotation = useMemo(() => {\n if (!includeRotation) return null;\n const desc = describeRotationFromConfig(controller, rotationUI, currentRotation);\n return {\n handle: {\n style: desc.handleStyle,\n ...createRotationProps(currentRotation, desc.radius),\n ...desc.attrs ?? {},\n ...(rotationAttrs == null ? void 0 : rotationAttrs()) ?? {}\n },\n connector: {\n style: desc.connectorStyle,\n \"data-epdf-rotation-connector\": true\n }\n };\n }, [\n includeRotation,\n controller.element.origin.x,\n controller.element.origin.y,\n controller.element.size.width,\n controller.element.size.height,\n (_a = controller.rotationCenter) == null ? void 0 : _a.x,\n (_b = controller.rotationCenter) == null ? void 0 : _b.y,\n (_c = controller.rotationElement) == null ? void 0 : _c.origin.x,\n (_d = controller.rotationElement) == null ? void 0 : _d.origin.y,\n (_e = controller.rotationElement) == null ? void 0 : _e.size.width,\n (_f = controller.rotationElement) == null ? void 0 : _f.size.height,\n controller.scale,\n currentRotation,\n rotationUI == null ? void 0 : rotationUI.handleSize,\n rotationUI == null ? void 0 : rotationUI.margin,\n rotationUI == null ? void 0 : rotationUI.zIndex,\n rotationUI == null ? void 0 : rotationUI.showConnector,\n rotationUI == null ? void 0 : rotationUI.connectorWidth,\n createRotationProps,\n rotationAttrs\n ]);\n return { dragProps, resize, vertices, rotation };\n}\nfunction useDoublePressProps(onDouble, { delay = 300, tolerancePx = 18 } = {}) {\n const last = useRef({ t: 0, x: 0, y: 0 });\n const handlePointerUp = useCallback(\n (e) => {\n if (!onDouble) return;\n if (e.pointerType === \"mouse\" || e.isPrimary === false) return;\n const now = performance.now();\n const x = e.clientX;\n const y = e.clientY;\n const withinTime = now - last.current.t <= delay;\n const dx = x - last.current.x;\n const dy = y - last.current.y;\n const withinDist = dx * dx + dy * dy <= tolerancePx * tolerancePx;\n if (withinTime && withinDist) onDouble == null ? void 0 : onDouble(e);\n last.current = { t: now, x, y };\n },\n [onDouble, delay, tolerancePx]\n );\n const handleDouble = useCallback(\n (e) => {\n onDouble == null ? void 0 : onDouble(e);\n },\n [onDouble]\n );\n return onDouble ? {\n // Computed property uses the framework’s name ('onDoubleClick' or 'onDblClick')\n [dblClickProp]: handleDouble,\n onPointerUpCapture: handlePointerUp\n } : {};\n}\nexport {\n CounterRotate,\n useDoublePressProps,\n useDragResize,\n useInteractionHandles\n};\n//# sourceMappingURL=index.js.map\n","import { createPluginPackage } from \"@embedpdf/core\";\nimport { SelectionPlugin, SelectionPluginPackage as SelectionPluginPackage$1 } from \"@embedpdf/plugin-selection\";\nexport * from \"@embedpdf/plugin-selection\";\nimport { jsxs, Fragment, jsx } from \"react/jsx-runtime\";\nimport { useState, useEffect, useMemo, Fragment as Fragment$1 } from \"react\";\nimport { useCapability, usePlugin, useDocumentState } from \"@embedpdf/core/react\";\nimport { CounterRotate } from \"@embedpdf/utils/react\";\nconst useSelectionCapability = () => useCapability(SelectionPlugin.id);\nconst useSelectionPlugin = () => usePlugin(SelectionPlugin.id);\nfunction TextSelection({\n documentId,\n pageIndex,\n scale: scaleOverride,\n rotation: rotationOverride,\n background = \"rgba(33,150,243)\",\n selectionMenu\n}) {\n var _a, _b;\n const { plugin: selPlugin } = useSelectionPlugin();\n const documentState = useDocumentState(documentId);\n const page = (_b = (_a = documentState == null ? void 0 : documentState.document) == null ? void 0 : _a.pages) == null ? void 0 : _b[pageIndex];\n const [rects, setRects] = useState([]);\n const [boundingRect, setBoundingRect] = useState(null);\n const [placement, setPlacement] = useState(null);\n useEffect(() => {\n if (!selPlugin || !documentId) return;\n return selPlugin.registerSelectionOnPage({\n documentId,\n pageIndex,\n onRectsChange: ({ rects: rects2, boundingRect: boundingRect2 }) => {\n setRects(rects2);\n setBoundingRect(boundingRect2);\n }\n });\n }, [selPlugin, documentId, pageIndex]);\n useEffect(() => {\n if (!selPlugin || !documentId) return;\n return selPlugin.onMenuPlacement(documentId, (newPlacement) => {\n setPlacement(newPlacement);\n });\n }, [selPlugin, documentId]);\n const actualScale = useMemo(() => {\n if (scaleOverride !== void 0) return scaleOverride;\n return (documentState == null ? void 0 : documentState.scale) ?? 1;\n }, [scaleOverride, documentState == null ? void 0 : documentState.scale]);\n const actualRotation = useMemo(() => {\n if (rotationOverride !== void 0) return rotationOverride;\n const pageRotation = (page == null ? void 0 : page.rotation) ?? 0;\n const docRotation = (documentState == null ? void 0 : documentState.rotation) ?? 0;\n return (pageRotation + docRotation) % 4;\n }, [rotationOverride, page == null ? void 0 : page.rotation, documentState == null ? void 0 : documentState.rotation]);\n const shouldRenderMenu = selectionMenu && placement && placement.pageIndex === pageIndex && placement.isVisible;\n if (!boundingRect) return null;\n return /* @__PURE__ */ jsxs(Fragment, { children: [\n /* @__PURE__ */ jsx(\n \"div\",\n {\n style: {\n position: \"absolute\",\n left: boundingRect.origin.x * actualScale,\n top: boundingRect.origin.y * actualScale,\n width: boundingRect.size.width * actualScale,\n height: boundingRect.size.height * actualScale,\n mixBlendMode: \"multiply\",\n isolation: \"isolate\",\n pointerEvents: \"none\"\n },\n children: rects.map((b, i) => /* @__PURE__ */ jsx(\n \"div\",\n {\n style: {\n position: \"absolute\",\n left: (b.origin.x - boundingRect.origin.x) * actualScale,\n top: (b.origin.y - boundingRect.origin.y) * actualScale,\n width: b.size.width * actualScale,\n height: b.size.height * actualScale,\n background\n }\n },\n i\n ))\n }\n ),\n shouldRenderMenu && /* @__PURE__ */ jsx(\n CounterRotate,\n {\n rect: {\n origin: {\n x: placement.rect.origin.x * actualScale,\n y: placement.rect.origin.y * actualScale\n },\n size: {\n width: placement.rect.size.width * actualScale,\n height: placement.rect.size.height * actualScale\n }\n },\n rotation: actualRotation,\n children: (props) => selectionMenu({\n ...props,\n context: {\n type: \"selection\",\n pageIndex\n },\n selected: true,\n placement\n })\n }\n )\n ] });\n}\nconst MarqueeSelection = ({\n documentId,\n pageIndex,\n scale,\n className,\n background,\n borderColor,\n borderStyle = \"dashed\",\n stroke,\n fill\n}) => {\n const { plugin: selPlugin } = useSelectionPlugin();\n const documentState = useDocumentState(documentId);\n const [rect, setRect] = useState(null);\n const resolvedBorderColor = borderColor ?? stroke ?? \"rgba(0,122,204,0.8)\";\n const resolvedBackground = background ?? fill ?? \"rgba(0,122,204,0.15)\";\n const actualScale = useMemo(() => {\n if (scale !== void 0) return scale;\n return (documentState == null ? void 0 : documentState.scale) ?? 1;\n }, [scale, documentState == null ? void 0 : documentState.scale]);\n useEffect(() => {\n if (!selPlugin || !documentId) return;\n return selPlugin.registerMarqueeOnPage({\n documentId,\n pageIndex,\n scale: actualScale,\n onRectChange: setRect\n });\n }, [selPlugin, documentId, pageIndex, actualScale]);\n if (!rect) return null;\n return /* @__PURE__ */ jsx(\n \"div\",\n {\n style: {\n position: \"absolute\",\n pointerEvents: \"none\",\n left: rect.origin.x * actualScale,\n top: rect.origin.y * actualScale,\n width: rect.size.width * actualScale,\n height: rect.size.height * actualScale,\n border: `1px ${borderStyle} ${resolvedBorderColor}`,\n background: resolvedBackground,\n boxSizing: \"border-box\",\n zIndex: 1e3\n },\n className\n }\n );\n};\nfunction SelectionLayer({\n documentId,\n pageIndex,\n scale,\n rotation,\n background,\n textStyle,\n marqueeStyle,\n marqueeClassName,\n selectionMenu\n}) {\n return /* @__PURE__ */ jsxs(Fragment$1, { children: [\n /* @__PURE__ */ jsx(\n TextSelection,\n {\n documentId,\n pageIndex,\n scale,\n rotation,\n background: (textStyle == null ? void 0 : textStyle.background) ?? background,\n selectionMenu\n }\n ),\n /* @__PURE__ */ jsx(\n MarqueeSelection,\n {\n documentId,\n pageIndex,\n scale,\n background: marqueeStyle == null ? void 0 : marqueeStyle.background,\n borderColor: marqueeStyle == null ? void 0 : marqueeStyle.borderColor,\n borderStyle: marqueeStyle == null ? void 0 : marqueeStyle.borderStyle,\n className: marqueeClassName\n }\n )\n ] });\n}\nfunction CopyToClipboard() {\n const { provides: sel } = useSelectionCapability();\n useEffect(() => {\n if (!sel) return;\n return sel.onCopyToClipboard(({ text }) => {\n navigator.clipboard.writeText(text);\n });\n }, [sel]);\n return null;\n}\nconst SelectionPluginPackage = createPluginPackage(SelectionPluginPackage$1).addUtility(CopyToClipboard).build();\nexport {\n CopyToClipboard,\n MarqueeSelection,\n SelectionLayer,\n SelectionPluginPackage,\n TextSelection,\n useSelectionCapability,\n useSelectionPlugin\n};\n//# sourceMappingURL=index.js.map\n","import { BasePlugin, createEmitter, createBehaviorEmitter } from \"@embedpdf/core\";\nconst INIT_INTERACTION_STATE = \"INTERACTION/INIT_STATE\";\nconst CLEANUP_INTERACTION_STATE = \"INTERACTION/CLEANUP_STATE\";\nconst ACTIVATE_MODE = \"INTERACTION/ACTIVATE_MODE\";\nconst PAUSE_INTERACTION = \"INTERACTION/PAUSE\";\nconst RESUME_INTERACTION = \"INTERACTION/RESUME\";\nconst SET_CURSOR = \"INTERACTION/SET_CURSOR\";\nconst SET_ACTIVE_DOCUMENT = \"INTERACTION/SET_ACTIVE_DOCUMENT\";\nconst SET_DEFAULT_MODE = \"INTERACTION/SET_DEFAULT_MODE\";\nconst SET_EXCLUSION_RULES = \"INTERACTION/SET_EXCLUSION_RULES\";\nconst ADD_EXCLUSION_CLASS = \"INTERACTION/ADD_EXCLUSION_CLASS\";\nconst REMOVE_EXCLUSION_CLASS = \"INTERACTION/REMOVE_EXCLUSION_CLASS\";\nconst ADD_EXCLUSION_ATTRIBUTE = \"INTERACTION/ADD_EXCLUSION_ATTRIBUTE\";\nconst REMOVE_EXCLUSION_ATTRIBUTE = \"INTERACTION/REMOVE_EXCLUSION_ATTRIBUTE\";\nfunction initInteractionState(documentId, state) {\n return { type: INIT_INTERACTION_STATE, payload: { documentId, state } };\n}\nfunction cleanupInteractionState(documentId) {\n return { type: CLEANUP_INTERACTION_STATE, payload: documentId };\n}\nfunction activateMode(documentId, mode) {\n return { type: ACTIVATE_MODE, payload: { documentId, mode } };\n}\nfunction pauseInteraction(documentId) {\n return { type: PAUSE_INTERACTION, payload: documentId };\n}\nfunction resumeInteraction(documentId) {\n return { type: RESUME_INTERACTION, payload: documentId };\n}\nfunction setCursor(documentId, cursor) {\n return { type: SET_CURSOR, payload: { documentId, cursor } };\n}\nfunction setDefaultMode(mode) {\n return { type: SET_DEFAULT_MODE, payload: { mode } };\n}\nfunction setExclusionRules(rules) {\n return { type: SET_EXCLUSION_RULES, payload: { rules } };\n}\nfunction addExclusionClass(className) {\n return { type: ADD_EXCLUSION_CLASS, payload: { className } };\n}\nfunction removeExclusionClass(className) {\n return { type: REMOVE_EXCLUSION_CLASS, payload: { className } };\n}\nfunction addExclusionAttribute(attribute) {\n return { type: ADD_EXCLUSION_ATTRIBUTE, payload: { attribute } };\n}\nfunction removeExclusionAttribute(attribute) {\n return { type: REMOVE_EXCLUSION_ATTRIBUTE, payload: { attribute } };\n}\nfunction mergeHandlers(list) {\n const keys = [\n \"onPointerDown\",\n \"onPointerUp\",\n \"onPointerMove\",\n \"onPointerEnter\",\n \"onPointerLeave\",\n \"onPointerCancel\",\n \"onMouseDown\",\n \"onMouseUp\",\n \"onMouseMove\",\n \"onMouseEnter\",\n \"onMouseLeave\",\n \"onMouseCancel\",\n \"onClick\",\n \"onDoubleClick\"\n ];\n const out = {};\n for (const k of keys) {\n out[k] = (pos, evt, modeId) => {\n var _a;\n for (const h of list) {\n if (evt.isImmediatePropagationStopped()) break;\n (_a = h[k]) == null ? void 0 : _a.call(h, pos, evt, modeId);\n }\n };\n }\n return out;\n}\nconst INITIAL_MODE$1 = \"pointerMode\";\nconst _InteractionManagerPlugin = class _InteractionManagerPlugin extends BasePlugin {\n constructor(id, registry, config) {\n super(id, registry);\n this.modes = /* @__PURE__ */ new Map();\n this.cursorClaims = /* @__PURE__ */ new Map();\n this.buckets = /* @__PURE__ */ new Map();\n this.alwaysGlobal = /* @__PURE__ */ new Map();\n this.alwaysPage = /* @__PURE__ */ new Map();\n this.pageActivities = /* @__PURE__ */ new Map();\n this.onModeChange$ = createEmitter();\n this.onHandlerChange$ = createEmitter();\n this.onCursorChange$ = createEmitter();\n this.onStateChange$ = createBehaviorEmitter();\n this.onPageActivityChange$ = createEmitter();\n this.registerMode({\n id: INITIAL_MODE$1,\n scope: \"page\",\n exclusive: false,\n cursor: \"auto\"\n });\n this.dispatch(setDefaultMode(INITIAL_MODE$1));\n if (config.exclusionRules) {\n this.dispatch(setExclusionRules(config.exclusionRules));\n }\n }\n // ─────────────────────────────────────────────────────────\n // Document Lifecycle Hooks (from BasePlugin)\n // ─────────────────────────────────────────────────────────\n onDocumentLoadingStarted(documentId) {\n const docState = {\n activeMode: this.state.defaultMode,\n cursor: \"auto\",\n paused: false\n };\n this.dispatch(initInteractionState(documentId, docState));\n this.cursorClaims.set(documentId, /* @__PURE__ */ new Map());\n this.buckets.set(documentId, /* @__PURE__ */ new Map());\n this.alwaysGlobal.set(documentId, /* @__PURE__ */ new Set());\n this.alwaysPage.set(documentId, /* @__PURE__ */ new Map());\n this.pageActivities.set(documentId, /* @__PURE__ */ new Map());\n const docBuckets = this.buckets.get(documentId);\n for (const modeId of this.modes.keys()) {\n docBuckets.set(modeId, { global: /* @__PURE__ */ new Set(), page: /* @__PURE__ */ new Map() });\n }\n this.logger.debug(\n \"InteractionManagerPlugin\",\n \"DocumentOpened\",\n `Initialized interaction state for document: ${documentId}`\n );\n }\n onDocumentClosed(documentId) {\n const topics = this.pageActivities.get(documentId);\n if (topics) {\n const activePages = new Set(topics.values());\n topics.clear();\n for (const pageIndex of activePages) {\n this.onPageActivityChange$.emit({ documentId, pageIndex, hasActivity: false });\n }\n }\n this.cursorClaims.delete(documentId);\n this.buckets.delete(documentId);\n this.alwaysGlobal.delete(documentId);\n this.alwaysPage.delete(documentId);\n this.pageActivities.delete(documentId);\n this.dispatch(cleanupInteractionState(documentId));\n this.logger.debug(\n \"InteractionManagerPlugin\",\n \"DocumentClosed\",\n `Cleaned up interaction state for document: ${documentId}`\n );\n }\n // ─────────────────────────────────────────────────────────\n // Capability\n // ─────────────────────────────────────────────────────────\n buildCapability() {\n return {\n // Active document operations\n getActiveMode: () => this.getActiveMode(),\n getActiveInteractionMode: () => this.getActiveInteractionMode(),\n activate: (modeId) => this.activate(modeId),\n activateDefaultMode: () => this.activateDefaultMode(),\n setCursor: (token, cursor, priority) => this.setCursor(token, cursor, priority),\n getCurrentCursor: () => this.getCurrentCursor(),\n removeCursor: (token) => this.removeCursor(token),\n getHandlersForScope: (scope) => this.getHandlersForScope(scope),\n activeModeIsExclusive: () => this.activeModeIsExclusive(),\n pause: () => this.pause(),\n resume: () => this.resume(),\n // Treat a destroyed registry as \"paused\" so late DOM events are ignored during teardown.\n isPaused: () => this.registry.isDestroyed() || this.isPaused(),\n getState: () => this.getDocumentStateOrThrow(),\n // Document-scoped operations\n forDocument: (documentId) => this.createInteractionScope(documentId),\n // Global management\n registerMode: (mode) => this.registerMode(mode),\n registerHandlers: (options) => this.registerHandlers(options),\n registerAlways: (options) => this.registerAlways(options),\n setDefaultMode: (id) => this.setDefaultMode(id),\n getDefaultMode: () => this.state.defaultMode,\n getExclusionRules: () => this.state.exclusionRules,\n setExclusionRules: (rules) => this.dispatch(setExclusionRules(rules)),\n addExclusionClass: (className) => this.dispatch(addExclusionClass(className)),\n removeExclusionClass: (className) => this.dispatch(removeExclusionClass(className)),\n addExclusionAttribute: (attribute) => this.dispatch(addExclusionAttribute(attribute)),\n removeExclusionAttribute: (attribute) => this.dispatch(removeExclusionAttribute(attribute)),\n // Page activity\n claimPageActivity: (documentId, topic, pageIndex) => this.claimPageActivity(documentId, topic, pageIndex),\n releasePageActivity: (documentId, topic) => this.releasePageActivity(documentId, topic),\n hasPageActivity: (documentId, pageIndex) => this.hasPageActivity(documentId, pageIndex),\n // Events\n onModeChange: this.onModeChange$.on,\n onCursorChange: this.onCursorChange$.on,\n onHandlerChange: this.onHandlerChange$.on,\n onStateChange: this.onStateChange$.on,\n onPageActivityChange: this.onPageActivityChange$.on\n };\n }\n // ─────────────────────────────────────────────────────────\n // Document Scoping\n // ─────────────────────────────────────────────────────────\n createInteractionScope(documentId) {\n return {\n getActiveMode: () => this.getActiveMode(documentId),\n getActiveInteractionMode: () => this.getActiveInteractionMode(documentId),\n activate: (modeId) => this.activate(modeId, documentId),\n activateDefaultMode: () => this.activateDefaultMode(documentId),\n setCursor: (token, cursor, priority) => this.setCursor(token, cursor, priority, documentId),\n getCurrentCursor: () => this.getCurrentCursor(documentId),\n removeCursor: (token) => this.removeCursor(token, documentId),\n getHandlersForScope: (scope) => this.getHandlersForScope(scope),\n activeModeIsExclusive: () => this.activeModeIsExclusive(documentId),\n pause: () => this.pause(documentId),\n resume: () => this.resume(documentId),\n isPaused: () => this.isPaused(documentId),\n getState: () => this.getDocumentStateOrThrow(documentId),\n claimPageActivity: (topic, pageIndex) => this.claimPageActivity(documentId, topic, pageIndex),\n releasePageActivity: (topic) => this.releasePageActivity(documentId, topic),\n hasPageActivity: (pageIndex) => this.hasPageActivity(documentId, pageIndex),\n onModeChange: (listener) => this.onModeChange$.on((event) => {\n if (event.documentId === documentId) listener(event.activeMode);\n }),\n onCursorChange: (listener) => this.onCursorChange$.on((event) => {\n if (event.documentId === documentId) listener(event.cursor);\n }),\n onStateChange: (listener) => this.onStateChange$.on((event) => {\n if (event.documentId === documentId) listener(event.state);\n }),\n onPageActivityChange: (listener) => this.onPageActivityChange$.on((event) => {\n if (event.documentId === documentId)\n listener({ pageIndex: event.pageIndex, hasActivity: event.hasActivity });\n })\n };\n }\n // ─────────────────────────────────────────────────────────\n // State Helpers\n // ─────────────────────────────────────────────────────────\n getDocumentState(documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n return this.state.documents[id] ?? null;\n }\n getDocumentStateOrThrow(documentId) {\n const state = this.getDocumentState(documentId);\n if (!state) {\n throw new Error(`Interaction state not found for document: ${documentId ?? \"active\"}`);\n }\n return state;\n }\n // ─────────────────────────────────────────────────────────\n // Core Operations\n // ─────────────────────────────────────────────────────────\n activate(modeId, documentId) {\n var _a;\n const id = documentId ?? this.getActiveDocumentId();\n const docState = this.getDocumentStateOrThrow(id);\n if (!this.modes.has(modeId)) {\n throw new Error(`[interaction] unknown mode '${modeId}'`);\n }\n if (modeId === docState.activeMode) return;\n const previousMode = docState.activeMode;\n (_a = this.cursorClaims.get(id)) == null ? void 0 : _a.clear();\n this.notifyHandlersInactive(id, previousMode);\n this.dispatch(activateMode(id, modeId));\n this.emitCursor(id);\n this.notifyHandlersActive(id, modeId);\n this.onModeChange$.emit({\n documentId: id,\n activeMode: modeId,\n previousMode\n });\n }\n activateDefaultMode(documentId) {\n const id = documentId ?? this.getActiveDocumentIdOrNull();\n if (!id) return;\n this.activate(this.state.defaultMode, id);\n }\n setDefaultMode(modeId) {\n if (!this.modes.has(modeId)) {\n throw new Error(`[interaction] cannot set unknown mode '${modeId}' as default`);\n }\n this.dispatch(setDefaultMode(modeId));\n }\n getActiveMode(documentId) {\n return this.getDocumentStateOrThrow(documentId).activeMode;\n }\n getActiveInteractionMode(documentId) {\n const docState = this.getDocumentState(documentId);\n if (!docState) return null;\n return this.modes.get(docState.activeMode) ?? null;\n }\n activeModeIsExclusive(documentId) {\n const mode = this.getActiveInteractionMode(documentId);\n return !!(mode == null ? void 0 : mode.exclusive);\n }\n pause(documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n this.dispatch(pauseInteraction(id));\n }\n resume(documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n this.dispatch(resumeInteraction(id));\n }\n isPaused(documentId) {\n return this.getDocumentStateOrThrow(documentId).paused;\n }\n // ─────────────────────────────────────────────────────────\n // Mode Management\n // ─────────────────────────────────────────────────────────\n registerMode(mode) {\n this.modes.set(mode.id, mode);\n for (const documentId of this.buckets.keys()) {\n const docBuckets = this.buckets.get(documentId);\n if (!docBuckets.has(mode.id)) {\n docBuckets.set(mode.id, { global: /* @__PURE__ */ new Set(), page: /* @__PURE__ */ new Map() });\n }\n }\n }\n // ─────────────────────────────────────────────────────────\n // Handler Management\n // ─────────────────────────────────────────────────────────\n registerHandlers({\n documentId,\n modeId,\n handlers,\n pageIndex\n }) {\n const modeIds = Array.isArray(modeId) ? modeId : [modeId];\n const cleanupFunctions = [];\n const docBuckets = this.buckets.get(documentId);\n if (!docBuckets) {\n throw new Error(`No buckets found for document: ${documentId}`);\n }\n for (const id of modeIds) {\n const bucket = docBuckets.get(id);\n if (!bucket) throw new Error(`unknown mode '${id}'`);\n if (pageIndex == null) {\n bucket.global.add(handlers);\n } else {\n const set = bucket.page.get(pageIndex) ?? /* @__PURE__ */ new Set();\n set.add(handlers);\n bucket.page.set(pageIndex, set);\n }\n cleanupFunctions.push(() => {\n if (pageIndex == null) {\n bucket.global.delete(handlers);\n } else {\n const set = bucket.page.get(pageIndex);\n if (set) {\n set.delete(handlers);\n if (set.size === 0) {\n bucket.page.delete(pageIndex);\n }\n }\n }\n });\n }\n this.onHandlerChange$.emit({ ...this.state });\n return () => {\n cleanupFunctions.forEach((cleanup) => cleanup());\n this.onHandlerChange$.emit({ ...this.state });\n };\n }\n registerAlways({ scope, handlers }) {\n if (scope.type === \"global\") {\n const set2 = this.alwaysGlobal.get(scope.documentId) ?? /* @__PURE__ */ new Set();\n set2.add(handlers);\n this.alwaysGlobal.set(scope.documentId, set2);\n this.onHandlerChange$.emit({ ...this.state });\n return () => {\n set2.delete(handlers);\n this.onHandlerChange$.emit({ ...this.state });\n };\n }\n const docPageMap = this.alwaysPage.get(scope.documentId) ?? /* @__PURE__ */ new Map();\n const set = docPageMap.get(scope.pageIndex) ?? /* @__PURE__ */ new Set();\n set.add(handlers);\n docPageMap.set(scope.pageIndex, set);\n this.alwaysPage.set(scope.documentId, docPageMap);\n this.onHandlerChange$.emit({ ...this.state });\n return () => {\n set.delete(handlers);\n this.onHandlerChange$.emit({ ...this.state });\n };\n }\n getHandlersForScope(scope) {\n var _a;\n const docState = this.getDocumentState(scope.documentId);\n if (!docState) return null;\n const mode = this.modes.get(docState.activeMode);\n if (!mode) return null;\n const docBuckets = this.buckets.get(scope.documentId);\n if (!docBuckets) return null;\n const bucket = docBuckets.get(mode.id);\n if (!bucket) return null;\n const mergeSets = (a, b) => a.size || b.size ? mergeHandlers([...a, ...b]) : null;\n if (scope.type === \"global\") {\n const alwaysSet = this.alwaysGlobal.get(scope.documentId) ?? /* @__PURE__ */ new Set();\n const modeSpecific = mode.scope === \"global\" ? bucket.global : /* @__PURE__ */ new Set();\n return mergeSets(alwaysSet, modeSpecific);\n }\n const alwaysPageSet = ((_a = this.alwaysPage.get(scope.documentId)) == null ? void 0 : _a.get(scope.pageIndex)) ?? /* @__PURE__ */ new Set();\n const modePageSet = mode.scope === \"page\" ? bucket.page.get(scope.pageIndex) ?? /* @__PURE__ */ new Set() : /* @__PURE__ */ new Set();\n return mergeSets(alwaysPageSet, modePageSet);\n }\n // ─────────────────────────────────────────────────────────\n // Cursor Management\n // ─────────────────────────────────────────────────────────\n setCursor(token, cursor, priority = 0, documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const claims = this.cursorClaims.get(id);\n if (!claims) return;\n claims.set(token, { cursor, priority });\n this.emitCursor(id);\n }\n removeCursor(token, documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const claims = this.cursorClaims.get(id);\n if (!claims) return;\n claims.delete(token);\n this.emitCursor(id);\n }\n getCurrentCursor(documentId) {\n return this.getDocumentStateOrThrow(documentId).cursor;\n }\n emitCursor(documentId) {\n var _a;\n const claims = this.cursorClaims.get(documentId);\n if (!claims) return;\n const docState = this.getDocumentState(documentId);\n if (!docState) return;\n const top = [...claims.values()].sort((a, b) => b.priority - a.priority)[0] ?? {\n cursor: ((_a = this.modes.get(docState.activeMode)) == null ? void 0 : _a.cursor) ?? \"auto\"\n };\n if (top.cursor !== docState.cursor) {\n this.dispatch(setCursor(documentId, top.cursor));\n this.onCursorChange$.emit({\n documentId,\n cursor: top.cursor\n });\n }\n }\n // ─────────────────────────────────────────────────────────\n // Page Activity Management\n // ─────────────────────────────────────────────────────────\n claimPageActivity(documentId, topic, pageIndex) {\n let topics = this.pageActivities.get(documentId);\n if (!topics) {\n topics = /* @__PURE__ */ new Map();\n this.pageActivities.set(documentId, topics);\n }\n const oldPage = topics.get(topic);\n if (oldPage === pageIndex) return;\n topics.set(topic, pageIndex);\n if (oldPage !== void 0 && !this.pageHasAnyTopic(documentId, oldPage)) {\n this.onPageActivityChange$.emit({ documentId, pageIndex: oldPage, hasActivity: false });\n }\n if (this.countTopicsOnPage(documentId, pageIndex) === 1) {\n this.onPageActivityChange$.emit({ documentId, pageIndex, hasActivity: true });\n }\n }\n releasePageActivity(documentId, topic) {\n const topics = this.pageActivities.get(documentId);\n if (!topics) return;\n const page = topics.get(topic);\n if (page === void 0) return;\n topics.delete(topic);\n if (!this.pageHasAnyTopic(documentId, page)) {\n this.onPageActivityChange$.emit({ documentId, pageIndex: page, hasActivity: false });\n }\n }\n hasPageActivity(documentId, pageIndex) {\n return this.pageHasAnyTopic(documentId, pageIndex);\n }\n /** Helper: does any topic point to this page? */\n pageHasAnyTopic(documentId, pageIndex) {\n const topics = this.pageActivities.get(documentId);\n if (!topics) return false;\n for (const p of topics.values()) {\n if (p === pageIndex) return true;\n }\n return false;\n }\n /** Helper: count topics on a page */\n countTopicsOnPage(documentId, pageIndex) {\n const topics = this.pageActivities.get(documentId);\n if (!topics) return 0;\n let count = 0;\n for (const p of topics.values()) {\n if (p === pageIndex) count++;\n }\n return count;\n }\n // ─────────────────────────────────────────────────────────\n // Handler Lifecycle Notifications\n // ─────────────────────────────────────────────────────────\n notifyHandlersActive(documentId, modeId) {\n var _a, _b;\n (_a = this.alwaysGlobal.get(documentId)) == null ? void 0 : _a.forEach((handler) => {\n var _a2;\n (_a2 = handler.onHandlerActiveStart) == null ? void 0 : _a2.call(handler, modeId);\n });\n (_b = this.alwaysPage.get(documentId)) == null ? void 0 : _b.forEach((handlerSet) => {\n handlerSet.forEach((handler) => {\n var _a2;\n (_a2 = handler.onHandlerActiveStart) == null ? void 0 : _a2.call(handler, modeId);\n });\n });\n const mode = this.modes.get(modeId);\n if (!mode) return;\n const docBuckets = this.buckets.get(documentId);\n if (!docBuckets) return;\n const bucket = docBuckets.get(modeId);\n if (!bucket) return;\n if (mode.scope === \"global\") {\n bucket.global.forEach((handler) => {\n var _a2;\n (_a2 = handler.onHandlerActiveStart) == null ? void 0 : _a2.call(handler, modeId);\n });\n }\n if (mode.scope === \"page\") {\n bucket.page.forEach((handlerSet) => {\n handlerSet.forEach((handler) => {\n var _a2;\n (_a2 = handler.onHandlerActiveStart) == null ? void 0 : _a2.call(handler, modeId);\n });\n });\n }\n }\n notifyHandlersInactive(documentId, modeId) {\n var _a, _b;\n (_a = this.alwaysGlobal.get(documentId)) == null ? void 0 : _a.forEach((handler) => {\n var _a2;\n (_a2 = handler.onHandlerActiveEnd) == null ? void 0 : _a2.call(handler, modeId);\n });\n (_b = this.alwaysPage.get(documentId)) == null ? void 0 : _b.forEach((handlerSet) => {\n handlerSet.forEach((handler) => {\n var _a2;\n (_a2 = handler.onHandlerActiveEnd) == null ? void 0 : _a2.call(handler, modeId);\n });\n });\n const mode = this.modes.get(modeId);\n if (!mode) return;\n const docBuckets = this.buckets.get(documentId);\n if (!docBuckets) return;\n const bucket = docBuckets.get(modeId);\n if (!bucket) return;\n if (mode.scope === \"global\") {\n bucket.global.forEach((handler) => {\n var _a2;\n (_a2 = handler.onHandlerActiveEnd) == null ? void 0 : _a2.call(handler, modeId);\n });\n }\n if (mode.scope === \"page\") {\n bucket.page.forEach((handlerSet) => {\n handlerSet.forEach((handler) => {\n var _a2;\n (_a2 = handler.onHandlerActiveEnd) == null ? void 0 : _a2.call(handler, modeId);\n });\n });\n }\n }\n // ─────────────────────────────────────────────────────────\n // Store Update Handlers\n // ─────────────────────────────────────────────────────────\n onStoreUpdated(prevState, newState) {\n for (const documentId in newState.documents) {\n const prevDoc = prevState.documents[documentId];\n const newDoc = newState.documents[documentId];\n if (prevDoc !== newDoc) {\n this.onStateChange$.emit({\n documentId,\n state: newDoc\n });\n }\n }\n }\n // ─────────────────────────────────────────────────────────\n // Lifecycle\n // ─────────────────────────────────────────────────────────\n async initialize(_) {\n this.logger.info(\n \"InteractionManagerPlugin\",\n \"Initialize\",\n \"Interaction Manager Plugin initialized\"\n );\n }\n async destroy() {\n this.pageActivities.clear();\n this.onModeChange$.clear();\n this.onCursorChange$.clear();\n this.onHandlerChange$.clear();\n this.onStateChange$.clear();\n this.onPageActivityChange$.clear();\n await super.destroy();\n }\n};\n_InteractionManagerPlugin.id = \"interaction-manager\";\nlet InteractionManagerPlugin = _InteractionManagerPlugin;\nconst INTERACTION_MANAGER_PLUGIN_ID = \"interaction-manager\";\nconst manifest = {\n id: INTERACTION_MANAGER_PLUGIN_ID,\n name: \"Interaction Manager Plugin\",\n version: \"1.0.0\",\n provides: [\"interaction-manager\"],\n requires: [],\n optional: [],\n defaultConfig: {\n exclusionRules: {\n classes: [],\n dataAttributes: [\"data-no-interaction\"]\n }\n }\n};\nconst INITIAL_MODE = \"pointerMode\";\nconst initialDocumentState = {\n activeMode: INITIAL_MODE,\n cursor: \"auto\",\n paused: false\n};\nconst initialState = {\n defaultMode: INITIAL_MODE,\n exclusionRules: {\n classes: [],\n dataAttributes: [\"data-no-interaction\"]\n },\n documents: {},\n activeDocumentId: null\n};\nconst reducer = (state = initialState, action) => {\n switch (action.type) {\n // ─────────────────────────────────────────────────────────\n // Document Lifecycle\n // ─────────────────────────────────────────────────────────\n case INIT_INTERACTION_STATE: {\n const { documentId, state: docState } = action.payload;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: docState\n },\n // Set as active if no active document\n activeDocumentId: state.activeDocumentId ?? documentId\n };\n }\n case CLEANUP_INTERACTION_STATE: {\n const documentId = action.payload;\n const { [documentId]: removed, ...remainingDocs } = state.documents;\n return {\n ...state,\n documents: remainingDocs,\n activeDocumentId: state.activeDocumentId === documentId ? null : state.activeDocumentId\n };\n }\n case SET_ACTIVE_DOCUMENT: {\n return {\n ...state,\n activeDocumentId: action.payload\n };\n }\n // ─────────────────────────────────────────────────────────\n // Per-Document Actions\n // ─────────────────────────────────────────────────────────\n case ACTIVATE_MODE: {\n const { documentId, mode } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...docState,\n activeMode: mode\n }\n }\n };\n }\n case SET_CURSOR: {\n const { documentId, cursor } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...docState,\n cursor\n }\n }\n };\n }\n case PAUSE_INTERACTION: {\n const documentId = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...docState,\n paused: true\n }\n }\n };\n }\n case RESUME_INTERACTION: {\n const documentId = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...docState,\n paused: false\n }\n }\n };\n }\n // ─────────────────────────────────────────────────────────\n // Global Actions\n // ─────────────────────────────────────────────────────────\n case SET_DEFAULT_MODE:\n return {\n ...state,\n defaultMode: action.payload.mode\n };\n case SET_EXCLUSION_RULES:\n return {\n ...state,\n exclusionRules: action.payload.rules\n };\n case ADD_EXCLUSION_CLASS:\n return {\n ...state,\n exclusionRules: {\n ...state.exclusionRules,\n classes: [...state.exclusionRules.classes || [], action.payload.className].filter(\n (v, i, a) => a.indexOf(v) === i\n )\n }\n };\n case REMOVE_EXCLUSION_CLASS:\n return {\n ...state,\n exclusionRules: {\n ...state.exclusionRules,\n classes: (state.exclusionRules.classes || []).filter(\n (c) => c !== action.payload.className\n )\n }\n };\n case ADD_EXCLUSION_ATTRIBUTE:\n return {\n ...state,\n exclusionRules: {\n ...state.exclusionRules,\n dataAttributes: [\n ...state.exclusionRules.dataAttributes || [],\n action.payload.attribute\n ].filter((v, i, a) => a.indexOf(v) === i)\n }\n };\n case REMOVE_EXCLUSION_ATTRIBUTE:\n return {\n ...state,\n exclusionRules: {\n ...state.exclusionRules,\n dataAttributes: (state.exclusionRules.dataAttributes || []).filter(\n (a) => a !== action.payload.attribute\n )\n }\n };\n default:\n return state;\n }\n};\nconst InteractionManagerPluginPackage = {\n manifest,\n create: (registry, config) => new InteractionManagerPlugin(INTERACTION_MANAGER_PLUGIN_ID, registry, config),\n reducer,\n initialState\n};\nexport {\n INTERACTION_MANAGER_PLUGIN_ID,\n InteractionManagerPlugin,\n InteractionManagerPluginPackage,\n initialDocumentState,\n initialState,\n manifest,\n reducer\n};\n//# sourceMappingURL=index.js.map\n","import { useCapability, usePlugin, useDocumentState } from \"@embedpdf/core/react\";\nimport { initialDocumentState, InteractionManagerPlugin } from \"@embedpdf/plugin-interaction-manager\";\nexport * from \"@embedpdf/plugin-interaction-manager\";\nimport { useState, useEffect, useRef, useCallback } from \"react\";\nimport { jsx, jsxs } from \"react/jsx-runtime\";\nimport { transformSize, restorePosition } from \"@embedpdf/models\";\nconst useInteractionManagerPlugin = () => usePlugin(InteractionManagerPlugin.id);\nconst useInteractionManagerCapability = () => useCapability(InteractionManagerPlugin.id);\nfunction useInteractionManager(documentId) {\n const { provides } = useInteractionManagerCapability();\n const [state, setState] = useState(initialDocumentState);\n useEffect(() => {\n if (!provides) return;\n const scope = provides.forDocument(documentId);\n return scope.onStateChange((state2) => {\n setState(state2);\n });\n }, [provides]);\n return {\n provides: (provides == null ? void 0 : provides.forDocument(documentId)) ?? null,\n state\n };\n}\nfunction useCursor(documentId) {\n const { provides } = useInteractionManagerCapability();\n return {\n setCursor: (token, cursor, prio = 0) => {\n if (!provides) return;\n const scope = provides.forDocument(documentId);\n scope.setCursor(token, cursor, prio);\n },\n removeCursor: (token) => {\n if (!provides) return;\n const scope = provides.forDocument(documentId);\n scope.removeCursor(token);\n }\n };\n}\nfunction usePointerHandlers({ modeId, pageIndex, documentId }) {\n const { provides } = useInteractionManagerCapability();\n return {\n register: (handlers, options) => {\n const finalModeId = (options == null ? void 0 : options.modeId) ?? modeId;\n const finalPageIndex = (options == null ? void 0 : options.pageIndex) ?? pageIndex;\n const finalDocumentId = (options == null ? void 0 : options.documentId) ?? documentId;\n return finalModeId ? provides == null ? void 0 : provides.registerHandlers({\n modeId: finalModeId,\n handlers,\n pageIndex: finalPageIndex,\n documentId: finalDocumentId\n }) : provides == null ? void 0 : provides.registerAlways({\n scope: finalPageIndex !== void 0 ? { type: \"page\", documentId: finalDocumentId, pageIndex: finalPageIndex } : { type: \"global\", documentId: finalDocumentId },\n handlers\n });\n }\n };\n}\nfunction useIsPageExclusive(documentId) {\n const { provides: cap } = useInteractionManagerCapability();\n const [isPageExclusive, setIsPageExclusive] = useState(() => {\n if (!cap) return false;\n const scope = cap.forDocument(documentId);\n const m = scope.getActiveInteractionMode();\n return (m == null ? void 0 : m.scope) === \"page\" && !!m.exclusive;\n });\n useEffect(() => {\n if (!cap) return;\n const scope = cap.forDocument(documentId);\n return scope.onModeChange(() => {\n const mode = scope.getActiveInteractionMode();\n setIsPageExclusive((mode == null ? void 0 : mode.scope) === \"page\" && !!(mode == null ? void 0 : mode.exclusive));\n });\n }, [cap, documentId]);\n return isPageExclusive;\n}\nconst domEventMap = {\n pointerdown: \"onPointerDown\",\n pointerup: \"onPointerUp\",\n pointermove: \"onPointerMove\",\n pointerenter: \"onPointerEnter\",\n pointerleave: \"onPointerLeave\",\n pointercancel: \"onPointerCancel\",\n mousedown: \"onMouseDown\",\n mouseup: \"onMouseUp\",\n mousemove: \"onMouseMove\",\n mouseenter: \"onMouseEnter\",\n mouseleave: \"onMouseLeave\",\n mousecancel: \"onMouseCancel\",\n click: \"onClick\",\n dblclick: \"onDoubleClick\",\n /* touch → pointer fallback for very old browsers */\n touchstart: \"onPointerDown\",\n touchend: \"onPointerUp\",\n touchmove: \"onPointerMove\",\n touchcancel: \"onPointerCancel\"\n};\nconst pointerEventTypes = [\n \"pointerdown\",\n \"pointerup\",\n \"pointermove\",\n \"pointerenter\",\n \"pointerleave\",\n \"pointercancel\",\n \"mousedown\",\n \"mouseup\",\n \"mousemove\",\n \"mouseenter\",\n \"mouseleave\",\n \"mousecancel\",\n \"click\",\n \"dblclick\"\n];\nconst touchEventTypes = [\"touchstart\", \"touchend\", \"touchmove\", \"touchcancel\"];\nconst HAS_POINTER = typeof PointerEvent !== \"undefined\";\nconst allEventTypes = HAS_POINTER ? pointerEventTypes : [...pointerEventTypes, ...touchEventTypes];\nfunction listenerOpts(eventType, wantsRawTouch) {\n return eventType.startsWith(\"touch\") ? { passive: !wantsRawTouch } : { passive: false };\n}\nfunction isTouchEvent(evt) {\n return typeof TouchEvent !== \"undefined\" && evt instanceof TouchEvent;\n}\nfunction shouldExcludeElement(element, rules) {\n var _a, _b, _c;\n if (!element) return false;\n let current = element;\n while (current) {\n if ((_a = rules.classes) == null ? void 0 : _a.length) {\n for (const className of rules.classes) {\n if ((_b = current.classList) == null ? void 0 : _b.contains(className)) {\n return true;\n }\n }\n }\n if ((_c = rules.dataAttributes) == null ? void 0 : _c.length) {\n for (const attr of rules.dataAttributes) {\n if (current.hasAttribute(attr)) {\n return true;\n }\n }\n }\n current = current.parentElement;\n }\n return false;\n}\nfunction createPointerProvider(cap, scope, element, convertEventToPoint) {\n const capScope = cap.forDocument(scope.documentId);\n let active = cap.getHandlersForScope(scope);\n const wantsRawTouchNow = () => {\n var _a;\n return ((_a = capScope.getActiveInteractionMode()) == null ? void 0 : _a.wantsRawTouch) !== false;\n };\n const listeners = {};\n let attachedWithRawTouch = wantsRawTouchNow();\n const addListeners = (raw) => {\n allEventTypes.forEach((type) => {\n const fn = listeners[type] ?? (listeners[type] = handleEvent);\n element.addEventListener(type, fn, listenerOpts(type, raw));\n });\n };\n const removeListeners = () => {\n allEventTypes.forEach((type) => {\n const fn = listeners[type];\n if (fn) element.removeEventListener(type, fn);\n });\n };\n addListeners(attachedWithRawTouch);\n element.style.touchAction = attachedWithRawTouch ? \"none\" : \"\";\n const stopMode = capScope.onModeChange(() => {\n if (scope.type === \"global\") {\n const mode = capScope.getActiveInteractionMode();\n element.style.cursor = (mode == null ? void 0 : mode.scope) === \"global\" ? mode.cursor ?? \"auto\" : \"auto\";\n }\n active = cap.getHandlersForScope(scope);\n const raw = wantsRawTouchNow();\n if (raw !== attachedWithRawTouch) {\n removeListeners();\n addListeners(raw);\n attachedWithRawTouch = raw;\n element.style.touchAction = attachedWithRawTouch ? \"none\" : \"\";\n }\n });\n const stopHandler = cap.onHandlerChange(() => {\n active = cap.getHandlersForScope(scope);\n });\n const initialMode = capScope.getActiveInteractionMode();\n const initialCursor = capScope.getCurrentCursor();\n element.style.cursor = scope.type === \"global\" && (initialMode == null ? void 0 : initialMode.scope) !== \"global\" ? \"auto\" : initialCursor;\n const stopCursor = capScope.onCursorChange((c) => {\n var _a;\n if (scope.type === \"global\" && ((_a = capScope.getActiveInteractionMode()) == null ? void 0 : _a.scope) !== \"global\") return;\n element.style.cursor = c;\n });\n const toPos = (e, host) => {\n if (convertEventToPoint) return convertEventToPoint(e, host);\n const r = host.getBoundingClientRect();\n return { x: e.clientX - r.left, y: e.clientY - r.top };\n };\n function handleEvent(evt) {\n var _a;\n if (cap.isPaused()) return;\n const exclusionRules = cap.getExclusionRules();\n if (evt.target && shouldExcludeElement(evt.target, exclusionRules)) {\n return;\n }\n const handlerKey = domEventMap[evt.type];\n if (!handlerKey || !(active == null ? void 0 : active[handlerKey])) return;\n if (isTouchEvent(evt) && attachedWithRawTouch && (evt.type === \"touchmove\" || evt.type === \"touchcancel\")) {\n evt.preventDefault();\n }\n let pos;\n let normEvt;\n let propagationStopped = false;\n if (isTouchEvent(evt)) {\n const tp = evt.type === \"touchend\" || evt.type === \"touchcancel\" ? evt.changedTouches[0] : evt.touches[0];\n if (!tp) return;\n pos = toPos(tp, element);\n normEvt = {\n clientX: tp.clientX,\n clientY: tp.clientY,\n ctrlKey: evt.ctrlKey,\n shiftKey: evt.shiftKey,\n altKey: evt.altKey,\n metaKey: evt.metaKey,\n target: evt.target,\n currentTarget: evt.currentTarget,\n setPointerCapture: () => {\n },\n releasePointerCapture: () => {\n },\n stopImmediatePropagation: () => {\n propagationStopped = true;\n },\n isImmediatePropagationStopped: () => propagationStopped\n };\n } else {\n const pe = evt;\n pos = toPos(pe, element);\n normEvt = {\n clientX: pe.clientX,\n clientY: pe.clientY,\n ctrlKey: pe.ctrlKey,\n shiftKey: pe.shiftKey,\n altKey: pe.altKey,\n metaKey: pe.metaKey,\n target: pe.target,\n currentTarget: pe.currentTarget,\n setPointerCapture: () => {\n var _a2, _b;\n (_b = (_a2 = pe.target) == null ? void 0 : _a2.setPointerCapture) == null ? void 0 : _b.call(_a2, pe.pointerId);\n },\n releasePointerCapture: () => {\n var _a2, _b;\n (_b = (_a2 = pe.target) == null ? void 0 : _a2.releasePointerCapture) == null ? void 0 : _b.call(_a2, pe.pointerId);\n },\n stopImmediatePropagation: () => {\n propagationStopped = true;\n },\n isImmediatePropagationStopped: () => propagationStopped\n };\n }\n (_a = active[handlerKey]) == null ? void 0 : _a.call(active, pos, normEvt, capScope.getActiveMode());\n }\n return () => {\n removeListeners();\n stopMode();\n stopCursor();\n stopHandler();\n };\n}\nconst GlobalPointerProvider = ({\n children,\n documentId,\n style,\n ...props\n}) => {\n const ref = useRef(null);\n const { provides: cap } = useInteractionManagerCapability();\n useEffect(() => {\n if (!cap || !ref.current) return;\n return createPointerProvider(cap, { type: \"global\", documentId }, ref.current);\n }, [cap, documentId]);\n return /* @__PURE__ */ jsx(\n \"div\",\n {\n ref,\n style: {\n width: \"100%\",\n height: \"100%\",\n ...style\n },\n ...props,\n children\n }\n );\n};\nconst PagePointerProvider = ({\n documentId,\n pageIndex,\n children,\n rotation: rotationOverride,\n scale: scaleOverride,\n convertEventToPoint,\n style,\n ...props\n}) => {\n var _a, _b;\n const ref = useRef(null);\n const { provides: cap } = useInteractionManagerCapability();\n const isPageExclusive = useIsPageExclusive(documentId);\n const documentState = useDocumentState(documentId);\n const page = (_b = (_a = documentState == null ? void 0 : documentState.document) == null ? void 0 : _a.pages) == null ? void 0 : _b[pageIndex];\n const naturalPageSize = (page == null ? void 0 : page.size) ?? { width: 0, height: 0 };\n const pageRotation = (page == null ? void 0 : page.rotation) ?? 0;\n const docRotation = (documentState == null ? void 0 : documentState.rotation) ?? 0;\n const rotation = rotationOverride !== void 0 ? rotationOverride : (pageRotation + docRotation) % 4;\n const scale = scaleOverride ?? (documentState == null ? void 0 : documentState.scale) ?? 1;\n const displaySize = transformSize(naturalPageSize, 0, scale);\n const defaultConvertEventToPoint = useCallback(\n (event, element) => {\n const rect = element.getBoundingClientRect();\n const displayPoint = {\n x: event.clientX - rect.left,\n y: event.clientY - rect.top\n };\n const rotatedNaturalSize = transformSize(\n {\n width: displaySize.width,\n height: displaySize.height\n },\n rotation,\n 1\n );\n return restorePosition(rotatedNaturalSize, displayPoint, rotation, scale);\n },\n [naturalPageSize, rotation, scale]\n );\n useEffect(() => {\n if (!cap || !ref.current) return;\n return createPointerProvider(\n cap,\n { type: \"page\", documentId, pageIndex },\n ref.current,\n convertEventToPoint || defaultConvertEventToPoint\n );\n }, [cap, documentId, pageIndex, convertEventToPoint, defaultConvertEventToPoint]);\n return /* @__PURE__ */ jsxs(\n \"div\",\n {\n ref,\n style: {\n position: \"relative\",\n width: displaySize.width,\n height: displaySize.height,\n ...style\n },\n ...props,\n children: [\n children,\n isPageExclusive && /* @__PURE__ */ jsx(\"div\", { style: { position: \"absolute\", top: 0, left: 0, right: 0, bottom: 0, zIndex: 10 } })\n ]\n }\n );\n};\nexport {\n GlobalPointerProvider,\n PagePointerProvider,\n useCursor,\n useInteractionManager,\n useInteractionManagerCapability,\n useInteractionManagerPlugin,\n useIsPageExclusive,\n usePointerHandlers\n};\n//# sourceMappingURL=index.js.map\n","import { BasePlugin, createBehaviorEmitter, setRotation as setRotation$1 } from \"@embedpdf/core\";\nconst ROTATE_PLUGIN_ID = \"rotate\";\nconst manifest = {\n id: ROTATE_PLUGIN_ID,\n name: \"Rotate Plugin\",\n version: \"1.0.0\",\n provides: [\"rotate\"],\n requires: [],\n optional: [],\n defaultConfig: {}\n};\nfunction getRotationMatrix(rotation, w, h) {\n let a = 1, b = 0, c = 0, d = 1, e = 0, f = 0;\n switch (rotation) {\n case 1:\n a = 0;\n b = 1;\n c = -1;\n d = 0;\n e = h;\n break;\n case 2:\n a = -1;\n b = 0;\n c = 0;\n d = -1;\n e = w;\n f = h;\n break;\n case 3:\n a = 0;\n b = -1;\n c = 1;\n d = 0;\n f = w;\n break;\n }\n return [a, b, c, d, e, f];\n}\nfunction getRotationMatrixString(rotation, w, h) {\n const [a, b, c, d, e, f] = getRotationMatrix(rotation, w, h);\n return `matrix(${a},${b},${c},${d},${e},${f})`;\n}\nfunction getNextRotation(current) {\n return (current + 1) % 4;\n}\nfunction getPreviousRotation(current) {\n return (current + 3) % 4;\n}\nconst INIT_ROTATE_STATE = \"ROTATE/INIT_STATE\";\nconst CLEANUP_ROTATE_STATE = \"ROTATE/CLEANUP_STATE\";\nconst SET_ACTIVE_ROTATE_DOCUMENT = \"ROTATE/SET_ACTIVE_DOCUMENT\";\nconst SET_ROTATION = \"ROTATE/SET_ROTATION\";\nfunction initRotateState(documentId, state) {\n return { type: INIT_ROTATE_STATE, payload: { documentId, state } };\n}\nfunction cleanupRotateState(documentId) {\n return { type: CLEANUP_ROTATE_STATE, payload: documentId };\n}\nfunction setActiveRotateDocument(documentId) {\n return { type: SET_ACTIVE_ROTATE_DOCUMENT, payload: documentId };\n}\nfunction setRotation(documentId, rotation) {\n return { type: SET_ROTATION, payload: { documentId, rotation } };\n}\nconst _RotatePlugin = class _RotatePlugin extends BasePlugin {\n constructor(id, registry, cfg) {\n super(id, registry);\n this.rotate$ = createBehaviorEmitter();\n this.defaultRotation = cfg.defaultRotation ?? 0;\n }\n // ─────────────────────────────────────────────────────────\n // Document Lifecycle Hooks (from BasePlugin)\n // ─────────────────────────────────────────────────────────\n onDocumentLoadingStarted(documentId) {\n const docState = {\n rotation: this.defaultRotation\n };\n this.dispatch(initRotateState(documentId, docState));\n this.dispatchCoreAction(setRotation$1(this.defaultRotation, documentId));\n this.logger.debug(\n \"RotatePlugin\",\n \"DocumentOpened\",\n `Initialized rotation state for document: ${documentId}`\n );\n }\n onDocumentClosed(documentId) {\n this.dispatch(cleanupRotateState(documentId));\n this.logger.debug(\n \"RotatePlugin\",\n \"DocumentClosed\",\n `Cleaned up rotation state for document: ${documentId}`\n );\n }\n // ─────────────────────────────────────────────────────────\n // Capability\n // ─────────────────────────────────────────────────────────\n buildCapability() {\n return {\n // Active document operations\n setRotation: (rotation) => this.setRotationForDocument(rotation),\n getRotation: () => this.getRotationForDocument(),\n rotateForward: () => this.rotateForward(),\n rotateBackward: () => this.rotateBackward(),\n // Document-scoped operations\n forDocument: (documentId) => this.createRotateScope(documentId),\n // Events\n onRotateChange: this.rotate$.on\n };\n }\n // ─────────────────────────────────────────────────────────\n // Document Scoping\n // ─────────────────────────────────────────────────────────\n createRotateScope(documentId) {\n return {\n setRotation: (rotation) => this.setRotationForDocument(rotation, documentId),\n getRotation: () => this.getRotationForDocument(documentId),\n rotateForward: () => this.rotateForward(documentId),\n rotateBackward: () => this.rotateBackward(documentId),\n onRotateChange: (listener) => this.rotate$.on((event) => {\n if (event.documentId === documentId) listener(event.rotation);\n })\n };\n }\n // ─────────────────────────────────────────────────────────\n // State Helpers\n // ─────────────────────────────────────────────────────────\n getDocumentState(documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n return this.state.documents[id] ?? null;\n }\n getDocumentStateOrThrow(documentId) {\n const state = this.getDocumentState(documentId);\n if (!state) {\n throw new Error(`Rotation state not found for document: ${documentId ?? \"active\"}`);\n }\n return state;\n }\n // ─────────────────────────────────────────────────────────\n // Core Operations\n // ─────────────────────────────────────────────────────────\n setRotationForDocument(rotation, documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const coreDoc = this.coreState.core.documents[id];\n if (!(coreDoc == null ? void 0 : coreDoc.document)) {\n throw new Error(`Document ${id} not loaded`);\n }\n this.dispatch(setRotation(id, rotation));\n this.dispatchCoreAction(setRotation$1(rotation, id));\n this.rotate$.emit({\n documentId: id,\n rotation\n });\n }\n getRotationForDocument(documentId) {\n return this.getDocumentStateOrThrow(documentId).rotation;\n }\n rotateForward(documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const currentRotation = this.getRotationForDocument(id);\n const nextRotation = getNextRotation(currentRotation);\n this.setRotationForDocument(nextRotation, id);\n }\n rotateBackward(documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const currentRotation = this.getRotationForDocument(id);\n const prevRotation = getPreviousRotation(currentRotation);\n this.setRotationForDocument(prevRotation, id);\n }\n getMatrixAsString(options) {\n return getRotationMatrixString(options.rotation, options.width, options.height);\n }\n // ─────────────────────────────────────────────────────────\n // Store Update Handlers\n // ─────────────────────────────────────────────────────────\n onStoreUpdated(prevState, newState) {\n for (const documentId in newState.documents) {\n const prevDoc = prevState.documents[documentId];\n const newDoc = newState.documents[documentId];\n if ((prevDoc == null ? void 0 : prevDoc.rotation) !== newDoc.rotation) {\n this.logger.debug(\n \"RotatePlugin\",\n \"RotationChanged\",\n `Rotation changed for document ${documentId}: ${(prevDoc == null ? void 0 : prevDoc.rotation) ?? 0} -> ${newDoc.rotation}`\n );\n }\n }\n }\n // ─────────────────────────────────────────────────────────\n // Lifecycle\n // ─────────────────────────────────────────────────────────\n async initialize(_config) {\n this.logger.info(\"RotatePlugin\", \"Initialize\", \"Rotate plugin initialized\");\n }\n async destroy() {\n this.rotate$.clear();\n super.destroy();\n }\n};\n_RotatePlugin.id = \"rotate\";\nlet RotatePlugin = _RotatePlugin;\nconst initialDocumentState = {\n rotation: 0\n};\nconst initialState = {\n documents: {},\n activeDocumentId: null\n};\nconst rotateReducer = (state = initialState, action) => {\n switch (action.type) {\n case INIT_ROTATE_STATE: {\n const { documentId, state: docState } = action.payload;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: docState\n },\n // Set as active if no active document\n activeDocumentId: state.activeDocumentId ?? documentId\n };\n }\n case CLEANUP_ROTATE_STATE: {\n const documentId = action.payload;\n const { [documentId]: removed, ...remainingDocs } = state.documents;\n return {\n ...state,\n documents: remainingDocs,\n activeDocumentId: state.activeDocumentId === documentId ? null : state.activeDocumentId\n };\n }\n case SET_ACTIVE_ROTATE_DOCUMENT: {\n return {\n ...state,\n activeDocumentId: action.payload\n };\n }\n case SET_ROTATION: {\n const { documentId, rotation } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...docState,\n rotation\n }\n }\n };\n }\n default:\n return state;\n }\n};\nconst RotatePluginPackage = {\n manifest,\n create: (registry, config) => new RotatePlugin(ROTATE_PLUGIN_ID, registry, config),\n reducer: rotateReducer,\n initialState\n};\nexport {\n CLEANUP_ROTATE_STATE,\n INIT_ROTATE_STATE,\n ROTATE_PLUGIN_ID,\n RotatePlugin,\n RotatePluginPackage,\n SET_ACTIVE_ROTATE_DOCUMENT,\n SET_ROTATION,\n cleanupRotateState,\n getNextRotation,\n getPreviousRotation,\n getRotationMatrix,\n getRotationMatrixString,\n initRotateState,\n initialDocumentState,\n initialState,\n manifest,\n rotateReducer,\n setActiveRotateDocument,\n setRotation\n};\n//# sourceMappingURL=index.js.map\n","import { useCapability, usePlugin, useDocumentState } from \"@embedpdf/core/react\";\nimport { initialDocumentState, RotatePlugin } from \"@embedpdf/plugin-rotate\";\nexport * from \"@embedpdf/plugin-rotate\";\nimport { useState, useEffect } from \"react\";\nimport { jsx } from \"react/jsx-runtime\";\nconst useRotatePlugin = () => usePlugin(RotatePlugin.id);\nconst useRotateCapability = () => useCapability(RotatePlugin.id);\nconst useRotate = (documentId) => {\n const { provides } = useRotateCapability();\n const [rotation, setRotation] = useState(initialDocumentState.rotation);\n useEffect(() => {\n if (!provides) return;\n const scope = provides.forDocument(documentId);\n setRotation(scope.getRotation());\n return scope.onRotateChange((newRotation) => {\n setRotation(newRotation);\n });\n }, [provides, documentId]);\n return {\n rotation,\n provides: (provides == null ? void 0 : provides.forDocument(documentId)) ?? null\n };\n};\nfunction Rotate({\n children,\n documentId,\n pageIndex,\n rotation: rotationOverride,\n scale: scaleOverride,\n style,\n ...props\n}) {\n var _a, _b, _c, _d;\n const { plugin: rotatePlugin } = useRotatePlugin();\n const documentState = useDocumentState(documentId);\n const page = (_b = (_a = documentState == null ? void 0 : documentState.document) == null ? void 0 : _a.pages) == null ? void 0 : _b[pageIndex];\n const width = ((_c = page == null ? void 0 : page.size) == null ? void 0 : _c.width) ?? 0;\n const height = ((_d = page == null ? void 0 : page.size) == null ? void 0 : _d.height) ?? 0;\n const pageRotation = (page == null ? void 0 : page.rotation) ?? 0;\n const docRotation = (documentState == null ? void 0 : documentState.rotation) ?? 0;\n const rotation = rotationOverride !== void 0 ? rotationOverride : (pageRotation + docRotation) % 4;\n const scale = scaleOverride ?? (documentState == null ? void 0 : documentState.scale) ?? 1;\n const matrix = (rotatePlugin == null ? void 0 : rotatePlugin.getMatrixAsString({\n width: width * scale,\n height: height * scale,\n rotation\n })) ?? \"matrix(1, 0, 0, 1, 0, 0)\";\n if (!page) return null;\n return /* @__PURE__ */ jsx(\n \"div\",\n {\n ...props,\n style: {\n position: \"absolute\",\n transformOrigin: \"0 0\",\n transform: matrix,\n ...style\n },\n children\n }\n );\n}\nexport {\n Rotate,\n useRotate,\n useRotateCapability,\n useRotatePlugin\n};\n//# sourceMappingURL=index.js.map\n","import { BasePlugin, createBehaviorEmitter } from \"@embedpdf/core\";\nimport { InteractionManagerPlugin } from \"@embedpdf/plugin-interaction-manager\";\nimport { ViewportPlugin } from \"@embedpdf/plugin-viewport\";\nconst INIT_PAN_STATE = \"PAN/INIT_STATE\";\nconst CLEANUP_PAN_STATE = \"PAN/CLEANUP_STATE\";\nconst SET_ACTIVE_PAN_DOCUMENT = \"PAN/SET_ACTIVE_DOCUMENT\";\nconst SET_PAN_MODE = \"PAN/SET_PAN_MODE\";\nfunction initPanState(documentId, state) {\n return { type: INIT_PAN_STATE, payload: { documentId, state } };\n}\nfunction cleanupPanState(documentId) {\n return { type: CLEANUP_PAN_STATE, payload: documentId };\n}\nfunction setActivePanDocument(documentId) {\n return { type: SET_ACTIVE_PAN_DOCUMENT, payload: documentId };\n}\nfunction setPanMode(documentId, isPanMode) {\n return { type: SET_PAN_MODE, payload: { documentId, isPanMode } };\n}\nconst _PanPlugin = class _PanPlugin extends BasePlugin {\n constructor(id, registry, config) {\n var _a, _b, _c;\n super(id, registry);\n this.panMode$ = createBehaviorEmitter();\n this.documentHandlers = /* @__PURE__ */ new Map();\n this.config = config;\n this.interactionManager = (_a = registry.getPlugin(InteractionManagerPlugin.id)) == null ? void 0 : _a.provides();\n this.viewport = (_b = registry.getPlugin(ViewportPlugin.id)) == null ? void 0 : _b.provides();\n if (this.interactionManager) {\n this.interactionManager.registerMode({\n id: \"panMode\",\n scope: \"global\",\n exclusive: false,\n cursor: \"grab\",\n wantsRawTouch: false\n });\n (_c = this.interactionManager) == null ? void 0 : _c.onModeChange((state) => {\n const isPanMode = state.activeMode === \"panMode\";\n const docState = this.getDocumentState(state.documentId);\n if (docState && docState.isPanMode !== isPanMode) {\n this.dispatch(setPanMode(state.documentId, isPanMode));\n }\n });\n }\n }\n // ─────────────────────────────────────────────────────────\n // Document Lifecycle Hooks (from BasePlugin)\n // ─────────────────────────────────────────────────────────\n onDocumentLoadingStarted(documentId) {\n const docState = {\n isPanMode: false\n };\n this.dispatch(initPanState(documentId, docState));\n this.registerPanHandlersForDocument(documentId);\n if (this.config.defaultMode === \"always\") {\n this.makePanDefault(true);\n }\n this.logger.debug(\n \"PanPlugin\",\n \"DocumentOpened\",\n `Initialized pan state for document: ${documentId}`\n );\n }\n onDocumentClosed(documentId) {\n const cleanup = this.documentHandlers.get(documentId);\n if (cleanup) {\n cleanup();\n this.documentHandlers.delete(documentId);\n }\n this.dispatch(cleanupPanState(documentId));\n this.logger.debug(\n \"PanPlugin\",\n \"DocumentClosed\",\n `Cleaned up pan state for document: ${documentId}`\n );\n }\n // ─────────────────────────────────────────────────────────\n // Capability\n // ─────────────────────────────────────────────────────────\n buildCapability() {\n return {\n // Active document operations\n enablePan: () => this.enablePan(),\n disablePan: () => this.disablePan(),\n togglePan: () => this.togglePan(),\n makePanDefault: (autoActivate) => this.makePanDefault(autoActivate),\n isPanMode: () => this.isPanMode(),\n // Document-scoped operations\n forDocument: (documentId) => this.createPanScope(documentId),\n // Events\n onPanModeChange: this.panMode$.on\n };\n }\n // ─────────────────────────────────────────────────────────\n // Document Scoping\n // ─────────────────────────────────────────────────────────\n createPanScope(documentId) {\n return {\n enablePan: () => this.enablePan(documentId),\n disablePan: () => this.disablePan(documentId),\n togglePan: () => this.togglePan(documentId),\n isPanMode: () => this.isPanMode(documentId),\n onPanModeChange: (listener) => this.panMode$.on((event) => {\n if (event.documentId === documentId) listener(event.isPanMode);\n })\n };\n }\n // ─────────────────────────────────────────────────────────\n // State Helpers\n // ─────────────────────────────────────────────────────────\n getDocumentState(documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n return this.state.documents[id] ?? null;\n }\n getDocumentStateOrThrow(documentId) {\n const state = this.getDocumentState(documentId);\n if (!state) {\n throw new Error(`Pan state not found for document: ${documentId ?? \"active\"}`);\n }\n return state;\n }\n // ─────────────────────────────────────────────────────────\n // Core Operations\n // ─────────────────────────────────────────────────────────\n enablePan(documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n this.interactionManager.forDocument(id).activate(\"panMode\");\n }\n disablePan(documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n this.interactionManager.forDocument(id).activateDefaultMode();\n }\n togglePan(documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const scope = this.interactionManager.forDocument(id);\n if (scope.getActiveMode() === \"panMode\") {\n scope.activateDefaultMode();\n } else {\n scope.activate(\"panMode\");\n }\n }\n makePanDefault(autoActivate = true) {\n if (!this.interactionManager) return;\n this.interactionManager.setDefaultMode(\"panMode\");\n if (autoActivate) {\n this.interactionManager.activateDefaultMode();\n }\n }\n isPanMode(documentId) {\n return this.getDocumentStateOrThrow(documentId).isPanMode;\n }\n // ─────────────────────────────────────────────────────────\n // Pan Handlers Registration\n // ─────────────────────────────────────────────────────────\n registerPanHandlersForDocument(documentId) {\n if (!this.interactionManager || !this.viewport) return;\n let dragState = null;\n const interactionScope = this.interactionManager.forDocument(documentId);\n const viewportScope = this.viewport.forDocument(documentId);\n const handlers = {\n onMouseDown: (_, pe) => {\n const metrics = viewportScope.getMetrics();\n dragState = {\n startX: pe.clientX,\n startY: pe.clientY,\n startLeft: metrics.scrollLeft,\n startTop: metrics.scrollTop\n };\n interactionScope.setCursor(\"panMode\", \"grabbing\", 10);\n },\n onMouseMove: (_, pe) => {\n if (!dragState) return;\n const dx = pe.clientX - dragState.startX;\n const dy = pe.clientY - dragState.startY;\n viewportScope.scrollTo({\n x: dragState.startLeft - dx,\n y: dragState.startTop - dy\n });\n },\n onMouseUp: () => {\n if (!dragState) return;\n dragState = null;\n interactionScope.removeCursor(\"panMode\");\n },\n onMouseLeave: () => {\n if (!dragState) return;\n dragState = null;\n interactionScope.removeCursor(\"panMode\");\n },\n onMouseCancel: () => {\n if (!dragState) return;\n dragState = null;\n interactionScope.removeCursor(\"panMode\");\n }\n };\n const unregister = this.interactionManager.registerHandlers({\n documentId,\n modeId: \"panMode\",\n handlers\n });\n this.documentHandlers.set(documentId, unregister);\n }\n // ─────────────────────────────────────────────────────────\n // Store Update Handlers\n // ─────────────────────────────────────────────────────────\n onStoreUpdated(prevState, newState) {\n for (const documentId in newState.documents) {\n const prevDoc = prevState.documents[documentId];\n const newDoc = newState.documents[documentId];\n if ((prevDoc == null ? void 0 : prevDoc.isPanMode) !== newDoc.isPanMode) {\n this.panMode$.emit({\n documentId,\n isPanMode: newDoc.isPanMode\n });\n this.logger.debug(\n \"PanPlugin\",\n \"PanModeChanged\",\n `Pan mode changed for document ${documentId}: ${(prevDoc == null ? void 0 : prevDoc.isPanMode) ?? false} -> ${newDoc.isPanMode}`\n );\n }\n }\n }\n // ─────────────────────────────────────────────────────────\n // Lifecycle\n // ─────────────────────────────────────────────────────────\n async initialize(_) {\n this.logger.info(\"PanPlugin\", \"Initialize\", \"Pan plugin initialized\");\n }\n async destroy() {\n this.documentHandlers.forEach((cleanup) => cleanup());\n this.documentHandlers.clear();\n this.panMode$.clear();\n await super.destroy();\n }\n};\n_PanPlugin.id = \"pan\";\nlet PanPlugin = _PanPlugin;\nconst PAN_PLUGIN_ID = \"pan\";\nconst manifest = {\n id: PAN_PLUGIN_ID,\n name: \"Pan Plugin\",\n version: \"1.0.0\",\n provides: [\"pan\"],\n requires: [\"interaction-manager\", \"viewport\"],\n optional: [],\n defaultConfig: {\n defaultMode: \"mobile\"\n }\n};\nconst initialDocumentState = {\n isPanMode: false\n};\nconst initialState = {\n documents: {},\n activeDocumentId: null\n};\nconst panReducer = (state = initialState, action) => {\n switch (action.type) {\n case INIT_PAN_STATE: {\n const { documentId, state: docState } = action.payload;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: docState\n },\n // Set as active if no active document\n activeDocumentId: state.activeDocumentId ?? documentId\n };\n }\n case CLEANUP_PAN_STATE: {\n const documentId = action.payload;\n const { [documentId]: removed, ...remainingDocs } = state.documents;\n return {\n ...state,\n documents: remainingDocs,\n activeDocumentId: state.activeDocumentId === documentId ? null : state.activeDocumentId\n };\n }\n case SET_ACTIVE_PAN_DOCUMENT: {\n return {\n ...state,\n activeDocumentId: action.payload\n };\n }\n case SET_PAN_MODE: {\n const { documentId, isPanMode } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...docState,\n isPanMode\n }\n }\n };\n }\n default:\n return state;\n }\n};\nconst PanPluginPackage = {\n manifest,\n create: (registry, config) => new PanPlugin(PAN_PLUGIN_ID, registry, config),\n reducer: panReducer,\n initialState\n};\nexport {\n CLEANUP_PAN_STATE,\n INIT_PAN_STATE,\n PAN_PLUGIN_ID,\n PanPlugin,\n PanPluginPackage,\n SET_ACTIVE_PAN_DOCUMENT,\n SET_PAN_MODE,\n cleanupPanState,\n initPanState,\n initialDocumentState,\n initialState,\n manifest,\n panReducer,\n setActivePanDocument,\n setPanMode\n};\n//# sourceMappingURL=index.js.map\n","import { createPluginPackage } from \"@embedpdf/core\";\nimport { PanPlugin, initialDocumentState, PanPluginPackage as PanPluginPackage$1 } from \"@embedpdf/plugin-pan\";\nexport * from \"@embedpdf/plugin-pan\";\nimport { useState, useEffect } from \"react\";\nimport { useCapability, usePlugin } from \"@embedpdf/core/react\";\nconst usePanPlugin = () => usePlugin(PanPlugin.id);\nconst usePanCapability = () => useCapability(PanPlugin.id);\nconst usePan = (documentId) => {\n const { provides } = usePanCapability();\n const [isPanning, setIsPanning] = useState(initialDocumentState.isPanMode);\n useEffect(() => {\n if (!provides) return;\n const scope = provides.forDocument(documentId);\n setIsPanning(scope.isPanMode());\n return scope.onPanModeChange((isPan) => {\n setIsPanning(isPan);\n });\n }, [provides, documentId]);\n return {\n provides: (provides == null ? void 0 : provides.forDocument(documentId)) ?? null,\n isPanning\n };\n};\nconst PanMode = () => {\n const { provides: pan } = usePanCapability();\n const { plugin: panPlugin } = usePanPlugin();\n useEffect(() => {\n var _a;\n if (!pan || !panPlugin) return;\n const mode = ((_a = panPlugin.config) == null ? void 0 : _a.defaultMode) ?? \"never\";\n const SUPPORT_TOUCH = typeof window !== \"undefined\" && (\"ontouchstart\" in window || navigator.maxTouchPoints > 0);\n if (mode === \"mobile\" && SUPPORT_TOUCH) {\n pan.makePanDefault();\n }\n }, [pan, panPlugin]);\n return null;\n};\nconst PanPluginPackage = createPluginPackage(PanPluginPackage$1).addUtility(PanMode).build();\nexport {\n PanMode,\n PanPluginPackage,\n usePan,\n usePanCapability,\n usePanPlugin\n};\n//# sourceMappingURL=index.js.map\n","import { BasePlugin, createScopedEmitter, REFRESH_PAGES } from \"@embedpdf/core\";\nimport { ignore } from \"@embedpdf/models\";\nconst THUMBNAIL_PLUGIN_ID = \"thumbnail\";\nconst manifest = {\n id: THUMBNAIL_PLUGIN_ID,\n name: \"Thumbnail Plugin\",\n version: \"1.0.0\",\n provides: [\"thumbnail\"],\n requires: [\"render\"],\n optional: [\"scroll\"],\n defaultConfig: {\n width: 150,\n gap: 10,\n buffer: 3,\n labelHeight: 16,\n autoScroll: true,\n scrollBehavior: \"smooth\",\n imagePadding: 0,\n paddingY: 0\n }\n};\nconst INIT_THUMBNAIL_STATE = \"THUMBNAIL/INIT_STATE\";\nconst CLEANUP_THUMBNAIL_STATE = \"THUMBNAIL/CLEANUP_STATE\";\nconst SET_ACTIVE_DOCUMENT = \"THUMBNAIL/SET_ACTIVE_DOCUMENT\";\nconst SET_WINDOW_STATE = \"THUMBNAIL/SET_WINDOW_STATE\";\nconst UPDATE_VIEWPORT_METRICS = \"THUMBNAIL/UPDATE_VIEWPORT_METRICS\";\nfunction initThumbnailState(documentId, state) {\n return { type: INIT_THUMBNAIL_STATE, payload: { documentId, state } };\n}\nfunction cleanupThumbnailState(documentId) {\n return { type: CLEANUP_THUMBNAIL_STATE, payload: documentId };\n}\nfunction setActiveDocument(documentId) {\n return { type: SET_ACTIVE_DOCUMENT, payload: documentId };\n}\nfunction setWindowState(documentId, window) {\n return { type: SET_WINDOW_STATE, payload: { documentId, window } };\n}\nfunction updateViewportMetrics(documentId, scrollY, viewportH) {\n return { type: UPDATE_VIEWPORT_METRICS, payload: { documentId, scrollY, viewportH } };\n}\nconst initialDocumentState = {\n thumbs: [],\n window: null,\n viewportH: 0,\n scrollY: 0\n};\nconst initialState = {\n documents: {},\n activeDocumentId: null\n};\nconst thumbnailReducer = (state = initialState, action) => {\n switch (action.type) {\n case INIT_THUMBNAIL_STATE: {\n const { documentId, state: docState } = action.payload;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: docState\n },\n // Set as active if no active document\n activeDocumentId: state.activeDocumentId ?? documentId\n };\n }\n case CLEANUP_THUMBNAIL_STATE: {\n const documentId = action.payload;\n const { [documentId]: removed, ...remainingDocs } = state.documents;\n return {\n ...state,\n documents: remainingDocs,\n activeDocumentId: state.activeDocumentId === documentId ? null : state.activeDocumentId\n };\n }\n case SET_ACTIVE_DOCUMENT: {\n return {\n ...state,\n activeDocumentId: action.payload\n };\n }\n case SET_WINDOW_STATE: {\n const { documentId, window } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...docState,\n window\n }\n }\n };\n }\n case UPDATE_VIEWPORT_METRICS: {\n const { documentId, scrollY, viewportH } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...docState,\n scrollY,\n viewportH\n }\n }\n };\n }\n default:\n return state;\n }\n};\nconst _ThumbnailPlugin = class _ThumbnailPlugin extends BasePlugin {\n constructor(id, registry, cfg) {\n var _a;\n super(id, registry);\n this.cfg = cfg;\n this.scrollCapability = null;\n this.taskCaches = /* @__PURE__ */ new Map();\n this.canAutoScroll = /* @__PURE__ */ new Map();\n this.window$ = createScopedEmitter(\n (documentId, window) => ({ documentId, window })\n );\n this.scrollTo$ = createScopedEmitter(\n (documentId, options) => ({ documentId, options })\n );\n this.refreshPages$ = createScopedEmitter(\n (documentId, pages) => ({ documentId, pages }),\n { cache: false }\n );\n this.renderCapability = this.registry.getPlugin(\"render\").provides();\n this.scrollCapability = ((_a = this.registry.getPlugin(\"scroll\")) == null ? void 0 : _a.provides()) ?? null;\n this.coreStore.onAction(REFRESH_PAGES, (action) => {\n const documentId = action.payload.documentId ?? this.getActiveDocumentId();\n const pages = action.payload.pageIndexes;\n this.refreshPages$.emit(documentId, pages);\n const taskCache = this.taskCaches.get(documentId);\n if (taskCache) {\n for (const pageIndex of pages) {\n taskCache.delete(pageIndex);\n }\n }\n });\n if (this.scrollCapability && this.cfg.autoScroll !== false) {\n this.scrollCapability.onPageChangeState(({ documentId, state }) => {\n this.canAutoScroll.set(documentId, !state.isChanging);\n if (!state.isChanging) {\n this.scrollToThumb(state.targetPage - 1, documentId);\n }\n });\n this.scrollCapability.onPageChange(({ documentId, pageNumber }) => {\n if (this.canAutoScroll.get(documentId) !== false) {\n this.scrollToThumb(pageNumber - 1, documentId);\n }\n });\n }\n }\n // ─────────────────────────────────────────────────────────\n // Document Lifecycle Hooks (from BasePlugin)\n // ─────────────────────────────────────────────────────────\n onDocumentLoadingStarted(documentId) {\n this.dispatch(\n initThumbnailState(documentId, {\n ...initialDocumentState\n })\n );\n this.taskCaches.set(documentId, /* @__PURE__ */ new Map());\n this.canAutoScroll.set(documentId, true);\n this.logger.debug(\n \"ThumbnailPlugin\",\n \"DocumentOpened\",\n `Initialized thumbnail state for document: ${documentId}`\n );\n }\n onDocumentLoaded(documentId) {\n this.calculateWindowState(documentId);\n }\n onDocumentClosed(documentId) {\n this.dispatch(cleanupThumbnailState(documentId));\n const taskCache = this.taskCaches.get(documentId);\n if (taskCache) {\n taskCache.forEach((task) => {\n task.abort({\n code: \"cancelled\",\n message: \"Document closed\"\n });\n });\n taskCache.clear();\n this.taskCaches.delete(documentId);\n }\n this.canAutoScroll.delete(documentId);\n this.window$.clearScope(documentId);\n this.scrollTo$.clearScope(documentId);\n this.refreshPages$.clearScope(documentId);\n this.logger.debug(\n \"ThumbnailPlugin\",\n \"DocumentClosed\",\n `Cleaned up thumbnail state for document: ${documentId}`\n );\n }\n onRotationChanged(documentId) {\n this.calculateWindowState(documentId);\n }\n // ─────────────────────────────────────────────────────────\n // Capability\n // ─────────────────────────────────────────────────────────\n buildCapability() {\n return {\n // Active document operations\n scrollToThumb: (pageIdx) => this.scrollToThumb(pageIdx),\n renderThumb: (idx, dpr) => this.renderThumb(idx, dpr),\n updateWindow: (scrollY, viewportH) => this.updateWindow(scrollY, viewportH),\n getWindow: () => this.getWindow(),\n // Document-scoped operations\n forDocument: (documentId) => this.createThumbnailScope(documentId),\n // Events\n onWindow: this.window$.onGlobal,\n onScrollTo: this.scrollTo$.onGlobal,\n onRefreshPages: this.refreshPages$.onGlobal\n };\n }\n // ─────────────────────────────────────────────────────────\n // Document Scoping\n // ─────────────────────────────────────────────────────────\n createThumbnailScope(documentId) {\n return {\n scrollToThumb: (pageIdx) => this.scrollToThumb(pageIdx, documentId),\n renderThumb: (idx, dpr) => this.renderThumb(idx, dpr, documentId),\n updateWindow: (scrollY, viewportH) => this.updateWindow(scrollY, viewportH, documentId),\n getWindow: () => this.getWindow(documentId),\n onWindow: this.window$.forScope(documentId),\n onScrollTo: this.scrollTo$.forScope(documentId),\n onRefreshPages: this.refreshPages$.forScope(documentId)\n };\n }\n // ─────────────────────────────────────────────────────────\n // State Helpers\n // ─────────────────────────────────────────────────────────\n getDocumentState(documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n return this.state.documents[id] ?? null;\n }\n // ─────────────────────────────────────────────────────────\n // Core Operations\n // ─────────────────────────────────────────────────────────\n calculateWindowState(documentId) {\n const coreDoc = this.coreState.core.documents[documentId];\n if (!(coreDoc == null ? void 0 : coreDoc.document)) return;\n const OUTER_W = this.cfg.width ?? 120;\n const L = this.cfg.labelHeight ?? 16;\n const GAP = this.cfg.gap ?? 8;\n const P = this.cfg.imagePadding ?? 0;\n const PADDING_Y = this.cfg.paddingY ?? 0;\n const INNER_W = Math.max(1, OUTER_W - 2 * P);\n let offset = PADDING_Y;\n const thumbs = coreDoc.document.pages.map((p) => {\n const isRotated90or270 = p.rotation % 2 === 1;\n const effectiveWidth = isRotated90or270 ? p.size.height : p.size.width;\n const effectiveHeight = isRotated90or270 ? p.size.width : p.size.height;\n const ratio = effectiveHeight / effectiveWidth;\n const imgH = Math.round(INNER_W * ratio);\n const wrapH = P + imgH + P + L;\n const meta = {\n pageIndex: p.index,\n width: INNER_W,\n // bitmap width (for <img> size)\n height: imgH,\n // bitmap height (for <img> size)\n wrapperHeight: wrapH,\n // full row height used by virtualizer\n top: offset,\n // top of the row\n labelHeight: L,\n padding: P\n };\n offset += wrapH + GAP;\n return meta;\n });\n const window = {\n start: -1,\n end: -1,\n items: [],\n totalHeight: offset - GAP + PADDING_Y\n // Add bottom padding to total height\n };\n const docState = this.getDocumentState(documentId);\n if (!docState) return;\n this.dispatch(\n initThumbnailState(documentId, {\n ...docState,\n thumbs,\n window\n })\n );\n if (docState.viewportH > 0) {\n this.updateWindow(docState.scrollY, docState.viewportH, documentId);\n } else {\n this.window$.emit(documentId, window);\n }\n }\n updateWindow(scrollY, viewportH, documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const docState = this.getDocumentState(id);\n if (!docState || !docState.window || docState.thumbs.length === 0) return;\n const BUF = this.cfg.buffer ?? 3;\n this.dispatch(updateViewportMetrics(id, scrollY, viewportH));\n let low = 0, high = docState.thumbs.length - 1, first = 0;\n while (low <= high) {\n const mid = low + high >> 1;\n const m = docState.thumbs[mid];\n if (m.top + m.wrapperHeight < scrollY) low = mid + 1;\n else {\n first = mid;\n high = mid - 1;\n }\n }\n let last = first;\n const limit = scrollY + viewportH;\n while (last + 1 < docState.thumbs.length && docState.thumbs[last].top < limit) last++;\n last = Math.min(docState.thumbs.length - 1, last + BUF);\n const start = Math.max(0, first - BUF);\n if (start === docState.window.start && last === docState.window.end) return;\n const newWindow = {\n start,\n end: last,\n items: docState.thumbs.slice(start, last + 1),\n totalHeight: docState.window.totalHeight\n };\n this.dispatch(setWindowState(id, newWindow));\n this.window$.emit(id, newWindow);\n }\n getWindow(documentId) {\n const docState = this.getDocumentState(documentId);\n return (docState == null ? void 0 : docState.window) ?? null;\n }\n scrollToThumb(pageIdx, documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const docState = this.getDocumentState(id);\n if (!docState || !docState.window) return;\n const item = docState.thumbs[pageIdx];\n if (!item) return;\n const behavior = this.cfg.scrollBehavior ?? \"smooth\";\n const PADDING_Y = this.cfg.paddingY ?? 0;\n if (docState.viewportH <= 0) {\n const top2 = Math.max(PADDING_Y, item.top - item.wrapperHeight);\n this.scrollTo$.emit(id, { top: top2, behavior });\n return;\n }\n const margin = 8;\n const top = item.top;\n const bottom = item.top + item.wrapperHeight;\n const needsUp = top < docState.scrollY + margin + PADDING_Y;\n const needsDown = bottom > docState.scrollY + docState.viewportH - margin;\n if (needsUp) {\n this.scrollTo$.emit(id, {\n top: Math.max(0, top - PADDING_Y),\n behavior\n });\n } else if (needsDown) {\n this.scrollTo$.emit(id, {\n top: Math.max(0, bottom - docState.viewportH + PADDING_Y),\n behavior\n });\n }\n }\n renderThumb(idx, dpr, documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const taskCache = this.taskCaches.get(id);\n if (!taskCache) {\n throw new Error(`Task cache not found for document: ${id}`);\n }\n if (taskCache.has(idx)) return taskCache.get(idx);\n const coreDoc = this.coreState.core.documents[id];\n if (!(coreDoc == null ? void 0 : coreDoc.document)) {\n throw new Error(`Document not found: ${id}`);\n }\n const page = coreDoc.document.pages[idx];\n if (!page) {\n throw new Error(`Page ${idx} not found in document: ${id}`);\n }\n const OUTER_W = this.cfg.width ?? 120;\n const P = this.cfg.imagePadding ?? 0;\n const INNER_W = Math.max(1, OUTER_W - 2 * P);\n const scale = INNER_W / page.size.width;\n const task = this.renderCapability.forDocument(id).renderPageRect({\n pageIndex: idx,\n rect: { origin: { x: 0, y: 0 }, size: page.size },\n options: {\n scaleFactor: scale,\n dpr,\n rotation: page.rotation\n }\n });\n taskCache.set(idx, task);\n task.wait(ignore, () => taskCache.delete(idx));\n return task;\n }\n // ─────────────────────────────────────────────────────────\n // Lifecycle\n // ─────────────────────────────────────────────────────────\n async initialize() {\n this.logger.info(\"ThumbnailPlugin\", \"Initialize\", \"Thumbnail plugin initialized\");\n }\n async destroy() {\n this.window$.clear();\n this.refreshPages$.clear();\n this.scrollTo$.clear();\n this.taskCaches.forEach((cache) => {\n cache.forEach((task) => {\n task.abort({\n code: \"cancelled\",\n message: \"Plugin destroyed\"\n });\n });\n cache.clear();\n });\n this.taskCaches.clear();\n this.canAutoScroll.clear();\n super.destroy();\n }\n};\n_ThumbnailPlugin.id = \"thumbnail\";\nlet ThumbnailPlugin = _ThumbnailPlugin;\nconst ThumbnailPluginPackage = {\n manifest,\n create: (registry, config) => new ThumbnailPlugin(THUMBNAIL_PLUGIN_ID, registry, config),\n reducer: thumbnailReducer,\n initialState\n};\nexport {\n CLEANUP_THUMBNAIL_STATE,\n INIT_THUMBNAIL_STATE,\n SET_ACTIVE_DOCUMENT,\n SET_WINDOW_STATE,\n THUMBNAIL_PLUGIN_ID,\n ThumbnailPlugin,\n ThumbnailPluginPackage,\n UPDATE_VIEWPORT_METRICS,\n cleanupThumbnailState,\n initThumbnailState,\n initialDocumentState,\n initialState,\n manifest,\n setActiveDocument,\n setWindowState,\n thumbnailReducer,\n updateViewportMetrics\n};\n//# sourceMappingURL=index.js.map\n","import { useCapability, usePlugin } from \"@embedpdf/core/react\";\nimport { ThumbnailPlugin } from \"@embedpdf/plugin-thumbnail\";\nexport * from \"@embedpdf/plugin-thumbnail\";\nimport { jsx } from \"react/jsx-runtime\";\nimport { useRef, useState, useEffect } from \"react\";\nimport { ignore, PdfErrorCode } from \"@embedpdf/models\";\nconst useThumbnailPlugin = () => usePlugin(ThumbnailPlugin.id);\nconst useThumbnailCapability = () => useCapability(ThumbnailPlugin.id);\nfunction ThumbnailsPane({ documentId, style, children, ...props }) {\n const { plugin: thumbnailPlugin } = useThumbnailPlugin();\n const viewportRef = useRef(null);\n const [windowData, setWindowData] = useState({ window: null, docId: null });\n const window2 = windowData.docId === documentId ? windowData.window : null;\n useEffect(() => {\n if (!thumbnailPlugin) return;\n const scope = thumbnailPlugin.provides().forDocument(documentId);\n const initialWindow = scope.getWindow();\n if (initialWindow) {\n setWindowData({ window: initialWindow, docId: documentId });\n }\n const unsubscribe = scope.onWindow((newWindow) => {\n setWindowData({ window: newWindow, docId: documentId });\n });\n return () => {\n unsubscribe();\n setWindowData({ window: null, docId: null });\n };\n }, [thumbnailPlugin, documentId]);\n useEffect(() => {\n const vp = viewportRef.current;\n if (!vp || !thumbnailPlugin) return;\n const scope = thumbnailPlugin.provides().forDocument(documentId);\n const onScroll = () => scope.updateWindow(vp.scrollTop, vp.clientHeight);\n vp.addEventListener(\"scroll\", onScroll);\n return () => vp.removeEventListener(\"scroll\", onScroll);\n }, [thumbnailPlugin, documentId]);\n useEffect(() => {\n const vp = viewportRef.current;\n if (!vp || !thumbnailPlugin) return;\n const scope = thumbnailPlugin.provides().forDocument(documentId);\n const resizeObserver = new ResizeObserver(() => {\n scope.updateWindow(vp.scrollTop, vp.clientHeight);\n });\n resizeObserver.observe(vp);\n return () => resizeObserver.disconnect();\n }, [thumbnailPlugin, documentId]);\n useEffect(() => {\n const vp = viewportRef.current;\n if (!vp || !thumbnailPlugin) return;\n const scope = thumbnailPlugin.provides().forDocument(documentId);\n scope.updateWindow(vp.scrollTop, vp.clientHeight);\n }, [window2, thumbnailPlugin, documentId]);\n useEffect(() => {\n const vp = viewportRef.current;\n if (!vp || !thumbnailPlugin || !window2) return;\n const scope = thumbnailPlugin.provides().forDocument(documentId);\n return scope.onScrollTo(({ top, behavior }) => {\n vp.scrollTo({ top, behavior });\n });\n }, [thumbnailPlugin, documentId, !!window2]);\n const paddingY = (thumbnailPlugin == null ? void 0 : thumbnailPlugin.cfg.paddingY) ?? 0;\n return /* @__PURE__ */ jsx(\n \"div\",\n {\n ref: viewportRef,\n style: {\n overflowY: \"auto\",\n position: \"relative\",\n paddingTop: paddingY,\n paddingBottom: paddingY,\n height: \"100%\",\n ...style\n },\n ...props,\n children: /* @__PURE__ */ jsx(\"div\", { style: { height: (window2 == null ? void 0 : window2.totalHeight) ?? 0, position: \"relative\" }, children: window2 == null ? void 0 : window2.items.map((m) => children(m)) })\n }\n );\n}\nfunction ThumbImg({ documentId, meta, style, ...props }) {\n const { provides: thumbs } = useThumbnailCapability();\n const { plugin: thumbnailPlugin } = useThumbnailPlugin();\n const [url, setUrl] = useState();\n const urlRef = useRef(null);\n const [refreshTick, setRefreshTick] = useState(0);\n useEffect(() => {\n if (!thumbnailPlugin) return;\n const scope = thumbnailPlugin.provides().forDocument(documentId);\n return scope.onRefreshPages((pages) => {\n if (pages.includes(meta.pageIndex)) {\n setRefreshTick((tick) => tick + 1);\n }\n });\n }, [thumbnailPlugin, documentId, meta.pageIndex]);\n useEffect(() => {\n const scope = thumbs == null ? void 0 : thumbs.forDocument(documentId);\n const task = scope == null ? void 0 : scope.renderThumb(meta.pageIndex, window.devicePixelRatio);\n task == null ? void 0 : task.wait((blob) => {\n const objectUrl = URL.createObjectURL(blob);\n urlRef.current = objectUrl;\n setUrl(objectUrl);\n }, ignore);\n return () => {\n if (urlRef.current) {\n URL.revokeObjectURL(urlRef.current);\n urlRef.current = null;\n } else {\n task == null ? void 0 : task.abort({\n code: PdfErrorCode.Cancelled,\n message: \"canceled render task\"\n });\n }\n };\n }, [thumbs, documentId, meta.pageIndex, refreshTick]);\n const handleImageLoad = () => {\n if (urlRef.current) {\n URL.revokeObjectURL(urlRef.current);\n urlRef.current = null;\n }\n };\n return url ? /* @__PURE__ */ jsx(\"img\", { src: url, onLoad: handleImageLoad, style, ...props }) : null;\n}\nexport {\n ThumbImg,\n ThumbnailsPane,\n useThumbnailCapability,\n useThumbnailPlugin\n};\n//# sourceMappingURL=index.js.map\n","import { BasePlugin, createEmitter } from \"@embedpdf/core\";\nimport { PdfPermissionFlag, PdfTaskHelper, PdfErrorCode, Task } from \"@embedpdf/models\";\nconst PRINT_PLUGIN_ID = \"print\";\nconst manifest = {\n id: PRINT_PLUGIN_ID,\n name: \"Print Plugin\",\n version: \"1.0.0\",\n provides: [\"print\"],\n requires: [],\n optional: [],\n defaultConfig: {}\n};\nconst _PrintPlugin = class _PrintPlugin extends BasePlugin {\n constructor(id, registry, _config) {\n super(id, registry);\n this.printReady$ = createEmitter();\n }\n // ─────────────────────────────────────────────────────────\n // Capability\n // ─────────────────────────────────────────────────────────\n buildCapability() {\n return {\n // Active document operations\n print: (options) => this.print(options),\n // Document-scoped operations\n forDocument: (documentId) => this.createPrintScope(documentId)\n };\n }\n // ─────────────────────────────────────────────────────────\n // Document Scoping\n // ─────────────────────────────────────────────────────────\n createPrintScope(documentId) {\n return {\n print: (options) => this.print(options, documentId)\n };\n }\n // ─────────────────────────────────────────────────────────\n // Core Operations\n // ─────────────────────────────────────────────────────────\n print(options, documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n if (!this.checkPermission(id, PdfPermissionFlag.Print)) {\n this.logger.debug(\n \"PrintPlugin\",\n \"Print\",\n `Cannot print: document ${id} lacks Print permission`\n );\n return PdfTaskHelper.reject({\n code: PdfErrorCode.Security,\n message: \"Document lacks Print permission\"\n });\n }\n const printOptions = options ?? {};\n const task = new Task();\n task.progress({ stage: \"preparing\", message: \"Preparing document...\" });\n const prepare = this.preparePrintDocument(printOptions, id);\n prepare.wait(\n (buffer) => {\n task.progress({ stage: \"document-ready\", message: \"Document prepared successfully\" });\n this.printReady$.emit({\n documentId: id,\n options: printOptions,\n buffer,\n task\n });\n },\n (error) => task.fail(error)\n );\n return task;\n }\n preparePrintDocument(options, documentId) {\n const coreDoc = this.coreState.core.documents[documentId];\n if (!(coreDoc == null ? void 0 : coreDoc.document)) {\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: `Document ${documentId} not found`\n });\n }\n return this.engine.preparePrintDocument(coreDoc.document, options);\n }\n // ─────────────────────────────────────────────────────────\n // Event Listeners\n // ─────────────────────────────────────────────────────────\n onPrintRequest(listener) {\n return this.printReady$.on(listener);\n }\n // ─────────────────────────────────────────────────────────\n // Lifecycle\n // ─────────────────────────────────────────────────────────\n async initialize(_) {\n this.logger.info(\"PrintPlugin\", \"Initialize\", \"Print plugin initialized\");\n }\n async destroy() {\n this.printReady$.clear();\n await super.destroy();\n }\n};\n_PrintPlugin.id = \"print\";\nlet PrintPlugin = _PrintPlugin;\nconst PrintPluginPackage = {\n manifest,\n create: (registry, config) => new PrintPlugin(PRINT_PLUGIN_ID, registry, config),\n reducer: () => {\n },\n initialState: {}\n};\nexport {\n PRINT_PLUGIN_ID,\n PrintPlugin,\n PrintPluginPackage,\n manifest\n};\n//# sourceMappingURL=index.js.map\n","import { createPluginPackage } from \"@embedpdf/core\";\nimport { PrintPlugin, PrintPluginPackage as PrintPluginPackage$1 } from \"@embedpdf/plugin-print\";\nexport * from \"@embedpdf/plugin-print\";\nimport { jsx } from \"react/jsx-runtime\";\nimport require$$0 from \"react-dom\";\nimport { useRef, useEffect } from \"react\";\nimport { useCapability, usePlugin } from \"@embedpdf/core/react\";\nvar client = {};\nvar hasRequiredClient;\nfunction requireClient() {\n if (hasRequiredClient) return client;\n hasRequiredClient = 1;\n var m = require$$0;\n if (process.env.NODE_ENV === \"production\") {\n client.createRoot = m.createRoot;\n client.hydrateRoot = m.hydrateRoot;\n } else {\n var i = m.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;\n client.createRoot = function(c, o) {\n i.usingClientEntryPoint = true;\n try {\n return m.createRoot(c, o);\n } finally {\n i.usingClientEntryPoint = false;\n }\n };\n client.hydrateRoot = function(c, h, o) {\n i.usingClientEntryPoint = true;\n try {\n return m.hydrateRoot(c, h, o);\n } finally {\n i.usingClientEntryPoint = false;\n }\n };\n }\n return client;\n}\nrequireClient();\nconst usePrintPlugin = () => usePlugin(PrintPlugin.id);\nconst usePrintCapability = () => useCapability(PrintPlugin.id);\nconst usePrint = (documentId) => {\n const { provides } = usePrintCapability();\n return {\n provides: (provides == null ? void 0 : provides.forDocument(documentId)) ?? null\n };\n};\nfunction PrintFrame() {\n const { provides: printCapability } = usePrintCapability();\n const { plugin: printPlugin } = usePrintPlugin();\n const iframeRef = useRef(null);\n const urlRef = useRef(null);\n useEffect(() => {\n if (!printCapability || !printPlugin) return;\n const unsubscribe = printPlugin.onPrintRequest(({ buffer, task }) => {\n const iframe = iframeRef.current;\n if (!iframe) return;\n if (urlRef.current) {\n URL.revokeObjectURL(urlRef.current);\n urlRef.current = null;\n }\n const url = URL.createObjectURL(new Blob([buffer], { type: \"application/pdf\" }));\n urlRef.current = url;\n iframe.onload = () => {\n var _a, _b;\n if (iframe.src === url) {\n task.progress({ stage: \"iframe-ready\", message: \"Ready to print\" });\n (_a = iframe.contentWindow) == null ? void 0 : _a.focus();\n (_b = iframe.contentWindow) == null ? void 0 : _b.print();\n task.progress({ stage: \"printing\", message: \"Print dialog opened\" });\n task.resolve(buffer);\n }\n };\n iframe.src = url;\n });\n return () => {\n unsubscribe();\n if (urlRef.current) {\n URL.revokeObjectURL(urlRef.current);\n }\n };\n }, [printCapability, printPlugin]);\n return /* @__PURE__ */ jsx(\n \"iframe\",\n {\n ref: iframeRef,\n style: { position: \"absolute\", display: \"none\" },\n title: \"Print Document\",\n src: \"about:blank\"\n }\n );\n}\nconst PrintPluginPackage = createPluginPackage(PrintPluginPackage$1).addUtility(PrintFrame).build();\nexport {\n PrintFrame,\n PrintPluginPackage,\n usePrint,\n usePrintCapability,\n usePrintPlugin\n};\n//# sourceMappingURL=index.js.map\n","export default import.meta.ROLLDOWN_FILE_URL_FKNdLzKnlftW3t_gzo81yw","import { useEffect, useMemo, useState, useId } from 'react';\nimport type { CSSProperties, ReactNode } from 'react';\nimport { createPluginRegistration } from '@embedpdf/core';\nimport { EmbedPDF } from '@embedpdf/core/react';\nimport { usePdfiumEngine } from '@embedpdf/engines/react';\nimport { DocumentContent, DocumentManagerPluginPackage, useDocumentManagerCapability } from '@embedpdf/plugin-document-manager/react';\nimport { Viewport, ViewportPluginPackage } from '@embedpdf/plugin-viewport/react';\nimport { Scroller, ScrollPluginPackage, useScroll } from '@embedpdf/plugin-scroll/react';\nimport { RenderLayer, RenderPluginPackage } from '@embedpdf/plugin-render/react';\nimport { ZoomPluginPackage, ZoomMode, useZoom } from '@embedpdf/plugin-zoom/react';\nimport type { ZoomLevel } from '@embedpdf/plugin-zoom';\nimport { SearchPluginPackage, SearchLayer, useSearch } from '@embedpdf/plugin-search/react';\nimport { SelectionPluginPackage, SelectionLayer } from '@embedpdf/plugin-selection/react';\nimport { InteractionManagerPluginPackage, PagePointerProvider } from '@embedpdf/plugin-interaction-manager/react';\nimport { RotatePluginPackage, useRotate } from '@embedpdf/plugin-rotate/react';\nimport { PanPluginPackage, PanMode, usePan } from '@embedpdf/plugin-pan/react';\nimport { ThumbnailPluginPackage, ThumbnailsPane, ThumbImg } from '@embedpdf/plugin-thumbnail/react';\nimport type { ThumbMeta } from '@embedpdf/plugin-thumbnail';\nimport { PrintPluginPackage, usePrint } from '@embedpdf/plugin-print/react';\nimport pdfiumWasmUrl from '@embedpdf/pdfium/pdfium.wasm?url';\nimport { Button, Select, Typography } from '@/ui';\nimport { ChevronLeft, ChevronRight, Download, Hand, Maximize2, Minimize2, PanelLeft, Printer, RotateCw, X } from 'lucide-react';\nimport { FileTypeIcon } from '@/components/FileTypeIcon';\nimport { useThemeController } from '@/providers/theme-controller';\n\nconst { Text } = Typography;\nconst ZOOM_OPTIONS = [\n { value: ZoomMode.Automatic, label: '自动缩放' },\n { value: ZoomMode.FitPage, label: '适合页高' },\n { value: ZoomMode.FitWidth, label: '适合页宽' },\n { value: '1', label: '实际大小' },\n];\ninterface PDFPreviewPanelProps {\n readonly file: File;\n readonly onClose: () => void;\n readonly fullscreen?: boolean;\n readonly onToggleFullscreen?: () => void;\n readonly style?: CSSProperties;\n readonly actions?: ReactNode;\n}\n\nfunction PDFDocument({ documentId, url, fileName }: Readonly<{ documentId: string; url: string; fileName: string }>) {\n const { provides: scroll, state: pages } = useScroll(documentId);\n const { provides: zoom } = useZoom(documentId);\n const { provides: search, state: results } = useSearch(documentId);\n const { provides: rotate } = useRotate(documentId);\n const { provides: pan, isPanning } = usePan(documentId);\n const { provides: print } = usePrint(documentId);\n const zoomLabelId = useId();\n const [zoomLevel, setZoomLevel] = useState<ZoomLevel>(ZoomMode.FitWidth);\n const [query, setQuery] = useState('');\n const [thumbnails, setThumbnails] = useState(false);\n return <>\n <div role=\"toolbar\" aria-label=\"PDF 工具栏\" style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 6, padding: 8, borderBottom: '1px solid var(--color-border)' }}>\n <Button aria-label=\"缩略图\" theme=\"borderless\" icon={<PanelLeft size={16}/>} onClick={() => setThumbnails(!thumbnails)}/>\n <Button aria-label=\"上一页\" disabled={pages.currentPage <= 1} theme=\"borderless\" icon={<ChevronLeft size={16}/>} onClick={() => scroll?.scrollToPreviousPage()}/>\n <span aria-label=\"PDF 页码\">{pages.currentPage} / {pages.totalPages}</span>\n <Button aria-label=\"下一页\" disabled={pages.currentPage >= pages.totalPages} theme=\"borderless\" icon={<ChevronRight size={16}/>} onClick={() => scroll?.scrollToNextPage()}/>\n <span id={zoomLabelId} className=\"sr-only\">PDF 缩放</span>\n <Select aria-labelledby={zoomLabelId} size=\"small\" value={String(zoomLevel)} style={{ width: 110 }} optionList={ZOOM_OPTIONS} onChange={value => {\n const level = value === '1' ? 1 : value as ZoomMode;\n setZoomLevel(level);\n zoom?.requestZoom(level);\n }}/>\n <Button aria-label=\"旋转\" theme=\"borderless\" icon={<RotateCw size={16}/>} onClick={() => rotate?.rotateForward()}/>\n <Button aria-label=\"拖动页面\" aria-pressed={isPanning} theme={isPanning ? 'solid' : 'borderless'} icon={<Hand size={16}/>} onClick={() => pan?.togglePan()}/>\n <form aria-label=\"PDF 搜索\" style={{ display: 'flex', gap: 4 }} onSubmit={event => {\n event.preventDefault();\n if (!query.trim()) { search?.stopSearch(); return; }\n search?.startSearch();\n search?.searchAllPages(query);\n }}>\n <input aria-label=\"搜索 PDF 文本\" placeholder=\"搜索 PDF 文本\" value={query} style={{ width: 120, color: 'inherit', background: 'transparent', border: '1px solid var(--color-border)', borderRadius: 'var(--semi-border-radius-small)' }} onChange={event => {\n setQuery(event.target.value);\n if (!event.target.value) search?.stopSearch();\n }}/>\n <Button htmlType=\"submit\" size=\"small\">搜索</Button>\n </form>\n {results.active && <>\n <span role=\"status\" aria-label=\"搜索结果\">{results.total ? results.activeResultIndex + 1 : 0} / {results.total}</span>\n <Button aria-label=\"上个结果\" size=\"small\" disabled={!results.total} onClick={() => search?.previousResult()}>↑</Button>\n <Button aria-label=\"下个结果\" size=\"small\" disabled={!results.total} onClick={() => search?.nextResult()}>↓</Button>\n </>}\n <Button aria-label=\"打印 PDF\" theme=\"borderless\" icon={<Printer size={16}/>} onClick={() => print?.print()}/>\n <a href={url} download={fileName} aria-label=\"下载 PDF\"><Download size={16}/></a>\n </div>\n <div style={{ display: 'flex', flex: 1, minHeight: 0 }}>\n {thumbnails && <ThumbnailsPane documentId={documentId} aria-label=\"PDF 缩略图\" style={{ width: 140, flexShrink: 0 }}>\n {(meta: ThumbMeta) => <button key={meta.pageIndex} aria-label={'跳到第 ' + (meta.pageIndex + 1) + ' 页'} style={{ position: 'absolute', top: meta.top, height: meta.wrapperHeight, width: '100%', border: 0, background: 'transparent', color: 'inherit' }} onClick={() => scroll?.scrollToPage({ pageNumber: meta.pageIndex + 1 })}>\n <ThumbImg documentId={documentId} meta={meta} style={{ display: 'block', margin: 'auto' }}/>\n {meta.pageIndex + 1}\n </button>}\n </ThumbnailsPane>}\n <Viewport documentId={documentId} style={{ flex: 1, minWidth: 0, height: '100%', background: 'var(--color-content-bg)' }}>\n <Scroller documentId={documentId} renderPage={({ width, height, pageIndex }) => <PagePointerProvider documentId={documentId} pageIndex={pageIndex} style={{ width, height, position: 'relative' }}>\n <RenderLayer documentId={documentId} pageIndex={pageIndex}/>\n <SearchLayer documentId={documentId} pageIndex={pageIndex}/>\n <SelectionLayer documentId={documentId} pageIndex={pageIndex}/>\n </PagePointerProvider>}/>\n </Viewport>\n </div>\n </>;\n}\n\nfunction PDFLoadError({ documentId, message }: Readonly<{ documentId: string; message: string | null }>) {\n const { provides } = useDocumentManagerCapability();\n const [password, setPassword] = useState('');\n return <form role=\"alert\" style={{ padding: 16 }} onSubmit={event => { event.preventDefault(); provides?.retryDocument(documentId, { password }); }}>\n <p>PDF 加载失败:{message}</p>\n <input aria-label=\"PDF 密码\" placeholder=\"加密 PDF 密码\" type=\"password\" value={password} onChange={event => setPassword(event.target.value)}/>\n <Button htmlType=\"submit\">重试</Button>\n </form>;\n}\n\nfunction PDFContent({ file }: Readonly<{ file: File }>) {\n // The engine and plugin modules remain behind the preview's existing lazy boundary.\n const wasmUrl = new URL(pdfiumWasmUrl, globalThis.location.href).href;\n const { engine, error } = usePdfiumEngine({ wasmUrl });\n const [source, setSource] = useState<{ file: File; url: string } | null>(null);\n useEffect(() => {\n const url = URL.createObjectURL(file);\n setSource({ file, url });\n return () => URL.revokeObjectURL(url);\n }, [file]);\n const url = source?.file === file ? source.url : null;\n const plugins = useMemo(() => [\n createPluginRegistration(DocumentManagerPluginPackage, { initialDocuments: url ? [{ url, name: file.name }] : [] }),\n createPluginRegistration(ViewportPluginPackage),\n createPluginRegistration(ScrollPluginPackage),\n createPluginRegistration(RenderPluginPackage),\n createPluginRegistration(InteractionManagerPluginPackage),\n createPluginRegistration(ZoomPluginPackage, { defaultZoomLevel: ZoomMode.FitWidth }),\n createPluginRegistration(SearchPluginPackage),\n createPluginRegistration(SelectionPluginPackage),\n createPluginRegistration(RotatePluginPackage),\n createPluginRegistration(PanPluginPackage),\n createPluginRegistration(ThumbnailPluginPackage),\n createPluginRegistration(PrintPluginPackage),\n ], [url, file.name]);\n if (error) return <div role=\"alert\">PDF 引擎加载失败:{error.message}</div>;\n if (!engine || !url) return <div role=\"status\">正在加载 PDF…</div>;\n return <EmbedPDF key={url} engine={engine} plugins={plugins}>\n {({ activeDocumentId }) => activeDocumentId ? <><PanMode/><DocumentContent documentId={activeDocumentId}>\n {({ isLoaded, isError, documentState }) => isLoaded\n ? <PDFDocument documentId={activeDocumentId} url={url} fileName={file.name}/>\n : isError ? <PDFLoadError documentId={activeDocumentId} message={documentState.error}/>\n : <div role=\"status\">正在加载 PDF…</div>}\n </DocumentContent></> : null}\n </EmbedPDF>;\n}\n\n/** Modular PDFium reader: no bundled editor, form, redaction or signature tools. */\nexport function PDFPreviewPanel({ file, onClose, fullscreen, onToggleFullscreen, style, actions }: PDFPreviewPanelProps) {\n const { isDark } = useThemeController();\n return <div style={{ width: '50%', minWidth: 320, display: 'flex', flexDirection: 'column', borderLeft: '1px solid var(--color-border)', overflow: 'hidden', flexShrink: 0, colorScheme: isDark ? 'dark' : 'light', ...style }}>\n <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '10px 16px', borderBottom: '1px solid var(--color-border)', flexShrink: 0 }}>\n <FileTypeIcon icon=\"vscode-icons:file-type-pdf2\" size={15}/>\n <Text ellipsis={{ showTooltip: true }} style={{ flex: 1, fontSize: 13, fontWeight: 500, minWidth: 0 }}>{file.name}</Text>\n {actions}\n {onToggleFullscreen && <Button aria-label={fullscreen ? '退出全屏' : '全屏'} theme=\"borderless\" size=\"small\" icon={fullscreen ? <Minimize2 size={14}/> : <Maximize2 size={14}/>} onClick={onToggleFullscreen}/>}\n <Button aria-label=\"关闭预览\" theme=\"borderless\" size=\"small\" icon={<X size={14}/>} onClick={onClose}/>\n </div>\n <PDFContent file={file}/>\n </div>;\n}\n"],"file":"PDFPreviewPanel-kBPz5dQr.js"}
1
+ {"version":3,"mappings":";;;;;;;IASMA,GAAa,CACjB,KAAM,OACN,KAAM,GACN,KAAM,CACJ,CAAC,OAAQ,CAAE,EAAG,uCAAwC,IAAK,QAAS,CAAC,EACrE,CAAC,OAAQ,CAAE,EAAG,yCAA0C,IAAK,QAAS,CAAC,EACvE,CAAC,OAAQ,CAAE,EAAG,2CAA4C,IAAK,QAAS,CAAC,EACzE,CACE,OACA,CACE,EAAG,oGACH,IAAK,QACP,CACF,CACF,CACF,EACAC,GAAW,KACL,GAAOC,EAAiBF,EAAU,C;;;;;;;ICjBlCA,GAAa,CACjB,KAAM,aACN,KAAM,GACN,KAAM,CACJ,CAAC,OAAQ,CAAE,EAAG,YAAa,IAAK,QAAS,CAAC,EAC1C,CAAC,OAAQ,CAAE,EAAG,YAAa,IAAK,QAAS,CAAC,EAC1C,CAAC,OAAQ,CAAE,EAAG,YAAa,IAAK,QAAS,CAAC,EAC1C,CAAC,OAAQ,CAAE,EAAG,aAAc,IAAK,QAAS,CAAC,CAC7C,CACF,EACAG,GAAW,KACL,GAAYD,EAAiBF,EAAU,C;;;;;;;ICXvCA,GAAa,CACjB,KAAM,aACN,KAAM,GACN,KAAM,CACJ,CAAC,OAAQ,CAAE,EAAG,aAAc,IAAK,QAAS,CAAC,EAC3C,CAAC,OAAQ,CAAE,EAAG,cAAe,IAAK,QAAS,CAAC,EAC5C,CAAC,OAAQ,CAAE,EAAG,YAAa,IAAK,QAAS,CAAC,EAC1C,CAAC,OAAQ,CAAE,EAAG,YAAa,IAAK,QAAS,CAAC,CAC5C,CACF,EACAI,GAAW,KACL,GAAYF,EAAiBF,EAAU,C;;;;;;;ICXvCA,GAAa,CAC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PI,EAA2B,iBAAE,IAC/B,EAAUK,UAAe,YACzB,EAAUv1B,QAAa,WACvB,EAAUw1B,SAAc,YACjBC,GACT,CAAGC,GAAY,CAAC,CAAC,EACb,EAAoC,iBAAE,IACxC,EAAmB,EAAmB3zB,OAAY,GAAK,SACvD,EAAmB,EAAmB4zB,IAAS,GAAK,MAC7CC,GACT,CAAGC,GAAqB,CAAC,CAAC,EACpB,GAAiB,OACjBvX,GAAW,CACf,GAAIwX,GACJ,KAAM,cACN,QAAS,QACT,SAAU,CAAC,MAAM,EACjB,SAAU,CAAC,WAAY,QAAQ,EAC/B,SAAU,CAAC,sBAAuB,QAAQ,EAC1C,cAAe,CACb,iBAAkBJ,EAAS,UAC3B,QAAS,GACT,QAAS,GACT,SAAU,GACV,WAAY,CACV,CACE,IAAK,GACL,IAAK,GACL,KAAM,GACR,EACA,CACE,IAAK,GACL,IAAK,EACL,KAAM,EACR,EACA,CACE,IAAK,EACL,IAAK,EACL,KAAM,EACR,EACA,CACE,IAAK,EACL,IAAK,EACL,KAAM,EACR,EACA,CACE,IAAK,EACL,IAAK,GACL,KAAM,EACR,EACA,CACE,IAAK,GACL,IAAK,GACL,KAAM,GACR,EACA,CACE,IAAK,GACL,IAAK,GACL,KAAM,GACR,EACA,CACE,IAAK,GACL,IAAK,GACL,KAAM,GACR,CACF,EACA,QAAS,CACP,CACE,KAAM,WACN,MAAOA,EAAS,OAClB,EACA,CACE,KAAM,YACN,MAAOA,EAAS,QAClB,EACA,CACE,KAAM,YACN,MAAOA,EAAS,SAClB,EACA,CACE,KAAM,MACN,MAAO,GACT,EACA,CACE,KAAM,MACN,MAAO,EACT,EACA,CACE,KAAM,OACN,MAAO,CACT,EACA,CACE,KAAM,OACN,MAAO,IACT,EACA,CACE,KAAM,OACN,MAAO,GACT,EACA,CACE,KAAM,OACN,MAAO,CACT,EACA,CACE,KAAM,OACN,MAAO,CACT,EACA,CACE,KAAM,OACN,MAAO,CACT,EACA,CACE,KAAM,QACN,MAAO,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B,EAAG,QAASJ,CAAoB,GACxM,kBAAChC,EAAD,CAAQ,aAAW,OAAO,MAAM,aAAa,KAAK,QAAQ,KAAM,kBAACqC,EAAD,CAAG,KAAM,EAAI,GAAG,QAASC,CAAS,EACjG,CACL,qBAACvB,GAAD,CAAkB,MAAM,EACvB,C,EACT,C,oLA3IQ,UAASwB,EACX,GAAe,CACjB,CAAE,MAAO1nB,EAAS,UAAW,MAAO,MAAO,EAC3C,CAAE,MAAOA,EAAS,QAAS,MAAO,MAAO,EACzC,CAAE,MAAOA,EAAS,SAAU,MAAO,MAAO,EAC1C,CAAE,MAAO,IAAK,MAAO,MAAO,CAChC,C","names":["__iconData","__iconData$4","createLucideIcon","__iconData$3","__iconData$2","__iconData$1","randomBytes","bytes","size","offset","toIntPos","p","toIntSize","s","toIntRect","r","swap","height","width","transformSize","rotation","scaleFactor","quadToRect","xs","q","ys","rectToQuad","rotatePosition","x","position","y","containerSize","scalePosition","transformPosition","restorePosition","rotateRect","rect","scaleRect","transformRect","boundingRect","rects","minX","minY","maxX","maxY","buildUserToDeviceMatrix","L","B","W","H","sx0","outW","sy0","outH","sx90","sy90","stripPdfUnwantedMarkers","text","PdfUnwantedTextRegex","flagsToNames","PdfAnnotationFlagName","raw","flag","namesToFlags","names","mask","PdfAnnotationFlagValue","name","pdfColorToWebColor","clamp","n","toHex","c","webColorToPdfColor","color","g","b","pdfAlphaToWebOpacity","alpha","webOpacityToPdfAlpha","hi","opacity","pdfDateToDate","pdf","mo","d","M","S","dateToPdfDate","z","len","date","serializeLogger","logger","NoopLogger","ConsoleLogger","PerfLogger","LevelLogger","levelLogger","AllLogger","allLogger","getRandomBytes","__require","__toCommonJS","browser_random_exports","i","uuidV4","hex","getImageMetadata","buffer","parsePng","parseJpeg","view","marker","segLen","ignore","\"Degree0\"","\"Degree90\"","\"Degree180\"","\"Degree270\"","Rotation2","Rotation","args","source","category","event","phase","level","markName","identifier","measureName","beginMark","startTime","duration","loggers","\"Pending\"","\"Resolved\"","\"Rejected\"","\"Aborted\"","TaskStage2","TaskStage","reason","Task","resolve","result","error","reject","TaskAbortedError","TaskRejectedError","resolvedCallback","rejectedCallback","cb","combinedTask","tasks","results","resolvedCount","isSettled","task","index","settledCount","onProgress","completedCount","PdfUnwantedTextMarkers","\"Unknown\"","\"XYZ\"","\"FitPage\"","\"FitHorizontal\"","\"FitVertical\"","\"FitRectangle\"","\"FitBoundingBox\"","\"FitBoundingBoxHorizontal\"","\"FitBoundingBoxVertical\"","PdfZoomMode2","PdfZoomMode","\"NotSet\"","\"True\"","\"False\"","PdfTrappedStatus2","PdfTrappedStatus","\"Courier\"","\"Courier_Bold\"","\"Courier_BoldOblique\"","\"Courier_Oblique\"","\"Helvetica\"","\"Helvetica_Bold\"","\"Helvetica_BoldOblique\"","\"Helvetica_Oblique\"","\"Times_Roman\"","\"Times_Bold\"","\"Times_BoldItalic\"","\"Times_Italic\"","\"Symbol\"","\"ZapfDingbats\"","PdfStandardFont2","PdfStandardFont","\"Left\"","\"Center\"","\"Right\"","PdfTextAlignment2","PdfTextAlignment","\"Normal\"","\"Multiply\"","\"Screen\"","\"Overlay\"","\"Darken\"","\"Lighten\"","\"ColorDodge\"","\"ColorBurn\"","\"HardLight\"","\"SoftLight\"","\"Difference\"","\"Exclusion\"","\"Hue\"","\"Saturation\"","\"Color\"","\"Luminosity\"","PdfBlendMode2","PdfBlendMode","\"Contain\"","\"Cover\"","\"Stretch\"","PdfStampFit2","PdfStampFit","\"Unsupported\"","\"Goto\"","\"RemoteGoto\"","\"URI\"","\"LaunchAppOrOpenFile\"","PdfActionType2","PdfActionType","\"UNKNOWN\"","\"TEXT\"","\"LINK\"","\"FREETEXT\"","\"LINE\"","\"SQUARE\"","\"CIRCLE\"","\"POLYGON\"","\"POLYLINE\"","\"HIGHLIGHT\"","\"UNDERLINE\"","\"SQUIGGLY\"","\"STRIKEOUT\"","\"STAMP\"","\"CARET\"","\"INK\"","\"POPUP\"","\"FILEATTACHMENT\"","\"SOUND\"","\"MOVIE\"","\"WIDGET\"","\"SCREEN\"","\"PRINTERMARK\"","\"TRAPNET\"","\"WATERMARK\"","\"THREED\"","\"RICHMEDIA\"","\"XFAWIDGET\"","\"REDACT\"","PdfAnnotationSubtype2","PdfAnnotationSubtype","\"Rollover\"","\"Down\"","AppearanceMode2","AppearanceMode","\"Comment\"","\"Key\"","\"Note\"","\"Help\"","\"NewParagraph\"","\"Paragraph\"","\"Insert\"","\"Graph\"","\"PushPin\"","\"Paperclip\"","\"Tag\"","\"Speaker\"","\"Mic\"","\"Approved\"","\"Experimental\"","\"NotApproved\"","\"AsIs\"","\"Expired\"","\"NotForPublicRelease\"","\"Confidential\"","\"Final\"","\"Sold\"","\"Departmental\"","\"ForComment\"","\"TopSecret\"","\"Draft\"","\"ForPublicRelease\"","\"Completed\"","\"Void\"","\"PreliminaryResults\"","\"InformationOnly\"","\"Witness\"","\"InitialHere\"","\"SignHere\"","\"Accepted\"","\"Custom\"","\"Image\"","PdfAnnotationName2","PdfAnnotationName","\"None\"","\"Square\"","\"Circle\"","\"Diamond\"","\"OpenArrow\"","\"ClosedArrow\"","\"Butt\"","\"ROpenArrow\"","\"RClosedArrow\"","\"Slash\"","PdfAnnotationLineEnding2","PdfAnnotationLineEnding","\"Reply\"","\"Group\"","PdfAnnotationReplyType2","PdfAnnotationReplyType","\"PUSHBUTTON\"","\"CHECKBOX\"","\"RADIOBUTTON\"","\"COMBOBOX\"","\"LISTBOX\"","\"TEXTFIELD\"","\"SIGNATURE\"","\"XFA\"","\"XFA_CHECKBOX\"","\"XFA_COMBOBOX\"","\"XFA_IMAGEFIELD\"","\"XFA_LISTBOX\"","\"XFA_PUSHBUTTON\"","\"XFA_SIGNATURE\"","\"XFA_TEXTFIELD\"","PDF_FORM_FIELD_TYPE2","PDF_FORM_FIELD_TYPE","\"InteriorColor\"","\"OverlayColor\"","\"TextColor\"","PdfAnnotationColorType2","PdfAnnotationColorType","\"SOLID\"","\"DASHED\"","\"BEVELED\"","\"INSET\"","\"CLOUDY\"","PdfAnnotationBorderStyle2","PdfAnnotationBorderStyle","\"NONE\"","\"READONLY\"","\"REQUIRED\"","\"NOEXPORT\"","\"TEXT_MULTIPLINE\"","\"TEXT_PASSWORD\"","\"TEXT_FILESELECT\"","\"TEXT_DONOTSPELLCHECK\"","\"TEXT_DONOTSCROLL\"","\"TEXT_COMB\"","\"TEXT_RICHTEXT\"","\"BUTTON_NOTOGGLETOOFF\"","\"BUTTON_RADIO\"","\"BUTTON_PUSHBUTTON\"","\"BUTTON_RADIOSINUNISON\"","\"CHOICE_COMBO\"","\"CHOICE_EDIT\"","\"CHOICE_SORT\"","\"CHOICE_MULTL_SELECT\"","\"CHOICE_DONOTSPELLCHECK\"","\"CHOICE_COMMITONSELCHANGE\"","PDF_FORM_FIELD_FLAG2","PDF_FORM_FIELD_FLAG","\"PATH\"","\"IMAGE\"","\"SHADING\"","\"FORM\"","PdfPageObjectType2","PdfPageObjectType","bit","acc","\"KEY_STROKE\"","\"FORMAT\"","\"VALIDATE\"","\"CALCULATE\"","PDF_ANNOT_AACTION_EVENT2","PDF_ANNOT_AACTION_EVENT","\"Keystroke\"","\"Format\"","\"Validate\"","\"Calculate\"","PdfJavaScriptWidgetEventType2","PdfJavaScriptWidgetEventType","\"DocumentNamed\"","\"WidgetKeystroke\"","\"WidgetFormat\"","\"WidgetValidate\"","\"WidgetCalculate\"","PdfJavaScriptActionTrigger2","PdfJavaScriptActionTrigger","\"Create\"","\"Read\"","\"Update\"","\"Delete\"","PdfEngineOperation2","PdfEngineOperation","\"Print\"","\"ModifyContents\"","\"CopyContents\"","\"ModifyAnnotations\"","\"FillForms\"","\"ExtractForAccessibility\"","\"AssembleDocument\"","\"PrintHighQuality\"","\"AllowAll\"","PdfPermissionFlag2","PdfPermissionFlag","flagNames","requiredFlags","f","currentPermissions","\"Display\"","PdfPageFlattenFlag2","PdfPageFlattenFlag","\"Ok\"","\"NotFound\"","\"WrongFormat\"","\"Password\"","\"Security\"","\"PageError\"","\"XFALoad\"","\"XFALayout\"","\"Cancelled\"","\"Initialization\"","\"NotReady\"","\"NotSupport\"","\"LoadDoc\"","\"DocNotOpen\"","\"CantCloseDoc\"","\"CantCreateNewDoc\"","\"CantImportPages\"","\"CantCreateAnnot\"","\"CantSetAnnotRect\"","\"CantSetAnnotContent\"","\"CantRemoveInkList\"","\"CantAddInkStoke\"","\"CantReadAttachmentSize\"","\"CantReadAttachmentContent\"","\"CantFocusAnnot\"","\"CantSelectText\"","\"CantSelectOption\"","\"CantCheckField\"","\"CantSetAnnotString\"","\"CantDeletePage\"","PdfErrorCode2","PdfErrorCode","TEXT_ALIGNMENT_INFOS","info","m","\"Times\"","PdfStandardFontFamily2","PdfStandardFontFamily","HELVETICA_DESC","STANDARD_FONT_DESCRIPTORS","familyStyleToId","family","BLEND_MODE_INFOS","CompoundTask","config","child","childIndex","progressValue","finalResult","otherChild","compound","record","resolved","\"handleChildSuccess\"","\"children\"","getPermissionOverride","overrides","PERMISSION_FLAG_TO_NAME","getEffectivePermission","docState","state","documentId","docConfig","globalConfig","pdfPermissions","docOverride","globalOverride","getEffectivePermissions","ALL_PERMISSION_FLAGS","calculateNextActiveDocument","currentActiveId","closingDocumentId","explicitNext","closingIndex","moveDocumentInOrder","fromIndex","currentOrder","toIndex","newOrder","createPluginRegistration","pluginPackage","hasAutoMountElements","pkg","isKeyedOptions","options","value","min","max","arePropsEqual","a","aType","visited","pairId","getPairId","aIsArray","bIsArray","arraysEqualUnordered","objectsEqual","objectId","objectIds","obj","objectIdCounter","used","elemA","j","aKeys","bKeys","key","valA","valB","createEmitter","listeners","l","v","createBehaviorEmitter","proxyMap","_value","initial","notify","baseOn","realListener","listener","destroy","ctl","KeyedEventControl","EventControl","equality","proxy","prev","mapped","selector","next","eq","createScopedEmitter","shouldCache","scopeCaches","scopeListeners","scopeProxyMaps","globalListeners","globalProxyMap","normalizeKey","getOrCreateListeners","getOrCreateProxyMap","normalizedKey","cached","data","globalEvent","toGlobalEvent","options2","set","map","createPluginPackage","PluginPackageBuilder","basePackage","id","dependencies","recursionStack","dfs","dep","temp","visit","message","store","pluginId","action","newPluginState","oldPluginState","type","handler","oldState","SET_ACTIVE_DOCUMENT","SET_ROTATION","START_LOADING_DOCUMENT","UPDATE_DOCUMENT_LOADING_PROGRESS","SET_DOCUMENT_LOADED","CLOSE_DOCUMENT","SET_DOCUMENT_ERROR","RETRY_LOADING_DOCUMENT","REFRESH_DOCUMENT","REFRESH_PAGES","SET_PAGES","SET_SCALE","SET_DEFAULT_SCALE","SET_DEFAULT_ROTATION","REORDER_DOCUMENTS","MOVE_DOCUMENT","UPDATE_DOCUMENT_SECURITY","setRotation","order","initialCoreState2","reducer","initialState","oldGlobalState","notifyGlobal","currentPluginState","newState","PluginStore","CORE_ACTION_TYPES","_a","_b","newDocState","scale","passwordProvided","autoActivate","progress","removed","remainingDocs","nextActiveDocumentId","targetId","newVersions","pageIndex","pageIndexes","DependencyResolver","engine","initialCoreState","Store","coreReducer","PluginRegistrationError","readyPromises","reg","dependsOn","allDeps","cap","provider","loadOrder","err","CircularDependencyError","finalConfig","manifest","plugin","packageCreator","capability","PluginNotFoundError","missingKeys","defaultConfig","PluginConfigurationError","currentConfig","newConfig","registrations","otherId","otherManifest","status","registry","now","cooldownTime","actionKey","debounceTime","actionType","timeout","doc","docId","flags","missingFlags","effectivePermissions","PermissionDeniedError","throttleMode","control","AutoMount","useMemo","utilities2","wrappers2","plugins","elements","element","contentWithUtilities","Fragment","children","utilities","Utility","wrappedContent","wrappers","Wrapper","content","EmbedPDF","setRegistry","useState","coreState","setCoreState","isInitializing","setIsInitializing","pluginsReady","setPluginsReady","initRef","useRef","onInitialized","useEffect","pdfViewer","PluginRegistry","initialize","unsubscribe","cleanup","unsub","contextValue","activeDocumentId","documents","documentOrder","activeDocument","documentStates","PDFContext","autoMountDomElements","useRegistry","useContext","usePlugin","useCapability","useCoreState","useDocumentState","createContext","usePdfiumEngine","defaultWasmUrl","setEngine","loading","setLoading","setError","engineRef","cancelled","worker","__vitePreload","pdfEngine","createPdfiumEngine","wasmUrl","e","_a2","_b2","fontFallback","BasePlugin","setActiveDocument","activeId","moveDocument","index1","id1","index2","id2","reorderDocuments","ownerPassword","previousId","currentId","limitError","documentName","startLoadingDocument","file","engineTask","validation","mergedOptions","retryOptions","retryLoadingDocument","closeDocument","documentIds","success","document","updateDocumentSecurity","setDocumentLoaded","pdfDocument","context","errorMessage","setDocumentError","lastSegment","url","filename","_DocumentManagerPlugin","DOCUMENT_MANAGER_PLUGIN_ID","DocumentManagerPluginPackage","manifest$10","DocumentManagerPlugin","DocumentContent","documentState","isLoading","isError","isLoaded","FilePicker","useDocumentManagerPlugin","useDocumentManagerCapability","inputRef","taskRef","optionsRef","provides","DocumentManagerPluginPackage$1","initViewportState","INIT_VIEWPORT_STATE","cleanupViewportState","CLEANUP_VIEWPORT_STATE","registerViewport","REGISTER_VIEWPORT","unregisterViewport","UNREGISTER_VIEWPORT","setViewportGap","SET_VIEWPORT_GAP","viewportGap","setViewportMetrics","SET_VIEWPORT_METRICS","setViewportScrollMetrics","SET_VIEWPORT_SCROLL_METRICS","setScrollActivity","SET_SCROLL_ACTIVITY","setSmoothScrollActivity","SET_SMOOTH_SCROLL_ACTIVITY","addViewportGate","ADD_VIEWPORT_GATE","removeViewportGate","REMOVE_VIEWPORT_GATE","VIEWPORT_PLUGIN_ID","initialViewportDocumentState","newActiveViewports","SET_ACTIVE_VIEWPORT_DOCUMENT","viewport","metrics","scrollMetrics","newGates","pos","emitter","behavior","finalX","finalY","alignX","alignY","prevViewport","prevState","newViewport","prevGates","addedGate","removedGate","_ViewportPlugin","manifest$9","ViewportPlugin","viewportReducer","initialState$8","useViewportRef","viewportPlugin","useViewportPlugin","containerRef","useLayoutEffect","container","onScroll","resizeObserver","unsubscribeScrollRequest","Viewport","props","viewportRef","viewportProvides","useViewportCapability","isGated","useIsViewportGated","restProps","ViewportElementContext","style","setIsGated","initScrollState","INIT_SCROLL_STATE","cleanupScrollState","CLEANUP_SCROLL_STATE","updateDocumentScrollState","UPDATE_DOCUMENT_SCROLL_STATE","setScrollStrategy","SET_SCROLL_STRATEGY","\"Vertical\"","\"Horizontal\"","ScrollStrategy2","ScrollStrategy","totalContentSize","_item","scrollOffset","clientSize","viewportStart","viewportEnd","startIndex","virtualItems","endIndex","range","visibleItems","pageVisibilityMetrics","visiblePages","renderedPageIndexes","item","currentPage","first","last","startSpacing","lastItem","endSpacing","visibilityMetrics","centeringOffsetX","centeringOffsetY","itemX","itemY","pageX","page","pageY","pageWidth","pageHeight","viewportLeft","viewportTop","viewportRight","viewportBottom","intersectionLeft","intersectionTop","intersectionRight","intersectionBottom","visibleWidth","visibleHeight","totalArea","visibleArea","maxVisibility","mostVisiblePages","item2","pageNumber","pageLayout","layout","pageRect","scaledBasePosition","pageCoordinates","rotatedSize","BaseScrollStrategy","yOffset","pdfPageObject","pageLayouts","pagesInSpread","sum","xOffset","remaining","updates","idx","elevatedPages","im","pages","computedMetrics","coreDoc","strategy","viewportScope","callback","getScrollerLayout","isInitial","strategyType","HorizontalScrollStrategy","VerticalScrollStrategy","defaultPageChangeState","pageChangeState","targetPage","coreDocState","vp","items","isProgrammaticScroll","metricsToCommit","spread","effectiveRotation","currentItemIndex","newStrategy","prevDoc","newDoc","_ScrollPlugin","SCROLL_PLUGIN_ID","manifest$8","ScrollPlugin","scrollReducer","Scroller","scrollPlugin","useScrollPlugin","layoutData","setLayoutData","newLayout","scrollerLayout","renderPage","useScrollCapability","setCurrentPage","totalPages","setTotalPages","scope","_RenderPlugin","RENDER_PLUGIN_ID","RenderPlugin","RenderLayer","scaleOverride","dprOverride","renderProvides","useRenderCapability","imageUrl","setImageUrl","urlRef","refreshVersion","actualScale","actualDpr","blob","initZoomState","INIT_ZOOM_STATE","cleanupZoomState","CLEANUP_ZOOM_STATE","setZoomLevel","SET_ZOOM_LEVEL","setMarqueeZoomActive","SET_MARQUEE_ZOOM_ACTIVE","createMarqueeHandler","opts","start","onPreview","evt","pageSize","minDragPx","onCommit","onSmallDrag","\"Automatic\"","\"FitWidth\"","ZoomMode2","ZoomMode","\"Top\"","VerticalZoomFocus2","VerticalZoomFocus","ZOOM_PLUGIN_ID","initialDocumentState","isActive","_c","interactionManager","cfg","isMarqueeActive","cur","target","delta","oldZoom","base","exactZoom","newZoom","focusPoint","center","focus","align","desiredScrollLeft","desiredScrollTop","setScale","scrollScope","pgGap","vpGap","spreads","availableWidth","availableHeight","maxContentW","maxContentH","contentW","contentH","mode","off","cw","zoom","availableSpace","offXold","offYold","offXnew","offYnew","cx","cy","baseLeft","baseTop","oldZ","availableW","availableH","vItem","it","pageRel","rotatedRect","targetZoom","pageAbsX","pageAbsY","cxContent","cyContent","avail","centerVX","centerVY","ranges","r2","handlers","_ZoomPlugin","manifest$7","ZoomPlugin","zoomReducer","initialState$6","useZoomCapability","setState","initSearchState","INIT_SEARCH_STATE","cleanupSearchState","CLEANUP_SEARCH_STATE","startSearchSession","START_SEARCH_SESSION","stopSearchSession","STOP_SEARCH_SESSION","setSearchFlags","SET_SEARCH_FLAGS","setShowAllResults","SET_SHOW_ALL_RESULTS","startSearch","START_SEARCH","setSearchResults","SET_SEARCH_RESULTS","appendSearchResults","APPEND_SEARCH_RESULTS","setActiveResultIndex","SET_ACTIVE_RESULT_INDEX","updateDocState","oldDocState","initialSearchDocumentState","newResults","firstHitIndex","initialState2","prevDocState","getDocId","getDocState","keyword","showAll","PdfTaskHelper","trimmedKeyword","force","oldTask","activeResultIndex","nextIndex","prevIndex","_SearchPlugin","SEARCH_PLUGIN_ID","manifest$6","SearchPlugin","searchReducer","initialState$5","SearchLayer","searchProvides","useSearchCapability","searchResultState","setSearchResultState","currentState","resultsToShow","originalIndex","activeHighlightColor","highlightColor","rectIndex","searchState","setSearchState","selectRectsForPage","selectBoundingRectForPage","selectBoundingRectsForAllPages","out","rectMap","bRect","getFormattedSelectionForPage","segmentRects","boundingRect2","getFormattedSelection","glyphAt","run","geo","pt","rel","gx","gy","gw","gh","toleranceFactor","halfTol","computeTolerance","bestIndex","bestDist","expandedLeft","expandedRight","expandedTop","expandedBottom","dist","totalHeight","count","factor","sliceBounds","sel","from","lastRun","lastCharOnPage","rectsWithinSlice","textRuns","runStart","runEnd","to","sIdx","eIdx","charCount","widthSum","prevRight","flushSubRun","gap","avgWidth","merge","mergeAdjacentRects","rectUnion","left","rect1","rect2","top","right","bottom","rectIntersect","rectIsEmpty","getVerticalOverlap","unionRect","shouldMergeHorizontalRects","textRun1","textRun2","averageWidth1","averageWidth2","rect1Left","rect1Right","rect2Left","previousTextRun","currentRect","textRun","resolveCharIndex","localIdx","charIndex","isGlyphWordBoundary","expandToWordBoundary","totalChars","getTotalCharCount","expandToLineBoundary","anchorRun","anchorTop","anchorBottom","runsOverlapVertically","isZeroSizeRun","unionHeight","bottom1","bottom2","top1","top2","intersectHeight","VERTICAL_OVERLAP_THRESHOLD_LINE","createTextSelectionHandler","minDrag","tolFactor","anchorGlyph","anchorPos","dragStarted","lastDblClickTime","reset","modeId","TRIPLE_CLICK_INTERVAL_MS","point","dx","dy","createMarqueeSelectionHandler","SELECTION_PLUGIN_ID","INIT_SELECTION_STATE","CLEANUP_SELECTION_STATE","CACHE_PAGE_GEOMETRY","SET_SELECTION","START_SELECTION","END_SELECTION","CLEAR_SELECTION","SET_RECTS","allRects","SET_SLICES","EVICT_PAGE_GEOMETRY","geometry","slices","RESET","initialSelectionDocumentState","imPlugin","initSelectionState","marqueeEnabled","cleanupSelectionState","enabled","onRectsChange","geoTask","interactionScope","enabledModes","sb","pageRects","setRects","setSlices","textHandler","cursor","active","unregisterHandlers","shouldShowRect","marqueeHandler","onRectChange","viewportRect","rectTopInView","vpMetrics","rectBottomInView","placement","bounds","tail","head","tailMetrics","headMetrics","modeConfig","pageIdx","cachePageGeometry","pinned","toEvict","candidate","evictPageGeometry","startSelection","endSelection","clearSelection","validationError","normalized","geoTasks","clamped","previouslyHighlighted","setSelection","pagesToNotify","isValidPointer","pageCount","minPage","maxPage","lastGlyphIndex","startMax","endMax","clampIndex","end","forward","allSlices","req","text2","modes","current","_SelectionPlugin","SelectionPluginPackage","manifest$5","SelectionPlugin","selectionReducer","initialState$4","getCounterRotation","w","h","CounterRotate","elementRef","handlePointerDown","handleTouchStart","menuWrapperProps","matrix","el","TextSelection","rotationOverride","selPlugin","useSelectionPlugin","setBoundingRect","setPlacement","rects2","newPlacement","actualRotation","shouldRenderMenu","selectionMenu","SelectionLayer","Fragment$1","textStyle","background","MarqueeSelection","marqueeStyle","marqueeClassName","CopyToClipboard","useSelectionCapability","setRect","resolvedBorderColor","borderColor","stroke","resolvedBackground","fill","borderStyle","SelectionPluginPackage$1","initInteractionState","INIT_INTERACTION_STATE","cleanupInteractionState","CLEANUP_INTERACTION_STATE","activateMode","ACTIVATE_MODE","pauseInteraction","PAUSE_INTERACTION","resumeInteraction","RESUME_INTERACTION","setCursor","SET_CURSOR","setDefaultMode","SET_DEFAULT_MODE","setExclusionRules","SET_EXCLUSION_RULES","addExclusionClass","ADD_EXCLUSION_CLASS","removeExclusionClass","REMOVE_EXCLUSION_CLASS","addExclusionAttribute","ADD_EXCLUSION_ATTRIBUTE","removeExclusionAttribute","REMOVE_EXCLUSION_ATTRIBUTE","mergeHandlers","keys","k","list","INITIAL_MODE$1","docBuckets","topics","activePages","token","priority","rules","className","attribute","topic","previousMode","modeIds","cleanupFunctions","bucket","set2","docPageMap","mergeSets","claims","oldPage","handlerSet","_InteractionManagerPlugin","INTERACTION_MANAGER_PLUGIN_ID","INITIAL_MODE","manifest$4","InteractionManagerPlugin","initialState$3","useIsPageExclusive","useInteractionManagerCapability","isPageExclusive","setIsPageExclusive","listenerOpts","eventType","wantsRawTouch","isTouchEvent","shouldExcludeElement","attr","createPointerProvider","capScope","wantsRawTouchNow","attachedWithRawTouch","addListeners","allEventTypes","fn","handleEvent","removeListeners","stopMode","stopHandler","initialMode","initialCursor","stopCursor","toPos","convertEventToPoint","host","exclusionRules","handlerKey","domEventMap","normEvt","propagationStopped","tp","pe","pointerEventTypes","touchEventTypes","ref","naturalPageSize","pageRotation","docRotation","displaySize","defaultConvertEventToPoint","useCallback","displayPoint","getRotationMatrix","getRotationMatrixString","getNextRotation","getPreviousRotation","initRotateState","INIT_ROTATE_STATE","cleanupRotateState","CLEANUP_ROTATE_STATE","ROTATE_PLUGIN_ID","setRotation$1","nextRotation","prevRotation","_RotatePlugin","SET_ACTIVE_ROTATE_DOCUMENT","manifest$3","RotatePlugin","rotateReducer","initialState$2","useRotateCapability","newRotation","initPanState","INIT_PAN_STATE","cleanupPanState","CLEANUP_PAN_STATE","setPanMode","SET_PAN_MODE","isPanMode","dragState","unregister","_PanPlugin","SET_ACTIVE_PAN_DOCUMENT","PanPluginPackage","manifest$2","PanPlugin","panReducer","initialState$1","usePanCapability","isPanning","setIsPanning","isPan","pan","panPlugin","usePanPlugin","SUPPORT_TOUCH","PanPluginPackage$1","PanMode","initThumbnailState","INIT_THUMBNAIL_STATE","cleanupThumbnailState","CLEANUP_THUMBNAIL_STATE","setWindowState","SET_WINDOW_STATE","updateViewportMetrics","UPDATE_VIEWPORT_METRICS","THUMBNAIL_PLUGIN_ID","taskCache","dpr","scrollY","viewportH","OUTER_W","GAP","P","PADDING_Y","INNER_W","thumbs","isRotated90or270","effectiveWidth","ratio","imgH","wrapH","meta","window","BUF","low","high","mid","limit","newWindow","needsUp","needsDown","cache","_ThumbnailPlugin","manifest$1","ThumbnailPlugin","thumbnailReducer","ThumbnailsPane","thumbnailPlugin","useThumbnailPlugin","windowData","setWindowData","window2","initialWindow","paddingY","ThumbImg","useThumbnailCapability","setUrl","refreshTick","setRefreshTick","tick","objectUrl","PRINT_PLUGIN_ID","printOptions","_PrintPlugin","PrintPluginPackage","PrintPlugin","requireClient","hasRequiredClient","client","require$$0","PrintFrame","printCapability","usePrintCapability","printPlugin","usePrintPlugin","iframeRef","iframe","PrintPluginPackage$1","import.meta.ROLLDOWN_FILE_URL_8HSUfh7cJHNFxCkInNzNXw","PDFDocument","scroll","useScroll","useZoom","search","useSearch","rotate","useRotate","usePan","print","usePrint","zoomLabelId","useId","zoomLevel","query","setQuery","thumbnails","setThumbnails","_Fragment","Button","PanelLeft","ChevronLeft","ChevronRight","Select","ZOOM_OPTIONS","RotateCw","Hand","Printer","fileName","Download","PagePointerProvider","PDFLoadError","password","setPassword","PDFContent","pdfiumWasmUrl","setSource","ViewportPluginPackage","ScrollPluginPackage","RenderPluginPackage","InteractionManagerPluginPackage","ZoomPluginPackage","SearchPluginPackage","RotatePluginPackage","ThumbnailPluginPackage","PDFPreviewPanel","useThemeController","isDark","FileTypeIcon","Text","actions","onToggleFullscreen","fullscreen","jsx","Minimize2","Maximize2","X","onClose","Typography"],"ignoreList":[0,1,2,3,4,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36],"sources":["../../../../node_modules/lucide-react/dist/esm/icons/hand.mjs","../../../../node_modules/lucide-react/dist/esm/icons/maximize-2.mjs","../../../../node_modules/lucide-react/dist/esm/icons/minimize-2.mjs","../../../../node_modules/lucide-react/dist/esm/icons/panel-left.mjs","../../../../node_modules/lucide-react/dist/esm/icons/printer.mjs","../../../../scripts/lib/browser-random.mjs","../../../../node_modules/@embedpdf/models/dist/index.js","../../../../node_modules/@embedpdf/core/dist/index.js","../../../../node_modules/@embedpdf/core/dist/react/index.js","../../../../node_modules/@embedpdf/engines/dist/react/index.js","../../../../node_modules/@embedpdf/plugin-document-manager/dist/index.js","../../../../node_modules/@embedpdf/plugin-document-manager/dist/react/index.js","../../../../node_modules/@embedpdf/plugin-viewport/dist/index.js","../../../../node_modules/@embedpdf/plugin-viewport/dist/react/index.js","../../../../node_modules/@embedpdf/plugin-scroll/dist/index.js","../../../../node_modules/@embedpdf/plugin-scroll/dist/react/index.js","../../../../node_modules/@embedpdf/plugin-render/dist/index.js","../../../../node_modules/@embedpdf/plugin-render/dist/react/index.js","../../../../node_modules/@embedpdf/plugin-zoom/dist/index.js","../../../../node_modules/@embedpdf/plugin-zoom/dist/react/index.js","../../../../node_modules/@embedpdf/plugin-search/dist/index.js","../../../../node_modules/@embedpdf/plugin-search/dist/react/index.js","../../../../node_modules/@embedpdf/plugin-selection/dist/index.js","../../../../node_modules/@embedpdf/utils/dist/index.js","../../../../node_modules/@embedpdf/utils/dist/react/index.js","../../../../node_modules/@embedpdf/plugin-selection/dist/react/index.js","../../../../node_modules/@embedpdf/plugin-interaction-manager/dist/index.js","../../../../node_modules/@embedpdf/plugin-interaction-manager/dist/react/index.js","../../../../node_modules/@embedpdf/plugin-rotate/dist/index.js","../../../../node_modules/@embedpdf/plugin-rotate/dist/react/index.js","../../../../node_modules/@embedpdf/plugin-pan/dist/index.js","../../../../node_modules/@embedpdf/plugin-pan/dist/react/index.js","../../../../node_modules/@embedpdf/plugin-thumbnail/dist/index.js","../../../../node_modules/@embedpdf/plugin-thumbnail/dist/react/index.js","../../../../node_modules/@embedpdf/plugin-print/dist/index.js","../../../../node_modules/@embedpdf/plugin-print/dist/react/index.js","../../../../node_modules/@embedpdf/pdfium/dist/pdfium.wasm?url","../../src/components/PDFPreviewPanel.tsx"],"sourcesContent":["/**\n * @license lucide-react v1.67.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.mjs';\n\nconst __iconData = {\n name: \"hand\",\n size: 24,\n node: [\n [\"path\", { d: \"M18 11V6a2 2 0 0 0-2-2a2 2 0 0 0-2 2\", key: \"1fvzgz\" }],\n [\"path\", { d: \"M14 10V4a2 2 0 0 0-2-2a2 2 0 0 0-2 2v2\", key: \"1kc0my\" }],\n [\"path\", { d: \"M10 10.5V6a2 2 0 0 0-2-2a2 2 0 0 0-2 2v8\", key: \"10h0bg\" }],\n [\n \"path\",\n {\n d: \"M18 8a2 2 0 1 1 4 0v6a8 8 0 0 1-8 8h-2c-2.8 0-4.5-.86-5.99-2.34l-3.6-3.6a2 2 0 0 1 2.83-2.82L7 15\",\n key: \"1s1gnw\"\n }\n ]\n ]\n};\n__iconData.node;\nconst Hand = createLucideIcon(__iconData);\n\nexport { __iconData, Hand as default };\n//# sourceMappingURL=hand.mjs.map\n","/**\n * @license lucide-react v1.67.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.mjs';\n\nconst __iconData = {\n name: \"maximize-2\",\n size: 24,\n node: [\n [\"path\", { d: \"M15 3h6v6\", key: \"1q9fwt\" }],\n [\"path\", { d: \"m21 3-7 7\", key: \"1l2asr\" }],\n [\"path\", { d: \"m3 21 7-7\", key: \"tjx5ai\" }],\n [\"path\", { d: \"M9 21H3v-6\", key: \"wtvkvv\" }]\n ]\n};\n__iconData.node;\nconst Maximize2 = createLucideIcon(__iconData);\n\nexport { __iconData, Maximize2 as default };\n//# sourceMappingURL=maximize-2.mjs.map\n","/**\n * @license lucide-react v1.67.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.mjs';\n\nconst __iconData = {\n name: \"minimize-2\",\n size: 24,\n node: [\n [\"path\", { d: \"m14 10 7-7\", key: \"oa77jy\" }],\n [\"path\", { d: \"M20 10h-6V4\", key: \"mjg0md\" }],\n [\"path\", { d: \"m3 21 7-7\", key: \"tjx5ai\" }],\n [\"path\", { d: \"M4 14h6v6\", key: \"rmj7iw\" }]\n ]\n};\n__iconData.node;\nconst Minimize2 = createLucideIcon(__iconData);\n\nexport { __iconData, Minimize2 as default };\n//# sourceMappingURL=minimize-2.mjs.map\n","/**\n * @license lucide-react v1.67.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.mjs';\n\nconst __iconData = {\n name: \"panel-left\",\n size: 24,\n node: [\n [\"rect\", { width: \"18\", height: \"18\", x: \"3\", y: \"3\", rx: \"2\", key: \"afitv7\" }],\n [\"path\", { d: \"M9 3v18\", key: \"fh3hqa\" }]\n ],\n aliases: [\"sidebar\"]\n};\n__iconData.node;\nconst PanelLeft = createLucideIcon(__iconData);\n\nexport { __iconData, PanelLeft as default };\n//# sourceMappingURL=panel-left.mjs.map\n","/**\n * @license lucide-react v1.67.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.mjs';\n\nconst __iconData = {\n name: \"printer\",\n size: 24,\n node: [\n [\n \"path\",\n {\n d: \"M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2\",\n key: \"143wyd\"\n }\n ],\n [\"path\", { d: \"M6 9V3a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v6\", key: \"1itne7\" }],\n [\"rect\", { x: \"6\", y: \"14\", width: \"12\", height: \"8\", rx: \"1\", key: \"1ue0tg\" }]\n ]\n};\n__iconData.node;\nconst Printer = createLucideIcon(__iconData);\n\nexport { __iconData, Printer as default };\n//# sourceMappingURL=printer.mjs.map\n","// EmbedPDF's UUID fallback needs bytes, not the Node crypto API or a Buffer.\nexport function randomBytes(size) {\n const bytes = new Uint8Array(size);\n for (let offset = 0; offset < size; offset += 65536) {\n globalThis.crypto.getRandomValues(bytes.subarray(offset, offset + 65536));\n }\n return bytes;\n}\n","var Rotation = /* @__PURE__ */ ((Rotation2) => {\n Rotation2[Rotation2[\"Degree0\"] = 0] = \"Degree0\";\n Rotation2[Rotation2[\"Degree90\"] = 1] = \"Degree90\";\n Rotation2[Rotation2[\"Degree180\"] = 2] = \"Degree180\";\n Rotation2[Rotation2[\"Degree270\"] = 3] = \"Degree270\";\n return Rotation2;\n})(Rotation || {});\nfunction toIntPos(p) {\n return { x: Math.floor(p.x), y: Math.floor(p.y) };\n}\nfunction toIntSize(s) {\n return { width: Math.ceil(s.width), height: Math.ceil(s.height) };\n}\nfunction toIntRect(r) {\n return {\n origin: toIntPos(r.origin),\n size: toIntSize(r.size)\n };\n}\nfunction calculateDegree(rotation) {\n switch (rotation) {\n case 0:\n return 0;\n case 1:\n return 90;\n case 2:\n return 180;\n case 3:\n return 270;\n }\n}\nfunction calculateAngle(rotation) {\n return calculateDegree(rotation) * Math.PI / 180;\n}\nfunction swap(size) {\n const { width, height } = size;\n return {\n width: height,\n height: width\n };\n}\nfunction transformSize(size, rotation, scaleFactor) {\n size = rotation % 2 === 0 ? size : swap(size);\n return {\n width: size.width * scaleFactor,\n height: size.height * scaleFactor\n };\n}\nfunction quadToRect(q) {\n const xs = [q.p1.x, q.p2.x, q.p3.x, q.p4.x];\n const ys = [q.p1.y, q.p2.y, q.p3.y, q.p4.y];\n return {\n origin: { x: Math.min(...xs), y: Math.min(...ys) },\n size: {\n width: Math.max(...xs) - Math.min(...xs),\n height: Math.max(...ys) - Math.min(...ys)\n }\n };\n}\nfunction rectToQuad(r) {\n return {\n p1: { x: r.origin.x, y: r.origin.y },\n p2: { x: r.origin.x + r.size.width, y: r.origin.y },\n p3: { x: r.origin.x + r.size.width, y: r.origin.y + r.size.height },\n p4: { x: r.origin.x, y: r.origin.y + r.size.height }\n };\n}\nfunction rotatePosition(containerSize, position, rotation) {\n let x = position.x;\n let y = position.y;\n switch (rotation) {\n case 0:\n x = position.x;\n y = position.y;\n break;\n case 1:\n x = containerSize.height - position.y;\n y = position.x;\n break;\n case 2:\n x = containerSize.width - position.x;\n y = containerSize.height - position.y;\n break;\n case 3:\n x = position.y;\n y = containerSize.width - position.x;\n break;\n }\n return {\n x,\n y\n };\n}\nfunction scalePosition(position, scaleFactor) {\n return {\n x: position.x * scaleFactor,\n y: position.y * scaleFactor\n };\n}\nfunction transformPosition(containerSize, position, rotation, scaleFactor) {\n return scalePosition(rotatePosition(containerSize, position, rotation), scaleFactor);\n}\nfunction restorePosition(containerSize, position, rotation, scaleFactor) {\n return scalePosition(\n rotatePosition(containerSize, position, (4 - rotation) % 4),\n 1 / scaleFactor\n );\n}\nfunction rectEquals(a, b) {\n return a.origin.x === b.origin.x && a.origin.y === b.origin.y && a.size.width === b.size.width && a.size.height === b.size.height;\n}\nfunction rectFromPoints(positions) {\n if (positions.length === 0) {\n return { origin: { x: 0, y: 0 }, size: { width: 0, height: 0 } };\n }\n const xs = positions.map((p) => p.x);\n const ys = positions.map((p) => p.y);\n const minX = Math.min(...xs);\n const minY = Math.min(...ys);\n return {\n origin: { x: minX, y: minY },\n size: {\n width: Math.max(...xs) - minX,\n height: Math.max(...ys) - minY\n }\n };\n}\nfunction rotateAndTranslatePoint(pos, angleRad, translate) {\n const cos = Math.cos(angleRad);\n const sin = Math.sin(angleRad);\n const newX = pos.x * cos - pos.y * sin;\n const newY = pos.x * sin + pos.y * cos;\n return {\n x: newX + translate.x,\n y: newY + translate.y\n };\n}\nfunction expandRect(rect, padding) {\n return {\n origin: { x: rect.origin.x - padding, y: rect.origin.y - padding },\n size: { width: rect.size.width + padding * 2, height: rect.size.height + padding * 2 }\n };\n}\nfunction rotateRect(containerSize, rect, rotation) {\n let x = rect.origin.x;\n let y = rect.origin.y;\n let size = rect.size;\n switch (rotation) {\n case 0:\n break;\n case 1:\n x = containerSize.height - rect.origin.y - rect.size.height;\n y = rect.origin.x;\n size = swap(rect.size);\n break;\n case 2:\n x = containerSize.width - rect.origin.x - rect.size.width;\n y = containerSize.height - rect.origin.y - rect.size.height;\n break;\n case 3:\n x = rect.origin.y;\n y = containerSize.width - rect.origin.x - rect.size.width;\n size = swap(rect.size);\n break;\n }\n return {\n origin: {\n x,\n y\n },\n size: {\n width: size.width,\n height: size.height\n }\n };\n}\nfunction scaleRect(rect, scaleFactor) {\n return {\n origin: {\n x: rect.origin.x * scaleFactor,\n y: rect.origin.y * scaleFactor\n },\n size: {\n width: rect.size.width * scaleFactor,\n height: rect.size.height * scaleFactor\n }\n };\n}\nfunction transformRect(containerSize, rect, rotation, scaleFactor) {\n return scaleRect(rotateRect(containerSize, rect, rotation), scaleFactor);\n}\nfunction restoreRect(containerSize, rect, rotation, scaleFactor) {\n return scaleRect(rotateRect(containerSize, rect, (4 - rotation) % 4), 1 / scaleFactor);\n}\nfunction restoreOffset(offset, rotation, scaleFactor) {\n let offsetX = offset.x;\n let offsetY = offset.y;\n switch (rotation) {\n case 0:\n offsetX = offset.x / scaleFactor;\n offsetY = offset.y / scaleFactor;\n break;\n case 1:\n offsetX = offset.y / scaleFactor;\n offsetY = -offset.x / scaleFactor;\n break;\n case 2:\n offsetX = -offset.x / scaleFactor;\n offsetY = -offset.y / scaleFactor;\n break;\n case 3:\n offsetX = -offset.y / scaleFactor;\n offsetY = offset.x / scaleFactor;\n break;\n }\n return {\n x: offsetX,\n y: offsetY\n };\n}\nconst EMPTY_RECT = { origin: { x: 0, y: 0 }, size: { width: 0, height: 0 } };\nfunction boundingRect(rects) {\n if (rects.length === 0) return null;\n let minX = rects[0].origin.x, minY = rects[0].origin.y, maxX = rects[0].origin.x + rects[0].size.width, maxY = rects[0].origin.y + rects[0].size.height;\n for (const r of rects) {\n minX = Math.min(minX, r.origin.x);\n minY = Math.min(minY, r.origin.y);\n maxX = Math.max(maxX, r.origin.x + r.size.width);\n maxY = Math.max(maxY, r.origin.y + r.size.height);\n }\n return {\n origin: {\n x: minX,\n y: minY\n },\n size: {\n width: maxX - minX,\n height: maxY - minY\n }\n };\n}\nfunction boundingRectOrEmpty(rects) {\n return boundingRect(rects) ?? EMPTY_RECT;\n}\nfunction normalizeAngle(degrees) {\n const normalized = degrees % 360;\n return normalized < 0 ? normalized + 360 : normalized;\n}\nfunction getRectCenter(rect) {\n return {\n x: rect.origin.x + rect.size.width / 2,\n y: rect.origin.y + rect.size.height / 2\n };\n}\nfunction rotatePointAround(point, center, angleDegrees) {\n const angleRad = angleDegrees * Math.PI / 180;\n const cos = Math.cos(angleRad);\n const sin = Math.sin(angleRad);\n const dx = point.x - center.x;\n const dy = point.y - center.y;\n return {\n x: center.x + dx * cos - dy * sin,\n y: center.y + dx * sin + dy * cos\n };\n}\nfunction rotateVertices(points, center, angleDegrees) {\n return points.map((v) => rotatePointAround(v, center, angleDegrees));\n}\nfunction calculateRotatedRectAABBAroundPoint(rect, angleDegrees, center) {\n const corners = [\n { x: rect.origin.x, y: rect.origin.y },\n { x: rect.origin.x + rect.size.width, y: rect.origin.y },\n { x: rect.origin.x + rect.size.width, y: rect.origin.y + rect.size.height },\n { x: rect.origin.x, y: rect.origin.y + rect.size.height }\n ];\n const rotated = rotateVertices(corners, center, angleDegrees);\n return rectFromPoints(rotated);\n}\nfunction calculateRotatedRectAABB(unrotatedRect, angleDegrees) {\n return calculateRotatedRectAABBAroundPoint(\n unrotatedRect,\n angleDegrees,\n getRectCenter(unrotatedRect)\n );\n}\nfunction inferRotationCenterFromRects(unrotatedRect, rotatedAabb, angleDegrees) {\n const angleRad = angleDegrees * Math.PI / 180;\n const cos = Math.cos(angleRad);\n const sin = Math.sin(angleRad);\n const m00 = 1 - cos;\n const m01 = sin;\n const m10 = -sin;\n const m11 = 1 - cos;\n const det = m00 * m11 - m01 * m10;\n const unrotatedCenter = getRectCenter(unrotatedRect);\n if (Math.abs(det) < 1e-10) return unrotatedCenter;\n const rotatedCenter = getRectCenter(rotatedAabb);\n const rhsX = rotatedCenter.x - (cos * unrotatedCenter.x - sin * unrotatedCenter.y);\n const rhsY = rotatedCenter.y - (sin * unrotatedCenter.x + cos * unrotatedCenter.y);\n return {\n x: (m11 * rhsX - m01 * rhsY) / det,\n y: (-m10 * rhsX + m00 * rhsY) / det\n };\n}\nfunction buildUserToDeviceMatrix(rect, rotation, outW, outH) {\n const L = rect.origin.x;\n const B = rect.origin.y;\n const W = rect.size.width;\n const H = rect.size.height;\n const sx0 = outW / W;\n const sy0 = outH / H;\n const sx90 = outW / H;\n const sy90 = outH / W;\n switch (rotation) {\n case 0:\n return { a: sx0, b: 0, c: 0, d: sy0, e: -sx0 * L, f: -sy0 * B };\n case 3:\n return { a: 0, b: -sy90, c: sx90, d: 0, e: -sx90 * B, f: sy90 * (L + W) };\n case 2:\n return { a: -sx0, b: 0, c: 0, d: -sy0, e: sx0 * (L + W), f: sy0 * (B + H) };\n case 1:\n return { a: 0, b: sy90, c: -sx90, d: 0, e: sx90 * (B + H), f: -sy90 * L };\n }\n}\nfunction fitSizeWithin(size, bounds) {\n const scale = Math.min(bounds.width / size.width, bounds.height / size.height, 1);\n return { width: size.width * scale, height: size.height * scale };\n}\nclass NoopLogger {\n /** {@inheritDoc Logger.isEnabled} */\n isEnabled() {\n return false;\n }\n /** {@inheritDoc Logger.debug} */\n debug() {\n }\n /** {@inheritDoc Logger.info} */\n info() {\n }\n /** {@inheritDoc Logger.warn} */\n warn() {\n }\n /** {@inheritDoc Logger.error} */\n error() {\n }\n /** {@inheritDoc Logger.perf} */\n perf() {\n }\n}\nclass ConsoleLogger {\n /** {@inheritDoc Logger.isEnabled} */\n isEnabled() {\n return true;\n }\n /** {@inheritDoc Logger.debug} */\n debug(source, category, ...args) {\n console.debug(`${source}.${category}`, ...args);\n }\n /** {@inheritDoc Logger.info} */\n info(source, category, ...args) {\n console.info(`${source}.${category}`, ...args);\n }\n /** {@inheritDoc Logger.warn} */\n warn(source, category, ...args) {\n console.warn(`${source}.${category}`, ...args);\n }\n /** {@inheritDoc Logger.error} */\n error(source, category, ...args) {\n console.error(`${source}.${category}`, ...args);\n }\n /** {@inheritDoc Logger.perf} */\n perf(source, category, event, phase, ...args) {\n console.info(`${source}.${category}.${event}.${phase}`, ...args);\n }\n}\nvar LogLevel = /* @__PURE__ */ ((LogLevel2) => {\n LogLevel2[LogLevel2[\"Debug\"] = 0] = \"Debug\";\n LogLevel2[LogLevel2[\"Info\"] = 1] = \"Info\";\n LogLevel2[LogLevel2[\"Warn\"] = 2] = \"Warn\";\n LogLevel2[LogLevel2[\"Error\"] = 3] = \"Error\";\n return LogLevel2;\n})(LogLevel || {});\nclass LevelLogger {\n /**\n * create new LevelLogger\n * @param logger - the original logger\n * @param level - log level that used for filtering, all logs lower than this level will be filtered out\n */\n constructor(logger, level) {\n this.logger = logger;\n this.level = level;\n }\n /** {@inheritDoc Logger.isEnabled} */\n isEnabled(level) {\n const levelMap = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3\n /* Error */\n };\n return this.level <= levelMap[level];\n }\n /** {@inheritDoc Logger.debug} */\n debug(source, category, ...args) {\n if (this.level <= 0) {\n this.logger.debug(source, category, ...args);\n }\n }\n /** {@inheritDoc Logger.info} */\n info(source, category, ...args) {\n if (this.level <= 1) {\n this.logger.info(source, category, ...args);\n }\n }\n /** {@inheritDoc Logger.warn} */\n warn(source, category, ...args) {\n if (this.level <= 2) {\n this.logger.warn(source, category, ...args);\n }\n }\n /** {@inheritDoc Logger.error} */\n error(source, category, ...args) {\n if (this.level <= 3) {\n this.logger.error(source, category, ...args);\n }\n }\n /** {@inheritDoc Logger.perf} */\n perf(source, category, event, phase, ...args) {\n this.logger.perf(source, category, event, phase, ...args);\n }\n}\nclass PerfLogger {\n /**\n * create new PerfLogger\n */\n constructor() {\n this.marks = /* @__PURE__ */ new Map();\n }\n /** {@inheritDoc Logger.isEnabled} */\n isEnabled() {\n return false;\n }\n /** {@inheritDoc Logger.debug} */\n debug(source, category, ...args) {\n }\n /** {@inheritDoc Logger.info} */\n info(source, category, ...args) {\n }\n /** {@inheritDoc Logger.warn} */\n warn(source, category, ...args) {\n }\n /** {@inheritDoc Logger.error} */\n error(source, category, ...args) {\n }\n /** {@inheritDoc Logger.perf} */\n perf(source, category, event, phase, identifier, ...args) {\n const markName = `${source}.${category}.${event}.${phase}.${identifier}`;\n switch (phase) {\n case \"Begin\":\n globalThis.performance.mark(markName, { detail: args });\n this.marks.set(`${source}.${category}.${event}.${identifier}`, Date.now());\n break;\n case \"End\":\n globalThis.performance.mark(markName, { detail: args });\n const measureName = `${source}.${category}.${event}.Measure.${identifier}`;\n const beginMark = `${source}.${category}.${event}.Begin.${identifier}`;\n globalThis.performance.measure(measureName, beginMark, markName);\n const startTime = this.marks.get(`${source}.${category}.${event}.${identifier}`);\n if (startTime) {\n const duration = Date.now() - startTime;\n console.info(`⏱️ ${source}.${category}.${event}.${identifier}: ${duration}ms`);\n this.marks.delete(`${source}.${category}.${event}.${identifier}`);\n }\n break;\n }\n }\n}\nclass AllLogger {\n /**\n * create new PerfLogger\n */\n constructor(loggers) {\n this.loggers = loggers;\n }\n /** {@inheritDoc Logger.isEnabled} */\n isEnabled(level) {\n return this.loggers.some((logger) => logger.isEnabled(level));\n }\n /** {@inheritDoc Logger.debug} */\n debug(source, category, ...args) {\n for (const logger of this.loggers) {\n logger.debug(source, category, ...args);\n }\n }\n /** {@inheritDoc Logger.info} */\n info(source, category, ...args) {\n for (const logger of this.loggers) {\n logger.info(source, category, ...args);\n }\n }\n /** {@inheritDoc Logger.warn} */\n warn(source, category, ...args) {\n for (const logger of this.loggers) {\n logger.warn(source, category, ...args);\n }\n }\n /** {@inheritDoc Logger.error} */\n error(source, category, ...args) {\n for (const logger of this.loggers) {\n logger.error(source, category, ...args);\n }\n }\n /** {@inheritDoc Logger.perf} */\n perf(source, category, event, phase, ...args) {\n for (const logger of this.loggers) {\n logger.perf(source, category, event, phase, ...args);\n }\n }\n}\nvar TaskStage = /* @__PURE__ */ ((TaskStage2) => {\n TaskStage2[TaskStage2[\"Pending\"] = 0] = \"Pending\";\n TaskStage2[TaskStage2[\"Resolved\"] = 1] = \"Resolved\";\n TaskStage2[TaskStage2[\"Rejected\"] = 2] = \"Rejected\";\n TaskStage2[TaskStage2[\"Aborted\"] = 3] = \"Aborted\";\n return TaskStage2;\n})(TaskStage || {});\nclass TaskAbortedError extends Error {\n constructor(reason) {\n super(`Task aborted: ${JSON.stringify(reason)}`);\n this.name = \"TaskAbortedError\";\n this.reason = reason;\n }\n}\nclass TaskRejectedError extends Error {\n constructor(reason) {\n super(`Task rejected: ${JSON.stringify(reason)}`);\n this.name = \"TaskRejectedError\";\n this.reason = reason;\n }\n}\nclass Task {\n constructor() {\n this.state = {\n stage: 0\n /* Pending */\n };\n this.resolvedCallbacks = [];\n this.rejectedCallbacks = [];\n this._promise = null;\n this.progressCbs = [];\n }\n /**\n * Convert task to promise\n * @returns promise that will be resolved when task is settled\n */\n toPromise() {\n if (!this._promise) {\n this._promise = new Promise((resolve, reject) => {\n this.wait(\n (result) => resolve(result),\n (error) => {\n if (error.type === \"abort\") {\n reject(new TaskAbortedError(error.reason));\n } else {\n reject(new TaskRejectedError(error.reason));\n }\n }\n );\n });\n }\n return this._promise;\n }\n /**\n * wait for task to be settled\n * @param resolvedCallback - callback for resolved value\n * @param rejectedCallback - callback for rejected value\n */\n wait(resolvedCallback, rejectedCallback) {\n switch (this.state.stage) {\n case 0:\n this.resolvedCallbacks.push(resolvedCallback);\n this.rejectedCallbacks.push(rejectedCallback);\n break;\n case 1:\n resolvedCallback(this.state.result);\n break;\n case 2:\n rejectedCallback({\n type: \"reject\",\n reason: this.state.reason\n });\n break;\n case 3:\n rejectedCallback({\n type: \"abort\",\n reason: this.state.reason\n });\n break;\n }\n }\n /**\n * resolve task with specific result\n * @param result - result value\n */\n resolve(result) {\n if (this.state.stage === 0) {\n this.state = {\n stage: 1,\n result\n };\n for (const resolvedCallback of this.resolvedCallbacks) {\n try {\n resolvedCallback(result);\n } catch (e) {\n }\n }\n this.resolvedCallbacks = [];\n this.rejectedCallbacks = [];\n }\n }\n /**\n * reject task with specific reason\n * @param reason - abort reason\n *\n */\n reject(reason) {\n if (this.state.stage === 0) {\n this.state = {\n stage: 2,\n reason\n };\n for (const rejectedCallback of this.rejectedCallbacks) {\n try {\n rejectedCallback({\n type: \"reject\",\n reason\n });\n } catch (e) {\n }\n }\n this.resolvedCallbacks = [];\n this.rejectedCallbacks = [];\n }\n }\n /**\n * abort task with specific reason\n * @param reason - abort reason\n */\n abort(reason) {\n if (this.state.stage === 0) {\n this.state = {\n stage: 3,\n reason\n };\n for (const rejectedCallback of this.rejectedCallbacks) {\n try {\n rejectedCallback({\n type: \"abort\",\n reason\n });\n } catch (e) {\n }\n }\n this.resolvedCallbacks = [];\n this.rejectedCallbacks = [];\n }\n }\n /**\n * fail task with a TaskError from another task\n * This is a convenience method for error propagation between tasks\n * @param error - TaskError from another task\n */\n fail(error) {\n if (error.type === \"abort\") {\n this.abort(error.reason);\n } else {\n this.reject(error.reason);\n }\n }\n /**\n * add a progress callback\n * @param cb - progress callback\n */\n onProgress(cb) {\n this.progressCbs.push(cb);\n }\n /**\n * call progress callback\n * @param p - progress value\n */\n progress(p) {\n for (const cb of this.progressCbs) cb(p);\n }\n /**\n * Static method to wait for all tasks to resolve\n * Returns a new task that resolves with an array of all results\n * Rejects immediately if any task fails\n *\n * @param tasks - array of tasks to wait for\n * @returns new task that resolves when all input tasks resolve\n * @public\n */\n static all(tasks) {\n const combinedTask = new Task();\n if (tasks.length === 0) {\n combinedTask.resolve([]);\n return combinedTask;\n }\n const results = new Array(tasks.length);\n let resolvedCount = 0;\n let isSettled = false;\n tasks.forEach((task, index) => {\n task.wait(\n (result) => {\n if (isSettled) return;\n results[index] = result;\n resolvedCount++;\n if (resolvedCount === tasks.length) {\n isSettled = true;\n combinedTask.resolve(results);\n }\n },\n (error) => {\n if (isSettled) return;\n isSettled = true;\n if (error.type === \"abort\") {\n combinedTask.abort(error.reason);\n } else {\n combinedTask.reject(error.reason);\n }\n }\n );\n });\n return combinedTask;\n }\n /**\n * Static method to wait for all tasks to settle (resolve, reject, or abort)\n * Always resolves with an array of settlement results\n *\n * @param tasks - array of tasks to wait for\n * @returns new task that resolves when all input tasks settle\n * @public\n */\n static allSettled(tasks) {\n const combinedTask = new Task();\n if (tasks.length === 0) {\n combinedTask.resolve([]);\n return combinedTask;\n }\n const results = new Array(tasks.length);\n let settledCount = 0;\n tasks.forEach((task, index) => {\n task.wait(\n (result) => {\n results[index] = { status: \"resolved\", value: result };\n settledCount++;\n if (settledCount === tasks.length) {\n combinedTask.resolve(results);\n }\n },\n (error) => {\n results[index] = {\n status: error.type === \"abort\" ? \"aborted\" : \"rejected\",\n reason: error.reason\n };\n settledCount++;\n if (settledCount === tasks.length) {\n combinedTask.resolve(results);\n }\n }\n );\n });\n return combinedTask;\n }\n /**\n * Static method that resolves/rejects with the first task that settles\n *\n * @param tasks - array of tasks to race\n * @returns new task that settles with the first input task that settles\n * @public\n */\n static race(tasks) {\n const combinedTask = new Task();\n if (tasks.length === 0) {\n combinedTask.reject(\"No tasks provided\");\n return combinedTask;\n }\n let isSettled = false;\n tasks.forEach((task) => {\n task.wait(\n (result) => {\n if (isSettled) return;\n isSettled = true;\n combinedTask.resolve(result);\n },\n (error) => {\n if (isSettled) return;\n isSettled = true;\n if (error.type === \"abort\") {\n combinedTask.abort(error.reason);\n } else {\n combinedTask.reject(error.reason);\n }\n }\n );\n });\n return combinedTask;\n }\n /**\n * Utility to track progress of multiple tasks\n *\n * @param tasks - array of tasks to track\n * @param onProgress - callback called when any task completes\n * @returns new task that resolves when all input tasks resolve\n * @public\n */\n static withProgress(tasks, onProgress) {\n const combinedTask = Task.all(tasks);\n if (onProgress) {\n let completedCount = 0;\n tasks.forEach((task) => {\n task.wait(\n () => {\n completedCount++;\n onProgress(completedCount, tasks.length);\n },\n () => {\n completedCount++;\n onProgress(completedCount, tasks.length);\n }\n );\n });\n }\n return combinedTask;\n }\n}\nconst PdfSoftHyphenMarker = \"­\";\nconst PdfZeroWidthSpace = \"​\";\nconst PdfWordJoiner = \"⁠\";\nconst PdfBomOrZwnbsp = \"\\uFEFF\";\nconst PdfNonCharacterFFFE = \"￾\";\nconst PdfNonCharacterFFFF = \"￿\";\nconst PdfUnwantedTextMarkers = Object.freeze([\n PdfSoftHyphenMarker,\n PdfZeroWidthSpace,\n PdfWordJoiner,\n PdfBomOrZwnbsp,\n PdfNonCharacterFFFE,\n PdfNonCharacterFFFF\n]);\nconst PdfUnwantedTextRegex = new RegExp(`[${PdfUnwantedTextMarkers.join(\"\")}]`, \"g\");\nfunction stripPdfUnwantedMarkers(text) {\n return text.replace(PdfUnwantedTextRegex, \"\");\n}\nvar PdfZoomMode = /* @__PURE__ */ ((PdfZoomMode2) => {\n PdfZoomMode2[PdfZoomMode2[\"Unknown\"] = 0] = \"Unknown\";\n PdfZoomMode2[PdfZoomMode2[\"XYZ\"] = 1] = \"XYZ\";\n PdfZoomMode2[PdfZoomMode2[\"FitPage\"] = 2] = \"FitPage\";\n PdfZoomMode2[PdfZoomMode2[\"FitHorizontal\"] = 3] = \"FitHorizontal\";\n PdfZoomMode2[PdfZoomMode2[\"FitVertical\"] = 4] = \"FitVertical\";\n PdfZoomMode2[PdfZoomMode2[\"FitRectangle\"] = 5] = \"FitRectangle\";\n PdfZoomMode2[PdfZoomMode2[\"FitBoundingBox\"] = 6] = \"FitBoundingBox\";\n PdfZoomMode2[PdfZoomMode2[\"FitBoundingBoxHorizontal\"] = 7] = \"FitBoundingBoxHorizontal\";\n PdfZoomMode2[PdfZoomMode2[\"FitBoundingBoxVertical\"] = 8] = \"FitBoundingBoxVertical\";\n return PdfZoomMode2;\n})(PdfZoomMode || {});\nvar PdfTrappedStatus = /* @__PURE__ */ ((PdfTrappedStatus2) => {\n PdfTrappedStatus2[PdfTrappedStatus2[\"NotSet\"] = 0] = \"NotSet\";\n PdfTrappedStatus2[PdfTrappedStatus2[\"True\"] = 1] = \"True\";\n PdfTrappedStatus2[PdfTrappedStatus2[\"False\"] = 2] = \"False\";\n PdfTrappedStatus2[PdfTrappedStatus2[\"Unknown\"] = 3] = \"Unknown\";\n return PdfTrappedStatus2;\n})(PdfTrappedStatus || {});\nvar PdfStandardFont = /* @__PURE__ */ ((PdfStandardFont2) => {\n PdfStandardFont2[PdfStandardFont2[\"Unknown\"] = -1] = \"Unknown\";\n PdfStandardFont2[PdfStandardFont2[\"Courier\"] = 0] = \"Courier\";\n PdfStandardFont2[PdfStandardFont2[\"Courier_Bold\"] = 1] = \"Courier_Bold\";\n PdfStandardFont2[PdfStandardFont2[\"Courier_BoldOblique\"] = 2] = \"Courier_BoldOblique\";\n PdfStandardFont2[PdfStandardFont2[\"Courier_Oblique\"] = 3] = \"Courier_Oblique\";\n PdfStandardFont2[PdfStandardFont2[\"Helvetica\"] = 4] = \"Helvetica\";\n PdfStandardFont2[PdfStandardFont2[\"Helvetica_Bold\"] = 5] = \"Helvetica_Bold\";\n PdfStandardFont2[PdfStandardFont2[\"Helvetica_BoldOblique\"] = 6] = \"Helvetica_BoldOblique\";\n PdfStandardFont2[PdfStandardFont2[\"Helvetica_Oblique\"] = 7] = \"Helvetica_Oblique\";\n PdfStandardFont2[PdfStandardFont2[\"Times_Roman\"] = 8] = \"Times_Roman\";\n PdfStandardFont2[PdfStandardFont2[\"Times_Bold\"] = 9] = \"Times_Bold\";\n PdfStandardFont2[PdfStandardFont2[\"Times_BoldItalic\"] = 10] = \"Times_BoldItalic\";\n PdfStandardFont2[PdfStandardFont2[\"Times_Italic\"] = 11] = \"Times_Italic\";\n PdfStandardFont2[PdfStandardFont2[\"Symbol\"] = 12] = \"Symbol\";\n PdfStandardFont2[PdfStandardFont2[\"ZapfDingbats\"] = 13] = \"ZapfDingbats\";\n return PdfStandardFont2;\n})(PdfStandardFont || {});\nvar PdfTextAlignment = /* @__PURE__ */ ((PdfTextAlignment2) => {\n PdfTextAlignment2[PdfTextAlignment2[\"Left\"] = 0] = \"Left\";\n PdfTextAlignment2[PdfTextAlignment2[\"Center\"] = 1] = \"Center\";\n PdfTextAlignment2[PdfTextAlignment2[\"Right\"] = 2] = \"Right\";\n return PdfTextAlignment2;\n})(PdfTextAlignment || {});\nvar PdfVerticalAlignment = /* @__PURE__ */ ((PdfVerticalAlignment2) => {\n PdfVerticalAlignment2[PdfVerticalAlignment2[\"Top\"] = 0] = \"Top\";\n PdfVerticalAlignment2[PdfVerticalAlignment2[\"Middle\"] = 1] = \"Middle\";\n PdfVerticalAlignment2[PdfVerticalAlignment2[\"Bottom\"] = 2] = \"Bottom\";\n return PdfVerticalAlignment2;\n})(PdfVerticalAlignment || {});\nvar PdfBlendMode = /* @__PURE__ */ ((PdfBlendMode2) => {\n PdfBlendMode2[PdfBlendMode2[\"Normal\"] = 0] = \"Normal\";\n PdfBlendMode2[PdfBlendMode2[\"Multiply\"] = 1] = \"Multiply\";\n PdfBlendMode2[PdfBlendMode2[\"Screen\"] = 2] = \"Screen\";\n PdfBlendMode2[PdfBlendMode2[\"Overlay\"] = 3] = \"Overlay\";\n PdfBlendMode2[PdfBlendMode2[\"Darken\"] = 4] = \"Darken\";\n PdfBlendMode2[PdfBlendMode2[\"Lighten\"] = 5] = \"Lighten\";\n PdfBlendMode2[PdfBlendMode2[\"ColorDodge\"] = 6] = \"ColorDodge\";\n PdfBlendMode2[PdfBlendMode2[\"ColorBurn\"] = 7] = \"ColorBurn\";\n PdfBlendMode2[PdfBlendMode2[\"HardLight\"] = 8] = \"HardLight\";\n PdfBlendMode2[PdfBlendMode2[\"SoftLight\"] = 9] = \"SoftLight\";\n PdfBlendMode2[PdfBlendMode2[\"Difference\"] = 10] = \"Difference\";\n PdfBlendMode2[PdfBlendMode2[\"Exclusion\"] = 11] = \"Exclusion\";\n PdfBlendMode2[PdfBlendMode2[\"Hue\"] = 12] = \"Hue\";\n PdfBlendMode2[PdfBlendMode2[\"Saturation\"] = 13] = \"Saturation\";\n PdfBlendMode2[PdfBlendMode2[\"Color\"] = 14] = \"Color\";\n PdfBlendMode2[PdfBlendMode2[\"Luminosity\"] = 15] = \"Luminosity\";\n return PdfBlendMode2;\n})(PdfBlendMode || {});\nvar PdfStampFit = /* @__PURE__ */ ((PdfStampFit2) => {\n PdfStampFit2[PdfStampFit2[\"Contain\"] = 0] = \"Contain\";\n PdfStampFit2[PdfStampFit2[\"Cover\"] = 1] = \"Cover\";\n PdfStampFit2[PdfStampFit2[\"Stretch\"] = 2] = \"Stretch\";\n return PdfStampFit2;\n})(PdfStampFit || {});\nvar PdfActionType = /* @__PURE__ */ ((PdfActionType2) => {\n PdfActionType2[PdfActionType2[\"Unsupported\"] = 0] = \"Unsupported\";\n PdfActionType2[PdfActionType2[\"Goto\"] = 1] = \"Goto\";\n PdfActionType2[PdfActionType2[\"RemoteGoto\"] = 2] = \"RemoteGoto\";\n PdfActionType2[PdfActionType2[\"URI\"] = 3] = \"URI\";\n PdfActionType2[PdfActionType2[\"LaunchAppOrOpenFile\"] = 4] = \"LaunchAppOrOpenFile\";\n return PdfActionType2;\n})(PdfActionType || {});\nconst AP_MODE_NORMAL = 1;\nconst AP_MODE_ROLLOVER = 2;\nconst AP_MODE_DOWN = 4;\nvar PdfAnnotationSubtype = /* @__PURE__ */ ((PdfAnnotationSubtype2) => {\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"UNKNOWN\"] = 0] = \"UNKNOWN\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"TEXT\"] = 1] = \"TEXT\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"LINK\"] = 2] = \"LINK\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"FREETEXT\"] = 3] = \"FREETEXT\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"LINE\"] = 4] = \"LINE\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"SQUARE\"] = 5] = \"SQUARE\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"CIRCLE\"] = 6] = \"CIRCLE\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"POLYGON\"] = 7] = \"POLYGON\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"POLYLINE\"] = 8] = \"POLYLINE\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"HIGHLIGHT\"] = 9] = \"HIGHLIGHT\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"UNDERLINE\"] = 10] = \"UNDERLINE\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"SQUIGGLY\"] = 11] = \"SQUIGGLY\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"STRIKEOUT\"] = 12] = \"STRIKEOUT\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"STAMP\"] = 13] = \"STAMP\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"CARET\"] = 14] = \"CARET\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"INK\"] = 15] = \"INK\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"POPUP\"] = 16] = \"POPUP\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"FILEATTACHMENT\"] = 17] = \"FILEATTACHMENT\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"SOUND\"] = 18] = \"SOUND\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"MOVIE\"] = 19] = \"MOVIE\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"WIDGET\"] = 20] = \"WIDGET\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"SCREEN\"] = 21] = \"SCREEN\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"PRINTERMARK\"] = 22] = \"PRINTERMARK\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"TRAPNET\"] = 23] = \"TRAPNET\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"WATERMARK\"] = 24] = \"WATERMARK\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"THREED\"] = 25] = \"THREED\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"RICHMEDIA\"] = 26] = \"RICHMEDIA\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"XFAWIDGET\"] = 27] = \"XFAWIDGET\";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2[\"REDACT\"] = 28] = \"REDACT\";\n return PdfAnnotationSubtype2;\n})(PdfAnnotationSubtype || {});\nconst PdfAnnotationSubtypeName = {\n [\n 0\n /* UNKNOWN */\n ]: \"unknow\",\n [\n 1\n /* TEXT */\n ]: \"text\",\n [\n 2\n /* LINK */\n ]: \"link\",\n [\n 3\n /* FREETEXT */\n ]: \"freetext\",\n [\n 4\n /* LINE */\n ]: \"line\",\n [\n 5\n /* SQUARE */\n ]: \"square\",\n [\n 6\n /* CIRCLE */\n ]: \"circle\",\n [\n 7\n /* POLYGON */\n ]: \"polygon\",\n [\n 8\n /* POLYLINE */\n ]: \"polyline\",\n [\n 9\n /* HIGHLIGHT */\n ]: \"highlight\",\n [\n 10\n /* UNDERLINE */\n ]: \"underline\",\n [\n 11\n /* SQUIGGLY */\n ]: \"squiggly\",\n [\n 12\n /* STRIKEOUT */\n ]: \"strikeout\",\n [\n 13\n /* STAMP */\n ]: \"stamp\",\n [\n 14\n /* CARET */\n ]: \"caret\",\n [\n 15\n /* INK */\n ]: \"ink\",\n [\n 16\n /* POPUP */\n ]: \"popup\",\n [\n 17\n /* FILEATTACHMENT */\n ]: \"fileattachment\",\n [\n 18\n /* SOUND */\n ]: \"sound\",\n [\n 19\n /* MOVIE */\n ]: \"movie\",\n [\n 20\n /* WIDGET */\n ]: \"widget\",\n [\n 21\n /* SCREEN */\n ]: \"screen\",\n [\n 22\n /* PRINTERMARK */\n ]: \"printermark\",\n [\n 23\n /* TRAPNET */\n ]: \"trapnet\",\n [\n 24\n /* WATERMARK */\n ]: \"watermark\",\n [\n 25\n /* THREED */\n ]: \"threed\",\n [\n 26\n /* RICHMEDIA */\n ]: \"richmedia\",\n [\n 27\n /* XFAWIDGET */\n ]: \"xfawidget\",\n [\n 28\n /* REDACT */\n ]: \"redact\"\n};\nvar PdfAnnotationObjectStatus = /* @__PURE__ */ ((PdfAnnotationObjectStatus2) => {\n PdfAnnotationObjectStatus2[PdfAnnotationObjectStatus2[\"Created\"] = 0] = \"Created\";\n PdfAnnotationObjectStatus2[PdfAnnotationObjectStatus2[\"Committed\"] = 1] = \"Committed\";\n return PdfAnnotationObjectStatus2;\n})(PdfAnnotationObjectStatus || {});\nvar AppearanceMode = /* @__PURE__ */ ((AppearanceMode2) => {\n AppearanceMode2[AppearanceMode2[\"Normal\"] = 0] = \"Normal\";\n AppearanceMode2[AppearanceMode2[\"Rollover\"] = 1] = \"Rollover\";\n AppearanceMode2[AppearanceMode2[\"Down\"] = 2] = \"Down\";\n return AppearanceMode2;\n})(AppearanceMode || {});\nvar PdfAnnotationState = /* @__PURE__ */ ((PdfAnnotationState2) => {\n PdfAnnotationState2[\"Marked\"] = \"Marked\";\n PdfAnnotationState2[\"Unmarked\"] = \"Unmarked\";\n PdfAnnotationState2[\"Accepted\"] = \"Accepted\";\n PdfAnnotationState2[\"Rejected\"] = \"Rejected\";\n PdfAnnotationState2[\"Completed\"] = \"Completed\";\n PdfAnnotationState2[\"Cancelled\"] = \"Cancelled\";\n PdfAnnotationState2[\"None\"] = \"None\";\n return PdfAnnotationState2;\n})(PdfAnnotationState || {});\nvar PdfAnnotationStateModel = /* @__PURE__ */ ((PdfAnnotationStateModel2) => {\n PdfAnnotationStateModel2[\"Marked\"] = \"Marked\";\n PdfAnnotationStateModel2[\"Review\"] = \"Review\";\n return PdfAnnotationStateModel2;\n})(PdfAnnotationStateModel || {});\nvar PdfAnnotationName = /* @__PURE__ */ ((PdfAnnotationName2) => {\n PdfAnnotationName2[PdfAnnotationName2[\"Unknown\"] = -1] = \"Unknown\";\n PdfAnnotationName2[PdfAnnotationName2[\"Comment\"] = 0] = \"Comment\";\n PdfAnnotationName2[PdfAnnotationName2[\"Key\"] = 1] = \"Key\";\n PdfAnnotationName2[PdfAnnotationName2[\"Note\"] = 2] = \"Note\";\n PdfAnnotationName2[PdfAnnotationName2[\"Help\"] = 3] = \"Help\";\n PdfAnnotationName2[PdfAnnotationName2[\"NewParagraph\"] = 4] = \"NewParagraph\";\n PdfAnnotationName2[PdfAnnotationName2[\"Paragraph\"] = 5] = \"Paragraph\";\n PdfAnnotationName2[PdfAnnotationName2[\"Insert\"] = 6] = \"Insert\";\n PdfAnnotationName2[PdfAnnotationName2[\"Graph\"] = 7] = \"Graph\";\n PdfAnnotationName2[PdfAnnotationName2[\"PushPin\"] = 8] = \"PushPin\";\n PdfAnnotationName2[PdfAnnotationName2[\"Paperclip\"] = 9] = \"Paperclip\";\n PdfAnnotationName2[PdfAnnotationName2[\"Tag\"] = 10] = \"Tag\";\n PdfAnnotationName2[PdfAnnotationName2[\"Speaker\"] = 11] = \"Speaker\";\n PdfAnnotationName2[PdfAnnotationName2[\"Mic\"] = 12] = \"Mic\";\n PdfAnnotationName2[PdfAnnotationName2[\"Approved\"] = 13] = \"Approved\";\n PdfAnnotationName2[PdfAnnotationName2[\"Experimental\"] = 14] = \"Experimental\";\n PdfAnnotationName2[PdfAnnotationName2[\"NotApproved\"] = 15] = \"NotApproved\";\n PdfAnnotationName2[PdfAnnotationName2[\"AsIs\"] = 16] = \"AsIs\";\n PdfAnnotationName2[PdfAnnotationName2[\"Expired\"] = 17] = \"Expired\";\n PdfAnnotationName2[PdfAnnotationName2[\"NotForPublicRelease\"] = 18] = \"NotForPublicRelease\";\n PdfAnnotationName2[PdfAnnotationName2[\"Confidential\"] = 19] = \"Confidential\";\n PdfAnnotationName2[PdfAnnotationName2[\"Final\"] = 20] = \"Final\";\n PdfAnnotationName2[PdfAnnotationName2[\"Sold\"] = 21] = \"Sold\";\n PdfAnnotationName2[PdfAnnotationName2[\"Departmental\"] = 22] = \"Departmental\";\n PdfAnnotationName2[PdfAnnotationName2[\"ForComment\"] = 23] = \"ForComment\";\n PdfAnnotationName2[PdfAnnotationName2[\"TopSecret\"] = 24] = \"TopSecret\";\n PdfAnnotationName2[PdfAnnotationName2[\"Draft\"] = 25] = \"Draft\";\n PdfAnnotationName2[PdfAnnotationName2[\"ForPublicRelease\"] = 26] = \"ForPublicRelease\";\n PdfAnnotationName2[PdfAnnotationName2[\"Completed\"] = 27] = \"Completed\";\n PdfAnnotationName2[PdfAnnotationName2[\"Void\"] = 28] = \"Void\";\n PdfAnnotationName2[PdfAnnotationName2[\"PreliminaryResults\"] = 29] = \"PreliminaryResults\";\n PdfAnnotationName2[PdfAnnotationName2[\"InformationOnly\"] = 30] = \"InformationOnly\";\n PdfAnnotationName2[PdfAnnotationName2[\"Rejected\"] = 31] = \"Rejected\";\n PdfAnnotationName2[PdfAnnotationName2[\"Witness\"] = 32] = \"Witness\";\n PdfAnnotationName2[PdfAnnotationName2[\"InitialHere\"] = 33] = \"InitialHere\";\n PdfAnnotationName2[PdfAnnotationName2[\"SignHere\"] = 34] = \"SignHere\";\n PdfAnnotationName2[PdfAnnotationName2[\"Accepted\"] = 35] = \"Accepted\";\n PdfAnnotationName2[PdfAnnotationName2[\"Custom\"] = 36] = \"Custom\";\n PdfAnnotationName2[PdfAnnotationName2[\"Image\"] = 37] = \"Image\";\n return PdfAnnotationName2;\n})(PdfAnnotationName || {});\nconst PdfAnnotationIcon = PdfAnnotationName;\nvar PdfAnnotationLineEnding = /* @__PURE__ */ ((PdfAnnotationLineEnding2) => {\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2[\"None\"] = 0] = \"None\";\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2[\"Square\"] = 1] = \"Square\";\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2[\"Circle\"] = 2] = \"Circle\";\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2[\"Diamond\"] = 3] = \"Diamond\";\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2[\"OpenArrow\"] = 4] = \"OpenArrow\";\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2[\"ClosedArrow\"] = 5] = \"ClosedArrow\";\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2[\"Butt\"] = 6] = \"Butt\";\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2[\"ROpenArrow\"] = 7] = \"ROpenArrow\";\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2[\"RClosedArrow\"] = 8] = \"RClosedArrow\";\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2[\"Slash\"] = 9] = \"Slash\";\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2[\"Unknown\"] = 10] = \"Unknown\";\n return PdfAnnotationLineEnding2;\n})(PdfAnnotationLineEnding || {});\nvar PdfAnnotationReplyType = /* @__PURE__ */ ((PdfAnnotationReplyType2) => {\n PdfAnnotationReplyType2[PdfAnnotationReplyType2[\"Unknown\"] = 0] = \"Unknown\";\n PdfAnnotationReplyType2[PdfAnnotationReplyType2[\"Reply\"] = 1] = \"Reply\";\n PdfAnnotationReplyType2[PdfAnnotationReplyType2[\"Group\"] = 2] = \"Group\";\n return PdfAnnotationReplyType2;\n})(PdfAnnotationReplyType || {});\nvar PDF_FORM_FIELD_TYPE = /* @__PURE__ */ ((PDF_FORM_FIELD_TYPE2) => {\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2[\"UNKNOWN\"] = 0] = \"UNKNOWN\";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2[\"PUSHBUTTON\"] = 1] = \"PUSHBUTTON\";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2[\"CHECKBOX\"] = 2] = \"CHECKBOX\";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2[\"RADIOBUTTON\"] = 3] = \"RADIOBUTTON\";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2[\"COMBOBOX\"] = 4] = \"COMBOBOX\";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2[\"LISTBOX\"] = 5] = \"LISTBOX\";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2[\"TEXTFIELD\"] = 6] = \"TEXTFIELD\";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2[\"SIGNATURE\"] = 7] = \"SIGNATURE\";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2[\"XFA\"] = 8] = \"XFA\";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2[\"XFA_CHECKBOX\"] = 9] = \"XFA_CHECKBOX\";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2[\"XFA_COMBOBOX\"] = 10] = \"XFA_COMBOBOX\";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2[\"XFA_IMAGEFIELD\"] = 11] = \"XFA_IMAGEFIELD\";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2[\"XFA_LISTBOX\"] = 12] = \"XFA_LISTBOX\";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2[\"XFA_PUSHBUTTON\"] = 13] = \"XFA_PUSHBUTTON\";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2[\"XFA_SIGNATURE\"] = 14] = \"XFA_SIGNATURE\";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2[\"XFA_TEXTFIELD\"] = 15] = \"XFA_TEXTFIELD\";\n return PDF_FORM_FIELD_TYPE2;\n})(PDF_FORM_FIELD_TYPE || {});\nvar PdfAnnotationColorType = /* @__PURE__ */ ((PdfAnnotationColorType2) => {\n PdfAnnotationColorType2[PdfAnnotationColorType2[\"Color\"] = 0] = \"Color\";\n PdfAnnotationColorType2[PdfAnnotationColorType2[\"InteriorColor\"] = 1] = \"InteriorColor\";\n PdfAnnotationColorType2[PdfAnnotationColorType2[\"OverlayColor\"] = 2] = \"OverlayColor\";\n PdfAnnotationColorType2[PdfAnnotationColorType2[\"TextColor\"] = 3] = \"TextColor\";\n return PdfAnnotationColorType2;\n})(PdfAnnotationColorType || {});\nvar PdfAnnotationBorderStyle = /* @__PURE__ */ ((PdfAnnotationBorderStyle2) => {\n PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2[\"UNKNOWN\"] = 0] = \"UNKNOWN\";\n PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2[\"SOLID\"] = 1] = \"SOLID\";\n PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2[\"DASHED\"] = 2] = \"DASHED\";\n PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2[\"BEVELED\"] = 3] = \"BEVELED\";\n PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2[\"INSET\"] = 4] = \"INSET\";\n PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2[\"UNDERLINE\"] = 5] = \"UNDERLINE\";\n PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2[\"CLOUDY\"] = 6] = \"CLOUDY\";\n return PdfAnnotationBorderStyle2;\n})(PdfAnnotationBorderStyle || {});\nvar PdfAnnotationFlags = /* @__PURE__ */ ((PdfAnnotationFlags2) => {\n PdfAnnotationFlags2[PdfAnnotationFlags2[\"NONE\"] = 0] = \"NONE\";\n PdfAnnotationFlags2[PdfAnnotationFlags2[\"INVISIBLE\"] = 1] = \"INVISIBLE\";\n PdfAnnotationFlags2[PdfAnnotationFlags2[\"HIDDEN\"] = 2] = \"HIDDEN\";\n PdfAnnotationFlags2[PdfAnnotationFlags2[\"PRINT\"] = 4] = \"PRINT\";\n PdfAnnotationFlags2[PdfAnnotationFlags2[\"NO_ZOOM\"] = 8] = \"NO_ZOOM\";\n PdfAnnotationFlags2[PdfAnnotationFlags2[\"NO_ROTATE\"] = 16] = \"NO_ROTATE\";\n PdfAnnotationFlags2[PdfAnnotationFlags2[\"NO_VIEW\"] = 32] = \"NO_VIEW\";\n PdfAnnotationFlags2[PdfAnnotationFlags2[\"READ_ONLY\"] = 64] = \"READ_ONLY\";\n PdfAnnotationFlags2[PdfAnnotationFlags2[\"LOCKED\"] = 128] = \"LOCKED\";\n PdfAnnotationFlags2[PdfAnnotationFlags2[\"TOGGLE_NOVIEW\"] = 256] = \"TOGGLE_NOVIEW\";\n PdfAnnotationFlags2[PdfAnnotationFlags2[\"LOCKED_CONTENTS\"] = 512] = \"LOCKED_CONTENTS\";\n return PdfAnnotationFlags2;\n})(PdfAnnotationFlags || {});\nvar PDF_FORM_FIELD_FLAG = /* @__PURE__ */ ((PDF_FORM_FIELD_FLAG2) => {\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"NONE\"] = 0] = \"NONE\";\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"READONLY\"] = 1] = \"READONLY\";\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"REQUIRED\"] = 2] = \"REQUIRED\";\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"NOEXPORT\"] = 4] = \"NOEXPORT\";\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"TEXT_MULTIPLINE\"] = 4096] = \"TEXT_MULTIPLINE\";\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"TEXT_PASSWORD\"] = 8192] = \"TEXT_PASSWORD\";\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"TEXT_FILESELECT\"] = 1048576] = \"TEXT_FILESELECT\";\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"TEXT_DONOTSPELLCHECK\"] = 4194304] = \"TEXT_DONOTSPELLCHECK\";\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"TEXT_DONOTSCROLL\"] = 8388608] = \"TEXT_DONOTSCROLL\";\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"TEXT_COMB\"] = 16777216] = \"TEXT_COMB\";\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"TEXT_RICHTEXT\"] = 33554432] = \"TEXT_RICHTEXT\";\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"BUTTON_NOTOGGLETOOFF\"] = 16384] = \"BUTTON_NOTOGGLETOOFF\";\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"BUTTON_RADIO\"] = 32768] = \"BUTTON_RADIO\";\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"BUTTON_PUSHBUTTON\"] = 65536] = \"BUTTON_PUSHBUTTON\";\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"BUTTON_RADIOSINUNISON\"] = 33554432] = \"BUTTON_RADIOSINUNISON\";\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"CHOICE_COMBO\"] = 131072] = \"CHOICE_COMBO\";\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"CHOICE_EDIT\"] = 262144] = \"CHOICE_EDIT\";\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"CHOICE_SORT\"] = 524288] = \"CHOICE_SORT\";\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"CHOICE_MULTL_SELECT\"] = 2097152] = \"CHOICE_MULTL_SELECT\";\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"CHOICE_DONOTSPELLCHECK\"] = 4194304] = \"CHOICE_DONOTSPELLCHECK\";\n PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2[\"CHOICE_COMMITONSELCHANGE\"] = 67108864] = \"CHOICE_COMMITONSELCHANGE\";\n return PDF_FORM_FIELD_FLAG2;\n})(PDF_FORM_FIELD_FLAG || {});\nvar PdfPageObjectType = /* @__PURE__ */ ((PdfPageObjectType2) => {\n PdfPageObjectType2[PdfPageObjectType2[\"UNKNOWN\"] = 0] = \"UNKNOWN\";\n PdfPageObjectType2[PdfPageObjectType2[\"TEXT\"] = 1] = \"TEXT\";\n PdfPageObjectType2[PdfPageObjectType2[\"PATH\"] = 2] = \"PATH\";\n PdfPageObjectType2[PdfPageObjectType2[\"IMAGE\"] = 3] = \"IMAGE\";\n PdfPageObjectType2[PdfPageObjectType2[\"SHADING\"] = 4] = \"SHADING\";\n PdfPageObjectType2[PdfPageObjectType2[\"FORM\"] = 5] = \"FORM\";\n return PdfPageObjectType2;\n})(PdfPageObjectType || {});\nconst PdfAnnotationFlagName = Object.freeze({\n [\n 1\n /* INVISIBLE */\n ]: \"invisible\",\n [\n 2\n /* HIDDEN */\n ]: \"hidden\",\n [\n 4\n /* PRINT */\n ]: \"print\",\n [\n 8\n /* NO_ZOOM */\n ]: \"noZoom\",\n [\n 16\n /* NO_ROTATE */\n ]: \"noRotate\",\n [\n 32\n /* NO_VIEW */\n ]: \"noView\",\n [\n 64\n /* READ_ONLY */\n ]: \"readOnly\",\n [\n 128\n /* LOCKED */\n ]: \"locked\",\n [\n 256\n /* TOGGLE_NOVIEW */\n ]: \"toggleNoView\",\n [\n 512\n /* LOCKED_CONTENTS */\n ]: \"lockedContents\"\n});\nconst PdfAnnotationFlagValue = Object.entries(\n PdfAnnotationFlagName\n).reduce(\n (acc, [bit, name]) => {\n acc[name] = Number(bit);\n return acc;\n },\n {}\n);\nfunction flagsToNames(raw) {\n return Object.keys(PdfAnnotationFlagName).filter((flag) => (raw & flag) !== 0).map((flag) => PdfAnnotationFlagName[flag]);\n}\nfunction namesToFlags(names) {\n return names.reduce(\n (mask, name) => mask | PdfAnnotationFlagValue[name],\n 0\n /* NONE */\n );\n}\nfunction isWidgetChecked(widget) {\n return widget.exportValue != null && widget.field.value === widget.exportValue;\n}\nvar PDF_ANNOT_AACTION_EVENT = /* @__PURE__ */ ((PDF_ANNOT_AACTION_EVENT2) => {\n PDF_ANNOT_AACTION_EVENT2[PDF_ANNOT_AACTION_EVENT2[\"KEY_STROKE\"] = 12] = \"KEY_STROKE\";\n PDF_ANNOT_AACTION_EVENT2[PDF_ANNOT_AACTION_EVENT2[\"FORMAT\"] = 13] = \"FORMAT\";\n PDF_ANNOT_AACTION_EVENT2[PDF_ANNOT_AACTION_EVENT2[\"VALIDATE\"] = 14] = \"VALIDATE\";\n PDF_ANNOT_AACTION_EVENT2[PDF_ANNOT_AACTION_EVENT2[\"CALCULATE\"] = 15] = \"CALCULATE\";\n return PDF_ANNOT_AACTION_EVENT2;\n})(PDF_ANNOT_AACTION_EVENT || {});\nvar PdfJavaScriptWidgetEventType = /* @__PURE__ */ ((PdfJavaScriptWidgetEventType2) => {\n PdfJavaScriptWidgetEventType2[\"Keystroke\"] = \"keystroke\";\n PdfJavaScriptWidgetEventType2[\"Format\"] = \"format\";\n PdfJavaScriptWidgetEventType2[\"Validate\"] = \"validate\";\n PdfJavaScriptWidgetEventType2[\"Calculate\"] = \"calculate\";\n return PdfJavaScriptWidgetEventType2;\n})(PdfJavaScriptWidgetEventType || {});\nvar PdfJavaScriptActionTrigger = /* @__PURE__ */ ((PdfJavaScriptActionTrigger2) => {\n PdfJavaScriptActionTrigger2[\"DocumentNamed\"] = \"document_named\";\n PdfJavaScriptActionTrigger2[\"WidgetKeystroke\"] = \"widget_keystroke\";\n PdfJavaScriptActionTrigger2[\"WidgetFormat\"] = \"widget_format\";\n PdfJavaScriptActionTrigger2[\"WidgetValidate\"] = \"widget_validate\";\n PdfJavaScriptActionTrigger2[\"WidgetCalculate\"] = \"widget_calculate\";\n return PdfJavaScriptActionTrigger2;\n})(PdfJavaScriptActionTrigger || {});\nvar PdfSegmentObjectType = /* @__PURE__ */ ((PdfSegmentObjectType2) => {\n PdfSegmentObjectType2[PdfSegmentObjectType2[\"UNKNOWN\"] = -1] = \"UNKNOWN\";\n PdfSegmentObjectType2[PdfSegmentObjectType2[\"LINETO\"] = 0] = \"LINETO\";\n PdfSegmentObjectType2[PdfSegmentObjectType2[\"BEZIERTO\"] = 1] = \"BEZIERTO\";\n PdfSegmentObjectType2[PdfSegmentObjectType2[\"MOVETO\"] = 2] = \"MOVETO\";\n return PdfSegmentObjectType2;\n})(PdfSegmentObjectType || {});\nvar FontCharset = /* @__PURE__ */ ((FontCharset2) => {\n FontCharset2[FontCharset2[\"ANSI\"] = 0] = \"ANSI\";\n FontCharset2[FontCharset2[\"DEFAULT\"] = 1] = \"DEFAULT\";\n FontCharset2[FontCharset2[\"SYMBOL\"] = 2] = \"SYMBOL\";\n FontCharset2[FontCharset2[\"SHIFTJIS\"] = 128] = \"SHIFTJIS\";\n FontCharset2[FontCharset2[\"HANGEUL\"] = 129] = \"HANGEUL\";\n FontCharset2[FontCharset2[\"GB2312\"] = 134] = \"GB2312\";\n FontCharset2[FontCharset2[\"CHINESEBIG5\"] = 136] = \"CHINESEBIG5\";\n FontCharset2[FontCharset2[\"GREEK\"] = 161] = \"GREEK\";\n FontCharset2[FontCharset2[\"VIETNAMESE\"] = 163] = \"VIETNAMESE\";\n FontCharset2[FontCharset2[\"HEBREW\"] = 177] = \"HEBREW\";\n FontCharset2[FontCharset2[\"ARABIC\"] = 178] = \"ARABIC\";\n FontCharset2[FontCharset2[\"CYRILLIC\"] = 204] = \"CYRILLIC\";\n FontCharset2[FontCharset2[\"THAI\"] = 222] = \"THAI\";\n FontCharset2[FontCharset2[\"EASTERNEUROPEAN\"] = 238] = \"EASTERNEUROPEAN\";\n return FontCharset2;\n})(FontCharset || {});\nvar PdfEngineFeature = /* @__PURE__ */ ((PdfEngineFeature2) => {\n PdfEngineFeature2[PdfEngineFeature2[\"RenderPage\"] = 0] = \"RenderPage\";\n PdfEngineFeature2[PdfEngineFeature2[\"RenderPageRect\"] = 1] = \"RenderPageRect\";\n PdfEngineFeature2[PdfEngineFeature2[\"Thumbnails\"] = 2] = \"Thumbnails\";\n PdfEngineFeature2[PdfEngineFeature2[\"Bookmarks\"] = 3] = \"Bookmarks\";\n PdfEngineFeature2[PdfEngineFeature2[\"Annotations\"] = 4] = \"Annotations\";\n return PdfEngineFeature2;\n})(PdfEngineFeature || {});\nvar PdfEngineOperation = /* @__PURE__ */ ((PdfEngineOperation2) => {\n PdfEngineOperation2[PdfEngineOperation2[\"Create\"] = 0] = \"Create\";\n PdfEngineOperation2[PdfEngineOperation2[\"Read\"] = 1] = \"Read\";\n PdfEngineOperation2[PdfEngineOperation2[\"Update\"] = 2] = \"Update\";\n PdfEngineOperation2[PdfEngineOperation2[\"Delete\"] = 3] = \"Delete\";\n return PdfEngineOperation2;\n})(PdfEngineOperation || {});\nvar MatchFlag = /* @__PURE__ */ ((MatchFlag2) => {\n MatchFlag2[MatchFlag2[\"None\"] = 0] = \"None\";\n MatchFlag2[MatchFlag2[\"MatchCase\"] = 1] = \"MatchCase\";\n MatchFlag2[MatchFlag2[\"MatchWholeWord\"] = 2] = \"MatchWholeWord\";\n MatchFlag2[MatchFlag2[\"MatchConsecutive\"] = 4] = \"MatchConsecutive\";\n return MatchFlag2;\n})(MatchFlag || {});\nfunction unionFlags(flags) {\n return flags.reduce(\n (flag, currFlag) => {\n return flag | currFlag;\n },\n 0\n /* None */\n );\n}\nfunction compareSearchTarget(targetA, targetB) {\n const flagA = unionFlags(targetA.flags);\n const flagB = unionFlags(targetB.flags);\n return flagA === flagB && targetA.keyword === targetB.keyword;\n}\nvar PdfPermissionFlag = /* @__PURE__ */ ((PdfPermissionFlag2) => {\n PdfPermissionFlag2[PdfPermissionFlag2[\"Print\"] = 4] = \"Print\";\n PdfPermissionFlag2[PdfPermissionFlag2[\"ModifyContents\"] = 8] = \"ModifyContents\";\n PdfPermissionFlag2[PdfPermissionFlag2[\"CopyContents\"] = 16] = \"CopyContents\";\n PdfPermissionFlag2[PdfPermissionFlag2[\"ModifyAnnotations\"] = 32] = \"ModifyAnnotations\";\n PdfPermissionFlag2[PdfPermissionFlag2[\"FillForms\"] = 256] = \"FillForms\";\n PdfPermissionFlag2[PdfPermissionFlag2[\"ExtractForAccessibility\"] = 512] = \"ExtractForAccessibility\";\n PdfPermissionFlag2[PdfPermissionFlag2[\"AssembleDocument\"] = 1024] = \"AssembleDocument\";\n PdfPermissionFlag2[PdfPermissionFlag2[\"PrintHighQuality\"] = 2048] = \"PrintHighQuality\";\n PdfPermissionFlag2[PdfPermissionFlag2[\"AllowAll\"] = 3900] = \"AllowAll\";\n return PdfPermissionFlag2;\n})(PdfPermissionFlag || {});\nfunction buildPermissions(...flags) {\n let result = flags.reduce((acc, flag) => acc | flag, 0);\n if (result & 2048) {\n result |= 4;\n }\n return result;\n}\nclass PermissionDeniedError extends Error {\n constructor(requiredFlags, currentPermissions) {\n const flagNames = requiredFlags.map((f) => PdfPermissionFlag[f]).join(\", \");\n super(`Permission denied. Required: ${flagNames}`);\n this.requiredFlags = requiredFlags;\n this.currentPermissions = currentPermissions;\n this.name = \"PermissionDeniedError\";\n }\n}\nvar PdfPageFlattenFlag = /* @__PURE__ */ ((PdfPageFlattenFlag2) => {\n PdfPageFlattenFlag2[PdfPageFlattenFlag2[\"Display\"] = 0] = \"Display\";\n PdfPageFlattenFlag2[PdfPageFlattenFlag2[\"Print\"] = 1] = \"Print\";\n return PdfPageFlattenFlag2;\n})(PdfPageFlattenFlag || {});\nvar PdfPageFlattenResult = /* @__PURE__ */ ((PdfPageFlattenResult2) => {\n PdfPageFlattenResult2[PdfPageFlattenResult2[\"Fail\"] = 0] = \"Fail\";\n PdfPageFlattenResult2[PdfPageFlattenResult2[\"Success\"] = 1] = \"Success\";\n PdfPageFlattenResult2[PdfPageFlattenResult2[\"NothingToDo\"] = 2] = \"NothingToDo\";\n return PdfPageFlattenResult2;\n})(PdfPageFlattenResult || {});\nvar PdfErrorCode = /* @__PURE__ */ ((PdfErrorCode2) => {\n PdfErrorCode2[PdfErrorCode2[\"Ok\"] = 0] = \"Ok\";\n PdfErrorCode2[PdfErrorCode2[\"Unknown\"] = 1] = \"Unknown\";\n PdfErrorCode2[PdfErrorCode2[\"NotFound\"] = 2] = \"NotFound\";\n PdfErrorCode2[PdfErrorCode2[\"WrongFormat\"] = 3] = \"WrongFormat\";\n PdfErrorCode2[PdfErrorCode2[\"Password\"] = 4] = \"Password\";\n PdfErrorCode2[PdfErrorCode2[\"Security\"] = 5] = \"Security\";\n PdfErrorCode2[PdfErrorCode2[\"PageError\"] = 6] = \"PageError\";\n PdfErrorCode2[PdfErrorCode2[\"XFALoad\"] = 7] = \"XFALoad\";\n PdfErrorCode2[PdfErrorCode2[\"XFALayout\"] = 8] = \"XFALayout\";\n PdfErrorCode2[PdfErrorCode2[\"Cancelled\"] = 9] = \"Cancelled\";\n PdfErrorCode2[PdfErrorCode2[\"Initialization\"] = 10] = \"Initialization\";\n PdfErrorCode2[PdfErrorCode2[\"NotReady\"] = 11] = \"NotReady\";\n PdfErrorCode2[PdfErrorCode2[\"NotSupport\"] = 12] = \"NotSupport\";\n PdfErrorCode2[PdfErrorCode2[\"LoadDoc\"] = 13] = \"LoadDoc\";\n PdfErrorCode2[PdfErrorCode2[\"DocNotOpen\"] = 14] = \"DocNotOpen\";\n PdfErrorCode2[PdfErrorCode2[\"CantCloseDoc\"] = 15] = \"CantCloseDoc\";\n PdfErrorCode2[PdfErrorCode2[\"CantCreateNewDoc\"] = 16] = \"CantCreateNewDoc\";\n PdfErrorCode2[PdfErrorCode2[\"CantImportPages\"] = 17] = \"CantImportPages\";\n PdfErrorCode2[PdfErrorCode2[\"CantCreateAnnot\"] = 18] = \"CantCreateAnnot\";\n PdfErrorCode2[PdfErrorCode2[\"CantSetAnnotRect\"] = 19] = \"CantSetAnnotRect\";\n PdfErrorCode2[PdfErrorCode2[\"CantSetAnnotContent\"] = 20] = \"CantSetAnnotContent\";\n PdfErrorCode2[PdfErrorCode2[\"CantRemoveInkList\"] = 21] = \"CantRemoveInkList\";\n PdfErrorCode2[PdfErrorCode2[\"CantAddInkStoke\"] = 22] = \"CantAddInkStoke\";\n PdfErrorCode2[PdfErrorCode2[\"CantReadAttachmentSize\"] = 23] = \"CantReadAttachmentSize\";\n PdfErrorCode2[PdfErrorCode2[\"CantReadAttachmentContent\"] = 24] = \"CantReadAttachmentContent\";\n PdfErrorCode2[PdfErrorCode2[\"CantFocusAnnot\"] = 25] = \"CantFocusAnnot\";\n PdfErrorCode2[PdfErrorCode2[\"CantSelectText\"] = 26] = \"CantSelectText\";\n PdfErrorCode2[PdfErrorCode2[\"CantSelectOption\"] = 27] = \"CantSelectOption\";\n PdfErrorCode2[PdfErrorCode2[\"CantCheckField\"] = 28] = \"CantCheckField\";\n PdfErrorCode2[PdfErrorCode2[\"CantSetAnnotString\"] = 29] = \"CantSetAnnotString\";\n PdfErrorCode2[PdfErrorCode2[\"CantDeletePage\"] = 30] = \"CantDeletePage\";\n return PdfErrorCode2;\n})(PdfErrorCode || {});\nclass PdfTaskHelper {\n /**\n * Create a task\n * @returns new task\n */\n static create() {\n return new Task();\n }\n /**\n * Create a task that has been resolved with value\n * @param result - resolved value\n * @returns resolved task\n */\n static resolve(result) {\n const task = new Task();\n task.resolve(result);\n return task;\n }\n /**\n * Create a task that has been rejected with error\n * @param reason - rejected error\n * @returns rejected task\n */\n static reject(reason) {\n const task = new Task();\n task.reject(reason);\n return task;\n }\n /**\n * Create a task that has been aborted with error\n * @param reason - aborted error\n * @returns aborted task\n */\n static abort(reason) {\n const task = new Task();\n task.reject(reason);\n return task;\n }\n}\nfunction pdfColorToWebColor(c) {\n const clamp = (n) => Math.max(0, Math.min(255, n));\n const toHex = (n) => clamp(n).toString(16).padStart(2, \"0\");\n return `#${toHex(c.red)}${toHex(c.green)}${toHex(c.blue)}`;\n}\nfunction webColorToPdfColor(color) {\n if (/^#?[0-9a-f]{3}$/i.test(color)) {\n color = color.replace(/^#?([0-9a-f])([0-9a-f])([0-9a-f])$/i, \"#$1$1$2$2$3$3\").toLowerCase();\n }\n const [, r, g, b] = /^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(color) ?? (() => {\n throw new Error(`Invalid hex colour: \"${color}\"`);\n })();\n return {\n red: parseInt(r, 16),\n green: parseInt(g, 16),\n blue: parseInt(b, 16)\n };\n}\nfunction getContrastStrokeColor(fillColor) {\n try {\n const { red, green, blue } = webColorToPdfColor(fillColor);\n const luminance = (0.299 * red + 0.587 * green + 0.114 * blue) / 255;\n return luminance < 0.45 ? \"#fff\" : \"#000\";\n } catch {\n return \"#000\";\n }\n}\nfunction pdfAlphaToWebOpacity(alpha) {\n const clamp = (n) => Math.max(0, Math.min(255, n));\n return clamp(alpha) / 255;\n}\nfunction webOpacityToPdfAlpha(opacity) {\n const clamp = (n, hi = 255) => Math.max(0, Math.min(hi, n));\n return clamp(Math.round(opacity * 255));\n}\nfunction extractPdfColor(c) {\n return { red: c.red, green: c.green, blue: c.blue };\n}\nfunction extractWebOpacity(c) {\n return pdfAlphaToWebOpacity(c.alpha);\n}\nfunction combinePdfColorWithAlpha(color, alpha) {\n return { ...color, alpha };\n}\nfunction combineWebColorWithOpacity(color, opacity) {\n return { color, opacity };\n}\nfunction pdfAlphaColorToWebAlphaColor(c) {\n const color = pdfColorToWebColor(extractPdfColor(c));\n const opacity = extractWebOpacity(c);\n return { color, opacity };\n}\nfunction webAlphaColorToPdfAlphaColor({ color, opacity }) {\n const pdfColor = webColorToPdfColor(color);\n const alpha = webOpacityToPdfAlpha(opacity);\n return combinePdfColorWithAlpha(pdfColor, alpha);\n}\nfunction pdfDateToDate(pdf) {\n if (!(pdf == null ? void 0 : pdf.startsWith(\"D:\")) || pdf.length < 16) return;\n const y = +pdf.slice(2, 6);\n const mo = +pdf.slice(6, 8) - 1;\n const d = +pdf.slice(8, 10);\n const H = +pdf.slice(10, 12);\n const M = +pdf.slice(12, 14);\n const S = +pdf.slice(14, 16);\n return new Date(Date.UTC(y, mo, d, H, M, S));\n}\nfunction dateToPdfDate(date = /* @__PURE__ */ new Date()) {\n const z = (n, len = 2) => n.toString().padStart(len, \"0\");\n const YYYY = date.getUTCFullYear();\n const MM = z(date.getUTCMonth() + 1);\n const DD = z(date.getUTCDate());\n const HH = z(date.getUTCHours());\n const mm = z(date.getUTCMinutes());\n const SS = z(date.getUTCSeconds());\n return `D:${YYYY}${MM}${DD}${HH}${mm}${SS}`;\n}\nconst MixedTextAlignment = Symbol(\"mixed\");\nconst TEXT_ALIGNMENT_INFOS = Object.freeze([\n { id: PdfTextAlignment.Left, label: \"Left\", css: \"left\" },\n { id: PdfTextAlignment.Center, label: \"Center\", css: \"center\" },\n { id: PdfTextAlignment.Right, label: \"Right\", css: \"right\" }\n]);\nconst enumToTextInfo = TEXT_ALIGNMENT_INFOS.reduce(\n (m, info) => {\n m[info.id] = info;\n return m;\n },\n {}\n);\nconst cssToTextEnum = TEXT_ALIGNMENT_INFOS.reduce(\n (m, info) => {\n m[info.css] = info.id;\n return m;\n },\n {}\n);\nfunction getTextAlignmentInfo(alignment) {\n return enumToTextInfo[alignment] ?? enumToTextInfo[PdfTextAlignment.Left];\n}\nfunction textAlignmentToCss(alignment) {\n return getTextAlignmentInfo(alignment).css;\n}\nfunction cssToTextAlignment(value) {\n return cssToTextEnum[value];\n}\nfunction textAlignmentLabel(alignment) {\n return getTextAlignmentInfo(alignment).label;\n}\nfunction reduceTextAlignments(values) {\n if (!values.length) return PdfTextAlignment.Left;\n const first = values[0];\n return values.every((a) => a === first) ? first : MixedTextAlignment;\n}\nconst textAlignmentSelectOptions = TEXT_ALIGNMENT_INFOS.map((info) => ({\n value: info.id,\n label: info.label\n}));\nvar PdfStandardFontFamily = /* @__PURE__ */ ((PdfStandardFontFamily2) => {\n PdfStandardFontFamily2[\"Courier\"] = \"Courier\";\n PdfStandardFontFamily2[\"Helvetica\"] = \"Helvetica\";\n PdfStandardFontFamily2[\"Times\"] = \"Times\";\n PdfStandardFontFamily2[\"Symbol\"] = \"Symbol\";\n PdfStandardFontFamily2[\"ZapfDingbats\"] = \"ZapfDingbats\";\n PdfStandardFontFamily2[\"Unknown\"] = \"Unknown\";\n return PdfStandardFontFamily2;\n})(PdfStandardFontFamily || {});\nconst DEFAULT_FALLBACK_FONT = PdfStandardFont.Helvetica;\nconst MixedStandardFont = Symbol(\"mixed\");\nconst HELVETICA_DESC = {\n id: PdfStandardFont.Helvetica,\n family: \"Helvetica\",\n bold: false,\n italic: false,\n label: \"Helvetica\",\n css: \"Helvetica, Arial, sans-serif\"\n};\nconst STANDARD_FONT_DESCRIPTORS = Object.freeze([\n {\n id: PdfStandardFont.Courier,\n family: \"Courier\",\n bold: false,\n italic: false,\n label: \"Courier\",\n css: \"Courier, monospace\"\n },\n {\n id: PdfStandardFont.Courier_Bold,\n family: \"Courier\",\n bold: true,\n italic: false,\n label: \"Courier Bold\",\n css: \"Courier, monospace\"\n },\n {\n id: PdfStandardFont.Courier_BoldOblique,\n family: \"Courier\",\n bold: true,\n italic: true,\n label: \"Courier Bold Oblique\",\n css: \"Courier, monospace\"\n },\n {\n id: PdfStandardFont.Courier_Oblique,\n family: \"Courier\",\n bold: false,\n italic: true,\n label: \"Courier Oblique\",\n css: \"Courier, monospace\"\n },\n HELVETICA_DESC,\n {\n id: PdfStandardFont.Helvetica_Bold,\n family: \"Helvetica\",\n bold: true,\n italic: false,\n label: \"Helvetica Bold\",\n css: \"Helvetica, Arial, sans-serif\"\n },\n {\n id: PdfStandardFont.Helvetica_BoldOblique,\n family: \"Helvetica\",\n bold: true,\n italic: true,\n label: \"Helvetica Bold Oblique\",\n css: \"Helvetica, Arial, sans-serif\"\n },\n {\n id: PdfStandardFont.Helvetica_Oblique,\n family: \"Helvetica\",\n bold: false,\n italic: true,\n label: \"Helvetica Oblique\",\n css: \"Helvetica, Arial, sans-serif\"\n },\n {\n id: PdfStandardFont.Times_Roman,\n family: \"Times\",\n bold: false,\n italic: false,\n label: \"Times Roman\",\n css: '\"Times New Roman\", Times, serif'\n },\n {\n id: PdfStandardFont.Times_Bold,\n family: \"Times\",\n bold: true,\n italic: false,\n label: \"Times Bold\",\n css: '\"Times New Roman\", Times, serif'\n },\n {\n id: PdfStandardFont.Times_BoldItalic,\n family: \"Times\",\n bold: true,\n italic: true,\n label: \"Times Bold Italic\",\n css: '\"Times New Roman\", Times, serif'\n },\n {\n id: PdfStandardFont.Times_Italic,\n family: \"Times\",\n bold: false,\n italic: true,\n label: \"Times Italic\",\n css: '\"Times New Roman\", Times, serif'\n },\n {\n id: PdfStandardFont.Symbol,\n family: \"Symbol\",\n bold: false,\n italic: false,\n label: \"Symbol\",\n css: \"Symbol, serif\"\n },\n {\n id: PdfStandardFont.ZapfDingbats,\n family: \"ZapfDingbats\",\n bold: false,\n italic: false,\n label: \"Zapf Dingbats\",\n css: \"ZapfDingbats, serif\"\n }\n]);\nconst idToDescriptor = STANDARD_FONT_DESCRIPTORS.reduce((m, d) => (m[d.id] = d, m), {});\nconst familyStyleToId = /* @__PURE__ */ new Map();\nfor (const d of STANDARD_FONT_DESCRIPTORS) {\n familyStyleToId.set(`${d.family}_${d.bold}_${d.italic}`, d.id);\n}\nfunction unknownDescriptor() {\n return HELVETICA_DESC;\n}\nfunction getStandardFontDescriptor(font) {\n return idToDescriptor[font] ?? unknownDescriptor();\n}\nfunction standardFontFamily(font) {\n return getStandardFontDescriptor(font).family;\n}\nfunction standardFontIsBold(font) {\n return getStandardFontDescriptor(font).bold;\n}\nfunction standardFontIsItalic(font) {\n return getStandardFontDescriptor(font).italic;\n}\nfunction makeStandardFont(family, { bold, italic }) {\n return familyStyleToId.get(`${family}_${bold}_${italic}`) ?? DEFAULT_FALLBACK_FONT;\n}\nfunction standardFontLabel(font) {\n return getStandardFontDescriptor(font).label;\n}\nfunction standardFontCss(font) {\n return getStandardFontDescriptor(font).css;\n}\nfunction standardFontCssProperties(font) {\n const desc = getStandardFontDescriptor(font);\n return {\n fontFamily: desc.css,\n fontWeight: desc.bold ? \"bold\" : \"normal\",\n fontStyle: desc.italic ? \"italic\" : \"normal\"\n };\n}\nconst standardFontFamilySelectOptions = Object.values(PdfStandardFontFamily).filter(\n (f) => f !== \"Unknown\"\n /* Unknown */\n).map((family) => ({ value: family, label: family }));\nfunction reduceStandardFonts(fonts) {\n if (!fonts.length) return PdfStandardFont.Unknown;\n const first = fonts[0];\n return fonts.every((f) => f === first) ? first : MixedStandardFont;\n}\nconst STANDARD_FONT_FAMILIES = [\n ...new Set(STANDARD_FONT_DESCRIPTORS.map((d) => d.family))\n];\nfunction standardFontFamilyLabel(fam) {\n switch (fam) {\n case \"Courier\":\n return \"Courier\";\n case \"Helvetica\":\n return \"Helvetica\";\n case \"Times\":\n return \"Times\";\n case \"Symbol\":\n return \"Symbol\";\n case \"ZapfDingbats\":\n return \"ZapfDingbats\";\n /* fallback */\n default:\n return \"Helvetica\";\n }\n}\nconst MixedBlendMode = Symbol(\"mixed\");\nconst BLEND_MODE_INFOS = Object.freeze([\n { id: PdfBlendMode.Normal, label: \"Normal\", css: \"normal\" },\n { id: PdfBlendMode.Multiply, label: \"Multiply\", css: \"multiply\" },\n { id: PdfBlendMode.Screen, label: \"Screen\", css: \"screen\" },\n { id: PdfBlendMode.Overlay, label: \"Overlay\", css: \"overlay\" },\n { id: PdfBlendMode.Darken, label: \"Darken\", css: \"darken\" },\n { id: PdfBlendMode.Lighten, label: \"Lighten\", css: \"lighten\" },\n { id: PdfBlendMode.ColorDodge, label: \"Color Dodge\", css: \"color-dodge\" },\n { id: PdfBlendMode.ColorBurn, label: \"Color Burn\", css: \"color-burn\" },\n { id: PdfBlendMode.HardLight, label: \"Hard Light\", css: \"hard-light\" },\n { id: PdfBlendMode.SoftLight, label: \"Soft Light\", css: \"soft-light\" },\n { id: PdfBlendMode.Difference, label: \"Difference\", css: \"difference\" },\n { id: PdfBlendMode.Exclusion, label: \"Exclusion\", css: \"exclusion\" },\n { id: PdfBlendMode.Hue, label: \"Hue\", css: \"hue\" },\n { id: PdfBlendMode.Saturation, label: \"Saturation\", css: \"saturation\" },\n { id: PdfBlendMode.Color, label: \"Color\", css: \"color\" },\n { id: PdfBlendMode.Luminosity, label: \"Luminosity\", css: \"luminosity\" }\n]);\nconst enumToInfo = BLEND_MODE_INFOS.reduce(\n (m, info) => {\n m[info.id] = info;\n return m;\n },\n {}\n);\nconst cssToEnum = BLEND_MODE_INFOS.reduce(\n (m, info) => {\n m[info.css] = info.id;\n return m;\n },\n {}\n);\nfunction getBlendModeInfo(mode) {\n return enumToInfo[mode] ?? enumToInfo[PdfBlendMode.Normal];\n}\nfunction blendModeToCss(mode) {\n return getBlendModeInfo(mode).css;\n}\nfunction cssToBlendMode(value) {\n return cssToEnum[value];\n}\nfunction blendModeLabel(mode) {\n return getBlendModeInfo(mode).label;\n}\nfunction reduceBlendModes(modes) {\n if (!modes.length) return PdfBlendMode.Normal;\n const first = modes[0];\n return modes.every((m) => m === first) ? first : MixedBlendMode;\n}\nconst blendModeSelectOptions = BLEND_MODE_INFOS.map((info) => ({\n value: info.id,\n label: info.label\n}));\nconst blendModeValues = BLEND_MODE_INFOS.map((info) => info.id);\nfunction uiBlendModeDisplay(value) {\n return value === MixedBlendMode ? \"(mixed)\" : blendModeLabel(value);\n}\nfunction serializeLogger(logger) {\n if (logger instanceof NoopLogger) {\n return { type: \"noop\" };\n }\n if (logger instanceof ConsoleLogger) {\n return { type: \"console\" };\n }\n if (logger instanceof PerfLogger) {\n return { type: \"perf\" };\n }\n if (logger instanceof LevelLogger) {\n const levelLogger = logger;\n return {\n type: \"level\",\n config: {\n level: levelLogger.level,\n logger: serializeLogger(levelLogger.logger)\n }\n };\n }\n if (logger instanceof AllLogger) {\n const allLogger = logger;\n return {\n type: \"all\",\n config: {\n loggers: allLogger.loggers.map(serializeLogger)\n }\n };\n }\n return { type: \"noop\" };\n}\nfunction deserializeLogger(serialized) {\n var _a, _b, _c;\n switch (serialized.type) {\n case \"noop\":\n return new NoopLogger();\n case \"console\":\n return new ConsoleLogger();\n case \"perf\":\n return new PerfLogger();\n case \"level\":\n if (!((_a = serialized.config) == null ? void 0 : _a.logger) || ((_b = serialized.config) == null ? void 0 : _b.level) === void 0) {\n throw new Error(\"LevelLogger requires logger and level in config\");\n }\n return new LevelLogger(deserializeLogger(serialized.config.logger), serialized.config.level);\n case \"all\":\n if (!((_c = serialized.config) == null ? void 0 : _c.loggers)) {\n throw new Error(\"AllLogger requires loggers array in config\");\n }\n return new AllLogger(serialized.config.loggers.map(deserializeLogger));\n default:\n return new NoopLogger();\n }\n}\nconst V4_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\nfunction isUuidV4(str) {\n return V4_REGEX.test(str);\n}\nfunction getRandomBytes(len) {\n var _a;\n if (typeof ((_a = globalThis.crypto) == null ? void 0 : _a.getRandomValues) === \"function\") {\n return globalThis.crypto.getRandomValues(new Uint8Array(len));\n }\n if (typeof require === \"function\") {\n try {\n const { randomBytes } = require(\"crypto\");\n return randomBytes(len);\n } catch {\n }\n }\n const bytes = new Uint8Array(len);\n for (let i = 0; i < len; i++) bytes[i] = Math.floor(Math.random() * 256);\n return bytes;\n}\nfunction uuidV4() {\n var _a;\n if (typeof ((_a = globalThis.crypto) == null ? void 0 : _a.randomUUID) === \"function\") {\n return globalThis.crypto.randomUUID();\n }\n const bytes = getRandomBytes(16);\n bytes[6] = bytes[6] & 15 | 64;\n bytes[8] = bytes[8] & 63 | 128;\n const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\nclass CompoundTask extends Task {\n constructor(config = {}) {\n super();\n this.children = /* @__PURE__ */ new Map();\n this.childResults = [];\n this.completedCount = 0;\n this.expectedCount = 0;\n this.isFinalized = false;\n this.config = {\n aggregate: config.aggregate ?? ((results) => results),\n onChildComplete: config.onChildComplete ?? (() => {\n }),\n failFast: config.failFast ?? true\n };\n }\n /**\n * Add a child task - automatically wires up completion handling\n */\n addChild(child, index) {\n if (this.state.stage !== TaskStage.Pending) {\n if (this.state.stage === TaskStage.Aborted) {\n child.abort(this.state.reason);\n }\n return this;\n }\n const childIndex = index ?? this.expectedCount;\n this.expectedCount = Math.max(this.expectedCount, childIndex + 1);\n this.children.set(child, childIndex);\n child.wait(\n (result) => this.handleChildSuccess(child, result, childIndex),\n (error) => this.handleChildError(child, error, childIndex)\n );\n return this;\n }\n /**\n * Finalize - signals that no more children will be added\n * If no children were added, resolves immediately\n */\n finalize() {\n if (this.isFinalized) return this;\n this.isFinalized = true;\n if (this.expectedCount === 0) {\n this.resolve(this.config.aggregate([]));\n }\n return this;\n }\n handleChildSuccess(child, result, index) {\n if (this.state.stage !== TaskStage.Pending) return;\n this.childResults[index] = result;\n this.completedCount++;\n this.children.delete(child);\n const progressValue = this.config.onChildComplete(\n this.completedCount,\n this.expectedCount,\n result,\n index\n );\n if (progressValue !== void 0) {\n this.progress(progressValue);\n }\n if (this.completedCount === this.expectedCount) {\n const finalResult = this.config.aggregate(this.childResults);\n this.resolve(finalResult);\n }\n }\n handleChildError(child, error, index) {\n if (this.state.stage !== TaskStage.Pending) return;\n this.children.delete(child);\n if (this.config.failFast) {\n for (const [otherChild] of this.children) {\n otherChild.abort(\"Sibling task failed\");\n }\n this.children.clear();\n this.fail(error);\n } else {\n this.childResults[index] = void 0;\n this.completedCount++;\n if (this.completedCount === this.expectedCount) {\n const finalResult = this.config.aggregate(this.childResults);\n this.resolve(finalResult);\n }\n }\n }\n /**\n * Override abort to propagate to all children\n */\n abort(reason) {\n for (const [child] of this.children) {\n child.abort(reason);\n }\n this.children.clear();\n super.abort(reason);\n }\n /**\n * Override reject to abort all children\n */\n reject(reason) {\n for (const [child] of this.children) {\n child.abort(reason);\n }\n this.children.clear();\n super.reject(reason);\n }\n /**\n * Get count of pending children\n */\n getPendingCount() {\n return this.children.size;\n }\n /**\n * Get count of completed children\n */\n getCompletedCount() {\n return this.completedCount;\n }\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n /**\n * Gather results from an array of tasks (progress-friendly).\n * (Formerly: all)\n */\n static gather(tasks) {\n const compound = new CompoundTask({\n aggregate: (results) => results,\n onChildComplete: (completed, total) => ({ completed, total })\n });\n tasks.forEach((task, index) => compound.addChild(task, index));\n compound.finalize();\n return compound;\n }\n /**\n * Gather into a Record indexed by number.\n * (Formerly: allIndexed)\n */\n static gatherIndexed(tasks) {\n const compound = new CompoundTask({\n aggregate: (results) => {\n const record = {};\n results.forEach((result, index) => {\n record[index] = result;\n });\n return record;\n },\n onChildComplete: (_completed, _total, result, index) => ({ page: index, result })\n });\n tasks.forEach((task, index) => compound.addChild(task, index));\n compound.finalize();\n return compound;\n }\n /**\n * Gather with custom aggregation config.\n * (Formerly: from)\n */\n static gatherFrom(tasks, config) {\n const compound = new CompoundTask(config);\n tasks.forEach((task, index) => compound.addChild(task, index));\n compound.finalize();\n return compound;\n }\n /**\n * Resolve with the first successful child; abort the rest.\n * (Formerly: race)\n */\n static first(tasks) {\n let resolved = false;\n const compound = new CompoundTask({\n aggregate: (results) => results[0],\n failFast: false\n });\n compound[\"handleChildSuccess\"] = (child, result) => {\n if (!resolved) {\n resolved = true;\n for (const [otherChild] of compound[\"children\"]) {\n if (otherChild !== child) otherChild.abort(\"Race won by sibling\");\n }\n compound.resolve(result);\n }\n };\n tasks.forEach((task, index) => compound.addChild(task, index));\n compound.finalize();\n return compound;\n }\n}\nclass TaskSequence {\n constructor(parentTask) {\n this.parentTask = parentTask;\n this.activeChild = null;\n this.disposed = false;\n const origAbort = parentTask.abort.bind(parentTask);\n parentTask.abort = (reason) => {\n var _a;\n this.disposed = true;\n (_a = this.activeChild) == null ? void 0 : _a.abort(reason);\n origAbort(reason);\n };\n }\n /**\n * Execute a child Task and return its result as a Promise.\n *\n * If the parent task has been aborted, throws `TaskAbortedError` immediately.\n * If the parent task is aborted while the child is running, the child is aborted too.\n */\n run(factory) {\n return new Promise((resolve, reject) => {\n if (this.disposed || this.parentTask.state.stage !== TaskStage.Pending) {\n reject(new TaskAbortedError(\"Sequence aborted\"));\n return;\n }\n const child = factory();\n this.activeChild = child;\n child.wait(\n (result) => {\n this.activeChild = null;\n resolve(result);\n },\n (error) => {\n this.activeChild = null;\n if (error.type === \"abort\") {\n reject(new TaskAbortedError(error.reason));\n } else {\n reject(new TaskRejectedError(error.reason));\n }\n }\n );\n });\n }\n /**\n * Execute a child Task and return its result as a Promise,\n * forwarding the child's progress events to the parent task\n * through the provided mapper function.\n *\n * If the parent task has been aborted, throws `TaskAbortedError` immediately.\n * If the parent task is aborted while the child is running, the child is aborted too.\n */\n runWithProgress(factory, mapProgress) {\n return new Promise((resolve, reject) => {\n if (this.disposed || this.parentTask.state.stage !== TaskStage.Pending) {\n reject(new TaskAbortedError(\"Sequence aborted\"));\n return;\n }\n const child = factory();\n this.activeChild = child;\n child.onProgress((p) => {\n this.parentTask.progress(mapProgress(p));\n });\n child.wait(\n (result) => {\n this.activeChild = null;\n resolve(result);\n },\n (error) => {\n this.activeChild = null;\n if (error.type === \"abort\") {\n reject(new TaskAbortedError(error.reason));\n } else {\n reject(new TaskRejectedError(error.reason));\n }\n }\n );\n });\n }\n /**\n * Execute an async function body that uses `run()` / `runWithProgress()`,\n * automatically handling abort and error routing to the parent task.\n *\n * - If the body throws `TaskAbortedError`, it is silently ignored\n * (the parent task was already aborted via the abort override).\n * - If the body throws `TaskRejectedError` (from a child task rejection\n * via `run()` / `runWithProgress()`), its `.reason` is forwarded directly\n * to the parent task, bypassing `mapError`.\n * - Any other thrown error is mapped through `mapError` and used to\n * reject the parent task. This handles unexpected runtime exceptions\n * in the async body itself.\n * - On success, the body is responsible for calling `parentTask.resolve()`.\n */\n execute(fn, mapError) {\n fn().catch((err) => {\n if (err instanceof TaskAbortedError) return;\n if (err instanceof TaskRejectedError) {\n this.parentTask.reject(err.reason);\n return;\n }\n this.parentTask.reject(mapError(err));\n });\n }\n}\nfunction getImageMetadata(buffer) {\n if (buffer.byteLength < 4) return null;\n const bytes = new Uint8Array(buffer);\n if (bytes[0] === 137 && bytes[1] === 80 && bytes[2] === 78 && bytes[3] === 71) {\n return parsePng(buffer);\n }\n if (bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) {\n return parseJpeg(buffer);\n }\n if (bytes[0] === 37 && bytes[1] === 80 && bytes[2] === 68 && bytes[3] === 70) {\n return { mimeType: \"application/pdf\" };\n }\n return null;\n}\nfunction parsePng(buffer) {\n if (buffer.byteLength < 24) return null;\n const view = new DataView(buffer);\n const width = view.getUint32(16);\n const height = view.getUint32(20);\n if (width === 0 || height === 0) return null;\n return { mimeType: \"image/png\", width, height };\n}\nfunction parseJpeg(buffer) {\n const bytes = new Uint8Array(buffer);\n let offset = 2;\n while (offset + 4 < bytes.byteLength) {\n if (bytes[offset] !== 255) return null;\n const marker = bytes[offset + 1];\n if (marker >= 192 && marker <= 195) {\n if (offset + 9 > bytes.byteLength) return null;\n const view = new DataView(buffer, offset + 5);\n const height = view.getUint16(0);\n const width = view.getUint16(2);\n if (width === 0 || height === 0) return null;\n return { mimeType: \"image/jpeg\", width, height };\n }\n if (marker === 216 || marker === 217) {\n offset += 2;\n } else if (marker === 255) {\n offset += 1;\n } else {\n const segLen = bytes[offset + 2] << 8 | bytes[offset + 3];\n offset += 2 + segLen;\n }\n }\n return null;\n}\nfunction ignore() {\n}\nexport {\n AP_MODE_DOWN,\n AP_MODE_NORMAL,\n AP_MODE_ROLLOVER,\n AllLogger,\n AppearanceMode,\n CompoundTask,\n ConsoleLogger,\n FontCharset,\n LevelLogger,\n LogLevel,\n MatchFlag,\n MixedBlendMode,\n MixedStandardFont,\n MixedTextAlignment,\n NoopLogger,\n PDF_ANNOT_AACTION_EVENT,\n PDF_FORM_FIELD_FLAG,\n PDF_FORM_FIELD_TYPE,\n PdfActionType,\n PdfAnnotationBorderStyle,\n PdfAnnotationColorType,\n PdfAnnotationFlagName,\n PdfAnnotationFlags,\n PdfAnnotationIcon,\n PdfAnnotationLineEnding,\n PdfAnnotationName,\n PdfAnnotationObjectStatus,\n PdfAnnotationReplyType,\n PdfAnnotationState,\n PdfAnnotationStateModel,\n PdfAnnotationSubtype,\n PdfAnnotationSubtypeName,\n PdfBlendMode,\n PdfBomOrZwnbsp,\n PdfEngineFeature,\n PdfEngineOperation,\n PdfErrorCode,\n PdfJavaScriptActionTrigger,\n PdfJavaScriptWidgetEventType,\n PdfNonCharacterFFFE,\n PdfNonCharacterFFFF,\n PdfPageFlattenFlag,\n PdfPageFlattenResult,\n PdfPageObjectType,\n PdfPermissionFlag,\n PdfSegmentObjectType,\n PdfSoftHyphenMarker,\n PdfStampFit,\n PdfStandardFont,\n PdfStandardFontFamily,\n PdfTaskHelper,\n PdfTextAlignment,\n PdfTrappedStatus,\n PdfUnwantedTextMarkers,\n PdfUnwantedTextRegex,\n PdfVerticalAlignment,\n PdfWordJoiner,\n PdfZeroWidthSpace,\n PdfZoomMode,\n PerfLogger,\n PermissionDeniedError,\n Rotation,\n STANDARD_FONT_FAMILIES,\n Task,\n TaskAbortedError,\n TaskRejectedError,\n TaskSequence,\n TaskStage,\n blendModeLabel,\n blendModeSelectOptions,\n blendModeToCss,\n blendModeValues,\n boundingRect,\n boundingRectOrEmpty,\n buildPermissions,\n buildUserToDeviceMatrix,\n calculateAngle,\n calculateDegree,\n calculateRotatedRectAABB,\n calculateRotatedRectAABBAroundPoint,\n combinePdfColorWithAlpha,\n combineWebColorWithOpacity,\n compareSearchTarget,\n cssToBlendMode,\n cssToTextAlignment,\n dateToPdfDate,\n deserializeLogger,\n expandRect,\n extractPdfColor,\n extractWebOpacity,\n fitSizeWithin,\n flagsToNames,\n getBlendModeInfo,\n getContrastStrokeColor,\n getImageMetadata,\n getRectCenter,\n getStandardFontDescriptor,\n getTextAlignmentInfo,\n ignore,\n inferRotationCenterFromRects,\n isUuidV4,\n isWidgetChecked,\n makeStandardFont,\n namesToFlags,\n normalizeAngle,\n pdfAlphaColorToWebAlphaColor,\n pdfAlphaToWebOpacity,\n pdfColorToWebColor,\n pdfDateToDate,\n quadToRect,\n rectEquals,\n rectFromPoints,\n rectToQuad,\n reduceBlendModes,\n reduceStandardFonts,\n reduceTextAlignments,\n restoreOffset,\n restorePosition,\n restoreRect,\n rotateAndTranslatePoint,\n rotatePointAround,\n rotatePosition,\n rotateRect,\n rotateVertices,\n scalePosition,\n scaleRect,\n serializeLogger,\n standardFontCss,\n standardFontCssProperties,\n standardFontFamily,\n standardFontFamilyLabel,\n standardFontFamilySelectOptions,\n standardFontIsBold,\n standardFontIsItalic,\n standardFontLabel,\n stripPdfUnwantedMarkers,\n swap,\n textAlignmentLabel,\n textAlignmentSelectOptions,\n textAlignmentToCss,\n toIntPos,\n toIntRect,\n toIntSize,\n transformPosition,\n transformRect,\n transformSize,\n uiBlendModeDisplay,\n unionFlags,\n uuidV4,\n webAlphaColorToPdfAlphaColor,\n webColorToPdfColor,\n webOpacityToPdfAlpha\n};\n//# sourceMappingURL=index.js.map\n","import { Rotation, PdfPermissionFlag, NoopLogger, PermissionDeniedError } from \"@embedpdf/models\";\nclass DependencyResolver {\n constructor() {\n this.dependencyGraph = /* @__PURE__ */ new Map();\n }\n addNode(id, dependencies = []) {\n this.dependencyGraph.set(id, new Set(dependencies));\n }\n hasCircularDependencies() {\n const visited = /* @__PURE__ */ new Set();\n const recursionStack = /* @__PURE__ */ new Set();\n const dfs = (id) => {\n visited.add(id);\n recursionStack.add(id);\n const dependencies = this.dependencyGraph.get(id) || /* @__PURE__ */ new Set();\n for (const dep of dependencies) {\n if (!visited.has(dep)) {\n if (dfs(dep)) return true;\n } else if (recursionStack.has(dep)) {\n return true;\n }\n }\n recursionStack.delete(id);\n return false;\n };\n for (const id of this.dependencyGraph.keys()) {\n if (!visited.has(id)) {\n if (dfs(id)) return true;\n }\n }\n return false;\n }\n resolveLoadOrder() {\n if (this.hasCircularDependencies()) {\n throw new Error(\"Circular dependencies detected\");\n }\n const result = [];\n const visited = /* @__PURE__ */ new Set();\n const temp = /* @__PURE__ */ new Set();\n const visit = (id) => {\n if (temp.has(id)) throw new Error(\"Circular dependency\");\n if (visited.has(id)) return;\n temp.add(id);\n const dependencies = this.dependencyGraph.get(id) || /* @__PURE__ */ new Set();\n for (const dep of dependencies) {\n visit(dep);\n }\n temp.delete(id);\n visited.add(id);\n result.push(id);\n };\n for (const id of this.dependencyGraph.keys()) {\n if (!visited.has(id)) {\n visit(id);\n }\n }\n return result;\n }\n}\nclass PluginRegistrationError extends Error {\n constructor(message) {\n super(message);\n this.name = \"PluginRegistrationError\";\n }\n}\nclass PluginNotFoundError extends Error {\n constructor(message) {\n super(message);\n this.name = \"PluginNotFoundError\";\n }\n}\nclass CircularDependencyError extends Error {\n constructor(message) {\n super(message);\n this.name = \"CircularDependencyError\";\n }\n}\nclass CapabilityNotFoundError extends Error {\n constructor(message) {\n super(message);\n this.name = \"CapabilityNotFoundError\";\n }\n}\nclass CapabilityConflictError extends Error {\n constructor(message) {\n super(message);\n this.name = \"CapabilityConflictError\";\n }\n}\nclass PluginInitializationError extends Error {\n constructor(message) {\n super(message);\n this.name = \"PluginInitializationError\";\n }\n}\nclass PluginConfigurationError extends Error {\n constructor(message) {\n super(message);\n this.name = \"PluginConfigurationError\";\n }\n}\nclass PluginStore {\n /**\n * Initializes the PluginStore with the main store and plugin ID.\n * @param store The main store instance.\n * @param pluginId The unique identifier for the plugin.\n */\n constructor(store, pluginId) {\n this.store = store;\n this.pluginId = pluginId;\n }\n /**\n * Gets the current state of the plugin.\n * @returns The plugin's state.\n */\n getState() {\n return this.store.getState().plugins[this.pluginId];\n }\n /**\n * Dispatches an action for the plugin and returns the *new* global state.\n * If you only need the plugin’s updated state, call `getState()` afterward.\n * @param action The action to dispatch.\n * @returns The updated global store state (after plugin reducer).\n */\n dispatch(action) {\n return this.store.dispatchToPlugin(this.pluginId, action);\n }\n /**\n * Subscribes to state changes only for this specific plugin.\n * You now receive (action, newPluginState, oldPluginState) in the callback.\n *\n * @param listener The callback to invoke when plugin state changes.\n * @returns A function to unsubscribe the listener.\n */\n subscribeToState(listener) {\n return this.store.subscribeToPlugin(this.pluginId, (action, newPluginState, oldPluginState) => {\n listener(\n action,\n newPluginState,\n oldPluginState\n );\n });\n }\n /**\n * Subscribes to a specific action type for the plugin.\n * This still uses the main store's `onAction`, so you get the *global*\n * old/new store states there. If you specifically want old/new plugin state,\n * use `subscribeToState` instead.\n *\n * @param type The action type to listen for.\n * @param handler The callback to invoke when the action occurs.\n * @returns A function to unsubscribe the handler.\n */\n onAction(type, handler) {\n return this.store.onAction(type, (action, state, oldState) => {\n handler(\n action,\n state.plugins[this.pluginId],\n oldState.plugins[this.pluginId]\n );\n });\n }\n}\nconst START_LOADING_DOCUMENT = \"START_LOADING_DOCUMENT\";\nconst UPDATE_DOCUMENT_LOADING_PROGRESS = \"UPDATE_DOCUMENT_LOADING_PROGRESS\";\nconst SET_DOCUMENT_LOADED = \"SET_DOCUMENT_LOADED\";\nconst SET_DOCUMENT_ERROR = \"SET_DOCUMENT_ERROR\";\nconst RETRY_LOADING_DOCUMENT = \"RETRY_LOADING_DOCUMENT\";\nconst CLOSE_DOCUMENT = \"CLOSE_DOCUMENT\";\nconst SET_ACTIVE_DOCUMENT = \"SET_ACTIVE_DOCUMENT\";\nconst REORDER_DOCUMENTS = \"REORDER_DOCUMENTS\";\nconst MOVE_DOCUMENT = \"MOVE_DOCUMENT\";\nconst UPDATE_DOCUMENT_SECURITY = \"UPDATE_DOCUMENT_SECURITY\";\nconst REFRESH_DOCUMENT = \"REFRESH_DOCUMENT\";\nconst REFRESH_PAGES = \"REFRESH_PAGES\";\nconst SET_PAGES = \"SET_PAGES\";\nconst SET_SCALE = \"SET_SCALE\";\nconst SET_ROTATION = \"SET_ROTATION\";\nconst SET_DEFAULT_SCALE = \"SET_DEFAULT_SCALE\";\nconst SET_DEFAULT_ROTATION = \"SET_DEFAULT_ROTATION\";\nconst CORE_ACTION_TYPES = [\n START_LOADING_DOCUMENT,\n UPDATE_DOCUMENT_LOADING_PROGRESS,\n SET_DOCUMENT_LOADED,\n CLOSE_DOCUMENT,\n SET_ACTIVE_DOCUMENT,\n SET_DOCUMENT_ERROR,\n RETRY_LOADING_DOCUMENT,\n REFRESH_DOCUMENT,\n REFRESH_PAGES,\n SET_PAGES,\n SET_SCALE,\n SET_ROTATION,\n SET_DEFAULT_SCALE,\n SET_DEFAULT_ROTATION,\n REORDER_DOCUMENTS,\n MOVE_DOCUMENT,\n UPDATE_DOCUMENT_SECURITY\n];\nconst startLoadingDocument = (documentId, name, scale, rotation, passwordProvided, autoActivate, permissions) => ({\n type: START_LOADING_DOCUMENT,\n payload: { documentId, name, scale, rotation, passwordProvided, autoActivate, permissions }\n});\nconst updateDocumentLoadingProgress = (documentId, progress) => ({\n type: UPDATE_DOCUMENT_LOADING_PROGRESS,\n payload: { documentId, progress }\n});\nconst setDocumentLoaded = (documentId, document) => ({\n type: SET_DOCUMENT_LOADED,\n payload: { documentId, document }\n});\nconst setDocumentError = (documentId, error, errorCode, errorDetails) => ({\n type: SET_DOCUMENT_ERROR,\n payload: { documentId, error, errorCode, errorDetails }\n});\nconst retryLoadingDocument = (documentId, passwordProvided) => ({\n type: RETRY_LOADING_DOCUMENT,\n payload: { documentId, passwordProvided }\n});\nconst closeDocument = (documentId, nextActiveDocumentId) => ({\n type: CLOSE_DOCUMENT,\n payload: { documentId, nextActiveDocumentId }\n});\nconst setActiveDocument = (documentId) => ({\n type: SET_ACTIVE_DOCUMENT,\n payload: documentId\n});\nconst refreshDocument = (documentId, document) => ({\n type: REFRESH_DOCUMENT,\n payload: { documentId, document }\n});\nconst refreshPages = (documentId, pageIndexes) => ({\n type: REFRESH_PAGES,\n payload: { documentId, pageIndexes }\n});\nconst setPages = (documentId, pages) => ({\n type: SET_PAGES,\n payload: { documentId, pages }\n});\nconst setScale = (scale, documentId) => ({\n type: SET_SCALE,\n payload: { scale, documentId }\n});\nconst setRotation = (rotation, documentId) => ({\n type: SET_ROTATION,\n payload: { rotation, documentId }\n});\nconst setDefaultScale = (scale) => ({\n type: SET_DEFAULT_SCALE,\n payload: scale\n});\nconst setDefaultRotation = (rotation) => ({\n type: SET_DEFAULT_ROTATION,\n payload: rotation\n});\nconst reorderDocuments = (order) => ({\n type: REORDER_DOCUMENTS,\n payload: order\n});\nconst moveDocument = (documentId, toIndex) => ({\n type: MOVE_DOCUMENT,\n payload: { documentId, toIndex }\n});\nconst updateDocumentSecurity = (documentId, permissions, isOwnerUnlocked) => ({\n type: UPDATE_DOCUMENT_SECURITY,\n payload: { documentId, permissions, isOwnerUnlocked }\n});\nclass Store {\n /**\n * Initializes the store with the provided core state.\n * @param reducer The core reducer function\n * @param initialCoreState The initial core state\n */\n constructor(reducer, initialCoreState2) {\n this.initialCoreState = initialCoreState2;\n this.pluginReducers = {};\n this.listeners = [];\n this.pluginListeners = {};\n this.isDispatching = false;\n this.state = { core: initialCoreState2, plugins: {} };\n this.coreReducer = reducer;\n }\n /**\n * Adds a reducer for a plugin-specific state.\n * @param pluginId The unique identifier for the plugin.\n * @param reducer The reducer function for the plugin state.\n * @param initialState The initial state for the plugin.\n */\n addPluginReducer(pluginId, reducer, initialState) {\n this.state.plugins[pluginId] = initialState;\n this.pluginReducers[pluginId] = reducer;\n }\n /**\n * Dispatches an action *only* to the core reducer.\n * Notifies the global store listeners with (action, newState, oldState).\n *\n * @param action The action to dispatch, typed as CoreAction\n * @returns The updated *global* store state\n */\n dispatchToCore(action) {\n if (!this.coreReducer) {\n return this.getState();\n }\n if (this.isDispatching) {\n throw new Error(\n \"Reducers may not dispatch actions. To trigger cascading actions, dispatch from a listener callback instead.\"\n );\n }\n const oldState = this.getState();\n try {\n this.isDispatching = true;\n this.state.core = this.coreReducer(this.state.core, action);\n } finally {\n this.isDispatching = false;\n }\n this.listeners.forEach((listener) => {\n const currentState = this.getState();\n listener(action, currentState, oldState);\n });\n return this.getState();\n }\n /**\n * Dispatches an action *only* to a specific plugin.\n * Optionally notifies global store listeners if `notifyGlobal` is true.\n * Always notifies plugin-specific listeners with (action, newPluginState, oldPluginState).\n *\n * @param pluginId The plugin identifier\n * @param action The plugin action to dispatch\n * @param notifyGlobal Whether to also notify global store listeners\n * @returns The updated plugin state\n */\n dispatchToPlugin(pluginId, action, notifyGlobal = true) {\n if (this.isDispatching) {\n throw new Error(\n \"Reducers may not dispatch actions. To trigger cascading actions, dispatch from a listener callback instead.\"\n );\n }\n const oldGlobalState = this.getState();\n const reducer = this.pluginReducers[pluginId];\n if (!reducer) {\n return oldGlobalState.plugins[pluginId];\n }\n const oldPluginState = oldGlobalState.plugins[pluginId];\n try {\n this.isDispatching = true;\n const newPluginState = reducer(oldPluginState, action);\n this.state.plugins[pluginId] = newPluginState;\n } finally {\n this.isDispatching = false;\n }\n if (notifyGlobal) {\n this.listeners.forEach((listener) => {\n const currentGlobalState = this.getState();\n listener(action, currentGlobalState, oldGlobalState);\n });\n }\n if (this.pluginListeners[pluginId]) {\n this.pluginListeners[pluginId].forEach((listener) => {\n const currentPluginState = this.getState().plugins[pluginId];\n listener(action, currentPluginState, oldPluginState);\n });\n }\n return this.getState().plugins[pluginId];\n }\n /**\n * Dispatches an action to update the state using:\n * - the core reducer (if it's a CoreAction)\n * - *all* plugin reducers (regardless of action type), with no global notify for each plugin\n *\n * Returns the new *global* store state after all reducers have processed the action.\n *\n * @param action The action to dispatch (can be CoreAction or any Action).\n */\n dispatch(action) {\n if (this.isDispatching) {\n throw new Error(\n \"Reducers may not dispatch actions. To trigger cascading actions, dispatch from a listener callback instead.\"\n );\n }\n const oldState = this.getState();\n try {\n this.isDispatching = true;\n if (this.isCoreAction(action)) {\n this.state.core = this.coreReducer(this.state.core, action);\n }\n for (const pluginId in this.pluginReducers) {\n const reducer = this.pluginReducers[pluginId];\n const oldPluginState = oldState.plugins[pluginId];\n if (reducer) {\n this.state.plugins[pluginId] = reducer(oldPluginState, action);\n }\n }\n } finally {\n this.isDispatching = false;\n }\n this.listeners.forEach((listener) => {\n const currentState = this.getState();\n listener(action, currentState, oldState);\n });\n return this.getState();\n }\n /**\n * Returns a shallow copy of the current state.\n * @returns The current store state.\n */\n getState() {\n if (this.isDispatching) {\n throw new Error(\n \"You may not call store.getState() while the reducer is executing. The reducer has already received the state as an argument. Pass it down from the top reducer instead of reading it from the store.\"\n );\n }\n return {\n core: { ...this.state.core },\n plugins: { ...this.state.plugins }\n };\n }\n /**\n * Subscribes a listener to *global* state changes.\n * The callback signature is now (action, newState, oldState).\n *\n * @param listener The callback to invoke on state changes\n * @returns A function to unsubscribe the listener\n */\n subscribe(listener) {\n if (this.isDispatching) {\n throw new Error(\n \"You may not call store.subscribe() while the reducer is executing. If you would like to be notified after the store has been updated, subscribe from a component and invoke store.getState() in the callback to access the latest state.\"\n );\n }\n this.listeners.push(listener);\n return () => {\n if (this.isDispatching) {\n throw new Error(\n \"You may not unsubscribe from a store listener while the reducer is executing.\"\n );\n }\n this.listeners = this.listeners.filter((l) => l !== listener);\n };\n }\n /**\n * Subscribes a listener to *plugin-specific* state changes.\n * The callback signature is now (action, newPluginState, oldPluginState).\n *\n * @param pluginId The unique identifier for the plugin.\n * @param listener The callback to invoke on plugin state changes.\n * @returns A function to unsubscribe the listener.\n */\n subscribeToPlugin(pluginId, listener) {\n if (!(pluginId in this.state.plugins)) {\n throw new Error(\n `Plugin state not found for plugin \"${pluginId}\". Did you forget to call addPluginReducer?`\n );\n }\n if (this.isDispatching) {\n throw new Error(\"You may not call store.subscribeToPlugin() while the reducer is executing.\");\n }\n if (!this.pluginListeners[pluginId]) {\n this.pluginListeners[pluginId] = [];\n }\n this.pluginListeners[pluginId].push(listener);\n return () => {\n if (this.isDispatching) {\n throw new Error(\n \"You may not unsubscribe from a store listener while the reducer is executing.\"\n );\n }\n this.pluginListeners[pluginId] = this.pluginListeners[pluginId].filter((l) => l !== listener);\n if (this.pluginListeners[pluginId].length === 0) {\n delete this.pluginListeners[pluginId];\n }\n };\n }\n /**\n * Subscribes to a specific action type (only from the core's action union).\n * The callback signature is (action, newState, oldState).\n *\n * @param type The action type to listen for.\n * @param handler The callback to invoke when the action occurs.\n * @returns A function to unsubscribe the handler.\n */\n onAction(type, handler) {\n return this.subscribe((action, newState, oldState) => {\n if (action.type === type) {\n handler(action, newState, oldState);\n }\n });\n }\n /**\n * Gets a PluginStore handle for a specific plugin.\n * @param pluginId The unique identifier for the plugin.\n * @returns A PluginStore instance for the plugin.\n */\n getPluginStore(pluginId) {\n if (!(pluginId in this.state.plugins)) {\n throw new Error(\n `Plugin state not found for plugin \"${pluginId}\". Did you forget to call addPluginReducer?`\n );\n }\n return new PluginStore(this, pluginId);\n }\n /**\n * Helper method to check if an action is a CoreAction.\n * Adjust if you have a more refined way to differentiate CoreAction vs. any other Action.\n */\n isCoreAction(action) {\n return CORE_ACTION_TYPES.includes(action.type);\n }\n /**\n * Destroy the store: drop every listener and plugin reducer\n */\n destroy() {\n var _a, _b;\n this.listeners.length = 0;\n for (const id in this.pluginListeners) {\n (_b = (_a = this.pluginListeners[id]) == null ? void 0 : _a.splice) == null ? void 0 : _b.call(_a, 0);\n }\n this.pluginListeners = {};\n this.pluginReducers = {};\n this.state.plugins = {};\n this.state.core = { ...this.initialCoreState };\n }\n}\nconst initialCoreState = (config) => ({\n documents: {},\n documentOrder: [],\n activeDocumentId: null,\n defaultScale: (config == null ? void 0 : config.defaultScale) ?? 1,\n defaultRotation: (config == null ? void 0 : config.defaultRotation) ?? Rotation.Degree0,\n globalPermissions: config == null ? void 0 : config.permissions\n});\nconst PERMISSION_NAME_TO_FLAG = {\n print: PdfPermissionFlag.Print,\n modifyContents: PdfPermissionFlag.ModifyContents,\n copyContents: PdfPermissionFlag.CopyContents,\n modifyAnnotations: PdfPermissionFlag.ModifyAnnotations,\n fillForms: PdfPermissionFlag.FillForms,\n extractForAccessibility: PdfPermissionFlag.ExtractForAccessibility,\n assembleDocument: PdfPermissionFlag.AssembleDocument,\n printHighQuality: PdfPermissionFlag.PrintHighQuality\n};\nconst ALL_PERMISSION_FLAGS = [\n PdfPermissionFlag.Print,\n PdfPermissionFlag.ModifyContents,\n PdfPermissionFlag.CopyContents,\n PdfPermissionFlag.ModifyAnnotations,\n PdfPermissionFlag.FillForms,\n PdfPermissionFlag.ExtractForAccessibility,\n PdfPermissionFlag.AssembleDocument,\n PdfPermissionFlag.PrintHighQuality\n];\nconst ALL_PERMISSION_NAMES = [\n \"print\",\n \"modifyContents\",\n \"copyContents\",\n \"modifyAnnotations\",\n \"fillForms\",\n \"extractForAccessibility\",\n \"assembleDocument\",\n \"printHighQuality\"\n];\nconst PERMISSION_FLAG_TO_NAME = {\n [PdfPermissionFlag.Print]: \"print\",\n [PdfPermissionFlag.ModifyContents]: \"modifyContents\",\n [PdfPermissionFlag.CopyContents]: \"copyContents\",\n [PdfPermissionFlag.ModifyAnnotations]: \"modifyAnnotations\",\n [PdfPermissionFlag.FillForms]: \"fillForms\",\n [PdfPermissionFlag.ExtractForAccessibility]: \"extractForAccessibility\",\n [PdfPermissionFlag.AssembleDocument]: \"assembleDocument\",\n [PdfPermissionFlag.PrintHighQuality]: \"printHighQuality\"\n};\nfunction getPermissionOverride(overrides, flag) {\n if (!overrides) return void 0;\n if (flag in overrides) {\n return overrides[flag];\n }\n const name = PERMISSION_FLAG_TO_NAME[flag];\n if (name && name in overrides) {\n return overrides[name];\n }\n return void 0;\n}\nconst getActiveDocumentState = (state) => {\n if (!state.activeDocumentId) return null;\n return state.documents[state.activeDocumentId] ?? null;\n};\nconst getDocumentState = (state, documentId) => {\n return state.documents[documentId] ?? null;\n};\nconst getDocumentIds = (state) => {\n return Object.keys(state.documents);\n};\nconst isDocumentLoaded = (state, documentId) => {\n return !!state.documents[documentId];\n};\nconst getDocumentCount = (state) => {\n return Object.keys(state.documents).length;\n};\nfunction getEffectivePermission(state, documentId, flag) {\n var _a;\n const docState = state.documents[documentId];\n const docConfig = docState == null ? void 0 : docState.permissions;\n const globalConfig = state.globalPermissions;\n const pdfPermissions = ((_a = docState == null ? void 0 : docState.document) == null ? void 0 : _a.permissions) ?? PdfPermissionFlag.AllowAll;\n const docOverride = getPermissionOverride(docConfig == null ? void 0 : docConfig.overrides, flag);\n if (docOverride !== void 0) {\n return docOverride;\n }\n const globalOverride = getPermissionOverride(globalConfig == null ? void 0 : globalConfig.overrides, flag);\n if (globalOverride !== void 0) {\n return globalOverride;\n }\n const enforce = (docConfig == null ? void 0 : docConfig.enforceDocumentPermissions) ?? (globalConfig == null ? void 0 : globalConfig.enforceDocumentPermissions) ?? true;\n if (!enforce) return true;\n return (pdfPermissions & flag) !== 0;\n}\nfunction getEffectivePermissions(state, documentId) {\n return ALL_PERMISSION_FLAGS.reduce((acc, flag) => {\n return getEffectivePermission(state, documentId, flag) ? acc | flag : acc;\n }, 0);\n}\nfunction calculateNextActiveDocument(state, closingDocumentId, explicitNext) {\n const currentActiveId = state.activeDocumentId;\n if (currentActiveId !== closingDocumentId) {\n return currentActiveId;\n }\n if (explicitNext !== void 0) {\n return explicitNext && state.documents[explicitNext] ? explicitNext : null;\n }\n const closingIndex = state.documentOrder.indexOf(closingDocumentId);\n if (closingIndex === -1) {\n return null;\n }\n if (closingIndex > 0) {\n return state.documentOrder[closingIndex - 1];\n }\n if (closingIndex < state.documentOrder.length - 1) {\n return state.documentOrder[closingIndex + 1];\n }\n return null;\n}\nfunction moveDocumentInOrder(currentOrder, documentId, toIndex) {\n const fromIndex = currentOrder.indexOf(documentId);\n if (fromIndex === -1) return null;\n if (toIndex < 0 || toIndex >= currentOrder.length) return null;\n if (fromIndex === toIndex) return null;\n const newOrder = [...currentOrder];\n newOrder.splice(fromIndex, 1);\n newOrder.splice(toIndex, 0, documentId);\n return newOrder;\n}\nconst coreReducer = (state, action) => {\n switch (action.type) {\n case START_LOADING_DOCUMENT: {\n const {\n documentId,\n name,\n scale,\n rotation,\n passwordProvided,\n autoActivate = true,\n permissions\n } = action.payload;\n const newDocState = {\n id: documentId,\n name,\n status: \"loading\",\n loadingProgress: 0,\n error: null,\n document: null,\n scale: scale ?? state.defaultScale,\n rotation: rotation ?? state.defaultRotation,\n passwordProvided: passwordProvided ?? false,\n pageRefreshVersions: {},\n permissions,\n loadStartedAt: Date.now()\n };\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: newDocState\n },\n documentOrder: [...state.documentOrder, documentId],\n // Only activate if autoActivate is true (default), or if no document is currently active\n activeDocumentId: autoActivate || !state.activeDocumentId ? documentId : state.activeDocumentId\n };\n }\n case UPDATE_DOCUMENT_LOADING_PROGRESS: {\n const { documentId, progress } = action.payload;\n const docState = state.documents[documentId];\n if (!docState || docState.status !== \"loading\") return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...docState,\n loadingProgress: progress\n }\n }\n };\n }\n case SET_DOCUMENT_LOADED: {\n const { documentId, document } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...docState,\n status: \"loaded\",\n document,\n error: null,\n errorCode: void 0,\n errorDetails: void 0,\n passwordProvided: void 0,\n loadedAt: Date.now()\n }\n }\n };\n }\n case SET_DOCUMENT_ERROR: {\n const { documentId, error, errorCode, errorDetails } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...docState,\n status: \"error\",\n error,\n errorCode,\n errorDetails\n }\n }\n };\n }\n case RETRY_LOADING_DOCUMENT: {\n const { documentId, passwordProvided } = action.payload;\n const docState = state.documents[documentId];\n if (!docState || docState.status !== \"error\") return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...docState,\n status: \"loading\",\n loadingProgress: 0,\n error: null,\n errorCode: void 0,\n errorDetails: void 0,\n passwordProvided: passwordProvided ?? false,\n loadStartedAt: Date.now()\n }\n }\n };\n }\n case CLOSE_DOCUMENT: {\n const { documentId, nextActiveDocumentId } = action.payload;\n const { [documentId]: removed, ...remainingDocs } = state.documents;\n return {\n ...state,\n documents: remainingDocs,\n documentOrder: state.documentOrder.filter((id) => id !== documentId),\n activeDocumentId: calculateNextActiveDocument(state, documentId, nextActiveDocumentId)\n };\n }\n case MOVE_DOCUMENT: {\n const { documentId, toIndex } = action.payload;\n const newOrder = moveDocumentInOrder(state.documentOrder, documentId, toIndex);\n if (!newOrder) return state;\n return {\n ...state,\n documentOrder: newOrder\n };\n }\n case REORDER_DOCUMENTS: {\n return {\n ...state,\n documentOrder: action.payload\n };\n }\n case SET_ACTIVE_DOCUMENT: {\n return {\n ...state,\n activeDocumentId: action.payload\n };\n }\n case SET_SCALE: {\n const { scale, documentId } = action.payload;\n const targetId = documentId ?? state.activeDocumentId;\n if (!targetId) return state;\n const docState = state.documents[targetId];\n if (!docState) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [targetId]: {\n ...docState,\n scale\n }\n }\n };\n }\n case SET_ROTATION: {\n const { rotation, documentId } = action.payload;\n const targetId = documentId ?? state.activeDocumentId;\n if (!targetId) return state;\n const docState = state.documents[targetId];\n if (!docState) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [targetId]: {\n ...docState,\n rotation\n }\n }\n };\n }\n case REFRESH_PAGES: {\n const { documentId, pageIndexes } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n const newVersions = { ...docState.pageRefreshVersions };\n for (const pageIndex of pageIndexes) {\n newVersions[pageIndex] = (newVersions[pageIndex] || 0) + 1;\n }\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...docState,\n pageRefreshVersions: newVersions\n }\n }\n };\n }\n case UPDATE_DOCUMENT_SECURITY: {\n const { documentId, permissions, isOwnerUnlocked } = action.payload;\n const docState = state.documents[documentId];\n if (!(docState == null ? void 0 : docState.document)) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...docState,\n document: {\n ...docState.document,\n permissions,\n isOwnerUnlocked\n }\n }\n }\n };\n }\n default:\n return state;\n }\n};\nclass PluginRegistry {\n constructor(engine, config) {\n this.plugins = /* @__PURE__ */ new Map();\n this.manifests = /* @__PURE__ */ new Map();\n this.capabilities = /* @__PURE__ */ new Map();\n this.status = /* @__PURE__ */ new Map();\n this.configurations = /* @__PURE__ */ new Map();\n this.initPromise = null;\n this.pendingRegistrations = [];\n this.processingRegistrations = [];\n this.initialized = false;\n this.isInitializing = false;\n this.pluginsReadyPromise = null;\n this.destroyed = false;\n this.resolver = new DependencyResolver();\n this.engine = engine;\n this.initialCoreState = initialCoreState(config);\n this.store = new Store(coreReducer, this.initialCoreState);\n this.logger = (config == null ? void 0 : config.logger) ?? new NoopLogger();\n }\n /**\n * Get the logger instance\n */\n getLogger() {\n return this.logger;\n }\n /**\n * Register a plugin without initializing it\n */\n registerPlugin(pluginPackage, config) {\n if (this.initialized && !this.isInitializing) {\n throw new PluginRegistrationError(\"Cannot register plugins after initialization\");\n }\n this.validateManifest(pluginPackage.manifest);\n this.store.addPluginReducer(\n pluginPackage.manifest.id,\n // We need one type assertion here since we can't fully reconcile TAction with Action\n // due to TypeScript's type system limitations with generic variance\n pluginPackage.reducer,\n \"function\" === typeof pluginPackage.initialState ? pluginPackage.initialState(\n this.initialCoreState,\n {\n ...pluginPackage.manifest.defaultConfig,\n ...config\n }\n ) : pluginPackage.initialState\n );\n this.pendingRegistrations.push({\n package: pluginPackage,\n config\n });\n }\n /**\n * Get the central store instance\n */\n getStore() {\n return this.store;\n }\n /**\n * Get the engine instance\n */\n getEngine() {\n return this.engine;\n }\n /**\n * Get a promise that resolves when all plugins are ready\n */\n pluginsReady() {\n if (this.pluginsReadyPromise) {\n return this.pluginsReadyPromise;\n }\n this.pluginsReadyPromise = (async () => {\n if (!this.initialized) {\n await this.initialize();\n }\n const readyPromises = Array.from(this.plugins.values()).map(\n (p) => typeof p.ready === \"function\" ? p.ready() : Promise.resolve()\n );\n await Promise.all(readyPromises);\n })();\n return this.pluginsReadyPromise;\n }\n /**\n * INITIALISE THE REGISTRY – runs once no-matter-how-many calls *\n */\n async initialize() {\n if (this.destroyed) {\n throw new PluginRegistrationError(\"Registry has been destroyed\");\n }\n if (this.initPromise) {\n return this.initPromise;\n }\n this.initPromise = (async () => {\n if (this.initialized) {\n throw new PluginRegistrationError(\"Registry is already initialized\");\n }\n this.isInitializing = true;\n try {\n if (this.destroyed) return;\n while (this.pendingRegistrations.length > 0) {\n if (this.destroyed) return;\n this.processingRegistrations = [...this.pendingRegistrations];\n this.pendingRegistrations = [];\n for (const reg of this.processingRegistrations) {\n const dependsOn = /* @__PURE__ */ new Set();\n const allDeps = [...reg.package.manifest.requires, ...reg.package.manifest.optional];\n for (const cap of allDeps) {\n const provider = this.processingRegistrations.find(\n (r) => r.package.manifest.provides.includes(cap)\n );\n if (provider) {\n dependsOn.add(provider.package.manifest.id);\n }\n }\n this.resolver.addNode(reg.package.manifest.id, [...dependsOn]);\n }\n const loadOrder = this.resolver.resolveLoadOrder();\n for (const id of loadOrder) {\n const reg = this.processingRegistrations.find((r) => r.package.manifest.id === id);\n this.instantiatePlugin(reg.package.manifest, reg.package.create, reg.config);\n }\n for (const id of loadOrder) {\n await this.runPluginInitialization(id);\n }\n this.processingRegistrations = [];\n this.resolver = new DependencyResolver();\n }\n this.initialized = true;\n } catch (err) {\n if (err instanceof Error) {\n throw new CircularDependencyError(\n `Failed to resolve plugin dependencies: ${err.message}`\n );\n }\n throw err;\n } finally {\n this.isInitializing = false;\n }\n })();\n return this.initPromise;\n }\n /**\n * Phase 2: Create instance and register capabilities\n */\n instantiatePlugin(manifest, packageCreator, config) {\n const finalConfig = {\n ...manifest.defaultConfig,\n ...config\n };\n this.validateConfig(manifest.id, finalConfig, manifest.defaultConfig);\n const plugin = packageCreator(this, finalConfig);\n this.validatePlugin(plugin);\n for (const capability of manifest.provides) {\n if (this.capabilities.has(capability)) {\n throw new PluginRegistrationError(\n `Capability ${capability} is already provided by plugin ${this.capabilities.get(capability)}`\n );\n }\n this.capabilities.set(capability, manifest.id);\n }\n this.plugins.set(manifest.id, plugin);\n this.manifests.set(manifest.id, manifest);\n this.status.set(manifest.id, \"registered\");\n this.configurations.set(manifest.id, finalConfig);\n }\n /**\n * Phase 3: Run the initialize method\n */\n async runPluginInitialization(pluginId) {\n const plugin = this.plugins.get(pluginId);\n if (!plugin) return;\n const manifest = this.manifests.get(pluginId);\n const config = this.configurations.get(pluginId);\n for (const capability of manifest.requires) {\n if (!this.capabilities.has(capability)) {\n throw new PluginRegistrationError(\n `Missing required capability: ${capability} for plugin ${pluginId}`\n );\n }\n }\n this.logger.debug(\"PluginRegistry\", \"InitializePlugin\", `Initializing plugin ${pluginId}`);\n try {\n if (plugin.initialize) {\n await plugin.initialize(config);\n }\n this.status.set(pluginId, \"active\");\n this.logger.info(\n \"PluginRegistry\",\n \"PluginInitialized\",\n `Plugin ${pluginId} initialized successfully`\n );\n } catch (error) {\n this.status.set(pluginId, \"error\");\n this.logger.error(\n \"PluginRegistry\",\n \"InitializationFailed\",\n `Plugin ${pluginId} initialization failed`,\n { error }\n );\n throw error;\n }\n }\n getPluginConfig(pluginId) {\n const config = this.configurations.get(pluginId);\n if (!config) {\n throw new PluginNotFoundError(`Configuration for plugin ${pluginId} not found`);\n }\n return config;\n }\n validateConfig(pluginId, config, defaultConfig) {\n const requiredKeys = Object.keys(defaultConfig);\n const missingKeys = requiredKeys.filter((key) => !config.hasOwnProperty(key));\n if (missingKeys.length > 0) {\n throw new PluginConfigurationError(\n `Missing required configuration keys for plugin ${pluginId}: ${missingKeys.join(\", \")}`\n );\n }\n }\n async updatePluginConfig(pluginId, config) {\n const plugin = this.getPlugin(pluginId);\n if (!plugin) {\n throw new PluginNotFoundError(`Plugin ${pluginId} not found`);\n }\n const manifest = this.manifests.get(pluginId);\n const currentConfig = this.configurations.get(pluginId);\n if (!manifest || !currentConfig) {\n throw new PluginNotFoundError(`Plugin ${pluginId} not found`);\n }\n const newConfig = {\n ...currentConfig,\n ...config\n };\n this.validateConfig(pluginId, newConfig, manifest.defaultConfig);\n this.configurations.set(pluginId, newConfig);\n if (plugin.initialize) {\n await plugin.initialize(newConfig);\n }\n }\n /**\n * Register multiple plugins at once\n */\n registerPluginBatch(registrations) {\n for (const reg of registrations) {\n this.registerPlugin(reg.package, reg.config);\n }\n }\n /**\n * Unregister a plugin\n */\n async unregisterPlugin(pluginId) {\n const plugin = this.plugins.get(pluginId);\n if (!plugin) {\n throw new PluginNotFoundError(`Plugin ${pluginId} is not registered`);\n }\n const manifest = this.manifests.get(pluginId);\n if (!manifest) {\n throw new PluginNotFoundError(`Manifest for plugin ${pluginId} not found`);\n }\n for (const [otherId, otherManifest] of this.manifests.entries()) {\n if (otherId === pluginId) continue;\n const dependsOnThis = [...otherManifest.requires, ...otherManifest.optional].some(\n (cap) => manifest.provides.includes(cap)\n );\n if (dependsOnThis) {\n throw new PluginRegistrationError(\n `Cannot unregister plugin ${pluginId}: plugin ${otherId} depends on it`\n );\n }\n }\n try {\n if (plugin.destroy) {\n await plugin.destroy();\n }\n for (const capability of manifest.provides) {\n this.capabilities.delete(capability);\n }\n this.plugins.delete(pluginId);\n this.manifests.delete(pluginId);\n this.status.delete(pluginId);\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to unregister plugin ${pluginId}: ${error.message}`);\n }\n throw error;\n }\n }\n /**\n * Get a plugin instance\n * @param pluginId The ID of the plugin to get\n * @returns The plugin instance or null if not found\n */\n getPlugin(pluginId) {\n const plugin = this.plugins.get(pluginId);\n if (!plugin) {\n return null;\n }\n return plugin;\n }\n /**\n * Get a plugin that provides a specific capability\n * @param capability The capability to get a provider for\n * @returns The plugin providing the capability or null if not found\n */\n getCapabilityProvider(capability) {\n const pluginId = this.capabilities.get(capability);\n if (!pluginId) {\n return null;\n }\n return this.getPlugin(pluginId);\n }\n /**\n * Check if a capability is available\n */\n hasCapability(capability) {\n return this.capabilities.has(capability);\n }\n /**\n * Get all registered plugins\n */\n getAllPlugins() {\n return Array.from(this.plugins.values());\n }\n /**\n * Get plugin status\n */\n getPluginStatus(pluginId) {\n const status = this.status.get(pluginId);\n if (!status) {\n throw new PluginNotFoundError(`Plugin ${pluginId} not found`);\n }\n return status;\n }\n /**\n * Validate plugin object\n */\n validatePlugin(plugin) {\n if (!plugin.id) {\n throw new PluginRegistrationError(\"Plugin must have an id\");\n }\n }\n /**\n * Validate plugin manifest\n */\n validateManifest(manifest) {\n if (!manifest.id) {\n throw new PluginRegistrationError(\"Manifest must have an id\");\n }\n if (!manifest.name) {\n throw new PluginRegistrationError(\"Manifest must have a name\");\n }\n if (!manifest.version) {\n throw new PluginRegistrationError(\"Manifest must have a version\");\n }\n if (!Array.isArray(manifest.provides)) {\n throw new PluginRegistrationError(\"Manifest must have a provides array\");\n }\n if (!Array.isArray(manifest.requires)) {\n throw new PluginRegistrationError(\"Manifest must have a requires array\");\n }\n if (!Array.isArray(manifest.optional)) {\n throw new PluginRegistrationError(\"Manifest must have an optional array\");\n }\n }\n isDestroyed() {\n return this.destroyed;\n }\n /**\n * DESTROY EVERYTHING – waits for any ongoing initialise(), once *\n */\n async destroy() {\n var _a;\n if (this.destroyed) throw new PluginRegistrationError(\"Registry has already been destroyed\");\n this.destroyed = true;\n try {\n await this.initPromise;\n } catch {\n }\n for (const plugin of Array.from(this.plugins.values()).reverse()) {\n await ((_a = plugin.destroy) == null ? void 0 : _a.call(plugin));\n }\n this.store.destroy();\n this.plugins.clear();\n this.manifests.clear();\n this.capabilities.clear();\n this.status.clear();\n this.pendingRegistrations.length = 0;\n this.processingRegistrations.length = 0;\n }\n}\nfunction createPluginRegistration(pluginPackage, config) {\n return {\n package: pluginPackage,\n config\n };\n}\nfunction hasAutoMountElements(pkg) {\n return \"autoMountElements\" in pkg && typeof pkg.autoMountElements === \"function\";\n}\nclass BasePlugin {\n constructor(id, registry) {\n this.id = id;\n this.registry = registry;\n this.cooldownActions = {};\n this.debouncedTimeouts = {};\n this.unsubscribeFromState = null;\n this.unsubscribeFromCoreStore = null;\n this.unsubscribeFromStartLoadingDocument = null;\n this.unsubscribeFromSetDocumentLoaded = null;\n this.unsubscribeFromCloseDocument = null;\n this.unsubscribeFromSetScale = null;\n this.unsubscribeFromSetRotation = null;\n if (id !== this.constructor.id) {\n throw new Error(\n `Plugin ID mismatch: ${id} !== ${this.constructor.id}`\n );\n }\n this.engine = this.registry.getEngine();\n this.logger = this.registry.getLogger();\n this.coreStore = this.registry.getStore();\n this.pluginStore = this.coreStore.getPluginStore(this.id);\n this.unsubscribeFromState = this.pluginStore.subscribeToState((action, newState, oldState) => {\n this.onStoreUpdated(oldState, newState);\n });\n this.unsubscribeFromCoreStore = this.coreStore.subscribe((action, newState, oldState) => {\n this.onCoreStoreUpdated(oldState, newState);\n if (newState.core.activeDocumentId !== oldState.core.activeDocumentId) {\n this.onActiveDocumentChanged(\n oldState.core.activeDocumentId,\n newState.core.activeDocumentId\n );\n }\n });\n this.unsubscribeFromStartLoadingDocument = this.coreStore.onAction(\n START_LOADING_DOCUMENT,\n (action) => {\n this.onDocumentLoadingStarted(action.payload.documentId);\n }\n );\n this.unsubscribeFromSetDocumentLoaded = this.coreStore.onAction(\n SET_DOCUMENT_LOADED,\n (action) => {\n this.onDocumentLoaded(action.payload.documentId);\n }\n );\n this.unsubscribeFromCloseDocument = this.coreStore.onAction(CLOSE_DOCUMENT, (action) => {\n this.onDocumentClosed(action.payload.documentId);\n });\n this.unsubscribeFromSetScale = this.coreStore.onAction(SET_SCALE, (action, state) => {\n const targetId = action.payload.documentId ?? state.core.activeDocumentId;\n if (targetId) {\n this.onScaleChanged(targetId, action.payload.scale);\n }\n });\n this.unsubscribeFromSetRotation = this.coreStore.onAction(SET_ROTATION, (action, state) => {\n const targetId = action.payload.documentId ?? state.core.activeDocumentId;\n if (targetId) {\n this.onRotationChanged(targetId, action.payload.rotation);\n }\n });\n this.readyPromise = new Promise((resolve) => {\n this.readyResolve = resolve;\n });\n this.readyResolve();\n }\n provides() {\n if (!this._capability) {\n const cap = this.buildCapability();\n this._capability = Object.freeze(cap);\n }\n return this._capability;\n }\n /**\n * Get a copy of the current state\n */\n get state() {\n return this.pluginStore.getState();\n }\n /**\n * Get a copy of the current core state\n */\n get coreState() {\n return this.coreStore.getState();\n }\n /**\n * @deprecated use `this.state` Get a copy of the current state\n */\n getState() {\n return this.pluginStore.getState();\n }\n /**\n * @deprecated use `this.coreState` Get a copy of the current core state\n */\n getCoreState() {\n return this.coreStore.getState();\n }\n /**\n * Core Dispatch\n */\n dispatchCoreAction(action) {\n return this.coreStore.dispatchToCore(action);\n }\n /**\n * Dispatch an action to all plugins\n */\n dispatchToAllPlugins(action) {\n return this.coreStore.dispatch(action);\n }\n /**\n * Dispatch an action\n */\n dispatch(action) {\n return this.pluginStore.dispatch(action);\n }\n /**\n * Dispatch an action with a cooldown to prevent rapid repeated calls\n * This executes immediately if cooldown has expired, then blocks subsequent calls\n * @param action The action to dispatch\n * @param cooldownTime Time in ms for cooldown (default: 100ms)\n * @returns boolean indicating whether the action was dispatched or blocked\n */\n cooldownDispatch(action, cooldownTime = 100) {\n const now = Date.now();\n const lastActionTime = this.cooldownActions[action.type] || 0;\n if (now - lastActionTime >= cooldownTime) {\n this.cooldownActions[action.type] = now;\n this.dispatch(action);\n return true;\n }\n return false;\n }\n /**\n * Dispatch an action with true debouncing - waits for the delay after the last call\n * Each new call resets the timer. Action only executes after no calls for the specified time.\n * @param action The action to dispatch\n * @param debounceTime Time in ms to wait after the last call\n */\n debouncedDispatch(action, debounceTime = 100) {\n const actionKey = action.type;\n if (this.debouncedTimeouts[actionKey]) {\n clearTimeout(this.debouncedTimeouts[actionKey]);\n }\n this.debouncedTimeouts[actionKey] = setTimeout(() => {\n this.dispatch(action);\n delete this.debouncedTimeouts[actionKey];\n }, debounceTime);\n }\n /**\n * Cancel a pending debounced action\n * @param actionType The action type to cancel\n */\n cancelDebouncedDispatch(actionType) {\n if (this.debouncedTimeouts[actionType]) {\n clearTimeout(this.debouncedTimeouts[actionType]);\n delete this.debouncedTimeouts[actionType];\n }\n }\n /**\n * Subscribe to state changes\n */\n subscribe(listener) {\n return this.pluginStore.subscribeToState(listener);\n }\n /**\n * Subscribe to core store changes\n */\n subscribeToCoreStore(listener) {\n return this.coreStore.subscribe(listener);\n }\n /**\n * Called when the plugin store state is updated\n * @param oldState Previous state\n * @param newState New state\n */\n onStoreUpdated(oldState, newState) {\n }\n /**\n * Called when the core store state is updated\n * @param oldState Previous state\n * @param newState New state\n */\n onCoreStoreUpdated(oldState, newState) {\n }\n /**\n * Called when a document is opened\n * Override to initialize per-document state\n * @param documentId The ID of the document that was opened\n */\n onDocumentLoadingStarted(documentId) {\n }\n /**\n * Called when a document is loaded\n * @param documentId The ID of the document that is loaded\n */\n onDocumentLoaded(documentId) {\n }\n /**\n * Called when a document is closed\n * Override to cleanup per-document state\n * @param documentId The ID of the document that was closed\n */\n onDocumentClosed(documentId) {\n }\n /**\n * Called when the active document changes\n * @param previousId The ID of the previous active document\n * @param currentId The ID of the new active document\n */\n onActiveDocumentChanged(previousId, currentId) {\n }\n onScaleChanged(documentId, scale) {\n }\n onRotationChanged(documentId, rotation) {\n }\n /**\n * Cleanup method to be called when plugin is being destroyed\n */\n destroy() {\n Object.values(this.debouncedTimeouts).forEach((timeout) => {\n clearTimeout(timeout);\n });\n this.debouncedTimeouts = {};\n if (this.unsubscribeFromState) {\n this.unsubscribeFromState();\n this.unsubscribeFromState = null;\n }\n if (this.unsubscribeFromCoreStore) {\n this.unsubscribeFromCoreStore();\n this.unsubscribeFromCoreStore = null;\n }\n if (this.unsubscribeFromStartLoadingDocument) {\n this.unsubscribeFromStartLoadingDocument();\n this.unsubscribeFromStartLoadingDocument = null;\n }\n if (this.unsubscribeFromSetDocumentLoaded) {\n this.unsubscribeFromSetDocumentLoaded();\n this.unsubscribeFromSetDocumentLoaded = null;\n }\n if (this.unsubscribeFromCloseDocument) {\n this.unsubscribeFromCloseDocument();\n this.unsubscribeFromCloseDocument = null;\n }\n if (this.unsubscribeFromSetScale) {\n this.unsubscribeFromSetScale();\n this.unsubscribeFromSetScale = null;\n }\n if (this.unsubscribeFromSetRotation) {\n this.unsubscribeFromSetRotation();\n this.unsubscribeFromSetRotation = null;\n }\n }\n /**\n * Returns a promise that resolves when the plugin is ready\n */\n ready() {\n return this.readyPromise;\n }\n /**\n * Mark the plugin as ready\n */\n markReady() {\n this.readyResolve();\n }\n /**\n * Reset the ready state (useful for plugins that need to reinitialize)\n */\n resetReady() {\n this.readyPromise = new Promise((resolve) => {\n this.readyResolve = resolve;\n });\n }\n /**\n * Get the active document ID\n * @throws Error if no active document exists\n */\n getActiveDocumentId() {\n const id = this.coreState.core.activeDocumentId;\n if (!id) {\n throw new Error(\"No active document\");\n }\n return id;\n }\n /**\n * Get the active document ID or null if none exists\n */\n getActiveDocumentIdOrNull() {\n return this.coreState.core.activeDocumentId;\n }\n /**\n * Get core document state for a specific document\n * @param documentId Document ID (optional, defaults to active document)\n * @returns Document state or null if not found\n */\n getCoreDocument(documentId) {\n const id = documentId ?? this.getActiveDocumentIdOrNull();\n if (!id) return null;\n return this.coreState.core.documents[id] ?? null;\n }\n /**\n * Get core document state for a specific document\n * @param documentId Document ID (optional, defaults to active document)\n * @throws Error if document not found\n */\n getCoreDocumentOrThrow(documentId) {\n const doc = this.getCoreDocument(documentId);\n if (!doc) {\n throw new Error(`Document not found: ${documentId ?? \"active\"}`);\n }\n return doc;\n }\n // ─────────────────────────────────────────────────────────\n // Permission Helpers\n // ─────────────────────────────────────────────────────────\n /**\n * Get the effective permission flags for a document.\n * Applies layered resolution: per-document override → global override → PDF permission.\n * Returns AllowAll if document not found.\n * @param documentId Document ID (optional, defaults to active document)\n */\n getDocumentPermissions(documentId) {\n const docId = documentId ?? this.coreState.core.activeDocumentId;\n if (!docId) return PdfPermissionFlag.AllowAll;\n return getEffectivePermissions(this.coreState.core, docId);\n }\n /**\n * Check if a document has the required permissions (returns boolean).\n * Applies layered resolution: per-document override → global override → PDF permission.\n * Useful for conditional UI logic.\n * @param documentId Document ID (optional, defaults to active document)\n * @param flags Permission flags to check\n */\n checkPermission(documentId, ...flags) {\n const docId = documentId ?? this.coreState.core.activeDocumentId;\n if (!docId) return true;\n return flags.every((flag) => getEffectivePermission(this.coreState.core, docId, flag));\n }\n /**\n * Assert that a document has the required permissions.\n * Applies layered resolution: per-document override → global override → PDF permission.\n * Throws PermissionDeniedError if any flag is missing.\n * @param documentId Document ID (optional, defaults to active document)\n * @param flags Permission flags to require\n */\n requirePermission(documentId, ...flags) {\n const docId = documentId ?? this.coreState.core.activeDocumentId;\n if (!docId) return;\n const missingFlags = [];\n for (const flag of flags) {\n if (!getEffectivePermission(this.coreState.core, docId, flag)) {\n missingFlags.push(flag);\n }\n }\n if (missingFlags.length > 0) {\n const effectivePermissions = getEffectivePermissions(this.coreState.core, docId);\n throw new PermissionDeniedError(missingFlags, effectivePermissions);\n }\n }\n}\nclass EventControl {\n constructor(handler, options) {\n this.handler = handler;\n this.options = options;\n this.lastRun = 0;\n this.handle = (data) => {\n if (this.options.mode === \"debounce\") {\n this.debounce(data);\n } else {\n this.throttle(data);\n }\n };\n }\n debounce(data) {\n if (this.timeoutId) {\n window.clearTimeout(this.timeoutId);\n }\n this.timeoutId = window.setTimeout(() => {\n this.handler(data);\n this.timeoutId = void 0;\n }, this.options.wait);\n }\n throttle(data) {\n if (this.options.mode === \"debounce\") return;\n const now = Date.now();\n const throttleMode = this.options.throttleMode || \"leading-trailing\";\n if (now - this.lastRun >= this.options.wait) {\n if (throttleMode === \"leading-trailing\") {\n this.handler(data);\n }\n this.lastRun = now;\n }\n if (this.timeoutId) {\n window.clearTimeout(this.timeoutId);\n }\n this.timeoutId = window.setTimeout(\n () => {\n this.handler(data);\n this.lastRun = Date.now();\n this.timeoutId = void 0;\n },\n this.options.wait - (now - this.lastRun)\n );\n }\n destroy() {\n if (this.timeoutId) {\n window.clearTimeout(this.timeoutId);\n }\n }\n}\nclass KeyedEventControl {\n constructor(handler, options) {\n this.handler = handler;\n this.options = options;\n this.controls = /* @__PURE__ */ new Map();\n this.handle = (data) => {\n const key = String(this.options.keyExtractor(data));\n let control = this.controls.get(key);\n if (!control) {\n control = new EventControl(this.handler, this.baseOptions);\n this.controls.set(key, control);\n }\n control.handle(data);\n };\n this.baseOptions = {\n mode: options.mode,\n wait: options.wait,\n ...options.mode === \"throttle\" && \"throttleMode\" in options ? { throttleMode: options.throttleMode } : {}\n };\n }\n destroy() {\n for (const control of this.controls.values()) {\n control.destroy();\n }\n this.controls.clear();\n }\n}\nfunction isKeyedOptions(options) {\n return \"keyExtractor\" in options;\n}\nfunction clamp(value, min, max) {\n return value < min ? min : value > max ? max : value;\n}\nfunction arePropsEqual(a, b, visited) {\n if (a === b) {\n return true;\n }\n if (a == null || b == null) {\n return a === b;\n }\n const aType = typeof a;\n const bType = typeof b;\n if (aType !== bType) return false;\n if (aType === \"object\") {\n if (!visited) visited = /* @__PURE__ */ new Set();\n const pairId = getPairId(a, b);\n if (visited.has(pairId)) {\n return true;\n }\n visited.add(pairId);\n const aIsArray = Array.isArray(a);\n const bIsArray = Array.isArray(b);\n if (aIsArray && bIsArray) {\n return arraysEqualUnordered(a, b, visited);\n } else if (!aIsArray && !bIsArray) {\n return objectsEqual(a, b, visited);\n } else {\n return false;\n }\n }\n return false;\n}\nfunction getPairId(a, b) {\n return `${objectId(a)}__${objectId(b)}`;\n}\nlet objectIdCounter = 0;\nconst objectIds = /* @__PURE__ */ new WeakMap();\nfunction objectId(obj) {\n if (!objectIds.has(obj)) {\n objectIds.set(obj, ++objectIdCounter);\n }\n return objectIds.get(obj);\n}\nfunction arraysEqualUnordered(a, b, visited) {\n if (a.length !== b.length) return false;\n const used = new Array(b.length).fill(false);\n outer: for (let i = 0; i < a.length; i++) {\n const elemA = a[i];\n for (let j = 0; j < b.length; j++) {\n if (used[j]) continue;\n if (arePropsEqual(elemA, b[j], visited)) {\n used[j] = true;\n continue outer;\n }\n }\n return false;\n }\n return true;\n}\nfunction objectsEqual(a, b, visited) {\n const aKeys = Object.keys(a).sort();\n const bKeys = Object.keys(b).sort();\n if (aKeys.length !== bKeys.length) return false;\n for (let i = 0; i < aKeys.length; i++) {\n if (aKeys[i] !== bKeys[i]) return false;\n }\n for (const key of aKeys) {\n const valA = a[key];\n const valB = b[key];\n if (!arePropsEqual(valA, valB, visited)) {\n return false;\n }\n }\n return true;\n}\nfunction createEmitter() {\n const listeners = /* @__PURE__ */ new Set();\n const on = (l) => {\n listeners.add(l);\n return () => listeners.delete(l);\n };\n return {\n emit: (v = void 0) => listeners.forEach((l) => l(v)),\n on,\n off: (l) => listeners.delete(l),\n clear: () => listeners.clear()\n };\n}\nfunction createBehaviorEmitter(initial, equality = arePropsEqual) {\n const listeners = /* @__PURE__ */ new Set();\n const proxyMap = /* @__PURE__ */ new Map();\n let _value = initial;\n const notify = (v) => listeners.forEach((l) => l(v));\n const baseOn = (listener, options) => {\n let realListener = listener;\n let destroy = () => {\n };\n if (options) {\n if (isKeyedOptions(options)) {\n const ctl = new KeyedEventControl(listener, options);\n realListener = ctl.handle;\n destroy = () => ctl.destroy();\n } else {\n const ctl = new EventControl(listener, options);\n realListener = ctl.handle;\n destroy = () => ctl.destroy();\n }\n proxyMap.set(listener, { wrapped: realListener, destroy });\n }\n if (_value !== void 0) realListener(_value);\n listeners.add(realListener);\n return () => {\n listeners.delete(realListener);\n destroy();\n proxyMap.delete(listener);\n };\n };\n return {\n /* emitter behaviour ---------------------------------------- */\n get value() {\n return _value;\n },\n emit(v = void 0) {\n if (_value === void 0 || !equality(_value, v)) {\n _value = v;\n notify(v);\n }\n },\n on: baseOn,\n off(listener) {\n const proxy = proxyMap.get(listener);\n if (proxy) {\n listeners.delete(proxy.wrapped);\n proxy.destroy();\n proxyMap.delete(listener);\n } else {\n listeners.delete(listener);\n }\n },\n clear() {\n listeners.clear();\n proxyMap.forEach((p) => p.destroy());\n proxyMap.clear();\n },\n /* derived hook --------------------------------------------- */\n select(selector, eq = arePropsEqual) {\n return (listener, options) => {\n let prev;\n if (_value !== void 0) {\n const mapped = selector(_value);\n prev = mapped;\n listener(mapped);\n }\n return baseOn(\n (next) => {\n const mapped = selector(next);\n if (prev === void 0 || !eq(prev, mapped)) {\n prev = mapped;\n listener(mapped);\n }\n },\n options\n );\n };\n }\n };\n}\nfunction createScopedEmitter(toGlobalEvent, options) {\n const shouldCache = (options == null ? void 0 : options.cache) ?? true;\n const equality = (options == null ? void 0 : options.equality) ?? arePropsEqual;\n const scopeCaches = /* @__PURE__ */ new Map();\n const scopeListeners = /* @__PURE__ */ new Map();\n const scopeProxyMaps = /* @__PURE__ */ new Map();\n const globalListeners = /* @__PURE__ */ new Set();\n const globalProxyMap = /* @__PURE__ */ new Map();\n const normalizeKey = (key) => String(key);\n const getOrCreateListeners = (key) => {\n let listeners = scopeListeners.get(key);\n if (!listeners) {\n listeners = /* @__PURE__ */ new Set();\n scopeListeners.set(key, listeners);\n }\n return listeners;\n };\n const getOrCreateProxyMap = (key) => {\n let proxyMap = scopeProxyMaps.get(key);\n if (!proxyMap) {\n proxyMap = /* @__PURE__ */ new Map();\n scopeProxyMaps.set(key, proxyMap);\n }\n return proxyMap;\n };\n const onGlobal = (listener, options2) => {\n let realListener = listener;\n let destroy = () => {\n };\n if (options2) {\n if (isKeyedOptions(options2)) {\n const ctl = new KeyedEventControl(listener, options2);\n realListener = ctl.handle;\n destroy = () => ctl.destroy();\n } else {\n const ctl = new EventControl(listener, options2);\n realListener = ctl.handle;\n destroy = () => ctl.destroy();\n }\n globalProxyMap.set(listener, { wrapped: realListener, destroy });\n }\n globalListeners.add(realListener);\n return () => {\n globalListeners.delete(realListener);\n destroy();\n globalProxyMap.delete(listener);\n };\n };\n return {\n emit(key, data) {\n const normalizedKey = normalizeKey(key);\n if (shouldCache) {\n const cached = scopeCaches.get(normalizedKey);\n if (cached !== void 0 && equality(cached, data)) {\n return;\n }\n scopeCaches.set(normalizedKey, data);\n }\n const listeners = scopeListeners.get(normalizedKey);\n if (listeners) {\n listeners.forEach((l) => l(data));\n }\n const globalEvent = toGlobalEvent(key, data);\n globalListeners.forEach((l) => l(globalEvent));\n },\n forScope(key) {\n const normalizedKey = normalizeKey(key);\n return (listener, options2) => {\n const listeners = getOrCreateListeners(normalizedKey);\n const proxyMap = getOrCreateProxyMap(normalizedKey);\n let realListener = listener;\n let destroy = () => {\n };\n if (options2) {\n if (isKeyedOptions(options2)) {\n const ctl = new KeyedEventControl(listener, options2);\n realListener = ctl.handle;\n destroy = () => ctl.destroy();\n } else {\n const ctl = new EventControl(listener, options2);\n realListener = ctl.handle;\n destroy = () => ctl.destroy();\n }\n proxyMap.set(listener, { wrapped: realListener, destroy });\n }\n if (shouldCache) {\n const cached = scopeCaches.get(normalizedKey);\n if (cached !== void 0) {\n realListener(cached);\n }\n }\n listeners.add(realListener);\n return () => {\n listeners.delete(realListener);\n destroy();\n proxyMap.delete(listener);\n if (listeners.size === 0) {\n scopeListeners.delete(normalizedKey);\n }\n if (proxyMap.size === 0) {\n scopeProxyMaps.delete(normalizedKey);\n }\n };\n };\n },\n onGlobal,\n getValue(key) {\n return shouldCache ? scopeCaches.get(normalizeKey(key)) : void 0;\n },\n getScopes() {\n if (shouldCache) {\n return Array.from(scopeCaches.keys());\n }\n return Array.from(scopeListeners.keys());\n },\n clearScope(key) {\n const normalizedKey = normalizeKey(key);\n if (shouldCache) {\n scopeCaches.delete(normalizedKey);\n }\n const listeners = scopeListeners.get(normalizedKey);\n if (listeners) {\n listeners.clear();\n scopeListeners.delete(normalizedKey);\n }\n const proxyMap = scopeProxyMaps.get(normalizedKey);\n if (proxyMap) {\n proxyMap.forEach((p) => p.destroy());\n proxyMap.clear();\n scopeProxyMaps.delete(normalizedKey);\n }\n },\n clear() {\n if (shouldCache) {\n scopeCaches.clear();\n }\n scopeListeners.forEach((set) => set.clear());\n scopeListeners.clear();\n scopeProxyMaps.forEach((map) => {\n map.forEach((p) => p.destroy());\n map.clear();\n });\n scopeProxyMaps.clear();\n globalListeners.clear();\n globalProxyMap.forEach((p) => p.destroy());\n globalProxyMap.clear();\n }\n };\n}\nfunction enumEntries(record) {\n return Object.entries(record).map(([k, v]) => {\n const maybeNum = Number(k);\n const typedKey = Number.isFinite(maybeNum) && k.trim() !== \"\" ? maybeNum : k;\n return [typedKey, v];\n });\n}\nclass PluginPackageBuilder {\n constructor(basePackage) {\n this.autoMountElements = [];\n this.package = basePackage;\n }\n addUtility(component) {\n this.autoMountElements.push({ component, type: \"utility\" });\n return this;\n }\n addWrapper(component) {\n this.autoMountElements.push({ component, type: \"wrapper\" });\n return this;\n }\n build() {\n return {\n ...this.package,\n autoMountElements: () => this.autoMountElements\n };\n }\n}\nfunction createPluginPackage(basePackage) {\n return new PluginPackageBuilder(basePackage);\n}\nexport {\n ALL_PERMISSION_FLAGS,\n ALL_PERMISSION_NAMES,\n BasePlugin,\n CLOSE_DOCUMENT,\n CORE_ACTION_TYPES,\n CapabilityConflictError,\n CapabilityNotFoundError,\n CircularDependencyError,\n DependencyResolver,\n EventControl,\n KeyedEventControl,\n MOVE_DOCUMENT,\n PERMISSION_FLAG_TO_NAME,\n PERMISSION_NAME_TO_FLAG,\n PluginConfigurationError,\n PluginInitializationError,\n PluginNotFoundError,\n PluginPackageBuilder,\n PluginRegistrationError,\n PluginRegistry,\n REFRESH_DOCUMENT,\n REFRESH_PAGES,\n REORDER_DOCUMENTS,\n RETRY_LOADING_DOCUMENT,\n SET_ACTIVE_DOCUMENT,\n SET_DEFAULT_ROTATION,\n SET_DEFAULT_SCALE,\n SET_DOCUMENT_ERROR,\n SET_DOCUMENT_LOADED,\n SET_PAGES,\n SET_ROTATION,\n SET_SCALE,\n START_LOADING_DOCUMENT,\n UPDATE_DOCUMENT_LOADING_PROGRESS,\n UPDATE_DOCUMENT_SECURITY,\n arePropsEqual,\n clamp,\n closeDocument,\n createBehaviorEmitter,\n createEmitter,\n createPluginPackage,\n createPluginRegistration,\n createScopedEmitter,\n enumEntries,\n getActiveDocumentState,\n getDocumentCount,\n getDocumentIds,\n getDocumentState,\n getEffectivePermission,\n getEffectivePermissions,\n getPermissionOverride,\n hasAutoMountElements,\n initialCoreState,\n isDocumentLoaded,\n isKeyedOptions,\n moveDocument,\n refreshDocument,\n refreshPages,\n reorderDocuments,\n retryLoadingDocument,\n setActiveDocument,\n setDefaultRotation,\n setDefaultScale,\n setDocumentError,\n setDocumentLoaded,\n setPages,\n setRotation,\n setScale,\n startLoadingDocument,\n updateDocumentLoadingProgress,\n updateDocumentSecurity\n};\n//# sourceMappingURL=index.js.map\n","import { createContext, useMemo, Fragment, useState, useRef, useEffect, useContext } from \"react\";\nimport { jsxs, jsx } from \"react/jsx-runtime\";\nimport { hasAutoMountElements, PluginRegistry } from \"@embedpdf/core\";\nimport { PdfPermissionFlag } from \"@embedpdf/models\";\nconst PDFContext = createContext({\n registry: null,\n coreState: null,\n isInitializing: true,\n pluginsReady: false,\n activeDocumentId: null,\n activeDocument: null,\n documents: {},\n documentStates: []\n});\nfunction AutoMount({ plugins, children }) {\n const { utilities, wrappers } = useMemo(() => {\n const utilities2 = [];\n const wrappers2 = [];\n for (const reg of plugins) {\n const pkg = reg.package;\n if (hasAutoMountElements(pkg)) {\n const elements = pkg.autoMountElements() || [];\n for (const element of elements) {\n if (element.type === \"utility\") {\n utilities2.push(element.component);\n } else if (element.type === \"wrapper\") {\n wrappers2.push(element.component);\n }\n }\n }\n }\n return { utilities: utilities2, wrappers: wrappers2 };\n }, [plugins]);\n const contentWithUtilities = /* @__PURE__ */ jsxs(Fragment, { children: [\n children,\n utilities.map((Utility, i) => /* @__PURE__ */ jsx(Utility, {}, `utility-${i}`))\n ] });\n const wrappedContent = wrappers.reduce(\n (content, Wrapper) => /* @__PURE__ */ jsx(Wrapper, { children: content }),\n contentWithUtilities\n );\n return /* @__PURE__ */ jsx(Fragment, { children: wrappedContent });\n}\nfunction EmbedPDF({\n engine,\n config,\n logger,\n onInitialized,\n plugins,\n children,\n autoMountDomElements = true\n}) {\n const [registry, setRegistry] = useState(null);\n const [coreState, setCoreState] = useState(null);\n const [isInitializing, setIsInitializing] = useState(true);\n const [pluginsReady, setPluginsReady] = useState(false);\n const initRef = useRef(onInitialized);\n useEffect(() => {\n initRef.current = onInitialized;\n }, [onInitialized]);\n useEffect(() => {\n const finalConfig = {\n ...config,\n logger: (config == null ? void 0 : config.logger) ?? logger\n };\n const pdfViewer = new PluginRegistry(engine, finalConfig);\n pdfViewer.registerPluginBatch(plugins);\n const initialize = async () => {\n var _a;\n await pdfViewer.initialize();\n if (pdfViewer.isDestroyed()) {\n return;\n }\n const store = pdfViewer.getStore();\n setCoreState(store.getState().core);\n const unsubscribe = store.subscribe((action, newState, oldState) => {\n if (store.isCoreAction(action) && newState.core !== oldState.core) {\n setCoreState(newState.core);\n }\n });\n await ((_a = initRef.current) == null ? void 0 : _a.call(initRef, pdfViewer));\n if (pdfViewer.isDestroyed()) {\n unsubscribe();\n return;\n }\n pdfViewer.pluginsReady().then(() => {\n if (!pdfViewer.isDestroyed()) {\n setPluginsReady(true);\n }\n });\n setRegistry(pdfViewer);\n setIsInitializing(false);\n return unsubscribe;\n };\n let cleanup;\n initialize().then((unsub) => {\n cleanup = unsub;\n }).catch(console.error);\n return () => {\n cleanup == null ? void 0 : cleanup();\n pdfViewer.destroy();\n setRegistry(null);\n setCoreState(null);\n setIsInitializing(true);\n setPluginsReady(false);\n };\n }, [engine, plugins]);\n const contextValue = useMemo(() => {\n const activeDocumentId = (coreState == null ? void 0 : coreState.activeDocumentId) ?? null;\n const documents = (coreState == null ? void 0 : coreState.documents) ?? {};\n const documentOrder = (coreState == null ? void 0 : coreState.documentOrder) ?? [];\n const activeDocument = activeDocumentId && documents[activeDocumentId] ? documents[activeDocumentId] : null;\n const documentStates = documentOrder.map((docId) => documents[docId]).filter((doc) => doc !== null && doc !== void 0);\n return {\n registry,\n coreState,\n isInitializing,\n pluginsReady,\n // Convenience accessors (always safe to use)\n activeDocumentId,\n activeDocument,\n documents,\n documentStates\n };\n }, [registry, coreState, isInitializing, pluginsReady]);\n const content = typeof children === \"function\" ? children(contextValue) : children;\n return /* @__PURE__ */ jsx(PDFContext.Provider, { value: contextValue, children: pluginsReady && autoMountDomElements ? /* @__PURE__ */ jsx(AutoMount, { plugins, children: content }) : content });\n}\nfunction useRegistry() {\n const contextValue = useContext(PDFContext);\n if (contextValue === void 0) {\n throw new Error(\"useCapability must be used within a PDFContext.Provider\");\n }\n const { registry, isInitializing } = contextValue;\n if (isInitializing) {\n return contextValue;\n }\n if (registry === null) {\n throw new Error(\"PDF registry failed to initialize properly\");\n }\n return contextValue;\n}\nfunction usePlugin(pluginId) {\n const { registry } = useRegistry();\n if (registry === null) {\n return {\n plugin: null,\n isLoading: true,\n ready: new Promise(() => {\n })\n };\n }\n const plugin = registry.getPlugin(pluginId);\n if (!plugin) {\n throw new Error(`Plugin ${pluginId} not found`);\n }\n return {\n plugin,\n isLoading: false,\n ready: plugin.ready()\n };\n}\nfunction useCapability(pluginId) {\n const { plugin, isLoading, ready } = usePlugin(pluginId);\n if (!plugin) {\n return {\n provides: null,\n isLoading,\n ready\n };\n }\n if (!plugin.provides) {\n throw new Error(`Plugin ${pluginId} does not provide a capability`);\n }\n return {\n provides: plugin.provides(),\n isLoading,\n ready\n };\n}\nfunction useStoreState() {\n const { registry } = useRegistry();\n const [state, setState] = useState(null);\n useEffect(() => {\n if (!registry) return;\n setState(registry.getStore().getState());\n const unsubscribe = registry.getStore().subscribe((_action, newState) => {\n setState(newState);\n });\n return () => unsubscribe();\n }, [registry]);\n return state;\n}\nfunction useCoreState() {\n const { coreState } = useContext(PDFContext);\n return coreState;\n}\nfunction useDocumentState(documentId) {\n const coreState = useCoreState();\n const documentState = useMemo(() => {\n if (!coreState || !documentId) return null;\n return coreState.documents[documentId] ?? null;\n }, [coreState, documentId]);\n return documentState;\n}\n({\n print: PdfPermissionFlag.Print,\n modifyContents: PdfPermissionFlag.ModifyContents,\n copyContents: PdfPermissionFlag.CopyContents,\n modifyAnnotations: PdfPermissionFlag.ModifyAnnotations,\n fillForms: PdfPermissionFlag.FillForms,\n extractForAccessibility: PdfPermissionFlag.ExtractForAccessibility,\n assembleDocument: PdfPermissionFlag.AssembleDocument,\n printHighQuality: PdfPermissionFlag.PrintHighQuality\n});\nconst ALL_PERMISSION_FLAGS = [\n PdfPermissionFlag.Print,\n PdfPermissionFlag.ModifyContents,\n PdfPermissionFlag.CopyContents,\n PdfPermissionFlag.ModifyAnnotations,\n PdfPermissionFlag.FillForms,\n PdfPermissionFlag.ExtractForAccessibility,\n PdfPermissionFlag.AssembleDocument,\n PdfPermissionFlag.PrintHighQuality\n];\nconst PERMISSION_FLAG_TO_NAME = {\n [PdfPermissionFlag.Print]: \"print\",\n [PdfPermissionFlag.ModifyContents]: \"modifyContents\",\n [PdfPermissionFlag.CopyContents]: \"copyContents\",\n [PdfPermissionFlag.ModifyAnnotations]: \"modifyAnnotations\",\n [PdfPermissionFlag.FillForms]: \"fillForms\",\n [PdfPermissionFlag.ExtractForAccessibility]: \"extractForAccessibility\",\n [PdfPermissionFlag.AssembleDocument]: \"assembleDocument\",\n [PdfPermissionFlag.PrintHighQuality]: \"printHighQuality\"\n};\nfunction getPermissionOverride(overrides, flag) {\n if (!overrides) return void 0;\n if (flag in overrides) {\n return overrides[flag];\n }\n const name = PERMISSION_FLAG_TO_NAME[flag];\n if (name && name in overrides) {\n return overrides[name];\n }\n return void 0;\n}\nfunction getEffectivePermission(state, documentId, flag) {\n var _a;\n const docState = state.documents[documentId];\n const docConfig = docState == null ? void 0 : docState.permissions;\n const globalConfig = state.globalPermissions;\n const pdfPermissions = ((_a = docState == null ? void 0 : docState.document) == null ? void 0 : _a.permissions) ?? PdfPermissionFlag.AllowAll;\n const docOverride = getPermissionOverride(docConfig == null ? void 0 : docConfig.overrides, flag);\n if (docOverride !== void 0) {\n return docOverride;\n }\n const globalOverride = getPermissionOverride(globalConfig == null ? void 0 : globalConfig.overrides, flag);\n if (globalOverride !== void 0) {\n return globalOverride;\n }\n const enforce = (docConfig == null ? void 0 : docConfig.enforceDocumentPermissions) ?? (globalConfig == null ? void 0 : globalConfig.enforceDocumentPermissions) ?? true;\n if (!enforce) return true;\n return (pdfPermissions & flag) !== 0;\n}\nfunction getEffectivePermissions(state, documentId) {\n return ALL_PERMISSION_FLAGS.reduce((acc, flag) => {\n return getEffectivePermission(state, documentId, flag) ? acc | flag : acc;\n }, 0);\n}\nfunction useDocumentPermissions(documentId) {\n const coreState = useCoreState();\n return useMemo(() => {\n var _a, _b;\n if (!coreState) {\n return {\n permissions: PdfPermissionFlag.AllowAll,\n pdfPermissions: PdfPermissionFlag.AllowAll,\n hasPermission: () => true,\n hasAllPermissions: () => true,\n canPrint: true,\n canModifyContents: true,\n canCopyContents: true,\n canModifyAnnotations: true,\n canFillForms: true,\n canExtractForAccessibility: true,\n canAssembleDocument: true,\n canPrintHighQuality: true\n };\n }\n const effectivePermissions = getEffectivePermissions(coreState, documentId);\n const pdfPermissions = ((_b = (_a = coreState.documents[documentId]) == null ? void 0 : _a.document) == null ? void 0 : _b.permissions) ?? PdfPermissionFlag.AllowAll;\n const hasPermission = (flag) => getEffectivePermission(coreState, documentId, flag);\n const hasAllPermissions = (...flags) => flags.every((flag) => getEffectivePermission(coreState, documentId, flag));\n return {\n permissions: effectivePermissions,\n pdfPermissions,\n hasPermission,\n hasAllPermissions,\n // All permission flags as booleans (using effective permissions)\n canPrint: hasPermission(PdfPermissionFlag.Print),\n canModifyContents: hasPermission(PdfPermissionFlag.ModifyContents),\n canCopyContents: hasPermission(PdfPermissionFlag.CopyContents),\n canModifyAnnotations: hasPermission(PdfPermissionFlag.ModifyAnnotations),\n canFillForms: hasPermission(PdfPermissionFlag.FillForms),\n canExtractForAccessibility: hasPermission(PdfPermissionFlag.ExtractForAccessibility),\n canAssembleDocument: hasPermission(PdfPermissionFlag.AssembleDocument),\n canPrintHighQuality: hasPermission(PdfPermissionFlag.PrintHighQuality)\n };\n }, [coreState, documentId]);\n}\nexport {\n EmbedPDF,\n PDFContext,\n useCapability,\n useCoreState,\n useDocumentPermissions,\n useDocumentState,\n usePlugin,\n useRegistry,\n useStoreState\n};\n//# sourceMappingURL=index.js.map\n","import { useState, useRef, useEffect, createContext, useContext } from \"react\";\nimport { ignore } from \"@embedpdf/models\";\nimport { jsx } from \"react/jsx-runtime\";\nconst defaultWasmUrl = `https://cdn.jsdelivr.net/npm/@embedpdf/pdfium@2.15.1/dist/pdfium.wasm`;\nfunction usePdfiumEngine(config) {\n const {\n wasmUrl = defaultWasmUrl,\n worker = true,\n logger,\n encoderPoolSize,\n fontFallback\n } = config ?? {};\n const [engine, setEngine] = useState(null);\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState(null);\n const engineRef = useRef(null);\n useEffect(() => {\n let cancelled = false;\n (async () => {\n try {\n const { createPdfiumEngine } = worker ? await import(\"@embedpdf/engines/pdfium-worker-engine\") : await import(\"@embedpdf/engines/pdfium-direct-engine\");\n const pdfEngine = await createPdfiumEngine(wasmUrl, {\n logger,\n encoderPoolSize,\n fontFallback\n });\n engineRef.current = pdfEngine;\n setEngine(pdfEngine);\n setLoading(false);\n } catch (e) {\n if (!cancelled) {\n setError(e);\n setLoading(false);\n }\n }\n })();\n return () => {\n var _a, _b;\n cancelled = true;\n (_b = (_a = engineRef.current) == null ? void 0 : _a.closeAllDocuments) == null ? void 0 : _b.call(_a).wait(() => {\n var _a2, _b2;\n (_b2 = (_a2 = engineRef.current) == null ? void 0 : _a2.destroy) == null ? void 0 : _b2.call(_a2);\n engineRef.current = null;\n }, ignore);\n };\n }, [wasmUrl, worker, logger, fontFallback]);\n return { engine, isLoading: loading, error };\n}\nconst PdfEngineContext = createContext(void 0);\nfunction useEngineContext() {\n const contextValue = useContext(PdfEngineContext);\n if (contextValue === void 0) {\n throw new Error(\"useEngineContext must be used within a PdfEngineProvider\");\n }\n return contextValue;\n}\nfunction useEngine() {\n const { engine, error } = useEngineContext();\n if (error) {\n throw error;\n }\n return engine;\n}\nfunction PdfEngineProvider({ children, engine, isLoading, error }) {\n const contextValue = {\n engine,\n isLoading,\n error\n };\n return /* @__PURE__ */ jsx(PdfEngineContext.Provider, { value: contextValue, children });\n}\nexport {\n PdfEngineProvider,\n useEngine,\n useEngineContext,\n usePdfiumEngine\n};\n//# sourceMappingURL=index.js.map\n","import { BasePlugin, createBehaviorEmitter, createEmitter, reorderDocuments, moveDocument, setActiveDocument, startLoadingDocument, retryLoadingDocument, closeDocument, updateDocumentSecurity, setDocumentLoaded, setDocumentError } from \"@embedpdf/core\";\nimport { Task, PdfErrorCode } from \"@embedpdf/models\";\nconst _DocumentManagerPlugin = class _DocumentManagerPlugin extends BasePlugin {\n constructor(id, registry, config) {\n super(id, registry);\n this.id = id;\n this.documentOpened$ = createBehaviorEmitter();\n this.documentClosed$ = createBehaviorEmitter();\n this.activeDocumentChanged$ = createBehaviorEmitter();\n this.documentError$ = createBehaviorEmitter();\n this.documentOrderChanged$ = createBehaviorEmitter();\n this.openFileRequest$ = createEmitter();\n this.loadOptions = /* @__PURE__ */ new Map();\n this.maxDocuments = config == null ? void 0 : config.maxDocuments;\n }\n buildCapability() {\n return {\n // Document lifecycle - orchestration only\n openFileDialog: (options) => this.openFileDialog(options),\n openDocumentUrl: (options) => this.openDocumentUrl(options),\n openDocumentBuffer: (options) => this.openDocumentBuffer(options),\n retryDocument: (documentId, options) => this.retryDocument(documentId, options),\n closeDocument: (documentId) => this.closeDocument(documentId),\n closeAllDocuments: () => this.closeAllDocuments(),\n setActiveDocument: (documentId) => {\n if (!this.isDocumentOpen(documentId)) {\n throw new Error(`Cannot set active document: ${documentId} is not open`);\n }\n this.dispatchCoreAction(setActiveDocument(documentId));\n },\n getActiveDocumentId: () => this.coreState.core.activeDocumentId,\n getActiveDocument: () => {\n var _a;\n const activeId = this.coreState.core.activeDocumentId;\n if (!activeId) return null;\n return ((_a = this.coreState.core.documents[activeId]) == null ? void 0 : _a.document) ?? null;\n },\n getDocumentOrder: () => this.coreState.core.documentOrder,\n moveDocument: (documentId, toIndex) => {\n this.dispatchCoreAction(moveDocument(documentId, toIndex));\n },\n swapDocuments: (id1, id2) => {\n const order = this.coreState.core.documentOrder;\n const index1 = order.indexOf(id1);\n const index2 = order.indexOf(id2);\n if (index1 === -1 || index2 === -1) {\n throw new Error(\"One or both documents not found in order\");\n }\n const newOrder = [...order];\n [newOrder[index1], newOrder[index2]] = [newOrder[index2], newOrder[index1]];\n this.dispatchCoreAction(reorderDocuments(newOrder));\n },\n getDocument: (documentId) => {\n var _a;\n return ((_a = this.coreState.core.documents[documentId]) == null ? void 0 : _a.document) ?? null;\n },\n getDocumentState: (documentId) => {\n return this.coreState.core.documents[documentId] ?? null;\n },\n getOpenDocuments: () => {\n return this.coreState.core.documentOrder.map((documentId) => this.coreState.core.documents[documentId]).filter((state) => state !== null);\n },\n isDocumentOpen: (documentId) => this.isDocumentOpen(documentId),\n getDocumentCount: () => {\n return Object.keys(this.coreState.core.documents).length;\n },\n getDocumentIndex: (documentId) => {\n return this.coreState.core.documentOrder.indexOf(documentId);\n },\n // Security\n setDocumentEncryption: (documentId, options) => this.setDocumentEncryption(documentId, options),\n unlockOwnerPermissions: (documentId, ownerPassword) => this.unlockOwnerPermissions(documentId, ownerPassword),\n removeEncryption: (documentId) => this.removeEncryption(documentId),\n // Events\n onDocumentOpened: this.documentOpened$.on,\n onDocumentClosed: this.documentClosed$.on,\n onDocumentError: this.documentError$.on,\n onActiveDocumentChanged: this.activeDocumentChanged$.on,\n onDocumentOrderChanged: this.documentOrderChanged$.on\n };\n }\n /**\n * Check if a document is currently open\n */\n isDocumentOpen(documentId) {\n return !!this.coreState.core.documents[documentId];\n }\n // ─────────────────────────────────────────────────────────\n // Document Lifecycle Hooks (from BasePlugin)\n // ─────────────────────────────────────────────────────────\n onDocumentLoaded(documentId) {\n const docState = this.coreState.core.documents[documentId];\n if (!docState || docState.status !== \"loaded\") return;\n this.loadOptions.delete(documentId);\n this.documentOpened$.emit(docState);\n this.logger.info(\n \"DocumentManagerPlugin\",\n \"DocumentOpened\",\n `Document ${documentId} opened successfully`,\n { name: docState.name }\n );\n }\n onDocumentClosed(documentId) {\n this.loadOptions.delete(documentId);\n this.documentClosed$.emit(documentId);\n this.logger.info(\"DocumentManagerPlugin\", \"DocumentClosed\", `Document ${documentId} closed`);\n }\n onActiveDocumentChanged(previousId, currentId) {\n this.activeDocumentChanged$.emit({\n previousDocumentId: previousId,\n currentDocumentId: currentId\n });\n this.logger.info(\n \"DocumentManagerPlugin\",\n \"ActiveDocumentChanged\",\n `Active document changed from ${previousId} to ${currentId}`\n );\n }\n onCoreStoreUpdated(oldState, newState) {\n if (oldState.core.documentOrder !== newState.core.documentOrder) {\n this.documentOrderChanged$.emit({\n order: newState.core.documentOrder\n });\n }\n }\n onOpenFileRequest(handler) {\n return this.openFileRequest$.on(handler);\n }\n // ─────────────────────────────────────────────────────────\n // Document Loading (orchestration only - no state management)\n // ─────────────────────────────────────────────────────────\n openDocumentUrl(options) {\n const task = new Task();\n const documentId = options.documentId || this.generateDocumentId();\n const limitError = this.checkDocumentLimit();\n if (limitError) {\n task.reject(limitError);\n return task;\n }\n const documentName = options.name ?? this.extractNameFromUrl(options.url);\n this.loadOptions.set(documentId, options);\n this.dispatchCoreAction(\n startLoadingDocument(\n documentId,\n documentName,\n options.scale,\n options.rotation,\n !!options.password,\n options.autoActivate,\n options.permissions\n )\n );\n this.logger.info(\n \"DocumentManagerPlugin\",\n \"OpenDocumentUrl\",\n `Starting to load document from URL: ${options.url}`,\n { documentId, passwordProvided: !!options.password }\n );\n const file = {\n id: documentId,\n url: options.url\n };\n const engineTask = this.engine.openDocumentUrl(file, {\n password: options.password,\n mode: options.mode,\n requestOptions: options.requestOptions,\n normalizeRotation: true\n });\n task.resolve({\n documentId,\n task: engineTask\n });\n this.handleLoadTask(documentId, engineTask, \"OpenDocumentUrl\");\n return task;\n }\n openDocumentBuffer(options) {\n const task = new Task();\n const limitError = this.checkDocumentLimit();\n if (limitError) {\n task.reject(limitError);\n return task;\n }\n const documentId = options.documentId || this.generateDocumentId();\n this.loadOptions.set(documentId, options);\n this.dispatchCoreAction(\n startLoadingDocument(\n documentId,\n options.name,\n options.scale,\n options.rotation,\n !!options.password,\n options.autoActivate,\n options.permissions\n )\n );\n this.logger.info(\n \"DocumentManagerPlugin\",\n \"OpenDocumentBuffer\",\n `Starting to load document from buffer: ${options.name}`,\n { documentId, passwordProvided: !!options.password }\n );\n const file = {\n id: documentId,\n content: options.buffer\n };\n const engineTask = this.engine.openDocumentBuffer(file, {\n password: options.password,\n normalizeRotation: true\n });\n task.resolve({\n documentId,\n task: engineTask\n });\n this.handleLoadTask(documentId, engineTask, \"OpenDocumentBuffer\");\n return task;\n }\n retryDocument(documentId, retryOptions) {\n const task = new Task();\n const validation = this.validateRetry(documentId);\n if (!validation.valid) {\n task.reject(validation.error);\n return task;\n }\n const originalOptions = this.loadOptions.get(documentId);\n const mergedOptions = {\n ...originalOptions,\n ...(retryOptions == null ? void 0 : retryOptions.password) && { password: retryOptions.password }\n };\n this.loadOptions.set(documentId, mergedOptions);\n this.dispatchCoreAction(retryLoadingDocument(documentId, !!(retryOptions == null ? void 0 : retryOptions.password)));\n this.logger.info(\n \"DocumentManagerPlugin\",\n \"RetryDocument\",\n `Retrying to load document ${documentId}`,\n { passwordProvided: !!(retryOptions == null ? void 0 : retryOptions.password) }\n );\n const engineTask = \"url\" in mergedOptions ? this.retryUrlDocument(documentId, mergedOptions) : this.retryBufferDocument(documentId, mergedOptions);\n task.resolve({\n documentId,\n task: engineTask\n });\n this.handleLoadTask(documentId, engineTask, \"RetryDocument\");\n return task;\n }\n openFileDialog(options) {\n const task = new Task();\n this.openFileRequest$.emit({ task, options });\n return task;\n }\n closeDocument(documentId) {\n const task = new Task();\n const docState = this.coreState.core.documents[documentId];\n if (!docState) {\n this.logger.warn(\n \"DocumentManagerPlugin\",\n \"CloseDocument\",\n `Cannot close document ${documentId}: not found in state`\n );\n task.resolve();\n return task;\n }\n if (docState.status === \"loaded\" && docState.document) {\n this.engine.closeDocument(docState.document).wait(\n () => {\n this.dispatchCoreAction(closeDocument(documentId));\n task.resolve();\n },\n (error) => {\n this.logger.error(\n \"DocumentManagerPlugin\",\n \"CloseDocument\",\n `Failed to close document ${documentId}`,\n error\n );\n task.fail(error);\n }\n );\n } else {\n this.logger.info(\n \"DocumentManagerPlugin\",\n \"CloseDocument\",\n `Closing document ${documentId} in ${docState.status} state (skipping engine close)`\n );\n this.dispatchCoreAction(closeDocument(documentId));\n task.resolve();\n }\n return task;\n }\n closeAllDocuments() {\n const documentIds = Object.keys(this.coreState.core.documents);\n const tasks = documentIds.map((documentId) => this.closeDocument(documentId));\n this.logger.info(\n \"DocumentManagerPlugin\",\n \"CloseAllDocuments\",\n `Closing ${documentIds.length} documents`\n );\n return Task.all(tasks);\n }\n // ─────────────────────────────────────────────────────────\n // Security Methods\n // ─────────────────────────────────────────────────────────\n setDocumentEncryption(documentId, options) {\n const task = new Task();\n const docState = this.coreState.core.documents[documentId];\n if (!(docState == null ? void 0 : docState.document)) {\n task.reject({\n code: PdfErrorCode.DocNotOpen,\n message: `Document ${documentId} is not open`\n });\n return task;\n }\n this.logger.info(\n \"DocumentManagerPlugin\",\n \"SetDocumentEncryption\",\n `Setting encryption on document ${documentId}`,\n { hasUserPassword: !!options.userPassword, allowedFlags: options.allowedFlags }\n );\n const engineTask = this.engine.setDocumentEncryption(\n docState.document,\n options.userPassword ?? \"\",\n options.ownerPassword,\n options.allowedFlags\n );\n engineTask.wait(\n (success) => {\n if (success) {\n this.logger.info(\n \"DocumentManagerPlugin\",\n \"SetDocumentEncryption\",\n `Encryption set successfully on document ${documentId}`\n );\n }\n task.resolve(success);\n },\n (error) => {\n this.logger.error(\n \"DocumentManagerPlugin\",\n \"SetDocumentEncryption\",\n `Failed to set encryption on document ${documentId}`,\n error\n );\n task.fail(error);\n }\n );\n return task;\n }\n unlockOwnerPermissions(documentId, ownerPassword) {\n const task = new Task();\n const docState = this.coreState.core.documents[documentId];\n if (!(docState == null ? void 0 : docState.document)) {\n task.reject({\n code: PdfErrorCode.DocNotOpen,\n message: `Document ${documentId} is not open`\n });\n return task;\n }\n const document = docState.document;\n this.logger.info(\n \"DocumentManagerPlugin\",\n \"UnlockOwnerPermissions\",\n `Attempting to unlock owner permissions on document ${documentId}`\n );\n const engineTask = this.engine.unlockOwnerPermissions(document, ownerPassword);\n engineTask.wait(\n (success) => {\n if (success) {\n this.logger.info(\n \"DocumentManagerPlugin\",\n \"UnlockOwnerPermissions\",\n `Owner permissions unlocked on document ${documentId}`\n );\n const fullPermissions = 4294967295;\n this.dispatchCoreAction(updateDocumentSecurity(documentId, fullPermissions, true));\n }\n task.resolve(success);\n },\n (error) => {\n this.logger.error(\n \"DocumentManagerPlugin\",\n \"UnlockOwnerPermissions\",\n `Failed to unlock owner permissions on document ${documentId}`,\n error\n );\n task.fail(error);\n }\n );\n return task;\n }\n removeEncryption(documentId) {\n const task = new Task();\n const docState = this.coreState.core.documents[documentId];\n if (!(docState == null ? void 0 : docState.document)) {\n task.reject({\n code: PdfErrorCode.DocNotOpen,\n message: `Document ${documentId} is not open`\n });\n return task;\n }\n this.logger.info(\n \"DocumentManagerPlugin\",\n \"RemoveEncryption\",\n `Marking document ${documentId} for encryption removal on save`\n );\n const engineTask = this.engine.removeEncryption(docState.document);\n engineTask.wait(\n (success) => {\n if (success) {\n this.logger.info(\n \"DocumentManagerPlugin\",\n \"RemoveEncryption\",\n `Document ${documentId} marked for encryption removal`\n );\n }\n task.resolve(success);\n },\n (error) => {\n this.logger.error(\n \"DocumentManagerPlugin\",\n \"RemoveEncryption\",\n `Failed to mark document ${documentId} for encryption removal`,\n error\n );\n task.fail(error);\n }\n );\n return task;\n }\n // ─────────────────────────────────────────────────────────\n // Helper Methods\n // ─────────────────────────────────────────────────────────\n checkDocumentLimit() {\n if (this.maxDocuments && Object.keys(this.coreState.core.documents).length >= this.maxDocuments) {\n return {\n code: PdfErrorCode.Unknown,\n message: `Maximum number of documents (${this.maxDocuments}) reached`\n };\n }\n return null;\n }\n validateRetry(documentId) {\n const docState = this.coreState.core.documents[documentId];\n if (!docState) {\n return {\n valid: false,\n error: {\n code: PdfErrorCode.NotFound,\n message: `Document ${documentId} not found`\n }\n };\n }\n if (docState.status === \"loaded\") {\n return {\n valid: false,\n error: {\n code: PdfErrorCode.Unknown,\n message: `Document ${documentId} is already loaded successfully`\n }\n };\n }\n if (docState.status !== \"error\") {\n return {\n valid: false,\n error: {\n code: PdfErrorCode.Unknown,\n message: `Document ${documentId} is not in error state (current state: ${docState.status})`\n }\n };\n }\n if (!this.loadOptions.has(documentId)) {\n return {\n valid: false,\n error: {\n code: PdfErrorCode.Unknown,\n message: `No retry information available for document ${documentId}`\n }\n };\n }\n return { valid: true };\n }\n retryUrlDocument(documentId, options) {\n const file = {\n id: documentId,\n url: options.url\n };\n return this.engine.openDocumentUrl(file, {\n password: options.password,\n mode: options.mode,\n requestOptions: options.requestOptions\n });\n }\n retryBufferDocument(documentId, options) {\n const file = {\n id: documentId,\n content: options.buffer\n };\n return this.engine.openDocumentBuffer(file, {\n password: options.password,\n normalizeRotation: true\n });\n }\n handleLoadTask(documentId, engineTask, context) {\n engineTask.wait(\n (pdfDocument) => {\n this.dispatchCoreAction(setDocumentLoaded(documentId, pdfDocument));\n },\n (error) => {\n this.handleLoadError(documentId, error, context);\n }\n );\n }\n handleLoadError(documentId, error, context) {\n var _a, _b, _c;\n const errorMessage = ((_a = error.reason) == null ? void 0 : _a.message) || \"Failed to load document\";\n this.logger.error(\"DocumentManagerPlugin\", context, \"Failed to load document\", error);\n this.dispatchCoreAction(\n setDocumentError(documentId, errorMessage, (_b = error.reason) == null ? void 0 : _b.code, error.reason)\n );\n this.documentError$.emit({\n documentId,\n message: errorMessage,\n code: (_c = error.reason) == null ? void 0 : _c.code,\n reason: error.reason\n });\n }\n generateDocumentId() {\n return `doc-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n }\n extractNameFromUrl(url) {\n try {\n const urlObj = new URL(url);\n const pathname = urlObj.pathname;\n const lastSegment = pathname.split(\"/\").pop();\n if (!lastSegment) {\n return void 0;\n }\n let filename = decodeURIComponent(lastSegment);\n if (!filename.toLowerCase().endsWith(\".pdf\")) {\n filename += \".pdf\";\n }\n return filename;\n } catch {\n return void 0;\n }\n }\n // ─────────────────────────────────────────────────────────\n // Plugin Lifecycle\n // ─────────────────────────────────────────────────────────\n async initialize(config) {\n var _a;\n this.logger.info(\"DocumentManagerPlugin\", \"Initialize\", \"Document Manager Plugin initialized\", {\n maxDocuments: this.maxDocuments,\n initialDocumentsCount: ((_a = config.initialDocuments) == null ? void 0 : _a.length) ?? 0\n });\n if (config.initialDocuments && config.initialDocuments.length > 0) {\n for (const docConfig of config.initialDocuments) {\n try {\n if (\"buffer\" in docConfig) {\n this.openDocumentBuffer(docConfig);\n } else if (\"url\" in docConfig) {\n this.openDocumentUrl(docConfig);\n }\n } catch (error) {\n this.logger.error(\n \"DocumentManagerPlugin\",\n \"Initialize\",\n \"Failed to initiate initial document load\",\n error\n );\n }\n }\n }\n }\n async destroy() {\n await this.closeAllDocuments().toPromise();\n this.loadOptions.clear();\n this.documentOpened$.clear();\n this.documentClosed$.clear();\n this.activeDocumentChanged$.clear();\n this.documentOrderChanged$.clear();\n this.documentError$.clear();\n super.destroy();\n }\n};\n_DocumentManagerPlugin.id = \"document-manager\";\nlet DocumentManagerPlugin = _DocumentManagerPlugin;\nconst DOCUMENT_MANAGER_PLUGIN_ID = \"document-manager\";\nconst manifest = {\n id: DOCUMENT_MANAGER_PLUGIN_ID,\n name: \"Document Manager Plugin\",\n version: \"1.0.0\",\n provides: [\"document-manager\"],\n requires: [],\n optional: [],\n defaultConfig: {\n maxDocuments: 10\n }\n};\nconst DocumentManagerPluginPackage = {\n manifest,\n create: (registry, config) => new DocumentManagerPlugin(DOCUMENT_MANAGER_PLUGIN_ID, registry, config),\n reducer: (state) => state,\n initialState: {}\n};\nexport {\n DOCUMENT_MANAGER_PLUGIN_ID,\n DocumentManagerPlugin,\n DocumentManagerPluginPackage,\n manifest\n};\n//# sourceMappingURL=index.js.map\n","import { createPluginPackage } from \"@embedpdf/core\";\nimport { DocumentManagerPlugin, DocumentManagerPluginPackage as DocumentManagerPluginPackage$1 } from \"@embedpdf/plugin-document-manager\";\nexport * from \"@embedpdf/plugin-document-manager\";\nimport { jsx, Fragment } from \"react/jsx-runtime\";\nimport { useDocumentState, usePlugin, useCapability, useCoreState } from \"@embedpdf/core/react\";\nimport { useMemo, useCallback, useRef, useEffect } from \"react\";\nfunction DocumentContent({ documentId, children }) {\n const documentState = useDocumentState(documentId);\n if (!documentState) return null;\n const isLoading = documentState.status === \"loading\";\n const isError = documentState.status === \"error\";\n const isLoaded = documentState.status === \"loaded\";\n return /* @__PURE__ */ jsx(Fragment, { children: children({ documentState, isLoading, isError, isLoaded }) });\n}\nconst useDocumentManagerPlugin = () => usePlugin(DocumentManagerPlugin.id);\nconst useDocumentManagerCapability = () => useCapability(DocumentManagerPlugin.id);\nconst useActiveDocument = () => {\n const coreState = useCoreState();\n return useMemo(() => {\n if (!coreState) {\n return {\n activeDocumentId: null,\n activeDocument: null\n };\n }\n const activeDocumentId = coreState.activeDocumentId;\n const activeDocument = activeDocumentId ? coreState.documents[activeDocumentId] ?? null : null;\n return {\n activeDocumentId,\n activeDocument\n };\n }, [coreState]);\n};\nconst useOpenDocuments = (documentIds) => {\n const coreState = useCoreState();\n return useMemo(() => {\n if (!coreState) return [];\n if (documentIds) {\n return documentIds.map((docId) => coreState.documents[docId]).filter((doc) => doc !== null && doc !== void 0);\n }\n return coreState.documentOrder.map((docId) => coreState.documents[docId]).filter((doc) => doc !== null && doc !== void 0);\n }, [coreState, documentIds]);\n};\nfunction DocumentContext({ children }) {\n const documentStates = useOpenDocuments();\n const { activeDocumentId } = useActiveDocument();\n const { provides } = useDocumentManagerCapability();\n const select = useCallback(\n (documentId) => {\n provides == null ? void 0 : provides.setActiveDocument(documentId);\n },\n [provides]\n );\n const close = useCallback(\n (documentId) => {\n provides == null ? void 0 : provides.closeDocument(documentId);\n },\n [provides]\n );\n const move = useCallback(\n (documentId, toIndex) => {\n provides == null ? void 0 : provides.moveDocument(documentId, toIndex);\n },\n [provides]\n );\n const actions = {\n select,\n close,\n move\n };\n return /* @__PURE__ */ jsx(Fragment, { children: children({ documentStates, activeDocumentId, actions }) });\n}\nfunction FilePicker() {\n const { plugin } = useDocumentManagerPlugin();\n const { provides } = useDocumentManagerCapability();\n const inputRef = useRef(null);\n const taskRef = useRef(null);\n const optionsRef = useRef(void 0);\n useEffect(() => {\n if (!(plugin == null ? void 0 : plugin.onOpenFileRequest)) return;\n const unsub = plugin.onOpenFileRequest(({ task, options }) => {\n var _a;\n taskRef.current = task;\n optionsRef.current = options;\n (_a = inputRef.current) == null ? void 0 : _a.click();\n });\n return unsub;\n }, [plugin]);\n const onChange = async (e) => {\n var _a, _b, _c, _d, _e;\n const file = (_a = e.currentTarget.files) == null ? void 0 : _a[0];\n if (!file || !provides) return;\n const buffer = await file.arrayBuffer();\n const openTask = provides.openDocumentBuffer({\n name: file.name,\n buffer,\n documentId: (_b = optionsRef.current) == null ? void 0 : _b.documentId,\n scale: (_c = optionsRef.current) == null ? void 0 : _c.scale,\n rotation: (_d = optionsRef.current) == null ? void 0 : _d.rotation,\n autoActivate: (_e = optionsRef.current) == null ? void 0 : _e.autoActivate\n });\n openTask.wait(\n (result) => {\n var _a2;\n (_a2 = taskRef.current) == null ? void 0 : _a2.resolve(result);\n },\n (error) => {\n var _a2;\n (_a2 = taskRef.current) == null ? void 0 : _a2.fail(error);\n }\n );\n };\n return /* @__PURE__ */ jsx(\n \"input\",\n {\n ref: inputRef,\n type: \"file\",\n accept: \"application/pdf\",\n style: { display: \"none\" },\n onChange\n }\n );\n}\nconst DocumentManagerPluginPackage = createPluginPackage(DocumentManagerPluginPackage$1).addUtility(FilePicker).build();\nexport {\n DocumentContent,\n DocumentContext,\n DocumentManagerPluginPackage,\n FilePicker,\n useActiveDocument,\n useDocumentManagerCapability,\n useDocumentManagerPlugin,\n useOpenDocuments\n};\n//# sourceMappingURL=index.js.map\n","import { BasePlugin, createBehaviorEmitter, createEmitter } from \"@embedpdf/core\";\nconst VIEWPORT_PLUGIN_ID = \"viewport\";\nconst manifest = {\n id: VIEWPORT_PLUGIN_ID,\n name: \"Viewport Plugin\",\n version: \"1.0.0\",\n provides: [\"viewport\"],\n requires: [],\n optional: [],\n defaultConfig: {\n viewportGap: 10,\n scrollEndDelay: 300\n }\n};\nconst INIT_VIEWPORT_STATE = \"INIT_VIEWPORT_STATE\";\nconst CLEANUP_VIEWPORT_STATE = \"CLEANUP_VIEWPORT_STATE\";\nconst REGISTER_VIEWPORT = \"REGISTER_VIEWPORT\";\nconst UNREGISTER_VIEWPORT = \"UNREGISTER_VIEWPORT\";\nconst SET_VIEWPORT_METRICS = \"SET_VIEWPORT_METRICS\";\nconst SET_VIEWPORT_SCROLL_METRICS = \"SET_VIEWPORT_SCROLL_METRICS\";\nconst SET_VIEWPORT_GAP = \"SET_VIEWPORT_GAP\";\nconst SET_SCROLL_ACTIVITY = \"SET_SCROLL_ACTIVITY\";\nconst SET_SMOOTH_SCROLL_ACTIVITY = \"SET_SMOOTH_SCROLL_ACTIVITY\";\nconst SET_ACTIVE_VIEWPORT_DOCUMENT = \"SET_ACTIVE_VIEWPORT_DOCUMENT\";\nconst ADD_VIEWPORT_GATE = \"ADD_VIEWPORT_GATE\";\nconst REMOVE_VIEWPORT_GATE = \"REMOVE_VIEWPORT_GATE\";\nfunction initViewportState(documentId) {\n return { type: INIT_VIEWPORT_STATE, payload: { documentId } };\n}\nfunction cleanupViewportState(documentId) {\n return { type: CLEANUP_VIEWPORT_STATE, payload: { documentId } };\n}\nfunction registerViewport(documentId) {\n return { type: REGISTER_VIEWPORT, payload: { documentId } };\n}\nfunction unregisterViewport(documentId) {\n return { type: UNREGISTER_VIEWPORT, payload: { documentId } };\n}\nfunction setViewportGap(viewportGap) {\n return { type: SET_VIEWPORT_GAP, payload: viewportGap };\n}\nfunction setViewportMetrics(documentId, metrics) {\n return { type: SET_VIEWPORT_METRICS, payload: { documentId, metrics } };\n}\nfunction setViewportScrollMetrics(documentId, scrollMetrics) {\n return { type: SET_VIEWPORT_SCROLL_METRICS, payload: { documentId, scrollMetrics } };\n}\nfunction setScrollActivity(documentId, isScrolling) {\n return { type: SET_SCROLL_ACTIVITY, payload: { documentId, isScrolling } };\n}\nfunction setSmoothScrollActivity(documentId, isSmoothScrolling) {\n return { type: SET_SMOOTH_SCROLL_ACTIVITY, payload: { documentId, isSmoothScrolling } };\n}\nfunction addViewportGate(documentId, key) {\n return { type: ADD_VIEWPORT_GATE, payload: { documentId, key } };\n}\nfunction removeViewportGate(documentId, key) {\n return { type: REMOVE_VIEWPORT_GATE, payload: { documentId, key } };\n}\nconst initialViewportDocumentState = {\n viewportMetrics: {\n width: 0,\n height: 0,\n scrollTop: 0,\n scrollLeft: 0,\n clientWidth: 0,\n clientHeight: 0,\n scrollWidth: 0,\n scrollHeight: 0,\n clientLeft: 0,\n clientTop: 0,\n relativePosition: { x: 0, y: 0 }\n },\n isScrolling: false,\n isSmoothScrolling: false,\n gates: /* @__PURE__ */ new Set()\n};\nconst initialState = {\n viewportGap: 0,\n documents: {},\n activeViewports: /* @__PURE__ */ new Set(),\n activeDocumentId: null\n};\nconst viewportReducer = (state = initialState, action) => {\n switch (action.type) {\n // ─────────────────────────────────────────────────────────\n // State Persistence (Document Lifecycle)\n // ─────────────────────────────────────────────────────────\n case INIT_VIEWPORT_STATE: {\n const { documentId } = action.payload;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: { ...initialViewportDocumentState, gates: /* @__PURE__ */ new Set() }\n }\n };\n }\n case CLEANUP_VIEWPORT_STATE: {\n const { documentId } = action.payload;\n const { [documentId]: removed, ...remainingDocs } = state.documents;\n const newActiveViewports = new Set(state.activeViewports);\n newActiveViewports.delete(documentId);\n return {\n ...state,\n documents: remainingDocs,\n activeViewports: newActiveViewports,\n activeDocumentId: state.activeDocumentId === documentId ? null : state.activeDocumentId\n };\n }\n // ─────────────────────────────────────────────────────────\n // Viewport Registration (DOM Lifecycle)\n // ─────────────────────────────────────────────────────────\n case REGISTER_VIEWPORT: {\n const { documentId } = action.payload;\n const newActiveViewports = new Set(state.activeViewports);\n newActiveViewports.add(documentId);\n return {\n ...state,\n activeViewports: newActiveViewports,\n // Set as active if no active document\n activeDocumentId: state.activeDocumentId ?? documentId\n };\n }\n case UNREGISTER_VIEWPORT: {\n const { documentId } = action.payload;\n const newActiveViewports = new Set(state.activeViewports);\n newActiveViewports.delete(documentId);\n return {\n ...state,\n activeViewports: newActiveViewports\n };\n }\n case SET_ACTIVE_VIEWPORT_DOCUMENT: {\n return {\n ...state,\n activeDocumentId: action.payload\n };\n }\n // ─────────────────────────────────────────────────────────\n // Viewport Operations\n // ─────────────────────────────────────────────────────────\n case SET_VIEWPORT_GAP: {\n return {\n ...state,\n viewportGap: action.payload\n };\n }\n case SET_VIEWPORT_METRICS: {\n const { documentId, metrics } = action.payload;\n const viewport = state.documents[documentId];\n if (!viewport) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...viewport,\n viewportMetrics: {\n width: metrics.width,\n height: metrics.height,\n scrollTop: metrics.scrollTop,\n scrollLeft: metrics.scrollLeft,\n clientWidth: metrics.clientWidth,\n clientHeight: metrics.clientHeight,\n scrollWidth: metrics.scrollWidth,\n scrollHeight: metrics.scrollHeight,\n clientLeft: metrics.clientLeft,\n clientTop: metrics.clientTop,\n relativePosition: {\n x: metrics.scrollWidth <= metrics.clientWidth ? 0 : metrics.scrollLeft / (metrics.scrollWidth - metrics.clientWidth),\n y: metrics.scrollHeight <= metrics.clientHeight ? 0 : metrics.scrollTop / (metrics.scrollHeight - metrics.clientHeight)\n }\n }\n }\n }\n };\n }\n case SET_VIEWPORT_SCROLL_METRICS: {\n const { documentId, scrollMetrics } = action.payload;\n const viewport = state.documents[documentId];\n if (!viewport) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...viewport,\n viewportMetrics: {\n ...viewport.viewportMetrics,\n scrollTop: scrollMetrics.scrollTop,\n scrollLeft: scrollMetrics.scrollLeft\n },\n isScrolling: true\n }\n }\n };\n }\n case SET_SCROLL_ACTIVITY: {\n const { documentId, isScrolling } = action.payload;\n const viewport = state.documents[documentId];\n if (!viewport) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...viewport,\n isScrolling\n }\n }\n };\n }\n case SET_SMOOTH_SCROLL_ACTIVITY: {\n const { documentId, isSmoothScrolling } = action.payload;\n const viewport = state.documents[documentId];\n if (!viewport) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...viewport,\n isSmoothScrolling\n }\n }\n };\n }\n // ─────────────────────────────────────────────────────────\n // Named Gate Operations\n // ─────────────────────────────────────────────────────────\n case ADD_VIEWPORT_GATE: {\n const { documentId, key } = action.payload;\n const viewport = state.documents[documentId];\n if (!viewport) return state;\n const newGates = new Set(viewport.gates);\n newGates.add(key);\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...viewport,\n gates: newGates\n }\n }\n };\n }\n case REMOVE_VIEWPORT_GATE: {\n const { documentId, key } = action.payload;\n const viewport = state.documents[documentId];\n if (!viewport) return state;\n const newGates = new Set(viewport.gates);\n newGates.delete(key);\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...viewport,\n gates: newGates\n }\n }\n };\n }\n default:\n return state;\n }\n};\nconst _ViewportPlugin = class _ViewportPlugin extends BasePlugin {\n constructor(id, registry, config) {\n super(id, registry);\n this.id = id;\n this.viewportResize$ = createBehaviorEmitter();\n this.viewportMetrics$ = createBehaviorEmitter();\n this.scrollMetrics$ = createBehaviorEmitter();\n this.scrollActivity$ = createBehaviorEmitter();\n this.gateState$ = createBehaviorEmitter();\n this.scrollRequests$ = /* @__PURE__ */ new Map();\n if (config.viewportGap) {\n this.dispatch(setViewportGap(config.viewportGap));\n }\n this.scrollEndDelay = config.scrollEndDelay || 100;\n }\n // ─────────────────────────────────────────────────────────\n // Document Lifecycle (from BasePlugin)\n // ─────────────────────────────────────────────────────────\n onDocumentLoadingStarted(documentId) {\n this.dispatch(initViewportState(documentId));\n this.scrollRequests$.set(documentId, createEmitter());\n this.logger.debug(\n \"ViewportPlugin\",\n \"DocumentOpened\",\n `Initialized viewport state for document: ${documentId}`\n );\n }\n onDocumentClosed(documentId) {\n var _a;\n this.dispatch(cleanupViewportState(documentId));\n (_a = this.scrollRequests$.get(documentId)) == null ? void 0 : _a.clear();\n this.scrollRequests$.delete(documentId);\n this.logger.debug(\n \"ViewportPlugin\",\n \"DocumentClosed\",\n `Cleaned up viewport state for document: ${documentId}`\n );\n }\n // ─────────────────────────────────────────────────────────\n // Capability\n // ─────────────────────────────────────────────────────────\n buildCapability() {\n return {\n // Global\n getViewportGap: () => this.state.viewportGap,\n // Active document operations\n getMetrics: () => this.getMetrics(),\n scrollTo: (pos) => this.scrollTo(pos),\n isScrolling: () => this.isScrolling(),\n isSmoothScrolling: () => this.isSmoothScrolling(),\n isGated: (documentId) => this.isGated(documentId),\n hasGate: (key, documentId) => this.hasGate(key, documentId),\n getGates: (documentId) => this.getGates(documentId),\n // Document-scoped operations\n forDocument: (documentId) => this.createViewportScope(documentId),\n gate: (key, documentId) => this.gate(key, documentId),\n releaseGate: (key, documentId) => this.releaseGate(key, documentId),\n // Check if viewport is currently mounted\n isViewportMounted: (documentId) => this.state.activeViewports.has(documentId),\n // Events\n onViewportChange: this.viewportMetrics$.on,\n onViewportResize: this.viewportResize$.on,\n onScrollChange: this.scrollMetrics$.on,\n onScrollActivity: this.scrollActivity$.on,\n onGateChange: this.gateState$.on\n };\n }\n // ─────────────────────────────────────────────────────────\n // Document Scoping\n // ─────────────────────────────────────────────────────────\n createViewportScope(documentId) {\n return {\n getMetrics: () => this.getMetrics(documentId),\n scrollTo: (pos) => this.scrollTo(pos, documentId),\n isScrolling: () => this.isScrolling(documentId),\n isSmoothScrolling: () => this.isSmoothScrolling(documentId),\n isGated: () => this.isGated(documentId),\n hasGate: (key) => this.hasGate(key, documentId),\n getGates: () => this.getGates(documentId),\n gate: (key) => this.gate(key, documentId),\n releaseGate: (key) => this.releaseGate(key, documentId),\n onViewportChange: (listener) => this.viewportMetrics$.on((event) => {\n if (event.documentId === documentId) listener(event.metrics);\n }),\n onScrollChange: (listener) => this.scrollMetrics$.on((event) => {\n if (event.documentId === documentId) listener(event.scrollMetrics);\n }),\n onScrollActivity: (listener) => this.scrollActivity$.on((event) => {\n if (event.documentId === documentId) listener(event.activity);\n }),\n onGateChange: (listener) => this.gateState$.on((event) => {\n if ((event == null ? void 0 : event.documentId) === documentId) listener(event);\n })\n };\n }\n // ─────────────────────────────────────────────────────────\n // Viewport Registration (Public API for components)\n // ─────────────────────────────────────────────────────────\n registerViewport(documentId) {\n if (!this.state.documents[documentId]) {\n throw new Error(\n `Cannot register viewport for ${documentId}: document state not found. Document must be opened before registering viewport.`\n );\n }\n if (!this.state.activeViewports.has(documentId)) {\n this.dispatch(registerViewport(documentId));\n this.logger.debug(\n \"ViewportPlugin\",\n \"RegisterViewport\",\n `Registered viewport (DOM mounted) for document: ${documentId}`\n );\n }\n }\n unregisterViewport(documentId) {\n if (this.registry.isDestroyed()) return;\n if (this.state.activeViewports.has(documentId)) {\n this.dispatch(unregisterViewport(documentId));\n this.logger.debug(\n \"ViewportPlugin\",\n \"UnregisterViewport\",\n `Unregistered viewport (DOM unmounted) for document: ${documentId}. State preserved.`\n );\n }\n }\n // ─────────────────────────────────────────────────────────\n // Per-Document Operations\n // ─────────────────────────────────────────────────────────\n setViewportResizeMetrics(documentId, metrics) {\n if (this.registry.isDestroyed()) return;\n this.dispatch(setViewportMetrics(documentId, metrics));\n const viewport = this.state.documents[documentId];\n if (viewport) {\n this.viewportResize$.emit({\n documentId,\n metrics: viewport.viewportMetrics\n });\n }\n }\n setViewportScrollMetrics(documentId, scrollMetrics) {\n if (this.registry.isDestroyed()) return;\n const viewport = this.state.documents[documentId];\n if (!viewport) return;\n if (scrollMetrics.scrollTop !== viewport.viewportMetrics.scrollTop || scrollMetrics.scrollLeft !== viewport.viewportMetrics.scrollLeft) {\n this.dispatch(setViewportScrollMetrics(documentId, scrollMetrics));\n this.bumpScrollActivity(documentId);\n this.scrollMetrics$.emit({\n documentId,\n scrollMetrics\n });\n }\n }\n onScrollRequest(documentId, listener) {\n const emitter = this.scrollRequests$.get(documentId);\n if (!emitter) {\n throw new Error(\n `Cannot subscribe to scroll requests for ${documentId}: document state not initialized`\n );\n }\n return emitter.on(listener);\n }\n // ─────────────────────────────────────────────────────────\n // Public Gating API\n // ─────────────────────────────────────────────────────────\n gate(key, documentId) {\n const viewport = this.state.documents[documentId];\n if (!viewport) {\n this.logger.warn(\n \"ViewportPlugin\",\n \"GateViewport\",\n `Cannot gate viewport for ${documentId}: document not found`\n );\n return;\n }\n if (!viewport.gates.has(key)) {\n this.dispatch(addViewportGate(documentId, key));\n this.logger.debug(\n \"ViewportPlugin\",\n \"GateAdded\",\n `Added gate '${key}' for document: ${documentId}. Total gates: ${viewport.gates.size + 1}`\n );\n }\n }\n releaseGate(key, documentId) {\n const viewport = this.state.documents[documentId];\n if (!viewport) {\n this.logger.warn(\n \"ViewportPlugin\",\n \"ReleaseGate\",\n `Cannot release gate for ${documentId}: document not found`\n );\n return;\n }\n if (viewport.gates.has(key)) {\n this.dispatch(removeViewportGate(documentId, key));\n this.logger.debug(\n \"ViewportPlugin\",\n \"GateReleased\",\n `Released gate '${key}' for document: ${documentId}. Remaining gates: ${viewport.gates.size - 1}`\n );\n }\n }\n // ─────────────────────────────────────────────────────────\n // Helper Methods\n // ─────────────────────────────────────────────────────────\n getViewportState(documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const viewport = this.state.documents[id];\n if (!viewport) {\n throw new Error(`Viewport state not found for document: ${id}`);\n }\n return viewport;\n }\n getMetrics(documentId) {\n return this.getViewportState(documentId).viewportMetrics;\n }\n isScrolling(documentId) {\n return this.getViewportState(documentId).isScrolling;\n }\n isSmoothScrolling(documentId) {\n return this.getViewportState(documentId).isSmoothScrolling;\n }\n isGated(documentId) {\n const viewport = this.getViewportState(documentId);\n return viewport.gates.size > 0;\n }\n hasGate(key, documentId) {\n const viewport = this.getViewportState(documentId);\n return viewport.gates.has(key);\n }\n getGates(documentId) {\n const viewport = this.getViewportState(documentId);\n return Array.from(viewport.gates);\n }\n scrollTo(pos, documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const viewport = this.getViewportState(id);\n const { x, y, alignX, alignY, behavior = \"auto\" } = pos;\n if (behavior === \"smooth\") {\n this.dispatch(setSmoothScrollActivity(id, true));\n }\n const metrics = viewport.viewportMetrics;\n let finalX = x;\n let finalY = y;\n if (alignX !== void 0) {\n finalX = x - metrics.clientWidth * (alignX / 100);\n }\n if (alignY !== void 0) {\n finalY = y - metrics.clientHeight * (alignY / 100);\n }\n const emitter = this.scrollRequests$.get(id);\n if (emitter) {\n emitter.emit({ x: finalX, y: finalY, behavior });\n }\n }\n bumpScrollActivity(documentId) {\n this.debouncedDispatch(setScrollActivity(documentId, false), this.scrollEndDelay);\n this.debouncedDispatch(setSmoothScrollActivity(documentId, false), this.scrollEndDelay);\n }\n // ─────────────────────────────────────────────────────────\n // State Change Handling\n // ─────────────────────────────────────────────────────────\n onStoreUpdated(prevState, newState) {\n for (const documentId in newState.documents) {\n const prevViewport = prevState.documents[documentId];\n const newViewport = newState.documents[documentId];\n if (prevViewport !== newViewport) {\n this.viewportMetrics$.emit({\n documentId,\n metrics: newViewport.viewportMetrics\n });\n if (prevViewport && (prevViewport.isScrolling !== newViewport.isScrolling || prevViewport.isSmoothScrolling !== newViewport.isSmoothScrolling)) {\n this.scrollActivity$.emit({\n documentId,\n activity: {\n isScrolling: newViewport.isScrolling,\n isSmoothScrolling: newViewport.isSmoothScrolling\n }\n });\n }\n if (prevViewport && prevViewport.gates !== newViewport.gates) {\n const prevGates = Array.from(prevViewport.gates);\n const newGates = Array.from(newViewport.gates);\n const addedGate = newGates.find((g) => !prevGates.includes(g));\n const removedGate = prevGates.find((g) => !newGates.includes(g));\n this.gateState$.emit({\n documentId,\n isGated: newViewport.gates.size > 0,\n gates: newGates,\n addedGate,\n removedGate\n });\n this.logger.debug(\n \"ViewportPlugin\",\n \"GateStateChanged\",\n `Gate state changed for document ${documentId}. Gates: [${newGates.join(\", \")}], Gated: ${newViewport.gates.size > 0}`\n );\n }\n }\n }\n }\n // ─────────────────────────────────────────────────────────\n // Lifecycle\n // ─────────────────────────────────────────────────────────\n async initialize(_config) {\n this.logger.info(\"ViewportPlugin\", \"Initialize\", \"Viewport plugin initialized\");\n }\n async destroy() {\n this.viewportMetrics$.clear();\n this.viewportResize$.clear();\n this.scrollMetrics$.clear();\n this.scrollActivity$.clear();\n this.gateState$.clear();\n this.scrollRequests$.forEach((emitter) => emitter.clear());\n this.scrollRequests$.clear();\n super.destroy();\n }\n};\n_ViewportPlugin.id = \"viewport\";\nlet ViewportPlugin = _ViewportPlugin;\nconst ViewportPluginPackage = {\n manifest,\n create: (registry, config) => new ViewportPlugin(VIEWPORT_PLUGIN_ID, registry, config),\n reducer: viewportReducer,\n initialState\n};\nexport {\n VIEWPORT_PLUGIN_ID,\n ViewportPlugin,\n ViewportPluginPackage,\n manifest\n};\n//# sourceMappingURL=index.js.map\n","import { jsx } from \"react/jsx-runtime\";\nimport { createContext, useState, useEffect, useContext, useRef, useLayoutEffect } from \"react\";\nimport { useCapability, usePlugin } from \"@embedpdf/core/react\";\nimport { ViewportPlugin } from \"@embedpdf/plugin-viewport\";\nexport * from \"@embedpdf/plugin-viewport\";\nconst ViewportElementContext = createContext(null);\nconst useViewportPlugin = () => usePlugin(ViewportPlugin.id);\nconst useViewportCapability = () => useCapability(ViewportPlugin.id);\nconst useViewportElement = () => {\n return useContext(ViewportElementContext);\n};\nconst useIsViewportGated = (documentId) => {\n const { provides } = useViewportCapability();\n const [isGated, setIsGated] = useState((provides == null ? void 0 : provides.isGated(documentId)) ?? false);\n useEffect(() => {\n if (!provides) return;\n setIsGated(provides.isGated(documentId));\n return provides.onGateChange((event) => {\n if (event.documentId === documentId) {\n setIsGated(event.isGated);\n }\n });\n }, [provides, documentId]);\n return isGated;\n};\nconst useViewportScrollActivity = (documentId) => {\n const { provides } = useViewportCapability();\n const [scrollActivity, setScrollActivity] = useState({\n isScrolling: false,\n isSmoothScrolling: false\n });\n useEffect(() => {\n if (!provides) return;\n return provides.onScrollActivity((event) => {\n if (event.documentId === documentId) {\n setScrollActivity(event.activity);\n }\n });\n }, [provides, documentId]);\n return scrollActivity;\n};\nfunction useViewportRef(documentId) {\n const { plugin: viewportPlugin } = useViewportPlugin();\n const containerRef = useRef(null);\n useLayoutEffect(() => {\n if (!viewportPlugin) return;\n const container = containerRef.current;\n if (!container) return;\n try {\n viewportPlugin.registerViewport(documentId);\n } catch (error) {\n console.error(`Failed to register viewport for document ${documentId}:`, error);\n return;\n }\n const onScroll = () => {\n viewportPlugin.setViewportScrollMetrics(documentId, {\n scrollTop: container.scrollTop,\n scrollLeft: container.scrollLeft\n });\n };\n container.addEventListener(\"scroll\", onScroll);\n const resizeObserver = new ResizeObserver(() => {\n viewportPlugin.setViewportResizeMetrics(documentId, {\n width: container.offsetWidth,\n height: container.offsetHeight,\n clientWidth: container.clientWidth,\n clientHeight: container.clientHeight,\n scrollTop: container.scrollTop,\n scrollLeft: container.scrollLeft,\n scrollWidth: container.scrollWidth,\n scrollHeight: container.scrollHeight,\n clientLeft: container.clientLeft,\n clientTop: container.clientTop\n });\n });\n resizeObserver.observe(container);\n const unsubscribeScrollRequest = viewportPlugin.onScrollRequest(\n documentId,\n ({ x, y, behavior = \"auto\" }) => {\n requestAnimationFrame(() => {\n container.scrollTo({ left: x, top: y, behavior });\n });\n }\n );\n return () => {\n viewportPlugin.unregisterViewport(documentId);\n resizeObserver.disconnect();\n container.removeEventListener(\"scroll\", onScroll);\n unsubscribeScrollRequest();\n };\n }, [viewportPlugin, documentId]);\n return containerRef;\n}\nfunction Viewport({ children, documentId, ...props }) {\n const [viewportGap, setViewportGap] = useState(0);\n const viewportRef = useViewportRef(documentId);\n const { provides: viewportProvides } = useViewportCapability();\n const isGated = useIsViewportGated(documentId);\n useEffect(() => {\n if (viewportProvides) {\n setViewportGap(viewportProvides.getViewportGap());\n }\n }, [viewportProvides]);\n const { style, ...restProps } = props;\n return /* @__PURE__ */ jsx(ViewportElementContext.Provider, { value: viewportRef, children: /* @__PURE__ */ jsx(\n \"div\",\n {\n ...restProps,\n ref: viewportRef,\n style: {\n width: \"100%\",\n height: \"100%\",\n overflow: \"auto\",\n ...typeof style === \"object\" ? style : {},\n padding: `${viewportGap}px`\n },\n children: !isGated && children\n }\n ) });\n}\nexport {\n Viewport,\n ViewportElementContext,\n useIsViewportGated,\n useViewportCapability,\n useViewportElement,\n useViewportPlugin,\n useViewportRef,\n useViewportScrollActivity\n};\n//# sourceMappingURL=index.js.map\n","import { BasePlugin, createBehaviorEmitter } from \"@embedpdf/core\";\nimport { scalePosition, transformPosition, transformRect, transformSize } from \"@embedpdf/models\";\nvar ScrollStrategy = /* @__PURE__ */ ((ScrollStrategy2) => {\n ScrollStrategy2[\"Vertical\"] = \"vertical\";\n ScrollStrategy2[\"Horizontal\"] = \"horizontal\";\n return ScrollStrategy2;\n})(ScrollStrategy || {});\nclass BaseScrollStrategy {\n constructor(config) {\n this.pageGap = config.pageGap ?? 20;\n this.viewportGap = config.viewportGap ?? 20;\n this.bufferSize = config.bufferSize ?? 2;\n }\n /**\n * Horizontal centering offset for items narrower than the content max width.\n * Vertical layout centers spreads within the row; horizontal layout overrides to 0\n * since items stay in a simple row without centering.\n */\n getCenteringOffsetX(_item, totalContentSize) {\n if (!totalContentSize || _item.width >= totalContentSize.width) return 0;\n return (totalContentSize.width - _item.width) / 2;\n }\n /**\n * Vertical centering offset for items shorter than the content max height.\n * Horizontal layout centers items within the row height; vertical layout keeps\n * items top-aligned and uses the default of 0.\n */\n getCenteringOffsetY(_item, _totalContentSize) {\n return 0;\n }\n getVisibleRange(viewport, virtualItems, scale) {\n const scrollOffset = this.getScrollOffset(viewport);\n const clientSize = this.getClientSize(viewport);\n const viewportStart = scrollOffset;\n const viewportEnd = scrollOffset + clientSize;\n let startIndex = 0;\n while (startIndex < virtualItems.length && (virtualItems[startIndex].offset + this.getItemSizeAlongScrollAxis(virtualItems[startIndex])) * scale <= viewportStart) {\n startIndex++;\n }\n let endIndex = startIndex;\n while (endIndex < virtualItems.length && virtualItems[endIndex].offset * scale <= viewportEnd) {\n endIndex++;\n }\n return {\n start: Math.max(0, startIndex - this.bufferSize),\n end: Math.min(virtualItems.length - 1, endIndex + this.bufferSize - 1)\n };\n }\n handleScroll(viewport, virtualItems, scale) {\n const range = this.getVisibleRange(viewport, virtualItems, scale);\n const visibleItems = virtualItems.slice(range.start, range.end + 1);\n const totalContentSize = this.getTotalContentSize(virtualItems);\n const pageVisibilityMetrics = this.calculatePageVisibility(\n visibleItems,\n viewport,\n scale,\n totalContentSize\n );\n const visiblePages = pageVisibilityMetrics.map((m) => m.pageNumber);\n const renderedPageIndexes = virtualItems.slice(range.start, range.end + 1).flatMap((item) => item.index);\n const currentPage = this.determineCurrentPage(pageVisibilityMetrics);\n const first = virtualItems[range.start];\n const last = virtualItems[range.end];\n const startSpacing = first ? first.offset * scale : 0;\n const lastItem = virtualItems[virtualItems.length - 1];\n const endSpacing = last ? (lastItem.offset + this.getItemSizeAlongScrollAxis(lastItem)) * scale - (last.offset + this.getItemSizeAlongScrollAxis(last)) * scale : 0;\n return {\n currentPage,\n visiblePages,\n pageVisibilityMetrics,\n renderedPageIndexes,\n scrollOffset: { x: viewport.scrollLeft, y: viewport.scrollTop },\n startSpacing,\n endSpacing\n };\n }\n calculatePageVisibility(virtualItems, viewport, scale, totalContentSize) {\n const visibilityMetrics = [];\n virtualItems.forEach((item) => {\n const centeringOffsetX = this.getCenteringOffsetX(item, totalContentSize);\n const centeringOffsetY = this.getCenteringOffsetY(item, totalContentSize);\n item.pageLayouts.forEach((page) => {\n const itemX = (item.x + centeringOffsetX) * scale;\n const itemY = (item.y + centeringOffsetY) * scale;\n const pageX = itemX + page.x * scale;\n const pageY = itemY + page.y * scale;\n const pageWidth = page.rotatedWidth * scale;\n const pageHeight = page.rotatedHeight * scale;\n const viewportLeft = viewport.scrollLeft;\n const viewportTop = viewport.scrollTop;\n const viewportRight = viewportLeft + viewport.clientWidth;\n const viewportBottom = viewportTop + viewport.clientHeight;\n const intersectionLeft = Math.max(pageX, viewportLeft);\n const intersectionTop = Math.max(pageY, viewportTop);\n const intersectionRight = Math.min(pageX + pageWidth, viewportRight);\n const intersectionBottom = Math.min(pageY + pageHeight, viewportBottom);\n if (intersectionLeft < intersectionRight && intersectionTop < intersectionBottom) {\n const visibleWidth = intersectionRight - intersectionLeft;\n const visibleHeight = intersectionBottom - intersectionTop;\n const totalArea = pageWidth * pageHeight;\n const visibleArea = visibleWidth * visibleHeight;\n visibilityMetrics.push({\n pageNumber: page.pageNumber,\n viewportX: intersectionLeft - viewportLeft,\n viewportY: intersectionTop - viewportTop,\n visiblePercentage: visibleArea / totalArea * 100,\n original: {\n pageX: (intersectionLeft - pageX) / scale,\n pageY: (intersectionTop - pageY) / scale,\n visibleWidth: visibleWidth / scale,\n visibleHeight: visibleHeight / scale,\n scale: 1\n },\n scaled: {\n pageX: intersectionLeft - pageX,\n pageY: intersectionTop - pageY,\n visibleWidth,\n visibleHeight,\n scale\n }\n });\n }\n });\n });\n return visibilityMetrics;\n }\n determineCurrentPage(visibilityMetrics) {\n if (visibilityMetrics.length === 0) return 1;\n const maxVisibility = Math.max(...visibilityMetrics.map((m) => m.visiblePercentage));\n const mostVisiblePages = visibilityMetrics.filter((m) => m.visiblePercentage === maxVisibility);\n return mostVisiblePages.length === 1 ? mostVisiblePages[0].pageNumber : mostVisiblePages.sort((a, b) => a.pageNumber - b.pageNumber)[0].pageNumber;\n }\n getRectLocationForPage(pageNumber, virtualItems, totalContentSize) {\n const item = virtualItems.find((item2) => item2.pageNumbers.includes(pageNumber));\n if (!item) return null;\n const pageLayout = item.pageLayouts.find((layout) => layout.pageNumber === pageNumber);\n if (!pageLayout) return null;\n const centeringOffsetX = this.getCenteringOffsetX(item, totalContentSize);\n const centeringOffsetY = this.getCenteringOffsetY(item, totalContentSize);\n return {\n origin: {\n x: item.x + pageLayout.x + centeringOffsetX,\n y: item.y + pageLayout.y + centeringOffsetY\n },\n size: {\n width: pageLayout.width,\n height: pageLayout.height\n }\n };\n }\n getScrollPositionForPage(pageNumber, virtualItems, scale, rotation, pageCoordinates) {\n const totalContentSize = this.getTotalContentSize(virtualItems);\n const pageRect = this.getRectLocationForPage(pageNumber, virtualItems, totalContentSize);\n if (!pageRect) return null;\n const scaledBasePosition = scalePosition(pageRect.origin, scale);\n if (pageCoordinates) {\n const rotatedSize = transformPosition(\n {\n width: pageRect.size.width,\n height: pageRect.size.height\n },\n {\n x: pageCoordinates.x,\n y: pageCoordinates.y\n },\n rotation,\n scale\n );\n return {\n x: scaledBasePosition.x + rotatedSize.x + this.viewportGap,\n y: scaledBasePosition.y + rotatedSize.y + this.viewportGap\n };\n }\n return {\n x: scaledBasePosition.x + this.viewportGap,\n y: scaledBasePosition.y + this.viewportGap\n };\n }\n getRectPositionForPage(pageNumber, virtualItems, scale, rotation, rect) {\n const totalContentSize = this.getTotalContentSize(virtualItems);\n const pageRect = this.getRectLocationForPage(pageNumber, virtualItems, totalContentSize);\n if (!pageRect) return null;\n const scaledBasePosition = scalePosition(pageRect.origin, scale);\n const rotatedSize = transformRect(\n {\n width: pageRect.size.width,\n height: pageRect.size.height\n },\n rect,\n rotation,\n scale\n );\n return {\n origin: {\n x: scaledBasePosition.x + rotatedSize.origin.x,\n y: scaledBasePosition.y + rotatedSize.origin.y\n },\n size: rotatedSize.size\n };\n }\n}\nclass VerticalScrollStrategy extends BaseScrollStrategy {\n constructor(config) {\n super(config);\n }\n createVirtualItems(pdfPageObject) {\n let yOffset = 0;\n return pdfPageObject.map((pagesInSpread, index) => {\n let pageX = 0;\n const pageLayouts = pagesInSpread.map((page) => {\n const layout = {\n pageNumber: page.index + 1,\n pageIndex: page.index,\n x: pageX,\n y: 0,\n width: page.size.width,\n height: page.size.height,\n rotatedWidth: page.rotatedSize.width,\n rotatedHeight: page.rotatedSize.height,\n elevated: false\n };\n pageX += page.rotatedSize.width + this.pageGap;\n return layout;\n });\n const width = pagesInSpread.reduce(\n (sum, page, i) => sum + page.rotatedSize.width + (i < pagesInSpread.length - 1 ? this.pageGap : 0),\n 0\n );\n const height = Math.max(...pagesInSpread.map((p) => p.rotatedSize.height));\n const item = {\n id: `item-${index}`,\n x: 0,\n y: yOffset,\n offset: yOffset,\n width,\n height,\n pageLayouts,\n pageNumbers: pagesInSpread.map((p) => p.index + 1),\n index\n };\n yOffset += height + this.pageGap;\n return item;\n });\n }\n getTotalContentSize(virtualItems) {\n if (virtualItems.length === 0) return { width: 0, height: 0 };\n const maxWidth = Math.max(...virtualItems.map((item) => item.width));\n const totalHeight = virtualItems[virtualItems.length - 1].y + virtualItems[virtualItems.length - 1].height;\n return {\n width: maxWidth,\n height: totalHeight\n };\n }\n getScrollOffset(viewport) {\n return viewport.scrollTop;\n }\n getClientSize(viewport) {\n return viewport.clientHeight;\n }\n /** Vertical scroll: extent along scroll axis is height. */\n getItemSizeAlongScrollAxis(item) {\n return item.height;\n }\n}\nclass HorizontalScrollStrategy extends BaseScrollStrategy {\n constructor(config) {\n super(config);\n }\n createVirtualItems(pdfPageObject) {\n let xOffset = 0;\n return pdfPageObject.map((pagesInSpread, index) => {\n let pageX = 0;\n const pageLayouts = pagesInSpread.map((page) => {\n const layout = {\n pageNumber: page.index + 1,\n pageIndex: page.index,\n x: pageX,\n y: 0,\n width: page.size.width,\n height: page.size.height,\n rotatedWidth: page.rotatedSize.width,\n rotatedHeight: page.rotatedSize.height,\n elevated: false\n };\n pageX += page.rotatedSize.width + this.pageGap;\n return layout;\n });\n const width = pagesInSpread.reduce(\n (sum, page, i) => sum + page.rotatedSize.width + (i < pagesInSpread.length - 1 ? this.pageGap : 0),\n 0\n );\n const height = Math.max(...pagesInSpread.map((p) => p.rotatedSize.height));\n const item = {\n id: `item-${index}`,\n x: xOffset,\n y: 0,\n offset: xOffset,\n width,\n height,\n pageLayouts,\n pageNumbers: pagesInSpread.map((p) => p.index + 1),\n index\n };\n xOffset += width + this.pageGap;\n return item;\n });\n }\n getTotalContentSize(virtualItems) {\n if (virtualItems.length === 0) return { width: 0, height: 0 };\n const totalWidth = virtualItems[virtualItems.length - 1].x + virtualItems[virtualItems.length - 1].width;\n const maxHeight = Math.max(...virtualItems.map((item) => item.height));\n return {\n width: totalWidth,\n height: maxHeight\n };\n }\n getScrollOffset(viewport) {\n return viewport.scrollLeft;\n }\n getClientSize(viewport) {\n return viewport.clientWidth;\n }\n /** Horizontal scroll: extent along scroll axis is width. */\n getItemSizeAlongScrollAxis(item) {\n return item.width;\n }\n /**\n * No centering for horizontal layout. Items are laid out in a simple row;\n * using total content width would produce incorrect offsets and shift pages.\n */\n /* eslint-disable no-unused-vars -- override intentionally ignores params */\n getCenteringOffsetX(_item, _totalContentSize) {\n return 0;\n }\n /**\n * Horizontal rows visually center shorter items within the tallest row height.\n * Match that DOM layout so page-coordinate targeting lands on the rendered page.\n */\n getCenteringOffsetY(item, totalContentSize) {\n if (!totalContentSize || item.height >= totalContentSize.height) return 0;\n return (totalContentSize.height - item.height) / 2;\n }\n}\nconst INIT_SCROLL_STATE = \"INIT_SCROLL_STATE\";\nconst CLEANUP_SCROLL_STATE = \"CLEANUP_SCROLL_STATE\";\nconst UPDATE_DOCUMENT_SCROLL_STATE = \"UPDATE_DOCUMENT_SCROLL_STATE\";\nconst SET_SCROLL_STRATEGY = \"SET_SCROLL_STRATEGY\";\nfunction initScrollState(documentId, state) {\n return { type: INIT_SCROLL_STATE, payload: { documentId, state } };\n}\nfunction cleanupScrollState(documentId) {\n return { type: CLEANUP_SCROLL_STATE, payload: documentId };\n}\nfunction updateDocumentScrollState(documentId, state) {\n return { type: UPDATE_DOCUMENT_SCROLL_STATE, payload: { documentId, state } };\n}\nfunction setScrollStrategy(documentId, strategy) {\n return { type: SET_SCROLL_STRATEGY, payload: { documentId, strategy } };\n}\nconst defaultPageChangeState = {\n isChanging: false,\n targetPage: 1,\n fromPage: 1,\n startTime: 0\n};\nconst initialState = (_coreState, config) => ({\n defaultStrategy: config.defaultStrategy ?? ScrollStrategy.Vertical,\n defaultPageGap: config.defaultPageGap ?? 10,\n defaultBufferSize: config.defaultBufferSize ?? 2,\n documents: {}\n});\nconst scrollReducer = (state, action) => {\n switch (action.type) {\n case INIT_SCROLL_STATE: {\n const { documentId, state: docState } = action.payload;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: docState\n }\n };\n }\n case CLEANUP_SCROLL_STATE: {\n const { [action.payload]: removed, ...remaining } = state.documents;\n return {\n ...state,\n documents: remaining\n };\n }\n case UPDATE_DOCUMENT_SCROLL_STATE: {\n const { documentId, state: updates } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...docState,\n ...updates\n }\n }\n };\n }\n case SET_SCROLL_STRATEGY: {\n const { documentId, strategy } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...docState,\n strategy\n }\n }\n };\n }\n default:\n return state;\n }\n};\nconst getScrollerLayout = (documentState, scale, elevatedPages) => {\n return {\n startSpacing: documentState.startSpacing,\n endSpacing: documentState.endSpacing,\n totalWidth: documentState.totalContentSize.width * scale,\n totalHeight: documentState.totalContentSize.height * scale,\n pageGap: documentState.pageGap * scale,\n strategy: documentState.strategy,\n items: documentState.renderedPageIndexes.map((idx) => {\n return {\n ...documentState.virtualItems[idx],\n pageLayouts: documentState.virtualItems[idx].pageLayouts.map((layout) => {\n return {\n ...layout,\n rotatedWidth: layout.rotatedWidth * scale,\n rotatedHeight: layout.rotatedHeight * scale,\n width: layout.width * scale,\n height: layout.height * scale,\n elevated: (elevatedPages == null ? void 0 : elevatedPages.has(layout.pageIndex)) ?? false\n };\n })\n };\n })\n };\n};\nconst _ScrollPlugin = class _ScrollPlugin extends BasePlugin {\n constructor(id, registry, config) {\n var _a, _b, _c;\n super(id, registry);\n this.id = id;\n this.config = config;\n this.elevatedPages = /* @__PURE__ */ new Map();\n this.strategies = /* @__PURE__ */ new Map();\n this.layoutReady = /* @__PURE__ */ new Set();\n this.initialLayoutFired = /* @__PURE__ */ new Set();\n this.scrollerLayoutEmitters = /* @__PURE__ */ new Map();\n this.pageChange$ = createBehaviorEmitter();\n this.scroll$ = createBehaviorEmitter();\n this.layoutChange$ = createBehaviorEmitter();\n this.pageChangeState$ = createBehaviorEmitter();\n this.layoutReady$ = createBehaviorEmitter();\n this.state$ = createBehaviorEmitter();\n this.viewport = this.registry.getPlugin(\"viewport\").provides();\n this.spread = ((_a = this.registry.getPlugin(\"spread\")) == null ? void 0 : _a.provides()) ?? null;\n this.viewport.onScrollActivity((event) => {\n const docState = this.getDocumentState(event.documentId);\n if ((docState == null ? void 0 : docState.pageChangeState.isChanging) && !event.activity.isSmoothScrolling) {\n this.completePageChange(event.documentId);\n }\n });\n (_b = this.spread) == null ? void 0 : _b.onSpreadChange((event) => {\n this.refreshDocumentLayout(event.documentId);\n });\n const im = (_c = this.registry.getPlugin(\"interaction-manager\")) == null ? void 0 : _c.provides();\n if (im) {\n im.onPageActivityChange((event) => {\n let pages = this.elevatedPages.get(event.documentId);\n if (event.hasActivity) {\n if (!pages) {\n pages = /* @__PURE__ */ new Set();\n this.elevatedPages.set(event.documentId, pages);\n }\n pages.add(event.pageIndex);\n } else {\n pages == null ? void 0 : pages.delete(event.pageIndex);\n }\n this.pushScrollerLayout(event.documentId);\n });\n }\n this.viewport.onViewportChange((event) => {\n const docState = this.getDocumentState(event.documentId);\n if (!docState) return;\n const computedMetrics = this.computeMetrics(event.documentId, event.metrics);\n if (this.layoutReady.has(event.documentId)) {\n this.commitMetrics(event.documentId, computedMetrics);\n } else {\n this.commitMetrics(event.documentId, {\n ...computedMetrics,\n scrollOffset: docState.scrollOffset\n });\n }\n });\n }\n // ─────────────────────────────────────────────────────────\n // Document Lifecycle Hooks (from BasePlugin)\n // ─────────────────────────────────────────────────────────\n onDocumentLoadingStarted(documentId) {\n const coreDoc = this.getCoreDocument(documentId);\n if (!coreDoc) return;\n const docState = this.createDocumentState(coreDoc);\n this.dispatch(initScrollState(documentId, docState));\n const strategy = this.createStrategy(docState.strategy);\n this.strategies.set(documentId, strategy);\n this.scrollerLayoutEmitters.set(documentId, createBehaviorEmitter());\n }\n onDocumentLoaded(documentId) {\n var _a;\n const coreDoc = this.getCoreDocument(documentId);\n if (!coreDoc) return;\n this.dispatch(\n updateDocumentScrollState(documentId, { totalPages: ((_a = coreDoc.document) == null ? void 0 : _a.pageCount) ?? 0 })\n );\n this.refreshDocumentLayout(documentId);\n this.logger.debug(\n \"ScrollPlugin\",\n \"DocumentOpened\",\n `Initialized scroll state for document: ${documentId}`\n );\n }\n onDocumentClosed(documentId) {\n this.strategies.delete(documentId);\n this.layoutReady.delete(documentId);\n this.initialLayoutFired.delete(documentId);\n this.elevatedPages.delete(documentId);\n const emitter = this.scrollerLayoutEmitters.get(documentId);\n if (emitter) {\n emitter.clear();\n this.scrollerLayoutEmitters.delete(documentId);\n }\n this.dispatch(cleanupScrollState(documentId));\n this.logger.debug(\n \"ScrollPlugin\",\n \"DocumentClosed\",\n `Cleaned up scroll state for document: ${documentId}`\n );\n }\n onScaleChanged(documentId) {\n const coreDoc = this.coreState.core.documents[documentId];\n if (!coreDoc || coreDoc.status !== \"loaded\") return;\n const viewportScope = this.viewport.forDocument(documentId);\n const metrics = this.computeMetrics(documentId, viewportScope.getMetrics());\n this.commitMetrics(documentId, metrics);\n }\n onRotationChanged(documentId) {\n this.refreshDocumentLayout(documentId);\n }\n // ─────────────────────────────────────────────────────────\n // Public API for Components (Scroller Layout)\n // ─────────────────────────────────────────────────────────\n /**\n * Subscribe to scroller layout updates for a specific document\n * This is the key method for the Scroller component to stay reactive\n */\n onScrollerData(documentId, callback) {\n const emitter = this.scrollerLayoutEmitters.get(documentId);\n if (!emitter) {\n throw new Error(`No scroller layout emitter found for document: ${documentId}`);\n }\n return emitter.on(callback);\n }\n /**\n * Get current scroller layout for a document\n */\n getScrollerLayout(documentId) {\n const docState = this.getDocumentState(documentId);\n const coreDoc = this.getCoreDocumentOrThrow(documentId);\n if (!docState || !coreDoc) {\n throw new Error(`Cannot get scroller layout for document: ${documentId}`);\n }\n return getScrollerLayout(docState, coreDoc.scale, this.elevatedPages.get(documentId));\n }\n setLayoutReady(documentId) {\n if (this.layoutReady.has(documentId)) {\n return;\n }\n const docState = this.getDocumentState(documentId);\n if (!docState) return;\n this.layoutReady.add(documentId);\n const isInitial = !this.initialLayoutFired.has(documentId);\n if (isInitial) {\n this.initialLayoutFired.add(documentId);\n }\n const viewport = this.viewport.forDocument(documentId);\n viewport.scrollTo({ ...docState.scrollOffset, behavior: \"instant\" });\n this.layoutReady$.emit({\n documentId,\n isInitial,\n pageNumber: docState.currentPage,\n totalPages: docState.totalPages\n });\n }\n clearLayoutReady(documentId) {\n this.layoutReady.delete(documentId);\n }\n // ─────────────────────────────────────────────────────────\n // Capability\n // ─────────────────────────────────────────────────────────\n buildCapability() {\n return {\n // Active document operations\n getCurrentPage: () => this.getCurrentPage(),\n getTotalPages: () => this.getTotalPages(),\n getPageChangeState: () => this.getPageChangeState(),\n scrollToPage: (options) => this.scrollToPage(options),\n scrollToNextPage: (behavior) => this.scrollToNextPage(behavior),\n scrollToPreviousPage: (behavior) => this.scrollToPreviousPage(behavior),\n getMetrics: (viewport) => this.getMetrics(viewport),\n getLayout: () => this.getLayout(),\n getRectPositionForPage: (page, rect, scale, rotation) => this.getRectPositionForPage(page, rect, scale, rotation),\n // Document-scoped operations\n forDocument: (documentId) => this.createScrollScope(documentId),\n // Global settings\n setScrollStrategy: (strategy, documentId) => this.setScrollStrategyForDocument(strategy, documentId),\n getPageGap: () => this.state.defaultPageGap,\n // Events\n onPageChange: this.pageChange$.on,\n onScroll: this.scroll$.on,\n onLayoutChange: this.layoutChange$.on,\n onLayoutReady: this.layoutReady$.on,\n onPageChangeState: this.pageChangeState$.on,\n onStateChange: this.state$.on\n };\n }\n // ─────────────────────────────────────────────────────────\n // Document Scoping\n // ─────────────────────────────────────────────────────────\n createScrollScope(documentId) {\n return {\n getCurrentPage: () => this.getCurrentPage(documentId),\n getTotalPages: () => this.getTotalPages(documentId),\n getPageChangeState: () => this.getPageChangeState(documentId),\n scrollToPage: (options) => this.scrollToPage(options, documentId),\n scrollToNextPage: (behavior) => this.scrollToNextPage(behavior, documentId),\n scrollToPreviousPage: (behavior) => this.scrollToPreviousPage(behavior, documentId),\n getSpreadPagesWithRotatedSize: () => this.getSpreadPagesWithRotatedSize(documentId),\n getMetrics: (viewport) => this.getMetrics(viewport, documentId),\n getLayout: () => this.getLayout(documentId),\n getRectPositionForPage: (page, rect, scale, rotation) => this.getRectPositionForPage(page, rect, scale, rotation, documentId),\n setScrollStrategy: (strategy) => this.setScrollStrategyForDocument(strategy, documentId),\n onPageChange: (listener) => this.pageChange$.on((event) => {\n if (event.documentId === documentId) listener(event);\n }),\n onScroll: (listener) => this.scroll$.on((event) => {\n if (event.documentId === documentId) listener(event.metrics);\n }),\n onLayoutChange: (listener) => this.layoutChange$.on((event) => {\n if (event.documentId === documentId) listener(event.layout);\n })\n };\n }\n // ─────────────────────────────────────────────────────────\n // State Helpers\n // ─────────────────────────────────────────────────────────\n getDocumentState(documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n return this.state.documents[id] ?? null;\n }\n getDocumentStateOrThrow(documentId) {\n const state = this.getDocumentState(documentId);\n if (!state) {\n throw new Error(`Scroll state not found for document: ${documentId ?? \"active\"}`);\n }\n return state;\n }\n getStrategy(documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const strategy = this.strategies.get(id);\n if (!strategy) {\n throw new Error(`Strategy not found for document: ${id}`);\n }\n return strategy;\n }\n createStrategy(strategyType) {\n const config = {\n pageGap: this.state.defaultPageGap,\n viewportGap: this.viewport.getViewportGap(),\n bufferSize: this.state.defaultBufferSize\n };\n return strategyType === ScrollStrategy.Horizontal ? new HorizontalScrollStrategy(config) : new VerticalScrollStrategy(config);\n }\n createDocumentState(coreDoc) {\n var _a;\n return {\n virtualItems: [],\n totalPages: ((_a = coreDoc.document) == null ? void 0 : _a.pageCount) ?? 0,\n currentPage: 1,\n totalContentSize: { width: 0, height: 0 },\n strategy: this.state.defaultStrategy,\n pageGap: this.state.defaultPageGap,\n visiblePages: [],\n pageVisibilityMetrics: [],\n renderedPageIndexes: [],\n scrollOffset: { x: 0, y: 0 },\n startSpacing: 0,\n endSpacing: 0,\n pageChangeState: defaultPageChangeState\n };\n }\n // ─────────────────────────────────────────────────────────\n // Page Change Management\n // ─────────────────────────────────────────────────────────\n startPageChange(documentId, targetPage, behavior = \"smooth\") {\n const docState = this.getDocumentState(documentId);\n if (!docState) return;\n const pageChangeState = {\n isChanging: true,\n targetPage,\n fromPage: docState.currentPage,\n startTime: Date.now()\n };\n this.dispatch(\n updateDocumentScrollState(documentId, {\n pageChangeState,\n currentPage: targetPage\n })\n );\n this.pageChange$.emit({\n documentId,\n pageNumber: targetPage,\n totalPages: docState.totalPages\n });\n if (behavior === \"instant\") {\n this.completePageChange(documentId);\n }\n }\n completePageChange(documentId) {\n const docState = this.getDocumentState(documentId);\n if (!docState || !docState.pageChangeState.isChanging) return;\n const pageChangeState = {\n isChanging: false,\n targetPage: docState.pageChangeState.targetPage,\n fromPage: docState.pageChangeState.fromPage,\n startTime: docState.pageChangeState.startTime\n };\n this.dispatch(updateDocumentScrollState(documentId, { pageChangeState }));\n }\n // ─────────────────────────────────────────────────────────\n // Layout & Metrics Computation\n // ─────────────────────────────────────────────────────────\n computeLayout(documentId, pages) {\n const strategy = this.getStrategy(documentId);\n const virtualItems = strategy.createVirtualItems(pages);\n const totalContentSize = strategy.getTotalContentSize(virtualItems);\n return { virtualItems, totalContentSize };\n }\n computeMetrics(documentId, vp, items) {\n const coreDocState = this.getCoreDocumentOrThrow(documentId);\n const docState = this.getDocumentState(documentId);\n const strategy = this.getStrategy(documentId);\n if (!docState) throw new Error(`Document state not found: ${documentId}`);\n return strategy.handleScroll(vp, items ?? docState.virtualItems, coreDocState.scale);\n }\n // ─────────────────────────────────────────────────────────\n // Commit (Single Source of Truth)\n // ─────────────────────────────────────────────────────────\n commitMetrics(documentId, metrics) {\n const docState = this.getDocumentState(documentId);\n if (!docState) return;\n const isProgrammaticScroll = docState.pageChangeState.isChanging;\n const metricsToCommit = isProgrammaticScroll && metrics.currentPage !== docState.currentPage ? { ...metrics, currentPage: docState.currentPage } : metrics;\n this.dispatch(updateDocumentScrollState(documentId, metricsToCommit));\n this.scroll$.emit({ documentId, metrics: metricsToCommit });\n if (!isProgrammaticScroll && metrics.currentPage !== docState.currentPage) {\n this.pageChange$.emit({\n documentId,\n pageNumber: metrics.currentPage,\n totalPages: docState.totalPages\n });\n }\n this.pushScrollerLayout(documentId);\n }\n pushScrollerLayout(documentId) {\n const emitter = this.scrollerLayoutEmitters.get(documentId);\n if (!emitter) return;\n try {\n const layout = this.getScrollerLayout(documentId);\n emitter.emit(layout);\n } catch (error) {\n }\n }\n refreshDocumentLayout(documentId) {\n const coreDoc = this.coreState.core.documents[documentId];\n const docState = this.getDocumentState(documentId);\n if (!coreDoc || !docState || coreDoc.status !== \"loaded\") return;\n const pages = this.getSpreadPagesWithRotatedSize(documentId);\n const layout = this.computeLayout(documentId, pages);\n const viewport = this.viewport.forDocument(documentId);\n const metrics = this.computeMetrics(documentId, viewport.getMetrics(), layout.virtualItems);\n this.dispatch(\n updateDocumentScrollState(documentId, {\n ...layout,\n ...metrics\n })\n );\n this.layoutChange$.emit({ documentId, layout });\n this.pushScrollerLayout(documentId);\n }\n getSpreadPagesWithRotatedSize(documentId) {\n var _a, _b;\n const id = documentId ?? this.getActiveDocumentId();\n const coreDoc = this.coreState.core.documents[id];\n if (!coreDoc) throw new Error(`Document ${id} not loaded`);\n const spreadPages = ((_a = this.spread) == null ? void 0 : _a.forDocument(id).getSpreadPages()) || ((_b = coreDoc.document) == null ? void 0 : _b.pages.map((page) => [page])) || [];\n return spreadPages.map(\n (spread) => spread.map((page) => {\n const effectiveRotation = ((page.rotation ?? 0) + coreDoc.rotation) % 4;\n return {\n ...page,\n rotatedSize: transformSize(page.size, effectiveRotation, 1)\n };\n })\n );\n }\n // ─────────────────────────────────────────────────────────\n // Core Operations\n // ─────────────────────────────────────────────────────────\n getCurrentPage(documentId) {\n return this.getDocumentStateOrThrow(documentId).currentPage;\n }\n getTotalPages(documentId) {\n return this.getDocumentStateOrThrow(documentId).totalPages;\n }\n getPageChangeState(documentId) {\n return this.getDocumentStateOrThrow(documentId).pageChangeState;\n }\n scrollToPage(options, documentId) {\n var _a;\n const id = documentId ?? this.getActiveDocumentId();\n const docState = this.getDocumentStateOrThrow(id);\n const strategy = this.getStrategy(id);\n const coreDoc = this.getCoreDocumentOrThrow(id);\n const { pageNumber, behavior = \"smooth\", pageCoordinates, alignX, alignY } = options;\n this.startPageChange(id, pageNumber, behavior);\n const pageObj = (_a = coreDoc.document) == null ? void 0 : _a.pages[pageNumber - 1];\n const effectiveRotation = (((pageObj == null ? void 0 : pageObj.rotation) ?? 0) + coreDoc.rotation) % 4;\n const position = strategy.getScrollPositionForPage(\n pageNumber,\n docState.virtualItems,\n coreDoc.scale,\n effectiveRotation,\n pageCoordinates\n );\n if (position) {\n const viewport = this.viewport.forDocument(id);\n viewport.scrollTo({ ...position, behavior, alignX, alignY });\n } else {\n this.completePageChange(id);\n }\n }\n scrollToNextPage(behavior = \"smooth\", documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const docState = this.getDocumentStateOrThrow(id);\n const strategy = this.getStrategy(id);\n const coreDoc = this.getCoreDocumentOrThrow(id);\n const currentItemIndex = docState.virtualItems.findIndex(\n (item) => item.pageNumbers.includes(docState.currentPage)\n );\n if (currentItemIndex >= 0 && currentItemIndex < docState.virtualItems.length - 1) {\n const nextItem = docState.virtualItems[currentItemIndex + 1];\n const targetPage = nextItem.pageNumbers[0];\n this.startPageChange(id, targetPage, behavior);\n const position = strategy.getScrollPositionForPage(\n targetPage,\n docState.virtualItems,\n coreDoc.scale,\n coreDoc.rotation\n );\n if (position) {\n const viewport = this.viewport.forDocument(id);\n viewport.scrollTo({ ...position, behavior });\n } else {\n this.completePageChange(id);\n }\n }\n }\n scrollToPreviousPage(behavior = \"smooth\", documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const docState = this.getDocumentStateOrThrow(id);\n const strategy = this.getStrategy(id);\n const coreDoc = this.coreState.core.documents[id];\n const currentItemIndex = docState.virtualItems.findIndex(\n (item) => item.pageNumbers.includes(docState.currentPage)\n );\n if (currentItemIndex > 0) {\n const prevItem = docState.virtualItems[currentItemIndex - 1];\n const targetPage = prevItem.pageNumbers[0];\n this.startPageChange(id, targetPage, behavior);\n const position = strategy.getScrollPositionForPage(\n targetPage,\n docState.virtualItems,\n coreDoc.scale,\n coreDoc.rotation\n );\n if (position) {\n const viewport = this.viewport.forDocument(id);\n viewport.scrollTo({ ...position, behavior });\n } else {\n this.completePageChange(id);\n }\n }\n }\n getMetrics(viewport, documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n if (viewport) {\n return this.computeMetrics(id, viewport);\n }\n const viewportScope = this.viewport.forDocument(id);\n return this.computeMetrics(id, viewportScope.getMetrics());\n }\n getLayout(documentId) {\n const docState = this.getDocumentStateOrThrow(documentId);\n return {\n virtualItems: docState.virtualItems,\n totalContentSize: docState.totalContentSize\n };\n }\n getRectPositionForPage(pageIndex, rect, scale, rotation, documentId) {\n var _a;\n const id = documentId ?? this.getActiveDocumentId();\n const docState = this.getDocumentStateOrThrow(id);\n const strategy = this.getStrategy(id);\n const coreDoc = this.getCoreDocumentOrThrow(id);\n let effectiveRotation = rotation;\n if (effectiveRotation === void 0) {\n const pageObj = (_a = coreDoc.document) == null ? void 0 : _a.pages[pageIndex];\n effectiveRotation = (((pageObj == null ? void 0 : pageObj.rotation) ?? 0) + coreDoc.rotation) % 4;\n }\n return strategy.getRectPositionForPage(\n pageIndex + 1,\n docState.virtualItems,\n scale ?? coreDoc.scale,\n effectiveRotation,\n rect\n );\n }\n setScrollStrategyForDocument(newStrategy, documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const docState = this.getDocumentState(id);\n if (!docState || docState.strategy === newStrategy) return;\n const strategy = this.createStrategy(newStrategy);\n this.strategies.set(id, strategy);\n this.dispatch(setScrollStrategy(id, newStrategy));\n this.refreshDocumentLayout(id);\n }\n // ─────────────────────────────────────────────────────────\n // Store Update Handlers\n // ─────────────────────────────────────────────────────────\n onStoreUpdated(prevState, newState) {\n for (const documentId in newState.documents) {\n const prevDoc = prevState.documents[documentId];\n const newDoc = newState.documents[documentId];\n if (prevDoc !== newDoc) {\n this.state$.emit(newDoc);\n if ((prevDoc == null ? void 0 : prevDoc.pageChangeState) !== newDoc.pageChangeState) {\n this.pageChangeState$.emit({\n documentId,\n state: newDoc.pageChangeState\n });\n }\n this.pushScrollerLayout(documentId);\n }\n }\n }\n // ─────────────────────────────────────────────────────────\n // Lifecycle\n // ─────────────────────────────────────────────────────────\n async initialize() {\n this.logger.info(\"ScrollPlugin\", \"Initialize\", \"Scroll plugin initialized\");\n }\n async destroy() {\n this.strategies.clear();\n this.layoutReady.clear();\n this.initialLayoutFired.clear();\n this.elevatedPages.clear();\n for (const emitter of this.scrollerLayoutEmitters.values()) {\n emitter.clear();\n }\n this.scrollerLayoutEmitters.clear();\n this.pageChange$.clear();\n this.scroll$.clear();\n this.layoutChange$.clear();\n this.pageChangeState$.clear();\n this.layoutReady$.clear();\n this.state$.clear();\n super.destroy();\n }\n};\n_ScrollPlugin.id = \"scroll\";\nlet ScrollPlugin = _ScrollPlugin;\nconst SCROLL_PLUGIN_ID = \"scroll\";\nconst manifest = {\n id: SCROLL_PLUGIN_ID,\n name: \"Scroll Plugin\",\n version: \"1.0.0\",\n provides: [\"scroll\"],\n requires: [\"viewport\"],\n optional: [\"spread\", \"interaction-manager\"],\n defaultConfig: {\n defaultPageGap: 10,\n defaultBufferSize: 4,\n defaultStrategy: ScrollStrategy.Vertical\n }\n};\nconst ScrollPluginPackage = {\n manifest,\n create: (registry, config) => new ScrollPlugin(SCROLL_PLUGIN_ID, registry, config),\n reducer: scrollReducer,\n initialState: (coreState, config) => initialState(coreState, config)\n};\nexport {\n SCROLL_PLUGIN_ID,\n ScrollPlugin,\n ScrollPluginPackage,\n ScrollStrategy,\n getScrollerLayout,\n manifest\n};\n//# sourceMappingURL=index.js.map\n","import { useState, useEffect, useLayoutEffect } from \"react\";\nimport { useCapability, usePlugin } from \"@embedpdf/core/react\";\nimport { ScrollPlugin, ScrollStrategy } from \"@embedpdf/plugin-scroll\";\nexport * from \"@embedpdf/plugin-scroll\";\nimport { jsxs, jsx } from \"react/jsx-runtime\";\nconst useScrollPlugin = () => usePlugin(ScrollPlugin.id);\nconst useScrollCapability = () => useCapability(ScrollPlugin.id);\nconst useScroll = (documentId) => {\n const { provides } = useScrollCapability();\n const [currentPage, setCurrentPage] = useState(1);\n const [totalPages, setTotalPages] = useState(1);\n useEffect(() => {\n if (!provides || !documentId) return;\n const scope = provides.forDocument(documentId);\n setCurrentPage(scope.getCurrentPage());\n setTotalPages(scope.getTotalPages());\n return provides.onPageChange((event) => {\n if (event.documentId === documentId) {\n setCurrentPage(event.pageNumber);\n setTotalPages(event.totalPages);\n }\n });\n }, [provides, documentId]);\n return {\n // New format (preferred)\n provides: (provides == null ? void 0 : provides.forDocument(documentId)) ?? null,\n state: {\n currentPage,\n totalPages\n }\n };\n};\nfunction Scroller({ documentId, renderPage, ...props }) {\n const { plugin: scrollPlugin } = useScrollPlugin();\n const [layoutData, setLayoutData] = useState({ layout: null, docId: null });\n useEffect(() => {\n if (!scrollPlugin || !documentId) return;\n const unsubscribe = scrollPlugin.onScrollerData(documentId, (newLayout) => {\n setLayoutData({ layout: newLayout, docId: documentId });\n });\n return () => {\n unsubscribe();\n setLayoutData({ layout: null, docId: null });\n scrollPlugin.clearLayoutReady(documentId);\n };\n }, [scrollPlugin, documentId]);\n const scrollerLayout = layoutData.docId === documentId ? layoutData.layout : null;\n useLayoutEffect(() => {\n if (!scrollPlugin || !documentId || !scrollerLayout) return;\n scrollPlugin.setLayoutReady(documentId);\n }, [scrollPlugin, documentId, scrollerLayout]);\n if (!scrollerLayout) return null;\n return /* @__PURE__ */ jsxs(\n \"div\",\n {\n ...props,\n style: {\n width: `${scrollerLayout.totalWidth}px`,\n height: `${scrollerLayout.totalHeight}px`,\n position: \"relative\",\n boxSizing: \"border-box\",\n margin: \"0 auto\",\n ...scrollerLayout.strategy === ScrollStrategy.Horizontal && {\n display: \"flex\",\n flexDirection: \"row\"\n }\n },\n children: [\n /* @__PURE__ */ jsx(\n \"div\",\n {\n style: {\n ...scrollerLayout.strategy === ScrollStrategy.Horizontal ? {\n width: scrollerLayout.startSpacing,\n height: \"100%\",\n flexShrink: 0\n } : {\n height: scrollerLayout.startSpacing,\n width: \"100%\"\n }\n }\n }\n ),\n /* @__PURE__ */ jsx(\n \"div\",\n {\n style: {\n gap: scrollerLayout.pageGap,\n display: \"flex\",\n alignItems: \"center\",\n position: \"relative\",\n boxSizing: \"border-box\",\n ...scrollerLayout.strategy === ScrollStrategy.Horizontal ? {\n flexDirection: \"row\",\n minHeight: \"100%\"\n } : {\n flexDirection: \"column\",\n minWidth: \"fit-content\"\n }\n },\n children: scrollerLayout.items.map((item) => /* @__PURE__ */ jsx(\n \"div\",\n {\n style: {\n display: \"flex\",\n justifyContent: \"center\",\n gap: scrollerLayout.pageGap\n },\n children: item.pageLayouts.map((layout) => /* @__PURE__ */ jsx(\n \"div\",\n {\n style: {\n width: `${layout.rotatedWidth}px`,\n height: `${layout.rotatedHeight}px`,\n position: \"relative\",\n zIndex: layout.elevated ? 1 : void 0\n },\n children: renderPage({\n ...layout\n })\n },\n layout.pageNumber\n ))\n },\n item.pageNumbers[0]\n ))\n }\n ),\n /* @__PURE__ */ jsx(\n \"div\",\n {\n style: {\n ...scrollerLayout.strategy === ScrollStrategy.Horizontal ? {\n width: scrollerLayout.endSpacing,\n height: \"100%\",\n flexShrink: 0\n } : {\n height: scrollerLayout.endSpacing,\n width: \"100%\"\n }\n }\n }\n )\n ]\n }\n );\n}\nexport {\n Scroller,\n useScroll,\n useScrollCapability,\n useScrollPlugin\n};\n//# sourceMappingURL=index.js.map\n","import { BasePlugin } from \"@embedpdf/core\";\nconst _RenderPlugin = class _RenderPlugin extends BasePlugin {\n constructor(id, registry, config) {\n super(id, registry);\n this.config = config;\n }\n // No onDocumentLoadingStarted or onDocumentClosed needed!\n buildCapability() {\n return {\n // Active document operations\n renderPage: (options) => this.renderPage(options),\n renderPageRect: (options) => this.renderPageRect(options),\n renderPageRaw: (options) => this.renderPageRaw(options),\n renderPageRectRaw: (options) => this.renderPageRectRaw(options),\n // Document-scoped operations\n forDocument: (documentId) => this.createRenderScope(documentId)\n };\n }\n // ─────────────────────────────────────────────────────────\n // Document Scoping\n // ─────────────────────────────────────────────────────────\n createRenderScope(documentId) {\n return {\n renderPage: (options) => this.renderPage(options, documentId),\n renderPageRect: (options) => this.renderPageRect(options, documentId),\n renderPageRaw: (options) => this.renderPageRaw(options, documentId),\n renderPageRectRaw: (options) => this.renderPageRectRaw(options, documentId)\n };\n }\n // ─────────────────────────────────────────────────────────\n // Core Operations\n // ─────────────────────────────────────────────────────────\n renderPage({ pageIndex, options }, documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const coreDoc = this.coreState.core.documents[id];\n if (!(coreDoc == null ? void 0 : coreDoc.document)) {\n throw new Error(`Document ${id} not loaded`);\n }\n const page = coreDoc.document.pages.find((p) => p.index === pageIndex);\n if (!page) {\n throw new Error(`Page ${pageIndex} not found in document ${id}`);\n }\n const mergedOptions = {\n ...options ?? {},\n withForms: (options == null ? void 0 : options.withForms) ?? this.config.withForms ?? false,\n withAnnotations: (options == null ? void 0 : options.withAnnotations) ?? this.config.withAnnotations ?? false,\n imageType: (options == null ? void 0 : options.imageType) ?? this.config.defaultImageType ?? \"image/png\",\n imageQuality: (options == null ? void 0 : options.imageQuality) ?? this.config.defaultImageQuality ?? 0.92\n };\n return this.engine.renderPage(coreDoc.document, page, mergedOptions);\n }\n renderPageRect({ pageIndex, rect, options }, documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const coreDoc = this.coreState.core.documents[id];\n if (!(coreDoc == null ? void 0 : coreDoc.document)) {\n throw new Error(`Document ${id} not loaded`);\n }\n const page = coreDoc.document.pages.find((p) => p.index === pageIndex);\n if (!page) {\n throw new Error(`Page ${pageIndex} not found in document ${id}`);\n }\n const mergedOptions = {\n ...options ?? {},\n withForms: (options == null ? void 0 : options.withForms) ?? this.config.withForms ?? false,\n withAnnotations: (options == null ? void 0 : options.withAnnotations) ?? this.config.withAnnotations ?? false,\n imageType: (options == null ? void 0 : options.imageType) ?? this.config.defaultImageType ?? \"image/png\",\n imageQuality: (options == null ? void 0 : options.imageQuality) ?? this.config.defaultImageQuality ?? 0.92\n };\n return this.engine.renderPageRect(coreDoc.document, page, rect, mergedOptions);\n }\n // ─────────────────────────────────────────────────────────\n // Raw Rendering (returns ImageDataLike, skips encoding)\n // ─────────────────────────────────────────────────────────\n renderPageRaw({ pageIndex, options }, documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const coreDoc = this.coreState.core.documents[id];\n if (!(coreDoc == null ? void 0 : coreDoc.document)) {\n throw new Error(`Document ${id} not loaded`);\n }\n const page = coreDoc.document.pages.find((p) => p.index === pageIndex);\n if (!page) {\n throw new Error(`Page ${pageIndex} not found in document ${id}`);\n }\n const mergedOptions = {\n ...options ?? {},\n withForms: (options == null ? void 0 : options.withForms) ?? this.config.withForms ?? false,\n withAnnotations: (options == null ? void 0 : options.withAnnotations) ?? this.config.withAnnotations ?? false\n };\n return this.engine.renderPageRaw(coreDoc.document, page, mergedOptions);\n }\n renderPageRectRaw({ pageIndex, rect, options }, documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const coreDoc = this.coreState.core.documents[id];\n if (!(coreDoc == null ? void 0 : coreDoc.document)) {\n throw new Error(`Document ${id} not loaded`);\n }\n const page = coreDoc.document.pages.find((p) => p.index === pageIndex);\n if (!page) {\n throw new Error(`Page ${pageIndex} not found in document ${id}`);\n }\n const mergedOptions = {\n ...options ?? {},\n withForms: (options == null ? void 0 : options.withForms) ?? this.config.withForms ?? false,\n withAnnotations: (options == null ? void 0 : options.withAnnotations) ?? this.config.withAnnotations ?? false\n };\n return this.engine.renderPageRectRaw(coreDoc.document, page, rect, mergedOptions);\n }\n // ─────────────────────────────────────────────────────────\n // Lifecycle\n // ─────────────────────────────────────────────────────────\n async initialize(_config) {\n this.logger.info(\"RenderPlugin\", \"Initialize\", \"Render plugin initialized\");\n }\n async destroy() {\n super.destroy();\n }\n};\n_RenderPlugin.id = \"render\";\nlet RenderPlugin = _RenderPlugin;\nconst RENDER_PLUGIN_ID = \"render\";\nconst manifest = {\n id: RENDER_PLUGIN_ID,\n name: \"Render Plugin\",\n version: \"1.0.0\",\n provides: [\"render\"],\n requires: [],\n optional: [],\n defaultConfig: {}\n};\nconst RenderPluginPackage = {\n manifest,\n create: (registry, config) => new RenderPlugin(RENDER_PLUGIN_ID, registry, config),\n reducer: () => {\n },\n initialState: {}\n};\nexport {\n RenderPlugin,\n RenderPluginPackage\n};\n//# sourceMappingURL=index.js.map\n","import { jsx } from \"react/jsx-runtime\";\nimport { useState, useRef, useMemo, useEffect, Fragment } from \"react\";\nimport { ignore, PdfErrorCode } from \"@embedpdf/models\";\nimport { useCapability, usePlugin, useDocumentState } from \"@embedpdf/core/react\";\nimport { RenderPlugin } from \"@embedpdf/plugin-render\";\nexport * from \"@embedpdf/plugin-render\";\nconst useRenderPlugin = () => usePlugin(RenderPlugin.id);\nconst useRenderCapability = () => useCapability(RenderPlugin.id);\nfunction RenderLayer({\n documentId,\n pageIndex,\n scale: scaleOverride,\n dpr: dprOverride,\n style,\n ...props\n}) {\n const { provides: renderProvides } = useRenderCapability();\n const documentState = useDocumentState(documentId);\n const [imageUrl, setImageUrl] = useState(null);\n const urlRef = useRef(null);\n const refreshVersion = useMemo(() => {\n if (!documentState) return 0;\n return documentState.pageRefreshVersions[pageIndex] || 0;\n }, [documentState, pageIndex]);\n const actualScale = useMemo(() => {\n if (scaleOverride !== void 0) return scaleOverride;\n return (documentState == null ? void 0 : documentState.scale) ?? 1;\n }, [scaleOverride, documentState == null ? void 0 : documentState.scale]);\n const actualDpr = useMemo(() => {\n if (dprOverride !== void 0) return dprOverride;\n return window.devicePixelRatio;\n }, [dprOverride]);\n useEffect(() => {\n if (!renderProvides) return;\n const task = renderProvides.forDocument(documentId).renderPage({\n pageIndex,\n options: {\n scaleFactor: actualScale,\n dpr: actualDpr\n }\n });\n task.wait((blob) => {\n const url = URL.createObjectURL(blob);\n setImageUrl(url);\n urlRef.current = url;\n }, ignore);\n return () => {\n if (urlRef.current) {\n URL.revokeObjectURL(urlRef.current);\n urlRef.current = null;\n } else {\n task.abort({\n code: PdfErrorCode.Cancelled,\n message: \"canceled render task\"\n });\n }\n };\n }, [documentId, pageIndex, actualScale, actualDpr, renderProvides, refreshVersion]);\n const handleImageLoad = () => {\n if (urlRef.current) {\n URL.revokeObjectURL(urlRef.current);\n urlRef.current = null;\n }\n };\n return /* @__PURE__ */ jsx(Fragment, { children: imageUrl && /* @__PURE__ */ jsx(\n \"img\",\n {\n src: imageUrl,\n onLoad: handleImageLoad,\n ...props,\n style: {\n width: \"100%\",\n height: \"100%\",\n ...style || {}\n }\n }\n ) });\n}\nexport {\n RenderLayer,\n useRenderCapability,\n useRenderPlugin\n};\n//# sourceMappingURL=index.js.map\n","import { clamp, BasePlugin, createEmitter, createBehaviorEmitter, setScale } from \"@embedpdf/core\";\nimport { rotateRect } from \"@embedpdf/models\";\nvar ZoomMode = /* @__PURE__ */ ((ZoomMode2) => {\n ZoomMode2[\"Automatic\"] = \"automatic\";\n ZoomMode2[\"FitPage\"] = \"fit-page\";\n ZoomMode2[\"FitWidth\"] = \"fit-width\";\n return ZoomMode2;\n})(ZoomMode || {});\nvar VerticalZoomFocus = /* @__PURE__ */ ((VerticalZoomFocus2) => {\n VerticalZoomFocus2[VerticalZoomFocus2[\"Center\"] = 0] = \"Center\";\n VerticalZoomFocus2[VerticalZoomFocus2[\"Top\"] = 1] = \"Top\";\n return VerticalZoomFocus2;\n})(VerticalZoomFocus || {});\nconst ZOOM_PLUGIN_ID = \"zoom\";\nconst manifest = {\n id: ZOOM_PLUGIN_ID,\n name: \"Zoom Plugin\",\n version: \"1.0.0\",\n provides: [\"zoom\"],\n requires: [\"viewport\", \"scroll\"],\n optional: [\"interaction-manager\", \"spread\"],\n defaultConfig: {\n defaultZoomLevel: ZoomMode.Automatic,\n minZoom: 0.2,\n maxZoom: 60,\n zoomStep: 0.1,\n zoomRanges: [\n {\n min: 0.2,\n max: 0.5,\n step: 0.05\n },\n {\n min: 0.5,\n max: 1,\n step: 0.1\n },\n {\n min: 1,\n max: 2,\n step: 0.2\n },\n {\n min: 2,\n max: 4,\n step: 0.4\n },\n {\n min: 4,\n max: 10,\n step: 0.8\n },\n {\n min: 10,\n max: 20,\n step: 1.6\n },\n {\n min: 20,\n max: 40,\n step: 3.2\n },\n {\n min: 40,\n max: 60,\n step: 6.4\n }\n ],\n presets: [\n {\n name: \"Fit Page\",\n value: ZoomMode.FitPage\n },\n {\n name: \"Fit Width\",\n value: ZoomMode.FitWidth\n },\n {\n name: \"Automatic\",\n value: ZoomMode.Automatic\n },\n {\n name: \"25%\",\n value: 0.25\n },\n {\n name: \"50%\",\n value: 0.5\n },\n {\n name: \"100%\",\n value: 1\n },\n {\n name: \"125%\",\n value: 1.25\n },\n {\n name: \"150%\",\n value: 1.5\n },\n {\n name: \"200%\",\n value: 2\n },\n {\n name: \"400%\",\n value: 4\n },\n {\n name: \"800%\",\n value: 8\n },\n {\n name: \"1600%\",\n value: 16\n }\n ]\n }\n};\nconst INIT_ZOOM_STATE = \"ZOOM/INIT_STATE\";\nconst CLEANUP_ZOOM_STATE = \"ZOOM/CLEANUP_STATE\";\nconst SET_ACTIVE_DOCUMENT = \"ZOOM/SET_ACTIVE_DOCUMENT\";\nconst SET_ZOOM_LEVEL = \"ZOOM/SET_ZOOM_LEVEL\";\nconst SET_MARQUEE_ZOOM_ACTIVE = \"ZOOM/SET_MARQUEE_ZOOM_ACTIVE\";\nfunction initZoomState(documentId, state) {\n return { type: INIT_ZOOM_STATE, payload: { documentId, state } };\n}\nfunction cleanupZoomState(documentId) {\n return { type: CLEANUP_ZOOM_STATE, payload: documentId };\n}\nfunction setZoomLevel(documentId, zoomLevel, currentZoomLevel) {\n return { type: SET_ZOOM_LEVEL, payload: { documentId, zoomLevel, currentZoomLevel } };\n}\nfunction setMarqueeZoomActive(documentId, isActive) {\n return { type: SET_MARQUEE_ZOOM_ACTIVE, payload: { documentId, isActive } };\n}\nconst initialDocumentState = {\n zoomLevel: ZoomMode.Automatic,\n currentZoomLevel: 1,\n isMarqueeZoomActive: false\n};\nconst initialState = {\n documents: {},\n activeDocumentId: null\n};\nconst zoomReducer = (state = initialState, action) => {\n switch (action.type) {\n case INIT_ZOOM_STATE: {\n const { documentId, state: docState } = action.payload;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: docState\n },\n // Set as active if no active document\n activeDocumentId: state.activeDocumentId ?? documentId\n };\n }\n case CLEANUP_ZOOM_STATE: {\n const documentId = action.payload;\n const { [documentId]: removed, ...remainingDocs } = state.documents;\n return {\n ...state,\n documents: remainingDocs,\n activeDocumentId: state.activeDocumentId === documentId ? null : state.activeDocumentId\n };\n }\n case SET_ACTIVE_DOCUMENT: {\n return {\n ...state,\n activeDocumentId: action.payload\n };\n }\n case SET_ZOOM_LEVEL: {\n const { documentId, zoomLevel, currentZoomLevel } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...docState,\n zoomLevel,\n currentZoomLevel\n }\n }\n };\n }\n case SET_MARQUEE_ZOOM_ACTIVE: {\n const { documentId, isActive } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...docState,\n isMarqueeZoomActive: isActive\n }\n }\n };\n }\n default:\n return state;\n }\n};\nfunction createMarqueeHandler(opts) {\n const { pageSize, scale, minDragPx = 5, onPreview, onCommit, onSmallDrag } = opts;\n let start = null;\n let last = null;\n return {\n onPointerDown: (pos, evt) => {\n var _a;\n start = pos;\n last = { origin: { x: pos.x, y: pos.y }, size: { width: 0, height: 0 } };\n onPreview == null ? void 0 : onPreview(last);\n (_a = evt.setPointerCapture) == null ? void 0 : _a.call(evt);\n },\n onPointerMove: (pos) => {\n if (!start) return;\n const x = clamp(pos.x, 0, pageSize.width);\n const y = clamp(pos.y, 0, pageSize.height);\n last = {\n origin: { x: Math.min(start.x, x), y: Math.min(start.y, y) },\n size: { width: Math.abs(x - start.x), height: Math.abs(y - start.y) }\n };\n onPreview == null ? void 0 : onPreview(last);\n },\n onPointerUp: (_pos, evt) => {\n var _a;\n if (last) {\n const dragPx = Math.max(last.size.width, last.size.height) * scale;\n if (dragPx > minDragPx) {\n onCommit == null ? void 0 : onCommit(last);\n } else {\n onSmallDrag == null ? void 0 : onSmallDrag();\n }\n }\n start = null;\n last = null;\n onPreview == null ? void 0 : onPreview(null);\n (_a = evt.releasePointerCapture) == null ? void 0 : _a.call(evt);\n },\n onPointerCancel: (_pos, evt) => {\n var _a;\n start = null;\n last = null;\n onPreview == null ? void 0 : onPreview(null);\n (_a = evt.releasePointerCapture) == null ? void 0 : _a.call(evt);\n }\n };\n}\nconst _ZoomPlugin = class _ZoomPlugin extends BasePlugin {\n constructor(id, registry, cfg) {\n var _a, _b, _c;\n super(id, registry);\n this.zoom$ = createEmitter();\n this.state$ = createBehaviorEmitter();\n this.viewportPlugin = registry.getPlugin(\"viewport\");\n this.viewport = this.viewportPlugin.provides();\n this.scroll = registry.getPlugin(\"scroll\").provides();\n const interactionManager = registry.getPlugin(\"interaction-manager\");\n this.interactionManager = (interactionManager == null ? void 0 : interactionManager.provides()) ?? null;\n const spread = registry.getPlugin(\"spread\");\n this.spread = (spread == null ? void 0 : spread.provides()) ?? null;\n this.minZoom = cfg.minZoom ?? 0.25;\n this.maxZoom = cfg.maxZoom ?? 10;\n this.zoomStep = cfg.zoomStep ?? 0.1;\n this.defaultZoomLevel = cfg.defaultZoomLevel;\n this.presets = cfg.presets ?? [];\n this.zoomRanges = this.normalizeRanges(cfg.zoomRanges ?? []);\n this.viewport.onViewportResize(\n (event) => this.recalcAuto(event.documentId, VerticalZoomFocus.Top),\n {\n mode: \"debounce\",\n wait: 150,\n keyExtractor: (event) => event.documentId\n }\n );\n (_a = this.spread) == null ? void 0 : _a.onSpreadChange((event) => {\n this.recalcAuto(event.documentId, VerticalZoomFocus.Top);\n });\n (_b = this.interactionManager) == null ? void 0 : _b.registerMode({\n id: \"marqueeZoom\",\n scope: \"page\",\n exclusive: true,\n cursor: \"zoom-in\"\n });\n (_c = this.interactionManager) == null ? void 0 : _c.onModeChange((state) => {\n const isMarqueeActive = state.activeMode === \"marqueeZoom\";\n const docState = this.getDocumentState(state.documentId);\n if (docState && docState.isMarqueeZoomActive !== isMarqueeActive) {\n this.dispatch(setMarqueeZoomActive(state.documentId, isMarqueeActive));\n }\n });\n }\n // ─────────────────────────────────────────────────────────\n // Document Lifecycle Hooks (from BasePlugin)\n // ─────────────────────────────────────────────────────────\n onDocumentLoadingStarted(documentId) {\n this.viewport.gate(\"zoom\", documentId);\n const docState = {\n ...initialDocumentState,\n zoomLevel: this.defaultZoomLevel\n };\n this.dispatch(initZoomState(documentId, docState));\n this.logger.debug(\n \"ZoomPlugin\",\n \"DocumentOpened\",\n `Initialized zoom state for document: ${documentId}`\n );\n }\n onDocumentLoaded(documentId) {\n this.recalcAuto(documentId, VerticalZoomFocus.Top);\n }\n onDocumentClosed(documentId) {\n this.dispatch(cleanupZoomState(documentId));\n this.logger.debug(\n \"ZoomPlugin\",\n \"DocumentClosed\",\n `Cleaned up zoom state for document: ${documentId}`\n );\n }\n onRotationChanged(documentId) {\n this.recalcAuto(documentId, VerticalZoomFocus.Top);\n }\n /*\n protected override onPagesChanged(documentId: string): void {\n // Recalculate auto modes when pages change\n this.recalcAuto(documentId, VerticalZoomFocus.Top);\n }*/\n // ─────────────────────────────────────────────────────────\n // Capability\n // ─────────────────────────────────────────────────────────\n buildCapability() {\n return {\n // Active document operations\n requestZoom: (level, c) => this.requestZoom(level, c),\n requestZoomBy: (d, c) => this.requestZoomBy(d, c),\n zoomIn: () => this.zoomIn(),\n zoomOut: () => this.zoomOut(),\n zoomToArea: (pageIndex, rect) => this.zoomToArea(pageIndex, rect),\n enableMarqueeZoom: () => this.enableMarqueeZoom(),\n disableMarqueeZoom: () => this.disableMarqueeZoom(),\n toggleMarqueeZoom: () => this.toggleMarqueeZoom(),\n isMarqueeZoomActive: () => this.isMarqueeZoomActive(),\n getState: () => this.getDocumentStateOrThrow(),\n // Document-scoped operations\n forDocument: (documentId) => this.createZoomScope(documentId),\n // Global\n registerMarqueeOnPage: (opts) => this.registerMarqueeOnPage(opts),\n getPresets: () => this.presets,\n // Events\n onZoomChange: this.zoom$.on,\n onStateChange: this.state$.on\n };\n }\n // ─────────────────────────────────────────────────────────\n // Document Scoping\n // ─────────────────────────────────────────────────────────\n createZoomScope(documentId) {\n return {\n requestZoom: (level, c) => this.requestZoom(level, c, documentId),\n requestZoomBy: (d, c) => this.requestZoomBy(d, c, documentId),\n zoomIn: () => this.zoomIn(documentId),\n zoomOut: () => this.zoomOut(documentId),\n zoomToArea: (pageIndex, rect) => this.zoomToArea(pageIndex, rect, documentId),\n enableMarqueeZoom: () => this.enableMarqueeZoom(documentId),\n disableMarqueeZoom: () => this.disableMarqueeZoom(documentId),\n toggleMarqueeZoom: () => this.toggleMarqueeZoom(documentId),\n isMarqueeZoomActive: () => this.isMarqueeZoomActive(documentId),\n getState: () => this.getDocumentStateOrThrow(documentId),\n onZoomChange: (listener) => this.zoom$.on((event) => {\n if (event.documentId === documentId) listener(event);\n }),\n onStateChange: (listener) => this.state$.on((event) => {\n if (event.documentId === documentId) listener(event.state);\n })\n };\n }\n // ─────────────────────────────────────────────────────────\n // State Helpers\n // ─────────────────────────────────────────────────────────\n getDocumentState(documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n return this.state.documents[id] ?? null;\n }\n getDocumentStateOrThrow(documentId) {\n const state = this.getDocumentState(documentId);\n if (!state) {\n throw new Error(`Zoom state not found for document: ${documentId ?? \"active\"}`);\n }\n return state;\n }\n // ─────────────────────────────────────────────────────────\n // Core Operations\n // ─────────────────────────────────────────────────────────\n requestZoom(level, center, documentId) {\n this.handleRequest({ level, center }, documentId);\n }\n requestZoomBy(delta, center, documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const docState = this.getDocumentStateOrThrow(id);\n const cur = docState.currentZoomLevel;\n const target = this.toZoom(cur + delta);\n this.handleRequest({ level: target, center }, id);\n }\n zoomIn(documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const docState = this.getDocumentStateOrThrow(id);\n const cur = docState.currentZoomLevel;\n this.handleRequest({ level: cur, delta: this.stepFor(cur) }, id);\n }\n zoomOut(documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const docState = this.getDocumentStateOrThrow(id);\n const cur = docState.currentZoomLevel;\n this.handleRequest({ level: cur, delta: -this.stepFor(cur) }, id);\n }\n zoomToArea(pageIndex, rect, documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n this.handleZoomToArea(id, pageIndex, rect);\n }\n enableMarqueeZoom(documentId) {\n var _a;\n const id = documentId ?? this.getActiveDocumentId();\n (_a = this.interactionManager) == null ? void 0 : _a.forDocument(id).activate(\"marqueeZoom\");\n }\n disableMarqueeZoom(documentId) {\n var _a;\n const id = documentId ?? this.getActiveDocumentId();\n (_a = this.interactionManager) == null ? void 0 : _a.forDocument(id).activateDefaultMode();\n }\n toggleMarqueeZoom(documentId) {\n var _a;\n const id = documentId ?? this.getActiveDocumentId();\n const scope = (_a = this.interactionManager) == null ? void 0 : _a.forDocument(id);\n if ((scope == null ? void 0 : scope.getActiveMode()) === \"marqueeZoom\") {\n scope.activateDefaultMode();\n } else {\n scope == null ? void 0 : scope.activate(\"marqueeZoom\");\n }\n }\n isMarqueeZoomActive(documentId) {\n var _a;\n const id = documentId ?? this.getActiveDocumentId();\n return ((_a = this.interactionManager) == null ? void 0 : _a.forDocument(id).getActiveMode()) === \"marqueeZoom\";\n }\n // ─────────────────────────────────────────────────────────\n // Main Zoom Logic\n // ─────────────────────────────────────────────────────────\n handleRequest({ level, delta = 0, center, focus = VerticalZoomFocus.Center, align = \"keep\" }, documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const docState = this.getDocumentStateOrThrow(id);\n const coreDoc = this.coreState.core.documents[id];\n if (!coreDoc) return;\n const viewport = this.viewport.forDocument(id);\n const metrics = viewport.getMetrics();\n const oldZoom = docState.currentZoomLevel;\n if (metrics.clientWidth === 0 || metrics.clientHeight === 0) {\n return;\n }\n const base = typeof level === \"number\" ? level : this.computeZoomForMode(id, level, metrics);\n if (base === false) return;\n const exactZoom = clamp(base + delta, this.minZoom, this.maxZoom);\n const newZoom = Math.floor(exactZoom * 1e3) / 1e3;\n const focusPoint = center ?? {\n vx: metrics.clientWidth / 2,\n vy: focus === VerticalZoomFocus.Top ? 0 : metrics.clientHeight / 2\n };\n const { desiredScrollLeft, desiredScrollTop } = this.computeScrollForZoomChange(\n id,\n metrics,\n oldZoom,\n newZoom,\n focusPoint,\n align\n );\n if (!isNaN(desiredScrollLeft) && !isNaN(desiredScrollTop)) {\n this.viewportPlugin.setViewportScrollMetrics(id, {\n scrollLeft: desiredScrollLeft,\n scrollTop: desiredScrollTop\n });\n }\n this.dispatch(setZoomLevel(id, typeof level === \"number\" ? newZoom : level, newZoom));\n this.dispatchCoreAction(setScale(newZoom, id));\n if (this.viewport.isGated(id)) {\n this.viewport.releaseGate(\"zoom\", id);\n }\n viewport.scrollTo({\n x: desiredScrollLeft,\n y: desiredScrollTop,\n behavior: \"instant\"\n });\n const evt = {\n documentId: id,\n oldZoom,\n newZoom,\n level,\n center: focusPoint,\n desiredScrollLeft,\n desiredScrollTop,\n viewport: metrics\n };\n this.zoom$.emit(evt);\n }\n computeZoomForMode(documentId, mode, vp) {\n const coreDoc = this.coreState.core.documents[documentId];\n if (!coreDoc) return false;\n const scrollScope = this.scroll.forDocument(documentId);\n const pgGap = scrollScope ? this.scroll.getPageGap() : 0;\n const vpGap = this.viewport.getViewportGap();\n const spreads = scrollScope.getSpreadPagesWithRotatedSize();\n if (!spreads.length) return false;\n if (vp.clientWidth === 0 || vp.clientHeight === 0) return false;\n const availableWidth = vp.clientWidth - 2 * vpGap;\n const availableHeight = vp.clientHeight - 2 * vpGap;\n if (availableWidth <= 0 || availableHeight <= 0) return false;\n let maxContentW = 0, maxContentH = 0;\n spreads.forEach((spread) => {\n const contentW = spread.reduce((s, p, i) => s + p.rotatedSize.width + (i ? pgGap : 0), 0);\n const contentH = Math.max(...spread.map((p) => p.rotatedSize.height));\n maxContentW = Math.max(maxContentW, contentW);\n maxContentH = Math.max(maxContentH, contentH);\n });\n switch (mode) {\n case ZoomMode.FitWidth:\n return availableWidth / maxContentW;\n case ZoomMode.FitPage:\n return Math.min(availableWidth / maxContentW, availableHeight / maxContentH);\n case ZoomMode.Automatic:\n return Math.min(availableWidth / maxContentW, 1);\n default:\n return 1;\n }\n }\n computeScrollForZoomChange(documentId, vp, oldZoom, newZoom, focus, align = \"keep\") {\n const scrollScope = this.scroll.forDocument(documentId);\n const layout = scrollScope.getLayout();\n const vpGap = this.viewport.getViewportGap();\n const contentW = layout.totalContentSize.width;\n const contentH = layout.totalContentSize.height;\n const availableWidth = vp.clientWidth - 2 * vpGap;\n const availableHeight = vp.clientHeight - 2 * vpGap;\n const off = (availableSpace, cw, zoom) => cw * zoom < availableSpace ? (availableSpace - cw * zoom) / 2 : 0;\n const offXold = off(availableWidth, contentW, oldZoom);\n const offYold = off(availableHeight, contentH, oldZoom);\n const offXnew = off(availableWidth, contentW, newZoom);\n const offYnew = off(availableHeight, contentH, newZoom);\n const cx = (vp.scrollLeft + focus.vx - vpGap - offXold) / oldZoom;\n const cy = (vp.scrollTop + focus.vy - vpGap - offYold) / oldZoom;\n const baseLeft = cx * newZoom + vpGap + offXnew;\n const baseTop = cy * newZoom + vpGap + offYnew;\n const desiredScrollLeft = align === \"center\" ? baseLeft - vp.clientWidth / 2 : baseLeft - focus.vx;\n const desiredScrollTop = align === \"center\" ? baseTop - vp.clientHeight / 2 : baseTop - focus.vy;\n return {\n desiredScrollLeft: Math.max(0, desiredScrollLeft),\n desiredScrollTop: Math.max(0, desiredScrollTop)\n };\n }\n handleZoomToArea(documentId, pageIndex, rect) {\n const coreDoc = this.coreState.core.documents[documentId];\n if (!coreDoc) return;\n const rotation = coreDoc.rotation;\n const viewport = this.viewport.forDocument(documentId);\n const vp = viewport.getMetrics();\n const vpGap = this.viewport.getViewportGap();\n const docState = this.getDocumentStateOrThrow(documentId);\n const oldZ = docState.currentZoomLevel;\n const availableW = vp.clientWidth - 2 * vpGap;\n const availableH = vp.clientHeight - 2 * vpGap;\n const scrollScope = this.scroll.forDocument(documentId);\n const layout = scrollScope.getLayout();\n const vItem = layout.virtualItems.find(\n (it) => it.pageLayouts.some((p) => p.pageIndex === pageIndex)\n );\n if (!vItem) return;\n const pageRel = vItem.pageLayouts.find((p) => p.pageIndex === pageIndex);\n const rotatedRect = rotateRect(\n { width: pageRel.width, height: pageRel.height },\n rect,\n rotation\n );\n const targetZoom = this.toZoom(\n Math.min(availableW / rotatedRect.size.width, availableH / rotatedRect.size.height)\n );\n const pageAbsX = vItem.x + pageRel.x;\n const pageAbsY = vItem.y + pageRel.y;\n const cxContent = pageAbsX + rotatedRect.origin.x + rotatedRect.size.width / 2;\n const cyContent = pageAbsY + rotatedRect.origin.y + rotatedRect.size.height / 2;\n const off = (avail, cw, z) => cw * z < avail ? (avail - cw * z) / 2 : 0;\n const offXold = off(availableW, layout.totalContentSize.width, oldZ);\n const offYold = off(availableH, layout.totalContentSize.height, oldZ);\n const centerVX = vpGap + offXold + cxContent * oldZ - vp.scrollLeft;\n const centerVY = vpGap + offYold + cyContent * oldZ - vp.scrollTop;\n this.handleRequest(\n {\n level: targetZoom,\n center: { vx: centerVX, vy: centerVY },\n align: \"center\"\n },\n documentId\n );\n }\n recalcAuto(documentId, focus) {\n const docState = this.getDocumentState(documentId);\n if (!docState) return;\n if (docState.zoomLevel === ZoomMode.Automatic || docState.zoomLevel === ZoomMode.FitPage || docState.zoomLevel === ZoomMode.FitWidth) {\n this.handleRequest({ level: docState.zoomLevel, focus }, documentId);\n }\n }\n // ─────────────────────────────────────────────────────────\n // Helpers\n // ─────────────────────────────────────────────────────────\n normalizeRanges(ranges) {\n return [...ranges].filter((r) => r.step > 0 && r.max > r.min).sort((a, b) => a.min - b.min);\n }\n stepFor(zoom) {\n const r = this.zoomRanges.find((r2) => zoom >= r2.min && zoom < r2.max);\n return r ? r.step : this.zoomStep;\n }\n toZoom(v) {\n return parseFloat(clamp(v, this.minZoom, this.maxZoom).toFixed(2));\n }\n // ─────────────────────────────────────────────────────────\n // Marquee Zoom\n // ─────────────────────────────────────────────────────────\n registerMarqueeOnPage(opts) {\n if (!this.interactionManager) {\n this.logger.warn(\n \"ZoomPlugin\",\n \"MissingDependency\",\n \"Interaction manager plugin not loaded, marquee zoom disabled\"\n );\n return () => {\n };\n }\n const coreDoc = this.coreState.core.documents[opts.documentId];\n if (!coreDoc || !coreDoc.document) {\n this.logger.warn(\"ZoomPlugin\", \"DocumentNotFound\", \"Document not found\");\n return () => {\n };\n }\n const page = coreDoc.document.pages[opts.pageIndex];\n if (!page) {\n this.logger.warn(\"ZoomPlugin\", \"PageNotFound\", `Page ${opts.pageIndex} not found`);\n return () => {\n };\n }\n const handlers = createMarqueeHandler({\n pageSize: page.size,\n scale: opts.scale,\n onPreview: opts.callback.onPreview,\n onCommit: (rect) => {\n var _a, _b;\n this.zoomToArea(opts.pageIndex, rect, opts.documentId);\n (_b = (_a = opts.callback).onCommit) == null ? void 0 : _b.call(_a, rect);\n },\n onSmallDrag: () => {\n var _a, _b;\n this.zoomIn(opts.documentId);\n (_b = (_a = opts.callback).onSmallDrag) == null ? void 0 : _b.call(_a);\n }\n });\n const off = this.interactionManager.registerHandlers({\n documentId: opts.documentId,\n modeId: \"marqueeZoom\",\n handlers,\n pageIndex: opts.pageIndex\n });\n return off;\n }\n // ─────────────────────────────────────────────────────────\n // Store Update Handlers\n // ─────────────────────────────────────────────────────────\n onStoreUpdated(prevState, newState) {\n for (const documentId in newState.documents) {\n const prevDoc = prevState.documents[documentId];\n const newDoc = newState.documents[documentId];\n if (prevDoc && newDoc && (prevDoc.currentZoomLevel !== newDoc.currentZoomLevel || prevDoc.zoomLevel !== newDoc.zoomLevel || prevDoc.isMarqueeZoomActive !== newDoc.isMarqueeZoomActive)) {\n this.state$.emit({\n documentId,\n state: newDoc\n });\n }\n }\n }\n // ─────────────────────────────────────────────────────────\n // Lifecycle\n // ─────────────────────────────────────────────────────────\n async initialize() {\n this.logger.info(\"ZoomPlugin\", \"Initialize\", \"Zoom plugin initialized\");\n }\n async destroy() {\n this.zoom$.clear();\n this.state$.clear();\n super.destroy();\n }\n};\n_ZoomPlugin.id = \"zoom\";\nlet ZoomPlugin = _ZoomPlugin;\nconst ZoomPluginPackage = {\n manifest,\n create: (registry, config) => new ZoomPlugin(ZOOM_PLUGIN_ID, registry, config),\n reducer: zoomReducer,\n initialState\n};\nexport {\n VerticalZoomFocus,\n ZOOM_PLUGIN_ID,\n ZoomMode,\n ZoomPlugin,\n ZoomPluginPackage,\n initialDocumentState,\n initialState,\n manifest\n};\n//# sourceMappingURL=index.js.map\n","import { useCapability, usePlugin, useDocumentState } from \"@embedpdf/core/react\";\nimport { initialDocumentState, ZoomPlugin } from \"@embedpdf/plugin-zoom\";\nexport * from \"@embedpdf/plugin-zoom\";\nimport { useState, useEffect, useRef, useLayoutEffect, useMemo } from \"react\";\nimport { useViewportElement } from \"@embedpdf/plugin-viewport/react\";\nimport { jsx } from \"react/jsx-runtime\";\nconst useZoomCapability = () => useCapability(ZoomPlugin.id);\nconst useZoomPlugin = () => usePlugin(ZoomPlugin.id);\nconst useZoom = (documentId) => {\n const { provides } = useZoomCapability();\n const [state, setState] = useState(initialDocumentState);\n useEffect(() => {\n if (!provides) return;\n const scope = provides.forDocument(documentId);\n setState(scope.getState());\n return scope.onStateChange((newState) => {\n setState(newState);\n });\n }, [provides, documentId]);\n return {\n state,\n provides: (provides == null ? void 0 : provides.forDocument(documentId)) ?? null\n };\n};\nfunction getTouchDistance(touches) {\n const [t1, t2] = [touches[0], touches[1]];\n const dx = t2.clientX - t1.clientX;\n const dy = t2.clientY - t1.clientY;\n return Math.hypot(dx, dy);\n}\nfunction getTouchCenter(touches) {\n const [t1, t2] = [touches[0], touches[1]];\n return {\n x: (t1.clientX + t2.clientX) / 2,\n y: (t1.clientY + t2.clientY) / 2\n };\n}\nfunction setupZoomGestures({\n element,\n container,\n documentId,\n zoomProvides,\n viewportGap = 0,\n options = {}\n}) {\n const { enablePinch = true, enableWheel = true } = options;\n if (typeof window === \"undefined\") {\n return () => {\n };\n }\n const zoomScope = zoomProvides.forDocument(documentId);\n const getState = () => zoomScope.getState();\n let initialZoom = 0;\n let currentScale = 1;\n let isPinching = false;\n let initialDistance = 0;\n let wheelZoomTimeout = null;\n let accumulatedWheelScale = 1;\n let initialElementWidth = 0;\n let initialElementHeight = 0;\n let initialElementLeft = 0;\n let initialElementTop = 0;\n let containerRectWidth = 0;\n let containerRectHeight = 0;\n let layoutWidth = 0;\n let layoutCenterX = 0;\n let pointerLocalY = 0;\n let pointerContainerX = 0;\n let pointerContainerY = 0;\n let currentGap = 0;\n let pivotLocalX = 0;\n const clamp = (val, min, max) => Math.min(Math.max(val, min), max);\n const updateMargin = () => {\n const availableWidth = container.clientWidth - 2 * viewportGap;\n const elementWidth = element.offsetWidth;\n const newMargin = elementWidth < availableWidth ? (availableWidth - elementWidth) / 2 : 0;\n element.style.marginLeft = `${newMargin}px`;\n };\n const calculateTransform = (scale) => {\n const finalWidth = initialElementWidth * scale;\n const finalHeight = initialElementHeight * scale;\n let ty = pointerLocalY * (1 - scale);\n const targetX = layoutCenterX - finalWidth / 2;\n const txCenter = targetX - initialElementLeft;\n const txMouse = pointerContainerX - pivotLocalX * scale - initialElementLeft;\n const overflow = Math.max(0, finalWidth - layoutWidth);\n const blendRange = layoutWidth * 0.3;\n const blend = Math.min(1, overflow / blendRange);\n let tx = txCenter + (txMouse - txCenter) * blend;\n const safeHeight = containerRectHeight - currentGap * 2;\n if (finalHeight > safeHeight) {\n const currentTop = initialElementTop + ty;\n const maxTop = currentGap;\n const minTop = containerRectHeight - currentGap - finalHeight;\n const constrainedTop = clamp(currentTop, minTop, maxTop);\n ty = constrainedTop - initialElementTop;\n }\n const safeWidth = containerRectWidth - currentGap * 2;\n if (finalWidth > safeWidth) {\n const currentLeft = initialElementLeft + tx;\n const maxLeft = currentGap;\n const minLeft = containerRectWidth - currentGap - finalWidth;\n const constrainedLeft = clamp(currentLeft, minLeft, maxLeft);\n tx = constrainedLeft - initialElementLeft;\n }\n return { tx, ty, blend, finalWidth };\n };\n const updateTransform = (scale) => {\n currentScale = scale;\n const { tx, ty } = calculateTransform(scale);\n element.style.transformOrigin = \"0 0\";\n element.style.transform = `translate(${tx}px, ${ty}px) scale(${scale})`;\n };\n const resetTransform = () => {\n element.style.transform = \"none\";\n element.style.transformOrigin = \"0 0\";\n currentScale = 1;\n };\n const commitZoom = () => {\n const { tx, finalWidth } = calculateTransform(currentScale);\n const delta = (currentScale - 1) * initialZoom;\n let anchorX;\n let anchorY = pointerContainerY;\n if (finalWidth <= layoutWidth) {\n anchorX = layoutCenterX;\n } else {\n const scaleDiff = 1 - currentScale;\n anchorX = Math.abs(scaleDiff) > 1e-3 ? initialElementLeft + tx / scaleDiff : pointerContainerX;\n }\n zoomScope.requestZoomBy(delta, { vx: anchorX, vy: anchorY });\n resetTransform();\n initialZoom = 0;\n };\n const initializeGestureState = (clientX, clientY) => {\n const containerRect = container.getBoundingClientRect();\n const innerRect = element.getBoundingClientRect();\n currentGap = viewportGap;\n initialElementWidth = innerRect.width;\n initialElementHeight = innerRect.height;\n initialElementLeft = innerRect.left - containerRect.left;\n initialElementTop = innerRect.top - containerRect.top;\n containerRectWidth = containerRect.width;\n containerRectHeight = containerRect.height;\n layoutWidth = container.clientWidth;\n layoutCenterX = container.clientLeft + layoutWidth / 2;\n const rawPointerLocalX = clientX - innerRect.left;\n pointerLocalY = clientY - innerRect.top;\n pointerContainerX = clientX - containerRect.left;\n pointerContainerY = clientY - containerRect.top;\n if (initialElementWidth < layoutWidth) {\n pivotLocalX = pointerContainerX * initialElementWidth / layoutWidth;\n } else {\n pivotLocalX = rawPointerLocalX;\n }\n };\n const handleTouchStart = (e) => {\n if (e.touches.length !== 2) return;\n isPinching = true;\n initialZoom = getState().currentZoomLevel;\n initialDistance = getTouchDistance(e.touches);\n const center = getTouchCenter(e.touches);\n initializeGestureState(center.x, center.y);\n e.preventDefault();\n };\n const handleTouchMove = (e) => {\n if (!isPinching || e.touches.length !== 2) return;\n const currentDistance = getTouchDistance(e.touches);\n const scale = currentDistance / initialDistance;\n updateTransform(scale);\n e.preventDefault();\n };\n const handleTouchEnd = (e) => {\n if (!isPinching) return;\n if (e.touches.length >= 2) return;\n isPinching = false;\n commitZoom();\n };\n const handleWheel = (e) => {\n if (!e.ctrlKey && !e.metaKey) return;\n e.preventDefault();\n if (wheelZoomTimeout === null) {\n initialZoom = getState().currentZoomLevel;\n accumulatedWheelScale = 1;\n initializeGestureState(e.clientX, e.clientY);\n } else {\n clearTimeout(wheelZoomTimeout);\n }\n const zoomFactor = 1 - e.deltaY * 0.01;\n accumulatedWheelScale *= zoomFactor;\n accumulatedWheelScale = Math.max(0.1, Math.min(10, accumulatedWheelScale));\n updateTransform(accumulatedWheelScale);\n wheelZoomTimeout = setTimeout(() => {\n wheelZoomTimeout = null;\n commitZoom();\n accumulatedWheelScale = 1;\n }, 150);\n };\n const unsubZoom = zoomScope.onStateChange(() => updateMargin());\n const resizeObserver = new ResizeObserver(() => updateMargin());\n resizeObserver.observe(element);\n resizeObserver.observe(container);\n updateMargin();\n if (enablePinch) {\n container.addEventListener(\"touchstart\", handleTouchStart, { passive: false });\n container.addEventListener(\"touchmove\", handleTouchMove, { passive: false });\n container.addEventListener(\"touchend\", handleTouchEnd);\n container.addEventListener(\"touchcancel\", handleTouchEnd);\n }\n if (enableWheel) {\n container.addEventListener(\"wheel\", handleWheel, { passive: false });\n }\n return () => {\n if (enablePinch) {\n container.removeEventListener(\"touchstart\", handleTouchStart);\n container.removeEventListener(\"touchmove\", handleTouchMove);\n container.removeEventListener(\"touchend\", handleTouchEnd);\n container.removeEventListener(\"touchcancel\", handleTouchEnd);\n }\n if (enableWheel) {\n container.removeEventListener(\"wheel\", handleWheel);\n }\n if (wheelZoomTimeout) {\n clearTimeout(wheelZoomTimeout);\n }\n unsubZoom();\n resizeObserver.disconnect();\n resetTransform();\n element.style.marginLeft = \"\";\n };\n}\nfunction useZoomGesture(documentId, options = {}) {\n const { provides: viewportProvides } = useCapability(\"viewport\");\n const { provides: zoomProvides } = useZoomCapability();\n const viewportElementRef = useViewportElement();\n const elementRef = useRef(null);\n useLayoutEffect(() => {\n const element = elementRef.current;\n const container = viewportElementRef == null ? void 0 : viewportElementRef.current;\n if (!element || !container || !zoomProvides) {\n return;\n }\n return setupZoomGestures({\n element,\n container,\n documentId,\n zoomProvides,\n viewportGap: (viewportProvides == null ? void 0 : viewportProvides.getViewportGap()) || 0,\n options\n });\n }, [\n viewportProvides,\n zoomProvides,\n documentId,\n viewportElementRef,\n options.enablePinch,\n options.enableWheel\n ]);\n return { elementRef };\n}\nfunction ZoomGestureWrapper({\n children,\n documentId,\n style,\n enablePinch = true,\n enableWheel = true,\n ...props\n}) {\n const options = useMemo(\n () => ({ enablePinch, enableWheel }),\n [enablePinch, enableWheel]\n );\n const { elementRef } = useZoomGesture(documentId, options);\n return /* @__PURE__ */ jsx(\n \"div\",\n {\n ref: elementRef,\n ...props,\n style: {\n ...style,\n display: \"inline-block\",\n overflow: \"visible\",\n boxSizing: \"border-box\"\n },\n children\n }\n );\n}\nconst MarqueeZoom = ({\n documentId,\n pageIndex,\n scale: scaleOverride,\n className,\n stroke = \"rgba(33,150,243,0.8)\",\n fill = \"rgba(33,150,243,0.15)\"\n}) => {\n const { provides: zoomPlugin } = useZoomCapability();\n const documentState = useDocumentState(documentId);\n const [rect, setRect] = useState(null);\n const actualScale = useMemo(() => {\n if (scaleOverride !== void 0) return scaleOverride;\n return (documentState == null ? void 0 : documentState.scale) ?? 1;\n }, [scaleOverride, documentState == null ? void 0 : documentState.scale]);\n useEffect(() => {\n if (!zoomPlugin) return;\n return zoomPlugin.registerMarqueeOnPage({\n documentId,\n pageIndex,\n scale: actualScale,\n callback: {\n onPreview: setRect\n }\n });\n }, [zoomPlugin, documentId, pageIndex, actualScale]);\n if (!rect) return null;\n return /* @__PURE__ */ jsx(\n \"div\",\n {\n style: {\n position: \"absolute\",\n pointerEvents: \"none\",\n left: rect.origin.x * actualScale,\n top: rect.origin.y * actualScale,\n width: rect.size.width * actualScale,\n height: rect.size.height * actualScale,\n border: `1px solid ${stroke}`,\n background: fill,\n boxSizing: \"border-box\"\n },\n className\n }\n );\n};\nexport {\n MarqueeZoom,\n ZoomGestureWrapper,\n useZoom,\n useZoomCapability,\n useZoomGesture,\n useZoomPlugin\n};\n//# sourceMappingURL=index.js.map\n","import { BasePlugin, createBehaviorEmitter } from \"@embedpdf/core\";\nimport { PdfErrorCode, PdfTaskHelper } from \"@embedpdf/models\";\nconst INIT_SEARCH_STATE = \"SEARCH/INIT_STATE\";\nconst CLEANUP_SEARCH_STATE = \"SEARCH/CLEANUP_STATE\";\nconst START_SEARCH_SESSION = \"SEARCH/START_SEARCH_SESSION\";\nconst STOP_SEARCH_SESSION = \"SEARCH/STOP_SEARCH_SESSION\";\nconst SET_SEARCH_FLAGS = \"SEARCH/SET_SEARCH_FLAGS\";\nconst SET_SHOW_ALL_RESULTS = \"SEARCH/SET_SHOW_ALL_RESULTS\";\nconst START_SEARCH = \"SEARCH/START_SEARCH\";\nconst SET_SEARCH_RESULTS = \"SEARCH/SET_SEARCH_RESULTS\";\nconst APPEND_SEARCH_RESULTS = \"SEARCH/APPEND_SEARCH_RESULTS\";\nconst SET_ACTIVE_RESULT_INDEX = \"SEARCH/SET_ACTIVE_RESULT_INDEX\";\nfunction initSearchState(documentId, state) {\n return { type: INIT_SEARCH_STATE, payload: { documentId, state } };\n}\nfunction cleanupSearchState(documentId) {\n return { type: CLEANUP_SEARCH_STATE, payload: documentId };\n}\nfunction startSearchSession(documentId) {\n return { type: START_SEARCH_SESSION, payload: { documentId } };\n}\nfunction stopSearchSession(documentId) {\n return { type: STOP_SEARCH_SESSION, payload: { documentId } };\n}\nfunction setSearchFlags(documentId, flags) {\n return { type: SET_SEARCH_FLAGS, payload: { documentId, flags } };\n}\nfunction setShowAllResults(documentId, showAll) {\n return { type: SET_SHOW_ALL_RESULTS, payload: { documentId, showAll } };\n}\nfunction startSearch(documentId, query) {\n return { type: START_SEARCH, payload: { documentId, query } };\n}\nfunction setSearchResults(documentId, results, total, activeResultIndex) {\n return { type: SET_SEARCH_RESULTS, payload: { documentId, results, total, activeResultIndex } };\n}\nfunction appendSearchResults(documentId, results) {\n return { type: APPEND_SEARCH_RESULTS, payload: { documentId, results } };\n}\nfunction setActiveResultIndex(documentId, index) {\n return { type: SET_ACTIVE_RESULT_INDEX, payload: { documentId, index } };\n}\nconst initialSearchDocumentState = {\n flags: [],\n results: [],\n total: 0,\n activeResultIndex: -1,\n showAllResults: true,\n query: \"\",\n loading: false,\n active: false\n};\nconst initialState = {\n documents: {}\n};\nconst updateDocState = (state, documentId, newDocState) => {\n const oldDocState = state.documents[documentId] || initialSearchDocumentState;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...oldDocState,\n ...newDocState\n }\n }\n };\n};\nconst searchReducer = (state = initialState, action) => {\n switch (action.type) {\n case INIT_SEARCH_STATE:\n return {\n ...state,\n documents: {\n ...state.documents,\n [action.payload.documentId]: action.payload.state\n }\n };\n case CLEANUP_SEARCH_STATE: {\n const documentId = action.payload;\n const { [documentId]: removed, ...remaining } = state.documents;\n return {\n ...state,\n documents: remaining\n };\n }\n case START_SEARCH_SESSION:\n return updateDocState(state, action.payload.documentId, { active: true });\n case STOP_SEARCH_SESSION:\n return updateDocState(state, action.payload.documentId, {\n results: [],\n total: 0,\n activeResultIndex: -1,\n query: \"\",\n loading: false,\n active: false\n });\n case SET_SEARCH_FLAGS:\n return updateDocState(state, action.payload.documentId, { flags: action.payload.flags });\n case SET_SHOW_ALL_RESULTS:\n return updateDocState(state, action.payload.documentId, {\n showAllResults: action.payload.showAll\n });\n case START_SEARCH:\n return updateDocState(state, action.payload.documentId, {\n loading: true,\n query: action.payload.query,\n // clear old results on new search start\n results: [],\n total: 0,\n activeResultIndex: -1\n });\n case APPEND_SEARCH_RESULTS: {\n const { documentId, results } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n const newResults = [...docState.results, ...results];\n const firstHitIndex = docState.activeResultIndex === -1 && newResults.length > 0 ? 0 : docState.activeResultIndex;\n return updateDocState(state, documentId, {\n results: newResults,\n total: newResults.length,\n // total-so-far\n activeResultIndex: firstHitIndex,\n // keep loading true until final SET_SEARCH_RESULTS\n loading: true\n });\n }\n case SET_SEARCH_RESULTS: {\n const { documentId, results, total, activeResultIndex } = action.payload;\n return updateDocState(state, documentId, {\n results,\n total,\n activeResultIndex,\n loading: false\n });\n }\n case SET_ACTIVE_RESULT_INDEX:\n return updateDocState(state, action.payload.documentId, {\n activeResultIndex: action.payload.index\n });\n default:\n return state;\n }\n};\nconst _SearchPlugin = class _SearchPlugin extends BasePlugin {\n constructor(id, registry, config) {\n super(id, registry);\n this.searchStop$ = createBehaviorEmitter();\n this.searchStart$ = createBehaviorEmitter();\n this.searchResult$ = createBehaviorEmitter();\n this.searchActiveResultChange$ = createBehaviorEmitter();\n this.searchResultState$ = createBehaviorEmitter();\n this.searchState$ = createBehaviorEmitter();\n this.currentTask = /* @__PURE__ */ new Map();\n this.pluginConfig = config;\n }\n onDocumentLoadingStarted(documentId) {\n const initialState2 = {\n ...initialSearchDocumentState,\n flags: this.pluginConfig.flags || [],\n showAllResults: this.pluginConfig.showAllResults ?? true\n };\n this.dispatch(initSearchState(documentId, initialState2));\n }\n onDocumentClosed(documentId) {\n this.stopSearchSession(documentId);\n this.dispatch(cleanupSearchState(documentId));\n this.currentTask.delete(documentId);\n }\n async initialize() {\n }\n onStoreUpdated(prevState, newState) {\n for (const documentId in newState.documents) {\n const prevDocState = prevState.documents[documentId];\n const newDocState = newState.documents[documentId];\n if (prevDocState !== newDocState) {\n this.searchState$.emit({ documentId, state: newDocState });\n if (!prevDocState || prevDocState.results !== newDocState.results || prevDocState.activeResultIndex !== newDocState.activeResultIndex || prevDocState.showAllResults !== newDocState.showAllResults || prevDocState.active !== newDocState.active) {\n this.searchResultState$.emit({\n documentId,\n state: {\n results: newDocState.results,\n activeResultIndex: newDocState.activeResultIndex,\n showAllResults: newDocState.showAllResults,\n active: newDocState.active\n }\n });\n }\n }\n }\n }\n buildCapability() {\n const getDocId = (documentId) => documentId ?? this.getActiveDocumentId();\n const getDocState = (docId) => {\n const id = getDocId(docId);\n const state = this.state.documents[id];\n if (!state) throw new Error(`Search state not found for document ${id}`);\n return state;\n };\n return {\n startSearch: (docId) => this.startSearchSession(getDocId(docId)),\n stopSearch: (docId) => this.stopSearchSession(getDocId(docId)),\n searchAllPages: (keyword, docId) => this.searchAllPages(keyword, getDocId(docId)),\n nextResult: (docId) => this.nextResult(getDocId(docId)),\n previousResult: (docId) => this.previousResult(getDocId(docId)),\n goToResult: (index, docId) => this.goToResult(index, getDocId(docId)),\n setShowAllResults: (showAll, docId) => this.dispatch(setShowAllResults(getDocId(docId), showAll)),\n getShowAllResults: (docId) => getDocState(docId).showAllResults,\n getFlags: (docId) => getDocState(docId).flags,\n setFlags: (flags, docId) => this.setFlags(flags, getDocId(docId)),\n getState: (docId) => getDocState(docId),\n forDocument: this.createSearchScope.bind(this),\n onSearchResult: this.searchResult$.on,\n onSearchStart: this.searchStart$.on,\n onSearchStop: this.searchStop$.on,\n onActiveResultChange: this.searchActiveResultChange$.on,\n onSearchResultStateChange: this.searchResultState$.on,\n onStateChange: this.searchState$.on\n };\n }\n createSearchScope(documentId) {\n const getDocState = () => {\n const state = this.state.documents[documentId];\n if (!state) throw new Error(`Search state not found for document ${documentId}`);\n return state;\n };\n return {\n startSearch: () => this.startSearchSession(documentId),\n stopSearch: () => this.stopSearchSession(documentId),\n searchAllPages: (keyword) => this.searchAllPages(keyword, documentId),\n nextResult: () => this.nextResult(documentId),\n previousResult: () => this.previousResult(documentId),\n goToResult: (index) => this.goToResult(index, documentId),\n setShowAllResults: (showAll) => this.dispatch(setShowAllResults(documentId, showAll)),\n getShowAllResults: () => getDocState().showAllResults,\n getFlags: () => getDocState().flags,\n setFlags: (flags) => this.setFlags(flags, documentId),\n getState: getDocState,\n onSearchResult: (listener) => this.searchResult$.on((event) => {\n if (event.documentId === documentId) listener(event.results);\n }),\n onSearchStart: (listener) => this.searchStart$.on((event) => {\n if (event.documentId === documentId) listener();\n }),\n onSearchStop: (listener) => this.searchStop$.on((event) => {\n if (event.documentId === documentId) listener();\n }),\n onActiveResultChange: (listener) => this.searchActiveResultChange$.on((event) => {\n if (event.documentId === documentId) listener(event.index);\n }),\n onSearchResultStateChange: (listener) => this.searchResultState$.on((event) => {\n if (event.documentId === documentId) listener(event.state);\n }),\n onStateChange: (listener) => this.searchState$.on((event) => {\n if (event.documentId === documentId) listener(event.state);\n })\n };\n }\n setFlags(flags, documentId) {\n this.dispatch(setSearchFlags(documentId, flags));\n const docState = this.state.documents[documentId];\n if (docState == null ? void 0 : docState.active) {\n this.searchAllPages(docState.query, documentId, true);\n }\n }\n notifySearchStart(documentId) {\n this.searchStart$.emit({ documentId });\n }\n notifySearchStop(documentId) {\n this.searchStop$.emit({ documentId });\n }\n notifyActiveResultChange(documentId, index) {\n this.searchActiveResultChange$.emit({ documentId, index });\n }\n startSearchSession(documentId) {\n const coreDoc = this.getCoreDocument(documentId);\n if (!coreDoc) return;\n this.dispatch(startSearchSession(documentId));\n this.notifySearchStart(documentId);\n }\n stopSearchSession(documentId) {\n var _a;\n const docState = this.state.documents[documentId];\n if (!(docState == null ? void 0 : docState.active)) return;\n const task = this.currentTask.get(documentId);\n if (task) {\n try {\n (_a = task.abort) == null ? void 0 : _a.call(task, { code: PdfErrorCode.Cancelled, message: \"search stopped\" });\n } catch {\n }\n this.currentTask.delete(documentId);\n }\n this.dispatch(stopSearchSession(documentId));\n this.notifySearchStop(documentId);\n }\n searchAllPages(keyword, documentId, force = false) {\n var _a;\n const docState = this.state.documents[documentId];\n if (!docState) {\n return PdfTaskHelper.reject({\n code: PdfErrorCode.NotFound,\n message: \"Search state not initialized\"\n });\n }\n const coreDoc = this.getCoreDocument(documentId);\n if (!(coreDoc == null ? void 0 : coreDoc.document)) {\n return PdfTaskHelper.reject({ code: PdfErrorCode.NotFound, message: \"Document not loaded\" });\n }\n const trimmedKeyword = keyword.trim();\n if (docState.query === trimmedKeyword && !force) {\n return PdfTaskHelper.resolve({\n results: docState.results,\n total: docState.total\n });\n }\n const oldTask = this.currentTask.get(documentId);\n if (oldTask) {\n try {\n (_a = oldTask.abort) == null ? void 0 : _a.call(oldTask, { code: PdfErrorCode.Cancelled, message: \"new search\" });\n } catch {\n }\n this.currentTask.delete(documentId);\n }\n this.dispatch(startSearch(documentId, trimmedKeyword));\n if (!trimmedKeyword) {\n this.dispatch(setSearchResults(documentId, [], 0, -1));\n return PdfTaskHelper.resolve({\n results: [],\n total: 0\n });\n }\n if (!docState.active) {\n this.startSearchSession(documentId);\n }\n const task = this.engine.searchAllPages(coreDoc.document, trimmedKeyword, {\n flags: docState.flags\n });\n this.currentTask.set(documentId, task);\n task.onProgress((p) => {\n var _a2;\n if ((_a2 = p == null ? void 0 : p.results) == null ? void 0 : _a2.length) {\n if (this.currentTask.get(documentId) === task) {\n this.dispatch(appendSearchResults(documentId, p.results));\n if (this.state.documents[documentId].activeResultIndex === -1) {\n this.dispatch(setActiveResultIndex(documentId, 0));\n this.notifyActiveResultChange(documentId, 0);\n }\n }\n }\n });\n task.wait(\n (results) => {\n this.currentTask.delete(documentId);\n const activeResultIndex = results.total > 0 ? 0 : -1;\n this.dispatch(\n setSearchResults(documentId, results.results, results.total, activeResultIndex)\n );\n this.searchResult$.emit({ documentId, results });\n if (results.total > 0) {\n this.notifyActiveResultChange(documentId, 0);\n }\n },\n (error) => {\n var _a2;\n if (((_a2 = error == null ? void 0 : error.reason) == null ? void 0 : _a2.code) !== PdfErrorCode.Cancelled) {\n console.error(\"Error during search:\", error);\n this.dispatch(setSearchResults(documentId, [], 0, -1));\n }\n this.currentTask.delete(documentId);\n }\n );\n return task;\n }\n nextResult(documentId) {\n const docState = this.state.documents[documentId];\n if (!docState || docState.results.length === 0) return -1;\n const nextIndex = docState.activeResultIndex >= docState.results.length - 1 ? 0 : docState.activeResultIndex + 1;\n return this.goToResult(nextIndex, documentId);\n }\n previousResult(documentId) {\n const docState = this.state.documents[documentId];\n if (!docState || docState.results.length === 0) return -1;\n const prevIndex = docState.activeResultIndex <= 0 ? docState.results.length - 1 : docState.activeResultIndex - 1;\n return this.goToResult(prevIndex, documentId);\n }\n goToResult(index, documentId) {\n const docState = this.state.documents[documentId];\n if (!docState || docState.results.length === 0 || index < 0 || index >= docState.results.length) {\n return -1;\n }\n this.dispatch(setActiveResultIndex(documentId, index));\n this.notifyActiveResultChange(documentId, index);\n return index;\n }\n async destroy() {\n for (const documentId of Object.keys(this.state.documents)) {\n this.stopSearchSession(documentId);\n }\n this.searchResult$.clear();\n this.searchStart$.clear();\n this.searchStop$.clear();\n this.searchActiveResultChange$.clear();\n this.searchResultState$.clear();\n this.searchState$.clear();\n super.destroy();\n }\n};\n_SearchPlugin.id = \"search\";\nlet SearchPlugin = _SearchPlugin;\nconst SEARCH_PLUGIN_ID = \"search\";\nconst manifest = {\n id: SEARCH_PLUGIN_ID,\n name: \"Search Plugin\",\n version: \"1.0.0\",\n provides: [\"search\"],\n requires: [],\n optional: [],\n defaultConfig: {\n flags: []\n }\n};\nconst SearchPluginPackage = {\n manifest,\n create: (registry, config) => new SearchPlugin(SEARCH_PLUGIN_ID, registry, config),\n reducer: searchReducer,\n initialState\n};\nexport {\n SEARCH_PLUGIN_ID,\n SearchPlugin,\n SearchPluginPackage,\n initialSearchDocumentState,\n initialState,\n manifest\n};\n//# sourceMappingURL=index.js.map\n","import { useCapability, usePlugin, useDocumentState } from \"@embedpdf/core/react\";\nimport { initialSearchDocumentState, SearchPlugin } from \"@embedpdf/plugin-search\";\nexport * from \"@embedpdf/plugin-search\";\nimport { useState, useMemo, useEffect } from \"react\";\nimport { jsx } from \"react/jsx-runtime\";\nconst useSearchPlugin = () => usePlugin(SearchPlugin.id);\nconst useSearchCapability = () => useCapability(SearchPlugin.id);\nconst useSearch = (documentId) => {\n const { provides } = useSearchCapability();\n const [searchState, setSearchState] = useState(initialSearchDocumentState);\n const scope = useMemo(() => provides == null ? void 0 : provides.forDocument(documentId), [provides, documentId]);\n useEffect(() => {\n if (!scope) {\n setSearchState(initialSearchDocumentState);\n return;\n }\n setSearchState(scope.getState());\n return scope.onStateChange((state) => setSearchState(state));\n }, [scope]);\n return {\n state: searchState,\n provides: scope ?? null\n };\n};\nfunction SearchLayer({\n documentId,\n pageIndex,\n scale: scaleOverride,\n style,\n highlightColor = \"#FFFF00\",\n activeHighlightColor = \"#FFBF00\",\n ...props\n}) {\n const { provides: searchProvides } = useSearchCapability();\n const [searchResultState, setSearchResultState] = useState(null);\n const documentState = useDocumentState(documentId);\n const scope = useMemo(\n () => searchProvides == null ? void 0 : searchProvides.forDocument(documentId),\n [searchProvides, documentId]\n );\n const actualScale = useMemo(() => {\n if (scaleOverride !== void 0) return scaleOverride;\n return (documentState == null ? void 0 : documentState.scale) ?? 1;\n }, [scaleOverride, documentState == null ? void 0 : documentState.scale]);\n useEffect(() => {\n if (!scope) {\n setSearchResultState(null);\n return;\n }\n const currentState = scope.getState();\n setSearchResultState({\n results: currentState.results,\n activeResultIndex: currentState.activeResultIndex,\n showAllResults: currentState.showAllResults,\n active: currentState.active\n });\n return scope.onSearchResultStateChange((state) => {\n setSearchResultState(state);\n });\n }, [scope]);\n if (!searchResultState || !searchResultState.active) {\n return null;\n }\n const pageResults = searchResultState.results.map((result, originalIndex) => ({ result, originalIndex })).filter(({ result }) => result.pageIndex === pageIndex);\n const resultsToShow = pageResults.filter(\n ({ originalIndex }) => searchResultState.showAllResults || originalIndex === searchResultState.activeResultIndex\n );\n return /* @__PURE__ */ jsx(\n \"div\",\n {\n style: {\n ...style,\n pointerEvents: \"none\"\n },\n ...props,\n children: resultsToShow.map(\n ({ result, originalIndex }) => result.rects.map((rect, rectIndex) => /* @__PURE__ */ jsx(\n \"div\",\n {\n style: {\n position: \"absolute\",\n top: rect.origin.y * actualScale,\n left: rect.origin.x * actualScale,\n width: rect.size.width * actualScale,\n height: rect.size.height * actualScale,\n backgroundColor: originalIndex === searchResultState.activeResultIndex ? activeHighlightColor : highlightColor,\n mixBlendMode: \"multiply\",\n transform: \"scale(1.02)\",\n transformOrigin: \"center\",\n transition: \"opacity .3s ease-in-out\",\n opacity: 1\n }\n },\n `${originalIndex}-${rectIndex}`\n ))\n )\n }\n );\n}\nexport {\n SearchLayer,\n useSearch,\n useSearchCapability,\n useSearchPlugin\n};\n//# sourceMappingURL=index.js.map\n","import { clamp, BasePlugin, createScopedEmitter, REFRESH_PAGES } from \"@embedpdf/core\";\nimport { boundingRect, Task, ignore, PdfErrorCode, PdfTaskHelper, PdfPermissionFlag } from \"@embedpdf/models\";\nconst SELECTION_PLUGIN_ID = \"selection\";\nconst manifest = {\n id: SELECTION_PLUGIN_ID,\n name: \"Selection Plugin\",\n version: \"1.0.0\",\n provides: [\"selection\"],\n requires: [\"interaction-manager\"],\n optional: [\"viewport\", \"scroll\"],\n defaultConfig: {\n menuHeight: 40\n }\n};\nconst INIT_SELECTION_STATE = \"SELECTION/INIT_STATE\";\nconst CLEANUP_SELECTION_STATE = \"SELECTION/CLEANUP_STATE\";\nconst CACHE_PAGE_GEOMETRY = \"SELECTION/CACHE_PAGE_GEOMETRY\";\nconst SET_SELECTION = \"SELECTION/SET_SELECTION\";\nconst START_SELECTION = \"SELECTION/START_SELECTION\";\nconst END_SELECTION = \"SELECTION/END_SELECTION\";\nconst CLEAR_SELECTION = \"SELECTION/CLEAR_SELECTION\";\nconst SET_RECTS = \"SELECTION/SET_RECTS\";\nconst SET_SLICES = \"SELECTION/SET_SLICES\";\nconst EVICT_PAGE_GEOMETRY = \"SELECTION/EVICT_PAGE_GEOMETRY\";\nconst RESET = \"SELECTION/RESET\";\nconst initSelectionState = (documentId, state) => ({\n type: INIT_SELECTION_STATE,\n payload: { documentId, state }\n});\nconst cleanupSelectionState = (documentId) => ({\n type: CLEANUP_SELECTION_STATE,\n payload: documentId\n});\nconst cachePageGeometry = (documentId, page, geo) => ({\n type: CACHE_PAGE_GEOMETRY,\n payload: { documentId, page, geo }\n});\nconst setSelection = (documentId, sel) => ({\n type: SET_SELECTION,\n payload: { documentId, selection: sel }\n});\nconst startSelection = (documentId) => ({\n type: START_SELECTION,\n payload: { documentId }\n});\nconst endSelection = (documentId) => ({\n type: END_SELECTION,\n payload: { documentId }\n});\nconst clearSelection = (documentId) => ({\n type: CLEAR_SELECTION,\n payload: { documentId }\n});\nconst setRects = (documentId, allRects) => ({\n type: SET_RECTS,\n payload: { documentId, rects: allRects }\n});\nconst setSlices = (documentId, slices) => ({ type: SET_SLICES, payload: { documentId, slices } });\nconst evictPageGeometry = (documentId, pages) => ({\n type: EVICT_PAGE_GEOMETRY,\n payload: { documentId, pages }\n});\nconst initialSelectionDocumentState = {\n geometry: {},\n rects: {},\n slices: {},\n selection: null,\n active: false,\n selecting: false\n};\nconst initialState = {\n documents: {}\n};\nconst updateDocState = (state, documentId, newDocState) => ({\n ...state,\n documents: {\n ...state.documents,\n [documentId]: newDocState\n }\n});\nconst selectionReducer = (state = initialState, action) => {\n switch (action.type) {\n case INIT_SELECTION_STATE: {\n const { documentId, state: docState } = action.payload;\n return updateDocState(state, documentId, docState);\n }\n case CLEANUP_SELECTION_STATE: {\n const documentId = action.payload;\n const { [documentId]: removed, ...remaining } = state.documents;\n return {\n ...state,\n documents: remaining\n };\n }\n case CACHE_PAGE_GEOMETRY: {\n const { documentId, page, geo } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return updateDocState(state, documentId, {\n ...docState,\n geometry: { ...docState.geometry, [page]: geo }\n });\n }\n case SET_SELECTION: {\n const { documentId, selection } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return updateDocState(state, documentId, {\n ...docState,\n selection,\n active: true\n });\n }\n case START_SELECTION: {\n const { documentId } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return updateDocState(state, documentId, {\n ...docState,\n selecting: true,\n selection: null,\n rects: {}\n });\n }\n case END_SELECTION: {\n const { documentId } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return updateDocState(state, documentId, { ...docState, selecting: false });\n }\n case CLEAR_SELECTION: {\n const { documentId } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return updateDocState(state, documentId, {\n ...docState,\n selecting: false,\n selection: null,\n rects: {},\n active: false\n });\n }\n case SET_RECTS: {\n const { documentId, rects } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return updateDocState(state, documentId, { ...docState, rects });\n }\n case SET_SLICES: {\n const { documentId, slices } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return updateDocState(state, documentId, { ...docState, slices });\n }\n case EVICT_PAGE_GEOMETRY: {\n const { documentId, pages } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n const geometry = { ...docState.geometry };\n const rects = { ...docState.rects };\n const slices = { ...docState.slices };\n for (const p of pages) {\n delete geometry[p];\n delete rects[p];\n delete slices[p];\n }\n return updateDocState(state, documentId, { ...docState, geometry, rects, slices });\n }\n case RESET: {\n const { documentId } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return updateDocState(state, documentId, initialSelectionDocumentState);\n }\n default:\n return state;\n }\n};\nfunction selectRectsForPage(state, page) {\n return state.rects[page] ?? [];\n}\nfunction selectBoundingRectForPage(state, page) {\n return boundingRect(selectRectsForPage(state, page));\n}\nfunction selectBoundingRectsForAllPages(state) {\n const out = [];\n const rectMap = state.rects;\n for (const key in rectMap) {\n const page = Number(key);\n const bRect = boundingRect(rectMap[page]);\n if (bRect) out.push({ page, rect: bRect });\n }\n return out;\n}\nfunction getFormattedSelectionForPage(state, page) {\n const segmentRects = state.rects[page] || [];\n if (segmentRects.length === 0) return null;\n const boundingRect2 = selectBoundingRectForPage(state, page);\n if (!boundingRect2) return null;\n return { pageIndex: page, rect: boundingRect2, segmentRects };\n}\nfunction getFormattedSelection(state) {\n const result = [];\n const pages = Object.keys(state.rects).map(Number);\n for (const pageIndex of pages) {\n const segmentRects = state.rects[pageIndex] || [];\n if (segmentRects.length === 0) continue;\n const boundingRect2 = selectBoundingRectForPage(state, pageIndex);\n if (boundingRect2) {\n result.push({\n pageIndex,\n rect: boundingRect2,\n segmentRects\n });\n }\n }\n return result;\n}\nfunction glyphAt(geo, pt, toleranceFactor = 1.5) {\n for (const run of geo.runs) {\n const inRun = pt.y >= run.rect.y && pt.y <= run.rect.y + run.rect.height && pt.x >= run.rect.x && pt.x <= run.rect.x + run.rect.width;\n if (!inRun) continue;\n const rel = run.glyphs.findIndex((g) => {\n const gx = g.tightX ?? g.x;\n const gy = g.tightY ?? g.y;\n const gw = g.tightWidth ?? g.width;\n const gh = g.tightHeight ?? g.height;\n return pt.x >= gx && pt.x <= gx + gw && pt.y >= gy && pt.y <= gy + gh;\n });\n if (rel !== -1) {\n return run.charStart + rel;\n }\n }\n if (toleranceFactor <= 0) return -1;\n const tolerance = computeTolerance(geo, toleranceFactor);\n const halfTol = tolerance / 2;\n let bestIndex = -1;\n let bestDist = Infinity;\n for (const run of geo.runs) {\n if (pt.y < run.rect.y - halfTol || pt.y > run.rect.y + run.rect.height + halfTol || pt.x < run.rect.x - halfTol || pt.x > run.rect.x + run.rect.width + halfTol) {\n continue;\n }\n for (let i = 0; i < run.glyphs.length; i++) {\n const g = run.glyphs[i];\n if (g.flags === 2) continue;\n const gx = g.tightX ?? g.x;\n const gy = g.tightY ?? g.y;\n const gw = g.tightWidth ?? g.width;\n const gh = g.tightHeight ?? g.height;\n const expandedLeft = gx - halfTol;\n const expandedRight = gx + gw + halfTol;\n const expandedTop = gy - halfTol;\n const expandedBottom = gy + gh + halfTol;\n if (pt.x < expandedLeft || pt.x > expandedRight || pt.y < expandedTop || pt.y > expandedBottom) {\n continue;\n }\n const curXdif = Math.min(Math.abs(pt.x - gx), Math.abs(pt.x - (gx + gw)));\n const curYdif = Math.min(Math.abs(pt.y - gy), Math.abs(pt.y - (gy + gh)));\n const dist = curXdif + curYdif;\n if (dist < bestDist) {\n bestDist = dist;\n bestIndex = run.charStart + i;\n }\n }\n }\n return bestIndex;\n}\nfunction computeTolerance(geo, factor) {\n let totalHeight = 0;\n let count = 0;\n for (const run of geo.runs) {\n for (const g of run.glyphs) {\n if (g.flags === 2) continue;\n totalHeight += g.height;\n count++;\n }\n }\n if (count === 0) return 0;\n return totalHeight / count * factor;\n}\nfunction sliceBounds(sel, geo, page) {\n if (!sel || !geo) return null;\n if (page < sel.start.page || page > sel.end.page) return null;\n const from = page === sel.start.page ? sel.start.index : 0;\n const lastRun = geo.runs[geo.runs.length - 1];\n const lastCharOnPage = lastRun.charStart + lastRun.glyphs.length - 1;\n const to = page === sel.end.page ? sel.end.index : lastCharOnPage;\n return { from, to };\n}\nfunction rectsWithinSlice(geo, from, to, merge = true) {\n const textRuns = [];\n const CHAR_DISTANCE_FACTOR = 2.5;\n for (const run of geo.runs) {\n const runStart = run.charStart;\n const runEnd = runStart + run.glyphs.length - 1;\n if (runEnd < from || runStart > to) continue;\n const sIdx = Math.max(from, runStart) - runStart;\n const eIdx = Math.min(to, runEnd) - runStart;\n let minX = Infinity, maxX = -Infinity;\n let minY = Infinity, maxY = -Infinity;\n let charCount = 0;\n let widthSum = 0;\n let prevRight = -Infinity;\n const flushSubRun = () => {\n if (minX !== Infinity && charCount > 0) {\n textRuns.push({\n rect: {\n origin: { x: minX, y: minY },\n size: { width: maxX - minX, height: maxY - minY }\n },\n charCount,\n fontSize: run.fontSize\n });\n }\n minX = Infinity;\n maxX = -Infinity;\n minY = Infinity;\n maxY = -Infinity;\n charCount = 0;\n widthSum = 0;\n prevRight = -Infinity;\n };\n for (let i = sIdx; i <= eIdx; i++) {\n const g = run.glyphs[i];\n if (g.flags === 2) continue;\n if (charCount > 0 && prevRight > -Infinity) {\n const gap = Math.abs(g.x - prevRight);\n const avgWidth = widthSum / charCount;\n if (avgWidth > 0 && gap > CHAR_DISTANCE_FACTOR * avgWidth) {\n flushSubRun();\n }\n }\n minX = Math.min(minX, g.x);\n maxX = Math.max(maxX, g.x + g.width);\n minY = Math.min(minY, g.y);\n maxY = Math.max(maxY, g.y + g.height);\n charCount++;\n widthSum += g.width;\n prevRight = g.x + g.width;\n }\n flushSubRun();\n }\n if (!merge) {\n return textRuns.map((run) => run.rect);\n }\n return mergeAdjacentRects(textRuns);\n}\nfunction rectUnion(rect1, rect2) {\n const left = Math.min(rect1.origin.x, rect2.origin.x);\n const top = Math.min(rect1.origin.y, rect2.origin.y);\n const right = Math.max(rect1.origin.x + rect1.size.width, rect2.origin.x + rect2.size.width);\n const bottom = Math.max(rect1.origin.y + rect1.size.height, rect2.origin.y + rect2.size.height);\n return {\n origin: { x: left, y: top },\n size: { width: right - left, height: bottom - top }\n };\n}\nfunction rectIntersect(rect1, rect2) {\n const left = Math.max(rect1.origin.x, rect2.origin.x);\n const top = Math.max(rect1.origin.y, rect2.origin.y);\n const right = Math.min(rect1.origin.x + rect1.size.width, rect2.origin.x + rect2.size.width);\n const bottom = Math.min(rect1.origin.y + rect1.size.height, rect2.origin.y + rect2.size.height);\n const width = Math.max(0, right - left);\n const height = Math.max(0, bottom - top);\n return {\n origin: { x: left, y: top },\n size: { width, height }\n };\n}\nfunction rectIsEmpty(rect) {\n return rect.size.width <= 0 || rect.size.height <= 0;\n}\nfunction getVerticalOverlap(rect1, rect2) {\n if (rectIsEmpty(rect1) || rectIsEmpty(rect2)) return 0;\n const unionRect = rectUnion(rect1, rect2);\n if (unionRect.size.height === rect1.size.height || unionRect.size.height === rect2.size.height) {\n return 1;\n }\n const intersectRect = rectIntersect(rect1, rect2);\n return intersectRect.size.height / unionRect.size.height;\n}\nfunction shouldMergeHorizontalRects(textRun1, textRun2) {\n const FONT_SIZE_RATIO_THRESHOLD = 1.5;\n if (textRun1.fontSize != null && textRun2.fontSize != null && textRun1.fontSize > 0 && textRun2.fontSize > 0) {\n const ratio = Math.max(textRun1.fontSize, textRun2.fontSize) / Math.min(textRun1.fontSize, textRun2.fontSize);\n if (ratio > FONT_SIZE_RATIO_THRESHOLD) {\n return false;\n }\n }\n const VERTICAL_OVERLAP_THRESHOLD = 0.8;\n const rect1 = textRun1.rect;\n const rect2 = textRun2.rect;\n if (getVerticalOverlap(rect1, rect2) < VERTICAL_OVERLAP_THRESHOLD) {\n return false;\n }\n const HORIZONTAL_WIDTH_FACTOR = 1;\n const averageWidth1 = HORIZONTAL_WIDTH_FACTOR * rect1.size.width / textRun1.charCount;\n const averageWidth2 = HORIZONTAL_WIDTH_FACTOR * rect2.size.width / textRun2.charCount;\n const rect1Left = rect1.origin.x - averageWidth1;\n const rect1Right = rect1.origin.x + rect1.size.width + averageWidth1;\n const rect2Left = rect2.origin.x - averageWidth2;\n const rect2Right = rect2.origin.x + rect2.size.width + averageWidth2;\n return rect1Left < rect2Right && rect1Right > rect2Left;\n}\nfunction mergeAdjacentRects(textRuns) {\n const results = [];\n let previousTextRun = null;\n let currentRect = null;\n for (const textRun of textRuns) {\n if (previousTextRun && currentRect) {\n if (shouldMergeHorizontalRects(previousTextRun, textRun)) {\n currentRect = rectUnion(currentRect, textRun.rect);\n } else {\n results.push(currentRect);\n currentRect = textRun.rect;\n }\n } else {\n currentRect = textRun.rect;\n }\n previousTextRun = textRun;\n }\n if (currentRect && !rectIsEmpty(currentRect)) {\n results.push(currentRect);\n }\n return results;\n}\nconst VERTICAL_OVERLAP_THRESHOLD_LINE = 0.5;\nfunction resolveCharIndex(geo, charIndex) {\n for (let r = 0; r < geo.runs.length; r++) {\n const run = geo.runs[r];\n const localIdx = charIndex - run.charStart;\n if (localIdx >= 0 && localIdx < run.glyphs.length) {\n return { runIdx: r, localIdx };\n }\n }\n return null;\n}\nfunction isGlyphWordBoundary(flags) {\n return flags === 1 || flags === 2;\n}\nfunction expandToWordBoundary(geo, charIndex) {\n const resolved = resolveCharIndex(geo, charIndex);\n if (!resolved) return null;\n const totalChars = getTotalCharCount(geo);\n if (totalChars === 0) return null;\n let from = charIndex;\n while (from > 0) {\n const prev = resolveCharIndex(geo, from - 1);\n if (!prev) break;\n if (isGlyphWordBoundary(geo.runs[prev.runIdx].glyphs[prev.localIdx].flags)) break;\n from--;\n }\n let to = charIndex;\n while (to < totalChars - 1) {\n const next = resolveCharIndex(geo, to + 1);\n if (!next) break;\n if (isGlyphWordBoundary(geo.runs[next.runIdx].glyphs[next.localIdx].flags)) break;\n to++;\n }\n return { from, to };\n}\nfunction expandToLineBoundary(geo, charIndex) {\n const resolved = resolveCharIndex(geo, charIndex);\n if (!resolved) return null;\n const anchorRun = geo.runs[resolved.runIdx];\n const anchorTop = anchorRun.rect.y;\n const anchorBottom = anchorRun.rect.y + anchorRun.rect.height;\n let from = anchorRun.charStart;\n let to = anchorRun.charStart + anchorRun.glyphs.length - 1;\n for (let r = resolved.runIdx - 1; r >= 0; r--) {\n const run = geo.runs[r];\n if (isZeroSizeRun(run)) continue;\n if (!runsOverlapVertically(run.rect.y, run.rect.y + run.rect.height, anchorTop, anchorBottom)) {\n break;\n }\n from = run.charStart;\n }\n for (let r = resolved.runIdx + 1; r < geo.runs.length; r++) {\n const run = geo.runs[r];\n if (isZeroSizeRun(run)) continue;\n if (!runsOverlapVertically(run.rect.y, run.rect.y + run.rect.height, anchorTop, anchorBottom)) {\n break;\n }\n to = run.charStart + run.glyphs.length - 1;\n }\n return { from, to };\n}\nfunction isZeroSizeRun(run) {\n return run.rect.width === 0 && run.rect.height === 0;\n}\nfunction runsOverlapVertically(top1, bottom1, top2, bottom2) {\n const unionHeight = Math.max(bottom1, bottom2) - Math.min(top1, top2);\n const intersectHeight = Math.max(0, Math.min(bottom1, bottom2) - Math.max(top1, top2));\n if (unionHeight === 0) return false;\n return intersectHeight / unionHeight >= VERTICAL_OVERLAP_THRESHOLD_LINE;\n}\nfunction getTotalCharCount(geo) {\n if (geo.runs.length === 0) return 0;\n const lastRun = geo.runs[geo.runs.length - 1];\n return lastRun.charStart + lastRun.glyphs.length;\n}\nconst TRIPLE_CLICK_INTERVAL_MS = 500;\nfunction createTextSelectionHandler(opts) {\n const minDrag = opts.minDragDistance ?? 3;\n const tolFactor = opts.toleranceFactor ?? 1.5;\n let anchorGlyph = null;\n let anchorPos = null;\n let dragStarted = false;\n let lastDblClickTime = 0;\n function reset() {\n var _a;\n anchorGlyph = null;\n anchorPos = null;\n dragStarted = false;\n (_a = opts.setHasTextAnchor) == null ? void 0 : _a.call(opts, false);\n }\n return {\n onPointerDown: (point, evt, modeId) => {\n var _a, _b;\n if (evt.target === evt.currentTarget) {\n (_a = opts.onEmptySpaceClick) == null ? void 0 : _a.call(opts, modeId);\n }\n if (!opts.isEnabled(modeId)) return;\n const now = Date.now();\n if (lastDblClickTime === 0 || now - lastDblClickTime >= TRIPLE_CLICK_INTERVAL_MS) {\n opts.onClear(modeId);\n }\n const geo = opts.getGeometry();\n if (!geo) return;\n const g = glyphAt(geo, point, tolFactor);\n if (g !== -1) {\n anchorGlyph = g;\n anchorPos = point;\n dragStarted = false;\n (_b = opts.setHasTextAnchor) == null ? void 0 : _b.call(opts, true);\n }\n },\n onPointerMove: (point, _evt, modeId) => {\n if (!opts.isEnabled(modeId)) return;\n const geo = opts.getGeometry();\n if (!geo) return;\n const g = glyphAt(geo, point, tolFactor);\n opts.setCursor(g !== -1 ? \"text\" : null);\n if (anchorGlyph !== null && anchorPos && !dragStarted) {\n const dx = point.x - anchorPos.x;\n const dy = point.y - anchorPos.y;\n const dist = Math.sqrt(dx * dx + dy * dy);\n if (dist >= minDrag) {\n dragStarted = true;\n opts.onBegin(anchorGlyph, modeId);\n if (g !== -1) {\n opts.onUpdate(g, modeId);\n }\n }\n return;\n }\n if (opts.isSelecting() && g !== -1) {\n opts.onUpdate(g, modeId);\n }\n },\n onPointerUp: (_point, _evt, modeId) => {\n if (!opts.isEnabled(modeId)) {\n reset();\n return;\n }\n if (dragStarted) {\n opts.onEnd(modeId);\n }\n reset();\n },\n onDoubleClick: (point, _evt, modeId) => {\n var _a;\n if (!opts.isEnabled(modeId)) return;\n const geo = opts.getGeometry();\n if (!geo) return;\n const g = glyphAt(geo, point, tolFactor);\n if (g === -1) return;\n lastDblClickTime = Date.now();\n (_a = opts.onWordSelect) == null ? void 0 : _a.call(opts, g, modeId);\n },\n onClick: (point, _evt, modeId) => {\n var _a;\n if (!opts.isEnabled(modeId)) return;\n if (lastDblClickTime === 0) return;\n const now = Date.now();\n if (now - lastDblClickTime > TRIPLE_CLICK_INTERVAL_MS) {\n lastDblClickTime = 0;\n return;\n }\n lastDblClickTime = 0;\n const geo = opts.getGeometry();\n if (!geo) return;\n const g = glyphAt(geo, point, tolFactor);\n if (g === -1) return;\n (_a = opts.onLineSelect) == null ? void 0 : _a.call(opts, g, modeId);\n },\n onHandlerActiveEnd: (modeId) => {\n reset();\n if (!opts.isEnabled(modeId)) return;\n opts.onClear(modeId);\n }\n };\n}\nfunction createMarqueeSelectionHandler(opts) {\n const { pageSize, scale, minDragPx = 5 } = opts;\n let start = null;\n let last = null;\n return {\n onPointerDown: (pos, evt, modeId) => {\n var _a, _b;\n if (!opts.isEnabled(modeId)) return;\n if ((_a = opts.isTextSelecting) == null ? void 0 : _a.call(opts)) return;\n start = pos;\n last = { origin: { x: pos.x, y: pos.y }, size: { width: 0, height: 0 } };\n opts.onBegin(pos, modeId);\n (_b = evt.setPointerCapture) == null ? void 0 : _b.call(evt);\n },\n onPointerMove: (pos, _evt, modeId) => {\n if (!start || !opts.isEnabled(modeId)) return;\n const x = clamp(pos.x, 0, pageSize.width);\n const y = clamp(pos.y, 0, pageSize.height);\n last = {\n origin: { x: Math.min(start.x, x), y: Math.min(start.y, y) },\n size: { width: Math.abs(x - start.x), height: Math.abs(y - start.y) }\n };\n opts.onChange(last, modeId);\n },\n onPointerUp: (_pos, evt, modeId) => {\n var _a;\n if (!opts.isEnabled(modeId)) return;\n if (last && start) {\n const dragPx = Math.max(last.size.width, last.size.height) * scale;\n if (dragPx > minDragPx) {\n opts.onEnd(last, modeId);\n } else {\n opts.onCancel(modeId);\n }\n }\n start = null;\n last = null;\n (_a = evt.releasePointerCapture) == null ? void 0 : _a.call(evt);\n },\n onPointerCancel: (_pos, evt, modeId) => {\n var _a;\n if (!opts.isEnabled(modeId)) return;\n start = null;\n last = null;\n opts.onCancel(modeId);\n (_a = evt.releasePointerCapture) == null ? void 0 : _a.call(evt);\n }\n };\n}\nconst _SelectionPlugin = class _SelectionPlugin extends BasePlugin {\n constructor(id, registry, config) {\n var _a, _b, _c;\n super(id, registry);\n this.enabledModesPerDoc = /* @__PURE__ */ new Map();\n this.selecting = /* @__PURE__ */ new Map();\n this.anchor = /* @__PURE__ */ new Map();\n this.hasTextAnchor = /* @__PURE__ */ new Map();\n this.marqueePage = /* @__PURE__ */ new Map();\n this.pageCallbacks = /* @__PURE__ */ new Map();\n this.geoAccessOrder = /* @__PURE__ */ new Map();\n this.menuPlacement$ = createScopedEmitter((documentId, placement) => ({ documentId, placement }));\n this.selChange$ = createScopedEmitter((documentId, selection) => ({\n documentId,\n selection,\n modeId: this.interactionManagerCapability.forDocument(documentId).getActiveMode()\n }));\n this.textRetrieved$ = createScopedEmitter(\n (documentId, text) => ({ documentId, text })\n );\n this.copyToClipboard$ = createScopedEmitter(\n (documentId, text) => ({ documentId, text }),\n { cache: false }\n );\n this.beginSelection$ = createScopedEmitter(\n (documentId, data) => ({\n documentId,\n page: data.page,\n index: data.index,\n modeId: data.modeId\n }),\n { cache: false }\n );\n this.endSelection$ = createScopedEmitter((documentId, data) => ({ documentId, modeId: data.modeId }), { cache: false });\n this.marqueeChange$ = createScopedEmitter(\n (documentId, data) => ({\n documentId,\n pageIndex: data.pageIndex,\n rect: data.rect,\n modeId: data.modeId\n }),\n { cache: false }\n );\n this.marqueeEnd$ = createScopedEmitter(\n (documentId, data) => ({\n documentId,\n pageIndex: data.pageIndex,\n rect: data.rect,\n modeId: data.modeId\n }),\n { cache: false }\n );\n this.emptySpaceClick$ = createScopedEmitter(\n (documentId, data) => ({\n documentId,\n pageIndex: data.pageIndex,\n modeId: data.modeId\n }),\n { cache: false }\n );\n this.viewportCapability = null;\n this.scrollCapability = null;\n this.config = config;\n this.menuHeight = config.menuHeight ?? 40;\n const imPlugin = registry.getPlugin(\"interaction-manager\");\n if (!imPlugin) {\n throw new Error(\"SelectionPlugin: InteractionManagerPlugin is required.\");\n }\n this.interactionManagerCapability = imPlugin.provides();\n this.viewportCapability = ((_a = registry.getPlugin(\"viewport\")) == null ? void 0 : _a.provides()) ?? null;\n this.scrollCapability = ((_b = registry.getPlugin(\"scroll\")) == null ? void 0 : _b.provides()) ?? null;\n this.coreStore.onAction(REFRESH_PAGES, (action) => {\n const { documentId, pageIndexes } = action.payload;\n const tasks = pageIndexes.map(\n (pageIndex) => this.getNewPageGeometryAndCache(documentId, pageIndex)\n );\n Task.all(tasks).wait(() => {\n pageIndexes.forEach((pageIndex) => {\n this.notifyPage(documentId, pageIndex);\n });\n }, ignore);\n });\n (_c = this.viewportCapability) == null ? void 0 : _c.onViewportChange(\n (event) => {\n this.recalculateMenuPlacement(event.documentId);\n },\n { mode: \"throttle\", wait: 100 }\n );\n }\n /* ── life-cycle ────────────────────────────────────────── */\n onDocumentLoadingStarted(documentId) {\n var _a;\n this.dispatch(initSelectionState(documentId, initialSelectionDocumentState));\n const marqueeEnabled = ((_a = this.config.marquee) == null ? void 0 : _a.enabled) !== false;\n this.enabledModesPerDoc.set(\n documentId,\n /* @__PURE__ */ new Map([\n [\n \"pointerMode\",\n {\n enableSelection: true,\n showSelectionRects: true,\n enableMarquee: marqueeEnabled,\n showMarqueeRects: true\n }\n ]\n ])\n );\n this.pageCallbacks.set(documentId, /* @__PURE__ */ new Map());\n this.geoAccessOrder.set(documentId, []);\n this.selecting.set(documentId, false);\n this.anchor.set(documentId, void 0);\n this.hasTextAnchor.set(documentId, false);\n }\n onDocumentClosed(documentId) {\n this.dispatch(cleanupSelectionState(documentId));\n this.enabledModesPerDoc.delete(documentId);\n this.pageCallbacks.delete(documentId);\n this.geoAccessOrder.delete(documentId);\n this.selecting.delete(documentId);\n this.hasTextAnchor.delete(documentId);\n this.anchor.delete(documentId);\n this.marqueePage.delete(documentId);\n this.selChange$.clearScope(documentId);\n this.textRetrieved$.clearScope(documentId);\n this.copyToClipboard$.clearScope(documentId);\n this.beginSelection$.clearScope(documentId);\n this.endSelection$.clearScope(documentId);\n this.menuPlacement$.clearScope(documentId);\n this.marqueeChange$.clearScope(documentId);\n this.marqueeEnd$.clearScope(documentId);\n this.emptySpaceClick$.clearScope(documentId);\n }\n async initialize() {\n }\n async destroy() {\n this.selChange$.clear();\n this.textRetrieved$.clear();\n this.copyToClipboard$.clear();\n this.beginSelection$.clear();\n this.endSelection$.clear();\n this.menuPlacement$.clear();\n this.marqueeChange$.clear();\n this.marqueeEnd$.clear();\n this.emptySpaceClick$.clear();\n super.destroy();\n }\n /* ── capability exposed to UI / other plugins ─────────── */\n buildCapability() {\n const getDocId = (documentId) => documentId ?? this.getActiveDocumentId();\n return {\n // Active document operations\n getFormattedSelection: (docId) => getFormattedSelection(this.getDocumentState(getDocId(docId))),\n getFormattedSelectionForPage: (p, docId) => getFormattedSelectionForPage(this.getDocumentState(getDocId(docId)), p),\n getHighlightRectsForPage: (p, docId) => selectRectsForPage(this.getDocumentState(getDocId(docId)), p),\n getHighlightRects: (docId) => this.getDocumentState(getDocId(docId)).rects,\n getBoundingRectForPage: (p, docId) => selectBoundingRectForPage(this.getDocumentState(getDocId(docId)), p),\n getBoundingRects: (docId) => selectBoundingRectsForAllPages(this.getDocumentState(getDocId(docId))),\n getSelectedText: (docId) => this.getSelectedText(getDocId(docId)),\n setSelection: (range, docId) => this.applySelection(getDocId(docId), range),\n clear: (docId) => this.clearSelection(getDocId(docId)),\n copyToClipboard: (docId) => this.copyToClipboard(getDocId(docId)),\n getState: (docId) => this.getDocumentState(getDocId(docId)),\n enableForMode: (modeId, options, docId) => {\n var _a;\n return (_a = this.enabledModesPerDoc.get(getDocId(docId))) == null ? void 0 : _a.set(modeId, { ...options });\n },\n isEnabledForMode: (modeId, docId) => {\n var _a;\n return ((_a = this.enabledModesPerDoc.get(getDocId(docId))) == null ? void 0 : _a.has(modeId)) ?? false;\n },\n setMarqueeEnabled: (enabled, docId) => this.setMarqueeEnabled(getDocId(docId), enabled),\n isMarqueeEnabled: (docId) => this.isMarqueeEnabled(getDocId(docId)),\n // Document-scoped operations\n forDocument: this.createSelectionScope.bind(this),\n // Global events\n onCopyToClipboard: this.copyToClipboard$.onGlobal,\n onSelectionChange: this.selChange$.onGlobal,\n onTextRetrieved: this.textRetrieved$.onGlobal,\n onBeginSelection: this.beginSelection$.onGlobal,\n onEndSelection: this.endSelection$.onGlobal,\n // Marquee selection events\n onMarqueeChange: this.marqueeChange$.onGlobal,\n onMarqueeEnd: this.marqueeEnd$.onGlobal,\n // Empty space click event\n onEmptySpaceClick: this.emptySpaceClick$.onGlobal\n };\n }\n createSelectionScope(documentId) {\n return {\n getFormattedSelection: () => getFormattedSelection(this.getDocumentState(documentId)),\n getFormattedSelectionForPage: (p) => getFormattedSelectionForPage(this.getDocumentState(documentId), p),\n getHighlightRectsForPage: (p) => selectRectsForPage(this.getDocumentState(documentId), p),\n getHighlightRects: () => this.getDocumentState(documentId).rects,\n getBoundingRectForPage: (p) => selectBoundingRectForPage(this.getDocumentState(documentId), p),\n getBoundingRects: () => selectBoundingRectsForAllPages(this.getDocumentState(documentId)),\n getSelectedText: () => this.getSelectedText(documentId),\n setSelection: (range) => this.applySelection(documentId, range),\n clear: () => this.clearSelection(documentId),\n copyToClipboard: () => this.copyToClipboard(documentId),\n getState: () => this.getDocumentState(documentId),\n setMarqueeEnabled: (enabled) => this.setMarqueeEnabled(documentId, enabled),\n isMarqueeEnabled: () => this.isMarqueeEnabled(documentId),\n onSelectionChange: this.selChange$.forScope(documentId),\n onTextRetrieved: this.textRetrieved$.forScope(documentId),\n onCopyToClipboard: this.copyToClipboard$.forScope(documentId),\n onBeginSelection: this.beginSelection$.forScope(documentId),\n onEndSelection: this.endSelection$.forScope(documentId),\n onMarqueeChange: this.marqueeChange$.forScope(documentId),\n onMarqueeEnd: this.marqueeEnd$.forScope(documentId),\n onEmptySpaceClick: this.emptySpaceClick$.forScope(documentId)\n };\n }\n getDocumentState(documentId) {\n const state = this.state.documents[documentId];\n if (!state) {\n throw new Error(`Selection state not found for document: ${documentId}`);\n }\n return state;\n }\n /**\n * Subscribe to menu placement changes for a specific document\n * @param documentId - The document ID to subscribe to\n * @param listener - Callback function that receives placement updates\n * @returns Unsubscribe function\n */\n onMenuPlacement(documentId, listener) {\n return this.menuPlacement$.forScope(documentId)(listener);\n }\n /**\n * Register text selection on a page. Uses `registerAlways` so any plugin\n * can enable text selection for their mode via `enableForMode()`.\n */\n registerSelectionOnPage(opts) {\n var _a;\n const { documentId, pageIndex, onRectsChange } = opts;\n const docState = this.state.documents[documentId];\n if (!docState) {\n this.logger.warn(\n \"SelectionPlugin\",\n \"RegisterFailed\",\n `Cannot register selection on page ${pageIndex} for document ${documentId}: document state not initialized.`\n );\n return () => {\n };\n }\n (_a = this.pageCallbacks.get(documentId)) == null ? void 0 : _a.set(pageIndex, onRectsChange);\n const geoTask = this.getOrLoadGeometry(documentId, pageIndex);\n const interactionScope = this.interactionManagerCapability.forDocument(documentId);\n const enabledModes = this.enabledModesPerDoc.get(documentId);\n onRectsChange({\n rects: selectRectsForPage(docState, pageIndex),\n boundingRect: selectBoundingRectForPage(docState, pageIndex)\n });\n geoTask.wait((geo) => {\n const currentState = this.getDocumentState(documentId);\n const sel = currentState.selection;\n if (!sel || pageIndex < sel.start.page || pageIndex > sel.end.page) return;\n const sb = sliceBounds(sel, geo, pageIndex);\n if (!sb) return;\n const pageRects = rectsWithinSlice(geo, sb.from, sb.to);\n this.dispatch(setRects(documentId, { ...currentState.rects, [pageIndex]: pageRects }));\n this.dispatch(\n setSlices(documentId, {\n ...currentState.slices,\n [pageIndex]: { start: sb.from, count: sb.to - sb.from + 1 }\n })\n );\n this.notifyPage(documentId, pageIndex);\n }, ignore);\n const textHandler = createTextSelectionHandler({\n getGeometry: () => this.getDocumentState(documentId).geometry[pageIndex],\n isEnabled: (modeId) => {\n const config = enabledModes == null ? void 0 : enabledModes.get(modeId);\n if (!config) return false;\n return config.enableSelection !== false;\n },\n onBegin: (g, modeId) => this.beginSelection(documentId, pageIndex, g, modeId),\n onUpdate: (g, modeId) => this.updateSelection(documentId, pageIndex, g, modeId),\n onEnd: (modeId) => this.endSelection(documentId, modeId),\n onClear: (modeId) => this.clearSelection(documentId, modeId),\n isSelecting: () => this.selecting.get(documentId) ?? false,\n setCursor: (cursor) => cursor ? interactionScope.setCursor(\"selection-text\", cursor, 10) : interactionScope.removeCursor(\"selection-text\"),\n onEmptySpaceClick: (modeId) => this.emptySpaceClick$.emit(documentId, { pageIndex, modeId }),\n onWordSelect: (g, modeId) => this.selectWord(documentId, pageIndex, g, modeId),\n onLineSelect: (g, modeId) => this.selectLine(documentId, pageIndex, g, modeId),\n setHasTextAnchor: (active) => this.hasTextAnchor.set(documentId, active),\n minDragDistance: this.config.minSelectionDragDistance,\n toleranceFactor: this.config.toleranceFactor\n });\n const unregisterHandlers = this.interactionManagerCapability.registerAlways({\n scope: { type: \"page\", documentId, pageIndex },\n handlers: textHandler\n });\n return () => {\n var _a2;\n unregisterHandlers();\n (_a2 = this.pageCallbacks.get(documentId)) == null ? void 0 : _a2.delete(pageIndex);\n geoTask.abort({ code: PdfErrorCode.Cancelled, message: \"Cleanup\" });\n };\n }\n /**\n * Register marquee selection on a page. Uses `registerAlways` so any plugin\n * can enable marquee selection for their mode via `enableForMode({ enableMarquee: true })`.\n */\n registerMarqueeOnPage(opts) {\n var _a;\n const { documentId, pageIndex, scale, onRectChange } = opts;\n const docState = this.state.documents[documentId];\n if (!docState) {\n this.logger.warn(\n \"SelectionPlugin\",\n \"RegisterMarqueeFailed\",\n `Cannot register marquee on page ${pageIndex} for document ${documentId}: document state not initialized.`\n );\n return () => {\n };\n }\n const coreDoc = this.coreState.core.documents[documentId];\n if (!coreDoc || !coreDoc.document) {\n this.logger.warn(\n \"SelectionPlugin\",\n \"DocumentNotFound\",\n `Cannot register marquee on page ${pageIndex}: document not found`\n );\n return () => {\n };\n }\n const page = coreDoc.document.pages[pageIndex];\n if (!page) {\n this.logger.warn(\n \"SelectionPlugin\",\n \"PageNotFound\",\n `Cannot register marquee on page ${pageIndex}: page not found`\n );\n return () => {\n };\n }\n const pageSize = page.size;\n const minDragPx = ((_a = this.config.marquee) == null ? void 0 : _a.minDragPx) ?? 5;\n const shouldShowRect = () => {\n var _a2;\n const mode = this.interactionManagerCapability.forDocument(documentId).getActiveMode();\n const config = (_a2 = this.enabledModesPerDoc.get(documentId)) == null ? void 0 : _a2.get(mode);\n return (config == null ? void 0 : config.showMarqueeRects) !== false;\n };\n const marqueeHandler = createMarqueeSelectionHandler({\n pageSize,\n scale,\n minDragPx,\n isEnabled: (modeId) => {\n var _a2;\n const config = (_a2 = this.enabledModesPerDoc.get(documentId)) == null ? void 0 : _a2.get(modeId);\n return (config == null ? void 0 : config.enableMarquee) === true;\n },\n isTextSelecting: () => (this.selecting.get(documentId) ?? false) || (this.hasTextAnchor.get(documentId) ?? false),\n onBegin: (pos, modeId) => this.beginMarquee(documentId, pageIndex, pos, modeId),\n onChange: (rect, modeId) => {\n this.updateMarquee(documentId, pageIndex, rect, modeId);\n onRectChange(shouldShowRect() ? rect : null);\n },\n onEnd: (rect, modeId) => {\n this.endMarquee(documentId, pageIndex, rect, modeId);\n onRectChange(null);\n },\n onCancel: (modeId) => {\n this.cancelMarquee(documentId, modeId);\n onRectChange(null);\n }\n });\n const unregisterHandlers = this.interactionManagerCapability.registerAlways({\n scope: { type: \"page\", documentId, pageIndex },\n handlers: marqueeHandler\n });\n return unregisterHandlers;\n }\n /**\n * Helper to calculate viewport relative metrics for a page rect.\n * Returns null if the rect cannot be converted to viewport space.\n */\n getPlacementMetrics(documentId, pageIndex, rect, vpMetrics) {\n var _a;\n const scrollScope = (_a = this.scrollCapability) == null ? void 0 : _a.forDocument(documentId);\n const viewportRect = scrollScope == null ? void 0 : scrollScope.getRectPositionForPage(pageIndex, rect);\n if (!viewportRect) return null;\n const rectTopInView = viewportRect.origin.y - vpMetrics.scrollTop;\n const rectBottomInView = viewportRect.origin.y + viewportRect.size.height - vpMetrics.scrollTop;\n return {\n pageIndex,\n rect,\n // Original Page Rect\n spaceAbove: rectTopInView,\n spaceBelow: vpMetrics.clientHeight - rectBottomInView,\n isBottomVisible: rectBottomInView > 0 && rectBottomInView <= vpMetrics.clientHeight,\n isTopVisible: rectTopInView >= 0 && rectTopInView < vpMetrics.clientHeight\n };\n }\n emitMenuPlacement(documentId, placement) {\n this.menuPlacement$.emit(documentId, placement);\n if (placement) {\n this.interactionManagerCapability.claimPageActivity(\n documentId,\n \"selection-menu\",\n placement.pageIndex\n );\n } else {\n this.interactionManagerCapability.releasePageActivity(documentId, \"selection-menu\");\n }\n }\n recalculateMenuPlacement(documentId) {\n const docState = this.state.documents[documentId];\n if (!docState) return;\n if (docState.selecting || docState.selection === null) {\n this.emitMenuPlacement(documentId, null);\n return;\n }\n const bounds = selectBoundingRectsForAllPages(docState);\n if (bounds.length === 0) {\n this.emitMenuPlacement(documentId, null);\n return;\n }\n const tail = bounds[bounds.length - 1];\n if (!this.viewportCapability || !this.scrollCapability) {\n this.emitMenuPlacement(documentId, {\n pageIndex: tail.page,\n rect: tail.rect,\n spaceAbove: 0,\n spaceBelow: Infinity,\n // Pretend we have infinite space below to prevent auto-flipping\n suggestTop: false,\n isVisible: true\n // Assume visible\n });\n return;\n }\n const viewportScope = this.viewportCapability.forDocument(documentId);\n const vpMetrics = viewportScope.getMetrics();\n const head = bounds[0];\n const tailMetrics = this.getPlacementMetrics(documentId, tail.page, tail.rect, vpMetrics);\n const headMetrics = this.getPlacementMetrics(documentId, head.page, head.rect, vpMetrics);\n if (tailMetrics) {\n if (tailMetrics.isBottomVisible && tailMetrics.spaceBelow > this.menuHeight) {\n this.emitMenuPlacement(documentId, {\n ...tailMetrics,\n suggestTop: false,\n isVisible: true\n });\n return;\n }\n }\n if (headMetrics) {\n if (headMetrics.isTopVisible) {\n this.emitMenuPlacement(documentId, {\n ...headMetrics,\n suggestTop: true,\n isVisible: true\n });\n return;\n }\n }\n if (tailMetrics && tailMetrics.isBottomVisible) {\n this.emitMenuPlacement(documentId, {\n ...tailMetrics,\n suggestTop: false,\n isVisible: true\n });\n return;\n }\n this.emitMenuPlacement(documentId, null);\n }\n notifyPage(documentId, pageIndex) {\n var _a, _b;\n const callback = (_a = this.pageCallbacks.get(documentId)) == null ? void 0 : _a.get(pageIndex);\n if (callback) {\n const docState = this.getDocumentState(documentId);\n const mode = this.interactionManagerCapability.forDocument(documentId).getActiveMode();\n const modeConfig = (_b = this.enabledModesPerDoc.get(documentId)) == null ? void 0 : _b.get(mode);\n const shouldShowRects = modeConfig && (modeConfig.showSelectionRects ?? modeConfig.showRects) !== false;\n if (shouldShowRects) {\n callback({\n rects: selectRectsForPage(docState, pageIndex),\n boundingRect: selectBoundingRectForPage(docState, pageIndex)\n });\n } else {\n callback({ rects: [], boundingRect: null });\n }\n }\n }\n notifyAllPages(documentId) {\n var _a;\n (_a = this.pageCallbacks.get(documentId)) == null ? void 0 : _a.forEach((_, pageIndex) => {\n this.notifyPage(documentId, pageIndex);\n });\n }\n getNewPageGeometryAndCache(documentId, pageIdx) {\n const coreDoc = this.getCoreDocument(documentId);\n if (!coreDoc || !coreDoc.document)\n return PdfTaskHelper.reject({ code: PdfErrorCode.NotFound, message: \"Doc Not Found\" });\n const page = coreDoc.document.pages.find((p) => p.index === pageIdx);\n const task = this.engine.getPageGeometry(coreDoc.document, page);\n task.wait((geo) => {\n this.dispatch(cachePageGeometry(documentId, pageIdx, geo));\n this.touchGeometry(documentId, pageIdx);\n }, ignore);\n return task;\n }\n /* ── geometry cache ───────────────────────────────────── */\n getOrLoadGeometry(documentId, pageIdx) {\n const cached = this.getDocumentState(documentId).geometry[pageIdx];\n if (cached) {\n this.touchGeometry(documentId, pageIdx);\n return PdfTaskHelper.resolve(cached);\n }\n return this.getNewPageGeometryAndCache(documentId, pageIdx);\n }\n /* ── geometry LRU eviction ──────────────────────────────── */\n touchGeometry(documentId, pageIdx) {\n const order = this.geoAccessOrder.get(documentId);\n if (!order) return;\n const idx = order.indexOf(pageIdx);\n if (idx > -1) order.splice(idx, 1);\n order.push(pageIdx);\n this.evictGeometryIfNeeded(documentId);\n }\n evictGeometryIfNeeded(documentId) {\n const max = this.config.maxCachedGeometries ?? 50;\n const order = this.geoAccessOrder.get(documentId);\n if (!order || order.length <= max) return;\n const pinned = this.pageCallbacks.get(documentId);\n const toEvict = [];\n while (order.length - toEvict.length > max) {\n const candidate = order.find((p) => !toEvict.includes(p) && !(pinned == null ? void 0 : pinned.has(p)));\n if (candidate === void 0) break;\n toEvict.push(candidate);\n }\n if (toEvict.length === 0) return;\n for (const p of toEvict) {\n const idx = order.indexOf(p);\n if (idx > -1) order.splice(idx, 1);\n }\n this.dispatch(evictPageGeometry(documentId, toEvict));\n }\n /* ── selection state updates ───────────────────────────── */\n beginSelection(documentId, page, index, modeId) {\n this.selecting.set(documentId, true);\n this.anchor.set(documentId, { page, index });\n this.dispatch(startSelection(documentId));\n this.beginSelection$.emit(documentId, { page, index, modeId });\n this.recalculateMenuPlacement(documentId);\n }\n endSelection(documentId, modeId) {\n this.selecting.set(documentId, false);\n this.anchor.set(documentId, void 0);\n this.dispatch(endSelection(documentId));\n this.endSelection$.emit(documentId, { modeId });\n this.recalculateMenuPlacement(documentId);\n }\n clearSelection(documentId, _modeId) {\n this.selecting.set(documentId, false);\n this.anchor.set(documentId, void 0);\n this.dispatch(clearSelection(documentId));\n this.selChange$.emit(documentId, null);\n this.emitMenuPlacement(documentId, null);\n this.notifyAllPages(documentId);\n }\n /**\n * Programmatically apply (or restore) a text selection without going through\n * the pointer drag flow. Useful for restoring a previously persisted selection\n * or driving selection from code (e.g. search results).\n *\n * Geometry for every page spanned by the range is loaded on demand (the data\n * comes from the WASM engine), so the returned task settles only once the\n * selection rects have actually been computed.\n *\n * Passing `null` is equivalent to calling {@link clearSelection}.\n *\n * @returns a task that resolves once the selection has been applied.\n */\n applySelection(documentId, range) {\n if (!this.state.documents[documentId]) {\n return PdfTaskHelper.reject({\n code: PdfErrorCode.NotFound,\n message: `Selection state not found for document: ${documentId}`\n });\n }\n if (range === null) {\n this.clearSelection(documentId);\n return PdfTaskHelper.resolve(void 0);\n }\n const validationError = this.validateRange(documentId, range);\n if (validationError) {\n return PdfTaskHelper.reject(validationError);\n }\n const normalized = this.normalizeRange(range);\n const pages = [];\n for (let p = normalized.start.page; p <= normalized.end.page; p++) {\n pages.push(p);\n }\n const geoTasks = pages.map((p) => this.getOrLoadGeometry(documentId, p));\n const result = PdfTaskHelper.create();\n Task.all(geoTasks).wait(() => {\n if (!this.state.documents[documentId]) {\n result.reject({\n code: PdfErrorCode.NotFound,\n message: `Selection state not found for document: ${documentId}`\n });\n return;\n }\n const clamped = this.clampRangeToGeometry(documentId, normalized);\n if (!clamped) {\n result.reject({\n code: PdfErrorCode.NotFound,\n message: `Cannot apply selection: page(s) ${normalized.start.page}-${normalized.end.page} have no text geometry`\n });\n return;\n }\n this.selecting.set(documentId, false);\n this.anchor.set(documentId, void 0);\n const previouslyHighlighted = Object.keys(this.getDocumentState(documentId).rects).map(\n Number\n );\n this.dispatch(startSelection(documentId));\n this.dispatch(setSelection(documentId, clamped));\n this.updateRectsAndSlices(documentId, clamped);\n this.dispatch(endSelection(documentId));\n this.selChange$.emit(documentId, clamped);\n const pagesToNotify = new Set(previouslyHighlighted);\n for (let p = clamped.start.page; p <= clamped.end.page; p++) {\n pagesToNotify.add(p);\n }\n pagesToNotify.forEach((p) => this.notifyPage(documentId, p));\n this.recalculateMenuPlacement(documentId);\n result.resolve(void 0);\n }, (error) => result.reject(error.reason));\n return result;\n }\n /**\n * Validate the structure and page bounds of a programmatic selection range.\n * Returns a rejection reason when the input is invalid, or null when it is\n * structurally sound. Glyph-index bounds are enforced separately, after the\n * page geometry has loaded (see {@link clampRangeToGeometry}).\n */\n validateRange(documentId, range) {\n var _a, _b;\n const isValidPointer = (g) => !!g && typeof g === \"object\" && Number.isInteger(g.page) && Number.isInteger(g.index);\n if (!range || typeof range !== \"object\" || !range.start || !range.end) {\n return { code: PdfErrorCode.Unknown, message: \"Invalid selection range: expected { start, end }\" };\n }\n if (!isValidPointer(range.start) || !isValidPointer(range.end)) {\n return {\n code: PdfErrorCode.Unknown,\n message: \"Invalid selection range: start/end must have integer page and index\"\n };\n }\n if (range.start.index < 0 || range.end.index < 0) {\n return { code: PdfErrorCode.Unknown, message: \"Invalid selection range: glyph index cannot be negative\" };\n }\n const pageCount = ((_b = (_a = this.getCoreDocument(documentId)) == null ? void 0 : _a.document) == null ? void 0 : _b.pageCount) ?? 0;\n const minPage = Math.min(range.start.page, range.end.page);\n const maxPage = Math.max(range.start.page, range.end.page);\n if (minPage < 0 || maxPage >= pageCount) {\n return {\n code: PdfErrorCode.NotFound,\n message: `Invalid selection range: page ${minPage < 0 ? minPage : maxPage} out of bounds [0, ${pageCount})`\n };\n }\n return null;\n }\n /**\n * Clamp the glyph indices of a (normalized) range to the number of glyphs\n * available on the corresponding pages. Returns null when none of the\n * spanned pages have any text geometry to select.\n */\n clampRangeToGeometry(documentId, range) {\n const docState = this.getDocumentState(documentId);\n const lastGlyphIndex = (page) => {\n const geo = docState.geometry[page];\n if (!geo || geo.runs.length === 0) return -1;\n const lastRun = geo.runs[geo.runs.length - 1];\n return lastRun.charStart + lastRun.glyphs.length - 1;\n };\n const startMax = lastGlyphIndex(range.start.page);\n const endMax = lastGlyphIndex(range.end.page);\n if (startMax < 0 && endMax < 0) return null;\n const clampIndex = (index, max) => max < 0 ? 0 : Math.min(Math.max(index, 0), max);\n return {\n start: { page: range.start.page, index: clampIndex(range.start.index, startMax) },\n end: { page: range.end.page, index: clampIndex(range.end.index, endMax) }\n };\n }\n /** Order a range so that `start` never comes after `end`. */\n normalizeRange(range) {\n const { start, end } = range;\n const forward = end.page > start.page || end.page === start.page && end.index >= start.index;\n return forward ? { start, end } : { start: end, end: start };\n }\n selectWord(documentId, page, charIndex, modeId) {\n const geo = this.getDocumentState(documentId).geometry[page];\n if (!geo) return;\n const bounds = expandToWordBoundary(geo, charIndex);\n if (!bounds) return;\n this.applyInstantSelection(documentId, page, bounds.from, bounds.to, modeId);\n }\n selectLine(documentId, page, charIndex, modeId) {\n const geo = this.getDocumentState(documentId).geometry[page];\n if (!geo) return;\n const bounds = expandToLineBoundary(geo, charIndex);\n if (!bounds) return;\n this.applyInstantSelection(documentId, page, bounds.from, bounds.to, modeId);\n }\n /**\n * Set a selection range without going through the drag begin/update/end flow.\n * Used by double-click (word) and triple-click (line) selection.\n */\n applyInstantSelection(documentId, page, from, to, modeId) {\n const range = {\n start: { page, index: from },\n end: { page, index: to }\n };\n this.selecting.set(documentId, false);\n this.anchor.set(documentId, void 0);\n this.dispatch(startSelection(documentId));\n this.dispatch(setSelection(documentId, range));\n this.updateRectsAndSlices(documentId, range);\n this.dispatch(endSelection(documentId));\n this.selChange$.emit(documentId, range);\n this.beginSelection$.emit(documentId, { page, index: from, modeId });\n this.endSelection$.emit(documentId, { modeId });\n for (let p = range.start.page; p <= range.end.page; p++) {\n this.notifyPage(documentId, p);\n }\n this.recalculateMenuPlacement(documentId);\n }\n updateSelection(documentId, page, index, modeId) {\n if (!this.selecting.get(documentId) || !this.anchor.get(documentId)) return;\n const a = this.anchor.get(documentId);\n const forward = page > a.page || page === a.page && index >= a.index;\n const start = forward ? a : { page, index };\n const end = forward ? { page, index } : a;\n const range = { start, end };\n this.dispatch(setSelection(documentId, range));\n this.updateRectsAndSlices(documentId, range);\n this.selChange$.emit(documentId, range);\n for (let p = range.start.page; p <= range.end.page; p++) {\n this.notifyPage(documentId, p);\n }\n }\n updateRectsAndSlices(documentId, range) {\n const docState = this.getDocumentState(documentId);\n const allRects = {};\n const allSlices = {};\n for (let p = range.start.page; p <= range.end.page; p++) {\n const geo = docState.geometry[p];\n const sb = sliceBounds(range, geo, p);\n if (!sb) continue;\n allRects[p] = rectsWithinSlice(geo, sb.from, sb.to);\n allSlices[p] = { start: sb.from, count: sb.to - sb.from + 1 };\n }\n this.dispatch(setRects(documentId, allRects));\n this.dispatch(setSlices(documentId, allSlices));\n }\n getSelectedText(documentId) {\n if (!this.checkPermission(documentId, PdfPermissionFlag.CopyContents)) {\n this.logger.debug(\n \"SelectionPlugin\",\n \"GetSelectedText\",\n `Cannot get selected text: document ${documentId} lacks CopyContents permission`\n );\n return PdfTaskHelper.reject({\n code: PdfErrorCode.Security,\n message: \"Document lacks CopyContents permission\"\n });\n }\n const coreDoc = this.getCoreDocument(documentId);\n const docState = this.getDocumentState(documentId);\n if (!(coreDoc == null ? void 0 : coreDoc.document) || !docState.selection) {\n return PdfTaskHelper.reject({\n code: PdfErrorCode.NotFound,\n message: \"Doc Not Found or No Selection\"\n });\n }\n const sel = docState.selection;\n const req = [];\n for (let p = sel.start.page; p <= sel.end.page; p++) {\n const s = docState.slices[p];\n if (s) req.push({ pageIndex: p, charIndex: s.start, charCount: s.count });\n }\n if (req.length === 0) return PdfTaskHelper.resolve([]);\n const task = this.engine.getTextSlices(coreDoc.document, req);\n task.wait((text) => {\n this.textRetrieved$.emit(documentId, text);\n }, ignore);\n return task;\n }\n copyToClipboard(documentId) {\n if (!this.checkPermission(documentId, PdfPermissionFlag.CopyContents)) {\n this.logger.debug(\n \"SelectionPlugin\",\n \"CopyToClipboard\",\n `Cannot copy to clipboard: document ${documentId} lacks CopyContents permission`\n );\n return;\n }\n const text = this.getSelectedText(documentId);\n text.wait((text2) => {\n this.copyToClipboard$.emit(documentId, text2.join(\"\\n\"));\n }, ignore);\n }\n /* ── marquee selection state updates ─────────────────────── */\n beginMarquee(documentId, pageIndex, _startPos, _modeId) {\n this.marqueePage.set(documentId, pageIndex);\n }\n updateMarquee(documentId, pageIndex, rect, modeId) {\n this.marqueeChange$.emit(documentId, { pageIndex, rect, modeId });\n }\n endMarquee(documentId, pageIndex, rect, modeId) {\n this.marqueeEnd$.emit(documentId, { pageIndex, rect, modeId });\n this.marqueeChange$.emit(documentId, { pageIndex, rect: null, modeId });\n this.marqueePage.delete(documentId);\n }\n cancelMarquee(documentId, modeId) {\n const pageIndex = this.marqueePage.get(documentId);\n if (pageIndex !== void 0) {\n this.marqueeChange$.emit(documentId, { pageIndex, rect: null, modeId });\n this.marqueePage.delete(documentId);\n }\n }\n /** @deprecated — shim for backward compat; delegates to pointerMode config */\n setMarqueeEnabled(documentId, enabled) {\n const modes = this.enabledModesPerDoc.get(documentId);\n if (!modes) return;\n const current = modes.get(\"pointerMode\");\n if (current) {\n current.enableMarquee = enabled;\n } else if (enabled) {\n modes.set(\"pointerMode\", { enableMarquee: true });\n }\n }\n /** @deprecated — shim for backward compat; reads pointerMode config */\n isMarqueeEnabled(documentId) {\n var _a;\n const config = (_a = this.enabledModesPerDoc.get(documentId)) == null ? void 0 : _a.get(\"pointerMode\");\n return (config == null ? void 0 : config.enableMarquee) !== false;\n }\n};\n_SelectionPlugin.id = \"selection\";\nlet SelectionPlugin = _SelectionPlugin;\nconst SelectionPluginPackage = {\n manifest,\n create: (registry, config) => new SelectionPlugin(SELECTION_PLUGIN_ID, registry, config),\n reducer: selectionReducer,\n initialState\n};\nexport {\n SELECTION_PLUGIN_ID,\n SelectionPlugin,\n SelectionPluginPackage,\n expandToLineBoundary,\n expandToWordBoundary,\n getVerticalOverlap,\n glyphAt,\n manifest,\n mergeAdjacentRects,\n rectIntersect,\n rectIsEmpty,\n rectUnion,\n rectsWithinSlice,\n shouldMergeHorizontalRects,\n sliceBounds\n};\n//# sourceMappingURL=index.js.map\n","function getCounterRotation(rect, rotation) {\n const { width: w, height: h } = rect.size;\n switch (rotation % 4) {\n case 1:\n return {\n matrix: `matrix(0, -1, 1, 0, 0, ${h})`,\n width: h,\n height: w\n };\n case 2:\n return {\n matrix: `matrix(-1, 0, 0, -1, ${w}, ${h})`,\n width: w,\n height: h\n };\n case 3:\n return {\n matrix: `matrix(0, 1, -1, 0, ${w}, 0)`,\n width: h,\n height: w\n };\n default:\n return {\n matrix: `matrix(1, 0, 0, 1, 0, 0)`,\n width: w,\n height: h\n };\n }\n}\nexport {\n getCounterRotation\n};\n//# sourceMappingURL=index.js.map\n","import { jsx } from \"react/jsx-runtime\";\nimport { getCounterRotation } from \"@embedpdf/utils\";\nimport { useRef, useEffect, Fragment, useCallback, useMemo } from \"react\";\nimport { rotatePointAround, calculateRotatedRectAABB, normalizeAngle } from \"@embedpdf/models\";\nconst dblClickProp = \"onDoubleClick\";\nfunction CounterRotate({ children, ...props }) {\n const { rect, rotation } = props;\n const { matrix, width, height } = getCounterRotation(rect, rotation);\n const elementRef = useRef(null);\n useEffect(() => {\n const element = elementRef.current;\n if (!element) return;\n const handlePointerDown = (e) => {\n e.stopPropagation();\n };\n const handleTouchStart = (e) => {\n e.stopPropagation();\n };\n element.addEventListener(\"pointerdown\", handlePointerDown, { capture: true });\n element.addEventListener(\"touchstart\", handleTouchStart, { capture: true, passive: true });\n return () => {\n element.removeEventListener(\"pointerdown\", handlePointerDown, { capture: true });\n element.removeEventListener(\"touchstart\", handleTouchStart, { capture: true });\n };\n }, []);\n const menuWrapperStyle = {\n position: \"absolute\",\n left: rect.origin.x,\n top: rect.origin.y,\n transform: matrix,\n transformOrigin: \"0 0\",\n width,\n height,\n pointerEvents: \"none\",\n zIndex: 3\n };\n const menuWrapperProps = {\n style: menuWrapperStyle,\n ref: (el) => {\n elementRef.current = el;\n }\n };\n return /* @__PURE__ */ jsx(Fragment, { children: children({\n menuWrapperProps,\n matrix,\n rect: {\n origin: { x: rect.origin.x, y: rect.origin.y },\n size: { width, height }\n }\n }) });\n}\nfunction getAnchor(handle) {\n return {\n x: handle.includes(\"e\") ? \"left\" : handle.includes(\"w\") ? \"right\" : \"center\",\n y: handle.includes(\"s\") ? \"top\" : handle.includes(\"n\") ? \"bottom\" : \"center\"\n };\n}\nfunction getAnchorPoint(rect, anchor) {\n const x = anchor.x === \"left\" ? rect.origin.x : anchor.x === \"right\" ? rect.origin.x + rect.size.width : rect.origin.x + rect.size.width / 2;\n const y = anchor.y === \"top\" ? rect.origin.y : anchor.y === \"bottom\" ? rect.origin.y + rect.size.height : rect.origin.y + rect.size.height / 2;\n return { x, y };\n}\nfunction applyResizeDelta(startRect, delta, anchor) {\n let x = startRect.origin.x;\n let y = startRect.origin.y;\n let width = startRect.size.width;\n let height = startRect.size.height;\n if (anchor.x === \"left\") {\n width += delta.x;\n } else if (anchor.x === \"right\") {\n x += delta.x;\n width -= delta.x;\n }\n if (anchor.y === \"top\") {\n height += delta.y;\n } else if (anchor.y === \"bottom\") {\n y += delta.y;\n height -= delta.y;\n }\n return { origin: { x, y }, size: { width, height } };\n}\nfunction enforceAspectRatio(rect, startRect, anchor, aspectRatio) {\n let { x, y } = rect.origin;\n let { width, height } = rect.size;\n const isEdgeHandle = anchor.x === \"center\" || anchor.y === \"center\";\n if (isEdgeHandle) {\n if (anchor.y === \"center\") {\n height = width / aspectRatio;\n y = startRect.origin.y + (startRect.size.height - height) / 2;\n } else {\n width = height * aspectRatio;\n x = startRect.origin.x + (startRect.size.width - width) / 2;\n }\n } else {\n const dw = Math.abs(width - startRect.size.width);\n const dh = Math.abs(height - startRect.size.height);\n const total = dw + dh;\n if (total === 0) {\n width = startRect.size.width;\n height = startRect.size.height;\n } else {\n const wWeight = dw / total;\n const hWeight = dh / total;\n const wFromW = width;\n const hFromW = width / aspectRatio;\n const wFromH = height * aspectRatio;\n const hFromH = height;\n width = wWeight * wFromW + hWeight * wFromH;\n height = wWeight * hFromW + hWeight * hFromH;\n }\n }\n if (anchor.x === \"right\") {\n x = startRect.origin.x + startRect.size.width - width;\n }\n if (anchor.y === \"bottom\") {\n y = startRect.origin.y + startRect.size.height - height;\n }\n return { origin: { x, y }, size: { width, height } };\n}\nfunction clampToBounds(rect, startRect, anchor, bbox, maintainAspectRatio) {\n if (!bbox) return rect;\n let { x, y } = rect.origin;\n let { width, height } = rect.size;\n width = Math.max(1, width);\n height = Math.max(1, height);\n const anchorX = anchor.x === \"left\" ? startRect.origin.x : startRect.origin.x + startRect.size.width;\n const anchorY = anchor.y === \"top\" ? startRect.origin.y : startRect.origin.y + startRect.size.height;\n const maxW = anchor.x === \"left\" ? bbox.width - anchorX : anchor.x === \"right\" ? anchorX : Math.min(startRect.origin.x, bbox.width - startRect.origin.x - startRect.size.width) * 2 + startRect.size.width;\n const maxH = anchor.y === \"top\" ? bbox.height - anchorY : anchor.y === \"bottom\" ? anchorY : Math.min(startRect.origin.y, bbox.height - startRect.origin.y - startRect.size.height) * 2 + startRect.size.height;\n if (maintainAspectRatio) {\n const scaleW = width > maxW ? maxW / width : 1;\n const scaleH = height > maxH ? maxH / height : 1;\n const scale = Math.min(scaleW, scaleH);\n if (scale < 1) {\n width *= scale;\n height *= scale;\n }\n } else {\n width = Math.min(width, maxW);\n height = Math.min(height, maxH);\n }\n if (anchor.x === \"left\") {\n x = anchorX;\n } else if (anchor.x === \"right\") {\n x = anchorX - width;\n } else {\n x = startRect.origin.x + (startRect.size.width - width) / 2;\n }\n if (anchor.y === \"top\") {\n y = anchorY;\n } else if (anchor.y === \"bottom\") {\n y = anchorY - height;\n } else {\n y = startRect.origin.y + (startRect.size.height - height) / 2;\n }\n x = Math.max(0, Math.min(x, bbox.width - width));\n y = Math.max(0, Math.min(y, bbox.height - height));\n return { origin: { x, y }, size: { width, height } };\n}\nfunction reanchorRect(rect, startRect, anchor) {\n let x;\n let y;\n if (anchor.x === \"left\") {\n x = startRect.origin.x;\n } else if (anchor.x === \"right\") {\n x = startRect.origin.x + startRect.size.width - rect.size.width;\n } else {\n x = startRect.origin.x + (startRect.size.width - rect.size.width) / 2;\n }\n if (anchor.y === \"top\") {\n y = startRect.origin.y;\n } else if (anchor.y === \"bottom\") {\n y = startRect.origin.y + startRect.size.height - rect.size.height;\n } else {\n y = startRect.origin.y + (startRect.size.height - rect.size.height) / 2;\n }\n return { origin: { x, y }, size: rect.size };\n}\nfunction applyConstraints(position, constraints, maintainAspectRatio, skipBoundingClamp = false) {\n if (!constraints) return position;\n let {\n origin: { x, y },\n size: { width, height }\n } = position;\n const minW = constraints.minWidth ?? 1;\n const minH = constraints.minHeight ?? 1;\n const maxW = constraints.maxWidth;\n const maxH = constraints.maxHeight;\n if (maintainAspectRatio && width > 0 && height > 0) {\n const ratio = width / height;\n if (width < minW) {\n width = minW;\n height = width / ratio;\n }\n if (height < minH) {\n height = minH;\n width = height * ratio;\n }\n if (maxW !== void 0 && width > maxW) {\n width = maxW;\n height = width / ratio;\n }\n if (maxH !== void 0 && height > maxH) {\n height = maxH;\n width = height * ratio;\n }\n } else {\n width = Math.max(minW, width);\n height = Math.max(minH, height);\n if (maxW !== void 0) width = Math.min(maxW, width);\n if (maxH !== void 0) height = Math.min(maxH, height);\n }\n if (constraints.boundingBox && !skipBoundingClamp) {\n x = Math.max(0, Math.min(x, constraints.boundingBox.width - width));\n y = Math.max(0, Math.min(y, constraints.boundingBox.height - height));\n }\n return { origin: { x, y }, size: { width, height } };\n}\nfunction isRectWithinRotatedBounds(rect, angleDegrees, bbox) {\n const eps = 1e-6;\n const aabb = calculateRotatedRectAABB(rect, angleDegrees);\n return aabb.origin.x >= -eps && aabb.origin.y >= -eps && aabb.origin.x + aabb.size.width <= bbox.width + eps && aabb.origin.y + aabb.size.height <= bbox.height + eps;\n}\nfunction computeResizeStep(delta, handle, config, clampLocalBounds, skipConstraintBoundingClamp) {\n const { startRect, maintainAspectRatio = false, annotationRotation = 0, constraints } = config;\n const anchor = getAnchor(handle);\n const aspectRatio = startRect.size.width / startRect.size.height || 1;\n let rect = applyResizeDelta(startRect, delta, anchor);\n if (maintainAspectRatio) {\n rect = enforceAspectRatio(rect, startRect, anchor, aspectRatio);\n }\n if (clampLocalBounds) {\n rect = clampToBounds(rect, startRect, anchor, constraints == null ? void 0 : constraints.boundingBox, maintainAspectRatio);\n }\n rect = applyConstraints(rect, constraints, maintainAspectRatio, skipConstraintBoundingClamp);\n if (skipConstraintBoundingClamp) {\n rect = reanchorRect(rect, startRect, anchor);\n }\n if (annotationRotation !== 0) {\n const anchorPt = getAnchorPoint(startRect, anchor);\n const oldCenter = {\n x: startRect.origin.x + startRect.size.width / 2,\n y: startRect.origin.y + startRect.size.height / 2\n };\n const newCenter = {\n x: rect.origin.x + rect.size.width / 2,\n y: rect.origin.y + rect.size.height / 2\n };\n const oldVisual = rotatePointAround(anchorPt, oldCenter, annotationRotation);\n const newVisual = rotatePointAround(anchorPt, newCenter, annotationRotation);\n rect = {\n origin: {\n x: rect.origin.x + (oldVisual.x - newVisual.x),\n y: rect.origin.y + (oldVisual.y - newVisual.y)\n },\n size: rect.size\n };\n }\n return rect;\n}\nfunction computeResizedRect(delta, handle, config) {\n const { annotationRotation = 0, constraints } = config;\n const bbox = constraints == null ? void 0 : constraints.boundingBox;\n if (annotationRotation !== 0 && bbox) {\n const target = computeResizeStep(delta, handle, config, false, true);\n if (isRectWithinRotatedBounds(target, annotationRotation, bbox)) {\n return target;\n }\n let best = computeResizeStep({ x: 0, y: 0 }, handle, config, false, true);\n let low = 0;\n let high = 1;\n for (let i = 0; i < 20; i += 1) {\n const mid = (low + high) / 2;\n const trial = computeResizeStep(\n { x: delta.x * mid, y: delta.y * mid },\n handle,\n config,\n false,\n true\n );\n if (isRectWithinRotatedBounds(trial, annotationRotation, bbox)) {\n best = trial;\n low = mid;\n } else {\n high = mid;\n }\n }\n return best;\n }\n return computeResizeStep(delta, handle, config, true, false);\n}\nconst ROTATION_HANDLE_MARGIN = 35;\nconst HANDLE_BASE_ANGLE = {\n n: 0,\n ne: 45,\n e: 90,\n se: 135,\n s: 180,\n sw: 225,\n w: 270,\n nw: 315\n};\nconst SECTOR_CURSORS = [\n \"ns-resize\",\n // 0: north\n \"nesw-resize\",\n // 1: NE\n \"ew-resize\",\n // 2: east\n \"nwse-resize\",\n // 3: SE\n \"ns-resize\",\n // 4: south\n \"nesw-resize\",\n // 5: SW\n \"ew-resize\",\n // 6: west\n \"nwse-resize\"\n // 7: NW\n];\nfunction diagonalCursor(handle, pageQuarterTurns, annotationRotation = 0) {\n const pageAngle = pageQuarterTurns * 90;\n const totalAngle = HANDLE_BASE_ANGLE[handle] + pageAngle + annotationRotation;\n const normalized = (totalAngle % 360 + 360) % 360;\n const sector = Math.round(normalized / 45) % 8;\n return SECTOR_CURSORS[sector];\n}\nfunction edgeOffset(k, spacing, mode) {\n const base = -k / 2;\n if (mode === \"center\") return base;\n return mode === \"outside\" ? base - spacing : base + spacing;\n}\nfunction describeResizeFromConfig(cfg, ui = {}) {\n const {\n handleSize = 8,\n spacing = 1,\n offsetMode = \"outside\",\n includeSides = false,\n zIndex = 3,\n rotationAwareCursor = true\n } = ui;\n const pageQuarterTurns = (cfg.pageRotation ?? 0) % 4;\n const annotationRot = cfg.annotationRotation ?? 0;\n const off = (edge) => ({\n [edge]: edgeOffset(handleSize, spacing, offsetMode) + \"px\"\n });\n const corners = [\n [\"nw\", { ...off(\"top\"), ...off(\"left\") }],\n [\"ne\", { ...off(\"top\"), ...off(\"right\") }],\n [\"sw\", { ...off(\"bottom\"), ...off(\"left\") }],\n [\"se\", { ...off(\"bottom\"), ...off(\"right\") }]\n ];\n const sides = includeSides ? [\n [\"n\", { ...off(\"top\"), left: `calc(50% - ${handleSize / 2}px)` }],\n [\"s\", { ...off(\"bottom\"), left: `calc(50% - ${handleSize / 2}px)` }],\n [\"w\", { ...off(\"left\"), top: `calc(50% - ${handleSize / 2}px)` }],\n [\"e\", { ...off(\"right\"), top: `calc(50% - ${handleSize / 2}px)` }]\n ] : [];\n const all = [...corners, ...sides];\n return all.map(([handle, pos]) => ({\n handle,\n style: {\n position: \"absolute\",\n width: handleSize + \"px\",\n height: handleSize + \"px\",\n borderRadius: \"50%\",\n zIndex,\n cursor: rotationAwareCursor ? diagonalCursor(handle, pageQuarterTurns, annotationRot) : \"default\",\n pointerEvents: \"auto\",\n touchAction: \"none\",\n ...pos\n },\n attrs: { \"data-epdf-handle\": handle }\n }));\n}\nfunction describeVerticesFromConfig(cfg, ui = {}, liveVertices) {\n const { vertexSize = 12, zIndex = 4 } = ui;\n const rect = cfg.element;\n const scale = cfg.scale ?? 1;\n const verts = liveVertices ?? cfg.vertices ?? [];\n return verts.map((v, i) => {\n const left = (v.x - rect.origin.x) * scale - vertexSize / 2;\n const top = (v.y - rect.origin.y) * scale - vertexSize / 2;\n return {\n handle: \"nw\",\n // not used; kept for type\n style: {\n position: \"absolute\",\n left: left + \"px\",\n top: top + \"px\",\n width: vertexSize + \"px\",\n height: vertexSize + \"px\",\n borderRadius: \"50%\",\n cursor: \"pointer\",\n zIndex,\n pointerEvents: \"auto\",\n touchAction: \"none\"\n },\n attrs: { \"data-epdf-vertex\": i }\n };\n });\n}\nfunction describeRotationFromConfig(cfg, ui = {}, currentAngle = 0) {\n const { handleSize = 16, zIndex = 5, showConnector = true, connectorWidth = 1 } = ui;\n const scale = cfg.scale ?? 1;\n const rect = cfg.element;\n const orbitRect = cfg.rotationElement ?? rect;\n const orbitCenter = cfg.rotationCenter ?? {\n x: rect.origin.x + rect.size.width / 2,\n y: rect.origin.y + rect.size.height / 2\n };\n orbitRect.size.width * scale;\n orbitRect.size.height * scale;\n const centerX = (orbitCenter.x - orbitRect.origin.x) * scale;\n const centerY = (orbitCenter.y - orbitRect.origin.y) * scale;\n const angleRad = currentAngle * Math.PI / 180;\n const margin = ui.margin ?? ROTATION_HANDLE_MARGIN;\n const radius = rect.size.height * scale / 2 + margin;\n const handleCenterX = centerX + radius * Math.sin(angleRad);\n const handleCenterY = centerY - radius * Math.cos(angleRad);\n const handleLeft = handleCenterX - handleSize / 2;\n const handleTop = handleCenterY - handleSize / 2;\n return {\n handleStyle: {\n position: \"absolute\",\n left: handleLeft + \"px\",\n top: handleTop + \"px\",\n width: handleSize + \"px\",\n height: handleSize + \"px\",\n borderRadius: \"50%\",\n cursor: \"grab\",\n zIndex,\n pointerEvents: \"auto\",\n touchAction: \"none\"\n },\n connectorStyle: showConnector ? {\n position: \"absolute\",\n left: centerX - connectorWidth / 2 + \"px\",\n top: centerY - radius + \"px\",\n width: connectorWidth + \"px\",\n height: radius + \"px\",\n transformOrigin: \"center bottom\",\n transform: `rotate(${currentAngle}deg)`,\n zIndex: zIndex - 1,\n pointerEvents: \"none\"\n } : {},\n radius,\n attrs: { \"data-epdf-rotation-handle\": true }\n };\n}\nclass DragResizeController {\n constructor(config, onUpdate) {\n this.config = config;\n this.onUpdate = onUpdate;\n this.state = \"idle\";\n this.startPoint = null;\n this.startElement = null;\n this.startRotationElement = null;\n this.gestureRotationCenter = null;\n this.activeHandle = null;\n this.currentPosition = null;\n this.activeVertexIndex = null;\n this.startVertices = [];\n this.currentVertices = [];\n this.rotationCenter = null;\n this.centerScreen = null;\n this.initialRotation = 0;\n this.lastComputedRotation = 0;\n this.rotationDelta = 0;\n this.rotationSnappedAngle = null;\n this.currentVertices = config.vertices || [];\n }\n updateConfig(config) {\n this.config = { ...this.config, ...config };\n if (this.state !== \"vertex-editing\") {\n this.currentVertices = config.vertices || [];\n }\n }\n // ---------------------------------------------------------------------------\n // Gesture start\n // ---------------------------------------------------------------------------\n startDrag(clientX, clientY) {\n this.state = \"dragging\";\n this.startPoint = { x: clientX, y: clientY };\n this.startElement = { ...this.config.element };\n this.startRotationElement = this.config.rotationElement ? { ...this.config.rotationElement } : null;\n this.currentPosition = { ...this.config.element };\n this.onUpdate({\n state: \"start\",\n transformData: {\n type: \"move\",\n changes: { rect: this.startElement }\n }\n });\n }\n startResize(handle, clientX, clientY) {\n this.state = \"resizing\";\n this.activeHandle = handle;\n this.startPoint = { x: clientX, y: clientY };\n this.startElement = { ...this.config.element };\n this.currentPosition = { ...this.config.element };\n this.onUpdate({\n state: \"start\",\n transformData: {\n type: \"resize\",\n changes: { rect: this.startElement },\n metadata: {\n handle: this.activeHandle,\n maintainAspectRatio: this.config.maintainAspectRatio\n }\n }\n });\n }\n startVertexEdit(vertexIndex, clientX, clientY) {\n this.currentVertices = [...this.config.vertices ?? this.currentVertices];\n if (vertexIndex < 0 || vertexIndex >= this.currentVertices.length) return;\n this.state = \"vertex-editing\";\n this.activeVertexIndex = vertexIndex;\n this.startPoint = { x: clientX, y: clientY };\n this.startVertices = [...this.currentVertices];\n this.gestureRotationCenter = this.config.rotationCenter ?? {\n x: this.config.element.origin.x + this.config.element.size.width / 2,\n y: this.config.element.origin.y + this.config.element.size.height / 2\n };\n this.onUpdate({\n state: \"start\",\n transformData: {\n type: \"vertex-edit\",\n changes: { vertices: this.startVertices },\n metadata: { vertexIndex }\n }\n });\n }\n startRotation(clientX, clientY, initialRotation = 0, orbitRadiusPx) {\n this.state = \"rotating\";\n this.startPoint = { x: clientX, y: clientY };\n this.startElement = { ...this.config.element };\n this.rotationCenter = this.config.rotationCenter ?? {\n x: this.config.element.origin.x + this.config.element.size.width / 2,\n y: this.config.element.origin.y + this.config.element.size.height / 2\n };\n const { scale = 1 } = this.config;\n const orbitRect = this.config.rotationElement ?? this.config.element;\n const sw = orbitRect.size.width * scale;\n const sh = orbitRect.size.height * scale;\n const radius = orbitRadiusPx ?? Math.max(sw, sh) / 2 + ROTATION_HANDLE_MARGIN;\n const pageRotOffset = (this.config.pageRotation ?? 0) * 90;\n const screenAngleRad = (initialRotation + pageRotOffset) * Math.PI / 180;\n this.centerScreen = {\n x: clientX - radius * Math.sin(screenAngleRad),\n y: clientY + radius * Math.cos(screenAngleRad)\n };\n this.initialRotation = initialRotation;\n this.lastComputedRotation = initialRotation;\n this.rotationDelta = 0;\n this.rotationSnappedAngle = null;\n this.onUpdate({\n state: \"start\",\n transformData: {\n type: \"rotate\",\n changes: { rotation: initialRotation },\n metadata: {\n rotationAngle: initialRotation,\n rotationDelta: 0,\n rotationCenter: this.rotationCenter,\n isSnapped: false\n }\n }\n });\n }\n // ---------------------------------------------------------------------------\n // Gesture move\n // ---------------------------------------------------------------------------\n move(clientX, clientY, buttons, lockAspectRatio) {\n if (this.state === \"idle\" || !this.startPoint) return;\n if (buttons !== void 0 && buttons === 0) {\n this.end();\n return;\n }\n if (this.state === \"dragging\" && this.startElement) {\n const delta = this.calculateDelta(clientX, clientY);\n const position = this.calculateDragPosition(delta);\n this.currentPosition = position;\n this.onUpdate({\n state: \"move\",\n transformData: { type: \"move\", changes: { rect: position } }\n });\n } else if (this.state === \"resizing\" && this.activeHandle && this.startElement) {\n const delta = this.calculateLocalDelta(clientX, clientY);\n const position = computeResizedRect(delta, this.activeHandle, {\n startRect: this.startElement,\n maintainAspectRatio: this.config.maintainAspectRatio || !!lockAspectRatio,\n annotationRotation: this.config.annotationRotation,\n constraints: this.config.constraints\n });\n this.currentPosition = position;\n this.onUpdate({\n state: \"move\",\n transformData: {\n type: \"resize\",\n changes: { rect: position },\n metadata: {\n handle: this.activeHandle,\n maintainAspectRatio: this.config.maintainAspectRatio || !!lockAspectRatio\n }\n }\n });\n } else if (this.state === \"vertex-editing\" && this.activeVertexIndex !== null) {\n const vertices = this.calculateVertexPosition(clientX, clientY);\n this.currentVertices = vertices;\n this.onUpdate({\n state: \"move\",\n transformData: {\n type: \"vertex-edit\",\n changes: { vertices },\n metadata: { vertexIndex: this.activeVertexIndex }\n }\n });\n } else if (this.state === \"rotating\" && this.rotationCenter) {\n const absoluteAngle = this.calculateAngleFromMouse(clientX, clientY);\n const snapResult = this.applyRotationSnapping(absoluteAngle);\n const snappedAngle = normalizeAngle(snapResult.angle);\n const previousAngle = this.lastComputedRotation;\n const rawDelta = snappedAngle - previousAngle;\n const adjustedDelta = rawDelta > 180 ? rawDelta - 360 : rawDelta < -180 ? rawDelta + 360 : rawDelta;\n this.rotationDelta += adjustedDelta;\n this.lastComputedRotation = snappedAngle;\n this.rotationSnappedAngle = snapResult.isSnapped ? snappedAngle : null;\n this.onUpdate({\n state: \"move\",\n transformData: {\n type: \"rotate\",\n changes: { rotation: snappedAngle },\n metadata: {\n rotationAngle: snappedAngle,\n rotationDelta: this.rotationDelta,\n rotationCenter: this.rotationCenter,\n isSnapped: snapResult.isSnapped,\n snappedAngle: this.rotationSnappedAngle ?? void 0,\n cursorPosition: { clientX, clientY }\n }\n }\n });\n }\n }\n // ---------------------------------------------------------------------------\n // Gesture end / cancel\n // ---------------------------------------------------------------------------\n end() {\n if (this.state === \"idle\") return;\n const wasState = this.state;\n const handle = this.activeHandle;\n const vertexIndex = this.activeVertexIndex;\n if (wasState === \"vertex-editing\") {\n this.onUpdate({\n state: \"end\",\n transformData: {\n type: \"vertex-edit\",\n changes: { vertices: this.currentVertices },\n metadata: { vertexIndex: vertexIndex || void 0 }\n }\n });\n } else if (wasState === \"rotating\") {\n this.onUpdate({\n state: \"end\",\n transformData: {\n type: \"rotate\",\n changes: { rotation: this.lastComputedRotation },\n metadata: {\n rotationAngle: this.lastComputedRotation,\n rotationDelta: this.rotationDelta,\n rotationCenter: this.rotationCenter || void 0,\n isSnapped: this.rotationSnappedAngle !== null,\n snappedAngle: this.rotationSnappedAngle ?? void 0\n }\n }\n });\n } else {\n const finalPosition = this.currentPosition || this.config.element;\n this.onUpdate({\n state: \"end\",\n transformData: {\n type: wasState === \"dragging\" ? \"move\" : \"resize\",\n changes: { rect: finalPosition },\n metadata: wasState === \"dragging\" ? void 0 : {\n handle: handle || void 0,\n maintainAspectRatio: this.config.maintainAspectRatio\n }\n }\n });\n }\n this.reset();\n }\n cancel() {\n if (this.state === \"idle\") return;\n if (this.state === \"vertex-editing\") {\n this.onUpdate({\n state: \"end\",\n transformData: {\n type: \"vertex-edit\",\n changes: { vertices: this.startVertices },\n metadata: { vertexIndex: this.activeVertexIndex || void 0 }\n }\n });\n } else if (this.state === \"rotating\") {\n this.onUpdate({\n state: \"end\",\n transformData: {\n type: \"rotate\",\n changes: { rotation: this.initialRotation },\n metadata: {\n rotationAngle: this.initialRotation,\n rotationDelta: 0,\n rotationCenter: this.rotationCenter || void 0,\n isSnapped: false\n }\n }\n });\n } else if (this.startElement) {\n this.onUpdate({\n state: \"end\",\n transformData: {\n type: this.state === \"dragging\" ? \"move\" : \"resize\",\n changes: { rect: this.startElement },\n metadata: this.state === \"dragging\" ? void 0 : {\n handle: this.activeHandle || void 0,\n maintainAspectRatio: this.config.maintainAspectRatio\n }\n }\n });\n }\n this.reset();\n }\n // ---------------------------------------------------------------------------\n // Private: state management\n // ---------------------------------------------------------------------------\n reset() {\n this.state = \"idle\";\n this.startPoint = null;\n this.startElement = null;\n this.startRotationElement = null;\n this.gestureRotationCenter = null;\n this.activeHandle = null;\n this.currentPosition = null;\n this.activeVertexIndex = null;\n this.startVertices = [];\n this.rotationCenter = null;\n this.centerScreen = null;\n this.initialRotation = 0;\n this.lastComputedRotation = 0;\n this.rotationDelta = 0;\n this.rotationSnappedAngle = null;\n }\n // ---------------------------------------------------------------------------\n // Private: coordinate transformation (screen → page → local)\n // ---------------------------------------------------------------------------\n calculateDelta(clientX, clientY) {\n if (!this.startPoint) return { x: 0, y: 0 };\n const rawDelta = {\n x: clientX - this.startPoint.x,\n y: clientY - this.startPoint.y\n };\n return this.transformDelta(rawDelta);\n }\n transformDelta(delta) {\n const { pageRotation = 0, scale = 1 } = this.config;\n const rad = pageRotation * Math.PI / 2;\n const cos = Math.cos(rad);\n const sin = Math.sin(rad);\n const scaledX = delta.x / scale;\n const scaledY = delta.y / scale;\n return {\n x: cos * scaledX + sin * scaledY,\n y: -sin * scaledX + cos * scaledY\n };\n }\n /**\n * Calculate delta projected into the annotation's local (unrotated) coordinate space.\n * Used for resize and vertex-edit where mouse movement must be mapped to the\n * annotation's own axes, accounting for its rotation.\n */\n calculateLocalDelta(clientX, clientY) {\n const pageDelta = this.calculateDelta(clientX, clientY);\n const { annotationRotation = 0 } = this.config;\n if (annotationRotation === 0) return pageDelta;\n const rad = annotationRotation * Math.PI / 180;\n const cos = Math.cos(rad);\n const sin = Math.sin(rad);\n return {\n x: cos * pageDelta.x + sin * pageDelta.y,\n y: -sin * pageDelta.x + cos * pageDelta.y\n };\n }\n // ---------------------------------------------------------------------------\n // Private: vertex clamping\n // ---------------------------------------------------------------------------\n clampPoint(p) {\n var _a;\n const bbox = (_a = this.config.constraints) == null ? void 0 : _a.boundingBox;\n if (!bbox) return p;\n const { annotationRotation = 0 } = this.config;\n if (annotationRotation === 0) {\n return {\n x: Math.max(0, Math.min(p.x, bbox.width)),\n y: Math.max(0, Math.min(p.y, bbox.height))\n };\n }\n const center = this.gestureRotationCenter ?? this.config.rotationCenter ?? {\n x: this.config.element.origin.x + this.config.element.size.width / 2,\n y: this.config.element.origin.y + this.config.element.size.height / 2\n };\n const visual = rotatePointAround(p, center, annotationRotation);\n const clampedX = Math.max(0, Math.min(visual.x, bbox.width));\n const clampedY = Math.max(0, Math.min(visual.y, bbox.height));\n if (clampedX === visual.x && clampedY === visual.y) return p;\n return rotatePointAround({ x: clampedX, y: clampedY }, center, -annotationRotation);\n }\n calculateVertexPosition(clientX, clientY) {\n if (this.activeVertexIndex === null) return this.startVertices;\n const delta = this.calculateLocalDelta(clientX, clientY);\n const newVertices = [...this.startVertices];\n const currentVertex = newVertices[this.activeVertexIndex];\n const moved = {\n x: currentVertex.x + delta.x,\n y: currentVertex.y + delta.y\n };\n newVertices[this.activeVertexIndex] = this.clampPoint(moved);\n return newVertices;\n }\n // ---------------------------------------------------------------------------\n // Private: drag position\n // ---------------------------------------------------------------------------\n calculateDragPosition(delta) {\n if (!this.startElement) return this.config.element;\n const position = {\n origin: {\n x: this.startElement.origin.x + delta.x,\n y: this.startElement.origin.y + delta.y\n },\n size: {\n width: this.startElement.size.width,\n height: this.startElement.size.height\n }\n };\n const { annotationRotation = 0, constraints } = this.config;\n const bbox = constraints == null ? void 0 : constraints.boundingBox;\n if (annotationRotation !== 0 && bbox) {\n let aabbW;\n let aabbH;\n let offsetX;\n let offsetY;\n if (this.startRotationElement) {\n aabbW = this.startRotationElement.size.width;\n aabbH = this.startRotationElement.size.height;\n offsetX = this.startRotationElement.origin.x - this.startElement.origin.x;\n offsetY = this.startRotationElement.origin.y - this.startElement.origin.y;\n } else {\n const rad = Math.abs(annotationRotation * Math.PI / 180);\n const cos = Math.abs(Math.cos(rad));\n const sin = Math.abs(Math.sin(rad));\n const w = position.size.width;\n const h = position.size.height;\n aabbW = w * cos + h * sin;\n aabbH = w * sin + h * cos;\n offsetX = (w - aabbW) / 2;\n offsetY = (h - aabbH) / 2;\n }\n let { x, y } = position.origin;\n x = Math.max(-offsetX, Math.min(x, bbox.width - aabbW - offsetX));\n y = Math.max(-offsetY, Math.min(y, bbox.height - aabbH - offsetY));\n return { origin: { x, y }, size: position.size };\n }\n return applyConstraints(position, constraints, this.config.maintainAspectRatio ?? false);\n }\n // ---------------------------------------------------------------------------\n // Private: rotation\n // ---------------------------------------------------------------------------\n /**\n * Calculate the angle from the center to a point in screen coordinates.\n */\n calculateAngleFromMouse(clientX, clientY) {\n if (!this.centerScreen) return this.initialRotation;\n const dx = clientX - this.centerScreen.x;\n const dy = clientY - this.centerScreen.y;\n const dist = Math.sqrt(dx * dx + dy * dy);\n if (dist < 10) return this.lastComputedRotation;\n const pageRotOffset = (this.config.pageRotation ?? 0) * 90;\n const angleDeg = Math.atan2(dy, dx) * (180 / Math.PI) + 90 - pageRotOffset;\n return normalizeAngle(Math.round(angleDeg));\n }\n applyRotationSnapping(angle) {\n const snapAngles = this.config.rotationSnapAngles ?? [0, 90, 180, 270];\n const threshold = this.config.rotationSnapThreshold ?? 4;\n const normalizedAngle = normalizeAngle(angle);\n for (const candidate of snapAngles) {\n const normalizedCandidate = normalizeAngle(candidate);\n const diff = Math.abs(normalizedAngle - normalizedCandidate);\n const minimalDiff = Math.min(diff, 360 - diff);\n if (minimalDiff <= threshold) {\n return {\n angle: normalizedCandidate,\n isSnapped: true,\n snapTarget: normalizedCandidate\n };\n }\n }\n return { angle: normalizedAngle, isSnapped: false };\n }\n}\nfunction useDragResize(options) {\n const { onUpdate, enabled = true, ...config } = options;\n const controllerRef = useRef(null);\n const onUpdateRef = useRef(onUpdate);\n const activePointerIdRef = useRef(null);\n const activeTargetRef = useRef(null);\n useEffect(() => {\n onUpdateRef.current = onUpdate;\n }, [onUpdate]);\n useEffect(() => {\n if (!controllerRef.current) {\n controllerRef.current = new DragResizeController(\n config,\n (event) => {\n var _a;\n return (_a = onUpdateRef.current) == null ? void 0 : _a.call(onUpdateRef, event);\n }\n );\n } else {\n controllerRef.current.updateConfig(config);\n }\n }, [\n config.element,\n config.rotationCenter,\n config.rotationElement,\n config.constraints,\n config.maintainAspectRatio,\n config.pageRotation,\n config.annotationRotation,\n config.scale,\n config.vertices\n ]);\n const endPointerSession = useCallback((pointerId) => {\n var _a, _b;\n const activePointerId = activePointerIdRef.current;\n const target = activeTargetRef.current;\n const id = pointerId ?? activePointerId;\n if (target && id !== null) {\n try {\n if ((_a = target.hasPointerCapture) == null ? void 0 : _a.call(target, id)) {\n (_b = target.releasePointerCapture) == null ? void 0 : _b.call(target, id);\n }\n } catch {\n }\n }\n activePointerIdRef.current = null;\n activeTargetRef.current = null;\n }, []);\n const startPointerSession = useCallback(\n (e) => {\n var _a;\n if (activePointerIdRef.current !== null && activePointerIdRef.current !== e.pointerId) {\n (_a = controllerRef.current) == null ? void 0 : _a.end();\n endPointerSession(activePointerIdRef.current);\n }\n const target = e.currentTarget;\n activePointerIdRef.current = e.pointerId;\n activeTargetRef.current = target;\n try {\n target.setPointerCapture(e.pointerId);\n } catch {\n }\n },\n [endPointerSession]\n );\n useEffect(() => {\n const eventTarget = globalThis;\n const handleGlobalPointerEnd = (e) => {\n var _a;\n const activePointerId = activePointerIdRef.current;\n if (activePointerId === null || e.pointerId !== activePointerId) return;\n (_a = controllerRef.current) == null ? void 0 : _a.end();\n endPointerSession(e.pointerId);\n };\n const handleWindowBlur = () => {\n var _a;\n if (activePointerIdRef.current === null) return;\n (_a = controllerRef.current) == null ? void 0 : _a.end();\n endPointerSession();\n };\n eventTarget.addEventListener(\"pointerup\", handleGlobalPointerEnd, true);\n eventTarget.addEventListener(\"pointercancel\", handleGlobalPointerEnd, true);\n eventTarget.addEventListener(\"blur\", handleWindowBlur, true);\n return () => {\n eventTarget.removeEventListener(\"pointerup\", handleGlobalPointerEnd, true);\n eventTarget.removeEventListener(\"pointercancel\", handleGlobalPointerEnd, true);\n eventTarget.removeEventListener(\"blur\", handleWindowBlur, true);\n };\n }, [endPointerSession]);\n useEffect(() => {\n return () => {\n var _a;\n if (activePointerIdRef.current !== null) {\n (_a = controllerRef.current) == null ? void 0 : _a.end();\n endPointerSession();\n }\n };\n }, [endPointerSession]);\n const handleDragStart = useCallback(\n (e) => {\n var _a;\n if (!enabled) return;\n e.preventDefault();\n e.stopPropagation();\n (_a = controllerRef.current) == null ? void 0 : _a.startDrag(e.clientX, e.clientY);\n startPointerSession(e);\n },\n [enabled, startPointerSession]\n );\n const handleMove = useCallback(\n (e) => {\n var _a;\n e.preventDefault();\n e.stopPropagation();\n const activePointerId = activePointerIdRef.current;\n if (activePointerId !== null && e.pointerId !== activePointerId) return;\n (_a = controllerRef.current) == null ? void 0 : _a.move(e.clientX, e.clientY, e.buttons, e.shiftKey);\n if (activePointerIdRef.current === e.pointerId && e.buttons === 0) {\n endPointerSession(e.pointerId);\n }\n },\n [endPointerSession]\n );\n const handleEndLike = useCallback(\n (e) => {\n var _a;\n e.preventDefault();\n e.stopPropagation();\n const activePointerId = activePointerIdRef.current;\n if (activePointerId !== null && e.pointerId !== activePointerId) return;\n (_a = controllerRef.current) == null ? void 0 : _a.end();\n endPointerSession(e.pointerId);\n },\n [endPointerSession]\n );\n const handleLostPointerCapture = useCallback(\n (e) => {\n var _a;\n const activePointerId = activePointerIdRef.current;\n if (activePointerId === null || e.pointerId !== activePointerId) return;\n (_a = controllerRef.current) == null ? void 0 : _a.end();\n endPointerSession(e.pointerId);\n },\n [endPointerSession]\n );\n const createResizeHandler = useCallback(\n (handle) => ({\n onPointerDown: (e) => {\n var _a;\n if (!enabled) return;\n e.preventDefault();\n e.stopPropagation();\n (_a = controllerRef.current) == null ? void 0 : _a.startResize(handle, e.clientX, e.clientY);\n startPointerSession(e);\n },\n onPointerMove: handleMove,\n onPointerUp: handleEndLike,\n onPointerCancel: handleEndLike,\n onLostPointerCapture: handleLostPointerCapture\n }),\n [enabled, handleMove, handleEndLike, handleLostPointerCapture, startPointerSession]\n );\n const createVertexHandler = useCallback(\n (vertexIndex) => ({\n onPointerDown: (e) => {\n var _a;\n if (!enabled) return;\n e.preventDefault();\n e.stopPropagation();\n (_a = controllerRef.current) == null ? void 0 : _a.startVertexEdit(vertexIndex, e.clientX, e.clientY);\n startPointerSession(e);\n },\n onPointerMove: handleMove,\n onPointerUp: handleEndLike,\n onPointerCancel: handleEndLike,\n onLostPointerCapture: handleLostPointerCapture\n }),\n [enabled, handleMove, handleEndLike, handleLostPointerCapture, startPointerSession]\n );\n const createRotationHandler = useCallback(\n (initialRotation = 0, orbitRadiusPx) => ({\n onPointerDown: (e) => {\n var _a;\n if (!enabled) return;\n e.preventDefault();\n e.stopPropagation();\n const handleRect = e.currentTarget.getBoundingClientRect();\n const handleCenterX = handleRect.left + handleRect.width / 2;\n const handleCenterY = handleRect.top + handleRect.height / 2;\n (_a = controllerRef.current) == null ? void 0 : _a.startRotation(\n handleCenterX,\n handleCenterY,\n initialRotation,\n orbitRadiusPx\n );\n startPointerSession(e);\n },\n onPointerMove: handleMove,\n onPointerUp: handleEndLike,\n onPointerCancel: handleEndLike,\n onLostPointerCapture: handleLostPointerCapture\n }),\n [enabled, handleMove, handleEndLike, handleLostPointerCapture, startPointerSession]\n );\n return {\n dragProps: enabled ? {\n onPointerDown: handleDragStart,\n onPointerMove: handleMove,\n onPointerUp: handleEndLike,\n onPointerCancel: handleEndLike,\n onLostPointerCapture: handleLostPointerCapture\n } : {},\n createResizeProps: createResizeHandler,\n createVertexProps: createVertexHandler,\n createRotationProps: createRotationHandler\n };\n}\nfunction useInteractionHandles(opts) {\n var _a, _b, _c, _d, _e, _f;\n const {\n controller,\n resizeUI,\n vertexUI,\n rotationUI,\n includeVertices = false,\n includeRotation = false,\n currentRotation = 0,\n handleAttrs,\n vertexAttrs,\n rotationAttrs\n } = opts;\n const { dragProps, createResizeProps, createVertexProps, createRotationProps } = useDragResize(controller);\n const resize = useMemo(() => {\n const desc = describeResizeFromConfig(controller, resizeUI);\n return desc.map((d) => {\n var _a2;\n return {\n key: (_a2 = d.attrs) == null ? void 0 : _a2[\"data-epdf-handle\"],\n style: d.style,\n ...createResizeProps(d.handle),\n ...d.attrs ?? {},\n ...(handleAttrs == null ? void 0 : handleAttrs(d.handle)) ?? {}\n };\n });\n }, [\n controller.element.origin.x,\n controller.element.origin.y,\n controller.element.size.width,\n controller.element.size.height,\n controller.scale,\n controller.pageRotation,\n controller.annotationRotation,\n controller.maintainAspectRatio,\n resizeUI == null ? void 0 : resizeUI.handleSize,\n resizeUI == null ? void 0 : resizeUI.spacing,\n resizeUI == null ? void 0 : resizeUI.offsetMode,\n resizeUI == null ? void 0 : resizeUI.includeSides,\n resizeUI == null ? void 0 : resizeUI.zIndex,\n resizeUI == null ? void 0 : resizeUI.rotationAwareCursor,\n createResizeProps,\n handleAttrs\n ]);\n const vertices = useMemo(() => {\n if (!includeVertices) return [];\n const desc = describeVerticesFromConfig(controller, vertexUI, controller.vertices);\n return desc.map((d, i) => ({\n key: i,\n style: d.style,\n ...createVertexProps(i),\n ...d.attrs ?? {},\n ...(vertexAttrs == null ? void 0 : vertexAttrs(i)) ?? {}\n }));\n }, [\n includeVertices,\n controller.element.origin.x,\n controller.element.origin.y,\n controller.element.size.width,\n controller.element.size.height,\n controller.scale,\n controller.vertices,\n // identity/content drives recalculation\n vertexUI == null ? void 0 : vertexUI.vertexSize,\n vertexUI == null ? void 0 : vertexUI.zIndex,\n createVertexProps,\n vertexAttrs\n ]);\n const rotation = useMemo(() => {\n if (!includeRotation) return null;\n const desc = describeRotationFromConfig(controller, rotationUI, currentRotation);\n return {\n handle: {\n style: desc.handleStyle,\n ...createRotationProps(currentRotation, desc.radius),\n ...desc.attrs ?? {},\n ...(rotationAttrs == null ? void 0 : rotationAttrs()) ?? {}\n },\n connector: {\n style: desc.connectorStyle,\n \"data-epdf-rotation-connector\": true\n }\n };\n }, [\n includeRotation,\n controller.element.origin.x,\n controller.element.origin.y,\n controller.element.size.width,\n controller.element.size.height,\n (_a = controller.rotationCenter) == null ? void 0 : _a.x,\n (_b = controller.rotationCenter) == null ? void 0 : _b.y,\n (_c = controller.rotationElement) == null ? void 0 : _c.origin.x,\n (_d = controller.rotationElement) == null ? void 0 : _d.origin.y,\n (_e = controller.rotationElement) == null ? void 0 : _e.size.width,\n (_f = controller.rotationElement) == null ? void 0 : _f.size.height,\n controller.scale,\n currentRotation,\n rotationUI == null ? void 0 : rotationUI.handleSize,\n rotationUI == null ? void 0 : rotationUI.margin,\n rotationUI == null ? void 0 : rotationUI.zIndex,\n rotationUI == null ? void 0 : rotationUI.showConnector,\n rotationUI == null ? void 0 : rotationUI.connectorWidth,\n createRotationProps,\n rotationAttrs\n ]);\n return { dragProps, resize, vertices, rotation };\n}\nfunction useDoublePressProps(onDouble, { delay = 300, tolerancePx = 18 } = {}) {\n const last = useRef({ t: 0, x: 0, y: 0 });\n const handlePointerUp = useCallback(\n (e) => {\n if (!onDouble) return;\n if (e.pointerType === \"mouse\" || e.isPrimary === false) return;\n const now = performance.now();\n const x = e.clientX;\n const y = e.clientY;\n const withinTime = now - last.current.t <= delay;\n const dx = x - last.current.x;\n const dy = y - last.current.y;\n const withinDist = dx * dx + dy * dy <= tolerancePx * tolerancePx;\n if (withinTime && withinDist) onDouble == null ? void 0 : onDouble(e);\n last.current = { t: now, x, y };\n },\n [onDouble, delay, tolerancePx]\n );\n const handleDouble = useCallback(\n (e) => {\n onDouble == null ? void 0 : onDouble(e);\n },\n [onDouble]\n );\n return onDouble ? {\n // Computed property uses the framework’s name ('onDoubleClick' or 'onDblClick')\n [dblClickProp]: handleDouble,\n onPointerUpCapture: handlePointerUp\n } : {};\n}\nexport {\n CounterRotate,\n useDoublePressProps,\n useDragResize,\n useInteractionHandles\n};\n//# sourceMappingURL=index.js.map\n","import { createPluginPackage } from \"@embedpdf/core\";\nimport { SelectionPlugin, SelectionPluginPackage as SelectionPluginPackage$1 } from \"@embedpdf/plugin-selection\";\nexport * from \"@embedpdf/plugin-selection\";\nimport { jsxs, Fragment, jsx } from \"react/jsx-runtime\";\nimport { useState, useEffect, useMemo, Fragment as Fragment$1 } from \"react\";\nimport { useCapability, usePlugin, useDocumentState } from \"@embedpdf/core/react\";\nimport { CounterRotate } from \"@embedpdf/utils/react\";\nconst useSelectionCapability = () => useCapability(SelectionPlugin.id);\nconst useSelectionPlugin = () => usePlugin(SelectionPlugin.id);\nfunction TextSelection({\n documentId,\n pageIndex,\n scale: scaleOverride,\n rotation: rotationOverride,\n background = \"rgba(33,150,243)\",\n selectionMenu\n}) {\n var _a, _b;\n const { plugin: selPlugin } = useSelectionPlugin();\n const documentState = useDocumentState(documentId);\n const page = (_b = (_a = documentState == null ? void 0 : documentState.document) == null ? void 0 : _a.pages) == null ? void 0 : _b[pageIndex];\n const [rects, setRects] = useState([]);\n const [boundingRect, setBoundingRect] = useState(null);\n const [placement, setPlacement] = useState(null);\n useEffect(() => {\n if (!selPlugin || !documentId) return;\n return selPlugin.registerSelectionOnPage({\n documentId,\n pageIndex,\n onRectsChange: ({ rects: rects2, boundingRect: boundingRect2 }) => {\n setRects(rects2);\n setBoundingRect(boundingRect2);\n }\n });\n }, [selPlugin, documentId, pageIndex]);\n useEffect(() => {\n if (!selPlugin || !documentId) return;\n return selPlugin.onMenuPlacement(documentId, (newPlacement) => {\n setPlacement(newPlacement);\n });\n }, [selPlugin, documentId]);\n const actualScale = useMemo(() => {\n if (scaleOverride !== void 0) return scaleOverride;\n return (documentState == null ? void 0 : documentState.scale) ?? 1;\n }, [scaleOverride, documentState == null ? void 0 : documentState.scale]);\n const actualRotation = useMemo(() => {\n if (rotationOverride !== void 0) return rotationOverride;\n const pageRotation = (page == null ? void 0 : page.rotation) ?? 0;\n const docRotation = (documentState == null ? void 0 : documentState.rotation) ?? 0;\n return (pageRotation + docRotation) % 4;\n }, [rotationOverride, page == null ? void 0 : page.rotation, documentState == null ? void 0 : documentState.rotation]);\n const shouldRenderMenu = selectionMenu && placement && placement.pageIndex === pageIndex && placement.isVisible;\n if (!boundingRect) return null;\n return /* @__PURE__ */ jsxs(Fragment, { children: [\n /* @__PURE__ */ jsx(\n \"div\",\n {\n style: {\n position: \"absolute\",\n left: boundingRect.origin.x * actualScale,\n top: boundingRect.origin.y * actualScale,\n width: boundingRect.size.width * actualScale,\n height: boundingRect.size.height * actualScale,\n mixBlendMode: \"multiply\",\n isolation: \"isolate\",\n pointerEvents: \"none\"\n },\n children: rects.map((b, i) => /* @__PURE__ */ jsx(\n \"div\",\n {\n style: {\n position: \"absolute\",\n left: (b.origin.x - boundingRect.origin.x) * actualScale,\n top: (b.origin.y - boundingRect.origin.y) * actualScale,\n width: b.size.width * actualScale,\n height: b.size.height * actualScale,\n background\n }\n },\n i\n ))\n }\n ),\n shouldRenderMenu && /* @__PURE__ */ jsx(\n CounterRotate,\n {\n rect: {\n origin: {\n x: placement.rect.origin.x * actualScale,\n y: placement.rect.origin.y * actualScale\n },\n size: {\n width: placement.rect.size.width * actualScale,\n height: placement.rect.size.height * actualScale\n }\n },\n rotation: actualRotation,\n children: (props) => selectionMenu({\n ...props,\n context: {\n type: \"selection\",\n pageIndex\n },\n selected: true,\n placement\n })\n }\n )\n ] });\n}\nconst MarqueeSelection = ({\n documentId,\n pageIndex,\n scale,\n className,\n background,\n borderColor,\n borderStyle = \"dashed\",\n stroke,\n fill\n}) => {\n const { plugin: selPlugin } = useSelectionPlugin();\n const documentState = useDocumentState(documentId);\n const [rect, setRect] = useState(null);\n const resolvedBorderColor = borderColor ?? stroke ?? \"rgba(0,122,204,0.8)\";\n const resolvedBackground = background ?? fill ?? \"rgba(0,122,204,0.15)\";\n const actualScale = useMemo(() => {\n if (scale !== void 0) return scale;\n return (documentState == null ? void 0 : documentState.scale) ?? 1;\n }, [scale, documentState == null ? void 0 : documentState.scale]);\n useEffect(() => {\n if (!selPlugin || !documentId) return;\n return selPlugin.registerMarqueeOnPage({\n documentId,\n pageIndex,\n scale: actualScale,\n onRectChange: setRect\n });\n }, [selPlugin, documentId, pageIndex, actualScale]);\n if (!rect) return null;\n return /* @__PURE__ */ jsx(\n \"div\",\n {\n style: {\n position: \"absolute\",\n pointerEvents: \"none\",\n left: rect.origin.x * actualScale,\n top: rect.origin.y * actualScale,\n width: rect.size.width * actualScale,\n height: rect.size.height * actualScale,\n border: `1px ${borderStyle} ${resolvedBorderColor}`,\n background: resolvedBackground,\n boxSizing: \"border-box\",\n zIndex: 1e3\n },\n className\n }\n );\n};\nfunction SelectionLayer({\n documentId,\n pageIndex,\n scale,\n rotation,\n background,\n textStyle,\n marqueeStyle,\n marqueeClassName,\n selectionMenu\n}) {\n return /* @__PURE__ */ jsxs(Fragment$1, { children: [\n /* @__PURE__ */ jsx(\n TextSelection,\n {\n documentId,\n pageIndex,\n scale,\n rotation,\n background: (textStyle == null ? void 0 : textStyle.background) ?? background,\n selectionMenu\n }\n ),\n /* @__PURE__ */ jsx(\n MarqueeSelection,\n {\n documentId,\n pageIndex,\n scale,\n background: marqueeStyle == null ? void 0 : marqueeStyle.background,\n borderColor: marqueeStyle == null ? void 0 : marqueeStyle.borderColor,\n borderStyle: marqueeStyle == null ? void 0 : marqueeStyle.borderStyle,\n className: marqueeClassName\n }\n )\n ] });\n}\nfunction CopyToClipboard() {\n const { provides: sel } = useSelectionCapability();\n useEffect(() => {\n if (!sel) return;\n return sel.onCopyToClipboard(({ text }) => {\n navigator.clipboard.writeText(text);\n });\n }, [sel]);\n return null;\n}\nconst SelectionPluginPackage = createPluginPackage(SelectionPluginPackage$1).addUtility(CopyToClipboard).build();\nexport {\n CopyToClipboard,\n MarqueeSelection,\n SelectionLayer,\n SelectionPluginPackage,\n TextSelection,\n useSelectionCapability,\n useSelectionPlugin\n};\n//# sourceMappingURL=index.js.map\n","import { BasePlugin, createEmitter, createBehaviorEmitter } from \"@embedpdf/core\";\nconst INIT_INTERACTION_STATE = \"INTERACTION/INIT_STATE\";\nconst CLEANUP_INTERACTION_STATE = \"INTERACTION/CLEANUP_STATE\";\nconst ACTIVATE_MODE = \"INTERACTION/ACTIVATE_MODE\";\nconst PAUSE_INTERACTION = \"INTERACTION/PAUSE\";\nconst RESUME_INTERACTION = \"INTERACTION/RESUME\";\nconst SET_CURSOR = \"INTERACTION/SET_CURSOR\";\nconst SET_ACTIVE_DOCUMENT = \"INTERACTION/SET_ACTIVE_DOCUMENT\";\nconst SET_DEFAULT_MODE = \"INTERACTION/SET_DEFAULT_MODE\";\nconst SET_EXCLUSION_RULES = \"INTERACTION/SET_EXCLUSION_RULES\";\nconst ADD_EXCLUSION_CLASS = \"INTERACTION/ADD_EXCLUSION_CLASS\";\nconst REMOVE_EXCLUSION_CLASS = \"INTERACTION/REMOVE_EXCLUSION_CLASS\";\nconst ADD_EXCLUSION_ATTRIBUTE = \"INTERACTION/ADD_EXCLUSION_ATTRIBUTE\";\nconst REMOVE_EXCLUSION_ATTRIBUTE = \"INTERACTION/REMOVE_EXCLUSION_ATTRIBUTE\";\nfunction initInteractionState(documentId, state) {\n return { type: INIT_INTERACTION_STATE, payload: { documentId, state } };\n}\nfunction cleanupInteractionState(documentId) {\n return { type: CLEANUP_INTERACTION_STATE, payload: documentId };\n}\nfunction activateMode(documentId, mode) {\n return { type: ACTIVATE_MODE, payload: { documentId, mode } };\n}\nfunction pauseInteraction(documentId) {\n return { type: PAUSE_INTERACTION, payload: documentId };\n}\nfunction resumeInteraction(documentId) {\n return { type: RESUME_INTERACTION, payload: documentId };\n}\nfunction setCursor(documentId, cursor) {\n return { type: SET_CURSOR, payload: { documentId, cursor } };\n}\nfunction setDefaultMode(mode) {\n return { type: SET_DEFAULT_MODE, payload: { mode } };\n}\nfunction setExclusionRules(rules) {\n return { type: SET_EXCLUSION_RULES, payload: { rules } };\n}\nfunction addExclusionClass(className) {\n return { type: ADD_EXCLUSION_CLASS, payload: { className } };\n}\nfunction removeExclusionClass(className) {\n return { type: REMOVE_EXCLUSION_CLASS, payload: { className } };\n}\nfunction addExclusionAttribute(attribute) {\n return { type: ADD_EXCLUSION_ATTRIBUTE, payload: { attribute } };\n}\nfunction removeExclusionAttribute(attribute) {\n return { type: REMOVE_EXCLUSION_ATTRIBUTE, payload: { attribute } };\n}\nfunction mergeHandlers(list) {\n const keys = [\n \"onPointerDown\",\n \"onPointerUp\",\n \"onPointerMove\",\n \"onPointerEnter\",\n \"onPointerLeave\",\n \"onPointerCancel\",\n \"onMouseDown\",\n \"onMouseUp\",\n \"onMouseMove\",\n \"onMouseEnter\",\n \"onMouseLeave\",\n \"onMouseCancel\",\n \"onClick\",\n \"onDoubleClick\"\n ];\n const out = {};\n for (const k of keys) {\n out[k] = (pos, evt, modeId) => {\n var _a;\n for (const h of list) {\n if (evt.isImmediatePropagationStopped()) break;\n (_a = h[k]) == null ? void 0 : _a.call(h, pos, evt, modeId);\n }\n };\n }\n return out;\n}\nconst INITIAL_MODE$1 = \"pointerMode\";\nconst _InteractionManagerPlugin = class _InteractionManagerPlugin extends BasePlugin {\n constructor(id, registry, config) {\n super(id, registry);\n this.modes = /* @__PURE__ */ new Map();\n this.cursorClaims = /* @__PURE__ */ new Map();\n this.buckets = /* @__PURE__ */ new Map();\n this.alwaysGlobal = /* @__PURE__ */ new Map();\n this.alwaysPage = /* @__PURE__ */ new Map();\n this.pageActivities = /* @__PURE__ */ new Map();\n this.onModeChange$ = createEmitter();\n this.onHandlerChange$ = createEmitter();\n this.onCursorChange$ = createEmitter();\n this.onStateChange$ = createBehaviorEmitter();\n this.onPageActivityChange$ = createEmitter();\n this.registerMode({\n id: INITIAL_MODE$1,\n scope: \"page\",\n exclusive: false,\n cursor: \"auto\"\n });\n this.dispatch(setDefaultMode(INITIAL_MODE$1));\n if (config.exclusionRules) {\n this.dispatch(setExclusionRules(config.exclusionRules));\n }\n }\n // ─────────────────────────────────────────────────────────\n // Document Lifecycle Hooks (from BasePlugin)\n // ─────────────────────────────────────────────────────────\n onDocumentLoadingStarted(documentId) {\n const docState = {\n activeMode: this.state.defaultMode,\n cursor: \"auto\",\n paused: false\n };\n this.dispatch(initInteractionState(documentId, docState));\n this.cursorClaims.set(documentId, /* @__PURE__ */ new Map());\n this.buckets.set(documentId, /* @__PURE__ */ new Map());\n this.alwaysGlobal.set(documentId, /* @__PURE__ */ new Set());\n this.alwaysPage.set(documentId, /* @__PURE__ */ new Map());\n this.pageActivities.set(documentId, /* @__PURE__ */ new Map());\n const docBuckets = this.buckets.get(documentId);\n for (const modeId of this.modes.keys()) {\n docBuckets.set(modeId, { global: /* @__PURE__ */ new Set(), page: /* @__PURE__ */ new Map() });\n }\n this.logger.debug(\n \"InteractionManagerPlugin\",\n \"DocumentOpened\",\n `Initialized interaction state for document: ${documentId}`\n );\n }\n onDocumentClosed(documentId) {\n const topics = this.pageActivities.get(documentId);\n if (topics) {\n const activePages = new Set(topics.values());\n topics.clear();\n for (const pageIndex of activePages) {\n this.onPageActivityChange$.emit({ documentId, pageIndex, hasActivity: false });\n }\n }\n this.cursorClaims.delete(documentId);\n this.buckets.delete(documentId);\n this.alwaysGlobal.delete(documentId);\n this.alwaysPage.delete(documentId);\n this.pageActivities.delete(documentId);\n this.dispatch(cleanupInteractionState(documentId));\n this.logger.debug(\n \"InteractionManagerPlugin\",\n \"DocumentClosed\",\n `Cleaned up interaction state for document: ${documentId}`\n );\n }\n // ─────────────────────────────────────────────────────────\n // Capability\n // ─────────────────────────────────────────────────────────\n buildCapability() {\n return {\n // Active document operations\n getActiveMode: () => this.getActiveMode(),\n getActiveInteractionMode: () => this.getActiveInteractionMode(),\n activate: (modeId) => this.activate(modeId),\n activateDefaultMode: () => this.activateDefaultMode(),\n setCursor: (token, cursor, priority) => this.setCursor(token, cursor, priority),\n getCurrentCursor: () => this.getCurrentCursor(),\n removeCursor: (token) => this.removeCursor(token),\n getHandlersForScope: (scope) => this.getHandlersForScope(scope),\n activeModeIsExclusive: () => this.activeModeIsExclusive(),\n pause: () => this.pause(),\n resume: () => this.resume(),\n // Treat a destroyed registry as \"paused\" so late DOM events are ignored during teardown.\n isPaused: () => this.registry.isDestroyed() || this.isPaused(),\n getState: () => this.getDocumentStateOrThrow(),\n // Document-scoped operations\n forDocument: (documentId) => this.createInteractionScope(documentId),\n // Global management\n registerMode: (mode) => this.registerMode(mode),\n registerHandlers: (options) => this.registerHandlers(options),\n registerAlways: (options) => this.registerAlways(options),\n setDefaultMode: (id) => this.setDefaultMode(id),\n getDefaultMode: () => this.state.defaultMode,\n getExclusionRules: () => this.state.exclusionRules,\n setExclusionRules: (rules) => this.dispatch(setExclusionRules(rules)),\n addExclusionClass: (className) => this.dispatch(addExclusionClass(className)),\n removeExclusionClass: (className) => this.dispatch(removeExclusionClass(className)),\n addExclusionAttribute: (attribute) => this.dispatch(addExclusionAttribute(attribute)),\n removeExclusionAttribute: (attribute) => this.dispatch(removeExclusionAttribute(attribute)),\n // Page activity\n claimPageActivity: (documentId, topic, pageIndex) => this.claimPageActivity(documentId, topic, pageIndex),\n releasePageActivity: (documentId, topic) => this.releasePageActivity(documentId, topic),\n hasPageActivity: (documentId, pageIndex) => this.hasPageActivity(documentId, pageIndex),\n // Events\n onModeChange: this.onModeChange$.on,\n onCursorChange: this.onCursorChange$.on,\n onHandlerChange: this.onHandlerChange$.on,\n onStateChange: this.onStateChange$.on,\n onPageActivityChange: this.onPageActivityChange$.on\n };\n }\n // ─────────────────────────────────────────────────────────\n // Document Scoping\n // ─────────────────────────────────────────────────────────\n createInteractionScope(documentId) {\n return {\n getActiveMode: () => this.getActiveMode(documentId),\n getActiveInteractionMode: () => this.getActiveInteractionMode(documentId),\n activate: (modeId) => this.activate(modeId, documentId),\n activateDefaultMode: () => this.activateDefaultMode(documentId),\n setCursor: (token, cursor, priority) => this.setCursor(token, cursor, priority, documentId),\n getCurrentCursor: () => this.getCurrentCursor(documentId),\n removeCursor: (token) => this.removeCursor(token, documentId),\n getHandlersForScope: (scope) => this.getHandlersForScope(scope),\n activeModeIsExclusive: () => this.activeModeIsExclusive(documentId),\n pause: () => this.pause(documentId),\n resume: () => this.resume(documentId),\n isPaused: () => this.isPaused(documentId),\n getState: () => this.getDocumentStateOrThrow(documentId),\n claimPageActivity: (topic, pageIndex) => this.claimPageActivity(documentId, topic, pageIndex),\n releasePageActivity: (topic) => this.releasePageActivity(documentId, topic),\n hasPageActivity: (pageIndex) => this.hasPageActivity(documentId, pageIndex),\n onModeChange: (listener) => this.onModeChange$.on((event) => {\n if (event.documentId === documentId) listener(event.activeMode);\n }),\n onCursorChange: (listener) => this.onCursorChange$.on((event) => {\n if (event.documentId === documentId) listener(event.cursor);\n }),\n onStateChange: (listener) => this.onStateChange$.on((event) => {\n if (event.documentId === documentId) listener(event.state);\n }),\n onPageActivityChange: (listener) => this.onPageActivityChange$.on((event) => {\n if (event.documentId === documentId)\n listener({ pageIndex: event.pageIndex, hasActivity: event.hasActivity });\n })\n };\n }\n // ─────────────────────────────────────────────────────────\n // State Helpers\n // ─────────────────────────────────────────────────────────\n getDocumentState(documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n return this.state.documents[id] ?? null;\n }\n getDocumentStateOrThrow(documentId) {\n const state = this.getDocumentState(documentId);\n if (!state) {\n throw new Error(`Interaction state not found for document: ${documentId ?? \"active\"}`);\n }\n return state;\n }\n // ─────────────────────────────────────────────────────────\n // Core Operations\n // ─────────────────────────────────────────────────────────\n activate(modeId, documentId) {\n var _a;\n const id = documentId ?? this.getActiveDocumentId();\n const docState = this.getDocumentStateOrThrow(id);\n if (!this.modes.has(modeId)) {\n throw new Error(`[interaction] unknown mode '${modeId}'`);\n }\n if (modeId === docState.activeMode) return;\n const previousMode = docState.activeMode;\n (_a = this.cursorClaims.get(id)) == null ? void 0 : _a.clear();\n this.notifyHandlersInactive(id, previousMode);\n this.dispatch(activateMode(id, modeId));\n this.emitCursor(id);\n this.notifyHandlersActive(id, modeId);\n this.onModeChange$.emit({\n documentId: id,\n activeMode: modeId,\n previousMode\n });\n }\n activateDefaultMode(documentId) {\n const id = documentId ?? this.getActiveDocumentIdOrNull();\n if (!id) return;\n this.activate(this.state.defaultMode, id);\n }\n setDefaultMode(modeId) {\n if (!this.modes.has(modeId)) {\n throw new Error(`[interaction] cannot set unknown mode '${modeId}' as default`);\n }\n this.dispatch(setDefaultMode(modeId));\n }\n getActiveMode(documentId) {\n return this.getDocumentStateOrThrow(documentId).activeMode;\n }\n getActiveInteractionMode(documentId) {\n const docState = this.getDocumentState(documentId);\n if (!docState) return null;\n return this.modes.get(docState.activeMode) ?? null;\n }\n activeModeIsExclusive(documentId) {\n const mode = this.getActiveInteractionMode(documentId);\n return !!(mode == null ? void 0 : mode.exclusive);\n }\n pause(documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n this.dispatch(pauseInteraction(id));\n }\n resume(documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n this.dispatch(resumeInteraction(id));\n }\n isPaused(documentId) {\n return this.getDocumentStateOrThrow(documentId).paused;\n }\n // ─────────────────────────────────────────────────────────\n // Mode Management\n // ─────────────────────────────────────────────────────────\n registerMode(mode) {\n this.modes.set(mode.id, mode);\n for (const documentId of this.buckets.keys()) {\n const docBuckets = this.buckets.get(documentId);\n if (!docBuckets.has(mode.id)) {\n docBuckets.set(mode.id, { global: /* @__PURE__ */ new Set(), page: /* @__PURE__ */ new Map() });\n }\n }\n }\n // ─────────────────────────────────────────────────────────\n // Handler Management\n // ─────────────────────────────────────────────────────────\n registerHandlers({\n documentId,\n modeId,\n handlers,\n pageIndex\n }) {\n const modeIds = Array.isArray(modeId) ? modeId : [modeId];\n const cleanupFunctions = [];\n const docBuckets = this.buckets.get(documentId);\n if (!docBuckets) {\n throw new Error(`No buckets found for document: ${documentId}`);\n }\n for (const id of modeIds) {\n const bucket = docBuckets.get(id);\n if (!bucket) throw new Error(`unknown mode '${id}'`);\n if (pageIndex == null) {\n bucket.global.add(handlers);\n } else {\n const set = bucket.page.get(pageIndex) ?? /* @__PURE__ */ new Set();\n set.add(handlers);\n bucket.page.set(pageIndex, set);\n }\n cleanupFunctions.push(() => {\n if (pageIndex == null) {\n bucket.global.delete(handlers);\n } else {\n const set = bucket.page.get(pageIndex);\n if (set) {\n set.delete(handlers);\n if (set.size === 0) {\n bucket.page.delete(pageIndex);\n }\n }\n }\n });\n }\n this.onHandlerChange$.emit({ ...this.state });\n return () => {\n cleanupFunctions.forEach((cleanup) => cleanup());\n this.onHandlerChange$.emit({ ...this.state });\n };\n }\n registerAlways({ scope, handlers }) {\n if (scope.type === \"global\") {\n const set2 = this.alwaysGlobal.get(scope.documentId) ?? /* @__PURE__ */ new Set();\n set2.add(handlers);\n this.alwaysGlobal.set(scope.documentId, set2);\n this.onHandlerChange$.emit({ ...this.state });\n return () => {\n set2.delete(handlers);\n this.onHandlerChange$.emit({ ...this.state });\n };\n }\n const docPageMap = this.alwaysPage.get(scope.documentId) ?? /* @__PURE__ */ new Map();\n const set = docPageMap.get(scope.pageIndex) ?? /* @__PURE__ */ new Set();\n set.add(handlers);\n docPageMap.set(scope.pageIndex, set);\n this.alwaysPage.set(scope.documentId, docPageMap);\n this.onHandlerChange$.emit({ ...this.state });\n return () => {\n set.delete(handlers);\n this.onHandlerChange$.emit({ ...this.state });\n };\n }\n getHandlersForScope(scope) {\n var _a;\n const docState = this.getDocumentState(scope.documentId);\n if (!docState) return null;\n const mode = this.modes.get(docState.activeMode);\n if (!mode) return null;\n const docBuckets = this.buckets.get(scope.documentId);\n if (!docBuckets) return null;\n const bucket = docBuckets.get(mode.id);\n if (!bucket) return null;\n const mergeSets = (a, b) => a.size || b.size ? mergeHandlers([...a, ...b]) : null;\n if (scope.type === \"global\") {\n const alwaysSet = this.alwaysGlobal.get(scope.documentId) ?? /* @__PURE__ */ new Set();\n const modeSpecific = mode.scope === \"global\" ? bucket.global : /* @__PURE__ */ new Set();\n return mergeSets(alwaysSet, modeSpecific);\n }\n const alwaysPageSet = ((_a = this.alwaysPage.get(scope.documentId)) == null ? void 0 : _a.get(scope.pageIndex)) ?? /* @__PURE__ */ new Set();\n const modePageSet = mode.scope === \"page\" ? bucket.page.get(scope.pageIndex) ?? /* @__PURE__ */ new Set() : /* @__PURE__ */ new Set();\n return mergeSets(alwaysPageSet, modePageSet);\n }\n // ─────────────────────────────────────────────────────────\n // Cursor Management\n // ─────────────────────────────────────────────────────────\n setCursor(token, cursor, priority = 0, documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const claims = this.cursorClaims.get(id);\n if (!claims) return;\n claims.set(token, { cursor, priority });\n this.emitCursor(id);\n }\n removeCursor(token, documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const claims = this.cursorClaims.get(id);\n if (!claims) return;\n claims.delete(token);\n this.emitCursor(id);\n }\n getCurrentCursor(documentId) {\n return this.getDocumentStateOrThrow(documentId).cursor;\n }\n emitCursor(documentId) {\n var _a;\n const claims = this.cursorClaims.get(documentId);\n if (!claims) return;\n const docState = this.getDocumentState(documentId);\n if (!docState) return;\n const top = [...claims.values()].sort((a, b) => b.priority - a.priority)[0] ?? {\n cursor: ((_a = this.modes.get(docState.activeMode)) == null ? void 0 : _a.cursor) ?? \"auto\"\n };\n if (top.cursor !== docState.cursor) {\n this.dispatch(setCursor(documentId, top.cursor));\n this.onCursorChange$.emit({\n documentId,\n cursor: top.cursor\n });\n }\n }\n // ─────────────────────────────────────────────────────────\n // Page Activity Management\n // ─────────────────────────────────────────────────────────\n claimPageActivity(documentId, topic, pageIndex) {\n let topics = this.pageActivities.get(documentId);\n if (!topics) {\n topics = /* @__PURE__ */ new Map();\n this.pageActivities.set(documentId, topics);\n }\n const oldPage = topics.get(topic);\n if (oldPage === pageIndex) return;\n topics.set(topic, pageIndex);\n if (oldPage !== void 0 && !this.pageHasAnyTopic(documentId, oldPage)) {\n this.onPageActivityChange$.emit({ documentId, pageIndex: oldPage, hasActivity: false });\n }\n if (this.countTopicsOnPage(documentId, pageIndex) === 1) {\n this.onPageActivityChange$.emit({ documentId, pageIndex, hasActivity: true });\n }\n }\n releasePageActivity(documentId, topic) {\n const topics = this.pageActivities.get(documentId);\n if (!topics) return;\n const page = topics.get(topic);\n if (page === void 0) return;\n topics.delete(topic);\n if (!this.pageHasAnyTopic(documentId, page)) {\n this.onPageActivityChange$.emit({ documentId, pageIndex: page, hasActivity: false });\n }\n }\n hasPageActivity(documentId, pageIndex) {\n return this.pageHasAnyTopic(documentId, pageIndex);\n }\n /** Helper: does any topic point to this page? */\n pageHasAnyTopic(documentId, pageIndex) {\n const topics = this.pageActivities.get(documentId);\n if (!topics) return false;\n for (const p of topics.values()) {\n if (p === pageIndex) return true;\n }\n return false;\n }\n /** Helper: count topics on a page */\n countTopicsOnPage(documentId, pageIndex) {\n const topics = this.pageActivities.get(documentId);\n if (!topics) return 0;\n let count = 0;\n for (const p of topics.values()) {\n if (p === pageIndex) count++;\n }\n return count;\n }\n // ─────────────────────────────────────────────────────────\n // Handler Lifecycle Notifications\n // ─────────────────────────────────────────────────────────\n notifyHandlersActive(documentId, modeId) {\n var _a, _b;\n (_a = this.alwaysGlobal.get(documentId)) == null ? void 0 : _a.forEach((handler) => {\n var _a2;\n (_a2 = handler.onHandlerActiveStart) == null ? void 0 : _a2.call(handler, modeId);\n });\n (_b = this.alwaysPage.get(documentId)) == null ? void 0 : _b.forEach((handlerSet) => {\n handlerSet.forEach((handler) => {\n var _a2;\n (_a2 = handler.onHandlerActiveStart) == null ? void 0 : _a2.call(handler, modeId);\n });\n });\n const mode = this.modes.get(modeId);\n if (!mode) return;\n const docBuckets = this.buckets.get(documentId);\n if (!docBuckets) return;\n const bucket = docBuckets.get(modeId);\n if (!bucket) return;\n if (mode.scope === \"global\") {\n bucket.global.forEach((handler) => {\n var _a2;\n (_a2 = handler.onHandlerActiveStart) == null ? void 0 : _a2.call(handler, modeId);\n });\n }\n if (mode.scope === \"page\") {\n bucket.page.forEach((handlerSet) => {\n handlerSet.forEach((handler) => {\n var _a2;\n (_a2 = handler.onHandlerActiveStart) == null ? void 0 : _a2.call(handler, modeId);\n });\n });\n }\n }\n notifyHandlersInactive(documentId, modeId) {\n var _a, _b;\n (_a = this.alwaysGlobal.get(documentId)) == null ? void 0 : _a.forEach((handler) => {\n var _a2;\n (_a2 = handler.onHandlerActiveEnd) == null ? void 0 : _a2.call(handler, modeId);\n });\n (_b = this.alwaysPage.get(documentId)) == null ? void 0 : _b.forEach((handlerSet) => {\n handlerSet.forEach((handler) => {\n var _a2;\n (_a2 = handler.onHandlerActiveEnd) == null ? void 0 : _a2.call(handler, modeId);\n });\n });\n const mode = this.modes.get(modeId);\n if (!mode) return;\n const docBuckets = this.buckets.get(documentId);\n if (!docBuckets) return;\n const bucket = docBuckets.get(modeId);\n if (!bucket) return;\n if (mode.scope === \"global\") {\n bucket.global.forEach((handler) => {\n var _a2;\n (_a2 = handler.onHandlerActiveEnd) == null ? void 0 : _a2.call(handler, modeId);\n });\n }\n if (mode.scope === \"page\") {\n bucket.page.forEach((handlerSet) => {\n handlerSet.forEach((handler) => {\n var _a2;\n (_a2 = handler.onHandlerActiveEnd) == null ? void 0 : _a2.call(handler, modeId);\n });\n });\n }\n }\n // ─────────────────────────────────────────────────────────\n // Store Update Handlers\n // ─────────────────────────────────────────────────────────\n onStoreUpdated(prevState, newState) {\n for (const documentId in newState.documents) {\n const prevDoc = prevState.documents[documentId];\n const newDoc = newState.documents[documentId];\n if (prevDoc !== newDoc) {\n this.onStateChange$.emit({\n documentId,\n state: newDoc\n });\n }\n }\n }\n // ─────────────────────────────────────────────────────────\n // Lifecycle\n // ─────────────────────────────────────────────────────────\n async initialize(_) {\n this.logger.info(\n \"InteractionManagerPlugin\",\n \"Initialize\",\n \"Interaction Manager Plugin initialized\"\n );\n }\n async destroy() {\n this.pageActivities.clear();\n this.onModeChange$.clear();\n this.onCursorChange$.clear();\n this.onHandlerChange$.clear();\n this.onStateChange$.clear();\n this.onPageActivityChange$.clear();\n await super.destroy();\n }\n};\n_InteractionManagerPlugin.id = \"interaction-manager\";\nlet InteractionManagerPlugin = _InteractionManagerPlugin;\nconst INTERACTION_MANAGER_PLUGIN_ID = \"interaction-manager\";\nconst manifest = {\n id: INTERACTION_MANAGER_PLUGIN_ID,\n name: \"Interaction Manager Plugin\",\n version: \"1.0.0\",\n provides: [\"interaction-manager\"],\n requires: [],\n optional: [],\n defaultConfig: {\n exclusionRules: {\n classes: [],\n dataAttributes: [\"data-no-interaction\"]\n }\n }\n};\nconst INITIAL_MODE = \"pointerMode\";\nconst initialDocumentState = {\n activeMode: INITIAL_MODE,\n cursor: \"auto\",\n paused: false\n};\nconst initialState = {\n defaultMode: INITIAL_MODE,\n exclusionRules: {\n classes: [],\n dataAttributes: [\"data-no-interaction\"]\n },\n documents: {},\n activeDocumentId: null\n};\nconst reducer = (state = initialState, action) => {\n switch (action.type) {\n // ─────────────────────────────────────────────────────────\n // Document Lifecycle\n // ─────────────────────────────────────────────────────────\n case INIT_INTERACTION_STATE: {\n const { documentId, state: docState } = action.payload;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: docState\n },\n // Set as active if no active document\n activeDocumentId: state.activeDocumentId ?? documentId\n };\n }\n case CLEANUP_INTERACTION_STATE: {\n const documentId = action.payload;\n const { [documentId]: removed, ...remainingDocs } = state.documents;\n return {\n ...state,\n documents: remainingDocs,\n activeDocumentId: state.activeDocumentId === documentId ? null : state.activeDocumentId\n };\n }\n case SET_ACTIVE_DOCUMENT: {\n return {\n ...state,\n activeDocumentId: action.payload\n };\n }\n // ─────────────────────────────────────────────────────────\n // Per-Document Actions\n // ─────────────────────────────────────────────────────────\n case ACTIVATE_MODE: {\n const { documentId, mode } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...docState,\n activeMode: mode\n }\n }\n };\n }\n case SET_CURSOR: {\n const { documentId, cursor } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...docState,\n cursor\n }\n }\n };\n }\n case PAUSE_INTERACTION: {\n const documentId = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...docState,\n paused: true\n }\n }\n };\n }\n case RESUME_INTERACTION: {\n const documentId = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...docState,\n paused: false\n }\n }\n };\n }\n // ─────────────────────────────────────────────────────────\n // Global Actions\n // ─────────────────────────────────────────────────────────\n case SET_DEFAULT_MODE:\n return {\n ...state,\n defaultMode: action.payload.mode\n };\n case SET_EXCLUSION_RULES:\n return {\n ...state,\n exclusionRules: action.payload.rules\n };\n case ADD_EXCLUSION_CLASS:\n return {\n ...state,\n exclusionRules: {\n ...state.exclusionRules,\n classes: [...state.exclusionRules.classes || [], action.payload.className].filter(\n (v, i, a) => a.indexOf(v) === i\n )\n }\n };\n case REMOVE_EXCLUSION_CLASS:\n return {\n ...state,\n exclusionRules: {\n ...state.exclusionRules,\n classes: (state.exclusionRules.classes || []).filter(\n (c) => c !== action.payload.className\n )\n }\n };\n case ADD_EXCLUSION_ATTRIBUTE:\n return {\n ...state,\n exclusionRules: {\n ...state.exclusionRules,\n dataAttributes: [\n ...state.exclusionRules.dataAttributes || [],\n action.payload.attribute\n ].filter((v, i, a) => a.indexOf(v) === i)\n }\n };\n case REMOVE_EXCLUSION_ATTRIBUTE:\n return {\n ...state,\n exclusionRules: {\n ...state.exclusionRules,\n dataAttributes: (state.exclusionRules.dataAttributes || []).filter(\n (a) => a !== action.payload.attribute\n )\n }\n };\n default:\n return state;\n }\n};\nconst InteractionManagerPluginPackage = {\n manifest,\n create: (registry, config) => new InteractionManagerPlugin(INTERACTION_MANAGER_PLUGIN_ID, registry, config),\n reducer,\n initialState\n};\nexport {\n INTERACTION_MANAGER_PLUGIN_ID,\n InteractionManagerPlugin,\n InteractionManagerPluginPackage,\n initialDocumentState,\n initialState,\n manifest,\n reducer\n};\n//# sourceMappingURL=index.js.map\n","import { useCapability, usePlugin, useDocumentState } from \"@embedpdf/core/react\";\nimport { initialDocumentState, InteractionManagerPlugin } from \"@embedpdf/plugin-interaction-manager\";\nexport * from \"@embedpdf/plugin-interaction-manager\";\nimport { useState, useEffect, useRef, useCallback } from \"react\";\nimport { jsx, jsxs } from \"react/jsx-runtime\";\nimport { transformSize, restorePosition } from \"@embedpdf/models\";\nconst useInteractionManagerPlugin = () => usePlugin(InteractionManagerPlugin.id);\nconst useInteractionManagerCapability = () => useCapability(InteractionManagerPlugin.id);\nfunction useInteractionManager(documentId) {\n const { provides } = useInteractionManagerCapability();\n const [state, setState] = useState(initialDocumentState);\n useEffect(() => {\n if (!provides) return;\n const scope = provides.forDocument(documentId);\n return scope.onStateChange((state2) => {\n setState(state2);\n });\n }, [provides]);\n return {\n provides: (provides == null ? void 0 : provides.forDocument(documentId)) ?? null,\n state\n };\n}\nfunction useCursor(documentId) {\n const { provides } = useInteractionManagerCapability();\n return {\n setCursor: (token, cursor, prio = 0) => {\n if (!provides) return;\n const scope = provides.forDocument(documentId);\n scope.setCursor(token, cursor, prio);\n },\n removeCursor: (token) => {\n if (!provides) return;\n const scope = provides.forDocument(documentId);\n scope.removeCursor(token);\n }\n };\n}\nfunction usePointerHandlers({ modeId, pageIndex, documentId }) {\n const { provides } = useInteractionManagerCapability();\n return {\n register: (handlers, options) => {\n const finalModeId = (options == null ? void 0 : options.modeId) ?? modeId;\n const finalPageIndex = (options == null ? void 0 : options.pageIndex) ?? pageIndex;\n const finalDocumentId = (options == null ? void 0 : options.documentId) ?? documentId;\n return finalModeId ? provides == null ? void 0 : provides.registerHandlers({\n modeId: finalModeId,\n handlers,\n pageIndex: finalPageIndex,\n documentId: finalDocumentId\n }) : provides == null ? void 0 : provides.registerAlways({\n scope: finalPageIndex !== void 0 ? { type: \"page\", documentId: finalDocumentId, pageIndex: finalPageIndex } : { type: \"global\", documentId: finalDocumentId },\n handlers\n });\n }\n };\n}\nfunction useIsPageExclusive(documentId) {\n const { provides: cap } = useInteractionManagerCapability();\n const [isPageExclusive, setIsPageExclusive] = useState(() => {\n if (!cap) return false;\n const scope = cap.forDocument(documentId);\n const m = scope.getActiveInteractionMode();\n return (m == null ? void 0 : m.scope) === \"page\" && !!m.exclusive;\n });\n useEffect(() => {\n if (!cap) return;\n const scope = cap.forDocument(documentId);\n return scope.onModeChange(() => {\n const mode = scope.getActiveInteractionMode();\n setIsPageExclusive((mode == null ? void 0 : mode.scope) === \"page\" && !!(mode == null ? void 0 : mode.exclusive));\n });\n }, [cap, documentId]);\n return isPageExclusive;\n}\nconst domEventMap = {\n pointerdown: \"onPointerDown\",\n pointerup: \"onPointerUp\",\n pointermove: \"onPointerMove\",\n pointerenter: \"onPointerEnter\",\n pointerleave: \"onPointerLeave\",\n pointercancel: \"onPointerCancel\",\n mousedown: \"onMouseDown\",\n mouseup: \"onMouseUp\",\n mousemove: \"onMouseMove\",\n mouseenter: \"onMouseEnter\",\n mouseleave: \"onMouseLeave\",\n mousecancel: \"onMouseCancel\",\n click: \"onClick\",\n dblclick: \"onDoubleClick\",\n /* touch → pointer fallback for very old browsers */\n touchstart: \"onPointerDown\",\n touchend: \"onPointerUp\",\n touchmove: \"onPointerMove\",\n touchcancel: \"onPointerCancel\"\n};\nconst pointerEventTypes = [\n \"pointerdown\",\n \"pointerup\",\n \"pointermove\",\n \"pointerenter\",\n \"pointerleave\",\n \"pointercancel\",\n \"mousedown\",\n \"mouseup\",\n \"mousemove\",\n \"mouseenter\",\n \"mouseleave\",\n \"mousecancel\",\n \"click\",\n \"dblclick\"\n];\nconst touchEventTypes = [\"touchstart\", \"touchend\", \"touchmove\", \"touchcancel\"];\nconst HAS_POINTER = typeof PointerEvent !== \"undefined\";\nconst allEventTypes = HAS_POINTER ? pointerEventTypes : [...pointerEventTypes, ...touchEventTypes];\nfunction listenerOpts(eventType, wantsRawTouch) {\n return eventType.startsWith(\"touch\") ? { passive: !wantsRawTouch } : { passive: false };\n}\nfunction isTouchEvent(evt) {\n return typeof TouchEvent !== \"undefined\" && evt instanceof TouchEvent;\n}\nfunction shouldExcludeElement(element, rules) {\n var _a, _b, _c;\n if (!element) return false;\n let current = element;\n while (current) {\n if ((_a = rules.classes) == null ? void 0 : _a.length) {\n for (const className of rules.classes) {\n if ((_b = current.classList) == null ? void 0 : _b.contains(className)) {\n return true;\n }\n }\n }\n if ((_c = rules.dataAttributes) == null ? void 0 : _c.length) {\n for (const attr of rules.dataAttributes) {\n if (current.hasAttribute(attr)) {\n return true;\n }\n }\n }\n current = current.parentElement;\n }\n return false;\n}\nfunction createPointerProvider(cap, scope, element, convertEventToPoint) {\n const capScope = cap.forDocument(scope.documentId);\n let active = cap.getHandlersForScope(scope);\n const wantsRawTouchNow = () => {\n var _a;\n return ((_a = capScope.getActiveInteractionMode()) == null ? void 0 : _a.wantsRawTouch) !== false;\n };\n const listeners = {};\n let attachedWithRawTouch = wantsRawTouchNow();\n const addListeners = (raw) => {\n allEventTypes.forEach((type) => {\n const fn = listeners[type] ?? (listeners[type] = handleEvent);\n element.addEventListener(type, fn, listenerOpts(type, raw));\n });\n };\n const removeListeners = () => {\n allEventTypes.forEach((type) => {\n const fn = listeners[type];\n if (fn) element.removeEventListener(type, fn);\n });\n };\n addListeners(attachedWithRawTouch);\n element.style.touchAction = attachedWithRawTouch ? \"none\" : \"\";\n const stopMode = capScope.onModeChange(() => {\n if (scope.type === \"global\") {\n const mode = capScope.getActiveInteractionMode();\n element.style.cursor = (mode == null ? void 0 : mode.scope) === \"global\" ? mode.cursor ?? \"auto\" : \"auto\";\n }\n active = cap.getHandlersForScope(scope);\n const raw = wantsRawTouchNow();\n if (raw !== attachedWithRawTouch) {\n removeListeners();\n addListeners(raw);\n attachedWithRawTouch = raw;\n element.style.touchAction = attachedWithRawTouch ? \"none\" : \"\";\n }\n });\n const stopHandler = cap.onHandlerChange(() => {\n active = cap.getHandlersForScope(scope);\n });\n const initialMode = capScope.getActiveInteractionMode();\n const initialCursor = capScope.getCurrentCursor();\n element.style.cursor = scope.type === \"global\" && (initialMode == null ? void 0 : initialMode.scope) !== \"global\" ? \"auto\" : initialCursor;\n const stopCursor = capScope.onCursorChange((c) => {\n var _a;\n if (scope.type === \"global\" && ((_a = capScope.getActiveInteractionMode()) == null ? void 0 : _a.scope) !== \"global\") return;\n element.style.cursor = c;\n });\n const toPos = (e, host) => {\n if (convertEventToPoint) return convertEventToPoint(e, host);\n const r = host.getBoundingClientRect();\n return { x: e.clientX - r.left, y: e.clientY - r.top };\n };\n function handleEvent(evt) {\n var _a;\n if (cap.isPaused()) return;\n const exclusionRules = cap.getExclusionRules();\n if (evt.target && shouldExcludeElement(evt.target, exclusionRules)) {\n return;\n }\n const handlerKey = domEventMap[evt.type];\n if (!handlerKey || !(active == null ? void 0 : active[handlerKey])) return;\n if (isTouchEvent(evt) && attachedWithRawTouch && (evt.type === \"touchmove\" || evt.type === \"touchcancel\")) {\n evt.preventDefault();\n }\n let pos;\n let normEvt;\n let propagationStopped = false;\n if (isTouchEvent(evt)) {\n const tp = evt.type === \"touchend\" || evt.type === \"touchcancel\" ? evt.changedTouches[0] : evt.touches[0];\n if (!tp) return;\n pos = toPos(tp, element);\n normEvt = {\n clientX: tp.clientX,\n clientY: tp.clientY,\n ctrlKey: evt.ctrlKey,\n shiftKey: evt.shiftKey,\n altKey: evt.altKey,\n metaKey: evt.metaKey,\n target: evt.target,\n currentTarget: evt.currentTarget,\n setPointerCapture: () => {\n },\n releasePointerCapture: () => {\n },\n stopImmediatePropagation: () => {\n propagationStopped = true;\n },\n isImmediatePropagationStopped: () => propagationStopped\n };\n } else {\n const pe = evt;\n pos = toPos(pe, element);\n normEvt = {\n clientX: pe.clientX,\n clientY: pe.clientY,\n ctrlKey: pe.ctrlKey,\n shiftKey: pe.shiftKey,\n altKey: pe.altKey,\n metaKey: pe.metaKey,\n target: pe.target,\n currentTarget: pe.currentTarget,\n setPointerCapture: () => {\n var _a2, _b;\n (_b = (_a2 = pe.target) == null ? void 0 : _a2.setPointerCapture) == null ? void 0 : _b.call(_a2, pe.pointerId);\n },\n releasePointerCapture: () => {\n var _a2, _b;\n (_b = (_a2 = pe.target) == null ? void 0 : _a2.releasePointerCapture) == null ? void 0 : _b.call(_a2, pe.pointerId);\n },\n stopImmediatePropagation: () => {\n propagationStopped = true;\n },\n isImmediatePropagationStopped: () => propagationStopped\n };\n }\n (_a = active[handlerKey]) == null ? void 0 : _a.call(active, pos, normEvt, capScope.getActiveMode());\n }\n return () => {\n removeListeners();\n stopMode();\n stopCursor();\n stopHandler();\n };\n}\nconst GlobalPointerProvider = ({\n children,\n documentId,\n style,\n ...props\n}) => {\n const ref = useRef(null);\n const { provides: cap } = useInteractionManagerCapability();\n useEffect(() => {\n if (!cap || !ref.current) return;\n return createPointerProvider(cap, { type: \"global\", documentId }, ref.current);\n }, [cap, documentId]);\n return /* @__PURE__ */ jsx(\n \"div\",\n {\n ref,\n style: {\n width: \"100%\",\n height: \"100%\",\n ...style\n },\n ...props,\n children\n }\n );\n};\nconst PagePointerProvider = ({\n documentId,\n pageIndex,\n children,\n rotation: rotationOverride,\n scale: scaleOverride,\n convertEventToPoint,\n style,\n ...props\n}) => {\n var _a, _b;\n const ref = useRef(null);\n const { provides: cap } = useInteractionManagerCapability();\n const isPageExclusive = useIsPageExclusive(documentId);\n const documentState = useDocumentState(documentId);\n const page = (_b = (_a = documentState == null ? void 0 : documentState.document) == null ? void 0 : _a.pages) == null ? void 0 : _b[pageIndex];\n const naturalPageSize = (page == null ? void 0 : page.size) ?? { width: 0, height: 0 };\n const pageRotation = (page == null ? void 0 : page.rotation) ?? 0;\n const docRotation = (documentState == null ? void 0 : documentState.rotation) ?? 0;\n const rotation = rotationOverride !== void 0 ? rotationOverride : (pageRotation + docRotation) % 4;\n const scale = scaleOverride ?? (documentState == null ? void 0 : documentState.scale) ?? 1;\n const displaySize = transformSize(naturalPageSize, 0, scale);\n const defaultConvertEventToPoint = useCallback(\n (event, element) => {\n const rect = element.getBoundingClientRect();\n const displayPoint = {\n x: event.clientX - rect.left,\n y: event.clientY - rect.top\n };\n const rotatedNaturalSize = transformSize(\n {\n width: displaySize.width,\n height: displaySize.height\n },\n rotation,\n 1\n );\n return restorePosition(rotatedNaturalSize, displayPoint, rotation, scale);\n },\n [naturalPageSize, rotation, scale]\n );\n useEffect(() => {\n if (!cap || !ref.current) return;\n return createPointerProvider(\n cap,\n { type: \"page\", documentId, pageIndex },\n ref.current,\n convertEventToPoint || defaultConvertEventToPoint\n );\n }, [cap, documentId, pageIndex, convertEventToPoint, defaultConvertEventToPoint]);\n return /* @__PURE__ */ jsxs(\n \"div\",\n {\n ref,\n style: {\n position: \"relative\",\n width: displaySize.width,\n height: displaySize.height,\n ...style\n },\n ...props,\n children: [\n children,\n isPageExclusive && /* @__PURE__ */ jsx(\"div\", { style: { position: \"absolute\", top: 0, left: 0, right: 0, bottom: 0, zIndex: 10 } })\n ]\n }\n );\n};\nexport {\n GlobalPointerProvider,\n PagePointerProvider,\n useCursor,\n useInteractionManager,\n useInteractionManagerCapability,\n useInteractionManagerPlugin,\n useIsPageExclusive,\n usePointerHandlers\n};\n//# sourceMappingURL=index.js.map\n","import { BasePlugin, createBehaviorEmitter, setRotation as setRotation$1 } from \"@embedpdf/core\";\nconst ROTATE_PLUGIN_ID = \"rotate\";\nconst manifest = {\n id: ROTATE_PLUGIN_ID,\n name: \"Rotate Plugin\",\n version: \"1.0.0\",\n provides: [\"rotate\"],\n requires: [],\n optional: [],\n defaultConfig: {}\n};\nfunction getRotationMatrix(rotation, w, h) {\n let a = 1, b = 0, c = 0, d = 1, e = 0, f = 0;\n switch (rotation) {\n case 1:\n a = 0;\n b = 1;\n c = -1;\n d = 0;\n e = h;\n break;\n case 2:\n a = -1;\n b = 0;\n c = 0;\n d = -1;\n e = w;\n f = h;\n break;\n case 3:\n a = 0;\n b = -1;\n c = 1;\n d = 0;\n f = w;\n break;\n }\n return [a, b, c, d, e, f];\n}\nfunction getRotationMatrixString(rotation, w, h) {\n const [a, b, c, d, e, f] = getRotationMatrix(rotation, w, h);\n return `matrix(${a},${b},${c},${d},${e},${f})`;\n}\nfunction getNextRotation(current) {\n return (current + 1) % 4;\n}\nfunction getPreviousRotation(current) {\n return (current + 3) % 4;\n}\nconst INIT_ROTATE_STATE = \"ROTATE/INIT_STATE\";\nconst CLEANUP_ROTATE_STATE = \"ROTATE/CLEANUP_STATE\";\nconst SET_ACTIVE_ROTATE_DOCUMENT = \"ROTATE/SET_ACTIVE_DOCUMENT\";\nconst SET_ROTATION = \"ROTATE/SET_ROTATION\";\nfunction initRotateState(documentId, state) {\n return { type: INIT_ROTATE_STATE, payload: { documentId, state } };\n}\nfunction cleanupRotateState(documentId) {\n return { type: CLEANUP_ROTATE_STATE, payload: documentId };\n}\nfunction setActiveRotateDocument(documentId) {\n return { type: SET_ACTIVE_ROTATE_DOCUMENT, payload: documentId };\n}\nfunction setRotation(documentId, rotation) {\n return { type: SET_ROTATION, payload: { documentId, rotation } };\n}\nconst _RotatePlugin = class _RotatePlugin extends BasePlugin {\n constructor(id, registry, cfg) {\n super(id, registry);\n this.rotate$ = createBehaviorEmitter();\n this.defaultRotation = cfg.defaultRotation ?? 0;\n }\n // ─────────────────────────────────────────────────────────\n // Document Lifecycle Hooks (from BasePlugin)\n // ─────────────────────────────────────────────────────────\n onDocumentLoadingStarted(documentId) {\n const docState = {\n rotation: this.defaultRotation\n };\n this.dispatch(initRotateState(documentId, docState));\n this.dispatchCoreAction(setRotation$1(this.defaultRotation, documentId));\n this.logger.debug(\n \"RotatePlugin\",\n \"DocumentOpened\",\n `Initialized rotation state for document: ${documentId}`\n );\n }\n onDocumentClosed(documentId) {\n this.dispatch(cleanupRotateState(documentId));\n this.logger.debug(\n \"RotatePlugin\",\n \"DocumentClosed\",\n `Cleaned up rotation state for document: ${documentId}`\n );\n }\n // ─────────────────────────────────────────────────────────\n // Capability\n // ─────────────────────────────────────────────────────────\n buildCapability() {\n return {\n // Active document operations\n setRotation: (rotation) => this.setRotationForDocument(rotation),\n getRotation: () => this.getRotationForDocument(),\n rotateForward: () => this.rotateForward(),\n rotateBackward: () => this.rotateBackward(),\n // Document-scoped operations\n forDocument: (documentId) => this.createRotateScope(documentId),\n // Events\n onRotateChange: this.rotate$.on\n };\n }\n // ─────────────────────────────────────────────────────────\n // Document Scoping\n // ─────────────────────────────────────────────────────────\n createRotateScope(documentId) {\n return {\n setRotation: (rotation) => this.setRotationForDocument(rotation, documentId),\n getRotation: () => this.getRotationForDocument(documentId),\n rotateForward: () => this.rotateForward(documentId),\n rotateBackward: () => this.rotateBackward(documentId),\n onRotateChange: (listener) => this.rotate$.on((event) => {\n if (event.documentId === documentId) listener(event.rotation);\n })\n };\n }\n // ─────────────────────────────────────────────────────────\n // State Helpers\n // ─────────────────────────────────────────────────────────\n getDocumentState(documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n return this.state.documents[id] ?? null;\n }\n getDocumentStateOrThrow(documentId) {\n const state = this.getDocumentState(documentId);\n if (!state) {\n throw new Error(`Rotation state not found for document: ${documentId ?? \"active\"}`);\n }\n return state;\n }\n // ─────────────────────────────────────────────────────────\n // Core Operations\n // ─────────────────────────────────────────────────────────\n setRotationForDocument(rotation, documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const coreDoc = this.coreState.core.documents[id];\n if (!(coreDoc == null ? void 0 : coreDoc.document)) {\n throw new Error(`Document ${id} not loaded`);\n }\n this.dispatch(setRotation(id, rotation));\n this.dispatchCoreAction(setRotation$1(rotation, id));\n this.rotate$.emit({\n documentId: id,\n rotation\n });\n }\n getRotationForDocument(documentId) {\n return this.getDocumentStateOrThrow(documentId).rotation;\n }\n rotateForward(documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const currentRotation = this.getRotationForDocument(id);\n const nextRotation = getNextRotation(currentRotation);\n this.setRotationForDocument(nextRotation, id);\n }\n rotateBackward(documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const currentRotation = this.getRotationForDocument(id);\n const prevRotation = getPreviousRotation(currentRotation);\n this.setRotationForDocument(prevRotation, id);\n }\n getMatrixAsString(options) {\n return getRotationMatrixString(options.rotation, options.width, options.height);\n }\n // ─────────────────────────────────────────────────────────\n // Store Update Handlers\n // ─────────────────────────────────────────────────────────\n onStoreUpdated(prevState, newState) {\n for (const documentId in newState.documents) {\n const prevDoc = prevState.documents[documentId];\n const newDoc = newState.documents[documentId];\n if ((prevDoc == null ? void 0 : prevDoc.rotation) !== newDoc.rotation) {\n this.logger.debug(\n \"RotatePlugin\",\n \"RotationChanged\",\n `Rotation changed for document ${documentId}: ${(prevDoc == null ? void 0 : prevDoc.rotation) ?? 0} -> ${newDoc.rotation}`\n );\n }\n }\n }\n // ─────────────────────────────────────────────────────────\n // Lifecycle\n // ─────────────────────────────────────────────────────────\n async initialize(_config) {\n this.logger.info(\"RotatePlugin\", \"Initialize\", \"Rotate plugin initialized\");\n }\n async destroy() {\n this.rotate$.clear();\n super.destroy();\n }\n};\n_RotatePlugin.id = \"rotate\";\nlet RotatePlugin = _RotatePlugin;\nconst initialDocumentState = {\n rotation: 0\n};\nconst initialState = {\n documents: {},\n activeDocumentId: null\n};\nconst rotateReducer = (state = initialState, action) => {\n switch (action.type) {\n case INIT_ROTATE_STATE: {\n const { documentId, state: docState } = action.payload;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: docState\n },\n // Set as active if no active document\n activeDocumentId: state.activeDocumentId ?? documentId\n };\n }\n case CLEANUP_ROTATE_STATE: {\n const documentId = action.payload;\n const { [documentId]: removed, ...remainingDocs } = state.documents;\n return {\n ...state,\n documents: remainingDocs,\n activeDocumentId: state.activeDocumentId === documentId ? null : state.activeDocumentId\n };\n }\n case SET_ACTIVE_ROTATE_DOCUMENT: {\n return {\n ...state,\n activeDocumentId: action.payload\n };\n }\n case SET_ROTATION: {\n const { documentId, rotation } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...docState,\n rotation\n }\n }\n };\n }\n default:\n return state;\n }\n};\nconst RotatePluginPackage = {\n manifest,\n create: (registry, config) => new RotatePlugin(ROTATE_PLUGIN_ID, registry, config),\n reducer: rotateReducer,\n initialState\n};\nexport {\n CLEANUP_ROTATE_STATE,\n INIT_ROTATE_STATE,\n ROTATE_PLUGIN_ID,\n RotatePlugin,\n RotatePluginPackage,\n SET_ACTIVE_ROTATE_DOCUMENT,\n SET_ROTATION,\n cleanupRotateState,\n getNextRotation,\n getPreviousRotation,\n getRotationMatrix,\n getRotationMatrixString,\n initRotateState,\n initialDocumentState,\n initialState,\n manifest,\n rotateReducer,\n setActiveRotateDocument,\n setRotation\n};\n//# sourceMappingURL=index.js.map\n","import { useCapability, usePlugin, useDocumentState } from \"@embedpdf/core/react\";\nimport { initialDocumentState, RotatePlugin } from \"@embedpdf/plugin-rotate\";\nexport * from \"@embedpdf/plugin-rotate\";\nimport { useState, useEffect } from \"react\";\nimport { jsx } from \"react/jsx-runtime\";\nconst useRotatePlugin = () => usePlugin(RotatePlugin.id);\nconst useRotateCapability = () => useCapability(RotatePlugin.id);\nconst useRotate = (documentId) => {\n const { provides } = useRotateCapability();\n const [rotation, setRotation] = useState(initialDocumentState.rotation);\n useEffect(() => {\n if (!provides) return;\n const scope = provides.forDocument(documentId);\n setRotation(scope.getRotation());\n return scope.onRotateChange((newRotation) => {\n setRotation(newRotation);\n });\n }, [provides, documentId]);\n return {\n rotation,\n provides: (provides == null ? void 0 : provides.forDocument(documentId)) ?? null\n };\n};\nfunction Rotate({\n children,\n documentId,\n pageIndex,\n rotation: rotationOverride,\n scale: scaleOverride,\n style,\n ...props\n}) {\n var _a, _b, _c, _d;\n const { plugin: rotatePlugin } = useRotatePlugin();\n const documentState = useDocumentState(documentId);\n const page = (_b = (_a = documentState == null ? void 0 : documentState.document) == null ? void 0 : _a.pages) == null ? void 0 : _b[pageIndex];\n const width = ((_c = page == null ? void 0 : page.size) == null ? void 0 : _c.width) ?? 0;\n const height = ((_d = page == null ? void 0 : page.size) == null ? void 0 : _d.height) ?? 0;\n const pageRotation = (page == null ? void 0 : page.rotation) ?? 0;\n const docRotation = (documentState == null ? void 0 : documentState.rotation) ?? 0;\n const rotation = rotationOverride !== void 0 ? rotationOverride : (pageRotation + docRotation) % 4;\n const scale = scaleOverride ?? (documentState == null ? void 0 : documentState.scale) ?? 1;\n const matrix = (rotatePlugin == null ? void 0 : rotatePlugin.getMatrixAsString({\n width: width * scale,\n height: height * scale,\n rotation\n })) ?? \"matrix(1, 0, 0, 1, 0, 0)\";\n if (!page) return null;\n return /* @__PURE__ */ jsx(\n \"div\",\n {\n ...props,\n style: {\n position: \"absolute\",\n transformOrigin: \"0 0\",\n transform: matrix,\n ...style\n },\n children\n }\n );\n}\nexport {\n Rotate,\n useRotate,\n useRotateCapability,\n useRotatePlugin\n};\n//# sourceMappingURL=index.js.map\n","import { BasePlugin, createBehaviorEmitter } from \"@embedpdf/core\";\nimport { InteractionManagerPlugin } from \"@embedpdf/plugin-interaction-manager\";\nimport { ViewportPlugin } from \"@embedpdf/plugin-viewport\";\nconst INIT_PAN_STATE = \"PAN/INIT_STATE\";\nconst CLEANUP_PAN_STATE = \"PAN/CLEANUP_STATE\";\nconst SET_ACTIVE_PAN_DOCUMENT = \"PAN/SET_ACTIVE_DOCUMENT\";\nconst SET_PAN_MODE = \"PAN/SET_PAN_MODE\";\nfunction initPanState(documentId, state) {\n return { type: INIT_PAN_STATE, payload: { documentId, state } };\n}\nfunction cleanupPanState(documentId) {\n return { type: CLEANUP_PAN_STATE, payload: documentId };\n}\nfunction setActivePanDocument(documentId) {\n return { type: SET_ACTIVE_PAN_DOCUMENT, payload: documentId };\n}\nfunction setPanMode(documentId, isPanMode) {\n return { type: SET_PAN_MODE, payload: { documentId, isPanMode } };\n}\nconst _PanPlugin = class _PanPlugin extends BasePlugin {\n constructor(id, registry, config) {\n var _a, _b, _c;\n super(id, registry);\n this.panMode$ = createBehaviorEmitter();\n this.documentHandlers = /* @__PURE__ */ new Map();\n this.config = config;\n this.interactionManager = (_a = registry.getPlugin(InteractionManagerPlugin.id)) == null ? void 0 : _a.provides();\n this.viewport = (_b = registry.getPlugin(ViewportPlugin.id)) == null ? void 0 : _b.provides();\n if (this.interactionManager) {\n this.interactionManager.registerMode({\n id: \"panMode\",\n scope: \"global\",\n exclusive: false,\n cursor: \"grab\",\n wantsRawTouch: false\n });\n (_c = this.interactionManager) == null ? void 0 : _c.onModeChange((state) => {\n const isPanMode = state.activeMode === \"panMode\";\n const docState = this.getDocumentState(state.documentId);\n if (docState && docState.isPanMode !== isPanMode) {\n this.dispatch(setPanMode(state.documentId, isPanMode));\n }\n });\n }\n }\n // ─────────────────────────────────────────────────────────\n // Document Lifecycle Hooks (from BasePlugin)\n // ─────────────────────────────────────────────────────────\n onDocumentLoadingStarted(documentId) {\n const docState = {\n isPanMode: false\n };\n this.dispatch(initPanState(documentId, docState));\n this.registerPanHandlersForDocument(documentId);\n if (this.config.defaultMode === \"always\") {\n this.makePanDefault(true);\n }\n this.logger.debug(\n \"PanPlugin\",\n \"DocumentOpened\",\n `Initialized pan state for document: ${documentId}`\n );\n }\n onDocumentClosed(documentId) {\n const cleanup = this.documentHandlers.get(documentId);\n if (cleanup) {\n cleanup();\n this.documentHandlers.delete(documentId);\n }\n this.dispatch(cleanupPanState(documentId));\n this.logger.debug(\n \"PanPlugin\",\n \"DocumentClosed\",\n `Cleaned up pan state for document: ${documentId}`\n );\n }\n // ─────────────────────────────────────────────────────────\n // Capability\n // ─────────────────────────────────────────────────────────\n buildCapability() {\n return {\n // Active document operations\n enablePan: () => this.enablePan(),\n disablePan: () => this.disablePan(),\n togglePan: () => this.togglePan(),\n makePanDefault: (autoActivate) => this.makePanDefault(autoActivate),\n isPanMode: () => this.isPanMode(),\n // Document-scoped operations\n forDocument: (documentId) => this.createPanScope(documentId),\n // Events\n onPanModeChange: this.panMode$.on\n };\n }\n // ─────────────────────────────────────────────────────────\n // Document Scoping\n // ─────────────────────────────────────────────────────────\n createPanScope(documentId) {\n return {\n enablePan: () => this.enablePan(documentId),\n disablePan: () => this.disablePan(documentId),\n togglePan: () => this.togglePan(documentId),\n isPanMode: () => this.isPanMode(documentId),\n onPanModeChange: (listener) => this.panMode$.on((event) => {\n if (event.documentId === documentId) listener(event.isPanMode);\n })\n };\n }\n // ─────────────────────────────────────────────────────────\n // State Helpers\n // ─────────────────────────────────────────────────────────\n getDocumentState(documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n return this.state.documents[id] ?? null;\n }\n getDocumentStateOrThrow(documentId) {\n const state = this.getDocumentState(documentId);\n if (!state) {\n throw new Error(`Pan state not found for document: ${documentId ?? \"active\"}`);\n }\n return state;\n }\n // ─────────────────────────────────────────────────────────\n // Core Operations\n // ─────────────────────────────────────────────────────────\n enablePan(documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n this.interactionManager.forDocument(id).activate(\"panMode\");\n }\n disablePan(documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n this.interactionManager.forDocument(id).activateDefaultMode();\n }\n togglePan(documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const scope = this.interactionManager.forDocument(id);\n if (scope.getActiveMode() === \"panMode\") {\n scope.activateDefaultMode();\n } else {\n scope.activate(\"panMode\");\n }\n }\n makePanDefault(autoActivate = true) {\n if (!this.interactionManager) return;\n this.interactionManager.setDefaultMode(\"panMode\");\n if (autoActivate) {\n this.interactionManager.activateDefaultMode();\n }\n }\n isPanMode(documentId) {\n return this.getDocumentStateOrThrow(documentId).isPanMode;\n }\n // ─────────────────────────────────────────────────────────\n // Pan Handlers Registration\n // ─────────────────────────────────────────────────────────\n registerPanHandlersForDocument(documentId) {\n if (!this.interactionManager || !this.viewport) return;\n let dragState = null;\n const interactionScope = this.interactionManager.forDocument(documentId);\n const viewportScope = this.viewport.forDocument(documentId);\n const handlers = {\n onMouseDown: (_, pe) => {\n const metrics = viewportScope.getMetrics();\n dragState = {\n startX: pe.clientX,\n startY: pe.clientY,\n startLeft: metrics.scrollLeft,\n startTop: metrics.scrollTop\n };\n interactionScope.setCursor(\"panMode\", \"grabbing\", 10);\n },\n onMouseMove: (_, pe) => {\n if (!dragState) return;\n const dx = pe.clientX - dragState.startX;\n const dy = pe.clientY - dragState.startY;\n viewportScope.scrollTo({\n x: dragState.startLeft - dx,\n y: dragState.startTop - dy\n });\n },\n onMouseUp: () => {\n if (!dragState) return;\n dragState = null;\n interactionScope.removeCursor(\"panMode\");\n },\n onMouseLeave: () => {\n if (!dragState) return;\n dragState = null;\n interactionScope.removeCursor(\"panMode\");\n },\n onMouseCancel: () => {\n if (!dragState) return;\n dragState = null;\n interactionScope.removeCursor(\"panMode\");\n }\n };\n const unregister = this.interactionManager.registerHandlers({\n documentId,\n modeId: \"panMode\",\n handlers\n });\n this.documentHandlers.set(documentId, unregister);\n }\n // ─────────────────────────────────────────────────────────\n // Store Update Handlers\n // ─────────────────────────────────────────────────────────\n onStoreUpdated(prevState, newState) {\n for (const documentId in newState.documents) {\n const prevDoc = prevState.documents[documentId];\n const newDoc = newState.documents[documentId];\n if ((prevDoc == null ? void 0 : prevDoc.isPanMode) !== newDoc.isPanMode) {\n this.panMode$.emit({\n documentId,\n isPanMode: newDoc.isPanMode\n });\n this.logger.debug(\n \"PanPlugin\",\n \"PanModeChanged\",\n `Pan mode changed for document ${documentId}: ${(prevDoc == null ? void 0 : prevDoc.isPanMode) ?? false} -> ${newDoc.isPanMode}`\n );\n }\n }\n }\n // ─────────────────────────────────────────────────────────\n // Lifecycle\n // ─────────────────────────────────────────────────────────\n async initialize(_) {\n this.logger.info(\"PanPlugin\", \"Initialize\", \"Pan plugin initialized\");\n }\n async destroy() {\n this.documentHandlers.forEach((cleanup) => cleanup());\n this.documentHandlers.clear();\n this.panMode$.clear();\n await super.destroy();\n }\n};\n_PanPlugin.id = \"pan\";\nlet PanPlugin = _PanPlugin;\nconst PAN_PLUGIN_ID = \"pan\";\nconst manifest = {\n id: PAN_PLUGIN_ID,\n name: \"Pan Plugin\",\n version: \"1.0.0\",\n provides: [\"pan\"],\n requires: [\"interaction-manager\", \"viewport\"],\n optional: [],\n defaultConfig: {\n defaultMode: \"mobile\"\n }\n};\nconst initialDocumentState = {\n isPanMode: false\n};\nconst initialState = {\n documents: {},\n activeDocumentId: null\n};\nconst panReducer = (state = initialState, action) => {\n switch (action.type) {\n case INIT_PAN_STATE: {\n const { documentId, state: docState } = action.payload;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: docState\n },\n // Set as active if no active document\n activeDocumentId: state.activeDocumentId ?? documentId\n };\n }\n case CLEANUP_PAN_STATE: {\n const documentId = action.payload;\n const { [documentId]: removed, ...remainingDocs } = state.documents;\n return {\n ...state,\n documents: remainingDocs,\n activeDocumentId: state.activeDocumentId === documentId ? null : state.activeDocumentId\n };\n }\n case SET_ACTIVE_PAN_DOCUMENT: {\n return {\n ...state,\n activeDocumentId: action.payload\n };\n }\n case SET_PAN_MODE: {\n const { documentId, isPanMode } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...docState,\n isPanMode\n }\n }\n };\n }\n default:\n return state;\n }\n};\nconst PanPluginPackage = {\n manifest,\n create: (registry, config) => new PanPlugin(PAN_PLUGIN_ID, registry, config),\n reducer: panReducer,\n initialState\n};\nexport {\n CLEANUP_PAN_STATE,\n INIT_PAN_STATE,\n PAN_PLUGIN_ID,\n PanPlugin,\n PanPluginPackage,\n SET_ACTIVE_PAN_DOCUMENT,\n SET_PAN_MODE,\n cleanupPanState,\n initPanState,\n initialDocumentState,\n initialState,\n manifest,\n panReducer,\n setActivePanDocument,\n setPanMode\n};\n//# sourceMappingURL=index.js.map\n","import { createPluginPackage } from \"@embedpdf/core\";\nimport { PanPlugin, initialDocumentState, PanPluginPackage as PanPluginPackage$1 } from \"@embedpdf/plugin-pan\";\nexport * from \"@embedpdf/plugin-pan\";\nimport { useState, useEffect } from \"react\";\nimport { useCapability, usePlugin } from \"@embedpdf/core/react\";\nconst usePanPlugin = () => usePlugin(PanPlugin.id);\nconst usePanCapability = () => useCapability(PanPlugin.id);\nconst usePan = (documentId) => {\n const { provides } = usePanCapability();\n const [isPanning, setIsPanning] = useState(initialDocumentState.isPanMode);\n useEffect(() => {\n if (!provides) return;\n const scope = provides.forDocument(documentId);\n setIsPanning(scope.isPanMode());\n return scope.onPanModeChange((isPan) => {\n setIsPanning(isPan);\n });\n }, [provides, documentId]);\n return {\n provides: (provides == null ? void 0 : provides.forDocument(documentId)) ?? null,\n isPanning\n };\n};\nconst PanMode = () => {\n const { provides: pan } = usePanCapability();\n const { plugin: panPlugin } = usePanPlugin();\n useEffect(() => {\n var _a;\n if (!pan || !panPlugin) return;\n const mode = ((_a = panPlugin.config) == null ? void 0 : _a.defaultMode) ?? \"never\";\n const SUPPORT_TOUCH = typeof window !== \"undefined\" && (\"ontouchstart\" in window || navigator.maxTouchPoints > 0);\n if (mode === \"mobile\" && SUPPORT_TOUCH) {\n pan.makePanDefault();\n }\n }, [pan, panPlugin]);\n return null;\n};\nconst PanPluginPackage = createPluginPackage(PanPluginPackage$1).addUtility(PanMode).build();\nexport {\n PanMode,\n PanPluginPackage,\n usePan,\n usePanCapability,\n usePanPlugin\n};\n//# sourceMappingURL=index.js.map\n","import { BasePlugin, createScopedEmitter, REFRESH_PAGES } from \"@embedpdf/core\";\nimport { ignore } from \"@embedpdf/models\";\nconst THUMBNAIL_PLUGIN_ID = \"thumbnail\";\nconst manifest = {\n id: THUMBNAIL_PLUGIN_ID,\n name: \"Thumbnail Plugin\",\n version: \"1.0.0\",\n provides: [\"thumbnail\"],\n requires: [\"render\"],\n optional: [\"scroll\"],\n defaultConfig: {\n width: 150,\n gap: 10,\n buffer: 3,\n labelHeight: 16,\n autoScroll: true,\n scrollBehavior: \"smooth\",\n imagePadding: 0,\n paddingY: 0\n }\n};\nconst INIT_THUMBNAIL_STATE = \"THUMBNAIL/INIT_STATE\";\nconst CLEANUP_THUMBNAIL_STATE = \"THUMBNAIL/CLEANUP_STATE\";\nconst SET_ACTIVE_DOCUMENT = \"THUMBNAIL/SET_ACTIVE_DOCUMENT\";\nconst SET_WINDOW_STATE = \"THUMBNAIL/SET_WINDOW_STATE\";\nconst UPDATE_VIEWPORT_METRICS = \"THUMBNAIL/UPDATE_VIEWPORT_METRICS\";\nfunction initThumbnailState(documentId, state) {\n return { type: INIT_THUMBNAIL_STATE, payload: { documentId, state } };\n}\nfunction cleanupThumbnailState(documentId) {\n return { type: CLEANUP_THUMBNAIL_STATE, payload: documentId };\n}\nfunction setActiveDocument(documentId) {\n return { type: SET_ACTIVE_DOCUMENT, payload: documentId };\n}\nfunction setWindowState(documentId, window) {\n return { type: SET_WINDOW_STATE, payload: { documentId, window } };\n}\nfunction updateViewportMetrics(documentId, scrollY, viewportH) {\n return { type: UPDATE_VIEWPORT_METRICS, payload: { documentId, scrollY, viewportH } };\n}\nconst initialDocumentState = {\n thumbs: [],\n window: null,\n viewportH: 0,\n scrollY: 0\n};\nconst initialState = {\n documents: {},\n activeDocumentId: null\n};\nconst thumbnailReducer = (state = initialState, action) => {\n switch (action.type) {\n case INIT_THUMBNAIL_STATE: {\n const { documentId, state: docState } = action.payload;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: docState\n },\n // Set as active if no active document\n activeDocumentId: state.activeDocumentId ?? documentId\n };\n }\n case CLEANUP_THUMBNAIL_STATE: {\n const documentId = action.payload;\n const { [documentId]: removed, ...remainingDocs } = state.documents;\n return {\n ...state,\n documents: remainingDocs,\n activeDocumentId: state.activeDocumentId === documentId ? null : state.activeDocumentId\n };\n }\n case SET_ACTIVE_DOCUMENT: {\n return {\n ...state,\n activeDocumentId: action.payload\n };\n }\n case SET_WINDOW_STATE: {\n const { documentId, window } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...docState,\n window\n }\n }\n };\n }\n case UPDATE_VIEWPORT_METRICS: {\n const { documentId, scrollY, viewportH } = action.payload;\n const docState = state.documents[documentId];\n if (!docState) return state;\n return {\n ...state,\n documents: {\n ...state.documents,\n [documentId]: {\n ...docState,\n scrollY,\n viewportH\n }\n }\n };\n }\n default:\n return state;\n }\n};\nconst _ThumbnailPlugin = class _ThumbnailPlugin extends BasePlugin {\n constructor(id, registry, cfg) {\n var _a;\n super(id, registry);\n this.cfg = cfg;\n this.scrollCapability = null;\n this.taskCaches = /* @__PURE__ */ new Map();\n this.canAutoScroll = /* @__PURE__ */ new Map();\n this.window$ = createScopedEmitter(\n (documentId, window) => ({ documentId, window })\n );\n this.scrollTo$ = createScopedEmitter(\n (documentId, options) => ({ documentId, options })\n );\n this.refreshPages$ = createScopedEmitter(\n (documentId, pages) => ({ documentId, pages }),\n { cache: false }\n );\n this.renderCapability = this.registry.getPlugin(\"render\").provides();\n this.scrollCapability = ((_a = this.registry.getPlugin(\"scroll\")) == null ? void 0 : _a.provides()) ?? null;\n this.coreStore.onAction(REFRESH_PAGES, (action) => {\n const documentId = action.payload.documentId ?? this.getActiveDocumentId();\n const pages = action.payload.pageIndexes;\n this.refreshPages$.emit(documentId, pages);\n const taskCache = this.taskCaches.get(documentId);\n if (taskCache) {\n for (const pageIndex of pages) {\n taskCache.delete(pageIndex);\n }\n }\n });\n if (this.scrollCapability && this.cfg.autoScroll !== false) {\n this.scrollCapability.onPageChangeState(({ documentId, state }) => {\n this.canAutoScroll.set(documentId, !state.isChanging);\n if (!state.isChanging) {\n this.scrollToThumb(state.targetPage - 1, documentId);\n }\n });\n this.scrollCapability.onPageChange(({ documentId, pageNumber }) => {\n if (this.canAutoScroll.get(documentId) !== false) {\n this.scrollToThumb(pageNumber - 1, documentId);\n }\n });\n }\n }\n // ─────────────────────────────────────────────────────────\n // Document Lifecycle Hooks (from BasePlugin)\n // ─────────────────────────────────────────────────────────\n onDocumentLoadingStarted(documentId) {\n this.dispatch(\n initThumbnailState(documentId, {\n ...initialDocumentState\n })\n );\n this.taskCaches.set(documentId, /* @__PURE__ */ new Map());\n this.canAutoScroll.set(documentId, true);\n this.logger.debug(\n \"ThumbnailPlugin\",\n \"DocumentOpened\",\n `Initialized thumbnail state for document: ${documentId}`\n );\n }\n onDocumentLoaded(documentId) {\n this.calculateWindowState(documentId);\n }\n onDocumentClosed(documentId) {\n this.dispatch(cleanupThumbnailState(documentId));\n const taskCache = this.taskCaches.get(documentId);\n if (taskCache) {\n taskCache.forEach((task) => {\n task.abort({\n code: \"cancelled\",\n message: \"Document closed\"\n });\n });\n taskCache.clear();\n this.taskCaches.delete(documentId);\n }\n this.canAutoScroll.delete(documentId);\n this.window$.clearScope(documentId);\n this.scrollTo$.clearScope(documentId);\n this.refreshPages$.clearScope(documentId);\n this.logger.debug(\n \"ThumbnailPlugin\",\n \"DocumentClosed\",\n `Cleaned up thumbnail state for document: ${documentId}`\n );\n }\n onRotationChanged(documentId) {\n this.calculateWindowState(documentId);\n }\n // ─────────────────────────────────────────────────────────\n // Capability\n // ─────────────────────────────────────────────────────────\n buildCapability() {\n return {\n // Active document operations\n scrollToThumb: (pageIdx) => this.scrollToThumb(pageIdx),\n renderThumb: (idx, dpr) => this.renderThumb(idx, dpr),\n updateWindow: (scrollY, viewportH) => this.updateWindow(scrollY, viewportH),\n getWindow: () => this.getWindow(),\n // Document-scoped operations\n forDocument: (documentId) => this.createThumbnailScope(documentId),\n // Events\n onWindow: this.window$.onGlobal,\n onScrollTo: this.scrollTo$.onGlobal,\n onRefreshPages: this.refreshPages$.onGlobal\n };\n }\n // ─────────────────────────────────────────────────────────\n // Document Scoping\n // ─────────────────────────────────────────────────────────\n createThumbnailScope(documentId) {\n return {\n scrollToThumb: (pageIdx) => this.scrollToThumb(pageIdx, documentId),\n renderThumb: (idx, dpr) => this.renderThumb(idx, dpr, documentId),\n updateWindow: (scrollY, viewportH) => this.updateWindow(scrollY, viewportH, documentId),\n getWindow: () => this.getWindow(documentId),\n onWindow: this.window$.forScope(documentId),\n onScrollTo: this.scrollTo$.forScope(documentId),\n onRefreshPages: this.refreshPages$.forScope(documentId)\n };\n }\n // ─────────────────────────────────────────────────────────\n // State Helpers\n // ─────────────────────────────────────────────────────────\n getDocumentState(documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n return this.state.documents[id] ?? null;\n }\n // ─────────────────────────────────────────────────────────\n // Core Operations\n // ─────────────────────────────────────────────────────────\n calculateWindowState(documentId) {\n const coreDoc = this.coreState.core.documents[documentId];\n if (!(coreDoc == null ? void 0 : coreDoc.document)) return;\n const OUTER_W = this.cfg.width ?? 120;\n const L = this.cfg.labelHeight ?? 16;\n const GAP = this.cfg.gap ?? 8;\n const P = this.cfg.imagePadding ?? 0;\n const PADDING_Y = this.cfg.paddingY ?? 0;\n const INNER_W = Math.max(1, OUTER_W - 2 * P);\n let offset = PADDING_Y;\n const thumbs = coreDoc.document.pages.map((p) => {\n const isRotated90or270 = p.rotation % 2 === 1;\n const effectiveWidth = isRotated90or270 ? p.size.height : p.size.width;\n const effectiveHeight = isRotated90or270 ? p.size.width : p.size.height;\n const ratio = effectiveHeight / effectiveWidth;\n const imgH = Math.round(INNER_W * ratio);\n const wrapH = P + imgH + P + L;\n const meta = {\n pageIndex: p.index,\n width: INNER_W,\n // bitmap width (for <img> size)\n height: imgH,\n // bitmap height (for <img> size)\n wrapperHeight: wrapH,\n // full row height used by virtualizer\n top: offset,\n // top of the row\n labelHeight: L,\n padding: P\n };\n offset += wrapH + GAP;\n return meta;\n });\n const window = {\n start: -1,\n end: -1,\n items: [],\n totalHeight: offset - GAP + PADDING_Y\n // Add bottom padding to total height\n };\n const docState = this.getDocumentState(documentId);\n if (!docState) return;\n this.dispatch(\n initThumbnailState(documentId, {\n ...docState,\n thumbs,\n window\n })\n );\n if (docState.viewportH > 0) {\n this.updateWindow(docState.scrollY, docState.viewportH, documentId);\n } else {\n this.window$.emit(documentId, window);\n }\n }\n updateWindow(scrollY, viewportH, documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const docState = this.getDocumentState(id);\n if (!docState || !docState.window || docState.thumbs.length === 0) return;\n const BUF = this.cfg.buffer ?? 3;\n this.dispatch(updateViewportMetrics(id, scrollY, viewportH));\n let low = 0, high = docState.thumbs.length - 1, first = 0;\n while (low <= high) {\n const mid = low + high >> 1;\n const m = docState.thumbs[mid];\n if (m.top + m.wrapperHeight < scrollY) low = mid + 1;\n else {\n first = mid;\n high = mid - 1;\n }\n }\n let last = first;\n const limit = scrollY + viewportH;\n while (last + 1 < docState.thumbs.length && docState.thumbs[last].top < limit) last++;\n last = Math.min(docState.thumbs.length - 1, last + BUF);\n const start = Math.max(0, first - BUF);\n if (start === docState.window.start && last === docState.window.end) return;\n const newWindow = {\n start,\n end: last,\n items: docState.thumbs.slice(start, last + 1),\n totalHeight: docState.window.totalHeight\n };\n this.dispatch(setWindowState(id, newWindow));\n this.window$.emit(id, newWindow);\n }\n getWindow(documentId) {\n const docState = this.getDocumentState(documentId);\n return (docState == null ? void 0 : docState.window) ?? null;\n }\n scrollToThumb(pageIdx, documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const docState = this.getDocumentState(id);\n if (!docState || !docState.window) return;\n const item = docState.thumbs[pageIdx];\n if (!item) return;\n const behavior = this.cfg.scrollBehavior ?? \"smooth\";\n const PADDING_Y = this.cfg.paddingY ?? 0;\n if (docState.viewportH <= 0) {\n const top2 = Math.max(PADDING_Y, item.top - item.wrapperHeight);\n this.scrollTo$.emit(id, { top: top2, behavior });\n return;\n }\n const margin = 8;\n const top = item.top;\n const bottom = item.top + item.wrapperHeight;\n const needsUp = top < docState.scrollY + margin + PADDING_Y;\n const needsDown = bottom > docState.scrollY + docState.viewportH - margin;\n if (needsUp) {\n this.scrollTo$.emit(id, {\n top: Math.max(0, top - PADDING_Y),\n behavior\n });\n } else if (needsDown) {\n this.scrollTo$.emit(id, {\n top: Math.max(0, bottom - docState.viewportH + PADDING_Y),\n behavior\n });\n }\n }\n renderThumb(idx, dpr, documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n const taskCache = this.taskCaches.get(id);\n if (!taskCache) {\n throw new Error(`Task cache not found for document: ${id}`);\n }\n if (taskCache.has(idx)) return taskCache.get(idx);\n const coreDoc = this.coreState.core.documents[id];\n if (!(coreDoc == null ? void 0 : coreDoc.document)) {\n throw new Error(`Document not found: ${id}`);\n }\n const page = coreDoc.document.pages[idx];\n if (!page) {\n throw new Error(`Page ${idx} not found in document: ${id}`);\n }\n const OUTER_W = this.cfg.width ?? 120;\n const P = this.cfg.imagePadding ?? 0;\n const INNER_W = Math.max(1, OUTER_W - 2 * P);\n const scale = INNER_W / page.size.width;\n const task = this.renderCapability.forDocument(id).renderPageRect({\n pageIndex: idx,\n rect: { origin: { x: 0, y: 0 }, size: page.size },\n options: {\n scaleFactor: scale,\n dpr,\n rotation: page.rotation\n }\n });\n taskCache.set(idx, task);\n task.wait(ignore, () => taskCache.delete(idx));\n return task;\n }\n // ─────────────────────────────────────────────────────────\n // Lifecycle\n // ─────────────────────────────────────────────────────────\n async initialize() {\n this.logger.info(\"ThumbnailPlugin\", \"Initialize\", \"Thumbnail plugin initialized\");\n }\n async destroy() {\n this.window$.clear();\n this.refreshPages$.clear();\n this.scrollTo$.clear();\n this.taskCaches.forEach((cache) => {\n cache.forEach((task) => {\n task.abort({\n code: \"cancelled\",\n message: \"Plugin destroyed\"\n });\n });\n cache.clear();\n });\n this.taskCaches.clear();\n this.canAutoScroll.clear();\n super.destroy();\n }\n};\n_ThumbnailPlugin.id = \"thumbnail\";\nlet ThumbnailPlugin = _ThumbnailPlugin;\nconst ThumbnailPluginPackage = {\n manifest,\n create: (registry, config) => new ThumbnailPlugin(THUMBNAIL_PLUGIN_ID, registry, config),\n reducer: thumbnailReducer,\n initialState\n};\nexport {\n CLEANUP_THUMBNAIL_STATE,\n INIT_THUMBNAIL_STATE,\n SET_ACTIVE_DOCUMENT,\n SET_WINDOW_STATE,\n THUMBNAIL_PLUGIN_ID,\n ThumbnailPlugin,\n ThumbnailPluginPackage,\n UPDATE_VIEWPORT_METRICS,\n cleanupThumbnailState,\n initThumbnailState,\n initialDocumentState,\n initialState,\n manifest,\n setActiveDocument,\n setWindowState,\n thumbnailReducer,\n updateViewportMetrics\n};\n//# sourceMappingURL=index.js.map\n","import { useCapability, usePlugin } from \"@embedpdf/core/react\";\nimport { ThumbnailPlugin } from \"@embedpdf/plugin-thumbnail\";\nexport * from \"@embedpdf/plugin-thumbnail\";\nimport { jsx } from \"react/jsx-runtime\";\nimport { useRef, useState, useEffect } from \"react\";\nimport { ignore, PdfErrorCode } from \"@embedpdf/models\";\nconst useThumbnailPlugin = () => usePlugin(ThumbnailPlugin.id);\nconst useThumbnailCapability = () => useCapability(ThumbnailPlugin.id);\nfunction ThumbnailsPane({ documentId, style, children, ...props }) {\n const { plugin: thumbnailPlugin } = useThumbnailPlugin();\n const viewportRef = useRef(null);\n const [windowData, setWindowData] = useState({ window: null, docId: null });\n const window2 = windowData.docId === documentId ? windowData.window : null;\n useEffect(() => {\n if (!thumbnailPlugin) return;\n const scope = thumbnailPlugin.provides().forDocument(documentId);\n const initialWindow = scope.getWindow();\n if (initialWindow) {\n setWindowData({ window: initialWindow, docId: documentId });\n }\n const unsubscribe = scope.onWindow((newWindow) => {\n setWindowData({ window: newWindow, docId: documentId });\n });\n return () => {\n unsubscribe();\n setWindowData({ window: null, docId: null });\n };\n }, [thumbnailPlugin, documentId]);\n useEffect(() => {\n const vp = viewportRef.current;\n if (!vp || !thumbnailPlugin) return;\n const scope = thumbnailPlugin.provides().forDocument(documentId);\n const onScroll = () => scope.updateWindow(vp.scrollTop, vp.clientHeight);\n vp.addEventListener(\"scroll\", onScroll);\n return () => vp.removeEventListener(\"scroll\", onScroll);\n }, [thumbnailPlugin, documentId]);\n useEffect(() => {\n const vp = viewportRef.current;\n if (!vp || !thumbnailPlugin) return;\n const scope = thumbnailPlugin.provides().forDocument(documentId);\n const resizeObserver = new ResizeObserver(() => {\n scope.updateWindow(vp.scrollTop, vp.clientHeight);\n });\n resizeObserver.observe(vp);\n return () => resizeObserver.disconnect();\n }, [thumbnailPlugin, documentId]);\n useEffect(() => {\n const vp = viewportRef.current;\n if (!vp || !thumbnailPlugin) return;\n const scope = thumbnailPlugin.provides().forDocument(documentId);\n scope.updateWindow(vp.scrollTop, vp.clientHeight);\n }, [window2, thumbnailPlugin, documentId]);\n useEffect(() => {\n const vp = viewportRef.current;\n if (!vp || !thumbnailPlugin || !window2) return;\n const scope = thumbnailPlugin.provides().forDocument(documentId);\n return scope.onScrollTo(({ top, behavior }) => {\n vp.scrollTo({ top, behavior });\n });\n }, [thumbnailPlugin, documentId, !!window2]);\n const paddingY = (thumbnailPlugin == null ? void 0 : thumbnailPlugin.cfg.paddingY) ?? 0;\n return /* @__PURE__ */ jsx(\n \"div\",\n {\n ref: viewportRef,\n style: {\n overflowY: \"auto\",\n position: \"relative\",\n paddingTop: paddingY,\n paddingBottom: paddingY,\n height: \"100%\",\n ...style\n },\n ...props,\n children: /* @__PURE__ */ jsx(\"div\", { style: { height: (window2 == null ? void 0 : window2.totalHeight) ?? 0, position: \"relative\" }, children: window2 == null ? void 0 : window2.items.map((m) => children(m)) })\n }\n );\n}\nfunction ThumbImg({ documentId, meta, style, ...props }) {\n const { provides: thumbs } = useThumbnailCapability();\n const { plugin: thumbnailPlugin } = useThumbnailPlugin();\n const [url, setUrl] = useState();\n const urlRef = useRef(null);\n const [refreshTick, setRefreshTick] = useState(0);\n useEffect(() => {\n if (!thumbnailPlugin) return;\n const scope = thumbnailPlugin.provides().forDocument(documentId);\n return scope.onRefreshPages((pages) => {\n if (pages.includes(meta.pageIndex)) {\n setRefreshTick((tick) => tick + 1);\n }\n });\n }, [thumbnailPlugin, documentId, meta.pageIndex]);\n useEffect(() => {\n const scope = thumbs == null ? void 0 : thumbs.forDocument(documentId);\n const task = scope == null ? void 0 : scope.renderThumb(meta.pageIndex, window.devicePixelRatio);\n task == null ? void 0 : task.wait((blob) => {\n const objectUrl = URL.createObjectURL(blob);\n urlRef.current = objectUrl;\n setUrl(objectUrl);\n }, ignore);\n return () => {\n if (urlRef.current) {\n URL.revokeObjectURL(urlRef.current);\n urlRef.current = null;\n } else {\n task == null ? void 0 : task.abort({\n code: PdfErrorCode.Cancelled,\n message: \"canceled render task\"\n });\n }\n };\n }, [thumbs, documentId, meta.pageIndex, refreshTick]);\n const handleImageLoad = () => {\n if (urlRef.current) {\n URL.revokeObjectURL(urlRef.current);\n urlRef.current = null;\n }\n };\n return url ? /* @__PURE__ */ jsx(\"img\", { src: url, onLoad: handleImageLoad, style, ...props }) : null;\n}\nexport {\n ThumbImg,\n ThumbnailsPane,\n useThumbnailCapability,\n useThumbnailPlugin\n};\n//# sourceMappingURL=index.js.map\n","import { BasePlugin, createEmitter } from \"@embedpdf/core\";\nimport { PdfPermissionFlag, PdfTaskHelper, PdfErrorCode, Task } from \"@embedpdf/models\";\nconst PRINT_PLUGIN_ID = \"print\";\nconst manifest = {\n id: PRINT_PLUGIN_ID,\n name: \"Print Plugin\",\n version: \"1.0.0\",\n provides: [\"print\"],\n requires: [],\n optional: [],\n defaultConfig: {}\n};\nconst _PrintPlugin = class _PrintPlugin extends BasePlugin {\n constructor(id, registry, _config) {\n super(id, registry);\n this.printReady$ = createEmitter();\n }\n // ─────────────────────────────────────────────────────────\n // Capability\n // ─────────────────────────────────────────────────────────\n buildCapability() {\n return {\n // Active document operations\n print: (options) => this.print(options),\n // Document-scoped operations\n forDocument: (documentId) => this.createPrintScope(documentId)\n };\n }\n // ─────────────────────────────────────────────────────────\n // Document Scoping\n // ─────────────────────────────────────────────────────────\n createPrintScope(documentId) {\n return {\n print: (options) => this.print(options, documentId)\n };\n }\n // ─────────────────────────────────────────────────────────\n // Core Operations\n // ─────────────────────────────────────────────────────────\n print(options, documentId) {\n const id = documentId ?? this.getActiveDocumentId();\n if (!this.checkPermission(id, PdfPermissionFlag.Print)) {\n this.logger.debug(\n \"PrintPlugin\",\n \"Print\",\n `Cannot print: document ${id} lacks Print permission`\n );\n return PdfTaskHelper.reject({\n code: PdfErrorCode.Security,\n message: \"Document lacks Print permission\"\n });\n }\n const printOptions = options ?? {};\n const task = new Task();\n task.progress({ stage: \"preparing\", message: \"Preparing document...\" });\n const prepare = this.preparePrintDocument(printOptions, id);\n prepare.wait(\n (buffer) => {\n task.progress({ stage: \"document-ready\", message: \"Document prepared successfully\" });\n this.printReady$.emit({\n documentId: id,\n options: printOptions,\n buffer,\n task\n });\n },\n (error) => task.fail(error)\n );\n return task;\n }\n preparePrintDocument(options, documentId) {\n const coreDoc = this.coreState.core.documents[documentId];\n if (!(coreDoc == null ? void 0 : coreDoc.document)) {\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: `Document ${documentId} not found`\n });\n }\n return this.engine.preparePrintDocument(coreDoc.document, options);\n }\n // ─────────────────────────────────────────────────────────\n // Event Listeners\n // ─────────────────────────────────────────────────────────\n onPrintRequest(listener) {\n return this.printReady$.on(listener);\n }\n // ─────────────────────────────────────────────────────────\n // Lifecycle\n // ─────────────────────────────────────────────────────────\n async initialize(_) {\n this.logger.info(\"PrintPlugin\", \"Initialize\", \"Print plugin initialized\");\n }\n async destroy() {\n this.printReady$.clear();\n await super.destroy();\n }\n};\n_PrintPlugin.id = \"print\";\nlet PrintPlugin = _PrintPlugin;\nconst PrintPluginPackage = {\n manifest,\n create: (registry, config) => new PrintPlugin(PRINT_PLUGIN_ID, registry, config),\n reducer: () => {\n },\n initialState: {}\n};\nexport {\n PRINT_PLUGIN_ID,\n PrintPlugin,\n PrintPluginPackage,\n manifest\n};\n//# sourceMappingURL=index.js.map\n","import { createPluginPackage } from \"@embedpdf/core\";\nimport { PrintPlugin, PrintPluginPackage as PrintPluginPackage$1 } from \"@embedpdf/plugin-print\";\nexport * from \"@embedpdf/plugin-print\";\nimport { jsx } from \"react/jsx-runtime\";\nimport require$$0 from \"react-dom\";\nimport { useRef, useEffect } from \"react\";\nimport { useCapability, usePlugin } from \"@embedpdf/core/react\";\nvar client = {};\nvar hasRequiredClient;\nfunction requireClient() {\n if (hasRequiredClient) return client;\n hasRequiredClient = 1;\n var m = require$$0;\n if (process.env.NODE_ENV === \"production\") {\n client.createRoot = m.createRoot;\n client.hydrateRoot = m.hydrateRoot;\n } else {\n var i = m.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;\n client.createRoot = function(c, o) {\n i.usingClientEntryPoint = true;\n try {\n return m.createRoot(c, o);\n } finally {\n i.usingClientEntryPoint = false;\n }\n };\n client.hydrateRoot = function(c, h, o) {\n i.usingClientEntryPoint = true;\n try {\n return m.hydrateRoot(c, h, o);\n } finally {\n i.usingClientEntryPoint = false;\n }\n };\n }\n return client;\n}\nrequireClient();\nconst usePrintPlugin = () => usePlugin(PrintPlugin.id);\nconst usePrintCapability = () => useCapability(PrintPlugin.id);\nconst usePrint = (documentId) => {\n const { provides } = usePrintCapability();\n return {\n provides: (provides == null ? void 0 : provides.forDocument(documentId)) ?? null\n };\n};\nfunction PrintFrame() {\n const { provides: printCapability } = usePrintCapability();\n const { plugin: printPlugin } = usePrintPlugin();\n const iframeRef = useRef(null);\n const urlRef = useRef(null);\n useEffect(() => {\n if (!printCapability || !printPlugin) return;\n const unsubscribe = printPlugin.onPrintRequest(({ buffer, task }) => {\n const iframe = iframeRef.current;\n if (!iframe) return;\n if (urlRef.current) {\n URL.revokeObjectURL(urlRef.current);\n urlRef.current = null;\n }\n const url = URL.createObjectURL(new Blob([buffer], { type: \"application/pdf\" }));\n urlRef.current = url;\n iframe.onload = () => {\n var _a, _b;\n if (iframe.src === url) {\n task.progress({ stage: \"iframe-ready\", message: \"Ready to print\" });\n (_a = iframe.contentWindow) == null ? void 0 : _a.focus();\n (_b = iframe.contentWindow) == null ? void 0 : _b.print();\n task.progress({ stage: \"printing\", message: \"Print dialog opened\" });\n task.resolve(buffer);\n }\n };\n iframe.src = url;\n });\n return () => {\n unsubscribe();\n if (urlRef.current) {\n URL.revokeObjectURL(urlRef.current);\n }\n };\n }, [printCapability, printPlugin]);\n return /* @__PURE__ */ jsx(\n \"iframe\",\n {\n ref: iframeRef,\n style: { position: \"absolute\", display: \"none\" },\n title: \"Print Document\",\n src: \"about:blank\"\n }\n );\n}\nconst PrintPluginPackage = createPluginPackage(PrintPluginPackage$1).addUtility(PrintFrame).build();\nexport {\n PrintFrame,\n PrintPluginPackage,\n usePrint,\n usePrintCapability,\n usePrintPlugin\n};\n//# sourceMappingURL=index.js.map\n","export default import.meta.ROLLDOWN_FILE_URL_8HSUfh7cJHNFxCkInNzNXw","import { useEffect, useMemo, useState, useId } from 'react';\nimport type { CSSProperties, ReactNode } from 'react';\nimport { createPluginRegistration } from '@embedpdf/core';\nimport { EmbedPDF } from '@embedpdf/core/react';\nimport { usePdfiumEngine } from '@embedpdf/engines/react';\nimport { DocumentContent, DocumentManagerPluginPackage, useDocumentManagerCapability } from '@embedpdf/plugin-document-manager/react';\nimport { Viewport, ViewportPluginPackage } from '@embedpdf/plugin-viewport/react';\nimport { Scroller, ScrollPluginPackage, useScroll } from '@embedpdf/plugin-scroll/react';\nimport { RenderLayer, RenderPluginPackage } from '@embedpdf/plugin-render/react';\nimport { ZoomPluginPackage, ZoomMode, useZoom } from '@embedpdf/plugin-zoom/react';\nimport type { ZoomLevel } from '@embedpdf/plugin-zoom';\nimport { SearchPluginPackage, SearchLayer, useSearch } from '@embedpdf/plugin-search/react';\nimport { SelectionPluginPackage, SelectionLayer } from '@embedpdf/plugin-selection/react';\nimport { InteractionManagerPluginPackage, PagePointerProvider } from '@embedpdf/plugin-interaction-manager/react';\nimport { RotatePluginPackage, useRotate } from '@embedpdf/plugin-rotate/react';\nimport { PanPluginPackage, PanMode, usePan } from '@embedpdf/plugin-pan/react';\nimport { ThumbnailPluginPackage, ThumbnailsPane, ThumbImg } from '@embedpdf/plugin-thumbnail/react';\nimport type { ThumbMeta } from '@embedpdf/plugin-thumbnail';\nimport { PrintPluginPackage, usePrint } from '@embedpdf/plugin-print/react';\nimport pdfiumWasmUrl from '@embedpdf/pdfium/pdfium.wasm?url';\nimport { Button, Select, Typography } from '@/ui';\nimport { ChevronLeft, ChevronRight, Download, Hand, Maximize2, Minimize2, PanelLeft, Printer, RotateCw, X } from 'lucide-react';\nimport { FileTypeIcon } from '@/components/FileTypeIcon';\nimport { useThemeController } from '@/providers/theme-controller';\n\nconst { Text } = Typography;\nconst ZOOM_OPTIONS = [\n { value: ZoomMode.Automatic, label: '自动缩放' },\n { value: ZoomMode.FitPage, label: '适合页高' },\n { value: ZoomMode.FitWidth, label: '适合页宽' },\n { value: '1', label: '实际大小' },\n];\ninterface PDFPreviewPanelProps {\n readonly file: File;\n readonly onClose: () => void;\n readonly fullscreen?: boolean;\n readonly onToggleFullscreen?: () => void;\n readonly style?: CSSProperties;\n readonly actions?: ReactNode;\n}\n\nfunction PDFDocument({ documentId, url, fileName }: Readonly<{ documentId: string; url: string; fileName: string }>) {\n const { provides: scroll, state: pages } = useScroll(documentId);\n const { provides: zoom } = useZoom(documentId);\n const { provides: search, state: results } = useSearch(documentId);\n const { provides: rotate } = useRotate(documentId);\n const { provides: pan, isPanning } = usePan(documentId);\n const { provides: print } = usePrint(documentId);\n const zoomLabelId = useId();\n const [zoomLevel, setZoomLevel] = useState<ZoomLevel>(ZoomMode.FitWidth);\n const [query, setQuery] = useState('');\n const [thumbnails, setThumbnails] = useState(false);\n return <>\n <div role=\"toolbar\" aria-label=\"PDF 工具栏\" style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 6, padding: 8, borderBottom: '1px solid var(--color-border)' }}>\n <Button aria-label=\"缩略图\" theme=\"borderless\" icon={<PanelLeft size={16}/>} onClick={() => setThumbnails(!thumbnails)}/>\n <Button aria-label=\"上一页\" disabled={pages.currentPage <= 1} theme=\"borderless\" icon={<ChevronLeft size={16}/>} onClick={() => scroll?.scrollToPreviousPage()}/>\n <span aria-label=\"PDF 页码\">{pages.currentPage} / {pages.totalPages}</span>\n <Button aria-label=\"下一页\" disabled={pages.currentPage >= pages.totalPages} theme=\"borderless\" icon={<ChevronRight size={16}/>} onClick={() => scroll?.scrollToNextPage()}/>\n <span id={zoomLabelId} className=\"sr-only\">PDF 缩放</span>\n <Select aria-labelledby={zoomLabelId} size=\"small\" value={String(zoomLevel)} style={{ width: 110 }} optionList={ZOOM_OPTIONS} onChange={value => {\n const level = value === '1' ? 1 : value as ZoomMode;\n setZoomLevel(level);\n zoom?.requestZoom(level);\n }}/>\n <Button aria-label=\"旋转\" theme=\"borderless\" icon={<RotateCw size={16}/>} onClick={() => rotate?.rotateForward()}/>\n <Button aria-label=\"拖动页面\" aria-pressed={isPanning} theme={isPanning ? 'solid' : 'borderless'} icon={<Hand size={16}/>} onClick={() => pan?.togglePan()}/>\n <form aria-label=\"PDF 搜索\" style={{ display: 'flex', gap: 4 }} onSubmit={event => {\n event.preventDefault();\n if (!query.trim()) { search?.stopSearch(); return; }\n search?.startSearch();\n search?.searchAllPages(query);\n }}>\n <input aria-label=\"搜索 PDF 文本\" placeholder=\"搜索 PDF 文本\" value={query} style={{ width: 120, color: 'inherit', background: 'transparent', border: '1px solid var(--color-border)', borderRadius: 'var(--semi-border-radius-small)' }} onChange={event => {\n setQuery(event.target.value);\n if (!event.target.value) search?.stopSearch();\n }}/>\n <Button htmlType=\"submit\" size=\"small\">搜索</Button>\n </form>\n {results.active && <>\n <span role=\"status\" aria-label=\"搜索结果\">{results.total ? results.activeResultIndex + 1 : 0} / {results.total}</span>\n <Button aria-label=\"上个结果\" size=\"small\" disabled={!results.total} onClick={() => search?.previousResult()}>↑</Button>\n <Button aria-label=\"下个结果\" size=\"small\" disabled={!results.total} onClick={() => search?.nextResult()}>↓</Button>\n </>}\n <Button aria-label=\"打印 PDF\" theme=\"borderless\" icon={<Printer size={16}/>} onClick={() => print?.print()}/>\n <a href={url} download={fileName} aria-label=\"下载 PDF\"><Download size={16}/></a>\n </div>\n <div style={{ display: 'flex', flex: 1, minHeight: 0 }}>\n {thumbnails && <ThumbnailsPane documentId={documentId} aria-label=\"PDF 缩略图\" style={{ width: 140, flexShrink: 0 }}>\n {(meta: ThumbMeta) => <button key={meta.pageIndex} aria-label={'跳到第 ' + (meta.pageIndex + 1) + ' 页'} style={{ position: 'absolute', top: meta.top, height: meta.wrapperHeight, width: '100%', border: 0, background: 'transparent', color: 'inherit' }} onClick={() => scroll?.scrollToPage({ pageNumber: meta.pageIndex + 1 })}>\n <ThumbImg documentId={documentId} meta={meta} style={{ display: 'block', margin: 'auto' }}/>\n {meta.pageIndex + 1}\n </button>}\n </ThumbnailsPane>}\n <Viewport documentId={documentId} style={{ flex: 1, minWidth: 0, height: '100%', background: 'var(--color-content-bg)' }}>\n <Scroller documentId={documentId} renderPage={({ width, height, pageIndex }) => <PagePointerProvider documentId={documentId} pageIndex={pageIndex} style={{ width, height, position: 'relative' }}>\n <RenderLayer documentId={documentId} pageIndex={pageIndex}/>\n <SearchLayer documentId={documentId} pageIndex={pageIndex}/>\n <SelectionLayer documentId={documentId} pageIndex={pageIndex}/>\n </PagePointerProvider>}/>\n </Viewport>\n </div>\n </>;\n}\n\nfunction PDFLoadError({ documentId, message }: Readonly<{ documentId: string; message: string | null }>) {\n const { provides } = useDocumentManagerCapability();\n const [password, setPassword] = useState('');\n return <form role=\"alert\" style={{ padding: 16 }} onSubmit={event => { event.preventDefault(); provides?.retryDocument(documentId, { password }); }}>\n <p>PDF 加载失败:{message}</p>\n <input aria-label=\"PDF 密码\" placeholder=\"加密 PDF 密码\" type=\"password\" value={password} onChange={event => setPassword(event.target.value)}/>\n <Button htmlType=\"submit\">重试</Button>\n </form>;\n}\n\nfunction PDFContent({ file }: Readonly<{ file: File }>) {\n // The engine and plugin modules remain behind the preview's existing lazy boundary.\n const wasmUrl = new URL(pdfiumWasmUrl, globalThis.location.href).href;\n const { engine, error } = usePdfiumEngine({ wasmUrl });\n const [source, setSource] = useState<{ file: File; url: string } | null>(null);\n useEffect(() => {\n const url = URL.createObjectURL(file);\n setSource({ file, url });\n return () => URL.revokeObjectURL(url);\n }, [file]);\n const url = source?.file === file ? source.url : null;\n const plugins = useMemo(() => [\n createPluginRegistration(DocumentManagerPluginPackage, { initialDocuments: url ? [{ url, name: file.name }] : [] }),\n createPluginRegistration(ViewportPluginPackage),\n createPluginRegistration(ScrollPluginPackage),\n createPluginRegistration(RenderPluginPackage),\n createPluginRegistration(InteractionManagerPluginPackage),\n createPluginRegistration(ZoomPluginPackage, { defaultZoomLevel: ZoomMode.FitWidth }),\n createPluginRegistration(SearchPluginPackage),\n createPluginRegistration(SelectionPluginPackage),\n createPluginRegistration(RotatePluginPackage),\n createPluginRegistration(PanPluginPackage),\n createPluginRegistration(ThumbnailPluginPackage),\n createPluginRegistration(PrintPluginPackage),\n ], [url, file.name]);\n if (error) return <div role=\"alert\">PDF 引擎加载失败:{error.message}</div>;\n if (!engine || !url) return <div role=\"status\">正在加载 PDF…</div>;\n return <EmbedPDF key={url} engine={engine} plugins={plugins}>\n {({ activeDocumentId }) => activeDocumentId ? <><PanMode/><DocumentContent documentId={activeDocumentId}>\n {({ isLoaded, isError, documentState }) => isLoaded\n ? <PDFDocument documentId={activeDocumentId} url={url} fileName={file.name}/>\n : isError ? <PDFLoadError documentId={activeDocumentId} message={documentState.error}/>\n : <div role=\"status\">正在加载 PDF…</div>}\n </DocumentContent></> : null}\n </EmbedPDF>;\n}\n\n/** Modular PDFium reader: no bundled editor, form, redaction or signature tools. */\nexport function PDFPreviewPanel({ file, onClose, fullscreen, onToggleFullscreen, style, actions }: PDFPreviewPanelProps) {\n const { isDark } = useThemeController();\n return <div style={{ width: '50%', minWidth: 320, display: 'flex', flexDirection: 'column', borderLeft: '1px solid var(--color-border)', overflow: 'hidden', flexShrink: 0, colorScheme: isDark ? 'dark' : 'light', ...style }}>\n <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '10px 16px', borderBottom: '1px solid var(--color-border)', flexShrink: 0 }}>\n <FileTypeIcon icon=\"vscode-icons:file-type-pdf2\" size={15}/>\n <Text ellipsis={{ showTooltip: true }} style={{ flex: 1, fontSize: 13, fontWeight: 500, minWidth: 0 }}>{file.name}</Text>\n {actions}\n {onToggleFullscreen && <Button aria-label={fullscreen ? '退出全屏' : '全屏'} theme=\"borderless\" size=\"small\" icon={fullscreen ? <Minimize2 size={14}/> : <Maximize2 size={14}/>} onClick={onToggleFullscreen}/>}\n <Button aria-label=\"关闭预览\" theme=\"borderless\" size=\"small\" icon={<X size={14}/>} onClick={onClose}/>\n </div>\n <PDFContent file={file}/>\n </div>;\n}\n"],"file":"PDFPreviewPanel-CMmnWBKW.js"}